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.

274533 lines
7.3MB

  1. /*
  2. ==============================================================================
  3. This file is part of the JUCE library - "Jules' Utility Class Extensions"
  4. Copyright 2004-9 by Raw Material Software Ltd.
  5. ------------------------------------------------------------------------------
  6. JUCE can be redistributed and/or modified under the terms of the GNU General
  7. Public License (Version 2), as published by the Free Software Foundation.
  8. A copy of the license is included in the JUCE distribution, or can be found
  9. online at www.gnu.org/licenses.
  10. JUCE is distributed in the hope that it will be useful, but WITHOUT ANY
  11. WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
  12. A PARTICULAR PURPOSE. See the GNU General Public License for more details.
  13. ------------------------------------------------------------------------------
  14. To release a closed-source product which uses JUCE, commercial licenses are
  15. available: visit www.rawmaterialsoftware.com/juce for more information.
  16. ==============================================================================
  17. */
  18. /*
  19. This monolithic file contains the entire Juce source tree!
  20. To build an app which uses Juce, all you need to do is to add this
  21. file to your project, and include juce.h in your own cpp files.
  22. */
  23. #ifdef __JUCE_JUCEHEADER__
  24. /* When you add the amalgamated cpp file to your project, you mustn't include it in
  25. a file where you've already included juce.h - just put it inside a file on its own,
  26. possibly with your config flags preceding it, but don't include anything else. */
  27. #error
  28. #endif
  29. /*** Start of inlined file: juce_TargetPlatform.h ***/
  30. #ifndef __JUCE_TARGETPLATFORM_JUCEHEADER__
  31. #define __JUCE_TARGETPLATFORM_JUCEHEADER__
  32. /* This file figures out which platform is being built, and defines some macros
  33. that the rest of the code can use for OS-specific compilation.
  34. Macros that will be set here are:
  35. - One of JUCE_WINDOWS, JUCE_MAC or JUCE_LINUX.
  36. - Either JUCE_32BIT or JUCE_64BIT, depending on the architecture.
  37. - Either JUCE_LITTLE_ENDIAN or JUCE_BIG_ENDIAN.
  38. - Either JUCE_INTEL or JUCE_PPC
  39. - Either JUCE_GCC or JUCE_MSVC
  40. */
  41. #if (defined (_WIN32) || defined (_WIN64))
  42. #define JUCE_WIN32 1
  43. #define JUCE_WINDOWS 1
  44. #elif defined (LINUX) || defined (__linux__)
  45. #define JUCE_LINUX 1
  46. #elif defined(__APPLE_CPP__) || defined(__APPLE_CC__)
  47. #include <CoreFoundation/CoreFoundation.h> // (needed to find out what platform we're using)
  48. #if TARGET_OS_IPHONE || TARGET_IPHONE_SIMULATOR
  49. #define JUCE_IPHONE 1
  50. #else
  51. #define JUCE_MAC 1
  52. #endif
  53. #else
  54. #error "Unknown platform!"
  55. #endif
  56. #if JUCE_WINDOWS
  57. #ifdef _MSC_VER
  58. #ifdef _WIN64
  59. #define JUCE_64BIT 1
  60. #else
  61. #define JUCE_32BIT 1
  62. #endif
  63. #endif
  64. #ifdef _DEBUG
  65. #define JUCE_DEBUG 1
  66. #endif
  67. #ifdef __MINGW32__
  68. #define JUCE_MINGW 1
  69. #endif
  70. /** If defined, this indicates that the processor is little-endian. */
  71. #define JUCE_LITTLE_ENDIAN 1
  72. #define JUCE_INTEL 1
  73. #endif
  74. #if JUCE_MAC
  75. #ifndef NDEBUG
  76. #define JUCE_DEBUG 1
  77. #endif
  78. #ifdef __LITTLE_ENDIAN__
  79. #define JUCE_LITTLE_ENDIAN 1
  80. #else
  81. #define JUCE_BIG_ENDIAN 1
  82. #endif
  83. #if defined (__ppc__) || defined (__ppc64__)
  84. #define JUCE_PPC 1
  85. #else
  86. #define JUCE_INTEL 1
  87. #endif
  88. #ifdef __LP64__
  89. #define JUCE_64BIT 1
  90. #else
  91. #define JUCE_32BIT 1
  92. #endif
  93. #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_4
  94. #error "Building for OSX 10.3 is no longer supported!"
  95. #endif
  96. #ifndef MAC_OS_X_VERSION_10_5
  97. #error "To build with 10.4 compatibility, use a 10.5 or 10.6 SDK and set the deployment target to 10.4"
  98. #endif
  99. #endif
  100. #if JUCE_IPHONE
  101. #ifndef NDEBUG
  102. #define JUCE_DEBUG 1
  103. #endif
  104. #ifdef __LITTLE_ENDIAN__
  105. #define JUCE_LITTLE_ENDIAN 1
  106. #else
  107. #define JUCE_BIG_ENDIAN 1
  108. #endif
  109. #endif
  110. #if JUCE_LINUX
  111. #ifdef _DEBUG
  112. #define JUCE_DEBUG 1
  113. #endif
  114. // Allow override for big-endian Linux platforms
  115. #ifndef JUCE_BIG_ENDIAN
  116. #define JUCE_LITTLE_ENDIAN 1
  117. #endif
  118. #if defined (__LP64__) || defined (_LP64)
  119. #define JUCE_64BIT 1
  120. #else
  121. #define JUCE_32BIT 1
  122. #endif
  123. #define JUCE_INTEL 1
  124. #endif
  125. // Compiler type macros.
  126. #ifdef __GNUC__
  127. #define JUCE_GCC 1
  128. #elif defined (_MSC_VER)
  129. #define JUCE_MSVC 1
  130. #if _MSC_VER >= 1400
  131. #define JUCE_USE_INTRINSICS 1
  132. #endif
  133. #else
  134. #error unknown compiler
  135. #endif
  136. #endif // __JUCE_TARGETPLATFORM_JUCEHEADER__
  137. /*** End of inlined file: juce_TargetPlatform.h ***/
  138. // FORCE_AMALGAMATOR_INCLUDE
  139. /*** Start of inlined file: juce_Config.h ***/
  140. #ifndef __JUCE_CONFIG_JUCEHEADER__
  141. #define __JUCE_CONFIG_JUCEHEADER__
  142. /*
  143. This file contains macros that enable/disable various JUCE features.
  144. */
  145. /** The name of the namespace that all Juce classes and functions will be
  146. put inside. If this is not defined, no namespace will be used.
  147. */
  148. #ifndef JUCE_NAMESPACE
  149. #define JUCE_NAMESPACE juce
  150. #endif
  151. /** JUCE_FORCE_DEBUG: Normally, JUCE_DEBUG is set to 1 or 0 based on compiler and
  152. project settings, but if you define this value, you can override this to force
  153. it to be true or false.
  154. */
  155. #ifndef JUCE_FORCE_DEBUG
  156. //#define JUCE_FORCE_DEBUG 0
  157. #endif
  158. /** JUCE_LOG_ASSERTIONS: If this flag is enabled, the the jassert and jassertfalse
  159. macros will always use Logger::writeToLog() to write a message when an assertion happens.
  160. Enabling it will also leave this turned on in release builds. When it's disabled,
  161. however, the jassert and jassertfalse macros will not be compiled in a
  162. release build.
  163. @see jassert, jassertfalse, Logger
  164. */
  165. #ifndef JUCE_LOG_ASSERTIONS
  166. #define JUCE_LOG_ASSERTIONS 0
  167. #endif
  168. /** JUCE_ASIO: Enables ASIO audio devices (MS Windows only).
  169. Turning this on means that you'll need to have the Steinberg ASIO SDK installed
  170. on your Windows build machine.
  171. See the comments in the ASIOAudioIODevice class's header file for more
  172. info about this.
  173. */
  174. #ifndef JUCE_ASIO
  175. #define JUCE_ASIO 0
  176. #endif
  177. /** JUCE_WASAPI: Enables WASAPI audio devices (Windows Vista and above).
  178. */
  179. #ifndef JUCE_WASAPI
  180. #define JUCE_WASAPI 0
  181. #endif
  182. /** JUCE_DIRECTSOUND: Enables DirectSound audio (MS Windows only).
  183. */
  184. #ifndef JUCE_DIRECTSOUND
  185. #define JUCE_DIRECTSOUND 1
  186. #endif
  187. /** JUCE_ALSA: Enables ALSA audio devices (Linux only). */
  188. #ifndef JUCE_ALSA
  189. #define JUCE_ALSA 1
  190. #endif
  191. /** JUCE_JACK: Enables JACK audio devices (Linux only). */
  192. #ifndef JUCE_JACK
  193. #define JUCE_JACK 0
  194. #endif
  195. /** JUCE_QUICKTIME: Enables the QuickTimeMovieComponent class (Mac and Windows).
  196. If you're building on Windows, you'll need to have the Apple QuickTime SDK
  197. installed, and its header files will need to be on your include path.
  198. */
  199. #if ! (defined (JUCE_QUICKTIME) || JUCE_LINUX || JUCE_IPHONE || (JUCE_WINDOWS && ! JUCE_MSVC))
  200. #define JUCE_QUICKTIME 0
  201. #endif
  202. #if (JUCE_IPHONE || JUCE_LINUX) && JUCE_QUICKTIME
  203. #undef JUCE_QUICKTIME
  204. #endif
  205. /** JUCE_OPENGL: Enables the OpenGLComponent class (available on all platforms).
  206. If you're not using OpenGL, you might want to turn this off to reduce your binary's size.
  207. */
  208. #ifndef JUCE_OPENGL
  209. #define JUCE_OPENGL 1
  210. #endif
  211. /** JUCE_USE_FLAC: Enables the FLAC audio codec classes (available on all platforms).
  212. If your app doesn't need to read FLAC files, you might want to disable this to
  213. reduce the size of your codebase and build time.
  214. */
  215. #ifndef JUCE_USE_FLAC
  216. #define JUCE_USE_FLAC 1
  217. #endif
  218. /** JUCE_USE_OGGVORBIS: Enables the Ogg-Vorbis audio codec classes (available on all platforms).
  219. If your app doesn't need to read Ogg-Vorbis files, you might want to disable this to
  220. reduce the size of your codebase and build time.
  221. */
  222. #ifndef JUCE_USE_OGGVORBIS
  223. #define JUCE_USE_OGGVORBIS 1
  224. #endif
  225. /** JUCE_USE_CDBURNER: Enables the audio CD reader code (Mac and Windows only).
  226. Unless you're using CD-burning, you should probably turn this flag off to
  227. reduce code size.
  228. */
  229. #if (! defined (JUCE_USE_CDBURNER)) && ! (JUCE_WINDOWS && ! JUCE_MSVC)
  230. #define JUCE_USE_CDBURNER 0
  231. #endif
  232. /** JUCE_USE_CDREADER: Enables the audio CD reader code (Mac and Windows only).
  233. Unless you're using CD-reading, you should probably turn this flag off to
  234. reduce code size.
  235. */
  236. #ifndef JUCE_USE_CDREADER
  237. #define JUCE_USE_CDREADER 0
  238. #endif
  239. /** JUCE_USE_CAMERA: Enables web-cam support using the CameraDevice class (Mac and Windows).
  240. */
  241. #if (JUCE_QUICKTIME || JUCE_WINDOWS) && ! defined (JUCE_USE_CAMERA)
  242. #define JUCE_USE_CAMERA 0
  243. #endif
  244. /** JUCE_ENABLE_REPAINT_DEBUGGING: If this option is turned on, each area of the screen that
  245. gets repainted will flash in a random colour, so that you can check exactly how much and how
  246. often your components are being drawn.
  247. */
  248. #ifndef JUCE_ENABLE_REPAINT_DEBUGGING
  249. #define JUCE_ENABLE_REPAINT_DEBUGGING 0
  250. #endif
  251. /** JUCE_USE_XINERAMA: Enables Xinerama multi-monitor support (Linux only).
  252. Unless you specifically want to disable this, it's best to leave this option turned on.
  253. */
  254. #ifndef JUCE_USE_XINERAMA
  255. #define JUCE_USE_XINERAMA 1
  256. #endif
  257. /** JUCE_USE_XSHM: Enables X shared memory for faster rendering on Linux. This is best left
  258. turned on unless you have a good reason to disable it.
  259. */
  260. #ifndef JUCE_USE_XSHM
  261. #define JUCE_USE_XSHM 1
  262. #endif
  263. /** JUCE_USE_XRENDER: Uses XRender to allow semi-transparent windowing on Linux.
  264. */
  265. #ifndef JUCE_USE_XRENDER
  266. #define JUCE_USE_XRENDER 0
  267. #endif
  268. /** JUCE_USE_XCURSOR: Uses XCursor to allow ARGB cursor on Linux. This is best left turned on
  269. unless you have a good reason to disable it.
  270. */
  271. #ifndef JUCE_USE_XCURSOR
  272. #define JUCE_USE_XCURSOR 1
  273. #endif
  274. /** JUCE_PLUGINHOST_VST: Enables the VST audio plugin hosting classes. This requires the
  275. Steinberg VST SDK to be installed on your machine, and should be left turned off unless
  276. you're building a plugin hosting app.
  277. @see VSTPluginFormat, AudioPluginFormat, AudioPluginFormatManager, JUCE_PLUGINHOST_AU
  278. */
  279. #ifndef JUCE_PLUGINHOST_VST
  280. #define JUCE_PLUGINHOST_VST 0
  281. #endif
  282. /** JUCE_PLUGINHOST_AU: Enables the AudioUnit plugin hosting classes. This is Mac-only,
  283. of course, and should only be enabled if you're building a plugin hosting app.
  284. @see AudioUnitPluginFormat, AudioPluginFormat, AudioPluginFormatManager, JUCE_PLUGINHOST_VST
  285. */
  286. #ifndef JUCE_PLUGINHOST_AU
  287. #define JUCE_PLUGINHOST_AU 0
  288. #endif
  289. /** JUCE_ONLY_BUILD_CORE_LIBRARY: Enabling this will avoid including any UI classes in the build.
  290. This should be enabled if you're writing a console application.
  291. */
  292. #ifndef JUCE_ONLY_BUILD_CORE_LIBRARY
  293. #define JUCE_ONLY_BUILD_CORE_LIBRARY 0
  294. #endif
  295. /** JUCE_WEB_BROWSER: This lets you disable the WebBrowserComponent class (Mac and Windows).
  296. If you're not using any embedded web-pages, turning this off may reduce your code size.
  297. */
  298. #ifndef JUCE_WEB_BROWSER
  299. #define JUCE_WEB_BROWSER 1
  300. #endif
  301. /** JUCE_SUPPORT_CARBON: Enabling this allows the Mac code to use old Carbon library functions.
  302. Carbon isn't required for a normal app, but may be needed by specialised classes like
  303. plugin-hosts, which support older APIs.
  304. */
  305. #ifndef JUCE_SUPPORT_CARBON
  306. #define JUCE_SUPPORT_CARBON 1
  307. #endif
  308. /* JUCE_INCLUDE_ZLIB_CODE: Can be used to disable Juce's embedded 3rd-party zlib code.
  309. You might need to tweak this if you're linking to an external zlib library in your app,
  310. but for normal apps, this option should be left alone.
  311. */
  312. #ifndef JUCE_INCLUDE_ZLIB_CODE
  313. #define JUCE_INCLUDE_ZLIB_CODE 1
  314. #endif
  315. #ifndef JUCE_INCLUDE_FLAC_CODE
  316. #define JUCE_INCLUDE_FLAC_CODE 1
  317. #endif
  318. #ifndef JUCE_INCLUDE_OGGVORBIS_CODE
  319. #define JUCE_INCLUDE_OGGVORBIS_CODE 1
  320. #endif
  321. #ifndef JUCE_INCLUDE_PNGLIB_CODE
  322. #define JUCE_INCLUDE_PNGLIB_CODE 1
  323. #endif
  324. #ifndef JUCE_INCLUDE_JPEGLIB_CODE
  325. #define JUCE_INCLUDE_JPEGLIB_CODE 1
  326. #endif
  327. /** JUCE_CHECK_MEMORY_LEAKS: Enables a memory-leak check when an app terminates.
  328. (Currently, this only affects Windows builds in debug mode).
  329. */
  330. #ifndef JUCE_CHECK_MEMORY_LEAKS
  331. #define JUCE_CHECK_MEMORY_LEAKS 1
  332. #endif
  333. /** JUCE_CATCH_UNHANDLED_EXCEPTIONS: Turn on juce's internal catching of exceptions
  334. that are thrown by the message dispatch loop. With it enabled, any unhandled exceptions
  335. are passed to the JUCEApplication::unhandledException() callback for logging.
  336. */
  337. #ifndef JUCE_CATCH_UNHANDLED_EXCEPTIONS
  338. #define JUCE_CATCH_UNHANDLED_EXCEPTIONS 1
  339. #endif
  340. // If only building the core classes, we can explicitly turn off some features to avoid including them:
  341. #if JUCE_ONLY_BUILD_CORE_LIBRARY
  342. #undef JUCE_QUICKTIME
  343. #define JUCE_QUICKTIME 0
  344. #undef JUCE_OPENGL
  345. #define JUCE_OPENGL 0
  346. #undef JUCE_USE_CDBURNER
  347. #define JUCE_USE_CDBURNER 0
  348. #undef JUCE_USE_CDREADER
  349. #define JUCE_USE_CDREADER 0
  350. #undef JUCE_WEB_BROWSER
  351. #define JUCE_WEB_BROWSER 0
  352. #undef JUCE_PLUGINHOST_AU
  353. #define JUCE_PLUGINHOST_AU 0
  354. #undef JUCE_PLUGINHOST_VST
  355. #define JUCE_PLUGINHOST_VST 0
  356. #endif
  357. #endif
  358. /*** End of inlined file: juce_Config.h ***/
  359. // FORCE_AMALGAMATOR_INCLUDE
  360. #ifndef JUCE_BUILD_CORE
  361. #define JUCE_BUILD_CORE 1
  362. #endif
  363. #ifndef JUCE_BUILD_MISC
  364. #define JUCE_BUILD_MISC 1
  365. #endif
  366. #ifndef JUCE_BUILD_GUI
  367. #define JUCE_BUILD_GUI 1
  368. #endif
  369. #ifndef JUCE_BUILD_NATIVE
  370. #define JUCE_BUILD_NATIVE 1
  371. #endif
  372. #if JUCE_ONLY_BUILD_CORE_LIBRARY
  373. #undef JUCE_BUILD_MISC
  374. #undef JUCE_BUILD_GUI
  375. #endif
  376. //==============================================================================
  377. #if JUCE_BUILD_NATIVE || JUCE_BUILD_CORE || (JUCE_BUILD_MISC && (JUCE_PLUGINHOST_VST || JUCE_PLUGINHOST_AU))
  378. #if JUCE_WINDOWS
  379. /*** Start of inlined file: juce_win32_NativeIncludes.h ***/
  380. #ifndef __JUCE_WIN32_NATIVEINCLUDES_JUCEHEADER__
  381. #define __JUCE_WIN32_NATIVEINCLUDES_JUCEHEADER__
  382. #ifndef STRICT
  383. #define STRICT 1
  384. #endif
  385. #undef WIN32_LEAN_AND_MEAN
  386. #define WIN32_LEAN_AND_MEAN 1
  387. #ifdef _MSC_VER
  388. #pragma warning (push)
  389. #pragma warning (disable : 4100 4201 4514 4312 4995)
  390. #endif
  391. #define _WIN32_WINNT 0x0500
  392. #define _UNICODE 1
  393. #define UNICODE 1
  394. #ifndef _WIN32_IE
  395. #define _WIN32_IE 0x0400
  396. #endif
  397. #include <windows.h>
  398. #include <windowsx.h>
  399. #include <commdlg.h>
  400. #include <shellapi.h>
  401. #include <mmsystem.h>
  402. #include <vfw.h>
  403. #include <tchar.h>
  404. #include <stddef.h>
  405. #include <ctime>
  406. #include <wininet.h>
  407. #include <nb30.h>
  408. #include <iphlpapi.h>
  409. #include <mapi.h>
  410. #include <float.h>
  411. #include <process.h>
  412. #include <Exdisp.h>
  413. #include <exdispid.h>
  414. #include <shlobj.h>
  415. #if ! JUCE_MINGW
  416. #include <crtdbg.h>
  417. #include <comutil.h>
  418. #endif
  419. #if JUCE_OPENGL
  420. #include <gl/gl.h>
  421. #endif
  422. #undef PACKED
  423. #if JUCE_ASIO
  424. /*
  425. This is very frustrating - we only need to use a handful of definitions from
  426. a couple of the header files in Steinberg's ASIO SDK, and it'd be easy to copy
  427. about 30 lines of code into this cpp file to create a fully stand-alone ASIO
  428. implementation...
  429. ..unfortunately that would break Steinberg's license agreement for use of
  430. their SDK, so I'm not allowed to do this.
  431. This means that anyone who wants to use JUCE's ASIO abilities will have to:
  432. 1) Agree to Steinberg's licensing terms and download the ASIO SDK
  433. (see www.steinberg.net/Steinberg/Developers.asp).
  434. 2) Rebuild the whole of JUCE, setting the global definition JUCE_ASIO (you
  435. can un-comment the "#define JUCE_ASIO" line in juce_Config.h
  436. if you prefer). Make sure that your header search path will find the
  437. iasiodrv.h file that comes with the SDK. (Only about 2-3 of the SDK header
  438. files are actually needed - so to simplify things, you could just copy
  439. these into your JUCE directory).
  440. If you're compiling and you get an error here because you don't have the
  441. ASIO SDK installed, you can disable ASIO support by commenting-out the
  442. "#define JUCE_ASIO" line in juce_Config.h, and rebuild your Juce library.
  443. */
  444. #include "iasiodrv.h"
  445. #endif
  446. #if JUCE_USE_CDBURNER
  447. /* You'll need the Platform SDK for these headers - if you don't have it and don't
  448. need to use CD-burning, then you might just want to disable the JUCE_USE_CDBURNER
  449. flag in juce_Config.h to avoid these includes.
  450. */
  451. #include <imapi.h>
  452. #include <imapierror.h>
  453. #endif
  454. #if JUCE_USE_CAMERA
  455. /* If you're using the camera classes, you'll need access to a few DirectShow headers.
  456. These files are provided in the normal Windows SDK, but some Microsoft plonker
  457. didn't realise that qedit.h doesn't actually compile without the rest of the DirectShow SDK..
  458. Microsoft's suggested fix for this is to hack their qedit.h file! See:
  459. http://social.msdn.microsoft.com/Forums/en-US/windowssdk/thread/ed097d2c-3d68-4f48-8448-277eaaf68252
  460. .. which is a bit of a bodge, but a lot less hassle than installing the full DShow SDK.
  461. An alternative workaround is to create a dummy dxtrans.h file and put it in your include path.
  462. The dummy file just needs to contain the following content:
  463. #define __IDxtCompositor_INTERFACE_DEFINED__
  464. #define __IDxtAlphaSetter_INTERFACE_DEFINED__
  465. #define __IDxtJpeg_INTERFACE_DEFINED__
  466. #define __IDxtKey_INTERFACE_DEFINED__
  467. ..and that should be enough to convince qedit.h that you have the SDK!
  468. */
  469. #include <dshow.h>
  470. #include <qedit.h>
  471. #include <dshowasf.h>
  472. #endif
  473. #if JUCE_WASAPI
  474. #include <MMReg.h>
  475. #include <mmdeviceapi.h>
  476. #include <Audioclient.h>
  477. #include <Avrt.h>
  478. #include <functiondiscoverykeys.h>
  479. #endif
  480. #if JUCE_QUICKTIME
  481. /* If you've got an include error here, you probably need to install the QuickTime SDK and
  482. add its header directory to your include path.
  483. Alternatively, if you don't need any QuickTime services, just turn off the JUCE_QUICKTIME
  484. flag in juce_Config.h
  485. */
  486. #include <Movies.h>
  487. #include <QTML.h>
  488. #include <QuickTimeComponents.h>
  489. #include <MediaHandlers.h>
  490. #include <ImageCodec.h>
  491. /* If you've got QuickTime 7 installed, then these COM objects should be found in
  492. the "\Program Files\Quicktime" directory. You'll need to add this directory to
  493. your include search path to make these import statements work.
  494. */
  495. #import <QTOLibrary.dll>
  496. #import <QTOControl.dll>
  497. #endif
  498. #ifdef _MSC_VER
  499. #pragma warning (pop)
  500. #endif
  501. /** A simple COM smart pointer.
  502. Avoids having to include ATL just to get one of these.
  503. */
  504. template <class ComClass>
  505. class ComSmartPtr
  506. {
  507. public:
  508. ComSmartPtr() throw() : p (0) {}
  509. ComSmartPtr (ComClass* const p_) : p (p_) { if (p_ != 0) p_->AddRef(); }
  510. ComSmartPtr (const ComSmartPtr<ComClass>& p_) : p (p_.p) { if (p != 0) p->AddRef(); }
  511. ~ComSmartPtr() { if (p != 0) p->Release(); }
  512. operator ComClass*() const throw() { return p; }
  513. ComClass& operator*() const throw() { return *p; }
  514. ComClass** operator&() throw() { return &p; }
  515. ComClass* operator->() const throw() { return p; }
  516. ComClass* operator= (ComClass* const newP)
  517. {
  518. if (newP != 0) newP->AddRef();
  519. if (p != 0) p->Release();
  520. p = newP;
  521. return newP;
  522. }
  523. ComClass* operator= (const ComSmartPtr<ComClass>& newP) { return operator= (newP.p); }
  524. HRESULT CoCreateInstance (REFCLSID rclsid, DWORD dwClsContext = CLSCTX_INPROC_SERVER)
  525. {
  526. #ifndef __MINGW32__
  527. operator= (0);
  528. return ::CoCreateInstance (rclsid, 0, dwClsContext, __uuidof (ComClass), (void**) &p);
  529. #else
  530. return S_FALSE;
  531. #endif
  532. }
  533. private:
  534. ComClass* p;
  535. };
  536. /** Handy base class for writing COM objects, providing ref-counting and a basic QueryInterface method.
  537. */
  538. template <class ComClass>
  539. class ComBaseClassHelper : public ComClass
  540. {
  541. public:
  542. ComBaseClassHelper() : refCount (1) {}
  543. virtual ~ComBaseClassHelper() {}
  544. HRESULT __stdcall QueryInterface (REFIID refId, void __RPC_FAR* __RPC_FAR* result)
  545. {
  546. if (refId == __uuidof (ComClass)) { AddRef(); *result = dynamic_cast <ComClass*> (this); return S_OK; }
  547. if (refId == IID_IUnknown) { AddRef(); *result = dynamic_cast <IUnknown*> (this); return S_OK; }
  548. *result = 0;
  549. return E_NOINTERFACE;
  550. }
  551. ULONG __stdcall AddRef() { return ++refCount; }
  552. ULONG __stdcall Release() { const int r = --refCount; if (r == 0) delete this; return r; }
  553. protected:
  554. int refCount;
  555. };
  556. #endif // __JUCE_WIN32_NATIVEINCLUDES_JUCEHEADER__
  557. /*** End of inlined file: juce_win32_NativeIncludes.h ***/
  558. #elif JUCE_LINUX
  559. /*** Start of inlined file: juce_linux_NativeIncludes.h ***/
  560. #ifndef __JUCE_LINUX_NATIVEINCLUDES_JUCEHEADER__
  561. #define __JUCE_LINUX_NATIVEINCLUDES_JUCEHEADER__
  562. /*
  563. This file wraps together all the linux-specific headers, so
  564. that we can include them all just once, and compile all our
  565. platform-specific stuff in one big lump, keeping it out of the
  566. way of the rest of the codebase.
  567. */
  568. #include <sched.h>
  569. #include <pthread.h>
  570. #include <sys/time.h>
  571. #include <errno.h>
  572. #include <sys/stat.h>
  573. #include <sys/dir.h>
  574. #include <sys/ptrace.h>
  575. #include <sys/vfs.h>
  576. #include <sys/wait.h>
  577. #include <fnmatch.h>
  578. #include <utime.h>
  579. #include <pwd.h>
  580. #include <fcntl.h>
  581. #include <dlfcn.h>
  582. #include <netdb.h>
  583. #include <arpa/inet.h>
  584. #include <netinet/in.h>
  585. #include <sys/types.h>
  586. #include <sys/ioctl.h>
  587. #include <sys/socket.h>
  588. #include <linux/if.h>
  589. #include <sys/sysinfo.h>
  590. #include <sys/file.h>
  591. #include <signal.h>
  592. /* Got a build error here? You'll need to install the freetype library...
  593. The name of the package to install is "libfreetype6-dev".
  594. */
  595. #include <ft2build.h>
  596. #include FT_FREETYPE_H
  597. #include <X11/Xlib.h>
  598. #include <X11/Xatom.h>
  599. #include <X11/Xresource.h>
  600. #include <X11/Xutil.h>
  601. #include <X11/Xmd.h>
  602. #include <X11/keysym.h>
  603. #include <X11/cursorfont.h>
  604. #if JUCE_USE_XINERAMA
  605. /* If you're trying to use Xinerama, you'll need to install the "libxinerama-dev" package.. */
  606. #include <X11/extensions/Xinerama.h>
  607. #endif
  608. #if JUCE_USE_XSHM
  609. #include <X11/extensions/XShm.h>
  610. #include <sys/shm.h>
  611. #include <sys/ipc.h>
  612. #endif
  613. #if JUCE_USE_XRENDER
  614. // If you're missing these headers, try installing the libxrender-dev and libxcomposite-dev
  615. #include <X11/extensions/Xrender.h>
  616. #include <X11/extensions/Xcomposite.h>
  617. #endif
  618. #if JUCE_USE_XCURSOR
  619. // If you're missing this header, try installing the libxcursor-dev package
  620. #include <X11/Xcursor/Xcursor.h>
  621. #endif
  622. #if JUCE_OPENGL
  623. /* Got an include error here?
  624. If you want to install OpenGL support, the packages to get are "mesa-common-dev"
  625. and "freeglut3-dev".
  626. Alternatively, you can turn off the JUCE_OPENGL flag in juce_Config.h if you
  627. want to disable it.
  628. */
  629. #include <GL/glx.h>
  630. #endif
  631. #undef KeyPress
  632. #if JUCE_ALSA
  633. /* Got an include error here? If so, you've either not got ALSA installed, or you've
  634. not got your paths set up correctly to find its header files.
  635. The package you need to install to get ASLA support is "libasound2-dev".
  636. If you don't have the ALSA library and don't want to build Juce with audio support,
  637. just disable the JUCE_ALSA flag in juce_Config.h
  638. */
  639. #include <alsa/asoundlib.h>
  640. #endif
  641. #if JUCE_JACK
  642. /* Got an include error here? If so, you've either not got jack-audio-connection-kit
  643. installed, or you've not got your paths set up correctly to find its header files.
  644. The package you need to install to get JACK support is "libjack-dev".
  645. If you don't have the jack-audio-connection-kit library and don't want to build
  646. Juce with low latency audio support, just disable the JUCE_JACK flag in juce_Config.h
  647. */
  648. #include <jack/jack.h>
  649. //#include <jack/transport.h>
  650. #endif
  651. #undef SIZEOF
  652. #endif // __JUCE_LINUX_NATIVEINCLUDES_JUCEHEADER__
  653. /*** End of inlined file: juce_linux_NativeIncludes.h ***/
  654. #elif JUCE_MAC || JUCE_IPHONE
  655. /*** Start of inlined file: juce_mac_NativeIncludes.h ***/
  656. #ifndef __JUCE_MAC_NATIVEINCLUDES_JUCEHEADER__
  657. #define __JUCE_MAC_NATIVEINCLUDES_JUCEHEADER__
  658. /*
  659. This file wraps together all the mac-specific code, so that
  660. we can include all the native headers just once, and compile all our
  661. platform-specific stuff in one big lump, keeping it out of the way of
  662. the rest of the codebase.
  663. */
  664. #define USE_COREGRAPHICS_RENDERING 1
  665. #if JUCE_IPHONE
  666. #import <Foundation/Foundation.h>
  667. #import <UIKit/UIKit.h>
  668. #import <AudioToolbox/AudioToolbox.h>
  669. #import <AVFoundation/AVFoundation.h>
  670. #import <CoreData/CoreData.h>
  671. #import <MobileCoreServices/MobileCoreServices.h>
  672. #import <QuartzCore/QuartzCore.h>
  673. #include <sys/fcntl.h>
  674. #if JUCE_OPENGL
  675. #include <OpenGLES/ES1/gl.h>
  676. #include <OpenGLES/ES1/glext.h>
  677. #endif
  678. #else
  679. #import <Cocoa/Cocoa.h>
  680. #import <CoreAudio/HostTime.h>
  681. #import <CoreAudio/AudioHardware.h>
  682. #import <CoreMIDI/MIDIServices.h>
  683. #import <QTKit/QTKit.h>
  684. #import <WebKit/WebKit.h>
  685. #import <DiscRecording/DiscRecording.h>
  686. #import <IOKit/IOKitLib.h>
  687. #import <IOKit/IOCFPlugIn.h>
  688. #import <IOKit/hid/IOHIDLib.h>
  689. #import <IOKit/hid/IOHIDKeys.h>
  690. #import <IOKit/pwr_mgt/IOPMLib.h>
  691. #include <Carbon/Carbon.h>
  692. #include <sys/dir.h>
  693. #endif
  694. #include <sys/socket.h>
  695. #include <sys/sysctl.h>
  696. #include <sys/stat.h>
  697. #include <sys/param.h>
  698. #include <sys/mount.h>
  699. #include <fnmatch.h>
  700. #include <utime.h>
  701. #include <dlfcn.h>
  702. #include <ifaddrs.h>
  703. #include <net/if_dl.h>
  704. #include <mach/mach_time.h>
  705. #if MACOS_10_4_OR_EARLIER
  706. #include <GLUT/glut.h>
  707. #endif
  708. #if ! CGFLOAT_DEFINED
  709. #define CGFloat float
  710. #endif
  711. #endif // __JUCE_MAC_NATIVEINCLUDES_JUCEHEADER__
  712. /*** End of inlined file: juce_mac_NativeIncludes.h ***/
  713. #else
  714. #error "Unknown platform!"
  715. #endif
  716. #endif
  717. //==============================================================================
  718. #define DONT_SET_USING_JUCE_NAMESPACE 1
  719. #undef max
  720. #undef min
  721. #define NO_DUMMY_DECL
  722. #if JUCE_BUILD_NATIVE
  723. #include "juce_amalgamated.h" // FORCE_AMALGAMATOR_INCLUDE
  724. #endif
  725. #if (defined(_MSC_VER) && (_MSC_VER <= 1200))
  726. #pragma warning (disable: 4309 4305)
  727. #endif
  728. #if JUCE_MAC && JUCE_32BIT && JUCE_SUPPORT_CARBON && JUCE_BUILD_NATIVE && ! JUCE_ONLY_BUILD_CORE_LIBRARY
  729. BEGIN_JUCE_NAMESPACE
  730. /*** Start of inlined file: juce_mac_CarbonViewWrapperComponent.h ***/
  731. #ifndef __JUCE_MAC_CARBONVIEWWRAPPERCOMPONENT_JUCEHEADER__
  732. #define __JUCE_MAC_CARBONVIEWWRAPPERCOMPONENT_JUCEHEADER__
  733. /**
  734. Creates a floating carbon window that can be used to hold a carbon UI.
  735. This is a handy class that's designed to be inlined where needed, e.g.
  736. in the audio plugin hosting code.
  737. */
  738. class CarbonViewWrapperComponent : public Component,
  739. public ComponentMovementWatcher,
  740. public Timer
  741. {
  742. public:
  743. CarbonViewWrapperComponent()
  744. : ComponentMovementWatcher (this),
  745. wrapperWindow (0),
  746. embeddedView (0),
  747. recursiveResize (false)
  748. {
  749. }
  750. virtual ~CarbonViewWrapperComponent()
  751. {
  752. jassert (embeddedView == 0); // must call deleteWindow() in the subclass's destructor!
  753. }
  754. virtual HIViewRef attachView (WindowRef windowRef, HIViewRef rootView) = 0;
  755. virtual void removeView (HIViewRef embeddedView) = 0;
  756. virtual void mouseDown (int, int) {}
  757. virtual void paint() {}
  758. virtual bool getEmbeddedViewSize (int& w, int& h)
  759. {
  760. if (embeddedView == 0)
  761. return false;
  762. HIRect bounds;
  763. HIViewGetBounds (embeddedView, &bounds);
  764. w = jmax (1, roundToInt (bounds.size.width));
  765. h = jmax (1, roundToInt (bounds.size.height));
  766. return true;
  767. }
  768. void createWindow()
  769. {
  770. if (wrapperWindow == 0)
  771. {
  772. Rect r;
  773. r.left = getScreenX();
  774. r.top = getScreenY();
  775. r.right = r.left + getWidth();
  776. r.bottom = r.top + getHeight();
  777. CreateNewWindow (kDocumentWindowClass,
  778. (WindowAttributes) (kWindowStandardHandlerAttribute | kWindowCompositingAttribute
  779. | kWindowNoShadowAttribute | kWindowNoTitleBarAttribute),
  780. &r, &wrapperWindow);
  781. jassert (wrapperWindow != 0);
  782. if (wrapperWindow == 0)
  783. return;
  784. NSWindow* carbonWindow = [[NSWindow alloc] initWithWindowRef: wrapperWindow];
  785. NSWindow* ownerWindow = [((NSView*) getWindowHandle()) window];
  786. [ownerWindow addChildWindow: carbonWindow
  787. ordered: NSWindowAbove];
  788. embeddedView = attachView (wrapperWindow, HIViewGetRoot (wrapperWindow));
  789. EventTypeSpec windowEventTypes[] = { { kEventClassWindow, kEventWindowGetClickActivation },
  790. { kEventClassWindow, kEventWindowHandleDeactivate } };
  791. EventHandlerUPP upp = NewEventHandlerUPP (carbonEventCallback);
  792. InstallWindowEventHandler (wrapperWindow, upp,
  793. sizeof (windowEventTypes) / sizeof (EventTypeSpec),
  794. windowEventTypes, this, &eventHandlerRef);
  795. setOurSizeToEmbeddedViewSize();
  796. setEmbeddedWindowToOurSize();
  797. creationTime = Time::getCurrentTime();
  798. }
  799. }
  800. void deleteWindow()
  801. {
  802. removeView (embeddedView);
  803. embeddedView = 0;
  804. if (wrapperWindow != 0)
  805. {
  806. RemoveEventHandler (eventHandlerRef);
  807. DisposeWindow (wrapperWindow);
  808. wrapperWindow = 0;
  809. }
  810. }
  811. void setOurSizeToEmbeddedViewSize()
  812. {
  813. int w, h;
  814. if (getEmbeddedViewSize (w, h))
  815. {
  816. if (w != getWidth() || h != getHeight())
  817. {
  818. startTimer (50);
  819. setSize (w, h);
  820. if (getParentComponent() != 0)
  821. getParentComponent()->setSize (w, h);
  822. }
  823. else
  824. {
  825. startTimer (jlimit (50, 500, getTimerInterval() + 20));
  826. }
  827. }
  828. else
  829. {
  830. stopTimer();
  831. }
  832. }
  833. void setEmbeddedWindowToOurSize()
  834. {
  835. if (! recursiveResize)
  836. {
  837. recursiveResize = true;
  838. if (embeddedView != 0)
  839. {
  840. HIRect r;
  841. r.origin.x = 0;
  842. r.origin.y = 0;
  843. r.size.width = (float) getWidth();
  844. r.size.height = (float) getHeight();
  845. HIViewSetFrame (embeddedView, &r);
  846. }
  847. if (wrapperWindow != 0)
  848. {
  849. Rect wr;
  850. wr.left = getScreenX();
  851. wr.top = getScreenY();
  852. wr.right = wr.left + getWidth();
  853. wr.bottom = wr.top + getHeight();
  854. SetWindowBounds (wrapperWindow, kWindowContentRgn, &wr);
  855. ShowWindow (wrapperWindow);
  856. }
  857. recursiveResize = false;
  858. }
  859. }
  860. void componentMovedOrResized (bool /*wasMoved*/, bool /*wasResized*/)
  861. {
  862. setEmbeddedWindowToOurSize();
  863. }
  864. void componentPeerChanged()
  865. {
  866. deleteWindow();
  867. createWindow();
  868. }
  869. void componentVisibilityChanged (Component&)
  870. {
  871. if (isShowing())
  872. createWindow();
  873. else
  874. deleteWindow();
  875. setEmbeddedWindowToOurSize();
  876. }
  877. static void recursiveHIViewRepaint (HIViewRef view)
  878. {
  879. HIViewSetNeedsDisplay (view, true);
  880. HIViewRef child = HIViewGetFirstSubview (view);
  881. while (child != 0)
  882. {
  883. recursiveHIViewRepaint (child);
  884. child = HIViewGetNextView (child);
  885. }
  886. }
  887. void timerCallback()
  888. {
  889. setOurSizeToEmbeddedViewSize();
  890. // To avoid strange overpainting problems when the UI is first opened, we'll
  891. // repaint it a few times during the first second that it's on-screen..
  892. if ((Time::getCurrentTime() - creationTime).inMilliseconds() < 1000)
  893. recursiveHIViewRepaint (HIViewGetRoot (wrapperWindow));
  894. }
  895. OSStatus carbonEventHandler (EventHandlerCallRef /*nextHandlerRef*/,
  896. EventRef event)
  897. {
  898. switch (GetEventKind (event))
  899. {
  900. case kEventWindowHandleDeactivate:
  901. ActivateWindow (wrapperWindow, TRUE);
  902. break;
  903. case kEventWindowGetClickActivation:
  904. {
  905. getTopLevelComponent()->toFront (false);
  906. ClickActivationResult howToHandleClick = kActivateAndHandleClick;
  907. SetEventParameter (event, kEventParamClickActivation, typeClickActivationResult,
  908. sizeof (ClickActivationResult), &howToHandleClick);
  909. HIViewSetNeedsDisplay (embeddedView, true);
  910. }
  911. break;
  912. }
  913. return noErr;
  914. }
  915. static pascal OSStatus carbonEventCallback (EventHandlerCallRef nextHandlerRef,
  916. EventRef event, void* userData)
  917. {
  918. return ((CarbonViewWrapperComponent*) userData)->carbonEventHandler (nextHandlerRef, event);
  919. }
  920. protected:
  921. WindowRef wrapperWindow;
  922. HIViewRef embeddedView;
  923. bool recursiveResize;
  924. Time creationTime;
  925. EventHandlerRef eventHandlerRef;
  926. };
  927. #endif // __JUCE_MAC_CARBONVIEWWRAPPERCOMPONENT_JUCEHEADER__
  928. /*** End of inlined file: juce_mac_CarbonViewWrapperComponent.h ***/
  929. END_JUCE_NAMESPACE
  930. #endif
  931. #define JUCE_AMALGAMATED_TEMPLATE 1
  932. //==============================================================================
  933. #if JUCE_BUILD_CORE
  934. /*** Start of inlined file: juce_FileLogger.cpp ***/
  935. BEGIN_JUCE_NAMESPACE
  936. FileLogger::FileLogger (const File& logFile_,
  937. const String& welcomeMessage,
  938. const int maxInitialFileSizeBytes)
  939. : logFile (logFile_)
  940. {
  941. if (maxInitialFileSizeBytes >= 0)
  942. trimFileSize (maxInitialFileSizeBytes);
  943. if (! logFile_.exists())
  944. {
  945. // do this so that the parent directories get created..
  946. logFile_.create();
  947. }
  948. logStream = logFile_.createOutputStream (256);
  949. jassert (logStream != 0);
  950. String welcome;
  951. welcome << "\r\n**********************************************************\r\n"
  952. << welcomeMessage
  953. << "\r\nLog started: " << Time::getCurrentTime().toString (true, true)
  954. << "\r\n";
  955. logMessage (welcome);
  956. }
  957. FileLogger::~FileLogger()
  958. {
  959. }
  960. void FileLogger::logMessage (const String& message)
  961. {
  962. if (logStream != 0)
  963. {
  964. DBG (message);
  965. const ScopedLock sl (logLock);
  966. (*logStream) << message << "\r\n";
  967. logStream->flush();
  968. }
  969. }
  970. void FileLogger::trimFileSize (int maxFileSizeBytes) const
  971. {
  972. if (maxFileSizeBytes <= 0)
  973. {
  974. logFile.deleteFile();
  975. }
  976. else
  977. {
  978. const int64 fileSize = logFile.getSize();
  979. if (fileSize > maxFileSizeBytes)
  980. {
  981. ScopedPointer <FileInputStream> in (logFile.createInputStream());
  982. jassert (in != 0);
  983. if (in != 0)
  984. {
  985. in->setPosition (fileSize - maxFileSizeBytes);
  986. String content;
  987. {
  988. MemoryBlock contentToSave;
  989. contentToSave.setSize (maxFileSizeBytes + 4);
  990. contentToSave.fillWith (0);
  991. in->read (contentToSave.getData(), maxFileSizeBytes);
  992. in = 0;
  993. content = contentToSave.toString();
  994. }
  995. int newStart = 0;
  996. while (newStart < fileSize
  997. && content[newStart] != '\n'
  998. && content[newStart] != '\r')
  999. ++newStart;
  1000. logFile.deleteFile();
  1001. logFile.appendText (content.substring (newStart), false, false);
  1002. }
  1003. }
  1004. }
  1005. }
  1006. FileLogger* FileLogger::createDefaultAppLogger (const String& logFileSubDirectoryName,
  1007. const String& logFileName,
  1008. const String& welcomeMessage,
  1009. const int maxInitialFileSizeBytes)
  1010. {
  1011. #if JUCE_MAC
  1012. File logFile ("~/Library/Logs");
  1013. logFile = logFile.getChildFile (logFileSubDirectoryName)
  1014. .getChildFile (logFileName);
  1015. #else
  1016. File logFile (File::getSpecialLocation (File::userApplicationDataDirectory));
  1017. if (logFile.isDirectory())
  1018. {
  1019. logFile = logFile.getChildFile (logFileSubDirectoryName)
  1020. .getChildFile (logFileName);
  1021. }
  1022. #endif
  1023. return new FileLogger (logFile, welcomeMessage, maxInitialFileSizeBytes);
  1024. }
  1025. END_JUCE_NAMESPACE
  1026. /*** End of inlined file: juce_FileLogger.cpp ***/
  1027. /*** Start of inlined file: juce_Logger.cpp ***/
  1028. BEGIN_JUCE_NAMESPACE
  1029. Logger::Logger()
  1030. {
  1031. }
  1032. Logger::~Logger()
  1033. {
  1034. }
  1035. static Logger* currentLogger = 0;
  1036. void Logger::setCurrentLogger (Logger* const newLogger,
  1037. const bool deleteOldLogger)
  1038. {
  1039. Logger* const oldLogger = currentLogger;
  1040. currentLogger = newLogger;
  1041. if (deleteOldLogger)
  1042. delete oldLogger;
  1043. }
  1044. void Logger::writeToLog (const String& message)
  1045. {
  1046. if (currentLogger != 0)
  1047. currentLogger->logMessage (message);
  1048. else
  1049. outputDebugString (message);
  1050. }
  1051. #if JUCE_LOG_ASSERTIONS
  1052. void JUCE_API juce_LogAssertion (const char* filename, const int lineNum) throw()
  1053. {
  1054. String m ("JUCE Assertion failure in ");
  1055. m << filename << ", line " << lineNum;
  1056. Logger::writeToLog (m);
  1057. }
  1058. #endif
  1059. END_JUCE_NAMESPACE
  1060. /*** End of inlined file: juce_Logger.cpp ***/
  1061. /*** Start of inlined file: juce_Random.cpp ***/
  1062. BEGIN_JUCE_NAMESPACE
  1063. Random::Random (const int64 seedValue) throw()
  1064. : seed (seedValue)
  1065. {
  1066. }
  1067. Random::~Random() throw()
  1068. {
  1069. }
  1070. void Random::setSeed (const int64 newSeed) throw()
  1071. {
  1072. seed = newSeed;
  1073. }
  1074. void Random::combineSeed (const int64 seedValue) throw()
  1075. {
  1076. seed ^= nextInt64() ^ seedValue;
  1077. }
  1078. void Random::setSeedRandomly()
  1079. {
  1080. combineSeed ((int64) (pointer_sized_int) this);
  1081. combineSeed (Time::getMillisecondCounter());
  1082. combineSeed (Time::getHighResolutionTicks());
  1083. combineSeed (Time::getHighResolutionTicksPerSecond());
  1084. combineSeed (Time::currentTimeMillis());
  1085. }
  1086. int Random::nextInt() throw()
  1087. {
  1088. seed = (seed * literal64bit (0x5deece66d) + 11) & literal64bit (0xffffffffffff);
  1089. return (int) (seed >> 16);
  1090. }
  1091. int Random::nextInt (const int maxValue) throw()
  1092. {
  1093. jassert (maxValue > 0);
  1094. return (nextInt() & 0x7fffffff) % maxValue;
  1095. }
  1096. int64 Random::nextInt64() throw()
  1097. {
  1098. return (((int64) nextInt()) << 32) | (int64) (uint64) (uint32) nextInt();
  1099. }
  1100. bool Random::nextBool() throw()
  1101. {
  1102. return (nextInt() & 0x80000000) != 0;
  1103. }
  1104. float Random::nextFloat() throw()
  1105. {
  1106. return static_cast <uint32> (nextInt()) / (float) 0xffffffff;
  1107. }
  1108. double Random::nextDouble() throw()
  1109. {
  1110. return static_cast <uint32> (nextInt()) / (double) 0xffffffff;
  1111. }
  1112. const BigInteger Random::nextLargeNumber (const BigInteger& maximumValue)
  1113. {
  1114. BigInteger n;
  1115. do
  1116. {
  1117. fillBitsRandomly (n, 0, maximumValue.getHighestBit() + 1);
  1118. }
  1119. while (n >= maximumValue);
  1120. return n;
  1121. }
  1122. void Random::fillBitsRandomly (BigInteger& arrayToChange, int startBit, int numBits)
  1123. {
  1124. arrayToChange.setBit (startBit + numBits - 1, true); // to force the array to pre-allocate space
  1125. while ((startBit & 31) != 0 && numBits > 0)
  1126. {
  1127. arrayToChange.setBit (startBit++, nextBool());
  1128. --numBits;
  1129. }
  1130. while (numBits >= 32)
  1131. {
  1132. arrayToChange.setBitRangeAsInt (startBit, 32, (unsigned int) nextInt());
  1133. startBit += 32;
  1134. numBits -= 32;
  1135. }
  1136. while (--numBits >= 0)
  1137. arrayToChange.setBit (startBit + numBits, nextBool());
  1138. }
  1139. Random& Random::getSystemRandom() throw()
  1140. {
  1141. static Random sysRand (1);
  1142. return sysRand;
  1143. }
  1144. END_JUCE_NAMESPACE
  1145. /*** End of inlined file: juce_Random.cpp ***/
  1146. /*** Start of inlined file: juce_RelativeTime.cpp ***/
  1147. BEGIN_JUCE_NAMESPACE
  1148. RelativeTime::RelativeTime (const double seconds_) throw()
  1149. : seconds (seconds_)
  1150. {
  1151. }
  1152. RelativeTime::RelativeTime (const RelativeTime& other) throw()
  1153. : seconds (other.seconds)
  1154. {
  1155. }
  1156. RelativeTime::~RelativeTime() throw()
  1157. {
  1158. }
  1159. const RelativeTime RelativeTime::milliseconds (const int milliseconds) throw()
  1160. {
  1161. return RelativeTime (milliseconds * 0.001);
  1162. }
  1163. const RelativeTime RelativeTime::milliseconds (const int64 milliseconds) throw()
  1164. {
  1165. return RelativeTime (milliseconds * 0.001);
  1166. }
  1167. const RelativeTime RelativeTime::minutes (const double numberOfMinutes) throw()
  1168. {
  1169. return RelativeTime (numberOfMinutes * 60.0);
  1170. }
  1171. const RelativeTime RelativeTime::hours (const double numberOfHours) throw()
  1172. {
  1173. return RelativeTime (numberOfHours * (60.0 * 60.0));
  1174. }
  1175. const RelativeTime RelativeTime::days (const double numberOfDays) throw()
  1176. {
  1177. return RelativeTime (numberOfDays * (60.0 * 60.0 * 24.0));
  1178. }
  1179. const RelativeTime RelativeTime::weeks (const double numberOfWeeks) throw()
  1180. {
  1181. return RelativeTime (numberOfWeeks * (60.0 * 60.0 * 24.0 * 7.0));
  1182. }
  1183. int64 RelativeTime::inMilliseconds() const throw()
  1184. {
  1185. return (int64)(seconds * 1000.0);
  1186. }
  1187. double RelativeTime::inMinutes() const throw()
  1188. {
  1189. return seconds / 60.0;
  1190. }
  1191. double RelativeTime::inHours() const throw()
  1192. {
  1193. return seconds / (60.0 * 60.0);
  1194. }
  1195. double RelativeTime::inDays() const throw()
  1196. {
  1197. return seconds / (60.0 * 60.0 * 24.0);
  1198. }
  1199. double RelativeTime::inWeeks() const throw()
  1200. {
  1201. return seconds / (60.0 * 60.0 * 24.0 * 7.0);
  1202. }
  1203. const String RelativeTime::getDescription (const String& returnValueForZeroTime) const throw()
  1204. {
  1205. if (seconds < 0.001 && seconds > -0.001)
  1206. return returnValueForZeroTime;
  1207. String result;
  1208. if (seconds < 0)
  1209. result = "-";
  1210. int fieldsShown = 0;
  1211. int n = abs ((int) inWeeks());
  1212. if (n > 0)
  1213. {
  1214. result << n << ((n == 1) ? TRANS(" week ")
  1215. : TRANS(" weeks "));
  1216. ++fieldsShown;
  1217. }
  1218. n = abs ((int) inDays()) % 7;
  1219. if (n > 0)
  1220. {
  1221. result << n << ((n == 1) ? TRANS(" day ")
  1222. : TRANS(" days "));
  1223. ++fieldsShown;
  1224. }
  1225. if (fieldsShown < 2)
  1226. {
  1227. n = abs ((int) inHours()) % 24;
  1228. if (n > 0)
  1229. {
  1230. result << n << ((n == 1) ? TRANS(" hr ")
  1231. : TRANS(" hrs "));
  1232. ++fieldsShown;
  1233. }
  1234. if (fieldsShown < 2)
  1235. {
  1236. n = abs ((int) inMinutes()) % 60;
  1237. if (n > 0)
  1238. {
  1239. result << n << ((n == 1) ? TRANS(" min ")
  1240. : TRANS(" mins "));
  1241. ++fieldsShown;
  1242. }
  1243. if (fieldsShown < 2)
  1244. {
  1245. n = abs ((int) inSeconds()) % 60;
  1246. if (n > 0)
  1247. {
  1248. result << n << ((n == 1) ? TRANS(" sec ")
  1249. : TRANS(" secs "));
  1250. ++fieldsShown;
  1251. }
  1252. if (fieldsShown < 1)
  1253. {
  1254. n = abs ((int) inMilliseconds()) % 1000;
  1255. if (n > 0)
  1256. {
  1257. result << n << TRANS(" ms");
  1258. ++fieldsShown;
  1259. }
  1260. }
  1261. }
  1262. }
  1263. }
  1264. return result.trimEnd();
  1265. }
  1266. RelativeTime& RelativeTime::operator= (const RelativeTime& other) throw()
  1267. {
  1268. seconds = other.seconds;
  1269. return *this;
  1270. }
  1271. bool RelativeTime::operator== (const RelativeTime& other) const throw()
  1272. {
  1273. return seconds == other.seconds;
  1274. }
  1275. bool RelativeTime::operator!= (const RelativeTime& other) const throw()
  1276. {
  1277. return seconds != other.seconds;
  1278. }
  1279. bool RelativeTime::operator> (const RelativeTime& other) const throw()
  1280. {
  1281. return seconds > other.seconds;
  1282. }
  1283. bool RelativeTime::operator< (const RelativeTime& other) const throw()
  1284. {
  1285. return seconds < other.seconds;
  1286. }
  1287. bool RelativeTime::operator>= (const RelativeTime& other) const throw()
  1288. {
  1289. return seconds >= other.seconds;
  1290. }
  1291. bool RelativeTime::operator<= (const RelativeTime& other) const throw()
  1292. {
  1293. return seconds <= other.seconds;
  1294. }
  1295. const RelativeTime RelativeTime::operator+ (const RelativeTime& timeToAdd) const throw()
  1296. {
  1297. return RelativeTime (seconds + timeToAdd.seconds);
  1298. }
  1299. const RelativeTime RelativeTime::operator- (const RelativeTime& timeToSubtract) const throw()
  1300. {
  1301. return RelativeTime (seconds - timeToSubtract.seconds);
  1302. }
  1303. const RelativeTime RelativeTime::operator+ (const double secondsToAdd) const throw()
  1304. {
  1305. return RelativeTime (seconds + secondsToAdd);
  1306. }
  1307. const RelativeTime RelativeTime::operator- (const double secondsToSubtract) const throw()
  1308. {
  1309. return RelativeTime (seconds - secondsToSubtract);
  1310. }
  1311. const RelativeTime& RelativeTime::operator+= (const RelativeTime& timeToAdd) throw()
  1312. {
  1313. seconds += timeToAdd.seconds;
  1314. return *this;
  1315. }
  1316. const RelativeTime& RelativeTime::operator-= (const RelativeTime& timeToSubtract) throw()
  1317. {
  1318. seconds -= timeToSubtract.seconds;
  1319. return *this;
  1320. }
  1321. const RelativeTime& RelativeTime::operator+= (const double secondsToAdd) throw()
  1322. {
  1323. seconds += secondsToAdd;
  1324. return *this;
  1325. }
  1326. const RelativeTime& RelativeTime::operator-= (const double secondsToSubtract) throw()
  1327. {
  1328. seconds -= secondsToSubtract;
  1329. return *this;
  1330. }
  1331. END_JUCE_NAMESPACE
  1332. /*** End of inlined file: juce_RelativeTime.cpp ***/
  1333. /*** Start of inlined file: juce_SystemStats.cpp ***/
  1334. BEGIN_JUCE_NAMESPACE
  1335. const String SystemStats::getJUCEVersion()
  1336. {
  1337. return "JUCE v" + String (JUCE_MAJOR_VERSION)
  1338. + "." + String (JUCE_MINOR_VERSION)
  1339. + "." + String (JUCE_BUILDNUMBER);
  1340. }
  1341. const StringArray SystemStats::getMACAddressStrings()
  1342. {
  1343. int64 macAddresses [16];
  1344. const int numAddresses = getMACAddresses (macAddresses, numElementsInArray (macAddresses), false);
  1345. StringArray s;
  1346. for (int i = 0; i < numAddresses; ++i)
  1347. {
  1348. s.add (String::toHexString (0xff & (int) (macAddresses [i] >> 40)).paddedLeft ('0', 2)
  1349. + "-" + String::toHexString (0xff & (int) (macAddresses [i] >> 32)).paddedLeft ('0', 2)
  1350. + "-" + String::toHexString (0xff & (int) (macAddresses [i] >> 24)).paddedLeft ('0', 2)
  1351. + "-" + String::toHexString (0xff & (int) (macAddresses [i] >> 16)).paddedLeft ('0', 2)
  1352. + "-" + String::toHexString (0xff & (int) (macAddresses [i] >> 8)).paddedLeft ('0', 2)
  1353. + "-" + String::toHexString (0xff & (int) (macAddresses [i] >> 0)).paddedLeft ('0', 2));
  1354. }
  1355. return s;
  1356. }
  1357. static bool juceInitialisedNonGUI = false;
  1358. #if JUCE_DEBUG
  1359. template <typename Type>
  1360. static void juce_testAtomicType (Type)
  1361. {
  1362. Atomic<Type> a, b;
  1363. a.set ((Type) 10);
  1364. a += (Type) 15;
  1365. a.memoryBarrier();
  1366. a -= (Type) 5;
  1367. ++a;
  1368. ++a;
  1369. --a;
  1370. a.memoryBarrier();
  1371. /* These are some simple test cases to check the atomics - let me know
  1372. if any of these assertions fail on your system!
  1373. */
  1374. jassert (a.get() == (Type) 21);
  1375. jassert (a.compareAndSetValue ((Type) 100, (Type) 50) == (Type) 21);
  1376. jassert (a.get() == (Type) 21);
  1377. jassert (a.compareAndSetValue ((Type) 101, a.get()) == (Type) 21);
  1378. jassert (a.get() == (Type) 101);
  1379. jassert (! a.compareAndSetBool ((Type) 300, (Type) 200));
  1380. jassert (a.get() == (Type) 101);
  1381. jassert (a.compareAndSetBool ((Type) 200, a.get()));
  1382. jassert (a.get() == (Type) 200);
  1383. jassert (a.exchange ((Type) 300) == (Type) 200);
  1384. jassert (a.get() == (Type) 300);
  1385. b = a;
  1386. jassert (b.get() == a.get());
  1387. }
  1388. static void juce_testAtomics()
  1389. {
  1390. juce_testAtomicType ((int) 0);
  1391. juce_testAtomicType ((unsigned int) 0);
  1392. juce_testAtomicType ((int32) 0);
  1393. juce_testAtomicType ((uint32) 0);
  1394. juce_testAtomicType ((long) 0);
  1395. juce_testAtomicType ((void*) 0);
  1396. juce_testAtomicType ((int*) 0);
  1397. #if ! ((JUCE_WINDOWS && JUCE_32BIT) || JUCE_PPC) // 64-bit intrinsics aren't available on some old platforms
  1398. juce_testAtomicType ((int64) 0);
  1399. juce_testAtomicType ((uint64) 0);
  1400. #endif
  1401. }
  1402. #endif
  1403. void JUCE_PUBLIC_FUNCTION initialiseJuce_NonGUI()
  1404. {
  1405. if (! juceInitialisedNonGUI)
  1406. {
  1407. #if JUCE_MAC || JUCE_IPHONE
  1408. const ScopedAutoReleasePool pool;
  1409. #endif
  1410. #if JUCE_DEBUG
  1411. {
  1412. // Some simple test code to keep an eye on things and make sure these functions
  1413. // work ok on all platforms. Let me know if any of these assertions fail!
  1414. static_jassert (sizeof (pointer_sized_int) == sizeof (void*));
  1415. static_jassert (sizeof (int8) == 1);
  1416. static_jassert (sizeof (uint8) == 1);
  1417. static_jassert (sizeof (int16) == 2);
  1418. static_jassert (sizeof (uint16) == 2);
  1419. static_jassert (sizeof (int32) == 4);
  1420. static_jassert (sizeof (uint32) == 4);
  1421. static_jassert (sizeof (int64) == 8);
  1422. static_jassert (sizeof (uint64) == 8);
  1423. char a1[7];
  1424. jassert (numElementsInArray(a1) == 7);
  1425. int a2[3];
  1426. jassert (numElementsInArray(a2) == 3);
  1427. juce_testAtomics();
  1428. jassert (ByteOrder::swap ((uint16) 0x1122) == 0x2211);
  1429. jassert (ByteOrder::swap ((uint32) 0x11223344) == 0x44332211);
  1430. // Some quick stream tests..
  1431. int randomInt = Random::getSystemRandom().nextInt();
  1432. int64 randomInt64 = Random::getSystemRandom().nextInt64();
  1433. double randomDouble = Random::getSystemRandom().nextDouble();
  1434. String randomString;
  1435. for (int i = 50; --i >= 0;)
  1436. randomString << (juce_wchar) (Random::getSystemRandom().nextInt() & 0xffff);
  1437. MemoryOutputStream mo;
  1438. mo.writeInt (randomInt);
  1439. mo.writeIntBigEndian (randomInt);
  1440. mo.writeCompressedInt (randomInt);
  1441. mo.writeString (randomString);
  1442. mo.writeInt64 (randomInt64);
  1443. mo.writeInt64BigEndian (randomInt64);
  1444. mo.writeDouble (randomDouble);
  1445. mo.writeDoubleBigEndian (randomDouble);
  1446. MemoryInputStream mi (mo.getData(), mo.getDataSize(), false);
  1447. jassert (mi.readInt() == randomInt);
  1448. jassert (mi.readIntBigEndian() == randomInt);
  1449. jassert (mi.readCompressedInt() == randomInt);
  1450. jassert (mi.readString() == randomString);
  1451. jassert (mi.readInt64() == randomInt64);
  1452. jassert (mi.readInt64BigEndian() == randomInt64);
  1453. jassert (mi.readDouble() == randomDouble);
  1454. jassert (mi.readDoubleBigEndian() == randomDouble);
  1455. }
  1456. #endif
  1457. // Now the real initialisation..
  1458. juceInitialisedNonGUI = true;
  1459. DBG (SystemStats::getJUCEVersion());
  1460. SystemStats::initialiseStats();
  1461. Random::getSystemRandom().setSeedRandomly(); // (mustn't call this before initialiseStats() because it relies on the time being set up)
  1462. }
  1463. }
  1464. #if JUCE_WINDOWS
  1465. // This is imported from the sockets code..
  1466. typedef int (__stdcall juce_CloseWin32SocketLibCall) (void);
  1467. extern juce_CloseWin32SocketLibCall* juce_CloseWin32SocketLib;
  1468. #endif
  1469. #if JUCE_DEBUG
  1470. extern void juce_CheckForDanglingStreams();
  1471. #endif
  1472. void JUCE_PUBLIC_FUNCTION shutdownJuce_NonGUI()
  1473. {
  1474. if (juceInitialisedNonGUI)
  1475. {
  1476. #if JUCE_MAC || JUCE_IPHONE
  1477. const ScopedAutoReleasePool pool;
  1478. #endif
  1479. #if JUCE_WINDOWS
  1480. // need to shut down sockets if they were used..
  1481. if (juce_CloseWin32SocketLib != 0)
  1482. (*juce_CloseWin32SocketLib)();
  1483. #endif
  1484. LocalisedStrings::setCurrentMappings (0);
  1485. Thread::stopAllThreads (3000);
  1486. #if JUCE_DEBUG
  1487. juce_CheckForDanglingStreams();
  1488. #endif
  1489. juceInitialisedNonGUI = false;
  1490. }
  1491. }
  1492. #ifdef JUCE_DLL
  1493. void* juce_Malloc (const int size)
  1494. {
  1495. return malloc (size);
  1496. }
  1497. void* juce_Calloc (const int size)
  1498. {
  1499. return calloc (1, size);
  1500. }
  1501. void* juce_Realloc (void* const block, const int size)
  1502. {
  1503. return realloc (block, size);
  1504. }
  1505. void juce_Free (void* const block)
  1506. {
  1507. free (block);
  1508. }
  1509. #if JUCE_DEBUG && JUCE_MSVC && JUCE_CHECK_MEMORY_LEAKS
  1510. void* juce_DebugMalloc (const int size, const char* file, const int line)
  1511. {
  1512. return _malloc_dbg (size, _NORMAL_BLOCK, file, line);
  1513. }
  1514. void* juce_DebugCalloc (const int size, const char* file, const int line)
  1515. {
  1516. return _calloc_dbg (1, size, _NORMAL_BLOCK, file, line);
  1517. }
  1518. void* juce_DebugRealloc (void* const block, const int size, const char* file, const int line)
  1519. {
  1520. return _realloc_dbg (block, size, _NORMAL_BLOCK, file, line);
  1521. }
  1522. void juce_DebugFree (void* const block)
  1523. {
  1524. _free_dbg (block, _NORMAL_BLOCK);
  1525. }
  1526. #endif
  1527. #endif
  1528. END_JUCE_NAMESPACE
  1529. /*** End of inlined file: juce_SystemStats.cpp ***/
  1530. /*** Start of inlined file: juce_Time.cpp ***/
  1531. #ifdef _MSC_VER
  1532. #pragma warning (disable: 4514)
  1533. #pragma warning (push)
  1534. #endif
  1535. #ifndef JUCE_WINDOWS
  1536. #include <sys/time.h>
  1537. #else
  1538. #include <ctime>
  1539. #endif
  1540. #include <sys/timeb.h>
  1541. BEGIN_JUCE_NAMESPACE
  1542. #ifdef _MSC_VER
  1543. #pragma warning (pop)
  1544. #ifdef _INC_TIME_INL
  1545. #define USE_NEW_SECURE_TIME_FNS
  1546. #endif
  1547. #endif
  1548. namespace TimeHelpers
  1549. {
  1550. static struct tm millisToLocal (const int64 millis) throw()
  1551. {
  1552. struct tm result;
  1553. const int64 seconds = millis / 1000;
  1554. if (seconds < literal64bit (86400) || seconds >= literal64bit (2145916800))
  1555. {
  1556. // use extended maths for dates beyond 1970 to 2037..
  1557. const int timeZoneAdjustment = 31536000 - (int) (Time (1971, 0, 1, 0, 0).toMilliseconds() / 1000);
  1558. const int64 jdm = seconds + timeZoneAdjustment + literal64bit (210866803200);
  1559. const int days = (int) (jdm / literal64bit (86400));
  1560. const int a = 32044 + days;
  1561. const int b = (4 * a + 3) / 146097;
  1562. const int c = a - (b * 146097) / 4;
  1563. const int d = (4 * c + 3) / 1461;
  1564. const int e = c - (d * 1461) / 4;
  1565. const int m = (5 * e + 2) / 153;
  1566. result.tm_mday = e - (153 * m + 2) / 5 + 1;
  1567. result.tm_mon = m + 2 - 12 * (m / 10);
  1568. result.tm_year = b * 100 + d - 6700 + (m / 10);
  1569. result.tm_wday = (days + 1) % 7;
  1570. result.tm_yday = -1;
  1571. int t = (int) (jdm % literal64bit (86400));
  1572. result.tm_hour = t / 3600;
  1573. t %= 3600;
  1574. result.tm_min = t / 60;
  1575. result.tm_sec = t % 60;
  1576. result.tm_isdst = -1;
  1577. }
  1578. else
  1579. {
  1580. time_t now = static_cast <time_t> (seconds);
  1581. #if JUCE_WINDOWS
  1582. #ifdef USE_NEW_SECURE_TIME_FNS
  1583. if (now >= 0 && now <= 0x793406fff)
  1584. localtime_s (&result, &now);
  1585. else
  1586. zeromem (&result, sizeof (result));
  1587. #else
  1588. result = *localtime (&now);
  1589. #endif
  1590. #else
  1591. // more thread-safe
  1592. localtime_r (&now, &result);
  1593. #endif
  1594. }
  1595. return result;
  1596. }
  1597. static int extendedModulo (const int64 value, const int modulo) throw()
  1598. {
  1599. return (int) (value >= 0 ? (value % modulo)
  1600. : (value - ((value / modulo) + 1) * modulo));
  1601. }
  1602. static uint32 lastMSCounterValue = 0;
  1603. }
  1604. Time::Time() throw()
  1605. : millisSinceEpoch (0)
  1606. {
  1607. }
  1608. Time::Time (const Time& other) throw()
  1609. : millisSinceEpoch (other.millisSinceEpoch)
  1610. {
  1611. }
  1612. Time::Time (const int64 ms) throw()
  1613. : millisSinceEpoch (ms)
  1614. {
  1615. }
  1616. Time::Time (const int year,
  1617. const int month,
  1618. const int day,
  1619. const int hours,
  1620. const int minutes,
  1621. const int seconds,
  1622. const int milliseconds,
  1623. const bool useLocalTime) throw()
  1624. {
  1625. jassert (year > 100); // year must be a 4-digit version
  1626. if (year < 1971 || year >= 2038 || ! useLocalTime)
  1627. {
  1628. // use extended maths for dates beyond 1970 to 2037..
  1629. const int timeZoneAdjustment = useLocalTime ? (31536000 - (int) (Time (1971, 0, 1, 0, 0).toMilliseconds() / 1000))
  1630. : 0;
  1631. const int a = (13 - month) / 12;
  1632. const int y = year + 4800 - a;
  1633. const int jd = day + (153 * (month + 12 * a - 2) + 2) / 5
  1634. + (y * 365) + (y / 4) - (y / 100) + (y / 400)
  1635. - 32045;
  1636. const int64 s = ((int64) jd) * literal64bit (86400) - literal64bit (210866803200);
  1637. millisSinceEpoch = 1000 * (s + (hours * 3600 + minutes * 60 + seconds - timeZoneAdjustment))
  1638. + milliseconds;
  1639. }
  1640. else
  1641. {
  1642. struct tm t;
  1643. t.tm_year = year - 1900;
  1644. t.tm_mon = month;
  1645. t.tm_mday = day;
  1646. t.tm_hour = hours;
  1647. t.tm_min = minutes;
  1648. t.tm_sec = seconds;
  1649. t.tm_isdst = -1;
  1650. millisSinceEpoch = 1000 * (int64) mktime (&t);
  1651. if (millisSinceEpoch < 0)
  1652. millisSinceEpoch = 0;
  1653. else
  1654. millisSinceEpoch += milliseconds;
  1655. }
  1656. }
  1657. Time::~Time() throw()
  1658. {
  1659. }
  1660. Time& Time::operator= (const Time& other) throw()
  1661. {
  1662. millisSinceEpoch = other.millisSinceEpoch;
  1663. return *this;
  1664. }
  1665. int64 Time::currentTimeMillis() throw()
  1666. {
  1667. static uint32 lastCounterResult = 0xffffffff;
  1668. static int64 correction = 0;
  1669. const uint32 now = getMillisecondCounter();
  1670. // check the counter hasn't wrapped (also triggered the first time this function is called)
  1671. if (now < lastCounterResult)
  1672. {
  1673. // double-check it's actually wrapped, in case multi-cpu machines have timers that drift a bit.
  1674. if (lastCounterResult == 0xffffffff || now < lastCounterResult - 10)
  1675. {
  1676. // get the time once using normal library calls, and store the difference needed to
  1677. // turn the millisecond counter into a real time.
  1678. #if JUCE_WINDOWS
  1679. struct _timeb t;
  1680. #ifdef USE_NEW_SECURE_TIME_FNS
  1681. _ftime_s (&t);
  1682. #else
  1683. _ftime (&t);
  1684. #endif
  1685. correction = (((int64) t.time) * 1000 + t.millitm) - now;
  1686. #else
  1687. struct timeval tv;
  1688. struct timezone tz;
  1689. gettimeofday (&tv, &tz);
  1690. correction = (((int64) tv.tv_sec) * 1000 + tv.tv_usec / 1000) - now;
  1691. #endif
  1692. }
  1693. }
  1694. lastCounterResult = now;
  1695. return correction + now;
  1696. }
  1697. uint32 juce_millisecondsSinceStartup() throw();
  1698. uint32 Time::getMillisecondCounter() throw()
  1699. {
  1700. const uint32 now = juce_millisecondsSinceStartup();
  1701. if (now < TimeHelpers::lastMSCounterValue)
  1702. {
  1703. // in multi-threaded apps this might be called concurrently, so
  1704. // make sure that our last counter value only increases and doesn't
  1705. // go backwards..
  1706. if (now < TimeHelpers::lastMSCounterValue - 1000)
  1707. TimeHelpers::lastMSCounterValue = now;
  1708. }
  1709. else
  1710. {
  1711. TimeHelpers::lastMSCounterValue = now;
  1712. }
  1713. return now;
  1714. }
  1715. uint32 Time::getApproximateMillisecondCounter() throw()
  1716. {
  1717. jassert (TimeHelpers::lastMSCounterValue != 0);
  1718. return TimeHelpers::lastMSCounterValue;
  1719. }
  1720. void Time::waitForMillisecondCounter (const uint32 targetTime) throw()
  1721. {
  1722. for (;;)
  1723. {
  1724. const uint32 now = getMillisecondCounter();
  1725. if (now >= targetTime)
  1726. break;
  1727. const int toWait = targetTime - now;
  1728. if (toWait > 2)
  1729. {
  1730. Thread::sleep (jmin (20, toWait >> 1));
  1731. }
  1732. else
  1733. {
  1734. // xxx should consider using mutex_pause on the mac as it apparently
  1735. // makes it seem less like a spinlock and avoids lowering the thread pri.
  1736. for (int i = 10; --i >= 0;)
  1737. Thread::yield();
  1738. }
  1739. }
  1740. }
  1741. double Time::highResolutionTicksToSeconds (const int64 ticks) throw()
  1742. {
  1743. return ticks / (double) getHighResolutionTicksPerSecond();
  1744. }
  1745. int64 Time::secondsToHighResolutionTicks (const double seconds) throw()
  1746. {
  1747. return (int64) (seconds * (double) getHighResolutionTicksPerSecond());
  1748. }
  1749. const Time JUCE_CALLTYPE Time::getCurrentTime() throw()
  1750. {
  1751. return Time (currentTimeMillis());
  1752. }
  1753. const String Time::toString (const bool includeDate,
  1754. const bool includeTime,
  1755. const bool includeSeconds,
  1756. const bool use24HourClock) const throw()
  1757. {
  1758. String result;
  1759. if (includeDate)
  1760. {
  1761. result << getDayOfMonth() << ' '
  1762. << getMonthName (true) << ' '
  1763. << getYear();
  1764. if (includeTime)
  1765. result << ' ';
  1766. }
  1767. if (includeTime)
  1768. {
  1769. const int mins = getMinutes();
  1770. result << (use24HourClock ? getHours() : getHoursInAmPmFormat())
  1771. << (mins < 10 ? ":0" : ":") << mins;
  1772. if (includeSeconds)
  1773. {
  1774. const int secs = getSeconds();
  1775. result << (secs < 10 ? ":0" : ":") << secs;
  1776. }
  1777. if (! use24HourClock)
  1778. result << (isAfternoon() ? "pm" : "am");
  1779. }
  1780. return result.trimEnd();
  1781. }
  1782. const String Time::formatted (const String& format) const throw()
  1783. {
  1784. String buffer;
  1785. int bufferSize = 128;
  1786. buffer.preallocateStorage (bufferSize);
  1787. struct tm t (TimeHelpers::millisToLocal (millisSinceEpoch));
  1788. while (CharacterFunctions::ftime (static_cast <juce_wchar*> (buffer), bufferSize, format, &t) <= 0)
  1789. {
  1790. bufferSize += 128;
  1791. buffer.preallocateStorage (bufferSize);
  1792. }
  1793. return buffer;
  1794. }
  1795. int Time::getYear() const throw()
  1796. {
  1797. return TimeHelpers::millisToLocal (millisSinceEpoch).tm_year + 1900;
  1798. }
  1799. int Time::getMonth() const throw()
  1800. {
  1801. return TimeHelpers::millisToLocal (millisSinceEpoch).tm_mon;
  1802. }
  1803. int Time::getDayOfMonth() const throw()
  1804. {
  1805. return TimeHelpers::millisToLocal (millisSinceEpoch).tm_mday;
  1806. }
  1807. int Time::getDayOfWeek() const throw()
  1808. {
  1809. return TimeHelpers::millisToLocal (millisSinceEpoch).tm_wday;
  1810. }
  1811. int Time::getHours() const throw()
  1812. {
  1813. return TimeHelpers::millisToLocal (millisSinceEpoch).tm_hour;
  1814. }
  1815. int Time::getHoursInAmPmFormat() const throw()
  1816. {
  1817. const int hours = getHours();
  1818. if (hours == 0)
  1819. return 12;
  1820. else if (hours <= 12)
  1821. return hours;
  1822. else
  1823. return hours - 12;
  1824. }
  1825. bool Time::isAfternoon() const throw()
  1826. {
  1827. return getHours() >= 12;
  1828. }
  1829. int Time::getMinutes() const throw()
  1830. {
  1831. return TimeHelpers::millisToLocal (millisSinceEpoch).tm_min;
  1832. }
  1833. int Time::getSeconds() const throw()
  1834. {
  1835. return TimeHelpers::extendedModulo (millisSinceEpoch / 1000, 60);
  1836. }
  1837. int Time::getMilliseconds() const throw()
  1838. {
  1839. return TimeHelpers::extendedModulo (millisSinceEpoch, 1000);
  1840. }
  1841. bool Time::isDaylightSavingTime() const throw()
  1842. {
  1843. return TimeHelpers::millisToLocal (millisSinceEpoch).tm_isdst != 0;
  1844. }
  1845. const String Time::getTimeZone() const throw()
  1846. {
  1847. String zone[2];
  1848. #if JUCE_WINDOWS
  1849. _tzset();
  1850. #ifdef USE_NEW_SECURE_TIME_FNS
  1851. {
  1852. char name [128];
  1853. size_t length;
  1854. for (int i = 0; i < 2; ++i)
  1855. {
  1856. zeromem (name, sizeof (name));
  1857. _get_tzname (&length, name, 127, i);
  1858. zone[i] = name;
  1859. }
  1860. }
  1861. #else
  1862. const char** const zonePtr = (const char**) _tzname;
  1863. zone[0] = zonePtr[0];
  1864. zone[1] = zonePtr[1];
  1865. #endif
  1866. #else
  1867. tzset();
  1868. const char** const zonePtr = (const char**) tzname;
  1869. zone[0] = zonePtr[0];
  1870. zone[1] = zonePtr[1];
  1871. #endif
  1872. if (isDaylightSavingTime())
  1873. {
  1874. zone[0] = zone[1];
  1875. if (zone[0].length() > 3
  1876. && zone[0].containsIgnoreCase ("daylight")
  1877. && zone[0].contains ("GMT"))
  1878. zone[0] = "BST";
  1879. }
  1880. return zone[0].substring (0, 3);
  1881. }
  1882. const String Time::getMonthName (const bool threeLetterVersion) const throw()
  1883. {
  1884. return getMonthName (getMonth(), threeLetterVersion);
  1885. }
  1886. const String Time::getWeekdayName (const bool threeLetterVersion) const throw()
  1887. {
  1888. return getWeekdayName (getDayOfWeek(), threeLetterVersion);
  1889. }
  1890. const String Time::getMonthName (int monthNumber, const bool threeLetterVersion) throw()
  1891. {
  1892. const char* const shortMonthNames[] = { "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" };
  1893. const char* const longMonthNames[] = { "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" };
  1894. monthNumber %= 12;
  1895. return TRANS (threeLetterVersion ? shortMonthNames [monthNumber]
  1896. : longMonthNames [monthNumber]);
  1897. }
  1898. const String Time::getWeekdayName (int day, const bool threeLetterVersion) throw()
  1899. {
  1900. const char* const shortDayNames[] = { "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" };
  1901. const char* const longDayNames[] = { "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday" };
  1902. day %= 7;
  1903. return TRANS (threeLetterVersion ? shortDayNames [day]
  1904. : longDayNames [day]);
  1905. }
  1906. END_JUCE_NAMESPACE
  1907. /*** End of inlined file: juce_Time.cpp ***/
  1908. /*** Start of inlined file: juce_BitArray.cpp ***/
  1909. BEGIN_JUCE_NAMESPACE
  1910. BigInteger::BigInteger()
  1911. : numValues (4),
  1912. highestBit (-1),
  1913. negative (false)
  1914. {
  1915. values.calloc (numValues + 1);
  1916. }
  1917. BigInteger::BigInteger (const int value)
  1918. : numValues (4),
  1919. highestBit (31),
  1920. negative (value < 0)
  1921. {
  1922. values.calloc (numValues + 1);
  1923. values[0] = abs (value);
  1924. highestBit = getHighestBit();
  1925. }
  1926. BigInteger::BigInteger (int64 value)
  1927. : numValues (4),
  1928. highestBit (63),
  1929. negative (value < 0)
  1930. {
  1931. values.calloc (numValues + 1);
  1932. if (value < 0)
  1933. value = -value;
  1934. values[0] = (unsigned int) value;
  1935. values[1] = (unsigned int) (value >> 32);
  1936. highestBit = getHighestBit();
  1937. }
  1938. BigInteger::BigInteger (const unsigned int value)
  1939. : numValues (4),
  1940. highestBit (31),
  1941. negative (false)
  1942. {
  1943. values.calloc (numValues + 1);
  1944. values[0] = value;
  1945. highestBit = getHighestBit();
  1946. }
  1947. BigInteger::BigInteger (const BigInteger& other)
  1948. : numValues (jmax (4, (other.highestBit >> 5) + 1)),
  1949. highestBit (other.getHighestBit()),
  1950. negative (other.negative)
  1951. {
  1952. values.malloc (numValues + 1);
  1953. memcpy (values, other.values, sizeof (unsigned int) * (numValues + 1));
  1954. }
  1955. BigInteger::~BigInteger()
  1956. {
  1957. }
  1958. void BigInteger::swapWith (BigInteger& other) throw()
  1959. {
  1960. values.swapWith (other.values);
  1961. swapVariables (numValues, other.numValues);
  1962. swapVariables (highestBit, other.highestBit);
  1963. swapVariables (negative, other.negative);
  1964. }
  1965. BigInteger& BigInteger::operator= (const BigInteger& other)
  1966. {
  1967. if (this != &other)
  1968. {
  1969. highestBit = other.getHighestBit();
  1970. numValues = jmax (4, (highestBit >> 5) + 1);
  1971. negative = other.negative;
  1972. values.malloc (numValues + 1);
  1973. memcpy (values, other.values, sizeof (unsigned int) * (numValues + 1));
  1974. }
  1975. return *this;
  1976. }
  1977. void BigInteger::ensureSize (const int numVals)
  1978. {
  1979. if (numVals + 2 >= numValues)
  1980. {
  1981. int oldSize = numValues;
  1982. numValues = ((numVals + 2) * 3) / 2;
  1983. values.realloc (numValues + 1);
  1984. while (oldSize < numValues)
  1985. values [oldSize++] = 0;
  1986. }
  1987. }
  1988. bool BigInteger::operator[] (const int bit) const throw()
  1989. {
  1990. return bit <= highestBit && bit >= 0
  1991. && ((values [bit >> 5] & (1 << (bit & 31))) != 0);
  1992. }
  1993. int BigInteger::toInteger() const throw()
  1994. {
  1995. const int n = (int) (values[0] & 0x7fffffff);
  1996. return negative ? -n : n;
  1997. }
  1998. const BigInteger BigInteger::getBitRange (int startBit, int numBits) const
  1999. {
  2000. BigInteger r;
  2001. numBits = jmin (numBits, getHighestBit() + 1 - startBit);
  2002. r.ensureSize (numBits >> 5);
  2003. r.highestBit = numBits;
  2004. int i = 0;
  2005. while (numBits > 0)
  2006. {
  2007. r.values[i++] = getBitRangeAsInt (startBit, jmin (32, numBits));
  2008. numBits -= 32;
  2009. startBit += 32;
  2010. }
  2011. r.highestBit = r.getHighestBit();
  2012. return r;
  2013. }
  2014. int BigInteger::getBitRangeAsInt (const int startBit, int numBits) const throw()
  2015. {
  2016. if (numBits > 32)
  2017. {
  2018. jassertfalse // use getBitRange() if you need more than 32 bits..
  2019. numBits = 32;
  2020. }
  2021. numBits = jmin (numBits, highestBit + 1 - startBit);
  2022. if (numBits <= 0)
  2023. return 0;
  2024. const int pos = startBit >> 5;
  2025. const int offset = startBit & 31;
  2026. const int endSpace = 32 - numBits;
  2027. uint32 n = ((uint32) values [pos]) >> offset;
  2028. if (offset > endSpace)
  2029. n |= ((uint32) values [pos + 1]) << (32 - offset);
  2030. return (int) (n & (((uint32) 0xffffffff) >> endSpace));
  2031. }
  2032. void BigInteger::setBitRangeAsInt (const int startBit, int numBits, unsigned int valueToSet)
  2033. {
  2034. if (numBits > 32)
  2035. {
  2036. jassertfalse
  2037. numBits = 32;
  2038. }
  2039. for (int i = 0; i < numBits; ++i)
  2040. {
  2041. setBit (startBit + i, (valueToSet & 1) != 0);
  2042. valueToSet >>= 1;
  2043. }
  2044. }
  2045. void BigInteger::clear()
  2046. {
  2047. if (numValues > 16)
  2048. {
  2049. numValues = 4;
  2050. values.calloc (numValues + 1);
  2051. }
  2052. else
  2053. {
  2054. zeromem (values, sizeof (unsigned int) * (numValues + 1));
  2055. }
  2056. highestBit = -1;
  2057. negative = false;
  2058. }
  2059. void BigInteger::setBit (const int bit)
  2060. {
  2061. if (bit >= 0)
  2062. {
  2063. if (bit > highestBit)
  2064. {
  2065. ensureSize (bit >> 5);
  2066. highestBit = bit;
  2067. }
  2068. values [bit >> 5] |= (1 << (bit & 31));
  2069. }
  2070. }
  2071. void BigInteger::setBit (const int bit, const bool shouldBeSet)
  2072. {
  2073. if (shouldBeSet)
  2074. setBit (bit);
  2075. else
  2076. clearBit (bit);
  2077. }
  2078. void BigInteger::clearBit (const int bit) throw()
  2079. {
  2080. if (bit >= 0 && bit <= highestBit)
  2081. values [bit >> 5] &= ~(1 << (bit & 31));
  2082. }
  2083. void BigInteger::setRange (int startBit, int numBits, const bool shouldBeSet)
  2084. {
  2085. while (--numBits >= 0)
  2086. setBit (startBit++, shouldBeSet);
  2087. }
  2088. void BigInteger::insertBit (const int bit, const bool shouldBeSet)
  2089. {
  2090. if (bit >= 0)
  2091. shiftBits (1, bit);
  2092. setBit (bit, shouldBeSet);
  2093. }
  2094. bool BigInteger::isZero() const throw()
  2095. {
  2096. return getHighestBit() < 0;
  2097. }
  2098. bool BigInteger::isOne() const throw()
  2099. {
  2100. return getHighestBit() == 0 && ! negative;
  2101. }
  2102. bool BigInteger::isNegative() const throw()
  2103. {
  2104. return negative && ! isZero();
  2105. }
  2106. void BigInteger::setNegative (const bool neg) throw()
  2107. {
  2108. negative = neg;
  2109. }
  2110. void BigInteger::negate() throw()
  2111. {
  2112. negative = (! negative) && ! isZero();
  2113. }
  2114. int BigInteger::countNumberOfSetBits() const throw()
  2115. {
  2116. int total = 0;
  2117. for (int i = (highestBit >> 5) + 1; --i >= 0;)
  2118. {
  2119. unsigned int n = values[i];
  2120. if (n == 0xffffffff)
  2121. {
  2122. total += 32;
  2123. }
  2124. else
  2125. {
  2126. while (n != 0)
  2127. {
  2128. total += (n & 1);
  2129. n >>= 1;
  2130. }
  2131. }
  2132. }
  2133. return total;
  2134. }
  2135. int BigInteger::getHighestBit() const throw()
  2136. {
  2137. for (int i = highestBit + 1; --i >= 0;)
  2138. if ((values [i >> 5] & (1 << (i & 31))) != 0)
  2139. return i;
  2140. return -1;
  2141. }
  2142. int BigInteger::findNextSetBit (int i) const throw()
  2143. {
  2144. for (; i <= highestBit; ++i)
  2145. if ((values [i >> 5] & (1 << (i & 31))) != 0)
  2146. return i;
  2147. return -1;
  2148. }
  2149. int BigInteger::findNextClearBit (int i) const throw()
  2150. {
  2151. for (; i <= highestBit; ++i)
  2152. if ((values [i >> 5] & (1 << (i & 31))) == 0)
  2153. break;
  2154. return i;
  2155. }
  2156. BigInteger& BigInteger::operator+= (const BigInteger& other)
  2157. {
  2158. if (other.isNegative())
  2159. return operator-= (-other);
  2160. if (isNegative())
  2161. {
  2162. if (compareAbsolute (other) < 0)
  2163. {
  2164. BigInteger temp (*this);
  2165. temp.negate();
  2166. *this = other;
  2167. operator-= (temp);
  2168. }
  2169. else
  2170. {
  2171. negate();
  2172. operator-= (other);
  2173. negate();
  2174. }
  2175. }
  2176. else
  2177. {
  2178. if (other.highestBit > highestBit)
  2179. highestBit = other.highestBit;
  2180. ++highestBit;
  2181. const int numInts = (highestBit >> 5) + 1;
  2182. ensureSize (numInts);
  2183. int64 remainder = 0;
  2184. for (int i = 0; i <= numInts; ++i)
  2185. {
  2186. if (i < numValues)
  2187. remainder += values[i];
  2188. if (i < other.numValues)
  2189. remainder += other.values[i];
  2190. values[i] = (unsigned int) remainder;
  2191. remainder >>= 32;
  2192. }
  2193. jassert (remainder == 0);
  2194. highestBit = getHighestBit();
  2195. }
  2196. return *this;
  2197. }
  2198. BigInteger& BigInteger::operator-= (const BigInteger& other)
  2199. {
  2200. if (other.isNegative())
  2201. return operator+= (-other);
  2202. if (! isNegative())
  2203. {
  2204. if (compareAbsolute (other) < 0)
  2205. {
  2206. BigInteger temp (other);
  2207. swapWith (temp);
  2208. operator-= (temp);
  2209. negate();
  2210. return *this;
  2211. }
  2212. }
  2213. else
  2214. {
  2215. negate();
  2216. operator+= (other);
  2217. negate();
  2218. return *this;
  2219. }
  2220. const int numInts = (highestBit >> 5) + 1;
  2221. const int maxOtherInts = (other.highestBit >> 5) + 1;
  2222. int64 amountToSubtract = 0;
  2223. for (int i = 0; i <= numInts; ++i)
  2224. {
  2225. if (i <= maxOtherInts)
  2226. amountToSubtract += (int64) other.values[i];
  2227. if (values[i] >= amountToSubtract)
  2228. {
  2229. values[i] = (unsigned int) (values[i] - amountToSubtract);
  2230. amountToSubtract = 0;
  2231. }
  2232. else
  2233. {
  2234. const int64 n = ((int64) values[i] + (((int64) 1) << 32)) - amountToSubtract;
  2235. values[i] = (unsigned int) n;
  2236. amountToSubtract = 1;
  2237. }
  2238. }
  2239. return *this;
  2240. }
  2241. BigInteger& BigInteger::operator*= (const BigInteger& other)
  2242. {
  2243. BigInteger total;
  2244. highestBit = getHighestBit();
  2245. const bool wasNegative = isNegative();
  2246. setNegative (false);
  2247. for (int i = 0; i <= highestBit; ++i)
  2248. {
  2249. if (operator[](i))
  2250. {
  2251. BigInteger n (other);
  2252. n.setNegative (false);
  2253. n <<= i;
  2254. total += n;
  2255. }
  2256. }
  2257. total.setNegative (wasNegative ^ other.isNegative());
  2258. swapWith (total);
  2259. return *this;
  2260. }
  2261. void BigInteger::divideBy (const BigInteger& divisor, BigInteger& remainder)
  2262. {
  2263. jassert (this != &remainder); // (can't handle passing itself in to get the remainder)
  2264. const int divHB = divisor.getHighestBit();
  2265. const int ourHB = getHighestBit();
  2266. if (divHB < 0 || ourHB < 0)
  2267. {
  2268. // division by zero
  2269. remainder.clear();
  2270. clear();
  2271. }
  2272. else
  2273. {
  2274. const bool wasNegative = isNegative();
  2275. swapWith (remainder);
  2276. remainder.setNegative (false);
  2277. clear();
  2278. BigInteger temp (divisor);
  2279. temp.setNegative (false);
  2280. int leftShift = ourHB - divHB;
  2281. temp <<= leftShift;
  2282. while (leftShift >= 0)
  2283. {
  2284. if (remainder.compareAbsolute (temp) >= 0)
  2285. {
  2286. remainder -= temp;
  2287. setBit (leftShift);
  2288. }
  2289. if (--leftShift >= 0)
  2290. temp >>= 1;
  2291. }
  2292. negative = wasNegative ^ divisor.isNegative();
  2293. remainder.setNegative (wasNegative);
  2294. }
  2295. }
  2296. BigInteger& BigInteger::operator/= (const BigInteger& other)
  2297. {
  2298. BigInteger remainder;
  2299. divideBy (other, remainder);
  2300. return *this;
  2301. }
  2302. BigInteger& BigInteger::operator|= (const BigInteger& other)
  2303. {
  2304. // this operation doesn't take into account negative values..
  2305. jassert (isNegative() == other.isNegative());
  2306. if (other.highestBit >= 0)
  2307. {
  2308. ensureSize (other.highestBit >> 5);
  2309. int n = (other.highestBit >> 5) + 1;
  2310. while (--n >= 0)
  2311. values[n] |= other.values[n];
  2312. if (other.highestBit > highestBit)
  2313. highestBit = other.highestBit;
  2314. highestBit = getHighestBit();
  2315. }
  2316. return *this;
  2317. }
  2318. BigInteger& BigInteger::operator&= (const BigInteger& other)
  2319. {
  2320. // this operation doesn't take into account negative values..
  2321. jassert (isNegative() == other.isNegative());
  2322. int n = numValues;
  2323. while (n > other.numValues)
  2324. values[--n] = 0;
  2325. while (--n >= 0)
  2326. values[n] &= other.values[n];
  2327. if (other.highestBit < highestBit)
  2328. highestBit = other.highestBit;
  2329. highestBit = getHighestBit();
  2330. return *this;
  2331. }
  2332. BigInteger& BigInteger::operator^= (const BigInteger& other)
  2333. {
  2334. // this operation will only work with the absolute values
  2335. jassert (isNegative() == other.isNegative());
  2336. if (other.highestBit >= 0)
  2337. {
  2338. ensureSize (other.highestBit >> 5);
  2339. int n = (other.highestBit >> 5) + 1;
  2340. while (--n >= 0)
  2341. values[n] ^= other.values[n];
  2342. if (other.highestBit > highestBit)
  2343. highestBit = other.highestBit;
  2344. highestBit = getHighestBit();
  2345. }
  2346. return *this;
  2347. }
  2348. BigInteger& BigInteger::operator%= (const BigInteger& divisor)
  2349. {
  2350. BigInteger remainder;
  2351. divideBy (divisor, remainder);
  2352. swapWith (remainder);
  2353. return *this;
  2354. }
  2355. BigInteger& BigInteger::operator<<= (int numBitsToShift)
  2356. {
  2357. shiftBits (numBitsToShift, 0);
  2358. return *this;
  2359. }
  2360. BigInteger& BigInteger::operator>>= (int numBitsToShift)
  2361. {
  2362. return operator<<= (-numBitsToShift);
  2363. }
  2364. BigInteger& BigInteger::operator++() { return operator+= (1); }
  2365. BigInteger& BigInteger::operator--() { return operator-= (1); }
  2366. const BigInteger BigInteger::operator++ (int) { const BigInteger old (*this); operator+= (1); return old; }
  2367. const BigInteger BigInteger::operator-- (int) { const BigInteger old (*this); operator-= (1); return old; }
  2368. const BigInteger BigInteger::operator+ (const BigInteger& other) const { BigInteger b (*this); return b += other; }
  2369. const BigInteger BigInteger::operator- (const BigInteger& other) const { BigInteger b (*this); return b -= other; }
  2370. const BigInteger BigInteger::operator* (const BigInteger& other) const { BigInteger b (*this); return b *= other; }
  2371. const BigInteger BigInteger::operator/ (const BigInteger& other) const { BigInteger b (*this); return b /= other; }
  2372. const BigInteger BigInteger::operator| (const BigInteger& other) const { BigInteger b (*this); return b |= other; }
  2373. const BigInteger BigInteger::operator& (const BigInteger& other) const { BigInteger b (*this); return b &= other; }
  2374. const BigInteger BigInteger::operator^ (const BigInteger& other) const { BigInteger b (*this); return b ^= other; }
  2375. const BigInteger BigInteger::operator% (const BigInteger& other) const { BigInteger b (*this); return b %= other; }
  2376. const BigInteger BigInteger::operator<< (const int numBits) const { BigInteger b (*this); return b <<= numBits; }
  2377. const BigInteger BigInteger::operator>> (const int numBits) const { BigInteger b (*this); return b >>= numBits; }
  2378. const BigInteger BigInteger::operator-() const { BigInteger b (*this); b.negate(); return b; }
  2379. int BigInteger::compare (const BigInteger& other) const throw()
  2380. {
  2381. if (isNegative() == other.isNegative())
  2382. {
  2383. const int absComp = compareAbsolute (other);
  2384. return isNegative() ? -absComp : absComp;
  2385. }
  2386. else
  2387. {
  2388. return isNegative() ? -1 : 1;
  2389. }
  2390. }
  2391. int BigInteger::compareAbsolute (const BigInteger& other) const throw()
  2392. {
  2393. const int h1 = getHighestBit();
  2394. const int h2 = other.getHighestBit();
  2395. if (h1 > h2)
  2396. return 1;
  2397. else if (h1 < h2)
  2398. return -1;
  2399. for (int i = (h1 >> 5) + 1; --i >= 0;)
  2400. if (values[i] != other.values[i])
  2401. return (values[i] > other.values[i]) ? 1 : -1;
  2402. return 0;
  2403. }
  2404. bool BigInteger::operator== (const BigInteger& other) const throw() { return compare (other) == 0; }
  2405. bool BigInteger::operator!= (const BigInteger& other) const throw() { return compare (other) != 0; }
  2406. bool BigInteger::operator< (const BigInteger& other) const throw() { return compare (other) < 0; }
  2407. bool BigInteger::operator<= (const BigInteger& other) const throw() { return compare (other) <= 0; }
  2408. bool BigInteger::operator> (const BigInteger& other) const throw() { return compare (other) > 0; }
  2409. bool BigInteger::operator>= (const BigInteger& other) const throw() { return compare (other) >= 0; }
  2410. void BigInteger::shiftBits (int bits, const int startBit)
  2411. {
  2412. if (highestBit < 0)
  2413. return;
  2414. if (startBit > 0)
  2415. {
  2416. if (bits < 0)
  2417. {
  2418. // right shift
  2419. for (int i = startBit; i <= highestBit; ++i)
  2420. setBit (i, operator[] (i - bits));
  2421. highestBit = getHighestBit();
  2422. }
  2423. else if (bits > 0)
  2424. {
  2425. // left shift
  2426. for (int i = highestBit + 1; --i >= startBit;)
  2427. setBit (i + bits, operator[] (i));
  2428. while (--bits >= 0)
  2429. clearBit (bits + startBit);
  2430. }
  2431. }
  2432. else
  2433. {
  2434. if (bits < 0)
  2435. {
  2436. // right shift
  2437. bits = -bits;
  2438. if (bits > highestBit)
  2439. {
  2440. clear();
  2441. }
  2442. else
  2443. {
  2444. const int wordsToMove = bits >> 5;
  2445. int top = 1 + (highestBit >> 5) - wordsToMove;
  2446. highestBit -= bits;
  2447. if (wordsToMove > 0)
  2448. {
  2449. int i;
  2450. for (i = 0; i < top; ++i)
  2451. values [i] = values [i + wordsToMove];
  2452. for (i = 0; i < wordsToMove; ++i)
  2453. values [top + i] = 0;
  2454. bits &= 31;
  2455. }
  2456. if (bits != 0)
  2457. {
  2458. const int invBits = 32 - bits;
  2459. --top;
  2460. for (int i = 0; i < top; ++i)
  2461. values[i] = (values[i] >> bits) | (values [i + 1] << invBits);
  2462. values[top] = (values[top] >> bits);
  2463. }
  2464. highestBit = getHighestBit();
  2465. }
  2466. }
  2467. else if (bits > 0)
  2468. {
  2469. // left shift
  2470. ensureSize (((highestBit + bits) >> 5) + 1);
  2471. const int wordsToMove = bits >> 5;
  2472. int top = 1 + (highestBit >> 5);
  2473. highestBit += bits;
  2474. if (wordsToMove > 0)
  2475. {
  2476. int i;
  2477. for (i = top; --i >= 0;)
  2478. values [i + wordsToMove] = values [i];
  2479. for (i = 0; i < wordsToMove; ++i)
  2480. values [i] = 0;
  2481. bits &= 31;
  2482. }
  2483. if (bits != 0)
  2484. {
  2485. const int invBits = 32 - bits;
  2486. for (int i = top + 1 + wordsToMove; --i > wordsToMove;)
  2487. values[i] = (values[i] << bits) | (values [i - 1] >> invBits);
  2488. values [wordsToMove] = values [wordsToMove] << bits;
  2489. }
  2490. highestBit = getHighestBit();
  2491. }
  2492. }
  2493. }
  2494. const BigInteger BigInteger::simpleGCD (BigInteger* m, BigInteger* n)
  2495. {
  2496. while (! m->isZero())
  2497. {
  2498. if (n->compareAbsolute (*m) > 0)
  2499. swapVariables (m, n);
  2500. *m -= *n;
  2501. }
  2502. return *n;
  2503. }
  2504. const BigInteger BigInteger::findGreatestCommonDivisor (BigInteger n) const
  2505. {
  2506. BigInteger m (*this);
  2507. while (! n.isZero())
  2508. {
  2509. if (abs (m.getHighestBit() - n.getHighestBit()) <= 16)
  2510. return simpleGCD (&m, &n);
  2511. BigInteger temp1 (m), temp2;
  2512. temp1.divideBy (n, temp2);
  2513. m = n;
  2514. n = temp2;
  2515. }
  2516. return m;
  2517. }
  2518. void BigInteger::exponentModulo (const BigInteger& exponent, const BigInteger& modulus)
  2519. {
  2520. BigInteger exp (exponent);
  2521. exp %= modulus;
  2522. BigInteger value (1);
  2523. swapWith (value);
  2524. value %= modulus;
  2525. while (! exp.isZero())
  2526. {
  2527. if (exp [0])
  2528. {
  2529. operator*= (value);
  2530. operator%= (modulus);
  2531. }
  2532. value *= value;
  2533. value %= modulus;
  2534. exp >>= 1;
  2535. }
  2536. }
  2537. void BigInteger::inverseModulo (const BigInteger& modulus)
  2538. {
  2539. if (modulus.isOne() || modulus.isNegative())
  2540. {
  2541. clear();
  2542. return;
  2543. }
  2544. if (isNegative() || compareAbsolute (modulus) >= 0)
  2545. operator%= (modulus);
  2546. if (isOne())
  2547. return;
  2548. if (! (*this)[0])
  2549. {
  2550. // not invertible
  2551. clear();
  2552. return;
  2553. }
  2554. BigInteger a1 (modulus);
  2555. BigInteger a2 (*this);
  2556. BigInteger b1 (modulus);
  2557. BigInteger b2 (1);
  2558. while (! a2.isOne())
  2559. {
  2560. BigInteger temp1, temp2, multiplier (a1);
  2561. multiplier.divideBy (a2, temp1);
  2562. temp1 = a2;
  2563. temp1 *= multiplier;
  2564. temp2 = a1;
  2565. temp2 -= temp1;
  2566. a1 = a2;
  2567. a2 = temp2;
  2568. temp1 = b2;
  2569. temp1 *= multiplier;
  2570. temp2 = b1;
  2571. temp2 -= temp1;
  2572. b1 = b2;
  2573. b2 = temp2;
  2574. }
  2575. while (b2.isNegative())
  2576. b2 += modulus;
  2577. b2 %= modulus;
  2578. swapWith (b2);
  2579. }
  2580. OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, const BigInteger& value)
  2581. {
  2582. return stream << value.toString (10);
  2583. }
  2584. const String BigInteger::toString (const int base, const int minimumNumCharacters) const
  2585. {
  2586. String s;
  2587. BigInteger v (*this);
  2588. if (base == 2 || base == 8 || base == 16)
  2589. {
  2590. const int bits = (base == 2) ? 1 : (base == 8 ? 3 : 4);
  2591. static const char* const hexDigits = "0123456789abcdef";
  2592. for (;;)
  2593. {
  2594. const int remainder = v.getBitRangeAsInt (0, bits);
  2595. v >>= bits;
  2596. if (remainder == 0 && v.isZero())
  2597. break;
  2598. s = String::charToString (hexDigits [remainder]) + s;
  2599. }
  2600. }
  2601. else if (base == 10)
  2602. {
  2603. const BigInteger ten (10);
  2604. BigInteger remainder;
  2605. for (;;)
  2606. {
  2607. v.divideBy (ten, remainder);
  2608. if (remainder.isZero() && v.isZero())
  2609. break;
  2610. s = String (remainder.getBitRangeAsInt (0, 8)) + s;
  2611. }
  2612. }
  2613. else
  2614. {
  2615. jassertfalse // can't do the specified base!
  2616. return String::empty;
  2617. }
  2618. s = s.paddedLeft ('0', minimumNumCharacters);
  2619. return isNegative() ? "-" + s : s;
  2620. }
  2621. void BigInteger::parseString (const String& text, const int base)
  2622. {
  2623. clear();
  2624. const juce_wchar* t = text;
  2625. if (base == 2 || base == 8 || base == 16)
  2626. {
  2627. const int bits = (base == 2) ? 1 : (base == 8 ? 3 : 4);
  2628. for (;;)
  2629. {
  2630. const juce_wchar c = *t++;
  2631. const int digit = CharacterFunctions::getHexDigitValue (c);
  2632. if (((unsigned int) digit) < (unsigned int) base)
  2633. {
  2634. operator<<= (bits);
  2635. operator+= (digit);
  2636. }
  2637. else if (c == 0)
  2638. {
  2639. break;
  2640. }
  2641. }
  2642. }
  2643. else if (base == 10)
  2644. {
  2645. const BigInteger ten ((unsigned int) 10);
  2646. for (;;)
  2647. {
  2648. const juce_wchar c = *t++;
  2649. if (c >= '0' && c <= '9')
  2650. {
  2651. operator*= (ten);
  2652. operator+= ((int) (c - '0'));
  2653. }
  2654. else if (c == 0)
  2655. {
  2656. break;
  2657. }
  2658. }
  2659. }
  2660. setNegative (text.trimStart().startsWithChar ('-'));
  2661. }
  2662. const MemoryBlock BigInteger::toMemoryBlock() const
  2663. {
  2664. const int numBytes = (getHighestBit() + 8) >> 3;
  2665. MemoryBlock mb ((size_t) numBytes);
  2666. for (int i = 0; i < numBytes; ++i)
  2667. mb[i] = (uint8) getBitRangeAsInt (i << 3, 8);
  2668. return mb;
  2669. }
  2670. void BigInteger::loadFromMemoryBlock (const MemoryBlock& data)
  2671. {
  2672. clear();
  2673. for (int i = (int) data.getSize(); --i >= 0;)
  2674. this->setBitRangeAsInt ((int) (i << 3), 8, data [i]);
  2675. }
  2676. END_JUCE_NAMESPACE
  2677. /*** End of inlined file: juce_BitArray.cpp ***/
  2678. /*** Start of inlined file: juce_MemoryBlock.cpp ***/
  2679. BEGIN_JUCE_NAMESPACE
  2680. MemoryBlock::MemoryBlock() throw()
  2681. : size (0)
  2682. {
  2683. }
  2684. MemoryBlock::MemoryBlock (const size_t initialSize,
  2685. const bool initialiseToZero) throw()
  2686. {
  2687. if (initialSize > 0)
  2688. {
  2689. size = initialSize;
  2690. data.allocate (initialSize, initialiseToZero);
  2691. }
  2692. else
  2693. {
  2694. size = 0;
  2695. }
  2696. }
  2697. MemoryBlock::MemoryBlock (const MemoryBlock& other) throw()
  2698. : size (other.size)
  2699. {
  2700. if (size > 0)
  2701. {
  2702. jassert (other.data != 0);
  2703. data.malloc (size);
  2704. memcpy (data, other.data, size);
  2705. }
  2706. }
  2707. MemoryBlock::MemoryBlock (const void* const dataToInitialiseFrom,
  2708. const size_t sizeInBytes) throw()
  2709. : size (jmax ((size_t) 0, sizeInBytes))
  2710. {
  2711. jassert (sizeInBytes >= 0);
  2712. if (size > 0)
  2713. {
  2714. jassert (dataToInitialiseFrom != 0); // non-zero size, but a zero pointer passed-in?
  2715. data.malloc (size);
  2716. if (dataToInitialiseFrom != 0)
  2717. memcpy (data, dataToInitialiseFrom, size);
  2718. }
  2719. }
  2720. MemoryBlock::~MemoryBlock() throw()
  2721. {
  2722. jassert (size >= 0); // should never happen
  2723. jassert (size == 0 || data != 0); // non-zero size but no data allocated?
  2724. }
  2725. MemoryBlock& MemoryBlock::operator= (const MemoryBlock& other) throw()
  2726. {
  2727. if (this != &other)
  2728. {
  2729. setSize (other.size, false);
  2730. memcpy (data, other.data, size);
  2731. }
  2732. return *this;
  2733. }
  2734. bool MemoryBlock::operator== (const MemoryBlock& other) const throw()
  2735. {
  2736. return matches (other.data, other.size);
  2737. }
  2738. bool MemoryBlock::operator!= (const MemoryBlock& other) const throw()
  2739. {
  2740. return ! operator== (other);
  2741. }
  2742. bool MemoryBlock::matches (const void* dataToCompare, size_t dataSize) const throw()
  2743. {
  2744. return size == dataSize
  2745. && memcmp (data, dataToCompare, size) == 0;
  2746. }
  2747. // this will resize the block to this size
  2748. void MemoryBlock::setSize (const size_t newSize,
  2749. const bool initialiseToZero) throw()
  2750. {
  2751. if (size != newSize)
  2752. {
  2753. if (newSize <= 0)
  2754. {
  2755. data.free();
  2756. size = 0;
  2757. }
  2758. else
  2759. {
  2760. if (data != 0)
  2761. {
  2762. data.realloc (newSize);
  2763. if (initialiseToZero && (newSize > size))
  2764. zeromem (data + size, newSize - size);
  2765. }
  2766. else
  2767. {
  2768. data.allocate (newSize, initialiseToZero);
  2769. }
  2770. size = newSize;
  2771. }
  2772. }
  2773. }
  2774. void MemoryBlock::ensureSize (const size_t minimumSize,
  2775. const bool initialiseToZero) throw()
  2776. {
  2777. if (size < minimumSize)
  2778. setSize (minimumSize, initialiseToZero);
  2779. }
  2780. void MemoryBlock::swapWith (MemoryBlock& other) throw()
  2781. {
  2782. swapVariables (size, other.size);
  2783. data.swapWith (other.data);
  2784. }
  2785. void MemoryBlock::fillWith (const uint8 value) throw()
  2786. {
  2787. memset (data, (int) value, size);
  2788. }
  2789. void MemoryBlock::append (const void* const srcData,
  2790. const size_t numBytes) throw()
  2791. {
  2792. if (numBytes > 0)
  2793. {
  2794. const size_t oldSize = size;
  2795. setSize (size + numBytes);
  2796. memcpy (data + oldSize, srcData, numBytes);
  2797. }
  2798. }
  2799. void MemoryBlock::copyFrom (const void* const src, int offset, size_t num) throw()
  2800. {
  2801. const char* d = static_cast<const char*> (src);
  2802. if (offset < 0)
  2803. {
  2804. d -= offset;
  2805. num -= offset;
  2806. offset = 0;
  2807. }
  2808. if (offset + num > size)
  2809. num = size - offset;
  2810. if (num > 0)
  2811. memcpy (data + offset, d, num);
  2812. }
  2813. void MemoryBlock::copyTo (void* const dst, int offset, size_t num) const throw()
  2814. {
  2815. char* d = static_cast<char*> (dst);
  2816. if (offset < 0)
  2817. {
  2818. zeromem (d, -offset);
  2819. d -= offset;
  2820. num += offset;
  2821. offset = 0;
  2822. }
  2823. if (offset + num > size)
  2824. {
  2825. const size_t newNum = size - offset;
  2826. zeromem (d + newNum, num - newNum);
  2827. num = newNum;
  2828. }
  2829. if (num > 0)
  2830. memcpy (d, data + offset, num);
  2831. }
  2832. void MemoryBlock::removeSection (size_t startByte, size_t numBytesToRemove) throw()
  2833. {
  2834. if (startByte < 0)
  2835. {
  2836. numBytesToRemove += startByte;
  2837. startByte = 0;
  2838. }
  2839. if (startByte + numBytesToRemove >= size)
  2840. {
  2841. setSize (startByte);
  2842. }
  2843. else if (numBytesToRemove > 0)
  2844. {
  2845. memmove (data + startByte,
  2846. data + startByte + numBytesToRemove,
  2847. size - (startByte + numBytesToRemove));
  2848. setSize (size - numBytesToRemove);
  2849. }
  2850. }
  2851. const String MemoryBlock::toString() const throw()
  2852. {
  2853. return String (static_cast <const char*> (getData()), size);
  2854. }
  2855. int MemoryBlock::getBitRange (const size_t bitRangeStart, size_t numBits) const throw()
  2856. {
  2857. int res = 0;
  2858. size_t byte = bitRangeStart >> 3;
  2859. int offsetInByte = (int) bitRangeStart & 7;
  2860. size_t bitsSoFar = 0;
  2861. while (numBits > 0 && (size_t) byte < size)
  2862. {
  2863. const int bitsThisTime = jmin ((int) numBits, 8 - offsetInByte);
  2864. const int mask = (0xff >> (8 - bitsThisTime)) << offsetInByte;
  2865. res |= (((data[byte] & mask) >> offsetInByte) << bitsSoFar);
  2866. bitsSoFar += bitsThisTime;
  2867. numBits -= bitsThisTime;
  2868. ++byte;
  2869. offsetInByte = 0;
  2870. }
  2871. return res;
  2872. }
  2873. void MemoryBlock::setBitRange (const size_t bitRangeStart, size_t numBits, int bitsToSet) throw()
  2874. {
  2875. size_t byte = bitRangeStart >> 3;
  2876. int offsetInByte = (int) bitRangeStart & 7;
  2877. unsigned int mask = ~((((unsigned int) 0xffffffff) << (32 - numBits)) >> (32 - numBits));
  2878. while (numBits > 0 && (size_t) byte < size)
  2879. {
  2880. const int bitsThisTime = jmin ((int) numBits, 8 - offsetInByte);
  2881. const unsigned int tempMask = (mask << offsetInByte) | ~((((unsigned int) 0xffffffff) >> offsetInByte) << offsetInByte);
  2882. const unsigned int tempBits = bitsToSet << offsetInByte;
  2883. data[byte] = (char) ((data[byte] & tempMask) | tempBits);
  2884. ++byte;
  2885. numBits -= bitsThisTime;
  2886. bitsToSet >>= bitsThisTime;
  2887. mask >>= bitsThisTime;
  2888. offsetInByte = 0;
  2889. }
  2890. }
  2891. void MemoryBlock::loadFromHexString (const String& hex) throw()
  2892. {
  2893. ensureSize (hex.length() >> 1);
  2894. char* dest = data;
  2895. int i = 0;
  2896. for (;;)
  2897. {
  2898. int byte = 0;
  2899. for (int loop = 2; --loop >= 0;)
  2900. {
  2901. byte <<= 4;
  2902. for (;;)
  2903. {
  2904. const juce_wchar c = hex [i++];
  2905. if (c >= '0' && c <= '9')
  2906. {
  2907. byte |= c - '0';
  2908. break;
  2909. }
  2910. else if (c >= 'a' && c <= 'z')
  2911. {
  2912. byte |= c - ('a' - 10);
  2913. break;
  2914. }
  2915. else if (c >= 'A' && c <= 'Z')
  2916. {
  2917. byte |= c - ('A' - 10);
  2918. break;
  2919. }
  2920. else if (c == 0)
  2921. {
  2922. setSize (static_cast <size_t> (dest - data));
  2923. return;
  2924. }
  2925. }
  2926. }
  2927. *dest++ = (char) byte;
  2928. }
  2929. }
  2930. static const char* const encodingTable
  2931. = ".ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+";
  2932. const String MemoryBlock::toBase64Encoding() const throw()
  2933. {
  2934. const size_t numChars = ((size << 3) + 5) / 6;
  2935. String destString ((unsigned int) size); // store the length, followed by a '.', and then the data.
  2936. const int initialLen = destString.length();
  2937. destString.preallocateStorage (initialLen + 2 + numChars);
  2938. juce_wchar* d = destString;
  2939. d += initialLen;
  2940. *d++ = '.';
  2941. for (size_t i = 0; i < numChars; ++i)
  2942. *d++ = encodingTable [getBitRange (i * 6, 6)];
  2943. *d++ = 0;
  2944. return destString;
  2945. }
  2946. bool MemoryBlock::fromBase64Encoding (const String& s) throw()
  2947. {
  2948. const int startPos = s.indexOfChar ('.') + 1;
  2949. if (startPos <= 0)
  2950. return false;
  2951. const int numBytesNeeded = s.substring (0, startPos - 1).getIntValue();
  2952. setSize (numBytesNeeded, true);
  2953. const int numChars = s.length() - startPos;
  2954. const juce_wchar* srcChars = s;
  2955. srcChars += startPos;
  2956. int pos = 0;
  2957. for (int i = 0; i < numChars; ++i)
  2958. {
  2959. const char c = (char) srcChars[i];
  2960. for (int j = 0; j < 64; ++j)
  2961. {
  2962. if (encodingTable[j] == c)
  2963. {
  2964. setBitRange (pos, 6, j);
  2965. pos += 6;
  2966. break;
  2967. }
  2968. }
  2969. }
  2970. return true;
  2971. }
  2972. END_JUCE_NAMESPACE
  2973. /*** End of inlined file: juce_MemoryBlock.cpp ***/
  2974. /*** Start of inlined file: juce_PropertySet.cpp ***/
  2975. BEGIN_JUCE_NAMESPACE
  2976. PropertySet::PropertySet (const bool ignoreCaseOfKeyNames) throw()
  2977. : properties (ignoreCaseOfKeyNames),
  2978. fallbackProperties (0),
  2979. ignoreCaseOfKeys (ignoreCaseOfKeyNames)
  2980. {
  2981. }
  2982. PropertySet::PropertySet (const PropertySet& other) throw()
  2983. : properties (other.properties),
  2984. fallbackProperties (other.fallbackProperties),
  2985. ignoreCaseOfKeys (other.ignoreCaseOfKeys)
  2986. {
  2987. }
  2988. PropertySet& PropertySet::operator= (const PropertySet& other) throw()
  2989. {
  2990. properties = other.properties;
  2991. fallbackProperties = other.fallbackProperties;
  2992. ignoreCaseOfKeys = other.ignoreCaseOfKeys;
  2993. propertyChanged();
  2994. return *this;
  2995. }
  2996. PropertySet::~PropertySet()
  2997. {
  2998. }
  2999. void PropertySet::clear()
  3000. {
  3001. const ScopedLock sl (lock);
  3002. if (properties.size() > 0)
  3003. {
  3004. properties.clear();
  3005. propertyChanged();
  3006. }
  3007. }
  3008. const String PropertySet::getValue (const String& keyName,
  3009. const String& defaultValue) const throw()
  3010. {
  3011. const ScopedLock sl (lock);
  3012. const int index = properties.getAllKeys().indexOf (keyName, ignoreCaseOfKeys);
  3013. if (index >= 0)
  3014. return properties.getAllValues() [index];
  3015. return fallbackProperties != 0 ? fallbackProperties->getValue (keyName, defaultValue)
  3016. : defaultValue;
  3017. }
  3018. int PropertySet::getIntValue (const String& keyName,
  3019. const int defaultValue) const throw()
  3020. {
  3021. const ScopedLock sl (lock);
  3022. const int index = properties.getAllKeys().indexOf (keyName, ignoreCaseOfKeys);
  3023. if (index >= 0)
  3024. return properties.getAllValues() [index].getIntValue();
  3025. return fallbackProperties != 0 ? fallbackProperties->getIntValue (keyName, defaultValue)
  3026. : defaultValue;
  3027. }
  3028. double PropertySet::getDoubleValue (const String& keyName,
  3029. const double defaultValue) const throw()
  3030. {
  3031. const ScopedLock sl (lock);
  3032. const int index = properties.getAllKeys().indexOf (keyName, ignoreCaseOfKeys);
  3033. if (index >= 0)
  3034. return properties.getAllValues()[index].getDoubleValue();
  3035. return fallbackProperties != 0 ? fallbackProperties->getDoubleValue (keyName, defaultValue)
  3036. : defaultValue;
  3037. }
  3038. bool PropertySet::getBoolValue (const String& keyName,
  3039. const bool defaultValue) const throw()
  3040. {
  3041. const ScopedLock sl (lock);
  3042. const int index = properties.getAllKeys().indexOf (keyName, ignoreCaseOfKeys);
  3043. if (index >= 0)
  3044. return properties.getAllValues() [index].getIntValue() != 0;
  3045. return fallbackProperties != 0 ? fallbackProperties->getBoolValue (keyName, defaultValue)
  3046. : defaultValue;
  3047. }
  3048. XmlElement* PropertySet::getXmlValue (const String& keyName) const
  3049. {
  3050. XmlDocument doc (getValue (keyName));
  3051. return doc.getDocumentElement();
  3052. }
  3053. void PropertySet::setValue (const String& keyName,
  3054. const String& value) throw()
  3055. {
  3056. jassert (keyName.isNotEmpty()); // shouldn't use an empty key name!
  3057. if (keyName.isNotEmpty())
  3058. {
  3059. const ScopedLock sl (lock);
  3060. const int index = properties.getAllKeys().indexOf (keyName, ignoreCaseOfKeys);
  3061. if (index < 0 || properties.getAllValues() [index] != value)
  3062. {
  3063. properties.set (keyName, value);
  3064. propertyChanged();
  3065. }
  3066. }
  3067. }
  3068. void PropertySet::removeValue (const String& keyName) throw()
  3069. {
  3070. if (keyName.isNotEmpty())
  3071. {
  3072. const ScopedLock sl (lock);
  3073. const int index = properties.getAllKeys().indexOf (keyName, ignoreCaseOfKeys);
  3074. if (index >= 0)
  3075. {
  3076. properties.remove (keyName);
  3077. propertyChanged();
  3078. }
  3079. }
  3080. }
  3081. void PropertySet::setValue (const String& keyName, const int value) throw()
  3082. {
  3083. setValue (keyName, String (value));
  3084. }
  3085. void PropertySet::setValue (const String& keyName, const double value) throw()
  3086. {
  3087. setValue (keyName, String (value));
  3088. }
  3089. void PropertySet::setValue (const String& keyName, const bool value) throw()
  3090. {
  3091. setValue (keyName, String (value ? "1" : "0"));
  3092. }
  3093. void PropertySet::setValue (const String& keyName, const XmlElement* const xml)
  3094. {
  3095. setValue (keyName, (xml == 0) ? String::empty
  3096. : xml->createDocument (String::empty, true));
  3097. }
  3098. bool PropertySet::containsKey (const String& keyName) const throw()
  3099. {
  3100. const ScopedLock sl (lock);
  3101. return properties.getAllKeys().contains (keyName, ignoreCaseOfKeys);
  3102. }
  3103. void PropertySet::setFallbackPropertySet (PropertySet* fallbackProperties_) throw()
  3104. {
  3105. const ScopedLock sl (lock);
  3106. fallbackProperties = fallbackProperties_;
  3107. }
  3108. XmlElement* PropertySet::createXml (const String& nodeName) const throw()
  3109. {
  3110. const ScopedLock sl (lock);
  3111. XmlElement* const xml = new XmlElement (nodeName);
  3112. for (int i = 0; i < properties.getAllKeys().size(); ++i)
  3113. {
  3114. XmlElement* const e = xml->createNewChildElement ("VALUE");
  3115. e->setAttribute ("name", properties.getAllKeys()[i]);
  3116. e->setAttribute ("val", properties.getAllValues()[i]);
  3117. }
  3118. return xml;
  3119. }
  3120. void PropertySet::restoreFromXml (const XmlElement& xml) throw()
  3121. {
  3122. const ScopedLock sl (lock);
  3123. clear();
  3124. forEachXmlChildElementWithTagName (xml, e, "VALUE")
  3125. {
  3126. if (e->hasAttribute ("name")
  3127. && e->hasAttribute ("val"))
  3128. {
  3129. properties.set (e->getStringAttribute ("name"),
  3130. e->getStringAttribute ("val"));
  3131. }
  3132. }
  3133. if (properties.size() > 0)
  3134. propertyChanged();
  3135. }
  3136. void PropertySet::propertyChanged()
  3137. {
  3138. }
  3139. END_JUCE_NAMESPACE
  3140. /*** End of inlined file: juce_PropertySet.cpp ***/
  3141. /*** Start of inlined file: juce_Variant.cpp ***/
  3142. BEGIN_JUCE_NAMESPACE
  3143. var::var() throw()
  3144. : type (voidType)
  3145. {
  3146. value.doubleValue = 0;
  3147. }
  3148. var::~var() throw()
  3149. {
  3150. if (type == stringType)
  3151. delete value.stringValue;
  3152. else if (type == objectType && value.objectValue != 0)
  3153. value.objectValue->decReferenceCount();
  3154. }
  3155. const var var::null;
  3156. var::var (const var& valueToCopy)
  3157. : type (valueToCopy.type),
  3158. value (valueToCopy.value)
  3159. {
  3160. if (type == stringType)
  3161. value.stringValue = new String (*(value.stringValue));
  3162. else if (type == objectType && value.objectValue != 0)
  3163. value.objectValue->incReferenceCount();
  3164. }
  3165. var::var (const int value_) throw()
  3166. : type (intType)
  3167. {
  3168. value.intValue = value_;
  3169. }
  3170. var::var (const bool value_) throw()
  3171. : type (boolType)
  3172. {
  3173. value.boolValue = value_;
  3174. }
  3175. var::var (const double value_) throw()
  3176. : type (doubleType)
  3177. {
  3178. value.doubleValue = value_;
  3179. }
  3180. var::var (const String& value_)
  3181. : type (stringType)
  3182. {
  3183. value.stringValue = new String (value_);
  3184. }
  3185. var::var (const char* const value_)
  3186. : type (stringType)
  3187. {
  3188. value.stringValue = new String (value_);
  3189. }
  3190. var::var (const juce_wchar* const value_)
  3191. : type (stringType)
  3192. {
  3193. value.stringValue = new String (value_);
  3194. }
  3195. var::var (DynamicObject* const object)
  3196. : type (objectType)
  3197. {
  3198. value.objectValue = object;
  3199. if (object != 0)
  3200. object->incReferenceCount();
  3201. }
  3202. var::var (MethodFunction method_) throw()
  3203. : type (methodType)
  3204. {
  3205. value.methodValue = method_;
  3206. }
  3207. void var::swapWith (var& other) throw()
  3208. {
  3209. swapVariables (type, other.type);
  3210. swapVariables (value, other.value);
  3211. }
  3212. var& var::operator= (const var& value_) { var newValue (value_); swapWith (newValue); return *this; }
  3213. var& var::operator= (int value_) { var newValue (value_); swapWith (newValue); return *this; }
  3214. var& var::operator= (bool value_) { var newValue (value_); swapWith (newValue); return *this; }
  3215. var& var::operator= (double value_) { var newValue (value_); swapWith (newValue); return *this; }
  3216. var& var::operator= (const char* value_) { var newValue (value_); swapWith (newValue); return *this; }
  3217. var& var::operator= (const juce_wchar* value_) { var newValue (value_); swapWith (newValue); return *this; }
  3218. var& var::operator= (const String& value_) { var newValue (value_); swapWith (newValue); return *this; }
  3219. var& var::operator= (DynamicObject* value_) { var newValue (value_); swapWith (newValue); return *this; }
  3220. var& var::operator= (MethodFunction value_) { var newValue (value_); swapWith (newValue); return *this; }
  3221. var::operator int() const
  3222. {
  3223. switch (type)
  3224. {
  3225. case voidType: break;
  3226. case intType: return value.intValue;
  3227. case boolType: return value.boolValue ? 1 : 0;
  3228. case doubleType: return static_cast <int> (value.doubleValue);
  3229. case stringType: return value.stringValue->getIntValue();
  3230. case objectType: break;
  3231. default: jassertfalse; break;
  3232. }
  3233. return 0;
  3234. }
  3235. var::operator bool() const
  3236. {
  3237. switch (type)
  3238. {
  3239. case voidType: break;
  3240. case intType: return value.intValue != 0;
  3241. case boolType: return value.boolValue;
  3242. case doubleType: return value.doubleValue != 0;
  3243. case stringType: return value.stringValue->getIntValue() != 0
  3244. || value.stringValue->trim().equalsIgnoreCase ("true")
  3245. || value.stringValue->trim().equalsIgnoreCase ("yes");
  3246. case objectType: return value.objectValue != 0;
  3247. default: jassertfalse; break;
  3248. }
  3249. return false;
  3250. }
  3251. var::operator float() const
  3252. {
  3253. return (float) operator double();
  3254. }
  3255. var::operator double() const
  3256. {
  3257. switch (type)
  3258. {
  3259. case voidType: break;
  3260. case intType: return value.intValue;
  3261. case boolType: return value.boolValue ? 1.0 : 0.0;
  3262. case doubleType: return value.doubleValue;
  3263. case stringType: return value.stringValue->getDoubleValue();
  3264. case objectType: break;
  3265. default: jassertfalse; break;
  3266. }
  3267. return 0.0;
  3268. }
  3269. const String var::toString() const
  3270. {
  3271. switch (type)
  3272. {
  3273. case voidType: return String::empty;
  3274. case intType: return String (value.intValue);
  3275. case boolType: return String::charToString (value.boolValue ? '1' : '0');
  3276. case doubleType: return String (value.doubleValue);
  3277. case stringType: return *(value.stringValue);
  3278. case objectType: return "Object 0x" + String::toHexString ((int) (pointer_sized_int) value.objectValue);
  3279. case methodType: return "Method";
  3280. default: jassertfalse; break;
  3281. }
  3282. return String::empty;
  3283. }
  3284. var::operator const String() const
  3285. {
  3286. return toString();
  3287. }
  3288. DynamicObject* var::getObject() const
  3289. {
  3290. return type == objectType ? value.objectValue : 0;
  3291. }
  3292. bool var::equals (const var& other) const throw()
  3293. {
  3294. switch (type)
  3295. {
  3296. case voidType: return other.isVoid();
  3297. case intType: return value.intValue == static_cast <int> (other);
  3298. case boolType: return value.boolValue == static_cast <bool> (other);
  3299. case doubleType: return value.doubleValue == static_cast <double> (other);
  3300. case stringType: return (*(value.stringValue)) == other.toString();
  3301. case objectType: return value.objectValue == other.getObject();
  3302. case methodType: return value.methodValue == other.value.methodValue && other.isMethod();
  3303. default: jassertfalse; break;
  3304. }
  3305. return false;
  3306. }
  3307. bool operator== (const var& v1, const var& v2) throw() { return v1.equals (v2); }
  3308. bool operator!= (const var& v1, const var& v2) throw() { return ! v1.equals (v2); }
  3309. bool operator== (const var& v1, const String& v2) throw() { return v1.toString() == v2; }
  3310. bool operator!= (const var& v1, const String& v2) throw() { return v1.toString() != v2; }
  3311. void var::writeToStream (OutputStream& output) const
  3312. {
  3313. switch (type)
  3314. {
  3315. case voidType: output.writeCompressedInt (0); break;
  3316. case intType: output.writeCompressedInt (5); output.writeByte (1); output.writeInt (value.intValue); break;
  3317. case boolType: output.writeCompressedInt (1); output.writeByte (value.boolValue ? 2 : 3); break;
  3318. case doubleType: output.writeCompressedInt (9); output.writeByte (4); output.writeDouble (value.doubleValue); break;
  3319. case stringType:
  3320. {
  3321. const int len = value.stringValue->getNumBytesAsUTF8() + 1;
  3322. output.writeCompressedInt (len + 1);
  3323. output.writeByte (5);
  3324. HeapBlock<char> temp (len);
  3325. value.stringValue->copyToUTF8 (temp, len);
  3326. output.write (temp, len);
  3327. break;
  3328. }
  3329. case objectType:
  3330. case methodType: output.writeCompressedInt (0); jassertfalse; break; // Can't write an object to a stream!
  3331. default: jassertfalse; break; // Is this a corrupted object?
  3332. }
  3333. }
  3334. const var var::readFromStream (InputStream& input)
  3335. {
  3336. const int numBytes = input.readCompressedInt();
  3337. if (numBytes > 0)
  3338. {
  3339. switch (input.readByte())
  3340. {
  3341. case 1: return var (input.readInt());
  3342. case 2: return var (true);
  3343. case 3: return var (false);
  3344. case 4: return var (input.readDouble());
  3345. case 5:
  3346. {
  3347. MemoryBlock mb;
  3348. input.readIntoMemoryBlock (mb, numBytes - 1);
  3349. return var (String::fromUTF8 (static_cast <const char*> (mb.getData()), (int) mb.getSize()));
  3350. }
  3351. default: input.skipNextBytes (numBytes - 1); break;
  3352. }
  3353. }
  3354. return var::null;
  3355. }
  3356. const var var::operator[] (const var::identifier& propertyName) const
  3357. {
  3358. if (type == objectType && value.objectValue != 0)
  3359. return value.objectValue->getProperty (propertyName);
  3360. return var::null;
  3361. }
  3362. const var var::invoke (const var::identifier& method, const var* arguments, int numArguments) const
  3363. {
  3364. if (type == objectType && value.objectValue != 0)
  3365. return value.objectValue->invokeMethod (method, arguments, numArguments);
  3366. return var::null;
  3367. }
  3368. const var var::invoke (const var& targetObject, const var* arguments, int numArguments) const
  3369. {
  3370. if (isMethod())
  3371. {
  3372. DynamicObject* const target = targetObject.getObject();
  3373. if (target != 0)
  3374. return (target->*(value.methodValue)) (arguments, numArguments);
  3375. }
  3376. return var::null;
  3377. }
  3378. const var var::call (const var::identifier& method) const
  3379. {
  3380. return invoke (method, 0, 0);
  3381. }
  3382. const var var::call (const var::identifier& method, const var& arg1) const
  3383. {
  3384. return invoke (method, &arg1, 1);
  3385. }
  3386. const var var::call (const var::identifier& method, const var& arg1, const var& arg2) const
  3387. {
  3388. var args[] = { arg1, arg2 };
  3389. return invoke (method, args, 2);
  3390. }
  3391. const var var::call (const var::identifier& method, const var& arg1, const var& arg2, const var& arg3)
  3392. {
  3393. var args[] = { arg1, arg2, arg3 };
  3394. return invoke (method, args, 3);
  3395. }
  3396. const var var::call (const var::identifier& method, const var& arg1, const var& arg2, const var& arg3, const var& arg4) const
  3397. {
  3398. var args[] = { arg1, arg2, arg3, arg4 };
  3399. return invoke (method, args, 4);
  3400. }
  3401. const var var::call (const var::identifier& method, const var& arg1, const var& arg2, const var& arg3, const var& arg4, const var& arg5) const
  3402. {
  3403. var args[] = { arg1, arg2, arg3, arg4, arg5 };
  3404. return invoke (method, args, 5);
  3405. }
  3406. var::identifier::identifier() throw()
  3407. : hashCode (0)
  3408. {
  3409. }
  3410. var::identifier::identifier (const String& name_)
  3411. : name (name_),
  3412. hashCode (name_.hashCode())
  3413. {
  3414. /* An identifier string must be suitable for use as a script variable or XML
  3415. attribute, so it can only contain this limited set of characters.. */
  3416. jassert (name.containsOnly ("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_") && name.isNotEmpty());
  3417. }
  3418. var::identifier::identifier (const char* const name_)
  3419. : name (name_),
  3420. hashCode (name.hashCode())
  3421. {
  3422. /* An identifier string must be suitable for use as a script variable or XML
  3423. attribute, so it can only contain this limited set of characters.. */
  3424. jassert (name.containsOnly ("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_") && name.isNotEmpty());
  3425. }
  3426. var::identifier::~identifier()
  3427. {
  3428. }
  3429. END_JUCE_NAMESPACE
  3430. /*** End of inlined file: juce_Variant.cpp ***/
  3431. /*** Start of inlined file: juce_NamedValueSet.cpp ***/
  3432. BEGIN_JUCE_NAMESPACE
  3433. NamedValueSet::NamedValue::NamedValue() throw()
  3434. {
  3435. }
  3436. inline NamedValueSet::NamedValue::NamedValue (const var::identifier& name_, const var& value_)
  3437. : name (name_), value (value_)
  3438. {
  3439. }
  3440. NamedValueSet::NamedValueSet() throw()
  3441. {
  3442. }
  3443. NamedValueSet::NamedValueSet (const NamedValueSet& other)
  3444. : values (other.values)
  3445. {
  3446. }
  3447. NamedValueSet& NamedValueSet::operator= (const NamedValueSet& other)
  3448. {
  3449. values = other.values;
  3450. return *this;
  3451. }
  3452. NamedValueSet::~NamedValueSet()
  3453. {
  3454. }
  3455. int NamedValueSet::size() const throw()
  3456. {
  3457. return values.size();
  3458. }
  3459. const var& NamedValueSet::operator[] (const var::identifier& name) const
  3460. {
  3461. for (int i = values.size(); --i >= 0;)
  3462. {
  3463. const NamedValue& v = values.getReference(i);
  3464. if (v.name == name)
  3465. return v.value;
  3466. }
  3467. return var::null;
  3468. }
  3469. const var NamedValueSet::getWithDefault (const var::identifier& name, const var& defaultReturnValue) const
  3470. {
  3471. const var* v = getItem (name);
  3472. return v != 0 ? *v : defaultReturnValue;
  3473. }
  3474. var* NamedValueSet::getItem (const var::identifier& name) const
  3475. {
  3476. for (int i = values.size(); --i >= 0;)
  3477. {
  3478. NamedValue& v = values.getReference(i);
  3479. if (v.name == name)
  3480. return &(v.value);
  3481. }
  3482. return 0;
  3483. }
  3484. bool NamedValueSet::set (const var::identifier& name, const var& newValue)
  3485. {
  3486. for (int i = values.size(); --i >= 0;)
  3487. {
  3488. NamedValue& v = values.getReference(i);
  3489. if (v.name == name)
  3490. {
  3491. if (v.value == newValue)
  3492. return false;
  3493. v.value = newValue;
  3494. return true;
  3495. }
  3496. }
  3497. values.add (NamedValue (name, newValue));
  3498. return true;
  3499. }
  3500. bool NamedValueSet::contains (const var::identifier& name) const
  3501. {
  3502. return getItem (name) != 0;
  3503. }
  3504. bool NamedValueSet::remove (const var::identifier& name)
  3505. {
  3506. for (int i = values.size(); --i >= 0;)
  3507. {
  3508. if (values.getReference(i).name == name)
  3509. {
  3510. values.remove (i);
  3511. return true;
  3512. }
  3513. }
  3514. return false;
  3515. }
  3516. const var::identifier NamedValueSet::getName (int index) const
  3517. {
  3518. jassert (((unsigned int) index) < (unsigned int) values.size());
  3519. return values [index].name;
  3520. }
  3521. void NamedValueSet::clear()
  3522. {
  3523. values.clear();
  3524. }
  3525. END_JUCE_NAMESPACE
  3526. /*** End of inlined file: juce_NamedValueSet.cpp ***/
  3527. /*** Start of inlined file: juce_DynamicObject.cpp ***/
  3528. BEGIN_JUCE_NAMESPACE
  3529. DynamicObject::DynamicObject()
  3530. {
  3531. }
  3532. DynamicObject::~DynamicObject()
  3533. {
  3534. }
  3535. bool DynamicObject::hasProperty (const var::identifier& propertyName) const
  3536. {
  3537. var* const v = properties.getItem (propertyName);
  3538. return v != 0 && ! v->isMethod();
  3539. }
  3540. const var DynamicObject::getProperty (const var::identifier& propertyName) const
  3541. {
  3542. return properties [propertyName];
  3543. }
  3544. void DynamicObject::setProperty (const var::identifier& propertyName, const var& newValue)
  3545. {
  3546. properties.set (propertyName, newValue);
  3547. }
  3548. void DynamicObject::removeProperty (const var::identifier& propertyName)
  3549. {
  3550. properties.remove (propertyName);
  3551. }
  3552. bool DynamicObject::hasMethod (const var::identifier& methodName) const
  3553. {
  3554. return getProperty (methodName).isMethod();
  3555. }
  3556. const var DynamicObject::invokeMethod (const var::identifier& methodName,
  3557. const var* parameters,
  3558. int numParameters)
  3559. {
  3560. return properties [methodName].invoke (var (this), parameters, numParameters);
  3561. }
  3562. void DynamicObject::setMethod (const var::identifier& name,
  3563. var::MethodFunction methodFunction)
  3564. {
  3565. properties.set (name, var (methodFunction));
  3566. }
  3567. void DynamicObject::clear()
  3568. {
  3569. properties.clear();
  3570. }
  3571. END_JUCE_NAMESPACE
  3572. /*** End of inlined file: juce_DynamicObject.cpp ***/
  3573. /*** Start of inlined file: juce_BlowFish.cpp ***/
  3574. BEGIN_JUCE_NAMESPACE
  3575. BlowFish::BlowFish (const void* const keyData, const int keyBytes)
  3576. {
  3577. jassert (keyData != 0);
  3578. jassert (keyBytes > 0);
  3579. static const uint32 initialPValues [18] =
  3580. {
  3581. 0x243f6a88, 0x85a308d3, 0x13198a2e, 0x03707344, 0xa4093822, 0x299f31d0, 0x082efa98, 0xec4e6c89,
  3582. 0x452821e6, 0x38d01377, 0xbe5466cf, 0x34e90c6c, 0xc0ac29b7, 0xc97c50dd, 0x3f84d5b5, 0xb5470917,
  3583. 0x9216d5d9, 0x8979fb1b
  3584. };
  3585. static const uint32 initialSValues [4 * 256] =
  3586. {
  3587. 0xd1310ba6, 0x98dfb5ac, 0x2ffd72db, 0xd01adfb7, 0xb8e1afed, 0x6a267e96, 0xba7c9045, 0xf12c7f99,
  3588. 0x24a19947, 0xb3916cf7, 0x0801f2e2, 0x858efc16, 0x636920d8, 0x71574e69, 0xa458fea3, 0xf4933d7e,
  3589. 0x0d95748f, 0x728eb658, 0x718bcd58, 0x82154aee, 0x7b54a41d, 0xc25a59b5, 0x9c30d539, 0x2af26013,
  3590. 0xc5d1b023, 0x286085f0, 0xca417918, 0xb8db38ef, 0x8e79dcb0, 0x603a180e, 0x6c9e0e8b, 0xb01e8a3e,
  3591. 0xd71577c1, 0xbd314b27, 0x78af2fda, 0x55605c60, 0xe65525f3, 0xaa55ab94, 0x57489862, 0x63e81440,
  3592. 0x55ca396a, 0x2aab10b6, 0xb4cc5c34, 0x1141e8ce, 0xa15486af, 0x7c72e993, 0xb3ee1411, 0x636fbc2a,
  3593. 0x2ba9c55d, 0x741831f6, 0xce5c3e16, 0x9b87931e, 0xafd6ba33, 0x6c24cf5c, 0x7a325381, 0x28958677,
  3594. 0x3b8f4898, 0x6b4bb9af, 0xc4bfe81b, 0x66282193, 0x61d809cc, 0xfb21a991, 0x487cac60, 0x5dec8032,
  3595. 0xef845d5d, 0xe98575b1, 0xdc262302, 0xeb651b88, 0x23893e81, 0xd396acc5, 0x0f6d6ff3, 0x83f44239,
  3596. 0x2e0b4482, 0xa4842004, 0x69c8f04a, 0x9e1f9b5e, 0x21c66842, 0xf6e96c9a, 0x670c9c61, 0xabd388f0,
  3597. 0x6a51a0d2, 0xd8542f68, 0x960fa728, 0xab5133a3, 0x6eef0b6c, 0x137a3be4, 0xba3bf050, 0x7efb2a98,
  3598. 0xa1f1651d, 0x39af0176, 0x66ca593e, 0x82430e88, 0x8cee8619, 0x456f9fb4, 0x7d84a5c3, 0x3b8b5ebe,
  3599. 0xe06f75d8, 0x85c12073, 0x401a449f, 0x56c16aa6, 0x4ed3aa62, 0x363f7706, 0x1bfedf72, 0x429b023d,
  3600. 0x37d0d724, 0xd00a1248, 0xdb0fead3, 0x49f1c09b, 0x075372c9, 0x80991b7b, 0x25d479d8, 0xf6e8def7,
  3601. 0xe3fe501a, 0xb6794c3b, 0x976ce0bd, 0x04c006ba, 0xc1a94fb6, 0x409f60c4, 0x5e5c9ec2, 0x196a2463,
  3602. 0x68fb6faf, 0x3e6c53b5, 0x1339b2eb, 0x3b52ec6f, 0x6dfc511f, 0x9b30952c, 0xcc814544, 0xaf5ebd09,
  3603. 0xbee3d004, 0xde334afd, 0x660f2807, 0x192e4bb3, 0xc0cba857, 0x45c8740f, 0xd20b5f39, 0xb9d3fbdb,
  3604. 0x5579c0bd, 0x1a60320a, 0xd6a100c6, 0x402c7279, 0x679f25fe, 0xfb1fa3cc, 0x8ea5e9f8, 0xdb3222f8,
  3605. 0x3c7516df, 0xfd616b15, 0x2f501ec8, 0xad0552ab, 0x323db5fa, 0xfd238760, 0x53317b48, 0x3e00df82,
  3606. 0x9e5c57bb, 0xca6f8ca0, 0x1a87562e, 0xdf1769db, 0xd542a8f6, 0x287effc3, 0xac6732c6, 0x8c4f5573,
  3607. 0x695b27b0, 0xbbca58c8, 0xe1ffa35d, 0xb8f011a0, 0x10fa3d98, 0xfd2183b8, 0x4afcb56c, 0x2dd1d35b,
  3608. 0x9a53e479, 0xb6f84565, 0xd28e49bc, 0x4bfb9790, 0xe1ddf2da, 0xa4cb7e33, 0x62fb1341, 0xcee4c6e8,
  3609. 0xef20cada, 0x36774c01, 0xd07e9efe, 0x2bf11fb4, 0x95dbda4d, 0xae909198, 0xeaad8e71, 0x6b93d5a0,
  3610. 0xd08ed1d0, 0xafc725e0, 0x8e3c5b2f, 0x8e7594b7, 0x8ff6e2fb, 0xf2122b64, 0x8888b812, 0x900df01c,
  3611. 0x4fad5ea0, 0x688fc31c, 0xd1cff191, 0xb3a8c1ad, 0x2f2f2218, 0xbe0e1777, 0xea752dfe, 0x8b021fa1,
  3612. 0xe5a0cc0f, 0xb56f74e8, 0x18acf3d6, 0xce89e299, 0xb4a84fe0, 0xfd13e0b7, 0x7cc43b81, 0xd2ada8d9,
  3613. 0x165fa266, 0x80957705, 0x93cc7314, 0x211a1477, 0xe6ad2065, 0x77b5fa86, 0xc75442f5, 0xfb9d35cf,
  3614. 0xebcdaf0c, 0x7b3e89a0, 0xd6411bd3, 0xae1e7e49, 0x00250e2d, 0x2071b35e, 0x226800bb, 0x57b8e0af,
  3615. 0x2464369b, 0xf009b91e, 0x5563911d, 0x59dfa6aa, 0x78c14389, 0xd95a537f, 0x207d5ba2, 0x02e5b9c5,
  3616. 0x83260376, 0x6295cfa9, 0x11c81968, 0x4e734a41, 0xb3472dca, 0x7b14a94a, 0x1b510052, 0x9a532915,
  3617. 0xd60f573f, 0xbc9bc6e4, 0x2b60a476, 0x81e67400, 0x08ba6fb5, 0x571be91f, 0xf296ec6b, 0x2a0dd915,
  3618. 0xb6636521, 0xe7b9f9b6, 0xff34052e, 0xc5855664, 0x53b02d5d, 0xa99f8fa1, 0x08ba4799, 0x6e85076a,
  3619. 0x4b7a70e9, 0xb5b32944, 0xdb75092e, 0xc4192623, 0xad6ea6b0, 0x49a7df7d, 0x9cee60b8, 0x8fedb266,
  3620. 0xecaa8c71, 0x699a17ff, 0x5664526c, 0xc2b19ee1, 0x193602a5, 0x75094c29, 0xa0591340, 0xe4183a3e,
  3621. 0x3f54989a, 0x5b429d65, 0x6b8fe4d6, 0x99f73fd6, 0xa1d29c07, 0xefe830f5, 0x4d2d38e6, 0xf0255dc1,
  3622. 0x4cdd2086, 0x8470eb26, 0x6382e9c6, 0x021ecc5e, 0x09686b3f, 0x3ebaefc9, 0x3c971814, 0x6b6a70a1,
  3623. 0x687f3584, 0x52a0e286, 0xb79c5305, 0xaa500737, 0x3e07841c, 0x7fdeae5c, 0x8e7d44ec, 0x5716f2b8,
  3624. 0xb03ada37, 0xf0500c0d, 0xf01c1f04, 0x0200b3ff, 0xae0cf51a, 0x3cb574b2, 0x25837a58, 0xdc0921bd,
  3625. 0xd19113f9, 0x7ca92ff6, 0x94324773, 0x22f54701, 0x3ae5e581, 0x37c2dadc, 0xc8b57634, 0x9af3dda7,
  3626. 0xa9446146, 0x0fd0030e, 0xecc8c73e, 0xa4751e41, 0xe238cd99, 0x3bea0e2f, 0x3280bba1, 0x183eb331,
  3627. 0x4e548b38, 0x4f6db908, 0x6f420d03, 0xf60a04bf, 0x2cb81290, 0x24977c79, 0x5679b072, 0xbcaf89af,
  3628. 0xde9a771f, 0xd9930810, 0xb38bae12, 0xdccf3f2e, 0x5512721f, 0x2e6b7124, 0x501adde6, 0x9f84cd87,
  3629. 0x7a584718, 0x7408da17, 0xbc9f9abc, 0xe94b7d8c, 0xec7aec3a, 0xdb851dfa, 0x63094366, 0xc464c3d2,
  3630. 0xef1c1847, 0x3215d908, 0xdd433b37, 0x24c2ba16, 0x12a14d43, 0x2a65c451, 0x50940002, 0x133ae4dd,
  3631. 0x71dff89e, 0x10314e55, 0x81ac77d6, 0x5f11199b, 0x043556f1, 0xd7a3c76b, 0x3c11183b, 0x5924a509,
  3632. 0xf28fe6ed, 0x97f1fbfa, 0x9ebabf2c, 0x1e153c6e, 0x86e34570, 0xeae96fb1, 0x860e5e0a, 0x5a3e2ab3,
  3633. 0x771fe71c, 0x4e3d06fa, 0x2965dcb9, 0x99e71d0f, 0x803e89d6, 0x5266c825, 0x2e4cc978, 0x9c10b36a,
  3634. 0xc6150eba, 0x94e2ea78, 0xa5fc3c53, 0x1e0a2df4, 0xf2f74ea7, 0x361d2b3d, 0x1939260f, 0x19c27960,
  3635. 0x5223a708, 0xf71312b6, 0xebadfe6e, 0xeac31f66, 0xe3bc4595, 0xa67bc883, 0xb17f37d1, 0x018cff28,
  3636. 0xc332ddef, 0xbe6c5aa5, 0x65582185, 0x68ab9802, 0xeecea50f, 0xdb2f953b, 0x2aef7dad, 0x5b6e2f84,
  3637. 0x1521b628, 0x29076170, 0xecdd4775, 0x619f1510, 0x13cca830, 0xeb61bd96, 0x0334fe1e, 0xaa0363cf,
  3638. 0xb5735c90, 0x4c70a239, 0xd59e9e0b, 0xcbaade14, 0xeecc86bc, 0x60622ca7, 0x9cab5cab, 0xb2f3846e,
  3639. 0x648b1eaf, 0x19bdf0ca, 0xa02369b9, 0x655abb50, 0x40685a32, 0x3c2ab4b3, 0x319ee9d5, 0xc021b8f7,
  3640. 0x9b540b19, 0x875fa099, 0x95f7997e, 0x623d7da8, 0xf837889a, 0x97e32d77, 0x11ed935f, 0x16681281,
  3641. 0x0e358829, 0xc7e61fd6, 0x96dedfa1, 0x7858ba99, 0x57f584a5, 0x1b227263, 0x9b83c3ff, 0x1ac24696,
  3642. 0xcdb30aeb, 0x532e3054, 0x8fd948e4, 0x6dbc3128, 0x58ebf2ef, 0x34c6ffea, 0xfe28ed61, 0xee7c3c73,
  3643. 0x5d4a14d9, 0xe864b7e3, 0x42105d14, 0x203e13e0, 0x45eee2b6, 0xa3aaabea, 0xdb6c4f15, 0xfacb4fd0,
  3644. 0xc742f442, 0xef6abbb5, 0x654f3b1d, 0x41cd2105, 0xd81e799e, 0x86854dc7, 0xe44b476a, 0x3d816250,
  3645. 0xcf62a1f2, 0x5b8d2646, 0xfc8883a0, 0xc1c7b6a3, 0x7f1524c3, 0x69cb7492, 0x47848a0b, 0x5692b285,
  3646. 0x095bbf00, 0xad19489d, 0x1462b174, 0x23820e00, 0x58428d2a, 0x0c55f5ea, 0x1dadf43e, 0x233f7061,
  3647. 0x3372f092, 0x8d937e41, 0xd65fecf1, 0x6c223bdb, 0x7cde3759, 0xcbee7460, 0x4085f2a7, 0xce77326e,
  3648. 0xa6078084, 0x19f8509e, 0xe8efd855, 0x61d99735, 0xa969a7aa, 0xc50c06c2, 0x5a04abfc, 0x800bcadc,
  3649. 0x9e447a2e, 0xc3453484, 0xfdd56705, 0x0e1e9ec9, 0xdb73dbd3, 0x105588cd, 0x675fda79, 0xe3674340,
  3650. 0xc5c43465, 0x713e38d8, 0x3d28f89e, 0xf16dff20, 0x153e21e7, 0x8fb03d4a, 0xe6e39f2b, 0xdb83adf7,
  3651. 0xe93d5a68, 0x948140f7, 0xf64c261c, 0x94692934, 0x411520f7, 0x7602d4f7, 0xbcf46b2e, 0xd4a20068,
  3652. 0xd4082471, 0x3320f46a, 0x43b7d4b7, 0x500061af, 0x1e39f62e, 0x97244546, 0x14214f74, 0xbf8b8840,
  3653. 0x4d95fc1d, 0x96b591af, 0x70f4ddd3, 0x66a02f45, 0xbfbc09ec, 0x03bd9785, 0x7fac6dd0, 0x31cb8504,
  3654. 0x96eb27b3, 0x55fd3941, 0xda2547e6, 0xabca0a9a, 0x28507825, 0x530429f4, 0x0a2c86da, 0xe9b66dfb,
  3655. 0x68dc1462, 0xd7486900, 0x680ec0a4, 0x27a18dee, 0x4f3ffea2, 0xe887ad8c, 0xb58ce006, 0x7af4d6b6,
  3656. 0xaace1e7c, 0xd3375fec, 0xce78a399, 0x406b2a42, 0x20fe9e35, 0xd9f385b9, 0xee39d7ab, 0x3b124e8b,
  3657. 0x1dc9faf7, 0x4b6d1856, 0x26a36631, 0xeae397b2, 0x3a6efa74, 0xdd5b4332, 0x6841e7f7, 0xca7820fb,
  3658. 0xfb0af54e, 0xd8feb397, 0x454056ac, 0xba489527, 0x55533a3a, 0x20838d87, 0xfe6ba9b7, 0xd096954b,
  3659. 0x55a867bc, 0xa1159a58, 0xcca92963, 0x99e1db33, 0xa62a4a56, 0x3f3125f9, 0x5ef47e1c, 0x9029317c,
  3660. 0xfdf8e802, 0x04272f70, 0x80bb155c, 0x05282ce3, 0x95c11548, 0xe4c66d22, 0x48c1133f, 0xc70f86dc,
  3661. 0x07f9c9ee, 0x41041f0f, 0x404779a4, 0x5d886e17, 0x325f51eb, 0xd59bc0d1, 0xf2bcc18f, 0x41113564,
  3662. 0x257b7834, 0x602a9c60, 0xdff8e8a3, 0x1f636c1b, 0x0e12b4c2, 0x02e1329e, 0xaf664fd1, 0xcad18115,
  3663. 0x6b2395e0, 0x333e92e1, 0x3b240b62, 0xeebeb922, 0x85b2a20e, 0xe6ba0d99, 0xde720c8c, 0x2da2f728,
  3664. 0xd0127845, 0x95b794fd, 0x647d0862, 0xe7ccf5f0, 0x5449a36f, 0x877d48fa, 0xc39dfd27, 0xf33e8d1e,
  3665. 0x0a476341, 0x992eff74, 0x3a6f6eab, 0xf4f8fd37, 0xa812dc60, 0xa1ebddf8, 0x991be14c, 0xdb6e6b0d,
  3666. 0xc67b5510, 0x6d672c37, 0x2765d43b, 0xdcd0e804, 0xf1290dc7, 0xcc00ffa3, 0xb5390f92, 0x690fed0b,
  3667. 0x667b9ffb, 0xcedb7d9c, 0xa091cf0b, 0xd9155ea3, 0xbb132f88, 0x515bad24, 0x7b9479bf, 0x763bd6eb,
  3668. 0x37392eb3, 0xcc115979, 0x8026e297, 0xf42e312d, 0x6842ada7, 0xc66a2b3b, 0x12754ccc, 0x782ef11c,
  3669. 0x6a124237, 0xb79251e7, 0x06a1bbe6, 0x4bfb6350, 0x1a6b1018, 0x11caedfa, 0x3d25bdd8, 0xe2e1c3c9,
  3670. 0x44421659, 0x0a121386, 0xd90cec6e, 0xd5abea2a, 0x64af674e, 0xda86a85f, 0xbebfe988, 0x64e4c3fe,
  3671. 0x9dbc8057, 0xf0f7c086, 0x60787bf8, 0x6003604d, 0xd1fd8346, 0xf6381fb0, 0x7745ae04, 0xd736fccc,
  3672. 0x83426b33, 0xf01eab71, 0xb0804187, 0x3c005e5f, 0x77a057be, 0xbde8ae24, 0x55464299, 0xbf582e61,
  3673. 0x4e58f48f, 0xf2ddfda2, 0xf474ef38, 0x8789bdc2, 0x5366f9c3, 0xc8b38e74, 0xb475f255, 0x46fcd9b9,
  3674. 0x7aeb2661, 0x8b1ddf84, 0x846a0e79, 0x915f95e2, 0x466e598e, 0x20b45770, 0x8cd55591, 0xc902de4c,
  3675. 0xb90bace1, 0xbb8205d0, 0x11a86248, 0x7574a99e, 0xb77f19b6, 0xe0a9dc09, 0x662d09a1, 0xc4324633,
  3676. 0xe85a1f02, 0x09f0be8c, 0x4a99a025, 0x1d6efe10, 0x1ab93d1d, 0x0ba5a4df, 0xa186f20f, 0x2868f169,
  3677. 0xdcb7da83, 0x573906fe, 0xa1e2ce9b, 0x4fcd7f52, 0x50115e01, 0xa70683fa, 0xa002b5c4, 0x0de6d027,
  3678. 0x9af88c27, 0x773f8641, 0xc3604c06, 0x61a806b5, 0xf0177a28, 0xc0f586e0, 0x006058aa, 0x30dc7d62,
  3679. 0x11e69ed7, 0x2338ea63, 0x53c2dd94, 0xc2c21634, 0xbbcbee56, 0x90bcb6de, 0xebfc7da1, 0xce591d76,
  3680. 0x6f05e409, 0x4b7c0188, 0x39720a3d, 0x7c927c24, 0x86e3725f, 0x724d9db9, 0x1ac15bb4, 0xd39eb8fc,
  3681. 0xed545578, 0x08fca5b5, 0xd83d7cd3, 0x4dad0fc4, 0x1e50ef5e, 0xb161e6f8, 0xa28514d9, 0x6c51133c,
  3682. 0x6fd5c7e7, 0x56e14ec4, 0x362abfce, 0xddc6c837, 0xd79a3234, 0x92638212, 0x670efa8e, 0x406000e0,
  3683. 0x3a39ce37, 0xd3faf5cf, 0xabc27737, 0x5ac52d1b, 0x5cb0679e, 0x4fa33742, 0xd3822740, 0x99bc9bbe,
  3684. 0xd5118e9d, 0xbf0f7315, 0xd62d1c7e, 0xc700c47b, 0xb78c1b6b, 0x21a19045, 0xb26eb1be, 0x6a366eb4,
  3685. 0x5748ab2f, 0xbc946e79, 0xc6a376d2, 0x6549c2c8, 0x530ff8ee, 0x468dde7d, 0xd5730a1d, 0x4cd04dc6,
  3686. 0x2939bbdb, 0xa9ba4650, 0xac9526e8, 0xbe5ee304, 0xa1fad5f0, 0x6a2d519a, 0x63ef8ce2, 0x9a86ee22,
  3687. 0xc089c2b8, 0x43242ef6, 0xa51e03aa, 0x9cf2d0a4, 0x83c061ba, 0x9be96a4d, 0x8fe51550, 0xba645bd6,
  3688. 0x2826a2f9, 0xa73a3ae1, 0x4ba99586, 0xef5562e9, 0xc72fefd3, 0xf752f7da, 0x3f046f69, 0x77fa0a59,
  3689. 0x80e4a915, 0x87b08601, 0x9b09e6ad, 0x3b3ee593, 0xe990fd5a, 0x9e34d797, 0x2cf0b7d9, 0x022b8b51,
  3690. 0x96d5ac3a, 0x017da67d, 0xd1cf3ed6, 0x7c7d2d28, 0x1f9f25cf, 0xadf2b89b, 0x5ad6b472, 0x5a88f54c,
  3691. 0xe029ac71, 0xe019a5e6, 0x47b0acfd, 0xed93fa9b, 0xe8d3c48d, 0x283b57cc, 0xf8d56629, 0x79132e28,
  3692. 0x785f0191, 0xed756055, 0xf7960e44, 0xe3d35e8c, 0x15056dd4, 0x88f46dba, 0x03a16125, 0x0564f0bd,
  3693. 0xc3eb9e15, 0x3c9057a2, 0x97271aec, 0xa93a072a, 0x1b3f6d9b, 0x1e6321f5, 0xf59c66fb, 0x26dcf319,
  3694. 0x7533d928, 0xb155fdf5, 0x03563482, 0x8aba3cbb, 0x28517711, 0xc20ad9f8, 0xabcc5167, 0xccad925f,
  3695. 0x4de81751, 0x3830dc8e, 0x379d5862, 0x9320f991, 0xea7a90c2, 0xfb3e7bce, 0x5121ce64, 0x774fbe32,
  3696. 0xa8b6e37e, 0xc3293d46, 0x48de5369, 0x6413e680, 0xa2ae0810, 0xdd6db224, 0x69852dfd, 0x09072166,
  3697. 0xb39a460a, 0x6445c0dd, 0x586cdecf, 0x1c20c8ae, 0x5bbef7dd, 0x1b588d40, 0xccd2017f, 0x6bb4e3bb,
  3698. 0xdda26a7e, 0x3a59ff45, 0x3e350a44, 0xbcb4cdd5, 0x72eacea8, 0xfa6484bb, 0x8d6612ae, 0xbf3c6f47,
  3699. 0xd29be463, 0x542f5d9e, 0xaec2771b, 0xf64e6370, 0x740e0d8d, 0xe75b1357, 0xf8721671, 0xaf537d5d,
  3700. 0x4040cb08, 0x4eb4e2cc, 0x34d2466a, 0x0115af84, 0xe1b00428, 0x95983a1d, 0x06b89fb4, 0xce6ea048,
  3701. 0x6f3f3b82, 0x3520ab82, 0x011a1d4b, 0x277227f8, 0x611560b1, 0xe7933fdc, 0xbb3a792b, 0x344525bd,
  3702. 0xa08839e1, 0x51ce794b, 0x2f32c9b7, 0xa01fbac9, 0xe01cc87e, 0xbcc7d1f6, 0xcf0111c3, 0xa1e8aac7,
  3703. 0x1a908749, 0xd44fbd9a, 0xd0dadecb, 0xd50ada38, 0x0339c32a, 0xc6913667, 0x8df9317c, 0xe0b12b4f,
  3704. 0xf79e59b7, 0x43f5bb3a, 0xf2d519ff, 0x27d9459c, 0xbf97222c, 0x15e6fc2a, 0x0f91fc71, 0x9b941525,
  3705. 0xfae59361, 0xceb69ceb, 0xc2a86459, 0x12baa8d1, 0xb6c1075e, 0xe3056a0c, 0x10d25065, 0xcb03a442,
  3706. 0xe0ec6e0e, 0x1698db3b, 0x4c98a0be, 0x3278e964, 0x9f1f9532, 0xe0d392df, 0xd3a0342b, 0x8971f21e,
  3707. 0x1b0a7441, 0x4ba3348c, 0xc5be7120, 0xc37632d8, 0xdf359f8d, 0x9b992f2e, 0xe60b6f47, 0x0fe3f11d,
  3708. 0xe54cda54, 0x1edad891, 0xce6279cf, 0xcd3e7e6f, 0x1618b166, 0xfd2c1d05, 0x848fd2c5, 0xf6fb2299,
  3709. 0xf523f357, 0xa6327623, 0x93a83531, 0x56cccd02, 0xacf08162, 0x5a75ebb5, 0x6e163697, 0x88d273cc,
  3710. 0xde966292, 0x81b949d0, 0x4c50901b, 0x71c65614, 0xe6c6c7bd, 0x327a140a, 0x45e1d006, 0xc3f27b9a,
  3711. 0xc9aa53fd, 0x62a80f00, 0xbb25bfe2, 0x35bdd2f6, 0x71126905, 0xb2040222, 0xb6cbcf7c, 0xcd769c2b,
  3712. 0x53113ec0, 0x1640e3d3, 0x38abbd60, 0x2547adf0, 0xba38209c, 0xf746ce76, 0x77afa1c5, 0x20756060,
  3713. 0x85cbfe4e, 0x8ae88dd8, 0x7aaaf9b0, 0x4cf9aa7e, 0x1948c25c, 0x02fb8a8c, 0x01c36ae4, 0xd6ebe1f9,
  3714. 0x90d4f869, 0xa65cdea0, 0x3f09252d, 0xc208e69f, 0xb74e6132, 0xce77e25b, 0x578fdfe3, 0x3ac372e6
  3715. };
  3716. memcpy (p, initialPValues, sizeof (p));
  3717. int i, j = 0;
  3718. for (i = 4; --i >= 0;)
  3719. {
  3720. s[i].malloc (256);
  3721. memcpy (s[i], initialSValues + i * 256, 256 * sizeof (uint32));
  3722. }
  3723. for (i = 0; i < 18; ++i)
  3724. {
  3725. uint32 d = 0;
  3726. for (int k = 0; k < 4; ++k)
  3727. {
  3728. d = (d << 8) | static_cast <const uint8*> (keyData)[j];
  3729. if (++j >= keyBytes)
  3730. j = 0;
  3731. }
  3732. p[i] = initialPValues[i] ^ d;
  3733. }
  3734. uint32 l = 0, r = 0;
  3735. for (i = 0; i < 18; i += 2)
  3736. {
  3737. encrypt (l, r);
  3738. p[i] = l;
  3739. p[i + 1] = r;
  3740. }
  3741. for (i = 0; i < 4; ++i)
  3742. {
  3743. for (j = 0; j < 256; j += 2)
  3744. {
  3745. encrypt (l, r);
  3746. s[i][j] = l;
  3747. s[i][j + 1] = r;
  3748. }
  3749. }
  3750. }
  3751. BlowFish::BlowFish (const BlowFish& other)
  3752. {
  3753. for (int i = 4; --i >= 0;)
  3754. s[i].malloc (256);
  3755. operator= (other);
  3756. }
  3757. BlowFish& BlowFish::operator= (const BlowFish& other)
  3758. {
  3759. memcpy (p, other.p, sizeof (p));
  3760. for (int i = 4; --i >= 0;)
  3761. memcpy (s[i], other.s[i], 256 * sizeof (uint32));
  3762. return *this;
  3763. }
  3764. BlowFish::~BlowFish()
  3765. {
  3766. }
  3767. uint32 BlowFish::F (const uint32 x) const throw()
  3768. {
  3769. return ((s[0][(x >> 24) & 0xff] + s[1][(x >> 16) & 0xff])
  3770. ^ s[2][(x >> 8) & 0xff]) + s[3][x & 0xff];
  3771. }
  3772. void BlowFish::encrypt (uint32& data1, uint32& data2) const throw()
  3773. {
  3774. uint32 l = data1;
  3775. uint32 r = data2;
  3776. for (int i = 0; i < 16; ++i)
  3777. {
  3778. l ^= p[i];
  3779. r ^= F(l);
  3780. swapVariables (l, r);
  3781. }
  3782. data1 = r ^ p[17];
  3783. data2 = l ^ p[16];
  3784. }
  3785. void BlowFish::decrypt (uint32& data1, uint32& data2) const throw()
  3786. {
  3787. uint32 l = data1;
  3788. uint32 r = data2;
  3789. for (int i = 17; i > 1; --i)
  3790. {
  3791. l ^= p[i];
  3792. r ^= F(l);
  3793. swapVariables (l, r);
  3794. }
  3795. data1 = r ^ p[0];
  3796. data2 = l ^ p[1];
  3797. }
  3798. END_JUCE_NAMESPACE
  3799. /*** End of inlined file: juce_BlowFish.cpp ***/
  3800. /*** Start of inlined file: juce_MD5.cpp ***/
  3801. BEGIN_JUCE_NAMESPACE
  3802. MD5::MD5()
  3803. {
  3804. zerostruct (result);
  3805. }
  3806. MD5::MD5 (const MD5& other)
  3807. {
  3808. memcpy (result, other.result, sizeof (result));
  3809. }
  3810. MD5& MD5::operator= (const MD5& other)
  3811. {
  3812. memcpy (result, other.result, sizeof (result));
  3813. return *this;
  3814. }
  3815. MD5::MD5 (const MemoryBlock& data)
  3816. {
  3817. ProcessContext context;
  3818. context.processBlock (data.getData(), data.getSize());
  3819. context.finish (result);
  3820. }
  3821. MD5::MD5 (const void* data, const size_t numBytes)
  3822. {
  3823. ProcessContext context;
  3824. context.processBlock (data, numBytes);
  3825. context.finish (result);
  3826. }
  3827. MD5::MD5 (const String& text)
  3828. {
  3829. ProcessContext context;
  3830. const int len = text.length();
  3831. const juce_wchar* const t = text;
  3832. for (int i = 0; i < len; ++i)
  3833. {
  3834. // force the string into integer-sized unicode characters, to try to make it
  3835. // get the same results on all platforms + compilers.
  3836. uint32 unicodeChar = ByteOrder::swapIfBigEndian ((uint32) t[i]);
  3837. context.processBlock (&unicodeChar, sizeof (unicodeChar));
  3838. }
  3839. context.finish (result);
  3840. }
  3841. void MD5::processStream (InputStream& input, int64 numBytesToRead)
  3842. {
  3843. ProcessContext context;
  3844. if (numBytesToRead < 0)
  3845. numBytesToRead = std::numeric_limits<int64>::max();
  3846. while (numBytesToRead > 0)
  3847. {
  3848. uint8 tempBuffer [512];
  3849. const int bytesRead = input.read (tempBuffer, (int) jmin (numBytesToRead, (int64) sizeof (tempBuffer)));
  3850. if (bytesRead <= 0)
  3851. break;
  3852. numBytesToRead -= bytesRead;
  3853. context.processBlock (tempBuffer, bytesRead);
  3854. }
  3855. context.finish (result);
  3856. }
  3857. MD5::MD5 (InputStream& input, int64 numBytesToRead)
  3858. {
  3859. processStream (input, numBytesToRead);
  3860. }
  3861. MD5::MD5 (const File& file)
  3862. {
  3863. const ScopedPointer <FileInputStream> fin (file.createInputStream());
  3864. if (fin != 0)
  3865. processStream (*fin, -1);
  3866. else
  3867. zerostruct (result);
  3868. }
  3869. MD5::~MD5()
  3870. {
  3871. }
  3872. namespace MD5Functions
  3873. {
  3874. static void encode (void* const output, const void* const input, const int numBytes) throw()
  3875. {
  3876. for (int i = 0; i < (numBytes >> 2); ++i)
  3877. static_cast<uint32*> (output)[i] = ByteOrder::swapIfBigEndian (static_cast<const uint32*> (input) [i]);
  3878. }
  3879. static inline uint32 F (const uint32 x, const uint32 y, const uint32 z) throw() { return (x & y) | (~x & z); }
  3880. static inline uint32 G (const uint32 x, const uint32 y, const uint32 z) throw() { return (x & z) | (y & ~z); }
  3881. static inline uint32 H (const uint32 x, const uint32 y, const uint32 z) throw() { return x ^ y ^ z; }
  3882. static inline uint32 I (const uint32 x, const uint32 y, const uint32 z) throw() { return y ^ (x | ~z); }
  3883. static inline uint32 rotateLeft (const uint32 x, const uint32 n) throw() { return (x << n) | (x >> (32 - n)); }
  3884. static void FF (uint32& a, const uint32 b, const uint32 c, const uint32 d, const uint32 x, const uint32 s, const uint32 ac) throw()
  3885. {
  3886. a += F (b, c, d) + x + ac;
  3887. a = rotateLeft (a, s) + b;
  3888. }
  3889. static void GG (uint32& a, const uint32 b, const uint32 c, const uint32 d, const uint32 x, const uint32 s, const uint32 ac) throw()
  3890. {
  3891. a += G (b, c, d) + x + ac;
  3892. a = rotateLeft (a, s) + b;
  3893. }
  3894. static void HH (uint32& a, const uint32 b, const uint32 c, const uint32 d, const uint32 x, const uint32 s, const uint32 ac) throw()
  3895. {
  3896. a += H (b, c, d) + x + ac;
  3897. a = rotateLeft (a, s) + b;
  3898. }
  3899. static void II (uint32& a, const uint32 b, const uint32 c, const uint32 d, const uint32 x, const uint32 s, const uint32 ac) throw()
  3900. {
  3901. a += I (b, c, d) + x + ac;
  3902. a = rotateLeft (a, s) + b;
  3903. }
  3904. }
  3905. MD5::ProcessContext::ProcessContext()
  3906. {
  3907. state[0] = 0x67452301;
  3908. state[1] = 0xefcdab89;
  3909. state[2] = 0x98badcfe;
  3910. state[3] = 0x10325476;
  3911. count[0] = 0;
  3912. count[1] = 0;
  3913. }
  3914. void MD5::ProcessContext::processBlock (const void* const data, const size_t dataSize)
  3915. {
  3916. int bufferPos = ((count[0] >> 3) & 0x3F);
  3917. count[0] += (uint32) (dataSize << 3);
  3918. if (count[0] < ((uint32) dataSize << 3))
  3919. count[1]++;
  3920. count[1] += (uint32) (dataSize >> 29);
  3921. const size_t spaceLeft = 64 - bufferPos;
  3922. size_t i = 0;
  3923. if (dataSize >= spaceLeft)
  3924. {
  3925. memcpy (buffer + bufferPos, data, spaceLeft);
  3926. transform (buffer);
  3927. for (i = spaceLeft; i + 64 <= dataSize; i += 64)
  3928. transform (static_cast <const char*> (data) + i);
  3929. bufferPos = 0;
  3930. }
  3931. memcpy (buffer + bufferPos, static_cast <const char*> (data) + i, dataSize - i);
  3932. }
  3933. void MD5::ProcessContext::finish (void* const result)
  3934. {
  3935. unsigned char encodedLength[8];
  3936. MD5Functions::encode (encodedLength, count, 8);
  3937. // Pad out to 56 mod 64.
  3938. const int index = (uint32) ((count[0] >> 3) & 0x3f);
  3939. const int paddingLength = (index < 56) ? (56 - index)
  3940. : (120 - index);
  3941. uint8 paddingBuffer [64];
  3942. zeromem (paddingBuffer, paddingLength);
  3943. paddingBuffer [0] = 0x80;
  3944. processBlock (paddingBuffer, paddingLength);
  3945. processBlock (encodedLength, 8);
  3946. MD5Functions::encode (result, state, 16);
  3947. zerostruct (buffer);
  3948. }
  3949. void MD5::ProcessContext::transform (const void* const bufferToTransform)
  3950. {
  3951. using namespace MD5Functions;
  3952. uint32 a = state[0];
  3953. uint32 b = state[1];
  3954. uint32 c = state[2];
  3955. uint32 d = state[3];
  3956. uint32 x[16];
  3957. encode (x, bufferToTransform, 64);
  3958. enum Constants
  3959. {
  3960. S11 = 7, S12 = 12, S13 = 17, S14 = 22, S21 = 5, S22 = 9, S23 = 14, S24 = 20,
  3961. S31 = 4, S32 = 11, S33 = 16, S34 = 23, S41 = 6, S42 = 10, S43 = 15, S44 = 21
  3962. };
  3963. FF (a, b, c, d, x[ 0], S11, 0xd76aa478); FF (d, a, b, c, x[ 1], S12, 0xe8c7b756);
  3964. FF (c, d, a, b, x[ 2], S13, 0x242070db); FF (b, c, d, a, x[ 3], S14, 0xc1bdceee);
  3965. FF (a, b, c, d, x[ 4], S11, 0xf57c0faf); FF (d, a, b, c, x[ 5], S12, 0x4787c62a);
  3966. FF (c, d, a, b, x[ 6], S13, 0xa8304613); FF (b, c, d, a, x[ 7], S14, 0xfd469501);
  3967. FF (a, b, c, d, x[ 8], S11, 0x698098d8); FF (d, a, b, c, x[ 9], S12, 0x8b44f7af);
  3968. FF (c, d, a, b, x[10], S13, 0xffff5bb1); FF (b, c, d, a, x[11], S14, 0x895cd7be);
  3969. FF (a, b, c, d, x[12], S11, 0x6b901122); FF (d, a, b, c, x[13], S12, 0xfd987193);
  3970. FF (c, d, a, b, x[14], S13, 0xa679438e); FF (b, c, d, a, x[15], S14, 0x49b40821);
  3971. GG (a, b, c, d, x[ 1], S21, 0xf61e2562); GG (d, a, b, c, x[ 6], S22, 0xc040b340);
  3972. GG (c, d, a, b, x[11], S23, 0x265e5a51); GG (b, c, d, a, x[ 0], S24, 0xe9b6c7aa);
  3973. GG (a, b, c, d, x[ 5], S21, 0xd62f105d); GG (d, a, b, c, x[10], S22, 0x02441453);
  3974. GG (c, d, a, b, x[15], S23, 0xd8a1e681); GG (b, c, d, a, x[ 4], S24, 0xe7d3fbc8);
  3975. GG (a, b, c, d, x[ 9], S21, 0x21e1cde6); GG (d, a, b, c, x[14], S22, 0xc33707d6);
  3976. GG (c, d, a, b, x[ 3], S23, 0xf4d50d87); GG (b, c, d, a, x[ 8], S24, 0x455a14ed);
  3977. GG (a, b, c, d, x[13], S21, 0xa9e3e905); GG (d, a, b, c, x[ 2], S22, 0xfcefa3f8);
  3978. GG (c, d, a, b, x[ 7], S23, 0x676f02d9); GG (b, c, d, a, x[12], S24, 0x8d2a4c8a);
  3979. HH (a, b, c, d, x[ 5], S31, 0xfffa3942); HH (d, a, b, c, x[ 8], S32, 0x8771f681);
  3980. HH (c, d, a, b, x[11], S33, 0x6d9d6122); HH (b, c, d, a, x[14], S34, 0xfde5380c);
  3981. HH (a, b, c, d, x[ 1], S31, 0xa4beea44); HH (d, a, b, c, x[ 4], S32, 0x4bdecfa9);
  3982. HH (c, d, a, b, x[ 7], S33, 0xf6bb4b60); HH (b, c, d, a, x[10], S34, 0xbebfbc70);
  3983. HH (a, b, c, d, x[13], S31, 0x289b7ec6); HH (d, a, b, c, x[ 0], S32, 0xeaa127fa);
  3984. HH (c, d, a, b, x[ 3], S33, 0xd4ef3085); HH (b, c, d, a, x[ 6], S34, 0x04881d05);
  3985. HH (a, b, c, d, x[ 9], S31, 0xd9d4d039); HH (d, a, b, c, x[12], S32, 0xe6db99e5);
  3986. HH (c, d, a, b, x[15], S33, 0x1fa27cf8); HH (b, c, d, a, x[ 2], S34, 0xc4ac5665);
  3987. II (a, b, c, d, x[ 0], S41, 0xf4292244); II (d, a, b, c, x[ 7], S42, 0x432aff97);
  3988. II (c, d, a, b, x[14], S43, 0xab9423a7); II (b, c, d, a, x[ 5], S44, 0xfc93a039);
  3989. II (a, b, c, d, x[12], S41, 0x655b59c3); II (d, a, b, c, x[ 3], S42, 0x8f0ccc92);
  3990. II (c, d, a, b, x[10], S43, 0xffeff47d); II (b, c, d, a, x[ 1], S44, 0x85845dd1);
  3991. II (a, b, c, d, x[ 8], S41, 0x6fa87e4f); II (d, a, b, c, x[15], S42, 0xfe2ce6e0);
  3992. II (c, d, a, b, x[ 6], S43, 0xa3014314); II (b, c, d, a, x[13], S44, 0x4e0811a1);
  3993. II (a, b, c, d, x[ 4], S41, 0xf7537e82); II (d, a, b, c, x[11], S42, 0xbd3af235);
  3994. II (c, d, a, b, x[ 2], S43, 0x2ad7d2bb); II (b, c, d, a, x[ 9], S44, 0xeb86d391);
  3995. state[0] += a;
  3996. state[1] += b;
  3997. state[2] += c;
  3998. state[3] += d;
  3999. zerostruct (x);
  4000. }
  4001. const MemoryBlock MD5::getRawChecksumData() const
  4002. {
  4003. return MemoryBlock (result, sizeof (result));
  4004. }
  4005. const String MD5::toHexString() const
  4006. {
  4007. return String::toHexString (result, sizeof (result), 0);
  4008. }
  4009. bool MD5::operator== (const MD5& other) const
  4010. {
  4011. return memcmp (result, other.result, sizeof (result)) == 0;
  4012. }
  4013. bool MD5::operator!= (const MD5& other) const
  4014. {
  4015. return ! operator== (other);
  4016. }
  4017. END_JUCE_NAMESPACE
  4018. /*** End of inlined file: juce_MD5.cpp ***/
  4019. /*** Start of inlined file: juce_Primes.cpp ***/
  4020. BEGIN_JUCE_NAMESPACE
  4021. namespace PrimesHelpers
  4022. {
  4023. static void createSmallSieve (const int numBits, BigInteger& result)
  4024. {
  4025. result.setBit (numBits);
  4026. result.clearBit (numBits); // to enlarge the array
  4027. result.setBit (0);
  4028. int n = 2;
  4029. do
  4030. {
  4031. for (int i = n + n; i < numBits; i += n)
  4032. result.setBit (i);
  4033. n = result.findNextClearBit (n + 1);
  4034. }
  4035. while (n <= (numBits >> 1));
  4036. }
  4037. static void bigSieve (const BigInteger& base, const int numBits, BigInteger& result,
  4038. const BigInteger& smallSieve, const int smallSieveSize)
  4039. {
  4040. jassert (! base[0]); // must be even!
  4041. result.setBit (numBits);
  4042. result.clearBit (numBits); // to enlarge the array
  4043. int index = smallSieve.findNextClearBit (0);
  4044. do
  4045. {
  4046. const int prime = (index << 1) + 1;
  4047. BigInteger r (base), remainder;
  4048. r.divideBy (prime, remainder);
  4049. int i = prime - remainder.getBitRangeAsInt (0, 32);
  4050. if (r.isZero())
  4051. i += prime;
  4052. if ((i & 1) == 0)
  4053. i += prime;
  4054. i = (i - 1) >> 1;
  4055. while (i < numBits)
  4056. {
  4057. result.setBit (i);
  4058. i += prime;
  4059. }
  4060. index = smallSieve.findNextClearBit (index + 1);
  4061. }
  4062. while (index < smallSieveSize);
  4063. }
  4064. static bool findCandidate (const BigInteger& base, const BigInteger& sieve,
  4065. const int numBits, BigInteger& result, const int certainty)
  4066. {
  4067. for (int i = 0; i < numBits; ++i)
  4068. {
  4069. if (! sieve[i])
  4070. {
  4071. result = base + (unsigned int) ((i << 1) + 1);
  4072. if (Primes::isProbablyPrime (result, certainty))
  4073. return true;
  4074. }
  4075. }
  4076. return false;
  4077. }
  4078. static bool passesMillerRabin (const BigInteger& n, int iterations)
  4079. {
  4080. const BigInteger one (1), two (2);
  4081. const BigInteger nMinusOne (n - one);
  4082. BigInteger d (nMinusOne);
  4083. const int s = d.findNextSetBit (0);
  4084. d >>= s;
  4085. BigInteger smallPrimes;
  4086. int numBitsInSmallPrimes = 0;
  4087. for (;;)
  4088. {
  4089. numBitsInSmallPrimes += 256;
  4090. createSmallSieve (numBitsInSmallPrimes, smallPrimes);
  4091. const int numPrimesFound = numBitsInSmallPrimes - smallPrimes.countNumberOfSetBits();
  4092. if (numPrimesFound > iterations + 1)
  4093. break;
  4094. }
  4095. int smallPrime = 2;
  4096. while (--iterations >= 0)
  4097. {
  4098. smallPrime = smallPrimes.findNextClearBit (smallPrime + 1);
  4099. BigInteger r (smallPrime);
  4100. r.exponentModulo (d, n);
  4101. if (r != one && r != nMinusOne)
  4102. {
  4103. for (int j = 0; j < s; ++j)
  4104. {
  4105. r.exponentModulo (two, n);
  4106. if (r == nMinusOne)
  4107. break;
  4108. }
  4109. if (r != nMinusOne)
  4110. return false;
  4111. }
  4112. }
  4113. return true;
  4114. }
  4115. }
  4116. const BigInteger Primes::createProbablePrime (const int bitLength,
  4117. const int certainty,
  4118. const int* randomSeeds,
  4119. int numRandomSeeds)
  4120. {
  4121. using namespace PrimesHelpers;
  4122. int defaultSeeds [16];
  4123. if (numRandomSeeds <= 0)
  4124. {
  4125. randomSeeds = defaultSeeds;
  4126. numRandomSeeds = numElementsInArray (defaultSeeds);
  4127. Random r (0);
  4128. for (int j = 10; --j >= 0;)
  4129. {
  4130. r.setSeedRandomly();
  4131. for (int i = numRandomSeeds; --i >= 0;)
  4132. defaultSeeds[i] ^= r.nextInt() ^ Random::getSystemRandom().nextInt();
  4133. }
  4134. }
  4135. BigInteger smallSieve;
  4136. const int smallSieveSize = 15000;
  4137. createSmallSieve (smallSieveSize, smallSieve);
  4138. BigInteger p;
  4139. for (int i = numRandomSeeds; --i >= 0;)
  4140. {
  4141. BigInteger p2;
  4142. Random r (randomSeeds[i]);
  4143. r.fillBitsRandomly (p2, 0, bitLength);
  4144. p ^= p2;
  4145. }
  4146. p.setBit (bitLength - 1);
  4147. p.clearBit (0);
  4148. const int searchLen = jmax (1024, (bitLength / 20) * 64);
  4149. while (p.getHighestBit() < bitLength)
  4150. {
  4151. p += 2 * searchLen;
  4152. BigInteger sieve;
  4153. bigSieve (p, searchLen, sieve,
  4154. smallSieve, smallSieveSize);
  4155. BigInteger candidate;
  4156. if (findCandidate (p, sieve, searchLen, candidate, certainty))
  4157. return candidate;
  4158. }
  4159. jassertfalse
  4160. return BigInteger();
  4161. }
  4162. bool Primes::isProbablyPrime (const BigInteger& number, const int certainty)
  4163. {
  4164. using namespace PrimesHelpers;
  4165. if (! number[0])
  4166. return false;
  4167. if (number.getHighestBit() <= 10)
  4168. {
  4169. const int num = number.getBitRangeAsInt (0, 10);
  4170. for (int i = num / 2; --i > 1;)
  4171. if (num % i == 0)
  4172. return false;
  4173. return true;
  4174. }
  4175. else
  4176. {
  4177. if (number.findGreatestCommonDivisor (2 * 3 * 5 * 7 * 11 * 13 * 17 * 19 * 23) != 1)
  4178. return false;
  4179. return passesMillerRabin (number, certainty);
  4180. }
  4181. }
  4182. END_JUCE_NAMESPACE
  4183. /*** End of inlined file: juce_Primes.cpp ***/
  4184. /*** Start of inlined file: juce_RSAKey.cpp ***/
  4185. BEGIN_JUCE_NAMESPACE
  4186. RSAKey::RSAKey()
  4187. {
  4188. }
  4189. RSAKey::RSAKey (const String& s)
  4190. {
  4191. if (s.containsChar (','))
  4192. {
  4193. part1.parseString (s.upToFirstOccurrenceOf (",", false, false), 16);
  4194. part2.parseString (s.fromFirstOccurrenceOf (",", false, false), 16);
  4195. }
  4196. else
  4197. {
  4198. // the string needs to be two hex numbers, comma-separated..
  4199. jassertfalse;
  4200. }
  4201. }
  4202. RSAKey::~RSAKey()
  4203. {
  4204. }
  4205. const String RSAKey::toString() const
  4206. {
  4207. return part1.toString (16) + "," + part2.toString (16);
  4208. }
  4209. bool RSAKey::applyToValue (BigInteger& value) const
  4210. {
  4211. if (part1.isZero() || part2.isZero() || value <= 0)
  4212. {
  4213. jassertfalse // using an uninitialised key
  4214. value.clear();
  4215. return false;
  4216. }
  4217. BigInteger result;
  4218. while (! value.isZero())
  4219. {
  4220. result *= part2;
  4221. BigInteger remainder;
  4222. value.divideBy (part2, remainder);
  4223. remainder.exponentModulo (part1, part2);
  4224. result += remainder;
  4225. }
  4226. value.swapWith (result);
  4227. return true;
  4228. }
  4229. static const BigInteger findBestCommonDivisor (const BigInteger& p, const BigInteger& q)
  4230. {
  4231. // try 3, 5, 9, 17, etc first because these only contain 2 bits and so
  4232. // are fast to divide + multiply
  4233. for (int i = 2; i <= 65536; i *= 2)
  4234. {
  4235. const BigInteger e (1 + i);
  4236. if (e.findGreatestCommonDivisor (p).isOne() && e.findGreatestCommonDivisor (q).isOne())
  4237. return e;
  4238. }
  4239. BigInteger e (4);
  4240. while (! (e.findGreatestCommonDivisor (p).isOne() && e.findGreatestCommonDivisor (q).isOne()))
  4241. ++e;
  4242. return e;
  4243. }
  4244. void RSAKey::createKeyPair (RSAKey& publicKey, RSAKey& privateKey,
  4245. const int numBits, const int* randomSeeds, const int numRandomSeeds)
  4246. {
  4247. jassert (numBits > 16); // not much point using less than this..
  4248. BigInteger p (Primes::createProbablePrime (numBits / 2, 30, randomSeeds, numRandomSeeds));
  4249. BigInteger q (Primes::createProbablePrime (numBits - numBits / 2, 30, randomSeeds, numRandomSeeds));
  4250. const BigInteger n (p * q);
  4251. const BigInteger m (--p * --q);
  4252. const BigInteger e (findBestCommonDivisor (p, q));
  4253. BigInteger d (e);
  4254. d.inverseModulo (m);
  4255. publicKey.part1 = e;
  4256. publicKey.part2 = n;
  4257. privateKey.part1 = d;
  4258. privateKey.part2 = n;
  4259. }
  4260. END_JUCE_NAMESPACE
  4261. /*** End of inlined file: juce_RSAKey.cpp ***/
  4262. /*** Start of inlined file: juce_InputStream.cpp ***/
  4263. BEGIN_JUCE_NAMESPACE
  4264. char InputStream::readByte()
  4265. {
  4266. char temp = 0;
  4267. read (&temp, 1);
  4268. return temp;
  4269. }
  4270. bool InputStream::readBool()
  4271. {
  4272. return readByte() != 0;
  4273. }
  4274. short InputStream::readShort()
  4275. {
  4276. char temp[2];
  4277. if (read (temp, 2) == 2)
  4278. return (short) ByteOrder::littleEndianShort (temp);
  4279. return 0;
  4280. }
  4281. short InputStream::readShortBigEndian()
  4282. {
  4283. char temp[2];
  4284. if (read (temp, 2) == 2)
  4285. return (short) ByteOrder::bigEndianShort (temp);
  4286. return 0;
  4287. }
  4288. int InputStream::readInt()
  4289. {
  4290. char temp[4];
  4291. if (read (temp, 4) == 4)
  4292. return (int) ByteOrder::littleEndianInt (temp);
  4293. return 0;
  4294. }
  4295. int InputStream::readIntBigEndian()
  4296. {
  4297. char temp[4];
  4298. if (read (temp, 4) == 4)
  4299. return (int) ByteOrder::bigEndianInt (temp);
  4300. return 0;
  4301. }
  4302. int InputStream::readCompressedInt()
  4303. {
  4304. const unsigned char sizeByte = readByte();
  4305. if (sizeByte == 0)
  4306. return 0;
  4307. const int numBytes = (sizeByte & 0x7f);
  4308. if (numBytes > 4)
  4309. {
  4310. jassertfalse // trying to read corrupt data - this method must only be used
  4311. // to read data that was written by OutputStream::writeCompressedInt()
  4312. return 0;
  4313. }
  4314. char bytes[4] = { 0, 0, 0, 0 };
  4315. if (read (bytes, numBytes) != numBytes)
  4316. return 0;
  4317. const int num = (int) ByteOrder::littleEndianInt (bytes);
  4318. return (sizeByte >> 7) ? -num : num;
  4319. }
  4320. int64 InputStream::readInt64()
  4321. {
  4322. union { uint8 asBytes[8]; uint64 asInt64; } n;
  4323. if (read (n.asBytes, 8) == 8)
  4324. return (int64) ByteOrder::swapIfBigEndian (n.asInt64);
  4325. return 0;
  4326. }
  4327. int64 InputStream::readInt64BigEndian()
  4328. {
  4329. union { uint8 asBytes[8]; uint64 asInt64; } n;
  4330. if (read (n.asBytes, 8) == 8)
  4331. return (int64) ByteOrder::swapIfLittleEndian (n.asInt64);
  4332. return 0;
  4333. }
  4334. float InputStream::readFloat()
  4335. {
  4336. // the union below relies on these types being the same size...
  4337. static_jassert (sizeof (int32) == sizeof (float));
  4338. union { int32 asInt; float asFloat; } n;
  4339. n.asInt = (int32) readInt();
  4340. return n.asFloat;
  4341. }
  4342. float InputStream::readFloatBigEndian()
  4343. {
  4344. union { int32 asInt; float asFloat; } n;
  4345. n.asInt = (int32) readIntBigEndian();
  4346. return n.asFloat;
  4347. }
  4348. double InputStream::readDouble()
  4349. {
  4350. union { int64 asInt; double asDouble; } n;
  4351. n.asInt = readInt64();
  4352. return n.asDouble;
  4353. }
  4354. double InputStream::readDoubleBigEndian()
  4355. {
  4356. union { int64 asInt; double asDouble; } n;
  4357. n.asInt = readInt64BigEndian();
  4358. return n.asDouble;
  4359. }
  4360. const String InputStream::readString()
  4361. {
  4362. MemoryBlock buffer (256);
  4363. char* data = static_cast<char*> (buffer.getData());
  4364. size_t i = 0;
  4365. while ((data[i] = readByte()) != 0)
  4366. {
  4367. if (++i >= buffer.getSize())
  4368. {
  4369. buffer.setSize (buffer.getSize() + 512);
  4370. data = static_cast<char*> (buffer.getData());
  4371. }
  4372. }
  4373. return String::fromUTF8 (data, (int) i);
  4374. }
  4375. const String InputStream::readNextLine()
  4376. {
  4377. MemoryBlock buffer (256);
  4378. char* data = static_cast<char*> (buffer.getData());
  4379. size_t i = 0;
  4380. while ((data[i] = readByte()) != 0)
  4381. {
  4382. if (data[i] == '\n')
  4383. break;
  4384. if (data[i] == '\r')
  4385. {
  4386. const int64 lastPos = getPosition();
  4387. if (readByte() != '\n')
  4388. setPosition (lastPos);
  4389. break;
  4390. }
  4391. if (++i >= buffer.getSize())
  4392. {
  4393. buffer.setSize (buffer.getSize() + 512);
  4394. data = static_cast<char*> (buffer.getData());
  4395. }
  4396. }
  4397. return String::fromUTF8 (data, (int) i);
  4398. }
  4399. int InputStream::readIntoMemoryBlock (MemoryBlock& block, int numBytes)
  4400. {
  4401. const int64 totalLength = getTotalLength();
  4402. if (totalLength >= 0)
  4403. {
  4404. const int totalBytesRemaining = (int) jmin ((int64) 0x7fffffff,
  4405. totalLength - getPosition());
  4406. if (numBytes < 0)
  4407. numBytes = totalBytesRemaining;
  4408. else if (numBytes > 0)
  4409. numBytes = jmin (numBytes, totalBytesRemaining);
  4410. else
  4411. return 0;
  4412. }
  4413. const size_t originalBlockSize = block.getSize();
  4414. int totalBytesRead = 0;
  4415. if (numBytes > 0)
  4416. {
  4417. // know how many bytes we want, so we can resize the block first..
  4418. block.setSize (originalBlockSize + numBytes, false);
  4419. totalBytesRead = read (static_cast<char*> (block.getData()) + originalBlockSize, numBytes);
  4420. }
  4421. else
  4422. {
  4423. // read until end of stram..
  4424. const int chunkSize = 32768;
  4425. for (;;)
  4426. {
  4427. block.ensureSize (originalBlockSize + totalBytesRead + chunkSize, false);
  4428. const int bytesJustIn = read (static_cast<char*> (block.getData())
  4429. + originalBlockSize
  4430. + totalBytesRead,
  4431. chunkSize);
  4432. if (bytesJustIn == 0)
  4433. break;
  4434. totalBytesRead += bytesJustIn;
  4435. }
  4436. }
  4437. // trim off any excess left at the end
  4438. block.setSize (originalBlockSize + totalBytesRead, false);
  4439. return totalBytesRead;
  4440. }
  4441. const String InputStream::readEntireStreamAsString()
  4442. {
  4443. MemoryBlock mb;
  4444. const int size = readIntoMemoryBlock (mb);
  4445. return String::createStringFromData (static_cast<const char*> (mb.getData()), size);
  4446. }
  4447. void InputStream::skipNextBytes (int64 numBytesToSkip)
  4448. {
  4449. if (numBytesToSkip > 0)
  4450. {
  4451. const int skipBufferSize = (int) jmin (numBytesToSkip, (int64) 16384);
  4452. HeapBlock<char> temp (skipBufferSize);
  4453. while (numBytesToSkip > 0 && ! isExhausted())
  4454. numBytesToSkip -= read (temp, (int) jmin (numBytesToSkip, (int64) skipBufferSize));
  4455. }
  4456. }
  4457. END_JUCE_NAMESPACE
  4458. /*** End of inlined file: juce_InputStream.cpp ***/
  4459. /*** Start of inlined file: juce_OutputStream.cpp ***/
  4460. BEGIN_JUCE_NAMESPACE
  4461. #if JUCE_DEBUG
  4462. static CriticalSection activeStreamLock;
  4463. static VoidArray activeStreams;
  4464. void juce_CheckForDanglingStreams()
  4465. {
  4466. /*
  4467. It's always a bad idea to leak any object, but if you're leaking output
  4468. streams, then there's a good chance that you're failing to flush a file
  4469. to disk properly, which could result in corrupted data and other similar
  4470. nastiness..
  4471. */
  4472. jassert (activeStreams.size() == 0);
  4473. };
  4474. #endif
  4475. OutputStream::OutputStream()
  4476. {
  4477. #if JUCE_DEBUG
  4478. const ScopedLock sl (activeStreamLock);
  4479. activeStreams.add (this);
  4480. #endif
  4481. }
  4482. OutputStream::~OutputStream()
  4483. {
  4484. #if JUCE_DEBUG
  4485. const ScopedLock sl (activeStreamLock);
  4486. activeStreams.removeValue (this);
  4487. #endif
  4488. }
  4489. void OutputStream::writeBool (const bool b)
  4490. {
  4491. writeByte (b ? (char) 1
  4492. : (char) 0);
  4493. }
  4494. void OutputStream::writeByte (char byte)
  4495. {
  4496. write (&byte, 1);
  4497. }
  4498. void OutputStream::writeShort (short value)
  4499. {
  4500. const unsigned short v = ByteOrder::swapIfBigEndian ((unsigned short) value);
  4501. write (&v, 2);
  4502. }
  4503. void OutputStream::writeShortBigEndian (short value)
  4504. {
  4505. const unsigned short v = ByteOrder::swapIfLittleEndian ((unsigned short) value);
  4506. write (&v, 2);
  4507. }
  4508. void OutputStream::writeInt (int value)
  4509. {
  4510. const unsigned int v = ByteOrder::swapIfBigEndian ((unsigned int) value);
  4511. write (&v, 4);
  4512. }
  4513. void OutputStream::writeIntBigEndian (int value)
  4514. {
  4515. const unsigned int v = ByteOrder::swapIfLittleEndian ((unsigned int) value);
  4516. write (&v, 4);
  4517. }
  4518. void OutputStream::writeCompressedInt (int value)
  4519. {
  4520. unsigned int un = (value < 0) ? (unsigned int) -value
  4521. : (unsigned int) value;
  4522. uint8 data[5];
  4523. int num = 0;
  4524. while (un > 0)
  4525. {
  4526. data[++num] = (uint8) un;
  4527. un >>= 8;
  4528. }
  4529. data[0] = (uint8) num;
  4530. if (value < 0)
  4531. data[0] |= 0x80;
  4532. write (data, num + 1);
  4533. }
  4534. void OutputStream::writeInt64 (int64 value)
  4535. {
  4536. const uint64 v = ByteOrder::swapIfBigEndian ((uint64) value);
  4537. write (&v, 8);
  4538. }
  4539. void OutputStream::writeInt64BigEndian (int64 value)
  4540. {
  4541. const uint64 v = ByteOrder::swapIfLittleEndian ((uint64) value);
  4542. write (&v, 8);
  4543. }
  4544. void OutputStream::writeFloat (float value)
  4545. {
  4546. union { int asInt; float asFloat; } n;
  4547. n.asFloat = value;
  4548. writeInt (n.asInt);
  4549. }
  4550. void OutputStream::writeFloatBigEndian (float value)
  4551. {
  4552. union { int asInt; float asFloat; } n;
  4553. n.asFloat = value;
  4554. writeIntBigEndian (n.asInt);
  4555. }
  4556. void OutputStream::writeDouble (double value)
  4557. {
  4558. union { int64 asInt; double asDouble; } n;
  4559. n.asDouble = value;
  4560. writeInt64 (n.asInt);
  4561. }
  4562. void OutputStream::writeDoubleBigEndian (double value)
  4563. {
  4564. union { int64 asInt; double asDouble; } n;
  4565. n.asDouble = value;
  4566. writeInt64BigEndian (n.asInt);
  4567. }
  4568. void OutputStream::writeString (const String& text)
  4569. {
  4570. // (This avoids using toUTF8() to prevent the memory bloat that it would leave behind
  4571. // if lots of large, persistent strings were to be written to streams).
  4572. const int numBytes = text.getNumBytesAsUTF8() + 1;
  4573. HeapBlock<char> temp (numBytes);
  4574. text.copyToUTF8 (temp, numBytes);
  4575. write (temp, numBytes);
  4576. }
  4577. void OutputStream::writeText (const String& text, const bool asUnicode,
  4578. const bool writeUnicodeHeaderBytes)
  4579. {
  4580. if (asUnicode)
  4581. {
  4582. if (writeUnicodeHeaderBytes)
  4583. write ("\x0ff\x0fe", 2);
  4584. const juce_wchar* src = text;
  4585. bool lastCharWasReturn = false;
  4586. while (*src != 0)
  4587. {
  4588. if (*src == L'\n' && ! lastCharWasReturn)
  4589. writeShort ((short) L'\r');
  4590. lastCharWasReturn = (*src == L'\r');
  4591. writeShort ((short) *src++);
  4592. }
  4593. }
  4594. else
  4595. {
  4596. const char* src = text.toUTF8();
  4597. const char* t = src;
  4598. for (;;)
  4599. {
  4600. if (*t == '\n')
  4601. {
  4602. if (t > src)
  4603. write (src, (int) (t - src));
  4604. write ("\r\n", 2);
  4605. src = t + 1;
  4606. }
  4607. else if (*t == '\r')
  4608. {
  4609. if (t[1] == '\n')
  4610. ++t;
  4611. }
  4612. else if (*t == 0)
  4613. {
  4614. if (t > src)
  4615. write (src, (int) (t - src));
  4616. break;
  4617. }
  4618. ++t;
  4619. }
  4620. }
  4621. }
  4622. int OutputStream::writeFromInputStream (InputStream& source, int64 numBytesToWrite)
  4623. {
  4624. if (numBytesToWrite < 0)
  4625. numBytesToWrite = std::numeric_limits<int64>::max();
  4626. int numWritten = 0;
  4627. while (numBytesToWrite > 0 && ! source.isExhausted())
  4628. {
  4629. char buffer [8192];
  4630. const int num = source.read (buffer, (int) jmin (numBytesToWrite, (int64) sizeof (buffer)));
  4631. if (num <= 0)
  4632. break;
  4633. write (buffer, num);
  4634. numBytesToWrite -= num;
  4635. numWritten += num;
  4636. }
  4637. return numWritten;
  4638. }
  4639. OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, const int number)
  4640. {
  4641. return stream << String (number);
  4642. }
  4643. OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, const double number)
  4644. {
  4645. return stream << String (number);
  4646. }
  4647. OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, const char character)
  4648. {
  4649. stream.writeByte (character);
  4650. return stream;
  4651. }
  4652. OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, const char* const text)
  4653. {
  4654. stream.write (text, (int) strlen (text));
  4655. return stream;
  4656. }
  4657. OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, const MemoryBlock& data)
  4658. {
  4659. stream.write (data.getData(), (int) data.getSize());
  4660. return stream;
  4661. }
  4662. OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, const File& fileToRead)
  4663. {
  4664. const ScopedPointer<FileInputStream> in (fileToRead.createInputStream());
  4665. if (in != 0)
  4666. stream.writeFromInputStream (*in, -1);
  4667. return stream;
  4668. }
  4669. END_JUCE_NAMESPACE
  4670. /*** End of inlined file: juce_OutputStream.cpp ***/
  4671. /*** Start of inlined file: juce_DirectoryIterator.cpp ***/
  4672. BEGIN_JUCE_NAMESPACE
  4673. DirectoryIterator::DirectoryIterator (const File& directory,
  4674. bool isRecursive_,
  4675. const String& wildCard_,
  4676. const int whatToLookFor_)
  4677. : fileFinder (directory, isRecursive ? "*" : wildCard_),
  4678. wildCard (wildCard_),
  4679. path (File::addTrailingSeparator (directory.getFullPathName())),
  4680. index (-1),
  4681. totalNumFiles (-1),
  4682. whatToLookFor (whatToLookFor_),
  4683. isRecursive (isRecursive_)
  4684. {
  4685. // you have to specify the type of files you're looking for!
  4686. jassert ((whatToLookFor_ & (File::findFiles | File::findDirectories)) != 0);
  4687. jassert (whatToLookFor_ > 0 && whatToLookFor_ <= 7);
  4688. }
  4689. DirectoryIterator::~DirectoryIterator()
  4690. {
  4691. }
  4692. bool DirectoryIterator::next()
  4693. {
  4694. return next (0, 0, 0, 0, 0, 0);
  4695. }
  4696. bool DirectoryIterator::next (bool* const isDirResult, bool* const isHiddenResult, int64* const fileSize,
  4697. Time* const modTime, Time* const creationTime, bool* const isReadOnly)
  4698. {
  4699. if (subIterator != 0)
  4700. {
  4701. if (subIterator->next (isDirResult, isHiddenResult, fileSize, modTime, creationTime, isReadOnly))
  4702. return true;
  4703. subIterator = 0;
  4704. }
  4705. String filename;
  4706. bool isDirectory, isHidden;
  4707. while (fileFinder.next (filename, &isDirectory, &isHidden, fileSize, modTime, creationTime, isReadOnly))
  4708. {
  4709. ++index;
  4710. if (! filename.containsOnly ("."))
  4711. {
  4712. const File fileFound (path + filename, 0);
  4713. bool matches = false;
  4714. if (isDirectory)
  4715. {
  4716. if (isRecursive && ((whatToLookFor & File::ignoreHiddenFiles) == 0 || ! isHidden))
  4717. subIterator = new DirectoryIterator (fileFound, true, wildCard, whatToLookFor);
  4718. matches = (whatToLookFor & File::findDirectories) != 0;
  4719. }
  4720. else
  4721. {
  4722. matches = (whatToLookFor & File::findFiles) != 0;
  4723. }
  4724. // if recursive, we're not relying on the OS iterator to do the wildcard match, so do it now..
  4725. if (matches && isRecursive)
  4726. matches = filename.matchesWildcard (wildCard, ! File::areFileNamesCaseSensitive());
  4727. if (matches && (whatToLookFor & File::ignoreHiddenFiles) != 0)
  4728. matches = ! isHidden;
  4729. if (matches)
  4730. {
  4731. currentFile = fileFound;
  4732. if (isHiddenResult != 0) *isHiddenResult = isHidden;
  4733. if (isDirResult != 0) *isDirResult = isDirectory;
  4734. return true;
  4735. }
  4736. else if (subIterator != 0)
  4737. {
  4738. return next();
  4739. }
  4740. }
  4741. }
  4742. return false;
  4743. }
  4744. const File DirectoryIterator::getFile() const
  4745. {
  4746. if (subIterator != 0)
  4747. return subIterator->getFile();
  4748. return currentFile;
  4749. }
  4750. float DirectoryIterator::getEstimatedProgress() const
  4751. {
  4752. if (totalNumFiles < 0)
  4753. totalNumFiles = File (path).getNumberOfChildFiles (File::findFilesAndDirectories);
  4754. if (totalNumFiles <= 0)
  4755. return 0.0f;
  4756. const float detailedIndex = (subIterator != 0) ? index + subIterator->getEstimatedProgress()
  4757. : (float) index;
  4758. return detailedIndex / totalNumFiles;
  4759. }
  4760. END_JUCE_NAMESPACE
  4761. /*** End of inlined file: juce_DirectoryIterator.cpp ***/
  4762. /*** Start of inlined file: juce_File.cpp ***/
  4763. #if ! JUCE_WINDOWS
  4764. #include <pwd.h>
  4765. #endif
  4766. BEGIN_JUCE_NAMESPACE
  4767. File::File (const String& fullPathName)
  4768. : fullPath (parseAbsolutePath (fullPathName))
  4769. {
  4770. }
  4771. File::File (const String& path, int)
  4772. : fullPath (path)
  4773. {
  4774. }
  4775. const File File::createFileWithoutCheckingPath (const String& path)
  4776. {
  4777. return File (path, 0);
  4778. }
  4779. File::File (const File& other)
  4780. : fullPath (other.fullPath)
  4781. {
  4782. }
  4783. File& File::operator= (const String& newPath)
  4784. {
  4785. fullPath = parseAbsolutePath (newPath);
  4786. return *this;
  4787. }
  4788. File& File::operator= (const File& other)
  4789. {
  4790. fullPath = other.fullPath;
  4791. return *this;
  4792. }
  4793. const File File::nonexistent;
  4794. const String File::parseAbsolutePath (const String& p)
  4795. {
  4796. if (p.isEmpty())
  4797. return String::empty;
  4798. #if JUCE_WINDOWS
  4799. // Windows..
  4800. String path (p.replaceCharacter ('/', '\\'));
  4801. if (path.startsWithChar (File::separator))
  4802. {
  4803. if (path[1] != File::separator)
  4804. {
  4805. /* When you supply a raw string to the File object constructor, it must be an absolute path.
  4806. If you're trying to parse a string that may be either a relative path or an absolute path,
  4807. you MUST provide a context against which the partial path can be evaluated - you can do
  4808. this by simply using File::getChildFile() instead of the File constructor. E.g. saying
  4809. "File::getCurrentWorkingDirectory().getChildFile (myUnknownPath)" would return an absolute
  4810. path if that's what was supplied, or would evaluate a partial path relative to the CWD.
  4811. */
  4812. jassertfalse
  4813. path = File::getCurrentWorkingDirectory().getFullPathName().substring (0, 2) + path;
  4814. }
  4815. }
  4816. else if (! path.containsChar (':'))
  4817. {
  4818. /* When you supply a raw string to the File object constructor, it must be an absolute path.
  4819. If you're trying to parse a string that may be either a relative path or an absolute path,
  4820. you MUST provide a context against which the partial path can be evaluated - you can do
  4821. this by simply using File::getChildFile() instead of the File constructor. E.g. saying
  4822. "File::getCurrentWorkingDirectory().getChildFile (myUnknownPath)" would return an absolute
  4823. path if that's what was supplied, or would evaluate a partial path relative to the CWD.
  4824. */
  4825. jassertfalse
  4826. return File::getCurrentWorkingDirectory().getChildFile (path).getFullPathName();
  4827. }
  4828. #else
  4829. // Mac or Linux..
  4830. String path (p.replaceCharacter ('\\', '/'));
  4831. if (path.startsWithChar ('~'))
  4832. {
  4833. if (path[1] == File::separator || path[1] == 0)
  4834. {
  4835. // expand a name of the form "~/abc"
  4836. path = File::getSpecialLocation (File::userHomeDirectory).getFullPathName()
  4837. + path.substring (1);
  4838. }
  4839. else
  4840. {
  4841. // expand a name of type "~dave/abc"
  4842. const String userName (path.substring (1).upToFirstOccurrenceOf ("/", false, false));
  4843. struct passwd* const pw = getpwnam (userName.toUTF8());
  4844. if (pw != 0)
  4845. path = addTrailingSeparator (pw->pw_dir) + path.fromFirstOccurrenceOf ("/", false, false);
  4846. }
  4847. }
  4848. else if (! path.startsWithChar (File::separator))
  4849. {
  4850. /* When you supply a raw string to the File object constructor, it must be an absolute path.
  4851. If you're trying to parse a string that may be either a relative path or an absolute path,
  4852. you MUST provide a context against which the partial path can be evaluated - you can do
  4853. this by simply using File::getChildFile() instead of the File constructor. E.g. saying
  4854. "File::getCurrentWorkingDirectory().getChildFile (myUnknownPath)" would return an absolute
  4855. path if that's what was supplied, or would evaluate a partial path relative to the CWD.
  4856. */
  4857. jassert (path.startsWith ("./") || path.startsWith ("../")); // (assume that a path "./xyz" is deliberately intended to be relative to the CWD)
  4858. return File::getCurrentWorkingDirectory().getChildFile (path).getFullPathName();
  4859. }
  4860. #endif
  4861. return path.trimCharactersAtEnd (separatorString);
  4862. }
  4863. const String File::addTrailingSeparator (const String& path)
  4864. {
  4865. return path.endsWithChar (File::separator) ? path
  4866. : path + File::separator;
  4867. }
  4868. #if JUCE_LINUX
  4869. #define NAMES_ARE_CASE_SENSITIVE 1
  4870. #endif
  4871. bool File::areFileNamesCaseSensitive()
  4872. {
  4873. #if NAMES_ARE_CASE_SENSITIVE
  4874. return true;
  4875. #else
  4876. return false;
  4877. #endif
  4878. }
  4879. bool File::operator== (const File& other) const
  4880. {
  4881. #if NAMES_ARE_CASE_SENSITIVE
  4882. return fullPath == other.fullPath;
  4883. #else
  4884. return fullPath.equalsIgnoreCase (other.fullPath);
  4885. #endif
  4886. }
  4887. bool File::operator!= (const File& other) const
  4888. {
  4889. return ! operator== (other);
  4890. }
  4891. bool File::operator< (const File& other) const
  4892. {
  4893. #if NAMES_ARE_CASE_SENSITIVE
  4894. return fullPath < other.fullPath;
  4895. #else
  4896. return fullPath.compareIgnoreCase (other.fullPath) < 0;
  4897. #endif
  4898. }
  4899. bool File::operator> (const File& other) const
  4900. {
  4901. #if NAMES_ARE_CASE_SENSITIVE
  4902. return fullPath > other.fullPath;
  4903. #else
  4904. return fullPath.compareIgnoreCase (other.fullPath) > 0;
  4905. #endif
  4906. }
  4907. bool File::setReadOnly (const bool shouldBeReadOnly,
  4908. const bool applyRecursively) const
  4909. {
  4910. bool worked = true;
  4911. if (applyRecursively && isDirectory())
  4912. {
  4913. Array <File> subFiles;
  4914. findChildFiles (subFiles, File::findFilesAndDirectories, false);
  4915. for (int i = subFiles.size(); --i >= 0;)
  4916. worked = subFiles.getReference(i).setReadOnly (shouldBeReadOnly, true) && worked;
  4917. }
  4918. return setFileReadOnlyInternal (shouldBeReadOnly) && worked;
  4919. }
  4920. bool File::deleteRecursively() const
  4921. {
  4922. bool worked = true;
  4923. if (isDirectory())
  4924. {
  4925. Array<File> subFiles;
  4926. findChildFiles (subFiles, File::findFilesAndDirectories, false);
  4927. for (int i = subFiles.size(); --i >= 0;)
  4928. worked = subFiles.getReference(i).deleteRecursively() && worked;
  4929. }
  4930. return deleteFile() && worked;
  4931. }
  4932. bool File::moveFileTo (const File& newFile) const
  4933. {
  4934. if (newFile.fullPath == fullPath)
  4935. return true;
  4936. #if ! NAMES_ARE_CASE_SENSITIVE
  4937. if (*this != newFile)
  4938. #endif
  4939. if (! newFile.deleteFile())
  4940. return false;
  4941. return moveInternal (newFile);
  4942. }
  4943. bool File::copyFileTo (const File& newFile) const
  4944. {
  4945. return (*this == newFile)
  4946. || (exists() && newFile.deleteFile() && copyInternal (newFile));
  4947. }
  4948. bool File::copyDirectoryTo (const File& newDirectory) const
  4949. {
  4950. if (isDirectory() && newDirectory.createDirectory())
  4951. {
  4952. Array<File> subFiles;
  4953. findChildFiles (subFiles, File::findFiles, false);
  4954. int i;
  4955. for (i = 0; i < subFiles.size(); ++i)
  4956. if (! subFiles.getReference(i).copyFileTo (newDirectory.getChildFile (subFiles.getReference(i).getFileName())))
  4957. return false;
  4958. subFiles.clear();
  4959. findChildFiles (subFiles, File::findDirectories, false);
  4960. for (i = 0; i < subFiles.size(); ++i)
  4961. if (! subFiles.getReference(i).copyDirectoryTo (newDirectory.getChildFile (subFiles.getReference(i).getFileName())))
  4962. return false;
  4963. return true;
  4964. }
  4965. return false;
  4966. }
  4967. const String File::getPathUpToLastSlash() const
  4968. {
  4969. const int lastSlash = fullPath.lastIndexOfChar (separator);
  4970. if (lastSlash > 0)
  4971. return fullPath.substring (0, lastSlash);
  4972. else if (lastSlash == 0)
  4973. return separatorString;
  4974. else
  4975. return fullPath;
  4976. }
  4977. const File File::getParentDirectory() const
  4978. {
  4979. return File (getPathUpToLastSlash());
  4980. }
  4981. const String File::getFileName() const
  4982. {
  4983. return fullPath.substring (fullPath.lastIndexOfChar (separator) + 1);
  4984. }
  4985. int File::hashCode() const
  4986. {
  4987. return fullPath.hashCode();
  4988. }
  4989. int64 File::hashCode64() const
  4990. {
  4991. return fullPath.hashCode64();
  4992. }
  4993. const String File::getFileNameWithoutExtension() const
  4994. {
  4995. const int lastSlash = fullPath.lastIndexOfChar (separator) + 1;
  4996. const int lastDot = fullPath.lastIndexOfChar ('.');
  4997. if (lastDot > lastSlash)
  4998. return fullPath.substring (lastSlash, lastDot);
  4999. else
  5000. return fullPath.substring (lastSlash);
  5001. }
  5002. bool File::isAChildOf (const File& potentialParent) const
  5003. {
  5004. if (potentialParent == File::nonexistent)
  5005. return false;
  5006. const String ourPath (getPathUpToLastSlash());
  5007. #if NAMES_ARE_CASE_SENSITIVE
  5008. if (potentialParent.fullPath == ourPath)
  5009. #else
  5010. if (potentialParent.fullPath.equalsIgnoreCase (ourPath))
  5011. #endif
  5012. {
  5013. return true;
  5014. }
  5015. else if (potentialParent.fullPath.length() >= ourPath.length())
  5016. {
  5017. return false;
  5018. }
  5019. else
  5020. {
  5021. return getParentDirectory().isAChildOf (potentialParent);
  5022. }
  5023. }
  5024. bool File::isAbsolutePath (const String& path)
  5025. {
  5026. return path.startsWithChar ('/') || path.startsWithChar ('\\')
  5027. #if JUCE_WINDOWS
  5028. || (path.isNotEmpty() && path[1] == ':');
  5029. #else
  5030. || path.startsWithChar ('~');
  5031. #endif
  5032. }
  5033. const File File::getChildFile (String relativePath) const
  5034. {
  5035. if (isAbsolutePath (relativePath))
  5036. {
  5037. // the path is really absolute..
  5038. return File (relativePath);
  5039. }
  5040. else
  5041. {
  5042. // it's relative, so remove any ../ or ./ bits at the start.
  5043. String path (fullPath);
  5044. if (relativePath[0] == '.')
  5045. {
  5046. #if JUCE_WINDOWS
  5047. relativePath = relativePath.replaceCharacter ('/', '\\').trimStart();
  5048. #else
  5049. relativePath = relativePath.replaceCharacter ('\\', '/').trimStart();
  5050. #endif
  5051. while (relativePath[0] == '.')
  5052. {
  5053. if (relativePath[1] == '.')
  5054. {
  5055. if (relativePath [2] == 0 || relativePath[2] == separator)
  5056. {
  5057. const int lastSlash = path.lastIndexOfChar (separator);
  5058. if (lastSlash >= 0)
  5059. path = path.substring (0, lastSlash);
  5060. relativePath = relativePath.substring (3);
  5061. }
  5062. else
  5063. {
  5064. break;
  5065. }
  5066. }
  5067. else if (relativePath[1] == separator)
  5068. {
  5069. relativePath = relativePath.substring (2);
  5070. }
  5071. else
  5072. {
  5073. break;
  5074. }
  5075. }
  5076. }
  5077. return File (addTrailingSeparator (path) + relativePath);
  5078. }
  5079. }
  5080. const File File::getSiblingFile (const String& fileName) const
  5081. {
  5082. return getParentDirectory().getChildFile (fileName);
  5083. }
  5084. const String File::descriptionOfSizeInBytes (const int64 bytes)
  5085. {
  5086. if (bytes == 1)
  5087. {
  5088. return "1 byte";
  5089. }
  5090. else if (bytes < 1024)
  5091. {
  5092. return String ((int) bytes) + " bytes";
  5093. }
  5094. else if (bytes < 1024 * 1024)
  5095. {
  5096. return String (bytes / 1024.0, 1) + " KB";
  5097. }
  5098. else if (bytes < 1024 * 1024 * 1024)
  5099. {
  5100. return String (bytes / (1024.0 * 1024.0), 1) + " MB";
  5101. }
  5102. else
  5103. {
  5104. return String (bytes / (1024.0 * 1024.0 * 1024.0), 1) + " GB";
  5105. }
  5106. }
  5107. bool File::create() const
  5108. {
  5109. if (exists())
  5110. return true;
  5111. {
  5112. const File parentDir (getParentDirectory());
  5113. if (parentDir == *this || ! parentDir.createDirectory())
  5114. return false;
  5115. FileOutputStream fo (*this, 8);
  5116. }
  5117. return exists();
  5118. }
  5119. bool File::createDirectory() const
  5120. {
  5121. if (! isDirectory())
  5122. {
  5123. const File parentDir (getParentDirectory());
  5124. if (parentDir == *this || ! parentDir.createDirectory())
  5125. return false;
  5126. createDirectoryInternal (fullPath.trimCharactersAtEnd (separatorString));
  5127. return isDirectory();
  5128. }
  5129. return true;
  5130. }
  5131. const Time File::getCreationTime() const
  5132. {
  5133. int64 m, a, c;
  5134. getFileTimesInternal (m, a, c);
  5135. return Time (c);
  5136. }
  5137. const Time File::getLastModificationTime() const
  5138. {
  5139. int64 m, a, c;
  5140. getFileTimesInternal (m, a, c);
  5141. return Time (m);
  5142. }
  5143. const Time File::getLastAccessTime() const
  5144. {
  5145. int64 m, a, c;
  5146. getFileTimesInternal (m, a, c);
  5147. return Time (a);
  5148. }
  5149. bool File::setLastModificationTime (const Time& t) const { return setFileTimesInternal (t.toMilliseconds(), 0, 0); }
  5150. bool File::setLastAccessTime (const Time& t) const { return setFileTimesInternal (0, t.toMilliseconds(), 0); }
  5151. bool File::setCreationTime (const Time& t) const { return setFileTimesInternal (0, 0, t.toMilliseconds()); }
  5152. bool File::loadFileAsData (MemoryBlock& destBlock) const
  5153. {
  5154. if (! existsAsFile())
  5155. return false;
  5156. FileInputStream in (*this);
  5157. return getSize() == in.readIntoMemoryBlock (destBlock);
  5158. }
  5159. const String File::loadFileAsString() const
  5160. {
  5161. if (! existsAsFile())
  5162. return String::empty;
  5163. FileInputStream in (*this);
  5164. return in.readEntireStreamAsString();
  5165. }
  5166. bool File::fileTypeMatches (const int whatToLookFor, const bool isDir, const bool isHidden)
  5167. {
  5168. return (whatToLookFor & (isDir ? findDirectories
  5169. : findFiles)) != 0
  5170. && ((! isHidden) || (whatToLookFor & File::ignoreHiddenFiles) == 0);
  5171. }
  5172. int File::findChildFiles (Array<File>& results,
  5173. const int whatToLookFor,
  5174. const bool searchRecursively,
  5175. const String& wildCardPattern) const
  5176. {
  5177. // you have to specify the type of files you're looking for!
  5178. jassert ((whatToLookFor & (findFiles | findDirectories)) != 0);
  5179. int total = 0;
  5180. if (isDirectory())
  5181. {
  5182. // find child files or directories in this directory first..
  5183. String path (addTrailingSeparator (fullPath)), filename;
  5184. bool itemIsDirectory, itemIsHidden;
  5185. DirectoryIterator::NativeIterator i (path, wildCardPattern);
  5186. while (i.next (filename, &itemIsDirectory, &itemIsHidden, 0, 0, 0, 0))
  5187. {
  5188. if (! filename.containsOnly ("."))
  5189. {
  5190. const File fileFound (path + filename, 0);
  5191. if (fileTypeMatches (whatToLookFor, itemIsDirectory, itemIsHidden))
  5192. {
  5193. results.add (fileFound);
  5194. ++total;
  5195. }
  5196. if (searchRecursively && itemIsDirectory
  5197. && fileTypeMatches (whatToLookFor | findDirectories, true, itemIsHidden))
  5198. {
  5199. total += fileFound.findChildFiles (results, whatToLookFor, true, wildCardPattern);
  5200. }
  5201. }
  5202. }
  5203. }
  5204. return total;
  5205. }
  5206. int File::getNumberOfChildFiles (const int whatToLookFor,
  5207. const String& wildCardPattern) const
  5208. {
  5209. // you have to specify the type of files you're looking for!
  5210. jassert (whatToLookFor > 0 && whatToLookFor <= 3);
  5211. int count = 0;
  5212. if (isDirectory())
  5213. {
  5214. String filename;
  5215. bool itemIsDirectory, itemIsHidden;
  5216. DirectoryIterator::NativeIterator i (*this, wildCardPattern);
  5217. while (i.next (filename, &itemIsDirectory, &itemIsHidden, 0, 0, 0, 0))
  5218. if (fileTypeMatches (whatToLookFor, itemIsDirectory, itemIsHidden)
  5219. && ! filename.containsOnly ("."))
  5220. ++count;
  5221. }
  5222. else
  5223. {
  5224. // trying to search for files inside a non-directory?
  5225. jassertfalse
  5226. }
  5227. return count;
  5228. }
  5229. bool File::containsSubDirectories() const
  5230. {
  5231. if (isDirectory())
  5232. {
  5233. String filename;
  5234. bool itemIsDirectory;
  5235. DirectoryIterator::NativeIterator i (*this, "*");
  5236. while (i.next (filename, &itemIsDirectory, 0, 0, 0, 0, 0))
  5237. if (itemIsDirectory)
  5238. return true;
  5239. }
  5240. return false;
  5241. }
  5242. const File File::getNonexistentChildFile (const String& prefix_,
  5243. const String& suffix,
  5244. bool putNumbersInBrackets) const
  5245. {
  5246. File f (getChildFile (prefix_ + suffix));
  5247. if (f.exists())
  5248. {
  5249. int num = 2;
  5250. String prefix (prefix_);
  5251. // remove any bracketed numbers that may already be on the end..
  5252. if (prefix.trim().endsWithChar (')'))
  5253. {
  5254. putNumbersInBrackets = true;
  5255. const int openBracks = prefix.lastIndexOfChar ('(');
  5256. const int closeBracks = prefix.lastIndexOfChar (')');
  5257. if (openBracks > 0
  5258. && closeBracks > openBracks
  5259. && prefix.substring (openBracks + 1, closeBracks).containsOnly ("0123456789"))
  5260. {
  5261. num = prefix.substring (openBracks + 1, closeBracks).getIntValue() + 1;
  5262. prefix = prefix.substring (0, openBracks);
  5263. }
  5264. }
  5265. // also use brackets if it ends in a digit.
  5266. putNumbersInBrackets = putNumbersInBrackets
  5267. || CharacterFunctions::isDigit (prefix.getLastCharacter());
  5268. do
  5269. {
  5270. if (putNumbersInBrackets)
  5271. f = getChildFile (prefix + '(' + String (num++) + ')' + suffix);
  5272. else
  5273. f = getChildFile (prefix + String (num++) + suffix);
  5274. } while (f.exists());
  5275. }
  5276. return f;
  5277. }
  5278. const File File::getNonexistentSibling (const bool putNumbersInBrackets) const
  5279. {
  5280. if (exists())
  5281. {
  5282. return getParentDirectory()
  5283. .getNonexistentChildFile (getFileNameWithoutExtension(),
  5284. getFileExtension(),
  5285. putNumbersInBrackets);
  5286. }
  5287. else
  5288. {
  5289. return *this;
  5290. }
  5291. }
  5292. const String File::getFileExtension() const
  5293. {
  5294. String ext;
  5295. if (! isDirectory())
  5296. {
  5297. const int indexOfDot = fullPath.lastIndexOfChar ('.');
  5298. if (indexOfDot > fullPath.lastIndexOfChar (separator))
  5299. ext = fullPath.substring (indexOfDot);
  5300. }
  5301. return ext;
  5302. }
  5303. bool File::hasFileExtension (const String& possibleSuffix) const
  5304. {
  5305. if (possibleSuffix.isEmpty())
  5306. return fullPath.lastIndexOfChar ('.') <= fullPath.lastIndexOfChar (separator);
  5307. const int semicolon = possibleSuffix.indexOfChar (0, ';');
  5308. if (semicolon >= 0)
  5309. {
  5310. return hasFileExtension (possibleSuffix.substring (0, semicolon).trimEnd())
  5311. || hasFileExtension (possibleSuffix.substring (semicolon + 1).trimStart());
  5312. }
  5313. else
  5314. {
  5315. if (fullPath.endsWithIgnoreCase (possibleSuffix))
  5316. {
  5317. if (possibleSuffix.startsWithChar ('.'))
  5318. return true;
  5319. const int dotPos = fullPath.length() - possibleSuffix.length() - 1;
  5320. if (dotPos >= 0)
  5321. return fullPath [dotPos] == '.';
  5322. }
  5323. }
  5324. return false;
  5325. }
  5326. const File File::withFileExtension (const String& newExtension) const
  5327. {
  5328. if (fullPath.isEmpty())
  5329. return File::nonexistent;
  5330. String filePart (getFileName());
  5331. int i = filePart.lastIndexOfChar ('.');
  5332. if (i >= 0)
  5333. filePart = filePart.substring (0, i);
  5334. if (newExtension.isNotEmpty() && ! newExtension.startsWithChar ('.'))
  5335. filePart << '.';
  5336. return getSiblingFile (filePart + newExtension);
  5337. }
  5338. bool File::startAsProcess (const String& parameters) const
  5339. {
  5340. return exists() && PlatformUtilities::openDocument (fullPath, parameters);
  5341. }
  5342. FileInputStream* File::createInputStream() const
  5343. {
  5344. if (existsAsFile())
  5345. return new FileInputStream (*this);
  5346. return 0;
  5347. }
  5348. FileOutputStream* File::createOutputStream (const int bufferSize) const
  5349. {
  5350. ScopedPointer <FileOutputStream> out (new FileOutputStream (*this, bufferSize));
  5351. if (out->failedToOpen())
  5352. return 0;
  5353. return out.release();
  5354. }
  5355. bool File::appendData (const void* const dataToAppend,
  5356. const int numberOfBytes) const
  5357. {
  5358. if (numberOfBytes > 0)
  5359. {
  5360. const ScopedPointer <FileOutputStream> out (createOutputStream());
  5361. if (out == 0)
  5362. return false;
  5363. out->write (dataToAppend, numberOfBytes);
  5364. }
  5365. return true;
  5366. }
  5367. bool File::replaceWithData (const void* const dataToWrite,
  5368. const int numberOfBytes) const
  5369. {
  5370. jassert (numberOfBytes >= 0); // a negative number of bytes??
  5371. if (numberOfBytes <= 0)
  5372. return deleteFile();
  5373. TemporaryFile tempFile (*this, TemporaryFile::useHiddenFile);
  5374. tempFile.getFile().appendData (dataToWrite, numberOfBytes);
  5375. return tempFile.overwriteTargetFileWithTemporary();
  5376. }
  5377. bool File::appendText (const String& text,
  5378. const bool asUnicode,
  5379. const bool writeUnicodeHeaderBytes) const
  5380. {
  5381. const ScopedPointer <FileOutputStream> out (createOutputStream());
  5382. if (out != 0)
  5383. {
  5384. out->writeText (text, asUnicode, writeUnicodeHeaderBytes);
  5385. return true;
  5386. }
  5387. return false;
  5388. }
  5389. bool File::replaceWithText (const String& textToWrite,
  5390. const bool asUnicode,
  5391. const bool writeUnicodeHeaderBytes) const
  5392. {
  5393. TemporaryFile tempFile (*this, TemporaryFile::useHiddenFile);
  5394. tempFile.getFile().appendText (textToWrite, asUnicode, writeUnicodeHeaderBytes);
  5395. return tempFile.overwriteTargetFileWithTemporary();
  5396. }
  5397. const String File::createLegalPathName (const String& original)
  5398. {
  5399. String s (original);
  5400. String start;
  5401. if (s[1] == ':')
  5402. {
  5403. start = s.substring (0, 2);
  5404. s = s.substring (2);
  5405. }
  5406. return start + s.removeCharacters ("\"#@,;:<>*^|?")
  5407. .substring (0, 1024);
  5408. }
  5409. const String File::createLegalFileName (const String& original)
  5410. {
  5411. String s (original.removeCharacters ("\"#@,;:<>*^|?\\/"));
  5412. const int maxLength = 128; // only the length of the filename, not the whole path
  5413. const int len = s.length();
  5414. if (len > maxLength)
  5415. {
  5416. const int lastDot = s.lastIndexOfChar ('.');
  5417. if (lastDot > jmax (0, len - 12))
  5418. {
  5419. s = s.substring (0, maxLength - (len - lastDot))
  5420. + s.substring (lastDot);
  5421. }
  5422. else
  5423. {
  5424. s = s.substring (0, maxLength);
  5425. }
  5426. }
  5427. return s;
  5428. }
  5429. const String File::getRelativePathFrom (const File& dir) const
  5430. {
  5431. String thisPath (fullPath);
  5432. {
  5433. int len = thisPath.length();
  5434. while (--len >= 0 && thisPath [len] == File::separator)
  5435. thisPath [len] = 0;
  5436. }
  5437. String dirPath (addTrailingSeparator (dir.existsAsFile() ? dir.getParentDirectory().getFullPathName()
  5438. : dir.fullPath));
  5439. const int len = jmin (thisPath.length(), dirPath.length());
  5440. int commonBitLength = 0;
  5441. for (int i = 0; i < len; ++i)
  5442. {
  5443. #if NAMES_ARE_CASE_SENSITIVE
  5444. if (thisPath[i] != dirPath[i])
  5445. #else
  5446. if (CharacterFunctions::toLowerCase (thisPath[i])
  5447. != CharacterFunctions::toLowerCase (dirPath[i]))
  5448. #endif
  5449. {
  5450. break;
  5451. }
  5452. ++commonBitLength;
  5453. }
  5454. while (commonBitLength > 0 && thisPath [commonBitLength - 1] != File::separator)
  5455. --commonBitLength;
  5456. // if the only common bit is the root, then just return the full path..
  5457. if (commonBitLength <= 0
  5458. || (commonBitLength == 1 && thisPath [1] == File::separator))
  5459. return fullPath;
  5460. thisPath = thisPath.substring (commonBitLength);
  5461. dirPath = dirPath.substring (commonBitLength);
  5462. while (dirPath.isNotEmpty())
  5463. {
  5464. #if JUCE_WINDOWS
  5465. thisPath = "..\\" + thisPath;
  5466. #else
  5467. thisPath = "../" + thisPath;
  5468. #endif
  5469. const int sep = dirPath.indexOfChar (separator);
  5470. if (sep >= 0)
  5471. dirPath = dirPath.substring (sep + 1);
  5472. else
  5473. dirPath = String::empty;
  5474. }
  5475. return thisPath;
  5476. }
  5477. const File File::createTempFile (const String& fileNameEnding)
  5478. {
  5479. const File tempFile (getSpecialLocation (tempDirectory)
  5480. .getChildFile ("temp_" + String (Random::getSystemRandom().nextInt()))
  5481. .withFileExtension (fileNameEnding));
  5482. if (tempFile.exists())
  5483. return createTempFile (fileNameEnding);
  5484. else
  5485. return tempFile;
  5486. }
  5487. END_JUCE_NAMESPACE
  5488. /*** End of inlined file: juce_File.cpp ***/
  5489. /*** Start of inlined file: juce_FileInputStream.cpp ***/
  5490. BEGIN_JUCE_NAMESPACE
  5491. void* juce_fileOpen (const File& file, bool forWriting);
  5492. void juce_fileClose (void* handle);
  5493. int juce_fileRead (void* handle, void* buffer, int size);
  5494. int64 juce_fileSetPosition (void* handle, int64 pos);
  5495. FileInputStream::FileInputStream (const File& f)
  5496. : file (f),
  5497. currentPosition (0),
  5498. needToSeek (true)
  5499. {
  5500. totalSize = f.getSize();
  5501. fileHandle = juce_fileOpen (f, false);
  5502. }
  5503. FileInputStream::~FileInputStream()
  5504. {
  5505. juce_fileClose (fileHandle);
  5506. }
  5507. int64 FileInputStream::getTotalLength()
  5508. {
  5509. return totalSize;
  5510. }
  5511. int FileInputStream::read (void* buffer, int bytesToRead)
  5512. {
  5513. int num = 0;
  5514. if (needToSeek)
  5515. {
  5516. if (juce_fileSetPosition (fileHandle, currentPosition) < 0)
  5517. return 0;
  5518. needToSeek = false;
  5519. }
  5520. num = juce_fileRead (fileHandle, buffer, bytesToRead);
  5521. currentPosition += num;
  5522. return num;
  5523. }
  5524. bool FileInputStream::isExhausted()
  5525. {
  5526. return currentPosition >= totalSize;
  5527. }
  5528. int64 FileInputStream::getPosition()
  5529. {
  5530. return currentPosition;
  5531. }
  5532. bool FileInputStream::setPosition (int64 pos)
  5533. {
  5534. pos = jlimit ((int64) 0, totalSize, pos);
  5535. needToSeek |= (currentPosition != pos);
  5536. currentPosition = pos;
  5537. return true;
  5538. }
  5539. END_JUCE_NAMESPACE
  5540. /*** End of inlined file: juce_FileInputStream.cpp ***/
  5541. /*** Start of inlined file: juce_FileOutputStream.cpp ***/
  5542. BEGIN_JUCE_NAMESPACE
  5543. void* juce_fileOpen (const File& file, bool forWriting);
  5544. void juce_fileClose (void* handle);
  5545. int juce_fileWrite (void* handle, const void* buffer, int size);
  5546. int64 juce_fileSetPosition (void* handle, int64 pos);
  5547. FileOutputStream::FileOutputStream (const File& f,
  5548. const int bufferSize_)
  5549. : file (f),
  5550. bufferSize (bufferSize_),
  5551. bytesInBuffer (0)
  5552. {
  5553. fileHandle = juce_fileOpen (f, true);
  5554. if (fileHandle != 0)
  5555. {
  5556. currentPosition = getPositionInternal();
  5557. if (currentPosition < 0)
  5558. {
  5559. jassertfalse
  5560. juce_fileClose (fileHandle);
  5561. fileHandle = 0;
  5562. }
  5563. }
  5564. buffer.malloc (jmax (bufferSize_, 16));
  5565. }
  5566. FileOutputStream::~FileOutputStream()
  5567. {
  5568. flush();
  5569. juce_fileClose (fileHandle);
  5570. }
  5571. int64 FileOutputStream::getPosition()
  5572. {
  5573. return currentPosition;
  5574. }
  5575. bool FileOutputStream::setPosition (int64 newPosition)
  5576. {
  5577. if (newPosition != currentPosition)
  5578. {
  5579. flush();
  5580. currentPosition = juce_fileSetPosition (fileHandle, newPosition);
  5581. }
  5582. return newPosition == currentPosition;
  5583. }
  5584. void FileOutputStream::flush()
  5585. {
  5586. if (bytesInBuffer > 0)
  5587. {
  5588. juce_fileWrite (fileHandle, buffer, bytesInBuffer);
  5589. bytesInBuffer = 0;
  5590. }
  5591. flushInternal();
  5592. }
  5593. bool FileOutputStream::write (const void* const src, const int numBytes)
  5594. {
  5595. if (bytesInBuffer + numBytes < bufferSize)
  5596. {
  5597. memcpy (buffer + bytesInBuffer, src, numBytes);
  5598. bytesInBuffer += numBytes;
  5599. currentPosition += numBytes;
  5600. }
  5601. else
  5602. {
  5603. if (bytesInBuffer > 0)
  5604. {
  5605. // flush the reservoir
  5606. const bool wroteOk = (juce_fileWrite (fileHandle, buffer, bytesInBuffer) == bytesInBuffer);
  5607. bytesInBuffer = 0;
  5608. if (! wroteOk)
  5609. return false;
  5610. }
  5611. if (numBytes < bufferSize)
  5612. {
  5613. memcpy (buffer + bytesInBuffer, src, numBytes);
  5614. bytesInBuffer += numBytes;
  5615. currentPosition += numBytes;
  5616. }
  5617. else
  5618. {
  5619. const int bytesWritten = juce_fileWrite (fileHandle, src, numBytes);
  5620. currentPosition += bytesWritten;
  5621. return bytesWritten == numBytes;
  5622. }
  5623. }
  5624. return true;
  5625. }
  5626. END_JUCE_NAMESPACE
  5627. /*** End of inlined file: juce_FileOutputStream.cpp ***/
  5628. /*** Start of inlined file: juce_FileSearchPath.cpp ***/
  5629. BEGIN_JUCE_NAMESPACE
  5630. FileSearchPath::FileSearchPath()
  5631. {
  5632. }
  5633. FileSearchPath::FileSearchPath (const String& path)
  5634. {
  5635. init (path);
  5636. }
  5637. FileSearchPath::FileSearchPath (const FileSearchPath& other)
  5638. : directories (other.directories)
  5639. {
  5640. }
  5641. FileSearchPath::~FileSearchPath()
  5642. {
  5643. }
  5644. FileSearchPath& FileSearchPath::operator= (const String& path)
  5645. {
  5646. init (path);
  5647. return *this;
  5648. }
  5649. void FileSearchPath::init (const String& path)
  5650. {
  5651. directories.clear();
  5652. directories.addTokens (path, ";", "\"");
  5653. directories.trim();
  5654. directories.removeEmptyStrings();
  5655. for (int i = directories.size(); --i >= 0;)
  5656. directories.set (i, directories[i].unquoted());
  5657. }
  5658. int FileSearchPath::getNumPaths() const
  5659. {
  5660. return directories.size();
  5661. }
  5662. const File FileSearchPath::operator[] (const int index) const
  5663. {
  5664. return File (directories [index]);
  5665. }
  5666. const String FileSearchPath::toString() const
  5667. {
  5668. StringArray directories2 (directories);
  5669. for (int i = directories2.size(); --i >= 0;)
  5670. if (directories2[i].containsChar (';'))
  5671. directories2.set (i, directories2[i].quoted());
  5672. return directories2.joinIntoString (";");
  5673. }
  5674. void FileSearchPath::add (const File& dir, const int insertIndex)
  5675. {
  5676. directories.insert (insertIndex, dir.getFullPathName());
  5677. }
  5678. void FileSearchPath::addIfNotAlreadyThere (const File& dir)
  5679. {
  5680. for (int i = 0; i < directories.size(); ++i)
  5681. if (File (directories[i]) == dir)
  5682. return;
  5683. add (dir);
  5684. }
  5685. void FileSearchPath::remove (const int index)
  5686. {
  5687. directories.remove (index);
  5688. }
  5689. void FileSearchPath::addPath (const FileSearchPath& other)
  5690. {
  5691. for (int i = 0; i < other.getNumPaths(); ++i)
  5692. addIfNotAlreadyThere (other[i]);
  5693. }
  5694. void FileSearchPath::removeRedundantPaths()
  5695. {
  5696. for (int i = directories.size(); --i >= 0;)
  5697. {
  5698. const File d1 (directories[i]);
  5699. for (int j = directories.size(); --j >= 0;)
  5700. {
  5701. const File d2 (directories[j]);
  5702. if ((i != j) && (d1.isAChildOf (d2) || d1 == d2))
  5703. {
  5704. directories.remove (i);
  5705. break;
  5706. }
  5707. }
  5708. }
  5709. }
  5710. void FileSearchPath::removeNonExistentPaths()
  5711. {
  5712. for (int i = directories.size(); --i >= 0;)
  5713. if (! File (directories[i]).isDirectory())
  5714. directories.remove (i);
  5715. }
  5716. int FileSearchPath::findChildFiles (Array<File>& results,
  5717. const int whatToLookFor,
  5718. const bool searchRecursively,
  5719. const String& wildCardPattern) const
  5720. {
  5721. int total = 0;
  5722. for (int i = 0; i < directories.size(); ++i)
  5723. total += operator[] (i).findChildFiles (results,
  5724. whatToLookFor,
  5725. searchRecursively,
  5726. wildCardPattern);
  5727. return total;
  5728. }
  5729. bool FileSearchPath::isFileInPath (const File& fileToCheck,
  5730. const bool checkRecursively) const
  5731. {
  5732. for (int i = directories.size(); --i >= 0;)
  5733. {
  5734. const File d (directories[i]);
  5735. if (checkRecursively)
  5736. {
  5737. if (fileToCheck.isAChildOf (d))
  5738. return true;
  5739. }
  5740. else
  5741. {
  5742. if (fileToCheck.getParentDirectory() == d)
  5743. return true;
  5744. }
  5745. }
  5746. return false;
  5747. }
  5748. END_JUCE_NAMESPACE
  5749. /*** End of inlined file: juce_FileSearchPath.cpp ***/
  5750. /*** Start of inlined file: juce_NamedPipe.cpp ***/
  5751. BEGIN_JUCE_NAMESPACE
  5752. NamedPipe::NamedPipe()
  5753. : internal (0)
  5754. {
  5755. }
  5756. NamedPipe::~NamedPipe()
  5757. {
  5758. close();
  5759. }
  5760. bool NamedPipe::openExisting (const String& pipeName)
  5761. {
  5762. currentPipeName = pipeName;
  5763. return openInternal (pipeName, false);
  5764. }
  5765. bool NamedPipe::createNewPipe (const String& pipeName)
  5766. {
  5767. currentPipeName = pipeName;
  5768. return openInternal (pipeName, true);
  5769. }
  5770. bool NamedPipe::isOpen() const
  5771. {
  5772. return internal != 0;
  5773. }
  5774. const String NamedPipe::getName() const
  5775. {
  5776. return currentPipeName;
  5777. }
  5778. // other methods for this class are implemented in the platform-specific files
  5779. END_JUCE_NAMESPACE
  5780. /*** End of inlined file: juce_NamedPipe.cpp ***/
  5781. /*** Start of inlined file: juce_TemporaryFile.cpp ***/
  5782. BEGIN_JUCE_NAMESPACE
  5783. TemporaryFile::TemporaryFile (const String& suffix, const int optionFlags)
  5784. {
  5785. createTempFile (File::getSpecialLocation (File::tempDirectory),
  5786. "temp_" + String (Random::getSystemRandom().nextInt()),
  5787. suffix,
  5788. optionFlags);
  5789. }
  5790. TemporaryFile::TemporaryFile (const File& targetFile_, const int optionFlags)
  5791. : targetFile (targetFile_)
  5792. {
  5793. // If you use this constructor, you need to give it a valid target file!
  5794. jassert (targetFile != File::nonexistent);
  5795. createTempFile (targetFile.getParentDirectory(),
  5796. targetFile.getFileNameWithoutExtension() + "_temp" + String (Random::getSystemRandom().nextInt()),
  5797. targetFile.getFileExtension(),
  5798. optionFlags);
  5799. }
  5800. void TemporaryFile::createTempFile (const File& parentDirectory, String name,
  5801. const String& suffix, const int optionFlags)
  5802. {
  5803. if ((optionFlags & useHiddenFile) != 0)
  5804. name = "." + name;
  5805. temporaryFile = parentDirectory.getNonexistentChildFile (name, suffix, (optionFlags & putNumbersInBrackets) != 0);
  5806. }
  5807. TemporaryFile::~TemporaryFile()
  5808. {
  5809. // Have a few attempts at deleting the file before giving up..
  5810. for (int i = 5; --i >= 0;)
  5811. {
  5812. if (temporaryFile.deleteFile())
  5813. return;
  5814. Thread::sleep (50);
  5815. }
  5816. // Failed to delete our temporary file! Check that you've deleted all the
  5817. // file output streams that were using it!
  5818. jassertfalse;
  5819. }
  5820. bool TemporaryFile::overwriteTargetFileWithTemporary() const
  5821. {
  5822. // This method only works if you created this object with the constructor
  5823. // that takes a target file!
  5824. jassert (targetFile != File::nonexistent);
  5825. if (temporaryFile.exists())
  5826. {
  5827. // Have a few attempts at overwriting the file before giving up..
  5828. for (int i = 5; --i >= 0;)
  5829. {
  5830. if (temporaryFile.moveFileTo (targetFile))
  5831. return true;
  5832. Thread::sleep (100);
  5833. }
  5834. }
  5835. else
  5836. {
  5837. // There's no temporary file to use. If your write failed, you should
  5838. // probably check, and not bother calling this method.
  5839. jassertfalse
  5840. }
  5841. return false;
  5842. }
  5843. END_JUCE_NAMESPACE
  5844. /*** End of inlined file: juce_TemporaryFile.cpp ***/
  5845. /*** Start of inlined file: juce_Socket.cpp ***/
  5846. #if JUCE_WINDOWS
  5847. #include <winsock2.h>
  5848. #ifdef _MSC_VER
  5849. #pragma warning (disable : 4127 4389 4018)
  5850. #endif
  5851. #else
  5852. #if JUCE_LINUX
  5853. #include <sys/types.h>
  5854. #include <sys/socket.h>
  5855. #include <sys/errno.h>
  5856. #include <unistd.h>
  5857. #include <netinet/in.h>
  5858. #elif (MACOSX_DEPLOYMENT_TARGET <= MAC_OS_X_VERSION_10_4) && ! JUCE_IPHONE
  5859. #include <CoreServices/CoreServices.h>
  5860. #endif
  5861. #include <fcntl.h>
  5862. #include <netdb.h>
  5863. #include <arpa/inet.h>
  5864. #include <netinet/tcp.h>
  5865. #endif
  5866. BEGIN_JUCE_NAMESPACE
  5867. #if defined (JUCE_LINUX) || defined (JUCE_MAC) || defined (JUCE_IPHONE)
  5868. typedef socklen_t juce_socklen_t;
  5869. #else
  5870. typedef int juce_socklen_t;
  5871. #endif
  5872. #if JUCE_WINDOWS
  5873. typedef int (__stdcall juce_CloseWin32SocketLibCall) (void);
  5874. juce_CloseWin32SocketLibCall* juce_CloseWin32SocketLib = 0;
  5875. static void initWin32Sockets()
  5876. {
  5877. static CriticalSection lock;
  5878. const ScopedLock sl (lock);
  5879. if (juce_CloseWin32SocketLib == 0)
  5880. {
  5881. WSADATA wsaData;
  5882. const WORD wVersionRequested = MAKEWORD (1, 1);
  5883. WSAStartup (wVersionRequested, &wsaData);
  5884. juce_CloseWin32SocketLib = &WSACleanup;
  5885. }
  5886. }
  5887. #endif
  5888. static bool resetSocketOptions (const int handle, const bool isDatagram, const bool allowBroadcast) throw()
  5889. {
  5890. const int sndBufSize = 65536;
  5891. const int rcvBufSize = 65536;
  5892. const int one = 1;
  5893. return handle > 0
  5894. && setsockopt (handle, SOL_SOCKET, SO_RCVBUF, (const char*) &rcvBufSize, sizeof (rcvBufSize)) == 0
  5895. && setsockopt (handle, SOL_SOCKET, SO_SNDBUF, (const char*) &sndBufSize, sizeof (sndBufSize)) == 0
  5896. && (isDatagram ? ((! allowBroadcast) || setsockopt (handle, SOL_SOCKET, SO_BROADCAST, (const char*) &one, sizeof (one)) == 0)
  5897. : (setsockopt (handle, IPPROTO_TCP, TCP_NODELAY, (const char*) &one, sizeof (one)) == 0));
  5898. }
  5899. static bool bindSocketToPort (const int handle, const int port) throw()
  5900. {
  5901. if (handle <= 0 || port <= 0)
  5902. return false;
  5903. struct sockaddr_in servTmpAddr;
  5904. zerostruct (servTmpAddr);
  5905. servTmpAddr.sin_family = PF_INET;
  5906. servTmpAddr.sin_addr.s_addr = htonl (INADDR_ANY);
  5907. servTmpAddr.sin_port = htons ((uint16) port);
  5908. return bind (handle, (struct sockaddr*) &servTmpAddr, sizeof (struct sockaddr_in)) >= 0;
  5909. }
  5910. static int readSocket (const int handle,
  5911. void* const destBuffer, const int maxBytesToRead,
  5912. bool volatile& connected,
  5913. const bool blockUntilSpecifiedAmountHasArrived) throw()
  5914. {
  5915. int bytesRead = 0;
  5916. while (bytesRead < maxBytesToRead)
  5917. {
  5918. int bytesThisTime;
  5919. #if JUCE_WINDOWS
  5920. bytesThisTime = recv (handle, ((char*) destBuffer) + bytesRead, maxBytesToRead - bytesRead, 0);
  5921. #else
  5922. while ((bytesThisTime = (int) ::read (handle, ((char*) destBuffer) + bytesRead, maxBytesToRead - bytesRead)) < 0
  5923. && errno == EINTR
  5924. && connected)
  5925. {
  5926. }
  5927. #endif
  5928. if (bytesThisTime <= 0 || ! connected)
  5929. {
  5930. if (bytesRead == 0)
  5931. bytesRead = -1;
  5932. break;
  5933. }
  5934. bytesRead += bytesThisTime;
  5935. if (! blockUntilSpecifiedAmountHasArrived)
  5936. break;
  5937. }
  5938. return bytesRead;
  5939. }
  5940. static int waitForReadiness (const int handle, const bool forReading,
  5941. const int timeoutMsecs) throw()
  5942. {
  5943. struct timeval timeout;
  5944. struct timeval* timeoutp;
  5945. if (timeoutMsecs >= 0)
  5946. {
  5947. timeout.tv_sec = timeoutMsecs / 1000;
  5948. timeout.tv_usec = (timeoutMsecs % 1000) * 1000;
  5949. timeoutp = &timeout;
  5950. }
  5951. else
  5952. {
  5953. timeoutp = 0;
  5954. }
  5955. fd_set rset, wset;
  5956. FD_ZERO (&rset);
  5957. FD_SET (handle, &rset);
  5958. FD_ZERO (&wset);
  5959. FD_SET (handle, &wset);
  5960. fd_set* const prset = forReading ? &rset : 0;
  5961. fd_set* const pwset = forReading ? 0 : &wset;
  5962. #if JUCE_WINDOWS
  5963. if (select (handle + 1, prset, pwset, 0, timeoutp) < 0)
  5964. return -1;
  5965. #else
  5966. {
  5967. int result;
  5968. while ((result = select (handle + 1, prset, pwset, 0, timeoutp)) < 0
  5969. && errno == EINTR)
  5970. {
  5971. }
  5972. if (result < 0)
  5973. return -1;
  5974. }
  5975. #endif
  5976. {
  5977. int opt;
  5978. juce_socklen_t len = sizeof (opt);
  5979. if (getsockopt (handle, SOL_SOCKET, SO_ERROR, (char*) &opt, &len) < 0
  5980. || opt != 0)
  5981. return -1;
  5982. }
  5983. if ((forReading && FD_ISSET (handle, &rset))
  5984. || ((! forReading) && FD_ISSET (handle, &wset)))
  5985. return 1;
  5986. return 0;
  5987. }
  5988. static bool setSocketBlockingState (const int handle, const bool shouldBlock) throw()
  5989. {
  5990. #if JUCE_WINDOWS
  5991. u_long nonBlocking = shouldBlock ? 0 : 1;
  5992. if (ioctlsocket (handle, FIONBIO, &nonBlocking) != 0)
  5993. return false;
  5994. #else
  5995. int socketFlags = fcntl (handle, F_GETFL, 0);
  5996. if (socketFlags == -1)
  5997. return false;
  5998. if (shouldBlock)
  5999. socketFlags &= ~O_NONBLOCK;
  6000. else
  6001. socketFlags |= O_NONBLOCK;
  6002. if (fcntl (handle, F_SETFL, socketFlags) != 0)
  6003. return false;
  6004. #endif
  6005. return true;
  6006. }
  6007. static bool connectSocket (int volatile& handle,
  6008. const bool isDatagram,
  6009. void** serverAddress,
  6010. const String& hostName,
  6011. const int portNumber,
  6012. const int timeOutMillisecs) throw()
  6013. {
  6014. struct hostent* const hostEnt = gethostbyname (hostName.toUTF8());
  6015. if (hostEnt == 0)
  6016. return false;
  6017. struct in_addr targetAddress;
  6018. memcpy (&targetAddress.s_addr,
  6019. *(hostEnt->h_addr_list),
  6020. sizeof (targetAddress.s_addr));
  6021. struct sockaddr_in servTmpAddr;
  6022. zerostruct (servTmpAddr);
  6023. servTmpAddr.sin_family = PF_INET;
  6024. servTmpAddr.sin_addr = targetAddress;
  6025. servTmpAddr.sin_port = htons ((uint16) portNumber);
  6026. if (handle < 0)
  6027. handle = (int) socket (AF_INET, isDatagram ? SOCK_DGRAM : SOCK_STREAM, 0);
  6028. if (handle < 0)
  6029. return false;
  6030. if (isDatagram)
  6031. {
  6032. *serverAddress = new struct sockaddr_in();
  6033. *((struct sockaddr_in*) *serverAddress) = servTmpAddr;
  6034. return true;
  6035. }
  6036. setSocketBlockingState (handle, false);
  6037. const int result = ::connect (handle, (struct sockaddr*) &servTmpAddr, sizeof (struct sockaddr_in));
  6038. if (result < 0)
  6039. {
  6040. #if JUCE_WINDOWS
  6041. if (result == SOCKET_ERROR && WSAGetLastError() == WSAEWOULDBLOCK)
  6042. #else
  6043. if (errno == EINPROGRESS)
  6044. #endif
  6045. {
  6046. if (waitForReadiness (handle, false, timeOutMillisecs) != 1)
  6047. {
  6048. setSocketBlockingState (handle, true);
  6049. return false;
  6050. }
  6051. }
  6052. }
  6053. setSocketBlockingState (handle, true);
  6054. resetSocketOptions (handle, false, false);
  6055. return true;
  6056. }
  6057. StreamingSocket::StreamingSocket()
  6058. : portNumber (0),
  6059. handle (-1),
  6060. connected (false),
  6061. isListener (false)
  6062. {
  6063. #if JUCE_WINDOWS
  6064. initWin32Sockets();
  6065. #endif
  6066. }
  6067. StreamingSocket::StreamingSocket (const String& hostName_,
  6068. const int portNumber_,
  6069. const int handle_)
  6070. : hostName (hostName_),
  6071. portNumber (portNumber_),
  6072. handle (handle_),
  6073. connected (true),
  6074. isListener (false)
  6075. {
  6076. #if JUCE_WINDOWS
  6077. initWin32Sockets();
  6078. #endif
  6079. resetSocketOptions (handle_, false, false);
  6080. }
  6081. StreamingSocket::~StreamingSocket()
  6082. {
  6083. close();
  6084. }
  6085. int StreamingSocket::read (void* destBuffer, const int maxBytesToRead, const bool blockUntilSpecifiedAmountHasArrived)
  6086. {
  6087. return (connected && ! isListener) ? readSocket (handle, destBuffer, maxBytesToRead, connected, blockUntilSpecifiedAmountHasArrived)
  6088. : -1;
  6089. }
  6090. int StreamingSocket::write (const void* sourceBuffer, const int numBytesToWrite)
  6091. {
  6092. if (isListener || ! connected)
  6093. return -1;
  6094. #if JUCE_WINDOWS
  6095. return send (handle, (const char*) sourceBuffer, numBytesToWrite, 0);
  6096. #else
  6097. int result;
  6098. while ((result = (int) ::write (handle, sourceBuffer, numBytesToWrite)) < 0
  6099. && errno == EINTR)
  6100. {
  6101. }
  6102. return result;
  6103. #endif
  6104. }
  6105. int StreamingSocket::waitUntilReady (const bool readyForReading,
  6106. const int timeoutMsecs) const
  6107. {
  6108. return connected ? waitForReadiness (handle, readyForReading, timeoutMsecs)
  6109. : -1;
  6110. }
  6111. bool StreamingSocket::bindToPort (const int port)
  6112. {
  6113. return bindSocketToPort (handle, port);
  6114. }
  6115. bool StreamingSocket::connect (const String& remoteHostName,
  6116. const int remotePortNumber,
  6117. const int timeOutMillisecs)
  6118. {
  6119. if (isListener)
  6120. {
  6121. jassertfalse // a listener socket can't connect to another one!
  6122. return false;
  6123. }
  6124. if (connected)
  6125. close();
  6126. hostName = remoteHostName;
  6127. portNumber = remotePortNumber;
  6128. isListener = false;
  6129. connected = connectSocket (handle, false, 0, remoteHostName,
  6130. remotePortNumber, timeOutMillisecs);
  6131. if (! (connected && resetSocketOptions (handle, false, false)))
  6132. {
  6133. close();
  6134. return false;
  6135. }
  6136. return true;
  6137. }
  6138. void StreamingSocket::close()
  6139. {
  6140. #if JUCE_WINDOWS
  6141. if (handle != SOCKET_ERROR || connected)
  6142. closesocket (handle);
  6143. connected = false;
  6144. #else
  6145. if (connected)
  6146. {
  6147. connected = false;
  6148. if (isListener)
  6149. {
  6150. // need to do this to interrupt the accept() function..
  6151. StreamingSocket temp;
  6152. temp.connect ("localhost", portNumber, 1000);
  6153. }
  6154. }
  6155. if (handle != -1)
  6156. ::close (handle);
  6157. #endif
  6158. hostName = String::empty;
  6159. portNumber = 0;
  6160. handle = -1;
  6161. isListener = false;
  6162. }
  6163. bool StreamingSocket::createListener (const int newPortNumber, const String& localHostName)
  6164. {
  6165. if (connected)
  6166. close();
  6167. hostName = "listener";
  6168. portNumber = newPortNumber;
  6169. isListener = true;
  6170. struct sockaddr_in servTmpAddr;
  6171. zerostruct (servTmpAddr);
  6172. servTmpAddr.sin_family = PF_INET;
  6173. servTmpAddr.sin_addr.s_addr = htonl (INADDR_ANY);
  6174. if (localHostName.isNotEmpty())
  6175. servTmpAddr.sin_addr.s_addr = ::inet_addr (localHostName.toUTF8());
  6176. servTmpAddr.sin_port = htons ((uint16) portNumber);
  6177. handle = (int) socket (AF_INET, SOCK_STREAM, 0);
  6178. if (handle < 0)
  6179. return false;
  6180. const int reuse = 1;
  6181. setsockopt (handle, SOL_SOCKET, SO_REUSEADDR, (const char*) &reuse, sizeof (reuse));
  6182. if (bind (handle, (struct sockaddr*) &servTmpAddr, sizeof (struct sockaddr_in)) < 0
  6183. || listen (handle, SOMAXCONN) < 0)
  6184. {
  6185. close();
  6186. return false;
  6187. }
  6188. connected = true;
  6189. return true;
  6190. }
  6191. StreamingSocket* StreamingSocket::waitForNextConnection() const
  6192. {
  6193. jassert (isListener || ! connected); // to call this method, you first have to use createListener() to
  6194. // prepare this socket as a listener.
  6195. if (connected && isListener)
  6196. {
  6197. struct sockaddr address;
  6198. juce_socklen_t len = sizeof (sockaddr);
  6199. const int newSocket = (int) accept (handle, &address, &len);
  6200. if (newSocket >= 0 && connected)
  6201. return new StreamingSocket (inet_ntoa (((struct sockaddr_in*) &address)->sin_addr),
  6202. portNumber, newSocket);
  6203. }
  6204. return 0;
  6205. }
  6206. bool StreamingSocket::isLocal() const throw()
  6207. {
  6208. return hostName == "127.0.0.1";
  6209. }
  6210. DatagramSocket::DatagramSocket (const int localPortNumber, const bool allowBroadcast_)
  6211. : portNumber (0),
  6212. handle (-1),
  6213. connected (true),
  6214. allowBroadcast (allowBroadcast_),
  6215. serverAddress (0)
  6216. {
  6217. #if JUCE_WINDOWS
  6218. initWin32Sockets();
  6219. #endif
  6220. handle = (int) socket (AF_INET, SOCK_DGRAM, 0);
  6221. bindToPort (localPortNumber);
  6222. }
  6223. DatagramSocket::DatagramSocket (const String& hostName_, const int portNumber_,
  6224. const int handle_, const int localPortNumber)
  6225. : hostName (hostName_),
  6226. portNumber (portNumber_),
  6227. handle (handle_),
  6228. connected (true),
  6229. allowBroadcast (false),
  6230. serverAddress (0)
  6231. {
  6232. #if JUCE_WINDOWS
  6233. initWin32Sockets();
  6234. #endif
  6235. resetSocketOptions (handle_, true, allowBroadcast);
  6236. bindToPort (localPortNumber);
  6237. }
  6238. DatagramSocket::~DatagramSocket()
  6239. {
  6240. close();
  6241. delete ((struct sockaddr_in*) serverAddress);
  6242. serverAddress = 0;
  6243. }
  6244. void DatagramSocket::close()
  6245. {
  6246. #if JUCE_WINDOWS
  6247. closesocket (handle);
  6248. connected = false;
  6249. #else
  6250. connected = false;
  6251. ::close (handle);
  6252. #endif
  6253. hostName = String::empty;
  6254. portNumber = 0;
  6255. handle = -1;
  6256. }
  6257. bool DatagramSocket::bindToPort (const int port)
  6258. {
  6259. return bindSocketToPort (handle, port);
  6260. }
  6261. bool DatagramSocket::connect (const String& remoteHostName,
  6262. const int remotePortNumber,
  6263. const int timeOutMillisecs)
  6264. {
  6265. if (connected)
  6266. close();
  6267. hostName = remoteHostName;
  6268. portNumber = remotePortNumber;
  6269. connected = connectSocket (handle, true, &serverAddress,
  6270. remoteHostName, remotePortNumber,
  6271. timeOutMillisecs);
  6272. if (! (connected && resetSocketOptions (handle, true, allowBroadcast)))
  6273. {
  6274. close();
  6275. return false;
  6276. }
  6277. return true;
  6278. }
  6279. DatagramSocket* DatagramSocket::waitForNextConnection() const
  6280. {
  6281. struct sockaddr address;
  6282. juce_socklen_t len = sizeof (sockaddr);
  6283. while (waitUntilReady (true, -1) == 1)
  6284. {
  6285. char buf[1];
  6286. if (recvfrom (handle, buf, 0, 0, &address, &len) > 0)
  6287. {
  6288. return new DatagramSocket (inet_ntoa (((struct sockaddr_in*) &address)->sin_addr),
  6289. ntohs (((struct sockaddr_in*) &address)->sin_port),
  6290. -1, -1);
  6291. }
  6292. }
  6293. return 0;
  6294. }
  6295. int DatagramSocket::waitUntilReady (const bool readyForReading,
  6296. const int timeoutMsecs) const
  6297. {
  6298. return connected ? waitForReadiness (handle, readyForReading, timeoutMsecs)
  6299. : -1;
  6300. }
  6301. int DatagramSocket::read (void* destBuffer, const int maxBytesToRead, const bool blockUntilSpecifiedAmountHasArrived)
  6302. {
  6303. return connected ? readSocket (handle, destBuffer, maxBytesToRead, connected, blockUntilSpecifiedAmountHasArrived)
  6304. : -1;
  6305. }
  6306. int DatagramSocket::write (const void* sourceBuffer, const int numBytesToWrite)
  6307. {
  6308. // You need to call connect() first to set the server address..
  6309. jassert (serverAddress != 0 && connected);
  6310. return connected ? (int) sendto (handle, (const char*) sourceBuffer,
  6311. numBytesToWrite, 0,
  6312. (const struct sockaddr*) serverAddress,
  6313. sizeof (struct sockaddr_in))
  6314. : -1;
  6315. }
  6316. bool DatagramSocket::isLocal() const throw()
  6317. {
  6318. return hostName == "127.0.0.1";
  6319. }
  6320. END_JUCE_NAMESPACE
  6321. /*** End of inlined file: juce_Socket.cpp ***/
  6322. /*** Start of inlined file: juce_URL.cpp ***/
  6323. BEGIN_JUCE_NAMESPACE
  6324. URL::URL()
  6325. {
  6326. }
  6327. URL::URL (const String& url_)
  6328. : url (url_)
  6329. {
  6330. int i = url.indexOfChar ('?');
  6331. if (i >= 0)
  6332. {
  6333. do
  6334. {
  6335. const int nextAmp = url.indexOfChar (i + 1, '&');
  6336. const int equalsPos = url.indexOfChar (i + 1, '=');
  6337. if (equalsPos > i + 1)
  6338. {
  6339. if (nextAmp < 0)
  6340. {
  6341. parameters.set (removeEscapeChars (url.substring (i + 1, equalsPos)),
  6342. removeEscapeChars (url.substring (equalsPos + 1)));
  6343. }
  6344. else if (nextAmp > 0 && equalsPos < nextAmp)
  6345. {
  6346. parameters.set (removeEscapeChars (url.substring (i + 1, equalsPos)),
  6347. removeEscapeChars (url.substring (equalsPos + 1, nextAmp)));
  6348. }
  6349. }
  6350. i = nextAmp;
  6351. }
  6352. while (i >= 0);
  6353. url = url.upToFirstOccurrenceOf ("?", false, false);
  6354. }
  6355. }
  6356. URL::URL (const URL& other)
  6357. : url (other.url),
  6358. postData (other.postData),
  6359. parameters (other.parameters),
  6360. filesToUpload (other.filesToUpload),
  6361. mimeTypes (other.mimeTypes)
  6362. {
  6363. }
  6364. URL& URL::operator= (const URL& other)
  6365. {
  6366. url = other.url;
  6367. postData = other.postData;
  6368. parameters = other.parameters;
  6369. filesToUpload = other.filesToUpload;
  6370. mimeTypes = other.mimeTypes;
  6371. return *this;
  6372. }
  6373. URL::~URL()
  6374. {
  6375. }
  6376. static const String getMangledParameters (const StringPairArray& parameters)
  6377. {
  6378. String p;
  6379. for (int i = 0; i < parameters.size(); ++i)
  6380. {
  6381. if (i > 0)
  6382. p += '&';
  6383. p << URL::addEscapeChars (parameters.getAllKeys() [i], true)
  6384. << '='
  6385. << URL::addEscapeChars (parameters.getAllValues() [i], true);
  6386. }
  6387. return p;
  6388. }
  6389. const String URL::toString (const bool includeGetParameters) const
  6390. {
  6391. if (includeGetParameters && parameters.size() > 0)
  6392. return url + "?" + getMangledParameters (parameters);
  6393. else
  6394. return url;
  6395. }
  6396. bool URL::isWellFormed() const
  6397. {
  6398. //xxx TODO
  6399. return url.isNotEmpty();
  6400. }
  6401. static int findStartOfDomain (const String& url)
  6402. {
  6403. int i = 0;
  6404. while (CharacterFunctions::isLetterOrDigit (url[i])
  6405. || CharacterFunctions::indexOfChar (L"+-.", url[i], false) >= 0)
  6406. ++i;
  6407. return url[i] == ':' ? i + 1 : 0;
  6408. }
  6409. const String URL::getDomain() const
  6410. {
  6411. int start = findStartOfDomain (url);
  6412. while (url[start] == '/')
  6413. ++start;
  6414. const int end1 = url.indexOfChar (start, '/');
  6415. const int end2 = url.indexOfChar (start, ':');
  6416. const int end = (end1 < 0 || end2 < 0) ? jmax (end1, end2)
  6417. : jmin (end1, end2);
  6418. return url.substring (start, end);
  6419. }
  6420. const String URL::getSubPath() const
  6421. {
  6422. int start = findStartOfDomain (url);
  6423. while (url[start] == '/')
  6424. ++start;
  6425. const int startOfPath = url.indexOfChar (start, '/') + 1;
  6426. return startOfPath <= 0 ? String::empty
  6427. : url.substring (startOfPath);
  6428. }
  6429. const String URL::getScheme() const
  6430. {
  6431. return url.substring (0, findStartOfDomain (url) - 1);
  6432. }
  6433. const URL URL::withNewSubPath (const String& newPath) const
  6434. {
  6435. int start = findStartOfDomain (url);
  6436. while (url[start] == '/')
  6437. ++start;
  6438. const int startOfPath = url.indexOfChar (start, '/') + 1;
  6439. URL u (*this);
  6440. if (startOfPath > 0)
  6441. u.url = url.substring (0, startOfPath);
  6442. if (! u.url.endsWithChar ('/'))
  6443. u.url << '/';
  6444. if (newPath.startsWithChar ('/'))
  6445. u.url << newPath.substring (1);
  6446. else
  6447. u.url << newPath;
  6448. return u;
  6449. }
  6450. bool URL::isProbablyAWebsiteURL (const String& possibleURL)
  6451. {
  6452. if (possibleURL.startsWithIgnoreCase ("http:")
  6453. || possibleURL.startsWithIgnoreCase ("ftp:"))
  6454. return true;
  6455. if (possibleURL.startsWithIgnoreCase ("file:")
  6456. || possibleURL.containsChar ('@')
  6457. || possibleURL.endsWithChar ('.')
  6458. || (! possibleURL.containsChar ('.')))
  6459. return false;
  6460. if (possibleURL.startsWithIgnoreCase ("www.")
  6461. && possibleURL.substring (5).containsChar ('.'))
  6462. return true;
  6463. const char* commonTLDs[] = { "com", "net", "org", "uk", "de", "fr", "jp" };
  6464. for (int i = 0; i < numElementsInArray (commonTLDs); ++i)
  6465. if ((possibleURL + "/").containsIgnoreCase ("." + String (commonTLDs[i]) + "/"))
  6466. return true;
  6467. return false;
  6468. }
  6469. bool URL::isProbablyAnEmailAddress (const String& possibleEmailAddress)
  6470. {
  6471. const int atSign = possibleEmailAddress.indexOfChar ('@');
  6472. return atSign > 0
  6473. && possibleEmailAddress.lastIndexOfChar ('.') > (atSign + 1)
  6474. && (! possibleEmailAddress.endsWithChar ('.'));
  6475. }
  6476. void* juce_openInternetFile (const String& url,
  6477. const String& headers,
  6478. const MemoryBlock& optionalPostData,
  6479. const bool isPost,
  6480. URL::OpenStreamProgressCallback* callback,
  6481. void* callbackContext,
  6482. int timeOutMs);
  6483. void juce_closeInternetFile (void* handle);
  6484. int juce_readFromInternetFile (void* handle, void* dest, int bytesToRead);
  6485. int juce_seekInInternetFile (void* handle, int newPosition);
  6486. int64 juce_getInternetFileContentLength (void* handle);
  6487. class WebInputStream : public InputStream
  6488. {
  6489. public:
  6490. WebInputStream (const URL& url,
  6491. const bool isPost_,
  6492. URL::OpenStreamProgressCallback* const progressCallback_,
  6493. void* const progressCallbackContext_,
  6494. const String& extraHeaders,
  6495. int timeOutMs_)
  6496. : position (0),
  6497. finished (false),
  6498. isPost (isPost_),
  6499. progressCallback (progressCallback_),
  6500. progressCallbackContext (progressCallbackContext_),
  6501. timeOutMs (timeOutMs_)
  6502. {
  6503. server = url.toString (! isPost);
  6504. if (isPost_)
  6505. createHeadersAndPostData (url);
  6506. headers += extraHeaders;
  6507. if (! headers.endsWithChar ('\n'))
  6508. headers << "\r\n";
  6509. handle = juce_openInternetFile (server, headers, postData, isPost,
  6510. progressCallback_, progressCallbackContext_,
  6511. timeOutMs);
  6512. }
  6513. ~WebInputStream()
  6514. {
  6515. juce_closeInternetFile (handle);
  6516. }
  6517. bool isError() const { return handle == 0; }
  6518. int64 getTotalLength() { return juce_getInternetFileContentLength (handle); }
  6519. bool isExhausted() { return finished; }
  6520. int64 getPosition() { return position; }
  6521. int read (void* dest, int bytes)
  6522. {
  6523. if (finished || isError())
  6524. {
  6525. return 0;
  6526. }
  6527. else
  6528. {
  6529. const int bytesRead = juce_readFromInternetFile (handle, dest, bytes);
  6530. position += bytesRead;
  6531. if (bytesRead == 0)
  6532. finished = true;
  6533. return bytesRead;
  6534. }
  6535. }
  6536. bool setPosition (int64 wantedPos)
  6537. {
  6538. if (wantedPos != position)
  6539. {
  6540. finished = false;
  6541. const int actualPos = juce_seekInInternetFile (handle, (int) wantedPos);
  6542. if (actualPos == wantedPos)
  6543. {
  6544. position = wantedPos;
  6545. }
  6546. else
  6547. {
  6548. if (wantedPos < position)
  6549. {
  6550. juce_closeInternetFile (handle);
  6551. position = 0;
  6552. finished = false;
  6553. handle = juce_openInternetFile (server, headers, postData, isPost,
  6554. progressCallback, progressCallbackContext,
  6555. timeOutMs);
  6556. }
  6557. skipNextBytes (wantedPos - position);
  6558. }
  6559. }
  6560. return true;
  6561. }
  6562. juce_UseDebuggingNewOperator
  6563. private:
  6564. String server, headers;
  6565. MemoryBlock postData;
  6566. int64 position;
  6567. bool finished;
  6568. const bool isPost;
  6569. void* handle;
  6570. URL::OpenStreamProgressCallback* const progressCallback;
  6571. void* const progressCallbackContext;
  6572. const int timeOutMs;
  6573. void createHeadersAndPostData (const URL& url)
  6574. {
  6575. MemoryOutputStream data (256, 256, &postData);
  6576. if (url.getFilesToUpload().size() > 0)
  6577. {
  6578. // need to upload some files, so do it as multi-part...
  6579. const String boundary (String::toHexString (Random::getSystemRandom().nextInt64()));
  6580. headers << "Content-Type: multipart/form-data; boundary=" << boundary << "\r\n";
  6581. data << "--" << boundary;
  6582. int i;
  6583. for (i = 0; i < url.getParameters().size(); ++i)
  6584. {
  6585. data << "\r\nContent-Disposition: form-data; name=\""
  6586. << url.getParameters().getAllKeys() [i]
  6587. << "\"\r\n\r\n"
  6588. << url.getParameters().getAllValues() [i]
  6589. << "\r\n--"
  6590. << boundary;
  6591. }
  6592. for (i = 0; i < url.getFilesToUpload().size(); ++i)
  6593. {
  6594. const File file (url.getFilesToUpload().getAllValues() [i]);
  6595. const String paramName (url.getFilesToUpload().getAllKeys() [i]);
  6596. data << "\r\nContent-Disposition: form-data; name=\"" << paramName
  6597. << "\"; filename=\"" << file.getFileName() << "\"\r\n";
  6598. const String mimeType (url.getMimeTypesOfUploadFiles()
  6599. .getValue (paramName, String::empty));
  6600. if (mimeType.isNotEmpty())
  6601. data << "Content-Type: " << mimeType << "\r\n";
  6602. data << "Content-Transfer-Encoding: binary\r\n\r\n"
  6603. << file << "\r\n--" << boundary;
  6604. }
  6605. data << "--\r\n";
  6606. }
  6607. else
  6608. {
  6609. data << getMangledParameters (url.getParameters())
  6610. << url.getPostData();
  6611. // just a short text attachment, so use simple url encoding..
  6612. headers = "Content-Type: application/x-www-form-urlencoded\r\nContent-length: "
  6613. + String ((unsigned int) postData.getSize())
  6614. + "\r\n";
  6615. }
  6616. }
  6617. WebInputStream (const WebInputStream&);
  6618. WebInputStream& operator= (const WebInputStream&);
  6619. };
  6620. InputStream* URL::createInputStream (const bool usePostCommand,
  6621. OpenStreamProgressCallback* const progressCallback,
  6622. void* const progressCallbackContext,
  6623. const String& extraHeaders,
  6624. const int timeOutMs) const
  6625. {
  6626. ScopedPointer <WebInputStream> wi (new WebInputStream (*this, usePostCommand,
  6627. progressCallback, progressCallbackContext,
  6628. extraHeaders,
  6629. timeOutMs));
  6630. return wi->isError() ? 0 : wi.release();
  6631. }
  6632. bool URL::readEntireBinaryStream (MemoryBlock& destData,
  6633. const bool usePostCommand) const
  6634. {
  6635. const ScopedPointer <InputStream> in (createInputStream (usePostCommand));
  6636. if (in != 0)
  6637. {
  6638. in->readIntoMemoryBlock (destData, -1);
  6639. return true;
  6640. }
  6641. return false;
  6642. }
  6643. const String URL::readEntireTextStream (const bool usePostCommand) const
  6644. {
  6645. const ScopedPointer <InputStream> in (createInputStream (usePostCommand));
  6646. if (in != 0)
  6647. return in->readEntireStreamAsString();
  6648. return String::empty;
  6649. }
  6650. XmlElement* URL::readEntireXmlStream (const bool usePostCommand) const
  6651. {
  6652. XmlDocument doc (readEntireTextStream (usePostCommand));
  6653. return doc.getDocumentElement();
  6654. }
  6655. const URL URL::withParameter (const String& parameterName,
  6656. const String& parameterValue) const
  6657. {
  6658. URL u (*this);
  6659. u.parameters.set (parameterName, parameterValue);
  6660. return u;
  6661. }
  6662. const URL URL::withFileToUpload (const String& parameterName,
  6663. const File& fileToUpload,
  6664. const String& mimeType) const
  6665. {
  6666. jassert (mimeType.isNotEmpty()); // You need to supply a mime type!
  6667. URL u (*this);
  6668. u.filesToUpload.set (parameterName, fileToUpload.getFullPathName());
  6669. u.mimeTypes.set (parameterName, mimeType);
  6670. return u;
  6671. }
  6672. const URL URL::withPOSTData (const String& postData_) const
  6673. {
  6674. URL u (*this);
  6675. u.postData = postData_;
  6676. return u;
  6677. }
  6678. const StringPairArray& URL::getParameters() const
  6679. {
  6680. return parameters;
  6681. }
  6682. const StringPairArray& URL::getFilesToUpload() const
  6683. {
  6684. return filesToUpload;
  6685. }
  6686. const StringPairArray& URL::getMimeTypesOfUploadFiles() const
  6687. {
  6688. return mimeTypes;
  6689. }
  6690. const String URL::removeEscapeChars (const String& s)
  6691. {
  6692. String result (s.replaceCharacter ('+', ' '));
  6693. int nextPercent = 0;
  6694. for (;;)
  6695. {
  6696. nextPercent = result.indexOfChar (nextPercent, '%');
  6697. if (nextPercent < 0)
  6698. break;
  6699. juce_wchar replacementChar = (juce_wchar) result.substring (nextPercent + 1, nextPercent + 3).getHexValue32();
  6700. result = result.replaceSection (nextPercent, 3, String::charToString (replacementChar));
  6701. ++nextPercent;
  6702. }
  6703. return result;
  6704. }
  6705. const String URL::addEscapeChars (const String& s, const bool isParameter)
  6706. {
  6707. String result;
  6708. result.preallocateStorage (s.length() + 8);
  6709. const char* utf8 = s.toUTF8();
  6710. const char* legalChars = isParameter ? "_-.*!'()"
  6711. : "_-$.*!'(),";
  6712. while (*utf8 != 0)
  6713. {
  6714. const char c = *utf8++;
  6715. if (CharacterFunctions::isLetterOrDigit (c)
  6716. || CharacterFunctions::indexOfChar (legalChars, c, false) >= 0)
  6717. {
  6718. result << c;
  6719. }
  6720. else
  6721. {
  6722. const int v = (int) (uint8) c;
  6723. result << (v < 0x10 ? "%0" : "%") << String::toHexString (v);
  6724. }
  6725. }
  6726. return result;
  6727. }
  6728. bool URL::launchInDefaultBrowser() const
  6729. {
  6730. String u (toString (true));
  6731. if (u.containsChar ('@') && ! u.containsChar (':'))
  6732. u = "mailto:" + u;
  6733. return PlatformUtilities::openDocument (u, String::empty);
  6734. }
  6735. END_JUCE_NAMESPACE
  6736. /*** End of inlined file: juce_URL.cpp ***/
  6737. /*** Start of inlined file: juce_BufferedInputStream.cpp ***/
  6738. BEGIN_JUCE_NAMESPACE
  6739. BufferedInputStream::BufferedInputStream (InputStream* const source_,
  6740. const int bufferSize_,
  6741. const bool deleteSourceWhenDestroyed)
  6742. : source (source_),
  6743. sourceToDelete (deleteSourceWhenDestroyed ? source_ : 0),
  6744. bufferSize (jmax (256, bufferSize_)),
  6745. position (source_->getPosition()),
  6746. lastReadPos (0),
  6747. bufferOverlap (128)
  6748. {
  6749. const int sourceSize = (int) source_->getTotalLength();
  6750. if (sourceSize >= 0)
  6751. bufferSize = jmin (jmax (32, sourceSize), bufferSize);
  6752. bufferStart = position;
  6753. buffer.malloc (bufferSize);
  6754. }
  6755. BufferedInputStream::~BufferedInputStream()
  6756. {
  6757. }
  6758. int64 BufferedInputStream::getTotalLength()
  6759. {
  6760. return source->getTotalLength();
  6761. }
  6762. int64 BufferedInputStream::getPosition()
  6763. {
  6764. return position;
  6765. }
  6766. bool BufferedInputStream::setPosition (int64 newPosition)
  6767. {
  6768. position = jmax ((int64) 0, newPosition);
  6769. return true;
  6770. }
  6771. bool BufferedInputStream::isExhausted()
  6772. {
  6773. return (position >= lastReadPos)
  6774. && source->isExhausted();
  6775. }
  6776. void BufferedInputStream::ensureBuffered()
  6777. {
  6778. const int64 bufferEndOverlap = lastReadPos - bufferOverlap;
  6779. if (position < bufferStart || position >= bufferEndOverlap)
  6780. {
  6781. int bytesRead;
  6782. if (position < lastReadPos
  6783. && position >= bufferEndOverlap
  6784. && position >= bufferStart)
  6785. {
  6786. const int bytesToKeep = (int) (lastReadPos - position);
  6787. memmove (buffer, buffer + (int) (position - bufferStart), bytesToKeep);
  6788. bufferStart = position;
  6789. bytesRead = source->read (buffer + bytesToKeep,
  6790. bufferSize - bytesToKeep);
  6791. lastReadPos += bytesRead;
  6792. bytesRead += bytesToKeep;
  6793. }
  6794. else
  6795. {
  6796. bufferStart = position;
  6797. source->setPosition (bufferStart);
  6798. bytesRead = source->read (buffer, bufferSize);
  6799. lastReadPos = bufferStart + bytesRead;
  6800. }
  6801. while (bytesRead < bufferSize)
  6802. buffer [bytesRead++] = 0;
  6803. }
  6804. }
  6805. int BufferedInputStream::read (void* destBuffer, int maxBytesToRead)
  6806. {
  6807. if (position >= bufferStart
  6808. && position + maxBytesToRead <= lastReadPos)
  6809. {
  6810. memcpy (destBuffer, buffer + (int) (position - bufferStart), maxBytesToRead);
  6811. position += maxBytesToRead;
  6812. return maxBytesToRead;
  6813. }
  6814. else
  6815. {
  6816. if (position < bufferStart || position >= lastReadPos)
  6817. ensureBuffered();
  6818. int bytesRead = 0;
  6819. while (maxBytesToRead > 0)
  6820. {
  6821. const int bytesAvailable = jmin (maxBytesToRead, (int) (lastReadPos - position));
  6822. if (bytesAvailable > 0)
  6823. {
  6824. memcpy (destBuffer, buffer + (int) (position - bufferStart), bytesAvailable);
  6825. maxBytesToRead -= bytesAvailable;
  6826. bytesRead += bytesAvailable;
  6827. position += bytesAvailable;
  6828. destBuffer = static_cast <char*> (destBuffer) + bytesAvailable;
  6829. }
  6830. const int64 oldLastReadPos = lastReadPos;
  6831. ensureBuffered();
  6832. if (oldLastReadPos == lastReadPos)
  6833. break; // if ensureBuffered() failed to read any more data, bail out
  6834. if (isExhausted())
  6835. break;
  6836. }
  6837. return bytesRead;
  6838. }
  6839. }
  6840. const String BufferedInputStream::readString()
  6841. {
  6842. if (position >= bufferStart
  6843. && position < lastReadPos)
  6844. {
  6845. const int maxChars = (int) (lastReadPos - position);
  6846. const char* const src = buffer + (int) (position - bufferStart);
  6847. for (int i = 0; i < maxChars; ++i)
  6848. {
  6849. if (src[i] == 0)
  6850. {
  6851. position += i + 1;
  6852. return String::fromUTF8 (src, i);
  6853. }
  6854. }
  6855. }
  6856. return InputStream::readString();
  6857. }
  6858. END_JUCE_NAMESPACE
  6859. /*** End of inlined file: juce_BufferedInputStream.cpp ***/
  6860. /*** Start of inlined file: juce_FileInputSource.cpp ***/
  6861. BEGIN_JUCE_NAMESPACE
  6862. FileInputSource::FileInputSource (const File& file_)
  6863. : file (file_)
  6864. {
  6865. }
  6866. FileInputSource::~FileInputSource()
  6867. {
  6868. }
  6869. InputStream* FileInputSource::createInputStream()
  6870. {
  6871. return file.createInputStream();
  6872. }
  6873. InputStream* FileInputSource::createInputStreamFor (const String& relatedItemPath)
  6874. {
  6875. return file.getSiblingFile (relatedItemPath).createInputStream();
  6876. }
  6877. int64 FileInputSource::hashCode() const
  6878. {
  6879. return file.hashCode();
  6880. }
  6881. END_JUCE_NAMESPACE
  6882. /*** End of inlined file: juce_FileInputSource.cpp ***/
  6883. /*** Start of inlined file: juce_MemoryInputStream.cpp ***/
  6884. BEGIN_JUCE_NAMESPACE
  6885. MemoryInputStream::MemoryInputStream (const void* const sourceData,
  6886. const size_t sourceDataSize,
  6887. const bool keepInternalCopy)
  6888. : data (static_cast <const char*> (sourceData)),
  6889. dataSize (sourceDataSize),
  6890. position (0)
  6891. {
  6892. if (keepInternalCopy)
  6893. {
  6894. internalCopy.append (data, sourceDataSize);
  6895. data = static_cast <const char*> (internalCopy.getData());
  6896. }
  6897. }
  6898. MemoryInputStream::MemoryInputStream (const MemoryBlock& sourceData,
  6899. const bool keepInternalCopy)
  6900. : data (static_cast <const char*> (sourceData.getData())),
  6901. dataSize (sourceData.getSize()),
  6902. position (0)
  6903. {
  6904. if (keepInternalCopy)
  6905. {
  6906. internalCopy = sourceData;
  6907. data = static_cast <const char*> (internalCopy.getData());
  6908. }
  6909. }
  6910. MemoryInputStream::~MemoryInputStream()
  6911. {
  6912. }
  6913. int64 MemoryInputStream::getTotalLength()
  6914. {
  6915. return dataSize;
  6916. }
  6917. int MemoryInputStream::read (void* const buffer, const int howMany)
  6918. {
  6919. jassert (howMany >= 0);
  6920. const int num = jmin (howMany, (int) (dataSize - position));
  6921. memcpy (buffer, data + position, num);
  6922. position += num;
  6923. return (int) num;
  6924. }
  6925. bool MemoryInputStream::isExhausted()
  6926. {
  6927. return (position >= dataSize);
  6928. }
  6929. bool MemoryInputStream::setPosition (const int64 pos)
  6930. {
  6931. position = (int) jlimit ((int64) 0, (int64) dataSize, pos);
  6932. return true;
  6933. }
  6934. int64 MemoryInputStream::getPosition()
  6935. {
  6936. return position;
  6937. }
  6938. END_JUCE_NAMESPACE
  6939. /*** End of inlined file: juce_MemoryInputStream.cpp ***/
  6940. /*** Start of inlined file: juce_MemoryOutputStream.cpp ***/
  6941. BEGIN_JUCE_NAMESPACE
  6942. MemoryOutputStream::MemoryOutputStream (const size_t initialSize,
  6943. const size_t blockSizeToIncreaseBy,
  6944. MemoryBlock* const memoryBlockToWriteTo)
  6945. : data (memoryBlockToWriteTo),
  6946. position (0),
  6947. size (0),
  6948. blockSize (jmax ((size_t) 16, blockSizeToIncreaseBy))
  6949. {
  6950. if (data == 0)
  6951. dataToDelete = data = new MemoryBlock (initialSize);
  6952. else
  6953. data->setSize (initialSize, false);
  6954. }
  6955. MemoryOutputStream::~MemoryOutputStream()
  6956. {
  6957. flush();
  6958. }
  6959. void MemoryOutputStream::flush()
  6960. {
  6961. if (dataToDelete == 0)
  6962. data->setSize (size, false);
  6963. }
  6964. void MemoryOutputStream::reset() throw()
  6965. {
  6966. position = 0;
  6967. size = 0;
  6968. }
  6969. bool MemoryOutputStream::write (const void* const buffer, int howMany)
  6970. {
  6971. if (howMany > 0)
  6972. {
  6973. size_t storageNeeded = position + howMany;
  6974. if (storageNeeded >= data->getSize())
  6975. {
  6976. // if we need more space, increase the block by at least 10%..
  6977. storageNeeded += jmax (blockSize, storageNeeded / 10);
  6978. storageNeeded = storageNeeded - (storageNeeded % blockSize) + blockSize;
  6979. data->ensureSize (storageNeeded);
  6980. }
  6981. data->copyFrom (buffer, (int) position, howMany);
  6982. position += howMany;
  6983. size = jmax (size, position);
  6984. }
  6985. return true;
  6986. }
  6987. const char* MemoryOutputStream::getData() const throw()
  6988. {
  6989. char* const d = static_cast <char*> (data->getData());
  6990. if (data->getSize() > size)
  6991. d [size] = 0;
  6992. return d;
  6993. }
  6994. bool MemoryOutputStream::setPosition (int64 newPosition)
  6995. {
  6996. if (newPosition <= (int64) size)
  6997. {
  6998. // ok to seek backwards
  6999. position = jlimit ((size_t) 0, size, (size_t) newPosition);
  7000. return true;
  7001. }
  7002. else
  7003. {
  7004. // trying to make it bigger isn't a good thing to do..
  7005. return false;
  7006. }
  7007. }
  7008. const String MemoryOutputStream::toUTF8() const
  7009. {
  7010. return String (getData(), getDataSize());
  7011. }
  7012. END_JUCE_NAMESPACE
  7013. /*** End of inlined file: juce_MemoryOutputStream.cpp ***/
  7014. /*** Start of inlined file: juce_SubregionStream.cpp ***/
  7015. BEGIN_JUCE_NAMESPACE
  7016. SubregionStream::SubregionStream (InputStream* const sourceStream,
  7017. const int64 startPositionInSourceStream_,
  7018. const int64 lengthOfSourceStream_,
  7019. const bool deleteSourceWhenDestroyed) throw()
  7020. : source (sourceStream),
  7021. startPositionInSourceStream (startPositionInSourceStream_),
  7022. lengthOfSourceStream (lengthOfSourceStream_)
  7023. {
  7024. if (deleteSourceWhenDestroyed)
  7025. sourceToDelete = source;
  7026. setPosition (0);
  7027. }
  7028. SubregionStream::~SubregionStream() throw()
  7029. {
  7030. }
  7031. int64 SubregionStream::getTotalLength()
  7032. {
  7033. const int64 srcLen = source->getTotalLength() - startPositionInSourceStream;
  7034. return (lengthOfSourceStream >= 0) ? jmin (lengthOfSourceStream, srcLen)
  7035. : srcLen;
  7036. }
  7037. int64 SubregionStream::getPosition()
  7038. {
  7039. return source->getPosition() - startPositionInSourceStream;
  7040. }
  7041. bool SubregionStream::setPosition (int64 newPosition)
  7042. {
  7043. return source->setPosition (jmax ((int64) 0, newPosition + startPositionInSourceStream));
  7044. }
  7045. int SubregionStream::read (void* destBuffer, int maxBytesToRead)
  7046. {
  7047. if (lengthOfSourceStream < 0)
  7048. {
  7049. return source->read (destBuffer, maxBytesToRead);
  7050. }
  7051. else
  7052. {
  7053. maxBytesToRead = (int) jmin ((int64) maxBytesToRead, lengthOfSourceStream - getPosition());
  7054. if (maxBytesToRead <= 0)
  7055. return 0;
  7056. return source->read (destBuffer, maxBytesToRead);
  7057. }
  7058. }
  7059. bool SubregionStream::isExhausted()
  7060. {
  7061. if (lengthOfSourceStream >= 0)
  7062. return (getPosition() >= lengthOfSourceStream) || source->isExhausted();
  7063. else
  7064. return source->isExhausted();
  7065. }
  7066. END_JUCE_NAMESPACE
  7067. /*** End of inlined file: juce_SubregionStream.cpp ***/
  7068. /*** Start of inlined file: juce_PerformanceCounter.cpp ***/
  7069. BEGIN_JUCE_NAMESPACE
  7070. PerformanceCounter::PerformanceCounter (const String& name_,
  7071. int runsPerPrintout,
  7072. const File& loggingFile)
  7073. : name (name_),
  7074. numRuns (0),
  7075. runsPerPrint (runsPerPrintout),
  7076. totalTime (0),
  7077. outputFile (loggingFile)
  7078. {
  7079. if (outputFile != File::nonexistent)
  7080. {
  7081. String s ("**** Counter for \"");
  7082. s << name_ << "\" started at: "
  7083. << Time::getCurrentTime().toString (true, true)
  7084. << "\r\n";
  7085. outputFile.appendText (s, false, false);
  7086. }
  7087. }
  7088. PerformanceCounter::~PerformanceCounter()
  7089. {
  7090. printStatistics();
  7091. }
  7092. void PerformanceCounter::start()
  7093. {
  7094. started = Time::getHighResolutionTicks();
  7095. }
  7096. void PerformanceCounter::stop()
  7097. {
  7098. const int64 now = Time::getHighResolutionTicks();
  7099. totalTime += 1000.0 * Time::highResolutionTicksToSeconds (now - started);
  7100. if (++numRuns == runsPerPrint)
  7101. printStatistics();
  7102. }
  7103. void PerformanceCounter::printStatistics()
  7104. {
  7105. if (numRuns > 0)
  7106. {
  7107. String s ("Performance count for \"");
  7108. s << name << "\" - average over " << numRuns << " run(s) = ";
  7109. const int micros = (int) (totalTime * (1000.0 / numRuns));
  7110. if (micros > 10000)
  7111. s << (micros/1000) << " millisecs";
  7112. else
  7113. s << micros << " microsecs";
  7114. s << ", total = " << String (totalTime / 1000, 5) << " seconds";
  7115. Logger::outputDebugString (s);
  7116. s << "\r\n";
  7117. if (outputFile != File::nonexistent)
  7118. outputFile.appendText (s, false, false);
  7119. numRuns = 0;
  7120. totalTime = 0;
  7121. }
  7122. }
  7123. END_JUCE_NAMESPACE
  7124. /*** End of inlined file: juce_PerformanceCounter.cpp ***/
  7125. /*** Start of inlined file: juce_Uuid.cpp ***/
  7126. BEGIN_JUCE_NAMESPACE
  7127. Uuid::Uuid()
  7128. {
  7129. // Mix up any available MAC addresses with some time-based pseudo-random numbers
  7130. // to make it very very unlikely that two UUIDs will ever be the same..
  7131. static int64 macAddresses[2];
  7132. static bool hasCheckedMacAddresses = false;
  7133. if (! hasCheckedMacAddresses)
  7134. {
  7135. hasCheckedMacAddresses = true;
  7136. SystemStats::getMACAddresses (macAddresses, 2);
  7137. }
  7138. value.asInt64[0] = macAddresses[0];
  7139. value.asInt64[1] = macAddresses[1];
  7140. // We'll use both a local RNG that is re-seeded, plus the shared RNG,
  7141. // whose seed will carry over between calls to this method.
  7142. Random r (macAddresses[0] ^ macAddresses[1]
  7143. ^ Random::getSystemRandom().nextInt64());
  7144. for (int i = 4; --i >= 0;)
  7145. {
  7146. r.setSeedRandomly(); // calling this repeatedly improves randomness
  7147. value.asInt[i] ^= r.nextInt();
  7148. value.asInt[i] ^= Random::getSystemRandom().nextInt();
  7149. }
  7150. }
  7151. Uuid::~Uuid() throw()
  7152. {
  7153. }
  7154. Uuid::Uuid (const Uuid& other)
  7155. : value (other.value)
  7156. {
  7157. }
  7158. Uuid& Uuid::operator= (const Uuid& other)
  7159. {
  7160. value = other.value;
  7161. return *this;
  7162. }
  7163. bool Uuid::operator== (const Uuid& other) const
  7164. {
  7165. return value.asInt64[0] == other.value.asInt64[0]
  7166. && value.asInt64[1] == other.value.asInt64[1];
  7167. }
  7168. bool Uuid::operator!= (const Uuid& other) const
  7169. {
  7170. return ! operator== (other);
  7171. }
  7172. bool Uuid::isNull() const throw()
  7173. {
  7174. return (value.asInt64 [0] == 0) && (value.asInt64 [1] == 0);
  7175. }
  7176. const String Uuid::toString() const
  7177. {
  7178. return String::toHexString (value.asBytes, sizeof (value.asBytes), 0);
  7179. }
  7180. Uuid::Uuid (const String& uuidString)
  7181. {
  7182. operator= (uuidString);
  7183. }
  7184. Uuid& Uuid::operator= (const String& uuidString)
  7185. {
  7186. MemoryBlock mb;
  7187. mb.loadFromHexString (uuidString);
  7188. mb.ensureSize (sizeof (value.asBytes), true);
  7189. mb.copyTo (value.asBytes, 0, sizeof (value.asBytes));
  7190. return *this;
  7191. }
  7192. Uuid::Uuid (const uint8* const rawData)
  7193. {
  7194. operator= (rawData);
  7195. }
  7196. Uuid& Uuid::operator= (const uint8* const rawData)
  7197. {
  7198. if (rawData != 0)
  7199. memcpy (value.asBytes, rawData, sizeof (value.asBytes));
  7200. else
  7201. zeromem (value.asBytes, sizeof (value.asBytes));
  7202. return *this;
  7203. }
  7204. END_JUCE_NAMESPACE
  7205. /*** End of inlined file: juce_Uuid.cpp ***/
  7206. /*** Start of inlined file: juce_ZipFile.cpp ***/
  7207. BEGIN_JUCE_NAMESPACE
  7208. class ZipFile::ZipEntryInfo
  7209. {
  7210. public:
  7211. ZipFile::ZipEntry entry;
  7212. int streamOffset;
  7213. int compressedSize;
  7214. bool compressed;
  7215. };
  7216. class ZipFile::ZipInputStream : public InputStream
  7217. {
  7218. public:
  7219. ZipInputStream (ZipFile& file_, ZipFile::ZipEntryInfo& zei)
  7220. : file (file_),
  7221. zipEntryInfo (zei),
  7222. pos (0),
  7223. headerSize (0),
  7224. inputStream (0)
  7225. {
  7226. inputStream = file_.inputStream;
  7227. if (file_.inputSource != 0)
  7228. {
  7229. inputStream = file.inputSource->createInputStream();
  7230. }
  7231. else
  7232. {
  7233. #if JUCE_DEBUG
  7234. file_.numOpenStreams++;
  7235. #endif
  7236. }
  7237. char buffer [30];
  7238. if (inputStream != 0
  7239. && inputStream->setPosition (zei.streamOffset)
  7240. && inputStream->read (buffer, 30) == 30
  7241. && ByteOrder::littleEndianInt (buffer) == 0x04034b50)
  7242. {
  7243. headerSize = 30 + ByteOrder::littleEndianShort (buffer + 26)
  7244. + ByteOrder::littleEndianShort (buffer + 28);
  7245. }
  7246. }
  7247. ~ZipInputStream() throw()
  7248. {
  7249. #if JUCE_DEBUG
  7250. if (inputStream != 0 && inputStream == file.inputStream)
  7251. file.numOpenStreams--;
  7252. #endif
  7253. if (inputStream != file.inputStream)
  7254. delete inputStream;
  7255. }
  7256. int64 getTotalLength() throw()
  7257. {
  7258. return zipEntryInfo.compressedSize;
  7259. }
  7260. int read (void* buffer, int howMany) throw()
  7261. {
  7262. if (headerSize <= 0)
  7263. return 0;
  7264. howMany = (int) jmin ((int64) howMany, zipEntryInfo.compressedSize - pos);
  7265. if (inputStream == 0)
  7266. return 0;
  7267. int num;
  7268. if (inputStream == file.inputStream)
  7269. {
  7270. const ScopedLock sl (file.lock);
  7271. inputStream->setPosition (pos + zipEntryInfo.streamOffset + headerSize);
  7272. num = inputStream->read (buffer, howMany);
  7273. }
  7274. else
  7275. {
  7276. inputStream->setPosition (pos + zipEntryInfo.streamOffset + headerSize);
  7277. num = inputStream->read (buffer, howMany);
  7278. }
  7279. pos += num;
  7280. return num;
  7281. }
  7282. bool isExhausted() throw()
  7283. {
  7284. return headerSize <= 0 || pos >= zipEntryInfo.compressedSize;
  7285. }
  7286. int64 getPosition() throw()
  7287. {
  7288. return pos;
  7289. }
  7290. bool setPosition (int64 newPos) throw()
  7291. {
  7292. pos = jlimit ((int64) 0, (int64) zipEntryInfo.compressedSize, newPos);
  7293. return true;
  7294. }
  7295. private:
  7296. ZipFile& file;
  7297. ZipEntryInfo zipEntryInfo;
  7298. int64 pos;
  7299. int headerSize;
  7300. InputStream* inputStream;
  7301. ZipInputStream (const ZipInputStream&);
  7302. ZipInputStream& operator= (const ZipInputStream&);
  7303. };
  7304. ZipFile::ZipFile (InputStream* const source_,
  7305. const bool deleteStreamWhenDestroyed) throw()
  7306. : inputStream (source_)
  7307. #if JUCE_DEBUG
  7308. , numOpenStreams (0)
  7309. #endif
  7310. {
  7311. if (deleteStreamWhenDestroyed)
  7312. streamToDelete = inputStream;
  7313. init();
  7314. }
  7315. ZipFile::ZipFile (const File& file)
  7316. : inputStream (0)
  7317. #if JUCE_DEBUG
  7318. , numOpenStreams (0)
  7319. #endif
  7320. {
  7321. inputSource = new FileInputSource (file);
  7322. init();
  7323. }
  7324. ZipFile::ZipFile (InputSource* const inputSource_)
  7325. : inputStream (0),
  7326. inputSource (inputSource_)
  7327. #if JUCE_DEBUG
  7328. , numOpenStreams (0)
  7329. #endif
  7330. {
  7331. init();
  7332. }
  7333. ZipFile::~ZipFile() throw()
  7334. {
  7335. #if JUCE_DEBUG
  7336. entries.clear();
  7337. // If you hit this assertion, it means you've created a stream to read
  7338. // one of the items in the zipfile, but you've forgotten to delete that
  7339. // stream object before deleting the file.. Streams can't be kept open
  7340. // after the file is deleted because they need to share the input
  7341. // stream that the file uses to read itself.
  7342. jassert (numOpenStreams == 0);
  7343. #endif
  7344. }
  7345. int ZipFile::getNumEntries() const throw()
  7346. {
  7347. return entries.size();
  7348. }
  7349. const ZipFile::ZipEntry* ZipFile::getEntry (const int index) const throw()
  7350. {
  7351. ZipEntryInfo* const zei = entries [index];
  7352. return zei != 0 ? &(zei->entry) : 0;
  7353. }
  7354. int ZipFile::getIndexOfFileName (const String& fileName) const throw()
  7355. {
  7356. for (int i = 0; i < entries.size(); ++i)
  7357. if (entries.getUnchecked (i)->entry.filename == fileName)
  7358. return i;
  7359. return -1;
  7360. }
  7361. const ZipFile::ZipEntry* ZipFile::getEntry (const String& fileName) const throw()
  7362. {
  7363. return getEntry (getIndexOfFileName (fileName));
  7364. }
  7365. InputStream* ZipFile::createStreamForEntry (const int index)
  7366. {
  7367. ZipEntryInfo* const zei = entries[index];
  7368. InputStream* stream = 0;
  7369. if (zei != 0)
  7370. {
  7371. stream = new ZipInputStream (*this, *zei);
  7372. if (zei->compressed)
  7373. {
  7374. stream = new GZIPDecompressorInputStream (stream, true, true,
  7375. zei->entry.uncompressedSize);
  7376. // (much faster to unzip in big blocks using a buffer..)
  7377. stream = new BufferedInputStream (stream, 32768, true);
  7378. }
  7379. }
  7380. return stream;
  7381. }
  7382. class ZipFile::ZipFilenameComparator
  7383. {
  7384. public:
  7385. int compareElements (const ZipFile::ZipEntryInfo* first, const ZipFile::ZipEntryInfo* second)
  7386. {
  7387. return first->entry.filename.compare (second->entry.filename);
  7388. }
  7389. };
  7390. void ZipFile::sortEntriesByFilename()
  7391. {
  7392. ZipFilenameComparator sorter;
  7393. entries.sort (sorter);
  7394. }
  7395. void ZipFile::init()
  7396. {
  7397. ScopedPointer <InputStream> toDelete;
  7398. InputStream* in = inputStream;
  7399. if (inputSource != 0)
  7400. {
  7401. in = inputSource->createInputStream();
  7402. toDelete = in;
  7403. }
  7404. if (in != 0)
  7405. {
  7406. int numEntries = 0;
  7407. int pos = findEndOfZipEntryTable (in, numEntries);
  7408. if (pos >= 0 && pos < in->getTotalLength())
  7409. {
  7410. const int size = (int) (in->getTotalLength() - pos);
  7411. in->setPosition (pos);
  7412. MemoryBlock headerData;
  7413. if (in->readIntoMemoryBlock (headerData, size) == size)
  7414. {
  7415. pos = 0;
  7416. for (int i = 0; i < numEntries; ++i)
  7417. {
  7418. if (pos + 46 > size)
  7419. break;
  7420. const char* const buffer = static_cast <const char*> (headerData.getData()) + pos;
  7421. const int fileNameLen = ByteOrder::littleEndianShort (buffer + 28);
  7422. if (pos + 46 + fileNameLen > size)
  7423. break;
  7424. ZipEntryInfo* const zei = new ZipEntryInfo();
  7425. zei->entry.filename = String::fromUTF8 (buffer + 46, fileNameLen);
  7426. const int time = ByteOrder::littleEndianShort (buffer + 12);
  7427. const int date = ByteOrder::littleEndianShort (buffer + 14);
  7428. const int year = 1980 + (date >> 9);
  7429. const int month = ((date >> 5) & 15) - 1;
  7430. const int day = date & 31;
  7431. const int hours = time >> 11;
  7432. const int minutes = (time >> 5) & 63;
  7433. const int seconds = (time & 31) << 1;
  7434. zei->entry.fileTime = Time (year, month, day, hours, minutes, seconds);
  7435. zei->compressed = ByteOrder::littleEndianShort (buffer + 10) != 0;
  7436. zei->compressedSize = ByteOrder::littleEndianInt (buffer + 20);
  7437. zei->entry.uncompressedSize = ByteOrder::littleEndianInt (buffer + 24);
  7438. zei->streamOffset = ByteOrder::littleEndianInt (buffer + 42);
  7439. entries.add (zei);
  7440. pos += 46 + fileNameLen
  7441. + ByteOrder::littleEndianShort (buffer + 30)
  7442. + ByteOrder::littleEndianShort (buffer + 32);
  7443. }
  7444. }
  7445. }
  7446. }
  7447. }
  7448. int ZipFile::findEndOfZipEntryTable (InputStream* input, int& numEntries)
  7449. {
  7450. BufferedInputStream in (input, 8192, false);
  7451. in.setPosition (in.getTotalLength());
  7452. int64 pos = in.getPosition();
  7453. const int64 lowestPos = jmax ((int64) 0, pos - 1024);
  7454. char buffer [32];
  7455. zeromem (buffer, sizeof (buffer));
  7456. while (pos > lowestPos)
  7457. {
  7458. in.setPosition (pos - 22);
  7459. pos = in.getPosition();
  7460. memcpy (buffer + 22, buffer, 4);
  7461. if (in.read (buffer, 22) != 22)
  7462. return 0;
  7463. for (int i = 0; i < 22; ++i)
  7464. {
  7465. if (ByteOrder::littleEndianInt (buffer + i) == 0x06054b50)
  7466. {
  7467. in.setPosition (pos + i);
  7468. in.read (buffer, 22);
  7469. numEntries = ByteOrder::littleEndianShort (buffer + 10);
  7470. return ByteOrder::littleEndianInt (buffer + 16);
  7471. }
  7472. }
  7473. }
  7474. return 0;
  7475. }
  7476. void ZipFile::uncompressTo (const File& targetDirectory,
  7477. const bool shouldOverwriteFiles)
  7478. {
  7479. for (int i = 0; i < entries.size(); ++i)
  7480. {
  7481. const ZipEntry& zei = entries.getUnchecked(i)->entry;
  7482. const File targetFile (targetDirectory.getChildFile (zei.filename));
  7483. if (zei.filename.endsWithChar ('/'))
  7484. {
  7485. targetFile.createDirectory(); // (entry is a directory, not a file)
  7486. }
  7487. else
  7488. {
  7489. ScopedPointer <InputStream> in (createStreamForEntry (i));
  7490. if (in != 0)
  7491. {
  7492. if (shouldOverwriteFiles)
  7493. targetFile.deleteFile();
  7494. if ((! targetFile.exists())
  7495. && targetFile.getParentDirectory().createDirectory())
  7496. {
  7497. ScopedPointer <FileOutputStream> out (targetFile.createOutputStream());
  7498. if (out != 0)
  7499. {
  7500. out->writeFromInputStream (*in, -1);
  7501. out = 0;
  7502. targetFile.setCreationTime (zei.fileTime);
  7503. targetFile.setLastModificationTime (zei.fileTime);
  7504. targetFile.setLastAccessTime (zei.fileTime);
  7505. }
  7506. }
  7507. }
  7508. }
  7509. }
  7510. }
  7511. END_JUCE_NAMESPACE
  7512. /*** End of inlined file: juce_ZipFile.cpp ***/
  7513. /*** Start of inlined file: juce_CharacterFunctions.cpp ***/
  7514. #ifdef _MSC_VER
  7515. #pragma warning (disable: 4514 4996)
  7516. #pragma warning (push)
  7517. #endif
  7518. #include <cwctype>
  7519. #include <cctype>
  7520. #include <ctime>
  7521. #ifdef _MSC_VER
  7522. #pragma warning (pop)
  7523. #endif
  7524. BEGIN_JUCE_NAMESPACE
  7525. int CharacterFunctions::length (const char* const s) throw()
  7526. {
  7527. return (int) strlen (s);
  7528. }
  7529. int CharacterFunctions::length (const juce_wchar* const s) throw()
  7530. {
  7531. return (int) wcslen (s);
  7532. }
  7533. void CharacterFunctions::copy (char* dest, const char* src, const int maxChars) throw()
  7534. {
  7535. strncpy (dest, src, maxChars);
  7536. }
  7537. void CharacterFunctions::copy (juce_wchar* dest, const juce_wchar* src, int maxChars) throw()
  7538. {
  7539. wcsncpy (dest, src, maxChars);
  7540. }
  7541. void CharacterFunctions::copy (juce_wchar* dest, const char* src, const int maxChars) throw()
  7542. {
  7543. mbstowcs (dest, src, maxChars);
  7544. }
  7545. void CharacterFunctions::copy (char* dest, const juce_wchar* src, const int maxChars) throw()
  7546. {
  7547. wcstombs (dest, src, maxChars);
  7548. }
  7549. int CharacterFunctions::bytesRequiredForCopy (const juce_wchar* src) throw()
  7550. {
  7551. return (int) wcstombs (0, src, 0);
  7552. }
  7553. void CharacterFunctions::append (char* dest, const char* src) throw()
  7554. {
  7555. strcat (dest, src);
  7556. }
  7557. void CharacterFunctions::append (juce_wchar* dest, const juce_wchar* src) throw()
  7558. {
  7559. wcscat (dest, src);
  7560. }
  7561. int CharacterFunctions::compare (const char* const s1, const char* const s2) throw()
  7562. {
  7563. return strcmp (s1, s2);
  7564. }
  7565. int CharacterFunctions::compare (const juce_wchar* s1, const juce_wchar* s2) throw()
  7566. {
  7567. jassert (s1 != 0 && s2 != 0);
  7568. return wcscmp (s1, s2);
  7569. }
  7570. int CharacterFunctions::compare (const char* const s1, const char* const s2, const int maxChars) throw()
  7571. {
  7572. jassert (s1 != 0 && s2 != 0);
  7573. return strncmp (s1, s2, maxChars);
  7574. }
  7575. int CharacterFunctions::compare (const juce_wchar* s1, const juce_wchar* s2, int maxChars) throw()
  7576. {
  7577. jassert (s1 != 0 && s2 != 0);
  7578. return wcsncmp (s1, s2, maxChars);
  7579. }
  7580. int CharacterFunctions::compare (const juce_wchar* s1, const char* s2) throw()
  7581. {
  7582. jassert (s1 != 0 && s2 != 0);
  7583. for (;;)
  7584. {
  7585. const int diff = (int) (*s1 - (juce_wchar) (unsigned char) *s2);
  7586. if (diff != 0)
  7587. return diff;
  7588. else if (*s1 == 0)
  7589. break;
  7590. ++s1;
  7591. ++s2;
  7592. }
  7593. return 0;
  7594. }
  7595. int CharacterFunctions::compare (const char* s1, const juce_wchar* s2) throw()
  7596. {
  7597. return -compare (s2, s1);
  7598. }
  7599. int CharacterFunctions::compareIgnoreCase (const char* const s1, const char* const s2) throw()
  7600. {
  7601. jassert (s1 != 0 && s2 != 0);
  7602. #if JUCE_WIN32
  7603. return stricmp (s1, s2);
  7604. #else
  7605. return strcasecmp (s1, s2);
  7606. #endif
  7607. }
  7608. int CharacterFunctions::compareIgnoreCase (const juce_wchar* s1, const juce_wchar* s2) throw()
  7609. {
  7610. jassert (s1 != 0 && s2 != 0);
  7611. #if JUCE_WIN32
  7612. return _wcsicmp (s1, s2);
  7613. #else
  7614. for (;;)
  7615. {
  7616. if (*s1 != *s2)
  7617. {
  7618. const int diff = toUpperCase (*s1) - toUpperCase (*s2);
  7619. if (diff != 0)
  7620. return diff < 0 ? -1 : 1;
  7621. }
  7622. else if (*s1 == 0)
  7623. break;
  7624. ++s1;
  7625. ++s2;
  7626. }
  7627. return 0;
  7628. #endif
  7629. }
  7630. int CharacterFunctions::compareIgnoreCase (const juce_wchar* s1, const char* s2) throw()
  7631. {
  7632. jassert (s1 != 0 && s2 != 0);
  7633. for (;;)
  7634. {
  7635. if (*s1 != *s2)
  7636. {
  7637. const int diff = toUpperCase (*s1) - toUpperCase (*s2);
  7638. if (diff != 0)
  7639. return diff < 0 ? -1 : 1;
  7640. }
  7641. else if (*s1 == 0)
  7642. break;
  7643. ++s1;
  7644. ++s2;
  7645. }
  7646. return 0;
  7647. }
  7648. int CharacterFunctions::compareIgnoreCase (const char* const s1, const char* const s2, const int maxChars) throw()
  7649. {
  7650. jassert (s1 != 0 && s2 != 0);
  7651. #if JUCE_WIN32
  7652. return strnicmp (s1, s2, maxChars);
  7653. #else
  7654. return strncasecmp (s1, s2, maxChars);
  7655. #endif
  7656. }
  7657. int CharacterFunctions::compareIgnoreCase (const juce_wchar* s1, const juce_wchar* s2, int maxChars) throw()
  7658. {
  7659. jassert (s1 != 0 && s2 != 0);
  7660. #if JUCE_WIN32
  7661. return _wcsnicmp (s1, s2, maxChars);
  7662. #else
  7663. while (--maxChars >= 0)
  7664. {
  7665. if (*s1 != *s2)
  7666. {
  7667. const int diff = toUpperCase (*s1) - toUpperCase (*s2);
  7668. if (diff != 0)
  7669. return diff < 0 ? -1 : 1;
  7670. }
  7671. else if (*s1 == 0)
  7672. break;
  7673. ++s1;
  7674. ++s2;
  7675. }
  7676. return 0;
  7677. #endif
  7678. }
  7679. const char* CharacterFunctions::find (const char* const haystack, const char* const needle) throw()
  7680. {
  7681. return strstr (haystack, needle);
  7682. }
  7683. const juce_wchar* CharacterFunctions::find (const juce_wchar* haystack, const juce_wchar* const needle) throw()
  7684. {
  7685. return wcsstr (haystack, needle);
  7686. }
  7687. int CharacterFunctions::indexOfChar (const char* const haystack, const char needle, const bool ignoreCase) throw()
  7688. {
  7689. if (haystack != 0)
  7690. {
  7691. int i = 0;
  7692. if (ignoreCase)
  7693. {
  7694. const char n1 = toLowerCase (needle);
  7695. const char n2 = toUpperCase (needle);
  7696. if (n1 != n2) // if the char is the same in upper/lower case, fall through to the normal search
  7697. {
  7698. while (haystack[i] != 0)
  7699. {
  7700. if (haystack[i] == n1 || haystack[i] == n2)
  7701. return i;
  7702. ++i;
  7703. }
  7704. return -1;
  7705. }
  7706. jassert (n1 == needle);
  7707. }
  7708. while (haystack[i] != 0)
  7709. {
  7710. if (haystack[i] == needle)
  7711. return i;
  7712. ++i;
  7713. }
  7714. }
  7715. return -1;
  7716. }
  7717. int CharacterFunctions::indexOfChar (const juce_wchar* const haystack, const juce_wchar needle, const bool ignoreCase) throw()
  7718. {
  7719. if (haystack != 0)
  7720. {
  7721. int i = 0;
  7722. if (ignoreCase)
  7723. {
  7724. const juce_wchar n1 = toLowerCase (needle);
  7725. const juce_wchar n2 = toUpperCase (needle);
  7726. if (n1 != n2) // if the char is the same in upper/lower case, fall through to the normal search
  7727. {
  7728. while (haystack[i] != 0)
  7729. {
  7730. if (haystack[i] == n1 || haystack[i] == n2)
  7731. return i;
  7732. ++i;
  7733. }
  7734. return -1;
  7735. }
  7736. jassert (n1 == needle);
  7737. }
  7738. while (haystack[i] != 0)
  7739. {
  7740. if (haystack[i] == needle)
  7741. return i;
  7742. ++i;
  7743. }
  7744. }
  7745. return -1;
  7746. }
  7747. int CharacterFunctions::indexOfCharFast (const char* const haystack, const char needle) throw()
  7748. {
  7749. jassert (haystack != 0);
  7750. int i = 0;
  7751. while (haystack[i] != 0)
  7752. {
  7753. if (haystack[i] == needle)
  7754. return i;
  7755. ++i;
  7756. }
  7757. return -1;
  7758. }
  7759. int CharacterFunctions::indexOfCharFast (const juce_wchar* const haystack, const juce_wchar needle) throw()
  7760. {
  7761. jassert (haystack != 0);
  7762. int i = 0;
  7763. while (haystack[i] != 0)
  7764. {
  7765. if (haystack[i] == needle)
  7766. return i;
  7767. ++i;
  7768. }
  7769. return -1;
  7770. }
  7771. int CharacterFunctions::getIntialSectionContainingOnly (const char* const text, const char* const allowedChars) throw()
  7772. {
  7773. return allowedChars == 0 ? 0 : (int) strspn (text, allowedChars);
  7774. }
  7775. int CharacterFunctions::getIntialSectionContainingOnly (const juce_wchar* const text, const juce_wchar* const allowedChars) throw()
  7776. {
  7777. if (allowedChars == 0)
  7778. return 0;
  7779. int i = 0;
  7780. for (;;)
  7781. {
  7782. if (indexOfCharFast (allowedChars, text[i]) < 0)
  7783. break;
  7784. ++i;
  7785. }
  7786. return i;
  7787. }
  7788. int CharacterFunctions::ftime (char* const dest, const int maxChars, const char* const format, const struct tm* const tm) throw()
  7789. {
  7790. return (int) strftime (dest, maxChars, format, tm);
  7791. }
  7792. int CharacterFunctions::ftime (juce_wchar* const dest, const int maxChars, const juce_wchar* const format, const struct tm* const tm) throw()
  7793. {
  7794. return (int) wcsftime (dest, maxChars, format, tm);
  7795. }
  7796. int CharacterFunctions::getIntValue (const char* const s) throw()
  7797. {
  7798. return atoi (s);
  7799. }
  7800. int CharacterFunctions::getIntValue (const juce_wchar* s) throw()
  7801. {
  7802. #if JUCE_WIN32
  7803. return _wtoi (s);
  7804. #else
  7805. int v = 0;
  7806. while (isWhitespace (*s))
  7807. ++s;
  7808. const bool isNeg = *s == '-';
  7809. if (isNeg)
  7810. ++s;
  7811. for (;;)
  7812. {
  7813. const wchar_t c = *s++;
  7814. if (c >= '0' && c <= '9')
  7815. v = v * 10 + (int) (c - '0');
  7816. else
  7817. break;
  7818. }
  7819. return isNeg ? -v : v;
  7820. #endif
  7821. }
  7822. int64 CharacterFunctions::getInt64Value (const char* s) throw()
  7823. {
  7824. #if JUCE_LINUX
  7825. return atoll (s);
  7826. #elif defined (JUCE_WIN32)
  7827. return _atoi64 (s);
  7828. #else
  7829. int64 v = 0;
  7830. while (isWhitespace (*s))
  7831. ++s;
  7832. const bool isNeg = *s == '-';
  7833. if (isNeg)
  7834. ++s;
  7835. for (;;)
  7836. {
  7837. const char c = *s++;
  7838. if (c >= '0' && c <= '9')
  7839. v = v * 10 + (int64) (c - '0');
  7840. else
  7841. break;
  7842. }
  7843. return isNeg ? -v : v;
  7844. #endif
  7845. }
  7846. int64 CharacterFunctions::getInt64Value (const juce_wchar* s) throw()
  7847. {
  7848. #if JUCE_WIN32
  7849. return _wtoi64 (s);
  7850. #else
  7851. int64 v = 0;
  7852. while (isWhitespace (*s))
  7853. ++s;
  7854. const bool isNeg = *s == '-';
  7855. if (isNeg)
  7856. ++s;
  7857. for (;;)
  7858. {
  7859. const juce_wchar c = *s++;
  7860. if (c >= '0' && c <= '9')
  7861. v = v * 10 + (int64) (c - '0');
  7862. else
  7863. break;
  7864. }
  7865. return isNeg ? -v : v;
  7866. #endif
  7867. }
  7868. static double juce_mulexp10 (const double value, int exponent) throw()
  7869. {
  7870. if (exponent == 0)
  7871. return value;
  7872. if (value == 0)
  7873. return 0;
  7874. const bool negative = (exponent < 0);
  7875. if (negative)
  7876. exponent = -exponent;
  7877. double result = 1.0, power = 10.0;
  7878. for (int bit = 1; exponent != 0; bit <<= 1)
  7879. {
  7880. if ((exponent & bit) != 0)
  7881. {
  7882. exponent ^= bit;
  7883. result *= power;
  7884. if (exponent == 0)
  7885. break;
  7886. }
  7887. power *= power;
  7888. }
  7889. return negative ? (value / result) : (value * result);
  7890. }
  7891. template <class CharType>
  7892. double juce_atof (const CharType* const original) throw()
  7893. {
  7894. double result[3] = { 0, 0, 0 }, accumulator[2] = { 0, 0 };
  7895. int exponentAdjustment[2] = { 0, 0 }, exponentAccumulator[2] = { -1, -1 };
  7896. int exponent = 0, decPointIndex = 0, digit = 0;
  7897. int lastDigit = 0, numSignificantDigits = 0;
  7898. bool isNegative = false, digitsFound = false;
  7899. const int maxSignificantDigits = 15 + 2;
  7900. const CharType* s = original;
  7901. while (CharacterFunctions::isWhitespace (*s))
  7902. ++s;
  7903. switch (*s)
  7904. {
  7905. case '-': isNegative = true; // fall-through..
  7906. case '+': ++s;
  7907. }
  7908. if (*s == 'n' || *s == 'N' || *s == 'i' || *s == 'I')
  7909. return atof (String (original).toUTF8()); // Let the c library deal with NAN and INF
  7910. for (;;)
  7911. {
  7912. if (CharacterFunctions::isDigit (*s))
  7913. {
  7914. lastDigit = digit;
  7915. digit = *s++ - '0';
  7916. digitsFound = true;
  7917. if (decPointIndex != 0)
  7918. exponentAdjustment[1]++;
  7919. if (numSignificantDigits == 0 && digit == 0)
  7920. continue;
  7921. if (++numSignificantDigits > maxSignificantDigits)
  7922. {
  7923. if (digit > 5)
  7924. ++accumulator [decPointIndex];
  7925. else if (digit == 5 && (lastDigit & 1) != 0)
  7926. ++accumulator [decPointIndex];
  7927. if (decPointIndex > 0)
  7928. exponentAdjustment[1]--;
  7929. else
  7930. exponentAdjustment[0]++;
  7931. while (CharacterFunctions::isDigit (*s))
  7932. {
  7933. ++s;
  7934. if (decPointIndex == 0)
  7935. exponentAdjustment[0]++;
  7936. }
  7937. }
  7938. else
  7939. {
  7940. const double maxAccumulatorValue = (double) ((std::numeric_limits<unsigned int>::max() - 9) / 10);
  7941. if (accumulator [decPointIndex] > maxAccumulatorValue)
  7942. {
  7943. result [decPointIndex] = juce_mulexp10 (result [decPointIndex], exponentAccumulator [decPointIndex])
  7944. + accumulator [decPointIndex];
  7945. accumulator [decPointIndex] = 0;
  7946. exponentAccumulator [decPointIndex] = 0;
  7947. }
  7948. accumulator [decPointIndex] = accumulator[decPointIndex] * 10 + digit;
  7949. exponentAccumulator [decPointIndex]++;
  7950. }
  7951. }
  7952. else if (decPointIndex == 0 && *s == '.')
  7953. {
  7954. ++s;
  7955. decPointIndex = 1;
  7956. if (numSignificantDigits > maxSignificantDigits)
  7957. {
  7958. while (CharacterFunctions::isDigit (*s))
  7959. ++s;
  7960. break;
  7961. }
  7962. }
  7963. else
  7964. {
  7965. break;
  7966. }
  7967. }
  7968. result[0] = juce_mulexp10 (result[0], exponentAccumulator[0]) + accumulator[0];
  7969. if (decPointIndex != 0)
  7970. result[1] = juce_mulexp10 (result[1], exponentAccumulator[1]) + accumulator[1];
  7971. if ((*s == 'e' || *s == 'E') && digitsFound)
  7972. {
  7973. bool negativeExponent = false;
  7974. switch (*++s)
  7975. {
  7976. case '-': negativeExponent = true; // fall-through..
  7977. case '+': ++s;
  7978. }
  7979. while (CharacterFunctions::isDigit (*s))
  7980. exponent = (exponent * 10) + (*s++ - '0');
  7981. if (negativeExponent)
  7982. exponent = -exponent;
  7983. }
  7984. double r = juce_mulexp10 (result[0], exponent + exponentAdjustment[0]);
  7985. if (decPointIndex != 0)
  7986. r += juce_mulexp10 (result[1], exponent - exponentAdjustment[1]);
  7987. return isNegative ? -r : r;
  7988. }
  7989. double CharacterFunctions::getDoubleValue (const char* const s) throw()
  7990. {
  7991. return juce_atof <char> (s);
  7992. }
  7993. double CharacterFunctions::getDoubleValue (const juce_wchar* const s) throw()
  7994. {
  7995. return juce_atof <juce_wchar> (s);
  7996. }
  7997. char CharacterFunctions::toUpperCase (const char character) throw()
  7998. {
  7999. return (char) toupper (character);
  8000. }
  8001. juce_wchar CharacterFunctions::toUpperCase (const juce_wchar character) throw()
  8002. {
  8003. return towupper (character);
  8004. }
  8005. void CharacterFunctions::toUpperCase (char* s) throw()
  8006. {
  8007. #if JUCE_WIN32
  8008. strupr (s);
  8009. #else
  8010. while (*s != 0)
  8011. {
  8012. *s = toUpperCase (*s);
  8013. ++s;
  8014. }
  8015. #endif
  8016. }
  8017. void CharacterFunctions::toUpperCase (juce_wchar* s) throw()
  8018. {
  8019. #if JUCE_WIN32
  8020. _wcsupr (s);
  8021. #else
  8022. while (*s != 0)
  8023. {
  8024. *s = toUpperCase (*s);
  8025. ++s;
  8026. }
  8027. #endif
  8028. }
  8029. bool CharacterFunctions::isUpperCase (const char character) throw()
  8030. {
  8031. return isupper (character) != 0;
  8032. }
  8033. bool CharacterFunctions::isUpperCase (const juce_wchar character) throw()
  8034. {
  8035. #if JUCE_WIN32
  8036. return iswupper (character) != 0;
  8037. #else
  8038. return toLowerCase (character) != character;
  8039. #endif
  8040. }
  8041. char CharacterFunctions::toLowerCase (const char character) throw()
  8042. {
  8043. return (char) tolower (character);
  8044. }
  8045. juce_wchar CharacterFunctions::toLowerCase (const juce_wchar character) throw()
  8046. {
  8047. return towlower (character);
  8048. }
  8049. void CharacterFunctions::toLowerCase (char* s) throw()
  8050. {
  8051. #if JUCE_WIN32
  8052. strlwr (s);
  8053. #else
  8054. while (*s != 0)
  8055. {
  8056. *s = toLowerCase (*s);
  8057. ++s;
  8058. }
  8059. #endif
  8060. }
  8061. void CharacterFunctions::toLowerCase (juce_wchar* s) throw()
  8062. {
  8063. #if JUCE_WIN32
  8064. _wcslwr (s);
  8065. #else
  8066. while (*s != 0)
  8067. {
  8068. *s = toLowerCase (*s);
  8069. ++s;
  8070. }
  8071. #endif
  8072. }
  8073. bool CharacterFunctions::isLowerCase (const char character) throw()
  8074. {
  8075. return islower (character) != 0;
  8076. }
  8077. bool CharacterFunctions::isLowerCase (const juce_wchar character) throw()
  8078. {
  8079. #if JUCE_WIN32
  8080. return iswlower (character) != 0;
  8081. #else
  8082. return toUpperCase (character) != character;
  8083. #endif
  8084. }
  8085. bool CharacterFunctions::isWhitespace (const char character) throw()
  8086. {
  8087. return character == ' ' || (character <= 13 && character >= 9);
  8088. }
  8089. bool CharacterFunctions::isWhitespace (const juce_wchar character) throw()
  8090. {
  8091. return iswspace (character) != 0;
  8092. }
  8093. bool CharacterFunctions::isDigit (const char character) throw()
  8094. {
  8095. return (character >= '0' && character <= '9');
  8096. }
  8097. bool CharacterFunctions::isDigit (const juce_wchar character) throw()
  8098. {
  8099. return iswdigit (character) != 0;
  8100. }
  8101. bool CharacterFunctions::isLetter (const char character) throw()
  8102. {
  8103. return (character >= 'a' && character <= 'z')
  8104. || (character >= 'A' && character <= 'Z');
  8105. }
  8106. bool CharacterFunctions::isLetter (const juce_wchar character) throw()
  8107. {
  8108. return iswalpha (character) != 0;
  8109. }
  8110. bool CharacterFunctions::isLetterOrDigit (const char character) throw()
  8111. {
  8112. return (character >= 'a' && character <= 'z')
  8113. || (character >= 'A' && character <= 'Z')
  8114. || (character >= '0' && character <= '9');
  8115. }
  8116. bool CharacterFunctions::isLetterOrDigit (const juce_wchar character) throw()
  8117. {
  8118. return iswalnum (character) != 0;
  8119. }
  8120. int CharacterFunctions::getHexDigitValue (const juce_wchar digit) throw()
  8121. {
  8122. if (digit >= '0' && digit <= '9')
  8123. return digit - '0';
  8124. else if (digit >= 'a' && digit <= 'f')
  8125. return digit - ('a' - 10);
  8126. else if (digit >= 'A' && digit <= 'F')
  8127. return digit - ('A' - 10);
  8128. return -1;
  8129. }
  8130. END_JUCE_NAMESPACE
  8131. /*** End of inlined file: juce_CharacterFunctions.cpp ***/
  8132. /*** Start of inlined file: juce_LocalisedStrings.cpp ***/
  8133. BEGIN_JUCE_NAMESPACE
  8134. LocalisedStrings::LocalisedStrings (const String& fileContents)
  8135. {
  8136. loadFromText (fileContents);
  8137. }
  8138. LocalisedStrings::LocalisedStrings (const File& fileToLoad)
  8139. {
  8140. loadFromText (fileToLoad.loadFileAsString());
  8141. }
  8142. LocalisedStrings::~LocalisedStrings()
  8143. {
  8144. }
  8145. const String LocalisedStrings::translate (const String& text) const
  8146. {
  8147. return translations.getValue (text, text);
  8148. }
  8149. static int findCloseQuote (const String& text, int startPos)
  8150. {
  8151. juce_wchar lastChar = 0;
  8152. for (;;)
  8153. {
  8154. const juce_wchar c = text [startPos];
  8155. if (c == 0 || (c == '"' && lastChar != '\\'))
  8156. break;
  8157. lastChar = c;
  8158. ++startPos;
  8159. }
  8160. return startPos;
  8161. }
  8162. static const String unescapeString (const String& s)
  8163. {
  8164. return s.replace ("\\\"", "\"")
  8165. .replace ("\\\'", "\'")
  8166. .replace ("\\t", "\t")
  8167. .replace ("\\r", "\r")
  8168. .replace ("\\n", "\n");
  8169. }
  8170. void LocalisedStrings::loadFromText (const String& fileContents)
  8171. {
  8172. StringArray lines;
  8173. lines.addLines (fileContents);
  8174. for (int i = 0; i < lines.size(); ++i)
  8175. {
  8176. String line (lines[i].trim());
  8177. if (line.startsWithChar ('"'))
  8178. {
  8179. int closeQuote = findCloseQuote (line, 1);
  8180. const String originalText (unescapeString (line.substring (1, closeQuote)));
  8181. if (originalText.isNotEmpty())
  8182. {
  8183. const int openingQuote = findCloseQuote (line, closeQuote + 1);
  8184. closeQuote = findCloseQuote (line, openingQuote + 1);
  8185. const String newText (unescapeString (line.substring (openingQuote + 1, closeQuote)));
  8186. if (newText.isNotEmpty())
  8187. translations.set (originalText, newText);
  8188. }
  8189. }
  8190. else if (line.startsWithIgnoreCase ("language:"))
  8191. {
  8192. languageName = line.substring (9).trim();
  8193. }
  8194. else if (line.startsWithIgnoreCase ("countries:"))
  8195. {
  8196. countryCodes.addTokens (line.substring (10).trim(), true);
  8197. countryCodes.trim();
  8198. countryCodes.removeEmptyStrings();
  8199. }
  8200. }
  8201. }
  8202. void LocalisedStrings::setIgnoresCase (const bool shouldIgnoreCase)
  8203. {
  8204. translations.setIgnoresCase (shouldIgnoreCase);
  8205. }
  8206. static CriticalSection currentMappingsLock;
  8207. static LocalisedStrings* currentMappings = 0;
  8208. void LocalisedStrings::setCurrentMappings (LocalisedStrings* newTranslations)
  8209. {
  8210. const ScopedLock sl (currentMappingsLock);
  8211. delete currentMappings;
  8212. currentMappings = newTranslations;
  8213. }
  8214. LocalisedStrings* LocalisedStrings::getCurrentMappings()
  8215. {
  8216. return currentMappings;
  8217. }
  8218. const String LocalisedStrings::translateWithCurrentMappings (const String& text)
  8219. {
  8220. const ScopedLock sl (currentMappingsLock);
  8221. if (currentMappings != 0)
  8222. return currentMappings->translate (text);
  8223. return text;
  8224. }
  8225. const String LocalisedStrings::translateWithCurrentMappings (const char* text)
  8226. {
  8227. return translateWithCurrentMappings (String (text));
  8228. }
  8229. END_JUCE_NAMESPACE
  8230. /*** End of inlined file: juce_LocalisedStrings.cpp ***/
  8231. /*** Start of inlined file: juce_String.cpp ***/
  8232. #ifdef _MSC_VER
  8233. #pragma warning (push)
  8234. #pragma warning (disable: 4514)
  8235. #endif
  8236. #include <locale>
  8237. #if JUCE_MSVC
  8238. #include <float.h>
  8239. #endif
  8240. BEGIN_JUCE_NAMESPACE
  8241. #ifdef _MSC_VER
  8242. #pragma warning (pop)
  8243. #endif
  8244. #if defined (JUCE_STRINGS_ARE_UNICODE) && ! JUCE_STRINGS_ARE_UNICODE
  8245. #error "JUCE_STRINGS_ARE_UNICODE is deprecated! All strings are now unicode by default."
  8246. #endif
  8247. class StringHolder
  8248. {
  8249. public:
  8250. StringHolder()
  8251. : refCount (0x3fffffff), allocatedNumChars (0)
  8252. {
  8253. text[0] = 0;
  8254. }
  8255. static juce_wchar* createUninitialised (const size_t numChars)
  8256. {
  8257. StringHolder* const s = reinterpret_cast <StringHolder*> (new char [sizeof (StringHolder) + numChars * sizeof (juce_wchar)]);
  8258. s->refCount.value = 0;
  8259. s->allocatedNumChars = numChars;
  8260. return &(s->text[0]);
  8261. }
  8262. static juce_wchar* createCopy (const juce_wchar* const src, const size_t numChars)
  8263. {
  8264. juce_wchar* const dest = createUninitialised (numChars);
  8265. copyChars (dest, src, numChars);
  8266. return dest;
  8267. }
  8268. static juce_wchar* createCopy (const char* const src, const size_t numChars)
  8269. {
  8270. juce_wchar* const dest = createUninitialised (numChars);
  8271. CharacterFunctions::copy (dest, src, (int) numChars);
  8272. dest [numChars] = 0;
  8273. return dest;
  8274. }
  8275. static inline juce_wchar* getEmpty() throw()
  8276. {
  8277. return &(empty.text[0]);
  8278. }
  8279. static void retain (juce_wchar* const text) throw()
  8280. {
  8281. ++(bufferFromText (text)->refCount);
  8282. }
  8283. static inline void release (StringHolder* const b) throw()
  8284. {
  8285. if (--(b->refCount) == -1 && b != &empty)
  8286. delete[] reinterpret_cast <char*> (b);
  8287. }
  8288. static void release (juce_wchar* const text) throw()
  8289. {
  8290. release (bufferFromText (text));
  8291. }
  8292. static juce_wchar* makeUnique (juce_wchar* const text)
  8293. {
  8294. StringHolder* const b = bufferFromText (text);
  8295. if (b->refCount.get() <= 0)
  8296. return text;
  8297. juce_wchar* const newText = createCopy (text, b->allocatedNumChars);
  8298. release (b);
  8299. return newText;
  8300. }
  8301. static juce_wchar* makeUniqueWithSize (juce_wchar* const text, size_t numChars)
  8302. {
  8303. StringHolder* const b = bufferFromText (text);
  8304. if (b->refCount.get() <= 0 && b->allocatedNumChars >= numChars)
  8305. return text;
  8306. juce_wchar* const newText = createUninitialised (jmax (b->allocatedNumChars, numChars));
  8307. copyChars (newText, text, b->allocatedNumChars);
  8308. release (b);
  8309. return newText;
  8310. }
  8311. static size_t getAllocatedNumChars (juce_wchar* const text) throw()
  8312. {
  8313. return bufferFromText (text)->allocatedNumChars;
  8314. }
  8315. static void copyChars (juce_wchar* const dest, const juce_wchar* const src, const size_t numChars) throw()
  8316. {
  8317. memcpy (dest, src, numChars * sizeof (juce_wchar));
  8318. dest [numChars] = 0;
  8319. }
  8320. Atomic<int> refCount;
  8321. size_t allocatedNumChars;
  8322. juce_wchar text[1];
  8323. static StringHolder empty;
  8324. private:
  8325. static inline StringHolder* bufferFromText (void* const text) throw()
  8326. {
  8327. // (Can't use offsetof() here because of warnings about this not being a POD)
  8328. return reinterpret_cast <StringHolder*> (static_cast <char*> (text)
  8329. - (reinterpret_cast <size_t> (reinterpret_cast <StringHolder*> (1)->text) - 1));
  8330. }
  8331. };
  8332. StringHolder StringHolder::empty;
  8333. const String String::empty;
  8334. void String::createInternal (const juce_wchar* const t, const size_t numChars)
  8335. {
  8336. jassert (t[numChars] == 0); // must have a null terminator
  8337. text = StringHolder::createCopy (t, numChars);
  8338. }
  8339. void String::appendInternal (const juce_wchar* const newText, const int numExtraChars)
  8340. {
  8341. if (numExtraChars > 0)
  8342. {
  8343. const int oldLen = length();
  8344. const int newTotalLen = oldLen + numExtraChars;
  8345. text = StringHolder::makeUniqueWithSize (text, newTotalLen);
  8346. StringHolder::copyChars (text + oldLen, newText, numExtraChars);
  8347. }
  8348. }
  8349. void String::preallocateStorage (const size_t numChars)
  8350. {
  8351. text = StringHolder::makeUniqueWithSize (text, numChars);
  8352. }
  8353. String::String() throw()
  8354. : text (StringHolder::getEmpty())
  8355. {
  8356. }
  8357. String::~String() throw()
  8358. {
  8359. StringHolder::release (text);
  8360. }
  8361. String::String (const String& other) throw()
  8362. : text (other.text)
  8363. {
  8364. StringHolder::retain (text);
  8365. }
  8366. void String::swapWith (String& other) throw()
  8367. {
  8368. swapVariables (text, other.text);
  8369. }
  8370. String& String::operator= (const String& other) throw()
  8371. {
  8372. juce_wchar* const newText = other.text;
  8373. StringHolder::retain (newText);
  8374. StringHolder::release (reinterpret_cast <Atomic<juce_wchar*>*> (&text)->exchange (newText));
  8375. return *this;
  8376. }
  8377. String::String (const size_t numChars, const int /*dummyVariable*/)
  8378. : text (StringHolder::createUninitialised (numChars))
  8379. {
  8380. }
  8381. String::String (const String& stringToCopy, const size_t charsToAllocate)
  8382. {
  8383. const size_t otherSize = StringHolder::getAllocatedNumChars (stringToCopy.text);
  8384. text = StringHolder::createUninitialised (jmax (charsToAllocate, otherSize));
  8385. StringHolder::copyChars (text, stringToCopy.text, otherSize);
  8386. }
  8387. String::String (const char* const t)
  8388. {
  8389. if (t != 0 && *t != 0)
  8390. text = StringHolder::createCopy (t, CharacterFunctions::length (t));
  8391. else
  8392. text = StringHolder::getEmpty();
  8393. }
  8394. String::String (const juce_wchar* const t)
  8395. {
  8396. if (t != 0 && *t != 0)
  8397. text = StringHolder::createCopy (t, CharacterFunctions::length (t));
  8398. else
  8399. text = StringHolder::getEmpty();
  8400. }
  8401. String::String (const char* const t, const size_t maxChars)
  8402. {
  8403. int i;
  8404. for (i = 0; (size_t) i < maxChars; ++i)
  8405. if (t[i] == 0)
  8406. break;
  8407. if (i > 0)
  8408. text = StringHolder::createCopy (t, i);
  8409. else
  8410. text = StringHolder::getEmpty();
  8411. }
  8412. String::String (const juce_wchar* const t, const size_t maxChars)
  8413. {
  8414. int i;
  8415. for (i = 0; (size_t) i < maxChars; ++i)
  8416. if (t[i] == 0)
  8417. break;
  8418. if (i > 0)
  8419. text = StringHolder::createCopy (t, i);
  8420. else
  8421. text = StringHolder::getEmpty();
  8422. }
  8423. const String String::charToString (const juce_wchar character)
  8424. {
  8425. String result ((size_t) 1, (int) 0);
  8426. result.text[0] = character;
  8427. result.text[1] = 0;
  8428. return result;
  8429. }
  8430. namespace NumberToStringConverters
  8431. {
  8432. // pass in a pointer to the END of a buffer..
  8433. static juce_wchar* int64ToString (juce_wchar* t, const int64 n) throw()
  8434. {
  8435. *--t = 0;
  8436. int64 v = (n >= 0) ? n : -n;
  8437. do
  8438. {
  8439. *--t = (juce_wchar) ('0' + (int) (v % 10));
  8440. v /= 10;
  8441. } while (v > 0);
  8442. if (n < 0)
  8443. *--t = '-';
  8444. return t;
  8445. }
  8446. static juce_wchar* uint64ToString (juce_wchar* t, int64 v) throw()
  8447. {
  8448. *--t = 0;
  8449. do
  8450. {
  8451. *--t = (juce_wchar) ('0' + (int) (v % 10));
  8452. v /= 10;
  8453. } while (v > 0);
  8454. return t;
  8455. }
  8456. static juce_wchar* intToString (juce_wchar* t, const int n) throw()
  8457. {
  8458. if (n == (int) 0x80000000) // (would cause an overflow)
  8459. return int64ToString (t, n);
  8460. *--t = 0;
  8461. int v = abs (n);
  8462. do
  8463. {
  8464. *--t = (juce_wchar) ('0' + (v % 10));
  8465. v /= 10;
  8466. } while (v > 0);
  8467. if (n < 0)
  8468. *--t = '-';
  8469. return t;
  8470. }
  8471. static juce_wchar* uintToString (juce_wchar* t, unsigned int v) throw()
  8472. {
  8473. *--t = 0;
  8474. do
  8475. {
  8476. *--t = (juce_wchar) ('0' + (v % 10));
  8477. v /= 10;
  8478. } while (v > 0);
  8479. return t;
  8480. }
  8481. static juce_wchar getDecimalPoint()
  8482. {
  8483. #if JUCE_WINDOWS && _MSC_VER < 1400
  8484. static juce_wchar dp = std::_USE (std::locale(), std::numpunct <wchar_t>).decimal_point();
  8485. #else
  8486. static juce_wchar dp = std::use_facet <std::numpunct <wchar_t> > (std::locale()).decimal_point();
  8487. #endif
  8488. return dp;
  8489. }
  8490. static juce_wchar* doubleToString (juce_wchar* buffer, int numChars, double n, int numDecPlaces, size_t& len) throw()
  8491. {
  8492. if (numDecPlaces > 0 && n > -1.0e20 && n < 1.0e20)
  8493. {
  8494. juce_wchar* const end = buffer + numChars;
  8495. juce_wchar* t = end;
  8496. int64 v = (int64) (pow (10.0, numDecPlaces) * std::abs (n) + 0.5);
  8497. *--t = (juce_wchar) 0;
  8498. while (numDecPlaces >= 0 || v > 0)
  8499. {
  8500. if (numDecPlaces == 0)
  8501. *--t = getDecimalPoint();
  8502. *--t = (juce_wchar) ('0' + (v % 10));
  8503. v /= 10;
  8504. --numDecPlaces;
  8505. }
  8506. if (n < 0)
  8507. *--t = '-';
  8508. len = end - t - 1;
  8509. return t;
  8510. }
  8511. else
  8512. {
  8513. #if JUCE_WIN32
  8514. #if _MSC_VER <= 1400
  8515. len = _snwprintf (buffer, numChars, L"%.9g", n);
  8516. #else
  8517. len = _snwprintf_s (buffer, numChars, _TRUNCATE, L"%.9g", n);
  8518. #endif
  8519. #else
  8520. len = swprintf (buffer, numChars, L"%.9g", n);
  8521. #endif
  8522. return buffer;
  8523. }
  8524. }
  8525. }
  8526. String::String (const int number)
  8527. {
  8528. juce_wchar buffer [16];
  8529. juce_wchar* const end = buffer + numElementsInArray (buffer);
  8530. juce_wchar* const start = NumberToStringConverters::intToString (end, number);
  8531. createInternal (start, end - start - 1);
  8532. }
  8533. String::String (const unsigned int number)
  8534. {
  8535. juce_wchar buffer [16];
  8536. juce_wchar* const end = buffer + numElementsInArray (buffer);
  8537. juce_wchar* const start = NumberToStringConverters::uintToString (end, number);
  8538. createInternal (start, end - start - 1);
  8539. }
  8540. String::String (const short number)
  8541. {
  8542. juce_wchar buffer [16];
  8543. juce_wchar* const end = buffer + numElementsInArray (buffer);
  8544. juce_wchar* const start = NumberToStringConverters::intToString (end, (int) number);
  8545. createInternal (start, end - start - 1);
  8546. }
  8547. String::String (const unsigned short number)
  8548. {
  8549. juce_wchar buffer [16];
  8550. juce_wchar* const end = buffer + numElementsInArray (buffer);
  8551. juce_wchar* const start = NumberToStringConverters::uintToString (end, (unsigned int) number);
  8552. createInternal (start, end - start - 1);
  8553. }
  8554. String::String (const int64 number)
  8555. {
  8556. juce_wchar buffer [32];
  8557. juce_wchar* const end = buffer + numElementsInArray (buffer);
  8558. juce_wchar* const start = NumberToStringConverters::int64ToString (end, number);
  8559. createInternal (start, end - start - 1);
  8560. }
  8561. String::String (const uint64 number)
  8562. {
  8563. juce_wchar buffer [32];
  8564. juce_wchar* const end = buffer + numElementsInArray (buffer);
  8565. juce_wchar* const start = NumberToStringConverters::uint64ToString (end, number);
  8566. createInternal (start, end - start - 1);
  8567. }
  8568. String::String (const float number, const int numberOfDecimalPlaces)
  8569. {
  8570. juce_wchar buffer [48];
  8571. size_t len;
  8572. juce_wchar* start = NumberToStringConverters::doubleToString (buffer, numElementsInArray (buffer), (double) number, numberOfDecimalPlaces, len);
  8573. createInternal (start, len);
  8574. }
  8575. String::String (const double number, const int numberOfDecimalPlaces)
  8576. {
  8577. juce_wchar buffer [48];
  8578. size_t len;
  8579. juce_wchar* start = NumberToStringConverters::doubleToString (buffer, numElementsInArray (buffer), number, numberOfDecimalPlaces, len);
  8580. createInternal (start, len);
  8581. }
  8582. int String::length() const throw()
  8583. {
  8584. return CharacterFunctions::length (text);
  8585. }
  8586. int String::hashCode() const throw()
  8587. {
  8588. const juce_wchar* t = text;
  8589. int result = 0;
  8590. while (*t != (juce_wchar) 0)
  8591. result = 31 * result + *t++;
  8592. return result;
  8593. }
  8594. int64 String::hashCode64() const throw()
  8595. {
  8596. const juce_wchar* t = text;
  8597. int64 result = 0;
  8598. while (*t != (juce_wchar) 0)
  8599. result = 101 * result + *t++;
  8600. return result;
  8601. }
  8602. bool JUCE_CALLTYPE operator== (const String& string1, const String& string2) throw()
  8603. {
  8604. return string1.compare (string2) == 0;
  8605. }
  8606. bool JUCE_CALLTYPE operator== (const String& string1, const char* string2) throw()
  8607. {
  8608. return string1.compare (string2) == 0;
  8609. }
  8610. bool JUCE_CALLTYPE operator== (const String& string1, const juce_wchar* string2) throw()
  8611. {
  8612. return string1.compare (string2) == 0;
  8613. }
  8614. bool JUCE_CALLTYPE operator!= (const String& string1, const String& string2) throw()
  8615. {
  8616. return string1.compare (string2) != 0;
  8617. }
  8618. bool JUCE_CALLTYPE operator!= (const String& string1, const char* string2) throw()
  8619. {
  8620. return string1.compare (string2) != 0;
  8621. }
  8622. bool JUCE_CALLTYPE operator!= (const String& string1, const juce_wchar* string2) throw()
  8623. {
  8624. return string1.compare (string2) != 0;
  8625. }
  8626. bool JUCE_CALLTYPE operator> (const String& string1, const String& string2) throw()
  8627. {
  8628. return string1.compare (string2) > 0;
  8629. }
  8630. bool JUCE_CALLTYPE operator< (const String& string1, const String& string2) throw()
  8631. {
  8632. return string1.compare (string2) < 0;
  8633. }
  8634. bool JUCE_CALLTYPE operator>= (const String& string1, const String& string2) throw()
  8635. {
  8636. return string1.compare (string2) >= 0;
  8637. }
  8638. bool JUCE_CALLTYPE operator<= (const String& string1, const String& string2) throw()
  8639. {
  8640. return string1.compare (string2) <= 0;
  8641. }
  8642. bool String::equalsIgnoreCase (const juce_wchar* t) const throw()
  8643. {
  8644. return t != 0 ? CharacterFunctions::compareIgnoreCase (text, t) == 0
  8645. : isEmpty();
  8646. }
  8647. bool String::equalsIgnoreCase (const char* t) const throw()
  8648. {
  8649. return t != 0 ? CharacterFunctions::compareIgnoreCase (text, t) == 0
  8650. : isEmpty();
  8651. }
  8652. bool String::equalsIgnoreCase (const String& other) const throw()
  8653. {
  8654. return text == other.text
  8655. || CharacterFunctions::compareIgnoreCase (text, other.text) == 0;
  8656. }
  8657. int String::compare (const String& other) const throw()
  8658. {
  8659. return (text == other.text) ? 0 : CharacterFunctions::compare (text, other.text);
  8660. }
  8661. int String::compare (const char* other) const throw()
  8662. {
  8663. return other == 0 ? isEmpty() : CharacterFunctions::compare (text, other);
  8664. }
  8665. int String::compare (const juce_wchar* other) const throw()
  8666. {
  8667. return other == 0 ? isEmpty() : CharacterFunctions::compare (text, other);
  8668. }
  8669. int String::compareIgnoreCase (const String& other) const throw()
  8670. {
  8671. return (text == other.text) ? 0 : CharacterFunctions::compareIgnoreCase (text, other.text);
  8672. }
  8673. int String::compareLexicographically (const String& other) const throw()
  8674. {
  8675. const juce_wchar* s1 = text;
  8676. while (*s1 != 0 && ! CharacterFunctions::isLetterOrDigit (*s1))
  8677. ++s1;
  8678. const juce_wchar* s2 = other.text;
  8679. while (*s2 != 0 && ! CharacterFunctions::isLetterOrDigit (*s2))
  8680. ++s2;
  8681. return CharacterFunctions::compareIgnoreCase (s1, s2);
  8682. }
  8683. String& String::operator+= (const juce_wchar* const t)
  8684. {
  8685. if (t != 0)
  8686. appendInternal (t, CharacterFunctions::length (t));
  8687. return *this;
  8688. }
  8689. String& String::operator+= (const String& other)
  8690. {
  8691. if (isEmpty())
  8692. operator= (other);
  8693. else
  8694. appendInternal (other.text, other.length());
  8695. return *this;
  8696. }
  8697. String& String::operator+= (const char ch)
  8698. {
  8699. const juce_wchar asString[] = { (juce_wchar) ch, 0 };
  8700. return operator+= (static_cast <const juce_wchar*> (asString));
  8701. }
  8702. String& String::operator+= (const juce_wchar ch)
  8703. {
  8704. const juce_wchar asString[] = { (juce_wchar) ch, 0 };
  8705. return operator+= (static_cast <const juce_wchar*> (asString));
  8706. }
  8707. String& String::operator+= (const int number)
  8708. {
  8709. juce_wchar buffer [16];
  8710. juce_wchar* const end = buffer + numElementsInArray (buffer);
  8711. juce_wchar* const start = NumberToStringConverters::intToString (end, number);
  8712. appendInternal (start, (int) (end - start));
  8713. return *this;
  8714. }
  8715. String& String::operator+= (const unsigned int number)
  8716. {
  8717. juce_wchar buffer [16];
  8718. juce_wchar* const end = buffer + numElementsInArray (buffer);
  8719. juce_wchar* const start = NumberToStringConverters::uintToString (end, number);
  8720. appendInternal (start, (int) (end - start));
  8721. return *this;
  8722. }
  8723. void String::append (const juce_wchar* const other, const int howMany)
  8724. {
  8725. if (howMany > 0)
  8726. {
  8727. int i;
  8728. for (i = 0; i < howMany; ++i)
  8729. if (other[i] == 0)
  8730. break;
  8731. appendInternal (other, i);
  8732. }
  8733. }
  8734. const String JUCE_CALLTYPE operator+ (const char* const string1, const String& string2)
  8735. {
  8736. String s (string1);
  8737. return s += string2;
  8738. }
  8739. const String JUCE_CALLTYPE operator+ (const juce_wchar* const string1, const String& string2)
  8740. {
  8741. String s (string1);
  8742. return s += string2;
  8743. }
  8744. const String JUCE_CALLTYPE operator+ (const char string1, const String& string2)
  8745. {
  8746. return String::charToString (string1) + string2;
  8747. }
  8748. const String JUCE_CALLTYPE operator+ (const juce_wchar string1, const String& string2)
  8749. {
  8750. return String::charToString (string1) + string2;
  8751. }
  8752. const String JUCE_CALLTYPE operator+ (String string1, const String& string2)
  8753. {
  8754. return string1 += string2;
  8755. }
  8756. const String JUCE_CALLTYPE operator+ (String string1, const char* const string2)
  8757. {
  8758. return string1 += string2;
  8759. }
  8760. const String JUCE_CALLTYPE operator+ (String string1, const juce_wchar* const string2)
  8761. {
  8762. return string1 += string2;
  8763. }
  8764. const String JUCE_CALLTYPE operator+ (String string1, const char string2)
  8765. {
  8766. return string1 += string2;
  8767. }
  8768. const String JUCE_CALLTYPE operator+ (String string1, const juce_wchar string2)
  8769. {
  8770. return string1 += string2;
  8771. }
  8772. String& JUCE_CALLTYPE operator<< (String& string1, const char characterToAppend)
  8773. {
  8774. return string1 += characterToAppend;
  8775. }
  8776. String& JUCE_CALLTYPE operator<< (String& string1, const juce_wchar characterToAppend)
  8777. {
  8778. return string1 += characterToAppend;
  8779. }
  8780. String& JUCE_CALLTYPE operator<< (String& string1, const char* const string2)
  8781. {
  8782. return string1 += string2;
  8783. }
  8784. String& JUCE_CALLTYPE operator<< (String& string1, const juce_wchar* const string2)
  8785. {
  8786. return string1 += string2;
  8787. }
  8788. String& JUCE_CALLTYPE operator<< (String& string1, const String& string2)
  8789. {
  8790. return string1 += string2;
  8791. }
  8792. String& JUCE_CALLTYPE operator<< (String& string1, const short number)
  8793. {
  8794. return string1 += (int) number;
  8795. }
  8796. String& JUCE_CALLTYPE operator<< (String& string1, const int number)
  8797. {
  8798. return string1 += number;
  8799. }
  8800. String& JUCE_CALLTYPE operator<< (String& string1, const unsigned int number)
  8801. {
  8802. return string1 += number;
  8803. }
  8804. String& JUCE_CALLTYPE operator<< (String& string1, const long number)
  8805. {
  8806. return string1 += (int) number;
  8807. }
  8808. String& JUCE_CALLTYPE operator<< (String& string1, const unsigned long number)
  8809. {
  8810. return string1 += (unsigned int) number;
  8811. }
  8812. String& JUCE_CALLTYPE operator<< (String& string1, const float number)
  8813. {
  8814. return string1 += String (number);
  8815. }
  8816. String& JUCE_CALLTYPE operator<< (String& string1, const double number)
  8817. {
  8818. return string1 += String (number);
  8819. }
  8820. OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, const String& text)
  8821. {
  8822. // (This avoids using toUTF8() to prevent the memory bloat that it would leave behind
  8823. // if lots of large, persistent strings were to be written to streams).
  8824. const int numBytes = text.getNumBytesAsUTF8();
  8825. HeapBlock<char> temp (numBytes + 1);
  8826. text.copyToUTF8 (temp, numBytes + 1);
  8827. stream.write (temp, numBytes);
  8828. return stream;
  8829. }
  8830. int String::indexOfChar (const juce_wchar character) const throw()
  8831. {
  8832. const juce_wchar* t = text;
  8833. for (;;)
  8834. {
  8835. if (*t == character)
  8836. return (int) (t - text);
  8837. if (*t++ == 0)
  8838. return -1;
  8839. }
  8840. }
  8841. int String::lastIndexOfChar (const juce_wchar character) const throw()
  8842. {
  8843. for (int i = length(); --i >= 0;)
  8844. if (text[i] == character)
  8845. return i;
  8846. return -1;
  8847. }
  8848. int String::indexOf (const String& t) const throw()
  8849. {
  8850. const juce_wchar* const r = CharacterFunctions::find (text, t.text);
  8851. return r == 0 ? -1 : (int) (r - text);
  8852. }
  8853. int String::indexOfChar (const int startIndex,
  8854. const juce_wchar character) const throw()
  8855. {
  8856. if (startIndex > 0 && startIndex >= length())
  8857. return -1;
  8858. const juce_wchar* t = text + jmax (0, startIndex);
  8859. for (;;)
  8860. {
  8861. if (*t == character)
  8862. return (int) (t - text);
  8863. if (*t == 0)
  8864. return -1;
  8865. ++t;
  8866. }
  8867. }
  8868. int String::indexOfAnyOf (const String& charactersToLookFor,
  8869. const int startIndex,
  8870. const bool ignoreCase) const throw()
  8871. {
  8872. if (startIndex > 0 && startIndex >= length())
  8873. return -1;
  8874. const juce_wchar* t = text + jmax (0, startIndex);
  8875. while (*t != 0)
  8876. {
  8877. if (CharacterFunctions::indexOfChar (charactersToLookFor.text, *t, ignoreCase) >= 0)
  8878. return (int) (t - text);
  8879. ++t;
  8880. }
  8881. return -1;
  8882. }
  8883. int String::indexOf (const int startIndex, const String& other) const throw()
  8884. {
  8885. if (startIndex > 0 && startIndex >= length())
  8886. return -1;
  8887. const juce_wchar* const found = CharacterFunctions::find (text + jmax (0, startIndex), other.text);
  8888. return found == 0 ? -1 : (int) (found - text);
  8889. }
  8890. int String::indexOfIgnoreCase (const String& other) const throw()
  8891. {
  8892. if (other.isNotEmpty())
  8893. {
  8894. const int len = other.length();
  8895. const int end = length() - len;
  8896. for (int i = 0; i <= end; ++i)
  8897. if (CharacterFunctions::compareIgnoreCase (text + i, other.text, len) == 0)
  8898. return i;
  8899. }
  8900. return -1;
  8901. }
  8902. int String::indexOfIgnoreCase (const int startIndex, const String& other) const throw()
  8903. {
  8904. if (other.isNotEmpty())
  8905. {
  8906. const int len = other.length();
  8907. const int end = length() - len;
  8908. for (int i = jmax (0, startIndex); i <= end; ++i)
  8909. if (CharacterFunctions::compareIgnoreCase (text + i, other.text, len) == 0)
  8910. return i;
  8911. }
  8912. return -1;
  8913. }
  8914. int String::lastIndexOf (const String& other) const throw()
  8915. {
  8916. if (other.isNotEmpty())
  8917. {
  8918. const int len = other.length();
  8919. int i = length() - len;
  8920. if (i >= 0)
  8921. {
  8922. const juce_wchar* n = text + i;
  8923. while (i >= 0)
  8924. {
  8925. if (CharacterFunctions::compare (n--, other.text, len) == 0)
  8926. return i;
  8927. --i;
  8928. }
  8929. }
  8930. }
  8931. return -1;
  8932. }
  8933. int String::lastIndexOfIgnoreCase (const String& other) const throw()
  8934. {
  8935. if (other.isNotEmpty())
  8936. {
  8937. const int len = other.length();
  8938. int i = length() - len;
  8939. if (i >= 0)
  8940. {
  8941. const juce_wchar* n = text + i;
  8942. while (i >= 0)
  8943. {
  8944. if (CharacterFunctions::compareIgnoreCase (n--, other.text, len) == 0)
  8945. return i;
  8946. --i;
  8947. }
  8948. }
  8949. }
  8950. return -1;
  8951. }
  8952. int String::lastIndexOfAnyOf (const String& charactersToLookFor, const bool ignoreCase) const throw()
  8953. {
  8954. for (int i = length(); --i >= 0;)
  8955. if (CharacterFunctions::indexOfChar (charactersToLookFor.text, text[i], ignoreCase) >= 0)
  8956. return i;
  8957. return -1;
  8958. }
  8959. bool String::contains (const String& other) const throw()
  8960. {
  8961. return indexOf (other) >= 0;
  8962. }
  8963. bool String::containsChar (const juce_wchar character) const throw()
  8964. {
  8965. const juce_wchar* t = text;
  8966. for (;;)
  8967. {
  8968. if (*t == 0)
  8969. return false;
  8970. if (*t == character)
  8971. return true;
  8972. ++t;
  8973. }
  8974. }
  8975. bool String::containsIgnoreCase (const String& t) const throw()
  8976. {
  8977. return indexOfIgnoreCase (t) >= 0;
  8978. }
  8979. int String::indexOfWholeWord (const String& word) const throw()
  8980. {
  8981. if (word.isNotEmpty())
  8982. {
  8983. const int wordLen = word.length();
  8984. const int end = length() - wordLen;
  8985. const juce_wchar* t = text;
  8986. for (int i = 0; i <= end; ++i)
  8987. {
  8988. if (CharacterFunctions::compare (t, word.text, wordLen) == 0
  8989. && (i == 0 || ! CharacterFunctions::isLetterOrDigit (* (t - 1)))
  8990. && ! CharacterFunctions::isLetterOrDigit (t [wordLen]))
  8991. {
  8992. return i;
  8993. }
  8994. ++t;
  8995. }
  8996. }
  8997. return -1;
  8998. }
  8999. int String::indexOfWholeWordIgnoreCase (const String& word) const throw()
  9000. {
  9001. if (word.isNotEmpty())
  9002. {
  9003. const int wordLen = word.length();
  9004. const int end = length() - wordLen;
  9005. const juce_wchar* t = text;
  9006. for (int i = 0; i <= end; ++i)
  9007. {
  9008. if (CharacterFunctions::compareIgnoreCase (t, word.text, wordLen) == 0
  9009. && (i == 0 || ! CharacterFunctions::isLetterOrDigit (* (t - 1)))
  9010. && ! CharacterFunctions::isLetterOrDigit (t [wordLen]))
  9011. {
  9012. return i;
  9013. }
  9014. ++t;
  9015. }
  9016. }
  9017. return -1;
  9018. }
  9019. bool String::containsWholeWord (const String& wordToLookFor) const throw()
  9020. {
  9021. return indexOfWholeWord (wordToLookFor) >= 0;
  9022. }
  9023. bool String::containsWholeWordIgnoreCase (const String& wordToLookFor) const throw()
  9024. {
  9025. return indexOfWholeWordIgnoreCase (wordToLookFor) >= 0;
  9026. }
  9027. static int indexOfMatch (const juce_wchar* const wildcard,
  9028. const juce_wchar* const test,
  9029. const bool ignoreCase) throw()
  9030. {
  9031. int start = 0;
  9032. while (test [start] != 0)
  9033. {
  9034. int i = 0;
  9035. for (;;)
  9036. {
  9037. const juce_wchar wc = wildcard [i];
  9038. const juce_wchar c = test [i + start];
  9039. if (wc == c
  9040. || (ignoreCase && CharacterFunctions::toLowerCase (wc) == CharacterFunctions::toLowerCase (c))
  9041. || (wc == '?' && c != 0))
  9042. {
  9043. if (wc == 0)
  9044. return start;
  9045. ++i;
  9046. }
  9047. else
  9048. {
  9049. if (wc == '*' && (wildcard [i + 1] == 0
  9050. || indexOfMatch (wildcard + i + 1,
  9051. test + start + i,
  9052. ignoreCase) >= 0))
  9053. {
  9054. return start;
  9055. }
  9056. break;
  9057. }
  9058. }
  9059. ++start;
  9060. }
  9061. return -1;
  9062. }
  9063. bool String::matchesWildcard (const String& wildcard, const bool ignoreCase) const throw()
  9064. {
  9065. int i = 0;
  9066. for (;;)
  9067. {
  9068. const juce_wchar wc = wildcard.text [i];
  9069. const juce_wchar c = text [i];
  9070. if (wc == c
  9071. || (ignoreCase && CharacterFunctions::toLowerCase (wc) == CharacterFunctions::toLowerCase (c))
  9072. || (wc == '?' && c != 0))
  9073. {
  9074. if (wc == 0)
  9075. return true;
  9076. ++i;
  9077. }
  9078. else
  9079. {
  9080. return wc == '*' && (wildcard [i + 1] == 0
  9081. || indexOfMatch (wildcard.text + i + 1,
  9082. text + i,
  9083. ignoreCase) >= 0);
  9084. }
  9085. }
  9086. }
  9087. const String String::repeatedString (const String& stringToRepeat, int numberOfTimesToRepeat)
  9088. {
  9089. const int len = stringToRepeat.length();
  9090. String result ((size_t) (len * numberOfTimesToRepeat + 1), (int) 0);
  9091. juce_wchar* n = result.text;
  9092. *n = 0;
  9093. while (--numberOfTimesToRepeat >= 0)
  9094. {
  9095. StringHolder::copyChars (n, stringToRepeat.text, len);
  9096. n += len;
  9097. }
  9098. return result;
  9099. }
  9100. const String String::paddedLeft (const juce_wchar padCharacter, int minimumLength) const
  9101. {
  9102. jassert (padCharacter != 0);
  9103. const int len = length();
  9104. if (len >= minimumLength || padCharacter == 0)
  9105. return *this;
  9106. String result ((size_t) minimumLength + 1, (int) 0);
  9107. juce_wchar* n = result.text;
  9108. minimumLength -= len;
  9109. while (--minimumLength >= 0)
  9110. *n++ = padCharacter;
  9111. StringHolder::copyChars (n, text, len);
  9112. return result;
  9113. }
  9114. const String String::paddedRight (const juce_wchar padCharacter, int minimumLength) const
  9115. {
  9116. jassert (padCharacter != 0);
  9117. const int len = length();
  9118. if (len >= minimumLength || padCharacter == 0)
  9119. return *this;
  9120. String result (*this, (size_t) minimumLength);
  9121. juce_wchar* n = result.text + len;
  9122. minimumLength -= len;
  9123. while (--minimumLength >= 0)
  9124. *n++ = padCharacter;
  9125. *n = 0;
  9126. return result;
  9127. }
  9128. const String String::replaceSection (int index, int numCharsToReplace, const String& stringToInsert) const
  9129. {
  9130. if (index < 0)
  9131. {
  9132. // a negative index to replace from?
  9133. jassertfalse
  9134. index = 0;
  9135. }
  9136. if (numCharsToReplace < 0)
  9137. {
  9138. // replacing a negative number of characters?
  9139. numCharsToReplace = 0;
  9140. jassertfalse;
  9141. }
  9142. const int len = length();
  9143. if (index + numCharsToReplace > len)
  9144. {
  9145. if (index > len)
  9146. {
  9147. // replacing beyond the end of the string?
  9148. index = len;
  9149. jassertfalse
  9150. }
  9151. numCharsToReplace = len - index;
  9152. }
  9153. const int newStringLen = stringToInsert.length();
  9154. const int newTotalLen = len + newStringLen - numCharsToReplace;
  9155. if (newTotalLen <= 0)
  9156. return String::empty;
  9157. String result ((size_t) newTotalLen, (int) 0);
  9158. StringHolder::copyChars (result.text, text, index);
  9159. if (newStringLen > 0)
  9160. StringHolder::copyChars (result.text + index, stringToInsert.text, newStringLen);
  9161. const int endStringLen = newTotalLen - (index + newStringLen);
  9162. if (endStringLen > 0)
  9163. StringHolder::copyChars (result.text + (index + newStringLen),
  9164. text + (index + numCharsToReplace),
  9165. endStringLen);
  9166. return result;
  9167. }
  9168. const String String::replace (const String& stringToReplace, const String& stringToInsert, const bool ignoreCase) const
  9169. {
  9170. const int stringToReplaceLen = stringToReplace.length();
  9171. const int stringToInsertLen = stringToInsert.length();
  9172. int i = 0;
  9173. String result (*this);
  9174. while ((i = (ignoreCase ? result.indexOfIgnoreCase (i, stringToReplace)
  9175. : result.indexOf (i, stringToReplace))) >= 0)
  9176. {
  9177. result = result.replaceSection (i, stringToReplaceLen, stringToInsert);
  9178. i += stringToInsertLen;
  9179. }
  9180. return result;
  9181. }
  9182. const String String::replaceCharacter (const juce_wchar charToReplace, const juce_wchar charToInsert) const
  9183. {
  9184. const int index = indexOfChar (charToReplace);
  9185. if (index < 0)
  9186. return *this;
  9187. String result (*this, size_t());
  9188. juce_wchar* t = result.text + index;
  9189. while (*t != 0)
  9190. {
  9191. if (*t == charToReplace)
  9192. *t = charToInsert;
  9193. ++t;
  9194. }
  9195. return result;
  9196. }
  9197. const String String::replaceCharacters (const String& charactersToReplace,
  9198. const String& charactersToInsertInstead) const
  9199. {
  9200. String result (*this, size_t());
  9201. juce_wchar* t = result.text;
  9202. const int len2 = charactersToInsertInstead.length();
  9203. // the two strings passed in are supposed to be the same length!
  9204. jassert (len2 == charactersToReplace.length());
  9205. while (*t != 0)
  9206. {
  9207. const int index = charactersToReplace.indexOfChar (*t);
  9208. if (((unsigned int) index) < (unsigned int) len2)
  9209. *t = charactersToInsertInstead [index];
  9210. ++t;
  9211. }
  9212. return result;
  9213. }
  9214. bool String::startsWith (const String& other) const throw()
  9215. {
  9216. return CharacterFunctions::compare (text, other.text, other.length()) == 0;
  9217. }
  9218. bool String::startsWithIgnoreCase (const String& other) const throw()
  9219. {
  9220. return CharacterFunctions::compareIgnoreCase (text, other.text, other.length()) == 0;
  9221. }
  9222. bool String::startsWithChar (const juce_wchar character) const throw()
  9223. {
  9224. jassert (character != 0); // strings can't contain a null character!
  9225. return text[0] == character;
  9226. }
  9227. bool String::endsWithChar (const juce_wchar character) const throw()
  9228. {
  9229. jassert (character != 0); // strings can't contain a null character!
  9230. return text[0] != 0
  9231. && text [length() - 1] == character;
  9232. }
  9233. bool String::endsWith (const String& other) const throw()
  9234. {
  9235. const int thisLen = length();
  9236. const int otherLen = other.length();
  9237. return thisLen >= otherLen
  9238. && CharacterFunctions::compare (text + thisLen - otherLen, other.text) == 0;
  9239. }
  9240. bool String::endsWithIgnoreCase (const String& other) const throw()
  9241. {
  9242. const int thisLen = length();
  9243. const int otherLen = other.length();
  9244. return thisLen >= otherLen
  9245. && CharacterFunctions::compareIgnoreCase (text + thisLen - otherLen, other.text) == 0;
  9246. }
  9247. const String String::toUpperCase() const
  9248. {
  9249. String result (*this, size_t());
  9250. CharacterFunctions::toUpperCase (result.text);
  9251. return result;
  9252. }
  9253. const String String::toLowerCase() const
  9254. {
  9255. String result (*this, size_t());
  9256. CharacterFunctions::toLowerCase (result.text);
  9257. return result;
  9258. }
  9259. juce_wchar& String::operator[] (const int index)
  9260. {
  9261. jassert (((unsigned int) index) <= (unsigned int) length());
  9262. text = StringHolder::makeUnique (text);
  9263. return text [index];
  9264. }
  9265. juce_wchar String::getLastCharacter() const throw()
  9266. {
  9267. return isEmpty() ? juce_wchar() : text [length() - 1];
  9268. }
  9269. const String String::substring (int start, int end) const
  9270. {
  9271. if (start < 0)
  9272. start = 0;
  9273. else if (end <= start)
  9274. return empty;
  9275. int len = 0;
  9276. while (len <= end && text [len] != 0)
  9277. ++len;
  9278. if (end >= len)
  9279. {
  9280. if (start == 0)
  9281. return *this;
  9282. end = len;
  9283. }
  9284. return String (text + start, end - start);
  9285. }
  9286. const String String::substring (const int start) const
  9287. {
  9288. if (start <= 0)
  9289. return *this;
  9290. const int len = length();
  9291. if (start >= len)
  9292. return empty;
  9293. return String (text + start, len - start);
  9294. }
  9295. const String String::dropLastCharacters (const int numberToDrop) const
  9296. {
  9297. return String (text, jmax (0, length() - numberToDrop));
  9298. }
  9299. const String String::getLastCharacters (const int numCharacters) const
  9300. {
  9301. return String (text + jmax (0, length() - jmax (0, numCharacters)));
  9302. }
  9303. const String String::fromFirstOccurrenceOf (const String& sub,
  9304. const bool includeSubString,
  9305. const bool ignoreCase) const
  9306. {
  9307. const int i = ignoreCase ? indexOfIgnoreCase (sub)
  9308. : indexOf (sub);
  9309. if (i < 0)
  9310. return empty;
  9311. return substring (includeSubString ? i : i + sub.length());
  9312. }
  9313. const String String::fromLastOccurrenceOf (const String& sub,
  9314. const bool includeSubString,
  9315. const bool ignoreCase) const
  9316. {
  9317. const int i = ignoreCase ? lastIndexOfIgnoreCase (sub)
  9318. : lastIndexOf (sub);
  9319. if (i < 0)
  9320. return *this;
  9321. return substring (includeSubString ? i : i + sub.length());
  9322. }
  9323. const String String::upToFirstOccurrenceOf (const String& sub,
  9324. const bool includeSubString,
  9325. const bool ignoreCase) const
  9326. {
  9327. const int i = ignoreCase ? indexOfIgnoreCase (sub)
  9328. : indexOf (sub);
  9329. if (i < 0)
  9330. return *this;
  9331. return substring (0, includeSubString ? i + sub.length() : i);
  9332. }
  9333. const String String::upToLastOccurrenceOf (const String& sub,
  9334. const bool includeSubString,
  9335. const bool ignoreCase) const
  9336. {
  9337. const int i = ignoreCase ? lastIndexOfIgnoreCase (sub)
  9338. : lastIndexOf (sub);
  9339. if (i < 0)
  9340. return *this;
  9341. return substring (0, includeSubString ? i + sub.length() : i);
  9342. }
  9343. bool String::isQuotedString() const
  9344. {
  9345. const String trimmed (trimStart());
  9346. return trimmed[0] == '"'
  9347. || trimmed[0] == '\'';
  9348. }
  9349. const String String::unquoted() const
  9350. {
  9351. String s (*this);
  9352. if (s.text[0] == '"' || s.text[0] == '\'')
  9353. s = s.substring (1);
  9354. const int lastCharIndex = s.length() - 1;
  9355. if (lastCharIndex >= 0
  9356. && (s [lastCharIndex] == '"' || s[lastCharIndex] == '\''))
  9357. s [lastCharIndex] = 0;
  9358. return s;
  9359. }
  9360. const String String::quoted (const juce_wchar quoteCharacter) const
  9361. {
  9362. if (isEmpty())
  9363. return charToString (quoteCharacter) + quoteCharacter;
  9364. String t (*this);
  9365. if (! t.startsWithChar (quoteCharacter))
  9366. t = charToString (quoteCharacter) + t;
  9367. if (! t.endsWithChar (quoteCharacter))
  9368. t += quoteCharacter;
  9369. return t;
  9370. }
  9371. const String String::trim() const
  9372. {
  9373. if (isEmpty())
  9374. return empty;
  9375. int start = 0;
  9376. while (CharacterFunctions::isWhitespace (text [start]))
  9377. ++start;
  9378. const int len = length();
  9379. int end = len - 1;
  9380. while ((end >= start) && CharacterFunctions::isWhitespace (text [end]))
  9381. --end;
  9382. ++end;
  9383. if (end <= start)
  9384. return empty;
  9385. else if (start > 0 || end < len)
  9386. return String (text + start, end - start);
  9387. return *this;
  9388. }
  9389. const String String::trimStart() const
  9390. {
  9391. if (isEmpty())
  9392. return empty;
  9393. const juce_wchar* t = text;
  9394. while (CharacterFunctions::isWhitespace (*t))
  9395. ++t;
  9396. if (t == text)
  9397. return *this;
  9398. return String (t);
  9399. }
  9400. const String String::trimEnd() const
  9401. {
  9402. if (isEmpty())
  9403. return empty;
  9404. const juce_wchar* endT = text + (length() - 1);
  9405. while ((endT >= text) && CharacterFunctions::isWhitespace (*endT))
  9406. --endT;
  9407. return String (text, (int) (++endT - text));
  9408. }
  9409. const String String::trimCharactersAtStart (const String& charactersToTrim) const
  9410. {
  9411. const juce_wchar* t = text;
  9412. while (charactersToTrim.containsChar (*t))
  9413. ++t;
  9414. return t == text ? *this : String (t);
  9415. }
  9416. const String String::trimCharactersAtEnd (const String& charactersToTrim) const
  9417. {
  9418. if (isEmpty())
  9419. return empty;
  9420. const int len = length();
  9421. const juce_wchar* endT = text + (len - 1);
  9422. int numToRemove = 0;
  9423. while (numToRemove < len && charactersToTrim.containsChar (*endT))
  9424. {
  9425. ++numToRemove;
  9426. --endT;
  9427. }
  9428. return numToRemove > 0 ? String (text, len - numToRemove) : *this;
  9429. }
  9430. const String String::retainCharacters (const String& charactersToRetain) const
  9431. {
  9432. if (isEmpty())
  9433. return empty;
  9434. String result (StringHolder::getAllocatedNumChars (text), (int) 0);
  9435. juce_wchar* dst = result.text;
  9436. const juce_wchar* src = text;
  9437. while (*src != 0)
  9438. {
  9439. if (charactersToRetain.containsChar (*src))
  9440. *dst++ = *src;
  9441. ++src;
  9442. }
  9443. *dst = 0;
  9444. return result;
  9445. }
  9446. const String String::removeCharacters (const String& charactersToRemove) const
  9447. {
  9448. if (isEmpty())
  9449. return empty;
  9450. String result (StringHolder::getAllocatedNumChars (text), (int) 0);
  9451. juce_wchar* dst = result.text;
  9452. const juce_wchar* src = text;
  9453. while (*src != 0)
  9454. {
  9455. if (! charactersToRemove.containsChar (*src))
  9456. *dst++ = *src;
  9457. ++src;
  9458. }
  9459. *dst = 0;
  9460. return result;
  9461. }
  9462. const String String::initialSectionContainingOnly (const String& permittedCharacters) const
  9463. {
  9464. int i = 0;
  9465. for (;;)
  9466. {
  9467. if (! permittedCharacters.containsChar (text[i]))
  9468. break;
  9469. ++i;
  9470. }
  9471. return substring (0, i);
  9472. }
  9473. const String String::initialSectionNotContaining (const String& charactersToStopAt) const
  9474. {
  9475. const juce_wchar* const t = text;
  9476. int i = 0;
  9477. while (t[i] != 0)
  9478. {
  9479. if (charactersToStopAt.containsChar (t[i]))
  9480. return String (text, i);
  9481. ++i;
  9482. }
  9483. return empty;
  9484. }
  9485. bool String::containsOnly (const String& chars) const throw()
  9486. {
  9487. const juce_wchar* t = text;
  9488. while (*t != 0)
  9489. if (! chars.containsChar (*t++))
  9490. return false;
  9491. return true;
  9492. }
  9493. bool String::containsAnyOf (const String& chars) const throw()
  9494. {
  9495. const juce_wchar* t = text;
  9496. while (*t != 0)
  9497. if (chars.containsChar (*t++))
  9498. return true;
  9499. return false;
  9500. }
  9501. bool String::containsNonWhitespaceChars() const throw()
  9502. {
  9503. const juce_wchar* t = text;
  9504. while (*t != 0)
  9505. if (! CharacterFunctions::isWhitespace (*t++))
  9506. return true;
  9507. return false;
  9508. }
  9509. const String String::formatted (const juce_wchar* const pf, ... )
  9510. {
  9511. jassert (pf != 0);
  9512. va_list args;
  9513. va_start (args, pf);
  9514. size_t bufferSize = 256;
  9515. String result (bufferSize, (int) 0);
  9516. result.text[0] = 0;
  9517. for (;;)
  9518. {
  9519. #if JUCE_LINUX && JUCE_64BIT
  9520. va_list tempArgs;
  9521. va_copy (tempArgs, args);
  9522. const int num = (int) vswprintf (result.text, bufferSize - 1, pf, tempArgs);
  9523. va_end (tempArgs);
  9524. #elif JUCE_WINDOWS
  9525. #ifdef _MSC_VER
  9526. #pragma warning (push)
  9527. #pragma warning (disable: 4996)
  9528. #endif
  9529. const int num = (int) _vsnwprintf (result.text, bufferSize - 1, pf, args);
  9530. #ifdef _MSC_VER
  9531. #pragma warning (pop)
  9532. #endif
  9533. #else
  9534. const int num = (int) vswprintf (result.text, bufferSize - 1, pf, args);
  9535. #endif
  9536. if (num > 0)
  9537. return result;
  9538. bufferSize += 256;
  9539. if (num == 0 || bufferSize > 65536) // the upper limit is a sanity check to avoid situations where vprintf repeatedly
  9540. break; // returns -1 because of an error rather than because it needs more space.
  9541. result.preallocateStorage (bufferSize);
  9542. }
  9543. return empty;
  9544. }
  9545. int String::getIntValue() const throw()
  9546. {
  9547. return CharacterFunctions::getIntValue (text);
  9548. }
  9549. int String::getTrailingIntValue() const throw()
  9550. {
  9551. int n = 0;
  9552. int mult = 1;
  9553. const juce_wchar* t = text + length();
  9554. while (--t >= text)
  9555. {
  9556. const juce_wchar c = *t;
  9557. if (! CharacterFunctions::isDigit (c))
  9558. {
  9559. if (c == '-')
  9560. n = -n;
  9561. break;
  9562. }
  9563. n += mult * (c - '0');
  9564. mult *= 10;
  9565. }
  9566. return n;
  9567. }
  9568. int64 String::getLargeIntValue() const throw()
  9569. {
  9570. return CharacterFunctions::getInt64Value (text);
  9571. }
  9572. float String::getFloatValue() const throw()
  9573. {
  9574. return (float) CharacterFunctions::getDoubleValue (text);
  9575. }
  9576. double String::getDoubleValue() const throw()
  9577. {
  9578. return CharacterFunctions::getDoubleValue (text);
  9579. }
  9580. static const juce_wchar* const hexDigits = T("0123456789abcdef");
  9581. const String String::toHexString (const int number)
  9582. {
  9583. juce_wchar buffer[32];
  9584. juce_wchar* const end = buffer + 32;
  9585. juce_wchar* t = end;
  9586. *--t = 0;
  9587. unsigned int v = (unsigned int) number;
  9588. do
  9589. {
  9590. *--t = hexDigits [v & 15];
  9591. v >>= 4;
  9592. } while (v != 0);
  9593. return String (t, (int) (((char*) end) - (char*) t) - 1);
  9594. }
  9595. const String String::toHexString (const int64 number)
  9596. {
  9597. juce_wchar buffer[32];
  9598. juce_wchar* const end = buffer + 32;
  9599. juce_wchar* t = end;
  9600. *--t = 0;
  9601. uint64 v = (uint64) number;
  9602. do
  9603. {
  9604. *--t = hexDigits [(int) (v & 15)];
  9605. v >>= 4;
  9606. } while (v != 0);
  9607. return String (t, (int) (((char*) end) - (char*) t));
  9608. }
  9609. const String String::toHexString (const short number)
  9610. {
  9611. return toHexString ((int) (unsigned short) number);
  9612. }
  9613. const String String::toHexString (const unsigned char* data,
  9614. const int size,
  9615. const int groupSize)
  9616. {
  9617. if (size <= 0)
  9618. return empty;
  9619. int numChars = (size * 2) + 2;
  9620. if (groupSize > 0)
  9621. numChars += size / groupSize;
  9622. String s ((size_t) numChars, (int) 0);
  9623. juce_wchar* d = s.text;
  9624. for (int i = 0; i < size; ++i)
  9625. {
  9626. *d++ = hexDigits [(*data) >> 4];
  9627. *d++ = hexDigits [(*data) & 0xf];
  9628. ++data;
  9629. if (groupSize > 0 && (i % groupSize) == (groupSize - 1) && i < (size - 1))
  9630. *d++ = ' ';
  9631. }
  9632. *d = 0;
  9633. return s;
  9634. }
  9635. int String::getHexValue32() const throw()
  9636. {
  9637. int result = 0;
  9638. const juce_wchar* c = text;
  9639. for (;;)
  9640. {
  9641. const int hexValue = CharacterFunctions::getHexDigitValue (*c);
  9642. if (hexValue >= 0)
  9643. result = (result << 4) | hexValue;
  9644. else if (*c == 0)
  9645. break;
  9646. ++c;
  9647. }
  9648. return result;
  9649. }
  9650. int64 String::getHexValue64() const throw()
  9651. {
  9652. int64 result = 0;
  9653. const juce_wchar* c = text;
  9654. for (;;)
  9655. {
  9656. const int hexValue = CharacterFunctions::getHexDigitValue (*c);
  9657. if (hexValue >= 0)
  9658. result = (result << 4) | hexValue;
  9659. else if (*c == 0)
  9660. break;
  9661. ++c;
  9662. }
  9663. return result;
  9664. }
  9665. const String String::createStringFromData (const void* const data_, const int size)
  9666. {
  9667. const char* const data = static_cast <const char*> (data_);
  9668. if (size <= 0 || data == 0)
  9669. {
  9670. return empty;
  9671. }
  9672. else if (size < 2)
  9673. {
  9674. return charToString (data[0]);
  9675. }
  9676. else if ((data[0] == (char)-2 && data[1] == (char)-1)
  9677. || (data[0] == (char)-1 && data[1] == (char)-2))
  9678. {
  9679. // assume it's 16-bit unicode
  9680. const bool bigEndian = (data[0] == (char)-2);
  9681. const int numChars = size / 2 - 1;
  9682. String result;
  9683. result.preallocateStorage (numChars + 2);
  9684. const uint16* const src = (const uint16*) (data + 2);
  9685. juce_wchar* const dst = const_cast <juce_wchar*> (static_cast <const juce_wchar*> (result));
  9686. if (bigEndian)
  9687. {
  9688. for (int i = 0; i < numChars; ++i)
  9689. dst[i] = (juce_wchar) ByteOrder::swapIfLittleEndian (src[i]);
  9690. }
  9691. else
  9692. {
  9693. for (int i = 0; i < numChars; ++i)
  9694. dst[i] = (juce_wchar) ByteOrder::swapIfBigEndian (src[i]);
  9695. }
  9696. dst [numChars] = 0;
  9697. return result;
  9698. }
  9699. else
  9700. {
  9701. return String::fromUTF8 (data, size);
  9702. }
  9703. }
  9704. const char* String::toUTF8() const
  9705. {
  9706. if (isEmpty())
  9707. {
  9708. return reinterpret_cast <const char*> (text);
  9709. }
  9710. else
  9711. {
  9712. const int currentLen = length() + 1;
  9713. const int utf8BytesNeeded = getNumBytesAsUTF8();
  9714. String* const mutableThis = const_cast <String*> (this);
  9715. mutableThis->text = StringHolder::makeUniqueWithSize (mutableThis->text, currentLen + 1 + utf8BytesNeeded / sizeof (juce_wchar));
  9716. char* const otherCopy = reinterpret_cast <char*> (mutableThis->text + currentLen);
  9717. copyToUTF8 (otherCopy, std::numeric_limits<int>::max());
  9718. return otherCopy;
  9719. }
  9720. }
  9721. int String::copyToUTF8 (char* const buffer, const int maxBufferSizeBytes) const throw()
  9722. {
  9723. jassert (maxBufferSizeBytes >= 0); // keep this value positive, or no characters will be copied!
  9724. int num = 0, index = 0;
  9725. for (;;)
  9726. {
  9727. const uint32 c = (uint32) text [index++];
  9728. if (c >= 0x80)
  9729. {
  9730. int numExtraBytes = 1;
  9731. if (c >= 0x800)
  9732. {
  9733. ++numExtraBytes;
  9734. if (c >= 0x10000)
  9735. {
  9736. ++numExtraBytes;
  9737. if (c >= 0x200000)
  9738. {
  9739. ++numExtraBytes;
  9740. if (c >= 0x4000000)
  9741. ++numExtraBytes;
  9742. }
  9743. }
  9744. }
  9745. if (buffer != 0)
  9746. {
  9747. if (num + numExtraBytes >= maxBufferSizeBytes)
  9748. {
  9749. buffer [num++] = 0;
  9750. break;
  9751. }
  9752. else
  9753. {
  9754. buffer [num++] = (uint8) ((0xff << (7 - numExtraBytes)) | (c >> (numExtraBytes * 6)));
  9755. while (--numExtraBytes >= 0)
  9756. buffer [num++] = (uint8) (0x80 | (0x3f & (c >> (numExtraBytes * 6))));
  9757. }
  9758. }
  9759. else
  9760. {
  9761. num += numExtraBytes + 1;
  9762. }
  9763. }
  9764. else
  9765. {
  9766. if (buffer != 0)
  9767. {
  9768. if (num + 1 >= maxBufferSizeBytes)
  9769. {
  9770. buffer [num++] = 0;
  9771. break;
  9772. }
  9773. buffer [num] = (uint8) c;
  9774. }
  9775. ++num;
  9776. }
  9777. if (c == 0)
  9778. break;
  9779. }
  9780. return num;
  9781. }
  9782. int String::getNumBytesAsUTF8() const throw()
  9783. {
  9784. int num = 0;
  9785. const juce_wchar* t = text;
  9786. for (;;)
  9787. {
  9788. const uint32 c = (uint32) *t;
  9789. if (c >= 0x80)
  9790. {
  9791. ++num;
  9792. if (c >= 0x800)
  9793. {
  9794. ++num;
  9795. if (c >= 0x10000)
  9796. {
  9797. ++num;
  9798. if (c >= 0x200000)
  9799. {
  9800. ++num;
  9801. if (c >= 0x4000000)
  9802. ++num;
  9803. }
  9804. }
  9805. }
  9806. }
  9807. else if (c == 0)
  9808. break;
  9809. ++num;
  9810. ++t;
  9811. }
  9812. return num;
  9813. }
  9814. const String String::fromUTF8 (const char* const buffer, int bufferSizeBytes)
  9815. {
  9816. if (buffer == 0)
  9817. return empty;
  9818. if (bufferSizeBytes < 0)
  9819. bufferSizeBytes = std::numeric_limits<int>::max();
  9820. size_t numBytes;
  9821. for (numBytes = 0; numBytes < (size_t) bufferSizeBytes; ++numBytes)
  9822. if (buffer [numBytes] == 0)
  9823. break;
  9824. String result ((size_t) numBytes + 1, (int) 0);
  9825. juce_wchar* dest = result.text;
  9826. size_t i = 0;
  9827. while (i < numBytes)
  9828. {
  9829. const char c = buffer [i++];
  9830. if (c < 0)
  9831. {
  9832. unsigned int mask = 0x7f;
  9833. int bit = 0x40;
  9834. int numExtraValues = 0;
  9835. while (bit != 0 && (c & bit) != 0)
  9836. {
  9837. bit >>= 1;
  9838. mask >>= 1;
  9839. ++numExtraValues;
  9840. }
  9841. int n = (mask & (unsigned char) c);
  9842. while (--numExtraValues >= 0 && i < (size_t) bufferSizeBytes)
  9843. {
  9844. const char nextByte = buffer[i];
  9845. if ((nextByte & 0xc0) != 0x80)
  9846. break;
  9847. n <<= 6;
  9848. n |= (nextByte & 0x3f);
  9849. ++i;
  9850. }
  9851. *dest++ = (juce_wchar) n;
  9852. }
  9853. else
  9854. {
  9855. *dest++ = (juce_wchar) c;
  9856. }
  9857. }
  9858. *dest = 0;
  9859. return result;
  9860. }
  9861. const char* String::toCString() const
  9862. {
  9863. if (isEmpty())
  9864. {
  9865. return reinterpret_cast <const char*> (text);
  9866. }
  9867. else
  9868. {
  9869. const int len = length();
  9870. String* const mutableThis = const_cast <String*> (this);
  9871. mutableThis->text = StringHolder::makeUniqueWithSize (mutableThis->text, (len + 1) * 2);
  9872. char* otherCopy = reinterpret_cast <char*> (mutableThis->text + len + 1);
  9873. CharacterFunctions::copy (otherCopy, text, len);
  9874. otherCopy [len] = 0;
  9875. return otherCopy;
  9876. }
  9877. }
  9878. #ifdef _MSC_VER
  9879. #pragma warning (disable: 4514 4996)
  9880. #pragma warning (push)
  9881. #endif
  9882. int String::getNumBytesAsCString() const throw()
  9883. {
  9884. return (int) wcstombs (0, text, 0);
  9885. }
  9886. int String::copyToCString (char* destBuffer, const int maxBufferSizeBytes) const throw()
  9887. {
  9888. const int numBytes = (int) wcstombs (destBuffer, text, maxBufferSizeBytes);
  9889. if (destBuffer != 0 && numBytes >= 0)
  9890. destBuffer [numBytes] = 0;
  9891. return numBytes;
  9892. }
  9893. #ifdef _MSC_VER
  9894. #pragma warning (pop)
  9895. #endif
  9896. void String::copyToUnicode (juce_wchar* const destBuffer, const int maxCharsToCopy) const throw()
  9897. {
  9898. StringHolder::copyChars (destBuffer, text, jmin (maxCharsToCopy, length()));
  9899. }
  9900. String::Concatenator::Concatenator (String& stringToAppendTo)
  9901. : result (stringToAppendTo),
  9902. nextIndex (stringToAppendTo.length())
  9903. {
  9904. }
  9905. String::Concatenator::~Concatenator()
  9906. {
  9907. }
  9908. void String::Concatenator::append (const String& s)
  9909. {
  9910. const int len = s.length();
  9911. if (len > 0)
  9912. {
  9913. result.preallocateStorage (nextIndex + len);
  9914. s.copyToUnicode (static_cast <juce_wchar*> (result) + nextIndex, len);
  9915. nextIndex += len;
  9916. }
  9917. }
  9918. END_JUCE_NAMESPACE
  9919. /*** End of inlined file: juce_String.cpp ***/
  9920. /*** Start of inlined file: juce_StringArray.cpp ***/
  9921. BEGIN_JUCE_NAMESPACE
  9922. StringArray::StringArray() throw()
  9923. {
  9924. }
  9925. StringArray::StringArray (const StringArray& other)
  9926. : strings (other.strings)
  9927. {
  9928. }
  9929. StringArray::StringArray (const String& firstValue)
  9930. {
  9931. strings.add (firstValue);
  9932. }
  9933. StringArray::StringArray (const juce_wchar* const* const initialStrings,
  9934. const int numberOfStrings)
  9935. {
  9936. for (int i = 0; i < numberOfStrings; ++i)
  9937. strings.add (initialStrings [i]);
  9938. }
  9939. StringArray::StringArray (const char* const* const initialStrings,
  9940. const int numberOfStrings)
  9941. {
  9942. for (int i = 0; i < numberOfStrings; ++i)
  9943. strings.add (initialStrings [i]);
  9944. }
  9945. StringArray::StringArray (const juce_wchar* const* const initialStrings)
  9946. {
  9947. int i = 0;
  9948. while (initialStrings[i] != 0)
  9949. strings.add (initialStrings [i++]);
  9950. }
  9951. StringArray::StringArray (const char* const* const initialStrings)
  9952. {
  9953. int i = 0;
  9954. while (initialStrings[i] != 0)
  9955. strings.add (initialStrings [i++]);
  9956. }
  9957. StringArray& StringArray::operator= (const StringArray& other)
  9958. {
  9959. strings = other.strings;
  9960. return *this;
  9961. }
  9962. StringArray::~StringArray()
  9963. {
  9964. }
  9965. bool StringArray::operator== (const StringArray& other) const throw()
  9966. {
  9967. if (other.size() != size())
  9968. return false;
  9969. for (int i = size(); --i >= 0;)
  9970. if (other.strings.getReference(i) != strings.getReference(i))
  9971. return false;
  9972. return true;
  9973. }
  9974. bool StringArray::operator!= (const StringArray& other) const throw()
  9975. {
  9976. return ! operator== (other);
  9977. }
  9978. void StringArray::clear()
  9979. {
  9980. strings.clear();
  9981. }
  9982. const String& StringArray::operator[] (const int index) const throw()
  9983. {
  9984. if (((unsigned int) index) < (unsigned int) strings.size())
  9985. return strings.getReference (index);
  9986. return String::empty;
  9987. }
  9988. String& StringArray::getReference (const int index) throw()
  9989. {
  9990. jassert (((unsigned int) index) < (unsigned int) strings.size());
  9991. return strings.getReference (index);
  9992. }
  9993. void StringArray::add (const String& newString)
  9994. {
  9995. strings.add (newString);
  9996. }
  9997. void StringArray::insert (const int index, const String& newString)
  9998. {
  9999. strings.insert (index, newString);
  10000. }
  10001. void StringArray::addIfNotAlreadyThere (const String& newString, const bool ignoreCase)
  10002. {
  10003. if (! contains (newString, ignoreCase))
  10004. add (newString);
  10005. }
  10006. void StringArray::addArray (const StringArray& otherArray, int startIndex, int numElementsToAdd)
  10007. {
  10008. if (startIndex < 0)
  10009. {
  10010. jassertfalse
  10011. startIndex = 0;
  10012. }
  10013. if (numElementsToAdd < 0 || startIndex + numElementsToAdd > otherArray.size())
  10014. numElementsToAdd = otherArray.size() - startIndex;
  10015. while (--numElementsToAdd >= 0)
  10016. strings.add (otherArray.strings.getReference (startIndex++));
  10017. }
  10018. void StringArray::set (const int index, const String& newString)
  10019. {
  10020. strings.set (index, newString);
  10021. }
  10022. bool StringArray::contains (const String& stringToLookFor, const bool ignoreCase) const
  10023. {
  10024. if (ignoreCase)
  10025. {
  10026. for (int i = size(); --i >= 0;)
  10027. if (strings.getReference(i).equalsIgnoreCase (stringToLookFor))
  10028. return true;
  10029. }
  10030. else
  10031. {
  10032. for (int i = size(); --i >= 0;)
  10033. if (stringToLookFor == strings.getReference(i))
  10034. return true;
  10035. }
  10036. return false;
  10037. }
  10038. int StringArray::indexOf (const String& stringToLookFor, const bool ignoreCase, int i) const
  10039. {
  10040. if (i < 0)
  10041. i = 0;
  10042. const int numElements = size();
  10043. if (ignoreCase)
  10044. {
  10045. while (i < numElements)
  10046. {
  10047. if (strings.getReference(i).equalsIgnoreCase (stringToLookFor))
  10048. return i;
  10049. ++i;
  10050. }
  10051. }
  10052. else
  10053. {
  10054. while (i < numElements)
  10055. {
  10056. if (stringToLookFor == strings.getReference (i))
  10057. return i;
  10058. ++i;
  10059. }
  10060. }
  10061. return -1;
  10062. }
  10063. void StringArray::remove (const int index)
  10064. {
  10065. strings.remove (index);
  10066. }
  10067. void StringArray::removeString (const String& stringToRemove,
  10068. const bool ignoreCase)
  10069. {
  10070. if (ignoreCase)
  10071. {
  10072. for (int i = size(); --i >= 0;)
  10073. if (strings.getReference(i).equalsIgnoreCase (stringToRemove))
  10074. strings.remove (i);
  10075. }
  10076. else
  10077. {
  10078. for (int i = size(); --i >= 0;)
  10079. if (stringToRemove == strings.getReference (i))
  10080. strings.remove (i);
  10081. }
  10082. }
  10083. void StringArray::removeRange (int startIndex, int numberToRemove)
  10084. {
  10085. strings.removeRange (startIndex, numberToRemove);
  10086. }
  10087. void StringArray::removeEmptyStrings (const bool removeWhitespaceStrings)
  10088. {
  10089. if (removeWhitespaceStrings)
  10090. {
  10091. for (int i = size(); --i >= 0;)
  10092. if (! strings.getReference(i).containsNonWhitespaceChars())
  10093. strings.remove (i);
  10094. }
  10095. else
  10096. {
  10097. for (int i = size(); --i >= 0;)
  10098. if (strings.getReference(i).isEmpty())
  10099. strings.remove (i);
  10100. }
  10101. }
  10102. void StringArray::trim()
  10103. {
  10104. for (int i = size(); --i >= 0;)
  10105. {
  10106. String& s = strings.getReference(i);
  10107. s = s.trim();
  10108. }
  10109. }
  10110. class InternalStringArrayComparator_CaseSensitive
  10111. {
  10112. public:
  10113. static int compareElements (String& first, String& second) { return first.compare (second); }
  10114. };
  10115. class InternalStringArrayComparator_CaseInsensitive
  10116. {
  10117. public:
  10118. static int compareElements (String& first, String& second) { return first.compareIgnoreCase (second); }
  10119. };
  10120. void StringArray::sort (const bool ignoreCase)
  10121. {
  10122. if (ignoreCase)
  10123. {
  10124. InternalStringArrayComparator_CaseInsensitive comp;
  10125. strings.sort (comp);
  10126. }
  10127. else
  10128. {
  10129. InternalStringArrayComparator_CaseSensitive comp;
  10130. strings.sort (comp);
  10131. }
  10132. }
  10133. void StringArray::move (const int currentIndex, int newIndex) throw()
  10134. {
  10135. strings.move (currentIndex, newIndex);
  10136. }
  10137. const String StringArray::joinIntoString (const String& separator, int start, int numberToJoin) const
  10138. {
  10139. const int last = (numberToJoin < 0) ? size()
  10140. : jmin (size(), start + numberToJoin);
  10141. if (start < 0)
  10142. start = 0;
  10143. if (start >= last)
  10144. return String::empty;
  10145. if (start == last - 1)
  10146. return strings.getReference (start);
  10147. const int separatorLen = separator.length();
  10148. int charsNeeded = separatorLen * (last - start - 1);
  10149. for (int i = start; i < last; ++i)
  10150. charsNeeded += strings.getReference(i).length();
  10151. String result;
  10152. result.preallocateStorage (charsNeeded);
  10153. juce_wchar* dest = result;
  10154. while (start < last)
  10155. {
  10156. const String& s = strings.getReference (start);
  10157. const int len = s.length();
  10158. if (len > 0)
  10159. {
  10160. s.copyToUnicode (dest, len);
  10161. dest += len;
  10162. }
  10163. if (++start < last && separatorLen > 0)
  10164. {
  10165. separator.copyToUnicode (dest, separatorLen);
  10166. dest += separatorLen;
  10167. }
  10168. }
  10169. *dest = 0;
  10170. return result;
  10171. }
  10172. int StringArray::addTokens (const String& text, const bool preserveQuotedStrings)
  10173. {
  10174. return addTokens (text, " \n\r\t", preserveQuotedStrings ? "\"" : "");
  10175. }
  10176. int StringArray::addTokens (const String& text, const String& breakCharacters, const String& quoteCharacters)
  10177. {
  10178. int num = 0;
  10179. if (text.isNotEmpty())
  10180. {
  10181. bool insideQuotes = false;
  10182. juce_wchar currentQuoteChar = 0;
  10183. int i = 0;
  10184. int tokenStart = 0;
  10185. for (;;)
  10186. {
  10187. const juce_wchar c = text[i];
  10188. const bool isBreak = (c == 0) || ((! insideQuotes) && breakCharacters.containsChar (c));
  10189. if (! isBreak)
  10190. {
  10191. if (quoteCharacters.containsChar (c))
  10192. {
  10193. if (insideQuotes)
  10194. {
  10195. // only break out of quotes-mode if we find a matching quote to the
  10196. // one that we opened with..
  10197. if (currentQuoteChar == c)
  10198. insideQuotes = false;
  10199. }
  10200. else
  10201. {
  10202. insideQuotes = true;
  10203. currentQuoteChar = c;
  10204. }
  10205. }
  10206. }
  10207. else
  10208. {
  10209. add (String (static_cast <const juce_wchar*> (text) + tokenStart, i - tokenStart));
  10210. ++num;
  10211. tokenStart = i + 1;
  10212. }
  10213. if (c == 0)
  10214. break;
  10215. ++i;
  10216. }
  10217. }
  10218. return num;
  10219. }
  10220. int StringArray::addLines (const String& sourceText)
  10221. {
  10222. int numLines = 0;
  10223. const juce_wchar* text = sourceText;
  10224. while (*text != 0)
  10225. {
  10226. const juce_wchar* const startOfLine = text;
  10227. while (*text != 0)
  10228. {
  10229. if (*text == '\r')
  10230. {
  10231. ++text;
  10232. if (*text == '\n')
  10233. ++text;
  10234. break;
  10235. }
  10236. if (*text == '\n')
  10237. {
  10238. ++text;
  10239. break;
  10240. }
  10241. ++text;
  10242. }
  10243. const juce_wchar* endOfLine = text;
  10244. if (endOfLine > startOfLine && (*(endOfLine - 1) == '\r' || *(endOfLine - 1) == '\n'))
  10245. --endOfLine;
  10246. if (endOfLine > startOfLine && (*(endOfLine - 1) == '\r' || *(endOfLine - 1) == '\n'))
  10247. --endOfLine;
  10248. add (String (startOfLine, jmax (0, (int) (endOfLine - startOfLine))));
  10249. ++numLines;
  10250. }
  10251. return numLines;
  10252. }
  10253. void StringArray::removeDuplicates (const bool ignoreCase)
  10254. {
  10255. for (int i = 0; i < size() - 1; ++i)
  10256. {
  10257. const String s (strings.getReference(i));
  10258. int nextIndex = i + 1;
  10259. for (;;)
  10260. {
  10261. nextIndex = indexOf (s, ignoreCase, nextIndex);
  10262. if (nextIndex < 0)
  10263. break;
  10264. strings.remove (nextIndex);
  10265. }
  10266. }
  10267. }
  10268. void StringArray::appendNumbersToDuplicates (const bool ignoreCase,
  10269. const bool appendNumberToFirstInstance,
  10270. const juce_wchar* preNumberString,
  10271. const juce_wchar* postNumberString)
  10272. {
  10273. if (preNumberString == 0)
  10274. preNumberString = L" (";
  10275. if (postNumberString == 0)
  10276. postNumberString = L")";
  10277. for (int i = 0; i < size() - 1; ++i)
  10278. {
  10279. String& s = strings.getReference(i);
  10280. int nextIndex = indexOf (s, ignoreCase, i + 1);
  10281. if (nextIndex >= 0)
  10282. {
  10283. const String original (s);
  10284. int number = 0;
  10285. if (appendNumberToFirstInstance)
  10286. s = original + preNumberString + String (++number) + postNumberString;
  10287. else
  10288. ++number;
  10289. while (nextIndex >= 0)
  10290. {
  10291. set (nextIndex, (*this)[nextIndex] + preNumberString + String (++number) + postNumberString);
  10292. nextIndex = indexOf (original, ignoreCase, nextIndex + 1);
  10293. }
  10294. }
  10295. }
  10296. }
  10297. void StringArray::minimiseStorageOverheads()
  10298. {
  10299. strings.minimiseStorageOverheads();
  10300. }
  10301. END_JUCE_NAMESPACE
  10302. /*** End of inlined file: juce_StringArray.cpp ***/
  10303. /*** Start of inlined file: juce_StringPairArray.cpp ***/
  10304. BEGIN_JUCE_NAMESPACE
  10305. StringPairArray::StringPairArray (const bool ignoreCase_)
  10306. : ignoreCase (ignoreCase_)
  10307. {
  10308. }
  10309. StringPairArray::StringPairArray (const StringPairArray& other)
  10310. : keys (other.keys),
  10311. values (other.values),
  10312. ignoreCase (other.ignoreCase)
  10313. {
  10314. }
  10315. StringPairArray::~StringPairArray()
  10316. {
  10317. }
  10318. StringPairArray& StringPairArray::operator= (const StringPairArray& other)
  10319. {
  10320. keys = other.keys;
  10321. values = other.values;
  10322. return *this;
  10323. }
  10324. bool StringPairArray::operator== (const StringPairArray& other) const
  10325. {
  10326. for (int i = keys.size(); --i >= 0;)
  10327. if (other [keys[i]] != values[i])
  10328. return false;
  10329. return true;
  10330. }
  10331. bool StringPairArray::operator!= (const StringPairArray& other) const
  10332. {
  10333. return ! operator== (other);
  10334. }
  10335. const String& StringPairArray::operator[] (const String& key) const
  10336. {
  10337. return values [keys.indexOf (key, ignoreCase)];
  10338. }
  10339. const String StringPairArray::getValue (const String& key, const String& defaultReturnValue) const
  10340. {
  10341. const int i = keys.indexOf (key, ignoreCase);
  10342. if (i >= 0)
  10343. return values[i];
  10344. return defaultReturnValue;
  10345. }
  10346. void StringPairArray::set (const String& key, const String& value)
  10347. {
  10348. const int i = keys.indexOf (key, ignoreCase);
  10349. if (i >= 0)
  10350. {
  10351. values.set (i, value);
  10352. }
  10353. else
  10354. {
  10355. keys.add (key);
  10356. values.add (value);
  10357. }
  10358. }
  10359. void StringPairArray::addArray (const StringPairArray& other)
  10360. {
  10361. for (int i = 0; i < other.size(); ++i)
  10362. set (other.keys[i], other.values[i]);
  10363. }
  10364. void StringPairArray::clear()
  10365. {
  10366. keys.clear();
  10367. values.clear();
  10368. }
  10369. void StringPairArray::remove (const String& key)
  10370. {
  10371. remove (keys.indexOf (key, ignoreCase));
  10372. }
  10373. void StringPairArray::remove (const int index)
  10374. {
  10375. keys.remove (index);
  10376. values.remove (index);
  10377. }
  10378. void StringPairArray::setIgnoresCase (const bool shouldIgnoreCase)
  10379. {
  10380. ignoreCase = shouldIgnoreCase;
  10381. }
  10382. const String StringPairArray::getDescription() const
  10383. {
  10384. String s;
  10385. for (int i = 0; i < keys.size(); ++i)
  10386. {
  10387. s << keys[i] << " = " << values[i];
  10388. if (i < keys.size())
  10389. s << ", ";
  10390. }
  10391. return s;
  10392. }
  10393. void StringPairArray::minimiseStorageOverheads()
  10394. {
  10395. keys.minimiseStorageOverheads();
  10396. values.minimiseStorageOverheads();
  10397. }
  10398. END_JUCE_NAMESPACE
  10399. /*** End of inlined file: juce_StringPairArray.cpp ***/
  10400. /*** Start of inlined file: juce_XmlDocument.cpp ***/
  10401. BEGIN_JUCE_NAMESPACE
  10402. XmlDocument::XmlDocument (const String& documentText)
  10403. : originalText (documentText),
  10404. ignoreEmptyTextElements (true)
  10405. {
  10406. }
  10407. XmlDocument::XmlDocument (const File& file)
  10408. : ignoreEmptyTextElements (true)
  10409. {
  10410. inputSource = new FileInputSource (file);
  10411. }
  10412. XmlDocument::~XmlDocument()
  10413. {
  10414. }
  10415. void XmlDocument::setInputSource (InputSource* const newSource) throw()
  10416. {
  10417. inputSource = newSource;
  10418. }
  10419. void XmlDocument::setEmptyTextElementsIgnored (const bool shouldBeIgnored) throw()
  10420. {
  10421. ignoreEmptyTextElements = shouldBeIgnored;
  10422. }
  10423. bool XmlDocument::isXmlIdentifierCharSlow (const juce_wchar c) throw()
  10424. {
  10425. return CharacterFunctions::isLetterOrDigit (c)
  10426. || c == '_' || c == '-' || c == ':' || c == '.';
  10427. }
  10428. inline bool XmlDocument::isXmlIdentifierChar (const juce_wchar c) const throw()
  10429. {
  10430. return (c > 0 && c <= 127) ? identifierLookupTable [(int) c]
  10431. : isXmlIdentifierCharSlow (c);
  10432. }
  10433. XmlElement* XmlDocument::getDocumentElement (const bool onlyReadOuterDocumentElement)
  10434. {
  10435. String textToParse (originalText);
  10436. if (textToParse.isEmpty() && inputSource != 0)
  10437. {
  10438. ScopedPointer <InputStream> in (inputSource->createInputStream());
  10439. if (in != 0)
  10440. {
  10441. MemoryBlock data;
  10442. in->readIntoMemoryBlock (data, onlyReadOuterDocumentElement ? 8192 : -1);
  10443. if (data.getSize() >= 2
  10444. && ((data[0] == (char)-2 && data[1] == (char)-1)
  10445. || (data[0] == (char)-1 && data[1] == (char)-2)))
  10446. {
  10447. textToParse = String::createStringFromData (static_cast <const char*> (data.getData()), (int) data.getSize());
  10448. }
  10449. else
  10450. {
  10451. textToParse = String::fromUTF8 (static_cast <const char*> (data.getData()), (int) data.getSize());
  10452. }
  10453. if (! onlyReadOuterDocumentElement)
  10454. originalText = textToParse;
  10455. }
  10456. }
  10457. input = textToParse;
  10458. lastError = String::empty;
  10459. errorOccurred = false;
  10460. outOfData = false;
  10461. needToLoadDTD = true;
  10462. for (int i = 0; i < 128; ++i)
  10463. identifierLookupTable[i] = isXmlIdentifierCharSlow ((juce_wchar) i);
  10464. if (textToParse.isEmpty())
  10465. {
  10466. lastError = "not enough input";
  10467. }
  10468. else
  10469. {
  10470. skipHeader();
  10471. if (input != 0)
  10472. {
  10473. ScopedPointer <XmlElement> result (readNextElement (! onlyReadOuterDocumentElement));
  10474. if (! errorOccurred)
  10475. return result.release();
  10476. }
  10477. else
  10478. {
  10479. lastError = "incorrect xml header";
  10480. }
  10481. }
  10482. return 0;
  10483. }
  10484. const String& XmlDocument::getLastParseError() const throw()
  10485. {
  10486. return lastError;
  10487. }
  10488. void XmlDocument::setLastError (const String& desc, const bool carryOn)
  10489. {
  10490. lastError = desc;
  10491. errorOccurred = ! carryOn;
  10492. }
  10493. const String XmlDocument::getFileContents (const String& filename) const
  10494. {
  10495. if (inputSource != 0)
  10496. {
  10497. const ScopedPointer <InputStream> in (inputSource->createInputStreamFor (filename.trim().unquoted()));
  10498. if (in != 0)
  10499. return in->readEntireStreamAsString();
  10500. }
  10501. return String::empty;
  10502. }
  10503. juce_wchar XmlDocument::readNextChar() throw()
  10504. {
  10505. if (*input != 0)
  10506. {
  10507. return *input++;
  10508. }
  10509. else
  10510. {
  10511. outOfData = true;
  10512. return 0;
  10513. }
  10514. }
  10515. int XmlDocument::findNextTokenLength() throw()
  10516. {
  10517. int len = 0;
  10518. juce_wchar c = *input;
  10519. while (isXmlIdentifierChar (c))
  10520. c = input [++len];
  10521. return len;
  10522. }
  10523. void XmlDocument::skipHeader()
  10524. {
  10525. const juce_wchar* const found = CharacterFunctions::find (input, T("<?xml"));
  10526. if (found != 0)
  10527. {
  10528. input = found;
  10529. input = CharacterFunctions::find (input, T("?>"));
  10530. if (input == 0)
  10531. return;
  10532. input += 2;
  10533. }
  10534. skipNextWhiteSpace();
  10535. const juce_wchar* docType = CharacterFunctions::find (input, T("<!DOCTYPE"));
  10536. if (docType == 0)
  10537. return;
  10538. input = docType + 9;
  10539. int n = 1;
  10540. while (n > 0)
  10541. {
  10542. const juce_wchar c = readNextChar();
  10543. if (outOfData)
  10544. return;
  10545. if (c == '<')
  10546. ++n;
  10547. else if (c == '>')
  10548. --n;
  10549. }
  10550. docType += 9;
  10551. dtdText = String (docType, (int) (input - (docType + 1))).trim();
  10552. }
  10553. void XmlDocument::skipNextWhiteSpace()
  10554. {
  10555. for (;;)
  10556. {
  10557. juce_wchar c = *input;
  10558. while (CharacterFunctions::isWhitespace (c))
  10559. c = *++input;
  10560. if (c == 0)
  10561. {
  10562. outOfData = true;
  10563. break;
  10564. }
  10565. else if (c == '<')
  10566. {
  10567. if (input[1] == '!'
  10568. && input[2] == '-'
  10569. && input[3] == '-')
  10570. {
  10571. const juce_wchar* const closeComment = CharacterFunctions::find (input, T("-->"));
  10572. if (closeComment == 0)
  10573. {
  10574. outOfData = true;
  10575. break;
  10576. }
  10577. input = closeComment + 3;
  10578. continue;
  10579. }
  10580. else if (input[1] == '?')
  10581. {
  10582. const juce_wchar* const closeBracket = CharacterFunctions::find (input, T("?>"));
  10583. if (closeBracket == 0)
  10584. {
  10585. outOfData = true;
  10586. break;
  10587. }
  10588. input = closeBracket + 2;
  10589. continue;
  10590. }
  10591. }
  10592. break;
  10593. }
  10594. }
  10595. void XmlDocument::readQuotedString (String& result)
  10596. {
  10597. const juce_wchar quote = readNextChar();
  10598. while (! outOfData)
  10599. {
  10600. const juce_wchar c = readNextChar();
  10601. if (c == quote)
  10602. break;
  10603. if (c == '&')
  10604. {
  10605. --input;
  10606. readEntity (result);
  10607. }
  10608. else
  10609. {
  10610. --input;
  10611. const juce_wchar* const start = input;
  10612. for (;;)
  10613. {
  10614. const juce_wchar character = *input;
  10615. if (character == quote)
  10616. {
  10617. result.append (start, (int) (input - start));
  10618. ++input;
  10619. return;
  10620. }
  10621. else if (character == '&')
  10622. {
  10623. result.append (start, (int) (input - start));
  10624. break;
  10625. }
  10626. else if (character == 0)
  10627. {
  10628. outOfData = true;
  10629. setLastError ("unmatched quotes", false);
  10630. break;
  10631. }
  10632. ++input;
  10633. }
  10634. }
  10635. }
  10636. }
  10637. XmlElement* XmlDocument::readNextElement (const bool alsoParseSubElements)
  10638. {
  10639. XmlElement* node = 0;
  10640. skipNextWhiteSpace();
  10641. if (outOfData)
  10642. return 0;
  10643. input = CharacterFunctions::find (input, T("<"));
  10644. if (input != 0)
  10645. {
  10646. ++input;
  10647. int tagLen = findNextTokenLength();
  10648. if (tagLen == 0)
  10649. {
  10650. // no tag name - but allow for a gap after the '<' before giving an error
  10651. skipNextWhiteSpace();
  10652. tagLen = findNextTokenLength();
  10653. if (tagLen == 0)
  10654. {
  10655. setLastError ("tag name missing", false);
  10656. return node;
  10657. }
  10658. }
  10659. node = new XmlElement (String (input, tagLen));
  10660. input += tagLen;
  10661. XmlElement::XmlAttributeNode* lastAttribute = 0;
  10662. // look for attributes
  10663. for (;;)
  10664. {
  10665. skipNextWhiteSpace();
  10666. const juce_wchar c = *input;
  10667. // empty tag..
  10668. if (c == '/' && input[1] == '>')
  10669. {
  10670. input += 2;
  10671. break;
  10672. }
  10673. // parse the guts of the element..
  10674. if (c == '>')
  10675. {
  10676. ++input;
  10677. skipNextWhiteSpace();
  10678. if (alsoParseSubElements)
  10679. readChildElements (node);
  10680. break;
  10681. }
  10682. // get an attribute..
  10683. if (isXmlIdentifierChar (c))
  10684. {
  10685. const int attNameLen = findNextTokenLength();
  10686. if (attNameLen > 0)
  10687. {
  10688. const juce_wchar* attNameStart = input;
  10689. input += attNameLen;
  10690. skipNextWhiteSpace();
  10691. if (readNextChar() == '=')
  10692. {
  10693. skipNextWhiteSpace();
  10694. const juce_wchar nextChar = *input;
  10695. if (nextChar == '"' || nextChar == '\'')
  10696. {
  10697. XmlElement::XmlAttributeNode* const newAtt
  10698. = new XmlElement::XmlAttributeNode (String (attNameStart, attNameLen),
  10699. String::empty);
  10700. readQuotedString (newAtt->value);
  10701. if (lastAttribute == 0)
  10702. node->attributes = newAtt;
  10703. else
  10704. lastAttribute->next = newAtt;
  10705. lastAttribute = newAtt;
  10706. continue;
  10707. }
  10708. }
  10709. }
  10710. }
  10711. else
  10712. {
  10713. if (! outOfData)
  10714. setLastError ("illegal character found in " + node->getTagName() + ": '" + c + "'", false);
  10715. }
  10716. break;
  10717. }
  10718. }
  10719. return node;
  10720. }
  10721. void XmlDocument::readChildElements (XmlElement* parent)
  10722. {
  10723. XmlElement* lastChildNode = 0;
  10724. for (;;)
  10725. {
  10726. skipNextWhiteSpace();
  10727. if (outOfData)
  10728. {
  10729. setLastError ("unmatched tags", false);
  10730. break;
  10731. }
  10732. if (*input == '<')
  10733. {
  10734. if (input[1] == '/')
  10735. {
  10736. // our close tag..
  10737. input = CharacterFunctions::find (input, T(">"));
  10738. ++input;
  10739. break;
  10740. }
  10741. else if (input[1] == '!'
  10742. && input[2] == '['
  10743. && input[3] == 'C'
  10744. && input[4] == 'D'
  10745. && input[5] == 'A'
  10746. && input[6] == 'T'
  10747. && input[7] == 'A'
  10748. && input[8] == '[')
  10749. {
  10750. input += 9;
  10751. const juce_wchar* const inputStart = input;
  10752. int len = 0;
  10753. for (;;)
  10754. {
  10755. if (*input == 0)
  10756. {
  10757. setLastError ("unterminated CDATA section", false);
  10758. outOfData = true;
  10759. break;
  10760. }
  10761. else if (input[0] == ']'
  10762. && input[1] == ']'
  10763. && input[2] == '>')
  10764. {
  10765. input += 3;
  10766. break;
  10767. }
  10768. ++input;
  10769. ++len;
  10770. }
  10771. XmlElement* const e = new XmlElement ((int) 0);
  10772. e->setText (String (inputStart, len));
  10773. if (lastChildNode != 0)
  10774. lastChildNode->nextElement = e;
  10775. else
  10776. parent->addChildElement (e);
  10777. lastChildNode = e;
  10778. }
  10779. else
  10780. {
  10781. // this is some other element, so parse and add it..
  10782. XmlElement* const n = readNextElement (true);
  10783. if (n != 0)
  10784. {
  10785. if (lastChildNode == 0)
  10786. parent->addChildElement (n);
  10787. else
  10788. lastChildNode->nextElement = n;
  10789. lastChildNode = n;
  10790. }
  10791. else
  10792. {
  10793. return;
  10794. }
  10795. }
  10796. }
  10797. else
  10798. {
  10799. // read character block..
  10800. XmlElement* const e = new XmlElement ((int)0);
  10801. if (lastChildNode != 0)
  10802. lastChildNode->nextElement = e;
  10803. else
  10804. parent->addChildElement (e);
  10805. lastChildNode = e;
  10806. String textElementContent;
  10807. for (;;)
  10808. {
  10809. const juce_wchar c = *input;
  10810. if (c == '<')
  10811. break;
  10812. if (c == 0)
  10813. {
  10814. setLastError ("unmatched tags", false);
  10815. outOfData = true;
  10816. return;
  10817. }
  10818. if (c == '&')
  10819. {
  10820. String entity;
  10821. readEntity (entity);
  10822. if (entity.startsWithChar ('<') && entity [1] != 0)
  10823. {
  10824. const juce_wchar* const oldInput = input;
  10825. const bool oldOutOfData = outOfData;
  10826. input = entity;
  10827. outOfData = false;
  10828. for (;;)
  10829. {
  10830. XmlElement* const n = readNextElement (true);
  10831. if (n == 0)
  10832. break;
  10833. if (lastChildNode == 0)
  10834. parent->addChildElement (n);
  10835. else
  10836. lastChildNode->nextElement = n;
  10837. lastChildNode = n;
  10838. }
  10839. input = oldInput;
  10840. outOfData = oldOutOfData;
  10841. }
  10842. else
  10843. {
  10844. textElementContent += entity;
  10845. }
  10846. }
  10847. else
  10848. {
  10849. const juce_wchar* start = input;
  10850. int len = 0;
  10851. for (;;)
  10852. {
  10853. const juce_wchar nextChar = *input;
  10854. if (nextChar == '<' || nextChar == '&')
  10855. {
  10856. break;
  10857. }
  10858. else if (nextChar == 0)
  10859. {
  10860. setLastError ("unmatched tags", false);
  10861. outOfData = true;
  10862. return;
  10863. }
  10864. ++input;
  10865. ++len;
  10866. }
  10867. textElementContent.append (start, len);
  10868. }
  10869. }
  10870. if (ignoreEmptyTextElements ? textElementContent.containsNonWhitespaceChars()
  10871. : textElementContent.isNotEmpty())
  10872. e->setText (textElementContent);
  10873. }
  10874. }
  10875. }
  10876. void XmlDocument::readEntity (String& result)
  10877. {
  10878. // skip over the ampersand
  10879. ++input;
  10880. if (CharacterFunctions::compareIgnoreCase (input, T("amp;"), 4) == 0)
  10881. {
  10882. input += 4;
  10883. result += '&';
  10884. }
  10885. else if (CharacterFunctions::compareIgnoreCase (input, T("quot;"), 5) == 0)
  10886. {
  10887. input += 5;
  10888. result += '"';
  10889. }
  10890. else if (CharacterFunctions::compareIgnoreCase (input, T("apos;"), 5) == 0)
  10891. {
  10892. input += 5;
  10893. result += '\'';
  10894. }
  10895. else if (CharacterFunctions::compareIgnoreCase (input, T("lt;"), 3) == 0)
  10896. {
  10897. input += 3;
  10898. result += '<';
  10899. }
  10900. else if (CharacterFunctions::compareIgnoreCase (input, T("gt;"), 3) == 0)
  10901. {
  10902. input += 3;
  10903. result += '>';
  10904. }
  10905. else if (*input == '#')
  10906. {
  10907. int charCode = 0;
  10908. ++input;
  10909. if (*input == 'x' || *input == 'X')
  10910. {
  10911. ++input;
  10912. int numChars = 0;
  10913. while (input[0] != ';')
  10914. {
  10915. const int hexValue = CharacterFunctions::getHexDigitValue (input[0]);
  10916. if (hexValue < 0 || ++numChars > 8)
  10917. {
  10918. setLastError ("illegal escape sequence", true);
  10919. break;
  10920. }
  10921. charCode = (charCode << 4) | hexValue;
  10922. ++input;
  10923. }
  10924. ++input;
  10925. }
  10926. else if (input[0] >= '0' && input[0] <= '9')
  10927. {
  10928. int numChars = 0;
  10929. while (input[0] != ';')
  10930. {
  10931. if (++numChars > 12)
  10932. {
  10933. setLastError ("illegal escape sequence", true);
  10934. break;
  10935. }
  10936. charCode = charCode * 10 + (input[0] - '0');
  10937. ++input;
  10938. }
  10939. ++input;
  10940. }
  10941. else
  10942. {
  10943. setLastError ("illegal escape sequence", true);
  10944. result += '&';
  10945. return;
  10946. }
  10947. result << (juce_wchar) charCode;
  10948. }
  10949. else
  10950. {
  10951. const juce_wchar* const entityNameStart = input;
  10952. const juce_wchar* const closingSemiColon = CharacterFunctions::find (input, T(";"));
  10953. if (closingSemiColon == 0)
  10954. {
  10955. outOfData = true;
  10956. result += '&';
  10957. }
  10958. else
  10959. {
  10960. input = closingSemiColon + 1;
  10961. result += expandExternalEntity (String (entityNameStart,
  10962. (int) (closingSemiColon - entityNameStart)));
  10963. }
  10964. }
  10965. }
  10966. const String XmlDocument::expandEntity (const String& ent)
  10967. {
  10968. if (ent.equalsIgnoreCase ("amp"))
  10969. return String::charToString ('&');
  10970. if (ent.equalsIgnoreCase ("quot"))
  10971. return String::charToString ('"');
  10972. if (ent.equalsIgnoreCase ("apos"))
  10973. return String::charToString ('\'');
  10974. if (ent.equalsIgnoreCase ("lt"))
  10975. return String::charToString ('<');
  10976. if (ent.equalsIgnoreCase ("gt"))
  10977. return String::charToString ('>');
  10978. if (ent[0] == '#')
  10979. {
  10980. if (ent[1] == 'x' || ent[1] == 'X')
  10981. return String::charToString (static_cast <juce_wchar> (ent.substring (2).getHexValue32()));
  10982. if (ent[1] >= '0' && ent[1] <= '9')
  10983. return String::charToString (static_cast <juce_wchar> (ent.substring (1).getIntValue()));
  10984. setLastError ("illegal escape sequence", false);
  10985. return String::charToString ('&');
  10986. }
  10987. return expandExternalEntity (ent);
  10988. }
  10989. const String XmlDocument::expandExternalEntity (const String& entity)
  10990. {
  10991. if (needToLoadDTD)
  10992. {
  10993. if (dtdText.isNotEmpty())
  10994. {
  10995. dtdText = dtdText.trimCharactersAtEnd (">");
  10996. tokenisedDTD.addTokens (dtdText, true);
  10997. if (tokenisedDTD [tokenisedDTD.size() - 2].equalsIgnoreCase ("system")
  10998. && tokenisedDTD [tokenisedDTD.size() - 1].isQuotedString())
  10999. {
  11000. const String fn (tokenisedDTD [tokenisedDTD.size() - 1]);
  11001. tokenisedDTD.clear();
  11002. tokenisedDTD.addTokens (getFileContents (fn), true);
  11003. }
  11004. else
  11005. {
  11006. tokenisedDTD.clear();
  11007. const int openBracket = dtdText.indexOfChar ('[');
  11008. if (openBracket > 0)
  11009. {
  11010. const int closeBracket = dtdText.lastIndexOfChar (']');
  11011. if (closeBracket > openBracket)
  11012. tokenisedDTD.addTokens (dtdText.substring (openBracket + 1,
  11013. closeBracket), true);
  11014. }
  11015. }
  11016. for (int i = tokenisedDTD.size(); --i >= 0;)
  11017. {
  11018. if (tokenisedDTD[i].startsWithChar ('%')
  11019. && tokenisedDTD[i].endsWithChar (';'))
  11020. {
  11021. const String parsed (getParameterEntity (tokenisedDTD[i].substring (1, tokenisedDTD[i].length() - 1)));
  11022. StringArray newToks;
  11023. newToks.addTokens (parsed, true);
  11024. tokenisedDTD.remove (i);
  11025. for (int j = newToks.size(); --j >= 0;)
  11026. tokenisedDTD.insert (i, newToks[j]);
  11027. }
  11028. }
  11029. }
  11030. needToLoadDTD = false;
  11031. }
  11032. for (int i = 0; i < tokenisedDTD.size(); ++i)
  11033. {
  11034. if (tokenisedDTD[i] == entity)
  11035. {
  11036. if (tokenisedDTD[i - 1].equalsIgnoreCase ("<!entity"))
  11037. {
  11038. String ent (tokenisedDTD [i + 1].trimCharactersAtEnd (">").trim().unquoted());
  11039. // check for sub-entities..
  11040. int ampersand = ent.indexOfChar ('&');
  11041. while (ampersand >= 0)
  11042. {
  11043. const int semiColon = ent.indexOf (i + 1, ";");
  11044. if (semiColon < 0)
  11045. {
  11046. setLastError ("entity without terminating semi-colon", false);
  11047. break;
  11048. }
  11049. const String resolved (expandEntity (ent.substring (i + 1, semiColon)));
  11050. ent = ent.substring (0, ampersand)
  11051. + resolved
  11052. + ent.substring (semiColon + 1);
  11053. ampersand = ent.indexOfChar (semiColon + 1, '&');
  11054. }
  11055. return ent;
  11056. }
  11057. }
  11058. }
  11059. setLastError ("unknown entity", true);
  11060. return entity;
  11061. }
  11062. const String XmlDocument::getParameterEntity (const String& entity)
  11063. {
  11064. for (int i = 0; i < tokenisedDTD.size(); ++i)
  11065. {
  11066. if (tokenisedDTD[i] == entity)
  11067. {
  11068. if (tokenisedDTD [i - 1] == "%"
  11069. && tokenisedDTD [i - 2].equalsIgnoreCase ("<!entity"))
  11070. {
  11071. const String ent (tokenisedDTD [i + 1].trimCharactersAtEnd (">"));
  11072. if (ent.equalsIgnoreCase ("system"))
  11073. return getFileContents (tokenisedDTD [i + 2].trimCharactersAtEnd (">"));
  11074. else
  11075. return ent.trim().unquoted();
  11076. }
  11077. }
  11078. }
  11079. return entity;
  11080. }
  11081. END_JUCE_NAMESPACE
  11082. /*** End of inlined file: juce_XmlDocument.cpp ***/
  11083. /*** Start of inlined file: juce_XmlElement.cpp ***/
  11084. BEGIN_JUCE_NAMESPACE
  11085. XmlElement::XmlAttributeNode::XmlAttributeNode (const XmlAttributeNode& other) throw()
  11086. : name (other.name),
  11087. value (other.value),
  11088. next (0)
  11089. {
  11090. }
  11091. XmlElement::XmlAttributeNode::XmlAttributeNode (const String& name_, const String& value_) throw()
  11092. : name (name_),
  11093. value (value_),
  11094. next (0)
  11095. {
  11096. }
  11097. XmlElement::XmlElement (const String& tagName_) throw()
  11098. : tagName (tagName_),
  11099. firstChildElement (0),
  11100. nextElement (0),
  11101. attributes (0)
  11102. {
  11103. // the tag name mustn't be empty, or it'll look like a text element!
  11104. jassert (tagName_.containsNonWhitespaceChars())
  11105. // The tag can't contain spaces or other characters that would create invalid XML!
  11106. jassert (! tagName_.containsAnyOf (" <>/&"));
  11107. }
  11108. XmlElement::XmlElement (int /*dummy*/) throw()
  11109. : firstChildElement (0),
  11110. nextElement (0),
  11111. attributes (0)
  11112. {
  11113. }
  11114. XmlElement::XmlElement (const XmlElement& other) throw()
  11115. : tagName (other.tagName),
  11116. firstChildElement (0),
  11117. nextElement (0),
  11118. attributes (0)
  11119. {
  11120. copyChildrenAndAttributesFrom (other);
  11121. }
  11122. XmlElement& XmlElement::operator= (const XmlElement& other) throw()
  11123. {
  11124. if (this != &other)
  11125. {
  11126. removeAllAttributes();
  11127. deleteAllChildElements();
  11128. tagName = other.tagName;
  11129. copyChildrenAndAttributesFrom (other);
  11130. }
  11131. return *this;
  11132. }
  11133. void XmlElement::copyChildrenAndAttributesFrom (const XmlElement& other) throw()
  11134. {
  11135. XmlElement* child = other.firstChildElement;
  11136. XmlElement* lastChild = 0;
  11137. while (child != 0)
  11138. {
  11139. XmlElement* const copiedChild = new XmlElement (*child);
  11140. if (lastChild != 0)
  11141. lastChild->nextElement = copiedChild;
  11142. else
  11143. firstChildElement = copiedChild;
  11144. lastChild = copiedChild;
  11145. child = child->nextElement;
  11146. }
  11147. const XmlAttributeNode* att = other.attributes;
  11148. XmlAttributeNode* lastAtt = 0;
  11149. while (att != 0)
  11150. {
  11151. XmlAttributeNode* const newAtt = new XmlAttributeNode (*att);
  11152. if (lastAtt != 0)
  11153. lastAtt->next = newAtt;
  11154. else
  11155. attributes = newAtt;
  11156. lastAtt = newAtt;
  11157. att = att->next;
  11158. }
  11159. }
  11160. XmlElement::~XmlElement() throw()
  11161. {
  11162. XmlElement* child = firstChildElement;
  11163. while (child != 0)
  11164. {
  11165. XmlElement* const nextChild = child->nextElement;
  11166. delete child;
  11167. child = nextChild;
  11168. }
  11169. XmlAttributeNode* att = attributes;
  11170. while (att != 0)
  11171. {
  11172. XmlAttributeNode* const nextAtt = att->next;
  11173. delete att;
  11174. att = nextAtt;
  11175. }
  11176. }
  11177. namespace XmlOutputFunctions
  11178. {
  11179. /*static bool isLegalXmlCharSlow (const juce_wchar character) throw()
  11180. {
  11181. if ((character >= 'a' && character <= 'z')
  11182. || (character >= 'A' && character <= 'Z')
  11183. || (character >= '0' && character <= '9'))
  11184. return true;
  11185. const char* t = " .,;:-()_+=?!'#@[]/\\*%~{}";
  11186. do
  11187. {
  11188. if (((juce_wchar) (uint8) *t) == character)
  11189. return true;
  11190. }
  11191. while (*++t != 0);
  11192. return false;
  11193. }
  11194. static void generateLegalCharConstants()
  11195. {
  11196. uint8 n[32];
  11197. zerostruct (n);
  11198. for (int i = 0; i < 256; ++i)
  11199. if (isLegalXmlCharSlow (i))
  11200. n[i >> 3] |= (1 << (i & 7));
  11201. String s;
  11202. for (int i = 0; i < 32; ++i)
  11203. s << (int) n[i] << ", ";
  11204. DBG (s);
  11205. }*/
  11206. static bool isLegalXmlChar (const uint32 c) throw()
  11207. {
  11208. static const unsigned char legalChars[] = { 0, 0, 0, 0, 171, 255, 255, 175, 255, 255, 255, 191, 254, 255, 255, 111 };
  11209. return c < sizeof (legalChars) * 8
  11210. && (legalChars [c >> 3] & (1 << (c & 7))) != 0;
  11211. }
  11212. static void escapeIllegalXmlChars (OutputStream& outputStream, const String& text, const bool changeNewLines)
  11213. {
  11214. const juce_wchar* t = text;
  11215. for (;;)
  11216. {
  11217. const juce_wchar character = *t++;
  11218. if (character == 0)
  11219. {
  11220. break;
  11221. }
  11222. else if (isLegalXmlChar ((uint32) character))
  11223. {
  11224. outputStream << (char) character;
  11225. }
  11226. else
  11227. {
  11228. switch (character)
  11229. {
  11230. case '&': outputStream << "&amp;"; break;
  11231. case '"': outputStream << "&quot;"; break;
  11232. case '>': outputStream << "&gt;"; break;
  11233. case '<': outputStream << "&lt;"; break;
  11234. case '\n':
  11235. if (changeNewLines)
  11236. outputStream << "&#10;";
  11237. else
  11238. outputStream << (char) character;
  11239. break;
  11240. case '\r':
  11241. if (changeNewLines)
  11242. outputStream << "&#13;";
  11243. else
  11244. outputStream << (char) character;
  11245. break;
  11246. default:
  11247. outputStream << "&#" << ((int) (unsigned int) character) << ';';
  11248. break;
  11249. }
  11250. }
  11251. }
  11252. }
  11253. static void writeSpaces (OutputStream& out, int numSpaces)
  11254. {
  11255. if (numSpaces > 0)
  11256. {
  11257. const char* const blanks = " ";
  11258. const int blankSize = (int) sizeof (blanks) - 1;
  11259. while (numSpaces > blankSize)
  11260. {
  11261. out.write (blanks, blankSize);
  11262. numSpaces -= blankSize;
  11263. }
  11264. out.write (blanks, numSpaces);
  11265. }
  11266. }
  11267. }
  11268. void XmlElement::writeElementAsText (OutputStream& outputStream,
  11269. const int indentationLevel,
  11270. const int lineWrapLength) const
  11271. {
  11272. using namespace XmlOutputFunctions;
  11273. writeSpaces (outputStream, indentationLevel);
  11274. if (! isTextElement())
  11275. {
  11276. outputStream.writeByte ('<');
  11277. outputStream << tagName;
  11278. const int attIndent = indentationLevel + tagName.length() + 1;
  11279. int lineLen = 0;
  11280. const XmlAttributeNode* att = attributes;
  11281. while (att != 0)
  11282. {
  11283. if (lineLen > lineWrapLength && indentationLevel >= 0)
  11284. {
  11285. outputStream.write ("\r\n", 2);
  11286. writeSpaces (outputStream, attIndent);
  11287. lineLen = 0;
  11288. }
  11289. const int64 startPos = outputStream.getPosition();
  11290. outputStream.writeByte (' ');
  11291. outputStream << att->name;
  11292. outputStream.write ("=\"", 2);
  11293. escapeIllegalXmlChars (outputStream, att->value, true);
  11294. outputStream.writeByte ('"');
  11295. lineLen += (int) (outputStream.getPosition() - startPos);
  11296. att = att->next;
  11297. }
  11298. if (firstChildElement != 0)
  11299. {
  11300. XmlElement* child = firstChildElement;
  11301. if (child->nextElement == 0 && child->isTextElement())
  11302. {
  11303. outputStream.writeByte ('>');
  11304. escapeIllegalXmlChars (outputStream, child->getText(), false);
  11305. }
  11306. else
  11307. {
  11308. if (indentationLevel >= 0)
  11309. outputStream.write (">\r\n", 3);
  11310. else
  11311. outputStream.writeByte ('>');
  11312. bool lastWasTextNode = false;
  11313. while (child != 0)
  11314. {
  11315. if (child->isTextElement())
  11316. {
  11317. if ((! lastWasTextNode) && (indentationLevel >= 0))
  11318. writeSpaces (outputStream, indentationLevel + 2);
  11319. escapeIllegalXmlChars (outputStream, child->getText(), false);
  11320. lastWasTextNode = true;
  11321. }
  11322. else
  11323. {
  11324. if (indentationLevel >= 0)
  11325. {
  11326. if (lastWasTextNode)
  11327. outputStream.write ("\r\n", 2);
  11328. child->writeElementAsText (outputStream, indentationLevel + 2, lineWrapLength);
  11329. }
  11330. else
  11331. {
  11332. child->writeElementAsText (outputStream, indentationLevel, lineWrapLength);
  11333. }
  11334. lastWasTextNode = false;
  11335. }
  11336. child = child->nextElement;
  11337. }
  11338. if (indentationLevel >= 0)
  11339. {
  11340. if (lastWasTextNode)
  11341. outputStream.write ("\r\n", 2);
  11342. writeSpaces (outputStream, indentationLevel);
  11343. }
  11344. }
  11345. outputStream.write ("</", 2);
  11346. outputStream << tagName;
  11347. if (indentationLevel >= 0)
  11348. outputStream.write (">\r\n", 3);
  11349. else
  11350. outputStream.writeByte ('>');
  11351. }
  11352. else
  11353. {
  11354. if (indentationLevel >= 0)
  11355. outputStream.write ("/>\r\n", 4);
  11356. else
  11357. outputStream.write ("/>", 2);
  11358. }
  11359. }
  11360. else
  11361. {
  11362. if (indentationLevel >= 0)
  11363. writeSpaces (outputStream, indentationLevel + 2);
  11364. escapeIllegalXmlChars (outputStream, getText(), false);
  11365. }
  11366. }
  11367. const String XmlElement::createDocument (const String& dtdToUse,
  11368. const bool allOnOneLine,
  11369. const bool includeXmlHeader,
  11370. const String& encodingType,
  11371. const int lineWrapLength) const
  11372. {
  11373. MemoryOutputStream mem (2048, 4096);
  11374. writeToStream (mem, dtdToUse, allOnOneLine, includeXmlHeader, encodingType, lineWrapLength);
  11375. return mem.toUTF8();
  11376. }
  11377. void XmlElement::writeToStream (OutputStream& output,
  11378. const String& dtdToUse,
  11379. const bool allOnOneLine,
  11380. const bool includeXmlHeader,
  11381. const String& encodingType,
  11382. const int lineWrapLength) const
  11383. {
  11384. if (includeXmlHeader)
  11385. output << "<?xml version=\"1.0\" encoding=\"" << encodingType
  11386. << (allOnOneLine ? "\"?> " : "\"?>\r\n\r\n");
  11387. if (dtdToUse.isNotEmpty())
  11388. output << dtdToUse << (allOnOneLine ? " " : "\r\n");
  11389. writeElementAsText (output, allOnOneLine ? -1 : 0, lineWrapLength);
  11390. }
  11391. bool XmlElement::writeToFile (const File& file,
  11392. const String& dtdToUse,
  11393. const String& encodingType,
  11394. const int lineWrapLength) const
  11395. {
  11396. if (file.hasWriteAccess())
  11397. {
  11398. TemporaryFile tempFile (file);
  11399. ScopedPointer <FileOutputStream> out (tempFile.getFile().createOutputStream());
  11400. if (out != 0)
  11401. {
  11402. writeToStream (*out, dtdToUse, false, true, encodingType, lineWrapLength);
  11403. out = 0;
  11404. return tempFile.overwriteTargetFileWithTemporary();
  11405. }
  11406. }
  11407. return false;
  11408. }
  11409. bool XmlElement::hasTagName (const String& tagNameWanted) const throw()
  11410. {
  11411. #if JUCE_DEBUG
  11412. // if debugging, check that the case is actually the same, because
  11413. // valid xml is case-sensitive, and although this lets it pass, it's
  11414. // better not to..
  11415. if (tagName.equalsIgnoreCase (tagNameWanted))
  11416. {
  11417. jassert (tagName == tagNameWanted);
  11418. return true;
  11419. }
  11420. else
  11421. {
  11422. return false;
  11423. }
  11424. #else
  11425. return tagName.equalsIgnoreCase (tagNameWanted);
  11426. #endif
  11427. }
  11428. XmlElement* XmlElement::getNextElementWithTagName (const String& requiredTagName) const
  11429. {
  11430. XmlElement* e = nextElement;
  11431. while (e != 0 && ! e->hasTagName (requiredTagName))
  11432. e = e->nextElement;
  11433. return e;
  11434. }
  11435. int XmlElement::getNumAttributes() const throw()
  11436. {
  11437. const XmlAttributeNode* att = attributes;
  11438. int count = 0;
  11439. while (att != 0)
  11440. {
  11441. att = att->next;
  11442. ++count;
  11443. }
  11444. return count;
  11445. }
  11446. const String& XmlElement::getAttributeName (const int index) const throw()
  11447. {
  11448. const XmlAttributeNode* att = attributes;
  11449. int count = 0;
  11450. while (att != 0)
  11451. {
  11452. if (count == index)
  11453. return att->name;
  11454. att = att->next;
  11455. ++count;
  11456. }
  11457. return String::empty;
  11458. }
  11459. const String& XmlElement::getAttributeValue (const int index) const throw()
  11460. {
  11461. const XmlAttributeNode* att = attributes;
  11462. int count = 0;
  11463. while (att != 0)
  11464. {
  11465. if (count == index)
  11466. return att->value;
  11467. att = att->next;
  11468. ++count;
  11469. }
  11470. return String::empty;
  11471. }
  11472. bool XmlElement::hasAttribute (const String& attributeName) const throw()
  11473. {
  11474. const XmlAttributeNode* att = attributes;
  11475. while (att != 0)
  11476. {
  11477. if (att->name.equalsIgnoreCase (attributeName))
  11478. return true;
  11479. att = att->next;
  11480. }
  11481. return false;
  11482. }
  11483. const String& XmlElement::getStringAttribute (const String& attributeName) const throw()
  11484. {
  11485. const XmlAttributeNode* att = attributes;
  11486. while (att != 0)
  11487. {
  11488. if (att->name.equalsIgnoreCase (attributeName))
  11489. return att->value;
  11490. att = att->next;
  11491. }
  11492. return String::empty;
  11493. }
  11494. const String XmlElement::getStringAttribute (const String& attributeName, const String& defaultReturnValue) const
  11495. {
  11496. const XmlAttributeNode* att = attributes;
  11497. while (att != 0)
  11498. {
  11499. if (att->name.equalsIgnoreCase (attributeName))
  11500. return att->value;
  11501. att = att->next;
  11502. }
  11503. return defaultReturnValue;
  11504. }
  11505. int XmlElement::getIntAttribute (const String& attributeName, const int defaultReturnValue) const
  11506. {
  11507. const XmlAttributeNode* att = attributes;
  11508. while (att != 0)
  11509. {
  11510. if (att->name.equalsIgnoreCase (attributeName))
  11511. return att->value.getIntValue();
  11512. att = att->next;
  11513. }
  11514. return defaultReturnValue;
  11515. }
  11516. double XmlElement::getDoubleAttribute (const String& attributeName, const double defaultReturnValue) const
  11517. {
  11518. const XmlAttributeNode* att = attributes;
  11519. while (att != 0)
  11520. {
  11521. if (att->name.equalsIgnoreCase (attributeName))
  11522. return att->value.getDoubleValue();
  11523. att = att->next;
  11524. }
  11525. return defaultReturnValue;
  11526. }
  11527. bool XmlElement::getBoolAttribute (const String& attributeName, const bool defaultReturnValue) const
  11528. {
  11529. const XmlAttributeNode* att = attributes;
  11530. while (att != 0)
  11531. {
  11532. if (att->name.equalsIgnoreCase (attributeName))
  11533. {
  11534. juce_wchar firstChar = att->value[0];
  11535. if (CharacterFunctions::isWhitespace (firstChar))
  11536. firstChar = att->value.trimStart() [0];
  11537. return firstChar == '1'
  11538. || firstChar == 't'
  11539. || firstChar == 'y'
  11540. || firstChar == 'T'
  11541. || firstChar == 'Y';
  11542. }
  11543. att = att->next;
  11544. }
  11545. return defaultReturnValue;
  11546. }
  11547. bool XmlElement::compareAttribute (const String& attributeName,
  11548. const String& stringToCompareAgainst,
  11549. const bool ignoreCase) const throw()
  11550. {
  11551. const XmlAttributeNode* att = attributes;
  11552. while (att != 0)
  11553. {
  11554. if (att->name.equalsIgnoreCase (attributeName))
  11555. {
  11556. if (ignoreCase)
  11557. return att->value.equalsIgnoreCase (stringToCompareAgainst);
  11558. else
  11559. return att->value == stringToCompareAgainst;
  11560. }
  11561. att = att->next;
  11562. }
  11563. return false;
  11564. }
  11565. void XmlElement::setAttribute (const String& attributeName, const String& value)
  11566. {
  11567. #if JUCE_DEBUG
  11568. // check the identifier being passed in is legal..
  11569. const juce_wchar* t = attributeName;
  11570. while (*t != 0)
  11571. {
  11572. jassert (CharacterFunctions::isLetterOrDigit (*t)
  11573. || *t == '_'
  11574. || *t == '-'
  11575. || *t == ':');
  11576. ++t;
  11577. }
  11578. #endif
  11579. if (attributes == 0)
  11580. {
  11581. attributes = new XmlAttributeNode (attributeName, value);
  11582. }
  11583. else
  11584. {
  11585. XmlAttributeNode* att = attributes;
  11586. for (;;)
  11587. {
  11588. if (att->name.equalsIgnoreCase (attributeName))
  11589. {
  11590. att->value = value;
  11591. break;
  11592. }
  11593. else if (att->next == 0)
  11594. {
  11595. att->next = new XmlAttributeNode (attributeName, value);
  11596. break;
  11597. }
  11598. att = att->next;
  11599. }
  11600. }
  11601. }
  11602. void XmlElement::setAttribute (const String& attributeName, const int number)
  11603. {
  11604. setAttribute (attributeName, String (number));
  11605. }
  11606. void XmlElement::setAttribute (const String& attributeName, const double number)
  11607. {
  11608. setAttribute (attributeName, String (number));
  11609. }
  11610. void XmlElement::removeAttribute (const String& attributeName) throw()
  11611. {
  11612. XmlAttributeNode* att = attributes;
  11613. XmlAttributeNode* lastAtt = 0;
  11614. while (att != 0)
  11615. {
  11616. if (att->name.equalsIgnoreCase (attributeName))
  11617. {
  11618. if (lastAtt == 0)
  11619. attributes = att->next;
  11620. else
  11621. lastAtt->next = att->next;
  11622. delete att;
  11623. break;
  11624. }
  11625. lastAtt = att;
  11626. att = att->next;
  11627. }
  11628. }
  11629. void XmlElement::removeAllAttributes() throw()
  11630. {
  11631. while (attributes != 0)
  11632. {
  11633. XmlAttributeNode* const nextAtt = attributes->next;
  11634. delete attributes;
  11635. attributes = nextAtt;
  11636. }
  11637. }
  11638. int XmlElement::getNumChildElements() const throw()
  11639. {
  11640. int count = 0;
  11641. const XmlElement* child = firstChildElement;
  11642. while (child != 0)
  11643. {
  11644. ++count;
  11645. child = child->nextElement;
  11646. }
  11647. return count;
  11648. }
  11649. XmlElement* XmlElement::getChildElement (const int index) const throw()
  11650. {
  11651. int count = 0;
  11652. XmlElement* child = firstChildElement;
  11653. while (child != 0 && count < index)
  11654. {
  11655. child = child->nextElement;
  11656. ++count;
  11657. }
  11658. return child;
  11659. }
  11660. XmlElement* XmlElement::getChildByName (const String& childName) const throw()
  11661. {
  11662. XmlElement* child = firstChildElement;
  11663. while (child != 0)
  11664. {
  11665. if (child->hasTagName (childName))
  11666. break;
  11667. child = child->nextElement;
  11668. }
  11669. return child;
  11670. }
  11671. void XmlElement::addChildElement (XmlElement* const newNode) throw()
  11672. {
  11673. if (newNode != 0)
  11674. {
  11675. if (firstChildElement == 0)
  11676. {
  11677. firstChildElement = newNode;
  11678. }
  11679. else
  11680. {
  11681. XmlElement* child = firstChildElement;
  11682. while (child->nextElement != 0)
  11683. child = child->nextElement;
  11684. child->nextElement = newNode;
  11685. // if this is non-zero, then something's probably
  11686. // gone wrong..
  11687. jassert (newNode->nextElement == 0);
  11688. }
  11689. }
  11690. }
  11691. void XmlElement::insertChildElement (XmlElement* const newNode,
  11692. int indexToInsertAt) throw()
  11693. {
  11694. if (newNode != 0)
  11695. {
  11696. removeChildElement (newNode, false);
  11697. if (indexToInsertAt == 0)
  11698. {
  11699. newNode->nextElement = firstChildElement;
  11700. firstChildElement = newNode;
  11701. }
  11702. else
  11703. {
  11704. if (firstChildElement == 0)
  11705. {
  11706. firstChildElement = newNode;
  11707. }
  11708. else
  11709. {
  11710. if (indexToInsertAt < 0)
  11711. indexToInsertAt = std::numeric_limits<int>::max();
  11712. XmlElement* child = firstChildElement;
  11713. while (child->nextElement != 0 && --indexToInsertAt > 0)
  11714. child = child->nextElement;
  11715. newNode->nextElement = child->nextElement;
  11716. child->nextElement = newNode;
  11717. }
  11718. }
  11719. }
  11720. }
  11721. XmlElement* XmlElement::createNewChildElement (const String& childTagName)
  11722. {
  11723. XmlElement* const newElement = new XmlElement (childTagName);
  11724. addChildElement (newElement);
  11725. return newElement;
  11726. }
  11727. bool XmlElement::replaceChildElement (XmlElement* const currentChildElement,
  11728. XmlElement* const newNode) throw()
  11729. {
  11730. if (newNode != 0)
  11731. {
  11732. XmlElement* child = firstChildElement;
  11733. XmlElement* previousNode = 0;
  11734. while (child != 0)
  11735. {
  11736. if (child == currentChildElement)
  11737. {
  11738. if (child != newNode)
  11739. {
  11740. if (previousNode == 0)
  11741. firstChildElement = newNode;
  11742. else
  11743. previousNode->nextElement = newNode;
  11744. newNode->nextElement = child->nextElement;
  11745. delete child;
  11746. }
  11747. return true;
  11748. }
  11749. previousNode = child;
  11750. child = child->nextElement;
  11751. }
  11752. }
  11753. return false;
  11754. }
  11755. void XmlElement::removeChildElement (XmlElement* const childToRemove,
  11756. const bool shouldDeleteTheChild) throw()
  11757. {
  11758. if (childToRemove != 0)
  11759. {
  11760. if (firstChildElement == childToRemove)
  11761. {
  11762. firstChildElement = childToRemove->nextElement;
  11763. childToRemove->nextElement = 0;
  11764. }
  11765. else
  11766. {
  11767. XmlElement* child = firstChildElement;
  11768. XmlElement* last = 0;
  11769. while (child != 0)
  11770. {
  11771. if (child == childToRemove)
  11772. {
  11773. if (last == 0)
  11774. firstChildElement = child->nextElement;
  11775. else
  11776. last->nextElement = child->nextElement;
  11777. childToRemove->nextElement = 0;
  11778. break;
  11779. }
  11780. last = child;
  11781. child = child->nextElement;
  11782. }
  11783. }
  11784. if (shouldDeleteTheChild)
  11785. delete childToRemove;
  11786. }
  11787. }
  11788. bool XmlElement::isEquivalentTo (const XmlElement* const other,
  11789. const bool ignoreOrderOfAttributes) const throw()
  11790. {
  11791. if (this != other)
  11792. {
  11793. if (other == 0 || tagName != other->tagName)
  11794. {
  11795. return false;
  11796. }
  11797. if (ignoreOrderOfAttributes)
  11798. {
  11799. int totalAtts = 0;
  11800. const XmlAttributeNode* att = attributes;
  11801. while (att != 0)
  11802. {
  11803. if (! other->compareAttribute (att->name, att->value))
  11804. return false;
  11805. att = att->next;
  11806. ++totalAtts;
  11807. }
  11808. if (totalAtts != other->getNumAttributes())
  11809. return false;
  11810. }
  11811. else
  11812. {
  11813. const XmlAttributeNode* thisAtt = attributes;
  11814. const XmlAttributeNode* otherAtt = other->attributes;
  11815. for (;;)
  11816. {
  11817. if (thisAtt == 0 || otherAtt == 0)
  11818. {
  11819. if (thisAtt == otherAtt) // both 0, so it's a match
  11820. break;
  11821. return false;
  11822. }
  11823. if (thisAtt->name != otherAtt->name
  11824. || thisAtt->value != otherAtt->value)
  11825. {
  11826. return false;
  11827. }
  11828. thisAtt = thisAtt->next;
  11829. otherAtt = otherAtt->next;
  11830. }
  11831. }
  11832. const XmlElement* thisChild = firstChildElement;
  11833. const XmlElement* otherChild = other->firstChildElement;
  11834. for (;;)
  11835. {
  11836. if (thisChild == 0 || otherChild == 0)
  11837. {
  11838. if (thisChild == otherChild) // both 0, so it's a match
  11839. break;
  11840. return false;
  11841. }
  11842. if (! thisChild->isEquivalentTo (otherChild, ignoreOrderOfAttributes))
  11843. return false;
  11844. thisChild = thisChild->nextElement;
  11845. otherChild = otherChild->nextElement;
  11846. }
  11847. }
  11848. return true;
  11849. }
  11850. void XmlElement::deleteAllChildElements() throw()
  11851. {
  11852. while (firstChildElement != 0)
  11853. {
  11854. XmlElement* const nextChild = firstChildElement->nextElement;
  11855. delete firstChildElement;
  11856. firstChildElement = nextChild;
  11857. }
  11858. }
  11859. void XmlElement::deleteAllChildElementsWithTagName (const String& name) throw()
  11860. {
  11861. XmlElement* child = firstChildElement;
  11862. while (child != 0)
  11863. {
  11864. if (child->hasTagName (name))
  11865. {
  11866. XmlElement* const nextChild = child->nextElement;
  11867. removeChildElement (child, true);
  11868. child = nextChild;
  11869. }
  11870. else
  11871. {
  11872. child = child->nextElement;
  11873. }
  11874. }
  11875. }
  11876. bool XmlElement::containsChildElement (const XmlElement* const possibleChild) const throw()
  11877. {
  11878. const XmlElement* child = firstChildElement;
  11879. while (child != 0)
  11880. {
  11881. if (child == possibleChild)
  11882. return true;
  11883. child = child->nextElement;
  11884. }
  11885. return false;
  11886. }
  11887. XmlElement* XmlElement::findParentElementOf (const XmlElement* const elementToLookFor) throw()
  11888. {
  11889. if (this == elementToLookFor || elementToLookFor == 0)
  11890. return 0;
  11891. XmlElement* child = firstChildElement;
  11892. while (child != 0)
  11893. {
  11894. if (elementToLookFor == child)
  11895. return this;
  11896. XmlElement* const found = child->findParentElementOf (elementToLookFor);
  11897. if (found != 0)
  11898. return found;
  11899. child = child->nextElement;
  11900. }
  11901. return 0;
  11902. }
  11903. void XmlElement::getChildElementsAsArray (XmlElement** elems) const throw()
  11904. {
  11905. XmlElement* e = firstChildElement;
  11906. while (e != 0)
  11907. {
  11908. *elems++ = e;
  11909. e = e->nextElement;
  11910. }
  11911. }
  11912. void XmlElement::reorderChildElements (XmlElement** const elems, const int num) throw()
  11913. {
  11914. XmlElement* e = firstChildElement = elems[0];
  11915. for (int i = 1; i < num; ++i)
  11916. {
  11917. e->nextElement = elems[i];
  11918. e = e->nextElement;
  11919. }
  11920. e->nextElement = 0;
  11921. }
  11922. bool XmlElement::isTextElement() const throw()
  11923. {
  11924. return tagName.isEmpty();
  11925. }
  11926. static const juce_wchar* const juce_xmltextContentAttributeName = L"text";
  11927. const String XmlElement::getText() const throw()
  11928. {
  11929. jassert (isTextElement()); // you're trying to get the text from an element that
  11930. // isn't actually a text element.. If this contains text sub-nodes, you
  11931. // probably want to use getAllSubText instead.
  11932. return getStringAttribute (juce_xmltextContentAttributeName);
  11933. }
  11934. void XmlElement::setText (const String& newText) throw()
  11935. {
  11936. if (isTextElement())
  11937. {
  11938. setAttribute (juce_xmltextContentAttributeName, newText);
  11939. }
  11940. else
  11941. {
  11942. jassertfalse // you can only change the text in a text element, not a normal one.
  11943. }
  11944. }
  11945. const String XmlElement::getAllSubText() const throw()
  11946. {
  11947. String result;
  11948. String::Concatenator concatenator (result);
  11949. const XmlElement* child = firstChildElement;
  11950. while (child != 0)
  11951. {
  11952. if (child->isTextElement())
  11953. concatenator.append (child->getText());
  11954. child = child->nextElement;
  11955. }
  11956. return result;
  11957. }
  11958. const String XmlElement::getChildElementAllSubText (const String& childTagName,
  11959. const String& defaultReturnValue) const throw()
  11960. {
  11961. const XmlElement* const child = getChildByName (childTagName);
  11962. if (child != 0)
  11963. return child->getAllSubText();
  11964. return defaultReturnValue;
  11965. }
  11966. XmlElement* XmlElement::createTextElement (const String& text) throw()
  11967. {
  11968. XmlElement* const e = new XmlElement ((int) 0);
  11969. e->setAttribute (juce_xmltextContentAttributeName, text);
  11970. return e;
  11971. }
  11972. void XmlElement::addTextElement (const String& text) throw()
  11973. {
  11974. addChildElement (createTextElement (text));
  11975. }
  11976. void XmlElement::deleteAllTextElements() throw()
  11977. {
  11978. XmlElement* child = firstChildElement;
  11979. while (child != 0)
  11980. {
  11981. XmlElement* const next = child->nextElement;
  11982. if (child->isTextElement())
  11983. removeChildElement (child, true);
  11984. child = next;
  11985. }
  11986. }
  11987. END_JUCE_NAMESPACE
  11988. /*** End of inlined file: juce_XmlElement.cpp ***/
  11989. /*** Start of inlined file: juce_ReadWriteLock.cpp ***/
  11990. BEGIN_JUCE_NAMESPACE
  11991. ReadWriteLock::ReadWriteLock() throw()
  11992. : numWaitingWriters (0),
  11993. numWriters (0),
  11994. writerThreadId (0)
  11995. {
  11996. }
  11997. ReadWriteLock::~ReadWriteLock() throw()
  11998. {
  11999. jassert (readerThreads.size() == 0);
  12000. jassert (numWriters == 0);
  12001. }
  12002. void ReadWriteLock::enterRead() const throw()
  12003. {
  12004. const Thread::ThreadID threadId = Thread::getCurrentThreadId();
  12005. const ScopedLock sl (accessLock);
  12006. for (;;)
  12007. {
  12008. jassert (readerThreads.size() % 2 == 0);
  12009. int i;
  12010. for (i = 0; i < readerThreads.size(); i += 2)
  12011. if (readerThreads.getUnchecked(i) == threadId)
  12012. break;
  12013. if (i < readerThreads.size()
  12014. || numWriters + numWaitingWriters == 0
  12015. || (threadId == writerThreadId && numWriters > 0))
  12016. {
  12017. if (i < readerThreads.size())
  12018. {
  12019. readerThreads.set (i + 1, (Thread::ThreadID) (1 + (pointer_sized_int) readerThreads.getUnchecked (i + 1)));
  12020. }
  12021. else
  12022. {
  12023. readerThreads.add (threadId);
  12024. readerThreads.add ((Thread::ThreadID) 1);
  12025. }
  12026. return;
  12027. }
  12028. const ScopedUnlock ul (accessLock);
  12029. waitEvent.wait (100);
  12030. }
  12031. }
  12032. void ReadWriteLock::exitRead() const throw()
  12033. {
  12034. const Thread::ThreadID threadId = Thread::getCurrentThreadId();
  12035. const ScopedLock sl (accessLock);
  12036. for (int i = 0; i < readerThreads.size(); i += 2)
  12037. {
  12038. if (readerThreads.getUnchecked(i) == threadId)
  12039. {
  12040. const pointer_sized_int newCount = ((pointer_sized_int) readerThreads.getUnchecked (i + 1)) - 1;
  12041. if (newCount == 0)
  12042. {
  12043. readerThreads.removeRange (i, 2);
  12044. waitEvent.signal();
  12045. }
  12046. else
  12047. {
  12048. readerThreads.set (i + 1, (Thread::ThreadID) newCount);
  12049. }
  12050. return;
  12051. }
  12052. }
  12053. jassertfalse // unlocking a lock that wasn't locked..
  12054. }
  12055. void ReadWriteLock::enterWrite() const throw()
  12056. {
  12057. const Thread::ThreadID threadId = Thread::getCurrentThreadId();
  12058. const ScopedLock sl (accessLock);
  12059. for (;;)
  12060. {
  12061. if (readerThreads.size() + numWriters == 0
  12062. || threadId == writerThreadId
  12063. || (readerThreads.size() == 2
  12064. && readerThreads.getUnchecked(0) == threadId))
  12065. {
  12066. writerThreadId = threadId;
  12067. ++numWriters;
  12068. break;
  12069. }
  12070. ++numWaitingWriters;
  12071. accessLock.exit();
  12072. waitEvent.wait (100);
  12073. accessLock.enter();
  12074. --numWaitingWriters;
  12075. }
  12076. }
  12077. bool ReadWriteLock::tryEnterWrite() const throw()
  12078. {
  12079. const Thread::ThreadID threadId = Thread::getCurrentThreadId();
  12080. const ScopedLock sl (accessLock);
  12081. if (readerThreads.size() + numWriters == 0
  12082. || threadId == writerThreadId
  12083. || (readerThreads.size() == 2
  12084. && readerThreads.getUnchecked(0) == threadId))
  12085. {
  12086. writerThreadId = threadId;
  12087. ++numWriters;
  12088. return true;
  12089. }
  12090. return false;
  12091. }
  12092. void ReadWriteLock::exitWrite() const throw()
  12093. {
  12094. const ScopedLock sl (accessLock);
  12095. // check this thread actually had the lock..
  12096. jassert (numWriters > 0 && writerThreadId == Thread::getCurrentThreadId());
  12097. if (--numWriters == 0)
  12098. {
  12099. writerThreadId = 0;
  12100. waitEvent.signal();
  12101. }
  12102. }
  12103. END_JUCE_NAMESPACE
  12104. /*** End of inlined file: juce_ReadWriteLock.cpp ***/
  12105. /*** Start of inlined file: juce_Thread.cpp ***/
  12106. BEGIN_JUCE_NAMESPACE
  12107. // these functions are implemented in the platform-specific code.
  12108. void* juce_createThread (void* userData);
  12109. void juce_killThread (void* handle);
  12110. bool juce_setThreadPriority (void* handle, int priority);
  12111. void juce_setCurrentThreadName (const String& name);
  12112. #if JUCE_WIN32
  12113. void juce_CloseThreadHandle (void* handle);
  12114. #endif
  12115. void Thread::threadEntryPoint (Thread* const thread)
  12116. {
  12117. {
  12118. const ScopedLock sl (runningThreadsLock);
  12119. runningThreads.add (thread);
  12120. }
  12121. JUCE_TRY
  12122. {
  12123. thread->threadId_ = Thread::getCurrentThreadId();
  12124. if (thread->threadName_.isNotEmpty())
  12125. juce_setCurrentThreadName (thread->threadName_);
  12126. if (thread->startSuspensionEvent_.wait (10000))
  12127. {
  12128. if (thread->affinityMask_ != 0)
  12129. setCurrentThreadAffinityMask (thread->affinityMask_);
  12130. thread->run();
  12131. }
  12132. }
  12133. JUCE_CATCH_ALL_ASSERT
  12134. {
  12135. const ScopedLock sl (runningThreadsLock);
  12136. jassert (runningThreads.contains (thread));
  12137. runningThreads.removeValue (thread);
  12138. }
  12139. #if JUCE_WIN32
  12140. juce_CloseThreadHandle (thread->threadHandle_);
  12141. #endif
  12142. thread->threadHandle_ = 0;
  12143. thread->threadId_ = 0;
  12144. }
  12145. // used to wrap the incoming call from the platform-specific code
  12146. void JUCE_API juce_threadEntryPoint (void* userData)
  12147. {
  12148. Thread::threadEntryPoint (static_cast <Thread*> (userData));
  12149. }
  12150. Thread::Thread (const String& threadName)
  12151. : threadName_ (threadName),
  12152. threadHandle_ (0),
  12153. threadPriority_ (5),
  12154. threadId_ (0),
  12155. affinityMask_ (0),
  12156. threadShouldExit_ (false)
  12157. {
  12158. }
  12159. Thread::~Thread()
  12160. {
  12161. stopThread (100);
  12162. }
  12163. void Thread::startThread()
  12164. {
  12165. const ScopedLock sl (startStopLock);
  12166. threadShouldExit_ = false;
  12167. if (threadHandle_ == 0)
  12168. {
  12169. threadHandle_ = juce_createThread (this);
  12170. juce_setThreadPriority (threadHandle_, threadPriority_);
  12171. startSuspensionEvent_.signal();
  12172. }
  12173. }
  12174. void Thread::startThread (const int priority)
  12175. {
  12176. const ScopedLock sl (startStopLock);
  12177. if (threadHandle_ == 0)
  12178. {
  12179. threadPriority_ = priority;
  12180. startThread();
  12181. }
  12182. else
  12183. {
  12184. setPriority (priority);
  12185. }
  12186. }
  12187. bool Thread::isThreadRunning() const
  12188. {
  12189. return threadHandle_ != 0;
  12190. }
  12191. void Thread::signalThreadShouldExit()
  12192. {
  12193. threadShouldExit_ = true;
  12194. }
  12195. bool Thread::waitForThreadToExit (const int timeOutMilliseconds) const
  12196. {
  12197. // Doh! So how exactly do you expect this thread to wait for itself to stop??
  12198. jassert (getThreadId() != getCurrentThreadId());
  12199. const int sleepMsPerIteration = 5;
  12200. int count = timeOutMilliseconds / sleepMsPerIteration;
  12201. while (isThreadRunning())
  12202. {
  12203. if (timeOutMilliseconds > 0 && --count < 0)
  12204. return false;
  12205. sleep (sleepMsPerIteration);
  12206. }
  12207. return true;
  12208. }
  12209. void Thread::stopThread (const int timeOutMilliseconds)
  12210. {
  12211. // agh! You can't stop the thread that's calling this method! How on earth
  12212. // would that work??
  12213. jassert (getCurrentThreadId() != getThreadId());
  12214. const ScopedLock sl (startStopLock);
  12215. if (isThreadRunning())
  12216. {
  12217. signalThreadShouldExit();
  12218. notify();
  12219. if (timeOutMilliseconds != 0)
  12220. waitForThreadToExit (timeOutMilliseconds);
  12221. if (isThreadRunning())
  12222. {
  12223. // very bad karma if this point is reached, as
  12224. // there are bound to be locks and events left in
  12225. // silly states when a thread is killed by force..
  12226. jassertfalse
  12227. Logger::writeToLog ("!! killing thread by force !!");
  12228. juce_killThread (threadHandle_);
  12229. threadHandle_ = 0;
  12230. threadId_ = 0;
  12231. const ScopedLock sl2 (runningThreadsLock);
  12232. runningThreads.removeValue (this);
  12233. }
  12234. }
  12235. }
  12236. bool Thread::setPriority (const int priority)
  12237. {
  12238. const ScopedLock sl (startStopLock);
  12239. const bool worked = juce_setThreadPriority (threadHandle_, priority);
  12240. if (worked)
  12241. threadPriority_ = priority;
  12242. return worked;
  12243. }
  12244. bool Thread::setCurrentThreadPriority (const int priority)
  12245. {
  12246. return juce_setThreadPriority (0, priority);
  12247. }
  12248. void Thread::setAffinityMask (const uint32 affinityMask)
  12249. {
  12250. affinityMask_ = affinityMask;
  12251. }
  12252. bool Thread::wait (const int timeOutMilliseconds) const
  12253. {
  12254. return defaultEvent_.wait (timeOutMilliseconds);
  12255. }
  12256. void Thread::notify() const
  12257. {
  12258. defaultEvent_.signal();
  12259. }
  12260. int Thread::getNumRunningThreads()
  12261. {
  12262. return runningThreads.size();
  12263. }
  12264. Thread* Thread::getCurrentThread()
  12265. {
  12266. const ThreadID thisId = getCurrentThreadId();
  12267. const ScopedLock sl (runningThreadsLock);
  12268. for (int i = runningThreads.size(); --i >= 0;)
  12269. {
  12270. Thread* const t = runningThreads.getUnchecked(i);
  12271. if (t->threadId_ == thisId)
  12272. return t;
  12273. }
  12274. return 0;
  12275. }
  12276. void Thread::stopAllThreads (const int timeOutMilliseconds)
  12277. {
  12278. {
  12279. const ScopedLock sl (runningThreadsLock);
  12280. for (int i = runningThreads.size(); --i >= 0;)
  12281. runningThreads.getUnchecked(i)->signalThreadShouldExit();
  12282. }
  12283. for (;;)
  12284. {
  12285. Thread* firstThread;
  12286. {
  12287. const ScopedLock sl (runningThreadsLock);
  12288. firstThread = runningThreads.getFirst();
  12289. }
  12290. if (firstThread == 0)
  12291. break;
  12292. firstThread->stopThread (timeOutMilliseconds);
  12293. }
  12294. }
  12295. Array<Thread*> Thread::runningThreads;
  12296. CriticalSection Thread::runningThreadsLock;
  12297. END_JUCE_NAMESPACE
  12298. /*** End of inlined file: juce_Thread.cpp ***/
  12299. /*** Start of inlined file: juce_ThreadPool.cpp ***/
  12300. BEGIN_JUCE_NAMESPACE
  12301. ThreadPoolJob::ThreadPoolJob (const String& name)
  12302. : jobName (name),
  12303. pool (0),
  12304. shouldStop (false),
  12305. isActive (false),
  12306. shouldBeDeleted (false)
  12307. {
  12308. }
  12309. ThreadPoolJob::~ThreadPoolJob()
  12310. {
  12311. // you mustn't delete a job while it's still in a pool! Use ThreadPool::removeJob()
  12312. // to remove it first!
  12313. jassert (pool == 0 || ! pool->contains (this));
  12314. }
  12315. const String ThreadPoolJob::getJobName() const
  12316. {
  12317. return jobName;
  12318. }
  12319. void ThreadPoolJob::setJobName (const String& newName)
  12320. {
  12321. jobName = newName;
  12322. }
  12323. void ThreadPoolJob::signalJobShouldExit()
  12324. {
  12325. shouldStop = true;
  12326. }
  12327. class ThreadPool::ThreadPoolThread : public Thread
  12328. {
  12329. public:
  12330. ThreadPoolThread (ThreadPool& pool_)
  12331. : Thread ("Pool"),
  12332. pool (pool_),
  12333. busy (false)
  12334. {
  12335. }
  12336. ~ThreadPoolThread()
  12337. {
  12338. }
  12339. void run()
  12340. {
  12341. while (! threadShouldExit())
  12342. {
  12343. if (! pool.runNextJob())
  12344. wait (500);
  12345. }
  12346. }
  12347. private:
  12348. ThreadPool& pool;
  12349. bool volatile busy;
  12350. ThreadPoolThread (const ThreadPoolThread&);
  12351. ThreadPoolThread& operator= (const ThreadPoolThread&);
  12352. };
  12353. ThreadPool::ThreadPool (const int numThreads,
  12354. const bool startThreadsOnlyWhenNeeded,
  12355. const int stopThreadsWhenNotUsedTimeoutMs)
  12356. : threadStopTimeout (stopThreadsWhenNotUsedTimeoutMs),
  12357. priority (5)
  12358. {
  12359. jassert (numThreads > 0); // not much point having one of these with no threads in it.
  12360. for (int i = jmax (1, numThreads); --i >= 0;)
  12361. threads.add (new ThreadPoolThread (*this));
  12362. if (! startThreadsOnlyWhenNeeded)
  12363. for (int i = threads.size(); --i >= 0;)
  12364. threads.getUnchecked(i)->startThread (priority);
  12365. }
  12366. ThreadPool::~ThreadPool()
  12367. {
  12368. removeAllJobs (true, 4000);
  12369. int i;
  12370. for (i = threads.size(); --i >= 0;)
  12371. threads.getUnchecked(i)->signalThreadShouldExit();
  12372. for (i = threads.size(); --i >= 0;)
  12373. threads.getUnchecked(i)->stopThread (500);
  12374. }
  12375. void ThreadPool::addJob (ThreadPoolJob* const job)
  12376. {
  12377. jassert (job != 0);
  12378. jassert (job->pool == 0);
  12379. if (job->pool == 0)
  12380. {
  12381. job->pool = this;
  12382. job->shouldStop = false;
  12383. job->isActive = false;
  12384. {
  12385. const ScopedLock sl (lock);
  12386. jobs.add (job);
  12387. int numRunning = 0;
  12388. for (int i = threads.size(); --i >= 0;)
  12389. if (threads.getUnchecked(i)->isThreadRunning() && ! threads.getUnchecked(i)->threadShouldExit())
  12390. ++numRunning;
  12391. if (numRunning < threads.size())
  12392. {
  12393. bool startedOne = false;
  12394. int n = 1000;
  12395. while (--n >= 0 && ! startedOne)
  12396. {
  12397. for (int i = threads.size(); --i >= 0;)
  12398. {
  12399. if (! threads.getUnchecked(i)->isThreadRunning())
  12400. {
  12401. threads.getUnchecked(i)->startThread (priority);
  12402. startedOne = true;
  12403. break;
  12404. }
  12405. }
  12406. if (! startedOne)
  12407. Thread::sleep (2);
  12408. }
  12409. }
  12410. }
  12411. for (int i = threads.size(); --i >= 0;)
  12412. threads.getUnchecked(i)->notify();
  12413. }
  12414. }
  12415. int ThreadPool::getNumJobs() const
  12416. {
  12417. return jobs.size();
  12418. }
  12419. ThreadPoolJob* ThreadPool::getJob (const int index) const
  12420. {
  12421. const ScopedLock sl (lock);
  12422. return jobs [index];
  12423. }
  12424. bool ThreadPool::contains (const ThreadPoolJob* const job) const
  12425. {
  12426. const ScopedLock sl (lock);
  12427. return jobs.contains (const_cast <ThreadPoolJob*> (job));
  12428. }
  12429. bool ThreadPool::isJobRunning (const ThreadPoolJob* const job) const
  12430. {
  12431. const ScopedLock sl (lock);
  12432. return jobs.contains (const_cast <ThreadPoolJob*> (job)) && job->isActive;
  12433. }
  12434. bool ThreadPool::waitForJobToFinish (const ThreadPoolJob* const job,
  12435. const int timeOutMs) const
  12436. {
  12437. if (job != 0)
  12438. {
  12439. const uint32 start = Time::getMillisecondCounter();
  12440. while (contains (job))
  12441. {
  12442. if (timeOutMs >= 0 && Time::getMillisecondCounter() >= start + timeOutMs)
  12443. return false;
  12444. jobFinishedSignal.wait (2);
  12445. }
  12446. }
  12447. return true;
  12448. }
  12449. bool ThreadPool::removeJob (ThreadPoolJob* const job,
  12450. const bool interruptIfRunning,
  12451. const int timeOutMs)
  12452. {
  12453. bool dontWait = true;
  12454. if (job != 0)
  12455. {
  12456. const ScopedLock sl (lock);
  12457. if (jobs.contains (job))
  12458. {
  12459. if (job->isActive)
  12460. {
  12461. if (interruptIfRunning)
  12462. job->signalJobShouldExit();
  12463. dontWait = false;
  12464. }
  12465. else
  12466. {
  12467. jobs.removeValue (job);
  12468. }
  12469. }
  12470. }
  12471. return dontWait || waitForJobToFinish (job, timeOutMs);
  12472. }
  12473. bool ThreadPool::removeAllJobs (const bool interruptRunningJobs,
  12474. const int timeOutMs,
  12475. const bool deleteInactiveJobs,
  12476. ThreadPool::JobSelector* selectedJobsToRemove)
  12477. {
  12478. Array <ThreadPoolJob*> jobsToWaitFor;
  12479. {
  12480. const ScopedLock sl (lock);
  12481. for (int i = jobs.size(); --i >= 0;)
  12482. {
  12483. ThreadPoolJob* const job = jobs.getUnchecked(i);
  12484. if (selectedJobsToRemove == 0 || selectedJobsToRemove->isJobSuitable (job))
  12485. {
  12486. if (job->isActive)
  12487. {
  12488. jobsToWaitFor.add (job);
  12489. if (interruptRunningJobs)
  12490. job->signalJobShouldExit();
  12491. }
  12492. else
  12493. {
  12494. jobs.remove (i);
  12495. if (deleteInactiveJobs)
  12496. delete job;
  12497. }
  12498. }
  12499. }
  12500. }
  12501. const uint32 start = Time::getMillisecondCounter();
  12502. for (;;)
  12503. {
  12504. for (int i = jobsToWaitFor.size(); --i >= 0;)
  12505. if (! isJobRunning (jobsToWaitFor.getUnchecked (i)))
  12506. jobsToWaitFor.remove (i);
  12507. if (jobsToWaitFor.size() == 0)
  12508. break;
  12509. if (timeOutMs >= 0 && Time::getMillisecondCounter() >= start + timeOutMs)
  12510. return false;
  12511. jobFinishedSignal.wait (20);
  12512. }
  12513. return true;
  12514. }
  12515. const StringArray ThreadPool::getNamesOfAllJobs (const bool onlyReturnActiveJobs) const
  12516. {
  12517. StringArray s;
  12518. const ScopedLock sl (lock);
  12519. for (int i = 0; i < jobs.size(); ++i)
  12520. {
  12521. const ThreadPoolJob* const job = jobs.getUnchecked(i);
  12522. if (job->isActive || ! onlyReturnActiveJobs)
  12523. s.add (job->getJobName());
  12524. }
  12525. return s;
  12526. }
  12527. bool ThreadPool::setThreadPriorities (const int newPriority)
  12528. {
  12529. bool ok = true;
  12530. if (priority != newPriority)
  12531. {
  12532. priority = newPriority;
  12533. for (int i = threads.size(); --i >= 0;)
  12534. if (! threads.getUnchecked(i)->setPriority (newPriority))
  12535. ok = false;
  12536. }
  12537. return ok;
  12538. }
  12539. bool ThreadPool::runNextJob()
  12540. {
  12541. ThreadPoolJob* job = 0;
  12542. {
  12543. const ScopedLock sl (lock);
  12544. for (int i = 0; i < jobs.size(); ++i)
  12545. {
  12546. job = jobs[i];
  12547. if (job != 0 && ! (job->isActive || job->shouldStop))
  12548. break;
  12549. job = 0;
  12550. }
  12551. if (job != 0)
  12552. job->isActive = true;
  12553. }
  12554. if (job != 0)
  12555. {
  12556. JUCE_TRY
  12557. {
  12558. ThreadPoolJob::JobStatus result = job->runJob();
  12559. lastJobEndTime = Time::getApproximateMillisecondCounter();
  12560. const ScopedLock sl (lock);
  12561. if (jobs.contains (job))
  12562. {
  12563. job->isActive = false;
  12564. if (result != ThreadPoolJob::jobNeedsRunningAgain || job->shouldStop)
  12565. {
  12566. job->pool = 0;
  12567. job->shouldStop = true;
  12568. jobs.removeValue (job);
  12569. if (result == ThreadPoolJob::jobHasFinishedAndShouldBeDeleted)
  12570. delete job;
  12571. jobFinishedSignal.signal();
  12572. }
  12573. else
  12574. {
  12575. // move the job to the end of the queue if it wants another go
  12576. jobs.move (jobs.indexOf (job), -1);
  12577. }
  12578. }
  12579. }
  12580. #if JUCE_CATCH_UNHANDLED_EXCEPTIONS
  12581. catch (...)
  12582. {
  12583. const ScopedLock sl (lock);
  12584. jobs.removeValue (job);
  12585. }
  12586. #endif
  12587. }
  12588. else
  12589. {
  12590. if (threadStopTimeout > 0
  12591. && Time::getApproximateMillisecondCounter() > lastJobEndTime + threadStopTimeout)
  12592. {
  12593. const ScopedLock sl (lock);
  12594. if (jobs.size() == 0)
  12595. for (int i = threads.size(); --i >= 0;)
  12596. threads.getUnchecked(i)->signalThreadShouldExit();
  12597. }
  12598. else
  12599. {
  12600. return false;
  12601. }
  12602. }
  12603. return true;
  12604. }
  12605. END_JUCE_NAMESPACE
  12606. /*** End of inlined file: juce_ThreadPool.cpp ***/
  12607. /*** Start of inlined file: juce_TimeSliceThread.cpp ***/
  12608. BEGIN_JUCE_NAMESPACE
  12609. TimeSliceThread::TimeSliceThread (const String& threadName)
  12610. : Thread (threadName),
  12611. index (0),
  12612. clientBeingCalled (0),
  12613. clientsChanged (false)
  12614. {
  12615. }
  12616. TimeSliceThread::~TimeSliceThread()
  12617. {
  12618. stopThread (2000);
  12619. }
  12620. void TimeSliceThread::addTimeSliceClient (TimeSliceClient* const client)
  12621. {
  12622. const ScopedLock sl (listLock);
  12623. clients.addIfNotAlreadyThere (client);
  12624. clientsChanged = true;
  12625. notify();
  12626. }
  12627. void TimeSliceThread::removeTimeSliceClient (TimeSliceClient* const client)
  12628. {
  12629. const ScopedLock sl1 (listLock);
  12630. clientsChanged = true;
  12631. // if there's a chance we're in the middle of calling this client, we need to
  12632. // also lock the outer lock..
  12633. if (clientBeingCalled == client)
  12634. {
  12635. const ScopedUnlock ul (listLock); // unlock first to get the order right..
  12636. const ScopedLock sl2 (callbackLock);
  12637. const ScopedLock sl3 (listLock);
  12638. clients.removeValue (client);
  12639. }
  12640. else
  12641. {
  12642. clients.removeValue (client);
  12643. }
  12644. }
  12645. int TimeSliceThread::getNumClients() const
  12646. {
  12647. return clients.size();
  12648. }
  12649. TimeSliceClient* TimeSliceThread::getClient (const int i) const
  12650. {
  12651. const ScopedLock sl (listLock);
  12652. return clients [i];
  12653. }
  12654. void TimeSliceThread::run()
  12655. {
  12656. int numCallsSinceBusy = 0;
  12657. while (! threadShouldExit())
  12658. {
  12659. int timeToWait = 500;
  12660. {
  12661. const ScopedLock sl (callbackLock);
  12662. {
  12663. const ScopedLock sl2 (listLock);
  12664. if (clients.size() > 0)
  12665. {
  12666. index = (index + 1) % clients.size();
  12667. clientBeingCalled = clients [index];
  12668. }
  12669. else
  12670. {
  12671. index = 0;
  12672. clientBeingCalled = 0;
  12673. }
  12674. if (clientsChanged)
  12675. {
  12676. clientsChanged = false;
  12677. numCallsSinceBusy = 0;
  12678. }
  12679. }
  12680. if (clientBeingCalled != 0)
  12681. {
  12682. if (clientBeingCalled->useTimeSlice())
  12683. numCallsSinceBusy = 0;
  12684. else
  12685. ++numCallsSinceBusy;
  12686. if (numCallsSinceBusy >= clients.size())
  12687. timeToWait = 500;
  12688. else if (index == 0)
  12689. timeToWait = 1; // throw in an occasional pause, to stop everything locking up
  12690. else
  12691. timeToWait = 0;
  12692. }
  12693. }
  12694. if (timeToWait > 0)
  12695. wait (timeToWait);
  12696. }
  12697. }
  12698. END_JUCE_NAMESPACE
  12699. /*** End of inlined file: juce_TimeSliceThread.cpp ***/
  12700. #endif
  12701. #if JUCE_BUILD_MISC
  12702. /*** Start of inlined file: juce_ValueTree.cpp ***/
  12703. BEGIN_JUCE_NAMESPACE
  12704. class ValueTree::SetPropertyAction : public UndoableAction
  12705. {
  12706. public:
  12707. SetPropertyAction (const SharedObjectPtr& target_, const var::identifier& name_,
  12708. const var& newValue_, const bool isAddingNewProperty_, const bool isDeletingProperty_)
  12709. : target (target_), name (name_), newValue (newValue_),
  12710. isAddingNewProperty (isAddingNewProperty_),
  12711. isDeletingProperty (isDeletingProperty_)
  12712. {
  12713. if (! isAddingNewProperty)
  12714. oldValue = target_->getProperty (name_);
  12715. }
  12716. ~SetPropertyAction() {}
  12717. bool perform()
  12718. {
  12719. jassert (! (isAddingNewProperty && target->hasProperty (name)));
  12720. if (isDeletingProperty)
  12721. target->removeProperty (name, 0);
  12722. else
  12723. target->setProperty (name, newValue, 0);
  12724. return true;
  12725. }
  12726. bool undo()
  12727. {
  12728. if (isAddingNewProperty)
  12729. target->removeProperty (name, 0);
  12730. else
  12731. target->setProperty (name, oldValue, 0);
  12732. return true;
  12733. }
  12734. int getSizeInUnits()
  12735. {
  12736. return (int) sizeof (*this); //xxx should be more accurate
  12737. }
  12738. private:
  12739. const SharedObjectPtr target;
  12740. const var::identifier name;
  12741. const var newValue;
  12742. var oldValue;
  12743. const bool isAddingNewProperty, isDeletingProperty;
  12744. SetPropertyAction (const SetPropertyAction&);
  12745. SetPropertyAction& operator= (const SetPropertyAction&);
  12746. };
  12747. class ValueTree::AddOrRemoveChildAction : public UndoableAction
  12748. {
  12749. public:
  12750. AddOrRemoveChildAction (const SharedObjectPtr& target_, const int childIndex_,
  12751. const SharedObjectPtr& newChild_)
  12752. : target (target_),
  12753. child (newChild_ != 0 ? newChild_ : target_->children [childIndex_]),
  12754. childIndex (childIndex_),
  12755. isDeleting (newChild_ == 0)
  12756. {
  12757. jassert (child != 0);
  12758. }
  12759. ~AddOrRemoveChildAction() {}
  12760. bool perform()
  12761. {
  12762. if (isDeleting)
  12763. target->removeChild (childIndex, 0);
  12764. else
  12765. target->addChild (child, childIndex, 0);
  12766. return true;
  12767. }
  12768. bool undo()
  12769. {
  12770. if (isDeleting)
  12771. {
  12772. target->addChild (child, childIndex, 0);
  12773. }
  12774. else
  12775. {
  12776. // If you hit this, it seems that your object's state is getting confused - probably
  12777. // because you've interleaved some undoable and non-undoable operations?
  12778. jassert (childIndex < target->children.size());
  12779. target->removeChild (childIndex, 0);
  12780. }
  12781. return true;
  12782. }
  12783. int getSizeInUnits()
  12784. {
  12785. return (int) sizeof (*this); //xxx should be more accurate
  12786. }
  12787. private:
  12788. const SharedObjectPtr target, child;
  12789. const int childIndex;
  12790. const bool isDeleting;
  12791. AddOrRemoveChildAction (const AddOrRemoveChildAction&);
  12792. AddOrRemoveChildAction& operator= (const AddOrRemoveChildAction&);
  12793. };
  12794. class ValueTree::MoveChildAction : public UndoableAction
  12795. {
  12796. public:
  12797. MoveChildAction (const SharedObjectPtr& target_,
  12798. const int startIndex_, const int endIndex_)
  12799. : target (target_),
  12800. startIndex (startIndex_),
  12801. endIndex (endIndex_)
  12802. {
  12803. }
  12804. ~MoveChildAction() {}
  12805. bool perform()
  12806. {
  12807. target->moveChild (startIndex, endIndex, 0);
  12808. return true;
  12809. }
  12810. bool undo()
  12811. {
  12812. target->moveChild (endIndex, startIndex, 0);
  12813. return true;
  12814. }
  12815. int getSizeInUnits()
  12816. {
  12817. return (int) sizeof (*this); //xxx should be more accurate
  12818. }
  12819. private:
  12820. const SharedObjectPtr target, child;
  12821. const int startIndex, endIndex;
  12822. MoveChildAction (const MoveChildAction&);
  12823. MoveChildAction& operator= (const MoveChildAction&);
  12824. };
  12825. ValueTree::SharedObject::SharedObject (const String& type_)
  12826. : type (type_), parent (0)
  12827. {
  12828. }
  12829. ValueTree::SharedObject::SharedObject (const SharedObject& other)
  12830. : type (other.type), properties (other.properties), parent (0)
  12831. {
  12832. for (int i = 0; i < other.children.size(); ++i)
  12833. {
  12834. SharedObject* const child = new SharedObject (*other.children.getUnchecked(i));
  12835. child->parent = this;
  12836. children.add (child);
  12837. }
  12838. }
  12839. ValueTree::SharedObject::~SharedObject()
  12840. {
  12841. jassert (parent == 0); // this should never happen unless something isn't obeying the ref-counting!
  12842. for (int i = children.size(); --i >= 0;)
  12843. {
  12844. const SharedObjectPtr c (children.getUnchecked(i));
  12845. c->parent = 0;
  12846. children.remove (i);
  12847. c->sendParentChangeMessage();
  12848. }
  12849. }
  12850. void ValueTree::SharedObject::sendPropertyChangeMessage (ValueTree& tree, const var::identifier& property)
  12851. {
  12852. for (int i = valueTreesWithListeners.size(); --i >= 0;)
  12853. {
  12854. ValueTree* const v = valueTreesWithListeners[i];
  12855. if (v != 0)
  12856. v->listeners.call (&ValueTree::Listener::valueTreePropertyChanged, tree, property);
  12857. }
  12858. }
  12859. void ValueTree::SharedObject::sendPropertyChangeMessage (const var::identifier& property)
  12860. {
  12861. ValueTree tree (this);
  12862. ValueTree::SharedObject* t = this;
  12863. while (t != 0)
  12864. {
  12865. t->sendPropertyChangeMessage (tree, property);
  12866. t = t->parent;
  12867. }
  12868. }
  12869. void ValueTree::SharedObject::sendChildChangeMessage (ValueTree& tree)
  12870. {
  12871. for (int i = valueTreesWithListeners.size(); --i >= 0;)
  12872. {
  12873. ValueTree* const v = valueTreesWithListeners[i];
  12874. if (v != 0)
  12875. v->listeners.call (&ValueTree::Listener::valueTreeChildrenChanged, tree);
  12876. }
  12877. }
  12878. void ValueTree::SharedObject::sendChildChangeMessage()
  12879. {
  12880. ValueTree tree (this);
  12881. ValueTree::SharedObject* t = this;
  12882. while (t != 0)
  12883. {
  12884. t->sendChildChangeMessage (tree);
  12885. t = t->parent;
  12886. }
  12887. }
  12888. void ValueTree::SharedObject::sendParentChangeMessage()
  12889. {
  12890. ValueTree tree (this);
  12891. int i;
  12892. for (i = children.size(); --i >= 0;)
  12893. {
  12894. SharedObject* const t = children[i];
  12895. if (t != 0)
  12896. t->sendParentChangeMessage();
  12897. }
  12898. for (i = valueTreesWithListeners.size(); --i >= 0;)
  12899. {
  12900. ValueTree* const v = valueTreesWithListeners[i];
  12901. if (v != 0)
  12902. v->listeners.call (&ValueTree::Listener::valueTreeParentChanged, tree);
  12903. }
  12904. }
  12905. const var& ValueTree::SharedObject::getProperty (const var::identifier& name) const
  12906. {
  12907. return properties [name];
  12908. }
  12909. const var ValueTree::SharedObject::getProperty (const var::identifier& name, const var& defaultReturnValue) const
  12910. {
  12911. return properties.getWithDefault (name, defaultReturnValue);
  12912. }
  12913. void ValueTree::SharedObject::setProperty (const var::identifier& name, const var& newValue, UndoManager* const undoManager)
  12914. {
  12915. if (undoManager == 0)
  12916. {
  12917. if (properties.set (name, newValue))
  12918. sendPropertyChangeMessage (name);
  12919. }
  12920. else
  12921. {
  12922. var* const existingValue = properties.getItem (name);
  12923. if (existingValue != 0)
  12924. {
  12925. if (*existingValue != newValue)
  12926. undoManager->perform (new SetPropertyAction (this, name, newValue, false, false));
  12927. }
  12928. else
  12929. {
  12930. undoManager->perform (new SetPropertyAction (this, name, newValue, true, false));
  12931. }
  12932. }
  12933. }
  12934. bool ValueTree::SharedObject::hasProperty (const var::identifier& name) const
  12935. {
  12936. return properties.contains (name);
  12937. }
  12938. void ValueTree::SharedObject::removeProperty (const var::identifier& name, UndoManager* const undoManager)
  12939. {
  12940. if (undoManager == 0)
  12941. {
  12942. if (properties.remove (name))
  12943. sendPropertyChangeMessage (name);
  12944. }
  12945. else
  12946. {
  12947. if (properties.contains (name))
  12948. undoManager->perform (new SetPropertyAction (this, name, var::null, false, true));
  12949. }
  12950. }
  12951. void ValueTree::SharedObject::removeAllProperties (UndoManager* const undoManager)
  12952. {
  12953. if (undoManager == 0)
  12954. {
  12955. while (properties.size() > 0)
  12956. {
  12957. const var::identifier name (properties.getName (properties.size() - 1));
  12958. properties.remove (name);
  12959. sendPropertyChangeMessage (name);
  12960. }
  12961. }
  12962. else
  12963. {
  12964. for (int i = properties.size(); --i >= 0;)
  12965. undoManager->perform (new SetPropertyAction (this, properties.getName(i), var::null, false, true));
  12966. }
  12967. }
  12968. ValueTree ValueTree::SharedObject::getChildWithName (const String& typeToMatch) const
  12969. {
  12970. for (int i = 0; i < children.size(); ++i)
  12971. if (children.getUnchecked(i)->type == typeToMatch)
  12972. return ValueTree (static_cast <SharedObject*> (children.getUnchecked(i)));
  12973. return ValueTree::invalid;
  12974. }
  12975. ValueTree ValueTree::SharedObject::getChildWithProperty (const var::identifier& propertyName, const var& propertyValue) const
  12976. {
  12977. for (int i = 0; i < children.size(); ++i)
  12978. if (children.getUnchecked(i)->getProperty (propertyName) == propertyValue)
  12979. return ValueTree (static_cast <SharedObject*> (children.getUnchecked(i)));
  12980. return ValueTree::invalid;
  12981. }
  12982. bool ValueTree::SharedObject::isAChildOf (const SharedObject* const possibleParent) const
  12983. {
  12984. const SharedObject* p = parent;
  12985. while (p != 0)
  12986. {
  12987. if (p == possibleParent)
  12988. return true;
  12989. p = p->parent;
  12990. }
  12991. return false;
  12992. }
  12993. int ValueTree::SharedObject::indexOf (const ValueTree& child) const
  12994. {
  12995. return children.indexOf (child.object);
  12996. }
  12997. void ValueTree::SharedObject::addChild (SharedObject* child, int index, UndoManager* const undoManager)
  12998. {
  12999. if (child != 0 && child->parent != this)
  13000. {
  13001. if (child != this && ! isAChildOf (child))
  13002. {
  13003. // You should always make sure that a child is removed from its previous parent before
  13004. // adding it somewhere else - otherwise, it's ambiguous as to whether a different
  13005. // undomanager should be used when removing it from its current parent..
  13006. jassert (child->parent == 0);
  13007. if (child->parent != 0)
  13008. {
  13009. jassert (child->parent->children.indexOf (child) >= 0);
  13010. child->parent->removeChild (child->parent->children.indexOf (child), undoManager);
  13011. }
  13012. if (undoManager == 0)
  13013. {
  13014. children.insert (index, child);
  13015. child->parent = this;
  13016. sendChildChangeMessage();
  13017. child->sendParentChangeMessage();
  13018. }
  13019. else
  13020. {
  13021. if (index < 0)
  13022. index = children.size();
  13023. undoManager->perform (new AddOrRemoveChildAction (this, index, child));
  13024. }
  13025. }
  13026. else
  13027. {
  13028. // You're attempting to create a recursive loop! A node
  13029. // can't be a child of one of its own children!
  13030. jassertfalse
  13031. }
  13032. }
  13033. }
  13034. void ValueTree::SharedObject::removeChild (const int childIndex, UndoManager* const undoManager)
  13035. {
  13036. const SharedObjectPtr child (children [childIndex]);
  13037. if (child != 0)
  13038. {
  13039. if (undoManager == 0)
  13040. {
  13041. children.remove (childIndex);
  13042. child->parent = 0;
  13043. sendChildChangeMessage();
  13044. child->sendParentChangeMessage();
  13045. }
  13046. else
  13047. {
  13048. undoManager->perform (new AddOrRemoveChildAction (this, childIndex, 0));
  13049. }
  13050. }
  13051. }
  13052. void ValueTree::SharedObject::removeAllChildren (UndoManager* const undoManager)
  13053. {
  13054. while (children.size() > 0)
  13055. removeChild (children.size() - 1, undoManager);
  13056. }
  13057. void ValueTree::SharedObject::moveChild (int currentIndex, int newIndex, UndoManager* undoManager)
  13058. {
  13059. // The source index must be a valid index!
  13060. jassert (((unsigned int) currentIndex) < (unsigned int) children.size());
  13061. if (currentIndex != newIndex
  13062. && ((unsigned int) currentIndex) < (unsigned int) children.size())
  13063. {
  13064. if (undoManager == 0)
  13065. {
  13066. children.move (currentIndex, newIndex);
  13067. sendChildChangeMessage();
  13068. }
  13069. else
  13070. {
  13071. if (((unsigned int) newIndex) >= (unsigned int) children.size())
  13072. newIndex = children.size() - 1;
  13073. undoManager->perform (new MoveChildAction (this, currentIndex, newIndex));
  13074. }
  13075. }
  13076. }
  13077. ValueTree::ValueTree() throw()
  13078. : object (0)
  13079. {
  13080. }
  13081. const ValueTree ValueTree::invalid;
  13082. ValueTree::ValueTree (const String& type_)
  13083. : object (new ValueTree::SharedObject (type_))
  13084. {
  13085. jassert (type_.isNotEmpty()); // All objects should be given a sensible type name!
  13086. }
  13087. ValueTree::ValueTree (SharedObject* const object_)
  13088. : object (object_)
  13089. {
  13090. }
  13091. ValueTree::ValueTree (const ValueTree& other)
  13092. : object (other.object)
  13093. {
  13094. }
  13095. ValueTree& ValueTree::operator= (const ValueTree& other)
  13096. {
  13097. if (listeners.size() > 0)
  13098. {
  13099. if (object != 0)
  13100. object->valueTreesWithListeners.removeValue (this);
  13101. if (other.object != 0)
  13102. other.object->valueTreesWithListeners.add (this);
  13103. }
  13104. object = other.object;
  13105. return *this;
  13106. }
  13107. ValueTree::~ValueTree()
  13108. {
  13109. if (listeners.size() > 0 && object != 0)
  13110. object->valueTreesWithListeners.removeValue (this);
  13111. }
  13112. bool ValueTree::operator== (const ValueTree& other) const
  13113. {
  13114. return object == other.object;
  13115. }
  13116. bool ValueTree::operator!= (const ValueTree& other) const
  13117. {
  13118. return object != other.object;
  13119. }
  13120. ValueTree ValueTree::createCopy() const
  13121. {
  13122. return ValueTree (object != 0 ? new SharedObject (*object) : 0);
  13123. }
  13124. bool ValueTree::hasType (const String& typeName) const
  13125. {
  13126. return object != 0 && object->type == typeName;
  13127. }
  13128. const String ValueTree::getType() const
  13129. {
  13130. return object != 0 ? object->type : String::empty;
  13131. }
  13132. ValueTree ValueTree::getParent() const
  13133. {
  13134. return ValueTree (object != 0 ? object->parent : (SharedObject*) 0);
  13135. }
  13136. const var& ValueTree::operator[] (const var::identifier& name) const
  13137. {
  13138. return object == 0 ? var::null : object->getProperty (name);
  13139. }
  13140. const var& ValueTree::getProperty (const var::identifier& name) const
  13141. {
  13142. return object == 0 ? var::null : object->getProperty (name);
  13143. }
  13144. const var ValueTree::getProperty (const var::identifier& name, const var& defaultReturnValue) const
  13145. {
  13146. return object == 0 ? defaultReturnValue : object->getProperty (name, defaultReturnValue);
  13147. }
  13148. void ValueTree::setProperty (const var::identifier& name, const var& newValue, UndoManager* const undoManager)
  13149. {
  13150. jassert (name.name.isNotEmpty());
  13151. if (object != 0 && name.name.isNotEmpty())
  13152. object->setProperty (name, newValue, undoManager);
  13153. }
  13154. bool ValueTree::hasProperty (const var::identifier& name) const
  13155. {
  13156. return object != 0 && object->hasProperty (name);
  13157. }
  13158. void ValueTree::removeProperty (const var::identifier& name, UndoManager* const undoManager)
  13159. {
  13160. if (object != 0)
  13161. object->removeProperty (name, undoManager);
  13162. }
  13163. void ValueTree::removeAllProperties (UndoManager* const undoManager)
  13164. {
  13165. if (object != 0)
  13166. object->removeAllProperties (undoManager);
  13167. }
  13168. int ValueTree::getNumProperties() const
  13169. {
  13170. return object == 0 ? 0 : object->properties.size();
  13171. }
  13172. const var::identifier ValueTree::getPropertyName (const int index) const
  13173. {
  13174. return object == 0 ? var::identifier()
  13175. : object->properties.getName (index);
  13176. }
  13177. class ValueTreePropertyValueSource : public Value::ValueSource,
  13178. public ValueTree::Listener
  13179. {
  13180. public:
  13181. ValueTreePropertyValueSource (const ValueTree& tree_,
  13182. const var::identifier& property_,
  13183. UndoManager* const undoManager_)
  13184. : tree (tree_),
  13185. property (property_),
  13186. undoManager (undoManager_)
  13187. {
  13188. tree.addListener (this);
  13189. }
  13190. ~ValueTreePropertyValueSource()
  13191. {
  13192. tree.removeListener (this);
  13193. }
  13194. const var getValue() const
  13195. {
  13196. return tree [property];
  13197. }
  13198. void setValue (const var& newValue)
  13199. {
  13200. tree.setProperty (property, newValue, undoManager);
  13201. }
  13202. void valueTreePropertyChanged (ValueTree& treeWhosePropertyHasChanged, const var::identifier& changedProperty)
  13203. {
  13204. if (tree == treeWhosePropertyHasChanged && property == changedProperty)
  13205. sendChangeMessage (false);
  13206. }
  13207. void valueTreeChildrenChanged (ValueTree&) {}
  13208. void valueTreeParentChanged (ValueTree&) {}
  13209. private:
  13210. ValueTree tree;
  13211. const var::identifier property;
  13212. UndoManager* const undoManager;
  13213. ValueTreePropertyValueSource& operator= (const ValueTreePropertyValueSource&);
  13214. };
  13215. Value ValueTree::getPropertyAsValue (const var::identifier& name, UndoManager* const undoManager) const
  13216. {
  13217. return Value (new ValueTreePropertyValueSource (*this, name, undoManager));
  13218. }
  13219. int ValueTree::getNumChildren() const
  13220. {
  13221. return object == 0 ? 0 : object->children.size();
  13222. }
  13223. ValueTree ValueTree::getChild (int index) const
  13224. {
  13225. return ValueTree (object != 0 ? (SharedObject*) object->children [index] : (SharedObject*) 0);
  13226. }
  13227. ValueTree ValueTree::getChildWithName (const String& type) const
  13228. {
  13229. return object != 0 ? object->getChildWithName (type) : ValueTree::invalid;
  13230. }
  13231. ValueTree ValueTree::getChildWithProperty (const var::identifier& propertyName, const var& propertyValue) const
  13232. {
  13233. return object != 0 ? object->getChildWithProperty (propertyName, propertyValue) : ValueTree::invalid;
  13234. }
  13235. bool ValueTree::isAChildOf (const ValueTree& possibleParent) const
  13236. {
  13237. return object != 0 && object->isAChildOf (possibleParent.object);
  13238. }
  13239. int ValueTree::indexOf (const ValueTree& child) const
  13240. {
  13241. return object != 0 ? object->indexOf (child) : -1;
  13242. }
  13243. void ValueTree::addChild (ValueTree child, int index, UndoManager* const undoManager)
  13244. {
  13245. if (object != 0)
  13246. object->addChild (child.object, index, undoManager);
  13247. }
  13248. void ValueTree::removeChild (const int childIndex, UndoManager* const undoManager)
  13249. {
  13250. if (object != 0)
  13251. object->removeChild (childIndex, undoManager);
  13252. }
  13253. void ValueTree::removeChild (const ValueTree& child, UndoManager* const undoManager)
  13254. {
  13255. if (object != 0)
  13256. object->removeChild (object->children.indexOf (child.object), undoManager);
  13257. }
  13258. void ValueTree::removeAllChildren (UndoManager* const undoManager)
  13259. {
  13260. if (object != 0)
  13261. object->removeAllChildren (undoManager);
  13262. }
  13263. void ValueTree::moveChild (int currentIndex, int newIndex, UndoManager* undoManager)
  13264. {
  13265. if (object != 0)
  13266. object->moveChild (currentIndex, newIndex, undoManager);
  13267. }
  13268. void ValueTree::addListener (Listener* listener)
  13269. {
  13270. if (listener != 0)
  13271. {
  13272. if (listeners.size() == 0 && object != 0)
  13273. object->valueTreesWithListeners.add (this);
  13274. listeners.add (listener);
  13275. }
  13276. }
  13277. void ValueTree::removeListener (Listener* listener)
  13278. {
  13279. listeners.remove (listener);
  13280. if (listeners.size() == 0 && object != 0)
  13281. object->valueTreesWithListeners.removeValue (this);
  13282. }
  13283. XmlElement* ValueTree::SharedObject::createXml() const
  13284. {
  13285. XmlElement* xml = new XmlElement (type);
  13286. int i;
  13287. for (i = 0; i < properties.size(); ++i)
  13288. {
  13289. var::identifier name (properties.getName(i));
  13290. const var& v = properties [name];
  13291. jassert (! v.isObject()); // DynamicObjects can't be stored as XML!
  13292. xml->setAttribute (name.name, v.toString());
  13293. }
  13294. for (i = 0; i < children.size(); ++i)
  13295. xml->addChildElement (children.getUnchecked(i)->createXml());
  13296. return xml;
  13297. }
  13298. XmlElement* ValueTree::createXml() const
  13299. {
  13300. return object != 0 ? object->createXml() : 0;
  13301. }
  13302. ValueTree ValueTree::fromXml (const XmlElement& xml)
  13303. {
  13304. ValueTree v (xml.getTagName());
  13305. const int numAtts = xml.getNumAttributes(); // xxx inefficient - should write an att iterator..
  13306. for (int i = 0; i < numAtts; ++i)
  13307. v.setProperty (xml.getAttributeName (i), var (xml.getAttributeValue (i)), 0);
  13308. forEachXmlChildElement (xml, e)
  13309. {
  13310. v.addChild (fromXml (*e), -1, 0);
  13311. }
  13312. return v;
  13313. }
  13314. void ValueTree::writeToStream (OutputStream& output)
  13315. {
  13316. output.writeString (getType());
  13317. const int numProps = getNumProperties();
  13318. output.writeCompressedInt (numProps);
  13319. int i;
  13320. for (i = 0; i < numProps; ++i)
  13321. {
  13322. const var::identifier name (getPropertyName(i));
  13323. output.writeString (name.name);
  13324. getProperty(name).writeToStream (output);
  13325. }
  13326. const int numChildren = getNumChildren();
  13327. output.writeCompressedInt (numChildren);
  13328. for (i = 0; i < numChildren; ++i)
  13329. getChild (i).writeToStream (output);
  13330. }
  13331. ValueTree ValueTree::readFromStream (InputStream& input)
  13332. {
  13333. const String type (input.readString());
  13334. if (type.isEmpty())
  13335. return ValueTree::invalid;
  13336. ValueTree v (type);
  13337. const int numProps = input.readCompressedInt();
  13338. if (numProps < 0)
  13339. {
  13340. jassertfalse // trying to read corrupted data!
  13341. return v;
  13342. }
  13343. int i;
  13344. for (i = 0; i < numProps; ++i)
  13345. {
  13346. const String name (input.readString());
  13347. jassert (name.isNotEmpty());
  13348. const var value (var::readFromStream (input));
  13349. v.setProperty (name, value, 0);
  13350. }
  13351. const int numChildren = input.readCompressedInt();
  13352. for (i = 0; i < numChildren; ++i)
  13353. v.addChild (readFromStream (input), -1, 0);
  13354. return v;
  13355. }
  13356. END_JUCE_NAMESPACE
  13357. /*** End of inlined file: juce_ValueTree.cpp ***/
  13358. /*** Start of inlined file: juce_Value.cpp ***/
  13359. BEGIN_JUCE_NAMESPACE
  13360. Value::ValueSource::ValueSource()
  13361. {
  13362. }
  13363. Value::ValueSource::~ValueSource()
  13364. {
  13365. }
  13366. void Value::ValueSource::sendChangeMessage (const bool synchronous)
  13367. {
  13368. if (synchronous)
  13369. {
  13370. for (int i = valuesWithListeners.size(); --i >= 0;)
  13371. {
  13372. Value* const v = valuesWithListeners[i];
  13373. if (v != 0)
  13374. v->callListeners();
  13375. }
  13376. }
  13377. else
  13378. {
  13379. triggerAsyncUpdate();
  13380. }
  13381. }
  13382. void Value::ValueSource::handleAsyncUpdate()
  13383. {
  13384. sendChangeMessage (true);
  13385. }
  13386. class SimpleValueSource : public Value::ValueSource
  13387. {
  13388. public:
  13389. SimpleValueSource()
  13390. {
  13391. }
  13392. SimpleValueSource (const var& initialValue)
  13393. : value (initialValue)
  13394. {
  13395. }
  13396. ~SimpleValueSource()
  13397. {
  13398. }
  13399. const var getValue() const
  13400. {
  13401. return value;
  13402. }
  13403. void setValue (const var& newValue)
  13404. {
  13405. if (newValue != value)
  13406. {
  13407. value = newValue;
  13408. sendChangeMessage (false);
  13409. }
  13410. }
  13411. private:
  13412. var value;
  13413. SimpleValueSource (const SimpleValueSource&);
  13414. SimpleValueSource& operator= (const SimpleValueSource&);
  13415. };
  13416. Value::Value()
  13417. : value (new SimpleValueSource())
  13418. {
  13419. }
  13420. Value::Value (ValueSource* const value_)
  13421. : value (value_)
  13422. {
  13423. jassert (value_ != 0);
  13424. }
  13425. Value::Value (const var& initialValue)
  13426. : value (new SimpleValueSource (initialValue))
  13427. {
  13428. }
  13429. Value::Value (const Value& other)
  13430. : value (other.value)
  13431. {
  13432. }
  13433. Value& Value::operator= (const Value& other)
  13434. {
  13435. value = other.value;
  13436. return *this;
  13437. }
  13438. Value::~Value()
  13439. {
  13440. if (listeners.size() > 0)
  13441. value->valuesWithListeners.removeValue (this);
  13442. }
  13443. const var Value::getValue() const
  13444. {
  13445. return value->getValue();
  13446. }
  13447. Value::operator const var() const
  13448. {
  13449. return getValue();
  13450. }
  13451. void Value::setValue (const var& newValue)
  13452. {
  13453. value->setValue (newValue);
  13454. }
  13455. const String Value::toString() const
  13456. {
  13457. return value->getValue().toString();
  13458. }
  13459. Value& Value::operator= (const var& newValue)
  13460. {
  13461. value->setValue (newValue);
  13462. return *this;
  13463. }
  13464. void Value::referTo (const Value& valueToReferTo)
  13465. {
  13466. if (valueToReferTo.value != value)
  13467. {
  13468. if (listeners.size() > 0)
  13469. {
  13470. value->valuesWithListeners.removeValue (this);
  13471. valueToReferTo.value->valuesWithListeners.add (this);
  13472. }
  13473. value = valueToReferTo.value;
  13474. callListeners();
  13475. }
  13476. }
  13477. bool Value::refersToSameSourceAs (const Value& other) const
  13478. {
  13479. return value == other.value;
  13480. }
  13481. bool Value::operator== (const Value& other) const
  13482. {
  13483. return value == other.value || value->getValue() == other.getValue();
  13484. }
  13485. bool Value::operator!= (const Value& other) const
  13486. {
  13487. return value != other.value && value->getValue() != other.getValue();
  13488. }
  13489. void Value::addListener (Listener* const listener)
  13490. {
  13491. if (listener != 0)
  13492. {
  13493. if (listeners.size() == 0)
  13494. value->valuesWithListeners.add (this);
  13495. listeners.add (listener);
  13496. }
  13497. }
  13498. void Value::removeListener (Listener* const listener)
  13499. {
  13500. listeners.remove (listener);
  13501. if (listeners.size() == 0)
  13502. value->valuesWithListeners.removeValue (this);
  13503. }
  13504. void Value::callListeners()
  13505. {
  13506. Value v (*this); // (create a copy in case this gets deleted by a callback)
  13507. listeners.call (&Listener::valueChanged, v);
  13508. }
  13509. OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, const Value& value)
  13510. {
  13511. return stream << value.toString();
  13512. }
  13513. END_JUCE_NAMESPACE
  13514. /*** End of inlined file: juce_Value.cpp ***/
  13515. /*** Start of inlined file: juce_Application.cpp ***/
  13516. #if JUCE_MSVC
  13517. #pragma warning (push)
  13518. #pragma warning (disable: 4245 4514 4100)
  13519. #include <crtdbg.h>
  13520. #pragma warning (pop)
  13521. #endif
  13522. BEGIN_JUCE_NAMESPACE
  13523. void juce_setCurrentThreadName (const String& name);
  13524. static JUCEApplication* appInstance = 0;
  13525. JUCEApplication::JUCEApplication()
  13526. : appReturnValue (0),
  13527. stillInitialising (true)
  13528. {
  13529. }
  13530. JUCEApplication::~JUCEApplication()
  13531. {
  13532. if (appLock != 0)
  13533. {
  13534. appLock->exit();
  13535. appLock = 0;
  13536. }
  13537. }
  13538. JUCEApplication* JUCEApplication::getInstance() throw()
  13539. {
  13540. return appInstance;
  13541. }
  13542. bool JUCEApplication::isInitialising() const throw()
  13543. {
  13544. return stillInitialising;
  13545. }
  13546. const String JUCEApplication::getApplicationVersion()
  13547. {
  13548. return String::empty;
  13549. }
  13550. bool JUCEApplication::moreThanOneInstanceAllowed()
  13551. {
  13552. return true;
  13553. }
  13554. void JUCEApplication::anotherInstanceStarted (const String&)
  13555. {
  13556. }
  13557. void JUCEApplication::systemRequestedQuit()
  13558. {
  13559. quit();
  13560. }
  13561. void JUCEApplication::quit()
  13562. {
  13563. MessageManager::getInstance()->stopDispatchLoop();
  13564. }
  13565. void JUCEApplication::setApplicationReturnValue (const int newReturnValue) throw()
  13566. {
  13567. appReturnValue = newReturnValue;
  13568. }
  13569. void JUCEApplication::unhandledException (const std::exception*,
  13570. const String&,
  13571. const int)
  13572. {
  13573. jassertfalse
  13574. }
  13575. void JUCEApplication::sendUnhandledException (const std::exception* const e,
  13576. const char* const sourceFile,
  13577. const int lineNumber)
  13578. {
  13579. if (appInstance != 0)
  13580. appInstance->unhandledException (e, sourceFile, lineNumber);
  13581. }
  13582. ApplicationCommandTarget* JUCEApplication::getNextCommandTarget()
  13583. {
  13584. return 0;
  13585. }
  13586. void JUCEApplication::getAllCommands (Array <CommandID>& commands)
  13587. {
  13588. commands.add (StandardApplicationCommandIDs::quit);
  13589. }
  13590. void JUCEApplication::getCommandInfo (const CommandID commandID, ApplicationCommandInfo& result)
  13591. {
  13592. if (commandID == StandardApplicationCommandIDs::quit)
  13593. {
  13594. result.setInfo (TRANS("Quit"),
  13595. TRANS("Quits the application"),
  13596. "Application",
  13597. 0);
  13598. result.defaultKeypresses.add (KeyPress ('q', ModifierKeys::commandModifier, 0));
  13599. }
  13600. }
  13601. bool JUCEApplication::perform (const InvocationInfo& info)
  13602. {
  13603. if (info.commandID == StandardApplicationCommandIDs::quit)
  13604. {
  13605. systemRequestedQuit();
  13606. return true;
  13607. }
  13608. return false;
  13609. }
  13610. int JUCEApplication::main (String& commandLine, JUCEApplication* const app)
  13611. {
  13612. if (! app->initialiseApp (commandLine))
  13613. return 0;
  13614. // now loop until a quit message is received..
  13615. JUCE_TRY
  13616. {
  13617. MessageManager::getInstance()->runDispatchLoop();
  13618. }
  13619. #if JUCE_CATCH_UNHANDLED_EXCEPTIONS
  13620. catch (const std::exception& e)
  13621. {
  13622. app->unhandledException (&e, __FILE__, __LINE__);
  13623. }
  13624. catch (...)
  13625. {
  13626. app->unhandledException (0, __FILE__, __LINE__);
  13627. }
  13628. #endif
  13629. return shutdownAppAndClearUp();
  13630. }
  13631. bool JUCEApplication::initialiseApp (String& commandLine)
  13632. {
  13633. jassert (appInstance == 0);
  13634. appInstance = this;
  13635. commandLineParameters = commandLine.trim();
  13636. commandLine = String::empty;
  13637. initialiseJuce_GUI();
  13638. #if ! JUCE_IPHONE
  13639. jassert (appLock == 0); // initialiseApp must only be called once!
  13640. if (! moreThanOneInstanceAllowed())
  13641. {
  13642. appLock = new InterProcessLock ("juceAppLock_" + getApplicationName());
  13643. if (! appLock->enter(0))
  13644. {
  13645. MessageManager::broadcastMessage (getApplicationName() + "/" + commandLineParameters);
  13646. delete appInstance;
  13647. appInstance = 0;
  13648. DBG ("Another instance is running - quitting...");
  13649. return false;
  13650. }
  13651. }
  13652. #endif
  13653. // let the app do its setting-up..
  13654. initialise (commandLineParameters);
  13655. // register for broadcast new app messages
  13656. MessageManager::getInstance()->registerBroadcastListener (this);
  13657. stillInitialising = false;
  13658. return true;
  13659. }
  13660. int JUCEApplication::shutdownAppAndClearUp()
  13661. {
  13662. jassert (appInstance != 0);
  13663. ScopedPointer<JUCEApplication> app (appInstance);
  13664. int returnValue = 0;
  13665. MessageManager::getInstance()->deregisterBroadcastListener (static_cast <JUCEApplication*> (app));
  13666. static bool reentrancyCheck = false;
  13667. if (! reentrancyCheck)
  13668. {
  13669. reentrancyCheck = true;
  13670. JUCE_TRY
  13671. {
  13672. // give the app a chance to clean up..
  13673. app->shutdown();
  13674. }
  13675. #if JUCE_CATCH_UNHANDLED_EXCEPTIONS
  13676. catch (const std::exception& e)
  13677. {
  13678. app->unhandledException (&e, __FILE__, __LINE__);
  13679. }
  13680. catch (...)
  13681. {
  13682. app->unhandledException (0, __FILE__, __LINE__);
  13683. }
  13684. #endif
  13685. JUCE_TRY
  13686. {
  13687. shutdownJuce_GUI();
  13688. returnValue = app->getApplicationReturnValue();
  13689. appInstance = 0;
  13690. app = 0;
  13691. }
  13692. JUCE_CATCH_ALL_ASSERT
  13693. reentrancyCheck = false;
  13694. }
  13695. return returnValue;
  13696. }
  13697. #if JUCE_IPHONE
  13698. extern int juce_IPhoneMain (int argc, const char* argv[], JUCEApplication* app);
  13699. #endif
  13700. #if ! JUCE_WINDOWS
  13701. extern const char* juce_Argv0;
  13702. #endif
  13703. int JUCEApplication::main (int argc, const char* argv[], JUCEApplication* const newApp)
  13704. {
  13705. #if ! JUCE_WINDOWS
  13706. juce_Argv0 = argv[0];
  13707. #endif
  13708. #if JUCE_IPHONE
  13709. const ScopedAutoReleasePool pool;
  13710. return juce_IPhoneMain (argc, argv, newApp);
  13711. #else
  13712. #if JUCE_MAC
  13713. const ScopedAutoReleasePool pool;
  13714. #endif
  13715. String cmd;
  13716. for (int i = 1; i < argc; ++i)
  13717. cmd << argv[i] << ' ';
  13718. return JUCEApplication::main (cmd, newApp);
  13719. #endif
  13720. }
  13721. void JUCEApplication::actionListenerCallback (const String& message)
  13722. {
  13723. if (message.startsWith (getApplicationName() + "/"))
  13724. anotherInstanceStarted (message.substring (getApplicationName().length() + 1));
  13725. }
  13726. static bool juceInitialisedGUI = false;
  13727. void JUCE_PUBLIC_FUNCTION initialiseJuce_GUI()
  13728. {
  13729. if (! juceInitialisedGUI)
  13730. {
  13731. #if JUCE_MAC || JUCE_IPHONE
  13732. const ScopedAutoReleasePool pool;
  13733. #endif
  13734. juceInitialisedGUI = true;
  13735. initialiseJuce_NonGUI();
  13736. MessageManager::getInstance();
  13737. LookAndFeel::setDefaultLookAndFeel (0);
  13738. juce_setCurrentThreadName ("Juce Message Thread");
  13739. #if JUCE_WINDOWS && JUCE_DEBUG
  13740. // This section is just for catching people who mess up their project settings and
  13741. // turn RTTI off..
  13742. try
  13743. {
  13744. TextButton tb (String::empty);
  13745. Component* c = &tb;
  13746. // Got an exception here? Then TURN ON RTTI in your compiler settings!!
  13747. c = dynamic_cast <Button*> (c);
  13748. }
  13749. catch (...)
  13750. {
  13751. // Ended up here? If so, TURN ON RTTI in your compiler settings!! And if you
  13752. // got as far as this catch statement, then why haven't you got exception catching
  13753. // turned on in the debugger???
  13754. jassertfalse
  13755. }
  13756. #endif
  13757. }
  13758. }
  13759. void JUCE_PUBLIC_FUNCTION shutdownJuce_GUI()
  13760. {
  13761. if (juceInitialisedGUI)
  13762. {
  13763. #if JUCE_MAC
  13764. const ScopedAutoReleasePool pool;
  13765. #endif
  13766. {
  13767. DeletedAtShutdown::deleteAll();
  13768. LookAndFeel::clearDefaultLookAndFeel();
  13769. }
  13770. delete MessageManager::getInstance();
  13771. shutdownJuce_NonGUI();
  13772. juceInitialisedGUI = false;
  13773. }
  13774. }
  13775. END_JUCE_NAMESPACE
  13776. /*** End of inlined file: juce_Application.cpp ***/
  13777. /*** Start of inlined file: juce_ApplicationCommandInfo.cpp ***/
  13778. BEGIN_JUCE_NAMESPACE
  13779. ApplicationCommandInfo::ApplicationCommandInfo (const CommandID commandID_) throw()
  13780. : commandID (commandID_),
  13781. flags (0)
  13782. {
  13783. }
  13784. void ApplicationCommandInfo::setInfo (const String& shortName_,
  13785. const String& description_,
  13786. const String& categoryName_,
  13787. const int flags_) throw()
  13788. {
  13789. shortName = shortName_;
  13790. description = description_;
  13791. categoryName = categoryName_;
  13792. flags = flags_;
  13793. }
  13794. void ApplicationCommandInfo::setActive (const bool b) throw()
  13795. {
  13796. if (b)
  13797. flags &= ~isDisabled;
  13798. else
  13799. flags |= isDisabled;
  13800. }
  13801. void ApplicationCommandInfo::setTicked (const bool b) throw()
  13802. {
  13803. if (b)
  13804. flags |= isTicked;
  13805. else
  13806. flags &= ~isTicked;
  13807. }
  13808. void ApplicationCommandInfo::addDefaultKeypress (const int keyCode, const ModifierKeys& modifiers) throw()
  13809. {
  13810. defaultKeypresses.add (KeyPress (keyCode, modifiers, 0));
  13811. }
  13812. END_JUCE_NAMESPACE
  13813. /*** End of inlined file: juce_ApplicationCommandInfo.cpp ***/
  13814. /*** Start of inlined file: juce_ApplicationCommandManager.cpp ***/
  13815. BEGIN_JUCE_NAMESPACE
  13816. ApplicationCommandManager::ApplicationCommandManager()
  13817. : firstTarget (0)
  13818. {
  13819. keyMappings = new KeyPressMappingSet (this);
  13820. Desktop::getInstance().addFocusChangeListener (this);
  13821. }
  13822. ApplicationCommandManager::~ApplicationCommandManager()
  13823. {
  13824. Desktop::getInstance().removeFocusChangeListener (this);
  13825. keyMappings = 0;
  13826. }
  13827. void ApplicationCommandManager::clearCommands()
  13828. {
  13829. commands.clear();
  13830. keyMappings->clearAllKeyPresses();
  13831. triggerAsyncUpdate();
  13832. }
  13833. void ApplicationCommandManager::registerCommand (const ApplicationCommandInfo& newCommand)
  13834. {
  13835. // zero isn't a valid command ID!
  13836. jassert (newCommand.commandID != 0);
  13837. // the name isn't optional!
  13838. jassert (newCommand.shortName.isNotEmpty());
  13839. if (getCommandForID (newCommand.commandID) == 0)
  13840. {
  13841. ApplicationCommandInfo* const newInfo = new ApplicationCommandInfo (newCommand);
  13842. newInfo->flags &= ~ApplicationCommandInfo::isTicked;
  13843. commands.add (newInfo);
  13844. keyMappings->resetToDefaultMapping (newCommand.commandID);
  13845. triggerAsyncUpdate();
  13846. }
  13847. else
  13848. {
  13849. // trying to re-register the same command with different parameters?
  13850. jassert (newCommand.shortName == getCommandForID (newCommand.commandID)->shortName
  13851. && (newCommand.description == getCommandForID (newCommand.commandID)->description || newCommand.description.isEmpty())
  13852. && newCommand.categoryName == getCommandForID (newCommand.commandID)->categoryName
  13853. && newCommand.defaultKeypresses == getCommandForID (newCommand.commandID)->defaultKeypresses
  13854. && (newCommand.flags & (ApplicationCommandInfo::wantsKeyUpDownCallbacks | ApplicationCommandInfo::hiddenFromKeyEditor | ApplicationCommandInfo::readOnlyInKeyEditor))
  13855. == (getCommandForID (newCommand.commandID)->flags & (ApplicationCommandInfo::wantsKeyUpDownCallbacks | ApplicationCommandInfo::hiddenFromKeyEditor | ApplicationCommandInfo::readOnlyInKeyEditor)));
  13856. }
  13857. }
  13858. void ApplicationCommandManager::registerAllCommandsForTarget (ApplicationCommandTarget* target)
  13859. {
  13860. if (target != 0)
  13861. {
  13862. Array <CommandID> commandIDs;
  13863. target->getAllCommands (commandIDs);
  13864. for (int i = 0; i < commandIDs.size(); ++i)
  13865. {
  13866. ApplicationCommandInfo info (commandIDs.getUnchecked(i));
  13867. target->getCommandInfo (info.commandID, info);
  13868. registerCommand (info);
  13869. }
  13870. }
  13871. }
  13872. void ApplicationCommandManager::removeCommand (const CommandID commandID)
  13873. {
  13874. for (int i = commands.size(); --i >= 0;)
  13875. {
  13876. if (commands.getUnchecked (i)->commandID == commandID)
  13877. {
  13878. commands.remove (i);
  13879. triggerAsyncUpdate();
  13880. const Array <KeyPress> keys (keyMappings->getKeyPressesAssignedToCommand (commandID));
  13881. for (int j = keys.size(); --j >= 0;)
  13882. keyMappings->removeKeyPress (keys.getReference (j));
  13883. }
  13884. }
  13885. }
  13886. void ApplicationCommandManager::commandStatusChanged()
  13887. {
  13888. triggerAsyncUpdate();
  13889. }
  13890. const ApplicationCommandInfo* ApplicationCommandManager::getCommandForID (const CommandID commandID) const throw()
  13891. {
  13892. for (int i = commands.size(); --i >= 0;)
  13893. if (commands.getUnchecked(i)->commandID == commandID)
  13894. return commands.getUnchecked(i);
  13895. return 0;
  13896. }
  13897. const String ApplicationCommandManager::getNameOfCommand (const CommandID commandID) const throw()
  13898. {
  13899. const ApplicationCommandInfo* const ci = getCommandForID (commandID);
  13900. return (ci != 0) ? ci->shortName : String::empty;
  13901. }
  13902. const String ApplicationCommandManager::getDescriptionOfCommand (const CommandID commandID) const throw()
  13903. {
  13904. const ApplicationCommandInfo* const ci = getCommandForID (commandID);
  13905. return (ci != 0) ? (ci->description.isNotEmpty() ? ci->description : ci->shortName)
  13906. : String::empty;
  13907. }
  13908. const StringArray ApplicationCommandManager::getCommandCategories() const throw()
  13909. {
  13910. StringArray s;
  13911. for (int i = 0; i < commands.size(); ++i)
  13912. s.addIfNotAlreadyThere (commands.getUnchecked(i)->categoryName, false);
  13913. return s;
  13914. }
  13915. const Array <CommandID> ApplicationCommandManager::getCommandsInCategory (const String& categoryName) const throw()
  13916. {
  13917. Array <CommandID> results;
  13918. for (int i = 0; i < commands.size(); ++i)
  13919. if (commands.getUnchecked(i)->categoryName == categoryName)
  13920. results.add (commands.getUnchecked(i)->commandID);
  13921. return results;
  13922. }
  13923. bool ApplicationCommandManager::invokeDirectly (const CommandID commandID, const bool asynchronously)
  13924. {
  13925. ApplicationCommandTarget::InvocationInfo info (commandID);
  13926. info.invocationMethod = ApplicationCommandTarget::InvocationInfo::direct;
  13927. return invoke (info, asynchronously);
  13928. }
  13929. bool ApplicationCommandManager::invoke (const ApplicationCommandTarget::InvocationInfo& info_, const bool asynchronously)
  13930. {
  13931. // This call isn't thread-safe for use from a non-UI thread without locking the message
  13932. // manager first..
  13933. jassert (MessageManager::getInstance()->currentThreadHasLockedMessageManager());
  13934. ApplicationCommandTarget* const target = getFirstCommandTarget (info_.commandID);
  13935. if (target == 0)
  13936. return false;
  13937. ApplicationCommandInfo commandInfo (0);
  13938. target->getCommandInfo (info_.commandID, commandInfo);
  13939. ApplicationCommandTarget::InvocationInfo info (info_);
  13940. info.commandFlags = commandInfo.flags;
  13941. sendListenerInvokeCallback (info);
  13942. const bool ok = target->invoke (info, asynchronously);
  13943. commandStatusChanged();
  13944. return ok;
  13945. }
  13946. ApplicationCommandTarget* ApplicationCommandManager::getFirstCommandTarget (const CommandID)
  13947. {
  13948. return firstTarget != 0 ? firstTarget
  13949. : findDefaultComponentTarget();
  13950. }
  13951. void ApplicationCommandManager::setFirstCommandTarget (ApplicationCommandTarget* const newTarget) throw()
  13952. {
  13953. firstTarget = newTarget;
  13954. }
  13955. ApplicationCommandTarget* ApplicationCommandManager::getTargetForCommand (const CommandID commandID,
  13956. ApplicationCommandInfo& upToDateInfo)
  13957. {
  13958. ApplicationCommandTarget* target = getFirstCommandTarget (commandID);
  13959. if (target == 0)
  13960. target = JUCEApplication::getInstance();
  13961. if (target != 0)
  13962. target = target->getTargetForCommand (commandID);
  13963. if (target != 0)
  13964. target->getCommandInfo (commandID, upToDateInfo);
  13965. return target;
  13966. }
  13967. ApplicationCommandTarget* ApplicationCommandManager::findTargetForComponent (Component* c)
  13968. {
  13969. ApplicationCommandTarget* target = dynamic_cast <ApplicationCommandTarget*> (c);
  13970. if (target == 0 && c != 0)
  13971. // (unable to use the syntax findParentComponentOfClass <ApplicationCommandTarget> () because of a VC6 compiler bug)
  13972. target = c->findParentComponentOfClass ((ApplicationCommandTarget*) 0);
  13973. return target;
  13974. }
  13975. ApplicationCommandTarget* ApplicationCommandManager::findDefaultComponentTarget()
  13976. {
  13977. Component* c = Component::getCurrentlyFocusedComponent();
  13978. if (c == 0)
  13979. {
  13980. TopLevelWindow* const activeWindow = TopLevelWindow::getActiveTopLevelWindow();
  13981. if (activeWindow != 0)
  13982. {
  13983. c = activeWindow->getPeer()->getLastFocusedSubcomponent();
  13984. if (c == 0)
  13985. c = activeWindow;
  13986. }
  13987. }
  13988. if (c == 0 && Process::isForegroundProcess())
  13989. {
  13990. // getting a bit desperate now - try all desktop comps..
  13991. for (int i = Desktop::getInstance().getNumComponents(); --i >= 0;)
  13992. {
  13993. ApplicationCommandTarget* const target
  13994. = findTargetForComponent (Desktop::getInstance().getComponent (i)
  13995. ->getPeer()->getLastFocusedSubcomponent());
  13996. if (target != 0)
  13997. return target;
  13998. }
  13999. }
  14000. if (c != 0)
  14001. {
  14002. ResizableWindow* const resizableWindow = dynamic_cast <ResizableWindow*> (c);
  14003. // if we're focused on a ResizableWindow, chances are that it's the content
  14004. // component that really should get the event. And if not, the event will
  14005. // still be passed up to the top level window anyway, so let's send it to the
  14006. // content comp.
  14007. if (resizableWindow != 0 && resizableWindow->getContentComponent() != 0)
  14008. c = resizableWindow->getContentComponent();
  14009. ApplicationCommandTarget* const target = findTargetForComponent (c);
  14010. if (target != 0)
  14011. return target;
  14012. }
  14013. return JUCEApplication::getInstance();
  14014. }
  14015. void ApplicationCommandManager::addListener (ApplicationCommandManagerListener* const listener) throw()
  14016. {
  14017. listeners.add (listener);
  14018. }
  14019. void ApplicationCommandManager::removeListener (ApplicationCommandManagerListener* const listener) throw()
  14020. {
  14021. listeners.remove (listener);
  14022. }
  14023. void ApplicationCommandManager::sendListenerInvokeCallback (const ApplicationCommandTarget::InvocationInfo& info)
  14024. {
  14025. listeners.call (&ApplicationCommandManagerListener::applicationCommandInvoked, info);
  14026. }
  14027. void ApplicationCommandManager::handleAsyncUpdate()
  14028. {
  14029. listeners.call (&ApplicationCommandManagerListener::applicationCommandListChanged);
  14030. }
  14031. void ApplicationCommandManager::globalFocusChanged (Component*)
  14032. {
  14033. commandStatusChanged();
  14034. }
  14035. END_JUCE_NAMESPACE
  14036. /*** End of inlined file: juce_ApplicationCommandManager.cpp ***/
  14037. /*** Start of inlined file: juce_ApplicationCommandTarget.cpp ***/
  14038. BEGIN_JUCE_NAMESPACE
  14039. ApplicationCommandTarget::ApplicationCommandTarget()
  14040. {
  14041. }
  14042. ApplicationCommandTarget::~ApplicationCommandTarget()
  14043. {
  14044. messageInvoker = 0;
  14045. }
  14046. bool ApplicationCommandTarget::tryToInvoke (const InvocationInfo& info, const bool async)
  14047. {
  14048. if (isCommandActive (info.commandID))
  14049. {
  14050. if (async)
  14051. {
  14052. if (messageInvoker == 0)
  14053. messageInvoker = new CommandTargetMessageInvoker (this);
  14054. messageInvoker->postMessage (new Message (0, 0, 0, new ApplicationCommandTarget::InvocationInfo (info)));
  14055. return true;
  14056. }
  14057. else
  14058. {
  14059. const bool success = perform (info);
  14060. jassert (success); // hmm - your target should have been able to perform this command. If it can't
  14061. // do it at the moment for some reason, it should clear the 'isActive' flag when it
  14062. // returns the command's info.
  14063. return success;
  14064. }
  14065. }
  14066. return false;
  14067. }
  14068. ApplicationCommandTarget* ApplicationCommandTarget::findFirstTargetParentComponent()
  14069. {
  14070. Component* c = dynamic_cast <Component*> (this);
  14071. if (c != 0)
  14072. // (unable to use the syntax findParentComponentOfClass <ApplicationCommandTarget> () because of a VC6 compiler bug)
  14073. return c->findParentComponentOfClass ((ApplicationCommandTarget*) 0);
  14074. return 0;
  14075. }
  14076. ApplicationCommandTarget* ApplicationCommandTarget::getTargetForCommand (const CommandID commandID)
  14077. {
  14078. ApplicationCommandTarget* target = this;
  14079. int depth = 0;
  14080. while (target != 0)
  14081. {
  14082. Array <CommandID> commandIDs;
  14083. target->getAllCommands (commandIDs);
  14084. if (commandIDs.contains (commandID))
  14085. return target;
  14086. target = target->getNextCommandTarget();
  14087. ++depth;
  14088. jassert (depth < 100); // could be a recursive command chain??
  14089. jassert (target != this); // definitely a recursive command chain!
  14090. if (depth > 100 || target == this)
  14091. break;
  14092. }
  14093. if (target == 0)
  14094. {
  14095. target = JUCEApplication::getInstance();
  14096. if (target != 0)
  14097. {
  14098. Array <CommandID> commandIDs;
  14099. target->getAllCommands (commandIDs);
  14100. if (commandIDs.contains (commandID))
  14101. return target;
  14102. }
  14103. }
  14104. return 0;
  14105. }
  14106. bool ApplicationCommandTarget::isCommandActive (const CommandID commandID)
  14107. {
  14108. ApplicationCommandInfo info (commandID);
  14109. info.flags = ApplicationCommandInfo::isDisabled;
  14110. getCommandInfo (commandID, info);
  14111. return (info.flags & ApplicationCommandInfo::isDisabled) == 0;
  14112. }
  14113. bool ApplicationCommandTarget::invoke (const InvocationInfo& info, const bool async)
  14114. {
  14115. ApplicationCommandTarget* target = this;
  14116. int depth = 0;
  14117. while (target != 0)
  14118. {
  14119. if (target->tryToInvoke (info, async))
  14120. return true;
  14121. target = target->getNextCommandTarget();
  14122. ++depth;
  14123. jassert (depth < 100); // could be a recursive command chain??
  14124. jassert (target != this); // definitely a recursive command chain!
  14125. if (depth > 100 || target == this)
  14126. break;
  14127. }
  14128. if (target == 0)
  14129. {
  14130. target = JUCEApplication::getInstance();
  14131. if (target != 0)
  14132. return target->tryToInvoke (info, async);
  14133. }
  14134. return false;
  14135. }
  14136. bool ApplicationCommandTarget::invokeDirectly (const CommandID commandID, const bool asynchronously)
  14137. {
  14138. ApplicationCommandTarget::InvocationInfo info (commandID);
  14139. info.invocationMethod = ApplicationCommandTarget::InvocationInfo::direct;
  14140. return invoke (info, asynchronously);
  14141. }
  14142. ApplicationCommandTarget::InvocationInfo::InvocationInfo (const CommandID commandID_) throw()
  14143. : commandID (commandID_),
  14144. commandFlags (0),
  14145. invocationMethod (direct),
  14146. originatingComponent (0),
  14147. isKeyDown (false),
  14148. millisecsSinceKeyPressed (0)
  14149. {
  14150. }
  14151. ApplicationCommandTarget::CommandTargetMessageInvoker::CommandTargetMessageInvoker (ApplicationCommandTarget* const owner_)
  14152. : owner (owner_)
  14153. {
  14154. }
  14155. ApplicationCommandTarget::CommandTargetMessageInvoker::~CommandTargetMessageInvoker()
  14156. {
  14157. }
  14158. void ApplicationCommandTarget::CommandTargetMessageInvoker::handleMessage (const Message& message)
  14159. {
  14160. const ScopedPointer <InvocationInfo> info (static_cast <InvocationInfo*> (message.pointerParameter));
  14161. owner->tryToInvoke (*info, false);
  14162. }
  14163. END_JUCE_NAMESPACE
  14164. /*** End of inlined file: juce_ApplicationCommandTarget.cpp ***/
  14165. /*** Start of inlined file: juce_ApplicationProperties.cpp ***/
  14166. BEGIN_JUCE_NAMESPACE
  14167. juce_ImplementSingleton (ApplicationProperties)
  14168. ApplicationProperties::ApplicationProperties() throw()
  14169. : msBeforeSaving (3000),
  14170. options (PropertiesFile::storeAsBinary),
  14171. commonSettingsAreReadOnly (0)
  14172. {
  14173. }
  14174. ApplicationProperties::~ApplicationProperties()
  14175. {
  14176. closeFiles();
  14177. clearSingletonInstance();
  14178. }
  14179. void ApplicationProperties::setStorageParameters (const String& applicationName,
  14180. const String& fileNameSuffix,
  14181. const String& folderName_,
  14182. const int millisecondsBeforeSaving,
  14183. const int propertiesFileOptions) throw()
  14184. {
  14185. appName = applicationName;
  14186. fileSuffix = fileNameSuffix;
  14187. folderName = folderName_;
  14188. msBeforeSaving = millisecondsBeforeSaving;
  14189. options = propertiesFileOptions;
  14190. }
  14191. bool ApplicationProperties::testWriteAccess (const bool testUserSettings,
  14192. const bool testCommonSettings,
  14193. const bool showWarningDialogOnFailure)
  14194. {
  14195. const bool userOk = (! testUserSettings) || getUserSettings()->save();
  14196. const bool commonOk = (! testCommonSettings) || getCommonSettings (false)->save();
  14197. if (! (userOk && commonOk))
  14198. {
  14199. if (showWarningDialogOnFailure)
  14200. {
  14201. String filenames;
  14202. if (userProps != 0 && ! userOk)
  14203. filenames << '\n' << userProps->getFile().getFullPathName();
  14204. if (commonProps != 0 && ! commonOk)
  14205. filenames << '\n' << commonProps->getFile().getFullPathName();
  14206. AlertWindow::showMessageBox (AlertWindow::WarningIcon,
  14207. appName + TRANS(" - Unable to save settings"),
  14208. TRANS("An error occurred when trying to save the application's settings file...\n\nIn order to save and restore its settings, ")
  14209. + appName + TRANS(" needs to be able to write to the following files:\n")
  14210. + filenames
  14211. + TRANS("\n\nMake sure that these files aren't read-only, and that the disk isn't full."));
  14212. }
  14213. return false;
  14214. }
  14215. return true;
  14216. }
  14217. void ApplicationProperties::openFiles() throw()
  14218. {
  14219. // You need to call setStorageParameters() before trying to get hold of the
  14220. // properties!
  14221. jassert (appName.isNotEmpty());
  14222. if (appName.isNotEmpty())
  14223. {
  14224. if (userProps == 0)
  14225. userProps = PropertiesFile::createDefaultAppPropertiesFile (appName, fileSuffix, folderName,
  14226. false, msBeforeSaving, options);
  14227. if (commonProps == 0)
  14228. commonProps = PropertiesFile::createDefaultAppPropertiesFile (appName, fileSuffix, folderName,
  14229. true, msBeforeSaving, options);
  14230. userProps->setFallbackPropertySet (commonProps);
  14231. }
  14232. }
  14233. PropertiesFile* ApplicationProperties::getUserSettings() throw()
  14234. {
  14235. if (userProps == 0)
  14236. openFiles();
  14237. return userProps;
  14238. }
  14239. PropertiesFile* ApplicationProperties::getCommonSettings (const bool returnUserPropsIfReadOnly) throw()
  14240. {
  14241. if (commonProps == 0)
  14242. openFiles();
  14243. if (returnUserPropsIfReadOnly)
  14244. {
  14245. if (commonSettingsAreReadOnly == 0)
  14246. commonSettingsAreReadOnly = commonProps->save() ? -1 : 1;
  14247. if (commonSettingsAreReadOnly > 0)
  14248. return userProps;
  14249. }
  14250. return commonProps;
  14251. }
  14252. bool ApplicationProperties::saveIfNeeded()
  14253. {
  14254. return (userProps == 0 || userProps->saveIfNeeded())
  14255. && (commonProps == 0 || commonProps->saveIfNeeded());
  14256. }
  14257. void ApplicationProperties::closeFiles()
  14258. {
  14259. userProps = 0;
  14260. commonProps = 0;
  14261. }
  14262. END_JUCE_NAMESPACE
  14263. /*** End of inlined file: juce_ApplicationProperties.cpp ***/
  14264. /*** Start of inlined file: juce_DeletedAtShutdown.cpp ***/
  14265. BEGIN_JUCE_NAMESPACE
  14266. static VoidArray objectsToDelete;
  14267. static CriticalSection lock;
  14268. DeletedAtShutdown::DeletedAtShutdown()
  14269. {
  14270. const ScopedLock sl (lock);
  14271. objectsToDelete.add (this);
  14272. }
  14273. DeletedAtShutdown::~DeletedAtShutdown()
  14274. {
  14275. const ScopedLock sl (lock);
  14276. objectsToDelete.removeValue (this);
  14277. }
  14278. void DeletedAtShutdown::deleteAll()
  14279. {
  14280. // make a local copy of the array, so it can't get into a loop if something
  14281. // creates another DeletedAtShutdown object during its destructor.
  14282. VoidArray localCopy;
  14283. {
  14284. const ScopedLock sl (lock);
  14285. localCopy = objectsToDelete;
  14286. }
  14287. for (int i = localCopy.size(); --i >= 0;)
  14288. {
  14289. JUCE_TRY
  14290. {
  14291. DeletedAtShutdown* deletee = static_cast <DeletedAtShutdown*> (localCopy.getUnchecked(i));
  14292. // double-check that it's not already been deleted during another object's destructor.
  14293. {
  14294. const ScopedLock sl (lock);
  14295. if (! objectsToDelete.contains (deletee))
  14296. deletee = 0;
  14297. }
  14298. delete deletee;
  14299. }
  14300. JUCE_CATCH_EXCEPTION
  14301. }
  14302. // if no objects got re-created during shutdown, this should have been emptied by their
  14303. // destructors
  14304. jassert (objectsToDelete.size() == 0);
  14305. objectsToDelete.clear(); // just to make sure the array doesn't have any memory still allocated
  14306. }
  14307. END_JUCE_NAMESPACE
  14308. /*** End of inlined file: juce_DeletedAtShutdown.cpp ***/
  14309. /*** Start of inlined file: juce_PropertiesFile.cpp ***/
  14310. BEGIN_JUCE_NAMESPACE
  14311. namespace PropertyFileConstants
  14312. {
  14313. static const int magicNumber = (int) ByteOrder::littleEndianInt ("PROP");
  14314. static const int magicNumberCompressed = (int) ByteOrder::littleEndianInt ("CPRP");
  14315. static const char* const fileTag = "PROPERTIES";
  14316. static const char* const valueTag = "VALUE";
  14317. static const char* const nameAttribute = "name";
  14318. static const char* const valueAttribute = "val";
  14319. }
  14320. PropertiesFile::PropertiesFile (const File& f, const int millisecondsBeforeSaving,
  14321. const int options_, InterProcessLock* const processLock_)
  14322. : PropertySet (ignoreCaseOfKeyNames),
  14323. file (f),
  14324. timerInterval (millisecondsBeforeSaving),
  14325. options (options_),
  14326. loadedOk (false),
  14327. needsWriting (false),
  14328. processLock (processLock_)
  14329. {
  14330. // You need to correctly specify just one storage format for the file
  14331. jassert ((options_ & (storeAsBinary | storeAsCompressedBinary | storeAsXML)) == storeAsBinary
  14332. || (options_ & (storeAsBinary | storeAsCompressedBinary | storeAsXML)) == storeAsCompressedBinary
  14333. || (options_ & (storeAsBinary | storeAsCompressedBinary | storeAsXML)) == storeAsXML);
  14334. ProcessScopedLock pl (createProcessLock());
  14335. if (pl != 0 && ! pl->isLocked())
  14336. return; // locking failure..
  14337. ScopedPointer<InputStream> fileStream (f.createInputStream());
  14338. if (fileStream != 0)
  14339. {
  14340. int magicNumber = fileStream->readInt();
  14341. if (magicNumber == PropertyFileConstants::magicNumberCompressed)
  14342. {
  14343. fileStream = new GZIPDecompressorInputStream (new SubregionStream (fileStream.release(), 4, -1, true), true);
  14344. magicNumber = PropertyFileConstants::magicNumber;
  14345. }
  14346. if (magicNumber == PropertyFileConstants::magicNumber)
  14347. {
  14348. loadedOk = true;
  14349. BufferedInputStream in (fileStream.release(), 2048, true);
  14350. int numValues = in.readInt();
  14351. while (--numValues >= 0 && ! in.isExhausted())
  14352. {
  14353. const String key (in.readString());
  14354. const String value (in.readString());
  14355. jassert (key.isNotEmpty());
  14356. if (key.isNotEmpty())
  14357. getAllProperties().set (key, value);
  14358. }
  14359. }
  14360. else
  14361. {
  14362. // Not a binary props file - let's see if it's XML..
  14363. fileStream = 0;
  14364. XmlDocument parser (f);
  14365. ScopedPointer<XmlElement> doc (parser.getDocumentElement (true));
  14366. if (doc != 0 && doc->hasTagName (PropertyFileConstants::fileTag))
  14367. {
  14368. doc = parser.getDocumentElement();
  14369. if (doc != 0)
  14370. {
  14371. loadedOk = true;
  14372. forEachXmlChildElementWithTagName (*doc, e, PropertyFileConstants::valueTag)
  14373. {
  14374. const String name (e->getStringAttribute (PropertyFileConstants::nameAttribute));
  14375. if (name.isNotEmpty())
  14376. {
  14377. getAllProperties().set (name,
  14378. e->getFirstChildElement() != 0
  14379. ? e->getFirstChildElement()->createDocument (String::empty, true)
  14380. : e->getStringAttribute (PropertyFileConstants::valueAttribute));
  14381. }
  14382. }
  14383. }
  14384. else
  14385. {
  14386. // must be a pretty broken XML file we're trying to parse here,
  14387. // or a sign that this object needs an InterProcessLock,
  14388. // or just a failure reading the file. This last reason is why
  14389. // we don't jassertfalse here.
  14390. }
  14391. }
  14392. }
  14393. }
  14394. else
  14395. {
  14396. loadedOk = ! f.exists();
  14397. }
  14398. }
  14399. PropertiesFile::~PropertiesFile()
  14400. {
  14401. if (! saveIfNeeded())
  14402. jassertfalse;
  14403. }
  14404. InterProcessLock::ScopedLockType* PropertiesFile::createProcessLock() const
  14405. {
  14406. return processLock != 0 ? new InterProcessLock::ScopedLockType (*processLock) : 0;
  14407. }
  14408. bool PropertiesFile::saveIfNeeded()
  14409. {
  14410. const ScopedLock sl (getLock());
  14411. return (! needsWriting) || save();
  14412. }
  14413. bool PropertiesFile::needsToBeSaved() const
  14414. {
  14415. const ScopedLock sl (getLock());
  14416. return needsWriting;
  14417. }
  14418. void PropertiesFile::setNeedsToBeSaved (const bool needsToBeSaved_)
  14419. {
  14420. const ScopedLock sl (getLock());
  14421. needsWriting = needsToBeSaved_;
  14422. }
  14423. bool PropertiesFile::save()
  14424. {
  14425. const ScopedLock sl (getLock());
  14426. stopTimer();
  14427. if (file == File::nonexistent
  14428. || file.isDirectory()
  14429. || ! file.getParentDirectory().createDirectory())
  14430. return false;
  14431. if ((options & storeAsXML) != 0)
  14432. {
  14433. XmlElement doc (PropertyFileConstants::fileTag);
  14434. for (int i = 0; i < getAllProperties().size(); ++i)
  14435. {
  14436. XmlElement* const e = doc.createNewChildElement (PropertyFileConstants::valueTag);
  14437. e->setAttribute (PropertyFileConstants::nameAttribute, getAllProperties().getAllKeys() [i]);
  14438. // if the value seems to contain xml, store it as such..
  14439. XmlDocument xmlContent (getAllProperties().getAllValues() [i]);
  14440. XmlElement* const childElement = xmlContent.getDocumentElement();
  14441. if (childElement != 0)
  14442. e->addChildElement (childElement);
  14443. else
  14444. e->setAttribute (PropertyFileConstants::valueAttribute,
  14445. getAllProperties().getAllValues() [i]);
  14446. }
  14447. ProcessScopedLock pl (createProcessLock());
  14448. if (pl != 0 && ! pl->isLocked())
  14449. return false; // locking failure..
  14450. if (doc.writeToFile (file, String::empty))
  14451. {
  14452. needsWriting = false;
  14453. return true;
  14454. }
  14455. }
  14456. else
  14457. {
  14458. ProcessScopedLock pl (createProcessLock());
  14459. if (pl != 0 && ! pl->isLocked())
  14460. return false; // locking failure..
  14461. TemporaryFile tempFile (file);
  14462. ScopedPointer <OutputStream> out (tempFile.getFile().createOutputStream());
  14463. if (out != 0)
  14464. {
  14465. if ((options & storeAsCompressedBinary) != 0)
  14466. {
  14467. out->writeInt (PropertyFileConstants::magicNumberCompressed);
  14468. out->flush();
  14469. out = new GZIPCompressorOutputStream (out.release(), 9, true);
  14470. }
  14471. else
  14472. {
  14473. // have you set up the storage option flags correctly?
  14474. jassert ((options & storeAsBinary) != 0);
  14475. out->writeInt (PropertyFileConstants::magicNumber);
  14476. }
  14477. const int numProperties = getAllProperties().size();
  14478. out->writeInt (numProperties);
  14479. for (int i = 0; i < numProperties; ++i)
  14480. {
  14481. out->writeString (getAllProperties().getAllKeys() [i]);
  14482. out->writeString (getAllProperties().getAllValues() [i]);
  14483. }
  14484. out = 0;
  14485. if (tempFile.overwriteTargetFileWithTemporary())
  14486. {
  14487. needsWriting = false;
  14488. return true;
  14489. }
  14490. }
  14491. }
  14492. return false;
  14493. }
  14494. void PropertiesFile::timerCallback()
  14495. {
  14496. saveIfNeeded();
  14497. }
  14498. void PropertiesFile::propertyChanged()
  14499. {
  14500. sendChangeMessage (this);
  14501. needsWriting = true;
  14502. if (timerInterval > 0)
  14503. startTimer (timerInterval);
  14504. else if (timerInterval == 0)
  14505. saveIfNeeded();
  14506. }
  14507. const File PropertiesFile::getDefaultAppSettingsFile (const String& applicationName,
  14508. const String& fileNameSuffix,
  14509. const String& folderName,
  14510. const bool commonToAllUsers)
  14511. {
  14512. // mustn't have illegal characters in this name..
  14513. jassert (applicationName == File::createLegalFileName (applicationName));
  14514. #if JUCE_MAC || JUCE_IPHONE
  14515. File dir (commonToAllUsers ? "/Library/Preferences"
  14516. : "~/Library/Preferences");
  14517. if (folderName.isNotEmpty())
  14518. dir = dir.getChildFile (folderName);
  14519. #endif
  14520. #ifdef JUCE_LINUX
  14521. const File dir ((commonToAllUsers ? "/var/" : "~/")
  14522. + (folderName.isNotEmpty() ? folderName
  14523. : ("." + applicationName)));
  14524. #endif
  14525. #if JUCE_WIN32
  14526. File dir (File::getSpecialLocation (commonToAllUsers ? File::commonApplicationDataDirectory
  14527. : File::userApplicationDataDirectory));
  14528. if (dir == File::nonexistent)
  14529. return File::nonexistent;
  14530. dir = dir.getChildFile (folderName.isNotEmpty() ? folderName
  14531. : applicationName);
  14532. #endif
  14533. return dir.getChildFile (applicationName)
  14534. .withFileExtension (fileNameSuffix);
  14535. }
  14536. PropertiesFile* PropertiesFile::createDefaultAppPropertiesFile (const String& applicationName,
  14537. const String& fileNameSuffix,
  14538. const String& folderName,
  14539. const bool commonToAllUsers,
  14540. const int millisecondsBeforeSaving,
  14541. const int propertiesFileOptions,
  14542. InterProcessLock* processLock_)
  14543. {
  14544. const File file (getDefaultAppSettingsFile (applicationName,
  14545. fileNameSuffix,
  14546. folderName,
  14547. commonToAllUsers));
  14548. jassert (file != File::nonexistent);
  14549. if (file == File::nonexistent)
  14550. return 0;
  14551. return new PropertiesFile (file, millisecondsBeforeSaving, propertiesFileOptions,processLock_);
  14552. }
  14553. END_JUCE_NAMESPACE
  14554. /*** End of inlined file: juce_PropertiesFile.cpp ***/
  14555. /*** Start of inlined file: juce_FileBasedDocument.cpp ***/
  14556. BEGIN_JUCE_NAMESPACE
  14557. FileBasedDocument::FileBasedDocument (const String& fileExtension_,
  14558. const String& fileWildcard_,
  14559. const String& openFileDialogTitle_,
  14560. const String& saveFileDialogTitle_)
  14561. : changedSinceSave (false),
  14562. fileExtension (fileExtension_),
  14563. fileWildcard (fileWildcard_),
  14564. openFileDialogTitle (openFileDialogTitle_),
  14565. saveFileDialogTitle (saveFileDialogTitle_)
  14566. {
  14567. }
  14568. FileBasedDocument::~FileBasedDocument()
  14569. {
  14570. }
  14571. void FileBasedDocument::setChangedFlag (const bool hasChanged)
  14572. {
  14573. if (changedSinceSave != hasChanged)
  14574. {
  14575. changedSinceSave = hasChanged;
  14576. sendChangeMessage (this);
  14577. }
  14578. }
  14579. void FileBasedDocument::changed()
  14580. {
  14581. changedSinceSave = true;
  14582. sendChangeMessage (this);
  14583. }
  14584. void FileBasedDocument::setFile (const File& newFile)
  14585. {
  14586. if (documentFile != newFile)
  14587. {
  14588. documentFile = newFile;
  14589. changed();
  14590. }
  14591. }
  14592. bool FileBasedDocument::loadFrom (const File& newFile,
  14593. const bool showMessageOnFailure)
  14594. {
  14595. MouseCursor::showWaitCursor();
  14596. const File oldFile (documentFile);
  14597. documentFile = newFile;
  14598. String error;
  14599. if (newFile.existsAsFile())
  14600. {
  14601. error = loadDocument (newFile);
  14602. if (error.isEmpty())
  14603. {
  14604. setChangedFlag (false);
  14605. MouseCursor::hideWaitCursor();
  14606. setLastDocumentOpened (newFile);
  14607. return true;
  14608. }
  14609. }
  14610. else
  14611. {
  14612. error = "The file doesn't exist";
  14613. }
  14614. documentFile = oldFile;
  14615. MouseCursor::hideWaitCursor();
  14616. if (showMessageOnFailure)
  14617. {
  14618. AlertWindow::showMessageBox (AlertWindow::WarningIcon,
  14619. TRANS("Failed to open file..."),
  14620. TRANS("There was an error while trying to load the file:\n\n")
  14621. + newFile.getFullPathName()
  14622. + "\n\n"
  14623. + error);
  14624. }
  14625. return false;
  14626. }
  14627. bool FileBasedDocument::loadFromUserSpecifiedFile (const bool showMessageOnFailure)
  14628. {
  14629. FileChooser fc (openFileDialogTitle,
  14630. getLastDocumentOpened(),
  14631. fileWildcard);
  14632. if (fc.browseForFileToOpen())
  14633. return loadFrom (fc.getResult(), showMessageOnFailure);
  14634. return false;
  14635. }
  14636. FileBasedDocument::SaveResult FileBasedDocument::save (const bool askUserForFileIfNotSpecified,
  14637. const bool showMessageOnFailure)
  14638. {
  14639. return saveAs (documentFile,
  14640. false,
  14641. askUserForFileIfNotSpecified,
  14642. showMessageOnFailure);
  14643. }
  14644. FileBasedDocument::SaveResult FileBasedDocument::saveAs (const File& newFile,
  14645. const bool warnAboutOverwritingExistingFiles,
  14646. const bool askUserForFileIfNotSpecified,
  14647. const bool showMessageOnFailure)
  14648. {
  14649. if (newFile == File::nonexistent)
  14650. {
  14651. if (askUserForFileIfNotSpecified)
  14652. {
  14653. return saveAsInteractive (true);
  14654. }
  14655. else
  14656. {
  14657. // can't save to an unspecified file
  14658. jassertfalse
  14659. return failedToWriteToFile;
  14660. }
  14661. }
  14662. if (warnAboutOverwritingExistingFiles && newFile.exists())
  14663. {
  14664. if (! AlertWindow::showOkCancelBox (AlertWindow::WarningIcon,
  14665. TRANS("File already exists"),
  14666. TRANS("There's already a file called:\n\n")
  14667. + newFile.getFullPathName()
  14668. + TRANS("\n\nAre you sure you want to overwrite it?"),
  14669. TRANS("overwrite"),
  14670. TRANS("cancel")))
  14671. {
  14672. return userCancelledSave;
  14673. }
  14674. }
  14675. MouseCursor::showWaitCursor();
  14676. const File oldFile (documentFile);
  14677. documentFile = newFile;
  14678. String error (saveDocument (newFile));
  14679. if (error.isEmpty())
  14680. {
  14681. setChangedFlag (false);
  14682. MouseCursor::hideWaitCursor();
  14683. return savedOk;
  14684. }
  14685. documentFile = oldFile;
  14686. MouseCursor::hideWaitCursor();
  14687. if (showMessageOnFailure)
  14688. {
  14689. AlertWindow::showMessageBox (AlertWindow::WarningIcon,
  14690. TRANS("Error writing to file..."),
  14691. TRANS("An error occurred while trying to save \"")
  14692. + getDocumentTitle()
  14693. + TRANS("\" to the file:\n\n")
  14694. + newFile.getFullPathName()
  14695. + "\n\n"
  14696. + error);
  14697. }
  14698. return failedToWriteToFile;
  14699. }
  14700. FileBasedDocument::SaveResult FileBasedDocument::saveIfNeededAndUserAgrees()
  14701. {
  14702. if (! hasChangedSinceSaved())
  14703. return savedOk;
  14704. const int r = AlertWindow::showYesNoCancelBox (AlertWindow::QuestionIcon,
  14705. TRANS("Closing document..."),
  14706. TRANS("Do you want to save the changes to \"")
  14707. + getDocumentTitle() + "\"?",
  14708. TRANS("save"),
  14709. TRANS("discard changes"),
  14710. TRANS("cancel"));
  14711. if (r == 1)
  14712. {
  14713. // save changes
  14714. return save (true, true);
  14715. }
  14716. else if (r == 2)
  14717. {
  14718. // discard changes
  14719. return savedOk;
  14720. }
  14721. return userCancelledSave;
  14722. }
  14723. FileBasedDocument::SaveResult FileBasedDocument::saveAsInteractive (const bool warnAboutOverwritingExistingFiles)
  14724. {
  14725. File f;
  14726. if (documentFile.existsAsFile())
  14727. f = documentFile;
  14728. else
  14729. f = getLastDocumentOpened();
  14730. String legalFilename (File::createLegalFileName (getDocumentTitle()));
  14731. if (legalFilename.isEmpty())
  14732. legalFilename = "unnamed";
  14733. if (f.existsAsFile() || f.getParentDirectory().isDirectory())
  14734. f = f.getSiblingFile (legalFilename);
  14735. else
  14736. f = File::getSpecialLocation (File::userDocumentsDirectory).getChildFile (legalFilename);
  14737. f = f.withFileExtension (fileExtension)
  14738. .getNonexistentSibling (true);
  14739. FileChooser fc (saveFileDialogTitle, f, fileWildcard);
  14740. if (fc.browseForFileToSave (warnAboutOverwritingExistingFiles))
  14741. {
  14742. setLastDocumentOpened (fc.getResult());
  14743. File chosen (fc.getResult());
  14744. if (chosen.getFileExtension().isEmpty())
  14745. {
  14746. chosen = chosen.withFileExtension (fileExtension);
  14747. if (chosen.exists())
  14748. {
  14749. if (! AlertWindow::showOkCancelBox (AlertWindow::WarningIcon,
  14750. TRANS("File already exists"),
  14751. TRANS("There's already a file called:")
  14752. + "\n\n" + chosen.getFullPathName()
  14753. + "\n\n" + TRANS("Are you sure you want to overwrite it?"),
  14754. TRANS("overwrite"),
  14755. TRANS("cancel")))
  14756. {
  14757. return userCancelledSave;
  14758. }
  14759. }
  14760. }
  14761. return saveAs (chosen, false, false, true);
  14762. }
  14763. return userCancelledSave;
  14764. }
  14765. END_JUCE_NAMESPACE
  14766. /*** End of inlined file: juce_FileBasedDocument.cpp ***/
  14767. /*** Start of inlined file: juce_RecentlyOpenedFilesList.cpp ***/
  14768. BEGIN_JUCE_NAMESPACE
  14769. RecentlyOpenedFilesList::RecentlyOpenedFilesList()
  14770. : maxNumberOfItems (10)
  14771. {
  14772. }
  14773. RecentlyOpenedFilesList::~RecentlyOpenedFilesList()
  14774. {
  14775. }
  14776. void RecentlyOpenedFilesList::setMaxNumberOfItems (const int newMaxNumber)
  14777. {
  14778. maxNumberOfItems = jmax (1, newMaxNumber);
  14779. while (getNumFiles() > maxNumberOfItems)
  14780. files.remove (getNumFiles() - 1);
  14781. }
  14782. int RecentlyOpenedFilesList::getNumFiles() const
  14783. {
  14784. return files.size();
  14785. }
  14786. const File RecentlyOpenedFilesList::getFile (const int index) const
  14787. {
  14788. return File (files [index]);
  14789. }
  14790. void RecentlyOpenedFilesList::clear()
  14791. {
  14792. files.clear();
  14793. }
  14794. void RecentlyOpenedFilesList::addFile (const File& file)
  14795. {
  14796. const String path (file.getFullPathName());
  14797. files.removeString (path, true);
  14798. files.insert (0, path);
  14799. setMaxNumberOfItems (maxNumberOfItems);
  14800. }
  14801. void RecentlyOpenedFilesList::removeNonExistentFiles()
  14802. {
  14803. for (int i = getNumFiles(); --i >= 0;)
  14804. if (! getFile(i).exists())
  14805. files.remove (i);
  14806. }
  14807. int RecentlyOpenedFilesList::createPopupMenuItems (PopupMenu& menuToAddTo,
  14808. const int baseItemId,
  14809. const bool showFullPaths,
  14810. const bool dontAddNonExistentFiles,
  14811. const File** filesToAvoid)
  14812. {
  14813. int num = 0;
  14814. for (int i = 0; i < getNumFiles(); ++i)
  14815. {
  14816. const File f (getFile(i));
  14817. if ((! dontAddNonExistentFiles) || f.exists())
  14818. {
  14819. bool needsAvoiding = false;
  14820. if (filesToAvoid != 0)
  14821. {
  14822. const File** avoid = filesToAvoid;
  14823. while (*avoid != 0)
  14824. {
  14825. if (f == **avoid)
  14826. {
  14827. needsAvoiding = true;
  14828. break;
  14829. }
  14830. ++avoid;
  14831. }
  14832. }
  14833. if (! needsAvoiding)
  14834. {
  14835. menuToAddTo.addItem (baseItemId + i,
  14836. showFullPaths ? f.getFullPathName()
  14837. : f.getFileName());
  14838. ++num;
  14839. }
  14840. }
  14841. }
  14842. return num;
  14843. }
  14844. const String RecentlyOpenedFilesList::toString() const
  14845. {
  14846. return files.joinIntoString ("\n");
  14847. }
  14848. void RecentlyOpenedFilesList::restoreFromString (const String& stringifiedVersion)
  14849. {
  14850. clear();
  14851. files.addLines (stringifiedVersion);
  14852. setMaxNumberOfItems (maxNumberOfItems);
  14853. }
  14854. END_JUCE_NAMESPACE
  14855. /*** End of inlined file: juce_RecentlyOpenedFilesList.cpp ***/
  14856. /*** Start of inlined file: juce_UndoManager.cpp ***/
  14857. BEGIN_JUCE_NAMESPACE
  14858. UndoManager::UndoManager (const int maxNumberOfUnitsToKeep,
  14859. const int minimumTransactions)
  14860. : totalUnitsStored (0),
  14861. nextIndex (0),
  14862. newTransaction (true),
  14863. reentrancyCheck (false)
  14864. {
  14865. setMaxNumberOfStoredUnits (maxNumberOfUnitsToKeep,
  14866. minimumTransactions);
  14867. }
  14868. UndoManager::~UndoManager()
  14869. {
  14870. clearUndoHistory();
  14871. }
  14872. void UndoManager::clearUndoHistory()
  14873. {
  14874. transactions.clear();
  14875. transactionNames.clear();
  14876. totalUnitsStored = 0;
  14877. nextIndex = 0;
  14878. sendChangeMessage (this);
  14879. }
  14880. int UndoManager::getNumberOfUnitsTakenUpByStoredCommands() const
  14881. {
  14882. return totalUnitsStored;
  14883. }
  14884. void UndoManager::setMaxNumberOfStoredUnits (const int maxNumberOfUnitsToKeep,
  14885. const int minimumTransactions)
  14886. {
  14887. maxNumUnitsToKeep = jmax (1, maxNumberOfUnitsToKeep);
  14888. minimumTransactionsToKeep = jmax (1, minimumTransactions);
  14889. }
  14890. bool UndoManager::perform (UndoableAction* const command, const String& actionName)
  14891. {
  14892. if (command != 0)
  14893. {
  14894. if (actionName.isNotEmpty())
  14895. currentTransactionName = actionName;
  14896. if (reentrancyCheck)
  14897. {
  14898. jassertfalse // don't call perform() recursively from the UndoableAction::perform() or
  14899. // undo() methods, or else these actions won't actually get done.
  14900. return false;
  14901. }
  14902. else
  14903. {
  14904. bool success = false;
  14905. JUCE_TRY
  14906. {
  14907. success = command->perform();
  14908. }
  14909. JUCE_CATCH_EXCEPTION
  14910. jassert (success);
  14911. if (success)
  14912. {
  14913. if (nextIndex > 0 && ! newTransaction)
  14914. {
  14915. OwnedArray<UndoableAction>* commandSet = transactions [nextIndex - 1];
  14916. jassert (commandSet != 0);
  14917. if (commandSet == 0)
  14918. return false;
  14919. commandSet->add (command);
  14920. }
  14921. else
  14922. {
  14923. OwnedArray<UndoableAction>* commandSet = new OwnedArray<UndoableAction>();
  14924. commandSet->add (command);
  14925. transactions.insert (nextIndex, commandSet);
  14926. transactionNames.insert (nextIndex, currentTransactionName);
  14927. ++nextIndex;
  14928. }
  14929. totalUnitsStored += command->getSizeInUnits();
  14930. newTransaction = false;
  14931. }
  14932. while (nextIndex < transactions.size())
  14933. {
  14934. const OwnedArray <UndoableAction>* const lastSet = transactions.getLast();
  14935. for (int i = lastSet->size(); --i >= 0;)
  14936. totalUnitsStored -= lastSet->getUnchecked (i)->getSizeInUnits();
  14937. transactions.removeLast();
  14938. transactionNames.remove (transactionNames.size() - 1);
  14939. }
  14940. while (nextIndex > 0
  14941. && totalUnitsStored > maxNumUnitsToKeep
  14942. && transactions.size() > minimumTransactionsToKeep)
  14943. {
  14944. const OwnedArray <UndoableAction>* const firstSet = transactions.getFirst();
  14945. for (int i = firstSet->size(); --i >= 0;)
  14946. totalUnitsStored -= firstSet->getUnchecked (i)->getSizeInUnits();
  14947. jassert (totalUnitsStored >= 0); // something fishy going on if this fails!
  14948. transactions.remove (0);
  14949. transactionNames.remove (0);
  14950. --nextIndex;
  14951. }
  14952. sendChangeMessage (this);
  14953. return success;
  14954. }
  14955. }
  14956. return false;
  14957. }
  14958. void UndoManager::beginNewTransaction (const String& actionName)
  14959. {
  14960. newTransaction = true;
  14961. currentTransactionName = actionName;
  14962. }
  14963. void UndoManager::setCurrentTransactionName (const String& newName)
  14964. {
  14965. currentTransactionName = newName;
  14966. }
  14967. bool UndoManager::canUndo() const
  14968. {
  14969. return nextIndex > 0;
  14970. }
  14971. bool UndoManager::canRedo() const
  14972. {
  14973. return nextIndex < transactions.size();
  14974. }
  14975. const String UndoManager::getUndoDescription() const
  14976. {
  14977. return transactionNames [nextIndex - 1];
  14978. }
  14979. const String UndoManager::getRedoDescription() const
  14980. {
  14981. return transactionNames [nextIndex];
  14982. }
  14983. bool UndoManager::undo()
  14984. {
  14985. const OwnedArray<UndoableAction>* const commandSet = transactions [nextIndex - 1];
  14986. if (commandSet == 0)
  14987. return false;
  14988. reentrancyCheck = true;
  14989. bool failed = false;
  14990. for (int i = commandSet->size(); --i >= 0;)
  14991. {
  14992. if (! commandSet->getUnchecked(i)->undo())
  14993. {
  14994. jassertfalse
  14995. failed = true;
  14996. break;
  14997. }
  14998. }
  14999. reentrancyCheck = false;
  15000. if (failed)
  15001. {
  15002. clearUndoHistory();
  15003. }
  15004. else
  15005. {
  15006. --nextIndex;
  15007. }
  15008. beginNewTransaction();
  15009. sendChangeMessage (this);
  15010. return true;
  15011. }
  15012. bool UndoManager::redo()
  15013. {
  15014. const OwnedArray<UndoableAction>* const commandSet = transactions [nextIndex];
  15015. if (commandSet == 0)
  15016. return false;
  15017. reentrancyCheck = true;
  15018. bool failed = false;
  15019. for (int i = 0; i < commandSet->size(); ++i)
  15020. {
  15021. if (! commandSet->getUnchecked(i)->perform())
  15022. {
  15023. jassertfalse
  15024. failed = true;
  15025. break;
  15026. }
  15027. }
  15028. reentrancyCheck = false;
  15029. if (failed)
  15030. {
  15031. clearUndoHistory();
  15032. }
  15033. else
  15034. {
  15035. ++nextIndex;
  15036. }
  15037. beginNewTransaction();
  15038. sendChangeMessage (this);
  15039. return true;
  15040. }
  15041. bool UndoManager::undoCurrentTransactionOnly()
  15042. {
  15043. return newTransaction ? false
  15044. : undo();
  15045. }
  15046. void UndoManager::getActionsInCurrentTransaction (Array <const UndoableAction*>& actionsFound) const
  15047. {
  15048. const OwnedArray <UndoableAction>* const commandSet = transactions [nextIndex - 1];
  15049. if (commandSet != 0 && ! newTransaction)
  15050. {
  15051. for (int i = 0; i < commandSet->size(); ++i)
  15052. actionsFound.add (commandSet->getUnchecked(i));
  15053. }
  15054. }
  15055. int UndoManager::getNumActionsInCurrentTransaction() const
  15056. {
  15057. const OwnedArray <UndoableAction>* const commandSet = transactions [nextIndex - 1];
  15058. if (commandSet != 0 && ! newTransaction)
  15059. return commandSet->size();
  15060. return 0;
  15061. }
  15062. END_JUCE_NAMESPACE
  15063. /*** End of inlined file: juce_UndoManager.cpp ***/
  15064. /*** Start of inlined file: juce_AiffAudioFormat.cpp ***/
  15065. BEGIN_JUCE_NAMESPACE
  15066. static const char* const aiffFormatName = "AIFF file";
  15067. static const char* const aiffExtensions[] = { ".aiff", ".aif", 0 };
  15068. class AiffAudioFormatReader : public AudioFormatReader
  15069. {
  15070. public:
  15071. int bytesPerFrame;
  15072. int64 dataChunkStart;
  15073. bool littleEndian;
  15074. AiffAudioFormatReader (InputStream* in)
  15075. : AudioFormatReader (in, TRANS (aiffFormatName))
  15076. {
  15077. if (input->readInt() == chunkName ("FORM"))
  15078. {
  15079. const int len = input->readIntBigEndian();
  15080. const int64 end = input->getPosition() + len;
  15081. const int nextType = input->readInt();
  15082. if (nextType == chunkName ("AIFF") || nextType == chunkName ("AIFC"))
  15083. {
  15084. bool hasGotVer = false;
  15085. bool hasGotData = false;
  15086. bool hasGotType = false;
  15087. while (input->getPosition() < end)
  15088. {
  15089. const int type = input->readInt();
  15090. const uint32 length = (uint32) input->readIntBigEndian();
  15091. const int64 chunkEnd = input->getPosition() + length;
  15092. if (type == chunkName ("FVER"))
  15093. {
  15094. hasGotVer = true;
  15095. const int ver = input->readIntBigEndian();
  15096. if (ver != 0 && ver != (int)0xa2805140)
  15097. break;
  15098. }
  15099. else if (type == chunkName ("COMM"))
  15100. {
  15101. hasGotType = true;
  15102. numChannels = (unsigned int)input->readShortBigEndian();
  15103. lengthInSamples = input->readIntBigEndian();
  15104. bitsPerSample = input->readShortBigEndian();
  15105. bytesPerFrame = (numChannels * bitsPerSample) >> 3;
  15106. unsigned char sampleRateBytes[10];
  15107. input->read (sampleRateBytes, 10);
  15108. const int byte0 = sampleRateBytes[0];
  15109. if ((byte0 & 0x80) != 0
  15110. || byte0 <= 0x3F || byte0 > 0x40
  15111. || (byte0 == 0x40 && sampleRateBytes[1] > 0x1C))
  15112. break;
  15113. unsigned int sampRate = ByteOrder::bigEndianInt (sampleRateBytes + 2);
  15114. sampRate >>= (16414 - ByteOrder::bigEndianShort (sampleRateBytes));
  15115. sampleRate = (int) sampRate;
  15116. if (length <= 18)
  15117. {
  15118. // some types don't have a chunk large enough to include a compression
  15119. // type, so assume it's just big-endian pcm
  15120. littleEndian = false;
  15121. }
  15122. else
  15123. {
  15124. const int compType = input->readInt();
  15125. if (compType == chunkName ("NONE") || compType == chunkName ("twos"))
  15126. {
  15127. littleEndian = false;
  15128. }
  15129. else if (compType == chunkName ("sowt"))
  15130. {
  15131. littleEndian = true;
  15132. }
  15133. else
  15134. {
  15135. sampleRate = 0;
  15136. break;
  15137. }
  15138. }
  15139. }
  15140. else if (type == chunkName ("SSND"))
  15141. {
  15142. hasGotData = true;
  15143. const int offset = input->readIntBigEndian();
  15144. dataChunkStart = input->getPosition() + 4 + offset;
  15145. lengthInSamples = (bytesPerFrame > 0) ? jmin (lengthInSamples, (int64) (length / bytesPerFrame)) : 0;
  15146. }
  15147. else if ((hasGotVer && hasGotData && hasGotType)
  15148. || chunkEnd < input->getPosition()
  15149. || input->isExhausted())
  15150. {
  15151. break;
  15152. }
  15153. input->setPosition (chunkEnd);
  15154. }
  15155. }
  15156. }
  15157. }
  15158. ~AiffAudioFormatReader()
  15159. {
  15160. }
  15161. bool readSamples (int** destSamples, int numDestChannels, int startOffsetInDestBuffer,
  15162. int64 startSampleInFile, int numSamples)
  15163. {
  15164. const int64 samplesAvailable = lengthInSamples - startSampleInFile;
  15165. if (samplesAvailable < numSamples)
  15166. {
  15167. for (int i = numDestChannels; --i >= 0;)
  15168. if (destSamples[i] != 0)
  15169. zeromem (destSamples[i] + startOffsetInDestBuffer, sizeof (int) * numSamples);
  15170. numSamples = (int) samplesAvailable;
  15171. }
  15172. if (numSamples <= 0)
  15173. return true;
  15174. input->setPosition (dataChunkStart + startSampleInFile * bytesPerFrame);
  15175. const int tempBufSize = 480 * 3 * 4; // (keep this a multiple of 3)
  15176. char tempBuffer [tempBufSize];
  15177. while (numSamples > 0)
  15178. {
  15179. int* left = destSamples[0];
  15180. if (left != 0)
  15181. left += startOffsetInDestBuffer;
  15182. int* right = numDestChannels > 1 ? destSamples[1] : 0;
  15183. if (right != 0)
  15184. right += startOffsetInDestBuffer;
  15185. const int numThisTime = jmin (tempBufSize / bytesPerFrame, numSamples);
  15186. const int bytesRead = input->read (tempBuffer, numThisTime * bytesPerFrame);
  15187. if (bytesRead < numThisTime * bytesPerFrame)
  15188. zeromem (tempBuffer + bytesRead, numThisTime * bytesPerFrame - bytesRead);
  15189. if (bitsPerSample == 16)
  15190. {
  15191. if (littleEndian)
  15192. {
  15193. const short* src = reinterpret_cast <const short*> (tempBuffer);
  15194. if (numChannels > 1)
  15195. {
  15196. if (left == 0)
  15197. {
  15198. for (int i = numThisTime; --i >= 0;)
  15199. {
  15200. *right++ = (int) ByteOrder::swapIfBigEndian ((unsigned short) *src++) << 16;
  15201. ++src;
  15202. }
  15203. }
  15204. else if (right == 0)
  15205. {
  15206. for (int i = numThisTime; --i >= 0;)
  15207. {
  15208. ++src;
  15209. *left++ = (int) ByteOrder::swapIfBigEndian ((unsigned short) *src++) << 16;
  15210. }
  15211. }
  15212. else
  15213. {
  15214. for (int i = numThisTime; --i >= 0;)
  15215. {
  15216. *left++ = (int) ByteOrder::swapIfBigEndian ((unsigned short) *src++) << 16;
  15217. *right++ = (int) ByteOrder::swapIfBigEndian ((unsigned short) *src++) << 16;
  15218. }
  15219. }
  15220. }
  15221. else
  15222. {
  15223. for (int i = numThisTime; --i >= 0;)
  15224. {
  15225. *left++ = (int) ByteOrder::swapIfBigEndian ((unsigned short) *src++) << 16;
  15226. }
  15227. }
  15228. }
  15229. else
  15230. {
  15231. const char* src = tempBuffer;
  15232. if (numChannels > 1)
  15233. {
  15234. if (left == 0)
  15235. {
  15236. for (int i = numThisTime; --i >= 0;)
  15237. {
  15238. *right++ = ByteOrder::bigEndianShort (src) << 16;
  15239. src += 4;
  15240. }
  15241. }
  15242. else if (right == 0)
  15243. {
  15244. for (int i = numThisTime; --i >= 0;)
  15245. {
  15246. src += 2;
  15247. *left++ = ByteOrder::bigEndianShort (src) << 16;
  15248. src += 2;
  15249. }
  15250. }
  15251. else
  15252. {
  15253. for (int i = numThisTime; --i >= 0;)
  15254. {
  15255. *left++ = ByteOrder::bigEndianShort (src) << 16;
  15256. src += 2;
  15257. *right++ = ByteOrder::bigEndianShort (src) << 16;
  15258. src += 2;
  15259. }
  15260. }
  15261. }
  15262. else
  15263. {
  15264. for (int i = numThisTime; --i >= 0;)
  15265. {
  15266. *left++ = ByteOrder::bigEndianShort (src) << 16;
  15267. src += 2;
  15268. }
  15269. }
  15270. }
  15271. }
  15272. else if (bitsPerSample == 24)
  15273. {
  15274. const char* src = (const char*)tempBuffer;
  15275. if (littleEndian)
  15276. {
  15277. if (numChannels > 1)
  15278. {
  15279. if (left == 0)
  15280. {
  15281. for (int i = numThisTime; --i >= 0;)
  15282. {
  15283. *right++ = ByteOrder::littleEndian24Bit (src) << 8;
  15284. src += 6;
  15285. }
  15286. }
  15287. else if (right == 0)
  15288. {
  15289. for (int i = numThisTime; --i >= 0;)
  15290. {
  15291. src += 3;
  15292. *left++ = ByteOrder::littleEndian24Bit (src) << 8;
  15293. src += 3;
  15294. }
  15295. }
  15296. else
  15297. {
  15298. for (int i = numThisTime; --i >= 0;)
  15299. {
  15300. *left++ = ByteOrder::littleEndian24Bit (src) << 8;
  15301. src += 3;
  15302. *right++ = ByteOrder::littleEndian24Bit (src) << 8;
  15303. src += 3;
  15304. }
  15305. }
  15306. }
  15307. else
  15308. {
  15309. for (int i = numThisTime; --i >= 0;)
  15310. {
  15311. *left++ = ByteOrder::littleEndian24Bit (src) << 8;
  15312. src += 3;
  15313. }
  15314. }
  15315. }
  15316. else
  15317. {
  15318. if (numChannels > 1)
  15319. {
  15320. if (left == 0)
  15321. {
  15322. for (int i = numThisTime; --i >= 0;)
  15323. {
  15324. *right++ = ByteOrder::bigEndian24Bit (src) << 8;
  15325. src += 6;
  15326. }
  15327. }
  15328. else if (right == 0)
  15329. {
  15330. for (int i = numThisTime; --i >= 0;)
  15331. {
  15332. src += 3;
  15333. *left++ = ByteOrder::bigEndian24Bit (src) << 8;
  15334. src += 3;
  15335. }
  15336. }
  15337. else
  15338. {
  15339. for (int i = numThisTime; --i >= 0;)
  15340. {
  15341. *left++ = ByteOrder::bigEndian24Bit (src) << 8;
  15342. src += 3;
  15343. *right++ = ByteOrder::bigEndian24Bit (src) << 8;
  15344. src += 3;
  15345. }
  15346. }
  15347. }
  15348. else
  15349. {
  15350. for (int i = numThisTime; --i >= 0;)
  15351. {
  15352. *left++ = ByteOrder::bigEndian24Bit (src) << 8;
  15353. src += 3;
  15354. }
  15355. }
  15356. }
  15357. }
  15358. else if (bitsPerSample == 32)
  15359. {
  15360. const unsigned int* src = reinterpret_cast <const unsigned int*> (tempBuffer);
  15361. unsigned int* l = reinterpret_cast <unsigned int*> (left);
  15362. unsigned int* r = reinterpret_cast <unsigned int*> (right);
  15363. if (littleEndian)
  15364. {
  15365. if (numChannels > 1)
  15366. {
  15367. if (l == 0)
  15368. {
  15369. for (int i = numThisTime; --i >= 0;)
  15370. {
  15371. ++src;
  15372. *r++ = ByteOrder::swapIfBigEndian (*src++);
  15373. }
  15374. }
  15375. else if (r == 0)
  15376. {
  15377. for (int i = numThisTime; --i >= 0;)
  15378. {
  15379. *l++ = ByteOrder::swapIfBigEndian (*src++);
  15380. ++src;
  15381. }
  15382. }
  15383. else
  15384. {
  15385. for (int i = numThisTime; --i >= 0;)
  15386. {
  15387. *l++ = ByteOrder::swapIfBigEndian (*src++);
  15388. *r++ = ByteOrder::swapIfBigEndian (*src++);
  15389. }
  15390. }
  15391. }
  15392. else
  15393. {
  15394. for (int i = numThisTime; --i >= 0;)
  15395. {
  15396. *l++ = ByteOrder::swapIfBigEndian (*src++);
  15397. }
  15398. }
  15399. }
  15400. else
  15401. {
  15402. if (numChannels > 1)
  15403. {
  15404. if (l == 0)
  15405. {
  15406. for (int i = numThisTime; --i >= 0;)
  15407. {
  15408. ++src;
  15409. *r++ = ByteOrder::swapIfLittleEndian (*src++);
  15410. }
  15411. }
  15412. else if (r == 0)
  15413. {
  15414. for (int i = numThisTime; --i >= 0;)
  15415. {
  15416. *l++ = ByteOrder::swapIfLittleEndian (*src++);
  15417. ++src;
  15418. }
  15419. }
  15420. else
  15421. {
  15422. for (int i = numThisTime; --i >= 0;)
  15423. {
  15424. *l++ = ByteOrder::swapIfLittleEndian (*src++);
  15425. *r++ = ByteOrder::swapIfLittleEndian (*src++);
  15426. }
  15427. }
  15428. }
  15429. else
  15430. {
  15431. for (int i = numThisTime; --i >= 0;)
  15432. {
  15433. *l++ = ByteOrder::swapIfLittleEndian (*src++);
  15434. }
  15435. }
  15436. }
  15437. left = reinterpret_cast <int*> (l);
  15438. right = reinterpret_cast <int*> (r);
  15439. }
  15440. else if (bitsPerSample == 8)
  15441. {
  15442. const char* src = tempBuffer;
  15443. if (numChannels > 1)
  15444. {
  15445. if (left == 0)
  15446. {
  15447. for (int i = numThisTime; --i >= 0;)
  15448. {
  15449. *right++ = ((int) *src++) << 24;
  15450. ++src;
  15451. }
  15452. }
  15453. else if (right == 0)
  15454. {
  15455. for (int i = numThisTime; --i >= 0;)
  15456. {
  15457. ++src;
  15458. *left++ = ((int) *src++) << 24;
  15459. }
  15460. }
  15461. else
  15462. {
  15463. for (int i = numThisTime; --i >= 0;)
  15464. {
  15465. *left++ = ((int) *src++) << 24;
  15466. *right++ = ((int) *src++) << 24;
  15467. }
  15468. }
  15469. }
  15470. else
  15471. {
  15472. for (int i = numThisTime; --i >= 0;)
  15473. {
  15474. *left++ = ((int) *src++) << 24;
  15475. }
  15476. }
  15477. }
  15478. startOffsetInDestBuffer += numThisTime;
  15479. numSamples -= numThisTime;
  15480. }
  15481. if (numSamples > 0)
  15482. {
  15483. for (int i = numDestChannels; --i >= 0;)
  15484. if (destSamples[i] != 0)
  15485. zeromem (destSamples[i] + startOffsetInDestBuffer,
  15486. sizeof (int) * numSamples);
  15487. }
  15488. return true;
  15489. }
  15490. juce_UseDebuggingNewOperator
  15491. private:
  15492. AiffAudioFormatReader (const AiffAudioFormatReader&);
  15493. AiffAudioFormatReader& operator= (const AiffAudioFormatReader&);
  15494. static inline int chunkName (const char* const name) { return (int) ByteOrder::littleEndianInt (name); }
  15495. };
  15496. class AiffAudioFormatWriter : public AudioFormatWriter
  15497. {
  15498. MemoryBlock tempBlock;
  15499. uint32 lengthInSamples, bytesWritten;
  15500. int64 headerPosition;
  15501. bool writeFailed;
  15502. static inline int chunkName (const char* const name) { return (int) ByteOrder::littleEndianInt (name); }
  15503. AiffAudioFormatWriter (const AiffAudioFormatWriter&);
  15504. AiffAudioFormatWriter& operator= (const AiffAudioFormatWriter&);
  15505. void writeHeader()
  15506. {
  15507. const bool couldSeekOk = output->setPosition (headerPosition);
  15508. (void) couldSeekOk;
  15509. // if this fails, you've given it an output stream that can't seek! It needs
  15510. // to be able to seek back to write the header
  15511. jassert (couldSeekOk);
  15512. const int headerLen = 54;
  15513. int audioBytes = lengthInSamples * ((bitsPerSample * numChannels) / 8);
  15514. audioBytes += (audioBytes & 1);
  15515. output->writeInt (chunkName ("FORM"));
  15516. output->writeIntBigEndian (headerLen + audioBytes - 8);
  15517. output->writeInt (chunkName ("AIFF"));
  15518. output->writeInt (chunkName ("COMM"));
  15519. output->writeIntBigEndian (18);
  15520. output->writeShortBigEndian ((short) numChannels);
  15521. output->writeIntBigEndian (lengthInSamples);
  15522. output->writeShortBigEndian ((short) bitsPerSample);
  15523. uint8 sampleRateBytes[10];
  15524. zeromem (sampleRateBytes, 10);
  15525. if (sampleRate <= 1)
  15526. {
  15527. sampleRateBytes[0] = 0x3f;
  15528. sampleRateBytes[1] = 0xff;
  15529. sampleRateBytes[2] = 0x80;
  15530. }
  15531. else
  15532. {
  15533. int mask = 0x40000000;
  15534. sampleRateBytes[0] = 0x40;
  15535. if (sampleRate >= mask)
  15536. {
  15537. jassertfalse
  15538. sampleRateBytes[1] = 0x1d;
  15539. }
  15540. else
  15541. {
  15542. int n = (int) sampleRate;
  15543. int i;
  15544. for (i = 0; i <= 32 ; ++i)
  15545. {
  15546. if ((n & mask) != 0)
  15547. break;
  15548. mask >>= 1;
  15549. }
  15550. n = n << (i + 1);
  15551. sampleRateBytes[1] = (uint8) (29 - i);
  15552. sampleRateBytes[2] = (uint8) ((n >> 24) & 0xff);
  15553. sampleRateBytes[3] = (uint8) ((n >> 16) & 0xff);
  15554. sampleRateBytes[4] = (uint8) ((n >> 8) & 0xff);
  15555. sampleRateBytes[5] = (uint8) (n & 0xff);
  15556. }
  15557. }
  15558. output->write (sampleRateBytes, 10);
  15559. output->writeInt (chunkName ("SSND"));
  15560. output->writeIntBigEndian (audioBytes + 8);
  15561. output->writeInt (0);
  15562. output->writeInt (0);
  15563. jassert (output->getPosition() == headerLen);
  15564. }
  15565. public:
  15566. AiffAudioFormatWriter (OutputStream* out,
  15567. const double sampleRate_,
  15568. const unsigned int chans,
  15569. const int bits)
  15570. : AudioFormatWriter (out,
  15571. TRANS (aiffFormatName),
  15572. sampleRate_,
  15573. chans,
  15574. bits),
  15575. lengthInSamples (0),
  15576. bytesWritten (0),
  15577. writeFailed (false)
  15578. {
  15579. headerPosition = out->getPosition();
  15580. writeHeader();
  15581. }
  15582. ~AiffAudioFormatWriter()
  15583. {
  15584. if ((bytesWritten & 1) != 0)
  15585. output->writeByte (0);
  15586. writeHeader();
  15587. }
  15588. bool write (const int** data, int numSamples)
  15589. {
  15590. if (writeFailed)
  15591. return false;
  15592. const int bytes = numChannels * numSamples * bitsPerSample / 8;
  15593. tempBlock.ensureSize (bytes, false);
  15594. char* buffer = static_cast <char*> (tempBlock.getData());
  15595. const int* left = data[0];
  15596. const int* right = data[1];
  15597. if (right == 0)
  15598. right = left;
  15599. if (bitsPerSample == 16)
  15600. {
  15601. short* b = reinterpret_cast <short*> (buffer);
  15602. if (numChannels > 1)
  15603. {
  15604. for (int i = numSamples; --i >= 0;)
  15605. {
  15606. *b++ = (short) ByteOrder::swapIfLittleEndian ((uint16) (*left++ >> 16));
  15607. *b++ = (short) ByteOrder::swapIfLittleEndian ((uint16) (*right++ >> 16));
  15608. }
  15609. }
  15610. else
  15611. {
  15612. for (int i = numSamples; --i >= 0;)
  15613. {
  15614. *b++ = (short) ByteOrder::swapIfLittleEndian ((uint16) (*left++ >> 16));
  15615. }
  15616. }
  15617. }
  15618. else if (bitsPerSample == 24)
  15619. {
  15620. char* b = buffer;
  15621. if (numChannels > 1)
  15622. {
  15623. for (int i = numSamples; --i >= 0;)
  15624. {
  15625. ByteOrder::bigEndian24BitToChars (*left++ >> 8, b);
  15626. b += 3;
  15627. ByteOrder::bigEndian24BitToChars (*right++ >> 8, b);
  15628. b += 3;
  15629. }
  15630. }
  15631. else
  15632. {
  15633. for (int i = numSamples; --i >= 0;)
  15634. {
  15635. ByteOrder::bigEndian24BitToChars (*left++ >> 8, b);
  15636. b += 3;
  15637. }
  15638. }
  15639. }
  15640. else if (bitsPerSample == 32)
  15641. {
  15642. uint32* b = reinterpret_cast <uint32*> (buffer);
  15643. if (numChannels > 1)
  15644. {
  15645. for (int i = numSamples; --i >= 0;)
  15646. {
  15647. *b++ = ByteOrder::swapIfLittleEndian ((uint32) *left++);
  15648. *b++ = ByteOrder::swapIfLittleEndian ((uint32) *right++);
  15649. }
  15650. }
  15651. else
  15652. {
  15653. for (int i = numSamples; --i >= 0;)
  15654. {
  15655. *b++ = ByteOrder::swapIfLittleEndian ((uint32) *left++);
  15656. }
  15657. }
  15658. }
  15659. else if (bitsPerSample == 8)
  15660. {
  15661. char* b = buffer;
  15662. if (numChannels > 1)
  15663. {
  15664. for (int i = numSamples; --i >= 0;)
  15665. {
  15666. *b++ = (char) (*left++ >> 24);
  15667. *b++ = (char) (*right++ >> 24);
  15668. }
  15669. }
  15670. else
  15671. {
  15672. for (int i = numSamples; --i >= 0;)
  15673. {
  15674. *b++ = (char) (*left++ >> 24);
  15675. }
  15676. }
  15677. }
  15678. if (bytesWritten + bytes >= (uint32) 0xfff00000
  15679. || ! output->write (buffer, bytes))
  15680. {
  15681. // failed to write to disk, so let's try writing the header.
  15682. // If it's just run out of disk space, then if it does manage
  15683. // to write the header, we'll still have a useable file..
  15684. writeHeader();
  15685. writeFailed = true;
  15686. return false;
  15687. }
  15688. else
  15689. {
  15690. bytesWritten += bytes;
  15691. lengthInSamples += numSamples;
  15692. return true;
  15693. }
  15694. }
  15695. juce_UseDebuggingNewOperator
  15696. };
  15697. AiffAudioFormat::AiffAudioFormat()
  15698. : AudioFormat (TRANS (aiffFormatName), StringArray (aiffExtensions))
  15699. {
  15700. }
  15701. AiffAudioFormat::~AiffAudioFormat()
  15702. {
  15703. }
  15704. const Array <int> AiffAudioFormat::getPossibleSampleRates()
  15705. {
  15706. const int rates[] = { 22050, 32000, 44100, 48000, 88200, 96000, 176400, 192000, 0 };
  15707. return Array <int> (rates);
  15708. }
  15709. const Array <int> AiffAudioFormat::getPossibleBitDepths()
  15710. {
  15711. const int depths[] = { 8, 16, 24, 0 };
  15712. return Array <int> (depths);
  15713. }
  15714. bool AiffAudioFormat::canDoStereo()
  15715. {
  15716. return true;
  15717. }
  15718. bool AiffAudioFormat::canDoMono()
  15719. {
  15720. return true;
  15721. }
  15722. #if JUCE_MAC
  15723. bool AiffAudioFormat::canHandleFile (const File& f)
  15724. {
  15725. if (AudioFormat::canHandleFile (f))
  15726. return true;
  15727. const OSType type = PlatformUtilities::getTypeOfFile (f.getFullPathName());
  15728. return type == 'AIFF' || type == 'AIFC'
  15729. || type == 'aiff' || type == 'aifc';
  15730. }
  15731. #endif
  15732. AudioFormatReader* AiffAudioFormat::createReaderFor (InputStream* sourceStream,
  15733. const bool deleteStreamIfOpeningFails)
  15734. {
  15735. ScopedPointer <AiffAudioFormatReader> w (new AiffAudioFormatReader (sourceStream));
  15736. if (w->sampleRate != 0)
  15737. return w.release();
  15738. if (! deleteStreamIfOpeningFails)
  15739. w->input = 0;
  15740. return 0;
  15741. }
  15742. AudioFormatWriter* AiffAudioFormat::createWriterFor (OutputStream* out,
  15743. double sampleRate,
  15744. unsigned int chans,
  15745. int bitsPerSample,
  15746. const StringPairArray& /*metadataValues*/,
  15747. int /*qualityOptionIndex*/)
  15748. {
  15749. if (getPossibleBitDepths().contains (bitsPerSample))
  15750. {
  15751. return new AiffAudioFormatWriter (out,
  15752. sampleRate,
  15753. chans,
  15754. bitsPerSample);
  15755. }
  15756. return 0;
  15757. }
  15758. END_JUCE_NAMESPACE
  15759. /*** End of inlined file: juce_AiffAudioFormat.cpp ***/
  15760. /*** Start of inlined file: juce_AudioCDReader.cpp ***/
  15761. BEGIN_JUCE_NAMESPACE
  15762. #if JUCE_MAC && JUCE_USE_CDREADER
  15763. // Mac version doesn't need any native code because it's all done with files..
  15764. // Windows + Linux versions are in the platform-dependent code sections.
  15765. static void findCDs (Array<File>& cds)
  15766. {
  15767. File volumes ("/Volumes");
  15768. volumes.findChildFiles (cds, File::findDirectories, false);
  15769. for (int i = cds.size(); --i >= 0;)
  15770. if (! cds.getReference(i).getChildFile (".TOC.plist").exists())
  15771. cds.remove (i);
  15772. }
  15773. const StringArray AudioCDReader::getAvailableCDNames()
  15774. {
  15775. Array<File> cds;
  15776. findCDs (cds);
  15777. StringArray names;
  15778. for (int i = 0; i < cds.size(); ++i)
  15779. names.add (cds.getReference(i).getFileName());
  15780. return names;
  15781. }
  15782. AudioCDReader* AudioCDReader::createReaderForCD (const int index)
  15783. {
  15784. Array<File> cds;
  15785. findCDs (cds);
  15786. if (cds[index] != File::nonexistent)
  15787. return new AudioCDReader (cds[index]);
  15788. else
  15789. return 0;
  15790. }
  15791. AudioCDReader::AudioCDReader (const File& volume)
  15792. : AudioFormatReader (0, "CD Audio"),
  15793. volumeDir (volume),
  15794. currentReaderTrack (-1),
  15795. reader (0)
  15796. {
  15797. sampleRate = 44100.0;
  15798. bitsPerSample = 16;
  15799. numChannels = 2;
  15800. usesFloatingPointData = false;
  15801. refreshTrackLengths();
  15802. }
  15803. AudioCDReader::~AudioCDReader()
  15804. {
  15805. }
  15806. static int getTrackNumber (const File& file)
  15807. {
  15808. return file.getFileName()
  15809. .initialSectionContainingOnly ("0123456789")
  15810. .getIntValue();
  15811. }
  15812. int AudioCDReader::compareElements (const File& first, const File& second)
  15813. {
  15814. const int firstTrack = getTrackNumber (first);
  15815. const int secondTrack = getTrackNumber (second);
  15816. jassert (firstTrack > 0 && secondTrack > 0);
  15817. return firstTrack - secondTrack;
  15818. }
  15819. void AudioCDReader::refreshTrackLengths()
  15820. {
  15821. tracks.clear();
  15822. trackStartSamples.clear();
  15823. volumeDir.findChildFiles (tracks, File::findFiles | File::ignoreHiddenFiles, false, "*.aiff");
  15824. tracks.sort (*this);
  15825. AiffAudioFormat format;
  15826. int sample = 0;
  15827. for (int i = 0; i < tracks.size(); ++i)
  15828. {
  15829. trackStartSamples.add (sample);
  15830. FileInputStream* const in = tracks.getReference(i).createInputStream();
  15831. if (in != 0)
  15832. {
  15833. ScopedPointer <AudioFormatReader> r (format.createReaderFor (in, true));
  15834. if (r != 0)
  15835. sample += (int) r->lengthInSamples;
  15836. }
  15837. }
  15838. trackStartSamples.add (sample);
  15839. lengthInSamples = sample;
  15840. }
  15841. bool AudioCDReader::readSamples (int** destSamples, int numDestChannels, int startOffsetInDestBuffer,
  15842. int64 startSampleInFile, int numSamples)
  15843. {
  15844. while (numSamples > 0)
  15845. {
  15846. int track = -1;
  15847. for (int i = 0; i < trackStartSamples.size() - 1; ++i)
  15848. {
  15849. if (startSampleInFile < trackStartSamples.getUnchecked (i + 1))
  15850. {
  15851. track = i;
  15852. break;
  15853. }
  15854. }
  15855. if (track < 0)
  15856. return false;
  15857. if (track != currentReaderTrack)
  15858. {
  15859. reader = 0;
  15860. FileInputStream* const in = tracks [track].createInputStream();
  15861. if (in != 0)
  15862. {
  15863. BufferedInputStream* const bin = new BufferedInputStream (in, 65536, true);
  15864. AiffAudioFormat format;
  15865. reader = format.createReaderFor (bin, true);
  15866. if (reader == 0)
  15867. currentReaderTrack = -1;
  15868. else
  15869. currentReaderTrack = track;
  15870. }
  15871. }
  15872. if (reader == 0)
  15873. return false;
  15874. const int startPos = (int) (startSampleInFile - trackStartSamples.getUnchecked (track));
  15875. const int numAvailable = (int) jmin ((int64) numSamples, reader->lengthInSamples - startPos);
  15876. reader->readSamples (destSamples, numDestChannels, startOffsetInDestBuffer, startPos, numAvailable);
  15877. numSamples -= numAvailable;
  15878. startSampleInFile += numAvailable;
  15879. }
  15880. return true;
  15881. }
  15882. bool AudioCDReader::isCDStillPresent() const
  15883. {
  15884. return volumeDir.exists();
  15885. }
  15886. int AudioCDReader::getNumTracks() const
  15887. {
  15888. return tracks.size();
  15889. }
  15890. int AudioCDReader::getPositionOfTrackStart (int trackNum) const
  15891. {
  15892. return trackStartSamples [trackNum];
  15893. }
  15894. bool AudioCDReader::isTrackAudio (int trackNum) const
  15895. {
  15896. return tracks [trackNum] != File::nonexistent;
  15897. }
  15898. void AudioCDReader::enableIndexScanning (bool b)
  15899. {
  15900. // any way to do this on a Mac??
  15901. }
  15902. int AudioCDReader::getLastIndex() const
  15903. {
  15904. return 0;
  15905. }
  15906. const Array <int> AudioCDReader::findIndexesInTrack (const int trackNumber)
  15907. {
  15908. return Array <int>();
  15909. }
  15910. int AudioCDReader::getCDDBId()
  15911. {
  15912. return 0; //xxx
  15913. }
  15914. #endif
  15915. END_JUCE_NAMESPACE
  15916. /*** End of inlined file: juce_AudioCDReader.cpp ***/
  15917. /*** Start of inlined file: juce_AudioFormat.cpp ***/
  15918. BEGIN_JUCE_NAMESPACE
  15919. AudioFormatReader::AudioFormatReader (InputStream* const in,
  15920. const String& formatName_)
  15921. : sampleRate (0),
  15922. bitsPerSample (0),
  15923. lengthInSamples (0),
  15924. numChannels (0),
  15925. usesFloatingPointData (false),
  15926. input (in),
  15927. formatName (formatName_)
  15928. {
  15929. }
  15930. AudioFormatReader::~AudioFormatReader()
  15931. {
  15932. delete input;
  15933. }
  15934. bool AudioFormatReader::read (int** destSamples,
  15935. int numDestChannels,
  15936. int64 startSampleInSource,
  15937. int numSamplesToRead,
  15938. const bool fillLeftoverChannelsWithCopies)
  15939. {
  15940. jassert (numDestChannels > 0); // you have to actually give this some channels to work with!
  15941. int startOffsetInDestBuffer = 0;
  15942. if (startSampleInSource < 0)
  15943. {
  15944. const int silence = (int) jmin (-startSampleInSource, (int64) numSamplesToRead);
  15945. for (int i = numDestChannels; --i >= 0;)
  15946. if (destSamples[i] != 0)
  15947. zeromem (destSamples[i], sizeof (int) * silence);
  15948. startOffsetInDestBuffer += silence;
  15949. numSamplesToRead -= silence;
  15950. startSampleInSource = 0;
  15951. }
  15952. if (numSamplesToRead <= 0)
  15953. return true;
  15954. if (! readSamples (destSamples, jmin ((int) numChannels, numDestChannels), startOffsetInDestBuffer,
  15955. startSampleInSource, numSamplesToRead))
  15956. return false;
  15957. if (numDestChannels > (int) numChannels)
  15958. {
  15959. if (fillLeftoverChannelsWithCopies)
  15960. {
  15961. int* lastFullChannel = destSamples[0];
  15962. for (int i = numDestChannels; --i > 0;)
  15963. {
  15964. if (destSamples[i] != 0)
  15965. {
  15966. lastFullChannel = destSamples[i];
  15967. break;
  15968. }
  15969. }
  15970. if (lastFullChannel != 0)
  15971. for (int i = numChannels; i < numDestChannels; ++i)
  15972. if (destSamples[i] != 0)
  15973. memcpy (destSamples[i], lastFullChannel, sizeof (int) * numSamplesToRead);
  15974. }
  15975. else
  15976. {
  15977. for (int i = numChannels; i < numDestChannels; ++i)
  15978. if (destSamples[i] != 0)
  15979. zeromem (destSamples[i], sizeof (int) * numSamplesToRead);
  15980. }
  15981. }
  15982. return true;
  15983. }
  15984. static void findAudioBufferMaxMin (const float* const buffer, const int num, float& maxVal, float& minVal) throw()
  15985. {
  15986. float mn = buffer[0];
  15987. float mx = mn;
  15988. for (int i = 1; i < num; ++i)
  15989. {
  15990. const float s = buffer[i];
  15991. if (s > mx) mx = s;
  15992. if (s < mn) mn = s;
  15993. }
  15994. maxVal = mx;
  15995. minVal = mn;
  15996. }
  15997. void AudioFormatReader::readMaxLevels (int64 startSampleInFile,
  15998. int64 numSamples,
  15999. float& lowestLeft, float& highestLeft,
  16000. float& lowestRight, float& highestRight)
  16001. {
  16002. if (numSamples <= 0)
  16003. {
  16004. lowestLeft = 0;
  16005. lowestRight = 0;
  16006. highestLeft = 0;
  16007. highestRight = 0;
  16008. return;
  16009. }
  16010. const int bufferSize = (int) jmin (numSamples, (int64) 4096);
  16011. MemoryBlock tempSpace (bufferSize * sizeof (int) * 2 + 64);
  16012. int* tempBuffer[3];
  16013. tempBuffer[0] = (int*) tempSpace.getData();
  16014. tempBuffer[1] = ((int*) tempSpace.getData()) + bufferSize;
  16015. tempBuffer[2] = 0;
  16016. if (usesFloatingPointData)
  16017. {
  16018. float lmin = 1.0e6f;
  16019. float lmax = -lmin;
  16020. float rmin = lmin;
  16021. float rmax = lmax;
  16022. while (numSamples > 0)
  16023. {
  16024. const int numToDo = (int) jmin (numSamples, (int64) bufferSize);
  16025. read ((int**) tempBuffer, 2, startSampleInFile, numToDo, false);
  16026. numSamples -= numToDo;
  16027. startSampleInFile += numToDo;
  16028. float bufmin, bufmax;
  16029. findAudioBufferMaxMin ((float*) tempBuffer[0], numToDo, bufmax, bufmin);
  16030. lmin = jmin (lmin, bufmin);
  16031. lmax = jmax (lmax, bufmax);
  16032. if (numChannels > 1)
  16033. {
  16034. findAudioBufferMaxMin ((float*) tempBuffer[1], numToDo, bufmax, bufmin);
  16035. rmin = jmin (rmin, bufmin);
  16036. rmax = jmax (rmax, bufmax);
  16037. }
  16038. }
  16039. if (numChannels <= 1)
  16040. {
  16041. rmax = lmax;
  16042. rmin = lmin;
  16043. }
  16044. lowestLeft = lmin;
  16045. highestLeft = lmax;
  16046. lowestRight = rmin;
  16047. highestRight = rmax;
  16048. }
  16049. else
  16050. {
  16051. int lmax = std::numeric_limits<int>::min();
  16052. int lmin = std::numeric_limits<int>::max();
  16053. int rmax = std::numeric_limits<int>::min();
  16054. int rmin = std::numeric_limits<int>::max();
  16055. while (numSamples > 0)
  16056. {
  16057. const int numToDo = (int) jmin (numSamples, (int64) bufferSize);
  16058. read ((int**) tempBuffer, 2, startSampleInFile, numToDo, false);
  16059. numSamples -= numToDo;
  16060. startSampleInFile += numToDo;
  16061. for (int j = numChannels; --j >= 0;)
  16062. {
  16063. int bufMax = std::numeric_limits<int>::min();
  16064. int bufMin = std::numeric_limits<int>::max();
  16065. const int* const b = tempBuffer[j];
  16066. for (int i = 0; i < numToDo; ++i)
  16067. {
  16068. const int samp = b[i];
  16069. if (samp < bufMin)
  16070. bufMin = samp;
  16071. if (samp > bufMax)
  16072. bufMax = samp;
  16073. }
  16074. if (j == 0)
  16075. {
  16076. lmax = jmax (lmax, bufMax);
  16077. lmin = jmin (lmin, bufMin);
  16078. }
  16079. else
  16080. {
  16081. rmax = jmax (rmax, bufMax);
  16082. rmin = jmin (rmin, bufMin);
  16083. }
  16084. }
  16085. }
  16086. if (numChannels <= 1)
  16087. {
  16088. rmax = lmax;
  16089. rmin = lmin;
  16090. }
  16091. lowestLeft = lmin / (float) std::numeric_limits<int>::max();
  16092. highestLeft = lmax / (float) std::numeric_limits<int>::max();
  16093. lowestRight = rmin / (float) std::numeric_limits<int>::max();
  16094. highestRight = rmax / (float) std::numeric_limits<int>::max();
  16095. }
  16096. }
  16097. int64 AudioFormatReader::searchForLevel (int64 startSample,
  16098. int64 numSamplesToSearch,
  16099. const double magnitudeRangeMinimum,
  16100. const double magnitudeRangeMaximum,
  16101. const int minimumConsecutiveSamples)
  16102. {
  16103. if (numSamplesToSearch == 0)
  16104. return -1;
  16105. const int bufferSize = 4096;
  16106. MemoryBlock tempSpace (bufferSize * sizeof (int) * 2 + 64);
  16107. int* tempBuffer[3];
  16108. tempBuffer[0] = (int*) tempSpace.getData();
  16109. tempBuffer[1] = ((int*) tempSpace.getData()) + bufferSize;
  16110. tempBuffer[2] = 0;
  16111. int consecutive = 0;
  16112. int64 firstMatchPos = -1;
  16113. jassert (magnitudeRangeMaximum > magnitudeRangeMinimum);
  16114. const double doubleMin = jlimit (0.0, (double) std::numeric_limits<int>::max(), magnitudeRangeMinimum * std::numeric_limits<int>::max());
  16115. const double doubleMax = jlimit (doubleMin, (double) std::numeric_limits<int>::max(), magnitudeRangeMaximum * std::numeric_limits<int>::max());
  16116. const int intMagnitudeRangeMinimum = roundToInt (doubleMin);
  16117. const int intMagnitudeRangeMaximum = roundToInt (doubleMax);
  16118. while (numSamplesToSearch != 0)
  16119. {
  16120. const int numThisTime = (int) jmin (abs64 (numSamplesToSearch), (int64) bufferSize);
  16121. int64 bufferStart = startSample;
  16122. if (numSamplesToSearch < 0)
  16123. bufferStart -= numThisTime;
  16124. if (bufferStart >= (int) lengthInSamples)
  16125. break;
  16126. read ((int**) tempBuffer, 2, bufferStart, numThisTime, false);
  16127. int num = numThisTime;
  16128. while (--num >= 0)
  16129. {
  16130. if (numSamplesToSearch < 0)
  16131. --startSample;
  16132. bool matches = false;
  16133. const int index = (int) (startSample - bufferStart);
  16134. if (usesFloatingPointData)
  16135. {
  16136. const float sample1 = std::abs (((float*) tempBuffer[0]) [index]);
  16137. if (sample1 >= magnitudeRangeMinimum
  16138. && sample1 <= magnitudeRangeMaximum)
  16139. {
  16140. matches = true;
  16141. }
  16142. else if (numChannels > 1)
  16143. {
  16144. const float sample2 = std::abs (((float*) tempBuffer[1]) [index]);
  16145. matches = (sample2 >= magnitudeRangeMinimum
  16146. && sample2 <= magnitudeRangeMaximum);
  16147. }
  16148. }
  16149. else
  16150. {
  16151. const int sample1 = abs (tempBuffer[0] [index]);
  16152. if (sample1 >= intMagnitudeRangeMinimum
  16153. && sample1 <= intMagnitudeRangeMaximum)
  16154. {
  16155. matches = true;
  16156. }
  16157. else if (numChannels > 1)
  16158. {
  16159. const int sample2 = abs (tempBuffer[1][index]);
  16160. matches = (sample2 >= intMagnitudeRangeMinimum
  16161. && sample2 <= intMagnitudeRangeMaximum);
  16162. }
  16163. }
  16164. if (matches)
  16165. {
  16166. if (firstMatchPos < 0)
  16167. firstMatchPos = startSample;
  16168. if (++consecutive >= minimumConsecutiveSamples)
  16169. {
  16170. if (firstMatchPos < 0 || firstMatchPos >= lengthInSamples)
  16171. return -1;
  16172. return firstMatchPos;
  16173. }
  16174. }
  16175. else
  16176. {
  16177. consecutive = 0;
  16178. firstMatchPos = -1;
  16179. }
  16180. if (numSamplesToSearch > 0)
  16181. ++startSample;
  16182. }
  16183. if (numSamplesToSearch > 0)
  16184. numSamplesToSearch -= numThisTime;
  16185. else
  16186. numSamplesToSearch += numThisTime;
  16187. }
  16188. return -1;
  16189. }
  16190. AudioFormatWriter::AudioFormatWriter (OutputStream* const out,
  16191. const String& formatName_,
  16192. const double rate,
  16193. const unsigned int numChannels_,
  16194. const unsigned int bitsPerSample_)
  16195. : sampleRate (rate),
  16196. numChannels (numChannels_),
  16197. bitsPerSample (bitsPerSample_),
  16198. usesFloatingPointData (false),
  16199. output (out),
  16200. formatName (formatName_)
  16201. {
  16202. }
  16203. AudioFormatWriter::~AudioFormatWriter()
  16204. {
  16205. delete output;
  16206. }
  16207. bool AudioFormatWriter::writeFromAudioReader (AudioFormatReader& reader,
  16208. int64 startSample,
  16209. int64 numSamplesToRead)
  16210. {
  16211. const int bufferSize = 16384;
  16212. const int maxChans = 128;
  16213. AudioSampleBuffer tempBuffer (reader.numChannels, bufferSize);
  16214. int* buffers [maxChans];
  16215. for (int i = maxChans; --i >= 0;)
  16216. buffers[i] = 0;
  16217. if (numSamplesToRead < 0)
  16218. numSamplesToRead = reader.lengthInSamples;
  16219. while (numSamplesToRead > 0)
  16220. {
  16221. const int numToDo = (int) jmin (numSamplesToRead, (int64) bufferSize);
  16222. for (int i = tempBuffer.getNumChannels(); --i >= 0;)
  16223. buffers[i] = (int*) tempBuffer.getSampleData (i, 0);
  16224. if (! reader.read (buffers, maxChans, startSample, numToDo, false))
  16225. return false;
  16226. if (reader.usesFloatingPointData != isFloatingPoint())
  16227. {
  16228. int** bufferChan = buffers;
  16229. while (*bufferChan != 0)
  16230. {
  16231. int* b = *bufferChan++;
  16232. if (isFloatingPoint())
  16233. {
  16234. // int -> float
  16235. const double factor = 1.0 / std::numeric_limits<int>::max();
  16236. for (int i = 0; i < numToDo; ++i)
  16237. ((float*) b)[i] = (float) (factor * b[i]);
  16238. }
  16239. else
  16240. {
  16241. // float -> int
  16242. for (int i = 0; i < numToDo; ++i)
  16243. {
  16244. const double samp = *(const float*) b;
  16245. if (samp <= -1.0)
  16246. *b++ = std::numeric_limits<int>::min();
  16247. else if (samp >= 1.0)
  16248. *b++ = std::numeric_limits<int>::max();
  16249. else
  16250. *b++ = roundToInt (std::numeric_limits<int>::max() * samp);
  16251. }
  16252. }
  16253. }
  16254. }
  16255. if (! write ((const int**) buffers, numToDo))
  16256. return false;
  16257. numSamplesToRead -= numToDo;
  16258. startSample += numToDo;
  16259. }
  16260. return true;
  16261. }
  16262. bool AudioFormatWriter::writeFromAudioSource (AudioSource& source,
  16263. int numSamplesToRead,
  16264. const int samplesPerBlock)
  16265. {
  16266. const int maxChans = 128;
  16267. AudioSampleBuffer tempBuffer (getNumChannels(), samplesPerBlock);
  16268. int* buffers [maxChans];
  16269. while (numSamplesToRead > 0)
  16270. {
  16271. const int numToDo = jmin (numSamplesToRead, samplesPerBlock);
  16272. AudioSourceChannelInfo info;
  16273. info.buffer = &tempBuffer;
  16274. info.startSample = 0;
  16275. info.numSamples = numToDo;
  16276. info.clearActiveBufferRegion();
  16277. source.getNextAudioBlock (info);
  16278. int i;
  16279. for (i = maxChans; --i >= 0;)
  16280. buffers[i] = 0;
  16281. for (i = tempBuffer.getNumChannels(); --i >= 0;)
  16282. buffers[i] = (int*) tempBuffer.getSampleData (i, 0);
  16283. if (! isFloatingPoint())
  16284. {
  16285. int** bufferChan = buffers;
  16286. while (*bufferChan != 0)
  16287. {
  16288. int* b = *bufferChan++;
  16289. // float -> int
  16290. for (int j = numToDo; --j >= 0;)
  16291. {
  16292. const double samp = *(const float*) b;
  16293. if (samp <= -1.0)
  16294. *b++ = std::numeric_limits<int>::min();
  16295. else if (samp >= 1.0)
  16296. *b++ = std::numeric_limits<int>::max();
  16297. else
  16298. *b++ = roundToInt (std::numeric_limits<int>::max() * samp);
  16299. }
  16300. }
  16301. }
  16302. if (! write ((const int**) buffers, numToDo))
  16303. return false;
  16304. numSamplesToRead -= numToDo;
  16305. }
  16306. return true;
  16307. }
  16308. AudioFormat::AudioFormat (const String& name,
  16309. const StringArray& extensions)
  16310. : formatName (name),
  16311. fileExtensions (extensions)
  16312. {
  16313. }
  16314. AudioFormat::~AudioFormat()
  16315. {
  16316. }
  16317. const String& AudioFormat::getFormatName() const
  16318. {
  16319. return formatName;
  16320. }
  16321. const StringArray& AudioFormat::getFileExtensions() const
  16322. {
  16323. return fileExtensions;
  16324. }
  16325. bool AudioFormat::canHandleFile (const File& f)
  16326. {
  16327. for (int i = 0; i < fileExtensions.size(); ++i)
  16328. if (f.hasFileExtension (fileExtensions[i]))
  16329. return true;
  16330. return false;
  16331. }
  16332. bool AudioFormat::isCompressed()
  16333. {
  16334. return false;
  16335. }
  16336. const StringArray AudioFormat::getQualityOptions()
  16337. {
  16338. return StringArray();
  16339. }
  16340. END_JUCE_NAMESPACE
  16341. /*** End of inlined file: juce_AudioFormat.cpp ***/
  16342. /*** Start of inlined file: juce_AudioFormatManager.cpp ***/
  16343. BEGIN_JUCE_NAMESPACE
  16344. AudioFormatManager::AudioFormatManager()
  16345. : defaultFormatIndex (0)
  16346. {
  16347. }
  16348. AudioFormatManager::~AudioFormatManager()
  16349. {
  16350. clearFormats();
  16351. clearSingletonInstance();
  16352. }
  16353. juce_ImplementSingleton (AudioFormatManager);
  16354. void AudioFormatManager::registerFormat (AudioFormat* newFormat,
  16355. const bool makeThisTheDefaultFormat)
  16356. {
  16357. jassert (newFormat != 0);
  16358. if (newFormat != 0)
  16359. {
  16360. #if JUCE_DEBUG
  16361. for (int i = getNumKnownFormats(); --i >= 0;)
  16362. {
  16363. if (getKnownFormat (i)->getFormatName() == newFormat->getFormatName())
  16364. {
  16365. jassertfalse // trying to add the same format twice!
  16366. }
  16367. }
  16368. #endif
  16369. if (makeThisTheDefaultFormat)
  16370. defaultFormatIndex = getNumKnownFormats();
  16371. knownFormats.add (newFormat);
  16372. }
  16373. }
  16374. void AudioFormatManager::registerBasicFormats()
  16375. {
  16376. #if JUCE_MAC
  16377. registerFormat (new AiffAudioFormat(), true);
  16378. registerFormat (new WavAudioFormat(), false);
  16379. #else
  16380. registerFormat (new WavAudioFormat(), true);
  16381. registerFormat (new AiffAudioFormat(), false);
  16382. #endif
  16383. #if JUCE_USE_FLAC
  16384. registerFormat (new FlacAudioFormat(), false);
  16385. #endif
  16386. #if JUCE_USE_OGGVORBIS
  16387. registerFormat (new OggVorbisAudioFormat(), false);
  16388. #endif
  16389. }
  16390. void AudioFormatManager::clearFormats()
  16391. {
  16392. knownFormats.clear();
  16393. defaultFormatIndex = 0;
  16394. }
  16395. int AudioFormatManager::getNumKnownFormats() const
  16396. {
  16397. return knownFormats.size();
  16398. }
  16399. AudioFormat* AudioFormatManager::getKnownFormat (const int index) const
  16400. {
  16401. return knownFormats [index];
  16402. }
  16403. AudioFormat* AudioFormatManager::getDefaultFormat() const
  16404. {
  16405. return getKnownFormat (defaultFormatIndex);
  16406. }
  16407. AudioFormat* AudioFormatManager::findFormatForFileExtension (const String& fileExtension) const
  16408. {
  16409. String e (fileExtension);
  16410. if (! e.startsWithChar ('.'))
  16411. e = "." + e;
  16412. for (int i = 0; i < getNumKnownFormats(); ++i)
  16413. if (getKnownFormat(i)->getFileExtensions().contains (e, true))
  16414. return getKnownFormat(i);
  16415. return 0;
  16416. }
  16417. const String AudioFormatManager::getWildcardForAllFormats() const
  16418. {
  16419. StringArray allExtensions;
  16420. int i;
  16421. for (i = 0; i < getNumKnownFormats(); ++i)
  16422. allExtensions.addArray (getKnownFormat (i)->getFileExtensions());
  16423. allExtensions.trim();
  16424. allExtensions.removeEmptyStrings();
  16425. String s;
  16426. for (i = 0; i < allExtensions.size(); ++i)
  16427. {
  16428. s << '*';
  16429. if (! allExtensions[i].startsWithChar ('.'))
  16430. s << '.';
  16431. s << allExtensions[i];
  16432. if (i < allExtensions.size() - 1)
  16433. s << ';';
  16434. }
  16435. return s;
  16436. }
  16437. AudioFormatReader* AudioFormatManager::createReaderFor (const File& file)
  16438. {
  16439. // you need to actually register some formats before the manager can
  16440. // use them to open a file!
  16441. jassert (getNumKnownFormats() > 0);
  16442. for (int i = 0; i < getNumKnownFormats(); ++i)
  16443. {
  16444. AudioFormat* const af = getKnownFormat(i);
  16445. if (af->canHandleFile (file))
  16446. {
  16447. InputStream* const in = file.createInputStream();
  16448. if (in != 0)
  16449. {
  16450. AudioFormatReader* const r = af->createReaderFor (in, true);
  16451. if (r != 0)
  16452. return r;
  16453. }
  16454. }
  16455. }
  16456. return 0;
  16457. }
  16458. AudioFormatReader* AudioFormatManager::createReaderFor (InputStream* audioFileStream)
  16459. {
  16460. // you need to actually register some formats before the manager can
  16461. // use them to open a file!
  16462. jassert (getNumKnownFormats() > 0);
  16463. ScopedPointer <InputStream> in (audioFileStream);
  16464. if (in != 0)
  16465. {
  16466. const int64 originalStreamPos = in->getPosition();
  16467. for (int i = 0; i < getNumKnownFormats(); ++i)
  16468. {
  16469. AudioFormatReader* const r = getKnownFormat(i)->createReaderFor (in, false);
  16470. if (r != 0)
  16471. {
  16472. in.release();
  16473. return r;
  16474. }
  16475. in->setPosition (originalStreamPos);
  16476. // the stream that is passed-in must be capable of being repositioned so
  16477. // that all the formats can have a go at opening it.
  16478. jassert (in->getPosition() == originalStreamPos);
  16479. }
  16480. }
  16481. return 0;
  16482. }
  16483. END_JUCE_NAMESPACE
  16484. /*** End of inlined file: juce_AudioFormatManager.cpp ***/
  16485. /*** Start of inlined file: juce_AudioSubsectionReader.cpp ***/
  16486. BEGIN_JUCE_NAMESPACE
  16487. AudioSubsectionReader::AudioSubsectionReader (AudioFormatReader* const source_,
  16488. const int64 startSample_,
  16489. const int64 length_,
  16490. const bool deleteSourceWhenDeleted_)
  16491. : AudioFormatReader (0, source_->getFormatName()),
  16492. source (source_),
  16493. startSample (startSample_),
  16494. deleteSourceWhenDeleted (deleteSourceWhenDeleted_)
  16495. {
  16496. length = jmin (jmax ((int64) 0, source->lengthInSamples - startSample), length_);
  16497. sampleRate = source->sampleRate;
  16498. bitsPerSample = source->bitsPerSample;
  16499. lengthInSamples = length;
  16500. numChannels = source->numChannels;
  16501. usesFloatingPointData = source->usesFloatingPointData;
  16502. }
  16503. AudioSubsectionReader::~AudioSubsectionReader()
  16504. {
  16505. if (deleteSourceWhenDeleted)
  16506. delete source;
  16507. }
  16508. bool AudioSubsectionReader::readSamples (int** destSamples, int numDestChannels, int startOffsetInDestBuffer,
  16509. int64 startSampleInFile, int numSamples)
  16510. {
  16511. if (startSampleInFile + numSamples > length)
  16512. {
  16513. for (int i = numDestChannels; --i >= 0;)
  16514. if (destSamples[i] != 0)
  16515. zeromem (destSamples[i], sizeof (int) * numSamples);
  16516. numSamples = jmin (numSamples, (int) (length - startSampleInFile));
  16517. if (numSamples <= 0)
  16518. return true;
  16519. }
  16520. return source->readSamples (destSamples, numDestChannels, startOffsetInDestBuffer,
  16521. startSampleInFile + startSample, numSamples);
  16522. }
  16523. void AudioSubsectionReader::readMaxLevels (int64 startSampleInFile,
  16524. int64 numSamples,
  16525. float& lowestLeft,
  16526. float& highestLeft,
  16527. float& lowestRight,
  16528. float& highestRight)
  16529. {
  16530. startSampleInFile = jmax ((int64) 0, startSampleInFile);
  16531. numSamples = jmax ((int64) 0, jmin (numSamples, length - startSampleInFile));
  16532. source->readMaxLevels (startSampleInFile + startSample,
  16533. numSamples,
  16534. lowestLeft,
  16535. highestLeft,
  16536. lowestRight,
  16537. highestRight);
  16538. }
  16539. END_JUCE_NAMESPACE
  16540. /*** End of inlined file: juce_AudioSubsectionReader.cpp ***/
  16541. /*** Start of inlined file: juce_AudioThumbnail.cpp ***/
  16542. BEGIN_JUCE_NAMESPACE
  16543. const int timeBeforeDeletingReader = 2000;
  16544. struct AudioThumbnailDataFormat
  16545. {
  16546. char thumbnailMagic[4];
  16547. int samplesPerThumbSample;
  16548. int64 totalSamples; // source samples
  16549. int64 numFinishedSamples; // source samples
  16550. int numThumbnailSamples;
  16551. int numChannels;
  16552. int sampleRate;
  16553. char future[16];
  16554. char data[1];
  16555. void swapEndiannessIfNeeded() throw()
  16556. {
  16557. #if JUCE_BIG_ENDIAN
  16558. flip (samplesPerThumbSample);
  16559. flip (totalSamples);
  16560. flip (numFinishedSamples);
  16561. flip (numThumbnailSamples);
  16562. flip (numChannels);
  16563. flip (sampleRate);
  16564. #endif
  16565. }
  16566. private:
  16567. #if JUCE_BIG_ENDIAN
  16568. static void flip (int& n) { n = (int) ByteOrder::swap ((uint32) n); }
  16569. static void flip (int64& n) { n = (int64) ByteOrder::swap ((uint64) n); }
  16570. #endif
  16571. };
  16572. AudioThumbnail::AudioThumbnail (const int orginalSamplesPerThumbnailSample_,
  16573. AudioFormatManager& formatManagerToUse_,
  16574. AudioThumbnailCache& cacheToUse)
  16575. : formatManagerToUse (formatManagerToUse_),
  16576. cache (cacheToUse),
  16577. orginalSamplesPerThumbnailSample (orginalSamplesPerThumbnailSample_)
  16578. {
  16579. clear();
  16580. }
  16581. AudioThumbnail::~AudioThumbnail()
  16582. {
  16583. cache.removeThumbnail (this);
  16584. const ScopedLock sl (readerLock);
  16585. reader = 0;
  16586. }
  16587. void AudioThumbnail::setSource (InputSource* const newSource)
  16588. {
  16589. cache.removeThumbnail (this);
  16590. timerCallback(); // stops the timer and deletes the reader
  16591. source = newSource;
  16592. clear();
  16593. if (newSource != 0
  16594. && ! (cache.loadThumb (*this, newSource->hashCode())
  16595. && isFullyLoaded()))
  16596. {
  16597. {
  16598. const ScopedLock sl (readerLock);
  16599. reader = createReader();
  16600. }
  16601. if (reader != 0)
  16602. {
  16603. initialiseFromAudioFile (*reader);
  16604. cache.addThumbnail (this);
  16605. }
  16606. }
  16607. sendChangeMessage (this);
  16608. }
  16609. bool AudioThumbnail::useTimeSlice()
  16610. {
  16611. const ScopedLock sl (readerLock);
  16612. if (isFullyLoaded())
  16613. {
  16614. if (reader != 0)
  16615. startTimer (timeBeforeDeletingReader);
  16616. cache.removeThumbnail (this);
  16617. return false;
  16618. }
  16619. if (reader == 0)
  16620. reader = createReader();
  16621. if (reader != 0)
  16622. {
  16623. readNextBlockFromAudioFile (*reader);
  16624. stopTimer();
  16625. sendChangeMessage (this);
  16626. const bool justFinished = isFullyLoaded();
  16627. if (justFinished)
  16628. cache.storeThumb (*this, source->hashCode());
  16629. return ! justFinished;
  16630. }
  16631. return false;
  16632. }
  16633. AudioFormatReader* AudioThumbnail::createReader() const
  16634. {
  16635. if (source != 0)
  16636. {
  16637. InputStream* const audioFileStream = source->createInputStream();
  16638. if (audioFileStream != 0)
  16639. return formatManagerToUse.createReaderFor (audioFileStream);
  16640. }
  16641. return 0;
  16642. }
  16643. void AudioThumbnail::timerCallback()
  16644. {
  16645. stopTimer();
  16646. const ScopedLock sl (readerLock);
  16647. reader = 0;
  16648. }
  16649. void AudioThumbnail::clear()
  16650. {
  16651. data.setSize (sizeof (AudioThumbnailDataFormat) + 3);
  16652. AudioThumbnailDataFormat* const d = (AudioThumbnailDataFormat*) data.getData();
  16653. d->thumbnailMagic[0] = 'j';
  16654. d->thumbnailMagic[1] = 'a';
  16655. d->thumbnailMagic[2] = 't';
  16656. d->thumbnailMagic[3] = 'm';
  16657. d->samplesPerThumbSample = orginalSamplesPerThumbnailSample;
  16658. d->totalSamples = 0;
  16659. d->numFinishedSamples = 0;
  16660. d->numThumbnailSamples = 0;
  16661. d->numChannels = 0;
  16662. d->sampleRate = 0;
  16663. numSamplesCached = 0;
  16664. cacheNeedsRefilling = true;
  16665. }
  16666. void AudioThumbnail::loadFrom (InputStream& input)
  16667. {
  16668. const ScopedLock sl (readerLock);
  16669. data.setSize (0);
  16670. input.readIntoMemoryBlock (data);
  16671. AudioThumbnailDataFormat* const d = (AudioThumbnailDataFormat*) data.getData();
  16672. d->swapEndiannessIfNeeded();
  16673. if (! (d->thumbnailMagic[0] == 'j'
  16674. && d->thumbnailMagic[1] == 'a'
  16675. && d->thumbnailMagic[2] == 't'
  16676. && d->thumbnailMagic[3] == 'm'))
  16677. {
  16678. clear();
  16679. }
  16680. numSamplesCached = 0;
  16681. cacheNeedsRefilling = true;
  16682. }
  16683. void AudioThumbnail::saveTo (OutputStream& output) const
  16684. {
  16685. AudioThumbnailDataFormat* const d = (AudioThumbnailDataFormat*) data.getData();
  16686. d->swapEndiannessIfNeeded();
  16687. output.write (data.getData(), (int) data.getSize());
  16688. d->swapEndiannessIfNeeded();
  16689. }
  16690. bool AudioThumbnail::initialiseFromAudioFile (AudioFormatReader& fileReader)
  16691. {
  16692. AudioThumbnailDataFormat* d = (AudioThumbnailDataFormat*) data.getData();
  16693. d->totalSamples = fileReader.lengthInSamples;
  16694. d->numChannels = jmin ((uint32) 2, fileReader.numChannels);
  16695. d->numFinishedSamples = 0;
  16696. d->sampleRate = roundToInt (fileReader.sampleRate);
  16697. d->numThumbnailSamples = (int) (d->totalSamples / d->samplesPerThumbSample) + 1;
  16698. data.setSize (sizeof (AudioThumbnailDataFormat) + 3 + d->numThumbnailSamples * d->numChannels * 2);
  16699. d = (AudioThumbnailDataFormat*) data.getData();
  16700. zeromem (&(d->data[0]), d->numThumbnailSamples * d->numChannels * 2);
  16701. return d->totalSamples > 0;
  16702. }
  16703. bool AudioThumbnail::readNextBlockFromAudioFile (AudioFormatReader& fileReader)
  16704. {
  16705. AudioThumbnailDataFormat* const d = (AudioThumbnailDataFormat*) data.getData();
  16706. if (d->numFinishedSamples < d->totalSamples)
  16707. {
  16708. const int numToDo = (int) jmin ((int64) 65536, d->totalSamples - d->numFinishedSamples);
  16709. generateSection (fileReader,
  16710. d->numFinishedSamples,
  16711. numToDo);
  16712. d->numFinishedSamples += numToDo;
  16713. }
  16714. cacheNeedsRefilling = true;
  16715. return (d->numFinishedSamples < d->totalSamples);
  16716. }
  16717. int AudioThumbnail::getNumChannels() const throw()
  16718. {
  16719. const AudioThumbnailDataFormat* const d = (const AudioThumbnailDataFormat*) data.getData();
  16720. jassert (d != 0);
  16721. return d->numChannels;
  16722. }
  16723. double AudioThumbnail::getTotalLength() const throw()
  16724. {
  16725. const AudioThumbnailDataFormat* const d = (const AudioThumbnailDataFormat*) data.getData();
  16726. jassert (d != 0);
  16727. if (d->sampleRate > 0)
  16728. return d->totalSamples / (double)d->sampleRate;
  16729. else
  16730. return 0.0;
  16731. }
  16732. void AudioThumbnail::generateSection (AudioFormatReader& fileReader,
  16733. int64 startSample,
  16734. int numSamples)
  16735. {
  16736. AudioThumbnailDataFormat* const d = (AudioThumbnailDataFormat*) data.getData();
  16737. jassert (d != 0);
  16738. int firstDataPos = (int) (startSample / d->samplesPerThumbSample);
  16739. int lastDataPos = (int) ((startSample + numSamples) / d->samplesPerThumbSample);
  16740. char* l = getChannelData (0);
  16741. char* r = getChannelData (1);
  16742. for (int i = firstDataPos; i < lastDataPos; ++i)
  16743. {
  16744. const int sourceStart = i * d->samplesPerThumbSample;
  16745. const int sourceEnd = sourceStart + d->samplesPerThumbSample;
  16746. float lowestLeft, highestLeft, lowestRight, highestRight;
  16747. fileReader.readMaxLevels (sourceStart,
  16748. sourceEnd - sourceStart,
  16749. lowestLeft,
  16750. highestLeft,
  16751. lowestRight,
  16752. highestRight);
  16753. int n = i * 2;
  16754. if (r != 0)
  16755. {
  16756. l [n] = (char) jlimit (-128.0f, 127.0f, lowestLeft * 127.0f);
  16757. r [n++] = (char) jlimit (-128.0f, 127.0f, lowestRight * 127.0f);
  16758. l [n] = (char) jlimit (-128.0f, 127.0f, highestLeft * 127.0f);
  16759. r [n++] = (char) jlimit (-128.0f, 127.0f, highestRight * 127.0f);
  16760. }
  16761. else
  16762. {
  16763. l [n++] = (char) jlimit (-128.0f, 127.0f, lowestLeft * 127.0f);
  16764. l [n++] = (char) jlimit (-128.0f, 127.0f, highestLeft * 127.0f);
  16765. }
  16766. }
  16767. }
  16768. char* AudioThumbnail::getChannelData (int channel) const
  16769. {
  16770. AudioThumbnailDataFormat* const d = (AudioThumbnailDataFormat*) data.getData();
  16771. jassert (d != 0);
  16772. if (channel >= 0 && channel < d->numChannels)
  16773. return d->data + (channel * 2 * d->numThumbnailSamples);
  16774. return 0;
  16775. }
  16776. bool AudioThumbnail::isFullyLoaded() const throw()
  16777. {
  16778. const AudioThumbnailDataFormat* const d = (const AudioThumbnailDataFormat*) data.getData();
  16779. jassert (d != 0);
  16780. return d->numFinishedSamples >= d->totalSamples;
  16781. }
  16782. void AudioThumbnail::refillCache (const int numSamples,
  16783. double startTime,
  16784. const double timePerPixel)
  16785. {
  16786. const AudioThumbnailDataFormat* const d = (const AudioThumbnailDataFormat*) data.getData();
  16787. jassert (d != 0);
  16788. if (numSamples <= 0
  16789. || timePerPixel <= 0.0
  16790. || d->sampleRate <= 0)
  16791. {
  16792. numSamplesCached = 0;
  16793. cacheNeedsRefilling = true;
  16794. return;
  16795. }
  16796. if (numSamples == numSamplesCached
  16797. && numChannelsCached == d->numChannels
  16798. && startTime == cachedStart
  16799. && timePerPixel == cachedTimePerPixel
  16800. && ! cacheNeedsRefilling)
  16801. {
  16802. return;
  16803. }
  16804. numSamplesCached = numSamples;
  16805. numChannelsCached = d->numChannels;
  16806. cachedStart = startTime;
  16807. cachedTimePerPixel = timePerPixel;
  16808. cachedLevels.ensureSize (2 * numChannelsCached * numSamples);
  16809. const bool needExtraDetail = (timePerPixel * d->sampleRate <= d->samplesPerThumbSample);
  16810. const ScopedLock sl (readerLock);
  16811. cacheNeedsRefilling = false;
  16812. if (needExtraDetail && reader == 0)
  16813. reader = createReader();
  16814. if (reader != 0 && timePerPixel * d->sampleRate <= d->samplesPerThumbSample)
  16815. {
  16816. startTimer (timeBeforeDeletingReader);
  16817. char* cacheData = static_cast <char*> (cachedLevels.getData());
  16818. int sample = roundToInt (startTime * d->sampleRate);
  16819. for (int i = numSamples; --i >= 0;)
  16820. {
  16821. const int nextSample = roundToInt ((startTime + timePerPixel) * d->sampleRate);
  16822. if (sample >= 0)
  16823. {
  16824. if (sample >= reader->lengthInSamples)
  16825. break;
  16826. float lmin, lmax, rmin, rmax;
  16827. reader->readMaxLevels (sample,
  16828. jmax (1, nextSample - sample),
  16829. lmin, lmax, rmin, rmax);
  16830. cacheData[0] = (char) jlimit (-128, 127, roundFloatToInt (lmin * 127.0f));
  16831. cacheData[1] = (char) jlimit (-128, 127, roundFloatToInt (lmax * 127.0f));
  16832. if (numChannelsCached > 1)
  16833. {
  16834. cacheData[2] = (char) jlimit (-128, 127, roundFloatToInt (rmin * 127.0f));
  16835. cacheData[3] = (char) jlimit (-128, 127, roundFloatToInt (rmax * 127.0f));
  16836. }
  16837. cacheData += 2 * numChannelsCached;
  16838. }
  16839. startTime += timePerPixel;
  16840. sample = nextSample;
  16841. }
  16842. }
  16843. else
  16844. {
  16845. for (int channelNum = 0; channelNum < numChannelsCached; ++channelNum)
  16846. {
  16847. char* const channelData = getChannelData (channelNum);
  16848. char* cacheData = static_cast <char*> (cachedLevels.getData()) + channelNum * 2;
  16849. const double timeToThumbSampleFactor = d->sampleRate / (double) d->samplesPerThumbSample;
  16850. startTime = cachedStart;
  16851. int sample = roundToInt (startTime * timeToThumbSampleFactor);
  16852. const int numFinished = (int) (d->numFinishedSamples / d->samplesPerThumbSample);
  16853. for (int i = numSamples; --i >= 0;)
  16854. {
  16855. const int nextSample = roundToInt ((startTime + timePerPixel) * timeToThumbSampleFactor);
  16856. if (sample >= 0 && channelData != 0)
  16857. {
  16858. char mx = -128;
  16859. char mn = 127;
  16860. while (sample <= nextSample)
  16861. {
  16862. if (sample >= numFinished)
  16863. break;
  16864. const int n = sample << 1;
  16865. const char sampMin = channelData [n];
  16866. const char sampMax = channelData [n + 1];
  16867. if (sampMin < mn)
  16868. mn = sampMin;
  16869. if (sampMax > mx)
  16870. mx = sampMax;
  16871. ++sample;
  16872. }
  16873. if (mn <= mx)
  16874. {
  16875. cacheData[0] = mn;
  16876. cacheData[1] = mx;
  16877. }
  16878. else
  16879. {
  16880. cacheData[0] = 1;
  16881. cacheData[1] = 0;
  16882. }
  16883. }
  16884. else
  16885. {
  16886. cacheData[0] = 1;
  16887. cacheData[1] = 0;
  16888. }
  16889. cacheData += numChannelsCached * 2;
  16890. startTime += timePerPixel;
  16891. sample = nextSample;
  16892. }
  16893. }
  16894. }
  16895. }
  16896. void AudioThumbnail::drawChannel (Graphics& g,
  16897. int x, int y, int w, int h,
  16898. double startTime,
  16899. double endTime,
  16900. int channelNum,
  16901. const float verticalZoomFactor)
  16902. {
  16903. refillCache (w, startTime, (endTime - startTime) / w);
  16904. if (numSamplesCached >= w
  16905. && channelNum >= 0
  16906. && channelNum < numChannelsCached)
  16907. {
  16908. const float topY = (float) y;
  16909. const float bottomY = topY + h;
  16910. const float midY = topY + h * 0.5f;
  16911. const float vscale = verticalZoomFactor * h / 256.0f;
  16912. const Rectangle<int> clip (g.getClipBounds());
  16913. const int skipLeft = jlimit (0, w, clip.getX() - x);
  16914. w -= skipLeft;
  16915. x += skipLeft;
  16916. const char* cacheData = static_cast <const char*> (cachedLevels.getData())
  16917. + (channelNum << 1)
  16918. + skipLeft * (numChannelsCached << 1);
  16919. while (--w >= 0)
  16920. {
  16921. const char mn = cacheData[0];
  16922. const char mx = cacheData[1];
  16923. cacheData += numChannelsCached << 1;
  16924. if (mn <= mx) // if the wrong way round, signifies that the sample's not yet known
  16925. g.drawLine ((float) x, jmax (midY - mx * vscale - 0.3f, topY),
  16926. (float) x, jmin (midY - mn * vscale + 0.3f, bottomY));
  16927. ++x;
  16928. if (x >= clip.getRight())
  16929. break;
  16930. }
  16931. }
  16932. }
  16933. END_JUCE_NAMESPACE
  16934. /*** End of inlined file: juce_AudioThumbnail.cpp ***/
  16935. /*** Start of inlined file: juce_AudioThumbnailCache.cpp ***/
  16936. BEGIN_JUCE_NAMESPACE
  16937. struct ThumbnailCacheEntry
  16938. {
  16939. int64 hash;
  16940. uint32 lastUsed;
  16941. MemoryBlock data;
  16942. juce_UseDebuggingNewOperator
  16943. };
  16944. AudioThumbnailCache::AudioThumbnailCache (const int maxNumThumbsToStore_)
  16945. : TimeSliceThread ("thumb cache"),
  16946. maxNumThumbsToStore (maxNumThumbsToStore_)
  16947. {
  16948. startThread (2);
  16949. }
  16950. AudioThumbnailCache::~AudioThumbnailCache()
  16951. {
  16952. }
  16953. bool AudioThumbnailCache::loadThumb (AudioThumbnail& thumb, const int64 hashCode)
  16954. {
  16955. for (int i = thumbs.size(); --i >= 0;)
  16956. {
  16957. if (thumbs[i]->hash == hashCode)
  16958. {
  16959. MemoryInputStream in (thumbs[i]->data, false);
  16960. thumb.loadFrom (in);
  16961. thumbs[i]->lastUsed = Time::getMillisecondCounter();
  16962. return true;
  16963. }
  16964. }
  16965. return false;
  16966. }
  16967. void AudioThumbnailCache::storeThumb (const AudioThumbnail& thumb,
  16968. const int64 hashCode)
  16969. {
  16970. MemoryOutputStream out;
  16971. thumb.saveTo (out);
  16972. ThumbnailCacheEntry* te = 0;
  16973. for (int i = thumbs.size(); --i >= 0;)
  16974. {
  16975. if (thumbs[i]->hash == hashCode)
  16976. {
  16977. te = thumbs[i];
  16978. break;
  16979. }
  16980. }
  16981. if (te == 0)
  16982. {
  16983. te = new ThumbnailCacheEntry();
  16984. te->hash = hashCode;
  16985. if (thumbs.size() < maxNumThumbsToStore)
  16986. {
  16987. thumbs.add (te);
  16988. }
  16989. else
  16990. {
  16991. int oldest = 0;
  16992. unsigned int oldestTime = Time::getMillisecondCounter() + 1;
  16993. int i;
  16994. for (i = thumbs.size(); --i >= 0;)
  16995. if (thumbs[i]->lastUsed < oldestTime)
  16996. oldest = i;
  16997. thumbs.set (i, te);
  16998. }
  16999. }
  17000. te->lastUsed = Time::getMillisecondCounter();
  17001. te->data.setSize (0);
  17002. te->data.append (out.getData(), out.getDataSize());
  17003. }
  17004. void AudioThumbnailCache::clear()
  17005. {
  17006. thumbs.clear();
  17007. }
  17008. void AudioThumbnailCache::addThumbnail (AudioThumbnail* const thumb)
  17009. {
  17010. addTimeSliceClient (thumb);
  17011. }
  17012. void AudioThumbnailCache::removeThumbnail (AudioThumbnail* const thumb)
  17013. {
  17014. removeTimeSliceClient (thumb);
  17015. }
  17016. END_JUCE_NAMESPACE
  17017. /*** End of inlined file: juce_AudioThumbnailCache.cpp ***/
  17018. /*** Start of inlined file: juce_QuickTimeAudioFormat.cpp ***/
  17019. #if JUCE_QUICKTIME && ! (JUCE_64BIT || JUCE_IPHONE)
  17020. #if ! JUCE_WINDOWS
  17021. #include <QuickTime/Movies.h>
  17022. #include <QuickTime/QTML.h>
  17023. #include <QuickTime/QuickTimeComponents.h>
  17024. #include <QuickTime/MediaHandlers.h>
  17025. #include <QuickTime/ImageCodec.h>
  17026. #else
  17027. #if JUCE_MSVC
  17028. #pragma warning (push)
  17029. #pragma warning (disable : 4100)
  17030. #endif
  17031. /* If you've got an include error here, you probably need to install the QuickTime SDK and
  17032. add its header directory to your include path.
  17033. Alternatively, if you don't need any QuickTime services, just turn off the JUC_QUICKTIME
  17034. flag in juce_Config.h
  17035. */
  17036. #include <Movies.h>
  17037. #include <QTML.h>
  17038. #include <QuickTimeComponents.h>
  17039. #include <MediaHandlers.h>
  17040. #include <ImageCodec.h>
  17041. #if JUCE_MSVC
  17042. #pragma warning (pop)
  17043. #endif
  17044. #endif
  17045. BEGIN_JUCE_NAMESPACE
  17046. bool juce_OpenQuickTimeMovieFromStream (InputStream* input, Movie& movie, Handle& dataHandle);
  17047. static const char* const quickTimeFormatName = "QuickTime file";
  17048. static const char* const quickTimeExtensions[] = { ".mov", ".mp3", ".mp4", 0 };
  17049. class QTAudioReader : public AudioFormatReader
  17050. {
  17051. public:
  17052. QTAudioReader (InputStream* const input_, const int trackNum_)
  17053. : AudioFormatReader (input_, TRANS (quickTimeFormatName)),
  17054. ok (false),
  17055. movie (0),
  17056. trackNum (trackNum_),
  17057. lastSampleRead (0),
  17058. lastThreadId (0),
  17059. extractor (0),
  17060. dataHandle (0)
  17061. {
  17062. bufferList.calloc (256, 1);
  17063. #ifdef WIN32
  17064. if (InitializeQTML (0) != noErr)
  17065. return;
  17066. #endif
  17067. if (EnterMovies() != noErr)
  17068. return;
  17069. bool opened = juce_OpenQuickTimeMovieFromStream (input_, movie, dataHandle);
  17070. if (! opened)
  17071. return;
  17072. {
  17073. const int numTracks = GetMovieTrackCount (movie);
  17074. int trackCount = 0;
  17075. for (int i = 1; i <= numTracks; ++i)
  17076. {
  17077. track = GetMovieIndTrack (movie, i);
  17078. media = GetTrackMedia (track);
  17079. OSType mediaType;
  17080. GetMediaHandlerDescription (media, &mediaType, 0, 0);
  17081. if (mediaType == SoundMediaType
  17082. && trackCount++ == trackNum_)
  17083. {
  17084. ok = true;
  17085. break;
  17086. }
  17087. }
  17088. }
  17089. if (! ok)
  17090. return;
  17091. ok = false;
  17092. lengthInSamples = GetMediaDecodeDuration (media);
  17093. usesFloatingPointData = false;
  17094. samplesPerFrame = (int) (GetMediaDecodeDuration (media) / GetMediaSampleCount (media));
  17095. trackUnitsPerFrame = GetMovieTimeScale (movie) * samplesPerFrame
  17096. / GetMediaTimeScale (media);
  17097. OSStatus err = MovieAudioExtractionBegin (movie, 0, &extractor);
  17098. unsigned long output_layout_size;
  17099. err = MovieAudioExtractionGetPropertyInfo (extractor,
  17100. kQTPropertyClass_MovieAudioExtraction_Audio,
  17101. kQTMovieAudioExtractionAudioPropertyID_AudioChannelLayout,
  17102. 0, &output_layout_size, 0);
  17103. if (err != noErr)
  17104. return;
  17105. HeapBlock <AudioChannelLayout> qt_audio_channel_layout;
  17106. qt_audio_channel_layout.calloc (output_layout_size, 1);
  17107. err = MovieAudioExtractionGetProperty (extractor,
  17108. kQTPropertyClass_MovieAudioExtraction_Audio,
  17109. kQTMovieAudioExtractionAudioPropertyID_AudioChannelLayout,
  17110. output_layout_size, qt_audio_channel_layout, 0);
  17111. qt_audio_channel_layout[0].mChannelLayoutTag = kAudioChannelLayoutTag_Stereo;
  17112. err = MovieAudioExtractionSetProperty (extractor,
  17113. kQTPropertyClass_MovieAudioExtraction_Audio,
  17114. kQTMovieAudioExtractionAudioPropertyID_AudioChannelLayout,
  17115. output_layout_size,
  17116. qt_audio_channel_layout);
  17117. err = MovieAudioExtractionGetProperty (extractor,
  17118. kQTPropertyClass_MovieAudioExtraction_Audio,
  17119. kQTMovieAudioExtractionAudioPropertyID_AudioStreamBasicDescription,
  17120. sizeof (inputStreamDesc),
  17121. &inputStreamDesc, 0);
  17122. if (err != noErr)
  17123. return;
  17124. inputStreamDesc.mFormatFlags = kAudioFormatFlagIsSignedInteger
  17125. | kAudioFormatFlagIsPacked
  17126. | kAudioFormatFlagsNativeEndian;
  17127. inputStreamDesc.mBitsPerChannel = sizeof (SInt16) * 8;
  17128. inputStreamDesc.mChannelsPerFrame = jmin ((UInt32) 2, inputStreamDesc.mChannelsPerFrame);
  17129. inputStreamDesc.mBytesPerFrame = sizeof (SInt16) * inputStreamDesc.mChannelsPerFrame;
  17130. inputStreamDesc.mBytesPerPacket = inputStreamDesc.mBytesPerFrame;
  17131. err = MovieAudioExtractionSetProperty (extractor,
  17132. kQTPropertyClass_MovieAudioExtraction_Audio,
  17133. kQTMovieAudioExtractionAudioPropertyID_AudioStreamBasicDescription,
  17134. sizeof (inputStreamDesc),
  17135. &inputStreamDesc);
  17136. if (err != noErr)
  17137. return;
  17138. Boolean allChannelsDiscrete = false;
  17139. err = MovieAudioExtractionSetProperty (extractor,
  17140. kQTPropertyClass_MovieAudioExtraction_Movie,
  17141. kQTMovieAudioExtractionMoviePropertyID_AllChannelsDiscrete,
  17142. sizeof (allChannelsDiscrete),
  17143. &allChannelsDiscrete);
  17144. if (err != noErr)
  17145. return;
  17146. bufferList->mNumberBuffers = 1;
  17147. bufferList->mBuffers[0].mNumberChannels = inputStreamDesc.mChannelsPerFrame;
  17148. bufferList->mBuffers[0].mDataByteSize = (UInt32) (samplesPerFrame * inputStreamDesc.mBytesPerFrame) + 16;
  17149. dataBuffer.malloc (bufferList->mBuffers[0].mDataByteSize);
  17150. bufferList->mBuffers[0].mData = dataBuffer;
  17151. sampleRate = inputStreamDesc.mSampleRate;
  17152. bitsPerSample = 16;
  17153. numChannels = inputStreamDesc.mChannelsPerFrame;
  17154. detachThread();
  17155. ok = true;
  17156. }
  17157. ~QTAudioReader()
  17158. {
  17159. if (dataHandle != 0)
  17160. DisposeHandle (dataHandle);
  17161. if (extractor != 0)
  17162. {
  17163. MovieAudioExtractionEnd (extractor);
  17164. extractor = 0;
  17165. }
  17166. checkThreadIsAttached();
  17167. DisposeMovie (movie);
  17168. #if JUCE_MAC
  17169. ExitMoviesOnThread ();
  17170. #endif
  17171. }
  17172. bool readSamples (int** destSamples, int numDestChannels, int startOffsetInDestBuffer,
  17173. int64 startSampleInFile, int numSamples)
  17174. {
  17175. checkThreadIsAttached();
  17176. while (numSamples > 0)
  17177. {
  17178. if (! loadFrame ((int) startSampleInFile))
  17179. return false;
  17180. const int numToDo = jmin (numSamples, samplesPerFrame);
  17181. for (int j = numDestChannels; --j >= 0;)
  17182. {
  17183. if (destSamples[j] != 0)
  17184. {
  17185. const short* const src = ((const short*) bufferList->mBuffers[0].mData) + j;
  17186. for (int i = 0; i < numToDo; ++i)
  17187. destSamples[j][startOffsetInDestBuffer + i] = src [i << 1] << 16;
  17188. }
  17189. }
  17190. startOffsetInDestBuffer += numToDo;
  17191. startSampleInFile += numToDo;
  17192. numSamples -= numToDo;
  17193. }
  17194. detachThread();
  17195. return true;
  17196. }
  17197. bool loadFrame (const int sampleNum)
  17198. {
  17199. if (lastSampleRead != sampleNum)
  17200. {
  17201. TimeRecord time;
  17202. time.scale = (TimeScale) inputStreamDesc.mSampleRate;
  17203. time.base = 0;
  17204. time.value.hi = 0;
  17205. time.value.lo = (UInt32) sampleNum;
  17206. OSStatus err = MovieAudioExtractionSetProperty (extractor,
  17207. kQTPropertyClass_MovieAudioExtraction_Movie,
  17208. kQTMovieAudioExtractionMoviePropertyID_CurrentTime,
  17209. sizeof (time), &time);
  17210. if (err != noErr)
  17211. return false;
  17212. }
  17213. bufferList->mBuffers[0].mDataByteSize = inputStreamDesc.mBytesPerFrame * samplesPerFrame;
  17214. UInt32 outFlags = 0;
  17215. UInt32 actualNumSamples = samplesPerFrame;
  17216. OSStatus err = MovieAudioExtractionFillBuffer (extractor, &actualNumSamples,
  17217. bufferList, &outFlags);
  17218. lastSampleRead = sampleNum + samplesPerFrame;
  17219. return err == noErr;
  17220. }
  17221. juce_UseDebuggingNewOperator
  17222. bool ok;
  17223. private:
  17224. Movie movie;
  17225. Media media;
  17226. Track track;
  17227. const int trackNum;
  17228. double trackUnitsPerFrame;
  17229. int samplesPerFrame;
  17230. int lastSampleRead;
  17231. Thread::ThreadID lastThreadId;
  17232. MovieAudioExtractionRef extractor;
  17233. AudioStreamBasicDescription inputStreamDesc;
  17234. HeapBlock <AudioBufferList> bufferList;
  17235. HeapBlock <char> dataBuffer;
  17236. Handle dataHandle;
  17237. void checkThreadIsAttached()
  17238. {
  17239. #if JUCE_MAC
  17240. if (Thread::getCurrentThreadId() != lastThreadId)
  17241. EnterMoviesOnThread (0);
  17242. AttachMovieToCurrentThread (movie);
  17243. #endif
  17244. }
  17245. void detachThread()
  17246. {
  17247. #if JUCE_MAC
  17248. DetachMovieFromCurrentThread (movie);
  17249. #endif
  17250. }
  17251. QTAudioReader (const QTAudioReader&);
  17252. QTAudioReader& operator= (const QTAudioReader&);
  17253. };
  17254. QuickTimeAudioFormat::QuickTimeAudioFormat()
  17255. : AudioFormat (TRANS (quickTimeFormatName), StringArray (quickTimeExtensions))
  17256. {
  17257. }
  17258. QuickTimeAudioFormat::~QuickTimeAudioFormat()
  17259. {
  17260. }
  17261. const Array <int> QuickTimeAudioFormat::getPossibleSampleRates()
  17262. {
  17263. return Array<int>();
  17264. }
  17265. const Array <int> QuickTimeAudioFormat::getPossibleBitDepths()
  17266. {
  17267. return Array<int>();
  17268. }
  17269. bool QuickTimeAudioFormat::canDoStereo()
  17270. {
  17271. return true;
  17272. }
  17273. bool QuickTimeAudioFormat::canDoMono()
  17274. {
  17275. return true;
  17276. }
  17277. AudioFormatReader* QuickTimeAudioFormat::createReaderFor (InputStream* sourceStream,
  17278. const bool deleteStreamIfOpeningFails)
  17279. {
  17280. ScopedPointer <QTAudioReader> r (new QTAudioReader (sourceStream, 0));
  17281. if (r->ok)
  17282. return r.release();
  17283. if (! deleteStreamIfOpeningFails)
  17284. r->input = 0;
  17285. return 0;
  17286. }
  17287. AudioFormatWriter* QuickTimeAudioFormat::createWriterFor (OutputStream* /*streamToWriteTo*/,
  17288. double /*sampleRateToUse*/,
  17289. unsigned int /*numberOfChannels*/,
  17290. int /*bitsPerSample*/,
  17291. const StringPairArray& /*metadataValues*/,
  17292. int /*qualityOptionIndex*/)
  17293. {
  17294. jassertfalse // not yet implemented!
  17295. return 0;
  17296. }
  17297. END_JUCE_NAMESPACE
  17298. #endif
  17299. /*** End of inlined file: juce_QuickTimeAudioFormat.cpp ***/
  17300. /*** Start of inlined file: juce_WavAudioFormat.cpp ***/
  17301. BEGIN_JUCE_NAMESPACE
  17302. static const char* const wavFormatName = "WAV file";
  17303. static const char* const wavExtensions[] = { ".wav", ".bwf", 0 };
  17304. const char* const WavAudioFormat::bwavDescription = "bwav description";
  17305. const char* const WavAudioFormat::bwavOriginator = "bwav originator";
  17306. const char* const WavAudioFormat::bwavOriginatorRef = "bwav originator ref";
  17307. const char* const WavAudioFormat::bwavOriginationDate = "bwav origination date";
  17308. const char* const WavAudioFormat::bwavOriginationTime = "bwav origination time";
  17309. const char* const WavAudioFormat::bwavTimeReference = "bwav time reference";
  17310. const char* const WavAudioFormat::bwavCodingHistory = "bwav coding history";
  17311. const StringPairArray WavAudioFormat::createBWAVMetadata (const String& description,
  17312. const String& originator,
  17313. const String& originatorRef,
  17314. const Time& date,
  17315. const int64 timeReferenceSamples,
  17316. const String& codingHistory)
  17317. {
  17318. StringPairArray m;
  17319. m.set (bwavDescription, description);
  17320. m.set (bwavOriginator, originator);
  17321. m.set (bwavOriginatorRef, originatorRef);
  17322. m.set (bwavOriginationDate, date.formatted ("%Y-%m-%d"));
  17323. m.set (bwavOriginationTime, date.formatted ("%H:%M:%S"));
  17324. m.set (bwavTimeReference, String (timeReferenceSamples));
  17325. m.set (bwavCodingHistory, codingHistory);
  17326. return m;
  17327. }
  17328. #if JUCE_MSVC
  17329. #pragma pack (push, 1)
  17330. #define PACKED
  17331. #elif JUCE_GCC
  17332. #define PACKED __attribute__((packed))
  17333. #else
  17334. #define PACKED
  17335. #endif
  17336. struct BWAVChunk
  17337. {
  17338. char description [256];
  17339. char originator [32];
  17340. char originatorRef [32];
  17341. char originationDate [10];
  17342. char originationTime [8];
  17343. uint32 timeRefLow;
  17344. uint32 timeRefHigh;
  17345. uint16 version;
  17346. uint8 umid[64];
  17347. uint8 reserved[190];
  17348. char codingHistory[1];
  17349. void copyTo (StringPairArray& values) const
  17350. {
  17351. values.set (WavAudioFormat::bwavDescription, String::fromUTF8 (description, 256));
  17352. values.set (WavAudioFormat::bwavOriginator, String::fromUTF8 (originator, 32));
  17353. values.set (WavAudioFormat::bwavOriginatorRef, String::fromUTF8 (originatorRef, 32));
  17354. values.set (WavAudioFormat::bwavOriginationDate, String::fromUTF8 (originationDate, 10));
  17355. values.set (WavAudioFormat::bwavOriginationTime, String::fromUTF8 (originationTime, 8));
  17356. const uint32 timeLow = ByteOrder::swapIfBigEndian (timeRefLow);
  17357. const uint32 timeHigh = ByteOrder::swapIfBigEndian (timeRefHigh);
  17358. const int64 time = (((int64)timeHigh) << 32) + timeLow;
  17359. values.set (WavAudioFormat::bwavTimeReference, String (time));
  17360. values.set (WavAudioFormat::bwavCodingHistory, String::fromUTF8 (codingHistory));
  17361. }
  17362. static MemoryBlock createFrom (const StringPairArray& values)
  17363. {
  17364. const size_t sizeNeeded = sizeof (BWAVChunk) + values [WavAudioFormat::bwavCodingHistory].getNumBytesAsUTF8();
  17365. MemoryBlock data ((sizeNeeded + 3) & ~3);
  17366. data.fillWith (0);
  17367. BWAVChunk* b = (BWAVChunk*) data.getData();
  17368. // Allow these calls to overwrite an extra byte at the end, which is fine as long
  17369. // as they get called in the right order..
  17370. values [WavAudioFormat::bwavDescription].copyToUTF8 (b->description, 257);
  17371. values [WavAudioFormat::bwavOriginator].copyToUTF8 (b->originator, 33);
  17372. values [WavAudioFormat::bwavOriginatorRef].copyToUTF8 (b->originatorRef, 33);
  17373. values [WavAudioFormat::bwavOriginationDate].copyToUTF8 (b->originationDate, 11);
  17374. values [WavAudioFormat::bwavOriginationTime].copyToUTF8 (b->originationTime, 9);
  17375. const int64 time = values [WavAudioFormat::bwavTimeReference].getLargeIntValue();
  17376. b->timeRefLow = ByteOrder::swapIfBigEndian ((uint32) (time & 0xffffffff));
  17377. b->timeRefHigh = ByteOrder::swapIfBigEndian ((uint32) (time >> 32));
  17378. values [WavAudioFormat::bwavCodingHistory].copyToUTF8 (b->codingHistory, 0x7fffffff);
  17379. if (b->description[0] != 0
  17380. || b->originator[0] != 0
  17381. || b->originationDate[0] != 0
  17382. || b->originationTime[0] != 0
  17383. || b->codingHistory[0] != 0
  17384. || time != 0)
  17385. {
  17386. return data;
  17387. }
  17388. return MemoryBlock();
  17389. }
  17390. } PACKED;
  17391. struct SMPLChunk
  17392. {
  17393. struct SampleLoop
  17394. {
  17395. uint32 identifier;
  17396. uint32 type;
  17397. uint32 start;
  17398. uint32 end;
  17399. uint32 fraction;
  17400. uint32 playCount;
  17401. } PACKED;
  17402. uint32 manufacturer;
  17403. uint32 product;
  17404. uint32 samplePeriod;
  17405. uint32 midiUnityNote;
  17406. uint32 midiPitchFraction;
  17407. uint32 smpteFormat;
  17408. uint32 smpteOffset;
  17409. uint32 numSampleLoops;
  17410. uint32 samplerData;
  17411. SampleLoop loops[1];
  17412. void copyTo (StringPairArray& values, const int totalSize) const
  17413. {
  17414. values.set ("Manufacturer", String (ByteOrder::swapIfBigEndian (manufacturer)));
  17415. values.set ("Product", String (ByteOrder::swapIfBigEndian (product)));
  17416. values.set ("SamplePeriod", String (ByteOrder::swapIfBigEndian (samplePeriod)));
  17417. values.set ("MidiUnityNote", String (ByteOrder::swapIfBigEndian (midiUnityNote)));
  17418. values.set ("MidiPitchFraction", String (ByteOrder::swapIfBigEndian (midiPitchFraction)));
  17419. values.set ("SmpteFormat", String (ByteOrder::swapIfBigEndian (smpteFormat)));
  17420. values.set ("SmpteOffset", String (ByteOrder::swapIfBigEndian (smpteOffset)));
  17421. values.set ("NumSampleLoops", String (ByteOrder::swapIfBigEndian (numSampleLoops)));
  17422. values.set ("SamplerData", String (ByteOrder::swapIfBigEndian (samplerData)));
  17423. for (uint32 i = 0; i < numSampleLoops; ++i)
  17424. {
  17425. if ((uint8*) (loops + (i + 1)) > ((uint8*) this) + totalSize)
  17426. break;
  17427. const String prefix ("Loop" + String(i));
  17428. values.set (prefix + "Identifier", String (ByteOrder::swapIfBigEndian (loops[i].identifier)));
  17429. values.set (prefix + "Type", String (ByteOrder::swapIfBigEndian (loops[i].type)));
  17430. values.set (prefix + "Start", String (ByteOrder::swapIfBigEndian (loops[i].start)));
  17431. values.set (prefix + "End", String (ByteOrder::swapIfBigEndian (loops[i].end)));
  17432. values.set (prefix + "Fraction", String (ByteOrder::swapIfBigEndian (loops[i].fraction)));
  17433. values.set (prefix + "PlayCount", String (ByteOrder::swapIfBigEndian (loops[i].playCount)));
  17434. }
  17435. }
  17436. static MemoryBlock createFrom (const StringPairArray& values)
  17437. {
  17438. const int numLoops = jmin (64, values.getValue ("NumSampleLoops", "0").getIntValue());
  17439. if (numLoops <= 0)
  17440. return MemoryBlock();
  17441. const size_t sizeNeeded = sizeof (SMPLChunk) + (numLoops - 1) * sizeof (SampleLoop);
  17442. MemoryBlock data ((sizeNeeded + 3) & ~3);
  17443. data.fillWith (0);
  17444. SMPLChunk* s = (SMPLChunk*) data.getData();
  17445. // Allow these calls to overwrite an extra byte at the end, which is fine as long
  17446. // as they get called in the right order..
  17447. s->manufacturer = ByteOrder::swapIfBigEndian ((uint32) values.getValue ("Manufacturer", "0").getIntValue());
  17448. s->product = ByteOrder::swapIfBigEndian ((uint32) values.getValue ("Product", "0").getIntValue());
  17449. s->samplePeriod = ByteOrder::swapIfBigEndian ((uint32) values.getValue ("SamplePeriod", "0").getIntValue());
  17450. s->midiUnityNote = ByteOrder::swapIfBigEndian ((uint32) values.getValue ("MidiUnityNote", "60").getIntValue());
  17451. s->midiPitchFraction = ByteOrder::swapIfBigEndian ((uint32) values.getValue ("MidiPitchFraction", "0").getIntValue());
  17452. s->smpteFormat = ByteOrder::swapIfBigEndian ((uint32) values.getValue ("SmpteFormat", "0").getIntValue());
  17453. s->smpteOffset = ByteOrder::swapIfBigEndian ((uint32) values.getValue ("SmpteOffset", "0").getIntValue());
  17454. s->numSampleLoops = ByteOrder::swapIfBigEndian ((uint32) numLoops);
  17455. s->samplerData = ByteOrder::swapIfBigEndian ((uint32) values.getValue ("SamplerData", "0").getIntValue());
  17456. for (int i = 0; i < numLoops; ++i)
  17457. {
  17458. const String prefix ("Loop" + String(i));
  17459. s->loops[i].identifier = ByteOrder::swapIfBigEndian ((uint32) values.getValue (prefix + "Identifier", "0").getIntValue());
  17460. s->loops[i].type = ByteOrder::swapIfBigEndian ((uint32) values.getValue (prefix + "Type", "0").getIntValue());
  17461. s->loops[i].start = ByteOrder::swapIfBigEndian ((uint32) values.getValue (prefix + "Start", "0").getIntValue());
  17462. s->loops[i].end = ByteOrder::swapIfBigEndian ((uint32) values.getValue (prefix + "End", "0").getIntValue());
  17463. s->loops[i].fraction = ByteOrder::swapIfBigEndian ((uint32) values.getValue (prefix + "Fraction", "0").getIntValue());
  17464. s->loops[i].playCount = ByteOrder::swapIfBigEndian ((uint32) values.getValue (prefix + "PlayCount", "0").getIntValue());
  17465. }
  17466. return data;
  17467. }
  17468. } PACKED;
  17469. struct ExtensibleWavSubFormat
  17470. {
  17471. uint32 data1;
  17472. uint16 data2;
  17473. uint16 data3;
  17474. uint8 data4[8];
  17475. } PACKED;
  17476. #if JUCE_MSVC
  17477. #pragma pack (pop)
  17478. #endif
  17479. #undef PACKED
  17480. class WavAudioFormatReader : public AudioFormatReader
  17481. {
  17482. int bytesPerFrame;
  17483. int64 dataChunkStart, dataLength;
  17484. static inline int chunkName (const char* const name) { return (int) ByteOrder::littleEndianInt (name); }
  17485. WavAudioFormatReader (const WavAudioFormatReader&);
  17486. WavAudioFormatReader& operator= (const WavAudioFormatReader&);
  17487. public:
  17488. int64 bwavChunkStart, bwavSize;
  17489. WavAudioFormatReader (InputStream* const in)
  17490. : AudioFormatReader (in, TRANS (wavFormatName)),
  17491. dataLength (0),
  17492. bwavChunkStart (0),
  17493. bwavSize (0)
  17494. {
  17495. if (input->readInt() == chunkName ("RIFF"))
  17496. {
  17497. const uint32 len = (uint32) input->readInt();
  17498. const int64 end = input->getPosition() + len;
  17499. bool hasGotType = false;
  17500. bool hasGotData = false;
  17501. if (input->readInt() == chunkName ("WAVE"))
  17502. {
  17503. while (input->getPosition() < end
  17504. && ! input->isExhausted())
  17505. {
  17506. const int chunkType = input->readInt();
  17507. uint32 length = (uint32) input->readInt();
  17508. const int64 chunkEnd = input->getPosition() + length + (length & 1);
  17509. if (chunkType == chunkName ("fmt "))
  17510. {
  17511. // read the format chunk
  17512. const unsigned short format = input->readShort();
  17513. const short numChans = input->readShort();
  17514. sampleRate = input->readInt();
  17515. const int bytesPerSec = input->readInt();
  17516. numChannels = numChans;
  17517. bytesPerFrame = bytesPerSec / (int)sampleRate;
  17518. bitsPerSample = 8 * bytesPerFrame / numChans;
  17519. if (format == 3)
  17520. {
  17521. usesFloatingPointData = true;
  17522. }
  17523. else if (format == 0xfffe /*WAVE_FORMAT_EXTENSIBLE*/)
  17524. {
  17525. if (length < 40) // too short
  17526. {
  17527. bytesPerFrame = 0;
  17528. }
  17529. else
  17530. {
  17531. input->skipNextBytes (12); // skip over blockAlign, bitsPerSample and speakerPosition mask
  17532. ExtensibleWavSubFormat subFormat;
  17533. subFormat.data1 = input->readInt();
  17534. subFormat.data2 = input->readShort();
  17535. subFormat.data3 = input->readShort();
  17536. input->read (subFormat.data4, sizeof (subFormat.data4));
  17537. const ExtensibleWavSubFormat pcmFormat
  17538. = { 0x00000001, 0x0000, 0x0010, { 0x80, 0x00, 0x00, 0xaa, 0x00, 0x38, 0x9b, 0x71 } };
  17539. if (memcmp (&subFormat, &pcmFormat, sizeof (subFormat)) != 0)
  17540. {
  17541. const ExtensibleWavSubFormat ambisonicFormat
  17542. = { 0x00000001, 0x0721, 0x11d3, { 0x86, 0x44, 0xC8, 0xC1, 0xCA, 0x00, 0x00, 0x00 } };
  17543. if (memcmp (&subFormat, &ambisonicFormat, sizeof (subFormat)) != 0)
  17544. bytesPerFrame = 0;
  17545. }
  17546. }
  17547. }
  17548. else if (format != 1)
  17549. {
  17550. bytesPerFrame = 0;
  17551. }
  17552. hasGotType = true;
  17553. }
  17554. else if (chunkType == chunkName ("data"))
  17555. {
  17556. // get the data chunk's position
  17557. dataLength = length;
  17558. dataChunkStart = input->getPosition();
  17559. lengthInSamples = (bytesPerFrame > 0) ? (dataLength / bytesPerFrame) : 0;
  17560. hasGotData = true;
  17561. }
  17562. else if (chunkType == chunkName ("bext"))
  17563. {
  17564. bwavChunkStart = input->getPosition();
  17565. bwavSize = length;
  17566. // Broadcast-wav extension chunk..
  17567. HeapBlock <BWAVChunk> bwav;
  17568. bwav.calloc (jmax ((size_t) length + 1, sizeof (BWAVChunk)), 1);
  17569. input->read (bwav, length);
  17570. bwav->copyTo (metadataValues);
  17571. }
  17572. else if (chunkType == chunkName ("smpl"))
  17573. {
  17574. HeapBlock <SMPLChunk> smpl;
  17575. smpl.calloc (jmax ((size_t) length + 1, sizeof (SMPLChunk)), 1);
  17576. input->read (smpl, length);
  17577. smpl->copyTo (metadataValues, length);
  17578. }
  17579. else if (chunkEnd <= input->getPosition())
  17580. {
  17581. break;
  17582. }
  17583. input->setPosition (chunkEnd);
  17584. }
  17585. }
  17586. }
  17587. }
  17588. ~WavAudioFormatReader()
  17589. {
  17590. }
  17591. bool readSamples (int** destSamples, int numDestChannels, int startOffsetInDestBuffer,
  17592. int64 startSampleInFile, int numSamples)
  17593. {
  17594. const int64 samplesAvailable = lengthInSamples - startSampleInFile;
  17595. if (samplesAvailable < numSamples)
  17596. {
  17597. for (int i = numDestChannels; --i >= 0;)
  17598. if (destSamples[i] != 0)
  17599. zeromem (destSamples[i] + startOffsetInDestBuffer, sizeof (int) * numSamples);
  17600. numSamples = (int) samplesAvailable;
  17601. }
  17602. if (numSamples <= 0)
  17603. return true;
  17604. input->setPosition (dataChunkStart + startSampleInFile * bytesPerFrame);
  17605. const int tempBufSize = 480 * 3 * 4; // (keep this a multiple of 3)
  17606. char tempBuffer [tempBufSize];
  17607. while (numSamples > 0)
  17608. {
  17609. int* left = destSamples[0];
  17610. if (left != 0)
  17611. left += startOffsetInDestBuffer;
  17612. int* right = numDestChannels > 1 ? destSamples[1] : 0;
  17613. if (right != 0)
  17614. right += startOffsetInDestBuffer;
  17615. const int numThisTime = jmin (tempBufSize / bytesPerFrame, numSamples);
  17616. const int bytesRead = input->read (tempBuffer, numThisTime * bytesPerFrame);
  17617. if (bytesRead < numThisTime * bytesPerFrame)
  17618. zeromem (tempBuffer + bytesRead, numThisTime * bytesPerFrame - bytesRead);
  17619. if (bitsPerSample == 16)
  17620. {
  17621. const short* src = reinterpret_cast <const short*> (tempBuffer);
  17622. if (numChannels > 1)
  17623. {
  17624. if (left == 0)
  17625. {
  17626. for (int i = numThisTime; --i >= 0;)
  17627. {
  17628. ++src;
  17629. *right++ = (int) ByteOrder::swapIfBigEndian ((unsigned short) *src++) << 16;
  17630. }
  17631. }
  17632. else if (right == 0)
  17633. {
  17634. for (int i = numThisTime; --i >= 0;)
  17635. {
  17636. *left++ = (int) ByteOrder::swapIfBigEndian ((unsigned short) *src++) << 16;
  17637. ++src;
  17638. }
  17639. }
  17640. else
  17641. {
  17642. for (int i = numThisTime; --i >= 0;)
  17643. {
  17644. *left++ = (int) ByteOrder::swapIfBigEndian ((unsigned short) *src++) << 16;
  17645. *right++ = (int) ByteOrder::swapIfBigEndian ((unsigned short) *src++) << 16;
  17646. }
  17647. }
  17648. }
  17649. else
  17650. {
  17651. for (int i = numThisTime; --i >= 0;)
  17652. {
  17653. *left++ = (int) ByteOrder::swapIfBigEndian ((unsigned short) *src++) << 16;
  17654. }
  17655. }
  17656. }
  17657. else if (bitsPerSample == 24)
  17658. {
  17659. const char* src = tempBuffer;
  17660. if (numChannels > 1)
  17661. {
  17662. if (left == 0)
  17663. {
  17664. for (int i = numThisTime; --i >= 0;)
  17665. {
  17666. src += 3;
  17667. *right++ = ByteOrder::littleEndian24Bit (src) << 8;
  17668. src += 3;
  17669. }
  17670. }
  17671. else if (right == 0)
  17672. {
  17673. for (int i = numThisTime; --i >= 0;)
  17674. {
  17675. *left++ = ByteOrder::littleEndian24Bit (src) << 8;
  17676. src += 6;
  17677. }
  17678. }
  17679. else
  17680. {
  17681. for (int i = 0; i < numThisTime; ++i)
  17682. {
  17683. *left++ = ByteOrder::littleEndian24Bit (src) << 8;
  17684. src += 3;
  17685. *right++ = ByteOrder::littleEndian24Bit (src) << 8;
  17686. src += 3;
  17687. }
  17688. }
  17689. }
  17690. else
  17691. {
  17692. for (int i = 0; i < numThisTime; ++i)
  17693. {
  17694. *left++ = ByteOrder::littleEndian24Bit (src) << 8;
  17695. src += 3;
  17696. }
  17697. }
  17698. }
  17699. else if (bitsPerSample == 32)
  17700. {
  17701. const unsigned int* src = (const unsigned int*) tempBuffer;
  17702. unsigned int* l = (unsigned int*) left;
  17703. unsigned int* r = (unsigned int*) right;
  17704. if (numChannels > 1)
  17705. {
  17706. if (l == 0)
  17707. {
  17708. for (int i = numThisTime; --i >= 0;)
  17709. {
  17710. ++src;
  17711. *r++ = ByteOrder::swapIfBigEndian (*src++);
  17712. }
  17713. }
  17714. else if (r == 0)
  17715. {
  17716. for (int i = numThisTime; --i >= 0;)
  17717. {
  17718. *l++ = ByteOrder::swapIfBigEndian (*src++);
  17719. ++src;
  17720. }
  17721. }
  17722. else
  17723. {
  17724. for (int i = numThisTime; --i >= 0;)
  17725. {
  17726. *l++ = ByteOrder::swapIfBigEndian (*src++);
  17727. *r++ = ByteOrder::swapIfBigEndian (*src++);
  17728. }
  17729. }
  17730. }
  17731. else
  17732. {
  17733. for (int i = numThisTime; --i >= 0;)
  17734. {
  17735. *l++ = ByteOrder::swapIfBigEndian (*src++);
  17736. }
  17737. }
  17738. left = (int*)l;
  17739. right = (int*)r;
  17740. }
  17741. else if (bitsPerSample == 8)
  17742. {
  17743. const unsigned char* src = (const unsigned char*) tempBuffer;
  17744. if (numChannels > 1)
  17745. {
  17746. if (left == 0)
  17747. {
  17748. for (int i = numThisTime; --i >= 0;)
  17749. {
  17750. ++src;
  17751. *right++ = ((int) *src++ - 128) << 24;
  17752. }
  17753. }
  17754. else if (right == 0)
  17755. {
  17756. for (int i = numThisTime; --i >= 0;)
  17757. {
  17758. *left++ = ((int) *src++ - 128) << 24;
  17759. ++src;
  17760. }
  17761. }
  17762. else
  17763. {
  17764. for (int i = numThisTime; --i >= 0;)
  17765. {
  17766. *left++ = ((int) *src++ - 128) << 24;
  17767. *right++ = ((int) *src++ - 128) << 24;
  17768. }
  17769. }
  17770. }
  17771. else
  17772. {
  17773. for (int i = numThisTime; --i >= 0;)
  17774. {
  17775. *left++ = ((int)*src++ - 128) << 24;
  17776. }
  17777. }
  17778. }
  17779. startOffsetInDestBuffer += numThisTime;
  17780. numSamples -= numThisTime;
  17781. }
  17782. if (numSamples > 0)
  17783. {
  17784. for (int i = numDestChannels; --i >= 0;)
  17785. if (destSamples[i] != 0)
  17786. zeromem (destSamples[i] + startOffsetInDestBuffer,
  17787. sizeof (int) * numSamples);
  17788. }
  17789. return true;
  17790. }
  17791. juce_UseDebuggingNewOperator
  17792. };
  17793. class WavAudioFormatWriter : public AudioFormatWriter
  17794. {
  17795. MemoryBlock tempBlock, bwavChunk, smplChunk;
  17796. uint32 lengthInSamples, bytesWritten;
  17797. int64 headerPosition;
  17798. bool writeFailed;
  17799. static inline int chunkName (const char* const name) { return (int) ByteOrder::littleEndianInt (name); }
  17800. WavAudioFormatWriter (const WavAudioFormatWriter&);
  17801. WavAudioFormatWriter& operator= (const WavAudioFormatWriter&);
  17802. void writeHeader()
  17803. {
  17804. const bool seekedOk = output->setPosition (headerPosition);
  17805. (void) seekedOk;
  17806. // if this fails, you've given it an output stream that can't seek! It needs
  17807. // to be able to seek back to write the header
  17808. jassert (seekedOk);
  17809. const int bytesPerFrame = numChannels * bitsPerSample / 8;
  17810. output->writeInt (chunkName ("RIFF"));
  17811. output->writeInt ((int) (lengthInSamples * bytesPerFrame
  17812. + ((bwavChunk.getSize() > 0) ? (44 + bwavChunk.getSize()) : 36)));
  17813. output->writeInt (chunkName ("WAVE"));
  17814. output->writeInt (chunkName ("fmt "));
  17815. output->writeInt (16);
  17816. output->writeShort ((bitsPerSample < 32) ? (short) 1 /*WAVE_FORMAT_PCM*/
  17817. : (short) 3 /*WAVE_FORMAT_IEEE_FLOAT*/);
  17818. output->writeShort ((short) numChannels);
  17819. output->writeInt ((int) sampleRate);
  17820. output->writeInt (bytesPerFrame * (int) sampleRate);
  17821. output->writeShort ((short) bytesPerFrame);
  17822. output->writeShort ((short) bitsPerSample);
  17823. if (bwavChunk.getSize() > 0)
  17824. {
  17825. output->writeInt (chunkName ("bext"));
  17826. output->writeInt ((int) bwavChunk.getSize());
  17827. output->write (bwavChunk.getData(), (int) bwavChunk.getSize());
  17828. }
  17829. if (smplChunk.getSize() > 0)
  17830. {
  17831. output->writeInt (chunkName ("smpl"));
  17832. output->writeInt ((int) smplChunk.getSize());
  17833. output->write (smplChunk.getData(), (int) smplChunk.getSize());
  17834. }
  17835. output->writeInt (chunkName ("data"));
  17836. output->writeInt (lengthInSamples * bytesPerFrame);
  17837. usesFloatingPointData = (bitsPerSample == 32);
  17838. }
  17839. public:
  17840. WavAudioFormatWriter (OutputStream* const out,
  17841. const double sampleRate_,
  17842. const unsigned int numChannels_,
  17843. const int bits,
  17844. const StringPairArray& metadataValues)
  17845. : AudioFormatWriter (out,
  17846. TRANS (wavFormatName),
  17847. sampleRate_,
  17848. numChannels_,
  17849. bits),
  17850. lengthInSamples (0),
  17851. bytesWritten (0),
  17852. writeFailed (false)
  17853. {
  17854. if (metadataValues.size() > 0)
  17855. {
  17856. bwavChunk = BWAVChunk::createFrom (metadataValues);
  17857. smplChunk = SMPLChunk::createFrom (metadataValues);
  17858. }
  17859. headerPosition = out->getPosition();
  17860. writeHeader();
  17861. }
  17862. ~WavAudioFormatWriter()
  17863. {
  17864. writeHeader();
  17865. }
  17866. bool write (const int** data, int numSamples)
  17867. {
  17868. if (writeFailed)
  17869. return false;
  17870. const int bytes = numChannels * numSamples * bitsPerSample / 8;
  17871. tempBlock.ensureSize (bytes, false);
  17872. char* buffer = static_cast <char*> (tempBlock.getData());
  17873. const int* left = data[0];
  17874. const int* right = data[1];
  17875. if (right == 0)
  17876. right = left;
  17877. if (bitsPerSample == 16)
  17878. {
  17879. short* b = (short*) buffer;
  17880. if (numChannels > 1)
  17881. {
  17882. for (int i = numSamples; --i >= 0;)
  17883. {
  17884. *b++ = (short) ByteOrder::swapIfBigEndian ((unsigned short) (*left++ >> 16));
  17885. *b++ = (short) ByteOrder::swapIfBigEndian ((unsigned short) (*right++ >> 16));
  17886. }
  17887. }
  17888. else
  17889. {
  17890. for (int i = numSamples; --i >= 0;)
  17891. {
  17892. *b++ = (short) ByteOrder::swapIfBigEndian ((unsigned short) (*left++ >> 16));
  17893. }
  17894. }
  17895. }
  17896. else if (bitsPerSample == 24)
  17897. {
  17898. char* b = buffer;
  17899. if (numChannels > 1)
  17900. {
  17901. for (int i = numSamples; --i >= 0;)
  17902. {
  17903. ByteOrder::littleEndian24BitToChars ((*left++) >> 8, b);
  17904. b += 3;
  17905. ByteOrder::littleEndian24BitToChars ((*right++) >> 8, b);
  17906. b += 3;
  17907. }
  17908. }
  17909. else
  17910. {
  17911. for (int i = numSamples; --i >= 0;)
  17912. {
  17913. ByteOrder::littleEndian24BitToChars ((*left++) >> 8, b);
  17914. b += 3;
  17915. }
  17916. }
  17917. }
  17918. else if (bitsPerSample == 32)
  17919. {
  17920. unsigned int* b = (unsigned int*) buffer;
  17921. if (numChannels > 1)
  17922. {
  17923. for (int i = numSamples; --i >= 0;)
  17924. {
  17925. *b++ = ByteOrder::swapIfBigEndian ((unsigned int) *left++);
  17926. *b++ = ByteOrder::swapIfBigEndian ((unsigned int) *right++);
  17927. }
  17928. }
  17929. else
  17930. {
  17931. for (int i = numSamples; --i >= 0;)
  17932. {
  17933. *b++ = ByteOrder::swapIfBigEndian ((unsigned int) *left++);
  17934. }
  17935. }
  17936. }
  17937. else if (bitsPerSample == 8)
  17938. {
  17939. unsigned char* b = (unsigned char*) buffer;
  17940. if (numChannels > 1)
  17941. {
  17942. for (int i = numSamples; --i >= 0;)
  17943. {
  17944. *b++ = (unsigned char) (128 + (*left++ >> 24));
  17945. *b++ = (unsigned char) (128 + (*right++ >> 24));
  17946. }
  17947. }
  17948. else
  17949. {
  17950. for (int i = numSamples; --i >= 0;)
  17951. {
  17952. *b++ = (unsigned char) (128 + (*left++ >> 24));
  17953. }
  17954. }
  17955. }
  17956. if (bytesWritten + bytes >= (uint32) 0xfff00000
  17957. || ! output->write (buffer, bytes))
  17958. {
  17959. // failed to write to disk, so let's try writing the header.
  17960. // If it's just run out of disk space, then if it does manage
  17961. // to write the header, we'll still have a useable file..
  17962. writeHeader();
  17963. writeFailed = true;
  17964. return false;
  17965. }
  17966. else
  17967. {
  17968. bytesWritten += bytes;
  17969. lengthInSamples += numSamples;
  17970. return true;
  17971. }
  17972. }
  17973. juce_UseDebuggingNewOperator
  17974. };
  17975. WavAudioFormat::WavAudioFormat()
  17976. : AudioFormat (TRANS (wavFormatName), StringArray (wavExtensions))
  17977. {
  17978. }
  17979. WavAudioFormat::~WavAudioFormat()
  17980. {
  17981. }
  17982. const Array <int> WavAudioFormat::getPossibleSampleRates()
  17983. {
  17984. const int rates[] = { 22050, 32000, 44100, 48000, 88200, 96000, 176400, 192000, 0 };
  17985. return Array <int> (rates);
  17986. }
  17987. const Array <int> WavAudioFormat::getPossibleBitDepths()
  17988. {
  17989. const int depths[] = { 8, 16, 24, 32, 0 };
  17990. return Array <int> (depths);
  17991. }
  17992. bool WavAudioFormat::canDoStereo()
  17993. {
  17994. return true;
  17995. }
  17996. bool WavAudioFormat::canDoMono()
  17997. {
  17998. return true;
  17999. }
  18000. AudioFormatReader* WavAudioFormat::createReaderFor (InputStream* sourceStream,
  18001. const bool deleteStreamIfOpeningFails)
  18002. {
  18003. ScopedPointer <WavAudioFormatReader> r (new WavAudioFormatReader (sourceStream));
  18004. if (r->sampleRate != 0)
  18005. return r.release();
  18006. if (! deleteStreamIfOpeningFails)
  18007. r->input = 0;
  18008. return 0;
  18009. }
  18010. AudioFormatWriter* WavAudioFormat::createWriterFor (OutputStream* out,
  18011. double sampleRate,
  18012. unsigned int numChannels,
  18013. int bitsPerSample,
  18014. const StringPairArray& metadataValues,
  18015. int /*qualityOptionIndex*/)
  18016. {
  18017. if (getPossibleBitDepths().contains (bitsPerSample))
  18018. {
  18019. return new WavAudioFormatWriter (out,
  18020. sampleRate,
  18021. numChannels,
  18022. bitsPerSample,
  18023. metadataValues);
  18024. }
  18025. return 0;
  18026. }
  18027. static bool juce_slowCopyOfWavFileWithNewMetadata (const File& file, const StringPairArray& metadata)
  18028. {
  18029. TemporaryFile tempFile (file);
  18030. WavAudioFormat wav;
  18031. ScopedPointer <AudioFormatReader> reader (wav.createReaderFor (file.createInputStream(), true));
  18032. if (reader != 0)
  18033. {
  18034. ScopedPointer <OutputStream> outStream (tempFile.getFile().createOutputStream());
  18035. if (outStream != 0)
  18036. {
  18037. ScopedPointer <AudioFormatWriter> writer (wav.createWriterFor (outStream, reader->sampleRate,
  18038. reader->numChannels, reader->bitsPerSample,
  18039. metadata, 0));
  18040. if (writer != 0)
  18041. {
  18042. outStream.release();
  18043. bool ok = writer->writeFromAudioReader (*reader, 0, -1);
  18044. writer = 0;
  18045. reader = 0;
  18046. return ok && tempFile.overwriteTargetFileWithTemporary();
  18047. }
  18048. }
  18049. }
  18050. return false;
  18051. }
  18052. bool WavAudioFormat::replaceMetadataInFile (const File& wavFile, const StringPairArray& newMetadata)
  18053. {
  18054. ScopedPointer <WavAudioFormatReader> reader ((WavAudioFormatReader*) createReaderFor (wavFile.createInputStream(), true));
  18055. if (reader != 0)
  18056. {
  18057. const int64 bwavPos = reader->bwavChunkStart;
  18058. const int64 bwavSize = reader->bwavSize;
  18059. reader = 0;
  18060. if (bwavSize > 0)
  18061. {
  18062. MemoryBlock chunk = BWAVChunk::createFrom (newMetadata);
  18063. if (chunk.getSize() <= (size_t) bwavSize)
  18064. {
  18065. // the new one will fit in the space available, so write it directly..
  18066. const int64 oldSize = wavFile.getSize();
  18067. {
  18068. ScopedPointer <FileOutputStream> out (wavFile.createOutputStream());
  18069. out->setPosition (bwavPos);
  18070. out->write (chunk.getData(), (int) chunk.getSize());
  18071. out->setPosition (oldSize);
  18072. }
  18073. jassert (wavFile.getSize() == oldSize);
  18074. return true;
  18075. }
  18076. }
  18077. }
  18078. return juce_slowCopyOfWavFileWithNewMetadata (wavFile, newMetadata);
  18079. }
  18080. END_JUCE_NAMESPACE
  18081. /*** End of inlined file: juce_WavAudioFormat.cpp ***/
  18082. /*** Start of inlined file: juce_AudioFormatReaderSource.cpp ***/
  18083. BEGIN_JUCE_NAMESPACE
  18084. AudioFormatReaderSource::AudioFormatReaderSource (AudioFormatReader* const reader_,
  18085. const bool deleteReaderWhenThisIsDeleted)
  18086. : reader (reader_),
  18087. deleteReader (deleteReaderWhenThisIsDeleted),
  18088. nextPlayPos (0),
  18089. looping (false)
  18090. {
  18091. jassert (reader != 0);
  18092. }
  18093. AudioFormatReaderSource::~AudioFormatReaderSource()
  18094. {
  18095. releaseResources();
  18096. if (deleteReader)
  18097. delete reader;
  18098. }
  18099. void AudioFormatReaderSource::setNextReadPosition (int newPosition)
  18100. {
  18101. nextPlayPos = newPosition;
  18102. }
  18103. void AudioFormatReaderSource::setLooping (const bool shouldLoop) throw()
  18104. {
  18105. looping = shouldLoop;
  18106. }
  18107. int AudioFormatReaderSource::getNextReadPosition() const
  18108. {
  18109. return (looping) ? (nextPlayPos % (int) reader->lengthInSamples)
  18110. : nextPlayPos;
  18111. }
  18112. int AudioFormatReaderSource::getTotalLength() const
  18113. {
  18114. return (int) reader->lengthInSamples;
  18115. }
  18116. void AudioFormatReaderSource::prepareToPlay (int /*samplesPerBlockExpected*/,
  18117. double /*sampleRate*/)
  18118. {
  18119. }
  18120. void AudioFormatReaderSource::releaseResources()
  18121. {
  18122. }
  18123. void AudioFormatReaderSource::getNextAudioBlock (const AudioSourceChannelInfo& info)
  18124. {
  18125. if (info.numSamples > 0)
  18126. {
  18127. const int start = nextPlayPos;
  18128. if (looping)
  18129. {
  18130. const int newStart = start % (int) reader->lengthInSamples;
  18131. const int newEnd = (start + info.numSamples) % (int) reader->lengthInSamples;
  18132. if (newEnd > newStart)
  18133. {
  18134. info.buffer->readFromAudioReader (reader,
  18135. info.startSample,
  18136. newEnd - newStart,
  18137. newStart,
  18138. true, true);
  18139. }
  18140. else
  18141. {
  18142. const int endSamps = (int) reader->lengthInSamples - newStart;
  18143. info.buffer->readFromAudioReader (reader,
  18144. info.startSample,
  18145. endSamps,
  18146. newStart,
  18147. true, true);
  18148. info.buffer->readFromAudioReader (reader,
  18149. info.startSample + endSamps,
  18150. newEnd,
  18151. 0,
  18152. true, true);
  18153. }
  18154. nextPlayPos = newEnd;
  18155. }
  18156. else
  18157. {
  18158. info.buffer->readFromAudioReader (reader,
  18159. info.startSample,
  18160. info.numSamples,
  18161. start,
  18162. true, true);
  18163. nextPlayPos += info.numSamples;
  18164. }
  18165. }
  18166. }
  18167. END_JUCE_NAMESPACE
  18168. /*** End of inlined file: juce_AudioFormatReaderSource.cpp ***/
  18169. /*** Start of inlined file: juce_AudioSourcePlayer.cpp ***/
  18170. BEGIN_JUCE_NAMESPACE
  18171. AudioSourcePlayer::AudioSourcePlayer()
  18172. : source (0),
  18173. sampleRate (0),
  18174. bufferSize (0),
  18175. tempBuffer (2, 8),
  18176. lastGain (1.0f),
  18177. gain (1.0f)
  18178. {
  18179. }
  18180. AudioSourcePlayer::~AudioSourcePlayer()
  18181. {
  18182. setSource (0);
  18183. }
  18184. void AudioSourcePlayer::setSource (AudioSource* newSource)
  18185. {
  18186. if (source != newSource)
  18187. {
  18188. AudioSource* const oldSource = source;
  18189. if (newSource != 0 && bufferSize > 0 && sampleRate > 0)
  18190. newSource->prepareToPlay (bufferSize, sampleRate);
  18191. {
  18192. const ScopedLock sl (readLock);
  18193. source = newSource;
  18194. }
  18195. if (oldSource != 0)
  18196. oldSource->releaseResources();
  18197. }
  18198. }
  18199. void AudioSourcePlayer::setGain (const float newGain) throw()
  18200. {
  18201. gain = newGain;
  18202. }
  18203. void AudioSourcePlayer::audioDeviceIOCallback (const float** inputChannelData,
  18204. int totalNumInputChannels,
  18205. float** outputChannelData,
  18206. int totalNumOutputChannels,
  18207. int numSamples)
  18208. {
  18209. // these should have been prepared by audioDeviceAboutToStart()...
  18210. jassert (sampleRate > 0 && bufferSize > 0);
  18211. const ScopedLock sl (readLock);
  18212. if (source != 0)
  18213. {
  18214. AudioSourceChannelInfo info;
  18215. int i, numActiveChans = 0, numInputs = 0, numOutputs = 0;
  18216. // messy stuff needed to compact the channels down into an array
  18217. // of non-zero pointers..
  18218. for (i = 0; i < totalNumInputChannels; ++i)
  18219. {
  18220. if (inputChannelData[i] != 0)
  18221. {
  18222. inputChans [numInputs++] = inputChannelData[i];
  18223. if (numInputs >= numElementsInArray (inputChans))
  18224. break;
  18225. }
  18226. }
  18227. for (i = 0; i < totalNumOutputChannels; ++i)
  18228. {
  18229. if (outputChannelData[i] != 0)
  18230. {
  18231. outputChans [numOutputs++] = outputChannelData[i];
  18232. if (numOutputs >= numElementsInArray (outputChans))
  18233. break;
  18234. }
  18235. }
  18236. if (numInputs > numOutputs)
  18237. {
  18238. // if there aren't enough output channels for the number of
  18239. // inputs, we need to create some temporary extra ones (can't
  18240. // use the input data in case it gets written to)
  18241. tempBuffer.setSize (numInputs - numOutputs, numSamples,
  18242. false, false, true);
  18243. for (i = 0; i < numOutputs; ++i)
  18244. {
  18245. channels[numActiveChans] = outputChans[i];
  18246. memcpy (channels[numActiveChans], inputChans[i], sizeof (float) * numSamples);
  18247. ++numActiveChans;
  18248. }
  18249. for (i = numOutputs; i < numInputs; ++i)
  18250. {
  18251. channels[numActiveChans] = tempBuffer.getSampleData (i - numOutputs, 0);
  18252. memcpy (channels[numActiveChans], inputChans[i], sizeof (float) * numSamples);
  18253. ++numActiveChans;
  18254. }
  18255. }
  18256. else
  18257. {
  18258. for (i = 0; i < numInputs; ++i)
  18259. {
  18260. channels[numActiveChans] = outputChans[i];
  18261. memcpy (channels[numActiveChans], inputChans[i], sizeof (float) * numSamples);
  18262. ++numActiveChans;
  18263. }
  18264. for (i = numInputs; i < numOutputs; ++i)
  18265. {
  18266. channels[numActiveChans] = outputChans[i];
  18267. zeromem (channels[numActiveChans], sizeof (float) * numSamples);
  18268. ++numActiveChans;
  18269. }
  18270. }
  18271. AudioSampleBuffer buffer (channels, numActiveChans, numSamples);
  18272. info.buffer = &buffer;
  18273. info.startSample = 0;
  18274. info.numSamples = numSamples;
  18275. source->getNextAudioBlock (info);
  18276. for (i = info.buffer->getNumChannels(); --i >= 0;)
  18277. info.buffer->applyGainRamp (i, info.startSample, info.numSamples, lastGain, gain);
  18278. lastGain = gain;
  18279. }
  18280. else
  18281. {
  18282. for (int i = 0; i < totalNumOutputChannels; ++i)
  18283. if (outputChannelData[i] != 0)
  18284. zeromem (outputChannelData[i], sizeof (float) * numSamples);
  18285. }
  18286. }
  18287. void AudioSourcePlayer::audioDeviceAboutToStart (AudioIODevice* device)
  18288. {
  18289. sampleRate = device->getCurrentSampleRate();
  18290. bufferSize = device->getCurrentBufferSizeSamples();
  18291. zeromem (channels, sizeof (channels));
  18292. if (source != 0)
  18293. source->prepareToPlay (bufferSize, sampleRate);
  18294. }
  18295. void AudioSourcePlayer::audioDeviceStopped()
  18296. {
  18297. if (source != 0)
  18298. source->releaseResources();
  18299. sampleRate = 0.0;
  18300. bufferSize = 0;
  18301. tempBuffer.setSize (2, 8);
  18302. }
  18303. END_JUCE_NAMESPACE
  18304. /*** End of inlined file: juce_AudioSourcePlayer.cpp ***/
  18305. /*** Start of inlined file: juce_AudioTransportSource.cpp ***/
  18306. BEGIN_JUCE_NAMESPACE
  18307. AudioTransportSource::AudioTransportSource()
  18308. : source (0),
  18309. resamplerSource (0),
  18310. bufferingSource (0),
  18311. positionableSource (0),
  18312. masterSource (0),
  18313. gain (1.0f),
  18314. lastGain (1.0f),
  18315. playing (false),
  18316. stopped (true),
  18317. sampleRate (44100.0),
  18318. sourceSampleRate (0.0),
  18319. blockSize (128),
  18320. readAheadBufferSize (0),
  18321. isPrepared (false),
  18322. inputStreamEOF (false)
  18323. {
  18324. }
  18325. AudioTransportSource::~AudioTransportSource()
  18326. {
  18327. setSource (0);
  18328. releaseResources();
  18329. }
  18330. void AudioTransportSource::setSource (PositionableAudioSource* const newSource,
  18331. int readAheadBufferSize_,
  18332. double sourceSampleRateToCorrectFor)
  18333. {
  18334. if (source == newSource)
  18335. {
  18336. if (source == 0)
  18337. return;
  18338. setSource (0, 0, 0); // deselect and reselect to avoid releasing resources wrongly
  18339. }
  18340. readAheadBufferSize = readAheadBufferSize_;
  18341. sourceSampleRate = sourceSampleRateToCorrectFor;
  18342. ResamplingAudioSource* newResamplerSource = 0;
  18343. BufferingAudioSource* newBufferingSource = 0;
  18344. PositionableAudioSource* newPositionableSource = 0;
  18345. AudioSource* newMasterSource = 0;
  18346. ScopedPointer <ResamplingAudioSource> oldResamplerSource (resamplerSource);
  18347. ScopedPointer <BufferingAudioSource> oldBufferingSource (bufferingSource);
  18348. AudioSource* oldMasterSource = masterSource;
  18349. if (newSource != 0)
  18350. {
  18351. newPositionableSource = newSource;
  18352. if (readAheadBufferSize_ > 0)
  18353. newPositionableSource = newBufferingSource
  18354. = new BufferingAudioSource (newPositionableSource, false, readAheadBufferSize_);
  18355. newPositionableSource->setNextReadPosition (0);
  18356. if (sourceSampleRateToCorrectFor != 0)
  18357. newMasterSource = newResamplerSource
  18358. = new ResamplingAudioSource (newPositionableSource, false);
  18359. else
  18360. newMasterSource = newPositionableSource;
  18361. if (isPrepared)
  18362. {
  18363. if (newResamplerSource != 0 && sourceSampleRate > 0 && sampleRate > 0)
  18364. newResamplerSource->setResamplingRatio (sourceSampleRate / sampleRate);
  18365. newMasterSource->prepareToPlay (blockSize, sampleRate);
  18366. }
  18367. }
  18368. {
  18369. const ScopedLock sl (callbackLock);
  18370. source = newSource;
  18371. resamplerSource = newResamplerSource;
  18372. bufferingSource = newBufferingSource;
  18373. masterSource = newMasterSource;
  18374. positionableSource = newPositionableSource;
  18375. playing = false;
  18376. }
  18377. if (oldMasterSource != 0)
  18378. oldMasterSource->releaseResources();
  18379. }
  18380. void AudioTransportSource::start()
  18381. {
  18382. if ((! playing) && masterSource != 0)
  18383. {
  18384. {
  18385. const ScopedLock sl (callbackLock);
  18386. playing = true;
  18387. stopped = false;
  18388. inputStreamEOF = false;
  18389. }
  18390. sendChangeMessage (this);
  18391. }
  18392. }
  18393. void AudioTransportSource::stop()
  18394. {
  18395. if (playing)
  18396. {
  18397. {
  18398. const ScopedLock sl (callbackLock);
  18399. playing = false;
  18400. }
  18401. int n = 500;
  18402. while (--n >= 0 && ! stopped)
  18403. Thread::sleep (2);
  18404. sendChangeMessage (this);
  18405. }
  18406. }
  18407. void AudioTransportSource::setPosition (double newPosition)
  18408. {
  18409. if (sampleRate > 0.0)
  18410. setNextReadPosition (roundToInt (newPosition * sampleRate));
  18411. }
  18412. double AudioTransportSource::getCurrentPosition() const
  18413. {
  18414. if (sampleRate > 0.0)
  18415. return getNextReadPosition() / sampleRate;
  18416. else
  18417. return 0.0;
  18418. }
  18419. void AudioTransportSource::setNextReadPosition (int newPosition)
  18420. {
  18421. if (positionableSource != 0)
  18422. {
  18423. if (sampleRate > 0 && sourceSampleRate > 0)
  18424. newPosition = roundToInt (newPosition * sourceSampleRate / sampleRate);
  18425. positionableSource->setNextReadPosition (newPosition);
  18426. }
  18427. }
  18428. int AudioTransportSource::getNextReadPosition() const
  18429. {
  18430. if (positionableSource != 0)
  18431. {
  18432. const double ratio = (sampleRate > 0 && sourceSampleRate > 0) ? sampleRate / sourceSampleRate : 1.0;
  18433. return roundToInt (positionableSource->getNextReadPosition() * ratio);
  18434. }
  18435. return 0;
  18436. }
  18437. int AudioTransportSource::getTotalLength() const
  18438. {
  18439. const ScopedLock sl (callbackLock);
  18440. if (positionableSource != 0)
  18441. {
  18442. const double ratio = (sampleRate > 0 && sourceSampleRate > 0) ? sampleRate / sourceSampleRate : 1.0;
  18443. return roundToInt (positionableSource->getTotalLength() * ratio);
  18444. }
  18445. return 0;
  18446. }
  18447. bool AudioTransportSource::isLooping() const
  18448. {
  18449. const ScopedLock sl (callbackLock);
  18450. return positionableSource != 0
  18451. && positionableSource->isLooping();
  18452. }
  18453. void AudioTransportSource::setGain (const float newGain) throw()
  18454. {
  18455. gain = newGain;
  18456. }
  18457. void AudioTransportSource::prepareToPlay (int samplesPerBlockExpected,
  18458. double sampleRate_)
  18459. {
  18460. const ScopedLock sl (callbackLock);
  18461. sampleRate = sampleRate_;
  18462. blockSize = samplesPerBlockExpected;
  18463. if (masterSource != 0)
  18464. masterSource->prepareToPlay (samplesPerBlockExpected, sampleRate);
  18465. if (resamplerSource != 0 && sourceSampleRate != 0)
  18466. resamplerSource->setResamplingRatio (sourceSampleRate / sampleRate);
  18467. isPrepared = true;
  18468. }
  18469. void AudioTransportSource::releaseResources()
  18470. {
  18471. const ScopedLock sl (callbackLock);
  18472. if (masterSource != 0)
  18473. masterSource->releaseResources();
  18474. isPrepared = false;
  18475. }
  18476. void AudioTransportSource::getNextAudioBlock (const AudioSourceChannelInfo& info)
  18477. {
  18478. const ScopedLock sl (callbackLock);
  18479. inputStreamEOF = false;
  18480. if (masterSource != 0 && ! stopped)
  18481. {
  18482. masterSource->getNextAudioBlock (info);
  18483. if (! playing)
  18484. {
  18485. // just stopped playing, so fade out the last block..
  18486. for (int i = info.buffer->getNumChannels(); --i >= 0;)
  18487. info.buffer->applyGainRamp (i, info.startSample, jmin (256, info.numSamples), 1.0f, 0.0f);
  18488. if (info.numSamples > 256)
  18489. info.buffer->clear (info.startSample + 256, info.numSamples - 256);
  18490. }
  18491. if (positionableSource->getNextReadPosition() > positionableSource->getTotalLength() + 1
  18492. && ! positionableSource->isLooping())
  18493. {
  18494. playing = false;
  18495. inputStreamEOF = true;
  18496. sendChangeMessage (this);
  18497. }
  18498. stopped = ! playing;
  18499. for (int i = info.buffer->getNumChannels(); --i >= 0;)
  18500. {
  18501. info.buffer->applyGainRamp (i, info.startSample, info.numSamples,
  18502. lastGain, gain);
  18503. }
  18504. }
  18505. else
  18506. {
  18507. info.clearActiveBufferRegion();
  18508. stopped = true;
  18509. }
  18510. lastGain = gain;
  18511. }
  18512. END_JUCE_NAMESPACE
  18513. /*** End of inlined file: juce_AudioTransportSource.cpp ***/
  18514. /*** Start of inlined file: juce_BufferingAudioSource.cpp ***/
  18515. BEGIN_JUCE_NAMESPACE
  18516. class SharedBufferingAudioSourceThread : public DeletedAtShutdown,
  18517. public Thread,
  18518. private Timer
  18519. {
  18520. public:
  18521. SharedBufferingAudioSourceThread()
  18522. : Thread ("Audio Buffer")
  18523. {
  18524. }
  18525. ~SharedBufferingAudioSourceThread()
  18526. {
  18527. stopThread (10000);
  18528. clearSingletonInstance();
  18529. }
  18530. juce_DeclareSingleton (SharedBufferingAudioSourceThread, false)
  18531. void addSource (BufferingAudioSource* source)
  18532. {
  18533. const ScopedLock sl (lock);
  18534. if (! sources.contains (source))
  18535. {
  18536. sources.add (source);
  18537. startThread();
  18538. stopTimer();
  18539. }
  18540. notify();
  18541. }
  18542. void removeSource (BufferingAudioSource* source)
  18543. {
  18544. const ScopedLock sl (lock);
  18545. sources.removeValue (source);
  18546. if (sources.size() == 0)
  18547. startTimer (5000);
  18548. }
  18549. private:
  18550. Array <BufferingAudioSource*> sources;
  18551. CriticalSection lock;
  18552. void run()
  18553. {
  18554. while (! threadShouldExit())
  18555. {
  18556. bool busy = false;
  18557. for (int i = sources.size(); --i >= 0;)
  18558. {
  18559. if (threadShouldExit())
  18560. return;
  18561. const ScopedLock sl (lock);
  18562. BufferingAudioSource* const b = sources[i];
  18563. if (b != 0 && b->readNextBufferChunk())
  18564. busy = true;
  18565. }
  18566. if (! busy)
  18567. wait (500);
  18568. }
  18569. }
  18570. void timerCallback()
  18571. {
  18572. stopTimer();
  18573. if (sources.size() == 0)
  18574. deleteInstance();
  18575. }
  18576. SharedBufferingAudioSourceThread (const SharedBufferingAudioSourceThread&);
  18577. SharedBufferingAudioSourceThread& operator= (const SharedBufferingAudioSourceThread&);
  18578. };
  18579. juce_ImplementSingleton (SharedBufferingAudioSourceThread)
  18580. BufferingAudioSource::BufferingAudioSource (PositionableAudioSource* source_,
  18581. const bool deleteSourceWhenDeleted_,
  18582. int numberOfSamplesToBuffer_)
  18583. : source (source_),
  18584. deleteSourceWhenDeleted (deleteSourceWhenDeleted_),
  18585. numberOfSamplesToBuffer (jmax (1024, numberOfSamplesToBuffer_)),
  18586. buffer (2, 0),
  18587. bufferValidStart (0),
  18588. bufferValidEnd (0),
  18589. nextPlayPos (0),
  18590. wasSourceLooping (false)
  18591. {
  18592. jassert (source_ != 0);
  18593. jassert (numberOfSamplesToBuffer_ > 1024); // not much point using this class if you're
  18594. // not using a larger buffer..
  18595. }
  18596. BufferingAudioSource::~BufferingAudioSource()
  18597. {
  18598. SharedBufferingAudioSourceThread* const thread = SharedBufferingAudioSourceThread::getInstanceWithoutCreating();
  18599. if (thread != 0)
  18600. thread->removeSource (this);
  18601. if (deleteSourceWhenDeleted)
  18602. delete source;
  18603. }
  18604. void BufferingAudioSource::prepareToPlay (int samplesPerBlockExpected, double sampleRate_)
  18605. {
  18606. source->prepareToPlay (samplesPerBlockExpected, sampleRate_);
  18607. sampleRate = sampleRate_;
  18608. buffer.setSize (2, jmax (samplesPerBlockExpected * 2, numberOfSamplesToBuffer));
  18609. buffer.clear();
  18610. bufferValidStart = 0;
  18611. bufferValidEnd = 0;
  18612. SharedBufferingAudioSourceThread::getInstance()->addSource (this);
  18613. while (bufferValidEnd - bufferValidStart < jmin (((int) sampleRate_) / 4,
  18614. buffer.getNumSamples() / 2))
  18615. {
  18616. SharedBufferingAudioSourceThread::getInstance()->notify();
  18617. Thread::sleep (5);
  18618. }
  18619. }
  18620. void BufferingAudioSource::releaseResources()
  18621. {
  18622. SharedBufferingAudioSourceThread* const thread = SharedBufferingAudioSourceThread::getInstanceWithoutCreating();
  18623. if (thread != 0)
  18624. thread->removeSource (this);
  18625. buffer.setSize (2, 0);
  18626. source->releaseResources();
  18627. }
  18628. void BufferingAudioSource::getNextAudioBlock (const AudioSourceChannelInfo& info)
  18629. {
  18630. const ScopedLock sl (bufferStartPosLock);
  18631. const int validStart = jlimit (bufferValidStart, bufferValidEnd, nextPlayPos) - nextPlayPos;
  18632. const int validEnd = jlimit (bufferValidStart, bufferValidEnd, nextPlayPos + info.numSamples) - nextPlayPos;
  18633. if (validStart == validEnd)
  18634. {
  18635. // total cache miss
  18636. info.clearActiveBufferRegion();
  18637. }
  18638. else
  18639. {
  18640. if (validStart > 0)
  18641. info.buffer->clear (info.startSample, validStart); // partial cache miss at start
  18642. if (validEnd < info.numSamples)
  18643. info.buffer->clear (info.startSample + validEnd,
  18644. info.numSamples - validEnd); // partial cache miss at end
  18645. if (validStart < validEnd)
  18646. {
  18647. for (int chan = jmin (2, info.buffer->getNumChannels()); --chan >= 0;)
  18648. {
  18649. const int startBufferIndex = (validStart + nextPlayPos) % buffer.getNumSamples();
  18650. const int endBufferIndex = (validEnd + nextPlayPos) % buffer.getNumSamples();
  18651. if (startBufferIndex < endBufferIndex)
  18652. {
  18653. info.buffer->copyFrom (chan, info.startSample + validStart,
  18654. buffer,
  18655. chan, startBufferIndex,
  18656. validEnd - validStart);
  18657. }
  18658. else
  18659. {
  18660. const int initialSize = buffer.getNumSamples() - startBufferIndex;
  18661. info.buffer->copyFrom (chan, info.startSample + validStart,
  18662. buffer,
  18663. chan, startBufferIndex,
  18664. initialSize);
  18665. info.buffer->copyFrom (chan, info.startSample + validStart + initialSize,
  18666. buffer,
  18667. chan, 0,
  18668. (validEnd - validStart) - initialSize);
  18669. }
  18670. }
  18671. }
  18672. nextPlayPos += info.numSamples;
  18673. if (source->isLooping() && nextPlayPos > 0)
  18674. nextPlayPos %= source->getTotalLength();
  18675. }
  18676. SharedBufferingAudioSourceThread* const thread = SharedBufferingAudioSourceThread::getInstanceWithoutCreating();
  18677. if (thread != 0)
  18678. thread->notify();
  18679. }
  18680. int BufferingAudioSource::getNextReadPosition() const
  18681. {
  18682. return (source->isLooping() && nextPlayPos > 0)
  18683. ? nextPlayPos % source->getTotalLength()
  18684. : nextPlayPos;
  18685. }
  18686. void BufferingAudioSource::setNextReadPosition (int newPosition)
  18687. {
  18688. const ScopedLock sl (bufferStartPosLock);
  18689. nextPlayPos = newPosition;
  18690. SharedBufferingAudioSourceThread* const thread = SharedBufferingAudioSourceThread::getInstanceWithoutCreating();
  18691. if (thread != 0)
  18692. thread->notify();
  18693. }
  18694. bool BufferingAudioSource::readNextBufferChunk()
  18695. {
  18696. int newBVS, newBVE, sectionToReadStart, sectionToReadEnd;
  18697. {
  18698. const ScopedLock sl (bufferStartPosLock);
  18699. if (wasSourceLooping != isLooping())
  18700. {
  18701. wasSourceLooping = isLooping();
  18702. bufferValidStart = 0;
  18703. bufferValidEnd = 0;
  18704. }
  18705. newBVS = jmax (0, nextPlayPos);
  18706. newBVE = newBVS + buffer.getNumSamples() - 4;
  18707. sectionToReadStart = 0;
  18708. sectionToReadEnd = 0;
  18709. const int maxChunkSize = 2048;
  18710. if (newBVS < bufferValidStart || newBVS >= bufferValidEnd)
  18711. {
  18712. newBVE = jmin (newBVE, newBVS + maxChunkSize);
  18713. sectionToReadStart = newBVS;
  18714. sectionToReadEnd = newBVE;
  18715. bufferValidStart = 0;
  18716. bufferValidEnd = 0;
  18717. }
  18718. else if (abs (newBVS - bufferValidStart) > 512
  18719. || abs (newBVE - bufferValidEnd) > 512)
  18720. {
  18721. newBVE = jmin (newBVE, bufferValidEnd + maxChunkSize);
  18722. sectionToReadStart = bufferValidEnd;
  18723. sectionToReadEnd = newBVE;
  18724. bufferValidStart = newBVS;
  18725. bufferValidEnd = jmin (bufferValidEnd, newBVE);
  18726. }
  18727. }
  18728. if (sectionToReadStart != sectionToReadEnd)
  18729. {
  18730. const int bufferIndexStart = sectionToReadStart % buffer.getNumSamples();
  18731. const int bufferIndexEnd = sectionToReadEnd % buffer.getNumSamples();
  18732. if (bufferIndexStart < bufferIndexEnd)
  18733. {
  18734. readBufferSection (sectionToReadStart,
  18735. sectionToReadEnd - sectionToReadStart,
  18736. bufferIndexStart);
  18737. }
  18738. else
  18739. {
  18740. const int initialSize = buffer.getNumSamples() - bufferIndexStart;
  18741. readBufferSection (sectionToReadStart,
  18742. initialSize,
  18743. bufferIndexStart);
  18744. readBufferSection (sectionToReadStart + initialSize,
  18745. (sectionToReadEnd - sectionToReadStart) - initialSize,
  18746. 0);
  18747. }
  18748. const ScopedLock sl2 (bufferStartPosLock);
  18749. bufferValidStart = newBVS;
  18750. bufferValidEnd = newBVE;
  18751. return true;
  18752. }
  18753. else
  18754. {
  18755. return false;
  18756. }
  18757. }
  18758. void BufferingAudioSource::readBufferSection (int start, int length, int bufferOffset)
  18759. {
  18760. if (source->getNextReadPosition() != start)
  18761. source->setNextReadPosition (start);
  18762. AudioSourceChannelInfo info;
  18763. info.buffer = &buffer;
  18764. info.startSample = bufferOffset;
  18765. info.numSamples = length;
  18766. source->getNextAudioBlock (info);
  18767. }
  18768. END_JUCE_NAMESPACE
  18769. /*** End of inlined file: juce_BufferingAudioSource.cpp ***/
  18770. /*** Start of inlined file: juce_ChannelRemappingAudioSource.cpp ***/
  18771. BEGIN_JUCE_NAMESPACE
  18772. ChannelRemappingAudioSource::ChannelRemappingAudioSource (AudioSource* const source_,
  18773. const bool deleteSourceWhenDeleted_)
  18774. : requiredNumberOfChannels (2),
  18775. source (source_),
  18776. deleteSourceWhenDeleted (deleteSourceWhenDeleted_),
  18777. buffer (2, 16)
  18778. {
  18779. remappedInfo.buffer = &buffer;
  18780. remappedInfo.startSample = 0;
  18781. }
  18782. ChannelRemappingAudioSource::~ChannelRemappingAudioSource()
  18783. {
  18784. if (deleteSourceWhenDeleted)
  18785. delete source;
  18786. }
  18787. void ChannelRemappingAudioSource::setNumberOfChannelsToProduce (const int requiredNumberOfChannels_) throw()
  18788. {
  18789. const ScopedLock sl (lock);
  18790. requiredNumberOfChannels = requiredNumberOfChannels_;
  18791. }
  18792. void ChannelRemappingAudioSource::clearAllMappings() throw()
  18793. {
  18794. const ScopedLock sl (lock);
  18795. remappedInputs.clear();
  18796. remappedOutputs.clear();
  18797. }
  18798. void ChannelRemappingAudioSource::setInputChannelMapping (const int destIndex, const int sourceIndex) throw()
  18799. {
  18800. const ScopedLock sl (lock);
  18801. while (remappedInputs.size() < destIndex)
  18802. remappedInputs.add (-1);
  18803. remappedInputs.set (destIndex, sourceIndex);
  18804. }
  18805. void ChannelRemappingAudioSource::setOutputChannelMapping (const int sourceIndex, const int destIndex) throw()
  18806. {
  18807. const ScopedLock sl (lock);
  18808. while (remappedOutputs.size() < sourceIndex)
  18809. remappedOutputs.add (-1);
  18810. remappedOutputs.set (sourceIndex, destIndex);
  18811. }
  18812. int ChannelRemappingAudioSource::getRemappedInputChannel (const int inputChannelIndex) const throw()
  18813. {
  18814. const ScopedLock sl (lock);
  18815. if (inputChannelIndex >= 0 && inputChannelIndex < remappedInputs.size())
  18816. return remappedInputs.getUnchecked (inputChannelIndex);
  18817. return -1;
  18818. }
  18819. int ChannelRemappingAudioSource::getRemappedOutputChannel (const int outputChannelIndex) const throw()
  18820. {
  18821. const ScopedLock sl (lock);
  18822. if (outputChannelIndex >= 0 && outputChannelIndex < remappedOutputs.size())
  18823. return remappedOutputs .getUnchecked (outputChannelIndex);
  18824. return -1;
  18825. }
  18826. void ChannelRemappingAudioSource::prepareToPlay (int samplesPerBlockExpected, double sampleRate)
  18827. {
  18828. source->prepareToPlay (samplesPerBlockExpected, sampleRate);
  18829. }
  18830. void ChannelRemappingAudioSource::releaseResources()
  18831. {
  18832. source->releaseResources();
  18833. }
  18834. void ChannelRemappingAudioSource::getNextAudioBlock (const AudioSourceChannelInfo& bufferToFill)
  18835. {
  18836. const ScopedLock sl (lock);
  18837. buffer.setSize (requiredNumberOfChannels, bufferToFill.numSamples, false, false, true);
  18838. const int numChans = bufferToFill.buffer->getNumChannels();
  18839. int i;
  18840. for (i = 0; i < buffer.getNumChannels(); ++i)
  18841. {
  18842. const int remappedChan = getRemappedInputChannel (i);
  18843. if (remappedChan >= 0 && remappedChan < numChans)
  18844. {
  18845. buffer.copyFrom (i, 0, *bufferToFill.buffer,
  18846. remappedChan,
  18847. bufferToFill.startSample,
  18848. bufferToFill.numSamples);
  18849. }
  18850. else
  18851. {
  18852. buffer.clear (i, 0, bufferToFill.numSamples);
  18853. }
  18854. }
  18855. remappedInfo.numSamples = bufferToFill.numSamples;
  18856. source->getNextAudioBlock (remappedInfo);
  18857. bufferToFill.clearActiveBufferRegion();
  18858. for (i = 0; i < requiredNumberOfChannels; ++i)
  18859. {
  18860. const int remappedChan = getRemappedOutputChannel (i);
  18861. if (remappedChan >= 0 && remappedChan < numChans)
  18862. {
  18863. bufferToFill.buffer->addFrom (remappedChan, bufferToFill.startSample,
  18864. buffer, i, 0, bufferToFill.numSamples);
  18865. }
  18866. }
  18867. }
  18868. XmlElement* ChannelRemappingAudioSource::createXml() const throw()
  18869. {
  18870. XmlElement* e = new XmlElement ("MAPPINGS");
  18871. String ins, outs;
  18872. int i;
  18873. const ScopedLock sl (lock);
  18874. for (i = 0; i < remappedInputs.size(); ++i)
  18875. ins << remappedInputs.getUnchecked(i) << ' ';
  18876. for (i = 0; i < remappedOutputs.size(); ++i)
  18877. outs << remappedOutputs.getUnchecked(i) << ' ';
  18878. e->setAttribute ("inputs", ins.trimEnd());
  18879. e->setAttribute ("outputs", outs.trimEnd());
  18880. return e;
  18881. }
  18882. void ChannelRemappingAudioSource::restoreFromXml (const XmlElement& e) throw()
  18883. {
  18884. if (e.hasTagName ("MAPPINGS"))
  18885. {
  18886. const ScopedLock sl (lock);
  18887. clearAllMappings();
  18888. StringArray ins, outs;
  18889. ins.addTokens (e.getStringAttribute ("inputs"), false);
  18890. outs.addTokens (e.getStringAttribute ("outputs"), false);
  18891. int i;
  18892. for (i = 0; i < ins.size(); ++i)
  18893. remappedInputs.add (ins[i].getIntValue());
  18894. for (i = 0; i < outs.size(); ++i)
  18895. remappedOutputs.add (outs[i].getIntValue());
  18896. }
  18897. }
  18898. END_JUCE_NAMESPACE
  18899. /*** End of inlined file: juce_ChannelRemappingAudioSource.cpp ***/
  18900. /*** Start of inlined file: juce_IIRFilterAudioSource.cpp ***/
  18901. BEGIN_JUCE_NAMESPACE
  18902. IIRFilterAudioSource::IIRFilterAudioSource (AudioSource* const inputSource,
  18903. const bool deleteInputWhenDeleted_)
  18904. : input (inputSource),
  18905. deleteInputWhenDeleted (deleteInputWhenDeleted_)
  18906. {
  18907. jassert (inputSource != 0);
  18908. for (int i = 2; --i >= 0;)
  18909. iirFilters.add (new IIRFilter());
  18910. }
  18911. IIRFilterAudioSource::~IIRFilterAudioSource()
  18912. {
  18913. if (deleteInputWhenDeleted)
  18914. delete input;
  18915. }
  18916. void IIRFilterAudioSource::setFilterParameters (const IIRFilter& newSettings)
  18917. {
  18918. for (int i = iirFilters.size(); --i >= 0;)
  18919. iirFilters.getUnchecked(i)->copyCoefficientsFrom (newSettings);
  18920. }
  18921. void IIRFilterAudioSource::prepareToPlay (int samplesPerBlockExpected, double sampleRate)
  18922. {
  18923. input->prepareToPlay (samplesPerBlockExpected, sampleRate);
  18924. for (int i = iirFilters.size(); --i >= 0;)
  18925. iirFilters.getUnchecked(i)->reset();
  18926. }
  18927. void IIRFilterAudioSource::releaseResources()
  18928. {
  18929. input->releaseResources();
  18930. }
  18931. void IIRFilterAudioSource::getNextAudioBlock (const AudioSourceChannelInfo& bufferToFill)
  18932. {
  18933. input->getNextAudioBlock (bufferToFill);
  18934. const int numChannels = bufferToFill.buffer->getNumChannels();
  18935. while (numChannels > iirFilters.size())
  18936. iirFilters.add (new IIRFilter (*iirFilters.getUnchecked (0)));
  18937. for (int i = 0; i < numChannels; ++i)
  18938. iirFilters.getUnchecked(i)
  18939. ->processSamples (bufferToFill.buffer->getSampleData (i, bufferToFill.startSample),
  18940. bufferToFill.numSamples);
  18941. }
  18942. END_JUCE_NAMESPACE
  18943. /*** End of inlined file: juce_IIRFilterAudioSource.cpp ***/
  18944. /*** Start of inlined file: juce_MixerAudioSource.cpp ***/
  18945. BEGIN_JUCE_NAMESPACE
  18946. MixerAudioSource::MixerAudioSource()
  18947. : tempBuffer (2, 0),
  18948. currentSampleRate (0.0),
  18949. bufferSizeExpected (0)
  18950. {
  18951. }
  18952. MixerAudioSource::~MixerAudioSource()
  18953. {
  18954. removeAllInputs();
  18955. }
  18956. void MixerAudioSource::addInputSource (AudioSource* input, const bool deleteWhenRemoved)
  18957. {
  18958. if (input != 0 && ! inputs.contains (input))
  18959. {
  18960. double localRate;
  18961. int localBufferSize;
  18962. {
  18963. const ScopedLock sl (lock);
  18964. localRate = currentSampleRate;
  18965. localBufferSize = bufferSizeExpected;
  18966. }
  18967. if (localRate != 0.0)
  18968. input->prepareToPlay (localBufferSize, localRate);
  18969. const ScopedLock sl (lock);
  18970. inputsToDelete.setBit (inputs.size(), deleteWhenRemoved);
  18971. inputs.add (input);
  18972. }
  18973. }
  18974. void MixerAudioSource::removeInputSource (AudioSource* input, const bool deleteInput)
  18975. {
  18976. if (input != 0)
  18977. {
  18978. int index;
  18979. {
  18980. const ScopedLock sl (lock);
  18981. index = inputs.indexOf (input);
  18982. if (index >= 0)
  18983. {
  18984. inputsToDelete.shiftBits (index, 1);
  18985. inputs.remove (index);
  18986. }
  18987. }
  18988. if (index >= 0)
  18989. {
  18990. input->releaseResources();
  18991. if (deleteInput)
  18992. delete input;
  18993. }
  18994. }
  18995. }
  18996. void MixerAudioSource::removeAllInputs()
  18997. {
  18998. VoidArray inputsCopy;
  18999. BigInteger inputsToDeleteCopy;
  19000. {
  19001. const ScopedLock sl (lock);
  19002. inputsCopy = inputs;
  19003. inputsToDeleteCopy = inputsToDelete;
  19004. }
  19005. for (int i = inputsCopy.size(); --i >= 0;)
  19006. if (inputsToDeleteCopy[i])
  19007. delete (AudioSource*) inputsCopy[i];
  19008. }
  19009. void MixerAudioSource::prepareToPlay (int samplesPerBlockExpected, double sampleRate)
  19010. {
  19011. tempBuffer.setSize (2, samplesPerBlockExpected);
  19012. const ScopedLock sl (lock);
  19013. currentSampleRate = sampleRate;
  19014. bufferSizeExpected = samplesPerBlockExpected;
  19015. for (int i = inputs.size(); --i >= 0;)
  19016. ((AudioSource*) inputs.getUnchecked(i))->prepareToPlay (samplesPerBlockExpected,
  19017. sampleRate);
  19018. }
  19019. void MixerAudioSource::releaseResources()
  19020. {
  19021. const ScopedLock sl (lock);
  19022. for (int i = inputs.size(); --i >= 0;)
  19023. ((AudioSource*) inputs.getUnchecked(i))->releaseResources();
  19024. tempBuffer.setSize (2, 0);
  19025. currentSampleRate = 0;
  19026. bufferSizeExpected = 0;
  19027. }
  19028. void MixerAudioSource::getNextAudioBlock (const AudioSourceChannelInfo& info)
  19029. {
  19030. const ScopedLock sl (lock);
  19031. if (inputs.size() > 0)
  19032. {
  19033. ((AudioSource*) inputs.getUnchecked(0))->getNextAudioBlock (info);
  19034. if (inputs.size() > 1)
  19035. {
  19036. tempBuffer.setSize (jmax (1, info.buffer->getNumChannels()),
  19037. info.buffer->getNumSamples());
  19038. AudioSourceChannelInfo info2;
  19039. info2.buffer = &tempBuffer;
  19040. info2.numSamples = info.numSamples;
  19041. info2.startSample = 0;
  19042. for (int i = 1; i < inputs.size(); ++i)
  19043. {
  19044. ((AudioSource*) inputs.getUnchecked(i))->getNextAudioBlock (info2);
  19045. for (int chan = 0; chan < info.buffer->getNumChannels(); ++chan)
  19046. info.buffer->addFrom (chan, info.startSample, tempBuffer, chan, 0, info.numSamples);
  19047. }
  19048. }
  19049. }
  19050. else
  19051. {
  19052. info.clearActiveBufferRegion();
  19053. }
  19054. }
  19055. END_JUCE_NAMESPACE
  19056. /*** End of inlined file: juce_MixerAudioSource.cpp ***/
  19057. /*** Start of inlined file: juce_ResamplingAudioSource.cpp ***/
  19058. BEGIN_JUCE_NAMESPACE
  19059. ResamplingAudioSource::ResamplingAudioSource (AudioSource* const inputSource,
  19060. const bool deleteInputWhenDeleted_)
  19061. : input (inputSource),
  19062. deleteInputWhenDeleted (deleteInputWhenDeleted_),
  19063. ratio (1.0),
  19064. lastRatio (1.0),
  19065. buffer (2, 0),
  19066. sampsInBuffer (0)
  19067. {
  19068. jassert (input != 0);
  19069. }
  19070. ResamplingAudioSource::~ResamplingAudioSource()
  19071. {
  19072. if (deleteInputWhenDeleted)
  19073. delete input;
  19074. }
  19075. void ResamplingAudioSource::setResamplingRatio (const double samplesInPerOutputSample)
  19076. {
  19077. jassert (samplesInPerOutputSample > 0);
  19078. const ScopedLock sl (ratioLock);
  19079. ratio = jmax (0.0, samplesInPerOutputSample);
  19080. }
  19081. void ResamplingAudioSource::prepareToPlay (int samplesPerBlockExpected,
  19082. double sampleRate)
  19083. {
  19084. const ScopedLock sl (ratioLock);
  19085. input->prepareToPlay (samplesPerBlockExpected, sampleRate);
  19086. buffer.setSize (2, roundToInt (samplesPerBlockExpected * ratio) + 32);
  19087. buffer.clear();
  19088. sampsInBuffer = 0;
  19089. bufferPos = 0;
  19090. subSampleOffset = 0.0;
  19091. createLowPass (ratio);
  19092. resetFilters();
  19093. }
  19094. void ResamplingAudioSource::releaseResources()
  19095. {
  19096. input->releaseResources();
  19097. buffer.setSize (2, 0);
  19098. }
  19099. void ResamplingAudioSource::getNextAudioBlock (const AudioSourceChannelInfo& info)
  19100. {
  19101. const ScopedLock sl (ratioLock);
  19102. if (lastRatio != ratio)
  19103. {
  19104. createLowPass (ratio);
  19105. lastRatio = ratio;
  19106. }
  19107. const int sampsNeeded = roundToInt (info.numSamples * ratio) + 2;
  19108. int bufferSize = buffer.getNumSamples();
  19109. if (bufferSize < sampsNeeded + 8)
  19110. {
  19111. bufferPos %= bufferSize;
  19112. bufferSize = sampsNeeded + 32;
  19113. buffer.setSize (buffer.getNumChannels(), bufferSize, true, true);
  19114. }
  19115. bufferPos %= bufferSize;
  19116. int endOfBufferPos = bufferPos + sampsInBuffer;
  19117. while (sampsNeeded > sampsInBuffer)
  19118. {
  19119. endOfBufferPos %= bufferSize;
  19120. int numToDo = jmin (sampsNeeded - sampsInBuffer,
  19121. bufferSize - endOfBufferPos);
  19122. AudioSourceChannelInfo readInfo;
  19123. readInfo.buffer = &buffer;
  19124. readInfo.numSamples = numToDo;
  19125. readInfo.startSample = endOfBufferPos;
  19126. input->getNextAudioBlock (readInfo);
  19127. if (ratio > 1.0001)
  19128. {
  19129. // for down-sampling, pre-apply the filter..
  19130. for (int i = jmin (2, info.buffer->getNumChannels()); --i >= 0;)
  19131. applyFilter (buffer.getSampleData (i, endOfBufferPos), numToDo, filterStates[i]);
  19132. }
  19133. sampsInBuffer += numToDo;
  19134. endOfBufferPos += numToDo;
  19135. }
  19136. float* dl = info.buffer->getSampleData (0, info.startSample);
  19137. float* dr = (info.buffer->getNumChannels() > 1) ? info.buffer->getSampleData (1, info.startSample) : 0;
  19138. const float* const bl = buffer.getSampleData (0, 0);
  19139. const float* const br = buffer.getSampleData (1, 0);
  19140. int nextPos = (bufferPos + 1) % bufferSize;
  19141. for (int m = info.numSamples; --m >= 0;)
  19142. {
  19143. const float alpha = (float) subSampleOffset;
  19144. const float invAlpha = 1.0f - alpha;
  19145. *dl++ = bl [bufferPos] * invAlpha + bl [nextPos] * alpha;
  19146. if (dr != 0)
  19147. *dr++ = br [bufferPos] * invAlpha + br [nextPos] * alpha;
  19148. subSampleOffset += ratio;
  19149. jassert (sampsInBuffer > 0);
  19150. while (subSampleOffset >= 1.0)
  19151. {
  19152. if (++bufferPos >= bufferSize)
  19153. bufferPos = 0;
  19154. --sampsInBuffer;
  19155. nextPos = (bufferPos + 1) % bufferSize;
  19156. subSampleOffset -= 1.0;
  19157. }
  19158. }
  19159. if (ratio < 0.9999)
  19160. {
  19161. // for up-sampling, apply the filter after transposing..
  19162. for (int i = jmin (2, info.buffer->getNumChannels()); --i >= 0;)
  19163. applyFilter (info.buffer->getSampleData (i, info.startSample), info.numSamples, filterStates[i]);
  19164. }
  19165. else if (ratio <= 1.0001)
  19166. {
  19167. // if the filter's not currently being applied, keep it stoked with the last couple of samples to avoid discontinuities
  19168. for (int i = jmin (2, info.buffer->getNumChannels()); --i >= 0;)
  19169. {
  19170. const float* const endOfBuffer = info.buffer->getSampleData (i, info.startSample + info.numSamples - 1);
  19171. FilterState& fs = filterStates[i];
  19172. if (info.numSamples > 1)
  19173. {
  19174. fs.y2 = fs.x2 = *(endOfBuffer - 1);
  19175. }
  19176. else
  19177. {
  19178. fs.y2 = fs.y1;
  19179. fs.x2 = fs.x1;
  19180. }
  19181. fs.y1 = fs.x1 = *endOfBuffer;
  19182. }
  19183. }
  19184. jassert (sampsInBuffer >= 0);
  19185. }
  19186. void ResamplingAudioSource::createLowPass (const double frequencyRatio)
  19187. {
  19188. const double proportionalRate = (frequencyRatio > 1.0) ? 0.5 / frequencyRatio
  19189. : 0.5 * frequencyRatio;
  19190. const double n = 1.0 / tan (double_Pi * jmax (0.001, proportionalRate));
  19191. const double nSquared = n * n;
  19192. const double c1 = 1.0 / (1.0 + std::sqrt (2.0) * n + nSquared);
  19193. setFilterCoefficients (c1,
  19194. c1 * 2.0f,
  19195. c1,
  19196. 1.0,
  19197. c1 * 2.0 * (1.0 - nSquared),
  19198. c1 * (1.0 - std::sqrt (2.0) * n + nSquared));
  19199. }
  19200. void ResamplingAudioSource::setFilterCoefficients (double c1, double c2, double c3, double c4, double c5, double c6)
  19201. {
  19202. const double a = 1.0 / c4;
  19203. c1 *= a;
  19204. c2 *= a;
  19205. c3 *= a;
  19206. c5 *= a;
  19207. c6 *= a;
  19208. coefficients[0] = c1;
  19209. coefficients[1] = c2;
  19210. coefficients[2] = c3;
  19211. coefficients[3] = c4;
  19212. coefficients[4] = c5;
  19213. coefficients[5] = c6;
  19214. }
  19215. void ResamplingAudioSource::resetFilters()
  19216. {
  19217. zeromem (filterStates, sizeof (filterStates));
  19218. }
  19219. void ResamplingAudioSource::applyFilter (float* samples, int num, FilterState& fs)
  19220. {
  19221. while (--num >= 0)
  19222. {
  19223. const double in = *samples;
  19224. double out = coefficients[0] * in
  19225. + coefficients[1] * fs.x1
  19226. + coefficients[2] * fs.x2
  19227. - coefficients[4] * fs.y1
  19228. - coefficients[5] * fs.y2;
  19229. #if JUCE_INTEL
  19230. if (! (out < -1.0e-8 || out > 1.0e-8))
  19231. out = 0;
  19232. #endif
  19233. fs.x2 = fs.x1;
  19234. fs.x1 = in;
  19235. fs.y2 = fs.y1;
  19236. fs.y1 = out;
  19237. *samples++ = (float) out;
  19238. }
  19239. }
  19240. END_JUCE_NAMESPACE
  19241. /*** End of inlined file: juce_ResamplingAudioSource.cpp ***/
  19242. /*** Start of inlined file: juce_ToneGeneratorAudioSource.cpp ***/
  19243. BEGIN_JUCE_NAMESPACE
  19244. ToneGeneratorAudioSource::ToneGeneratorAudioSource()
  19245. : frequency (1000.0),
  19246. sampleRate (44100.0),
  19247. currentPhase (0.0),
  19248. phasePerSample (0.0),
  19249. amplitude (0.5f)
  19250. {
  19251. }
  19252. ToneGeneratorAudioSource::~ToneGeneratorAudioSource()
  19253. {
  19254. }
  19255. void ToneGeneratorAudioSource::setAmplitude (const float newAmplitude)
  19256. {
  19257. amplitude = newAmplitude;
  19258. }
  19259. void ToneGeneratorAudioSource::setFrequency (const double newFrequencyHz)
  19260. {
  19261. frequency = newFrequencyHz;
  19262. phasePerSample = 0.0;
  19263. }
  19264. void ToneGeneratorAudioSource::prepareToPlay (int /*samplesPerBlockExpected*/,
  19265. double sampleRate_)
  19266. {
  19267. currentPhase = 0.0;
  19268. phasePerSample = 0.0;
  19269. sampleRate = sampleRate_;
  19270. }
  19271. void ToneGeneratorAudioSource::releaseResources()
  19272. {
  19273. }
  19274. void ToneGeneratorAudioSource::getNextAudioBlock (const AudioSourceChannelInfo& info)
  19275. {
  19276. if (phasePerSample == 0.0)
  19277. phasePerSample = double_Pi * 2.0 / (sampleRate / frequency);
  19278. for (int i = 0; i < info.numSamples; ++i)
  19279. {
  19280. const float sample = amplitude * (float) std::sin (currentPhase);
  19281. currentPhase += phasePerSample;
  19282. for (int j = info.buffer->getNumChannels(); --j >= 0;)
  19283. *info.buffer->getSampleData (j, info.startSample + i) = sample;
  19284. }
  19285. }
  19286. END_JUCE_NAMESPACE
  19287. /*** End of inlined file: juce_ToneGeneratorAudioSource.cpp ***/
  19288. /*** Start of inlined file: juce_AudioDeviceManager.cpp ***/
  19289. BEGIN_JUCE_NAMESPACE
  19290. AudioDeviceManager::AudioDeviceSetup::AudioDeviceSetup()
  19291. : sampleRate (0),
  19292. bufferSize (0),
  19293. useDefaultInputChannels (true),
  19294. useDefaultOutputChannels (true)
  19295. {
  19296. }
  19297. bool AudioDeviceManager::AudioDeviceSetup::operator== (const AudioDeviceManager::AudioDeviceSetup& other) const
  19298. {
  19299. return outputDeviceName == other.outputDeviceName
  19300. && inputDeviceName == other.inputDeviceName
  19301. && sampleRate == other.sampleRate
  19302. && bufferSize == other.bufferSize
  19303. && inputChannels == other.inputChannels
  19304. && useDefaultInputChannels == other.useDefaultInputChannels
  19305. && outputChannels == other.outputChannels
  19306. && useDefaultOutputChannels == other.useDefaultOutputChannels;
  19307. }
  19308. AudioDeviceManager::AudioDeviceManager()
  19309. : currentAudioDevice (0),
  19310. numInputChansNeeded (0),
  19311. numOutputChansNeeded (2),
  19312. listNeedsScanning (true),
  19313. useInputNames (false),
  19314. inputLevelMeasurementEnabledCount (0),
  19315. inputLevel (0),
  19316. tempBuffer (2, 2),
  19317. defaultMidiOutput (0),
  19318. cpuUsageMs (0),
  19319. timeToCpuScale (0)
  19320. {
  19321. callbackHandler.owner = this;
  19322. }
  19323. AudioDeviceManager::~AudioDeviceManager()
  19324. {
  19325. currentAudioDevice = 0;
  19326. defaultMidiOutput = 0;
  19327. }
  19328. void AudioDeviceManager::createDeviceTypesIfNeeded()
  19329. {
  19330. if (availableDeviceTypes.size() == 0)
  19331. {
  19332. createAudioDeviceTypes (availableDeviceTypes);
  19333. while (lastDeviceTypeConfigs.size() < availableDeviceTypes.size())
  19334. lastDeviceTypeConfigs.add (new AudioDeviceSetup());
  19335. if (availableDeviceTypes.size() > 0)
  19336. currentDeviceType = availableDeviceTypes.getUnchecked(0)->getTypeName();
  19337. }
  19338. }
  19339. const OwnedArray <AudioIODeviceType>& AudioDeviceManager::getAvailableDeviceTypes()
  19340. {
  19341. scanDevicesIfNeeded();
  19342. return availableDeviceTypes;
  19343. }
  19344. AudioIODeviceType* juce_createAudioIODeviceType_CoreAudio();
  19345. AudioIODeviceType* juce_createAudioIODeviceType_iPhoneAudio();
  19346. AudioIODeviceType* juce_createAudioIODeviceType_WASAPI();
  19347. AudioIODeviceType* juce_createAudioIODeviceType_DirectSound();
  19348. AudioIODeviceType* juce_createAudioIODeviceType_ASIO();
  19349. AudioIODeviceType* juce_createAudioIODeviceType_ALSA();
  19350. AudioIODeviceType* juce_createAudioIODeviceType_JACK();
  19351. void AudioDeviceManager::createAudioDeviceTypes (OwnedArray <AudioIODeviceType>& list)
  19352. {
  19353. (void) list; // (to avoid 'unused param' warnings)
  19354. #if JUCE_WINDOWS
  19355. #if JUCE_WASAPI
  19356. if (SystemStats::getOperatingSystemType() >= SystemStats::WinVista)
  19357. list.add (juce_createAudioIODeviceType_WASAPI());
  19358. #endif
  19359. #if JUCE_DIRECTSOUND
  19360. list.add (juce_createAudioIODeviceType_DirectSound());
  19361. #endif
  19362. #if JUCE_ASIO
  19363. list.add (juce_createAudioIODeviceType_ASIO());
  19364. #endif
  19365. #endif
  19366. #if JUCE_MAC
  19367. list.add (juce_createAudioIODeviceType_CoreAudio());
  19368. #endif
  19369. #if JUCE_IPHONE
  19370. list.add (juce_createAudioIODeviceType_iPhoneAudio());
  19371. #endif
  19372. #if JUCE_LINUX && JUCE_ALSA
  19373. list.add (juce_createAudioIODeviceType_ALSA());
  19374. #endif
  19375. #if JUCE_LINUX && JUCE_JACK
  19376. list.add (juce_createAudioIODeviceType_JACK());
  19377. #endif
  19378. }
  19379. const String AudioDeviceManager::initialise (const int numInputChannelsNeeded,
  19380. const int numOutputChannelsNeeded,
  19381. const XmlElement* const e,
  19382. const bool selectDefaultDeviceOnFailure,
  19383. const String& preferredDefaultDeviceName,
  19384. const AudioDeviceSetup* preferredSetupOptions)
  19385. {
  19386. scanDevicesIfNeeded();
  19387. numInputChansNeeded = numInputChannelsNeeded;
  19388. numOutputChansNeeded = numOutputChannelsNeeded;
  19389. if (e != 0 && e->hasTagName ("DEVICESETUP"))
  19390. {
  19391. lastExplicitSettings = new XmlElement (*e);
  19392. String error;
  19393. AudioDeviceSetup setup;
  19394. if (preferredSetupOptions != 0)
  19395. setup = *preferredSetupOptions;
  19396. if (e->getStringAttribute ("audioDeviceName").isNotEmpty())
  19397. {
  19398. setup.inputDeviceName = setup.outputDeviceName
  19399. = e->getStringAttribute ("audioDeviceName");
  19400. }
  19401. else
  19402. {
  19403. setup.inputDeviceName = e->getStringAttribute ("audioInputDeviceName");
  19404. setup.outputDeviceName = e->getStringAttribute ("audioOutputDeviceName");
  19405. }
  19406. currentDeviceType = e->getStringAttribute ("deviceType");
  19407. if (currentDeviceType.isEmpty())
  19408. {
  19409. AudioIODeviceType* const type = findType (setup.inputDeviceName, setup.outputDeviceName);
  19410. if (type != 0)
  19411. currentDeviceType = type->getTypeName();
  19412. else if (availableDeviceTypes.size() > 0)
  19413. currentDeviceType = availableDeviceTypes[0]->getTypeName();
  19414. }
  19415. setup.bufferSize = e->getIntAttribute ("audioDeviceBufferSize");
  19416. setup.sampleRate = e->getDoubleAttribute ("audioDeviceRate");
  19417. setup.inputChannels.parseString (e->getStringAttribute ("audioDeviceInChans", "11"), 2);
  19418. setup.outputChannels.parseString (e->getStringAttribute ("audioDeviceOutChans", "11"), 2);
  19419. setup.useDefaultInputChannels = ! e->hasAttribute ("audioDeviceInChans");
  19420. setup.useDefaultOutputChannels = ! e->hasAttribute ("audioDeviceOutChans");
  19421. error = setAudioDeviceSetup (setup, true);
  19422. midiInsFromXml.clear();
  19423. forEachXmlChildElementWithTagName (*e, c, "MIDIINPUT")
  19424. midiInsFromXml.add (c->getStringAttribute ("name"));
  19425. const StringArray allMidiIns (MidiInput::getDevices());
  19426. for (int i = allMidiIns.size(); --i >= 0;)
  19427. setMidiInputEnabled (allMidiIns[i], midiInsFromXml.contains (allMidiIns[i]));
  19428. if (error.isNotEmpty() && selectDefaultDeviceOnFailure)
  19429. error = initialise (numInputChannelsNeeded, numOutputChannelsNeeded, 0,
  19430. false, preferredDefaultDeviceName);
  19431. setDefaultMidiOutput (e->getStringAttribute ("defaultMidiOutput"));
  19432. return error;
  19433. }
  19434. else
  19435. {
  19436. AudioDeviceSetup setup;
  19437. if (preferredSetupOptions != 0)
  19438. {
  19439. setup = *preferredSetupOptions;
  19440. }
  19441. else if (preferredDefaultDeviceName.isNotEmpty())
  19442. {
  19443. for (int j = availableDeviceTypes.size(); --j >= 0;)
  19444. {
  19445. AudioIODeviceType* const type = availableDeviceTypes.getUnchecked(j);
  19446. StringArray outs (type->getDeviceNames (false));
  19447. int i;
  19448. for (i = 0; i < outs.size(); ++i)
  19449. {
  19450. if (outs[i].matchesWildcard (preferredDefaultDeviceName, true))
  19451. {
  19452. setup.outputDeviceName = outs[i];
  19453. break;
  19454. }
  19455. }
  19456. StringArray ins (type->getDeviceNames (true));
  19457. for (i = 0; i < ins.size(); ++i)
  19458. {
  19459. if (ins[i].matchesWildcard (preferredDefaultDeviceName, true))
  19460. {
  19461. setup.inputDeviceName = ins[i];
  19462. break;
  19463. }
  19464. }
  19465. }
  19466. }
  19467. insertDefaultDeviceNames (setup);
  19468. return setAudioDeviceSetup (setup, false);
  19469. }
  19470. }
  19471. void AudioDeviceManager::insertDefaultDeviceNames (AudioDeviceSetup& setup) const
  19472. {
  19473. AudioIODeviceType* type = getCurrentDeviceTypeObject();
  19474. if (type != 0)
  19475. {
  19476. if (setup.outputDeviceName.isEmpty())
  19477. setup.outputDeviceName = type->getDeviceNames (false) [type->getDefaultDeviceIndex (false)];
  19478. if (setup.inputDeviceName.isEmpty())
  19479. setup.inputDeviceName = type->getDeviceNames (true) [type->getDefaultDeviceIndex (true)];
  19480. }
  19481. }
  19482. XmlElement* AudioDeviceManager::createStateXml() const
  19483. {
  19484. return lastExplicitSettings != 0 ? new XmlElement (*lastExplicitSettings) : 0;
  19485. }
  19486. void AudioDeviceManager::scanDevicesIfNeeded()
  19487. {
  19488. if (listNeedsScanning)
  19489. {
  19490. listNeedsScanning = false;
  19491. createDeviceTypesIfNeeded();
  19492. for (int i = availableDeviceTypes.size(); --i >= 0;)
  19493. availableDeviceTypes.getUnchecked(i)->scanForDevices();
  19494. }
  19495. }
  19496. AudioIODeviceType* AudioDeviceManager::findType (const String& inputName, const String& outputName)
  19497. {
  19498. scanDevicesIfNeeded();
  19499. for (int i = availableDeviceTypes.size(); --i >= 0;)
  19500. {
  19501. AudioIODeviceType* const type = availableDeviceTypes.getUnchecked(i);
  19502. if ((inputName.isNotEmpty() && type->getDeviceNames (true).contains (inputName, true))
  19503. || (outputName.isNotEmpty() && type->getDeviceNames (false).contains (outputName, true)))
  19504. {
  19505. return type;
  19506. }
  19507. }
  19508. return 0;
  19509. }
  19510. void AudioDeviceManager::getAudioDeviceSetup (AudioDeviceSetup& setup)
  19511. {
  19512. setup = currentSetup;
  19513. }
  19514. void AudioDeviceManager::deleteCurrentDevice()
  19515. {
  19516. currentAudioDevice = 0;
  19517. currentSetup.inputDeviceName = String::empty;
  19518. currentSetup.outputDeviceName = String::empty;
  19519. }
  19520. void AudioDeviceManager::setCurrentAudioDeviceType (const String& type,
  19521. const bool treatAsChosenDevice)
  19522. {
  19523. for (int i = 0; i < availableDeviceTypes.size(); ++i)
  19524. {
  19525. if (availableDeviceTypes.getUnchecked(i)->getTypeName() == type
  19526. && currentDeviceType != type)
  19527. {
  19528. currentDeviceType = type;
  19529. AudioDeviceSetup s (*lastDeviceTypeConfigs.getUnchecked(i));
  19530. insertDefaultDeviceNames (s);
  19531. setAudioDeviceSetup (s, treatAsChosenDevice);
  19532. sendChangeMessage (this);
  19533. break;
  19534. }
  19535. }
  19536. }
  19537. AudioIODeviceType* AudioDeviceManager::getCurrentDeviceTypeObject() const
  19538. {
  19539. for (int i = 0; i < availableDeviceTypes.size(); ++i)
  19540. if (availableDeviceTypes[i]->getTypeName() == currentDeviceType)
  19541. return availableDeviceTypes[i];
  19542. return availableDeviceTypes[0];
  19543. }
  19544. const String AudioDeviceManager::setAudioDeviceSetup (const AudioDeviceSetup& newSetup,
  19545. const bool treatAsChosenDevice)
  19546. {
  19547. jassert (&newSetup != &currentSetup); // this will have no effect
  19548. if (newSetup == currentSetup && currentAudioDevice != 0)
  19549. return String::empty;
  19550. if (! (newSetup == currentSetup))
  19551. sendChangeMessage (this);
  19552. stopDevice();
  19553. const String newInputDeviceName (numInputChansNeeded == 0 ? String::empty : newSetup.inputDeviceName);
  19554. const String newOutputDeviceName (numOutputChansNeeded == 0 ? String::empty : newSetup.outputDeviceName);
  19555. String error;
  19556. AudioIODeviceType* type = getCurrentDeviceTypeObject();
  19557. if (type == 0 || (newInputDeviceName.isEmpty() && newOutputDeviceName.isEmpty()))
  19558. {
  19559. deleteCurrentDevice();
  19560. if (treatAsChosenDevice)
  19561. updateXml();
  19562. return String::empty;
  19563. }
  19564. if (currentSetup.inputDeviceName != newInputDeviceName
  19565. || currentSetup.outputDeviceName != newOutputDeviceName
  19566. || currentAudioDevice == 0)
  19567. {
  19568. deleteCurrentDevice();
  19569. scanDevicesIfNeeded();
  19570. if (newOutputDeviceName.isNotEmpty()
  19571. && ! type->getDeviceNames (false).contains (newOutputDeviceName))
  19572. {
  19573. return "No such device: " + newOutputDeviceName;
  19574. }
  19575. if (newInputDeviceName.isNotEmpty()
  19576. && ! type->getDeviceNames (true).contains (newInputDeviceName))
  19577. {
  19578. return "No such device: " + newInputDeviceName;
  19579. }
  19580. currentAudioDevice = type->createDevice (newOutputDeviceName, newInputDeviceName);
  19581. if (currentAudioDevice == 0)
  19582. error = "Can't open the audio device!\n\nThis may be because another application is currently using the same device - if so, you should close any other applications and try again!";
  19583. else
  19584. error = currentAudioDevice->getLastError();
  19585. if (error.isNotEmpty())
  19586. {
  19587. deleteCurrentDevice();
  19588. return error;
  19589. }
  19590. if (newSetup.useDefaultInputChannels)
  19591. {
  19592. inputChannels.clear();
  19593. inputChannels.setRange (0, numInputChansNeeded, true);
  19594. }
  19595. if (newSetup.useDefaultOutputChannels)
  19596. {
  19597. outputChannels.clear();
  19598. outputChannels.setRange (0, numOutputChansNeeded, true);
  19599. }
  19600. if (newInputDeviceName.isEmpty())
  19601. inputChannels.clear();
  19602. if (newOutputDeviceName.isEmpty())
  19603. outputChannels.clear();
  19604. }
  19605. if (! newSetup.useDefaultInputChannels)
  19606. inputChannels = newSetup.inputChannels;
  19607. if (! newSetup.useDefaultOutputChannels)
  19608. outputChannels = newSetup.outputChannels;
  19609. currentSetup = newSetup;
  19610. currentSetup.sampleRate = chooseBestSampleRate (newSetup.sampleRate);
  19611. error = currentAudioDevice->open (inputChannels,
  19612. outputChannels,
  19613. currentSetup.sampleRate,
  19614. currentSetup.bufferSize);
  19615. if (error.isEmpty())
  19616. {
  19617. currentDeviceType = currentAudioDevice->getTypeName();
  19618. currentAudioDevice->start (&callbackHandler);
  19619. currentSetup.sampleRate = currentAudioDevice->getCurrentSampleRate();
  19620. currentSetup.bufferSize = currentAudioDevice->getCurrentBufferSizeSamples();
  19621. currentSetup.inputChannels = currentAudioDevice->getActiveInputChannels();
  19622. currentSetup.outputChannels = currentAudioDevice->getActiveOutputChannels();
  19623. for (int i = 0; i < availableDeviceTypes.size(); ++i)
  19624. if (availableDeviceTypes.getUnchecked (i)->getTypeName() == currentDeviceType)
  19625. *(lastDeviceTypeConfigs.getUnchecked (i)) = currentSetup;
  19626. if (treatAsChosenDevice)
  19627. updateXml();
  19628. }
  19629. else
  19630. {
  19631. deleteCurrentDevice();
  19632. }
  19633. return error;
  19634. }
  19635. double AudioDeviceManager::chooseBestSampleRate (double rate) const
  19636. {
  19637. jassert (currentAudioDevice != 0);
  19638. if (rate > 0)
  19639. {
  19640. bool ok = false;
  19641. for (int i = currentAudioDevice->getNumSampleRates(); --i >= 0;)
  19642. {
  19643. const double sr = currentAudioDevice->getSampleRate (i);
  19644. if (sr == rate)
  19645. ok = true;
  19646. }
  19647. if (! ok)
  19648. rate = 0;
  19649. }
  19650. if (rate == 0)
  19651. {
  19652. double lowestAbove44 = 0.0;
  19653. for (int i = currentAudioDevice->getNumSampleRates(); --i >= 0;)
  19654. {
  19655. const double sr = currentAudioDevice->getSampleRate (i);
  19656. if (sr >= 44100.0 && (lowestAbove44 == 0 || sr < lowestAbove44))
  19657. lowestAbove44 = sr;
  19658. }
  19659. if (lowestAbove44 == 0.0)
  19660. rate = currentAudioDevice->getSampleRate (0);
  19661. else
  19662. rate = lowestAbove44;
  19663. }
  19664. return rate;
  19665. }
  19666. void AudioDeviceManager::stopDevice()
  19667. {
  19668. if (currentAudioDevice != 0)
  19669. currentAudioDevice->stop();
  19670. testSound = 0;
  19671. }
  19672. void AudioDeviceManager::closeAudioDevice()
  19673. {
  19674. stopDevice();
  19675. currentAudioDevice = 0;
  19676. }
  19677. void AudioDeviceManager::restartLastAudioDevice()
  19678. {
  19679. if (currentAudioDevice == 0)
  19680. {
  19681. if (currentSetup.inputDeviceName.isEmpty()
  19682. && currentSetup.outputDeviceName.isEmpty())
  19683. {
  19684. // This method will only reload the last device that was running
  19685. // before closeAudioDevice() was called - you need to actually open
  19686. // one first, with setAudioDevice().
  19687. jassertfalse
  19688. return;
  19689. }
  19690. AudioDeviceSetup s (currentSetup);
  19691. setAudioDeviceSetup (s, false);
  19692. }
  19693. }
  19694. void AudioDeviceManager::updateXml()
  19695. {
  19696. lastExplicitSettings = new XmlElement ("DEVICESETUP");
  19697. lastExplicitSettings->setAttribute ("deviceType", currentDeviceType);
  19698. lastExplicitSettings->setAttribute ("audioOutputDeviceName", currentSetup.outputDeviceName);
  19699. lastExplicitSettings->setAttribute ("audioInputDeviceName", currentSetup.inputDeviceName);
  19700. if (currentAudioDevice != 0)
  19701. {
  19702. lastExplicitSettings->setAttribute ("audioDeviceRate", currentAudioDevice->getCurrentSampleRate());
  19703. if (currentAudioDevice->getDefaultBufferSize() != currentAudioDevice->getCurrentBufferSizeSamples())
  19704. lastExplicitSettings->setAttribute ("audioDeviceBufferSize", currentAudioDevice->getCurrentBufferSizeSamples());
  19705. if (! currentSetup.useDefaultInputChannels)
  19706. lastExplicitSettings->setAttribute ("audioDeviceInChans", currentSetup.inputChannels.toString (2));
  19707. if (! currentSetup.useDefaultOutputChannels)
  19708. lastExplicitSettings->setAttribute ("audioDeviceOutChans", currentSetup.outputChannels.toString (2));
  19709. }
  19710. for (int i = 0; i < enabledMidiInputs.size(); ++i)
  19711. {
  19712. XmlElement* const m = lastExplicitSettings->createNewChildElement ("MIDIINPUT");
  19713. m->setAttribute ("name", enabledMidiInputs[i]->getName());
  19714. }
  19715. if (midiInsFromXml.size() > 0)
  19716. {
  19717. // Add any midi devices that have been enabled before, but which aren't currently
  19718. // open because the device has been disconnected.
  19719. const StringArray availableMidiDevices (MidiInput::getDevices());
  19720. for (int i = 0; i < midiInsFromXml.size(); ++i)
  19721. {
  19722. if (! availableMidiDevices.contains (midiInsFromXml[i], true))
  19723. {
  19724. XmlElement* const m = lastExplicitSettings->createNewChildElement ("MIDIINPUT");
  19725. m->setAttribute ("name", midiInsFromXml[i]);
  19726. }
  19727. }
  19728. }
  19729. if (defaultMidiOutputName.isNotEmpty())
  19730. lastExplicitSettings->setAttribute ("defaultMidiOutput", defaultMidiOutputName);
  19731. }
  19732. void AudioDeviceManager::addAudioCallback (AudioIODeviceCallback* newCallback)
  19733. {
  19734. {
  19735. const ScopedLock sl (audioCallbackLock);
  19736. if (callbacks.contains (newCallback))
  19737. return;
  19738. }
  19739. if (currentAudioDevice != 0 && newCallback != 0)
  19740. newCallback->audioDeviceAboutToStart (currentAudioDevice);
  19741. const ScopedLock sl (audioCallbackLock);
  19742. callbacks.add (newCallback);
  19743. }
  19744. void AudioDeviceManager::removeAudioCallback (AudioIODeviceCallback* callback)
  19745. {
  19746. if (callback != 0)
  19747. {
  19748. bool needsDeinitialising = currentAudioDevice != 0;
  19749. {
  19750. const ScopedLock sl (audioCallbackLock);
  19751. needsDeinitialising = needsDeinitialising && callbacks.contains (callback);
  19752. callbacks.removeValue (callback);
  19753. }
  19754. if (needsDeinitialising)
  19755. callback->audioDeviceStopped();
  19756. }
  19757. }
  19758. void AudioDeviceManager::audioDeviceIOCallbackInt (const float** inputChannelData,
  19759. int numInputChannels,
  19760. float** outputChannelData,
  19761. int numOutputChannels,
  19762. int numSamples)
  19763. {
  19764. const ScopedLock sl (audioCallbackLock);
  19765. if (inputLevelMeasurementEnabledCount > 0)
  19766. {
  19767. for (int j = 0; j < numSamples; ++j)
  19768. {
  19769. float s = 0;
  19770. for (int i = 0; i < numInputChannels; ++i)
  19771. s += std::abs (inputChannelData[i][j]);
  19772. s /= numInputChannels;
  19773. const double decayFactor = 0.99992;
  19774. if (s > inputLevel)
  19775. inputLevel = s;
  19776. else if (inputLevel > 0.001f)
  19777. inputLevel *= decayFactor;
  19778. else
  19779. inputLevel = 0;
  19780. }
  19781. }
  19782. if (callbacks.size() > 0)
  19783. {
  19784. const double callbackStartTime = Time::getMillisecondCounterHiRes();
  19785. tempBuffer.setSize (jmax (1, numOutputChannels), jmax (1, numSamples), false, false, true);
  19786. callbacks.getUnchecked(0)->audioDeviceIOCallback (inputChannelData, numInputChannels,
  19787. outputChannelData, numOutputChannels, numSamples);
  19788. float** const tempChans = tempBuffer.getArrayOfChannels();
  19789. for (int i = callbacks.size(); --i > 0;)
  19790. {
  19791. callbacks.getUnchecked(i)->audioDeviceIOCallback (inputChannelData, numInputChannels,
  19792. tempChans, numOutputChannels, numSamples);
  19793. for (int chan = 0; chan < numOutputChannels; ++chan)
  19794. {
  19795. const float* const src = tempChans [chan];
  19796. float* const dst = outputChannelData [chan];
  19797. if (src != 0 && dst != 0)
  19798. for (int j = 0; j < numSamples; ++j)
  19799. dst[j] += src[j];
  19800. }
  19801. }
  19802. const double msTaken = Time::getMillisecondCounterHiRes() - callbackStartTime;
  19803. const double filterAmount = 0.2;
  19804. cpuUsageMs += filterAmount * (msTaken - cpuUsageMs);
  19805. }
  19806. else
  19807. {
  19808. for (int i = 0; i < numOutputChannels; ++i)
  19809. zeromem (outputChannelData[i], sizeof (float) * numSamples);
  19810. }
  19811. if (testSound != 0)
  19812. {
  19813. const int numSamps = jmin (numSamples, testSound->getNumSamples() - testSoundPosition);
  19814. const float* const src = testSound->getSampleData (0, testSoundPosition);
  19815. for (int i = 0; i < numOutputChannels; ++i)
  19816. for (int j = 0; j < numSamps; ++j)
  19817. outputChannelData [i][j] += src[j];
  19818. testSoundPosition += numSamps;
  19819. if (testSoundPosition >= testSound->getNumSamples())
  19820. testSound = 0;
  19821. }
  19822. }
  19823. void AudioDeviceManager::audioDeviceAboutToStartInt (AudioIODevice* const device)
  19824. {
  19825. cpuUsageMs = 0;
  19826. const double sampleRate = device->getCurrentSampleRate();
  19827. const int blockSize = device->getCurrentBufferSizeSamples();
  19828. if (sampleRate > 0.0 && blockSize > 0)
  19829. {
  19830. const double msPerBlock = 1000.0 * blockSize / sampleRate;
  19831. timeToCpuScale = (msPerBlock > 0.0) ? (1.0 / msPerBlock) : 0.0;
  19832. }
  19833. {
  19834. const ScopedLock sl (audioCallbackLock);
  19835. for (int i = callbacks.size(); --i >= 0;)
  19836. callbacks.getUnchecked(i)->audioDeviceAboutToStart (device);
  19837. }
  19838. sendChangeMessage (this);
  19839. }
  19840. void AudioDeviceManager::audioDeviceStoppedInt()
  19841. {
  19842. cpuUsageMs = 0;
  19843. timeToCpuScale = 0;
  19844. sendChangeMessage (this);
  19845. const ScopedLock sl (audioCallbackLock);
  19846. for (int i = callbacks.size(); --i >= 0;)
  19847. callbacks.getUnchecked(i)->audioDeviceStopped();
  19848. }
  19849. double AudioDeviceManager::getCpuUsage() const
  19850. {
  19851. return jlimit (0.0, 1.0, timeToCpuScale * cpuUsageMs);
  19852. }
  19853. void AudioDeviceManager::setMidiInputEnabled (const String& name,
  19854. const bool enabled)
  19855. {
  19856. if (enabled != isMidiInputEnabled (name))
  19857. {
  19858. if (enabled)
  19859. {
  19860. const int index = MidiInput::getDevices().indexOf (name);
  19861. if (index >= 0)
  19862. {
  19863. MidiInput* const min = MidiInput::openDevice (index, &callbackHandler);
  19864. if (min != 0)
  19865. {
  19866. enabledMidiInputs.add (min);
  19867. min->start();
  19868. }
  19869. }
  19870. }
  19871. else
  19872. {
  19873. for (int i = enabledMidiInputs.size(); --i >= 0;)
  19874. if (enabledMidiInputs[i]->getName() == name)
  19875. enabledMidiInputs.remove (i);
  19876. }
  19877. updateXml();
  19878. sendChangeMessage (this);
  19879. }
  19880. }
  19881. bool AudioDeviceManager::isMidiInputEnabled (const String& name) const
  19882. {
  19883. for (int i = enabledMidiInputs.size(); --i >= 0;)
  19884. if (enabledMidiInputs[i]->getName() == name)
  19885. return true;
  19886. return false;
  19887. }
  19888. void AudioDeviceManager::addMidiInputCallback (const String& name,
  19889. MidiInputCallback* callback)
  19890. {
  19891. removeMidiInputCallback (name, callback);
  19892. if (name.isEmpty())
  19893. {
  19894. midiCallbacks.add (callback);
  19895. midiCallbackDevices.add (0);
  19896. }
  19897. else
  19898. {
  19899. for (int i = enabledMidiInputs.size(); --i >= 0;)
  19900. {
  19901. if (enabledMidiInputs[i]->getName() == name)
  19902. {
  19903. const ScopedLock sl (midiCallbackLock);
  19904. midiCallbacks.add (callback);
  19905. midiCallbackDevices.add (enabledMidiInputs[i]);
  19906. break;
  19907. }
  19908. }
  19909. }
  19910. }
  19911. void AudioDeviceManager::removeMidiInputCallback (const String& name,
  19912. MidiInputCallback* /*callback*/)
  19913. {
  19914. const ScopedLock sl (midiCallbackLock);
  19915. for (int i = midiCallbacks.size(); --i >= 0;)
  19916. {
  19917. String devName;
  19918. if (midiCallbackDevices.getUnchecked(i) != 0)
  19919. devName = midiCallbackDevices.getUnchecked(i)->getName();
  19920. if (devName == name)
  19921. {
  19922. midiCallbacks.remove (i);
  19923. midiCallbackDevices.remove (i);
  19924. }
  19925. }
  19926. }
  19927. void AudioDeviceManager::handleIncomingMidiMessageInt (MidiInput* source,
  19928. const MidiMessage& message)
  19929. {
  19930. if (! message.isActiveSense())
  19931. {
  19932. const bool isDefaultSource = (source == 0 || source == enabledMidiInputs.getFirst());
  19933. const ScopedLock sl (midiCallbackLock);
  19934. for (int i = midiCallbackDevices.size(); --i >= 0;)
  19935. {
  19936. MidiInput* const md = midiCallbackDevices.getUnchecked(i);
  19937. if (md == source || (md == 0 && isDefaultSource))
  19938. midiCallbacks.getUnchecked(i)->handleIncomingMidiMessage (source, message);
  19939. }
  19940. }
  19941. }
  19942. void AudioDeviceManager::setDefaultMidiOutput (const String& deviceName)
  19943. {
  19944. if (defaultMidiOutputName != deviceName)
  19945. {
  19946. SortedSet <AudioIODeviceCallback*> oldCallbacks;
  19947. {
  19948. const ScopedLock sl (audioCallbackLock);
  19949. oldCallbacks = callbacks;
  19950. callbacks.clear();
  19951. }
  19952. if (currentAudioDevice != 0)
  19953. for (int i = oldCallbacks.size(); --i >= 0;)
  19954. oldCallbacks.getUnchecked(i)->audioDeviceStopped();
  19955. defaultMidiOutput = 0;
  19956. defaultMidiOutputName = deviceName;
  19957. if (deviceName.isNotEmpty())
  19958. defaultMidiOutput = MidiOutput::openDevice (MidiOutput::getDevices().indexOf (deviceName));
  19959. if (currentAudioDevice != 0)
  19960. for (int i = oldCallbacks.size(); --i >= 0;)
  19961. oldCallbacks.getUnchecked(i)->audioDeviceAboutToStart (currentAudioDevice);
  19962. {
  19963. const ScopedLock sl (audioCallbackLock);
  19964. callbacks = oldCallbacks;
  19965. }
  19966. updateXml();
  19967. sendChangeMessage (this);
  19968. }
  19969. }
  19970. void AudioDeviceManager::CallbackHandler::audioDeviceIOCallback (const float** inputChannelData,
  19971. int numInputChannels,
  19972. float** outputChannelData,
  19973. int numOutputChannels,
  19974. int numSamples)
  19975. {
  19976. owner->audioDeviceIOCallbackInt (inputChannelData, numInputChannels, outputChannelData, numOutputChannels, numSamples);
  19977. }
  19978. void AudioDeviceManager::CallbackHandler::audioDeviceAboutToStart (AudioIODevice* device)
  19979. {
  19980. owner->audioDeviceAboutToStartInt (device);
  19981. }
  19982. void AudioDeviceManager::CallbackHandler::audioDeviceStopped()
  19983. {
  19984. owner->audioDeviceStoppedInt();
  19985. }
  19986. void AudioDeviceManager::CallbackHandler::handleIncomingMidiMessage (MidiInput* source, const MidiMessage& message)
  19987. {
  19988. owner->handleIncomingMidiMessageInt (source, message);
  19989. }
  19990. void AudioDeviceManager::playTestSound()
  19991. {
  19992. { // cunningly nested to swap, unlock and delete in that order.
  19993. ScopedPointer <AudioSampleBuffer> oldSound;
  19994. {
  19995. const ScopedLock sl (audioCallbackLock);
  19996. oldSound = testSound;
  19997. }
  19998. }
  19999. testSoundPosition = 0;
  20000. if (currentAudioDevice != 0)
  20001. {
  20002. const double sampleRate = currentAudioDevice->getCurrentSampleRate();
  20003. const int soundLength = (int) sampleRate;
  20004. AudioSampleBuffer* const newSound = new AudioSampleBuffer (1, soundLength);
  20005. float* samples = newSound->getSampleData (0);
  20006. const double frequency = MidiMessage::getMidiNoteInHertz (80);
  20007. const float amplitude = 0.5f;
  20008. const double phasePerSample = double_Pi * 2.0 / (sampleRate / frequency);
  20009. for (int i = 0; i < soundLength; ++i)
  20010. samples[i] = amplitude * (float) std::sin (i * phasePerSample);
  20011. newSound->applyGainRamp (0, 0, soundLength / 10, 0.0f, 1.0f);
  20012. newSound->applyGainRamp (0, soundLength - soundLength / 4, soundLength / 4, 1.0f, 0.0f);
  20013. const ScopedLock sl (audioCallbackLock);
  20014. testSound = newSound;
  20015. }
  20016. }
  20017. void AudioDeviceManager::enableInputLevelMeasurement (const bool enableMeasurement)
  20018. {
  20019. const ScopedLock sl (audioCallbackLock);
  20020. if (enableMeasurement)
  20021. ++inputLevelMeasurementEnabledCount;
  20022. else
  20023. --inputLevelMeasurementEnabledCount;
  20024. inputLevel = 0;
  20025. }
  20026. double AudioDeviceManager::getCurrentInputLevel() const
  20027. {
  20028. jassert (inputLevelMeasurementEnabledCount > 0); // you need to call enableInputLevelMeasurement() before using this!
  20029. return inputLevel;
  20030. }
  20031. END_JUCE_NAMESPACE
  20032. /*** End of inlined file: juce_AudioDeviceManager.cpp ***/
  20033. /*** Start of inlined file: juce_AudioIODevice.cpp ***/
  20034. BEGIN_JUCE_NAMESPACE
  20035. AudioIODevice::AudioIODevice (const String& deviceName, const String& typeName_)
  20036. : name (deviceName),
  20037. typeName (typeName_)
  20038. {
  20039. }
  20040. AudioIODevice::~AudioIODevice()
  20041. {
  20042. }
  20043. bool AudioIODevice::hasControlPanel() const
  20044. {
  20045. return false;
  20046. }
  20047. bool AudioIODevice::showControlPanel()
  20048. {
  20049. jassertfalse // this should only be called for devices which return true from
  20050. // their hasControlPanel() method.
  20051. return false;
  20052. }
  20053. END_JUCE_NAMESPACE
  20054. /*** End of inlined file: juce_AudioIODevice.cpp ***/
  20055. /*** Start of inlined file: juce_AudioIODeviceType.cpp ***/
  20056. BEGIN_JUCE_NAMESPACE
  20057. AudioIODeviceType::AudioIODeviceType (const String& name)
  20058. : typeName (name)
  20059. {
  20060. }
  20061. AudioIODeviceType::~AudioIODeviceType()
  20062. {
  20063. }
  20064. END_JUCE_NAMESPACE
  20065. /*** End of inlined file: juce_AudioIODeviceType.cpp ***/
  20066. /*** Start of inlined file: juce_MidiOutput.cpp ***/
  20067. BEGIN_JUCE_NAMESPACE
  20068. MidiOutput::MidiOutput()
  20069. : Thread ("midi out"),
  20070. internal (0),
  20071. firstMessage (0)
  20072. {
  20073. }
  20074. MidiOutput::PendingMessage::PendingMessage (const uint8* const data, const int len,
  20075. const double sampleNumber)
  20076. : message (data, len, sampleNumber)
  20077. {
  20078. }
  20079. void MidiOutput::sendBlockOfMessages (const MidiBuffer& buffer,
  20080. const double millisecondCounterToStartAt,
  20081. double samplesPerSecondForBuffer)
  20082. {
  20083. // You've got to call startBackgroundThread() for this to actually work..
  20084. jassert (isThreadRunning());
  20085. // this needs to be a value in the future - RTFM for this method!
  20086. jassert (millisecondCounterToStartAt > 0);
  20087. const double timeScaleFactor = 1000.0 / samplesPerSecondForBuffer;
  20088. MidiBuffer::Iterator i (buffer);
  20089. const uint8* data;
  20090. int len, time;
  20091. while (i.getNextEvent (data, len, time))
  20092. {
  20093. const double eventTime = millisecondCounterToStartAt + timeScaleFactor * time;
  20094. PendingMessage* const m
  20095. = new PendingMessage (data, len, eventTime);
  20096. const ScopedLock sl (lock);
  20097. if (firstMessage == 0 || firstMessage->message.getTimeStamp() > eventTime)
  20098. {
  20099. m->next = firstMessage;
  20100. firstMessage = m;
  20101. }
  20102. else
  20103. {
  20104. PendingMessage* mm = firstMessage;
  20105. while (mm->next != 0 && mm->next->message.getTimeStamp() <= eventTime)
  20106. mm = mm->next;
  20107. m->next = mm->next;
  20108. mm->next = m;
  20109. }
  20110. }
  20111. notify();
  20112. }
  20113. void MidiOutput::clearAllPendingMessages()
  20114. {
  20115. const ScopedLock sl (lock);
  20116. while (firstMessage != 0)
  20117. {
  20118. PendingMessage* const m = firstMessage;
  20119. firstMessage = firstMessage->next;
  20120. delete m;
  20121. }
  20122. }
  20123. void MidiOutput::startBackgroundThread()
  20124. {
  20125. startThread (9);
  20126. }
  20127. void MidiOutput::stopBackgroundThread()
  20128. {
  20129. stopThread (5000);
  20130. }
  20131. void MidiOutput::run()
  20132. {
  20133. while (! threadShouldExit())
  20134. {
  20135. uint32 now = Time::getMillisecondCounter();
  20136. uint32 eventTime = 0;
  20137. uint32 timeToWait = 500;
  20138. PendingMessage* message;
  20139. {
  20140. const ScopedLock sl (lock);
  20141. message = firstMessage;
  20142. if (message != 0)
  20143. {
  20144. eventTime = roundToInt (message->message.getTimeStamp());
  20145. if (eventTime > now + 20)
  20146. {
  20147. timeToWait = eventTime - (now + 20);
  20148. message = 0;
  20149. }
  20150. else
  20151. {
  20152. firstMessage = message->next;
  20153. }
  20154. }
  20155. }
  20156. if (message != 0)
  20157. {
  20158. if (eventTime > now)
  20159. {
  20160. Time::waitForMillisecondCounter (eventTime);
  20161. if (threadShouldExit())
  20162. break;
  20163. }
  20164. if (eventTime > now - 200)
  20165. sendMessageNow (message->message);
  20166. delete message;
  20167. }
  20168. else
  20169. {
  20170. jassert (timeToWait < 1000 * 30);
  20171. wait (timeToWait);
  20172. }
  20173. }
  20174. clearAllPendingMessages();
  20175. }
  20176. END_JUCE_NAMESPACE
  20177. /*** End of inlined file: juce_MidiOutput.cpp ***/
  20178. /*** Start of inlined file: juce_AudioDataConverters.cpp ***/
  20179. BEGIN_JUCE_NAMESPACE
  20180. void AudioDataConverters::convertFloatToInt16LE (const float* source, void* dest, int numSamples, const int destBytesPerSample)
  20181. {
  20182. const double maxVal = (double) 0x7fff;
  20183. char* intData = static_cast <char*> (dest);
  20184. if (dest != (void*) source || destBytesPerSample <= 4)
  20185. {
  20186. for (int i = 0; i < numSamples; ++i)
  20187. {
  20188. *(uint16*) intData = ByteOrder::swapIfBigEndian ((uint16) (short) roundToInt (jlimit (-maxVal, maxVal, maxVal * source[i])));
  20189. intData += destBytesPerSample;
  20190. }
  20191. }
  20192. else
  20193. {
  20194. intData += destBytesPerSample * numSamples;
  20195. for (int i = numSamples; --i >= 0;)
  20196. {
  20197. intData -= destBytesPerSample;
  20198. *(uint16*) intData = ByteOrder::swapIfBigEndian ((uint16) (short) roundToInt (jlimit (-maxVal, maxVal, maxVal * source[i])));
  20199. }
  20200. }
  20201. }
  20202. void AudioDataConverters::convertFloatToInt16BE (const float* source, void* dest, int numSamples, const int destBytesPerSample)
  20203. {
  20204. const double maxVal = (double) 0x7fff;
  20205. char* intData = static_cast <char*> (dest);
  20206. if (dest != (void*) source || destBytesPerSample <= 4)
  20207. {
  20208. for (int i = 0; i < numSamples; ++i)
  20209. {
  20210. *(uint16*) intData = ByteOrder::swapIfLittleEndian ((uint16) (short) roundToInt (jlimit (-maxVal, maxVal, maxVal * source[i])));
  20211. intData += destBytesPerSample;
  20212. }
  20213. }
  20214. else
  20215. {
  20216. intData += destBytesPerSample * numSamples;
  20217. for (int i = numSamples; --i >= 0;)
  20218. {
  20219. intData -= destBytesPerSample;
  20220. *(uint16*) intData = ByteOrder::swapIfLittleEndian ((uint16) (short) roundToInt (jlimit (-maxVal, maxVal, maxVal * source[i])));
  20221. }
  20222. }
  20223. }
  20224. void AudioDataConverters::convertFloatToInt24LE (const float* source, void* dest, int numSamples, const int destBytesPerSample)
  20225. {
  20226. const double maxVal = (double) 0x7fffff;
  20227. char* intData = static_cast <char*> (dest);
  20228. if (dest != (void*) source || destBytesPerSample <= 4)
  20229. {
  20230. for (int i = 0; i < numSamples; ++i)
  20231. {
  20232. ByteOrder::littleEndian24BitToChars ((uint32) roundToInt (jlimit (-maxVal, maxVal, maxVal * source[i])), intData);
  20233. intData += destBytesPerSample;
  20234. }
  20235. }
  20236. else
  20237. {
  20238. intData += destBytesPerSample * numSamples;
  20239. for (int i = numSamples; --i >= 0;)
  20240. {
  20241. intData -= destBytesPerSample;
  20242. ByteOrder::littleEndian24BitToChars ((uint32) roundToInt (jlimit (-maxVal, maxVal, maxVal * source[i])), intData);
  20243. }
  20244. }
  20245. }
  20246. void AudioDataConverters::convertFloatToInt24BE (const float* source, void* dest, int numSamples, const int destBytesPerSample)
  20247. {
  20248. const double maxVal = (double) 0x7fffff;
  20249. char* intData = static_cast <char*> (dest);
  20250. if (dest != (void*) source || destBytesPerSample <= 4)
  20251. {
  20252. for (int i = 0; i < numSamples; ++i)
  20253. {
  20254. ByteOrder::bigEndian24BitToChars ((uint32) roundToInt (jlimit (-maxVal, maxVal, maxVal * source[i])), intData);
  20255. intData += destBytesPerSample;
  20256. }
  20257. }
  20258. else
  20259. {
  20260. intData += destBytesPerSample * numSamples;
  20261. for (int i = numSamples; --i >= 0;)
  20262. {
  20263. intData -= destBytesPerSample;
  20264. ByteOrder::bigEndian24BitToChars ((uint32) roundToInt (jlimit (-maxVal, maxVal, maxVal * source[i])), intData);
  20265. }
  20266. }
  20267. }
  20268. void AudioDataConverters::convertFloatToInt32LE (const float* source, void* dest, int numSamples, const int destBytesPerSample)
  20269. {
  20270. const double maxVal = (double) 0x7fffffff;
  20271. char* intData = static_cast <char*> (dest);
  20272. if (dest != (void*) source || destBytesPerSample <= 4)
  20273. {
  20274. for (int i = 0; i < numSamples; ++i)
  20275. {
  20276. *(uint32*)intData = ByteOrder::swapIfBigEndian ((uint32) roundToInt (jlimit (-maxVal, maxVal, maxVal * source[i])));
  20277. intData += destBytesPerSample;
  20278. }
  20279. }
  20280. else
  20281. {
  20282. intData += destBytesPerSample * numSamples;
  20283. for (int i = numSamples; --i >= 0;)
  20284. {
  20285. intData -= destBytesPerSample;
  20286. *(uint32*)intData = ByteOrder::swapIfBigEndian ((uint32) roundToInt (jlimit (-maxVal, maxVal, maxVal * source[i])));
  20287. }
  20288. }
  20289. }
  20290. void AudioDataConverters::convertFloatToInt32BE (const float* source, void* dest, int numSamples, const int destBytesPerSample)
  20291. {
  20292. const double maxVal = (double) 0x7fffffff;
  20293. char* intData = static_cast <char*> (dest);
  20294. if (dest != (void*) source || destBytesPerSample <= 4)
  20295. {
  20296. for (int i = 0; i < numSamples; ++i)
  20297. {
  20298. *(uint32*)intData = ByteOrder::swapIfLittleEndian ((uint32) roundToInt (jlimit (-maxVal, maxVal, maxVal * source[i])));
  20299. intData += destBytesPerSample;
  20300. }
  20301. }
  20302. else
  20303. {
  20304. intData += destBytesPerSample * numSamples;
  20305. for (int i = numSamples; --i >= 0;)
  20306. {
  20307. intData -= destBytesPerSample;
  20308. *(uint32*)intData = ByteOrder::swapIfLittleEndian ((uint32) roundToInt (jlimit (-maxVal, maxVal, maxVal * source[i])));
  20309. }
  20310. }
  20311. }
  20312. void AudioDataConverters::convertFloatToFloat32LE (const float* source, void* dest, int numSamples, const int destBytesPerSample)
  20313. {
  20314. jassert (dest != (void*) source || destBytesPerSample <= 4); // This op can't be performed on in-place data!
  20315. char* d = static_cast <char*> (dest);
  20316. for (int i = 0; i < numSamples; ++i)
  20317. {
  20318. *(float*) d = source[i];
  20319. #if JUCE_BIG_ENDIAN
  20320. *(uint32*) d = ByteOrder::swap (*(uint32*) d);
  20321. #endif
  20322. d += destBytesPerSample;
  20323. }
  20324. }
  20325. void AudioDataConverters::convertFloatToFloat32BE (const float* source, void* dest, int numSamples, const int destBytesPerSample)
  20326. {
  20327. jassert (dest != (void*) source || destBytesPerSample <= 4); // This op can't be performed on in-place data!
  20328. char* d = static_cast <char*> (dest);
  20329. for (int i = 0; i < numSamples; ++i)
  20330. {
  20331. *(float*) d = source[i];
  20332. #if JUCE_LITTLE_ENDIAN
  20333. *(uint32*) d = ByteOrder::swap (*(uint32*) d);
  20334. #endif
  20335. d += destBytesPerSample;
  20336. }
  20337. }
  20338. void AudioDataConverters::convertInt16LEToFloat (const void* const source, float* const dest, int numSamples, const int srcBytesPerSample)
  20339. {
  20340. const float scale = 1.0f / 0x7fff;
  20341. const char* intData = static_cast <const char*> (source);
  20342. if (source != (void*) dest || srcBytesPerSample >= 4)
  20343. {
  20344. for (int i = 0; i < numSamples; ++i)
  20345. {
  20346. dest[i] = scale * (short) ByteOrder::swapIfBigEndian (*(uint16*)intData);
  20347. intData += srcBytesPerSample;
  20348. }
  20349. }
  20350. else
  20351. {
  20352. intData += srcBytesPerSample * numSamples;
  20353. for (int i = numSamples; --i >= 0;)
  20354. {
  20355. intData -= srcBytesPerSample;
  20356. dest[i] = scale * (short) ByteOrder::swapIfBigEndian (*(uint16*)intData);
  20357. }
  20358. }
  20359. }
  20360. void AudioDataConverters::convertInt16BEToFloat (const void* const source, float* const dest, int numSamples, const int srcBytesPerSample)
  20361. {
  20362. const float scale = 1.0f / 0x7fff;
  20363. const char* intData = static_cast <const char*> (source);
  20364. if (source != (void*) dest || srcBytesPerSample >= 4)
  20365. {
  20366. for (int i = 0; i < numSamples; ++i)
  20367. {
  20368. dest[i] = scale * (short) ByteOrder::swapIfLittleEndian (*(uint16*)intData);
  20369. intData += srcBytesPerSample;
  20370. }
  20371. }
  20372. else
  20373. {
  20374. intData += srcBytesPerSample * numSamples;
  20375. for (int i = numSamples; --i >= 0;)
  20376. {
  20377. intData -= srcBytesPerSample;
  20378. dest[i] = scale * (short) ByteOrder::swapIfLittleEndian (*(uint16*)intData);
  20379. }
  20380. }
  20381. }
  20382. void AudioDataConverters::convertInt24LEToFloat (const void* const source, float* const dest, int numSamples, const int srcBytesPerSample)
  20383. {
  20384. const float scale = 1.0f / 0x7fffff;
  20385. const char* intData = static_cast <const char*> (source);
  20386. if (source != (void*) dest || srcBytesPerSample >= 4)
  20387. {
  20388. for (int i = 0; i < numSamples; ++i)
  20389. {
  20390. dest[i] = scale * (short) ByteOrder::littleEndian24Bit (intData);
  20391. intData += srcBytesPerSample;
  20392. }
  20393. }
  20394. else
  20395. {
  20396. intData += srcBytesPerSample * numSamples;
  20397. for (int i = numSamples; --i >= 0;)
  20398. {
  20399. intData -= srcBytesPerSample;
  20400. dest[i] = scale * (short) ByteOrder::littleEndian24Bit (intData);
  20401. }
  20402. }
  20403. }
  20404. void AudioDataConverters::convertInt24BEToFloat (const void* const source, float* const dest, int numSamples, const int srcBytesPerSample)
  20405. {
  20406. const float scale = 1.0f / 0x7fffff;
  20407. const char* intData = static_cast <const char*> (source);
  20408. if (source != (void*) dest || srcBytesPerSample >= 4)
  20409. {
  20410. for (int i = 0; i < numSamples; ++i)
  20411. {
  20412. dest[i] = scale * (short) ByteOrder::bigEndian24Bit (intData);
  20413. intData += srcBytesPerSample;
  20414. }
  20415. }
  20416. else
  20417. {
  20418. intData += srcBytesPerSample * numSamples;
  20419. for (int i = numSamples; --i >= 0;)
  20420. {
  20421. intData -= srcBytesPerSample;
  20422. dest[i] = scale * (short) ByteOrder::bigEndian24Bit (intData);
  20423. }
  20424. }
  20425. }
  20426. void AudioDataConverters::convertInt32LEToFloat (const void* const source, float* const dest, int numSamples, const int srcBytesPerSample)
  20427. {
  20428. const float scale = 1.0f / 0x7fffffff;
  20429. const char* intData = static_cast <const char*> (source);
  20430. if (source != (void*) dest || srcBytesPerSample >= 4)
  20431. {
  20432. for (int i = 0; i < numSamples; ++i)
  20433. {
  20434. dest[i] = scale * (int) ByteOrder::swapIfBigEndian (*(uint32*) intData);
  20435. intData += srcBytesPerSample;
  20436. }
  20437. }
  20438. else
  20439. {
  20440. intData += srcBytesPerSample * numSamples;
  20441. for (int i = numSamples; --i >= 0;)
  20442. {
  20443. intData -= srcBytesPerSample;
  20444. dest[i] = scale * (int) ByteOrder::swapIfBigEndian (*(uint32*) intData);
  20445. }
  20446. }
  20447. }
  20448. void AudioDataConverters::convertInt32BEToFloat (const void* const source, float* const dest, int numSamples, const int srcBytesPerSample)
  20449. {
  20450. const float scale = 1.0f / 0x7fffffff;
  20451. const char* intData = static_cast <const char*> (source);
  20452. if (source != (void*) dest || srcBytesPerSample >= 4)
  20453. {
  20454. for (int i = 0; i < numSamples; ++i)
  20455. {
  20456. dest[i] = scale * (int) ByteOrder::swapIfLittleEndian (*(uint32*) intData);
  20457. intData += srcBytesPerSample;
  20458. }
  20459. }
  20460. else
  20461. {
  20462. intData += srcBytesPerSample * numSamples;
  20463. for (int i = numSamples; --i >= 0;)
  20464. {
  20465. intData -= srcBytesPerSample;
  20466. dest[i] = scale * (int) ByteOrder::swapIfLittleEndian (*(uint32*) intData);
  20467. }
  20468. }
  20469. }
  20470. void AudioDataConverters::convertFloat32LEToFloat (const void* const source, float* const dest, int numSamples, const int srcBytesPerSample)
  20471. {
  20472. const char* s = static_cast <const char*> (source);
  20473. for (int i = 0; i < numSamples; ++i)
  20474. {
  20475. dest[i] = *(float*)s;
  20476. #if JUCE_BIG_ENDIAN
  20477. uint32* const d = (uint32*) (dest + i);
  20478. *d = ByteOrder::swap (*d);
  20479. #endif
  20480. s += srcBytesPerSample;
  20481. }
  20482. }
  20483. void AudioDataConverters::convertFloat32BEToFloat (const void* const source, float* const dest, int numSamples, const int srcBytesPerSample)
  20484. {
  20485. const char* s = static_cast <const char*> (source);
  20486. for (int i = 0; i < numSamples; ++i)
  20487. {
  20488. dest[i] = *(float*)s;
  20489. #if JUCE_LITTLE_ENDIAN
  20490. uint32* const d = (uint32*) (dest + i);
  20491. *d = ByteOrder::swap (*d);
  20492. #endif
  20493. s += srcBytesPerSample;
  20494. }
  20495. }
  20496. void AudioDataConverters::convertFloatToFormat (const DataFormat destFormat,
  20497. const float* const source,
  20498. void* const dest,
  20499. const int numSamples)
  20500. {
  20501. switch (destFormat)
  20502. {
  20503. case int16LE:
  20504. convertFloatToInt16LE (source, dest, numSamples);
  20505. break;
  20506. case int16BE:
  20507. convertFloatToInt16BE (source, dest, numSamples);
  20508. break;
  20509. case int24LE:
  20510. convertFloatToInt24LE (source, dest, numSamples);
  20511. break;
  20512. case int24BE:
  20513. convertFloatToInt24BE (source, dest, numSamples);
  20514. break;
  20515. case int32LE:
  20516. convertFloatToInt32LE (source, dest, numSamples);
  20517. break;
  20518. case int32BE:
  20519. convertFloatToInt32BE (source, dest, numSamples);
  20520. break;
  20521. case float32LE:
  20522. convertFloatToFloat32LE (source, dest, numSamples);
  20523. break;
  20524. case float32BE:
  20525. convertFloatToFloat32BE (source, dest, numSamples);
  20526. break;
  20527. default:
  20528. jassertfalse
  20529. break;
  20530. }
  20531. }
  20532. void AudioDataConverters::convertFormatToFloat (const DataFormat sourceFormat,
  20533. const void* const source,
  20534. float* const dest,
  20535. const int numSamples)
  20536. {
  20537. switch (sourceFormat)
  20538. {
  20539. case int16LE:
  20540. convertInt16LEToFloat (source, dest, numSamples);
  20541. break;
  20542. case int16BE:
  20543. convertInt16BEToFloat (source, dest, numSamples);
  20544. break;
  20545. case int24LE:
  20546. convertInt24LEToFloat (source, dest, numSamples);
  20547. break;
  20548. case int24BE:
  20549. convertInt24BEToFloat (source, dest, numSamples);
  20550. break;
  20551. case int32LE:
  20552. convertInt32LEToFloat (source, dest, numSamples);
  20553. break;
  20554. case int32BE:
  20555. convertInt32BEToFloat (source, dest, numSamples);
  20556. break;
  20557. case float32LE:
  20558. convertFloat32LEToFloat (source, dest, numSamples);
  20559. break;
  20560. case float32BE:
  20561. convertFloat32BEToFloat (source, dest, numSamples);
  20562. break;
  20563. default:
  20564. jassertfalse
  20565. break;
  20566. }
  20567. }
  20568. void AudioDataConverters::interleaveSamples (const float** const source,
  20569. float* const dest,
  20570. const int numSamples,
  20571. const int numChannels)
  20572. {
  20573. for (int chan = 0; chan < numChannels; ++chan)
  20574. {
  20575. int i = chan;
  20576. const float* src = source [chan];
  20577. for (int j = 0; j < numSamples; ++j)
  20578. {
  20579. dest [i] = src [j];
  20580. i += numChannels;
  20581. }
  20582. }
  20583. }
  20584. void AudioDataConverters::deinterleaveSamples (const float* const source,
  20585. float** const dest,
  20586. const int numSamples,
  20587. const int numChannels)
  20588. {
  20589. for (int chan = 0; chan < numChannels; ++chan)
  20590. {
  20591. int i = chan;
  20592. float* dst = dest [chan];
  20593. for (int j = 0; j < numSamples; ++j)
  20594. {
  20595. dst [j] = source [i];
  20596. i += numChannels;
  20597. }
  20598. }
  20599. }
  20600. END_JUCE_NAMESPACE
  20601. /*** End of inlined file: juce_AudioDataConverters.cpp ***/
  20602. /*** Start of inlined file: juce_AudioSampleBuffer.cpp ***/
  20603. BEGIN_JUCE_NAMESPACE
  20604. AudioSampleBuffer::AudioSampleBuffer (const int numChannels_,
  20605. const int numSamples) throw()
  20606. : numChannels (numChannels_),
  20607. size (numSamples)
  20608. {
  20609. jassert (numSamples >= 0);
  20610. jassert (numChannels_ > 0);
  20611. allocateData();
  20612. }
  20613. AudioSampleBuffer::AudioSampleBuffer (const AudioSampleBuffer& other) throw()
  20614. : numChannels (other.numChannels),
  20615. size (other.size)
  20616. {
  20617. allocateData();
  20618. const size_t numBytes = size * sizeof (float);
  20619. for (int i = 0; i < numChannels; ++i)
  20620. memcpy (channels[i], other.channels[i], numBytes);
  20621. }
  20622. void AudioSampleBuffer::allocateData()
  20623. {
  20624. const size_t channelListSize = (numChannels + 1) * sizeof (float*);
  20625. allocatedBytes = (int) (numChannels * size * sizeof (float) + channelListSize + 32);
  20626. allocatedData.malloc (allocatedBytes);
  20627. channels = reinterpret_cast <float**> (allocatedData.getData());
  20628. float* chan = (float*) (allocatedData + channelListSize);
  20629. for (int i = 0; i < numChannels; ++i)
  20630. {
  20631. channels[i] = chan;
  20632. chan += size;
  20633. }
  20634. channels [numChannels] = 0;
  20635. }
  20636. AudioSampleBuffer::AudioSampleBuffer (float** dataToReferTo,
  20637. const int numChannels_,
  20638. const int numSamples) throw()
  20639. : numChannels (numChannels_),
  20640. size (numSamples),
  20641. allocatedBytes (0)
  20642. {
  20643. jassert (numChannels_ > 0);
  20644. allocateChannels (dataToReferTo);
  20645. }
  20646. void AudioSampleBuffer::setDataToReferTo (float** dataToReferTo,
  20647. const int newNumChannels,
  20648. const int newNumSamples) throw()
  20649. {
  20650. jassert (newNumChannels > 0);
  20651. allocatedBytes = 0;
  20652. allocatedData.free();
  20653. numChannels = newNumChannels;
  20654. size = newNumSamples;
  20655. allocateChannels (dataToReferTo);
  20656. }
  20657. void AudioSampleBuffer::allocateChannels (float** const dataToReferTo)
  20658. {
  20659. // (try to avoid doing a malloc here, as that'll blow up things like Pro-Tools)
  20660. if (numChannels < numElementsInArray (preallocatedChannelSpace))
  20661. {
  20662. channels = static_cast <float**> (preallocatedChannelSpace);
  20663. }
  20664. else
  20665. {
  20666. allocatedData.malloc (numChannels + 1, sizeof (float*));
  20667. channels = reinterpret_cast <float**> (allocatedData.getData());
  20668. }
  20669. for (int i = 0; i < numChannels; ++i)
  20670. {
  20671. // you have to pass in the same number of valid pointers as numChannels
  20672. jassert (dataToReferTo[i] != 0);
  20673. channels[i] = dataToReferTo[i];
  20674. }
  20675. channels [numChannels] = 0;
  20676. }
  20677. AudioSampleBuffer& AudioSampleBuffer::operator= (const AudioSampleBuffer& other) throw()
  20678. {
  20679. if (this != &other)
  20680. {
  20681. setSize (other.getNumChannels(), other.getNumSamples(), false, false, false);
  20682. const size_t numBytes = size * sizeof (float);
  20683. for (int i = 0; i < numChannels; ++i)
  20684. memcpy (channels[i], other.channels[i], numBytes);
  20685. }
  20686. return *this;
  20687. }
  20688. AudioSampleBuffer::~AudioSampleBuffer() throw()
  20689. {
  20690. }
  20691. void AudioSampleBuffer::setSize (const int newNumChannels,
  20692. const int newNumSamples,
  20693. const bool keepExistingContent,
  20694. const bool clearExtraSpace,
  20695. const bool avoidReallocating) throw()
  20696. {
  20697. jassert (newNumChannels > 0);
  20698. if (newNumSamples != size || newNumChannels != numChannels)
  20699. {
  20700. const size_t channelListSize = (newNumChannels + 1) * sizeof (float*);
  20701. const size_t newTotalBytes = (newNumChannels * newNumSamples * sizeof (float)) + channelListSize + 32;
  20702. if (keepExistingContent)
  20703. {
  20704. HeapBlock <char> newData;
  20705. newData.allocate (newTotalBytes, clearExtraSpace);
  20706. const int numChansToCopy = jmin (numChannels, newNumChannels);
  20707. const size_t numBytesToCopy = sizeof (float) * jmin (newNumSamples, size);
  20708. float** const newChannels = reinterpret_cast <float**> (newData.getData());
  20709. float* newChan = reinterpret_cast <float*> (newData + channelListSize);
  20710. for (int i = 0; i < numChansToCopy; ++i)
  20711. {
  20712. memcpy (newChan, channels[i], numBytesToCopy);
  20713. newChannels[i] = newChan;
  20714. newChan += newNumSamples;
  20715. }
  20716. allocatedData.swapWith (newData);
  20717. allocatedBytes = (int) newTotalBytes;
  20718. channels = newChannels;
  20719. }
  20720. else
  20721. {
  20722. if (avoidReallocating && allocatedBytes >= newTotalBytes)
  20723. {
  20724. if (clearExtraSpace)
  20725. zeromem (allocatedData, newTotalBytes);
  20726. }
  20727. else
  20728. {
  20729. allocatedBytes = newTotalBytes;
  20730. allocatedData.allocate (newTotalBytes, clearExtraSpace);
  20731. channels = reinterpret_cast <float**> (allocatedData.getData());
  20732. }
  20733. float* chan = reinterpret_cast <float*> (allocatedData + channelListSize);
  20734. for (int i = 0; i < newNumChannels; ++i)
  20735. {
  20736. channels[i] = chan;
  20737. chan += newNumSamples;
  20738. }
  20739. }
  20740. channels [newNumChannels] = 0;
  20741. size = newNumSamples;
  20742. numChannels = newNumChannels;
  20743. }
  20744. }
  20745. void AudioSampleBuffer::clear() throw()
  20746. {
  20747. for (int i = 0; i < numChannels; ++i)
  20748. zeromem (channels[i], size * sizeof (float));
  20749. }
  20750. void AudioSampleBuffer::clear (const int startSample,
  20751. const int numSamples) throw()
  20752. {
  20753. jassert (startSample >= 0 && startSample + numSamples <= size);
  20754. for (int i = 0; i < numChannels; ++i)
  20755. zeromem (channels [i] + startSample, numSamples * sizeof (float));
  20756. }
  20757. void AudioSampleBuffer::clear (const int channel,
  20758. const int startSample,
  20759. const int numSamples) throw()
  20760. {
  20761. jassert (((unsigned int) channel) < (unsigned int) numChannels);
  20762. jassert (startSample >= 0 && startSample + numSamples <= size);
  20763. zeromem (channels [channel] + startSample, numSamples * sizeof (float));
  20764. }
  20765. void AudioSampleBuffer::applyGain (const int channel,
  20766. const int startSample,
  20767. int numSamples,
  20768. const float gain) throw()
  20769. {
  20770. jassert (((unsigned int) channel) < (unsigned int) numChannels);
  20771. jassert (startSample >= 0 && startSample + numSamples <= size);
  20772. if (gain != 1.0f)
  20773. {
  20774. float* d = channels [channel] + startSample;
  20775. if (gain == 0.0f)
  20776. {
  20777. zeromem (d, sizeof (float) * numSamples);
  20778. }
  20779. else
  20780. {
  20781. while (--numSamples >= 0)
  20782. *d++ *= gain;
  20783. }
  20784. }
  20785. }
  20786. void AudioSampleBuffer::applyGainRamp (const int channel,
  20787. const int startSample,
  20788. int numSamples,
  20789. float startGain,
  20790. float endGain) throw()
  20791. {
  20792. if (startGain == endGain)
  20793. {
  20794. applyGain (channel, startSample, numSamples, startGain);
  20795. }
  20796. else
  20797. {
  20798. jassert (((unsigned int) channel) < (unsigned int) numChannels);
  20799. jassert (startSample >= 0 && startSample + numSamples <= size);
  20800. const float increment = (endGain - startGain) / numSamples;
  20801. float* d = channels [channel] + startSample;
  20802. while (--numSamples >= 0)
  20803. {
  20804. *d++ *= startGain;
  20805. startGain += increment;
  20806. }
  20807. }
  20808. }
  20809. void AudioSampleBuffer::applyGain (const int startSample,
  20810. const int numSamples,
  20811. const float gain) throw()
  20812. {
  20813. for (int i = 0; i < numChannels; ++i)
  20814. applyGain (i, startSample, numSamples, gain);
  20815. }
  20816. void AudioSampleBuffer::addFrom (const int destChannel,
  20817. const int destStartSample,
  20818. const AudioSampleBuffer& source,
  20819. const int sourceChannel,
  20820. const int sourceStartSample,
  20821. int numSamples,
  20822. const float gain) throw()
  20823. {
  20824. jassert (&source != this || sourceChannel != destChannel);
  20825. jassert (((unsigned int) destChannel) < (unsigned int) numChannels);
  20826. jassert (destStartSample >= 0 && destStartSample + numSamples <= size);
  20827. jassert (((unsigned int) sourceChannel) < (unsigned int) source.numChannels);
  20828. jassert (sourceStartSample >= 0 && sourceStartSample + numSamples <= source.size);
  20829. if (gain != 0.0f && numSamples > 0)
  20830. {
  20831. float* d = channels [destChannel] + destStartSample;
  20832. const float* s = source.channels [sourceChannel] + sourceStartSample;
  20833. if (gain != 1.0f)
  20834. {
  20835. while (--numSamples >= 0)
  20836. *d++ += gain * *s++;
  20837. }
  20838. else
  20839. {
  20840. while (--numSamples >= 0)
  20841. *d++ += *s++;
  20842. }
  20843. }
  20844. }
  20845. void AudioSampleBuffer::addFrom (const int destChannel,
  20846. const int destStartSample,
  20847. const float* source,
  20848. int numSamples,
  20849. const float gain) throw()
  20850. {
  20851. jassert (((unsigned int) destChannel) < (unsigned int) numChannels);
  20852. jassert (destStartSample >= 0 && destStartSample + numSamples <= size);
  20853. jassert (source != 0);
  20854. if (gain != 0.0f && numSamples > 0)
  20855. {
  20856. float* d = channels [destChannel] + destStartSample;
  20857. if (gain != 1.0f)
  20858. {
  20859. while (--numSamples >= 0)
  20860. *d++ += gain * *source++;
  20861. }
  20862. else
  20863. {
  20864. while (--numSamples >= 0)
  20865. *d++ += *source++;
  20866. }
  20867. }
  20868. }
  20869. void AudioSampleBuffer::addFromWithRamp (const int destChannel,
  20870. const int destStartSample,
  20871. const float* source,
  20872. int numSamples,
  20873. float startGain,
  20874. const float endGain) throw()
  20875. {
  20876. jassert (((unsigned int) destChannel) < (unsigned int) numChannels);
  20877. jassert (destStartSample >= 0 && destStartSample + numSamples <= size);
  20878. jassert (source != 0);
  20879. if (startGain == endGain)
  20880. {
  20881. addFrom (destChannel,
  20882. destStartSample,
  20883. source,
  20884. numSamples,
  20885. startGain);
  20886. }
  20887. else
  20888. {
  20889. if (numSamples > 0 && (startGain != 0.0f || endGain != 0.0f))
  20890. {
  20891. const float increment = (endGain - startGain) / numSamples;
  20892. float* d = channels [destChannel] + destStartSample;
  20893. while (--numSamples >= 0)
  20894. {
  20895. *d++ += startGain * *source++;
  20896. startGain += increment;
  20897. }
  20898. }
  20899. }
  20900. }
  20901. void AudioSampleBuffer::copyFrom (const int destChannel,
  20902. const int destStartSample,
  20903. const AudioSampleBuffer& source,
  20904. const int sourceChannel,
  20905. const int sourceStartSample,
  20906. int numSamples) throw()
  20907. {
  20908. jassert (&source != this || sourceChannel != destChannel);
  20909. jassert (((unsigned int) destChannel) < (unsigned int) numChannels);
  20910. jassert (destStartSample >= 0 && destStartSample + numSamples <= size);
  20911. jassert (((unsigned int) sourceChannel) < (unsigned int) source.numChannels);
  20912. jassert (sourceStartSample >= 0 && sourceStartSample + numSamples <= source.size);
  20913. if (numSamples > 0)
  20914. {
  20915. memcpy (channels [destChannel] + destStartSample,
  20916. source.channels [sourceChannel] + sourceStartSample,
  20917. sizeof (float) * numSamples);
  20918. }
  20919. }
  20920. void AudioSampleBuffer::copyFrom (const int destChannel,
  20921. const int destStartSample,
  20922. const float* source,
  20923. int numSamples) throw()
  20924. {
  20925. jassert (((unsigned int) destChannel) < (unsigned int) numChannels);
  20926. jassert (destStartSample >= 0 && destStartSample + numSamples <= size);
  20927. jassert (source != 0);
  20928. if (numSamples > 0)
  20929. {
  20930. memcpy (channels [destChannel] + destStartSample,
  20931. source,
  20932. sizeof (float) * numSamples);
  20933. }
  20934. }
  20935. void AudioSampleBuffer::copyFrom (const int destChannel,
  20936. const int destStartSample,
  20937. const float* source,
  20938. int numSamples,
  20939. const float gain) throw()
  20940. {
  20941. jassert (((unsigned int) destChannel) < (unsigned int) numChannels);
  20942. jassert (destStartSample >= 0 && destStartSample + numSamples <= size);
  20943. jassert (source != 0);
  20944. if (numSamples > 0)
  20945. {
  20946. float* d = channels [destChannel] + destStartSample;
  20947. if (gain != 1.0f)
  20948. {
  20949. if (gain == 0)
  20950. {
  20951. zeromem (d, sizeof (float) * numSamples);
  20952. }
  20953. else
  20954. {
  20955. while (--numSamples >= 0)
  20956. *d++ = gain * *source++;
  20957. }
  20958. }
  20959. else
  20960. {
  20961. memcpy (d, source, sizeof (float) * numSamples);
  20962. }
  20963. }
  20964. }
  20965. void AudioSampleBuffer::copyFromWithRamp (const int destChannel,
  20966. const int destStartSample,
  20967. const float* source,
  20968. int numSamples,
  20969. float startGain,
  20970. float endGain) throw()
  20971. {
  20972. jassert (((unsigned int) destChannel) < (unsigned int) numChannels);
  20973. jassert (destStartSample >= 0 && destStartSample + numSamples <= size);
  20974. jassert (source != 0);
  20975. if (startGain == endGain)
  20976. {
  20977. copyFrom (destChannel,
  20978. destStartSample,
  20979. source,
  20980. numSamples,
  20981. startGain);
  20982. }
  20983. else
  20984. {
  20985. if (numSamples > 0 && (startGain != 0.0f || endGain != 0.0f))
  20986. {
  20987. const float increment = (endGain - startGain) / numSamples;
  20988. float* d = channels [destChannel] + destStartSample;
  20989. while (--numSamples >= 0)
  20990. {
  20991. *d++ = startGain * *source++;
  20992. startGain += increment;
  20993. }
  20994. }
  20995. }
  20996. }
  20997. void AudioSampleBuffer::findMinMax (const int channel,
  20998. const int startSample,
  20999. int numSamples,
  21000. float& minVal,
  21001. float& maxVal) const throw()
  21002. {
  21003. jassert (((unsigned int) channel) < (unsigned int) numChannels);
  21004. jassert (startSample >= 0 && startSample + numSamples <= size);
  21005. if (numSamples <= 0)
  21006. {
  21007. minVal = 0.0f;
  21008. maxVal = 0.0f;
  21009. }
  21010. else
  21011. {
  21012. const float* d = channels [channel] + startSample;
  21013. float mn = *d++;
  21014. float mx = mn;
  21015. while (--numSamples > 0) // (> 0 rather than >= 0 because we've already taken the first sample)
  21016. {
  21017. const float samp = *d++;
  21018. if (samp > mx)
  21019. mx = samp;
  21020. if (samp < mn)
  21021. mn = samp;
  21022. }
  21023. maxVal = mx;
  21024. minVal = mn;
  21025. }
  21026. }
  21027. float AudioSampleBuffer::getMagnitude (const int channel,
  21028. const int startSample,
  21029. const int numSamples) const throw()
  21030. {
  21031. jassert (((unsigned int) channel) < (unsigned int) numChannels);
  21032. jassert (startSample >= 0 && startSample + numSamples <= size);
  21033. float mn, mx;
  21034. findMinMax (channel, startSample, numSamples, mn, mx);
  21035. return jmax (mn, -mn, mx, -mx);
  21036. }
  21037. float AudioSampleBuffer::getMagnitude (const int startSample,
  21038. const int numSamples) const throw()
  21039. {
  21040. float mag = 0.0f;
  21041. for (int i = 0; i < numChannels; ++i)
  21042. mag = jmax (mag, getMagnitude (i, startSample, numSamples));
  21043. return mag;
  21044. }
  21045. float AudioSampleBuffer::getRMSLevel (const int channel,
  21046. const int startSample,
  21047. const int numSamples) const throw()
  21048. {
  21049. jassert (((unsigned int) channel) < (unsigned int) numChannels);
  21050. jassert (startSample >= 0 && startSample + numSamples <= size);
  21051. if (numSamples <= 0 || channel < 0 || channel >= numChannels)
  21052. return 0.0f;
  21053. const float* const data = channels [channel] + startSample;
  21054. double sum = 0.0;
  21055. for (int i = 0; i < numSamples; ++i)
  21056. {
  21057. const float sample = data [i];
  21058. sum += sample * sample;
  21059. }
  21060. return (float) std::sqrt (sum / numSamples);
  21061. }
  21062. void AudioSampleBuffer::readFromAudioReader (AudioFormatReader* reader,
  21063. const int startSample,
  21064. const int numSamples,
  21065. const int readerStartSample,
  21066. const bool useLeftChan,
  21067. const bool useRightChan) throw()
  21068. {
  21069. jassert (reader != 0);
  21070. jassert (startSample >= 0 && startSample + numSamples <= size);
  21071. if (numSamples > 0)
  21072. {
  21073. int* chans[3];
  21074. if (useLeftChan == useRightChan)
  21075. {
  21076. chans[0] = (int*) getSampleData (0, startSample);
  21077. chans[1] = (reader->numChannels > 1 && getNumChannels() > 1) ? (int*) getSampleData (1, startSample) : 0;
  21078. }
  21079. else if (useLeftChan || (reader->numChannels == 1))
  21080. {
  21081. chans[0] = (int*) getSampleData (0, startSample);
  21082. chans[1] = 0;
  21083. }
  21084. else if (useRightChan)
  21085. {
  21086. chans[0] = 0;
  21087. chans[1] = (int*) getSampleData (0, startSample);
  21088. }
  21089. chans[2] = 0;
  21090. reader->read (chans, 2, readerStartSample, numSamples, true);
  21091. if (! reader->usesFloatingPointData)
  21092. {
  21093. for (int j = 0; j < 2; ++j)
  21094. {
  21095. float* const d = reinterpret_cast <float*> (chans[j]);
  21096. if (d != 0)
  21097. {
  21098. const float multiplier = 1.0f / 0x7fffffff;
  21099. for (int i = 0; i < numSamples; ++i)
  21100. d[i] = *(int*)(d + i) * multiplier;
  21101. }
  21102. }
  21103. }
  21104. if (numChannels > 1 && (chans[0] == 0 || chans[1] == 0))
  21105. {
  21106. // if this is a stereo buffer and the source was mono, dupe the first channel..
  21107. memcpy (getSampleData (1, startSample),
  21108. getSampleData (0, startSample),
  21109. sizeof (float) * numSamples);
  21110. }
  21111. }
  21112. }
  21113. void AudioSampleBuffer::writeToAudioWriter (AudioFormatWriter* writer,
  21114. const int startSample,
  21115. const int numSamples) const throw()
  21116. {
  21117. jassert (startSample >= 0 && startSample + numSamples <= size);
  21118. if (numSamples > 0)
  21119. {
  21120. int* chans [3];
  21121. if (writer->isFloatingPoint())
  21122. {
  21123. chans[0] = (int*) getSampleData (0, startSample);
  21124. if (numChannels > 1)
  21125. chans[1] = (int*) getSampleData (1, startSample);
  21126. else
  21127. chans[1] = 0;
  21128. chans[2] = 0;
  21129. writer->write ((const int**) chans, numSamples);
  21130. }
  21131. else
  21132. {
  21133. HeapBlock <int> tempBuffer (numSamples * 2);
  21134. chans[0] = tempBuffer;
  21135. if (numChannels > 1)
  21136. chans[1] = chans[0] + numSamples;
  21137. else
  21138. chans[1] = 0;
  21139. chans[2] = 0;
  21140. for (int j = 0; j < 2; ++j)
  21141. {
  21142. int* const dest = chans[j];
  21143. if (dest != 0)
  21144. {
  21145. const float* const src = channels [j] + startSample;
  21146. for (int i = 0; i < numSamples; ++i)
  21147. {
  21148. const double samp = src[i];
  21149. if (samp <= -1.0)
  21150. dest[i] = std::numeric_limits<int>::min();
  21151. else if (samp >= 1.0)
  21152. dest[i] = std::numeric_limits<int>::max();
  21153. else
  21154. dest[i] = roundToInt (std::numeric_limits<int>::max() * samp);
  21155. }
  21156. }
  21157. }
  21158. writer->write ((const int**) chans, numSamples);
  21159. }
  21160. }
  21161. }
  21162. END_JUCE_NAMESPACE
  21163. /*** End of inlined file: juce_AudioSampleBuffer.cpp ***/
  21164. /*** Start of inlined file: juce_IIRFilter.cpp ***/
  21165. BEGIN_JUCE_NAMESPACE
  21166. IIRFilter::IIRFilter()
  21167. : active (false)
  21168. {
  21169. reset();
  21170. }
  21171. IIRFilter::IIRFilter (const IIRFilter& other)
  21172. : active (other.active)
  21173. {
  21174. const ScopedLock sl (other.processLock);
  21175. memcpy (coefficients, other.coefficients, sizeof (coefficients));
  21176. reset();
  21177. }
  21178. IIRFilter::~IIRFilter()
  21179. {
  21180. }
  21181. void IIRFilter::reset() throw()
  21182. {
  21183. const ScopedLock sl (processLock);
  21184. x1 = 0;
  21185. x2 = 0;
  21186. y1 = 0;
  21187. y2 = 0;
  21188. }
  21189. float IIRFilter::processSingleSampleRaw (const float in) throw()
  21190. {
  21191. float out = coefficients[0] * in
  21192. + coefficients[1] * x1
  21193. + coefficients[2] * x2
  21194. - coefficients[4] * y1
  21195. - coefficients[5] * y2;
  21196. #if JUCE_INTEL
  21197. if (! (out < -1.0e-8 || out > 1.0e-8))
  21198. out = 0;
  21199. #endif
  21200. x2 = x1;
  21201. x1 = in;
  21202. y2 = y1;
  21203. y1 = out;
  21204. return out;
  21205. }
  21206. void IIRFilter::processSamples (float* const samples,
  21207. const int numSamples) throw()
  21208. {
  21209. const ScopedLock sl (processLock);
  21210. if (active)
  21211. {
  21212. for (int i = 0; i < numSamples; ++i)
  21213. {
  21214. const float in = samples[i];
  21215. float out = coefficients[0] * in
  21216. + coefficients[1] * x1
  21217. + coefficients[2] * x2
  21218. - coefficients[4] * y1
  21219. - coefficients[5] * y2;
  21220. #if JUCE_INTEL
  21221. if (! (out < -1.0e-8 || out > 1.0e-8))
  21222. out = 0;
  21223. #endif
  21224. x2 = x1;
  21225. x1 = in;
  21226. y2 = y1;
  21227. y1 = out;
  21228. samples[i] = out;
  21229. }
  21230. }
  21231. }
  21232. void IIRFilter::makeLowPass (const double sampleRate,
  21233. const double frequency) throw()
  21234. {
  21235. jassert (sampleRate > 0);
  21236. const double n = 1.0 / tan (double_Pi * frequency / sampleRate);
  21237. const double nSquared = n * n;
  21238. const double c1 = 1.0 / (1.0 + std::sqrt (2.0) * n + nSquared);
  21239. setCoefficients (c1,
  21240. c1 * 2.0f,
  21241. c1,
  21242. 1.0,
  21243. c1 * 2.0 * (1.0 - nSquared),
  21244. c1 * (1.0 - std::sqrt (2.0) * n + nSquared));
  21245. }
  21246. void IIRFilter::makeHighPass (const double sampleRate,
  21247. const double frequency) throw()
  21248. {
  21249. const double n = tan (double_Pi * frequency / sampleRate);
  21250. const double nSquared = n * n;
  21251. const double c1 = 1.0 / (1.0 + std::sqrt (2.0) * n + nSquared);
  21252. setCoefficients (c1,
  21253. c1 * -2.0f,
  21254. c1,
  21255. 1.0,
  21256. c1 * 2.0 * (nSquared - 1.0),
  21257. c1 * (1.0 - std::sqrt (2.0) * n + nSquared));
  21258. }
  21259. void IIRFilter::makeLowShelf (const double sampleRate,
  21260. const double cutOffFrequency,
  21261. const double Q,
  21262. const float gainFactor) throw()
  21263. {
  21264. jassert (sampleRate > 0);
  21265. jassert (Q > 0);
  21266. const double A = jmax (0.0f, gainFactor);
  21267. const double aminus1 = A - 1.0;
  21268. const double aplus1 = A + 1.0;
  21269. const double omega = (double_Pi * 2.0 * jmax (cutOffFrequency, 2.0)) / sampleRate;
  21270. const double coso = std::cos (omega);
  21271. const double beta = std::sin (omega) * std::sqrt (A) / Q;
  21272. const double aminus1TimesCoso = aminus1 * coso;
  21273. setCoefficients (A * (aplus1 - aminus1TimesCoso + beta),
  21274. A * 2.0 * (aminus1 - aplus1 * coso),
  21275. A * (aplus1 - aminus1TimesCoso - beta),
  21276. aplus1 + aminus1TimesCoso + beta,
  21277. -2.0 * (aminus1 + aplus1 * coso),
  21278. aplus1 + aminus1TimesCoso - beta);
  21279. }
  21280. void IIRFilter::makeHighShelf (const double sampleRate,
  21281. const double cutOffFrequency,
  21282. const double Q,
  21283. const float gainFactor) throw()
  21284. {
  21285. jassert (sampleRate > 0);
  21286. jassert (Q > 0);
  21287. const double A = jmax (0.0f, gainFactor);
  21288. const double aminus1 = A - 1.0;
  21289. const double aplus1 = A + 1.0;
  21290. const double omega = (double_Pi * 2.0 * jmax (cutOffFrequency, 2.0)) / sampleRate;
  21291. const double coso = std::cos (omega);
  21292. const double beta = std::sin (omega) * std::sqrt (A) / Q;
  21293. const double aminus1TimesCoso = aminus1 * coso;
  21294. setCoefficients (A * (aplus1 + aminus1TimesCoso + beta),
  21295. A * -2.0 * (aminus1 + aplus1 * coso),
  21296. A * (aplus1 + aminus1TimesCoso - beta),
  21297. aplus1 - aminus1TimesCoso + beta,
  21298. 2.0 * (aminus1 - aplus1 * coso),
  21299. aplus1 - aminus1TimesCoso - beta);
  21300. }
  21301. void IIRFilter::makeBandPass (const double sampleRate,
  21302. const double centreFrequency,
  21303. const double Q,
  21304. const float gainFactor) throw()
  21305. {
  21306. jassert (sampleRate > 0);
  21307. jassert (Q > 0);
  21308. const double A = jmax (0.0f, gainFactor);
  21309. const double omega = (double_Pi * 2.0 * jmax (centreFrequency, 2.0)) / sampleRate;
  21310. const double alpha = 0.5 * std::sin (omega) / Q;
  21311. const double c2 = -2.0 * std::cos (omega);
  21312. const double alphaTimesA = alpha * A;
  21313. const double alphaOverA = alpha / A;
  21314. setCoefficients (1.0 + alphaTimesA,
  21315. c2,
  21316. 1.0 - alphaTimesA,
  21317. 1.0 + alphaOverA,
  21318. c2,
  21319. 1.0 - alphaOverA);
  21320. }
  21321. void IIRFilter::makeInactive() throw()
  21322. {
  21323. const ScopedLock sl (processLock);
  21324. active = false;
  21325. }
  21326. void IIRFilter::copyCoefficientsFrom (const IIRFilter& other) throw()
  21327. {
  21328. const ScopedLock sl (processLock);
  21329. memcpy (coefficients, other.coefficients, sizeof (coefficients));
  21330. active = other.active;
  21331. }
  21332. void IIRFilter::setCoefficients (double c1,
  21333. double c2,
  21334. double c3,
  21335. double c4,
  21336. double c5,
  21337. double c6) throw()
  21338. {
  21339. const double a = 1.0 / c4;
  21340. c1 *= a;
  21341. c2 *= a;
  21342. c3 *= a;
  21343. c5 *= a;
  21344. c6 *= a;
  21345. const ScopedLock sl (processLock);
  21346. coefficients[0] = (float) c1;
  21347. coefficients[1] = (float) c2;
  21348. coefficients[2] = (float) c3;
  21349. coefficients[3] = (float) c4;
  21350. coefficients[4] = (float) c5;
  21351. coefficients[5] = (float) c6;
  21352. active = true;
  21353. }
  21354. END_JUCE_NAMESPACE
  21355. /*** End of inlined file: juce_IIRFilter.cpp ***/
  21356. /*** Start of inlined file: juce_MidiBuffer.cpp ***/
  21357. BEGIN_JUCE_NAMESPACE
  21358. MidiBuffer::MidiBuffer() throw()
  21359. : bytesUsed (0)
  21360. {
  21361. }
  21362. MidiBuffer::MidiBuffer (const MidiMessage& message) throw()
  21363. : bytesUsed (0)
  21364. {
  21365. addEvent (message, 0);
  21366. }
  21367. MidiBuffer::MidiBuffer (const MidiBuffer& other) throw()
  21368. : data (other.data),
  21369. bytesUsed (other.bytesUsed)
  21370. {
  21371. }
  21372. MidiBuffer& MidiBuffer::operator= (const MidiBuffer& other) throw()
  21373. {
  21374. bytesUsed = other.bytesUsed;
  21375. data = other.data;
  21376. return *this;
  21377. }
  21378. void MidiBuffer::swapWith (MidiBuffer& other)
  21379. {
  21380. data.swapWith (other.data);
  21381. swapVariables <int> (bytesUsed, other.bytesUsed);
  21382. }
  21383. MidiBuffer::~MidiBuffer() throw()
  21384. {
  21385. }
  21386. inline uint8* MidiBuffer::getData() const throw()
  21387. {
  21388. return static_cast <uint8*> (data.getData());
  21389. }
  21390. inline int MidiBuffer::getEventTime (const void* const d) throw()
  21391. {
  21392. return *static_cast <const int*> (d);
  21393. }
  21394. inline uint16 MidiBuffer::getEventDataSize (const void* const d) throw()
  21395. {
  21396. return *reinterpret_cast <const uint16*> (static_cast <const char*> (d) + sizeof (int));
  21397. }
  21398. inline uint16 MidiBuffer::getEventTotalSize (const void* const d) throw()
  21399. {
  21400. return getEventDataSize (d) + sizeof (int) + sizeof (uint16);
  21401. }
  21402. void MidiBuffer::clear() throw()
  21403. {
  21404. bytesUsed = 0;
  21405. }
  21406. void MidiBuffer::clear (const int startSample,
  21407. const int numSamples) throw()
  21408. {
  21409. uint8* const start = findEventAfter (getData(), startSample - 1);
  21410. uint8* const end = findEventAfter (start, startSample + numSamples - 1);
  21411. if (end > start)
  21412. {
  21413. const int bytesToMove = bytesUsed - (int) (end - getData());
  21414. if (bytesToMove > 0)
  21415. memmove (start, end, bytesToMove);
  21416. bytesUsed -= (int) (end - start);
  21417. }
  21418. }
  21419. void MidiBuffer::addEvent (const MidiMessage& m,
  21420. const int sampleNumber) throw()
  21421. {
  21422. addEvent (m.getRawData(), m.getRawDataSize(), sampleNumber);
  21423. }
  21424. static int findActualEventLength (const uint8* const data,
  21425. const int maxBytes) throw()
  21426. {
  21427. unsigned int byte = (unsigned int) *data;
  21428. int size = 0;
  21429. if (byte == 0xf0 || byte == 0xf7)
  21430. {
  21431. const uint8* d = data + 1;
  21432. while (d < data + maxBytes)
  21433. if (*d++ == 0xf7)
  21434. break;
  21435. size = (int) (d - data);
  21436. }
  21437. else if (byte == 0xff)
  21438. {
  21439. int n;
  21440. const int bytesLeft = MidiMessage::readVariableLengthVal (data + 1, n);
  21441. size = jmin (maxBytes, n + 2 + bytesLeft);
  21442. }
  21443. else if (byte >= 0x80)
  21444. {
  21445. size = jmin (maxBytes, MidiMessage::getMessageLengthFromFirstByte ((uint8) byte));
  21446. }
  21447. return size;
  21448. }
  21449. void MidiBuffer::addEvent (const uint8* const newData,
  21450. const int maxBytes,
  21451. const int sampleNumber) throw()
  21452. {
  21453. const int numBytes = findActualEventLength (newData, maxBytes);
  21454. if (numBytes > 0)
  21455. {
  21456. int spaceNeeded = bytesUsed + numBytes + sizeof (int) + sizeof (uint16);
  21457. data.ensureSize ((spaceNeeded + spaceNeeded / 2 + 8) & ~7);
  21458. uint8* d = findEventAfter (getData(), sampleNumber);
  21459. const int bytesToMove = bytesUsed - (int) (d - getData());
  21460. if (bytesToMove > 0)
  21461. memmove (d + numBytes + sizeof (int) + sizeof (uint16), d, bytesToMove);
  21462. *reinterpret_cast <int*> (d) = sampleNumber;
  21463. d += sizeof (int);
  21464. *reinterpret_cast <uint16*> (d) = (uint16) numBytes;
  21465. d += sizeof (uint16);
  21466. memcpy (d, newData, numBytes);
  21467. bytesUsed += numBytes + sizeof (int) + sizeof (uint16);
  21468. }
  21469. }
  21470. void MidiBuffer::addEvents (const MidiBuffer& otherBuffer,
  21471. const int startSample,
  21472. const int numSamples,
  21473. const int sampleDeltaToAdd) throw()
  21474. {
  21475. Iterator i (otherBuffer);
  21476. i.setNextSamplePosition (startSample);
  21477. const uint8* eventData;
  21478. int eventSize, position;
  21479. while (i.getNextEvent (eventData, eventSize, position)
  21480. && (position < startSample + numSamples || numSamples < 0))
  21481. {
  21482. addEvent (eventData, eventSize, position + sampleDeltaToAdd);
  21483. }
  21484. }
  21485. void MidiBuffer::ensureSize (size_t minimumNumBytes)
  21486. {
  21487. data.ensureSize (minimumNumBytes);
  21488. }
  21489. bool MidiBuffer::isEmpty() const throw()
  21490. {
  21491. return bytesUsed == 0;
  21492. }
  21493. int MidiBuffer::getNumEvents() const throw()
  21494. {
  21495. int n = 0;
  21496. const uint8* d = getData();
  21497. const uint8* const end = d + bytesUsed;
  21498. while (d < end)
  21499. {
  21500. d += getEventTotalSize (d);
  21501. ++n;
  21502. }
  21503. return n;
  21504. }
  21505. int MidiBuffer::getFirstEventTime() const throw()
  21506. {
  21507. return bytesUsed > 0 ? getEventTime (data.getData()) : 0;
  21508. }
  21509. int MidiBuffer::getLastEventTime() const throw()
  21510. {
  21511. if (bytesUsed == 0)
  21512. return 0;
  21513. const uint8* d = getData();
  21514. const uint8* const endData = d + bytesUsed;
  21515. for (;;)
  21516. {
  21517. const uint8* const nextOne = d + getEventTotalSize (d);
  21518. if (nextOne >= endData)
  21519. return getEventTime (d);
  21520. d = nextOne;
  21521. }
  21522. }
  21523. uint8* MidiBuffer::findEventAfter (uint8* d, const int samplePosition) const throw()
  21524. {
  21525. const uint8* const endData = getData() + bytesUsed;
  21526. while (d < endData && getEventTime (d) <= samplePosition)
  21527. d += getEventTotalSize (d);
  21528. return d;
  21529. }
  21530. MidiBuffer::Iterator::Iterator (const MidiBuffer& buffer_) throw()
  21531. : buffer (buffer_),
  21532. data (buffer_.getData())
  21533. {
  21534. }
  21535. MidiBuffer::Iterator::~Iterator() throw()
  21536. {
  21537. }
  21538. void MidiBuffer::Iterator::setNextSamplePosition (const int samplePosition) throw()
  21539. {
  21540. data = buffer.getData();
  21541. const uint8* dataEnd = data + buffer.bytesUsed;
  21542. while (data < dataEnd && getEventTime (data) < samplePosition)
  21543. data += getEventTotalSize (data);
  21544. }
  21545. bool MidiBuffer::Iterator::getNextEvent (const uint8* &midiData, int& numBytes, int& samplePosition) throw()
  21546. {
  21547. if (data >= buffer.getData() + buffer.bytesUsed)
  21548. return false;
  21549. samplePosition = getEventTime (data);
  21550. numBytes = getEventDataSize (data);
  21551. data += sizeof (int) + sizeof (uint16);
  21552. midiData = data;
  21553. data += numBytes;
  21554. return true;
  21555. }
  21556. bool MidiBuffer::Iterator::getNextEvent (MidiMessage& result, int& samplePosition) throw()
  21557. {
  21558. if (data >= buffer.getData() + buffer.bytesUsed)
  21559. return false;
  21560. samplePosition = getEventTime (data);
  21561. const int numBytes = getEventDataSize (data);
  21562. data += sizeof (int) + sizeof (uint16);
  21563. result = MidiMessage (data, numBytes, samplePosition);
  21564. data += numBytes;
  21565. return true;
  21566. }
  21567. END_JUCE_NAMESPACE
  21568. /*** End of inlined file: juce_MidiBuffer.cpp ***/
  21569. /*** Start of inlined file: juce_MidiFile.cpp ***/
  21570. BEGIN_JUCE_NAMESPACE
  21571. namespace MidiFileHelpers
  21572. {
  21573. static void writeVariableLengthInt (OutputStream& out, unsigned int v)
  21574. {
  21575. unsigned int buffer = v & 0x7F;
  21576. while ((v >>= 7) != 0)
  21577. {
  21578. buffer <<= 8;
  21579. buffer |= ((v & 0x7F) | 0x80);
  21580. }
  21581. for (;;)
  21582. {
  21583. out.writeByte ((char) buffer);
  21584. if (buffer & 0x80)
  21585. buffer >>= 8;
  21586. else
  21587. break;
  21588. }
  21589. }
  21590. static bool parseMidiHeader (const uint8* &data, short& timeFormat, short& fileType, short& numberOfTracks) throw()
  21591. {
  21592. unsigned int ch = (int) ByteOrder::bigEndianInt (data);
  21593. data += 4;
  21594. if (ch != ByteOrder::bigEndianInt ("MThd"))
  21595. {
  21596. bool ok = false;
  21597. if (ch == ByteOrder::bigEndianInt ("RIFF"))
  21598. {
  21599. for (int i = 0; i < 8; ++i)
  21600. {
  21601. ch = ByteOrder::bigEndianInt (data);
  21602. data += 4;
  21603. if (ch == ByteOrder::bigEndianInt ("MThd"))
  21604. {
  21605. ok = true;
  21606. break;
  21607. }
  21608. }
  21609. }
  21610. if (! ok)
  21611. return false;
  21612. }
  21613. unsigned int bytesRemaining = ByteOrder::bigEndianInt (data);
  21614. data += 4;
  21615. fileType = (short) ByteOrder::bigEndianShort (data);
  21616. data += 2;
  21617. numberOfTracks = (short) ByteOrder::bigEndianShort (data);
  21618. data += 2;
  21619. timeFormat = (short) ByteOrder::bigEndianShort (data);
  21620. data += 2;
  21621. bytesRemaining -= 6;
  21622. data += bytesRemaining;
  21623. return true;
  21624. }
  21625. static double convertTicksToSeconds (const double time,
  21626. const MidiMessageSequence& tempoEvents,
  21627. const int timeFormat)
  21628. {
  21629. if (timeFormat > 0)
  21630. {
  21631. int numer = 4, denom = 4;
  21632. double tempoTime = 0.0, correctedTempoTime = 0.0;
  21633. const double tickLen = 1.0 / (timeFormat & 0x7fff);
  21634. double secsPerTick = 0.5 * tickLen;
  21635. const int numEvents = tempoEvents.getNumEvents();
  21636. for (int i = 0; i < numEvents; ++i)
  21637. {
  21638. const MidiMessage& m = tempoEvents.getEventPointer(i)->message;
  21639. if (time <= m.getTimeStamp())
  21640. break;
  21641. if (timeFormat > 0)
  21642. {
  21643. correctedTempoTime = correctedTempoTime
  21644. + (m.getTimeStamp() - tempoTime) * secsPerTick;
  21645. }
  21646. else
  21647. {
  21648. correctedTempoTime = tickLen * m.getTimeStamp() / (((timeFormat & 0x7fff) >> 8) * (timeFormat & 0xff));
  21649. }
  21650. tempoTime = m.getTimeStamp();
  21651. if (m.isTempoMetaEvent())
  21652. secsPerTick = tickLen * m.getTempoSecondsPerQuarterNote();
  21653. else if (m.isTimeSignatureMetaEvent())
  21654. m.getTimeSignatureInfo (numer, denom);
  21655. while (i + 1 < numEvents)
  21656. {
  21657. const MidiMessage& m2 = tempoEvents.getEventPointer(i + 1)->message;
  21658. if (m2.getTimeStamp() == tempoTime)
  21659. {
  21660. ++i;
  21661. if (m2.isTempoMetaEvent())
  21662. secsPerTick = tickLen * m2.getTempoSecondsPerQuarterNote();
  21663. else if (m2.isTimeSignatureMetaEvent())
  21664. m2.getTimeSignatureInfo (numer, denom);
  21665. }
  21666. else
  21667. {
  21668. break;
  21669. }
  21670. }
  21671. }
  21672. return correctedTempoTime + (time - tempoTime) * secsPerTick;
  21673. }
  21674. else
  21675. {
  21676. return time / (((timeFormat & 0x7fff) >> 8) * (timeFormat & 0xff));
  21677. }
  21678. }
  21679. }
  21680. MidiFile::MidiFile()
  21681. : timeFormat ((short) (unsigned short) 0xe728)
  21682. {
  21683. }
  21684. MidiFile::~MidiFile()
  21685. {
  21686. clear();
  21687. }
  21688. void MidiFile::clear()
  21689. {
  21690. tracks.clear();
  21691. }
  21692. int MidiFile::getNumTracks() const throw()
  21693. {
  21694. return tracks.size();
  21695. }
  21696. const MidiMessageSequence* MidiFile::getTrack (const int index) const throw()
  21697. {
  21698. return tracks [index];
  21699. }
  21700. void MidiFile::addTrack (const MidiMessageSequence& trackSequence)
  21701. {
  21702. tracks.add (new MidiMessageSequence (trackSequence));
  21703. }
  21704. short MidiFile::getTimeFormat() const throw()
  21705. {
  21706. return timeFormat;
  21707. }
  21708. void MidiFile::setTicksPerQuarterNote (const int ticks) throw()
  21709. {
  21710. timeFormat = (short) ticks;
  21711. }
  21712. void MidiFile::setSmpteTimeFormat (const int framesPerSecond,
  21713. const int subframeResolution) throw()
  21714. {
  21715. timeFormat = (short) (((-framesPerSecond) << 8) | subframeResolution);
  21716. }
  21717. void MidiFile::findAllTempoEvents (MidiMessageSequence& tempoChangeEvents) const
  21718. {
  21719. for (int i = tracks.size(); --i >= 0;)
  21720. {
  21721. const int numEvents = tracks.getUnchecked(i)->getNumEvents();
  21722. for (int j = 0; j < numEvents; ++j)
  21723. {
  21724. const MidiMessage& m = tracks.getUnchecked(i)->getEventPointer (j)->message;
  21725. if (m.isTempoMetaEvent())
  21726. tempoChangeEvents.addEvent (m);
  21727. }
  21728. }
  21729. }
  21730. void MidiFile::findAllTimeSigEvents (MidiMessageSequence& timeSigEvents) const
  21731. {
  21732. for (int i = tracks.size(); --i >= 0;)
  21733. {
  21734. const int numEvents = tracks.getUnchecked(i)->getNumEvents();
  21735. for (int j = 0; j < numEvents; ++j)
  21736. {
  21737. const MidiMessage& m = tracks.getUnchecked(i)->getEventPointer (j)->message;
  21738. if (m.isTimeSignatureMetaEvent())
  21739. timeSigEvents.addEvent (m);
  21740. }
  21741. }
  21742. }
  21743. double MidiFile::getLastTimestamp() const
  21744. {
  21745. double t = 0.0;
  21746. for (int i = tracks.size(); --i >= 0;)
  21747. t = jmax (t, tracks.getUnchecked(i)->getEndTime());
  21748. return t;
  21749. }
  21750. bool MidiFile::readFrom (InputStream& sourceStream)
  21751. {
  21752. clear();
  21753. MemoryBlock data;
  21754. const int maxSensibleMidiFileSize = 2 * 1024 * 1024;
  21755. // (put a sanity-check on the file size, as midi files are generally small)
  21756. if (sourceStream.readIntoMemoryBlock (data, maxSensibleMidiFileSize))
  21757. {
  21758. size_t size = data.getSize();
  21759. const uint8* d = static_cast <const uint8*> (data.getData());
  21760. short fileType, expectedTracks;
  21761. if (size > 16 && MidiFileHelpers::parseMidiHeader (d, timeFormat, fileType, expectedTracks))
  21762. {
  21763. size -= (int) (d - static_cast <const uint8*> (data.getData()));
  21764. int track = 0;
  21765. while (size > 0 && track < expectedTracks)
  21766. {
  21767. const int chunkType = (int) ByteOrder::bigEndianInt (d);
  21768. d += 4;
  21769. const int chunkSize = (int) ByteOrder::bigEndianInt (d);
  21770. d += 4;
  21771. if (chunkSize <= 0)
  21772. break;
  21773. if (size < 0)
  21774. return false;
  21775. if (chunkType == (int) ByteOrder::bigEndianInt ("MTrk"))
  21776. {
  21777. readNextTrack (d, chunkSize);
  21778. }
  21779. size -= chunkSize + 8;
  21780. d += chunkSize;
  21781. ++track;
  21782. }
  21783. return true;
  21784. }
  21785. }
  21786. return false;
  21787. }
  21788. // a comparator that puts all the note-offs before note-ons that have the same time
  21789. int MidiFile::compareElements (const MidiMessageSequence::MidiEventHolder* const first,
  21790. const MidiMessageSequence::MidiEventHolder* const second)
  21791. {
  21792. const double diff = (first->message.getTimeStamp() - second->message.getTimeStamp());
  21793. if (diff == 0)
  21794. {
  21795. if (first->message.isNoteOff() && second->message.isNoteOn())
  21796. return -1;
  21797. else if (first->message.isNoteOn() && second->message.isNoteOff())
  21798. return 1;
  21799. else
  21800. return 0;
  21801. }
  21802. else
  21803. {
  21804. return (diff > 0) ? 1 : -1;
  21805. }
  21806. }
  21807. void MidiFile::readNextTrack (const uint8* data, int size)
  21808. {
  21809. double time = 0;
  21810. char lastStatusByte = 0;
  21811. MidiMessageSequence result;
  21812. while (size > 0)
  21813. {
  21814. int bytesUsed;
  21815. const int delay = MidiMessage::readVariableLengthVal (data, bytesUsed);
  21816. data += bytesUsed;
  21817. size -= bytesUsed;
  21818. time += delay;
  21819. int messSize = 0;
  21820. const MidiMessage mm (data, size, messSize, lastStatusByte, time);
  21821. if (messSize <= 0)
  21822. break;
  21823. size -= messSize;
  21824. data += messSize;
  21825. result.addEvent (mm);
  21826. const char firstByte = *(mm.getRawData());
  21827. if ((firstByte & 0xf0) != 0xf0)
  21828. lastStatusByte = firstByte;
  21829. }
  21830. // use a sort that puts all the note-offs before note-ons that have the same time
  21831. result.list.sort (*this, true);
  21832. result.updateMatchedPairs();
  21833. addTrack (result);
  21834. }
  21835. void MidiFile::convertTimestampTicksToSeconds()
  21836. {
  21837. MidiMessageSequence tempoEvents;
  21838. findAllTempoEvents (tempoEvents);
  21839. findAllTimeSigEvents (tempoEvents);
  21840. for (int i = 0; i < tracks.size(); ++i)
  21841. {
  21842. MidiMessageSequence& ms = *tracks.getUnchecked(i);
  21843. for (int j = ms.getNumEvents(); --j >= 0;)
  21844. {
  21845. MidiMessage& m = ms.getEventPointer(j)->message;
  21846. m.setTimeStamp (MidiFileHelpers::convertTicksToSeconds (m.getTimeStamp(),
  21847. tempoEvents,
  21848. timeFormat));
  21849. }
  21850. }
  21851. }
  21852. bool MidiFile::writeTo (OutputStream& out)
  21853. {
  21854. out.writeIntBigEndian ((int) ByteOrder::bigEndianInt ("MThd"));
  21855. out.writeIntBigEndian (6);
  21856. out.writeShortBigEndian (1); // type
  21857. out.writeShortBigEndian ((short) tracks.size());
  21858. out.writeShortBigEndian (timeFormat);
  21859. for (int i = 0; i < tracks.size(); ++i)
  21860. writeTrack (out, i);
  21861. out.flush();
  21862. return true;
  21863. }
  21864. void MidiFile::writeTrack (OutputStream& mainOut,
  21865. const int trackNum)
  21866. {
  21867. MemoryOutputStream out;
  21868. const MidiMessageSequence& ms = *tracks[trackNum];
  21869. int lastTick = 0;
  21870. char lastStatusByte = 0;
  21871. for (int i = 0; i < ms.getNumEvents(); ++i)
  21872. {
  21873. const MidiMessage& mm = ms.getEventPointer(i)->message;
  21874. const int tick = roundToInt (mm.getTimeStamp());
  21875. const int delta = jmax (0, tick - lastTick);
  21876. MidiFileHelpers::writeVariableLengthInt (out, delta);
  21877. lastTick = tick;
  21878. const char statusByte = *(mm.getRawData());
  21879. if ((statusByte == lastStatusByte)
  21880. && ((statusByte & 0xf0) != 0xf0)
  21881. && i > 0
  21882. && mm.getRawDataSize() > 1)
  21883. {
  21884. out.write (mm.getRawData() + 1, mm.getRawDataSize() - 1);
  21885. }
  21886. else
  21887. {
  21888. out.write (mm.getRawData(), mm.getRawDataSize());
  21889. }
  21890. lastStatusByte = statusByte;
  21891. }
  21892. out.writeByte (0);
  21893. const MidiMessage m (MidiMessage::endOfTrack());
  21894. out.write (m.getRawData(),
  21895. m.getRawDataSize());
  21896. mainOut.writeIntBigEndian ((int) ByteOrder::bigEndianInt ("MTrk"));
  21897. mainOut.writeIntBigEndian ((int) out.getDataSize());
  21898. mainOut.write (out.getData(), (int) out.getDataSize());
  21899. }
  21900. END_JUCE_NAMESPACE
  21901. /*** End of inlined file: juce_MidiFile.cpp ***/
  21902. /*** Start of inlined file: juce_MidiKeyboardState.cpp ***/
  21903. BEGIN_JUCE_NAMESPACE
  21904. MidiKeyboardState::MidiKeyboardState()
  21905. {
  21906. zerostruct (noteStates);
  21907. }
  21908. MidiKeyboardState::~MidiKeyboardState()
  21909. {
  21910. }
  21911. void MidiKeyboardState::reset()
  21912. {
  21913. const ScopedLock sl (lock);
  21914. zerostruct (noteStates);
  21915. eventsToAdd.clear();
  21916. }
  21917. bool MidiKeyboardState::isNoteOn (const int midiChannel, const int n) const throw()
  21918. {
  21919. jassert (midiChannel >= 0 && midiChannel <= 16);
  21920. return ((unsigned int) n) < 128
  21921. && (noteStates[n] & (1 << (midiChannel - 1))) != 0;
  21922. }
  21923. bool MidiKeyboardState::isNoteOnForChannels (const int midiChannelMask, const int n) const throw()
  21924. {
  21925. return ((unsigned int) n) < 128
  21926. && (noteStates[n] & midiChannelMask) != 0;
  21927. }
  21928. void MidiKeyboardState::noteOn (const int midiChannel, const int midiNoteNumber, const float velocity)
  21929. {
  21930. jassert (midiChannel >= 0 && midiChannel <= 16);
  21931. jassert (((unsigned int) midiNoteNumber) < 128);
  21932. const ScopedLock sl (lock);
  21933. if (((unsigned int) midiNoteNumber) < 128)
  21934. {
  21935. const int timeNow = (int) Time::getMillisecondCounter();
  21936. eventsToAdd.addEvent (MidiMessage::noteOn (midiChannel, midiNoteNumber, velocity), timeNow);
  21937. eventsToAdd.clear (0, timeNow - 500);
  21938. noteOnInternal (midiChannel, midiNoteNumber, velocity);
  21939. }
  21940. }
  21941. void MidiKeyboardState::noteOnInternal (const int midiChannel, const int midiNoteNumber, const float velocity)
  21942. {
  21943. if (((unsigned int) midiNoteNumber) < 128)
  21944. {
  21945. noteStates [midiNoteNumber] |= (1 << (midiChannel - 1));
  21946. for (int i = listeners.size(); --i >= 0;)
  21947. listeners.getUnchecked(i)->handleNoteOn (this, midiChannel, midiNoteNumber, velocity);
  21948. }
  21949. }
  21950. void MidiKeyboardState::noteOff (const int midiChannel, const int midiNoteNumber)
  21951. {
  21952. const ScopedLock sl (lock);
  21953. if (isNoteOn (midiChannel, midiNoteNumber))
  21954. {
  21955. const int timeNow = (int) Time::getMillisecondCounter();
  21956. eventsToAdd.addEvent (MidiMessage::noteOff (midiChannel, midiNoteNumber), timeNow);
  21957. eventsToAdd.clear (0, timeNow - 500);
  21958. noteOffInternal (midiChannel, midiNoteNumber);
  21959. }
  21960. }
  21961. void MidiKeyboardState::noteOffInternal (const int midiChannel, const int midiNoteNumber)
  21962. {
  21963. if (isNoteOn (midiChannel, midiNoteNumber))
  21964. {
  21965. noteStates [midiNoteNumber] &= ~(1 << (midiChannel - 1));
  21966. for (int i = listeners.size(); --i >= 0;)
  21967. listeners.getUnchecked(i)->handleNoteOff (this, midiChannel, midiNoteNumber);
  21968. }
  21969. }
  21970. void MidiKeyboardState::allNotesOff (const int midiChannel)
  21971. {
  21972. const ScopedLock sl (lock);
  21973. if (midiChannel <= 0)
  21974. {
  21975. for (int i = 1; i <= 16; ++i)
  21976. allNotesOff (i);
  21977. }
  21978. else
  21979. {
  21980. for (int i = 0; i < 128; ++i)
  21981. noteOff (midiChannel, i);
  21982. }
  21983. }
  21984. void MidiKeyboardState::processNextMidiEvent (const MidiMessage& message)
  21985. {
  21986. if (message.isNoteOn())
  21987. {
  21988. noteOnInternal (message.getChannel(), message.getNoteNumber(), message.getFloatVelocity());
  21989. }
  21990. else if (message.isNoteOff())
  21991. {
  21992. noteOffInternal (message.getChannel(), message.getNoteNumber());
  21993. }
  21994. else if (message.isAllNotesOff())
  21995. {
  21996. for (int i = 0; i < 128; ++i)
  21997. noteOffInternal (message.getChannel(), i);
  21998. }
  21999. }
  22000. void MidiKeyboardState::processNextMidiBuffer (MidiBuffer& buffer,
  22001. const int startSample,
  22002. const int numSamples,
  22003. const bool injectIndirectEvents)
  22004. {
  22005. MidiBuffer::Iterator i (buffer);
  22006. MidiMessage message (0xf4, 0.0);
  22007. int time;
  22008. const ScopedLock sl (lock);
  22009. while (i.getNextEvent (message, time))
  22010. processNextMidiEvent (message);
  22011. if (injectIndirectEvents)
  22012. {
  22013. MidiBuffer::Iterator i2 (eventsToAdd);
  22014. const int firstEventToAdd = eventsToAdd.getFirstEventTime();
  22015. const double scaleFactor = numSamples / (double) (eventsToAdd.getLastEventTime() + 1 - firstEventToAdd);
  22016. while (i2.getNextEvent (message, time))
  22017. {
  22018. const int pos = jlimit (0, numSamples - 1, roundToInt ((time - firstEventToAdd) * scaleFactor));
  22019. buffer.addEvent (message, startSample + pos);
  22020. }
  22021. }
  22022. eventsToAdd.clear();
  22023. }
  22024. void MidiKeyboardState::addListener (MidiKeyboardStateListener* const listener) throw()
  22025. {
  22026. const ScopedLock sl (lock);
  22027. listeners.addIfNotAlreadyThere (listener);
  22028. }
  22029. void MidiKeyboardState::removeListener (MidiKeyboardStateListener* const listener) throw()
  22030. {
  22031. const ScopedLock sl (lock);
  22032. listeners.removeValue (listener);
  22033. }
  22034. END_JUCE_NAMESPACE
  22035. /*** End of inlined file: juce_MidiKeyboardState.cpp ***/
  22036. /*** Start of inlined file: juce_MidiMessage.cpp ***/
  22037. BEGIN_JUCE_NAMESPACE
  22038. int MidiMessage::readVariableLengthVal (const uint8* data,
  22039. int& numBytesUsed) throw()
  22040. {
  22041. numBytesUsed = 0;
  22042. int v = 0;
  22043. int i;
  22044. do
  22045. {
  22046. i = (int) *data++;
  22047. if (++numBytesUsed > 6)
  22048. break;
  22049. v = (v << 7) + (i & 0x7f);
  22050. } while (i & 0x80);
  22051. return v;
  22052. }
  22053. int MidiMessage::getMessageLengthFromFirstByte (const uint8 firstByte) throw()
  22054. {
  22055. // this method only works for valid starting bytes of a short midi message
  22056. jassert (firstByte >= 0x80
  22057. && firstByte != 0xf0
  22058. && firstByte != 0xf7);
  22059. static const char messageLengths[] =
  22060. {
  22061. 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
  22062. 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
  22063. 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
  22064. 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
  22065. 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
  22066. 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
  22067. 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
  22068. 1, 2, 3, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1
  22069. };
  22070. return messageLengths [firstByte & 0x7f];
  22071. }
  22072. MidiMessage::MidiMessage (const void* const d, const int dataSize, const double t)
  22073. : timeStamp (t),
  22074. size (dataSize)
  22075. {
  22076. jassert (dataSize > 0);
  22077. if (dataSize <= 4)
  22078. data = static_cast<uint8*> (preallocatedData.asBytes);
  22079. else
  22080. data = new uint8 [dataSize];
  22081. memcpy (data, d, dataSize);
  22082. // check that the length matches the data..
  22083. jassert (size > 3 || data[0] >= 0xf0 || getMessageLengthFromFirstByte (data[0]) == size);
  22084. }
  22085. MidiMessage::MidiMessage (const int byte1, const double t) throw()
  22086. : timeStamp (t),
  22087. data (static_cast<uint8*> (preallocatedData.asBytes)),
  22088. size (1)
  22089. {
  22090. data[0] = (uint8) byte1;
  22091. // check that the length matches the data..
  22092. jassert (byte1 >= 0xf0 || getMessageLengthFromFirstByte ((uint8) byte1) == 1);
  22093. }
  22094. MidiMessage::MidiMessage (const int byte1, const int byte2, const double t) throw()
  22095. : timeStamp (t),
  22096. data (static_cast<uint8*> (preallocatedData.asBytes)),
  22097. size (2)
  22098. {
  22099. data[0] = (uint8) byte1;
  22100. data[1] = (uint8) byte2;
  22101. // check that the length matches the data..
  22102. jassert (byte1 >= 0xf0 || getMessageLengthFromFirstByte ((uint8) byte1) == 2);
  22103. }
  22104. MidiMessage::MidiMessage (const int byte1, const int byte2, const int byte3, const double t) throw()
  22105. : timeStamp (t),
  22106. data (static_cast<uint8*> (preallocatedData.asBytes)),
  22107. size (3)
  22108. {
  22109. data[0] = (uint8) byte1;
  22110. data[1] = (uint8) byte2;
  22111. data[2] = (uint8) byte3;
  22112. // check that the length matches the data..
  22113. jassert (byte1 >= 0xf0 || getMessageLengthFromFirstByte ((uint8) byte1) == 3);
  22114. }
  22115. MidiMessage::MidiMessage (const MidiMessage& other)
  22116. : timeStamp (other.timeStamp),
  22117. size (other.size)
  22118. {
  22119. if (other.data != static_cast <const uint8*> (other.preallocatedData.asBytes))
  22120. {
  22121. data = new uint8 [size];
  22122. memcpy (data, other.data, size);
  22123. }
  22124. else
  22125. {
  22126. data = static_cast<uint8*> (preallocatedData.asBytes);
  22127. preallocatedData.asInt32 = other.preallocatedData.asInt32;
  22128. }
  22129. }
  22130. MidiMessage::MidiMessage (const MidiMessage& other, const double newTimeStamp)
  22131. : timeStamp (newTimeStamp),
  22132. size (other.size)
  22133. {
  22134. if (other.data != static_cast <const uint8*> (other.preallocatedData.asBytes))
  22135. {
  22136. data = new uint8 [size];
  22137. memcpy (data, other.data, size);
  22138. }
  22139. else
  22140. {
  22141. data = static_cast<uint8*> (preallocatedData.asBytes);
  22142. preallocatedData.asInt32 = other.preallocatedData.asInt32;
  22143. }
  22144. }
  22145. MidiMessage::MidiMessage (const void* src_, int sz, int& numBytesUsed, const uint8 lastStatusByte, double t)
  22146. : timeStamp (t),
  22147. data (static_cast<uint8*> (preallocatedData.asBytes))
  22148. {
  22149. const uint8* src = static_cast <const uint8*> (src_);
  22150. unsigned int byte = (unsigned int) *src;
  22151. if (byte < 0x80)
  22152. {
  22153. byte = (unsigned int) (uint8) lastStatusByte;
  22154. numBytesUsed = -1;
  22155. }
  22156. else
  22157. {
  22158. numBytesUsed = 0;
  22159. --sz;
  22160. ++src;
  22161. }
  22162. if (byte >= 0x80)
  22163. {
  22164. if (byte == 0xf0)
  22165. {
  22166. const uint8* d = src;
  22167. while (d < src + sz)
  22168. {
  22169. if (*d >= 0x80) // stop if we hit a status byte, and don't include it in this message
  22170. {
  22171. if (*d == 0xf7) // include an 0xf7 if we hit one
  22172. ++d;
  22173. break;
  22174. }
  22175. ++d;
  22176. }
  22177. size = 1 + (int) (d - src);
  22178. data = new uint8 [size];
  22179. *data = (uint8) byte;
  22180. memcpy (data + 1, src, size - 1);
  22181. }
  22182. else if (byte == 0xff)
  22183. {
  22184. int n;
  22185. const int bytesLeft = readVariableLengthVal (src + 1, n);
  22186. size = jmin (sz + 1, n + 2 + bytesLeft);
  22187. data = new uint8 [size];
  22188. *data = (uint8) byte;
  22189. memcpy (data + 1, src, size - 1);
  22190. }
  22191. else
  22192. {
  22193. preallocatedData.asInt32 = 0;
  22194. size = getMessageLengthFromFirstByte ((uint8) byte);
  22195. data[0] = (uint8) byte;
  22196. if (size > 1)
  22197. {
  22198. data[1] = src[0];
  22199. if (size > 2)
  22200. data[2] = src[1];
  22201. }
  22202. }
  22203. numBytesUsed += size;
  22204. }
  22205. else
  22206. {
  22207. preallocatedData.asInt32 = 0;
  22208. size = 0;
  22209. }
  22210. }
  22211. MidiMessage& MidiMessage::operator= (const MidiMessage& other)
  22212. {
  22213. if (this != &other)
  22214. {
  22215. timeStamp = other.timeStamp;
  22216. size = other.size;
  22217. if (data != static_cast <const uint8*> (preallocatedData.asBytes))
  22218. delete[] data;
  22219. if (other.data != static_cast <const uint8*> (other.preallocatedData.asBytes))
  22220. {
  22221. data = new uint8 [size];
  22222. memcpy (data, other.data, size);
  22223. }
  22224. else
  22225. {
  22226. data = static_cast<uint8*> (preallocatedData.asBytes);
  22227. preallocatedData.asInt32 = other.preallocatedData.asInt32;
  22228. }
  22229. }
  22230. return *this;
  22231. }
  22232. MidiMessage::~MidiMessage()
  22233. {
  22234. if (data != static_cast <const uint8*> (preallocatedData.asBytes))
  22235. delete[] data;
  22236. }
  22237. int MidiMessage::getChannel() const throw()
  22238. {
  22239. if ((data[0] & 0xf0) != 0xf0)
  22240. return (data[0] & 0xf) + 1;
  22241. else
  22242. return 0;
  22243. }
  22244. bool MidiMessage::isForChannel (const int channel) const throw()
  22245. {
  22246. jassert (channel > 0 && channel <= 16); // valid channels are numbered 1 to 16
  22247. return ((data[0] & 0xf) == channel - 1)
  22248. && ((data[0] & 0xf0) != 0xf0);
  22249. }
  22250. void MidiMessage::setChannel (const int channel) throw()
  22251. {
  22252. jassert (channel > 0 && channel <= 16); // valid channels are numbered 1 to 16
  22253. if ((data[0] & 0xf0) != (uint8) 0xf0)
  22254. data[0] = (uint8) ((data[0] & (uint8)0xf0)
  22255. | (uint8)(channel - 1));
  22256. }
  22257. bool MidiMessage::isNoteOn (const bool returnTrueForVelocity0) const throw()
  22258. {
  22259. return ((data[0] & 0xf0) == 0x90)
  22260. && (returnTrueForVelocity0 || data[2] != 0);
  22261. }
  22262. bool MidiMessage::isNoteOff (const bool returnTrueForNoteOnVelocity0) const throw()
  22263. {
  22264. return ((data[0] & 0xf0) == 0x80)
  22265. || (returnTrueForNoteOnVelocity0 && (data[2] == 0) && ((data[0] & 0xf0) == 0x90));
  22266. }
  22267. bool MidiMessage::isNoteOnOrOff() const throw()
  22268. {
  22269. const int d = data[0] & 0xf0;
  22270. return (d == 0x90) || (d == 0x80);
  22271. }
  22272. int MidiMessage::getNoteNumber() const throw()
  22273. {
  22274. return data[1];
  22275. }
  22276. void MidiMessage::setNoteNumber (const int newNoteNumber) throw()
  22277. {
  22278. if (isNoteOnOrOff())
  22279. data[1] = (uint8) jlimit (0, 127, newNoteNumber);
  22280. }
  22281. uint8 MidiMessage::getVelocity() const throw()
  22282. {
  22283. if (isNoteOnOrOff())
  22284. return data[2];
  22285. else
  22286. return 0;
  22287. }
  22288. float MidiMessage::getFloatVelocity() const throw()
  22289. {
  22290. return getVelocity() * (1.0f / 127.0f);
  22291. }
  22292. void MidiMessage::setVelocity (const float newVelocity) throw()
  22293. {
  22294. if (isNoteOnOrOff())
  22295. data[2] = (uint8) jlimit (0, 0x7f, roundToInt (newVelocity * 127.0f));
  22296. }
  22297. void MidiMessage::multiplyVelocity (const float scaleFactor) throw()
  22298. {
  22299. if (isNoteOnOrOff())
  22300. data[2] = (uint8) jlimit (0, 0x7f, roundToInt (scaleFactor * data[2]));
  22301. }
  22302. bool MidiMessage::isAftertouch() const throw()
  22303. {
  22304. return (data[0] & 0xf0) == 0xa0;
  22305. }
  22306. int MidiMessage::getAfterTouchValue() const throw()
  22307. {
  22308. return data[2];
  22309. }
  22310. const MidiMessage MidiMessage::aftertouchChange (const int channel,
  22311. const int noteNum,
  22312. const int aftertouchValue) throw()
  22313. {
  22314. jassert (channel > 0 && channel <= 16); // valid channels are numbered 1 to 16
  22315. jassert (((unsigned int) noteNum) <= 127);
  22316. jassert (((unsigned int) aftertouchValue) <= 127);
  22317. return MidiMessage (0xa0 | jlimit (0, 15, channel - 1),
  22318. noteNum & 0x7f,
  22319. aftertouchValue & 0x7f);
  22320. }
  22321. bool MidiMessage::isChannelPressure() const throw()
  22322. {
  22323. return (data[0] & 0xf0) == 0xd0;
  22324. }
  22325. int MidiMessage::getChannelPressureValue() const throw()
  22326. {
  22327. jassert (isChannelPressure());
  22328. return data[1];
  22329. }
  22330. const MidiMessage MidiMessage::channelPressureChange (const int channel,
  22331. const int pressure) throw()
  22332. {
  22333. jassert (channel > 0 && channel <= 16); // valid channels are numbered 1 to 16
  22334. jassert (((unsigned int) pressure) <= 127);
  22335. return MidiMessage (0xd0 | jlimit (0, 15, channel - 1),
  22336. pressure & 0x7f);
  22337. }
  22338. bool MidiMessage::isProgramChange() const throw()
  22339. {
  22340. return (data[0] & 0xf0) == 0xc0;
  22341. }
  22342. int MidiMessage::getProgramChangeNumber() const throw()
  22343. {
  22344. return data[1];
  22345. }
  22346. const MidiMessage MidiMessage::programChange (const int channel,
  22347. const int programNumber) throw()
  22348. {
  22349. jassert (channel > 0 && channel <= 16); // valid channels are numbered 1 to 16
  22350. return MidiMessage (0xc0 | jlimit (0, 15, channel - 1),
  22351. programNumber & 0x7f);
  22352. }
  22353. bool MidiMessage::isPitchWheel() const throw()
  22354. {
  22355. return (data[0] & 0xf0) == 0xe0;
  22356. }
  22357. int MidiMessage::getPitchWheelValue() const throw()
  22358. {
  22359. return data[1] | (data[2] << 7);
  22360. }
  22361. const MidiMessage MidiMessage::pitchWheel (const int channel,
  22362. const int position) throw()
  22363. {
  22364. jassert (channel > 0 && channel <= 16); // valid channels are numbered 1 to 16
  22365. jassert (((unsigned int) position) <= 0x3fff);
  22366. return MidiMessage (0xe0 | jlimit (0, 15, channel - 1),
  22367. position & 127,
  22368. (position >> 7) & 127);
  22369. }
  22370. bool MidiMessage::isController() const throw()
  22371. {
  22372. return (data[0] & 0xf0) == 0xb0;
  22373. }
  22374. int MidiMessage::getControllerNumber() const throw()
  22375. {
  22376. jassert (isController());
  22377. return data[1];
  22378. }
  22379. int MidiMessage::getControllerValue() const throw()
  22380. {
  22381. jassert (isController());
  22382. return data[2];
  22383. }
  22384. const MidiMessage MidiMessage::controllerEvent (const int channel,
  22385. const int controllerType,
  22386. const int value) throw()
  22387. {
  22388. // the channel must be between 1 and 16 inclusive
  22389. jassert (channel > 0 && channel <= 16);
  22390. return MidiMessage (0xb0 | jlimit (0, 15, channel - 1),
  22391. controllerType & 127,
  22392. value & 127);
  22393. }
  22394. const MidiMessage MidiMessage::noteOn (const int channel,
  22395. const int noteNumber,
  22396. const float velocity) throw()
  22397. {
  22398. return noteOn (channel, noteNumber, (uint8)(velocity * 127.0f));
  22399. }
  22400. const MidiMessage MidiMessage::noteOn (const int channel,
  22401. const int noteNumber,
  22402. const uint8 velocity) throw()
  22403. {
  22404. jassert (channel > 0 && channel <= 16);
  22405. jassert (((unsigned int) noteNumber) <= 127);
  22406. return MidiMessage (0x90 | jlimit (0, 15, channel - 1),
  22407. noteNumber & 127,
  22408. jlimit (0, 127, roundToInt (velocity)));
  22409. }
  22410. const MidiMessage MidiMessage::noteOff (const int channel,
  22411. const int noteNumber) throw()
  22412. {
  22413. jassert (channel > 0 && channel <= 16);
  22414. jassert (((unsigned int) noteNumber) <= 127);
  22415. return MidiMessage (0x80 | jlimit (0, 15, channel - 1), noteNumber & 127, 0);
  22416. }
  22417. const MidiMessage MidiMessage::allNotesOff (const int channel) throw()
  22418. {
  22419. jassert (channel > 0 && channel <= 16);
  22420. return controllerEvent (channel, 123, 0);
  22421. }
  22422. bool MidiMessage::isAllNotesOff() const throw()
  22423. {
  22424. return (data[0] & 0xf0) == 0xb0
  22425. && data[1] == 123;
  22426. }
  22427. const MidiMessage MidiMessage::allSoundOff (const int channel) throw()
  22428. {
  22429. return controllerEvent (channel, 120, 0);
  22430. }
  22431. bool MidiMessage::isAllSoundOff() const throw()
  22432. {
  22433. return (data[0] & 0xf0) == 0xb0
  22434. && data[1] == 120;
  22435. }
  22436. const MidiMessage MidiMessage::allControllersOff (const int channel) throw()
  22437. {
  22438. return controllerEvent (channel, 121, 0);
  22439. }
  22440. const MidiMessage MidiMessage::masterVolume (const float volume)
  22441. {
  22442. const int vol = jlimit (0, 0x3fff, roundToInt (volume * 0x4000));
  22443. uint8 buf[8];
  22444. buf[0] = 0xf0;
  22445. buf[1] = 0x7f;
  22446. buf[2] = 0x7f;
  22447. buf[3] = 0x04;
  22448. buf[4] = 0x01;
  22449. buf[5] = (uint8) (vol & 0x7f);
  22450. buf[6] = (uint8) (vol >> 7);
  22451. buf[7] = 0xf7;
  22452. return MidiMessage (buf, 8);
  22453. }
  22454. bool MidiMessage::isSysEx() const throw()
  22455. {
  22456. return *data == 0xf0;
  22457. }
  22458. const MidiMessage MidiMessage::createSysExMessage (const uint8* sysexData, const int dataSize)
  22459. {
  22460. MemoryBlock mm (dataSize + 2);
  22461. uint8* const m = static_cast <uint8*> (mm.getData());
  22462. m[0] = 0xf0;
  22463. memcpy (m + 1, sysexData, dataSize);
  22464. m[dataSize + 1] = 0xf7;
  22465. return MidiMessage (m, dataSize + 2);
  22466. }
  22467. const uint8* MidiMessage::getSysExData() const throw()
  22468. {
  22469. return (isSysEx()) ? getRawData() + 1 : 0;
  22470. }
  22471. int MidiMessage::getSysExDataSize() const throw()
  22472. {
  22473. return (isSysEx()) ? size - 2 : 0;
  22474. }
  22475. bool MidiMessage::isMetaEvent() const throw()
  22476. {
  22477. return *data == 0xff;
  22478. }
  22479. bool MidiMessage::isActiveSense() const throw()
  22480. {
  22481. return *data == 0xfe;
  22482. }
  22483. int MidiMessage::getMetaEventType() const throw()
  22484. {
  22485. if (*data != 0xff)
  22486. return -1;
  22487. else
  22488. return data[1];
  22489. }
  22490. int MidiMessage::getMetaEventLength() const throw()
  22491. {
  22492. if (*data == 0xff)
  22493. {
  22494. int n;
  22495. return jmin (size - 2, readVariableLengthVal (data + 2, n));
  22496. }
  22497. return 0;
  22498. }
  22499. const uint8* MidiMessage::getMetaEventData() const throw()
  22500. {
  22501. int n;
  22502. const uint8* d = data + 2;
  22503. readVariableLengthVal (d, n);
  22504. return d + n;
  22505. }
  22506. bool MidiMessage::isTrackMetaEvent() const throw()
  22507. {
  22508. return getMetaEventType() == 0;
  22509. }
  22510. bool MidiMessage::isEndOfTrackMetaEvent() const throw()
  22511. {
  22512. return getMetaEventType() == 47;
  22513. }
  22514. bool MidiMessage::isTextMetaEvent() const throw()
  22515. {
  22516. const int t = getMetaEventType();
  22517. return t > 0 && t < 16;
  22518. }
  22519. const String MidiMessage::getTextFromTextMetaEvent() const
  22520. {
  22521. return String (reinterpret_cast <const char*> (getMetaEventData()), getMetaEventLength());
  22522. }
  22523. bool MidiMessage::isTrackNameEvent() const throw()
  22524. {
  22525. return (data[1] == 3)
  22526. && (*data == 0xff);
  22527. }
  22528. bool MidiMessage::isTempoMetaEvent() const throw()
  22529. {
  22530. return (data[1] == 81)
  22531. && (*data == 0xff);
  22532. }
  22533. bool MidiMessage::isMidiChannelMetaEvent() const throw()
  22534. {
  22535. return (data[1] == 0x20)
  22536. && (*data == 0xff)
  22537. && (data[2] == 1);
  22538. }
  22539. int MidiMessage::getMidiChannelMetaEventChannel() const throw()
  22540. {
  22541. return data[3] + 1;
  22542. }
  22543. double MidiMessage::getTempoSecondsPerQuarterNote() const throw()
  22544. {
  22545. if (! isTempoMetaEvent())
  22546. return 0.0;
  22547. const uint8* const d = getMetaEventData();
  22548. return (((unsigned int) d[0] << 16)
  22549. | ((unsigned int) d[1] << 8)
  22550. | d[2])
  22551. / 1000000.0;
  22552. }
  22553. double MidiMessage::getTempoMetaEventTickLength (const short timeFormat) const throw()
  22554. {
  22555. if (timeFormat > 0)
  22556. {
  22557. if (! isTempoMetaEvent())
  22558. return 0.5 / timeFormat;
  22559. return getTempoSecondsPerQuarterNote() / timeFormat;
  22560. }
  22561. else
  22562. {
  22563. const int frameCode = (-timeFormat) >> 8;
  22564. double framesPerSecond;
  22565. switch (frameCode)
  22566. {
  22567. case 24: framesPerSecond = 24.0; break;
  22568. case 25: framesPerSecond = 25.0; break;
  22569. case 29: framesPerSecond = 29.97; break;
  22570. case 30: framesPerSecond = 30.0; break;
  22571. default: framesPerSecond = 30.0; break;
  22572. }
  22573. return (1.0 / framesPerSecond) / (timeFormat & 0xff);
  22574. }
  22575. }
  22576. const MidiMessage MidiMessage::tempoMetaEvent (int microsecondsPerQuarterNote) throw()
  22577. {
  22578. uint8 d[8];
  22579. d[0] = 0xff;
  22580. d[1] = 81;
  22581. d[2] = 3;
  22582. d[3] = (uint8) (microsecondsPerQuarterNote >> 16);
  22583. d[4] = (uint8) ((microsecondsPerQuarterNote >> 8) & 0xff);
  22584. d[5] = (uint8) (microsecondsPerQuarterNote & 0xff);
  22585. return MidiMessage (d, 6, 0.0);
  22586. }
  22587. bool MidiMessage::isTimeSignatureMetaEvent() const throw()
  22588. {
  22589. return (data[1] == 0x58)
  22590. && (*data == (uint8) 0xff);
  22591. }
  22592. void MidiMessage::getTimeSignatureInfo (int& numerator, int& denominator) const throw()
  22593. {
  22594. if (isTimeSignatureMetaEvent())
  22595. {
  22596. const uint8* const d = getMetaEventData();
  22597. numerator = d[0];
  22598. denominator = 1 << d[1];
  22599. }
  22600. else
  22601. {
  22602. numerator = 4;
  22603. denominator = 4;
  22604. }
  22605. }
  22606. const MidiMessage MidiMessage::timeSignatureMetaEvent (const int numerator, const int denominator)
  22607. {
  22608. uint8 d[8];
  22609. d[0] = 0xff;
  22610. d[1] = 0x58;
  22611. d[2] = 0x04;
  22612. d[3] = (uint8) numerator;
  22613. int n = 1;
  22614. int powerOfTwo = 0;
  22615. while (n < denominator)
  22616. {
  22617. n <<= 1;
  22618. ++powerOfTwo;
  22619. }
  22620. d[4] = (uint8) powerOfTwo;
  22621. d[5] = 0x01;
  22622. d[6] = 96;
  22623. return MidiMessage (d, 7, 0.0);
  22624. }
  22625. const MidiMessage MidiMessage::midiChannelMetaEvent (const int channel) throw()
  22626. {
  22627. uint8 d[8];
  22628. d[0] = 0xff;
  22629. d[1] = 0x20;
  22630. d[2] = 0x01;
  22631. d[3] = (uint8) jlimit (0, 0xff, channel - 1);
  22632. return MidiMessage (d, 4, 0.0);
  22633. }
  22634. bool MidiMessage::isKeySignatureMetaEvent() const throw()
  22635. {
  22636. return getMetaEventType() == 89;
  22637. }
  22638. int MidiMessage::getKeySignatureNumberOfSharpsOrFlats() const throw()
  22639. {
  22640. return (int) *getMetaEventData();
  22641. }
  22642. const MidiMessage MidiMessage::endOfTrack() throw()
  22643. {
  22644. return MidiMessage (0xff, 0x2f, 0, 0.0);
  22645. }
  22646. bool MidiMessage::isSongPositionPointer() const throw()
  22647. {
  22648. return *data == 0xf2;
  22649. }
  22650. int MidiMessage::getSongPositionPointerMidiBeat() const throw()
  22651. {
  22652. return data[1] | (data[2] << 7);
  22653. }
  22654. const MidiMessage MidiMessage::songPositionPointer (const int positionInMidiBeats) throw()
  22655. {
  22656. return MidiMessage (0xf2,
  22657. positionInMidiBeats & 127,
  22658. (positionInMidiBeats >> 7) & 127);
  22659. }
  22660. bool MidiMessage::isMidiStart() const throw()
  22661. {
  22662. return *data == 0xfa;
  22663. }
  22664. const MidiMessage MidiMessage::midiStart() throw()
  22665. {
  22666. return MidiMessage (0xfa);
  22667. }
  22668. bool MidiMessage::isMidiContinue() const throw()
  22669. {
  22670. return *data == 0xfb;
  22671. }
  22672. const MidiMessage MidiMessage::midiContinue() throw()
  22673. {
  22674. return MidiMessage (0xfb);
  22675. }
  22676. bool MidiMessage::isMidiStop() const throw()
  22677. {
  22678. return *data == 0xfc;
  22679. }
  22680. const MidiMessage MidiMessage::midiStop() throw()
  22681. {
  22682. return MidiMessage (0xfc);
  22683. }
  22684. bool MidiMessage::isMidiClock() const throw()
  22685. {
  22686. return *data == 0xf8;
  22687. }
  22688. const MidiMessage MidiMessage::midiClock() throw()
  22689. {
  22690. return MidiMessage (0xf8);
  22691. }
  22692. bool MidiMessage::isQuarterFrame() const throw()
  22693. {
  22694. return *data == 0xf1;
  22695. }
  22696. int MidiMessage::getQuarterFrameSequenceNumber() const throw()
  22697. {
  22698. return ((int) data[1]) >> 4;
  22699. }
  22700. int MidiMessage::getQuarterFrameValue() const throw()
  22701. {
  22702. return ((int) data[1]) & 0x0f;
  22703. }
  22704. const MidiMessage MidiMessage::quarterFrame (const int sequenceNumber,
  22705. const int value) throw()
  22706. {
  22707. return MidiMessage (0xf1, (sequenceNumber << 4) | value);
  22708. }
  22709. bool MidiMessage::isFullFrame() const throw()
  22710. {
  22711. return data[0] == 0xf0
  22712. && data[1] == 0x7f
  22713. && size >= 10
  22714. && data[3] == 0x01
  22715. && data[4] == 0x01;
  22716. }
  22717. void MidiMessage::getFullFrameParameters (int& hours,
  22718. int& minutes,
  22719. int& seconds,
  22720. int& frames,
  22721. MidiMessage::SmpteTimecodeType& timecodeType) const throw()
  22722. {
  22723. jassert (isFullFrame());
  22724. timecodeType = (SmpteTimecodeType) (data[5] >> 5);
  22725. hours = data[5] & 0x1f;
  22726. minutes = data[6];
  22727. seconds = data[7];
  22728. frames = data[8];
  22729. }
  22730. const MidiMessage MidiMessage::fullFrame (const int hours,
  22731. const int minutes,
  22732. const int seconds,
  22733. const int frames,
  22734. MidiMessage::SmpteTimecodeType timecodeType)
  22735. {
  22736. uint8 d[10];
  22737. d[0] = 0xf0;
  22738. d[1] = 0x7f;
  22739. d[2] = 0x7f;
  22740. d[3] = 0x01;
  22741. d[4] = 0x01;
  22742. d[5] = (uint8) ((hours & 0x01f) | (timecodeType << 5));
  22743. d[6] = (uint8) minutes;
  22744. d[7] = (uint8) seconds;
  22745. d[8] = (uint8) frames;
  22746. d[9] = 0xf7;
  22747. return MidiMessage (d, 10, 0.0);
  22748. }
  22749. bool MidiMessage::isMidiMachineControlMessage() const throw()
  22750. {
  22751. return data[0] == 0xf0
  22752. && data[1] == 0x7f
  22753. && data[3] == 0x06
  22754. && size > 5;
  22755. }
  22756. MidiMessage::MidiMachineControlCommand MidiMessage::getMidiMachineControlCommand() const throw()
  22757. {
  22758. jassert (isMidiMachineControlMessage());
  22759. return (MidiMachineControlCommand) data[4];
  22760. }
  22761. const MidiMessage MidiMessage::midiMachineControlCommand (MidiMessage::MidiMachineControlCommand command)
  22762. {
  22763. uint8 d[6];
  22764. d[0] = 0xf0;
  22765. d[1] = 0x7f;
  22766. d[2] = 0x00;
  22767. d[3] = 0x06;
  22768. d[4] = (uint8) command;
  22769. d[5] = 0xf7;
  22770. return MidiMessage (d, 6, 0.0);
  22771. }
  22772. bool MidiMessage::isMidiMachineControlGoto (int& hours,
  22773. int& minutes,
  22774. int& seconds,
  22775. int& frames) const throw()
  22776. {
  22777. if (size >= 12
  22778. && data[0] == 0xf0
  22779. && data[1] == 0x7f
  22780. && data[3] == 0x06
  22781. && data[4] == 0x44
  22782. && data[5] == 0x06
  22783. && data[6] == 0x01)
  22784. {
  22785. hours = data[7] % 24; // (that some machines send out hours > 24)
  22786. minutes = data[8];
  22787. seconds = data[9];
  22788. frames = data[10];
  22789. return true;
  22790. }
  22791. return false;
  22792. }
  22793. const MidiMessage MidiMessage::midiMachineControlGoto (int hours,
  22794. int minutes,
  22795. int seconds,
  22796. int frames)
  22797. {
  22798. uint8 d[12];
  22799. d[0] = 0xf0;
  22800. d[1] = 0x7f;
  22801. d[2] = 0x00;
  22802. d[3] = 0x06;
  22803. d[4] = 0x44;
  22804. d[5] = 0x06;
  22805. d[6] = 0x01;
  22806. d[7] = (uint8) hours;
  22807. d[8] = (uint8) minutes;
  22808. d[9] = (uint8) seconds;
  22809. d[10] = (uint8) frames;
  22810. d[11] = 0xf7;
  22811. return MidiMessage (d, 12, 0.0);
  22812. }
  22813. const String MidiMessage::getMidiNoteName (int note,
  22814. bool useSharps,
  22815. bool includeOctaveNumber,
  22816. int octaveNumForMiddleC) throw()
  22817. {
  22818. static const char* const sharpNoteNames[] = { "C", "C#", "D", "D#", "E",
  22819. "F", "F#", "G", "G#", "A",
  22820. "A#", "B" };
  22821. static const char* const flatNoteNames[] = { "C", "Db", "D", "Eb", "E",
  22822. "F", "Gb", "G", "Ab", "A",
  22823. "Bb", "B" };
  22824. if (((unsigned int) note) < 128)
  22825. {
  22826. const String s ((useSharps) ? sharpNoteNames [note % 12]
  22827. : flatNoteNames [note % 12]);
  22828. if (includeOctaveNumber)
  22829. return s + String (note / 12 + (octaveNumForMiddleC - 5));
  22830. else
  22831. return s;
  22832. }
  22833. return String::empty;
  22834. }
  22835. const double MidiMessage::getMidiNoteInHertz (int noteNumber) throw()
  22836. {
  22837. noteNumber -= 12 * 6 + 9; // now 0 = A440
  22838. return 440.0 * pow (2.0, noteNumber / 12.0);
  22839. }
  22840. const String MidiMessage::getGMInstrumentName (int n) throw()
  22841. {
  22842. const char *names[] =
  22843. {
  22844. "Acoustic Grand Piano", "Bright Acoustic Piano", "Electric Grand Piano", "Honky-tonk Piano",
  22845. "Electric Piano 1", "Electric Piano 2", "Harpsichord", "Clavinet", "Celesta", "Glockenspiel",
  22846. "Music Box", "Vibraphone", "Marimba", "Xylophone", "Tubular Bells", "Dulcimer", "Drawbar Organ",
  22847. "Percussive Organ", "Rock Organ", "Church Organ", "Reed Organ", "Accordion", "Harmonica",
  22848. "Tango Accordion", "Acoustic Guitar (nylon)", "Acoustic Guitar (steel)", "Electric Guitar (jazz)",
  22849. "Electric Guitar (clean)", "Electric Guitar (mute)", "Overdriven Guitar", "Distortion Guitar",
  22850. "Guitar Harmonics", "Acoustic Bass", "Electric Bass (finger)", "Electric Bass (pick)",
  22851. "Fretless Bass", "Slap Bass 1", "Slap Bass 2", "Synth Bass 1", "Synth Bass 2", "Violin",
  22852. "Viola", "Cello", "Contrabass", "Tremolo Strings", "Pizzicato Strings", "Orchestral Harp",
  22853. "Timpani", "String Ensemble 1", "String Ensemble 2", "SynthStrings 1", "SynthStrings 2",
  22854. "Choir Aahs", "Voice Oohs", "Synth Voice", "Orchestra Hit", "Trumpet", "Trombone", "Tuba",
  22855. "Muted Trumpet", "French Horn", "Brass Section", "SynthBrass 1", "SynthBrass 2", "Soprano Sax",
  22856. "Alto Sax", "Tenor Sax", "Baritone Sax", "Oboe", "English Horn", "Bassoon", "Clarinet",
  22857. "Piccolo", "Flute", "Recorder", "Pan Flute", "Blown Bottle", "Shakuhachi", "Whistle",
  22858. "Ocarina", "Lead 1 (square)", "Lead 2 (sawtooth)", "Lead 3 (calliope)", "Lead 4 (chiff)",
  22859. "Lead 5 (charang)", "Lead 6 (voice)", "Lead 7 (fifths)", "Lead 8 (bass+lead)", "Pad 1 (new age)",
  22860. "Pad 2 (warm)", "Pad 3 (polysynth)", "Pad 4 (choir)", "Pad 5 (bowed)", "Pad 6 (metallic)",
  22861. "Pad 7 (halo)", "Pad 8 (sweep)", "FX 1 (rain)", "FX 2 (soundtrack)", "FX 3 (crystal)",
  22862. "FX 4 (atmosphere)", "FX 5 (brightness)", "FX 6 (goblins)", "FX 7 (echoes)", "FX 8 (sci-fi)",
  22863. "Sitar", "Banjo", "Shamisen", "Koto", "Kalimba", "Bag pipe", "Fiddle", "Shanai", "Tinkle Bell",
  22864. "Agogo", "Steel Drums", "Woodblock", "Taiko Drum", "Melodic Tom", "Synth Drum", "Reverse Cymbal",
  22865. "Guitar Fret Noise", "Breath Noise", "Seashore", "Bird Tweet", "Telephone Ring", "Helicopter",
  22866. "Applause", "Gunshot"
  22867. };
  22868. return (((unsigned int) n) < 128) ? names[n]
  22869. : (const char*)0;
  22870. }
  22871. const String MidiMessage::getGMInstrumentBankName (int n) throw()
  22872. {
  22873. const char* names[] =
  22874. {
  22875. "Piano", "Chromatic Percussion", "Organ", "Guitar",
  22876. "Bass", "Strings", "Ensemble", "Brass",
  22877. "Reed", "Pipe", "Synth Lead", "Synth Pad",
  22878. "Synth Effects", "Ethnic", "Percussive", "Sound Effects"
  22879. };
  22880. return (((unsigned int) n) <= 15) ? names[n]
  22881. : (const char*)0;
  22882. }
  22883. const String MidiMessage::getRhythmInstrumentName (int n) throw()
  22884. {
  22885. const char* names[] =
  22886. {
  22887. "Acoustic Bass Drum", "Bass Drum 1", "Side Stick", "Acoustic Snare",
  22888. "Hand Clap", "Electric Snare", "Low Floor Tom", "Closed Hi-Hat", "High Floor Tom",
  22889. "Pedal Hi-Hat", "Low Tom", "Open Hi-Hat", "Low-Mid Tom", "Hi-Mid Tom", "Crash Cymbal 1",
  22890. "High Tom", "Ride Cymbal 1", "Chinese Cymbal", "Ride Bell", "Tambourine", "Splash Cymbal",
  22891. "Cowbell", "Crash Cymbal 2", "Vibraslap", "Ride Cymbal 2", "Hi Bongo", "Low Bongo",
  22892. "Mute Hi Conga", "Open Hi Conga", "Low Conga", "High Timbale", "Low Timbale", "High Agogo",
  22893. "Low Agogo", "Cabasa", "Maracas", "Short Whistle", "Long Whistle", "Short Guiro",
  22894. "Long Guiro", "Claves", "Hi Wood Block", "Low Wood Block", "Mute Cuica", "Open Cuica",
  22895. "Mute Triangle", "Open Triangle"
  22896. };
  22897. return (n >= 35 && n <= 81) ? names [n - 35]
  22898. : (const char*)0;
  22899. }
  22900. const String MidiMessage::getControllerName (int n) throw()
  22901. {
  22902. const char* names[] =
  22903. {
  22904. "Bank Select", "Modulation Wheel (coarse)", "Breath controller (coarse)",
  22905. 0, "Foot Pedal (coarse)", "Portamento Time (coarse)",
  22906. "Data Entry (coarse)", "Volume (coarse)", "Balance (coarse)",
  22907. 0, "Pan position (coarse)", "Expression (coarse)", "Effect Control 1 (coarse)",
  22908. "Effect Control 2 (coarse)", 0, 0, "General Purpose Slider 1", "General Purpose Slider 2",
  22909. "General Purpose Slider 3", "General Purpose Slider 4", 0, 0, 0, 0, 0, 0, 0, 0,
  22910. 0, 0, 0, 0, "Bank Select (fine)", "Modulation Wheel (fine)", "Breath controller (fine)",
  22911. 0, "Foot Pedal (fine)", "Portamento Time (fine)", "Data Entry (fine)", "Volume (fine)",
  22912. "Balance (fine)", 0, "Pan position (fine)", "Expression (fine)", "Effect Control 1 (fine)",
  22913. "Effect Control 2 (fine)", 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  22914. "Hold Pedal (on/off)", "Portamento (on/off)", "Sustenuto Pedal (on/off)", "Soft Pedal (on/off)",
  22915. "Legato Pedal (on/off)", "Hold 2 Pedal (on/off)", "Sound Variation", "Sound Timbre",
  22916. "Sound Release Time", "Sound Attack Time", "Sound Brightness", "Sound Control 6",
  22917. "Sound Control 7", "Sound Control 8", "Sound Control 9", "Sound Control 10",
  22918. "General Purpose Button 1 (on/off)", "General Purpose Button 2 (on/off)",
  22919. "General Purpose Button 3 (on/off)", "General Purpose Button 4 (on/off)",
  22920. 0, 0, 0, 0, 0, 0, 0, "Reverb Level", "Tremolo Level", "Chorus Level", "Celeste Level",
  22921. "Phaser Level", "Data Button increment", "Data Button decrement", "Non-registered Parameter (fine)",
  22922. "Non-registered Parameter (coarse)", "Registered Parameter (fine)", "Registered Parameter (coarse)",
  22923. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, "All Sound Off", "All Controllers Off",
  22924. "Local Keyboard (on/off)", "All Notes Off", "Omni Mode Off", "Omni Mode On", "Mono Operation",
  22925. "Poly Operation"
  22926. };
  22927. return (((unsigned int) n) < 128) ? names[n]
  22928. : (const char*)0;
  22929. }
  22930. END_JUCE_NAMESPACE
  22931. /*** End of inlined file: juce_MidiMessage.cpp ***/
  22932. /*** Start of inlined file: juce_MidiMessageCollector.cpp ***/
  22933. BEGIN_JUCE_NAMESPACE
  22934. MidiMessageCollector::MidiMessageCollector()
  22935. : lastCallbackTime (0),
  22936. sampleRate (44100.0001)
  22937. {
  22938. }
  22939. MidiMessageCollector::~MidiMessageCollector()
  22940. {
  22941. }
  22942. void MidiMessageCollector::reset (const double sampleRate_)
  22943. {
  22944. jassert (sampleRate_ > 0);
  22945. const ScopedLock sl (midiCallbackLock);
  22946. sampleRate = sampleRate_;
  22947. incomingMessages.clear();
  22948. lastCallbackTime = Time::getMillisecondCounterHiRes();
  22949. }
  22950. void MidiMessageCollector::addMessageToQueue (const MidiMessage& message)
  22951. {
  22952. // you need to call reset() to set the correct sample rate before using this object
  22953. jassert (sampleRate != 44100.0001);
  22954. // the messages that come in here need to be time-stamped correctly - see MidiInput
  22955. // for details of what the number should be.
  22956. jassert (message.getTimeStamp() != 0);
  22957. const ScopedLock sl (midiCallbackLock);
  22958. const int sampleNumber
  22959. = (int) ((message.getTimeStamp() - 0.001 * lastCallbackTime) * sampleRate);
  22960. incomingMessages.addEvent (message, sampleNumber);
  22961. // if the messages don't get used for over a second, we'd better
  22962. // get rid of any old ones to avoid the queue getting too big
  22963. if (sampleNumber > sampleRate)
  22964. incomingMessages.clear (0, sampleNumber - (int) sampleRate);
  22965. }
  22966. void MidiMessageCollector::removeNextBlockOfMessages (MidiBuffer& destBuffer,
  22967. const int numSamples)
  22968. {
  22969. // you need to call reset() to set the correct sample rate before using this object
  22970. jassert (sampleRate != 44100.0001);
  22971. const double timeNow = Time::getMillisecondCounterHiRes();
  22972. const double msElapsed = timeNow - lastCallbackTime;
  22973. const ScopedLock sl (midiCallbackLock);
  22974. lastCallbackTime = timeNow;
  22975. if (! incomingMessages.isEmpty())
  22976. {
  22977. int numSourceSamples = jmax (1, roundToInt (msElapsed * 0.001 * sampleRate));
  22978. int startSample = 0;
  22979. int scale = 1 << 16;
  22980. const uint8* midiData;
  22981. int numBytes, samplePosition;
  22982. MidiBuffer::Iterator iter (incomingMessages);
  22983. if (numSourceSamples > numSamples)
  22984. {
  22985. // if our list of events is longer than the buffer we're being
  22986. // asked for, scale them down to squeeze them all in..
  22987. const int maxBlockLengthToUse = numSamples << 5;
  22988. if (numSourceSamples > maxBlockLengthToUse)
  22989. {
  22990. startSample = numSourceSamples - maxBlockLengthToUse;
  22991. numSourceSamples = maxBlockLengthToUse;
  22992. iter.setNextSamplePosition (startSample);
  22993. }
  22994. scale = (numSamples << 10) / numSourceSamples;
  22995. while (iter.getNextEvent (midiData, numBytes, samplePosition))
  22996. {
  22997. samplePosition = ((samplePosition - startSample) * scale) >> 10;
  22998. destBuffer.addEvent (midiData, numBytes,
  22999. jlimit (0, numSamples - 1, samplePosition));
  23000. }
  23001. }
  23002. else
  23003. {
  23004. // if our event list is shorter than the number we need, put them
  23005. // towards the end of the buffer
  23006. startSample = numSamples - numSourceSamples;
  23007. while (iter.getNextEvent (midiData, numBytes, samplePosition))
  23008. {
  23009. destBuffer.addEvent (midiData, numBytes,
  23010. jlimit (0, numSamples - 1, samplePosition + startSample));
  23011. }
  23012. }
  23013. incomingMessages.clear();
  23014. }
  23015. }
  23016. void MidiMessageCollector::handleNoteOn (MidiKeyboardState*, int midiChannel, int midiNoteNumber, float velocity)
  23017. {
  23018. MidiMessage m (MidiMessage::noteOn (midiChannel, midiNoteNumber, velocity));
  23019. m.setTimeStamp (Time::getMillisecondCounterHiRes() * 0.001);
  23020. addMessageToQueue (m);
  23021. }
  23022. void MidiMessageCollector::handleNoteOff (MidiKeyboardState*, int midiChannel, int midiNoteNumber)
  23023. {
  23024. MidiMessage m (MidiMessage::noteOff (midiChannel, midiNoteNumber));
  23025. m.setTimeStamp (Time::getMillisecondCounterHiRes() * 0.001);
  23026. addMessageToQueue (m);
  23027. }
  23028. void MidiMessageCollector::handleIncomingMidiMessage (MidiInput*, const MidiMessage& message)
  23029. {
  23030. addMessageToQueue (message);
  23031. }
  23032. END_JUCE_NAMESPACE
  23033. /*** End of inlined file: juce_MidiMessageCollector.cpp ***/
  23034. /*** Start of inlined file: juce_MidiMessageSequence.cpp ***/
  23035. BEGIN_JUCE_NAMESPACE
  23036. MidiMessageSequence::MidiMessageSequence()
  23037. {
  23038. }
  23039. MidiMessageSequence::MidiMessageSequence (const MidiMessageSequence& other)
  23040. {
  23041. list.ensureStorageAllocated (other.list.size());
  23042. for (int i = 0; i < other.list.size(); ++i)
  23043. list.add (new MidiEventHolder (other.list.getUnchecked(i)->message));
  23044. }
  23045. MidiMessageSequence& MidiMessageSequence::operator= (const MidiMessageSequence& other)
  23046. {
  23047. MidiMessageSequence otherCopy (other);
  23048. swapWith (otherCopy);
  23049. return *this;
  23050. }
  23051. void MidiMessageSequence::swapWith (MidiMessageSequence& other) throw()
  23052. {
  23053. list.swapWithArray (other.list);
  23054. }
  23055. MidiMessageSequence::~MidiMessageSequence()
  23056. {
  23057. }
  23058. void MidiMessageSequence::clear()
  23059. {
  23060. list.clear();
  23061. }
  23062. int MidiMessageSequence::getNumEvents() const
  23063. {
  23064. return list.size();
  23065. }
  23066. MidiMessageSequence::MidiEventHolder* MidiMessageSequence::getEventPointer (const int index) const
  23067. {
  23068. return list [index];
  23069. }
  23070. double MidiMessageSequence::getTimeOfMatchingKeyUp (const int index) const
  23071. {
  23072. const MidiEventHolder* const meh = list [index];
  23073. if (meh != 0 && meh->noteOffObject != 0)
  23074. return meh->noteOffObject->message.getTimeStamp();
  23075. else
  23076. return 0.0;
  23077. }
  23078. int MidiMessageSequence::getIndexOfMatchingKeyUp (const int index) const
  23079. {
  23080. const MidiEventHolder* const meh = list [index];
  23081. return (meh != 0) ? list.indexOf (meh->noteOffObject) : -1;
  23082. }
  23083. int MidiMessageSequence::getIndexOf (MidiEventHolder* const event) const
  23084. {
  23085. return list.indexOf (event);
  23086. }
  23087. int MidiMessageSequence::getNextIndexAtTime (const double timeStamp) const
  23088. {
  23089. const int numEvents = list.size();
  23090. int i;
  23091. for (i = 0; i < numEvents; ++i)
  23092. if (list.getUnchecked(i)->message.getTimeStamp() >= timeStamp)
  23093. break;
  23094. return i;
  23095. }
  23096. double MidiMessageSequence::getStartTime() const
  23097. {
  23098. if (list.size() > 0)
  23099. return list.getUnchecked(0)->message.getTimeStamp();
  23100. else
  23101. return 0;
  23102. }
  23103. double MidiMessageSequence::getEndTime() const
  23104. {
  23105. if (list.size() > 0)
  23106. return list.getLast()->message.getTimeStamp();
  23107. else
  23108. return 0;
  23109. }
  23110. double MidiMessageSequence::getEventTime (const int index) const
  23111. {
  23112. if (((unsigned int) index) < (unsigned int) list.size())
  23113. return list.getUnchecked (index)->message.getTimeStamp();
  23114. return 0.0;
  23115. }
  23116. void MidiMessageSequence::addEvent (const MidiMessage& newMessage,
  23117. double timeAdjustment)
  23118. {
  23119. MidiEventHolder* const newOne = new MidiEventHolder (newMessage);
  23120. timeAdjustment += newMessage.getTimeStamp();
  23121. newOne->message.setTimeStamp (timeAdjustment);
  23122. int i;
  23123. for (i = list.size(); --i >= 0;)
  23124. if (list.getUnchecked(i)->message.getTimeStamp() <= timeAdjustment)
  23125. break;
  23126. list.insert (i + 1, newOne);
  23127. }
  23128. void MidiMessageSequence::deleteEvent (const int index,
  23129. const bool deleteMatchingNoteUp)
  23130. {
  23131. if (((unsigned int) index) < (unsigned int) list.size())
  23132. {
  23133. if (deleteMatchingNoteUp)
  23134. deleteEvent (getIndexOfMatchingKeyUp (index), false);
  23135. list.remove (index);
  23136. }
  23137. }
  23138. void MidiMessageSequence::addSequence (const MidiMessageSequence& other,
  23139. double timeAdjustment,
  23140. double firstAllowableTime,
  23141. double endOfAllowableDestTimes)
  23142. {
  23143. firstAllowableTime -= timeAdjustment;
  23144. endOfAllowableDestTimes -= timeAdjustment;
  23145. for (int i = 0; i < other.list.size(); ++i)
  23146. {
  23147. const MidiMessage& m = other.list.getUnchecked(i)->message;
  23148. const double t = m.getTimeStamp();
  23149. if (t >= firstAllowableTime && t < endOfAllowableDestTimes)
  23150. {
  23151. MidiEventHolder* const newOne = new MidiEventHolder (m);
  23152. newOne->message.setTimeStamp (timeAdjustment + t);
  23153. list.add (newOne);
  23154. }
  23155. }
  23156. sort();
  23157. }
  23158. int MidiMessageSequence::compareElements (const MidiMessageSequence::MidiEventHolder* const first,
  23159. const MidiMessageSequence::MidiEventHolder* const second) throw()
  23160. {
  23161. const double diff = first->message.getTimeStamp()
  23162. - second->message.getTimeStamp();
  23163. return (diff > 0) - (diff < 0);
  23164. }
  23165. void MidiMessageSequence::sort()
  23166. {
  23167. list.sort (*this, true);
  23168. }
  23169. void MidiMessageSequence::updateMatchedPairs()
  23170. {
  23171. for (int i = 0; i < list.size(); ++i)
  23172. {
  23173. const MidiMessage& m1 = list.getUnchecked(i)->message;
  23174. if (m1.isNoteOn())
  23175. {
  23176. list.getUnchecked(i)->noteOffObject = 0;
  23177. const int note = m1.getNoteNumber();
  23178. const int chan = m1.getChannel();
  23179. const int len = list.size();
  23180. for (int j = i + 1; j < len; ++j)
  23181. {
  23182. const MidiMessage& m = list.getUnchecked(j)->message;
  23183. if (m.getNoteNumber() == note && m.getChannel() == chan)
  23184. {
  23185. if (m.isNoteOff())
  23186. {
  23187. list.getUnchecked(i)->noteOffObject = list[j];
  23188. break;
  23189. }
  23190. else if (m.isNoteOn())
  23191. {
  23192. list.insert (j, new MidiEventHolder (MidiMessage::noteOff (chan, note)));
  23193. list.getUnchecked(j)->message.setTimeStamp (m.getTimeStamp());
  23194. list.getUnchecked(i)->noteOffObject = list[j];
  23195. break;
  23196. }
  23197. }
  23198. }
  23199. }
  23200. }
  23201. }
  23202. void MidiMessageSequence::addTimeToMessages (const double delta)
  23203. {
  23204. for (int i = list.size(); --i >= 0;)
  23205. list.getUnchecked (i)->message.setTimeStamp (list.getUnchecked (i)->message.getTimeStamp()
  23206. + delta);
  23207. }
  23208. void MidiMessageSequence::extractMidiChannelMessages (const int channelNumberToExtract,
  23209. MidiMessageSequence& destSequence,
  23210. const bool alsoIncludeMetaEvents) const
  23211. {
  23212. for (int i = 0; i < list.size(); ++i)
  23213. {
  23214. const MidiMessage& mm = list.getUnchecked(i)->message;
  23215. if (mm.isForChannel (channelNumberToExtract)
  23216. || (alsoIncludeMetaEvents && mm.isMetaEvent()))
  23217. {
  23218. destSequence.addEvent (mm);
  23219. }
  23220. }
  23221. }
  23222. void MidiMessageSequence::extractSysExMessages (MidiMessageSequence& destSequence) const
  23223. {
  23224. for (int i = 0; i < list.size(); ++i)
  23225. {
  23226. const MidiMessage& mm = list.getUnchecked(i)->message;
  23227. if (mm.isSysEx())
  23228. destSequence.addEvent (mm);
  23229. }
  23230. }
  23231. void MidiMessageSequence::deleteMidiChannelMessages (const int channelNumberToRemove)
  23232. {
  23233. for (int i = list.size(); --i >= 0;)
  23234. if (list.getUnchecked(i)->message.isForChannel (channelNumberToRemove))
  23235. list.remove(i);
  23236. }
  23237. void MidiMessageSequence::deleteSysExMessages()
  23238. {
  23239. for (int i = list.size(); --i >= 0;)
  23240. if (list.getUnchecked(i)->message.isSysEx())
  23241. list.remove(i);
  23242. }
  23243. void MidiMessageSequence::createControllerUpdatesForTime (const int channelNumber,
  23244. const double time,
  23245. OwnedArray<MidiMessage>& dest)
  23246. {
  23247. bool doneProg = false;
  23248. bool donePitchWheel = false;
  23249. Array <int> doneControllers;
  23250. doneControllers.ensureStorageAllocated (32);
  23251. for (int i = list.size(); --i >= 0;)
  23252. {
  23253. const MidiMessage& mm = list.getUnchecked(i)->message;
  23254. if (mm.isForChannel (channelNumber)
  23255. && mm.getTimeStamp() <= time)
  23256. {
  23257. if (mm.isProgramChange())
  23258. {
  23259. if (! doneProg)
  23260. {
  23261. dest.add (new MidiMessage (mm, 0.0));
  23262. doneProg = true;
  23263. }
  23264. }
  23265. else if (mm.isController())
  23266. {
  23267. if (! doneControllers.contains (mm.getControllerNumber()))
  23268. {
  23269. dest.add (new MidiMessage (mm, 0.0));
  23270. doneControllers.add (mm.getControllerNumber());
  23271. }
  23272. }
  23273. else if (mm.isPitchWheel())
  23274. {
  23275. if (! donePitchWheel)
  23276. {
  23277. dest.add (new MidiMessage (mm, 0.0));
  23278. donePitchWheel = true;
  23279. }
  23280. }
  23281. }
  23282. }
  23283. }
  23284. MidiMessageSequence::MidiEventHolder::MidiEventHolder (const MidiMessage& message_)
  23285. : message (message_),
  23286. noteOffObject (0)
  23287. {
  23288. }
  23289. MidiMessageSequence::MidiEventHolder::~MidiEventHolder()
  23290. {
  23291. }
  23292. END_JUCE_NAMESPACE
  23293. /*** End of inlined file: juce_MidiMessageSequence.cpp ***/
  23294. /*** Start of inlined file: juce_AudioPluginFormat.cpp ***/
  23295. BEGIN_JUCE_NAMESPACE
  23296. AudioPluginFormat::AudioPluginFormat() throw()
  23297. {
  23298. }
  23299. AudioPluginFormat::~AudioPluginFormat()
  23300. {
  23301. }
  23302. END_JUCE_NAMESPACE
  23303. /*** End of inlined file: juce_AudioPluginFormat.cpp ***/
  23304. /*** Start of inlined file: juce_AudioPluginFormatManager.cpp ***/
  23305. BEGIN_JUCE_NAMESPACE
  23306. AudioPluginFormatManager::AudioPluginFormatManager() throw()
  23307. {
  23308. }
  23309. AudioPluginFormatManager::~AudioPluginFormatManager() throw()
  23310. {
  23311. clearSingletonInstance();
  23312. }
  23313. juce_ImplementSingleton_SingleThreaded (AudioPluginFormatManager);
  23314. void AudioPluginFormatManager::addDefaultFormats()
  23315. {
  23316. #if JUCE_DEBUG
  23317. // you should only call this method once!
  23318. for (int i = formats.size(); --i >= 0;)
  23319. {
  23320. #if JUCE_PLUGINHOST_VST && ! (JUCE_MAC && JUCE_64BIT)
  23321. jassert (dynamic_cast <VSTPluginFormat*> (formats[i]) == 0);
  23322. #endif
  23323. #if JUCE_PLUGINHOST_AU && JUCE_MAC
  23324. jassert (dynamic_cast <AudioUnitPluginFormat*> (formats[i]) == 0);
  23325. #endif
  23326. #if JUCE_PLUGINHOST_DX && JUCE_WIN32
  23327. jassert (dynamic_cast <DirectXPluginFormat*> (formats[i]) == 0);
  23328. #endif
  23329. #if JUCE_PLUGINHOST_LADSPA && JUCE_LINUX
  23330. jassert (dynamic_cast <LADSPAPluginFormat*> (formats[i]) == 0);
  23331. #endif
  23332. }
  23333. #endif
  23334. #if JUCE_PLUGINHOST_AU && JUCE_MAC
  23335. formats.add (new AudioUnitPluginFormat());
  23336. #endif
  23337. #if JUCE_PLUGINHOST_VST && ! (JUCE_MAC && JUCE_64BIT)
  23338. formats.add (new VSTPluginFormat());
  23339. #endif
  23340. #if JUCE_PLUGINHOST_DX && JUCE_WIN32
  23341. formats.add (new DirectXPluginFormat());
  23342. #endif
  23343. #if JUCE_PLUGINHOST_LADSPA && JUCE_LINUX
  23344. formats.add (new LADSPAPluginFormat());
  23345. #endif
  23346. }
  23347. int AudioPluginFormatManager::getNumFormats() throw()
  23348. {
  23349. return formats.size();
  23350. }
  23351. AudioPluginFormat* AudioPluginFormatManager::getFormat (const int index) throw()
  23352. {
  23353. return formats [index];
  23354. }
  23355. void AudioPluginFormatManager::addFormat (AudioPluginFormat* const format) throw()
  23356. {
  23357. formats.add (format);
  23358. }
  23359. AudioPluginInstance* AudioPluginFormatManager::createPluginInstance (const PluginDescription& description,
  23360. String& errorMessage) const
  23361. {
  23362. AudioPluginInstance* result = 0;
  23363. for (int i = 0; i < formats.size(); ++i)
  23364. {
  23365. result = formats.getUnchecked(i)->createInstanceFromDescription (description);
  23366. if (result != 0)
  23367. break;
  23368. }
  23369. if (result == 0)
  23370. {
  23371. if (! doesPluginStillExist (description))
  23372. errorMessage = TRANS ("This plug-in file no longer exists");
  23373. else
  23374. errorMessage = TRANS ("This plug-in failed to load correctly");
  23375. }
  23376. return result;
  23377. }
  23378. bool AudioPluginFormatManager::doesPluginStillExist (const PluginDescription& description) const
  23379. {
  23380. for (int i = 0; i < formats.size(); ++i)
  23381. if (formats.getUnchecked(i)->getName() == description.pluginFormatName)
  23382. return formats.getUnchecked(i)->doesPluginStillExist (description);
  23383. return false;
  23384. }
  23385. END_JUCE_NAMESPACE
  23386. /*** End of inlined file: juce_AudioPluginFormatManager.cpp ***/
  23387. /*** Start of inlined file: juce_AudioPluginInstance.cpp ***/
  23388. #define JUCE_PLUGIN_HOST 1
  23389. BEGIN_JUCE_NAMESPACE
  23390. AudioPluginInstance::AudioPluginInstance()
  23391. {
  23392. }
  23393. AudioPluginInstance::~AudioPluginInstance()
  23394. {
  23395. }
  23396. END_JUCE_NAMESPACE
  23397. /*** End of inlined file: juce_AudioPluginInstance.cpp ***/
  23398. /*** Start of inlined file: juce_KnownPluginList.cpp ***/
  23399. BEGIN_JUCE_NAMESPACE
  23400. KnownPluginList::KnownPluginList()
  23401. {
  23402. }
  23403. KnownPluginList::~KnownPluginList()
  23404. {
  23405. }
  23406. void KnownPluginList::clear()
  23407. {
  23408. if (types.size() > 0)
  23409. {
  23410. types.clear();
  23411. sendChangeMessage (this);
  23412. }
  23413. }
  23414. PluginDescription* KnownPluginList::getTypeForFile (const String& fileOrIdentifier) const throw()
  23415. {
  23416. for (int i = 0; i < types.size(); ++i)
  23417. if (types.getUnchecked(i)->fileOrIdentifier == fileOrIdentifier)
  23418. return types.getUnchecked(i);
  23419. return 0;
  23420. }
  23421. PluginDescription* KnownPluginList::getTypeForIdentifierString (const String& identifierString) const throw()
  23422. {
  23423. for (int i = 0; i < types.size(); ++i)
  23424. if (types.getUnchecked(i)->createIdentifierString() == identifierString)
  23425. return types.getUnchecked(i);
  23426. return 0;
  23427. }
  23428. bool KnownPluginList::addType (const PluginDescription& type)
  23429. {
  23430. for (int i = types.size(); --i >= 0;)
  23431. {
  23432. if (types.getUnchecked(i)->isDuplicateOf (type))
  23433. {
  23434. // strange - found a duplicate plugin with different info..
  23435. jassert (types.getUnchecked(i)->name == type.name);
  23436. jassert (types.getUnchecked(i)->isInstrument == type.isInstrument);
  23437. *types.getUnchecked(i) = type;
  23438. return false;
  23439. }
  23440. }
  23441. types.add (new PluginDescription (type));
  23442. sendChangeMessage (this);
  23443. return true;
  23444. }
  23445. void KnownPluginList::removeType (const int index) throw()
  23446. {
  23447. types.remove (index);
  23448. sendChangeMessage (this);
  23449. }
  23450. static Time getFileModTime (const String& fileOrIdentifier) throw()
  23451. {
  23452. if (fileOrIdentifier.startsWithChar ('/')
  23453. || fileOrIdentifier[1] == ':')
  23454. {
  23455. return File (fileOrIdentifier).getLastModificationTime();
  23456. }
  23457. return Time (0);
  23458. }
  23459. static bool timesAreDifferent (const Time& t1, const Time& t2) throw()
  23460. {
  23461. return t1 != t2 || t1 == Time (0);
  23462. }
  23463. bool KnownPluginList::isListingUpToDate (const String& fileOrIdentifier) const throw()
  23464. {
  23465. if (getTypeForFile (fileOrIdentifier) == 0)
  23466. return false;
  23467. for (int i = types.size(); --i >= 0;)
  23468. {
  23469. const PluginDescription* const d = types.getUnchecked(i);
  23470. if (d->fileOrIdentifier == fileOrIdentifier
  23471. && timesAreDifferent (d->lastFileModTime, getFileModTime (fileOrIdentifier)))
  23472. {
  23473. return false;
  23474. }
  23475. }
  23476. return true;
  23477. }
  23478. bool KnownPluginList::scanAndAddFile (const String& fileOrIdentifier,
  23479. const bool dontRescanIfAlreadyInList,
  23480. OwnedArray <PluginDescription>& typesFound,
  23481. AudioPluginFormat& format)
  23482. {
  23483. bool addedOne = false;
  23484. if (dontRescanIfAlreadyInList
  23485. && getTypeForFile (fileOrIdentifier) != 0)
  23486. {
  23487. bool needsRescanning = false;
  23488. for (int i = types.size(); --i >= 0;)
  23489. {
  23490. const PluginDescription* const d = types.getUnchecked(i);
  23491. if (d->fileOrIdentifier == fileOrIdentifier)
  23492. {
  23493. if (timesAreDifferent (d->lastFileModTime, getFileModTime (fileOrIdentifier)))
  23494. needsRescanning = true;
  23495. else
  23496. typesFound.add (new PluginDescription (*d));
  23497. }
  23498. }
  23499. if (! needsRescanning)
  23500. return false;
  23501. }
  23502. OwnedArray <PluginDescription> found;
  23503. format.findAllTypesForFile (found, fileOrIdentifier);
  23504. for (int i = 0; i < found.size(); ++i)
  23505. {
  23506. PluginDescription* const desc = found.getUnchecked(i);
  23507. jassert (desc != 0);
  23508. if (addType (*desc))
  23509. addedOne = true;
  23510. typesFound.add (new PluginDescription (*desc));
  23511. }
  23512. return addedOne;
  23513. }
  23514. void KnownPluginList::scanAndAddDragAndDroppedFiles (const StringArray& files,
  23515. OwnedArray <PluginDescription>& typesFound)
  23516. {
  23517. for (int i = 0; i < files.size(); ++i)
  23518. {
  23519. bool loaded = false;
  23520. for (int j = 0; j < AudioPluginFormatManager::getInstance()->getNumFormats(); ++j)
  23521. {
  23522. AudioPluginFormat* const format = AudioPluginFormatManager::getInstance()->getFormat (j);
  23523. if (scanAndAddFile (files[i], true, typesFound, *format))
  23524. loaded = true;
  23525. }
  23526. if (! loaded)
  23527. {
  23528. const File f (files[i]);
  23529. if (f.isDirectory())
  23530. {
  23531. StringArray s;
  23532. {
  23533. Array<File> subFiles;
  23534. f.findChildFiles (subFiles, File::findFilesAndDirectories, false);
  23535. for (int j = 0; j < subFiles.size(); ++j)
  23536. s.add (subFiles.getReference(j).getFullPathName());
  23537. }
  23538. scanAndAddDragAndDroppedFiles (s, typesFound);
  23539. }
  23540. }
  23541. }
  23542. }
  23543. class PluginSorter
  23544. {
  23545. public:
  23546. KnownPluginList::SortMethod method;
  23547. PluginSorter() throw() {}
  23548. int compareElements (const PluginDescription* const first,
  23549. const PluginDescription* const second) const throw()
  23550. {
  23551. int diff = 0;
  23552. if (method == KnownPluginList::sortByCategory)
  23553. diff = first->category.compareLexicographically (second->category);
  23554. else if (method == KnownPluginList::sortByManufacturer)
  23555. diff = first->manufacturerName.compareLexicographically (second->manufacturerName);
  23556. else if (method == KnownPluginList::sortByFileSystemLocation)
  23557. diff = first->fileOrIdentifier.replaceCharacter ('\\', '/')
  23558. .upToLastOccurrenceOf ("/", false, false)
  23559. .compare (second->fileOrIdentifier.replaceCharacter ('\\', '/')
  23560. .upToLastOccurrenceOf ("/", false, false));
  23561. if (diff == 0)
  23562. diff = first->name.compareLexicographically (second->name);
  23563. return diff;
  23564. }
  23565. };
  23566. void KnownPluginList::sort (const SortMethod method)
  23567. {
  23568. if (method != defaultOrder)
  23569. {
  23570. PluginSorter sorter;
  23571. sorter.method = method;
  23572. types.sort (sorter, true);
  23573. sendChangeMessage (this);
  23574. }
  23575. }
  23576. XmlElement* KnownPluginList::createXml() const
  23577. {
  23578. XmlElement* const e = new XmlElement ("KNOWNPLUGINS");
  23579. for (int i = 0; i < types.size(); ++i)
  23580. e->addChildElement (types.getUnchecked(i)->createXml());
  23581. return e;
  23582. }
  23583. void KnownPluginList::recreateFromXml (const XmlElement& xml)
  23584. {
  23585. clear();
  23586. if (xml.hasTagName ("KNOWNPLUGINS"))
  23587. {
  23588. forEachXmlChildElement (xml, e)
  23589. {
  23590. PluginDescription info;
  23591. if (info.loadFromXml (*e))
  23592. addType (info);
  23593. }
  23594. }
  23595. }
  23596. const int menuIdBase = 0x324503f4;
  23597. // This is used to turn a bunch of paths into a nested menu structure.
  23598. struct PluginFilesystemTree
  23599. {
  23600. private:
  23601. String folder;
  23602. OwnedArray <PluginFilesystemTree> subFolders;
  23603. Array <PluginDescription*> plugins;
  23604. void addPlugin (PluginDescription* const pd, const String& path)
  23605. {
  23606. if (path.isEmpty())
  23607. {
  23608. plugins.add (pd);
  23609. }
  23610. else
  23611. {
  23612. const String firstSubFolder (path.upToFirstOccurrenceOf ("/", false, false));
  23613. const String remainingPath (path.fromFirstOccurrenceOf ("/", false, false));
  23614. for (int i = subFolders.size(); --i >= 0;)
  23615. {
  23616. if (subFolders.getUnchecked(i)->folder.equalsIgnoreCase (firstSubFolder))
  23617. {
  23618. subFolders.getUnchecked(i)->addPlugin (pd, remainingPath);
  23619. return;
  23620. }
  23621. }
  23622. PluginFilesystemTree* const newFolder = new PluginFilesystemTree();
  23623. newFolder->folder = firstSubFolder;
  23624. subFolders.add (newFolder);
  23625. newFolder->addPlugin (pd, remainingPath);
  23626. }
  23627. }
  23628. // removes any deeply nested folders that don't contain any actual plugins
  23629. void optimise()
  23630. {
  23631. for (int i = subFolders.size(); --i >= 0;)
  23632. {
  23633. PluginFilesystemTree* const sub = subFolders.getUnchecked(i);
  23634. sub->optimise();
  23635. if (sub->plugins.size() == 0)
  23636. {
  23637. for (int j = 0; j < sub->subFolders.size(); ++j)
  23638. subFolders.add (sub->subFolders.getUnchecked(j));
  23639. sub->subFolders.clear (false);
  23640. subFolders.remove (i);
  23641. }
  23642. }
  23643. }
  23644. public:
  23645. void buildTree (const Array <PluginDescription*>& allPlugins)
  23646. {
  23647. for (int i = 0; i < allPlugins.size(); ++i)
  23648. {
  23649. String path (allPlugins.getUnchecked(i)
  23650. ->fileOrIdentifier.replaceCharacter ('\\', '/')
  23651. .upToLastOccurrenceOf ("/", false, false));
  23652. if (path.substring (1, 2) == ":")
  23653. path = path.substring (2);
  23654. addPlugin (allPlugins.getUnchecked(i), path);
  23655. }
  23656. optimise();
  23657. }
  23658. void addToMenu (PopupMenu& m, const OwnedArray <PluginDescription>& allPlugins) const
  23659. {
  23660. int i;
  23661. for (i = 0; i < subFolders.size(); ++i)
  23662. {
  23663. const PluginFilesystemTree* const sub = subFolders.getUnchecked(i);
  23664. PopupMenu subMenu;
  23665. sub->addToMenu (subMenu, allPlugins);
  23666. #if JUCE_MAC
  23667. // avoid the special AU formatting nonsense on Mac..
  23668. m.addSubMenu (sub->folder.fromFirstOccurrenceOf (":", false, false), subMenu);
  23669. #else
  23670. m.addSubMenu (sub->folder, subMenu);
  23671. #endif
  23672. }
  23673. for (i = 0; i < plugins.size(); ++i)
  23674. {
  23675. PluginDescription* const plugin = plugins.getUnchecked(i);
  23676. m.addItem (allPlugins.indexOf (plugin) + menuIdBase,
  23677. plugin->name, true, false);
  23678. }
  23679. }
  23680. };
  23681. void KnownPluginList::addToMenu (PopupMenu& menu, const SortMethod sortMethod) const
  23682. {
  23683. Array <PluginDescription*> sorted;
  23684. {
  23685. PluginSorter sorter;
  23686. sorter.method = sortMethod;
  23687. for (int i = 0; i < types.size(); ++i)
  23688. sorted.addSorted (sorter, types.getUnchecked(i));
  23689. }
  23690. if (sortMethod == sortByCategory
  23691. || sortMethod == sortByManufacturer)
  23692. {
  23693. String lastSubMenuName;
  23694. PopupMenu sub;
  23695. for (int i = 0; i < sorted.size(); ++i)
  23696. {
  23697. const PluginDescription* const pd = sorted.getUnchecked(i);
  23698. String thisSubMenuName (sortMethod == sortByCategory ? pd->category
  23699. : pd->manufacturerName);
  23700. if (! thisSubMenuName.containsNonWhitespaceChars())
  23701. thisSubMenuName = "Other";
  23702. if (thisSubMenuName != lastSubMenuName)
  23703. {
  23704. if (sub.getNumItems() > 0)
  23705. {
  23706. menu.addSubMenu (lastSubMenuName, sub);
  23707. sub.clear();
  23708. }
  23709. lastSubMenuName = thisSubMenuName;
  23710. }
  23711. sub.addItem (types.indexOf (pd) + menuIdBase, pd->name, true, false);
  23712. }
  23713. if (sub.getNumItems() > 0)
  23714. menu.addSubMenu (lastSubMenuName, sub);
  23715. }
  23716. else if (sortMethod == sortByFileSystemLocation)
  23717. {
  23718. PluginFilesystemTree root;
  23719. root.buildTree (sorted);
  23720. root.addToMenu (menu, types);
  23721. }
  23722. else
  23723. {
  23724. for (int i = 0; i < sorted.size(); ++i)
  23725. {
  23726. const PluginDescription* const pd = sorted.getUnchecked(i);
  23727. menu.addItem (types.indexOf (pd) + menuIdBase, pd->name, true, false);
  23728. }
  23729. }
  23730. }
  23731. int KnownPluginList::getIndexChosenByMenu (const int menuResultCode) const
  23732. {
  23733. const int i = menuResultCode - menuIdBase;
  23734. return (((unsigned int) i) < (unsigned int) types.size()) ? i : -1;
  23735. }
  23736. END_JUCE_NAMESPACE
  23737. /*** End of inlined file: juce_KnownPluginList.cpp ***/
  23738. /*** Start of inlined file: juce_PluginDescription.cpp ***/
  23739. BEGIN_JUCE_NAMESPACE
  23740. PluginDescription::PluginDescription() throw()
  23741. : uid (0),
  23742. isInstrument (false),
  23743. numInputChannels (0),
  23744. numOutputChannels (0)
  23745. {
  23746. }
  23747. PluginDescription::~PluginDescription() throw()
  23748. {
  23749. }
  23750. PluginDescription::PluginDescription (const PluginDescription& other) throw()
  23751. : name (other.name),
  23752. pluginFormatName (other.pluginFormatName),
  23753. category (other.category),
  23754. manufacturerName (other.manufacturerName),
  23755. version (other.version),
  23756. fileOrIdentifier (other.fileOrIdentifier),
  23757. lastFileModTime (other.lastFileModTime),
  23758. uid (other.uid),
  23759. isInstrument (other.isInstrument),
  23760. numInputChannels (other.numInputChannels),
  23761. numOutputChannels (other.numOutputChannels)
  23762. {
  23763. }
  23764. PluginDescription& PluginDescription::operator= (const PluginDescription& other) throw()
  23765. {
  23766. name = other.name;
  23767. pluginFormatName = other.pluginFormatName;
  23768. category = other.category;
  23769. manufacturerName = other.manufacturerName;
  23770. version = other.version;
  23771. fileOrIdentifier = other.fileOrIdentifier;
  23772. uid = other.uid;
  23773. isInstrument = other.isInstrument;
  23774. lastFileModTime = other.lastFileModTime;
  23775. numInputChannels = other.numInputChannels;
  23776. numOutputChannels = other.numOutputChannels;
  23777. return *this;
  23778. }
  23779. bool PluginDescription::isDuplicateOf (const PluginDescription& other) const
  23780. {
  23781. return fileOrIdentifier == other.fileOrIdentifier
  23782. && uid == other.uid;
  23783. }
  23784. const String PluginDescription::createIdentifierString() const throw()
  23785. {
  23786. return pluginFormatName
  23787. + "-" + name
  23788. + "-" + String::toHexString (fileOrIdentifier.hashCode())
  23789. + "-" + String::toHexString (uid);
  23790. }
  23791. XmlElement* PluginDescription::createXml() const
  23792. {
  23793. XmlElement* const e = new XmlElement ("PLUGIN");
  23794. e->setAttribute ("name", name);
  23795. e->setAttribute ("format", pluginFormatName);
  23796. e->setAttribute ("category", category);
  23797. e->setAttribute ("manufacturer", manufacturerName);
  23798. e->setAttribute ("version", version);
  23799. e->setAttribute ("file", fileOrIdentifier);
  23800. e->setAttribute ("uid", String::toHexString (uid));
  23801. e->setAttribute ("isInstrument", isInstrument);
  23802. e->setAttribute ("fileTime", String::toHexString (lastFileModTime.toMilliseconds()));
  23803. e->setAttribute ("numInputs", numInputChannels);
  23804. e->setAttribute ("numOutputs", numOutputChannels);
  23805. return e;
  23806. }
  23807. bool PluginDescription::loadFromXml (const XmlElement& xml)
  23808. {
  23809. if (xml.hasTagName ("PLUGIN"))
  23810. {
  23811. name = xml.getStringAttribute ("name");
  23812. pluginFormatName = xml.getStringAttribute ("format");
  23813. category = xml.getStringAttribute ("category");
  23814. manufacturerName = xml.getStringAttribute ("manufacturer");
  23815. version = xml.getStringAttribute ("version");
  23816. fileOrIdentifier = xml.getStringAttribute ("file");
  23817. uid = xml.getStringAttribute ("uid").getHexValue32();
  23818. isInstrument = xml.getBoolAttribute ("isInstrument", false);
  23819. lastFileModTime = Time (xml.getStringAttribute ("fileTime").getHexValue64());
  23820. numInputChannels = xml.getIntAttribute ("numInputs");
  23821. numOutputChannels = xml.getIntAttribute ("numOutputs");
  23822. return true;
  23823. }
  23824. return false;
  23825. }
  23826. END_JUCE_NAMESPACE
  23827. /*** End of inlined file: juce_PluginDescription.cpp ***/
  23828. /*** Start of inlined file: juce_PluginDirectoryScanner.cpp ***/
  23829. BEGIN_JUCE_NAMESPACE
  23830. PluginDirectoryScanner::PluginDirectoryScanner (KnownPluginList& listToAddTo,
  23831. AudioPluginFormat& formatToLookFor,
  23832. FileSearchPath directoriesToSearch,
  23833. const bool recursive,
  23834. const File& deadMansPedalFile_)
  23835. : list (listToAddTo),
  23836. format (formatToLookFor),
  23837. deadMansPedalFile (deadMansPedalFile_),
  23838. nextIndex (0),
  23839. progress (0)
  23840. {
  23841. directoriesToSearch.removeRedundantPaths();
  23842. filesOrIdentifiersToScan = format.searchPathsForPlugins (directoriesToSearch, recursive);
  23843. // If any plugins have crashed recently when being loaded, move them to the
  23844. // end of the list to give the others a chance to load correctly..
  23845. const StringArray crashedPlugins (getDeadMansPedalFile());
  23846. for (int i = 0; i < crashedPlugins.size(); ++i)
  23847. {
  23848. const String f = crashedPlugins[i];
  23849. for (int j = filesOrIdentifiersToScan.size(); --j >= 0;)
  23850. if (f == filesOrIdentifiersToScan[j])
  23851. filesOrIdentifiersToScan.move (j, -1);
  23852. }
  23853. }
  23854. PluginDirectoryScanner::~PluginDirectoryScanner()
  23855. {
  23856. }
  23857. const String PluginDirectoryScanner::getNextPluginFileThatWillBeScanned() const throw()
  23858. {
  23859. return format.getNameOfPluginFromIdentifier (filesOrIdentifiersToScan [nextIndex]);
  23860. }
  23861. bool PluginDirectoryScanner::scanNextFile (const bool dontRescanIfAlreadyInList)
  23862. {
  23863. String file (filesOrIdentifiersToScan [nextIndex]);
  23864. if (file.isNotEmpty())
  23865. {
  23866. if (! list.isListingUpToDate (file))
  23867. {
  23868. OwnedArray <PluginDescription> typesFound;
  23869. // Add this plugin to the end of the dead-man's pedal list in case it crashes...
  23870. StringArray crashedPlugins (getDeadMansPedalFile());
  23871. crashedPlugins.removeString (file);
  23872. crashedPlugins.add (file);
  23873. setDeadMansPedalFile (crashedPlugins);
  23874. list.scanAndAddFile (file,
  23875. dontRescanIfAlreadyInList,
  23876. typesFound,
  23877. format);
  23878. // Managed to load without crashing, so remove it from the dead-man's-pedal..
  23879. crashedPlugins.removeString (file);
  23880. setDeadMansPedalFile (crashedPlugins);
  23881. if (typesFound.size() == 0)
  23882. failedFiles.add (file);
  23883. }
  23884. ++nextIndex;
  23885. progress = nextIndex / (float) filesOrIdentifiersToScan.size();
  23886. }
  23887. return nextIndex < filesOrIdentifiersToScan.size();
  23888. }
  23889. const StringArray PluginDirectoryScanner::getDeadMansPedalFile() throw()
  23890. {
  23891. StringArray lines;
  23892. if (deadMansPedalFile != File::nonexistent)
  23893. {
  23894. lines.addLines (deadMansPedalFile.loadFileAsString());
  23895. lines.removeEmptyStrings();
  23896. }
  23897. return lines;
  23898. }
  23899. void PluginDirectoryScanner::setDeadMansPedalFile (const StringArray& newContents) throw()
  23900. {
  23901. if (deadMansPedalFile != File::nonexistent)
  23902. deadMansPedalFile.replaceWithText (newContents.joinIntoString ("\n"), true, true);
  23903. }
  23904. END_JUCE_NAMESPACE
  23905. /*** End of inlined file: juce_PluginDirectoryScanner.cpp ***/
  23906. /*** Start of inlined file: juce_PluginListComponent.cpp ***/
  23907. BEGIN_JUCE_NAMESPACE
  23908. PluginListComponent::PluginListComponent (KnownPluginList& listToEdit,
  23909. const File& deadMansPedalFile_,
  23910. PropertiesFile* const propertiesToUse_)
  23911. : list (listToEdit),
  23912. deadMansPedalFile (deadMansPedalFile_),
  23913. propertiesToUse (propertiesToUse_)
  23914. {
  23915. addAndMakeVisible (listBox = new ListBox (String::empty, this));
  23916. addAndMakeVisible (optionsButton = new TextButton ("Options..."));
  23917. optionsButton->addButtonListener (this);
  23918. optionsButton->setTriggeredOnMouseDown (true);
  23919. setSize (400, 600);
  23920. list.addChangeListener (this);
  23921. }
  23922. PluginListComponent::~PluginListComponent()
  23923. {
  23924. list.removeChangeListener (this);
  23925. deleteAllChildren();
  23926. }
  23927. void PluginListComponent::resized()
  23928. {
  23929. listBox->setBounds (0, 0, getWidth(), getHeight() - 30);
  23930. optionsButton->changeWidthToFitText (24);
  23931. optionsButton->setTopLeftPosition (8, getHeight() - 28);
  23932. }
  23933. void PluginListComponent::changeListenerCallback (void*)
  23934. {
  23935. listBox->updateContent();
  23936. listBox->repaint();
  23937. }
  23938. int PluginListComponent::getNumRows()
  23939. {
  23940. return list.getNumTypes();
  23941. }
  23942. void PluginListComponent::paintListBoxItem (int row,
  23943. Graphics& g,
  23944. int width, int height,
  23945. bool rowIsSelected)
  23946. {
  23947. if (rowIsSelected)
  23948. g.fillAll (findColour (TextEditor::highlightColourId));
  23949. const PluginDescription* const pd = list.getType (row);
  23950. if (pd != 0)
  23951. {
  23952. GlyphArrangement ga;
  23953. ga.addCurtailedLineOfText (Font (height * 0.7f, Font::bold), pd->name, 8.0f, height * 0.8f, width - 10.0f, true);
  23954. g.setColour (Colours::black);
  23955. ga.draw (g);
  23956. const Rectangle<float> bb (ga.getBoundingBox (0, -1, false));
  23957. String desc;
  23958. desc << pd->pluginFormatName
  23959. << (pd->isInstrument ? " instrument" : " effect")
  23960. << " - "
  23961. << pd->numInputChannels << (pd->numInputChannels == 1 ? " in" : " ins")
  23962. << " / "
  23963. << pd->numOutputChannels << (pd->numOutputChannels == 1 ? " out" : " outs");
  23964. if (pd->manufacturerName.isNotEmpty())
  23965. desc << " - " << pd->manufacturerName;
  23966. if (pd->version.isNotEmpty())
  23967. desc << " - " << pd->version;
  23968. if (pd->category.isNotEmpty())
  23969. desc << " - category: '" << pd->category << '\'';
  23970. g.setColour (Colours::grey);
  23971. ga.clear();
  23972. ga.addCurtailedLineOfText (Font (height * 0.6f), desc, bb.getRight() + 10.0f, height * 0.8f, width - bb.getRight() - 12.0f, true);
  23973. ga.draw (g);
  23974. }
  23975. }
  23976. void PluginListComponent::deleteKeyPressed (int lastRowSelected)
  23977. {
  23978. list.removeType (lastRowSelected);
  23979. }
  23980. void PluginListComponent::buttonClicked (Button* b)
  23981. {
  23982. if (optionsButton == b)
  23983. {
  23984. PopupMenu menu;
  23985. menu.addItem (1, TRANS("Clear list"));
  23986. menu.addItem (5, TRANS("Remove selected plugin from list"), listBox->getNumSelectedRows() > 0);
  23987. menu.addItem (6, TRANS("Show folder containing selected plugin"), listBox->getNumSelectedRows() > 0);
  23988. menu.addItem (7, TRANS("Remove any plugins whose files no longer exist"));
  23989. menu.addSeparator();
  23990. menu.addItem (2, TRANS("Sort alphabetically"));
  23991. menu.addItem (3, TRANS("Sort by category"));
  23992. menu.addItem (4, TRANS("Sort by manufacturer"));
  23993. menu.addSeparator();
  23994. for (int i = 0; i < AudioPluginFormatManager::getInstance()->getNumFormats(); ++i)
  23995. {
  23996. AudioPluginFormat* const format = AudioPluginFormatManager::getInstance()->getFormat (i);
  23997. if (format->getDefaultLocationsToSearch().getNumPaths() > 0)
  23998. menu.addItem (10 + i, "Scan for new or updated " + format->getName() + " plugins...");
  23999. }
  24000. const int r = menu.showAt (optionsButton);
  24001. if (r == 1)
  24002. {
  24003. list.clear();
  24004. }
  24005. else if (r == 2)
  24006. {
  24007. list.sort (KnownPluginList::sortAlphabetically);
  24008. }
  24009. else if (r == 3)
  24010. {
  24011. list.sort (KnownPluginList::sortByCategory);
  24012. }
  24013. else if (r == 4)
  24014. {
  24015. list.sort (KnownPluginList::sortByManufacturer);
  24016. }
  24017. else if (r == 5)
  24018. {
  24019. const SparseSet <int> selected (listBox->getSelectedRows());
  24020. for (int i = list.getNumTypes(); --i >= 0;)
  24021. if (selected.contains (i))
  24022. list.removeType (i);
  24023. }
  24024. else if (r == 6)
  24025. {
  24026. const PluginDescription* const desc = list.getType (listBox->getSelectedRow());
  24027. if (desc != 0)
  24028. {
  24029. if (File (desc->fileOrIdentifier).existsAsFile())
  24030. File (desc->fileOrIdentifier).getParentDirectory().startAsProcess();
  24031. }
  24032. }
  24033. else if (r == 7)
  24034. {
  24035. for (int i = list.getNumTypes(); --i >= 0;)
  24036. {
  24037. if (! AudioPluginFormatManager::getInstance()->doesPluginStillExist (*list.getType (i)))
  24038. {
  24039. list.removeType (i);
  24040. }
  24041. }
  24042. }
  24043. else if (r != 0)
  24044. {
  24045. typeToScan = r - 10;
  24046. startTimer (1);
  24047. }
  24048. }
  24049. }
  24050. void PluginListComponent::timerCallback()
  24051. {
  24052. stopTimer();
  24053. scanFor (AudioPluginFormatManager::getInstance()->getFormat (typeToScan));
  24054. }
  24055. bool PluginListComponent::isInterestedInFileDrag (const StringArray& /*files*/)
  24056. {
  24057. return true;
  24058. }
  24059. void PluginListComponent::filesDropped (const StringArray& files, int, int)
  24060. {
  24061. OwnedArray <PluginDescription> typesFound;
  24062. list.scanAndAddDragAndDroppedFiles (files, typesFound);
  24063. }
  24064. void PluginListComponent::scanFor (AudioPluginFormat* format)
  24065. {
  24066. if (format == 0)
  24067. return;
  24068. FileSearchPath path (format->getDefaultLocationsToSearch());
  24069. if (propertiesToUse != 0)
  24070. path = propertiesToUse->getValue ("lastPluginScanPath_" + format->getName(), path.toString());
  24071. {
  24072. AlertWindow aw (TRANS("Select folders to scan..."), String::empty, AlertWindow::NoIcon);
  24073. FileSearchPathListComponent pathList;
  24074. pathList.setSize (500, 300);
  24075. pathList.setPath (path);
  24076. aw.addCustomComponent (&pathList);
  24077. aw.addButton (TRANS("Scan"), 1, KeyPress::returnKey);
  24078. aw.addButton (TRANS("Cancel"), 0, KeyPress (KeyPress::escapeKey));
  24079. if (aw.runModalLoop() == 0)
  24080. return;
  24081. path = pathList.getPath();
  24082. }
  24083. if (propertiesToUse != 0)
  24084. {
  24085. propertiesToUse->setValue ("lastPluginScanPath_" + format->getName(), path.toString());
  24086. propertiesToUse->saveIfNeeded();
  24087. }
  24088. double progress = 0.0;
  24089. AlertWindow aw (TRANS("Scanning for plugins..."),
  24090. TRANS("Searching for all possible plugin files..."), AlertWindow::NoIcon);
  24091. aw.addButton (TRANS("Cancel"), 0, KeyPress (KeyPress::escapeKey));
  24092. aw.addProgressBarComponent (progress);
  24093. aw.enterModalState();
  24094. MessageManager::getInstance()->runDispatchLoopUntil (300);
  24095. PluginDirectoryScanner scanner (list, *format, path, true, deadMansPedalFile);
  24096. for (;;)
  24097. {
  24098. aw.setMessage (TRANS("Testing:\n\n")
  24099. + scanner.getNextPluginFileThatWillBeScanned());
  24100. MessageManager::getInstance()->runDispatchLoopUntil (20);
  24101. if (! scanner.scanNextFile (true))
  24102. break;
  24103. if (! aw.isCurrentlyModal())
  24104. break;
  24105. progress = scanner.getProgress();
  24106. }
  24107. if (scanner.getFailedFiles().size() > 0)
  24108. {
  24109. StringArray shortNames;
  24110. for (int i = 0; i < scanner.getFailedFiles().size(); ++i)
  24111. shortNames.add (File (scanner.getFailedFiles()[i]).getFileName());
  24112. AlertWindow::showMessageBox (AlertWindow::InfoIcon,
  24113. TRANS("Scan complete"),
  24114. TRANS("Note that the following files appeared to be plugin files, but failed to load correctly:\n\n")
  24115. + shortNames.joinIntoString (", "));
  24116. }
  24117. }
  24118. END_JUCE_NAMESPACE
  24119. /*** End of inlined file: juce_PluginListComponent.cpp ***/
  24120. /*** Start of inlined file: juce_AudioUnitPluginFormat.mm ***/
  24121. #if JUCE_PLUGINHOST_AU && ! (JUCE_LINUX || JUCE_WINDOWS)
  24122. #include <AudioUnit/AudioUnit.h>
  24123. #include <AudioUnit/AUCocoaUIView.h>
  24124. #include <CoreAudioKit/AUGenericView.h>
  24125. #if JUCE_SUPPORT_CARBON
  24126. #include <AudioToolbox/AudioUnitUtilities.h>
  24127. #include <AudioUnit/AudioUnitCarbonView.h>
  24128. #endif
  24129. BEGIN_JUCE_NAMESPACE
  24130. #if JUCE_MAC && JUCE_SUPPORT_CARBON
  24131. #endif
  24132. #if JUCE_MAC
  24133. // Change this to disable logging of various activities
  24134. #ifndef AU_LOGGING
  24135. #define AU_LOGGING 1
  24136. #endif
  24137. #if AU_LOGGING
  24138. #define log(a) Logger::writeToLog(a);
  24139. #else
  24140. #define log(a)
  24141. #endif
  24142. static int insideCallback = 0;
  24143. static const String osTypeToString (OSType type)
  24144. {
  24145. char s[4];
  24146. s[0] = (char) (((uint32) type) >> 24);
  24147. s[1] = (char) (((uint32) type) >> 16);
  24148. s[2] = (char) (((uint32) type) >> 8);
  24149. s[3] = (char) ((uint32) type);
  24150. return String (s, 4);
  24151. }
  24152. static OSType stringToOSType (const String& s1)
  24153. {
  24154. const String s (s1 + " ");
  24155. return (((OSType) (unsigned char) s[0]) << 24)
  24156. | (((OSType) (unsigned char) s[1]) << 16)
  24157. | (((OSType) (unsigned char) s[2]) << 8)
  24158. | ((OSType) (unsigned char) s[3]);
  24159. }
  24160. static const char* auIdentifierPrefix = "AudioUnit:";
  24161. static const String createAUPluginIdentifier (const ComponentDescription& desc)
  24162. {
  24163. jassert (osTypeToString ('abcd') == "abcd"); // agh, must have got the endianness wrong..
  24164. jassert (stringToOSType ("abcd") == (OSType) 'abcd'); // ditto
  24165. String s (auIdentifierPrefix);
  24166. if (desc.componentType == kAudioUnitType_MusicDevice)
  24167. s << "Synths/";
  24168. else if (desc.componentType == kAudioUnitType_MusicEffect
  24169. || desc.componentType == kAudioUnitType_Effect)
  24170. s << "Effects/";
  24171. else if (desc.componentType == kAudioUnitType_Generator)
  24172. s << "Generators/";
  24173. else if (desc.componentType == kAudioUnitType_Panner)
  24174. s << "Panners/";
  24175. s << osTypeToString (desc.componentType) << ","
  24176. << osTypeToString (desc.componentSubType) << ","
  24177. << osTypeToString (desc.componentManufacturer);
  24178. return s;
  24179. }
  24180. static void getAUDetails (ComponentRecord* comp, String& name, String& manufacturer)
  24181. {
  24182. Handle componentNameHandle = NewHandle (sizeof (void*));
  24183. Handle componentInfoHandle = NewHandle (sizeof (void*));
  24184. if (componentNameHandle != 0 && componentInfoHandle != 0)
  24185. {
  24186. ComponentDescription desc;
  24187. if (GetComponentInfo (comp, &desc, componentNameHandle, componentInfoHandle, 0) == noErr)
  24188. {
  24189. ConstStr255Param nameString = (ConstStr255Param) (*componentNameHandle);
  24190. ConstStr255Param infoString = (ConstStr255Param) (*componentInfoHandle);
  24191. if (nameString != 0 && nameString[0] != 0)
  24192. {
  24193. const String all ((const char*) nameString + 1, nameString[0]);
  24194. DBG ("name: "+ all);
  24195. manufacturer = all.upToFirstOccurrenceOf (":", false, false).trim();
  24196. name = all.fromFirstOccurrenceOf (":", false, false).trim();
  24197. }
  24198. if (infoString != 0 && infoString[0] != 0)
  24199. {
  24200. DBG ("info: " + String ((const char*) infoString + 1, infoString[0]));
  24201. }
  24202. if (name.isEmpty())
  24203. name = "<Unknown>";
  24204. }
  24205. DisposeHandle (componentNameHandle);
  24206. DisposeHandle (componentInfoHandle);
  24207. }
  24208. }
  24209. static bool getComponentDescFromIdentifier (const String& fileOrIdentifier, ComponentDescription& desc,
  24210. String& name, String& version, String& manufacturer)
  24211. {
  24212. zerostruct (desc);
  24213. if (fileOrIdentifier.startsWithIgnoreCase (auIdentifierPrefix))
  24214. {
  24215. String s (fileOrIdentifier.substring (jmax (fileOrIdentifier.lastIndexOfChar (':'),
  24216. fileOrIdentifier.lastIndexOfChar ('/')) + 1));
  24217. StringArray tokens;
  24218. tokens.addTokens (s, ",", String::empty);
  24219. tokens.trim();
  24220. tokens.removeEmptyStrings();
  24221. if (tokens.size() == 3)
  24222. {
  24223. desc.componentType = stringToOSType (tokens[0]);
  24224. desc.componentSubType = stringToOSType (tokens[1]);
  24225. desc.componentManufacturer = stringToOSType (tokens[2]);
  24226. ComponentRecord* comp = FindNextComponent (0, &desc);
  24227. if (comp != 0)
  24228. {
  24229. getAUDetails (comp, name, manufacturer);
  24230. return true;
  24231. }
  24232. }
  24233. }
  24234. return false;
  24235. }
  24236. class AudioUnitPluginWindowCarbon;
  24237. class AudioUnitPluginWindowCocoa;
  24238. class AudioUnitPluginInstance : public AudioPluginInstance
  24239. {
  24240. public:
  24241. ~AudioUnitPluginInstance();
  24242. // AudioPluginInstance methods:
  24243. void fillInPluginDescription (PluginDescription& desc) const
  24244. {
  24245. desc.name = pluginName;
  24246. desc.fileOrIdentifier = createAUPluginIdentifier (componentDesc);
  24247. desc.uid = ((int) componentDesc.componentType)
  24248. ^ ((int) componentDesc.componentSubType)
  24249. ^ ((int) componentDesc.componentManufacturer);
  24250. desc.lastFileModTime = 0;
  24251. desc.pluginFormatName = "AudioUnit";
  24252. desc.category = getCategory();
  24253. desc.manufacturerName = manufacturer;
  24254. desc.version = version;
  24255. desc.numInputChannels = getNumInputChannels();
  24256. desc.numOutputChannels = getNumOutputChannels();
  24257. desc.isInstrument = (componentDesc.componentType == kAudioUnitType_MusicDevice);
  24258. }
  24259. const String getName() const { return pluginName; }
  24260. bool acceptsMidi() const { return wantsMidiMessages; }
  24261. bool producesMidi() const { return false; }
  24262. // AudioProcessor methods:
  24263. void prepareToPlay (double sampleRate, int estimatedSamplesPerBlock);
  24264. void releaseResources();
  24265. void processBlock (AudioSampleBuffer& buffer,
  24266. MidiBuffer& midiMessages);
  24267. AudioProcessorEditor* createEditor();
  24268. const String getInputChannelName (const int index) const;
  24269. bool isInputChannelStereoPair (int index) const;
  24270. const String getOutputChannelName (const int index) const;
  24271. bool isOutputChannelStereoPair (int index) const;
  24272. int getNumParameters();
  24273. float getParameter (int index);
  24274. void setParameter (int index, float newValue);
  24275. const String getParameterName (int index);
  24276. const String getParameterText (int index);
  24277. bool isParameterAutomatable (int index) const;
  24278. int getNumPrograms();
  24279. int getCurrentProgram();
  24280. void setCurrentProgram (int index);
  24281. const String getProgramName (int index);
  24282. void changeProgramName (int index, const String& newName);
  24283. void getStateInformation (MemoryBlock& destData);
  24284. void getCurrentProgramStateInformation (MemoryBlock& destData);
  24285. void setStateInformation (const void* data, int sizeInBytes);
  24286. void setCurrentProgramStateInformation (const void* data, int sizeInBytes);
  24287. juce_UseDebuggingNewOperator
  24288. private:
  24289. friend class AudioUnitPluginWindowCarbon;
  24290. friend class AudioUnitPluginWindowCocoa;
  24291. friend class AudioUnitPluginFormat;
  24292. ComponentDescription componentDesc;
  24293. String pluginName, manufacturer, version;
  24294. String fileOrIdentifier;
  24295. CriticalSection lock;
  24296. bool initialised, wantsMidiMessages, wasPlaying;
  24297. HeapBlock <AudioBufferList> outputBufferList;
  24298. AudioTimeStamp timeStamp;
  24299. AudioSampleBuffer* currentBuffer;
  24300. AudioUnit audioUnit;
  24301. Array <int> parameterIds;
  24302. bool getComponentDescFromFile (const String& fileOrIdentifier);
  24303. void initialise();
  24304. OSStatus renderGetInput (AudioUnitRenderActionFlags* ioActionFlags,
  24305. const AudioTimeStamp* inTimeStamp,
  24306. UInt32 inBusNumber,
  24307. UInt32 inNumberFrames,
  24308. AudioBufferList* ioData) const;
  24309. static OSStatus renderGetInputCallback (void* inRefCon,
  24310. AudioUnitRenderActionFlags* ioActionFlags,
  24311. const AudioTimeStamp* inTimeStamp,
  24312. UInt32 inBusNumber,
  24313. UInt32 inNumberFrames,
  24314. AudioBufferList* ioData)
  24315. {
  24316. return ((AudioUnitPluginInstance*) inRefCon)
  24317. ->renderGetInput (ioActionFlags, inTimeStamp, inBusNumber, inNumberFrames, ioData);
  24318. }
  24319. OSStatus getBeatAndTempo (Float64* outCurrentBeat, Float64* outCurrentTempo) const;
  24320. OSStatus getMusicalTimeLocation (UInt32* outDeltaSampleOffsetToNextBeat, Float32* outTimeSig_Numerator,
  24321. UInt32* outTimeSig_Denominator, Float64* outCurrentMeasureDownBeat) const;
  24322. OSStatus getTransportState (Boolean* outIsPlaying, Boolean* outTransportStateChanged,
  24323. Float64* outCurrentSampleInTimeLine, Boolean* outIsCycling,
  24324. Float64* outCycleStartBeat, Float64* outCycleEndBeat);
  24325. static OSStatus getBeatAndTempoCallback (void* inHostUserData, Float64* outCurrentBeat, Float64* outCurrentTempo)
  24326. {
  24327. return ((AudioUnitPluginInstance*) inHostUserData)->getBeatAndTempo (outCurrentBeat, outCurrentTempo);
  24328. }
  24329. static OSStatus getMusicalTimeLocationCallback (void* inHostUserData, UInt32* outDeltaSampleOffsetToNextBeat,
  24330. Float32* outTimeSig_Numerator, UInt32* outTimeSig_Denominator,
  24331. Float64* outCurrentMeasureDownBeat)
  24332. {
  24333. return ((AudioUnitPluginInstance*) inHostUserData)
  24334. ->getMusicalTimeLocation (outDeltaSampleOffsetToNextBeat, outTimeSig_Numerator,
  24335. outTimeSig_Denominator, outCurrentMeasureDownBeat);
  24336. }
  24337. static OSStatus getTransportStateCallback (void* inHostUserData, Boolean* outIsPlaying, Boolean* outTransportStateChanged,
  24338. Float64* outCurrentSampleInTimeLine, Boolean* outIsCycling,
  24339. Float64* outCycleStartBeat, Float64* outCycleEndBeat)
  24340. {
  24341. return ((AudioUnitPluginInstance*) inHostUserData)
  24342. ->getTransportState (outIsPlaying, outTransportStateChanged,
  24343. outCurrentSampleInTimeLine, outIsCycling,
  24344. outCycleStartBeat, outCycleEndBeat);
  24345. }
  24346. void getNumChannels (int& numIns, int& numOuts)
  24347. {
  24348. numIns = 0;
  24349. numOuts = 0;
  24350. AUChannelInfo supportedChannels [128];
  24351. UInt32 supportedChannelsSize = sizeof (supportedChannels);
  24352. if (AudioUnitGetProperty (audioUnit, kAudioUnitProperty_SupportedNumChannels, kAudioUnitScope_Global,
  24353. 0, supportedChannels, &supportedChannelsSize) == noErr
  24354. && supportedChannelsSize > 0)
  24355. {
  24356. for (int i = 0; i < supportedChannelsSize / sizeof (AUChannelInfo); ++i)
  24357. {
  24358. numIns = jmax (numIns, (int) supportedChannels[i].inChannels);
  24359. numOuts = jmax (numOuts, (int) supportedChannels[i].outChannels);
  24360. }
  24361. }
  24362. else
  24363. {
  24364. // (this really means the plugin will take any number of ins/outs as long
  24365. // as they are the same)
  24366. numIns = numOuts = 2;
  24367. }
  24368. }
  24369. const String getCategory() const;
  24370. AudioUnitPluginInstance (const String& fileOrIdentifier);
  24371. };
  24372. AudioUnitPluginInstance::AudioUnitPluginInstance (const String& fileOrIdentifier)
  24373. : fileOrIdentifier (fileOrIdentifier),
  24374. initialised (false),
  24375. wantsMidiMessages (false),
  24376. audioUnit (0),
  24377. currentBuffer (0)
  24378. {
  24379. try
  24380. {
  24381. ++insideCallback;
  24382. log ("Opening AU: " + fileOrIdentifier);
  24383. if (getComponentDescFromFile (fileOrIdentifier))
  24384. {
  24385. ComponentRecord* const comp = FindNextComponent (0, &componentDesc);
  24386. if (comp != 0)
  24387. {
  24388. audioUnit = (AudioUnit) OpenComponent (comp);
  24389. wantsMidiMessages = componentDesc.componentType == kAudioUnitType_MusicDevice
  24390. || componentDesc.componentType == kAudioUnitType_MusicEffect;
  24391. }
  24392. }
  24393. --insideCallback;
  24394. }
  24395. catch (...)
  24396. {
  24397. --insideCallback;
  24398. }
  24399. }
  24400. AudioUnitPluginInstance::~AudioUnitPluginInstance()
  24401. {
  24402. const ScopedLock sl (lock);
  24403. jassert (insideCallback == 0);
  24404. if (audioUnit != 0)
  24405. {
  24406. AudioUnitUninitialize (audioUnit);
  24407. CloseComponent (audioUnit);
  24408. audioUnit = 0;
  24409. }
  24410. }
  24411. bool AudioUnitPluginInstance::getComponentDescFromFile (const String& fileOrIdentifier)
  24412. {
  24413. zerostruct (componentDesc);
  24414. if (getComponentDescFromIdentifier (fileOrIdentifier, componentDesc, pluginName, version, manufacturer))
  24415. return true;
  24416. const File file (fileOrIdentifier);
  24417. if (! file.hasFileExtension (".component"))
  24418. return false;
  24419. const char* const utf8 = fileOrIdentifier.toUTF8();
  24420. CFURLRef url = CFURLCreateFromFileSystemRepresentation (0, (const UInt8*) utf8,
  24421. strlen (utf8), file.isDirectory());
  24422. if (url != 0)
  24423. {
  24424. CFBundleRef bundleRef = CFBundleCreate (kCFAllocatorDefault, url);
  24425. CFRelease (url);
  24426. if (bundleRef != 0)
  24427. {
  24428. CFTypeRef name = CFBundleGetValueForInfoDictionaryKey (bundleRef, CFSTR("CFBundleName"));
  24429. if (name != 0 && CFGetTypeID (name) == CFStringGetTypeID())
  24430. pluginName = PlatformUtilities::cfStringToJuceString ((CFStringRef) name);
  24431. if (pluginName.isEmpty())
  24432. pluginName = file.getFileNameWithoutExtension();
  24433. CFTypeRef versionString = CFBundleGetValueForInfoDictionaryKey (bundleRef, CFSTR("CFBundleVersion"));
  24434. if (versionString != 0 && CFGetTypeID (versionString) == CFStringGetTypeID())
  24435. version = PlatformUtilities::cfStringToJuceString ((CFStringRef) versionString);
  24436. CFTypeRef manuString = CFBundleGetValueForInfoDictionaryKey (bundleRef, CFSTR("CFBundleGetInfoString"));
  24437. if (manuString != 0 && CFGetTypeID (manuString) == CFStringGetTypeID())
  24438. manufacturer = PlatformUtilities::cfStringToJuceString ((CFStringRef) manuString);
  24439. short resFileId = CFBundleOpenBundleResourceMap (bundleRef);
  24440. UseResFile (resFileId);
  24441. for (int i = 1; i <= Count1Resources ('thng'); ++i)
  24442. {
  24443. Handle h = Get1IndResource ('thng', i);
  24444. if (h != 0)
  24445. {
  24446. HLock (h);
  24447. const uint32* const types = (const uint32*) *h;
  24448. if (types[0] == kAudioUnitType_MusicDevice
  24449. || types[0] == kAudioUnitType_MusicEffect
  24450. || types[0] == kAudioUnitType_Effect
  24451. || types[0] == kAudioUnitType_Generator
  24452. || types[0] == kAudioUnitType_Panner)
  24453. {
  24454. componentDesc.componentType = types[0];
  24455. componentDesc.componentSubType = types[1];
  24456. componentDesc.componentManufacturer = types[2];
  24457. break;
  24458. }
  24459. HUnlock (h);
  24460. ReleaseResource (h);
  24461. }
  24462. }
  24463. CFBundleCloseBundleResourceMap (bundleRef, resFileId);
  24464. CFRelease (bundleRef);
  24465. }
  24466. }
  24467. return componentDesc.componentType != 0 && componentDesc.componentSubType != 0;
  24468. }
  24469. void AudioUnitPluginInstance::initialise()
  24470. {
  24471. if (initialised || audioUnit == 0)
  24472. return;
  24473. log ("Initialising AU: " + pluginName);
  24474. parameterIds.clear();
  24475. {
  24476. UInt32 paramListSize = 0;
  24477. AudioUnitGetProperty (audioUnit, kAudioUnitProperty_ParameterList, kAudioUnitScope_Global,
  24478. 0, 0, &paramListSize);
  24479. if (paramListSize > 0)
  24480. {
  24481. parameterIds.insertMultiple (0, 0, paramListSize / sizeof (int));
  24482. AudioUnitGetProperty (audioUnit, kAudioUnitProperty_ParameterList, kAudioUnitScope_Global,
  24483. 0, &parameterIds.getReference(0), &paramListSize);
  24484. }
  24485. }
  24486. {
  24487. AURenderCallbackStruct info;
  24488. zerostruct (info);
  24489. info.inputProcRefCon = this;
  24490. info.inputProc = renderGetInputCallback;
  24491. AudioUnitSetProperty (audioUnit, kAudioUnitProperty_SetRenderCallback, kAudioUnitScope_Input,
  24492. 0, &info, sizeof (info));
  24493. }
  24494. {
  24495. HostCallbackInfo info;
  24496. zerostruct (info);
  24497. info.hostUserData = this;
  24498. info.beatAndTempoProc = getBeatAndTempoCallback;
  24499. info.musicalTimeLocationProc = getMusicalTimeLocationCallback;
  24500. info.transportStateProc = getTransportStateCallback;
  24501. AudioUnitSetProperty (audioUnit, kAudioUnitProperty_HostCallbacks, kAudioUnitScope_Global,
  24502. 0, &info, sizeof (info));
  24503. }
  24504. int numIns, numOuts;
  24505. getNumChannels (numIns, numOuts);
  24506. setPlayConfigDetails (numIns, numOuts, 0, 0);
  24507. initialised = AudioUnitInitialize (audioUnit) == noErr;
  24508. setLatencySamples (0);
  24509. }
  24510. void AudioUnitPluginInstance::prepareToPlay (double sampleRate_,
  24511. int samplesPerBlockExpected)
  24512. {
  24513. initialise();
  24514. if (initialised)
  24515. {
  24516. int numIns, numOuts;
  24517. getNumChannels (numIns, numOuts);
  24518. setPlayConfigDetails (numIns, numOuts, sampleRate_, samplesPerBlockExpected);
  24519. Float64 latencySecs = 0.0;
  24520. UInt32 latencySize = sizeof (latencySecs);
  24521. AudioUnitGetProperty (audioUnit, kAudioUnitProperty_Latency, kAudioUnitScope_Global,
  24522. 0, &latencySecs, &latencySize);
  24523. setLatencySamples (roundToInt (latencySecs * sampleRate_));
  24524. AudioUnitReset (audioUnit, kAudioUnitScope_Input, 0);
  24525. AudioUnitReset (audioUnit, kAudioUnitScope_Output, 0);
  24526. AudioUnitReset (audioUnit, kAudioUnitScope_Global, 0);
  24527. AudioStreamBasicDescription stream;
  24528. zerostruct (stream);
  24529. stream.mSampleRate = sampleRate_;
  24530. stream.mFormatID = kAudioFormatLinearPCM;
  24531. stream.mFormatFlags = kAudioFormatFlagsNativeFloatPacked | kAudioFormatFlagIsNonInterleaved;
  24532. stream.mFramesPerPacket = 1;
  24533. stream.mBytesPerPacket = 4;
  24534. stream.mBytesPerFrame = 4;
  24535. stream.mBitsPerChannel = 32;
  24536. stream.mChannelsPerFrame = numIns;
  24537. OSStatus err = AudioUnitSetProperty (audioUnit,
  24538. kAudioUnitProperty_StreamFormat,
  24539. kAudioUnitScope_Input,
  24540. 0, &stream, sizeof (stream));
  24541. stream.mChannelsPerFrame = numOuts;
  24542. err = AudioUnitSetProperty (audioUnit,
  24543. kAudioUnitProperty_StreamFormat,
  24544. kAudioUnitScope_Output,
  24545. 0, &stream, sizeof (stream));
  24546. outputBufferList.calloc (sizeof (AudioBufferList) + sizeof (AudioBuffer) * (numOuts + 1), 1);
  24547. outputBufferList->mNumberBuffers = numOuts;
  24548. for (int i = numOuts; --i >= 0;)
  24549. outputBufferList->mBuffers[i].mNumberChannels = 1;
  24550. zerostruct (timeStamp);
  24551. timeStamp.mSampleTime = 0;
  24552. timeStamp.mHostTime = AudioGetCurrentHostTime();
  24553. timeStamp.mFlags = kAudioTimeStampSampleTimeValid | kAudioTimeStampHostTimeValid;
  24554. currentBuffer = 0;
  24555. wasPlaying = false;
  24556. }
  24557. }
  24558. void AudioUnitPluginInstance::releaseResources()
  24559. {
  24560. if (initialised)
  24561. {
  24562. AudioUnitReset (audioUnit, kAudioUnitScope_Input, 0);
  24563. AudioUnitReset (audioUnit, kAudioUnitScope_Output, 0);
  24564. AudioUnitReset (audioUnit, kAudioUnitScope_Global, 0);
  24565. outputBufferList.free();
  24566. currentBuffer = 0;
  24567. }
  24568. }
  24569. OSStatus AudioUnitPluginInstance::renderGetInput (AudioUnitRenderActionFlags* ioActionFlags,
  24570. const AudioTimeStamp* inTimeStamp,
  24571. UInt32 inBusNumber,
  24572. UInt32 inNumberFrames,
  24573. AudioBufferList* ioData) const
  24574. {
  24575. if (inBusNumber == 0
  24576. && currentBuffer != 0)
  24577. {
  24578. jassert (inNumberFrames == currentBuffer->getNumSamples()); // if this ever happens, might need to add extra handling
  24579. for (int i = 0; i < ioData->mNumberBuffers; ++i)
  24580. {
  24581. if (i < currentBuffer->getNumChannels())
  24582. {
  24583. memcpy (ioData->mBuffers[i].mData,
  24584. currentBuffer->getSampleData (i, 0),
  24585. sizeof (float) * inNumberFrames);
  24586. }
  24587. else
  24588. {
  24589. zeromem (ioData->mBuffers[i].mData, sizeof (float) * inNumberFrames);
  24590. }
  24591. }
  24592. }
  24593. return noErr;
  24594. }
  24595. void AudioUnitPluginInstance::processBlock (AudioSampleBuffer& buffer,
  24596. MidiBuffer& midiMessages)
  24597. {
  24598. const int numSamples = buffer.getNumSamples();
  24599. if (initialised)
  24600. {
  24601. AudioUnitRenderActionFlags flags = 0;
  24602. timeStamp.mHostTime = AudioGetCurrentHostTime();
  24603. for (int i = getNumOutputChannels(); --i >= 0;)
  24604. {
  24605. outputBufferList->mBuffers[i].mDataByteSize = sizeof (float) * numSamples;
  24606. outputBufferList->mBuffers[i].mData = buffer.getSampleData (i, 0);
  24607. }
  24608. currentBuffer = &buffer;
  24609. if (wantsMidiMessages)
  24610. {
  24611. const uint8* midiEventData;
  24612. int midiEventSize, midiEventPosition;
  24613. MidiBuffer::Iterator i (midiMessages);
  24614. while (i.getNextEvent (midiEventData, midiEventSize, midiEventPosition))
  24615. {
  24616. if (midiEventSize <= 3)
  24617. MusicDeviceMIDIEvent (audioUnit,
  24618. midiEventData[0], midiEventData[1], midiEventData[2],
  24619. midiEventPosition);
  24620. else
  24621. MusicDeviceSysEx (audioUnit, midiEventData, midiEventSize);
  24622. }
  24623. midiMessages.clear();
  24624. }
  24625. AudioUnitRender (audioUnit, &flags, &timeStamp,
  24626. 0, numSamples, outputBufferList);
  24627. timeStamp.mSampleTime += numSamples;
  24628. }
  24629. else
  24630. {
  24631. // Not initialised, so just bypass..
  24632. for (int i = getNumInputChannels(); i < getNumOutputChannels(); ++i)
  24633. buffer.clear (i, 0, buffer.getNumSamples());
  24634. }
  24635. }
  24636. OSStatus AudioUnitPluginInstance::getBeatAndTempo (Float64* outCurrentBeat, Float64* outCurrentTempo) const
  24637. {
  24638. AudioPlayHead* const ph = getPlayHead();
  24639. AudioPlayHead::CurrentPositionInfo result;
  24640. if (ph != 0 && ph->getCurrentPosition (result))
  24641. {
  24642. if (outCurrentBeat != 0)
  24643. *outCurrentBeat = result.ppqPosition;
  24644. if (outCurrentTempo != 0)
  24645. *outCurrentTempo = result.bpm;
  24646. }
  24647. else
  24648. {
  24649. if (outCurrentBeat != 0)
  24650. *outCurrentBeat = 0;
  24651. if (outCurrentTempo != 0)
  24652. *outCurrentTempo = 120.0;
  24653. }
  24654. return noErr;
  24655. }
  24656. OSStatus AudioUnitPluginInstance::getMusicalTimeLocation (UInt32* outDeltaSampleOffsetToNextBeat,
  24657. Float32* outTimeSig_Numerator,
  24658. UInt32* outTimeSig_Denominator,
  24659. Float64* outCurrentMeasureDownBeat) const
  24660. {
  24661. AudioPlayHead* const ph = getPlayHead();
  24662. AudioPlayHead::CurrentPositionInfo result;
  24663. if (ph != 0 && ph->getCurrentPosition (result))
  24664. {
  24665. if (outTimeSig_Numerator != 0)
  24666. *outTimeSig_Numerator = result.timeSigNumerator;
  24667. if (outTimeSig_Denominator != 0)
  24668. *outTimeSig_Denominator = result.timeSigDenominator;
  24669. if (outDeltaSampleOffsetToNextBeat != 0)
  24670. *outDeltaSampleOffsetToNextBeat = 0; //xxx
  24671. if (outCurrentMeasureDownBeat != 0)
  24672. *outCurrentMeasureDownBeat = result.ppqPositionOfLastBarStart; //xxx wrong
  24673. }
  24674. else
  24675. {
  24676. if (outDeltaSampleOffsetToNextBeat != 0)
  24677. *outDeltaSampleOffsetToNextBeat = 0;
  24678. if (outTimeSig_Numerator != 0)
  24679. *outTimeSig_Numerator = 4;
  24680. if (outTimeSig_Denominator != 0)
  24681. *outTimeSig_Denominator = 4;
  24682. if (outCurrentMeasureDownBeat != 0)
  24683. *outCurrentMeasureDownBeat = 0;
  24684. }
  24685. return noErr;
  24686. }
  24687. OSStatus AudioUnitPluginInstance::getTransportState (Boolean* outIsPlaying,
  24688. Boolean* outTransportStateChanged,
  24689. Float64* outCurrentSampleInTimeLine,
  24690. Boolean* outIsCycling,
  24691. Float64* outCycleStartBeat,
  24692. Float64* outCycleEndBeat)
  24693. {
  24694. AudioPlayHead* const ph = getPlayHead();
  24695. AudioPlayHead::CurrentPositionInfo result;
  24696. if (ph != 0 && ph->getCurrentPosition (result))
  24697. {
  24698. if (outIsPlaying != 0)
  24699. *outIsPlaying = result.isPlaying;
  24700. if (outTransportStateChanged != 0)
  24701. {
  24702. *outTransportStateChanged = result.isPlaying != wasPlaying;
  24703. wasPlaying = result.isPlaying;
  24704. }
  24705. if (outCurrentSampleInTimeLine != 0)
  24706. *outCurrentSampleInTimeLine = roundToInt (result.timeInSeconds * getSampleRate());
  24707. if (outIsCycling != 0)
  24708. *outIsCycling = false;
  24709. if (outCycleStartBeat != 0)
  24710. *outCycleStartBeat = 0;
  24711. if (outCycleEndBeat != 0)
  24712. *outCycleEndBeat = 0;
  24713. }
  24714. else
  24715. {
  24716. if (outIsPlaying != 0)
  24717. *outIsPlaying = false;
  24718. if (outTransportStateChanged != 0)
  24719. *outTransportStateChanged = false;
  24720. if (outCurrentSampleInTimeLine != 0)
  24721. *outCurrentSampleInTimeLine = 0;
  24722. if (outIsCycling != 0)
  24723. *outIsCycling = false;
  24724. if (outCycleStartBeat != 0)
  24725. *outCycleStartBeat = 0;
  24726. if (outCycleEndBeat != 0)
  24727. *outCycleEndBeat = 0;
  24728. }
  24729. return noErr;
  24730. }
  24731. static VoidArray activeWindows;
  24732. class AudioUnitPluginWindowCocoa : public AudioProcessorEditor
  24733. {
  24734. public:
  24735. AudioUnitPluginWindowCocoa (AudioUnitPluginInstance& plugin_, const bool createGenericViewIfNeeded)
  24736. : AudioProcessorEditor (&plugin_),
  24737. plugin (plugin_),
  24738. wrapper (0)
  24739. {
  24740. addAndMakeVisible (wrapper = new NSViewComponent());
  24741. activeWindows.add (this);
  24742. setOpaque (true);
  24743. setVisible (true);
  24744. setSize (100, 100);
  24745. createView (createGenericViewIfNeeded);
  24746. }
  24747. ~AudioUnitPluginWindowCocoa()
  24748. {
  24749. const bool wasValid = isValid();
  24750. wrapper->setView (0);
  24751. activeWindows.removeValue (this);
  24752. if (wasValid)
  24753. plugin.editorBeingDeleted (this);
  24754. delete wrapper;
  24755. }
  24756. bool isValid() const { return wrapper->getView() != 0; }
  24757. void paint (Graphics& g)
  24758. {
  24759. g.fillAll (Colours::white);
  24760. }
  24761. void resized()
  24762. {
  24763. wrapper->setSize (getWidth(), getHeight());
  24764. }
  24765. private:
  24766. AudioUnitPluginInstance& plugin;
  24767. NSViewComponent* wrapper;
  24768. bool createView (const bool createGenericViewIfNeeded)
  24769. {
  24770. NSView* pluginView = 0;
  24771. UInt32 dataSize = 0;
  24772. Boolean isWritable = false;
  24773. if (AudioUnitGetPropertyInfo (plugin.audioUnit, kAudioUnitProperty_CocoaUI, kAudioUnitScope_Global,
  24774. 0, &dataSize, &isWritable) == noErr
  24775. && dataSize != 0
  24776. && AudioUnitGetPropertyInfo (plugin.audioUnit, kAudioUnitProperty_CocoaUI, kAudioUnitScope_Global,
  24777. 0, &dataSize, &isWritable) == noErr)
  24778. {
  24779. HeapBlock <AudioUnitCocoaViewInfo> info;
  24780. info.calloc (dataSize, 1);
  24781. if (AudioUnitGetProperty (plugin.audioUnit, kAudioUnitProperty_CocoaUI, kAudioUnitScope_Global,
  24782. 0, info, &dataSize) == noErr)
  24783. {
  24784. NSString* viewClassName = (NSString*) (info->mCocoaAUViewClass[0]);
  24785. NSString* path = (NSString*) CFURLCopyPath (info->mCocoaAUViewBundleLocation);
  24786. NSBundle* viewBundle = [NSBundle bundleWithPath: [path autorelease]];
  24787. Class viewClass = [viewBundle classNamed: viewClassName];
  24788. if ([viewClass conformsToProtocol: @protocol (AUCocoaUIBase)]
  24789. && [viewClass instancesRespondToSelector: @selector (interfaceVersion)]
  24790. && [viewClass instancesRespondToSelector: @selector (uiViewForAudioUnit: withSize:)])
  24791. {
  24792. id factory = [[[viewClass alloc] init] autorelease];
  24793. pluginView = [factory uiViewForAudioUnit: plugin.audioUnit
  24794. withSize: NSMakeSize (getWidth(), getHeight())];
  24795. }
  24796. for (int i = (dataSize - sizeof (CFURLRef)) / sizeof (CFStringRef); --i >= 0;)
  24797. {
  24798. CFRelease (info->mCocoaAUViewClass[i]);
  24799. CFRelease (info->mCocoaAUViewBundleLocation);
  24800. }
  24801. }
  24802. }
  24803. if (createGenericViewIfNeeded && (pluginView == 0))
  24804. pluginView = [[AUGenericView alloc] initWithAudioUnit: plugin.audioUnit];
  24805. wrapper->setView (pluginView);
  24806. if (pluginView != 0)
  24807. setSize ([pluginView frame].size.width,
  24808. [pluginView frame].size.height);
  24809. return pluginView != 0;
  24810. }
  24811. };
  24812. #if JUCE_SUPPORT_CARBON
  24813. class AudioUnitPluginWindowCarbon : public AudioProcessorEditor
  24814. {
  24815. public:
  24816. AudioUnitPluginWindowCarbon (AudioUnitPluginInstance& plugin_)
  24817. : AudioProcessorEditor (&plugin_),
  24818. plugin (plugin_),
  24819. viewComponent (0)
  24820. {
  24821. addAndMakeVisible (innerWrapper = new InnerWrapperComponent (this));
  24822. activeWindows.add (this);
  24823. setOpaque (true);
  24824. setVisible (true);
  24825. setSize (400, 300);
  24826. ComponentDescription viewList [16];
  24827. UInt32 viewListSize = sizeof (viewList);
  24828. AudioUnitGetProperty (plugin.audioUnit, kAudioUnitProperty_GetUIComponentList, kAudioUnitScope_Global,
  24829. 0, &viewList, &viewListSize);
  24830. componentRecord = FindNextComponent (0, &viewList[0]);
  24831. }
  24832. ~AudioUnitPluginWindowCarbon()
  24833. {
  24834. innerWrapper = 0;
  24835. activeWindows.removeValue (this);
  24836. if (isValid())
  24837. plugin.editorBeingDeleted (this);
  24838. }
  24839. bool isValid() const throw() { return componentRecord != 0; }
  24840. void paint (Graphics& g)
  24841. {
  24842. g.fillAll (Colours::black);
  24843. }
  24844. void resized()
  24845. {
  24846. innerWrapper->setSize (getWidth(), getHeight());
  24847. }
  24848. bool keyStateChanged (bool)
  24849. {
  24850. return false;
  24851. }
  24852. bool keyPressed (const KeyPress&)
  24853. {
  24854. return false;
  24855. }
  24856. void broughtToFront()
  24857. {
  24858. activeWindows.removeValue (this);
  24859. activeWindows.add (this);
  24860. }
  24861. AudioUnit getAudioUnit() const { return plugin.audioUnit; }
  24862. AudioUnitCarbonView getViewComponent()
  24863. {
  24864. if (viewComponent == 0 && componentRecord != 0)
  24865. viewComponent = (AudioUnitCarbonView) OpenComponent (componentRecord);
  24866. return viewComponent;
  24867. }
  24868. void closeViewComponent()
  24869. {
  24870. if (viewComponent != 0)
  24871. {
  24872. CloseComponent (viewComponent);
  24873. viewComponent = 0;
  24874. }
  24875. }
  24876. juce_UseDebuggingNewOperator
  24877. private:
  24878. AudioUnitPluginInstance& plugin;
  24879. ComponentRecord* componentRecord;
  24880. AudioUnitCarbonView viewComponent;
  24881. class InnerWrapperComponent : public CarbonViewWrapperComponent
  24882. {
  24883. public:
  24884. InnerWrapperComponent (AudioUnitPluginWindowCarbon* const owner_)
  24885. : owner (owner_)
  24886. {
  24887. }
  24888. ~InnerWrapperComponent()
  24889. {
  24890. deleteWindow();
  24891. }
  24892. HIViewRef attachView (WindowRef windowRef, HIViewRef rootView)
  24893. {
  24894. log ("Opening AU GUI: " + owner->plugin.getName());
  24895. AudioUnitCarbonView viewComponent = owner->getViewComponent();
  24896. if (viewComponent == 0)
  24897. return 0;
  24898. Float32Point pos = { 0, 0 };
  24899. Float32Point size = { 250, 200 };
  24900. HIViewRef pluginView = 0;
  24901. AudioUnitCarbonViewCreate (viewComponent,
  24902. owner->getAudioUnit(),
  24903. windowRef,
  24904. rootView,
  24905. &pos,
  24906. &size,
  24907. (ControlRef*) &pluginView);
  24908. return pluginView;
  24909. }
  24910. void removeView (HIViewRef)
  24911. {
  24912. log ("Closing AU GUI: " + owner->plugin.getName());
  24913. owner->closeViewComponent();
  24914. }
  24915. private:
  24916. AudioUnitPluginWindowCarbon* const owner;
  24917. };
  24918. friend class InnerWrapperComponent;
  24919. ScopedPointer<InnerWrapperComponent> innerWrapper;
  24920. };
  24921. #endif
  24922. AudioProcessorEditor* AudioUnitPluginInstance::createEditor()
  24923. {
  24924. ScopedPointer<AudioProcessorEditor> w (new AudioUnitPluginWindowCocoa (*this, false));
  24925. if (! static_cast <AudioUnitPluginWindowCocoa*> (static_cast <AudioProcessorEditor*> (w))->isValid())
  24926. w = 0;
  24927. #if JUCE_SUPPORT_CARBON
  24928. if (w == 0)
  24929. {
  24930. w = new AudioUnitPluginWindowCarbon (*this);
  24931. if (! static_cast <AudioUnitPluginWindowCarbon*> (static_cast <AudioProcessorEditor*> (w))->isValid())
  24932. w = 0;
  24933. }
  24934. #endif
  24935. if (w == 0)
  24936. w = new AudioUnitPluginWindowCocoa (*this, true); // use AUGenericView as a fallback
  24937. return w.release();
  24938. }
  24939. const String AudioUnitPluginInstance::getCategory() const
  24940. {
  24941. const char* result = 0;
  24942. switch (componentDesc.componentType)
  24943. {
  24944. case kAudioUnitType_Effect:
  24945. case kAudioUnitType_MusicEffect:
  24946. result = "Effect";
  24947. break;
  24948. case kAudioUnitType_MusicDevice:
  24949. result = "Synth";
  24950. break;
  24951. case kAudioUnitType_Generator:
  24952. result = "Generator";
  24953. break;
  24954. case kAudioUnitType_Panner:
  24955. result = "Panner";
  24956. break;
  24957. default:
  24958. break;
  24959. }
  24960. return result;
  24961. }
  24962. int AudioUnitPluginInstance::getNumParameters()
  24963. {
  24964. return parameterIds.size();
  24965. }
  24966. float AudioUnitPluginInstance::getParameter (int index)
  24967. {
  24968. const ScopedLock sl (lock);
  24969. Float32 value = 0.0f;
  24970. if (audioUnit != 0 && ((unsigned int) index) < (unsigned int) parameterIds.size())
  24971. {
  24972. AudioUnitGetParameter (audioUnit,
  24973. (UInt32) parameterIds.getUnchecked (index),
  24974. kAudioUnitScope_Global, 0,
  24975. &value);
  24976. }
  24977. return value;
  24978. }
  24979. void AudioUnitPluginInstance::setParameter (int index, float newValue)
  24980. {
  24981. const ScopedLock sl (lock);
  24982. if (audioUnit != 0 && ((unsigned int) index) < (unsigned int) parameterIds.size())
  24983. {
  24984. AudioUnitSetParameter (audioUnit,
  24985. (UInt32) parameterIds.getUnchecked (index),
  24986. kAudioUnitScope_Global, 0,
  24987. newValue, 0);
  24988. }
  24989. }
  24990. const String AudioUnitPluginInstance::getParameterName (int index)
  24991. {
  24992. AudioUnitParameterInfo info;
  24993. zerostruct (info);
  24994. UInt32 sz = sizeof (info);
  24995. String name;
  24996. if (AudioUnitGetProperty (audioUnit,
  24997. kAudioUnitProperty_ParameterInfo,
  24998. kAudioUnitScope_Global,
  24999. parameterIds [index], &info, &sz) == noErr)
  25000. {
  25001. if ((info.flags & kAudioUnitParameterFlag_HasCFNameString) != 0)
  25002. name = PlatformUtilities::cfStringToJuceString (info.cfNameString);
  25003. else
  25004. name = String (info.name, sizeof (info.name));
  25005. }
  25006. return name;
  25007. }
  25008. const String AudioUnitPluginInstance::getParameterText (int index)
  25009. {
  25010. return String (getParameter (index));
  25011. }
  25012. bool AudioUnitPluginInstance::isParameterAutomatable (int index) const
  25013. {
  25014. AudioUnitParameterInfo info;
  25015. UInt32 sz = sizeof (info);
  25016. if (AudioUnitGetProperty (audioUnit,
  25017. kAudioUnitProperty_ParameterInfo,
  25018. kAudioUnitScope_Global,
  25019. parameterIds [index], &info, &sz) == noErr)
  25020. {
  25021. return (info.flags & kAudioUnitParameterFlag_NonRealTime) == 0;
  25022. }
  25023. return true;
  25024. }
  25025. int AudioUnitPluginInstance::getNumPrograms()
  25026. {
  25027. CFArrayRef presets;
  25028. UInt32 sz = sizeof (CFArrayRef);
  25029. int num = 0;
  25030. if (AudioUnitGetProperty (audioUnit,
  25031. kAudioUnitProperty_FactoryPresets,
  25032. kAudioUnitScope_Global,
  25033. 0, &presets, &sz) == noErr)
  25034. {
  25035. num = (int) CFArrayGetCount (presets);
  25036. CFRelease (presets);
  25037. }
  25038. return num;
  25039. }
  25040. int AudioUnitPluginInstance::getCurrentProgram()
  25041. {
  25042. AUPreset current;
  25043. current.presetNumber = 0;
  25044. UInt32 sz = sizeof (AUPreset);
  25045. AudioUnitGetProperty (audioUnit,
  25046. kAudioUnitProperty_FactoryPresets,
  25047. kAudioUnitScope_Global,
  25048. 0, &current, &sz);
  25049. return current.presetNumber;
  25050. }
  25051. void AudioUnitPluginInstance::setCurrentProgram (int newIndex)
  25052. {
  25053. AUPreset current;
  25054. current.presetNumber = newIndex;
  25055. current.presetName = 0;
  25056. AudioUnitSetProperty (audioUnit,
  25057. kAudioUnitProperty_FactoryPresets,
  25058. kAudioUnitScope_Global,
  25059. 0, &current, sizeof (AUPreset));
  25060. }
  25061. const String AudioUnitPluginInstance::getProgramName (int index)
  25062. {
  25063. String s;
  25064. CFArrayRef presets;
  25065. UInt32 sz = sizeof (CFArrayRef);
  25066. if (AudioUnitGetProperty (audioUnit,
  25067. kAudioUnitProperty_FactoryPresets,
  25068. kAudioUnitScope_Global,
  25069. 0, &presets, &sz) == noErr)
  25070. {
  25071. for (CFIndex i = 0; i < CFArrayGetCount (presets); ++i)
  25072. {
  25073. const AUPreset* p = (const AUPreset*) CFArrayGetValueAtIndex (presets, i);
  25074. if (p != 0 && p->presetNumber == index)
  25075. {
  25076. s = PlatformUtilities::cfStringToJuceString (p->presetName);
  25077. break;
  25078. }
  25079. }
  25080. CFRelease (presets);
  25081. }
  25082. return s;
  25083. }
  25084. void AudioUnitPluginInstance::changeProgramName (int index, const String& newName)
  25085. {
  25086. jassertfalse // xxx not implemented!
  25087. }
  25088. const String AudioUnitPluginInstance::getInputChannelName (const int index) const
  25089. {
  25090. if (((unsigned int) index) < (unsigned int) getNumInputChannels())
  25091. return "Input " + String (index + 1);
  25092. return String::empty;
  25093. }
  25094. bool AudioUnitPluginInstance::isInputChannelStereoPair (int index) const
  25095. {
  25096. if (((unsigned int) index) >= (unsigned int) getNumInputChannels())
  25097. return false;
  25098. return true;
  25099. }
  25100. const String AudioUnitPluginInstance::getOutputChannelName (const int index) const
  25101. {
  25102. if (((unsigned int) index) < (unsigned int) getNumOutputChannels())
  25103. return "Output " + String (index + 1);
  25104. return String::empty;
  25105. }
  25106. bool AudioUnitPluginInstance::isOutputChannelStereoPair (int index) const
  25107. {
  25108. if (((unsigned int) index) >= (unsigned int) getNumOutputChannels())
  25109. return false;
  25110. return true;
  25111. }
  25112. void AudioUnitPluginInstance::getStateInformation (MemoryBlock& destData)
  25113. {
  25114. getCurrentProgramStateInformation (destData);
  25115. }
  25116. void AudioUnitPluginInstance::getCurrentProgramStateInformation (MemoryBlock& destData)
  25117. {
  25118. CFPropertyListRef propertyList = 0;
  25119. UInt32 sz = sizeof (CFPropertyListRef);
  25120. if (AudioUnitGetProperty (audioUnit,
  25121. kAudioUnitProperty_ClassInfo,
  25122. kAudioUnitScope_Global,
  25123. 0, &propertyList, &sz) == noErr)
  25124. {
  25125. CFWriteStreamRef stream = CFWriteStreamCreateWithAllocatedBuffers (kCFAllocatorDefault, kCFAllocatorDefault);
  25126. CFWriteStreamOpen (stream);
  25127. CFIndex bytesWritten = CFPropertyListWriteToStream (propertyList, stream, kCFPropertyListBinaryFormat_v1_0, 0);
  25128. CFWriteStreamClose (stream);
  25129. CFDataRef data = (CFDataRef) CFWriteStreamCopyProperty (stream, kCFStreamPropertyDataWritten);
  25130. destData.setSize (bytesWritten);
  25131. destData.copyFrom (CFDataGetBytePtr (data), 0, destData.getSize());
  25132. CFRelease (data);
  25133. CFRelease (stream);
  25134. CFRelease (propertyList);
  25135. }
  25136. }
  25137. void AudioUnitPluginInstance::setStateInformation (const void* data, int sizeInBytes)
  25138. {
  25139. setCurrentProgramStateInformation (data, sizeInBytes);
  25140. }
  25141. void AudioUnitPluginInstance::setCurrentProgramStateInformation (const void* data, int sizeInBytes)
  25142. {
  25143. CFReadStreamRef stream = CFReadStreamCreateWithBytesNoCopy (kCFAllocatorDefault,
  25144. (const UInt8*) data,
  25145. sizeInBytes,
  25146. kCFAllocatorNull);
  25147. CFReadStreamOpen (stream);
  25148. CFPropertyListFormat format = kCFPropertyListBinaryFormat_v1_0;
  25149. CFPropertyListRef propertyList = CFPropertyListCreateFromStream (kCFAllocatorDefault,
  25150. stream,
  25151. 0,
  25152. kCFPropertyListImmutable,
  25153. &format,
  25154. 0);
  25155. CFRelease (stream);
  25156. if (propertyList != 0)
  25157. AudioUnitSetProperty (audioUnit,
  25158. kAudioUnitProperty_ClassInfo,
  25159. kAudioUnitScope_Global,
  25160. 0, &propertyList, sizeof (propertyList));
  25161. }
  25162. AudioUnitPluginFormat::AudioUnitPluginFormat()
  25163. {
  25164. }
  25165. AudioUnitPluginFormat::~AudioUnitPluginFormat()
  25166. {
  25167. }
  25168. void AudioUnitPluginFormat::findAllTypesForFile (OwnedArray <PluginDescription>& results,
  25169. const String& fileOrIdentifier)
  25170. {
  25171. if (! fileMightContainThisPluginType (fileOrIdentifier))
  25172. return;
  25173. PluginDescription desc;
  25174. desc.fileOrIdentifier = fileOrIdentifier;
  25175. desc.uid = 0;
  25176. try
  25177. {
  25178. ScopedPointer <AudioPluginInstance> createdInstance (createInstanceFromDescription (desc));
  25179. AudioUnitPluginInstance* const auInstance = dynamic_cast <AudioUnitPluginInstance*> ((AudioPluginInstance*) createdInstance);
  25180. if (auInstance != 0)
  25181. {
  25182. auInstance->fillInPluginDescription (desc);
  25183. results.add (new PluginDescription (desc));
  25184. }
  25185. }
  25186. catch (...)
  25187. {
  25188. // crashed while loading...
  25189. }
  25190. }
  25191. AudioPluginInstance* AudioUnitPluginFormat::createInstanceFromDescription (const PluginDescription& desc)
  25192. {
  25193. if (fileMightContainThisPluginType (desc.fileOrIdentifier))
  25194. {
  25195. ScopedPointer <AudioUnitPluginInstance> result (new AudioUnitPluginInstance (desc.fileOrIdentifier));
  25196. if (result->audioUnit != 0)
  25197. {
  25198. result->initialise();
  25199. return result.release();
  25200. }
  25201. }
  25202. return 0;
  25203. }
  25204. const StringArray AudioUnitPluginFormat::searchPathsForPlugins (const FileSearchPath& /*directoriesToSearch*/,
  25205. const bool /*recursive*/)
  25206. {
  25207. StringArray result;
  25208. ComponentRecord* comp = 0;
  25209. ComponentDescription desc;
  25210. zerostruct (desc);
  25211. for (;;)
  25212. {
  25213. zerostruct (desc);
  25214. comp = FindNextComponent (comp, &desc);
  25215. if (comp == 0)
  25216. break;
  25217. GetComponentInfo (comp, &desc, 0, 0, 0);
  25218. if (desc.componentType == kAudioUnitType_MusicDevice
  25219. || desc.componentType == kAudioUnitType_MusicEffect
  25220. || desc.componentType == kAudioUnitType_Effect
  25221. || desc.componentType == kAudioUnitType_Generator
  25222. || desc.componentType == kAudioUnitType_Panner)
  25223. {
  25224. const String s (createAUPluginIdentifier (desc));
  25225. DBG (s);
  25226. result.add (s);
  25227. }
  25228. }
  25229. return result;
  25230. }
  25231. bool AudioUnitPluginFormat::fileMightContainThisPluginType (const String& fileOrIdentifier)
  25232. {
  25233. ComponentDescription desc;
  25234. String name, version, manufacturer;
  25235. if (getComponentDescFromIdentifier (fileOrIdentifier, desc, name, version, manufacturer))
  25236. return FindNextComponent (0, &desc) != 0;
  25237. const File f (fileOrIdentifier);
  25238. return f.hasFileExtension (".component")
  25239. && f.isDirectory();
  25240. }
  25241. const String AudioUnitPluginFormat::getNameOfPluginFromIdentifier (const String& fileOrIdentifier)
  25242. {
  25243. ComponentDescription desc;
  25244. String name, version, manufacturer;
  25245. getComponentDescFromIdentifier (fileOrIdentifier, desc, name, version, manufacturer);
  25246. if (name.isEmpty())
  25247. name = fileOrIdentifier;
  25248. return name;
  25249. }
  25250. bool AudioUnitPluginFormat::doesPluginStillExist (const PluginDescription& desc)
  25251. {
  25252. if (desc.fileOrIdentifier.startsWithIgnoreCase (auIdentifierPrefix))
  25253. return fileMightContainThisPluginType (desc.fileOrIdentifier);
  25254. else
  25255. return File (desc.fileOrIdentifier).exists();
  25256. }
  25257. const FileSearchPath AudioUnitPluginFormat::getDefaultLocationsToSearch()
  25258. {
  25259. return FileSearchPath ("/(Default AudioUnit locations)");
  25260. }
  25261. #endif
  25262. END_JUCE_NAMESPACE
  25263. #undef log
  25264. #endif
  25265. /*** End of inlined file: juce_AudioUnitPluginFormat.mm ***/
  25266. /*** Start of inlined file: juce_VSTPluginFormat.mm ***/
  25267. // This file just wraps juce_VSTPluginFormat.cpp in an objective-C wrapper
  25268. #define JUCE_MAC_VST_INCLUDED 1
  25269. /*** Start of inlined file: juce_VSTPluginFormat.cpp ***/
  25270. #if JUCE_PLUGINHOST_VST
  25271. #if JUCE_WINDOWS
  25272. #undef _WIN32_WINNT
  25273. #define _WIN32_WINNT 0x500
  25274. #undef STRICT
  25275. #define STRICT
  25276. #include <windows.h>
  25277. #include <float.h>
  25278. #pragma warning (disable : 4312 4355)
  25279. #elif JUCE_LINUX
  25280. #include <float.h>
  25281. #include <sys/time.h>
  25282. #include <X11/Xlib.h>
  25283. #include <X11/Xutil.h>
  25284. #include <X11/Xatom.h>
  25285. #undef Font
  25286. #undef KeyPress
  25287. #undef Drawable
  25288. #undef Time
  25289. #else
  25290. #ifndef JUCE_MAC_VST_INCLUDED
  25291. // On the mac, this file needs to be compiled indirectly, by using
  25292. // juce_VSTPluginFormat.mm instead - that wraps it as an objective-C file for cocoa
  25293. #error
  25294. #endif
  25295. #include <Cocoa/Cocoa.h>
  25296. #include <Carbon/Carbon.h>
  25297. #endif
  25298. #if ! (JUCE_MAC && JUCE_64BIT)
  25299. BEGIN_JUCE_NAMESPACE
  25300. #if JUCE_MAC && JUCE_SUPPORT_CARBON
  25301. #endif
  25302. #undef PRAGMA_ALIGN_SUPPORTED
  25303. #define VST_FORCE_DEPRECATED 0
  25304. #ifdef _MSC_VER
  25305. #pragma warning (push)
  25306. #pragma warning (disable: 4996)
  25307. #endif
  25308. /* Obviously you're going to need the Steinberg vstsdk2.4 folder in
  25309. your include path if you want to add VST support.
  25310. If you're not interested in VSTs, you can disable them by changing the
  25311. JUCE_PLUGINHOST_VST flag in juce_Config.h
  25312. */
  25313. #include "pluginterfaces/vst2.x/aeffectx.h"
  25314. #ifdef _MSC_VER
  25315. #pragma warning (pop)
  25316. #endif
  25317. #if JUCE_LINUX
  25318. #define Font JUCE_NAMESPACE::Font
  25319. #define KeyPress JUCE_NAMESPACE::KeyPress
  25320. #define Drawable JUCE_NAMESPACE::Drawable
  25321. #define Time JUCE_NAMESPACE::Time
  25322. #endif
  25323. /*** Start of inlined file: juce_VSTMidiEventList.h ***/
  25324. #ifdef __aeffect__
  25325. #ifndef __JUCE_VSTMIDIEVENTLIST_JUCEHEADER__
  25326. #define __JUCE_VSTMIDIEVENTLIST_JUCEHEADER__
  25327. /** Holds a set of VSTMidiEvent objects and makes it easy to add
  25328. events to the list.
  25329. This is used by both the VST hosting code and the plugin wrapper.
  25330. */
  25331. class VSTMidiEventList
  25332. {
  25333. public:
  25334. VSTMidiEventList()
  25335. : numEventsUsed (0), numEventsAllocated (0)
  25336. {
  25337. }
  25338. ~VSTMidiEventList()
  25339. {
  25340. freeEvents();
  25341. }
  25342. void clear()
  25343. {
  25344. numEventsUsed = 0;
  25345. if (events != 0)
  25346. events->numEvents = 0;
  25347. }
  25348. void addEvent (const void* const midiData, const int numBytes, const int frameOffset)
  25349. {
  25350. ensureSize (numEventsUsed + 1);
  25351. VstMidiEvent* const e = (VstMidiEvent*) (events->events [numEventsUsed]);
  25352. events->numEvents = ++numEventsUsed;
  25353. if (numBytes <= 4)
  25354. {
  25355. if (e->type == kVstSysExType)
  25356. {
  25357. juce_free (((VstMidiSysexEvent*) e)->sysexDump);
  25358. e->type = kVstMidiType;
  25359. e->byteSize = sizeof (VstMidiEvent);
  25360. e->noteLength = 0;
  25361. e->noteOffset = 0;
  25362. e->detune = 0;
  25363. e->noteOffVelocity = 0;
  25364. }
  25365. e->deltaFrames = frameOffset;
  25366. memcpy (e->midiData, midiData, numBytes);
  25367. }
  25368. else
  25369. {
  25370. VstMidiSysexEvent* const se = (VstMidiSysexEvent*) e;
  25371. if (se->type == kVstSysExType)
  25372. se->sysexDump = (char*) juce_realloc (se->sysexDump, numBytes);
  25373. else
  25374. se->sysexDump = (char*) juce_malloc (numBytes);
  25375. memcpy (se->sysexDump, midiData, numBytes);
  25376. se->type = kVstSysExType;
  25377. se->byteSize = sizeof (VstMidiSysexEvent);
  25378. se->deltaFrames = frameOffset;
  25379. se->flags = 0;
  25380. se->dumpBytes = numBytes;
  25381. se->resvd1 = 0;
  25382. se->resvd2 = 0;
  25383. }
  25384. }
  25385. // Handy method to pull the events out of an event buffer supplied by the host
  25386. // or plugin.
  25387. static void addEventsToMidiBuffer (const VstEvents* events, MidiBuffer& dest)
  25388. {
  25389. for (int i = 0; i < events->numEvents; ++i)
  25390. {
  25391. const VstEvent* const e = events->events[i];
  25392. if (e != 0)
  25393. {
  25394. if (e->type == kVstMidiType)
  25395. {
  25396. dest.addEvent ((const JUCE_NAMESPACE::uint8*) ((const VstMidiEvent*) e)->midiData,
  25397. 4, e->deltaFrames);
  25398. }
  25399. else if (e->type == kVstSysExType)
  25400. {
  25401. dest.addEvent ((const JUCE_NAMESPACE::uint8*) ((const VstMidiSysexEvent*) e)->sysexDump,
  25402. (int) ((const VstMidiSysexEvent*) e)->dumpBytes,
  25403. e->deltaFrames);
  25404. }
  25405. }
  25406. }
  25407. }
  25408. void ensureSize (int numEventsNeeded)
  25409. {
  25410. if (numEventsNeeded > numEventsAllocated)
  25411. {
  25412. numEventsNeeded = (numEventsNeeded + 32) & ~31;
  25413. const int size = 20 + sizeof (VstEvent*) * numEventsNeeded;
  25414. if (events == 0)
  25415. events.calloc (size, 1);
  25416. else
  25417. events.realloc (size, 1);
  25418. for (int i = numEventsAllocated; i < numEventsNeeded; ++i)
  25419. {
  25420. VstMidiEvent* const e = (VstMidiEvent*) juce_calloc (jmax ((int) sizeof (VstMidiEvent),
  25421. (int) sizeof (VstMidiSysexEvent)));
  25422. e->type = kVstMidiType;
  25423. e->byteSize = sizeof (VstMidiEvent);
  25424. events->events[i] = (VstEvent*) e;
  25425. }
  25426. numEventsAllocated = numEventsNeeded;
  25427. }
  25428. }
  25429. void freeEvents()
  25430. {
  25431. if (events != 0)
  25432. {
  25433. for (int i = numEventsAllocated; --i >= 0;)
  25434. {
  25435. VstMidiEvent* const e = (VstMidiEvent*) (events->events[i]);
  25436. if (e->type == kVstSysExType)
  25437. juce_free (((VstMidiSysexEvent*) e)->sysexDump);
  25438. juce_free (e);
  25439. }
  25440. events.free();
  25441. numEventsUsed = 0;
  25442. numEventsAllocated = 0;
  25443. }
  25444. }
  25445. HeapBlock <VstEvents> events;
  25446. private:
  25447. int numEventsUsed, numEventsAllocated;
  25448. };
  25449. #endif // __JUCE_VSTMIDIEVENTLIST_JUCEHEADER__
  25450. #endif // __JUCE_VSTMIDIEVENTLIST_JUCEHEADER__
  25451. /*** End of inlined file: juce_VSTMidiEventList.h ***/
  25452. #if ! JUCE_WIN32
  25453. static void _fpreset() {}
  25454. static void _clearfp() {}
  25455. #endif
  25456. extern void juce_callAnyTimersSynchronously();
  25457. const int fxbVersionNum = 1;
  25458. struct fxProgram
  25459. {
  25460. long chunkMagic; // 'CcnK'
  25461. long byteSize; // of this chunk, excl. magic + byteSize
  25462. long fxMagic; // 'FxCk'
  25463. long version;
  25464. long fxID; // fx unique id
  25465. long fxVersion;
  25466. long numParams;
  25467. char prgName[28];
  25468. float params[1]; // variable no. of parameters
  25469. };
  25470. struct fxSet
  25471. {
  25472. long chunkMagic; // 'CcnK'
  25473. long byteSize; // of this chunk, excl. magic + byteSize
  25474. long fxMagic; // 'FxBk'
  25475. long version;
  25476. long fxID; // fx unique id
  25477. long fxVersion;
  25478. long numPrograms;
  25479. char future[128];
  25480. fxProgram programs[1]; // variable no. of programs
  25481. };
  25482. struct fxChunkSet
  25483. {
  25484. long chunkMagic; // 'CcnK'
  25485. long byteSize; // of this chunk, excl. magic + byteSize
  25486. long fxMagic; // 'FxCh', 'FPCh', or 'FBCh'
  25487. long version;
  25488. long fxID; // fx unique id
  25489. long fxVersion;
  25490. long numPrograms;
  25491. char future[128];
  25492. long chunkSize;
  25493. char chunk[8]; // variable
  25494. };
  25495. struct fxProgramSet
  25496. {
  25497. long chunkMagic; // 'CcnK'
  25498. long byteSize; // of this chunk, excl. magic + byteSize
  25499. long fxMagic; // 'FxCh', 'FPCh', or 'FBCh'
  25500. long version;
  25501. long fxID; // fx unique id
  25502. long fxVersion;
  25503. long numPrograms;
  25504. char name[28];
  25505. long chunkSize;
  25506. char chunk[8]; // variable
  25507. };
  25508. static long vst_swap (const long x) throw()
  25509. {
  25510. #ifdef JUCE_LITTLE_ENDIAN
  25511. return (long) ByteOrder::swap ((uint32) x);
  25512. #else
  25513. return x;
  25514. #endif
  25515. }
  25516. static float vst_swapFloat (const float x) throw()
  25517. {
  25518. #ifdef JUCE_LITTLE_ENDIAN
  25519. union { uint32 asInt; float asFloat; } n;
  25520. n.asFloat = x;
  25521. n.asInt = ByteOrder::swap (n.asInt);
  25522. return n.asFloat;
  25523. #else
  25524. return x;
  25525. #endif
  25526. }
  25527. typedef AEffect* (*MainCall) (audioMasterCallback);
  25528. static VstIntPtr VSTCALLBACK audioMaster (AEffect* effect, VstInt32 opcode, VstInt32 index, VstIntPtr value, void* ptr, float opt);
  25529. static int shellUIDToCreate = 0;
  25530. static int insideVSTCallback = 0;
  25531. class VSTPluginWindow;
  25532. // Change this to disable logging of various VST activities
  25533. #ifndef VST_LOGGING
  25534. #define VST_LOGGING 1
  25535. #endif
  25536. #if VST_LOGGING
  25537. #define log(a) Logger::writeToLog(a);
  25538. #else
  25539. #define log(a)
  25540. #endif
  25541. #if JUCE_MAC && JUCE_PPC
  25542. static void* NewCFMFromMachO (void* const machofp) throw()
  25543. {
  25544. void* result = juce_malloc (8);
  25545. ((void**) result)[0] = machofp;
  25546. ((void**) result)[1] = result;
  25547. return result;
  25548. }
  25549. #endif
  25550. #if JUCE_LINUX
  25551. extern Display* display;
  25552. extern XContext windowHandleXContext;
  25553. typedef void (*EventProcPtr) (XEvent* ev);
  25554. static bool xErrorTriggered;
  25555. static int temporaryErrorHandler (Display*, XErrorEvent*)
  25556. {
  25557. xErrorTriggered = true;
  25558. return 0;
  25559. }
  25560. static int getPropertyFromXWindow (Window handle, Atom atom)
  25561. {
  25562. XErrorHandler oldErrorHandler = XSetErrorHandler (temporaryErrorHandler);
  25563. xErrorTriggered = false;
  25564. int userSize;
  25565. unsigned long bytes, userCount;
  25566. unsigned char* data;
  25567. Atom userType;
  25568. XGetWindowProperty (display, handle, atom, 0, 1, false, AnyPropertyType,
  25569. &userType, &userSize, &userCount, &bytes, &data);
  25570. XSetErrorHandler (oldErrorHandler);
  25571. return (userCount == 1 && ! xErrorTriggered) ? *(int*) data
  25572. : 0;
  25573. }
  25574. static Window getChildWindow (Window windowToCheck)
  25575. {
  25576. Window rootWindow, parentWindow;
  25577. Window* childWindows;
  25578. unsigned int numChildren;
  25579. XQueryTree (display,
  25580. windowToCheck,
  25581. &rootWindow,
  25582. &parentWindow,
  25583. &childWindows,
  25584. &numChildren);
  25585. if (numChildren > 0)
  25586. return childWindows [0];
  25587. return 0;
  25588. }
  25589. static void translateJuceToXButtonModifiers (const MouseEvent& e, XEvent& ev) throw()
  25590. {
  25591. if (e.mods.isLeftButtonDown())
  25592. {
  25593. ev.xbutton.button = Button1;
  25594. ev.xbutton.state |= Button1Mask;
  25595. }
  25596. else if (e.mods.isRightButtonDown())
  25597. {
  25598. ev.xbutton.button = Button3;
  25599. ev.xbutton.state |= Button3Mask;
  25600. }
  25601. else if (e.mods.isMiddleButtonDown())
  25602. {
  25603. ev.xbutton.button = Button2;
  25604. ev.xbutton.state |= Button2Mask;
  25605. }
  25606. }
  25607. static void translateJuceToXMotionModifiers (const MouseEvent& e, XEvent& ev) throw()
  25608. {
  25609. if (e.mods.isLeftButtonDown())
  25610. ev.xmotion.state |= Button1Mask;
  25611. else if (e.mods.isRightButtonDown())
  25612. ev.xmotion.state |= Button3Mask;
  25613. else if (e.mods.isMiddleButtonDown())
  25614. ev.xmotion.state |= Button2Mask;
  25615. }
  25616. static void translateJuceToXCrossingModifiers (const MouseEvent& e, XEvent& ev) throw()
  25617. {
  25618. if (e.mods.isLeftButtonDown())
  25619. ev.xcrossing.state |= Button1Mask;
  25620. else if (e.mods.isRightButtonDown())
  25621. ev.xcrossing.state |= Button3Mask;
  25622. else if (e.mods.isMiddleButtonDown())
  25623. ev.xcrossing.state |= Button2Mask;
  25624. }
  25625. static void translateJuceToXMouseWheelModifiers (const MouseEvent& e, const float increment, XEvent& ev) throw()
  25626. {
  25627. if (increment < 0)
  25628. {
  25629. ev.xbutton.button = Button5;
  25630. ev.xbutton.state |= Button5Mask;
  25631. }
  25632. else if (increment > 0)
  25633. {
  25634. ev.xbutton.button = Button4;
  25635. ev.xbutton.state |= Button4Mask;
  25636. }
  25637. }
  25638. #endif
  25639. static VoidArray activeModules;
  25640. class ModuleHandle : public ReferenceCountedObject
  25641. {
  25642. public:
  25643. File file;
  25644. MainCall moduleMain;
  25645. String pluginName;
  25646. static ModuleHandle* findOrCreateModule (const File& file)
  25647. {
  25648. for (int i = activeModules.size(); --i >= 0;)
  25649. {
  25650. ModuleHandle* const module = (ModuleHandle*) activeModules.getUnchecked(i);
  25651. if (module->file == file)
  25652. return module;
  25653. }
  25654. _fpreset(); // (doesn't do any harm)
  25655. ++insideVSTCallback;
  25656. shellUIDToCreate = 0;
  25657. log ("Attempting to load VST: " + file.getFullPathName());
  25658. ScopedPointer <ModuleHandle> m (new ModuleHandle (file));
  25659. if (! m->open())
  25660. m = 0;
  25661. --insideVSTCallback;
  25662. _fpreset(); // (doesn't do any harm)
  25663. return m.release();
  25664. }
  25665. ModuleHandle (const File& file_)
  25666. : file (file_),
  25667. moduleMain (0),
  25668. #if JUCE_WIN32 || JUCE_LINUX
  25669. hModule (0)
  25670. #elif JUCE_MAC
  25671. fragId (0),
  25672. resHandle (0),
  25673. bundleRef (0),
  25674. resFileId (0)
  25675. #endif
  25676. {
  25677. activeModules.add (this);
  25678. #if JUCE_WIN32 || JUCE_LINUX
  25679. fullParentDirectoryPathName = file_.getParentDirectory().getFullPathName();
  25680. #elif JUCE_MAC
  25681. FSRef ref;
  25682. PlatformUtilities::makeFSRefFromPath (&ref, file_.getParentDirectory().getFullPathName());
  25683. FSGetCatalogInfo (&ref, kFSCatInfoNone, 0, 0, &parentDirFSSpec, 0);
  25684. #endif
  25685. }
  25686. ~ModuleHandle()
  25687. {
  25688. activeModules.removeValue (this);
  25689. close();
  25690. }
  25691. juce_UseDebuggingNewOperator
  25692. #if JUCE_WIN32 || JUCE_LINUX
  25693. void* hModule;
  25694. String fullParentDirectoryPathName;
  25695. bool open()
  25696. {
  25697. #if JUCE_WIN32
  25698. static bool timePeriodSet = false;
  25699. if (! timePeriodSet)
  25700. {
  25701. timePeriodSet = true;
  25702. timeBeginPeriod (2);
  25703. }
  25704. #endif
  25705. pluginName = file.getFileNameWithoutExtension();
  25706. hModule = PlatformUtilities::loadDynamicLibrary (file.getFullPathName());
  25707. moduleMain = (MainCall) PlatformUtilities::getProcedureEntryPoint (hModule, "VSTPluginMain");
  25708. if (moduleMain == 0)
  25709. moduleMain = (MainCall) PlatformUtilities::getProcedureEntryPoint (hModule, "main");
  25710. return moduleMain != 0;
  25711. }
  25712. void close()
  25713. {
  25714. _fpreset(); // (doesn't do any harm)
  25715. PlatformUtilities::freeDynamicLibrary (hModule);
  25716. }
  25717. void closeEffect (AEffect* eff)
  25718. {
  25719. eff->dispatcher (eff, effClose, 0, 0, 0, 0);
  25720. }
  25721. #else
  25722. CFragConnectionID fragId;
  25723. Handle resHandle;
  25724. CFBundleRef bundleRef;
  25725. FSSpec parentDirFSSpec;
  25726. short resFileId;
  25727. bool open()
  25728. {
  25729. bool ok = false;
  25730. const String filename (file.getFullPathName());
  25731. if (file.hasFileExtension (".vst"))
  25732. {
  25733. const char* const utf8 = filename.toUTF8();
  25734. CFURLRef url = CFURLCreateFromFileSystemRepresentation (0, (const UInt8*) utf8,
  25735. strlen (utf8), file.isDirectory());
  25736. if (url != 0)
  25737. {
  25738. bundleRef = CFBundleCreate (kCFAllocatorDefault, url);
  25739. CFRelease (url);
  25740. if (bundleRef != 0)
  25741. {
  25742. if (CFBundleLoadExecutable (bundleRef))
  25743. {
  25744. moduleMain = (MainCall) CFBundleGetFunctionPointerForName (bundleRef, CFSTR("main_macho"));
  25745. if (moduleMain == 0)
  25746. moduleMain = (MainCall) CFBundleGetFunctionPointerForName (bundleRef, CFSTR("VSTPluginMain"));
  25747. if (moduleMain != 0)
  25748. {
  25749. CFTypeRef name = CFBundleGetValueForInfoDictionaryKey (bundleRef, CFSTR("CFBundleName"));
  25750. if (name != 0)
  25751. {
  25752. if (CFGetTypeID (name) == CFStringGetTypeID())
  25753. {
  25754. char buffer[1024];
  25755. if (CFStringGetCString ((CFStringRef) name, buffer, sizeof (buffer), CFStringGetSystemEncoding()))
  25756. pluginName = buffer;
  25757. }
  25758. }
  25759. if (pluginName.isEmpty())
  25760. pluginName = file.getFileNameWithoutExtension();
  25761. resFileId = CFBundleOpenBundleResourceMap (bundleRef);
  25762. ok = true;
  25763. }
  25764. }
  25765. if (! ok)
  25766. {
  25767. CFBundleUnloadExecutable (bundleRef);
  25768. CFRelease (bundleRef);
  25769. bundleRef = 0;
  25770. }
  25771. }
  25772. }
  25773. }
  25774. #if JUCE_PPC
  25775. else
  25776. {
  25777. FSRef fn;
  25778. if (FSPathMakeRef ((UInt8*) filename.toUTF8(), &fn, 0) == noErr)
  25779. {
  25780. resFileId = FSOpenResFile (&fn, fsRdPerm);
  25781. if (resFileId != -1)
  25782. {
  25783. const int numEffs = Count1Resources ('aEff');
  25784. for (int i = 0; i < numEffs; ++i)
  25785. {
  25786. resHandle = Get1IndResource ('aEff', i + 1);
  25787. if (resHandle != 0)
  25788. {
  25789. OSType type;
  25790. Str255 name;
  25791. SInt16 id;
  25792. GetResInfo (resHandle, &id, &type, name);
  25793. pluginName = String ((const char*) name + 1, name[0]);
  25794. DetachResource (resHandle);
  25795. HLock (resHandle);
  25796. Ptr ptr;
  25797. Str255 errorText;
  25798. OSErr err = GetMemFragment (*resHandle, GetHandleSize (resHandle),
  25799. name, kPrivateCFragCopy,
  25800. &fragId, &ptr, errorText);
  25801. if (err == noErr)
  25802. {
  25803. moduleMain = (MainCall) newMachOFromCFM (ptr);
  25804. ok = true;
  25805. }
  25806. else
  25807. {
  25808. HUnlock (resHandle);
  25809. }
  25810. break;
  25811. }
  25812. }
  25813. if (! ok)
  25814. CloseResFile (resFileId);
  25815. }
  25816. }
  25817. }
  25818. #endif
  25819. return ok;
  25820. }
  25821. void close()
  25822. {
  25823. #if JUCE_PPC
  25824. if (fragId != 0)
  25825. {
  25826. if (moduleMain != 0)
  25827. disposeMachOFromCFM ((void*) moduleMain);
  25828. CloseConnection (&fragId);
  25829. HUnlock (resHandle);
  25830. if (resFileId != 0)
  25831. CloseResFile (resFileId);
  25832. }
  25833. else
  25834. #endif
  25835. if (bundleRef != 0)
  25836. {
  25837. CFBundleCloseBundleResourceMap (bundleRef, resFileId);
  25838. if (CFGetRetainCount (bundleRef) == 1)
  25839. CFBundleUnloadExecutable (bundleRef);
  25840. if (CFGetRetainCount (bundleRef) > 0)
  25841. CFRelease (bundleRef);
  25842. }
  25843. }
  25844. void closeEffect (AEffect* eff)
  25845. {
  25846. #if JUCE_PPC
  25847. if (fragId != 0)
  25848. {
  25849. VoidArray thingsToDelete;
  25850. thingsToDelete.add ((void*) eff->dispatcher);
  25851. thingsToDelete.add ((void*) eff->process);
  25852. thingsToDelete.add ((void*) eff->setParameter);
  25853. thingsToDelete.add ((void*) eff->getParameter);
  25854. thingsToDelete.add ((void*) eff->processReplacing);
  25855. eff->dispatcher (eff, effClose, 0, 0, 0, 0);
  25856. for (int i = thingsToDelete.size(); --i >= 0;)
  25857. disposeMachOFromCFM (thingsToDelete[i]);
  25858. }
  25859. else
  25860. #endif
  25861. {
  25862. eff->dispatcher (eff, effClose, 0, 0, 0, 0);
  25863. }
  25864. }
  25865. #if JUCE_PPC
  25866. static void* newMachOFromCFM (void* cfmfp)
  25867. {
  25868. if (cfmfp == 0)
  25869. return 0;
  25870. UInt32* const mfp = new UInt32[6];
  25871. mfp[0] = 0x3d800000 | ((UInt32) cfmfp >> 16);
  25872. mfp[1] = 0x618c0000 | ((UInt32) cfmfp & 0xffff);
  25873. mfp[2] = 0x800c0000;
  25874. mfp[3] = 0x804c0004;
  25875. mfp[4] = 0x7c0903a6;
  25876. mfp[5] = 0x4e800420;
  25877. MakeDataExecutable (mfp, sizeof (UInt32) * 6);
  25878. return mfp;
  25879. }
  25880. static void disposeMachOFromCFM (void* ptr)
  25881. {
  25882. delete[] static_cast <UInt32*> (ptr);
  25883. }
  25884. void coerceAEffectFunctionCalls (AEffect* eff)
  25885. {
  25886. if (fragId != 0)
  25887. {
  25888. eff->dispatcher = (AEffectDispatcherProc) newMachOFromCFM ((void*) eff->dispatcher);
  25889. eff->process = (AEffectProcessProc) newMachOFromCFM ((void*) eff->process);
  25890. eff->setParameter = (AEffectSetParameterProc) newMachOFromCFM ((void*) eff->setParameter);
  25891. eff->getParameter = (AEffectGetParameterProc) newMachOFromCFM ((void*) eff->getParameter);
  25892. eff->processReplacing = (AEffectProcessProc) newMachOFromCFM ((void*) eff->processReplacing);
  25893. }
  25894. }
  25895. #endif
  25896. #endif
  25897. };
  25898. /**
  25899. An instance of a plugin, created by a VSTPluginFormat.
  25900. */
  25901. class VSTPluginInstance : public AudioPluginInstance,
  25902. private Timer,
  25903. private AsyncUpdater
  25904. {
  25905. public:
  25906. ~VSTPluginInstance();
  25907. // AudioPluginInstance methods:
  25908. void fillInPluginDescription (PluginDescription& desc) const
  25909. {
  25910. desc.name = name;
  25911. desc.fileOrIdentifier = module->file.getFullPathName();
  25912. desc.uid = getUID();
  25913. desc.lastFileModTime = module->file.getLastModificationTime();
  25914. desc.pluginFormatName = "VST";
  25915. desc.category = getCategory();
  25916. {
  25917. char buffer [kVstMaxVendorStrLen + 8];
  25918. zerostruct (buffer);
  25919. dispatch (effGetVendorString, 0, 0, buffer, 0);
  25920. desc.manufacturerName = buffer;
  25921. }
  25922. desc.version = getVersion();
  25923. desc.numInputChannels = getNumInputChannels();
  25924. desc.numOutputChannels = getNumOutputChannels();
  25925. desc.isInstrument = (effect != 0 && (effect->flags & effFlagsIsSynth) != 0);
  25926. }
  25927. const String getName() const { return name; }
  25928. int getUID() const throw();
  25929. bool acceptsMidi() const { return wantsMidiMessages; }
  25930. bool producesMidi() const { return dispatch (effCanDo, 0, 0, (void*) "sendVstMidiEvent", 0) > 0; }
  25931. // AudioProcessor methods:
  25932. void prepareToPlay (double sampleRate, int estimatedSamplesPerBlock);
  25933. void releaseResources();
  25934. void processBlock (AudioSampleBuffer& buffer,
  25935. MidiBuffer& midiMessages);
  25936. AudioProcessorEditor* createEditor();
  25937. const String getInputChannelName (const int index) const;
  25938. bool isInputChannelStereoPair (int index) const;
  25939. const String getOutputChannelName (const int index) const;
  25940. bool isOutputChannelStereoPair (int index) const;
  25941. int getNumParameters() { return effect != 0 ? effect->numParams : 0; }
  25942. float getParameter (int index);
  25943. void setParameter (int index, float newValue);
  25944. const String getParameterName (int index);
  25945. const String getParameterText (int index);
  25946. bool isParameterAutomatable (int index) const;
  25947. int getNumPrograms() { return effect != 0 ? effect->numPrograms : 0; }
  25948. int getCurrentProgram() { return dispatch (effGetProgram, 0, 0, 0, 0); }
  25949. void setCurrentProgram (int index);
  25950. const String getProgramName (int index);
  25951. void changeProgramName (int index, const String& newName);
  25952. void getStateInformation (MemoryBlock& destData);
  25953. void getCurrentProgramStateInformation (MemoryBlock& destData);
  25954. void setStateInformation (const void* data, int sizeInBytes);
  25955. void setCurrentProgramStateInformation (const void* data, int sizeInBytes);
  25956. void timerCallback();
  25957. void handleAsyncUpdate();
  25958. VstIntPtr handleCallback (VstInt32 opcode, VstInt32 index, VstInt32 value, void *ptr, float opt);
  25959. juce_UseDebuggingNewOperator
  25960. private:
  25961. friend class VSTPluginWindow;
  25962. friend class VSTPluginFormat;
  25963. AEffect* effect;
  25964. String name;
  25965. CriticalSection lock;
  25966. bool wantsMidiMessages, initialised, isPowerOn;
  25967. mutable StringArray programNames;
  25968. AudioSampleBuffer tempBuffer;
  25969. CriticalSection midiInLock;
  25970. MidiBuffer incomingMidi;
  25971. VSTMidiEventList midiEventsToSend;
  25972. VstTimeInfo vstHostTime;
  25973. HeapBlock <float*> channels;
  25974. ReferenceCountedObjectPtr <ModuleHandle> module;
  25975. int dispatch (const int opcode, const int index, const int value, void* const ptr, float opt) const;
  25976. bool restoreProgramSettings (const fxProgram* const prog);
  25977. const String getCurrentProgramName();
  25978. void setParamsInProgramBlock (fxProgram* const prog) throw();
  25979. void updateStoredProgramNames();
  25980. void initialise();
  25981. void handleMidiFromPlugin (const VstEvents* const events);
  25982. void createTempParameterStore (MemoryBlock& dest);
  25983. void restoreFromTempParameterStore (const MemoryBlock& mb);
  25984. const String getParameterLabel (int index) const;
  25985. bool usesChunks() const throw() { return effect != 0 && (effect->flags & effFlagsProgramChunks) != 0; }
  25986. void getChunkData (MemoryBlock& mb, bool isPreset, int maxSizeMB) const;
  25987. void setChunkData (const char* data, int size, bool isPreset);
  25988. bool loadFromFXBFile (const void* data, int numBytes);
  25989. bool saveToFXBFile (MemoryBlock& dest, bool isFXB, int maxSizeMB);
  25990. int getVersionNumber() const throw() { return effect != 0 ? effect->version : 0; }
  25991. const String getVersion() const throw();
  25992. const String getCategory() const throw();
  25993. bool hasEditor() const throw() { return effect != 0 && (effect->flags & effFlagsHasEditor) != 0; }
  25994. void setPower (const bool on);
  25995. VSTPluginInstance (const ReferenceCountedObjectPtr <ModuleHandle>& module);
  25996. };
  25997. VSTPluginInstance::VSTPluginInstance (const ReferenceCountedObjectPtr <ModuleHandle>& module_)
  25998. : effect (0),
  25999. wantsMidiMessages (false),
  26000. initialised (false),
  26001. isPowerOn (false),
  26002. tempBuffer (1, 1),
  26003. module (module_)
  26004. {
  26005. try
  26006. {
  26007. _fpreset();
  26008. ++insideVSTCallback;
  26009. name = module->pluginName;
  26010. log ("Creating VST instance: " + name);
  26011. #if JUCE_MAC
  26012. if (module->resFileId != 0)
  26013. UseResFile (module->resFileId);
  26014. #if JUCE_PPC
  26015. if (module->fragId != 0)
  26016. {
  26017. static void* audioMasterCoerced = 0;
  26018. if (audioMasterCoerced == 0)
  26019. audioMasterCoerced = NewCFMFromMachO ((void*) &audioMaster);
  26020. effect = module->moduleMain ((audioMasterCallback) audioMasterCoerced);
  26021. }
  26022. else
  26023. #endif
  26024. #endif
  26025. {
  26026. effect = module->moduleMain (&audioMaster);
  26027. }
  26028. --insideVSTCallback;
  26029. if (effect != 0 && effect->magic == kEffectMagic)
  26030. {
  26031. #if JUCE_PPC
  26032. module->coerceAEffectFunctionCalls (effect);
  26033. #endif
  26034. jassert (effect->resvd2 == 0);
  26035. jassert (effect->object != 0);
  26036. _fpreset(); // some dodgy plugs fuck around with this
  26037. }
  26038. else
  26039. {
  26040. effect = 0;
  26041. }
  26042. }
  26043. catch (...)
  26044. {
  26045. --insideVSTCallback;
  26046. }
  26047. }
  26048. VSTPluginInstance::~VSTPluginInstance()
  26049. {
  26050. {
  26051. const ScopedLock sl (lock);
  26052. jassert (insideVSTCallback == 0);
  26053. if (effect != 0 && effect->magic == kEffectMagic)
  26054. {
  26055. try
  26056. {
  26057. #if JUCE_MAC
  26058. if (module->resFileId != 0)
  26059. UseResFile (module->resFileId);
  26060. #endif
  26061. // Must delete any editors before deleting the plugin instance!
  26062. jassert (getActiveEditor() == 0);
  26063. _fpreset(); // some dodgy plugs fuck around with this
  26064. module->closeEffect (effect);
  26065. }
  26066. catch (...)
  26067. {}
  26068. }
  26069. module = 0;
  26070. effect = 0;
  26071. }
  26072. }
  26073. void VSTPluginInstance::initialise()
  26074. {
  26075. if (initialised || effect == 0)
  26076. return;
  26077. log ("Initialising VST: " + module->pluginName);
  26078. initialised = true;
  26079. dispatch (effIdentify, 0, 0, 0, 0);
  26080. // this code would ask the plugin for its name, but so few plugins
  26081. // actually bother implementing this correctly, that it's better to
  26082. // just ignore it and use the file name instead.
  26083. /* {
  26084. char buffer [256];
  26085. zerostruct (buffer);
  26086. dispatch (effGetEffectName, 0, 0, buffer, 0);
  26087. name = String (buffer).trim();
  26088. if (name.isEmpty())
  26089. name = module->pluginName;
  26090. }
  26091. */
  26092. if (getSampleRate() > 0)
  26093. dispatch (effSetSampleRate, 0, 0, 0, (float) getSampleRate());
  26094. if (getBlockSize() > 0)
  26095. dispatch (effSetBlockSize, 0, jmax (32, getBlockSize()), 0, 0);
  26096. dispatch (effOpen, 0, 0, 0, 0);
  26097. setPlayConfigDetails (effect->numInputs, effect->numOutputs,
  26098. getSampleRate(), getBlockSize());
  26099. if (getNumPrograms() > 1)
  26100. setCurrentProgram (0);
  26101. else
  26102. dispatch (effSetProgram, 0, 0, 0, 0);
  26103. int i;
  26104. for (i = effect->numInputs; --i >= 0;)
  26105. dispatch (effConnectInput, i, 1, 0, 0);
  26106. for (i = effect->numOutputs; --i >= 0;)
  26107. dispatch (effConnectOutput, i, 1, 0, 0);
  26108. updateStoredProgramNames();
  26109. wantsMidiMessages = dispatch (effCanDo, 0, 0, (void*) "receiveVstMidiEvent", 0) > 0;
  26110. setLatencySamples (effect->initialDelay);
  26111. }
  26112. void VSTPluginInstance::prepareToPlay (double sampleRate_,
  26113. int samplesPerBlockExpected)
  26114. {
  26115. setPlayConfigDetails (effect->numInputs, effect->numOutputs,
  26116. sampleRate_, samplesPerBlockExpected);
  26117. setLatencySamples (effect->initialDelay);
  26118. channels.calloc (jmax (16, getNumOutputChannels(), getNumInputChannels()) + 2);
  26119. vstHostTime.tempo = 120.0;
  26120. vstHostTime.timeSigNumerator = 4;
  26121. vstHostTime.timeSigDenominator = 4;
  26122. vstHostTime.sampleRate = sampleRate_;
  26123. vstHostTime.samplePos = 0;
  26124. vstHostTime.flags = kVstNanosValid; /*| kVstTransportPlaying | kVstTempoValid | kVstTimeSigValid*/;
  26125. initialise();
  26126. if (initialised)
  26127. {
  26128. wantsMidiMessages = wantsMidiMessages
  26129. || (dispatch (effCanDo, 0, 0, (void*) "receiveVstMidiEvent", 0) > 0);
  26130. if (wantsMidiMessages)
  26131. midiEventsToSend.ensureSize (256);
  26132. else
  26133. midiEventsToSend.freeEvents();
  26134. incomingMidi.clear();
  26135. dispatch (effSetSampleRate, 0, 0, 0, (float) sampleRate_);
  26136. dispatch (effSetBlockSize, 0, jmax (16, samplesPerBlockExpected), 0, 0);
  26137. tempBuffer.setSize (jmax (1, effect->numOutputs), samplesPerBlockExpected);
  26138. if (! isPowerOn)
  26139. setPower (true);
  26140. // dodgy hack to force some plugins to initialise the sample rate..
  26141. if ((! hasEditor()) && getNumParameters() > 0)
  26142. {
  26143. const float old = getParameter (0);
  26144. setParameter (0, (old < 0.5f) ? 1.0f : 0.0f);
  26145. setParameter (0, old);
  26146. }
  26147. dispatch (effStartProcess, 0, 0, 0, 0);
  26148. }
  26149. }
  26150. void VSTPluginInstance::releaseResources()
  26151. {
  26152. if (initialised)
  26153. {
  26154. dispatch (effStopProcess, 0, 0, 0, 0);
  26155. setPower (false);
  26156. }
  26157. tempBuffer.setSize (1, 1);
  26158. incomingMidi.clear();
  26159. midiEventsToSend.freeEvents();
  26160. channels.free();
  26161. }
  26162. void VSTPluginInstance::processBlock (AudioSampleBuffer& buffer,
  26163. MidiBuffer& midiMessages)
  26164. {
  26165. const int numSamples = buffer.getNumSamples();
  26166. if (initialised)
  26167. {
  26168. AudioPlayHead* playHead = getPlayHead();
  26169. if (playHead != 0)
  26170. {
  26171. AudioPlayHead::CurrentPositionInfo position;
  26172. playHead->getCurrentPosition (position);
  26173. vstHostTime.tempo = position.bpm;
  26174. vstHostTime.timeSigNumerator = position.timeSigNumerator;
  26175. vstHostTime.timeSigDenominator = position.timeSigDenominator;
  26176. vstHostTime.ppqPos = position.ppqPosition;
  26177. vstHostTime.barStartPos = position.ppqPositionOfLastBarStart;
  26178. vstHostTime.flags |= kVstTempoValid | kVstTimeSigValid | kVstPpqPosValid | kVstBarsValid;
  26179. if (position.isPlaying)
  26180. vstHostTime.flags |= kVstTransportPlaying;
  26181. else
  26182. vstHostTime.flags &= ~kVstTransportPlaying;
  26183. }
  26184. #if JUCE_WIN32
  26185. vstHostTime.nanoSeconds = timeGetTime() * 1000000.0;
  26186. #elif JUCE_LINUX
  26187. timeval micro;
  26188. gettimeofday (&micro, 0);
  26189. vstHostTime.nanoSeconds = micro.tv_usec * 1000.0;
  26190. #elif JUCE_MAC
  26191. UnsignedWide micro;
  26192. Microseconds (&micro);
  26193. vstHostTime.nanoSeconds = micro.lo * 1000.0;
  26194. #endif
  26195. if (wantsMidiMessages)
  26196. {
  26197. midiEventsToSend.clear();
  26198. midiEventsToSend.ensureSize (1);
  26199. MidiBuffer::Iterator iter (midiMessages);
  26200. const uint8* midiData;
  26201. int numBytesOfMidiData, samplePosition;
  26202. while (iter.getNextEvent (midiData, numBytesOfMidiData, samplePosition))
  26203. {
  26204. midiEventsToSend.addEvent (midiData, numBytesOfMidiData,
  26205. jlimit (0, numSamples - 1, samplePosition));
  26206. }
  26207. try
  26208. {
  26209. effect->dispatcher (effect, effProcessEvents, 0, 0, midiEventsToSend.events, 0);
  26210. }
  26211. catch (...)
  26212. {}
  26213. }
  26214. int i;
  26215. const int maxChans = jmax (effect->numInputs, effect->numOutputs);
  26216. for (i = 0; i < maxChans; ++i)
  26217. channels[i] = buffer.getSampleData (i);
  26218. channels [maxChans] = 0;
  26219. _clearfp();
  26220. if ((effect->flags & effFlagsCanReplacing) != 0)
  26221. {
  26222. try
  26223. {
  26224. effect->processReplacing (effect, channels, channels, numSamples);
  26225. }
  26226. catch (...)
  26227. {}
  26228. }
  26229. else
  26230. {
  26231. tempBuffer.setSize (effect->numOutputs, numSamples);
  26232. tempBuffer.clear();
  26233. float* outs [64];
  26234. for (i = effect->numOutputs; --i >= 0;)
  26235. outs[i] = tempBuffer.getSampleData (i);
  26236. outs [effect->numOutputs] = 0;
  26237. try
  26238. {
  26239. effect->process (effect, channels, outs, numSamples);
  26240. }
  26241. catch (...)
  26242. {}
  26243. for (i = effect->numOutputs; --i >= 0;)
  26244. buffer.copyFrom (i, 0, outs[i], numSamples);
  26245. }
  26246. }
  26247. else
  26248. {
  26249. // Not initialised, so just bypass..
  26250. for (int i = getNumInputChannels(); i < getNumOutputChannels(); ++i)
  26251. buffer.clear (i, 0, buffer.getNumSamples());
  26252. }
  26253. {
  26254. // copy any incoming midi..
  26255. const ScopedLock sl (midiInLock);
  26256. midiMessages.swapWith (incomingMidi);
  26257. incomingMidi.clear();
  26258. }
  26259. }
  26260. void VSTPluginInstance::handleMidiFromPlugin (const VstEvents* const events)
  26261. {
  26262. if (events != 0)
  26263. {
  26264. const ScopedLock sl (midiInLock);
  26265. VSTMidiEventList::addEventsToMidiBuffer (events, incomingMidi);
  26266. }
  26267. }
  26268. static Array <VSTPluginWindow*> activeVSTWindows;
  26269. class VSTPluginWindow : public AudioProcessorEditor,
  26270. #if ! JUCE_MAC
  26271. public ComponentMovementWatcher,
  26272. #endif
  26273. public Timer
  26274. {
  26275. public:
  26276. VSTPluginWindow (VSTPluginInstance& plugin_)
  26277. : AudioProcessorEditor (&plugin_),
  26278. #if ! JUCE_MAC
  26279. ComponentMovementWatcher (this),
  26280. #endif
  26281. plugin (plugin_),
  26282. isOpen (false),
  26283. wasShowing (false),
  26284. pluginRefusesToResize (false),
  26285. pluginWantsKeys (false),
  26286. alreadyInside (false),
  26287. recursiveResize (false)
  26288. {
  26289. #if JUCE_WIN32
  26290. sizeCheckCount = 0;
  26291. pluginHWND = 0;
  26292. #elif JUCE_LINUX
  26293. pluginWindow = None;
  26294. pluginProc = None;
  26295. #else
  26296. addAndMakeVisible (innerWrapper = new InnerWrapperComponent (this));
  26297. #endif
  26298. activeVSTWindows.add (this);
  26299. setSize (1, 1);
  26300. setOpaque (true);
  26301. setVisible (true);
  26302. }
  26303. ~VSTPluginWindow()
  26304. {
  26305. #if JUCE_MAC
  26306. innerWrapper = 0;
  26307. #else
  26308. closePluginWindow();
  26309. #endif
  26310. activeVSTWindows.removeValue (this);
  26311. plugin.editorBeingDeleted (this);
  26312. }
  26313. #if ! JUCE_MAC
  26314. void componentMovedOrResized (bool /*wasMoved*/, bool /*wasResized*/)
  26315. {
  26316. if (recursiveResize)
  26317. return;
  26318. Component* const topComp = getTopLevelComponent();
  26319. if (topComp->getPeer() != 0)
  26320. {
  26321. const Point<int> pos (relativePositionToOtherComponent (topComp, Point<int>()));
  26322. recursiveResize = true;
  26323. #if JUCE_WIN32
  26324. if (pluginHWND != 0)
  26325. MoveWindow (pluginHWND, pos.getX(), pos.getY(), getWidth(), getHeight(), TRUE);
  26326. #elif JUCE_LINUX
  26327. if (pluginWindow != 0)
  26328. {
  26329. XResizeWindow (display, pluginWindow, getWidth(), getHeight());
  26330. XMoveWindow (display, pluginWindow, pos.getX(), pos.getY());
  26331. XMapRaised (display, pluginWindow);
  26332. }
  26333. #endif
  26334. recursiveResize = false;
  26335. }
  26336. }
  26337. void componentVisibilityChanged (Component&)
  26338. {
  26339. const bool isShowingNow = isShowing();
  26340. if (wasShowing != isShowingNow)
  26341. {
  26342. wasShowing = isShowingNow;
  26343. if (isShowingNow)
  26344. openPluginWindow();
  26345. else
  26346. closePluginWindow();
  26347. }
  26348. componentMovedOrResized (true, true);
  26349. }
  26350. void componentPeerChanged()
  26351. {
  26352. closePluginWindow();
  26353. openPluginWindow();
  26354. }
  26355. #endif
  26356. bool keyStateChanged (bool)
  26357. {
  26358. return pluginWantsKeys;
  26359. }
  26360. bool keyPressed (const KeyPress&)
  26361. {
  26362. return pluginWantsKeys;
  26363. }
  26364. #if JUCE_MAC
  26365. void paint (Graphics& g)
  26366. {
  26367. g.fillAll (Colours::black);
  26368. }
  26369. #else
  26370. void paint (Graphics& g)
  26371. {
  26372. if (isOpen)
  26373. {
  26374. ComponentPeer* const peer = getPeer();
  26375. if (peer != 0)
  26376. {
  26377. const Point<int> pos (getScreenPosition() - peer->getScreenPosition());
  26378. peer->addMaskedRegion (pos.getX(), pos.getY(), getWidth(), getHeight());
  26379. #if JUCE_LINUX
  26380. if (pluginWindow != 0)
  26381. {
  26382. const Rectangle<int> clip (g.getClipBounds());
  26383. XEvent ev;
  26384. zerostruct (ev);
  26385. ev.xexpose.type = Expose;
  26386. ev.xexpose.display = display;
  26387. ev.xexpose.window = pluginWindow;
  26388. ev.xexpose.x = clip.getX();
  26389. ev.xexpose.y = clip.getY();
  26390. ev.xexpose.width = clip.getWidth();
  26391. ev.xexpose.height = clip.getHeight();
  26392. sendEventToChild (&ev);
  26393. }
  26394. #endif
  26395. }
  26396. }
  26397. else
  26398. {
  26399. g.fillAll (Colours::black);
  26400. }
  26401. }
  26402. #endif
  26403. void timerCallback()
  26404. {
  26405. #if JUCE_WIN32
  26406. if (--sizeCheckCount <= 0)
  26407. {
  26408. sizeCheckCount = 10;
  26409. checkPluginWindowSize();
  26410. }
  26411. #endif
  26412. try
  26413. {
  26414. static bool reentrant = false;
  26415. if (! reentrant)
  26416. {
  26417. reentrant = true;
  26418. plugin.dispatch (effEditIdle, 0, 0, 0, 0);
  26419. reentrant = false;
  26420. }
  26421. }
  26422. catch (...)
  26423. {}
  26424. }
  26425. void mouseDown (const MouseEvent& e)
  26426. {
  26427. #if JUCE_LINUX
  26428. if (pluginWindow == 0)
  26429. return;
  26430. toFront (true);
  26431. XEvent ev;
  26432. zerostruct (ev);
  26433. ev.xbutton.display = display;
  26434. ev.xbutton.type = ButtonPress;
  26435. ev.xbutton.window = pluginWindow;
  26436. ev.xbutton.root = RootWindow (display, DefaultScreen (display));
  26437. ev.xbutton.time = CurrentTime;
  26438. ev.xbutton.x = e.x;
  26439. ev.xbutton.y = e.y;
  26440. ev.xbutton.x_root = e.getScreenX();
  26441. ev.xbutton.y_root = e.getScreenY();
  26442. translateJuceToXButtonModifiers (e, ev);
  26443. sendEventToChild (&ev);
  26444. #elif JUCE_WIN32
  26445. (void) e;
  26446. toFront (true);
  26447. #endif
  26448. }
  26449. void broughtToFront()
  26450. {
  26451. activeVSTWindows.removeValue (this);
  26452. activeVSTWindows.add (this);
  26453. #if JUCE_MAC
  26454. dispatch (effEditTop, 0, 0, 0, 0);
  26455. #endif
  26456. }
  26457. juce_UseDebuggingNewOperator
  26458. private:
  26459. VSTPluginInstance& plugin;
  26460. bool isOpen, wasShowing, recursiveResize;
  26461. bool pluginWantsKeys, pluginRefusesToResize, alreadyInside;
  26462. #if JUCE_WIN32
  26463. HWND pluginHWND;
  26464. void* originalWndProc;
  26465. int sizeCheckCount;
  26466. #elif JUCE_LINUX
  26467. Window pluginWindow;
  26468. EventProcPtr pluginProc;
  26469. #endif
  26470. #if JUCE_MAC
  26471. void openPluginWindow (WindowRef parentWindow)
  26472. {
  26473. if (isOpen || parentWindow == 0)
  26474. return;
  26475. isOpen = true;
  26476. ERect* rect = 0;
  26477. dispatch (effEditGetRect, 0, 0, &rect, 0);
  26478. dispatch (effEditOpen, 0, 0, parentWindow, 0);
  26479. // do this before and after like in the steinberg example
  26480. dispatch (effEditGetRect, 0, 0, &rect, 0);
  26481. dispatch (effGetProgram, 0, 0, 0, 0); // also in steinberg code
  26482. // Install keyboard hooks
  26483. pluginWantsKeys = (dispatch (effKeysRequired, 0, 0, 0, 0) == 0);
  26484. // double-check it's not too tiny
  26485. int w = 250, h = 150;
  26486. if (rect != 0)
  26487. {
  26488. w = rect->right - rect->left;
  26489. h = rect->bottom - rect->top;
  26490. if (w == 0 || h == 0)
  26491. {
  26492. w = 250;
  26493. h = 150;
  26494. }
  26495. }
  26496. w = jmax (w, 32);
  26497. h = jmax (h, 32);
  26498. setSize (w, h);
  26499. startTimer (18 + JUCE_NAMESPACE::Random::getSystemRandom().nextInt (5));
  26500. repaint();
  26501. }
  26502. #else
  26503. void openPluginWindow()
  26504. {
  26505. if (isOpen || getWindowHandle() == 0)
  26506. return;
  26507. log ("Opening VST UI: " + plugin.name);
  26508. isOpen = true;
  26509. ERect* rect = 0;
  26510. dispatch (effEditGetRect, 0, 0, &rect, 0);
  26511. dispatch (effEditOpen, 0, 0, getWindowHandle(), 0);
  26512. // do this before and after like in the steinberg example
  26513. dispatch (effEditGetRect, 0, 0, &rect, 0);
  26514. dispatch (effGetProgram, 0, 0, 0, 0); // also in steinberg code
  26515. // Install keyboard hooks
  26516. pluginWantsKeys = (dispatch (effKeysRequired, 0, 0, 0, 0) == 0);
  26517. #if JUCE_WIN32
  26518. originalWndProc = 0;
  26519. pluginHWND = GetWindow ((HWND) getWindowHandle(), GW_CHILD);
  26520. if (pluginHWND == 0)
  26521. {
  26522. isOpen = false;
  26523. setSize (300, 150);
  26524. return;
  26525. }
  26526. #pragma warning (push)
  26527. #pragma warning (disable: 4244)
  26528. originalWndProc = (void*) GetWindowLongPtr (pluginHWND, GWL_WNDPROC);
  26529. if (! pluginWantsKeys)
  26530. SetWindowLongPtr (pluginHWND, GWLP_WNDPROC, (LONG_PTR) vstHookWndProc);
  26531. #pragma warning (pop)
  26532. int w, h;
  26533. RECT r;
  26534. GetWindowRect (pluginHWND, &r);
  26535. w = r.right - r.left;
  26536. h = r.bottom - r.top;
  26537. if (rect != 0)
  26538. {
  26539. const int rw = rect->right - rect->left;
  26540. const int rh = rect->bottom - rect->top;
  26541. if ((rw > 50 && rh > 50 && rw < 2000 && rh < 2000 && rw != w && rh != h)
  26542. || ((w == 0 && rw > 0) || (h == 0 && rh > 0)))
  26543. {
  26544. // very dodgy logic to decide which size is right.
  26545. if (abs (rw - w) > 350 || abs (rh - h) > 350)
  26546. {
  26547. SetWindowPos (pluginHWND, 0,
  26548. 0, 0, rw, rh,
  26549. SWP_NOMOVE | SWP_NOACTIVATE | SWP_NOOWNERZORDER | SWP_NOZORDER);
  26550. GetWindowRect (pluginHWND, &r);
  26551. w = r.right - r.left;
  26552. h = r.bottom - r.top;
  26553. pluginRefusesToResize = (w != rw) || (h != rh);
  26554. w = rw;
  26555. h = rh;
  26556. }
  26557. }
  26558. }
  26559. #elif JUCE_LINUX
  26560. pluginWindow = getChildWindow ((Window) getWindowHandle());
  26561. if (pluginWindow != 0)
  26562. pluginProc = (EventProcPtr) getPropertyFromXWindow (pluginWindow,
  26563. XInternAtom (display, "_XEventProc", False));
  26564. int w = 250, h = 150;
  26565. if (rect != 0)
  26566. {
  26567. w = rect->right - rect->left;
  26568. h = rect->bottom - rect->top;
  26569. if (w == 0 || h == 0)
  26570. {
  26571. w = 250;
  26572. h = 150;
  26573. }
  26574. }
  26575. if (pluginWindow != 0)
  26576. XMapRaised (display, pluginWindow);
  26577. #endif
  26578. // double-check it's not too tiny
  26579. w = jmax (w, 32);
  26580. h = jmax (h, 32);
  26581. setSize (w, h);
  26582. #if JUCE_WIN32
  26583. checkPluginWindowSize();
  26584. #endif
  26585. startTimer (18 + JUCE_NAMESPACE::Random::getSystemRandom().nextInt (5));
  26586. repaint();
  26587. }
  26588. #endif
  26589. #if ! JUCE_MAC
  26590. void closePluginWindow()
  26591. {
  26592. if (isOpen)
  26593. {
  26594. log ("Closing VST UI: " + plugin.getName());
  26595. isOpen = false;
  26596. dispatch (effEditClose, 0, 0, 0, 0);
  26597. #if JUCE_WIN32
  26598. #pragma warning (push)
  26599. #pragma warning (disable: 4244)
  26600. if (pluginHWND != 0 && IsWindow (pluginHWND))
  26601. SetWindowLongPtr (pluginHWND, GWLP_WNDPROC, (LONG_PTR) originalWndProc);
  26602. #pragma warning (pop)
  26603. stopTimer();
  26604. if (pluginHWND != 0 && IsWindow (pluginHWND))
  26605. DestroyWindow (pluginHWND);
  26606. pluginHWND = 0;
  26607. #elif JUCE_LINUX
  26608. stopTimer();
  26609. pluginWindow = 0;
  26610. pluginProc = 0;
  26611. #endif
  26612. }
  26613. }
  26614. #endif
  26615. int dispatch (const int opcode, const int index, const int value, void* const ptr, float opt)
  26616. {
  26617. return plugin.dispatch (opcode, index, value, ptr, opt);
  26618. }
  26619. #if JUCE_WIN32
  26620. void checkPluginWindowSize() throw()
  26621. {
  26622. RECT r;
  26623. GetWindowRect (pluginHWND, &r);
  26624. const int w = r.right - r.left;
  26625. const int h = r.bottom - r.top;
  26626. if (isShowing() && w > 0 && h > 0
  26627. && (w != getWidth() || h != getHeight())
  26628. && ! pluginRefusesToResize)
  26629. {
  26630. setSize (w, h);
  26631. sizeCheckCount = 0;
  26632. }
  26633. }
  26634. // hooks to get keyboard events from VST windows..
  26635. static LRESULT CALLBACK vstHookWndProc (HWND hW, UINT message, WPARAM wParam, LPARAM lParam)
  26636. {
  26637. for (int i = activeVSTWindows.size(); --i >= 0;)
  26638. {
  26639. const VSTPluginWindow* const w = (const VSTPluginWindow*) activeVSTWindows.getUnchecked (i);
  26640. if (w->pluginHWND == hW)
  26641. {
  26642. if (message == WM_CHAR
  26643. || message == WM_KEYDOWN
  26644. || message == WM_SYSKEYDOWN
  26645. || message == WM_KEYUP
  26646. || message == WM_SYSKEYUP
  26647. || message == WM_APPCOMMAND)
  26648. {
  26649. SendMessage ((HWND) w->getTopLevelComponent()->getWindowHandle(),
  26650. message, wParam, lParam);
  26651. }
  26652. return CallWindowProc ((WNDPROC) (w->originalWndProc),
  26653. (HWND) w->pluginHWND,
  26654. message,
  26655. wParam,
  26656. lParam);
  26657. }
  26658. }
  26659. return DefWindowProc (hW, message, wParam, lParam);
  26660. }
  26661. #endif
  26662. #if JUCE_LINUX
  26663. // overload mouse/keyboard events to forward them to the plugin's inner window..
  26664. void sendEventToChild (XEvent* event)
  26665. {
  26666. if (pluginProc != 0)
  26667. {
  26668. // if the plugin publishes an event procedure, pass the event directly..
  26669. pluginProc (event);
  26670. }
  26671. else if (pluginWindow != 0)
  26672. {
  26673. // if the plugin has a window, then send the event to the window so that
  26674. // its message thread will pick it up..
  26675. XSendEvent (display, pluginWindow, False, 0L, event);
  26676. XFlush (display);
  26677. }
  26678. }
  26679. void mouseEnter (const MouseEvent& e)
  26680. {
  26681. if (pluginWindow != 0)
  26682. {
  26683. XEvent ev;
  26684. zerostruct (ev);
  26685. ev.xcrossing.display = display;
  26686. ev.xcrossing.type = EnterNotify;
  26687. ev.xcrossing.window = pluginWindow;
  26688. ev.xcrossing.root = RootWindow (display, DefaultScreen (display));
  26689. ev.xcrossing.time = CurrentTime;
  26690. ev.xcrossing.x = e.x;
  26691. ev.xcrossing.y = e.y;
  26692. ev.xcrossing.x_root = e.getScreenX();
  26693. ev.xcrossing.y_root = e.getScreenY();
  26694. ev.xcrossing.mode = NotifyNormal; // NotifyGrab, NotifyUngrab
  26695. ev.xcrossing.detail = NotifyAncestor; // NotifyVirtual, NotifyInferior, NotifyNonlinear,NotifyNonlinearVirtual
  26696. translateJuceToXCrossingModifiers (e, ev);
  26697. sendEventToChild (&ev);
  26698. }
  26699. }
  26700. void mouseExit (const MouseEvent& e)
  26701. {
  26702. if (pluginWindow != 0)
  26703. {
  26704. XEvent ev;
  26705. zerostruct (ev);
  26706. ev.xcrossing.display = display;
  26707. ev.xcrossing.type = LeaveNotify;
  26708. ev.xcrossing.window = pluginWindow;
  26709. ev.xcrossing.root = RootWindow (display, DefaultScreen (display));
  26710. ev.xcrossing.time = CurrentTime;
  26711. ev.xcrossing.x = e.x;
  26712. ev.xcrossing.y = e.y;
  26713. ev.xcrossing.x_root = e.getScreenX();
  26714. ev.xcrossing.y_root = e.getScreenY();
  26715. ev.xcrossing.mode = NotifyNormal; // NotifyGrab, NotifyUngrab
  26716. ev.xcrossing.detail = NotifyAncestor; // NotifyVirtual, NotifyInferior, NotifyNonlinear,NotifyNonlinearVirtual
  26717. ev.xcrossing.focus = hasKeyboardFocus (true); // TODO - yes ?
  26718. translateJuceToXCrossingModifiers (e, ev);
  26719. sendEventToChild (&ev);
  26720. }
  26721. }
  26722. void mouseMove (const MouseEvent& e)
  26723. {
  26724. if (pluginWindow != 0)
  26725. {
  26726. XEvent ev;
  26727. zerostruct (ev);
  26728. ev.xmotion.display = display;
  26729. ev.xmotion.type = MotionNotify;
  26730. ev.xmotion.window = pluginWindow;
  26731. ev.xmotion.root = RootWindow (display, DefaultScreen (display));
  26732. ev.xmotion.time = CurrentTime;
  26733. ev.xmotion.is_hint = NotifyNormal;
  26734. ev.xmotion.x = e.x;
  26735. ev.xmotion.y = e.y;
  26736. ev.xmotion.x_root = e.getScreenX();
  26737. ev.xmotion.y_root = e.getScreenY();
  26738. sendEventToChild (&ev);
  26739. }
  26740. }
  26741. void mouseDrag (const MouseEvent& e)
  26742. {
  26743. if (pluginWindow != 0)
  26744. {
  26745. XEvent ev;
  26746. zerostruct (ev);
  26747. ev.xmotion.display = display;
  26748. ev.xmotion.type = MotionNotify;
  26749. ev.xmotion.window = pluginWindow;
  26750. ev.xmotion.root = RootWindow (display, DefaultScreen (display));
  26751. ev.xmotion.time = CurrentTime;
  26752. ev.xmotion.x = e.x ;
  26753. ev.xmotion.y = e.y;
  26754. ev.xmotion.x_root = e.getScreenX();
  26755. ev.xmotion.y_root = e.getScreenY();
  26756. ev.xmotion.is_hint = NotifyNormal;
  26757. translateJuceToXMotionModifiers (e, ev);
  26758. sendEventToChild (&ev);
  26759. }
  26760. }
  26761. void mouseUp (const MouseEvent& e)
  26762. {
  26763. if (pluginWindow != 0)
  26764. {
  26765. XEvent ev;
  26766. zerostruct (ev);
  26767. ev.xbutton.display = display;
  26768. ev.xbutton.type = ButtonRelease;
  26769. ev.xbutton.window = pluginWindow;
  26770. ev.xbutton.root = RootWindow (display, DefaultScreen (display));
  26771. ev.xbutton.time = CurrentTime;
  26772. ev.xbutton.x = e.x;
  26773. ev.xbutton.y = e.y;
  26774. ev.xbutton.x_root = e.getScreenX();
  26775. ev.xbutton.y_root = e.getScreenY();
  26776. translateJuceToXButtonModifiers (e, ev);
  26777. sendEventToChild (&ev);
  26778. }
  26779. }
  26780. void mouseWheelMove (const MouseEvent& e,
  26781. float incrementX,
  26782. float incrementY)
  26783. {
  26784. if (pluginWindow != 0)
  26785. {
  26786. XEvent ev;
  26787. zerostruct (ev);
  26788. ev.xbutton.display = display;
  26789. ev.xbutton.type = ButtonPress;
  26790. ev.xbutton.window = pluginWindow;
  26791. ev.xbutton.root = RootWindow (display, DefaultScreen (display));
  26792. ev.xbutton.time = CurrentTime;
  26793. ev.xbutton.x = e.x;
  26794. ev.xbutton.y = e.y;
  26795. ev.xbutton.x_root = e.getScreenX();
  26796. ev.xbutton.y_root = e.getScreenY();
  26797. translateJuceToXMouseWheelModifiers (e, incrementY, ev);
  26798. sendEventToChild (&ev);
  26799. // TODO - put a usleep here ?
  26800. ev.xbutton.type = ButtonRelease;
  26801. sendEventToChild (&ev);
  26802. }
  26803. }
  26804. #endif
  26805. #if JUCE_MAC
  26806. #if ! JUCE_SUPPORT_CARBON
  26807. #error "To build VSTs, you need to enable the JUCE_SUPPORT_CARBON flag in your config!"
  26808. #endif
  26809. class InnerWrapperComponent : public CarbonViewWrapperComponent
  26810. {
  26811. public:
  26812. InnerWrapperComponent (VSTPluginWindow* const owner_)
  26813. : owner (owner_),
  26814. alreadyInside (false)
  26815. {
  26816. }
  26817. ~InnerWrapperComponent()
  26818. {
  26819. deleteWindow();
  26820. }
  26821. HIViewRef attachView (WindowRef windowRef, HIViewRef rootView)
  26822. {
  26823. owner->openPluginWindow (windowRef);
  26824. return 0;
  26825. }
  26826. void removeView (HIViewRef)
  26827. {
  26828. owner->dispatch (effEditClose, 0, 0, 0, 0);
  26829. owner->dispatch (effEditSleep, 0, 0, 0, 0);
  26830. }
  26831. bool getEmbeddedViewSize (int& w, int& h)
  26832. {
  26833. ERect* rect = 0;
  26834. owner->dispatch (effEditGetRect, 0, 0, &rect, 0);
  26835. w = rect->right - rect->left;
  26836. h = rect->bottom - rect->top;
  26837. return true;
  26838. }
  26839. void mouseDown (int x, int y)
  26840. {
  26841. if (! alreadyInside)
  26842. {
  26843. alreadyInside = true;
  26844. getTopLevelComponent()->toFront (true);
  26845. owner->dispatch (effEditMouse, x, y, 0, 0);
  26846. alreadyInside = false;
  26847. }
  26848. else
  26849. {
  26850. PostEvent (::mouseDown, 0);
  26851. }
  26852. }
  26853. void paint()
  26854. {
  26855. ComponentPeer* const peer = getPeer();
  26856. if (peer != 0)
  26857. {
  26858. const Point<int> pos (getScreenPosition() - peer->getScreenPosition());
  26859. ERect r;
  26860. r.left = pos.getX();
  26861. r.right = r.left + getWidth();
  26862. r.top = pos.getY();
  26863. r.bottom = r.top + getHeight();
  26864. owner->dispatch (effEditDraw, 0, 0, &r, 0);
  26865. }
  26866. }
  26867. private:
  26868. VSTPluginWindow* const owner;
  26869. bool alreadyInside;
  26870. };
  26871. friend class InnerWrapperComponent;
  26872. ScopedPointer <InnerWrapperComponent> innerWrapper;
  26873. void resized()
  26874. {
  26875. innerWrapper->setSize (getWidth(), getHeight());
  26876. }
  26877. #endif
  26878. };
  26879. AudioProcessorEditor* VSTPluginInstance::createEditor()
  26880. {
  26881. if (hasEditor())
  26882. return new VSTPluginWindow (*this);
  26883. return 0;
  26884. }
  26885. void VSTPluginInstance::handleAsyncUpdate()
  26886. {
  26887. // indicates that something about the plugin has changed..
  26888. updateHostDisplay();
  26889. }
  26890. bool VSTPluginInstance::restoreProgramSettings (const fxProgram* const prog)
  26891. {
  26892. if (vst_swap (prog->chunkMagic) == 'CcnK' && vst_swap (prog->fxMagic) == 'FxCk')
  26893. {
  26894. changeProgramName (getCurrentProgram(), prog->prgName);
  26895. for (int i = 0; i < vst_swap (prog->numParams); ++i)
  26896. setParameter (i, vst_swapFloat (prog->params[i]));
  26897. return true;
  26898. }
  26899. return false;
  26900. }
  26901. bool VSTPluginInstance::loadFromFXBFile (const void* const data,
  26902. const int dataSize)
  26903. {
  26904. if (dataSize < 28)
  26905. return false;
  26906. const fxSet* const set = (const fxSet*) data;
  26907. if ((vst_swap (set->chunkMagic) != 'CcnK' && vst_swap (set->chunkMagic) != 'KncC')
  26908. || vst_swap (set->version) > fxbVersionNum)
  26909. return false;
  26910. if (vst_swap (set->fxMagic) == 'FxBk')
  26911. {
  26912. // bank of programs
  26913. if (vst_swap (set->numPrograms) >= 0)
  26914. {
  26915. const int oldProg = getCurrentProgram();
  26916. const int numParams = vst_swap (((const fxProgram*) (set->programs))->numParams);
  26917. const int progLen = sizeof (fxProgram) + (numParams - 1) * sizeof (float);
  26918. for (int i = 0; i < vst_swap (set->numPrograms); ++i)
  26919. {
  26920. if (i != oldProg)
  26921. {
  26922. const fxProgram* const prog = (const fxProgram*) (((const char*) (set->programs)) + i * progLen);
  26923. if (((const char*) prog) - ((const char*) set) >= dataSize)
  26924. return false;
  26925. if (vst_swap (set->numPrograms) > 0)
  26926. setCurrentProgram (i);
  26927. if (! restoreProgramSettings (prog))
  26928. return false;
  26929. }
  26930. }
  26931. if (vst_swap (set->numPrograms) > 0)
  26932. setCurrentProgram (oldProg);
  26933. const fxProgram* const prog = (const fxProgram*) (((const char*) (set->programs)) + oldProg * progLen);
  26934. if (((const char*) prog) - ((const char*) set) >= dataSize)
  26935. return false;
  26936. if (! restoreProgramSettings (prog))
  26937. return false;
  26938. }
  26939. }
  26940. else if (vst_swap (set->fxMagic) == 'FxCk')
  26941. {
  26942. // single program
  26943. const fxProgram* const prog = (const fxProgram*) data;
  26944. if (vst_swap (prog->chunkMagic) != 'CcnK')
  26945. return false;
  26946. changeProgramName (getCurrentProgram(), prog->prgName);
  26947. for (int i = 0; i < vst_swap (prog->numParams); ++i)
  26948. setParameter (i, vst_swapFloat (prog->params[i]));
  26949. }
  26950. else if (vst_swap (set->fxMagic) == 'FBCh' || vst_swap (set->fxMagic) == 'hCBF')
  26951. {
  26952. // non-preset chunk
  26953. const fxChunkSet* const cset = (const fxChunkSet*) data;
  26954. if (vst_swap (cset->chunkSize) + sizeof (fxChunkSet) - 8 > (unsigned int) dataSize)
  26955. return false;
  26956. setChunkData (cset->chunk, vst_swap (cset->chunkSize), false);
  26957. }
  26958. else if (vst_swap (set->fxMagic) == 'FPCh' || vst_swap (set->fxMagic) == 'hCPF')
  26959. {
  26960. // preset chunk
  26961. const fxProgramSet* const cset = (const fxProgramSet*) data;
  26962. if (vst_swap (cset->chunkSize) + sizeof (fxProgramSet) - 8 > (unsigned int) dataSize)
  26963. return false;
  26964. setChunkData (cset->chunk, vst_swap (cset->chunkSize), true);
  26965. changeProgramName (getCurrentProgram(), cset->name);
  26966. }
  26967. else
  26968. {
  26969. return false;
  26970. }
  26971. return true;
  26972. }
  26973. void VSTPluginInstance::setParamsInProgramBlock (fxProgram* const prog) throw()
  26974. {
  26975. const int numParams = getNumParameters();
  26976. prog->chunkMagic = vst_swap ('CcnK');
  26977. prog->byteSize = 0;
  26978. prog->fxMagic = vst_swap ('FxCk');
  26979. prog->version = vst_swap (fxbVersionNum);
  26980. prog->fxID = vst_swap (getUID());
  26981. prog->fxVersion = vst_swap (getVersionNumber());
  26982. prog->numParams = vst_swap (numParams);
  26983. getCurrentProgramName().copyToCString (prog->prgName, sizeof (prog->prgName) - 1);
  26984. for (int i = 0; i < numParams; ++i)
  26985. prog->params[i] = vst_swapFloat (getParameter (i));
  26986. }
  26987. bool VSTPluginInstance::saveToFXBFile (MemoryBlock& dest, bool isFXB, int maxSizeMB)
  26988. {
  26989. const int numPrograms = getNumPrograms();
  26990. const int numParams = getNumParameters();
  26991. if (usesChunks())
  26992. {
  26993. if (isFXB)
  26994. {
  26995. MemoryBlock chunk;
  26996. getChunkData (chunk, false, maxSizeMB);
  26997. const size_t totalLen = sizeof (fxChunkSet) + chunk.getSize() - 8;
  26998. dest.setSize (totalLen, true);
  26999. fxChunkSet* const set = (fxChunkSet*) dest.getData();
  27000. set->chunkMagic = vst_swap ('CcnK');
  27001. set->byteSize = 0;
  27002. set->fxMagic = vst_swap ('FBCh');
  27003. set->version = vst_swap (fxbVersionNum);
  27004. set->fxID = vst_swap (getUID());
  27005. set->fxVersion = vst_swap (getVersionNumber());
  27006. set->numPrograms = vst_swap (numPrograms);
  27007. set->chunkSize = vst_swap ((long) chunk.getSize());
  27008. chunk.copyTo (set->chunk, 0, chunk.getSize());
  27009. }
  27010. else
  27011. {
  27012. MemoryBlock chunk;
  27013. getChunkData (chunk, true, maxSizeMB);
  27014. const size_t totalLen = sizeof (fxProgramSet) + chunk.getSize() - 8;
  27015. dest.setSize (totalLen, true);
  27016. fxProgramSet* const set = (fxProgramSet*) dest.getData();
  27017. set->chunkMagic = vst_swap ('CcnK');
  27018. set->byteSize = 0;
  27019. set->fxMagic = vst_swap ('FPCh');
  27020. set->version = vst_swap (fxbVersionNum);
  27021. set->fxID = vst_swap (getUID());
  27022. set->fxVersion = vst_swap (getVersionNumber());
  27023. set->numPrograms = vst_swap (numPrograms);
  27024. set->chunkSize = vst_swap ((long) chunk.getSize());
  27025. getCurrentProgramName().copyToCString (set->name, sizeof (set->name) - 1);
  27026. chunk.copyTo (set->chunk, 0, chunk.getSize());
  27027. }
  27028. }
  27029. else
  27030. {
  27031. if (isFXB)
  27032. {
  27033. const int progLen = sizeof (fxProgram) + (numParams - 1) * sizeof (float);
  27034. const int len = (sizeof (fxSet) - sizeof (fxProgram)) + progLen * jmax (1, numPrograms);
  27035. dest.setSize (len, true);
  27036. fxSet* const set = (fxSet*) dest.getData();
  27037. set->chunkMagic = vst_swap ('CcnK');
  27038. set->byteSize = 0;
  27039. set->fxMagic = vst_swap ('FxBk');
  27040. set->version = vst_swap (fxbVersionNum);
  27041. set->fxID = vst_swap (getUID());
  27042. set->fxVersion = vst_swap (getVersionNumber());
  27043. set->numPrograms = vst_swap (numPrograms);
  27044. const int oldProgram = getCurrentProgram();
  27045. MemoryBlock oldSettings;
  27046. createTempParameterStore (oldSettings);
  27047. setParamsInProgramBlock ((fxProgram*) (((char*) (set->programs)) + oldProgram * progLen));
  27048. for (int i = 0; i < numPrograms; ++i)
  27049. {
  27050. if (i != oldProgram)
  27051. {
  27052. setCurrentProgram (i);
  27053. setParamsInProgramBlock ((fxProgram*) (((char*) (set->programs)) + i * progLen));
  27054. }
  27055. }
  27056. setCurrentProgram (oldProgram);
  27057. restoreFromTempParameterStore (oldSettings);
  27058. }
  27059. else
  27060. {
  27061. const int totalLen = sizeof (fxProgram) + (numParams - 1) * sizeof (float);
  27062. dest.setSize (totalLen, true);
  27063. setParamsInProgramBlock ((fxProgram*) dest.getData());
  27064. }
  27065. }
  27066. return true;
  27067. }
  27068. void VSTPluginInstance::getChunkData (MemoryBlock& mb, bool isPreset, int maxSizeMB) const
  27069. {
  27070. if (usesChunks())
  27071. {
  27072. void* data = 0;
  27073. const int bytes = dispatch (effGetChunk, isPreset ? 1 : 0, 0, &data, 0.0f);
  27074. if (data != 0 && bytes <= maxSizeMB * 1024 * 1024)
  27075. {
  27076. mb.setSize (bytes);
  27077. mb.copyFrom (data, 0, bytes);
  27078. }
  27079. }
  27080. }
  27081. void VSTPluginInstance::setChunkData (const char* data, int size, bool isPreset)
  27082. {
  27083. if (size > 0 && usesChunks())
  27084. {
  27085. dispatch (effSetChunk, isPreset ? 1 : 0, size, (void*) data, 0.0f);
  27086. if (! isPreset)
  27087. updateStoredProgramNames();
  27088. }
  27089. }
  27090. void VSTPluginInstance::timerCallback()
  27091. {
  27092. if (dispatch (effIdle, 0, 0, 0, 0) == 0)
  27093. stopTimer();
  27094. }
  27095. int VSTPluginInstance::dispatch (const int opcode, const int index, const int value, void* const ptr, float opt) const
  27096. {
  27097. const ScopedLock sl (lock);
  27098. ++insideVSTCallback;
  27099. int result = 0;
  27100. try
  27101. {
  27102. if (effect != 0)
  27103. {
  27104. #if JUCE_MAC
  27105. if (module->resFileId != 0)
  27106. UseResFile (module->resFileId);
  27107. CGrafPtr oldPort;
  27108. if (getActiveEditor() != 0)
  27109. {
  27110. const Point<int> pos (getActiveEditor()->relativePositionToOtherComponent (getActiveEditor()->getTopLevelComponent(), Point<int>()));
  27111. GetPort (&oldPort);
  27112. SetPortWindowPort ((WindowRef) getActiveEditor()->getWindowHandle());
  27113. SetOrigin (-pos.getX(), -pos.getY());
  27114. }
  27115. #endif
  27116. result = effect->dispatcher (effect, opcode, index, value, ptr, opt);
  27117. #if JUCE_MAC
  27118. if (getActiveEditor() != 0)
  27119. SetPort (oldPort);
  27120. module->resFileId = CurResFile();
  27121. #endif
  27122. --insideVSTCallback;
  27123. return result;
  27124. }
  27125. }
  27126. catch (...)
  27127. {
  27128. }
  27129. --insideVSTCallback;
  27130. return result;
  27131. }
  27132. // handles non plugin-specific callbacks..
  27133. static const int defaultVSTSampleRateValue = 16384;
  27134. static const int defaultVSTBlockSizeValue = 512;
  27135. static VstIntPtr handleGeneralCallback (VstInt32 opcode, VstInt32 index, VstInt32 value, void *ptr, float opt)
  27136. {
  27137. (void) index;
  27138. (void) value;
  27139. (void) opt;
  27140. switch (opcode)
  27141. {
  27142. case audioMasterCanDo:
  27143. {
  27144. static const char* canDos[] = { "supplyIdle",
  27145. "sendVstEvents",
  27146. "sendVstMidiEvent",
  27147. "sendVstTimeInfo",
  27148. "receiveVstEvents",
  27149. "receiveVstMidiEvent",
  27150. "supportShell",
  27151. "shellCategory" };
  27152. for (int i = 0; i < numElementsInArray (canDos); ++i)
  27153. if (strcmp (canDos[i], (const char*) ptr) == 0)
  27154. return 1;
  27155. return 0;
  27156. }
  27157. case audioMasterVersion:
  27158. return 0x2400;
  27159. case audioMasterCurrentId:
  27160. return shellUIDToCreate;
  27161. case audioMasterGetNumAutomatableParameters:
  27162. return 0;
  27163. case audioMasterGetAutomationState:
  27164. return 1;
  27165. case audioMasterGetVendorVersion:
  27166. return 0x0101;
  27167. case audioMasterGetVendorString:
  27168. case audioMasterGetProductString:
  27169. {
  27170. String hostName ("Juce VST Host");
  27171. if (JUCEApplication::getInstance() != 0)
  27172. hostName = JUCEApplication::getInstance()->getApplicationName();
  27173. hostName.copyToCString ((char*) ptr, jmin (kVstMaxVendorStrLen, kVstMaxProductStrLen) - 1);
  27174. }
  27175. break;
  27176. case audioMasterGetSampleRate:
  27177. return (VstIntPtr) defaultVSTSampleRateValue;
  27178. case audioMasterGetBlockSize:
  27179. return (VstIntPtr) defaultVSTBlockSizeValue;
  27180. case audioMasterSetOutputSampleRate:
  27181. return 0;
  27182. default:
  27183. DBG ("*** Unhandled VST Callback: " + String ((int) opcode));
  27184. break;
  27185. }
  27186. return 0;
  27187. }
  27188. // handles callbacks for a specific plugin
  27189. VstIntPtr VSTPluginInstance::handleCallback (VstInt32 opcode, VstInt32 index, VstInt32 value, void *ptr, float opt)
  27190. {
  27191. switch (opcode)
  27192. {
  27193. case audioMasterAutomate:
  27194. sendParamChangeMessageToListeners (index, opt);
  27195. break;
  27196. case audioMasterProcessEvents:
  27197. handleMidiFromPlugin ((const VstEvents*) ptr);
  27198. break;
  27199. case audioMasterGetTime:
  27200. #ifdef _MSC_VER
  27201. #pragma warning (push)
  27202. #pragma warning (disable: 4311)
  27203. #endif
  27204. return (VstIntPtr) &vstHostTime;
  27205. #ifdef _MSC_VER
  27206. #pragma warning (pop)
  27207. #endif
  27208. break;
  27209. case audioMasterIdle:
  27210. if (insideVSTCallback == 0 && MessageManager::getInstance()->isThisTheMessageThread())
  27211. {
  27212. ++insideVSTCallback;
  27213. #if JUCE_MAC
  27214. if (getActiveEditor() != 0)
  27215. dispatch (effEditIdle, 0, 0, 0, 0);
  27216. #endif
  27217. juce_callAnyTimersSynchronously();
  27218. handleUpdateNowIfNeeded();
  27219. for (int i = ComponentPeer::getNumPeers(); --i >= 0;)
  27220. ComponentPeer::getPeer (i)->performAnyPendingRepaintsNow();
  27221. --insideVSTCallback;
  27222. }
  27223. break;
  27224. case audioMasterUpdateDisplay:
  27225. triggerAsyncUpdate();
  27226. break;
  27227. case audioMasterTempoAt:
  27228. // returns (10000 * bpm)
  27229. break;
  27230. case audioMasterNeedIdle:
  27231. startTimer (50);
  27232. break;
  27233. case audioMasterSizeWindow:
  27234. if (getActiveEditor() != 0)
  27235. getActiveEditor()->setSize (index, value);
  27236. return 1;
  27237. case audioMasterGetSampleRate:
  27238. return (VstIntPtr) (getSampleRate() > 0 ? getSampleRate() : defaultVSTSampleRateValue);
  27239. case audioMasterGetBlockSize:
  27240. return (VstIntPtr) (getBlockSize() > 0 ? getBlockSize() : defaultVSTBlockSizeValue);
  27241. case audioMasterWantMidi:
  27242. wantsMidiMessages = true;
  27243. break;
  27244. case audioMasterGetDirectory:
  27245. #if JUCE_MAC
  27246. return (VstIntPtr) (void*) &module->parentDirFSSpec;
  27247. #else
  27248. return (VstIntPtr) (pointer_sized_uint) module->fullParentDirectoryPathName.toUTF8();
  27249. #endif
  27250. case audioMasterGetAutomationState:
  27251. // returns 0: not supported, 1: off, 2:read, 3:write, 4:read/write
  27252. break;
  27253. // none of these are handled (yet)..
  27254. case audioMasterBeginEdit:
  27255. case audioMasterEndEdit:
  27256. case audioMasterSetTime:
  27257. case audioMasterPinConnected:
  27258. case audioMasterGetParameterQuantization:
  27259. case audioMasterIOChanged:
  27260. case audioMasterGetInputLatency:
  27261. case audioMasterGetOutputLatency:
  27262. case audioMasterGetPreviousPlug:
  27263. case audioMasterGetNextPlug:
  27264. case audioMasterWillReplaceOrAccumulate:
  27265. case audioMasterGetCurrentProcessLevel:
  27266. case audioMasterOfflineStart:
  27267. case audioMasterOfflineRead:
  27268. case audioMasterOfflineWrite:
  27269. case audioMasterOfflineGetCurrentPass:
  27270. case audioMasterOfflineGetCurrentMetaPass:
  27271. case audioMasterVendorSpecific:
  27272. case audioMasterSetIcon:
  27273. case audioMasterGetLanguage:
  27274. case audioMasterOpenWindow:
  27275. case audioMasterCloseWindow:
  27276. break;
  27277. default:
  27278. return handleGeneralCallback (opcode, index, value, ptr, opt);
  27279. }
  27280. return 0;
  27281. }
  27282. // entry point for all callbacks from the plugin
  27283. static VstIntPtr VSTCALLBACK audioMaster (AEffect* effect, VstInt32 opcode, VstInt32 index, VstIntPtr value, void* ptr, float opt)
  27284. {
  27285. try
  27286. {
  27287. if (effect != 0 && effect->resvd2 != 0)
  27288. {
  27289. return ((VSTPluginInstance*)(effect->resvd2))
  27290. ->handleCallback (opcode, index, value, ptr, opt);
  27291. }
  27292. return handleGeneralCallback (opcode, index, value, ptr, opt);
  27293. }
  27294. catch (...)
  27295. {
  27296. return 0;
  27297. }
  27298. }
  27299. const String VSTPluginInstance::getVersion() const throw()
  27300. {
  27301. unsigned int v = dispatch (effGetVendorVersion, 0, 0, 0, 0);
  27302. String s;
  27303. if (v == 0 || v == -1)
  27304. v = getVersionNumber();
  27305. if (v != 0)
  27306. {
  27307. int versionBits[4];
  27308. int n = 0;
  27309. while (v != 0)
  27310. {
  27311. versionBits [n++] = (v & 0xff);
  27312. v >>= 8;
  27313. }
  27314. s << 'V';
  27315. while (n > 0)
  27316. {
  27317. s << versionBits [--n];
  27318. if (n > 0)
  27319. s << '.';
  27320. }
  27321. }
  27322. return s;
  27323. }
  27324. int VSTPluginInstance::getUID() const throw()
  27325. {
  27326. int uid = effect != 0 ? effect->uniqueID : 0;
  27327. if (uid == 0)
  27328. uid = module->file.hashCode();
  27329. return uid;
  27330. }
  27331. const String VSTPluginInstance::getCategory() const throw()
  27332. {
  27333. const char* result = 0;
  27334. switch (dispatch (effGetPlugCategory, 0, 0, 0, 0))
  27335. {
  27336. case kPlugCategEffect:
  27337. result = "Effect";
  27338. break;
  27339. case kPlugCategSynth:
  27340. result = "Synth";
  27341. break;
  27342. case kPlugCategAnalysis:
  27343. result = "Anaylsis";
  27344. break;
  27345. case kPlugCategMastering:
  27346. result = "Mastering";
  27347. break;
  27348. case kPlugCategSpacializer:
  27349. result = "Spacial";
  27350. break;
  27351. case kPlugCategRoomFx:
  27352. result = "Reverb";
  27353. break;
  27354. case kPlugSurroundFx:
  27355. result = "Surround";
  27356. break;
  27357. case kPlugCategRestoration:
  27358. result = "Restoration";
  27359. break;
  27360. case kPlugCategGenerator:
  27361. result = "Tone generation";
  27362. break;
  27363. default:
  27364. break;
  27365. }
  27366. return result;
  27367. }
  27368. float VSTPluginInstance::getParameter (int index)
  27369. {
  27370. if (effect != 0 && ((unsigned int) index) < (unsigned int) effect->numParams)
  27371. {
  27372. try
  27373. {
  27374. const ScopedLock sl (lock);
  27375. return effect->getParameter (effect, index);
  27376. }
  27377. catch (...)
  27378. {
  27379. }
  27380. }
  27381. return 0.0f;
  27382. }
  27383. void VSTPluginInstance::setParameter (int index, float newValue)
  27384. {
  27385. if (effect != 0 && ((unsigned int) index) < (unsigned int) effect->numParams)
  27386. {
  27387. try
  27388. {
  27389. const ScopedLock sl (lock);
  27390. if (effect->getParameter (effect, index) != newValue)
  27391. effect->setParameter (effect, index, newValue);
  27392. }
  27393. catch (...)
  27394. {
  27395. }
  27396. }
  27397. }
  27398. const String VSTPluginInstance::getParameterName (int index)
  27399. {
  27400. if (effect != 0)
  27401. {
  27402. jassert (index >= 0 && index < effect->numParams);
  27403. char nm [256];
  27404. zerostruct (nm);
  27405. dispatch (effGetParamName, index, 0, nm, 0);
  27406. return String (nm).trim();
  27407. }
  27408. return String::empty;
  27409. }
  27410. const String VSTPluginInstance::getParameterLabel (int index) const
  27411. {
  27412. if (effect != 0)
  27413. {
  27414. jassert (index >= 0 && index < effect->numParams);
  27415. char nm [256];
  27416. zerostruct (nm);
  27417. dispatch (effGetParamLabel, index, 0, nm, 0);
  27418. return String (nm).trim();
  27419. }
  27420. return String::empty;
  27421. }
  27422. const String VSTPluginInstance::getParameterText (int index)
  27423. {
  27424. if (effect != 0)
  27425. {
  27426. jassert (index >= 0 && index < effect->numParams);
  27427. char nm [256];
  27428. zerostruct (nm);
  27429. dispatch (effGetParamDisplay, index, 0, nm, 0);
  27430. return String (nm).trim();
  27431. }
  27432. return String::empty;
  27433. }
  27434. bool VSTPluginInstance::isParameterAutomatable (int index) const
  27435. {
  27436. if (effect != 0)
  27437. {
  27438. jassert (index >= 0 && index < effect->numParams);
  27439. return dispatch (effCanBeAutomated, index, 0, 0, 0) != 0;
  27440. }
  27441. return false;
  27442. }
  27443. void VSTPluginInstance::createTempParameterStore (MemoryBlock& dest)
  27444. {
  27445. dest.setSize (64 + 4 * getNumParameters());
  27446. dest.fillWith (0);
  27447. getCurrentProgramName().copyToCString ((char*) dest.getData(), 63);
  27448. float* const p = (float*) (((char*) dest.getData()) + 64);
  27449. for (int i = 0; i < getNumParameters(); ++i)
  27450. p[i] = getParameter(i);
  27451. }
  27452. void VSTPluginInstance::restoreFromTempParameterStore (const MemoryBlock& m)
  27453. {
  27454. changeProgramName (getCurrentProgram(), (const char*) m.getData());
  27455. float* p = (float*) (((char*) m.getData()) + 64);
  27456. for (int i = 0; i < getNumParameters(); ++i)
  27457. setParameter (i, p[i]);
  27458. }
  27459. void VSTPluginInstance::setCurrentProgram (int newIndex)
  27460. {
  27461. if (getNumPrograms() > 0 && newIndex != getCurrentProgram())
  27462. dispatch (effSetProgram, 0, jlimit (0, getNumPrograms() - 1, newIndex), 0, 0);
  27463. }
  27464. const String VSTPluginInstance::getProgramName (int index)
  27465. {
  27466. if (index == getCurrentProgram())
  27467. {
  27468. return getCurrentProgramName();
  27469. }
  27470. else if (effect != 0)
  27471. {
  27472. char nm [256];
  27473. zerostruct (nm);
  27474. if (dispatch (effGetProgramNameIndexed,
  27475. jlimit (0, getNumPrograms(), index),
  27476. -1, nm, 0) != 0)
  27477. {
  27478. return String (nm).trim();
  27479. }
  27480. }
  27481. return programNames [index];
  27482. }
  27483. void VSTPluginInstance::changeProgramName (int index, const String& newName)
  27484. {
  27485. if (index == getCurrentProgram())
  27486. {
  27487. if (getNumPrograms() > 0 && newName != getCurrentProgramName())
  27488. dispatch (effSetProgramName, 0, 0, (void*) newName.substring (0, 24).toCString(), 0.0f);
  27489. }
  27490. else
  27491. {
  27492. jassertfalse // xxx not implemented!
  27493. }
  27494. }
  27495. void VSTPluginInstance::updateStoredProgramNames()
  27496. {
  27497. if (effect != 0 && getNumPrograms() > 0)
  27498. {
  27499. char nm [256];
  27500. zerostruct (nm);
  27501. // only do this if the plugin can't use indexed names..
  27502. if (dispatch (effGetProgramNameIndexed, 0, -1, nm, 0) == 0)
  27503. {
  27504. const int oldProgram = getCurrentProgram();
  27505. MemoryBlock oldSettings;
  27506. createTempParameterStore (oldSettings);
  27507. for (int i = 0; i < getNumPrograms(); ++i)
  27508. {
  27509. setCurrentProgram (i);
  27510. getCurrentProgramName(); // (this updates the list)
  27511. }
  27512. setCurrentProgram (oldProgram);
  27513. restoreFromTempParameterStore (oldSettings);
  27514. }
  27515. }
  27516. }
  27517. const String VSTPluginInstance::getCurrentProgramName()
  27518. {
  27519. if (effect != 0)
  27520. {
  27521. char nm [256];
  27522. zerostruct (nm);
  27523. dispatch (effGetProgramName, 0, 0, nm, 0);
  27524. const int index = getCurrentProgram();
  27525. if (programNames[index].isEmpty())
  27526. {
  27527. while (programNames.size() < index)
  27528. programNames.add (String::empty);
  27529. programNames.set (index, String (nm).trim());
  27530. }
  27531. return String (nm).trim();
  27532. }
  27533. return String::empty;
  27534. }
  27535. const String VSTPluginInstance::getInputChannelName (const int index) const
  27536. {
  27537. if (index >= 0 && index < getNumInputChannels())
  27538. {
  27539. VstPinProperties pinProps;
  27540. if (dispatch (effGetInputProperties, index, 0, &pinProps, 0.0f) != 0)
  27541. return String (pinProps.label, sizeof (pinProps.label));
  27542. }
  27543. return String::empty;
  27544. }
  27545. bool VSTPluginInstance::isInputChannelStereoPair (int index) const
  27546. {
  27547. if (index < 0 || index >= getNumInputChannels())
  27548. return false;
  27549. VstPinProperties pinProps;
  27550. if (dispatch (effGetInputProperties, index, 0, &pinProps, 0.0f) != 0)
  27551. return (pinProps.flags & kVstPinIsStereo) != 0;
  27552. return true;
  27553. }
  27554. const String VSTPluginInstance::getOutputChannelName (const int index) const
  27555. {
  27556. if (index >= 0 && index < getNumOutputChannels())
  27557. {
  27558. VstPinProperties pinProps;
  27559. if (dispatch (effGetOutputProperties, index, 0, &pinProps, 0.0f) != 0)
  27560. return String (pinProps.label, sizeof (pinProps.label));
  27561. }
  27562. return String::empty;
  27563. }
  27564. bool VSTPluginInstance::isOutputChannelStereoPair (int index) const
  27565. {
  27566. if (index < 0 || index >= getNumOutputChannels())
  27567. return false;
  27568. VstPinProperties pinProps;
  27569. if (dispatch (effGetOutputProperties, index, 0, &pinProps, 0.0f) != 0)
  27570. return (pinProps.flags & kVstPinIsStereo) != 0;
  27571. return true;
  27572. }
  27573. void VSTPluginInstance::setPower (const bool on)
  27574. {
  27575. dispatch (effMainsChanged, 0, on ? 1 : 0, 0, 0);
  27576. isPowerOn = on;
  27577. }
  27578. const int defaultMaxSizeMB = 64;
  27579. void VSTPluginInstance::getStateInformation (MemoryBlock& destData)
  27580. {
  27581. saveToFXBFile (destData, true, defaultMaxSizeMB);
  27582. }
  27583. void VSTPluginInstance::getCurrentProgramStateInformation (MemoryBlock& destData)
  27584. {
  27585. saveToFXBFile (destData, false, defaultMaxSizeMB);
  27586. }
  27587. void VSTPluginInstance::setStateInformation (const void* data, int sizeInBytes)
  27588. {
  27589. loadFromFXBFile (data, sizeInBytes);
  27590. }
  27591. void VSTPluginInstance::setCurrentProgramStateInformation (const void* data, int sizeInBytes)
  27592. {
  27593. loadFromFXBFile (data, sizeInBytes);
  27594. }
  27595. VSTPluginFormat::VSTPluginFormat()
  27596. {
  27597. }
  27598. VSTPluginFormat::~VSTPluginFormat()
  27599. {
  27600. }
  27601. void VSTPluginFormat::findAllTypesForFile (OwnedArray <PluginDescription>& results,
  27602. const String& fileOrIdentifier)
  27603. {
  27604. if (! fileMightContainThisPluginType (fileOrIdentifier))
  27605. return;
  27606. PluginDescription desc;
  27607. desc.fileOrIdentifier = fileOrIdentifier;
  27608. desc.uid = 0;
  27609. ScopedPointer <VSTPluginInstance> instance (dynamic_cast <VSTPluginInstance*> (createInstanceFromDescription (desc)));
  27610. if (instance == 0)
  27611. return;
  27612. try
  27613. {
  27614. #if JUCE_MAC
  27615. if (instance->module->resFileId != 0)
  27616. UseResFile (instance->module->resFileId);
  27617. #endif
  27618. instance->fillInPluginDescription (desc);
  27619. VstPlugCategory category = (VstPlugCategory) instance->dispatch (effGetPlugCategory, 0, 0, 0, 0);
  27620. if (category != kPlugCategShell)
  27621. {
  27622. // Normal plugin...
  27623. results.add (new PluginDescription (desc));
  27624. ++insideVSTCallback;
  27625. instance->dispatch (effOpen, 0, 0, 0, 0);
  27626. --insideVSTCallback;
  27627. }
  27628. else
  27629. {
  27630. // It's a shell plugin, so iterate all the subtypes...
  27631. char shellEffectName [64];
  27632. for (;;)
  27633. {
  27634. zerostruct (shellEffectName);
  27635. const int uid = instance->dispatch (effShellGetNextPlugin, 0, 0, shellEffectName, 0);
  27636. if (uid == 0)
  27637. {
  27638. break;
  27639. }
  27640. else
  27641. {
  27642. desc.uid = uid;
  27643. desc.name = shellEffectName;
  27644. bool alreadyThere = false;
  27645. for (int i = results.size(); --i >= 0;)
  27646. {
  27647. PluginDescription* const d = results.getUnchecked(i);
  27648. if (d->isDuplicateOf (desc))
  27649. {
  27650. alreadyThere = true;
  27651. break;
  27652. }
  27653. }
  27654. if (! alreadyThere)
  27655. results.add (new PluginDescription (desc));
  27656. }
  27657. }
  27658. }
  27659. }
  27660. catch (...)
  27661. {
  27662. // crashed while loading...
  27663. }
  27664. }
  27665. AudioPluginInstance* VSTPluginFormat::createInstanceFromDescription (const PluginDescription& desc)
  27666. {
  27667. ScopedPointer <VSTPluginInstance> result;
  27668. if (fileMightContainThisPluginType (desc.fileOrIdentifier))
  27669. {
  27670. File file (desc.fileOrIdentifier);
  27671. const File previousWorkingDirectory (File::getCurrentWorkingDirectory());
  27672. file.getParentDirectory().setAsCurrentWorkingDirectory();
  27673. const ReferenceCountedObjectPtr <ModuleHandle> module (ModuleHandle::findOrCreateModule (file));
  27674. if (module != 0)
  27675. {
  27676. shellUIDToCreate = desc.uid;
  27677. result = new VSTPluginInstance (module);
  27678. if (result->effect != 0)
  27679. {
  27680. result->effect->resvd2 = (VstIntPtr) (pointer_sized_int) (VSTPluginInstance*) result;
  27681. result->initialise();
  27682. }
  27683. else
  27684. {
  27685. result = 0;
  27686. }
  27687. }
  27688. previousWorkingDirectory.setAsCurrentWorkingDirectory();
  27689. }
  27690. return result.release();
  27691. }
  27692. bool VSTPluginFormat::fileMightContainThisPluginType (const String& fileOrIdentifier)
  27693. {
  27694. const File f (fileOrIdentifier);
  27695. #if JUCE_MAC
  27696. if (f.isDirectory() && f.hasFileExtension (".vst"))
  27697. return true;
  27698. #if JUCE_PPC
  27699. FSRef fileRef;
  27700. if (PlatformUtilities::makeFSRefFromPath (&fileRef, f.getFullPathName()))
  27701. {
  27702. const short resFileId = FSOpenResFile (&fileRef, fsRdPerm);
  27703. if (resFileId != -1)
  27704. {
  27705. const int numEffects = Count1Resources ('aEff');
  27706. CloseResFile (resFileId);
  27707. if (numEffects > 0)
  27708. return true;
  27709. }
  27710. }
  27711. #endif
  27712. return false;
  27713. #elif JUCE_WIN32
  27714. return f.existsAsFile()
  27715. && f.hasFileExtension (".dll");
  27716. #elif JUCE_LINUX
  27717. return f.existsAsFile()
  27718. && f.hasFileExtension (".so");
  27719. #endif
  27720. }
  27721. const String VSTPluginFormat::getNameOfPluginFromIdentifier (const String& fileOrIdentifier)
  27722. {
  27723. return fileOrIdentifier;
  27724. }
  27725. bool VSTPluginFormat::doesPluginStillExist (const PluginDescription& desc)
  27726. {
  27727. return File (desc.fileOrIdentifier).exists();
  27728. }
  27729. const StringArray VSTPluginFormat::searchPathsForPlugins (const FileSearchPath& directoriesToSearch, const bool recursive)
  27730. {
  27731. StringArray results;
  27732. for (int j = 0; j < directoriesToSearch.getNumPaths(); ++j)
  27733. recursiveFileSearch (results, directoriesToSearch [j], recursive);
  27734. return results;
  27735. }
  27736. void VSTPluginFormat::recursiveFileSearch (StringArray& results, const File& dir, const bool recursive)
  27737. {
  27738. // avoid allowing the dir iterator to be recursive, because we want to avoid letting it delve inside
  27739. // .component or .vst directories.
  27740. DirectoryIterator iter (dir, false, "*", File::findFilesAndDirectories);
  27741. while (iter.next())
  27742. {
  27743. const File f (iter.getFile());
  27744. bool isPlugin = false;
  27745. if (fileMightContainThisPluginType (f.getFullPathName()))
  27746. {
  27747. isPlugin = true;
  27748. results.add (f.getFullPathName());
  27749. }
  27750. if (recursive && (! isPlugin) && f.isDirectory())
  27751. recursiveFileSearch (results, f, true);
  27752. }
  27753. }
  27754. const FileSearchPath VSTPluginFormat::getDefaultLocationsToSearch()
  27755. {
  27756. #if JUCE_MAC
  27757. return FileSearchPath ("~/Library/Audio/Plug-Ins/VST;/Library/Audio/Plug-Ins/VST");
  27758. #elif JUCE_WIN32
  27759. const String programFiles (File::getSpecialLocation (File::globalApplicationsDirectory).getFullPathName());
  27760. return FileSearchPath (programFiles + "\\Steinberg\\VstPlugins");
  27761. #elif JUCE_LINUX
  27762. return FileSearchPath ("/usr/lib/vst");
  27763. #endif
  27764. }
  27765. END_JUCE_NAMESPACE
  27766. #endif
  27767. #undef log
  27768. #endif
  27769. /*** End of inlined file: juce_VSTPluginFormat.cpp ***/
  27770. /*** End of inlined file: juce_VSTPluginFormat.mm ***/
  27771. /*** Start of inlined file: juce_AudioProcessor.cpp ***/
  27772. BEGIN_JUCE_NAMESPACE
  27773. AudioProcessor::AudioProcessor()
  27774. : playHead (0),
  27775. activeEditor (0),
  27776. sampleRate (0),
  27777. blockSize (0),
  27778. numInputChannels (0),
  27779. numOutputChannels (0),
  27780. latencySamples (0),
  27781. suspended (false),
  27782. nonRealtime (false)
  27783. {
  27784. }
  27785. AudioProcessor::~AudioProcessor()
  27786. {
  27787. // ooh, nasty - the editor should have been deleted before the filter
  27788. // that it refers to is deleted..
  27789. jassert (activeEditor == 0);
  27790. #if JUCE_DEBUG
  27791. // This will fail if you've called beginParameterChangeGesture() for one
  27792. // or more parameters without having made a corresponding call to endParameterChangeGesture...
  27793. jassert (changingParams.countNumberOfSetBits() == 0);
  27794. #endif
  27795. }
  27796. void AudioProcessor::setPlayHead (AudioPlayHead* const newPlayHead) throw()
  27797. {
  27798. playHead = newPlayHead;
  27799. }
  27800. void AudioProcessor::addListener (AudioProcessorListener* const newListener) throw()
  27801. {
  27802. const ScopedLock sl (listenerLock);
  27803. listeners.addIfNotAlreadyThere (newListener);
  27804. }
  27805. void AudioProcessor::removeListener (AudioProcessorListener* const listenerToRemove) throw()
  27806. {
  27807. const ScopedLock sl (listenerLock);
  27808. listeners.removeValue (listenerToRemove);
  27809. }
  27810. void AudioProcessor::setPlayConfigDetails (const int numIns,
  27811. const int numOuts,
  27812. const double sampleRate_,
  27813. const int blockSize_) throw()
  27814. {
  27815. numInputChannels = numIns;
  27816. numOutputChannels = numOuts;
  27817. sampleRate = sampleRate_;
  27818. blockSize = blockSize_;
  27819. }
  27820. void AudioProcessor::setNonRealtime (const bool nonRealtime_) throw()
  27821. {
  27822. nonRealtime = nonRealtime_;
  27823. }
  27824. void AudioProcessor::setLatencySamples (const int newLatency)
  27825. {
  27826. if (latencySamples != newLatency)
  27827. {
  27828. latencySamples = newLatency;
  27829. updateHostDisplay();
  27830. }
  27831. }
  27832. void AudioProcessor::setParameterNotifyingHost (const int parameterIndex,
  27833. const float newValue)
  27834. {
  27835. setParameter (parameterIndex, newValue);
  27836. sendParamChangeMessageToListeners (parameterIndex, newValue);
  27837. }
  27838. void AudioProcessor::sendParamChangeMessageToListeners (const int parameterIndex, const float newValue)
  27839. {
  27840. jassert (((unsigned int) parameterIndex) < (unsigned int) getNumParameters());
  27841. for (int i = listeners.size(); --i >= 0;)
  27842. {
  27843. AudioProcessorListener* l;
  27844. {
  27845. const ScopedLock sl (listenerLock);
  27846. l = (AudioProcessorListener*) listeners [i];
  27847. }
  27848. if (l != 0)
  27849. l->audioProcessorParameterChanged (this, parameterIndex, newValue);
  27850. }
  27851. }
  27852. void AudioProcessor::beginParameterChangeGesture (int parameterIndex)
  27853. {
  27854. jassert (((unsigned int) parameterIndex) < (unsigned int) getNumParameters());
  27855. #if JUCE_DEBUG
  27856. // This means you've called beginParameterChangeGesture twice in succession without a matching
  27857. // call to endParameterChangeGesture. That might be fine in most hosts, but better to avoid doing it.
  27858. jassert (! changingParams [parameterIndex]);
  27859. changingParams.setBit (parameterIndex);
  27860. #endif
  27861. for (int i = listeners.size(); --i >= 0;)
  27862. {
  27863. AudioProcessorListener* l;
  27864. {
  27865. const ScopedLock sl (listenerLock);
  27866. l = (AudioProcessorListener*) listeners [i];
  27867. }
  27868. if (l != 0)
  27869. l->audioProcessorParameterChangeGestureBegin (this, parameterIndex);
  27870. }
  27871. }
  27872. void AudioProcessor::endParameterChangeGesture (int parameterIndex)
  27873. {
  27874. jassert (((unsigned int) parameterIndex) < (unsigned int) getNumParameters());
  27875. #if JUCE_DEBUG
  27876. // This means you've called endParameterChangeGesture without having previously called
  27877. // endParameterChangeGesture. That might be fine in most hosts, but better to keep the
  27878. // calls matched correctly.
  27879. jassert (changingParams [parameterIndex]);
  27880. changingParams.clearBit (parameterIndex);
  27881. #endif
  27882. for (int i = listeners.size(); --i >= 0;)
  27883. {
  27884. AudioProcessorListener* l;
  27885. {
  27886. const ScopedLock sl (listenerLock);
  27887. l = (AudioProcessorListener*) listeners [i];
  27888. }
  27889. if (l != 0)
  27890. l->audioProcessorParameterChangeGestureEnd (this, parameterIndex);
  27891. }
  27892. }
  27893. void AudioProcessor::updateHostDisplay()
  27894. {
  27895. for (int i = listeners.size(); --i >= 0;)
  27896. {
  27897. AudioProcessorListener* l;
  27898. {
  27899. const ScopedLock sl (listenerLock);
  27900. l = (AudioProcessorListener*) listeners [i];
  27901. }
  27902. if (l != 0)
  27903. l->audioProcessorChanged (this);
  27904. }
  27905. }
  27906. bool AudioProcessor::isParameterAutomatable (int /*parameterIndex*/) const
  27907. {
  27908. return true;
  27909. }
  27910. bool AudioProcessor::isMetaParameter (int /*parameterIndex*/) const
  27911. {
  27912. return false;
  27913. }
  27914. void AudioProcessor::suspendProcessing (const bool shouldBeSuspended)
  27915. {
  27916. const ScopedLock sl (callbackLock);
  27917. suspended = shouldBeSuspended;
  27918. }
  27919. void AudioProcessor::reset()
  27920. {
  27921. }
  27922. void AudioProcessor::editorBeingDeleted (AudioProcessorEditor* const editor) throw()
  27923. {
  27924. const ScopedLock sl (callbackLock);
  27925. jassert (activeEditor == editor);
  27926. if (activeEditor == editor)
  27927. activeEditor = 0;
  27928. }
  27929. AudioProcessorEditor* AudioProcessor::createEditorIfNeeded()
  27930. {
  27931. if (activeEditor != 0)
  27932. return activeEditor;
  27933. AudioProcessorEditor* const ed = createEditor();
  27934. if (ed != 0)
  27935. {
  27936. // you must give your editor comp a size before returning it..
  27937. jassert (ed->getWidth() > 0 && ed->getHeight() > 0);
  27938. const ScopedLock sl (callbackLock);
  27939. activeEditor = ed;
  27940. }
  27941. return ed;
  27942. }
  27943. void AudioProcessor::getCurrentProgramStateInformation (JUCE_NAMESPACE::MemoryBlock& destData)
  27944. {
  27945. getStateInformation (destData);
  27946. }
  27947. void AudioProcessor::setCurrentProgramStateInformation (const void* data, int sizeInBytes)
  27948. {
  27949. setStateInformation (data, sizeInBytes);
  27950. }
  27951. // magic number to identify memory blocks that we've stored as XML
  27952. const uint32 magicXmlNumber = 0x21324356;
  27953. void AudioProcessor::copyXmlToBinary (const XmlElement& xml,
  27954. JUCE_NAMESPACE::MemoryBlock& destData)
  27955. {
  27956. const String xmlString (xml.createDocument (String::empty, true, false));
  27957. const int stringLength = xmlString.getNumBytesAsUTF8();
  27958. destData.setSize (stringLength + 10);
  27959. char* const d = (char*) destData.getData();
  27960. *(uint32*) d = ByteOrder::swapIfBigEndian ((const uint32) magicXmlNumber);
  27961. *(uint32*) (d + 4) = ByteOrder::swapIfBigEndian ((const uint32) stringLength);
  27962. xmlString.copyToUTF8 (d + 8, stringLength + 1);
  27963. }
  27964. XmlElement* AudioProcessor::getXmlFromBinary (const void* data,
  27965. const int sizeInBytes)
  27966. {
  27967. if (sizeInBytes > 8
  27968. && ByteOrder::littleEndianInt (data) == magicXmlNumber)
  27969. {
  27970. const int stringLength = (int) ByteOrder::littleEndianInt (((const char*) data) + 4);
  27971. if (stringLength > 0)
  27972. {
  27973. XmlDocument doc (String::fromUTF8 (((const char*) data) + 8,
  27974. jmin ((sizeInBytes - 8), stringLength)));
  27975. return doc.getDocumentElement();
  27976. }
  27977. }
  27978. return 0;
  27979. }
  27980. void AudioProcessorListener::audioProcessorParameterChangeGestureBegin (AudioProcessor*, int)
  27981. {
  27982. }
  27983. void AudioProcessorListener::audioProcessorParameterChangeGestureEnd (AudioProcessor*, int)
  27984. {
  27985. }
  27986. bool AudioPlayHead::CurrentPositionInfo::operator== (const CurrentPositionInfo& other) const throw()
  27987. {
  27988. return timeInSeconds == other.timeInSeconds
  27989. && ppqPosition == other.ppqPosition
  27990. && editOriginTime == other.editOriginTime
  27991. && ppqPositionOfLastBarStart == other.ppqPositionOfLastBarStart
  27992. && frameRate == other.frameRate
  27993. && isPlaying == other.isPlaying
  27994. && isRecording == other.isRecording
  27995. && bpm == other.bpm
  27996. && timeSigNumerator == other.timeSigNumerator
  27997. && timeSigDenominator == other.timeSigDenominator;
  27998. }
  27999. bool AudioPlayHead::CurrentPositionInfo::operator!= (const CurrentPositionInfo& other) const throw()
  28000. {
  28001. return ! operator== (other);
  28002. }
  28003. void AudioPlayHead::CurrentPositionInfo::resetToDefault()
  28004. {
  28005. zerostruct (*this);
  28006. timeSigNumerator = 4;
  28007. timeSigDenominator = 4;
  28008. bpm = 120;
  28009. }
  28010. END_JUCE_NAMESPACE
  28011. /*** End of inlined file: juce_AudioProcessor.cpp ***/
  28012. /*** Start of inlined file: juce_AudioProcessorEditor.cpp ***/
  28013. BEGIN_JUCE_NAMESPACE
  28014. AudioProcessorEditor::AudioProcessorEditor (AudioProcessor* const owner_)
  28015. : owner (owner_)
  28016. {
  28017. // the filter must be valid..
  28018. jassert (owner != 0);
  28019. }
  28020. AudioProcessorEditor::~AudioProcessorEditor()
  28021. {
  28022. // if this fails, then the wrapper hasn't called editorBeingDeleted() on the
  28023. // filter for some reason..
  28024. jassert (owner->getActiveEditor() != this);
  28025. }
  28026. END_JUCE_NAMESPACE
  28027. /*** End of inlined file: juce_AudioProcessorEditor.cpp ***/
  28028. /*** Start of inlined file: juce_AudioProcessorGraph.cpp ***/
  28029. BEGIN_JUCE_NAMESPACE
  28030. const int AudioProcessorGraph::midiChannelIndex = 0x1000;
  28031. AudioProcessorGraph::Node::Node (const uint32 id_, AudioProcessor* const processor_)
  28032. : id (id_),
  28033. processor (processor_),
  28034. isPrepared (false)
  28035. {
  28036. jassert (processor_ != 0);
  28037. }
  28038. AudioProcessorGraph::Node::~Node()
  28039. {
  28040. delete processor;
  28041. }
  28042. void AudioProcessorGraph::Node::prepare (const double sampleRate, const int blockSize,
  28043. AudioProcessorGraph* const graph)
  28044. {
  28045. if (! isPrepared)
  28046. {
  28047. isPrepared = true;
  28048. AudioProcessorGraph::AudioGraphIOProcessor* const ioProc
  28049. = dynamic_cast <AudioProcessorGraph::AudioGraphIOProcessor*> (processor);
  28050. if (ioProc != 0)
  28051. ioProc->setParentGraph (graph);
  28052. processor->setPlayConfigDetails (processor->getNumInputChannels(),
  28053. processor->getNumOutputChannels(),
  28054. sampleRate, blockSize);
  28055. processor->prepareToPlay (sampleRate, blockSize);
  28056. }
  28057. }
  28058. void AudioProcessorGraph::Node::unprepare()
  28059. {
  28060. if (isPrepared)
  28061. {
  28062. isPrepared = false;
  28063. processor->releaseResources();
  28064. }
  28065. }
  28066. AudioProcessorGraph::AudioProcessorGraph()
  28067. : lastNodeId (0),
  28068. renderingBuffers (1, 1),
  28069. currentAudioOutputBuffer (1, 1)
  28070. {
  28071. }
  28072. AudioProcessorGraph::~AudioProcessorGraph()
  28073. {
  28074. clearRenderingSequence();
  28075. clear();
  28076. }
  28077. const String AudioProcessorGraph::getName() const
  28078. {
  28079. return "Audio Graph";
  28080. }
  28081. void AudioProcessorGraph::clear()
  28082. {
  28083. nodes.clear();
  28084. connections.clear();
  28085. triggerAsyncUpdate();
  28086. }
  28087. AudioProcessorGraph::Node* AudioProcessorGraph::getNodeForId (const uint32 nodeId) const
  28088. {
  28089. for (int i = nodes.size(); --i >= 0;)
  28090. if (nodes.getUnchecked(i)->id == nodeId)
  28091. return nodes.getUnchecked(i);
  28092. return 0;
  28093. }
  28094. AudioProcessorGraph::Node* AudioProcessorGraph::addNode (AudioProcessor* const newProcessor,
  28095. uint32 nodeId)
  28096. {
  28097. if (newProcessor == 0)
  28098. {
  28099. jassertfalse
  28100. return 0;
  28101. }
  28102. if (nodeId == 0)
  28103. {
  28104. nodeId = ++lastNodeId;
  28105. }
  28106. else
  28107. {
  28108. // you can't add a node with an id that already exists in the graph..
  28109. jassert (getNodeForId (nodeId) == 0);
  28110. removeNode (nodeId);
  28111. }
  28112. lastNodeId = nodeId;
  28113. Node* const n = new Node (nodeId, newProcessor);
  28114. nodes.add (n);
  28115. triggerAsyncUpdate();
  28116. AudioProcessorGraph::AudioGraphIOProcessor* const ioProc
  28117. = dynamic_cast <AudioProcessorGraph::AudioGraphIOProcessor*> (n->processor);
  28118. if (ioProc != 0)
  28119. ioProc->setParentGraph (this);
  28120. return n;
  28121. }
  28122. bool AudioProcessorGraph::removeNode (const uint32 nodeId)
  28123. {
  28124. disconnectNode (nodeId);
  28125. for (int i = nodes.size(); --i >= 0;)
  28126. {
  28127. if (nodes.getUnchecked(i)->id == nodeId)
  28128. {
  28129. AudioProcessorGraph::AudioGraphIOProcessor* const ioProc
  28130. = dynamic_cast <AudioProcessorGraph::AudioGraphIOProcessor*> (nodes.getUnchecked(i)->processor);
  28131. if (ioProc != 0)
  28132. ioProc->setParentGraph (0);
  28133. nodes.remove (i);
  28134. triggerAsyncUpdate();
  28135. return true;
  28136. }
  28137. }
  28138. return false;
  28139. }
  28140. const AudioProcessorGraph::Connection* AudioProcessorGraph::getConnectionBetween (const uint32 sourceNodeId,
  28141. const int sourceChannelIndex,
  28142. const uint32 destNodeId,
  28143. const int destChannelIndex) const
  28144. {
  28145. for (int i = connections.size(); --i >= 0;)
  28146. {
  28147. const Connection* const c = connections.getUnchecked(i);
  28148. if (c->sourceNodeId == sourceNodeId
  28149. && c->destNodeId == destNodeId
  28150. && c->sourceChannelIndex == sourceChannelIndex
  28151. && c->destChannelIndex == destChannelIndex)
  28152. {
  28153. return c;
  28154. }
  28155. }
  28156. return 0;
  28157. }
  28158. bool AudioProcessorGraph::isConnected (const uint32 possibleSourceNodeId,
  28159. const uint32 possibleDestNodeId) const
  28160. {
  28161. for (int i = connections.size(); --i >= 0;)
  28162. {
  28163. const Connection* const c = connections.getUnchecked(i);
  28164. if (c->sourceNodeId == possibleSourceNodeId
  28165. && c->destNodeId == possibleDestNodeId)
  28166. {
  28167. return true;
  28168. }
  28169. }
  28170. return false;
  28171. }
  28172. bool AudioProcessorGraph::canConnect (const uint32 sourceNodeId,
  28173. const int sourceChannelIndex,
  28174. const uint32 destNodeId,
  28175. const int destChannelIndex) const
  28176. {
  28177. if (sourceChannelIndex < 0
  28178. || destChannelIndex < 0
  28179. || sourceNodeId == destNodeId
  28180. || (destChannelIndex == midiChannelIndex) != (sourceChannelIndex == midiChannelIndex))
  28181. return false;
  28182. const Node* const source = getNodeForId (sourceNodeId);
  28183. if (source == 0
  28184. || (sourceChannelIndex != midiChannelIndex && sourceChannelIndex >= source->processor->getNumOutputChannels())
  28185. || (sourceChannelIndex == midiChannelIndex && ! source->processor->producesMidi()))
  28186. return false;
  28187. const Node* const dest = getNodeForId (destNodeId);
  28188. if (dest == 0
  28189. || (destChannelIndex != midiChannelIndex && destChannelIndex >= dest->processor->getNumInputChannels())
  28190. || (destChannelIndex == midiChannelIndex && ! dest->processor->acceptsMidi()))
  28191. return false;
  28192. return getConnectionBetween (sourceNodeId, sourceChannelIndex,
  28193. destNodeId, destChannelIndex) == 0;
  28194. }
  28195. bool AudioProcessorGraph::addConnection (const uint32 sourceNodeId,
  28196. const int sourceChannelIndex,
  28197. const uint32 destNodeId,
  28198. const int destChannelIndex)
  28199. {
  28200. if (! canConnect (sourceNodeId, sourceChannelIndex, destNodeId, destChannelIndex))
  28201. return false;
  28202. Connection* const c = new Connection();
  28203. c->sourceNodeId = sourceNodeId;
  28204. c->sourceChannelIndex = sourceChannelIndex;
  28205. c->destNodeId = destNodeId;
  28206. c->destChannelIndex = destChannelIndex;
  28207. connections.add (c);
  28208. triggerAsyncUpdate();
  28209. return true;
  28210. }
  28211. void AudioProcessorGraph::removeConnection (const int index)
  28212. {
  28213. connections.remove (index);
  28214. triggerAsyncUpdate();
  28215. }
  28216. bool AudioProcessorGraph::removeConnection (const uint32 sourceNodeId, const int sourceChannelIndex,
  28217. const uint32 destNodeId, const int destChannelIndex)
  28218. {
  28219. bool doneAnything = false;
  28220. for (int i = connections.size(); --i >= 0;)
  28221. {
  28222. const Connection* const c = connections.getUnchecked(i);
  28223. if (c->sourceNodeId == sourceNodeId
  28224. && c->destNodeId == destNodeId
  28225. && c->sourceChannelIndex == sourceChannelIndex
  28226. && c->destChannelIndex == destChannelIndex)
  28227. {
  28228. removeConnection (i);
  28229. doneAnything = true;
  28230. triggerAsyncUpdate();
  28231. }
  28232. }
  28233. return doneAnything;
  28234. }
  28235. bool AudioProcessorGraph::disconnectNode (const uint32 nodeId)
  28236. {
  28237. bool doneAnything = false;
  28238. for (int i = connections.size(); --i >= 0;)
  28239. {
  28240. const Connection* const c = connections.getUnchecked(i);
  28241. if (c->sourceNodeId == nodeId || c->destNodeId == nodeId)
  28242. {
  28243. removeConnection (i);
  28244. doneAnything = true;
  28245. triggerAsyncUpdate();
  28246. }
  28247. }
  28248. return doneAnything;
  28249. }
  28250. bool AudioProcessorGraph::removeIllegalConnections()
  28251. {
  28252. bool doneAnything = false;
  28253. for (int i = connections.size(); --i >= 0;)
  28254. {
  28255. const Connection* const c = connections.getUnchecked(i);
  28256. const Node* const source = getNodeForId (c->sourceNodeId);
  28257. const Node* const dest = getNodeForId (c->destNodeId);
  28258. if (source == 0 || dest == 0
  28259. || (c->sourceChannelIndex != midiChannelIndex
  28260. && (((unsigned int) c->sourceChannelIndex) >= (unsigned int) source->processor->getNumOutputChannels()))
  28261. || (c->sourceChannelIndex == midiChannelIndex
  28262. && ! source->processor->producesMidi())
  28263. || (c->destChannelIndex != midiChannelIndex
  28264. && (((unsigned int) c->destChannelIndex) >= (unsigned int) dest->processor->getNumInputChannels()))
  28265. || (c->destChannelIndex == midiChannelIndex
  28266. && ! dest->processor->acceptsMidi()))
  28267. {
  28268. removeConnection (i);
  28269. doneAnything = true;
  28270. triggerAsyncUpdate();
  28271. }
  28272. }
  28273. return doneAnything;
  28274. }
  28275. namespace GraphRenderingOps
  28276. {
  28277. class AudioGraphRenderingOp
  28278. {
  28279. public:
  28280. AudioGraphRenderingOp() {}
  28281. virtual ~AudioGraphRenderingOp() {}
  28282. virtual void perform (AudioSampleBuffer& sharedBufferChans,
  28283. const OwnedArray <MidiBuffer>& sharedMidiBuffers,
  28284. const int numSamples) = 0;
  28285. juce_UseDebuggingNewOperator
  28286. };
  28287. class ClearChannelOp : public AudioGraphRenderingOp
  28288. {
  28289. public:
  28290. ClearChannelOp (const int channelNum_)
  28291. : channelNum (channelNum_)
  28292. {}
  28293. ~ClearChannelOp() {}
  28294. void perform (AudioSampleBuffer& sharedBufferChans, const OwnedArray <MidiBuffer>&, const int numSamples)
  28295. {
  28296. sharedBufferChans.clear (channelNum, 0, numSamples);
  28297. }
  28298. private:
  28299. const int channelNum;
  28300. ClearChannelOp (const ClearChannelOp&);
  28301. ClearChannelOp& operator= (const ClearChannelOp&);
  28302. };
  28303. class CopyChannelOp : public AudioGraphRenderingOp
  28304. {
  28305. public:
  28306. CopyChannelOp (const int srcChannelNum_, const int dstChannelNum_)
  28307. : srcChannelNum (srcChannelNum_),
  28308. dstChannelNum (dstChannelNum_)
  28309. {}
  28310. ~CopyChannelOp() {}
  28311. void perform (AudioSampleBuffer& sharedBufferChans, const OwnedArray <MidiBuffer>&, const int numSamples)
  28312. {
  28313. sharedBufferChans.copyFrom (dstChannelNum, 0, sharedBufferChans, srcChannelNum, 0, numSamples);
  28314. }
  28315. private:
  28316. const int srcChannelNum, dstChannelNum;
  28317. CopyChannelOp (const CopyChannelOp&);
  28318. CopyChannelOp& operator= (const CopyChannelOp&);
  28319. };
  28320. class AddChannelOp : public AudioGraphRenderingOp
  28321. {
  28322. public:
  28323. AddChannelOp (const int srcChannelNum_, const int dstChannelNum_)
  28324. : srcChannelNum (srcChannelNum_),
  28325. dstChannelNum (dstChannelNum_)
  28326. {}
  28327. ~AddChannelOp() {}
  28328. void perform (AudioSampleBuffer& sharedBufferChans, const OwnedArray <MidiBuffer>&, const int numSamples)
  28329. {
  28330. sharedBufferChans.addFrom (dstChannelNum, 0, sharedBufferChans, srcChannelNum, 0, numSamples);
  28331. }
  28332. private:
  28333. const int srcChannelNum, dstChannelNum;
  28334. AddChannelOp (const AddChannelOp&);
  28335. AddChannelOp& operator= (const AddChannelOp&);
  28336. };
  28337. class ClearMidiBufferOp : public AudioGraphRenderingOp
  28338. {
  28339. public:
  28340. ClearMidiBufferOp (const int bufferNum_)
  28341. : bufferNum (bufferNum_)
  28342. {}
  28343. ~ClearMidiBufferOp() {}
  28344. void perform (AudioSampleBuffer&, const OwnedArray <MidiBuffer>& sharedMidiBuffers, const int)
  28345. {
  28346. sharedMidiBuffers.getUnchecked (bufferNum)->clear();
  28347. }
  28348. private:
  28349. const int bufferNum;
  28350. ClearMidiBufferOp (const ClearMidiBufferOp&);
  28351. ClearMidiBufferOp& operator= (const ClearMidiBufferOp&);
  28352. };
  28353. class CopyMidiBufferOp : public AudioGraphRenderingOp
  28354. {
  28355. public:
  28356. CopyMidiBufferOp (const int srcBufferNum_, const int dstBufferNum_)
  28357. : srcBufferNum (srcBufferNum_),
  28358. dstBufferNum (dstBufferNum_)
  28359. {}
  28360. ~CopyMidiBufferOp() {}
  28361. void perform (AudioSampleBuffer&, const OwnedArray <MidiBuffer>& sharedMidiBuffers, const int)
  28362. {
  28363. *sharedMidiBuffers.getUnchecked (dstBufferNum) = *sharedMidiBuffers.getUnchecked (srcBufferNum);
  28364. }
  28365. private:
  28366. const int srcBufferNum, dstBufferNum;
  28367. CopyMidiBufferOp (const CopyMidiBufferOp&);
  28368. CopyMidiBufferOp& operator= (const CopyMidiBufferOp&);
  28369. };
  28370. class AddMidiBufferOp : public AudioGraphRenderingOp
  28371. {
  28372. public:
  28373. AddMidiBufferOp (const int srcBufferNum_, const int dstBufferNum_)
  28374. : srcBufferNum (srcBufferNum_),
  28375. dstBufferNum (dstBufferNum_)
  28376. {}
  28377. ~AddMidiBufferOp() {}
  28378. void perform (AudioSampleBuffer&, const OwnedArray <MidiBuffer>& sharedMidiBuffers, const int numSamples)
  28379. {
  28380. sharedMidiBuffers.getUnchecked (dstBufferNum)
  28381. ->addEvents (*sharedMidiBuffers.getUnchecked (srcBufferNum), 0, numSamples, 0);
  28382. }
  28383. private:
  28384. const int srcBufferNum, dstBufferNum;
  28385. AddMidiBufferOp (const AddMidiBufferOp&);
  28386. AddMidiBufferOp& operator= (const AddMidiBufferOp&);
  28387. };
  28388. class ProcessBufferOp : public AudioGraphRenderingOp
  28389. {
  28390. public:
  28391. ProcessBufferOp (const AudioProcessorGraph::Node::Ptr& node_,
  28392. const Array <int>& audioChannelsToUse_,
  28393. const int totalChans_,
  28394. const int midiBufferToUse_)
  28395. : node (node_),
  28396. processor (node_->processor),
  28397. audioChannelsToUse (audioChannelsToUse_),
  28398. totalChans (jmax (1, totalChans_)),
  28399. midiBufferToUse (midiBufferToUse_)
  28400. {
  28401. channels.calloc (totalChans);
  28402. while (audioChannelsToUse.size() < totalChans)
  28403. audioChannelsToUse.add (0);
  28404. }
  28405. ~ProcessBufferOp()
  28406. {
  28407. }
  28408. void perform (AudioSampleBuffer& sharedBufferChans, const OwnedArray <MidiBuffer>& sharedMidiBuffers, const int numSamples)
  28409. {
  28410. for (int i = totalChans; --i >= 0;)
  28411. channels[i] = sharedBufferChans.getSampleData (audioChannelsToUse.getUnchecked (i), 0);
  28412. AudioSampleBuffer buffer (channels, totalChans, numSamples);
  28413. processor->processBlock (buffer, *sharedMidiBuffers.getUnchecked (midiBufferToUse));
  28414. }
  28415. const AudioProcessorGraph::Node::Ptr node;
  28416. AudioProcessor* const processor;
  28417. private:
  28418. Array <int> audioChannelsToUse;
  28419. HeapBlock <float*> channels;
  28420. int totalChans;
  28421. int midiBufferToUse;
  28422. ProcessBufferOp (const ProcessBufferOp&);
  28423. ProcessBufferOp& operator= (const ProcessBufferOp&);
  28424. };
  28425. /** Used to calculate the correct sequence of rendering ops needed, based on
  28426. the best re-use of shared buffers at each stage.
  28427. */
  28428. class RenderingOpSequenceCalculator
  28429. {
  28430. public:
  28431. RenderingOpSequenceCalculator (AudioProcessorGraph& graph_,
  28432. const VoidArray& orderedNodes_,
  28433. VoidArray& renderingOps)
  28434. : graph (graph_),
  28435. orderedNodes (orderedNodes_)
  28436. {
  28437. nodeIds.add (-2); // first buffer is read-only zeros
  28438. channels.add (0);
  28439. midiNodeIds.add (-2);
  28440. for (int i = 0; i < orderedNodes.size(); ++i)
  28441. {
  28442. createRenderingOpsForNode ((AudioProcessorGraph::Node*) orderedNodes.getUnchecked(i),
  28443. renderingOps, i);
  28444. markAnyUnusedBuffersAsFree (i);
  28445. }
  28446. }
  28447. int getNumBuffersNeeded() const { return nodeIds.size(); }
  28448. int getNumMidiBuffersNeeded() const { return midiNodeIds.size(); }
  28449. juce_UseDebuggingNewOperator
  28450. private:
  28451. AudioProcessorGraph& graph;
  28452. const VoidArray& orderedNodes;
  28453. Array <int> nodeIds, channels, midiNodeIds;
  28454. void createRenderingOpsForNode (AudioProcessorGraph::Node* const node,
  28455. VoidArray& renderingOps,
  28456. const int ourRenderingIndex)
  28457. {
  28458. const int numIns = node->processor->getNumInputChannels();
  28459. const int numOuts = node->processor->getNumOutputChannels();
  28460. const int totalChans = jmax (numIns, numOuts);
  28461. Array <int> audioChannelsToUse;
  28462. int midiBufferToUse = -1;
  28463. for (int inputChan = 0; inputChan < numIns; ++inputChan)
  28464. {
  28465. // get a list of all the inputs to this node
  28466. Array <int> sourceNodes, sourceOutputChans;
  28467. for (int i = graph.getNumConnections(); --i >= 0;)
  28468. {
  28469. const AudioProcessorGraph::Connection* const c = graph.getConnection (i);
  28470. if (c->destNodeId == node->id && c->destChannelIndex == inputChan)
  28471. {
  28472. sourceNodes.add (c->sourceNodeId);
  28473. sourceOutputChans.add (c->sourceChannelIndex);
  28474. }
  28475. }
  28476. int bufIndex = -1;
  28477. if (sourceNodes.size() == 0)
  28478. {
  28479. // unconnected input channel
  28480. if (inputChan >= numOuts)
  28481. {
  28482. bufIndex = getReadOnlyEmptyBuffer();
  28483. jassert (bufIndex >= 0);
  28484. }
  28485. else
  28486. {
  28487. bufIndex = getFreeBuffer (false);
  28488. renderingOps.add (new ClearChannelOp (bufIndex));
  28489. }
  28490. }
  28491. else if (sourceNodes.size() == 1)
  28492. {
  28493. // channel with a straightforward single input..
  28494. const int srcNode = sourceNodes.getUnchecked(0);
  28495. const int srcChan = sourceOutputChans.getUnchecked(0);
  28496. bufIndex = getBufferContaining (srcNode, srcChan);
  28497. if (bufIndex < 0)
  28498. {
  28499. // if not found, this is probably a feedback loop
  28500. bufIndex = getReadOnlyEmptyBuffer();
  28501. jassert (bufIndex >= 0);
  28502. }
  28503. if (inputChan < numOuts
  28504. && isBufferNeededLater (ourRenderingIndex,
  28505. inputChan,
  28506. srcNode, srcChan))
  28507. {
  28508. // can't mess up this channel because it's needed later by another node, so we
  28509. // need to use a copy of it..
  28510. const int newFreeBuffer = getFreeBuffer (false);
  28511. renderingOps.add (new CopyChannelOp (bufIndex, newFreeBuffer));
  28512. bufIndex = newFreeBuffer;
  28513. }
  28514. }
  28515. else
  28516. {
  28517. // channel with a mix of several inputs..
  28518. // try to find a re-usable channel from our inputs..
  28519. int reusableInputIndex = -1;
  28520. for (int i = 0; i < sourceNodes.size(); ++i)
  28521. {
  28522. const int sourceBufIndex = getBufferContaining (sourceNodes.getUnchecked(i),
  28523. sourceOutputChans.getUnchecked(i));
  28524. if (sourceBufIndex >= 0
  28525. && ! isBufferNeededLater (ourRenderingIndex,
  28526. inputChan,
  28527. sourceNodes.getUnchecked(i),
  28528. sourceOutputChans.getUnchecked(i)))
  28529. {
  28530. // we've found one of our input chans that can be re-used..
  28531. reusableInputIndex = i;
  28532. bufIndex = sourceBufIndex;
  28533. break;
  28534. }
  28535. }
  28536. if (reusableInputIndex < 0)
  28537. {
  28538. // can't re-use any of our input chans, so get a new one and copy everything into it..
  28539. bufIndex = getFreeBuffer (false);
  28540. jassert (bufIndex != 0);
  28541. const int srcIndex = getBufferContaining (sourceNodes.getUnchecked (0),
  28542. sourceOutputChans.getUnchecked (0));
  28543. if (srcIndex < 0)
  28544. {
  28545. // if not found, this is probably a feedback loop
  28546. renderingOps.add (new ClearChannelOp (bufIndex));
  28547. }
  28548. else
  28549. {
  28550. renderingOps.add (new CopyChannelOp (srcIndex, bufIndex));
  28551. }
  28552. reusableInputIndex = 0;
  28553. }
  28554. for (int j = 0; j < sourceNodes.size(); ++j)
  28555. {
  28556. if (j != reusableInputIndex)
  28557. {
  28558. const int srcIndex = getBufferContaining (sourceNodes.getUnchecked(j),
  28559. sourceOutputChans.getUnchecked(j));
  28560. if (srcIndex >= 0)
  28561. renderingOps.add (new AddChannelOp (srcIndex, bufIndex));
  28562. }
  28563. }
  28564. }
  28565. jassert (bufIndex >= 0);
  28566. audioChannelsToUse.add (bufIndex);
  28567. if (inputChan < numOuts)
  28568. markBufferAsContaining (bufIndex, node->id, inputChan);
  28569. }
  28570. for (int outputChan = numIns; outputChan < numOuts; ++outputChan)
  28571. {
  28572. const int bufIndex = getFreeBuffer (false);
  28573. jassert (bufIndex != 0);
  28574. audioChannelsToUse.add (bufIndex);
  28575. markBufferAsContaining (bufIndex, node->id, outputChan);
  28576. }
  28577. // Now the same thing for midi..
  28578. Array <int> midiSourceNodes;
  28579. for (int i = graph.getNumConnections(); --i >= 0;)
  28580. {
  28581. const AudioProcessorGraph::Connection* const c = graph.getConnection (i);
  28582. if (c->destNodeId == node->id && c->destChannelIndex == AudioProcessorGraph::midiChannelIndex)
  28583. midiSourceNodes.add (c->sourceNodeId);
  28584. }
  28585. if (midiSourceNodes.size() == 0)
  28586. {
  28587. // No midi inputs..
  28588. midiBufferToUse = getFreeBuffer (true); // need to pick a buffer even if the processor doesn't use midi
  28589. if (node->processor->acceptsMidi() || node->processor->producesMidi())
  28590. renderingOps.add (new ClearMidiBufferOp (midiBufferToUse));
  28591. }
  28592. else if (midiSourceNodes.size() == 1)
  28593. {
  28594. // One midi input..
  28595. midiBufferToUse = getBufferContaining (midiSourceNodes.getUnchecked(0),
  28596. AudioProcessorGraph::midiChannelIndex);
  28597. if (midiBufferToUse >= 0)
  28598. {
  28599. if (isBufferNeededLater (ourRenderingIndex,
  28600. AudioProcessorGraph::midiChannelIndex,
  28601. midiSourceNodes.getUnchecked(0),
  28602. AudioProcessorGraph::midiChannelIndex))
  28603. {
  28604. // can't mess up this channel because it's needed later by another node, so we
  28605. // need to use a copy of it..
  28606. const int newFreeBuffer = getFreeBuffer (true);
  28607. renderingOps.add (new CopyMidiBufferOp (midiBufferToUse, newFreeBuffer));
  28608. midiBufferToUse = newFreeBuffer;
  28609. }
  28610. }
  28611. else
  28612. {
  28613. // probably a feedback loop, so just use an empty one..
  28614. midiBufferToUse = getFreeBuffer (true); // need to pick a buffer even if the processor doesn't use midi
  28615. }
  28616. }
  28617. else
  28618. {
  28619. // More than one midi input being mixed..
  28620. int reusableInputIndex = -1;
  28621. for (int i = 0; i < midiSourceNodes.size(); ++i)
  28622. {
  28623. const int sourceBufIndex = getBufferContaining (midiSourceNodes.getUnchecked(i),
  28624. AudioProcessorGraph::midiChannelIndex);
  28625. if (sourceBufIndex >= 0
  28626. && ! isBufferNeededLater (ourRenderingIndex,
  28627. AudioProcessorGraph::midiChannelIndex,
  28628. midiSourceNodes.getUnchecked(i),
  28629. AudioProcessorGraph::midiChannelIndex))
  28630. {
  28631. // we've found one of our input buffers that can be re-used..
  28632. reusableInputIndex = i;
  28633. midiBufferToUse = sourceBufIndex;
  28634. break;
  28635. }
  28636. }
  28637. if (reusableInputIndex < 0)
  28638. {
  28639. // can't re-use any of our input buffers, so get a new one and copy everything into it..
  28640. midiBufferToUse = getFreeBuffer (true);
  28641. jassert (midiBufferToUse >= 0);
  28642. const int srcIndex = getBufferContaining (midiSourceNodes.getUnchecked(0),
  28643. AudioProcessorGraph::midiChannelIndex);
  28644. if (srcIndex >= 0)
  28645. renderingOps.add (new CopyMidiBufferOp (srcIndex, midiBufferToUse));
  28646. else
  28647. renderingOps.add (new ClearMidiBufferOp (midiBufferToUse));
  28648. reusableInputIndex = 0;
  28649. }
  28650. for (int j = 0; j < midiSourceNodes.size(); ++j)
  28651. {
  28652. if (j != reusableInputIndex)
  28653. {
  28654. const int srcIndex = getBufferContaining (midiSourceNodes.getUnchecked(j),
  28655. AudioProcessorGraph::midiChannelIndex);
  28656. if (srcIndex >= 0)
  28657. renderingOps.add (new AddMidiBufferOp (srcIndex, midiBufferToUse));
  28658. }
  28659. }
  28660. }
  28661. if (node->processor->producesMidi())
  28662. markBufferAsContaining (midiBufferToUse, node->id,
  28663. AudioProcessorGraph::midiChannelIndex);
  28664. renderingOps.add (new ProcessBufferOp (node, audioChannelsToUse,
  28665. totalChans, midiBufferToUse));
  28666. }
  28667. int getFreeBuffer (const bool forMidi)
  28668. {
  28669. if (forMidi)
  28670. {
  28671. for (int i = 1; i < midiNodeIds.size(); ++i)
  28672. if (midiNodeIds.getUnchecked(i) < 0)
  28673. return i;
  28674. midiNodeIds.add (-1);
  28675. return midiNodeIds.size() - 1;
  28676. }
  28677. else
  28678. {
  28679. for (int i = 1; i < nodeIds.size(); ++i)
  28680. if (nodeIds.getUnchecked(i) < 0)
  28681. return i;
  28682. nodeIds.add (-1);
  28683. channels.add (0);
  28684. return nodeIds.size() - 1;
  28685. }
  28686. }
  28687. int getReadOnlyEmptyBuffer() const
  28688. {
  28689. return 0;
  28690. }
  28691. int getBufferContaining (const int nodeId, const int outputChannel) const
  28692. {
  28693. if (outputChannel == AudioProcessorGraph::midiChannelIndex)
  28694. {
  28695. for (int i = midiNodeIds.size(); --i >= 0;)
  28696. if (midiNodeIds.getUnchecked(i) == nodeId)
  28697. return i;
  28698. }
  28699. else
  28700. {
  28701. for (int i = nodeIds.size(); --i >= 0;)
  28702. if (nodeIds.getUnchecked(i) == nodeId
  28703. && channels.getUnchecked(i) == outputChannel)
  28704. return i;
  28705. }
  28706. return -1;
  28707. }
  28708. void markAnyUnusedBuffersAsFree (const int stepIndex)
  28709. {
  28710. int i;
  28711. for (i = 0; i < nodeIds.size(); ++i)
  28712. {
  28713. if (nodeIds.getUnchecked(i) >= 0
  28714. && ! isBufferNeededLater (stepIndex, -1,
  28715. nodeIds.getUnchecked(i),
  28716. channels.getUnchecked(i)))
  28717. {
  28718. nodeIds.set (i, -1);
  28719. }
  28720. }
  28721. for (i = 0; i < midiNodeIds.size(); ++i)
  28722. {
  28723. if (midiNodeIds.getUnchecked(i) >= 0
  28724. && ! isBufferNeededLater (stepIndex, -1,
  28725. midiNodeIds.getUnchecked(i),
  28726. AudioProcessorGraph::midiChannelIndex))
  28727. {
  28728. midiNodeIds.set (i, -1);
  28729. }
  28730. }
  28731. }
  28732. bool isBufferNeededLater (int stepIndexToSearchFrom,
  28733. int inputChannelOfIndexToIgnore,
  28734. const int nodeId,
  28735. const int outputChanIndex) const
  28736. {
  28737. while (stepIndexToSearchFrom < orderedNodes.size())
  28738. {
  28739. const AudioProcessorGraph::Node* const node = (const AudioProcessorGraph::Node*) orderedNodes.getUnchecked (stepIndexToSearchFrom);
  28740. if (outputChanIndex == AudioProcessorGraph::midiChannelIndex)
  28741. {
  28742. if (inputChannelOfIndexToIgnore != AudioProcessorGraph::midiChannelIndex
  28743. && graph.getConnectionBetween (nodeId, AudioProcessorGraph::midiChannelIndex,
  28744. node->id, AudioProcessorGraph::midiChannelIndex) != 0)
  28745. return true;
  28746. }
  28747. else
  28748. {
  28749. for (int i = 0; i < node->processor->getNumInputChannels(); ++i)
  28750. if (i != inputChannelOfIndexToIgnore
  28751. && graph.getConnectionBetween (nodeId, outputChanIndex,
  28752. node->id, i) != 0)
  28753. return true;
  28754. }
  28755. inputChannelOfIndexToIgnore = -1;
  28756. ++stepIndexToSearchFrom;
  28757. }
  28758. return false;
  28759. }
  28760. void markBufferAsContaining (int bufferNum, int nodeId, int outputIndex)
  28761. {
  28762. if (outputIndex == AudioProcessorGraph::midiChannelIndex)
  28763. {
  28764. jassert (bufferNum > 0 && bufferNum < midiNodeIds.size());
  28765. midiNodeIds.set (bufferNum, nodeId);
  28766. }
  28767. else
  28768. {
  28769. jassert (bufferNum >= 0 && bufferNum < nodeIds.size());
  28770. nodeIds.set (bufferNum, nodeId);
  28771. channels.set (bufferNum, outputIndex);
  28772. }
  28773. }
  28774. RenderingOpSequenceCalculator (const RenderingOpSequenceCalculator&);
  28775. RenderingOpSequenceCalculator& operator= (const RenderingOpSequenceCalculator&);
  28776. };
  28777. }
  28778. void AudioProcessorGraph::clearRenderingSequence()
  28779. {
  28780. const ScopedLock sl (renderLock);
  28781. for (int i = renderingOps.size(); --i >= 0;)
  28782. {
  28783. GraphRenderingOps::AudioGraphRenderingOp* const r
  28784. = (GraphRenderingOps::AudioGraphRenderingOp*) renderingOps.getUnchecked(i);
  28785. renderingOps.remove (i);
  28786. delete r;
  28787. }
  28788. }
  28789. bool AudioProcessorGraph::isAnInputTo (const uint32 possibleInputId,
  28790. const uint32 possibleDestinationId,
  28791. const int recursionCheck) const
  28792. {
  28793. if (recursionCheck > 0)
  28794. {
  28795. for (int i = connections.size(); --i >= 0;)
  28796. {
  28797. const AudioProcessorGraph::Connection* const c = connections.getUnchecked (i);
  28798. if (c->destNodeId == possibleDestinationId
  28799. && (c->sourceNodeId == possibleInputId
  28800. || isAnInputTo (possibleInputId, c->sourceNodeId, recursionCheck - 1)))
  28801. return true;
  28802. }
  28803. }
  28804. return false;
  28805. }
  28806. void AudioProcessorGraph::buildRenderingSequence()
  28807. {
  28808. VoidArray newRenderingOps;
  28809. int numRenderingBuffersNeeded = 2;
  28810. int numMidiBuffersNeeded = 1;
  28811. {
  28812. MessageManagerLock mml;
  28813. VoidArray orderedNodes;
  28814. int i;
  28815. for (i = 0; i < nodes.size(); ++i)
  28816. {
  28817. Node* const node = nodes.getUnchecked(i);
  28818. node->prepare (getSampleRate(), getBlockSize(), this);
  28819. int j = 0;
  28820. for (; j < orderedNodes.size(); ++j)
  28821. if (isAnInputTo (node->id,
  28822. ((Node*) orderedNodes.getUnchecked (j))->id,
  28823. nodes.size() + 1))
  28824. break;
  28825. orderedNodes.insert (j, node);
  28826. }
  28827. GraphRenderingOps::RenderingOpSequenceCalculator calculator (*this, orderedNodes, newRenderingOps);
  28828. numRenderingBuffersNeeded = calculator.getNumBuffersNeeded();
  28829. numMidiBuffersNeeded = calculator.getNumMidiBuffersNeeded();
  28830. }
  28831. VoidArray oldRenderingOps (renderingOps);
  28832. {
  28833. // swap over to the new rendering sequence..
  28834. const ScopedLock sl (renderLock);
  28835. renderingBuffers.setSize (numRenderingBuffersNeeded, getBlockSize());
  28836. renderingBuffers.clear();
  28837. for (int i = midiBuffers.size(); --i >= 0;)
  28838. midiBuffers.getUnchecked(i)->clear();
  28839. while (midiBuffers.size() < numMidiBuffersNeeded)
  28840. midiBuffers.add (new MidiBuffer());
  28841. renderingOps = newRenderingOps;
  28842. }
  28843. for (int i = oldRenderingOps.size(); --i >= 0;)
  28844. delete (GraphRenderingOps::AudioGraphRenderingOp*) oldRenderingOps.getUnchecked(i);
  28845. }
  28846. void AudioProcessorGraph::handleAsyncUpdate()
  28847. {
  28848. buildRenderingSequence();
  28849. }
  28850. void AudioProcessorGraph::prepareToPlay (double /*sampleRate*/, int estimatedSamplesPerBlock)
  28851. {
  28852. currentAudioInputBuffer = 0;
  28853. currentAudioOutputBuffer.setSize (jmax (1, getNumOutputChannels()), estimatedSamplesPerBlock);
  28854. currentMidiInputBuffer = 0;
  28855. currentMidiOutputBuffer.clear();
  28856. clearRenderingSequence();
  28857. buildRenderingSequence();
  28858. }
  28859. void AudioProcessorGraph::releaseResources()
  28860. {
  28861. for (int i = 0; i < nodes.size(); ++i)
  28862. nodes.getUnchecked(i)->unprepare();
  28863. renderingBuffers.setSize (1, 1);
  28864. midiBuffers.clear();
  28865. currentAudioInputBuffer = 0;
  28866. currentAudioOutputBuffer.setSize (1, 1);
  28867. currentMidiInputBuffer = 0;
  28868. currentMidiOutputBuffer.clear();
  28869. }
  28870. void AudioProcessorGraph::processBlock (AudioSampleBuffer& buffer, MidiBuffer& midiMessages)
  28871. {
  28872. const int numSamples = buffer.getNumSamples();
  28873. const ScopedLock sl (renderLock);
  28874. currentAudioInputBuffer = &buffer;
  28875. currentAudioOutputBuffer.setSize (jmax (1, buffer.getNumChannels()), numSamples);
  28876. currentAudioOutputBuffer.clear();
  28877. currentMidiInputBuffer = &midiMessages;
  28878. currentMidiOutputBuffer.clear();
  28879. int i;
  28880. for (i = 0; i < renderingOps.size(); ++i)
  28881. {
  28882. GraphRenderingOps::AudioGraphRenderingOp* const op
  28883. = (GraphRenderingOps::AudioGraphRenderingOp*) renderingOps.getUnchecked(i);
  28884. op->perform (renderingBuffers, midiBuffers, numSamples);
  28885. }
  28886. for (i = 0; i < buffer.getNumChannels(); ++i)
  28887. buffer.copyFrom (i, 0, currentAudioOutputBuffer, i, 0, numSamples);
  28888. midiMessages.clear();
  28889. midiMessages.addEvents (currentMidiOutputBuffer, 0, buffer.getNumSamples(), 0);
  28890. }
  28891. const String AudioProcessorGraph::getInputChannelName (const int channelIndex) const
  28892. {
  28893. return "Input " + String (channelIndex + 1);
  28894. }
  28895. const String AudioProcessorGraph::getOutputChannelName (const int channelIndex) const
  28896. {
  28897. return "Output " + String (channelIndex + 1);
  28898. }
  28899. bool AudioProcessorGraph::isInputChannelStereoPair (int /*index*/) const
  28900. {
  28901. return true;
  28902. }
  28903. bool AudioProcessorGraph::isOutputChannelStereoPair (int /*index*/) const
  28904. {
  28905. return true;
  28906. }
  28907. bool AudioProcessorGraph::acceptsMidi() const
  28908. {
  28909. return true;
  28910. }
  28911. bool AudioProcessorGraph::producesMidi() const
  28912. {
  28913. return true;
  28914. }
  28915. void AudioProcessorGraph::getStateInformation (JUCE_NAMESPACE::MemoryBlock& /*destData*/)
  28916. {
  28917. }
  28918. void AudioProcessorGraph::setStateInformation (const void* /*data*/, int /*sizeInBytes*/)
  28919. {
  28920. }
  28921. AudioProcessorGraph::AudioGraphIOProcessor::AudioGraphIOProcessor (const IODeviceType type_)
  28922. : type (type_),
  28923. graph (0)
  28924. {
  28925. }
  28926. AudioProcessorGraph::AudioGraphIOProcessor::~AudioGraphIOProcessor()
  28927. {
  28928. }
  28929. const String AudioProcessorGraph::AudioGraphIOProcessor::getName() const
  28930. {
  28931. switch (type)
  28932. {
  28933. case audioOutputNode:
  28934. return "Audio Output";
  28935. case audioInputNode:
  28936. return "Audio Input";
  28937. case midiOutputNode:
  28938. return "Midi Output";
  28939. case midiInputNode:
  28940. return "Midi Input";
  28941. default:
  28942. break;
  28943. }
  28944. return String::empty;
  28945. }
  28946. void AudioProcessorGraph::AudioGraphIOProcessor::fillInPluginDescription (PluginDescription& d) const
  28947. {
  28948. d.name = getName();
  28949. d.uid = d.name.hashCode();
  28950. d.category = "I/O devices";
  28951. d.pluginFormatName = "Internal";
  28952. d.manufacturerName = "Raw Material Software";
  28953. d.version = "1.0";
  28954. d.isInstrument = false;
  28955. d.numInputChannels = getNumInputChannels();
  28956. if (type == audioOutputNode && graph != 0)
  28957. d.numInputChannels = graph->getNumInputChannels();
  28958. d.numOutputChannels = getNumOutputChannels();
  28959. if (type == audioInputNode && graph != 0)
  28960. d.numOutputChannels = graph->getNumOutputChannels();
  28961. }
  28962. void AudioProcessorGraph::AudioGraphIOProcessor::prepareToPlay (double, int)
  28963. {
  28964. jassert (graph != 0);
  28965. }
  28966. void AudioProcessorGraph::AudioGraphIOProcessor::releaseResources()
  28967. {
  28968. }
  28969. void AudioProcessorGraph::AudioGraphIOProcessor::processBlock (AudioSampleBuffer& buffer,
  28970. MidiBuffer& midiMessages)
  28971. {
  28972. jassert (graph != 0);
  28973. switch (type)
  28974. {
  28975. case audioOutputNode:
  28976. {
  28977. for (int i = jmin (graph->currentAudioOutputBuffer.getNumChannels(),
  28978. buffer.getNumChannels()); --i >= 0;)
  28979. {
  28980. graph->currentAudioOutputBuffer.addFrom (i, 0, buffer, i, 0, buffer.getNumSamples());
  28981. }
  28982. break;
  28983. }
  28984. case audioInputNode:
  28985. {
  28986. for (int i = jmin (graph->currentAudioInputBuffer->getNumChannels(),
  28987. buffer.getNumChannels()); --i >= 0;)
  28988. {
  28989. buffer.copyFrom (i, 0, *graph->currentAudioInputBuffer, i, 0, buffer.getNumSamples());
  28990. }
  28991. break;
  28992. }
  28993. case midiOutputNode:
  28994. graph->currentMidiOutputBuffer.addEvents (midiMessages, 0, buffer.getNumSamples(), 0);
  28995. break;
  28996. case midiInputNode:
  28997. midiMessages.addEvents (*graph->currentMidiInputBuffer, 0, buffer.getNumSamples(), 0);
  28998. break;
  28999. default:
  29000. break;
  29001. }
  29002. }
  29003. bool AudioProcessorGraph::AudioGraphIOProcessor::acceptsMidi() const
  29004. {
  29005. return type == midiOutputNode;
  29006. }
  29007. bool AudioProcessorGraph::AudioGraphIOProcessor::producesMidi() const
  29008. {
  29009. return type == midiInputNode;
  29010. }
  29011. const String AudioProcessorGraph::AudioGraphIOProcessor::getInputChannelName (const int channelIndex) const
  29012. {
  29013. switch (type)
  29014. {
  29015. case audioOutputNode:
  29016. return "Output " + String (channelIndex + 1);
  29017. case midiOutputNode:
  29018. return "Midi Output";
  29019. default:
  29020. break;
  29021. }
  29022. return String::empty;
  29023. }
  29024. const String AudioProcessorGraph::AudioGraphIOProcessor::getOutputChannelName (const int channelIndex) const
  29025. {
  29026. switch (type)
  29027. {
  29028. case audioInputNode:
  29029. return "Input " + String (channelIndex + 1);
  29030. case midiInputNode:
  29031. return "Midi Input";
  29032. default:
  29033. break;
  29034. }
  29035. return String::empty;
  29036. }
  29037. bool AudioProcessorGraph::AudioGraphIOProcessor::isInputChannelStereoPair (int /*index*/) const
  29038. {
  29039. return type == audioInputNode || type == audioOutputNode;
  29040. }
  29041. bool AudioProcessorGraph::AudioGraphIOProcessor::isOutputChannelStereoPair (int index) const
  29042. {
  29043. return isInputChannelStereoPair (index);
  29044. }
  29045. bool AudioProcessorGraph::AudioGraphIOProcessor::isInput() const
  29046. {
  29047. return type == audioInputNode || type == midiInputNode;
  29048. }
  29049. bool AudioProcessorGraph::AudioGraphIOProcessor::isOutput() const
  29050. {
  29051. return type == audioOutputNode || type == midiOutputNode;
  29052. }
  29053. AudioProcessorEditor* AudioProcessorGraph::AudioGraphIOProcessor::createEditor()
  29054. {
  29055. return 0;
  29056. }
  29057. int AudioProcessorGraph::AudioGraphIOProcessor::getNumParameters() { return 0; }
  29058. const String AudioProcessorGraph::AudioGraphIOProcessor::getParameterName (int) { return String::empty; }
  29059. float AudioProcessorGraph::AudioGraphIOProcessor::getParameter (int) { return 0.0f; }
  29060. const String AudioProcessorGraph::AudioGraphIOProcessor::getParameterText (int) { return String::empty; }
  29061. void AudioProcessorGraph::AudioGraphIOProcessor::setParameter (int, float) { }
  29062. int AudioProcessorGraph::AudioGraphIOProcessor::getNumPrograms() { return 0; }
  29063. int AudioProcessorGraph::AudioGraphIOProcessor::getCurrentProgram() { return 0; }
  29064. void AudioProcessorGraph::AudioGraphIOProcessor::setCurrentProgram (int) { }
  29065. const String AudioProcessorGraph::AudioGraphIOProcessor::getProgramName (int) { return String::empty; }
  29066. void AudioProcessorGraph::AudioGraphIOProcessor::changeProgramName (int, const String&) { }
  29067. void AudioProcessorGraph::AudioGraphIOProcessor::getStateInformation (JUCE_NAMESPACE::MemoryBlock&)
  29068. {
  29069. }
  29070. void AudioProcessorGraph::AudioGraphIOProcessor::setStateInformation (const void*, int)
  29071. {
  29072. }
  29073. void AudioProcessorGraph::AudioGraphIOProcessor::setParentGraph (AudioProcessorGraph* const newGraph)
  29074. {
  29075. graph = newGraph;
  29076. if (graph != 0)
  29077. {
  29078. setPlayConfigDetails (type == audioOutputNode ? graph->getNumOutputChannels() : 0,
  29079. type == audioInputNode ? graph->getNumInputChannels() : 0,
  29080. getSampleRate(),
  29081. getBlockSize());
  29082. updateHostDisplay();
  29083. }
  29084. }
  29085. END_JUCE_NAMESPACE
  29086. /*** End of inlined file: juce_AudioProcessorGraph.cpp ***/
  29087. /*** Start of inlined file: juce_AudioProcessorPlayer.cpp ***/
  29088. BEGIN_JUCE_NAMESPACE
  29089. AudioProcessorPlayer::AudioProcessorPlayer()
  29090. : processor (0),
  29091. sampleRate (0),
  29092. blockSize (0),
  29093. isPrepared (false),
  29094. numInputChans (0),
  29095. numOutputChans (0),
  29096. tempBuffer (1, 1)
  29097. {
  29098. }
  29099. AudioProcessorPlayer::~AudioProcessorPlayer()
  29100. {
  29101. setProcessor (0);
  29102. }
  29103. void AudioProcessorPlayer::setProcessor (AudioProcessor* const processorToPlay)
  29104. {
  29105. if (processor != processorToPlay)
  29106. {
  29107. if (processorToPlay != 0 && sampleRate > 0 && blockSize > 0)
  29108. {
  29109. processorToPlay->setPlayConfigDetails (numInputChans, numOutputChans,
  29110. sampleRate, blockSize);
  29111. processorToPlay->prepareToPlay (sampleRate, blockSize);
  29112. }
  29113. AudioProcessor* oldOne;
  29114. {
  29115. const ScopedLock sl (lock);
  29116. oldOne = isPrepared ? processor : 0;
  29117. processor = processorToPlay;
  29118. isPrepared = true;
  29119. }
  29120. if (oldOne != 0)
  29121. oldOne->releaseResources();
  29122. }
  29123. }
  29124. void AudioProcessorPlayer::audioDeviceIOCallback (const float** inputChannelData,
  29125. int numInputChannels,
  29126. float** outputChannelData,
  29127. int numOutputChannels,
  29128. int numSamples)
  29129. {
  29130. // these should have been prepared by audioDeviceAboutToStart()...
  29131. jassert (sampleRate > 0 && blockSize > 0);
  29132. incomingMidi.clear();
  29133. messageCollector.removeNextBlockOfMessages (incomingMidi, numSamples);
  29134. int i, totalNumChans = 0;
  29135. if (numInputChannels > numOutputChannels)
  29136. {
  29137. // if there aren't enough output channels for the number of
  29138. // inputs, we need to create some temporary extra ones (can't
  29139. // use the input data in case it gets written to)
  29140. tempBuffer.setSize (numInputChannels - numOutputChannels, numSamples,
  29141. false, false, true);
  29142. for (i = 0; i < numOutputChannels; ++i)
  29143. {
  29144. channels[totalNumChans] = outputChannelData[i];
  29145. memcpy (channels[totalNumChans], inputChannelData[i], sizeof (float) * numSamples);
  29146. ++totalNumChans;
  29147. }
  29148. for (i = numOutputChannels; i < numInputChannels; ++i)
  29149. {
  29150. channels[totalNumChans] = tempBuffer.getSampleData (i - numOutputChannels, 0);
  29151. memcpy (channels[totalNumChans], inputChannelData[i], sizeof (float) * numSamples);
  29152. ++totalNumChans;
  29153. }
  29154. }
  29155. else
  29156. {
  29157. for (i = 0; i < numInputChannels; ++i)
  29158. {
  29159. channels[totalNumChans] = outputChannelData[i];
  29160. memcpy (channels[totalNumChans], inputChannelData[i], sizeof (float) * numSamples);
  29161. ++totalNumChans;
  29162. }
  29163. for (i = numInputChannels; i < numOutputChannels; ++i)
  29164. {
  29165. channels[totalNumChans] = outputChannelData[i];
  29166. zeromem (channels[totalNumChans], sizeof (float) * numSamples);
  29167. ++totalNumChans;
  29168. }
  29169. }
  29170. AudioSampleBuffer buffer (channels, totalNumChans, numSamples);
  29171. const ScopedLock sl (lock);
  29172. if (processor != 0)
  29173. processor->processBlock (buffer, incomingMidi);
  29174. }
  29175. void AudioProcessorPlayer::audioDeviceAboutToStart (AudioIODevice* device)
  29176. {
  29177. const ScopedLock sl (lock);
  29178. sampleRate = device->getCurrentSampleRate();
  29179. blockSize = device->getCurrentBufferSizeSamples();
  29180. numInputChans = device->getActiveInputChannels().countNumberOfSetBits();
  29181. numOutputChans = device->getActiveOutputChannels().countNumberOfSetBits();
  29182. messageCollector.reset (sampleRate);
  29183. zeromem (channels, sizeof (channels));
  29184. if (processor != 0)
  29185. {
  29186. if (isPrepared)
  29187. processor->releaseResources();
  29188. AudioProcessor* const oldProcessor = processor;
  29189. setProcessor (0);
  29190. setProcessor (oldProcessor);
  29191. }
  29192. }
  29193. void AudioProcessorPlayer::audioDeviceStopped()
  29194. {
  29195. const ScopedLock sl (lock);
  29196. if (processor != 0 && isPrepared)
  29197. processor->releaseResources();
  29198. sampleRate = 0.0;
  29199. blockSize = 0;
  29200. isPrepared = false;
  29201. tempBuffer.setSize (1, 1);
  29202. }
  29203. void AudioProcessorPlayer::handleIncomingMidiMessage (MidiInput*, const MidiMessage& message)
  29204. {
  29205. messageCollector.addMessageToQueue (message);
  29206. }
  29207. END_JUCE_NAMESPACE
  29208. /*** End of inlined file: juce_AudioProcessorPlayer.cpp ***/
  29209. /*** Start of inlined file: juce_GenericAudioProcessorEditor.cpp ***/
  29210. BEGIN_JUCE_NAMESPACE
  29211. class ProcessorParameterPropertyComp : public PropertyComponent,
  29212. public AudioProcessorListener,
  29213. public AsyncUpdater
  29214. {
  29215. public:
  29216. ProcessorParameterPropertyComp (const String& name,
  29217. AudioProcessor* const owner_,
  29218. const int index_)
  29219. : PropertyComponent (name),
  29220. owner (owner_),
  29221. index (index_)
  29222. {
  29223. addAndMakeVisible (slider = new ParamSlider (owner_, index_));
  29224. owner_->addListener (this);
  29225. }
  29226. ~ProcessorParameterPropertyComp()
  29227. {
  29228. owner->removeListener (this);
  29229. deleteAllChildren();
  29230. }
  29231. void refresh()
  29232. {
  29233. slider->setValue (owner->getParameter (index), false);
  29234. }
  29235. void audioProcessorChanged (AudioProcessor*) {}
  29236. void audioProcessorParameterChanged (AudioProcessor*, int parameterIndex, float)
  29237. {
  29238. if (parameterIndex == index)
  29239. triggerAsyncUpdate();
  29240. }
  29241. void handleAsyncUpdate()
  29242. {
  29243. refresh();
  29244. }
  29245. juce_UseDebuggingNewOperator
  29246. private:
  29247. AudioProcessor* const owner;
  29248. const int index;
  29249. Slider* slider;
  29250. class ParamSlider : public Slider
  29251. {
  29252. public:
  29253. ParamSlider (AudioProcessor* const owner_, const int index_)
  29254. : Slider (String::empty),
  29255. owner (owner_),
  29256. index (index_)
  29257. {
  29258. setRange (0.0, 1.0, 0.0);
  29259. setSliderStyle (Slider::LinearBar);
  29260. setTextBoxIsEditable (false);
  29261. setScrollWheelEnabled (false);
  29262. }
  29263. ~ParamSlider()
  29264. {
  29265. }
  29266. void valueChanged()
  29267. {
  29268. const float newVal = (float) getValue();
  29269. if (owner->getParameter (index) != newVal)
  29270. owner->setParameter (index, newVal);
  29271. }
  29272. const String getTextFromValue (double /*value*/)
  29273. {
  29274. return owner->getParameterText (index);
  29275. }
  29276. juce_UseDebuggingNewOperator
  29277. private:
  29278. AudioProcessor* const owner;
  29279. const int index;
  29280. ParamSlider (const ParamSlider&);
  29281. ParamSlider& operator= (const ParamSlider&);
  29282. };
  29283. ProcessorParameterPropertyComp (const ProcessorParameterPropertyComp&);
  29284. ProcessorParameterPropertyComp& operator= (const ProcessorParameterPropertyComp&);
  29285. };
  29286. GenericAudioProcessorEditor::GenericAudioProcessorEditor (AudioProcessor* const owner_)
  29287. : AudioProcessorEditor (owner_)
  29288. {
  29289. setOpaque (true);
  29290. addAndMakeVisible (panel = new PropertyPanel());
  29291. Array <PropertyComponent*> params;
  29292. const int numParams = owner_->getNumParameters();
  29293. int totalHeight = 0;
  29294. for (int i = 0; i < numParams; ++i)
  29295. {
  29296. String name (owner_->getParameterName (i));
  29297. if (name.trim().isEmpty())
  29298. name = "Unnamed";
  29299. ProcessorParameterPropertyComp* const pc = new ProcessorParameterPropertyComp (name, owner_, i);
  29300. params.add (pc);
  29301. totalHeight += pc->getPreferredHeight();
  29302. }
  29303. panel->addProperties (params);
  29304. setSize (400, jlimit (25, 400, totalHeight));
  29305. }
  29306. GenericAudioProcessorEditor::~GenericAudioProcessorEditor()
  29307. {
  29308. deleteAllChildren();
  29309. }
  29310. void GenericAudioProcessorEditor::paint (Graphics& g)
  29311. {
  29312. g.fillAll (Colours::white);
  29313. }
  29314. void GenericAudioProcessorEditor::resized()
  29315. {
  29316. panel->setSize (getWidth(), getHeight());
  29317. }
  29318. END_JUCE_NAMESPACE
  29319. /*** End of inlined file: juce_GenericAudioProcessorEditor.cpp ***/
  29320. /*** Start of inlined file: juce_Sampler.cpp ***/
  29321. BEGIN_JUCE_NAMESPACE
  29322. SamplerSound::SamplerSound (const String& name_,
  29323. AudioFormatReader& source,
  29324. const BigInteger& midiNotes_,
  29325. const int midiNoteForNormalPitch,
  29326. const double attackTimeSecs,
  29327. const double releaseTimeSecs,
  29328. const double maxSampleLengthSeconds)
  29329. : name (name_),
  29330. midiNotes (midiNotes_),
  29331. midiRootNote (midiNoteForNormalPitch)
  29332. {
  29333. sourceSampleRate = source.sampleRate;
  29334. if (sourceSampleRate <= 0 || source.lengthInSamples <= 0)
  29335. {
  29336. length = 0;
  29337. attackSamples = 0;
  29338. releaseSamples = 0;
  29339. }
  29340. else
  29341. {
  29342. length = jmin ((int) source.lengthInSamples,
  29343. (int) (maxSampleLengthSeconds * sourceSampleRate));
  29344. data = new AudioSampleBuffer (jmin (2, (int) source.numChannels), length + 4);
  29345. data->readFromAudioReader (&source, 0, length + 4, 0, true, true);
  29346. attackSamples = roundToInt (attackTimeSecs * sourceSampleRate);
  29347. releaseSamples = roundToInt (releaseTimeSecs * sourceSampleRate);
  29348. }
  29349. }
  29350. SamplerSound::~SamplerSound()
  29351. {
  29352. }
  29353. bool SamplerSound::appliesToNote (const int midiNoteNumber)
  29354. {
  29355. return midiNotes [midiNoteNumber];
  29356. }
  29357. bool SamplerSound::appliesToChannel (const int /*midiChannel*/)
  29358. {
  29359. return true;
  29360. }
  29361. SamplerVoice::SamplerVoice()
  29362. : pitchRatio (0.0),
  29363. sourceSamplePosition (0.0),
  29364. lgain (0.0f),
  29365. rgain (0.0f),
  29366. isInAttack (false),
  29367. isInRelease (false)
  29368. {
  29369. }
  29370. SamplerVoice::~SamplerVoice()
  29371. {
  29372. }
  29373. bool SamplerVoice::canPlaySound (SynthesiserSound* sound)
  29374. {
  29375. return dynamic_cast <const SamplerSound*> (sound) != 0;
  29376. }
  29377. void SamplerVoice::startNote (const int midiNoteNumber,
  29378. const float velocity,
  29379. SynthesiserSound* s,
  29380. const int /*currentPitchWheelPosition*/)
  29381. {
  29382. const SamplerSound* const sound = dynamic_cast <const SamplerSound*> (s);
  29383. jassert (sound != 0); // this object can only play SamplerSounds!
  29384. if (sound != 0)
  29385. {
  29386. const double targetFreq = MidiMessage::getMidiNoteInHertz (midiNoteNumber);
  29387. const double naturalFreq = MidiMessage::getMidiNoteInHertz (sound->midiRootNote);
  29388. pitchRatio = (targetFreq * sound->sourceSampleRate) / (naturalFreq * getSampleRate());
  29389. sourceSamplePosition = 0.0;
  29390. lgain = velocity;
  29391. rgain = velocity;
  29392. isInAttack = (sound->attackSamples > 0);
  29393. isInRelease = false;
  29394. if (isInAttack)
  29395. {
  29396. attackReleaseLevel = 0.0f;
  29397. attackDelta = (float) (pitchRatio / sound->attackSamples);
  29398. }
  29399. else
  29400. {
  29401. attackReleaseLevel = 1.0f;
  29402. attackDelta = 0.0f;
  29403. }
  29404. if (sound->releaseSamples > 0)
  29405. {
  29406. releaseDelta = (float) (-pitchRatio / sound->releaseSamples);
  29407. }
  29408. else
  29409. {
  29410. releaseDelta = 0.0f;
  29411. }
  29412. }
  29413. }
  29414. void SamplerVoice::stopNote (const bool allowTailOff)
  29415. {
  29416. if (allowTailOff)
  29417. {
  29418. isInAttack = false;
  29419. isInRelease = true;
  29420. }
  29421. else
  29422. {
  29423. clearCurrentNote();
  29424. }
  29425. }
  29426. void SamplerVoice::pitchWheelMoved (const int /*newValue*/)
  29427. {
  29428. }
  29429. void SamplerVoice::controllerMoved (const int /*controllerNumber*/,
  29430. const int /*newValue*/)
  29431. {
  29432. }
  29433. void SamplerVoice::renderNextBlock (AudioSampleBuffer& outputBuffer, int startSample, int numSamples)
  29434. {
  29435. const SamplerSound* const playingSound = static_cast <SamplerSound*> (getCurrentlyPlayingSound().getObject());
  29436. if (playingSound != 0)
  29437. {
  29438. const float* const inL = playingSound->data->getSampleData (0, 0);
  29439. const float* const inR = playingSound->data->getNumChannels() > 1
  29440. ? playingSound->data->getSampleData (1, 0) : 0;
  29441. float* outL = outputBuffer.getSampleData (0, startSample);
  29442. float* outR = outputBuffer.getNumChannels() > 1 ? outputBuffer.getSampleData (1, startSample) : 0;
  29443. while (--numSamples >= 0)
  29444. {
  29445. const int pos = (int) sourceSamplePosition;
  29446. const float alpha = (float) (sourceSamplePosition - pos);
  29447. const float invAlpha = 1.0f - alpha;
  29448. // just using a very simple linear interpolation here..
  29449. float l = (inL [pos] * invAlpha + inL [pos + 1] * alpha);
  29450. float r = (inR != 0) ? (inR [pos] * invAlpha + inR [pos + 1] * alpha)
  29451. : l;
  29452. l *= lgain;
  29453. r *= rgain;
  29454. if (isInAttack)
  29455. {
  29456. l *= attackReleaseLevel;
  29457. r *= attackReleaseLevel;
  29458. attackReleaseLevel += attackDelta;
  29459. if (attackReleaseLevel >= 1.0f)
  29460. {
  29461. attackReleaseLevel = 1.0f;
  29462. isInAttack = false;
  29463. }
  29464. }
  29465. else if (isInRelease)
  29466. {
  29467. l *= attackReleaseLevel;
  29468. r *= attackReleaseLevel;
  29469. attackReleaseLevel += releaseDelta;
  29470. if (attackReleaseLevel <= 0.0f)
  29471. {
  29472. stopNote (false);
  29473. break;
  29474. }
  29475. }
  29476. if (outR != 0)
  29477. {
  29478. *outL++ += l;
  29479. *outR++ += r;
  29480. }
  29481. else
  29482. {
  29483. *outL++ += (l + r) * 0.5f;
  29484. }
  29485. sourceSamplePosition += pitchRatio;
  29486. if (sourceSamplePosition > playingSound->length)
  29487. {
  29488. stopNote (false);
  29489. break;
  29490. }
  29491. }
  29492. }
  29493. }
  29494. END_JUCE_NAMESPACE
  29495. /*** End of inlined file: juce_Sampler.cpp ***/
  29496. /*** Start of inlined file: juce_Synthesiser.cpp ***/
  29497. BEGIN_JUCE_NAMESPACE
  29498. SynthesiserSound::SynthesiserSound()
  29499. {
  29500. }
  29501. SynthesiserSound::~SynthesiserSound()
  29502. {
  29503. }
  29504. SynthesiserVoice::SynthesiserVoice()
  29505. : currentSampleRate (44100.0),
  29506. currentlyPlayingNote (-1),
  29507. noteOnTime (0),
  29508. currentlyPlayingSound (0)
  29509. {
  29510. }
  29511. SynthesiserVoice::~SynthesiserVoice()
  29512. {
  29513. }
  29514. bool SynthesiserVoice::isPlayingChannel (const int midiChannel) const
  29515. {
  29516. return currentlyPlayingSound != 0
  29517. && currentlyPlayingSound->appliesToChannel (midiChannel);
  29518. }
  29519. void SynthesiserVoice::setCurrentPlaybackSampleRate (const double newRate)
  29520. {
  29521. currentSampleRate = newRate;
  29522. }
  29523. void SynthesiserVoice::clearCurrentNote()
  29524. {
  29525. currentlyPlayingNote = -1;
  29526. currentlyPlayingSound = 0;
  29527. }
  29528. Synthesiser::Synthesiser()
  29529. : sampleRate (0),
  29530. lastNoteOnCounter (0),
  29531. shouldStealNotes (true)
  29532. {
  29533. for (int i = 0; i < numElementsInArray (lastPitchWheelValues); ++i)
  29534. lastPitchWheelValues[i] = 0x2000;
  29535. }
  29536. Synthesiser::~Synthesiser()
  29537. {
  29538. }
  29539. SynthesiserVoice* Synthesiser::getVoice (const int index) const
  29540. {
  29541. const ScopedLock sl (lock);
  29542. return voices [index];
  29543. }
  29544. void Synthesiser::clearVoices()
  29545. {
  29546. const ScopedLock sl (lock);
  29547. voices.clear();
  29548. }
  29549. void Synthesiser::addVoice (SynthesiserVoice* const newVoice)
  29550. {
  29551. const ScopedLock sl (lock);
  29552. voices.add (newVoice);
  29553. }
  29554. void Synthesiser::removeVoice (const int index)
  29555. {
  29556. const ScopedLock sl (lock);
  29557. voices.remove (index);
  29558. }
  29559. void Synthesiser::clearSounds()
  29560. {
  29561. const ScopedLock sl (lock);
  29562. sounds.clear();
  29563. }
  29564. void Synthesiser::addSound (const SynthesiserSound::Ptr& newSound)
  29565. {
  29566. const ScopedLock sl (lock);
  29567. sounds.add (newSound);
  29568. }
  29569. void Synthesiser::removeSound (const int index)
  29570. {
  29571. const ScopedLock sl (lock);
  29572. sounds.remove (index);
  29573. }
  29574. void Synthesiser::setNoteStealingEnabled (const bool shouldStealNotes_)
  29575. {
  29576. shouldStealNotes = shouldStealNotes_;
  29577. }
  29578. void Synthesiser::setCurrentPlaybackSampleRate (const double newRate)
  29579. {
  29580. if (sampleRate != newRate)
  29581. {
  29582. const ScopedLock sl (lock);
  29583. allNotesOff (0, false);
  29584. sampleRate = newRate;
  29585. for (int i = voices.size(); --i >= 0;)
  29586. voices.getUnchecked (i)->setCurrentPlaybackSampleRate (newRate);
  29587. }
  29588. }
  29589. void Synthesiser::renderNextBlock (AudioSampleBuffer& outputBuffer,
  29590. const MidiBuffer& midiData,
  29591. int startSample,
  29592. int numSamples)
  29593. {
  29594. // must set the sample rate before using this!
  29595. jassert (sampleRate != 0);
  29596. const ScopedLock sl (lock);
  29597. MidiBuffer::Iterator midiIterator (midiData);
  29598. midiIterator.setNextSamplePosition (startSample);
  29599. MidiMessage m (0xf4, 0.0);
  29600. while (numSamples > 0)
  29601. {
  29602. int midiEventPos;
  29603. const bool useEvent = midiIterator.getNextEvent (m, midiEventPos)
  29604. && midiEventPos < startSample + numSamples;
  29605. const int numThisTime = useEvent ? midiEventPos - startSample
  29606. : numSamples;
  29607. if (numThisTime > 0)
  29608. {
  29609. for (int i = voices.size(); --i >= 0;)
  29610. voices.getUnchecked (i)->renderNextBlock (outputBuffer, startSample, numThisTime);
  29611. }
  29612. if (useEvent)
  29613. {
  29614. if (m.isNoteOn())
  29615. {
  29616. const int channel = m.getChannel();
  29617. noteOn (channel,
  29618. m.getNoteNumber(),
  29619. m.getFloatVelocity());
  29620. }
  29621. else if (m.isNoteOff())
  29622. {
  29623. noteOff (m.getChannel(),
  29624. m.getNoteNumber(),
  29625. true);
  29626. }
  29627. else if (m.isAllNotesOff() || m.isAllSoundOff())
  29628. {
  29629. allNotesOff (m.getChannel(), true);
  29630. }
  29631. else if (m.isPitchWheel())
  29632. {
  29633. const int channel = m.getChannel();
  29634. const int wheelPos = m.getPitchWheelValue();
  29635. lastPitchWheelValues [channel - 1] = wheelPos;
  29636. handlePitchWheel (channel, wheelPos);
  29637. }
  29638. else if (m.isController())
  29639. {
  29640. handleController (m.getChannel(),
  29641. m.getControllerNumber(),
  29642. m.getControllerValue());
  29643. }
  29644. }
  29645. startSample += numThisTime;
  29646. numSamples -= numThisTime;
  29647. }
  29648. }
  29649. void Synthesiser::noteOn (const int midiChannel,
  29650. const int midiNoteNumber,
  29651. const float velocity)
  29652. {
  29653. const ScopedLock sl (lock);
  29654. for (int i = sounds.size(); --i >= 0;)
  29655. {
  29656. SynthesiserSound* const sound = sounds.getUnchecked(i);
  29657. if (sound->appliesToNote (midiNoteNumber)
  29658. && sound->appliesToChannel (midiChannel))
  29659. {
  29660. startVoice (findFreeVoice (sound, shouldStealNotes),
  29661. sound, midiChannel, midiNoteNumber, velocity);
  29662. }
  29663. }
  29664. }
  29665. void Synthesiser::startVoice (SynthesiserVoice* const voice,
  29666. SynthesiserSound* const sound,
  29667. const int midiChannel,
  29668. const int midiNoteNumber,
  29669. const float velocity)
  29670. {
  29671. if (voice != 0 && sound != 0)
  29672. {
  29673. if (voice->currentlyPlayingSound != 0)
  29674. voice->stopNote (false);
  29675. voice->startNote (midiNoteNumber,
  29676. velocity,
  29677. sound,
  29678. lastPitchWheelValues [midiChannel - 1]);
  29679. voice->currentlyPlayingNote = midiNoteNumber;
  29680. voice->noteOnTime = ++lastNoteOnCounter;
  29681. voice->currentlyPlayingSound = sound;
  29682. }
  29683. }
  29684. void Synthesiser::noteOff (const int midiChannel,
  29685. const int midiNoteNumber,
  29686. const bool allowTailOff)
  29687. {
  29688. const ScopedLock sl (lock);
  29689. for (int i = voices.size(); --i >= 0;)
  29690. {
  29691. SynthesiserVoice* const voice = voices.getUnchecked (i);
  29692. if (voice->getCurrentlyPlayingNote() == midiNoteNumber)
  29693. {
  29694. SynthesiserSound* const sound = voice->getCurrentlyPlayingSound();
  29695. if (sound != 0
  29696. && sound->appliesToNote (midiNoteNumber)
  29697. && sound->appliesToChannel (midiChannel))
  29698. {
  29699. voice->stopNote (allowTailOff);
  29700. // the subclass MUST call clearCurrentNote() if it's not tailing off! RTFM for stopNote()!
  29701. jassert (allowTailOff || (voice->getCurrentlyPlayingNote() < 0 && voice->getCurrentlyPlayingSound() == 0));
  29702. }
  29703. }
  29704. }
  29705. }
  29706. void Synthesiser::allNotesOff (const int midiChannel,
  29707. const bool allowTailOff)
  29708. {
  29709. const ScopedLock sl (lock);
  29710. for (int i = voices.size(); --i >= 0;)
  29711. {
  29712. SynthesiserVoice* const voice = voices.getUnchecked (i);
  29713. if (midiChannel <= 0 || voice->isPlayingChannel (midiChannel))
  29714. voice->stopNote (allowTailOff);
  29715. }
  29716. }
  29717. void Synthesiser::handlePitchWheel (const int midiChannel,
  29718. const int wheelValue)
  29719. {
  29720. const ScopedLock sl (lock);
  29721. for (int i = voices.size(); --i >= 0;)
  29722. {
  29723. SynthesiserVoice* const voice = voices.getUnchecked (i);
  29724. if (midiChannel <= 0 || voice->isPlayingChannel (midiChannel))
  29725. {
  29726. voice->pitchWheelMoved (wheelValue);
  29727. }
  29728. }
  29729. }
  29730. void Synthesiser::handleController (const int midiChannel,
  29731. const int controllerNumber,
  29732. const int controllerValue)
  29733. {
  29734. const ScopedLock sl (lock);
  29735. for (int i = voices.size(); --i >= 0;)
  29736. {
  29737. SynthesiserVoice* const voice = voices.getUnchecked (i);
  29738. if (midiChannel <= 0 || voice->isPlayingChannel (midiChannel))
  29739. voice->controllerMoved (controllerNumber, controllerValue);
  29740. }
  29741. }
  29742. SynthesiserVoice* Synthesiser::findFreeVoice (SynthesiserSound* soundToPlay,
  29743. const bool stealIfNoneAvailable) const
  29744. {
  29745. const ScopedLock sl (lock);
  29746. for (int i = voices.size(); --i >= 0;)
  29747. if (voices.getUnchecked (i)->getCurrentlyPlayingNote() < 0
  29748. && voices.getUnchecked (i)->canPlaySound (soundToPlay))
  29749. return voices.getUnchecked (i);
  29750. if (stealIfNoneAvailable)
  29751. {
  29752. // currently this just steals the one that's been playing the longest, but could be made a bit smarter..
  29753. SynthesiserVoice* oldest = 0;
  29754. for (int i = voices.size(); --i >= 0;)
  29755. {
  29756. SynthesiserVoice* const voice = voices.getUnchecked (i);
  29757. if (voice->canPlaySound (soundToPlay)
  29758. && (oldest == 0 || oldest->noteOnTime > voice->noteOnTime))
  29759. oldest = voice;
  29760. }
  29761. jassert (oldest != 0);
  29762. return oldest;
  29763. }
  29764. return 0;
  29765. }
  29766. END_JUCE_NAMESPACE
  29767. /*** End of inlined file: juce_Synthesiser.cpp ***/
  29768. /*** Start of inlined file: juce_ActionBroadcaster.cpp ***/
  29769. BEGIN_JUCE_NAMESPACE
  29770. ActionBroadcaster::ActionBroadcaster() throw()
  29771. {
  29772. // are you trying to create this object before or after juce has been intialised??
  29773. jassert (MessageManager::instance != 0);
  29774. }
  29775. ActionBroadcaster::~ActionBroadcaster()
  29776. {
  29777. // all event-based objects must be deleted BEFORE juce is shut down!
  29778. jassert (MessageManager::instance != 0);
  29779. }
  29780. void ActionBroadcaster::addActionListener (ActionListener* const listener)
  29781. {
  29782. actionListenerList.addActionListener (listener);
  29783. }
  29784. void ActionBroadcaster::removeActionListener (ActionListener* const listener)
  29785. {
  29786. jassert (actionListenerList.isValidMessageListener());
  29787. if (actionListenerList.isValidMessageListener())
  29788. actionListenerList.removeActionListener (listener);
  29789. }
  29790. void ActionBroadcaster::removeAllActionListeners()
  29791. {
  29792. actionListenerList.removeAllActionListeners();
  29793. }
  29794. void ActionBroadcaster::sendActionMessage (const String& message) const
  29795. {
  29796. actionListenerList.sendActionMessage (message);
  29797. }
  29798. END_JUCE_NAMESPACE
  29799. /*** End of inlined file: juce_ActionBroadcaster.cpp ***/
  29800. /*** Start of inlined file: juce_ActionListenerList.cpp ***/
  29801. BEGIN_JUCE_NAMESPACE
  29802. // special message of our own with a string in it
  29803. class ActionMessage : public Message
  29804. {
  29805. public:
  29806. const String message;
  29807. ActionMessage (const String& messageText,
  29808. void* const listener_) throw()
  29809. : message (messageText)
  29810. {
  29811. pointerParameter = listener_;
  29812. }
  29813. ~ActionMessage() throw()
  29814. {
  29815. }
  29816. private:
  29817. ActionMessage (const ActionMessage&);
  29818. ActionMessage& operator= (const ActionMessage&);
  29819. };
  29820. ActionListenerList::ActionListenerList() throw()
  29821. {
  29822. }
  29823. ActionListenerList::~ActionListenerList() throw()
  29824. {
  29825. }
  29826. void ActionListenerList::addActionListener (ActionListener* const listener) throw()
  29827. {
  29828. const ScopedLock sl (actionListenerLock_);
  29829. jassert (listener != 0);
  29830. jassert (! actionListeners_.contains (listener)); // trying to add a listener to the list twice!
  29831. if (listener != 0)
  29832. actionListeners_.add (listener);
  29833. }
  29834. void ActionListenerList::removeActionListener (ActionListener* const listener) throw()
  29835. {
  29836. const ScopedLock sl (actionListenerLock_);
  29837. jassert (actionListeners_.contains (listener)); // trying to remove a listener that isn't on the list!
  29838. actionListeners_.removeValue (listener);
  29839. }
  29840. void ActionListenerList::removeAllActionListeners() throw()
  29841. {
  29842. const ScopedLock sl (actionListenerLock_);
  29843. actionListeners_.clear();
  29844. }
  29845. void ActionListenerList::sendActionMessage (const String& message) const
  29846. {
  29847. const ScopedLock sl (actionListenerLock_);
  29848. for (int i = actionListeners_.size(); --i >= 0;)
  29849. postMessage (new ActionMessage (message, static_cast <ActionListener*> (actionListeners_.getUnchecked(i))));
  29850. }
  29851. void ActionListenerList::handleMessage (const Message& message)
  29852. {
  29853. const ActionMessage& am = (const ActionMessage&) message;
  29854. if (actionListeners_.contains (am.pointerParameter))
  29855. static_cast <ActionListener*> (am.pointerParameter)->actionListenerCallback (am.message);
  29856. }
  29857. END_JUCE_NAMESPACE
  29858. /*** End of inlined file: juce_ActionListenerList.cpp ***/
  29859. /*** Start of inlined file: juce_AsyncUpdater.cpp ***/
  29860. BEGIN_JUCE_NAMESPACE
  29861. AsyncUpdater::AsyncUpdater() throw()
  29862. : asyncMessagePending (false)
  29863. {
  29864. internalAsyncHandler.owner = this;
  29865. }
  29866. AsyncUpdater::~AsyncUpdater()
  29867. {
  29868. }
  29869. void AsyncUpdater::triggerAsyncUpdate() throw()
  29870. {
  29871. if (! asyncMessagePending)
  29872. {
  29873. asyncMessagePending = true;
  29874. internalAsyncHandler.postMessage (new Message());
  29875. }
  29876. }
  29877. void AsyncUpdater::cancelPendingUpdate() throw()
  29878. {
  29879. asyncMessagePending = false;
  29880. }
  29881. void AsyncUpdater::handleUpdateNowIfNeeded()
  29882. {
  29883. if (asyncMessagePending)
  29884. {
  29885. asyncMessagePending = false;
  29886. handleAsyncUpdate();
  29887. }
  29888. }
  29889. void AsyncUpdater::AsyncUpdaterInternal::handleMessage (const Message&)
  29890. {
  29891. owner->handleUpdateNowIfNeeded();
  29892. }
  29893. END_JUCE_NAMESPACE
  29894. /*** End of inlined file: juce_AsyncUpdater.cpp ***/
  29895. /*** Start of inlined file: juce_ChangeBroadcaster.cpp ***/
  29896. BEGIN_JUCE_NAMESPACE
  29897. ChangeBroadcaster::ChangeBroadcaster() throw()
  29898. {
  29899. // are you trying to create this object before or after juce has been intialised??
  29900. jassert (MessageManager::instance != 0);
  29901. }
  29902. ChangeBroadcaster::~ChangeBroadcaster()
  29903. {
  29904. // all event-based objects must be deleted BEFORE juce is shut down!
  29905. jassert (MessageManager::instance != 0);
  29906. }
  29907. void ChangeBroadcaster::addChangeListener (ChangeListener* const listener) throw()
  29908. {
  29909. changeListenerList.addChangeListener (listener);
  29910. }
  29911. void ChangeBroadcaster::removeChangeListener (ChangeListener* const listener) throw()
  29912. {
  29913. jassert (changeListenerList.isValidMessageListener());
  29914. if (changeListenerList.isValidMessageListener())
  29915. changeListenerList.removeChangeListener (listener);
  29916. }
  29917. void ChangeBroadcaster::removeAllChangeListeners() throw()
  29918. {
  29919. changeListenerList.removeAllChangeListeners();
  29920. }
  29921. void ChangeBroadcaster::sendChangeMessage (void* objectThatHasChanged) throw()
  29922. {
  29923. changeListenerList.sendChangeMessage (objectThatHasChanged);
  29924. }
  29925. void ChangeBroadcaster::sendSynchronousChangeMessage (void* objectThatHasChanged)
  29926. {
  29927. changeListenerList.sendSynchronousChangeMessage (objectThatHasChanged);
  29928. }
  29929. void ChangeBroadcaster::dispatchPendingMessages()
  29930. {
  29931. changeListenerList.dispatchPendingMessages();
  29932. }
  29933. END_JUCE_NAMESPACE
  29934. /*** End of inlined file: juce_ChangeBroadcaster.cpp ***/
  29935. /*** Start of inlined file: juce_ChangeListenerList.cpp ***/
  29936. BEGIN_JUCE_NAMESPACE
  29937. ChangeListenerList::ChangeListenerList() throw()
  29938. : lastChangedObject (0),
  29939. messagePending (false)
  29940. {
  29941. }
  29942. ChangeListenerList::~ChangeListenerList() throw()
  29943. {
  29944. }
  29945. void ChangeListenerList::addChangeListener (ChangeListener* const listener) throw()
  29946. {
  29947. const ScopedLock sl (lock);
  29948. jassert (listener != 0);
  29949. if (listener != 0)
  29950. listeners.add (listener);
  29951. }
  29952. void ChangeListenerList::removeChangeListener (ChangeListener* const listener) throw()
  29953. {
  29954. const ScopedLock sl (lock);
  29955. listeners.removeValue (listener);
  29956. }
  29957. void ChangeListenerList::removeAllChangeListeners() throw()
  29958. {
  29959. const ScopedLock sl (lock);
  29960. listeners.clear();
  29961. }
  29962. void ChangeListenerList::sendChangeMessage (void* const objectThatHasChanged) throw()
  29963. {
  29964. const ScopedLock sl (lock);
  29965. if ((! messagePending) && (listeners.size() > 0))
  29966. {
  29967. lastChangedObject = objectThatHasChanged;
  29968. postMessage (new Message (0, 0, 0, objectThatHasChanged));
  29969. messagePending = true;
  29970. }
  29971. }
  29972. void ChangeListenerList::handleMessage (const Message& message)
  29973. {
  29974. sendSynchronousChangeMessage (message.pointerParameter);
  29975. }
  29976. void ChangeListenerList::sendSynchronousChangeMessage (void* const objectThatHasChanged)
  29977. {
  29978. const ScopedLock sl (lock);
  29979. messagePending = false;
  29980. for (int i = listeners.size(); --i >= 0;)
  29981. {
  29982. ChangeListener* const l = static_cast <ChangeListener*> (listeners.getUnchecked (i));
  29983. {
  29984. const ScopedUnlock tempUnlocker (lock);
  29985. l->changeListenerCallback (objectThatHasChanged);
  29986. }
  29987. i = jmin (i, listeners.size());
  29988. }
  29989. }
  29990. void ChangeListenerList::dispatchPendingMessages()
  29991. {
  29992. if (messagePending)
  29993. sendSynchronousChangeMessage (lastChangedObject);
  29994. }
  29995. END_JUCE_NAMESPACE
  29996. /*** End of inlined file: juce_ChangeListenerList.cpp ***/
  29997. /*** Start of inlined file: juce_InterprocessConnection.cpp ***/
  29998. BEGIN_JUCE_NAMESPACE
  29999. InterprocessConnection::InterprocessConnection (const bool callbacksOnMessageThread,
  30000. const uint32 magicMessageHeaderNumber)
  30001. : Thread ("Juce IPC connection"),
  30002. callbackConnectionState (false),
  30003. useMessageThread (callbacksOnMessageThread),
  30004. magicMessageHeader (magicMessageHeaderNumber),
  30005. pipeReceiveMessageTimeout (-1)
  30006. {
  30007. }
  30008. InterprocessConnection::~InterprocessConnection()
  30009. {
  30010. callbackConnectionState = false;
  30011. disconnect();
  30012. }
  30013. bool InterprocessConnection::connectToSocket (const String& hostName,
  30014. const int portNumber,
  30015. const int timeOutMillisecs)
  30016. {
  30017. disconnect();
  30018. const ScopedLock sl (pipeAndSocketLock);
  30019. socket = new StreamingSocket();
  30020. if (socket->connect (hostName, portNumber, timeOutMillisecs))
  30021. {
  30022. connectionMadeInt();
  30023. startThread();
  30024. return true;
  30025. }
  30026. else
  30027. {
  30028. socket = 0;
  30029. return false;
  30030. }
  30031. }
  30032. bool InterprocessConnection::connectToPipe (const String& pipeName,
  30033. const int pipeReceiveMessageTimeoutMs)
  30034. {
  30035. disconnect();
  30036. ScopedPointer <NamedPipe> newPipe (new NamedPipe());
  30037. if (newPipe->openExisting (pipeName))
  30038. {
  30039. const ScopedLock sl (pipeAndSocketLock);
  30040. pipeReceiveMessageTimeout = pipeReceiveMessageTimeoutMs;
  30041. initialiseWithPipe (newPipe.release());
  30042. return true;
  30043. }
  30044. return false;
  30045. }
  30046. bool InterprocessConnection::createPipe (const String& pipeName,
  30047. const int pipeReceiveMessageTimeoutMs)
  30048. {
  30049. disconnect();
  30050. ScopedPointer <NamedPipe> newPipe (new NamedPipe());
  30051. if (newPipe->createNewPipe (pipeName))
  30052. {
  30053. const ScopedLock sl (pipeAndSocketLock);
  30054. pipeReceiveMessageTimeout = pipeReceiveMessageTimeoutMs;
  30055. initialiseWithPipe (newPipe.release());
  30056. return true;
  30057. }
  30058. return false;
  30059. }
  30060. void InterprocessConnection::disconnect()
  30061. {
  30062. if (socket != 0)
  30063. socket->close();
  30064. if (pipe != 0)
  30065. {
  30066. pipe->cancelPendingReads();
  30067. pipe->close();
  30068. }
  30069. stopThread (4000);
  30070. {
  30071. const ScopedLock sl (pipeAndSocketLock);
  30072. socket = 0;
  30073. pipe = 0;
  30074. }
  30075. connectionLostInt();
  30076. }
  30077. bool InterprocessConnection::isConnected() const
  30078. {
  30079. const ScopedLock sl (pipeAndSocketLock);
  30080. return ((socket != 0 && socket->isConnected())
  30081. || (pipe != 0 && pipe->isOpen()))
  30082. && isThreadRunning();
  30083. }
  30084. const String InterprocessConnection::getConnectedHostName() const
  30085. {
  30086. if (pipe != 0)
  30087. {
  30088. return "localhost";
  30089. }
  30090. else if (socket != 0)
  30091. {
  30092. if (! socket->isLocal())
  30093. return socket->getHostName();
  30094. return "localhost";
  30095. }
  30096. return String::empty;
  30097. }
  30098. bool InterprocessConnection::sendMessage (const MemoryBlock& message)
  30099. {
  30100. uint32 messageHeader[2];
  30101. messageHeader [0] = ByteOrder::swapIfBigEndian (magicMessageHeader);
  30102. messageHeader [1] = ByteOrder::swapIfBigEndian ((uint32) message.getSize());
  30103. MemoryBlock messageData (sizeof (messageHeader) + message.getSize());
  30104. messageData.copyFrom (messageHeader, 0, sizeof (messageHeader));
  30105. messageData.copyFrom (message.getData(), sizeof (messageHeader), message.getSize());
  30106. size_t bytesWritten = 0;
  30107. const ScopedLock sl (pipeAndSocketLock);
  30108. if (socket != 0)
  30109. {
  30110. bytesWritten = socket->write (messageData.getData(), (int) messageData.getSize());
  30111. }
  30112. else if (pipe != 0)
  30113. {
  30114. bytesWritten = pipe->write (messageData.getData(), (int) messageData.getSize());
  30115. }
  30116. if (bytesWritten < 0)
  30117. {
  30118. // error..
  30119. return false;
  30120. }
  30121. return (bytesWritten == messageData.getSize());
  30122. }
  30123. void InterprocessConnection::initialiseWithSocket (StreamingSocket* const socket_)
  30124. {
  30125. jassert (socket == 0);
  30126. socket = socket_;
  30127. connectionMadeInt();
  30128. startThread();
  30129. }
  30130. void InterprocessConnection::initialiseWithPipe (NamedPipe* const pipe_)
  30131. {
  30132. jassert (pipe == 0);
  30133. pipe = pipe_;
  30134. connectionMadeInt();
  30135. startThread();
  30136. }
  30137. const int messageMagicNumber = 0xb734128b;
  30138. void InterprocessConnection::handleMessage (const Message& message)
  30139. {
  30140. if (message.intParameter1 == messageMagicNumber)
  30141. {
  30142. switch (message.intParameter2)
  30143. {
  30144. case 0:
  30145. {
  30146. ScopedPointer <MemoryBlock> data (static_cast <MemoryBlock*> (message.pointerParameter));
  30147. messageReceived (*data);
  30148. break;
  30149. }
  30150. case 1:
  30151. connectionMade();
  30152. break;
  30153. case 2:
  30154. connectionLost();
  30155. break;
  30156. }
  30157. }
  30158. }
  30159. void InterprocessConnection::connectionMadeInt()
  30160. {
  30161. if (! callbackConnectionState)
  30162. {
  30163. callbackConnectionState = true;
  30164. if (useMessageThread)
  30165. postMessage (new Message (messageMagicNumber, 1, 0, 0));
  30166. else
  30167. connectionMade();
  30168. }
  30169. }
  30170. void InterprocessConnection::connectionLostInt()
  30171. {
  30172. if (callbackConnectionState)
  30173. {
  30174. callbackConnectionState = false;
  30175. if (useMessageThread)
  30176. postMessage (new Message (messageMagicNumber, 2, 0, 0));
  30177. else
  30178. connectionLost();
  30179. }
  30180. }
  30181. void InterprocessConnection::deliverDataInt (const MemoryBlock& data)
  30182. {
  30183. jassert (callbackConnectionState);
  30184. if (useMessageThread)
  30185. postMessage (new Message (messageMagicNumber, 0, 0, new MemoryBlock (data)));
  30186. else
  30187. messageReceived (data);
  30188. }
  30189. bool InterprocessConnection::readNextMessageInt()
  30190. {
  30191. const int maximumMessageSize = 1024 * 1024 * 10; // sanity check
  30192. uint32 messageHeader[2];
  30193. const int bytes = (socket != 0) ? socket->read (messageHeader, sizeof (messageHeader), true)
  30194. : pipe->read (messageHeader, sizeof (messageHeader), pipeReceiveMessageTimeout);
  30195. if (bytes == sizeof (messageHeader)
  30196. && ByteOrder::swapIfBigEndian (messageHeader[0]) == magicMessageHeader)
  30197. {
  30198. int bytesInMessage = (int) ByteOrder::swapIfBigEndian (messageHeader[1]);
  30199. if (bytesInMessage > 0 && bytesInMessage < maximumMessageSize)
  30200. {
  30201. MemoryBlock messageData (bytesInMessage, true);
  30202. int bytesRead = 0;
  30203. while (bytesInMessage > 0)
  30204. {
  30205. if (threadShouldExit())
  30206. return false;
  30207. const int numThisTime = jmin (bytesInMessage, 65536);
  30208. const int bytesIn = (socket != 0) ? socket->read (static_cast <char*> (messageData.getData()) + bytesRead, numThisTime, true)
  30209. : pipe->read (static_cast <char*> (messageData.getData()) + bytesRead, numThisTime, pipeReceiveMessageTimeout);
  30210. if (bytesIn <= 0)
  30211. break;
  30212. bytesRead += bytesIn;
  30213. bytesInMessage -= bytesIn;
  30214. }
  30215. if (bytesRead >= 0)
  30216. deliverDataInt (messageData);
  30217. }
  30218. }
  30219. else if (bytes < 0)
  30220. {
  30221. {
  30222. const ScopedLock sl (pipeAndSocketLock);
  30223. socket = 0;
  30224. }
  30225. connectionLostInt();
  30226. return false;
  30227. }
  30228. return true;
  30229. }
  30230. void InterprocessConnection::run()
  30231. {
  30232. while (! threadShouldExit())
  30233. {
  30234. if (socket != 0)
  30235. {
  30236. const int ready = socket->waitUntilReady (true, 0);
  30237. if (ready < 0)
  30238. {
  30239. {
  30240. const ScopedLock sl (pipeAndSocketLock);
  30241. socket = 0;
  30242. }
  30243. connectionLostInt();
  30244. break;
  30245. }
  30246. else if (ready > 0)
  30247. {
  30248. if (! readNextMessageInt())
  30249. break;
  30250. }
  30251. else
  30252. {
  30253. Thread::sleep (2);
  30254. }
  30255. }
  30256. else if (pipe != 0)
  30257. {
  30258. if (! pipe->isOpen())
  30259. {
  30260. {
  30261. const ScopedLock sl (pipeAndSocketLock);
  30262. pipe = 0;
  30263. }
  30264. connectionLostInt();
  30265. break;
  30266. }
  30267. else
  30268. {
  30269. if (! readNextMessageInt())
  30270. break;
  30271. }
  30272. }
  30273. else
  30274. {
  30275. break;
  30276. }
  30277. }
  30278. }
  30279. END_JUCE_NAMESPACE
  30280. /*** End of inlined file: juce_InterprocessConnection.cpp ***/
  30281. /*** Start of inlined file: juce_InterprocessConnectionServer.cpp ***/
  30282. BEGIN_JUCE_NAMESPACE
  30283. InterprocessConnectionServer::InterprocessConnectionServer()
  30284. : Thread ("Juce IPC server")
  30285. {
  30286. }
  30287. InterprocessConnectionServer::~InterprocessConnectionServer()
  30288. {
  30289. stop();
  30290. }
  30291. bool InterprocessConnectionServer::beginWaitingForSocket (const int portNumber)
  30292. {
  30293. stop();
  30294. socket = new StreamingSocket();
  30295. if (socket->createListener (portNumber))
  30296. {
  30297. startThread();
  30298. return true;
  30299. }
  30300. socket = 0;
  30301. return false;
  30302. }
  30303. void InterprocessConnectionServer::stop()
  30304. {
  30305. signalThreadShouldExit();
  30306. if (socket != 0)
  30307. socket->close();
  30308. stopThread (4000);
  30309. socket = 0;
  30310. }
  30311. void InterprocessConnectionServer::run()
  30312. {
  30313. while ((! threadShouldExit()) && socket != 0)
  30314. {
  30315. ScopedPointer <StreamingSocket> clientSocket (socket->waitForNextConnection());
  30316. if (clientSocket != 0)
  30317. {
  30318. InterprocessConnection* newConnection = createConnectionObject();
  30319. if (newConnection != 0)
  30320. newConnection->initialiseWithSocket (clientSocket.release());
  30321. }
  30322. }
  30323. }
  30324. END_JUCE_NAMESPACE
  30325. /*** End of inlined file: juce_InterprocessConnectionServer.cpp ***/
  30326. /*** Start of inlined file: juce_Message.cpp ***/
  30327. BEGIN_JUCE_NAMESPACE
  30328. Message::Message() throw()
  30329. : intParameter1 (0),
  30330. intParameter2 (0),
  30331. intParameter3 (0),
  30332. pointerParameter (0)
  30333. {
  30334. }
  30335. Message::Message (const int intParameter1_,
  30336. const int intParameter2_,
  30337. const int intParameter3_,
  30338. void* const pointerParameter_) throw()
  30339. : intParameter1 (intParameter1_),
  30340. intParameter2 (intParameter2_),
  30341. intParameter3 (intParameter3_),
  30342. pointerParameter (pointerParameter_)
  30343. {
  30344. }
  30345. Message::~Message() throw()
  30346. {
  30347. }
  30348. END_JUCE_NAMESPACE
  30349. /*** End of inlined file: juce_Message.cpp ***/
  30350. /*** Start of inlined file: juce_MessageListener.cpp ***/
  30351. BEGIN_JUCE_NAMESPACE
  30352. MessageListener::MessageListener() throw()
  30353. {
  30354. // are you trying to create a messagelistener before or after juce has been intialised??
  30355. jassert (MessageManager::instance != 0);
  30356. if (MessageManager::instance != 0)
  30357. MessageManager::instance->messageListeners.add (this);
  30358. }
  30359. MessageListener::~MessageListener()
  30360. {
  30361. if (MessageManager::instance != 0)
  30362. MessageManager::instance->messageListeners.removeValue (this);
  30363. }
  30364. void MessageListener::postMessage (Message* const message) const throw()
  30365. {
  30366. message->messageRecipient = const_cast <MessageListener*> (this);
  30367. if (MessageManager::instance == 0)
  30368. MessageManager::getInstance();
  30369. MessageManager::instance->postMessageToQueue (message);
  30370. }
  30371. bool MessageListener::isValidMessageListener() const throw()
  30372. {
  30373. return (MessageManager::instance != 0)
  30374. && MessageManager::instance->messageListeners.contains (this);
  30375. }
  30376. END_JUCE_NAMESPACE
  30377. /*** End of inlined file: juce_MessageListener.cpp ***/
  30378. /*** Start of inlined file: juce_MessageManager.cpp ***/
  30379. BEGIN_JUCE_NAMESPACE
  30380. // platform-specific functions..
  30381. bool juce_dispatchNextMessageOnSystemQueue (bool returnIfNoPendingMessages);
  30382. bool juce_postMessageToSystemQueue (void* message);
  30383. MessageManager* MessageManager::instance = 0;
  30384. static const int quitMessageId = 0xfffff321;
  30385. MessageManager::MessageManager() throw()
  30386. : quitMessagePosted (false),
  30387. quitMessageReceived (false),
  30388. threadWithLock (0)
  30389. {
  30390. messageThreadId = Thread::getCurrentThreadId();
  30391. }
  30392. MessageManager::~MessageManager() throw()
  30393. {
  30394. broadcastListeners = 0;
  30395. doPlatformSpecificShutdown();
  30396. jassert (instance == this);
  30397. instance = 0; // do this last in case this instance is still needed by doPlatformSpecificShutdown()
  30398. }
  30399. MessageManager* MessageManager::getInstance() throw()
  30400. {
  30401. if (instance == 0)
  30402. {
  30403. instance = new MessageManager();
  30404. doPlatformSpecificInitialisation();
  30405. }
  30406. return instance;
  30407. }
  30408. void MessageManager::postMessageToQueue (Message* const message)
  30409. {
  30410. if (quitMessagePosted || ! juce_postMessageToSystemQueue (message))
  30411. delete message;
  30412. }
  30413. CallbackMessage::CallbackMessage() throw() {}
  30414. CallbackMessage::~CallbackMessage() throw() {}
  30415. void CallbackMessage::post()
  30416. {
  30417. if (MessageManager::instance != 0)
  30418. MessageManager::instance->postCallbackMessage (this);
  30419. }
  30420. void MessageManager::postCallbackMessage (Message* const message)
  30421. {
  30422. message->messageRecipient = 0;
  30423. postMessageToQueue (message);
  30424. }
  30425. // not for public use..
  30426. void MessageManager::deliverMessage (void* const message)
  30427. {
  30428. const ScopedPointer <Message> m (static_cast <Message*> (message));
  30429. MessageListener* const recipient = m->messageRecipient;
  30430. JUCE_TRY
  30431. {
  30432. if (messageListeners.contains (recipient))
  30433. {
  30434. recipient->handleMessage (*m);
  30435. }
  30436. else if (recipient == 0)
  30437. {
  30438. if (m->intParameter1 == quitMessageId)
  30439. {
  30440. quitMessageReceived = true;
  30441. }
  30442. else
  30443. {
  30444. CallbackMessage* const cm = dynamic_cast <CallbackMessage*> (static_cast <Message*> (m));
  30445. if (cm != 0)
  30446. cm->messageCallback();
  30447. }
  30448. }
  30449. }
  30450. JUCE_CATCH_EXCEPTION
  30451. }
  30452. #if ! (JUCE_MAC || JUCE_IPHONE)
  30453. void MessageManager::runDispatchLoop()
  30454. {
  30455. jassert (isThisTheMessageThread()); // must only be called by the message thread
  30456. runDispatchLoopUntil (-1);
  30457. }
  30458. void MessageManager::stopDispatchLoop()
  30459. {
  30460. Message* const m = new Message (quitMessageId, 0, 0, 0);
  30461. m->messageRecipient = 0;
  30462. postMessageToQueue (m);
  30463. quitMessagePosted = true;
  30464. }
  30465. bool MessageManager::runDispatchLoopUntil (int millisecondsToRunFor)
  30466. {
  30467. jassert (isThisTheMessageThread()); // must only be called by the message thread
  30468. const int64 endTime = Time::currentTimeMillis() + millisecondsToRunFor;
  30469. while ((millisecondsToRunFor < 0 || endTime > Time::currentTimeMillis())
  30470. && ! quitMessageReceived)
  30471. {
  30472. JUCE_TRY
  30473. {
  30474. if (! juce_dispatchNextMessageOnSystemQueue (millisecondsToRunFor >= 0))
  30475. {
  30476. const int msToWait = (int) (endTime - Time::currentTimeMillis());
  30477. if (msToWait > 0)
  30478. Thread::sleep (jmin (5, msToWait));
  30479. }
  30480. }
  30481. JUCE_CATCH_EXCEPTION
  30482. }
  30483. return ! quitMessageReceived;
  30484. }
  30485. #endif
  30486. void MessageManager::deliverBroadcastMessage (const String& value)
  30487. {
  30488. if (broadcastListeners != 0)
  30489. broadcastListeners->sendActionMessage (value);
  30490. }
  30491. void MessageManager::registerBroadcastListener (ActionListener* const listener) throw()
  30492. {
  30493. if (broadcastListeners == 0)
  30494. broadcastListeners = new ActionListenerList();
  30495. broadcastListeners->addActionListener (listener);
  30496. }
  30497. void MessageManager::deregisterBroadcastListener (ActionListener* const listener) throw()
  30498. {
  30499. if (broadcastListeners != 0)
  30500. broadcastListeners->removeActionListener (listener);
  30501. }
  30502. bool MessageManager::isThisTheMessageThread() const throw()
  30503. {
  30504. return Thread::getCurrentThreadId() == messageThreadId;
  30505. }
  30506. void MessageManager::setCurrentThreadAsMessageThread()
  30507. {
  30508. if (messageThreadId != Thread::getCurrentThreadId())
  30509. {
  30510. messageThreadId = Thread::getCurrentThreadId();
  30511. // This is needed on windows to make sure the message window is created by this thread
  30512. doPlatformSpecificShutdown();
  30513. doPlatformSpecificInitialisation();
  30514. }
  30515. }
  30516. bool MessageManager::currentThreadHasLockedMessageManager() const throw()
  30517. {
  30518. const Thread::ThreadID thisThread = Thread::getCurrentThreadId();
  30519. return thisThread == messageThreadId || thisThread == threadWithLock;
  30520. }
  30521. /* The only safe way to lock the message thread while another thread does
  30522. some work is by posting a special message, whose purpose is to tie up the event
  30523. loop until the other thread has finished its business.
  30524. Any other approach can get horribly deadlocked if the OS uses its own hidden locks which
  30525. get locked before making an event callback, because if the same OS lock gets indirectly
  30526. accessed from another thread inside a MM lock, you're screwed. (this is exactly what happens
  30527. in Cocoa).
  30528. */
  30529. class MessageManagerLock::SharedEvents : public ReferenceCountedObject
  30530. {
  30531. public:
  30532. SharedEvents() {}
  30533. ~SharedEvents() {}
  30534. /* This class just holds a couple of events to communicate between the BlockingMessage
  30535. and the MessageManagerLock. Because both of these objects may be deleted at any time,
  30536. this shared data must be kept in a separate, ref-counted container. */
  30537. WaitableEvent lockedEvent, releaseEvent;
  30538. private:
  30539. SharedEvents (const SharedEvents&);
  30540. SharedEvents& operator= (const SharedEvents&);
  30541. };
  30542. class MessageManagerLock::BlockingMessage : public CallbackMessage
  30543. {
  30544. public:
  30545. BlockingMessage (MessageManagerLock::SharedEvents* const events_) : events (events_) {}
  30546. ~BlockingMessage() throw() {}
  30547. void messageCallback()
  30548. {
  30549. events->lockedEvent.signal();
  30550. events->releaseEvent.wait();
  30551. }
  30552. juce_UseDebuggingNewOperator
  30553. private:
  30554. ReferenceCountedObjectPtr <MessageManagerLock::SharedEvents> events;
  30555. BlockingMessage (const BlockingMessage&);
  30556. BlockingMessage& operator= (const BlockingMessage&);
  30557. };
  30558. MessageManagerLock::MessageManagerLock (Thread* const threadToCheck) throw()
  30559. : sharedEvents (0),
  30560. locked (false)
  30561. {
  30562. init (threadToCheck, 0);
  30563. }
  30564. MessageManagerLock::MessageManagerLock (ThreadPoolJob* const jobToCheckForExitSignal) throw()
  30565. : sharedEvents (0),
  30566. locked (false)
  30567. {
  30568. init (0, jobToCheckForExitSignal);
  30569. }
  30570. void MessageManagerLock::init (Thread* const threadToCheck, ThreadPoolJob* const job) throw()
  30571. {
  30572. if (MessageManager::instance != 0)
  30573. {
  30574. if (MessageManager::instance->currentThreadHasLockedMessageManager())
  30575. {
  30576. locked = true; // either we're on the message thread, or this is a re-entrant call.
  30577. }
  30578. else
  30579. {
  30580. if (threadToCheck == 0 && job == 0)
  30581. {
  30582. MessageManager::instance->lockingLock.enter();
  30583. }
  30584. else
  30585. {
  30586. while (! MessageManager::instance->lockingLock.tryEnter())
  30587. {
  30588. if ((threadToCheck != 0 && threadToCheck->threadShouldExit())
  30589. || (job != 0 && job->shouldExit()))
  30590. return;
  30591. Thread::sleep (1);
  30592. }
  30593. }
  30594. sharedEvents = new SharedEvents();
  30595. sharedEvents->incReferenceCount();
  30596. (new BlockingMessage (sharedEvents))->post();
  30597. while (! sharedEvents->lockedEvent.wait (50))
  30598. {
  30599. if ((threadToCheck != 0 && threadToCheck->threadShouldExit())
  30600. || (job != 0 && job->shouldExit()))
  30601. {
  30602. sharedEvents->releaseEvent.signal();
  30603. sharedEvents->decReferenceCount();
  30604. sharedEvents = 0;
  30605. MessageManager::instance->lockingLock.exit();
  30606. return;
  30607. }
  30608. }
  30609. jassert (MessageManager::instance->threadWithLock == 0);
  30610. MessageManager::instance->threadWithLock = Thread::getCurrentThreadId();
  30611. locked = true;
  30612. }
  30613. }
  30614. }
  30615. MessageManagerLock::~MessageManagerLock() throw()
  30616. {
  30617. if (sharedEvents != 0)
  30618. {
  30619. jassert (MessageManager::instance == 0 || MessageManager::instance->currentThreadHasLockedMessageManager());
  30620. sharedEvents->releaseEvent.signal();
  30621. sharedEvents->decReferenceCount();
  30622. if (MessageManager::instance != 0)
  30623. {
  30624. MessageManager::instance->threadWithLock = 0;
  30625. MessageManager::instance->lockingLock.exit();
  30626. }
  30627. }
  30628. }
  30629. END_JUCE_NAMESPACE
  30630. /*** End of inlined file: juce_MessageManager.cpp ***/
  30631. /*** Start of inlined file: juce_MultiTimer.cpp ***/
  30632. BEGIN_JUCE_NAMESPACE
  30633. class MultiTimer::MultiTimerCallback : public Timer
  30634. {
  30635. public:
  30636. MultiTimerCallback (const int timerId_, MultiTimer& owner_)
  30637. : timerId (timerId_),
  30638. owner (owner_)
  30639. {
  30640. }
  30641. ~MultiTimerCallback()
  30642. {
  30643. }
  30644. void timerCallback()
  30645. {
  30646. owner.timerCallback (timerId);
  30647. }
  30648. const int timerId;
  30649. private:
  30650. MultiTimer& owner;
  30651. };
  30652. MultiTimer::MultiTimer() throw()
  30653. {
  30654. }
  30655. MultiTimer::MultiTimer (const MultiTimer&) throw()
  30656. {
  30657. }
  30658. MultiTimer::~MultiTimer()
  30659. {
  30660. const ScopedLock sl (timerListLock);
  30661. timers.clear();
  30662. }
  30663. void MultiTimer::startTimer (const int timerId, const int intervalInMilliseconds) throw()
  30664. {
  30665. const ScopedLock sl (timerListLock);
  30666. for (int i = timers.size(); --i >= 0;)
  30667. {
  30668. MultiTimerCallback* const t = timers.getUnchecked(i);
  30669. if (t->timerId == timerId)
  30670. {
  30671. t->startTimer (intervalInMilliseconds);
  30672. return;
  30673. }
  30674. }
  30675. MultiTimerCallback* const newTimer = new MultiTimerCallback (timerId, *this);
  30676. timers.add (newTimer);
  30677. newTimer->startTimer (intervalInMilliseconds);
  30678. }
  30679. void MultiTimer::stopTimer (const int timerId) throw()
  30680. {
  30681. const ScopedLock sl (timerListLock);
  30682. for (int i = timers.size(); --i >= 0;)
  30683. {
  30684. MultiTimerCallback* const t = timers.getUnchecked(i);
  30685. if (t->timerId == timerId)
  30686. t->stopTimer();
  30687. }
  30688. }
  30689. bool MultiTimer::isTimerRunning (const int timerId) const throw()
  30690. {
  30691. const ScopedLock sl (timerListLock);
  30692. for (int i = timers.size(); --i >= 0;)
  30693. {
  30694. const MultiTimerCallback* const t = timers.getUnchecked(i);
  30695. if (t->timerId == timerId)
  30696. return t->isTimerRunning();
  30697. }
  30698. return false;
  30699. }
  30700. int MultiTimer::getTimerInterval (const int timerId) const throw()
  30701. {
  30702. const ScopedLock sl (timerListLock);
  30703. for (int i = timers.size(); --i >= 0;)
  30704. {
  30705. const MultiTimerCallback* const t = timers.getUnchecked(i);
  30706. if (t->timerId == timerId)
  30707. return t->getTimerInterval();
  30708. }
  30709. return 0;
  30710. }
  30711. END_JUCE_NAMESPACE
  30712. /*** End of inlined file: juce_MultiTimer.cpp ***/
  30713. /*** Start of inlined file: juce_Timer.cpp ***/
  30714. BEGIN_JUCE_NAMESPACE
  30715. class InternalTimerThread : private Thread,
  30716. private MessageListener,
  30717. private DeletedAtShutdown,
  30718. private AsyncUpdater
  30719. {
  30720. public:
  30721. InternalTimerThread()
  30722. : Thread ("Juce Timer"),
  30723. firstTimer (0),
  30724. callbackNeeded (0)
  30725. {
  30726. triggerAsyncUpdate();
  30727. }
  30728. ~InternalTimerThread() throw()
  30729. {
  30730. stopThread (4000);
  30731. jassert (instance == this || instance == 0);
  30732. if (instance == this)
  30733. instance = 0;
  30734. }
  30735. void run()
  30736. {
  30737. uint32 lastTime = Time::getMillisecondCounter();
  30738. while (! threadShouldExit())
  30739. {
  30740. const uint32 now = Time::getMillisecondCounter();
  30741. if (now <= lastTime)
  30742. {
  30743. wait (2);
  30744. continue;
  30745. }
  30746. const int elapsed = now - lastTime;
  30747. lastTime = now;
  30748. int timeUntilFirstTimer = 1000;
  30749. {
  30750. const ScopedLock sl (lock);
  30751. decrementAllCounters (elapsed);
  30752. if (firstTimer != 0)
  30753. timeUntilFirstTimer = firstTimer->countdownMs;
  30754. }
  30755. if (timeUntilFirstTimer <= 0)
  30756. {
  30757. /* If we managed to set the atomic boolean to true then send a message, this is needed
  30758. as a memory barrier so the message won't be sent before callbackNeeded is set to true,
  30759. but if it fails it means the message-thread changed the value from under us so at least
  30760. some processing is happenening and we can just loop around and try again
  30761. */
  30762. if (callbackNeeded.compareAndSetBool (1, 0))
  30763. {
  30764. postMessage (new Message());
  30765. /* Sometimes our message can get discarded by the OS (e.g. when running as an RTAS
  30766. when the app has a modal loop), so this is how long to wait before assuming the
  30767. message has been lost and trying again.
  30768. */
  30769. const uint32 messageDeliveryTimeout = now + 2000;
  30770. while (callbackNeeded.get() != 0)
  30771. {
  30772. wait (4);
  30773. if (threadShouldExit())
  30774. return;
  30775. if (Time::getMillisecondCounter() > messageDeliveryTimeout)
  30776. break;
  30777. }
  30778. }
  30779. }
  30780. else
  30781. {
  30782. // don't wait for too long because running this loop also helps keep the
  30783. // Time::getApproximateMillisecondTimer value stay up-to-date
  30784. wait (jlimit (1, 50, timeUntilFirstTimer));
  30785. }
  30786. }
  30787. }
  30788. void callTimers()
  30789. {
  30790. const ScopedLock sl (lock);
  30791. while (firstTimer != 0 && firstTimer->countdownMs <= 0)
  30792. {
  30793. Timer* const t = firstTimer;
  30794. t->countdownMs = t->periodMs;
  30795. removeTimer (t);
  30796. addTimer (t);
  30797. const ScopedUnlock ul (lock);
  30798. JUCE_TRY
  30799. {
  30800. t->timerCallback();
  30801. }
  30802. JUCE_CATCH_EXCEPTION
  30803. }
  30804. /* This is needed as a memory barrier to make sure all processing of current timers is done
  30805. before the boolean is set. This set should never fail since if it was false in the first place,
  30806. we wouldn't get a message (so it can't be changed from false to true from under us), and if we
  30807. get a message then the value is true and the other thread can only set it to true again and
  30808. we will get another callback to set it to false.
  30809. */
  30810. callbackNeeded.set (0);
  30811. }
  30812. void handleMessage (const Message&)
  30813. {
  30814. callTimers();
  30815. }
  30816. void callTimersSynchronously()
  30817. {
  30818. if (! isThreadRunning())
  30819. {
  30820. // (This is relied on by some plugins in cases where the MM has
  30821. // had to restart and the async callback never started)
  30822. cancelPendingUpdate();
  30823. triggerAsyncUpdate();
  30824. }
  30825. callTimers();
  30826. }
  30827. static void callAnyTimersSynchronously()
  30828. {
  30829. if (InternalTimerThread::instance != 0)
  30830. InternalTimerThread::instance->callTimersSynchronously();
  30831. }
  30832. static inline void add (Timer* const tim) throw()
  30833. {
  30834. if (instance == 0)
  30835. instance = new InternalTimerThread();
  30836. const ScopedLock sl (instance->lock);
  30837. instance->addTimer (tim);
  30838. }
  30839. static inline void remove (Timer* const tim) throw()
  30840. {
  30841. if (instance != 0)
  30842. {
  30843. const ScopedLock sl (instance->lock);
  30844. instance->removeTimer (tim);
  30845. }
  30846. }
  30847. static inline void resetCounter (Timer* const tim,
  30848. const int newCounter) throw()
  30849. {
  30850. if (instance != 0)
  30851. {
  30852. tim->countdownMs = newCounter;
  30853. tim->periodMs = newCounter;
  30854. if ((tim->next != 0 && tim->next->countdownMs < tim->countdownMs)
  30855. || (tim->previous != 0 && tim->previous->countdownMs > tim->countdownMs))
  30856. {
  30857. const ScopedLock sl (instance->lock);
  30858. instance->removeTimer (tim);
  30859. instance->addTimer (tim);
  30860. }
  30861. }
  30862. }
  30863. private:
  30864. friend class Timer;
  30865. static InternalTimerThread* instance;
  30866. static CriticalSection lock;
  30867. Timer* volatile firstTimer;
  30868. Atomic <int> callbackNeeded;
  30869. void addTimer (Timer* const t) throw()
  30870. {
  30871. #if JUCE_DEBUG
  30872. Timer* tt = firstTimer;
  30873. while (tt != 0)
  30874. {
  30875. // trying to add a timer that's already here - shouldn't get to this point,
  30876. // so if you get this assertion, let me know!
  30877. jassert (tt != t);
  30878. tt = tt->next;
  30879. }
  30880. jassert (t->previous == 0 && t->next == 0);
  30881. #endif
  30882. Timer* i = firstTimer;
  30883. if (i == 0 || i->countdownMs > t->countdownMs)
  30884. {
  30885. t->next = firstTimer;
  30886. firstTimer = t;
  30887. }
  30888. else
  30889. {
  30890. while (i->next != 0 && i->next->countdownMs <= t->countdownMs)
  30891. i = i->next;
  30892. jassert (i != 0);
  30893. t->next = i->next;
  30894. t->previous = i;
  30895. i->next = t;
  30896. }
  30897. if (t->next != 0)
  30898. t->next->previous = t;
  30899. jassert ((t->next == 0 || t->next->countdownMs >= t->countdownMs)
  30900. && (t->previous == 0 || t->previous->countdownMs <= t->countdownMs));
  30901. notify();
  30902. }
  30903. void removeTimer (Timer* const t) throw()
  30904. {
  30905. #if JUCE_DEBUG
  30906. Timer* tt = firstTimer;
  30907. bool found = false;
  30908. while (tt != 0)
  30909. {
  30910. if (tt == t)
  30911. {
  30912. found = true;
  30913. break;
  30914. }
  30915. tt = tt->next;
  30916. }
  30917. // trying to remove a timer that's not here - shouldn't get to this point,
  30918. // so if you get this assertion, let me know!
  30919. jassert (found);
  30920. #endif
  30921. if (t->previous != 0)
  30922. {
  30923. jassert (firstTimer != t);
  30924. t->previous->next = t->next;
  30925. }
  30926. else
  30927. {
  30928. jassert (firstTimer == t);
  30929. firstTimer = t->next;
  30930. }
  30931. if (t->next != 0)
  30932. t->next->previous = t->previous;
  30933. t->next = 0;
  30934. t->previous = 0;
  30935. }
  30936. void decrementAllCounters (const int numMillisecs) const
  30937. {
  30938. Timer* t = firstTimer;
  30939. while (t != 0)
  30940. {
  30941. t->countdownMs -= numMillisecs;
  30942. t = t->next;
  30943. }
  30944. }
  30945. void handleAsyncUpdate()
  30946. {
  30947. startThread (7);
  30948. }
  30949. InternalTimerThread (const InternalTimerThread&);
  30950. InternalTimerThread& operator= (const InternalTimerThread&);
  30951. };
  30952. InternalTimerThread* InternalTimerThread::instance = 0;
  30953. CriticalSection InternalTimerThread::lock;
  30954. void juce_callAnyTimersSynchronously()
  30955. {
  30956. InternalTimerThread::callAnyTimersSynchronously();
  30957. }
  30958. #if JUCE_DEBUG
  30959. static SortedSet <Timer*> activeTimers;
  30960. #endif
  30961. Timer::Timer() throw()
  30962. : countdownMs (0),
  30963. periodMs (0),
  30964. previous (0),
  30965. next (0)
  30966. {
  30967. #if JUCE_DEBUG
  30968. activeTimers.add (this);
  30969. #endif
  30970. }
  30971. Timer::Timer (const Timer&) throw()
  30972. : countdownMs (0),
  30973. periodMs (0),
  30974. previous (0),
  30975. next (0)
  30976. {
  30977. #if JUCE_DEBUG
  30978. activeTimers.add (this);
  30979. #endif
  30980. }
  30981. Timer::~Timer()
  30982. {
  30983. stopTimer();
  30984. #if JUCE_DEBUG
  30985. activeTimers.removeValue (this);
  30986. #endif
  30987. }
  30988. void Timer::startTimer (const int interval) throw()
  30989. {
  30990. const ScopedLock sl (InternalTimerThread::lock);
  30991. #if JUCE_DEBUG
  30992. // this isn't a valid object! Your timer might be a dangling pointer or something..
  30993. jassert (activeTimers.contains (this));
  30994. #endif
  30995. if (periodMs == 0)
  30996. {
  30997. countdownMs = interval;
  30998. periodMs = jmax (1, interval);
  30999. InternalTimerThread::add (this);
  31000. }
  31001. else
  31002. {
  31003. InternalTimerThread::resetCounter (this, interval);
  31004. }
  31005. }
  31006. void Timer::stopTimer() throw()
  31007. {
  31008. const ScopedLock sl (InternalTimerThread::lock);
  31009. #if JUCE_DEBUG
  31010. // this isn't a valid object! Your timer might be a dangling pointer or something..
  31011. jassert (activeTimers.contains (this));
  31012. #endif
  31013. if (periodMs > 0)
  31014. {
  31015. InternalTimerThread::remove (this);
  31016. periodMs = 0;
  31017. }
  31018. }
  31019. END_JUCE_NAMESPACE
  31020. /*** End of inlined file: juce_Timer.cpp ***/
  31021. #endif
  31022. #if JUCE_BUILD_GUI
  31023. /*** Start of inlined file: juce_Component.cpp ***/
  31024. BEGIN_JUCE_NAMESPACE
  31025. Component* Component::currentlyFocusedComponent = 0;
  31026. static Array <Component*> modalComponentStack, modalComponentReturnValueKeys;
  31027. static Array <int> modalReturnValues;
  31028. enum ComponentMessageNumbers
  31029. {
  31030. customCommandMessage = 0x7fff0001,
  31031. exitModalStateMessage = 0x7fff0002
  31032. };
  31033. #define checkMessageManagerIsLocked jassert (MessageManager::getInstance()->currentThreadHasLockedMessageManager());
  31034. static uint32 nextComponentUID = 0;
  31035. Component::Component()
  31036. : parentComponent_ (0),
  31037. componentUID (++nextComponentUID),
  31038. numDeepMouseListeners (0),
  31039. lookAndFeel_ (0),
  31040. effect_ (0),
  31041. bufferedImage_ (0),
  31042. mouseListeners_ (0),
  31043. keyListeners_ (0),
  31044. componentFlags_ (0)
  31045. {
  31046. }
  31047. Component::Component (const String& name)
  31048. : componentName_ (name),
  31049. parentComponent_ (0),
  31050. componentUID (++nextComponentUID),
  31051. numDeepMouseListeners (0),
  31052. lookAndFeel_ (0),
  31053. effect_ (0),
  31054. bufferedImage_ (0),
  31055. mouseListeners_ (0),
  31056. keyListeners_ (0),
  31057. componentFlags_ (0)
  31058. {
  31059. }
  31060. Component::~Component()
  31061. {
  31062. componentListeners.call (&ComponentListener::componentBeingDeleted, *this);
  31063. if (parentComponent_ != 0)
  31064. {
  31065. parentComponent_->removeChildComponent (this);
  31066. }
  31067. else if ((currentlyFocusedComponent == this)
  31068. || isParentOf (currentlyFocusedComponent))
  31069. {
  31070. giveAwayFocus();
  31071. }
  31072. if (flags.hasHeavyweightPeerFlag)
  31073. removeFromDesktop();
  31074. modalComponentStack.removeValue (this);
  31075. for (int i = childComponentList_.size(); --i >= 0;)
  31076. childComponentList_.getUnchecked(i)->parentComponent_ = 0;
  31077. delete bufferedImage_;
  31078. delete mouseListeners_;
  31079. delete keyListeners_;
  31080. }
  31081. void Component::setName (const String& name)
  31082. {
  31083. // if component methods are being called from threads other than the message
  31084. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  31085. checkMessageManagerIsLocked
  31086. if (componentName_ != name)
  31087. {
  31088. componentName_ = name;
  31089. if (flags.hasHeavyweightPeerFlag)
  31090. {
  31091. ComponentPeer* const peer = getPeer();
  31092. jassert (peer != 0);
  31093. if (peer != 0)
  31094. peer->setTitle (name);
  31095. }
  31096. BailOutChecker checker (this);
  31097. componentListeners.callChecked (checker, &ComponentListener::componentNameChanged, *this);
  31098. }
  31099. }
  31100. void Component::setVisible (bool shouldBeVisible)
  31101. {
  31102. if (flags.visibleFlag != shouldBeVisible)
  31103. {
  31104. // if component methods are being called from threads other than the message
  31105. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  31106. checkMessageManagerIsLocked
  31107. SafePointer<Component> safePointer (this);
  31108. flags.visibleFlag = shouldBeVisible;
  31109. internalRepaint (0, 0, getWidth(), getHeight());
  31110. sendFakeMouseMove();
  31111. if (! shouldBeVisible)
  31112. {
  31113. if (currentlyFocusedComponent == this
  31114. || isParentOf (currentlyFocusedComponent))
  31115. {
  31116. if (parentComponent_ != 0)
  31117. parentComponent_->grabKeyboardFocus();
  31118. else
  31119. giveAwayFocus();
  31120. }
  31121. }
  31122. if (safePointer != 0)
  31123. {
  31124. sendVisibilityChangeMessage();
  31125. if (safePointer != 0 && flags.hasHeavyweightPeerFlag)
  31126. {
  31127. ComponentPeer* const peer = getPeer();
  31128. jassert (peer != 0);
  31129. if (peer != 0)
  31130. {
  31131. peer->setVisible (shouldBeVisible);
  31132. internalHierarchyChanged();
  31133. }
  31134. }
  31135. }
  31136. }
  31137. }
  31138. void Component::visibilityChanged()
  31139. {
  31140. }
  31141. void Component::sendVisibilityChangeMessage()
  31142. {
  31143. BailOutChecker checker (this);
  31144. visibilityChanged();
  31145. if (! checker.shouldBailOut())
  31146. componentListeners.callChecked (checker, &ComponentListener::componentVisibilityChanged, *this);
  31147. }
  31148. bool Component::isShowing() const
  31149. {
  31150. if (flags.visibleFlag)
  31151. {
  31152. if (parentComponent_ != 0)
  31153. {
  31154. return parentComponent_->isShowing();
  31155. }
  31156. else
  31157. {
  31158. const ComponentPeer* const peer = getPeer();
  31159. return peer != 0 && ! peer->isMinimised();
  31160. }
  31161. }
  31162. return false;
  31163. }
  31164. class FadeOutProxyComponent : public Component,
  31165. public Timer
  31166. {
  31167. public:
  31168. FadeOutProxyComponent (Component* comp,
  31169. const int fadeLengthMs,
  31170. const int deltaXToMove,
  31171. const int deltaYToMove,
  31172. const float scaleFactorAtEnd)
  31173. : lastTime (0),
  31174. alpha (1.0f),
  31175. scale (1.0f)
  31176. {
  31177. image = comp->createComponentSnapshot (comp->getLocalBounds());
  31178. setBounds (comp->getBounds());
  31179. comp->getParentComponent()->addAndMakeVisible (this);
  31180. toBehind (comp);
  31181. alphaChangePerMs = -1.0f / (float)fadeLengthMs;
  31182. centreX = comp->getX() + comp->getWidth() * 0.5f;
  31183. xChangePerMs = deltaXToMove / (float)fadeLengthMs;
  31184. centreY = comp->getY() + comp->getHeight() * 0.5f;
  31185. yChangePerMs = deltaYToMove / (float)fadeLengthMs;
  31186. scaleChangePerMs = (scaleFactorAtEnd - 1.0f) / (float)fadeLengthMs;
  31187. setInterceptsMouseClicks (false, false);
  31188. // 30 fps is enough for a fade, but we need a higher rate if it's moving as well..
  31189. startTimer (1000 / ((deltaXToMove == 0 && deltaYToMove == 0) ? 30 : 50));
  31190. }
  31191. ~FadeOutProxyComponent()
  31192. {
  31193. delete image;
  31194. }
  31195. void paint (Graphics& g)
  31196. {
  31197. g.setOpacity (alpha);
  31198. g.drawImage (image,
  31199. 0, 0, getWidth(), getHeight(),
  31200. 0, 0, image->getWidth(), image->getHeight());
  31201. }
  31202. void timerCallback()
  31203. {
  31204. const uint32 now = Time::getMillisecondCounter();
  31205. if (lastTime == 0)
  31206. lastTime = now;
  31207. const int msPassed = (now > lastTime) ? now - lastTime : 0;
  31208. lastTime = now;
  31209. alpha += alphaChangePerMs * msPassed;
  31210. if (alpha > 0)
  31211. {
  31212. if (xChangePerMs != 0.0f || yChangePerMs != 0.0f || scaleChangePerMs != 0.0f)
  31213. {
  31214. centreX += xChangePerMs * msPassed;
  31215. centreY += yChangePerMs * msPassed;
  31216. scale += scaleChangePerMs * msPassed;
  31217. const int w = roundToInt (image->getWidth() * scale);
  31218. const int h = roundToInt (image->getHeight() * scale);
  31219. setBounds (roundToInt (centreX) - w / 2,
  31220. roundToInt (centreY) - h / 2,
  31221. w, h);
  31222. }
  31223. repaint();
  31224. }
  31225. else
  31226. {
  31227. delete this;
  31228. }
  31229. }
  31230. juce_UseDebuggingNewOperator
  31231. private:
  31232. Image* image;
  31233. uint32 lastTime;
  31234. float alpha, alphaChangePerMs;
  31235. float centreX, xChangePerMs;
  31236. float centreY, yChangePerMs;
  31237. float scale, scaleChangePerMs;
  31238. FadeOutProxyComponent (const FadeOutProxyComponent&);
  31239. FadeOutProxyComponent& operator= (const FadeOutProxyComponent&);
  31240. };
  31241. void Component::fadeOutComponent (const int millisecondsToFade,
  31242. const int deltaXToMove,
  31243. const int deltaYToMove,
  31244. const float scaleFactorAtEnd)
  31245. {
  31246. //xxx won't work for comps without parents
  31247. if (isShowing() && millisecondsToFade > 0)
  31248. new FadeOutProxyComponent (this, millisecondsToFade,
  31249. deltaXToMove, deltaYToMove, scaleFactorAtEnd);
  31250. setVisible (false);
  31251. }
  31252. bool Component::isValidComponent() const
  31253. {
  31254. return (this != 0) && isValidMessageListener();
  31255. }
  31256. void* Component::getWindowHandle() const
  31257. {
  31258. const ComponentPeer* const peer = getPeer();
  31259. if (peer != 0)
  31260. return peer->getNativeHandle();
  31261. return 0;
  31262. }
  31263. void Component::addToDesktop (int styleWanted, void* nativeWindowToAttachTo)
  31264. {
  31265. // if component methods are being called from threads other than the message
  31266. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  31267. checkMessageManagerIsLocked
  31268. if (isOpaque())
  31269. styleWanted &= ~ComponentPeer::windowIsSemiTransparent;
  31270. else
  31271. styleWanted |= ComponentPeer::windowIsSemiTransparent;
  31272. int currentStyleFlags = 0;
  31273. // don't use getPeer(), so that we only get the peer that's specifically
  31274. // for this comp, and not for one of its parents.
  31275. ComponentPeer* peer = ComponentPeer::getPeerFor (this);
  31276. if (peer != 0)
  31277. currentStyleFlags = peer->getStyleFlags();
  31278. if (styleWanted != currentStyleFlags || ! flags.hasHeavyweightPeerFlag)
  31279. {
  31280. SafePointer<Component> safePointer (this);
  31281. #if JUCE_LINUX
  31282. // it's wise to give the component a non-zero size before
  31283. // putting it on the desktop, as X windows get confused by this, and
  31284. // a (1, 1) minimum size is enforced here.
  31285. setSize (jmax (1, getWidth()),
  31286. jmax (1, getHeight()));
  31287. #endif
  31288. const Point<int> topLeft (relativePositionToGlobal (Point<int> (0, 0)));
  31289. bool wasFullscreen = false;
  31290. bool wasMinimised = false;
  31291. ComponentBoundsConstrainer* currentConstainer = 0;
  31292. Rectangle<int> oldNonFullScreenBounds;
  31293. if (peer != 0)
  31294. {
  31295. wasFullscreen = peer->isFullScreen();
  31296. wasMinimised = peer->isMinimised();
  31297. currentConstainer = peer->getConstrainer();
  31298. oldNonFullScreenBounds = peer->getNonFullScreenBounds();
  31299. removeFromDesktop();
  31300. setTopLeftPosition (topLeft.getX(), topLeft.getY());
  31301. }
  31302. if (parentComponent_ != 0)
  31303. parentComponent_->removeChildComponent (this);
  31304. if (safePointer != 0)
  31305. {
  31306. flags.hasHeavyweightPeerFlag = true;
  31307. peer = createNewPeer (styleWanted, nativeWindowToAttachTo);
  31308. Desktop::getInstance().addDesktopComponent (this);
  31309. bounds_.setPosition (topLeft);
  31310. peer->setBounds (topLeft.getX(), topLeft.getY(), getWidth(), getHeight(), false);
  31311. peer->setVisible (isVisible());
  31312. if (wasFullscreen)
  31313. {
  31314. peer->setFullScreen (true);
  31315. peer->setNonFullScreenBounds (oldNonFullScreenBounds);
  31316. }
  31317. if (wasMinimised)
  31318. peer->setMinimised (true);
  31319. if (isAlwaysOnTop())
  31320. peer->setAlwaysOnTop (true);
  31321. peer->setConstrainer (currentConstainer);
  31322. repaint();
  31323. }
  31324. internalHierarchyChanged();
  31325. }
  31326. }
  31327. void Component::removeFromDesktop()
  31328. {
  31329. // if component methods are being called from threads other than the message
  31330. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  31331. checkMessageManagerIsLocked
  31332. if (flags.hasHeavyweightPeerFlag)
  31333. {
  31334. ComponentPeer* const peer = ComponentPeer::getPeerFor (this);
  31335. flags.hasHeavyweightPeerFlag = false;
  31336. jassert (peer != 0);
  31337. delete peer;
  31338. Desktop::getInstance().removeDesktopComponent (this);
  31339. }
  31340. }
  31341. bool Component::isOnDesktop() const throw()
  31342. {
  31343. return flags.hasHeavyweightPeerFlag;
  31344. }
  31345. void Component::userTriedToCloseWindow()
  31346. {
  31347. /* This means that the user's trying to get rid of your window with the 'close window' system
  31348. menu option (on windows) or possibly the task manager - you should really handle this
  31349. and delete or hide your component in an appropriate way.
  31350. If you want to ignore the event and don't want to trigger this assertion, just override
  31351. this method and do nothing.
  31352. */
  31353. jassertfalse
  31354. }
  31355. void Component::minimisationStateChanged (bool)
  31356. {
  31357. }
  31358. void Component::setOpaque (const bool shouldBeOpaque)
  31359. {
  31360. if (shouldBeOpaque != flags.opaqueFlag)
  31361. {
  31362. flags.opaqueFlag = shouldBeOpaque;
  31363. if (flags.hasHeavyweightPeerFlag)
  31364. {
  31365. const ComponentPeer* const peer = ComponentPeer::getPeerFor (this);
  31366. if (peer != 0)
  31367. {
  31368. // to make it recreate the heavyweight window
  31369. addToDesktop (peer->getStyleFlags());
  31370. }
  31371. }
  31372. repaint();
  31373. }
  31374. }
  31375. bool Component::isOpaque() const throw()
  31376. {
  31377. return flags.opaqueFlag;
  31378. }
  31379. void Component::setBufferedToImage (const bool shouldBeBuffered)
  31380. {
  31381. if (shouldBeBuffered != flags.bufferToImageFlag)
  31382. {
  31383. deleteAndZero (bufferedImage_);
  31384. flags.bufferToImageFlag = shouldBeBuffered;
  31385. }
  31386. }
  31387. void Component::toFront (const bool setAsForeground)
  31388. {
  31389. // if component methods are being called from threads other than the message
  31390. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  31391. checkMessageManagerIsLocked
  31392. if (flags.hasHeavyweightPeerFlag)
  31393. {
  31394. ComponentPeer* const peer = getPeer();
  31395. if (peer != 0)
  31396. {
  31397. peer->toFront (setAsForeground);
  31398. if (setAsForeground && ! hasKeyboardFocus (true))
  31399. grabKeyboardFocus();
  31400. }
  31401. }
  31402. else if (parentComponent_ != 0)
  31403. {
  31404. Array<Component*>& childList = parentComponent_->childComponentList_;
  31405. if (childList.getLast() != this)
  31406. {
  31407. const int index = childList.indexOf (this);
  31408. if (index >= 0)
  31409. {
  31410. int insertIndex = -1;
  31411. if (! flags.alwaysOnTopFlag)
  31412. {
  31413. insertIndex = childList.size() - 1;
  31414. while (insertIndex > 0 && childList.getUnchecked (insertIndex)->isAlwaysOnTop())
  31415. --insertIndex;
  31416. }
  31417. if (index != insertIndex)
  31418. {
  31419. childList.move (index, insertIndex);
  31420. sendFakeMouseMove();
  31421. repaintParent();
  31422. }
  31423. }
  31424. }
  31425. if (setAsForeground)
  31426. {
  31427. internalBroughtToFront();
  31428. grabKeyboardFocus();
  31429. }
  31430. }
  31431. }
  31432. void Component::toBehind (Component* const other)
  31433. {
  31434. if (other != 0 && other != this)
  31435. {
  31436. // the two components must belong to the same parent..
  31437. jassert (parentComponent_ == other->parentComponent_);
  31438. if (parentComponent_ != 0)
  31439. {
  31440. Array<Component*>& childList = parentComponent_->childComponentList_;
  31441. const int index = childList.indexOf (this);
  31442. if (index >= 0 && childList [index + 1] != other)
  31443. {
  31444. int otherIndex = childList.indexOf (other);
  31445. if (otherIndex >= 0)
  31446. {
  31447. if (index < otherIndex)
  31448. --otherIndex;
  31449. childList.move (index, otherIndex);
  31450. sendFakeMouseMove();
  31451. repaintParent();
  31452. }
  31453. }
  31454. }
  31455. else if (isOnDesktop())
  31456. {
  31457. jassert (other->isOnDesktop());
  31458. if (other->isOnDesktop())
  31459. {
  31460. ComponentPeer* const us = getPeer();
  31461. ComponentPeer* const them = other->getPeer();
  31462. jassert (us != 0 && them != 0);
  31463. if (us != 0 && them != 0)
  31464. us->toBehind (them);
  31465. }
  31466. }
  31467. }
  31468. }
  31469. void Component::toBack()
  31470. {
  31471. Array<Component*>& childList = parentComponent_->childComponentList_;
  31472. if (isOnDesktop())
  31473. {
  31474. jassertfalse //xxx need to add this to native window
  31475. }
  31476. else if (parentComponent_ != 0 && childList.getFirst() != this)
  31477. {
  31478. const int index = childList.indexOf (this);
  31479. if (index > 0)
  31480. {
  31481. int insertIndex = 0;
  31482. if (flags.alwaysOnTopFlag)
  31483. {
  31484. while (insertIndex < childList.size()
  31485. && ! childList.getUnchecked (insertIndex)->isAlwaysOnTop())
  31486. {
  31487. ++insertIndex;
  31488. }
  31489. }
  31490. if (index != insertIndex)
  31491. {
  31492. childList.move (index, insertIndex);
  31493. sendFakeMouseMove();
  31494. repaintParent();
  31495. }
  31496. }
  31497. }
  31498. }
  31499. void Component::setAlwaysOnTop (const bool shouldStayOnTop)
  31500. {
  31501. if (shouldStayOnTop != flags.alwaysOnTopFlag)
  31502. {
  31503. flags.alwaysOnTopFlag = shouldStayOnTop;
  31504. if (isOnDesktop())
  31505. {
  31506. ComponentPeer* const peer = getPeer();
  31507. jassert (peer != 0);
  31508. if (peer != 0)
  31509. {
  31510. if (! peer->setAlwaysOnTop (shouldStayOnTop))
  31511. {
  31512. // some kinds of peer can't change their always-on-top status, so
  31513. // for these, we'll need to create a new window
  31514. const int oldFlags = peer->getStyleFlags();
  31515. removeFromDesktop();
  31516. addToDesktop (oldFlags);
  31517. }
  31518. }
  31519. }
  31520. if (shouldStayOnTop)
  31521. toFront (false);
  31522. internalHierarchyChanged();
  31523. }
  31524. }
  31525. bool Component::isAlwaysOnTop() const throw()
  31526. {
  31527. return flags.alwaysOnTopFlag;
  31528. }
  31529. int Component::proportionOfWidth (const float proportion) const throw()
  31530. {
  31531. return roundToInt (proportion * bounds_.getWidth());
  31532. }
  31533. int Component::proportionOfHeight (const float proportion) const throw()
  31534. {
  31535. return roundToInt (proportion * bounds_.getHeight());
  31536. }
  31537. int Component::getParentWidth() const throw()
  31538. {
  31539. return (parentComponent_ != 0) ? parentComponent_->getWidth()
  31540. : getParentMonitorArea().getWidth();
  31541. }
  31542. int Component::getParentHeight() const throw()
  31543. {
  31544. return (parentComponent_ != 0) ? parentComponent_->getHeight()
  31545. : getParentMonitorArea().getHeight();
  31546. }
  31547. int Component::getScreenX() const
  31548. {
  31549. return getScreenPosition().getX();
  31550. }
  31551. int Component::getScreenY() const
  31552. {
  31553. return getScreenPosition().getY();
  31554. }
  31555. const Point<int> Component::getScreenPosition() const
  31556. {
  31557. return (parentComponent_ != 0) ? parentComponent_->getScreenPosition() + getPosition()
  31558. : (flags.hasHeavyweightPeerFlag ? getPeer()->getScreenPosition()
  31559. : getPosition());
  31560. }
  31561. const Rectangle<int> Component::getScreenBounds() const
  31562. {
  31563. return bounds_.withPosition (getScreenPosition());
  31564. }
  31565. const Point<int> Component::relativePositionToGlobal (const Point<int>& relativePosition) const
  31566. {
  31567. const Component* c = this;
  31568. Point<int> p (relativePosition);
  31569. do
  31570. {
  31571. if (c->flags.hasHeavyweightPeerFlag)
  31572. return c->getPeer()->relativePositionToGlobal (p);
  31573. p += c->getPosition();
  31574. c = c->parentComponent_;
  31575. }
  31576. while (c != 0);
  31577. return p;
  31578. }
  31579. const Point<int> Component::globalPositionToRelative (const Point<int>& screenPosition) const
  31580. {
  31581. if (flags.hasHeavyweightPeerFlag)
  31582. {
  31583. return getPeer()->globalPositionToRelative (screenPosition);
  31584. }
  31585. else
  31586. {
  31587. if (parentComponent_ != 0)
  31588. return parentComponent_->globalPositionToRelative (screenPosition) - getPosition();
  31589. return screenPosition - getPosition();
  31590. }
  31591. }
  31592. const Point<int> Component::relativePositionToOtherComponent (const Component* const targetComponent, const Point<int>& positionRelativeToThis) const
  31593. {
  31594. Point<int> p (positionRelativeToThis);
  31595. if (targetComponent != 0)
  31596. {
  31597. const Component* c = this;
  31598. do
  31599. {
  31600. if (c == targetComponent)
  31601. return p;
  31602. if (c->flags.hasHeavyweightPeerFlag)
  31603. {
  31604. p = c->getPeer()->relativePositionToGlobal (p);
  31605. break;
  31606. }
  31607. p += c->getPosition();
  31608. c = c->parentComponent_;
  31609. }
  31610. while (c != 0);
  31611. p = targetComponent->globalPositionToRelative (p);
  31612. }
  31613. return p;
  31614. }
  31615. void Component::setBounds (int x, int y, int w, int h)
  31616. {
  31617. // if component methods are being called from threads other than the message
  31618. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  31619. checkMessageManagerIsLocked
  31620. if (w < 0) w = 0;
  31621. if (h < 0) h = 0;
  31622. const bool wasResized = (getWidth() != w || getHeight() != h);
  31623. const bool wasMoved = (getX() != x || getY() != y);
  31624. #if JUCE_DEBUG
  31625. // It's a very bad idea to try to resize a window during its paint() method!
  31626. jassert (! (flags.isInsidePaintCall && wasResized && isOnDesktop()));
  31627. #endif
  31628. if (wasMoved || wasResized)
  31629. {
  31630. if (flags.visibleFlag)
  31631. {
  31632. // send a fake mouse move to trigger enter/exit messages if needed..
  31633. sendFakeMouseMove();
  31634. if (! flags.hasHeavyweightPeerFlag)
  31635. repaintParent();
  31636. }
  31637. bounds_.setBounds (x, y, w, h);
  31638. if (wasResized)
  31639. repaint();
  31640. else if (! flags.hasHeavyweightPeerFlag)
  31641. repaintParent();
  31642. if (flags.hasHeavyweightPeerFlag)
  31643. {
  31644. ComponentPeer* const peer = getPeer();
  31645. if (peer != 0)
  31646. {
  31647. if (wasMoved && wasResized)
  31648. peer->setBounds (getX(), getY(), getWidth(), getHeight(), false);
  31649. else if (wasMoved)
  31650. peer->setPosition (getX(), getY());
  31651. else if (wasResized)
  31652. peer->setSize (getWidth(), getHeight());
  31653. }
  31654. }
  31655. sendMovedResizedMessages (wasMoved, wasResized);
  31656. }
  31657. }
  31658. void Component::sendMovedResizedMessages (const bool wasMoved, const bool wasResized)
  31659. {
  31660. JUCE_TRY
  31661. {
  31662. if (wasMoved)
  31663. moved();
  31664. if (wasResized)
  31665. {
  31666. resized();
  31667. for (int i = childComponentList_.size(); --i >= 0;)
  31668. {
  31669. childComponentList_.getUnchecked(i)->parentSizeChanged();
  31670. i = jmin (i, childComponentList_.size());
  31671. }
  31672. }
  31673. BailOutChecker checker (this);
  31674. if (parentComponent_ != 0)
  31675. parentComponent_->childBoundsChanged (this);
  31676. if (! checker.shouldBailOut())
  31677. componentListeners.callChecked (checker, &ComponentListener::componentMovedOrResized,
  31678. *this, wasMoved, wasResized);
  31679. }
  31680. JUCE_CATCH_EXCEPTION
  31681. }
  31682. void Component::setSize (const int w, const int h)
  31683. {
  31684. setBounds (getX(), getY(), w, h);
  31685. }
  31686. void Component::setTopLeftPosition (const int x, const int y)
  31687. {
  31688. setBounds (x, y, getWidth(), getHeight());
  31689. }
  31690. void Component::setTopRightPosition (const int x, const int y)
  31691. {
  31692. setTopLeftPosition (x - getWidth(), y);
  31693. }
  31694. void Component::setBounds (const Rectangle<int>& r)
  31695. {
  31696. setBounds (r.getX(),
  31697. r.getY(),
  31698. r.getWidth(),
  31699. r.getHeight());
  31700. }
  31701. void Component::setBoundsRelative (const float x, const float y,
  31702. const float w, const float h)
  31703. {
  31704. const int pw = getParentWidth();
  31705. const int ph = getParentHeight();
  31706. setBounds (roundToInt (x * pw),
  31707. roundToInt (y * ph),
  31708. roundToInt (w * pw),
  31709. roundToInt (h * ph));
  31710. }
  31711. void Component::setCentrePosition (const int x, const int y)
  31712. {
  31713. setTopLeftPosition (x - getWidth() / 2,
  31714. y - getHeight() / 2);
  31715. }
  31716. void Component::setCentreRelative (const float x, const float y)
  31717. {
  31718. setCentrePosition (roundToInt (getParentWidth() * x),
  31719. roundToInt (getParentHeight() * y));
  31720. }
  31721. void Component::centreWithSize (const int width, const int height)
  31722. {
  31723. setBounds ((getParentWidth() - width) / 2,
  31724. (getParentHeight() - height) / 2,
  31725. width,
  31726. height);
  31727. }
  31728. void Component::setBoundsInset (const BorderSize& borders)
  31729. {
  31730. setBounds (borders.getLeft(),
  31731. borders.getTop(),
  31732. getParentWidth() - (borders.getLeftAndRight()),
  31733. getParentHeight() - (borders.getTopAndBottom()));
  31734. }
  31735. void Component::setBoundsToFit (int x, int y, int width, int height,
  31736. const Justification& justification,
  31737. const bool onlyReduceInSize)
  31738. {
  31739. // it's no good calling this method unless both the component and
  31740. // target rectangle have a finite size.
  31741. jassert (getWidth() > 0 && getHeight() > 0 && width > 0 && height > 0);
  31742. if (getWidth() > 0 && getHeight() > 0
  31743. && width > 0 && height > 0)
  31744. {
  31745. int newW, newH;
  31746. if (onlyReduceInSize && getWidth() <= width && getHeight() <= height)
  31747. {
  31748. newW = getWidth();
  31749. newH = getHeight();
  31750. }
  31751. else
  31752. {
  31753. const double imageRatio = getHeight() / (double) getWidth();
  31754. const double targetRatio = height / (double) width;
  31755. if (imageRatio <= targetRatio)
  31756. {
  31757. newW = width;
  31758. newH = jmin (height, roundToInt (newW * imageRatio));
  31759. }
  31760. else
  31761. {
  31762. newH = height;
  31763. newW = jmin (width, roundToInt (newH / imageRatio));
  31764. }
  31765. }
  31766. if (newW > 0 && newH > 0)
  31767. {
  31768. int newX, newY;
  31769. justification.applyToRectangle (newX, newY, newW, newH,
  31770. x, y, width, height);
  31771. setBounds (newX, newY, newW, newH);
  31772. }
  31773. }
  31774. }
  31775. bool Component::hitTest (int x, int y)
  31776. {
  31777. if (! flags.ignoresMouseClicksFlag)
  31778. return true;
  31779. if (flags.allowChildMouseClicksFlag)
  31780. {
  31781. for (int i = getNumChildComponents(); --i >= 0;)
  31782. {
  31783. Component* const c = getChildComponent (i);
  31784. if (c->isVisible()
  31785. && c->bounds_.contains (x, y)
  31786. && c->hitTest (x - c->getX(),
  31787. y - c->getY()))
  31788. {
  31789. return true;
  31790. }
  31791. }
  31792. }
  31793. return false;
  31794. }
  31795. void Component::setInterceptsMouseClicks (const bool allowClicks,
  31796. const bool allowClicksOnChildComponents) throw()
  31797. {
  31798. flags.ignoresMouseClicksFlag = ! allowClicks;
  31799. flags.allowChildMouseClicksFlag = allowClicksOnChildComponents;
  31800. }
  31801. void Component::getInterceptsMouseClicks (bool& allowsClicksOnThisComponent,
  31802. bool& allowsClicksOnChildComponents) const throw()
  31803. {
  31804. allowsClicksOnThisComponent = ! flags.ignoresMouseClicksFlag;
  31805. allowsClicksOnChildComponents = flags.allowChildMouseClicksFlag;
  31806. }
  31807. bool Component::contains (const int x, const int y)
  31808. {
  31809. if (((unsigned int) x) < (unsigned int) getWidth()
  31810. && ((unsigned int) y) < (unsigned int) getHeight()
  31811. && hitTest (x, y))
  31812. {
  31813. if (parentComponent_ != 0)
  31814. {
  31815. return parentComponent_->contains (x + getX(),
  31816. y + getY());
  31817. }
  31818. else if (flags.hasHeavyweightPeerFlag)
  31819. {
  31820. const ComponentPeer* const peer = getPeer();
  31821. if (peer != 0)
  31822. return peer->contains (Point<int> (x, y), true);
  31823. }
  31824. }
  31825. return false;
  31826. }
  31827. bool Component::reallyContains (int x, int y, const bool returnTrueIfWithinAChild)
  31828. {
  31829. if (! contains (x, y))
  31830. return false;
  31831. Component* p = this;
  31832. while (p->parentComponent_ != 0)
  31833. {
  31834. x += p->getX();
  31835. y += p->getY();
  31836. p = p->parentComponent_;
  31837. }
  31838. const Component* const c = p->getComponentAt (x, y);
  31839. return (c == this) || (returnTrueIfWithinAChild && isParentOf (c));
  31840. }
  31841. Component* Component::getComponentAt (const Point<int>& position)
  31842. {
  31843. return getComponentAt (position.getX(), position.getY());
  31844. }
  31845. Component* Component::getComponentAt (const int x, const int y)
  31846. {
  31847. if (flags.visibleFlag
  31848. && ((unsigned int) x) < (unsigned int) getWidth()
  31849. && ((unsigned int) y) < (unsigned int) getHeight()
  31850. && hitTest (x, y))
  31851. {
  31852. for (int i = childComponentList_.size(); --i >= 0;)
  31853. {
  31854. Component* const child = childComponentList_.getUnchecked(i);
  31855. Component* const c = child->getComponentAt (x - child->getX(),
  31856. y - child->getY());
  31857. if (c != 0)
  31858. return c;
  31859. }
  31860. return this;
  31861. }
  31862. return 0;
  31863. }
  31864. void Component::addChildComponent (Component* const child, int zOrder)
  31865. {
  31866. // if component methods are being called from threads other than the message
  31867. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  31868. checkMessageManagerIsLocked
  31869. if (child != 0 && child->parentComponent_ != this)
  31870. {
  31871. if (child->parentComponent_ != 0)
  31872. child->parentComponent_->removeChildComponent (child);
  31873. else
  31874. child->removeFromDesktop();
  31875. child->parentComponent_ = this;
  31876. if (child->isVisible())
  31877. child->repaintParent();
  31878. if (! child->isAlwaysOnTop())
  31879. {
  31880. if (zOrder < 0 || zOrder > childComponentList_.size())
  31881. zOrder = childComponentList_.size();
  31882. while (zOrder > 0)
  31883. {
  31884. if (! childComponentList_.getUnchecked (zOrder - 1)->isAlwaysOnTop())
  31885. break;
  31886. --zOrder;
  31887. }
  31888. }
  31889. childComponentList_.insert (zOrder, child);
  31890. child->internalHierarchyChanged();
  31891. internalChildrenChanged();
  31892. }
  31893. }
  31894. void Component::addAndMakeVisible (Component* const child, int zOrder)
  31895. {
  31896. if (child != 0)
  31897. {
  31898. child->setVisible (true);
  31899. addChildComponent (child, zOrder);
  31900. }
  31901. }
  31902. void Component::removeChildComponent (Component* const child)
  31903. {
  31904. removeChildComponent (childComponentList_.indexOf (child));
  31905. }
  31906. Component* Component::removeChildComponent (const int index)
  31907. {
  31908. // if component methods are being called from threads other than the message
  31909. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  31910. checkMessageManagerIsLocked
  31911. Component* const child = childComponentList_ [index];
  31912. if (child != 0)
  31913. {
  31914. sendFakeMouseMove();
  31915. child->repaintParent();
  31916. childComponentList_.remove (index);
  31917. child->parentComponent_ = 0;
  31918. JUCE_TRY
  31919. {
  31920. if ((currentlyFocusedComponent == child)
  31921. || child->isParentOf (currentlyFocusedComponent))
  31922. {
  31923. // get rid first to force the grabKeyboardFocus to change to us.
  31924. giveAwayFocus();
  31925. grabKeyboardFocus();
  31926. }
  31927. }
  31928. #if JUCE_CATCH_UNHANDLED_EXCEPTIONS
  31929. catch (const std::exception& e)
  31930. {
  31931. currentlyFocusedComponent = 0;
  31932. Desktop::getInstance().triggerFocusCallback();
  31933. JUCEApplication::sendUnhandledException (&e, __FILE__, __LINE__);
  31934. }
  31935. catch (...)
  31936. {
  31937. currentlyFocusedComponent = 0;
  31938. Desktop::getInstance().triggerFocusCallback();
  31939. JUCEApplication::sendUnhandledException (0, __FILE__, __LINE__);
  31940. }
  31941. #endif
  31942. child->internalHierarchyChanged();
  31943. internalChildrenChanged();
  31944. }
  31945. return child;
  31946. }
  31947. void Component::removeAllChildren()
  31948. {
  31949. while (childComponentList_.size() > 0)
  31950. removeChildComponent (childComponentList_.size() - 1);
  31951. }
  31952. void Component::deleteAllChildren()
  31953. {
  31954. while (childComponentList_.size() > 0)
  31955. delete (removeChildComponent (childComponentList_.size() - 1));
  31956. }
  31957. int Component::getNumChildComponents() const throw()
  31958. {
  31959. return childComponentList_.size();
  31960. }
  31961. Component* Component::getChildComponent (const int index) const throw()
  31962. {
  31963. return childComponentList_ [index];
  31964. }
  31965. int Component::getIndexOfChildComponent (const Component* const child) const throw()
  31966. {
  31967. return childComponentList_.indexOf (const_cast <Component*> (child));
  31968. }
  31969. Component* Component::getTopLevelComponent() const throw()
  31970. {
  31971. const Component* comp = this;
  31972. while (comp->parentComponent_ != 0)
  31973. comp = comp->parentComponent_;
  31974. return const_cast <Component*> (comp);
  31975. }
  31976. bool Component::isParentOf (const Component* possibleChild) const throw()
  31977. {
  31978. if (! possibleChild->isValidComponent())
  31979. {
  31980. jassert (possibleChild == 0);
  31981. return false;
  31982. }
  31983. while (possibleChild != 0)
  31984. {
  31985. possibleChild = possibleChild->parentComponent_;
  31986. if (possibleChild == this)
  31987. return true;
  31988. }
  31989. return false;
  31990. }
  31991. void Component::parentHierarchyChanged()
  31992. {
  31993. }
  31994. void Component::childrenChanged()
  31995. {
  31996. }
  31997. void Component::internalChildrenChanged()
  31998. {
  31999. if (componentListeners.isEmpty())
  32000. {
  32001. childrenChanged();
  32002. }
  32003. else
  32004. {
  32005. BailOutChecker checker (this);
  32006. childrenChanged();
  32007. if (! checker.shouldBailOut())
  32008. componentListeners.callChecked (checker, &ComponentListener::componentChildrenChanged, *this);
  32009. }
  32010. }
  32011. void Component::internalHierarchyChanged()
  32012. {
  32013. BailOutChecker checker (this);
  32014. parentHierarchyChanged();
  32015. if (checker.shouldBailOut())
  32016. return;
  32017. componentListeners.callChecked (checker, &ComponentListener::componentParentHierarchyChanged, *this);
  32018. if (checker.shouldBailOut())
  32019. return;
  32020. for (int i = childComponentList_.size(); --i >= 0;)
  32021. {
  32022. childComponentList_.getUnchecked (i)->internalHierarchyChanged();
  32023. if (checker.shouldBailOut())
  32024. {
  32025. // you really shouldn't delete the parent component during a callback telling you
  32026. // that it's changed..
  32027. jassertfalse;
  32028. return;
  32029. }
  32030. i = jmin (i, childComponentList_.size());
  32031. }
  32032. }
  32033. void* Component::runModalLoopCallback (void* userData)
  32034. {
  32035. return (void*) (pointer_sized_int) static_cast <Component*> (userData)->runModalLoop();
  32036. }
  32037. int Component::runModalLoop()
  32038. {
  32039. if (! MessageManager::getInstance()->isThisTheMessageThread())
  32040. {
  32041. // use a callback so this can be called from non-gui threads
  32042. return (int) (pointer_sized_int)
  32043. MessageManager::getInstance()
  32044. ->callFunctionOnMessageThread (&runModalLoopCallback, this);
  32045. }
  32046. SafePointer<Component> prevFocused (getCurrentlyFocusedComponent());
  32047. if (! isCurrentlyModal())
  32048. enterModalState();
  32049. JUCE_TRY
  32050. {
  32051. while (flags.currentlyModalFlag && flags.visibleFlag)
  32052. {
  32053. if (! MessageManager::getInstance()->runDispatchLoopUntil (20))
  32054. break;
  32055. // check whether this component was deleted during the last message
  32056. if (! isValidMessageListener())
  32057. break;
  32058. }
  32059. }
  32060. #if JUCE_CATCH_UNHANDLED_EXCEPTIONS
  32061. catch (const std::exception& e)
  32062. {
  32063. JUCEApplication::sendUnhandledException (&e, __FILE__, __LINE__);
  32064. return 0;
  32065. }
  32066. catch (...)
  32067. {
  32068. JUCEApplication::sendUnhandledException (0, __FILE__, __LINE__);
  32069. return 0;
  32070. }
  32071. #endif
  32072. const int modalIndex = modalComponentReturnValueKeys.indexOf (this);
  32073. int returnValue = 0;
  32074. if (modalIndex >= 0)
  32075. {
  32076. modalComponentReturnValueKeys.remove (modalIndex);
  32077. returnValue = modalReturnValues.remove (modalIndex);
  32078. }
  32079. modalComponentStack.removeValue (this);
  32080. if (prevFocused != 0)
  32081. prevFocused->grabKeyboardFocus();
  32082. return returnValue;
  32083. }
  32084. void Component::enterModalState (const bool takeKeyboardFocus_)
  32085. {
  32086. // if component methods are being called from threads other than the message
  32087. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  32088. checkMessageManagerIsLocked
  32089. // Check for an attempt to make a component modal when it already is!
  32090. // This can cause nasty problems..
  32091. jassert (! flags.currentlyModalFlag);
  32092. if (! isCurrentlyModal())
  32093. {
  32094. modalComponentStack.add (this);
  32095. modalComponentReturnValueKeys.add (this);
  32096. modalReturnValues.add (0);
  32097. flags.currentlyModalFlag = true;
  32098. setVisible (true);
  32099. if (takeKeyboardFocus_)
  32100. grabKeyboardFocus();
  32101. }
  32102. }
  32103. void Component::exitModalState (const int returnValue)
  32104. {
  32105. if (isCurrentlyModal())
  32106. {
  32107. if (MessageManager::getInstance()->isThisTheMessageThread())
  32108. {
  32109. const int modalIndex = modalComponentReturnValueKeys.indexOf (this);
  32110. if (modalIndex >= 0)
  32111. {
  32112. modalReturnValues.set (modalIndex, returnValue);
  32113. }
  32114. else
  32115. {
  32116. modalComponentReturnValueKeys.add (this);
  32117. modalReturnValues.add (returnValue);
  32118. }
  32119. modalComponentStack.removeValue (this);
  32120. flags.currentlyModalFlag = false;
  32121. bringModalComponentToFront();
  32122. }
  32123. else
  32124. {
  32125. postMessage (new Message (exitModalStateMessage, returnValue, 0, 0));
  32126. }
  32127. }
  32128. }
  32129. bool Component::isCurrentlyModal() const throw()
  32130. {
  32131. return flags.currentlyModalFlag
  32132. && getCurrentlyModalComponent() == this;
  32133. }
  32134. bool Component::isCurrentlyBlockedByAnotherModalComponent() const
  32135. {
  32136. Component* const mc = getCurrentlyModalComponent();
  32137. return mc != 0
  32138. && mc != this
  32139. && (! mc->isParentOf (this))
  32140. && ! mc->canModalEventBeSentToComponent (this);
  32141. }
  32142. int JUCE_CALLTYPE Component::getNumCurrentlyModalComponents() throw()
  32143. {
  32144. return modalComponentStack.size();
  32145. }
  32146. Component* JUCE_CALLTYPE Component::getCurrentlyModalComponent (int index) throw()
  32147. {
  32148. Component* const c = static_cast <Component*> (modalComponentStack [modalComponentStack.size() - index - 1]);
  32149. return c->isValidComponent() ? c : 0;
  32150. }
  32151. void Component::bringModalComponentToFront()
  32152. {
  32153. ComponentPeer* lastOne = 0;
  32154. for (int i = 0; i < getNumCurrentlyModalComponents(); ++i)
  32155. {
  32156. Component* const c = getCurrentlyModalComponent (i);
  32157. if (c == 0)
  32158. break;
  32159. ComponentPeer* peer = c->getPeer();
  32160. if (peer != 0 && peer != lastOne)
  32161. {
  32162. if (lastOne == 0)
  32163. {
  32164. peer->toFront (true);
  32165. peer->grabFocus();
  32166. }
  32167. else
  32168. peer->toBehind (lastOne);
  32169. lastOne = peer;
  32170. }
  32171. }
  32172. }
  32173. void Component::setBroughtToFrontOnMouseClick (const bool shouldBeBroughtToFront) throw()
  32174. {
  32175. flags.bringToFrontOnClickFlag = shouldBeBroughtToFront;
  32176. }
  32177. bool Component::isBroughtToFrontOnMouseClick() const throw()
  32178. {
  32179. return flags.bringToFrontOnClickFlag;
  32180. }
  32181. void Component::setMouseCursor (const MouseCursor& cursor)
  32182. {
  32183. if (cursor_ != cursor)
  32184. {
  32185. cursor_ = cursor;
  32186. if (flags.visibleFlag)
  32187. updateMouseCursor();
  32188. }
  32189. }
  32190. const MouseCursor Component::getMouseCursor()
  32191. {
  32192. return cursor_;
  32193. }
  32194. void Component::updateMouseCursor() const
  32195. {
  32196. sendFakeMouseMove();
  32197. }
  32198. void Component::setRepaintsOnMouseActivity (const bool shouldRepaint) throw()
  32199. {
  32200. flags.repaintOnMouseActivityFlag = shouldRepaint;
  32201. }
  32202. void Component::repaintParent()
  32203. {
  32204. if (flags.visibleFlag)
  32205. internalRepaint (0, 0, getWidth(), getHeight());
  32206. }
  32207. void Component::repaint()
  32208. {
  32209. repaint (0, 0, getWidth(), getHeight());
  32210. }
  32211. void Component::repaint (const int x, const int y,
  32212. const int w, const int h)
  32213. {
  32214. deleteAndZero (bufferedImage_);
  32215. if (flags.visibleFlag)
  32216. internalRepaint (x, y, w, h);
  32217. }
  32218. void Component::internalRepaint (int x, int y, int w, int h)
  32219. {
  32220. // if component methods are being called from threads other than the message
  32221. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  32222. checkMessageManagerIsLocked
  32223. if (x < 0)
  32224. {
  32225. w += x;
  32226. x = 0;
  32227. }
  32228. if (x + w > getWidth())
  32229. w = getWidth() - x;
  32230. if (w > 0)
  32231. {
  32232. if (y < 0)
  32233. {
  32234. h += y;
  32235. y = 0;
  32236. }
  32237. if (y + h > getHeight())
  32238. h = getHeight() - y;
  32239. if (h > 0)
  32240. {
  32241. if (parentComponent_ != 0)
  32242. {
  32243. x += getX();
  32244. y += getY();
  32245. if (parentComponent_->flags.visibleFlag)
  32246. parentComponent_->internalRepaint (x, y, w, h);
  32247. }
  32248. else if (flags.hasHeavyweightPeerFlag)
  32249. {
  32250. ComponentPeer* const peer = getPeer();
  32251. if (peer != 0)
  32252. peer->repaint (x, y, w, h);
  32253. }
  32254. }
  32255. }
  32256. }
  32257. void Component::renderComponent (Graphics& g)
  32258. {
  32259. const Rectangle<int> clipBounds (g.getClipBounds());
  32260. g.saveState();
  32261. clipObscuredRegions (g, clipBounds, 0, 0);
  32262. if (! g.isClipEmpty())
  32263. {
  32264. if (flags.bufferToImageFlag)
  32265. {
  32266. if (bufferedImage_ == 0)
  32267. {
  32268. bufferedImage_ = Image::createNativeImage (flags.opaqueFlag ? Image::RGB : Image::ARGB,
  32269. getWidth(), getHeight(), ! flags.opaqueFlag);
  32270. Graphics imG (*bufferedImage_);
  32271. paint (imG);
  32272. }
  32273. g.setColour (Colours::black);
  32274. g.drawImageAt (bufferedImage_, 0, 0);
  32275. }
  32276. else
  32277. {
  32278. paint (g);
  32279. }
  32280. }
  32281. g.restoreState();
  32282. for (int i = 0; i < childComponentList_.size(); ++i)
  32283. {
  32284. Component* const child = childComponentList_.getUnchecked (i);
  32285. if (child->isVisible() && clipBounds.intersects (child->getBounds()))
  32286. {
  32287. g.saveState();
  32288. if (g.reduceClipRegion (child->getX(), child->getY(),
  32289. child->getWidth(), child->getHeight()))
  32290. {
  32291. for (int j = i + 1; j < childComponentList_.size(); ++j)
  32292. {
  32293. const Component* const sibling = childComponentList_.getUnchecked (j);
  32294. if (sibling->flags.opaqueFlag && sibling->isVisible())
  32295. g.excludeClipRegion (sibling->getBounds());
  32296. }
  32297. if (! g.isClipEmpty())
  32298. {
  32299. g.setOrigin (child->getX(), child->getY());
  32300. child->paintEntireComponent (g);
  32301. }
  32302. }
  32303. g.restoreState();
  32304. }
  32305. }
  32306. g.saveState();
  32307. paintOverChildren (g);
  32308. g.restoreState();
  32309. }
  32310. void Component::paintEntireComponent (Graphics& g)
  32311. {
  32312. jassert (! g.isClipEmpty());
  32313. #if JUCE_DEBUG
  32314. flags.isInsidePaintCall = true;
  32315. #endif
  32316. if (effect_ != 0)
  32317. {
  32318. ScopedPointer<Image> effectImage (Image::createNativeImage (flags.opaqueFlag ? Image::RGB : Image::ARGB,
  32319. getWidth(), getHeight(),
  32320. ! flags.opaqueFlag));
  32321. {
  32322. Graphics g2 (*effectImage);
  32323. renderComponent (g2);
  32324. }
  32325. effect_->applyEffect (*effectImage, g);
  32326. }
  32327. else
  32328. {
  32329. renderComponent (g);
  32330. }
  32331. #if JUCE_DEBUG
  32332. flags.isInsidePaintCall = false;
  32333. #endif
  32334. }
  32335. Image* Component::createComponentSnapshot (const Rectangle<int>& areaToGrab,
  32336. const bool clipImageToComponentBounds)
  32337. {
  32338. Rectangle<int> r (areaToGrab);
  32339. if (clipImageToComponentBounds)
  32340. r = r.getIntersection (getLocalBounds());
  32341. ScopedPointer<Image> componentImage (Image::createNativeImage (flags.opaqueFlag ? Image::RGB : Image::ARGB,
  32342. jmax (1, r.getWidth()),
  32343. jmax (1, r.getHeight()),
  32344. true));
  32345. Graphics imageContext (*componentImage);
  32346. imageContext.setOrigin (-r.getX(), -r.getY());
  32347. paintEntireComponent (imageContext);
  32348. return componentImage.release();
  32349. }
  32350. void Component::setComponentEffect (ImageEffectFilter* const effect)
  32351. {
  32352. if (effect_ != effect)
  32353. {
  32354. effect_ = effect;
  32355. repaint();
  32356. }
  32357. }
  32358. LookAndFeel& Component::getLookAndFeel() const throw()
  32359. {
  32360. const Component* c = this;
  32361. do
  32362. {
  32363. if (c->lookAndFeel_ != 0)
  32364. return *(c->lookAndFeel_);
  32365. c = c->parentComponent_;
  32366. }
  32367. while (c != 0);
  32368. return LookAndFeel::getDefaultLookAndFeel();
  32369. }
  32370. void Component::setLookAndFeel (LookAndFeel* const newLookAndFeel)
  32371. {
  32372. if (lookAndFeel_ != newLookAndFeel)
  32373. {
  32374. lookAndFeel_ = newLookAndFeel;
  32375. sendLookAndFeelChange();
  32376. }
  32377. }
  32378. void Component::lookAndFeelChanged()
  32379. {
  32380. }
  32381. void Component::sendLookAndFeelChange()
  32382. {
  32383. repaint();
  32384. lookAndFeelChanged();
  32385. // (it's not a great idea to do anything that would delete this component
  32386. // during the lookAndFeelChanged() callback)
  32387. jassert (isValidComponent());
  32388. SafePointer<Component> safePointer (this);
  32389. for (int i = childComponentList_.size(); --i >= 0;)
  32390. {
  32391. childComponentList_.getUnchecked (i)->sendLookAndFeelChange();
  32392. if (safePointer == 0)
  32393. return;
  32394. i = jmin (i, childComponentList_.size());
  32395. }
  32396. }
  32397. static const var::identifier getColourPropertyId (const int colourId)
  32398. {
  32399. String s;
  32400. s.preallocateStorage (18);
  32401. s << "jcclr_" << String::toHexString (colourId);
  32402. return s;
  32403. }
  32404. const Colour Component::findColour (const int colourId, const bool inheritFromParent) const
  32405. {
  32406. var* v = properties.getItem (getColourPropertyId (colourId));
  32407. if (v != 0)
  32408. return Colour ((int) *v);
  32409. if (inheritFromParent && parentComponent_ != 0)
  32410. return parentComponent_->findColour (colourId, true);
  32411. return getLookAndFeel().findColour (colourId);
  32412. }
  32413. bool Component::isColourSpecified (const int colourId) const
  32414. {
  32415. return properties.contains (getColourPropertyId (colourId));
  32416. }
  32417. void Component::removeColour (const int colourId)
  32418. {
  32419. if (properties.remove (getColourPropertyId (colourId)))
  32420. colourChanged();
  32421. }
  32422. void Component::setColour (const int colourId, const Colour& colour)
  32423. {
  32424. if (properties.set (getColourPropertyId (colourId), (int) colour.getARGB()))
  32425. colourChanged();
  32426. }
  32427. void Component::copyAllExplicitColoursTo (Component& target) const
  32428. {
  32429. bool changed = false;
  32430. for (int i = properties.size(); --i >= 0;)
  32431. {
  32432. const var::identifier name (properties.getName(i));
  32433. if (name.name.startsWith ("jcclr_"))
  32434. if (target.properties.set (name, properties [name]))
  32435. changed = true;
  32436. }
  32437. if (changed)
  32438. target.colourChanged();
  32439. }
  32440. void Component::colourChanged()
  32441. {
  32442. }
  32443. const Rectangle<int> Component::getLocalBounds() const throw()
  32444. {
  32445. return Rectangle<int> (0, 0, getWidth(), getHeight());
  32446. }
  32447. const Rectangle<int> Component::getUnclippedArea() const
  32448. {
  32449. int x = 0, y = 0, w = getWidth(), h = getHeight();
  32450. Component* p = parentComponent_;
  32451. int px = getX();
  32452. int py = getY();
  32453. while (p != 0)
  32454. {
  32455. if (! Rectangle<int>::intersectRectangles (x, y, w, h, -px, -py, p->getWidth(), p->getHeight()))
  32456. return Rectangle<int>();
  32457. px += p->getX();
  32458. py += p->getY();
  32459. p = p->parentComponent_;
  32460. }
  32461. return Rectangle<int> (x, y, w, h);
  32462. }
  32463. void Component::clipObscuredRegions (Graphics& g, const Rectangle<int>& clipRect,
  32464. const int deltaX, const int deltaY) const
  32465. {
  32466. for (int i = childComponentList_.size(); --i >= 0;)
  32467. {
  32468. const Component* const c = childComponentList_.getUnchecked(i);
  32469. if (c->isVisible())
  32470. {
  32471. const Rectangle<int> newClip (clipRect.getIntersection (c->bounds_));
  32472. if (! newClip.isEmpty())
  32473. {
  32474. if (c->isOpaque())
  32475. {
  32476. g.excludeClipRegion (newClip.translated (deltaX, deltaY));
  32477. }
  32478. else
  32479. {
  32480. c->clipObscuredRegions (g, newClip.translated (-c->getX(), -c->getY()),
  32481. c->getX() + deltaX,
  32482. c->getY() + deltaY);
  32483. }
  32484. }
  32485. }
  32486. }
  32487. }
  32488. void Component::getVisibleArea (RectangleList& result, const bool includeSiblings) const
  32489. {
  32490. result.clear();
  32491. const Rectangle<int> unclipped (getUnclippedArea());
  32492. if (! unclipped.isEmpty())
  32493. {
  32494. result.add (unclipped);
  32495. if (includeSiblings)
  32496. {
  32497. const Component* const c = getTopLevelComponent();
  32498. c->subtractObscuredRegions (result, c->relativePositionToOtherComponent (this, Point<int>()),
  32499. c->getLocalBounds(), this);
  32500. }
  32501. subtractObscuredRegions (result, Point<int>(), unclipped, 0);
  32502. result.consolidate();
  32503. }
  32504. }
  32505. void Component::subtractObscuredRegions (RectangleList& result,
  32506. const Point<int>& delta,
  32507. const Rectangle<int>& clipRect,
  32508. const Component* const compToAvoid) const
  32509. {
  32510. for (int i = childComponentList_.size(); --i >= 0;)
  32511. {
  32512. const Component* const c = childComponentList_.getUnchecked(i);
  32513. if (c != compToAvoid && c->isVisible())
  32514. {
  32515. if (c->isOpaque())
  32516. {
  32517. Rectangle<int> childBounds (c->bounds_.getIntersection (clipRect));
  32518. childBounds.translate (delta.getX(), delta.getY());
  32519. result.subtract (childBounds);
  32520. }
  32521. else
  32522. {
  32523. Rectangle<int> newClip (clipRect.getIntersection (c->bounds_));
  32524. newClip.translate (-c->getX(), -c->getY());
  32525. c->subtractObscuredRegions (result, c->getPosition() + delta,
  32526. newClip, compToAvoid);
  32527. }
  32528. }
  32529. }
  32530. }
  32531. void Component::mouseEnter (const MouseEvent&)
  32532. {
  32533. // base class does nothing
  32534. }
  32535. void Component::mouseExit (const MouseEvent&)
  32536. {
  32537. // base class does nothing
  32538. }
  32539. void Component::mouseDown (const MouseEvent&)
  32540. {
  32541. // base class does nothing
  32542. }
  32543. void Component::mouseUp (const MouseEvent&)
  32544. {
  32545. // base class does nothing
  32546. }
  32547. void Component::mouseDrag (const MouseEvent&)
  32548. {
  32549. // base class does nothing
  32550. }
  32551. void Component::mouseMove (const MouseEvent&)
  32552. {
  32553. // base class does nothing
  32554. }
  32555. void Component::mouseDoubleClick (const MouseEvent&)
  32556. {
  32557. // base class does nothing
  32558. }
  32559. void Component::mouseWheelMove (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY)
  32560. {
  32561. // the base class just passes this event up to its parent..
  32562. if (parentComponent_ != 0)
  32563. parentComponent_->mouseWheelMove (e.getEventRelativeTo (parentComponent_),
  32564. wheelIncrementX, wheelIncrementY);
  32565. }
  32566. void Component::resized()
  32567. {
  32568. // base class does nothing
  32569. }
  32570. void Component::moved()
  32571. {
  32572. // base class does nothing
  32573. }
  32574. void Component::childBoundsChanged (Component*)
  32575. {
  32576. // base class does nothing
  32577. }
  32578. void Component::parentSizeChanged()
  32579. {
  32580. // base class does nothing
  32581. }
  32582. void Component::addComponentListener (ComponentListener* const newListener)
  32583. {
  32584. jassert (isValidComponent());
  32585. componentListeners.add (newListener);
  32586. }
  32587. void Component::removeComponentListener (ComponentListener* const listenerToRemove)
  32588. {
  32589. jassert (isValidComponent());
  32590. componentListeners.remove (listenerToRemove);
  32591. }
  32592. void Component::inputAttemptWhenModal()
  32593. {
  32594. bringModalComponentToFront();
  32595. getLookAndFeel().playAlertSound();
  32596. }
  32597. bool Component::canModalEventBeSentToComponent (const Component*)
  32598. {
  32599. return false;
  32600. }
  32601. void Component::internalModalInputAttempt()
  32602. {
  32603. Component* const current = getCurrentlyModalComponent();
  32604. if (current != 0)
  32605. current->inputAttemptWhenModal();
  32606. }
  32607. void Component::paint (Graphics&)
  32608. {
  32609. // all painting is done in the subclasses
  32610. jassert (! isOpaque()); // if your component's opaque, you've gotta paint it!
  32611. }
  32612. void Component::paintOverChildren (Graphics&)
  32613. {
  32614. // all painting is done in the subclasses
  32615. }
  32616. void Component::handleMessage (const Message& message)
  32617. {
  32618. if (message.intParameter1 == exitModalStateMessage)
  32619. {
  32620. exitModalState (message.intParameter2);
  32621. }
  32622. else if (message.intParameter1 == customCommandMessage)
  32623. {
  32624. handleCommandMessage (message.intParameter2);
  32625. }
  32626. }
  32627. void Component::postCommandMessage (const int commandId)
  32628. {
  32629. postMessage (new Message (customCommandMessage, commandId, 0, 0));
  32630. }
  32631. void Component::handleCommandMessage (int)
  32632. {
  32633. // used by subclasses
  32634. }
  32635. void Component::addMouseListener (MouseListener* const newListener,
  32636. const bool wantsEventsForAllNestedChildComponents)
  32637. {
  32638. // if component methods are being called from threads other than the message
  32639. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  32640. checkMessageManagerIsLocked
  32641. if (mouseListeners_ == 0)
  32642. mouseListeners_ = new Array<MouseListener*>();
  32643. if (! mouseListeners_->contains (newListener))
  32644. {
  32645. if (wantsEventsForAllNestedChildComponents)
  32646. {
  32647. mouseListeners_->insert (0, newListener);
  32648. ++numDeepMouseListeners;
  32649. }
  32650. else
  32651. {
  32652. mouseListeners_->add (newListener);
  32653. }
  32654. }
  32655. }
  32656. void Component::removeMouseListener (MouseListener* const listenerToRemove)
  32657. {
  32658. // if component methods are being called from threads other than the message
  32659. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  32660. checkMessageManagerIsLocked
  32661. if (mouseListeners_ != 0)
  32662. {
  32663. const int index = mouseListeners_->indexOf (listenerToRemove);
  32664. if (index >= 0)
  32665. {
  32666. if (index < numDeepMouseListeners)
  32667. --numDeepMouseListeners;
  32668. mouseListeners_->remove (index);
  32669. }
  32670. }
  32671. }
  32672. void Component::internalMouseEnter (MouseInputSource& source, const Point<int>& relativePos, const Time& time)
  32673. {
  32674. if (isCurrentlyBlockedByAnotherModalComponent())
  32675. {
  32676. // if something else is modal, always just show a normal mouse cursor
  32677. source.showMouseCursor (MouseCursor::NormalCursor);
  32678. return;
  32679. }
  32680. if (! flags.mouseInsideFlag)
  32681. {
  32682. flags.mouseInsideFlag = true;
  32683. flags.mouseOverFlag = true;
  32684. flags.draggingFlag = false;
  32685. BailOutChecker checker (this);
  32686. if (flags.repaintOnMouseActivityFlag)
  32687. repaint();
  32688. const MouseEvent me (source, relativePos, source.getCurrentModifiers(),
  32689. this, time, relativePos,
  32690. time, 0, false);
  32691. mouseEnter (me);
  32692. if (checker.shouldBailOut())
  32693. return;
  32694. Desktop::getInstance().resetTimer();
  32695. Desktop::getInstance().mouseListeners.callChecked (checker, &MouseListener::mouseEnter, me);
  32696. if (checker.shouldBailOut())
  32697. return;
  32698. if (mouseListeners_ != 0)
  32699. {
  32700. for (int i = mouseListeners_->size(); --i >= 0;)
  32701. {
  32702. mouseListeners_->getUnchecked(i)->mouseEnter (me);
  32703. if (checker.shouldBailOut())
  32704. return;
  32705. i = jmin (i, mouseListeners_->size());
  32706. }
  32707. }
  32708. Component* p = parentComponent_;
  32709. while (p != 0)
  32710. {
  32711. if (p->numDeepMouseListeners > 0)
  32712. {
  32713. BailOutChecker checker2 (this, p);
  32714. for (int i = p->numDeepMouseListeners; --i >= 0;)
  32715. {
  32716. p->mouseListeners_->getUnchecked(i)->mouseEnter (me);
  32717. if (checker2.shouldBailOut())
  32718. return;
  32719. i = jmin (i, p->numDeepMouseListeners);
  32720. }
  32721. }
  32722. p = p->parentComponent_;
  32723. }
  32724. }
  32725. }
  32726. void Component::internalMouseExit (MouseInputSource& source, const Point<int>& relativePos, const Time& time)
  32727. {
  32728. BailOutChecker checker (this);
  32729. if (flags.draggingFlag)
  32730. {
  32731. internalMouseUp (source, relativePos, time, source.getCurrentModifiers().getRawFlags());
  32732. if (checker.shouldBailOut())
  32733. return;
  32734. }
  32735. if (flags.mouseInsideFlag || flags.mouseOverFlag)
  32736. {
  32737. flags.mouseInsideFlag = false;
  32738. flags.mouseOverFlag = false;
  32739. flags.draggingFlag = false;
  32740. if (flags.repaintOnMouseActivityFlag)
  32741. repaint();
  32742. const MouseEvent me (source, relativePos, source.getCurrentModifiers(),
  32743. this, time, relativePos,
  32744. time, 0, false);
  32745. mouseExit (me);
  32746. if (checker.shouldBailOut())
  32747. return;
  32748. Desktop::getInstance().resetTimer();
  32749. Desktop::getInstance().mouseListeners.callChecked (checker, &MouseListener::mouseExit, me);
  32750. if (checker.shouldBailOut())
  32751. return;
  32752. if (mouseListeners_ != 0)
  32753. {
  32754. for (int i = mouseListeners_->size(); --i >= 0;)
  32755. {
  32756. ((MouseListener*) mouseListeners_->getUnchecked (i))->mouseExit (me);
  32757. if (checker.shouldBailOut())
  32758. return;
  32759. i = jmin (i, mouseListeners_->size());
  32760. }
  32761. }
  32762. Component* p = parentComponent_;
  32763. while (p != 0)
  32764. {
  32765. if (p->numDeepMouseListeners > 0)
  32766. {
  32767. BailOutChecker checker2 (this, p);
  32768. for (int i = p->numDeepMouseListeners; --i >= 0;)
  32769. {
  32770. p->mouseListeners_->getUnchecked (i)->mouseExit (me);
  32771. if (checker2.shouldBailOut())
  32772. return;
  32773. i = jmin (i, p->numDeepMouseListeners);
  32774. }
  32775. }
  32776. p = p->parentComponent_;
  32777. }
  32778. }
  32779. }
  32780. class InternalDragRepeater : public Timer
  32781. {
  32782. public:
  32783. InternalDragRepeater()
  32784. {}
  32785. ~InternalDragRepeater()
  32786. {
  32787. clearSingletonInstance();
  32788. }
  32789. juce_DeclareSingleton_SingleThreaded_Minimal (InternalDragRepeater)
  32790. void timerCallback()
  32791. {
  32792. Desktop& desktop = Desktop::getInstance();
  32793. int numMiceDown = 0;
  32794. for (int i = desktop.getNumMouseSources(); --i >= 0;)
  32795. {
  32796. MouseInputSource* const source = desktop.getMouseSource(i);
  32797. if (source->isDragging())
  32798. {
  32799. source->triggerFakeMove();
  32800. ++numMiceDown;
  32801. }
  32802. }
  32803. if (numMiceDown == 0)
  32804. deleteInstance();
  32805. }
  32806. juce_UseDebuggingNewOperator
  32807. private:
  32808. InternalDragRepeater (const InternalDragRepeater&);
  32809. InternalDragRepeater& operator= (const InternalDragRepeater&);
  32810. };
  32811. juce_ImplementSingleton_SingleThreaded (InternalDragRepeater)
  32812. void Component::beginDragAutoRepeat (const int interval)
  32813. {
  32814. if (interval > 0)
  32815. {
  32816. if (InternalDragRepeater::getInstance()->getTimerInterval() != interval)
  32817. InternalDragRepeater::getInstance()->startTimer (interval);
  32818. }
  32819. else
  32820. {
  32821. InternalDragRepeater::deleteInstance();
  32822. }
  32823. }
  32824. void Component::internalMouseDown (MouseInputSource& source, const Point<int>& relativePos, const Time& time)
  32825. {
  32826. Desktop& desktop = Desktop::getInstance();
  32827. BailOutChecker checker (this);
  32828. if (isCurrentlyBlockedByAnotherModalComponent())
  32829. {
  32830. internalModalInputAttempt();
  32831. if (checker.shouldBailOut())
  32832. return;
  32833. // If processing the input attempt has exited the modal loop, we'll allow the event
  32834. // to be delivered..
  32835. if (isCurrentlyBlockedByAnotherModalComponent())
  32836. {
  32837. // allow blocked mouse-events to go to global listeners..
  32838. const MouseEvent me (source, relativePos, source.getCurrentModifiers(),
  32839. this, time, relativePos, time,
  32840. source.getNumberOfMultipleClicks(), false);
  32841. desktop.resetTimer();
  32842. desktop.mouseListeners.callChecked (checker, &MouseListener::mouseDown, me);
  32843. return;
  32844. }
  32845. }
  32846. {
  32847. Component* c = this;
  32848. while (c != 0)
  32849. {
  32850. if (c->isBroughtToFrontOnMouseClick())
  32851. {
  32852. c->toFront (true);
  32853. if (checker.shouldBailOut())
  32854. return;
  32855. }
  32856. c = c->parentComponent_;
  32857. }
  32858. }
  32859. if (! flags.dontFocusOnMouseClickFlag)
  32860. {
  32861. grabFocusInternal (focusChangedByMouseClick);
  32862. if (checker.shouldBailOut())
  32863. return;
  32864. }
  32865. flags.draggingFlag = true;
  32866. flags.mouseOverFlag = true;
  32867. if (flags.repaintOnMouseActivityFlag)
  32868. repaint();
  32869. const MouseEvent me (source, relativePos, source.getCurrentModifiers(),
  32870. this, time, relativePos, time,
  32871. source.getNumberOfMultipleClicks(), false);
  32872. mouseDown (me);
  32873. if (checker.shouldBailOut())
  32874. return;
  32875. desktop.resetTimer();
  32876. desktop.mouseListeners.callChecked (checker, &MouseListener::mouseDown, me);
  32877. if (checker.shouldBailOut())
  32878. return;
  32879. if (mouseListeners_ != 0)
  32880. {
  32881. for (int i = mouseListeners_->size(); --i >= 0;)
  32882. {
  32883. ((MouseListener*) mouseListeners_->getUnchecked (i))->mouseDown (me);
  32884. if (checker.shouldBailOut())
  32885. return;
  32886. i = jmin (i, mouseListeners_->size());
  32887. }
  32888. }
  32889. Component* p = parentComponent_;
  32890. while (p != 0)
  32891. {
  32892. if (p->numDeepMouseListeners > 0)
  32893. {
  32894. BailOutChecker checker2 (this, p);
  32895. for (int i = p->numDeepMouseListeners; --i >= 0;)
  32896. {
  32897. p->mouseListeners_->getUnchecked (i)->mouseDown (me);
  32898. if (checker2.shouldBailOut())
  32899. return;
  32900. i = jmin (i, p->numDeepMouseListeners);
  32901. }
  32902. }
  32903. p = p->parentComponent_;
  32904. }
  32905. }
  32906. void Component::internalMouseUp (MouseInputSource& source, const Point<int>& relativePos, const Time& time, const ModifierKeys& oldModifiers)
  32907. {
  32908. if (flags.draggingFlag)
  32909. {
  32910. Desktop& desktop = Desktop::getInstance();
  32911. flags.draggingFlag = false;
  32912. BailOutChecker checker (this);
  32913. if (flags.repaintOnMouseActivityFlag)
  32914. repaint();
  32915. const MouseEvent me (source, relativePos,
  32916. oldModifiers, this, time,
  32917. globalPositionToRelative (source.getLastMouseDownPosition()),
  32918. source.getLastMouseDownTime(),
  32919. source.getNumberOfMultipleClicks(),
  32920. source.hasMouseMovedSignificantlySincePressed());
  32921. mouseUp (me);
  32922. if (checker.shouldBailOut())
  32923. return;
  32924. desktop.resetTimer();
  32925. desktop.mouseListeners.callChecked (checker, &MouseListener::mouseUp, me);
  32926. if (checker.shouldBailOut())
  32927. return;
  32928. if (mouseListeners_ != 0)
  32929. {
  32930. for (int i = mouseListeners_->size(); --i >= 0;)
  32931. {
  32932. ((MouseListener*) mouseListeners_->getUnchecked (i))->mouseUp (me);
  32933. if (checker.shouldBailOut())
  32934. return;
  32935. i = jmin (i, mouseListeners_->size());
  32936. }
  32937. }
  32938. {
  32939. Component* p = parentComponent_;
  32940. while (p != 0)
  32941. {
  32942. if (p->numDeepMouseListeners > 0)
  32943. {
  32944. BailOutChecker checker2 (this, p);
  32945. for (int i = p->numDeepMouseListeners; --i >= 0;)
  32946. {
  32947. p->mouseListeners_->getUnchecked (i)->mouseUp (me);
  32948. if (checker2.shouldBailOut())
  32949. return;
  32950. i = jmin (i, p->numDeepMouseListeners);
  32951. }
  32952. }
  32953. p = p->parentComponent_;
  32954. }
  32955. }
  32956. // check for double-click
  32957. if (me.getNumberOfClicks() >= 2)
  32958. {
  32959. const int numListeners = (mouseListeners_ != 0) ? mouseListeners_->size() : 0;
  32960. mouseDoubleClick (me);
  32961. if (checker.shouldBailOut())
  32962. return;
  32963. desktop.mouseListeners.callChecked (checker, &MouseListener::mouseDoubleClick, me);
  32964. if (checker.shouldBailOut())
  32965. return;
  32966. for (int i = numListeners; --i >= 0;)
  32967. {
  32968. if (checker.shouldBailOut())
  32969. return;
  32970. MouseListener* const ml = (MouseListener*)((*mouseListeners_)[i]);
  32971. if (ml != 0)
  32972. ml->mouseDoubleClick (me);
  32973. }
  32974. if (checker.shouldBailOut())
  32975. return;
  32976. Component* p = parentComponent_;
  32977. while (p != 0)
  32978. {
  32979. if (p->numDeepMouseListeners > 0)
  32980. {
  32981. BailOutChecker checker2 (this, p);
  32982. for (int i = p->numDeepMouseListeners; --i >= 0;)
  32983. {
  32984. p->mouseListeners_->getUnchecked (i)->mouseDoubleClick (me);
  32985. if (checker2.shouldBailOut())
  32986. return;
  32987. i = jmin (i, p->numDeepMouseListeners);
  32988. }
  32989. }
  32990. p = p->parentComponent_;
  32991. }
  32992. }
  32993. }
  32994. }
  32995. void Component::internalMouseDrag (MouseInputSource& source, const Point<int>& relativePos, const Time& time)
  32996. {
  32997. if (flags.draggingFlag)
  32998. {
  32999. Desktop& desktop = Desktop::getInstance();
  33000. flags.mouseOverFlag = reallyContains (relativePos.getX(), relativePos.getY(), false);
  33001. BailOutChecker checker (this);
  33002. const MouseEvent me (source, relativePos,
  33003. source.getCurrentModifiers(), this, time,
  33004. globalPositionToRelative (source.getLastMouseDownPosition()),
  33005. source.getLastMouseDownTime(),
  33006. source.getNumberOfMultipleClicks(),
  33007. source.hasMouseMovedSignificantlySincePressed());
  33008. mouseDrag (me);
  33009. if (checker.shouldBailOut())
  33010. return;
  33011. desktop.resetTimer();
  33012. desktop.mouseListeners.callChecked (checker, &MouseListener::mouseDrag, me);
  33013. if (checker.shouldBailOut())
  33014. return;
  33015. if (mouseListeners_ != 0)
  33016. {
  33017. for (int i = mouseListeners_->size(); --i >= 0;)
  33018. {
  33019. ((MouseListener*) mouseListeners_->getUnchecked (i))->mouseDrag (me);
  33020. if (checker.shouldBailOut())
  33021. return;
  33022. i = jmin (i, mouseListeners_->size());
  33023. }
  33024. }
  33025. Component* p = parentComponent_;
  33026. while (p != 0)
  33027. {
  33028. if (p->numDeepMouseListeners > 0)
  33029. {
  33030. BailOutChecker checker2 (this, p);
  33031. for (int i = p->numDeepMouseListeners; --i >= 0;)
  33032. {
  33033. p->mouseListeners_->getUnchecked (i)->mouseDrag (me);
  33034. if (checker2.shouldBailOut())
  33035. return;
  33036. i = jmin (i, p->numDeepMouseListeners);
  33037. }
  33038. }
  33039. p = p->parentComponent_;
  33040. }
  33041. }
  33042. }
  33043. void Component::internalMouseMove (MouseInputSource& source, const Point<int>& relativePos, const Time& time)
  33044. {
  33045. Desktop& desktop = Desktop::getInstance();
  33046. BailOutChecker checker (this);
  33047. const MouseEvent me (source, relativePos, source.getCurrentModifiers(),
  33048. this, time, relativePos,
  33049. time, 0, false);
  33050. if (isCurrentlyBlockedByAnotherModalComponent())
  33051. {
  33052. // allow blocked mouse-events to go to global listeners..
  33053. desktop.sendMouseMove();
  33054. }
  33055. else
  33056. {
  33057. flags.mouseOverFlag = true;
  33058. mouseMove (me);
  33059. if (checker.shouldBailOut())
  33060. return;
  33061. desktop.resetTimer();
  33062. desktop.mouseListeners.callChecked (checker, &MouseListener::mouseMove, me);
  33063. if (checker.shouldBailOut())
  33064. return;
  33065. if (mouseListeners_ != 0)
  33066. {
  33067. for (int i = mouseListeners_->size(); --i >= 0;)
  33068. {
  33069. ((MouseListener*) mouseListeners_->getUnchecked (i))->mouseMove (me);
  33070. if (checker.shouldBailOut())
  33071. return;
  33072. i = jmin (i, mouseListeners_->size());
  33073. }
  33074. }
  33075. Component* p = parentComponent_;
  33076. while (p != 0)
  33077. {
  33078. if (p->numDeepMouseListeners > 0)
  33079. {
  33080. BailOutChecker checker2 (this, p);
  33081. for (int i = p->numDeepMouseListeners; --i >= 0;)
  33082. {
  33083. p->mouseListeners_->getUnchecked (i)->mouseMove (me);
  33084. if (checker2.shouldBailOut())
  33085. return;
  33086. i = jmin (i, p->numDeepMouseListeners);
  33087. }
  33088. }
  33089. p = p->parentComponent_;
  33090. }
  33091. }
  33092. }
  33093. void Component::internalMouseWheel (MouseInputSource& source, const Point<int>& relativePos,
  33094. const Time& time, const float amountX, const float amountY)
  33095. {
  33096. Desktop& desktop = Desktop::getInstance();
  33097. BailOutChecker checker (this);
  33098. const float wheelIncrementX = amountX * (1.0f / 256.0f);
  33099. const float wheelIncrementY = amountY * (1.0f / 256.0f);
  33100. const MouseEvent me (source, relativePos, source.getCurrentModifiers(),
  33101. this, time, relativePos, time, 0, false);
  33102. if (isCurrentlyBlockedByAnotherModalComponent())
  33103. {
  33104. // allow blocked mouse-events to go to global listeners..
  33105. desktop.mouseListeners.callChecked (checker, &MouseListener::mouseWheelMove, me, wheelIncrementX, wheelIncrementY);
  33106. }
  33107. else
  33108. {
  33109. mouseWheelMove (me, wheelIncrementX, wheelIncrementY);
  33110. if (checker.shouldBailOut())
  33111. return;
  33112. desktop.mouseListeners.callChecked (checker, &MouseListener::mouseWheelMove, me, wheelIncrementX, wheelIncrementY);
  33113. if (checker.shouldBailOut())
  33114. return;
  33115. if (mouseListeners_ != 0)
  33116. {
  33117. for (int i = mouseListeners_->size(); --i >= 0;)
  33118. {
  33119. ((MouseListener*) mouseListeners_->getUnchecked (i))->mouseWheelMove (me, wheelIncrementX, wheelIncrementY);
  33120. if (checker.shouldBailOut())
  33121. return;
  33122. i = jmin (i, mouseListeners_->size());
  33123. }
  33124. }
  33125. Component* p = parentComponent_;
  33126. while (p != 0)
  33127. {
  33128. if (p->numDeepMouseListeners > 0)
  33129. {
  33130. BailOutChecker checker2 (this, p);
  33131. for (int i = p->numDeepMouseListeners; --i >= 0;)
  33132. {
  33133. p->mouseListeners_->getUnchecked (i)->mouseWheelMove (me, wheelIncrementX, wheelIncrementY);
  33134. if (checker2.shouldBailOut())
  33135. return;
  33136. i = jmin (i, p->numDeepMouseListeners);
  33137. }
  33138. }
  33139. p = p->parentComponent_;
  33140. }
  33141. }
  33142. }
  33143. void Component::sendFakeMouseMove() const
  33144. {
  33145. Desktop::getInstance().getMainMouseSource().triggerFakeMove();
  33146. }
  33147. void Component::broughtToFront()
  33148. {
  33149. }
  33150. void Component::internalBroughtToFront()
  33151. {
  33152. if (! isValidComponent())
  33153. return;
  33154. if (flags.hasHeavyweightPeerFlag)
  33155. Desktop::getInstance().componentBroughtToFront (this);
  33156. BailOutChecker checker (this);
  33157. broughtToFront();
  33158. if (checker.shouldBailOut())
  33159. return;
  33160. componentListeners.callChecked (checker, &ComponentListener::componentBroughtToFront, *this);
  33161. if (checker.shouldBailOut())
  33162. return;
  33163. // When brought to the front and there's a modal component blocking this one,
  33164. // we need to bring the modal one to the front instead..
  33165. Component* const cm = getCurrentlyModalComponent();
  33166. if (cm != 0 && cm->getTopLevelComponent() != getTopLevelComponent())
  33167. bringModalComponentToFront();
  33168. }
  33169. void Component::focusGained (FocusChangeType)
  33170. {
  33171. // base class does nothing
  33172. }
  33173. void Component::internalFocusGain (const FocusChangeType cause)
  33174. {
  33175. SafePointer<Component> safePointer (this);
  33176. focusGained (cause);
  33177. if (safePointer != 0)
  33178. internalChildFocusChange (cause);
  33179. }
  33180. void Component::focusLost (FocusChangeType)
  33181. {
  33182. // base class does nothing
  33183. }
  33184. void Component::internalFocusLoss (const FocusChangeType cause)
  33185. {
  33186. SafePointer<Component> safePointer (this);
  33187. focusLost (focusChangedDirectly);
  33188. if (safePointer != 0)
  33189. internalChildFocusChange (cause);
  33190. }
  33191. void Component::focusOfChildComponentChanged (FocusChangeType /*cause*/)
  33192. {
  33193. // base class does nothing
  33194. }
  33195. void Component::internalChildFocusChange (FocusChangeType cause)
  33196. {
  33197. const bool childIsNowFocused = hasKeyboardFocus (true);
  33198. if (flags.childCompFocusedFlag != childIsNowFocused)
  33199. {
  33200. flags.childCompFocusedFlag = childIsNowFocused;
  33201. SafePointer<Component> safePointer (this);
  33202. focusOfChildComponentChanged (cause);
  33203. if (safePointer == 0)
  33204. return;
  33205. }
  33206. if (parentComponent_ != 0)
  33207. parentComponent_->internalChildFocusChange (cause);
  33208. }
  33209. bool Component::isEnabled() const throw()
  33210. {
  33211. return (! flags.isDisabledFlag)
  33212. && (parentComponent_ == 0 || parentComponent_->isEnabled());
  33213. }
  33214. void Component::setEnabled (const bool shouldBeEnabled)
  33215. {
  33216. if (flags.isDisabledFlag == shouldBeEnabled)
  33217. {
  33218. flags.isDisabledFlag = ! shouldBeEnabled;
  33219. // if any parent components are disabled, setting our flag won't make a difference,
  33220. // so no need to send a change message
  33221. if (parentComponent_ == 0 || parentComponent_->isEnabled())
  33222. sendEnablementChangeMessage();
  33223. }
  33224. }
  33225. void Component::sendEnablementChangeMessage()
  33226. {
  33227. SafePointer<Component> safePointer (this);
  33228. enablementChanged();
  33229. if (safePointer == 0)
  33230. return;
  33231. for (int i = getNumChildComponents(); --i >= 0;)
  33232. {
  33233. Component* const c = getChildComponent (i);
  33234. if (c != 0)
  33235. {
  33236. c->sendEnablementChangeMessage();
  33237. if (safePointer == 0)
  33238. return;
  33239. }
  33240. }
  33241. }
  33242. void Component::enablementChanged()
  33243. {
  33244. }
  33245. void Component::setWantsKeyboardFocus (const bool wantsFocus) throw()
  33246. {
  33247. flags.wantsFocusFlag = wantsFocus;
  33248. }
  33249. void Component::setMouseClickGrabsKeyboardFocus (const bool shouldGrabFocus)
  33250. {
  33251. flags.dontFocusOnMouseClickFlag = ! shouldGrabFocus;
  33252. }
  33253. bool Component::getMouseClickGrabsKeyboardFocus() const throw()
  33254. {
  33255. return ! flags.dontFocusOnMouseClickFlag;
  33256. }
  33257. bool Component::getWantsKeyboardFocus() const throw()
  33258. {
  33259. return flags.wantsFocusFlag && ! flags.isDisabledFlag;
  33260. }
  33261. void Component::setFocusContainer (const bool shouldBeFocusContainer) throw()
  33262. {
  33263. flags.isFocusContainerFlag = shouldBeFocusContainer;
  33264. }
  33265. bool Component::isFocusContainer() const throw()
  33266. {
  33267. return flags.isFocusContainerFlag;
  33268. }
  33269. int Component::getExplicitFocusOrder() const
  33270. {
  33271. return properties ["_jexfo"];
  33272. }
  33273. void Component::setExplicitFocusOrder (const int newFocusOrderIndex)
  33274. {
  33275. properties.set ("_jexfo", newFocusOrderIndex);
  33276. }
  33277. KeyboardFocusTraverser* Component::createFocusTraverser()
  33278. {
  33279. if (flags.isFocusContainerFlag || parentComponent_ == 0)
  33280. return new KeyboardFocusTraverser();
  33281. return parentComponent_->createFocusTraverser();
  33282. }
  33283. void Component::takeKeyboardFocus (const FocusChangeType cause)
  33284. {
  33285. // give the focus to this component
  33286. if (currentlyFocusedComponent != this)
  33287. {
  33288. JUCE_TRY
  33289. {
  33290. // get the focus onto our desktop window
  33291. ComponentPeer* const peer = getPeer();
  33292. if (peer != 0)
  33293. {
  33294. SafePointer<Component> safePointer (this);
  33295. peer->grabFocus();
  33296. if (peer->isFocused() && currentlyFocusedComponent != this)
  33297. {
  33298. Component* const componentLosingFocus = currentlyFocusedComponent;
  33299. currentlyFocusedComponent = this;
  33300. Desktop::getInstance().triggerFocusCallback();
  33301. // call this after setting currentlyFocusedComponent so that the one that's
  33302. // losing it has a chance to see where focus is going
  33303. if (componentLosingFocus->isValidComponent())
  33304. componentLosingFocus->internalFocusLoss (cause);
  33305. if (currentlyFocusedComponent == this)
  33306. {
  33307. focusGained (cause);
  33308. if (safePointer != 0)
  33309. internalChildFocusChange (cause);
  33310. }
  33311. }
  33312. }
  33313. }
  33314. #if JUCE_CATCH_UNHANDLED_EXCEPTIONS
  33315. catch (const std::exception& e)
  33316. {
  33317. currentlyFocusedComponent = 0;
  33318. Desktop::getInstance().triggerFocusCallback();
  33319. JUCEApplication::sendUnhandledException (&e, __FILE__, __LINE__);
  33320. }
  33321. catch (...)
  33322. {
  33323. currentlyFocusedComponent = 0;
  33324. Desktop::getInstance().triggerFocusCallback();
  33325. JUCEApplication::sendUnhandledException (0, __FILE__, __LINE__);
  33326. }
  33327. #endif
  33328. }
  33329. }
  33330. void Component::grabFocusInternal (const FocusChangeType cause, const bool canTryParent)
  33331. {
  33332. if (isShowing())
  33333. {
  33334. if (flags.wantsFocusFlag && (isEnabled() || parentComponent_ == 0))
  33335. {
  33336. takeKeyboardFocus (cause);
  33337. }
  33338. else
  33339. {
  33340. if (isParentOf (currentlyFocusedComponent)
  33341. && currentlyFocusedComponent->isShowing())
  33342. {
  33343. // do nothing if the focused component is actually a child of ours..
  33344. }
  33345. else
  33346. {
  33347. // find the default child component..
  33348. ScopedPointer <KeyboardFocusTraverser> traverser (createFocusTraverser());
  33349. if (traverser != 0)
  33350. {
  33351. Component* const defaultComp = traverser->getDefaultComponent (this);
  33352. traverser = 0;
  33353. if (defaultComp != 0)
  33354. {
  33355. defaultComp->grabFocusInternal (cause, false);
  33356. return;
  33357. }
  33358. }
  33359. if (canTryParent && parentComponent_ != 0)
  33360. {
  33361. // if no children want it and we're allowed to try our parent comp,
  33362. // then pass up to parent, which will try our siblings.
  33363. parentComponent_->grabFocusInternal (cause, true);
  33364. }
  33365. }
  33366. }
  33367. }
  33368. }
  33369. void Component::grabKeyboardFocus()
  33370. {
  33371. // if component methods are being called from threads other than the message
  33372. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  33373. checkMessageManagerIsLocked
  33374. grabFocusInternal (focusChangedDirectly);
  33375. }
  33376. void Component::moveKeyboardFocusToSibling (const bool moveToNext)
  33377. {
  33378. // if component methods are being called from threads other than the message
  33379. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  33380. checkMessageManagerIsLocked
  33381. if (parentComponent_ != 0)
  33382. {
  33383. ScopedPointer <KeyboardFocusTraverser> traverser (createFocusTraverser());
  33384. if (traverser != 0)
  33385. {
  33386. Component* const nextComp = moveToNext ? traverser->getNextComponent (this)
  33387. : traverser->getPreviousComponent (this);
  33388. traverser = 0;
  33389. if (nextComp != 0)
  33390. {
  33391. if (nextComp->isCurrentlyBlockedByAnotherModalComponent())
  33392. {
  33393. SafePointer<Component> nextCompPointer (nextComp);
  33394. internalModalInputAttempt();
  33395. if (nextCompPointer == 0 || nextComp->isCurrentlyBlockedByAnotherModalComponent())
  33396. return;
  33397. }
  33398. nextComp->grabFocusInternal (focusChangedByTabKey);
  33399. return;
  33400. }
  33401. }
  33402. parentComponent_->moveKeyboardFocusToSibling (moveToNext);
  33403. }
  33404. }
  33405. bool Component::hasKeyboardFocus (const bool trueIfChildIsFocused) const
  33406. {
  33407. return (currentlyFocusedComponent == this)
  33408. || (trueIfChildIsFocused && isParentOf (currentlyFocusedComponent));
  33409. }
  33410. Component* JUCE_CALLTYPE Component::getCurrentlyFocusedComponent() throw()
  33411. {
  33412. return currentlyFocusedComponent;
  33413. }
  33414. void Component::giveAwayFocus()
  33415. {
  33416. // use a copy so we can clear the value before the call
  33417. Component* const componentLosingFocus = currentlyFocusedComponent;
  33418. currentlyFocusedComponent = 0;
  33419. Desktop::getInstance().triggerFocusCallback();
  33420. if (componentLosingFocus->isValidComponent())
  33421. componentLosingFocus->internalFocusLoss (focusChangedDirectly);
  33422. }
  33423. bool Component::isMouseOver() const throw()
  33424. {
  33425. return flags.mouseOverFlag;
  33426. }
  33427. bool Component::isMouseButtonDown() const throw()
  33428. {
  33429. return flags.draggingFlag;
  33430. }
  33431. bool Component::isMouseOverOrDragging() const throw()
  33432. {
  33433. return flags.mouseOverFlag || flags.draggingFlag;
  33434. }
  33435. bool JUCE_CALLTYPE Component::isMouseButtonDownAnywhere() throw()
  33436. {
  33437. return ModifierKeys::getCurrentModifiers().isAnyMouseButtonDown();
  33438. }
  33439. const Point<int> Component::getMouseXYRelative() const
  33440. {
  33441. return globalPositionToRelative (Desktop::getMousePosition());
  33442. }
  33443. const Rectangle<int> Component::getParentMonitorArea() const
  33444. {
  33445. return Desktop::getInstance()
  33446. .getMonitorAreaContaining (relativePositionToGlobal (Point<int> (getWidth() / 2,
  33447. getHeight() / 2)));
  33448. }
  33449. void Component::addKeyListener (KeyListener* const newListener)
  33450. {
  33451. if (keyListeners_ == 0)
  33452. keyListeners_ = new VoidArray();
  33453. keyListeners_->addIfNotAlreadyThere (newListener);
  33454. }
  33455. void Component::removeKeyListener (KeyListener* const listenerToRemove)
  33456. {
  33457. if (keyListeners_ != 0)
  33458. keyListeners_->removeValue (listenerToRemove);
  33459. }
  33460. bool Component::keyPressed (const KeyPress&)
  33461. {
  33462. return false;
  33463. }
  33464. bool Component::keyStateChanged (const bool /*isKeyDown*/)
  33465. {
  33466. return false;
  33467. }
  33468. void Component::modifierKeysChanged (const ModifierKeys& modifiers)
  33469. {
  33470. if (parentComponent_ != 0)
  33471. parentComponent_->modifierKeysChanged (modifiers);
  33472. }
  33473. void Component::internalModifierKeysChanged()
  33474. {
  33475. sendFakeMouseMove();
  33476. modifierKeysChanged (ModifierKeys::getCurrentModifiers());
  33477. }
  33478. ComponentPeer* Component::getPeer() const
  33479. {
  33480. if (flags.hasHeavyweightPeerFlag)
  33481. return ComponentPeer::getPeerFor (this);
  33482. else if (parentComponent_ != 0)
  33483. return parentComponent_->getPeer();
  33484. else
  33485. return 0;
  33486. }
  33487. Component::BailOutChecker::BailOutChecker (Component* const component1, Component* const component2_)
  33488. : safePointer1 (component1), safePointer2 (component2_), component2 (component2_)
  33489. {
  33490. jassert (component1 != 0);
  33491. }
  33492. bool Component::BailOutChecker::shouldBailOut() const throw()
  33493. {
  33494. return safePointer1 == 0 || safePointer2.getComponent() != component2;
  33495. }
  33496. END_JUCE_NAMESPACE
  33497. /*** End of inlined file: juce_Component.cpp ***/
  33498. /*** Start of inlined file: juce_ComponentListener.cpp ***/
  33499. BEGIN_JUCE_NAMESPACE
  33500. void ComponentListener::componentMovedOrResized (Component&, bool, bool) {}
  33501. void ComponentListener::componentBroughtToFront (Component&) {}
  33502. void ComponentListener::componentVisibilityChanged (Component&) {}
  33503. void ComponentListener::componentChildrenChanged (Component&) {}
  33504. void ComponentListener::componentParentHierarchyChanged (Component&) {}
  33505. void ComponentListener::componentNameChanged (Component&) {}
  33506. void ComponentListener::componentBeingDeleted (Component&) {}
  33507. END_JUCE_NAMESPACE
  33508. /*** End of inlined file: juce_ComponentListener.cpp ***/
  33509. /*** Start of inlined file: juce_Desktop.cpp ***/
  33510. BEGIN_JUCE_NAMESPACE
  33511. Desktop::Desktop()
  33512. : mouseClickCounter (0),
  33513. kioskModeComponent (0)
  33514. {
  33515. createMouseInputSources();
  33516. refreshMonitorSizes();
  33517. }
  33518. Desktop::~Desktop()
  33519. {
  33520. jassert (instance == this);
  33521. instance = 0;
  33522. // doh! If you don't delete all your windows before exiting, you're going to
  33523. // be leaking memory!
  33524. jassert (desktopComponents.size() == 0);
  33525. }
  33526. Desktop& JUCE_CALLTYPE Desktop::getInstance()
  33527. {
  33528. if (instance == 0)
  33529. instance = new Desktop();
  33530. return *instance;
  33531. }
  33532. Desktop* Desktop::instance = 0;
  33533. extern void juce_updateMultiMonitorInfo (Array <Rectangle<int> >& monitorCoords,
  33534. const bool clipToWorkArea);
  33535. void Desktop::refreshMonitorSizes()
  33536. {
  33537. const Array <Rectangle<int> > oldClipped (monitorCoordsClipped);
  33538. const Array <Rectangle<int> > oldUnclipped (monitorCoordsUnclipped);
  33539. monitorCoordsClipped.clear();
  33540. monitorCoordsUnclipped.clear();
  33541. juce_updateMultiMonitorInfo (monitorCoordsClipped, true);
  33542. juce_updateMultiMonitorInfo (monitorCoordsUnclipped, false);
  33543. jassert (monitorCoordsClipped.size() > 0
  33544. && monitorCoordsClipped.size() == monitorCoordsUnclipped.size());
  33545. if (oldClipped != monitorCoordsClipped
  33546. || oldUnclipped != monitorCoordsUnclipped)
  33547. {
  33548. for (int i = ComponentPeer::getNumPeers(); --i >= 0;)
  33549. {
  33550. ComponentPeer* const p = ComponentPeer::getPeer (i);
  33551. if (p != 0)
  33552. p->handleScreenSizeChange();
  33553. }
  33554. }
  33555. }
  33556. int Desktop::getNumDisplayMonitors() const throw()
  33557. {
  33558. return monitorCoordsClipped.size();
  33559. }
  33560. const Rectangle<int> Desktop::getDisplayMonitorCoordinates (const int index, const bool clippedToWorkArea) const throw()
  33561. {
  33562. return clippedToWorkArea ? monitorCoordsClipped [index]
  33563. : monitorCoordsUnclipped [index];
  33564. }
  33565. const RectangleList Desktop::getAllMonitorDisplayAreas (const bool clippedToWorkArea) const throw()
  33566. {
  33567. RectangleList rl;
  33568. for (int i = 0; i < getNumDisplayMonitors(); ++i)
  33569. rl.addWithoutMerging (getDisplayMonitorCoordinates (i, clippedToWorkArea));
  33570. return rl;
  33571. }
  33572. const Rectangle<int> Desktop::getMainMonitorArea (const bool clippedToWorkArea) const throw()
  33573. {
  33574. return getDisplayMonitorCoordinates (0, clippedToWorkArea);
  33575. }
  33576. const Rectangle<int> Desktop::getMonitorAreaContaining (const Point<int>& position, const bool clippedToWorkArea) const
  33577. {
  33578. Rectangle<int> best (getMainMonitorArea (clippedToWorkArea));
  33579. double bestDistance = 1.0e10;
  33580. for (int i = getNumDisplayMonitors(); --i >= 0;)
  33581. {
  33582. const Rectangle<int> rect (getDisplayMonitorCoordinates (i, clippedToWorkArea));
  33583. if (rect.contains (position))
  33584. return rect;
  33585. const double distance = rect.getCentre().getDistanceFrom (position);
  33586. if (distance < bestDistance)
  33587. {
  33588. bestDistance = distance;
  33589. best = rect;
  33590. }
  33591. }
  33592. return best;
  33593. }
  33594. int Desktop::getNumComponents() const throw()
  33595. {
  33596. return desktopComponents.size();
  33597. }
  33598. Component* Desktop::getComponent (const int index) const throw()
  33599. {
  33600. return desktopComponents [index];
  33601. }
  33602. Component* Desktop::findComponentAt (const Point<int>& screenPosition) const
  33603. {
  33604. for (int i = desktopComponents.size(); --i >= 0;)
  33605. {
  33606. Component* const c = desktopComponents.getUnchecked(i);
  33607. const Point<int> relative (c->globalPositionToRelative (screenPosition));
  33608. if (c->contains (relative.getX(), relative.getY()))
  33609. return c->getComponentAt (relative.getX(), relative.getY());
  33610. }
  33611. return 0;
  33612. }
  33613. void Desktop::addDesktopComponent (Component* const c)
  33614. {
  33615. jassert (c != 0);
  33616. jassert (! desktopComponents.contains (c));
  33617. desktopComponents.addIfNotAlreadyThere (c);
  33618. }
  33619. void Desktop::removeDesktopComponent (Component* const c)
  33620. {
  33621. desktopComponents.removeValue (c);
  33622. }
  33623. void Desktop::componentBroughtToFront (Component* const c)
  33624. {
  33625. const int index = desktopComponents.indexOf (c);
  33626. jassert (index >= 0);
  33627. if (index >= 0)
  33628. {
  33629. int newIndex = -1;
  33630. if (! c->isAlwaysOnTop())
  33631. {
  33632. newIndex = desktopComponents.size();
  33633. while (newIndex > 0 && desktopComponents.getUnchecked (newIndex - 1)->isAlwaysOnTop())
  33634. --newIndex;
  33635. --newIndex;
  33636. }
  33637. desktopComponents.move (index, newIndex);
  33638. }
  33639. }
  33640. const Point<int> Desktop::getLastMouseDownPosition() throw()
  33641. {
  33642. return getInstance().getMainMouseSource().getLastMouseDownPosition();
  33643. }
  33644. int Desktop::getMouseButtonClickCounter() throw()
  33645. {
  33646. return getInstance().mouseClickCounter;
  33647. }
  33648. void Desktop::incrementMouseClickCounter() throw()
  33649. {
  33650. ++mouseClickCounter;
  33651. }
  33652. int Desktop::getNumDraggingMouseSources() const throw()
  33653. {
  33654. int num = 0;
  33655. for (int i = mouseSources.size(); --i >= 0;)
  33656. if (mouseSources.getUnchecked(i)->isDragging())
  33657. ++num;
  33658. return num;
  33659. }
  33660. MouseInputSource* Desktop::getDraggingMouseSource (int index) const throw()
  33661. {
  33662. int num = 0;
  33663. for (int i = mouseSources.size(); --i >= 0;)
  33664. {
  33665. MouseInputSource* const mi = mouseSources.getUnchecked(i);
  33666. if (mi->isDragging())
  33667. {
  33668. if (index == num)
  33669. return mi;
  33670. ++num;
  33671. }
  33672. }
  33673. return 0;
  33674. }
  33675. void Desktop::addFocusChangeListener (FocusChangeListener* const listener)
  33676. {
  33677. focusListeners.add (listener);
  33678. }
  33679. void Desktop::removeFocusChangeListener (FocusChangeListener* const listener)
  33680. {
  33681. focusListeners.remove (listener);
  33682. }
  33683. void Desktop::triggerFocusCallback()
  33684. {
  33685. triggerAsyncUpdate();
  33686. }
  33687. void Desktop::handleAsyncUpdate()
  33688. {
  33689. Component* currentFocus = Component::getCurrentlyFocusedComponent();
  33690. focusListeners.call (&FocusChangeListener::globalFocusChanged, currentFocus);
  33691. }
  33692. void Desktop::addGlobalMouseListener (MouseListener* const listener)
  33693. {
  33694. mouseListeners.add (listener);
  33695. resetTimer();
  33696. }
  33697. void Desktop::removeGlobalMouseListener (MouseListener* const listener)
  33698. {
  33699. mouseListeners.remove (listener);
  33700. resetTimer();
  33701. }
  33702. void Desktop::timerCallback()
  33703. {
  33704. if (lastFakeMouseMove != getMousePosition())
  33705. sendMouseMove();
  33706. }
  33707. void Desktop::sendMouseMove()
  33708. {
  33709. if (! mouseListeners.isEmpty())
  33710. {
  33711. startTimer (20);
  33712. lastFakeMouseMove = getMousePosition();
  33713. Component* const target = findComponentAt (lastFakeMouseMove);
  33714. if (target != 0)
  33715. {
  33716. Component::BailOutChecker checker (target);
  33717. const Point<int> pos (target->globalPositionToRelative (lastFakeMouseMove));
  33718. const Time now (Time::getCurrentTime());
  33719. const MouseEvent me (getMainMouseSource(), pos, ModifierKeys::getCurrentModifiers(),
  33720. target, now, pos, now, 0, false);
  33721. if (me.mods.isAnyMouseButtonDown())
  33722. mouseListeners.callChecked (checker, &MouseListener::mouseDrag, me);
  33723. else
  33724. mouseListeners.callChecked (checker, &MouseListener::mouseMove, me);
  33725. }
  33726. }
  33727. }
  33728. void Desktop::resetTimer()
  33729. {
  33730. if (mouseListeners.size() == 0)
  33731. stopTimer();
  33732. else
  33733. startTimer (100);
  33734. lastFakeMouseMove = getMousePosition();
  33735. }
  33736. extern void juce_setKioskComponent (Component* kioskModeComponent, bool enableOrDisable, bool allowMenusAndBars);
  33737. void Desktop::setKioskModeComponent (Component* componentToUse, const bool allowMenusAndBars)
  33738. {
  33739. if (kioskModeComponent != componentToUse)
  33740. {
  33741. // agh! Don't delete a component without first stopping it being the kiosk comp
  33742. jassert (kioskModeComponent == 0 || kioskModeComponent->isValidComponent());
  33743. // agh! Don't remove a component from the desktop if it's the kiosk comp!
  33744. jassert (kioskModeComponent == 0 || kioskModeComponent->isOnDesktop());
  33745. if (kioskModeComponent->isValidComponent())
  33746. {
  33747. juce_setKioskComponent (kioskModeComponent, false, allowMenusAndBars);
  33748. kioskModeComponent->setBounds (kioskComponentOriginalBounds);
  33749. }
  33750. kioskModeComponent = componentToUse;
  33751. if (kioskModeComponent != 0)
  33752. {
  33753. jassert (kioskModeComponent->isValidComponent());
  33754. // Only components that are already on the desktop can be put into kiosk mode!
  33755. jassert (kioskModeComponent->isOnDesktop());
  33756. kioskComponentOriginalBounds = kioskModeComponent->getBounds();
  33757. juce_setKioskComponent (kioskModeComponent, true, allowMenusAndBars);
  33758. }
  33759. }
  33760. }
  33761. END_JUCE_NAMESPACE
  33762. /*** End of inlined file: juce_Desktop.cpp ***/
  33763. /*** Start of inlined file: juce_ArrowButton.cpp ***/
  33764. BEGIN_JUCE_NAMESPACE
  33765. ArrowButton::ArrowButton (const String& name,
  33766. float arrowDirectionInRadians,
  33767. const Colour& arrowColour)
  33768. : Button (name),
  33769. colour (arrowColour)
  33770. {
  33771. path.lineTo (0.0f, 1.0f);
  33772. path.lineTo (1.0f, 0.5f);
  33773. path.closeSubPath();
  33774. path.applyTransform (AffineTransform::rotation (float_Pi * 2.0f * arrowDirectionInRadians,
  33775. 0.5f, 0.5f));
  33776. setComponentEffect (&shadow);
  33777. buttonStateChanged();
  33778. }
  33779. ArrowButton::~ArrowButton()
  33780. {
  33781. }
  33782. void ArrowButton::paintButton (Graphics& g,
  33783. bool /*isMouseOverButton*/,
  33784. bool /*isButtonDown*/)
  33785. {
  33786. g.setColour (colour);
  33787. g.fillPath (path, path.getTransformToScaleToFit ((float) offset,
  33788. (float) offset,
  33789. (float) (getWidth() - 3),
  33790. (float) (getHeight() - 3),
  33791. false));
  33792. }
  33793. void ArrowButton::buttonStateChanged()
  33794. {
  33795. offset = (isDown()) ? 1 : 0;
  33796. shadow.setShadowProperties ((isDown()) ? 1.2f : 3.0f,
  33797. 0.3f, -1, 0);
  33798. }
  33799. END_JUCE_NAMESPACE
  33800. /*** End of inlined file: juce_ArrowButton.cpp ***/
  33801. /*** Start of inlined file: juce_Button.cpp ***/
  33802. BEGIN_JUCE_NAMESPACE
  33803. class Button::RepeatTimer : public Timer
  33804. {
  33805. public:
  33806. RepeatTimer (Button& owner_) : owner (owner_) {}
  33807. void timerCallback() { owner.repeatTimerCallback(); }
  33808. juce_UseDebuggingNewOperator
  33809. private:
  33810. Button& owner;
  33811. RepeatTimer (const RepeatTimer&);
  33812. RepeatTimer& operator= (const RepeatTimer&);
  33813. };
  33814. Button::Button (const String& name)
  33815. : Component (name),
  33816. text (name),
  33817. buttonPressTime (0),
  33818. lastTimeCallbackTime (0),
  33819. commandManagerToUse (0),
  33820. autoRepeatDelay (-1),
  33821. autoRepeatSpeed (0),
  33822. autoRepeatMinimumDelay (-1),
  33823. radioGroupId (0),
  33824. commandID (0),
  33825. connectedEdgeFlags (0),
  33826. buttonState (buttonNormal),
  33827. lastToggleState (false),
  33828. clickTogglesState (false),
  33829. needsToRelease (false),
  33830. needsRepainting (false),
  33831. isKeyDown (false),
  33832. triggerOnMouseDown (false),
  33833. generateTooltip (false)
  33834. {
  33835. setWantsKeyboardFocus (true);
  33836. isOn.addListener (this);
  33837. }
  33838. Button::~Button()
  33839. {
  33840. isOn.removeListener (this);
  33841. if (commandManagerToUse != 0)
  33842. commandManagerToUse->removeListener (this);
  33843. repeatTimer = 0;
  33844. clearShortcuts();
  33845. }
  33846. void Button::setButtonText (const String& newText)
  33847. {
  33848. if (text != newText)
  33849. {
  33850. text = newText;
  33851. repaint();
  33852. }
  33853. }
  33854. void Button::setTooltip (const String& newTooltip)
  33855. {
  33856. SettableTooltipClient::setTooltip (newTooltip);
  33857. generateTooltip = false;
  33858. }
  33859. const String Button::getTooltip()
  33860. {
  33861. if (generateTooltip && commandManagerToUse != 0 && commandID != 0)
  33862. {
  33863. String tt (commandManagerToUse->getDescriptionOfCommand (commandID));
  33864. Array <KeyPress> keyPresses (commandManagerToUse->getKeyMappings()->getKeyPressesAssignedToCommand (commandID));
  33865. for (int i = 0; i < keyPresses.size(); ++i)
  33866. {
  33867. const String key (keyPresses.getReference(i).getTextDescription());
  33868. tt << " [";
  33869. if (key.length() == 1)
  33870. tt << TRANS("shortcut") << ": '" << key << "']";
  33871. else
  33872. tt << key << ']';
  33873. }
  33874. return tt;
  33875. }
  33876. return SettableTooltipClient::getTooltip();
  33877. }
  33878. void Button::setConnectedEdges (const int connectedEdgeFlags_)
  33879. {
  33880. if (connectedEdgeFlags != connectedEdgeFlags_)
  33881. {
  33882. connectedEdgeFlags = connectedEdgeFlags_;
  33883. repaint();
  33884. }
  33885. }
  33886. void Button::setToggleState (const bool shouldBeOn,
  33887. const bool sendChangeNotification)
  33888. {
  33889. if (shouldBeOn != lastToggleState)
  33890. {
  33891. if (isOn != shouldBeOn) // this test means that if the value is void rather than explicitly set to
  33892. isOn = shouldBeOn; // false, it won't be changed unless the required value is true.
  33893. lastToggleState = shouldBeOn;
  33894. repaint();
  33895. if (sendChangeNotification)
  33896. {
  33897. Component::SafePointer<Component> deletionWatcher (this);
  33898. sendClickMessage (ModifierKeys());
  33899. if (deletionWatcher == 0)
  33900. return;
  33901. }
  33902. if (lastToggleState)
  33903. turnOffOtherButtonsInGroup (sendChangeNotification);
  33904. }
  33905. }
  33906. void Button::setClickingTogglesState (const bool shouldToggle) throw()
  33907. {
  33908. clickTogglesState = shouldToggle;
  33909. // if you've got clickTogglesState turned on, you shouldn't also connect the button
  33910. // up to be a command invoker. Instead, your command handler must flip the state of whatever
  33911. // it is that this button represents, and the button will update its state to reflect this
  33912. // in the applicationCommandListChanged() method.
  33913. jassert (commandManagerToUse == 0 || ! clickTogglesState);
  33914. }
  33915. bool Button::getClickingTogglesState() const throw()
  33916. {
  33917. return clickTogglesState;
  33918. }
  33919. void Button::valueChanged (Value& value)
  33920. {
  33921. if (value.refersToSameSourceAs (isOn))
  33922. setToggleState (isOn.getValue(), true);
  33923. }
  33924. void Button::setRadioGroupId (const int newGroupId)
  33925. {
  33926. if (radioGroupId != newGroupId)
  33927. {
  33928. radioGroupId = newGroupId;
  33929. if (lastToggleState)
  33930. turnOffOtherButtonsInGroup (true);
  33931. }
  33932. }
  33933. void Button::turnOffOtherButtonsInGroup (const bool sendChangeNotification)
  33934. {
  33935. Component* const p = getParentComponent();
  33936. if (p != 0 && radioGroupId != 0)
  33937. {
  33938. Component::SafePointer<Component> deletionWatcher (this);
  33939. for (int i = p->getNumChildComponents(); --i >= 0;)
  33940. {
  33941. Component* const c = p->getChildComponent (i);
  33942. if (c != this)
  33943. {
  33944. Button* const b = dynamic_cast <Button*> (c);
  33945. if (b != 0 && b->getRadioGroupId() == radioGroupId)
  33946. {
  33947. b->setToggleState (false, sendChangeNotification);
  33948. if (deletionWatcher == 0)
  33949. return;
  33950. }
  33951. }
  33952. }
  33953. }
  33954. }
  33955. void Button::enablementChanged()
  33956. {
  33957. updateState (0);
  33958. repaint();
  33959. }
  33960. Button::ButtonState Button::updateState (const MouseEvent* const e)
  33961. {
  33962. ButtonState state = buttonNormal;
  33963. if (isEnabled() && isVisible() && ! isCurrentlyBlockedByAnotherModalComponent())
  33964. {
  33965. Point<int> mousePos;
  33966. if (e == 0)
  33967. mousePos = getMouseXYRelative();
  33968. else
  33969. mousePos = e->getEventRelativeTo (this).getPosition();
  33970. const bool over = reallyContains (mousePos.getX(), mousePos.getY(), true);
  33971. const bool down = isMouseButtonDown();
  33972. if ((down && (over || (triggerOnMouseDown && buttonState == buttonDown))) || isKeyDown)
  33973. state = buttonDown;
  33974. else if (over)
  33975. state = buttonOver;
  33976. }
  33977. setState (state);
  33978. return state;
  33979. }
  33980. void Button::setState (const ButtonState newState)
  33981. {
  33982. if (buttonState != newState)
  33983. {
  33984. buttonState = newState;
  33985. repaint();
  33986. if (buttonState == buttonDown)
  33987. {
  33988. buttonPressTime = Time::getApproximateMillisecondCounter();
  33989. lastTimeCallbackTime = buttonPressTime;
  33990. }
  33991. sendStateMessage();
  33992. }
  33993. }
  33994. bool Button::isDown() const throw()
  33995. {
  33996. return buttonState == buttonDown;
  33997. }
  33998. bool Button::isOver() const throw()
  33999. {
  34000. return buttonState != buttonNormal;
  34001. }
  34002. void Button::buttonStateChanged()
  34003. {
  34004. }
  34005. uint32 Button::getMillisecondsSinceButtonDown() const throw()
  34006. {
  34007. const uint32 now = Time::getApproximateMillisecondCounter();
  34008. return now > buttonPressTime ? now - buttonPressTime : 0;
  34009. }
  34010. void Button::setTriggeredOnMouseDown (const bool isTriggeredOnMouseDown) throw()
  34011. {
  34012. triggerOnMouseDown = isTriggeredOnMouseDown;
  34013. }
  34014. void Button::clicked()
  34015. {
  34016. }
  34017. void Button::clicked (const ModifierKeys& /*modifiers*/)
  34018. {
  34019. clicked();
  34020. }
  34021. static const int clickMessageId = 0x2f3f4f99;
  34022. void Button::triggerClick()
  34023. {
  34024. postCommandMessage (clickMessageId);
  34025. }
  34026. void Button::internalClickCallback (const ModifierKeys& modifiers)
  34027. {
  34028. if (clickTogglesState)
  34029. setToggleState ((radioGroupId != 0) || ! lastToggleState, false);
  34030. sendClickMessage (modifiers);
  34031. }
  34032. void Button::flashButtonState()
  34033. {
  34034. if (isEnabled())
  34035. {
  34036. needsToRelease = true;
  34037. setState (buttonDown);
  34038. getRepeatTimer().startTimer (100);
  34039. }
  34040. }
  34041. void Button::handleCommandMessage (int commandId)
  34042. {
  34043. if (commandId == clickMessageId)
  34044. {
  34045. if (isEnabled())
  34046. {
  34047. flashButtonState();
  34048. internalClickCallback (ModifierKeys::getCurrentModifiers());
  34049. }
  34050. }
  34051. else
  34052. {
  34053. Component::handleCommandMessage (commandId);
  34054. }
  34055. }
  34056. void Button::addButtonListener (ButtonListener* const newListener)
  34057. {
  34058. buttonListeners.add (newListener);
  34059. }
  34060. void Button::removeButtonListener (ButtonListener* const listener)
  34061. {
  34062. buttonListeners.remove (listener);
  34063. }
  34064. void Button::sendClickMessage (const ModifierKeys& modifiers)
  34065. {
  34066. Component::BailOutChecker checker (this);
  34067. if (commandManagerToUse != 0 && commandID != 0)
  34068. {
  34069. ApplicationCommandTarget::InvocationInfo info (commandID);
  34070. info.invocationMethod = ApplicationCommandTarget::InvocationInfo::fromButton;
  34071. info.originatingComponent = this;
  34072. commandManagerToUse->invoke (info, true);
  34073. }
  34074. clicked (modifiers);
  34075. if (! checker.shouldBailOut())
  34076. buttonListeners.callChecked (checker, &ButtonListener::buttonClicked, this);
  34077. }
  34078. void Button::sendStateMessage()
  34079. {
  34080. Component::BailOutChecker checker (this);
  34081. buttonStateChanged();
  34082. if (! checker.shouldBailOut())
  34083. buttonListeners.callChecked (checker, &ButtonListener::buttonStateChanged, this);
  34084. }
  34085. void Button::paint (Graphics& g)
  34086. {
  34087. if (needsToRelease && isEnabled())
  34088. {
  34089. needsToRelease = false;
  34090. needsRepainting = true;
  34091. }
  34092. paintButton (g, isOver(), isDown());
  34093. }
  34094. void Button::mouseEnter (const MouseEvent& e)
  34095. {
  34096. updateState (&e);
  34097. }
  34098. void Button::mouseExit (const MouseEvent& e)
  34099. {
  34100. updateState (&e);
  34101. }
  34102. void Button::mouseDown (const MouseEvent& e)
  34103. {
  34104. updateState (&e);
  34105. if (isDown())
  34106. {
  34107. if (autoRepeatDelay >= 0)
  34108. getRepeatTimer().startTimer (autoRepeatDelay);
  34109. if (triggerOnMouseDown)
  34110. internalClickCallback (e.mods);
  34111. }
  34112. }
  34113. void Button::mouseUp (const MouseEvent& e)
  34114. {
  34115. const bool wasDown = isDown();
  34116. updateState (&e);
  34117. if (wasDown && isOver() && ! triggerOnMouseDown)
  34118. internalClickCallback (e.mods);
  34119. }
  34120. void Button::mouseDrag (const MouseEvent& e)
  34121. {
  34122. const ButtonState oldState = buttonState;
  34123. updateState (&e);
  34124. if (autoRepeatDelay >= 0 && buttonState != oldState && isDown())
  34125. getRepeatTimer().startTimer (autoRepeatSpeed);
  34126. }
  34127. void Button::focusGained (FocusChangeType)
  34128. {
  34129. updateState (0);
  34130. repaint();
  34131. }
  34132. void Button::focusLost (FocusChangeType)
  34133. {
  34134. updateState (0);
  34135. repaint();
  34136. }
  34137. void Button::setVisible (bool shouldBeVisible)
  34138. {
  34139. if (shouldBeVisible != isVisible())
  34140. {
  34141. Component::setVisible (shouldBeVisible);
  34142. if (! shouldBeVisible)
  34143. needsToRelease = false;
  34144. updateState (0);
  34145. }
  34146. else
  34147. {
  34148. Component::setVisible (shouldBeVisible);
  34149. }
  34150. }
  34151. void Button::parentHierarchyChanged()
  34152. {
  34153. Component* const newKeySource = (shortcuts.size() == 0) ? 0 : getTopLevelComponent();
  34154. if (newKeySource != keySource.getComponent())
  34155. {
  34156. if (keySource != 0)
  34157. keySource->removeKeyListener (this);
  34158. keySource = newKeySource;
  34159. if (keySource != 0)
  34160. keySource->addKeyListener (this);
  34161. }
  34162. }
  34163. void Button::setCommandToTrigger (ApplicationCommandManager* const commandManagerToUse_,
  34164. const int commandID_,
  34165. const bool generateTooltip_)
  34166. {
  34167. commandID = commandID_;
  34168. generateTooltip = generateTooltip_;
  34169. if (commandManagerToUse != commandManagerToUse_)
  34170. {
  34171. if (commandManagerToUse != 0)
  34172. commandManagerToUse->removeListener (this);
  34173. commandManagerToUse = commandManagerToUse_;
  34174. if (commandManagerToUse != 0)
  34175. commandManagerToUse->addListener (this);
  34176. // if you've got clickTogglesState turned on, you shouldn't also connect the button
  34177. // up to be a command invoker. Instead, your command handler must flip the state of whatever
  34178. // it is that this button represents, and the button will update its state to reflect this
  34179. // in the applicationCommandListChanged() method.
  34180. jassert (commandManagerToUse == 0 || ! clickTogglesState);
  34181. }
  34182. if (commandManagerToUse != 0)
  34183. applicationCommandListChanged();
  34184. else
  34185. setEnabled (true);
  34186. }
  34187. void Button::applicationCommandInvoked (const ApplicationCommandTarget::InvocationInfo& info)
  34188. {
  34189. if (info.commandID == commandID
  34190. && (info.commandFlags & ApplicationCommandInfo::dontTriggerVisualFeedback) == 0)
  34191. {
  34192. flashButtonState();
  34193. }
  34194. }
  34195. void Button::applicationCommandListChanged()
  34196. {
  34197. if (commandManagerToUse != 0)
  34198. {
  34199. ApplicationCommandInfo info (0);
  34200. ApplicationCommandTarget* const target = commandManagerToUse->getTargetForCommand (commandID, info);
  34201. setEnabled (target != 0 && (info.flags & ApplicationCommandInfo::isDisabled) == 0);
  34202. if (target != 0)
  34203. setToggleState ((info.flags & ApplicationCommandInfo::isTicked) != 0, false);
  34204. }
  34205. }
  34206. void Button::addShortcut (const KeyPress& key)
  34207. {
  34208. if (key.isValid())
  34209. {
  34210. jassert (! isRegisteredForShortcut (key)); // already registered!
  34211. shortcuts.add (key);
  34212. parentHierarchyChanged();
  34213. }
  34214. }
  34215. void Button::clearShortcuts()
  34216. {
  34217. shortcuts.clear();
  34218. parentHierarchyChanged();
  34219. }
  34220. bool Button::isShortcutPressed() const
  34221. {
  34222. if (! isCurrentlyBlockedByAnotherModalComponent())
  34223. {
  34224. for (int i = shortcuts.size(); --i >= 0;)
  34225. if (shortcuts.getReference(i).isCurrentlyDown())
  34226. return true;
  34227. }
  34228. return false;
  34229. }
  34230. bool Button::isRegisteredForShortcut (const KeyPress& key) const
  34231. {
  34232. for (int i = shortcuts.size(); --i >= 0;)
  34233. if (key == shortcuts.getReference(i))
  34234. return true;
  34235. return false;
  34236. }
  34237. bool Button::keyStateChanged (const bool, Component*)
  34238. {
  34239. if (! isEnabled())
  34240. return false;
  34241. const bool wasDown = isKeyDown;
  34242. isKeyDown = isShortcutPressed();
  34243. if (autoRepeatDelay >= 0 && (isKeyDown && ! wasDown))
  34244. getRepeatTimer().startTimer (autoRepeatDelay);
  34245. updateState (0);
  34246. if (isEnabled() && wasDown && ! isKeyDown)
  34247. {
  34248. internalClickCallback (ModifierKeys::getCurrentModifiers());
  34249. // (return immediately - this button may now have been deleted)
  34250. return true;
  34251. }
  34252. return wasDown || isKeyDown;
  34253. }
  34254. bool Button::keyPressed (const KeyPress&, Component*)
  34255. {
  34256. // returning true will avoid forwarding events for keys that we're using as shortcuts
  34257. return isShortcutPressed();
  34258. }
  34259. bool Button::keyPressed (const KeyPress& key)
  34260. {
  34261. if (isEnabled() && key.isKeyCode (KeyPress::returnKey))
  34262. {
  34263. triggerClick();
  34264. return true;
  34265. }
  34266. return false;
  34267. }
  34268. void Button::setRepeatSpeed (const int initialDelayMillisecs,
  34269. const int repeatMillisecs,
  34270. const int minimumDelayInMillisecs) throw()
  34271. {
  34272. autoRepeatDelay = initialDelayMillisecs;
  34273. autoRepeatSpeed = repeatMillisecs;
  34274. autoRepeatMinimumDelay = jmin (autoRepeatSpeed, minimumDelayInMillisecs);
  34275. }
  34276. void Button::repeatTimerCallback()
  34277. {
  34278. if (needsRepainting)
  34279. {
  34280. getRepeatTimer().stopTimer();
  34281. updateState (0);
  34282. needsRepainting = false;
  34283. }
  34284. else if (autoRepeatSpeed > 0 && (isKeyDown || (updateState (0) == buttonDown)))
  34285. {
  34286. int repeatSpeed = autoRepeatSpeed;
  34287. if (autoRepeatMinimumDelay >= 0)
  34288. {
  34289. double timeHeldDown = jmin (1.0, getMillisecondsSinceButtonDown() / 4000.0);
  34290. timeHeldDown *= timeHeldDown;
  34291. repeatSpeed = repeatSpeed + (int) (timeHeldDown * (autoRepeatMinimumDelay - repeatSpeed));
  34292. }
  34293. repeatSpeed = jmax (1, repeatSpeed);
  34294. getRepeatTimer().startTimer (repeatSpeed);
  34295. const uint32 now = Time::getApproximateMillisecondCounter();
  34296. const int numTimesToCallback = (now > lastTimeCallbackTime) ? jmax (1, (int) (now - lastTimeCallbackTime) / repeatSpeed) : 1;
  34297. lastTimeCallbackTime = now;
  34298. Component::SafePointer<Component> deletionWatcher (this);
  34299. for (int i = numTimesToCallback; --i >= 0;)
  34300. {
  34301. internalClickCallback (ModifierKeys::getCurrentModifiers());
  34302. if (deletionWatcher == 0 || ! isDown())
  34303. return;
  34304. }
  34305. }
  34306. else if (! needsToRelease)
  34307. {
  34308. getRepeatTimer().stopTimer();
  34309. }
  34310. }
  34311. Button::RepeatTimer& Button::getRepeatTimer()
  34312. {
  34313. if (repeatTimer == 0)
  34314. repeatTimer = new RepeatTimer (*this);
  34315. return *repeatTimer;
  34316. }
  34317. END_JUCE_NAMESPACE
  34318. /*** End of inlined file: juce_Button.cpp ***/
  34319. /*** Start of inlined file: juce_DrawableButton.cpp ***/
  34320. BEGIN_JUCE_NAMESPACE
  34321. DrawableButton::DrawableButton (const String& name,
  34322. const DrawableButton::ButtonStyle buttonStyle)
  34323. : Button (name),
  34324. style (buttonStyle),
  34325. edgeIndent (3)
  34326. {
  34327. if (buttonStyle == ImageOnButtonBackground)
  34328. {
  34329. backgroundOff = Colour (0xffbbbbff);
  34330. backgroundOn = Colour (0xff3333ff);
  34331. }
  34332. else
  34333. {
  34334. backgroundOff = Colours::transparentBlack;
  34335. backgroundOn = Colour (0xaabbbbff);
  34336. }
  34337. }
  34338. DrawableButton::~DrawableButton()
  34339. {
  34340. deleteImages();
  34341. }
  34342. void DrawableButton::deleteImages()
  34343. {
  34344. }
  34345. void DrawableButton::setImages (const Drawable* normal,
  34346. const Drawable* over,
  34347. const Drawable* down,
  34348. const Drawable* disabled,
  34349. const Drawable* normalOn,
  34350. const Drawable* overOn,
  34351. const Drawable* downOn,
  34352. const Drawable* disabledOn)
  34353. {
  34354. deleteImages();
  34355. jassert (normal != 0); // you really need to give it at least a normal image..
  34356. if (normal != 0)
  34357. normalImage = normal->createCopy();
  34358. if (over != 0)
  34359. overImage = over->createCopy();
  34360. if (down != 0)
  34361. downImage = down->createCopy();
  34362. if (disabled != 0)
  34363. disabledImage = disabled->createCopy();
  34364. if (normalOn != 0)
  34365. normalImageOn = normalOn->createCopy();
  34366. if (overOn != 0)
  34367. overImageOn = overOn->createCopy();
  34368. if (downOn != 0)
  34369. downImageOn = downOn->createCopy();
  34370. if (disabledOn != 0)
  34371. disabledImageOn = disabledOn->createCopy();
  34372. repaint();
  34373. }
  34374. void DrawableButton::setButtonStyle (const DrawableButton::ButtonStyle newStyle)
  34375. {
  34376. if (style != newStyle)
  34377. {
  34378. style = newStyle;
  34379. repaint();
  34380. }
  34381. }
  34382. void DrawableButton::setBackgroundColours (const Colour& toggledOffColour,
  34383. const Colour& toggledOnColour)
  34384. {
  34385. if (backgroundOff != toggledOffColour
  34386. || backgroundOn != toggledOnColour)
  34387. {
  34388. backgroundOff = toggledOffColour;
  34389. backgroundOn = toggledOnColour;
  34390. repaint();
  34391. }
  34392. }
  34393. const Colour& DrawableButton::getBackgroundColour() const throw()
  34394. {
  34395. return getToggleState() ? backgroundOn
  34396. : backgroundOff;
  34397. }
  34398. void DrawableButton::setEdgeIndent (const int numPixelsIndent)
  34399. {
  34400. edgeIndent = numPixelsIndent;
  34401. repaint();
  34402. }
  34403. void DrawableButton::paintButton (Graphics& g,
  34404. bool isMouseOverButton,
  34405. bool isButtonDown)
  34406. {
  34407. Rectangle<int> imageSpace;
  34408. if (style == ImageOnButtonBackground)
  34409. {
  34410. const int insetX = getWidth() / 4;
  34411. const int insetY = getHeight() / 4;
  34412. imageSpace.setBounds (insetX, insetY, getWidth() - insetX * 2, getHeight() - insetY * 2);
  34413. getLookAndFeel().drawButtonBackground (g, *this,
  34414. getBackgroundColour(),
  34415. isMouseOverButton,
  34416. isButtonDown);
  34417. }
  34418. else
  34419. {
  34420. g.fillAll (getBackgroundColour());
  34421. const int textH = (style == ImageAboveTextLabel)
  34422. ? jmin (16, proportionOfHeight (0.25f))
  34423. : 0;
  34424. const int indentX = jmin (edgeIndent, proportionOfWidth (0.3f));
  34425. const int indentY = jmin (edgeIndent, proportionOfHeight (0.3f));
  34426. imageSpace.setBounds (indentX, indentY,
  34427. getWidth() - indentX * 2,
  34428. getHeight() - indentY * 2 - textH);
  34429. if (textH > 0)
  34430. {
  34431. g.setFont ((float) textH);
  34432. g.setColour (Colours::black.withAlpha (isEnabled() ? 1.0f : 0.4f));
  34433. g.drawFittedText (getButtonText(),
  34434. 2, getHeight() - textH - 1,
  34435. getWidth() - 4, textH,
  34436. Justification::centred, 1);
  34437. }
  34438. }
  34439. g.setImageResamplingQuality (Graphics::mediumResamplingQuality);
  34440. g.setOpacity (1.0f);
  34441. const Drawable* imageToDraw = 0;
  34442. if (isEnabled())
  34443. {
  34444. imageToDraw = getCurrentImage();
  34445. }
  34446. else
  34447. {
  34448. imageToDraw = getToggleState() ? disabledImageOn
  34449. : disabledImage;
  34450. if (imageToDraw == 0)
  34451. {
  34452. g.setOpacity (0.4f);
  34453. imageToDraw = getNormalImage();
  34454. }
  34455. }
  34456. if (imageToDraw != 0)
  34457. {
  34458. if (style == ImageRaw)
  34459. {
  34460. imageToDraw->draw (g, 1.0f);
  34461. }
  34462. else
  34463. {
  34464. imageToDraw->drawWithin (g,
  34465. imageSpace.getX(),
  34466. imageSpace.getY(),
  34467. imageSpace.getWidth(),
  34468. imageSpace.getHeight(),
  34469. RectanglePlacement::centred,
  34470. 1.0f);
  34471. }
  34472. }
  34473. }
  34474. const Drawable* DrawableButton::getCurrentImage() const throw()
  34475. {
  34476. if (isDown())
  34477. return getDownImage();
  34478. if (isOver())
  34479. return getOverImage();
  34480. return getNormalImage();
  34481. }
  34482. const Drawable* DrawableButton::getNormalImage() const throw()
  34483. {
  34484. return (getToggleState() && normalImageOn != 0) ? normalImageOn
  34485. : normalImage;
  34486. }
  34487. const Drawable* DrawableButton::getOverImage() const throw()
  34488. {
  34489. const Drawable* d = normalImage;
  34490. if (getToggleState())
  34491. {
  34492. if (overImageOn != 0)
  34493. d = overImageOn;
  34494. else if (normalImageOn != 0)
  34495. d = normalImageOn;
  34496. else if (overImage != 0)
  34497. d = overImage;
  34498. }
  34499. else
  34500. {
  34501. if (overImage != 0)
  34502. d = overImage;
  34503. }
  34504. return d;
  34505. }
  34506. const Drawable* DrawableButton::getDownImage() const throw()
  34507. {
  34508. const Drawable* d = normalImage;
  34509. if (getToggleState())
  34510. {
  34511. if (downImageOn != 0)
  34512. d = downImageOn;
  34513. else if (overImageOn != 0)
  34514. d = overImageOn;
  34515. else if (normalImageOn != 0)
  34516. d = normalImageOn;
  34517. else if (downImage != 0)
  34518. d = downImage;
  34519. else
  34520. d = getOverImage();
  34521. }
  34522. else
  34523. {
  34524. if (downImage != 0)
  34525. d = downImage;
  34526. else
  34527. d = getOverImage();
  34528. }
  34529. return d;
  34530. }
  34531. END_JUCE_NAMESPACE
  34532. /*** End of inlined file: juce_DrawableButton.cpp ***/
  34533. /*** Start of inlined file: juce_HyperlinkButton.cpp ***/
  34534. BEGIN_JUCE_NAMESPACE
  34535. HyperlinkButton::HyperlinkButton (const String& linkText,
  34536. const URL& linkURL)
  34537. : Button (linkText),
  34538. url (linkURL),
  34539. font (14.0f, Font::underlined),
  34540. resizeFont (true),
  34541. justification (Justification::centred)
  34542. {
  34543. setMouseCursor (MouseCursor::PointingHandCursor);
  34544. setTooltip (linkURL.toString (false));
  34545. }
  34546. HyperlinkButton::~HyperlinkButton()
  34547. {
  34548. }
  34549. void HyperlinkButton::setFont (const Font& newFont,
  34550. const bool resizeToMatchComponentHeight,
  34551. const Justification& justificationType)
  34552. {
  34553. font = newFont;
  34554. resizeFont = resizeToMatchComponentHeight;
  34555. justification = justificationType;
  34556. repaint();
  34557. }
  34558. void HyperlinkButton::setURL (const URL& newURL) throw()
  34559. {
  34560. url = newURL;
  34561. setTooltip (newURL.toString (false));
  34562. }
  34563. const Font HyperlinkButton::getFontToUse() const
  34564. {
  34565. Font f (font);
  34566. if (resizeFont)
  34567. f.setHeight (getHeight() * 0.7f);
  34568. return f;
  34569. }
  34570. void HyperlinkButton::changeWidthToFitText()
  34571. {
  34572. setSize (getFontToUse().getStringWidth (getName()) + 6, getHeight());
  34573. }
  34574. void HyperlinkButton::colourChanged()
  34575. {
  34576. repaint();
  34577. }
  34578. void HyperlinkButton::clicked()
  34579. {
  34580. if (url.isWellFormed())
  34581. url.launchInDefaultBrowser();
  34582. }
  34583. void HyperlinkButton::paintButton (Graphics& g,
  34584. bool isMouseOverButton,
  34585. bool isButtonDown)
  34586. {
  34587. const Colour textColour (findColour (textColourId));
  34588. if (isEnabled())
  34589. g.setColour ((isMouseOverButton) ? textColour.darker ((isButtonDown) ? 1.3f : 0.4f)
  34590. : textColour);
  34591. else
  34592. g.setColour (textColour.withMultipliedAlpha (0.4f));
  34593. g.setFont (getFontToUse());
  34594. g.drawText (getButtonText(),
  34595. 2, 0, getWidth() - 2, getHeight(),
  34596. justification.getOnlyHorizontalFlags() | Justification::verticallyCentred,
  34597. true);
  34598. }
  34599. END_JUCE_NAMESPACE
  34600. /*** End of inlined file: juce_HyperlinkButton.cpp ***/
  34601. /*** Start of inlined file: juce_ImageButton.cpp ***/
  34602. BEGIN_JUCE_NAMESPACE
  34603. ImageButton::ImageButton (const String& text_)
  34604. : Button (text_),
  34605. scaleImageToFit (true),
  34606. preserveProportions (true),
  34607. alphaThreshold (0),
  34608. imageX (0),
  34609. imageY (0),
  34610. imageW (0),
  34611. imageH (0),
  34612. normalImage (0),
  34613. overImage (0),
  34614. downImage (0)
  34615. {
  34616. }
  34617. ImageButton::~ImageButton()
  34618. {
  34619. deleteImages();
  34620. }
  34621. void ImageButton::deleteImages()
  34622. {
  34623. ImageCache::releaseOrDelete (normalImage);
  34624. ImageCache::releaseOrDelete (overImage);
  34625. ImageCache::releaseOrDelete (downImage);
  34626. }
  34627. void ImageButton::setImages (const bool resizeButtonNowToFitThisImage,
  34628. const bool rescaleImagesWhenButtonSizeChanges,
  34629. const bool preserveImageProportions,
  34630. Image* const normalImage_,
  34631. const float imageOpacityWhenNormal,
  34632. const Colour& overlayColourWhenNormal,
  34633. Image* const overImage_,
  34634. const float imageOpacityWhenOver,
  34635. const Colour& overlayColourWhenOver,
  34636. Image* const downImage_,
  34637. const float imageOpacityWhenDown,
  34638. const Colour& overlayColourWhenDown,
  34639. const float hitTestAlphaThreshold)
  34640. {
  34641. deleteImages();
  34642. normalImage = normalImage_;
  34643. overImage = overImage_;
  34644. downImage = downImage_;
  34645. if (resizeButtonNowToFitThisImage && normalImage != 0)
  34646. {
  34647. imageW = normalImage->getWidth();
  34648. imageH = normalImage->getHeight();
  34649. setSize (imageW, imageH);
  34650. }
  34651. scaleImageToFit = rescaleImagesWhenButtonSizeChanges;
  34652. preserveProportions = preserveImageProportions;
  34653. normalOpacity = imageOpacityWhenNormal;
  34654. normalOverlay = overlayColourWhenNormal;
  34655. overOpacity = imageOpacityWhenOver;
  34656. overOverlay = overlayColourWhenOver;
  34657. downOpacity = imageOpacityWhenDown;
  34658. downOverlay = overlayColourWhenDown;
  34659. alphaThreshold = (unsigned char) jlimit (0, 0xff, roundToInt (255.0f * hitTestAlphaThreshold));
  34660. repaint();
  34661. }
  34662. Image* ImageButton::getCurrentImage() const
  34663. {
  34664. if (isDown() || getToggleState())
  34665. return getDownImage();
  34666. if (isOver())
  34667. return getOverImage();
  34668. return getNormalImage();
  34669. }
  34670. Image* ImageButton::getNormalImage() const throw()
  34671. {
  34672. return normalImage;
  34673. }
  34674. Image* ImageButton::getOverImage() const throw()
  34675. {
  34676. return (overImage != 0) ? overImage
  34677. : normalImage;
  34678. }
  34679. Image* ImageButton::getDownImage() const throw()
  34680. {
  34681. return (downImage != 0) ? downImage
  34682. : getOverImage();
  34683. }
  34684. void ImageButton::paintButton (Graphics& g,
  34685. bool isMouseOverButton,
  34686. bool isButtonDown)
  34687. {
  34688. if (! isEnabled())
  34689. {
  34690. isMouseOverButton = false;
  34691. isButtonDown = false;
  34692. }
  34693. Image* const im = getCurrentImage();
  34694. if (im != 0)
  34695. {
  34696. const int iw = im->getWidth();
  34697. const int ih = im->getHeight();
  34698. imageW = getWidth();
  34699. imageH = getHeight();
  34700. imageX = (imageW - iw) >> 1;
  34701. imageY = (imageH - ih) >> 1;
  34702. if (scaleImageToFit)
  34703. {
  34704. if (preserveProportions)
  34705. {
  34706. int newW, newH;
  34707. const float imRatio = ih / (float)iw;
  34708. const float destRatio = imageH / (float)imageW;
  34709. if (imRatio > destRatio)
  34710. {
  34711. newW = roundToInt (imageH / imRatio);
  34712. newH = imageH;
  34713. }
  34714. else
  34715. {
  34716. newW = imageW;
  34717. newH = roundToInt (imageW * imRatio);
  34718. }
  34719. imageX = (imageW - newW) / 2;
  34720. imageY = (imageH - newH) / 2;
  34721. imageW = newW;
  34722. imageH = newH;
  34723. }
  34724. else
  34725. {
  34726. imageX = 0;
  34727. imageY = 0;
  34728. }
  34729. }
  34730. if (! scaleImageToFit)
  34731. {
  34732. imageW = iw;
  34733. imageH = ih;
  34734. }
  34735. getLookAndFeel().drawImageButton (g, im, imageX, imageY, imageW, imageH,
  34736. isButtonDown ? downOverlay
  34737. : (isMouseOverButton ? overOverlay
  34738. : normalOverlay),
  34739. isButtonDown ? downOpacity
  34740. : (isMouseOverButton ? overOpacity
  34741. : normalOpacity),
  34742. *this);
  34743. }
  34744. }
  34745. bool ImageButton::hitTest (int x, int y)
  34746. {
  34747. if (alphaThreshold == 0)
  34748. return true;
  34749. Image* const im = getCurrentImage();
  34750. return im == 0
  34751. || (imageW > 0 && imageH > 0
  34752. && alphaThreshold < im->getPixelAt (((x - imageX) * im->getWidth()) / imageW,
  34753. ((y - imageY) * im->getHeight()) / imageH).getAlpha());
  34754. }
  34755. END_JUCE_NAMESPACE
  34756. /*** End of inlined file: juce_ImageButton.cpp ***/
  34757. /*** Start of inlined file: juce_ShapeButton.cpp ***/
  34758. BEGIN_JUCE_NAMESPACE
  34759. ShapeButton::ShapeButton (const String& text_,
  34760. const Colour& normalColour_,
  34761. const Colour& overColour_,
  34762. const Colour& downColour_)
  34763. : Button (text_),
  34764. normalColour (normalColour_),
  34765. overColour (overColour_),
  34766. downColour (downColour_),
  34767. maintainShapeProportions (false),
  34768. outlineWidth (0.0f)
  34769. {
  34770. }
  34771. ShapeButton::~ShapeButton()
  34772. {
  34773. }
  34774. void ShapeButton::setColours (const Colour& newNormalColour,
  34775. const Colour& newOverColour,
  34776. const Colour& newDownColour)
  34777. {
  34778. normalColour = newNormalColour;
  34779. overColour = newOverColour;
  34780. downColour = newDownColour;
  34781. }
  34782. void ShapeButton::setOutline (const Colour& newOutlineColour,
  34783. const float newOutlineWidth)
  34784. {
  34785. outlineColour = newOutlineColour;
  34786. outlineWidth = newOutlineWidth;
  34787. }
  34788. void ShapeButton::setShape (const Path& newShape,
  34789. const bool resizeNowToFitThisShape,
  34790. const bool maintainShapeProportions_,
  34791. const bool hasShadow)
  34792. {
  34793. shape = newShape;
  34794. maintainShapeProportions = maintainShapeProportions_;
  34795. shadow.setShadowProperties (3.0f, 0.5f, 0, 0);
  34796. setComponentEffect ((hasShadow) ? &shadow : 0);
  34797. if (resizeNowToFitThisShape)
  34798. {
  34799. Rectangle<float> bounds (shape.getBounds());
  34800. if (hasShadow)
  34801. bounds.expand (4.0f, 4.0f);
  34802. shape.applyTransform (AffineTransform::translation (-bounds.getX(), -bounds.getY()));
  34803. setSize (1 + (int) (bounds.getWidth() + outlineWidth),
  34804. 1 + (int) (bounds.getHeight() + outlineWidth));
  34805. }
  34806. }
  34807. void ShapeButton::paintButton (Graphics& g, bool isMouseOverButton, bool isButtonDown)
  34808. {
  34809. if (! isEnabled())
  34810. {
  34811. isMouseOverButton = false;
  34812. isButtonDown = false;
  34813. }
  34814. g.setColour ((isButtonDown) ? downColour
  34815. : (isMouseOverButton) ? overColour
  34816. : normalColour);
  34817. int w = getWidth();
  34818. int h = getHeight();
  34819. if (getComponentEffect() != 0)
  34820. {
  34821. w -= 4;
  34822. h -= 4;
  34823. }
  34824. const float offset = (outlineWidth * 0.5f) + (isButtonDown ? 1.5f : 0.0f);
  34825. const AffineTransform trans (shape.getTransformToScaleToFit (offset, offset,
  34826. w - offset - outlineWidth,
  34827. h - offset - outlineWidth,
  34828. maintainShapeProportions));
  34829. g.fillPath (shape, trans);
  34830. if (outlineWidth > 0.0f)
  34831. {
  34832. g.setColour (outlineColour);
  34833. g.strokePath (shape, PathStrokeType (outlineWidth), trans);
  34834. }
  34835. }
  34836. END_JUCE_NAMESPACE
  34837. /*** End of inlined file: juce_ShapeButton.cpp ***/
  34838. /*** Start of inlined file: juce_TextButton.cpp ***/
  34839. BEGIN_JUCE_NAMESPACE
  34840. TextButton::TextButton (const String& name,
  34841. const String& toolTip)
  34842. : Button (name)
  34843. {
  34844. setTooltip (toolTip);
  34845. }
  34846. TextButton::~TextButton()
  34847. {
  34848. }
  34849. void TextButton::paintButton (Graphics& g,
  34850. bool isMouseOverButton,
  34851. bool isButtonDown)
  34852. {
  34853. getLookAndFeel().drawButtonBackground (g, *this,
  34854. findColour (getToggleState() ? buttonOnColourId
  34855. : buttonColourId),
  34856. isMouseOverButton,
  34857. isButtonDown);
  34858. getLookAndFeel().drawButtonText (g, *this,
  34859. isMouseOverButton,
  34860. isButtonDown);
  34861. }
  34862. void TextButton::colourChanged()
  34863. {
  34864. repaint();
  34865. }
  34866. const Font TextButton::getFont()
  34867. {
  34868. return Font (jmin (15.0f, getHeight() * 0.6f));
  34869. }
  34870. void TextButton::changeWidthToFitText (const int newHeight)
  34871. {
  34872. if (newHeight >= 0)
  34873. setSize (jmax (1, getWidth()), newHeight);
  34874. setSize (getFont().getStringWidth (getButtonText()) + getHeight(),
  34875. getHeight());
  34876. }
  34877. END_JUCE_NAMESPACE
  34878. /*** End of inlined file: juce_TextButton.cpp ***/
  34879. /*** Start of inlined file: juce_ToggleButton.cpp ***/
  34880. BEGIN_JUCE_NAMESPACE
  34881. ToggleButton::ToggleButton (const String& buttonText)
  34882. : Button (buttonText)
  34883. {
  34884. setClickingTogglesState (true);
  34885. }
  34886. ToggleButton::~ToggleButton()
  34887. {
  34888. }
  34889. void ToggleButton::paintButton (Graphics& g,
  34890. bool isMouseOverButton,
  34891. bool isButtonDown)
  34892. {
  34893. getLookAndFeel().drawToggleButton (g, *this,
  34894. isMouseOverButton,
  34895. isButtonDown);
  34896. }
  34897. void ToggleButton::changeWidthToFitText()
  34898. {
  34899. getLookAndFeel().changeToggleButtonWidthToFitText (*this);
  34900. }
  34901. void ToggleButton::colourChanged()
  34902. {
  34903. repaint();
  34904. }
  34905. END_JUCE_NAMESPACE
  34906. /*** End of inlined file: juce_ToggleButton.cpp ***/
  34907. /*** Start of inlined file: juce_ToolbarButton.cpp ***/
  34908. BEGIN_JUCE_NAMESPACE
  34909. ToolbarButton::ToolbarButton (const int itemId_,
  34910. const String& buttonText,
  34911. Drawable* const normalImage_,
  34912. Drawable* const toggledOnImage_)
  34913. : ToolbarItemComponent (itemId_, buttonText, true),
  34914. normalImage (normalImage_),
  34915. toggledOnImage (toggledOnImage_)
  34916. {
  34917. jassert (normalImage_ != 0);
  34918. }
  34919. ToolbarButton::~ToolbarButton()
  34920. {
  34921. }
  34922. bool ToolbarButton::getToolbarItemSizes (int toolbarDepth,
  34923. bool /*isToolbarVertical*/,
  34924. int& preferredSize,
  34925. int& minSize, int& maxSize)
  34926. {
  34927. preferredSize = minSize = maxSize = toolbarDepth;
  34928. return true;
  34929. }
  34930. void ToolbarButton::paintButtonArea (Graphics& g,
  34931. int width, int height,
  34932. bool /*isMouseOver*/,
  34933. bool /*isMouseDown*/)
  34934. {
  34935. Drawable* d = normalImage;
  34936. if (getToggleState() && toggledOnImage != 0)
  34937. d = toggledOnImage;
  34938. if (! isEnabled())
  34939. {
  34940. Image im (Image::ARGB, width, height, true);
  34941. Graphics g2 (im);
  34942. d->drawWithin (g2, 0, 0, width, height, RectanglePlacement::centred, 1.0f);
  34943. im.desaturate();
  34944. g.drawImageAt (&im, 0, 0);
  34945. }
  34946. else
  34947. {
  34948. d->drawWithin (g, 0, 0, width, height, RectanglePlacement::centred, 1.0f);
  34949. }
  34950. }
  34951. void ToolbarButton::contentAreaChanged (const Rectangle<int>&)
  34952. {
  34953. }
  34954. END_JUCE_NAMESPACE
  34955. /*** End of inlined file: juce_ToolbarButton.cpp ***/
  34956. /*** Start of inlined file: juce_CodeDocument.cpp ***/
  34957. BEGIN_JUCE_NAMESPACE
  34958. class CodeDocumentLine
  34959. {
  34960. public:
  34961. CodeDocumentLine (const juce_wchar* const line_,
  34962. const int lineLength_,
  34963. const int numNewLineChars,
  34964. const int lineStartInFile_)
  34965. : line (line_, lineLength_),
  34966. lineStartInFile (lineStartInFile_),
  34967. lineLength (lineLength_),
  34968. lineLengthWithoutNewLines (lineLength_ - numNewLineChars)
  34969. {
  34970. }
  34971. ~CodeDocumentLine()
  34972. {
  34973. }
  34974. static void createLines (Array <CodeDocumentLine*>& newLines, const String& text)
  34975. {
  34976. const juce_wchar* const t = text;
  34977. int pos = 0;
  34978. while (t [pos] != 0)
  34979. {
  34980. const int startOfLine = pos;
  34981. int numNewLineChars = 0;
  34982. while (t[pos] != 0)
  34983. {
  34984. if (t[pos] == '\r')
  34985. {
  34986. ++numNewLineChars;
  34987. ++pos;
  34988. if (t[pos] == '\n')
  34989. {
  34990. ++numNewLineChars;
  34991. ++pos;
  34992. }
  34993. break;
  34994. }
  34995. if (t[pos] == '\n')
  34996. {
  34997. ++numNewLineChars;
  34998. ++pos;
  34999. break;
  35000. }
  35001. ++pos;
  35002. }
  35003. newLines.add (new CodeDocumentLine (t + startOfLine, pos - startOfLine,
  35004. numNewLineChars, startOfLine));
  35005. }
  35006. jassert (pos == text.length());
  35007. }
  35008. bool endsWithLineBreak() const throw()
  35009. {
  35010. return lineLengthWithoutNewLines != lineLength;
  35011. }
  35012. void updateLength() throw()
  35013. {
  35014. lineLengthWithoutNewLines = lineLength = line.length();
  35015. while (lineLengthWithoutNewLines > 0
  35016. && (line [lineLengthWithoutNewLines - 1] == '\n'
  35017. || line [lineLengthWithoutNewLines - 1] == '\r'))
  35018. {
  35019. --lineLengthWithoutNewLines;
  35020. }
  35021. }
  35022. String line;
  35023. int lineStartInFile, lineLength, lineLengthWithoutNewLines;
  35024. };
  35025. CodeDocument::Iterator::Iterator (CodeDocument* const document_)
  35026. : document (document_),
  35027. currentLine (document_->lines[0]),
  35028. line (0),
  35029. position (0)
  35030. {
  35031. }
  35032. CodeDocument::Iterator::Iterator (const CodeDocument::Iterator& other)
  35033. : document (other.document),
  35034. currentLine (other.currentLine),
  35035. line (other.line),
  35036. position (other.position)
  35037. {
  35038. }
  35039. CodeDocument::Iterator& CodeDocument::Iterator::operator= (const CodeDocument::Iterator& other) throw()
  35040. {
  35041. document = other.document;
  35042. currentLine = other.currentLine;
  35043. line = other.line;
  35044. position = other.position;
  35045. return *this;
  35046. }
  35047. CodeDocument::Iterator::~Iterator() throw()
  35048. {
  35049. }
  35050. juce_wchar CodeDocument::Iterator::nextChar()
  35051. {
  35052. if (currentLine == 0)
  35053. return 0;
  35054. jassert (currentLine == document->lines.getUnchecked (line));
  35055. const juce_wchar result = currentLine->line [position - currentLine->lineStartInFile];
  35056. if (++position >= currentLine->lineStartInFile + currentLine->lineLength)
  35057. {
  35058. ++line;
  35059. currentLine = document->lines [line];
  35060. }
  35061. return result;
  35062. }
  35063. void CodeDocument::Iterator::skip()
  35064. {
  35065. if (currentLine != 0)
  35066. {
  35067. jassert (currentLine == document->lines.getUnchecked (line));
  35068. if (++position >= currentLine->lineStartInFile + currentLine->lineLength)
  35069. {
  35070. ++line;
  35071. currentLine = document->lines [line];
  35072. }
  35073. }
  35074. }
  35075. void CodeDocument::Iterator::skipToEndOfLine()
  35076. {
  35077. if (currentLine != 0)
  35078. {
  35079. jassert (currentLine == document->lines.getUnchecked (line));
  35080. ++line;
  35081. currentLine = document->lines [line];
  35082. if (currentLine != 0)
  35083. position = currentLine->lineStartInFile;
  35084. else
  35085. position = document->getNumCharacters();
  35086. }
  35087. }
  35088. juce_wchar CodeDocument::Iterator::peekNextChar() const
  35089. {
  35090. if (currentLine == 0)
  35091. return 0;
  35092. jassert (currentLine == document->lines.getUnchecked (line));
  35093. return const_cast <const String&> (currentLine->line) [position - currentLine->lineStartInFile];
  35094. }
  35095. void CodeDocument::Iterator::skipWhitespace()
  35096. {
  35097. while (CharacterFunctions::isWhitespace (peekNextChar()))
  35098. skip();
  35099. }
  35100. bool CodeDocument::Iterator::isEOF() const throw()
  35101. {
  35102. return currentLine == 0;
  35103. }
  35104. CodeDocument::Position::Position() throw()
  35105. : owner (0), characterPos (0), line (0),
  35106. indexInLine (0), positionMaintained (false)
  35107. {
  35108. }
  35109. CodeDocument::Position::Position (const CodeDocument* const ownerDocument,
  35110. const int line_, const int indexInLine_) throw()
  35111. : owner (const_cast <CodeDocument*> (ownerDocument)),
  35112. characterPos (0), line (line_),
  35113. indexInLine (indexInLine_), positionMaintained (false)
  35114. {
  35115. setLineAndIndex (line_, indexInLine_);
  35116. }
  35117. CodeDocument::Position::Position (const CodeDocument* const ownerDocument,
  35118. const int characterPos_) throw()
  35119. : owner (const_cast <CodeDocument*> (ownerDocument)),
  35120. positionMaintained (false)
  35121. {
  35122. setPosition (characterPos_);
  35123. }
  35124. CodeDocument::Position::Position (const Position& other) throw()
  35125. : owner (other.owner), characterPos (other.characterPos), line (other.line),
  35126. indexInLine (other.indexInLine), positionMaintained (false)
  35127. {
  35128. jassert (*this == other);
  35129. }
  35130. CodeDocument::Position::~Position() throw()
  35131. {
  35132. setPositionMaintained (false);
  35133. }
  35134. CodeDocument::Position& CodeDocument::Position::operator= (const Position& other) throw()
  35135. {
  35136. if (this != &other)
  35137. {
  35138. const bool wasPositionMaintained = positionMaintained;
  35139. if (owner != other.owner)
  35140. setPositionMaintained (false);
  35141. owner = other.owner;
  35142. line = other.line;
  35143. indexInLine = other.indexInLine;
  35144. characterPos = other.characterPos;
  35145. setPositionMaintained (wasPositionMaintained);
  35146. jassert (*this == other);
  35147. }
  35148. return *this;
  35149. }
  35150. bool CodeDocument::Position::operator== (const Position& other) const throw()
  35151. {
  35152. jassert ((characterPos == other.characterPos)
  35153. == (line == other.line && indexInLine == other.indexInLine));
  35154. return characterPos == other.characterPos
  35155. && line == other.line
  35156. && indexInLine == other.indexInLine
  35157. && owner == other.owner;
  35158. }
  35159. bool CodeDocument::Position::operator!= (const Position& other) const throw()
  35160. {
  35161. return ! operator== (other);
  35162. }
  35163. void CodeDocument::Position::setLineAndIndex (const int newLine, const int newIndexInLine) throw()
  35164. {
  35165. jassert (owner != 0);
  35166. if (owner->lines.size() == 0)
  35167. {
  35168. line = 0;
  35169. indexInLine = 0;
  35170. characterPos = 0;
  35171. }
  35172. else
  35173. {
  35174. if (newLine >= owner->lines.size())
  35175. {
  35176. line = owner->lines.size() - 1;
  35177. CodeDocumentLine* const l = owner->lines.getUnchecked (line);
  35178. jassert (l != 0);
  35179. indexInLine = l->lineLengthWithoutNewLines;
  35180. characterPos = l->lineStartInFile + indexInLine;
  35181. }
  35182. else
  35183. {
  35184. line = jmax (0, newLine);
  35185. CodeDocumentLine* const l = owner->lines.getUnchecked (line);
  35186. jassert (l != 0);
  35187. if (l->lineLengthWithoutNewLines > 0)
  35188. indexInLine = jlimit (0, l->lineLengthWithoutNewLines, newIndexInLine);
  35189. else
  35190. indexInLine = 0;
  35191. characterPos = l->lineStartInFile + indexInLine;
  35192. }
  35193. }
  35194. }
  35195. void CodeDocument::Position::setPosition (const int newPosition) throw()
  35196. {
  35197. jassert (owner != 0);
  35198. line = 0;
  35199. indexInLine = 0;
  35200. characterPos = 0;
  35201. if (newPosition > 0)
  35202. {
  35203. int lineStart = 0;
  35204. int lineEnd = owner->lines.size();
  35205. for (;;)
  35206. {
  35207. if (lineEnd - lineStart < 4)
  35208. {
  35209. for (int i = lineStart; i < lineEnd; ++i)
  35210. {
  35211. CodeDocumentLine* const l = owner->lines.getUnchecked (i);
  35212. int index = newPosition - l->lineStartInFile;
  35213. if (index >= 0 && (index < l->lineLength || i == lineEnd - 1))
  35214. {
  35215. line = i;
  35216. indexInLine = jmin (l->lineLengthWithoutNewLines, index);
  35217. characterPos = l->lineStartInFile + indexInLine;
  35218. }
  35219. }
  35220. break;
  35221. }
  35222. else
  35223. {
  35224. const int midIndex = (lineStart + lineEnd + 1) / 2;
  35225. CodeDocumentLine* const mid = owner->lines.getUnchecked (midIndex);
  35226. if (newPosition >= mid->lineStartInFile)
  35227. lineStart = midIndex;
  35228. else
  35229. lineEnd = midIndex;
  35230. }
  35231. }
  35232. }
  35233. }
  35234. void CodeDocument::Position::moveBy (int characterDelta) throw()
  35235. {
  35236. jassert (owner != 0);
  35237. if (characterDelta == 1)
  35238. {
  35239. setPosition (getPosition());
  35240. // If moving right, make sure we don't get stuck between the \r and \n characters..
  35241. if (line < owner->lines.size())
  35242. {
  35243. CodeDocumentLine* const l = owner->lines.getUnchecked (line);
  35244. if (indexInLine + characterDelta < l->lineLength
  35245. && indexInLine + characterDelta >= l->lineLengthWithoutNewLines + 1)
  35246. ++characterDelta;
  35247. }
  35248. }
  35249. setPosition (characterPos + characterDelta);
  35250. }
  35251. const CodeDocument::Position CodeDocument::Position::movedBy (const int characterDelta) const throw()
  35252. {
  35253. CodeDocument::Position p (*this);
  35254. p.moveBy (characterDelta);
  35255. return p;
  35256. }
  35257. const CodeDocument::Position CodeDocument::Position::movedByLines (const int deltaLines) const throw()
  35258. {
  35259. CodeDocument::Position p (*this);
  35260. p.setLineAndIndex (getLineNumber() + deltaLines, getIndexInLine());
  35261. return p;
  35262. }
  35263. const juce_wchar CodeDocument::Position::getCharacter() const throw()
  35264. {
  35265. const CodeDocumentLine* const l = owner->lines [line];
  35266. return l == 0 ? 0 : l->line [getIndexInLine()];
  35267. }
  35268. const String CodeDocument::Position::getLineText() const throw()
  35269. {
  35270. const CodeDocumentLine* const l = owner->lines [line];
  35271. return l == 0 ? String::empty : l->line;
  35272. }
  35273. void CodeDocument::Position::setPositionMaintained (const bool isMaintained) throw()
  35274. {
  35275. if (isMaintained != positionMaintained)
  35276. {
  35277. positionMaintained = isMaintained;
  35278. if (owner != 0)
  35279. {
  35280. if (isMaintained)
  35281. {
  35282. jassert (! owner->positionsToMaintain.contains (this));
  35283. owner->positionsToMaintain.add (this);
  35284. }
  35285. else
  35286. {
  35287. // If this happens, you may have deleted the document while there are Position objects that are still using it...
  35288. jassert (owner->positionsToMaintain.contains (this));
  35289. owner->positionsToMaintain.removeValue (this);
  35290. }
  35291. }
  35292. }
  35293. }
  35294. CodeDocument::CodeDocument()
  35295. : undoManager (std::numeric_limits<int>::max(), 10000),
  35296. currentActionIndex (0),
  35297. indexOfSavedState (-1),
  35298. maximumLineLength (-1),
  35299. newLineChars ("\r\n")
  35300. {
  35301. }
  35302. CodeDocument::~CodeDocument()
  35303. {
  35304. }
  35305. const String CodeDocument::getAllContent() const throw()
  35306. {
  35307. return getTextBetween (Position (this, 0),
  35308. Position (this, lines.size(), 0));
  35309. }
  35310. const String CodeDocument::getTextBetween (const Position& start, const Position& end) const throw()
  35311. {
  35312. if (end.getPosition() <= start.getPosition())
  35313. return String::empty;
  35314. const int startLine = start.getLineNumber();
  35315. const int endLine = end.getLineNumber();
  35316. if (startLine == endLine)
  35317. {
  35318. CodeDocumentLine* const line = lines [startLine];
  35319. return (line == 0) ? String::empty : line->line.substring (start.getIndexInLine(), end.getIndexInLine());
  35320. }
  35321. String result;
  35322. result.preallocateStorage (end.getPosition() - start.getPosition() + 4);
  35323. String::Concatenator concatenator (result);
  35324. const int maxLine = jmin (lines.size() - 1, endLine);
  35325. for (int i = jmax (0, startLine); i <= maxLine; ++i)
  35326. {
  35327. const CodeDocumentLine* line = lines.getUnchecked(i);
  35328. int len = line->lineLength;
  35329. if (i == startLine)
  35330. {
  35331. const int index = start.getIndexInLine();
  35332. concatenator.append (line->line.substring (index, len));
  35333. }
  35334. else if (i == endLine)
  35335. {
  35336. len = end.getIndexInLine();
  35337. concatenator.append (line->line.substring (0, len));
  35338. }
  35339. else
  35340. {
  35341. concatenator.append (line->line);
  35342. }
  35343. }
  35344. return result;
  35345. }
  35346. int CodeDocument::getNumCharacters() const throw()
  35347. {
  35348. const CodeDocumentLine* const lastLine = lines.getLast();
  35349. return (lastLine == 0) ? 0 : lastLine->lineStartInFile + lastLine->lineLength;
  35350. }
  35351. const String CodeDocument::getLine (const int lineIndex) const throw()
  35352. {
  35353. const CodeDocumentLine* const line = lines [lineIndex];
  35354. return (line == 0) ? String::empty : line->line;
  35355. }
  35356. int CodeDocument::getMaximumLineLength() throw()
  35357. {
  35358. if (maximumLineLength < 0)
  35359. {
  35360. maximumLineLength = 0;
  35361. for (int i = lines.size(); --i >= 0;)
  35362. maximumLineLength = jmax (maximumLineLength, lines.getUnchecked(i)->lineLength);
  35363. }
  35364. return maximumLineLength;
  35365. }
  35366. void CodeDocument::deleteSection (const Position& startPosition, const Position& endPosition)
  35367. {
  35368. remove (startPosition.getPosition(), endPosition.getPosition(), true);
  35369. }
  35370. void CodeDocument::insertText (const Position& position, const String& text)
  35371. {
  35372. insert (text, position.getPosition(), true);
  35373. }
  35374. void CodeDocument::replaceAllContent (const String& newContent)
  35375. {
  35376. remove (0, getNumCharacters(), true);
  35377. insert (newContent, 0, true);
  35378. }
  35379. bool CodeDocument::loadFromStream (InputStream& stream)
  35380. {
  35381. replaceAllContent (stream.readEntireStreamAsString());
  35382. setSavePoint();
  35383. clearUndoHistory();
  35384. return true;
  35385. }
  35386. bool CodeDocument::writeToStream (OutputStream& stream)
  35387. {
  35388. for (int i = 0; i < lines.size(); ++i)
  35389. {
  35390. String temp (lines.getUnchecked(i)->line); // use a copy to avoid bloating the memory footprint of the stored string.
  35391. const char* utf8 = temp.toUTF8();
  35392. if (! stream.write (utf8, (int) strlen (utf8)))
  35393. return false;
  35394. }
  35395. return true;
  35396. }
  35397. void CodeDocument::setNewLineCharacters (const String& newLine) throw()
  35398. {
  35399. jassert (newLine == "\r\n" || newLine == "\n" || newLine == "\r");
  35400. newLineChars = newLine;
  35401. }
  35402. void CodeDocument::newTransaction()
  35403. {
  35404. undoManager.beginNewTransaction (String::empty);
  35405. }
  35406. void CodeDocument::undo()
  35407. {
  35408. newTransaction();
  35409. undoManager.undo();
  35410. }
  35411. void CodeDocument::redo()
  35412. {
  35413. undoManager.redo();
  35414. }
  35415. void CodeDocument::clearUndoHistory()
  35416. {
  35417. undoManager.clearUndoHistory();
  35418. }
  35419. void CodeDocument::setSavePoint() throw()
  35420. {
  35421. indexOfSavedState = currentActionIndex;
  35422. }
  35423. bool CodeDocument::hasChangedSinceSavePoint() const throw()
  35424. {
  35425. return currentActionIndex != indexOfSavedState;
  35426. }
  35427. static int getCodeCharacterCategory (const juce_wchar character) throw()
  35428. {
  35429. return (CharacterFunctions::isLetterOrDigit (character) || character == '_')
  35430. ? 2 : (CharacterFunctions::isWhitespace (character) ? 0 : 1);
  35431. }
  35432. const CodeDocument::Position CodeDocument::findWordBreakAfter (const Position& position) const throw()
  35433. {
  35434. Position p (position);
  35435. const int maxDistance = 256;
  35436. int i = 0;
  35437. while (i < maxDistance
  35438. && CharacterFunctions::isWhitespace (p.getCharacter())
  35439. && (i == 0 || (p.getCharacter() != '\n'
  35440. && p.getCharacter() != '\r')))
  35441. {
  35442. ++i;
  35443. p.moveBy (1);
  35444. }
  35445. if (i == 0)
  35446. {
  35447. const int type = getCodeCharacterCategory (p.getCharacter());
  35448. while (i < maxDistance && type == getCodeCharacterCategory (p.getCharacter()))
  35449. {
  35450. ++i;
  35451. p.moveBy (1);
  35452. }
  35453. while (i < maxDistance
  35454. && CharacterFunctions::isWhitespace (p.getCharacter())
  35455. && (i == 0 || (p.getCharacter() != '\n'
  35456. && p.getCharacter() != '\r')))
  35457. {
  35458. ++i;
  35459. p.moveBy (1);
  35460. }
  35461. }
  35462. return p;
  35463. }
  35464. const CodeDocument::Position CodeDocument::findWordBreakBefore (const Position& position) const throw()
  35465. {
  35466. Position p (position);
  35467. const int maxDistance = 256;
  35468. int i = 0;
  35469. bool stoppedAtLineStart = false;
  35470. while (i < maxDistance)
  35471. {
  35472. const juce_wchar c = p.movedBy (-1).getCharacter();
  35473. if (c == '\r' || c == '\n')
  35474. {
  35475. stoppedAtLineStart = true;
  35476. if (i > 0)
  35477. break;
  35478. }
  35479. if (! CharacterFunctions::isWhitespace (c))
  35480. break;
  35481. p.moveBy (-1);
  35482. ++i;
  35483. }
  35484. if (i < maxDistance && ! stoppedAtLineStart)
  35485. {
  35486. const int type = getCodeCharacterCategory (p.movedBy (-1).getCharacter());
  35487. while (i < maxDistance && type == getCodeCharacterCategory (p.movedBy (-1).getCharacter()))
  35488. {
  35489. p.moveBy (-1);
  35490. ++i;
  35491. }
  35492. }
  35493. return p;
  35494. }
  35495. void CodeDocument::checkLastLineStatus()
  35496. {
  35497. while (lines.size() > 0
  35498. && lines.getLast()->lineLength == 0
  35499. && (lines.size() == 1 || ! lines.getUnchecked (lines.size() - 2)->endsWithLineBreak()))
  35500. {
  35501. // remove any empty lines at the end if the preceding line doesn't end in a newline.
  35502. lines.removeLast();
  35503. }
  35504. const CodeDocumentLine* const lastLine = lines.getLast();
  35505. if (lastLine != 0 && lastLine->endsWithLineBreak())
  35506. {
  35507. // check that there's an empty line at the end if the preceding one ends in a newline..
  35508. lines.add (new CodeDocumentLine (String::empty, 0, 0, lastLine->lineStartInFile + lastLine->lineLength));
  35509. }
  35510. }
  35511. void CodeDocument::addListener (CodeDocument::Listener* const listener) throw()
  35512. {
  35513. listeners.add (listener);
  35514. }
  35515. void CodeDocument::removeListener (CodeDocument::Listener* const listener) throw()
  35516. {
  35517. listeners.remove (listener);
  35518. }
  35519. void CodeDocument::sendListenerChangeMessage (const int startLine, const int endLine)
  35520. {
  35521. Position startPos (this, startLine, 0);
  35522. Position endPos (this, endLine, 0);
  35523. listeners.call (&Listener::codeDocumentChanged, startPos, endPos);
  35524. }
  35525. class CodeDocumentInsertAction : public UndoableAction
  35526. {
  35527. CodeDocument& owner;
  35528. const String text;
  35529. int insertPos;
  35530. CodeDocumentInsertAction (const CodeDocumentInsertAction&);
  35531. CodeDocumentInsertAction& operator= (const CodeDocumentInsertAction&);
  35532. public:
  35533. CodeDocumentInsertAction (CodeDocument& owner_, const String& text_, const int insertPos_) throw()
  35534. : owner (owner_),
  35535. text (text_),
  35536. insertPos (insertPos_)
  35537. {
  35538. }
  35539. ~CodeDocumentInsertAction() {}
  35540. bool perform()
  35541. {
  35542. owner.currentActionIndex++;
  35543. owner.insert (text, insertPos, false);
  35544. return true;
  35545. }
  35546. bool undo()
  35547. {
  35548. owner.currentActionIndex--;
  35549. owner.remove (insertPos, insertPos + text.length(), false);
  35550. return true;
  35551. }
  35552. int getSizeInUnits() { return text.length() + 32; }
  35553. };
  35554. void CodeDocument::insert (const String& text, const int insertPos, const bool undoable)
  35555. {
  35556. if (text.isEmpty())
  35557. return;
  35558. if (undoable)
  35559. {
  35560. undoManager.perform (new CodeDocumentInsertAction (*this, text, insertPos));
  35561. }
  35562. else
  35563. {
  35564. Position pos (this, insertPos);
  35565. const int firstAffectedLine = pos.getLineNumber();
  35566. int lastAffectedLine = firstAffectedLine + 1;
  35567. CodeDocumentLine* const firstLine = lines [firstAffectedLine];
  35568. String textInsideOriginalLine (text);
  35569. if (firstLine != 0)
  35570. {
  35571. const int index = pos.getIndexInLine();
  35572. textInsideOriginalLine = firstLine->line.substring (0, index)
  35573. + textInsideOriginalLine
  35574. + firstLine->line.substring (index);
  35575. }
  35576. maximumLineLength = -1;
  35577. Array <CodeDocumentLine*> newLines;
  35578. CodeDocumentLine::createLines (newLines, textInsideOriginalLine);
  35579. jassert (newLines.size() > 0);
  35580. CodeDocumentLine* const newFirstLine = newLines.getUnchecked (0);
  35581. newFirstLine->lineStartInFile = firstLine != 0 ? firstLine->lineStartInFile : 0;
  35582. lines.set (firstAffectedLine, newFirstLine);
  35583. if (newLines.size() > 1)
  35584. {
  35585. for (int i = 1; i < newLines.size(); ++i)
  35586. {
  35587. CodeDocumentLine* const l = newLines.getUnchecked (i);
  35588. lines.insert (firstAffectedLine + i, l);
  35589. }
  35590. lastAffectedLine = lines.size();
  35591. }
  35592. int i, lineStart = newFirstLine->lineStartInFile;
  35593. for (i = firstAffectedLine; i < lines.size(); ++i)
  35594. {
  35595. CodeDocumentLine* const l = lines.getUnchecked (i);
  35596. l->lineStartInFile = lineStart;
  35597. lineStart += l->lineLength;
  35598. }
  35599. checkLastLineStatus();
  35600. const int newTextLength = text.length();
  35601. for (i = 0; i < positionsToMaintain.size(); ++i)
  35602. {
  35603. CodeDocument::Position* const p = positionsToMaintain.getUnchecked(i);
  35604. if (p->getPosition() >= insertPos)
  35605. p->setPosition (p->getPosition() + newTextLength);
  35606. }
  35607. sendListenerChangeMessage (firstAffectedLine, lastAffectedLine);
  35608. }
  35609. }
  35610. class CodeDocumentDeleteAction : public UndoableAction
  35611. {
  35612. CodeDocument& owner;
  35613. int startPos, endPos;
  35614. String removedText;
  35615. CodeDocumentDeleteAction (const CodeDocumentDeleteAction&);
  35616. CodeDocumentDeleteAction& operator= (const CodeDocumentDeleteAction&);
  35617. public:
  35618. CodeDocumentDeleteAction (CodeDocument& owner_, const int startPos_, const int endPos_) throw()
  35619. : owner (owner_),
  35620. startPos (startPos_),
  35621. endPos (endPos_)
  35622. {
  35623. removedText = owner.getTextBetween (CodeDocument::Position (&owner, startPos),
  35624. CodeDocument::Position (&owner, endPos));
  35625. }
  35626. ~CodeDocumentDeleteAction() {}
  35627. bool perform()
  35628. {
  35629. owner.currentActionIndex++;
  35630. owner.remove (startPos, endPos, false);
  35631. return true;
  35632. }
  35633. bool undo()
  35634. {
  35635. owner.currentActionIndex--;
  35636. owner.insert (removedText, startPos, false);
  35637. return true;
  35638. }
  35639. int getSizeInUnits() { return removedText.length() + 32; }
  35640. };
  35641. void CodeDocument::remove (const int startPos, const int endPos, const bool undoable)
  35642. {
  35643. if (endPos <= startPos)
  35644. return;
  35645. if (undoable)
  35646. {
  35647. undoManager.perform (new CodeDocumentDeleteAction (*this, startPos, endPos));
  35648. }
  35649. else
  35650. {
  35651. Position startPosition (this, startPos);
  35652. Position endPosition (this, endPos);
  35653. maximumLineLength = -1;
  35654. const int firstAffectedLine = startPosition.getLineNumber();
  35655. const int endLine = endPosition.getLineNumber();
  35656. int lastAffectedLine = firstAffectedLine + 1;
  35657. CodeDocumentLine* const firstLine = lines.getUnchecked (firstAffectedLine);
  35658. if (firstAffectedLine == endLine)
  35659. {
  35660. firstLine->line = firstLine->line.substring (0, startPosition.getIndexInLine())
  35661. + firstLine->line.substring (endPosition.getIndexInLine());
  35662. firstLine->updateLength();
  35663. }
  35664. else
  35665. {
  35666. lastAffectedLine = lines.size();
  35667. CodeDocumentLine* const lastLine = lines.getUnchecked (endLine);
  35668. jassert (lastLine != 0);
  35669. firstLine->line = firstLine->line.substring (0, startPosition.getIndexInLine())
  35670. + lastLine->line.substring (endPosition.getIndexInLine());
  35671. firstLine->updateLength();
  35672. int numLinesToRemove = endLine - firstAffectedLine;
  35673. lines.removeRange (firstAffectedLine + 1, numLinesToRemove);
  35674. }
  35675. int i;
  35676. for (i = firstAffectedLine + 1; i < lines.size(); ++i)
  35677. {
  35678. CodeDocumentLine* const l = lines.getUnchecked (i);
  35679. const CodeDocumentLine* const previousLine = lines.getUnchecked (i - 1);
  35680. l->lineStartInFile = previousLine->lineStartInFile + previousLine->lineLength;
  35681. }
  35682. checkLastLineStatus();
  35683. const int totalChars = getNumCharacters();
  35684. for (i = 0; i < positionsToMaintain.size(); ++i)
  35685. {
  35686. CodeDocument::Position* p = positionsToMaintain.getUnchecked(i);
  35687. if (p->getPosition() > startPosition.getPosition())
  35688. p->setPosition (jmax (startPos, p->getPosition() + startPos - endPos));
  35689. if (p->getPosition() > totalChars)
  35690. p->setPosition (totalChars);
  35691. }
  35692. sendListenerChangeMessage (firstAffectedLine, lastAffectedLine);
  35693. }
  35694. }
  35695. END_JUCE_NAMESPACE
  35696. /*** End of inlined file: juce_CodeDocument.cpp ***/
  35697. /*** Start of inlined file: juce_CodeEditorComponent.cpp ***/
  35698. BEGIN_JUCE_NAMESPACE
  35699. class CodeEditorComponent::CaretComponent : public Component,
  35700. public Timer
  35701. {
  35702. public:
  35703. CaretComponent (CodeEditorComponent& owner_)
  35704. : owner (owner_)
  35705. {
  35706. setAlwaysOnTop (true);
  35707. setInterceptsMouseClicks (false, false);
  35708. }
  35709. ~CaretComponent()
  35710. {
  35711. }
  35712. void paint (Graphics& g)
  35713. {
  35714. g.fillAll (findColour (CodeEditorComponent::caretColourId));
  35715. }
  35716. void timerCallback()
  35717. {
  35718. setVisible (shouldBeShown() && ! isVisible());
  35719. }
  35720. void updatePosition()
  35721. {
  35722. startTimer (400);
  35723. setVisible (shouldBeShown());
  35724. setBounds (owner.getCharacterBounds (owner.getCaretPos()).withWidth (2));
  35725. }
  35726. private:
  35727. CodeEditorComponent& owner;
  35728. CaretComponent (const CaretComponent&);
  35729. CaretComponent& operator= (const CaretComponent&);
  35730. bool shouldBeShown() const { return owner.hasKeyboardFocus (true); }
  35731. };
  35732. class CodeEditorComponent::CodeEditorLine
  35733. {
  35734. public:
  35735. CodeEditorLine() throw()
  35736. : highlightColumnStart (0), highlightColumnEnd (0)
  35737. {
  35738. }
  35739. ~CodeEditorLine() throw()
  35740. {
  35741. }
  35742. bool update (CodeDocument& document, int lineNum,
  35743. CodeDocument::Iterator& source,
  35744. CodeTokeniser* analyser, const int spacesPerTab,
  35745. const CodeDocument::Position& selectionStart,
  35746. const CodeDocument::Position& selectionEnd)
  35747. {
  35748. Array <SyntaxToken> newTokens;
  35749. newTokens.ensureStorageAllocated (8);
  35750. if (analyser == 0)
  35751. {
  35752. newTokens.add (SyntaxToken (document.getLine (lineNum), -1));
  35753. }
  35754. else if (lineNum < document.getNumLines())
  35755. {
  35756. const CodeDocument::Position pos (&document, lineNum, 0);
  35757. createTokens (pos.getPosition(), pos.getLineText(),
  35758. source, analyser, newTokens);
  35759. }
  35760. replaceTabsWithSpaces (newTokens, spacesPerTab);
  35761. int newHighlightStart = 0;
  35762. int newHighlightEnd = 0;
  35763. if (selectionStart.getLineNumber() <= lineNum && selectionEnd.getLineNumber() >= lineNum)
  35764. {
  35765. const String line (document.getLine (lineNum));
  35766. CodeDocument::Position lineStart (&document, lineNum, 0), lineEnd (&document, lineNum + 1, 0);
  35767. newHighlightStart = indexToColumn (jmax (0, selectionStart.getPosition() - lineStart.getPosition()),
  35768. line, spacesPerTab);
  35769. newHighlightEnd = indexToColumn (jmin (lineEnd.getPosition() - lineStart.getPosition(), selectionEnd.getPosition() - lineStart.getPosition()),
  35770. line, spacesPerTab);
  35771. }
  35772. if (newHighlightStart != highlightColumnStart || newHighlightEnd != highlightColumnEnd)
  35773. {
  35774. highlightColumnStart = newHighlightStart;
  35775. highlightColumnEnd = newHighlightEnd;
  35776. }
  35777. else
  35778. {
  35779. if (tokens.size() == newTokens.size())
  35780. {
  35781. bool allTheSame = true;
  35782. for (int i = newTokens.size(); --i >= 0;)
  35783. {
  35784. if (tokens.getReference(i) != newTokens.getReference(i))
  35785. {
  35786. allTheSame = false;
  35787. break;
  35788. }
  35789. }
  35790. if (allTheSame)
  35791. return false;
  35792. }
  35793. }
  35794. tokens.swapWithArray (newTokens);
  35795. return true;
  35796. }
  35797. void draw (CodeEditorComponent& owner, Graphics& g, const Font& font,
  35798. float x, const int y, const int baselineOffset, const int lineHeight,
  35799. const Colour& highlightColour) const throw()
  35800. {
  35801. if (highlightColumnStart < highlightColumnEnd)
  35802. {
  35803. g.setColour (highlightColour);
  35804. g.fillRect (roundToInt (x + highlightColumnStart * owner.getCharWidth()), y,
  35805. roundToInt ((highlightColumnEnd - highlightColumnStart) * owner.getCharWidth()), lineHeight);
  35806. }
  35807. int lastType = std::numeric_limits<int>::min();
  35808. for (int i = 0; i < tokens.size(); ++i)
  35809. {
  35810. SyntaxToken& token = tokens.getReference(i);
  35811. if (lastType != token.tokenType)
  35812. {
  35813. lastType = token.tokenType;
  35814. g.setColour (owner.getColourForTokenType (lastType));
  35815. }
  35816. g.drawSingleLineText (token.text, roundToInt (x), y + baselineOffset);
  35817. if (i < tokens.size() - 1)
  35818. {
  35819. if (token.width < 0)
  35820. token.width = font.getStringWidthFloat (token.text);
  35821. x += token.width;
  35822. }
  35823. }
  35824. }
  35825. private:
  35826. struct SyntaxToken
  35827. {
  35828. String text;
  35829. int tokenType;
  35830. float width;
  35831. SyntaxToken (const String& text_, const int type) throw()
  35832. : text (text_), tokenType (type), width (-1.0f)
  35833. {
  35834. }
  35835. bool operator!= (const SyntaxToken& other) const throw()
  35836. {
  35837. return text != other.text || tokenType != other.tokenType;
  35838. }
  35839. };
  35840. Array <SyntaxToken> tokens;
  35841. int highlightColumnStart, highlightColumnEnd;
  35842. static void createTokens (int startPosition, const String& lineText,
  35843. CodeDocument::Iterator& source,
  35844. CodeTokeniser* analyser,
  35845. Array <SyntaxToken>& newTokens)
  35846. {
  35847. CodeDocument::Iterator lastIterator (source);
  35848. const int lineLength = lineText.length();
  35849. for (;;)
  35850. {
  35851. int tokenType = analyser->readNextToken (source);
  35852. int tokenStart = lastIterator.getPosition();
  35853. int tokenEnd = source.getPosition();
  35854. if (tokenEnd <= tokenStart)
  35855. break;
  35856. tokenEnd -= startPosition;
  35857. if (tokenEnd > 0)
  35858. {
  35859. tokenStart -= startPosition;
  35860. newTokens.add (SyntaxToken (lineText.substring (jmax (0, tokenStart), tokenEnd),
  35861. tokenType));
  35862. if (tokenEnd >= lineLength)
  35863. break;
  35864. }
  35865. lastIterator = source;
  35866. }
  35867. source = lastIterator;
  35868. }
  35869. static void replaceTabsWithSpaces (Array <SyntaxToken>& tokens, const int spacesPerTab) throw()
  35870. {
  35871. int x = 0;
  35872. for (int i = 0; i < tokens.size(); ++i)
  35873. {
  35874. SyntaxToken& t = tokens.getReference(i);
  35875. for (;;)
  35876. {
  35877. int tabPos = t.text.indexOfChar ('\t');
  35878. if (tabPos < 0)
  35879. break;
  35880. const int spacesNeeded = spacesPerTab - ((tabPos + x) % spacesPerTab);
  35881. t.text = t.text.replaceSection (tabPos, 1, String::repeatedString (" ", spacesNeeded));
  35882. }
  35883. x += t.text.length();
  35884. }
  35885. }
  35886. int indexToColumn (int index, const String& line, int spacesPerTab) const throw()
  35887. {
  35888. jassert (index <= line.length());
  35889. int col = 0;
  35890. for (int i = 0; i < index; ++i)
  35891. {
  35892. if (line[i] != '\t')
  35893. ++col;
  35894. else
  35895. col += spacesPerTab - (col % spacesPerTab);
  35896. }
  35897. return col;
  35898. }
  35899. };
  35900. CodeEditorComponent::CodeEditorComponent (CodeDocument& document_,
  35901. CodeTokeniser* const codeTokeniser_)
  35902. : document (document_),
  35903. firstLineOnScreen (0),
  35904. gutter (5),
  35905. spacesPerTab (4),
  35906. lineHeight (0),
  35907. linesOnScreen (0),
  35908. columnsOnScreen (0),
  35909. scrollbarThickness (16),
  35910. columnToTryToMaintain (-1),
  35911. useSpacesForTabs (false),
  35912. xOffset (0),
  35913. codeTokeniser (codeTokeniser_)
  35914. {
  35915. caretPos = CodeDocument::Position (&document_, 0, 0);
  35916. caretPos.setPositionMaintained (true);
  35917. selectionStart = CodeDocument::Position (&document_, 0, 0);
  35918. selectionStart.setPositionMaintained (true);
  35919. selectionEnd = CodeDocument::Position (&document_, 0, 0);
  35920. selectionEnd.setPositionMaintained (true);
  35921. setOpaque (true);
  35922. setMouseCursor (MouseCursor (MouseCursor::IBeamCursor));
  35923. setWantsKeyboardFocus (true);
  35924. addAndMakeVisible (verticalScrollBar = new ScrollBar (true));
  35925. verticalScrollBar->setSingleStepSize (1.0);
  35926. addAndMakeVisible (horizontalScrollBar = new ScrollBar (false));
  35927. horizontalScrollBar->setSingleStepSize (1.0);
  35928. addAndMakeVisible (caret = new CaretComponent (*this));
  35929. Font f (12.0f);
  35930. f.setTypefaceName (Font::getDefaultMonospacedFontName());
  35931. setFont (f);
  35932. resetToDefaultColours();
  35933. verticalScrollBar->addListener (this);
  35934. horizontalScrollBar->addListener (this);
  35935. document.addListener (this);
  35936. }
  35937. CodeEditorComponent::~CodeEditorComponent()
  35938. {
  35939. document.removeListener (this);
  35940. deleteAllChildren();
  35941. }
  35942. void CodeEditorComponent::loadContent (const String& newContent)
  35943. {
  35944. clearCachedIterators (0);
  35945. document.replaceAllContent (newContent);
  35946. document.clearUndoHistory();
  35947. document.setSavePoint();
  35948. caretPos.setPosition (0);
  35949. selectionStart.setPosition (0);
  35950. selectionEnd.setPosition (0);
  35951. scrollToLine (0);
  35952. }
  35953. bool CodeEditorComponent::isTextInputActive() const
  35954. {
  35955. return true;
  35956. }
  35957. void CodeEditorComponent::codeDocumentChanged (const CodeDocument::Position& affectedTextStart,
  35958. const CodeDocument::Position& affectedTextEnd)
  35959. {
  35960. clearCachedIterators (affectedTextStart.getLineNumber());
  35961. triggerAsyncUpdate();
  35962. caret->updatePosition();
  35963. columnToTryToMaintain = -1;
  35964. if (affectedTextEnd.getPosition() >= selectionStart.getPosition()
  35965. && affectedTextStart.getPosition() <= selectionEnd.getPosition())
  35966. deselectAll();
  35967. if (caretPos.getPosition() > affectedTextEnd.getPosition()
  35968. || caretPos.getPosition() < affectedTextStart.getPosition())
  35969. moveCaretTo (affectedTextStart, false);
  35970. updateScrollBars();
  35971. }
  35972. void CodeEditorComponent::resized()
  35973. {
  35974. linesOnScreen = (getHeight() - scrollbarThickness) / lineHeight;
  35975. columnsOnScreen = (int) ((getWidth() - scrollbarThickness) / charWidth);
  35976. lines.clear();
  35977. rebuildLineTokens();
  35978. caret->updatePosition();
  35979. verticalScrollBar->setBounds (getWidth() - scrollbarThickness, 0, scrollbarThickness, getHeight() - scrollbarThickness);
  35980. horizontalScrollBar->setBounds (gutter, getHeight() - scrollbarThickness, getWidth() - scrollbarThickness - gutter, scrollbarThickness);
  35981. updateScrollBars();
  35982. }
  35983. void CodeEditorComponent::paint (Graphics& g)
  35984. {
  35985. handleUpdateNowIfNeeded();
  35986. g.fillAll (findColour (CodeEditorComponent::backgroundColourId));
  35987. g.reduceClipRegion (gutter, 0, verticalScrollBar->getX() - gutter, horizontalScrollBar->getY());
  35988. g.setFont (font);
  35989. const int baselineOffset = (int) font.getAscent();
  35990. const Colour defaultColour (findColour (CodeEditorComponent::defaultTextColourId));
  35991. const Colour highlightColour (findColour (CodeEditorComponent::highlightColourId));
  35992. const Rectangle<int> clip (g.getClipBounds());
  35993. const int firstLineToDraw = jmax (0, clip.getY() / lineHeight);
  35994. const int lastLineToDraw = jmin (lines.size(), clip.getBottom() / lineHeight + 1);
  35995. for (int j = firstLineToDraw; j < lastLineToDraw; ++j)
  35996. {
  35997. lines.getUnchecked(j)->draw (*this, g, font,
  35998. (float) (gutter - xOffset * charWidth),
  35999. lineHeight * j, baselineOffset, lineHeight,
  36000. highlightColour);
  36001. }
  36002. }
  36003. void CodeEditorComponent::setScrollbarThickness (const int thickness) throw()
  36004. {
  36005. if (scrollbarThickness != thickness)
  36006. {
  36007. scrollbarThickness = thickness;
  36008. resized();
  36009. }
  36010. }
  36011. void CodeEditorComponent::handleAsyncUpdate()
  36012. {
  36013. rebuildLineTokens();
  36014. }
  36015. void CodeEditorComponent::rebuildLineTokens()
  36016. {
  36017. cancelPendingUpdate();
  36018. const int numNeeded = linesOnScreen + 1;
  36019. int minLineToRepaint = numNeeded;
  36020. int maxLineToRepaint = 0;
  36021. if (numNeeded != lines.size())
  36022. {
  36023. lines.clear();
  36024. for (int i = numNeeded; --i >= 0;)
  36025. lines.add (new CodeEditorLine());
  36026. minLineToRepaint = 0;
  36027. maxLineToRepaint = numNeeded;
  36028. }
  36029. jassert (numNeeded == lines.size());
  36030. CodeDocument::Iterator source (&document);
  36031. getIteratorForPosition (CodeDocument::Position (&document, firstLineOnScreen, 0).getPosition(), source);
  36032. for (int i = 0; i < numNeeded; ++i)
  36033. {
  36034. CodeEditorLine* const line = lines.getUnchecked(i);
  36035. if (line->update (document, firstLineOnScreen + i, source, codeTokeniser, spacesPerTab,
  36036. selectionStart, selectionEnd))
  36037. {
  36038. minLineToRepaint = jmin (minLineToRepaint, i);
  36039. maxLineToRepaint = jmax (maxLineToRepaint, i);
  36040. }
  36041. }
  36042. if (minLineToRepaint <= maxLineToRepaint)
  36043. {
  36044. repaint (gutter, lineHeight * minLineToRepaint - 1,
  36045. verticalScrollBar->getX() - gutter,
  36046. lineHeight * (1 + maxLineToRepaint - minLineToRepaint) + 2);
  36047. }
  36048. }
  36049. void CodeEditorComponent::moveCaretTo (const CodeDocument::Position& newPos, const bool highlighting)
  36050. {
  36051. caretPos = newPos;
  36052. columnToTryToMaintain = -1;
  36053. if (highlighting)
  36054. {
  36055. if (dragType == notDragging)
  36056. {
  36057. if (abs (caretPos.getPosition() - selectionStart.getPosition())
  36058. < abs (caretPos.getPosition() - selectionEnd.getPosition()))
  36059. dragType = draggingSelectionStart;
  36060. else
  36061. dragType = draggingSelectionEnd;
  36062. }
  36063. if (dragType == draggingSelectionStart)
  36064. {
  36065. selectionStart = caretPos;
  36066. if (selectionEnd.getPosition() < selectionStart.getPosition())
  36067. {
  36068. const CodeDocument::Position temp (selectionStart);
  36069. selectionStart = selectionEnd;
  36070. selectionEnd = temp;
  36071. dragType = draggingSelectionEnd;
  36072. }
  36073. }
  36074. else
  36075. {
  36076. selectionEnd = caretPos;
  36077. if (selectionEnd.getPosition() < selectionStart.getPosition())
  36078. {
  36079. const CodeDocument::Position temp (selectionStart);
  36080. selectionStart = selectionEnd;
  36081. selectionEnd = temp;
  36082. dragType = draggingSelectionStart;
  36083. }
  36084. }
  36085. triggerAsyncUpdate();
  36086. }
  36087. else
  36088. {
  36089. deselectAll();
  36090. }
  36091. caret->updatePosition();
  36092. scrollToKeepCaretOnScreen();
  36093. updateScrollBars();
  36094. }
  36095. void CodeEditorComponent::deselectAll()
  36096. {
  36097. if (selectionStart != selectionEnd)
  36098. triggerAsyncUpdate();
  36099. selectionStart = caretPos;
  36100. selectionEnd = caretPos;
  36101. }
  36102. void CodeEditorComponent::updateScrollBars()
  36103. {
  36104. verticalScrollBar->setRangeLimits (0, jmax (document.getNumLines(), firstLineOnScreen + linesOnScreen));
  36105. verticalScrollBar->setCurrentRange (firstLineOnScreen, linesOnScreen);
  36106. horizontalScrollBar->setRangeLimits (0, jmax ((double) document.getMaximumLineLength(), xOffset + columnsOnScreen));
  36107. horizontalScrollBar->setCurrentRange (xOffset, columnsOnScreen);
  36108. }
  36109. void CodeEditorComponent::scrollToLineInternal (int newFirstLineOnScreen)
  36110. {
  36111. newFirstLineOnScreen = jlimit (0, jmax (0, document.getNumLines() - 1),
  36112. newFirstLineOnScreen);
  36113. if (newFirstLineOnScreen != firstLineOnScreen)
  36114. {
  36115. firstLineOnScreen = newFirstLineOnScreen;
  36116. caret->updatePosition();
  36117. updateCachedIterators (firstLineOnScreen);
  36118. triggerAsyncUpdate();
  36119. }
  36120. }
  36121. void CodeEditorComponent::scrollToColumnInternal (double column)
  36122. {
  36123. const double newOffset = jlimit (0.0, document.getMaximumLineLength() + 3.0, column);
  36124. if (xOffset != newOffset)
  36125. {
  36126. xOffset = newOffset;
  36127. caret->updatePosition();
  36128. repaint();
  36129. }
  36130. }
  36131. void CodeEditorComponent::scrollToLine (int newFirstLineOnScreen)
  36132. {
  36133. scrollToLineInternal (newFirstLineOnScreen);
  36134. updateScrollBars();
  36135. }
  36136. void CodeEditorComponent::scrollToColumn (int newFirstColumnOnScreen)
  36137. {
  36138. scrollToColumnInternal (newFirstColumnOnScreen);
  36139. updateScrollBars();
  36140. }
  36141. void CodeEditorComponent::scrollBy (int deltaLines)
  36142. {
  36143. scrollToLine (firstLineOnScreen + deltaLines);
  36144. }
  36145. void CodeEditorComponent::scrollToKeepCaretOnScreen()
  36146. {
  36147. if (caretPos.getLineNumber() < firstLineOnScreen)
  36148. scrollBy (caretPos.getLineNumber() - firstLineOnScreen);
  36149. else if (caretPos.getLineNumber() >= firstLineOnScreen + linesOnScreen)
  36150. scrollBy (caretPos.getLineNumber() - (firstLineOnScreen + linesOnScreen - 1));
  36151. const int column = indexToColumn (caretPos.getLineNumber(), caretPos.getIndexInLine());
  36152. if (column >= xOffset + columnsOnScreen - 1)
  36153. scrollToColumn (column + 1 - columnsOnScreen);
  36154. else if (column < xOffset)
  36155. scrollToColumn (column);
  36156. }
  36157. const Rectangle<int> CodeEditorComponent::getCharacterBounds (const CodeDocument::Position& pos) const throw()
  36158. {
  36159. return Rectangle<int> (roundToInt ((gutter - xOffset * charWidth) + indexToColumn (pos.getLineNumber(), pos.getIndexInLine()) * charWidth),
  36160. (pos.getLineNumber() - firstLineOnScreen) * lineHeight,
  36161. roundToInt (charWidth),
  36162. lineHeight);
  36163. }
  36164. const CodeDocument::Position CodeEditorComponent::getPositionAt (int x, int y)
  36165. {
  36166. const int line = y / lineHeight + firstLineOnScreen;
  36167. const int column = roundToInt ((x - (gutter - xOffset * charWidth)) / charWidth);
  36168. const int index = columnToIndex (line, column);
  36169. return CodeDocument::Position (&document, line, index);
  36170. }
  36171. void CodeEditorComponent::insertTextAtCaret (const String& newText)
  36172. {
  36173. document.deleteSection (selectionStart, selectionEnd);
  36174. if (newText.isNotEmpty())
  36175. document.insertText (caretPos, newText);
  36176. scrollToKeepCaretOnScreen();
  36177. }
  36178. void CodeEditorComponent::insertTabAtCaret()
  36179. {
  36180. if (CharacterFunctions::isWhitespace (caretPos.getCharacter())
  36181. && caretPos.getLineNumber() == caretPos.movedBy (1).getLineNumber())
  36182. {
  36183. moveCaretTo (document.findWordBreakAfter (caretPos), false);
  36184. }
  36185. if (useSpacesForTabs)
  36186. {
  36187. const int caretCol = indexToColumn (caretPos.getLineNumber(), caretPos.getIndexInLine());
  36188. const int spacesNeeded = spacesPerTab - (caretCol % spacesPerTab);
  36189. insertTextAtCaret (String::repeatedString (" ", spacesNeeded));
  36190. }
  36191. else
  36192. {
  36193. insertTextAtCaret ("\t");
  36194. }
  36195. }
  36196. void CodeEditorComponent::cut()
  36197. {
  36198. insertTextAtCaret (String::empty);
  36199. }
  36200. void CodeEditorComponent::copy()
  36201. {
  36202. newTransaction();
  36203. const String selection (document.getTextBetween (selectionStart, selectionEnd));
  36204. if (selection.isNotEmpty())
  36205. SystemClipboard::copyTextToClipboard (selection);
  36206. }
  36207. void CodeEditorComponent::copyThenCut()
  36208. {
  36209. copy();
  36210. cut();
  36211. newTransaction();
  36212. }
  36213. void CodeEditorComponent::paste()
  36214. {
  36215. newTransaction();
  36216. const String clip (SystemClipboard::getTextFromClipboard());
  36217. if (clip.isNotEmpty())
  36218. insertTextAtCaret (clip);
  36219. newTransaction();
  36220. }
  36221. void CodeEditorComponent::cursorLeft (const bool moveInWholeWordSteps, const bool selecting)
  36222. {
  36223. newTransaction();
  36224. if (moveInWholeWordSteps)
  36225. moveCaretTo (document.findWordBreakBefore (caretPos), selecting);
  36226. else
  36227. moveCaretTo (caretPos.movedBy (-1), selecting);
  36228. }
  36229. void CodeEditorComponent::cursorRight (const bool moveInWholeWordSteps, const bool selecting)
  36230. {
  36231. newTransaction();
  36232. if (moveInWholeWordSteps)
  36233. moveCaretTo (document.findWordBreakAfter (caretPos), selecting);
  36234. else
  36235. moveCaretTo (caretPos.movedBy (1), selecting);
  36236. }
  36237. void CodeEditorComponent::moveLineDelta (const int delta, const bool selecting)
  36238. {
  36239. CodeDocument::Position pos (caretPos);
  36240. const int newLineNum = pos.getLineNumber() + delta;
  36241. if (columnToTryToMaintain < 0)
  36242. columnToTryToMaintain = indexToColumn (pos.getLineNumber(), pos.getIndexInLine());
  36243. pos.setLineAndIndex (newLineNum, columnToIndex (newLineNum, columnToTryToMaintain));
  36244. const int colToMaintain = columnToTryToMaintain;
  36245. moveCaretTo (pos, selecting);
  36246. columnToTryToMaintain = colToMaintain;
  36247. }
  36248. void CodeEditorComponent::cursorDown (const bool selecting)
  36249. {
  36250. newTransaction();
  36251. if (caretPos.getLineNumber() == document.getNumLines() - 1)
  36252. moveCaretTo (CodeDocument::Position (&document, std::numeric_limits<int>::max(), std::numeric_limits<int>::max()), selecting);
  36253. else
  36254. moveLineDelta (1, selecting);
  36255. }
  36256. void CodeEditorComponent::cursorUp (const bool selecting)
  36257. {
  36258. newTransaction();
  36259. if (caretPos.getLineNumber() == 0)
  36260. moveCaretTo (CodeDocument::Position (&document, 0, 0), selecting);
  36261. else
  36262. moveLineDelta (-1, selecting);
  36263. }
  36264. void CodeEditorComponent::pageDown (const bool selecting)
  36265. {
  36266. newTransaction();
  36267. scrollBy (jlimit (0, linesOnScreen, 1 + document.getNumLines() - firstLineOnScreen - linesOnScreen));
  36268. moveLineDelta (linesOnScreen, selecting);
  36269. }
  36270. void CodeEditorComponent::pageUp (const bool selecting)
  36271. {
  36272. newTransaction();
  36273. scrollBy (-linesOnScreen);
  36274. moveLineDelta (-linesOnScreen, selecting);
  36275. }
  36276. void CodeEditorComponent::scrollUp()
  36277. {
  36278. newTransaction();
  36279. scrollBy (1);
  36280. if (caretPos.getLineNumber() < firstLineOnScreen)
  36281. moveLineDelta (1, false);
  36282. }
  36283. void CodeEditorComponent::scrollDown()
  36284. {
  36285. newTransaction();
  36286. scrollBy (-1);
  36287. if (caretPos.getLineNumber() >= firstLineOnScreen + linesOnScreen)
  36288. moveLineDelta (-1, false);
  36289. }
  36290. void CodeEditorComponent::goToStartOfDocument (const bool selecting)
  36291. {
  36292. newTransaction();
  36293. moveCaretTo (CodeDocument::Position (&document, 0, 0), selecting);
  36294. }
  36295. static int findFirstNonWhitespaceChar (const String& line) throw()
  36296. {
  36297. const int len = line.length();
  36298. for (int i = 0; i < len; ++i)
  36299. if (! CharacterFunctions::isWhitespace (line [i]))
  36300. return i;
  36301. return 0;
  36302. }
  36303. void CodeEditorComponent::goToStartOfLine (const bool selecting)
  36304. {
  36305. newTransaction();
  36306. int index = findFirstNonWhitespaceChar (caretPos.getLineText());
  36307. if (index >= caretPos.getIndexInLine() && caretPos.getIndexInLine() > 0)
  36308. index = 0;
  36309. moveCaretTo (CodeDocument::Position (&document, caretPos.getLineNumber(), index), selecting);
  36310. }
  36311. void CodeEditorComponent::goToEndOfDocument (const bool selecting)
  36312. {
  36313. newTransaction();
  36314. moveCaretTo (CodeDocument::Position (&document, std::numeric_limits<int>::max(), std::numeric_limits<int>::max()), selecting);
  36315. }
  36316. void CodeEditorComponent::goToEndOfLine (const bool selecting)
  36317. {
  36318. newTransaction();
  36319. moveCaretTo (CodeDocument::Position (&document, caretPos.getLineNumber(), std::numeric_limits<int>::max()), selecting);
  36320. }
  36321. void CodeEditorComponent::backspace (const bool moveInWholeWordSteps)
  36322. {
  36323. if (moveInWholeWordSteps)
  36324. {
  36325. cut(); // in case something is already highlighted
  36326. moveCaretTo (document.findWordBreakBefore (caretPos), true);
  36327. }
  36328. else
  36329. {
  36330. if (selectionStart == selectionEnd)
  36331. selectionStart.moveBy (-1);
  36332. }
  36333. cut();
  36334. }
  36335. void CodeEditorComponent::deleteForward (const bool moveInWholeWordSteps)
  36336. {
  36337. if (moveInWholeWordSteps)
  36338. {
  36339. cut(); // in case something is already highlighted
  36340. moveCaretTo (document.findWordBreakAfter (caretPos), true);
  36341. }
  36342. else
  36343. {
  36344. if (selectionStart == selectionEnd)
  36345. selectionEnd.moveBy (1);
  36346. else
  36347. newTransaction();
  36348. }
  36349. cut();
  36350. }
  36351. void CodeEditorComponent::selectAll()
  36352. {
  36353. newTransaction();
  36354. moveCaretTo (CodeDocument::Position (&document, std::numeric_limits<int>::max(), std::numeric_limits<int>::max()), false);
  36355. moveCaretTo (CodeDocument::Position (&document, 0, 0), true);
  36356. }
  36357. void CodeEditorComponent::undo()
  36358. {
  36359. document.undo();
  36360. scrollToKeepCaretOnScreen();
  36361. }
  36362. void CodeEditorComponent::redo()
  36363. {
  36364. document.redo();
  36365. scrollToKeepCaretOnScreen();
  36366. }
  36367. void CodeEditorComponent::newTransaction()
  36368. {
  36369. document.newTransaction();
  36370. startTimer (600);
  36371. }
  36372. void CodeEditorComponent::timerCallback()
  36373. {
  36374. newTransaction();
  36375. }
  36376. const Range<int> CodeEditorComponent::getHighlightedRegion() const
  36377. {
  36378. return Range<int> (selectionStart.getPosition(), selectionEnd.getPosition());
  36379. }
  36380. void CodeEditorComponent::setHighlightedRegion (const Range<int>& newRange)
  36381. {
  36382. moveCaretTo (CodeDocument::Position (&document, newRange.getStart()), false);
  36383. moveCaretTo (CodeDocument::Position (&document, newRange.getEnd()), true);
  36384. }
  36385. const String CodeEditorComponent::getTextInRange (const Range<int>& range) const
  36386. {
  36387. return document.getTextBetween (CodeDocument::Position (&document, range.getStart()),
  36388. CodeDocument::Position (&document, range.getEnd()));
  36389. }
  36390. bool CodeEditorComponent::keyPressed (const KeyPress& key)
  36391. {
  36392. const bool moveInWholeWordSteps = key.getModifiers().isCtrlDown() || key.getModifiers().isAltDown();
  36393. const bool shiftDown = key.getModifiers().isShiftDown();
  36394. if (key.isKeyCode (KeyPress::leftKey))
  36395. {
  36396. cursorLeft (moveInWholeWordSteps, shiftDown);
  36397. }
  36398. else if (key.isKeyCode (KeyPress::rightKey))
  36399. {
  36400. cursorRight (moveInWholeWordSteps, shiftDown);
  36401. }
  36402. else if (key.isKeyCode (KeyPress::upKey))
  36403. {
  36404. if (key.getModifiers().isCtrlDown() && ! shiftDown)
  36405. scrollDown();
  36406. #if JUCE_MAC
  36407. else if (key.getModifiers().isCommandDown())
  36408. goToStartOfDocument (shiftDown);
  36409. #endif
  36410. else
  36411. cursorUp (shiftDown);
  36412. }
  36413. else if (key.isKeyCode (KeyPress::downKey))
  36414. {
  36415. if (key.getModifiers().isCtrlDown() && ! shiftDown)
  36416. scrollUp();
  36417. #if JUCE_MAC
  36418. else if (key.getModifiers().isCommandDown())
  36419. goToEndOfDocument (shiftDown);
  36420. #endif
  36421. else
  36422. cursorDown (shiftDown);
  36423. }
  36424. else if (key.isKeyCode (KeyPress::pageDownKey))
  36425. {
  36426. pageDown (shiftDown);
  36427. }
  36428. else if (key.isKeyCode (KeyPress::pageUpKey))
  36429. {
  36430. pageUp (shiftDown);
  36431. }
  36432. else if (key.isKeyCode (KeyPress::homeKey))
  36433. {
  36434. if (moveInWholeWordSteps)
  36435. goToStartOfDocument (shiftDown);
  36436. else
  36437. goToStartOfLine (shiftDown);
  36438. }
  36439. else if (key.isKeyCode (KeyPress::endKey))
  36440. {
  36441. if (moveInWholeWordSteps)
  36442. goToEndOfDocument (shiftDown);
  36443. else
  36444. goToEndOfLine (shiftDown);
  36445. }
  36446. else if (key.isKeyCode (KeyPress::backspaceKey))
  36447. {
  36448. backspace (moveInWholeWordSteps);
  36449. }
  36450. else if (key.isKeyCode (KeyPress::deleteKey))
  36451. {
  36452. deleteForward (moveInWholeWordSteps);
  36453. }
  36454. else if (key == KeyPress ('c', ModifierKeys::commandModifier, 0))
  36455. {
  36456. copy();
  36457. }
  36458. else if (key == KeyPress ('x', ModifierKeys::commandModifier, 0))
  36459. {
  36460. copyThenCut();
  36461. }
  36462. else if (key == KeyPress ('v', ModifierKeys::commandModifier, 0))
  36463. {
  36464. paste();
  36465. }
  36466. else if (key == KeyPress ('z', ModifierKeys::commandModifier, 0))
  36467. {
  36468. undo();
  36469. }
  36470. else if (key == KeyPress ('y', ModifierKeys::commandModifier, 0)
  36471. || key == KeyPress ('z', ModifierKeys::commandModifier | ModifierKeys::shiftModifier, 0))
  36472. {
  36473. redo();
  36474. }
  36475. else if (key == KeyPress ('a', ModifierKeys::commandModifier, 0))
  36476. {
  36477. selectAll();
  36478. }
  36479. else if (key == KeyPress::tabKey || key.getTextCharacter() == '\t')
  36480. {
  36481. insertTabAtCaret();
  36482. }
  36483. else if (key == KeyPress::returnKey)
  36484. {
  36485. newTransaction();
  36486. insertTextAtCaret (document.getNewLineCharacters());
  36487. }
  36488. else if (key.isKeyCode (KeyPress::escapeKey))
  36489. {
  36490. newTransaction();
  36491. }
  36492. else if (key.getTextCharacter() >= ' ')
  36493. {
  36494. insertTextAtCaret (String::charToString (key.getTextCharacter()));
  36495. }
  36496. else
  36497. {
  36498. return false;
  36499. }
  36500. return true;
  36501. }
  36502. void CodeEditorComponent::mouseDown (const MouseEvent& e)
  36503. {
  36504. newTransaction();
  36505. dragType = notDragging;
  36506. if (! e.mods.isPopupMenu())
  36507. {
  36508. beginDragAutoRepeat (100);
  36509. moveCaretTo (getPositionAt (e.x, e.y), e.mods.isShiftDown());
  36510. }
  36511. else
  36512. {
  36513. /*PopupMenu m;
  36514. addPopupMenuItems (m, &e);
  36515. const int result = m.show();
  36516. if (result != 0)
  36517. performPopupMenuAction (result);
  36518. */
  36519. }
  36520. }
  36521. void CodeEditorComponent::mouseDrag (const MouseEvent& e)
  36522. {
  36523. if (! e.mods.isPopupMenu())
  36524. moveCaretTo (getPositionAt (e.x, e.y), true);
  36525. }
  36526. void CodeEditorComponent::mouseUp (const MouseEvent&)
  36527. {
  36528. newTransaction();
  36529. beginDragAutoRepeat (0);
  36530. dragType = notDragging;
  36531. }
  36532. void CodeEditorComponent::mouseDoubleClick (const MouseEvent& e)
  36533. {
  36534. CodeDocument::Position tokenStart (getPositionAt (e.x, e.y));
  36535. CodeDocument::Position tokenEnd (tokenStart);
  36536. if (e.getNumberOfClicks() > 2)
  36537. {
  36538. tokenStart.setLineAndIndex (tokenStart.getLineNumber(), 0);
  36539. tokenEnd.setLineAndIndex (tokenStart.getLineNumber() + 1, 0);
  36540. }
  36541. else
  36542. {
  36543. while (CharacterFunctions::isLetterOrDigit (tokenEnd.getCharacter()))
  36544. tokenEnd.moveBy (1);
  36545. tokenStart = tokenEnd;
  36546. while (tokenStart.getIndexInLine() > 0
  36547. && CharacterFunctions::isLetterOrDigit (tokenStart.movedBy (-1).getCharacter()))
  36548. tokenStart.moveBy (-1);
  36549. }
  36550. moveCaretTo (tokenEnd, false);
  36551. moveCaretTo (tokenStart, true);
  36552. }
  36553. void CodeEditorComponent::mouseWheelMove (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY)
  36554. {
  36555. if ((verticalScrollBar->isVisible() && wheelIncrementY != 0)
  36556. || (horizontalScrollBar->isVisible() && wheelIncrementX != 0))
  36557. {
  36558. verticalScrollBar->mouseWheelMove (e, 0, wheelIncrementY);
  36559. horizontalScrollBar->mouseWheelMove (e, wheelIncrementX, 0);
  36560. }
  36561. else
  36562. {
  36563. Component::mouseWheelMove (e, wheelIncrementX, wheelIncrementY);
  36564. }
  36565. }
  36566. void CodeEditorComponent::scrollBarMoved (ScrollBar* scrollBarThatHasMoved, double newRangeStart)
  36567. {
  36568. if (scrollBarThatHasMoved == verticalScrollBar)
  36569. scrollToLineInternal ((int) newRangeStart);
  36570. else
  36571. scrollToColumnInternal (newRangeStart);
  36572. }
  36573. void CodeEditorComponent::focusGained (FocusChangeType)
  36574. {
  36575. caret->updatePosition();
  36576. }
  36577. void CodeEditorComponent::focusLost (FocusChangeType)
  36578. {
  36579. caret->updatePosition();
  36580. }
  36581. void CodeEditorComponent::setTabSize (const int numSpaces, const bool insertSpaces) throw()
  36582. {
  36583. useSpacesForTabs = insertSpaces;
  36584. if (spacesPerTab != numSpaces)
  36585. {
  36586. spacesPerTab = numSpaces;
  36587. triggerAsyncUpdate();
  36588. }
  36589. }
  36590. int CodeEditorComponent::indexToColumn (int lineNum, int index) const throw()
  36591. {
  36592. const String line (document.getLine (lineNum));
  36593. jassert (index <= line.length());
  36594. int col = 0;
  36595. for (int i = 0; i < index; ++i)
  36596. {
  36597. if (line[i] != '\t')
  36598. ++col;
  36599. else
  36600. col += getTabSize() - (col % getTabSize());
  36601. }
  36602. return col;
  36603. }
  36604. int CodeEditorComponent::columnToIndex (int lineNum, int column) const throw()
  36605. {
  36606. const String line (document.getLine (lineNum));
  36607. const int lineLength = line.length();
  36608. int i, col = 0;
  36609. for (i = 0; i < lineLength; ++i)
  36610. {
  36611. if (line[i] != '\t')
  36612. ++col;
  36613. else
  36614. col += getTabSize() - (col % getTabSize());
  36615. if (col > column)
  36616. break;
  36617. }
  36618. return i;
  36619. }
  36620. void CodeEditorComponent::setFont (const Font& newFont)
  36621. {
  36622. font = newFont;
  36623. charWidth = font.getStringWidthFloat ("0");
  36624. lineHeight = roundToInt (font.getHeight());
  36625. resized();
  36626. }
  36627. void CodeEditorComponent::resetToDefaultColours()
  36628. {
  36629. coloursForTokenCategories.clear();
  36630. if (codeTokeniser != 0)
  36631. {
  36632. for (int i = codeTokeniser->getTokenTypes().size(); --i >= 0;)
  36633. setColourForTokenType (i, codeTokeniser->getDefaultColour (i));
  36634. }
  36635. }
  36636. void CodeEditorComponent::setColourForTokenType (const int tokenType, const Colour& colour)
  36637. {
  36638. jassert (tokenType < 256);
  36639. while (coloursForTokenCategories.size() < tokenType)
  36640. coloursForTokenCategories.add (Colours::black);
  36641. coloursForTokenCategories.set (tokenType, colour);
  36642. repaint();
  36643. }
  36644. const Colour CodeEditorComponent::getColourForTokenType (const int tokenType) const throw()
  36645. {
  36646. if (((unsigned int) tokenType) >= (unsigned int) coloursForTokenCategories.size())
  36647. return findColour (CodeEditorComponent::defaultTextColourId);
  36648. return coloursForTokenCategories.getReference (tokenType);
  36649. }
  36650. void CodeEditorComponent::clearCachedIterators (const int firstLineToBeInvalid) throw()
  36651. {
  36652. int i;
  36653. for (i = cachedIterators.size(); --i >= 0;)
  36654. if (cachedIterators.getUnchecked (i)->getLine() < firstLineToBeInvalid)
  36655. break;
  36656. cachedIterators.removeRange (jmax (0, i - 1), cachedIterators.size());
  36657. }
  36658. void CodeEditorComponent::updateCachedIterators (int maxLineNum)
  36659. {
  36660. const int maxNumCachedPositions = 5000;
  36661. const int linesBetweenCachedSources = jmax (10, document.getNumLines() / maxNumCachedPositions);
  36662. if (cachedIterators.size() == 0)
  36663. cachedIterators.add (new CodeDocument::Iterator (&document));
  36664. if (codeTokeniser == 0)
  36665. return;
  36666. for (;;)
  36667. {
  36668. CodeDocument::Iterator* last = cachedIterators.getLast();
  36669. if (last->getLine() >= maxLineNum)
  36670. break;
  36671. CodeDocument::Iterator* t = new CodeDocument::Iterator (*last);
  36672. cachedIterators.add (t);
  36673. const int targetLine = last->getLine() + linesBetweenCachedSources;
  36674. for (;;)
  36675. {
  36676. codeTokeniser->readNextToken (*t);
  36677. if (t->getLine() >= targetLine)
  36678. break;
  36679. if (t->isEOF())
  36680. return;
  36681. }
  36682. }
  36683. }
  36684. void CodeEditorComponent::getIteratorForPosition (int position, CodeDocument::Iterator& source)
  36685. {
  36686. if (codeTokeniser == 0)
  36687. return;
  36688. for (int i = cachedIterators.size(); --i >= 0;)
  36689. {
  36690. CodeDocument::Iterator* t = cachedIterators.getUnchecked (i);
  36691. if (t->getPosition() <= position)
  36692. {
  36693. source = *t;
  36694. break;
  36695. }
  36696. }
  36697. while (source.getPosition() < position)
  36698. {
  36699. const CodeDocument::Iterator original (source);
  36700. codeTokeniser->readNextToken (source);
  36701. if (source.getPosition() > position || source.isEOF())
  36702. {
  36703. source = original;
  36704. break;
  36705. }
  36706. }
  36707. }
  36708. END_JUCE_NAMESPACE
  36709. /*** End of inlined file: juce_CodeEditorComponent.cpp ***/
  36710. /*** Start of inlined file: juce_CPlusPlusCodeTokeniser.cpp ***/
  36711. BEGIN_JUCE_NAMESPACE
  36712. CPlusPlusCodeTokeniser::CPlusPlusCodeTokeniser()
  36713. {
  36714. }
  36715. CPlusPlusCodeTokeniser::~CPlusPlusCodeTokeniser()
  36716. {
  36717. }
  36718. namespace CppTokeniser
  36719. {
  36720. static bool isIdentifierStart (const juce_wchar c) throw()
  36721. {
  36722. return CharacterFunctions::isLetter (c)
  36723. || c == '_' || c == '@';
  36724. }
  36725. static bool isIdentifierBody (const juce_wchar c) throw()
  36726. {
  36727. return CharacterFunctions::isLetterOrDigit (c)
  36728. || c == '_' || c == '@';
  36729. }
  36730. static bool isReservedKeyword (const juce_wchar* const token, const int tokenLength) throw()
  36731. {
  36732. static const juce_wchar* const keywords2Char[] =
  36733. { T("if"), T("do"), T("or"), T("id"), 0 };
  36734. static const juce_wchar* const keywords3Char[] =
  36735. { T("for"), T("int"), T("new"), T("try"), T("xor"), T("and"), T("asm"), T("not"), 0 };
  36736. static const juce_wchar* const keywords4Char[] =
  36737. { T("bool"), T("void"), T("this"), T("true"), T("long"), T("else"), T("char"),
  36738. T("enum"), T("case"), T("goto"), T("auto"), 0 };
  36739. static const juce_wchar* const keywords5Char[] =
  36740. { T("while"), T("bitor"), T("break"), T("catch"), T("class"), T("compl"), T("const"), T("false"),
  36741. T("float"), T("short"), T("throw"), T("union"), T("using"), T("or_eq"), 0 };
  36742. static const juce_wchar* const keywords6Char[] =
  36743. { T("return"), T("struct"), T("and_eq"), T("bitand"), T("delete"), T("double"), T("extern"),
  36744. T("friend"), T("inline"), T("not_eq"), T("public"), T("sizeof"), T("static"), T("signed"),
  36745. T("switch"), T("typeid"), T("wchar_t"), T("xor_eq"), 0};
  36746. static const juce_wchar* const keywordsOther[] =
  36747. { T("const_cast"), T("continue"), T("default"), T("explicit"), T("mutable"), T("namespace"),
  36748. T("operator"), T("private"), T("protected"), T("register"), T("reinterpret_cast"), T("static_cast"),
  36749. T("template"), T("typedef"), T("typename"), T("unsigned"), T("virtual"), T("volatile"),
  36750. T("@implementation"), T("@interface"), T("@end"), T("@synthesize"), T("@dynamic"), T("@public"),
  36751. T("@private"), T("@property"), T("@protected"), T("@class"), 0 };
  36752. const juce_wchar* const* k;
  36753. switch (tokenLength)
  36754. {
  36755. case 2: k = keywords2Char; break;
  36756. case 3: k = keywords3Char; break;
  36757. case 4: k = keywords4Char; break;
  36758. case 5: k = keywords5Char; break;
  36759. case 6: k = keywords6Char; break;
  36760. default:
  36761. if (tokenLength < 2 || tokenLength > 16)
  36762. return false;
  36763. k = keywordsOther;
  36764. break;
  36765. }
  36766. int i = 0;
  36767. while (k[i] != 0)
  36768. {
  36769. if (k[i][0] == token[0] && CharacterFunctions::compare (k[i], token) == 0)
  36770. return true;
  36771. ++i;
  36772. }
  36773. return false;
  36774. }
  36775. static int parseIdentifier (CodeDocument::Iterator& source) throw()
  36776. {
  36777. int tokenLength = 0;
  36778. juce_wchar possibleIdentifier [19];
  36779. while (isIdentifierBody (source.peekNextChar()))
  36780. {
  36781. const juce_wchar c = source.nextChar();
  36782. if (tokenLength < numElementsInArray (possibleIdentifier) - 1)
  36783. possibleIdentifier [tokenLength] = c;
  36784. ++tokenLength;
  36785. }
  36786. if (tokenLength > 1 && tokenLength <= 16)
  36787. {
  36788. possibleIdentifier [tokenLength] = 0;
  36789. if (isReservedKeyword (possibleIdentifier, tokenLength))
  36790. return CPlusPlusCodeTokeniser::tokenType_builtInKeyword;
  36791. }
  36792. return CPlusPlusCodeTokeniser::tokenType_identifier;
  36793. }
  36794. static bool skipNumberSuffix (CodeDocument::Iterator& source)
  36795. {
  36796. const juce_wchar c = source.peekNextChar();
  36797. if (c == 'l' || c == 'L' || c == 'u' || c == 'U')
  36798. source.skip();
  36799. if (CharacterFunctions::isLetterOrDigit (source.peekNextChar()))
  36800. return false;
  36801. return true;
  36802. }
  36803. static bool isHexDigit (const juce_wchar c) throw()
  36804. {
  36805. return (c >= '0' && c <= '9')
  36806. || (c >= 'a' && c <= 'f')
  36807. || (c >= 'A' && c <= 'F');
  36808. }
  36809. static bool parseHexLiteral (CodeDocument::Iterator& source) throw()
  36810. {
  36811. if (source.nextChar() != '0')
  36812. return false;
  36813. juce_wchar c = source.nextChar();
  36814. if (c != 'x' && c != 'X')
  36815. return false;
  36816. int numDigits = 0;
  36817. while (isHexDigit (source.peekNextChar()))
  36818. {
  36819. ++numDigits;
  36820. source.skip();
  36821. }
  36822. if (numDigits == 0)
  36823. return false;
  36824. return skipNumberSuffix (source);
  36825. }
  36826. static bool isOctalDigit (const juce_wchar c) throw()
  36827. {
  36828. return c >= '0' && c <= '7';
  36829. }
  36830. static bool parseOctalLiteral (CodeDocument::Iterator& source) throw()
  36831. {
  36832. if (source.nextChar() != '0')
  36833. return false;
  36834. if (! isOctalDigit (source.nextChar()))
  36835. return false;
  36836. while (isOctalDigit (source.peekNextChar()))
  36837. source.skip();
  36838. return skipNumberSuffix (source);
  36839. }
  36840. static bool isDecimalDigit (const juce_wchar c) throw()
  36841. {
  36842. return c >= '0' && c <= '9';
  36843. }
  36844. static bool parseDecimalLiteral (CodeDocument::Iterator& source) throw()
  36845. {
  36846. int numChars = 0;
  36847. while (isDecimalDigit (source.peekNextChar()))
  36848. {
  36849. ++numChars;
  36850. source.skip();
  36851. }
  36852. if (numChars == 0)
  36853. return false;
  36854. return skipNumberSuffix (source);
  36855. }
  36856. static bool parseFloatLiteral (CodeDocument::Iterator& source) throw()
  36857. {
  36858. int numDigits = 0;
  36859. while (isDecimalDigit (source.peekNextChar()))
  36860. {
  36861. source.skip();
  36862. ++numDigits;
  36863. }
  36864. const bool hasPoint = (source.peekNextChar() == '.');
  36865. if (hasPoint)
  36866. {
  36867. source.skip();
  36868. while (isDecimalDigit (source.peekNextChar()))
  36869. {
  36870. source.skip();
  36871. ++numDigits;
  36872. }
  36873. }
  36874. if (numDigits == 0)
  36875. return false;
  36876. juce_wchar c = source.peekNextChar();
  36877. const bool hasExponent = (c == 'e' || c == 'E');
  36878. if (hasExponent)
  36879. {
  36880. source.skip();
  36881. c = source.peekNextChar();
  36882. if (c == '+' || c == '-')
  36883. source.skip();
  36884. int numExpDigits = 0;
  36885. while (isDecimalDigit (source.peekNextChar()))
  36886. {
  36887. source.skip();
  36888. ++numExpDigits;
  36889. }
  36890. if (numExpDigits == 0)
  36891. return false;
  36892. }
  36893. c = source.peekNextChar();
  36894. if (c == 'f' || c == 'F')
  36895. source.skip();
  36896. else if (! (hasExponent || hasPoint))
  36897. return false;
  36898. return true;
  36899. }
  36900. static int parseNumber (CodeDocument::Iterator& source)
  36901. {
  36902. const CodeDocument::Iterator original (source);
  36903. if (parseFloatLiteral (source))
  36904. return CPlusPlusCodeTokeniser::tokenType_floatLiteral;
  36905. source = original;
  36906. if (parseHexLiteral (source))
  36907. return CPlusPlusCodeTokeniser::tokenType_integerLiteral;
  36908. source = original;
  36909. if (parseOctalLiteral (source))
  36910. return CPlusPlusCodeTokeniser::tokenType_integerLiteral;
  36911. source = original;
  36912. if (parseDecimalLiteral (source))
  36913. return CPlusPlusCodeTokeniser::tokenType_integerLiteral;
  36914. source = original;
  36915. source.skip();
  36916. return CPlusPlusCodeTokeniser::tokenType_error;
  36917. }
  36918. static void skipQuotedString (CodeDocument::Iterator& source) throw()
  36919. {
  36920. const juce_wchar quote = source.nextChar();
  36921. for (;;)
  36922. {
  36923. const juce_wchar c = source.nextChar();
  36924. if (c == quote || c == 0)
  36925. break;
  36926. if (c == '\\')
  36927. source.skip();
  36928. }
  36929. }
  36930. static void skipComment (CodeDocument::Iterator& source) throw()
  36931. {
  36932. bool lastWasStar = false;
  36933. for (;;)
  36934. {
  36935. const juce_wchar c = source.nextChar();
  36936. if (c == 0 || (c == '/' && lastWasStar))
  36937. break;
  36938. lastWasStar = (c == '*');
  36939. }
  36940. }
  36941. }
  36942. int CPlusPlusCodeTokeniser::readNextToken (CodeDocument::Iterator& source)
  36943. {
  36944. int result = tokenType_error;
  36945. source.skipWhitespace();
  36946. juce_wchar firstChar = source.peekNextChar();
  36947. switch (firstChar)
  36948. {
  36949. case 0:
  36950. source.skip();
  36951. break;
  36952. case '0':
  36953. case '1':
  36954. case '2':
  36955. case '3':
  36956. case '4':
  36957. case '5':
  36958. case '6':
  36959. case '7':
  36960. case '8':
  36961. case '9':
  36962. result = CppTokeniser::parseNumber (source);
  36963. break;
  36964. case '.':
  36965. result = CppTokeniser::parseNumber (source);
  36966. if (result == tokenType_error)
  36967. result = tokenType_punctuation;
  36968. break;
  36969. case ',':
  36970. case ';':
  36971. case ':':
  36972. source.skip();
  36973. result = tokenType_punctuation;
  36974. break;
  36975. case '(':
  36976. case ')':
  36977. case '{':
  36978. case '}':
  36979. case '[':
  36980. case ']':
  36981. source.skip();
  36982. result = tokenType_bracket;
  36983. break;
  36984. case '"':
  36985. case '\'':
  36986. CppTokeniser::skipQuotedString (source);
  36987. result = tokenType_stringLiteral;
  36988. break;
  36989. case '+':
  36990. result = tokenType_operator;
  36991. source.skip();
  36992. if (source.peekNextChar() == '+')
  36993. source.skip();
  36994. else if (source.peekNextChar() == '=')
  36995. source.skip();
  36996. break;
  36997. case '-':
  36998. source.skip();
  36999. result = CppTokeniser::parseNumber (source);
  37000. if (result == tokenType_error)
  37001. {
  37002. result = tokenType_operator;
  37003. if (source.peekNextChar() == '-')
  37004. source.skip();
  37005. else if (source.peekNextChar() == '=')
  37006. source.skip();
  37007. }
  37008. break;
  37009. case '*':
  37010. case '%':
  37011. case '=':
  37012. case '!':
  37013. result = tokenType_operator;
  37014. source.skip();
  37015. if (source.peekNextChar() == '=')
  37016. source.skip();
  37017. break;
  37018. case '/':
  37019. result = tokenType_operator;
  37020. source.skip();
  37021. if (source.peekNextChar() == '=')
  37022. {
  37023. source.skip();
  37024. }
  37025. else if (source.peekNextChar() == '/')
  37026. {
  37027. result = tokenType_comment;
  37028. source.skipToEndOfLine();
  37029. }
  37030. else if (source.peekNextChar() == '*')
  37031. {
  37032. source.skip();
  37033. result = tokenType_comment;
  37034. CppTokeniser::skipComment (source);
  37035. }
  37036. break;
  37037. case '?':
  37038. case '~':
  37039. source.skip();
  37040. result = tokenType_operator;
  37041. break;
  37042. case '<':
  37043. source.skip();
  37044. result = tokenType_operator;
  37045. if (source.peekNextChar() == '=')
  37046. {
  37047. source.skip();
  37048. }
  37049. else if (source.peekNextChar() == '<')
  37050. {
  37051. source.skip();
  37052. if (source.peekNextChar() == '=')
  37053. source.skip();
  37054. }
  37055. break;
  37056. case '>':
  37057. source.skip();
  37058. result = tokenType_operator;
  37059. if (source.peekNextChar() == '=')
  37060. {
  37061. source.skip();
  37062. }
  37063. else if (source.peekNextChar() == '<')
  37064. {
  37065. source.skip();
  37066. if (source.peekNextChar() == '=')
  37067. source.skip();
  37068. }
  37069. break;
  37070. case '|':
  37071. source.skip();
  37072. result = tokenType_operator;
  37073. if (source.peekNextChar() == '=')
  37074. {
  37075. source.skip();
  37076. }
  37077. else if (source.peekNextChar() == '|')
  37078. {
  37079. source.skip();
  37080. if (source.peekNextChar() == '=')
  37081. source.skip();
  37082. }
  37083. break;
  37084. case '&':
  37085. source.skip();
  37086. result = tokenType_operator;
  37087. if (source.peekNextChar() == '=')
  37088. {
  37089. source.skip();
  37090. }
  37091. else if (source.peekNextChar() == '&')
  37092. {
  37093. source.skip();
  37094. if (source.peekNextChar() == '=')
  37095. source.skip();
  37096. }
  37097. break;
  37098. case '^':
  37099. source.skip();
  37100. result = tokenType_operator;
  37101. if (source.peekNextChar() == '=')
  37102. {
  37103. source.skip();
  37104. }
  37105. else if (source.peekNextChar() == '^')
  37106. {
  37107. source.skip();
  37108. if (source.peekNextChar() == '=')
  37109. source.skip();
  37110. }
  37111. break;
  37112. case '#':
  37113. result = tokenType_preprocessor;
  37114. source.skipToEndOfLine();
  37115. break;
  37116. default:
  37117. if (CppTokeniser::isIdentifierStart (firstChar))
  37118. result = CppTokeniser::parseIdentifier (source);
  37119. else
  37120. source.skip();
  37121. break;
  37122. }
  37123. return result;
  37124. }
  37125. const StringArray CPlusPlusCodeTokeniser::getTokenTypes()
  37126. {
  37127. const char* const types[] =
  37128. {
  37129. "Error",
  37130. "Comment",
  37131. "C++ keyword",
  37132. "Identifier",
  37133. "Integer literal",
  37134. "Float literal",
  37135. "String literal",
  37136. "Operator",
  37137. "Bracket",
  37138. "Punctuation",
  37139. "Preprocessor line",
  37140. 0
  37141. };
  37142. return StringArray (types);
  37143. }
  37144. const Colour CPlusPlusCodeTokeniser::getDefaultColour (const int tokenType)
  37145. {
  37146. const uint32 colours[] =
  37147. {
  37148. 0xffcc0000, // error
  37149. 0xff00aa00, // comment
  37150. 0xff0000cc, // keyword
  37151. 0xff000000, // identifier
  37152. 0xff880000, // int literal
  37153. 0xff885500, // float literal
  37154. 0xff990099, // string literal
  37155. 0xff225500, // operator
  37156. 0xff000055, // bracket
  37157. 0xff004400, // punctuation
  37158. 0xff660000 // preprocessor
  37159. };
  37160. if (tokenType >= 0 && tokenType < numElementsInArray (colours))
  37161. return Colour (colours [tokenType]);
  37162. return Colours::black;
  37163. }
  37164. bool CPlusPlusCodeTokeniser::isReservedKeyword (const String& token) throw()
  37165. {
  37166. return CppTokeniser::isReservedKeyword (token, token.length());
  37167. }
  37168. END_JUCE_NAMESPACE
  37169. /*** End of inlined file: juce_CPlusPlusCodeTokeniser.cpp ***/
  37170. /*** Start of inlined file: juce_ComboBox.cpp ***/
  37171. BEGIN_JUCE_NAMESPACE
  37172. ComboBox::ComboBox (const String& name)
  37173. : Component (name),
  37174. lastCurrentId (0),
  37175. isButtonDown (false),
  37176. separatorPending (false),
  37177. menuActive (false),
  37178. label (0)
  37179. {
  37180. noChoicesMessage = TRANS("(no choices)");
  37181. setRepaintsOnMouseActivity (true);
  37182. lookAndFeelChanged();
  37183. currentId.addListener (this);
  37184. }
  37185. ComboBox::~ComboBox()
  37186. {
  37187. currentId.removeListener (this);
  37188. if (menuActive)
  37189. PopupMenu::dismissAllActiveMenus();
  37190. label = 0;
  37191. deleteAllChildren();
  37192. }
  37193. void ComboBox::setEditableText (const bool isEditable)
  37194. {
  37195. label->setEditable (isEditable, isEditable, false);
  37196. setWantsKeyboardFocus (! isEditable);
  37197. resized();
  37198. }
  37199. bool ComboBox::isTextEditable() const throw()
  37200. {
  37201. return label->isEditable();
  37202. }
  37203. void ComboBox::setJustificationType (const Justification& justification) throw()
  37204. {
  37205. label->setJustificationType (justification);
  37206. }
  37207. const Justification ComboBox::getJustificationType() const throw()
  37208. {
  37209. return label->getJustificationType();
  37210. }
  37211. void ComboBox::setTooltip (const String& newTooltip)
  37212. {
  37213. SettableTooltipClient::setTooltip (newTooltip);
  37214. label->setTooltip (newTooltip);
  37215. }
  37216. void ComboBox::addItem (const String& newItemText,
  37217. const int newItemId) throw()
  37218. {
  37219. // you can't add empty strings to the list..
  37220. jassert (newItemText.isNotEmpty());
  37221. // IDs must be non-zero, as zero is used to indicate a lack of selecion.
  37222. jassert (newItemId != 0);
  37223. // you shouldn't use duplicate item IDs!
  37224. jassert (getItemForId (newItemId) == 0);
  37225. if (newItemText.isNotEmpty() && newItemId != 0)
  37226. {
  37227. if (separatorPending)
  37228. {
  37229. separatorPending = false;
  37230. ItemInfo* const item = new ItemInfo();
  37231. item->itemId = 0;
  37232. item->isEnabled = false;
  37233. item->isHeading = false;
  37234. items.add (item);
  37235. }
  37236. ItemInfo* const item = new ItemInfo();
  37237. item->name = newItemText;
  37238. item->itemId = newItemId;
  37239. item->isEnabled = true;
  37240. item->isHeading = false;
  37241. items.add (item);
  37242. }
  37243. }
  37244. void ComboBox::addSeparator() throw()
  37245. {
  37246. separatorPending = (items.size() > 0);
  37247. }
  37248. void ComboBox::addSectionHeading (const String& headingName) throw()
  37249. {
  37250. // you can't add empty strings to the list..
  37251. jassert (headingName.isNotEmpty());
  37252. if (headingName.isNotEmpty())
  37253. {
  37254. if (separatorPending)
  37255. {
  37256. separatorPending = false;
  37257. ItemInfo* const item = new ItemInfo();
  37258. item->itemId = 0;
  37259. item->isEnabled = false;
  37260. item->isHeading = false;
  37261. items.add (item);
  37262. }
  37263. ItemInfo* const item = new ItemInfo();
  37264. item->name = headingName;
  37265. item->itemId = 0;
  37266. item->isEnabled = true;
  37267. item->isHeading = true;
  37268. items.add (item);
  37269. }
  37270. }
  37271. void ComboBox::setItemEnabled (const int itemId,
  37272. const bool shouldBeEnabled) throw()
  37273. {
  37274. ItemInfo* const item = getItemForId (itemId);
  37275. if (item != 0)
  37276. item->isEnabled = shouldBeEnabled;
  37277. }
  37278. void ComboBox::changeItemText (const int itemId,
  37279. const String& newText) throw()
  37280. {
  37281. ItemInfo* const item = getItemForId (itemId);
  37282. jassert (item != 0);
  37283. if (item != 0)
  37284. item->name = newText;
  37285. }
  37286. void ComboBox::clear (const bool dontSendChangeMessage)
  37287. {
  37288. items.clear();
  37289. separatorPending = false;
  37290. if (! label->isEditable())
  37291. setSelectedItemIndex (-1, dontSendChangeMessage);
  37292. }
  37293. bool ComboBox::ItemInfo::isSeparator() const throw()
  37294. {
  37295. return name.isEmpty();
  37296. }
  37297. bool ComboBox::ItemInfo::isRealItem() const throw()
  37298. {
  37299. return ! (isHeading || name.isEmpty());
  37300. }
  37301. ComboBox::ItemInfo* ComboBox::getItemForId (const int itemId) const throw()
  37302. {
  37303. if (itemId != 0)
  37304. {
  37305. for (int i = items.size(); --i >= 0;)
  37306. if (items.getUnchecked(i)->itemId == itemId)
  37307. return items.getUnchecked(i);
  37308. }
  37309. return 0;
  37310. }
  37311. ComboBox::ItemInfo* ComboBox::getItemForIndex (const int index) const throw()
  37312. {
  37313. int n = 0;
  37314. for (int i = 0; i < items.size(); ++i)
  37315. {
  37316. ItemInfo* const item = items.getUnchecked(i);
  37317. if (item->isRealItem())
  37318. if (n++ == index)
  37319. return item;
  37320. }
  37321. return 0;
  37322. }
  37323. int ComboBox::getNumItems() const throw()
  37324. {
  37325. int n = 0;
  37326. for (int i = items.size(); --i >= 0;)
  37327. if (items.getUnchecked(i)->isRealItem())
  37328. ++n;
  37329. return n;
  37330. }
  37331. const String ComboBox::getItemText (const int index) const throw()
  37332. {
  37333. const ItemInfo* const item = getItemForIndex (index);
  37334. if (item != 0)
  37335. return item->name;
  37336. return String::empty;
  37337. }
  37338. int ComboBox::getItemId (const int index) const throw()
  37339. {
  37340. const ItemInfo* const item = getItemForIndex (index);
  37341. return (item != 0) ? item->itemId : 0;
  37342. }
  37343. int ComboBox::indexOfItemId (const int itemId) const throw()
  37344. {
  37345. int n = 0;
  37346. for (int i = 0; i < items.size(); ++i)
  37347. {
  37348. const ItemInfo* const item = items.getUnchecked(i);
  37349. if (item->isRealItem())
  37350. {
  37351. if (item->itemId == itemId)
  37352. return n;
  37353. ++n;
  37354. }
  37355. }
  37356. return -1;
  37357. }
  37358. int ComboBox::getSelectedItemIndex() const throw()
  37359. {
  37360. int index = indexOfItemId (currentId.getValue());
  37361. if (getText() != getItemText (index))
  37362. index = -1;
  37363. return index;
  37364. }
  37365. void ComboBox::setSelectedItemIndex (const int index,
  37366. const bool dontSendChangeMessage) throw()
  37367. {
  37368. setSelectedId (getItemId (index), dontSendChangeMessage);
  37369. }
  37370. int ComboBox::getSelectedId() const throw()
  37371. {
  37372. const ItemInfo* const item = getItemForId (currentId.getValue());
  37373. return (item != 0 && getText() == item->name)
  37374. ? item->itemId
  37375. : 0;
  37376. }
  37377. void ComboBox::setSelectedId (const int newItemId,
  37378. const bool dontSendChangeMessage) throw()
  37379. {
  37380. const ItemInfo* const item = getItemForId (newItemId);
  37381. const String newItemText (item != 0 ? item->name : String::empty);
  37382. if (lastCurrentId != newItemId || label->getText() != newItemText)
  37383. {
  37384. if (! dontSendChangeMessage)
  37385. triggerAsyncUpdate();
  37386. label->setText (newItemText, false);
  37387. lastCurrentId = newItemId;
  37388. currentId = newItemId;
  37389. repaint(); // for the benefit of the 'none selected' text
  37390. }
  37391. }
  37392. void ComboBox::valueChanged (Value&)
  37393. {
  37394. if (lastCurrentId != (int) currentId.getValue())
  37395. setSelectedId (currentId.getValue(), false);
  37396. }
  37397. const String ComboBox::getText() const throw()
  37398. {
  37399. return label->getText();
  37400. }
  37401. void ComboBox::setText (const String& newText,
  37402. const bool dontSendChangeMessage) throw()
  37403. {
  37404. for (int i = items.size(); --i >= 0;)
  37405. {
  37406. const ItemInfo* const item = items.getUnchecked(i);
  37407. if (item->isRealItem()
  37408. && item->name == newText)
  37409. {
  37410. setSelectedId (item->itemId, dontSendChangeMessage);
  37411. return;
  37412. }
  37413. }
  37414. lastCurrentId = 0;
  37415. currentId = 0;
  37416. if (label->getText() != newText)
  37417. {
  37418. label->setText (newText, false);
  37419. if (! dontSendChangeMessage)
  37420. triggerAsyncUpdate();
  37421. }
  37422. repaint();
  37423. }
  37424. void ComboBox::showEditor()
  37425. {
  37426. jassert (isTextEditable()); // you probably shouldn't do this to a non-editable combo box?
  37427. label->showEditor();
  37428. }
  37429. void ComboBox::setTextWhenNothingSelected (const String& newMessage) throw()
  37430. {
  37431. textWhenNothingSelected = newMessage;
  37432. repaint();
  37433. }
  37434. const String ComboBox::getTextWhenNothingSelected() const throw()
  37435. {
  37436. return textWhenNothingSelected;
  37437. }
  37438. void ComboBox::setTextWhenNoChoicesAvailable (const String& newMessage) throw()
  37439. {
  37440. noChoicesMessage = newMessage;
  37441. }
  37442. const String ComboBox::getTextWhenNoChoicesAvailable() const throw()
  37443. {
  37444. return noChoicesMessage;
  37445. }
  37446. void ComboBox::paint (Graphics& g)
  37447. {
  37448. getLookAndFeel().drawComboBox (g,
  37449. getWidth(),
  37450. getHeight(),
  37451. isButtonDown,
  37452. label->getRight(),
  37453. 0,
  37454. getWidth() - label->getRight(),
  37455. getHeight(),
  37456. *this);
  37457. if (textWhenNothingSelected.isNotEmpty()
  37458. && label->getText().isEmpty()
  37459. && ! label->isBeingEdited())
  37460. {
  37461. g.setColour (findColour (textColourId).withMultipliedAlpha (0.5f));
  37462. g.setFont (label->getFont());
  37463. g.drawFittedText (textWhenNothingSelected,
  37464. label->getX() + 2, label->getY() + 1,
  37465. label->getWidth() - 4, label->getHeight() - 2,
  37466. label->getJustificationType(),
  37467. jmax (1, (int) (label->getHeight() / label->getFont().getHeight())));
  37468. }
  37469. }
  37470. void ComboBox::resized()
  37471. {
  37472. if (getHeight() > 0 && getWidth() > 0)
  37473. getLookAndFeel().positionComboBoxText (*this, *label);
  37474. }
  37475. void ComboBox::enablementChanged()
  37476. {
  37477. repaint();
  37478. }
  37479. void ComboBox::lookAndFeelChanged()
  37480. {
  37481. repaint();
  37482. Label* const newLabel = getLookAndFeel().createComboBoxTextBox (*this);
  37483. if (label != 0)
  37484. {
  37485. newLabel->setEditable (label->isEditable());
  37486. newLabel->setJustificationType (label->getJustificationType());
  37487. newLabel->setTooltip (label->getTooltip());
  37488. newLabel->setText (label->getText(), false);
  37489. }
  37490. label = newLabel;
  37491. addAndMakeVisible (newLabel);
  37492. newLabel->addListener (this);
  37493. newLabel->addMouseListener (this, false);
  37494. newLabel->setColour (Label::backgroundColourId, Colours::transparentBlack);
  37495. newLabel->setColour (Label::textColourId, findColour (ComboBox::textColourId));
  37496. newLabel->setColour (TextEditor::textColourId, findColour (ComboBox::textColourId));
  37497. newLabel->setColour (TextEditor::backgroundColourId, Colours::transparentBlack);
  37498. newLabel->setColour (TextEditor::highlightColourId, findColour (TextEditor::highlightColourId));
  37499. newLabel->setColour (TextEditor::outlineColourId, Colours::transparentBlack);
  37500. resized();
  37501. }
  37502. void ComboBox::colourChanged()
  37503. {
  37504. lookAndFeelChanged();
  37505. }
  37506. bool ComboBox::keyPressed (const KeyPress& key)
  37507. {
  37508. bool used = false;
  37509. if (key.isKeyCode (KeyPress::upKey)
  37510. || key.isKeyCode (KeyPress::leftKey))
  37511. {
  37512. setSelectedItemIndex (jmax (0, getSelectedItemIndex() - 1));
  37513. used = true;
  37514. }
  37515. else if (key.isKeyCode (KeyPress::downKey)
  37516. || key.isKeyCode (KeyPress::rightKey))
  37517. {
  37518. setSelectedItemIndex (jmin (getSelectedItemIndex() + 1, getNumItems() - 1));
  37519. used = true;
  37520. }
  37521. else if (key.isKeyCode (KeyPress::returnKey))
  37522. {
  37523. showPopup();
  37524. used = true;
  37525. }
  37526. return used;
  37527. }
  37528. bool ComboBox::keyStateChanged (const bool isKeyDown)
  37529. {
  37530. // only forward key events that aren't used by this component
  37531. return isKeyDown
  37532. && (KeyPress::isKeyCurrentlyDown (KeyPress::upKey)
  37533. || KeyPress::isKeyCurrentlyDown (KeyPress::leftKey)
  37534. || KeyPress::isKeyCurrentlyDown (KeyPress::downKey)
  37535. || KeyPress::isKeyCurrentlyDown (KeyPress::rightKey));
  37536. }
  37537. void ComboBox::focusGained (FocusChangeType)
  37538. {
  37539. repaint();
  37540. }
  37541. void ComboBox::focusLost (FocusChangeType)
  37542. {
  37543. repaint();
  37544. }
  37545. void ComboBox::labelTextChanged (Label*)
  37546. {
  37547. triggerAsyncUpdate();
  37548. }
  37549. void ComboBox::showPopup()
  37550. {
  37551. if (! menuActive)
  37552. {
  37553. const int selectedId = getSelectedId();
  37554. Component::SafePointer<Component> deletionWatcher (this);
  37555. PopupMenu menu;
  37556. menu.setLookAndFeel (&getLookAndFeel());
  37557. for (int i = 0; i < items.size(); ++i)
  37558. {
  37559. const ItemInfo* const item = items.getUnchecked(i);
  37560. if (item->isSeparator())
  37561. menu.addSeparator();
  37562. else if (item->isHeading)
  37563. menu.addSectionHeader (item->name);
  37564. else
  37565. menu.addItem (item->itemId, item->name,
  37566. item->isEnabled, item->itemId == selectedId);
  37567. }
  37568. if (items.size() == 0)
  37569. menu.addItem (1, noChoicesMessage, false);
  37570. const int itemHeight = jlimit (12, 24, getHeight());
  37571. menuActive = true;
  37572. const int resultId = menu.showAt (this, selectedId,
  37573. getWidth(), 1, itemHeight);
  37574. if (deletionWatcher == 0)
  37575. return;
  37576. menuActive = false;
  37577. if (resultId != 0)
  37578. setSelectedId (resultId);
  37579. }
  37580. }
  37581. void ComboBox::mouseDown (const MouseEvent& e)
  37582. {
  37583. beginDragAutoRepeat (300);
  37584. isButtonDown = isEnabled();
  37585. if (isButtonDown
  37586. && (e.eventComponent == this || ! label->isEditable()))
  37587. {
  37588. showPopup();
  37589. }
  37590. }
  37591. void ComboBox::mouseDrag (const MouseEvent& e)
  37592. {
  37593. beginDragAutoRepeat (50);
  37594. if (isButtonDown && ! e.mouseWasClicked())
  37595. showPopup();
  37596. }
  37597. void ComboBox::mouseUp (const MouseEvent& e2)
  37598. {
  37599. if (isButtonDown)
  37600. {
  37601. isButtonDown = false;
  37602. repaint();
  37603. const MouseEvent e (e2.getEventRelativeTo (this));
  37604. if (reallyContains (e.x, e.y, true)
  37605. && (e2.eventComponent == this || ! label->isEditable()))
  37606. {
  37607. showPopup();
  37608. }
  37609. }
  37610. }
  37611. void ComboBox::addListener (ComboBoxListener* const listener) throw()
  37612. {
  37613. listeners.add (listener);
  37614. }
  37615. void ComboBox::removeListener (ComboBoxListener* const listener) throw()
  37616. {
  37617. listeners.remove (listener);
  37618. }
  37619. void ComboBox::handleAsyncUpdate()
  37620. {
  37621. Component::BailOutChecker checker (this);
  37622. listeners.callChecked (checker, &ComboBoxListener::comboBoxChanged, this);
  37623. }
  37624. END_JUCE_NAMESPACE
  37625. /*** End of inlined file: juce_ComboBox.cpp ***/
  37626. /*** Start of inlined file: juce_Label.cpp ***/
  37627. BEGIN_JUCE_NAMESPACE
  37628. Label::Label (const String& componentName,
  37629. const String& labelText)
  37630. : Component (componentName),
  37631. textValue (labelText),
  37632. lastTextValue (labelText),
  37633. font (15.0f),
  37634. justification (Justification::centredLeft),
  37635. ownerComponent (0),
  37636. horizontalBorderSize (5),
  37637. verticalBorderSize (1),
  37638. minimumHorizontalScale (0.7f),
  37639. editSingleClick (false),
  37640. editDoubleClick (false),
  37641. lossOfFocusDiscardsChanges (false)
  37642. {
  37643. setColour (TextEditor::textColourId, Colours::black);
  37644. setColour (TextEditor::backgroundColourId, Colours::transparentBlack);
  37645. setColour (TextEditor::outlineColourId, Colours::transparentBlack);
  37646. textValue.addListener (this);
  37647. }
  37648. Label::~Label()
  37649. {
  37650. textValue.removeListener (this);
  37651. if (ownerComponent != 0)
  37652. ownerComponent->removeComponentListener (this);
  37653. editor = 0;
  37654. }
  37655. void Label::setText (const String& newText,
  37656. const bool broadcastChangeMessage)
  37657. {
  37658. hideEditor (true);
  37659. if (lastTextValue != newText)
  37660. {
  37661. lastTextValue = newText;
  37662. textValue = newText;
  37663. repaint();
  37664. textWasChanged();
  37665. if (ownerComponent != 0)
  37666. componentMovedOrResized (*ownerComponent, true, true);
  37667. if (broadcastChangeMessage)
  37668. callChangeListeners();
  37669. }
  37670. }
  37671. const String Label::getText (const bool returnActiveEditorContents) const throw()
  37672. {
  37673. return (returnActiveEditorContents && isBeingEdited())
  37674. ? editor->getText()
  37675. : textValue.toString();
  37676. }
  37677. void Label::valueChanged (Value&)
  37678. {
  37679. if (lastTextValue != textValue.toString())
  37680. setText (textValue.toString(), true);
  37681. }
  37682. void Label::setFont (const Font& newFont) throw()
  37683. {
  37684. font = newFont;
  37685. repaint();
  37686. }
  37687. const Font& Label::getFont() const throw()
  37688. {
  37689. return font;
  37690. }
  37691. void Label::setEditable (const bool editOnSingleClick,
  37692. const bool editOnDoubleClick,
  37693. const bool lossOfFocusDiscardsChanges_) throw()
  37694. {
  37695. editSingleClick = editOnSingleClick;
  37696. editDoubleClick = editOnDoubleClick;
  37697. lossOfFocusDiscardsChanges = lossOfFocusDiscardsChanges_;
  37698. setWantsKeyboardFocus (editOnSingleClick || editOnDoubleClick);
  37699. setFocusContainer (editOnSingleClick || editOnDoubleClick);
  37700. }
  37701. void Label::setJustificationType (const Justification& justification_) throw()
  37702. {
  37703. justification = justification_;
  37704. repaint();
  37705. }
  37706. void Label::setBorderSize (int h, int v)
  37707. {
  37708. horizontalBorderSize = h;
  37709. verticalBorderSize = v;
  37710. repaint();
  37711. }
  37712. Component* Label::getAttachedComponent() const
  37713. {
  37714. return static_cast<Component*> (ownerComponent);
  37715. }
  37716. void Label::attachToComponent (Component* owner,
  37717. const bool onLeft)
  37718. {
  37719. if (ownerComponent != 0)
  37720. ownerComponent->removeComponentListener (this);
  37721. ownerComponent = owner;
  37722. leftOfOwnerComp = onLeft;
  37723. if (ownerComponent != 0)
  37724. {
  37725. setVisible (owner->isVisible());
  37726. ownerComponent->addComponentListener (this);
  37727. componentParentHierarchyChanged (*ownerComponent);
  37728. componentMovedOrResized (*ownerComponent, true, true);
  37729. }
  37730. }
  37731. void Label::componentMovedOrResized (Component& component,
  37732. bool /*wasMoved*/,
  37733. bool /*wasResized*/)
  37734. {
  37735. if (leftOfOwnerComp)
  37736. {
  37737. setSize (jmin (getFont().getStringWidth (textValue.toString()) + 8, component.getX()),
  37738. component.getHeight());
  37739. setTopRightPosition (component.getX(), component.getY());
  37740. }
  37741. else
  37742. {
  37743. setSize (component.getWidth(),
  37744. 8 + roundToInt (getFont().getHeight()));
  37745. setTopLeftPosition (component.getX(), component.getY() - getHeight());
  37746. }
  37747. }
  37748. void Label::componentParentHierarchyChanged (Component& component)
  37749. {
  37750. if (component.getParentComponent() != 0)
  37751. component.getParentComponent()->addChildComponent (this);
  37752. }
  37753. void Label::componentVisibilityChanged (Component& component)
  37754. {
  37755. setVisible (component.isVisible());
  37756. }
  37757. void Label::textWasEdited()
  37758. {
  37759. }
  37760. void Label::textWasChanged()
  37761. {
  37762. }
  37763. void Label::showEditor()
  37764. {
  37765. if (editor == 0)
  37766. {
  37767. addAndMakeVisible (editor = createEditorComponent());
  37768. editor->setText (getText(), false);
  37769. editor->addListener (this);
  37770. editor->grabKeyboardFocus();
  37771. editor->setHighlightedRegion (Range<int> (0, textValue.toString().length()));
  37772. editor->addListener (this);
  37773. resized();
  37774. repaint();
  37775. editorShown (editor);
  37776. enterModalState (false);
  37777. editor->grabKeyboardFocus();
  37778. }
  37779. }
  37780. void Label::editorShown (TextEditor* /*editorComponent*/)
  37781. {
  37782. }
  37783. void Label::editorAboutToBeHidden (TextEditor* /*editorComponent*/)
  37784. {
  37785. }
  37786. bool Label::updateFromTextEditorContents()
  37787. {
  37788. jassert (editor != 0);
  37789. const String newText (editor->getText());
  37790. if (textValue.toString() != newText)
  37791. {
  37792. lastTextValue = newText;
  37793. textValue = newText;
  37794. repaint();
  37795. textWasChanged();
  37796. if (ownerComponent != 0)
  37797. componentMovedOrResized (*ownerComponent, true, true);
  37798. return true;
  37799. }
  37800. return false;
  37801. }
  37802. void Label::hideEditor (const bool discardCurrentEditorContents)
  37803. {
  37804. if (editor != 0)
  37805. {
  37806. Component::SafePointer<Component> deletionChecker (this);
  37807. editorAboutToBeHidden (editor);
  37808. const bool changed = (! discardCurrentEditorContents)
  37809. && updateFromTextEditorContents();
  37810. editor = 0;
  37811. repaint();
  37812. if (changed)
  37813. textWasEdited();
  37814. if (deletionChecker != 0)
  37815. exitModalState (0);
  37816. if (changed && deletionChecker != 0)
  37817. callChangeListeners();
  37818. }
  37819. }
  37820. void Label::inputAttemptWhenModal()
  37821. {
  37822. if (editor != 0)
  37823. {
  37824. if (lossOfFocusDiscardsChanges)
  37825. textEditorEscapeKeyPressed (*editor);
  37826. else
  37827. textEditorReturnKeyPressed (*editor);
  37828. }
  37829. }
  37830. bool Label::isBeingEdited() const throw()
  37831. {
  37832. return editor != 0;
  37833. }
  37834. TextEditor* Label::createEditorComponent()
  37835. {
  37836. TextEditor* const ed = new TextEditor (getName());
  37837. ed->setFont (font);
  37838. // copy these colours from our own settings..
  37839. const int cols[] = { TextEditor::backgroundColourId,
  37840. TextEditor::textColourId,
  37841. TextEditor::highlightColourId,
  37842. TextEditor::highlightedTextColourId,
  37843. TextEditor::caretColourId,
  37844. TextEditor::outlineColourId,
  37845. TextEditor::focusedOutlineColourId,
  37846. TextEditor::shadowColourId };
  37847. for (int i = 0; i < numElementsInArray (cols); ++i)
  37848. ed->setColour (cols[i], findColour (cols[i]));
  37849. return ed;
  37850. }
  37851. void Label::paint (Graphics& g)
  37852. {
  37853. getLookAndFeel().drawLabel (g, *this);
  37854. }
  37855. void Label::mouseUp (const MouseEvent& e)
  37856. {
  37857. if (editSingleClick
  37858. && e.mouseWasClicked()
  37859. && contains (e.x, e.y)
  37860. && ! e.mods.isPopupMenu())
  37861. {
  37862. showEditor();
  37863. }
  37864. }
  37865. void Label::mouseDoubleClick (const MouseEvent& e)
  37866. {
  37867. if (editDoubleClick && ! e.mods.isPopupMenu())
  37868. showEditor();
  37869. }
  37870. void Label::resized()
  37871. {
  37872. if (editor != 0)
  37873. editor->setBoundsInset (BorderSize (0));
  37874. }
  37875. void Label::focusGained (FocusChangeType cause)
  37876. {
  37877. if (editSingleClick && cause == focusChangedByTabKey)
  37878. showEditor();
  37879. }
  37880. void Label::enablementChanged()
  37881. {
  37882. repaint();
  37883. }
  37884. void Label::colourChanged()
  37885. {
  37886. repaint();
  37887. }
  37888. void Label::setMinimumHorizontalScale (const float newScale)
  37889. {
  37890. if (minimumHorizontalScale != newScale)
  37891. {
  37892. minimumHorizontalScale = newScale;
  37893. repaint();
  37894. }
  37895. }
  37896. // We'll use a custom focus traverser here to make sure focus goes from the
  37897. // text editor to another component rather than back to the label itself.
  37898. class LabelKeyboardFocusTraverser : public KeyboardFocusTraverser
  37899. {
  37900. public:
  37901. LabelKeyboardFocusTraverser() {}
  37902. Component* getNextComponent (Component* current)
  37903. {
  37904. return KeyboardFocusTraverser::getNextComponent (dynamic_cast <TextEditor*> (current) != 0
  37905. ? current->getParentComponent() : current);
  37906. }
  37907. Component* getPreviousComponent (Component* current)
  37908. {
  37909. return KeyboardFocusTraverser::getPreviousComponent (dynamic_cast <TextEditor*> (current) != 0
  37910. ? current->getParentComponent() : current);
  37911. }
  37912. };
  37913. KeyboardFocusTraverser* Label::createFocusTraverser()
  37914. {
  37915. return new LabelKeyboardFocusTraverser();
  37916. }
  37917. void Label::addListener (LabelListener* const listener) throw()
  37918. {
  37919. listeners.add (listener);
  37920. }
  37921. void Label::removeListener (LabelListener* const listener) throw()
  37922. {
  37923. listeners.remove (listener);
  37924. }
  37925. void Label::callChangeListeners()
  37926. {
  37927. Component::BailOutChecker checker (this);
  37928. listeners.callChecked (checker, &LabelListener::labelTextChanged, this);
  37929. }
  37930. void Label::textEditorTextChanged (TextEditor& ed)
  37931. {
  37932. if (editor != 0)
  37933. {
  37934. jassert (&ed == editor);
  37935. if (! (hasKeyboardFocus (true) || isCurrentlyBlockedByAnotherModalComponent()))
  37936. {
  37937. if (lossOfFocusDiscardsChanges)
  37938. textEditorEscapeKeyPressed (ed);
  37939. else
  37940. textEditorReturnKeyPressed (ed);
  37941. }
  37942. }
  37943. }
  37944. void Label::textEditorReturnKeyPressed (TextEditor& ed)
  37945. {
  37946. if (editor != 0)
  37947. {
  37948. jassert (&ed == editor);
  37949. (void) ed;
  37950. const bool changed = updateFromTextEditorContents();
  37951. hideEditor (true);
  37952. if (changed)
  37953. {
  37954. Component::SafePointer<Component> deletionChecker (this);
  37955. textWasEdited();
  37956. if (deletionChecker != 0)
  37957. callChangeListeners();
  37958. }
  37959. }
  37960. }
  37961. void Label::textEditorEscapeKeyPressed (TextEditor& ed)
  37962. {
  37963. if (editor != 0)
  37964. {
  37965. jassert (&ed == editor);
  37966. (void) ed;
  37967. editor->setText (textValue.toString(), false);
  37968. hideEditor (true);
  37969. }
  37970. }
  37971. void Label::textEditorFocusLost (TextEditor& ed)
  37972. {
  37973. textEditorTextChanged (ed);
  37974. }
  37975. END_JUCE_NAMESPACE
  37976. /*** End of inlined file: juce_Label.cpp ***/
  37977. /*** Start of inlined file: juce_ListBox.cpp ***/
  37978. BEGIN_JUCE_NAMESPACE
  37979. class ListBoxRowComponent : public Component,
  37980. public TooltipClient
  37981. {
  37982. public:
  37983. ListBoxRowComponent (ListBox& owner_)
  37984. : owner (owner_),
  37985. row (-1),
  37986. selected (false),
  37987. isDragging (false)
  37988. {
  37989. }
  37990. ~ListBoxRowComponent()
  37991. {
  37992. deleteAllChildren();
  37993. }
  37994. void paint (Graphics& g)
  37995. {
  37996. if (owner.getModel() != 0)
  37997. owner.getModel()->paintListBoxItem (row, g, getWidth(), getHeight(), selected);
  37998. }
  37999. void update (const int row_, const bool selected_)
  38000. {
  38001. if (row != row_ || selected != selected_)
  38002. {
  38003. repaint();
  38004. row = row_;
  38005. selected = selected_;
  38006. }
  38007. if (owner.getModel() != 0)
  38008. {
  38009. Component* const customComp = owner.getModel()->refreshComponentForRow (row_, selected_, getChildComponent (0));
  38010. if (customComp != 0)
  38011. {
  38012. addAndMakeVisible (customComp);
  38013. customComp->setBounds (0, 0, getWidth(), getHeight());
  38014. for (int i = getNumChildComponents(); --i >= 0;)
  38015. if (getChildComponent (i) != customComp)
  38016. delete getChildComponent (i);
  38017. }
  38018. else
  38019. {
  38020. deleteAllChildren();
  38021. }
  38022. }
  38023. }
  38024. void mouseDown (const MouseEvent& e)
  38025. {
  38026. isDragging = false;
  38027. selectRowOnMouseUp = false;
  38028. if (isEnabled())
  38029. {
  38030. if (! selected)
  38031. {
  38032. owner.selectRowsBasedOnModifierKeys (row, e.mods);
  38033. if (owner.getModel() != 0)
  38034. owner.getModel()->listBoxItemClicked (row, e);
  38035. }
  38036. else
  38037. {
  38038. selectRowOnMouseUp = true;
  38039. }
  38040. }
  38041. }
  38042. void mouseUp (const MouseEvent& e)
  38043. {
  38044. if (isEnabled() && selectRowOnMouseUp && ! isDragging)
  38045. {
  38046. owner.selectRowsBasedOnModifierKeys (row, e.mods);
  38047. if (owner.getModel() != 0)
  38048. owner.getModel()->listBoxItemClicked (row, e);
  38049. }
  38050. }
  38051. void mouseDoubleClick (const MouseEvent& e)
  38052. {
  38053. if (owner.getModel() != 0 && isEnabled())
  38054. owner.getModel()->listBoxItemDoubleClicked (row, e);
  38055. }
  38056. void mouseDrag (const MouseEvent& e)
  38057. {
  38058. if (isEnabled() && owner.getModel() != 0 && ! (e.mouseWasClicked() || isDragging))
  38059. {
  38060. const SparseSet<int> selectedRows (owner.getSelectedRows());
  38061. if (selectedRows.size() > 0)
  38062. {
  38063. const String dragDescription (owner.getModel()->getDragSourceDescription (selectedRows));
  38064. if (dragDescription.isNotEmpty())
  38065. {
  38066. isDragging = true;
  38067. owner.startDragAndDrop (e, dragDescription);
  38068. }
  38069. }
  38070. }
  38071. }
  38072. void resized()
  38073. {
  38074. if (getNumChildComponents() > 0)
  38075. getChildComponent(0)->setBounds (0, 0, getWidth(), getHeight());
  38076. }
  38077. const String getTooltip()
  38078. {
  38079. if (owner.getModel() != 0)
  38080. return owner.getModel()->getTooltipForRow (row);
  38081. return String::empty;
  38082. }
  38083. juce_UseDebuggingNewOperator
  38084. bool neededFlag;
  38085. private:
  38086. ListBox& owner;
  38087. int row;
  38088. bool selected, isDragging, selectRowOnMouseUp;
  38089. ListBoxRowComponent (const ListBoxRowComponent&);
  38090. ListBoxRowComponent& operator= (const ListBoxRowComponent&);
  38091. };
  38092. class ListViewport : public Viewport
  38093. {
  38094. public:
  38095. int firstIndex, firstWholeIndex, lastWholeIndex;
  38096. bool hasUpdated;
  38097. ListViewport (ListBox& owner_)
  38098. : owner (owner_)
  38099. {
  38100. setWantsKeyboardFocus (false);
  38101. setViewedComponent (new Component());
  38102. getViewedComponent()->addMouseListener (this, false);
  38103. getViewedComponent()->setWantsKeyboardFocus (false);
  38104. }
  38105. ~ListViewport()
  38106. {
  38107. getViewedComponent()->removeMouseListener (this);
  38108. getViewedComponent()->deleteAllChildren();
  38109. }
  38110. ListBoxRowComponent* getComponentForRow (const int row) const throw()
  38111. {
  38112. return static_cast <ListBoxRowComponent*>
  38113. (getViewedComponent()->getChildComponent (row % jmax (1, getViewedComponent()->getNumChildComponents())));
  38114. }
  38115. int getRowNumberOfComponent (Component* const rowComponent) const throw()
  38116. {
  38117. const int index = getIndexOfChildComponent (rowComponent);
  38118. const int num = getViewedComponent()->getNumChildComponents();
  38119. for (int i = num; --i >= 0;)
  38120. if (((firstIndex + i) % jmax (1, num)) == index)
  38121. return firstIndex + i;
  38122. return -1;
  38123. }
  38124. Component* getComponentForRowIfOnscreen (const int row) const throw()
  38125. {
  38126. return (row >= firstIndex && row < firstIndex + getViewedComponent()->getNumChildComponents())
  38127. ? getComponentForRow (row) : 0;
  38128. }
  38129. void visibleAreaChanged (int, int, int, int)
  38130. {
  38131. updateVisibleArea (true);
  38132. if (owner.getModel() != 0)
  38133. owner.getModel()->listWasScrolled();
  38134. }
  38135. void updateVisibleArea (const bool makeSureItUpdatesContent)
  38136. {
  38137. hasUpdated = false;
  38138. const int newX = getViewedComponent()->getX();
  38139. int newY = getViewedComponent()->getY();
  38140. const int newW = jmax (owner.minimumRowWidth, getMaximumVisibleWidth());
  38141. const int newH = owner.totalItems * owner.getRowHeight();
  38142. if (newY + newH < getMaximumVisibleHeight() && newH > getMaximumVisibleHeight())
  38143. newY = getMaximumVisibleHeight() - newH;
  38144. getViewedComponent()->setBounds (newX, newY, newW, newH);
  38145. if (makeSureItUpdatesContent && ! hasUpdated)
  38146. updateContents();
  38147. }
  38148. void updateContents()
  38149. {
  38150. hasUpdated = true;
  38151. const int rowHeight = owner.getRowHeight();
  38152. if (rowHeight > 0)
  38153. {
  38154. const int y = getViewPositionY();
  38155. const int w = getViewedComponent()->getWidth();
  38156. const int numNeeded = 2 + getMaximumVisibleHeight() / rowHeight;
  38157. while (numNeeded > getViewedComponent()->getNumChildComponents())
  38158. getViewedComponent()->addAndMakeVisible (new ListBoxRowComponent (owner));
  38159. jassert (numNeeded >= 0);
  38160. while (numNeeded < getViewedComponent()->getNumChildComponents())
  38161. {
  38162. Component* const rowToRemove
  38163. = getViewedComponent()->getChildComponent (getViewedComponent()->getNumChildComponents() - 1);
  38164. delete rowToRemove;
  38165. }
  38166. firstIndex = y / rowHeight;
  38167. firstWholeIndex = (y + rowHeight - 1) / rowHeight;
  38168. lastWholeIndex = (y + getMaximumVisibleHeight() - 1) / rowHeight;
  38169. for (int i = 0; i < numNeeded; ++i)
  38170. {
  38171. const int row = i + firstIndex;
  38172. ListBoxRowComponent* const rowComp = getComponentForRow (row);
  38173. if (rowComp != 0)
  38174. {
  38175. rowComp->setBounds (0, row * rowHeight, w, rowHeight);
  38176. rowComp->update (row, owner.isRowSelected (row));
  38177. }
  38178. }
  38179. }
  38180. if (owner.headerComponent != 0)
  38181. owner.headerComponent->setBounds (owner.outlineThickness + getViewedComponent()->getX(),
  38182. owner.outlineThickness,
  38183. jmax (owner.getWidth() - owner.outlineThickness * 2,
  38184. getViewedComponent()->getWidth()),
  38185. owner.headerComponent->getHeight());
  38186. }
  38187. void paint (Graphics& g)
  38188. {
  38189. if (isOpaque())
  38190. g.fillAll (owner.findColour (ListBox::backgroundColourId));
  38191. }
  38192. bool keyPressed (const KeyPress& key)
  38193. {
  38194. if (key.isKeyCode (KeyPress::upKey)
  38195. || key.isKeyCode (KeyPress::downKey)
  38196. || key.isKeyCode (KeyPress::pageUpKey)
  38197. || key.isKeyCode (KeyPress::pageDownKey)
  38198. || key.isKeyCode (KeyPress::homeKey)
  38199. || key.isKeyCode (KeyPress::endKey))
  38200. {
  38201. // we want to avoid these keypresses going to the viewport, and instead allow
  38202. // them to pass up to our listbox..
  38203. return false;
  38204. }
  38205. return Viewport::keyPressed (key);
  38206. }
  38207. juce_UseDebuggingNewOperator
  38208. private:
  38209. ListBox& owner;
  38210. ListViewport (const ListViewport&);
  38211. ListViewport& operator= (const ListViewport&);
  38212. };
  38213. ListBox::ListBox (const String& name, ListBoxModel* const model_)
  38214. : Component (name),
  38215. model (model_),
  38216. headerComponent (0),
  38217. totalItems (0),
  38218. rowHeight (22),
  38219. minimumRowWidth (0),
  38220. outlineThickness (0),
  38221. lastRowSelected (-1),
  38222. mouseMoveSelects (false),
  38223. multipleSelection (false),
  38224. hasDoneInitialUpdate (false)
  38225. {
  38226. addAndMakeVisible (viewport = new ListViewport (*this));
  38227. setWantsKeyboardFocus (true);
  38228. colourChanged();
  38229. }
  38230. ListBox::~ListBox()
  38231. {
  38232. deleteAllChildren();
  38233. }
  38234. void ListBox::setModel (ListBoxModel* const newModel)
  38235. {
  38236. if (model != newModel)
  38237. {
  38238. model = newModel;
  38239. updateContent();
  38240. }
  38241. }
  38242. void ListBox::setMultipleSelectionEnabled (bool b)
  38243. {
  38244. multipleSelection = b;
  38245. }
  38246. void ListBox::setMouseMoveSelectsRows (bool b)
  38247. {
  38248. mouseMoveSelects = b;
  38249. if (b)
  38250. addMouseListener (this, true);
  38251. }
  38252. void ListBox::paint (Graphics& g)
  38253. {
  38254. if (! hasDoneInitialUpdate)
  38255. updateContent();
  38256. g.fillAll (findColour (backgroundColourId));
  38257. }
  38258. void ListBox::paintOverChildren (Graphics& g)
  38259. {
  38260. if (outlineThickness > 0)
  38261. {
  38262. g.setColour (findColour (outlineColourId));
  38263. g.drawRect (0, 0, getWidth(), getHeight(), outlineThickness);
  38264. }
  38265. }
  38266. void ListBox::resized()
  38267. {
  38268. viewport->setBoundsInset (BorderSize (outlineThickness + ((headerComponent != 0) ? headerComponent->getHeight() : 0),
  38269. outlineThickness,
  38270. outlineThickness,
  38271. outlineThickness));
  38272. viewport->setSingleStepSizes (20, getRowHeight());
  38273. viewport->updateVisibleArea (false);
  38274. }
  38275. void ListBox::visibilityChanged()
  38276. {
  38277. viewport->updateVisibleArea (true);
  38278. }
  38279. Viewport* ListBox::getViewport() const throw()
  38280. {
  38281. return viewport;
  38282. }
  38283. void ListBox::updateContent()
  38284. {
  38285. hasDoneInitialUpdate = true;
  38286. totalItems = (model != 0) ? model->getNumRows() : 0;
  38287. bool selectionChanged = false;
  38288. if (selected [selected.size() - 1] >= totalItems)
  38289. {
  38290. selected.removeRange (Range <int> (totalItems, std::numeric_limits<int>::max()));
  38291. lastRowSelected = getSelectedRow (0);
  38292. selectionChanged = true;
  38293. }
  38294. viewport->updateVisibleArea (isVisible());
  38295. viewport->resized();
  38296. if (selectionChanged && model != 0)
  38297. model->selectedRowsChanged (lastRowSelected);
  38298. }
  38299. void ListBox::selectRow (const int row,
  38300. bool dontScroll,
  38301. bool deselectOthersFirst)
  38302. {
  38303. selectRowInternal (row, dontScroll, deselectOthersFirst, false);
  38304. }
  38305. void ListBox::selectRowInternal (const int row,
  38306. bool dontScroll,
  38307. bool deselectOthersFirst,
  38308. bool isMouseClick)
  38309. {
  38310. if (! multipleSelection)
  38311. deselectOthersFirst = true;
  38312. if ((! isRowSelected (row))
  38313. || (deselectOthersFirst && getNumSelectedRows() > 1))
  38314. {
  38315. if (((unsigned int) row) < (unsigned int) totalItems)
  38316. {
  38317. if (deselectOthersFirst)
  38318. selected.clear();
  38319. selected.addRange (Range<int> (row, row + 1));
  38320. if (getHeight() == 0 || getWidth() == 0)
  38321. dontScroll = true;
  38322. viewport->hasUpdated = false;
  38323. if (row < viewport->firstWholeIndex && ! dontScroll)
  38324. {
  38325. viewport->setViewPosition (viewport->getViewPositionX(),
  38326. row * getRowHeight());
  38327. }
  38328. else if (row >= viewport->lastWholeIndex && ! dontScroll)
  38329. {
  38330. const int rowsOnScreen = viewport->lastWholeIndex - viewport->firstWholeIndex;
  38331. if (row >= lastRowSelected + rowsOnScreen
  38332. && rowsOnScreen < totalItems - 1
  38333. && ! isMouseClick)
  38334. {
  38335. viewport->setViewPosition (viewport->getViewPositionX(),
  38336. jlimit (0, jmax (0, totalItems - rowsOnScreen), row)
  38337. * getRowHeight());
  38338. }
  38339. else
  38340. {
  38341. viewport->setViewPosition (viewport->getViewPositionX(),
  38342. jmax (0, (row + 1) * getRowHeight() - viewport->getMaximumVisibleHeight()));
  38343. }
  38344. }
  38345. if (! viewport->hasUpdated)
  38346. viewport->updateContents();
  38347. lastRowSelected = row;
  38348. model->selectedRowsChanged (row);
  38349. }
  38350. else
  38351. {
  38352. if (deselectOthersFirst)
  38353. deselectAllRows();
  38354. }
  38355. }
  38356. }
  38357. void ListBox::deselectRow (const int row)
  38358. {
  38359. if (selected.contains (row))
  38360. {
  38361. selected.removeRange (Range <int> (row, row + 1));
  38362. if (row == lastRowSelected)
  38363. lastRowSelected = getSelectedRow (0);
  38364. viewport->updateContents();
  38365. model->selectedRowsChanged (lastRowSelected);
  38366. }
  38367. }
  38368. void ListBox::setSelectedRows (const SparseSet<int>& setOfRowsToBeSelected,
  38369. const bool sendNotificationEventToModel)
  38370. {
  38371. selected = setOfRowsToBeSelected;
  38372. selected.removeRange (Range <int> (totalItems, std::numeric_limits<int>::max()));
  38373. if (! isRowSelected (lastRowSelected))
  38374. lastRowSelected = getSelectedRow (0);
  38375. viewport->updateContents();
  38376. if ((model != 0) && sendNotificationEventToModel)
  38377. model->selectedRowsChanged (lastRowSelected);
  38378. }
  38379. const SparseSet<int> ListBox::getSelectedRows() const
  38380. {
  38381. return selected;
  38382. }
  38383. void ListBox::selectRangeOfRows (int firstRow, int lastRow)
  38384. {
  38385. if (multipleSelection && (firstRow != lastRow))
  38386. {
  38387. const int numRows = totalItems - 1;
  38388. firstRow = jlimit (0, jmax (0, numRows), firstRow);
  38389. lastRow = jlimit (0, jmax (0, numRows), lastRow);
  38390. selected.addRange (Range <int> (jmin (firstRow, lastRow),
  38391. jmax (firstRow, lastRow) + 1));
  38392. selected.removeRange (Range <int> (lastRow, lastRow + 1));
  38393. }
  38394. selectRowInternal (lastRow, false, false, true);
  38395. }
  38396. void ListBox::flipRowSelection (const int row)
  38397. {
  38398. if (isRowSelected (row))
  38399. deselectRow (row);
  38400. else
  38401. selectRowInternal (row, false, false, true);
  38402. }
  38403. void ListBox::deselectAllRows()
  38404. {
  38405. if (! selected.isEmpty())
  38406. {
  38407. selected.clear();
  38408. lastRowSelected = -1;
  38409. viewport->updateContents();
  38410. if (model != 0)
  38411. model->selectedRowsChanged (lastRowSelected);
  38412. }
  38413. }
  38414. void ListBox::selectRowsBasedOnModifierKeys (const int row,
  38415. const ModifierKeys& mods)
  38416. {
  38417. if (multipleSelection && mods.isCommandDown())
  38418. {
  38419. flipRowSelection (row);
  38420. }
  38421. else if (multipleSelection && mods.isShiftDown() && lastRowSelected >= 0)
  38422. {
  38423. selectRangeOfRows (lastRowSelected, row);
  38424. }
  38425. else if ((! mods.isPopupMenu()) || ! isRowSelected (row))
  38426. {
  38427. selectRowInternal (row, false, true, true);
  38428. }
  38429. }
  38430. int ListBox::getNumSelectedRows() const
  38431. {
  38432. return selected.size();
  38433. }
  38434. int ListBox::getSelectedRow (const int index) const
  38435. {
  38436. return (((unsigned int) index) < (unsigned int) selected.size())
  38437. ? selected [index] : -1;
  38438. }
  38439. bool ListBox::isRowSelected (const int row) const
  38440. {
  38441. return selected.contains (row);
  38442. }
  38443. int ListBox::getLastRowSelected() const
  38444. {
  38445. return (isRowSelected (lastRowSelected)) ? lastRowSelected : -1;
  38446. }
  38447. int ListBox::getRowContainingPosition (const int x, const int y) const throw()
  38448. {
  38449. if (((unsigned int) x) < (unsigned int) getWidth())
  38450. {
  38451. const int row = (viewport->getViewPositionY() + y - viewport->getY()) / rowHeight;
  38452. if (((unsigned int) row) < (unsigned int) totalItems)
  38453. return row;
  38454. }
  38455. return -1;
  38456. }
  38457. int ListBox::getInsertionIndexForPosition (const int x, const int y) const throw()
  38458. {
  38459. if (((unsigned int) x) < (unsigned int) getWidth())
  38460. {
  38461. const int row = (viewport->getViewPositionY() + y + rowHeight / 2 - viewport->getY()) / rowHeight;
  38462. return jlimit (0, totalItems, row);
  38463. }
  38464. return -1;
  38465. }
  38466. Component* ListBox::getComponentForRowNumber (const int row) const throw()
  38467. {
  38468. Component* const listRowComp = viewport->getComponentForRowIfOnscreen (row);
  38469. return listRowComp != 0 ? listRowComp->getChildComponent (0) : 0;
  38470. }
  38471. int ListBox::getRowNumberOfComponent (Component* const rowComponent) const throw()
  38472. {
  38473. return viewport->getRowNumberOfComponent (rowComponent);
  38474. }
  38475. const Rectangle<int> ListBox::getRowPosition (const int rowNumber,
  38476. const bool relativeToComponentTopLeft) const throw()
  38477. {
  38478. int y = viewport->getY() + rowHeight * rowNumber;
  38479. if (relativeToComponentTopLeft)
  38480. y -= viewport->getViewPositionY();
  38481. return Rectangle<int> (viewport->getX(), y,
  38482. viewport->getViewedComponent()->getWidth(), rowHeight);
  38483. }
  38484. void ListBox::setVerticalPosition (const double proportion)
  38485. {
  38486. const int offscreen = viewport->getViewedComponent()->getHeight() - viewport->getHeight();
  38487. viewport->setViewPosition (viewport->getViewPositionX(),
  38488. jmax (0, roundToInt (proportion * offscreen)));
  38489. }
  38490. double ListBox::getVerticalPosition() const
  38491. {
  38492. const int offscreen = viewport->getViewedComponent()->getHeight() - viewport->getHeight();
  38493. return (offscreen > 0) ? viewport->getViewPositionY() / (double) offscreen
  38494. : 0;
  38495. }
  38496. int ListBox::getVisibleRowWidth() const throw()
  38497. {
  38498. return viewport->getViewWidth();
  38499. }
  38500. void ListBox::scrollToEnsureRowIsOnscreen (const int row)
  38501. {
  38502. if (row < viewport->firstWholeIndex)
  38503. {
  38504. viewport->setViewPosition (viewport->getViewPositionX(),
  38505. row * getRowHeight());
  38506. }
  38507. else if (row >= viewport->lastWholeIndex)
  38508. {
  38509. viewport->setViewPosition (viewport->getViewPositionX(),
  38510. jmax (0, (row + 1) * getRowHeight() - viewport->getMaximumVisibleHeight()));
  38511. }
  38512. }
  38513. bool ListBox::keyPressed (const KeyPress& key)
  38514. {
  38515. const int numVisibleRows = viewport->getHeight() / getRowHeight();
  38516. const bool multiple = multipleSelection
  38517. && (lastRowSelected >= 0)
  38518. && (key.getModifiers().isShiftDown()
  38519. || key.getModifiers().isCtrlDown()
  38520. || key.getModifiers().isCommandDown());
  38521. if (key.isKeyCode (KeyPress::upKey))
  38522. {
  38523. if (multiple)
  38524. selectRangeOfRows (lastRowSelected, lastRowSelected - 1);
  38525. else
  38526. selectRow (jmax (0, lastRowSelected - 1));
  38527. }
  38528. else if (key.isKeyCode (KeyPress::returnKey)
  38529. && isRowSelected (lastRowSelected))
  38530. {
  38531. if (model != 0)
  38532. model->returnKeyPressed (lastRowSelected);
  38533. }
  38534. else if (key.isKeyCode (KeyPress::pageUpKey))
  38535. {
  38536. if (multiple)
  38537. selectRangeOfRows (lastRowSelected, lastRowSelected - numVisibleRows);
  38538. else
  38539. selectRow (jmax (0, jmax (0, lastRowSelected) - numVisibleRows));
  38540. }
  38541. else if (key.isKeyCode (KeyPress::pageDownKey))
  38542. {
  38543. if (multiple)
  38544. selectRangeOfRows (lastRowSelected, lastRowSelected + numVisibleRows);
  38545. else
  38546. selectRow (jmin (totalItems - 1, jmax (0, lastRowSelected) + numVisibleRows));
  38547. }
  38548. else if (key.isKeyCode (KeyPress::homeKey))
  38549. {
  38550. if (multiple && key.getModifiers().isShiftDown())
  38551. selectRangeOfRows (lastRowSelected, 0);
  38552. else
  38553. selectRow (0);
  38554. }
  38555. else if (key.isKeyCode (KeyPress::endKey))
  38556. {
  38557. if (multiple && key.getModifiers().isShiftDown())
  38558. selectRangeOfRows (lastRowSelected, totalItems - 1);
  38559. else
  38560. selectRow (totalItems - 1);
  38561. }
  38562. else if (key.isKeyCode (KeyPress::downKey))
  38563. {
  38564. if (multiple)
  38565. selectRangeOfRows (lastRowSelected, lastRowSelected + 1);
  38566. else
  38567. selectRow (jmin (totalItems - 1, jmax (0, lastRowSelected) + 1));
  38568. }
  38569. else if ((key.isKeyCode (KeyPress::deleteKey) || key.isKeyCode (KeyPress::backspaceKey))
  38570. && isRowSelected (lastRowSelected))
  38571. {
  38572. if (model != 0)
  38573. model->deleteKeyPressed (lastRowSelected);
  38574. }
  38575. else if (multiple && key == KeyPress ('a', ModifierKeys::commandModifier, 0))
  38576. {
  38577. selectRangeOfRows (0, std::numeric_limits<int>::max());
  38578. }
  38579. else
  38580. {
  38581. return false;
  38582. }
  38583. return true;
  38584. }
  38585. bool ListBox::keyStateChanged (const bool isKeyDown)
  38586. {
  38587. return isKeyDown
  38588. && (KeyPress::isKeyCurrentlyDown (KeyPress::upKey)
  38589. || KeyPress::isKeyCurrentlyDown (KeyPress::pageUpKey)
  38590. || KeyPress::isKeyCurrentlyDown (KeyPress::downKey)
  38591. || KeyPress::isKeyCurrentlyDown (KeyPress::pageDownKey)
  38592. || KeyPress::isKeyCurrentlyDown (KeyPress::homeKey)
  38593. || KeyPress::isKeyCurrentlyDown (KeyPress::endKey)
  38594. || KeyPress::isKeyCurrentlyDown (KeyPress::returnKey));
  38595. }
  38596. void ListBox::mouseWheelMove (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY)
  38597. {
  38598. getHorizontalScrollBar()->mouseWheelMove (e, wheelIncrementX, 0);
  38599. getVerticalScrollBar()->mouseWheelMove (e, 0, wheelIncrementY);
  38600. }
  38601. void ListBox::mouseMove (const MouseEvent& e)
  38602. {
  38603. if (mouseMoveSelects)
  38604. {
  38605. const MouseEvent e2 (e.getEventRelativeTo (this));
  38606. selectRow (getRowContainingPosition (e2.x, e2.y), true);
  38607. }
  38608. }
  38609. void ListBox::mouseExit (const MouseEvent& e)
  38610. {
  38611. mouseMove (e);
  38612. }
  38613. void ListBox::mouseUp (const MouseEvent& e)
  38614. {
  38615. if (e.mouseWasClicked() && model != 0)
  38616. model->backgroundClicked();
  38617. }
  38618. void ListBox::setRowHeight (const int newHeight)
  38619. {
  38620. rowHeight = jmax (1, newHeight);
  38621. viewport->setSingleStepSizes (20, rowHeight);
  38622. updateContent();
  38623. }
  38624. int ListBox::getNumRowsOnScreen() const throw()
  38625. {
  38626. return viewport->getMaximumVisibleHeight() / rowHeight;
  38627. }
  38628. void ListBox::setMinimumContentWidth (const int newMinimumWidth)
  38629. {
  38630. minimumRowWidth = newMinimumWidth;
  38631. updateContent();
  38632. }
  38633. int ListBox::getVisibleContentWidth() const throw()
  38634. {
  38635. return viewport->getMaximumVisibleWidth();
  38636. }
  38637. ScrollBar* ListBox::getVerticalScrollBar() const throw()
  38638. {
  38639. return viewport->getVerticalScrollBar();
  38640. }
  38641. ScrollBar* ListBox::getHorizontalScrollBar() const throw()
  38642. {
  38643. return viewport->getHorizontalScrollBar();
  38644. }
  38645. void ListBox::colourChanged()
  38646. {
  38647. setOpaque (findColour (backgroundColourId).isOpaque());
  38648. viewport->setOpaque (isOpaque());
  38649. repaint();
  38650. }
  38651. void ListBox::setOutlineThickness (const int outlineThickness_)
  38652. {
  38653. outlineThickness = outlineThickness_;
  38654. resized();
  38655. }
  38656. void ListBox::setHeaderComponent (Component* const newHeaderComponent)
  38657. {
  38658. if (headerComponent != newHeaderComponent)
  38659. {
  38660. delete headerComponent;
  38661. headerComponent = newHeaderComponent;
  38662. addAndMakeVisible (newHeaderComponent);
  38663. ListBox::resized();
  38664. }
  38665. }
  38666. void ListBox::repaintRow (const int rowNumber) throw()
  38667. {
  38668. const Rectangle<int> r (getRowPosition (rowNumber, true));
  38669. repaint (r.getX(), r.getY(), r.getWidth(), r.getHeight());
  38670. }
  38671. Image* ListBox::createSnapshotOfSelectedRows (int& imageX, int& imageY)
  38672. {
  38673. Rectangle<int> imageArea;
  38674. const int firstRow = getRowContainingPosition (0, 0);
  38675. int i;
  38676. for (i = getNumRowsOnScreen() + 2; --i >= 0;)
  38677. {
  38678. Component* rowComp = viewport->getComponentForRowIfOnscreen (firstRow + i);
  38679. if (rowComp != 0 && isRowSelected (firstRow + i))
  38680. {
  38681. const Point<int> pos (rowComp->relativePositionToOtherComponent (this, Point<int>()));
  38682. const Rectangle<int> rowRect (pos.getX(), pos.getY(), rowComp->getWidth(), rowComp->getHeight());
  38683. if (imageArea.isEmpty())
  38684. imageArea = rowRect;
  38685. else
  38686. imageArea = imageArea.getUnion (rowRect);
  38687. }
  38688. }
  38689. imageArea = imageArea.getIntersection (getLocalBounds());
  38690. imageX = imageArea.getX();
  38691. imageY = imageArea.getY();
  38692. Image* snapshot = Image::createNativeImage (Image::ARGB, imageArea.getWidth(), imageArea.getHeight(), true);
  38693. for (i = getNumRowsOnScreen() + 2; --i >= 0;)
  38694. {
  38695. Component* rowComp = viewport->getComponentForRowIfOnscreen (firstRow + i);
  38696. if (rowComp != 0 && isRowSelected (firstRow + i))
  38697. {
  38698. const Point<int> pos (rowComp->relativePositionToOtherComponent (this, Point<int>()));
  38699. Graphics g (*snapshot);
  38700. g.setOrigin (pos.getX() - imageX, pos.getY() - imageY);
  38701. if (g.reduceClipRegion (0, 0, rowComp->getWidth(), rowComp->getHeight()))
  38702. rowComp->paintEntireComponent (g);
  38703. }
  38704. }
  38705. return snapshot;
  38706. }
  38707. void ListBox::startDragAndDrop (const MouseEvent& e, const String& dragDescription)
  38708. {
  38709. DragAndDropContainer* const dragContainer
  38710. = DragAndDropContainer::findParentDragContainerFor (this);
  38711. if (dragContainer != 0)
  38712. {
  38713. int x, y;
  38714. Image* dragImage = createSnapshotOfSelectedRows (x, y);
  38715. dragImage->multiplyAllAlphas (0.6f);
  38716. MouseEvent e2 (e.getEventRelativeTo (this));
  38717. const Point<int> p (x - e2.x, y - e2.y);
  38718. dragContainer->startDragging (dragDescription, this, dragImage, true, &p);
  38719. }
  38720. else
  38721. {
  38722. // to be able to do a drag-and-drop operation, the listbox needs to
  38723. // be inside a component which is also a DragAndDropContainer.
  38724. jassertfalse
  38725. }
  38726. }
  38727. Component* ListBoxModel::refreshComponentForRow (int, bool, Component* existingComponentToUpdate)
  38728. {
  38729. (void) existingComponentToUpdate;
  38730. jassert (existingComponentToUpdate == 0); // indicates a failure in the code the recycles the components
  38731. return 0;
  38732. }
  38733. void ListBoxModel::listBoxItemClicked (int, const MouseEvent&)
  38734. {
  38735. }
  38736. void ListBoxModel::listBoxItemDoubleClicked (int, const MouseEvent&)
  38737. {
  38738. }
  38739. void ListBoxModel::backgroundClicked()
  38740. {
  38741. }
  38742. void ListBoxModel::selectedRowsChanged (int)
  38743. {
  38744. }
  38745. void ListBoxModel::deleteKeyPressed (int)
  38746. {
  38747. }
  38748. void ListBoxModel::returnKeyPressed (int)
  38749. {
  38750. }
  38751. void ListBoxModel::listWasScrolled()
  38752. {
  38753. }
  38754. const String ListBoxModel::getDragSourceDescription (const SparseSet<int>&)
  38755. {
  38756. return String::empty;
  38757. }
  38758. const String ListBoxModel::getTooltipForRow (int)
  38759. {
  38760. return String::empty;
  38761. }
  38762. END_JUCE_NAMESPACE
  38763. /*** End of inlined file: juce_ListBox.cpp ***/
  38764. /*** Start of inlined file: juce_ProgressBar.cpp ***/
  38765. BEGIN_JUCE_NAMESPACE
  38766. ProgressBar::ProgressBar (double& progress_)
  38767. : progress (progress_),
  38768. displayPercentage (true),
  38769. lastCallbackTime (0)
  38770. {
  38771. currentValue = jlimit (0.0, 1.0, progress);
  38772. }
  38773. ProgressBar::~ProgressBar()
  38774. {
  38775. }
  38776. void ProgressBar::setPercentageDisplay (const bool shouldDisplayPercentage)
  38777. {
  38778. displayPercentage = shouldDisplayPercentage;
  38779. repaint();
  38780. }
  38781. void ProgressBar::setTextToDisplay (const String& text)
  38782. {
  38783. displayPercentage = false;
  38784. displayedMessage = text;
  38785. }
  38786. void ProgressBar::lookAndFeelChanged()
  38787. {
  38788. setOpaque (findColour (backgroundColourId).isOpaque());
  38789. }
  38790. void ProgressBar::colourChanged()
  38791. {
  38792. lookAndFeelChanged();
  38793. }
  38794. void ProgressBar::paint (Graphics& g)
  38795. {
  38796. String text;
  38797. if (displayPercentage)
  38798. {
  38799. if (currentValue >= 0 && currentValue <= 1.0)
  38800. text << roundToInt (currentValue * 100.0) << '%';
  38801. }
  38802. else
  38803. {
  38804. text = displayedMessage;
  38805. }
  38806. getLookAndFeel().drawProgressBar (g, *this,
  38807. getWidth(), getHeight(),
  38808. currentValue, text);
  38809. }
  38810. void ProgressBar::visibilityChanged()
  38811. {
  38812. if (isVisible())
  38813. startTimer (30);
  38814. else
  38815. stopTimer();
  38816. }
  38817. void ProgressBar::timerCallback()
  38818. {
  38819. double newProgress = progress;
  38820. const uint32 now = Time::getMillisecondCounter();
  38821. const int timeSinceLastCallback = (int) (now - lastCallbackTime);
  38822. lastCallbackTime = now;
  38823. if (currentValue != newProgress
  38824. || newProgress < 0 || newProgress >= 1.0
  38825. || currentMessage != displayedMessage)
  38826. {
  38827. if (currentValue < newProgress
  38828. && newProgress >= 0 && newProgress < 1.0
  38829. && currentValue >= 0 && currentValue < 1.0)
  38830. {
  38831. newProgress = jmin (currentValue + 0.0008 * timeSinceLastCallback,
  38832. newProgress);
  38833. }
  38834. currentValue = newProgress;
  38835. currentMessage = displayedMessage;
  38836. repaint();
  38837. }
  38838. }
  38839. END_JUCE_NAMESPACE
  38840. /*** End of inlined file: juce_ProgressBar.cpp ***/
  38841. /*** Start of inlined file: juce_Slider.cpp ***/
  38842. BEGIN_JUCE_NAMESPACE
  38843. class SliderPopupDisplayComponent : public BubbleComponent
  38844. {
  38845. public:
  38846. SliderPopupDisplayComponent (Slider* const owner_)
  38847. : owner (owner_),
  38848. font (15.0f, Font::bold)
  38849. {
  38850. setAlwaysOnTop (true);
  38851. }
  38852. ~SliderPopupDisplayComponent()
  38853. {
  38854. }
  38855. void paintContent (Graphics& g, int w, int h)
  38856. {
  38857. g.setFont (font);
  38858. g.setColour (Colours::black);
  38859. g.drawFittedText (text, 0, 0, w, h, Justification::centred, 1);
  38860. }
  38861. void getContentSize (int& w, int& h)
  38862. {
  38863. w = font.getStringWidth (text) + 18;
  38864. h = (int) (font.getHeight() * 1.6f);
  38865. }
  38866. void updatePosition (const String& newText)
  38867. {
  38868. if (text != newText)
  38869. {
  38870. text = newText;
  38871. repaint();
  38872. }
  38873. BubbleComponent::setPosition (owner);
  38874. }
  38875. juce_UseDebuggingNewOperator
  38876. private:
  38877. Slider* owner;
  38878. Font font;
  38879. String text;
  38880. SliderPopupDisplayComponent (const SliderPopupDisplayComponent&);
  38881. SliderPopupDisplayComponent& operator= (const SliderPopupDisplayComponent&);
  38882. };
  38883. Slider::Slider (const String& name)
  38884. : Component (name),
  38885. lastCurrentValue (0),
  38886. lastValueMin (0),
  38887. lastValueMax (0),
  38888. minimum (0),
  38889. maximum (10),
  38890. interval (0),
  38891. skewFactor (1.0),
  38892. velocityModeSensitivity (1.0),
  38893. velocityModeOffset (0.0),
  38894. velocityModeThreshold (1),
  38895. rotaryStart (float_Pi * 1.2f),
  38896. rotaryEnd (float_Pi * 2.8f),
  38897. numDecimalPlaces (7),
  38898. sliderRegionStart (0),
  38899. sliderRegionSize (1),
  38900. sliderBeingDragged (-1),
  38901. pixelsForFullDragExtent (250),
  38902. style (LinearHorizontal),
  38903. textBoxPos (TextBoxLeft),
  38904. textBoxWidth (80),
  38905. textBoxHeight (20),
  38906. incDecButtonMode (incDecButtonsNotDraggable),
  38907. editableText (true),
  38908. doubleClickToValue (false),
  38909. isVelocityBased (false),
  38910. userKeyOverridesVelocity (true),
  38911. rotaryStop (true),
  38912. incDecButtonsSideBySide (false),
  38913. sendChangeOnlyOnRelease (false),
  38914. popupDisplayEnabled (false),
  38915. menuEnabled (false),
  38916. menuShown (false),
  38917. scrollWheelEnabled (true),
  38918. snapsToMousePos (true),
  38919. valueBox (0),
  38920. incButton (0),
  38921. decButton (0),
  38922. popupDisplay (0),
  38923. parentForPopupDisplay (0)
  38924. {
  38925. setWantsKeyboardFocus (false);
  38926. setRepaintsOnMouseActivity (true);
  38927. lookAndFeelChanged();
  38928. updateText();
  38929. currentValue.addListener (this);
  38930. valueMin.addListener (this);
  38931. valueMax.addListener (this);
  38932. }
  38933. Slider::~Slider()
  38934. {
  38935. currentValue.removeListener (this);
  38936. valueMin.removeListener (this);
  38937. valueMax.removeListener (this);
  38938. popupDisplay = 0;
  38939. deleteAllChildren();
  38940. }
  38941. void Slider::handleAsyncUpdate()
  38942. {
  38943. cancelPendingUpdate();
  38944. Component::BailOutChecker checker (this);
  38945. listeners.callChecked (checker, &SliderListener::sliderValueChanged, this);
  38946. }
  38947. void Slider::sendDragStart()
  38948. {
  38949. startedDragging();
  38950. Component::BailOutChecker checker (this);
  38951. listeners.callChecked (checker, &SliderListener::sliderDragStarted, this);
  38952. }
  38953. void Slider::sendDragEnd()
  38954. {
  38955. stoppedDragging();
  38956. sliderBeingDragged = -1;
  38957. Component::BailOutChecker checker (this);
  38958. listeners.callChecked (checker, &SliderListener::sliderDragEnded, this);
  38959. }
  38960. void Slider::addListener (SliderListener* const listener)
  38961. {
  38962. listeners.add (listener);
  38963. }
  38964. void Slider::removeListener (SliderListener* const listener)
  38965. {
  38966. listeners.remove (listener);
  38967. }
  38968. void Slider::setSliderStyle (const SliderStyle newStyle)
  38969. {
  38970. if (style != newStyle)
  38971. {
  38972. style = newStyle;
  38973. repaint();
  38974. lookAndFeelChanged();
  38975. }
  38976. }
  38977. void Slider::setRotaryParameters (const float startAngleRadians,
  38978. const float endAngleRadians,
  38979. const bool stopAtEnd)
  38980. {
  38981. // make sure the values are sensible..
  38982. jassert (rotaryStart >= 0 && rotaryEnd >= 0);
  38983. jassert (rotaryStart < float_Pi * 4.0f && rotaryEnd < float_Pi * 4.0f);
  38984. jassert (rotaryStart < rotaryEnd);
  38985. rotaryStart = startAngleRadians;
  38986. rotaryEnd = endAngleRadians;
  38987. rotaryStop = stopAtEnd;
  38988. }
  38989. void Slider::setVelocityBasedMode (const bool velBased)
  38990. {
  38991. isVelocityBased = velBased;
  38992. }
  38993. void Slider::setVelocityModeParameters (const double sensitivity,
  38994. const int threshold,
  38995. const double offset,
  38996. const bool userCanPressKeyToSwapMode)
  38997. {
  38998. jassert (threshold >= 0);
  38999. jassert (sensitivity > 0);
  39000. jassert (offset >= 0);
  39001. velocityModeSensitivity = sensitivity;
  39002. velocityModeOffset = offset;
  39003. velocityModeThreshold = threshold;
  39004. userKeyOverridesVelocity = userCanPressKeyToSwapMode;
  39005. }
  39006. void Slider::setSkewFactor (const double factor)
  39007. {
  39008. skewFactor = factor;
  39009. }
  39010. void Slider::setSkewFactorFromMidPoint (const double sliderValueToShowAtMidPoint)
  39011. {
  39012. if (maximum > minimum)
  39013. skewFactor = log (0.5) / log ((sliderValueToShowAtMidPoint - minimum)
  39014. / (maximum - minimum));
  39015. }
  39016. void Slider::setMouseDragSensitivity (const int distanceForFullScaleDrag)
  39017. {
  39018. jassert (distanceForFullScaleDrag > 0);
  39019. pixelsForFullDragExtent = distanceForFullScaleDrag;
  39020. }
  39021. void Slider::setIncDecButtonsMode (const IncDecButtonMode mode)
  39022. {
  39023. if (incDecButtonMode != mode)
  39024. {
  39025. incDecButtonMode = mode;
  39026. lookAndFeelChanged();
  39027. }
  39028. }
  39029. void Slider::setTextBoxStyle (const TextEntryBoxPosition newPosition,
  39030. const bool isReadOnly,
  39031. const int textEntryBoxWidth,
  39032. const int textEntryBoxHeight)
  39033. {
  39034. textBoxPos = newPosition;
  39035. editableText = ! isReadOnly;
  39036. textBoxWidth = textEntryBoxWidth;
  39037. textBoxHeight = textEntryBoxHeight;
  39038. repaint();
  39039. lookAndFeelChanged();
  39040. }
  39041. void Slider::setTextBoxIsEditable (const bool shouldBeEditable)
  39042. {
  39043. editableText = shouldBeEditable;
  39044. if (valueBox != 0)
  39045. valueBox->setEditable (shouldBeEditable && isEnabled());
  39046. }
  39047. void Slider::showTextBox()
  39048. {
  39049. jassert (editableText); // this should probably be avoided in read-only sliders.
  39050. if (valueBox != 0)
  39051. valueBox->showEditor();
  39052. }
  39053. void Slider::hideTextBox (const bool discardCurrentEditorContents)
  39054. {
  39055. if (valueBox != 0)
  39056. {
  39057. valueBox->hideEditor (discardCurrentEditorContents);
  39058. if (discardCurrentEditorContents)
  39059. updateText();
  39060. }
  39061. }
  39062. void Slider::setChangeNotificationOnlyOnRelease (const bool onlyNotifyOnRelease)
  39063. {
  39064. sendChangeOnlyOnRelease = onlyNotifyOnRelease;
  39065. }
  39066. void Slider::setSliderSnapsToMousePosition (const bool shouldSnapToMouse)
  39067. {
  39068. snapsToMousePos = shouldSnapToMouse;
  39069. }
  39070. void Slider::setPopupDisplayEnabled (const bool enabled,
  39071. Component* const parentComponentToUse)
  39072. {
  39073. popupDisplayEnabled = enabled;
  39074. parentForPopupDisplay = parentComponentToUse;
  39075. }
  39076. void Slider::colourChanged()
  39077. {
  39078. lookAndFeelChanged();
  39079. }
  39080. void Slider::lookAndFeelChanged()
  39081. {
  39082. const String previousTextBoxContent (valueBox != 0 ? valueBox->getText()
  39083. : getTextFromValue (currentValue.getValue()));
  39084. deleteAllChildren();
  39085. valueBox = 0;
  39086. LookAndFeel& lf = getLookAndFeel();
  39087. if (textBoxPos != NoTextBox)
  39088. {
  39089. addAndMakeVisible (valueBox = getLookAndFeel().createSliderTextBox (*this));
  39090. valueBox->setWantsKeyboardFocus (false);
  39091. valueBox->setText (previousTextBoxContent, false);
  39092. valueBox->setEditable (editableText && isEnabled());
  39093. valueBox->addListener (this);
  39094. if (style == LinearBar)
  39095. valueBox->addMouseListener (this, false);
  39096. valueBox->setTooltip (getTooltip());
  39097. }
  39098. if (style == IncDecButtons)
  39099. {
  39100. addAndMakeVisible (incButton = lf.createSliderButton (true));
  39101. incButton->addButtonListener (this);
  39102. addAndMakeVisible (decButton = lf.createSliderButton (false));
  39103. decButton->addButtonListener (this);
  39104. if (incDecButtonMode != incDecButtonsNotDraggable)
  39105. {
  39106. incButton->addMouseListener (this, false);
  39107. decButton->addMouseListener (this, false);
  39108. }
  39109. else
  39110. {
  39111. incButton->setRepeatSpeed (300, 100, 20);
  39112. incButton->addMouseListener (decButton, false);
  39113. decButton->setRepeatSpeed (300, 100, 20);
  39114. decButton->addMouseListener (incButton, false);
  39115. }
  39116. incButton->setTooltip (getTooltip());
  39117. decButton->setTooltip (getTooltip());
  39118. }
  39119. setComponentEffect (lf.getSliderEffect());
  39120. resized();
  39121. repaint();
  39122. }
  39123. void Slider::setRange (const double newMin,
  39124. const double newMax,
  39125. const double newInt)
  39126. {
  39127. if (minimum != newMin
  39128. || maximum != newMax
  39129. || interval != newInt)
  39130. {
  39131. minimum = newMin;
  39132. maximum = newMax;
  39133. interval = newInt;
  39134. // figure out the number of DPs needed to display all values at this
  39135. // interval setting.
  39136. numDecimalPlaces = 7;
  39137. if (newInt != 0)
  39138. {
  39139. int v = abs ((int) (newInt * 10000000));
  39140. while ((v % 10) == 0)
  39141. {
  39142. --numDecimalPlaces;
  39143. v /= 10;
  39144. }
  39145. }
  39146. // keep the current values inside the new range..
  39147. if (style != TwoValueHorizontal && style != TwoValueVertical)
  39148. {
  39149. setValue (getValue(), false, false);
  39150. }
  39151. else
  39152. {
  39153. setMinValue (getMinValue(), false, false);
  39154. setMaxValue (getMaxValue(), false, false);
  39155. }
  39156. updateText();
  39157. }
  39158. }
  39159. void Slider::triggerChangeMessage (const bool synchronous)
  39160. {
  39161. if (synchronous)
  39162. handleAsyncUpdate();
  39163. else
  39164. triggerAsyncUpdate();
  39165. valueChanged();
  39166. }
  39167. void Slider::valueChanged (Value& value)
  39168. {
  39169. if (value.refersToSameSourceAs (currentValue))
  39170. {
  39171. if (style != TwoValueHorizontal && style != TwoValueVertical)
  39172. setValue (currentValue.getValue(), false, false);
  39173. }
  39174. else if (value.refersToSameSourceAs (valueMin))
  39175. setMinValue (valueMin.getValue(), false, false, true);
  39176. else if (value.refersToSameSourceAs (valueMax))
  39177. setMaxValue (valueMax.getValue(), false, false, true);
  39178. }
  39179. double Slider::getValue() const
  39180. {
  39181. // for a two-value style slider, you should use the getMinValue() and getMaxValue()
  39182. // methods to get the two values.
  39183. jassert (style != TwoValueHorizontal && style != TwoValueVertical);
  39184. return currentValue.getValue();
  39185. }
  39186. void Slider::setValue (double newValue,
  39187. const bool sendUpdateMessage,
  39188. const bool sendMessageSynchronously)
  39189. {
  39190. // for a two-value style slider, you should use the setMinValue() and setMaxValue()
  39191. // methods to set the two values.
  39192. jassert (style != TwoValueHorizontal && style != TwoValueVertical);
  39193. newValue = constrainedValue (newValue);
  39194. if (style == ThreeValueHorizontal || style == ThreeValueVertical)
  39195. {
  39196. jassert ((double) valueMin.getValue() <= (double) valueMax.getValue());
  39197. newValue = jlimit ((double) valueMin.getValue(),
  39198. (double) valueMax.getValue(),
  39199. newValue);
  39200. }
  39201. if (newValue != lastCurrentValue)
  39202. {
  39203. if (valueBox != 0)
  39204. valueBox->hideEditor (true);
  39205. lastCurrentValue = newValue;
  39206. currentValue = newValue;
  39207. updateText();
  39208. repaint();
  39209. if (popupDisplay != 0)
  39210. {
  39211. static_cast <SliderPopupDisplayComponent*> (static_cast <Component*> (popupDisplay))
  39212. ->updatePosition (getTextFromValue (newValue));
  39213. popupDisplay->repaint();
  39214. }
  39215. if (sendUpdateMessage)
  39216. triggerChangeMessage (sendMessageSynchronously);
  39217. }
  39218. }
  39219. double Slider::getMinValue() const
  39220. {
  39221. // The minimum value only applies to sliders that are in two- or three-value mode.
  39222. jassert (style == TwoValueHorizontal || style == TwoValueVertical
  39223. || style == ThreeValueHorizontal || style == ThreeValueVertical);
  39224. return valueMin.getValue();
  39225. }
  39226. double Slider::getMaxValue() const
  39227. {
  39228. // The maximum value only applies to sliders that are in two- or three-value mode.
  39229. jassert (style == TwoValueHorizontal || style == TwoValueVertical
  39230. || style == ThreeValueHorizontal || style == ThreeValueVertical);
  39231. return valueMax.getValue();
  39232. }
  39233. void Slider::setMinValue (double newValue, const bool sendUpdateMessage, const bool sendMessageSynchronously, const bool allowNudgingOfOtherValues)
  39234. {
  39235. // The minimum value only applies to sliders that are in two- or three-value mode.
  39236. jassert (style == TwoValueHorizontal || style == TwoValueVertical
  39237. || style == ThreeValueHorizontal || style == ThreeValueVertical);
  39238. newValue = constrainedValue (newValue);
  39239. if (style == TwoValueHorizontal || style == TwoValueVertical)
  39240. {
  39241. if (allowNudgingOfOtherValues && newValue > (double) valueMax.getValue())
  39242. setMaxValue (newValue, sendUpdateMessage, sendMessageSynchronously);
  39243. newValue = jmin ((double) valueMax.getValue(), newValue);
  39244. }
  39245. else
  39246. {
  39247. if (allowNudgingOfOtherValues && newValue > lastCurrentValue)
  39248. setValue (newValue, sendUpdateMessage, sendMessageSynchronously);
  39249. newValue = jmin (lastCurrentValue, newValue);
  39250. }
  39251. if (lastValueMin != newValue)
  39252. {
  39253. lastValueMin = newValue;
  39254. valueMin = newValue;
  39255. repaint();
  39256. if (popupDisplay != 0)
  39257. {
  39258. static_cast <SliderPopupDisplayComponent*> (static_cast <Component*> (popupDisplay))
  39259. ->updatePosition (getTextFromValue (newValue));
  39260. popupDisplay->repaint();
  39261. }
  39262. if (sendUpdateMessage)
  39263. triggerChangeMessage (sendMessageSynchronously);
  39264. }
  39265. }
  39266. void Slider::setMaxValue (double newValue, const bool sendUpdateMessage, const bool sendMessageSynchronously, const bool allowNudgingOfOtherValues)
  39267. {
  39268. // The maximum value only applies to sliders that are in two- or three-value mode.
  39269. jassert (style == TwoValueHorizontal || style == TwoValueVertical
  39270. || style == ThreeValueHorizontal || style == ThreeValueVertical);
  39271. newValue = constrainedValue (newValue);
  39272. if (style == TwoValueHorizontal || style == TwoValueVertical)
  39273. {
  39274. if (allowNudgingOfOtherValues && newValue < (double) valueMin.getValue())
  39275. setMinValue (newValue, sendUpdateMessage, sendMessageSynchronously);
  39276. newValue = jmax ((double) valueMin.getValue(), newValue);
  39277. }
  39278. else
  39279. {
  39280. if (allowNudgingOfOtherValues && newValue < lastCurrentValue)
  39281. setValue (newValue, sendUpdateMessage, sendMessageSynchronously);
  39282. newValue = jmax (lastCurrentValue, newValue);
  39283. }
  39284. if (lastValueMax != newValue)
  39285. {
  39286. lastValueMax = newValue;
  39287. valueMax = newValue;
  39288. repaint();
  39289. if (popupDisplay != 0)
  39290. {
  39291. static_cast <SliderPopupDisplayComponent*> (static_cast <Component*> (popupDisplay))
  39292. ->updatePosition (getTextFromValue (valueMax.getValue()));
  39293. popupDisplay->repaint();
  39294. }
  39295. if (sendUpdateMessage)
  39296. triggerChangeMessage (sendMessageSynchronously);
  39297. }
  39298. }
  39299. void Slider::setDoubleClickReturnValue (const bool isDoubleClickEnabled,
  39300. const double valueToSetOnDoubleClick)
  39301. {
  39302. doubleClickToValue = isDoubleClickEnabled;
  39303. doubleClickReturnValue = valueToSetOnDoubleClick;
  39304. }
  39305. double Slider::getDoubleClickReturnValue (bool& isEnabled_) const
  39306. {
  39307. isEnabled_ = doubleClickToValue;
  39308. return doubleClickReturnValue;
  39309. }
  39310. void Slider::updateText()
  39311. {
  39312. if (valueBox != 0)
  39313. valueBox->setText (getTextFromValue (currentValue.getValue()), false);
  39314. }
  39315. void Slider::setTextValueSuffix (const String& suffix)
  39316. {
  39317. if (textSuffix != suffix)
  39318. {
  39319. textSuffix = suffix;
  39320. updateText();
  39321. }
  39322. }
  39323. const String Slider::getTextValueSuffix() const
  39324. {
  39325. return textSuffix;
  39326. }
  39327. const String Slider::getTextFromValue (double v)
  39328. {
  39329. if (getNumDecimalPlacesToDisplay() > 0)
  39330. return String (v, getNumDecimalPlacesToDisplay()) + getTextValueSuffix();
  39331. else
  39332. return String (roundToInt (v)) + getTextValueSuffix();
  39333. }
  39334. double Slider::getValueFromText (const String& text)
  39335. {
  39336. String t (text.trimStart());
  39337. if (t.endsWith (textSuffix))
  39338. t = t.substring (0, t.length() - textSuffix.length());
  39339. while (t.startsWithChar ('+'))
  39340. t = t.substring (1).trimStart();
  39341. return t.initialSectionContainingOnly ("0123456789.,-")
  39342. .getDoubleValue();
  39343. }
  39344. double Slider::proportionOfLengthToValue (double proportion)
  39345. {
  39346. if (skewFactor != 1.0 && proportion > 0.0)
  39347. proportion = exp (log (proportion) / skewFactor);
  39348. return minimum + (maximum - minimum) * proportion;
  39349. }
  39350. double Slider::valueToProportionOfLength (double value)
  39351. {
  39352. const double n = (value - minimum) / (maximum - minimum);
  39353. return skewFactor == 1.0 ? n : pow (n, skewFactor);
  39354. }
  39355. double Slider::snapValue (double attemptedValue, const bool)
  39356. {
  39357. return attemptedValue;
  39358. }
  39359. void Slider::startedDragging()
  39360. {
  39361. }
  39362. void Slider::stoppedDragging()
  39363. {
  39364. }
  39365. void Slider::valueChanged()
  39366. {
  39367. }
  39368. void Slider::enablementChanged()
  39369. {
  39370. repaint();
  39371. }
  39372. void Slider::setPopupMenuEnabled (const bool menuEnabled_)
  39373. {
  39374. menuEnabled = menuEnabled_;
  39375. }
  39376. void Slider::setScrollWheelEnabled (const bool enabled)
  39377. {
  39378. scrollWheelEnabled = enabled;
  39379. }
  39380. void Slider::labelTextChanged (Label* label)
  39381. {
  39382. const double newValue = snapValue (getValueFromText (label->getText()), false);
  39383. if (newValue != (double) currentValue.getValue())
  39384. {
  39385. sendDragStart();
  39386. setValue (newValue, true, true);
  39387. sendDragEnd();
  39388. }
  39389. updateText(); // force a clean-up of the text, needed in case setValue() hasn't done this.
  39390. }
  39391. void Slider::buttonClicked (Button* button)
  39392. {
  39393. if (style == IncDecButtons)
  39394. {
  39395. sendDragStart();
  39396. if (button == incButton)
  39397. setValue (snapValue (getValue() + interval, false), true, true);
  39398. else if (button == decButton)
  39399. setValue (snapValue (getValue() - interval, false), true, true);
  39400. sendDragEnd();
  39401. }
  39402. }
  39403. double Slider::constrainedValue (double value) const
  39404. {
  39405. if (interval > 0)
  39406. value = minimum + interval * std::floor ((value - minimum) / interval + 0.5);
  39407. if (value <= minimum || maximum <= minimum)
  39408. value = minimum;
  39409. else if (value >= maximum)
  39410. value = maximum;
  39411. return value;
  39412. }
  39413. float Slider::getLinearSliderPos (const double value)
  39414. {
  39415. double sliderPosProportional;
  39416. if (maximum > minimum)
  39417. {
  39418. if (value < minimum)
  39419. {
  39420. sliderPosProportional = 0.0;
  39421. }
  39422. else if (value > maximum)
  39423. {
  39424. sliderPosProportional = 1.0;
  39425. }
  39426. else
  39427. {
  39428. sliderPosProportional = valueToProportionOfLength (value);
  39429. jassert (sliderPosProportional >= 0 && sliderPosProportional <= 1.0);
  39430. }
  39431. }
  39432. else
  39433. {
  39434. sliderPosProportional = 0.5;
  39435. }
  39436. if (isVertical() || style == IncDecButtons)
  39437. sliderPosProportional = 1.0 - sliderPosProportional;
  39438. return (float) (sliderRegionStart + sliderPosProportional * sliderRegionSize);
  39439. }
  39440. bool Slider::isHorizontal() const
  39441. {
  39442. return style == LinearHorizontal
  39443. || style == LinearBar
  39444. || style == TwoValueHorizontal
  39445. || style == ThreeValueHorizontal;
  39446. }
  39447. bool Slider::isVertical() const
  39448. {
  39449. return style == LinearVertical
  39450. || style == TwoValueVertical
  39451. || style == ThreeValueVertical;
  39452. }
  39453. bool Slider::incDecDragDirectionIsHorizontal() const
  39454. {
  39455. return incDecButtonMode == incDecButtonsDraggable_Horizontal
  39456. || (incDecButtonMode == incDecButtonsDraggable_AutoDirection && incDecButtonsSideBySide);
  39457. }
  39458. float Slider::getPositionOfValue (const double value)
  39459. {
  39460. if (isHorizontal() || isVertical())
  39461. {
  39462. return getLinearSliderPos (value);
  39463. }
  39464. else
  39465. {
  39466. jassertfalse // not a valid call on a slider that doesn't work linearly!
  39467. return 0.0f;
  39468. }
  39469. }
  39470. void Slider::paint (Graphics& g)
  39471. {
  39472. if (style != IncDecButtons)
  39473. {
  39474. if (style == Rotary || style == RotaryHorizontalDrag || style == RotaryVerticalDrag)
  39475. {
  39476. const float sliderPos = (float) valueToProportionOfLength (lastCurrentValue);
  39477. jassert (sliderPos >= 0 && sliderPos <= 1.0f);
  39478. getLookAndFeel().drawRotarySlider (g,
  39479. sliderRect.getX(),
  39480. sliderRect.getY(),
  39481. sliderRect.getWidth(),
  39482. sliderRect.getHeight(),
  39483. sliderPos,
  39484. rotaryStart, rotaryEnd,
  39485. *this);
  39486. }
  39487. else
  39488. {
  39489. getLookAndFeel().drawLinearSlider (g,
  39490. sliderRect.getX(),
  39491. sliderRect.getY(),
  39492. sliderRect.getWidth(),
  39493. sliderRect.getHeight(),
  39494. getLinearSliderPos (lastCurrentValue),
  39495. getLinearSliderPos (lastValueMin),
  39496. getLinearSliderPos (lastValueMax),
  39497. style,
  39498. *this);
  39499. }
  39500. if (style == LinearBar && valueBox == 0)
  39501. {
  39502. g.setColour (findColour (Slider::textBoxOutlineColourId));
  39503. g.drawRect (0, 0, getWidth(), getHeight(), 1);
  39504. }
  39505. }
  39506. }
  39507. void Slider::resized()
  39508. {
  39509. int minXSpace = 0;
  39510. int minYSpace = 0;
  39511. if (textBoxPos == TextBoxLeft || textBoxPos == TextBoxRight)
  39512. minXSpace = 30;
  39513. else
  39514. minYSpace = 15;
  39515. const int tbw = jmax (0, jmin (textBoxWidth, getWidth() - minXSpace));
  39516. const int tbh = jmax (0, jmin (textBoxHeight, getHeight() - minYSpace));
  39517. if (style == LinearBar)
  39518. {
  39519. if (valueBox != 0)
  39520. valueBox->setBounds (0, 0, getWidth(), getHeight());
  39521. }
  39522. else
  39523. {
  39524. if (textBoxPos == NoTextBox)
  39525. {
  39526. sliderRect.setBounds (0, 0, getWidth(), getHeight());
  39527. }
  39528. else if (textBoxPos == TextBoxLeft)
  39529. {
  39530. valueBox->setBounds (0, (getHeight() - tbh) / 2, tbw, tbh);
  39531. sliderRect.setBounds (tbw, 0, getWidth() - tbw, getHeight());
  39532. }
  39533. else if (textBoxPos == TextBoxRight)
  39534. {
  39535. valueBox->setBounds (getWidth() - tbw, (getHeight() - tbh) / 2, tbw, tbh);
  39536. sliderRect.setBounds (0, 0, getWidth() - tbw, getHeight());
  39537. }
  39538. else if (textBoxPos == TextBoxAbove)
  39539. {
  39540. valueBox->setBounds ((getWidth() - tbw) / 2, 0, tbw, tbh);
  39541. sliderRect.setBounds (0, tbh, getWidth(), getHeight() - tbh);
  39542. }
  39543. else if (textBoxPos == TextBoxBelow)
  39544. {
  39545. valueBox->setBounds ((getWidth() - tbw) / 2, getHeight() - tbh, tbw, tbh);
  39546. sliderRect.setBounds (0, 0, getWidth(), getHeight() - tbh);
  39547. }
  39548. }
  39549. const int indent = getLookAndFeel().getSliderThumbRadius (*this);
  39550. if (style == LinearBar)
  39551. {
  39552. const int barIndent = 1;
  39553. sliderRegionStart = barIndent;
  39554. sliderRegionSize = getWidth() - barIndent * 2;
  39555. sliderRect.setBounds (sliderRegionStart, barIndent,
  39556. sliderRegionSize, getHeight() - barIndent * 2);
  39557. }
  39558. else if (isHorizontal())
  39559. {
  39560. sliderRegionStart = sliderRect.getX() + indent;
  39561. sliderRegionSize = jmax (1, sliderRect.getWidth() - indent * 2);
  39562. sliderRect.setBounds (sliderRegionStart, sliderRect.getY(),
  39563. sliderRegionSize, sliderRect.getHeight());
  39564. }
  39565. else if (isVertical())
  39566. {
  39567. sliderRegionStart = sliderRect.getY() + indent;
  39568. sliderRegionSize = jmax (1, sliderRect.getHeight() - indent * 2);
  39569. sliderRect.setBounds (sliderRect.getX(), sliderRegionStart,
  39570. sliderRect.getWidth(), sliderRegionSize);
  39571. }
  39572. else
  39573. {
  39574. sliderRegionStart = 0;
  39575. sliderRegionSize = 100;
  39576. }
  39577. if (style == IncDecButtons)
  39578. {
  39579. Rectangle<int> buttonRect (sliderRect);
  39580. if (textBoxPos == TextBoxLeft || textBoxPos == TextBoxRight)
  39581. buttonRect.expand (-2, 0);
  39582. else
  39583. buttonRect.expand (0, -2);
  39584. incDecButtonsSideBySide = buttonRect.getWidth() > buttonRect.getHeight();
  39585. if (incDecButtonsSideBySide)
  39586. {
  39587. decButton->setBounds (buttonRect.getX(),
  39588. buttonRect.getY(),
  39589. buttonRect.getWidth() / 2,
  39590. buttonRect.getHeight());
  39591. decButton->setConnectedEdges (Button::ConnectedOnRight);
  39592. incButton->setBounds (buttonRect.getCentreX(),
  39593. buttonRect.getY(),
  39594. buttonRect.getWidth() / 2,
  39595. buttonRect.getHeight());
  39596. incButton->setConnectedEdges (Button::ConnectedOnLeft);
  39597. }
  39598. else
  39599. {
  39600. incButton->setBounds (buttonRect.getX(),
  39601. buttonRect.getY(),
  39602. buttonRect.getWidth(),
  39603. buttonRect.getHeight() / 2);
  39604. incButton->setConnectedEdges (Button::ConnectedOnBottom);
  39605. decButton->setBounds (buttonRect.getX(),
  39606. buttonRect.getCentreY(),
  39607. buttonRect.getWidth(),
  39608. buttonRect.getHeight() / 2);
  39609. decButton->setConnectedEdges (Button::ConnectedOnTop);
  39610. }
  39611. }
  39612. }
  39613. void Slider::focusOfChildComponentChanged (FocusChangeType)
  39614. {
  39615. repaint();
  39616. }
  39617. void Slider::mouseDown (const MouseEvent& e)
  39618. {
  39619. mouseWasHidden = false;
  39620. incDecDragged = false;
  39621. mouseXWhenLastDragged = e.x;
  39622. mouseYWhenLastDragged = e.y;
  39623. mouseDragStartX = e.getMouseDownX();
  39624. mouseDragStartY = e.getMouseDownY();
  39625. if (isEnabled())
  39626. {
  39627. if (e.mods.isPopupMenu() && menuEnabled)
  39628. {
  39629. menuShown = true;
  39630. PopupMenu m;
  39631. m.setLookAndFeel (&getLookAndFeel());
  39632. m.addItem (1, TRANS ("velocity-sensitive mode"), true, isVelocityBased);
  39633. m.addSeparator();
  39634. if (style == Rotary || style == RotaryHorizontalDrag || style == RotaryVerticalDrag)
  39635. {
  39636. PopupMenu rotaryMenu;
  39637. rotaryMenu.addItem (2, TRANS ("use circular dragging"), true, style == Rotary);
  39638. rotaryMenu.addItem (3, TRANS ("use left-right dragging"), true, style == RotaryHorizontalDrag);
  39639. rotaryMenu.addItem (4, TRANS ("use up-down dragging"), true, style == RotaryVerticalDrag);
  39640. m.addSubMenu (TRANS ("rotary mode"), rotaryMenu);
  39641. }
  39642. const int r = m.show();
  39643. if (r == 1)
  39644. {
  39645. setVelocityBasedMode (! isVelocityBased);
  39646. }
  39647. else if (r == 2)
  39648. {
  39649. setSliderStyle (Rotary);
  39650. }
  39651. else if (r == 3)
  39652. {
  39653. setSliderStyle (RotaryHorizontalDrag);
  39654. }
  39655. else if (r == 4)
  39656. {
  39657. setSliderStyle (RotaryVerticalDrag);
  39658. }
  39659. }
  39660. else if (maximum > minimum)
  39661. {
  39662. menuShown = false;
  39663. if (valueBox != 0)
  39664. valueBox->hideEditor (true);
  39665. sliderBeingDragged = 0;
  39666. if (style == TwoValueHorizontal
  39667. || style == TwoValueVertical
  39668. || style == ThreeValueHorizontal
  39669. || style == ThreeValueVertical)
  39670. {
  39671. const float mousePos = (float) (isVertical() ? e.y : e.x);
  39672. const float normalPosDistance = std::abs (getLinearSliderPos (currentValue.getValue()) - mousePos);
  39673. const float minPosDistance = std::abs (getLinearSliderPos (valueMin.getValue()) - 0.1f - mousePos);
  39674. const float maxPosDistance = std::abs (getLinearSliderPos (valueMax.getValue()) + 0.1f - mousePos);
  39675. if (style == TwoValueHorizontal || style == TwoValueVertical)
  39676. {
  39677. if (maxPosDistance <= minPosDistance)
  39678. sliderBeingDragged = 2;
  39679. else
  39680. sliderBeingDragged = 1;
  39681. }
  39682. else if (style == ThreeValueHorizontal || style == ThreeValueVertical)
  39683. {
  39684. if (normalPosDistance >= minPosDistance && maxPosDistance >= minPosDistance)
  39685. sliderBeingDragged = 1;
  39686. else if (normalPosDistance >= maxPosDistance)
  39687. sliderBeingDragged = 2;
  39688. }
  39689. }
  39690. minMaxDiff = (double) valueMax.getValue() - (double) valueMin.getValue();
  39691. lastAngle = rotaryStart + (rotaryEnd - rotaryStart)
  39692. * valueToProportionOfLength (currentValue.getValue());
  39693. valueWhenLastDragged = ((sliderBeingDragged == 2) ? valueMax
  39694. : ((sliderBeingDragged == 1) ? valueMin
  39695. : currentValue)).getValue();
  39696. valueOnMouseDown = valueWhenLastDragged;
  39697. if (popupDisplayEnabled)
  39698. {
  39699. SliderPopupDisplayComponent* const popup = new SliderPopupDisplayComponent (this);
  39700. popupDisplay = popup;
  39701. if (parentForPopupDisplay != 0)
  39702. {
  39703. parentForPopupDisplay->addChildComponent (popup);
  39704. }
  39705. else
  39706. {
  39707. popup->addToDesktop (0);
  39708. }
  39709. popup->setVisible (true);
  39710. }
  39711. sendDragStart();
  39712. mouseDrag (e);
  39713. }
  39714. }
  39715. }
  39716. void Slider::mouseUp (const MouseEvent&)
  39717. {
  39718. if (isEnabled()
  39719. && (! menuShown)
  39720. && (maximum > minimum)
  39721. && (style != IncDecButtons || incDecDragged))
  39722. {
  39723. restoreMouseIfHidden();
  39724. if (sendChangeOnlyOnRelease && valueOnMouseDown != (double) currentValue.getValue())
  39725. triggerChangeMessage (false);
  39726. sendDragEnd();
  39727. popupDisplay = 0;
  39728. if (style == IncDecButtons)
  39729. {
  39730. incButton->setState (Button::buttonNormal);
  39731. decButton->setState (Button::buttonNormal);
  39732. }
  39733. }
  39734. }
  39735. void Slider::restoreMouseIfHidden()
  39736. {
  39737. if (mouseWasHidden)
  39738. {
  39739. mouseWasHidden = false;
  39740. for (int i = Desktop::getInstance().getNumMouseSources(); --i >= 0;)
  39741. Desktop::getInstance().getMouseSource(i)->enableUnboundedMouseMovement (false);
  39742. const double pos = (sliderBeingDragged == 2) ? getMaxValue()
  39743. : ((sliderBeingDragged == 1) ? getMinValue()
  39744. : (double) currentValue.getValue());
  39745. Point<int> mousePos;
  39746. if (style == RotaryHorizontalDrag || style == RotaryVerticalDrag)
  39747. {
  39748. mousePos = Desktop::getLastMouseDownPosition();
  39749. if (style == RotaryHorizontalDrag)
  39750. {
  39751. const double posDiff = valueToProportionOfLength (pos) - valueToProportionOfLength (valueOnMouseDown);
  39752. mousePos += Point<int> (roundToInt (pixelsForFullDragExtent * posDiff), 0);
  39753. }
  39754. else
  39755. {
  39756. const double posDiff = valueToProportionOfLength (valueOnMouseDown) - valueToProportionOfLength (pos);
  39757. mousePos += Point<int> (0, roundToInt (pixelsForFullDragExtent * posDiff));
  39758. }
  39759. }
  39760. else
  39761. {
  39762. const int pixelPos = (int) getLinearSliderPos (pos);
  39763. mousePos = relativePositionToGlobal (Point<int> (isHorizontal() ? pixelPos : (getWidth() / 2),
  39764. isVertical() ? pixelPos : (getHeight() / 2)));
  39765. }
  39766. Desktop::setMousePosition (mousePos);
  39767. }
  39768. }
  39769. void Slider::modifierKeysChanged (const ModifierKeys& modifiers)
  39770. {
  39771. if (isEnabled()
  39772. && style != IncDecButtons
  39773. && style != Rotary
  39774. && isVelocityBased == modifiers.isAnyModifierKeyDown())
  39775. {
  39776. restoreMouseIfHidden();
  39777. }
  39778. }
  39779. static double smallestAngleBetween (double a1, double a2)
  39780. {
  39781. return jmin (std::abs (a1 - a2),
  39782. std::abs (a1 + double_Pi * 2.0 - a2),
  39783. std::abs (a2 + double_Pi * 2.0 - a1));
  39784. }
  39785. void Slider::mouseDrag (const MouseEvent& e)
  39786. {
  39787. if (isEnabled()
  39788. && (! menuShown)
  39789. && (maximum > minimum))
  39790. {
  39791. if (style == Rotary)
  39792. {
  39793. int dx = e.x - sliderRect.getCentreX();
  39794. int dy = e.y - sliderRect.getCentreY();
  39795. if (dx * dx + dy * dy > 25)
  39796. {
  39797. double angle = std::atan2 ((double) dx, (double) -dy);
  39798. while (angle < 0.0)
  39799. angle += double_Pi * 2.0;
  39800. if (rotaryStop && ! e.mouseWasClicked())
  39801. {
  39802. if (std::abs (angle - lastAngle) > double_Pi)
  39803. {
  39804. if (angle >= lastAngle)
  39805. angle -= double_Pi * 2.0;
  39806. else
  39807. angle += double_Pi * 2.0;
  39808. }
  39809. if (angle >= lastAngle)
  39810. angle = jmin (angle, (double) jmax (rotaryStart, rotaryEnd));
  39811. else
  39812. angle = jmax (angle, (double) jmin (rotaryStart, rotaryEnd));
  39813. }
  39814. else
  39815. {
  39816. while (angle < rotaryStart)
  39817. angle += double_Pi * 2.0;
  39818. if (angle > rotaryEnd)
  39819. {
  39820. if (smallestAngleBetween (angle, rotaryStart) <= smallestAngleBetween (angle, rotaryEnd))
  39821. angle = rotaryStart;
  39822. else
  39823. angle = rotaryEnd;
  39824. }
  39825. }
  39826. const double proportion = (angle - rotaryStart) / (rotaryEnd - rotaryStart);
  39827. valueWhenLastDragged = proportionOfLengthToValue (jlimit (0.0, 1.0, proportion));
  39828. lastAngle = angle;
  39829. }
  39830. }
  39831. else
  39832. {
  39833. if (style == LinearBar && e.mouseWasClicked()
  39834. && valueBox != 0 && valueBox->isEditable())
  39835. return;
  39836. if (style == IncDecButtons && ! incDecDragged)
  39837. {
  39838. if (e.getDistanceFromDragStart() < 10 || e.mouseWasClicked())
  39839. return;
  39840. incDecDragged = true;
  39841. mouseDragStartX = e.x;
  39842. mouseDragStartY = e.y;
  39843. }
  39844. if ((isVelocityBased == (userKeyOverridesVelocity ? e.mods.testFlags (ModifierKeys::ctrlModifier | ModifierKeys::commandModifier | ModifierKeys::altModifier)
  39845. : false))
  39846. || ((maximum - minimum) / sliderRegionSize < interval))
  39847. {
  39848. const int mousePos = (isHorizontal() || style == RotaryHorizontalDrag) ? e.x : e.y;
  39849. double scaledMousePos = (mousePos - sliderRegionStart) / (double) sliderRegionSize;
  39850. if (style == RotaryHorizontalDrag
  39851. || style == RotaryVerticalDrag
  39852. || style == IncDecButtons
  39853. || ((style == LinearHorizontal || style == LinearVertical || style == LinearBar)
  39854. && ! snapsToMousePos))
  39855. {
  39856. const int mouseDiff = (style == RotaryHorizontalDrag
  39857. || style == LinearHorizontal
  39858. || style == LinearBar
  39859. || (style == IncDecButtons && incDecDragDirectionIsHorizontal()))
  39860. ? e.x - mouseDragStartX
  39861. : mouseDragStartY - e.y;
  39862. double newPos = valueToProportionOfLength (valueOnMouseDown)
  39863. + mouseDiff * (1.0 / pixelsForFullDragExtent);
  39864. valueWhenLastDragged = proportionOfLengthToValue (jlimit (0.0, 1.0, newPos));
  39865. if (style == IncDecButtons)
  39866. {
  39867. incButton->setState (mouseDiff < 0 ? Button::buttonNormal : Button::buttonDown);
  39868. decButton->setState (mouseDiff > 0 ? Button::buttonNormal : Button::buttonDown);
  39869. }
  39870. }
  39871. else
  39872. {
  39873. if (isVertical())
  39874. scaledMousePos = 1.0 - scaledMousePos;
  39875. valueWhenLastDragged = proportionOfLengthToValue (jlimit (0.0, 1.0, scaledMousePos));
  39876. }
  39877. }
  39878. else
  39879. {
  39880. const int mouseDiff = (isHorizontal() || style == RotaryHorizontalDrag
  39881. || (style == IncDecButtons && incDecDragDirectionIsHorizontal()))
  39882. ? e.x - mouseXWhenLastDragged
  39883. : e.y - mouseYWhenLastDragged;
  39884. const double maxSpeed = jmax (200, sliderRegionSize);
  39885. double speed = jlimit (0.0, maxSpeed, (double) abs (mouseDiff));
  39886. if (speed != 0)
  39887. {
  39888. speed = 0.2 * velocityModeSensitivity
  39889. * (1.0 + std::sin (double_Pi * (1.5 + jmin (0.5, velocityModeOffset
  39890. + jmax (0.0, (double) (speed - velocityModeThreshold))
  39891. / maxSpeed))));
  39892. if (mouseDiff < 0)
  39893. speed = -speed;
  39894. if (isVertical() || style == RotaryVerticalDrag
  39895. || (style == IncDecButtons && ! incDecDragDirectionIsHorizontal()))
  39896. speed = -speed;
  39897. const double currentPos = valueToProportionOfLength (valueWhenLastDragged);
  39898. valueWhenLastDragged = proportionOfLengthToValue (jlimit (0.0, 1.0, currentPos + speed));
  39899. e.source.enableUnboundedMouseMovement (true, false);
  39900. mouseWasHidden = true;
  39901. }
  39902. }
  39903. }
  39904. valueWhenLastDragged = jlimit (minimum, maximum, valueWhenLastDragged);
  39905. if (sliderBeingDragged == 0)
  39906. {
  39907. setValue (snapValue (valueWhenLastDragged, true),
  39908. ! sendChangeOnlyOnRelease, true);
  39909. }
  39910. else if (sliderBeingDragged == 1)
  39911. {
  39912. setMinValue (snapValue (valueWhenLastDragged, true),
  39913. ! sendChangeOnlyOnRelease, false, true);
  39914. if (e.mods.isShiftDown())
  39915. setMaxValue (getMinValue() + minMaxDiff, false, false, true);
  39916. else
  39917. minMaxDiff = (double) valueMax.getValue() - (double) valueMin.getValue();
  39918. }
  39919. else
  39920. {
  39921. jassert (sliderBeingDragged == 2);
  39922. setMaxValue (snapValue (valueWhenLastDragged, true),
  39923. ! sendChangeOnlyOnRelease, false, true);
  39924. if (e.mods.isShiftDown())
  39925. setMinValue (getMaxValue() - minMaxDiff, false, false, true);
  39926. else
  39927. minMaxDiff = (double) valueMax.getValue() - (double) valueMin.getValue();
  39928. }
  39929. mouseXWhenLastDragged = e.x;
  39930. mouseYWhenLastDragged = e.y;
  39931. }
  39932. }
  39933. void Slider::mouseDoubleClick (const MouseEvent&)
  39934. {
  39935. if (doubleClickToValue
  39936. && isEnabled()
  39937. && style != IncDecButtons
  39938. && minimum <= doubleClickReturnValue
  39939. && maximum >= doubleClickReturnValue)
  39940. {
  39941. sendDragStart();
  39942. setValue (doubleClickReturnValue, true, true);
  39943. sendDragEnd();
  39944. }
  39945. }
  39946. void Slider::mouseWheelMove (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY)
  39947. {
  39948. if (scrollWheelEnabled && isEnabled()
  39949. && style != TwoValueHorizontal
  39950. && style != TwoValueVertical)
  39951. {
  39952. if (maximum > minimum && ! e.mods.isAnyMouseButtonDown())
  39953. {
  39954. if (valueBox != 0)
  39955. valueBox->hideEditor (false);
  39956. const double value = (double) currentValue.getValue();
  39957. const double proportionDelta = (wheelIncrementX != 0 ? -wheelIncrementX : wheelIncrementY) * 0.15f;
  39958. const double currentPos = valueToProportionOfLength (value);
  39959. const double newValue = proportionOfLengthToValue (jlimit (0.0, 1.0, currentPos + proportionDelta));
  39960. double delta = (newValue != value)
  39961. ? jmax (std::abs (newValue - value), interval) : 0;
  39962. if (value > newValue)
  39963. delta = -delta;
  39964. sendDragStart();
  39965. setValue (snapValue (value + delta, false), true, true);
  39966. sendDragEnd();
  39967. }
  39968. }
  39969. else
  39970. {
  39971. Component::mouseWheelMove (e, wheelIncrementX, wheelIncrementY);
  39972. }
  39973. }
  39974. void SliderListener::sliderDragStarted (Slider*)
  39975. {
  39976. }
  39977. void SliderListener::sliderDragEnded (Slider*)
  39978. {
  39979. }
  39980. END_JUCE_NAMESPACE
  39981. /*** End of inlined file: juce_Slider.cpp ***/
  39982. /*** Start of inlined file: juce_TableHeaderComponent.cpp ***/
  39983. BEGIN_JUCE_NAMESPACE
  39984. class DragOverlayComp : public Component
  39985. {
  39986. public:
  39987. DragOverlayComp (Image* const image_)
  39988. : image (image_)
  39989. {
  39990. image->multiplyAllAlphas (0.8f);
  39991. setAlwaysOnTop (true);
  39992. }
  39993. ~DragOverlayComp()
  39994. {
  39995. }
  39996. void paint (Graphics& g)
  39997. {
  39998. g.drawImageAt (image, 0, 0);
  39999. }
  40000. private:
  40001. ScopedPointer <Image> image;
  40002. DragOverlayComp (const DragOverlayComp&);
  40003. DragOverlayComp& operator= (const DragOverlayComp&);
  40004. };
  40005. TableHeaderComponent::TableHeaderComponent()
  40006. : columnsChanged (false),
  40007. columnsResized (false),
  40008. sortChanged (false),
  40009. menuActive (true),
  40010. stretchToFit (false),
  40011. columnIdBeingResized (0),
  40012. columnIdBeingDragged (0),
  40013. columnIdUnderMouse (0),
  40014. lastDeliberateWidth (0)
  40015. {
  40016. }
  40017. TableHeaderComponent::~TableHeaderComponent()
  40018. {
  40019. dragOverlayComp = 0;
  40020. }
  40021. void TableHeaderComponent::setPopupMenuActive (const bool hasMenu)
  40022. {
  40023. menuActive = hasMenu;
  40024. }
  40025. bool TableHeaderComponent::isPopupMenuActive() const { return menuActive; }
  40026. int TableHeaderComponent::getNumColumns (const bool onlyCountVisibleColumns) const
  40027. {
  40028. if (onlyCountVisibleColumns)
  40029. {
  40030. int num = 0;
  40031. for (int i = columns.size(); --i >= 0;)
  40032. if (columns.getUnchecked(i)->isVisible())
  40033. ++num;
  40034. return num;
  40035. }
  40036. else
  40037. {
  40038. return columns.size();
  40039. }
  40040. }
  40041. const String TableHeaderComponent::getColumnName (const int columnId) const
  40042. {
  40043. const ColumnInfo* const ci = getInfoForId (columnId);
  40044. return ci != 0 ? ci->name : String::empty;
  40045. }
  40046. void TableHeaderComponent::setColumnName (const int columnId, const String& newName)
  40047. {
  40048. ColumnInfo* const ci = getInfoForId (columnId);
  40049. if (ci != 0 && ci->name != newName)
  40050. {
  40051. ci->name = newName;
  40052. sendColumnsChanged();
  40053. }
  40054. }
  40055. void TableHeaderComponent::addColumn (const String& columnName,
  40056. const int columnId,
  40057. const int width,
  40058. const int minimumWidth,
  40059. const int maximumWidth,
  40060. const int propertyFlags,
  40061. const int insertIndex)
  40062. {
  40063. // can't have a duplicate or null ID!
  40064. jassert (columnId != 0 && getIndexOfColumnId (columnId, false) < 0);
  40065. jassert (width > 0);
  40066. ColumnInfo* const ci = new ColumnInfo();
  40067. ci->name = columnName;
  40068. ci->id = columnId;
  40069. ci->width = width;
  40070. ci->lastDeliberateWidth = width;
  40071. ci->minimumWidth = minimumWidth;
  40072. ci->maximumWidth = maximumWidth;
  40073. if (ci->maximumWidth < 0)
  40074. ci->maximumWidth = std::numeric_limits<int>::max();
  40075. jassert (ci->maximumWidth >= ci->minimumWidth);
  40076. ci->propertyFlags = propertyFlags;
  40077. columns.insert (insertIndex, ci);
  40078. sendColumnsChanged();
  40079. }
  40080. void TableHeaderComponent::removeColumn (const int columnIdToRemove)
  40081. {
  40082. const int index = getIndexOfColumnId (columnIdToRemove, false);
  40083. if (index >= 0)
  40084. {
  40085. columns.remove (index);
  40086. sortChanged = true;
  40087. sendColumnsChanged();
  40088. }
  40089. }
  40090. void TableHeaderComponent::removeAllColumns()
  40091. {
  40092. if (columns.size() > 0)
  40093. {
  40094. columns.clear();
  40095. sendColumnsChanged();
  40096. }
  40097. }
  40098. void TableHeaderComponent::moveColumn (const int columnId, int newIndex)
  40099. {
  40100. const int currentIndex = getIndexOfColumnId (columnId, false);
  40101. newIndex = visibleIndexToTotalIndex (newIndex);
  40102. if (columns [currentIndex] != 0 && currentIndex != newIndex)
  40103. {
  40104. columns.move (currentIndex, newIndex);
  40105. sendColumnsChanged();
  40106. }
  40107. }
  40108. int TableHeaderComponent::getColumnWidth (const int columnId) const
  40109. {
  40110. const ColumnInfo* const ci = getInfoForId (columnId);
  40111. return ci != 0 ? ci->width : 0;
  40112. }
  40113. void TableHeaderComponent::setColumnWidth (const int columnId, const int newWidth)
  40114. {
  40115. ColumnInfo* const ci = getInfoForId (columnId);
  40116. if (ci != 0 && ci->width != newWidth)
  40117. {
  40118. const int numColumns = getNumColumns (true);
  40119. ci->lastDeliberateWidth = ci->width
  40120. = jlimit (ci->minimumWidth, ci->maximumWidth, newWidth);
  40121. if (stretchToFit)
  40122. {
  40123. const int index = getIndexOfColumnId (columnId, true) + 1;
  40124. if (((unsigned int) index) < (unsigned int) numColumns)
  40125. {
  40126. const int x = getColumnPosition (index).getX();
  40127. if (lastDeliberateWidth == 0)
  40128. lastDeliberateWidth = getTotalWidth();
  40129. resizeColumnsToFit (visibleIndexToTotalIndex (index), lastDeliberateWidth - x);
  40130. }
  40131. }
  40132. repaint();
  40133. columnsResized = true;
  40134. triggerAsyncUpdate();
  40135. }
  40136. }
  40137. int TableHeaderComponent::getIndexOfColumnId (const int columnId, const bool onlyCountVisibleColumns) const
  40138. {
  40139. int n = 0;
  40140. for (int i = 0; i < columns.size(); ++i)
  40141. {
  40142. if ((! onlyCountVisibleColumns) || columns.getUnchecked(i)->isVisible())
  40143. {
  40144. if (columns.getUnchecked(i)->id == columnId)
  40145. return n;
  40146. ++n;
  40147. }
  40148. }
  40149. return -1;
  40150. }
  40151. int TableHeaderComponent::getColumnIdOfIndex (int index, const bool onlyCountVisibleColumns) const
  40152. {
  40153. if (onlyCountVisibleColumns)
  40154. index = visibleIndexToTotalIndex (index);
  40155. const ColumnInfo* const ci = columns [index];
  40156. return (ci != 0) ? ci->id : 0;
  40157. }
  40158. const Rectangle<int> TableHeaderComponent::getColumnPosition (const int index) const
  40159. {
  40160. int x = 0, width = 0, n = 0;
  40161. for (int i = 0; i < columns.size(); ++i)
  40162. {
  40163. x += width;
  40164. if (columns.getUnchecked(i)->isVisible())
  40165. {
  40166. width = columns.getUnchecked(i)->width;
  40167. if (n++ == index)
  40168. break;
  40169. }
  40170. else
  40171. {
  40172. width = 0;
  40173. }
  40174. }
  40175. return Rectangle<int> (x, 0, width, getHeight());
  40176. }
  40177. int TableHeaderComponent::getColumnIdAtX (const int xToFind) const
  40178. {
  40179. if (xToFind >= 0)
  40180. {
  40181. int x = 0;
  40182. for (int i = 0; i < columns.size(); ++i)
  40183. {
  40184. const ColumnInfo* const ci = columns.getUnchecked(i);
  40185. if (ci->isVisible())
  40186. {
  40187. x += ci->width;
  40188. if (xToFind < x)
  40189. return ci->id;
  40190. }
  40191. }
  40192. }
  40193. return 0;
  40194. }
  40195. int TableHeaderComponent::getTotalWidth() const
  40196. {
  40197. int w = 0;
  40198. for (int i = columns.size(); --i >= 0;)
  40199. if (columns.getUnchecked(i)->isVisible())
  40200. w += columns.getUnchecked(i)->width;
  40201. return w;
  40202. }
  40203. void TableHeaderComponent::setStretchToFitActive (const bool shouldStretchToFit)
  40204. {
  40205. stretchToFit = shouldStretchToFit;
  40206. lastDeliberateWidth = getTotalWidth();
  40207. resized();
  40208. }
  40209. bool TableHeaderComponent::isStretchToFitActive() const
  40210. {
  40211. return stretchToFit;
  40212. }
  40213. void TableHeaderComponent::resizeAllColumnsToFit (int targetTotalWidth)
  40214. {
  40215. if (stretchToFit && getWidth() > 0
  40216. && columnIdBeingResized == 0 && columnIdBeingDragged == 0)
  40217. {
  40218. lastDeliberateWidth = targetTotalWidth;
  40219. resizeColumnsToFit (0, targetTotalWidth);
  40220. }
  40221. }
  40222. void TableHeaderComponent::resizeColumnsToFit (int firstColumnIndex, int targetTotalWidth)
  40223. {
  40224. targetTotalWidth = jmax (targetTotalWidth, 0);
  40225. StretchableObjectResizer sor;
  40226. int i;
  40227. for (i = firstColumnIndex; i < columns.size(); ++i)
  40228. {
  40229. ColumnInfo* const ci = columns.getUnchecked(i);
  40230. if (ci->isVisible())
  40231. sor.addItem (ci->lastDeliberateWidth, ci->minimumWidth, ci->maximumWidth);
  40232. }
  40233. sor.resizeToFit (targetTotalWidth);
  40234. int visIndex = 0;
  40235. for (i = firstColumnIndex; i < columns.size(); ++i)
  40236. {
  40237. ColumnInfo* const ci = columns.getUnchecked(i);
  40238. if (ci->isVisible())
  40239. {
  40240. const int newWidth = jlimit (ci->minimumWidth, ci->maximumWidth,
  40241. (int) std::floor (sor.getItemSize (visIndex++)));
  40242. if (newWidth != ci->width)
  40243. {
  40244. ci->width = newWidth;
  40245. repaint();
  40246. columnsResized = true;
  40247. triggerAsyncUpdate();
  40248. }
  40249. }
  40250. }
  40251. }
  40252. void TableHeaderComponent::setColumnVisible (const int columnId, const bool shouldBeVisible)
  40253. {
  40254. ColumnInfo* const ci = getInfoForId (columnId);
  40255. if (ci != 0 && shouldBeVisible != ci->isVisible())
  40256. {
  40257. if (shouldBeVisible)
  40258. ci->propertyFlags |= visible;
  40259. else
  40260. ci->propertyFlags &= ~visible;
  40261. sendColumnsChanged();
  40262. resized();
  40263. }
  40264. }
  40265. bool TableHeaderComponent::isColumnVisible (const int columnId) const
  40266. {
  40267. const ColumnInfo* const ci = getInfoForId (columnId);
  40268. return ci != 0 && ci->isVisible();
  40269. }
  40270. void TableHeaderComponent::setSortColumnId (const int columnId, const bool sortForwards)
  40271. {
  40272. if (getSortColumnId() != columnId || isSortedForwards() != sortForwards)
  40273. {
  40274. for (int i = columns.size(); --i >= 0;)
  40275. columns.getUnchecked(i)->propertyFlags &= ~(sortedForwards | sortedBackwards);
  40276. ColumnInfo* const ci = getInfoForId (columnId);
  40277. if (ci != 0)
  40278. ci->propertyFlags |= (sortForwards ? sortedForwards : sortedBackwards);
  40279. reSortTable();
  40280. }
  40281. }
  40282. int TableHeaderComponent::getSortColumnId() const
  40283. {
  40284. for (int i = columns.size(); --i >= 0;)
  40285. if ((columns.getUnchecked(i)->propertyFlags & (sortedForwards | sortedBackwards)) != 0)
  40286. return columns.getUnchecked(i)->id;
  40287. return 0;
  40288. }
  40289. bool TableHeaderComponent::isSortedForwards() const
  40290. {
  40291. for (int i = columns.size(); --i >= 0;)
  40292. if ((columns.getUnchecked(i)->propertyFlags & (sortedForwards | sortedBackwards)) != 0)
  40293. return (columns.getUnchecked(i)->propertyFlags & sortedForwards) != 0;
  40294. return true;
  40295. }
  40296. void TableHeaderComponent::reSortTable()
  40297. {
  40298. sortChanged = true;
  40299. repaint();
  40300. triggerAsyncUpdate();
  40301. }
  40302. const String TableHeaderComponent::toString() const
  40303. {
  40304. String s;
  40305. XmlElement doc ("TABLELAYOUT");
  40306. doc.setAttribute ("sortedCol", getSortColumnId());
  40307. doc.setAttribute ("sortForwards", isSortedForwards());
  40308. for (int i = 0; i < columns.size(); ++i)
  40309. {
  40310. const ColumnInfo* const ci = columns.getUnchecked (i);
  40311. XmlElement* const e = doc.createNewChildElement ("COLUMN");
  40312. e->setAttribute ("id", ci->id);
  40313. e->setAttribute ("visible", ci->isVisible());
  40314. e->setAttribute ("width", ci->width);
  40315. }
  40316. return doc.createDocument (String::empty, true, false);
  40317. }
  40318. void TableHeaderComponent::restoreFromString (const String& storedVersion)
  40319. {
  40320. XmlDocument doc (storedVersion);
  40321. ScopedPointer <XmlElement> storedXml (doc.getDocumentElement());
  40322. int index = 0;
  40323. if (storedXml != 0 && storedXml->hasTagName ("TABLELAYOUT"))
  40324. {
  40325. forEachXmlChildElement (*storedXml, col)
  40326. {
  40327. const int tabId = col->getIntAttribute ("id");
  40328. ColumnInfo* const ci = getInfoForId (tabId);
  40329. if (ci != 0)
  40330. {
  40331. columns.move (columns.indexOf (ci), index);
  40332. ci->width = col->getIntAttribute ("width");
  40333. setColumnVisible (tabId, col->getBoolAttribute ("visible"));
  40334. }
  40335. ++index;
  40336. }
  40337. columnsResized = true;
  40338. sendColumnsChanged();
  40339. setSortColumnId (storedXml->getIntAttribute ("sortedCol"),
  40340. storedXml->getBoolAttribute ("sortForwards", true));
  40341. }
  40342. }
  40343. void TableHeaderComponent::addListener (TableHeaderListener* const newListener)
  40344. {
  40345. listeners.addIfNotAlreadyThere (newListener);
  40346. }
  40347. void TableHeaderComponent::removeListener (TableHeaderListener* const listenerToRemove)
  40348. {
  40349. listeners.removeValue (listenerToRemove);
  40350. }
  40351. void TableHeaderComponent::columnClicked (int columnId, const ModifierKeys& mods)
  40352. {
  40353. const ColumnInfo* const ci = getInfoForId (columnId);
  40354. if (ci != 0 && (ci->propertyFlags & sortable) != 0 && ! mods.isPopupMenu())
  40355. setSortColumnId (columnId, (ci->propertyFlags & sortedForwards) == 0);
  40356. }
  40357. void TableHeaderComponent::addMenuItems (PopupMenu& menu, const int /*columnIdClicked*/)
  40358. {
  40359. for (int i = 0; i < columns.size(); ++i)
  40360. {
  40361. const ColumnInfo* const ci = columns.getUnchecked(i);
  40362. if ((ci->propertyFlags & appearsOnColumnMenu) != 0)
  40363. menu.addItem (ci->id, ci->name,
  40364. (ci->propertyFlags & (sortedForwards | sortedBackwards)) == 0,
  40365. isColumnVisible (ci->id));
  40366. }
  40367. }
  40368. void TableHeaderComponent::reactToMenuItem (const int menuReturnId, const int /*columnIdClicked*/)
  40369. {
  40370. if (getIndexOfColumnId (menuReturnId, false) >= 0)
  40371. setColumnVisible (menuReturnId, ! isColumnVisible (menuReturnId));
  40372. }
  40373. void TableHeaderComponent::paint (Graphics& g)
  40374. {
  40375. LookAndFeel& lf = getLookAndFeel();
  40376. lf.drawTableHeaderBackground (g, *this);
  40377. const Rectangle<int> clip (g.getClipBounds());
  40378. int x = 0;
  40379. for (int i = 0; i < columns.size(); ++i)
  40380. {
  40381. const ColumnInfo* const ci = columns.getUnchecked(i);
  40382. if (ci->isVisible())
  40383. {
  40384. if (x + ci->width > clip.getX()
  40385. && (ci->id != columnIdBeingDragged
  40386. || dragOverlayComp == 0
  40387. || ! dragOverlayComp->isVisible()))
  40388. {
  40389. g.saveState();
  40390. g.setOrigin (x, 0);
  40391. g.reduceClipRegion (0, 0, ci->width, getHeight());
  40392. lf.drawTableHeaderColumn (g, ci->name, ci->id, ci->width, getHeight(),
  40393. ci->id == columnIdUnderMouse,
  40394. ci->id == columnIdUnderMouse && isMouseButtonDown(),
  40395. ci->propertyFlags);
  40396. g.restoreState();
  40397. }
  40398. x += ci->width;
  40399. if (x >= clip.getRight())
  40400. break;
  40401. }
  40402. }
  40403. }
  40404. void TableHeaderComponent::resized()
  40405. {
  40406. }
  40407. void TableHeaderComponent::mouseMove (const MouseEvent& e)
  40408. {
  40409. updateColumnUnderMouse (e.x, e.y);
  40410. }
  40411. void TableHeaderComponent::mouseEnter (const MouseEvent& e)
  40412. {
  40413. updateColumnUnderMouse (e.x, e.y);
  40414. }
  40415. void TableHeaderComponent::mouseExit (const MouseEvent& e)
  40416. {
  40417. updateColumnUnderMouse (e.x, e.y);
  40418. }
  40419. void TableHeaderComponent::mouseDown (const MouseEvent& e)
  40420. {
  40421. repaint();
  40422. columnIdBeingResized = 0;
  40423. columnIdBeingDragged = 0;
  40424. if (columnIdUnderMouse != 0)
  40425. {
  40426. draggingColumnOffset = e.x - getColumnPosition (getIndexOfColumnId (columnIdUnderMouse, true)).getX();
  40427. if (e.mods.isPopupMenu())
  40428. columnClicked (columnIdUnderMouse, e.mods);
  40429. }
  40430. if (menuActive && e.mods.isPopupMenu())
  40431. showColumnChooserMenu (columnIdUnderMouse);
  40432. }
  40433. void TableHeaderComponent::mouseDrag (const MouseEvent& e)
  40434. {
  40435. if (columnIdBeingResized == 0
  40436. && columnIdBeingDragged == 0
  40437. && ! (e.mouseWasClicked() || e.mods.isPopupMenu()))
  40438. {
  40439. dragOverlayComp = 0;
  40440. columnIdBeingResized = getResizeDraggerAt (e.getMouseDownX());
  40441. if (columnIdBeingResized != 0)
  40442. {
  40443. const ColumnInfo* const ci = getInfoForId (columnIdBeingResized);
  40444. initialColumnWidth = ci->width;
  40445. }
  40446. else
  40447. {
  40448. beginDrag (e);
  40449. }
  40450. }
  40451. if (columnIdBeingResized != 0)
  40452. {
  40453. const ColumnInfo* const ci = getInfoForId (columnIdBeingResized);
  40454. if (ci != 0)
  40455. {
  40456. int w = jlimit (ci->minimumWidth, ci->maximumWidth,
  40457. initialColumnWidth + e.getDistanceFromDragStartX());
  40458. if (stretchToFit)
  40459. {
  40460. // prevent us dragging a column too far right if we're in stretch-to-fit mode
  40461. int minWidthOnRight = 0;
  40462. for (int i = getIndexOfColumnId (columnIdBeingResized, false) + 1; i < columns.size(); ++i)
  40463. if (columns.getUnchecked (i)->isVisible())
  40464. minWidthOnRight += columns.getUnchecked (i)->minimumWidth;
  40465. const Rectangle<int> currentPos (getColumnPosition (getIndexOfColumnId (columnIdBeingResized, true)));
  40466. w = jmax (ci->minimumWidth, jmin (w, getWidth() - minWidthOnRight - currentPos.getX()));
  40467. }
  40468. setColumnWidth (columnIdBeingResized, w);
  40469. }
  40470. }
  40471. else if (columnIdBeingDragged != 0)
  40472. {
  40473. if (e.y >= -50 && e.y < getHeight() + 50)
  40474. {
  40475. if (dragOverlayComp != 0)
  40476. {
  40477. dragOverlayComp->setVisible (true);
  40478. dragOverlayComp->setBounds (jlimit (0,
  40479. jmax (0, getTotalWidth() - dragOverlayComp->getWidth()),
  40480. e.x - draggingColumnOffset),
  40481. 0,
  40482. dragOverlayComp->getWidth(),
  40483. getHeight());
  40484. for (int i = columns.size(); --i >= 0;)
  40485. {
  40486. const int currentIndex = getIndexOfColumnId (columnIdBeingDragged, true);
  40487. int newIndex = currentIndex;
  40488. if (newIndex > 0)
  40489. {
  40490. // if the previous column isn't draggable, we can't move our column
  40491. // past it, because that'd change the undraggable column's position..
  40492. const ColumnInfo* const previous = columns.getUnchecked (newIndex - 1);
  40493. if ((previous->propertyFlags & draggable) != 0)
  40494. {
  40495. const int leftOfPrevious = getColumnPosition (newIndex - 1).getX();
  40496. const int rightOfCurrent = getColumnPosition (newIndex).getRight();
  40497. if (abs (dragOverlayComp->getX() - leftOfPrevious)
  40498. < abs (dragOverlayComp->getRight() - rightOfCurrent))
  40499. {
  40500. --newIndex;
  40501. }
  40502. }
  40503. }
  40504. if (newIndex < columns.size() - 1)
  40505. {
  40506. // if the next column isn't draggable, we can't move our column
  40507. // past it, because that'd change the undraggable column's position..
  40508. const ColumnInfo* const nextCol = columns.getUnchecked (newIndex + 1);
  40509. if ((nextCol->propertyFlags & draggable) != 0)
  40510. {
  40511. const int leftOfCurrent = getColumnPosition (newIndex).getX();
  40512. const int rightOfNext = getColumnPosition (newIndex + 1).getRight();
  40513. if (abs (dragOverlayComp->getX() - leftOfCurrent)
  40514. > abs (dragOverlayComp->getRight() - rightOfNext))
  40515. {
  40516. ++newIndex;
  40517. }
  40518. }
  40519. }
  40520. if (newIndex != currentIndex)
  40521. moveColumn (columnIdBeingDragged, newIndex);
  40522. else
  40523. break;
  40524. }
  40525. }
  40526. }
  40527. else
  40528. {
  40529. endDrag (draggingColumnOriginalIndex);
  40530. }
  40531. }
  40532. }
  40533. void TableHeaderComponent::beginDrag (const MouseEvent& e)
  40534. {
  40535. if (columnIdBeingDragged == 0)
  40536. {
  40537. columnIdBeingDragged = getColumnIdAtX (e.getMouseDownX());
  40538. const ColumnInfo* const ci = getInfoForId (columnIdBeingDragged);
  40539. if (ci == 0 || (ci->propertyFlags & draggable) == 0)
  40540. {
  40541. columnIdBeingDragged = 0;
  40542. }
  40543. else
  40544. {
  40545. draggingColumnOriginalIndex = getIndexOfColumnId (columnIdBeingDragged, true);
  40546. const Rectangle<int> columnRect (getColumnPosition (draggingColumnOriginalIndex));
  40547. const int temp = columnIdBeingDragged;
  40548. columnIdBeingDragged = 0;
  40549. addAndMakeVisible (dragOverlayComp = new DragOverlayComp (createComponentSnapshot (columnRect, false)));
  40550. columnIdBeingDragged = temp;
  40551. dragOverlayComp->setBounds (columnRect);
  40552. for (int i = listeners.size(); --i >= 0;)
  40553. {
  40554. listeners.getUnchecked(i)->tableColumnDraggingChanged (this, columnIdBeingDragged);
  40555. i = jmin (i, listeners.size() - 1);
  40556. }
  40557. }
  40558. }
  40559. }
  40560. void TableHeaderComponent::endDrag (const int finalIndex)
  40561. {
  40562. if (columnIdBeingDragged != 0)
  40563. {
  40564. moveColumn (columnIdBeingDragged, finalIndex);
  40565. columnIdBeingDragged = 0;
  40566. repaint();
  40567. for (int i = listeners.size(); --i >= 0;)
  40568. {
  40569. listeners.getUnchecked(i)->tableColumnDraggingChanged (this, 0);
  40570. i = jmin (i, listeners.size() - 1);
  40571. }
  40572. }
  40573. }
  40574. void TableHeaderComponent::mouseUp (const MouseEvent& e)
  40575. {
  40576. mouseDrag (e);
  40577. for (int i = columns.size(); --i >= 0;)
  40578. if (columns.getUnchecked (i)->isVisible())
  40579. columns.getUnchecked (i)->lastDeliberateWidth = columns.getUnchecked (i)->width;
  40580. columnIdBeingResized = 0;
  40581. repaint();
  40582. endDrag (getIndexOfColumnId (columnIdBeingDragged, true));
  40583. updateColumnUnderMouse (e.x, e.y);
  40584. if (columnIdUnderMouse != 0 && e.mouseWasClicked() && ! e.mods.isPopupMenu())
  40585. columnClicked (columnIdUnderMouse, e.mods);
  40586. dragOverlayComp = 0;
  40587. }
  40588. const MouseCursor TableHeaderComponent::getMouseCursor()
  40589. {
  40590. if (columnIdBeingResized != 0 || (getResizeDraggerAt (getMouseXYRelative().getX()) != 0 && ! isMouseButtonDown()))
  40591. return MouseCursor (MouseCursor::LeftRightResizeCursor);
  40592. return Component::getMouseCursor();
  40593. }
  40594. bool TableHeaderComponent::ColumnInfo::isVisible() const
  40595. {
  40596. return (propertyFlags & TableHeaderComponent::visible) != 0;
  40597. }
  40598. TableHeaderComponent::ColumnInfo* TableHeaderComponent::getInfoForId (const int id) const
  40599. {
  40600. for (int i = columns.size(); --i >= 0;)
  40601. if (columns.getUnchecked(i)->id == id)
  40602. return columns.getUnchecked(i);
  40603. return 0;
  40604. }
  40605. int TableHeaderComponent::visibleIndexToTotalIndex (const int visibleIndex) const
  40606. {
  40607. int n = 0;
  40608. for (int i = 0; i < columns.size(); ++i)
  40609. {
  40610. if (columns.getUnchecked(i)->isVisible())
  40611. {
  40612. if (n == visibleIndex)
  40613. return i;
  40614. ++n;
  40615. }
  40616. }
  40617. return -1;
  40618. }
  40619. void TableHeaderComponent::sendColumnsChanged()
  40620. {
  40621. if (stretchToFit && lastDeliberateWidth > 0)
  40622. resizeAllColumnsToFit (lastDeliberateWidth);
  40623. repaint();
  40624. columnsChanged = true;
  40625. triggerAsyncUpdate();
  40626. }
  40627. void TableHeaderComponent::handleAsyncUpdate()
  40628. {
  40629. const bool changed = columnsChanged || sortChanged;
  40630. const bool sized = columnsResized || changed;
  40631. const bool sorted = sortChanged;
  40632. columnsChanged = false;
  40633. columnsResized = false;
  40634. sortChanged = false;
  40635. if (sorted)
  40636. {
  40637. for (int i = listeners.size(); --i >= 0;)
  40638. {
  40639. listeners.getUnchecked(i)->tableSortOrderChanged (this);
  40640. i = jmin (i, listeners.size() - 1);
  40641. }
  40642. }
  40643. if (changed)
  40644. {
  40645. for (int i = listeners.size(); --i >= 0;)
  40646. {
  40647. listeners.getUnchecked(i)->tableColumnsChanged (this);
  40648. i = jmin (i, listeners.size() - 1);
  40649. }
  40650. }
  40651. if (sized)
  40652. {
  40653. for (int i = listeners.size(); --i >= 0;)
  40654. {
  40655. listeners.getUnchecked(i)->tableColumnsResized (this);
  40656. i = jmin (i, listeners.size() - 1);
  40657. }
  40658. }
  40659. }
  40660. int TableHeaderComponent::getResizeDraggerAt (const int mouseX) const
  40661. {
  40662. if (((unsigned int) mouseX) < (unsigned int) getWidth())
  40663. {
  40664. const int draggableDistance = 3;
  40665. int x = 0;
  40666. for (int i = 0; i < columns.size(); ++i)
  40667. {
  40668. const ColumnInfo* const ci = columns.getUnchecked(i);
  40669. if (ci->isVisible())
  40670. {
  40671. if (abs (mouseX - (x + ci->width)) <= draggableDistance
  40672. && (ci->propertyFlags & resizable) != 0)
  40673. return ci->id;
  40674. x += ci->width;
  40675. }
  40676. }
  40677. }
  40678. return 0;
  40679. }
  40680. void TableHeaderComponent::updateColumnUnderMouse (int x, int y)
  40681. {
  40682. const int newCol = (reallyContains (x, y, true) && getResizeDraggerAt (x) == 0)
  40683. ? getColumnIdAtX (x) : 0;
  40684. if (newCol != columnIdUnderMouse)
  40685. {
  40686. columnIdUnderMouse = newCol;
  40687. repaint();
  40688. }
  40689. }
  40690. void TableHeaderComponent::showColumnChooserMenu (const int columnIdClicked)
  40691. {
  40692. PopupMenu m;
  40693. addMenuItems (m, columnIdClicked);
  40694. if (m.getNumItems() > 0)
  40695. {
  40696. m.setLookAndFeel (&getLookAndFeel());
  40697. const int result = m.show();
  40698. if (result != 0)
  40699. reactToMenuItem (result, columnIdClicked);
  40700. }
  40701. }
  40702. void TableHeaderListener::tableColumnDraggingChanged (TableHeaderComponent*, int)
  40703. {
  40704. }
  40705. END_JUCE_NAMESPACE
  40706. /*** End of inlined file: juce_TableHeaderComponent.cpp ***/
  40707. /*** Start of inlined file: juce_TableListBox.cpp ***/
  40708. BEGIN_JUCE_NAMESPACE
  40709. static const char* const tableColumnPropertyTag = "_tableColumnID";
  40710. class TableListRowComp : public Component,
  40711. public TooltipClient
  40712. {
  40713. public:
  40714. TableListRowComp (TableListBox& owner_)
  40715. : owner (owner_),
  40716. row (-1),
  40717. isSelected (false)
  40718. {
  40719. }
  40720. ~TableListRowComp()
  40721. {
  40722. deleteAllChildren();
  40723. }
  40724. void paint (Graphics& g)
  40725. {
  40726. TableListBoxModel* const model = owner.getModel();
  40727. if (model != 0)
  40728. {
  40729. const TableHeaderComponent* const header = owner.getHeader();
  40730. model->paintRowBackground (g, row, getWidth(), getHeight(), isSelected);
  40731. const int numColumns = header->getNumColumns (true);
  40732. for (int i = 0; i < numColumns; ++i)
  40733. {
  40734. if (! columnsWithComponents [i])
  40735. {
  40736. const int columnId = header->getColumnIdOfIndex (i, true);
  40737. Rectangle<int> columnRect (header->getColumnPosition (i));
  40738. columnRect.setSize (columnRect.getWidth(), getHeight());
  40739. g.saveState();
  40740. g.reduceClipRegion (columnRect);
  40741. g.setOrigin (columnRect.getX(), 0);
  40742. model->paintCell (g, row, columnId, columnRect.getWidth(), columnRect.getHeight(), isSelected);
  40743. g.restoreState();
  40744. }
  40745. }
  40746. }
  40747. }
  40748. void update (const int newRow, const bool isNowSelected)
  40749. {
  40750. if (newRow != row || isNowSelected != isSelected)
  40751. {
  40752. row = newRow;
  40753. isSelected = isNowSelected;
  40754. repaint();
  40755. }
  40756. if (row < owner.getNumRows())
  40757. {
  40758. jassert (row >= 0);
  40759. const var::identifier tagPropertyName ("_tableLastUseNum");
  40760. const int newTag = Random::getSystemRandom().nextInt();
  40761. const TableHeaderComponent* const header = owner.getHeader();
  40762. const int numColumns = header->getNumColumns (true);
  40763. int i;
  40764. columnsWithComponents.clear();
  40765. if (owner.getModel() != 0)
  40766. {
  40767. for (i = 0; i < numColumns; ++i)
  40768. {
  40769. const int columnId = header->getColumnIdOfIndex (i, true);
  40770. Component* const newComp
  40771. = owner.getModel()->refreshComponentForCell (row, columnId, isSelected,
  40772. findChildComponentForColumn (columnId));
  40773. if (newComp != 0)
  40774. {
  40775. addAndMakeVisible (newComp);
  40776. newComp->getProperties().set (tagPropertyName, newTag);
  40777. newComp->getProperties().set (tableColumnPropertyTag, columnId);
  40778. const Rectangle<int> columnRect (header->getColumnPosition (i));
  40779. newComp->setBounds (columnRect.getX(), 0, columnRect.getWidth(), getHeight());
  40780. columnsWithComponents.setBit (i);
  40781. }
  40782. }
  40783. }
  40784. for (i = getNumChildComponents(); --i >= 0;)
  40785. {
  40786. Component* const c = getChildComponent (i);
  40787. if ((int) c->getProperties() [tagPropertyName] != newTag)
  40788. delete c;
  40789. }
  40790. }
  40791. else
  40792. {
  40793. columnsWithComponents.clear();
  40794. deleteAllChildren();
  40795. }
  40796. }
  40797. void resized()
  40798. {
  40799. for (int i = getNumChildComponents(); --i >= 0;)
  40800. {
  40801. Component* const c = getChildComponent (i);
  40802. const int columnId = c->getProperties() [tableColumnPropertyTag];
  40803. if (columnId != 0)
  40804. {
  40805. const Rectangle<int> columnRect (owner.getHeader()->getColumnPosition (owner.getHeader()->getIndexOfColumnId (columnId, true)));
  40806. c->setBounds (columnRect.getX(), 0, columnRect.getWidth(), getHeight());
  40807. }
  40808. }
  40809. }
  40810. void mouseDown (const MouseEvent& e)
  40811. {
  40812. isDragging = false;
  40813. selectRowOnMouseUp = false;
  40814. if (isEnabled())
  40815. {
  40816. if (! isSelected)
  40817. {
  40818. owner.selectRowsBasedOnModifierKeys (row, e.mods);
  40819. const int columnId = owner.getHeader()->getColumnIdAtX (e.x);
  40820. if (columnId != 0 && owner.getModel() != 0)
  40821. owner.getModel()->cellClicked (row, columnId, e);
  40822. }
  40823. else
  40824. {
  40825. selectRowOnMouseUp = true;
  40826. }
  40827. }
  40828. }
  40829. void mouseDrag (const MouseEvent& e)
  40830. {
  40831. if (isEnabled() && owner.getModel() != 0 && ! (e.mouseWasClicked() || isDragging))
  40832. {
  40833. const SparseSet<int> selectedRows (owner.getSelectedRows());
  40834. if (selectedRows.size() > 0)
  40835. {
  40836. const String dragDescription (owner.getModel()->getDragSourceDescription (selectedRows));
  40837. if (dragDescription.isNotEmpty())
  40838. {
  40839. isDragging = true;
  40840. owner.startDragAndDrop (e, dragDescription);
  40841. }
  40842. }
  40843. }
  40844. }
  40845. void mouseUp (const MouseEvent& e)
  40846. {
  40847. if (selectRowOnMouseUp && e.mouseWasClicked() && isEnabled())
  40848. {
  40849. owner.selectRowsBasedOnModifierKeys (row, e.mods);
  40850. const int columnId = owner.getHeader()->getColumnIdAtX (e.x);
  40851. if (columnId != 0 && owner.getModel() != 0)
  40852. owner.getModel()->cellClicked (row, columnId, e);
  40853. }
  40854. }
  40855. void mouseDoubleClick (const MouseEvent& e)
  40856. {
  40857. const int columnId = owner.getHeader()->getColumnIdAtX (e.x);
  40858. if (columnId != 0 && owner.getModel() != 0)
  40859. owner.getModel()->cellDoubleClicked (row, columnId, e);
  40860. }
  40861. const String getTooltip()
  40862. {
  40863. const int columnId = owner.getHeader()->getColumnIdAtX (getMouseXYRelative().getX());
  40864. if (columnId != 0 && owner.getModel() != 0)
  40865. return owner.getModel()->getCellTooltip (row, columnId);
  40866. return String::empty;
  40867. }
  40868. juce_UseDebuggingNewOperator
  40869. private:
  40870. TableListBox& owner;
  40871. int row;
  40872. bool isSelected, isDragging, selectRowOnMouseUp;
  40873. BigInteger columnsWithComponents;
  40874. Component* findChildComponentForColumn (const int columnId) const
  40875. {
  40876. for (int i = getNumChildComponents(); --i >= 0;)
  40877. {
  40878. Component* const c = getChildComponent (i);
  40879. if ((int) c->getProperties() [tableColumnPropertyTag] == columnId)
  40880. return c;
  40881. }
  40882. return 0;
  40883. }
  40884. TableListRowComp (const TableListRowComp&);
  40885. TableListRowComp& operator= (const TableListRowComp&);
  40886. };
  40887. class TableListBoxHeader : public TableHeaderComponent
  40888. {
  40889. public:
  40890. TableListBoxHeader (TableListBox& owner_)
  40891. : owner (owner_)
  40892. {
  40893. }
  40894. ~TableListBoxHeader()
  40895. {
  40896. }
  40897. void addMenuItems (PopupMenu& menu, int columnIdClicked)
  40898. {
  40899. if (owner.isAutoSizeMenuOptionShown())
  40900. {
  40901. menu.addItem (0xf836743, TRANS("Auto-size this column"), columnIdClicked != 0);
  40902. menu.addItem (0xf836744, TRANS("Auto-size all columns"), owner.getHeader()->getNumColumns (true) > 0);
  40903. menu.addSeparator();
  40904. }
  40905. TableHeaderComponent::addMenuItems (menu, columnIdClicked);
  40906. }
  40907. void reactToMenuItem (int menuReturnId, int columnIdClicked)
  40908. {
  40909. if (menuReturnId == 0xf836743)
  40910. {
  40911. owner.autoSizeColumn (columnIdClicked);
  40912. }
  40913. else if (menuReturnId == 0xf836744)
  40914. {
  40915. owner.autoSizeAllColumns();
  40916. }
  40917. else
  40918. {
  40919. TableHeaderComponent::reactToMenuItem (menuReturnId, columnIdClicked);
  40920. }
  40921. }
  40922. juce_UseDebuggingNewOperator
  40923. private:
  40924. TableListBox& owner;
  40925. TableListBoxHeader (const TableListBoxHeader&);
  40926. TableListBoxHeader& operator= (const TableListBoxHeader&);
  40927. };
  40928. TableListBox::TableListBox (const String& name, TableListBoxModel* const model_)
  40929. : ListBox (name, 0),
  40930. model (model_),
  40931. autoSizeOptionsShown (true)
  40932. {
  40933. ListBox::model = this;
  40934. header = new TableListBoxHeader (*this);
  40935. header->setSize (100, 28);
  40936. header->addListener (this);
  40937. setHeaderComponent (header);
  40938. }
  40939. TableListBox::~TableListBox()
  40940. {
  40941. deleteAllChildren();
  40942. }
  40943. void TableListBox::setModel (TableListBoxModel* const newModel)
  40944. {
  40945. if (model != newModel)
  40946. {
  40947. model = newModel;
  40948. updateContent();
  40949. }
  40950. }
  40951. int TableListBox::getHeaderHeight() const
  40952. {
  40953. return header->getHeight();
  40954. }
  40955. void TableListBox::setHeaderHeight (const int newHeight)
  40956. {
  40957. header->setSize (header->getWidth(), newHeight);
  40958. resized();
  40959. }
  40960. void TableListBox::autoSizeColumn (const int columnId)
  40961. {
  40962. const int width = model != 0 ? model->getColumnAutoSizeWidth (columnId) : 0;
  40963. if (width > 0)
  40964. header->setColumnWidth (columnId, width);
  40965. }
  40966. void TableListBox::autoSizeAllColumns()
  40967. {
  40968. for (int i = 0; i < header->getNumColumns (true); ++i)
  40969. autoSizeColumn (header->getColumnIdOfIndex (i, true));
  40970. }
  40971. void TableListBox::setAutoSizeMenuOptionShown (const bool shouldBeShown)
  40972. {
  40973. autoSizeOptionsShown = shouldBeShown;
  40974. }
  40975. bool TableListBox::isAutoSizeMenuOptionShown() const
  40976. {
  40977. return autoSizeOptionsShown;
  40978. }
  40979. const Rectangle<int> TableListBox::getCellPosition (const int columnId,
  40980. const int rowNumber,
  40981. const bool relativeToComponentTopLeft) const
  40982. {
  40983. Rectangle<int> headerCell (header->getColumnPosition (header->getIndexOfColumnId (columnId, true)));
  40984. if (relativeToComponentTopLeft)
  40985. headerCell.translate (header->getX(), 0);
  40986. const Rectangle<int> row (getRowPosition (rowNumber, relativeToComponentTopLeft));
  40987. return Rectangle<int> (headerCell.getX(), row.getY(),
  40988. headerCell.getWidth(), row.getHeight());
  40989. }
  40990. void TableListBox::scrollToEnsureColumnIsOnscreen (const int columnId)
  40991. {
  40992. ScrollBar* const scrollbar = getHorizontalScrollBar();
  40993. if (scrollbar != 0)
  40994. {
  40995. const Rectangle<int> pos (header->getColumnPosition (header->getIndexOfColumnId (columnId, true)));
  40996. double x = scrollbar->getCurrentRangeStart();
  40997. const double w = scrollbar->getCurrentRangeSize();
  40998. if (pos.getX() < x)
  40999. x = pos.getX();
  41000. else if (pos.getRight() > x + w)
  41001. x += jmax (0.0, pos.getRight() - (x + w));
  41002. scrollbar->setCurrentRangeStart (x);
  41003. }
  41004. }
  41005. int TableListBox::getNumRows()
  41006. {
  41007. return model != 0 ? model->getNumRows() : 0;
  41008. }
  41009. void TableListBox::paintListBoxItem (int, Graphics&, int, int, bool)
  41010. {
  41011. }
  41012. Component* TableListBox::refreshComponentForRow (int rowNumber, bool isRowSelected_, Component* existingComponentToUpdate)
  41013. {
  41014. if (existingComponentToUpdate == 0)
  41015. existingComponentToUpdate = new TableListRowComp (*this);
  41016. static_cast <TableListRowComp*> (existingComponentToUpdate)->update (rowNumber, isRowSelected_);
  41017. return existingComponentToUpdate;
  41018. }
  41019. void TableListBox::selectedRowsChanged (int row)
  41020. {
  41021. if (model != 0)
  41022. model->selectedRowsChanged (row);
  41023. }
  41024. void TableListBox::deleteKeyPressed (int row)
  41025. {
  41026. if (model != 0)
  41027. model->deleteKeyPressed (row);
  41028. }
  41029. void TableListBox::returnKeyPressed (int row)
  41030. {
  41031. if (model != 0)
  41032. model->returnKeyPressed (row);
  41033. }
  41034. void TableListBox::backgroundClicked()
  41035. {
  41036. if (model != 0)
  41037. model->backgroundClicked();
  41038. }
  41039. void TableListBox::listWasScrolled()
  41040. {
  41041. if (model != 0)
  41042. model->listWasScrolled();
  41043. }
  41044. void TableListBox::tableColumnsChanged (TableHeaderComponent*)
  41045. {
  41046. setMinimumContentWidth (header->getTotalWidth());
  41047. repaint();
  41048. updateColumnComponents();
  41049. }
  41050. void TableListBox::tableColumnsResized (TableHeaderComponent*)
  41051. {
  41052. setMinimumContentWidth (header->getTotalWidth());
  41053. repaint();
  41054. updateColumnComponents();
  41055. }
  41056. void TableListBox::tableSortOrderChanged (TableHeaderComponent*)
  41057. {
  41058. if (model != 0)
  41059. model->sortOrderChanged (header->getSortColumnId(),
  41060. header->isSortedForwards());
  41061. }
  41062. void TableListBox::tableColumnDraggingChanged (TableHeaderComponent*, int columnIdNowBeingDragged_)
  41063. {
  41064. columnIdNowBeingDragged = columnIdNowBeingDragged_;
  41065. repaint();
  41066. }
  41067. void TableListBox::resized()
  41068. {
  41069. ListBox::resized();
  41070. header->resizeAllColumnsToFit (getVisibleContentWidth());
  41071. setMinimumContentWidth (header->getTotalWidth());
  41072. }
  41073. void TableListBox::updateColumnComponents() const
  41074. {
  41075. const int firstRow = getRowContainingPosition (0, 0);
  41076. for (int i = firstRow + getNumRowsOnScreen() + 2; --i >= firstRow;)
  41077. {
  41078. TableListRowComp* const rowComp = dynamic_cast <TableListRowComp*> (getComponentForRowNumber (i));
  41079. if (rowComp != 0)
  41080. rowComp->resized();
  41081. }
  41082. }
  41083. void TableListBoxModel::cellClicked (int, int, const MouseEvent&)
  41084. {
  41085. }
  41086. void TableListBoxModel::cellDoubleClicked (int, int, const MouseEvent&)
  41087. {
  41088. }
  41089. void TableListBoxModel::backgroundClicked()
  41090. {
  41091. }
  41092. void TableListBoxModel::sortOrderChanged (int, const bool)
  41093. {
  41094. }
  41095. int TableListBoxModel::getColumnAutoSizeWidth (int)
  41096. {
  41097. return 0;
  41098. }
  41099. void TableListBoxModel::selectedRowsChanged (int)
  41100. {
  41101. }
  41102. void TableListBoxModel::deleteKeyPressed (int)
  41103. {
  41104. }
  41105. void TableListBoxModel::returnKeyPressed (int)
  41106. {
  41107. }
  41108. void TableListBoxModel::listWasScrolled()
  41109. {
  41110. }
  41111. const String TableListBoxModel::getCellTooltip (int /*rowNumber*/, int /*columnId*/)
  41112. {
  41113. return String::empty;
  41114. }
  41115. const String TableListBoxModel::getDragSourceDescription (const SparseSet<int>&)
  41116. {
  41117. return String::empty;
  41118. }
  41119. Component* TableListBoxModel::refreshComponentForCell (int, int, bool, Component* existingComponentToUpdate)
  41120. {
  41121. (void) existingComponentToUpdate;
  41122. jassert (existingComponentToUpdate == 0); // indicates a failure in the code the recycles the components
  41123. return 0;
  41124. }
  41125. END_JUCE_NAMESPACE
  41126. /*** End of inlined file: juce_TableListBox.cpp ***/
  41127. /*** Start of inlined file: juce_TextEditor.cpp ***/
  41128. BEGIN_JUCE_NAMESPACE
  41129. // a word or space that can't be broken down any further
  41130. struct TextAtom
  41131. {
  41132. String atomText;
  41133. float width;
  41134. uint16 numChars;
  41135. bool isWhitespace() const { return CharacterFunctions::isWhitespace (atomText[0]); }
  41136. bool isNewLine() const { return atomText[0] == '\r' || atomText[0] == '\n'; }
  41137. const String getText (const juce_wchar passwordCharacter) const
  41138. {
  41139. if (passwordCharacter == 0)
  41140. return atomText;
  41141. else
  41142. return String::repeatedString (String::charToString (passwordCharacter),
  41143. atomText.length());
  41144. }
  41145. const String getTrimmedText (const juce_wchar passwordCharacter) const
  41146. {
  41147. if (passwordCharacter == 0)
  41148. return atomText.substring (0, numChars);
  41149. else if (isNewLine())
  41150. return String::empty;
  41151. else
  41152. return String::repeatedString (String::charToString (passwordCharacter), numChars);
  41153. }
  41154. };
  41155. // a run of text with a single font and colour
  41156. class TextEditor::UniformTextSection
  41157. {
  41158. public:
  41159. UniformTextSection (const String& text,
  41160. const Font& font_,
  41161. const Colour& colour_,
  41162. const juce_wchar passwordCharacter)
  41163. : font (font_),
  41164. colour (colour_)
  41165. {
  41166. initialiseAtoms (text, passwordCharacter);
  41167. }
  41168. UniformTextSection (const UniformTextSection& other)
  41169. : font (other.font),
  41170. colour (other.colour)
  41171. {
  41172. atoms.ensureStorageAllocated (other.atoms.size());
  41173. for (int i = 0; i < other.atoms.size(); ++i)
  41174. atoms.add (new TextAtom (*other.atoms.getUnchecked(i)));
  41175. }
  41176. ~UniformTextSection()
  41177. {
  41178. // (no need to delete the atoms, as they're explicitly deleted by the caller)
  41179. }
  41180. void clear()
  41181. {
  41182. for (int i = atoms.size(); --i >= 0;)
  41183. delete getAtom(i);
  41184. atoms.clear();
  41185. }
  41186. int getNumAtoms() const
  41187. {
  41188. return atoms.size();
  41189. }
  41190. TextAtom* getAtom (const int index) const throw()
  41191. {
  41192. return atoms.getUnchecked (index);
  41193. }
  41194. void append (const UniformTextSection& other, const juce_wchar passwordCharacter)
  41195. {
  41196. if (other.atoms.size() > 0)
  41197. {
  41198. TextAtom* const lastAtom = atoms.getLast();
  41199. int i = 0;
  41200. if (lastAtom != 0)
  41201. {
  41202. if (! CharacterFunctions::isWhitespace (lastAtom->atomText.getLastCharacter()))
  41203. {
  41204. TextAtom* const first = other.getAtom(0);
  41205. if (! CharacterFunctions::isWhitespace (first->atomText[0]))
  41206. {
  41207. lastAtom->atomText += first->atomText;
  41208. lastAtom->numChars = (uint16) (lastAtom->numChars + first->numChars);
  41209. lastAtom->width = font.getStringWidthFloat (lastAtom->getText (passwordCharacter));
  41210. delete first;
  41211. ++i;
  41212. }
  41213. }
  41214. }
  41215. atoms.ensureStorageAllocated (atoms.size() + other.atoms.size() - i);
  41216. while (i < other.atoms.size())
  41217. {
  41218. atoms.add (other.getAtom(i));
  41219. ++i;
  41220. }
  41221. }
  41222. }
  41223. UniformTextSection* split (const int indexToBreakAt,
  41224. const juce_wchar passwordCharacter)
  41225. {
  41226. UniformTextSection* const section2 = new UniformTextSection (String::empty,
  41227. font, colour,
  41228. passwordCharacter);
  41229. int index = 0;
  41230. for (int i = 0; i < atoms.size(); ++i)
  41231. {
  41232. TextAtom* const atom = getAtom(i);
  41233. const int nextIndex = index + atom->numChars;
  41234. if (index == indexToBreakAt)
  41235. {
  41236. int j;
  41237. for (j = i; j < atoms.size(); ++j)
  41238. section2->atoms.add (getAtom (j));
  41239. for (j = atoms.size(); --j >= i;)
  41240. atoms.remove (j);
  41241. break;
  41242. }
  41243. else if (indexToBreakAt >= index && indexToBreakAt < nextIndex)
  41244. {
  41245. TextAtom* const secondAtom = new TextAtom();
  41246. secondAtom->atomText = atom->atomText.substring (indexToBreakAt - index);
  41247. secondAtom->width = font.getStringWidthFloat (secondAtom->getText (passwordCharacter));
  41248. secondAtom->numChars = (uint16) secondAtom->atomText.length();
  41249. section2->atoms.add (secondAtom);
  41250. atom->atomText = atom->atomText.substring (0, indexToBreakAt - index);
  41251. atom->width = font.getStringWidthFloat (atom->getText (passwordCharacter));
  41252. atom->numChars = (uint16) (indexToBreakAt - index);
  41253. int j;
  41254. for (j = i + 1; j < atoms.size(); ++j)
  41255. section2->atoms.add (getAtom (j));
  41256. for (j = atoms.size(); --j > i;)
  41257. atoms.remove (j);
  41258. break;
  41259. }
  41260. index = nextIndex;
  41261. }
  41262. return section2;
  41263. }
  41264. void appendAllText (String::Concatenator& concatenator) const
  41265. {
  41266. for (int i = 0; i < atoms.size(); ++i)
  41267. concatenator.append (getAtom(i)->atomText);
  41268. }
  41269. void appendSubstring (String::Concatenator& concatenator,
  41270. const Range<int>& range) const
  41271. {
  41272. int index = 0;
  41273. for (int i = 0; i < atoms.size(); ++i)
  41274. {
  41275. const TextAtom* const atom = getAtom (i);
  41276. const int nextIndex = index + atom->numChars;
  41277. if (range.getStart() < nextIndex)
  41278. {
  41279. if (range.getEnd() <= index)
  41280. break;
  41281. const Range<int> r ((range - index).getIntersectionWith (Range<int> (0, (int) atom->numChars)));
  41282. if (! r.isEmpty())
  41283. concatenator.append (atom->atomText.substring (r.getStart(), r.getEnd()));
  41284. }
  41285. index = nextIndex;
  41286. }
  41287. }
  41288. int getTotalLength() const
  41289. {
  41290. int total = 0;
  41291. for (int i = atoms.size(); --i >= 0;)
  41292. total += getAtom(i)->numChars;
  41293. return total;
  41294. }
  41295. void setFont (const Font& newFont,
  41296. const juce_wchar passwordCharacter)
  41297. {
  41298. if (font != newFont)
  41299. {
  41300. font = newFont;
  41301. for (int i = atoms.size(); --i >= 0;)
  41302. {
  41303. TextAtom* const atom = atoms.getUnchecked(i);
  41304. atom->width = newFont.getStringWidthFloat (atom->getText (passwordCharacter));
  41305. }
  41306. }
  41307. }
  41308. juce_UseDebuggingNewOperator
  41309. Font font;
  41310. Colour colour;
  41311. private:
  41312. Array <TextAtom*> atoms;
  41313. void initialiseAtoms (const String& textToParse,
  41314. const juce_wchar passwordCharacter)
  41315. {
  41316. int i = 0;
  41317. const int len = textToParse.length();
  41318. const juce_wchar* const text = textToParse;
  41319. while (i < len)
  41320. {
  41321. int start = i;
  41322. // create a whitespace atom unless it starts with non-ws
  41323. if (CharacterFunctions::isWhitespace (text[i])
  41324. && text[i] != '\r'
  41325. && text[i] != '\n')
  41326. {
  41327. while (i < len
  41328. && CharacterFunctions::isWhitespace (text[i])
  41329. && text[i] != '\r'
  41330. && text[i] != '\n')
  41331. {
  41332. ++i;
  41333. }
  41334. }
  41335. else
  41336. {
  41337. if (text[i] == '\r')
  41338. {
  41339. ++i;
  41340. if ((i < len) && (text[i] == '\n'))
  41341. {
  41342. ++start;
  41343. ++i;
  41344. }
  41345. }
  41346. else if (text[i] == '\n')
  41347. {
  41348. ++i;
  41349. }
  41350. else
  41351. {
  41352. while ((i < len) && ! CharacterFunctions::isWhitespace (text[i]))
  41353. ++i;
  41354. }
  41355. }
  41356. TextAtom* const atom = new TextAtom();
  41357. atom->atomText = String (text + start, i - start);
  41358. atom->width = font.getStringWidthFloat (atom->getText (passwordCharacter));
  41359. atom->numChars = (uint16) (i - start);
  41360. atoms.add (atom);
  41361. }
  41362. }
  41363. UniformTextSection& operator= (const UniformTextSection& other);
  41364. };
  41365. class TextEditor::Iterator
  41366. {
  41367. public:
  41368. Iterator (const Array <UniformTextSection*>& sections_,
  41369. const float wordWrapWidth_,
  41370. const juce_wchar passwordCharacter_)
  41371. : indexInText (0),
  41372. lineY (0),
  41373. lineHeight (0),
  41374. maxDescent (0),
  41375. atomX (0),
  41376. atomRight (0),
  41377. atom (0),
  41378. currentSection (0),
  41379. sections (sections_),
  41380. sectionIndex (0),
  41381. atomIndex (0),
  41382. wordWrapWidth (wordWrapWidth_),
  41383. passwordCharacter (passwordCharacter_)
  41384. {
  41385. jassert (wordWrapWidth_ > 0);
  41386. if (sections.size() > 0)
  41387. {
  41388. currentSection = sections.getUnchecked (sectionIndex);
  41389. if (currentSection != 0)
  41390. beginNewLine();
  41391. }
  41392. }
  41393. Iterator (const Iterator& other)
  41394. : indexInText (other.indexInText),
  41395. lineY (other.lineY),
  41396. lineHeight (other.lineHeight),
  41397. maxDescent (other.maxDescent),
  41398. atomX (other.atomX),
  41399. atomRight (other.atomRight),
  41400. atom (other.atom),
  41401. currentSection (other.currentSection),
  41402. sections (other.sections),
  41403. sectionIndex (other.sectionIndex),
  41404. atomIndex (other.atomIndex),
  41405. wordWrapWidth (other.wordWrapWidth),
  41406. passwordCharacter (other.passwordCharacter),
  41407. tempAtom (other.tempAtom)
  41408. {
  41409. }
  41410. ~Iterator()
  41411. {
  41412. }
  41413. bool next()
  41414. {
  41415. if (atom == &tempAtom)
  41416. {
  41417. const int numRemaining = tempAtom.atomText.length() - tempAtom.numChars;
  41418. if (numRemaining > 0)
  41419. {
  41420. tempAtom.atomText = tempAtom.atomText.substring (tempAtom.numChars);
  41421. atomX = 0;
  41422. if (tempAtom.numChars > 0)
  41423. lineY += lineHeight;
  41424. indexInText += tempAtom.numChars;
  41425. GlyphArrangement g;
  41426. g.addLineOfText (currentSection->font, atom->getText (passwordCharacter), 0.0f, 0.0f);
  41427. int split;
  41428. for (split = 0; split < g.getNumGlyphs(); ++split)
  41429. if (shouldWrap (g.getGlyph (split).getRight()))
  41430. break;
  41431. if (split > 0 && split <= numRemaining)
  41432. {
  41433. tempAtom.numChars = (uint16) split;
  41434. tempAtom.width = g.getGlyph (split - 1).getRight();
  41435. atomRight = atomX + tempAtom.width;
  41436. return true;
  41437. }
  41438. }
  41439. }
  41440. bool forceNewLine = false;
  41441. if (sectionIndex >= sections.size())
  41442. {
  41443. moveToEndOfLastAtom();
  41444. return false;
  41445. }
  41446. else if (atomIndex >= currentSection->getNumAtoms() - 1)
  41447. {
  41448. if (atomIndex >= currentSection->getNumAtoms())
  41449. {
  41450. if (++sectionIndex >= sections.size())
  41451. {
  41452. moveToEndOfLastAtom();
  41453. return false;
  41454. }
  41455. atomIndex = 0;
  41456. currentSection = sections.getUnchecked (sectionIndex);
  41457. }
  41458. else
  41459. {
  41460. const TextAtom* const lastAtom = currentSection->getAtom (atomIndex);
  41461. if (! lastAtom->isWhitespace())
  41462. {
  41463. // handle the case where the last atom in a section is actually part of the same
  41464. // word as the first atom of the next section...
  41465. float right = atomRight + lastAtom->width;
  41466. float lineHeight2 = lineHeight;
  41467. float maxDescent2 = maxDescent;
  41468. for (int section = sectionIndex + 1; section < sections.size(); ++section)
  41469. {
  41470. const UniformTextSection* const s = sections.getUnchecked (section);
  41471. if (s->getNumAtoms() == 0)
  41472. break;
  41473. const TextAtom* const nextAtom = s->getAtom (0);
  41474. if (nextAtom->isWhitespace())
  41475. break;
  41476. right += nextAtom->width;
  41477. lineHeight2 = jmax (lineHeight2, s->font.getHeight());
  41478. maxDescent2 = jmax (maxDescent2, s->font.getDescent());
  41479. if (shouldWrap (right))
  41480. {
  41481. lineHeight = lineHeight2;
  41482. maxDescent = maxDescent2;
  41483. forceNewLine = true;
  41484. break;
  41485. }
  41486. if (s->getNumAtoms() > 1)
  41487. break;
  41488. }
  41489. }
  41490. }
  41491. }
  41492. if (atom != 0)
  41493. {
  41494. atomX = atomRight;
  41495. indexInText += atom->numChars;
  41496. if (atom->isNewLine())
  41497. beginNewLine();
  41498. }
  41499. atom = currentSection->getAtom (atomIndex);
  41500. atomRight = atomX + atom->width;
  41501. ++atomIndex;
  41502. if (shouldWrap (atomRight) || forceNewLine)
  41503. {
  41504. if (atom->isWhitespace())
  41505. {
  41506. // leave whitespace at the end of a line, but truncate it to avoid scrolling
  41507. atomRight = jmin (atomRight, wordWrapWidth);
  41508. }
  41509. else
  41510. {
  41511. atomRight = atom->width;
  41512. if (shouldWrap (atomRight)) // atom too big to fit on a line, so break it up..
  41513. {
  41514. tempAtom = *atom;
  41515. tempAtom.width = 0;
  41516. tempAtom.numChars = 0;
  41517. atom = &tempAtom;
  41518. if (atomX > 0)
  41519. beginNewLine();
  41520. return next();
  41521. }
  41522. beginNewLine();
  41523. return true;
  41524. }
  41525. }
  41526. return true;
  41527. }
  41528. void beginNewLine()
  41529. {
  41530. atomX = 0;
  41531. lineY += lineHeight;
  41532. int tempSectionIndex = sectionIndex;
  41533. int tempAtomIndex = atomIndex;
  41534. const UniformTextSection* section = sections.getUnchecked (tempSectionIndex);
  41535. lineHeight = section->font.getHeight();
  41536. maxDescent = section->font.getDescent();
  41537. float x = (atom != 0) ? atom->width : 0;
  41538. while (! shouldWrap (x))
  41539. {
  41540. if (tempSectionIndex >= sections.size())
  41541. break;
  41542. bool checkSize = false;
  41543. if (tempAtomIndex >= section->getNumAtoms())
  41544. {
  41545. if (++tempSectionIndex >= sections.size())
  41546. break;
  41547. tempAtomIndex = 0;
  41548. section = sections.getUnchecked (tempSectionIndex);
  41549. checkSize = true;
  41550. }
  41551. const TextAtom* const nextAtom = section->getAtom (tempAtomIndex);
  41552. if (nextAtom == 0)
  41553. break;
  41554. x += nextAtom->width;
  41555. if (shouldWrap (x) || nextAtom->isNewLine())
  41556. break;
  41557. if (checkSize)
  41558. {
  41559. lineHeight = jmax (lineHeight, section->font.getHeight());
  41560. maxDescent = jmax (maxDescent, section->font.getDescent());
  41561. }
  41562. ++tempAtomIndex;
  41563. }
  41564. }
  41565. void draw (Graphics& g, const UniformTextSection*& lastSection) const
  41566. {
  41567. if (passwordCharacter != 0 || ! atom->isWhitespace())
  41568. {
  41569. if (lastSection != currentSection)
  41570. {
  41571. lastSection = currentSection;
  41572. g.setColour (currentSection->colour);
  41573. g.setFont (currentSection->font);
  41574. }
  41575. jassert (atom->getTrimmedText (passwordCharacter).isNotEmpty());
  41576. GlyphArrangement ga;
  41577. ga.addLineOfText (currentSection->font,
  41578. atom->getTrimmedText (passwordCharacter),
  41579. atomX,
  41580. (float) roundToInt (lineY + lineHeight - maxDescent));
  41581. ga.draw (g);
  41582. }
  41583. }
  41584. void drawSelection (Graphics& g,
  41585. const Range<int>& selection) const
  41586. {
  41587. const int startX = roundToInt (indexToX (selection.getStart()));
  41588. const int endX = roundToInt (indexToX (selection.getEnd()));
  41589. const int y = roundToInt (lineY);
  41590. const int nextY = roundToInt (lineY + lineHeight);
  41591. g.fillRect (startX, y, endX - startX, nextY - y);
  41592. }
  41593. void drawSelectedText (Graphics& g,
  41594. const Range<int>& selection,
  41595. const Colour& selectedTextColour) const
  41596. {
  41597. if (passwordCharacter != 0 || ! atom->isWhitespace())
  41598. {
  41599. GlyphArrangement ga;
  41600. ga.addLineOfText (currentSection->font,
  41601. atom->getTrimmedText (passwordCharacter),
  41602. atomX,
  41603. (float) roundToInt (lineY + lineHeight - maxDescent));
  41604. if (selection.getEnd() < indexInText + atom->numChars)
  41605. {
  41606. GlyphArrangement ga2 (ga);
  41607. ga2.removeRangeOfGlyphs (0, selection.getEnd() - indexInText);
  41608. ga.removeRangeOfGlyphs (selection.getEnd() - indexInText, -1);
  41609. g.setColour (currentSection->colour);
  41610. ga2.draw (g);
  41611. }
  41612. if (selection.getStart() > indexInText)
  41613. {
  41614. GlyphArrangement ga2 (ga);
  41615. ga2.removeRangeOfGlyphs (selection.getStart() - indexInText, -1);
  41616. ga.removeRangeOfGlyphs (0, selection.getStart() - indexInText);
  41617. g.setColour (currentSection->colour);
  41618. ga2.draw (g);
  41619. }
  41620. g.setColour (selectedTextColour);
  41621. ga.draw (g);
  41622. }
  41623. }
  41624. float indexToX (const int indexToFind) const
  41625. {
  41626. if (indexToFind <= indexInText)
  41627. return atomX;
  41628. if (indexToFind >= indexInText + atom->numChars)
  41629. return atomRight;
  41630. GlyphArrangement g;
  41631. g.addLineOfText (currentSection->font,
  41632. atom->getText (passwordCharacter),
  41633. atomX, 0.0f);
  41634. if (indexToFind - indexInText >= g.getNumGlyphs())
  41635. return atomRight;
  41636. return jmin (atomRight, g.getGlyph (indexToFind - indexInText).getLeft());
  41637. }
  41638. int xToIndex (const float xToFind) const
  41639. {
  41640. if (xToFind <= atomX || atom->isNewLine())
  41641. return indexInText;
  41642. if (xToFind >= atomRight)
  41643. return indexInText + atom->numChars;
  41644. GlyphArrangement g;
  41645. g.addLineOfText (currentSection->font,
  41646. atom->getText (passwordCharacter),
  41647. atomX, 0.0f);
  41648. int j;
  41649. for (j = 0; j < g.getNumGlyphs(); ++j)
  41650. if ((g.getGlyph(j).getLeft() + g.getGlyph(j).getRight()) / 2 > xToFind)
  41651. break;
  41652. return indexInText + j;
  41653. }
  41654. bool getCharPosition (const int index, float& cx, float& cy, float& lineHeight_)
  41655. {
  41656. while (next())
  41657. {
  41658. if (indexInText + atom->numChars > index)
  41659. {
  41660. cx = indexToX (index);
  41661. cy = lineY;
  41662. lineHeight_ = lineHeight;
  41663. return true;
  41664. }
  41665. }
  41666. cx = atomX;
  41667. cy = lineY;
  41668. lineHeight_ = lineHeight;
  41669. return false;
  41670. }
  41671. juce_UseDebuggingNewOperator
  41672. int indexInText;
  41673. float lineY, lineHeight, maxDescent;
  41674. float atomX, atomRight;
  41675. const TextAtom* atom;
  41676. const UniformTextSection* currentSection;
  41677. private:
  41678. const Array <UniformTextSection*>& sections;
  41679. int sectionIndex, atomIndex;
  41680. const float wordWrapWidth;
  41681. const juce_wchar passwordCharacter;
  41682. TextAtom tempAtom;
  41683. Iterator& operator= (const Iterator&);
  41684. void moveToEndOfLastAtom()
  41685. {
  41686. if (atom != 0)
  41687. {
  41688. atomX = atomRight;
  41689. if (atom->isNewLine())
  41690. {
  41691. atomX = 0.0f;
  41692. lineY += lineHeight;
  41693. }
  41694. }
  41695. }
  41696. bool shouldWrap (const float x) const
  41697. {
  41698. return (x - 0.0001f) >= wordWrapWidth;
  41699. }
  41700. };
  41701. class TextEditor::InsertAction : public UndoableAction
  41702. {
  41703. TextEditor& owner;
  41704. const String text;
  41705. const int insertIndex, oldCaretPos, newCaretPos;
  41706. const Font font;
  41707. const Colour colour;
  41708. InsertAction (const InsertAction&);
  41709. InsertAction& operator= (const InsertAction&);
  41710. public:
  41711. InsertAction (TextEditor& owner_,
  41712. const String& text_,
  41713. const int insertIndex_,
  41714. const Font& font_,
  41715. const Colour& colour_,
  41716. const int oldCaretPos_,
  41717. const int newCaretPos_)
  41718. : owner (owner_),
  41719. text (text_),
  41720. insertIndex (insertIndex_),
  41721. oldCaretPos (oldCaretPos_),
  41722. newCaretPos (newCaretPos_),
  41723. font (font_),
  41724. colour (colour_)
  41725. {
  41726. }
  41727. ~InsertAction()
  41728. {
  41729. }
  41730. bool perform()
  41731. {
  41732. owner.insert (text, insertIndex, font, colour, 0, newCaretPos);
  41733. return true;
  41734. }
  41735. bool undo()
  41736. {
  41737. owner.remove (Range<int> (insertIndex, insertIndex + text.length()), 0, oldCaretPos);
  41738. return true;
  41739. }
  41740. int getSizeInUnits()
  41741. {
  41742. return text.length() + 16;
  41743. }
  41744. };
  41745. class TextEditor::RemoveAction : public UndoableAction
  41746. {
  41747. TextEditor& owner;
  41748. const Range<int> range;
  41749. const int oldCaretPos, newCaretPos;
  41750. Array <UniformTextSection*> removedSections;
  41751. RemoveAction (const RemoveAction&);
  41752. RemoveAction& operator= (const RemoveAction&);
  41753. public:
  41754. RemoveAction (TextEditor& owner_,
  41755. const Range<int> range_,
  41756. const int oldCaretPos_,
  41757. const int newCaretPos_,
  41758. const Array <UniformTextSection*>& removedSections_)
  41759. : owner (owner_),
  41760. range (range_),
  41761. oldCaretPos (oldCaretPos_),
  41762. newCaretPos (newCaretPos_),
  41763. removedSections (removedSections_)
  41764. {
  41765. }
  41766. ~RemoveAction()
  41767. {
  41768. for (int i = removedSections.size(); --i >= 0;)
  41769. {
  41770. UniformTextSection* const section = removedSections.getUnchecked (i);
  41771. section->clear();
  41772. delete section;
  41773. }
  41774. }
  41775. bool perform()
  41776. {
  41777. owner.remove (range, 0, newCaretPos);
  41778. return true;
  41779. }
  41780. bool undo()
  41781. {
  41782. owner.reinsert (range.getStart(), removedSections);
  41783. owner.moveCursorTo (oldCaretPos, false);
  41784. return true;
  41785. }
  41786. int getSizeInUnits()
  41787. {
  41788. int n = 0;
  41789. for (int i = removedSections.size(); --i >= 0;)
  41790. n += removedSections.getUnchecked (i)->getTotalLength();
  41791. return n + 16;
  41792. }
  41793. };
  41794. class TextEditor::TextHolderComponent : public Component,
  41795. public Timer,
  41796. public Value::Listener
  41797. {
  41798. public:
  41799. TextHolderComponent (TextEditor& owner_)
  41800. : owner (owner_)
  41801. {
  41802. setWantsKeyboardFocus (false);
  41803. setInterceptsMouseClicks (false, true);
  41804. owner.getTextValue().addListener (this);
  41805. }
  41806. ~TextHolderComponent()
  41807. {
  41808. owner.getTextValue().removeListener (this);
  41809. }
  41810. void paint (Graphics& g)
  41811. {
  41812. owner.drawContent (g);
  41813. }
  41814. void timerCallback()
  41815. {
  41816. owner.timerCallbackInt();
  41817. }
  41818. const MouseCursor getMouseCursor()
  41819. {
  41820. return owner.getMouseCursor();
  41821. }
  41822. void valueChanged (Value&)
  41823. {
  41824. owner.textWasChangedByValue();
  41825. }
  41826. private:
  41827. TextEditor& owner;
  41828. TextHolderComponent (const TextHolderComponent&);
  41829. TextHolderComponent& operator= (const TextHolderComponent&);
  41830. };
  41831. class TextEditorViewport : public Viewport
  41832. {
  41833. public:
  41834. TextEditorViewport (TextEditor* const owner_)
  41835. : owner (owner_),
  41836. lastWordWrapWidth (0)
  41837. {
  41838. }
  41839. ~TextEditorViewport()
  41840. {
  41841. }
  41842. void visibleAreaChanged (int, int, int, int)
  41843. {
  41844. const float wordWrapWidth = owner->getWordWrapWidth();
  41845. if (wordWrapWidth != lastWordWrapWidth)
  41846. {
  41847. lastWordWrapWidth = wordWrapWidth;
  41848. owner->updateTextHolderSize();
  41849. }
  41850. }
  41851. private:
  41852. TextEditor* const owner;
  41853. float lastWordWrapWidth;
  41854. TextEditorViewport (const TextEditorViewport&);
  41855. TextEditorViewport& operator= (const TextEditorViewport&);
  41856. };
  41857. namespace TextEditorDefs
  41858. {
  41859. const int flashSpeedIntervalMs = 380;
  41860. const int textChangeMessageId = 0x10003001;
  41861. const int returnKeyMessageId = 0x10003002;
  41862. const int escapeKeyMessageId = 0x10003003;
  41863. const int focusLossMessageId = 0x10003004;
  41864. const int maxActionsPerTransaction = 100;
  41865. }
  41866. TextEditor::TextEditor (const String& name,
  41867. const juce_wchar passwordCharacter_)
  41868. : Component (name),
  41869. borderSize (1, 1, 1, 3),
  41870. readOnly (false),
  41871. multiline (false),
  41872. wordWrap (false),
  41873. returnKeyStartsNewLine (false),
  41874. caretVisible (true),
  41875. popupMenuEnabled (true),
  41876. selectAllTextWhenFocused (false),
  41877. scrollbarVisible (true),
  41878. wasFocused (false),
  41879. caretFlashState (true),
  41880. keepCursorOnScreen (true),
  41881. tabKeyUsed (false),
  41882. menuActive (false),
  41883. valueTextNeedsUpdating (false),
  41884. cursorX (0),
  41885. cursorY (0),
  41886. cursorHeight (0),
  41887. maxTextLength (0),
  41888. leftIndent (4),
  41889. topIndent (4),
  41890. lastTransactionTime (0),
  41891. currentFont (14.0f),
  41892. totalNumChars (0),
  41893. caretPosition (0),
  41894. passwordCharacter (passwordCharacter_),
  41895. dragType (notDragging)
  41896. {
  41897. setOpaque (true);
  41898. addAndMakeVisible (viewport = new TextEditorViewport (this));
  41899. viewport->setViewedComponent (textHolder = new TextHolderComponent (*this));
  41900. viewport->setWantsKeyboardFocus (false);
  41901. viewport->setScrollBarsShown (false, false);
  41902. setMouseCursor (MouseCursor::IBeamCursor);
  41903. setWantsKeyboardFocus (true);
  41904. }
  41905. TextEditor::~TextEditor()
  41906. {
  41907. textValue.referTo (Value());
  41908. clearInternal (0);
  41909. viewport = 0;
  41910. textHolder = 0;
  41911. }
  41912. void TextEditor::newTransaction()
  41913. {
  41914. lastTransactionTime = Time::getApproximateMillisecondCounter();
  41915. undoManager.beginNewTransaction();
  41916. }
  41917. void TextEditor::doUndoRedo (const bool isRedo)
  41918. {
  41919. if (! isReadOnly())
  41920. {
  41921. if (isRedo ? undoManager.redo()
  41922. : undoManager.undo())
  41923. {
  41924. scrollToMakeSureCursorIsVisible();
  41925. repaint();
  41926. textChanged();
  41927. }
  41928. }
  41929. }
  41930. void TextEditor::setMultiLine (const bool shouldBeMultiLine,
  41931. const bool shouldWordWrap)
  41932. {
  41933. multiline = shouldBeMultiLine;
  41934. wordWrap = shouldWordWrap && shouldBeMultiLine;
  41935. setScrollbarsShown (scrollbarVisible);
  41936. viewport->setViewPosition (0, 0);
  41937. resized();
  41938. scrollToMakeSureCursorIsVisible();
  41939. }
  41940. bool TextEditor::isMultiLine() const
  41941. {
  41942. return multiline;
  41943. }
  41944. void TextEditor::setScrollbarsShown (bool enabled)
  41945. {
  41946. scrollbarVisible = enabled;
  41947. enabled = enabled && isMultiLine();
  41948. viewport->setScrollBarsShown (enabled, enabled);
  41949. }
  41950. void TextEditor::setReadOnly (const bool shouldBeReadOnly)
  41951. {
  41952. readOnly = shouldBeReadOnly;
  41953. enablementChanged();
  41954. }
  41955. bool TextEditor::isReadOnly() const
  41956. {
  41957. return readOnly || ! isEnabled();
  41958. }
  41959. bool TextEditor::isTextInputActive() const
  41960. {
  41961. return ! isReadOnly();
  41962. }
  41963. void TextEditor::setReturnKeyStartsNewLine (const bool shouldStartNewLine)
  41964. {
  41965. returnKeyStartsNewLine = shouldStartNewLine;
  41966. }
  41967. void TextEditor::setTabKeyUsedAsCharacter (const bool shouldTabKeyBeUsed)
  41968. {
  41969. tabKeyUsed = shouldTabKeyBeUsed;
  41970. }
  41971. void TextEditor::setPopupMenuEnabled (const bool b)
  41972. {
  41973. popupMenuEnabled = b;
  41974. }
  41975. void TextEditor::setSelectAllWhenFocused (const bool b)
  41976. {
  41977. selectAllTextWhenFocused = b;
  41978. }
  41979. const Font TextEditor::getFont() const
  41980. {
  41981. return currentFont;
  41982. }
  41983. void TextEditor::setFont (const Font& newFont)
  41984. {
  41985. currentFont = newFont;
  41986. scrollToMakeSureCursorIsVisible();
  41987. }
  41988. void TextEditor::applyFontToAllText (const Font& newFont)
  41989. {
  41990. currentFont = newFont;
  41991. const Colour overallColour (findColour (textColourId));
  41992. for (int i = sections.size(); --i >= 0;)
  41993. {
  41994. UniformTextSection* const uts = sections.getUnchecked (i);
  41995. uts->setFont (newFont, passwordCharacter);
  41996. uts->colour = overallColour;
  41997. }
  41998. coalesceSimilarSections();
  41999. updateTextHolderSize();
  42000. scrollToMakeSureCursorIsVisible();
  42001. repaint();
  42002. }
  42003. void TextEditor::colourChanged()
  42004. {
  42005. setOpaque (findColour (backgroundColourId).isOpaque());
  42006. repaint();
  42007. }
  42008. void TextEditor::setCaretVisible (const bool shouldCaretBeVisible)
  42009. {
  42010. caretVisible = shouldCaretBeVisible;
  42011. if (shouldCaretBeVisible)
  42012. textHolder->startTimer (TextEditorDefs::flashSpeedIntervalMs);
  42013. setMouseCursor (shouldCaretBeVisible ? MouseCursor::IBeamCursor
  42014. : MouseCursor::NormalCursor);
  42015. }
  42016. void TextEditor::setInputRestrictions (const int maxLen,
  42017. const String& chars)
  42018. {
  42019. maxTextLength = jmax (0, maxLen);
  42020. allowedCharacters = chars;
  42021. }
  42022. void TextEditor::setTextToShowWhenEmpty (const String& text, const Colour& colourToUse)
  42023. {
  42024. textToShowWhenEmpty = text;
  42025. colourForTextWhenEmpty = colourToUse;
  42026. }
  42027. void TextEditor::setPasswordCharacter (const juce_wchar newPasswordCharacter)
  42028. {
  42029. if (passwordCharacter != newPasswordCharacter)
  42030. {
  42031. passwordCharacter = newPasswordCharacter;
  42032. resized();
  42033. repaint();
  42034. }
  42035. }
  42036. void TextEditor::setScrollBarThickness (const int newThicknessPixels)
  42037. {
  42038. viewport->setScrollBarThickness (newThicknessPixels);
  42039. }
  42040. void TextEditor::setScrollBarButtonVisibility (const bool buttonsVisible)
  42041. {
  42042. viewport->setScrollBarButtonVisibility (buttonsVisible);
  42043. }
  42044. void TextEditor::clear()
  42045. {
  42046. clearInternal (0);
  42047. updateTextHolderSize();
  42048. undoManager.clearUndoHistory();
  42049. }
  42050. void TextEditor::setText (const String& newText,
  42051. const bool sendTextChangeMessage)
  42052. {
  42053. const int newLength = newText.length();
  42054. if (newLength != getTotalNumChars() || getText() != newText)
  42055. {
  42056. const int oldCursorPos = caretPosition;
  42057. const bool cursorWasAtEnd = oldCursorPos >= getTotalNumChars();
  42058. clearInternal (0);
  42059. insert (newText, 0, currentFont, findColour (textColourId), 0, caretPosition);
  42060. // if you're adding text with line-feeds to a single-line text editor, it
  42061. // ain't gonna look right!
  42062. jassert (multiline || ! newText.containsAnyOf ("\r\n"));
  42063. if (cursorWasAtEnd && ! isMultiLine())
  42064. moveCursorTo (getTotalNumChars(), false);
  42065. else
  42066. moveCursorTo (oldCursorPos, false);
  42067. if (sendTextChangeMessage)
  42068. textChanged();
  42069. repaint();
  42070. }
  42071. updateTextHolderSize();
  42072. scrollToMakeSureCursorIsVisible();
  42073. undoManager.clearUndoHistory();
  42074. }
  42075. Value& TextEditor::getTextValue()
  42076. {
  42077. if (valueTextNeedsUpdating)
  42078. {
  42079. valueTextNeedsUpdating = false;
  42080. textValue = getText();
  42081. }
  42082. return textValue;
  42083. }
  42084. void TextEditor::textWasChangedByValue()
  42085. {
  42086. if (textValue.getValueSource().getReferenceCount() > 1)
  42087. setText (textValue.getValue());
  42088. }
  42089. void TextEditor::textChanged()
  42090. {
  42091. updateTextHolderSize();
  42092. postCommandMessage (TextEditorDefs::textChangeMessageId);
  42093. if (textValue.getValueSource().getReferenceCount() > 1)
  42094. {
  42095. valueTextNeedsUpdating = false;
  42096. textValue = getText();
  42097. }
  42098. }
  42099. void TextEditor::returnPressed()
  42100. {
  42101. postCommandMessage (TextEditorDefs::returnKeyMessageId);
  42102. }
  42103. void TextEditor::escapePressed()
  42104. {
  42105. postCommandMessage (TextEditorDefs::escapeKeyMessageId);
  42106. }
  42107. void TextEditor::addListener (TextEditorListener* const newListener)
  42108. {
  42109. listeners.add (newListener);
  42110. }
  42111. void TextEditor::removeListener (TextEditorListener* const listenerToRemove)
  42112. {
  42113. listeners.remove (listenerToRemove);
  42114. }
  42115. void TextEditor::timerCallbackInt()
  42116. {
  42117. const bool newState = (! caretFlashState) && ! isCurrentlyBlockedByAnotherModalComponent();
  42118. if (caretFlashState != newState)
  42119. {
  42120. caretFlashState = newState;
  42121. if (caretFlashState)
  42122. wasFocused = true;
  42123. if (caretVisible
  42124. && hasKeyboardFocus (false)
  42125. && ! isReadOnly())
  42126. {
  42127. repaintCaret();
  42128. }
  42129. }
  42130. const unsigned int now = Time::getApproximateMillisecondCounter();
  42131. if (now > lastTransactionTime + 200)
  42132. newTransaction();
  42133. }
  42134. void TextEditor::repaintCaret()
  42135. {
  42136. if (! findColour (caretColourId).isTransparent())
  42137. repaint (borderSize.getLeft() + textHolder->getX() + leftIndent + roundToInt (cursorX) - 1,
  42138. borderSize.getTop() + textHolder->getY() + topIndent + roundToInt (cursorY) - 1,
  42139. 4,
  42140. roundToInt (cursorHeight) + 2);
  42141. }
  42142. void TextEditor::repaintText (const Range<int>& range)
  42143. {
  42144. if (! range.isEmpty())
  42145. {
  42146. float x = 0, y = 0, lh = currentFont.getHeight();
  42147. const float wordWrapWidth = getWordWrapWidth();
  42148. if (wordWrapWidth > 0)
  42149. {
  42150. Iterator i (sections, wordWrapWidth, passwordCharacter);
  42151. i.getCharPosition (range.getStart(), x, y, lh);
  42152. const int y1 = (int) y;
  42153. int y2;
  42154. if (range.getEnd() >= getTotalNumChars())
  42155. {
  42156. y2 = textHolder->getHeight();
  42157. }
  42158. else
  42159. {
  42160. i.getCharPosition (range.getEnd(), x, y, lh);
  42161. y2 = (int) (y + lh * 2.0f);
  42162. }
  42163. textHolder->repaint (0, y1, textHolder->getWidth(), y2 - y1);
  42164. }
  42165. }
  42166. }
  42167. void TextEditor::moveCaret (int newCaretPos)
  42168. {
  42169. if (newCaretPos < 0)
  42170. newCaretPos = 0;
  42171. else if (newCaretPos > getTotalNumChars())
  42172. newCaretPos = getTotalNumChars();
  42173. if (newCaretPos != getCaretPosition())
  42174. {
  42175. repaintCaret();
  42176. caretFlashState = true;
  42177. caretPosition = newCaretPos;
  42178. textHolder->startTimer (TextEditorDefs::flashSpeedIntervalMs);
  42179. scrollToMakeSureCursorIsVisible();
  42180. repaintCaret();
  42181. }
  42182. }
  42183. void TextEditor::setCaretPosition (const int newIndex)
  42184. {
  42185. moveCursorTo (newIndex, false);
  42186. }
  42187. int TextEditor::getCaretPosition() const
  42188. {
  42189. return caretPosition;
  42190. }
  42191. void TextEditor::scrollEditorToPositionCaret (const int desiredCaretX,
  42192. const int desiredCaretY)
  42193. {
  42194. updateCaretPosition();
  42195. int vx = roundToInt (cursorX) - desiredCaretX;
  42196. int vy = roundToInt (cursorY) - desiredCaretY;
  42197. if (desiredCaretX < jmax (1, proportionOfWidth (0.05f)))
  42198. {
  42199. vx += desiredCaretX - proportionOfWidth (0.2f);
  42200. }
  42201. else if (desiredCaretX > jmax (0, viewport->getMaximumVisibleWidth() - (wordWrap ? 2 : 10)))
  42202. {
  42203. vx += desiredCaretX + (isMultiLine() ? proportionOfWidth (0.2f) : 10) - viewport->getMaximumVisibleWidth();
  42204. }
  42205. vx = jlimit (0, jmax (0, textHolder->getWidth() + 8 - viewport->getMaximumVisibleWidth()), vx);
  42206. if (! isMultiLine())
  42207. {
  42208. vy = viewport->getViewPositionY();
  42209. }
  42210. else
  42211. {
  42212. vy = jlimit (0, jmax (0, textHolder->getHeight() - viewport->getMaximumVisibleHeight()), vy);
  42213. const int curH = roundToInt (cursorHeight);
  42214. if (desiredCaretY < 0)
  42215. {
  42216. vy = jmax (0, desiredCaretY + vy);
  42217. }
  42218. else if (desiredCaretY > jmax (0, viewport->getMaximumVisibleHeight() - topIndent - curH))
  42219. {
  42220. vy += desiredCaretY + 2 + curH + topIndent - viewport->getMaximumVisibleHeight();
  42221. }
  42222. }
  42223. viewport->setViewPosition (vx, vy);
  42224. }
  42225. const Rectangle<int> TextEditor::getCaretRectangle()
  42226. {
  42227. updateCaretPosition();
  42228. return Rectangle<int> (roundToInt (cursorX) - viewport->getX(),
  42229. roundToInt (cursorY) - viewport->getY(),
  42230. 1, roundToInt (cursorHeight));
  42231. }
  42232. float TextEditor::getWordWrapWidth() const
  42233. {
  42234. return (wordWrap) ? (float) (viewport->getMaximumVisibleWidth() - leftIndent - leftIndent / 2)
  42235. : 1.0e10f;
  42236. }
  42237. void TextEditor::updateTextHolderSize()
  42238. {
  42239. const float wordWrapWidth = getWordWrapWidth();
  42240. if (wordWrapWidth > 0)
  42241. {
  42242. float maxWidth = 0.0f;
  42243. Iterator i (sections, wordWrapWidth, passwordCharacter);
  42244. while (i.next())
  42245. maxWidth = jmax (maxWidth, i.atomRight);
  42246. const int w = leftIndent + roundToInt (maxWidth);
  42247. const int h = topIndent + roundToInt (jmax (i.lineY + i.lineHeight,
  42248. currentFont.getHeight()));
  42249. textHolder->setSize (w + 1, h + 1);
  42250. }
  42251. }
  42252. int TextEditor::getTextWidth() const
  42253. {
  42254. return textHolder->getWidth();
  42255. }
  42256. int TextEditor::getTextHeight() const
  42257. {
  42258. return textHolder->getHeight();
  42259. }
  42260. void TextEditor::setIndents (const int newLeftIndent,
  42261. const int newTopIndent)
  42262. {
  42263. leftIndent = newLeftIndent;
  42264. topIndent = newTopIndent;
  42265. }
  42266. void TextEditor::setBorder (const BorderSize& border)
  42267. {
  42268. borderSize = border;
  42269. resized();
  42270. }
  42271. const BorderSize TextEditor::getBorder() const
  42272. {
  42273. return borderSize;
  42274. }
  42275. void TextEditor::setScrollToShowCursor (const bool shouldScrollToShowCursor)
  42276. {
  42277. keepCursorOnScreen = shouldScrollToShowCursor;
  42278. }
  42279. void TextEditor::updateCaretPosition()
  42280. {
  42281. cursorHeight = currentFont.getHeight(); // (in case the text is empty and the call below doesn't set this value)
  42282. getCharPosition (caretPosition, cursorX, cursorY, cursorHeight);
  42283. }
  42284. void TextEditor::scrollToMakeSureCursorIsVisible()
  42285. {
  42286. updateCaretPosition();
  42287. if (keepCursorOnScreen)
  42288. {
  42289. int x = viewport->getViewPositionX();
  42290. int y = viewport->getViewPositionY();
  42291. const int relativeCursorX = roundToInt (cursorX) - x;
  42292. const int relativeCursorY = roundToInt (cursorY) - y;
  42293. if (relativeCursorX < jmax (1, proportionOfWidth (0.05f)))
  42294. {
  42295. x += relativeCursorX - proportionOfWidth (0.2f);
  42296. }
  42297. else if (relativeCursorX > jmax (0, viewport->getMaximumVisibleWidth() - (wordWrap ? 2 : 10)))
  42298. {
  42299. x += relativeCursorX + (isMultiLine() ? proportionOfWidth (0.2f) : 10) - viewport->getMaximumVisibleWidth();
  42300. }
  42301. x = jlimit (0, jmax (0, textHolder->getWidth() + 8 - viewport->getMaximumVisibleWidth()), x);
  42302. if (! isMultiLine())
  42303. {
  42304. y = (getHeight() - textHolder->getHeight() - topIndent) / -2;
  42305. }
  42306. else
  42307. {
  42308. const int curH = roundToInt (cursorHeight);
  42309. if (relativeCursorY < 0)
  42310. {
  42311. y = jmax (0, relativeCursorY + y);
  42312. }
  42313. else if (relativeCursorY > jmax (0, viewport->getMaximumVisibleHeight() - topIndent - curH))
  42314. {
  42315. y += relativeCursorY + 2 + curH + topIndent - viewport->getMaximumVisibleHeight();
  42316. }
  42317. }
  42318. viewport->setViewPosition (x, y);
  42319. }
  42320. }
  42321. void TextEditor::moveCursorTo (const int newPosition,
  42322. const bool isSelecting)
  42323. {
  42324. if (isSelecting)
  42325. {
  42326. moveCaret (newPosition);
  42327. const Range<int> oldSelection (selection);
  42328. if (dragType == notDragging)
  42329. {
  42330. if (abs (getCaretPosition() - selection.getStart()) < abs (getCaretPosition() - selection.getEnd()))
  42331. dragType = draggingSelectionStart;
  42332. else
  42333. dragType = draggingSelectionEnd;
  42334. }
  42335. if (dragType == draggingSelectionStart)
  42336. {
  42337. if (getCaretPosition() >= selection.getEnd())
  42338. dragType = draggingSelectionEnd;
  42339. selection = Range<int>::between (getCaretPosition(), selection.getEnd());
  42340. }
  42341. else
  42342. {
  42343. if (getCaretPosition() < selection.getStart())
  42344. dragType = draggingSelectionStart;
  42345. selection = Range<int>::between (getCaretPosition(), selection.getStart());
  42346. }
  42347. repaintText (selection.getUnionWith (oldSelection));
  42348. }
  42349. else
  42350. {
  42351. dragType = notDragging;
  42352. repaintText (selection);
  42353. moveCaret (newPosition);
  42354. selection = Range<int>::emptyRange (getCaretPosition());
  42355. }
  42356. }
  42357. int TextEditor::getTextIndexAt (const int x,
  42358. const int y)
  42359. {
  42360. return indexAtPosition ((float) (x + viewport->getViewPositionX() - leftIndent),
  42361. (float) (y + viewport->getViewPositionY() - topIndent));
  42362. }
  42363. void TextEditor::insertTextAtCaret (const String& newText_)
  42364. {
  42365. String newText (newText_);
  42366. if (allowedCharacters.isNotEmpty())
  42367. newText = newText.retainCharacters (allowedCharacters);
  42368. if ((! returnKeyStartsNewLine) && newText == "\n")
  42369. {
  42370. returnPressed();
  42371. return;
  42372. }
  42373. if (! isMultiLine())
  42374. newText = newText.replaceCharacters ("\r\n", " ");
  42375. else
  42376. newText = newText.replace ("\r\n", "\n");
  42377. const int newCaretPos = selection.getStart() + newText.length();
  42378. const int insertIndex = selection.getStart();
  42379. remove (selection, getUndoManager(),
  42380. newText.isNotEmpty() ? newCaretPos - 1 : newCaretPos);
  42381. if (maxTextLength > 0)
  42382. newText = newText.substring (0, maxTextLength - getTotalNumChars());
  42383. if (newText.isNotEmpty())
  42384. insert (newText,
  42385. insertIndex,
  42386. currentFont,
  42387. findColour (textColourId),
  42388. getUndoManager(),
  42389. newCaretPos);
  42390. textChanged();
  42391. }
  42392. void TextEditor::setHighlightedRegion (const Range<int>& newSelection)
  42393. {
  42394. moveCursorTo (newSelection.getStart(), false);
  42395. moveCursorTo (newSelection.getEnd(), true);
  42396. }
  42397. void TextEditor::copy()
  42398. {
  42399. if (passwordCharacter == 0)
  42400. {
  42401. const String selectedText (getHighlightedText());
  42402. if (selectedText.isNotEmpty())
  42403. SystemClipboard::copyTextToClipboard (selectedText);
  42404. }
  42405. }
  42406. void TextEditor::paste()
  42407. {
  42408. if (! isReadOnly())
  42409. {
  42410. const String clip (SystemClipboard::getTextFromClipboard());
  42411. if (clip.isNotEmpty())
  42412. insertTextAtCaret (clip);
  42413. }
  42414. }
  42415. void TextEditor::cut()
  42416. {
  42417. if (! isReadOnly())
  42418. {
  42419. moveCaret (selection.getEnd());
  42420. insertTextAtCaret (String::empty);
  42421. }
  42422. }
  42423. void TextEditor::drawContent (Graphics& g)
  42424. {
  42425. const float wordWrapWidth = getWordWrapWidth();
  42426. if (wordWrapWidth > 0)
  42427. {
  42428. g.setOrigin (leftIndent, topIndent);
  42429. const Rectangle<int> clip (g.getClipBounds());
  42430. Colour selectedTextColour;
  42431. Iterator i (sections, wordWrapWidth, passwordCharacter);
  42432. while (i.lineY + 200.0 < clip.getY() && i.next())
  42433. {}
  42434. if (! selection.isEmpty())
  42435. {
  42436. g.setColour (findColour (highlightColourId)
  42437. .withMultipliedAlpha (hasKeyboardFocus (true) ? 1.0f : 0.5f));
  42438. selectedTextColour = findColour (highlightedTextColourId);
  42439. Iterator i2 (i);
  42440. while (i2.next() && i2.lineY < clip.getBottom())
  42441. {
  42442. if (i2.lineY + i2.lineHeight >= clip.getY()
  42443. && selection.intersects (Range<int> (i2.indexInText, i2.indexInText + i2.atom->numChars)))
  42444. {
  42445. i2.drawSelection (g, selection);
  42446. }
  42447. }
  42448. }
  42449. const UniformTextSection* lastSection = 0;
  42450. while (i.next() && i.lineY < clip.getBottom())
  42451. {
  42452. if (i.lineY + i.lineHeight >= clip.getY())
  42453. {
  42454. if (selection.intersects (Range<int> (i.indexInText, i.indexInText + i.atom->numChars)))
  42455. {
  42456. i.drawSelectedText (g, selection, selectedTextColour);
  42457. lastSection = 0;
  42458. }
  42459. else
  42460. {
  42461. i.draw (g, lastSection);
  42462. }
  42463. }
  42464. }
  42465. }
  42466. }
  42467. void TextEditor::paint (Graphics& g)
  42468. {
  42469. getLookAndFeel().fillTextEditorBackground (g, getWidth(), getHeight(), *this);
  42470. }
  42471. void TextEditor::paintOverChildren (Graphics& g)
  42472. {
  42473. if (caretFlashState
  42474. && hasKeyboardFocus (false)
  42475. && caretVisible
  42476. && ! isReadOnly())
  42477. {
  42478. g.setColour (findColour (caretColourId));
  42479. g.fillRect (borderSize.getLeft() + textHolder->getX() + leftIndent + cursorX,
  42480. borderSize.getTop() + textHolder->getY() + topIndent + cursorY,
  42481. 2.0f, cursorHeight);
  42482. }
  42483. if (textToShowWhenEmpty.isNotEmpty()
  42484. && (! hasKeyboardFocus (false))
  42485. && getTotalNumChars() == 0)
  42486. {
  42487. g.setColour (colourForTextWhenEmpty);
  42488. g.setFont (getFont());
  42489. if (isMultiLine())
  42490. {
  42491. g.drawText (textToShowWhenEmpty,
  42492. 0, 0, getWidth(), getHeight(),
  42493. Justification::centred, true);
  42494. }
  42495. else
  42496. {
  42497. g.drawText (textToShowWhenEmpty,
  42498. leftIndent, topIndent,
  42499. viewport->getWidth() - leftIndent,
  42500. viewport->getHeight() - topIndent,
  42501. Justification::centredLeft, true);
  42502. }
  42503. }
  42504. getLookAndFeel().drawTextEditorOutline (g, getWidth(), getHeight(), *this);
  42505. }
  42506. void TextEditor::mouseDown (const MouseEvent& e)
  42507. {
  42508. beginDragAutoRepeat (100);
  42509. newTransaction();
  42510. if (wasFocused || ! selectAllTextWhenFocused)
  42511. {
  42512. if (! (popupMenuEnabled && e.mods.isPopupMenu()))
  42513. {
  42514. moveCursorTo (getTextIndexAt (e.x, e.y),
  42515. e.mods.isShiftDown());
  42516. }
  42517. else
  42518. {
  42519. PopupMenu m;
  42520. m.setLookAndFeel (&getLookAndFeel());
  42521. addPopupMenuItems (m, &e);
  42522. menuActive = true;
  42523. const int result = m.show();
  42524. menuActive = false;
  42525. if (result != 0)
  42526. performPopupMenuAction (result);
  42527. }
  42528. }
  42529. }
  42530. void TextEditor::mouseDrag (const MouseEvent& e)
  42531. {
  42532. if (wasFocused || ! selectAllTextWhenFocused)
  42533. {
  42534. if (! (popupMenuEnabled && e.mods.isPopupMenu()))
  42535. {
  42536. moveCursorTo (getTextIndexAt (e.x, e.y), true);
  42537. }
  42538. }
  42539. }
  42540. void TextEditor::mouseUp (const MouseEvent& e)
  42541. {
  42542. newTransaction();
  42543. textHolder->startTimer (TextEditorDefs::flashSpeedIntervalMs);
  42544. if (wasFocused || ! selectAllTextWhenFocused)
  42545. {
  42546. if (e.mouseWasClicked() && ! (popupMenuEnabled && e.mods.isPopupMenu()))
  42547. {
  42548. moveCaret (getTextIndexAt (e.x, e.y));
  42549. }
  42550. }
  42551. wasFocused = true;
  42552. }
  42553. void TextEditor::mouseDoubleClick (const MouseEvent& e)
  42554. {
  42555. int tokenEnd = getTextIndexAt (e.x, e.y);
  42556. int tokenStart = tokenEnd;
  42557. if (e.getNumberOfClicks() > 3)
  42558. {
  42559. tokenStart = 0;
  42560. tokenEnd = getTotalNumChars();
  42561. }
  42562. else
  42563. {
  42564. const String t (getText());
  42565. const int totalLength = getTotalNumChars();
  42566. while (tokenEnd < totalLength)
  42567. {
  42568. if (CharacterFunctions::isLetterOrDigit (t [tokenEnd]))
  42569. ++tokenEnd;
  42570. else
  42571. break;
  42572. }
  42573. tokenStart = tokenEnd;
  42574. while (tokenStart > 0)
  42575. {
  42576. if (CharacterFunctions::isLetterOrDigit (t [tokenStart - 1]))
  42577. --tokenStart;
  42578. else
  42579. break;
  42580. }
  42581. if (e.getNumberOfClicks() > 2)
  42582. {
  42583. while (tokenEnd < totalLength)
  42584. {
  42585. if (t [tokenEnd] != '\r' && t [tokenEnd] != '\n')
  42586. ++tokenEnd;
  42587. else
  42588. break;
  42589. }
  42590. while (tokenStart > 0)
  42591. {
  42592. if (t [tokenStart - 1] != '\r' && t [tokenStart - 1] != '\n')
  42593. --tokenStart;
  42594. else
  42595. break;
  42596. }
  42597. }
  42598. }
  42599. moveCursorTo (tokenEnd, false);
  42600. moveCursorTo (tokenStart, true);
  42601. }
  42602. void TextEditor::mouseWheelMove (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY)
  42603. {
  42604. if (! viewport->useMouseWheelMoveIfNeeded (e, wheelIncrementX, wheelIncrementY))
  42605. Component::mouseWheelMove (e, wheelIncrementX, wheelIncrementY);
  42606. }
  42607. bool TextEditor::keyPressed (const KeyPress& key)
  42608. {
  42609. if (isReadOnly() && key != KeyPress ('c', ModifierKeys::commandModifier, 0))
  42610. return false;
  42611. const bool moveInWholeWordSteps = key.getModifiers().isCtrlDown() || key.getModifiers().isAltDown();
  42612. if (key.isKeyCode (KeyPress::leftKey)
  42613. || key.isKeyCode (KeyPress::upKey))
  42614. {
  42615. newTransaction();
  42616. int newPos;
  42617. if (isMultiLine() && key.isKeyCode (KeyPress::upKey))
  42618. newPos = indexAtPosition (cursorX, cursorY - 1);
  42619. else if (moveInWholeWordSteps)
  42620. newPos = findWordBreakBefore (getCaretPosition());
  42621. else
  42622. newPos = getCaretPosition() - 1;
  42623. moveCursorTo (newPos, key.getModifiers().isShiftDown());
  42624. }
  42625. else if (key.isKeyCode (KeyPress::rightKey)
  42626. || key.isKeyCode (KeyPress::downKey))
  42627. {
  42628. newTransaction();
  42629. int newPos;
  42630. if (isMultiLine() && key.isKeyCode (KeyPress::downKey))
  42631. newPos = indexAtPosition (cursorX, cursorY + cursorHeight + 1);
  42632. else if (moveInWholeWordSteps)
  42633. newPos = findWordBreakAfter (getCaretPosition());
  42634. else
  42635. newPos = getCaretPosition() + 1;
  42636. moveCursorTo (newPos, key.getModifiers().isShiftDown());
  42637. }
  42638. else if (key.isKeyCode (KeyPress::pageDownKey) && isMultiLine())
  42639. {
  42640. newTransaction();
  42641. moveCursorTo (indexAtPosition (cursorX, cursorY + cursorHeight + viewport->getViewHeight()),
  42642. key.getModifiers().isShiftDown());
  42643. }
  42644. else if (key.isKeyCode (KeyPress::pageUpKey) && isMultiLine())
  42645. {
  42646. newTransaction();
  42647. moveCursorTo (indexAtPosition (cursorX, cursorY - viewport->getViewHeight()),
  42648. key.getModifiers().isShiftDown());
  42649. }
  42650. else if (key.isKeyCode (KeyPress::homeKey))
  42651. {
  42652. newTransaction();
  42653. if (isMultiLine() && ! moveInWholeWordSteps)
  42654. moveCursorTo (indexAtPosition (0.0f, cursorY),
  42655. key.getModifiers().isShiftDown());
  42656. else
  42657. moveCursorTo (0, key.getModifiers().isShiftDown());
  42658. }
  42659. else if (key.isKeyCode (KeyPress::endKey))
  42660. {
  42661. newTransaction();
  42662. if (isMultiLine() && ! moveInWholeWordSteps)
  42663. moveCursorTo (indexAtPosition ((float) textHolder->getWidth(), cursorY),
  42664. key.getModifiers().isShiftDown());
  42665. else
  42666. moveCursorTo (getTotalNumChars(), key.getModifiers().isShiftDown());
  42667. }
  42668. else if (key.isKeyCode (KeyPress::backspaceKey))
  42669. {
  42670. if (moveInWholeWordSteps)
  42671. {
  42672. moveCursorTo (findWordBreakBefore (getCaretPosition()), true);
  42673. }
  42674. else
  42675. {
  42676. if (selection.isEmpty() && selection.getStart() > 0)
  42677. selection.setStart (selection.getEnd() - 1);
  42678. }
  42679. cut();
  42680. }
  42681. else if (key.isKeyCode (KeyPress::deleteKey))
  42682. {
  42683. if (key.getModifiers().isShiftDown())
  42684. copy();
  42685. if (selection.isEmpty() && selection.getStart() < getTotalNumChars())
  42686. selection.setEnd (selection.getStart() + 1);
  42687. cut();
  42688. }
  42689. else if (key == KeyPress ('c', ModifierKeys::commandModifier, 0)
  42690. || key == KeyPress (KeyPress::insertKey, ModifierKeys::ctrlModifier, 0))
  42691. {
  42692. newTransaction();
  42693. copy();
  42694. }
  42695. else if (key == KeyPress ('x', ModifierKeys::commandModifier, 0))
  42696. {
  42697. newTransaction();
  42698. copy();
  42699. cut();
  42700. }
  42701. else if (key == KeyPress ('v', ModifierKeys::commandModifier, 0)
  42702. || key == KeyPress (KeyPress::insertKey, ModifierKeys::shiftModifier, 0))
  42703. {
  42704. newTransaction();
  42705. paste();
  42706. }
  42707. else if (key == KeyPress ('z', ModifierKeys::commandModifier, 0))
  42708. {
  42709. newTransaction();
  42710. doUndoRedo (false);
  42711. }
  42712. else if (key == KeyPress ('y', ModifierKeys::commandModifier, 0))
  42713. {
  42714. newTransaction();
  42715. doUndoRedo (true);
  42716. }
  42717. else if (key == KeyPress ('a', ModifierKeys::commandModifier, 0))
  42718. {
  42719. newTransaction();
  42720. moveCursorTo (getTotalNumChars(), false);
  42721. moveCursorTo (0, true);
  42722. }
  42723. else if (key == KeyPress::returnKey)
  42724. {
  42725. newTransaction();
  42726. insertTextAtCaret ("\n");
  42727. }
  42728. else if (key.isKeyCode (KeyPress::escapeKey))
  42729. {
  42730. newTransaction();
  42731. moveCursorTo (getCaretPosition(), false);
  42732. escapePressed();
  42733. }
  42734. else if (key.getTextCharacter() >= ' '
  42735. || (tabKeyUsed && (key.getTextCharacter() == '\t')))
  42736. {
  42737. insertTextAtCaret (String::charToString (key.getTextCharacter()));
  42738. lastTransactionTime = Time::getApproximateMillisecondCounter();
  42739. }
  42740. else
  42741. {
  42742. return false;
  42743. }
  42744. return true;
  42745. }
  42746. bool TextEditor::keyStateChanged (const bool isKeyDown)
  42747. {
  42748. if (! isKeyDown)
  42749. return false;
  42750. #if JUCE_WIN32
  42751. if (KeyPress (KeyPress::F4Key, ModifierKeys::altModifier, 0).isCurrentlyDown())
  42752. return false; // We need to explicitly allow alt-F4 to pass through on Windows
  42753. #endif
  42754. // (overridden to avoid forwarding key events to the parent)
  42755. return ! ModifierKeys::getCurrentModifiers().isCommandDown();
  42756. }
  42757. const int baseMenuItemID = 0x7fff0000;
  42758. void TextEditor::addPopupMenuItems (PopupMenu& m, const MouseEvent*)
  42759. {
  42760. const bool writable = ! isReadOnly();
  42761. if (passwordCharacter == 0)
  42762. {
  42763. m.addItem (baseMenuItemID + 1, TRANS("cut"), writable);
  42764. m.addItem (baseMenuItemID + 2, TRANS("copy"), ! selection.isEmpty());
  42765. m.addItem (baseMenuItemID + 3, TRANS("paste"), writable);
  42766. }
  42767. m.addItem (baseMenuItemID + 4, TRANS("delete"), writable);
  42768. m.addSeparator();
  42769. m.addItem (baseMenuItemID + 5, TRANS("select all"));
  42770. m.addSeparator();
  42771. if (getUndoManager() != 0)
  42772. {
  42773. m.addItem (baseMenuItemID + 6, TRANS("undo"), undoManager.canUndo());
  42774. m.addItem (baseMenuItemID + 7, TRANS("redo"), undoManager.canRedo());
  42775. }
  42776. }
  42777. void TextEditor::performPopupMenuAction (const int menuItemID)
  42778. {
  42779. switch (menuItemID)
  42780. {
  42781. case baseMenuItemID + 1:
  42782. copy();
  42783. cut();
  42784. break;
  42785. case baseMenuItemID + 2:
  42786. copy();
  42787. break;
  42788. case baseMenuItemID + 3:
  42789. paste();
  42790. break;
  42791. case baseMenuItemID + 4:
  42792. cut();
  42793. break;
  42794. case baseMenuItemID + 5:
  42795. moveCursorTo (getTotalNumChars(), false);
  42796. moveCursorTo (0, true);
  42797. break;
  42798. case baseMenuItemID + 6:
  42799. doUndoRedo (false);
  42800. break;
  42801. case baseMenuItemID + 7:
  42802. doUndoRedo (true);
  42803. break;
  42804. default:
  42805. break;
  42806. }
  42807. }
  42808. void TextEditor::focusGained (FocusChangeType)
  42809. {
  42810. newTransaction();
  42811. caretFlashState = true;
  42812. if (selectAllTextWhenFocused)
  42813. {
  42814. moveCursorTo (0, false);
  42815. moveCursorTo (getTotalNumChars(), true);
  42816. }
  42817. repaint();
  42818. if (caretVisible)
  42819. textHolder->startTimer (TextEditorDefs::flashSpeedIntervalMs);
  42820. ComponentPeer* const peer = getPeer();
  42821. if (peer != 0 && ! isReadOnly())
  42822. peer->textInputRequired (getScreenPosition() - peer->getScreenPosition());
  42823. }
  42824. void TextEditor::focusLost (FocusChangeType)
  42825. {
  42826. newTransaction();
  42827. wasFocused = false;
  42828. textHolder->stopTimer();
  42829. caretFlashState = false;
  42830. postCommandMessage (TextEditorDefs::focusLossMessageId);
  42831. repaint();
  42832. }
  42833. void TextEditor::resized()
  42834. {
  42835. viewport->setBoundsInset (borderSize);
  42836. viewport->setSingleStepSizes (16, roundToInt (currentFont.getHeight()));
  42837. updateTextHolderSize();
  42838. if (! isMultiLine())
  42839. {
  42840. scrollToMakeSureCursorIsVisible();
  42841. }
  42842. else
  42843. {
  42844. updateCaretPosition();
  42845. }
  42846. }
  42847. void TextEditor::handleCommandMessage (const int commandId)
  42848. {
  42849. Component::BailOutChecker checker (this);
  42850. switch (commandId)
  42851. {
  42852. case TextEditorDefs::textChangeMessageId:
  42853. listeners.callChecked (checker, &TextEditorListener::textEditorTextChanged, (TextEditor&) *this);
  42854. break;
  42855. case TextEditorDefs::returnKeyMessageId:
  42856. listeners.callChecked (checker, &TextEditorListener::textEditorReturnKeyPressed, (TextEditor&) *this);
  42857. break;
  42858. case TextEditorDefs::escapeKeyMessageId:
  42859. listeners.callChecked (checker, &TextEditorListener::textEditorEscapeKeyPressed, (TextEditor&) *this);
  42860. break;
  42861. case TextEditorDefs::focusLossMessageId:
  42862. listeners.callChecked (checker, &TextEditorListener::textEditorFocusLost, (TextEditor&) *this);
  42863. break;
  42864. default:
  42865. jassertfalse
  42866. break;
  42867. }
  42868. }
  42869. void TextEditor::enablementChanged()
  42870. {
  42871. setMouseCursor (isReadOnly() ? MouseCursor::NormalCursor
  42872. : MouseCursor::IBeamCursor);
  42873. repaint();
  42874. }
  42875. UndoManager* TextEditor::getUndoManager() throw()
  42876. {
  42877. return isReadOnly() ? &undoManager : 0;
  42878. }
  42879. void TextEditor::clearInternal (UndoManager* const um)
  42880. {
  42881. remove (Range<int> (0, getTotalNumChars()), um, caretPosition);
  42882. }
  42883. void TextEditor::insert (const String& text,
  42884. const int insertIndex,
  42885. const Font& font,
  42886. const Colour& colour,
  42887. UndoManager* const um,
  42888. const int caretPositionToMoveTo)
  42889. {
  42890. if (text.isNotEmpty())
  42891. {
  42892. if (um != 0)
  42893. {
  42894. if (um->getNumActionsInCurrentTransaction() > TextEditorDefs::maxActionsPerTransaction)
  42895. newTransaction();
  42896. um->perform (new InsertAction (*this, text, insertIndex, font, colour,
  42897. caretPosition, caretPositionToMoveTo));
  42898. }
  42899. else
  42900. {
  42901. repaintText (Range<int> (insertIndex, getTotalNumChars())); // must do this before and after changing the data, in case
  42902. // a line gets moved due to word wrap
  42903. int index = 0;
  42904. int nextIndex = 0;
  42905. for (int i = 0; i < sections.size(); ++i)
  42906. {
  42907. nextIndex = index + sections.getUnchecked (i)->getTotalLength();
  42908. if (insertIndex == index)
  42909. {
  42910. sections.insert (i, new UniformTextSection (text,
  42911. font, colour,
  42912. passwordCharacter));
  42913. break;
  42914. }
  42915. else if (insertIndex > index && insertIndex < nextIndex)
  42916. {
  42917. splitSection (i, insertIndex - index);
  42918. sections.insert (i + 1, new UniformTextSection (text,
  42919. font, colour,
  42920. passwordCharacter));
  42921. break;
  42922. }
  42923. index = nextIndex;
  42924. }
  42925. if (nextIndex == insertIndex)
  42926. sections.add (new UniformTextSection (text,
  42927. font, colour,
  42928. passwordCharacter));
  42929. coalesceSimilarSections();
  42930. totalNumChars = -1;
  42931. valueTextNeedsUpdating = true;
  42932. moveCursorTo (caretPositionToMoveTo, false);
  42933. repaintText (Range<int> (insertIndex, getTotalNumChars()));
  42934. }
  42935. }
  42936. }
  42937. void TextEditor::reinsert (const int insertIndex,
  42938. const Array <UniformTextSection*>& sectionsToInsert)
  42939. {
  42940. int index = 0;
  42941. int nextIndex = 0;
  42942. for (int i = 0; i < sections.size(); ++i)
  42943. {
  42944. nextIndex = index + sections.getUnchecked (i)->getTotalLength();
  42945. if (insertIndex == index)
  42946. {
  42947. for (int j = sectionsToInsert.size(); --j >= 0;)
  42948. sections.insert (i, new UniformTextSection (*sectionsToInsert.getUnchecked(j)));
  42949. break;
  42950. }
  42951. else if (insertIndex > index && insertIndex < nextIndex)
  42952. {
  42953. splitSection (i, insertIndex - index);
  42954. for (int j = sectionsToInsert.size(); --j >= 0;)
  42955. sections.insert (i + 1, new UniformTextSection (*sectionsToInsert.getUnchecked(j)));
  42956. break;
  42957. }
  42958. index = nextIndex;
  42959. }
  42960. if (nextIndex == insertIndex)
  42961. {
  42962. for (int j = 0; j < sectionsToInsert.size(); ++j)
  42963. sections.add (new UniformTextSection (*sectionsToInsert.getUnchecked(j)));
  42964. }
  42965. coalesceSimilarSections();
  42966. totalNumChars = -1;
  42967. valueTextNeedsUpdating = true;
  42968. }
  42969. void TextEditor::remove (const Range<int>& range,
  42970. UndoManager* const um,
  42971. const int caretPositionToMoveTo)
  42972. {
  42973. if (! range.isEmpty())
  42974. {
  42975. int index = 0;
  42976. for (int i = 0; i < sections.size(); ++i)
  42977. {
  42978. const int nextIndex = index + sections.getUnchecked(i)->getTotalLength();
  42979. if (range.getStart() > index && range.getStart() < nextIndex)
  42980. {
  42981. splitSection (i, range.getStart() - index);
  42982. --i;
  42983. }
  42984. else if (range.getEnd() > index && range.getEnd() < nextIndex)
  42985. {
  42986. splitSection (i, range.getEnd() - index);
  42987. --i;
  42988. }
  42989. else
  42990. {
  42991. index = nextIndex;
  42992. if (index > range.getEnd())
  42993. break;
  42994. }
  42995. }
  42996. index = 0;
  42997. if (um != 0)
  42998. {
  42999. Array <UniformTextSection*> removedSections;
  43000. for (int i = 0; i < sections.size(); ++i)
  43001. {
  43002. if (range.getEnd() <= range.getStart())
  43003. break;
  43004. UniformTextSection* const section = sections.getUnchecked (i);
  43005. const int nextIndex = index + section->getTotalLength();
  43006. if (range.getStart() <= index && range.getEnd() >= nextIndex)
  43007. removedSections.add (new UniformTextSection (*section));
  43008. index = nextIndex;
  43009. }
  43010. if (um->getNumActionsInCurrentTransaction() > TextEditorDefs::maxActionsPerTransaction)
  43011. newTransaction();
  43012. um->perform (new RemoveAction (*this, range, caretPosition,
  43013. caretPositionToMoveTo, removedSections));
  43014. }
  43015. else
  43016. {
  43017. Range<int> remainingRange (range);
  43018. for (int i = 0; i < sections.size(); ++i)
  43019. {
  43020. UniformTextSection* const section = sections.getUnchecked (i);
  43021. const int nextIndex = index + section->getTotalLength();
  43022. if (remainingRange.getStart() <= index && remainingRange.getEnd() >= nextIndex)
  43023. {
  43024. sections.remove(i);
  43025. section->clear();
  43026. delete section;
  43027. remainingRange.setEnd (remainingRange.getEnd() - (nextIndex - index));
  43028. if (remainingRange.isEmpty())
  43029. break;
  43030. --i;
  43031. }
  43032. else
  43033. {
  43034. index = nextIndex;
  43035. }
  43036. }
  43037. coalesceSimilarSections();
  43038. totalNumChars = -1;
  43039. valueTextNeedsUpdating = true;
  43040. moveCursorTo (caretPositionToMoveTo, false);
  43041. repaintText (Range<int> (range.getStart(), getTotalNumChars()));
  43042. }
  43043. }
  43044. }
  43045. const String TextEditor::getText() const
  43046. {
  43047. String t;
  43048. t.preallocateStorage (getTotalNumChars());
  43049. String::Concatenator concatenator (t);
  43050. for (int i = 0; i < sections.size(); ++i)
  43051. sections.getUnchecked (i)->appendAllText (concatenator);
  43052. return t;
  43053. }
  43054. const String TextEditor::getTextInRange (const Range<int>& range) const
  43055. {
  43056. String t;
  43057. if (! range.isEmpty())
  43058. {
  43059. t.preallocateStorage (jmin (getTotalNumChars(), range.getLength()));
  43060. String::Concatenator concatenator (t);
  43061. int index = 0;
  43062. for (int i = 0; i < sections.size(); ++i)
  43063. {
  43064. const UniformTextSection* const s = sections.getUnchecked (i);
  43065. const int nextIndex = index + s->getTotalLength();
  43066. if (range.getStart() < nextIndex)
  43067. {
  43068. if (range.getEnd() <= index)
  43069. break;
  43070. s->appendSubstring (concatenator, range - index);
  43071. }
  43072. index = nextIndex;
  43073. }
  43074. }
  43075. return t;
  43076. }
  43077. const String TextEditor::getHighlightedText() const
  43078. {
  43079. return getTextInRange (selection);
  43080. }
  43081. int TextEditor::getTotalNumChars() const
  43082. {
  43083. if (totalNumChars < 0)
  43084. {
  43085. totalNumChars = 0;
  43086. for (int i = sections.size(); --i >= 0;)
  43087. totalNumChars += sections.getUnchecked (i)->getTotalLength();
  43088. }
  43089. return totalNumChars;
  43090. }
  43091. bool TextEditor::isEmpty() const
  43092. {
  43093. return getTotalNumChars() == 0;
  43094. }
  43095. void TextEditor::getCharPosition (const int index, float& cx, float& cy, float& lineHeight) const
  43096. {
  43097. const float wordWrapWidth = getWordWrapWidth();
  43098. if (wordWrapWidth > 0 && sections.size() > 0)
  43099. {
  43100. Iterator i (sections, wordWrapWidth, passwordCharacter);
  43101. i.getCharPosition (index, cx, cy, lineHeight);
  43102. }
  43103. else
  43104. {
  43105. cx = cy = 0;
  43106. lineHeight = currentFont.getHeight();
  43107. }
  43108. }
  43109. int TextEditor::indexAtPosition (const float x, const float y)
  43110. {
  43111. const float wordWrapWidth = getWordWrapWidth();
  43112. if (wordWrapWidth > 0)
  43113. {
  43114. Iterator i (sections, wordWrapWidth, passwordCharacter);
  43115. while (i.next())
  43116. {
  43117. if (i.lineY + i.lineHeight > y)
  43118. {
  43119. if (i.lineY > y)
  43120. return jmax (0, i.indexInText - 1);
  43121. if (i.atomX >= x)
  43122. return i.indexInText;
  43123. if (x < i.atomRight)
  43124. return i.xToIndex (x);
  43125. }
  43126. }
  43127. }
  43128. return getTotalNumChars();
  43129. }
  43130. static int getCharacterCategory (const juce_wchar character)
  43131. {
  43132. return CharacterFunctions::isLetterOrDigit (character)
  43133. ? 2 : (CharacterFunctions::isWhitespace (character) ? 0 : 1);
  43134. }
  43135. int TextEditor::findWordBreakAfter (const int position) const
  43136. {
  43137. const String t (getTextInRange (Range<int> (position, position + 512)));
  43138. const int totalLength = t.length();
  43139. int i = 0;
  43140. while (i < totalLength && CharacterFunctions::isWhitespace (t[i]))
  43141. ++i;
  43142. const int type = getCharacterCategory (t[i]);
  43143. while (i < totalLength && type == getCharacterCategory (t[i]))
  43144. ++i;
  43145. while (i < totalLength && CharacterFunctions::isWhitespace (t[i]))
  43146. ++i;
  43147. return position + i;
  43148. }
  43149. int TextEditor::findWordBreakBefore (const int position) const
  43150. {
  43151. if (position <= 0)
  43152. return 0;
  43153. const int startOfBuffer = jmax (0, position - 512);
  43154. const String t (getTextInRange (Range<int> (startOfBuffer, position)));
  43155. int i = position - startOfBuffer;
  43156. while (i > 0 && CharacterFunctions::isWhitespace (t [i - 1]))
  43157. --i;
  43158. if (i > 0)
  43159. {
  43160. const int type = getCharacterCategory (t [i - 1]);
  43161. while (i > 0 && type == getCharacterCategory (t [i - 1]))
  43162. --i;
  43163. }
  43164. jassert (startOfBuffer + i >= 0);
  43165. return startOfBuffer + i;
  43166. }
  43167. void TextEditor::splitSection (const int sectionIndex,
  43168. const int charToSplitAt)
  43169. {
  43170. jassert (sections[sectionIndex] != 0);
  43171. sections.insert (sectionIndex + 1,
  43172. sections.getUnchecked (sectionIndex)->split (charToSplitAt, passwordCharacter));
  43173. }
  43174. void TextEditor::coalesceSimilarSections()
  43175. {
  43176. for (int i = 0; i < sections.size() - 1; ++i)
  43177. {
  43178. UniformTextSection* const s1 = sections.getUnchecked (i);
  43179. UniformTextSection* const s2 = sections.getUnchecked (i + 1);
  43180. if (s1->font == s2->font
  43181. && s1->colour == s2->colour)
  43182. {
  43183. s1->append (*s2, passwordCharacter);
  43184. sections.remove (i + 1);
  43185. delete s2;
  43186. --i;
  43187. }
  43188. }
  43189. }
  43190. END_JUCE_NAMESPACE
  43191. /*** End of inlined file: juce_TextEditor.cpp ***/
  43192. /*** Start of inlined file: juce_Toolbar.cpp ***/
  43193. BEGIN_JUCE_NAMESPACE
  43194. const char* const Toolbar::toolbarDragDescriptor = "_toolbarItem_";
  43195. class ToolbarSpacerComp : public ToolbarItemComponent
  43196. {
  43197. public:
  43198. ToolbarSpacerComp (const int itemId_, const float fixedSize_, const bool drawBar_)
  43199. : ToolbarItemComponent (itemId_, String::empty, false),
  43200. fixedSize (fixedSize_),
  43201. drawBar (drawBar_)
  43202. {
  43203. }
  43204. ~ToolbarSpacerComp()
  43205. {
  43206. }
  43207. bool getToolbarItemSizes (int toolbarThickness, bool /*isToolbarVertical*/,
  43208. int& preferredSize, int& minSize, int& maxSize)
  43209. {
  43210. if (fixedSize <= 0)
  43211. {
  43212. preferredSize = toolbarThickness * 2;
  43213. minSize = 4;
  43214. maxSize = 32768;
  43215. }
  43216. else
  43217. {
  43218. maxSize = roundToInt (toolbarThickness * fixedSize);
  43219. minSize = drawBar ? maxSize : jmin (4, maxSize);
  43220. preferredSize = maxSize;
  43221. if (getEditingMode() == editableOnPalette)
  43222. preferredSize = maxSize = toolbarThickness / (drawBar ? 3 : 2);
  43223. }
  43224. return true;
  43225. }
  43226. void paintButtonArea (Graphics&, int, int, bool, bool)
  43227. {
  43228. }
  43229. void contentAreaChanged (const Rectangle<int>&)
  43230. {
  43231. }
  43232. int getResizeOrder() const throw()
  43233. {
  43234. return fixedSize <= 0 ? 0 : 1;
  43235. }
  43236. void paint (Graphics& g)
  43237. {
  43238. const int w = getWidth();
  43239. const int h = getHeight();
  43240. if (drawBar)
  43241. {
  43242. g.setColour (findColour (Toolbar::separatorColourId, true));
  43243. const float thickness = 0.2f;
  43244. if (isToolbarVertical())
  43245. g.fillRect (w * 0.1f, h * (0.5f - thickness * 0.5f), w * 0.8f, h * thickness);
  43246. else
  43247. g.fillRect (w * (0.5f - thickness * 0.5f), h * 0.1f, w * thickness, h * 0.8f);
  43248. }
  43249. if (getEditingMode() != normalMode && ! drawBar)
  43250. {
  43251. g.setColour (findColour (Toolbar::separatorColourId, true));
  43252. const int indentX = jmin (2, (w - 3) / 2);
  43253. const int indentY = jmin (2, (h - 3) / 2);
  43254. g.drawRect (indentX, indentY, w - indentX * 2, h - indentY * 2, 1);
  43255. if (fixedSize <= 0)
  43256. {
  43257. float x1, y1, x2, y2, x3, y3, x4, y4, hw, hl;
  43258. if (isToolbarVertical())
  43259. {
  43260. x1 = w * 0.5f;
  43261. y1 = h * 0.4f;
  43262. x2 = x1;
  43263. y2 = indentX * 2.0f;
  43264. x3 = x1;
  43265. y3 = h * 0.6f;
  43266. x4 = x1;
  43267. y4 = h - y2;
  43268. hw = w * 0.15f;
  43269. hl = w * 0.2f;
  43270. }
  43271. else
  43272. {
  43273. x1 = w * 0.4f;
  43274. y1 = h * 0.5f;
  43275. x2 = indentX * 2.0f;
  43276. y2 = y1;
  43277. x3 = w * 0.6f;
  43278. y3 = y1;
  43279. x4 = w - x2;
  43280. y4 = y1;
  43281. hw = h * 0.15f;
  43282. hl = h * 0.2f;
  43283. }
  43284. Path p;
  43285. p.addArrow (x1, y1, x2, y2, 1.5f, hw, hl);
  43286. p.addArrow (x3, y3, x4, y4, 1.5f, hw, hl);
  43287. g.fillPath (p);
  43288. }
  43289. }
  43290. }
  43291. juce_UseDebuggingNewOperator
  43292. private:
  43293. const float fixedSize;
  43294. const bool drawBar;
  43295. ToolbarSpacerComp (const ToolbarSpacerComp&);
  43296. ToolbarSpacerComp& operator= (const ToolbarSpacerComp&);
  43297. };
  43298. class MissingItemsComponent : public PopupMenuCustomComponent
  43299. {
  43300. public:
  43301. MissingItemsComponent (Toolbar& owner_, const int height_)
  43302. : PopupMenuCustomComponent (true),
  43303. owner (owner_),
  43304. height (height_)
  43305. {
  43306. for (int i = owner_.items.size(); --i >= 0;)
  43307. {
  43308. ToolbarItemComponent* const tc = owner_.items.getUnchecked(i);
  43309. if (dynamic_cast <ToolbarSpacerComp*> (tc) == 0 && ! tc->isVisible())
  43310. {
  43311. oldIndexes.insert (0, i);
  43312. addAndMakeVisible (tc, 0);
  43313. }
  43314. }
  43315. layout (400);
  43316. }
  43317. ~MissingItemsComponent()
  43318. {
  43319. // deleting the toolbar while its menu it open??
  43320. jassert (owner.isValidComponent());
  43321. for (int i = 0; i < getNumChildComponents(); ++i)
  43322. {
  43323. ToolbarItemComponent* const tc = dynamic_cast <ToolbarItemComponent*> (getChildComponent (i));
  43324. if (tc != 0)
  43325. {
  43326. tc->setVisible (false);
  43327. const int index = oldIndexes.remove (i);
  43328. owner.addChildComponent (tc, index);
  43329. --i;
  43330. }
  43331. }
  43332. owner.resized();
  43333. }
  43334. void layout (const int preferredWidth)
  43335. {
  43336. const int indent = 8;
  43337. int x = indent;
  43338. int y = indent;
  43339. int maxX = 0;
  43340. for (int i = 0; i < getNumChildComponents(); ++i)
  43341. {
  43342. ToolbarItemComponent* const tc = dynamic_cast <ToolbarItemComponent*> (getChildComponent (i));
  43343. if (tc != 0)
  43344. {
  43345. int preferredSize = 1, minSize = 1, maxSize = 1;
  43346. if (tc->getToolbarItemSizes (height, false, preferredSize, minSize, maxSize))
  43347. {
  43348. if (x + preferredSize > preferredWidth && x > indent)
  43349. {
  43350. x = indent;
  43351. y += height;
  43352. }
  43353. tc->setBounds (x, y, preferredSize, height);
  43354. x += preferredSize;
  43355. maxX = jmax (maxX, x);
  43356. }
  43357. }
  43358. }
  43359. setSize (maxX + 8, y + height + 8);
  43360. }
  43361. void getIdealSize (int& idealWidth, int& idealHeight)
  43362. {
  43363. idealWidth = getWidth();
  43364. idealHeight = getHeight();
  43365. }
  43366. juce_UseDebuggingNewOperator
  43367. private:
  43368. Toolbar& owner;
  43369. const int height;
  43370. Array <int> oldIndexes;
  43371. MissingItemsComponent (const MissingItemsComponent&);
  43372. MissingItemsComponent& operator= (const MissingItemsComponent&);
  43373. };
  43374. Toolbar::Toolbar()
  43375. : vertical (false),
  43376. isEditingActive (false),
  43377. toolbarStyle (Toolbar::iconsOnly)
  43378. {
  43379. addChildComponent (missingItemsButton = getLookAndFeel().createToolbarMissingItemsButton (*this));
  43380. missingItemsButton->setAlwaysOnTop (true);
  43381. missingItemsButton->addButtonListener (this);
  43382. }
  43383. Toolbar::~Toolbar()
  43384. {
  43385. animator.cancelAllAnimations (true);
  43386. deleteAllChildren();
  43387. }
  43388. void Toolbar::setVertical (const bool shouldBeVertical)
  43389. {
  43390. if (vertical != shouldBeVertical)
  43391. {
  43392. vertical = shouldBeVertical;
  43393. resized();
  43394. }
  43395. }
  43396. void Toolbar::clear()
  43397. {
  43398. for (int i = items.size(); --i >= 0;)
  43399. {
  43400. ToolbarItemComponent* const tc = items.getUnchecked(i);
  43401. items.remove (i);
  43402. delete tc;
  43403. }
  43404. resized();
  43405. }
  43406. ToolbarItemComponent* Toolbar::createItem (ToolbarItemFactory& factory, const int itemId)
  43407. {
  43408. if (itemId == ToolbarItemFactory::separatorBarId)
  43409. return new ToolbarSpacerComp (itemId, 0.1f, true);
  43410. else if (itemId == ToolbarItemFactory::spacerId)
  43411. return new ToolbarSpacerComp (itemId, 0.5f, false);
  43412. else if (itemId == ToolbarItemFactory::flexibleSpacerId)
  43413. return new ToolbarSpacerComp (itemId, 0, false);
  43414. return factory.createItem (itemId);
  43415. }
  43416. void Toolbar::addItemInternal (ToolbarItemFactory& factory,
  43417. const int itemId,
  43418. const int insertIndex)
  43419. {
  43420. // An ID can't be zero - this might indicate a mistake somewhere?
  43421. jassert (itemId != 0);
  43422. ToolbarItemComponent* const tc = createItem (factory, itemId);
  43423. if (tc != 0)
  43424. {
  43425. #if JUCE_DEBUG
  43426. Array <int> allowedIds;
  43427. factory.getAllToolbarItemIds (allowedIds);
  43428. // If your factory can create an item for a given ID, it must also return
  43429. // that ID from its getAllToolbarItemIds() method!
  43430. jassert (allowedIds.contains (itemId));
  43431. #endif
  43432. items.insert (insertIndex, tc);
  43433. addAndMakeVisible (tc, insertIndex);
  43434. }
  43435. }
  43436. void Toolbar::addItem (ToolbarItemFactory& factory,
  43437. const int itemId,
  43438. const int insertIndex)
  43439. {
  43440. addItemInternal (factory, itemId, insertIndex);
  43441. resized();
  43442. }
  43443. void Toolbar::addDefaultItems (ToolbarItemFactory& factoryToUse)
  43444. {
  43445. Array <int> ids;
  43446. factoryToUse.getDefaultItemSet (ids);
  43447. clear();
  43448. for (int i = 0; i < ids.size(); ++i)
  43449. addItemInternal (factoryToUse, ids.getUnchecked (i), -1);
  43450. resized();
  43451. }
  43452. void Toolbar::removeToolbarItem (const int itemIndex)
  43453. {
  43454. ToolbarItemComponent* const tc = getItemComponent (itemIndex);
  43455. if (tc != 0)
  43456. {
  43457. items.removeValue (tc);
  43458. delete tc;
  43459. resized();
  43460. }
  43461. }
  43462. int Toolbar::getNumItems() const throw()
  43463. {
  43464. return items.size();
  43465. }
  43466. int Toolbar::getItemId (const int itemIndex) const throw()
  43467. {
  43468. ToolbarItemComponent* const tc = getItemComponent (itemIndex);
  43469. return tc != 0 ? tc->getItemId() : 0;
  43470. }
  43471. ToolbarItemComponent* Toolbar::getItemComponent (const int itemIndex) const throw()
  43472. {
  43473. return items [itemIndex];
  43474. }
  43475. ToolbarItemComponent* Toolbar::getNextActiveComponent (int index, const int delta) const
  43476. {
  43477. for (;;)
  43478. {
  43479. index += delta;
  43480. ToolbarItemComponent* const tc = getItemComponent (index);
  43481. if (tc == 0)
  43482. break;
  43483. if (tc->isActive)
  43484. return tc;
  43485. }
  43486. return 0;
  43487. }
  43488. void Toolbar::setStyle (const ToolbarItemStyle& newStyle)
  43489. {
  43490. if (toolbarStyle != newStyle)
  43491. {
  43492. toolbarStyle = newStyle;
  43493. updateAllItemPositions (false);
  43494. }
  43495. }
  43496. const String Toolbar::toString() const
  43497. {
  43498. String s ("TB:");
  43499. for (int i = 0; i < getNumItems(); ++i)
  43500. s << getItemId(i) << ' ';
  43501. return s.trimEnd();
  43502. }
  43503. bool Toolbar::restoreFromString (ToolbarItemFactory& factoryToUse,
  43504. const String& savedVersion)
  43505. {
  43506. if (! savedVersion.startsWith ("TB:"))
  43507. return false;
  43508. StringArray tokens;
  43509. tokens.addTokens (savedVersion.substring (3), false);
  43510. clear();
  43511. for (int i = 0; i < tokens.size(); ++i)
  43512. addItemInternal (factoryToUse, tokens[i].getIntValue(), -1);
  43513. resized();
  43514. return true;
  43515. }
  43516. void Toolbar::paint (Graphics& g)
  43517. {
  43518. getLookAndFeel().paintToolbarBackground (g, getWidth(), getHeight(), *this);
  43519. }
  43520. int Toolbar::getThickness() const throw()
  43521. {
  43522. return vertical ? getWidth() : getHeight();
  43523. }
  43524. int Toolbar::getLength() const throw()
  43525. {
  43526. return vertical ? getHeight() : getWidth();
  43527. }
  43528. void Toolbar::setEditingActive (const bool active)
  43529. {
  43530. if (isEditingActive != active)
  43531. {
  43532. isEditingActive = active;
  43533. updateAllItemPositions (false);
  43534. }
  43535. }
  43536. void Toolbar::resized()
  43537. {
  43538. updateAllItemPositions (false);
  43539. }
  43540. void Toolbar::updateAllItemPositions (const bool animate)
  43541. {
  43542. if (getWidth() > 0 && getHeight() > 0)
  43543. {
  43544. StretchableObjectResizer resizer;
  43545. int i;
  43546. for (i = 0; i < items.size(); ++i)
  43547. {
  43548. ToolbarItemComponent* const tc = items.getUnchecked(i);
  43549. tc->setEditingMode (isEditingActive ? ToolbarItemComponent::editableOnToolbar
  43550. : ToolbarItemComponent::normalMode);
  43551. tc->setStyle (toolbarStyle);
  43552. ToolbarSpacerComp* const spacer = dynamic_cast <ToolbarSpacerComp*> (tc);
  43553. int preferredSize = 1, minSize = 1, maxSize = 1;
  43554. if (tc->getToolbarItemSizes (getThickness(), isVertical(),
  43555. preferredSize, minSize, maxSize))
  43556. {
  43557. tc->isActive = true;
  43558. resizer.addItem (preferredSize, minSize, maxSize,
  43559. spacer != 0 ? spacer->getResizeOrder() : 2);
  43560. }
  43561. else
  43562. {
  43563. tc->isActive = false;
  43564. tc->setVisible (false);
  43565. }
  43566. }
  43567. resizer.resizeToFit (getLength());
  43568. int totalLength = 0;
  43569. for (i = 0; i < resizer.getNumItems(); ++i)
  43570. totalLength += (int) resizer.getItemSize (i);
  43571. const bool itemsOffTheEnd = totalLength > getLength();
  43572. const int extrasButtonSize = getThickness() / 2;
  43573. missingItemsButton->setSize (extrasButtonSize, extrasButtonSize);
  43574. missingItemsButton->setVisible (itemsOffTheEnd);
  43575. missingItemsButton->setEnabled (! isEditingActive);
  43576. if (vertical)
  43577. missingItemsButton->setCentrePosition (getWidth() / 2,
  43578. getHeight() - 4 - extrasButtonSize / 2);
  43579. else
  43580. missingItemsButton->setCentrePosition (getWidth() - 4 - extrasButtonSize / 2,
  43581. getHeight() / 2);
  43582. const int maxLength = itemsOffTheEnd ? (vertical ? missingItemsButton->getY()
  43583. : missingItemsButton->getX()) - 4
  43584. : getLength();
  43585. int pos = 0, activeIndex = 0;
  43586. for (i = 0; i < items.size(); ++i)
  43587. {
  43588. ToolbarItemComponent* const tc = items.getUnchecked(i);
  43589. if (tc->isActive)
  43590. {
  43591. const int size = (int) resizer.getItemSize (activeIndex++);
  43592. Rectangle<int> newBounds;
  43593. if (vertical)
  43594. newBounds.setBounds (0, pos, getWidth(), size);
  43595. else
  43596. newBounds.setBounds (pos, 0, size, getHeight());
  43597. if (animate)
  43598. {
  43599. animator.animateComponent (tc, newBounds, 200, 3.0, 0.0);
  43600. }
  43601. else
  43602. {
  43603. animator.cancelAnimation (tc, false);
  43604. tc->setBounds (newBounds);
  43605. }
  43606. pos += size;
  43607. tc->setVisible (pos <= maxLength
  43608. && ((! tc->isBeingDragged)
  43609. || tc->getEditingMode() == ToolbarItemComponent::editableOnPalette));
  43610. }
  43611. }
  43612. }
  43613. }
  43614. void Toolbar::buttonClicked (Button*)
  43615. {
  43616. jassert (missingItemsButton->isShowing());
  43617. if (missingItemsButton->isShowing())
  43618. {
  43619. PopupMenu m;
  43620. m.addCustomItem (1, new MissingItemsComponent (*this, getThickness()));
  43621. m.showAt (missingItemsButton);
  43622. }
  43623. }
  43624. bool Toolbar::isInterestedInDragSource (const String& sourceDescription,
  43625. Component* /*sourceComponent*/)
  43626. {
  43627. return sourceDescription == toolbarDragDescriptor && isEditingActive;
  43628. }
  43629. void Toolbar::itemDragMove (const String&, Component* sourceComponent, int x, int y)
  43630. {
  43631. ToolbarItemComponent* const tc = dynamic_cast <ToolbarItemComponent*> (sourceComponent);
  43632. if (tc != 0)
  43633. {
  43634. if (getNumItems() == 0)
  43635. {
  43636. if (tc->getEditingMode() == ToolbarItemComponent::editableOnPalette)
  43637. {
  43638. ToolbarItemPalette* const palette = tc->findParentComponentOfClass ((ToolbarItemPalette*) 0);
  43639. if (palette != 0)
  43640. palette->replaceComponent (tc);
  43641. }
  43642. else
  43643. {
  43644. jassert (tc->getEditingMode() == ToolbarItemComponent::editableOnToolbar);
  43645. }
  43646. items.add (tc);
  43647. addChildComponent (tc);
  43648. updateAllItemPositions (false);
  43649. }
  43650. else
  43651. {
  43652. for (int i = getNumItems(); --i >= 0;)
  43653. {
  43654. int currentIndex = getIndexOfChildComponent (tc);
  43655. if (currentIndex < 0)
  43656. {
  43657. if (tc->getEditingMode() == ToolbarItemComponent::editableOnPalette)
  43658. {
  43659. ToolbarItemPalette* const palette = tc->findParentComponentOfClass ((ToolbarItemPalette*) 0);
  43660. if (palette != 0)
  43661. palette->replaceComponent (tc);
  43662. }
  43663. else
  43664. {
  43665. jassert (tc->getEditingMode() == ToolbarItemComponent::editableOnToolbar);
  43666. }
  43667. items.add (tc);
  43668. addChildComponent (tc);
  43669. currentIndex = getIndexOfChildComponent (tc);
  43670. updateAllItemPositions (true);
  43671. }
  43672. int newIndex = currentIndex;
  43673. const int dragObjectLeft = vertical ? (y - tc->dragOffsetY) : (x - tc->dragOffsetX);
  43674. const int dragObjectRight = dragObjectLeft + (vertical ? tc->getHeight() : tc->getWidth());
  43675. const Rectangle<int> current (animator.getComponentDestination (getChildComponent (newIndex)));
  43676. ToolbarItemComponent* const prev = getNextActiveComponent (newIndex, -1);
  43677. if (prev != 0)
  43678. {
  43679. const Rectangle<int> previousPos (animator.getComponentDestination (prev));
  43680. if (abs (dragObjectLeft - (vertical ? previousPos.getY() : previousPos.getX())
  43681. < abs (dragObjectRight - (vertical ? current.getBottom() : current.getRight()))))
  43682. {
  43683. newIndex = getIndexOfChildComponent (prev);
  43684. }
  43685. }
  43686. ToolbarItemComponent* const next = getNextActiveComponent (newIndex, 1);
  43687. if (next != 0)
  43688. {
  43689. const Rectangle<int> nextPos (animator.getComponentDestination (next));
  43690. if (abs (dragObjectLeft - (vertical ? current.getY() : current.getX())
  43691. > abs (dragObjectRight - (vertical ? nextPos.getBottom() : nextPos.getRight()))))
  43692. {
  43693. newIndex = getIndexOfChildComponent (next) + 1;
  43694. }
  43695. }
  43696. if (newIndex != currentIndex)
  43697. {
  43698. items.removeValue (tc);
  43699. removeChildComponent (tc);
  43700. addChildComponent (tc, newIndex);
  43701. items.insert (newIndex, tc);
  43702. updateAllItemPositions (true);
  43703. }
  43704. else
  43705. {
  43706. break;
  43707. }
  43708. }
  43709. }
  43710. }
  43711. }
  43712. void Toolbar::itemDragExit (const String&, Component* sourceComponent)
  43713. {
  43714. ToolbarItemComponent* const tc = dynamic_cast <ToolbarItemComponent*> (sourceComponent);
  43715. if (tc != 0)
  43716. {
  43717. if (isParentOf (tc))
  43718. {
  43719. items.removeValue (tc);
  43720. removeChildComponent (tc);
  43721. updateAllItemPositions (true);
  43722. }
  43723. }
  43724. }
  43725. void Toolbar::itemDropped (const String&, Component*, int, int)
  43726. {
  43727. }
  43728. void Toolbar::mouseDown (const MouseEvent& e)
  43729. {
  43730. if (e.mods.isPopupMenu())
  43731. {
  43732. }
  43733. }
  43734. class ToolbarCustomisationDialog : public DialogWindow
  43735. {
  43736. public:
  43737. ToolbarCustomisationDialog (ToolbarItemFactory& factory,
  43738. Toolbar* const toolbar_,
  43739. const int optionFlags)
  43740. : DialogWindow (TRANS("Add/remove items from toolbar"), Colours::white, true, true),
  43741. toolbar (toolbar_)
  43742. {
  43743. setContentComponent (new CustomiserPanel (factory, toolbar, optionFlags), true, true);
  43744. setResizable (true, true);
  43745. setResizeLimits (400, 300, 1500, 1000);
  43746. positionNearBar();
  43747. }
  43748. ~ToolbarCustomisationDialog()
  43749. {
  43750. setContentComponent (0, true);
  43751. }
  43752. void closeButtonPressed()
  43753. {
  43754. setVisible (false);
  43755. }
  43756. bool canModalEventBeSentToComponent (const Component* comp)
  43757. {
  43758. return toolbar->isParentOf (comp);
  43759. }
  43760. void positionNearBar()
  43761. {
  43762. const Rectangle<int> screenSize (toolbar->getParentMonitorArea());
  43763. const int tbx = toolbar->getScreenX();
  43764. const int tby = toolbar->getScreenY();
  43765. const int gap = 8;
  43766. int x, y;
  43767. if (toolbar->isVertical())
  43768. {
  43769. y = tby;
  43770. if (tbx > screenSize.getCentreX())
  43771. x = tbx - getWidth() - gap;
  43772. else
  43773. x = tbx + toolbar->getWidth() + gap;
  43774. }
  43775. else
  43776. {
  43777. x = tbx + (toolbar->getWidth() - getWidth()) / 2;
  43778. if (tby > screenSize.getCentreY())
  43779. y = tby - getHeight() - gap;
  43780. else
  43781. y = tby + toolbar->getHeight() + gap;
  43782. }
  43783. setTopLeftPosition (x, y);
  43784. }
  43785. private:
  43786. Toolbar* const toolbar;
  43787. class CustomiserPanel : public Component,
  43788. private ComboBoxListener,
  43789. private ButtonListener
  43790. {
  43791. public:
  43792. CustomiserPanel (ToolbarItemFactory& factory_,
  43793. Toolbar* const toolbar_,
  43794. const int optionFlags)
  43795. : factory (factory_),
  43796. toolbar (toolbar_),
  43797. styleBox (0),
  43798. defaultButton (0)
  43799. {
  43800. addAndMakeVisible (palette = new ToolbarItemPalette (factory, toolbar));
  43801. if ((optionFlags & (Toolbar::allowIconsOnlyChoice
  43802. | Toolbar::allowIconsWithTextChoice
  43803. | Toolbar::allowTextOnlyChoice)) != 0)
  43804. {
  43805. addAndMakeVisible (styleBox = new ComboBox (String::empty));
  43806. styleBox->setEditableText (false);
  43807. if ((optionFlags & Toolbar::allowIconsOnlyChoice) != 0)
  43808. styleBox->addItem (TRANS("Show icons only"), 1);
  43809. if ((optionFlags & Toolbar::allowIconsWithTextChoice) != 0)
  43810. styleBox->addItem (TRANS("Show icons and descriptions"), 2);
  43811. if ((optionFlags & Toolbar::allowTextOnlyChoice) != 0)
  43812. styleBox->addItem (TRANS("Show descriptions only"), 3);
  43813. if (toolbar_->getStyle() == Toolbar::iconsOnly)
  43814. styleBox->setSelectedId (1);
  43815. else if (toolbar_->getStyle() == Toolbar::iconsWithText)
  43816. styleBox->setSelectedId (2);
  43817. else if (toolbar_->getStyle() == Toolbar::textOnly)
  43818. styleBox->setSelectedId (3);
  43819. styleBox->addListener (this);
  43820. }
  43821. if ((optionFlags & Toolbar::showResetToDefaultsButton) != 0)
  43822. {
  43823. addAndMakeVisible (defaultButton = new TextButton (TRANS ("Restore to default set of items")));
  43824. defaultButton->addButtonListener (this);
  43825. }
  43826. addAndMakeVisible (instructions = new Label (String::empty,
  43827. 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.")));
  43828. instructions->setFont (Font (13.0f));
  43829. setSize (500, 300);
  43830. }
  43831. ~CustomiserPanel()
  43832. {
  43833. deleteAllChildren();
  43834. }
  43835. void comboBoxChanged (ComboBox*)
  43836. {
  43837. if (styleBox->getSelectedId() == 1)
  43838. toolbar->setStyle (Toolbar::iconsOnly);
  43839. else if (styleBox->getSelectedId() == 2)
  43840. toolbar->setStyle (Toolbar::iconsWithText);
  43841. else if (styleBox->getSelectedId() == 3)
  43842. toolbar->setStyle (Toolbar::textOnly);
  43843. palette->resized(); // to make it update the styles
  43844. }
  43845. void buttonClicked (Button*)
  43846. {
  43847. toolbar->addDefaultItems (factory);
  43848. }
  43849. void paint (Graphics& g)
  43850. {
  43851. Colour background;
  43852. DialogWindow* const dw = findParentComponentOfClass ((DialogWindow*) 0);
  43853. if (dw != 0)
  43854. background = dw->getBackgroundColour();
  43855. g.setColour (background.contrasting().withAlpha (0.3f));
  43856. g.fillRect (palette->getX(), palette->getBottom() - 1, palette->getWidth(), 1);
  43857. }
  43858. void resized()
  43859. {
  43860. palette->setBounds (0, 0, getWidth(), getHeight() - 120);
  43861. if (styleBox != 0)
  43862. styleBox->setBounds (10, getHeight() - 110, 200, 22);
  43863. if (defaultButton != 0)
  43864. {
  43865. defaultButton->changeWidthToFitText (22);
  43866. defaultButton->setTopLeftPosition (240, getHeight() - 110);
  43867. }
  43868. instructions->setBounds (10, getHeight() - 80, getWidth() - 20, 80);
  43869. }
  43870. private:
  43871. ToolbarItemFactory& factory;
  43872. Toolbar* const toolbar;
  43873. Label* instructions;
  43874. ToolbarItemPalette* palette;
  43875. ComboBox* styleBox;
  43876. TextButton* defaultButton;
  43877. };
  43878. };
  43879. void Toolbar::showCustomisationDialog (ToolbarItemFactory& factory, const int optionFlags)
  43880. {
  43881. setEditingActive (true);
  43882. ToolbarCustomisationDialog dw (factory, this, optionFlags);
  43883. dw.runModalLoop();
  43884. jassert (isValidComponent()); // ? deleting the toolbar while it's being edited?
  43885. setEditingActive (false);
  43886. }
  43887. END_JUCE_NAMESPACE
  43888. /*** End of inlined file: juce_Toolbar.cpp ***/
  43889. /*** Start of inlined file: juce_ToolbarItemComponent.cpp ***/
  43890. BEGIN_JUCE_NAMESPACE
  43891. ToolbarItemFactory::ToolbarItemFactory()
  43892. {
  43893. }
  43894. ToolbarItemFactory::~ToolbarItemFactory()
  43895. {
  43896. }
  43897. class ItemDragAndDropOverlayComponent : public Component
  43898. {
  43899. public:
  43900. ItemDragAndDropOverlayComponent()
  43901. : isDragging (false)
  43902. {
  43903. setAlwaysOnTop (true);
  43904. setRepaintsOnMouseActivity (true);
  43905. setMouseCursor (MouseCursor::DraggingHandCursor);
  43906. }
  43907. ~ItemDragAndDropOverlayComponent()
  43908. {
  43909. }
  43910. void paint (Graphics& g)
  43911. {
  43912. ToolbarItemComponent* const tc = dynamic_cast <ToolbarItemComponent*> (getParentComponent());
  43913. if (isMouseOverOrDragging()
  43914. && tc != 0
  43915. && tc->getEditingMode() == ToolbarItemComponent::editableOnToolbar)
  43916. {
  43917. g.setColour (findColour (Toolbar::editingModeOutlineColourId, true));
  43918. g.drawRect (0, 0, getWidth(), getHeight(),
  43919. jmin (2, (getWidth() - 1) / 2, (getHeight() - 1) / 2));
  43920. }
  43921. }
  43922. void mouseDown (const MouseEvent& e)
  43923. {
  43924. isDragging = false;
  43925. ToolbarItemComponent* const tc = dynamic_cast <ToolbarItemComponent*> (getParentComponent());
  43926. if (tc != 0)
  43927. {
  43928. tc->dragOffsetX = e.x;
  43929. tc->dragOffsetY = e.y;
  43930. }
  43931. }
  43932. void mouseDrag (const MouseEvent& e)
  43933. {
  43934. if (! (isDragging || e.mouseWasClicked()))
  43935. {
  43936. isDragging = true;
  43937. DragAndDropContainer* const dnd = DragAndDropContainer::findParentDragContainerFor (this);
  43938. if (dnd != 0)
  43939. {
  43940. dnd->startDragging (Toolbar::toolbarDragDescriptor, getParentComponent(), 0, true);
  43941. ToolbarItemComponent* const tc = dynamic_cast <ToolbarItemComponent*> (getParentComponent());
  43942. if (tc != 0)
  43943. {
  43944. tc->isBeingDragged = true;
  43945. if (tc->getEditingMode() == ToolbarItemComponent::editableOnToolbar)
  43946. tc->setVisible (false);
  43947. }
  43948. }
  43949. }
  43950. }
  43951. void mouseUp (const MouseEvent&)
  43952. {
  43953. isDragging = false;
  43954. ToolbarItemComponent* const tc = dynamic_cast <ToolbarItemComponent*> (getParentComponent());
  43955. if (tc != 0)
  43956. {
  43957. tc->isBeingDragged = false;
  43958. Toolbar* const tb = tc->getToolbar();
  43959. if (tb != 0)
  43960. tb->updateAllItemPositions (true);
  43961. else if (tc->getEditingMode() == ToolbarItemComponent::editableOnToolbar)
  43962. delete tc;
  43963. }
  43964. }
  43965. void parentSizeChanged()
  43966. {
  43967. setBounds (0, 0, getParentWidth(), getParentHeight());
  43968. }
  43969. juce_UseDebuggingNewOperator
  43970. private:
  43971. bool isDragging;
  43972. ItemDragAndDropOverlayComponent (const ItemDragAndDropOverlayComponent&);
  43973. ItemDragAndDropOverlayComponent& operator= (const ItemDragAndDropOverlayComponent&);
  43974. };
  43975. ToolbarItemComponent::ToolbarItemComponent (const int itemId_,
  43976. const String& labelText,
  43977. const bool isBeingUsedAsAButton_)
  43978. : Button (labelText),
  43979. itemId (itemId_),
  43980. mode (normalMode),
  43981. toolbarStyle (Toolbar::iconsOnly),
  43982. dragOffsetX (0),
  43983. dragOffsetY (0),
  43984. isActive (true),
  43985. isBeingDragged (false),
  43986. isBeingUsedAsAButton (isBeingUsedAsAButton_)
  43987. {
  43988. // Your item ID can't be 0!
  43989. jassert (itemId_ != 0);
  43990. }
  43991. ToolbarItemComponent::~ToolbarItemComponent()
  43992. {
  43993. jassert (overlayComp == 0 || overlayComp->isValidComponent());
  43994. overlayComp = 0;
  43995. }
  43996. Toolbar* ToolbarItemComponent::getToolbar() const
  43997. {
  43998. return dynamic_cast <Toolbar*> (getParentComponent());
  43999. }
  44000. bool ToolbarItemComponent::isToolbarVertical() const
  44001. {
  44002. const Toolbar* const t = getToolbar();
  44003. return t != 0 && t->isVertical();
  44004. }
  44005. void ToolbarItemComponent::setStyle (const Toolbar::ToolbarItemStyle& newStyle)
  44006. {
  44007. if (toolbarStyle != newStyle)
  44008. {
  44009. toolbarStyle = newStyle;
  44010. repaint();
  44011. resized();
  44012. }
  44013. }
  44014. void ToolbarItemComponent::paintButton (Graphics& g, const bool over, const bool down)
  44015. {
  44016. if (isBeingUsedAsAButton)
  44017. getLookAndFeel().paintToolbarButtonBackground (g, getWidth(), getHeight(),
  44018. over, down, *this);
  44019. if (toolbarStyle != Toolbar::iconsOnly)
  44020. {
  44021. const int indent = contentArea.getX();
  44022. int y = indent;
  44023. int h = getHeight() - indent * 2;
  44024. if (toolbarStyle == Toolbar::iconsWithText)
  44025. {
  44026. y = contentArea.getBottom() + indent / 2;
  44027. h -= contentArea.getHeight();
  44028. }
  44029. getLookAndFeel().paintToolbarButtonLabel (g, indent, y, getWidth() - indent * 2, h,
  44030. getButtonText(), *this);
  44031. }
  44032. if (! contentArea.isEmpty())
  44033. {
  44034. g.saveState();
  44035. g.setOrigin (contentArea.getX(), contentArea.getY());
  44036. g.reduceClipRegion (0, 0, contentArea.getWidth(), contentArea.getHeight());
  44037. paintButtonArea (g, contentArea.getWidth(), contentArea.getHeight(), over, down);
  44038. g.restoreState();
  44039. }
  44040. }
  44041. void ToolbarItemComponent::resized()
  44042. {
  44043. if (toolbarStyle != Toolbar::textOnly)
  44044. {
  44045. const int indent = jmin (proportionOfWidth (0.08f),
  44046. proportionOfHeight (0.08f));
  44047. contentArea = Rectangle<int> (indent, indent,
  44048. getWidth() - indent * 2,
  44049. toolbarStyle == Toolbar::iconsWithText ? proportionOfHeight (0.55f)
  44050. : (getHeight() - indent * 2));
  44051. }
  44052. else
  44053. {
  44054. contentArea = Rectangle<int>();
  44055. }
  44056. contentAreaChanged (contentArea);
  44057. }
  44058. void ToolbarItemComponent::setEditingMode (const ToolbarEditingMode newMode)
  44059. {
  44060. if (mode != newMode)
  44061. {
  44062. mode = newMode;
  44063. repaint();
  44064. if (mode == normalMode)
  44065. {
  44066. jassert (overlayComp == 0 || overlayComp->isValidComponent());
  44067. overlayComp = 0;
  44068. }
  44069. else if (overlayComp == 0)
  44070. {
  44071. addAndMakeVisible (overlayComp = new ItemDragAndDropOverlayComponent());
  44072. overlayComp->parentSizeChanged();
  44073. }
  44074. resized();
  44075. }
  44076. }
  44077. END_JUCE_NAMESPACE
  44078. /*** End of inlined file: juce_ToolbarItemComponent.cpp ***/
  44079. /*** Start of inlined file: juce_ToolbarItemPalette.cpp ***/
  44080. BEGIN_JUCE_NAMESPACE
  44081. ToolbarItemPalette::ToolbarItemPalette (ToolbarItemFactory& factory_,
  44082. Toolbar* const toolbar_)
  44083. : factory (factory_),
  44084. toolbar (toolbar_)
  44085. {
  44086. Component* const itemHolder = new Component();
  44087. Array <int> allIds;
  44088. factory_.getAllToolbarItemIds (allIds);
  44089. for (int i = 0; i < allIds.size(); ++i)
  44090. {
  44091. ToolbarItemComponent* const tc = Toolbar::createItem (factory_, allIds.getUnchecked (i));
  44092. jassert (tc != 0);
  44093. if (tc != 0)
  44094. {
  44095. itemHolder->addAndMakeVisible (tc);
  44096. tc->setEditingMode (ToolbarItemComponent::editableOnPalette);
  44097. }
  44098. }
  44099. viewport = new Viewport();
  44100. viewport->setViewedComponent (itemHolder);
  44101. addAndMakeVisible (viewport);
  44102. }
  44103. ToolbarItemPalette::~ToolbarItemPalette()
  44104. {
  44105. viewport->getViewedComponent()->deleteAllChildren();
  44106. deleteAllChildren();
  44107. }
  44108. void ToolbarItemPalette::resized()
  44109. {
  44110. viewport->setBoundsInset (BorderSize (1));
  44111. Component* const itemHolder = viewport->getViewedComponent();
  44112. const int indent = 8;
  44113. const int preferredWidth = viewport->getWidth() - viewport->getScrollBarThickness() - indent;
  44114. const int height = toolbar->getThickness();
  44115. int x = indent;
  44116. int y = indent;
  44117. int maxX = 0;
  44118. for (int i = 0; i < itemHolder->getNumChildComponents(); ++i)
  44119. {
  44120. ToolbarItemComponent* const tc = dynamic_cast <ToolbarItemComponent*> (itemHolder->getChildComponent (i));
  44121. if (tc != 0)
  44122. {
  44123. tc->setStyle (toolbar->getStyle());
  44124. int preferredSize = 1, minSize = 1, maxSize = 1;
  44125. if (tc->getToolbarItemSizes (height, false, preferredSize, minSize, maxSize))
  44126. {
  44127. if (x + preferredSize > preferredWidth && x > indent)
  44128. {
  44129. x = indent;
  44130. y += height;
  44131. }
  44132. tc->setBounds (x, y, preferredSize, height);
  44133. x += preferredSize + 8;
  44134. maxX = jmax (maxX, x);
  44135. }
  44136. }
  44137. }
  44138. itemHolder->setSize (maxX, y + height + 8);
  44139. }
  44140. void ToolbarItemPalette::replaceComponent (ToolbarItemComponent* const comp)
  44141. {
  44142. ToolbarItemComponent* const tc = Toolbar::createItem (factory, comp->getItemId());
  44143. jassert (tc != 0);
  44144. if (tc != 0)
  44145. {
  44146. tc->setBounds (comp->getBounds());
  44147. tc->setStyle (toolbar->getStyle());
  44148. tc->setEditingMode (comp->getEditingMode());
  44149. viewport->getViewedComponent()->addAndMakeVisible (tc, getIndexOfChildComponent (comp));
  44150. }
  44151. }
  44152. END_JUCE_NAMESPACE
  44153. /*** End of inlined file: juce_ToolbarItemPalette.cpp ***/
  44154. /*** Start of inlined file: juce_TreeView.cpp ***/
  44155. BEGIN_JUCE_NAMESPACE
  44156. class TreeViewContentComponent : public Component,
  44157. public TooltipClient
  44158. {
  44159. public:
  44160. TreeViewContentComponent (TreeView& owner_)
  44161. : owner (owner_),
  44162. buttonUnderMouse (0),
  44163. isDragging (false)
  44164. {
  44165. }
  44166. ~TreeViewContentComponent()
  44167. {
  44168. deleteAllChildren();
  44169. }
  44170. void mouseDown (const MouseEvent& e)
  44171. {
  44172. updateButtonUnderMouse (e);
  44173. isDragging = false;
  44174. needSelectionOnMouseUp = false;
  44175. Rectangle<int> pos;
  44176. TreeViewItem* const item = findItemAt (e.y, pos);
  44177. if (item == 0)
  44178. return;
  44179. // (if the open/close buttons are hidden, we'll treat clicks to the left of the item
  44180. // as selection clicks)
  44181. if (e.x < pos.getX() && owner.openCloseButtonsVisible)
  44182. {
  44183. if (e.x >= pos.getX() - owner.getIndentSize())
  44184. item->setOpen (! item->isOpen());
  44185. // (clicks to the left of an open/close button are ignored)
  44186. }
  44187. else
  44188. {
  44189. // mouse-down inside the body of the item..
  44190. if (! owner.isMultiSelectEnabled())
  44191. item->setSelected (true, true);
  44192. else if (item->isSelected())
  44193. needSelectionOnMouseUp = ! e.mods.isPopupMenu();
  44194. else
  44195. selectBasedOnModifiers (item, e.mods);
  44196. if (e.x >= pos.getX())
  44197. item->itemClicked (e.withNewPosition (e.getPosition() - pos.getPosition()));
  44198. }
  44199. }
  44200. void mouseUp (const MouseEvent& e)
  44201. {
  44202. updateButtonUnderMouse (e);
  44203. if (needSelectionOnMouseUp && e.mouseWasClicked())
  44204. {
  44205. Rectangle<int> pos;
  44206. TreeViewItem* const item = findItemAt (e.y, pos);
  44207. if (item != 0)
  44208. selectBasedOnModifiers (item, e.mods);
  44209. }
  44210. }
  44211. void mouseDoubleClick (const MouseEvent& e)
  44212. {
  44213. if (e.getNumberOfClicks() != 3) // ignore triple clicks
  44214. {
  44215. Rectangle<int> pos;
  44216. TreeViewItem* const item = findItemAt (e.y, pos);
  44217. if (item != 0 && (e.x >= pos.getX() || ! owner.openCloseButtonsVisible))
  44218. item->itemDoubleClicked (e.withNewPosition (e.getPosition() - pos.getPosition()));
  44219. }
  44220. }
  44221. void mouseDrag (const MouseEvent& e)
  44222. {
  44223. if (isEnabled()
  44224. && ! (isDragging || e.mouseWasClicked()
  44225. || e.getDistanceFromDragStart() < 5
  44226. || e.mods.isPopupMenu()))
  44227. {
  44228. isDragging = true;
  44229. Rectangle<int> pos;
  44230. TreeViewItem* const item = findItemAt (e.getMouseDownY(), pos);
  44231. if (item != 0 && e.getMouseDownX() >= pos.getX())
  44232. {
  44233. const String dragDescription (item->getDragSourceDescription());
  44234. if (dragDescription.isNotEmpty())
  44235. {
  44236. DragAndDropContainer* const dragContainer
  44237. = DragAndDropContainer::findParentDragContainerFor (this);
  44238. if (dragContainer != 0)
  44239. {
  44240. pos.setSize (pos.getWidth(), item->itemHeight);
  44241. Image* dragImage = Component::createComponentSnapshot (pos, true);
  44242. dragImage->multiplyAllAlphas (0.6f);
  44243. Point<int> imageOffset (pos.getX() - e.x, pos.getY() - e.y);
  44244. dragContainer->startDragging (dragDescription, &owner, dragImage, true, &imageOffset);
  44245. }
  44246. else
  44247. {
  44248. // to be able to do a drag-and-drop operation, the treeview needs to
  44249. // be inside a component which is also a DragAndDropContainer.
  44250. jassertfalse
  44251. }
  44252. }
  44253. }
  44254. }
  44255. }
  44256. void mouseMove (const MouseEvent& e)
  44257. {
  44258. updateButtonUnderMouse (e);
  44259. }
  44260. void mouseExit (const MouseEvent& e)
  44261. {
  44262. updateButtonUnderMouse (e);
  44263. }
  44264. void paint (Graphics& g)
  44265. {
  44266. if (owner.rootItem != 0)
  44267. {
  44268. owner.handleAsyncUpdate();
  44269. if (! owner.rootItemVisible)
  44270. g.setOrigin (0, -owner.rootItem->itemHeight);
  44271. owner.rootItem->paintRecursively (g, getWidth());
  44272. }
  44273. }
  44274. TreeViewItem* findItemAt (int y, Rectangle<int>& itemPosition) const
  44275. {
  44276. if (owner.rootItem != 0)
  44277. {
  44278. owner.handleAsyncUpdate();
  44279. if (! owner.rootItemVisible)
  44280. y += owner.rootItem->itemHeight;
  44281. TreeViewItem* const ti = owner.rootItem->findItemRecursively (y);
  44282. if (ti != 0)
  44283. itemPosition = ti->getItemPosition (false);
  44284. return ti;
  44285. }
  44286. return 0;
  44287. }
  44288. void updateComponents()
  44289. {
  44290. const int visibleTop = -getY();
  44291. const int visibleBottom = visibleTop + getParentHeight();
  44292. BigInteger itemsToKeep;
  44293. {
  44294. TreeViewItem* item = owner.rootItem;
  44295. int y = (item != 0 && ! owner.rootItemVisible) ? -item->itemHeight : 0;
  44296. while (item != 0 && y < visibleBottom)
  44297. {
  44298. y += item->itemHeight;
  44299. if (y >= visibleTop)
  44300. {
  44301. const int index = rowComponentIds.indexOf (item->uid);
  44302. if (index < 0)
  44303. {
  44304. Component* const comp = item->createItemComponent();
  44305. if (comp != 0)
  44306. {
  44307. addAndMakeVisible (comp);
  44308. itemsToKeep.setBit (rowComponentItems.size());
  44309. rowComponentItems.add (item);
  44310. rowComponentIds.add (item->uid);
  44311. rowComponents.add (comp);
  44312. }
  44313. }
  44314. else
  44315. {
  44316. itemsToKeep.setBit (index);
  44317. }
  44318. }
  44319. item = item->getNextVisibleItem (true);
  44320. }
  44321. }
  44322. for (int i = rowComponentItems.size(); --i >= 0;)
  44323. {
  44324. Component* const comp = rowComponents.getUnchecked(i);
  44325. bool keep = false;
  44326. if (isParentOf (comp))
  44327. {
  44328. if (itemsToKeep[i])
  44329. {
  44330. const TreeViewItem* const item = rowComponentItems.getUnchecked(i);
  44331. Rectangle<int> pos (item->getItemPosition (false));
  44332. pos.setSize (pos.getWidth(), item->itemHeight);
  44333. if (pos.getBottom() >= visibleTop && pos.getY() < visibleBottom)
  44334. {
  44335. keep = true;
  44336. comp->setBounds (pos);
  44337. }
  44338. }
  44339. if ((! keep) && isMouseDraggingInChildCompOf (comp))
  44340. {
  44341. keep = true;
  44342. comp->setSize (0, 0);
  44343. }
  44344. }
  44345. if (! keep)
  44346. {
  44347. delete comp;
  44348. rowComponents.remove (i);
  44349. rowComponentIds.remove (i);
  44350. rowComponentItems.remove (i);
  44351. }
  44352. }
  44353. }
  44354. void updateButtonUnderMouse (const MouseEvent& e)
  44355. {
  44356. TreeViewItem* newItem = 0;
  44357. if (owner.openCloseButtonsVisible)
  44358. {
  44359. Rectangle<int> pos;
  44360. TreeViewItem* item = findItemAt (e.y, pos);
  44361. if (item != 0 && e.x < pos.getX() && e.x >= pos.getX() - owner.getIndentSize())
  44362. {
  44363. newItem = item;
  44364. if (! newItem->mightContainSubItems())
  44365. newItem = 0;
  44366. }
  44367. }
  44368. if (buttonUnderMouse != newItem)
  44369. {
  44370. if (buttonUnderMouse != 0 && containsItem (buttonUnderMouse))
  44371. {
  44372. const Rectangle<int> r (buttonUnderMouse->getItemPosition (false));
  44373. repaint (0, r.getY(), r.getX(), buttonUnderMouse->getItemHeight());
  44374. }
  44375. buttonUnderMouse = newItem;
  44376. if (buttonUnderMouse != 0)
  44377. {
  44378. const Rectangle<int> r (buttonUnderMouse->getItemPosition (false));
  44379. repaint (0, r.getY(), r.getX(), buttonUnderMouse->getItemHeight());
  44380. }
  44381. }
  44382. }
  44383. bool isMouseOverButton (TreeViewItem* const item) const throw()
  44384. {
  44385. return item == buttonUnderMouse;
  44386. }
  44387. void resized()
  44388. {
  44389. owner.itemsChanged();
  44390. }
  44391. const String getTooltip()
  44392. {
  44393. Rectangle<int> pos;
  44394. TreeViewItem* const item = findItemAt (getMouseXYRelative().getY(), pos);
  44395. if (item != 0)
  44396. return item->getTooltip();
  44397. return owner.getTooltip();
  44398. }
  44399. juce_UseDebuggingNewOperator
  44400. private:
  44401. TreeView& owner;
  44402. Array <TreeViewItem*> rowComponentItems;
  44403. Array <int> rowComponentIds;
  44404. Array <Component*> rowComponents;
  44405. TreeViewItem* buttonUnderMouse;
  44406. bool isDragging, needSelectionOnMouseUp;
  44407. void selectBasedOnModifiers (TreeViewItem* const item, const ModifierKeys& modifiers)
  44408. {
  44409. TreeViewItem* firstSelected = 0;
  44410. if (modifiers.isShiftDown() && ((firstSelected = owner.getSelectedItem (0)) != 0))
  44411. {
  44412. TreeViewItem* const lastSelected = owner.getSelectedItem (owner.getNumSelectedItems() - 1);
  44413. jassert (lastSelected != 0);
  44414. int rowStart = firstSelected->getRowNumberInTree();
  44415. int rowEnd = lastSelected->getRowNumberInTree();
  44416. if (rowStart > rowEnd)
  44417. swapVariables (rowStart, rowEnd);
  44418. int ourRow = item->getRowNumberInTree();
  44419. int otherEnd = ourRow < rowEnd ? rowStart : rowEnd;
  44420. if (ourRow > otherEnd)
  44421. swapVariables (ourRow, otherEnd);
  44422. for (int i = ourRow; i <= otherEnd; ++i)
  44423. owner.getItemOnRow (i)->setSelected (true, false);
  44424. }
  44425. else
  44426. {
  44427. const bool cmd = modifiers.isCommandDown();
  44428. item->setSelected ((! cmd) || ! item->isSelected(), ! cmd);
  44429. }
  44430. }
  44431. bool containsItem (TreeViewItem* const item) const
  44432. {
  44433. for (int i = rowComponentItems.size(); --i >= 0;)
  44434. if (rowComponentItems.getUnchecked(i) == item)
  44435. return true;
  44436. return false;
  44437. }
  44438. static bool isMouseDraggingInChildCompOf (Component* const comp)
  44439. {
  44440. for (int i = Desktop::getInstance().getNumMouseSources(); --i >= 0;)
  44441. {
  44442. MouseInputSource* const source = Desktop::getInstance().getMouseSource(i);
  44443. if (source->isDragging())
  44444. {
  44445. Component* const underMouse = source->getComponentUnderMouse();
  44446. if (underMouse != 0 && (comp == underMouse || comp->isParentOf (underMouse)))
  44447. return true;
  44448. }
  44449. }
  44450. return false;
  44451. }
  44452. TreeViewContentComponent (const TreeViewContentComponent&);
  44453. TreeViewContentComponent& operator= (const TreeViewContentComponent&);
  44454. };
  44455. class TreeView::TreeViewport : public Viewport
  44456. {
  44457. public:
  44458. TreeViewport() throw() : lastX (-1) {}
  44459. ~TreeViewport() throw() {}
  44460. void updateComponents (const bool triggerResize = false)
  44461. {
  44462. TreeViewContentComponent* const tvc = static_cast <TreeViewContentComponent*> (getViewedComponent());
  44463. if (tvc != 0)
  44464. {
  44465. if (triggerResize)
  44466. tvc->resized();
  44467. else
  44468. tvc->updateComponents();
  44469. }
  44470. repaint();
  44471. }
  44472. void visibleAreaChanged (int x, int, int, int)
  44473. {
  44474. const bool hasScrolledSideways = (x != lastX);
  44475. lastX = x;
  44476. updateComponents (hasScrolledSideways);
  44477. }
  44478. juce_UseDebuggingNewOperator
  44479. private:
  44480. int lastX;
  44481. TreeViewport (const TreeViewport&);
  44482. TreeViewport& operator= (const TreeViewport&);
  44483. };
  44484. TreeView::TreeView (const String& componentName)
  44485. : Component (componentName),
  44486. rootItem (0),
  44487. dragInsertPointHighlight (0),
  44488. dragTargetGroupHighlight (0),
  44489. indentSize (24),
  44490. defaultOpenness (false),
  44491. needsRecalculating (true),
  44492. rootItemVisible (true),
  44493. multiSelectEnabled (false),
  44494. openCloseButtonsVisible (true)
  44495. {
  44496. addAndMakeVisible (viewport = new TreeViewport());
  44497. viewport->setViewedComponent (new TreeViewContentComponent (*this));
  44498. viewport->setWantsKeyboardFocus (false);
  44499. setWantsKeyboardFocus (true);
  44500. }
  44501. TreeView::~TreeView()
  44502. {
  44503. if (rootItem != 0)
  44504. rootItem->setOwnerView (0);
  44505. deleteAllChildren();
  44506. }
  44507. void TreeView::setRootItem (TreeViewItem* const newRootItem)
  44508. {
  44509. if (rootItem != newRootItem)
  44510. {
  44511. if (newRootItem != 0)
  44512. {
  44513. jassert (newRootItem->ownerView == 0); // can't use a tree item in more than one tree at once..
  44514. if (newRootItem->ownerView != 0)
  44515. newRootItem->ownerView->setRootItem (0);
  44516. }
  44517. if (rootItem != 0)
  44518. rootItem->setOwnerView (0);
  44519. rootItem = newRootItem;
  44520. if (newRootItem != 0)
  44521. newRootItem->setOwnerView (this);
  44522. needsRecalculating = true;
  44523. handleAsyncUpdate();
  44524. if (rootItem != 0 && (defaultOpenness || ! rootItemVisible))
  44525. {
  44526. rootItem->setOpen (false); // force a re-open
  44527. rootItem->setOpen (true);
  44528. }
  44529. }
  44530. }
  44531. void TreeView::deleteRootItem()
  44532. {
  44533. const ScopedPointer <TreeViewItem> deleter (rootItem);
  44534. setRootItem (0);
  44535. }
  44536. void TreeView::setRootItemVisible (const bool shouldBeVisible)
  44537. {
  44538. rootItemVisible = shouldBeVisible;
  44539. if (rootItem != 0 && (defaultOpenness || ! rootItemVisible))
  44540. {
  44541. rootItem->setOpen (false); // force a re-open
  44542. rootItem->setOpen (true);
  44543. }
  44544. itemsChanged();
  44545. }
  44546. void TreeView::colourChanged()
  44547. {
  44548. setOpaque (findColour (backgroundColourId).isOpaque());
  44549. repaint();
  44550. }
  44551. void TreeView::setIndentSize (const int newIndentSize)
  44552. {
  44553. if (indentSize != newIndentSize)
  44554. {
  44555. indentSize = newIndentSize;
  44556. resized();
  44557. }
  44558. }
  44559. void TreeView::setDefaultOpenness (const bool isOpenByDefault)
  44560. {
  44561. if (defaultOpenness != isOpenByDefault)
  44562. {
  44563. defaultOpenness = isOpenByDefault;
  44564. itemsChanged();
  44565. }
  44566. }
  44567. void TreeView::setMultiSelectEnabled (const bool canMultiSelect)
  44568. {
  44569. multiSelectEnabled = canMultiSelect;
  44570. }
  44571. void TreeView::setOpenCloseButtonsVisible (const bool shouldBeVisible)
  44572. {
  44573. if (openCloseButtonsVisible != shouldBeVisible)
  44574. {
  44575. openCloseButtonsVisible = shouldBeVisible;
  44576. itemsChanged();
  44577. }
  44578. }
  44579. Viewport* TreeView::getViewport() const throw()
  44580. {
  44581. return viewport;
  44582. }
  44583. void TreeView::clearSelectedItems()
  44584. {
  44585. if (rootItem != 0)
  44586. rootItem->deselectAllRecursively();
  44587. }
  44588. int TreeView::getNumSelectedItems() const throw()
  44589. {
  44590. return (rootItem != 0) ? rootItem->countSelectedItemsRecursively() : 0;
  44591. }
  44592. TreeViewItem* TreeView::getSelectedItem (const int index) const throw()
  44593. {
  44594. return (rootItem != 0) ? rootItem->getSelectedItemWithIndex (index) : 0;
  44595. }
  44596. int TreeView::getNumRowsInTree() const
  44597. {
  44598. if (rootItem != 0)
  44599. return rootItem->getNumRows() - (rootItemVisible ? 0 : 1);
  44600. return 0;
  44601. }
  44602. TreeViewItem* TreeView::getItemOnRow (int index) const
  44603. {
  44604. if (! rootItemVisible)
  44605. ++index;
  44606. if (rootItem != 0 && index >= 0)
  44607. return rootItem->getItemOnRow (index);
  44608. return 0;
  44609. }
  44610. TreeViewItem* TreeView::getItemAt (int y) const throw()
  44611. {
  44612. TreeViewContentComponent* const tc = static_cast <TreeViewContentComponent*> (viewport->getViewedComponent());
  44613. Rectangle<int> pos;
  44614. return tc->findItemAt (relativePositionToOtherComponent (tc, Point<int> (0, y)).getY(), pos);
  44615. }
  44616. TreeViewItem* TreeView::findItemFromIdentifierString (const String& identifierString) const
  44617. {
  44618. if (rootItem == 0)
  44619. return 0;
  44620. return rootItem->findItemFromIdentifierString (identifierString);
  44621. }
  44622. XmlElement* TreeView::getOpennessState (const bool alsoIncludeScrollPosition) const
  44623. {
  44624. XmlElement* e = 0;
  44625. if (rootItem != 0)
  44626. {
  44627. e = rootItem->getOpennessState();
  44628. if (e != 0 && alsoIncludeScrollPosition)
  44629. e->setAttribute ("scrollPos", viewport->getViewPositionY());
  44630. }
  44631. return e;
  44632. }
  44633. void TreeView::restoreOpennessState (const XmlElement& newState)
  44634. {
  44635. if (rootItem != 0)
  44636. {
  44637. rootItem->restoreOpennessState (newState);
  44638. if (newState.hasAttribute ("scrollPos"))
  44639. viewport->setViewPosition (viewport->getViewPositionX(),
  44640. newState.getIntAttribute ("scrollPos"));
  44641. }
  44642. }
  44643. void TreeView::paint (Graphics& g)
  44644. {
  44645. g.fillAll (findColour (backgroundColourId));
  44646. }
  44647. void TreeView::resized()
  44648. {
  44649. viewport->setBounds (0, 0, getWidth(), getHeight());
  44650. itemsChanged();
  44651. handleAsyncUpdate();
  44652. }
  44653. void TreeView::enablementChanged()
  44654. {
  44655. repaint();
  44656. }
  44657. void TreeView::moveSelectedRow (int delta)
  44658. {
  44659. if (delta == 0)
  44660. return;
  44661. int rowSelected = 0;
  44662. TreeViewItem* const firstSelected = getSelectedItem (0);
  44663. if (firstSelected != 0)
  44664. rowSelected = firstSelected->getRowNumberInTree();
  44665. rowSelected = jlimit (0, getNumRowsInTree() - 1, rowSelected + delta);
  44666. for (;;)
  44667. {
  44668. TreeViewItem* item = getItemOnRow (rowSelected);
  44669. if (item != 0)
  44670. {
  44671. if (! item->canBeSelected())
  44672. {
  44673. // if the row we want to highlight doesn't allow it, try skipping
  44674. // to the next item..
  44675. const int nextRowToTry = jlimit (0, getNumRowsInTree() - 1,
  44676. rowSelected + (delta < 0 ? -1 : 1));
  44677. if (rowSelected != nextRowToTry)
  44678. {
  44679. rowSelected = nextRowToTry;
  44680. continue;
  44681. }
  44682. else
  44683. {
  44684. break;
  44685. }
  44686. }
  44687. item->setSelected (true, true);
  44688. scrollToKeepItemVisible (item);
  44689. }
  44690. break;
  44691. }
  44692. }
  44693. void TreeView::scrollToKeepItemVisible (TreeViewItem* item)
  44694. {
  44695. if (item != 0 && item->ownerView == this)
  44696. {
  44697. handleAsyncUpdate();
  44698. item = item->getDeepestOpenParentItem();
  44699. int y = item->y;
  44700. int viewTop = viewport->getViewPositionY();
  44701. if (y < viewTop)
  44702. {
  44703. viewport->setViewPosition (viewport->getViewPositionX(), y);
  44704. }
  44705. else if (y + item->itemHeight > viewTop + viewport->getViewHeight())
  44706. {
  44707. viewport->setViewPosition (viewport->getViewPositionX(),
  44708. (y + item->itemHeight) - viewport->getViewHeight());
  44709. }
  44710. }
  44711. }
  44712. bool TreeView::keyPressed (const KeyPress& key)
  44713. {
  44714. if (key.isKeyCode (KeyPress::upKey))
  44715. {
  44716. moveSelectedRow (-1);
  44717. }
  44718. else if (key.isKeyCode (KeyPress::downKey))
  44719. {
  44720. moveSelectedRow (1);
  44721. }
  44722. else if (key.isKeyCode (KeyPress::pageDownKey) || key.isKeyCode (KeyPress::pageUpKey))
  44723. {
  44724. if (rootItem != 0)
  44725. {
  44726. int rowsOnScreen = getHeight() / jmax (1, rootItem->itemHeight);
  44727. if (key.isKeyCode (KeyPress::pageUpKey))
  44728. rowsOnScreen = -rowsOnScreen;
  44729. moveSelectedRow (rowsOnScreen);
  44730. }
  44731. }
  44732. else if (key.isKeyCode (KeyPress::homeKey))
  44733. {
  44734. moveSelectedRow (-0x3fffffff);
  44735. }
  44736. else if (key.isKeyCode (KeyPress::endKey))
  44737. {
  44738. moveSelectedRow (0x3fffffff);
  44739. }
  44740. else if (key.isKeyCode (KeyPress::returnKey))
  44741. {
  44742. TreeViewItem* const firstSelected = getSelectedItem (0);
  44743. if (firstSelected != 0)
  44744. firstSelected->setOpen (! firstSelected->isOpen());
  44745. }
  44746. else if (key.isKeyCode (KeyPress::leftKey))
  44747. {
  44748. TreeViewItem* const firstSelected = getSelectedItem (0);
  44749. if (firstSelected != 0)
  44750. {
  44751. if (firstSelected->isOpen())
  44752. {
  44753. firstSelected->setOpen (false);
  44754. }
  44755. else
  44756. {
  44757. TreeViewItem* parent = firstSelected->parentItem;
  44758. if ((! rootItemVisible) && parent == rootItem)
  44759. parent = 0;
  44760. if (parent != 0)
  44761. {
  44762. parent->setSelected (true, true);
  44763. scrollToKeepItemVisible (parent);
  44764. }
  44765. }
  44766. }
  44767. }
  44768. else if (key.isKeyCode (KeyPress::rightKey))
  44769. {
  44770. TreeViewItem* const firstSelected = getSelectedItem (0);
  44771. if (firstSelected != 0)
  44772. {
  44773. if (firstSelected->isOpen() || ! firstSelected->mightContainSubItems())
  44774. moveSelectedRow (1);
  44775. else
  44776. firstSelected->setOpen (true);
  44777. }
  44778. }
  44779. else
  44780. {
  44781. return false;
  44782. }
  44783. return true;
  44784. }
  44785. void TreeView::itemsChanged() throw()
  44786. {
  44787. needsRecalculating = true;
  44788. repaint();
  44789. triggerAsyncUpdate();
  44790. }
  44791. void TreeView::handleAsyncUpdate()
  44792. {
  44793. if (needsRecalculating)
  44794. {
  44795. needsRecalculating = false;
  44796. const ScopedLock sl (nodeAlterationLock);
  44797. if (rootItem != 0)
  44798. rootItem->updatePositions (rootItemVisible ? 0 : -rootItem->itemHeight);
  44799. viewport->updateComponents();
  44800. if (rootItem != 0)
  44801. {
  44802. viewport->getViewedComponent()
  44803. ->setSize (jmax (viewport->getMaximumVisibleWidth(), rootItem->totalWidth),
  44804. rootItem->totalHeight - (rootItemVisible ? 0 : rootItem->itemHeight));
  44805. }
  44806. else
  44807. {
  44808. viewport->getViewedComponent()->setSize (0, 0);
  44809. }
  44810. }
  44811. }
  44812. class TreeView::InsertPointHighlight : public Component
  44813. {
  44814. public:
  44815. InsertPointHighlight()
  44816. : lastItem (0)
  44817. {
  44818. setSize (100, 12);
  44819. setAlwaysOnTop (true);
  44820. setInterceptsMouseClicks (false, false);
  44821. }
  44822. ~InsertPointHighlight() {}
  44823. void setTargetPosition (TreeViewItem* const item, int insertIndex, const int x, const int y, const int width) throw()
  44824. {
  44825. lastItem = item;
  44826. lastIndex = insertIndex;
  44827. const int offset = getHeight() / 2;
  44828. setBounds (x - offset, y - offset, width - (x - offset), getHeight());
  44829. }
  44830. void paint (Graphics& g)
  44831. {
  44832. Path p;
  44833. const float h = (float) getHeight();
  44834. p.addEllipse (2.0f, 2.0f, h - 4.0f, h - 4.0f);
  44835. p.startNewSubPath (h - 2.0f, h / 2.0f);
  44836. p.lineTo ((float) getWidth(), h / 2.0f);
  44837. g.setColour (findColour (TreeView::dragAndDropIndicatorColourId, true));
  44838. g.strokePath (p, PathStrokeType (2.0f));
  44839. }
  44840. TreeViewItem* lastItem;
  44841. int lastIndex;
  44842. private:
  44843. InsertPointHighlight (const InsertPointHighlight&);
  44844. InsertPointHighlight& operator= (const InsertPointHighlight&);
  44845. };
  44846. class TreeView::TargetGroupHighlight : public Component
  44847. {
  44848. public:
  44849. TargetGroupHighlight()
  44850. {
  44851. setAlwaysOnTop (true);
  44852. setInterceptsMouseClicks (false, false);
  44853. }
  44854. ~TargetGroupHighlight() {}
  44855. void setTargetPosition (TreeViewItem* const item) throw()
  44856. {
  44857. Rectangle<int> r (item->getItemPosition (true));
  44858. r.setHeight (item->getItemHeight());
  44859. setBounds (r);
  44860. }
  44861. void paint (Graphics& g)
  44862. {
  44863. g.setColour (findColour (TreeView::dragAndDropIndicatorColourId, true));
  44864. g.drawRoundedRectangle (1.0f, 1.0f, getWidth() - 2.0f, getHeight() - 2.0f, 3.0f, 2.0f);
  44865. }
  44866. private:
  44867. TargetGroupHighlight (const TargetGroupHighlight&);
  44868. TargetGroupHighlight& operator= (const TargetGroupHighlight&);
  44869. };
  44870. void TreeView::showDragHighlight (TreeViewItem* item, int insertIndex, int x, int y) throw()
  44871. {
  44872. beginDragAutoRepeat (1000 / 30);
  44873. if (dragInsertPointHighlight == 0)
  44874. {
  44875. addAndMakeVisible (dragInsertPointHighlight = new InsertPointHighlight());
  44876. addAndMakeVisible (dragTargetGroupHighlight = new TargetGroupHighlight());
  44877. }
  44878. dragInsertPointHighlight->setTargetPosition (item, insertIndex, x, y, viewport->getViewWidth());
  44879. dragTargetGroupHighlight->setTargetPosition (item);
  44880. }
  44881. void TreeView::hideDragHighlight() throw()
  44882. {
  44883. deleteAndZero (dragInsertPointHighlight);
  44884. deleteAndZero (dragTargetGroupHighlight);
  44885. }
  44886. TreeViewItem* TreeView::getInsertPosition (int& x, int& y, int& insertIndex,
  44887. const StringArray& files, const String& sourceDescription,
  44888. Component* sourceComponent) const throw()
  44889. {
  44890. insertIndex = 0;
  44891. TreeViewItem* item = getItemAt (y);
  44892. if (item == 0)
  44893. return 0;
  44894. Rectangle<int> itemPos (item->getItemPosition (true));
  44895. insertIndex = item->getIndexInParent();
  44896. const int oldY = y;
  44897. y = itemPos.getY();
  44898. if (item->getNumSubItems() == 0 || ! item->isOpen())
  44899. {
  44900. if (files.size() > 0 ? item->isInterestedInFileDrag (files)
  44901. : item->isInterestedInDragSource (sourceDescription, sourceComponent))
  44902. {
  44903. // Check if we're trying to drag into an empty group item..
  44904. if (oldY > itemPos.getY() + itemPos.getHeight() / 4
  44905. && oldY < itemPos.getBottom() - itemPos.getHeight() / 4)
  44906. {
  44907. insertIndex = 0;
  44908. x = itemPos.getX() + getIndentSize();
  44909. y = itemPos.getBottom();
  44910. return item;
  44911. }
  44912. }
  44913. }
  44914. if (oldY > itemPos.getCentreY())
  44915. {
  44916. y += item->getItemHeight();
  44917. while (item->isLastOfSiblings() && item->parentItem != 0
  44918. && item->parentItem->parentItem != 0)
  44919. {
  44920. if (x > itemPos.getX())
  44921. break;
  44922. item = item->parentItem;
  44923. itemPos = item->getItemPosition (true);
  44924. insertIndex = item->getIndexInParent();
  44925. }
  44926. ++insertIndex;
  44927. }
  44928. x = itemPos.getX();
  44929. return item->parentItem;
  44930. }
  44931. void TreeView::handleDrag (const StringArray& files, const String& sourceDescription, Component* sourceComponent, int x, int y)
  44932. {
  44933. const bool scrolled = viewport->autoScroll (x, y, 20, 10);
  44934. int insertIndex;
  44935. TreeViewItem* const item = getInsertPosition (x, y, insertIndex, files, sourceDescription, sourceComponent);
  44936. if (item != 0)
  44937. {
  44938. if (scrolled || dragInsertPointHighlight == 0
  44939. || dragInsertPointHighlight->lastItem != item
  44940. || dragInsertPointHighlight->lastIndex != insertIndex)
  44941. {
  44942. if (files.size() > 0 ? item->isInterestedInFileDrag (files)
  44943. : item->isInterestedInDragSource (sourceDescription, sourceComponent))
  44944. showDragHighlight (item, insertIndex, x, y);
  44945. else
  44946. hideDragHighlight();
  44947. }
  44948. }
  44949. else
  44950. {
  44951. hideDragHighlight();
  44952. }
  44953. }
  44954. void TreeView::handleDrop (const StringArray& files, const String& sourceDescription, Component* sourceComponent, int x, int y)
  44955. {
  44956. hideDragHighlight();
  44957. int insertIndex;
  44958. TreeViewItem* const item = getInsertPosition (x, y, insertIndex, files, sourceDescription, sourceComponent);
  44959. if (item != 0)
  44960. {
  44961. if (files.size() > 0)
  44962. {
  44963. if (item->isInterestedInFileDrag (files))
  44964. item->filesDropped (files, insertIndex);
  44965. }
  44966. else
  44967. {
  44968. if (item->isInterestedInDragSource (sourceDescription, sourceComponent))
  44969. item->itemDropped (sourceDescription, sourceComponent, insertIndex);
  44970. }
  44971. }
  44972. }
  44973. bool TreeView::isInterestedInFileDrag (const StringArray&)
  44974. {
  44975. return true;
  44976. }
  44977. void TreeView::fileDragEnter (const StringArray& files, int x, int y)
  44978. {
  44979. fileDragMove (files, x, y);
  44980. }
  44981. void TreeView::fileDragMove (const StringArray& files, int x, int y)
  44982. {
  44983. handleDrag (files, String::empty, 0, x, y);
  44984. }
  44985. void TreeView::fileDragExit (const StringArray&)
  44986. {
  44987. hideDragHighlight();
  44988. }
  44989. void TreeView::filesDropped (const StringArray& files, int x, int y)
  44990. {
  44991. handleDrop (files, String::empty, 0, x, y);
  44992. }
  44993. bool TreeView::isInterestedInDragSource (const String& /*sourceDescription*/, Component* /*sourceComponent*/)
  44994. {
  44995. return true;
  44996. }
  44997. void TreeView::itemDragEnter (const String& sourceDescription, Component* sourceComponent, int x, int y)
  44998. {
  44999. itemDragMove (sourceDescription, sourceComponent, x, y);
  45000. }
  45001. void TreeView::itemDragMove (const String& sourceDescription, Component* sourceComponent, int x, int y)
  45002. {
  45003. handleDrag (StringArray(), sourceDescription, sourceComponent, x, y);
  45004. }
  45005. void TreeView::itemDragExit (const String& /*sourceDescription*/, Component* /*sourceComponent*/)
  45006. {
  45007. hideDragHighlight();
  45008. }
  45009. void TreeView::itemDropped (const String& sourceDescription, Component* sourceComponent, int x, int y)
  45010. {
  45011. handleDrop (StringArray(), sourceDescription, sourceComponent, x, y);
  45012. }
  45013. enum TreeViewOpenness
  45014. {
  45015. opennessDefault = 0,
  45016. opennessClosed = 1,
  45017. opennessOpen = 2
  45018. };
  45019. TreeViewItem::TreeViewItem()
  45020. : ownerView (0),
  45021. parentItem (0),
  45022. y (0),
  45023. itemHeight (0),
  45024. totalHeight (0),
  45025. selected (false),
  45026. redrawNeeded (true),
  45027. drawLinesInside (true),
  45028. drawsInLeftMargin (false),
  45029. openness (opennessDefault)
  45030. {
  45031. static int nextUID = 0;
  45032. uid = nextUID++;
  45033. }
  45034. TreeViewItem::~TreeViewItem()
  45035. {
  45036. }
  45037. const String TreeViewItem::getUniqueName() const
  45038. {
  45039. return String::empty;
  45040. }
  45041. void TreeViewItem::itemOpennessChanged (bool)
  45042. {
  45043. }
  45044. int TreeViewItem::getNumSubItems() const throw()
  45045. {
  45046. return subItems.size();
  45047. }
  45048. TreeViewItem* TreeViewItem::getSubItem (const int index) const throw()
  45049. {
  45050. return subItems [index];
  45051. }
  45052. void TreeViewItem::clearSubItems()
  45053. {
  45054. if (subItems.size() > 0)
  45055. {
  45056. if (ownerView != 0)
  45057. {
  45058. const ScopedLock sl (ownerView->nodeAlterationLock);
  45059. subItems.clear();
  45060. treeHasChanged();
  45061. }
  45062. else
  45063. {
  45064. subItems.clear();
  45065. }
  45066. }
  45067. }
  45068. void TreeViewItem::addSubItem (TreeViewItem* const newItem, const int insertPosition)
  45069. {
  45070. if (newItem != 0)
  45071. {
  45072. newItem->parentItem = this;
  45073. newItem->setOwnerView (ownerView);
  45074. newItem->y = 0;
  45075. newItem->itemHeight = newItem->getItemHeight();
  45076. newItem->totalHeight = 0;
  45077. newItem->itemWidth = newItem->getItemWidth();
  45078. newItem->totalWidth = 0;
  45079. if (ownerView != 0)
  45080. {
  45081. const ScopedLock sl (ownerView->nodeAlterationLock);
  45082. subItems.insert (insertPosition, newItem);
  45083. treeHasChanged();
  45084. if (newItem->isOpen())
  45085. newItem->itemOpennessChanged (true);
  45086. }
  45087. else
  45088. {
  45089. subItems.insert (insertPosition, newItem);
  45090. if (newItem->isOpen())
  45091. newItem->itemOpennessChanged (true);
  45092. }
  45093. }
  45094. }
  45095. void TreeViewItem::removeSubItem (const int index, const bool deleteItem)
  45096. {
  45097. if (ownerView != 0)
  45098. {
  45099. const ScopedLock sl (ownerView->nodeAlterationLock);
  45100. if (((unsigned int) index) < (unsigned int) subItems.size())
  45101. {
  45102. subItems.remove (index, deleteItem);
  45103. treeHasChanged();
  45104. }
  45105. }
  45106. else
  45107. {
  45108. subItems.remove (index, deleteItem);
  45109. }
  45110. }
  45111. bool TreeViewItem::isOpen() const throw()
  45112. {
  45113. if (openness == opennessDefault)
  45114. return ownerView != 0 && ownerView->defaultOpenness;
  45115. else
  45116. return openness == opennessOpen;
  45117. }
  45118. void TreeViewItem::setOpen (const bool shouldBeOpen)
  45119. {
  45120. if (isOpen() != shouldBeOpen)
  45121. {
  45122. openness = shouldBeOpen ? opennessOpen
  45123. : opennessClosed;
  45124. treeHasChanged();
  45125. itemOpennessChanged (isOpen());
  45126. }
  45127. }
  45128. bool TreeViewItem::isSelected() const throw()
  45129. {
  45130. return selected;
  45131. }
  45132. void TreeViewItem::deselectAllRecursively()
  45133. {
  45134. setSelected (false, false);
  45135. for (int i = 0; i < subItems.size(); ++i)
  45136. subItems.getUnchecked(i)->deselectAllRecursively();
  45137. }
  45138. void TreeViewItem::setSelected (const bool shouldBeSelected,
  45139. const bool deselectOtherItemsFirst)
  45140. {
  45141. if (shouldBeSelected && ! canBeSelected())
  45142. return;
  45143. if (deselectOtherItemsFirst)
  45144. getTopLevelItem()->deselectAllRecursively();
  45145. if (shouldBeSelected != selected)
  45146. {
  45147. selected = shouldBeSelected;
  45148. if (ownerView != 0)
  45149. ownerView->repaint();
  45150. itemSelectionChanged (shouldBeSelected);
  45151. }
  45152. }
  45153. void TreeViewItem::paintItem (Graphics&, int, int)
  45154. {
  45155. }
  45156. void TreeViewItem::paintOpenCloseButton (Graphics& g, int width, int height, bool isMouseOver)
  45157. {
  45158. ownerView->getLookAndFeel()
  45159. .drawTreeviewPlusMinusBox (g, 0, 0, width, height, ! isOpen(), isMouseOver);
  45160. }
  45161. void TreeViewItem::itemClicked (const MouseEvent&)
  45162. {
  45163. }
  45164. void TreeViewItem::itemDoubleClicked (const MouseEvent&)
  45165. {
  45166. if (mightContainSubItems())
  45167. setOpen (! isOpen());
  45168. }
  45169. void TreeViewItem::itemSelectionChanged (bool)
  45170. {
  45171. }
  45172. const String TreeViewItem::getTooltip()
  45173. {
  45174. return String::empty;
  45175. }
  45176. const String TreeViewItem::getDragSourceDescription()
  45177. {
  45178. return String::empty;
  45179. }
  45180. bool TreeViewItem::isInterestedInFileDrag (const StringArray&)
  45181. {
  45182. return false;
  45183. }
  45184. void TreeViewItem::filesDropped (const StringArray& /*files*/, int /*insertIndex*/)
  45185. {
  45186. }
  45187. bool TreeViewItem::isInterestedInDragSource (const String& /*sourceDescription*/, Component* /*sourceComponent*/)
  45188. {
  45189. return false;
  45190. }
  45191. void TreeViewItem::itemDropped (const String& /*sourceDescription*/, Component* /*sourceComponent*/, int /*insertIndex*/)
  45192. {
  45193. }
  45194. const Rectangle<int> TreeViewItem::getItemPosition (const bool relativeToTreeViewTopLeft) const throw()
  45195. {
  45196. const int indentX = getIndentX();
  45197. int width = itemWidth;
  45198. if (ownerView != 0 && width < 0)
  45199. width = ownerView->viewport->getViewWidth() - indentX;
  45200. Rectangle<int> r (indentX, y, jmax (0, width), totalHeight);
  45201. if (relativeToTreeViewTopLeft)
  45202. r -= ownerView->viewport->getViewPosition();
  45203. return r;
  45204. }
  45205. void TreeViewItem::treeHasChanged() const throw()
  45206. {
  45207. if (ownerView != 0)
  45208. ownerView->itemsChanged();
  45209. }
  45210. void TreeViewItem::repaintItem() const
  45211. {
  45212. if (ownerView != 0 && areAllParentsOpen())
  45213. {
  45214. const Rectangle<int> r (getItemPosition (true));
  45215. ownerView->viewport->repaint (0, r.getY(), r.getRight(), r.getHeight());
  45216. }
  45217. }
  45218. bool TreeViewItem::areAllParentsOpen() const throw()
  45219. {
  45220. return parentItem == 0
  45221. || (parentItem->isOpen() && parentItem->areAllParentsOpen());
  45222. }
  45223. void TreeViewItem::updatePositions (int newY)
  45224. {
  45225. y = newY;
  45226. itemHeight = getItemHeight();
  45227. totalHeight = itemHeight;
  45228. itemWidth = getItemWidth();
  45229. totalWidth = jmax (itemWidth, 0) + getIndentX();
  45230. if (isOpen())
  45231. {
  45232. newY += totalHeight;
  45233. for (int i = 0; i < subItems.size(); ++i)
  45234. {
  45235. TreeViewItem* const ti = subItems.getUnchecked(i);
  45236. ti->updatePositions (newY);
  45237. newY += ti->totalHeight;
  45238. totalHeight += ti->totalHeight;
  45239. totalWidth = jmax (totalWidth, ti->totalWidth);
  45240. }
  45241. }
  45242. }
  45243. TreeViewItem* TreeViewItem::getDeepestOpenParentItem() throw()
  45244. {
  45245. TreeViewItem* result = this;
  45246. TreeViewItem* item = this;
  45247. while (item->parentItem != 0)
  45248. {
  45249. item = item->parentItem;
  45250. if (! item->isOpen())
  45251. result = item;
  45252. }
  45253. return result;
  45254. }
  45255. void TreeViewItem::setOwnerView (TreeView* const newOwner) throw()
  45256. {
  45257. ownerView = newOwner;
  45258. for (int i = subItems.size(); --i >= 0;)
  45259. subItems.getUnchecked(i)->setOwnerView (newOwner);
  45260. }
  45261. int TreeViewItem::getIndentX() const throw()
  45262. {
  45263. const int indentWidth = ownerView->getIndentSize();
  45264. int x = ownerView->rootItemVisible ? indentWidth : 0;
  45265. if (! ownerView->openCloseButtonsVisible)
  45266. x -= indentWidth;
  45267. TreeViewItem* p = parentItem;
  45268. while (p != 0)
  45269. {
  45270. x += indentWidth;
  45271. p = p->parentItem;
  45272. }
  45273. return x;
  45274. }
  45275. void TreeViewItem::setDrawsInLeftMargin (bool canDrawInLeftMargin) throw()
  45276. {
  45277. drawsInLeftMargin = canDrawInLeftMargin;
  45278. }
  45279. void TreeViewItem::paintRecursively (Graphics& g, int width)
  45280. {
  45281. jassert (ownerView != 0);
  45282. if (ownerView == 0)
  45283. return;
  45284. const int indent = getIndentX();
  45285. const int itemW = itemWidth < 0 ? width - indent : itemWidth;
  45286. g.setColour (ownerView->findColour (TreeView::linesColourId));
  45287. const float halfH = itemHeight * 0.5f;
  45288. int depth = 0;
  45289. TreeViewItem* p = parentItem;
  45290. while (p != 0)
  45291. {
  45292. ++depth;
  45293. p = p->parentItem;
  45294. }
  45295. if (! ownerView->rootItemVisible)
  45296. --depth;
  45297. const int indentWidth = ownerView->getIndentSize();
  45298. if (depth >= 0 && ownerView->openCloseButtonsVisible)
  45299. {
  45300. float x = (depth + 0.5f) * indentWidth;
  45301. if (depth >= 0)
  45302. {
  45303. if (parentItem != 0 && parentItem->drawLinesInside)
  45304. g.drawLine (x, 0, x, isLastOfSiblings() ? halfH : (float) itemHeight);
  45305. if ((parentItem != 0 && parentItem->drawLinesInside)
  45306. || (parentItem == 0 && drawLinesInside))
  45307. g.drawLine (x, halfH, x + indentWidth / 2, halfH);
  45308. }
  45309. p = parentItem;
  45310. int d = depth;
  45311. while (p != 0 && --d >= 0)
  45312. {
  45313. x -= (float) indentWidth;
  45314. if ((p->parentItem == 0 || p->parentItem->drawLinesInside)
  45315. && ! p->isLastOfSiblings())
  45316. {
  45317. g.drawLine (x, 0, x, (float) itemHeight);
  45318. }
  45319. p = p->parentItem;
  45320. }
  45321. if (mightContainSubItems())
  45322. {
  45323. g.saveState();
  45324. g.setOrigin (depth * indentWidth, 0);
  45325. g.reduceClipRegion (0, 0, indentWidth, itemHeight);
  45326. paintOpenCloseButton (g, indentWidth, itemHeight,
  45327. static_cast <TreeViewContentComponent*> (ownerView->viewport->getViewedComponent())
  45328. ->isMouseOverButton (this));
  45329. g.restoreState();
  45330. }
  45331. }
  45332. {
  45333. g.saveState();
  45334. g.setOrigin (indent, 0);
  45335. if (g.reduceClipRegion (drawsInLeftMargin ? -indent : 0, 0,
  45336. drawsInLeftMargin ? itemW + indent : itemW, itemHeight))
  45337. paintItem (g, itemW, itemHeight);
  45338. g.restoreState();
  45339. }
  45340. if (isOpen())
  45341. {
  45342. const Rectangle<int> clip (g.getClipBounds());
  45343. for (int i = 0; i < subItems.size(); ++i)
  45344. {
  45345. TreeViewItem* const ti = subItems.getUnchecked(i);
  45346. const int relY = ti->y - y;
  45347. if (relY >= clip.getBottom())
  45348. break;
  45349. if (relY + ti->totalHeight >= clip.getY())
  45350. {
  45351. g.saveState();
  45352. g.setOrigin (0, relY);
  45353. if (g.reduceClipRegion (0, 0, width, ti->totalHeight))
  45354. ti->paintRecursively (g, width);
  45355. g.restoreState();
  45356. }
  45357. }
  45358. }
  45359. }
  45360. bool TreeViewItem::isLastOfSiblings() const throw()
  45361. {
  45362. return parentItem == 0
  45363. || parentItem->subItems.getLast() == this;
  45364. }
  45365. int TreeViewItem::getIndexInParent() const throw()
  45366. {
  45367. if (parentItem == 0)
  45368. return 0;
  45369. return parentItem->subItems.indexOf (this);
  45370. }
  45371. TreeViewItem* TreeViewItem::getTopLevelItem() throw()
  45372. {
  45373. return (parentItem == 0) ? this
  45374. : parentItem->getTopLevelItem();
  45375. }
  45376. int TreeViewItem::getNumRows() const throw()
  45377. {
  45378. int num = 1;
  45379. if (isOpen())
  45380. {
  45381. for (int i = subItems.size(); --i >= 0;)
  45382. num += subItems.getUnchecked(i)->getNumRows();
  45383. }
  45384. return num;
  45385. }
  45386. TreeViewItem* TreeViewItem::getItemOnRow (int index) throw()
  45387. {
  45388. if (index == 0)
  45389. return this;
  45390. if (index > 0 && isOpen())
  45391. {
  45392. --index;
  45393. for (int i = 0; i < subItems.size(); ++i)
  45394. {
  45395. TreeViewItem* const item = subItems.getUnchecked(i);
  45396. if (index == 0)
  45397. return item;
  45398. const int numRows = item->getNumRows();
  45399. if (numRows > index)
  45400. return item->getItemOnRow (index);
  45401. index -= numRows;
  45402. }
  45403. }
  45404. return 0;
  45405. }
  45406. TreeViewItem* TreeViewItem::findItemRecursively (int targetY) throw()
  45407. {
  45408. if (((unsigned int) targetY) < (unsigned int) totalHeight)
  45409. {
  45410. const int h = itemHeight;
  45411. if (targetY < h)
  45412. return this;
  45413. if (isOpen())
  45414. {
  45415. targetY -= h;
  45416. for (int i = 0; i < subItems.size(); ++i)
  45417. {
  45418. TreeViewItem* const ti = subItems.getUnchecked(i);
  45419. if (targetY < ti->totalHeight)
  45420. return ti->findItemRecursively (targetY);
  45421. targetY -= ti->totalHeight;
  45422. }
  45423. }
  45424. }
  45425. return 0;
  45426. }
  45427. int TreeViewItem::countSelectedItemsRecursively() const throw()
  45428. {
  45429. int total = 0;
  45430. if (isSelected())
  45431. ++total;
  45432. for (int i = subItems.size(); --i >= 0;)
  45433. total += subItems.getUnchecked(i)->countSelectedItemsRecursively();
  45434. return total;
  45435. }
  45436. TreeViewItem* TreeViewItem::getSelectedItemWithIndex (int index) throw()
  45437. {
  45438. if (isSelected())
  45439. {
  45440. if (index == 0)
  45441. return this;
  45442. --index;
  45443. }
  45444. if (index >= 0)
  45445. {
  45446. for (int i = 0; i < subItems.size(); ++i)
  45447. {
  45448. TreeViewItem* const item = subItems.getUnchecked(i);
  45449. TreeViewItem* const found = item->getSelectedItemWithIndex (index);
  45450. if (found != 0)
  45451. return found;
  45452. index -= item->countSelectedItemsRecursively();
  45453. }
  45454. }
  45455. return 0;
  45456. }
  45457. int TreeViewItem::getRowNumberInTree() const throw()
  45458. {
  45459. if (parentItem != 0 && ownerView != 0)
  45460. {
  45461. int n = 1 + parentItem->getRowNumberInTree();
  45462. int ourIndex = parentItem->subItems.indexOf (this);
  45463. jassert (ourIndex >= 0);
  45464. while (--ourIndex >= 0)
  45465. n += parentItem->subItems [ourIndex]->getNumRows();
  45466. if (parentItem->parentItem == 0
  45467. && ! ownerView->rootItemVisible)
  45468. --n;
  45469. return n;
  45470. }
  45471. else
  45472. {
  45473. return 0;
  45474. }
  45475. }
  45476. void TreeViewItem::setLinesDrawnForSubItems (const bool drawLines) throw()
  45477. {
  45478. drawLinesInside = drawLines;
  45479. }
  45480. TreeViewItem* TreeViewItem::getNextVisibleItem (const bool recurse) const throw()
  45481. {
  45482. if (recurse && isOpen() && subItems.size() > 0)
  45483. return subItems [0];
  45484. if (parentItem != 0)
  45485. {
  45486. const int nextIndex = parentItem->subItems.indexOf (this) + 1;
  45487. if (nextIndex >= parentItem->subItems.size())
  45488. return parentItem->getNextVisibleItem (false);
  45489. return parentItem->subItems [nextIndex];
  45490. }
  45491. return 0;
  45492. }
  45493. const String TreeViewItem::getItemIdentifierString() const
  45494. {
  45495. String s;
  45496. if (parentItem != 0)
  45497. s = parentItem->getItemIdentifierString();
  45498. return s + "/" + getUniqueName().replaceCharacter ('/', '\\');
  45499. }
  45500. TreeViewItem* TreeViewItem::findItemFromIdentifierString (const String& identifierString)
  45501. {
  45502. const String thisId (getUniqueName());
  45503. if (thisId == identifierString)
  45504. return this;
  45505. if (identifierString.startsWith (thisId + "/"))
  45506. {
  45507. const String remainingPath (identifierString.substring (thisId.length() + 1));
  45508. bool wasOpen = isOpen();
  45509. setOpen (true);
  45510. for (int i = subItems.size(); --i >= 0;)
  45511. {
  45512. TreeViewItem* item = subItems.getUnchecked(i)->findItemFromIdentifierString (remainingPath);
  45513. if (item != 0)
  45514. return item;
  45515. }
  45516. setOpen (wasOpen);
  45517. }
  45518. return 0;
  45519. }
  45520. void TreeViewItem::restoreOpennessState (const XmlElement& e) throw()
  45521. {
  45522. if (e.hasTagName ("CLOSED"))
  45523. {
  45524. setOpen (false);
  45525. }
  45526. else if (e.hasTagName ("OPEN"))
  45527. {
  45528. setOpen (true);
  45529. forEachXmlChildElement (e, n)
  45530. {
  45531. const String id (n->getStringAttribute ("id"));
  45532. for (int i = 0; i < subItems.size(); ++i)
  45533. {
  45534. TreeViewItem* const ti = subItems.getUnchecked(i);
  45535. if (ti->getUniqueName() == id)
  45536. {
  45537. ti->restoreOpennessState (*n);
  45538. break;
  45539. }
  45540. }
  45541. }
  45542. }
  45543. }
  45544. XmlElement* TreeViewItem::getOpennessState() const throw()
  45545. {
  45546. const String name (getUniqueName());
  45547. if (name.isNotEmpty())
  45548. {
  45549. XmlElement* e;
  45550. if (isOpen())
  45551. {
  45552. e = new XmlElement ("OPEN");
  45553. for (int i = 0; i < subItems.size(); ++i)
  45554. e->addChildElement (subItems.getUnchecked(i)->getOpennessState());
  45555. }
  45556. else
  45557. {
  45558. e = new XmlElement ("CLOSED");
  45559. }
  45560. e->setAttribute ("id", name);
  45561. return e;
  45562. }
  45563. else
  45564. {
  45565. // trying to save the openness for an element that has no name - this won't
  45566. // work because it needs the names to identify what to open.
  45567. jassertfalse
  45568. }
  45569. return 0;
  45570. }
  45571. END_JUCE_NAMESPACE
  45572. /*** End of inlined file: juce_TreeView.cpp ***/
  45573. /*** Start of inlined file: juce_DirectoryContentsDisplayComponent.cpp ***/
  45574. BEGIN_JUCE_NAMESPACE
  45575. DirectoryContentsDisplayComponent::DirectoryContentsDisplayComponent (DirectoryContentsList& listToShow)
  45576. : fileList (listToShow)
  45577. {
  45578. }
  45579. DirectoryContentsDisplayComponent::~DirectoryContentsDisplayComponent()
  45580. {
  45581. }
  45582. FileBrowserListener::~FileBrowserListener()
  45583. {
  45584. }
  45585. void DirectoryContentsDisplayComponent::addListener (FileBrowserListener* const listener)
  45586. {
  45587. listeners.add (listener);
  45588. }
  45589. void DirectoryContentsDisplayComponent::removeListener (FileBrowserListener* const listener)
  45590. {
  45591. listeners.remove (listener);
  45592. }
  45593. void DirectoryContentsDisplayComponent::sendSelectionChangeMessage()
  45594. {
  45595. Component::BailOutChecker checker (dynamic_cast <Component*> (this));
  45596. listeners.callChecked (checker, &FileBrowserListener::selectionChanged);
  45597. }
  45598. void DirectoryContentsDisplayComponent::sendMouseClickMessage (const File& file, const MouseEvent& e)
  45599. {
  45600. if (fileList.getDirectory().exists())
  45601. {
  45602. Component::BailOutChecker checker (dynamic_cast <Component*> (this));
  45603. listeners.callChecked (checker, &FileBrowserListener::fileClicked, file, e);
  45604. }
  45605. }
  45606. void DirectoryContentsDisplayComponent::sendDoubleClickMessage (const File& file)
  45607. {
  45608. if (fileList.getDirectory().exists())
  45609. {
  45610. Component::BailOutChecker checker (dynamic_cast <Component*> (this));
  45611. listeners.callChecked (checker, &FileBrowserListener::fileDoubleClicked, file);
  45612. }
  45613. }
  45614. END_JUCE_NAMESPACE
  45615. /*** End of inlined file: juce_DirectoryContentsDisplayComponent.cpp ***/
  45616. /*** Start of inlined file: juce_DirectoryContentsList.cpp ***/
  45617. BEGIN_JUCE_NAMESPACE
  45618. DirectoryContentsList::DirectoryContentsList (const FileFilter* const fileFilter_,
  45619. TimeSliceThread& thread_)
  45620. : fileFilter (fileFilter_),
  45621. thread (thread_),
  45622. fileTypeFlags (File::ignoreHiddenFiles | File::findFiles),
  45623. fileFindHandle (0),
  45624. shouldStop (true)
  45625. {
  45626. }
  45627. DirectoryContentsList::~DirectoryContentsList()
  45628. {
  45629. clear();
  45630. }
  45631. void DirectoryContentsList::setIgnoresHiddenFiles (const bool shouldIgnoreHiddenFiles)
  45632. {
  45633. setTypeFlags (shouldIgnoreHiddenFiles ? (fileTypeFlags | File::ignoreHiddenFiles)
  45634. : (fileTypeFlags & ~File::ignoreHiddenFiles));
  45635. }
  45636. bool DirectoryContentsList::ignoresHiddenFiles() const
  45637. {
  45638. return (fileTypeFlags & File::ignoreHiddenFiles) != 0;
  45639. }
  45640. const File& DirectoryContentsList::getDirectory() const
  45641. {
  45642. return root;
  45643. }
  45644. void DirectoryContentsList::setDirectory (const File& directory,
  45645. const bool includeDirectories,
  45646. const bool includeFiles)
  45647. {
  45648. jassert (includeDirectories || includeFiles); // you have to speciify at least one of these!
  45649. if (directory != root)
  45650. {
  45651. clear();
  45652. root = directory;
  45653. // (this forces a refresh when setTypeFlags() is called, rather than triggering two refreshes)
  45654. fileTypeFlags &= ~(File::findDirectories | File::findFiles);
  45655. }
  45656. int newFlags = fileTypeFlags;
  45657. if (includeDirectories) newFlags |= File::findDirectories; else newFlags &= ~File::findDirectories;
  45658. if (includeFiles) newFlags |= File::findFiles; else newFlags &= ~File::findFiles;
  45659. setTypeFlags (newFlags);
  45660. }
  45661. void DirectoryContentsList::setTypeFlags (const int newFlags)
  45662. {
  45663. if (fileTypeFlags != newFlags)
  45664. {
  45665. fileTypeFlags = newFlags;
  45666. refresh();
  45667. }
  45668. }
  45669. void DirectoryContentsList::clear()
  45670. {
  45671. shouldStop = true;
  45672. thread.removeTimeSliceClient (this);
  45673. fileFindHandle = 0;
  45674. if (files.size() > 0)
  45675. {
  45676. files.clear();
  45677. changed();
  45678. }
  45679. }
  45680. void DirectoryContentsList::refresh()
  45681. {
  45682. clear();
  45683. if (root.isDirectory())
  45684. {
  45685. fileFindHandle = new DirectoryIterator (root, false, "*", fileTypeFlags);
  45686. shouldStop = false;
  45687. thread.addTimeSliceClient (this);
  45688. }
  45689. }
  45690. int DirectoryContentsList::getNumFiles() const
  45691. {
  45692. return files.size();
  45693. }
  45694. bool DirectoryContentsList::getFileInfo (const int index,
  45695. FileInfo& result) const
  45696. {
  45697. const ScopedLock sl (fileListLock);
  45698. const FileInfo* const info = files [index];
  45699. if (info != 0)
  45700. {
  45701. result = *info;
  45702. return true;
  45703. }
  45704. return false;
  45705. }
  45706. const File DirectoryContentsList::getFile (const int index) const
  45707. {
  45708. const ScopedLock sl (fileListLock);
  45709. const FileInfo* const info = files [index];
  45710. if (info != 0)
  45711. return root.getChildFile (info->filename);
  45712. return File::nonexistent;
  45713. }
  45714. bool DirectoryContentsList::isStillLoading() const
  45715. {
  45716. return fileFindHandle != 0;
  45717. }
  45718. void DirectoryContentsList::changed()
  45719. {
  45720. sendChangeMessage (this);
  45721. }
  45722. bool DirectoryContentsList::useTimeSlice()
  45723. {
  45724. const uint32 startTime = Time::getApproximateMillisecondCounter();
  45725. bool hasChanged = false;
  45726. for (int i = 100; --i >= 0;)
  45727. {
  45728. if (! checkNextFile (hasChanged))
  45729. {
  45730. if (hasChanged)
  45731. changed();
  45732. return false;
  45733. }
  45734. if (shouldStop || (Time::getApproximateMillisecondCounter() > startTime + 150))
  45735. break;
  45736. }
  45737. if (hasChanged)
  45738. changed();
  45739. return true;
  45740. }
  45741. bool DirectoryContentsList::checkNextFile (bool& hasChanged)
  45742. {
  45743. if (fileFindHandle != 0)
  45744. {
  45745. bool fileFoundIsDir, isHidden, isReadOnly;
  45746. int64 fileSize;
  45747. Time modTime, creationTime;
  45748. if (fileFindHandle->next (&fileFoundIsDir, &isHidden, &fileSize,
  45749. &modTime, &creationTime, &isReadOnly))
  45750. {
  45751. if (addFile (fileFindHandle->getFile(), fileFoundIsDir,
  45752. fileSize, modTime, creationTime, isReadOnly))
  45753. {
  45754. hasChanged = true;
  45755. }
  45756. return true;
  45757. }
  45758. else
  45759. {
  45760. fileFindHandle = 0;
  45761. }
  45762. }
  45763. return false;
  45764. }
  45765. int DirectoryContentsList::compareElements (const DirectoryContentsList::FileInfo* const first,
  45766. const DirectoryContentsList::FileInfo* const second)
  45767. {
  45768. #if JUCE_WINDOWS
  45769. if (first->isDirectory != second->isDirectory)
  45770. return first->isDirectory ? -1 : 1;
  45771. #endif
  45772. return first->filename.compareIgnoreCase (second->filename);
  45773. }
  45774. bool DirectoryContentsList::addFile (const File& file,
  45775. const bool isDir,
  45776. const int64 fileSize,
  45777. const Time& modTime,
  45778. const Time& creationTime,
  45779. const bool isReadOnly)
  45780. {
  45781. if (fileFilter == 0
  45782. || ((! isDir) && fileFilter->isFileSuitable (file))
  45783. || (isDir && fileFilter->isDirectorySuitable (file)))
  45784. {
  45785. ScopedPointer <FileInfo> info (new FileInfo());
  45786. info->filename = file.getFileName();
  45787. info->fileSize = fileSize;
  45788. info->modificationTime = modTime;
  45789. info->creationTime = creationTime;
  45790. info->isDirectory = isDir;
  45791. info->isReadOnly = isReadOnly;
  45792. const ScopedLock sl (fileListLock);
  45793. for (int i = files.size(); --i >= 0;)
  45794. if (files.getUnchecked(i)->filename == info->filename)
  45795. return false;
  45796. files.addSorted (*this, info.release());
  45797. return true;
  45798. }
  45799. return false;
  45800. }
  45801. END_JUCE_NAMESPACE
  45802. /*** End of inlined file: juce_DirectoryContentsList.cpp ***/
  45803. /*** Start of inlined file: juce_FileBrowserComponent.cpp ***/
  45804. BEGIN_JUCE_NAMESPACE
  45805. FileBrowserComponent::FileBrowserComponent (int flags_,
  45806. const File& initialFileOrDirectory,
  45807. const FileFilter* fileFilter_,
  45808. FilePreviewComponent* previewComp_)
  45809. : FileFilter (String::empty),
  45810. fileFilter (fileFilter_),
  45811. flags (flags_),
  45812. previewComp (previewComp_),
  45813. thread ("Juce FileBrowser")
  45814. {
  45815. // You need to specify one or other of the open/save flags..
  45816. jassert ((flags & (saveMode | openMode)) != 0);
  45817. jassert ((flags & (saveMode | openMode)) != (saveMode | openMode));
  45818. // You need to specify at least one of these flags..
  45819. jassert ((flags & (canSelectFiles | canSelectDirectories)) != 0);
  45820. String filename;
  45821. if (initialFileOrDirectory == File::nonexistent)
  45822. {
  45823. currentRoot = File::getCurrentWorkingDirectory();
  45824. }
  45825. else if (initialFileOrDirectory.isDirectory())
  45826. {
  45827. currentRoot = initialFileOrDirectory;
  45828. }
  45829. else
  45830. {
  45831. chosenFiles.add (initialFileOrDirectory);
  45832. currentRoot = initialFileOrDirectory.getParentDirectory();
  45833. filename = initialFileOrDirectory.getFileName();
  45834. }
  45835. fileList = new DirectoryContentsList (this, thread);
  45836. if ((flags & useTreeView) != 0)
  45837. {
  45838. FileTreeComponent* const tree = new FileTreeComponent (*fileList);
  45839. if ((flags & canSelectMultipleItems) != 0)
  45840. tree->setMultiSelectEnabled (true);
  45841. addAndMakeVisible (tree);
  45842. fileListComponent = tree;
  45843. }
  45844. else
  45845. {
  45846. FileListComponent* const list = new FileListComponent (*fileList);
  45847. list->setOutlineThickness (1);
  45848. if ((flags & canSelectMultipleItems) != 0)
  45849. list->setMultipleSelectionEnabled (true);
  45850. addAndMakeVisible (list);
  45851. fileListComponent = list;
  45852. }
  45853. fileListComponent->addListener (this);
  45854. addAndMakeVisible (currentPathBox = new ComboBox ("path"));
  45855. currentPathBox->setEditableText (true);
  45856. StringArray rootNames, rootPaths;
  45857. const BigInteger separators (getRoots (rootNames, rootPaths));
  45858. for (int i = 0; i < rootNames.size(); ++i)
  45859. {
  45860. if (separators [i])
  45861. currentPathBox->addSeparator();
  45862. currentPathBox->addItem (rootNames[i], i + 1);
  45863. }
  45864. currentPathBox->addSeparator();
  45865. currentPathBox->addListener (this);
  45866. addAndMakeVisible (filenameBox = new TextEditor());
  45867. filenameBox->setMultiLine (false);
  45868. filenameBox->setSelectAllWhenFocused (true);
  45869. filenameBox->setText (filename, false);
  45870. filenameBox->addListener (this);
  45871. filenameBox->setReadOnly ((flags & (filenameBoxIsReadOnly | canSelectMultipleItems)) != 0);
  45872. Label* label = new Label ("f", TRANS("file:"));
  45873. addAndMakeVisible (label);
  45874. label->attachToComponent (filenameBox, true);
  45875. addAndMakeVisible (goUpButton = getLookAndFeel().createFileBrowserGoUpButton());
  45876. goUpButton->addButtonListener (this);
  45877. goUpButton->setTooltip (TRANS ("go up to parent directory"));
  45878. if (previewComp != 0)
  45879. addAndMakeVisible (previewComp);
  45880. setRoot (currentRoot);
  45881. thread.startThread (4);
  45882. }
  45883. FileBrowserComponent::~FileBrowserComponent()
  45884. {
  45885. if (previewComp != 0)
  45886. removeChildComponent (previewComp);
  45887. deleteAllChildren();
  45888. fileList = 0;
  45889. thread.stopThread (10000);
  45890. }
  45891. void FileBrowserComponent::addListener (FileBrowserListener* const newListener)
  45892. {
  45893. listeners.add (newListener);
  45894. }
  45895. void FileBrowserComponent::removeListener (FileBrowserListener* const listener)
  45896. {
  45897. listeners.remove (listener);
  45898. }
  45899. bool FileBrowserComponent::isSaveMode() const throw()
  45900. {
  45901. return (flags & saveMode) != 0;
  45902. }
  45903. int FileBrowserComponent::getNumSelectedFiles() const throw()
  45904. {
  45905. if (chosenFiles.size() == 0 && currentFileIsValid())
  45906. return 1;
  45907. return chosenFiles.size();
  45908. }
  45909. const File FileBrowserComponent::getSelectedFile (int index) const throw()
  45910. {
  45911. if ((flags & canSelectDirectories) != 0 && filenameBox->getText().isEmpty())
  45912. return currentRoot;
  45913. if (! filenameBox->isReadOnly())
  45914. return currentRoot.getChildFile (filenameBox->getText());
  45915. return chosenFiles[index];
  45916. }
  45917. bool FileBrowserComponent::currentFileIsValid() const
  45918. {
  45919. if (isSaveMode())
  45920. return ! getSelectedFile (0).isDirectory();
  45921. else
  45922. return getSelectedFile (0).exists();
  45923. }
  45924. const File FileBrowserComponent::getHighlightedFile() const throw()
  45925. {
  45926. return fileListComponent->getSelectedFile (0);
  45927. }
  45928. void FileBrowserComponent::deselectAllFiles()
  45929. {
  45930. fileListComponent->deselectAllFiles();
  45931. }
  45932. bool FileBrowserComponent::isFileSuitable (const File& file) const
  45933. {
  45934. return (flags & canSelectFiles) != 0 ? (fileFilter == 0 || fileFilter->isFileSuitable (file))
  45935. : false;
  45936. }
  45937. bool FileBrowserComponent::isDirectorySuitable (const File&) const
  45938. {
  45939. return true;
  45940. }
  45941. bool FileBrowserComponent::isFileOrDirSuitable (const File& f) const
  45942. {
  45943. if (f.isDirectory())
  45944. return (flags & canSelectDirectories) != 0 && (fileFilter == 0 || fileFilter->isDirectorySuitable (f));
  45945. return (flags & canSelectFiles) != 0 && f.exists()
  45946. && (fileFilter == 0 || fileFilter->isFileSuitable (f));
  45947. }
  45948. const File FileBrowserComponent::getRoot() const
  45949. {
  45950. return currentRoot;
  45951. }
  45952. void FileBrowserComponent::setRoot (const File& newRootDirectory)
  45953. {
  45954. if (currentRoot != newRootDirectory)
  45955. {
  45956. fileListComponent->scrollToTop();
  45957. String path (newRootDirectory.getFullPathName());
  45958. if (path.isEmpty())
  45959. path = File::separatorString;
  45960. StringArray rootNames, rootPaths;
  45961. getRoots (rootNames, rootPaths);
  45962. if (! rootPaths.contains (path, true))
  45963. {
  45964. bool alreadyListed = false;
  45965. for (int i = currentPathBox->getNumItems(); --i >= 0;)
  45966. {
  45967. if (currentPathBox->getItemText (i).equalsIgnoreCase (path))
  45968. {
  45969. alreadyListed = true;
  45970. break;
  45971. }
  45972. }
  45973. if (! alreadyListed)
  45974. currentPathBox->addItem (path, currentPathBox->getNumItems() + 2);
  45975. }
  45976. }
  45977. currentRoot = newRootDirectory;
  45978. fileList->setDirectory (currentRoot, true, true);
  45979. String currentRootName (currentRoot.getFullPathName());
  45980. if (currentRootName.isEmpty())
  45981. currentRootName = File::separatorString;
  45982. currentPathBox->setText (currentRootName, true);
  45983. goUpButton->setEnabled (currentRoot.getParentDirectory().isDirectory()
  45984. && currentRoot.getParentDirectory() != currentRoot);
  45985. }
  45986. void FileBrowserComponent::goUp()
  45987. {
  45988. setRoot (getRoot().getParentDirectory());
  45989. }
  45990. void FileBrowserComponent::refresh()
  45991. {
  45992. fileList->refresh();
  45993. }
  45994. const String FileBrowserComponent::getActionVerb() const
  45995. {
  45996. return isSaveMode() ? TRANS("Save") : TRANS("Open");
  45997. }
  45998. FilePreviewComponent* FileBrowserComponent::getPreviewComponent() const throw()
  45999. {
  46000. return previewComp;
  46001. }
  46002. void FileBrowserComponent::resized()
  46003. {
  46004. getLookAndFeel()
  46005. .layoutFileBrowserComponent (*this, fileListComponent,
  46006. previewComp, currentPathBox,
  46007. filenameBox, goUpButton);
  46008. }
  46009. void FileBrowserComponent::sendListenerChangeMessage()
  46010. {
  46011. Component::BailOutChecker checker (this);
  46012. if (previewComp != 0)
  46013. previewComp->selectedFileChanged (getSelectedFile (0));
  46014. // You shouldn't delete the browser when the file gets changed!
  46015. jassert (! checker.shouldBailOut());
  46016. listeners.callChecked (checker, &FileBrowserListener::selectionChanged);
  46017. }
  46018. void FileBrowserComponent::selectionChanged()
  46019. {
  46020. StringArray newFilenames;
  46021. bool resetChosenFiles = true;
  46022. for (int i = 0; i < fileListComponent->getNumSelectedFiles(); ++i)
  46023. {
  46024. const File f (fileListComponent->getSelectedFile (i));
  46025. if (isFileOrDirSuitable (f))
  46026. {
  46027. if (resetChosenFiles)
  46028. {
  46029. chosenFiles.clear();
  46030. resetChosenFiles = false;
  46031. }
  46032. chosenFiles.add (f);
  46033. newFilenames.add (f.getRelativePathFrom (getRoot()));
  46034. }
  46035. }
  46036. if (newFilenames.size() > 0)
  46037. filenameBox->setText (newFilenames.joinIntoString (", "), false);
  46038. sendListenerChangeMessage();
  46039. }
  46040. void FileBrowserComponent::fileClicked (const File& f, const MouseEvent& e)
  46041. {
  46042. Component::BailOutChecker checker (this);
  46043. listeners.callChecked (checker, &FileBrowserListener::fileClicked, f, e);
  46044. }
  46045. void FileBrowserComponent::fileDoubleClicked (const File& f)
  46046. {
  46047. if (f.isDirectory())
  46048. {
  46049. setRoot (f);
  46050. if ((flags & canSelectDirectories) != 0)
  46051. filenameBox->setText (String::empty);
  46052. }
  46053. else
  46054. {
  46055. Component::BailOutChecker checker (this);
  46056. listeners.callChecked (checker, &FileBrowserListener::fileDoubleClicked, f);
  46057. }
  46058. }
  46059. bool FileBrowserComponent::keyPressed (const KeyPress& key)
  46060. {
  46061. (void) key;
  46062. #if JUCE_LINUX || JUCE_WINDOWS
  46063. if (key.getModifiers().isCommandDown()
  46064. && (key.getKeyCode() == 'H' || key.getKeyCode() == 'h'))
  46065. {
  46066. fileList->setIgnoresHiddenFiles (! fileList->ignoresHiddenFiles());
  46067. fileList->refresh();
  46068. return true;
  46069. }
  46070. #endif
  46071. return false;
  46072. }
  46073. void FileBrowserComponent::textEditorTextChanged (TextEditor&)
  46074. {
  46075. sendListenerChangeMessage();
  46076. }
  46077. void FileBrowserComponent::textEditorReturnKeyPressed (TextEditor&)
  46078. {
  46079. if (filenameBox->getText().containsChar (File::separator))
  46080. {
  46081. const File f (currentRoot.getChildFile (filenameBox->getText()));
  46082. if (f.isDirectory())
  46083. {
  46084. setRoot (f);
  46085. chosenFiles.clear();
  46086. filenameBox->setText (String::empty);
  46087. }
  46088. else
  46089. {
  46090. setRoot (f.getParentDirectory());
  46091. chosenFiles.clear();
  46092. chosenFiles.add (f);
  46093. filenameBox->setText (f.getFileName());
  46094. }
  46095. }
  46096. else
  46097. {
  46098. fileDoubleClicked (getSelectedFile (0));
  46099. }
  46100. }
  46101. void FileBrowserComponent::textEditorEscapeKeyPressed (TextEditor&)
  46102. {
  46103. }
  46104. void FileBrowserComponent::textEditorFocusLost (TextEditor&)
  46105. {
  46106. if (! isSaveMode())
  46107. selectionChanged();
  46108. }
  46109. void FileBrowserComponent::buttonClicked (Button*)
  46110. {
  46111. goUp();
  46112. }
  46113. void FileBrowserComponent::comboBoxChanged (ComboBox*)
  46114. {
  46115. const String newText (currentPathBox->getText().trim().unquoted());
  46116. if (newText.isNotEmpty())
  46117. {
  46118. const int index = currentPathBox->getSelectedId() - 1;
  46119. StringArray rootNames, rootPaths;
  46120. getRoots (rootNames, rootPaths);
  46121. if (rootPaths [index].isNotEmpty())
  46122. {
  46123. setRoot (File (rootPaths [index]));
  46124. }
  46125. else
  46126. {
  46127. File f (newText);
  46128. for (;;)
  46129. {
  46130. if (f.isDirectory())
  46131. {
  46132. setRoot (f);
  46133. break;
  46134. }
  46135. if (f.getParentDirectory() == f)
  46136. break;
  46137. f = f.getParentDirectory();
  46138. }
  46139. }
  46140. }
  46141. }
  46142. const BigInteger FileBrowserComponent::getRoots (StringArray& rootNames, StringArray& rootPaths)
  46143. {
  46144. BigInteger separators;
  46145. #if JUCE_WINDOWS
  46146. Array<File> roots;
  46147. File::findFileSystemRoots (roots);
  46148. rootPaths.clear();
  46149. for (int i = 0; i < roots.size(); ++i)
  46150. {
  46151. const File& drive = roots.getReference(i);
  46152. String name (drive.getFullPathName());
  46153. rootPaths.add (name);
  46154. if (drive.isOnHardDisk())
  46155. {
  46156. String volume (drive.getVolumeLabel());
  46157. if (volume.isEmpty())
  46158. volume = TRANS("Hard Drive");
  46159. name << " [" << drive.getVolumeLabel() << ']';
  46160. }
  46161. else if (drive.isOnCDRomDrive())
  46162. {
  46163. name << TRANS(" [CD/DVD drive]");
  46164. }
  46165. rootNames.add (name);
  46166. }
  46167. separators.setBit (rootPaths.size());
  46168. rootPaths.add (File::getSpecialLocation (File::userDocumentsDirectory).getFullPathName());
  46169. rootNames.add ("Documents");
  46170. rootPaths.add (File::getSpecialLocation (File::userDesktopDirectory).getFullPathName());
  46171. rootNames.add ("Desktop");
  46172. #endif
  46173. #if JUCE_MAC
  46174. rootPaths.add (File::getSpecialLocation (File::userHomeDirectory).getFullPathName());
  46175. rootNames.add ("Home folder");
  46176. rootPaths.add (File::getSpecialLocation (File::userDocumentsDirectory).getFullPathName());
  46177. rootNames.add ("Documents");
  46178. rootPaths.add (File::getSpecialLocation (File::userDesktopDirectory).getFullPathName());
  46179. rootNames.add ("Desktop");
  46180. separators.setBit (rootPaths.size());
  46181. Array <File> volumes;
  46182. File vol ("/Volumes");
  46183. vol.findChildFiles (volumes, File::findDirectories, false);
  46184. for (int i = 0; i < volumes.size(); ++i)
  46185. {
  46186. const File& volume = volumes.getReference(i);
  46187. if (volume.isDirectory() && ! volume.getFileName().startsWithChar ('.'))
  46188. {
  46189. rootPaths.add (volume.getFullPathName());
  46190. rootNames.add (volume.getFileName());
  46191. }
  46192. }
  46193. #endif
  46194. #if JUCE_LINUX
  46195. rootPaths.add ("/");
  46196. rootNames.add ("/");
  46197. rootPaths.add (File::getSpecialLocation (File::userHomeDirectory).getFullPathName());
  46198. rootNames.add ("Home folder");
  46199. rootPaths.add (File::getSpecialLocation (File::userDesktopDirectory).getFullPathName());
  46200. rootNames.add ("Desktop");
  46201. #endif
  46202. return separators;
  46203. }
  46204. END_JUCE_NAMESPACE
  46205. /*** End of inlined file: juce_FileBrowserComponent.cpp ***/
  46206. /*** Start of inlined file: juce_FileChooser.cpp ***/
  46207. BEGIN_JUCE_NAMESPACE
  46208. FileChooser::FileChooser (const String& chooserBoxTitle,
  46209. const File& currentFileOrDirectory,
  46210. const String& fileFilters,
  46211. const bool useNativeDialogBox_)
  46212. : title (chooserBoxTitle),
  46213. filters (fileFilters),
  46214. startingFile (currentFileOrDirectory),
  46215. useNativeDialogBox (useNativeDialogBox_)
  46216. {
  46217. #if JUCE_LINUX
  46218. useNativeDialogBox = false;
  46219. #endif
  46220. if (! fileFilters.containsNonWhitespaceChars())
  46221. filters = "*";
  46222. }
  46223. FileChooser::~FileChooser()
  46224. {
  46225. }
  46226. bool FileChooser::browseForFileToOpen (FilePreviewComponent* previewComponent)
  46227. {
  46228. return showDialog (false, true, false, false, false, previewComponent);
  46229. }
  46230. bool FileChooser::browseForMultipleFilesToOpen (FilePreviewComponent* previewComponent)
  46231. {
  46232. return showDialog (false, true, false, false, true, previewComponent);
  46233. }
  46234. bool FileChooser::browseForMultipleFilesOrDirectories (FilePreviewComponent* previewComponent)
  46235. {
  46236. return showDialog (true, true, false, false, true, previewComponent);
  46237. }
  46238. bool FileChooser::browseForFileToSave (const bool warnAboutOverwritingExistingFiles)
  46239. {
  46240. return showDialog (false, true, true, warnAboutOverwritingExistingFiles, false, 0);
  46241. }
  46242. bool FileChooser::browseForDirectory()
  46243. {
  46244. return showDialog (true, false, false, false, false, 0);
  46245. }
  46246. const File FileChooser::getResult() const
  46247. {
  46248. // if you've used a multiple-file select, you should use the getResults() method
  46249. // to retrieve all the files that were chosen.
  46250. jassert (results.size() <= 1);
  46251. return results.getFirst();
  46252. }
  46253. const Array<File>& FileChooser::getResults() const
  46254. {
  46255. return results;
  46256. }
  46257. bool FileChooser::showDialog (const bool selectsDirectories,
  46258. const bool selectsFiles,
  46259. const bool isSave,
  46260. const bool warnAboutOverwritingExistingFiles,
  46261. const bool selectMultipleFiles,
  46262. FilePreviewComponent* const previewComponent)
  46263. {
  46264. Component::SafePointer<Component> previouslyFocused (Component::getCurrentlyFocusedComponent());
  46265. results.clear();
  46266. // the preview component needs to be the right size before you pass it in here..
  46267. jassert (previewComponent == 0 || (previewComponent->getWidth() > 10
  46268. && previewComponent->getHeight() > 10));
  46269. #if JUCE_WINDOWS
  46270. if (useNativeDialogBox && ! (selectsFiles && selectsDirectories))
  46271. #elif JUCE_MAC
  46272. if (useNativeDialogBox && (previewComponent == 0))
  46273. #else
  46274. if (false)
  46275. #endif
  46276. {
  46277. showPlatformDialog (results, title, startingFile, filters,
  46278. selectsDirectories, selectsFiles, isSave,
  46279. warnAboutOverwritingExistingFiles,
  46280. selectMultipleFiles,
  46281. previewComponent);
  46282. }
  46283. else
  46284. {
  46285. WildcardFileFilter wildcard (selectsFiles ? filters : String::empty,
  46286. selectsDirectories ? "*" : String::empty,
  46287. String::empty);
  46288. int flags = isSave ? FileBrowserComponent::saveMode
  46289. : FileBrowserComponent::openMode;
  46290. if (selectsFiles)
  46291. flags |= FileBrowserComponent::canSelectFiles;
  46292. if (selectsDirectories)
  46293. {
  46294. flags |= FileBrowserComponent::canSelectDirectories;
  46295. if (! isSave)
  46296. flags |= FileBrowserComponent::filenameBoxIsReadOnly;
  46297. }
  46298. if (selectMultipleFiles)
  46299. flags |= FileBrowserComponent::canSelectMultipleItems;
  46300. FileBrowserComponent browserComponent (flags, startingFile, &wildcard, previewComponent);
  46301. FileChooserDialogBox box (title, String::empty,
  46302. browserComponent,
  46303. warnAboutOverwritingExistingFiles,
  46304. browserComponent.findColour (AlertWindow::backgroundColourId));
  46305. if (box.show())
  46306. {
  46307. for (int i = 0; i < browserComponent.getNumSelectedFiles(); ++i)
  46308. results.add (browserComponent.getSelectedFile (i));
  46309. }
  46310. }
  46311. if (previouslyFocused != 0)
  46312. previouslyFocused->grabKeyboardFocus();
  46313. return results.size() > 0;
  46314. }
  46315. FilePreviewComponent::FilePreviewComponent()
  46316. {
  46317. }
  46318. FilePreviewComponent::~FilePreviewComponent()
  46319. {
  46320. }
  46321. END_JUCE_NAMESPACE
  46322. /*** End of inlined file: juce_FileChooser.cpp ***/
  46323. /*** Start of inlined file: juce_FileChooserDialogBox.cpp ***/
  46324. BEGIN_JUCE_NAMESPACE
  46325. FileChooserDialogBox::FileChooserDialogBox (const String& name,
  46326. const String& instructions,
  46327. FileBrowserComponent& chooserComponent,
  46328. const bool warnAboutOverwritingExistingFiles_,
  46329. const Colour& backgroundColour)
  46330. : ResizableWindow (name, backgroundColour, true),
  46331. warnAboutOverwritingExistingFiles (warnAboutOverwritingExistingFiles_)
  46332. {
  46333. content = new ContentComponent();
  46334. content->setName (name);
  46335. content->instructions = instructions;
  46336. content->chooserComponent = &chooserComponent;
  46337. content->addAndMakeVisible (&chooserComponent);
  46338. content->okButton = new TextButton (chooserComponent.getActionVerb());
  46339. content->addAndMakeVisible (content->okButton);
  46340. content->okButton->addButtonListener (this);
  46341. content->okButton->setEnabled (chooserComponent.currentFileIsValid());
  46342. content->okButton->addShortcut (KeyPress (KeyPress::returnKey, 0, 0));
  46343. content->cancelButton = new TextButton (TRANS("Cancel"));
  46344. content->addAndMakeVisible (content->cancelButton);
  46345. content->cancelButton->addButtonListener (this);
  46346. content->cancelButton->addShortcut (KeyPress (KeyPress::escapeKey, 0, 0));
  46347. setContentComponent (content);
  46348. setResizable (true, true);
  46349. setResizeLimits (300, 300, 1200, 1000);
  46350. content->chooserComponent->addListener (this);
  46351. }
  46352. FileChooserDialogBox::~FileChooserDialogBox()
  46353. {
  46354. content->chooserComponent->removeListener (this);
  46355. }
  46356. bool FileChooserDialogBox::show (int w, int h)
  46357. {
  46358. if (w <= 0)
  46359. {
  46360. Component* const previewComp = content->chooserComponent->getPreviewComponent();
  46361. if (previewComp != 0)
  46362. w = 400 + previewComp->getWidth();
  46363. else
  46364. w = 600;
  46365. }
  46366. if (h <= 0)
  46367. h = 500;
  46368. centreWithSize (w, h);
  46369. const bool ok = (runModalLoop() != 0);
  46370. setVisible (false);
  46371. return ok;
  46372. }
  46373. void FileChooserDialogBox::buttonClicked (Button* button)
  46374. {
  46375. if (button == content->okButton)
  46376. {
  46377. if (warnAboutOverwritingExistingFiles
  46378. && content->chooserComponent->isSaveMode()
  46379. && content->chooserComponent->getSelectedFile(0).exists())
  46380. {
  46381. if (! AlertWindow::showOkCancelBox (AlertWindow::WarningIcon,
  46382. TRANS("File already exists"),
  46383. TRANS("There's already a file called:")
  46384. + "\n\n" + content->chooserComponent->getSelectedFile(0).getFullPathName()
  46385. + "\n\n" + TRANS("Are you sure you want to overwrite it?"),
  46386. TRANS("overwrite"),
  46387. TRANS("cancel")))
  46388. {
  46389. return;
  46390. }
  46391. }
  46392. exitModalState (1);
  46393. }
  46394. else if (button == content->cancelButton)
  46395. closeButtonPressed();
  46396. }
  46397. void FileChooserDialogBox::closeButtonPressed()
  46398. {
  46399. setVisible (false);
  46400. }
  46401. void FileChooserDialogBox::selectionChanged()
  46402. {
  46403. content->okButton->setEnabled (content->chooserComponent->currentFileIsValid());
  46404. }
  46405. void FileChooserDialogBox::fileClicked (const File&, const MouseEvent&)
  46406. {
  46407. }
  46408. void FileChooserDialogBox::fileDoubleClicked (const File&)
  46409. {
  46410. selectionChanged();
  46411. content->okButton->triggerClick();
  46412. }
  46413. FileChooserDialogBox::ContentComponent::ContentComponent()
  46414. {
  46415. setInterceptsMouseClicks (false, true);
  46416. }
  46417. FileChooserDialogBox::ContentComponent::~ContentComponent()
  46418. {
  46419. delete okButton;
  46420. delete cancelButton;
  46421. }
  46422. void FileChooserDialogBox::ContentComponent::paint (Graphics& g)
  46423. {
  46424. g.setColour (getLookAndFeel().findColour (FileChooserDialogBox::titleTextColourId));
  46425. text.draw (g);
  46426. }
  46427. void FileChooserDialogBox::ContentComponent::resized()
  46428. {
  46429. getLookAndFeel().createFileChooserHeaderText (getName(), instructions, text, getWidth());
  46430. const Rectangle<float> bb (text.getBoundingBox (0, text.getNumGlyphs(), false));
  46431. const int y = roundToInt (bb.getBottom()) + 10;
  46432. const int buttonHeight = 26;
  46433. const int buttonY = getHeight() - buttonHeight - 8;
  46434. chooserComponent->setBounds (0, y, getWidth(), buttonY - y - 20);
  46435. okButton->setBounds (proportionOfWidth (0.25f), buttonY,
  46436. proportionOfWidth (0.2f), buttonHeight);
  46437. cancelButton->setBounds (proportionOfWidth (0.55f), buttonY,
  46438. proportionOfWidth (0.2f), buttonHeight);
  46439. }
  46440. END_JUCE_NAMESPACE
  46441. /*** End of inlined file: juce_FileChooserDialogBox.cpp ***/
  46442. /*** Start of inlined file: juce_FileFilter.cpp ***/
  46443. BEGIN_JUCE_NAMESPACE
  46444. FileFilter::FileFilter (const String& filterDescription)
  46445. : description (filterDescription)
  46446. {
  46447. }
  46448. FileFilter::~FileFilter()
  46449. {
  46450. }
  46451. const String& FileFilter::getDescription() const throw()
  46452. {
  46453. return description;
  46454. }
  46455. END_JUCE_NAMESPACE
  46456. /*** End of inlined file: juce_FileFilter.cpp ***/
  46457. /*** Start of inlined file: juce_FileListComponent.cpp ***/
  46458. BEGIN_JUCE_NAMESPACE
  46459. Image* juce_createIconForFile (const File& file);
  46460. FileListComponent::FileListComponent (DirectoryContentsList& listToShow)
  46461. : ListBox (String::empty, 0),
  46462. DirectoryContentsDisplayComponent (listToShow)
  46463. {
  46464. setModel (this);
  46465. fileList.addChangeListener (this);
  46466. }
  46467. FileListComponent::~FileListComponent()
  46468. {
  46469. fileList.removeChangeListener (this);
  46470. deleteAllChildren();
  46471. }
  46472. int FileListComponent::getNumSelectedFiles() const
  46473. {
  46474. return getNumSelectedRows();
  46475. }
  46476. const File FileListComponent::getSelectedFile (int index) const
  46477. {
  46478. return fileList.getFile (getSelectedRow (index));
  46479. }
  46480. void FileListComponent::deselectAllFiles()
  46481. {
  46482. deselectAllRows();
  46483. }
  46484. void FileListComponent::scrollToTop()
  46485. {
  46486. getVerticalScrollBar()->setCurrentRangeStart (0);
  46487. }
  46488. void FileListComponent::changeListenerCallback (void*)
  46489. {
  46490. updateContent();
  46491. if (lastDirectory != fileList.getDirectory())
  46492. {
  46493. lastDirectory = fileList.getDirectory();
  46494. deselectAllRows();
  46495. }
  46496. }
  46497. class FileListItemComponent : public Component,
  46498. public TimeSliceClient,
  46499. public AsyncUpdater
  46500. {
  46501. public:
  46502. FileListItemComponent (FileListComponent& owner_, TimeSliceThread& thread_)
  46503. : owner (owner_), thread (thread_),
  46504. highlighted (false), index (0), icon (0)
  46505. {
  46506. }
  46507. ~FileListItemComponent()
  46508. {
  46509. thread.removeTimeSliceClient (this);
  46510. clearIcon();
  46511. }
  46512. void paint (Graphics& g)
  46513. {
  46514. getLookAndFeel().drawFileBrowserRow (g, getWidth(), getHeight(),
  46515. file.getFileName(),
  46516. icon,
  46517. fileSize, modTime,
  46518. isDirectory, highlighted,
  46519. index);
  46520. }
  46521. void mouseDown (const MouseEvent& e)
  46522. {
  46523. owner.selectRowsBasedOnModifierKeys (index, e.mods);
  46524. owner.sendMouseClickMessage (file, e);
  46525. }
  46526. void mouseDoubleClick (const MouseEvent&)
  46527. {
  46528. owner.sendDoubleClickMessage (file);
  46529. }
  46530. void update (const File& root,
  46531. const DirectoryContentsList::FileInfo* const fileInfo,
  46532. const int index_,
  46533. const bool highlighted_)
  46534. {
  46535. thread.removeTimeSliceClient (this);
  46536. if (highlighted_ != highlighted
  46537. || index_ != index)
  46538. {
  46539. index = index_;
  46540. highlighted = highlighted_;
  46541. repaint();
  46542. }
  46543. File newFile;
  46544. String newFileSize;
  46545. String newModTime;
  46546. if (fileInfo != 0)
  46547. {
  46548. newFile = root.getChildFile (fileInfo->filename);
  46549. newFileSize = File::descriptionOfSizeInBytes (fileInfo->fileSize);
  46550. newModTime = fileInfo->modificationTime.formatted ("%d %b '%y %H:%M");
  46551. }
  46552. if (newFile != file
  46553. || fileSize != newFileSize
  46554. || modTime != newModTime)
  46555. {
  46556. file = newFile;
  46557. fileSize = newFileSize;
  46558. modTime = newModTime;
  46559. isDirectory = fileInfo != 0 && fileInfo->isDirectory;
  46560. repaint();
  46561. clearIcon();
  46562. }
  46563. if (file != File::nonexistent
  46564. && icon == 0 && ! isDirectory)
  46565. {
  46566. updateIcon (true);
  46567. if (icon == 0)
  46568. thread.addTimeSliceClient (this);
  46569. }
  46570. }
  46571. bool useTimeSlice()
  46572. {
  46573. updateIcon (false);
  46574. return false;
  46575. }
  46576. void handleAsyncUpdate()
  46577. {
  46578. repaint();
  46579. }
  46580. juce_UseDebuggingNewOperator
  46581. private:
  46582. FileListComponent& owner;
  46583. TimeSliceThread& thread;
  46584. bool highlighted;
  46585. int index;
  46586. File file;
  46587. String fileSize;
  46588. String modTime;
  46589. Image* icon;
  46590. bool isDirectory;
  46591. void clearIcon()
  46592. {
  46593. ImageCache::release (icon);
  46594. icon = 0;
  46595. }
  46596. void updateIcon (const bool onlyUpdateIfCached)
  46597. {
  46598. if (icon == 0)
  46599. {
  46600. const int hashCode = (file.getFullPathName() + "_iconCacheSalt").hashCode();
  46601. Image* im = ImageCache::getFromHashCode (hashCode);
  46602. if (im == 0 && ! onlyUpdateIfCached)
  46603. {
  46604. im = juce_createIconForFile (file);
  46605. if (im != 0)
  46606. ImageCache::addImageToCache (im, hashCode);
  46607. }
  46608. if (im != 0)
  46609. {
  46610. icon = im;
  46611. triggerAsyncUpdate();
  46612. }
  46613. }
  46614. }
  46615. };
  46616. int FileListComponent::getNumRows()
  46617. {
  46618. return fileList.getNumFiles();
  46619. }
  46620. void FileListComponent::paintListBoxItem (int, Graphics&, int, int, bool)
  46621. {
  46622. }
  46623. Component* FileListComponent::refreshComponentForRow (int row, bool isSelected, Component* existingComponentToUpdate)
  46624. {
  46625. FileListItemComponent* comp = dynamic_cast <FileListItemComponent*> (existingComponentToUpdate);
  46626. if (comp == 0)
  46627. {
  46628. delete existingComponentToUpdate;
  46629. comp = new FileListItemComponent (*this, fileList.getTimeSliceThread());
  46630. }
  46631. DirectoryContentsList::FileInfo fileInfo;
  46632. if (fileList.getFileInfo (row, fileInfo))
  46633. comp->update (fileList.getDirectory(), &fileInfo, row, isSelected);
  46634. else
  46635. comp->update (fileList.getDirectory(), 0, row, isSelected);
  46636. return comp;
  46637. }
  46638. void FileListComponent::selectedRowsChanged (int /*lastRowSelected*/)
  46639. {
  46640. sendSelectionChangeMessage();
  46641. }
  46642. void FileListComponent::deleteKeyPressed (int /*currentSelectedRow*/)
  46643. {
  46644. }
  46645. void FileListComponent::returnKeyPressed (int currentSelectedRow)
  46646. {
  46647. sendDoubleClickMessage (fileList.getFile (currentSelectedRow));
  46648. }
  46649. END_JUCE_NAMESPACE
  46650. /*** End of inlined file: juce_FileListComponent.cpp ***/
  46651. /*** Start of inlined file: juce_FilenameComponent.cpp ***/
  46652. BEGIN_JUCE_NAMESPACE
  46653. FilenameComponent::FilenameComponent (const String& name,
  46654. const File& currentFile,
  46655. const bool canEditFilename,
  46656. const bool isDirectory,
  46657. const bool isForSaving,
  46658. const String& fileBrowserWildcard,
  46659. const String& enforcedSuffix_,
  46660. const String& textWhenNothingSelected)
  46661. : Component (name),
  46662. maxRecentFiles (30),
  46663. isDir (isDirectory),
  46664. isSaving (isForSaving),
  46665. isFileDragOver (false),
  46666. wildcard (fileBrowserWildcard),
  46667. enforcedSuffix (enforcedSuffix_)
  46668. {
  46669. addAndMakeVisible (filenameBox = new ComboBox ("fn"));
  46670. filenameBox->setEditableText (canEditFilename);
  46671. filenameBox->addListener (this);
  46672. filenameBox->setTextWhenNothingSelected (textWhenNothingSelected);
  46673. filenameBox->setTextWhenNoChoicesAvailable (TRANS("(no recently seleced files)"));
  46674. browseButton = 0;
  46675. setBrowseButtonText ("...");
  46676. setCurrentFile (currentFile, true);
  46677. }
  46678. FilenameComponent::~FilenameComponent()
  46679. {
  46680. deleteAllChildren();
  46681. }
  46682. void FilenameComponent::paintOverChildren (Graphics& g)
  46683. {
  46684. if (isFileDragOver)
  46685. {
  46686. g.setColour (Colours::red.withAlpha (0.2f));
  46687. g.drawRect (0, 0, getWidth(), getHeight(), 3);
  46688. }
  46689. }
  46690. void FilenameComponent::resized()
  46691. {
  46692. getLookAndFeel().layoutFilenameComponent (*this, filenameBox, browseButton);
  46693. }
  46694. void FilenameComponent::setBrowseButtonText (const String& newBrowseButtonText)
  46695. {
  46696. browseButtonText = newBrowseButtonText;
  46697. lookAndFeelChanged();
  46698. }
  46699. void FilenameComponent::lookAndFeelChanged()
  46700. {
  46701. deleteAndZero (browseButton);
  46702. addAndMakeVisible (browseButton = getLookAndFeel().createFilenameComponentBrowseButton (browseButtonText));
  46703. browseButton->setConnectedEdges (Button::ConnectedOnLeft);
  46704. resized();
  46705. browseButton->addButtonListener (this);
  46706. }
  46707. void FilenameComponent::setTooltip (const String& newTooltip)
  46708. {
  46709. SettableTooltipClient::setTooltip (newTooltip);
  46710. filenameBox->setTooltip (newTooltip);
  46711. }
  46712. void FilenameComponent::setDefaultBrowseTarget (const File& newDefaultDirectory)
  46713. {
  46714. defaultBrowseFile = newDefaultDirectory;
  46715. }
  46716. void FilenameComponent::buttonClicked (Button*)
  46717. {
  46718. FileChooser fc (TRANS("Choose a new file"),
  46719. getCurrentFile() == File::nonexistent ? defaultBrowseFile
  46720. : getCurrentFile(),
  46721. wildcard);
  46722. if (isDir ? fc.browseForDirectory()
  46723. : (isSaving ? fc.browseForFileToSave (false)
  46724. : fc.browseForFileToOpen()))
  46725. {
  46726. setCurrentFile (fc.getResult(), true);
  46727. }
  46728. }
  46729. void FilenameComponent::comboBoxChanged (ComboBox*)
  46730. {
  46731. setCurrentFile (getCurrentFile(), true);
  46732. }
  46733. bool FilenameComponent::isInterestedInFileDrag (const StringArray&)
  46734. {
  46735. return true;
  46736. }
  46737. void FilenameComponent::filesDropped (const StringArray& filenames, int, int)
  46738. {
  46739. isFileDragOver = false;
  46740. repaint();
  46741. const File f (filenames[0]);
  46742. if (f.exists() && (f.isDirectory() == isDir))
  46743. setCurrentFile (f, true);
  46744. }
  46745. void FilenameComponent::fileDragEnter (const StringArray&, int, int)
  46746. {
  46747. isFileDragOver = true;
  46748. repaint();
  46749. }
  46750. void FilenameComponent::fileDragExit (const StringArray&)
  46751. {
  46752. isFileDragOver = false;
  46753. repaint();
  46754. }
  46755. const File FilenameComponent::getCurrentFile() const
  46756. {
  46757. File f (filenameBox->getText());
  46758. if (enforcedSuffix.isNotEmpty())
  46759. f = f.withFileExtension (enforcedSuffix);
  46760. return f;
  46761. }
  46762. void FilenameComponent::setCurrentFile (File newFile,
  46763. const bool addToRecentlyUsedList,
  46764. const bool sendChangeNotification)
  46765. {
  46766. if (enforcedSuffix.isNotEmpty())
  46767. newFile = newFile.withFileExtension (enforcedSuffix);
  46768. if (newFile.getFullPathName() != lastFilename)
  46769. {
  46770. lastFilename = newFile.getFullPathName();
  46771. if (addToRecentlyUsedList)
  46772. addRecentlyUsedFile (newFile);
  46773. filenameBox->setText (lastFilename, true);
  46774. if (sendChangeNotification)
  46775. triggerAsyncUpdate();
  46776. }
  46777. }
  46778. void FilenameComponent::setFilenameIsEditable (const bool shouldBeEditable)
  46779. {
  46780. filenameBox->setEditableText (shouldBeEditable);
  46781. }
  46782. const StringArray FilenameComponent::getRecentlyUsedFilenames() const
  46783. {
  46784. StringArray names;
  46785. for (int i = 0; i < filenameBox->getNumItems(); ++i)
  46786. names.add (filenameBox->getItemText (i));
  46787. return names;
  46788. }
  46789. void FilenameComponent::setRecentlyUsedFilenames (const StringArray& filenames)
  46790. {
  46791. if (filenames != getRecentlyUsedFilenames())
  46792. {
  46793. filenameBox->clear();
  46794. for (int i = 0; i < jmin (filenames.size(), maxRecentFiles); ++i)
  46795. filenameBox->addItem (filenames[i], i + 1);
  46796. }
  46797. }
  46798. void FilenameComponent::setMaxNumberOfRecentFiles (const int newMaximum)
  46799. {
  46800. maxRecentFiles = jmax (1, newMaximum);
  46801. setRecentlyUsedFilenames (getRecentlyUsedFilenames());
  46802. }
  46803. void FilenameComponent::addRecentlyUsedFile (const File& file)
  46804. {
  46805. StringArray files (getRecentlyUsedFilenames());
  46806. if (file.getFullPathName().isNotEmpty())
  46807. {
  46808. files.removeString (file.getFullPathName(), true);
  46809. files.insert (0, file.getFullPathName());
  46810. setRecentlyUsedFilenames (files);
  46811. }
  46812. }
  46813. void FilenameComponent::addListener (FilenameComponentListener* const listener)
  46814. {
  46815. listeners.add (listener);
  46816. }
  46817. void FilenameComponent::removeListener (FilenameComponentListener* const listener)
  46818. {
  46819. listeners.remove (listener);
  46820. }
  46821. void FilenameComponent::handleAsyncUpdate()
  46822. {
  46823. Component::BailOutChecker checker (this);
  46824. listeners.callChecked (checker, &FilenameComponentListener::filenameComponentChanged, this);
  46825. }
  46826. END_JUCE_NAMESPACE
  46827. /*** End of inlined file: juce_FilenameComponent.cpp ***/
  46828. /*** Start of inlined file: juce_FileSearchPathListComponent.cpp ***/
  46829. BEGIN_JUCE_NAMESPACE
  46830. FileSearchPathListComponent::FileSearchPathListComponent()
  46831. {
  46832. addAndMakeVisible (listBox = new ListBox (String::empty, this));
  46833. listBox->setColour (ListBox::backgroundColourId, Colours::black.withAlpha (0.02f));
  46834. listBox->setColour (ListBox::outlineColourId, Colours::black.withAlpha (0.1f));
  46835. listBox->setOutlineThickness (1);
  46836. addAndMakeVisible (addButton = new TextButton ("+"));
  46837. addButton->addButtonListener (this);
  46838. addButton->setConnectedEdges (Button::ConnectedOnLeft | Button::ConnectedOnRight | Button::ConnectedOnBottom | Button::ConnectedOnTop);
  46839. addAndMakeVisible (removeButton = new TextButton ("-"));
  46840. removeButton->addButtonListener (this);
  46841. removeButton->setConnectedEdges (Button::ConnectedOnLeft | Button::ConnectedOnRight | Button::ConnectedOnBottom | Button::ConnectedOnTop);
  46842. addAndMakeVisible (changeButton = new TextButton (TRANS("change...")));
  46843. changeButton->addButtonListener (this);
  46844. addAndMakeVisible (upButton = new DrawableButton (String::empty, DrawableButton::ImageOnButtonBackground));
  46845. upButton->addButtonListener (this);
  46846. {
  46847. Path arrowPath;
  46848. arrowPath.addArrow (50.0f, 100.0f, 50.0f, 0.0f, 40.0f, 100.0f, 50.0f);
  46849. DrawablePath arrowImage;
  46850. arrowImage.setFill (Colours::black.withAlpha (0.4f));
  46851. arrowImage.setPath (arrowPath);
  46852. upButton->setImages (&arrowImage);
  46853. }
  46854. addAndMakeVisible (downButton = new DrawableButton (String::empty, DrawableButton::ImageOnButtonBackground));
  46855. downButton->addButtonListener (this);
  46856. {
  46857. Path arrowPath;
  46858. arrowPath.addArrow (50.0f, 0.0f, 50.0f, 100.0f, 40.0f, 100.0f, 50.0f);
  46859. DrawablePath arrowImage;
  46860. arrowImage.setFill (Colours::black.withAlpha (0.4f));
  46861. arrowImage.setPath (arrowPath);
  46862. downButton->setImages (&arrowImage);
  46863. }
  46864. updateButtons();
  46865. }
  46866. FileSearchPathListComponent::~FileSearchPathListComponent()
  46867. {
  46868. deleteAllChildren();
  46869. }
  46870. void FileSearchPathListComponent::updateButtons()
  46871. {
  46872. const bool anythingSelected = listBox->getNumSelectedRows() > 0;
  46873. removeButton->setEnabled (anythingSelected);
  46874. changeButton->setEnabled (anythingSelected);
  46875. upButton->setEnabled (anythingSelected);
  46876. downButton->setEnabled (anythingSelected);
  46877. }
  46878. void FileSearchPathListComponent::changed()
  46879. {
  46880. listBox->updateContent();
  46881. listBox->repaint();
  46882. updateButtons();
  46883. }
  46884. void FileSearchPathListComponent::setPath (const FileSearchPath& newPath)
  46885. {
  46886. if (newPath.toString() != path.toString())
  46887. {
  46888. path = newPath;
  46889. changed();
  46890. }
  46891. }
  46892. void FileSearchPathListComponent::setDefaultBrowseTarget (const File& newDefaultDirectory)
  46893. {
  46894. defaultBrowseTarget = newDefaultDirectory;
  46895. }
  46896. int FileSearchPathListComponent::getNumRows()
  46897. {
  46898. return path.getNumPaths();
  46899. }
  46900. void FileSearchPathListComponent::paintListBoxItem (int rowNumber, Graphics& g, int width, int height, bool rowIsSelected)
  46901. {
  46902. if (rowIsSelected)
  46903. g.fillAll (findColour (TextEditor::highlightColourId));
  46904. g.setColour (findColour (ListBox::textColourId));
  46905. Font f (height * 0.7f);
  46906. f.setHorizontalScale (0.9f);
  46907. g.setFont (f);
  46908. g.drawText (path [rowNumber].getFullPathName(),
  46909. 4, 0, width - 6, height,
  46910. Justification::centredLeft, true);
  46911. }
  46912. void FileSearchPathListComponent::deleteKeyPressed (int row)
  46913. {
  46914. if (((unsigned int) row) < (unsigned int) path.getNumPaths())
  46915. {
  46916. path.remove (row);
  46917. changed();
  46918. }
  46919. }
  46920. void FileSearchPathListComponent::returnKeyPressed (int row)
  46921. {
  46922. FileChooser chooser (TRANS("Change folder..."), path [row], "*");
  46923. if (chooser.browseForDirectory())
  46924. {
  46925. path.remove (row);
  46926. path.add (chooser.getResult(), row);
  46927. changed();
  46928. }
  46929. }
  46930. void FileSearchPathListComponent::listBoxItemDoubleClicked (int row, const MouseEvent&)
  46931. {
  46932. returnKeyPressed (row);
  46933. }
  46934. void FileSearchPathListComponent::selectedRowsChanged (int)
  46935. {
  46936. updateButtons();
  46937. }
  46938. void FileSearchPathListComponent::paint (Graphics& g)
  46939. {
  46940. g.fillAll (findColour (backgroundColourId));
  46941. }
  46942. void FileSearchPathListComponent::resized()
  46943. {
  46944. const int buttonH = 22;
  46945. const int buttonY = getHeight() - buttonH - 4;
  46946. listBox->setBounds (2, 2, getWidth() - 4, buttonY - 5);
  46947. addButton->setBounds (2, buttonY, buttonH, buttonH);
  46948. removeButton->setBounds (addButton->getRight(), buttonY, buttonH, buttonH);
  46949. changeButton->changeWidthToFitText (buttonH);
  46950. downButton->setSize (buttonH * 2, buttonH);
  46951. upButton->setSize (buttonH * 2, buttonH);
  46952. downButton->setTopRightPosition (getWidth() - 2, buttonY);
  46953. upButton->setTopRightPosition (downButton->getX() - 4, buttonY);
  46954. changeButton->setTopRightPosition (upButton->getX() - 8, buttonY);
  46955. }
  46956. bool FileSearchPathListComponent::isInterestedInFileDrag (const StringArray&)
  46957. {
  46958. return true;
  46959. }
  46960. void FileSearchPathListComponent::filesDropped (const StringArray& filenames, int, int mouseY)
  46961. {
  46962. for (int i = filenames.size(); --i >= 0;)
  46963. {
  46964. const File f (filenames[i]);
  46965. if (f.isDirectory())
  46966. {
  46967. const int row = listBox->getRowContainingPosition (0, mouseY - listBox->getY());
  46968. path.add (f, row);
  46969. changed();
  46970. }
  46971. }
  46972. }
  46973. void FileSearchPathListComponent::buttonClicked (Button* button)
  46974. {
  46975. const int currentRow = listBox->getSelectedRow();
  46976. if (button == removeButton)
  46977. {
  46978. deleteKeyPressed (currentRow);
  46979. }
  46980. else if (button == addButton)
  46981. {
  46982. File start (defaultBrowseTarget);
  46983. if (start == File::nonexistent)
  46984. start = path [0];
  46985. if (start == File::nonexistent)
  46986. start = File::getCurrentWorkingDirectory();
  46987. FileChooser chooser (TRANS("Add a folder..."), start, "*");
  46988. if (chooser.browseForDirectory())
  46989. {
  46990. path.add (chooser.getResult(), currentRow);
  46991. }
  46992. }
  46993. else if (button == changeButton)
  46994. {
  46995. returnKeyPressed (currentRow);
  46996. }
  46997. else if (button == upButton)
  46998. {
  46999. if (currentRow > 0 && currentRow < path.getNumPaths())
  47000. {
  47001. const File f (path[currentRow]);
  47002. path.remove (currentRow);
  47003. path.add (f, currentRow - 1);
  47004. listBox->selectRow (currentRow - 1);
  47005. }
  47006. }
  47007. else if (button == downButton)
  47008. {
  47009. if (currentRow >= 0 && currentRow < path.getNumPaths() - 1)
  47010. {
  47011. const File f (path[currentRow]);
  47012. path.remove (currentRow);
  47013. path.add (f, currentRow + 1);
  47014. listBox->selectRow (currentRow + 1);
  47015. }
  47016. }
  47017. changed();
  47018. }
  47019. END_JUCE_NAMESPACE
  47020. /*** End of inlined file: juce_FileSearchPathListComponent.cpp ***/
  47021. /*** Start of inlined file: juce_FileTreeComponent.cpp ***/
  47022. BEGIN_JUCE_NAMESPACE
  47023. Image* juce_createIconForFile (const File& file);
  47024. class FileListTreeItem : public TreeViewItem,
  47025. public TimeSliceClient,
  47026. public AsyncUpdater,
  47027. public ChangeListener
  47028. {
  47029. public:
  47030. FileListTreeItem (FileTreeComponent& owner_,
  47031. DirectoryContentsList* const parentContentsList_,
  47032. const int indexInContentsList_,
  47033. const File& file_,
  47034. TimeSliceThread& thread_)
  47035. : file (file_),
  47036. owner (owner_),
  47037. parentContentsList (parentContentsList_),
  47038. indexInContentsList (indexInContentsList_),
  47039. subContentsList (0),
  47040. canDeleteSubContentsList (false),
  47041. thread (thread_),
  47042. icon (0)
  47043. {
  47044. DirectoryContentsList::FileInfo fileInfo;
  47045. if (parentContentsList_ != 0
  47046. && parentContentsList_->getFileInfo (indexInContentsList_, fileInfo))
  47047. {
  47048. fileSize = File::descriptionOfSizeInBytes (fileInfo.fileSize);
  47049. modTime = fileInfo.modificationTime.formatted ("%d %b '%y %H:%M");
  47050. isDirectory = fileInfo.isDirectory;
  47051. }
  47052. else
  47053. {
  47054. isDirectory = true;
  47055. }
  47056. }
  47057. ~FileListTreeItem()
  47058. {
  47059. thread.removeTimeSliceClient (this);
  47060. clearSubItems();
  47061. ImageCache::release (icon);
  47062. if (canDeleteSubContentsList)
  47063. delete subContentsList;
  47064. }
  47065. bool mightContainSubItems() { return isDirectory; }
  47066. const String getUniqueName() const { return file.getFullPathName(); }
  47067. int getItemHeight() const { return 22; }
  47068. const String getDragSourceDescription() { return owner.getDragAndDropDescription(); }
  47069. void itemOpennessChanged (bool isNowOpen)
  47070. {
  47071. if (isNowOpen)
  47072. {
  47073. clearSubItems();
  47074. isDirectory = file.isDirectory();
  47075. if (isDirectory)
  47076. {
  47077. if (subContentsList == 0)
  47078. {
  47079. jassert (parentContentsList != 0);
  47080. DirectoryContentsList* const l = new DirectoryContentsList (parentContentsList->getFilter(), thread);
  47081. l->setDirectory (file, true, true);
  47082. setSubContentsList (l);
  47083. canDeleteSubContentsList = true;
  47084. }
  47085. changeListenerCallback (0);
  47086. }
  47087. }
  47088. }
  47089. void setSubContentsList (DirectoryContentsList* newList)
  47090. {
  47091. jassert (subContentsList == 0);
  47092. subContentsList = newList;
  47093. newList->addChangeListener (this);
  47094. }
  47095. void changeListenerCallback (void*)
  47096. {
  47097. clearSubItems();
  47098. if (isOpen() && subContentsList != 0)
  47099. {
  47100. for (int i = 0; i < subContentsList->getNumFiles(); ++i)
  47101. {
  47102. FileListTreeItem* const item
  47103. = new FileListTreeItem (owner, subContentsList, i, subContentsList->getFile(i), thread);
  47104. addSubItem (item);
  47105. }
  47106. }
  47107. }
  47108. void paintItem (Graphics& g, int width, int height)
  47109. {
  47110. if (file != File::nonexistent)
  47111. {
  47112. updateIcon (true);
  47113. if (icon == 0)
  47114. thread.addTimeSliceClient (this);
  47115. }
  47116. owner.getLookAndFeel()
  47117. .drawFileBrowserRow (g, width, height,
  47118. file.getFileName(),
  47119. icon,
  47120. fileSize, modTime,
  47121. isDirectory, isSelected(),
  47122. indexInContentsList);
  47123. }
  47124. void itemClicked (const MouseEvent& e)
  47125. {
  47126. owner.sendMouseClickMessage (file, e);
  47127. }
  47128. void itemDoubleClicked (const MouseEvent& e)
  47129. {
  47130. TreeViewItem::itemDoubleClicked (e);
  47131. owner.sendDoubleClickMessage (file);
  47132. }
  47133. void itemSelectionChanged (bool)
  47134. {
  47135. owner.sendSelectionChangeMessage();
  47136. }
  47137. bool useTimeSlice()
  47138. {
  47139. updateIcon (false);
  47140. thread.removeTimeSliceClient (this);
  47141. return false;
  47142. }
  47143. void handleAsyncUpdate()
  47144. {
  47145. owner.repaint();
  47146. }
  47147. const File file;
  47148. juce_UseDebuggingNewOperator
  47149. private:
  47150. FileTreeComponent& owner;
  47151. DirectoryContentsList* parentContentsList;
  47152. int indexInContentsList;
  47153. DirectoryContentsList* subContentsList;
  47154. bool isDirectory, canDeleteSubContentsList;
  47155. TimeSliceThread& thread;
  47156. Image* icon;
  47157. String fileSize;
  47158. String modTime;
  47159. void updateIcon (const bool onlyUpdateIfCached)
  47160. {
  47161. if (icon == 0)
  47162. {
  47163. const int hashCode = (file.getFullPathName() + "_iconCacheSalt").hashCode();
  47164. Image* im = ImageCache::getFromHashCode (hashCode);
  47165. if (im == 0 && ! onlyUpdateIfCached)
  47166. {
  47167. im = juce_createIconForFile (file);
  47168. if (im != 0)
  47169. ImageCache::addImageToCache (im, hashCode);
  47170. }
  47171. if (im != 0)
  47172. {
  47173. icon = im;
  47174. triggerAsyncUpdate();
  47175. }
  47176. }
  47177. }
  47178. };
  47179. FileTreeComponent::FileTreeComponent (DirectoryContentsList& listToShow)
  47180. : DirectoryContentsDisplayComponent (listToShow)
  47181. {
  47182. FileListTreeItem* const root
  47183. = new FileListTreeItem (*this, 0, 0, listToShow.getDirectory(),
  47184. listToShow.getTimeSliceThread());
  47185. root->setSubContentsList (&listToShow);
  47186. setRootItemVisible (false);
  47187. setRootItem (root);
  47188. }
  47189. FileTreeComponent::~FileTreeComponent()
  47190. {
  47191. deleteRootItem();
  47192. }
  47193. const File FileTreeComponent::getSelectedFile (const int index) const
  47194. {
  47195. const FileListTreeItem* const item = dynamic_cast <const FileListTreeItem*> (getSelectedItem (index));
  47196. return item != 0 ? item->file
  47197. : File::nonexistent;
  47198. }
  47199. void FileTreeComponent::deselectAllFiles()
  47200. {
  47201. clearSelectedItems();
  47202. }
  47203. void FileTreeComponent::scrollToTop()
  47204. {
  47205. getViewport()->getVerticalScrollBar()->setCurrentRangeStart (0);
  47206. }
  47207. void FileTreeComponent::setDragAndDropDescription (const String& description)
  47208. {
  47209. dragAndDropDescription = description;
  47210. }
  47211. END_JUCE_NAMESPACE
  47212. /*** End of inlined file: juce_FileTreeComponent.cpp ***/
  47213. /*** Start of inlined file: juce_ImagePreviewComponent.cpp ***/
  47214. BEGIN_JUCE_NAMESPACE
  47215. ImagePreviewComponent::ImagePreviewComponent()
  47216. {
  47217. }
  47218. ImagePreviewComponent::~ImagePreviewComponent()
  47219. {
  47220. }
  47221. void ImagePreviewComponent::getThumbSize (int& w, int& h) const
  47222. {
  47223. const int availableW = proportionOfWidth (0.97f);
  47224. const int availableH = getHeight() - 13 * 4;
  47225. const double scale = jmin (1.0,
  47226. availableW / (double) w,
  47227. availableH / (double) h);
  47228. w = roundToInt (scale * w);
  47229. h = roundToInt (scale * h);
  47230. }
  47231. void ImagePreviewComponent::selectedFileChanged (const File& file)
  47232. {
  47233. if (fileToLoad != file)
  47234. {
  47235. fileToLoad = file;
  47236. startTimer (100);
  47237. }
  47238. }
  47239. void ImagePreviewComponent::timerCallback()
  47240. {
  47241. stopTimer();
  47242. currentThumbnail = 0;
  47243. currentDetails = String::empty;
  47244. repaint();
  47245. ScopedPointer <FileInputStream> in (fileToLoad.createInputStream());
  47246. if (in != 0)
  47247. {
  47248. ImageFileFormat* const format = ImageFileFormat::findImageFormatForStream (*in);
  47249. if (format != 0)
  47250. {
  47251. currentThumbnail = format->decodeImage (*in);
  47252. if (currentThumbnail != 0)
  47253. {
  47254. int w = currentThumbnail->getWidth();
  47255. int h = currentThumbnail->getHeight();
  47256. currentDetails
  47257. << fileToLoad.getFileName() << "\n"
  47258. << format->getFormatName() << "\n"
  47259. << w << " x " << h << " pixels\n"
  47260. << File::descriptionOfSizeInBytes (fileToLoad.getSize());
  47261. getThumbSize (w, h);
  47262. currentThumbnail = currentThumbnail->createCopy (w, h);
  47263. }
  47264. }
  47265. }
  47266. }
  47267. void ImagePreviewComponent::paint (Graphics& g)
  47268. {
  47269. if (currentThumbnail != 0)
  47270. {
  47271. g.setFont (13.0f);
  47272. int w = currentThumbnail->getWidth();
  47273. int h = currentThumbnail->getHeight();
  47274. getThumbSize (w, h);
  47275. const int numLines = 4;
  47276. const int totalH = 13 * numLines + h + 4;
  47277. const int y = (getHeight() - totalH) / 2;
  47278. g.drawImageWithin (currentThumbnail,
  47279. (getWidth() - w) / 2, y, w, h,
  47280. RectanglePlacement::centred | RectanglePlacement::onlyReduceInSize,
  47281. false);
  47282. g.drawFittedText (currentDetails,
  47283. 0, y + h + 4, getWidth(), 100,
  47284. Justification::centredTop, numLines);
  47285. }
  47286. }
  47287. END_JUCE_NAMESPACE
  47288. /*** End of inlined file: juce_ImagePreviewComponent.cpp ***/
  47289. /*** Start of inlined file: juce_WildcardFileFilter.cpp ***/
  47290. BEGIN_JUCE_NAMESPACE
  47291. WildcardFileFilter::WildcardFileFilter (const String& fileWildcardPatterns,
  47292. const String& directoryWildcardPatterns,
  47293. const String& description_)
  47294. : FileFilter (description_.isEmpty() ? fileWildcardPatterns
  47295. : (description_ + " (" + fileWildcardPatterns + ")"))
  47296. {
  47297. parse (fileWildcardPatterns, fileWildcards);
  47298. parse (directoryWildcardPatterns, directoryWildcards);
  47299. }
  47300. WildcardFileFilter::~WildcardFileFilter()
  47301. {
  47302. }
  47303. bool WildcardFileFilter::isFileSuitable (const File& file) const
  47304. {
  47305. return match (file, fileWildcards);
  47306. }
  47307. bool WildcardFileFilter::isDirectorySuitable (const File& file) const
  47308. {
  47309. return match (file, directoryWildcards);
  47310. }
  47311. void WildcardFileFilter::parse (const String& pattern, StringArray& result)
  47312. {
  47313. result.addTokens (pattern.toLowerCase(), ";,", "\"'");
  47314. result.trim();
  47315. result.removeEmptyStrings();
  47316. // special case for *.*, because people use it to mean "any file", but it
  47317. // would actually ignore files with no extension.
  47318. for (int i = result.size(); --i >= 0;)
  47319. if (result[i] == "*.*")
  47320. result.set (i, "*");
  47321. }
  47322. bool WildcardFileFilter::match (const File& file, const StringArray& wildcards)
  47323. {
  47324. const String filename (file.getFileName());
  47325. for (int i = wildcards.size(); --i >= 0;)
  47326. if (filename.matchesWildcard (wildcards[i], true))
  47327. return true;
  47328. return false;
  47329. }
  47330. END_JUCE_NAMESPACE
  47331. /*** End of inlined file: juce_WildcardFileFilter.cpp ***/
  47332. /*** Start of inlined file: juce_KeyboardFocusTraverser.cpp ***/
  47333. BEGIN_JUCE_NAMESPACE
  47334. KeyboardFocusTraverser::KeyboardFocusTraverser()
  47335. {
  47336. }
  47337. KeyboardFocusTraverser::~KeyboardFocusTraverser()
  47338. {
  47339. }
  47340. namespace KeyboardFocusHelpers
  47341. {
  47342. // This will sort a set of components, so that they are ordered in terms of
  47343. // left-to-right and then top-to-bottom.
  47344. class ScreenPositionComparator
  47345. {
  47346. public:
  47347. ScreenPositionComparator() {}
  47348. static int compareElements (const Component* const first, const Component* const second)
  47349. {
  47350. int explicitOrder1 = first->getExplicitFocusOrder();
  47351. if (explicitOrder1 <= 0)
  47352. explicitOrder1 = std::numeric_limits<int>::max() / 2;
  47353. int explicitOrder2 = second->getExplicitFocusOrder();
  47354. if (explicitOrder2 <= 0)
  47355. explicitOrder2 = std::numeric_limits<int>::max() / 2;
  47356. if (explicitOrder1 != explicitOrder2)
  47357. return explicitOrder1 - explicitOrder2;
  47358. const int diff = first->getY() - second->getY();
  47359. return (diff == 0) ? first->getX() - second->getX()
  47360. : diff;
  47361. }
  47362. };
  47363. static void findAllFocusableComponents (Component* const parent, Array <Component*>& comps)
  47364. {
  47365. if (parent->getNumChildComponents() > 0)
  47366. {
  47367. Array <Component*> localComps;
  47368. ScreenPositionComparator comparator;
  47369. int i;
  47370. for (i = parent->getNumChildComponents(); --i >= 0;)
  47371. {
  47372. Component* const c = parent->getChildComponent (i);
  47373. if (c->isVisible() && c->isEnabled())
  47374. localComps.addSorted (comparator, c);
  47375. }
  47376. for (i = 0; i < localComps.size(); ++i)
  47377. {
  47378. Component* const c = localComps.getUnchecked (i);
  47379. if (c->getWantsKeyboardFocus())
  47380. comps.add (c);
  47381. if (! c->isFocusContainer())
  47382. findAllFocusableComponents (c, comps);
  47383. }
  47384. }
  47385. }
  47386. }
  47387. static Component* getIncrementedComponent (Component* const current, const int delta)
  47388. {
  47389. Component* focusContainer = current->getParentComponent();
  47390. if (focusContainer != 0)
  47391. {
  47392. while (focusContainer->getParentComponent() != 0 && ! focusContainer->isFocusContainer())
  47393. focusContainer = focusContainer->getParentComponent();
  47394. if (focusContainer != 0)
  47395. {
  47396. Array <Component*> comps;
  47397. KeyboardFocusHelpers::findAllFocusableComponents (focusContainer, comps);
  47398. if (comps.size() > 0)
  47399. {
  47400. const int index = comps.indexOf (current);
  47401. return comps [(index + comps.size() + delta) % comps.size()];
  47402. }
  47403. }
  47404. }
  47405. return 0;
  47406. }
  47407. Component* KeyboardFocusTraverser::getNextComponent (Component* current)
  47408. {
  47409. return getIncrementedComponent (current, 1);
  47410. }
  47411. Component* KeyboardFocusTraverser::getPreviousComponent (Component* current)
  47412. {
  47413. return getIncrementedComponent (current, -1);
  47414. }
  47415. Component* KeyboardFocusTraverser::getDefaultComponent (Component* parentComponent)
  47416. {
  47417. Array <Component*> comps;
  47418. if (parentComponent != 0)
  47419. KeyboardFocusHelpers::findAllFocusableComponents (parentComponent, comps);
  47420. return comps.getFirst();
  47421. }
  47422. END_JUCE_NAMESPACE
  47423. /*** End of inlined file: juce_KeyboardFocusTraverser.cpp ***/
  47424. /*** Start of inlined file: juce_KeyListener.cpp ***/
  47425. BEGIN_JUCE_NAMESPACE
  47426. bool KeyListener::keyStateChanged (const bool, Component*)
  47427. {
  47428. return false;
  47429. }
  47430. END_JUCE_NAMESPACE
  47431. /*** End of inlined file: juce_KeyListener.cpp ***/
  47432. /*** Start of inlined file: juce_KeyMappingEditorComponent.cpp ***/
  47433. BEGIN_JUCE_NAMESPACE
  47434. // N.B. these two includes are put here deliberately to avoid problems with
  47435. // old GCCs failing on long include paths
  47436. const int maxKeys = 3;
  47437. class KeyMappingChangeButton : public Button
  47438. {
  47439. public:
  47440. KeyMappingChangeButton (KeyMappingEditorComponent* const owner_,
  47441. const CommandID commandID_,
  47442. const String& keyName,
  47443. const int keyNum_)
  47444. : Button (keyName),
  47445. owner (owner_),
  47446. commandID (commandID_),
  47447. keyNum (keyNum_)
  47448. {
  47449. setWantsKeyboardFocus (false);
  47450. setTriggeredOnMouseDown (keyNum >= 0);
  47451. if (keyNum_ < 0)
  47452. setTooltip (TRANS("adds a new key-mapping"));
  47453. else
  47454. setTooltip (TRANS("click to change this key-mapping"));
  47455. }
  47456. ~KeyMappingChangeButton()
  47457. {
  47458. }
  47459. void paintButton (Graphics& g, bool /*isOver*/, bool /*isDown*/)
  47460. {
  47461. getLookAndFeel().drawKeymapChangeButton (g, getWidth(), getHeight(), *this,
  47462. keyNum >= 0 ? getName() : String::empty);
  47463. }
  47464. void clicked()
  47465. {
  47466. if (keyNum >= 0)
  47467. {
  47468. // existing key clicked..
  47469. PopupMenu m;
  47470. m.addItem (1, TRANS("change this key-mapping"));
  47471. m.addSeparator();
  47472. m.addItem (2, TRANS("remove this key-mapping"));
  47473. const int res = m.show();
  47474. if (res == 1)
  47475. {
  47476. owner->assignNewKey (commandID, keyNum);
  47477. }
  47478. else if (res == 2)
  47479. {
  47480. owner->getMappings()->removeKeyPress (commandID, keyNum);
  47481. }
  47482. }
  47483. else
  47484. {
  47485. // + button pressed..
  47486. owner->assignNewKey (commandID, -1);
  47487. }
  47488. }
  47489. void fitToContent (const int h) throw()
  47490. {
  47491. if (keyNum < 0)
  47492. {
  47493. setSize (h, h);
  47494. }
  47495. else
  47496. {
  47497. Font f (h * 0.6f);
  47498. setSize (jlimit (h * 4, h * 8, 6 + f.getStringWidth (getName())), h);
  47499. }
  47500. }
  47501. juce_UseDebuggingNewOperator
  47502. private:
  47503. KeyMappingEditorComponent* const owner;
  47504. const CommandID commandID;
  47505. const int keyNum;
  47506. KeyMappingChangeButton (const KeyMappingChangeButton&);
  47507. KeyMappingChangeButton& operator= (const KeyMappingChangeButton&);
  47508. };
  47509. class KeyMappingItemComponent : public Component
  47510. {
  47511. public:
  47512. KeyMappingItemComponent (KeyMappingEditorComponent* const owner_,
  47513. const CommandID commandID_)
  47514. : owner (owner_),
  47515. commandID (commandID_)
  47516. {
  47517. setInterceptsMouseClicks (false, true);
  47518. const bool isReadOnly = owner_->isCommandReadOnly (commandID);
  47519. const Array <KeyPress> keyPresses (owner_->getMappings()->getKeyPressesAssignedToCommand (commandID));
  47520. for (int i = 0; i < jmin (maxKeys, keyPresses.size()); ++i)
  47521. {
  47522. KeyMappingChangeButton* const kb
  47523. = new KeyMappingChangeButton (owner_, commandID,
  47524. owner_->getDescriptionForKeyPress (keyPresses.getReference (i)), i);
  47525. kb->setEnabled (! isReadOnly);
  47526. addAndMakeVisible (kb);
  47527. }
  47528. KeyMappingChangeButton* const kb
  47529. = new KeyMappingChangeButton (owner_, commandID, String::empty, -1);
  47530. addChildComponent (kb);
  47531. kb->setVisible (keyPresses.size() < maxKeys && ! isReadOnly);
  47532. }
  47533. ~KeyMappingItemComponent()
  47534. {
  47535. deleteAllChildren();
  47536. }
  47537. void paint (Graphics& g)
  47538. {
  47539. g.setFont (getHeight() * 0.7f);
  47540. g.setColour (findColour (KeyMappingEditorComponent::textColourId));
  47541. g.drawFittedText (owner->getMappings()->getCommandManager()->getNameOfCommand (commandID),
  47542. 4, 0, jmax (40, getChildComponent (0)->getX() - 5), getHeight(),
  47543. Justification::centredLeft, true);
  47544. }
  47545. void resized()
  47546. {
  47547. int x = getWidth() - 4;
  47548. for (int i = getNumChildComponents(); --i >= 0;)
  47549. {
  47550. KeyMappingChangeButton* const kb = dynamic_cast <KeyMappingChangeButton*> (getChildComponent (i));
  47551. kb->fitToContent (getHeight() - 2);
  47552. kb->setTopRightPosition (x, 1);
  47553. x -= kb->getWidth() + 5;
  47554. }
  47555. }
  47556. juce_UseDebuggingNewOperator
  47557. private:
  47558. KeyMappingEditorComponent* const owner;
  47559. const CommandID commandID;
  47560. KeyMappingItemComponent (const KeyMappingItemComponent&);
  47561. KeyMappingItemComponent& operator= (const KeyMappingItemComponent&);
  47562. };
  47563. class KeyMappingTreeViewItem : public TreeViewItem
  47564. {
  47565. public:
  47566. KeyMappingTreeViewItem (KeyMappingEditorComponent* const owner_,
  47567. const CommandID commandID_)
  47568. : owner (owner_),
  47569. commandID (commandID_)
  47570. {
  47571. }
  47572. ~KeyMappingTreeViewItem()
  47573. {
  47574. }
  47575. const String getUniqueName() const { return String ((int) commandID) + "_id"; }
  47576. bool mightContainSubItems() { return false; }
  47577. int getItemHeight() const { return 20; }
  47578. Component* createItemComponent()
  47579. {
  47580. return new KeyMappingItemComponent (owner, commandID);
  47581. }
  47582. juce_UseDebuggingNewOperator
  47583. private:
  47584. KeyMappingEditorComponent* const owner;
  47585. const CommandID commandID;
  47586. KeyMappingTreeViewItem (const KeyMappingTreeViewItem&);
  47587. KeyMappingTreeViewItem& operator= (const KeyMappingTreeViewItem&);
  47588. };
  47589. class KeyCategoryTreeViewItem : public TreeViewItem
  47590. {
  47591. public:
  47592. KeyCategoryTreeViewItem (KeyMappingEditorComponent* const owner_,
  47593. const String& name)
  47594. : owner (owner_),
  47595. categoryName (name)
  47596. {
  47597. }
  47598. ~KeyCategoryTreeViewItem()
  47599. {
  47600. }
  47601. const String getUniqueName() const { return categoryName + "_cat"; }
  47602. bool mightContainSubItems() { return true; }
  47603. int getItemHeight() const { return 28; }
  47604. void paintItem (Graphics& g, int width, int height)
  47605. {
  47606. g.setFont (height * 0.6f, Font::bold);
  47607. g.setColour (owner->findColour (KeyMappingEditorComponent::textColourId));
  47608. g.drawText (categoryName,
  47609. 2, 0, width - 2, height,
  47610. Justification::centredLeft, true);
  47611. }
  47612. void itemOpennessChanged (bool isNowOpen)
  47613. {
  47614. if (isNowOpen)
  47615. {
  47616. if (getNumSubItems() == 0)
  47617. {
  47618. Array <CommandID> commands (owner->getMappings()->getCommandManager()->getCommandsInCategory (categoryName));
  47619. for (int i = 0; i < commands.size(); ++i)
  47620. {
  47621. if (owner->shouldCommandBeIncluded (commands[i]))
  47622. addSubItem (new KeyMappingTreeViewItem (owner, commands[i]));
  47623. }
  47624. }
  47625. }
  47626. else
  47627. {
  47628. clearSubItems();
  47629. }
  47630. }
  47631. juce_UseDebuggingNewOperator
  47632. private:
  47633. KeyMappingEditorComponent* owner;
  47634. String categoryName;
  47635. KeyCategoryTreeViewItem (const KeyCategoryTreeViewItem&);
  47636. KeyCategoryTreeViewItem& operator= (const KeyCategoryTreeViewItem&);
  47637. };
  47638. KeyMappingEditorComponent::KeyMappingEditorComponent (KeyPressMappingSet* const mappingManager,
  47639. const bool showResetToDefaultButton)
  47640. : mappings (mappingManager)
  47641. {
  47642. jassert (mappingManager != 0); // can't be null!
  47643. mappingManager->addChangeListener (this);
  47644. setLinesDrawnForSubItems (false);
  47645. resetButton = 0;
  47646. if (showResetToDefaultButton)
  47647. {
  47648. addAndMakeVisible (resetButton = new TextButton (TRANS("reset to defaults")));
  47649. resetButton->addButtonListener (this);
  47650. }
  47651. addAndMakeVisible (tree = new TreeView());
  47652. tree->setColour (TreeView::backgroundColourId, findColour (backgroundColourId));
  47653. tree->setRootItemVisible (false);
  47654. tree->setDefaultOpenness (true);
  47655. tree->setRootItem (this);
  47656. }
  47657. KeyMappingEditorComponent::~KeyMappingEditorComponent()
  47658. {
  47659. mappings->removeChangeListener (this);
  47660. deleteAllChildren();
  47661. }
  47662. bool KeyMappingEditorComponent::mightContainSubItems()
  47663. {
  47664. return true;
  47665. }
  47666. const String KeyMappingEditorComponent::getUniqueName() const
  47667. {
  47668. return "keys";
  47669. }
  47670. void KeyMappingEditorComponent::setColours (const Colour& mainBackground,
  47671. const Colour& textColour)
  47672. {
  47673. setColour (backgroundColourId, mainBackground);
  47674. setColour (textColourId, textColour);
  47675. tree->setColour (TreeView::backgroundColourId, mainBackground);
  47676. }
  47677. void KeyMappingEditorComponent::parentHierarchyChanged()
  47678. {
  47679. changeListenerCallback (0);
  47680. }
  47681. void KeyMappingEditorComponent::resized()
  47682. {
  47683. int h = getHeight();
  47684. if (resetButton != 0)
  47685. {
  47686. const int buttonHeight = 20;
  47687. h -= buttonHeight + 8;
  47688. int x = getWidth() - 8;
  47689. resetButton->changeWidthToFitText (buttonHeight);
  47690. resetButton->setTopRightPosition (x, h + 6);
  47691. }
  47692. tree->setBounds (0, 0, getWidth(), h);
  47693. }
  47694. void KeyMappingEditorComponent::buttonClicked (Button* button)
  47695. {
  47696. if (button == resetButton)
  47697. {
  47698. if (AlertWindow::showOkCancelBox (AlertWindow::QuestionIcon,
  47699. TRANS("Reset to defaults"),
  47700. TRANS("Are you sure you want to reset all the key-mappings to their default state?"),
  47701. TRANS("Reset")))
  47702. {
  47703. mappings->resetToDefaultMappings();
  47704. }
  47705. }
  47706. }
  47707. void KeyMappingEditorComponent::changeListenerCallback (void*)
  47708. {
  47709. ScopedPointer <XmlElement> oldOpenness (tree->getOpennessState (true));
  47710. clearSubItems();
  47711. const StringArray categories (mappings->getCommandManager()->getCommandCategories());
  47712. for (int i = 0; i < categories.size(); ++i)
  47713. {
  47714. const Array <CommandID> commands (mappings->getCommandManager()->getCommandsInCategory (categories[i]));
  47715. int count = 0;
  47716. for (int j = 0; j < commands.size(); ++j)
  47717. if (shouldCommandBeIncluded (commands[j]))
  47718. ++count;
  47719. if (count > 0)
  47720. addSubItem (new KeyCategoryTreeViewItem (this, categories[i]));
  47721. }
  47722. if (oldOpenness != 0)
  47723. tree->restoreOpennessState (*oldOpenness);
  47724. }
  47725. class KeyEntryWindow : public AlertWindow
  47726. {
  47727. public:
  47728. KeyEntryWindow (KeyMappingEditorComponent* const owner_)
  47729. : AlertWindow (TRANS("New key-mapping"),
  47730. TRANS("Please press a key combination now..."),
  47731. AlertWindow::NoIcon),
  47732. owner (owner_)
  47733. {
  47734. addButton (TRANS("ok"), 1);
  47735. addButton (TRANS("cancel"), 0);
  47736. // (avoid return + escape keys getting processed by the buttons..)
  47737. for (int i = getNumChildComponents(); --i >= 0;)
  47738. getChildComponent (i)->setWantsKeyboardFocus (false);
  47739. setWantsKeyboardFocus (true);
  47740. grabKeyboardFocus();
  47741. }
  47742. ~KeyEntryWindow()
  47743. {
  47744. }
  47745. bool keyPressed (const KeyPress& key)
  47746. {
  47747. lastPress = key;
  47748. String message (TRANS("Key: ") + owner->getDescriptionForKeyPress (key));
  47749. const CommandID previousCommand = owner->getMappings()->findCommandForKeyPress (key);
  47750. if (previousCommand != 0)
  47751. {
  47752. message << "\n\n"
  47753. << TRANS("(Currently assigned to \"")
  47754. << owner->getMappings()->getCommandManager()->getNameOfCommand (previousCommand)
  47755. << "\")";
  47756. }
  47757. setMessage (message);
  47758. return true;
  47759. }
  47760. bool keyStateChanged (bool)
  47761. {
  47762. return true;
  47763. }
  47764. KeyPress lastPress;
  47765. juce_UseDebuggingNewOperator
  47766. private:
  47767. KeyMappingEditorComponent* owner;
  47768. KeyEntryWindow (const KeyEntryWindow&);
  47769. KeyEntryWindow& operator= (const KeyEntryWindow&);
  47770. };
  47771. void KeyMappingEditorComponent::assignNewKey (const CommandID commandID, const int index)
  47772. {
  47773. KeyEntryWindow entryWindow (this);
  47774. if (entryWindow.runModalLoop() != 0)
  47775. {
  47776. entryWindow.setVisible (false);
  47777. if (entryWindow.lastPress.isValid())
  47778. {
  47779. const CommandID previousCommand = mappings->findCommandForKeyPress (entryWindow.lastPress);
  47780. if (previousCommand != 0)
  47781. {
  47782. if (! AlertWindow::showOkCancelBox (AlertWindow::WarningIcon,
  47783. TRANS("Change key-mapping"),
  47784. TRANS("This key is already assigned to the command \"")
  47785. + mappings->getCommandManager()->getNameOfCommand (previousCommand)
  47786. + TRANS("\"\n\nDo you want to re-assign it to this new command instead?"),
  47787. TRANS("re-assign"),
  47788. TRANS("cancel")))
  47789. {
  47790. return;
  47791. }
  47792. }
  47793. mappings->removeKeyPress (entryWindow.lastPress);
  47794. if (index >= 0)
  47795. mappings->removeKeyPress (commandID, index);
  47796. mappings->addKeyPress (commandID, entryWindow.lastPress, index);
  47797. }
  47798. }
  47799. }
  47800. bool KeyMappingEditorComponent::shouldCommandBeIncluded (const CommandID commandID)
  47801. {
  47802. const ApplicationCommandInfo* const ci = mappings->getCommandManager()->getCommandForID (commandID);
  47803. return (ci != 0) && ((ci->flags & ApplicationCommandInfo::hiddenFromKeyEditor) == 0);
  47804. }
  47805. bool KeyMappingEditorComponent::isCommandReadOnly (const CommandID commandID)
  47806. {
  47807. const ApplicationCommandInfo* const ci = mappings->getCommandManager()->getCommandForID (commandID);
  47808. return (ci != 0) && ((ci->flags & ApplicationCommandInfo::readOnlyInKeyEditor) != 0);
  47809. }
  47810. const String KeyMappingEditorComponent::getDescriptionForKeyPress (const KeyPress& key)
  47811. {
  47812. return key.getTextDescription();
  47813. }
  47814. END_JUCE_NAMESPACE
  47815. /*** End of inlined file: juce_KeyMappingEditorComponent.cpp ***/
  47816. /*** Start of inlined file: juce_KeyPress.cpp ***/
  47817. BEGIN_JUCE_NAMESPACE
  47818. KeyPress::KeyPress() throw()
  47819. : keyCode (0),
  47820. mods (0),
  47821. textCharacter (0)
  47822. {
  47823. }
  47824. KeyPress::KeyPress (const int keyCode_,
  47825. const ModifierKeys& mods_,
  47826. const juce_wchar textCharacter_) throw()
  47827. : keyCode (keyCode_),
  47828. mods (mods_),
  47829. textCharacter (textCharacter_)
  47830. {
  47831. }
  47832. KeyPress::KeyPress (const int keyCode_) throw()
  47833. : keyCode (keyCode_),
  47834. textCharacter (0)
  47835. {
  47836. }
  47837. KeyPress::KeyPress (const KeyPress& other) throw()
  47838. : keyCode (other.keyCode),
  47839. mods (other.mods),
  47840. textCharacter (other.textCharacter)
  47841. {
  47842. }
  47843. KeyPress& KeyPress::operator= (const KeyPress& other) throw()
  47844. {
  47845. keyCode = other.keyCode;
  47846. mods = other.mods;
  47847. textCharacter = other.textCharacter;
  47848. return *this;
  47849. }
  47850. bool KeyPress::operator== (const KeyPress& other) const throw()
  47851. {
  47852. return mods.getRawFlags() == other.mods.getRawFlags()
  47853. && (textCharacter == other.textCharacter
  47854. || textCharacter == 0
  47855. || other.textCharacter == 0)
  47856. && (keyCode == other.keyCode
  47857. || (keyCode < 256
  47858. && other.keyCode < 256
  47859. && CharacterFunctions::toLowerCase ((juce_wchar) keyCode)
  47860. == CharacterFunctions::toLowerCase ((juce_wchar) other.keyCode)));
  47861. }
  47862. bool KeyPress::operator!= (const KeyPress& other) const throw()
  47863. {
  47864. return ! operator== (other);
  47865. }
  47866. bool KeyPress::isCurrentlyDown() const
  47867. {
  47868. return isKeyCurrentlyDown (keyCode)
  47869. && (ModifierKeys::getCurrentModifiers().getRawFlags() & ModifierKeys::allKeyboardModifiers)
  47870. == (mods.getRawFlags() & ModifierKeys::allKeyboardModifiers);
  47871. }
  47872. namespace KeyPressHelpers
  47873. {
  47874. struct KeyNameAndCode
  47875. {
  47876. const char* name;
  47877. int code;
  47878. };
  47879. static const KeyNameAndCode translations[] =
  47880. {
  47881. { "spacebar", KeyPress::spaceKey },
  47882. { "return", KeyPress::returnKey },
  47883. { "escape", KeyPress::escapeKey },
  47884. { "backspace", KeyPress::backspaceKey },
  47885. { "cursor left", KeyPress::leftKey },
  47886. { "cursor right", KeyPress::rightKey },
  47887. { "cursor up", KeyPress::upKey },
  47888. { "cursor down", KeyPress::downKey },
  47889. { "page up", KeyPress::pageUpKey },
  47890. { "page down", KeyPress::pageDownKey },
  47891. { "home", KeyPress::homeKey },
  47892. { "end", KeyPress::endKey },
  47893. { "delete", KeyPress::deleteKey },
  47894. { "insert", KeyPress::insertKey },
  47895. { "tab", KeyPress::tabKey },
  47896. { "play", KeyPress::playKey },
  47897. { "stop", KeyPress::stopKey },
  47898. { "fast forward", KeyPress::fastForwardKey },
  47899. { "rewind", KeyPress::rewindKey }
  47900. };
  47901. static const String numberPadPrefix() { return "numpad "; }
  47902. }
  47903. const KeyPress KeyPress::createFromDescription (const String& desc)
  47904. {
  47905. int modifiers = 0;
  47906. if (desc.containsWholeWordIgnoreCase ("ctrl")
  47907. || desc.containsWholeWordIgnoreCase ("control")
  47908. || desc.containsWholeWordIgnoreCase ("ctl"))
  47909. modifiers |= ModifierKeys::ctrlModifier;
  47910. if (desc.containsWholeWordIgnoreCase ("shift")
  47911. || desc.containsWholeWordIgnoreCase ("shft"))
  47912. modifiers |= ModifierKeys::shiftModifier;
  47913. if (desc.containsWholeWordIgnoreCase ("alt")
  47914. || desc.containsWholeWordIgnoreCase ("option"))
  47915. modifiers |= ModifierKeys::altModifier;
  47916. if (desc.containsWholeWordIgnoreCase ("command")
  47917. || desc.containsWholeWordIgnoreCase ("cmd"))
  47918. modifiers |= ModifierKeys::commandModifier;
  47919. int key = 0;
  47920. for (int i = 0; i < numElementsInArray (KeyPressHelpers::translations); ++i)
  47921. {
  47922. if (desc.containsWholeWordIgnoreCase (String (KeyPressHelpers::translations[i].name)))
  47923. {
  47924. key = KeyPressHelpers::translations[i].code;
  47925. break;
  47926. }
  47927. }
  47928. if (key == 0)
  47929. {
  47930. // see if it's a numpad key..
  47931. if (desc.containsIgnoreCase (KeyPressHelpers::numberPadPrefix()))
  47932. {
  47933. const juce_wchar lastChar = desc.trimEnd().getLastCharacter();
  47934. if (lastChar >= '0' && lastChar <= '9')
  47935. key = numberPad0 + lastChar - '0';
  47936. else if (lastChar == '+')
  47937. key = numberPadAdd;
  47938. else if (lastChar == '-')
  47939. key = numberPadSubtract;
  47940. else if (lastChar == '*')
  47941. key = numberPadMultiply;
  47942. else if (lastChar == '/')
  47943. key = numberPadDivide;
  47944. else if (lastChar == '.')
  47945. key = numberPadDecimalPoint;
  47946. else if (lastChar == '=')
  47947. key = numberPadEquals;
  47948. else if (desc.endsWith ("separator"))
  47949. key = numberPadSeparator;
  47950. else if (desc.endsWith ("delete"))
  47951. key = numberPadDelete;
  47952. }
  47953. if (key == 0)
  47954. {
  47955. // see if it's a function key..
  47956. for (int i = 1; i <= 12; ++i)
  47957. if (desc.containsWholeWordIgnoreCase ("f" + String (i)))
  47958. key = F1Key + i - 1;
  47959. if (key == 0)
  47960. {
  47961. // give up and use the hex code..
  47962. const int hexCode = desc.fromFirstOccurrenceOf ("#", false, false)
  47963. .toLowerCase()
  47964. .retainCharacters ("0123456789abcdef")
  47965. .getHexValue32();
  47966. if (hexCode > 0)
  47967. key = hexCode;
  47968. else
  47969. key = CharacterFunctions::toUpperCase (desc.getLastCharacter());
  47970. }
  47971. }
  47972. }
  47973. return KeyPress (key, ModifierKeys (modifiers), 0);
  47974. }
  47975. const String KeyPress::getTextDescription() const
  47976. {
  47977. String desc;
  47978. if (keyCode > 0)
  47979. {
  47980. // some keyboard layouts use a shift-key to get the slash, but in those cases, we
  47981. // want to store it as being a slash, not shift+whatever.
  47982. if (textCharacter == '/')
  47983. return "/";
  47984. if (mods.isCtrlDown())
  47985. desc << "ctrl + ";
  47986. if (mods.isShiftDown())
  47987. desc << "shift + ";
  47988. #if JUCE_MAC
  47989. // only do this on the mac, because on Windows ctrl and command are the same,
  47990. // and this would get confusing
  47991. if (mods.isCommandDown())
  47992. desc << "command + ";
  47993. if (mods.isAltDown())
  47994. desc << "option + ";
  47995. #else
  47996. if (mods.isAltDown())
  47997. desc << "alt + ";
  47998. #endif
  47999. for (int i = 0; i < numElementsInArray (KeyPressHelpers::translations); ++i)
  48000. if (keyCode == KeyPressHelpers::translations[i].code)
  48001. return desc + KeyPressHelpers::translations[i].name;
  48002. if (keyCode >= F1Key && keyCode <= F16Key)
  48003. desc << 'F' << (1 + keyCode - F1Key);
  48004. else if (keyCode >= numberPad0 && keyCode <= numberPad9)
  48005. desc << KeyPressHelpers::numberPadPrefix() << (keyCode - numberPad0);
  48006. else if (keyCode >= 33 && keyCode < 176)
  48007. desc += CharacterFunctions::toUpperCase ((juce_wchar) keyCode);
  48008. else if (keyCode == numberPadAdd)
  48009. desc << KeyPressHelpers::numberPadPrefix() << '+';
  48010. else if (keyCode == numberPadSubtract)
  48011. desc << KeyPressHelpers::numberPadPrefix() << '-';
  48012. else if (keyCode == numberPadMultiply)
  48013. desc << KeyPressHelpers::numberPadPrefix() << '*';
  48014. else if (keyCode == numberPadDivide)
  48015. desc << KeyPressHelpers::numberPadPrefix() << '/';
  48016. else if (keyCode == numberPadSeparator)
  48017. desc << KeyPressHelpers::numberPadPrefix() << "separator";
  48018. else if (keyCode == numberPadDecimalPoint)
  48019. desc << KeyPressHelpers::numberPadPrefix() << '.';
  48020. else if (keyCode == numberPadDelete)
  48021. desc << KeyPressHelpers::numberPadPrefix() << "delete";
  48022. else
  48023. desc << '#' << String::toHexString (keyCode);
  48024. }
  48025. return desc;
  48026. }
  48027. END_JUCE_NAMESPACE
  48028. /*** End of inlined file: juce_KeyPress.cpp ***/
  48029. /*** Start of inlined file: juce_KeyPressMappingSet.cpp ***/
  48030. BEGIN_JUCE_NAMESPACE
  48031. KeyPressMappingSet::KeyPressMappingSet (ApplicationCommandManager* const commandManager_)
  48032. : commandManager (commandManager_)
  48033. {
  48034. // A manager is needed to get the descriptions of commands, and will be called when
  48035. // a command is invoked. So you can't leave this null..
  48036. jassert (commandManager_ != 0);
  48037. Desktop::getInstance().addFocusChangeListener (this);
  48038. }
  48039. KeyPressMappingSet::KeyPressMappingSet (const KeyPressMappingSet& other)
  48040. : commandManager (other.commandManager)
  48041. {
  48042. Desktop::getInstance().addFocusChangeListener (this);
  48043. }
  48044. KeyPressMappingSet::~KeyPressMappingSet()
  48045. {
  48046. Desktop::getInstance().removeFocusChangeListener (this);
  48047. }
  48048. const Array <KeyPress> KeyPressMappingSet::getKeyPressesAssignedToCommand (const CommandID commandID) const
  48049. {
  48050. for (int i = 0; i < mappings.size(); ++i)
  48051. if (mappings.getUnchecked(i)->commandID == commandID)
  48052. return mappings.getUnchecked (i)->keypresses;
  48053. return Array <KeyPress> ();
  48054. }
  48055. void KeyPressMappingSet::addKeyPress (const CommandID commandID,
  48056. const KeyPress& newKeyPress,
  48057. int insertIndex)
  48058. {
  48059. // If you specify an upper-case letter but no shift key, how is the user supposed to press it!?
  48060. // Stick to lower-case letters when defining a keypress, to avoid ambiguity.
  48061. jassert (! (CharacterFunctions::isUpperCase (newKeyPress.getTextCharacter())
  48062. && ! newKeyPress.getModifiers().isShiftDown()));
  48063. if (findCommandForKeyPress (newKeyPress) != commandID)
  48064. {
  48065. removeKeyPress (newKeyPress);
  48066. if (newKeyPress.isValid())
  48067. {
  48068. for (int i = mappings.size(); --i >= 0;)
  48069. {
  48070. if (mappings.getUnchecked(i)->commandID == commandID)
  48071. {
  48072. mappings.getUnchecked(i)->keypresses.insert (insertIndex, newKeyPress);
  48073. sendChangeMessage (this);
  48074. return;
  48075. }
  48076. }
  48077. const ApplicationCommandInfo* const ci = commandManager->getCommandForID (commandID);
  48078. if (ci != 0)
  48079. {
  48080. CommandMapping* const cm = new CommandMapping();
  48081. cm->commandID = commandID;
  48082. cm->keypresses.add (newKeyPress);
  48083. cm->wantsKeyUpDownCallbacks = (ci->flags & ApplicationCommandInfo::wantsKeyUpDownCallbacks) != 0;
  48084. mappings.add (cm);
  48085. sendChangeMessage (this);
  48086. }
  48087. }
  48088. }
  48089. }
  48090. void KeyPressMappingSet::resetToDefaultMappings()
  48091. {
  48092. mappings.clear();
  48093. for (int i = 0; i < commandManager->getNumCommands(); ++i)
  48094. {
  48095. const ApplicationCommandInfo* const ci = commandManager->getCommandForIndex (i);
  48096. for (int j = 0; j < ci->defaultKeypresses.size(); ++j)
  48097. {
  48098. addKeyPress (ci->commandID,
  48099. ci->defaultKeypresses.getReference (j));
  48100. }
  48101. }
  48102. sendChangeMessage (this);
  48103. }
  48104. void KeyPressMappingSet::resetToDefaultMapping (const CommandID commandID)
  48105. {
  48106. clearAllKeyPresses (commandID);
  48107. const ApplicationCommandInfo* const ci = commandManager->getCommandForID (commandID);
  48108. for (int j = 0; j < ci->defaultKeypresses.size(); ++j)
  48109. {
  48110. addKeyPress (ci->commandID,
  48111. ci->defaultKeypresses.getReference (j));
  48112. }
  48113. }
  48114. void KeyPressMappingSet::clearAllKeyPresses()
  48115. {
  48116. if (mappings.size() > 0)
  48117. {
  48118. sendChangeMessage (this);
  48119. mappings.clear();
  48120. }
  48121. }
  48122. void KeyPressMappingSet::clearAllKeyPresses (const CommandID commandID)
  48123. {
  48124. for (int i = mappings.size(); --i >= 0;)
  48125. {
  48126. if (mappings.getUnchecked(i)->commandID == commandID)
  48127. {
  48128. mappings.remove (i);
  48129. sendChangeMessage (this);
  48130. }
  48131. }
  48132. }
  48133. void KeyPressMappingSet::removeKeyPress (const KeyPress& keypress)
  48134. {
  48135. if (keypress.isValid())
  48136. {
  48137. for (int i = mappings.size(); --i >= 0;)
  48138. {
  48139. CommandMapping* const cm = mappings.getUnchecked(i);
  48140. for (int j = cm->keypresses.size(); --j >= 0;)
  48141. {
  48142. if (keypress == cm->keypresses [j])
  48143. {
  48144. cm->keypresses.remove (j);
  48145. sendChangeMessage (this);
  48146. }
  48147. }
  48148. }
  48149. }
  48150. }
  48151. void KeyPressMappingSet::removeKeyPress (const CommandID commandID, const int keyPressIndex)
  48152. {
  48153. for (int i = mappings.size(); --i >= 0;)
  48154. {
  48155. if (mappings.getUnchecked(i)->commandID == commandID)
  48156. {
  48157. mappings.getUnchecked(i)->keypresses.remove (keyPressIndex);
  48158. sendChangeMessage (this);
  48159. break;
  48160. }
  48161. }
  48162. }
  48163. CommandID KeyPressMappingSet::findCommandForKeyPress (const KeyPress& keyPress) const throw()
  48164. {
  48165. for (int i = 0; i < mappings.size(); ++i)
  48166. if (mappings.getUnchecked(i)->keypresses.contains (keyPress))
  48167. return mappings.getUnchecked(i)->commandID;
  48168. return 0;
  48169. }
  48170. bool KeyPressMappingSet::containsMapping (const CommandID commandID, const KeyPress& keyPress) const throw()
  48171. {
  48172. for (int i = mappings.size(); --i >= 0;)
  48173. if (mappings.getUnchecked(i)->commandID == commandID)
  48174. return mappings.getUnchecked(i)->keypresses.contains (keyPress);
  48175. return false;
  48176. }
  48177. void KeyPressMappingSet::invokeCommand (const CommandID commandID,
  48178. const KeyPress& key,
  48179. const bool isKeyDown,
  48180. const int millisecsSinceKeyPressed,
  48181. Component* const originatingComponent) const
  48182. {
  48183. ApplicationCommandTarget::InvocationInfo info (commandID);
  48184. info.invocationMethod = ApplicationCommandTarget::InvocationInfo::fromKeyPress;
  48185. info.isKeyDown = isKeyDown;
  48186. info.keyPress = key;
  48187. info.millisecsSinceKeyPressed = millisecsSinceKeyPressed;
  48188. info.originatingComponent = originatingComponent;
  48189. commandManager->invoke (info, false);
  48190. }
  48191. bool KeyPressMappingSet::restoreFromXml (const XmlElement& xmlVersion)
  48192. {
  48193. if (xmlVersion.hasTagName ("KEYMAPPINGS"))
  48194. {
  48195. if (xmlVersion.getBoolAttribute ("basedOnDefaults", true))
  48196. {
  48197. // if the XML was created as a set of differences from the default mappings,
  48198. // (i.e. by calling createXml (true)), then we need to first restore the defaults.
  48199. resetToDefaultMappings();
  48200. }
  48201. else
  48202. {
  48203. // if the XML was created calling createXml (false), then we need to clear all
  48204. // the keys and treat the xml as describing the entire set of mappings.
  48205. clearAllKeyPresses();
  48206. }
  48207. forEachXmlChildElement (xmlVersion, map)
  48208. {
  48209. const CommandID commandId = map->getStringAttribute ("commandId").getHexValue32();
  48210. if (commandId != 0)
  48211. {
  48212. const KeyPress key (KeyPress::createFromDescription (map->getStringAttribute ("key")));
  48213. if (map->hasTagName ("MAPPING"))
  48214. {
  48215. addKeyPress (commandId, key);
  48216. }
  48217. else if (map->hasTagName ("UNMAPPING"))
  48218. {
  48219. if (containsMapping (commandId, key))
  48220. removeKeyPress (key);
  48221. }
  48222. }
  48223. }
  48224. return true;
  48225. }
  48226. return false;
  48227. }
  48228. XmlElement* KeyPressMappingSet::createXml (const bool saveDifferencesFromDefaultSet) const
  48229. {
  48230. ScopedPointer <KeyPressMappingSet> defaultSet;
  48231. if (saveDifferencesFromDefaultSet)
  48232. {
  48233. defaultSet = new KeyPressMappingSet (commandManager);
  48234. defaultSet->resetToDefaultMappings();
  48235. }
  48236. XmlElement* const doc = new XmlElement ("KEYMAPPINGS");
  48237. doc->setAttribute ("basedOnDefaults", saveDifferencesFromDefaultSet);
  48238. int i;
  48239. for (i = 0; i < mappings.size(); ++i)
  48240. {
  48241. const CommandMapping* const cm = mappings.getUnchecked(i);
  48242. for (int j = 0; j < cm->keypresses.size(); ++j)
  48243. {
  48244. if (defaultSet == 0
  48245. || ! defaultSet->containsMapping (cm->commandID, cm->keypresses.getReference (j)))
  48246. {
  48247. XmlElement* const map = doc->createNewChildElement ("MAPPING");
  48248. map->setAttribute ("commandId", String::toHexString ((int) cm->commandID));
  48249. map->setAttribute ("description", commandManager->getDescriptionOfCommand (cm->commandID));
  48250. map->setAttribute ("key", cm->keypresses.getReference (j).getTextDescription());
  48251. }
  48252. }
  48253. }
  48254. if (defaultSet != 0)
  48255. {
  48256. for (i = 0; i < defaultSet->mappings.size(); ++i)
  48257. {
  48258. const CommandMapping* const cm = defaultSet->mappings.getUnchecked(i);
  48259. for (int j = 0; j < cm->keypresses.size(); ++j)
  48260. {
  48261. if (! containsMapping (cm->commandID, cm->keypresses.getReference (j)))
  48262. {
  48263. XmlElement* const map = doc->createNewChildElement ("UNMAPPING");
  48264. map->setAttribute ("commandId", String::toHexString ((int) cm->commandID));
  48265. map->setAttribute ("description", commandManager->getDescriptionOfCommand (cm->commandID));
  48266. map->setAttribute ("key", cm->keypresses.getReference (j).getTextDescription());
  48267. }
  48268. }
  48269. }
  48270. }
  48271. return doc;
  48272. }
  48273. bool KeyPressMappingSet::keyPressed (const KeyPress& key,
  48274. Component* originatingComponent)
  48275. {
  48276. bool used = false;
  48277. const CommandID commandID = findCommandForKeyPress (key);
  48278. const ApplicationCommandInfo* const ci = commandManager->getCommandForID (commandID);
  48279. if (ci != 0
  48280. && (ci->flags & ApplicationCommandInfo::wantsKeyUpDownCallbacks) == 0)
  48281. {
  48282. ApplicationCommandInfo info (0);
  48283. if (commandManager->getTargetForCommand (commandID, info) != 0
  48284. && (info.flags & ApplicationCommandInfo::isDisabled) == 0)
  48285. {
  48286. invokeCommand (commandID, key, true, 0, originatingComponent);
  48287. used = true;
  48288. }
  48289. else
  48290. {
  48291. if (originatingComponent != 0)
  48292. originatingComponent->getLookAndFeel().playAlertSound();
  48293. }
  48294. }
  48295. return used;
  48296. }
  48297. bool KeyPressMappingSet::keyStateChanged (const bool /*isKeyDown*/, Component* originatingComponent)
  48298. {
  48299. bool used = false;
  48300. const uint32 now = Time::getMillisecondCounter();
  48301. for (int i = mappings.size(); --i >= 0;)
  48302. {
  48303. CommandMapping* const cm = mappings.getUnchecked(i);
  48304. if (cm->wantsKeyUpDownCallbacks)
  48305. {
  48306. for (int j = cm->keypresses.size(); --j >= 0;)
  48307. {
  48308. const KeyPress key (cm->keypresses.getReference (j));
  48309. const bool isDown = key.isCurrentlyDown();
  48310. int keyPressEntryIndex = 0;
  48311. bool wasDown = false;
  48312. for (int k = keysDown.size(); --k >= 0;)
  48313. {
  48314. if (key == keysDown.getUnchecked(k)->key)
  48315. {
  48316. keyPressEntryIndex = k;
  48317. wasDown = true;
  48318. used = true;
  48319. break;
  48320. }
  48321. }
  48322. if (isDown != wasDown)
  48323. {
  48324. int millisecs = 0;
  48325. if (isDown)
  48326. {
  48327. KeyPressTime* const k = new KeyPressTime();
  48328. k->key = key;
  48329. k->timeWhenPressed = now;
  48330. keysDown.add (k);
  48331. }
  48332. else
  48333. {
  48334. const uint32 pressTime = keysDown.getUnchecked (keyPressEntryIndex)->timeWhenPressed;
  48335. if (now > pressTime)
  48336. millisecs = now - pressTime;
  48337. keysDown.remove (keyPressEntryIndex);
  48338. }
  48339. invokeCommand (cm->commandID, key, isDown, millisecs, originatingComponent);
  48340. used = true;
  48341. }
  48342. }
  48343. }
  48344. }
  48345. return used;
  48346. }
  48347. void KeyPressMappingSet::globalFocusChanged (Component* focusedComponent)
  48348. {
  48349. if (focusedComponent != 0)
  48350. focusedComponent->keyStateChanged (false);
  48351. }
  48352. END_JUCE_NAMESPACE
  48353. /*** End of inlined file: juce_KeyPressMappingSet.cpp ***/
  48354. /*** Start of inlined file: juce_ModifierKeys.cpp ***/
  48355. BEGIN_JUCE_NAMESPACE
  48356. ModifierKeys::ModifierKeys (const int flags_) throw()
  48357. : flags (flags_)
  48358. {
  48359. }
  48360. ModifierKeys::ModifierKeys (const ModifierKeys& other) throw()
  48361. : flags (other.flags)
  48362. {
  48363. }
  48364. ModifierKeys& ModifierKeys::operator= (const ModifierKeys& other) throw()
  48365. {
  48366. flags = other.flags;
  48367. return *this;
  48368. }
  48369. ModifierKeys ModifierKeys::currentModifiers;
  48370. const ModifierKeys ModifierKeys::getCurrentModifiers() throw()
  48371. {
  48372. return currentModifiers;
  48373. }
  48374. int ModifierKeys::getNumMouseButtonsDown() const throw()
  48375. {
  48376. int num = 0;
  48377. if (isLeftButtonDown()) ++num;
  48378. if (isRightButtonDown()) ++num;
  48379. if (isMiddleButtonDown()) ++num;
  48380. return num;
  48381. }
  48382. END_JUCE_NAMESPACE
  48383. /*** End of inlined file: juce_ModifierKeys.cpp ***/
  48384. /*** Start of inlined file: juce_ComponentAnimator.cpp ***/
  48385. BEGIN_JUCE_NAMESPACE
  48386. class ComponentAnimator::AnimationTask
  48387. {
  48388. public:
  48389. AnimationTask (Component* const comp)
  48390. : component (comp)
  48391. {
  48392. }
  48393. Component::SafePointer<Component> component;
  48394. Rectangle<int> destination;
  48395. int msElapsed, msTotal;
  48396. double startSpeed, midSpeed, endSpeed, lastProgress;
  48397. double left, top, right, bottom;
  48398. bool useTimeslice (const int elapsed)
  48399. {
  48400. if (component == 0)
  48401. return false;
  48402. msElapsed += elapsed;
  48403. double newProgress = msElapsed / (double) msTotal;
  48404. if (newProgress >= 0 && newProgress < 1.0)
  48405. {
  48406. newProgress = timeToDistance (newProgress);
  48407. const double delta = (newProgress - lastProgress) / (1.0 - lastProgress);
  48408. jassert (newProgress >= lastProgress);
  48409. lastProgress = newProgress;
  48410. left += (destination.getX() - left) * delta;
  48411. top += (destination.getY() - top) * delta;
  48412. right += (destination.getRight() - right) * delta;
  48413. bottom += (destination.getBottom() - bottom) * delta;
  48414. if (delta < 1.0)
  48415. {
  48416. const Rectangle<int> newBounds (roundToInt (left),
  48417. roundToInt (top),
  48418. roundToInt (right - left),
  48419. roundToInt (bottom - top));
  48420. if (newBounds != destination)
  48421. {
  48422. component->setBounds (newBounds);
  48423. return true;
  48424. }
  48425. }
  48426. }
  48427. component->setBounds (destination);
  48428. return false;
  48429. }
  48430. void moveToFinalDestination()
  48431. {
  48432. if (component != 0)
  48433. component->setBounds (destination);
  48434. }
  48435. private:
  48436. inline double timeToDistance (const double time) const
  48437. {
  48438. return (time < 0.5) ? time * (startSpeed + time * (midSpeed - startSpeed))
  48439. : 0.5 * (startSpeed + 0.5 * (midSpeed - startSpeed))
  48440. + (time - 0.5) * (midSpeed + (time - 0.5) * (endSpeed - midSpeed));
  48441. }
  48442. };
  48443. ComponentAnimator::ComponentAnimator()
  48444. : lastTime (0)
  48445. {
  48446. }
  48447. ComponentAnimator::~ComponentAnimator()
  48448. {
  48449. cancelAllAnimations (false);
  48450. jassert (tasks.size() == 0);
  48451. }
  48452. ComponentAnimator::AnimationTask* ComponentAnimator::findTaskFor (Component* const component) const
  48453. {
  48454. for (int i = tasks.size(); --i >= 0;)
  48455. if (component == tasks.getUnchecked(i)->component.getComponent())
  48456. return tasks.getUnchecked(i);
  48457. return 0;
  48458. }
  48459. void ComponentAnimator::animateComponent (Component* const component,
  48460. const Rectangle<int>& finalPosition,
  48461. const int millisecondsToSpendMoving,
  48462. const double startSpeed,
  48463. const double endSpeed)
  48464. {
  48465. if (component != 0)
  48466. {
  48467. AnimationTask* at = findTaskFor (component);
  48468. if (at == 0)
  48469. {
  48470. at = new AnimationTask (component);
  48471. tasks.add (at);
  48472. sendChangeMessage (this);
  48473. }
  48474. at->msElapsed = 0;
  48475. at->lastProgress = 0;
  48476. at->msTotal = jmax (1, millisecondsToSpendMoving);
  48477. at->destination = finalPosition;
  48478. // the speeds must be 0 or greater!
  48479. jassert (startSpeed >= 0 && endSpeed >= 0)
  48480. const double invTotalDistance = 4.0 / (startSpeed + endSpeed + 2.0);
  48481. at->startSpeed = jmax (0.0, startSpeed * invTotalDistance);
  48482. at->midSpeed = invTotalDistance;
  48483. at->endSpeed = jmax (0.0, endSpeed * invTotalDistance);
  48484. at->left = component->getX();
  48485. at->top = component->getY();
  48486. at->right = component->getRight();
  48487. at->bottom = component->getBottom();
  48488. if (! isTimerRunning())
  48489. {
  48490. lastTime = Time::getMillisecondCounter();
  48491. startTimer (1000 / 50);
  48492. }
  48493. }
  48494. }
  48495. void ComponentAnimator::cancelAllAnimations (const bool moveComponentsToTheirFinalPositions)
  48496. {
  48497. for (int i = tasks.size(); --i >= 0;)
  48498. {
  48499. AnimationTask* const at = tasks.getUnchecked(i);
  48500. if (moveComponentsToTheirFinalPositions)
  48501. at->moveToFinalDestination();
  48502. delete at;
  48503. tasks.remove (i);
  48504. sendChangeMessage (this);
  48505. }
  48506. }
  48507. void ComponentAnimator::cancelAnimation (Component* const component,
  48508. const bool moveComponentToItsFinalPosition)
  48509. {
  48510. AnimationTask* const at = findTaskFor (component);
  48511. if (at != 0)
  48512. {
  48513. if (moveComponentToItsFinalPosition)
  48514. at->moveToFinalDestination();
  48515. tasks.removeValue (at);
  48516. delete at;
  48517. sendChangeMessage (this);
  48518. }
  48519. }
  48520. const Rectangle<int> ComponentAnimator::getComponentDestination (Component* const component)
  48521. {
  48522. AnimationTask* const at = findTaskFor (component);
  48523. if (at != 0)
  48524. return at->destination;
  48525. else if (component != 0)
  48526. return component->getBounds();
  48527. return Rectangle<int>();
  48528. }
  48529. bool ComponentAnimator::isAnimating (Component* component) const
  48530. {
  48531. return findTaskFor (component) != 0;
  48532. }
  48533. void ComponentAnimator::timerCallback()
  48534. {
  48535. const uint32 timeNow = Time::getMillisecondCounter();
  48536. if (lastTime == 0 || lastTime == timeNow)
  48537. lastTime = timeNow;
  48538. const int elapsed = timeNow - lastTime;
  48539. for (int i = tasks.size(); --i >= 0;)
  48540. {
  48541. AnimationTask* const at = tasks.getUnchecked(i);
  48542. if (! at->useTimeslice (elapsed))
  48543. {
  48544. tasks.remove (i);
  48545. delete at;
  48546. sendChangeMessage (this);
  48547. }
  48548. }
  48549. lastTime = timeNow;
  48550. if (tasks.size() == 0)
  48551. stopTimer();
  48552. }
  48553. END_JUCE_NAMESPACE
  48554. /*** End of inlined file: juce_ComponentAnimator.cpp ***/
  48555. /*** Start of inlined file: juce_ComponentBoundsConstrainer.cpp ***/
  48556. BEGIN_JUCE_NAMESPACE
  48557. ComponentBoundsConstrainer::ComponentBoundsConstrainer() throw()
  48558. : minW (0),
  48559. maxW (0x3fffffff),
  48560. minH (0),
  48561. maxH (0x3fffffff),
  48562. minOffTop (0),
  48563. minOffLeft (0),
  48564. minOffBottom (0),
  48565. minOffRight (0),
  48566. aspectRatio (0.0)
  48567. {
  48568. }
  48569. ComponentBoundsConstrainer::~ComponentBoundsConstrainer()
  48570. {
  48571. }
  48572. void ComponentBoundsConstrainer::setMinimumWidth (const int minimumWidth) throw()
  48573. {
  48574. minW = minimumWidth;
  48575. }
  48576. void ComponentBoundsConstrainer::setMaximumWidth (const int maximumWidth) throw()
  48577. {
  48578. maxW = maximumWidth;
  48579. }
  48580. void ComponentBoundsConstrainer::setMinimumHeight (const int minimumHeight) throw()
  48581. {
  48582. minH = minimumHeight;
  48583. }
  48584. void ComponentBoundsConstrainer::setMaximumHeight (const int maximumHeight) throw()
  48585. {
  48586. maxH = maximumHeight;
  48587. }
  48588. void ComponentBoundsConstrainer::setMinimumSize (const int minimumWidth, const int minimumHeight) throw()
  48589. {
  48590. jassert (maxW >= minimumWidth);
  48591. jassert (maxH >= minimumHeight);
  48592. jassert (minimumWidth > 0 && minimumHeight > 0);
  48593. minW = minimumWidth;
  48594. minH = minimumHeight;
  48595. if (minW > maxW)
  48596. maxW = minW;
  48597. if (minH > maxH)
  48598. maxH = minH;
  48599. }
  48600. void ComponentBoundsConstrainer::setMaximumSize (const int maximumWidth, const int maximumHeight) throw()
  48601. {
  48602. jassert (maximumWidth >= minW);
  48603. jassert (maximumHeight >= minH);
  48604. jassert (maximumWidth > 0 && maximumHeight > 0);
  48605. maxW = jmax (minW, maximumWidth);
  48606. maxH = jmax (minH, maximumHeight);
  48607. }
  48608. void ComponentBoundsConstrainer::setSizeLimits (const int minimumWidth,
  48609. const int minimumHeight,
  48610. const int maximumWidth,
  48611. const int maximumHeight) throw()
  48612. {
  48613. jassert (maximumWidth >= minimumWidth);
  48614. jassert (maximumHeight >= minimumHeight);
  48615. jassert (maximumWidth > 0 && maximumHeight > 0);
  48616. jassert (minimumWidth > 0 && minimumHeight > 0);
  48617. minW = jmax (0, minimumWidth);
  48618. minH = jmax (0, minimumHeight);
  48619. maxW = jmax (minW, maximumWidth);
  48620. maxH = jmax (minH, maximumHeight);
  48621. }
  48622. void ComponentBoundsConstrainer::setMinimumOnscreenAmounts (const int minimumWhenOffTheTop,
  48623. const int minimumWhenOffTheLeft,
  48624. const int minimumWhenOffTheBottom,
  48625. const int minimumWhenOffTheRight) throw()
  48626. {
  48627. minOffTop = minimumWhenOffTheTop;
  48628. minOffLeft = minimumWhenOffTheLeft;
  48629. minOffBottom = minimumWhenOffTheBottom;
  48630. minOffRight = minimumWhenOffTheRight;
  48631. }
  48632. void ComponentBoundsConstrainer::setFixedAspectRatio (const double widthOverHeight) throw()
  48633. {
  48634. aspectRatio = jmax (0.0, widthOverHeight);
  48635. }
  48636. double ComponentBoundsConstrainer::getFixedAspectRatio() const throw()
  48637. {
  48638. return aspectRatio;
  48639. }
  48640. void ComponentBoundsConstrainer::setBoundsForComponent (Component* const component,
  48641. const Rectangle<int>& targetBounds,
  48642. const bool isStretchingTop,
  48643. const bool isStretchingLeft,
  48644. const bool isStretchingBottom,
  48645. const bool isStretchingRight)
  48646. {
  48647. jassert (component != 0);
  48648. Rectangle<int> limits, bounds (targetBounds);
  48649. BorderSize border;
  48650. Component* const parent = component->getParentComponent();
  48651. if (parent == 0)
  48652. {
  48653. ComponentPeer* peer = component->getPeer();
  48654. if (peer != 0)
  48655. border = peer->getFrameSize();
  48656. limits = Desktop::getInstance().getMonitorAreaContaining (bounds.getCentre());
  48657. }
  48658. else
  48659. {
  48660. limits.setSize (parent->getWidth(), parent->getHeight());
  48661. }
  48662. border.addTo (bounds);
  48663. checkBounds (bounds,
  48664. border.addedTo (component->getBounds()), limits,
  48665. isStretchingTop, isStretchingLeft,
  48666. isStretchingBottom, isStretchingRight);
  48667. border.subtractFrom (bounds);
  48668. applyBoundsToComponent (component, bounds);
  48669. }
  48670. void ComponentBoundsConstrainer::checkComponentBounds (Component* component)
  48671. {
  48672. setBoundsForComponent (component, component->getBounds(),
  48673. false, false, false, false);
  48674. }
  48675. void ComponentBoundsConstrainer::applyBoundsToComponent (Component* component,
  48676. const Rectangle<int>& bounds)
  48677. {
  48678. component->setBounds (bounds);
  48679. }
  48680. void ComponentBoundsConstrainer::resizeStart()
  48681. {
  48682. }
  48683. void ComponentBoundsConstrainer::resizeEnd()
  48684. {
  48685. }
  48686. void ComponentBoundsConstrainer::checkBounds (Rectangle<int>& bounds,
  48687. const Rectangle<int>& old,
  48688. const Rectangle<int>& limits,
  48689. const bool isStretchingTop,
  48690. const bool isStretchingLeft,
  48691. const bool isStretchingBottom,
  48692. const bool isStretchingRight)
  48693. {
  48694. int x = bounds.getX();
  48695. int y = bounds.getY();
  48696. int w = bounds.getWidth();
  48697. int h = bounds.getHeight();
  48698. // constrain the size if it's being stretched..
  48699. if (isStretchingLeft)
  48700. {
  48701. x = jlimit (old.getRight() - maxW, old.getRight() - minW, x);
  48702. w = old.getRight() - x;
  48703. }
  48704. if (isStretchingRight)
  48705. {
  48706. w = jlimit (minW, maxW, w);
  48707. }
  48708. if (isStretchingTop)
  48709. {
  48710. y = jlimit (old.getBottom() - maxH, old.getBottom() - minH, y);
  48711. h = old.getBottom() - y;
  48712. }
  48713. if (isStretchingBottom)
  48714. {
  48715. h = jlimit (minH, maxH, h);
  48716. }
  48717. // constrain the aspect ratio if one has been specified..
  48718. if (aspectRatio > 0.0 && w > 0 && h > 0)
  48719. {
  48720. bool adjustWidth;
  48721. if ((isStretchingTop || isStretchingBottom) && ! (isStretchingLeft || isStretchingRight))
  48722. {
  48723. adjustWidth = true;
  48724. }
  48725. else if ((isStretchingLeft || isStretchingRight) && ! (isStretchingTop || isStretchingBottom))
  48726. {
  48727. adjustWidth = false;
  48728. }
  48729. else
  48730. {
  48731. const double oldRatio = (old.getHeight() > 0) ? std::abs (old.getWidth() / (double) old.getHeight()) : 0.0;
  48732. const double newRatio = std::abs (w / (double) h);
  48733. adjustWidth = (oldRatio > newRatio);
  48734. }
  48735. if (adjustWidth)
  48736. {
  48737. w = roundToInt (h * aspectRatio);
  48738. if (w > maxW || w < minW)
  48739. {
  48740. w = jlimit (minW, maxW, w);
  48741. h = roundToInt (w / aspectRatio);
  48742. }
  48743. }
  48744. else
  48745. {
  48746. h = roundToInt (w / aspectRatio);
  48747. if (h > maxH || h < minH)
  48748. {
  48749. h = jlimit (minH, maxH, h);
  48750. w = roundToInt (h * aspectRatio);
  48751. }
  48752. }
  48753. if ((isStretchingTop || isStretchingBottom) && ! (isStretchingLeft || isStretchingRight))
  48754. {
  48755. x = old.getX() + (old.getWidth() - w) / 2;
  48756. }
  48757. else if ((isStretchingLeft || isStretchingRight) && ! (isStretchingTop || isStretchingBottom))
  48758. {
  48759. y = old.getY() + (old.getHeight() - h) / 2;
  48760. }
  48761. else
  48762. {
  48763. if (isStretchingLeft)
  48764. x = old.getRight() - w;
  48765. if (isStretchingTop)
  48766. y = old.getBottom() - h;
  48767. }
  48768. }
  48769. // ...and constrain the position if limits have been set for that.
  48770. if (minOffTop > 0 || minOffLeft > 0 || minOffBottom > 0 || minOffRight > 0)
  48771. {
  48772. if (minOffTop > 0)
  48773. {
  48774. const int limit = limits.getY() + jmin (minOffTop - h, 0);
  48775. if (y < limit)
  48776. {
  48777. if (isStretchingTop)
  48778. h -= (limit - y);
  48779. y = limit;
  48780. }
  48781. }
  48782. if (minOffLeft > 0)
  48783. {
  48784. const int limit = limits.getX() + jmin (minOffLeft - w, 0);
  48785. if (x < limit)
  48786. {
  48787. if (isStretchingLeft)
  48788. w -= (limit - x);
  48789. x = limit;
  48790. }
  48791. }
  48792. if (minOffBottom > 0)
  48793. {
  48794. const int limit = limits.getBottom() - jmin (minOffBottom, h);
  48795. if (y > limit)
  48796. {
  48797. if (isStretchingBottom)
  48798. h += (limit - y);
  48799. else
  48800. y = limit;
  48801. }
  48802. }
  48803. if (minOffRight > 0)
  48804. {
  48805. const int limit = limits.getRight() - jmin (minOffRight, w);
  48806. if (x > limit)
  48807. {
  48808. if (isStretchingRight)
  48809. w += (limit - x);
  48810. else
  48811. x = limit;
  48812. }
  48813. }
  48814. }
  48815. jassert (w >= 0 && h >= 0);
  48816. bounds = Rectangle<int> (x, y, w, h);
  48817. }
  48818. END_JUCE_NAMESPACE
  48819. /*** End of inlined file: juce_ComponentBoundsConstrainer.cpp ***/
  48820. /*** Start of inlined file: juce_ComponentMovementWatcher.cpp ***/
  48821. BEGIN_JUCE_NAMESPACE
  48822. ComponentMovementWatcher::ComponentMovementWatcher (Component* const component_)
  48823. : component (component_),
  48824. lastPeer (0),
  48825. reentrant (false)
  48826. {
  48827. jassert (component != 0); // can't use this with a null pointer..
  48828. component->addComponentListener (this);
  48829. registerWithParentComps();
  48830. }
  48831. ComponentMovementWatcher::~ComponentMovementWatcher()
  48832. {
  48833. component->removeComponentListener (this);
  48834. unregister();
  48835. }
  48836. void ComponentMovementWatcher::componentParentHierarchyChanged (Component&)
  48837. {
  48838. // agh! don't delete the target component without deleting this object first!
  48839. jassert (component != 0);
  48840. if (! reentrant)
  48841. {
  48842. reentrant = true;
  48843. ComponentPeer* const peer = component->getPeer();
  48844. if (peer != lastPeer)
  48845. {
  48846. componentPeerChanged();
  48847. if (component == 0)
  48848. return;
  48849. lastPeer = peer;
  48850. }
  48851. unregister();
  48852. registerWithParentComps();
  48853. reentrant = false;
  48854. componentMovedOrResized (*component, true, true);
  48855. }
  48856. }
  48857. void ComponentMovementWatcher::componentMovedOrResized (Component&, bool wasMoved, bool wasResized)
  48858. {
  48859. // agh! don't delete the target component without deleting this object first!
  48860. jassert (component != 0);
  48861. if (wasMoved)
  48862. {
  48863. const Point<int> pos (component->relativePositionToOtherComponent (component->getTopLevelComponent(), Point<int>()));
  48864. wasMoved = lastBounds.getPosition() != pos;
  48865. lastBounds.setPosition (pos);
  48866. }
  48867. wasResized = (lastBounds.getWidth() != component->getWidth() || lastBounds.getHeight() != component->getHeight());
  48868. lastBounds.setSize (component->getWidth(), component->getHeight());
  48869. if (wasMoved || wasResized)
  48870. componentMovedOrResized (wasMoved, wasResized);
  48871. }
  48872. void ComponentMovementWatcher::registerWithParentComps() throw()
  48873. {
  48874. Component* p = component->getParentComponent();
  48875. while (p != 0)
  48876. {
  48877. p->addComponentListener (this);
  48878. registeredParentComps.add (p);
  48879. p = p->getParentComponent();
  48880. }
  48881. }
  48882. void ComponentMovementWatcher::unregister() throw()
  48883. {
  48884. for (int i = registeredParentComps.size(); --i >= 0;)
  48885. static_cast <Component*> (registeredParentComps.getUnchecked(i))->removeComponentListener (this);
  48886. registeredParentComps.clear();
  48887. }
  48888. END_JUCE_NAMESPACE
  48889. /*** End of inlined file: juce_ComponentMovementWatcher.cpp ***/
  48890. /*** Start of inlined file: juce_GroupComponent.cpp ***/
  48891. BEGIN_JUCE_NAMESPACE
  48892. GroupComponent::GroupComponent (const String& componentName,
  48893. const String& labelText)
  48894. : Component (componentName),
  48895. text (labelText),
  48896. justification (Justification::left)
  48897. {
  48898. setInterceptsMouseClicks (false, true);
  48899. }
  48900. GroupComponent::~GroupComponent()
  48901. {
  48902. }
  48903. void GroupComponent::setText (const String& newText)
  48904. {
  48905. if (text != newText)
  48906. {
  48907. text = newText;
  48908. repaint();
  48909. }
  48910. }
  48911. const String GroupComponent::getText() const
  48912. {
  48913. return text;
  48914. }
  48915. void GroupComponent::setTextLabelPosition (const Justification& newJustification)
  48916. {
  48917. if (justification.getFlags() != newJustification.getFlags())
  48918. {
  48919. justification = newJustification;
  48920. repaint();
  48921. }
  48922. }
  48923. void GroupComponent::paint (Graphics& g)
  48924. {
  48925. getLookAndFeel()
  48926. .drawGroupComponentOutline (g, getWidth(), getHeight(),
  48927. text, justification,
  48928. *this);
  48929. }
  48930. void GroupComponent::enablementChanged()
  48931. {
  48932. repaint();
  48933. }
  48934. void GroupComponent::colourChanged()
  48935. {
  48936. repaint();
  48937. }
  48938. END_JUCE_NAMESPACE
  48939. /*** End of inlined file: juce_GroupComponent.cpp ***/
  48940. /*** Start of inlined file: juce_MultiDocumentPanel.cpp ***/
  48941. BEGIN_JUCE_NAMESPACE
  48942. MultiDocumentPanelWindow::MultiDocumentPanelWindow (const Colour& backgroundColour)
  48943. : DocumentWindow (String::empty, backgroundColour,
  48944. DocumentWindow::maximiseButton | DocumentWindow::closeButton, false)
  48945. {
  48946. }
  48947. MultiDocumentPanelWindow::~MultiDocumentPanelWindow()
  48948. {
  48949. }
  48950. void MultiDocumentPanelWindow::maximiseButtonPressed()
  48951. {
  48952. MultiDocumentPanel* const owner = getOwner();
  48953. jassert (owner != 0); // these windows are only designed to be used inside a MultiDocumentPanel!
  48954. if (owner != 0)
  48955. owner->setLayoutMode (MultiDocumentPanel::MaximisedWindowsWithTabs);
  48956. }
  48957. void MultiDocumentPanelWindow::closeButtonPressed()
  48958. {
  48959. MultiDocumentPanel* const owner = getOwner();
  48960. jassert (owner != 0); // these windows are only designed to be used inside a MultiDocumentPanel!
  48961. if (owner != 0)
  48962. owner->closeDocument (getContentComponent(), true);
  48963. }
  48964. void MultiDocumentPanelWindow::activeWindowStatusChanged()
  48965. {
  48966. DocumentWindow::activeWindowStatusChanged();
  48967. updateOrder();
  48968. }
  48969. void MultiDocumentPanelWindow::broughtToFront()
  48970. {
  48971. DocumentWindow::broughtToFront();
  48972. updateOrder();
  48973. }
  48974. void MultiDocumentPanelWindow::updateOrder()
  48975. {
  48976. MultiDocumentPanel* const owner = getOwner();
  48977. if (owner != 0)
  48978. owner->updateOrder();
  48979. }
  48980. MultiDocumentPanel* MultiDocumentPanelWindow::getOwner() const throw()
  48981. {
  48982. // (unable to use the syntax findParentComponentOfClass <MultiDocumentPanel> () because of a VC6 compiler bug)
  48983. return findParentComponentOfClass ((MultiDocumentPanel*) 0);
  48984. }
  48985. class MDITabbedComponentInternal : public TabbedComponent
  48986. {
  48987. public:
  48988. MDITabbedComponentInternal()
  48989. : TabbedComponent (TabbedButtonBar::TabsAtTop)
  48990. {
  48991. }
  48992. ~MDITabbedComponentInternal()
  48993. {
  48994. }
  48995. void currentTabChanged (int, const String&)
  48996. {
  48997. // (unable to use the syntax findParentComponentOfClass <MultiDocumentPanel> () because of a VC6 compiler bug)
  48998. MultiDocumentPanel* const owner = findParentComponentOfClass ((MultiDocumentPanel*) 0);
  48999. if (owner != 0)
  49000. owner->updateOrder();
  49001. }
  49002. };
  49003. MultiDocumentPanel::MultiDocumentPanel()
  49004. : mode (MaximisedWindowsWithTabs),
  49005. tabComponent (0),
  49006. backgroundColour (Colours::lightblue),
  49007. maximumNumDocuments (0),
  49008. numDocsBeforeTabsUsed (0)
  49009. {
  49010. setOpaque (true);
  49011. }
  49012. MultiDocumentPanel::~MultiDocumentPanel()
  49013. {
  49014. closeAllDocuments (false);
  49015. }
  49016. static bool shouldDeleteComp (Component* const c)
  49017. {
  49018. return c->getProperties() ["mdiDocumentDelete_"];
  49019. }
  49020. bool MultiDocumentPanel::closeAllDocuments (const bool checkItsOkToCloseFirst)
  49021. {
  49022. while (components.size() > 0)
  49023. if (! closeDocument (components.getLast(), checkItsOkToCloseFirst))
  49024. return false;
  49025. return true;
  49026. }
  49027. MultiDocumentPanelWindow* MultiDocumentPanel::createNewDocumentWindow()
  49028. {
  49029. return new MultiDocumentPanelWindow (backgroundColour);
  49030. }
  49031. void MultiDocumentPanel::addWindow (Component* component)
  49032. {
  49033. MultiDocumentPanelWindow* const dw = createNewDocumentWindow();
  49034. dw->setResizable (true, false);
  49035. dw->setContentComponent (component, false, true);
  49036. dw->setName (component->getName());
  49037. const var bkg (component->getProperties() ["mdiDocumentBkg_"]);
  49038. dw->setBackgroundColour (bkg.isVoid() ? backgroundColour : Colour ((int) bkg));
  49039. int x = 4;
  49040. Component* const topComp = getChildComponent (getNumChildComponents() - 1);
  49041. if (topComp != 0 && topComp->getX() == x && topComp->getY() == x)
  49042. x += 16;
  49043. dw->setTopLeftPosition (x, x);
  49044. const var pos (component->getProperties() ["mdiDocumentPos_"]);
  49045. if (pos.toString().isNotEmpty())
  49046. dw->restoreWindowStateFromString (pos.toString());
  49047. addAndMakeVisible (dw);
  49048. dw->toFront (true);
  49049. }
  49050. bool MultiDocumentPanel::addDocument (Component* const component,
  49051. const Colour& docColour,
  49052. const bool deleteWhenRemoved)
  49053. {
  49054. // If you try passing a full DocumentWindow or ResizableWindow in here, you'll end up
  49055. // with a frame-within-a-frame! Just pass in the bare content component.
  49056. jassert (dynamic_cast <ResizableWindow*> (component) == 0);
  49057. if (component == 0 || (maximumNumDocuments > 0 && components.size() >= maximumNumDocuments))
  49058. return false;
  49059. components.add (component);
  49060. component->getProperties().set ("mdiDocumentDelete_", deleteWhenRemoved);
  49061. component->getProperties().set ("mdiDocumentBkg_", (int) docColour.getARGB());
  49062. component->addComponentListener (this);
  49063. if (mode == FloatingWindows)
  49064. {
  49065. if (isFullscreenWhenOneDocument())
  49066. {
  49067. if (components.size() == 1)
  49068. {
  49069. addAndMakeVisible (component);
  49070. }
  49071. else
  49072. {
  49073. if (components.size() == 2)
  49074. addWindow (components.getFirst());
  49075. addWindow (component);
  49076. }
  49077. }
  49078. else
  49079. {
  49080. addWindow (component);
  49081. }
  49082. }
  49083. else
  49084. {
  49085. if (tabComponent == 0 && components.size() > numDocsBeforeTabsUsed)
  49086. {
  49087. addAndMakeVisible (tabComponent = new MDITabbedComponentInternal());
  49088. Array <Component*> temp (components);
  49089. for (int i = 0; i < temp.size(); ++i)
  49090. tabComponent->addTab (temp[i]->getName(), docColour, temp[i], false);
  49091. resized();
  49092. }
  49093. else
  49094. {
  49095. if (tabComponent != 0)
  49096. tabComponent->addTab (component->getName(), docColour, component, false);
  49097. else
  49098. addAndMakeVisible (component);
  49099. }
  49100. setActiveDocument (component);
  49101. }
  49102. resized();
  49103. activeDocumentChanged();
  49104. return true;
  49105. }
  49106. bool MultiDocumentPanel::closeDocument (Component* component,
  49107. const bool checkItsOkToCloseFirst)
  49108. {
  49109. if (components.contains (component))
  49110. {
  49111. if (checkItsOkToCloseFirst && ! tryToCloseDocument (component))
  49112. return false;
  49113. component->removeComponentListener (this);
  49114. const bool shouldDelete = shouldDeleteComp (component);
  49115. component->getProperties().remove ("mdiDocumentDelete_");
  49116. component->getProperties().remove ("mdiDocumentBkg_");
  49117. if (mode == FloatingWindows)
  49118. {
  49119. for (int i = getNumChildComponents(); --i >= 0;)
  49120. {
  49121. MultiDocumentPanelWindow* const dw = dynamic_cast <MultiDocumentPanelWindow*> (getChildComponent (i));
  49122. if (dw != 0 && dw->getContentComponent() == component)
  49123. {
  49124. dw->setContentComponent (0, false);
  49125. delete dw;
  49126. break;
  49127. }
  49128. }
  49129. if (shouldDelete)
  49130. delete component;
  49131. components.removeValue (component);
  49132. if (isFullscreenWhenOneDocument() && components.size() == 1)
  49133. {
  49134. for (int i = getNumChildComponents(); --i >= 0;)
  49135. {
  49136. MultiDocumentPanelWindow* const dw = dynamic_cast <MultiDocumentPanelWindow*> (getChildComponent (i));
  49137. if (dw != 0)
  49138. {
  49139. dw->setContentComponent (0, false);
  49140. delete dw;
  49141. }
  49142. }
  49143. addAndMakeVisible (components.getFirst());
  49144. }
  49145. }
  49146. else
  49147. {
  49148. jassert (components.indexOf (component) >= 0);
  49149. if (tabComponent != 0)
  49150. {
  49151. for (int i = tabComponent->getNumTabs(); --i >= 0;)
  49152. if (tabComponent->getTabContentComponent (i) == component)
  49153. tabComponent->removeTab (i);
  49154. }
  49155. else
  49156. {
  49157. removeChildComponent (component);
  49158. }
  49159. if (shouldDelete)
  49160. delete component;
  49161. if (tabComponent != 0 && tabComponent->getNumTabs() <= numDocsBeforeTabsUsed)
  49162. deleteAndZero (tabComponent);
  49163. components.removeValue (component);
  49164. if (components.size() > 0 && tabComponent == 0)
  49165. addAndMakeVisible (components.getFirst());
  49166. }
  49167. resized();
  49168. activeDocumentChanged();
  49169. }
  49170. else
  49171. {
  49172. jassertfalse
  49173. }
  49174. return true;
  49175. }
  49176. int MultiDocumentPanel::getNumDocuments() const throw()
  49177. {
  49178. return components.size();
  49179. }
  49180. Component* MultiDocumentPanel::getDocument (const int index) const throw()
  49181. {
  49182. return components [index];
  49183. }
  49184. Component* MultiDocumentPanel::getActiveDocument() const throw()
  49185. {
  49186. if (mode == FloatingWindows)
  49187. {
  49188. for (int i = getNumChildComponents(); --i >= 0;)
  49189. {
  49190. MultiDocumentPanelWindow* const dw = dynamic_cast <MultiDocumentPanelWindow*> (getChildComponent (i));
  49191. if (dw != 0 && dw->isActiveWindow())
  49192. return dw->getContentComponent();
  49193. }
  49194. }
  49195. return components.getLast();
  49196. }
  49197. void MultiDocumentPanel::setActiveDocument (Component* component)
  49198. {
  49199. if (mode == FloatingWindows)
  49200. {
  49201. component = getContainerComp (component);
  49202. if (component != 0)
  49203. component->toFront (true);
  49204. }
  49205. else if (tabComponent != 0)
  49206. {
  49207. jassert (components.indexOf (component) >= 0);
  49208. for (int i = tabComponent->getNumTabs(); --i >= 0;)
  49209. {
  49210. if (tabComponent->getTabContentComponent (i) == component)
  49211. {
  49212. tabComponent->setCurrentTabIndex (i);
  49213. break;
  49214. }
  49215. }
  49216. }
  49217. else
  49218. {
  49219. component->grabKeyboardFocus();
  49220. }
  49221. }
  49222. void MultiDocumentPanel::activeDocumentChanged()
  49223. {
  49224. }
  49225. void MultiDocumentPanel::setMaximumNumDocuments (const int newNumber)
  49226. {
  49227. maximumNumDocuments = newNumber;
  49228. }
  49229. void MultiDocumentPanel::useFullscreenWhenOneDocument (const bool shouldUseTabs)
  49230. {
  49231. numDocsBeforeTabsUsed = shouldUseTabs ? 1 : 0;
  49232. }
  49233. bool MultiDocumentPanel::isFullscreenWhenOneDocument() const throw()
  49234. {
  49235. return numDocsBeforeTabsUsed != 0;
  49236. }
  49237. void MultiDocumentPanel::setLayoutMode (const LayoutMode newLayoutMode)
  49238. {
  49239. if (mode != newLayoutMode)
  49240. {
  49241. mode = newLayoutMode;
  49242. if (mode == FloatingWindows)
  49243. {
  49244. deleteAndZero (tabComponent);
  49245. }
  49246. else
  49247. {
  49248. for (int i = getNumChildComponents(); --i >= 0;)
  49249. {
  49250. MultiDocumentPanelWindow* const dw = dynamic_cast <MultiDocumentPanelWindow*> (getChildComponent (i));
  49251. if (dw != 0)
  49252. {
  49253. dw->getContentComponent()->getProperties().set ("mdiDocumentPos_", dw->getWindowStateAsString());
  49254. dw->setContentComponent (0, false);
  49255. delete dw;
  49256. }
  49257. }
  49258. }
  49259. resized();
  49260. const Array <Component*> tempComps (components);
  49261. components.clear();
  49262. for (int i = 0; i < tempComps.size(); ++i)
  49263. {
  49264. Component* const c = tempComps.getUnchecked(i);
  49265. addDocument (c,
  49266. Colour ((int) c->getProperties().getWithDefault ("mdiDocumentBkg_", (int) Colours::white.getARGB())),
  49267. shouldDeleteComp (c));
  49268. }
  49269. }
  49270. }
  49271. void MultiDocumentPanel::setBackgroundColour (const Colour& newBackgroundColour)
  49272. {
  49273. if (backgroundColour != newBackgroundColour)
  49274. {
  49275. backgroundColour = newBackgroundColour;
  49276. setOpaque (newBackgroundColour.isOpaque());
  49277. repaint();
  49278. }
  49279. }
  49280. void MultiDocumentPanel::paint (Graphics& g)
  49281. {
  49282. g.fillAll (backgroundColour);
  49283. }
  49284. void MultiDocumentPanel::resized()
  49285. {
  49286. if (mode == MaximisedWindowsWithTabs || components.size() == numDocsBeforeTabsUsed)
  49287. {
  49288. for (int i = getNumChildComponents(); --i >= 0;)
  49289. getChildComponent (i)->setBounds (0, 0, getWidth(), getHeight());
  49290. }
  49291. setWantsKeyboardFocus (components.size() == 0);
  49292. }
  49293. Component* MultiDocumentPanel::getContainerComp (Component* c) const
  49294. {
  49295. if (mode == FloatingWindows)
  49296. {
  49297. for (int i = 0; i < getNumChildComponents(); ++i)
  49298. {
  49299. MultiDocumentPanelWindow* const dw = dynamic_cast <MultiDocumentPanelWindow*> (getChildComponent (i));
  49300. if (dw != 0 && dw->getContentComponent() == c)
  49301. {
  49302. c = dw;
  49303. break;
  49304. }
  49305. }
  49306. }
  49307. return c;
  49308. }
  49309. void MultiDocumentPanel::componentNameChanged (Component&)
  49310. {
  49311. if (mode == FloatingWindows)
  49312. {
  49313. for (int i = 0; i < getNumChildComponents(); ++i)
  49314. {
  49315. MultiDocumentPanelWindow* const dw = dynamic_cast <MultiDocumentPanelWindow*> (getChildComponent (i));
  49316. if (dw != 0)
  49317. dw->setName (dw->getContentComponent()->getName());
  49318. }
  49319. }
  49320. else if (tabComponent != 0)
  49321. {
  49322. for (int i = tabComponent->getNumTabs(); --i >= 0;)
  49323. tabComponent->setTabName (i, tabComponent->getTabContentComponent (i)->getName());
  49324. }
  49325. }
  49326. void MultiDocumentPanel::updateOrder()
  49327. {
  49328. const Array <Component*> oldList (components);
  49329. if (mode == FloatingWindows)
  49330. {
  49331. components.clear();
  49332. for (int i = 0; i < getNumChildComponents(); ++i)
  49333. {
  49334. MultiDocumentPanelWindow* const dw = dynamic_cast <MultiDocumentPanelWindow*> (getChildComponent (i));
  49335. if (dw != 0)
  49336. components.add (dw->getContentComponent());
  49337. }
  49338. }
  49339. else
  49340. {
  49341. if (tabComponent != 0)
  49342. {
  49343. Component* const current = tabComponent->getCurrentContentComponent();
  49344. if (current != 0)
  49345. {
  49346. components.removeValue (current);
  49347. components.add (current);
  49348. }
  49349. }
  49350. }
  49351. if (components != oldList)
  49352. activeDocumentChanged();
  49353. }
  49354. END_JUCE_NAMESPACE
  49355. /*** End of inlined file: juce_MultiDocumentPanel.cpp ***/
  49356. /*** Start of inlined file: juce_ResizableBorderComponent.cpp ***/
  49357. BEGIN_JUCE_NAMESPACE
  49358. ResizableBorderComponent::Zone::Zone (int zoneFlags) throw()
  49359. : zone (zoneFlags)
  49360. {
  49361. }
  49362. ResizableBorderComponent::Zone::Zone (const ResizableBorderComponent::Zone& other) throw() : zone (other.zone) {}
  49363. ResizableBorderComponent::Zone& ResizableBorderComponent::Zone::operator= (const ResizableBorderComponent::Zone& other) throw() { zone = other.zone; return *this; }
  49364. bool ResizableBorderComponent::Zone::operator== (const ResizableBorderComponent::Zone& other) const throw() { return zone == other.zone; }
  49365. bool ResizableBorderComponent::Zone::operator!= (const ResizableBorderComponent::Zone& other) const throw() { return zone != other.zone; }
  49366. const ResizableBorderComponent::Zone ResizableBorderComponent::Zone::fromPositionOnBorder (const Rectangle<int>& totalSize,
  49367. const BorderSize& border,
  49368. const Point<int>& position)
  49369. {
  49370. int z = 0;
  49371. if (totalSize.contains (position)
  49372. && ! border.subtractedFrom (totalSize).contains (position))
  49373. {
  49374. const int minW = jmax (totalSize.getWidth() / 10, jmin (10, totalSize.getWidth() / 3));
  49375. if (position.getX() < jmax (border.getLeft(), minW))
  49376. z |= left;
  49377. else if (position.getX() >= totalSize.getWidth() - jmax (border.getRight(), minW))
  49378. z |= right;
  49379. const int minH = jmax (totalSize.getHeight() / 10, jmin (10, totalSize.getHeight() / 3));
  49380. if (position.getY() < jmax (border.getTop(), minH))
  49381. z |= top;
  49382. else if (position.getY() >= totalSize.getHeight() - jmax (border.getBottom(), minH))
  49383. z |= bottom;
  49384. }
  49385. return Zone (z);
  49386. }
  49387. const MouseCursor ResizableBorderComponent::Zone::getMouseCursor() const throw()
  49388. {
  49389. MouseCursor::StandardCursorType mc = MouseCursor::NormalCursor;
  49390. switch (zone)
  49391. {
  49392. case (left | top): mc = MouseCursor::TopLeftCornerResizeCursor; break;
  49393. case top: mc = MouseCursor::TopEdgeResizeCursor; break;
  49394. case (right | top): mc = MouseCursor::TopRightCornerResizeCursor; break;
  49395. case left: mc = MouseCursor::LeftEdgeResizeCursor; break;
  49396. case right: mc = MouseCursor::RightEdgeResizeCursor; break;
  49397. case (left | bottom): mc = MouseCursor::BottomLeftCornerResizeCursor; break;
  49398. case bottom: mc = MouseCursor::BottomEdgeResizeCursor; break;
  49399. case (right | bottom): mc = MouseCursor::BottomRightCornerResizeCursor; break;
  49400. default: break;
  49401. }
  49402. return mc;
  49403. }
  49404. const Rectangle<int> ResizableBorderComponent::Zone::resizeRectangleBy (Rectangle<int> b, const Point<int>& offset) const throw()
  49405. {
  49406. if (isDraggingWholeObject())
  49407. return b + offset;
  49408. if (isDraggingLeftEdge())
  49409. b.setLeft (b.getX() + offset.getX());
  49410. if (isDraggingRightEdge())
  49411. b.setWidth (jmax (0, b.getWidth() + offset.getX()));
  49412. if (isDraggingTopEdge())
  49413. b.setTop (b.getY() + offset.getY());
  49414. if (isDraggingBottomEdge())
  49415. b.setHeight (jmax (0, b.getHeight() + offset.getY()));
  49416. return b;
  49417. }
  49418. const Rectangle<float> ResizableBorderComponent::Zone::resizeRectangleBy (Rectangle<float> b, const Point<float>& offset) const throw()
  49419. {
  49420. if (isDraggingWholeObject())
  49421. return b + offset;
  49422. if (isDraggingLeftEdge())
  49423. b.setLeft (b.getX() + offset.getX());
  49424. if (isDraggingRightEdge())
  49425. b.setWidth (jmax (0.0f, b.getWidth() + offset.getX()));
  49426. if (isDraggingTopEdge())
  49427. b.setTop (b.getY() + offset.getY());
  49428. if (isDraggingBottomEdge())
  49429. b.setHeight (jmax (0.0f, b.getHeight() + offset.getY()));
  49430. return b;
  49431. }
  49432. ResizableBorderComponent::ResizableBorderComponent (Component* const componentToResize,
  49433. ComponentBoundsConstrainer* const constrainer_)
  49434. : component (componentToResize),
  49435. constrainer (constrainer_),
  49436. borderSize (5),
  49437. mouseZone (0)
  49438. {
  49439. }
  49440. ResizableBorderComponent::~ResizableBorderComponent()
  49441. {
  49442. }
  49443. void ResizableBorderComponent::paint (Graphics& g)
  49444. {
  49445. getLookAndFeel().drawResizableFrame (g, getWidth(), getHeight(), borderSize);
  49446. }
  49447. void ResizableBorderComponent::mouseEnter (const MouseEvent& e)
  49448. {
  49449. updateMouseZone (e);
  49450. }
  49451. void ResizableBorderComponent::mouseMove (const MouseEvent& e)
  49452. {
  49453. updateMouseZone (e);
  49454. }
  49455. void ResizableBorderComponent::mouseDown (const MouseEvent& e)
  49456. {
  49457. if (component == 0)
  49458. {
  49459. jassertfalse // You've deleted the component that this resizer was supposed to be using!
  49460. return;
  49461. }
  49462. updateMouseZone (e);
  49463. originalBounds = component->getBounds();
  49464. if (constrainer != 0)
  49465. constrainer->resizeStart();
  49466. }
  49467. void ResizableBorderComponent::mouseDrag (const MouseEvent& e)
  49468. {
  49469. if (component == 0)
  49470. {
  49471. jassertfalse // You've deleted the component that this resizer was supposed to be using!
  49472. return;
  49473. }
  49474. const Rectangle<int> bounds (mouseZone.resizeRectangleBy (originalBounds, e.getOffsetFromDragStart()));
  49475. if (constrainer != 0)
  49476. constrainer->setBoundsForComponent (component, bounds,
  49477. mouseZone.isDraggingTopEdge(),
  49478. mouseZone.isDraggingLeftEdge(),
  49479. mouseZone.isDraggingBottomEdge(),
  49480. mouseZone.isDraggingRightEdge());
  49481. else
  49482. component->setBounds (bounds);
  49483. }
  49484. void ResizableBorderComponent::mouseUp (const MouseEvent&)
  49485. {
  49486. if (constrainer != 0)
  49487. constrainer->resizeEnd();
  49488. }
  49489. bool ResizableBorderComponent::hitTest (int x, int y)
  49490. {
  49491. return x < borderSize.getLeft()
  49492. || x >= getWidth() - borderSize.getRight()
  49493. || y < borderSize.getTop()
  49494. || y >= getHeight() - borderSize.getBottom();
  49495. }
  49496. void ResizableBorderComponent::setBorderThickness (const BorderSize& newBorderSize)
  49497. {
  49498. if (borderSize != newBorderSize)
  49499. {
  49500. borderSize = newBorderSize;
  49501. repaint();
  49502. }
  49503. }
  49504. const BorderSize ResizableBorderComponent::getBorderThickness() const
  49505. {
  49506. return borderSize;
  49507. }
  49508. void ResizableBorderComponent::updateMouseZone (const MouseEvent& e)
  49509. {
  49510. Zone newZone (Zone::fromPositionOnBorder (getLocalBounds(), borderSize, e.getPosition()));
  49511. if (mouseZone != newZone)
  49512. {
  49513. mouseZone = newZone;
  49514. setMouseCursor (newZone.getMouseCursor());
  49515. }
  49516. }
  49517. END_JUCE_NAMESPACE
  49518. /*** End of inlined file: juce_ResizableBorderComponent.cpp ***/
  49519. /*** Start of inlined file: juce_ResizableCornerComponent.cpp ***/
  49520. BEGIN_JUCE_NAMESPACE
  49521. ResizableCornerComponent::ResizableCornerComponent (Component* const componentToResize,
  49522. ComponentBoundsConstrainer* const constrainer_)
  49523. : component (componentToResize),
  49524. constrainer (constrainer_)
  49525. {
  49526. setRepaintsOnMouseActivity (true);
  49527. setMouseCursor (MouseCursor::BottomRightCornerResizeCursor);
  49528. }
  49529. ResizableCornerComponent::~ResizableCornerComponent()
  49530. {
  49531. }
  49532. void ResizableCornerComponent::paint (Graphics& g)
  49533. {
  49534. getLookAndFeel()
  49535. .drawCornerResizer (g, getWidth(), getHeight(),
  49536. isMouseOverOrDragging(),
  49537. isMouseButtonDown());
  49538. }
  49539. void ResizableCornerComponent::mouseDown (const MouseEvent&)
  49540. {
  49541. if (component == 0)
  49542. {
  49543. jassertfalse; // You've deleted the component that this resizer is supposed to be controlling!
  49544. return;
  49545. }
  49546. originalBounds = component->getBounds();
  49547. if (constrainer != 0)
  49548. constrainer->resizeStart();
  49549. }
  49550. void ResizableCornerComponent::mouseDrag (const MouseEvent& e)
  49551. {
  49552. if (component == 0)
  49553. {
  49554. jassertfalse; // You've deleted the component that this resizer is supposed to be controlling!
  49555. return;
  49556. }
  49557. Rectangle<int> r (originalBounds.withSize (originalBounds.getWidth() + e.getDistanceFromDragStartX(),
  49558. originalBounds.getHeight() + e.getDistanceFromDragStartY()));
  49559. if (constrainer != 0)
  49560. constrainer->setBoundsForComponent (component, r, false, false, true, true);
  49561. else
  49562. component->setBounds (r);
  49563. }
  49564. void ResizableCornerComponent::mouseUp (const MouseEvent&)
  49565. {
  49566. if (constrainer != 0)
  49567. constrainer->resizeStart();
  49568. }
  49569. bool ResizableCornerComponent::hitTest (int x, int y)
  49570. {
  49571. if (getWidth() <= 0)
  49572. return false;
  49573. const int yAtX = getHeight() - (getHeight() * x / getWidth());
  49574. return y >= yAtX - getHeight() / 4;
  49575. }
  49576. END_JUCE_NAMESPACE
  49577. /*** End of inlined file: juce_ResizableCornerComponent.cpp ***/
  49578. /*** Start of inlined file: juce_ScrollBar.cpp ***/
  49579. BEGIN_JUCE_NAMESPACE
  49580. class ScrollBar::ScrollbarButton : public Button
  49581. {
  49582. public:
  49583. int direction;
  49584. ScrollbarButton (const int direction_, ScrollBar& owner_)
  49585. : Button (String::empty),
  49586. direction (direction_),
  49587. owner (owner_)
  49588. {
  49589. setWantsKeyboardFocus (false);
  49590. }
  49591. ~ScrollbarButton()
  49592. {
  49593. }
  49594. void paintButton (Graphics& g, bool over, bool down)
  49595. {
  49596. getLookAndFeel()
  49597. .drawScrollbarButton (g, owner,
  49598. getWidth(), getHeight(),
  49599. direction,
  49600. owner.isVertical(),
  49601. over, down);
  49602. }
  49603. void clicked()
  49604. {
  49605. owner.moveScrollbarInSteps ((direction == 1 || direction == 2) ? 1 : -1);
  49606. }
  49607. juce_UseDebuggingNewOperator
  49608. private:
  49609. ScrollBar& owner;
  49610. ScrollbarButton (const ScrollbarButton&);
  49611. ScrollbarButton& operator= (const ScrollbarButton&);
  49612. };
  49613. ScrollBar::ScrollBar (const bool vertical_,
  49614. const bool buttonsAreVisible)
  49615. : totalRange (0.0, 1.0),
  49616. visibleRange (0.0, 0.1),
  49617. singleStepSize (0.1),
  49618. thumbAreaStart (0),
  49619. thumbAreaSize (0),
  49620. thumbStart (0),
  49621. thumbSize (0),
  49622. initialDelayInMillisecs (100),
  49623. repeatDelayInMillisecs (50),
  49624. minimumDelayInMillisecs (10),
  49625. vertical (vertical_),
  49626. isDraggingThumb (false),
  49627. autohides (true),
  49628. upButton (0),
  49629. downButton (0)
  49630. {
  49631. setButtonVisibility (buttonsAreVisible);
  49632. setRepaintsOnMouseActivity (true);
  49633. setFocusContainer (true);
  49634. }
  49635. ScrollBar::~ScrollBar()
  49636. {
  49637. deleteAllChildren();
  49638. }
  49639. void ScrollBar::setRangeLimits (const Range<double>& newRangeLimit)
  49640. {
  49641. if (totalRange != newRangeLimit)
  49642. {
  49643. totalRange = newRangeLimit;
  49644. setCurrentRange (visibleRange);
  49645. updateThumbPosition();
  49646. }
  49647. }
  49648. void ScrollBar::setRangeLimits (const double newMinimum, const double newMaximum)
  49649. {
  49650. jassert (newMaximum >= newMinimum); // these can't be the wrong way round!
  49651. setRangeLimits (Range<double> (newMinimum, newMaximum));
  49652. }
  49653. void ScrollBar::setCurrentRange (const Range<double>& newRange)
  49654. {
  49655. const Range<double> constrainedRange (totalRange.constrainRange (newRange));
  49656. if (visibleRange != constrainedRange)
  49657. {
  49658. visibleRange = constrainedRange;
  49659. updateThumbPosition();
  49660. triggerAsyncUpdate();
  49661. }
  49662. }
  49663. void ScrollBar::setCurrentRange (const double newStart, const double newSize)
  49664. {
  49665. setCurrentRange (Range<double> (newStart, newStart + newSize));
  49666. }
  49667. void ScrollBar::setCurrentRangeStart (const double newStart)
  49668. {
  49669. setCurrentRange (visibleRange.movedToStartAt (newStart));
  49670. }
  49671. void ScrollBar::setSingleStepSize (const double newSingleStepSize)
  49672. {
  49673. singleStepSize = newSingleStepSize;
  49674. }
  49675. void ScrollBar::moveScrollbarInSteps (const int howManySteps)
  49676. {
  49677. setCurrentRange (visibleRange + howManySteps * singleStepSize);
  49678. }
  49679. void ScrollBar::moveScrollbarInPages (const int howManyPages)
  49680. {
  49681. setCurrentRange (visibleRange + howManyPages * visibleRange.getLength());
  49682. }
  49683. void ScrollBar::scrollToTop()
  49684. {
  49685. setCurrentRange (visibleRange.movedToStartAt (getMinimumRangeLimit()));
  49686. }
  49687. void ScrollBar::scrollToBottom()
  49688. {
  49689. setCurrentRange (visibleRange.movedToEndAt (getMaximumRangeLimit()));
  49690. }
  49691. void ScrollBar::setButtonRepeatSpeed (const int initialDelayInMillisecs_,
  49692. const int repeatDelayInMillisecs_,
  49693. const int minimumDelayInMillisecs_)
  49694. {
  49695. initialDelayInMillisecs = initialDelayInMillisecs_;
  49696. repeatDelayInMillisecs = repeatDelayInMillisecs_;
  49697. minimumDelayInMillisecs = minimumDelayInMillisecs_;
  49698. if (upButton != 0)
  49699. {
  49700. upButton->setRepeatSpeed (initialDelayInMillisecs, repeatDelayInMillisecs, minimumDelayInMillisecs);
  49701. downButton->setRepeatSpeed (initialDelayInMillisecs, repeatDelayInMillisecs, minimumDelayInMillisecs);
  49702. }
  49703. }
  49704. void ScrollBar::addListener (ScrollBarListener* const listener)
  49705. {
  49706. listeners.add (listener);
  49707. }
  49708. void ScrollBar::removeListener (ScrollBarListener* const listener)
  49709. {
  49710. listeners.remove (listener);
  49711. }
  49712. void ScrollBar::handleAsyncUpdate()
  49713. {
  49714. double start = visibleRange.getStart(); // (need to use a temp variable for VC7 compatibility)
  49715. listeners.call (&ScrollBarListener::scrollBarMoved, this, start);
  49716. }
  49717. void ScrollBar::updateThumbPosition()
  49718. {
  49719. int newThumbSize = roundToInt (totalRange.getLength() > 0 ? (visibleRange.getLength() * thumbAreaSize) / totalRange.getLength()
  49720. : thumbAreaSize);
  49721. if (newThumbSize < getLookAndFeel().getMinimumScrollbarThumbSize (*this))
  49722. newThumbSize = jmin (getLookAndFeel().getMinimumScrollbarThumbSize (*this), thumbAreaSize - 1);
  49723. if (newThumbSize > thumbAreaSize)
  49724. newThumbSize = thumbAreaSize;
  49725. int newThumbStart = thumbAreaStart;
  49726. if (totalRange.getLength() > visibleRange.getLength())
  49727. newThumbStart += roundToInt (((visibleRange.getStart() - totalRange.getStart()) * (thumbAreaSize - newThumbSize))
  49728. / (totalRange.getLength() - visibleRange.getLength()));
  49729. setVisible ((! autohides) || (totalRange.getLength() > visibleRange.getLength() && visibleRange.getLength() > 0.0));
  49730. if (thumbStart != newThumbStart || thumbSize != newThumbSize)
  49731. {
  49732. const int repaintStart = jmin (thumbStart, newThumbStart) - 4;
  49733. const int repaintSize = jmax (thumbStart + thumbSize, newThumbStart + newThumbSize) + 8 - repaintStart;
  49734. if (vertical)
  49735. repaint (0, repaintStart, getWidth(), repaintSize);
  49736. else
  49737. repaint (repaintStart, 0, repaintSize, getHeight());
  49738. thumbStart = newThumbStart;
  49739. thumbSize = newThumbSize;
  49740. }
  49741. }
  49742. void ScrollBar::setOrientation (const bool shouldBeVertical)
  49743. {
  49744. if (vertical != shouldBeVertical)
  49745. {
  49746. vertical = shouldBeVertical;
  49747. if (upButton != 0)
  49748. {
  49749. upButton->direction = vertical ? 0 : 3;
  49750. downButton->direction = vertical ? 2 : 1;
  49751. }
  49752. updateThumbPosition();
  49753. }
  49754. }
  49755. void ScrollBar::setButtonVisibility (const bool buttonsAreVisible)
  49756. {
  49757. delete upButton;
  49758. upButton = 0;
  49759. delete downButton;
  49760. downButton = 0;
  49761. if (buttonsAreVisible)
  49762. {
  49763. addAndMakeVisible (upButton = new ScrollbarButton (vertical ? 0 : 3, *this));
  49764. addAndMakeVisible (downButton = new ScrollbarButton (vertical ? 2 : 1, *this));
  49765. setButtonRepeatSpeed (initialDelayInMillisecs, repeatDelayInMillisecs, minimumDelayInMillisecs);
  49766. }
  49767. updateThumbPosition();
  49768. }
  49769. void ScrollBar::setAutoHide (const bool shouldHideWhenFullRange)
  49770. {
  49771. autohides = shouldHideWhenFullRange;
  49772. updateThumbPosition();
  49773. }
  49774. bool ScrollBar::autoHides() const throw()
  49775. {
  49776. return autohides;
  49777. }
  49778. void ScrollBar::paint (Graphics& g)
  49779. {
  49780. if (thumbAreaSize > 0)
  49781. {
  49782. LookAndFeel& lf = getLookAndFeel();
  49783. const int thumb = (thumbAreaSize > lf.getMinimumScrollbarThumbSize (*this))
  49784. ? thumbSize : 0;
  49785. if (vertical)
  49786. {
  49787. lf.drawScrollbar (g, *this,
  49788. 0, thumbAreaStart,
  49789. getWidth(), thumbAreaSize,
  49790. vertical,
  49791. thumbStart, thumb,
  49792. isMouseOver(), isMouseButtonDown());
  49793. }
  49794. else
  49795. {
  49796. lf.drawScrollbar (g, *this,
  49797. thumbAreaStart, 0,
  49798. thumbAreaSize, getHeight(),
  49799. vertical,
  49800. thumbStart, thumb,
  49801. isMouseOver(), isMouseButtonDown());
  49802. }
  49803. }
  49804. }
  49805. void ScrollBar::lookAndFeelChanged()
  49806. {
  49807. setComponentEffect (getLookAndFeel().getScrollbarEffect());
  49808. }
  49809. void ScrollBar::resized()
  49810. {
  49811. const int length = ((vertical) ? getHeight() : getWidth());
  49812. const int buttonSize = (upButton != 0) ? jmin (getLookAndFeel().getScrollbarButtonSize (*this), (length >> 1))
  49813. : 0;
  49814. if (length < 32 + getLookAndFeel().getMinimumScrollbarThumbSize (*this))
  49815. {
  49816. thumbAreaStart = length >> 1;
  49817. thumbAreaSize = 0;
  49818. }
  49819. else
  49820. {
  49821. thumbAreaStart = buttonSize;
  49822. thumbAreaSize = length - (buttonSize << 1);
  49823. }
  49824. if (upButton != 0)
  49825. {
  49826. if (vertical)
  49827. {
  49828. upButton->setBounds (0, 0, getWidth(), buttonSize);
  49829. downButton->setBounds (0, thumbAreaStart + thumbAreaSize, getWidth(), buttonSize);
  49830. }
  49831. else
  49832. {
  49833. upButton->setBounds (0, 0, buttonSize, getHeight());
  49834. downButton->setBounds (thumbAreaStart + thumbAreaSize, 0, buttonSize, getHeight());
  49835. }
  49836. }
  49837. updateThumbPosition();
  49838. }
  49839. void ScrollBar::mouseDown (const MouseEvent& e)
  49840. {
  49841. isDraggingThumb = false;
  49842. lastMousePos = vertical ? e.y : e.x;
  49843. dragStartMousePos = lastMousePos;
  49844. dragStartRange = visibleRange.getStart();
  49845. if (dragStartMousePos < thumbStart)
  49846. {
  49847. moveScrollbarInPages (-1);
  49848. startTimer (400);
  49849. }
  49850. else if (dragStartMousePos >= thumbStart + thumbSize)
  49851. {
  49852. moveScrollbarInPages (1);
  49853. startTimer (400);
  49854. }
  49855. else
  49856. {
  49857. isDraggingThumb = (thumbAreaSize > getLookAndFeel().getMinimumScrollbarThumbSize (*this))
  49858. && (thumbAreaSize > thumbSize);
  49859. }
  49860. }
  49861. void ScrollBar::mouseDrag (const MouseEvent& e)
  49862. {
  49863. if (isDraggingThumb)
  49864. {
  49865. const int deltaPixels = ((vertical) ? e.y : e.x) - dragStartMousePos;
  49866. setCurrentRangeStart (dragStartRange
  49867. + deltaPixels * (totalRange.getLength() - visibleRange.getLength())
  49868. / (thumbAreaSize - thumbSize));
  49869. }
  49870. else
  49871. {
  49872. lastMousePos = (vertical) ? e.y : e.x;
  49873. }
  49874. }
  49875. void ScrollBar::mouseUp (const MouseEvent&)
  49876. {
  49877. isDraggingThumb = false;
  49878. stopTimer();
  49879. repaint();
  49880. }
  49881. void ScrollBar::mouseWheelMove (const MouseEvent&,
  49882. float wheelIncrementX,
  49883. float wheelIncrementY)
  49884. {
  49885. float increment = vertical ? wheelIncrementY : wheelIncrementX;
  49886. if (increment < 0)
  49887. increment = jmin (increment * 10.0f, -1.0f);
  49888. else if (increment > 0)
  49889. increment = jmax (increment * 10.0f, 1.0f);
  49890. setCurrentRange (visibleRange - singleStepSize * increment);
  49891. }
  49892. void ScrollBar::timerCallback()
  49893. {
  49894. if (isMouseButtonDown())
  49895. {
  49896. startTimer (40);
  49897. if (lastMousePos < thumbStart)
  49898. setCurrentRange (visibleRange - visibleRange.getLength());
  49899. else if (lastMousePos > thumbStart + thumbSize)
  49900. setCurrentRangeStart (visibleRange.getEnd());
  49901. }
  49902. else
  49903. {
  49904. stopTimer();
  49905. }
  49906. }
  49907. bool ScrollBar::keyPressed (const KeyPress& key)
  49908. {
  49909. if (! isVisible())
  49910. return false;
  49911. if (key.isKeyCode (KeyPress::upKey) || key.isKeyCode (KeyPress::leftKey))
  49912. moveScrollbarInSteps (-1);
  49913. else if (key.isKeyCode (KeyPress::downKey) || key.isKeyCode (KeyPress::rightKey))
  49914. moveScrollbarInSteps (1);
  49915. else if (key.isKeyCode (KeyPress::pageUpKey))
  49916. moveScrollbarInPages (-1);
  49917. else if (key.isKeyCode (KeyPress::pageDownKey))
  49918. moveScrollbarInPages (1);
  49919. else if (key.isKeyCode (KeyPress::homeKey))
  49920. scrollToTop();
  49921. else if (key.isKeyCode (KeyPress::endKey))
  49922. scrollToBottom();
  49923. else
  49924. return false;
  49925. return true;
  49926. }
  49927. END_JUCE_NAMESPACE
  49928. /*** End of inlined file: juce_ScrollBar.cpp ***/
  49929. /*** Start of inlined file: juce_StretchableLayoutManager.cpp ***/
  49930. BEGIN_JUCE_NAMESPACE
  49931. StretchableLayoutManager::StretchableLayoutManager()
  49932. : totalSize (0)
  49933. {
  49934. }
  49935. StretchableLayoutManager::~StretchableLayoutManager()
  49936. {
  49937. }
  49938. void StretchableLayoutManager::clearAllItems()
  49939. {
  49940. items.clear();
  49941. totalSize = 0;
  49942. }
  49943. void StretchableLayoutManager::setItemLayout (const int itemIndex,
  49944. const double minimumSize,
  49945. const double maximumSize,
  49946. const double preferredSize)
  49947. {
  49948. ItemLayoutProperties* layout = getInfoFor (itemIndex);
  49949. if (layout == 0)
  49950. {
  49951. layout = new ItemLayoutProperties();
  49952. layout->itemIndex = itemIndex;
  49953. int i;
  49954. for (i = 0; i < items.size(); ++i)
  49955. if (items.getUnchecked (i)->itemIndex > itemIndex)
  49956. break;
  49957. items.insert (i, layout);
  49958. }
  49959. layout->minSize = minimumSize;
  49960. layout->maxSize = maximumSize;
  49961. layout->preferredSize = preferredSize;
  49962. layout->currentSize = 0;
  49963. }
  49964. bool StretchableLayoutManager::getItemLayout (const int itemIndex,
  49965. double& minimumSize,
  49966. double& maximumSize,
  49967. double& preferredSize) const
  49968. {
  49969. const ItemLayoutProperties* const layout = getInfoFor (itemIndex);
  49970. if (layout != 0)
  49971. {
  49972. minimumSize = layout->minSize;
  49973. maximumSize = layout->maxSize;
  49974. preferredSize = layout->preferredSize;
  49975. return true;
  49976. }
  49977. return false;
  49978. }
  49979. void StretchableLayoutManager::setTotalSize (const int newTotalSize)
  49980. {
  49981. totalSize = newTotalSize;
  49982. fitComponentsIntoSpace (0, items.size(), totalSize, 0);
  49983. }
  49984. int StretchableLayoutManager::getItemCurrentPosition (const int itemIndex) const
  49985. {
  49986. int pos = 0;
  49987. for (int i = 0; i < itemIndex; ++i)
  49988. {
  49989. const ItemLayoutProperties* const layout = getInfoFor (i);
  49990. if (layout != 0)
  49991. pos += layout->currentSize;
  49992. }
  49993. return pos;
  49994. }
  49995. int StretchableLayoutManager::getItemCurrentAbsoluteSize (const int itemIndex) const
  49996. {
  49997. const ItemLayoutProperties* const layout = getInfoFor (itemIndex);
  49998. if (layout != 0)
  49999. return layout->currentSize;
  50000. return 0;
  50001. }
  50002. double StretchableLayoutManager::getItemCurrentRelativeSize (const int itemIndex) const
  50003. {
  50004. const ItemLayoutProperties* const layout = getInfoFor (itemIndex);
  50005. if (layout != 0)
  50006. return -layout->currentSize / (double) totalSize;
  50007. return 0;
  50008. }
  50009. void StretchableLayoutManager::setItemPosition (const int itemIndex,
  50010. int newPosition)
  50011. {
  50012. for (int i = items.size(); --i >= 0;)
  50013. {
  50014. const ItemLayoutProperties* const layout = items.getUnchecked(i);
  50015. if (layout->itemIndex == itemIndex)
  50016. {
  50017. int realTotalSize = jmax (totalSize, getMinimumSizeOfItems (0, items.size()));
  50018. const int minSizeAfterThisComp = getMinimumSizeOfItems (i, items.size());
  50019. const int maxSizeAfterThisComp = getMaximumSizeOfItems (i + 1, items.size());
  50020. newPosition = jmax (newPosition, totalSize - maxSizeAfterThisComp - layout->currentSize);
  50021. newPosition = jmin (newPosition, realTotalSize - minSizeAfterThisComp);
  50022. int endPos = fitComponentsIntoSpace (0, i, newPosition, 0);
  50023. endPos += layout->currentSize;
  50024. fitComponentsIntoSpace (i + 1, items.size(), totalSize - endPos, endPos);
  50025. updatePrefSizesToMatchCurrentPositions();
  50026. break;
  50027. }
  50028. }
  50029. }
  50030. void StretchableLayoutManager::layOutComponents (Component** const components,
  50031. int numComponents,
  50032. int x, int y, int w, int h,
  50033. const bool vertically,
  50034. const bool resizeOtherDimension)
  50035. {
  50036. setTotalSize (vertically ? h : w);
  50037. int pos = vertically ? y : x;
  50038. for (int i = 0; i < numComponents; ++i)
  50039. {
  50040. const ItemLayoutProperties* const layout = getInfoFor (i);
  50041. if (layout != 0)
  50042. {
  50043. Component* const c = components[i];
  50044. if (c != 0)
  50045. {
  50046. if (i == numComponents - 1)
  50047. {
  50048. // if it's the last item, crop it to exactly fit the available space..
  50049. if (resizeOtherDimension)
  50050. {
  50051. if (vertically)
  50052. c->setBounds (x, pos, w, jmax (layout->currentSize, h - pos));
  50053. else
  50054. c->setBounds (pos, y, jmax (layout->currentSize, w - pos), h);
  50055. }
  50056. else
  50057. {
  50058. if (vertically)
  50059. c->setBounds (c->getX(), pos, c->getWidth(), jmax (layout->currentSize, h - pos));
  50060. else
  50061. c->setBounds (pos, c->getY(), jmax (layout->currentSize, w - pos), c->getHeight());
  50062. }
  50063. }
  50064. else
  50065. {
  50066. if (resizeOtherDimension)
  50067. {
  50068. if (vertically)
  50069. c->setBounds (x, pos, w, layout->currentSize);
  50070. else
  50071. c->setBounds (pos, y, layout->currentSize, h);
  50072. }
  50073. else
  50074. {
  50075. if (vertically)
  50076. c->setBounds (c->getX(), pos, c->getWidth(), layout->currentSize);
  50077. else
  50078. c->setBounds (pos, c->getY(), layout->currentSize, c->getHeight());
  50079. }
  50080. }
  50081. }
  50082. pos += layout->currentSize;
  50083. }
  50084. }
  50085. }
  50086. StretchableLayoutManager::ItemLayoutProperties* StretchableLayoutManager::getInfoFor (const int itemIndex) const
  50087. {
  50088. for (int i = items.size(); --i >= 0;)
  50089. if (items.getUnchecked(i)->itemIndex == itemIndex)
  50090. return items.getUnchecked(i);
  50091. return 0;
  50092. }
  50093. int StretchableLayoutManager::fitComponentsIntoSpace (const int startIndex,
  50094. const int endIndex,
  50095. const int availableSpace,
  50096. int startPos)
  50097. {
  50098. // calculate the total sizes
  50099. int i;
  50100. double totalIdealSize = 0.0;
  50101. int totalMinimums = 0;
  50102. for (i = startIndex; i < endIndex; ++i)
  50103. {
  50104. ItemLayoutProperties* const layout = items.getUnchecked (i);
  50105. layout->currentSize = sizeToRealSize (layout->minSize, totalSize);
  50106. totalMinimums += layout->currentSize;
  50107. totalIdealSize += sizeToRealSize (layout->preferredSize, availableSpace);
  50108. }
  50109. if (totalIdealSize <= 0)
  50110. totalIdealSize = 1.0;
  50111. // now calc the best sizes..
  50112. int extraSpace = availableSpace - totalMinimums;
  50113. while (extraSpace > 0)
  50114. {
  50115. int numWantingMoreSpace = 0;
  50116. int numHavingTakenExtraSpace = 0;
  50117. // first figure out how many comps want a slice of the extra space..
  50118. for (i = startIndex; i < endIndex; ++i)
  50119. {
  50120. ItemLayoutProperties* const layout = items.getUnchecked (i);
  50121. double sizeWanted = sizeToRealSize (layout->preferredSize, availableSpace);
  50122. const int bestSize = jlimit (layout->currentSize,
  50123. jmax (layout->currentSize,
  50124. sizeToRealSize (layout->maxSize, totalSize)),
  50125. roundToInt (sizeWanted * availableSpace / totalIdealSize));
  50126. if (bestSize > layout->currentSize)
  50127. ++numWantingMoreSpace;
  50128. }
  50129. // ..share out the extra space..
  50130. for (i = startIndex; i < endIndex; ++i)
  50131. {
  50132. ItemLayoutProperties* const layout = items.getUnchecked (i);
  50133. double sizeWanted = sizeToRealSize (layout->preferredSize, availableSpace);
  50134. int bestSize = jlimit (layout->currentSize,
  50135. jmax (layout->currentSize, sizeToRealSize (layout->maxSize, totalSize)),
  50136. roundToInt (sizeWanted * availableSpace / totalIdealSize));
  50137. const int extraWanted = bestSize - layout->currentSize;
  50138. if (extraWanted > 0)
  50139. {
  50140. const int extraAllowed = jmin (extraWanted,
  50141. extraSpace / jmax (1, numWantingMoreSpace));
  50142. if (extraAllowed > 0)
  50143. {
  50144. ++numHavingTakenExtraSpace;
  50145. --numWantingMoreSpace;
  50146. layout->currentSize += extraAllowed;
  50147. extraSpace -= extraAllowed;
  50148. }
  50149. }
  50150. }
  50151. if (numHavingTakenExtraSpace <= 0)
  50152. break;
  50153. }
  50154. // ..and calculate the end position
  50155. for (i = startIndex; i < endIndex; ++i)
  50156. {
  50157. ItemLayoutProperties* const layout = items.getUnchecked(i);
  50158. startPos += layout->currentSize;
  50159. }
  50160. return startPos;
  50161. }
  50162. int StretchableLayoutManager::getMinimumSizeOfItems (const int startIndex,
  50163. const int endIndex) const
  50164. {
  50165. int totalMinimums = 0;
  50166. for (int i = startIndex; i < endIndex; ++i)
  50167. totalMinimums += sizeToRealSize (items.getUnchecked (i)->minSize, totalSize);
  50168. return totalMinimums;
  50169. }
  50170. int StretchableLayoutManager::getMaximumSizeOfItems (const int startIndex, const int endIndex) const
  50171. {
  50172. int totalMaximums = 0;
  50173. for (int i = startIndex; i < endIndex; ++i)
  50174. totalMaximums += sizeToRealSize (items.getUnchecked (i)->maxSize, totalSize);
  50175. return totalMaximums;
  50176. }
  50177. void StretchableLayoutManager::updatePrefSizesToMatchCurrentPositions()
  50178. {
  50179. for (int i = 0; i < items.size(); ++i)
  50180. {
  50181. ItemLayoutProperties* const layout = items.getUnchecked (i);
  50182. layout->preferredSize
  50183. = (layout->preferredSize < 0) ? getItemCurrentRelativeSize (i)
  50184. : getItemCurrentAbsoluteSize (i);
  50185. }
  50186. }
  50187. int StretchableLayoutManager::sizeToRealSize (double size, int totalSpace)
  50188. {
  50189. if (size < 0)
  50190. size *= -totalSpace;
  50191. return roundToInt (size);
  50192. }
  50193. END_JUCE_NAMESPACE
  50194. /*** End of inlined file: juce_StretchableLayoutManager.cpp ***/
  50195. /*** Start of inlined file: juce_StretchableLayoutResizerBar.cpp ***/
  50196. BEGIN_JUCE_NAMESPACE
  50197. StretchableLayoutResizerBar::StretchableLayoutResizerBar (StretchableLayoutManager* layout_,
  50198. const int itemIndex_,
  50199. const bool isVertical_)
  50200. : layout (layout_),
  50201. itemIndex (itemIndex_),
  50202. isVertical (isVertical_)
  50203. {
  50204. setRepaintsOnMouseActivity (true);
  50205. setMouseCursor (MouseCursor (isVertical_ ? MouseCursor::LeftRightResizeCursor
  50206. : MouseCursor::UpDownResizeCursor));
  50207. }
  50208. StretchableLayoutResizerBar::~StretchableLayoutResizerBar()
  50209. {
  50210. }
  50211. void StretchableLayoutResizerBar::paint (Graphics& g)
  50212. {
  50213. getLookAndFeel().drawStretchableLayoutResizerBar (g,
  50214. getWidth(), getHeight(),
  50215. isVertical,
  50216. isMouseOver(),
  50217. isMouseButtonDown());
  50218. }
  50219. void StretchableLayoutResizerBar::mouseDown (const MouseEvent&)
  50220. {
  50221. mouseDownPos = layout->getItemCurrentPosition (itemIndex);
  50222. }
  50223. void StretchableLayoutResizerBar::mouseDrag (const MouseEvent& e)
  50224. {
  50225. const int desiredPos = mouseDownPos + (isVertical ? e.getDistanceFromDragStartX()
  50226. : e.getDistanceFromDragStartY());
  50227. layout->setItemPosition (itemIndex, desiredPos);
  50228. hasBeenMoved();
  50229. }
  50230. void StretchableLayoutResizerBar::hasBeenMoved()
  50231. {
  50232. if (getParentComponent() != 0)
  50233. getParentComponent()->resized();
  50234. }
  50235. END_JUCE_NAMESPACE
  50236. /*** End of inlined file: juce_StretchableLayoutResizerBar.cpp ***/
  50237. /*** Start of inlined file: juce_StretchableObjectResizer.cpp ***/
  50238. BEGIN_JUCE_NAMESPACE
  50239. StretchableObjectResizer::StretchableObjectResizer()
  50240. {
  50241. }
  50242. StretchableObjectResizer::~StretchableObjectResizer()
  50243. {
  50244. }
  50245. void StretchableObjectResizer::addItem (const double size,
  50246. const double minSize, const double maxSize,
  50247. const int order)
  50248. {
  50249. // the order must be >= 0 but less than the maximum integer value.
  50250. jassert (order >= 0 && order < std::numeric_limits<int>::max());
  50251. Item* const item = new Item();
  50252. item->size = size;
  50253. item->minSize = minSize;
  50254. item->maxSize = maxSize;
  50255. item->order = order;
  50256. items.add (item);
  50257. }
  50258. double StretchableObjectResizer::getItemSize (const int index) const throw()
  50259. {
  50260. const Item* const it = items [index];
  50261. return it != 0 ? it->size : 0;
  50262. }
  50263. void StretchableObjectResizer::resizeToFit (const double targetSize)
  50264. {
  50265. int order = 0;
  50266. for (;;)
  50267. {
  50268. double currentSize = 0;
  50269. double minSize = 0;
  50270. double maxSize = 0;
  50271. int nextHighestOrder = std::numeric_limits<int>::max();
  50272. for (int i = 0; i < items.size(); ++i)
  50273. {
  50274. const Item* const it = items.getUnchecked(i);
  50275. currentSize += it->size;
  50276. if (it->order <= order)
  50277. {
  50278. minSize += it->minSize;
  50279. maxSize += it->maxSize;
  50280. }
  50281. else
  50282. {
  50283. minSize += it->size;
  50284. maxSize += it->size;
  50285. nextHighestOrder = jmin (nextHighestOrder, it->order);
  50286. }
  50287. }
  50288. const double thisIterationTarget = jlimit (minSize, maxSize, targetSize);
  50289. if (thisIterationTarget >= currentSize)
  50290. {
  50291. const double availableExtraSpace = maxSize - currentSize;
  50292. const double targetAmountOfExtraSpace = thisIterationTarget - currentSize;
  50293. const double scale = targetAmountOfExtraSpace / availableExtraSpace;
  50294. for (int i = 0; i < items.size(); ++i)
  50295. {
  50296. Item* const it = items.getUnchecked(i);
  50297. if (it->order <= order)
  50298. it->size = jmin (it->maxSize, it->size + (it->maxSize - it->size) * scale);
  50299. }
  50300. }
  50301. else
  50302. {
  50303. const double amountOfSlack = currentSize - minSize;
  50304. const double targetAmountOfSlack = thisIterationTarget - minSize;
  50305. const double scale = targetAmountOfSlack / amountOfSlack;
  50306. for (int i = 0; i < items.size(); ++i)
  50307. {
  50308. Item* const it = items.getUnchecked(i);
  50309. if (it->order <= order)
  50310. it->size = jmax (it->minSize, it->minSize + (it->size - it->minSize) * scale);
  50311. }
  50312. }
  50313. if (nextHighestOrder < std::numeric_limits<int>::max())
  50314. order = nextHighestOrder;
  50315. else
  50316. break;
  50317. }
  50318. }
  50319. END_JUCE_NAMESPACE
  50320. /*** End of inlined file: juce_StretchableObjectResizer.cpp ***/
  50321. /*** Start of inlined file: juce_TabbedButtonBar.cpp ***/
  50322. BEGIN_JUCE_NAMESPACE
  50323. TabBarButton::TabBarButton (const String& name,
  50324. TabbedButtonBar* const owner_,
  50325. const int index)
  50326. : Button (name),
  50327. owner (owner_),
  50328. tabIndex (index),
  50329. overlapPixels (0)
  50330. {
  50331. shadow.setShadowProperties (2.2f, 0.7f, 0, 0);
  50332. setComponentEffect (&shadow);
  50333. setWantsKeyboardFocus (false);
  50334. }
  50335. TabBarButton::~TabBarButton()
  50336. {
  50337. }
  50338. void TabBarButton::paintButton (Graphics& g,
  50339. bool isMouseOverButton,
  50340. bool isButtonDown)
  50341. {
  50342. int x, y, w, h;
  50343. getActiveArea (x, y, w, h);
  50344. g.setOrigin (x, y);
  50345. getLookAndFeel()
  50346. .drawTabButton (g, w, h,
  50347. owner->getTabBackgroundColour (tabIndex),
  50348. tabIndex, getButtonText(), *this,
  50349. owner->getOrientation(),
  50350. isMouseOverButton, isButtonDown,
  50351. getToggleState());
  50352. }
  50353. void TabBarButton::clicked (const ModifierKeys& mods)
  50354. {
  50355. if (mods.isPopupMenu())
  50356. owner->popupMenuClickOnTab (tabIndex, getButtonText());
  50357. else
  50358. owner->setCurrentTabIndex (tabIndex);
  50359. }
  50360. bool TabBarButton::hitTest (int mx, int my)
  50361. {
  50362. int x, y, w, h;
  50363. getActiveArea (x, y, w, h);
  50364. if (owner->getOrientation() == TabbedButtonBar::TabsAtLeft
  50365. || owner->getOrientation() == TabbedButtonBar::TabsAtRight)
  50366. {
  50367. if (((unsigned int) mx) < (unsigned int) getWidth()
  50368. && my >= y + overlapPixels
  50369. && my < y + h - overlapPixels)
  50370. return true;
  50371. }
  50372. else
  50373. {
  50374. if (mx >= x + overlapPixels && mx < x + w - overlapPixels
  50375. && ((unsigned int) my) < (unsigned int) getHeight())
  50376. return true;
  50377. }
  50378. Path p;
  50379. getLookAndFeel()
  50380. .createTabButtonShape (p, w, h, tabIndex, getButtonText(), *this,
  50381. owner->getOrientation(),
  50382. false, false, getToggleState());
  50383. return p.contains ((float) (mx - x),
  50384. (float) (my - y));
  50385. }
  50386. int TabBarButton::getBestTabLength (const int depth)
  50387. {
  50388. return jlimit (depth * 2,
  50389. depth * 7,
  50390. getLookAndFeel().getTabButtonBestWidth (tabIndex, getButtonText(), depth, *this));
  50391. }
  50392. void TabBarButton::getActiveArea (int& x, int& y, int& w, int& h)
  50393. {
  50394. x = 0;
  50395. y = 0;
  50396. int r = getWidth();
  50397. int b = getHeight();
  50398. const int spaceAroundImage = getLookAndFeel().getTabButtonSpaceAroundImage();
  50399. if (owner->getOrientation() != TabbedButtonBar::TabsAtLeft)
  50400. r -= spaceAroundImage;
  50401. if (owner->getOrientation() != TabbedButtonBar::TabsAtRight)
  50402. x += spaceAroundImage;
  50403. if (owner->getOrientation() != TabbedButtonBar::TabsAtBottom)
  50404. y += spaceAroundImage;
  50405. if (owner->getOrientation() != TabbedButtonBar::TabsAtTop)
  50406. b -= spaceAroundImage;
  50407. w = r - x;
  50408. h = b - y;
  50409. }
  50410. class TabAreaBehindFrontButtonComponent : public Component
  50411. {
  50412. public:
  50413. TabAreaBehindFrontButtonComponent (TabbedButtonBar* const owner_)
  50414. : owner (owner_)
  50415. {
  50416. setInterceptsMouseClicks (false, false);
  50417. }
  50418. ~TabAreaBehindFrontButtonComponent()
  50419. {
  50420. }
  50421. void paint (Graphics& g)
  50422. {
  50423. getLookAndFeel()
  50424. .drawTabAreaBehindFrontButton (g, getWidth(), getHeight(),
  50425. *owner, owner->getOrientation());
  50426. }
  50427. void enablementChanged()
  50428. {
  50429. repaint();
  50430. }
  50431. private:
  50432. TabbedButtonBar* const owner;
  50433. TabAreaBehindFrontButtonComponent (const TabAreaBehindFrontButtonComponent&);
  50434. TabAreaBehindFrontButtonComponent& operator= (const TabAreaBehindFrontButtonComponent&);
  50435. };
  50436. TabbedButtonBar::TabbedButtonBar (const Orientation orientation_)
  50437. : orientation (orientation_),
  50438. currentTabIndex (-1),
  50439. extraTabsButton (0)
  50440. {
  50441. setInterceptsMouseClicks (false, true);
  50442. addAndMakeVisible (behindFrontTab = new TabAreaBehindFrontButtonComponent (this));
  50443. setFocusContainer (true);
  50444. }
  50445. TabbedButtonBar::~TabbedButtonBar()
  50446. {
  50447. deleteAllChildren();
  50448. }
  50449. void TabbedButtonBar::setOrientation (const Orientation newOrientation)
  50450. {
  50451. orientation = newOrientation;
  50452. for (int i = getNumChildComponents(); --i >= 0;)
  50453. getChildComponent (i)->resized();
  50454. resized();
  50455. }
  50456. TabBarButton* TabbedButtonBar::createTabButton (const String& name, const int index)
  50457. {
  50458. return new TabBarButton (name, this, index);
  50459. }
  50460. void TabbedButtonBar::clearTabs()
  50461. {
  50462. tabs.clear();
  50463. tabColours.clear();
  50464. currentTabIndex = -1;
  50465. deleteAndZero (extraTabsButton);
  50466. removeChildComponent (behindFrontTab);
  50467. deleteAllChildren();
  50468. addChildComponent (behindFrontTab);
  50469. setCurrentTabIndex (-1);
  50470. }
  50471. void TabbedButtonBar::addTab (const String& tabName,
  50472. const Colour& tabBackgroundColour,
  50473. int insertIndex)
  50474. {
  50475. jassert (tabName.isNotEmpty()); // you have to give them all a name..
  50476. if (tabName.isNotEmpty())
  50477. {
  50478. if (((unsigned int) insertIndex) > (unsigned int) tabs.size())
  50479. insertIndex = tabs.size();
  50480. for (int i = tabs.size(); --i >= insertIndex;)
  50481. {
  50482. TabBarButton* const tb = getTabButton (i);
  50483. if (tb != 0)
  50484. tb->tabIndex++;
  50485. }
  50486. tabs.insert (insertIndex, tabName);
  50487. tabColours.insert (insertIndex, tabBackgroundColour);
  50488. TabBarButton* const tb = createTabButton (tabName, insertIndex);
  50489. jassert (tb != 0); // your createTabButton() mustn't return zero!
  50490. addAndMakeVisible (tb, insertIndex);
  50491. resized();
  50492. if (currentTabIndex < 0)
  50493. setCurrentTabIndex (0);
  50494. }
  50495. }
  50496. void TabbedButtonBar::setTabName (const int tabIndex,
  50497. const String& newName)
  50498. {
  50499. if (((unsigned int) tabIndex) < (unsigned int) tabs.size()
  50500. && tabs[tabIndex] != newName)
  50501. {
  50502. tabs.set (tabIndex, newName);
  50503. TabBarButton* const tb = getTabButton (tabIndex);
  50504. if (tb != 0)
  50505. tb->setButtonText (newName);
  50506. resized();
  50507. }
  50508. }
  50509. void TabbedButtonBar::removeTab (const int tabIndex)
  50510. {
  50511. if (((unsigned int) tabIndex) < (unsigned int) tabs.size())
  50512. {
  50513. const int oldTabIndex = currentTabIndex;
  50514. if (currentTabIndex == tabIndex)
  50515. currentTabIndex = -1;
  50516. tabs.remove (tabIndex);
  50517. tabColours.remove (tabIndex);
  50518. delete getTabButton (tabIndex);
  50519. for (int i = tabIndex + 1; i <= tabs.size(); ++i)
  50520. {
  50521. TabBarButton* const tb = getTabButton (i);
  50522. if (tb != 0)
  50523. tb->tabIndex--;
  50524. }
  50525. resized();
  50526. setCurrentTabIndex (jlimit (0, jmax (0, tabs.size() - 1), oldTabIndex));
  50527. }
  50528. }
  50529. void TabbedButtonBar::moveTab (const int currentIndex,
  50530. const int newIndex)
  50531. {
  50532. tabs.move (currentIndex, newIndex);
  50533. tabColours.move (currentIndex, newIndex);
  50534. resized();
  50535. }
  50536. int TabbedButtonBar::getNumTabs() const
  50537. {
  50538. return tabs.size();
  50539. }
  50540. const StringArray TabbedButtonBar::getTabNames() const
  50541. {
  50542. return tabs;
  50543. }
  50544. void TabbedButtonBar::setCurrentTabIndex (int newIndex, const bool sendChangeMessage_)
  50545. {
  50546. if (currentTabIndex != newIndex)
  50547. {
  50548. if (((unsigned int) newIndex) >= (unsigned int) tabs.size())
  50549. newIndex = -1;
  50550. currentTabIndex = newIndex;
  50551. for (int i = 0; i < getNumChildComponents(); ++i)
  50552. {
  50553. TabBarButton* const tb = dynamic_cast <TabBarButton*> (getChildComponent (i));
  50554. if (tb != 0)
  50555. tb->setToggleState (tb->tabIndex == newIndex, false);
  50556. }
  50557. resized();
  50558. if (sendChangeMessage_)
  50559. sendChangeMessage (this);
  50560. currentTabChanged (newIndex, newIndex >= 0 ? tabs [newIndex] : String::empty);
  50561. }
  50562. }
  50563. TabBarButton* TabbedButtonBar::getTabButton (const int index) const
  50564. {
  50565. for (int i = getNumChildComponents(); --i >= 0;)
  50566. {
  50567. TabBarButton* const tb = dynamic_cast <TabBarButton*> (getChildComponent (i));
  50568. if (tb != 0 && tb->tabIndex == index)
  50569. return tb;
  50570. }
  50571. return 0;
  50572. }
  50573. void TabbedButtonBar::lookAndFeelChanged()
  50574. {
  50575. deleteAndZero (extraTabsButton);
  50576. resized();
  50577. }
  50578. void TabbedButtonBar::resized()
  50579. {
  50580. const double minimumScale = 0.7;
  50581. int depth = getWidth();
  50582. int length = getHeight();
  50583. if (orientation == TabsAtTop || orientation == TabsAtBottom)
  50584. swapVariables (depth, length);
  50585. const int overlap = getLookAndFeel().getTabButtonOverlap (depth)
  50586. + getLookAndFeel().getTabButtonSpaceAroundImage() * 2;
  50587. int i, totalLength = overlap;
  50588. int numVisibleButtons = tabs.size();
  50589. for (i = 0; i < getNumChildComponents(); ++i)
  50590. {
  50591. TabBarButton* const tb = dynamic_cast <TabBarButton*> (getChildComponent (i));
  50592. if (tb != 0)
  50593. {
  50594. totalLength += tb->getBestTabLength (depth) - overlap;
  50595. tb->overlapPixels = overlap / 2;
  50596. }
  50597. }
  50598. double scale = 1.0;
  50599. if (totalLength > length)
  50600. scale = jmax (minimumScale, length / (double) totalLength);
  50601. const bool isTooBig = totalLength * scale > length;
  50602. int tabsButtonPos = 0;
  50603. if (isTooBig)
  50604. {
  50605. if (extraTabsButton == 0)
  50606. {
  50607. addAndMakeVisible (extraTabsButton = getLookAndFeel().createTabBarExtrasButton());
  50608. extraTabsButton->addButtonListener (this);
  50609. extraTabsButton->setAlwaysOnTop (true);
  50610. extraTabsButton->setTriggeredOnMouseDown (true);
  50611. }
  50612. const int buttonSize = jmin (proportionOfWidth (0.7f), proportionOfHeight (0.7f));
  50613. extraTabsButton->setSize (buttonSize, buttonSize);
  50614. if (orientation == TabsAtTop || orientation == TabsAtBottom)
  50615. {
  50616. tabsButtonPos = getWidth() - buttonSize / 2 - 1;
  50617. extraTabsButton->setCentrePosition (tabsButtonPos, getHeight() / 2);
  50618. }
  50619. else
  50620. {
  50621. tabsButtonPos = getHeight() - buttonSize / 2 - 1;
  50622. extraTabsButton->setCentrePosition (getWidth() / 2, tabsButtonPos);
  50623. }
  50624. totalLength = 0;
  50625. for (i = 0; i < tabs.size(); ++i)
  50626. {
  50627. TabBarButton* const tb = getTabButton (i);
  50628. if (tb != 0)
  50629. {
  50630. const int newLength = totalLength + tb->getBestTabLength (depth);
  50631. if (i > 0 && newLength * minimumScale > tabsButtonPos)
  50632. {
  50633. totalLength += overlap;
  50634. break;
  50635. }
  50636. numVisibleButtons = i + 1;
  50637. totalLength = newLength - overlap;
  50638. }
  50639. }
  50640. scale = jmax (minimumScale, tabsButtonPos / (double) totalLength);
  50641. }
  50642. else
  50643. {
  50644. deleteAndZero (extraTabsButton);
  50645. }
  50646. int pos = 0;
  50647. TabBarButton* frontTab = 0;
  50648. for (i = 0; i < tabs.size(); ++i)
  50649. {
  50650. TabBarButton* const tb = getTabButton (i);
  50651. if (tb != 0)
  50652. {
  50653. const int bestLength = roundToInt (scale * tb->getBestTabLength (depth));
  50654. if (i < numVisibleButtons)
  50655. {
  50656. if (orientation == TabsAtTop || orientation == TabsAtBottom)
  50657. tb->setBounds (pos, 0, bestLength, getHeight());
  50658. else
  50659. tb->setBounds (0, pos, getWidth(), bestLength);
  50660. tb->toBack();
  50661. if (tb->tabIndex == currentTabIndex)
  50662. frontTab = tb;
  50663. tb->setVisible (true);
  50664. }
  50665. else
  50666. {
  50667. tb->setVisible (false);
  50668. }
  50669. pos += bestLength - overlap;
  50670. }
  50671. }
  50672. behindFrontTab->setBounds (0, 0, getWidth(), getHeight());
  50673. if (frontTab != 0)
  50674. {
  50675. frontTab->toFront (false);
  50676. behindFrontTab->toBehind (frontTab);
  50677. }
  50678. }
  50679. const Colour TabbedButtonBar::getTabBackgroundColour (const int tabIndex)
  50680. {
  50681. return tabColours [tabIndex];
  50682. }
  50683. void TabbedButtonBar::setTabBackgroundColour (const int tabIndex, const Colour& newColour)
  50684. {
  50685. if (((unsigned int) tabIndex) < (unsigned int) tabColours.size()
  50686. && tabColours [tabIndex] != newColour)
  50687. {
  50688. tabColours.set (tabIndex, newColour);
  50689. repaint();
  50690. }
  50691. }
  50692. void TabbedButtonBar::buttonClicked (Button* button)
  50693. {
  50694. if (extraTabsButton == button)
  50695. {
  50696. PopupMenu m;
  50697. for (int i = 0; i < tabs.size(); ++i)
  50698. {
  50699. TabBarButton* const tb = getTabButton (i);
  50700. if (tb != 0 && ! tb->isVisible())
  50701. m.addItem (tb->tabIndex + 1, tabs[i], true, i == currentTabIndex);
  50702. }
  50703. const int res = m.showAt (extraTabsButton);
  50704. if (res != 0)
  50705. setCurrentTabIndex (res - 1);
  50706. }
  50707. }
  50708. void TabbedButtonBar::currentTabChanged (const int, const String&)
  50709. {
  50710. }
  50711. void TabbedButtonBar::popupMenuClickOnTab (const int, const String&)
  50712. {
  50713. }
  50714. END_JUCE_NAMESPACE
  50715. /*** End of inlined file: juce_TabbedButtonBar.cpp ***/
  50716. /*** Start of inlined file: juce_TabbedComponent.cpp ***/
  50717. BEGIN_JUCE_NAMESPACE
  50718. class TabCompButtonBar : public TabbedButtonBar
  50719. {
  50720. public:
  50721. TabCompButtonBar (TabbedComponent* const owner_,
  50722. const TabbedButtonBar::Orientation orientation_)
  50723. : TabbedButtonBar (orientation_),
  50724. owner (owner_)
  50725. {
  50726. }
  50727. ~TabCompButtonBar()
  50728. {
  50729. }
  50730. void currentTabChanged (int newCurrentTabIndex,
  50731. const String& newTabName)
  50732. {
  50733. owner->changeCallback (newCurrentTabIndex, newTabName);
  50734. }
  50735. void popupMenuClickOnTab (int tabIndex,
  50736. const String& tabName)
  50737. {
  50738. owner->popupMenuClickOnTab (tabIndex, tabName);
  50739. }
  50740. const Colour getTabBackgroundColour (const int tabIndex)
  50741. {
  50742. return owner->tabs->getTabBackgroundColour (tabIndex);
  50743. }
  50744. TabBarButton* createTabButton (const String& tabName, int tabIndex)
  50745. {
  50746. return owner->createTabButton (tabName, tabIndex);
  50747. }
  50748. juce_UseDebuggingNewOperator
  50749. private:
  50750. TabbedComponent* const owner;
  50751. TabCompButtonBar (const TabCompButtonBar&);
  50752. TabCompButtonBar& operator= (const TabCompButtonBar&);
  50753. };
  50754. TabbedComponent::TabbedComponent (const TabbedButtonBar::Orientation orientation)
  50755. : panelComponent (0),
  50756. tabDepth (30),
  50757. outlineThickness (1),
  50758. edgeIndent (0)
  50759. {
  50760. addAndMakeVisible (tabs = new TabCompButtonBar (this, orientation));
  50761. }
  50762. TabbedComponent::~TabbedComponent()
  50763. {
  50764. clearTabs();
  50765. delete tabs;
  50766. }
  50767. void TabbedComponent::setOrientation (const TabbedButtonBar::Orientation orientation)
  50768. {
  50769. tabs->setOrientation (orientation);
  50770. resized();
  50771. }
  50772. TabbedButtonBar::Orientation TabbedComponent::getOrientation() const throw()
  50773. {
  50774. return tabs->getOrientation();
  50775. }
  50776. void TabbedComponent::setTabBarDepth (const int newDepth)
  50777. {
  50778. if (tabDepth != newDepth)
  50779. {
  50780. tabDepth = newDepth;
  50781. resized();
  50782. }
  50783. }
  50784. TabBarButton* TabbedComponent::createTabButton (const String& tabName, const int tabIndex)
  50785. {
  50786. return new TabBarButton (tabName, tabs, tabIndex);
  50787. }
  50788. void TabbedComponent::clearTabs()
  50789. {
  50790. if (panelComponent != 0)
  50791. {
  50792. panelComponent->setVisible (false);
  50793. removeChildComponent (panelComponent);
  50794. panelComponent = 0;
  50795. }
  50796. tabs->clearTabs();
  50797. for (int i = contentComponents.size(); --i >= 0;)
  50798. {
  50799. Component* const c = contentComponents.getUnchecked(i);
  50800. // be careful not to delete these components until they've been removed from the tab component
  50801. jassert (c == 0 || c->isValidComponent());
  50802. if (c != 0 && (bool) c->getProperties() ["deleteByTabComp_"])
  50803. delete c;
  50804. }
  50805. contentComponents.clear();
  50806. }
  50807. void TabbedComponent::addTab (const String& tabName,
  50808. const Colour& tabBackgroundColour,
  50809. Component* const contentComponent,
  50810. const bool deleteComponentWhenNotNeeded,
  50811. const int insertIndex)
  50812. {
  50813. contentComponents.insert (insertIndex, contentComponent);
  50814. if (contentComponent != 0)
  50815. contentComponent->getProperties().set ("deleteByTabComp_", deleteComponentWhenNotNeeded);
  50816. tabs->addTab (tabName, tabBackgroundColour, insertIndex);
  50817. }
  50818. void TabbedComponent::setTabName (const int tabIndex,
  50819. const String& newName)
  50820. {
  50821. tabs->setTabName (tabIndex, newName);
  50822. }
  50823. void TabbedComponent::removeTab (const int tabIndex)
  50824. {
  50825. Component* const c = contentComponents [tabIndex];
  50826. if (c != 0 && (bool) c->getProperties() ["deleteByTabComp_"])
  50827. {
  50828. if (c == panelComponent)
  50829. panelComponent = 0;
  50830. delete c;
  50831. }
  50832. contentComponents.remove (tabIndex);
  50833. tabs->removeTab (tabIndex);
  50834. }
  50835. int TabbedComponent::getNumTabs() const
  50836. {
  50837. return tabs->getNumTabs();
  50838. }
  50839. const StringArray TabbedComponent::getTabNames() const
  50840. {
  50841. return tabs->getTabNames();
  50842. }
  50843. Component* TabbedComponent::getTabContentComponent (const int tabIndex) const throw()
  50844. {
  50845. return contentComponents [tabIndex];
  50846. }
  50847. const Colour TabbedComponent::getTabBackgroundColour (const int tabIndex) const throw()
  50848. {
  50849. return tabs->getTabBackgroundColour (tabIndex);
  50850. }
  50851. void TabbedComponent::setTabBackgroundColour (const int tabIndex, const Colour& newColour)
  50852. {
  50853. tabs->setTabBackgroundColour (tabIndex, newColour);
  50854. if (getCurrentTabIndex() == tabIndex)
  50855. repaint();
  50856. }
  50857. void TabbedComponent::setCurrentTabIndex (const int newTabIndex, const bool sendChangeMessage)
  50858. {
  50859. tabs->setCurrentTabIndex (newTabIndex, sendChangeMessage);
  50860. }
  50861. int TabbedComponent::getCurrentTabIndex() const
  50862. {
  50863. return tabs->getCurrentTabIndex();
  50864. }
  50865. const String& TabbedComponent::getCurrentTabName() const
  50866. {
  50867. return tabs->getCurrentTabName();
  50868. }
  50869. void TabbedComponent::setOutline (int thickness)
  50870. {
  50871. outlineThickness = thickness;
  50872. repaint();
  50873. }
  50874. void TabbedComponent::setIndent (const int indentThickness)
  50875. {
  50876. edgeIndent = indentThickness;
  50877. }
  50878. void TabbedComponent::paint (Graphics& g)
  50879. {
  50880. g.fillAll (findColour (backgroundColourId));
  50881. const TabbedButtonBar::Orientation o = getOrientation();
  50882. int x = 0;
  50883. int y = 0;
  50884. int r = getWidth();
  50885. int b = getHeight();
  50886. if (o == TabbedButtonBar::TabsAtTop)
  50887. y += tabDepth;
  50888. else if (o == TabbedButtonBar::TabsAtBottom)
  50889. b -= tabDepth;
  50890. else if (o == TabbedButtonBar::TabsAtLeft)
  50891. x += tabDepth;
  50892. else if (o == TabbedButtonBar::TabsAtRight)
  50893. r -= tabDepth;
  50894. g.reduceClipRegion (x, y, r - x, b - y);
  50895. g.fillAll (tabs->getTabBackgroundColour (getCurrentTabIndex()));
  50896. if (outlineThickness > 0)
  50897. {
  50898. if (o == TabbedButtonBar::TabsAtTop)
  50899. --y;
  50900. else if (o == TabbedButtonBar::TabsAtBottom)
  50901. ++b;
  50902. else if (o == TabbedButtonBar::TabsAtLeft)
  50903. --x;
  50904. else if (o == TabbedButtonBar::TabsAtRight)
  50905. ++r;
  50906. g.setColour (findColour (outlineColourId));
  50907. g.drawRect (x, y, r - x, b - y, outlineThickness);
  50908. }
  50909. }
  50910. void TabbedComponent::resized()
  50911. {
  50912. const TabbedButtonBar::Orientation o = getOrientation();
  50913. const int indent = edgeIndent + outlineThickness;
  50914. BorderSize indents (indent);
  50915. if (o == TabbedButtonBar::TabsAtTop)
  50916. {
  50917. tabs->setBounds (0, 0, getWidth(), tabDepth);
  50918. indents.setTop (tabDepth + edgeIndent);
  50919. }
  50920. else if (o == TabbedButtonBar::TabsAtBottom)
  50921. {
  50922. tabs->setBounds (0, getHeight() - tabDepth, getWidth(), tabDepth);
  50923. indents.setBottom (tabDepth + edgeIndent);
  50924. }
  50925. else if (o == TabbedButtonBar::TabsAtLeft)
  50926. {
  50927. tabs->setBounds (0, 0, tabDepth, getHeight());
  50928. indents.setLeft (tabDepth + edgeIndent);
  50929. }
  50930. else if (o == TabbedButtonBar::TabsAtRight)
  50931. {
  50932. tabs->setBounds (getWidth() - tabDepth, 0, tabDepth, getHeight());
  50933. indents.setRight (tabDepth + edgeIndent);
  50934. }
  50935. const Rectangle<int> bounds (indents.subtractedFrom (getLocalBounds()));
  50936. for (int i = contentComponents.size(); --i >= 0;)
  50937. if (contentComponents.getUnchecked (i) != 0)
  50938. contentComponents.getUnchecked (i)->setBounds (bounds);
  50939. }
  50940. void TabbedComponent::lookAndFeelChanged()
  50941. {
  50942. for (int i = contentComponents.size(); --i >= 0;)
  50943. if (contentComponents.getUnchecked (i) != 0)
  50944. contentComponents.getUnchecked (i)->lookAndFeelChanged();
  50945. }
  50946. void TabbedComponent::changeCallback (const int newCurrentTabIndex,
  50947. const String& newTabName)
  50948. {
  50949. if (panelComponent != 0)
  50950. {
  50951. panelComponent->setVisible (false);
  50952. removeChildComponent (panelComponent);
  50953. panelComponent = 0;
  50954. }
  50955. if (getCurrentTabIndex() >= 0)
  50956. {
  50957. panelComponent = contentComponents [getCurrentTabIndex()];
  50958. if (panelComponent != 0)
  50959. {
  50960. // do these ops as two stages instead of addAndMakeVisible() so that the
  50961. // component has always got a parent when it gets the visibilityChanged() callback
  50962. addChildComponent (panelComponent);
  50963. panelComponent->setVisible (true);
  50964. panelComponent->toFront (true);
  50965. }
  50966. repaint();
  50967. }
  50968. resized();
  50969. currentTabChanged (newCurrentTabIndex, newTabName);
  50970. }
  50971. void TabbedComponent::currentTabChanged (const int, const String&)
  50972. {
  50973. }
  50974. void TabbedComponent::popupMenuClickOnTab (const int, const String&)
  50975. {
  50976. }
  50977. END_JUCE_NAMESPACE
  50978. /*** End of inlined file: juce_TabbedComponent.cpp ***/
  50979. /*** Start of inlined file: juce_Viewport.cpp ***/
  50980. BEGIN_JUCE_NAMESPACE
  50981. Viewport::Viewport (const String& componentName)
  50982. : Component (componentName),
  50983. contentComp (0),
  50984. scrollBarThickness (0),
  50985. singleStepX (16),
  50986. singleStepY (16),
  50987. showHScrollbar (true),
  50988. showVScrollbar (true)
  50989. {
  50990. // content holder is used to clip the contents so they don't overlap the scrollbars
  50991. addAndMakeVisible (contentHolder = new Component());
  50992. contentHolder->setInterceptsMouseClicks (false, true);
  50993. verticalScrollBar = new ScrollBar (true);
  50994. horizontalScrollBar = new ScrollBar (false);
  50995. addChildComponent (verticalScrollBar);
  50996. addChildComponent (horizontalScrollBar);
  50997. verticalScrollBar->addListener (this);
  50998. horizontalScrollBar->addListener (this);
  50999. setInterceptsMouseClicks (false, true);
  51000. setWantsKeyboardFocus (true);
  51001. }
  51002. Viewport::~Viewport()
  51003. {
  51004. contentHolder->deleteAllChildren();
  51005. deleteAllChildren();
  51006. }
  51007. void Viewport::visibleAreaChanged (int, int, int, int)
  51008. {
  51009. }
  51010. void Viewport::setViewedComponent (Component* const newViewedComponent)
  51011. {
  51012. if (contentComp.getComponent() != newViewedComponent)
  51013. {
  51014. {
  51015. ScopedPointer<Component> oldCompDeleter (contentComp);
  51016. contentComp = 0;
  51017. }
  51018. contentComp = newViewedComponent;
  51019. if (contentComp != 0)
  51020. {
  51021. contentComp->setTopLeftPosition (0, 0);
  51022. contentHolder->addAndMakeVisible (contentComp);
  51023. contentComp->addComponentListener (this);
  51024. }
  51025. updateVisibleRegion();
  51026. }
  51027. }
  51028. int Viewport::getMaximumVisibleWidth() const throw()
  51029. {
  51030. return jmax (0, getWidth() - (verticalScrollBar->isVisible() ? getScrollBarThickness() : 0));
  51031. }
  51032. int Viewport::getMaximumVisibleHeight() const throw()
  51033. {
  51034. return jmax (0, getHeight() - (horizontalScrollBar->isVisible() ? getScrollBarThickness() : 0));
  51035. }
  51036. void Viewport::setViewPosition (const int xPixelsOffset, const int yPixelsOffset)
  51037. {
  51038. if (contentComp != 0)
  51039. contentComp->setTopLeftPosition (-xPixelsOffset,
  51040. -yPixelsOffset);
  51041. }
  51042. void Viewport::setViewPositionProportionately (const double x, const double y)
  51043. {
  51044. if (contentComp != 0)
  51045. setViewPosition (jmax (0, roundToInt (x * (contentComp->getWidth() - getWidth()))),
  51046. jmax (0, roundToInt (y * (contentComp->getHeight() - getHeight()))));
  51047. }
  51048. bool Viewport::autoScroll (int mouseX, int mouseY, int activeBorderThickness, int maximumSpeed)
  51049. {
  51050. if (contentComp != 0)
  51051. {
  51052. int dx = 0, dy = 0;
  51053. if (horizontalScrollBar->isVisible())
  51054. {
  51055. if (mouseX < activeBorderThickness)
  51056. dx = activeBorderThickness - mouseX;
  51057. else if (mouseX >= contentHolder->getWidth() - activeBorderThickness)
  51058. dx = (contentHolder->getWidth() - activeBorderThickness) - mouseX;
  51059. if (dx < 0)
  51060. dx = jmax (dx, -maximumSpeed, contentHolder->getWidth() - contentComp->getRight());
  51061. else
  51062. dx = jmin (dx, maximumSpeed, -contentComp->getX());
  51063. }
  51064. if (verticalScrollBar->isVisible())
  51065. {
  51066. if (mouseY < activeBorderThickness)
  51067. dy = activeBorderThickness - mouseY;
  51068. else if (mouseY >= contentHolder->getHeight() - activeBorderThickness)
  51069. dy = (contentHolder->getHeight() - activeBorderThickness) - mouseY;
  51070. if (dy < 0)
  51071. dy = jmax (dy, -maximumSpeed, contentHolder->getHeight() - contentComp->getBottom());
  51072. else
  51073. dy = jmin (dy, maximumSpeed, -contentComp->getY());
  51074. }
  51075. if (dx != 0 || dy != 0)
  51076. {
  51077. contentComp->setTopLeftPosition (contentComp->getX() + dx,
  51078. contentComp->getY() + dy);
  51079. return true;
  51080. }
  51081. }
  51082. return false;
  51083. }
  51084. void Viewport::componentMovedOrResized (Component&, bool, bool)
  51085. {
  51086. updateVisibleRegion();
  51087. }
  51088. void Viewport::resized()
  51089. {
  51090. updateVisibleRegion();
  51091. }
  51092. void Viewport::updateVisibleRegion()
  51093. {
  51094. if (contentComp != 0)
  51095. {
  51096. Rectangle<int> newViewPos;
  51097. newViewPos.setPosition (-contentComp->getPosition());
  51098. if (newViewPos.getX() == 0 && newViewPos.getY() == 0
  51099. && contentComp->getWidth() <= getWidth()
  51100. && contentComp->getHeight() <= getHeight())
  51101. {
  51102. horizontalScrollBar->setVisible (! horizontalScrollBar->autoHides());
  51103. verticalScrollBar->setVisible (! verticalScrollBar->autoHides());
  51104. }
  51105. horizontalScrollBar->setRangeLimits (0.0, contentComp->getWidth());
  51106. horizontalScrollBar->setCurrentRange (newViewPos.getX(), getMaximumVisibleWidth());
  51107. horizontalScrollBar->setSingleStepSize (singleStepX);
  51108. if (! (contentComp->getWidth() > 0 && showHScrollbar && getHeight() > getScrollBarThickness()))
  51109. horizontalScrollBar->setVisible (! horizontalScrollBar->autoHides());
  51110. verticalScrollBar->setRangeLimits (0.0, contentComp->getHeight());
  51111. verticalScrollBar->setCurrentRange (newViewPos.getY(), getMaximumVisibleHeight());
  51112. verticalScrollBar->setSingleStepSize (singleStepY);
  51113. if (! (contentComp->getHeight() > 0 && showVScrollbar && getWidth() > getScrollBarThickness()))
  51114. verticalScrollBar->setVisible (! verticalScrollBar->autoHides());
  51115. if (verticalScrollBar->isVisible())
  51116. {
  51117. horizontalScrollBar->setCurrentRange (newViewPos.getX(), getMaximumVisibleWidth());
  51118. verticalScrollBar->setCurrentRange (newViewPos.getY(), getMaximumVisibleHeight());
  51119. verticalScrollBar
  51120. ->setBounds (getMaximumVisibleWidth(), 0,
  51121. getScrollBarThickness(), getMaximumVisibleHeight());
  51122. }
  51123. if (horizontalScrollBar->isVisible())
  51124. {
  51125. horizontalScrollBar->setCurrentRange (newViewPos.getX(), getMaximumVisibleWidth());
  51126. horizontalScrollBar
  51127. ->setBounds (0, getMaximumVisibleHeight(),
  51128. getMaximumVisibleWidth(), getScrollBarThickness());
  51129. }
  51130. contentHolder->setSize (getMaximumVisibleWidth(),
  51131. getMaximumVisibleHeight());
  51132. newViewPos.setSize (jmin (contentComp->getRight(), getMaximumVisibleWidth()),
  51133. jmin (contentComp->getBottom(), getMaximumVisibleHeight()));
  51134. if (lastViewPos != newViewPos)
  51135. {
  51136. lastViewPos = newViewPos;
  51137. visibleAreaChanged (newViewPos.getX(), newViewPos.getY(), newViewPos.getWidth(), newViewPos.getHeight());
  51138. }
  51139. horizontalScrollBar->handleUpdateNowIfNeeded();
  51140. verticalScrollBar->handleUpdateNowIfNeeded();
  51141. }
  51142. else
  51143. {
  51144. horizontalScrollBar->setVisible (! horizontalScrollBar->autoHides());
  51145. verticalScrollBar->setVisible (! verticalScrollBar->autoHides());
  51146. }
  51147. }
  51148. void Viewport::setSingleStepSizes (const int stepX, const int stepY)
  51149. {
  51150. singleStepX = stepX;
  51151. singleStepY = stepY;
  51152. updateVisibleRegion();
  51153. }
  51154. void Viewport::setScrollBarsShown (const bool showVerticalScrollbarIfNeeded,
  51155. const bool showHorizontalScrollbarIfNeeded)
  51156. {
  51157. if (showVScrollbar != showVerticalScrollbarIfNeeded
  51158. || showHScrollbar != showHorizontalScrollbarIfNeeded)
  51159. {
  51160. showVScrollbar = showVerticalScrollbarIfNeeded;
  51161. showHScrollbar = showHorizontalScrollbarIfNeeded;
  51162. horizontalScrollBar->setVisible (true);
  51163. verticalScrollBar->setVisible (true);
  51164. updateVisibleRegion();
  51165. }
  51166. }
  51167. void Viewport::setScrollBarThickness (const int thickness)
  51168. {
  51169. scrollBarThickness = thickness;
  51170. updateVisibleRegion();
  51171. }
  51172. int Viewport::getScrollBarThickness() const throw()
  51173. {
  51174. return (scrollBarThickness > 0) ? scrollBarThickness
  51175. : getLookAndFeel().getDefaultScrollbarWidth();
  51176. }
  51177. void Viewport::setScrollBarButtonVisibility (const bool buttonsVisible)
  51178. {
  51179. verticalScrollBar->setButtonVisibility (buttonsVisible);
  51180. horizontalScrollBar->setButtonVisibility (buttonsVisible);
  51181. }
  51182. void Viewport::scrollBarMoved (ScrollBar* scrollBarThatHasMoved, double newRangeStart)
  51183. {
  51184. if (scrollBarThatHasMoved == horizontalScrollBar)
  51185. {
  51186. setViewPosition (roundToInt (newRangeStart), getViewPositionY());
  51187. }
  51188. else if (scrollBarThatHasMoved == verticalScrollBar)
  51189. {
  51190. setViewPosition (getViewPositionX(), roundToInt (newRangeStart));
  51191. }
  51192. }
  51193. void Viewport::mouseWheelMove (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY)
  51194. {
  51195. if (! useMouseWheelMoveIfNeeded (e, wheelIncrementX, wheelIncrementY))
  51196. Component::mouseWheelMove (e, wheelIncrementX, wheelIncrementY);
  51197. }
  51198. bool Viewport::useMouseWheelMoveIfNeeded (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY)
  51199. {
  51200. if (! (e.mods.isAltDown() || e.mods.isCtrlDown()))
  51201. {
  51202. const bool hasVertBar = verticalScrollBar->isVisible();
  51203. const bool hasHorzBar = horizontalScrollBar->isVisible();
  51204. if (hasHorzBar && (wheelIncrementX != 0 || e.mods.isShiftDown() || ! hasVertBar))
  51205. {
  51206. if (wheelIncrementX == 0 && ! hasVertBar)
  51207. wheelIncrementX = wheelIncrementY;
  51208. horizontalScrollBar->mouseWheelMove (e.getEventRelativeTo (horizontalScrollBar),
  51209. wheelIncrementX, wheelIncrementY);
  51210. return true;
  51211. }
  51212. else if (hasVertBar && wheelIncrementY != 0)
  51213. {
  51214. verticalScrollBar->mouseWheelMove (e.getEventRelativeTo (verticalScrollBar),
  51215. wheelIncrementX, wheelIncrementY);
  51216. return true;
  51217. }
  51218. }
  51219. return false;
  51220. }
  51221. bool Viewport::keyPressed (const KeyPress& key)
  51222. {
  51223. const bool isUpDownKey = key.isKeyCode (KeyPress::upKey)
  51224. || key.isKeyCode (KeyPress::downKey)
  51225. || key.isKeyCode (KeyPress::pageUpKey)
  51226. || key.isKeyCode (KeyPress::pageDownKey)
  51227. || key.isKeyCode (KeyPress::homeKey)
  51228. || key.isKeyCode (KeyPress::endKey);
  51229. if (verticalScrollBar->isVisible() && isUpDownKey)
  51230. return verticalScrollBar->keyPressed (key);
  51231. const bool isLeftRightKey = key.isKeyCode (KeyPress::leftKey)
  51232. || key.isKeyCode (KeyPress::rightKey);
  51233. if (horizontalScrollBar->isVisible() && (isUpDownKey || isLeftRightKey))
  51234. return horizontalScrollBar->keyPressed (key);
  51235. return false;
  51236. }
  51237. END_JUCE_NAMESPACE
  51238. /*** End of inlined file: juce_Viewport.cpp ***/
  51239. /*** Start of inlined file: juce_LookAndFeel.cpp ***/
  51240. BEGIN_JUCE_NAMESPACE
  51241. static const Colour createBaseColour (const Colour& buttonColour,
  51242. const bool hasKeyboardFocus,
  51243. const bool isMouseOverButton,
  51244. const bool isButtonDown) throw()
  51245. {
  51246. const float sat = hasKeyboardFocus ? 1.3f : 0.9f;
  51247. const Colour baseColour (buttonColour.withMultipliedSaturation (sat));
  51248. if (isButtonDown)
  51249. return baseColour.contrasting (0.2f);
  51250. else if (isMouseOverButton)
  51251. return baseColour.contrasting (0.1f);
  51252. return baseColour;
  51253. }
  51254. LookAndFeel::LookAndFeel()
  51255. {
  51256. /* if this fails it means you're trying to create a LookAndFeel object before
  51257. the static Colours have been initialised. That ain't gonna work. It probably
  51258. means that you're using a static LookAndFeel object and that your compiler has
  51259. decided to intialise it before the Colours class.
  51260. */
  51261. jassert (Colours::white == Colour (0xffffffff));
  51262. // set up the standard set of colours..
  51263. const int textButtonColour = 0xffbbbbff;
  51264. const int textHighlightColour = 0x401111ee;
  51265. const int standardOutlineColour = 0xb2808080;
  51266. static const int standardColours[] =
  51267. {
  51268. TextButton::buttonColourId, textButtonColour,
  51269. TextButton::buttonOnColourId, 0xff4444ff,
  51270. TextButton::textColourOnId, 0xff000000,
  51271. TextButton::textColourOffId, 0xff000000,
  51272. ComboBox::buttonColourId, 0xffbbbbff,
  51273. ComboBox::outlineColourId, standardOutlineColour,
  51274. ToggleButton::textColourId, 0xff000000,
  51275. TextEditor::backgroundColourId, 0xffffffff,
  51276. TextEditor::textColourId, 0xff000000,
  51277. TextEditor::highlightColourId, textHighlightColour,
  51278. TextEditor::highlightedTextColourId, 0xff000000,
  51279. TextEditor::caretColourId, 0xff000000,
  51280. TextEditor::outlineColourId, 0x00000000,
  51281. TextEditor::focusedOutlineColourId, textButtonColour,
  51282. TextEditor::shadowColourId, 0x38000000,
  51283. Label::backgroundColourId, 0x00000000,
  51284. Label::textColourId, 0xff000000,
  51285. Label::outlineColourId, 0x00000000,
  51286. ScrollBar::backgroundColourId, 0x00000000,
  51287. ScrollBar::thumbColourId, 0xffffffff,
  51288. ScrollBar::trackColourId, 0xffffffff,
  51289. TreeView::linesColourId, 0x4c000000,
  51290. TreeView::backgroundColourId, 0x00000000,
  51291. TreeView::dragAndDropIndicatorColourId, 0x80ff0000,
  51292. PopupMenu::backgroundColourId, 0xffffffff,
  51293. PopupMenu::textColourId, 0xff000000,
  51294. PopupMenu::headerTextColourId, 0xff000000,
  51295. PopupMenu::highlightedTextColourId, 0xffffffff,
  51296. PopupMenu::highlightedBackgroundColourId, 0x991111aa,
  51297. ComboBox::textColourId, 0xff000000,
  51298. ComboBox::backgroundColourId, 0xffffffff,
  51299. ComboBox::arrowColourId, 0x99000000,
  51300. ListBox::backgroundColourId, 0xffffffff,
  51301. ListBox::outlineColourId, standardOutlineColour,
  51302. ListBox::textColourId, 0xff000000,
  51303. Slider::backgroundColourId, 0x00000000,
  51304. Slider::thumbColourId, textButtonColour,
  51305. Slider::trackColourId, 0x7fffffff,
  51306. Slider::rotarySliderFillColourId, 0x7f0000ff,
  51307. Slider::rotarySliderOutlineColourId, 0x66000000,
  51308. Slider::textBoxTextColourId, 0xff000000,
  51309. Slider::textBoxBackgroundColourId, 0xffffffff,
  51310. Slider::textBoxHighlightColourId, textHighlightColour,
  51311. Slider::textBoxOutlineColourId, standardOutlineColour,
  51312. ResizableWindow::backgroundColourId, 0xff777777,
  51313. //DocumentWindow::textColourId, 0xff000000, // (this is deliberately not set)
  51314. AlertWindow::backgroundColourId, 0xffededed,
  51315. AlertWindow::textColourId, 0xff000000,
  51316. AlertWindow::outlineColourId, 0xff666666,
  51317. ProgressBar::backgroundColourId, 0xffeeeeee,
  51318. ProgressBar::foregroundColourId, 0xffaaaaee,
  51319. TooltipWindow::backgroundColourId, 0xffeeeebb,
  51320. TooltipWindow::textColourId, 0xff000000,
  51321. TooltipWindow::outlineColourId, 0x4c000000,
  51322. TabbedComponent::backgroundColourId, 0x00000000,
  51323. TabbedComponent::outlineColourId, 0xff777777,
  51324. TabbedButtonBar::tabOutlineColourId, 0x80000000,
  51325. TabbedButtonBar::frontOutlineColourId, 0x90000000,
  51326. Toolbar::backgroundColourId, 0xfff6f8f9,
  51327. Toolbar::separatorColourId, 0x4c000000,
  51328. Toolbar::buttonMouseOverBackgroundColourId, 0x4c0000ff,
  51329. Toolbar::buttonMouseDownBackgroundColourId, 0x800000ff,
  51330. Toolbar::labelTextColourId, 0xff000000,
  51331. Toolbar::editingModeOutlineColourId, 0xffff0000,
  51332. HyperlinkButton::textColourId, 0xcc1111ee,
  51333. GroupComponent::outlineColourId, 0x66000000,
  51334. GroupComponent::textColourId, 0xff000000,
  51335. DirectoryContentsDisplayComponent::highlightColourId, textHighlightColour,
  51336. DirectoryContentsDisplayComponent::textColourId, 0xff000000,
  51337. 0x1000440, /*LassoComponent::lassoFillColourId*/ 0x66dddddd,
  51338. 0x1000441, /*LassoComponent::lassoOutlineColourId*/ 0x99111111,
  51339. MidiKeyboardComponent::whiteNoteColourId, 0xffffffff,
  51340. MidiKeyboardComponent::blackNoteColourId, 0xff000000,
  51341. MidiKeyboardComponent::keySeparatorLineColourId, 0x66000000,
  51342. MidiKeyboardComponent::mouseOverKeyOverlayColourId, 0x80ffff00,
  51343. MidiKeyboardComponent::keyDownOverlayColourId, 0xffb6b600,
  51344. MidiKeyboardComponent::textLabelColourId, 0xff000000,
  51345. MidiKeyboardComponent::upDownButtonBackgroundColourId, 0xffd3d3d3,
  51346. MidiKeyboardComponent::upDownButtonArrowColourId, 0xff000000,
  51347. CodeEditorComponent::backgroundColourId, 0xffffffff,
  51348. CodeEditorComponent::caretColourId, 0xff000000,
  51349. CodeEditorComponent::highlightColourId, textHighlightColour,
  51350. CodeEditorComponent::defaultTextColourId, 0xff000000,
  51351. ColourSelector::backgroundColourId, 0xffe5e5e5,
  51352. ColourSelector::labelTextColourId, 0xff000000,
  51353. KeyMappingEditorComponent::backgroundColourId, 0x00000000,
  51354. KeyMappingEditorComponent::textColourId, 0xff000000,
  51355. FileSearchPathListComponent::backgroundColourId, 0xffffffff,
  51356. FileChooserDialogBox::titleTextColourId, 0xff000000,
  51357. };
  51358. for (int i = 0; i < numElementsInArray (standardColours); i += 2)
  51359. setColour (standardColours [i], Colour (standardColours [i + 1]));
  51360. static String defaultSansName, defaultSerifName, defaultFixedName;
  51361. if (defaultSansName.isEmpty())
  51362. Font::getPlatformDefaultFontNames (defaultSansName, defaultSerifName, defaultFixedName);
  51363. defaultSans = defaultSansName;
  51364. defaultSerif = defaultSerifName;
  51365. defaultFixed = defaultFixedName;
  51366. }
  51367. LookAndFeel::~LookAndFeel()
  51368. {
  51369. }
  51370. const Colour LookAndFeel::findColour (const int colourId) const throw()
  51371. {
  51372. const int index = colourIds.indexOf (colourId);
  51373. if (index >= 0)
  51374. return colours [index];
  51375. jassertfalse
  51376. return Colours::black;
  51377. }
  51378. void LookAndFeel::setColour (const int colourId, const Colour& colour) throw()
  51379. {
  51380. const int index = colourIds.indexOf (colourId);
  51381. if (index >= 0)
  51382. colours.set (index, colour);
  51383. colourIds.add (colourId);
  51384. colours.add (colour);
  51385. }
  51386. bool LookAndFeel::isColourSpecified (const int colourId) const throw()
  51387. {
  51388. return colourIds.contains (colourId);
  51389. }
  51390. static LookAndFeel* defaultLF = 0;
  51391. static LookAndFeel* currentDefaultLF = 0;
  51392. LookAndFeel& LookAndFeel::getDefaultLookAndFeel() throw()
  51393. {
  51394. // if this happens, your app hasn't initialised itself properly.. if you're
  51395. // trying to hack your own main() function, have a look at
  51396. // JUCEApplication::initialiseForGUI()
  51397. jassert (currentDefaultLF != 0);
  51398. return *currentDefaultLF;
  51399. }
  51400. void LookAndFeel::setDefaultLookAndFeel (LookAndFeel* newDefaultLookAndFeel) throw()
  51401. {
  51402. if (newDefaultLookAndFeel == 0)
  51403. {
  51404. if (defaultLF == 0)
  51405. defaultLF = new LookAndFeel();
  51406. newDefaultLookAndFeel = defaultLF;
  51407. }
  51408. currentDefaultLF = newDefaultLookAndFeel;
  51409. for (int i = Desktop::getInstance().getNumComponents(); --i >= 0;)
  51410. {
  51411. Component* const c = Desktop::getInstance().getComponent (i);
  51412. if (c != 0)
  51413. c->sendLookAndFeelChange();
  51414. }
  51415. }
  51416. void LookAndFeel::clearDefaultLookAndFeel() throw()
  51417. {
  51418. if (currentDefaultLF == defaultLF)
  51419. currentDefaultLF = 0;
  51420. deleteAndZero (defaultLF);
  51421. }
  51422. const Typeface::Ptr LookAndFeel::getTypefaceForFont (const Font& font)
  51423. {
  51424. String faceName (font.getTypefaceName());
  51425. if (faceName == Font::getDefaultSansSerifFontName())
  51426. faceName = defaultSans;
  51427. else if (faceName == Font::getDefaultSerifFontName())
  51428. faceName = defaultSerif;
  51429. else if (faceName == Font::getDefaultMonospacedFontName())
  51430. faceName = defaultFixed;
  51431. Font f (font);
  51432. f.setTypefaceName (faceName);
  51433. return Typeface::createSystemTypefaceFor (f);
  51434. }
  51435. void LookAndFeel::setDefaultSansSerifTypefaceName (const String& newName)
  51436. {
  51437. defaultSans = newName;
  51438. }
  51439. const MouseCursor LookAndFeel::getMouseCursorFor (Component& component)
  51440. {
  51441. return component.getMouseCursor();
  51442. }
  51443. void LookAndFeel::drawButtonBackground (Graphics& g,
  51444. Button& button,
  51445. const Colour& backgroundColour,
  51446. bool isMouseOverButton,
  51447. bool isButtonDown)
  51448. {
  51449. const int width = button.getWidth();
  51450. const int height = button.getHeight();
  51451. const float outlineThickness = button.isEnabled() ? ((isButtonDown || isMouseOverButton) ? 1.2f : 0.7f) : 0.4f;
  51452. const float halfThickness = outlineThickness * 0.5f;
  51453. const float indentL = button.isConnectedOnLeft() ? 0.1f : halfThickness;
  51454. const float indentR = button.isConnectedOnRight() ? 0.1f : halfThickness;
  51455. const float indentT = button.isConnectedOnTop() ? 0.1f : halfThickness;
  51456. const float indentB = button.isConnectedOnBottom() ? 0.1f : halfThickness;
  51457. const Colour baseColour (createBaseColour (backgroundColour,
  51458. button.hasKeyboardFocus (true),
  51459. isMouseOverButton, isButtonDown)
  51460. .withMultipliedAlpha (button.isEnabled() ? 1.0f : 0.5f));
  51461. drawGlassLozenge (g,
  51462. indentL,
  51463. indentT,
  51464. width - indentL - indentR,
  51465. height - indentT - indentB,
  51466. baseColour, outlineThickness, -1.0f,
  51467. button.isConnectedOnLeft(),
  51468. button.isConnectedOnRight(),
  51469. button.isConnectedOnTop(),
  51470. button.isConnectedOnBottom());
  51471. }
  51472. const Font LookAndFeel::getFontForTextButton (TextButton& button)
  51473. {
  51474. return button.getFont();
  51475. }
  51476. void LookAndFeel::drawButtonText (Graphics& g, TextButton& button,
  51477. bool /*isMouseOverButton*/, bool /*isButtonDown*/)
  51478. {
  51479. Font font (getFontForTextButton (button));
  51480. g.setFont (font);
  51481. g.setColour (button.findColour (button.getToggleState() ? TextButton::textColourOnId
  51482. : TextButton::textColourOffId)
  51483. .withMultipliedAlpha (button.isEnabled() ? 1.0f : 0.5f));
  51484. const int yIndent = jmin (4, button.proportionOfHeight (0.3f));
  51485. const int cornerSize = jmin (button.getHeight(), button.getWidth()) / 2;
  51486. const int fontHeight = roundToInt (font.getHeight() * 0.6f);
  51487. const int leftIndent = jmin (fontHeight, 2 + cornerSize / (button.isConnectedOnLeft() ? 4 : 2));
  51488. const int rightIndent = jmin (fontHeight, 2 + cornerSize / (button.isConnectedOnRight() ? 4 : 2));
  51489. g.drawFittedText (button.getButtonText(),
  51490. leftIndent,
  51491. yIndent,
  51492. button.getWidth() - leftIndent - rightIndent,
  51493. button.getHeight() - yIndent * 2,
  51494. Justification::centred, 2);
  51495. }
  51496. void LookAndFeel::drawTickBox (Graphics& g,
  51497. Component& component,
  51498. float x, float y, float w, float h,
  51499. const bool ticked,
  51500. const bool isEnabled,
  51501. const bool isMouseOverButton,
  51502. const bool isButtonDown)
  51503. {
  51504. const float boxSize = w * 0.7f;
  51505. drawGlassSphere (g, x, y + (h - boxSize) * 0.5f, boxSize,
  51506. createBaseColour (component.findColour (TextButton::buttonColourId)
  51507. .withMultipliedAlpha (isEnabled ? 1.0f : 0.5f),
  51508. true,
  51509. isMouseOverButton,
  51510. isButtonDown),
  51511. isEnabled ? ((isButtonDown || isMouseOverButton) ? 1.1f : 0.5f) : 0.3f);
  51512. if (ticked)
  51513. {
  51514. Path tick;
  51515. tick.startNewSubPath (1.5f, 3.0f);
  51516. tick.lineTo (3.0f, 6.0f);
  51517. tick.lineTo (6.0f, 0.0f);
  51518. g.setColour (isEnabled ? Colours::black : Colours::grey);
  51519. const AffineTransform trans (AffineTransform::scale (w / 9.0f, h / 9.0f)
  51520. .translated (x, y));
  51521. g.strokePath (tick, PathStrokeType (2.5f), trans);
  51522. }
  51523. }
  51524. void LookAndFeel::drawToggleButton (Graphics& g,
  51525. ToggleButton& button,
  51526. bool isMouseOverButton,
  51527. bool isButtonDown)
  51528. {
  51529. if (button.hasKeyboardFocus (true))
  51530. {
  51531. g.setColour (button.findColour (TextEditor::focusedOutlineColourId));
  51532. g.drawRect (0, 0, button.getWidth(), button.getHeight());
  51533. }
  51534. float fontSize = jmin (15.0f, button.getHeight() * 0.75f);
  51535. const float tickWidth = fontSize * 1.1f;
  51536. drawTickBox (g, button, 4.0f, (button.getHeight() - tickWidth) * 0.5f,
  51537. tickWidth, tickWidth,
  51538. button.getToggleState(),
  51539. button.isEnabled(),
  51540. isMouseOverButton,
  51541. isButtonDown);
  51542. g.setColour (button.findColour (ToggleButton::textColourId));
  51543. g.setFont (fontSize);
  51544. if (! button.isEnabled())
  51545. g.setOpacity (0.5f);
  51546. const int textX = (int) tickWidth + 5;
  51547. g.drawFittedText (button.getButtonText(),
  51548. textX, 0,
  51549. button.getWidth() - textX - 2, button.getHeight(),
  51550. Justification::centredLeft, 10);
  51551. }
  51552. void LookAndFeel::changeToggleButtonWidthToFitText (ToggleButton& button)
  51553. {
  51554. Font font (jmin (15.0f, button.getHeight() * 0.6f));
  51555. const int tickWidth = jmin (24, button.getHeight());
  51556. button.setSize (font.getStringWidth (button.getButtonText()) + tickWidth + 8,
  51557. button.getHeight());
  51558. }
  51559. AlertWindow* LookAndFeel::createAlertWindow (const String& title,
  51560. const String& message,
  51561. const String& button1,
  51562. const String& button2,
  51563. const String& button3,
  51564. AlertWindow::AlertIconType iconType,
  51565. int numButtons,
  51566. Component* associatedComponent)
  51567. {
  51568. AlertWindow* aw = new AlertWindow (title, message, iconType, associatedComponent);
  51569. if (numButtons == 1)
  51570. {
  51571. aw->addButton (button1, 0,
  51572. KeyPress (KeyPress::escapeKey, 0, 0),
  51573. KeyPress (KeyPress::returnKey, 0, 0));
  51574. }
  51575. else
  51576. {
  51577. const KeyPress button1ShortCut (CharacterFunctions::toLowerCase (button1[0]), 0, 0);
  51578. KeyPress button2ShortCut (CharacterFunctions::toLowerCase (button2[0]), 0, 0);
  51579. if (button1ShortCut == button2ShortCut)
  51580. button2ShortCut = KeyPress();
  51581. if (numButtons == 2)
  51582. {
  51583. aw->addButton (button1, 1, KeyPress (KeyPress::returnKey, 0, 0), button1ShortCut);
  51584. aw->addButton (button2, 0, KeyPress (KeyPress::escapeKey, 0, 0), button2ShortCut);
  51585. }
  51586. else if (numButtons == 3)
  51587. {
  51588. aw->addButton (button1, 1, button1ShortCut);
  51589. aw->addButton (button2, 2, button2ShortCut);
  51590. aw->addButton (button3, 0, KeyPress (KeyPress::escapeKey, 0, 0));
  51591. }
  51592. }
  51593. return aw;
  51594. }
  51595. void LookAndFeel::drawAlertBox (Graphics& g,
  51596. AlertWindow& alert,
  51597. const Rectangle<int>& textArea,
  51598. TextLayout& textLayout)
  51599. {
  51600. g.fillAll (alert.findColour (AlertWindow::backgroundColourId));
  51601. int iconSpaceUsed = 0;
  51602. Justification alignment (Justification::horizontallyCentred);
  51603. const int iconWidth = 80;
  51604. int iconSize = jmin (iconWidth + 50, alert.getHeight() + 20);
  51605. if (alert.containsAnyExtraComponents() || alert.getNumButtons() > 2)
  51606. iconSize = jmin (iconSize, textArea.getHeight() + 50);
  51607. const Rectangle<int> iconRect (iconSize / -10, iconSize / -10,
  51608. iconSize, iconSize);
  51609. if (alert.getAlertType() != AlertWindow::NoIcon)
  51610. {
  51611. Path icon;
  51612. uint32 colour;
  51613. char character;
  51614. if (alert.getAlertType() == AlertWindow::WarningIcon)
  51615. {
  51616. colour = 0x55ff5555;
  51617. character = '!';
  51618. icon.addTriangle (iconRect.getX() + iconRect.getWidth() * 0.5f, (float) iconRect.getY(),
  51619. (float) iconRect.getRight(), (float) iconRect.getBottom(),
  51620. (float) iconRect.getX(), (float) iconRect.getBottom());
  51621. icon = icon.createPathWithRoundedCorners (5.0f);
  51622. }
  51623. else
  51624. {
  51625. colour = alert.getAlertType() == AlertWindow::InfoIcon ? 0x605555ff : 0x40b69900;
  51626. character = alert.getAlertType() == AlertWindow::InfoIcon ? 'i' : '?';
  51627. icon.addEllipse ((float) iconRect.getX(), (float) iconRect.getY(),
  51628. (float) iconRect.getWidth(), (float) iconRect.getHeight());
  51629. }
  51630. GlyphArrangement ga;
  51631. ga.addFittedText (Font (iconRect.getHeight() * 0.9f, Font::bold),
  51632. String::charToString (character),
  51633. (float) iconRect.getX(), (float) iconRect.getY(),
  51634. (float) iconRect.getWidth(), (float) iconRect.getHeight(),
  51635. Justification::centred, false);
  51636. ga.createPath (icon);
  51637. icon.setUsingNonZeroWinding (false);
  51638. g.setColour (Colour (colour));
  51639. g.fillPath (icon);
  51640. iconSpaceUsed = iconWidth;
  51641. alignment = Justification::left;
  51642. }
  51643. g.setColour (alert.findColour (AlertWindow::textColourId));
  51644. textLayout.drawWithin (g,
  51645. textArea.getX() + iconSpaceUsed, textArea.getY(),
  51646. textArea.getWidth() - iconSpaceUsed, textArea.getHeight(),
  51647. alignment.getFlags() | Justification::top);
  51648. g.setColour (alert.findColour (AlertWindow::outlineColourId));
  51649. g.drawRect (0, 0, alert.getWidth(), alert.getHeight());
  51650. }
  51651. int LookAndFeel::getAlertBoxWindowFlags()
  51652. {
  51653. return ComponentPeer::windowAppearsOnTaskbar
  51654. | ComponentPeer::windowHasDropShadow;
  51655. }
  51656. int LookAndFeel::getAlertWindowButtonHeight()
  51657. {
  51658. return 28;
  51659. }
  51660. const Font LookAndFeel::getAlertWindowFont()
  51661. {
  51662. return Font (12.0f);
  51663. }
  51664. void LookAndFeel::drawProgressBar (Graphics& g, ProgressBar& progressBar,
  51665. int width, int height,
  51666. double progress, const String& textToShow)
  51667. {
  51668. const Colour background (progressBar.findColour (ProgressBar::backgroundColourId));
  51669. const Colour foreground (progressBar.findColour (ProgressBar::foregroundColourId));
  51670. g.fillAll (background);
  51671. if (progress >= 0.0f && progress < 1.0f)
  51672. {
  51673. drawGlassLozenge (g, 1.0f, 1.0f,
  51674. (float) jlimit (0.0, width - 2.0, progress * (width - 2.0)),
  51675. (float) (height - 2),
  51676. foreground,
  51677. 0.5f, 0.0f,
  51678. true, true, true, true);
  51679. }
  51680. else
  51681. {
  51682. // spinning bar..
  51683. g.setColour (foreground);
  51684. const int stripeWidth = height * 2;
  51685. const int position = (Time::getMillisecondCounter() / 15) % stripeWidth;
  51686. Path p;
  51687. for (float x = (float) (- position); x < width + stripeWidth; x += stripeWidth)
  51688. p.addQuadrilateral (x, 0.0f,
  51689. x + stripeWidth * 0.5f, 0.0f,
  51690. x, (float) height,
  51691. x - stripeWidth * 0.5f, (float) height);
  51692. Image im (Image::ARGB, width, height, true);
  51693. {
  51694. Graphics g2 (im);
  51695. drawGlassLozenge (g2, 1.0f, 1.0f,
  51696. (float) (width - 2),
  51697. (float) (height - 2),
  51698. foreground,
  51699. 0.5f, 0.0f,
  51700. true, true, true, true);
  51701. }
  51702. g.setTiledImageFill (im, 0, 0, 0.85f);
  51703. g.fillPath (p);
  51704. }
  51705. if (textToShow.isNotEmpty())
  51706. {
  51707. g.setColour (Colour::contrasting (background, foreground));
  51708. g.setFont (height * 0.6f);
  51709. g.drawText (textToShow, 0, 0, width, height, Justification::centred, false);
  51710. }
  51711. }
  51712. void LookAndFeel::drawSpinningWaitAnimation (Graphics& g, const Colour& colour, int x, int y, int w, int h)
  51713. {
  51714. const float radius = jmin (w, h) * 0.4f;
  51715. const float thickness = radius * 0.15f;
  51716. Path p;
  51717. p.addRoundedRectangle (radius * 0.4f, thickness * -0.5f,
  51718. radius * 0.6f, thickness,
  51719. thickness * 0.5f);
  51720. const float cx = x + w * 0.5f;
  51721. const float cy = y + h * 0.5f;
  51722. const uint32 animationIndex = (Time::getMillisecondCounter() / (1000 / 10)) % 12;
  51723. for (int i = 0; i < 12; ++i)
  51724. {
  51725. const int n = (i + 12 - animationIndex) % 12;
  51726. g.setColour (colour.withMultipliedAlpha ((n + 1) / 12.0f));
  51727. g.fillPath (p, AffineTransform::rotation (i * (float_Pi / 6.0f))
  51728. .translated (cx, cy));
  51729. }
  51730. }
  51731. void LookAndFeel::drawScrollbarButton (Graphics& g,
  51732. ScrollBar& scrollbar,
  51733. int width, int height,
  51734. int buttonDirection,
  51735. bool /*isScrollbarVertical*/,
  51736. bool /*isMouseOverButton*/,
  51737. bool isButtonDown)
  51738. {
  51739. Path p;
  51740. if (buttonDirection == 0)
  51741. p.addTriangle (width * 0.5f, height * 0.2f,
  51742. width * 0.1f, height * 0.7f,
  51743. width * 0.9f, height * 0.7f);
  51744. else if (buttonDirection == 1)
  51745. p.addTriangle (width * 0.8f, height * 0.5f,
  51746. width * 0.3f, height * 0.1f,
  51747. width * 0.3f, height * 0.9f);
  51748. else if (buttonDirection == 2)
  51749. p.addTriangle (width * 0.5f, height * 0.8f,
  51750. width * 0.1f, height * 0.3f,
  51751. width * 0.9f, height * 0.3f);
  51752. else if (buttonDirection == 3)
  51753. p.addTriangle (width * 0.2f, height * 0.5f,
  51754. width * 0.7f, height * 0.1f,
  51755. width * 0.7f, height * 0.9f);
  51756. if (isButtonDown)
  51757. g.setColour (scrollbar.findColour (ScrollBar::thumbColourId).contrasting (0.2f));
  51758. else
  51759. g.setColour (scrollbar.findColour (ScrollBar::thumbColourId));
  51760. g.fillPath (p);
  51761. g.setColour (Colour (0x80000000));
  51762. g.strokePath (p, PathStrokeType (0.5f));
  51763. }
  51764. void LookAndFeel::drawScrollbar (Graphics& g,
  51765. ScrollBar& scrollbar,
  51766. int x, int y,
  51767. int width, int height,
  51768. bool isScrollbarVertical,
  51769. int thumbStartPosition,
  51770. int thumbSize,
  51771. bool /*isMouseOver*/,
  51772. bool /*isMouseDown*/)
  51773. {
  51774. g.fillAll (scrollbar.findColour (ScrollBar::backgroundColourId));
  51775. Path slotPath, thumbPath;
  51776. const float slotIndent = jmin (width, height) > 15 ? 1.0f : 0.0f;
  51777. const float slotIndentx2 = slotIndent * 2.0f;
  51778. const float thumbIndent = slotIndent + 1.0f;
  51779. const float thumbIndentx2 = thumbIndent * 2.0f;
  51780. float gx1 = 0.0f, gy1 = 0.0f, gx2 = 0.0f, gy2 = 0.0f;
  51781. if (isScrollbarVertical)
  51782. {
  51783. slotPath.addRoundedRectangle (x + slotIndent,
  51784. y + slotIndent,
  51785. width - slotIndentx2,
  51786. height - slotIndentx2,
  51787. (width - slotIndentx2) * 0.5f);
  51788. if (thumbSize > 0)
  51789. thumbPath.addRoundedRectangle (x + thumbIndent,
  51790. thumbStartPosition + thumbIndent,
  51791. width - thumbIndentx2,
  51792. thumbSize - thumbIndentx2,
  51793. (width - thumbIndentx2) * 0.5f);
  51794. gx1 = (float) x;
  51795. gx2 = x + width * 0.7f;
  51796. }
  51797. else
  51798. {
  51799. slotPath.addRoundedRectangle (x + slotIndent,
  51800. y + slotIndent,
  51801. width - slotIndentx2,
  51802. height - slotIndentx2,
  51803. (height - slotIndentx2) * 0.5f);
  51804. if (thumbSize > 0)
  51805. thumbPath.addRoundedRectangle (thumbStartPosition + thumbIndent,
  51806. y + thumbIndent,
  51807. thumbSize - thumbIndentx2,
  51808. height - thumbIndentx2,
  51809. (height - thumbIndentx2) * 0.5f);
  51810. gy1 = (float) y;
  51811. gy2 = y + height * 0.7f;
  51812. }
  51813. const Colour thumbColour (scrollbar.findColour (ScrollBar::thumbColourId));
  51814. g.setGradientFill (ColourGradient (thumbColour.overlaidWith (Colour (0x44000000)), gx1, gy1,
  51815. thumbColour.overlaidWith (Colour (0x19000000)), gx2, gy2, false));
  51816. g.fillPath (slotPath);
  51817. if (isScrollbarVertical)
  51818. {
  51819. gx1 = x + width * 0.6f;
  51820. gx2 = (float) x + width;
  51821. }
  51822. else
  51823. {
  51824. gy1 = y + height * 0.6f;
  51825. gy2 = (float) y + height;
  51826. }
  51827. g.setGradientFill (ColourGradient (Colours::transparentBlack,gx1, gy1,
  51828. Colour (0x19000000), gx2, gy2, false));
  51829. g.fillPath (slotPath);
  51830. g.setColour (thumbColour);
  51831. g.fillPath (thumbPath);
  51832. g.setGradientFill (ColourGradient (Colour (0x10000000), gx1, gy1,
  51833. Colours::transparentBlack, gx2, gy2, false));
  51834. g.saveState();
  51835. if (isScrollbarVertical)
  51836. g.reduceClipRegion (x + width / 2, y, width, height);
  51837. else
  51838. g.reduceClipRegion (x, y + height / 2, width, height);
  51839. g.fillPath (thumbPath);
  51840. g.restoreState();
  51841. g.setColour (Colour (0x4c000000));
  51842. g.strokePath (thumbPath, PathStrokeType (0.4f));
  51843. }
  51844. ImageEffectFilter* LookAndFeel::getScrollbarEffect()
  51845. {
  51846. return 0;
  51847. }
  51848. int LookAndFeel::getMinimumScrollbarThumbSize (ScrollBar& scrollbar)
  51849. {
  51850. return jmin (scrollbar.getWidth(), scrollbar.getHeight()) * 2;
  51851. }
  51852. int LookAndFeel::getDefaultScrollbarWidth()
  51853. {
  51854. return 18;
  51855. }
  51856. int LookAndFeel::getScrollbarButtonSize (ScrollBar& scrollbar)
  51857. {
  51858. return 2 + (scrollbar.isVertical() ? scrollbar.getWidth()
  51859. : scrollbar.getHeight());
  51860. }
  51861. const Path LookAndFeel::getTickShape (const float height)
  51862. {
  51863. static const unsigned char tickShapeData[] =
  51864. {
  51865. 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,
  51866. 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,
  51867. 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,
  51868. 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,
  51869. 96,140,68,0,128,188,67,0,224,168,68,0,0,119,67,99,101
  51870. };
  51871. Path p;
  51872. p.loadPathFromData (tickShapeData, sizeof (tickShapeData));
  51873. p.scaleToFit (0, 0, height * 2.0f, height, true);
  51874. return p;
  51875. }
  51876. const Path LookAndFeel::getCrossShape (const float height)
  51877. {
  51878. static const unsigned char crossShapeData[] =
  51879. {
  51880. 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,
  51881. 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,
  51882. 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,
  51883. 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,
  51884. 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,
  51885. 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,
  51886. 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
  51887. };
  51888. Path p;
  51889. p.loadPathFromData (crossShapeData, sizeof (crossShapeData));
  51890. p.scaleToFit (0, 0, height * 2.0f, height, true);
  51891. return p;
  51892. }
  51893. void LookAndFeel::drawTreeviewPlusMinusBox (Graphics& g, int x, int y, int w, int h, bool isPlus, bool /*isMouseOver*/)
  51894. {
  51895. const int boxSize = ((jmin (16, w, h) << 1) / 3) | 1;
  51896. x += (w - boxSize) >> 1;
  51897. y += (h - boxSize) >> 1;
  51898. w = boxSize;
  51899. h = boxSize;
  51900. g.setColour (Colour (0xe5ffffff));
  51901. g.fillRect (x, y, w, h);
  51902. g.setColour (Colour (0x80000000));
  51903. g.drawRect (x, y, w, h);
  51904. const float size = boxSize / 2 + 1.0f;
  51905. const float centre = (float) (boxSize / 2);
  51906. g.fillRect (x + (w - size) * 0.5f, y + centre, size, 1.0f);
  51907. if (isPlus)
  51908. g.fillRect (x + centre, y + (h - size) * 0.5f, 1.0f, size);
  51909. }
  51910. void LookAndFeel::drawBubble (Graphics& g,
  51911. float tipX, float tipY,
  51912. float boxX, float boxY,
  51913. float boxW, float boxH)
  51914. {
  51915. int side = 0;
  51916. if (tipX < boxX)
  51917. side = 1;
  51918. else if (tipX > boxX + boxW)
  51919. side = 3;
  51920. else if (tipY > boxY + boxH)
  51921. side = 2;
  51922. const float indent = 2.0f;
  51923. Path p;
  51924. p.addBubble (boxX + indent,
  51925. boxY + indent,
  51926. boxW - indent * 2.0f,
  51927. boxH - indent * 2.0f,
  51928. 5.0f,
  51929. tipX, tipY,
  51930. side,
  51931. 0.5f,
  51932. jmin (15.0f, boxW * 0.3f, boxH * 0.3f));
  51933. //xxx need to take comp as param for colour
  51934. g.setColour (findColour (TooltipWindow::backgroundColourId).withAlpha (0.9f));
  51935. g.fillPath (p);
  51936. //xxx as above
  51937. g.setColour (findColour (TooltipWindow::textColourId).withAlpha (0.4f));
  51938. g.strokePath (p, PathStrokeType (1.33f));
  51939. }
  51940. const Font LookAndFeel::getPopupMenuFont()
  51941. {
  51942. return Font (17.0f);
  51943. }
  51944. void LookAndFeel::getIdealPopupMenuItemSize (const String& text,
  51945. const bool isSeparator,
  51946. int standardMenuItemHeight,
  51947. int& idealWidth,
  51948. int& idealHeight)
  51949. {
  51950. if (isSeparator)
  51951. {
  51952. idealWidth = 50;
  51953. idealHeight = standardMenuItemHeight > 0 ? standardMenuItemHeight / 2 : 10;
  51954. }
  51955. else
  51956. {
  51957. Font font (getPopupMenuFont());
  51958. if (standardMenuItemHeight > 0 && font.getHeight() > standardMenuItemHeight / 1.3f)
  51959. font.setHeight (standardMenuItemHeight / 1.3f);
  51960. idealHeight = standardMenuItemHeight > 0 ? standardMenuItemHeight : roundToInt (font.getHeight() * 1.3f);
  51961. idealWidth = font.getStringWidth (text) + idealHeight * 2;
  51962. }
  51963. }
  51964. void LookAndFeel::drawPopupMenuBackground (Graphics& g, int width, int height)
  51965. {
  51966. const Colour background (findColour (PopupMenu::backgroundColourId));
  51967. g.fillAll (background);
  51968. g.setColour (background.overlaidWith (Colour (0x2badd8e6)));
  51969. for (int i = 0; i < height; i += 3)
  51970. g.fillRect (0, i, width, 1);
  51971. #if ! JUCE_MAC
  51972. g.setColour (findColour (PopupMenu::textColourId).withAlpha (0.6f));
  51973. g.drawRect (0, 0, width, height);
  51974. #endif
  51975. }
  51976. void LookAndFeel::drawPopupMenuUpDownArrow (Graphics& g,
  51977. int width, int height,
  51978. bool isScrollUpArrow)
  51979. {
  51980. const Colour background (findColour (PopupMenu::backgroundColourId));
  51981. g.setGradientFill (ColourGradient (background, 0.0f, height * 0.5f,
  51982. background.withAlpha (0.0f),
  51983. 0.0f, isScrollUpArrow ? ((float) height) : 0.0f,
  51984. false));
  51985. g.fillRect (1, 1, width - 2, height - 2);
  51986. const float hw = width * 0.5f;
  51987. const float arrowW = height * 0.3f;
  51988. const float y1 = height * (isScrollUpArrow ? 0.6f : 0.3f);
  51989. const float y2 = height * (isScrollUpArrow ? 0.3f : 0.6f);
  51990. Path p;
  51991. p.addTriangle (hw - arrowW, y1,
  51992. hw + arrowW, y1,
  51993. hw, y2);
  51994. g.setColour (findColour (PopupMenu::textColourId).withAlpha (0.5f));
  51995. g.fillPath (p);
  51996. }
  51997. void LookAndFeel::drawPopupMenuItem (Graphics& g,
  51998. int width, int height,
  51999. const bool isSeparator,
  52000. const bool isActive,
  52001. const bool isHighlighted,
  52002. const bool isTicked,
  52003. const bool hasSubMenu,
  52004. const String& text,
  52005. const String& shortcutKeyText,
  52006. Image* image,
  52007. const Colour* const textColourToUse)
  52008. {
  52009. const float halfH = height * 0.5f;
  52010. if (isSeparator)
  52011. {
  52012. const float separatorIndent = 5.5f;
  52013. g.setColour (Colour (0x33000000));
  52014. g.drawLine (separatorIndent, halfH, width - separatorIndent, halfH);
  52015. g.setColour (Colour (0x66ffffff));
  52016. g.drawLine (separatorIndent, halfH + 1.0f, width - separatorIndent, halfH + 1.0f);
  52017. }
  52018. else
  52019. {
  52020. Colour textColour (findColour (PopupMenu::textColourId));
  52021. if (textColourToUse != 0)
  52022. textColour = *textColourToUse;
  52023. if (isHighlighted)
  52024. {
  52025. g.setColour (findColour (PopupMenu::highlightedBackgroundColourId));
  52026. g.fillRect (1, 1, width - 2, height - 2);
  52027. g.setColour (findColour (PopupMenu::highlightedTextColourId));
  52028. }
  52029. else
  52030. {
  52031. g.setColour (textColour);
  52032. }
  52033. if (! isActive)
  52034. g.setOpacity (0.3f);
  52035. Font font (getPopupMenuFont());
  52036. if (font.getHeight() > height / 1.3f)
  52037. font.setHeight (height / 1.3f);
  52038. g.setFont (font);
  52039. const int leftBorder = (height * 5) / 4;
  52040. const int rightBorder = 4;
  52041. if (image != 0)
  52042. {
  52043. g.drawImageWithin (image,
  52044. 2, 1, leftBorder - 4, height - 2,
  52045. RectanglePlacement::centred | RectanglePlacement::onlyReduceInSize, false);
  52046. }
  52047. else if (isTicked)
  52048. {
  52049. const Path tick (getTickShape (1.0f));
  52050. const float th = font.getAscent();
  52051. const float ty = halfH - th * 0.5f;
  52052. g.fillPath (tick, tick.getTransformToScaleToFit (2.0f, ty, (float) (leftBorder - 4),
  52053. th, true));
  52054. }
  52055. g.drawFittedText (text,
  52056. leftBorder, 0,
  52057. width - (leftBorder + rightBorder), height,
  52058. Justification::centredLeft, 1);
  52059. if (shortcutKeyText.isNotEmpty())
  52060. {
  52061. Font f2 (font);
  52062. f2.setHeight (f2.getHeight() * 0.75f);
  52063. f2.setHorizontalScale (0.95f);
  52064. g.setFont (f2);
  52065. g.drawText (shortcutKeyText,
  52066. leftBorder,
  52067. 0,
  52068. width - (leftBorder + rightBorder + 4),
  52069. height,
  52070. Justification::centredRight,
  52071. true);
  52072. }
  52073. if (hasSubMenu)
  52074. {
  52075. const float arrowH = 0.6f * getPopupMenuFont().getAscent();
  52076. const float x = width - height * 0.6f;
  52077. Path p;
  52078. p.addTriangle (x, halfH - arrowH * 0.5f,
  52079. x, halfH + arrowH * 0.5f,
  52080. x + arrowH * 0.6f, halfH);
  52081. g.fillPath (p);
  52082. }
  52083. }
  52084. }
  52085. int LookAndFeel::getMenuWindowFlags()
  52086. {
  52087. return ComponentPeer::windowHasDropShadow;
  52088. }
  52089. void LookAndFeel::drawMenuBarBackground (Graphics& g, int width, int height,
  52090. bool, MenuBarComponent& menuBar)
  52091. {
  52092. const Colour baseColour (createBaseColour (menuBar.findColour (PopupMenu::backgroundColourId), false, false, false));
  52093. if (menuBar.isEnabled())
  52094. {
  52095. drawShinyButtonShape (g,
  52096. -4.0f, 0.0f,
  52097. width + 8.0f, (float) height,
  52098. 0.0f,
  52099. baseColour,
  52100. 0.4f,
  52101. true, true, true, true);
  52102. }
  52103. else
  52104. {
  52105. g.fillAll (baseColour);
  52106. }
  52107. }
  52108. const Font LookAndFeel::getMenuBarFont (MenuBarComponent& menuBar, int /*itemIndex*/, const String& /*itemText*/)
  52109. {
  52110. return Font (menuBar.getHeight() * 0.7f);
  52111. }
  52112. int LookAndFeel::getMenuBarItemWidth (MenuBarComponent& menuBar, int itemIndex, const String& itemText)
  52113. {
  52114. return getMenuBarFont (menuBar, itemIndex, itemText)
  52115. .getStringWidth (itemText) + menuBar.getHeight();
  52116. }
  52117. void LookAndFeel::drawMenuBarItem (Graphics& g,
  52118. int width, int height,
  52119. int itemIndex,
  52120. const String& itemText,
  52121. bool isMouseOverItem,
  52122. bool isMenuOpen,
  52123. bool /*isMouseOverBar*/,
  52124. MenuBarComponent& menuBar)
  52125. {
  52126. if (! menuBar.isEnabled())
  52127. {
  52128. g.setColour (menuBar.findColour (PopupMenu::textColourId)
  52129. .withMultipliedAlpha (0.5f));
  52130. }
  52131. else if (isMenuOpen || isMouseOverItem)
  52132. {
  52133. g.fillAll (menuBar.findColour (PopupMenu::highlightedBackgroundColourId));
  52134. g.setColour (menuBar.findColour (PopupMenu::highlightedTextColourId));
  52135. }
  52136. else
  52137. {
  52138. g.setColour (menuBar.findColour (PopupMenu::textColourId));
  52139. }
  52140. g.setFont (getMenuBarFont (menuBar, itemIndex, itemText));
  52141. g.drawFittedText (itemText, 0, 0, width, height, Justification::centred, 1);
  52142. }
  52143. void LookAndFeel::fillTextEditorBackground (Graphics& g, int /*width*/, int /*height*/,
  52144. TextEditor& textEditor)
  52145. {
  52146. g.fillAll (textEditor.findColour (TextEditor::backgroundColourId));
  52147. }
  52148. void LookAndFeel::drawTextEditorOutline (Graphics& g, int width, int height, TextEditor& textEditor)
  52149. {
  52150. if (textEditor.isEnabled())
  52151. {
  52152. if (textEditor.hasKeyboardFocus (true) && ! textEditor.isReadOnly())
  52153. {
  52154. const int border = 2;
  52155. g.setColour (textEditor.findColour (TextEditor::focusedOutlineColourId));
  52156. g.drawRect (0, 0, width, height, border);
  52157. g.setOpacity (1.0f);
  52158. const Colour shadowColour (textEditor.findColour (TextEditor::shadowColourId).withMultipliedAlpha (0.75f));
  52159. g.drawBevel (0, 0, width, height + 2, border + 2, shadowColour, shadowColour);
  52160. }
  52161. else
  52162. {
  52163. g.setColour (textEditor.findColour (TextEditor::outlineColourId));
  52164. g.drawRect (0, 0, width, height);
  52165. g.setOpacity (1.0f);
  52166. const Colour shadowColour (textEditor.findColour (TextEditor::shadowColourId));
  52167. g.drawBevel (0, 0, width, height + 2, 3, shadowColour, shadowColour);
  52168. }
  52169. }
  52170. }
  52171. void LookAndFeel::drawComboBox (Graphics& g, int width, int height,
  52172. const bool isButtonDown,
  52173. int buttonX, int buttonY,
  52174. int buttonW, int buttonH,
  52175. ComboBox& box)
  52176. {
  52177. g.fillAll (box.findColour (ComboBox::backgroundColourId));
  52178. if (box.isEnabled() && box.hasKeyboardFocus (false))
  52179. {
  52180. g.setColour (box.findColour (TextButton::buttonColourId));
  52181. g.drawRect (0, 0, width, height, 2);
  52182. }
  52183. else
  52184. {
  52185. g.setColour (box.findColour (ComboBox::outlineColourId));
  52186. g.drawRect (0, 0, width, height);
  52187. }
  52188. const float outlineThickness = box.isEnabled() ? (isButtonDown ? 1.2f : 0.5f) : 0.3f;
  52189. const Colour baseColour (createBaseColour (box.findColour (ComboBox::buttonColourId),
  52190. box.hasKeyboardFocus (true),
  52191. false, isButtonDown)
  52192. .withMultipliedAlpha (box.isEnabled() ? 1.0f : 0.5f));
  52193. drawGlassLozenge (g,
  52194. buttonX + outlineThickness, buttonY + outlineThickness,
  52195. buttonW - outlineThickness * 2.0f, buttonH - outlineThickness * 2.0f,
  52196. baseColour, outlineThickness, -1.0f,
  52197. true, true, true, true);
  52198. if (box.isEnabled())
  52199. {
  52200. const float arrowX = 0.3f;
  52201. const float arrowH = 0.2f;
  52202. Path p;
  52203. p.addTriangle (buttonX + buttonW * 0.5f, buttonY + buttonH * (0.45f - arrowH),
  52204. buttonX + buttonW * (1.0f - arrowX), buttonY + buttonH * 0.45f,
  52205. buttonX + buttonW * arrowX, buttonY + buttonH * 0.45f);
  52206. p.addTriangle (buttonX + buttonW * 0.5f, buttonY + buttonH * (0.55f + arrowH),
  52207. buttonX + buttonW * (1.0f - arrowX), buttonY + buttonH * 0.55f,
  52208. buttonX + buttonW * arrowX, buttonY + buttonH * 0.55f);
  52209. g.setColour (box.findColour (ComboBox::arrowColourId));
  52210. g.fillPath (p);
  52211. }
  52212. }
  52213. const Font LookAndFeel::getComboBoxFont (ComboBox& box)
  52214. {
  52215. return Font (jmin (15.0f, box.getHeight() * 0.85f));
  52216. }
  52217. Label* LookAndFeel::createComboBoxTextBox (ComboBox&)
  52218. {
  52219. return new Label (String::empty, String::empty);
  52220. }
  52221. void LookAndFeel::positionComboBoxText (ComboBox& box, Label& label)
  52222. {
  52223. label.setBounds (1, 1,
  52224. box.getWidth() + 3 - box.getHeight(),
  52225. box.getHeight() - 2);
  52226. label.setFont (getComboBoxFont (box));
  52227. }
  52228. void LookAndFeel::drawLabel (Graphics& g, Label& label)
  52229. {
  52230. g.fillAll (label.findColour (Label::backgroundColourId));
  52231. if (! label.isBeingEdited())
  52232. {
  52233. const float alpha = label.isEnabled() ? 1.0f : 0.5f;
  52234. g.setColour (label.findColour (Label::textColourId).withMultipliedAlpha (alpha));
  52235. g.setFont (label.getFont());
  52236. g.drawFittedText (label.getText(),
  52237. label.getHorizontalBorderSize(),
  52238. label.getVerticalBorderSize(),
  52239. label.getWidth() - 2 * label.getHorizontalBorderSize(),
  52240. label.getHeight() - 2 * label.getVerticalBorderSize(),
  52241. label.getJustificationType(),
  52242. jmax (1, (int) (label.getHeight() / label.getFont().getHeight())),
  52243. label.getMinimumHorizontalScale());
  52244. g.setColour (label.findColour (Label::outlineColourId).withMultipliedAlpha (alpha));
  52245. g.drawRect (0, 0, label.getWidth(), label.getHeight());
  52246. }
  52247. else if (label.isEnabled())
  52248. {
  52249. g.setColour (label.findColour (Label::outlineColourId));
  52250. g.drawRect (0, 0, label.getWidth(), label.getHeight());
  52251. }
  52252. }
  52253. void LookAndFeel::drawLinearSliderBackground (Graphics& g,
  52254. int x, int y,
  52255. int width, int height,
  52256. float /*sliderPos*/,
  52257. float /*minSliderPos*/,
  52258. float /*maxSliderPos*/,
  52259. const Slider::SliderStyle /*style*/,
  52260. Slider& slider)
  52261. {
  52262. const float sliderRadius = (float) (getSliderThumbRadius (slider) - 2);
  52263. const Colour trackColour (slider.findColour (Slider::trackColourId));
  52264. const Colour gradCol1 (trackColour.overlaidWith (Colours::black.withAlpha (slider.isEnabled() ? 0.25f : 0.13f)));
  52265. const Colour gradCol2 (trackColour.overlaidWith (Colour (0x14000000)));
  52266. Path indent;
  52267. if (slider.isHorizontal())
  52268. {
  52269. const float iy = y + height * 0.5f - sliderRadius * 0.5f;
  52270. const float ih = sliderRadius;
  52271. g.setGradientFill (ColourGradient (gradCol1, 0.0f, iy,
  52272. gradCol2, 0.0f, iy + ih, false));
  52273. indent.addRoundedRectangle (x - sliderRadius * 0.5f, iy,
  52274. width + sliderRadius, ih,
  52275. 5.0f);
  52276. g.fillPath (indent);
  52277. }
  52278. else
  52279. {
  52280. const float ix = x + width * 0.5f - sliderRadius * 0.5f;
  52281. const float iw = sliderRadius;
  52282. g.setGradientFill (ColourGradient (gradCol1, ix, 0.0f,
  52283. gradCol2, ix + iw, 0.0f, false));
  52284. indent.addRoundedRectangle (ix, y - sliderRadius * 0.5f,
  52285. iw, height + sliderRadius,
  52286. 5.0f);
  52287. g.fillPath (indent);
  52288. }
  52289. g.setColour (Colour (0x4c000000));
  52290. g.strokePath (indent, PathStrokeType (0.5f));
  52291. }
  52292. void LookAndFeel::drawLinearSliderThumb (Graphics& g,
  52293. int x, int y,
  52294. int width, int height,
  52295. float sliderPos,
  52296. float minSliderPos,
  52297. float maxSliderPos,
  52298. const Slider::SliderStyle style,
  52299. Slider& slider)
  52300. {
  52301. const float sliderRadius = (float) (getSliderThumbRadius (slider) - 2);
  52302. Colour knobColour (createBaseColour (slider.findColour (Slider::thumbColourId),
  52303. slider.hasKeyboardFocus (false) && slider.isEnabled(),
  52304. slider.isMouseOverOrDragging() && slider.isEnabled(),
  52305. slider.isMouseButtonDown() && slider.isEnabled()));
  52306. const float outlineThickness = slider.isEnabled() ? 0.8f : 0.3f;
  52307. if (style == Slider::LinearHorizontal || style == Slider::LinearVertical)
  52308. {
  52309. float kx, ky;
  52310. if (style == Slider::LinearVertical)
  52311. {
  52312. kx = x + width * 0.5f;
  52313. ky = sliderPos;
  52314. }
  52315. else
  52316. {
  52317. kx = sliderPos;
  52318. ky = y + height * 0.5f;
  52319. }
  52320. drawGlassSphere (g,
  52321. kx - sliderRadius,
  52322. ky - sliderRadius,
  52323. sliderRadius * 2.0f,
  52324. knobColour, outlineThickness);
  52325. }
  52326. else
  52327. {
  52328. if (style == Slider::ThreeValueVertical)
  52329. {
  52330. drawGlassSphere (g, x + width * 0.5f - sliderRadius,
  52331. sliderPos - sliderRadius,
  52332. sliderRadius * 2.0f,
  52333. knobColour, outlineThickness);
  52334. }
  52335. else if (style == Slider::ThreeValueHorizontal)
  52336. {
  52337. drawGlassSphere (g,sliderPos - sliderRadius,
  52338. y + height * 0.5f - sliderRadius,
  52339. sliderRadius * 2.0f,
  52340. knobColour, outlineThickness);
  52341. }
  52342. if (style == Slider::TwoValueVertical || style == Slider::ThreeValueVertical)
  52343. {
  52344. const float sr = jmin (sliderRadius, width * 0.4f);
  52345. drawGlassPointer (g, jmax (0.0f, x + width * 0.5f - sliderRadius * 2.0f),
  52346. minSliderPos - sliderRadius,
  52347. sliderRadius * 2.0f, knobColour, outlineThickness, 1);
  52348. drawGlassPointer (g, jmin (x + width - sliderRadius * 2.0f, x + width * 0.5f), maxSliderPos - sr,
  52349. sliderRadius * 2.0f, knobColour, outlineThickness, 3);
  52350. }
  52351. else if (style == Slider::TwoValueHorizontal || style == Slider::ThreeValueHorizontal)
  52352. {
  52353. const float sr = jmin (sliderRadius, height * 0.4f);
  52354. drawGlassPointer (g, minSliderPos - sr,
  52355. jmax (0.0f, y + height * 0.5f - sliderRadius * 2.0f),
  52356. sliderRadius * 2.0f, knobColour, outlineThickness, 2);
  52357. drawGlassPointer (g, maxSliderPos - sliderRadius,
  52358. jmin (y + height - sliderRadius * 2.0f, y + height * 0.5f),
  52359. sliderRadius * 2.0f, knobColour, outlineThickness, 4);
  52360. }
  52361. }
  52362. }
  52363. void LookAndFeel::drawLinearSlider (Graphics& g,
  52364. int x, int y,
  52365. int width, int height,
  52366. float sliderPos,
  52367. float minSliderPos,
  52368. float maxSliderPos,
  52369. const Slider::SliderStyle style,
  52370. Slider& slider)
  52371. {
  52372. g.fillAll (slider.findColour (Slider::backgroundColourId));
  52373. if (style == Slider::LinearBar)
  52374. {
  52375. const bool isMouseOver = slider.isMouseOverOrDragging() && slider.isEnabled();
  52376. Colour baseColour (createBaseColour (slider.findColour (Slider::thumbColourId)
  52377. .withMultipliedSaturation (slider.isEnabled() ? 1.0f : 0.5f),
  52378. false,
  52379. isMouseOver,
  52380. isMouseOver || slider.isMouseButtonDown()));
  52381. drawShinyButtonShape (g,
  52382. (float) x, (float) y, sliderPos - (float) x, (float) height, 0.0f,
  52383. baseColour,
  52384. slider.isEnabled() ? 0.9f : 0.3f,
  52385. true, true, true, true);
  52386. }
  52387. else
  52388. {
  52389. drawLinearSliderBackground (g, x, y, width, height, sliderPos, minSliderPos, maxSliderPos, style, slider);
  52390. drawLinearSliderThumb (g, x, y, width, height, sliderPos, minSliderPos, maxSliderPos, style, slider);
  52391. }
  52392. }
  52393. int LookAndFeel::getSliderThumbRadius (Slider& slider)
  52394. {
  52395. return jmin (7,
  52396. slider.getHeight() / 2,
  52397. slider.getWidth() / 2) + 2;
  52398. }
  52399. void LookAndFeel::drawRotarySlider (Graphics& g,
  52400. int x, int y,
  52401. int width, int height,
  52402. float sliderPos,
  52403. const float rotaryStartAngle,
  52404. const float rotaryEndAngle,
  52405. Slider& slider)
  52406. {
  52407. const float radius = jmin (width / 2, height / 2) - 2.0f;
  52408. const float centreX = x + width * 0.5f;
  52409. const float centreY = y + height * 0.5f;
  52410. const float rx = centreX - radius;
  52411. const float ry = centreY - radius;
  52412. const float rw = radius * 2.0f;
  52413. const float angle = rotaryStartAngle + sliderPos * (rotaryEndAngle - rotaryStartAngle);
  52414. const bool isMouseOver = slider.isMouseOverOrDragging() && slider.isEnabled();
  52415. if (radius > 12.0f)
  52416. {
  52417. if (slider.isEnabled())
  52418. g.setColour (slider.findColour (Slider::rotarySliderFillColourId).withAlpha (isMouseOver ? 1.0f : 0.7f));
  52419. else
  52420. g.setColour (Colour (0x80808080));
  52421. const float thickness = 0.7f;
  52422. {
  52423. Path filledArc;
  52424. filledArc.addPieSegment (rx, ry, rw, rw,
  52425. rotaryStartAngle,
  52426. angle,
  52427. thickness);
  52428. g.fillPath (filledArc);
  52429. }
  52430. if (thickness > 0)
  52431. {
  52432. const float innerRadius = radius * 0.2f;
  52433. Path p;
  52434. p.addTriangle (-innerRadius, 0.0f,
  52435. 0.0f, -radius * thickness * 1.1f,
  52436. innerRadius, 0.0f);
  52437. p.addEllipse (-innerRadius, -innerRadius, innerRadius * 2.0f, innerRadius * 2.0f);
  52438. g.fillPath (p, AffineTransform::rotation (angle).translated (centreX, centreY));
  52439. }
  52440. if (slider.isEnabled())
  52441. g.setColour (slider.findColour (Slider::rotarySliderOutlineColourId));
  52442. else
  52443. g.setColour (Colour (0x80808080));
  52444. Path outlineArc;
  52445. outlineArc.addPieSegment (rx, ry, rw, rw, rotaryStartAngle, rotaryEndAngle, thickness);
  52446. outlineArc.closeSubPath();
  52447. g.strokePath (outlineArc, PathStrokeType (slider.isEnabled() ? (isMouseOver ? 2.0f : 1.2f) : 0.3f));
  52448. }
  52449. else
  52450. {
  52451. if (slider.isEnabled())
  52452. g.setColour (slider.findColour (Slider::rotarySliderFillColourId).withAlpha (isMouseOver ? 1.0f : 0.7f));
  52453. else
  52454. g.setColour (Colour (0x80808080));
  52455. Path p;
  52456. p.addEllipse (-0.4f * rw, -0.4f * rw, rw * 0.8f, rw * 0.8f);
  52457. PathStrokeType (rw * 0.1f).createStrokedPath (p, p);
  52458. p.addLineSegment (0.0f, 0.0f, 0.0f, -radius, rw * 0.2f);
  52459. g.fillPath (p, AffineTransform::rotation (angle).translated (centreX, centreY));
  52460. }
  52461. }
  52462. Button* LookAndFeel::createSliderButton (const bool isIncrement)
  52463. {
  52464. return new TextButton (isIncrement ? "+" : "-", String::empty);
  52465. }
  52466. class SliderLabelComp : public Label
  52467. {
  52468. public:
  52469. SliderLabelComp() : Label (String::empty, String::empty) {}
  52470. ~SliderLabelComp() {}
  52471. void mouseWheelMove (const MouseEvent&, float, float) {}
  52472. };
  52473. Label* LookAndFeel::createSliderTextBox (Slider& slider)
  52474. {
  52475. Label* const l = new SliderLabelComp();
  52476. l->setJustificationType (Justification::centred);
  52477. l->setColour (Label::textColourId, slider.findColour (Slider::textBoxTextColourId));
  52478. l->setColour (Label::backgroundColourId,
  52479. (slider.getSliderStyle() == Slider::LinearBar) ? Colours::transparentBlack
  52480. : slider.findColour (Slider::textBoxBackgroundColourId));
  52481. l->setColour (Label::outlineColourId, slider.findColour (Slider::textBoxOutlineColourId));
  52482. l->setColour (TextEditor::textColourId, slider.findColour (Slider::textBoxTextColourId));
  52483. l->setColour (TextEditor::backgroundColourId,
  52484. slider.findColour (Slider::textBoxBackgroundColourId)
  52485. .withAlpha (slider.getSliderStyle() == Slider::LinearBar ? 0.7f : 1.0f));
  52486. l->setColour (TextEditor::outlineColourId, slider.findColour (Slider::textBoxOutlineColourId));
  52487. return l;
  52488. }
  52489. ImageEffectFilter* LookAndFeel::getSliderEffect()
  52490. {
  52491. return 0;
  52492. }
  52493. static const TextLayout layoutTooltipText (const String& text) throw()
  52494. {
  52495. const float tooltipFontSize = 12.0f;
  52496. const int maxToolTipWidth = 400;
  52497. const Font f (tooltipFontSize, Font::bold);
  52498. TextLayout tl (text, f);
  52499. tl.layout (maxToolTipWidth, Justification::left, true);
  52500. return tl;
  52501. }
  52502. void LookAndFeel::getTooltipSize (const String& tipText, int& width, int& height)
  52503. {
  52504. const TextLayout tl (layoutTooltipText (tipText));
  52505. width = tl.getWidth() + 14;
  52506. height = tl.getHeight() + 6;
  52507. }
  52508. void LookAndFeel::drawTooltip (Graphics& g, const String& text, int width, int height)
  52509. {
  52510. g.fillAll (findColour (TooltipWindow::backgroundColourId));
  52511. const Colour textCol (findColour (TooltipWindow::textColourId));
  52512. #if ! JUCE_MAC // The mac windows already have a non-optional 1 pix outline, so don't double it here..
  52513. g.setColour (findColour (TooltipWindow::outlineColourId));
  52514. g.drawRect (0, 0, width, height, 1);
  52515. #endif
  52516. const TextLayout tl (layoutTooltipText (text));
  52517. g.setColour (findColour (TooltipWindow::textColourId));
  52518. tl.drawWithin (g, 0, 0, width, height, Justification::centred);
  52519. }
  52520. Button* LookAndFeel::createFilenameComponentBrowseButton (const String& text)
  52521. {
  52522. return new TextButton (text, TRANS("click to browse for a different file"));
  52523. }
  52524. void LookAndFeel::layoutFilenameComponent (FilenameComponent& filenameComp,
  52525. ComboBox* filenameBox,
  52526. Button* browseButton)
  52527. {
  52528. browseButton->setSize (80, filenameComp.getHeight());
  52529. TextButton* const tb = dynamic_cast <TextButton*> (browseButton);
  52530. if (tb != 0)
  52531. tb->changeWidthToFitText();
  52532. browseButton->setTopRightPosition (filenameComp.getWidth(), 0);
  52533. filenameBox->setBounds (0, 0, browseButton->getX(), filenameComp.getHeight());
  52534. }
  52535. void LookAndFeel::drawImageButton (Graphics& g, Image* image,
  52536. int imageX, int imageY, int imageW, int imageH,
  52537. const Colour& overlayColour,
  52538. float imageOpacity,
  52539. ImageButton& button)
  52540. {
  52541. if (! button.isEnabled())
  52542. imageOpacity *= 0.3f;
  52543. if (! overlayColour.isOpaque())
  52544. {
  52545. g.setOpacity (imageOpacity);
  52546. g.drawImage (image, imageX, imageY, imageW, imageH,
  52547. 0, 0, image->getWidth(), image->getHeight(), false);
  52548. }
  52549. if (! overlayColour.isTransparent())
  52550. {
  52551. g.setColour (overlayColour);
  52552. g.drawImage (image, imageX, imageY, imageW, imageH,
  52553. 0, 0, image->getWidth(), image->getHeight(), true);
  52554. }
  52555. }
  52556. void LookAndFeel::drawCornerResizer (Graphics& g,
  52557. int w, int h,
  52558. bool /*isMouseOver*/,
  52559. bool /*isMouseDragging*/)
  52560. {
  52561. const float lineThickness = jmin (w, h) * 0.075f;
  52562. for (float i = 0.0f; i < 1.0f; i += 0.3f)
  52563. {
  52564. g.setColour (Colours::lightgrey);
  52565. g.drawLine (w * i,
  52566. h + 1.0f,
  52567. w + 1.0f,
  52568. h * i,
  52569. lineThickness);
  52570. g.setColour (Colours::darkgrey);
  52571. g.drawLine (w * i + lineThickness,
  52572. h + 1.0f,
  52573. w + 1.0f,
  52574. h * i + lineThickness,
  52575. lineThickness);
  52576. }
  52577. }
  52578. void LookAndFeel::drawResizableFrame (Graphics&, int /*w*/, int /*h*/,
  52579. const BorderSize& /*borders*/)
  52580. {
  52581. }
  52582. void LookAndFeel::fillResizableWindowBackground (Graphics& g, int /*w*/, int /*h*/,
  52583. const BorderSize& /*border*/, ResizableWindow& window)
  52584. {
  52585. g.fillAll (window.getBackgroundColour());
  52586. }
  52587. void LookAndFeel::drawResizableWindowBorder (Graphics& g, int w, int h,
  52588. const BorderSize& border, ResizableWindow&)
  52589. {
  52590. g.setColour (Colour (0x80000000));
  52591. g.drawRect (0, 0, w, h);
  52592. g.setColour (Colour (0x19000000));
  52593. g.drawRect (border.getLeft() - 1,
  52594. border.getTop() - 1,
  52595. w + 2 - border.getLeftAndRight(),
  52596. h + 2 - border.getTopAndBottom());
  52597. }
  52598. void LookAndFeel::drawDocumentWindowTitleBar (DocumentWindow& window,
  52599. Graphics& g, int w, int h,
  52600. int titleSpaceX, int titleSpaceW,
  52601. const Image* icon,
  52602. bool drawTitleTextOnLeft)
  52603. {
  52604. const bool isActive = window.isActiveWindow();
  52605. g.setGradientFill (ColourGradient (window.getBackgroundColour(),
  52606. 0.0f, 0.0f,
  52607. window.getBackgroundColour().contrasting (isActive ? 0.15f : 0.05f),
  52608. 0.0f, (float) h, false));
  52609. g.fillAll();
  52610. Font font (h * 0.65f, Font::bold);
  52611. g.setFont (font);
  52612. int textW = font.getStringWidth (window.getName());
  52613. int iconW = 0;
  52614. int iconH = 0;
  52615. if (icon != 0)
  52616. {
  52617. iconH = (int) font.getHeight();
  52618. iconW = icon->getWidth() * iconH / icon->getHeight() + 4;
  52619. }
  52620. textW = jmin (titleSpaceW, textW + iconW);
  52621. int textX = drawTitleTextOnLeft ? titleSpaceX
  52622. : jmax (titleSpaceX, (w - textW) / 2);
  52623. if (textX + textW > titleSpaceX + titleSpaceW)
  52624. textX = titleSpaceX + titleSpaceW - textW;
  52625. if (icon != 0)
  52626. {
  52627. g.setOpacity (isActive ? 1.0f : 0.6f);
  52628. g.drawImageWithin (icon, textX, (h - iconH) / 2, iconW, iconH,
  52629. RectanglePlacement::centred, false);
  52630. textX += iconW;
  52631. textW -= iconW;
  52632. }
  52633. if (window.isColourSpecified (DocumentWindow::textColourId) || isColourSpecified (DocumentWindow::textColourId))
  52634. g.setColour (findColour (DocumentWindow::textColourId));
  52635. else
  52636. g.setColour (window.getBackgroundColour().contrasting (isActive ? 0.7f : 0.4f));
  52637. g.drawText (window.getName(), textX, 0, textW, h, Justification::centredLeft, true);
  52638. }
  52639. class GlassWindowButton : public Button
  52640. {
  52641. public:
  52642. GlassWindowButton (const String& name, const Colour& col,
  52643. const Path& normalShape_,
  52644. const Path& toggledShape_) throw()
  52645. : Button (name),
  52646. colour (col),
  52647. normalShape (normalShape_),
  52648. toggledShape (toggledShape_)
  52649. {
  52650. }
  52651. ~GlassWindowButton()
  52652. {
  52653. }
  52654. void paintButton (Graphics& g, bool isMouseOverButton, bool isButtonDown)
  52655. {
  52656. float alpha = isMouseOverButton ? (isButtonDown ? 1.0f : 0.8f) : 0.55f;
  52657. if (! isEnabled())
  52658. alpha *= 0.5f;
  52659. float x = 0, y = 0, diam;
  52660. if (getWidth() < getHeight())
  52661. {
  52662. diam = (float) getWidth();
  52663. y = (getHeight() - getWidth()) * 0.5f;
  52664. }
  52665. else
  52666. {
  52667. diam = (float) getHeight();
  52668. y = (getWidth() - getHeight()) * 0.5f;
  52669. }
  52670. x += diam * 0.05f;
  52671. y += diam * 0.05f;
  52672. diam *= 0.9f;
  52673. g.setGradientFill (ColourGradient (Colour::greyLevel (0.9f).withAlpha (alpha), 0, y + diam,
  52674. Colour::greyLevel (0.6f).withAlpha (alpha), 0, y, false));
  52675. g.fillEllipse (x, y, diam, diam);
  52676. x += 2.0f;
  52677. y += 2.0f;
  52678. diam -= 4.0f;
  52679. LookAndFeel::drawGlassSphere (g, x, y, diam, colour.withAlpha (alpha), 1.0f);
  52680. Path& p = getToggleState() ? toggledShape : normalShape;
  52681. const AffineTransform t (p.getTransformToScaleToFit (x + diam * 0.3f, y + diam * 0.3f,
  52682. diam * 0.4f, diam * 0.4f, true));
  52683. g.setColour (Colours::black.withAlpha (alpha * 0.6f));
  52684. g.fillPath (p, t);
  52685. }
  52686. juce_UseDebuggingNewOperator
  52687. private:
  52688. Colour colour;
  52689. Path normalShape, toggledShape;
  52690. GlassWindowButton (const GlassWindowButton&);
  52691. GlassWindowButton& operator= (const GlassWindowButton&);
  52692. };
  52693. Button* LookAndFeel::createDocumentWindowButton (int buttonType)
  52694. {
  52695. Path shape;
  52696. const float crossThickness = 0.25f;
  52697. if (buttonType == DocumentWindow::closeButton)
  52698. {
  52699. shape.addLineSegment (0.0f, 0.0f, 1.0f, 1.0f, crossThickness * 1.4f);
  52700. shape.addLineSegment (1.0f, 0.0f, 0.0f, 1.0f, crossThickness * 1.4f);
  52701. return new GlassWindowButton ("close", Colour (0xffdd1100), shape, shape);
  52702. }
  52703. else if (buttonType == DocumentWindow::minimiseButton)
  52704. {
  52705. shape.addLineSegment (0.0f, 0.5f, 1.0f, 0.5f, crossThickness);
  52706. return new GlassWindowButton ("minimise", Colour (0xffaa8811), shape, shape);
  52707. }
  52708. else if (buttonType == DocumentWindow::maximiseButton)
  52709. {
  52710. shape.addLineSegment (0.5f, 0.0f, 0.5f, 1.0f, crossThickness);
  52711. shape.addLineSegment (0.0f, 0.5f, 1.0f, 0.5f, crossThickness);
  52712. Path fullscreenShape;
  52713. fullscreenShape.startNewSubPath (45.0f, 100.0f);
  52714. fullscreenShape.lineTo (0.0f, 100.0f);
  52715. fullscreenShape.lineTo (0.0f, 0.0f);
  52716. fullscreenShape.lineTo (100.0f, 0.0f);
  52717. fullscreenShape.lineTo (100.0f, 45.0f);
  52718. fullscreenShape.addRectangle (45.0f, 45.0f, 100.0f, 100.0f);
  52719. PathStrokeType (30.0f).createStrokedPath (fullscreenShape, fullscreenShape);
  52720. return new GlassWindowButton ("maximise", Colour (0xff119911), shape, fullscreenShape);
  52721. }
  52722. jassertfalse
  52723. return 0;
  52724. }
  52725. void LookAndFeel::positionDocumentWindowButtons (DocumentWindow&,
  52726. int titleBarX,
  52727. int titleBarY,
  52728. int titleBarW,
  52729. int titleBarH,
  52730. Button* minimiseButton,
  52731. Button* maximiseButton,
  52732. Button* closeButton,
  52733. bool positionTitleBarButtonsOnLeft)
  52734. {
  52735. const int buttonW = titleBarH - titleBarH / 8;
  52736. int x = positionTitleBarButtonsOnLeft ? titleBarX + 4
  52737. : titleBarX + titleBarW - buttonW - buttonW / 4;
  52738. if (closeButton != 0)
  52739. {
  52740. closeButton->setBounds (x, titleBarY, buttonW, titleBarH);
  52741. x += positionTitleBarButtonsOnLeft ? buttonW : -(buttonW + buttonW / 4);
  52742. }
  52743. if (positionTitleBarButtonsOnLeft)
  52744. swapVariables (minimiseButton, maximiseButton);
  52745. if (maximiseButton != 0)
  52746. {
  52747. maximiseButton->setBounds (x, titleBarY, buttonW, titleBarH);
  52748. x += positionTitleBarButtonsOnLeft ? buttonW : -buttonW;
  52749. }
  52750. if (minimiseButton != 0)
  52751. minimiseButton->setBounds (x, titleBarY, buttonW, titleBarH);
  52752. }
  52753. int LookAndFeel::getDefaultMenuBarHeight()
  52754. {
  52755. return 24;
  52756. }
  52757. DropShadower* LookAndFeel::createDropShadowerForComponent (Component*)
  52758. {
  52759. return new DropShadower (0.4f, 1, 5, 10);
  52760. }
  52761. void LookAndFeel::drawStretchableLayoutResizerBar (Graphics& g,
  52762. int w, int h,
  52763. bool /*isVerticalBar*/,
  52764. bool isMouseOver,
  52765. bool isMouseDragging)
  52766. {
  52767. float alpha = 0.5f;
  52768. if (isMouseOver || isMouseDragging)
  52769. {
  52770. g.fillAll (Colour (0x190000ff));
  52771. alpha = 1.0f;
  52772. }
  52773. const float cx = w * 0.5f;
  52774. const float cy = h * 0.5f;
  52775. const float cr = jmin (w, h) * 0.4f;
  52776. g.setGradientFill (ColourGradient (Colours::white.withAlpha (alpha), cx + cr * 0.1f, cy + cr,
  52777. Colours::black.withAlpha (alpha), cx, cy - cr * 4.0f,
  52778. true));
  52779. g.fillEllipse (cx - cr, cy - cr, cr * 2.0f, cr * 2.0f);
  52780. }
  52781. void LookAndFeel::drawGroupComponentOutline (Graphics& g, int width, int height,
  52782. const String& text,
  52783. const Justification& position,
  52784. GroupComponent& group)
  52785. {
  52786. const float textH = 15.0f;
  52787. const float indent = 3.0f;
  52788. const float textEdgeGap = 4.0f;
  52789. float cs = 5.0f;
  52790. Font f (textH);
  52791. Path p;
  52792. float x = indent;
  52793. float y = f.getAscent() - 3.0f;
  52794. float w = jmax (0.0f, width - x * 2.0f);
  52795. float h = jmax (0.0f, height - y - indent);
  52796. cs = jmin (cs, w * 0.5f, h * 0.5f);
  52797. const float cs2 = 2.0f * cs;
  52798. float textW = text.isEmpty() ? 0 : jlimit (0.0f, jmax (0.0f, w - cs2 - textEdgeGap * 2), f.getStringWidth (text) + textEdgeGap * 2.0f);
  52799. float textX = cs + textEdgeGap;
  52800. if (position.testFlags (Justification::horizontallyCentred))
  52801. textX = cs + (w - cs2 - textW) * 0.5f;
  52802. else if (position.testFlags (Justification::right))
  52803. textX = w - cs - textW - textEdgeGap;
  52804. p.startNewSubPath (x + textX + textW, y);
  52805. p.lineTo (x + w - cs, y);
  52806. p.addArc (x + w - cs2, y, cs2, cs2, 0, float_Pi * 0.5f);
  52807. p.lineTo (x + w, y + h - cs);
  52808. p.addArc (x + w - cs2, y + h - cs2, cs2, cs2, float_Pi * 0.5f, float_Pi);
  52809. p.lineTo (x + cs, y + h);
  52810. p.addArc (x, y + h - cs2, cs2, cs2, float_Pi, float_Pi * 1.5f);
  52811. p.lineTo (x, y + cs);
  52812. p.addArc (x, y, cs2, cs2, float_Pi * 1.5f, float_Pi * 2.0f);
  52813. p.lineTo (x + textX, y);
  52814. const float alpha = group.isEnabled() ? 1.0f : 0.5f;
  52815. g.setColour (group.findColour (GroupComponent::outlineColourId)
  52816. .withMultipliedAlpha (alpha));
  52817. g.strokePath (p, PathStrokeType (2.0f));
  52818. g.setColour (group.findColour (GroupComponent::textColourId)
  52819. .withMultipliedAlpha (alpha));
  52820. g.setFont (f);
  52821. g.drawText (text,
  52822. roundToInt (x + textX), 0,
  52823. roundToInt (textW),
  52824. roundToInt (textH),
  52825. Justification::centred, true);
  52826. }
  52827. int LookAndFeel::getTabButtonOverlap (int tabDepth)
  52828. {
  52829. return 1 + tabDepth / 3;
  52830. }
  52831. int LookAndFeel::getTabButtonSpaceAroundImage()
  52832. {
  52833. return 4;
  52834. }
  52835. void LookAndFeel::createTabButtonShape (Path& p,
  52836. int width, int height,
  52837. int /*tabIndex*/,
  52838. const String& /*text*/,
  52839. Button& /*button*/,
  52840. TabbedButtonBar::Orientation orientation,
  52841. const bool /*isMouseOver*/,
  52842. const bool /*isMouseDown*/,
  52843. const bool /*isFrontTab*/)
  52844. {
  52845. const float w = (float) width;
  52846. const float h = (float) height;
  52847. float length = w;
  52848. float depth = h;
  52849. if (orientation == TabbedButtonBar::TabsAtLeft
  52850. || orientation == TabbedButtonBar::TabsAtRight)
  52851. {
  52852. swapVariables (length, depth);
  52853. }
  52854. const float indent = (float) getTabButtonOverlap ((int) depth);
  52855. const float overhang = 4.0f;
  52856. if (orientation == TabbedButtonBar::TabsAtLeft)
  52857. {
  52858. p.startNewSubPath (w, 0.0f);
  52859. p.lineTo (0.0f, indent);
  52860. p.lineTo (0.0f, h - indent);
  52861. p.lineTo (w, h);
  52862. p.lineTo (w + overhang, h + overhang);
  52863. p.lineTo (w + overhang, -overhang);
  52864. }
  52865. else if (orientation == TabbedButtonBar::TabsAtRight)
  52866. {
  52867. p.startNewSubPath (0.0f, 0.0f);
  52868. p.lineTo (w, indent);
  52869. p.lineTo (w, h - indent);
  52870. p.lineTo (0.0f, h);
  52871. p.lineTo (-overhang, h + overhang);
  52872. p.lineTo (-overhang, -overhang);
  52873. }
  52874. else if (orientation == TabbedButtonBar::TabsAtBottom)
  52875. {
  52876. p.startNewSubPath (0.0f, 0.0f);
  52877. p.lineTo (indent, h);
  52878. p.lineTo (w - indent, h);
  52879. p.lineTo (w, 0.0f);
  52880. p.lineTo (w + overhang, -overhang);
  52881. p.lineTo (-overhang, -overhang);
  52882. }
  52883. else
  52884. {
  52885. p.startNewSubPath (0.0f, h);
  52886. p.lineTo (indent, 0.0f);
  52887. p.lineTo (w - indent, 0.0f);
  52888. p.lineTo (w, h);
  52889. p.lineTo (w + overhang, h + overhang);
  52890. p.lineTo (-overhang, h + overhang);
  52891. }
  52892. p.closeSubPath();
  52893. p = p.createPathWithRoundedCorners (3.0f);
  52894. }
  52895. void LookAndFeel::fillTabButtonShape (Graphics& g,
  52896. const Path& path,
  52897. const Colour& preferredColour,
  52898. int /*tabIndex*/,
  52899. const String& /*text*/,
  52900. Button& button,
  52901. TabbedButtonBar::Orientation /*orientation*/,
  52902. const bool /*isMouseOver*/,
  52903. const bool /*isMouseDown*/,
  52904. const bool isFrontTab)
  52905. {
  52906. g.setColour (isFrontTab ? preferredColour
  52907. : preferredColour.withMultipliedAlpha (0.9f));
  52908. g.fillPath (path);
  52909. g.setColour (button.findColour (isFrontTab ? TabbedButtonBar::frontOutlineColourId
  52910. : TabbedButtonBar::tabOutlineColourId, false)
  52911. .withMultipliedAlpha (button.isEnabled() ? 1.0f : 0.5f));
  52912. g.strokePath (path, PathStrokeType (isFrontTab ? 1.0f : 0.5f));
  52913. }
  52914. void LookAndFeel::drawTabButtonText (Graphics& g,
  52915. int x, int y, int w, int h,
  52916. const Colour& preferredBackgroundColour,
  52917. int /*tabIndex*/,
  52918. const String& text,
  52919. Button& button,
  52920. TabbedButtonBar::Orientation orientation,
  52921. const bool isMouseOver,
  52922. const bool isMouseDown,
  52923. const bool isFrontTab)
  52924. {
  52925. int length = w;
  52926. int depth = h;
  52927. if (orientation == TabbedButtonBar::TabsAtLeft
  52928. || orientation == TabbedButtonBar::TabsAtRight)
  52929. {
  52930. swapVariables (length, depth);
  52931. }
  52932. Font font (depth * 0.6f);
  52933. font.setUnderline (button.hasKeyboardFocus (false));
  52934. GlyphArrangement textLayout;
  52935. textLayout.addFittedText (font, text.trim(),
  52936. 0.0f, 0.0f, (float) length, (float) depth,
  52937. Justification::centred,
  52938. jmax (1, depth / 12));
  52939. AffineTransform transform;
  52940. if (orientation == TabbedButtonBar::TabsAtLeft)
  52941. {
  52942. transform = transform.rotated (float_Pi * -0.5f)
  52943. .translated ((float) x, (float) (y + h));
  52944. }
  52945. else if (orientation == TabbedButtonBar::TabsAtRight)
  52946. {
  52947. transform = transform.rotated (float_Pi * 0.5f)
  52948. .translated ((float) (x + w), (float) y);
  52949. }
  52950. else
  52951. {
  52952. transform = transform.translated ((float) x, (float) y);
  52953. }
  52954. if (isFrontTab && (button.isColourSpecified (TabbedButtonBar::frontTextColourId) || isColourSpecified (TabbedButtonBar::frontTextColourId)))
  52955. g.setColour (findColour (TabbedButtonBar::frontTextColourId));
  52956. else if (button.isColourSpecified (TabbedButtonBar::tabTextColourId) || isColourSpecified (TabbedButtonBar::tabTextColourId))
  52957. g.setColour (findColour (TabbedButtonBar::tabTextColourId));
  52958. else
  52959. g.setColour (preferredBackgroundColour.contrasting());
  52960. if (! (isMouseOver || isMouseDown))
  52961. g.setOpacity (0.8f);
  52962. if (! button.isEnabled())
  52963. g.setOpacity (0.3f);
  52964. textLayout.draw (g, transform);
  52965. }
  52966. int LookAndFeel::getTabButtonBestWidth (int /*tabIndex*/,
  52967. const String& text,
  52968. int tabDepth,
  52969. Button&)
  52970. {
  52971. Font f (tabDepth * 0.6f);
  52972. return f.getStringWidth (text.trim()) + getTabButtonOverlap (tabDepth) * 2;
  52973. }
  52974. void LookAndFeel::drawTabButton (Graphics& g,
  52975. int w, int h,
  52976. const Colour& preferredColour,
  52977. int tabIndex,
  52978. const String& text,
  52979. Button& button,
  52980. TabbedButtonBar::Orientation orientation,
  52981. const bool isMouseOver,
  52982. const bool isMouseDown,
  52983. const bool isFrontTab)
  52984. {
  52985. int length = w;
  52986. int depth = h;
  52987. if (orientation == TabbedButtonBar::TabsAtLeft
  52988. || orientation == TabbedButtonBar::TabsAtRight)
  52989. {
  52990. swapVariables (length, depth);
  52991. }
  52992. Path tabShape;
  52993. createTabButtonShape (tabShape, w, h,
  52994. tabIndex, text, button, orientation,
  52995. isMouseOver, isMouseDown, isFrontTab);
  52996. fillTabButtonShape (g, tabShape, preferredColour,
  52997. tabIndex, text, button, orientation,
  52998. isMouseOver, isMouseDown, isFrontTab);
  52999. const int indent = getTabButtonOverlap (depth);
  53000. int x = 0, y = 0;
  53001. if (orientation == TabbedButtonBar::TabsAtLeft
  53002. || orientation == TabbedButtonBar::TabsAtRight)
  53003. {
  53004. y += indent;
  53005. h -= indent * 2;
  53006. }
  53007. else
  53008. {
  53009. x += indent;
  53010. w -= indent * 2;
  53011. }
  53012. drawTabButtonText (g, x, y, w, h, preferredColour,
  53013. tabIndex, text, button, orientation,
  53014. isMouseOver, isMouseDown, isFrontTab);
  53015. }
  53016. void LookAndFeel::drawTabAreaBehindFrontButton (Graphics& g,
  53017. int w, int h,
  53018. TabbedButtonBar& tabBar,
  53019. TabbedButtonBar::Orientation orientation)
  53020. {
  53021. const float shadowSize = 0.2f;
  53022. float x1 = 0.0f, y1 = 0.0f, x2 = 0.0f, y2 = 0.0f;
  53023. Rectangle<int> shadowRect;
  53024. if (orientation == TabbedButtonBar::TabsAtLeft)
  53025. {
  53026. x1 = (float) w;
  53027. x2 = w * (1.0f - shadowSize);
  53028. shadowRect.setBounds ((int) x2, 0, w - (int) x2, h);
  53029. }
  53030. else if (orientation == TabbedButtonBar::TabsAtRight)
  53031. {
  53032. x2 = w * shadowSize;
  53033. shadowRect.setBounds (0, 0, (int) x2, h);
  53034. }
  53035. else if (orientation == TabbedButtonBar::TabsAtBottom)
  53036. {
  53037. y2 = h * shadowSize;
  53038. shadowRect.setBounds (0, 0, w, (int) y2);
  53039. }
  53040. else
  53041. {
  53042. y1 = (float) h;
  53043. y2 = h * (1.0f - shadowSize);
  53044. shadowRect.setBounds (0, (int) y2, w, h - (int) y2);
  53045. }
  53046. g.setGradientFill (ColourGradient (Colours::black.withAlpha (tabBar.isEnabled() ? 0.3f : 0.15f), x1, y1,
  53047. Colours::transparentBlack, x2, y2, false));
  53048. shadowRect.expand (2, 2);
  53049. g.fillRect (shadowRect);
  53050. g.setColour (Colour (0x80000000));
  53051. if (orientation == TabbedButtonBar::TabsAtLeft)
  53052. {
  53053. g.fillRect (w - 1, 0, 1, h);
  53054. }
  53055. else if (orientation == TabbedButtonBar::TabsAtRight)
  53056. {
  53057. g.fillRect (0, 0, 1, h);
  53058. }
  53059. else if (orientation == TabbedButtonBar::TabsAtBottom)
  53060. {
  53061. g.fillRect (0, 0, w, 1);
  53062. }
  53063. else
  53064. {
  53065. g.fillRect (0, h - 1, w, 1);
  53066. }
  53067. }
  53068. Button* LookAndFeel::createTabBarExtrasButton()
  53069. {
  53070. const float thickness = 7.0f;
  53071. const float indent = 22.0f;
  53072. Path p;
  53073. p.addEllipse (-10.0f, -10.0f, 120.0f, 120.0f);
  53074. DrawablePath ellipse;
  53075. ellipse.setPath (p);
  53076. ellipse.setFill (Colour (0x99ffffff));
  53077. p.clear();
  53078. p.addEllipse (0.0f, 0.0f, 100.0f, 100.0f);
  53079. p.addRectangle (indent, 50.0f - thickness, 100.0f - indent * 2.0f, thickness * 2.0f);
  53080. p.addRectangle (50.0f - thickness, indent, thickness * 2.0f, 50.0f - indent - thickness);
  53081. p.addRectangle (50.0f - thickness, 50.0f + thickness, thickness * 2.0f, 50.0f - indent - thickness);
  53082. p.setUsingNonZeroWinding (false);
  53083. DrawablePath dp;
  53084. dp.setPath (p);
  53085. dp.setFill (Colour (0x59000000));
  53086. DrawableComposite normalImage;
  53087. normalImage.insertDrawable (ellipse);
  53088. normalImage.insertDrawable (dp);
  53089. dp.setFill (Colour (0xcc000000));
  53090. DrawableComposite overImage;
  53091. overImage.insertDrawable (ellipse);
  53092. overImage.insertDrawable (dp);
  53093. DrawableButton* db = new DrawableButton ("tabs", DrawableButton::ImageFitted);
  53094. db->setImages (&normalImage, &overImage, 0);
  53095. return db;
  53096. }
  53097. void LookAndFeel::drawTableHeaderBackground (Graphics& g, TableHeaderComponent& header)
  53098. {
  53099. g.fillAll (Colours::white);
  53100. const int w = header.getWidth();
  53101. const int h = header.getHeight();
  53102. g.setGradientFill (ColourGradient (Colour (0xffe8ebf9), 0.0f, h * 0.5f,
  53103. Colour (0xfff6f8f9), 0.0f, h - 1.0f,
  53104. false));
  53105. g.fillRect (0, h / 2, w, h);
  53106. g.setColour (Colour (0x33000000));
  53107. g.fillRect (0, h - 1, w, 1);
  53108. for (int i = header.getNumColumns (true); --i >= 0;)
  53109. g.fillRect (header.getColumnPosition (i).getRight() - 1, 0, 1, h - 1);
  53110. }
  53111. void LookAndFeel::drawTableHeaderColumn (Graphics& g, const String& columnName, int /*columnId*/,
  53112. int width, int height,
  53113. bool isMouseOver, bool isMouseDown,
  53114. int columnFlags)
  53115. {
  53116. if (isMouseDown)
  53117. g.fillAll (Colour (0x8899aadd));
  53118. else if (isMouseOver)
  53119. g.fillAll (Colour (0x5599aadd));
  53120. int rightOfText = width - 4;
  53121. if ((columnFlags & (TableHeaderComponent::sortedForwards | TableHeaderComponent::sortedBackwards)) != 0)
  53122. {
  53123. const float top = height * ((columnFlags & TableHeaderComponent::sortedForwards) != 0 ? 0.35f : (1.0f - 0.35f));
  53124. const float bottom = height - top;
  53125. const float w = height * 0.5f;
  53126. const float x = rightOfText - (w * 1.25f);
  53127. rightOfText = (int) x;
  53128. Path sortArrow;
  53129. sortArrow.addTriangle (x, bottom, x + w * 0.5f, top, x + w, bottom);
  53130. g.setColour (Colour (0x99000000));
  53131. g.fillPath (sortArrow);
  53132. }
  53133. g.setColour (Colours::black);
  53134. g.setFont (height * 0.5f, Font::bold);
  53135. const int textX = 4;
  53136. g.drawFittedText (columnName, textX, 0, rightOfText - textX, height, Justification::centredLeft, 1);
  53137. }
  53138. void LookAndFeel::paintToolbarBackground (Graphics& g, int w, int h, Toolbar& toolbar)
  53139. {
  53140. const Colour background (toolbar.findColour (Toolbar::backgroundColourId));
  53141. g.setGradientFill (ColourGradient (background, 0.0f, 0.0f,
  53142. background.darker (0.1f),
  53143. toolbar.isVertical() ? w - 1.0f : 0.0f,
  53144. toolbar.isVertical() ? 0.0f : h - 1.0f,
  53145. false));
  53146. g.fillAll();
  53147. }
  53148. Button* LookAndFeel::createToolbarMissingItemsButton (Toolbar& /*toolbar*/)
  53149. {
  53150. return createTabBarExtrasButton();
  53151. }
  53152. void LookAndFeel::paintToolbarButtonBackground (Graphics& g, int /*width*/, int /*height*/,
  53153. bool isMouseOver, bool isMouseDown,
  53154. ToolbarItemComponent& component)
  53155. {
  53156. if (isMouseDown)
  53157. g.fillAll (component.findColour (Toolbar::buttonMouseDownBackgroundColourId, true));
  53158. else if (isMouseOver)
  53159. g.fillAll (component.findColour (Toolbar::buttonMouseOverBackgroundColourId, true));
  53160. }
  53161. void LookAndFeel::paintToolbarButtonLabel (Graphics& g, int x, int y, int width, int height,
  53162. const String& text, ToolbarItemComponent& component)
  53163. {
  53164. g.setColour (component.findColour (Toolbar::labelTextColourId, true)
  53165. .withAlpha (component.isEnabled() ? 1.0f : 0.25f));
  53166. const float fontHeight = jmin (14.0f, height * 0.85f);
  53167. g.setFont (fontHeight);
  53168. g.drawFittedText (text,
  53169. x, y, width, height,
  53170. Justification::centred,
  53171. jmax (1, height / (int) fontHeight));
  53172. }
  53173. void LookAndFeel::drawPropertyPanelSectionHeader (Graphics& g, const String& name,
  53174. bool isOpen, int width, int height)
  53175. {
  53176. const int buttonSize = (height * 3) / 4;
  53177. const int buttonIndent = (height - buttonSize) / 2;
  53178. drawTreeviewPlusMinusBox (g, buttonIndent, buttonIndent, buttonSize, buttonSize, ! isOpen, false);
  53179. const int textX = buttonIndent * 2 + buttonSize + 2;
  53180. g.setColour (Colours::black);
  53181. g.setFont (height * 0.7f, Font::bold);
  53182. g.drawText (name, textX, 0, width - textX - 4, height, Justification::centredLeft, true);
  53183. }
  53184. void LookAndFeel::drawPropertyComponentBackground (Graphics& g, int width, int height,
  53185. PropertyComponent&)
  53186. {
  53187. g.setColour (Colour (0x66ffffff));
  53188. g.fillRect (0, 0, width, height - 1);
  53189. }
  53190. void LookAndFeel::drawPropertyComponentLabel (Graphics& g, int, int height,
  53191. PropertyComponent& component)
  53192. {
  53193. g.setColour (Colours::black);
  53194. if (! component.isEnabled())
  53195. g.setOpacity (0.6f);
  53196. g.setFont (jmin (height, 24) * 0.65f);
  53197. const Rectangle<int> r (getPropertyComponentContentPosition (component));
  53198. g.drawFittedText (component.getName(),
  53199. 3, r.getY(), r.getX() - 5, r.getHeight(),
  53200. Justification::centredLeft, 2);
  53201. }
  53202. const Rectangle<int> LookAndFeel::getPropertyComponentContentPosition (PropertyComponent& component)
  53203. {
  53204. return Rectangle<int> (component.getWidth() / 3, 1,
  53205. component.getWidth() - component.getWidth() / 3 - 1, component.getHeight() - 3);
  53206. }
  53207. void LookAndFeel::createFileChooserHeaderText (const String& title,
  53208. const String& instructions,
  53209. GlyphArrangement& text,
  53210. int width)
  53211. {
  53212. text.clear();
  53213. text.addJustifiedText (Font (17.0f, Font::bold), title,
  53214. 8.0f, 22.0f, width - 16.0f,
  53215. Justification::centred);
  53216. text.addJustifiedText (Font (14.0f), instructions,
  53217. 8.0f, 24.0f + 16.0f, width - 16.0f,
  53218. Justification::centred);
  53219. }
  53220. void LookAndFeel::drawFileBrowserRow (Graphics& g, int width, int height,
  53221. const String& filename, Image* icon,
  53222. const String& fileSizeDescription,
  53223. const String& fileTimeDescription,
  53224. const bool isDirectory,
  53225. const bool isItemSelected,
  53226. const int /*itemIndex*/)
  53227. {
  53228. if (isItemSelected)
  53229. g.fillAll (findColour (DirectoryContentsDisplayComponent::highlightColourId));
  53230. g.setColour (findColour (DirectoryContentsDisplayComponent::textColourId));
  53231. g.setFont (height * 0.7f);
  53232. Image* im = icon;
  53233. Image* toRelease = 0;
  53234. if (im == 0)
  53235. {
  53236. toRelease = im = (isDirectory ? getDefaultFolderImage()
  53237. : getDefaultDocumentFileImage());
  53238. }
  53239. const int x = 32;
  53240. if (im != 0)
  53241. {
  53242. g.drawImageWithin (im, 2, 2, x - 4, height - 4,
  53243. RectanglePlacement::centred | RectanglePlacement::onlyReduceInSize,
  53244. false);
  53245. ImageCache::release (toRelease);
  53246. }
  53247. if (width > 450 && ! isDirectory)
  53248. {
  53249. const int sizeX = roundToInt (width * 0.7f);
  53250. const int dateX = roundToInt (width * 0.8f);
  53251. g.drawFittedText (filename,
  53252. x, 0, sizeX - x, height,
  53253. Justification::centredLeft, 1);
  53254. g.setFont (height * 0.5f);
  53255. g.setColour (Colours::darkgrey);
  53256. if (! isDirectory)
  53257. {
  53258. g.drawFittedText (fileSizeDescription,
  53259. sizeX, 0, dateX - sizeX - 8, height,
  53260. Justification::centredRight, 1);
  53261. g.drawFittedText (fileTimeDescription,
  53262. dateX, 0, width - 8 - dateX, height,
  53263. Justification::centredRight, 1);
  53264. }
  53265. }
  53266. else
  53267. {
  53268. g.drawFittedText (filename,
  53269. x, 0, width - x, height,
  53270. Justification::centredLeft, 1);
  53271. }
  53272. }
  53273. Button* LookAndFeel::createFileBrowserGoUpButton()
  53274. {
  53275. DrawableButton* goUpButton = new DrawableButton ("up", DrawableButton::ImageOnButtonBackground);
  53276. Path arrowPath;
  53277. arrowPath.addArrow (50.0f, 100.0f, 50.0f, 0.0f, 40.0f, 100.0f, 50.0f);
  53278. DrawablePath arrowImage;
  53279. arrowImage.setFill (Colours::black.withAlpha (0.4f));
  53280. arrowImage.setPath (arrowPath);
  53281. goUpButton->setImages (&arrowImage);
  53282. return goUpButton;
  53283. }
  53284. void LookAndFeel::layoutFileBrowserComponent (FileBrowserComponent& browserComp,
  53285. DirectoryContentsDisplayComponent* fileListComponent,
  53286. FilePreviewComponent* previewComp,
  53287. ComboBox* currentPathBox,
  53288. TextEditor* filenameBox,
  53289. Button* goUpButton)
  53290. {
  53291. const int x = 8;
  53292. int w = browserComp.getWidth() - x - x;
  53293. if (previewComp != 0)
  53294. {
  53295. const int previewWidth = w / 3;
  53296. previewComp->setBounds (x + w - previewWidth, 0, previewWidth, browserComp.getHeight());
  53297. w -= previewWidth + 4;
  53298. }
  53299. int y = 4;
  53300. const int controlsHeight = 22;
  53301. const int bottomSectionHeight = controlsHeight + 8;
  53302. const int upButtonWidth = 50;
  53303. currentPathBox->setBounds (x, y, w - upButtonWidth - 6, controlsHeight);
  53304. goUpButton->setBounds (x + w - upButtonWidth, y, upButtonWidth, controlsHeight);
  53305. y += controlsHeight + 4;
  53306. Component* const listAsComp = dynamic_cast <Component*> (fileListComponent);
  53307. listAsComp->setBounds (x, y, w, browserComp.getHeight() - y - bottomSectionHeight);
  53308. y = listAsComp->getBottom() + 4;
  53309. filenameBox->setBounds (x + 50, y, w - 50, controlsHeight);
  53310. }
  53311. Image* LookAndFeel::getDefaultFolderImage()
  53312. {
  53313. 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,
  53314. 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,
  53315. 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,
  53316. 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,
  53317. 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,
  53318. 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,
  53319. 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,
  53320. 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,
  53321. 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,
  53322. 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,
  53323. 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,
  53324. 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,
  53325. 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,
  53326. 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,
  53327. 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,
  53328. 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,
  53329. 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,
  53330. 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,
  53331. 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,
  53332. 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,
  53333. 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,
  53334. 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,
  53335. 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,
  53336. 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,
  53337. 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,
  53338. 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,
  53339. 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,
  53340. 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,
  53341. 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,
  53342. 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,
  53343. 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,
  53344. 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,
  53345. 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,
  53346. 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,
  53347. 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,
  53348. 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,
  53349. 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,
  53350. 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,
  53351. 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,
  53352. 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,
  53353. 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,
  53354. 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,
  53355. 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,
  53356. 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};
  53357. return ImageCache::getFromMemory (foldericon_png, sizeof (foldericon_png));
  53358. }
  53359. Image* LookAndFeel::getDefaultDocumentFileImage()
  53360. {
  53361. 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,
  53362. 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,
  53363. 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,
  53364. 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,
  53365. 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,
  53366. 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,
  53367. 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,
  53368. 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,
  53369. 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,
  53370. 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,
  53371. 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,
  53372. 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,
  53373. 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,
  53374. 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,
  53375. 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,
  53376. 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,
  53377. 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,
  53378. 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,
  53379. 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,
  53380. 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,
  53381. 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,
  53382. 174,66,96,130,0,0};
  53383. return ImageCache::getFromMemory (fileicon_png, sizeof (fileicon_png));
  53384. }
  53385. void LookAndFeel::playAlertSound()
  53386. {
  53387. PlatformUtilities::beep();
  53388. }
  53389. void LookAndFeel::drawLevelMeter (Graphics& g, int width, int height, float level)
  53390. {
  53391. g.setColour (Colours::white.withAlpha (0.7f));
  53392. g.fillRoundedRectangle (0.0f, 0.0f, (float) width, (float) height, 3.0f);
  53393. g.setColour (Colours::black.withAlpha (0.2f));
  53394. g.drawRoundedRectangle (1.0f, 1.0f, width - 2.0f, height - 2.0f, 3.0f, 1.0f);
  53395. const int totalBlocks = 7;
  53396. const int numBlocks = roundToInt (totalBlocks * level);
  53397. const float w = (width - 6.0f) / (float) totalBlocks;
  53398. for (int i = 0; i < totalBlocks; ++i)
  53399. {
  53400. if (i >= numBlocks)
  53401. g.setColour (Colours::lightblue.withAlpha (0.6f));
  53402. else
  53403. g.setColour (i < totalBlocks - 1 ? Colours::blue.withAlpha (0.5f)
  53404. : Colours::red);
  53405. g.fillRoundedRectangle (3.0f + i * w + w * 0.1f, 3.0f, w * 0.8f, height - 6.0f, w * 0.4f);
  53406. }
  53407. }
  53408. void LookAndFeel::drawKeymapChangeButton (Graphics& g, int width, int height, Button& button, const String& keyDescription)
  53409. {
  53410. const Colour textColour (button.findColour (KeyMappingEditorComponent::textColourId, true));
  53411. if (keyDescription.isNotEmpty())
  53412. {
  53413. if (button.isEnabled())
  53414. {
  53415. const float alpha = button.isDown() ? 0.3f : (button.isOver() ? 0.15f : 0.08f);
  53416. g.fillAll (textColour.withAlpha (alpha));
  53417. g.setOpacity (0.3f);
  53418. g.drawBevel (0, 0, width, height, 2);
  53419. }
  53420. g.setColour (textColour);
  53421. g.setFont (height * 0.6f);
  53422. g.drawFittedText (keyDescription,
  53423. 3, 0, width - 6, height,
  53424. Justification::centred, 1);
  53425. }
  53426. else
  53427. {
  53428. const float thickness = 7.0f;
  53429. const float indent = 22.0f;
  53430. Path p;
  53431. p.addEllipse (0.0f, 0.0f, 100.0f, 100.0f);
  53432. p.addRectangle (indent, 50.0f - thickness, 100.0f - indent * 2.0f, thickness * 2.0f);
  53433. p.addRectangle (50.0f - thickness, indent, thickness * 2.0f, 50.0f - indent - thickness);
  53434. p.addRectangle (50.0f - thickness, 50.0f + thickness, thickness * 2.0f, 50.0f - indent - thickness);
  53435. p.setUsingNonZeroWinding (false);
  53436. g.setColour (textColour.withAlpha (button.isDown() ? 0.7f : (button.isOver() ? 0.5f : 0.3f)));
  53437. g.fillPath (p, p.getTransformToScaleToFit (2.0f, 2.0f, width - 4.0f, height - 4.0f, true));
  53438. }
  53439. if (button.hasKeyboardFocus (false))
  53440. {
  53441. g.setColour (textColour.withAlpha (0.4f));
  53442. g.drawRect (0, 0, width, height);
  53443. }
  53444. }
  53445. static void createRoundedPath (Path& p,
  53446. const float x, const float y,
  53447. const float w, const float h,
  53448. const float cs,
  53449. const bool curveTopLeft, const bool curveTopRight,
  53450. const bool curveBottomLeft, const bool curveBottomRight) throw()
  53451. {
  53452. const float cs2 = 2.0f * cs;
  53453. if (curveTopLeft)
  53454. {
  53455. p.startNewSubPath (x, y + cs);
  53456. p.addArc (x, y, cs2, cs2, float_Pi * 1.5f, float_Pi * 2.0f);
  53457. }
  53458. else
  53459. {
  53460. p.startNewSubPath (x, y);
  53461. }
  53462. if (curveTopRight)
  53463. {
  53464. p.lineTo (x + w - cs, y);
  53465. p.addArc (x + w - cs2, y, cs2, cs2, 0.0f, float_Pi * 0.5f);
  53466. }
  53467. else
  53468. {
  53469. p.lineTo (x + w, y);
  53470. }
  53471. if (curveBottomRight)
  53472. {
  53473. p.lineTo (x + w, y + h - cs);
  53474. p.addArc (x + w - cs2, y + h - cs2, cs2, cs2, float_Pi * 0.5f, float_Pi);
  53475. }
  53476. else
  53477. {
  53478. p.lineTo (x + w, y + h);
  53479. }
  53480. if (curveBottomLeft)
  53481. {
  53482. p.lineTo (x + cs, y + h);
  53483. p.addArc (x, y + h - cs2, cs2, cs2, float_Pi, float_Pi * 1.5f);
  53484. }
  53485. else
  53486. {
  53487. p.lineTo (x, y + h);
  53488. }
  53489. p.closeSubPath();
  53490. }
  53491. void LookAndFeel::drawShinyButtonShape (Graphics& g,
  53492. float x, float y, float w, float h,
  53493. float maxCornerSize,
  53494. const Colour& baseColour,
  53495. const float strokeWidth,
  53496. const bool flatOnLeft,
  53497. const bool flatOnRight,
  53498. const bool flatOnTop,
  53499. const bool flatOnBottom) throw()
  53500. {
  53501. if (w <= strokeWidth * 1.1f || h <= strokeWidth * 1.1f)
  53502. return;
  53503. const float cs = jmin (maxCornerSize, w * 0.5f, h * 0.5f);
  53504. Path outline;
  53505. createRoundedPath (outline, x, y, w, h, cs,
  53506. ! (flatOnLeft || flatOnTop),
  53507. ! (flatOnRight || flatOnTop),
  53508. ! (flatOnLeft || flatOnBottom),
  53509. ! (flatOnRight || flatOnBottom));
  53510. ColourGradient cg (baseColour, 0.0f, y,
  53511. baseColour.overlaidWith (Colour (0x070000ff)), 0.0f, y + h,
  53512. false);
  53513. cg.addColour (0.5, baseColour.overlaidWith (Colour (0x33ffffff)));
  53514. cg.addColour (0.51, baseColour.overlaidWith (Colour (0x110000ff)));
  53515. g.setGradientFill (cg);
  53516. g.fillPath (outline);
  53517. g.setColour (Colour (0x80000000));
  53518. g.strokePath (outline, PathStrokeType (strokeWidth));
  53519. }
  53520. void LookAndFeel::drawGlassSphere (Graphics& g,
  53521. const float x, const float y,
  53522. const float diameter,
  53523. const Colour& colour,
  53524. const float outlineThickness) throw()
  53525. {
  53526. if (diameter <= outlineThickness)
  53527. return;
  53528. Path p;
  53529. p.addEllipse (x, y, diameter, diameter);
  53530. {
  53531. ColourGradient cg (Colours::white.overlaidWith (colour.withMultipliedAlpha (0.3f)), 0, y,
  53532. Colours::white.overlaidWith (colour.withMultipliedAlpha (0.3f)), 0, y + diameter, false);
  53533. cg.addColour (0.4, Colours::white.overlaidWith (colour));
  53534. g.setGradientFill (cg);
  53535. g.fillPath (p);
  53536. }
  53537. g.setGradientFill (ColourGradient (Colours::white, 0, y + diameter * 0.06f,
  53538. Colours::transparentWhite, 0, y + diameter * 0.3f, false));
  53539. g.fillEllipse (x + diameter * 0.2f, y + diameter * 0.05f, diameter * 0.6f, diameter * 0.4f);
  53540. ColourGradient cg (Colours::transparentBlack,
  53541. x + diameter * 0.5f, y + diameter * 0.5f,
  53542. Colours::black.withAlpha (0.5f * outlineThickness * colour.getFloatAlpha()),
  53543. x, y + diameter * 0.5f, true);
  53544. cg.addColour (0.7, Colours::transparentBlack);
  53545. cg.addColour (0.8, Colours::black.withAlpha (0.1f * outlineThickness));
  53546. g.setGradientFill (cg);
  53547. g.fillPath (p);
  53548. g.setColour (Colours::black.withAlpha (0.5f * colour.getFloatAlpha()));
  53549. g.drawEllipse (x, y, diameter, diameter, outlineThickness);
  53550. }
  53551. void LookAndFeel::drawGlassPointer (Graphics& g,
  53552. const float x, const float y,
  53553. const float diameter,
  53554. const Colour& colour, const float outlineThickness,
  53555. const int direction) throw()
  53556. {
  53557. if (diameter <= outlineThickness)
  53558. return;
  53559. Path p;
  53560. p.startNewSubPath (x + diameter * 0.5f, y);
  53561. p.lineTo (x + diameter, y + diameter * 0.6f);
  53562. p.lineTo (x + diameter, y + diameter);
  53563. p.lineTo (x, y + diameter);
  53564. p.lineTo (x, y + diameter * 0.6f);
  53565. p.closeSubPath();
  53566. p.applyTransform (AffineTransform::rotation (direction * (float_Pi * 0.5f), x + diameter * 0.5f, y + diameter * 0.5f));
  53567. {
  53568. ColourGradient cg (Colours::white.overlaidWith (colour.withMultipliedAlpha (0.3f)), 0, y,
  53569. Colours::white.overlaidWith (colour.withMultipliedAlpha (0.3f)), 0, y + diameter, false);
  53570. cg.addColour (0.4, Colours::white.overlaidWith (colour));
  53571. g.setGradientFill (cg);
  53572. g.fillPath (p);
  53573. }
  53574. ColourGradient cg (Colours::transparentBlack,
  53575. x + diameter * 0.5f, y + diameter * 0.5f,
  53576. Colours::black.withAlpha (0.5f * outlineThickness * colour.getFloatAlpha()),
  53577. x - diameter * 0.2f, y + diameter * 0.5f, true);
  53578. cg.addColour (0.5, Colours::transparentBlack);
  53579. cg.addColour (0.7, Colours::black.withAlpha (0.07f * outlineThickness));
  53580. g.setGradientFill (cg);
  53581. g.fillPath (p);
  53582. g.setColour (Colours::black.withAlpha (0.5f * colour.getFloatAlpha()));
  53583. g.strokePath (p, PathStrokeType (outlineThickness));
  53584. }
  53585. void LookAndFeel::drawGlassLozenge (Graphics& g,
  53586. const float x, const float y,
  53587. const float width, const float height,
  53588. const Colour& colour,
  53589. const float outlineThickness,
  53590. const float cornerSize,
  53591. const bool flatOnLeft,
  53592. const bool flatOnRight,
  53593. const bool flatOnTop,
  53594. const bool flatOnBottom) throw()
  53595. {
  53596. if (width <= outlineThickness || height <= outlineThickness)
  53597. return;
  53598. const int intX = (int) x;
  53599. const int intY = (int) y;
  53600. const int intW = (int) width;
  53601. const int intH = (int) height;
  53602. const float cs = cornerSize < 0 ? jmin (width * 0.5f, height * 0.5f) : cornerSize;
  53603. const float edgeBlurRadius = height * 0.75f + (height - cs * 2.0f);
  53604. const int intEdge = (int) edgeBlurRadius;
  53605. Path outline;
  53606. createRoundedPath (outline, x, y, width, height, cs,
  53607. ! (flatOnLeft || flatOnTop),
  53608. ! (flatOnRight || flatOnTop),
  53609. ! (flatOnLeft || flatOnBottom),
  53610. ! (flatOnRight || flatOnBottom));
  53611. {
  53612. ColourGradient cg (colour.darker (0.2f), 0, y,
  53613. colour.darker (0.2f), 0, y + height, false);
  53614. cg.addColour (0.03, colour.withMultipliedAlpha (0.3f));
  53615. cg.addColour (0.4, colour);
  53616. cg.addColour (0.97, colour.withMultipliedAlpha (0.3f));
  53617. g.setGradientFill (cg);
  53618. g.fillPath (outline);
  53619. }
  53620. ColourGradient cg (Colours::transparentBlack, x + edgeBlurRadius, y + height * 0.5f,
  53621. colour.darker (0.2f), x, y + height * 0.5f, true);
  53622. cg.addColour (jlimit (0.0, 1.0, 1.0 - (cs * 0.5f) / edgeBlurRadius), Colours::transparentBlack);
  53623. cg.addColour (jlimit (0.0, 1.0, 1.0 - (cs * 0.25f) / edgeBlurRadius), colour.darker (0.2f).withMultipliedAlpha (0.3f));
  53624. if (! (flatOnLeft || flatOnTop || flatOnBottom))
  53625. {
  53626. g.saveState();
  53627. g.setGradientFill (cg);
  53628. g.reduceClipRegion (intX, intY, intEdge, intH);
  53629. g.fillPath (outline);
  53630. g.restoreState();
  53631. }
  53632. if (! (flatOnRight || flatOnTop || flatOnBottom))
  53633. {
  53634. cg.x1 = x + width - edgeBlurRadius;
  53635. cg.x2 = x + width;
  53636. g.saveState();
  53637. g.setGradientFill (cg);
  53638. g.reduceClipRegion (intX + intW - intEdge, intY, 2 + intEdge, intH);
  53639. g.fillPath (outline);
  53640. g.restoreState();
  53641. }
  53642. {
  53643. const float leftIndent = flatOnLeft ? 0.0f : cs * 0.4f;
  53644. const float rightIndent = flatOnRight ? 0.0f : cs * 0.4f;
  53645. Path highlight;
  53646. createRoundedPath (highlight,
  53647. x + leftIndent,
  53648. y + cs * 0.1f,
  53649. width - (leftIndent + rightIndent),
  53650. height * 0.4f, cs * 0.4f,
  53651. ! (flatOnLeft || flatOnTop),
  53652. ! (flatOnRight || flatOnTop),
  53653. ! (flatOnLeft || flatOnBottom),
  53654. ! (flatOnRight || flatOnBottom));
  53655. g.setGradientFill (ColourGradient (colour.brighter (10.0f), 0, y + height * 0.06f,
  53656. Colours::transparentWhite, 0, y + height * 0.4f, false));
  53657. g.fillPath (highlight);
  53658. }
  53659. g.setColour (colour.darker().withMultipliedAlpha (1.5f));
  53660. g.strokePath (outline, PathStrokeType (outlineThickness));
  53661. }
  53662. END_JUCE_NAMESPACE
  53663. /*** End of inlined file: juce_LookAndFeel.cpp ***/
  53664. /*** Start of inlined file: juce_OldSchoolLookAndFeel.cpp ***/
  53665. BEGIN_JUCE_NAMESPACE
  53666. OldSchoolLookAndFeel::OldSchoolLookAndFeel()
  53667. {
  53668. setColour (TextButton::buttonColourId, Colour (0xffbbbbff));
  53669. setColour (ListBox::outlineColourId, findColour (ComboBox::outlineColourId));
  53670. setColour (ScrollBar::thumbColourId, Colour (0xffbbbbdd));
  53671. setColour (ScrollBar::backgroundColourId, Colours::transparentBlack);
  53672. setColour (Slider::thumbColourId, Colours::white);
  53673. setColour (Slider::trackColourId, Colour (0x7f000000));
  53674. setColour (Slider::textBoxOutlineColourId, Colours::grey);
  53675. setColour (ProgressBar::backgroundColourId, Colours::white.withAlpha (0.6f));
  53676. setColour (ProgressBar::foregroundColourId, Colours::green.withAlpha (0.7f));
  53677. setColour (PopupMenu::backgroundColourId, Colour (0xffeef5f8));
  53678. setColour (PopupMenu::highlightedBackgroundColourId, Colour (0xbfa4c2ce));
  53679. setColour (PopupMenu::highlightedTextColourId, Colours::black);
  53680. setColour (TextEditor::focusedOutlineColourId, findColour (TextButton::buttonColourId));
  53681. scrollbarShadow.setShadowProperties (2.2f, 0.5f, 0, 0);
  53682. }
  53683. OldSchoolLookAndFeel::~OldSchoolLookAndFeel()
  53684. {
  53685. }
  53686. void OldSchoolLookAndFeel::drawButtonBackground (Graphics& g,
  53687. Button& button,
  53688. const Colour& backgroundColour,
  53689. bool isMouseOverButton,
  53690. bool isButtonDown)
  53691. {
  53692. const int width = button.getWidth();
  53693. const int height = button.getHeight();
  53694. const float indent = 2.0f;
  53695. const int cornerSize = jmin (roundToInt (width * 0.4f),
  53696. roundToInt (height * 0.4f));
  53697. Path p;
  53698. p.addRoundedRectangle (indent, indent,
  53699. width - indent * 2.0f,
  53700. height - indent * 2.0f,
  53701. (float) cornerSize);
  53702. Colour bc (backgroundColour.withMultipliedSaturation (0.3f));
  53703. if (isMouseOverButton)
  53704. {
  53705. if (isButtonDown)
  53706. bc = bc.brighter();
  53707. else if (bc.getBrightness() > 0.5f)
  53708. bc = bc.darker (0.1f);
  53709. else
  53710. bc = bc.brighter (0.1f);
  53711. }
  53712. g.setColour (bc);
  53713. g.fillPath (p);
  53714. g.setColour (bc.contrasting().withAlpha ((isMouseOverButton) ? 0.6f : 0.4f));
  53715. g.strokePath (p, PathStrokeType ((isMouseOverButton) ? 2.0f : 1.4f));
  53716. }
  53717. void OldSchoolLookAndFeel::drawTickBox (Graphics& g,
  53718. Component& /*component*/,
  53719. float x, float y, float w, float h,
  53720. const bool ticked,
  53721. const bool isEnabled,
  53722. const bool /*isMouseOverButton*/,
  53723. const bool isButtonDown)
  53724. {
  53725. Path box;
  53726. box.addRoundedRectangle (0.0f, 2.0f, 6.0f, 6.0f, 1.0f);
  53727. g.setColour (isEnabled ? Colours::blue.withAlpha (isButtonDown ? 0.3f : 0.1f)
  53728. : Colours::lightgrey.withAlpha (0.1f));
  53729. AffineTransform trans (AffineTransform::scale (w / 9.0f, h / 9.0f).translated (x, y));
  53730. g.fillPath (box, trans);
  53731. g.setColour (Colours::black.withAlpha (0.6f));
  53732. g.strokePath (box, PathStrokeType (0.9f), trans);
  53733. if (ticked)
  53734. {
  53735. Path tick;
  53736. tick.startNewSubPath (1.5f, 3.0f);
  53737. tick.lineTo (3.0f, 6.0f);
  53738. tick.lineTo (6.0f, 0.0f);
  53739. g.setColour (isEnabled ? Colours::black : Colours::grey);
  53740. g.strokePath (tick, PathStrokeType (2.5f), trans);
  53741. }
  53742. }
  53743. void OldSchoolLookAndFeel::drawToggleButton (Graphics& g,
  53744. ToggleButton& button,
  53745. bool isMouseOverButton,
  53746. bool isButtonDown)
  53747. {
  53748. if (button.hasKeyboardFocus (true))
  53749. {
  53750. g.setColour (button.findColour (TextEditor::focusedOutlineColourId));
  53751. g.drawRect (0, 0, button.getWidth(), button.getHeight());
  53752. }
  53753. const int tickWidth = jmin (20, button.getHeight() - 4);
  53754. drawTickBox (g, button, 4.0f, (button.getHeight() - tickWidth) * 0.5f,
  53755. (float) tickWidth, (float) tickWidth,
  53756. button.getToggleState(),
  53757. button.isEnabled(),
  53758. isMouseOverButton,
  53759. isButtonDown);
  53760. g.setColour (button.findColour (ToggleButton::textColourId));
  53761. g.setFont (jmin (15.0f, button.getHeight() * 0.6f));
  53762. if (! button.isEnabled())
  53763. g.setOpacity (0.5f);
  53764. const int textX = tickWidth + 5;
  53765. g.drawFittedText (button.getButtonText(),
  53766. textX, 4,
  53767. button.getWidth() - textX - 2, button.getHeight() - 8,
  53768. Justification::centredLeft, 10);
  53769. }
  53770. void OldSchoolLookAndFeel::drawProgressBar (Graphics& g, ProgressBar& progressBar,
  53771. int width, int height,
  53772. double progress, const String& textToShow)
  53773. {
  53774. if (progress < 0 || progress >= 1.0)
  53775. {
  53776. LookAndFeel::drawProgressBar (g, progressBar, width, height, progress, textToShow);
  53777. }
  53778. else
  53779. {
  53780. const Colour background (progressBar.findColour (ProgressBar::backgroundColourId));
  53781. const Colour foreground (progressBar.findColour (ProgressBar::foregroundColourId));
  53782. g.fillAll (background);
  53783. g.setColour (foreground);
  53784. g.fillRect (1, 1,
  53785. jlimit (0, width - 2, roundToInt (progress * (width - 2))),
  53786. height - 2);
  53787. if (textToShow.isNotEmpty())
  53788. {
  53789. g.setColour (Colour::contrasting (background, foreground));
  53790. g.setFont (height * 0.6f);
  53791. g.drawText (textToShow, 0, 0, width, height, Justification::centred, false);
  53792. }
  53793. }
  53794. }
  53795. void OldSchoolLookAndFeel::drawScrollbarButton (Graphics& g,
  53796. ScrollBar& bar,
  53797. int width, int height,
  53798. int buttonDirection,
  53799. bool isScrollbarVertical,
  53800. bool isMouseOverButton,
  53801. bool isButtonDown)
  53802. {
  53803. if (isScrollbarVertical)
  53804. width -= 2;
  53805. else
  53806. height -= 2;
  53807. Path p;
  53808. if (buttonDirection == 0)
  53809. p.addTriangle (width * 0.5f, height * 0.2f,
  53810. width * 0.1f, height * 0.7f,
  53811. width * 0.9f, height * 0.7f);
  53812. else if (buttonDirection == 1)
  53813. p.addTriangle (width * 0.8f, height * 0.5f,
  53814. width * 0.3f, height * 0.1f,
  53815. width * 0.3f, height * 0.9f);
  53816. else if (buttonDirection == 2)
  53817. p.addTriangle (width * 0.5f, height * 0.8f,
  53818. width * 0.1f, height * 0.3f,
  53819. width * 0.9f, height * 0.3f);
  53820. else if (buttonDirection == 3)
  53821. p.addTriangle (width * 0.2f, height * 0.5f,
  53822. width * 0.7f, height * 0.1f,
  53823. width * 0.7f, height * 0.9f);
  53824. if (isButtonDown)
  53825. g.setColour (Colours::white);
  53826. else if (isMouseOverButton)
  53827. g.setColour (Colours::white.withAlpha (0.7f));
  53828. else
  53829. g.setColour (bar.findColour (ScrollBar::thumbColourId).withAlpha (0.5f));
  53830. g.fillPath (p);
  53831. g.setColour (Colours::black.withAlpha (0.5f));
  53832. g.strokePath (p, PathStrokeType (0.5f));
  53833. }
  53834. void OldSchoolLookAndFeel::drawScrollbar (Graphics& g,
  53835. ScrollBar& bar,
  53836. int x, int y,
  53837. int width, int height,
  53838. bool isScrollbarVertical,
  53839. int thumbStartPosition,
  53840. int thumbSize,
  53841. bool isMouseOver,
  53842. bool isMouseDown)
  53843. {
  53844. g.fillAll (bar.findColour (ScrollBar::backgroundColourId));
  53845. g.setColour (bar.findColour (ScrollBar::thumbColourId)
  53846. .withAlpha ((isMouseOver || isMouseDown) ? 0.4f : 0.15f));
  53847. if (thumbSize > 0.0f)
  53848. {
  53849. Rectangle<int> thumb;
  53850. if (isScrollbarVertical)
  53851. {
  53852. width -= 2;
  53853. g.fillRect (x + roundToInt (width * 0.35f), y,
  53854. roundToInt (width * 0.3f), height);
  53855. thumb.setBounds (x + 1, thumbStartPosition,
  53856. width - 2, thumbSize);
  53857. }
  53858. else
  53859. {
  53860. height -= 2;
  53861. g.fillRect (x, y + roundToInt (height * 0.35f),
  53862. width, roundToInt (height * 0.3f));
  53863. thumb.setBounds (thumbStartPosition, y + 1,
  53864. thumbSize, height - 2);
  53865. }
  53866. g.setColour (bar.findColour (ScrollBar::thumbColourId)
  53867. .withAlpha ((isMouseOver || isMouseDown) ? 0.95f : 0.7f));
  53868. g.fillRect (thumb);
  53869. g.setColour (Colours::black.withAlpha ((isMouseOver || isMouseDown) ? 0.4f : 0.25f));
  53870. g.drawRect (thumb.getX(), thumb.getY(), thumb.getWidth(), thumb.getHeight());
  53871. if (thumbSize > 16)
  53872. {
  53873. for (int i = 3; --i >= 0;)
  53874. {
  53875. const float linePos = thumbStartPosition + thumbSize / 2 + (i - 1) * 4.0f;
  53876. g.setColour (Colours::black.withAlpha (0.15f));
  53877. if (isScrollbarVertical)
  53878. {
  53879. g.drawLine (x + width * 0.2f, linePos, width * 0.8f, linePos);
  53880. g.setColour (Colours::white.withAlpha (0.15f));
  53881. g.drawLine (width * 0.2f, linePos - 1, width * 0.8f, linePos - 1);
  53882. }
  53883. else
  53884. {
  53885. g.drawLine (linePos, height * 0.2f, linePos, height * 0.8f);
  53886. g.setColour (Colours::white.withAlpha (0.15f));
  53887. g.drawLine (linePos - 1, height * 0.2f, linePos - 1, height * 0.8f);
  53888. }
  53889. }
  53890. }
  53891. }
  53892. }
  53893. ImageEffectFilter* OldSchoolLookAndFeel::getScrollbarEffect()
  53894. {
  53895. return &scrollbarShadow;
  53896. }
  53897. void OldSchoolLookAndFeel::drawPopupMenuBackground (Graphics& g, int width, int height)
  53898. {
  53899. g.fillAll (findColour (PopupMenu::backgroundColourId));
  53900. g.setColour (Colours::black.withAlpha (0.6f));
  53901. g.drawRect (0, 0, width, height);
  53902. }
  53903. void OldSchoolLookAndFeel::drawMenuBarBackground (Graphics& g, int /*width*/, int /*height*/,
  53904. bool, MenuBarComponent& menuBar)
  53905. {
  53906. g.fillAll (menuBar.findColour (PopupMenu::backgroundColourId));
  53907. }
  53908. void OldSchoolLookAndFeel::drawTextEditorOutline (Graphics& g, int width, int height, TextEditor& textEditor)
  53909. {
  53910. if (textEditor.isEnabled())
  53911. {
  53912. g.setColour (textEditor.findColour (TextEditor::outlineColourId));
  53913. g.drawRect (0, 0, width, height);
  53914. }
  53915. }
  53916. void OldSchoolLookAndFeel::drawComboBox (Graphics& g, int width, int height,
  53917. const bool isButtonDown,
  53918. int buttonX, int buttonY,
  53919. int buttonW, int buttonH,
  53920. ComboBox& box)
  53921. {
  53922. g.fillAll (box.findColour (ComboBox::backgroundColourId));
  53923. g.setColour (box.findColour ((isButtonDown) ? ComboBox::buttonColourId
  53924. : ComboBox::backgroundColourId));
  53925. g.fillRect (buttonX, buttonY, buttonW, buttonH);
  53926. g.setColour (box.findColour (ComboBox::outlineColourId));
  53927. g.drawRect (0, 0, width, height);
  53928. const float arrowX = 0.2f;
  53929. const float arrowH = 0.3f;
  53930. if (box.isEnabled())
  53931. {
  53932. Path p;
  53933. p.addTriangle (buttonX + buttonW * 0.5f, buttonY + buttonH * (0.45f - arrowH),
  53934. buttonX + buttonW * (1.0f - arrowX), buttonY + buttonH * 0.45f,
  53935. buttonX + buttonW * arrowX, buttonY + buttonH * 0.45f);
  53936. p.addTriangle (buttonX + buttonW * 0.5f, buttonY + buttonH * (0.55f + arrowH),
  53937. buttonX + buttonW * (1.0f - arrowX), buttonY + buttonH * 0.55f,
  53938. buttonX + buttonW * arrowX, buttonY + buttonH * 0.55f);
  53939. g.setColour (box.findColour ((isButtonDown) ? ComboBox::backgroundColourId
  53940. : ComboBox::buttonColourId));
  53941. g.fillPath (p);
  53942. }
  53943. }
  53944. const Font OldSchoolLookAndFeel::getComboBoxFont (ComboBox& box)
  53945. {
  53946. Font f (jmin (15.0f, box.getHeight() * 0.85f));
  53947. f.setHorizontalScale (0.9f);
  53948. return f;
  53949. }
  53950. static void drawTriangle (Graphics& g, float x1, float y1, float x2, float y2, float x3, float y3, const Colour& fill, const Colour& outline) throw()
  53951. {
  53952. Path p;
  53953. p.addTriangle (x1, y1, x2, y2, x3, y3);
  53954. g.setColour (fill);
  53955. g.fillPath (p);
  53956. g.setColour (outline);
  53957. g.strokePath (p, PathStrokeType (0.3f));
  53958. }
  53959. void OldSchoolLookAndFeel::drawLinearSlider (Graphics& g,
  53960. int x, int y,
  53961. int w, int h,
  53962. float sliderPos,
  53963. float minSliderPos,
  53964. float maxSliderPos,
  53965. const Slider::SliderStyle style,
  53966. Slider& slider)
  53967. {
  53968. g.fillAll (slider.findColour (Slider::backgroundColourId));
  53969. if (style == Slider::LinearBar)
  53970. {
  53971. g.setColour (slider.findColour (Slider::thumbColourId));
  53972. g.fillRect (x, y, (int) sliderPos - x, h);
  53973. g.setColour (slider.findColour (Slider::textBoxTextColourId).withMultipliedAlpha (0.5f));
  53974. g.drawRect (x, y, (int) sliderPos - x, h);
  53975. }
  53976. else
  53977. {
  53978. g.setColour (slider.findColour (Slider::trackColourId)
  53979. .withMultipliedAlpha (slider.isEnabled() ? 1.0f : 0.3f));
  53980. if (slider.isHorizontal())
  53981. {
  53982. g.fillRect (x, y + roundToInt (h * 0.6f),
  53983. w, roundToInt (h * 0.2f));
  53984. }
  53985. else
  53986. {
  53987. g.fillRect (x + roundToInt (w * 0.5f - jmin (3.0f, w * 0.1f)), y,
  53988. jmin (4, roundToInt (w * 0.2f)), h);
  53989. }
  53990. float alpha = 0.35f;
  53991. if (slider.isEnabled())
  53992. alpha = slider.isMouseOverOrDragging() ? 1.0f : 0.7f;
  53993. const Colour fill (slider.findColour (Slider::thumbColourId).withAlpha (alpha));
  53994. const Colour outline (Colours::black.withAlpha (slider.isEnabled() ? 0.7f : 0.35f));
  53995. if (style == Slider::TwoValueVertical || style == Slider::ThreeValueVertical)
  53996. {
  53997. drawTriangle (g, x + w * 0.5f + jmin (4.0f, w * 0.3f), minSliderPos,
  53998. x + w * 0.5f - jmin (8.0f, w * 0.4f), minSliderPos - 7.0f,
  53999. x + w * 0.5f - jmin (8.0f, w * 0.4f), minSliderPos,
  54000. fill, outline);
  54001. drawTriangle (g, x + w * 0.5f + jmin (4.0f, w * 0.3f), maxSliderPos,
  54002. x + w * 0.5f - jmin (8.0f, w * 0.4f), maxSliderPos,
  54003. x + w * 0.5f - jmin (8.0f, w * 0.4f), maxSliderPos + 7.0f,
  54004. fill, outline);
  54005. }
  54006. else if (style == Slider::TwoValueHorizontal || style == Slider::ThreeValueHorizontal)
  54007. {
  54008. drawTriangle (g, minSliderPos, y + h * 0.6f - jmin (4.0f, h * 0.3f),
  54009. minSliderPos - 7.0f, y + h * 0.9f ,
  54010. minSliderPos, y + h * 0.9f,
  54011. fill, outline);
  54012. drawTriangle (g, maxSliderPos, y + h * 0.6f - jmin (4.0f, h * 0.3f),
  54013. maxSliderPos, y + h * 0.9f,
  54014. maxSliderPos + 7.0f, y + h * 0.9f,
  54015. fill, outline);
  54016. }
  54017. if (style == Slider::LinearHorizontal || style == Slider::ThreeValueHorizontal)
  54018. {
  54019. drawTriangle (g, sliderPos, y + h * 0.9f,
  54020. sliderPos - 7.0f, y + h * 0.2f,
  54021. sliderPos + 7.0f, y + h * 0.2f,
  54022. fill, outline);
  54023. }
  54024. else if (style == Slider::LinearVertical || style == Slider::ThreeValueVertical)
  54025. {
  54026. drawTriangle (g, x + w * 0.5f - jmin (4.0f, w * 0.3f), sliderPos,
  54027. x + w * 0.5f + jmin (8.0f, w * 0.4f), sliderPos - 7.0f,
  54028. x + w * 0.5f + jmin (8.0f, w * 0.4f), sliderPos + 7.0f,
  54029. fill, outline);
  54030. }
  54031. }
  54032. }
  54033. Button* OldSchoolLookAndFeel::createSliderButton (const bool isIncrement)
  54034. {
  54035. if (isIncrement)
  54036. return new ArrowButton ("u", 0.75f, Colours::white.withAlpha (0.8f));
  54037. else
  54038. return new ArrowButton ("d", 0.25f, Colours::white.withAlpha (0.8f));
  54039. }
  54040. ImageEffectFilter* OldSchoolLookAndFeel::getSliderEffect()
  54041. {
  54042. return &scrollbarShadow;
  54043. }
  54044. int OldSchoolLookAndFeel::getSliderThumbRadius (Slider&)
  54045. {
  54046. return 8;
  54047. }
  54048. void OldSchoolLookAndFeel::drawCornerResizer (Graphics& g,
  54049. int w, int h,
  54050. bool isMouseOver,
  54051. bool isMouseDragging)
  54052. {
  54053. g.setColour ((isMouseOver || isMouseDragging) ? Colours::lightgrey
  54054. : Colours::darkgrey);
  54055. const float lineThickness = jmin (w, h) * 0.1f;
  54056. for (float i = 0.0f; i < 1.0f; i += 0.3f)
  54057. {
  54058. g.drawLine (w * i,
  54059. h + 1.0f,
  54060. w + 1.0f,
  54061. h * i,
  54062. lineThickness);
  54063. }
  54064. }
  54065. Button* OldSchoolLookAndFeel::createDocumentWindowButton (int buttonType)
  54066. {
  54067. Path shape;
  54068. if (buttonType == DocumentWindow::closeButton)
  54069. {
  54070. shape.addLineSegment (0.0f, 0.0f, 1.0f, 1.0f, 0.35f);
  54071. shape.addLineSegment (1.0f, 0.0f, 0.0f, 1.0f, 0.35f);
  54072. ShapeButton* const b = new ShapeButton ("close",
  54073. Colour (0x7fff3333),
  54074. Colour (0xd7ff3333),
  54075. Colour (0xf7ff3333));
  54076. b->setShape (shape, true, true, true);
  54077. return b;
  54078. }
  54079. else if (buttonType == DocumentWindow::minimiseButton)
  54080. {
  54081. shape.addLineSegment (0.0f, 0.5f, 1.0f, 0.5f, 0.25f);
  54082. DrawableButton* b = new DrawableButton ("minimise", DrawableButton::ImageFitted);
  54083. DrawablePath dp;
  54084. dp.setPath (shape);
  54085. dp.setFill (Colours::black.withAlpha (0.3f));
  54086. b->setImages (&dp);
  54087. return b;
  54088. }
  54089. else if (buttonType == DocumentWindow::maximiseButton)
  54090. {
  54091. shape.addLineSegment (0.5f, 0.0f, 0.5f, 1.0f, 0.25f);
  54092. shape.addLineSegment (0.0f, 0.5f, 1.0f, 0.5f, 0.25f);
  54093. DrawableButton* b = new DrawableButton ("maximise", DrawableButton::ImageFitted);
  54094. DrawablePath dp;
  54095. dp.setPath (shape);
  54096. dp.setFill (Colours::black.withAlpha (0.3f));
  54097. b->setImages (&dp);
  54098. return b;
  54099. }
  54100. jassertfalse
  54101. return 0;
  54102. }
  54103. void OldSchoolLookAndFeel::positionDocumentWindowButtons (DocumentWindow&,
  54104. int titleBarX,
  54105. int titleBarY,
  54106. int titleBarW,
  54107. int titleBarH,
  54108. Button* minimiseButton,
  54109. Button* maximiseButton,
  54110. Button* closeButton,
  54111. bool positionTitleBarButtonsOnLeft)
  54112. {
  54113. titleBarY += titleBarH / 8;
  54114. titleBarH -= titleBarH / 4;
  54115. const int buttonW = titleBarH;
  54116. int x = positionTitleBarButtonsOnLeft ? titleBarX + 4
  54117. : titleBarX + titleBarW - buttonW - 4;
  54118. if (closeButton != 0)
  54119. {
  54120. closeButton->setBounds (x, titleBarY, buttonW, titleBarH);
  54121. x += positionTitleBarButtonsOnLeft ? buttonW + buttonW / 5
  54122. : -(buttonW + buttonW / 5);
  54123. }
  54124. if (positionTitleBarButtonsOnLeft)
  54125. swapVariables (minimiseButton, maximiseButton);
  54126. if (maximiseButton != 0)
  54127. {
  54128. maximiseButton->setBounds (x, titleBarY - 2, buttonW, titleBarH);
  54129. x += positionTitleBarButtonsOnLeft ? buttonW : -buttonW;
  54130. }
  54131. if (minimiseButton != 0)
  54132. minimiseButton->setBounds (x, titleBarY - 2, buttonW, titleBarH);
  54133. }
  54134. END_JUCE_NAMESPACE
  54135. /*** End of inlined file: juce_OldSchoolLookAndFeel.cpp ***/
  54136. /*** Start of inlined file: juce_MenuBarComponent.cpp ***/
  54137. BEGIN_JUCE_NAMESPACE
  54138. class DummyMenuComponent : public Component
  54139. {
  54140. DummyMenuComponent (const DummyMenuComponent&);
  54141. DummyMenuComponent& operator= (const DummyMenuComponent&);
  54142. public:
  54143. DummyMenuComponent() {}
  54144. ~DummyMenuComponent() {}
  54145. void inputAttemptWhenModal()
  54146. {
  54147. exitModalState (0);
  54148. }
  54149. };
  54150. MenuBarComponent::MenuBarComponent (MenuBarModel* model_)
  54151. : model (0),
  54152. itemUnderMouse (-1),
  54153. currentPopupIndex (-1),
  54154. indexToShowAgain (-1),
  54155. lastMouseX (0),
  54156. lastMouseY (0),
  54157. inModalState (false)
  54158. {
  54159. setRepaintsOnMouseActivity (true);
  54160. setWantsKeyboardFocus (false);
  54161. setMouseClickGrabsKeyboardFocus (false);
  54162. setModel (model_);
  54163. }
  54164. MenuBarComponent::~MenuBarComponent()
  54165. {
  54166. setModel (0);
  54167. Desktop::getInstance().removeGlobalMouseListener (this);
  54168. currentPopup = 0;
  54169. }
  54170. void MenuBarComponent::setModel (MenuBarModel* const newModel)
  54171. {
  54172. if (model != newModel)
  54173. {
  54174. if (model != 0)
  54175. model->removeListener (this);
  54176. model = newModel;
  54177. if (model != 0)
  54178. model->addListener (this);
  54179. repaint();
  54180. menuBarItemsChanged (0);
  54181. }
  54182. }
  54183. void MenuBarComponent::paint (Graphics& g)
  54184. {
  54185. const bool isMouseOverBar = currentPopupIndex >= 0 || itemUnderMouse >= 0 || isMouseOver();
  54186. getLookAndFeel().drawMenuBarBackground (g,
  54187. getWidth(),
  54188. getHeight(),
  54189. isMouseOverBar,
  54190. *this);
  54191. if (model != 0)
  54192. {
  54193. for (int i = 0; i < menuNames.size(); ++i)
  54194. {
  54195. g.saveState();
  54196. g.setOrigin (xPositions [i], 0);
  54197. g.reduceClipRegion (0, 0, xPositions[i + 1] - xPositions[i], getHeight());
  54198. getLookAndFeel().drawMenuBarItem (g,
  54199. xPositions[i + 1] - xPositions[i],
  54200. getHeight(),
  54201. i,
  54202. menuNames[i],
  54203. i == itemUnderMouse,
  54204. i == currentPopupIndex,
  54205. isMouseOverBar,
  54206. *this);
  54207. g.restoreState();
  54208. }
  54209. }
  54210. }
  54211. void MenuBarComponent::resized()
  54212. {
  54213. xPositions.clear();
  54214. int x = 2;
  54215. xPositions.add (x);
  54216. for (int i = 0; i < menuNames.size(); ++i)
  54217. {
  54218. x += getLookAndFeel().getMenuBarItemWidth (*this, i, menuNames[i]);
  54219. xPositions.add (x);
  54220. }
  54221. }
  54222. int MenuBarComponent::getItemAt (const int x, const int y)
  54223. {
  54224. for (int i = 0; i < xPositions.size(); ++i)
  54225. if (x >= xPositions[i] && x < xPositions[i + 1])
  54226. return reallyContains (x, y, true) ? i : -1;
  54227. return -1;
  54228. }
  54229. void MenuBarComponent::repaintMenuItem (int index)
  54230. {
  54231. if (((unsigned int) index) < (unsigned int) xPositions.size())
  54232. {
  54233. const int x1 = xPositions [index];
  54234. const int x2 = xPositions [index + 1];
  54235. repaint (x1 - 2, 0, x2 - x1 + 4, getHeight());
  54236. }
  54237. }
  54238. void MenuBarComponent::updateItemUnderMouse (int x, int y)
  54239. {
  54240. const int newItem = getItemAt (x, y);
  54241. if (itemUnderMouse != newItem)
  54242. {
  54243. repaintMenuItem (itemUnderMouse);
  54244. itemUnderMouse = newItem;
  54245. repaintMenuItem (itemUnderMouse);
  54246. }
  54247. }
  54248. void MenuBarComponent::hideCurrentMenu()
  54249. {
  54250. currentPopup = 0;
  54251. repaint();
  54252. }
  54253. void MenuBarComponent::showMenu (int index)
  54254. {
  54255. if (index != currentPopupIndex)
  54256. {
  54257. if (inModalState)
  54258. {
  54259. hideCurrentMenu();
  54260. indexToShowAgain = index;
  54261. return;
  54262. }
  54263. indexToShowAgain = -1;
  54264. currentPopupIndex = -1;
  54265. itemUnderMouse = index;
  54266. currentPopup = 0;
  54267. menuBarItemsChanged (0);
  54268. Component::SafePointer<Component> prevFocused (getCurrentlyFocusedComponent());
  54269. Component::SafePointer<Component> deletionChecker (this);
  54270. enterModalState (false);
  54271. inModalState = true;
  54272. int result = 0;
  54273. ApplicationCommandManager* managerOfChosenCommand = 0;
  54274. Desktop::getInstance().addGlobalMouseListener (this);
  54275. for (;;)
  54276. {
  54277. const int x = getScreenX() + xPositions [itemUnderMouse];
  54278. const int w = xPositions [itemUnderMouse + 1] - xPositions [itemUnderMouse];
  54279. currentPopupIndex = itemUnderMouse;
  54280. indexToShowAgain = -1;
  54281. repaint();
  54282. if (((unsigned int) itemUnderMouse) < (unsigned int) menuNames.size())
  54283. {
  54284. PopupMenu m (model->getMenuForIndex (itemUnderMouse,
  54285. menuNames [itemUnderMouse]));
  54286. if (m.lookAndFeel == 0)
  54287. m.setLookAndFeel (&getLookAndFeel());
  54288. currentPopup = m.createMenuComponent (x, getScreenY(),
  54289. w, getHeight(),
  54290. 0, w, 0, 0,
  54291. true, this,
  54292. &managerOfChosenCommand,
  54293. this);
  54294. }
  54295. if (currentPopup == 0)
  54296. {
  54297. currentPopup = new DummyMenuComponent();
  54298. addAndMakeVisible (currentPopup);
  54299. }
  54300. currentPopup->enterModalState (false);
  54301. currentPopup->toFront (false); // need to do this after making it modal, or it could
  54302. // be stuck behind other comps that are already modal..
  54303. result = currentPopup->runModalLoop();
  54304. if (deletionChecker == 0)
  54305. return;
  54306. const int lastPopupIndex = currentPopupIndex;
  54307. currentPopup = 0;
  54308. currentPopupIndex = -1;
  54309. if (result != 0)
  54310. {
  54311. topLevelIndexClicked = lastPopupIndex;
  54312. break;
  54313. }
  54314. else if (indexToShowAgain >= 0)
  54315. {
  54316. menuBarItemsChanged (0);
  54317. repaint();
  54318. itemUnderMouse = indexToShowAgain;
  54319. if (((unsigned int) itemUnderMouse) >= (unsigned int) menuNames.size())
  54320. break;
  54321. }
  54322. else
  54323. {
  54324. break;
  54325. }
  54326. }
  54327. Desktop::getInstance().removeGlobalMouseListener (this);
  54328. inModalState = false;
  54329. exitModalState (0);
  54330. if (prevFocused != 0)
  54331. prevFocused->grabKeyboardFocus();
  54332. const Point<int> mousePos (getMouseXYRelative());
  54333. updateItemUnderMouse (mousePos.getX(), mousePos.getY());
  54334. repaint();
  54335. if (result != 0)
  54336. {
  54337. if (managerOfChosenCommand != 0)
  54338. {
  54339. ApplicationCommandTarget::InvocationInfo info (result);
  54340. info.invocationMethod = ApplicationCommandTarget::InvocationInfo::fromMenu;
  54341. managerOfChosenCommand->invoke (info, true);
  54342. }
  54343. postCommandMessage (result);
  54344. }
  54345. }
  54346. }
  54347. void MenuBarComponent::handleCommandMessage (int commandId)
  54348. {
  54349. if (model != 0)
  54350. model->menuItemSelected (commandId, topLevelIndexClicked);
  54351. }
  54352. void MenuBarComponent::mouseEnter (const MouseEvent& e)
  54353. {
  54354. if (e.eventComponent == this)
  54355. updateItemUnderMouse (e.x, e.y);
  54356. }
  54357. void MenuBarComponent::mouseExit (const MouseEvent& e)
  54358. {
  54359. if (e.eventComponent == this)
  54360. updateItemUnderMouse (e.x, e.y);
  54361. }
  54362. void MenuBarComponent::mouseDown (const MouseEvent& e)
  54363. {
  54364. if (currentPopupIndex < 0)
  54365. {
  54366. const MouseEvent e2 (e.getEventRelativeTo (this));
  54367. updateItemUnderMouse (e2.x, e2.y);
  54368. currentPopupIndex = -2;
  54369. showMenu (itemUnderMouse);
  54370. }
  54371. }
  54372. void MenuBarComponent::mouseDrag (const MouseEvent& e)
  54373. {
  54374. const MouseEvent e2 (e.getEventRelativeTo (this));
  54375. const int item = getItemAt (e2.x, e2.y);
  54376. if (item >= 0)
  54377. showMenu (item);
  54378. }
  54379. void MenuBarComponent::mouseUp (const MouseEvent& e)
  54380. {
  54381. const MouseEvent e2 (e.getEventRelativeTo (this));
  54382. updateItemUnderMouse (e2.x, e2.y);
  54383. if (itemUnderMouse < 0 && dynamic_cast <DummyMenuComponent*> (static_cast <Component*> (currentPopup)) != 0)
  54384. hideCurrentMenu();
  54385. }
  54386. void MenuBarComponent::mouseMove (const MouseEvent& e)
  54387. {
  54388. const MouseEvent e2 (e.getEventRelativeTo (this));
  54389. if (lastMouseX != e2.x || lastMouseY != e2.y)
  54390. {
  54391. if (currentPopupIndex >= 0)
  54392. {
  54393. const int item = getItemAt (e2.x, e2.y);
  54394. if (item >= 0)
  54395. showMenu (item);
  54396. }
  54397. else
  54398. {
  54399. updateItemUnderMouse (e2.x, e2.y);
  54400. }
  54401. lastMouseX = e2.x;
  54402. lastMouseY = e2.y;
  54403. }
  54404. }
  54405. bool MenuBarComponent::keyPressed (const KeyPress& key)
  54406. {
  54407. bool used = false;
  54408. const int numMenus = menuNames.size();
  54409. const int currentIndex = jlimit (0, menuNames.size() - 1, currentPopupIndex);
  54410. if (key.isKeyCode (KeyPress::leftKey))
  54411. {
  54412. showMenu ((currentIndex + numMenus - 1) % numMenus);
  54413. used = true;
  54414. }
  54415. else if (key.isKeyCode (KeyPress::rightKey))
  54416. {
  54417. showMenu ((currentIndex + 1) % numMenus);
  54418. used = true;
  54419. }
  54420. return used;
  54421. }
  54422. void MenuBarComponent::inputAttemptWhenModal()
  54423. {
  54424. hideCurrentMenu();
  54425. }
  54426. void MenuBarComponent::menuBarItemsChanged (MenuBarModel* /*menuBarModel*/)
  54427. {
  54428. StringArray newNames;
  54429. if (model != 0)
  54430. newNames = model->getMenuBarNames();
  54431. if (newNames != menuNames)
  54432. {
  54433. menuNames = newNames;
  54434. repaint();
  54435. resized();
  54436. }
  54437. }
  54438. void MenuBarComponent::menuCommandInvoked (MenuBarModel* /*menuBarModel*/,
  54439. const ApplicationCommandTarget::InvocationInfo& info)
  54440. {
  54441. if (model == 0
  54442. || (info.commandFlags & ApplicationCommandInfo::dontTriggerVisualFeedback) != 0)
  54443. return;
  54444. for (int i = 0; i < menuNames.size(); ++i)
  54445. {
  54446. const PopupMenu menu (model->getMenuForIndex (i, menuNames [i]));
  54447. if (menu.containsCommandItem (info.commandID))
  54448. {
  54449. itemUnderMouse = i;
  54450. repaintMenuItem (i);
  54451. startTimer (200);
  54452. break;
  54453. }
  54454. }
  54455. }
  54456. void MenuBarComponent::timerCallback()
  54457. {
  54458. stopTimer();
  54459. const Point<int> mousePos (getMouseXYRelative());
  54460. updateItemUnderMouse (mousePos.getX(), mousePos.getY());
  54461. }
  54462. END_JUCE_NAMESPACE
  54463. /*** End of inlined file: juce_MenuBarComponent.cpp ***/
  54464. /*** Start of inlined file: juce_MenuBarModel.cpp ***/
  54465. BEGIN_JUCE_NAMESPACE
  54466. MenuBarModel::MenuBarModel() throw()
  54467. : manager (0)
  54468. {
  54469. }
  54470. MenuBarModel::~MenuBarModel()
  54471. {
  54472. setApplicationCommandManagerToWatch (0);
  54473. }
  54474. void MenuBarModel::menuItemsChanged()
  54475. {
  54476. triggerAsyncUpdate();
  54477. }
  54478. void MenuBarModel::setApplicationCommandManagerToWatch (ApplicationCommandManager* const newManager) throw()
  54479. {
  54480. if (manager != newManager)
  54481. {
  54482. if (manager != 0)
  54483. manager->removeListener (this);
  54484. manager = newManager;
  54485. if (manager != 0)
  54486. manager->addListener (this);
  54487. }
  54488. }
  54489. void MenuBarModel::addListener (MenuBarModelListener* const newListener) throw()
  54490. {
  54491. listeners.add (newListener);
  54492. }
  54493. void MenuBarModel::removeListener (MenuBarModelListener* const listenerToRemove) throw()
  54494. {
  54495. // Trying to remove a listener that isn't on the list!
  54496. // If this assertion happens because this object is a dangling pointer, make sure you've not
  54497. // deleted this menu model while it's still being used by something (e.g. by a MenuBarComponent)
  54498. jassert (listeners.contains (listenerToRemove));
  54499. listeners.remove (listenerToRemove);
  54500. }
  54501. void MenuBarModel::handleAsyncUpdate()
  54502. {
  54503. listeners.call (&MenuBarModelListener::menuBarItemsChanged, this);
  54504. }
  54505. void MenuBarModel::applicationCommandInvoked (const ApplicationCommandTarget::InvocationInfo& info)
  54506. {
  54507. listeners.call (&MenuBarModelListener::menuCommandInvoked, this, info);
  54508. }
  54509. void MenuBarModel::applicationCommandListChanged()
  54510. {
  54511. menuItemsChanged();
  54512. }
  54513. END_JUCE_NAMESPACE
  54514. /*** End of inlined file: juce_MenuBarModel.cpp ***/
  54515. /*** Start of inlined file: juce_PopupMenu.cpp ***/
  54516. BEGIN_JUCE_NAMESPACE
  54517. class PopupMenu::Item
  54518. {
  54519. public:
  54520. Item()
  54521. : itemId (0), active (true), isSeparator (true), isTicked (false),
  54522. usesColour (false), customComp (0), commandManager (0)
  54523. {
  54524. }
  54525. Item (const int itemId_,
  54526. const String& text_,
  54527. const bool active_,
  54528. const bool isTicked_,
  54529. const Image* im,
  54530. const Colour& textColour_,
  54531. const bool usesColour_,
  54532. PopupMenuCustomComponent* const customComp_,
  54533. const PopupMenu* const subMenu_,
  54534. ApplicationCommandManager* const commandManager_)
  54535. : itemId (itemId_), text (text_), textColour (textColour_),
  54536. active (active_), isSeparator (false), isTicked (isTicked_),
  54537. usesColour (usesColour_), customComp (customComp_),
  54538. commandManager (commandManager_)
  54539. {
  54540. if (subMenu_ != 0)
  54541. subMenu = new PopupMenu (*subMenu_);
  54542. if (im != 0)
  54543. image = im->createCopy();
  54544. if (commandManager_ != 0 && itemId_ != 0)
  54545. {
  54546. String shortcutKey;
  54547. Array <KeyPress> keyPresses (commandManager_->getKeyMappings()
  54548. ->getKeyPressesAssignedToCommand (itemId_));
  54549. for (int i = 0; i < keyPresses.size(); ++i)
  54550. {
  54551. const String key (keyPresses.getReference(i).getTextDescription());
  54552. if (shortcutKey.isNotEmpty())
  54553. shortcutKey << ", ";
  54554. if (key.length() == 1)
  54555. shortcutKey << "shortcut: '" << key << '\'';
  54556. else
  54557. shortcutKey << key;
  54558. }
  54559. shortcutKey = shortcutKey.trim();
  54560. if (shortcutKey.isNotEmpty())
  54561. text << "<end>" << shortcutKey;
  54562. }
  54563. }
  54564. Item (const Item& other)
  54565. : itemId (other.itemId),
  54566. text (other.text),
  54567. textColour (other.textColour),
  54568. active (other.active),
  54569. isSeparator (other.isSeparator),
  54570. isTicked (other.isTicked),
  54571. usesColour (other.usesColour),
  54572. customComp (other.customComp),
  54573. commandManager (other.commandManager)
  54574. {
  54575. if (other.subMenu != 0)
  54576. subMenu = new PopupMenu (*(other.subMenu));
  54577. if (other.image != 0)
  54578. image = other.image->createCopy();
  54579. }
  54580. ~Item()
  54581. {
  54582. customComp = 0;
  54583. }
  54584. bool canBeTriggered() const throw()
  54585. {
  54586. return active && ! (isSeparator || (subMenu != 0));
  54587. }
  54588. bool hasActiveSubMenu() const throw()
  54589. {
  54590. return active && (subMenu != 0);
  54591. }
  54592. const int itemId;
  54593. String text;
  54594. const Colour textColour;
  54595. const bool active, isSeparator, isTicked, usesColour;
  54596. ScopedPointer <Image> image;
  54597. ReferenceCountedObjectPtr <PopupMenuCustomComponent> customComp;
  54598. ScopedPointer <PopupMenu> subMenu;
  54599. ApplicationCommandManager* const commandManager;
  54600. juce_UseDebuggingNewOperator
  54601. private:
  54602. Item& operator= (const Item&);
  54603. };
  54604. class PopupMenu::ItemComponent : public Component
  54605. {
  54606. public:
  54607. ItemComponent (const PopupMenu::Item& itemInfo_)
  54608. : itemInfo (itemInfo_),
  54609. isHighlighted (false)
  54610. {
  54611. if (itemInfo.customComp != 0)
  54612. addAndMakeVisible (itemInfo.customComp);
  54613. }
  54614. ~ItemComponent()
  54615. {
  54616. if (itemInfo.customComp != 0)
  54617. removeChildComponent (itemInfo.customComp);
  54618. }
  54619. void getIdealSize (int& idealWidth,
  54620. int& idealHeight,
  54621. const int standardItemHeight)
  54622. {
  54623. if (itemInfo.customComp != 0)
  54624. {
  54625. itemInfo.customComp->getIdealSize (idealWidth, idealHeight);
  54626. }
  54627. else
  54628. {
  54629. getLookAndFeel().getIdealPopupMenuItemSize (itemInfo.text,
  54630. itemInfo.isSeparator,
  54631. standardItemHeight,
  54632. idealWidth,
  54633. idealHeight);
  54634. }
  54635. }
  54636. void paint (Graphics& g)
  54637. {
  54638. if (itemInfo.customComp == 0)
  54639. {
  54640. String mainText (itemInfo.text);
  54641. String endText;
  54642. const int endIndex = mainText.indexOf ("<end>");
  54643. if (endIndex >= 0)
  54644. {
  54645. endText = mainText.substring (endIndex + 5).trim();
  54646. mainText = mainText.substring (0, endIndex);
  54647. }
  54648. getLookAndFeel()
  54649. .drawPopupMenuItem (g, getWidth(), getHeight(),
  54650. itemInfo.isSeparator,
  54651. itemInfo.active,
  54652. isHighlighted,
  54653. itemInfo.isTicked,
  54654. itemInfo.subMenu != 0,
  54655. mainText, endText,
  54656. itemInfo.image,
  54657. itemInfo.usesColour ? &(itemInfo.textColour) : 0);
  54658. }
  54659. }
  54660. void resized()
  54661. {
  54662. if (getNumChildComponents() > 0)
  54663. getChildComponent(0)->setBounds (2, 0, getWidth() - 4, getHeight());
  54664. }
  54665. void setHighlighted (bool shouldBeHighlighted)
  54666. {
  54667. shouldBeHighlighted = shouldBeHighlighted && itemInfo.active;
  54668. if (isHighlighted != shouldBeHighlighted)
  54669. {
  54670. isHighlighted = shouldBeHighlighted;
  54671. if (itemInfo.customComp != 0)
  54672. {
  54673. itemInfo.customComp->isHighlighted = shouldBeHighlighted;
  54674. itemInfo.customComp->repaint();
  54675. }
  54676. repaint();
  54677. }
  54678. }
  54679. PopupMenu::Item itemInfo;
  54680. juce_UseDebuggingNewOperator
  54681. private:
  54682. bool isHighlighted;
  54683. ItemComponent (const ItemComponent&);
  54684. ItemComponent& operator= (const ItemComponent&);
  54685. };
  54686. namespace PopupMenuSettings
  54687. {
  54688. static const int scrollZone = 24;
  54689. static const int borderSize = 2;
  54690. static const int timerInterval = 50;
  54691. static const int dismissCommandId = 0x6287345f;
  54692. }
  54693. class PopupMenu::Window : public Component,
  54694. private Timer
  54695. {
  54696. public:
  54697. Window()
  54698. : Component ("menu"),
  54699. owner (0),
  54700. currentChild (0),
  54701. activeSubMenu (0),
  54702. menuBarComponent (0),
  54703. managerOfChosenCommand (0),
  54704. minimumWidth (0),
  54705. maximumNumColumns (7),
  54706. standardItemHeight (0),
  54707. isOver (false),
  54708. hasBeenOver (false),
  54709. isDown (false),
  54710. needsToScroll (false),
  54711. hideOnExit (false),
  54712. disableMouseMoves (false),
  54713. hasAnyJuceCompHadFocus (false),
  54714. numColumns (0),
  54715. contentHeight (0),
  54716. childYOffset (0),
  54717. timeEnteredCurrentChildComp (0),
  54718. scrollAcceleration (1.0)
  54719. {
  54720. menuCreationTime = lastFocused = lastScroll = Time::getMillisecondCounter();
  54721. setWantsKeyboardFocus (true);
  54722. setMouseClickGrabsKeyboardFocus (false);
  54723. setOpaque (true);
  54724. setAlwaysOnTop (true);
  54725. Desktop::getInstance().addGlobalMouseListener (this);
  54726. getActiveWindows().add (this);
  54727. }
  54728. ~Window()
  54729. {
  54730. getActiveWindows().removeValue (this);
  54731. Desktop::getInstance().removeGlobalMouseListener (this);
  54732. jassert (activeSubMenu == 0 || activeSubMenu->isValidComponent());
  54733. activeSubMenu = 0;
  54734. deleteAllChildren();
  54735. }
  54736. static Window* create (const PopupMenu& menu,
  54737. const bool dismissOnMouseUp,
  54738. Window* const owner_,
  54739. const int minX, const int maxX,
  54740. const int minY, const int maxY,
  54741. const int minimumWidth,
  54742. const int maximumNumColumns,
  54743. const int standardItemHeight,
  54744. const bool alignToRectangle,
  54745. const int itemIdThatMustBeVisible,
  54746. Component* const menuBarComponent,
  54747. ApplicationCommandManager** managerOfChosenCommand,
  54748. Component* const componentAttachedTo)
  54749. {
  54750. if (menu.items.size() > 0)
  54751. {
  54752. int totalItems = 0;
  54753. ScopedPointer <Window> mw (new Window());
  54754. mw->setLookAndFeel (menu.lookAndFeel);
  54755. mw->setWantsKeyboardFocus (false);
  54756. mw->minimumWidth = minimumWidth;
  54757. mw->maximumNumColumns = maximumNumColumns;
  54758. mw->standardItemHeight = standardItemHeight;
  54759. mw->dismissOnMouseUp = dismissOnMouseUp;
  54760. for (int i = 0; i < menu.items.size(); ++i)
  54761. {
  54762. PopupMenu::Item* const item = menu.items.getUnchecked(i);
  54763. mw->addItem (*item);
  54764. ++totalItems;
  54765. }
  54766. if (totalItems > 0)
  54767. {
  54768. mw->owner = owner_;
  54769. mw->menuBarComponent = menuBarComponent;
  54770. mw->managerOfChosenCommand = managerOfChosenCommand;
  54771. mw->componentAttachedTo = componentAttachedTo;
  54772. mw->componentAttachedToOriginal = componentAttachedTo;
  54773. mw->calculateWindowPos (minX, maxX, minY, maxY, alignToRectangle);
  54774. mw->setTopLeftPosition (mw->windowPos.getX(),
  54775. mw->windowPos.getY());
  54776. mw->updateYPositions();
  54777. if (itemIdThatMustBeVisible != 0)
  54778. {
  54779. const int y = minY - mw->windowPos.getY();
  54780. mw->ensureItemIsVisible (itemIdThatMustBeVisible,
  54781. (((unsigned int) y) < (unsigned int) mw->windowPos.getHeight()) ? y : -1);
  54782. }
  54783. mw->resizeToBestWindowPos();
  54784. mw->addToDesktop (ComponentPeer::windowIsTemporary
  54785. | mw->getLookAndFeel().getMenuWindowFlags());
  54786. return mw.release();
  54787. }
  54788. }
  54789. return 0;
  54790. }
  54791. void paint (Graphics& g)
  54792. {
  54793. getLookAndFeel().drawPopupMenuBackground (g, getWidth(), getHeight());
  54794. }
  54795. void paintOverChildren (Graphics& g)
  54796. {
  54797. if (isScrolling())
  54798. {
  54799. LookAndFeel& lf = getLookAndFeel();
  54800. if (isScrollZoneActive (false))
  54801. lf.drawPopupMenuUpDownArrow (g, getWidth(), PopupMenuSettings::scrollZone, true);
  54802. if (isScrollZoneActive (true))
  54803. {
  54804. g.setOrigin (0, getHeight() - PopupMenuSettings::scrollZone);
  54805. lf.drawPopupMenuUpDownArrow (g, getWidth(), PopupMenuSettings::scrollZone, false);
  54806. }
  54807. }
  54808. }
  54809. bool isScrollZoneActive (bool bottomOne) const
  54810. {
  54811. return isScrolling()
  54812. && (bottomOne
  54813. ? childYOffset < contentHeight - windowPos.getHeight()
  54814. : childYOffset > 0);
  54815. }
  54816. void addItem (const PopupMenu::Item& item)
  54817. {
  54818. PopupMenu::ItemComponent* const mic = new PopupMenu::ItemComponent (item);
  54819. addAndMakeVisible (mic);
  54820. int itemW = 80;
  54821. int itemH = 16;
  54822. mic->getIdealSize (itemW, itemH, standardItemHeight);
  54823. mic->setSize (itemW, jlimit (2, 600, itemH));
  54824. mic->addMouseListener (this, false);
  54825. }
  54826. // hide this and all sub-comps
  54827. void hide (const PopupMenu::Item* const item)
  54828. {
  54829. if (isVisible())
  54830. {
  54831. jassert (activeSubMenu == 0 || activeSubMenu->isValidComponent());
  54832. activeSubMenu = 0;
  54833. currentChild = 0;
  54834. exitModalState (item != 0 ? item->itemId : 0);
  54835. setVisible (false);
  54836. if (item != 0
  54837. && item->commandManager != 0
  54838. && item->itemId != 0)
  54839. {
  54840. *managerOfChosenCommand = item->commandManager;
  54841. }
  54842. }
  54843. }
  54844. void dismissMenu (const PopupMenu::Item* const item)
  54845. {
  54846. if (owner != 0)
  54847. {
  54848. owner->dismissMenu (item);
  54849. }
  54850. else
  54851. {
  54852. if (item != 0)
  54853. {
  54854. // need a copy of this on the stack as the one passed in will get deleted during this call
  54855. const PopupMenu::Item mi (*item);
  54856. hide (&mi);
  54857. }
  54858. else
  54859. {
  54860. hide (0);
  54861. }
  54862. }
  54863. }
  54864. void mouseMove (const MouseEvent&)
  54865. {
  54866. timerCallback();
  54867. }
  54868. void mouseDown (const MouseEvent&)
  54869. {
  54870. timerCallback();
  54871. }
  54872. void mouseDrag (const MouseEvent&)
  54873. {
  54874. timerCallback();
  54875. }
  54876. void mouseUp (const MouseEvent&)
  54877. {
  54878. timerCallback();
  54879. }
  54880. void mouseWheelMove (const MouseEvent&, float /*amountX*/, float amountY)
  54881. {
  54882. alterChildYPos (roundToInt (-10.0f * amountY * PopupMenuSettings::scrollZone));
  54883. lastMouse = Point<int> (-1, -1);
  54884. }
  54885. bool keyPressed (const KeyPress& key)
  54886. {
  54887. if (key.isKeyCode (KeyPress::downKey))
  54888. {
  54889. selectNextItem (1);
  54890. }
  54891. else if (key.isKeyCode (KeyPress::upKey))
  54892. {
  54893. selectNextItem (-1);
  54894. }
  54895. else if (key.isKeyCode (KeyPress::leftKey))
  54896. {
  54897. if (owner != 0)
  54898. {
  54899. Component::SafePointer<Window> parentWindow (owner);
  54900. PopupMenu::ItemComponent* currentChildOfParent = parentWindow->currentChild;
  54901. hide (0);
  54902. if (parentWindow != 0)
  54903. parentWindow->setCurrentlyHighlightedChild (currentChildOfParent);
  54904. disableTimerUntilMouseMoves();
  54905. }
  54906. else if (menuBarComponent != 0)
  54907. {
  54908. menuBarComponent->keyPressed (key);
  54909. }
  54910. }
  54911. else if (key.isKeyCode (KeyPress::rightKey))
  54912. {
  54913. disableTimerUntilMouseMoves();
  54914. if (showSubMenuFor (currentChild))
  54915. {
  54916. jassert (activeSubMenu == 0 || activeSubMenu->isValidComponent());
  54917. if (activeSubMenu != 0 && activeSubMenu->isVisible())
  54918. activeSubMenu->selectNextItem (1);
  54919. }
  54920. else if (menuBarComponent != 0)
  54921. {
  54922. menuBarComponent->keyPressed (key);
  54923. }
  54924. }
  54925. else if (key.isKeyCode (KeyPress::returnKey))
  54926. {
  54927. triggerCurrentlyHighlightedItem();
  54928. }
  54929. else if (key.isKeyCode (KeyPress::escapeKey))
  54930. {
  54931. dismissMenu (0);
  54932. }
  54933. else
  54934. {
  54935. return false;
  54936. }
  54937. return true;
  54938. }
  54939. void inputAttemptWhenModal()
  54940. {
  54941. timerCallback();
  54942. if (! isOverAnyMenu())
  54943. {
  54944. if (componentAttachedTo != 0)
  54945. {
  54946. // we want to dismiss the menu, but if we do it synchronously, then
  54947. // the mouse-click will be allowed to pass through. That's good, except
  54948. // when the user clicks on the button that orginally popped the menu up,
  54949. // as they'll expect the menu to go away, and in fact it'll just
  54950. // come back. So only dismiss synchronously if they're not on the original
  54951. // comp that we're attached to.
  54952. const Point<int> mousePos (componentAttachedTo->getMouseXYRelative());
  54953. if (componentAttachedTo->reallyContains (mousePos.getX(), mousePos.getY(), true))
  54954. {
  54955. postCommandMessage (PopupMenuSettings::dismissCommandId); // dismiss asynchrounously
  54956. return;
  54957. }
  54958. }
  54959. dismissMenu (0);
  54960. }
  54961. }
  54962. void handleCommandMessage (int commandId)
  54963. {
  54964. Component::handleCommandMessage (commandId);
  54965. if (commandId == PopupMenuSettings::dismissCommandId)
  54966. dismissMenu (0);
  54967. }
  54968. void timerCallback()
  54969. {
  54970. if (! isVisible())
  54971. return;
  54972. if (componentAttachedTo != componentAttachedToOriginal)
  54973. {
  54974. dismissMenu (0);
  54975. return;
  54976. }
  54977. Window* currentlyModalWindow = dynamic_cast <Window*> (Component::getCurrentlyModalComponent());
  54978. if (currentlyModalWindow != 0 && ! treeContains (currentlyModalWindow))
  54979. return;
  54980. startTimer (PopupMenuSettings::timerInterval); // do this in case it was called from a mouse
  54981. // move rather than a real timer callback
  54982. const Point<int> globalMousePos (Desktop::getMousePosition());
  54983. const Point<int> localMousePos (globalPositionToRelative (globalMousePos));
  54984. const uint32 now = Time::getMillisecondCounter();
  54985. if (now > timeEnteredCurrentChildComp + 100
  54986. && reallyContains (localMousePos.getX(), localMousePos.getY(), true)
  54987. && currentChild->isValidComponent()
  54988. && (! disableMouseMoves)
  54989. && ! (activeSubMenu != 0 && activeSubMenu->isVisible()))
  54990. {
  54991. showSubMenuFor (currentChild);
  54992. }
  54993. if (globalMousePos != lastMouse || now > lastMouseMoveTime + 350)
  54994. {
  54995. highlightItemUnderMouse (globalMousePos, localMousePos);
  54996. }
  54997. bool overScrollArea = false;
  54998. if (isScrolling()
  54999. && (isOver || (isDown && ((unsigned int) localMousePos.getX()) < (unsigned int) getWidth()))
  55000. && ((isScrollZoneActive (false) && localMousePos.getY() < PopupMenuSettings::scrollZone)
  55001. || (isScrollZoneActive (true) && localMousePos.getY() > getHeight() - PopupMenuSettings::scrollZone)))
  55002. {
  55003. if (now > lastScroll + 20)
  55004. {
  55005. scrollAcceleration = jmin (4.0, scrollAcceleration * 1.04);
  55006. int amount = 0;
  55007. for (int i = 0; i < getNumChildComponents() && amount == 0; ++i)
  55008. amount = ((int) scrollAcceleration) * getChildComponent (i)->getHeight();
  55009. alterChildYPos (localMousePos.getY() < PopupMenuSettings::scrollZone ? -amount : amount);
  55010. lastScroll = now;
  55011. }
  55012. overScrollArea = true;
  55013. lastMouse = Point<int> (-1, -1); // trigger a mouse-move
  55014. }
  55015. else
  55016. {
  55017. scrollAcceleration = 1.0;
  55018. }
  55019. const bool wasDown = isDown;
  55020. bool isOverAny = isOverAnyMenu();
  55021. if (hideOnExit && hasBeenOver && (! isOverAny) && activeSubMenu != 0)
  55022. {
  55023. activeSubMenu->updateMouseOverStatus (globalMousePos);
  55024. isOverAny = isOverAnyMenu();
  55025. }
  55026. if (hideOnExit && hasBeenOver && ! isOverAny)
  55027. {
  55028. hide (0);
  55029. }
  55030. else
  55031. {
  55032. isDown = hasBeenOver
  55033. && (ModifierKeys::getCurrentModifiers().isAnyMouseButtonDown()
  55034. || ModifierKeys::getCurrentModifiersRealtime().isAnyMouseButtonDown());
  55035. bool anyFocused = Process::isForegroundProcess();
  55036. if (anyFocused && Component::getCurrentlyFocusedComponent() == 0)
  55037. {
  55038. // because no component at all may have focus, our test here will
  55039. // only be triggered when something has focus and then loses it.
  55040. anyFocused = ! hasAnyJuceCompHadFocus;
  55041. for (int i = ComponentPeer::getNumPeers(); --i >= 0;)
  55042. {
  55043. if (ComponentPeer::getPeer (i)->isFocused())
  55044. {
  55045. anyFocused = true;
  55046. hasAnyJuceCompHadFocus = true;
  55047. break;
  55048. }
  55049. }
  55050. }
  55051. if (! anyFocused)
  55052. {
  55053. if (now > lastFocused + 10)
  55054. {
  55055. wasHiddenBecauseOfAppChange() = true;
  55056. dismissMenu (0);
  55057. return; // may have been deleted by the previous call..
  55058. }
  55059. }
  55060. else if (wasDown && now > menuCreationTime + 250
  55061. && ! (isDown || overScrollArea))
  55062. {
  55063. isOver = reallyContains (localMousePos.getX(), localMousePos.getY(), true);
  55064. if (isOver)
  55065. {
  55066. triggerCurrentlyHighlightedItem();
  55067. }
  55068. else if ((hasBeenOver || ! dismissOnMouseUp) && ! isOverAny)
  55069. {
  55070. dismissMenu (0);
  55071. }
  55072. return; // may have been deleted by the previous calls..
  55073. }
  55074. else
  55075. {
  55076. lastFocused = now;
  55077. }
  55078. }
  55079. }
  55080. static Array<Window*>& getActiveWindows()
  55081. {
  55082. static Array<Window*> activeMenuWindows;
  55083. return activeMenuWindows;
  55084. }
  55085. static bool& wasHiddenBecauseOfAppChange() throw()
  55086. {
  55087. static bool b = false;
  55088. return b;
  55089. }
  55090. juce_UseDebuggingNewOperator
  55091. private:
  55092. Window* owner;
  55093. PopupMenu::ItemComponent* currentChild;
  55094. ScopedPointer <Window> activeSubMenu;
  55095. Component* menuBarComponent;
  55096. ApplicationCommandManager** managerOfChosenCommand;
  55097. Component::SafePointer<Component> componentAttachedTo;
  55098. Component* componentAttachedToOriginal;
  55099. Rectangle<int> windowPos;
  55100. Point<int> lastMouse;
  55101. int minimumWidth, maximumNumColumns, standardItemHeight;
  55102. bool isOver, hasBeenOver, isDown, needsToScroll;
  55103. bool dismissOnMouseUp, hideOnExit, disableMouseMoves, hasAnyJuceCompHadFocus;
  55104. int numColumns, contentHeight, childYOffset;
  55105. Array <int> columnWidths;
  55106. uint32 menuCreationTime, lastFocused, lastScroll, lastMouseMoveTime, timeEnteredCurrentChildComp;
  55107. double scrollAcceleration;
  55108. bool overlaps (const Rectangle<int>& r) const
  55109. {
  55110. return r.intersects (getBounds())
  55111. || (owner != 0 && owner->overlaps (r));
  55112. }
  55113. bool isOverAnyMenu() const
  55114. {
  55115. return (owner != 0) ? owner->isOverAnyMenu()
  55116. : isOverChildren();
  55117. }
  55118. bool isOverChildren() const
  55119. {
  55120. jassert (activeSubMenu == 0 || activeSubMenu->isValidComponent());
  55121. return isVisible()
  55122. && (isOver || (activeSubMenu != 0 && activeSubMenu->isOverChildren()));
  55123. }
  55124. void updateMouseOverStatus (const Point<int>& globalMousePos)
  55125. {
  55126. const Point<int> relPos (globalPositionToRelative (globalMousePos));
  55127. isOver = reallyContains (relPos.getX(), relPos.getY(), true);
  55128. if (activeSubMenu != 0)
  55129. activeSubMenu->updateMouseOverStatus (globalMousePos);
  55130. }
  55131. bool treeContains (const Window* const window) const throw()
  55132. {
  55133. const Window* mw = this;
  55134. while (mw->owner != 0)
  55135. mw = mw->owner;
  55136. while (mw != 0)
  55137. {
  55138. if (mw == window)
  55139. return true;
  55140. mw = mw->activeSubMenu;
  55141. }
  55142. return false;
  55143. }
  55144. void calculateWindowPos (const int minX, const int maxX,
  55145. const int minY, const int maxY,
  55146. const bool alignToRectangle)
  55147. {
  55148. const Rectangle<int> mon (Desktop::getInstance()
  55149. .getMonitorAreaContaining (Point<int> ((minX + maxX) / 2,
  55150. (minY + maxY) / 2),
  55151. #if JUCE_MAC
  55152. true));
  55153. #else
  55154. false)); // on windows, don't stop the menu overlapping the taskbar
  55155. #endif
  55156. int x, y, widthToUse, heightToUse;
  55157. layoutMenuItems (mon.getWidth() - 24, widthToUse, heightToUse);
  55158. if (alignToRectangle)
  55159. {
  55160. x = minX;
  55161. const int spaceUnder = mon.getHeight() - (maxY - mon.getY());
  55162. const int spaceOver = minY - mon.getY();
  55163. if (heightToUse < spaceUnder - 30 || spaceUnder >= spaceOver)
  55164. y = maxY;
  55165. else
  55166. y = minY - heightToUse;
  55167. }
  55168. else
  55169. {
  55170. bool tendTowardsRight = (minX + maxX) / 2 < mon.getCentreX();
  55171. if (owner != 0)
  55172. {
  55173. if (owner->owner != 0)
  55174. {
  55175. const bool ownerGoingRight = (owner->getX() + owner->getWidth() / 2
  55176. > owner->owner->getX() + owner->owner->getWidth() / 2);
  55177. if (ownerGoingRight && maxX + widthToUse < mon.getRight() - 4)
  55178. tendTowardsRight = true;
  55179. else if ((! ownerGoingRight) && minX > widthToUse + 4)
  55180. tendTowardsRight = false;
  55181. }
  55182. else if (maxX + widthToUse < mon.getRight() - 32)
  55183. {
  55184. tendTowardsRight = true;
  55185. }
  55186. }
  55187. const int biggestSpace = jmax (mon.getRight() - maxX,
  55188. minX - mon.getX()) - 32;
  55189. if (biggestSpace < widthToUse)
  55190. {
  55191. layoutMenuItems (biggestSpace + (maxX - minX) / 3, widthToUse, heightToUse);
  55192. if (numColumns > 1)
  55193. layoutMenuItems (biggestSpace - 4, widthToUse, heightToUse);
  55194. tendTowardsRight = (mon.getRight() - maxX) >= (minX - mon.getX());
  55195. }
  55196. if (tendTowardsRight)
  55197. x = jmin (mon.getRight() - widthToUse - 4, maxX);
  55198. else
  55199. x = jmax (mon.getX() + 4, minX - widthToUse);
  55200. y = minY;
  55201. if ((minY + maxY) / 2 > mon.getCentreY())
  55202. y = jmax (mon.getY(), maxY - heightToUse);
  55203. }
  55204. x = jmax (mon.getX() + 1, jmin (mon.getRight() - (widthToUse + 6), x));
  55205. y = jmax (mon.getY() + 1, jmin (mon.getBottom() - (heightToUse + 6), y));
  55206. windowPos.setBounds (x, y, widthToUse, heightToUse);
  55207. // sets this flag if it's big enough to obscure any of its parent menus
  55208. hideOnExit = (owner != 0)
  55209. && owner->windowPos.intersects (windowPos.expanded (-4, -4));
  55210. }
  55211. void layoutMenuItems (const int maxMenuW, int& width, int& height)
  55212. {
  55213. numColumns = 0;
  55214. contentHeight = 0;
  55215. const int maxMenuH = getParentHeight() - 24;
  55216. int totalW;
  55217. do
  55218. {
  55219. ++numColumns;
  55220. totalW = workOutBestSize (maxMenuW);
  55221. if (totalW > maxMenuW)
  55222. {
  55223. numColumns = jmax (1, numColumns - 1);
  55224. totalW = workOutBestSize (maxMenuW); // to update col widths
  55225. break;
  55226. }
  55227. else if (totalW > maxMenuW / 2 || contentHeight < maxMenuH)
  55228. {
  55229. break;
  55230. }
  55231. } while (numColumns < maximumNumColumns);
  55232. const int actualH = jmin (contentHeight, maxMenuH);
  55233. needsToScroll = contentHeight > actualH;
  55234. width = updateYPositions();
  55235. height = actualH + PopupMenuSettings::borderSize * 2;
  55236. }
  55237. int workOutBestSize (const int maxMenuW)
  55238. {
  55239. int totalW = 0;
  55240. contentHeight = 0;
  55241. int childNum = 0;
  55242. for (int col = 0; col < numColumns; ++col)
  55243. {
  55244. int i, colW = 50, colH = 0;
  55245. const int numChildren = jmin (getNumChildComponents() - childNum,
  55246. (getNumChildComponents() + numColumns - 1) / numColumns);
  55247. for (i = numChildren; --i >= 0;)
  55248. {
  55249. colW = jmax (colW, getChildComponent (childNum + i)->getWidth());
  55250. colH += getChildComponent (childNum + i)->getHeight();
  55251. }
  55252. colW = jmin (maxMenuW / jmax (1, numColumns - 2), colW + PopupMenuSettings::borderSize * 2);
  55253. columnWidths.set (col, colW);
  55254. totalW += colW;
  55255. contentHeight = jmax (contentHeight, colH);
  55256. childNum += numChildren;
  55257. }
  55258. if (totalW < minimumWidth)
  55259. {
  55260. totalW = minimumWidth;
  55261. for (int col = 0; col < numColumns; ++col)
  55262. columnWidths.set (0, totalW / numColumns);
  55263. }
  55264. return totalW;
  55265. }
  55266. void ensureItemIsVisible (const int itemId, int wantedY)
  55267. {
  55268. jassert (itemId != 0)
  55269. for (int i = getNumChildComponents(); --i >= 0;)
  55270. {
  55271. PopupMenu::ItemComponent* const m = static_cast <PopupMenu::ItemComponent*> (getChildComponent (i));
  55272. if (m != 0
  55273. && m->itemInfo.itemId == itemId
  55274. && windowPos.getHeight() > PopupMenuSettings::scrollZone * 4)
  55275. {
  55276. const int currentY = m->getY();
  55277. if (wantedY > 0 || currentY < 0 || m->getBottom() > windowPos.getHeight())
  55278. {
  55279. if (wantedY < 0)
  55280. wantedY = jlimit (PopupMenuSettings::scrollZone,
  55281. jmax (PopupMenuSettings::scrollZone,
  55282. windowPos.getHeight() - (PopupMenuSettings::scrollZone + m->getHeight())),
  55283. currentY);
  55284. const Rectangle<int> mon (Desktop::getInstance().getMonitorAreaContaining (windowPos.getPosition(), true));
  55285. int deltaY = wantedY - currentY;
  55286. windowPos.setSize (jmin (windowPos.getWidth(), mon.getWidth()),
  55287. jmin (windowPos.getHeight(), mon.getHeight()));
  55288. const int newY = jlimit (mon.getY(),
  55289. mon.getBottom() - windowPos.getHeight(),
  55290. windowPos.getY() + deltaY);
  55291. deltaY -= newY - windowPos.getY();
  55292. childYOffset -= deltaY;
  55293. windowPos.setPosition (windowPos.getX(), newY);
  55294. updateYPositions();
  55295. }
  55296. break;
  55297. }
  55298. }
  55299. }
  55300. void resizeToBestWindowPos()
  55301. {
  55302. Rectangle<int> r (windowPos);
  55303. if (childYOffset < 0)
  55304. {
  55305. r.setBounds (r.getX(), r.getY() - childYOffset,
  55306. r.getWidth(), r.getHeight() + childYOffset);
  55307. }
  55308. else if (childYOffset > 0)
  55309. {
  55310. const int spaceAtBottom = r.getHeight() - (contentHeight - childYOffset);
  55311. if (spaceAtBottom > 0)
  55312. r.setSize (r.getWidth(), r.getHeight() - spaceAtBottom);
  55313. }
  55314. setBounds (r);
  55315. updateYPositions();
  55316. }
  55317. void alterChildYPos (const int delta)
  55318. {
  55319. if (isScrolling())
  55320. {
  55321. childYOffset += delta;
  55322. if (delta < 0)
  55323. {
  55324. childYOffset = jmax (childYOffset, 0);
  55325. }
  55326. else if (delta > 0)
  55327. {
  55328. childYOffset = jmin (childYOffset,
  55329. contentHeight - windowPos.getHeight() + PopupMenuSettings::borderSize);
  55330. }
  55331. updateYPositions();
  55332. }
  55333. else
  55334. {
  55335. childYOffset = 0;
  55336. }
  55337. resizeToBestWindowPos();
  55338. repaint();
  55339. }
  55340. int updateYPositions()
  55341. {
  55342. int x = 0;
  55343. int childNum = 0;
  55344. for (int col = 0; col < numColumns; ++col)
  55345. {
  55346. const int numChildren = jmin (getNumChildComponents() - childNum,
  55347. (getNumChildComponents() + numColumns - 1) / numColumns);
  55348. const int colW = columnWidths [col];
  55349. int y = PopupMenuSettings::borderSize - (childYOffset + (getY() - windowPos.getY()));
  55350. for (int i = 0; i < numChildren; ++i)
  55351. {
  55352. Component* const c = getChildComponent (childNum + i);
  55353. c->setBounds (x, y, colW, c->getHeight());
  55354. y += c->getHeight();
  55355. }
  55356. x += colW;
  55357. childNum += numChildren;
  55358. }
  55359. return x;
  55360. }
  55361. bool isScrolling() const throw()
  55362. {
  55363. return childYOffset != 0 || needsToScroll;
  55364. }
  55365. void setCurrentlyHighlightedChild (PopupMenu::ItemComponent* const child)
  55366. {
  55367. if (currentChild->isValidComponent())
  55368. currentChild->setHighlighted (false);
  55369. currentChild = child;
  55370. if (currentChild != 0)
  55371. {
  55372. currentChild->setHighlighted (true);
  55373. timeEnteredCurrentChildComp = Time::getApproximateMillisecondCounter();
  55374. }
  55375. }
  55376. bool showSubMenuFor (PopupMenu::ItemComponent* const childComp)
  55377. {
  55378. jassert (activeSubMenu == 0 || activeSubMenu->isValidComponent());
  55379. activeSubMenu = 0;
  55380. if (childComp->isValidComponent() && childComp->itemInfo.hasActiveSubMenu())
  55381. {
  55382. const Point<int> topLeft (childComp->relativePositionToGlobal (Point<int>()));
  55383. const Point<int> bottomRight (childComp->relativePositionToGlobal (Point<int> (childComp->getWidth(), childComp->getHeight())));
  55384. activeSubMenu = Window::create (*(childComp->itemInfo.subMenu),
  55385. dismissOnMouseUp,
  55386. this,
  55387. topLeft.getX(), bottomRight.getX(), topLeft.getY(), bottomRight.getY(),
  55388. 0, maximumNumColumns,
  55389. standardItemHeight,
  55390. false, 0, menuBarComponent,
  55391. managerOfChosenCommand,
  55392. componentAttachedTo);
  55393. if (activeSubMenu != 0)
  55394. {
  55395. activeSubMenu->setVisible (true);
  55396. activeSubMenu->enterModalState (false);
  55397. activeSubMenu->toFront (false);
  55398. return true;
  55399. }
  55400. }
  55401. return false;
  55402. }
  55403. void highlightItemUnderMouse (const Point<int>& globalMousePos, const Point<int>& localMousePos)
  55404. {
  55405. isOver = reallyContains (localMousePos.getX(), localMousePos.getY(), true);
  55406. if (isOver)
  55407. hasBeenOver = true;
  55408. if (lastMouse.getDistanceFrom (globalMousePos) > 2)
  55409. {
  55410. lastMouseMoveTime = Time::getApproximateMillisecondCounter();
  55411. if (disableMouseMoves && isOver)
  55412. disableMouseMoves = false;
  55413. }
  55414. if (disableMouseMoves || (activeSubMenu != 0 && activeSubMenu->isOverChildren()))
  55415. return;
  55416. bool isMovingTowardsMenu = false;
  55417. jassert (activeSubMenu == 0 || activeSubMenu->isValidComponent())
  55418. if (isOver && (activeSubMenu != 0) && globalMousePos != lastMouse)
  55419. {
  55420. // try to intelligently guess whether the user is moving the mouse towards a currently-open
  55421. // submenu. To do this, look at whether the mouse stays inside a triangular region that
  55422. // extends from the last mouse pos to the submenu's rectangle..
  55423. float subX = (float) activeSubMenu->getScreenX();
  55424. if (activeSubMenu->getX() > getX())
  55425. {
  55426. lastMouse -= Point<int> (2, 0); // to enlarge the triangle a bit, in case the mouse only moves a couple of pixels
  55427. }
  55428. else
  55429. {
  55430. lastMouse += Point<int> (2, 0);
  55431. subX += activeSubMenu->getWidth();
  55432. }
  55433. Path areaTowardsSubMenu;
  55434. areaTowardsSubMenu.addTriangle ((float) lastMouse.getX(),
  55435. (float) lastMouse.getY(),
  55436. subX,
  55437. (float) activeSubMenu->getScreenY(),
  55438. subX,
  55439. (float) (activeSubMenu->getScreenY() + activeSubMenu->getHeight()));
  55440. isMovingTowardsMenu = areaTowardsSubMenu.contains ((float) globalMousePos.getX(), (float) globalMousePos.getY());
  55441. }
  55442. lastMouse = globalMousePos;
  55443. if (! isMovingTowardsMenu)
  55444. {
  55445. Component* c = getComponentAt (localMousePos.getX(), localMousePos.getY());
  55446. if (c == this)
  55447. c = 0;
  55448. PopupMenu::ItemComponent* mic = dynamic_cast <PopupMenu::ItemComponent*> (c);
  55449. if (mic == 0 && c != 0)
  55450. mic = c->findParentComponentOfClass ((PopupMenu::ItemComponent*) 0);
  55451. if (mic != currentChild
  55452. && (isOver || (activeSubMenu == 0) || ! activeSubMenu->isVisible()))
  55453. {
  55454. if (isOver && (c != 0) && (activeSubMenu != 0))
  55455. {
  55456. activeSubMenu->hide (0);
  55457. }
  55458. if (! isOver)
  55459. mic = 0;
  55460. setCurrentlyHighlightedChild (mic);
  55461. }
  55462. }
  55463. }
  55464. void triggerCurrentlyHighlightedItem()
  55465. {
  55466. if (currentChild->isValidComponent()
  55467. && currentChild->itemInfo.canBeTriggered()
  55468. && (currentChild->itemInfo.customComp == 0
  55469. || currentChild->itemInfo.customComp->isTriggeredAutomatically))
  55470. {
  55471. dismissMenu (&currentChild->itemInfo);
  55472. }
  55473. }
  55474. void selectNextItem (const int delta)
  55475. {
  55476. disableTimerUntilMouseMoves();
  55477. PopupMenu::ItemComponent* mic = 0;
  55478. bool wasLastOne = (currentChild == 0);
  55479. const int numItems = getNumChildComponents();
  55480. for (int i = 0; i < numItems + 1; ++i)
  55481. {
  55482. int index = (delta > 0) ? i : (numItems - 1 - i);
  55483. index = (index + numItems) % numItems;
  55484. mic = dynamic_cast <PopupMenu::ItemComponent*> (getChildComponent (index));
  55485. if (mic != 0 && (mic->itemInfo.canBeTriggered() || mic->itemInfo.hasActiveSubMenu())
  55486. && wasLastOne)
  55487. break;
  55488. if (mic == currentChild)
  55489. wasLastOne = true;
  55490. }
  55491. setCurrentlyHighlightedChild (mic);
  55492. }
  55493. void disableTimerUntilMouseMoves()
  55494. {
  55495. disableMouseMoves = true;
  55496. if (owner != 0)
  55497. owner->disableTimerUntilMouseMoves();
  55498. }
  55499. Window (const Window&);
  55500. Window& operator= (const Window&);
  55501. };
  55502. PopupMenu::PopupMenu()
  55503. : lookAndFeel (0),
  55504. separatorPending (false)
  55505. {
  55506. }
  55507. PopupMenu::PopupMenu (const PopupMenu& other)
  55508. : lookAndFeel (other.lookAndFeel),
  55509. separatorPending (false)
  55510. {
  55511. items.ensureStorageAllocated (other.items.size());
  55512. for (int i = 0; i < other.items.size(); ++i)
  55513. items.add (new Item (*other.items.getUnchecked(i)));
  55514. }
  55515. PopupMenu& PopupMenu::operator= (const PopupMenu& other)
  55516. {
  55517. if (this != &other)
  55518. {
  55519. lookAndFeel = other.lookAndFeel;
  55520. clear();
  55521. items.ensureStorageAllocated (other.items.size());
  55522. for (int i = 0; i < other.items.size(); ++i)
  55523. items.add (new Item (*other.items.getUnchecked(i)));
  55524. }
  55525. return *this;
  55526. }
  55527. PopupMenu::~PopupMenu()
  55528. {
  55529. clear();
  55530. }
  55531. void PopupMenu::clear()
  55532. {
  55533. items.clear();
  55534. separatorPending = false;
  55535. }
  55536. void PopupMenu::addSeparatorIfPending()
  55537. {
  55538. if (separatorPending)
  55539. {
  55540. separatorPending = false;
  55541. if (items.size() > 0)
  55542. items.add (new Item());
  55543. }
  55544. }
  55545. void PopupMenu::addItem (const int itemResultId,
  55546. const String& itemText,
  55547. const bool isActive,
  55548. const bool isTicked,
  55549. const Image* const iconToUse)
  55550. {
  55551. jassert (itemResultId != 0); // 0 is used as a return value to indicate that the user
  55552. // didn't pick anything, so you shouldn't use it as the id
  55553. // for an item..
  55554. addSeparatorIfPending();
  55555. items.add (new Item (itemResultId, itemText, isActive, isTicked,
  55556. iconToUse, Colours::black, false, 0, 0, 0));
  55557. }
  55558. void PopupMenu::addCommandItem (ApplicationCommandManager* commandManager,
  55559. const int commandID,
  55560. const String& displayName)
  55561. {
  55562. jassert (commandManager != 0 && commandID != 0);
  55563. const ApplicationCommandInfo* const registeredInfo = commandManager->getCommandForID (commandID);
  55564. if (registeredInfo != 0)
  55565. {
  55566. ApplicationCommandInfo info (*registeredInfo);
  55567. ApplicationCommandTarget* const target = commandManager->getTargetForCommand (commandID, info);
  55568. addSeparatorIfPending();
  55569. items.add (new Item (commandID,
  55570. displayName.isNotEmpty() ? displayName
  55571. : info.shortName,
  55572. target != 0 && (info.flags & ApplicationCommandInfo::isDisabled) == 0,
  55573. (info.flags & ApplicationCommandInfo::isTicked) != 0,
  55574. 0,
  55575. Colours::black,
  55576. false,
  55577. 0, 0,
  55578. commandManager));
  55579. }
  55580. }
  55581. void PopupMenu::addColouredItem (const int itemResultId,
  55582. const String& itemText,
  55583. const Colour& itemTextColour,
  55584. const bool isActive,
  55585. const bool isTicked,
  55586. const Image* const iconToUse)
  55587. {
  55588. jassert (itemResultId != 0); // 0 is used as a return value to indicate that the user
  55589. // didn't pick anything, so you shouldn't use it as the id
  55590. // for an item..
  55591. addSeparatorIfPending();
  55592. items.add (new Item (itemResultId, itemText, isActive, isTicked,
  55593. iconToUse, itemTextColour, true, 0, 0, 0));
  55594. }
  55595. void PopupMenu::addCustomItem (const int itemResultId,
  55596. PopupMenuCustomComponent* const customComponent)
  55597. {
  55598. jassert (itemResultId != 0); // 0 is used as a return value to indicate that the user
  55599. // didn't pick anything, so you shouldn't use it as the id
  55600. // for an item..
  55601. addSeparatorIfPending();
  55602. items.add (new Item (itemResultId, String::empty, true, false, 0,
  55603. Colours::black, false, customComponent, 0, 0));
  55604. }
  55605. class NormalComponentWrapper : public PopupMenuCustomComponent
  55606. {
  55607. public:
  55608. NormalComponentWrapper (Component* const comp,
  55609. const int w, const int h,
  55610. const bool triggerMenuItemAutomaticallyWhenClicked)
  55611. : PopupMenuCustomComponent (triggerMenuItemAutomaticallyWhenClicked),
  55612. width (w),
  55613. height (h)
  55614. {
  55615. addAndMakeVisible (comp);
  55616. }
  55617. ~NormalComponentWrapper() {}
  55618. void getIdealSize (int& idealWidth, int& idealHeight)
  55619. {
  55620. idealWidth = width;
  55621. idealHeight = height;
  55622. }
  55623. void resized()
  55624. {
  55625. if (getChildComponent(0) != 0)
  55626. getChildComponent(0)->setBounds (0, 0, getWidth(), getHeight());
  55627. }
  55628. juce_UseDebuggingNewOperator
  55629. private:
  55630. const int width, height;
  55631. NormalComponentWrapper (const NormalComponentWrapper&);
  55632. NormalComponentWrapper& operator= (const NormalComponentWrapper&);
  55633. };
  55634. void PopupMenu::addCustomItem (const int itemResultId,
  55635. Component* customComponent,
  55636. int idealWidth, int idealHeight,
  55637. const bool triggerMenuItemAutomaticallyWhenClicked)
  55638. {
  55639. addCustomItem (itemResultId,
  55640. new NormalComponentWrapper (customComponent,
  55641. idealWidth, idealHeight,
  55642. triggerMenuItemAutomaticallyWhenClicked));
  55643. }
  55644. void PopupMenu::addSubMenu (const String& subMenuName,
  55645. const PopupMenu& subMenu,
  55646. const bool isActive,
  55647. Image* const iconToUse,
  55648. const bool isTicked)
  55649. {
  55650. addSeparatorIfPending();
  55651. items.add (new Item (0, subMenuName, isActive && (subMenu.getNumItems() > 0), isTicked,
  55652. iconToUse, Colours::black, false, 0, &subMenu, 0));
  55653. }
  55654. void PopupMenu::addSeparator()
  55655. {
  55656. separatorPending = true;
  55657. }
  55658. class HeaderItemComponent : public PopupMenuCustomComponent
  55659. {
  55660. public:
  55661. HeaderItemComponent (const String& name)
  55662. : PopupMenuCustomComponent (false)
  55663. {
  55664. setName (name);
  55665. }
  55666. ~HeaderItemComponent()
  55667. {
  55668. }
  55669. void paint (Graphics& g)
  55670. {
  55671. Font f (getLookAndFeel().getPopupMenuFont());
  55672. f.setBold (true);
  55673. g.setFont (f);
  55674. g.setColour (findColour (PopupMenu::headerTextColourId));
  55675. g.drawFittedText (getName(),
  55676. 12, 0, getWidth() - 16, proportionOfHeight (0.8f),
  55677. Justification::bottomLeft, 1);
  55678. }
  55679. void getIdealSize (int& idealWidth,
  55680. int& idealHeight)
  55681. {
  55682. getLookAndFeel().getIdealPopupMenuItemSize (getName(), false, -1, idealWidth, idealHeight);
  55683. idealHeight += idealHeight / 2;
  55684. idealWidth += idealWidth / 4;
  55685. }
  55686. juce_UseDebuggingNewOperator
  55687. };
  55688. void PopupMenu::addSectionHeader (const String& title)
  55689. {
  55690. addCustomItem (0X4734a34f, new HeaderItemComponent (title));
  55691. }
  55692. Component* PopupMenu::createMenuComponent (const int x, const int y, const int w, const int h,
  55693. const int itemIdThatMustBeVisible,
  55694. const int minimumWidth,
  55695. const int maximumNumColumns,
  55696. const int standardItemHeight,
  55697. const bool alignToRectangle,
  55698. Component* menuBarComponent,
  55699. ApplicationCommandManager** managerOfChosenCommand,
  55700. Component* const componentAttachedTo)
  55701. {
  55702. Window* const pw
  55703. = Window::create (*this,
  55704. ModifierKeys::getCurrentModifiers().isAnyMouseButtonDown(),
  55705. 0,
  55706. x, x + w,
  55707. y, y + h,
  55708. minimumWidth,
  55709. maximumNumColumns,
  55710. standardItemHeight,
  55711. alignToRectangle,
  55712. itemIdThatMustBeVisible,
  55713. menuBarComponent,
  55714. managerOfChosenCommand,
  55715. componentAttachedTo);
  55716. if (pw != 0)
  55717. pw->setVisible (true);
  55718. return pw;
  55719. }
  55720. int PopupMenu::showMenu (const int x, const int y, const int w, const int h,
  55721. const int itemIdThatMustBeVisible,
  55722. const int minimumWidth,
  55723. const int maximumNumColumns,
  55724. const int standardItemHeight,
  55725. const bool alignToRectangle,
  55726. Component* const componentAttachedTo)
  55727. {
  55728. Component::SafePointer<Component> prevFocused (Component::getCurrentlyFocusedComponent());
  55729. Component::SafePointer<Component> prevTopLevel ((prevFocused != 0) ? prevFocused->getTopLevelComponent() : 0);
  55730. Window::wasHiddenBecauseOfAppChange() = false;
  55731. int result = 0;
  55732. ApplicationCommandManager* managerOfChosenCommand = 0;
  55733. ScopedPointer <Component> popupComp (createMenuComponent (x, y, w, h,
  55734. itemIdThatMustBeVisible,
  55735. minimumWidth,
  55736. maximumNumColumns > 0 ? maximumNumColumns : 7,
  55737. standardItemHeight,
  55738. alignToRectangle, 0,
  55739. &managerOfChosenCommand,
  55740. componentAttachedTo));
  55741. if (popupComp != 0)
  55742. {
  55743. popupComp->enterModalState (false);
  55744. popupComp->toFront (false); // need to do this after making it modal, or it could
  55745. // be stuck behind other comps that are already modal..
  55746. result = popupComp->runModalLoop();
  55747. popupComp = 0;
  55748. if (! Window::wasHiddenBecauseOfAppChange())
  55749. {
  55750. if (prevTopLevel != 0)
  55751. prevTopLevel->toFront (true);
  55752. if (prevFocused != 0)
  55753. prevFocused->grabKeyboardFocus();
  55754. }
  55755. }
  55756. if (managerOfChosenCommand != 0 && result != 0)
  55757. {
  55758. ApplicationCommandTarget::InvocationInfo info (result);
  55759. info.invocationMethod = ApplicationCommandTarget::InvocationInfo::fromMenu;
  55760. managerOfChosenCommand->invoke (info, true);
  55761. }
  55762. return result;
  55763. }
  55764. int PopupMenu::show (const int itemIdThatMustBeVisible,
  55765. const int minimumWidth,
  55766. const int maximumNumColumns,
  55767. const int standardItemHeight)
  55768. {
  55769. const Point<int> mousePos (Desktop::getMousePosition());
  55770. return showAt (mousePos.getX(), mousePos.getY(),
  55771. itemIdThatMustBeVisible,
  55772. minimumWidth,
  55773. maximumNumColumns,
  55774. standardItemHeight);
  55775. }
  55776. int PopupMenu::showAt (const int screenX,
  55777. const int screenY,
  55778. const int itemIdThatMustBeVisible,
  55779. const int minimumWidth,
  55780. const int maximumNumColumns,
  55781. const int standardItemHeight)
  55782. {
  55783. return showMenu (screenX, screenY, 1, 1,
  55784. itemIdThatMustBeVisible,
  55785. minimumWidth, maximumNumColumns,
  55786. standardItemHeight,
  55787. false, 0);
  55788. }
  55789. int PopupMenu::showAt (Component* componentToAttachTo,
  55790. const int itemIdThatMustBeVisible,
  55791. const int minimumWidth,
  55792. const int maximumNumColumns,
  55793. const int standardItemHeight)
  55794. {
  55795. if (componentToAttachTo != 0)
  55796. {
  55797. return showMenu (componentToAttachTo->getScreenX(),
  55798. componentToAttachTo->getScreenY(),
  55799. componentToAttachTo->getWidth(),
  55800. componentToAttachTo->getHeight(),
  55801. itemIdThatMustBeVisible,
  55802. minimumWidth,
  55803. maximumNumColumns,
  55804. standardItemHeight,
  55805. true, componentToAttachTo);
  55806. }
  55807. else
  55808. {
  55809. return show (itemIdThatMustBeVisible,
  55810. minimumWidth,
  55811. maximumNumColumns,
  55812. standardItemHeight);
  55813. }
  55814. }
  55815. void JUCE_CALLTYPE PopupMenu::dismissAllActiveMenus()
  55816. {
  55817. for (int i = Window::getActiveWindows().size(); --i >= 0;)
  55818. {
  55819. Window* const pmw = Window::getActiveWindows()[i];
  55820. if (pmw != 0)
  55821. pmw->dismissMenu (0);
  55822. }
  55823. }
  55824. int PopupMenu::getNumItems() const throw()
  55825. {
  55826. int num = 0;
  55827. for (int i = items.size(); --i >= 0;)
  55828. if (! (items.getUnchecked(i))->isSeparator)
  55829. ++num;
  55830. return num;
  55831. }
  55832. bool PopupMenu::containsCommandItem (const int commandID) const
  55833. {
  55834. for (int i = items.size(); --i >= 0;)
  55835. {
  55836. const Item* mi = items.getUnchecked (i);
  55837. if ((mi->itemId == commandID && mi->commandManager != 0)
  55838. || (mi->subMenu != 0 && mi->subMenu->containsCommandItem (commandID)))
  55839. {
  55840. return true;
  55841. }
  55842. }
  55843. return false;
  55844. }
  55845. bool PopupMenu::containsAnyActiveItems() const throw()
  55846. {
  55847. for (int i = items.size(); --i >= 0;)
  55848. {
  55849. const Item* const mi = items.getUnchecked (i);
  55850. if (mi->subMenu != 0)
  55851. {
  55852. if (mi->subMenu->containsAnyActiveItems())
  55853. return true;
  55854. }
  55855. else if (mi->active)
  55856. {
  55857. return true;
  55858. }
  55859. }
  55860. return false;
  55861. }
  55862. void PopupMenu::setLookAndFeel (LookAndFeel* const newLookAndFeel)
  55863. {
  55864. lookAndFeel = newLookAndFeel;
  55865. }
  55866. PopupMenuCustomComponent::PopupMenuCustomComponent (const bool isTriggeredAutomatically_)
  55867. : isHighlighted (false),
  55868. isTriggeredAutomatically (isTriggeredAutomatically_)
  55869. {
  55870. }
  55871. PopupMenuCustomComponent::~PopupMenuCustomComponent()
  55872. {
  55873. }
  55874. void PopupMenuCustomComponent::triggerMenuItem()
  55875. {
  55876. PopupMenu::ItemComponent* const mic = dynamic_cast <PopupMenu::ItemComponent*> (getParentComponent());
  55877. if (mic != 0)
  55878. {
  55879. PopupMenu::Window* const pmw = dynamic_cast <PopupMenu::Window*> (mic->getParentComponent());
  55880. if (pmw != 0)
  55881. {
  55882. pmw->dismissMenu (&mic->itemInfo);
  55883. }
  55884. else
  55885. {
  55886. // something must have gone wrong with the component hierarchy if this happens..
  55887. jassertfalse
  55888. }
  55889. }
  55890. else
  55891. {
  55892. // why isn't this component inside a menu? Not much point triggering the item if
  55893. // there's no menu.
  55894. jassertfalse
  55895. }
  55896. }
  55897. PopupMenu::MenuItemIterator::MenuItemIterator (const PopupMenu& menu_)
  55898. : subMenu (0),
  55899. itemId (0),
  55900. isSeparator (false),
  55901. isTicked (false),
  55902. isEnabled (false),
  55903. isCustomComponent (false),
  55904. isSectionHeader (false),
  55905. customColour (0),
  55906. customImage (0),
  55907. menu (menu_),
  55908. index (0)
  55909. {
  55910. }
  55911. PopupMenu::MenuItemIterator::~MenuItemIterator()
  55912. {
  55913. }
  55914. bool PopupMenu::MenuItemIterator::next()
  55915. {
  55916. if (index >= menu.items.size())
  55917. return false;
  55918. const Item* const item = menu.items.getUnchecked (index);
  55919. ++index;
  55920. itemName = item->customComp != 0 ? item->customComp->getName() : item->text;
  55921. subMenu = item->subMenu;
  55922. itemId = item->itemId;
  55923. isSeparator = item->isSeparator;
  55924. isTicked = item->isTicked;
  55925. isEnabled = item->active;
  55926. isSectionHeader = dynamic_cast <HeaderItemComponent*> ((PopupMenuCustomComponent*) item->customComp) != 0;
  55927. isCustomComponent = (! isSectionHeader) && item->customComp != 0;
  55928. customColour = item->usesColour ? &(item->textColour) : 0;
  55929. customImage = item->image;
  55930. commandManager = item->commandManager;
  55931. return true;
  55932. }
  55933. END_JUCE_NAMESPACE
  55934. /*** End of inlined file: juce_PopupMenu.cpp ***/
  55935. /*** Start of inlined file: juce_ComponentDragger.cpp ***/
  55936. BEGIN_JUCE_NAMESPACE
  55937. ComponentDragger::ComponentDragger()
  55938. : constrainer (0)
  55939. {
  55940. }
  55941. ComponentDragger::~ComponentDragger()
  55942. {
  55943. }
  55944. void ComponentDragger::startDraggingComponent (Component* const componentToDrag,
  55945. ComponentBoundsConstrainer* const constrainer_)
  55946. {
  55947. jassert (componentToDrag->isValidComponent());
  55948. if (componentToDrag != 0)
  55949. {
  55950. constrainer = constrainer_;
  55951. originalPos = componentToDrag->relativePositionToGlobal (Point<int>());
  55952. }
  55953. }
  55954. void ComponentDragger::dragComponent (Component* const componentToDrag, const MouseEvent& e)
  55955. {
  55956. jassert (componentToDrag->isValidComponent());
  55957. jassert (e.mods.isAnyMouseButtonDown()); // (the event has to be a drag event..)
  55958. if (componentToDrag != 0)
  55959. {
  55960. Rectangle<int> bounds (componentToDrag->getBounds().withPosition (originalPos));
  55961. const Component* const parentComp = componentToDrag->getParentComponent();
  55962. if (parentComp != 0)
  55963. bounds.setPosition (parentComp->globalPositionToRelative (originalPos));
  55964. bounds.setPosition (bounds.getPosition() + e.getOffsetFromDragStart());
  55965. if (constrainer != 0)
  55966. constrainer->setBoundsForComponent (componentToDrag, bounds, false, false, false, false);
  55967. else
  55968. componentToDrag->setBounds (bounds);
  55969. }
  55970. }
  55971. END_JUCE_NAMESPACE
  55972. /*** End of inlined file: juce_ComponentDragger.cpp ***/
  55973. /*** Start of inlined file: juce_DragAndDropContainer.cpp ***/
  55974. BEGIN_JUCE_NAMESPACE
  55975. bool juce_performDragDropFiles (const StringArray& files, const bool copyFiles, bool& shouldStop);
  55976. bool juce_performDragDropText (const String& text, bool& shouldStop);
  55977. class DragImageComponent : public Component,
  55978. public Timer
  55979. {
  55980. public:
  55981. DragImageComponent (Image* const im,
  55982. const String& desc,
  55983. Component* const sourceComponent,
  55984. Component* const mouseDragSource_,
  55985. DragAndDropContainer* const o,
  55986. const Point<int>& imageOffset_)
  55987. : image (im),
  55988. source (sourceComponent),
  55989. mouseDragSource (mouseDragSource_),
  55990. owner (o),
  55991. dragDesc (desc),
  55992. imageOffset (imageOffset_),
  55993. hasCheckedForExternalDrag (false),
  55994. drawImage (true)
  55995. {
  55996. setSize (im->getWidth(), im->getHeight());
  55997. if (mouseDragSource == 0)
  55998. mouseDragSource = source;
  55999. mouseDragSource->addMouseListener (this, false);
  56000. startTimer (200);
  56001. setInterceptsMouseClicks (false, false);
  56002. setAlwaysOnTop (true);
  56003. }
  56004. ~DragImageComponent()
  56005. {
  56006. if (owner->dragImageComponent == this)
  56007. owner->dragImageComponent.release();
  56008. if (mouseDragSource != 0)
  56009. {
  56010. mouseDragSource->removeMouseListener (this);
  56011. if (getCurrentlyOver() != 0 && getCurrentlyOver()->isInterestedInDragSource (dragDesc, source))
  56012. getCurrentlyOver()->itemDragExit (dragDesc, source);
  56013. }
  56014. }
  56015. void paint (Graphics& g)
  56016. {
  56017. if (isOpaque())
  56018. g.fillAll (Colours::white);
  56019. if (drawImage)
  56020. {
  56021. g.setOpacity (1.0f);
  56022. g.drawImageAt (image, 0, 0);
  56023. }
  56024. }
  56025. DragAndDropTarget* findTarget (const Point<int>& screenPos, Point<int>& relativePos)
  56026. {
  56027. Component* hit = getParentComponent();
  56028. if (hit == 0)
  56029. {
  56030. hit = Desktop::getInstance().findComponentAt (screenPos);
  56031. }
  56032. else
  56033. {
  56034. const Point<int> relPos (hit->globalPositionToRelative (screenPos));
  56035. hit = hit->getComponentAt (relPos.getX(), relPos.getY());
  56036. }
  56037. // (note: use a local copy of the dragDesc member in case the callback runs
  56038. // a modal loop and deletes this object before the method completes)
  56039. const String dragDescLocal (dragDesc);
  56040. while (hit != 0)
  56041. {
  56042. DragAndDropTarget* const ddt = dynamic_cast <DragAndDropTarget*> (hit);
  56043. if (ddt != 0 && ddt->isInterestedInDragSource (dragDescLocal, source))
  56044. {
  56045. relativePos = hit->globalPositionToRelative (screenPos);
  56046. return ddt;
  56047. }
  56048. hit = hit->getParentComponent();
  56049. }
  56050. return 0;
  56051. }
  56052. void mouseUp (const MouseEvent& e)
  56053. {
  56054. if (e.originalComponent != this)
  56055. {
  56056. if (mouseDragSource != 0)
  56057. mouseDragSource->removeMouseListener (this);
  56058. bool dropAccepted = false;
  56059. DragAndDropTarget* ddt = 0;
  56060. Point<int> relPos;
  56061. if (isVisible())
  56062. {
  56063. setVisible (false);
  56064. ddt = findTarget (e.getScreenPosition(), relPos);
  56065. // fade this component and remove it - it'll be deleted later by the timer callback
  56066. dropAccepted = ddt != 0;
  56067. setVisible (true);
  56068. if (dropAccepted || source == 0)
  56069. {
  56070. fadeOutComponent (120);
  56071. }
  56072. else
  56073. {
  56074. const Point<int> target (source->relativePositionToGlobal (Point<int> (source->getWidth() / 2,
  56075. source->getHeight() / 2)));
  56076. const Point<int> ourCentre (relativePositionToGlobal (Point<int> (getWidth() / 2,
  56077. getHeight() / 2)));
  56078. fadeOutComponent (120,
  56079. target.getX() - ourCentre.getX(),
  56080. target.getY() - ourCentre.getY());
  56081. }
  56082. }
  56083. if (getParentComponent() != 0)
  56084. getParentComponent()->removeChildComponent (this);
  56085. if (dropAccepted && ddt != 0)
  56086. {
  56087. // (note: use a local copy of the dragDesc member in case the callback runs
  56088. // a modal loop and deletes this object before the method completes)
  56089. const String dragDescLocal (dragDesc);
  56090. currentlyOverComp = 0;
  56091. ddt->itemDropped (dragDescLocal, source, relPos.getX(), relPos.getY());
  56092. }
  56093. // careful - this object could now be deleted..
  56094. }
  56095. }
  56096. void updateLocation (const bool canDoExternalDrag, const Point<int>& screenPos)
  56097. {
  56098. // (note: use a local copy of the dragDesc member in case the callback runs
  56099. // a modal loop and deletes this object before it returns)
  56100. const String dragDescLocal (dragDesc);
  56101. Point<int> newPos (screenPos + imageOffset);
  56102. if (getParentComponent() != 0)
  56103. newPos = getParentComponent()->globalPositionToRelative (newPos);
  56104. //if (newX != getX() || newY != getY())
  56105. {
  56106. setTopLeftPosition (newPos.getX(), newPos.getY());
  56107. Point<int> relPos;
  56108. DragAndDropTarget* const ddt = findTarget (screenPos, relPos);
  56109. Component* ddtComp = dynamic_cast <Component*> (ddt);
  56110. drawImage = (ddt == 0) || ddt->shouldDrawDragImageWhenOver();
  56111. if (ddtComp != currentlyOverComp)
  56112. {
  56113. if (currentlyOverComp != 0 && source != 0
  56114. && getCurrentlyOver()->isInterestedInDragSource (dragDescLocal, source))
  56115. {
  56116. getCurrentlyOver()->itemDragExit (dragDescLocal, source);
  56117. }
  56118. currentlyOverComp = ddtComp;
  56119. if (ddt != 0 && ddt->isInterestedInDragSource (dragDescLocal, source))
  56120. ddt->itemDragEnter (dragDescLocal, source, relPos.getX(), relPos.getY());
  56121. }
  56122. if (getCurrentlyOver() != 0 && getCurrentlyOver()->isInterestedInDragSource (dragDescLocal, source))
  56123. getCurrentlyOver()->itemDragMove (dragDescLocal, source, relPos.getX(), relPos.getY());
  56124. if (getCurrentlyOver() == 0
  56125. && canDoExternalDrag
  56126. && ! hasCheckedForExternalDrag)
  56127. {
  56128. if (Desktop::getInstance().findComponentAt (screenPos) == 0)
  56129. {
  56130. hasCheckedForExternalDrag = true;
  56131. StringArray files;
  56132. bool canMoveFiles = false;
  56133. if (owner->shouldDropFilesWhenDraggedExternally (dragDescLocal, source, files, canMoveFiles)
  56134. && files.size() > 0)
  56135. {
  56136. Component::SafePointer<Component> cdw (this);
  56137. setVisible (false);
  56138. if (ModifierKeys::getCurrentModifiersRealtime().isAnyMouseButtonDown())
  56139. DragAndDropContainer::performExternalDragDropOfFiles (files, canMoveFiles);
  56140. if (cdw != 0)
  56141. delete this;
  56142. return;
  56143. }
  56144. }
  56145. }
  56146. }
  56147. }
  56148. void mouseDrag (const MouseEvent& e)
  56149. {
  56150. if (e.originalComponent != this)
  56151. updateLocation (true, e.getScreenPosition());
  56152. }
  56153. void timerCallback()
  56154. {
  56155. if (source == 0)
  56156. {
  56157. delete this;
  56158. }
  56159. else if (! isMouseButtonDownAnywhere())
  56160. {
  56161. if (mouseDragSource != 0)
  56162. mouseDragSource->removeMouseListener (this);
  56163. delete this;
  56164. }
  56165. }
  56166. private:
  56167. ScopedPointer<Image> image;
  56168. Component::SafePointer<Component> source;
  56169. Component::SafePointer<Component> mouseDragSource;
  56170. DragAndDropContainer* const owner;
  56171. Component::SafePointer<Component> currentlyOverComp;
  56172. DragAndDropTarget* getCurrentlyOver()
  56173. {
  56174. return dynamic_cast <DragAndDropTarget*> (static_cast <Component*> (currentlyOverComp));
  56175. }
  56176. String dragDesc;
  56177. const Point<int> imageOffset;
  56178. bool hasCheckedForExternalDrag, drawImage;
  56179. DragImageComponent (const DragImageComponent&);
  56180. DragImageComponent& operator= (const DragImageComponent&);
  56181. };
  56182. DragAndDropContainer::DragAndDropContainer()
  56183. {
  56184. }
  56185. DragAndDropContainer::~DragAndDropContainer()
  56186. {
  56187. dragImageComponent = 0;
  56188. }
  56189. void DragAndDropContainer::startDragging (const String& sourceDescription,
  56190. Component* sourceComponent,
  56191. Image* dragImage_,
  56192. const bool allowDraggingToExternalWindows,
  56193. const Point<int>* imageOffsetFromMouse)
  56194. {
  56195. ScopedPointer <Image> dragImage (dragImage_);
  56196. if (dragImageComponent == 0)
  56197. {
  56198. Component* const thisComp = dynamic_cast <Component*> (this);
  56199. if (thisComp == 0)
  56200. {
  56201. jassertfalse; // Your DragAndDropContainer needs to be a Component!
  56202. return;
  56203. }
  56204. MouseInputSource* draggingSource = Desktop::getInstance().getDraggingMouseSource (0);
  56205. if (draggingSource == 0 || ! draggingSource->isDragging())
  56206. {
  56207. jassertfalse; // You must call startDragging() from within a mouseDown or mouseDrag callback!
  56208. return;
  56209. }
  56210. const Point<int> lastMouseDown (Desktop::getLastMouseDownPosition());
  56211. Point<int> imageOffset;
  56212. if (dragImage == 0)
  56213. {
  56214. dragImage = sourceComponent->createComponentSnapshot (sourceComponent->getLocalBounds());
  56215. if (dragImage->getFormat() != Image::ARGB)
  56216. {
  56217. Image* newIm = Image::createNativeImage (Image::ARGB, dragImage->getWidth(), dragImage->getHeight(), true);
  56218. Graphics g2 (*newIm);
  56219. g2.drawImageAt (dragImage, 0, 0);
  56220. dragImage = newIm;
  56221. }
  56222. dragImage->multiplyAllAlphas (0.6f);
  56223. const int lo = 150;
  56224. const int hi = 400;
  56225. Point<int> relPos (sourceComponent->globalPositionToRelative (lastMouseDown));
  56226. Point<int> clipped (dragImage->getBounds().getConstrainedPoint (relPos));
  56227. for (int y = dragImage->getHeight(); --y >= 0;)
  56228. {
  56229. const double dy = (y - clipped.getY()) * (y - clipped.getY());
  56230. for (int x = dragImage->getWidth(); --x >= 0;)
  56231. {
  56232. const int dx = x - clipped.getX();
  56233. const int distance = roundToInt (std::sqrt (dx * dx + dy));
  56234. if (distance > lo)
  56235. {
  56236. const float alpha = (distance > hi) ? 0
  56237. : (hi - distance) / (float) (hi - lo)
  56238. + Random::getSystemRandom().nextFloat() * 0.008f;
  56239. dragImage->multiplyAlphaAt (x, y, alpha);
  56240. }
  56241. }
  56242. }
  56243. imageOffset = -clipped;
  56244. }
  56245. else
  56246. {
  56247. if (imageOffsetFromMouse == 0)
  56248. imageOffset = -dragImage->getBounds().getCentre();
  56249. else
  56250. imageOffset = -(dragImage->getBounds().getConstrainedPoint (-*imageOffsetFromMouse));
  56251. }
  56252. dragImageComponent = new DragImageComponent (dragImage.release(), sourceDescription, sourceComponent,
  56253. draggingSource->getComponentUnderMouse(), this, imageOffset);
  56254. currentDragDesc = sourceDescription;
  56255. if (allowDraggingToExternalWindows)
  56256. {
  56257. if (! Desktop::canUseSemiTransparentWindows())
  56258. dragImageComponent->setOpaque (true);
  56259. dragImageComponent->addToDesktop (ComponentPeer::windowIgnoresMouseClicks
  56260. | ComponentPeer::windowIsTemporary
  56261. | ComponentPeer::windowIgnoresKeyPresses);
  56262. }
  56263. else
  56264. thisComp->addChildComponent (dragImageComponent);
  56265. static_cast <DragImageComponent*> (static_cast <Component*> (dragImageComponent))->updateLocation (false, lastMouseDown);
  56266. dragImageComponent->setVisible (true);
  56267. }
  56268. }
  56269. bool DragAndDropContainer::isDragAndDropActive() const
  56270. {
  56271. return dragImageComponent != 0;
  56272. }
  56273. const String DragAndDropContainer::getCurrentDragDescription() const
  56274. {
  56275. return (dragImageComponent != 0) ? currentDragDesc
  56276. : String::empty;
  56277. }
  56278. DragAndDropContainer* DragAndDropContainer::findParentDragContainerFor (Component* c)
  56279. {
  56280. if (c == 0)
  56281. return 0;
  56282. // (unable to use the syntax findParentComponentOfClass <DragAndDropContainer> () because of a VC6 compiler bug)
  56283. return c->findParentComponentOfClass ((DragAndDropContainer*) 0);
  56284. }
  56285. bool DragAndDropContainer::shouldDropFilesWhenDraggedExternally (const String&, Component*, StringArray&, bool&)
  56286. {
  56287. return false;
  56288. }
  56289. void DragAndDropTarget::itemDragEnter (const String&, Component*, int, int)
  56290. {
  56291. }
  56292. void DragAndDropTarget::itemDragMove (const String&, Component*, int, int)
  56293. {
  56294. }
  56295. void DragAndDropTarget::itemDragExit (const String&, Component*)
  56296. {
  56297. }
  56298. bool DragAndDropTarget::shouldDrawDragImageWhenOver()
  56299. {
  56300. return true;
  56301. }
  56302. void FileDragAndDropTarget::fileDragEnter (const StringArray&, int, int)
  56303. {
  56304. }
  56305. void FileDragAndDropTarget::fileDragMove (const StringArray&, int, int)
  56306. {
  56307. }
  56308. void FileDragAndDropTarget::fileDragExit (const StringArray&)
  56309. {
  56310. }
  56311. END_JUCE_NAMESPACE
  56312. /*** End of inlined file: juce_DragAndDropContainer.cpp ***/
  56313. /*** Start of inlined file: juce_MouseCursor.cpp ***/
  56314. BEGIN_JUCE_NAMESPACE
  56315. class MouseCursor::SharedCursorHandle
  56316. {
  56317. public:
  56318. explicit SharedCursorHandle (const MouseCursor::StandardCursorType type)
  56319. : handle (createStandardMouseCursor (type)),
  56320. refCount (1),
  56321. standardType (type),
  56322. isStandard (true)
  56323. {
  56324. }
  56325. SharedCursorHandle (const Image& image, const int hotSpotX, const int hotSpotY)
  56326. : handle (createMouseCursorFromImage (image, hotSpotX, hotSpotY)),
  56327. refCount (1),
  56328. standardType (MouseCursor::NormalCursor),
  56329. isStandard (false)
  56330. {
  56331. }
  56332. static SharedCursorHandle* createStandard (const MouseCursor::StandardCursorType type)
  56333. {
  56334. const ScopedLock sl (getLock());
  56335. for (int i = getCursors().size(); --i >= 0;)
  56336. {
  56337. SharedCursorHandle* const sc = getCursors().getUnchecked(i);
  56338. if (sc->standardType == type)
  56339. return sc->retain();
  56340. }
  56341. SharedCursorHandle* const sc = new SharedCursorHandle (type);
  56342. getCursors().add (sc);
  56343. return sc;
  56344. }
  56345. SharedCursorHandle* retain() throw()
  56346. {
  56347. ++refCount;
  56348. return this;
  56349. }
  56350. void release()
  56351. {
  56352. if (--refCount == 0)
  56353. {
  56354. if (isStandard)
  56355. {
  56356. const ScopedLock sl (getLock());
  56357. getCursors().removeValue (this);
  56358. }
  56359. delete this;
  56360. }
  56361. }
  56362. void* getHandle() const throw() { return handle; }
  56363. juce_UseDebuggingNewOperator
  56364. private:
  56365. void* const handle;
  56366. Atomic <int> refCount;
  56367. const MouseCursor::StandardCursorType standardType;
  56368. const bool isStandard;
  56369. static CriticalSection& getLock()
  56370. {
  56371. static CriticalSection lock;
  56372. return lock;
  56373. }
  56374. static Array <SharedCursorHandle*>& getCursors()
  56375. {
  56376. static Array <SharedCursorHandle*> cursors;
  56377. return cursors;
  56378. }
  56379. ~SharedCursorHandle()
  56380. {
  56381. deleteMouseCursor (handle, isStandard);
  56382. }
  56383. SharedCursorHandle& operator= (const SharedCursorHandle&);
  56384. };
  56385. MouseCursor::MouseCursor()
  56386. : cursorHandle (SharedCursorHandle::createStandard (NormalCursor))
  56387. {
  56388. jassert (cursorHandle != 0);
  56389. }
  56390. MouseCursor::MouseCursor (const StandardCursorType type)
  56391. : cursorHandle (SharedCursorHandle::createStandard (type))
  56392. {
  56393. jassert (cursorHandle != 0);
  56394. }
  56395. MouseCursor::MouseCursor (const Image& image, const int hotSpotX, const int hotSpotY)
  56396. : cursorHandle (new SharedCursorHandle (image, hotSpotX, hotSpotY))
  56397. {
  56398. }
  56399. MouseCursor::MouseCursor (const MouseCursor& other)
  56400. : cursorHandle (other.cursorHandle->retain())
  56401. {
  56402. }
  56403. MouseCursor::~MouseCursor()
  56404. {
  56405. cursorHandle->release();
  56406. }
  56407. MouseCursor& MouseCursor::operator= (const MouseCursor& other)
  56408. {
  56409. other.cursorHandle->retain();
  56410. cursorHandle->release();
  56411. cursorHandle = other.cursorHandle;
  56412. return *this;
  56413. }
  56414. bool MouseCursor::operator== (const MouseCursor& other) const throw()
  56415. {
  56416. return getHandle() == other.getHandle();
  56417. }
  56418. bool MouseCursor::operator!= (const MouseCursor& other) const throw()
  56419. {
  56420. return getHandle() != other.getHandle();
  56421. }
  56422. void* MouseCursor::getHandle() const throw()
  56423. {
  56424. return cursorHandle->getHandle();
  56425. }
  56426. void MouseCursor::showWaitCursor()
  56427. {
  56428. Desktop::getInstance().getMainMouseSource().showMouseCursor (MouseCursor::WaitCursor);
  56429. }
  56430. void MouseCursor::hideWaitCursor()
  56431. {
  56432. Desktop::getInstance().getMainMouseSource().revealCursor();
  56433. }
  56434. END_JUCE_NAMESPACE
  56435. /*** End of inlined file: juce_MouseCursor.cpp ***/
  56436. /*** Start of inlined file: juce_MouseEvent.cpp ***/
  56437. BEGIN_JUCE_NAMESPACE
  56438. MouseEvent::MouseEvent (MouseInputSource& source_,
  56439. const Point<int>& position,
  56440. const ModifierKeys& mods_,
  56441. Component* const originator,
  56442. const Time& eventTime_,
  56443. const Point<int> mouseDownPos_,
  56444. const Time& mouseDownTime_,
  56445. const int numberOfClicks_,
  56446. const bool mouseWasDragged) throw()
  56447. : x (position.getX()),
  56448. y (position.getY()),
  56449. mods (mods_),
  56450. eventComponent (originator),
  56451. originalComponent (originator),
  56452. eventTime (eventTime_),
  56453. source (source_),
  56454. mouseDownPos (mouseDownPos_),
  56455. mouseDownTime (mouseDownTime_),
  56456. numberOfClicks (numberOfClicks_),
  56457. wasMovedSinceMouseDown (mouseWasDragged)
  56458. {
  56459. }
  56460. MouseEvent::~MouseEvent() throw()
  56461. {
  56462. }
  56463. const MouseEvent MouseEvent::getEventRelativeTo (Component* const otherComponent) const throw()
  56464. {
  56465. if (otherComponent == 0)
  56466. {
  56467. jassertfalse
  56468. return *this;
  56469. }
  56470. return MouseEvent (source, eventComponent->relativePositionToOtherComponent (otherComponent, getPosition()),
  56471. mods, originalComponent, eventTime,
  56472. eventComponent->relativePositionToOtherComponent (otherComponent, mouseDownPos),
  56473. mouseDownTime, numberOfClicks, wasMovedSinceMouseDown);
  56474. }
  56475. const MouseEvent MouseEvent::withNewPosition (const Point<int>& newPosition) const throw()
  56476. {
  56477. return MouseEvent (source, newPosition, mods, originalComponent,
  56478. eventTime, mouseDownPos, mouseDownTime,
  56479. numberOfClicks, wasMovedSinceMouseDown);
  56480. }
  56481. bool MouseEvent::mouseWasClicked() const throw()
  56482. {
  56483. return ! wasMovedSinceMouseDown;
  56484. }
  56485. int MouseEvent::getMouseDownX() const throw()
  56486. {
  56487. return mouseDownPos.getX();
  56488. }
  56489. int MouseEvent::getMouseDownY() const throw()
  56490. {
  56491. return mouseDownPos.getY();
  56492. }
  56493. const Point<int> MouseEvent::getMouseDownPosition() const throw()
  56494. {
  56495. return mouseDownPos;
  56496. }
  56497. int MouseEvent::getDistanceFromDragStartX() const throw()
  56498. {
  56499. return x - mouseDownPos.getX();
  56500. }
  56501. int MouseEvent::getDistanceFromDragStartY() const throw()
  56502. {
  56503. return y - mouseDownPos.getY();
  56504. }
  56505. int MouseEvent::getDistanceFromDragStart() const throw()
  56506. {
  56507. return mouseDownPos.getDistanceFrom (getPosition());
  56508. }
  56509. const Point<int> MouseEvent::getOffsetFromDragStart() const throw()
  56510. {
  56511. return getPosition() - mouseDownPos;
  56512. }
  56513. int MouseEvent::getLengthOfMousePress() const throw()
  56514. {
  56515. if (mouseDownTime.toMilliseconds() > 0)
  56516. return jmax (0, (int) (eventTime - mouseDownTime).inMilliseconds());
  56517. return 0;
  56518. }
  56519. const Point<int> MouseEvent::getPosition() const throw()
  56520. {
  56521. return Point<int> (x, y);
  56522. }
  56523. int MouseEvent::getScreenX() const
  56524. {
  56525. return getScreenPosition().getX();
  56526. }
  56527. int MouseEvent::getScreenY() const
  56528. {
  56529. return getScreenPosition().getY();
  56530. }
  56531. const Point<int> MouseEvent::getScreenPosition() const
  56532. {
  56533. return eventComponent->relativePositionToGlobal (Point<int> (x, y));
  56534. }
  56535. int MouseEvent::getMouseDownScreenX() const
  56536. {
  56537. return getMouseDownScreenPosition().getX();
  56538. }
  56539. int MouseEvent::getMouseDownScreenY() const
  56540. {
  56541. return getMouseDownScreenPosition().getY();
  56542. }
  56543. const Point<int> MouseEvent::getMouseDownScreenPosition() const
  56544. {
  56545. return eventComponent->relativePositionToGlobal (mouseDownPos);
  56546. }
  56547. static int doubleClickTimeOutMs = 400;
  56548. void MouseEvent::setDoubleClickTimeout (const int newTime) throw()
  56549. {
  56550. doubleClickTimeOutMs = newTime;
  56551. }
  56552. int MouseEvent::getDoubleClickTimeout() throw()
  56553. {
  56554. return doubleClickTimeOutMs;
  56555. }
  56556. END_JUCE_NAMESPACE
  56557. /*** End of inlined file: juce_MouseEvent.cpp ***/
  56558. /*** Start of inlined file: juce_MouseInputSource.cpp ***/
  56559. BEGIN_JUCE_NAMESPACE
  56560. class MouseInputSourceInternal : public AsyncUpdater
  56561. {
  56562. public:
  56563. MouseInputSourceInternal (MouseInputSource& source_, const int index_, const bool isMouseDevice_)
  56564. : index (index_), isMouseDevice (isMouseDevice_), source (source_), lastPeer (0), lastTime (0),
  56565. isUnboundedMouseModeOn (false), isCursorVisibleUntilOffscreen (false), currentCursorHandle (0),
  56566. mouseEventCounter (0)
  56567. {
  56568. zerostruct (mouseDowns);
  56569. }
  56570. ~MouseInputSourceInternal()
  56571. {
  56572. }
  56573. bool isDragging() const throw()
  56574. {
  56575. return buttonState.isAnyMouseButtonDown();
  56576. }
  56577. Component* getComponentUnderMouse() const
  56578. {
  56579. return static_cast <Component*> (componentUnderMouse);
  56580. }
  56581. const ModifierKeys getCurrentModifiers() const
  56582. {
  56583. return ModifierKeys::getCurrentModifiers().withoutMouseButtons().withFlags (buttonState.getRawFlags());
  56584. }
  56585. ComponentPeer* getPeer()
  56586. {
  56587. if (! ComponentPeer::isValidPeer (lastPeer))
  56588. lastPeer = 0;
  56589. return lastPeer;
  56590. }
  56591. Component* findComponentAt (const Point<int>& screenPos)
  56592. {
  56593. ComponentPeer* const peer = getPeer();
  56594. if (peer != 0)
  56595. {
  56596. Component* const comp = peer->getComponent();
  56597. const Point<int> relativePos (comp->globalPositionToRelative (screenPos));
  56598. // (the contains() call is needed to test for overlapping desktop windows)
  56599. if (comp->contains (relativePos.getX(), relativePos.getY()))
  56600. return comp->getComponentAt (relativePos);
  56601. }
  56602. return 0;
  56603. }
  56604. const Point<int> getScreenPosition() const throw()
  56605. {
  56606. return lastScreenPos + unboundedMouseOffset;
  56607. }
  56608. void sendMouseEnter (Component* const comp, const Point<int>& screenPos, const int64 time)
  56609. {
  56610. //DBG ("Mouse " + String (source.getIndex()) + " enter: " + comp->globalPositionToRelative (screenPos).toString() + " - Comp: " + String::toHexString ((int) comp));
  56611. comp->internalMouseEnter (source, comp->globalPositionToRelative (screenPos), time);
  56612. }
  56613. void sendMouseExit (Component* const comp, const Point<int>& screenPos, const int64 time)
  56614. {
  56615. //DBG ("Mouse " + String (source.getIndex()) + " exit: " + comp->globalPositionToRelative (screenPos).toString() + " - Comp: " + String::toHexString ((int) comp));
  56616. comp->internalMouseExit (source, comp->globalPositionToRelative (screenPos), time);
  56617. }
  56618. void sendMouseMove (Component* const comp, const Point<int>& screenPos, const int64 time)
  56619. {
  56620. //DBG ("Mouse " + String (source.getIndex()) + " move: " + comp->globalPositionToRelative (screenPos).toString() + " - Comp: " + String::toHexString ((int) comp));
  56621. comp->internalMouseMove (source, comp->globalPositionToRelative (screenPos), time);
  56622. }
  56623. void sendMouseDown (Component* const comp, const Point<int>& screenPos, const int64 time)
  56624. {
  56625. //DBG ("Mouse " + String (source.getIndex()) + " down: " + comp->globalPositionToRelative (screenPos).toString() + " - Comp: " + String::toHexString ((int) comp));
  56626. comp->internalMouseDown (source, comp->globalPositionToRelative (screenPos), time);
  56627. }
  56628. void sendMouseDrag (Component* const comp, const Point<int>& screenPos, const int64 time)
  56629. {
  56630. //DBG ("Mouse " + String (source.getIndex()) + " drag: " + comp->globalPositionToRelative (screenPos).toString() + " - Comp: " + String::toHexString ((int) comp));
  56631. comp->internalMouseDrag (source, comp->globalPositionToRelative (screenPos), time);
  56632. }
  56633. void sendMouseUp (Component* const comp, const Point<int>& screenPos, const int64 time)
  56634. {
  56635. //DBG ("Mouse " + String (source.getIndex()) + " up: " + comp->globalPositionToRelative (screenPos).toString() + " - Comp: " + String::toHexString ((int) comp));
  56636. comp->internalMouseUp (source, comp->globalPositionToRelative (screenPos), time, getCurrentModifiers());
  56637. }
  56638. void sendMouseWheel (Component* const comp, const Point<int>& screenPos, const int64 time, float x, float y)
  56639. {
  56640. //DBG ("Mouse " + String (source.getIndex()) + " wheel: " + comp->globalPositionToRelative (screenPos).toString() + " - Comp: " + String::toHexString ((int) comp));
  56641. comp->internalMouseWheel (source, comp->globalPositionToRelative (screenPos), time, x, y);
  56642. }
  56643. // (returns true if the button change caused a modal event loop)
  56644. bool setButtons (const Point<int>& screenPos, const int64 time, const ModifierKeys& newButtonState)
  56645. {
  56646. if (buttonState == newButtonState)
  56647. return false;
  56648. // (ignore secondary clicks when there's already a button down)
  56649. if (buttonState.isAnyMouseButtonDown() == newButtonState.isAnyMouseButtonDown())
  56650. {
  56651. buttonState = newButtonState;
  56652. return false;
  56653. }
  56654. const int lastCounter = mouseEventCounter;
  56655. if (buttonState.isAnyMouseButtonDown())
  56656. {
  56657. Component* const current = getComponentUnderMouse();
  56658. if (current != 0)
  56659. sendMouseUp (current, screenPos + unboundedMouseOffset, time);
  56660. enableUnboundedMouseMovement (false, false);
  56661. }
  56662. buttonState = newButtonState;
  56663. if (buttonState.isAnyMouseButtonDown())
  56664. {
  56665. Desktop::getInstance().incrementMouseClickCounter();
  56666. Component* const current = getComponentUnderMouse();
  56667. if (current != 0)
  56668. {
  56669. registerMouseDown (screenPos, time, current);
  56670. sendMouseDown (current, screenPos, time);
  56671. }
  56672. }
  56673. return lastCounter != mouseEventCounter;
  56674. }
  56675. void setComponentUnderMouse (Component* const newComponent, const Point<int>& screenPos, const int64 time)
  56676. {
  56677. Component* current = getComponentUnderMouse();
  56678. if (newComponent != current)
  56679. {
  56680. Component::SafePointer<Component> safeNewComp (newComponent);
  56681. const ModifierKeys originalButtonState (buttonState);
  56682. if (current != 0)
  56683. {
  56684. setButtons (screenPos, time, ModifierKeys());
  56685. sendMouseExit (current, screenPos, time);
  56686. buttonState = originalButtonState;
  56687. }
  56688. componentUnderMouse = safeNewComp;
  56689. current = getComponentUnderMouse();
  56690. if (current != 0)
  56691. sendMouseEnter (current, screenPos, time);
  56692. revealCursor (false);
  56693. setButtons (screenPos, time, originalButtonState);
  56694. }
  56695. }
  56696. void setPeer (ComponentPeer* const newPeer, const Point<int>& screenPos, const int64 time)
  56697. {
  56698. ModifierKeys::updateCurrentModifiers();
  56699. if (newPeer != lastPeer)
  56700. {
  56701. setComponentUnderMouse (0, screenPos, time);
  56702. lastPeer = newPeer;
  56703. setComponentUnderMouse (findComponentAt (screenPos), screenPos, time);
  56704. }
  56705. }
  56706. void setScreenPos (const Point<int>& newScreenPos, const int64 time, const bool forceUpdate)
  56707. {
  56708. if (! isDragging())
  56709. setComponentUnderMouse (findComponentAt (newScreenPos), newScreenPos, time);
  56710. if (newScreenPos != lastScreenPos || forceUpdate)
  56711. {
  56712. cancelPendingUpdate();
  56713. lastScreenPos = newScreenPos;
  56714. Component* const current = getComponentUnderMouse();
  56715. if (current != 0)
  56716. {
  56717. if (isDragging())
  56718. {
  56719. registerMouseDrag (newScreenPos);
  56720. sendMouseDrag (current, newScreenPos + unboundedMouseOffset, time);
  56721. if (isUnboundedMouseModeOn)
  56722. handleUnboundedDrag (current);
  56723. }
  56724. else
  56725. {
  56726. sendMouseMove (current, newScreenPos, time);
  56727. }
  56728. }
  56729. revealCursor (false);
  56730. }
  56731. }
  56732. void handleEvent (ComponentPeer* const newPeer, const Point<int>& positionWithinPeer, const int64 time, const ModifierKeys& newMods)
  56733. {
  56734. jassert (newPeer != 0);
  56735. lastTime = time;
  56736. ++mouseEventCounter;
  56737. const Point<int> screenPos (newPeer->relativePositionToGlobal (positionWithinPeer));
  56738. if (isDragging() && newMods.isAnyMouseButtonDown())
  56739. {
  56740. setScreenPos (screenPos, time, false);
  56741. }
  56742. else
  56743. {
  56744. setPeer (newPeer, screenPos, time);
  56745. ComponentPeer* peer = getPeer();
  56746. if (peer != 0)
  56747. {
  56748. if (setButtons (screenPos, time, newMods))
  56749. return; // some modal events have been dispatched, so the current event is now out-of-date
  56750. peer = getPeer();
  56751. if (peer != 0)
  56752. setScreenPos (screenPos, time, false);
  56753. }
  56754. }
  56755. }
  56756. void handleWheel (ComponentPeer* const peer, const Point<int>& positionWithinPeer, int64 time, float x, float y)
  56757. {
  56758. jassert (peer != 0);
  56759. lastTime = time;
  56760. ++mouseEventCounter;
  56761. const Point<int> screenPos (peer->relativePositionToGlobal (positionWithinPeer));
  56762. setPeer (peer, screenPos, time);
  56763. setScreenPos (screenPos, time, false);
  56764. triggerFakeMove();
  56765. if (! isDragging())
  56766. {
  56767. Component* current = getComponentUnderMouse();
  56768. if (current != 0)
  56769. sendMouseWheel (current, screenPos, time, x, y);
  56770. }
  56771. }
  56772. const Time getLastMouseDownTime() const throw()
  56773. {
  56774. return Time (mouseDowns[0].time);
  56775. }
  56776. const Point<int> getLastMouseDownPosition() const throw()
  56777. {
  56778. return mouseDowns[0].position;
  56779. }
  56780. int getNumberOfMultipleClicks() const throw()
  56781. {
  56782. int numClicks = 0;
  56783. if (mouseDowns[0].time != 0)
  56784. {
  56785. if (! mouseMovedSignificantlySincePressed)
  56786. ++numClicks;
  56787. for (int i = 1; i < numElementsInArray (mouseDowns); ++i)
  56788. {
  56789. if (mouseDowns[0].time - mouseDowns[i].time < (int) (MouseEvent::getDoubleClickTimeout() * (1.0 + 0.25 * (i - 1)))
  56790. && abs (mouseDowns[0].position.getX() - mouseDowns[i].position.getX()) < 8
  56791. && abs (mouseDowns[0].position.getY() - mouseDowns[i].position.getY()) < 8
  56792. && mouseDowns[0].component == mouseDowns[i].component)
  56793. {
  56794. ++numClicks;
  56795. }
  56796. else
  56797. {
  56798. break;
  56799. }
  56800. }
  56801. }
  56802. return numClicks;
  56803. }
  56804. bool hasMouseMovedSignificantlySincePressed() const throw()
  56805. {
  56806. return mouseMovedSignificantlySincePressed
  56807. || lastTime > mouseDowns[0].time + 300;
  56808. }
  56809. void triggerFakeMove()
  56810. {
  56811. triggerAsyncUpdate();
  56812. }
  56813. void handleAsyncUpdate()
  56814. {
  56815. if (! isDragging())
  56816. setScreenPos (Desktop::getMousePosition(), jmax (lastTime, Time::currentTimeMillis()), true);
  56817. }
  56818. void enableUnboundedMouseMovement (bool enable, bool keepCursorVisibleUntilOffscreen)
  56819. {
  56820. enable = enable && isDragging();
  56821. isCursorVisibleUntilOffscreen = keepCursorVisibleUntilOffscreen;
  56822. if (enable != isUnboundedMouseModeOn)
  56823. {
  56824. if ((! enable) && ((! isCursorVisibleUntilOffscreen) || ! unboundedMouseOffset.isOrigin()))
  56825. {
  56826. // when released, return the mouse to within the component's bounds
  56827. Component* current = getComponentUnderMouse();
  56828. if (current != 0)
  56829. Desktop::setMousePosition (current->getScreenBounds()
  56830. .getConstrainedPoint (current->getMouseXYRelative()));
  56831. }
  56832. isUnboundedMouseModeOn = enable;
  56833. unboundedMouseOffset = Point<int>();
  56834. revealCursor (true);
  56835. }
  56836. }
  56837. void handleUnboundedDrag (Component* current)
  56838. {
  56839. const Rectangle<int> screenArea (current->getParentMonitorArea().expanded (-2, -2));
  56840. if (! screenArea.contains (lastScreenPos))
  56841. {
  56842. const Point<int> componentCentre (current->getScreenBounds().getCentre());
  56843. unboundedMouseOffset += (lastScreenPos - componentCentre);
  56844. Desktop::setMousePosition (componentCentre);
  56845. }
  56846. else if (isCursorVisibleUntilOffscreen
  56847. && (! unboundedMouseOffset.isOrigin())
  56848. && screenArea.contains (lastScreenPos + unboundedMouseOffset))
  56849. {
  56850. Desktop::setMousePosition (lastScreenPos + unboundedMouseOffset);
  56851. unboundedMouseOffset = Point<int>();
  56852. }
  56853. }
  56854. void showMouseCursor (MouseCursor cursor, bool forcedUpdate)
  56855. {
  56856. if (isUnboundedMouseModeOn && ((! unboundedMouseOffset.isOrigin()) || ! isCursorVisibleUntilOffscreen))
  56857. {
  56858. cursor = MouseCursor::NoCursor;
  56859. forcedUpdate = true;
  56860. }
  56861. if (forcedUpdate || cursor.getHandle() != currentCursorHandle)
  56862. {
  56863. currentCursorHandle = cursor.getHandle();
  56864. cursor.showInWindow (getPeer());
  56865. }
  56866. }
  56867. void hideCursor()
  56868. {
  56869. showMouseCursor (MouseCursor::NoCursor, true);
  56870. }
  56871. void revealCursor (bool forcedUpdate)
  56872. {
  56873. MouseCursor mc (MouseCursor::NormalCursor);
  56874. Component* current = getComponentUnderMouse();
  56875. if (current != 0)
  56876. mc = current->getLookAndFeel().getMouseCursorFor (*current);
  56877. showMouseCursor (mc, forcedUpdate);
  56878. }
  56879. int index;
  56880. bool isMouseDevice;
  56881. Point<int> lastScreenPos;
  56882. ModifierKeys buttonState;
  56883. private:
  56884. MouseInputSource& source;
  56885. Component::SafePointer<Component> componentUnderMouse;
  56886. ComponentPeer* lastPeer;
  56887. Point<int> unboundedMouseOffset;
  56888. bool isUnboundedMouseModeOn, isCursorVisibleUntilOffscreen;
  56889. void* currentCursorHandle;
  56890. int mouseEventCounter;
  56891. struct RecentMouseDown
  56892. {
  56893. Point<int> position;
  56894. int64 time;
  56895. Component* component;
  56896. };
  56897. RecentMouseDown mouseDowns[4];
  56898. bool mouseMovedSignificantlySincePressed;
  56899. int64 lastTime;
  56900. void registerMouseDown (const Point<int>& screenPos, const int64 time, Component* const component) throw()
  56901. {
  56902. for (int i = numElementsInArray (mouseDowns); --i > 0;)
  56903. mouseDowns[i] = mouseDowns[i - 1];
  56904. mouseDowns[0].position = screenPos;
  56905. mouseDowns[0].time = time;
  56906. mouseDowns[0].component = component;
  56907. mouseMovedSignificantlySincePressed = false;
  56908. }
  56909. void registerMouseDrag (const Point<int>& screenPos) throw()
  56910. {
  56911. mouseMovedSignificantlySincePressed = mouseMovedSignificantlySincePressed
  56912. || mouseDowns[0].position.getDistanceFrom (screenPos) >= 4;
  56913. }
  56914. MouseInputSourceInternal (const MouseInputSourceInternal&);
  56915. MouseInputSourceInternal& operator= (const MouseInputSourceInternal&);
  56916. };
  56917. MouseInputSource::MouseInputSource (const int index, const bool isMouseDevice)
  56918. {
  56919. pimpl = new MouseInputSourceInternal (*this, index, isMouseDevice);
  56920. }
  56921. MouseInputSource::~MouseInputSource()
  56922. {
  56923. }
  56924. bool MouseInputSource::isMouse() const { return pimpl->isMouseDevice; }
  56925. bool MouseInputSource::isTouch() const { return ! isMouse(); }
  56926. bool MouseInputSource::canHover() const { return isMouse(); }
  56927. bool MouseInputSource::hasMouseWheel() const { return isMouse(); }
  56928. int MouseInputSource::getIndex() const { return pimpl->index; }
  56929. bool MouseInputSource::isDragging() const { return pimpl->isDragging(); }
  56930. const Point<int> MouseInputSource::getScreenPosition() const { return pimpl->getScreenPosition(); }
  56931. const ModifierKeys MouseInputSource::getCurrentModifiers() const { return pimpl->getCurrentModifiers(); }
  56932. Component* MouseInputSource::getComponentUnderMouse() const { return pimpl->getComponentUnderMouse(); }
  56933. void MouseInputSource::triggerFakeMove() const { pimpl->triggerFakeMove(); }
  56934. int MouseInputSource::getNumberOfMultipleClicks() const throw() { return pimpl->getNumberOfMultipleClicks(); }
  56935. const Time MouseInputSource::getLastMouseDownTime() const throw() { return pimpl->getLastMouseDownTime(); }
  56936. const Point<int> MouseInputSource::getLastMouseDownPosition() const throw() { return pimpl->getLastMouseDownPosition(); }
  56937. bool MouseInputSource::hasMouseMovedSignificantlySincePressed() const throw() { return pimpl->hasMouseMovedSignificantlySincePressed(); }
  56938. bool MouseInputSource::canDoUnboundedMovement() const throw() { return isMouse(); }
  56939. void MouseInputSource::enableUnboundedMouseMovement (bool isEnabled, bool keepCursorVisibleUntilOffscreen) { pimpl->enableUnboundedMouseMovement (isEnabled, keepCursorVisibleUntilOffscreen); }
  56940. bool MouseInputSource::hasMouseCursor() const throw() { return isMouse(); }
  56941. void MouseInputSource::showMouseCursor (const MouseCursor& cursor) { pimpl->showMouseCursor (cursor, false); }
  56942. void MouseInputSource::hideCursor() { pimpl->hideCursor(); }
  56943. void MouseInputSource::revealCursor() { pimpl->revealCursor (false); }
  56944. void MouseInputSource::forceMouseCursorUpdate() { pimpl->revealCursor (true); }
  56945. void MouseInputSource::handleEvent (ComponentPeer* peer, const Point<int>& positionWithinPeer, const int64 time, const ModifierKeys& mods)
  56946. {
  56947. pimpl->handleEvent (peer, positionWithinPeer, time, mods.withOnlyMouseButtons());
  56948. }
  56949. void MouseInputSource::handleWheel (ComponentPeer* const peer, const Point<int>& positionWithinPeer, const int64 time, const float x, const float y)
  56950. {
  56951. pimpl->handleWheel (peer, positionWithinPeer, time, x, y);
  56952. }
  56953. END_JUCE_NAMESPACE
  56954. /*** End of inlined file: juce_MouseInputSource.cpp ***/
  56955. /*** Start of inlined file: juce_MouseHoverDetector.cpp ***/
  56956. BEGIN_JUCE_NAMESPACE
  56957. MouseHoverDetector::MouseHoverDetector (const int hoverTimeMillisecs_)
  56958. : source (0),
  56959. hoverTimeMillisecs (hoverTimeMillisecs_),
  56960. hasJustHovered (false)
  56961. {
  56962. internalTimer.owner = this;
  56963. }
  56964. MouseHoverDetector::~MouseHoverDetector()
  56965. {
  56966. setHoverComponent (0);
  56967. }
  56968. void MouseHoverDetector::setHoverTimeMillisecs (const int newTimeInMillisecs)
  56969. {
  56970. hoverTimeMillisecs = newTimeInMillisecs;
  56971. }
  56972. void MouseHoverDetector::setHoverComponent (Component* const newSourceComponent)
  56973. {
  56974. if (source != newSourceComponent)
  56975. {
  56976. internalTimer.stopTimer();
  56977. hasJustHovered = false;
  56978. if (source != 0)
  56979. {
  56980. // ! you need to delete the hover detector before deleting its component
  56981. jassert (source->isValidComponent());
  56982. source->removeMouseListener (&internalTimer);
  56983. }
  56984. source = newSourceComponent;
  56985. if (newSourceComponent != 0)
  56986. newSourceComponent->addMouseListener (&internalTimer, false);
  56987. }
  56988. }
  56989. void MouseHoverDetector::hoverTimerCallback()
  56990. {
  56991. internalTimer.stopTimer();
  56992. if (source != 0)
  56993. {
  56994. const Point<int> pos (source->getMouseXYRelative());
  56995. if (source->reallyContains (pos.getX(), pos.getY(), false))
  56996. {
  56997. hasJustHovered = true;
  56998. mouseHovered (pos.getX(), pos.getY());
  56999. }
  57000. }
  57001. }
  57002. void MouseHoverDetector::checkJustHoveredCallback()
  57003. {
  57004. if (hasJustHovered)
  57005. {
  57006. hasJustHovered = false;
  57007. mouseMovedAfterHover();
  57008. }
  57009. }
  57010. void MouseHoverDetector::HoverDetectorInternal::timerCallback()
  57011. {
  57012. owner->hoverTimerCallback();
  57013. }
  57014. void MouseHoverDetector::HoverDetectorInternal::mouseEnter (const MouseEvent&)
  57015. {
  57016. stopTimer();
  57017. owner->checkJustHoveredCallback();
  57018. }
  57019. void MouseHoverDetector::HoverDetectorInternal::mouseExit (const MouseEvent&)
  57020. {
  57021. stopTimer();
  57022. owner->checkJustHoveredCallback();
  57023. }
  57024. void MouseHoverDetector::HoverDetectorInternal::mouseDown (const MouseEvent&)
  57025. {
  57026. stopTimer();
  57027. owner->checkJustHoveredCallback();
  57028. }
  57029. void MouseHoverDetector::HoverDetectorInternal::mouseUp (const MouseEvent&)
  57030. {
  57031. stopTimer();
  57032. owner->checkJustHoveredCallback();
  57033. }
  57034. void MouseHoverDetector::HoverDetectorInternal::mouseMove (const MouseEvent& e)
  57035. {
  57036. if (lastX != e.x || lastY != e.y) // to avoid fake mouse-moves setting it off
  57037. {
  57038. lastX = e.x;
  57039. lastY = e.y;
  57040. if (owner->source != 0)
  57041. startTimer (owner->hoverTimeMillisecs);
  57042. owner->checkJustHoveredCallback();
  57043. }
  57044. }
  57045. void MouseHoverDetector::HoverDetectorInternal::mouseWheelMove (const MouseEvent&, float, float)
  57046. {
  57047. stopTimer();
  57048. owner->checkJustHoveredCallback();
  57049. }
  57050. END_JUCE_NAMESPACE
  57051. /*** End of inlined file: juce_MouseHoverDetector.cpp ***/
  57052. /*** Start of inlined file: juce_MouseListener.cpp ***/
  57053. BEGIN_JUCE_NAMESPACE
  57054. void MouseListener::mouseEnter (const MouseEvent&)
  57055. {
  57056. }
  57057. void MouseListener::mouseExit (const MouseEvent&)
  57058. {
  57059. }
  57060. void MouseListener::mouseDown (const MouseEvent&)
  57061. {
  57062. }
  57063. void MouseListener::mouseUp (const MouseEvent&)
  57064. {
  57065. }
  57066. void MouseListener::mouseDrag (const MouseEvent&)
  57067. {
  57068. }
  57069. void MouseListener::mouseMove (const MouseEvent&)
  57070. {
  57071. }
  57072. void MouseListener::mouseDoubleClick (const MouseEvent&)
  57073. {
  57074. }
  57075. void MouseListener::mouseWheelMove (const MouseEvent&, float, float)
  57076. {
  57077. }
  57078. END_JUCE_NAMESPACE
  57079. /*** End of inlined file: juce_MouseListener.cpp ***/
  57080. /*** Start of inlined file: juce_BooleanPropertyComponent.cpp ***/
  57081. BEGIN_JUCE_NAMESPACE
  57082. BooleanPropertyComponent::BooleanPropertyComponent (const String& name,
  57083. const String& buttonTextWhenTrue,
  57084. const String& buttonTextWhenFalse)
  57085. : PropertyComponent (name),
  57086. onText (buttonTextWhenTrue),
  57087. offText (buttonTextWhenFalse)
  57088. {
  57089. createButton();
  57090. button->addButtonListener (this);
  57091. }
  57092. BooleanPropertyComponent::BooleanPropertyComponent (const Value& valueToControl,
  57093. const String& name,
  57094. const String& buttonText)
  57095. : PropertyComponent (name),
  57096. onText (buttonText),
  57097. offText (buttonText)
  57098. {
  57099. createButton();
  57100. button->setButtonText (buttonText);
  57101. button->getToggleStateValue().referTo (valueToControl);
  57102. button->setClickingTogglesState (true);
  57103. }
  57104. BooleanPropertyComponent::~BooleanPropertyComponent()
  57105. {
  57106. deleteAllChildren();
  57107. }
  57108. void BooleanPropertyComponent::createButton()
  57109. {
  57110. addAndMakeVisible (button = new ToggleButton (String::empty));
  57111. button->setClickingTogglesState (false);
  57112. }
  57113. void BooleanPropertyComponent::setState (const bool newState)
  57114. {
  57115. button->setToggleState (newState, true);
  57116. }
  57117. bool BooleanPropertyComponent::getState() const
  57118. {
  57119. return button->getToggleState();
  57120. }
  57121. void BooleanPropertyComponent::paint (Graphics& g)
  57122. {
  57123. PropertyComponent::paint (g);
  57124. g.setColour (Colours::white);
  57125. g.fillRect (button->getBounds());
  57126. g.setColour (findColour (ComboBox::outlineColourId));
  57127. g.drawRect (button->getBounds());
  57128. }
  57129. void BooleanPropertyComponent::refresh()
  57130. {
  57131. button->setToggleState (getState(), false);
  57132. button->setButtonText (button->getToggleState() ? onText : offText);
  57133. }
  57134. void BooleanPropertyComponent::buttonClicked (Button*)
  57135. {
  57136. setState (! getState());
  57137. }
  57138. END_JUCE_NAMESPACE
  57139. /*** End of inlined file: juce_BooleanPropertyComponent.cpp ***/
  57140. /*** Start of inlined file: juce_ButtonPropertyComponent.cpp ***/
  57141. BEGIN_JUCE_NAMESPACE
  57142. ButtonPropertyComponent::ButtonPropertyComponent (const String& name,
  57143. const bool triggerOnMouseDown)
  57144. : PropertyComponent (name)
  57145. {
  57146. addAndMakeVisible (button = new TextButton (String::empty));
  57147. button->setTriggeredOnMouseDown (triggerOnMouseDown);
  57148. button->addButtonListener (this);
  57149. }
  57150. ButtonPropertyComponent::~ButtonPropertyComponent()
  57151. {
  57152. deleteAllChildren();
  57153. }
  57154. void ButtonPropertyComponent::refresh()
  57155. {
  57156. button->setButtonText (getButtonText());
  57157. }
  57158. void ButtonPropertyComponent::buttonClicked (Button*)
  57159. {
  57160. buttonClicked();
  57161. }
  57162. END_JUCE_NAMESPACE
  57163. /*** End of inlined file: juce_ButtonPropertyComponent.cpp ***/
  57164. /*** Start of inlined file: juce_ChoicePropertyComponent.cpp ***/
  57165. BEGIN_JUCE_NAMESPACE
  57166. ChoicePropertyComponent::ChoicePropertyComponent (const String& name)
  57167. : PropertyComponent (name),
  57168. comboBox (0)
  57169. {
  57170. }
  57171. ChoicePropertyComponent::ChoicePropertyComponent (const Value& valueToControl,
  57172. const String& name,
  57173. const StringArray& choices_,
  57174. const Array <int>* choiceIDs)
  57175. : PropertyComponent (name),
  57176. choices (choices_),
  57177. comboBox (0)
  57178. {
  57179. createComboBox (choiceIDs);
  57180. comboBox->getSelectedIdAsValue().referTo (valueToControl);
  57181. }
  57182. ChoicePropertyComponent::~ChoicePropertyComponent()
  57183. {
  57184. deleteAllChildren();
  57185. }
  57186. void ChoicePropertyComponent::createComboBox (const Array <int>* choiceIDs)
  57187. {
  57188. // The array of IDs must contain the same number of values as the choices list!
  57189. jassert (choiceIDs == 0 || choiceIDs->size() == choices.size());
  57190. addAndMakeVisible (comboBox = new ComboBox (String::empty));
  57191. int itemId = 0;
  57192. for (int i = 0; i < choices.size(); ++i)
  57193. {
  57194. if (choices[i].isNotEmpty())
  57195. comboBox->addItem (choices[i], choiceIDs == 0 ? ++itemId
  57196. : ((*choiceIDs)[i]));
  57197. else
  57198. comboBox->addSeparator();
  57199. }
  57200. comboBox->setEditableText (false);
  57201. }
  57202. void ChoicePropertyComponent::setIndex (const int newIndex)
  57203. {
  57204. comboBox->setSelectedId (comboBox->getItemId (newIndex));
  57205. }
  57206. int ChoicePropertyComponent::getIndex() const
  57207. {
  57208. return comboBox->getSelectedItemIndex();
  57209. }
  57210. const StringArray& ChoicePropertyComponent::getChoices() const
  57211. {
  57212. return choices;
  57213. }
  57214. void ChoicePropertyComponent::refresh()
  57215. {
  57216. if (comboBox == 0)
  57217. {
  57218. createComboBox (0);
  57219. comboBox->addListener (this);
  57220. }
  57221. comboBox->setSelectedId (getIndex() + 1, true);
  57222. }
  57223. void ChoicePropertyComponent::comboBoxChanged (ComboBox*)
  57224. {
  57225. const int newIndex = comboBox->getSelectedId() - 1;
  57226. if (newIndex != getIndex())
  57227. setIndex (newIndex);
  57228. }
  57229. END_JUCE_NAMESPACE
  57230. /*** End of inlined file: juce_ChoicePropertyComponent.cpp ***/
  57231. /*** Start of inlined file: juce_PropertyComponent.cpp ***/
  57232. BEGIN_JUCE_NAMESPACE
  57233. PropertyComponent::PropertyComponent (const String& name,
  57234. const int preferredHeight_)
  57235. : Component (name),
  57236. preferredHeight (preferredHeight_)
  57237. {
  57238. jassert (name.isNotEmpty());
  57239. }
  57240. PropertyComponent::~PropertyComponent()
  57241. {
  57242. }
  57243. void PropertyComponent::paint (Graphics& g)
  57244. {
  57245. getLookAndFeel().drawPropertyComponentBackground (g, getWidth(), getHeight(), *this);
  57246. getLookAndFeel().drawPropertyComponentLabel (g, getWidth(), getHeight(), *this);
  57247. }
  57248. void PropertyComponent::resized()
  57249. {
  57250. if (getNumChildComponents() > 0)
  57251. getChildComponent (0)->setBounds (getLookAndFeel().getPropertyComponentContentPosition (*this));
  57252. }
  57253. void PropertyComponent::enablementChanged()
  57254. {
  57255. repaint();
  57256. }
  57257. END_JUCE_NAMESPACE
  57258. /*** End of inlined file: juce_PropertyComponent.cpp ***/
  57259. /*** Start of inlined file: juce_PropertyPanel.cpp ***/
  57260. BEGIN_JUCE_NAMESPACE
  57261. class PropertyPanel::PropertyHolderComponent : public Component
  57262. {
  57263. public:
  57264. PropertyHolderComponent()
  57265. {
  57266. }
  57267. ~PropertyHolderComponent()
  57268. {
  57269. deleteAllChildren();
  57270. }
  57271. void paint (Graphics&)
  57272. {
  57273. }
  57274. void updateLayout (int width);
  57275. void refreshAll() const;
  57276. private:
  57277. PropertyHolderComponent (const PropertyHolderComponent&);
  57278. PropertyHolderComponent& operator= (const PropertyHolderComponent&);
  57279. };
  57280. class PropertySectionComponent : public Component
  57281. {
  57282. public:
  57283. PropertySectionComponent (const String& sectionTitle,
  57284. const Array <PropertyComponent*>& newProperties,
  57285. const bool open)
  57286. : Component (sectionTitle),
  57287. titleHeight (sectionTitle.isNotEmpty() ? 22 : 0),
  57288. isOpen_ (open)
  57289. {
  57290. for (int i = newProperties.size(); --i >= 0;)
  57291. {
  57292. addAndMakeVisible (newProperties.getUnchecked(i));
  57293. newProperties.getUnchecked(i)->refresh();
  57294. }
  57295. }
  57296. ~PropertySectionComponent()
  57297. {
  57298. deleteAllChildren();
  57299. }
  57300. void paint (Graphics& g)
  57301. {
  57302. if (titleHeight > 0)
  57303. getLookAndFeel().drawPropertyPanelSectionHeader (g, getName(), isOpen(), getWidth(), titleHeight);
  57304. }
  57305. void resized()
  57306. {
  57307. int y = titleHeight;
  57308. for (int i = getNumChildComponents(); --i >= 0;)
  57309. {
  57310. PropertyComponent* const pec = dynamic_cast <PropertyComponent*> (getChildComponent (i));
  57311. if (pec != 0)
  57312. {
  57313. const int prefH = pec->getPreferredHeight();
  57314. pec->setBounds (1, y, getWidth() - 2, prefH);
  57315. y += prefH;
  57316. }
  57317. }
  57318. }
  57319. int getPreferredHeight() const
  57320. {
  57321. int y = titleHeight;
  57322. if (isOpen())
  57323. {
  57324. for (int i = 0; i < getNumChildComponents(); ++i)
  57325. {
  57326. PropertyComponent* pec = dynamic_cast <PropertyComponent*> (getChildComponent (i));
  57327. if (pec != 0)
  57328. y += pec->getPreferredHeight();
  57329. }
  57330. }
  57331. return y;
  57332. }
  57333. void setOpen (const bool open)
  57334. {
  57335. if (isOpen_ != open)
  57336. {
  57337. isOpen_ = open;
  57338. for (int i = 0; i < getNumChildComponents(); ++i)
  57339. {
  57340. PropertyComponent* pec = dynamic_cast <PropertyComponent*> (getChildComponent (i));
  57341. if (pec != 0)
  57342. pec->setVisible (open);
  57343. }
  57344. // (unable to use the syntax findParentComponentOfClass <DragAndDropContainer> () because of a VC6 compiler bug)
  57345. PropertyPanel* const pp = findParentComponentOfClass ((PropertyPanel*) 0);
  57346. if (pp != 0)
  57347. pp->resized();
  57348. }
  57349. }
  57350. bool isOpen() const
  57351. {
  57352. return isOpen_;
  57353. }
  57354. void refreshAll() const
  57355. {
  57356. for (int i = 0; i < getNumChildComponents(); ++i)
  57357. {
  57358. PropertyComponent* pec = dynamic_cast <PropertyComponent*> (getChildComponent (i));
  57359. if (pec != 0)
  57360. pec->refresh();
  57361. }
  57362. }
  57363. void mouseDown (const MouseEvent&)
  57364. {
  57365. }
  57366. void mouseUp (const MouseEvent& e)
  57367. {
  57368. if (e.getMouseDownX() < titleHeight
  57369. && e.x < titleHeight
  57370. && e.y < titleHeight
  57371. && e.getNumberOfClicks() != 2)
  57372. {
  57373. setOpen (! isOpen());
  57374. }
  57375. }
  57376. void mouseDoubleClick (const MouseEvent& e)
  57377. {
  57378. if (e.y < titleHeight)
  57379. setOpen (! isOpen());
  57380. }
  57381. private:
  57382. int titleHeight;
  57383. bool isOpen_;
  57384. PropertySectionComponent (const PropertySectionComponent&);
  57385. PropertySectionComponent& operator= (const PropertySectionComponent&);
  57386. };
  57387. void PropertyPanel::PropertyHolderComponent::updateLayout (const int width)
  57388. {
  57389. int y = 0;
  57390. for (int i = getNumChildComponents(); --i >= 0;)
  57391. {
  57392. PropertySectionComponent* const section
  57393. = dynamic_cast <PropertySectionComponent*> (getChildComponent (i));
  57394. if (section != 0)
  57395. {
  57396. const int prefH = section->getPreferredHeight();
  57397. section->setBounds (0, y, width, prefH);
  57398. y += prefH;
  57399. }
  57400. }
  57401. setSize (width, y);
  57402. repaint();
  57403. }
  57404. void PropertyPanel::PropertyHolderComponent::refreshAll() const
  57405. {
  57406. for (int i = getNumChildComponents(); --i >= 0;)
  57407. {
  57408. PropertySectionComponent* const section
  57409. = dynamic_cast <PropertySectionComponent*> (getChildComponent (i));
  57410. if (section != 0)
  57411. section->refreshAll();
  57412. }
  57413. }
  57414. PropertyPanel::PropertyPanel()
  57415. {
  57416. messageWhenEmpty = TRANS("(nothing selected)");
  57417. addAndMakeVisible (viewport = new Viewport());
  57418. viewport->setViewedComponent (propertyHolderComponent = new PropertyHolderComponent());
  57419. viewport->setFocusContainer (true);
  57420. }
  57421. PropertyPanel::~PropertyPanel()
  57422. {
  57423. clear();
  57424. deleteAllChildren();
  57425. }
  57426. void PropertyPanel::paint (Graphics& g)
  57427. {
  57428. if (propertyHolderComponent->getNumChildComponents() == 0)
  57429. {
  57430. g.setColour (Colours::black.withAlpha (0.5f));
  57431. g.setFont (14.0f);
  57432. g.drawText (messageWhenEmpty, 0, 0, getWidth(), 30,
  57433. Justification::centred, true);
  57434. }
  57435. }
  57436. void PropertyPanel::resized()
  57437. {
  57438. viewport->setBounds (0, 0, getWidth(), getHeight());
  57439. updatePropHolderLayout();
  57440. }
  57441. void PropertyPanel::clear()
  57442. {
  57443. if (propertyHolderComponent->getNumChildComponents() > 0)
  57444. {
  57445. propertyHolderComponent->deleteAllChildren();
  57446. repaint();
  57447. }
  57448. }
  57449. void PropertyPanel::addProperties (const Array <PropertyComponent*>& newProperties)
  57450. {
  57451. if (propertyHolderComponent->getNumChildComponents() == 0)
  57452. repaint();
  57453. propertyHolderComponent->addAndMakeVisible (new PropertySectionComponent (String::empty,
  57454. newProperties,
  57455. true), 0);
  57456. updatePropHolderLayout();
  57457. }
  57458. void PropertyPanel::addSection (const String& sectionTitle,
  57459. const Array <PropertyComponent*>& newProperties,
  57460. const bool shouldBeOpen)
  57461. {
  57462. jassert (sectionTitle.isNotEmpty());
  57463. if (propertyHolderComponent->getNumChildComponents() == 0)
  57464. repaint();
  57465. propertyHolderComponent->addAndMakeVisible (new PropertySectionComponent (sectionTitle,
  57466. newProperties,
  57467. shouldBeOpen), 0);
  57468. updatePropHolderLayout();
  57469. }
  57470. void PropertyPanel::updatePropHolderLayout() const
  57471. {
  57472. const int maxWidth = viewport->getMaximumVisibleWidth();
  57473. propertyHolderComponent->updateLayout (maxWidth);
  57474. const int newMaxWidth = viewport->getMaximumVisibleWidth();
  57475. if (maxWidth != newMaxWidth)
  57476. {
  57477. // need to do this twice because of scrollbars changing the size, etc.
  57478. propertyHolderComponent->updateLayout (newMaxWidth);
  57479. }
  57480. }
  57481. void PropertyPanel::refreshAll() const
  57482. {
  57483. propertyHolderComponent->refreshAll();
  57484. }
  57485. const StringArray PropertyPanel::getSectionNames() const
  57486. {
  57487. StringArray s;
  57488. for (int i = 0; i < propertyHolderComponent->getNumChildComponents(); ++i)
  57489. {
  57490. PropertySectionComponent* const section = dynamic_cast <PropertySectionComponent*> (propertyHolderComponent->getChildComponent (i));
  57491. if (section != 0 && section->getName().isNotEmpty())
  57492. s.add (section->getName());
  57493. }
  57494. return s;
  57495. }
  57496. bool PropertyPanel::isSectionOpen (const int sectionIndex) const
  57497. {
  57498. int index = 0;
  57499. for (int i = 0; i < propertyHolderComponent->getNumChildComponents(); ++i)
  57500. {
  57501. PropertySectionComponent* const section = dynamic_cast <PropertySectionComponent*> (propertyHolderComponent->getChildComponent (i));
  57502. if (section != 0 && section->getName().isNotEmpty())
  57503. {
  57504. if (index == sectionIndex)
  57505. return section->isOpen();
  57506. ++index;
  57507. }
  57508. }
  57509. return false;
  57510. }
  57511. void PropertyPanel::setSectionOpen (const int sectionIndex, const bool shouldBeOpen)
  57512. {
  57513. int index = 0;
  57514. for (int i = 0; i < propertyHolderComponent->getNumChildComponents(); ++i)
  57515. {
  57516. PropertySectionComponent* const section = dynamic_cast <PropertySectionComponent*> (propertyHolderComponent->getChildComponent (i));
  57517. if (section != 0 && section->getName().isNotEmpty())
  57518. {
  57519. if (index == sectionIndex)
  57520. {
  57521. section->setOpen (shouldBeOpen);
  57522. break;
  57523. }
  57524. ++index;
  57525. }
  57526. }
  57527. }
  57528. void PropertyPanel::setSectionEnabled (const int sectionIndex, const bool shouldBeEnabled)
  57529. {
  57530. int index = 0;
  57531. for (int i = 0; i < propertyHolderComponent->getNumChildComponents(); ++i)
  57532. {
  57533. PropertySectionComponent* const section = dynamic_cast <PropertySectionComponent*> (propertyHolderComponent->getChildComponent (i));
  57534. if (section != 0 && section->getName().isNotEmpty())
  57535. {
  57536. if (index == sectionIndex)
  57537. {
  57538. section->setEnabled (shouldBeEnabled);
  57539. break;
  57540. }
  57541. ++index;
  57542. }
  57543. }
  57544. }
  57545. XmlElement* PropertyPanel::getOpennessState() const
  57546. {
  57547. XmlElement* const xml = new XmlElement ("PROPERTYPANELSTATE");
  57548. xml->setAttribute ("scrollPos", viewport->getViewPositionY());
  57549. const StringArray sections (getSectionNames());
  57550. for (int i = 0; i < sections.size(); ++i)
  57551. {
  57552. if (sections[i].isNotEmpty())
  57553. {
  57554. XmlElement* const e = xml->createNewChildElement ("SECTION");
  57555. e->setAttribute ("name", sections[i]);
  57556. e->setAttribute ("open", isSectionOpen (i) ? 1 : 0);
  57557. }
  57558. }
  57559. return xml;
  57560. }
  57561. void PropertyPanel::restoreOpennessState (const XmlElement& xml)
  57562. {
  57563. if (xml.hasTagName ("PROPERTYPANELSTATE"))
  57564. {
  57565. const StringArray sections (getSectionNames());
  57566. forEachXmlChildElementWithTagName (xml, e, "SECTION")
  57567. {
  57568. setSectionOpen (sections.indexOf (e->getStringAttribute ("name")),
  57569. e->getBoolAttribute ("open"));
  57570. }
  57571. viewport->setViewPosition (viewport->getViewPositionX(),
  57572. xml.getIntAttribute ("scrollPos", viewport->getViewPositionY()));
  57573. }
  57574. }
  57575. void PropertyPanel::setMessageWhenEmpty (const String& newMessage)
  57576. {
  57577. if (messageWhenEmpty != newMessage)
  57578. {
  57579. messageWhenEmpty = newMessage;
  57580. repaint();
  57581. }
  57582. }
  57583. const String& PropertyPanel::getMessageWhenEmpty() const
  57584. {
  57585. return messageWhenEmpty;
  57586. }
  57587. END_JUCE_NAMESPACE
  57588. /*** End of inlined file: juce_PropertyPanel.cpp ***/
  57589. /*** Start of inlined file: juce_SliderPropertyComponent.cpp ***/
  57590. BEGIN_JUCE_NAMESPACE
  57591. SliderPropertyComponent::SliderPropertyComponent (const String& name,
  57592. const double rangeMin,
  57593. const double rangeMax,
  57594. const double interval,
  57595. const double skewFactor)
  57596. : PropertyComponent (name)
  57597. {
  57598. addAndMakeVisible (slider = new Slider (name));
  57599. slider->setRange (rangeMin, rangeMax, interval);
  57600. slider->setSkewFactor (skewFactor);
  57601. slider->setSliderStyle (Slider::LinearBar);
  57602. slider->addListener (this);
  57603. }
  57604. SliderPropertyComponent::SliderPropertyComponent (const Value& valueToControl,
  57605. const String& name,
  57606. const double rangeMin,
  57607. const double rangeMax,
  57608. const double interval,
  57609. const double skewFactor)
  57610. : PropertyComponent (name)
  57611. {
  57612. addAndMakeVisible (slider = new Slider (name));
  57613. slider->setRange (rangeMin, rangeMax, interval);
  57614. slider->setSkewFactor (skewFactor);
  57615. slider->setSliderStyle (Slider::LinearBar);
  57616. slider->getValueObject().referTo (valueToControl);
  57617. }
  57618. SliderPropertyComponent::~SliderPropertyComponent()
  57619. {
  57620. deleteAllChildren();
  57621. }
  57622. void SliderPropertyComponent::setValue (const double /*newValue*/)
  57623. {
  57624. }
  57625. double SliderPropertyComponent::getValue() const
  57626. {
  57627. return slider->getValue();
  57628. }
  57629. void SliderPropertyComponent::refresh()
  57630. {
  57631. slider->setValue (getValue(), false);
  57632. }
  57633. void SliderPropertyComponent::sliderValueChanged (Slider*)
  57634. {
  57635. if (getValue() != slider->getValue())
  57636. setValue (slider->getValue());
  57637. }
  57638. END_JUCE_NAMESPACE
  57639. /*** End of inlined file: juce_SliderPropertyComponent.cpp ***/
  57640. /*** Start of inlined file: juce_TextPropertyComponent.cpp ***/
  57641. BEGIN_JUCE_NAMESPACE
  57642. class TextPropLabel : public Label
  57643. {
  57644. TextPropertyComponent& owner;
  57645. int maxChars;
  57646. bool isMultiline;
  57647. public:
  57648. TextPropLabel (TextPropertyComponent& owner_,
  57649. const int maxChars_, const bool isMultiline_)
  57650. : Label (String::empty, String::empty),
  57651. owner (owner_),
  57652. maxChars (maxChars_),
  57653. isMultiline (isMultiline_)
  57654. {
  57655. setEditable (true, true, false);
  57656. setColour (backgroundColourId, Colours::white);
  57657. setColour (outlineColourId, findColour (ComboBox::outlineColourId));
  57658. }
  57659. ~TextPropLabel()
  57660. {
  57661. }
  57662. TextEditor* createEditorComponent()
  57663. {
  57664. TextEditor* const textEditor = Label::createEditorComponent();
  57665. textEditor->setInputRestrictions (maxChars);
  57666. if (isMultiline)
  57667. {
  57668. textEditor->setMultiLine (true, true);
  57669. textEditor->setReturnKeyStartsNewLine (true);
  57670. }
  57671. return textEditor;
  57672. }
  57673. void textWasEdited()
  57674. {
  57675. owner.textWasEdited();
  57676. }
  57677. };
  57678. TextPropertyComponent::TextPropertyComponent (const String& name,
  57679. const int maxNumChars,
  57680. const bool isMultiLine)
  57681. : PropertyComponent (name)
  57682. {
  57683. createEditor (maxNumChars, isMultiLine);
  57684. }
  57685. TextPropertyComponent::TextPropertyComponent (const Value& valueToControl,
  57686. const String& name,
  57687. const int maxNumChars,
  57688. const bool isMultiLine)
  57689. : PropertyComponent (name)
  57690. {
  57691. createEditor (maxNumChars, isMultiLine);
  57692. textEditor->getTextValue().referTo (valueToControl);
  57693. }
  57694. TextPropertyComponent::~TextPropertyComponent()
  57695. {
  57696. deleteAllChildren();
  57697. }
  57698. void TextPropertyComponent::setText (const String& newText)
  57699. {
  57700. textEditor->setText (newText, true);
  57701. }
  57702. const String TextPropertyComponent::getText() const
  57703. {
  57704. return textEditor->getText();
  57705. }
  57706. void TextPropertyComponent::createEditor (const int maxNumChars, const bool isMultiLine)
  57707. {
  57708. addAndMakeVisible (textEditor = new TextPropLabel (*this, maxNumChars, isMultiLine));
  57709. if (isMultiLine)
  57710. {
  57711. textEditor->setJustificationType (Justification::topLeft);
  57712. preferredHeight = 120;
  57713. }
  57714. }
  57715. void TextPropertyComponent::refresh()
  57716. {
  57717. textEditor->setText (getText(), false);
  57718. }
  57719. void TextPropertyComponent::textWasEdited()
  57720. {
  57721. const String newText (textEditor->getText());
  57722. if (getText() != newText)
  57723. setText (newText);
  57724. }
  57725. END_JUCE_NAMESPACE
  57726. /*** End of inlined file: juce_TextPropertyComponent.cpp ***/
  57727. /*** Start of inlined file: juce_AudioDeviceSelectorComponent.cpp ***/
  57728. BEGIN_JUCE_NAMESPACE
  57729. class SimpleDeviceManagerInputLevelMeter : public Component,
  57730. public Timer
  57731. {
  57732. public:
  57733. SimpleDeviceManagerInputLevelMeter (AudioDeviceManager* const manager_)
  57734. : manager (manager_),
  57735. level (0)
  57736. {
  57737. startTimer (50);
  57738. manager->enableInputLevelMeasurement (true);
  57739. }
  57740. ~SimpleDeviceManagerInputLevelMeter()
  57741. {
  57742. manager->enableInputLevelMeasurement (false);
  57743. }
  57744. void timerCallback()
  57745. {
  57746. const float newLevel = (float) manager->getCurrentInputLevel();
  57747. if (std::abs (level - newLevel) > 0.005f)
  57748. {
  57749. level = newLevel;
  57750. repaint();
  57751. }
  57752. }
  57753. void paint (Graphics& g)
  57754. {
  57755. getLookAndFeel().drawLevelMeter (g, getWidth(), getHeight(),
  57756. (float) exp (log (level) / 3.0)); // (add a bit of a skew to make the level more obvious)
  57757. }
  57758. private:
  57759. AudioDeviceManager* const manager;
  57760. float level;
  57761. SimpleDeviceManagerInputLevelMeter (const SimpleDeviceManagerInputLevelMeter&);
  57762. SimpleDeviceManagerInputLevelMeter& operator= (const SimpleDeviceManagerInputLevelMeter&);
  57763. };
  57764. class AudioDeviceSelectorComponent::MidiInputSelectorComponentListBox : public ListBox,
  57765. public ListBoxModel
  57766. {
  57767. public:
  57768. MidiInputSelectorComponentListBox (AudioDeviceManager& deviceManager_,
  57769. const String& noItemsMessage_,
  57770. const int minNumber_,
  57771. const int maxNumber_)
  57772. : ListBox (String::empty, 0),
  57773. deviceManager (deviceManager_),
  57774. noItemsMessage (noItemsMessage_),
  57775. minNumber (minNumber_),
  57776. maxNumber (maxNumber_)
  57777. {
  57778. items = MidiInput::getDevices();
  57779. setModel (this);
  57780. setOutlineThickness (1);
  57781. }
  57782. ~MidiInputSelectorComponentListBox()
  57783. {
  57784. }
  57785. int getNumRows()
  57786. {
  57787. return items.size();
  57788. }
  57789. void paintListBoxItem (int row,
  57790. Graphics& g,
  57791. int width, int height,
  57792. bool rowIsSelected)
  57793. {
  57794. if (((unsigned int) row) < (unsigned int) items.size())
  57795. {
  57796. if (rowIsSelected)
  57797. g.fillAll (findColour (TextEditor::highlightColourId)
  57798. .withMultipliedAlpha (0.3f));
  57799. const String item (items [row]);
  57800. bool enabled = deviceManager.isMidiInputEnabled (item);
  57801. const int x = getTickX();
  57802. const float tickW = height * 0.75f;
  57803. getLookAndFeel().drawTickBox (g, *this, x - tickW, (height - tickW) / 2, tickW, tickW,
  57804. enabled, true, true, false);
  57805. g.setFont (height * 0.6f);
  57806. g.setColour (findColour (ListBox::textColourId, true).withMultipliedAlpha (enabled ? 1.0f : 0.6f));
  57807. g.drawText (item, x, 0, width - x - 2, height, Justification::centredLeft, true);
  57808. }
  57809. }
  57810. void listBoxItemClicked (int row, const MouseEvent& e)
  57811. {
  57812. selectRow (row);
  57813. if (e.x < getTickX())
  57814. flipEnablement (row);
  57815. }
  57816. void listBoxItemDoubleClicked (int row, const MouseEvent&)
  57817. {
  57818. flipEnablement (row);
  57819. }
  57820. void returnKeyPressed (int row)
  57821. {
  57822. flipEnablement (row);
  57823. }
  57824. void paint (Graphics& g)
  57825. {
  57826. ListBox::paint (g);
  57827. if (items.size() == 0)
  57828. {
  57829. g.setColour (Colours::grey);
  57830. g.setFont (13.0f);
  57831. g.drawText (noItemsMessage,
  57832. 0, 0, getWidth(), getHeight() / 2,
  57833. Justification::centred, true);
  57834. }
  57835. }
  57836. int getBestHeight (const int preferredHeight)
  57837. {
  57838. const int extra = getOutlineThickness() * 2;
  57839. return jmax (getRowHeight() * 2 + extra,
  57840. jmin (getRowHeight() * getNumRows() + extra,
  57841. preferredHeight));
  57842. }
  57843. juce_UseDebuggingNewOperator
  57844. private:
  57845. AudioDeviceManager& deviceManager;
  57846. const String noItemsMessage;
  57847. StringArray items;
  57848. int minNumber, maxNumber;
  57849. void flipEnablement (const int row)
  57850. {
  57851. if (((unsigned int) row) < (unsigned int) items.size())
  57852. {
  57853. const String item (items [row]);
  57854. deviceManager.setMidiInputEnabled (item, ! deviceManager.isMidiInputEnabled (item));
  57855. }
  57856. }
  57857. int getTickX() const
  57858. {
  57859. return getRowHeight() + 5;
  57860. }
  57861. MidiInputSelectorComponentListBox (const MidiInputSelectorComponentListBox&);
  57862. MidiInputSelectorComponentListBox& operator= (const MidiInputSelectorComponentListBox&);
  57863. };
  57864. class AudioDeviceSettingsPanel : public Component,
  57865. public ComboBoxListener,
  57866. public ChangeListener,
  57867. public ButtonListener
  57868. {
  57869. public:
  57870. AudioDeviceSettingsPanel (AudioIODeviceType* type_,
  57871. AudioIODeviceType::DeviceSetupDetails& setup_,
  57872. const bool hideAdvancedOptionsWithButton)
  57873. : type (type_),
  57874. setup (setup_)
  57875. {
  57876. sampleRateDropDown = 0;
  57877. sampleRateLabel = 0;
  57878. bufferSizeDropDown = 0;
  57879. bufferSizeLabel = 0;
  57880. outputDeviceDropDown = 0;
  57881. outputDeviceLabel = 0;
  57882. inputDeviceDropDown = 0;
  57883. inputDeviceLabel = 0;
  57884. testButton = 0;
  57885. inputLevelMeter = 0;
  57886. showUIButton = 0;
  57887. inputChanList = 0;
  57888. outputChanList = 0;
  57889. inputChanLabel = 0;
  57890. outputChanLabel = 0;
  57891. showAdvancedSettingsButton = 0;
  57892. if (hideAdvancedOptionsWithButton)
  57893. {
  57894. addAndMakeVisible (showAdvancedSettingsButton = new TextButton (TRANS("Show advanced settings...")));
  57895. showAdvancedSettingsButton->addButtonListener (this);
  57896. }
  57897. type->scanForDevices();
  57898. setup.manager->addChangeListener (this);
  57899. changeListenerCallback (0);
  57900. }
  57901. ~AudioDeviceSettingsPanel()
  57902. {
  57903. setup.manager->removeChangeListener (this);
  57904. deleteAndZero (outputDeviceLabel);
  57905. deleteAndZero (inputDeviceLabel);
  57906. deleteAndZero (sampleRateLabel);
  57907. deleteAndZero (bufferSizeLabel);
  57908. deleteAndZero (showUIButton);
  57909. deleteAndZero (inputChanLabel);
  57910. deleteAndZero (outputChanLabel);
  57911. deleteAndZero (showAdvancedSettingsButton);
  57912. deleteAllChildren();
  57913. }
  57914. void resized()
  57915. {
  57916. const int lx = proportionOfWidth (0.35f);
  57917. const int w = proportionOfWidth (0.4f);
  57918. const int h = 24;
  57919. const int space = 6;
  57920. const int dh = h + space;
  57921. int y = 0;
  57922. if (outputDeviceDropDown != 0)
  57923. {
  57924. outputDeviceDropDown->setBounds (lx, y, w, h);
  57925. if (testButton != 0)
  57926. testButton->setBounds (proportionOfWidth (0.77f),
  57927. outputDeviceDropDown->getY(),
  57928. proportionOfWidth (0.18f),
  57929. h);
  57930. y += dh;
  57931. }
  57932. if (inputDeviceDropDown != 0)
  57933. {
  57934. inputDeviceDropDown->setBounds (lx, y, w, h);
  57935. inputLevelMeter->setBounds (proportionOfWidth (0.77f),
  57936. inputDeviceDropDown->getY(),
  57937. proportionOfWidth (0.18f),
  57938. h);
  57939. y += dh;
  57940. }
  57941. const int maxBoxHeight = 100;//(getHeight() - y - dh * 2) / numBoxes;
  57942. if (outputChanList != 0)
  57943. {
  57944. const int bh = outputChanList->getBestHeight (maxBoxHeight);
  57945. outputChanList->setBounds (lx, y, proportionOfWidth (0.55f), bh);
  57946. y += bh + space;
  57947. }
  57948. if (inputChanList != 0)
  57949. {
  57950. const int bh = inputChanList->getBestHeight (maxBoxHeight);
  57951. inputChanList->setBounds (lx, y, proportionOfWidth (0.55f), bh);
  57952. y += bh + space;
  57953. }
  57954. y += space * 2;
  57955. if (showAdvancedSettingsButton != 0)
  57956. {
  57957. showAdvancedSettingsButton->changeWidthToFitText (h);
  57958. showAdvancedSettingsButton->setTopLeftPosition (lx, y);
  57959. }
  57960. if (sampleRateDropDown != 0)
  57961. {
  57962. sampleRateDropDown->setVisible (showAdvancedSettingsButton == 0
  57963. || ! showAdvancedSettingsButton->isVisible());
  57964. sampleRateDropDown->setBounds (lx, y, w, h);
  57965. y += dh;
  57966. }
  57967. if (bufferSizeDropDown != 0)
  57968. {
  57969. bufferSizeDropDown->setVisible (showAdvancedSettingsButton == 0
  57970. || ! showAdvancedSettingsButton->isVisible());
  57971. bufferSizeDropDown->setBounds (lx, y, w, h);
  57972. y += dh;
  57973. }
  57974. if (showUIButton != 0)
  57975. {
  57976. showUIButton->setVisible (showAdvancedSettingsButton == 0
  57977. || ! showAdvancedSettingsButton->isVisible());
  57978. showUIButton->changeWidthToFitText (h);
  57979. showUIButton->setTopLeftPosition (lx, y);
  57980. }
  57981. }
  57982. void comboBoxChanged (ComboBox* comboBoxThatHasChanged)
  57983. {
  57984. if (comboBoxThatHasChanged == 0)
  57985. return;
  57986. AudioDeviceManager::AudioDeviceSetup config;
  57987. setup.manager->getAudioDeviceSetup (config);
  57988. String error;
  57989. if (comboBoxThatHasChanged == outputDeviceDropDown
  57990. || comboBoxThatHasChanged == inputDeviceDropDown)
  57991. {
  57992. if (outputDeviceDropDown != 0)
  57993. config.outputDeviceName = outputDeviceDropDown->getSelectedId() < 0 ? String::empty
  57994. : outputDeviceDropDown->getText();
  57995. if (inputDeviceDropDown != 0)
  57996. config.inputDeviceName = inputDeviceDropDown->getSelectedId() < 0 ? String::empty
  57997. : inputDeviceDropDown->getText();
  57998. if (! type->hasSeparateInputsAndOutputs())
  57999. config.inputDeviceName = config.outputDeviceName;
  58000. if (comboBoxThatHasChanged == inputDeviceDropDown)
  58001. config.useDefaultInputChannels = true;
  58002. else
  58003. config.useDefaultOutputChannels = true;
  58004. error = setup.manager->setAudioDeviceSetup (config, true);
  58005. showCorrectDeviceName (inputDeviceDropDown, true);
  58006. showCorrectDeviceName (outputDeviceDropDown, false);
  58007. updateControlPanelButton();
  58008. resized();
  58009. }
  58010. else if (comboBoxThatHasChanged == sampleRateDropDown)
  58011. {
  58012. if (sampleRateDropDown->getSelectedId() > 0)
  58013. {
  58014. config.sampleRate = sampleRateDropDown->getSelectedId();
  58015. error = setup.manager->setAudioDeviceSetup (config, true);
  58016. }
  58017. }
  58018. else if (comboBoxThatHasChanged == bufferSizeDropDown)
  58019. {
  58020. if (bufferSizeDropDown->getSelectedId() > 0)
  58021. {
  58022. config.bufferSize = bufferSizeDropDown->getSelectedId();
  58023. error = setup.manager->setAudioDeviceSetup (config, true);
  58024. }
  58025. }
  58026. if (error.isNotEmpty())
  58027. {
  58028. AlertWindow::showMessageBox (AlertWindow::WarningIcon,
  58029. "Error when trying to open audio device!",
  58030. error);
  58031. }
  58032. }
  58033. void buttonClicked (Button* button)
  58034. {
  58035. if (button == showAdvancedSettingsButton)
  58036. {
  58037. showAdvancedSettingsButton->setVisible (false);
  58038. resized();
  58039. }
  58040. else if (button == showUIButton)
  58041. {
  58042. AudioIODevice* const device = setup.manager->getCurrentAudioDevice();
  58043. if (device != 0 && device->showControlPanel())
  58044. {
  58045. setup.manager->closeAudioDevice();
  58046. setup.manager->restartLastAudioDevice();
  58047. getTopLevelComponent()->toFront (true);
  58048. }
  58049. }
  58050. else if (button == testButton && testButton != 0)
  58051. {
  58052. setup.manager->playTestSound();
  58053. }
  58054. }
  58055. void updateControlPanelButton()
  58056. {
  58057. AudioIODevice* const currentDevice = setup.manager->getCurrentAudioDevice();
  58058. deleteAndZero (showUIButton);
  58059. if (currentDevice != 0 && currentDevice->hasControlPanel())
  58060. {
  58061. addAndMakeVisible (showUIButton = new TextButton (TRANS ("show this device's control panel"),
  58062. TRANS ("opens the device's own control panel")));
  58063. showUIButton->addButtonListener (this);
  58064. }
  58065. resized();
  58066. }
  58067. void changeListenerCallback (void*)
  58068. {
  58069. AudioIODevice* const currentDevice = setup.manager->getCurrentAudioDevice();
  58070. if (setup.maxNumOutputChannels > 0 || ! type->hasSeparateInputsAndOutputs())
  58071. {
  58072. if (outputDeviceDropDown == 0)
  58073. {
  58074. outputDeviceDropDown = new ComboBox (String::empty);
  58075. outputDeviceDropDown->addListener (this);
  58076. addAndMakeVisible (outputDeviceDropDown);
  58077. outputDeviceLabel = new Label (String::empty,
  58078. type->hasSeparateInputsAndOutputs() ? TRANS ("output:")
  58079. : TRANS ("device:"));
  58080. outputDeviceLabel->attachToComponent (outputDeviceDropDown, true);
  58081. if (setup.maxNumOutputChannels > 0)
  58082. {
  58083. addAndMakeVisible (testButton = new TextButton (TRANS ("Test")));
  58084. testButton->addButtonListener (this);
  58085. }
  58086. }
  58087. addNamesToDeviceBox (*outputDeviceDropDown, false);
  58088. }
  58089. if (setup.maxNumInputChannels > 0 && type->hasSeparateInputsAndOutputs())
  58090. {
  58091. if (inputDeviceDropDown == 0)
  58092. {
  58093. inputDeviceDropDown = new ComboBox (String::empty);
  58094. inputDeviceDropDown->addListener (this);
  58095. addAndMakeVisible (inputDeviceDropDown);
  58096. inputDeviceLabel = new Label (String::empty, TRANS ("input:"));
  58097. inputDeviceLabel->attachToComponent (inputDeviceDropDown, true);
  58098. addAndMakeVisible (inputLevelMeter
  58099. = new SimpleDeviceManagerInputLevelMeter (setup.manager));
  58100. }
  58101. addNamesToDeviceBox (*inputDeviceDropDown, true);
  58102. }
  58103. updateControlPanelButton();
  58104. showCorrectDeviceName (inputDeviceDropDown, true);
  58105. showCorrectDeviceName (outputDeviceDropDown, false);
  58106. if (currentDevice != 0)
  58107. {
  58108. if (setup.maxNumOutputChannels > 0
  58109. && setup.minNumOutputChannels < setup.manager->getCurrentAudioDevice()->getOutputChannelNames().size())
  58110. {
  58111. if (outputChanList == 0)
  58112. {
  58113. addAndMakeVisible (outputChanList
  58114. = new ChannelSelectorListBox (setup, ChannelSelectorListBox::audioOutputType,
  58115. TRANS ("(no audio output channels found)")));
  58116. outputChanLabel = new Label (String::empty, TRANS ("active output channels:"));
  58117. outputChanLabel->attachToComponent (outputChanList, true);
  58118. }
  58119. outputChanList->refresh();
  58120. }
  58121. else
  58122. {
  58123. deleteAndZero (outputChanLabel);
  58124. deleteAndZero (outputChanList);
  58125. }
  58126. if (setup.maxNumInputChannels > 0
  58127. && setup.minNumInputChannels < setup.manager->getCurrentAudioDevice()->getInputChannelNames().size())
  58128. {
  58129. if (inputChanList == 0)
  58130. {
  58131. addAndMakeVisible (inputChanList
  58132. = new ChannelSelectorListBox (setup, ChannelSelectorListBox::audioInputType,
  58133. TRANS ("(no audio input channels found)")));
  58134. inputChanLabel = new Label (String::empty, TRANS ("active input channels:"));
  58135. inputChanLabel->attachToComponent (inputChanList, true);
  58136. }
  58137. inputChanList->refresh();
  58138. }
  58139. else
  58140. {
  58141. deleteAndZero (inputChanLabel);
  58142. deleteAndZero (inputChanList);
  58143. }
  58144. // sample rate..
  58145. {
  58146. if (sampleRateDropDown == 0)
  58147. {
  58148. addAndMakeVisible (sampleRateDropDown = new ComboBox (String::empty));
  58149. sampleRateDropDown->addListener (this);
  58150. delete sampleRateLabel;
  58151. sampleRateLabel = new Label (String::empty, TRANS ("sample rate:"));
  58152. sampleRateLabel->attachToComponent (sampleRateDropDown, true);
  58153. }
  58154. else
  58155. {
  58156. sampleRateDropDown->clear();
  58157. sampleRateDropDown->removeListener (this);
  58158. }
  58159. const int numRates = currentDevice->getNumSampleRates();
  58160. for (int i = 0; i < numRates; ++i)
  58161. {
  58162. const int rate = roundToInt (currentDevice->getSampleRate (i));
  58163. sampleRateDropDown->addItem (String (rate) + " Hz", rate);
  58164. }
  58165. sampleRateDropDown->setSelectedId (roundToInt (currentDevice->getCurrentSampleRate()), true);
  58166. sampleRateDropDown->addListener (this);
  58167. }
  58168. // buffer size
  58169. {
  58170. if (bufferSizeDropDown == 0)
  58171. {
  58172. addAndMakeVisible (bufferSizeDropDown = new ComboBox (String::empty));
  58173. bufferSizeDropDown->addListener (this);
  58174. delete bufferSizeLabel;
  58175. bufferSizeLabel = new Label (String::empty, TRANS ("audio buffer size:"));
  58176. bufferSizeLabel->attachToComponent (bufferSizeDropDown, true);
  58177. }
  58178. else
  58179. {
  58180. bufferSizeDropDown->clear();
  58181. }
  58182. const int numBufferSizes = currentDevice->getNumBufferSizesAvailable();
  58183. double currentRate = currentDevice->getCurrentSampleRate();
  58184. if (currentRate == 0)
  58185. currentRate = 48000.0;
  58186. for (int i = 0; i < numBufferSizes; ++i)
  58187. {
  58188. const int bs = currentDevice->getBufferSizeSamples (i);
  58189. bufferSizeDropDown->addItem (String (bs)
  58190. + " samples ("
  58191. + String (bs * 1000.0 / currentRate, 1)
  58192. + " ms)",
  58193. bs);
  58194. }
  58195. bufferSizeDropDown->setSelectedId (currentDevice->getCurrentBufferSizeSamples(), true);
  58196. }
  58197. }
  58198. else
  58199. {
  58200. jassert (setup.manager->getCurrentAudioDevice() == 0); // not the correct device type!
  58201. deleteAndZero (sampleRateLabel);
  58202. deleteAndZero (bufferSizeLabel);
  58203. deleteAndZero (sampleRateDropDown);
  58204. deleteAndZero (bufferSizeDropDown);
  58205. if (outputDeviceDropDown != 0)
  58206. outputDeviceDropDown->setSelectedId (-1, true);
  58207. if (inputDeviceDropDown != 0)
  58208. inputDeviceDropDown->setSelectedId (-1, true);
  58209. }
  58210. resized();
  58211. setSize (getWidth(), getLowestY() + 4);
  58212. }
  58213. private:
  58214. AudioIODeviceType* const type;
  58215. const AudioIODeviceType::DeviceSetupDetails setup;
  58216. ComboBox* outputDeviceDropDown;
  58217. ComboBox* inputDeviceDropDown;
  58218. ComboBox* sampleRateDropDown;
  58219. ComboBox* bufferSizeDropDown;
  58220. Label* outputDeviceLabel;
  58221. Label* inputDeviceLabel;
  58222. Label* sampleRateLabel;
  58223. Label* bufferSizeLabel;
  58224. Label* inputChanLabel;
  58225. Label* outputChanLabel;
  58226. TextButton* testButton;
  58227. Component* inputLevelMeter;
  58228. TextButton* showUIButton;
  58229. TextButton* showAdvancedSettingsButton;
  58230. void showCorrectDeviceName (ComboBox* const box, const bool isInput)
  58231. {
  58232. if (box != 0)
  58233. {
  58234. AudioIODevice* const currentDevice = dynamic_cast <AudioIODevice*> (setup.manager->getCurrentAudioDevice());
  58235. const int index = type->getIndexOfDevice (currentDevice, isInput);
  58236. box->setSelectedId (index + 1, true);
  58237. if (testButton != 0 && ! isInput)
  58238. testButton->setEnabled (index >= 0);
  58239. }
  58240. }
  58241. void addNamesToDeviceBox (ComboBox& combo, bool isInputs)
  58242. {
  58243. const StringArray devs (type->getDeviceNames (isInputs));
  58244. combo.clear (true);
  58245. for (int i = 0; i < devs.size(); ++i)
  58246. combo.addItem (devs[i], i + 1);
  58247. combo.addItem (TRANS("<< none >>"), -1);
  58248. combo.setSelectedId (-1, true);
  58249. }
  58250. int getLowestY() const
  58251. {
  58252. int y = 0;
  58253. for (int i = getNumChildComponents(); --i >= 0;)
  58254. y = jmax (y, getChildComponent (i)->getBottom());
  58255. return y;
  58256. }
  58257. public:
  58258. class ChannelSelectorListBox : public ListBox,
  58259. public ListBoxModel
  58260. {
  58261. public:
  58262. enum BoxType
  58263. {
  58264. audioInputType,
  58265. audioOutputType
  58266. };
  58267. ChannelSelectorListBox (const AudioIODeviceType::DeviceSetupDetails& setup_,
  58268. const BoxType type_,
  58269. const String& noItemsMessage_)
  58270. : ListBox (String::empty, 0),
  58271. setup (setup_),
  58272. type (type_),
  58273. noItemsMessage (noItemsMessage_)
  58274. {
  58275. refresh();
  58276. setModel (this);
  58277. setOutlineThickness (1);
  58278. }
  58279. ~ChannelSelectorListBox()
  58280. {
  58281. }
  58282. void refresh()
  58283. {
  58284. items.clear();
  58285. AudioIODevice* const currentDevice = setup.manager->getCurrentAudioDevice();
  58286. if (currentDevice != 0)
  58287. {
  58288. if (type == audioInputType)
  58289. items = currentDevice->getInputChannelNames();
  58290. else if (type == audioOutputType)
  58291. items = currentDevice->getOutputChannelNames();
  58292. if (setup.useStereoPairs)
  58293. {
  58294. StringArray pairs;
  58295. for (int i = 0; i < items.size(); i += 2)
  58296. {
  58297. const String name (items[i]);
  58298. const String name2 (items[i + 1]);
  58299. String commonBit;
  58300. for (int j = 0; j < name.length(); ++j)
  58301. if (name.substring (0, j).equalsIgnoreCase (name2.substring (0, j)))
  58302. commonBit = name.substring (0, j);
  58303. // Make sure we only split the name at a space, because otherwise, things
  58304. // like "input 11" + "input 12" would become "input 11 + 2"
  58305. while (commonBit.isNotEmpty() && ! CharacterFunctions::isWhitespace (commonBit.getLastCharacter()))
  58306. commonBit = commonBit.dropLastCharacters (1);
  58307. pairs.add (name.trim() + " + " + name2.substring (commonBit.length()).trim());
  58308. }
  58309. items = pairs;
  58310. }
  58311. }
  58312. updateContent();
  58313. repaint();
  58314. }
  58315. int getNumRows()
  58316. {
  58317. return items.size();
  58318. }
  58319. void paintListBoxItem (int row,
  58320. Graphics& g,
  58321. int width, int height,
  58322. bool rowIsSelected)
  58323. {
  58324. if (((unsigned int) row) < (unsigned int) items.size())
  58325. {
  58326. if (rowIsSelected)
  58327. g.fillAll (findColour (TextEditor::highlightColourId)
  58328. .withMultipliedAlpha (0.3f));
  58329. const String item (items [row]);
  58330. bool enabled = false;
  58331. AudioDeviceManager::AudioDeviceSetup config;
  58332. setup.manager->getAudioDeviceSetup (config);
  58333. if (setup.useStereoPairs)
  58334. {
  58335. if (type == audioInputType)
  58336. enabled = config.inputChannels [row * 2] || config.inputChannels [row * 2 + 1];
  58337. else if (type == audioOutputType)
  58338. enabled = config.outputChannels [row * 2] || config.outputChannels [row * 2 + 1];
  58339. }
  58340. else
  58341. {
  58342. if (type == audioInputType)
  58343. enabled = config.inputChannels [row];
  58344. else if (type == audioOutputType)
  58345. enabled = config.outputChannels [row];
  58346. }
  58347. const int x = getTickX();
  58348. const float tickW = height * 0.75f;
  58349. getLookAndFeel().drawTickBox (g, *this, x - tickW, (height - tickW) / 2, tickW, tickW,
  58350. enabled, true, true, false);
  58351. g.setFont (height * 0.6f);
  58352. g.setColour (findColour (ListBox::textColourId, true).withMultipliedAlpha (enabled ? 1.0f : 0.6f));
  58353. g.drawText (item, x, 0, width - x - 2, height, Justification::centredLeft, true);
  58354. }
  58355. }
  58356. void listBoxItemClicked (int row, const MouseEvent& e)
  58357. {
  58358. selectRow (row);
  58359. if (e.x < getTickX())
  58360. flipEnablement (row);
  58361. }
  58362. void listBoxItemDoubleClicked (int row, const MouseEvent&)
  58363. {
  58364. flipEnablement (row);
  58365. }
  58366. void returnKeyPressed (int row)
  58367. {
  58368. flipEnablement (row);
  58369. }
  58370. void paint (Graphics& g)
  58371. {
  58372. ListBox::paint (g);
  58373. if (items.size() == 0)
  58374. {
  58375. g.setColour (Colours::grey);
  58376. g.setFont (13.0f);
  58377. g.drawText (noItemsMessage,
  58378. 0, 0, getWidth(), getHeight() / 2,
  58379. Justification::centred, true);
  58380. }
  58381. }
  58382. int getBestHeight (int maxHeight)
  58383. {
  58384. return getRowHeight() * jlimit (2, jmax (2, maxHeight / getRowHeight()),
  58385. getNumRows())
  58386. + getOutlineThickness() * 2;
  58387. }
  58388. juce_UseDebuggingNewOperator
  58389. private:
  58390. const AudioIODeviceType::DeviceSetupDetails setup;
  58391. const BoxType type;
  58392. const String noItemsMessage;
  58393. StringArray items;
  58394. void flipEnablement (const int row)
  58395. {
  58396. jassert (type == audioInputType || type == audioOutputType);
  58397. if (((unsigned int) row) < (unsigned int) items.size())
  58398. {
  58399. AudioDeviceManager::AudioDeviceSetup config;
  58400. setup.manager->getAudioDeviceSetup (config);
  58401. if (setup.useStereoPairs)
  58402. {
  58403. BigInteger bits;
  58404. BigInteger& original = (type == audioInputType ? config.inputChannels
  58405. : config.outputChannels);
  58406. int i;
  58407. for (i = 0; i < 256; i += 2)
  58408. bits.setBit (i / 2, original [i] || original [i + 1]);
  58409. if (type == audioInputType)
  58410. {
  58411. config.useDefaultInputChannels = false;
  58412. flipBit (bits, row, setup.minNumInputChannels / 2, setup.maxNumInputChannels / 2);
  58413. }
  58414. else
  58415. {
  58416. config.useDefaultOutputChannels = false;
  58417. flipBit (bits, row, setup.minNumOutputChannels / 2, setup.maxNumOutputChannels / 2);
  58418. }
  58419. for (i = 0; i < 256; ++i)
  58420. original.setBit (i, bits [i / 2]);
  58421. }
  58422. else
  58423. {
  58424. if (type == audioInputType)
  58425. {
  58426. config.useDefaultInputChannels = false;
  58427. flipBit (config.inputChannels, row, setup.minNumInputChannels, setup.maxNumInputChannels);
  58428. }
  58429. else
  58430. {
  58431. config.useDefaultOutputChannels = false;
  58432. flipBit (config.outputChannels, row, setup.minNumOutputChannels, setup.maxNumOutputChannels);
  58433. }
  58434. }
  58435. String error (setup.manager->setAudioDeviceSetup (config, true));
  58436. if (! error.isEmpty())
  58437. {
  58438. //xxx
  58439. }
  58440. }
  58441. }
  58442. static void flipBit (BigInteger& chans, int index, int minNumber, int maxNumber)
  58443. {
  58444. const int numActive = chans.countNumberOfSetBits();
  58445. if (chans [index])
  58446. {
  58447. if (numActive > minNumber)
  58448. chans.setBit (index, false);
  58449. }
  58450. else
  58451. {
  58452. if (numActive >= maxNumber)
  58453. {
  58454. const int firstActiveChan = chans.findNextSetBit();
  58455. chans.setBit (index > firstActiveChan
  58456. ? firstActiveChan : chans.getHighestBit(),
  58457. false);
  58458. }
  58459. chans.setBit (index, true);
  58460. }
  58461. }
  58462. int getTickX() const
  58463. {
  58464. return getRowHeight() + 5;
  58465. }
  58466. ChannelSelectorListBox (const ChannelSelectorListBox&);
  58467. ChannelSelectorListBox& operator= (const ChannelSelectorListBox&);
  58468. };
  58469. private:
  58470. ChannelSelectorListBox* inputChanList;
  58471. ChannelSelectorListBox* outputChanList;
  58472. AudioDeviceSettingsPanel (const AudioDeviceSettingsPanel&);
  58473. AudioDeviceSettingsPanel& operator= (const AudioDeviceSettingsPanel&);
  58474. };
  58475. AudioDeviceSelectorComponent::AudioDeviceSelectorComponent (AudioDeviceManager& deviceManager_,
  58476. const int minInputChannels_,
  58477. const int maxInputChannels_,
  58478. const int minOutputChannels_,
  58479. const int maxOutputChannels_,
  58480. const bool showMidiInputOptions,
  58481. const bool showMidiOutputSelector,
  58482. const bool showChannelsAsStereoPairs_,
  58483. const bool hideAdvancedOptionsWithButton_)
  58484. : deviceManager (deviceManager_),
  58485. deviceTypeDropDown (0),
  58486. deviceTypeDropDownLabel (0),
  58487. audioDeviceSettingsComp (0),
  58488. minOutputChannels (minOutputChannels_),
  58489. maxOutputChannels (maxOutputChannels_),
  58490. minInputChannels (minInputChannels_),
  58491. maxInputChannels (maxInputChannels_),
  58492. showChannelsAsStereoPairs (showChannelsAsStereoPairs_),
  58493. hideAdvancedOptionsWithButton (hideAdvancedOptionsWithButton_)
  58494. {
  58495. jassert (minOutputChannels >= 0 && minOutputChannels <= maxOutputChannels);
  58496. jassert (minInputChannels >= 0 && minInputChannels <= maxInputChannels);
  58497. if (deviceManager_.getAvailableDeviceTypes().size() > 1)
  58498. {
  58499. deviceTypeDropDown = new ComboBox (String::empty);
  58500. for (int i = 0; i < deviceManager_.getAvailableDeviceTypes().size(); ++i)
  58501. {
  58502. deviceTypeDropDown
  58503. ->addItem (deviceManager_.getAvailableDeviceTypes().getUnchecked(i)->getTypeName(),
  58504. i + 1);
  58505. }
  58506. addAndMakeVisible (deviceTypeDropDown);
  58507. deviceTypeDropDown->addListener (this);
  58508. deviceTypeDropDownLabel = new Label (String::empty, TRANS ("audio device type:"));
  58509. deviceTypeDropDownLabel->setJustificationType (Justification::centredRight);
  58510. deviceTypeDropDownLabel->attachToComponent (deviceTypeDropDown, true);
  58511. }
  58512. if (showMidiInputOptions)
  58513. {
  58514. addAndMakeVisible (midiInputsList
  58515. = new MidiInputSelectorComponentListBox (deviceManager,
  58516. TRANS("(no midi inputs available)"),
  58517. 0, 0));
  58518. midiInputsLabel = new Label (String::empty, TRANS ("active midi inputs:"));
  58519. midiInputsLabel->setJustificationType (Justification::topRight);
  58520. midiInputsLabel->attachToComponent (midiInputsList, true);
  58521. }
  58522. else
  58523. {
  58524. midiInputsList = 0;
  58525. midiInputsLabel = 0;
  58526. }
  58527. if (showMidiOutputSelector)
  58528. {
  58529. addAndMakeVisible (midiOutputSelector = new ComboBox (String::empty));
  58530. midiOutputSelector->addListener (this);
  58531. midiOutputLabel = new Label ("lm", TRANS("Midi Output:"));
  58532. midiOutputLabel->attachToComponent (midiOutputSelector, true);
  58533. }
  58534. else
  58535. {
  58536. midiOutputSelector = 0;
  58537. midiOutputLabel = 0;
  58538. }
  58539. deviceManager_.addChangeListener (this);
  58540. changeListenerCallback (0);
  58541. }
  58542. AudioDeviceSelectorComponent::~AudioDeviceSelectorComponent()
  58543. {
  58544. deviceManager.removeChangeListener (this);
  58545. deleteAllChildren();
  58546. }
  58547. void AudioDeviceSelectorComponent::resized()
  58548. {
  58549. const int lx = proportionOfWidth (0.35f);
  58550. const int w = proportionOfWidth (0.4f);
  58551. const int h = 24;
  58552. const int space = 6;
  58553. const int dh = h + space;
  58554. int y = 15;
  58555. if (deviceTypeDropDown != 0)
  58556. {
  58557. deviceTypeDropDown->setBounds (lx, y, proportionOfWidth (0.3f), h);
  58558. y += dh + space * 2;
  58559. }
  58560. if (audioDeviceSettingsComp != 0)
  58561. {
  58562. audioDeviceSettingsComp->setBounds (0, y, getWidth(), audioDeviceSettingsComp->getHeight());
  58563. y += audioDeviceSettingsComp->getHeight() + space;
  58564. }
  58565. if (midiInputsList != 0)
  58566. {
  58567. const int bh = midiInputsList->getBestHeight (jmin (h * 8, getHeight() - y - space - h));
  58568. midiInputsList->setBounds (lx, y, w, bh);
  58569. y += bh + space;
  58570. }
  58571. if (midiOutputSelector != 0)
  58572. midiOutputSelector->setBounds (lx, y, w, h);
  58573. }
  58574. void AudioDeviceSelectorComponent::childBoundsChanged (Component* child)
  58575. {
  58576. if (child == audioDeviceSettingsComp)
  58577. resized();
  58578. }
  58579. void AudioDeviceSelectorComponent::buttonClicked (Button*)
  58580. {
  58581. AudioIODevice* const device = deviceManager.getCurrentAudioDevice();
  58582. if (device != 0 && device->hasControlPanel())
  58583. {
  58584. if (device->showControlPanel())
  58585. deviceManager.restartLastAudioDevice();
  58586. getTopLevelComponent()->toFront (true);
  58587. }
  58588. }
  58589. void AudioDeviceSelectorComponent::comboBoxChanged (ComboBox* comboBoxThatHasChanged)
  58590. {
  58591. if (comboBoxThatHasChanged == deviceTypeDropDown)
  58592. {
  58593. AudioIODeviceType* const type = deviceManager.getAvailableDeviceTypes() [deviceTypeDropDown->getSelectedId() - 1];
  58594. if (type != 0)
  58595. {
  58596. deleteAndZero (audioDeviceSettingsComp);
  58597. deviceManager.setCurrentAudioDeviceType (type->getTypeName(), true);
  58598. changeListenerCallback (0); // needed in case the type hasn't actally changed
  58599. }
  58600. }
  58601. else if (comboBoxThatHasChanged == midiOutputSelector)
  58602. {
  58603. deviceManager.setDefaultMidiOutput (midiOutputSelector->getText());
  58604. }
  58605. }
  58606. void AudioDeviceSelectorComponent::changeListenerCallback (void*)
  58607. {
  58608. if (deviceTypeDropDown != 0)
  58609. {
  58610. deviceTypeDropDown->setText (deviceManager.getCurrentAudioDeviceType(), false);
  58611. }
  58612. if (audioDeviceSettingsComp == 0
  58613. || audioDeviceSettingsCompType != deviceManager.getCurrentAudioDeviceType())
  58614. {
  58615. audioDeviceSettingsCompType = deviceManager.getCurrentAudioDeviceType();
  58616. deleteAndZero (audioDeviceSettingsComp);
  58617. AudioIODeviceType* const type
  58618. = deviceManager.getAvailableDeviceTypes() [deviceTypeDropDown == 0
  58619. ? 0 : deviceTypeDropDown->getSelectedId() - 1];
  58620. if (type != 0)
  58621. {
  58622. AudioIODeviceType::DeviceSetupDetails details;
  58623. details.manager = &deviceManager;
  58624. details.minNumInputChannels = minInputChannels;
  58625. details.maxNumInputChannels = maxInputChannels;
  58626. details.minNumOutputChannels = minOutputChannels;
  58627. details.maxNumOutputChannels = maxOutputChannels;
  58628. details.useStereoPairs = showChannelsAsStereoPairs;
  58629. audioDeviceSettingsComp = new AudioDeviceSettingsPanel (type, details, hideAdvancedOptionsWithButton);
  58630. if (audioDeviceSettingsComp != 0)
  58631. {
  58632. addAndMakeVisible (audioDeviceSettingsComp);
  58633. audioDeviceSettingsComp->resized();
  58634. }
  58635. }
  58636. }
  58637. if (midiInputsList != 0)
  58638. {
  58639. midiInputsList->updateContent();
  58640. midiInputsList->repaint();
  58641. }
  58642. if (midiOutputSelector != 0)
  58643. {
  58644. midiOutputSelector->clear();
  58645. const StringArray midiOuts (MidiOutput::getDevices());
  58646. midiOutputSelector->addItem (TRANS("<< none >>"), -1);
  58647. midiOutputSelector->addSeparator();
  58648. for (int i = 0; i < midiOuts.size(); ++i)
  58649. midiOutputSelector->addItem (midiOuts[i], i + 1);
  58650. int current = -1;
  58651. if (deviceManager.getDefaultMidiOutput() != 0)
  58652. current = 1 + midiOuts.indexOf (deviceManager.getDefaultMidiOutputName());
  58653. midiOutputSelector->setSelectedId (current, true);
  58654. }
  58655. resized();
  58656. }
  58657. END_JUCE_NAMESPACE
  58658. /*** End of inlined file: juce_AudioDeviceSelectorComponent.cpp ***/
  58659. /*** Start of inlined file: juce_BubbleComponent.cpp ***/
  58660. BEGIN_JUCE_NAMESPACE
  58661. BubbleComponent::BubbleComponent()
  58662. : side (0),
  58663. allowablePlacements (above | below | left | right),
  58664. arrowTipX (0.0f),
  58665. arrowTipY (0.0f)
  58666. {
  58667. setInterceptsMouseClicks (false, false);
  58668. shadow.setShadowProperties (5.0f, 0.35f, 0, 0);
  58669. setComponentEffect (&shadow);
  58670. }
  58671. BubbleComponent::~BubbleComponent()
  58672. {
  58673. }
  58674. void BubbleComponent::paint (Graphics& g)
  58675. {
  58676. int x = content.getX();
  58677. int y = content.getY();
  58678. int w = content.getWidth();
  58679. int h = content.getHeight();
  58680. int cw, ch;
  58681. getContentSize (cw, ch);
  58682. if (side == 3)
  58683. x += w - cw;
  58684. else if (side != 1)
  58685. x += (w - cw) / 2;
  58686. w = cw;
  58687. if (side == 2)
  58688. y += h - ch;
  58689. else if (side != 0)
  58690. y += (h - ch) / 2;
  58691. h = ch;
  58692. getLookAndFeel().drawBubble (g, arrowTipX, arrowTipY,
  58693. (float) x, (float) y,
  58694. (float) w, (float) h);
  58695. const int cx = x + (w - cw) / 2;
  58696. const int cy = y + (h - ch) / 2;
  58697. const int indent = 3;
  58698. g.setOrigin (cx + indent, cy + indent);
  58699. g.reduceClipRegion (0, 0, cw - indent * 2, ch - indent * 2);
  58700. paintContent (g, cw - indent * 2, ch - indent * 2);
  58701. }
  58702. void BubbleComponent::setAllowedPlacement (const int newPlacement)
  58703. {
  58704. allowablePlacements = newPlacement;
  58705. }
  58706. void BubbleComponent::setPosition (Component* componentToPointTo)
  58707. {
  58708. jassert (componentToPointTo->isValidComponent());
  58709. Point<int> pos;
  58710. if (getParentComponent() != 0)
  58711. pos = componentToPointTo->relativePositionToOtherComponent (getParentComponent(), pos);
  58712. else
  58713. pos = componentToPointTo->relativePositionToGlobal (pos);
  58714. setPosition (Rectangle<int> (pos.getX(), pos.getY(), componentToPointTo->getWidth(), componentToPointTo->getHeight()));
  58715. }
  58716. void BubbleComponent::setPosition (const int arrowTipX_,
  58717. const int arrowTipY_)
  58718. {
  58719. setPosition (Rectangle<int> (arrowTipX_, arrowTipY_, 1, 1));
  58720. }
  58721. void BubbleComponent::setPosition (const Rectangle<int>& rectangleToPointTo)
  58722. {
  58723. Rectangle<int> availableSpace;
  58724. if (getParentComponent() != 0)
  58725. {
  58726. availableSpace.setSize (getParentComponent()->getWidth(),
  58727. getParentComponent()->getHeight());
  58728. }
  58729. else
  58730. {
  58731. availableSpace = getParentMonitorArea();
  58732. }
  58733. int x = 0;
  58734. int y = 0;
  58735. int w = 150;
  58736. int h = 30;
  58737. getContentSize (w, h);
  58738. w += 30;
  58739. h += 30;
  58740. const float edgeIndent = 2.0f;
  58741. const int arrowLength = jmin (10, h / 3, w / 3);
  58742. int spaceAbove = ((allowablePlacements & above) != 0) ? jmax (0, rectangleToPointTo.getY() - availableSpace.getY()) : -1;
  58743. int spaceBelow = ((allowablePlacements & below) != 0) ? jmax (0, availableSpace.getBottom() - rectangleToPointTo.getBottom()) : -1;
  58744. int spaceLeft = ((allowablePlacements & left) != 0) ? jmax (0, rectangleToPointTo.getX() - availableSpace.getX()) : -1;
  58745. int spaceRight = ((allowablePlacements & right) != 0) ? jmax (0, availableSpace.getRight() - rectangleToPointTo.getRight()) : -1;
  58746. // look at whether the component is elongated, and if so, try to position next to its longer dimension.
  58747. if (rectangleToPointTo.getWidth() > rectangleToPointTo.getHeight() * 2
  58748. && (spaceAbove > h + 20 || spaceBelow > h + 20))
  58749. {
  58750. spaceLeft = spaceRight = 0;
  58751. }
  58752. else if (rectangleToPointTo.getWidth() < rectangleToPointTo.getHeight() / 2
  58753. && (spaceLeft > w + 20 || spaceRight > w + 20))
  58754. {
  58755. spaceAbove = spaceBelow = 0;
  58756. }
  58757. if (jmax (spaceAbove, spaceBelow) >= jmax (spaceLeft, spaceRight))
  58758. {
  58759. x = rectangleToPointTo.getX() + (rectangleToPointTo.getWidth() - w) / 2;
  58760. arrowTipX = w * 0.5f;
  58761. content.setSize (w, h - arrowLength);
  58762. if (spaceAbove >= spaceBelow)
  58763. {
  58764. // above
  58765. y = rectangleToPointTo.getY() - h;
  58766. content.setPosition (0, 0);
  58767. arrowTipY = h - edgeIndent;
  58768. side = 2;
  58769. }
  58770. else
  58771. {
  58772. // below
  58773. y = rectangleToPointTo.getBottom();
  58774. content.setPosition (0, arrowLength);
  58775. arrowTipY = edgeIndent;
  58776. side = 0;
  58777. }
  58778. }
  58779. else
  58780. {
  58781. y = rectangleToPointTo.getY() + (rectangleToPointTo.getHeight() - h) / 2;
  58782. arrowTipY = h * 0.5f;
  58783. content.setSize (w - arrowLength, h);
  58784. if (spaceLeft > spaceRight)
  58785. {
  58786. // on the left
  58787. x = rectangleToPointTo.getX() - w;
  58788. content.setPosition (0, 0);
  58789. arrowTipX = w - edgeIndent;
  58790. side = 3;
  58791. }
  58792. else
  58793. {
  58794. // on the right
  58795. x = rectangleToPointTo.getRight();
  58796. content.setPosition (arrowLength, 0);
  58797. arrowTipX = edgeIndent;
  58798. side = 1;
  58799. }
  58800. }
  58801. setBounds (x, y, w, h);
  58802. }
  58803. END_JUCE_NAMESPACE
  58804. /*** End of inlined file: juce_BubbleComponent.cpp ***/
  58805. /*** Start of inlined file: juce_BubbleMessageComponent.cpp ***/
  58806. BEGIN_JUCE_NAMESPACE
  58807. BubbleMessageComponent::BubbleMessageComponent (int fadeOutLengthMs)
  58808. : fadeOutLength (fadeOutLengthMs),
  58809. deleteAfterUse (false)
  58810. {
  58811. }
  58812. BubbleMessageComponent::~BubbleMessageComponent()
  58813. {
  58814. fadeOutComponent (fadeOutLength);
  58815. }
  58816. void BubbleMessageComponent::showAt (int x, int y,
  58817. const String& text,
  58818. const int numMillisecondsBeforeRemoving,
  58819. const bool removeWhenMouseClicked,
  58820. const bool deleteSelfAfterUse)
  58821. {
  58822. textLayout.clear();
  58823. textLayout.setText (text, Font (14.0f));
  58824. textLayout.layout (256, Justification::centredLeft, true);
  58825. setPosition (x, y);
  58826. init (numMillisecondsBeforeRemoving, removeWhenMouseClicked, deleteSelfAfterUse);
  58827. }
  58828. void BubbleMessageComponent::showAt (Component* const component,
  58829. const String& text,
  58830. const int numMillisecondsBeforeRemoving,
  58831. const bool removeWhenMouseClicked,
  58832. const bool deleteSelfAfterUse)
  58833. {
  58834. textLayout.clear();
  58835. textLayout.setText (text, Font (14.0f));
  58836. textLayout.layout (256, Justification::centredLeft, true);
  58837. setPosition (component);
  58838. init (numMillisecondsBeforeRemoving, removeWhenMouseClicked, deleteSelfAfterUse);
  58839. }
  58840. void BubbleMessageComponent::init (const int numMillisecondsBeforeRemoving,
  58841. const bool removeWhenMouseClicked,
  58842. const bool deleteSelfAfterUse)
  58843. {
  58844. setVisible (true);
  58845. deleteAfterUse = deleteSelfAfterUse;
  58846. if (numMillisecondsBeforeRemoving > 0)
  58847. expiryTime = Time::getMillisecondCounter() + numMillisecondsBeforeRemoving;
  58848. else
  58849. expiryTime = 0;
  58850. startTimer (77);
  58851. mouseClickCounter = Desktop::getInstance().getMouseButtonClickCounter();
  58852. if (! (removeWhenMouseClicked && isShowing()))
  58853. mouseClickCounter += 0xfffff;
  58854. repaint();
  58855. }
  58856. void BubbleMessageComponent::getContentSize (int& w, int& h)
  58857. {
  58858. w = textLayout.getWidth() + 16;
  58859. h = textLayout.getHeight() + 16;
  58860. }
  58861. void BubbleMessageComponent::paintContent (Graphics& g, int w, int h)
  58862. {
  58863. g.setColour (findColour (TooltipWindow::textColourId));
  58864. textLayout.drawWithin (g, 0, 0, w, h, Justification::centred);
  58865. }
  58866. void BubbleMessageComponent::timerCallback()
  58867. {
  58868. if (Desktop::getInstance().getMouseButtonClickCounter() > mouseClickCounter)
  58869. {
  58870. stopTimer();
  58871. setVisible (false);
  58872. if (deleteAfterUse)
  58873. delete this;
  58874. }
  58875. else if (expiryTime != 0 && Time::getMillisecondCounter() > expiryTime)
  58876. {
  58877. stopTimer();
  58878. fadeOutComponent (fadeOutLength);
  58879. if (deleteAfterUse)
  58880. delete this;
  58881. }
  58882. }
  58883. END_JUCE_NAMESPACE
  58884. /*** End of inlined file: juce_BubbleMessageComponent.cpp ***/
  58885. /*** Start of inlined file: juce_ColourSelector.cpp ***/
  58886. BEGIN_JUCE_NAMESPACE
  58887. static const int swatchesPerRow = 8;
  58888. static const int swatchHeight = 22;
  58889. class ColourComponentSlider : public Slider
  58890. {
  58891. public:
  58892. ColourComponentSlider (const String& name)
  58893. : Slider (name)
  58894. {
  58895. setRange (0.0, 255.0, 1.0);
  58896. }
  58897. ~ColourComponentSlider()
  58898. {
  58899. }
  58900. const String getTextFromValue (double value)
  58901. {
  58902. return String::toHexString ((int) value).toUpperCase().paddedLeft ('0', 2);
  58903. }
  58904. double getValueFromText (const String& text)
  58905. {
  58906. return (double) text.getHexValue32();
  58907. }
  58908. private:
  58909. ColourComponentSlider (const ColourComponentSlider&);
  58910. ColourComponentSlider& operator= (const ColourComponentSlider&);
  58911. };
  58912. class ColourSpaceMarker : public Component
  58913. {
  58914. public:
  58915. ColourSpaceMarker()
  58916. {
  58917. setInterceptsMouseClicks (false, false);
  58918. }
  58919. ~ColourSpaceMarker()
  58920. {
  58921. }
  58922. void paint (Graphics& g)
  58923. {
  58924. g.setColour (Colour::greyLevel (0.1f));
  58925. g.drawEllipse (1.0f, 1.0f, getWidth() - 2.0f, getHeight() - 2.0f, 1.0f);
  58926. g.setColour (Colour::greyLevel (0.9f));
  58927. g.drawEllipse (2.0f, 2.0f, getWidth() - 4.0f, getHeight() - 4.0f, 1.0f);
  58928. }
  58929. private:
  58930. ColourSpaceMarker (const ColourSpaceMarker&);
  58931. ColourSpaceMarker& operator= (const ColourSpaceMarker&);
  58932. };
  58933. class ColourSelector::ColourSpaceView : public Component
  58934. {
  58935. public:
  58936. ColourSpaceView (ColourSelector* owner_,
  58937. float& h_, float& s_, float& v_,
  58938. const int edgeSize)
  58939. : owner (owner_),
  58940. h (h_), s (s_), v (v_),
  58941. lastHue (0.0f),
  58942. edge (edgeSize)
  58943. {
  58944. addAndMakeVisible (marker = new ColourSpaceMarker());
  58945. setMouseCursor (MouseCursor::CrosshairCursor);
  58946. }
  58947. ~ColourSpaceView()
  58948. {
  58949. deleteAllChildren();
  58950. }
  58951. void paint (Graphics& g)
  58952. {
  58953. if (colours == 0)
  58954. {
  58955. const int width = getWidth() / 2;
  58956. const int height = getHeight() / 2;
  58957. colours = new Image (Image::RGB, width, height, false);
  58958. Image::BitmapData pixels (*colours, 0, 0, width, height, true);
  58959. for (int y = 0; y < height; ++y)
  58960. {
  58961. const float val = 1.0f - y / (float) height;
  58962. for (int x = 0; x < width; ++x)
  58963. {
  58964. const float sat = x / (float) width;
  58965. const Colour col (h, sat, val, 1.0f);
  58966. PixelRGB* const pix = (PixelRGB*) pixels.getPixelPointer (x, y);
  58967. pix->set (col.getPixelARGB());
  58968. }
  58969. }
  58970. }
  58971. g.setOpacity (1.0f);
  58972. g.drawImage (colours, edge, edge, getWidth() - edge * 2, getHeight() - edge * 2,
  58973. 0, 0, colours->getWidth(), colours->getHeight());
  58974. }
  58975. void mouseDown (const MouseEvent& e)
  58976. {
  58977. mouseDrag (e);
  58978. }
  58979. void mouseDrag (const MouseEvent& e)
  58980. {
  58981. const float sat = (e.x - edge) / (float) (getWidth() - edge * 2);
  58982. const float val = 1.0f - (e.y - edge) / (float) (getHeight() - edge * 2);
  58983. owner->setSV (sat, val);
  58984. }
  58985. void updateIfNeeded()
  58986. {
  58987. if (lastHue != h)
  58988. {
  58989. lastHue = h;
  58990. colours = 0;
  58991. repaint();
  58992. }
  58993. updateMarker();
  58994. }
  58995. void resized()
  58996. {
  58997. colours = 0;
  58998. updateMarker();
  58999. }
  59000. private:
  59001. ColourSelector* const owner;
  59002. float& h;
  59003. float& s;
  59004. float& v;
  59005. float lastHue;
  59006. ColourSpaceMarker* marker;
  59007. const int edge;
  59008. ScopedPointer <Image> colours;
  59009. void updateMarker() const
  59010. {
  59011. marker->setBounds (roundToInt ((getWidth() - edge * 2) * s),
  59012. roundToInt ((getHeight() - edge * 2) * (1.0f - v)),
  59013. edge * 2, edge * 2);
  59014. }
  59015. ColourSpaceView (const ColourSpaceView&);
  59016. ColourSpaceView& operator= (const ColourSpaceView&);
  59017. };
  59018. class HueSelectorMarker : public Component
  59019. {
  59020. public:
  59021. HueSelectorMarker()
  59022. {
  59023. setInterceptsMouseClicks (false, false);
  59024. }
  59025. ~HueSelectorMarker()
  59026. {
  59027. }
  59028. void paint (Graphics& g)
  59029. {
  59030. Path p;
  59031. p.addTriangle (1.0f, 1.0f,
  59032. getWidth() * 0.3f, getHeight() * 0.5f,
  59033. 1.0f, getHeight() - 1.0f);
  59034. p.addTriangle (getWidth() - 1.0f, 1.0f,
  59035. getWidth() * 0.7f, getHeight() * 0.5f,
  59036. getWidth() - 1.0f, getHeight() - 1.0f);
  59037. g.setColour (Colours::white.withAlpha (0.75f));
  59038. g.fillPath (p);
  59039. g.setColour (Colours::black.withAlpha (0.75f));
  59040. g.strokePath (p, PathStrokeType (1.2f));
  59041. }
  59042. private:
  59043. HueSelectorMarker (const HueSelectorMarker&);
  59044. HueSelectorMarker& operator= (const HueSelectorMarker&);
  59045. };
  59046. class ColourSelector::HueSelectorComp : public Component
  59047. {
  59048. public:
  59049. HueSelectorComp (ColourSelector* owner_,
  59050. float& h_, float& s_, float& v_,
  59051. const int edgeSize)
  59052. : owner (owner_),
  59053. h (h_), s (s_), v (v_),
  59054. lastHue (0.0f),
  59055. edge (edgeSize)
  59056. {
  59057. addAndMakeVisible (marker = new HueSelectorMarker());
  59058. }
  59059. ~HueSelectorComp()
  59060. {
  59061. deleteAllChildren();
  59062. }
  59063. void paint (Graphics& g)
  59064. {
  59065. const float yScale = 1.0f / (getHeight() - edge * 2);
  59066. const Rectangle<int> clip (g.getClipBounds());
  59067. for (int y = jmin (clip.getBottom(), getHeight() - edge); --y >= jmax (edge, clip.getY());)
  59068. {
  59069. g.setColour (Colour ((y - edge) * yScale, 1.0f, 1.0f, 1.0f));
  59070. g.fillRect (edge, y, getWidth() - edge * 2, 1);
  59071. }
  59072. }
  59073. void resized()
  59074. {
  59075. marker->setBounds (0, roundToInt ((getHeight() - edge * 2) * h),
  59076. getWidth(), edge * 2);
  59077. }
  59078. void mouseDown (const MouseEvent& e)
  59079. {
  59080. mouseDrag (e);
  59081. }
  59082. void mouseDrag (const MouseEvent& e)
  59083. {
  59084. const float hue = (e.y - edge) / (float) (getHeight() - edge * 2);
  59085. owner->setHue (hue);
  59086. }
  59087. void updateIfNeeded()
  59088. {
  59089. resized();
  59090. }
  59091. private:
  59092. ColourSelector* const owner;
  59093. float& h;
  59094. float& s;
  59095. float& v;
  59096. float lastHue;
  59097. HueSelectorMarker* marker;
  59098. const int edge;
  59099. HueSelectorComp (const HueSelectorComp&);
  59100. HueSelectorComp& operator= (const HueSelectorComp&);
  59101. };
  59102. class ColourSelector::SwatchComponent : public Component
  59103. {
  59104. public:
  59105. SwatchComponent (ColourSelector* owner_, int index_)
  59106. : owner (owner_),
  59107. index (index_)
  59108. {
  59109. }
  59110. ~SwatchComponent()
  59111. {
  59112. }
  59113. void paint (Graphics& g)
  59114. {
  59115. const Colour colour (owner->getSwatchColour (index));
  59116. g.fillCheckerBoard (0, 0, getWidth(), getHeight(),
  59117. 6, 6,
  59118. Colour (0xffdddddd).overlaidWith (colour),
  59119. Colour (0xffffffff).overlaidWith (colour));
  59120. }
  59121. void mouseDown (const MouseEvent&)
  59122. {
  59123. PopupMenu m;
  59124. m.addItem (1, TRANS("Use this swatch as the current colour"));
  59125. m.addSeparator();
  59126. m.addItem (2, TRANS("Set this swatch to the current colour"));
  59127. const int r = m.showAt (this);
  59128. if (r == 1)
  59129. {
  59130. owner->setCurrentColour (owner->getSwatchColour (index));
  59131. }
  59132. else if (r == 2)
  59133. {
  59134. if (owner->getSwatchColour (index) != owner->getCurrentColour())
  59135. {
  59136. owner->setSwatchColour (index, owner->getCurrentColour());
  59137. repaint();
  59138. }
  59139. }
  59140. }
  59141. private:
  59142. ColourSelector* const owner;
  59143. const int index;
  59144. SwatchComponent (const SwatchComponent&);
  59145. SwatchComponent& operator= (const SwatchComponent&);
  59146. };
  59147. ColourSelector::ColourSelector (const int flags_,
  59148. const int edgeGap_,
  59149. const int gapAroundColourSpaceComponent)
  59150. : colour (Colours::white),
  59151. flags (flags_),
  59152. topSpace (0),
  59153. edgeGap (edgeGap_)
  59154. {
  59155. // not much point having a selector with no components in it!
  59156. jassert ((flags_ & (showColourAtTop | showSliders | showColourspace)) != 0);
  59157. updateHSV();
  59158. if ((flags & showSliders) != 0)
  59159. {
  59160. addAndMakeVisible (sliders[0] = new ColourComponentSlider (TRANS ("red")));
  59161. addAndMakeVisible (sliders[1] = new ColourComponentSlider (TRANS ("green")));
  59162. addAndMakeVisible (sliders[2] = new ColourComponentSlider (TRANS ("blue")));
  59163. addChildComponent (sliders[3] = new ColourComponentSlider (TRANS ("alpha")));
  59164. sliders[3]->setVisible ((flags & showAlphaChannel) != 0);
  59165. for (int i = 4; --i >= 0;)
  59166. sliders[i]->addListener (this);
  59167. }
  59168. else
  59169. {
  59170. zeromem (sliders, sizeof (sliders));
  59171. }
  59172. if ((flags & showColourspace) != 0)
  59173. {
  59174. addAndMakeVisible (colourSpace = new ColourSpaceView (this, h, s, v, gapAroundColourSpaceComponent));
  59175. addAndMakeVisible (hueSelector = new HueSelectorComp (this, h, s, v, gapAroundColourSpaceComponent));
  59176. }
  59177. else
  59178. {
  59179. colourSpace = 0;
  59180. hueSelector = 0;
  59181. }
  59182. update();
  59183. }
  59184. ColourSelector::~ColourSelector()
  59185. {
  59186. dispatchPendingMessages();
  59187. swatchComponents.clear();
  59188. deleteAllChildren();
  59189. }
  59190. const Colour ColourSelector::getCurrentColour() const
  59191. {
  59192. return ((flags & showAlphaChannel) != 0) ? colour
  59193. : colour.withAlpha ((uint8) 0xff);
  59194. }
  59195. void ColourSelector::setCurrentColour (const Colour& c)
  59196. {
  59197. if (c != colour)
  59198. {
  59199. colour = ((flags & showAlphaChannel) != 0) ? c : c.withAlpha ((uint8) 0xff);
  59200. updateHSV();
  59201. update();
  59202. }
  59203. }
  59204. void ColourSelector::setHue (float newH)
  59205. {
  59206. newH = jlimit (0.0f, 1.0f, newH);
  59207. if (h != newH)
  59208. {
  59209. h = newH;
  59210. colour = Colour (h, s, v, colour.getFloatAlpha());
  59211. update();
  59212. }
  59213. }
  59214. void ColourSelector::setSV (float newS, float newV)
  59215. {
  59216. newS = jlimit (0.0f, 1.0f, newS);
  59217. newV = jlimit (0.0f, 1.0f, newV);
  59218. if (s != newS || v != newV)
  59219. {
  59220. s = newS;
  59221. v = newV;
  59222. colour = Colour (h, s, v, colour.getFloatAlpha());
  59223. update();
  59224. }
  59225. }
  59226. void ColourSelector::updateHSV()
  59227. {
  59228. colour.getHSB (h, s, v);
  59229. }
  59230. void ColourSelector::update()
  59231. {
  59232. if (sliders[0] != 0)
  59233. {
  59234. sliders[0]->setValue ((int) colour.getRed());
  59235. sliders[1]->setValue ((int) colour.getGreen());
  59236. sliders[2]->setValue ((int) colour.getBlue());
  59237. sliders[3]->setValue ((int) colour.getAlpha());
  59238. }
  59239. if (colourSpace != 0)
  59240. {
  59241. colourSpace->updateIfNeeded();
  59242. hueSelector->updateIfNeeded();
  59243. }
  59244. if ((flags & showColourAtTop) != 0)
  59245. repaint (0, edgeGap, getWidth(), topSpace - edgeGap);
  59246. sendChangeMessage (this);
  59247. }
  59248. void ColourSelector::paint (Graphics& g)
  59249. {
  59250. g.fillAll (findColour (backgroundColourId));
  59251. if ((flags & showColourAtTop) != 0)
  59252. {
  59253. const Colour currentColour (getCurrentColour());
  59254. g.fillCheckerBoard (edgeGap, edgeGap, getWidth() - edgeGap - edgeGap, topSpace - edgeGap - edgeGap,
  59255. 10, 10,
  59256. Colour (0xffdddddd).overlaidWith (currentColour),
  59257. Colour (0xffffffff).overlaidWith (currentColour));
  59258. g.setColour (Colours::white.overlaidWith (currentColour).contrasting());
  59259. g.setFont (14.0f, true);
  59260. g.drawText (currentColour.toDisplayString ((flags & showAlphaChannel) != 0),
  59261. 0, edgeGap, getWidth(), topSpace - edgeGap * 2,
  59262. Justification::centred, false);
  59263. }
  59264. if ((flags & showSliders) != 0)
  59265. {
  59266. g.setColour (findColour (labelTextColourId));
  59267. g.setFont (11.0f);
  59268. for (int i = 4; --i >= 0;)
  59269. {
  59270. if (sliders[i]->isVisible())
  59271. g.drawText (sliders[i]->getName() + ":",
  59272. 0, sliders[i]->getY(),
  59273. sliders[i]->getX() - 8, sliders[i]->getHeight(),
  59274. Justification::centredRight, false);
  59275. }
  59276. }
  59277. }
  59278. void ColourSelector::resized()
  59279. {
  59280. const int numSliders = ((flags & showAlphaChannel) != 0) ? 4 : 3;
  59281. const int numSwatches = getNumSwatches();
  59282. const int swatchSpace = numSwatches > 0 ? edgeGap + swatchHeight * ((numSwatches + 7) / swatchesPerRow) : 0;
  59283. const int sliderSpace = ((flags & showSliders) != 0) ? jmin (22 * numSliders + edgeGap, proportionOfHeight (0.3f)) : 0;
  59284. topSpace = ((flags & showColourAtTop) != 0) ? jmin (30 + edgeGap * 2, proportionOfHeight (0.2f)) : edgeGap;
  59285. int y = topSpace;
  59286. if ((flags & showColourspace) != 0)
  59287. {
  59288. const int hueWidth = jmin (50, proportionOfWidth (0.15f));
  59289. colourSpace->setBounds (edgeGap, y,
  59290. getWidth() - hueWidth - edgeGap - 4,
  59291. getHeight() - topSpace - sliderSpace - swatchSpace - edgeGap);
  59292. hueSelector->setBounds (colourSpace->getRight() + 4, y,
  59293. getWidth() - edgeGap - (colourSpace->getRight() + 4),
  59294. colourSpace->getHeight());
  59295. y = getHeight() - sliderSpace - swatchSpace - edgeGap;
  59296. }
  59297. if ((flags & showSliders) != 0)
  59298. {
  59299. const int sliderHeight = jmax (4, sliderSpace / numSliders);
  59300. for (int i = 0; i < numSliders; ++i)
  59301. {
  59302. sliders[i]->setBounds (proportionOfWidth (0.2f), y,
  59303. proportionOfWidth (0.72f), sliderHeight - 2);
  59304. y += sliderHeight;
  59305. }
  59306. }
  59307. if (numSwatches > 0)
  59308. {
  59309. const int startX = 8;
  59310. const int xGap = 4;
  59311. const int yGap = 4;
  59312. const int swatchWidth = (getWidth() - startX * 2) / swatchesPerRow;
  59313. y += edgeGap;
  59314. if (swatchComponents.size() != numSwatches)
  59315. {
  59316. swatchComponents.clear();
  59317. for (int i = 0; i < numSwatches; ++i)
  59318. {
  59319. SwatchComponent* const sc = new SwatchComponent (this, i);
  59320. swatchComponents.add (sc);
  59321. addAndMakeVisible (sc);
  59322. }
  59323. }
  59324. int x = startX;
  59325. for (int i = 0; i < swatchComponents.size(); ++i)
  59326. {
  59327. SwatchComponent* const sc = swatchComponents.getUnchecked(i);
  59328. sc->setBounds (x + xGap / 2,
  59329. y + yGap / 2,
  59330. swatchWidth - xGap,
  59331. swatchHeight - yGap);
  59332. if (((i + 1) % swatchesPerRow) == 0)
  59333. {
  59334. x = startX;
  59335. y += swatchHeight;
  59336. }
  59337. else
  59338. {
  59339. x += swatchWidth;
  59340. }
  59341. }
  59342. }
  59343. }
  59344. void ColourSelector::sliderValueChanged (Slider*)
  59345. {
  59346. if (sliders[0] != 0)
  59347. setCurrentColour (Colour ((uint8) sliders[0]->getValue(),
  59348. (uint8) sliders[1]->getValue(),
  59349. (uint8) sliders[2]->getValue(),
  59350. (uint8) sliders[3]->getValue()));
  59351. }
  59352. int ColourSelector::getNumSwatches() const
  59353. {
  59354. return 0;
  59355. }
  59356. const Colour ColourSelector::getSwatchColour (const int) const
  59357. {
  59358. jassertfalse // if you've overridden getNumSwatches(), you also need to implement this method
  59359. return Colours::black;
  59360. }
  59361. void ColourSelector::setSwatchColour (const int, const Colour&) const
  59362. {
  59363. jassertfalse // if you've overridden getNumSwatches(), you also need to implement this method
  59364. }
  59365. END_JUCE_NAMESPACE
  59366. /*** End of inlined file: juce_ColourSelector.cpp ***/
  59367. /*** Start of inlined file: juce_DropShadower.cpp ***/
  59368. BEGIN_JUCE_NAMESPACE
  59369. class ShadowWindow : public Component
  59370. {
  59371. Component* owner;
  59372. Image** shadowImageSections;
  59373. const int type; // 0 = left, 1 = right, 2 = top, 3 = bottom. left + right are full-height
  59374. public:
  59375. ShadowWindow (Component* const owner_,
  59376. const int type_,
  59377. Image** const shadowImageSections_)
  59378. : owner (owner_),
  59379. shadowImageSections (shadowImageSections_),
  59380. type (type_)
  59381. {
  59382. setInterceptsMouseClicks (false, false);
  59383. if (owner_->isOnDesktop())
  59384. {
  59385. setSize (1, 1); // to keep the OS happy by not having zero-size windows
  59386. addToDesktop (ComponentPeer::windowIgnoresMouseClicks
  59387. | ComponentPeer::windowIsTemporary
  59388. | ComponentPeer::windowIgnoresKeyPresses);
  59389. }
  59390. else if (owner_->getParentComponent() != 0)
  59391. {
  59392. owner_->getParentComponent()->addChildComponent (this);
  59393. }
  59394. }
  59395. ~ShadowWindow()
  59396. {
  59397. }
  59398. void paint (Graphics& g)
  59399. {
  59400. Image* const topLeft = shadowImageSections [type * 3];
  59401. Image* const bottomRight = shadowImageSections [type * 3 + 1];
  59402. Image* const filler = shadowImageSections [type * 3 + 2];
  59403. g.setOpacity (1.0f);
  59404. if (type < 2)
  59405. {
  59406. int imH = jmin (topLeft->getHeight(), getHeight() / 2);
  59407. g.drawImage (topLeft,
  59408. 0, 0, topLeft->getWidth(), imH,
  59409. 0, 0, topLeft->getWidth(), imH);
  59410. imH = jmin (bottomRight->getHeight(), getHeight() - getHeight() / 2);
  59411. g.drawImage (bottomRight,
  59412. 0, getHeight() - imH, bottomRight->getWidth(), imH,
  59413. 0, bottomRight->getHeight() - imH, bottomRight->getWidth(), imH);
  59414. g.setTiledImageFill (*filler, 0, 0, 1.0f);
  59415. g.fillRect (0, topLeft->getHeight(), getWidth(), getHeight() - (topLeft->getHeight() + bottomRight->getHeight()));
  59416. }
  59417. else
  59418. {
  59419. int imW = jmin (topLeft->getWidth(), getWidth() / 2);
  59420. g.drawImage (topLeft,
  59421. 0, 0, imW, topLeft->getHeight(),
  59422. 0, 0, imW, topLeft->getHeight());
  59423. imW = jmin (bottomRight->getWidth(), getWidth() - getWidth() / 2);
  59424. g.drawImage (bottomRight,
  59425. getWidth() - imW, 0, imW, bottomRight->getHeight(),
  59426. bottomRight->getWidth() - imW, 0, imW, bottomRight->getHeight());
  59427. g.setTiledImageFill (*filler, 0, 0, 1.0f);
  59428. g.fillRect (topLeft->getWidth(), 0, getWidth() - (topLeft->getWidth() + bottomRight->getWidth()), getHeight());
  59429. }
  59430. }
  59431. void resized()
  59432. {
  59433. repaint(); // (needed for correct repainting)
  59434. }
  59435. private:
  59436. ShadowWindow (const ShadowWindow&);
  59437. ShadowWindow& operator= (const ShadowWindow&);
  59438. };
  59439. DropShadower::DropShadower (const float alpha_,
  59440. const int xOffset_,
  59441. const int yOffset_,
  59442. const float blurRadius_)
  59443. : owner (0),
  59444. numShadows (0),
  59445. shadowEdge (jmax (xOffset_, yOffset_) + (int) blurRadius_),
  59446. xOffset (xOffset_),
  59447. yOffset (yOffset_),
  59448. alpha (alpha_),
  59449. blurRadius (blurRadius_),
  59450. inDestructor (false),
  59451. reentrant (false)
  59452. {
  59453. }
  59454. DropShadower::~DropShadower()
  59455. {
  59456. if (owner != 0)
  59457. owner->removeComponentListener (this);
  59458. inDestructor = true;
  59459. deleteShadowWindows();
  59460. }
  59461. void DropShadower::deleteShadowWindows()
  59462. {
  59463. if (numShadows > 0)
  59464. {
  59465. int i;
  59466. for (i = numShadows; --i >= 0;)
  59467. delete shadowWindows[i];
  59468. for (i = 12; --i >= 0;)
  59469. delete shadowImageSections[i];
  59470. numShadows = 0;
  59471. }
  59472. }
  59473. void DropShadower::setOwner (Component* componentToFollow)
  59474. {
  59475. if (componentToFollow != owner)
  59476. {
  59477. if (owner != 0)
  59478. owner->removeComponentListener (this);
  59479. // (the component can't be null)
  59480. jassert (componentToFollow != 0);
  59481. owner = componentToFollow;
  59482. jassert (owner != 0);
  59483. jassert (owner->isOpaque()); // doesn't work properly for semi-transparent comps!
  59484. owner->addComponentListener (this);
  59485. updateShadows();
  59486. }
  59487. }
  59488. void DropShadower::componentMovedOrResized (Component&, bool /*wasMoved*/, bool /*wasResized*/)
  59489. {
  59490. updateShadows();
  59491. }
  59492. void DropShadower::componentBroughtToFront (Component&)
  59493. {
  59494. bringShadowWindowsToFront();
  59495. }
  59496. void DropShadower::componentChildrenChanged (Component&)
  59497. {
  59498. }
  59499. void DropShadower::componentParentHierarchyChanged (Component&)
  59500. {
  59501. deleteShadowWindows();
  59502. updateShadows();
  59503. }
  59504. void DropShadower::componentVisibilityChanged (Component&)
  59505. {
  59506. updateShadows();
  59507. }
  59508. void DropShadower::updateShadows()
  59509. {
  59510. if (reentrant || inDestructor || (owner == 0))
  59511. return;
  59512. reentrant = true;
  59513. ComponentPeer* const nw = owner->getPeer();
  59514. const bool isOwnerVisible = owner->isVisible()
  59515. && (nw == 0 || ! nw->isMinimised());
  59516. const bool createShadowWindows = numShadows == 0
  59517. && owner->getWidth() > 0
  59518. && owner->getHeight() > 0
  59519. && isOwnerVisible
  59520. && (Desktop::canUseSemiTransparentWindows()
  59521. || owner->getParentComponent() != 0);
  59522. if (createShadowWindows)
  59523. {
  59524. // keep a cached version of the image to save doing the gaussian too often
  59525. String imageId;
  59526. imageId << shadowEdge << ',' << xOffset << ',' << yOffset << ',' << alpha;
  59527. const int hash = imageId.hashCode();
  59528. Image* bigIm = ImageCache::getFromHashCode (hash);
  59529. if (bigIm == 0)
  59530. {
  59531. bigIm = Image::createNativeImage (Image::ARGB, shadowEdge * 5, shadowEdge * 5, true);
  59532. Graphics bigG (*bigIm);
  59533. bigG.setColour (Colours::black.withAlpha (alpha));
  59534. bigG.fillRect (shadowEdge + xOffset,
  59535. shadowEdge + yOffset,
  59536. bigIm->getWidth() - (shadowEdge * 2),
  59537. bigIm->getHeight() - (shadowEdge * 2));
  59538. ImageConvolutionKernel blurKernel (roundToInt (blurRadius * 2.0f));
  59539. blurKernel.createGaussianBlur (blurRadius);
  59540. blurKernel.applyToImage (*bigIm, 0,
  59541. Rectangle<int> (xOffset, yOffset,
  59542. bigIm->getWidth(), bigIm->getHeight()));
  59543. ImageCache::addImageToCache (bigIm, hash);
  59544. }
  59545. const int iw = bigIm->getWidth();
  59546. const int ih = bigIm->getHeight();
  59547. const int shadowEdge2 = shadowEdge * 2;
  59548. setShadowImage (bigIm, 0, shadowEdge, shadowEdge2, 0, 0);
  59549. setShadowImage (bigIm, 1, shadowEdge, shadowEdge2, 0, ih - shadowEdge2);
  59550. setShadowImage (bigIm, 2, shadowEdge, shadowEdge, 0, shadowEdge2);
  59551. setShadowImage (bigIm, 3, shadowEdge, shadowEdge2, iw - shadowEdge, 0);
  59552. setShadowImage (bigIm, 4, shadowEdge, shadowEdge2, iw - shadowEdge, ih - shadowEdge2);
  59553. setShadowImage (bigIm, 5, shadowEdge, shadowEdge, iw - shadowEdge, shadowEdge2);
  59554. setShadowImage (bigIm, 6, shadowEdge, shadowEdge, shadowEdge, 0);
  59555. setShadowImage (bigIm, 7, shadowEdge, shadowEdge, iw - shadowEdge2, 0);
  59556. setShadowImage (bigIm, 8, shadowEdge, shadowEdge, shadowEdge2, 0);
  59557. setShadowImage (bigIm, 9, shadowEdge, shadowEdge, shadowEdge, ih - shadowEdge);
  59558. setShadowImage (bigIm, 10, shadowEdge, shadowEdge, iw - shadowEdge2, ih - shadowEdge);
  59559. setShadowImage (bigIm, 11, shadowEdge, shadowEdge, shadowEdge2, ih - shadowEdge);
  59560. ImageCache::release (bigIm);
  59561. for (int i = 0; i < 4; ++i)
  59562. {
  59563. shadowWindows[numShadows] = new ShadowWindow (owner, i, shadowImageSections);
  59564. ++numShadows;
  59565. }
  59566. }
  59567. if (numShadows > 0)
  59568. {
  59569. for (int i = numShadows; --i >= 0;)
  59570. {
  59571. shadowWindows[i]->setAlwaysOnTop (owner->isAlwaysOnTop());
  59572. shadowWindows[i]->setVisible (isOwnerVisible);
  59573. }
  59574. const int x = owner->getX();
  59575. const int y = owner->getY() - shadowEdge;
  59576. const int w = owner->getWidth();
  59577. const int h = owner->getHeight() + shadowEdge + shadowEdge;
  59578. shadowWindows[0]->setBounds (x - shadowEdge,
  59579. y,
  59580. shadowEdge,
  59581. h);
  59582. shadowWindows[1]->setBounds (x + w,
  59583. y,
  59584. shadowEdge,
  59585. h);
  59586. shadowWindows[2]->setBounds (x,
  59587. y,
  59588. w,
  59589. shadowEdge);
  59590. shadowWindows[3]->setBounds (x,
  59591. owner->getBottom(),
  59592. w,
  59593. shadowEdge);
  59594. }
  59595. reentrant = false;
  59596. if (createShadowWindows)
  59597. bringShadowWindowsToFront();
  59598. }
  59599. void DropShadower::setShadowImage (Image* const src, const int num, const int w, const int h,
  59600. const int sx, const int sy)
  59601. {
  59602. shadowImageSections[num] = new Image (Image::ARGB, w, h, true);
  59603. Graphics g (*shadowImageSections[num]);
  59604. g.drawImage (src, 0, 0, w, h, sx, sy, w, h);
  59605. }
  59606. void DropShadower::bringShadowWindowsToFront()
  59607. {
  59608. if (! (inDestructor || reentrant))
  59609. {
  59610. updateShadows();
  59611. reentrant = true;
  59612. for (int i = numShadows; --i >= 0;)
  59613. shadowWindows[i]->toBehind (owner);
  59614. reentrant = false;
  59615. }
  59616. }
  59617. END_JUCE_NAMESPACE
  59618. /*** End of inlined file: juce_DropShadower.cpp ***/
  59619. /*** Start of inlined file: juce_MagnifierComponent.cpp ***/
  59620. BEGIN_JUCE_NAMESPACE
  59621. class MagnifyingPeer : public ComponentPeer
  59622. {
  59623. public:
  59624. MagnifyingPeer (Component* const component_,
  59625. MagnifierComponent* const magnifierComp_)
  59626. : ComponentPeer (component_, 0),
  59627. magnifierComp (magnifierComp_)
  59628. {
  59629. }
  59630. ~MagnifyingPeer()
  59631. {
  59632. }
  59633. void* getNativeHandle() const { return 0; }
  59634. void setVisible (bool) {}
  59635. void setTitle (const String&) {}
  59636. void setPosition (int, int) {}
  59637. void setSize (int, int) {}
  59638. void setBounds (int, int, int, int, bool) {}
  59639. void setMinimised (bool) {}
  59640. bool isMinimised() const { return false; }
  59641. void setFullScreen (bool) {}
  59642. bool isFullScreen() const { return false; }
  59643. const BorderSize getFrameSize() const { return BorderSize (0); }
  59644. bool setAlwaysOnTop (bool) { return true; }
  59645. void toFront (bool) {}
  59646. void toBehind (ComponentPeer*) {}
  59647. void setIcon (const Image&) {}
  59648. bool isFocused() const
  59649. {
  59650. return magnifierComp->hasKeyboardFocus (true);
  59651. }
  59652. void grabFocus()
  59653. {
  59654. ComponentPeer* peer = magnifierComp->getPeer();
  59655. if (peer != 0)
  59656. peer->grabFocus();
  59657. }
  59658. void textInputRequired (const Point<int>& position)
  59659. {
  59660. ComponentPeer* peer = magnifierComp->getPeer();
  59661. if (peer != 0)
  59662. peer->textInputRequired (position);
  59663. }
  59664. const Rectangle<int> getBounds() const
  59665. {
  59666. return Rectangle<int> (magnifierComp->getScreenX(), magnifierComp->getScreenY(),
  59667. component->getWidth(), component->getHeight());
  59668. }
  59669. const Point<int> getScreenPosition() const
  59670. {
  59671. return magnifierComp->getScreenPosition();
  59672. }
  59673. const Point<int> relativePositionToGlobal (const Point<int>& relativePosition)
  59674. {
  59675. const double zoom = magnifierComp->getScaleFactor();
  59676. return magnifierComp->relativePositionToGlobal (Point<int> (roundToInt (relativePosition.getX() * zoom),
  59677. roundToInt (relativePosition.getY() * zoom)));
  59678. }
  59679. const Point<int> globalPositionToRelative (const Point<int>& screenPosition)
  59680. {
  59681. const Point<int> p (magnifierComp->globalPositionToRelative (screenPosition));
  59682. const double zoom = magnifierComp->getScaleFactor();
  59683. return Point<int> (roundToInt (p.getX() / zoom),
  59684. roundToInt (p.getY() / zoom));
  59685. }
  59686. bool contains (const Point<int>& position, bool) const
  59687. {
  59688. return ((unsigned int) position.getX()) < (unsigned int) magnifierComp->getWidth()
  59689. && ((unsigned int) position.getY()) < (unsigned int) magnifierComp->getHeight();
  59690. }
  59691. void repaint (int x, int y, int w, int h)
  59692. {
  59693. const double zoom = magnifierComp->getScaleFactor();
  59694. magnifierComp->repaint ((int) (x * zoom),
  59695. (int) (y * zoom),
  59696. roundToInt (w * zoom) + 1,
  59697. roundToInt (h * zoom) + 1);
  59698. }
  59699. void performAnyPendingRepaintsNow()
  59700. {
  59701. }
  59702. juce_UseDebuggingNewOperator
  59703. private:
  59704. MagnifierComponent* const magnifierComp;
  59705. MagnifyingPeer (const MagnifyingPeer&);
  59706. MagnifyingPeer& operator= (const MagnifyingPeer&);
  59707. };
  59708. class PeerHolderComp : public Component
  59709. {
  59710. public:
  59711. PeerHolderComp (MagnifierComponent* const magnifierComp_)
  59712. : magnifierComp (magnifierComp_)
  59713. {
  59714. setVisible (true);
  59715. }
  59716. ~PeerHolderComp()
  59717. {
  59718. }
  59719. ComponentPeer* createNewPeer (int, void*)
  59720. {
  59721. return new MagnifyingPeer (this, magnifierComp);
  59722. }
  59723. void childBoundsChanged (Component* c)
  59724. {
  59725. if (c != 0)
  59726. {
  59727. setSize (c->getWidth(), c->getHeight());
  59728. magnifierComp->childBoundsChanged (this);
  59729. }
  59730. }
  59731. void mouseWheelMove (const MouseEvent& e, float ix, float iy)
  59732. {
  59733. // unhandled mouse wheel moves can be referred upwards to the parent comp..
  59734. Component* const p = magnifierComp->getParentComponent();
  59735. if (p != 0)
  59736. p->mouseWheelMove (e.getEventRelativeTo (p), ix, iy);
  59737. }
  59738. private:
  59739. MagnifierComponent* const magnifierComp;
  59740. PeerHolderComp (const PeerHolderComp&);
  59741. PeerHolderComp& operator= (const PeerHolderComp&);
  59742. };
  59743. MagnifierComponent::MagnifierComponent (Component* const content_,
  59744. const bool deleteContentCompWhenNoLongerNeeded)
  59745. : content (content_),
  59746. scaleFactor (0.0),
  59747. peer (0),
  59748. deleteContent (deleteContentCompWhenNoLongerNeeded),
  59749. quality (Graphics::lowResamplingQuality),
  59750. mouseSource (0, true)
  59751. {
  59752. holderComp = new PeerHolderComp (this);
  59753. setScaleFactor (1.0);
  59754. }
  59755. MagnifierComponent::~MagnifierComponent()
  59756. {
  59757. delete holderComp;
  59758. if (deleteContent)
  59759. delete content;
  59760. }
  59761. void MagnifierComponent::setScaleFactor (double newScaleFactor)
  59762. {
  59763. jassert (newScaleFactor > 0.0); // hmm - unlikely to work well with a negative scale factor
  59764. newScaleFactor = jlimit (1.0 / 8.0, 1000.0, newScaleFactor);
  59765. if (scaleFactor != newScaleFactor)
  59766. {
  59767. scaleFactor = newScaleFactor;
  59768. if (scaleFactor == 1.0)
  59769. {
  59770. holderComp->removeFromDesktop();
  59771. peer = 0;
  59772. addChildComponent (content);
  59773. childBoundsChanged (content);
  59774. }
  59775. else
  59776. {
  59777. holderComp->addAndMakeVisible (content);
  59778. holderComp->childBoundsChanged (content);
  59779. childBoundsChanged (holderComp);
  59780. holderComp->addToDesktop (0);
  59781. peer = holderComp->getPeer();
  59782. }
  59783. repaint();
  59784. }
  59785. }
  59786. void MagnifierComponent::setResamplingQuality (Graphics::ResamplingQuality newQuality)
  59787. {
  59788. quality = newQuality;
  59789. }
  59790. void MagnifierComponent::paint (Graphics& g)
  59791. {
  59792. const int w = holderComp->getWidth();
  59793. const int h = holderComp->getHeight();
  59794. if (w == 0 || h == 0)
  59795. return;
  59796. const Rectangle<int> r (g.getClipBounds());
  59797. const int srcX = (int) (r.getX() / scaleFactor);
  59798. const int srcY = (int) (r.getY() / scaleFactor);
  59799. int srcW = roundToInt (r.getRight() / scaleFactor) - srcX;
  59800. int srcH = roundToInt (r.getBottom() / scaleFactor) - srcY;
  59801. if (scaleFactor >= 1.0)
  59802. {
  59803. ++srcW;
  59804. ++srcH;
  59805. }
  59806. Image temp (Image::ARGB, jmax (w, srcX + srcW), jmax (h, srcY + srcH), false);
  59807. temp.clear (Rectangle<int> (srcX, srcY, srcW, srcH));
  59808. {
  59809. Graphics g2 (temp);
  59810. g2.reduceClipRegion (srcX, srcY, srcW, srcH);
  59811. holderComp->paintEntireComponent (g2);
  59812. }
  59813. g.setImageResamplingQuality (quality);
  59814. g.drawImageTransformed (&temp, temp.getBounds(),
  59815. AffineTransform::scale ((float) scaleFactor, (float) scaleFactor),
  59816. false);
  59817. }
  59818. void MagnifierComponent::childBoundsChanged (Component* c)
  59819. {
  59820. if (c != 0)
  59821. setSize (roundToInt (c->getWidth() * scaleFactor),
  59822. roundToInt (c->getHeight() * scaleFactor));
  59823. }
  59824. void MagnifierComponent::passOnMouseEventToPeer (const MouseEvent& e)
  59825. {
  59826. if (peer != 0)
  59827. mouseSource.handleEvent (peer, Point<int> (scaleInt (e.x), scaleInt (e.y)),
  59828. e.eventTime.toMilliseconds(), ModifierKeys::getCurrentModifiers());
  59829. }
  59830. void MagnifierComponent::mouseDown (const MouseEvent& e)
  59831. {
  59832. passOnMouseEventToPeer (e);
  59833. }
  59834. void MagnifierComponent::mouseUp (const MouseEvent& e)
  59835. {
  59836. passOnMouseEventToPeer (e);
  59837. }
  59838. void MagnifierComponent::mouseDrag (const MouseEvent& e)
  59839. {
  59840. passOnMouseEventToPeer (e);
  59841. }
  59842. void MagnifierComponent::mouseMove (const MouseEvent& e)
  59843. {
  59844. passOnMouseEventToPeer (e);
  59845. }
  59846. void MagnifierComponent::mouseEnter (const MouseEvent& e)
  59847. {
  59848. passOnMouseEventToPeer (e);
  59849. }
  59850. void MagnifierComponent::mouseExit (const MouseEvent& e)
  59851. {
  59852. passOnMouseEventToPeer (e);
  59853. }
  59854. void MagnifierComponent::mouseWheelMove (const MouseEvent& e, float ix, float iy)
  59855. {
  59856. if (peer != 0)
  59857. peer->handleMouseWheel (e.source.getIndex(),
  59858. Point<int> (scaleInt (e.x), scaleInt (e.y)), e.eventTime.toMilliseconds(),
  59859. ix * 256.0f, iy * 256.0f);
  59860. else
  59861. Component::mouseWheelMove (e, ix, iy);
  59862. }
  59863. int MagnifierComponent::scaleInt (const int n) const
  59864. {
  59865. return roundToInt (n / scaleFactor);
  59866. }
  59867. END_JUCE_NAMESPACE
  59868. /*** End of inlined file: juce_MagnifierComponent.cpp ***/
  59869. /*** Start of inlined file: juce_MidiKeyboardComponent.cpp ***/
  59870. BEGIN_JUCE_NAMESPACE
  59871. class MidiKeyboardUpDownButton : public Button
  59872. {
  59873. public:
  59874. MidiKeyboardUpDownButton (MidiKeyboardComponent* const owner_,
  59875. const int delta_)
  59876. : Button (String::empty),
  59877. owner (owner_),
  59878. delta (delta_)
  59879. {
  59880. setOpaque (true);
  59881. }
  59882. ~MidiKeyboardUpDownButton()
  59883. {
  59884. }
  59885. void clicked()
  59886. {
  59887. int note = owner->getLowestVisibleKey();
  59888. if (delta < 0)
  59889. note = (note - 1) / 12;
  59890. else
  59891. note = note / 12 + 1;
  59892. owner->setLowestVisibleKey (note * 12);
  59893. }
  59894. void paintButton (Graphics& g,
  59895. bool isMouseOverButton,
  59896. bool isButtonDown)
  59897. {
  59898. owner->drawUpDownButton (g, getWidth(), getHeight(),
  59899. isMouseOverButton, isButtonDown,
  59900. delta > 0);
  59901. }
  59902. private:
  59903. MidiKeyboardComponent* const owner;
  59904. const int delta;
  59905. MidiKeyboardUpDownButton (const MidiKeyboardUpDownButton&);
  59906. MidiKeyboardUpDownButton& operator= (const MidiKeyboardUpDownButton&);
  59907. };
  59908. MidiKeyboardComponent::MidiKeyboardComponent (MidiKeyboardState& state_,
  59909. const Orientation orientation_)
  59910. : state (state_),
  59911. xOffset (0),
  59912. blackNoteLength (1),
  59913. keyWidth (16.0f),
  59914. orientation (orientation_),
  59915. midiChannel (1),
  59916. midiInChannelMask (0xffff),
  59917. velocity (1.0f),
  59918. noteUnderMouse (-1),
  59919. mouseDownNote (-1),
  59920. rangeStart (0),
  59921. rangeEnd (127),
  59922. firstKey (12 * 4),
  59923. canScroll (true),
  59924. mouseDragging (false),
  59925. useMousePositionForVelocity (true),
  59926. keyMappingOctave (6),
  59927. octaveNumForMiddleC (3)
  59928. {
  59929. addChildComponent (scrollDown = new MidiKeyboardUpDownButton (this, -1));
  59930. addChildComponent (scrollUp = new MidiKeyboardUpDownButton (this, 1));
  59931. // initialise with a default set of querty key-mappings..
  59932. const char* const keymap = "awsedftgyhujkolp;";
  59933. for (int i = String (keymap).length(); --i >= 0;)
  59934. setKeyPressForNote (KeyPress (keymap[i], 0, 0), i);
  59935. setOpaque (true);
  59936. setWantsKeyboardFocus (true);
  59937. state.addListener (this);
  59938. }
  59939. MidiKeyboardComponent::~MidiKeyboardComponent()
  59940. {
  59941. state.removeListener (this);
  59942. jassert (mouseDownNote < 0 && keysPressed.countNumberOfSetBits() == 0); // leaving stuck notes!
  59943. deleteAllChildren();
  59944. }
  59945. void MidiKeyboardComponent::setKeyWidth (const float widthInPixels)
  59946. {
  59947. keyWidth = widthInPixels;
  59948. resized();
  59949. }
  59950. void MidiKeyboardComponent::setOrientation (const Orientation newOrientation)
  59951. {
  59952. if (orientation != newOrientation)
  59953. {
  59954. orientation = newOrientation;
  59955. resized();
  59956. }
  59957. }
  59958. void MidiKeyboardComponent::setAvailableRange (const int lowestNote,
  59959. const int highestNote)
  59960. {
  59961. jassert (lowestNote >= 0 && lowestNote <= 127);
  59962. jassert (highestNote >= 0 && highestNote <= 127);
  59963. jassert (lowestNote <= highestNote);
  59964. if (rangeStart != lowestNote || rangeEnd != highestNote)
  59965. {
  59966. rangeStart = jlimit (0, 127, lowestNote);
  59967. rangeEnd = jlimit (0, 127, highestNote);
  59968. firstKey = jlimit (rangeStart, rangeEnd, firstKey);
  59969. resized();
  59970. }
  59971. }
  59972. void MidiKeyboardComponent::setLowestVisibleKey (int noteNumber)
  59973. {
  59974. noteNumber = jlimit (rangeStart, rangeEnd, noteNumber);
  59975. if (noteNumber != firstKey)
  59976. {
  59977. firstKey = noteNumber;
  59978. sendChangeMessage (this);
  59979. resized();
  59980. }
  59981. }
  59982. void MidiKeyboardComponent::setScrollButtonsVisible (const bool canScroll_)
  59983. {
  59984. if (canScroll != canScroll_)
  59985. {
  59986. canScroll = canScroll_;
  59987. resized();
  59988. }
  59989. }
  59990. void MidiKeyboardComponent::colourChanged()
  59991. {
  59992. repaint();
  59993. }
  59994. void MidiKeyboardComponent::setMidiChannel (const int midiChannelNumber)
  59995. {
  59996. jassert (midiChannelNumber > 0 && midiChannelNumber <= 16);
  59997. if (midiChannel != midiChannelNumber)
  59998. {
  59999. resetAnyKeysInUse();
  60000. midiChannel = jlimit (1, 16, midiChannelNumber);
  60001. }
  60002. }
  60003. void MidiKeyboardComponent::setMidiChannelsToDisplay (const int midiChannelMask)
  60004. {
  60005. midiInChannelMask = midiChannelMask;
  60006. triggerAsyncUpdate();
  60007. }
  60008. void MidiKeyboardComponent::setVelocity (const float velocity_, const bool useMousePositionForVelocity_)
  60009. {
  60010. velocity = jlimit (0.0f, 1.0f, velocity_);
  60011. useMousePositionForVelocity = useMousePositionForVelocity_;
  60012. }
  60013. void MidiKeyboardComponent::getKeyPosition (int midiNoteNumber, const float keyWidth_, int& x, int& w) const
  60014. {
  60015. jassert (midiNoteNumber >= 0 && midiNoteNumber < 128);
  60016. static const float blackNoteWidth = 0.7f;
  60017. static const float notePos[] = { 0.0f, 1 - blackNoteWidth * 0.6f,
  60018. 1.0f, 2 - blackNoteWidth * 0.4f,
  60019. 2.0f, 3.0f, 4 - blackNoteWidth * 0.7f,
  60020. 4.0f, 5 - blackNoteWidth * 0.5f,
  60021. 5.0f, 6 - blackNoteWidth * 0.3f,
  60022. 6.0f };
  60023. static const float widths[] = { 1.0f, blackNoteWidth,
  60024. 1.0f, blackNoteWidth,
  60025. 1.0f, 1.0f, blackNoteWidth,
  60026. 1.0f, blackNoteWidth,
  60027. 1.0f, blackNoteWidth,
  60028. 1.0f };
  60029. const int octave = midiNoteNumber / 12;
  60030. const int note = midiNoteNumber % 12;
  60031. x = roundToInt (octave * 7.0f * keyWidth_ + notePos [note] * keyWidth_);
  60032. w = roundToInt (widths [note] * keyWidth_);
  60033. }
  60034. void MidiKeyboardComponent::getKeyPos (int midiNoteNumber, int& x, int& w) const
  60035. {
  60036. getKeyPosition (midiNoteNumber, keyWidth, x, w);
  60037. int rx, rw;
  60038. getKeyPosition (rangeStart, keyWidth, rx, rw);
  60039. x -= xOffset + rx;
  60040. }
  60041. int MidiKeyboardComponent::getKeyStartPosition (const int midiNoteNumber) const
  60042. {
  60043. int x, y;
  60044. getKeyPos (midiNoteNumber, x, y);
  60045. return x;
  60046. }
  60047. static const uint8 whiteNotes[] = { 0, 2, 4, 5, 7, 9, 11 };
  60048. static const uint8 blackNotes[] = { 1, 3, 6, 8, 10 };
  60049. int MidiKeyboardComponent::xyToNote (const Point<int>& pos, float& mousePositionVelocity)
  60050. {
  60051. if (! reallyContains (pos.getX(), pos.getY(), false))
  60052. return -1;
  60053. Point<int> p (pos);
  60054. if (orientation != horizontalKeyboard)
  60055. {
  60056. p = Point<int> (p.getY(), p.getX());
  60057. if (orientation == verticalKeyboardFacingLeft)
  60058. p = Point<int> (p.getX(), getWidth() - p.getY());
  60059. else
  60060. p = Point<int> (getHeight() - p.getX(), p.getY());
  60061. }
  60062. return remappedXYToNote (p + Point<int> (xOffset, 0), mousePositionVelocity);
  60063. }
  60064. int MidiKeyboardComponent::remappedXYToNote (const Point<int>& pos, float& mousePositionVelocity) const
  60065. {
  60066. if (pos.getY() < blackNoteLength)
  60067. {
  60068. for (int octaveStart = 12 * (rangeStart / 12); octaveStart <= rangeEnd; octaveStart += 12)
  60069. {
  60070. for (int i = 0; i < 5; ++i)
  60071. {
  60072. const int note = octaveStart + blackNotes [i];
  60073. if (note >= rangeStart && note <= rangeEnd)
  60074. {
  60075. int kx, kw;
  60076. getKeyPos (note, kx, kw);
  60077. kx += xOffset;
  60078. if (pos.getX() >= kx && pos.getX() < kx + kw)
  60079. {
  60080. mousePositionVelocity = pos.getY() / (float) blackNoteLength;
  60081. return note;
  60082. }
  60083. }
  60084. }
  60085. }
  60086. }
  60087. for (int octaveStart = 12 * (rangeStart / 12); octaveStart <= rangeEnd; octaveStart += 12)
  60088. {
  60089. for (int i = 0; i < 7; ++i)
  60090. {
  60091. const int note = octaveStart + whiteNotes [i];
  60092. if (note >= rangeStart && note <= rangeEnd)
  60093. {
  60094. int kx, kw;
  60095. getKeyPos (note, kx, kw);
  60096. kx += xOffset;
  60097. if (pos.getX() >= kx && pos.getX() < kx + kw)
  60098. {
  60099. const int whiteNoteLength = (orientation == horizontalKeyboard) ? getHeight() : getWidth();
  60100. mousePositionVelocity = pos.getY() / (float) whiteNoteLength;
  60101. return note;
  60102. }
  60103. }
  60104. }
  60105. }
  60106. mousePositionVelocity = 0;
  60107. return -1;
  60108. }
  60109. void MidiKeyboardComponent::repaintNote (const int noteNum)
  60110. {
  60111. if (noteNum >= rangeStart && noteNum <= rangeEnd)
  60112. {
  60113. int x, w;
  60114. getKeyPos (noteNum, x, w);
  60115. if (orientation == horizontalKeyboard)
  60116. repaint (x, 0, w, getHeight());
  60117. else if (orientation == verticalKeyboardFacingLeft)
  60118. repaint (0, x, getWidth(), w);
  60119. else if (orientation == verticalKeyboardFacingRight)
  60120. repaint (0, getHeight() - x - w, getWidth(), w);
  60121. }
  60122. }
  60123. void MidiKeyboardComponent::paint (Graphics& g)
  60124. {
  60125. g.fillAll (Colours::white.overlaidWith (findColour (whiteNoteColourId)));
  60126. const Colour lineColour (findColour (keySeparatorLineColourId));
  60127. const Colour textColour (findColour (textLabelColourId));
  60128. int x, w, octave;
  60129. for (octave = 0; octave < 128; octave += 12)
  60130. {
  60131. for (int white = 0; white < 7; ++white)
  60132. {
  60133. const int noteNum = octave + whiteNotes [white];
  60134. if (noteNum >= rangeStart && noteNum <= rangeEnd)
  60135. {
  60136. getKeyPos (noteNum, x, w);
  60137. if (orientation == horizontalKeyboard)
  60138. drawWhiteNote (noteNum, g, x, 0, w, getHeight(),
  60139. state.isNoteOnForChannels (midiInChannelMask, noteNum),
  60140. noteUnderMouse == noteNum,
  60141. lineColour, textColour);
  60142. else if (orientation == verticalKeyboardFacingLeft)
  60143. drawWhiteNote (noteNum, g, 0, x, getWidth(), w,
  60144. state.isNoteOnForChannels (midiInChannelMask, noteNum),
  60145. noteUnderMouse == noteNum,
  60146. lineColour, textColour);
  60147. else if (orientation == verticalKeyboardFacingRight)
  60148. drawWhiteNote (noteNum, g, 0, getHeight() - x - w, getWidth(), w,
  60149. state.isNoteOnForChannels (midiInChannelMask, noteNum),
  60150. noteUnderMouse == noteNum,
  60151. lineColour, textColour);
  60152. }
  60153. }
  60154. }
  60155. float x1 = 0.0f, y1 = 0.0f, x2 = 0.0f, y2 = 0.0f;
  60156. if (orientation == verticalKeyboardFacingLeft)
  60157. {
  60158. x1 = getWidth() - 1.0f;
  60159. x2 = getWidth() - 5.0f;
  60160. }
  60161. else if (orientation == verticalKeyboardFacingRight)
  60162. x2 = 5.0f;
  60163. else
  60164. y2 = 5.0f;
  60165. g.setGradientFill (ColourGradient (Colours::black.withAlpha (0.3f), x1, y1,
  60166. Colours::transparentBlack, x2, y2, false));
  60167. getKeyPos (rangeEnd, x, w);
  60168. x += w;
  60169. if (orientation == verticalKeyboardFacingLeft)
  60170. g.fillRect (getWidth() - 5, 0, 5, x);
  60171. else if (orientation == verticalKeyboardFacingRight)
  60172. g.fillRect (0, 0, 5, x);
  60173. else
  60174. g.fillRect (0, 0, x, 5);
  60175. g.setColour (lineColour);
  60176. if (orientation == verticalKeyboardFacingLeft)
  60177. g.fillRect (0, 0, 1, x);
  60178. else if (orientation == verticalKeyboardFacingRight)
  60179. g.fillRect (getWidth() - 1, 0, 1, x);
  60180. else
  60181. g.fillRect (0, getHeight() - 1, x, 1);
  60182. const Colour blackNoteColour (findColour (blackNoteColourId));
  60183. for (octave = 0; octave < 128; octave += 12)
  60184. {
  60185. for (int black = 0; black < 5; ++black)
  60186. {
  60187. const int noteNum = octave + blackNotes [black];
  60188. if (noteNum >= rangeStart && noteNum <= rangeEnd)
  60189. {
  60190. getKeyPos (noteNum, x, w);
  60191. if (orientation == horizontalKeyboard)
  60192. drawBlackNote (noteNum, g, x, 0, w, blackNoteLength,
  60193. state.isNoteOnForChannels (midiInChannelMask, noteNum),
  60194. noteUnderMouse == noteNum,
  60195. blackNoteColour);
  60196. else if (orientation == verticalKeyboardFacingLeft)
  60197. drawBlackNote (noteNum, g, getWidth() - blackNoteLength, x, blackNoteLength, w,
  60198. state.isNoteOnForChannels (midiInChannelMask, noteNum),
  60199. noteUnderMouse == noteNum,
  60200. blackNoteColour);
  60201. else if (orientation == verticalKeyboardFacingRight)
  60202. drawBlackNote (noteNum, g, 0, getHeight() - x - w, blackNoteLength, w,
  60203. state.isNoteOnForChannels (midiInChannelMask, noteNum),
  60204. noteUnderMouse == noteNum,
  60205. blackNoteColour);
  60206. }
  60207. }
  60208. }
  60209. }
  60210. void MidiKeyboardComponent::drawWhiteNote (int midiNoteNumber,
  60211. Graphics& g, int x, int y, int w, int h,
  60212. bool isDown, bool isOver,
  60213. const Colour& lineColour,
  60214. const Colour& textColour)
  60215. {
  60216. Colour c (Colours::transparentWhite);
  60217. if (isDown)
  60218. c = findColour (keyDownOverlayColourId);
  60219. if (isOver)
  60220. c = c.overlaidWith (findColour (mouseOverKeyOverlayColourId));
  60221. g.setColour (c);
  60222. g.fillRect (x, y, w, h);
  60223. const String text (getWhiteNoteText (midiNoteNumber));
  60224. if (! text.isEmpty())
  60225. {
  60226. g.setColour (textColour);
  60227. Font f (jmin (12.0f, keyWidth * 0.9f));
  60228. f.setHorizontalScale (0.8f);
  60229. g.setFont (f);
  60230. Justification justification (Justification::centredBottom);
  60231. if (orientation == verticalKeyboardFacingLeft)
  60232. justification = Justification::centredLeft;
  60233. else if (orientation == verticalKeyboardFacingRight)
  60234. justification = Justification::centredRight;
  60235. g.drawFittedText (text, x + 2, y + 2, w - 4, h - 4, justification, 1);
  60236. }
  60237. g.setColour (lineColour);
  60238. if (orientation == horizontalKeyboard)
  60239. g.fillRect (x, y, 1, h);
  60240. else if (orientation == verticalKeyboardFacingLeft)
  60241. g.fillRect (x, y, w, 1);
  60242. else if (orientation == verticalKeyboardFacingRight)
  60243. g.fillRect (x, y + h - 1, w, 1);
  60244. if (midiNoteNumber == rangeEnd)
  60245. {
  60246. if (orientation == horizontalKeyboard)
  60247. g.fillRect (x + w, y, 1, h);
  60248. else if (orientation == verticalKeyboardFacingLeft)
  60249. g.fillRect (x, y + h, w, 1);
  60250. else if (orientation == verticalKeyboardFacingRight)
  60251. g.fillRect (x, y - 1, w, 1);
  60252. }
  60253. }
  60254. void MidiKeyboardComponent::drawBlackNote (int /*midiNoteNumber*/,
  60255. Graphics& g, int x, int y, int w, int h,
  60256. bool isDown, bool isOver,
  60257. const Colour& noteFillColour)
  60258. {
  60259. Colour c (noteFillColour);
  60260. if (isDown)
  60261. c = c.overlaidWith (findColour (keyDownOverlayColourId));
  60262. if (isOver)
  60263. c = c.overlaidWith (findColour (mouseOverKeyOverlayColourId));
  60264. g.setColour (c);
  60265. g.fillRect (x, y, w, h);
  60266. if (isDown)
  60267. {
  60268. g.setColour (noteFillColour);
  60269. g.drawRect (x, y, w, h);
  60270. }
  60271. else
  60272. {
  60273. const int xIndent = jmax (1, jmin (w, h) / 8);
  60274. g.setColour (c.brighter());
  60275. if (orientation == horizontalKeyboard)
  60276. g.fillRect (x + xIndent, y, w - xIndent * 2, 7 * h / 8);
  60277. else if (orientation == verticalKeyboardFacingLeft)
  60278. g.fillRect (x + w / 8, y + xIndent, w - w / 8, h - xIndent * 2);
  60279. else if (orientation == verticalKeyboardFacingRight)
  60280. g.fillRect (x, y + xIndent, 7 * w / 8, h - xIndent * 2);
  60281. }
  60282. }
  60283. void MidiKeyboardComponent::setOctaveForMiddleC (const int octaveNumForMiddleC_)
  60284. {
  60285. octaveNumForMiddleC = octaveNumForMiddleC_;
  60286. repaint();
  60287. }
  60288. const String MidiKeyboardComponent::getWhiteNoteText (const int midiNoteNumber)
  60289. {
  60290. if (keyWidth > 14.0f && midiNoteNumber % 12 == 0)
  60291. return MidiMessage::getMidiNoteName (midiNoteNumber, true, true, octaveNumForMiddleC);
  60292. return String::empty;
  60293. }
  60294. void MidiKeyboardComponent::drawUpDownButton (Graphics& g, int w, int h,
  60295. const bool isMouseOver_,
  60296. const bool isButtonDown,
  60297. const bool movesOctavesUp)
  60298. {
  60299. g.fillAll (findColour (upDownButtonBackgroundColourId));
  60300. float angle;
  60301. if (orientation == MidiKeyboardComponent::horizontalKeyboard)
  60302. angle = movesOctavesUp ? 0.0f : 0.5f;
  60303. else if (orientation == MidiKeyboardComponent::verticalKeyboardFacingLeft)
  60304. angle = movesOctavesUp ? 0.25f : 0.75f;
  60305. else
  60306. angle = movesOctavesUp ? 0.75f : 0.25f;
  60307. Path path;
  60308. path.lineTo (0.0f, 1.0f);
  60309. path.lineTo (1.0f, 0.5f);
  60310. path.closeSubPath();
  60311. path.applyTransform (AffineTransform::rotation (float_Pi * 2.0f * angle, 0.5f, 0.5f));
  60312. g.setColour (findColour (upDownButtonArrowColourId)
  60313. .withAlpha (isButtonDown ? 1.0f : (isMouseOver_ ? 0.6f : 0.4f)));
  60314. g.fillPath (path, path.getTransformToScaleToFit (1.0f, 1.0f,
  60315. w - 2.0f,
  60316. h - 2.0f,
  60317. true));
  60318. }
  60319. void MidiKeyboardComponent::resized()
  60320. {
  60321. int w = getWidth();
  60322. int h = getHeight();
  60323. if (w > 0 && h > 0)
  60324. {
  60325. if (orientation != horizontalKeyboard)
  60326. swapVariables (w, h);
  60327. blackNoteLength = roundToInt (h * 0.7f);
  60328. int kx2, kw2;
  60329. getKeyPos (rangeEnd, kx2, kw2);
  60330. kx2 += kw2;
  60331. if (firstKey != rangeStart)
  60332. {
  60333. int kx1, kw1;
  60334. getKeyPos (rangeStart, kx1, kw1);
  60335. if (kx2 - kx1 <= w)
  60336. {
  60337. firstKey = rangeStart;
  60338. sendChangeMessage (this);
  60339. repaint();
  60340. }
  60341. }
  60342. const bool showScrollButtons = canScroll && (firstKey > rangeStart || kx2 > w + xOffset * 2);
  60343. scrollDown->setVisible (showScrollButtons);
  60344. scrollUp->setVisible (showScrollButtons);
  60345. xOffset = 0;
  60346. if (showScrollButtons)
  60347. {
  60348. const int scrollButtonW = jmin (12, w / 2);
  60349. if (orientation == horizontalKeyboard)
  60350. {
  60351. scrollDown->setBounds (0, 0, scrollButtonW, getHeight());
  60352. scrollUp->setBounds (getWidth() - scrollButtonW, 0, scrollButtonW, getHeight());
  60353. }
  60354. else if (orientation == verticalKeyboardFacingLeft)
  60355. {
  60356. scrollDown->setBounds (0, 0, getWidth(), scrollButtonW);
  60357. scrollUp->setBounds (0, getHeight() - scrollButtonW, getWidth(), scrollButtonW);
  60358. }
  60359. else if (orientation == verticalKeyboardFacingRight)
  60360. {
  60361. scrollDown->setBounds (0, getHeight() - scrollButtonW, getWidth(), scrollButtonW);
  60362. scrollUp->setBounds (0, 0, getWidth(), scrollButtonW);
  60363. }
  60364. int endOfLastKey, kw;
  60365. getKeyPos (rangeEnd, endOfLastKey, kw);
  60366. endOfLastKey += kw;
  60367. float mousePositionVelocity;
  60368. const int spaceAvailable = w - scrollButtonW * 2;
  60369. const int lastStartKey = remappedXYToNote (Point<int> (endOfLastKey - spaceAvailable, 0), mousePositionVelocity) + 1;
  60370. if (lastStartKey >= 0 && firstKey > lastStartKey)
  60371. {
  60372. firstKey = jlimit (rangeStart, rangeEnd, lastStartKey);
  60373. sendChangeMessage (this);
  60374. }
  60375. int newOffset = 0;
  60376. getKeyPos (firstKey, newOffset, kw);
  60377. xOffset = newOffset - scrollButtonW;
  60378. }
  60379. else
  60380. {
  60381. firstKey = rangeStart;
  60382. }
  60383. timerCallback();
  60384. repaint();
  60385. }
  60386. }
  60387. void MidiKeyboardComponent::handleNoteOn (MidiKeyboardState*, int /*midiChannel*/, int /*midiNoteNumber*/, float /*velocity*/)
  60388. {
  60389. triggerAsyncUpdate();
  60390. }
  60391. void MidiKeyboardComponent::handleNoteOff (MidiKeyboardState*, int /*midiChannel*/, int /*midiNoteNumber*/)
  60392. {
  60393. triggerAsyncUpdate();
  60394. }
  60395. void MidiKeyboardComponent::handleAsyncUpdate()
  60396. {
  60397. for (int i = rangeStart; i <= rangeEnd; ++i)
  60398. {
  60399. if (keysCurrentlyDrawnDown[i] != state.isNoteOnForChannels (midiInChannelMask, i))
  60400. {
  60401. keysCurrentlyDrawnDown.setBit (i, state.isNoteOnForChannels (midiInChannelMask, i));
  60402. repaintNote (i);
  60403. }
  60404. }
  60405. }
  60406. void MidiKeyboardComponent::resetAnyKeysInUse()
  60407. {
  60408. if (keysPressed.countNumberOfSetBits() > 0 || mouseDownNote > 0)
  60409. {
  60410. state.allNotesOff (midiChannel);
  60411. keysPressed.clear();
  60412. mouseDownNote = -1;
  60413. }
  60414. }
  60415. void MidiKeyboardComponent::updateNoteUnderMouse (const Point<int>& pos)
  60416. {
  60417. float mousePositionVelocity = 0.0f;
  60418. const int newNote = (mouseDragging || isMouseOver())
  60419. ? xyToNote (pos, mousePositionVelocity) : -1;
  60420. if (noteUnderMouse != newNote)
  60421. {
  60422. if (mouseDownNote >= 0)
  60423. {
  60424. state.noteOff (midiChannel, mouseDownNote);
  60425. mouseDownNote = -1;
  60426. }
  60427. if (mouseDragging && newNote >= 0)
  60428. {
  60429. if (! useMousePositionForVelocity)
  60430. mousePositionVelocity = 1.0f;
  60431. state.noteOn (midiChannel, newNote, mousePositionVelocity * velocity);
  60432. mouseDownNote = newNote;
  60433. }
  60434. repaintNote (noteUnderMouse);
  60435. noteUnderMouse = newNote;
  60436. repaintNote (noteUnderMouse);
  60437. }
  60438. else if (mouseDownNote >= 0 && ! mouseDragging)
  60439. {
  60440. state.noteOff (midiChannel, mouseDownNote);
  60441. mouseDownNote = -1;
  60442. }
  60443. }
  60444. void MidiKeyboardComponent::mouseMove (const MouseEvent& e)
  60445. {
  60446. updateNoteUnderMouse (e.getPosition());
  60447. stopTimer();
  60448. }
  60449. void MidiKeyboardComponent::mouseDrag (const MouseEvent& e)
  60450. {
  60451. float mousePositionVelocity;
  60452. const int newNote = xyToNote (e.getPosition(), mousePositionVelocity);
  60453. if (newNote >= 0)
  60454. mouseDraggedToKey (newNote, e);
  60455. updateNoteUnderMouse (e.getPosition());
  60456. }
  60457. bool MidiKeyboardComponent::mouseDownOnKey (int /*midiNoteNumber*/, const MouseEvent&)
  60458. {
  60459. return true;
  60460. }
  60461. void MidiKeyboardComponent::mouseDraggedToKey (int /*midiNoteNumber*/, const MouseEvent&)
  60462. {
  60463. }
  60464. void MidiKeyboardComponent::mouseDown (const MouseEvent& e)
  60465. {
  60466. float mousePositionVelocity;
  60467. const int newNote = xyToNote (e.getPosition(), mousePositionVelocity);
  60468. mouseDragging = false;
  60469. if (newNote >= 0 && mouseDownOnKey (newNote, e))
  60470. {
  60471. repaintNote (noteUnderMouse);
  60472. noteUnderMouse = -1;
  60473. mouseDragging = true;
  60474. updateNoteUnderMouse (e.getPosition());
  60475. startTimer (500);
  60476. }
  60477. }
  60478. void MidiKeyboardComponent::mouseUp (const MouseEvent& e)
  60479. {
  60480. mouseDragging = false;
  60481. updateNoteUnderMouse (e.getPosition());
  60482. stopTimer();
  60483. }
  60484. void MidiKeyboardComponent::mouseEnter (const MouseEvent& e)
  60485. {
  60486. updateNoteUnderMouse (e.getPosition());
  60487. }
  60488. void MidiKeyboardComponent::mouseExit (const MouseEvent& e)
  60489. {
  60490. updateNoteUnderMouse (e.getPosition());
  60491. }
  60492. void MidiKeyboardComponent::mouseWheelMove (const MouseEvent&, float ix, float iy)
  60493. {
  60494. setLowestVisibleKey (getLowestVisibleKey() + roundToInt ((ix != 0 ? ix : iy) * 5.0f));
  60495. }
  60496. void MidiKeyboardComponent::timerCallback()
  60497. {
  60498. updateNoteUnderMouse (getMouseXYRelative());
  60499. }
  60500. void MidiKeyboardComponent::clearKeyMappings()
  60501. {
  60502. resetAnyKeysInUse();
  60503. keyPressNotes.clear();
  60504. keyPresses.clear();
  60505. }
  60506. void MidiKeyboardComponent::setKeyPressForNote (const KeyPress& key,
  60507. const int midiNoteOffsetFromC)
  60508. {
  60509. removeKeyPressForNote (midiNoteOffsetFromC);
  60510. keyPressNotes.add (midiNoteOffsetFromC);
  60511. keyPresses.add (key);
  60512. }
  60513. void MidiKeyboardComponent::removeKeyPressForNote (const int midiNoteOffsetFromC)
  60514. {
  60515. for (int i = keyPressNotes.size(); --i >= 0;)
  60516. {
  60517. if (keyPressNotes.getUnchecked (i) == midiNoteOffsetFromC)
  60518. {
  60519. keyPressNotes.remove (i);
  60520. keyPresses.remove (i);
  60521. }
  60522. }
  60523. }
  60524. void MidiKeyboardComponent::setKeyPressBaseOctave (const int newOctaveNumber)
  60525. {
  60526. jassert (newOctaveNumber >= 0 && newOctaveNumber <= 10);
  60527. keyMappingOctave = newOctaveNumber;
  60528. }
  60529. bool MidiKeyboardComponent::keyStateChanged (const bool /*isKeyDown*/)
  60530. {
  60531. bool keyPressUsed = false;
  60532. for (int i = keyPresses.size(); --i >= 0;)
  60533. {
  60534. const int note = 12 * keyMappingOctave + keyPressNotes.getUnchecked (i);
  60535. if (keyPresses.getReference(i).isCurrentlyDown())
  60536. {
  60537. if (! keysPressed [note])
  60538. {
  60539. keysPressed.setBit (note);
  60540. state.noteOn (midiChannel, note, velocity);
  60541. keyPressUsed = true;
  60542. }
  60543. }
  60544. else
  60545. {
  60546. if (keysPressed [note])
  60547. {
  60548. keysPressed.clearBit (note);
  60549. state.noteOff (midiChannel, note);
  60550. keyPressUsed = true;
  60551. }
  60552. }
  60553. }
  60554. return keyPressUsed;
  60555. }
  60556. void MidiKeyboardComponent::focusLost (FocusChangeType)
  60557. {
  60558. resetAnyKeysInUse();
  60559. }
  60560. END_JUCE_NAMESPACE
  60561. /*** End of inlined file: juce_MidiKeyboardComponent.cpp ***/
  60562. /*** Start of inlined file: juce_OpenGLComponent.cpp ***/
  60563. #if JUCE_OPENGL
  60564. BEGIN_JUCE_NAMESPACE
  60565. extern void juce_glViewport (const int w, const int h);
  60566. OpenGLPixelFormat::OpenGLPixelFormat (const int bitsPerRGBComponent,
  60567. const int alphaBits_,
  60568. const int depthBufferBits_,
  60569. const int stencilBufferBits_)
  60570. : redBits (bitsPerRGBComponent),
  60571. greenBits (bitsPerRGBComponent),
  60572. blueBits (bitsPerRGBComponent),
  60573. alphaBits (alphaBits_),
  60574. depthBufferBits (depthBufferBits_),
  60575. stencilBufferBits (stencilBufferBits_),
  60576. accumulationBufferRedBits (0),
  60577. accumulationBufferGreenBits (0),
  60578. accumulationBufferBlueBits (0),
  60579. accumulationBufferAlphaBits (0),
  60580. fullSceneAntiAliasingNumSamples (0)
  60581. {
  60582. }
  60583. OpenGLPixelFormat::OpenGLPixelFormat (const OpenGLPixelFormat& other)
  60584. : redBits (other.redBits),
  60585. greenBits (other.greenBits),
  60586. blueBits (other.blueBits),
  60587. alphaBits (other.alphaBits),
  60588. depthBufferBits (other.depthBufferBits),
  60589. stencilBufferBits (other.stencilBufferBits),
  60590. accumulationBufferRedBits (other.accumulationBufferRedBits),
  60591. accumulationBufferGreenBits (other.accumulationBufferGreenBits),
  60592. accumulationBufferBlueBits (other.accumulationBufferBlueBits),
  60593. accumulationBufferAlphaBits (other.accumulationBufferAlphaBits),
  60594. fullSceneAntiAliasingNumSamples (other.fullSceneAntiAliasingNumSamples)
  60595. {
  60596. }
  60597. OpenGLPixelFormat& OpenGLPixelFormat::operator= (const OpenGLPixelFormat& other)
  60598. {
  60599. redBits = other.redBits;
  60600. greenBits = other.greenBits;
  60601. blueBits = other.blueBits;
  60602. alphaBits = other.alphaBits;
  60603. depthBufferBits = other.depthBufferBits;
  60604. stencilBufferBits = other.stencilBufferBits;
  60605. accumulationBufferRedBits = other.accumulationBufferRedBits;
  60606. accumulationBufferGreenBits = other.accumulationBufferGreenBits;
  60607. accumulationBufferBlueBits = other.accumulationBufferBlueBits;
  60608. accumulationBufferAlphaBits = other.accumulationBufferAlphaBits;
  60609. fullSceneAntiAliasingNumSamples = other.fullSceneAntiAliasingNumSamples;
  60610. return *this;
  60611. }
  60612. bool OpenGLPixelFormat::operator== (const OpenGLPixelFormat& other) const
  60613. {
  60614. return redBits == other.redBits
  60615. && greenBits == other.greenBits
  60616. && blueBits == other.blueBits
  60617. && alphaBits == other.alphaBits
  60618. && depthBufferBits == other.depthBufferBits
  60619. && stencilBufferBits == other.stencilBufferBits
  60620. && accumulationBufferRedBits == other.accumulationBufferRedBits
  60621. && accumulationBufferGreenBits == other.accumulationBufferGreenBits
  60622. && accumulationBufferBlueBits == other.accumulationBufferBlueBits
  60623. && accumulationBufferAlphaBits == other.accumulationBufferAlphaBits
  60624. && fullSceneAntiAliasingNumSamples == other.fullSceneAntiAliasingNumSamples;
  60625. }
  60626. static VoidArray knownContexts;
  60627. OpenGLContext::OpenGLContext() throw()
  60628. {
  60629. knownContexts.add (this);
  60630. }
  60631. OpenGLContext::~OpenGLContext()
  60632. {
  60633. knownContexts.removeValue (this);
  60634. }
  60635. OpenGLContext* OpenGLContext::getCurrentContext()
  60636. {
  60637. for (int i = knownContexts.size(); --i >= 0;)
  60638. {
  60639. OpenGLContext* const oglc = (OpenGLContext*) knownContexts.getUnchecked(i);
  60640. if (oglc->isActive())
  60641. return oglc;
  60642. }
  60643. return 0;
  60644. }
  60645. class OpenGLComponent::OpenGLComponentWatcher : public ComponentMovementWatcher
  60646. {
  60647. public:
  60648. OpenGLComponentWatcher (OpenGLComponent* const owner_)
  60649. : ComponentMovementWatcher (owner_),
  60650. owner (owner_),
  60651. wasShowing (false)
  60652. {
  60653. }
  60654. ~OpenGLComponentWatcher() {}
  60655. void componentMovedOrResized (bool /*wasMoved*/, bool /*wasResized*/)
  60656. {
  60657. owner->updateContextPosition();
  60658. }
  60659. void componentPeerChanged()
  60660. {
  60661. const ScopedLock sl (owner->getContextLock());
  60662. owner->deleteContext();
  60663. }
  60664. void componentVisibilityChanged (Component&)
  60665. {
  60666. const bool isShowingNow = owner->isShowing();
  60667. if (wasShowing != isShowingNow)
  60668. {
  60669. wasShowing = isShowingNow;
  60670. owner->updateContextPosition();
  60671. }
  60672. }
  60673. juce_UseDebuggingNewOperator
  60674. private:
  60675. OpenGLComponent* const owner;
  60676. bool wasShowing;
  60677. };
  60678. OpenGLComponent::OpenGLComponent (const OpenGLType type_)
  60679. : type (type_),
  60680. contextToShareListsWith (0),
  60681. needToUpdateViewport (true)
  60682. {
  60683. setOpaque (true);
  60684. componentWatcher = new OpenGLComponentWatcher (this);
  60685. }
  60686. OpenGLComponent::~OpenGLComponent()
  60687. {
  60688. deleteContext();
  60689. componentWatcher = 0;
  60690. }
  60691. void OpenGLComponent::deleteContext()
  60692. {
  60693. const ScopedLock sl (contextLock);
  60694. context = 0;
  60695. }
  60696. void OpenGLComponent::updateContextPosition()
  60697. {
  60698. needToUpdateViewport = true;
  60699. if (getWidth() > 0 && getHeight() > 0)
  60700. {
  60701. Component* const topComp = getTopLevelComponent();
  60702. if (topComp->getPeer() != 0)
  60703. {
  60704. const ScopedLock sl (contextLock);
  60705. if (context != 0)
  60706. context->updateWindowPosition (getScreenX() - topComp->getScreenX(),
  60707. getScreenY() - topComp->getScreenY(),
  60708. getWidth(),
  60709. getHeight(),
  60710. topComp->getHeight());
  60711. }
  60712. }
  60713. }
  60714. const OpenGLPixelFormat OpenGLComponent::getPixelFormat() const
  60715. {
  60716. OpenGLPixelFormat pf;
  60717. const ScopedLock sl (contextLock);
  60718. if (context != 0)
  60719. pf = context->getPixelFormat();
  60720. return pf;
  60721. }
  60722. void OpenGLComponent::setPixelFormat (const OpenGLPixelFormat& formatToUse)
  60723. {
  60724. if (! (preferredPixelFormat == formatToUse))
  60725. {
  60726. const ScopedLock sl (contextLock);
  60727. deleteContext();
  60728. preferredPixelFormat = formatToUse;
  60729. }
  60730. }
  60731. void OpenGLComponent::shareWith (OpenGLContext* c)
  60732. {
  60733. if (contextToShareListsWith != c)
  60734. {
  60735. const ScopedLock sl (contextLock);
  60736. deleteContext();
  60737. contextToShareListsWith = c;
  60738. }
  60739. }
  60740. bool OpenGLComponent::makeCurrentContextActive()
  60741. {
  60742. if (context == 0)
  60743. {
  60744. const ScopedLock sl (contextLock);
  60745. if (isShowing() && getTopLevelComponent()->getPeer() != 0)
  60746. {
  60747. context = createContext();
  60748. if (context != 0)
  60749. {
  60750. updateContextPosition();
  60751. if (context->makeActive())
  60752. newOpenGLContextCreated();
  60753. }
  60754. }
  60755. }
  60756. return context != 0 && context->makeActive();
  60757. }
  60758. void OpenGLComponent::makeCurrentContextInactive()
  60759. {
  60760. if (context != 0)
  60761. context->makeInactive();
  60762. }
  60763. bool OpenGLComponent::isActiveContext() const throw()
  60764. {
  60765. return context != 0 && context->isActive();
  60766. }
  60767. void OpenGLComponent::swapBuffers()
  60768. {
  60769. if (context != 0)
  60770. context->swapBuffers();
  60771. }
  60772. void OpenGLComponent::paint (Graphics&)
  60773. {
  60774. if (renderAndSwapBuffers())
  60775. {
  60776. ComponentPeer* const peer = getPeer();
  60777. if (peer != 0)
  60778. {
  60779. const Point<int> topLeft (getScreenPosition() - peer->getScreenPosition());
  60780. peer->addMaskedRegion (topLeft.getX(), topLeft.getY(), getWidth(), getHeight());
  60781. }
  60782. }
  60783. }
  60784. bool OpenGLComponent::renderAndSwapBuffers()
  60785. {
  60786. const ScopedLock sl (contextLock);
  60787. if (! makeCurrentContextActive())
  60788. return false;
  60789. if (needToUpdateViewport)
  60790. {
  60791. needToUpdateViewport = false;
  60792. juce_glViewport (getWidth(), getHeight());
  60793. }
  60794. renderOpenGL();
  60795. swapBuffers();
  60796. return true;
  60797. }
  60798. void OpenGLComponent::internalRepaint (int x, int y, int w, int h)
  60799. {
  60800. Component::internalRepaint (x, y, w, h);
  60801. if (context != 0)
  60802. context->repaint();
  60803. }
  60804. END_JUCE_NAMESPACE
  60805. #endif
  60806. /*** End of inlined file: juce_OpenGLComponent.cpp ***/
  60807. /*** Start of inlined file: juce_PreferencesPanel.cpp ***/
  60808. BEGIN_JUCE_NAMESPACE
  60809. PreferencesPanel::PreferencesPanel()
  60810. : buttonSize (70)
  60811. {
  60812. }
  60813. PreferencesPanel::~PreferencesPanel()
  60814. {
  60815. currentPage = 0;
  60816. deleteAllChildren();
  60817. }
  60818. void PreferencesPanel::addSettingsPage (const String& title,
  60819. const Drawable* icon,
  60820. const Drawable* overIcon,
  60821. const Drawable* downIcon)
  60822. {
  60823. DrawableButton* button = new DrawableButton (title, DrawableButton::ImageAboveTextLabel);
  60824. button->setImages (icon, overIcon, downIcon);
  60825. button->setRadioGroupId (1);
  60826. button->addButtonListener (this);
  60827. button->setClickingTogglesState (true);
  60828. button->setWantsKeyboardFocus (false);
  60829. addAndMakeVisible (button);
  60830. resized();
  60831. if (currentPage == 0)
  60832. setCurrentPage (title);
  60833. }
  60834. void PreferencesPanel::addSettingsPage (const String& title,
  60835. const char* imageData,
  60836. const int imageDataSize)
  60837. {
  60838. DrawableImage icon, iconOver, iconDown;
  60839. icon.setImage (ImageCache::getFromMemory (imageData, imageDataSize), true);
  60840. iconOver.setImage (ImageCache::getFromMemory (imageData, imageDataSize), true);
  60841. iconOver.setOverlayColour (Colours::black.withAlpha (0.12f));
  60842. iconDown.setImage (ImageCache::getFromMemory (imageData, imageDataSize), true);
  60843. iconDown.setOverlayColour (Colours::black.withAlpha (0.25f));
  60844. addSettingsPage (title, &icon, &iconOver, &iconDown);
  60845. }
  60846. class PrefsDialogWindow : public DialogWindow
  60847. {
  60848. public:
  60849. PrefsDialogWindow (const String& dialogtitle,
  60850. const Colour& backgroundColour)
  60851. : DialogWindow (dialogtitle, backgroundColour, true)
  60852. {
  60853. }
  60854. ~PrefsDialogWindow()
  60855. {
  60856. }
  60857. void closeButtonPressed()
  60858. {
  60859. exitModalState (0);
  60860. }
  60861. private:
  60862. PrefsDialogWindow (const PrefsDialogWindow&);
  60863. PrefsDialogWindow& operator= (const PrefsDialogWindow&);
  60864. };
  60865. void PreferencesPanel::showInDialogBox (const String& dialogtitle,
  60866. int dialogWidth,
  60867. int dialogHeight,
  60868. const Colour& backgroundColour)
  60869. {
  60870. setSize (dialogWidth, dialogHeight);
  60871. PrefsDialogWindow dw (dialogtitle, backgroundColour);
  60872. dw.setContentComponent (this, true, true);
  60873. dw.centreAroundComponent (0, dw.getWidth(), dw.getHeight());
  60874. dw.runModalLoop();
  60875. dw.setContentComponent (0, false, false);
  60876. }
  60877. void PreferencesPanel::resized()
  60878. {
  60879. int x = 0;
  60880. for (int i = 0; i < getNumChildComponents(); ++i)
  60881. {
  60882. Component* c = getChildComponent (i);
  60883. if (dynamic_cast <DrawableButton*> (c) == 0)
  60884. {
  60885. c->setBounds (0, buttonSize + 5, getWidth(), getHeight() - buttonSize - 5);
  60886. }
  60887. else
  60888. {
  60889. c->setBounds (x, 0, buttonSize, buttonSize);
  60890. x += buttonSize;
  60891. }
  60892. }
  60893. }
  60894. void PreferencesPanel::paint (Graphics& g)
  60895. {
  60896. g.setColour (Colours::grey);
  60897. g.fillRect (0, buttonSize + 2, getWidth(), 1);
  60898. }
  60899. void PreferencesPanel::setCurrentPage (const String& pageName)
  60900. {
  60901. if (currentPageName != pageName)
  60902. {
  60903. currentPageName = pageName;
  60904. currentPage = 0;
  60905. currentPage = createComponentForPage (pageName);
  60906. if (currentPage != 0)
  60907. {
  60908. addAndMakeVisible (currentPage);
  60909. currentPage->toBack();
  60910. resized();
  60911. }
  60912. for (int i = 0; i < getNumChildComponents(); ++i)
  60913. {
  60914. DrawableButton* db = dynamic_cast <DrawableButton*> (getChildComponent (i));
  60915. if (db != 0 && db->getName() == pageName)
  60916. {
  60917. db->setToggleState (true, false);
  60918. break;
  60919. }
  60920. }
  60921. }
  60922. }
  60923. void PreferencesPanel::buttonClicked (Button*)
  60924. {
  60925. for (int i = 0; i < getNumChildComponents(); ++i)
  60926. {
  60927. DrawableButton* db = dynamic_cast <DrawableButton*> (getChildComponent (i));
  60928. if (db != 0 && db->getToggleState())
  60929. {
  60930. setCurrentPage (db->getName());
  60931. break;
  60932. }
  60933. }
  60934. }
  60935. END_JUCE_NAMESPACE
  60936. /*** End of inlined file: juce_PreferencesPanel.cpp ***/
  60937. /*** Start of inlined file: juce_SystemTrayIconComponent.cpp ***/
  60938. #if JUCE_WINDOWS || JUCE_LINUX
  60939. BEGIN_JUCE_NAMESPACE
  60940. SystemTrayIconComponent::SystemTrayIconComponent()
  60941. {
  60942. addToDesktop (0);
  60943. }
  60944. SystemTrayIconComponent::~SystemTrayIconComponent()
  60945. {
  60946. }
  60947. END_JUCE_NAMESPACE
  60948. #endif
  60949. /*** End of inlined file: juce_SystemTrayIconComponent.cpp ***/
  60950. /*** Start of inlined file: juce_AlertWindow.cpp ***/
  60951. BEGIN_JUCE_NAMESPACE
  60952. class AlertWindowTextEditor : public TextEditor
  60953. {
  60954. public:
  60955. AlertWindowTextEditor (const String& name, const bool isPasswordBox)
  60956. : TextEditor (name, isPasswordBox ? getDefaultPasswordChar() : 0)
  60957. {
  60958. setSelectAllWhenFocused (true);
  60959. }
  60960. ~AlertWindowTextEditor()
  60961. {
  60962. }
  60963. void returnPressed()
  60964. {
  60965. // pass these up the component hierarchy to be trigger the buttons
  60966. getParentComponent()->keyPressed (KeyPress (KeyPress::returnKey, 0, '\n'));
  60967. }
  60968. void escapePressed()
  60969. {
  60970. // pass these up the component hierarchy to be trigger the buttons
  60971. getParentComponent()->keyPressed (KeyPress (KeyPress::escapeKey, 0, 0));
  60972. }
  60973. private:
  60974. AlertWindowTextEditor (const AlertWindowTextEditor&);
  60975. AlertWindowTextEditor& operator= (const AlertWindowTextEditor&);
  60976. static juce_wchar getDefaultPasswordChar() throw()
  60977. {
  60978. #if JUCE_LINUX
  60979. return 0x2022;
  60980. #else
  60981. return 0x25cf;
  60982. #endif
  60983. }
  60984. };
  60985. AlertWindow::AlertWindow (const String& title,
  60986. const String& message,
  60987. AlertIconType iconType,
  60988. Component* associatedComponent_)
  60989. : TopLevelWindow (title, true),
  60990. alertIconType (iconType),
  60991. associatedComponent (associatedComponent_)
  60992. {
  60993. if (message.isEmpty())
  60994. text = " "; // to force an update if the message is empty
  60995. setMessage (message);
  60996. for (int i = Desktop::getInstance().getNumComponents(); --i >= 0;)
  60997. {
  60998. Component* const c = Desktop::getInstance().getComponent (i);
  60999. if (c != 0 && c->isAlwaysOnTop() && c->isShowing())
  61000. {
  61001. setAlwaysOnTop (true);
  61002. break;
  61003. }
  61004. }
  61005. if (JUCEApplication::getInstance() == 0)
  61006. setAlwaysOnTop (true); // for a plugin, make it always-on-top because the host windows are often top-level
  61007. lookAndFeelChanged();
  61008. constrainer.setMinimumOnscreenAmounts (0x10000, 0x10000, 0x10000, 0x10000);
  61009. }
  61010. AlertWindow::~AlertWindow()
  61011. {
  61012. for (int i = customComps.size(); --i >= 0;)
  61013. removeChildComponent ((Component*) customComps[i]);
  61014. deleteAllChildren();
  61015. }
  61016. void AlertWindow::userTriedToCloseWindow()
  61017. {
  61018. exitModalState (0);
  61019. }
  61020. void AlertWindow::setMessage (const String& message)
  61021. {
  61022. const String newMessage (message.substring (0, 2048));
  61023. if (text != newMessage)
  61024. {
  61025. text = newMessage;
  61026. font.setHeight (15.0f);
  61027. Font titleFont (font.getHeight() * 1.1f, Font::bold);
  61028. textLayout.setText (getName() + "\n\n", titleFont);
  61029. textLayout.appendText (text, font);
  61030. updateLayout (true);
  61031. repaint();
  61032. }
  61033. }
  61034. void AlertWindow::buttonClicked (Button* button)
  61035. {
  61036. for (int i = 0; i < buttons.size(); i++)
  61037. {
  61038. TextButton* const c = (TextButton*) buttons[i];
  61039. if (button->getName() == c->getName())
  61040. {
  61041. if (c->getParentComponent() != 0)
  61042. c->getParentComponent()->exitModalState (c->getCommandID());
  61043. break;
  61044. }
  61045. }
  61046. }
  61047. void AlertWindow::addButton (const String& name,
  61048. const int returnValue,
  61049. const KeyPress& shortcutKey1,
  61050. const KeyPress& shortcutKey2)
  61051. {
  61052. TextButton* const b = new TextButton (name, String::empty);
  61053. b->setWantsKeyboardFocus (true);
  61054. b->setMouseClickGrabsKeyboardFocus (false);
  61055. b->setCommandToTrigger (0, returnValue, false);
  61056. b->addShortcut (shortcutKey1);
  61057. b->addShortcut (shortcutKey2);
  61058. b->addButtonListener (this);
  61059. b->changeWidthToFitText (getLookAndFeel().getAlertWindowButtonHeight());
  61060. addAndMakeVisible (b, 0);
  61061. buttons.add (b);
  61062. updateLayout (false);
  61063. }
  61064. int AlertWindow::getNumButtons() const
  61065. {
  61066. return buttons.size();
  61067. }
  61068. void AlertWindow::triggerButtonClick (const String& buttonName)
  61069. {
  61070. for (int i = buttons.size(); --i >= 0;)
  61071. {
  61072. TextButton* const b = (TextButton*) buttons[i];
  61073. if (buttonName == b->getName())
  61074. {
  61075. b->triggerClick();
  61076. break;
  61077. }
  61078. }
  61079. }
  61080. void AlertWindow::addTextEditor (const String& name,
  61081. const String& initialContents,
  61082. const String& onScreenLabel,
  61083. const bool isPasswordBox)
  61084. {
  61085. AlertWindowTextEditor* const tc = new AlertWindowTextEditor (name, isPasswordBox);
  61086. tc->setColour (TextEditor::outlineColourId, findColour (ComboBox::outlineColourId));
  61087. tc->setFont (font);
  61088. tc->setText (initialContents);
  61089. tc->setCaretPosition (initialContents.length());
  61090. addAndMakeVisible (tc);
  61091. textBoxes.add (tc);
  61092. allComps.add (tc);
  61093. textboxNames.add (onScreenLabel);
  61094. updateLayout (false);
  61095. }
  61096. const String AlertWindow::getTextEditorContents (const String& nameOfTextEditor) const
  61097. {
  61098. for (int i = textBoxes.size(); --i >= 0;)
  61099. if (((TextEditor*)textBoxes[i])->getName() == nameOfTextEditor)
  61100. return ((TextEditor*)textBoxes[i])->getText();
  61101. return String::empty;
  61102. }
  61103. void AlertWindow::addComboBox (const String& name,
  61104. const StringArray& items,
  61105. const String& onScreenLabel)
  61106. {
  61107. ComboBox* const cb = new ComboBox (name);
  61108. for (int i = 0; i < items.size(); ++i)
  61109. cb->addItem (items[i], i + 1);
  61110. addAndMakeVisible (cb);
  61111. cb->setSelectedItemIndex (0);
  61112. comboBoxes.add (cb);
  61113. allComps.add (cb);
  61114. comboBoxNames.add (onScreenLabel);
  61115. updateLayout (false);
  61116. }
  61117. ComboBox* AlertWindow::getComboBoxComponent (const String& nameOfList) const
  61118. {
  61119. for (int i = comboBoxes.size(); --i >= 0;)
  61120. if (((ComboBox*) comboBoxes[i])->getName() == nameOfList)
  61121. return (ComboBox*) comboBoxes[i];
  61122. return 0;
  61123. }
  61124. class AlertTextComp : public TextEditor
  61125. {
  61126. public:
  61127. AlertTextComp (const String& message,
  61128. const Font& font)
  61129. {
  61130. setReadOnly (true);
  61131. setMultiLine (true, true);
  61132. setCaretVisible (false);
  61133. setScrollbarsShown (true);
  61134. lookAndFeelChanged();
  61135. setWantsKeyboardFocus (false);
  61136. setFont (font);
  61137. setText (message, false);
  61138. bestWidth = 2 * (int) std::sqrt (font.getHeight() * font.getStringWidth (message));
  61139. setColour (TextEditor::backgroundColourId, Colours::transparentBlack);
  61140. setColour (TextEditor::outlineColourId, Colours::transparentBlack);
  61141. setColour (TextEditor::shadowColourId, Colours::transparentBlack);
  61142. }
  61143. ~AlertTextComp()
  61144. {
  61145. }
  61146. int getPreferredWidth() const throw() { return bestWidth; }
  61147. void updateLayout (const int width)
  61148. {
  61149. TextLayout text;
  61150. text.appendText (getText(), getFont());
  61151. text.layout (width - 8, Justification::topLeft, true);
  61152. setSize (width, jmin (width, text.getHeight() + (int) getFont().getHeight()));
  61153. }
  61154. private:
  61155. int bestWidth;
  61156. AlertTextComp (const AlertTextComp&);
  61157. AlertTextComp& operator= (const AlertTextComp&);
  61158. };
  61159. void AlertWindow::addTextBlock (const String& textBlock)
  61160. {
  61161. AlertTextComp* const c = new AlertTextComp (textBlock, font);
  61162. textBlocks.add (c);
  61163. allComps.add (c);
  61164. addAndMakeVisible (c);
  61165. updateLayout (false);
  61166. }
  61167. void AlertWindow::addProgressBarComponent (double& progressValue)
  61168. {
  61169. ProgressBar* const pb = new ProgressBar (progressValue);
  61170. progressBars.add (pb);
  61171. allComps.add (pb);
  61172. addAndMakeVisible (pb);
  61173. updateLayout (false);
  61174. }
  61175. void AlertWindow::addCustomComponent (Component* const component)
  61176. {
  61177. customComps.add (component);
  61178. allComps.add (component);
  61179. addAndMakeVisible (component);
  61180. updateLayout (false);
  61181. }
  61182. int AlertWindow::getNumCustomComponents() const
  61183. {
  61184. return customComps.size();
  61185. }
  61186. Component* AlertWindow::getCustomComponent (const int index) const
  61187. {
  61188. return (Component*) customComps [index];
  61189. }
  61190. Component* AlertWindow::removeCustomComponent (const int index)
  61191. {
  61192. Component* const c = getCustomComponent (index);
  61193. if (c != 0)
  61194. {
  61195. customComps.removeValue (c);
  61196. allComps.removeValue (c);
  61197. removeChildComponent (c);
  61198. updateLayout (false);
  61199. }
  61200. return c;
  61201. }
  61202. void AlertWindow::paint (Graphics& g)
  61203. {
  61204. getLookAndFeel().drawAlertBox (g, *this, textArea, textLayout);
  61205. g.setColour (findColour (textColourId));
  61206. g.setFont (getLookAndFeel().getAlertWindowFont());
  61207. int i;
  61208. for (i = textBoxes.size(); --i >= 0;)
  61209. {
  61210. const TextEditor* const te = (TextEditor*) textBoxes[i];
  61211. g.drawFittedText (textboxNames[i],
  61212. te->getX(), te->getY() - 14,
  61213. te->getWidth(), 14,
  61214. Justification::centredLeft, 1);
  61215. }
  61216. for (i = comboBoxNames.size(); --i >= 0;)
  61217. {
  61218. const ComboBox* const cb = (ComboBox*) comboBoxes[i];
  61219. g.drawFittedText (comboBoxNames[i],
  61220. cb->getX(), cb->getY() - 14,
  61221. cb->getWidth(), 14,
  61222. Justification::centredLeft, 1);
  61223. }
  61224. for (i = customComps.size(); --i >= 0;)
  61225. {
  61226. const Component* const c = (Component*) customComps[i];
  61227. g.drawFittedText (c->getName(),
  61228. c->getX(), c->getY() - 14,
  61229. c->getWidth(), 14,
  61230. Justification::centredLeft, 1);
  61231. }
  61232. }
  61233. void AlertWindow::updateLayout (const bool onlyIncreaseSize)
  61234. {
  61235. const int titleH = 24;
  61236. const int iconWidth = 80;
  61237. const int wid = jmax (font.getStringWidth (text),
  61238. font.getStringWidth (getName()));
  61239. const int sw = (int) std::sqrt (font.getHeight() * wid);
  61240. int w = jmin (300 + sw * 2, (int) (getParentWidth() * 0.7f));
  61241. const int edgeGap = 10;
  61242. const int labelHeight = 18;
  61243. int iconSpace;
  61244. if (alertIconType == NoIcon)
  61245. {
  61246. textLayout.layout (w, Justification::horizontallyCentred, true);
  61247. iconSpace = 0;
  61248. }
  61249. else
  61250. {
  61251. textLayout.layout (w, Justification::left, true);
  61252. iconSpace = iconWidth;
  61253. }
  61254. w = jmax (350, textLayout.getWidth() + iconSpace + edgeGap * 4);
  61255. w = jmin (w, (int) (getParentWidth() * 0.7f));
  61256. const int textLayoutH = textLayout.getHeight();
  61257. const int textBottom = 16 + titleH + textLayoutH;
  61258. int h = textBottom;
  61259. int buttonW = 40;
  61260. int i;
  61261. for (i = 0; i < buttons.size(); ++i)
  61262. buttonW += 16 + ((const TextButton*) buttons[i])->getWidth();
  61263. w = jmax (buttonW, w);
  61264. h += (textBoxes.size() + comboBoxes.size() + progressBars.size()) * 50;
  61265. if (buttons.size() > 0)
  61266. h += 20 + ((TextButton*) buttons[0])->getHeight();
  61267. for (i = customComps.size(); --i >= 0;)
  61268. {
  61269. Component* c = (Component*) customComps[i];
  61270. w = jmax (w, (c->getWidth() * 100) / 80);
  61271. h += 10 + c->getHeight();
  61272. if (c->getName().isNotEmpty())
  61273. h += labelHeight;
  61274. }
  61275. for (i = textBlocks.size(); --i >= 0;)
  61276. {
  61277. const AlertTextComp* const ac = (AlertTextComp*) textBlocks[i];
  61278. w = jmax (w, ac->getPreferredWidth());
  61279. }
  61280. w = jmin (w, (int) (getParentWidth() * 0.7f));
  61281. for (i = textBlocks.size(); --i >= 0;)
  61282. {
  61283. AlertTextComp* const ac = (AlertTextComp*) textBlocks[i];
  61284. ac->updateLayout ((int) (w * 0.8f));
  61285. h += ac->getHeight() + 10;
  61286. }
  61287. h = jmin (getParentHeight() - 50, h);
  61288. if (onlyIncreaseSize)
  61289. {
  61290. w = jmax (w, getWidth());
  61291. h = jmax (h, getHeight());
  61292. }
  61293. if (! isVisible())
  61294. {
  61295. centreAroundComponent (associatedComponent, w, h);
  61296. }
  61297. else
  61298. {
  61299. const int cx = getX() + getWidth() / 2;
  61300. const int cy = getY() + getHeight() / 2;
  61301. setBounds (cx - w / 2,
  61302. cy - h / 2,
  61303. w, h);
  61304. }
  61305. textArea.setBounds (edgeGap, edgeGap, w - (edgeGap * 2), h - edgeGap);
  61306. const int spacer = 16;
  61307. int totalWidth = -spacer;
  61308. for (i = buttons.size(); --i >= 0;)
  61309. totalWidth += ((TextButton*) buttons[i])->getWidth() + spacer;
  61310. int x = (w - totalWidth) / 2;
  61311. int y = (int) (getHeight() * 0.95f);
  61312. for (i = 0; i < buttons.size(); ++i)
  61313. {
  61314. TextButton* const c = (TextButton*) buttons[i];
  61315. int ny = proportionOfHeight (0.95f) - c->getHeight();
  61316. c->setTopLeftPosition (x, ny);
  61317. if (ny < y)
  61318. y = ny;
  61319. x += c->getWidth() + spacer;
  61320. c->toFront (false);
  61321. }
  61322. y = textBottom;
  61323. for (i = 0; i < allComps.size(); ++i)
  61324. {
  61325. Component* const c = (Component*) allComps[i];
  61326. h = 22;
  61327. const int comboIndex = comboBoxes.indexOf (c);
  61328. if (comboIndex >= 0 && comboBoxNames [comboIndex].isNotEmpty())
  61329. y += labelHeight;
  61330. const int tbIndex = textBoxes.indexOf (c);
  61331. if (tbIndex >= 0 && textboxNames[tbIndex].isNotEmpty())
  61332. y += labelHeight;
  61333. if (customComps.contains (c))
  61334. {
  61335. if (c->getName().isNotEmpty())
  61336. y += labelHeight;
  61337. c->setTopLeftPosition (proportionOfWidth (0.1f), y);
  61338. h = c->getHeight();
  61339. }
  61340. else if (textBlocks.contains (c))
  61341. {
  61342. c->setTopLeftPosition ((getWidth() - c->getWidth()) / 2, y);
  61343. h = c->getHeight();
  61344. }
  61345. else
  61346. {
  61347. c->setBounds (proportionOfWidth (0.1f), y, proportionOfWidth (0.8f), h);
  61348. }
  61349. y += h + 10;
  61350. }
  61351. setWantsKeyboardFocus (getNumChildComponents() == 0);
  61352. }
  61353. bool AlertWindow::containsAnyExtraComponents() const
  61354. {
  61355. return textBoxes.size()
  61356. + comboBoxes.size()
  61357. + progressBars.size()
  61358. + customComps.size() > 0;
  61359. }
  61360. void AlertWindow::mouseDown (const MouseEvent&)
  61361. {
  61362. dragger.startDraggingComponent (this, &constrainer);
  61363. }
  61364. void AlertWindow::mouseDrag (const MouseEvent& e)
  61365. {
  61366. dragger.dragComponent (this, e);
  61367. }
  61368. bool AlertWindow::keyPressed (const KeyPress& key)
  61369. {
  61370. for (int i = buttons.size(); --i >= 0;)
  61371. {
  61372. TextButton* const b = (TextButton*) buttons[i];
  61373. if (b->isRegisteredForShortcut (key))
  61374. {
  61375. b->triggerClick();
  61376. return true;
  61377. }
  61378. }
  61379. if (key.isKeyCode (KeyPress::escapeKey) && buttons.size() == 0)
  61380. {
  61381. exitModalState (0);
  61382. return true;
  61383. }
  61384. else if (key.isKeyCode (KeyPress::returnKey) && buttons.size() == 1)
  61385. {
  61386. ((TextButton*) buttons.getFirst())->triggerClick();
  61387. return true;
  61388. }
  61389. return false;
  61390. }
  61391. void AlertWindow::lookAndFeelChanged()
  61392. {
  61393. const int newFlags = getLookAndFeel().getAlertBoxWindowFlags();
  61394. setUsingNativeTitleBar ((newFlags & ComponentPeer::windowHasTitleBar) != 0);
  61395. setDropShadowEnabled (isOpaque() && (newFlags & ComponentPeer::windowHasDropShadow) != 0);
  61396. }
  61397. int AlertWindow::getDesktopWindowStyleFlags() const
  61398. {
  61399. return getLookAndFeel().getAlertBoxWindowFlags();
  61400. }
  61401. struct AlertWindowInfo
  61402. {
  61403. String title, message, button1, button2, button3;
  61404. AlertWindow::AlertIconType iconType;
  61405. int numButtons;
  61406. Component::SafePointer<Component> associatedComponent;
  61407. int run() const
  61408. {
  61409. return (int) (pointer_sized_int)
  61410. MessageManager::getInstance()->callFunctionOnMessageThread (showCallback, (void*) this);
  61411. }
  61412. private:
  61413. int show() const
  61414. {
  61415. LookAndFeel& lf = associatedComponent != 0 ? associatedComponent->getLookAndFeel()
  61416. : LookAndFeel::getDefaultLookAndFeel();
  61417. ScopedPointer <Component> alertBox (lf.createAlertWindow (title, message, button1, button2, button3,
  61418. iconType, numButtons, associatedComponent));
  61419. jassert (alertBox != 0); // you have to return one of these!
  61420. return alertBox->runModalLoop();
  61421. }
  61422. static void* showCallback (void* userData)
  61423. {
  61424. return (void*) (pointer_sized_int) ((const AlertWindowInfo*) userData)->show();
  61425. }
  61426. };
  61427. void AlertWindow::showMessageBox (AlertIconType iconType,
  61428. const String& title,
  61429. const String& message,
  61430. const String& buttonText,
  61431. Component* associatedComponent)
  61432. {
  61433. AlertWindowInfo info;
  61434. info.title = title;
  61435. info.message = message;
  61436. info.button1 = buttonText.isEmpty() ? TRANS("ok") : buttonText;
  61437. info.iconType = iconType;
  61438. info.numButtons = 1;
  61439. info.associatedComponent = associatedComponent;
  61440. info.run();
  61441. }
  61442. bool AlertWindow::showOkCancelBox (AlertIconType iconType,
  61443. const String& title,
  61444. const String& message,
  61445. const String& button1Text,
  61446. const String& button2Text,
  61447. Component* associatedComponent)
  61448. {
  61449. AlertWindowInfo info;
  61450. info.title = title;
  61451. info.message = message;
  61452. info.button1 = button1Text.isEmpty() ? TRANS("ok") : button1Text;
  61453. info.button2 = button2Text.isEmpty() ? TRANS("cancel") : button2Text;
  61454. info.iconType = iconType;
  61455. info.numButtons = 2;
  61456. info.associatedComponent = associatedComponent;
  61457. return info.run() != 0;
  61458. }
  61459. int AlertWindow::showYesNoCancelBox (AlertIconType iconType,
  61460. const String& title,
  61461. const String& message,
  61462. const String& button1Text,
  61463. const String& button2Text,
  61464. const String& button3Text,
  61465. Component* associatedComponent)
  61466. {
  61467. AlertWindowInfo info;
  61468. info.title = title;
  61469. info.message = message;
  61470. info.button1 = button1Text.isEmpty() ? TRANS("yes") : button1Text;
  61471. info.button2 = button2Text.isEmpty() ? TRANS("no") : button2Text;
  61472. info.button3 = button3Text.isEmpty() ? TRANS("cancel") : button3Text;
  61473. info.iconType = iconType;
  61474. info.numButtons = 3;
  61475. info.associatedComponent = associatedComponent;
  61476. return info.run();
  61477. }
  61478. END_JUCE_NAMESPACE
  61479. /*** End of inlined file: juce_AlertWindow.cpp ***/
  61480. /*** Start of inlined file: juce_ComponentPeer.cpp ***/
  61481. BEGIN_JUCE_NAMESPACE
  61482. //#define JUCE_ENABLE_REPAINT_DEBUGGING 1
  61483. static VoidArray heavyweightPeers;
  61484. ComponentPeer::ComponentPeer (Component* const component_, const int styleFlags_)
  61485. : component (component_),
  61486. styleFlags (styleFlags_),
  61487. lastPaintTime (0),
  61488. constrainer (0),
  61489. lastDragAndDropCompUnderMouse (0),
  61490. fakeMouseMessageSent (false),
  61491. isWindowMinimised (false)
  61492. {
  61493. heavyweightPeers.add (this);
  61494. }
  61495. ComponentPeer::~ComponentPeer()
  61496. {
  61497. heavyweightPeers.removeValue (this);
  61498. Desktop::getInstance().triggerFocusCallback();
  61499. }
  61500. int ComponentPeer::getNumPeers() throw()
  61501. {
  61502. return heavyweightPeers.size();
  61503. }
  61504. ComponentPeer* ComponentPeer::getPeer (const int index) throw()
  61505. {
  61506. return (ComponentPeer*) heavyweightPeers [index];
  61507. }
  61508. ComponentPeer* ComponentPeer::getPeerFor (const Component* const component) throw()
  61509. {
  61510. for (int i = heavyweightPeers.size(); --i >= 0;)
  61511. {
  61512. ComponentPeer* const peer = (ComponentPeer*) heavyweightPeers.getUnchecked(i);
  61513. if (peer->getComponent() == component)
  61514. return peer;
  61515. }
  61516. return 0;
  61517. }
  61518. bool ComponentPeer::isValidPeer (const ComponentPeer* const peer) throw()
  61519. {
  61520. return heavyweightPeers.contains (const_cast <ComponentPeer*> (peer));
  61521. }
  61522. void ComponentPeer::updateCurrentModifiers() throw()
  61523. {
  61524. ModifierKeys::updateCurrentModifiers();
  61525. }
  61526. void ComponentPeer::handleMouseEvent (const int touchIndex, const Point<int>& positionWithinPeer, const ModifierKeys& newMods, const int64 time)
  61527. {
  61528. MouseInputSource* const mouse = Desktop::getInstance().getMouseSource (touchIndex);
  61529. jassert (mouse != 0); // not enough sources!
  61530. mouse->handleEvent (this, positionWithinPeer, time, newMods);
  61531. }
  61532. void ComponentPeer::handleMouseWheel (const int touchIndex, const Point<int>& positionWithinPeer, const int64 time, const float x, const float y)
  61533. {
  61534. MouseInputSource* const mouse = Desktop::getInstance().getMouseSource (touchIndex);
  61535. jassert (mouse != 0); // not enough sources!
  61536. mouse->handleWheel (this, positionWithinPeer, time, x, y);
  61537. }
  61538. void ComponentPeer::handlePaint (LowLevelGraphicsContext& contextToPaintTo)
  61539. {
  61540. Graphics g (&contextToPaintTo);
  61541. #if JUCE_ENABLE_REPAINT_DEBUGGING
  61542. g.saveState();
  61543. #endif
  61544. JUCE_TRY
  61545. {
  61546. component->paintEntireComponent (g);
  61547. }
  61548. JUCE_CATCH_EXCEPTION
  61549. #if JUCE_ENABLE_REPAINT_DEBUGGING
  61550. // enabling this code will fill all areas that get repainted with a colour overlay, to show
  61551. // clearly when things are being repainted.
  61552. {
  61553. g.restoreState();
  61554. g.fillAll (Colour ((uint8) Random::getSystemRandom().nextInt (255),
  61555. (uint8) Random::getSystemRandom().nextInt (255),
  61556. (uint8) Random::getSystemRandom().nextInt (255),
  61557. (uint8) 0x50));
  61558. }
  61559. #endif
  61560. }
  61561. bool ComponentPeer::handleKeyPress (const int keyCode,
  61562. const juce_wchar textCharacter)
  61563. {
  61564. updateCurrentModifiers();
  61565. Component* target = Component::getCurrentlyFocusedComponent() != 0
  61566. ? Component::getCurrentlyFocusedComponent()
  61567. : component;
  61568. if (target->isCurrentlyBlockedByAnotherModalComponent())
  61569. {
  61570. Component* const currentModalComp = Component::getCurrentlyModalComponent();
  61571. if (currentModalComp != 0)
  61572. target = currentModalComp;
  61573. }
  61574. const KeyPress keyInfo (keyCode,
  61575. ModifierKeys::getCurrentModifiers().getRawFlags()
  61576. & ModifierKeys::allKeyboardModifiers,
  61577. textCharacter);
  61578. bool keyWasUsed = false;
  61579. while (target != 0)
  61580. {
  61581. const Component::SafePointer<Component> deletionChecker (target);
  61582. if (target->keyListeners_ != 0)
  61583. {
  61584. for (int i = target->keyListeners_->size(); --i >= 0;)
  61585. {
  61586. keyWasUsed = ((KeyListener*) target->keyListeners_->getUnchecked(i))->keyPressed (keyInfo, target);
  61587. if (keyWasUsed || deletionChecker == 0)
  61588. return keyWasUsed;
  61589. i = jmin (i, target->keyListeners_->size());
  61590. }
  61591. }
  61592. keyWasUsed = target->keyPressed (keyInfo);
  61593. if (keyWasUsed || deletionChecker == 0)
  61594. break;
  61595. if (keyInfo.isKeyCode (KeyPress::tabKey) && Component::getCurrentlyFocusedComponent() != 0)
  61596. {
  61597. Component* const currentlyFocused = Component::getCurrentlyFocusedComponent();
  61598. currentlyFocused->moveKeyboardFocusToSibling (! keyInfo.getModifiers().isShiftDown());
  61599. keyWasUsed = (currentlyFocused != Component::getCurrentlyFocusedComponent());
  61600. break;
  61601. }
  61602. target = target->parentComponent_;
  61603. }
  61604. return keyWasUsed;
  61605. }
  61606. bool ComponentPeer::handleKeyUpOrDown (const bool isKeyDown)
  61607. {
  61608. updateCurrentModifiers();
  61609. Component* target = Component::getCurrentlyFocusedComponent() != 0
  61610. ? Component::getCurrentlyFocusedComponent()
  61611. : component;
  61612. if (target->isCurrentlyBlockedByAnotherModalComponent())
  61613. {
  61614. Component* const currentModalComp = Component::getCurrentlyModalComponent();
  61615. if (currentModalComp != 0)
  61616. target = currentModalComp;
  61617. }
  61618. bool keyWasUsed = false;
  61619. while (target != 0)
  61620. {
  61621. const Component::SafePointer<Component> deletionChecker (target);
  61622. keyWasUsed = target->keyStateChanged (isKeyDown);
  61623. if (keyWasUsed || deletionChecker == 0)
  61624. break;
  61625. if (target->keyListeners_ != 0)
  61626. {
  61627. for (int i = target->keyListeners_->size(); --i >= 0;)
  61628. {
  61629. keyWasUsed = ((KeyListener*) target->keyListeners_->getUnchecked(i))->keyStateChanged (isKeyDown, target);
  61630. if (keyWasUsed || deletionChecker == 0)
  61631. return keyWasUsed;
  61632. i = jmin (i, target->keyListeners_->size());
  61633. }
  61634. }
  61635. target = target->parentComponent_;
  61636. }
  61637. return keyWasUsed;
  61638. }
  61639. void ComponentPeer::handleModifierKeysChange()
  61640. {
  61641. updateCurrentModifiers();
  61642. Component* target = Desktop::getInstance().getMainMouseSource().getComponentUnderMouse();
  61643. if (target == 0)
  61644. target = Component::getCurrentlyFocusedComponent();
  61645. if (target == 0)
  61646. target = component;
  61647. if (target != 0)
  61648. target->internalModifierKeysChanged();
  61649. }
  61650. TextInputTarget* ComponentPeer::findCurrentTextInputTarget()
  61651. {
  61652. Component* const c = Component::getCurrentlyFocusedComponent();
  61653. if (component->isParentOf (c))
  61654. {
  61655. TextInputTarget* const ti = dynamic_cast <TextInputTarget*> (c);
  61656. if (ti != 0 && ti->isTextInputActive())
  61657. return ti;
  61658. }
  61659. return 0;
  61660. }
  61661. void ComponentPeer::handleBroughtToFront()
  61662. {
  61663. updateCurrentModifiers();
  61664. if (component != 0)
  61665. component->internalBroughtToFront();
  61666. }
  61667. void ComponentPeer::setConstrainer (ComponentBoundsConstrainer* const newConstrainer) throw()
  61668. {
  61669. constrainer = newConstrainer;
  61670. }
  61671. void ComponentPeer::handleMovedOrResized()
  61672. {
  61673. jassert (component->isValidComponent());
  61674. updateCurrentModifiers();
  61675. const bool nowMinimised = isMinimised();
  61676. if (component->flags.hasHeavyweightPeerFlag && ! nowMinimised)
  61677. {
  61678. const Component::SafePointer<Component> deletionChecker (component);
  61679. const Rectangle<int> newBounds (getBounds());
  61680. const bool wasMoved = (component->getPosition() != newBounds.getPosition());
  61681. const bool wasResized = (component->getWidth() != newBounds.getWidth() || component->getHeight() != newBounds.getHeight());
  61682. if (wasMoved || wasResized)
  61683. {
  61684. component->bounds_ = newBounds;
  61685. if (wasResized)
  61686. component->repaint();
  61687. component->sendMovedResizedMessages (wasMoved, wasResized);
  61688. if (deletionChecker == 0)
  61689. return;
  61690. }
  61691. }
  61692. if (isWindowMinimised != nowMinimised)
  61693. {
  61694. isWindowMinimised = nowMinimised;
  61695. component->minimisationStateChanged (nowMinimised);
  61696. component->sendVisibilityChangeMessage();
  61697. }
  61698. if (! isFullScreen())
  61699. lastNonFullscreenBounds = component->getBounds();
  61700. }
  61701. void ComponentPeer::handleFocusGain()
  61702. {
  61703. updateCurrentModifiers();
  61704. if (component->isParentOf (lastFocusedComponent))
  61705. {
  61706. Component::currentlyFocusedComponent = lastFocusedComponent;
  61707. Desktop::getInstance().triggerFocusCallback();
  61708. lastFocusedComponent->internalFocusGain (Component::focusChangedDirectly);
  61709. }
  61710. else
  61711. {
  61712. if (! component->isCurrentlyBlockedByAnotherModalComponent())
  61713. component->grabKeyboardFocus();
  61714. else
  61715. Component::bringModalComponentToFront();
  61716. }
  61717. }
  61718. void ComponentPeer::handleFocusLoss()
  61719. {
  61720. updateCurrentModifiers();
  61721. if (component->hasKeyboardFocus (true))
  61722. {
  61723. lastFocusedComponent = Component::currentlyFocusedComponent;
  61724. if (lastFocusedComponent != 0)
  61725. {
  61726. Component::currentlyFocusedComponent = 0;
  61727. Desktop::getInstance().triggerFocusCallback();
  61728. lastFocusedComponent->internalFocusLoss (Component::focusChangedByMouseClick);
  61729. }
  61730. }
  61731. }
  61732. Component* ComponentPeer::getLastFocusedSubcomponent() const throw()
  61733. {
  61734. return (component->isParentOf (lastFocusedComponent) && lastFocusedComponent->isShowing())
  61735. ? static_cast <Component*> (lastFocusedComponent)
  61736. : component;
  61737. }
  61738. void ComponentPeer::handleScreenSizeChange()
  61739. {
  61740. updateCurrentModifiers();
  61741. component->parentSizeChanged();
  61742. handleMovedOrResized();
  61743. }
  61744. void ComponentPeer::setNonFullScreenBounds (const Rectangle<int>& newBounds) throw()
  61745. {
  61746. lastNonFullscreenBounds = newBounds;
  61747. }
  61748. const Rectangle<int>& ComponentPeer::getNonFullScreenBounds() const throw()
  61749. {
  61750. return lastNonFullscreenBounds;
  61751. }
  61752. static FileDragAndDropTarget* findDragAndDropTarget (Component* c,
  61753. const StringArray& files,
  61754. FileDragAndDropTarget* const lastOne)
  61755. {
  61756. while (c != 0)
  61757. {
  61758. FileDragAndDropTarget* const t = dynamic_cast <FileDragAndDropTarget*> (c);
  61759. if (t != 0 && (t == lastOne || t->isInterestedInFileDrag (files)))
  61760. return t;
  61761. c = c->getParentComponent();
  61762. }
  61763. return 0;
  61764. }
  61765. void ComponentPeer::handleFileDragMove (const StringArray& files, const Point<int>& position)
  61766. {
  61767. updateCurrentModifiers();
  61768. FileDragAndDropTarget* lastTarget
  61769. = dynamic_cast<FileDragAndDropTarget*> (static_cast<Component*> (dragAndDropTargetComponent));
  61770. FileDragAndDropTarget* newTarget = 0;
  61771. Component* const compUnderMouse = component->getComponentAt (position);
  61772. if (compUnderMouse != lastDragAndDropCompUnderMouse)
  61773. {
  61774. lastDragAndDropCompUnderMouse = compUnderMouse;
  61775. newTarget = findDragAndDropTarget (compUnderMouse, files, lastTarget);
  61776. if (newTarget != lastTarget)
  61777. {
  61778. if (lastTarget != 0)
  61779. lastTarget->fileDragExit (files);
  61780. dragAndDropTargetComponent = 0;
  61781. if (newTarget != 0)
  61782. {
  61783. dragAndDropTargetComponent = dynamic_cast <Component*> (newTarget);
  61784. const Point<int> pos (component->relativePositionToOtherComponent (dragAndDropTargetComponent, position));
  61785. newTarget->fileDragEnter (files, pos.getX(), pos.getY());
  61786. }
  61787. }
  61788. }
  61789. else
  61790. {
  61791. newTarget = lastTarget;
  61792. }
  61793. if (newTarget != 0)
  61794. {
  61795. Component* const targetComp = dynamic_cast <Component*> (newTarget);
  61796. const Point<int> pos (component->relativePositionToOtherComponent (targetComp, position));
  61797. newTarget->fileDragMove (files, pos.getX(), pos.getY());
  61798. }
  61799. }
  61800. void ComponentPeer::handleFileDragExit (const StringArray& files)
  61801. {
  61802. handleFileDragMove (files, Point<int> (-1, -1));
  61803. jassert (dragAndDropTargetComponent == 0);
  61804. lastDragAndDropCompUnderMouse = 0;
  61805. }
  61806. void ComponentPeer::handleFileDragDrop (const StringArray& files, const Point<int>& position)
  61807. {
  61808. handleFileDragMove (files, position);
  61809. if (dragAndDropTargetComponent != 0)
  61810. {
  61811. FileDragAndDropTarget* const target
  61812. = dynamic_cast<FileDragAndDropTarget*> (static_cast<Component*> (dragAndDropTargetComponent));
  61813. dragAndDropTargetComponent = 0;
  61814. lastDragAndDropCompUnderMouse = 0;
  61815. if (target != 0)
  61816. {
  61817. Component* const targetComp = dynamic_cast <Component*> (target);
  61818. if (targetComp->isCurrentlyBlockedByAnotherModalComponent())
  61819. {
  61820. targetComp->internalModalInputAttempt();
  61821. if (targetComp->isCurrentlyBlockedByAnotherModalComponent())
  61822. return;
  61823. }
  61824. const Point<int> pos (component->relativePositionToOtherComponent (targetComp, position));
  61825. target->filesDropped (files, pos.getX(), pos.getY());
  61826. }
  61827. }
  61828. }
  61829. void ComponentPeer::handleUserClosingWindow()
  61830. {
  61831. updateCurrentModifiers();
  61832. component->userTriedToCloseWindow();
  61833. }
  61834. void ComponentPeer::bringModalComponentToFront()
  61835. {
  61836. Component::bringModalComponentToFront();
  61837. }
  61838. void ComponentPeer::clearMaskedRegion()
  61839. {
  61840. maskedRegion.clear();
  61841. }
  61842. void ComponentPeer::addMaskedRegion (int x, int y, int w, int h)
  61843. {
  61844. maskedRegion.add (x, y, w, h);
  61845. }
  61846. const StringArray ComponentPeer::getAvailableRenderingEngines() throw()
  61847. {
  61848. StringArray s;
  61849. s.add ("Software Renderer");
  61850. return s;
  61851. }
  61852. int ComponentPeer::getCurrentRenderingEngine() throw()
  61853. {
  61854. return 0;
  61855. }
  61856. void ComponentPeer::setCurrentRenderingEngine (int /*index*/) throw()
  61857. {
  61858. }
  61859. END_JUCE_NAMESPACE
  61860. /*** End of inlined file: juce_ComponentPeer.cpp ***/
  61861. /*** Start of inlined file: juce_DialogWindow.cpp ***/
  61862. BEGIN_JUCE_NAMESPACE
  61863. DialogWindow::DialogWindow (const String& name,
  61864. const Colour& backgroundColour_,
  61865. const bool escapeKeyTriggersCloseButton_,
  61866. const bool addToDesktop_)
  61867. : DocumentWindow (name, backgroundColour_, DocumentWindow::closeButton, addToDesktop_),
  61868. escapeKeyTriggersCloseButton (escapeKeyTriggersCloseButton_)
  61869. {
  61870. }
  61871. DialogWindow::~DialogWindow()
  61872. {
  61873. }
  61874. void DialogWindow::resized()
  61875. {
  61876. DocumentWindow::resized();
  61877. const KeyPress esc (KeyPress::escapeKey, 0, 0);
  61878. if (escapeKeyTriggersCloseButton
  61879. && getCloseButton() != 0
  61880. && ! getCloseButton()->isRegisteredForShortcut (esc))
  61881. {
  61882. getCloseButton()->addShortcut (esc);
  61883. }
  61884. }
  61885. class TempDialogWindow : public DialogWindow
  61886. {
  61887. public:
  61888. TempDialogWindow (const String& title, const Colour& colour, const bool escapeCloses)
  61889. : DialogWindow (title, colour, escapeCloses, true)
  61890. {
  61891. }
  61892. ~TempDialogWindow()
  61893. {
  61894. }
  61895. void closeButtonPressed()
  61896. {
  61897. setVisible (false);
  61898. }
  61899. private:
  61900. TempDialogWindow (const TempDialogWindow&);
  61901. TempDialogWindow& operator= (const TempDialogWindow&);
  61902. };
  61903. int DialogWindow::showModalDialog (const String& dialogTitle,
  61904. Component* contentComponent,
  61905. Component* componentToCentreAround,
  61906. const Colour& colour,
  61907. const bool escapeKeyTriggersCloseButton,
  61908. const bool shouldBeResizable,
  61909. const bool useBottomRightCornerResizer)
  61910. {
  61911. TempDialogWindow dw (dialogTitle, colour, escapeKeyTriggersCloseButton);
  61912. dw.setContentComponent (contentComponent, true, true);
  61913. dw.centreAroundComponent (componentToCentreAround, dw.getWidth(), dw.getHeight());
  61914. dw.setResizable (shouldBeResizable, useBottomRightCornerResizer);
  61915. const int result = dw.runModalLoop();
  61916. dw.setContentComponent (0, false);
  61917. return result;
  61918. }
  61919. END_JUCE_NAMESPACE
  61920. /*** End of inlined file: juce_DialogWindow.cpp ***/
  61921. /*** Start of inlined file: juce_DocumentWindow.cpp ***/
  61922. BEGIN_JUCE_NAMESPACE
  61923. class DocumentWindow::ButtonListenerProxy : public ButtonListener
  61924. {
  61925. public:
  61926. ButtonListenerProxy (DocumentWindow& owner_)
  61927. : owner (owner_)
  61928. {
  61929. }
  61930. void buttonClicked (Button* button)
  61931. {
  61932. if (button == owner.getMinimiseButton())
  61933. owner.minimiseButtonPressed();
  61934. else if (button == owner.getMaximiseButton())
  61935. owner.maximiseButtonPressed();
  61936. else if (button == owner.getCloseButton())
  61937. owner.closeButtonPressed();
  61938. }
  61939. juce_UseDebuggingNewOperator
  61940. private:
  61941. DocumentWindow& owner;
  61942. ButtonListenerProxy (const ButtonListenerProxy&);
  61943. ButtonListenerProxy& operator= (const ButtonListenerProxy&);
  61944. };
  61945. DocumentWindow::DocumentWindow (const String& title,
  61946. const Colour& backgroundColour,
  61947. const int requiredButtons_,
  61948. const bool addToDesktop_)
  61949. : ResizableWindow (title, backgroundColour, addToDesktop_),
  61950. titleBarHeight (26),
  61951. menuBarHeight (24),
  61952. requiredButtons (requiredButtons_),
  61953. #if JUCE_MAC
  61954. positionTitleBarButtonsOnLeft (true),
  61955. #else
  61956. positionTitleBarButtonsOnLeft (false),
  61957. #endif
  61958. drawTitleTextCentred (true),
  61959. menuBarModel (0)
  61960. {
  61961. setResizeLimits (128, 128, 32768, 32768);
  61962. lookAndFeelChanged();
  61963. }
  61964. DocumentWindow::~DocumentWindow()
  61965. {
  61966. for (int i = numElementsInArray (titleBarButtons); --i >= 0;)
  61967. titleBarButtons[i] = 0;
  61968. menuBar = 0;
  61969. }
  61970. void DocumentWindow::repaintTitleBar()
  61971. {
  61972. const Rectangle<int> titleBarArea (getTitleBarArea());
  61973. repaint (titleBarArea.getX(), titleBarArea.getY(),
  61974. titleBarArea.getWidth(), titleBarArea.getHeight());
  61975. }
  61976. void DocumentWindow::setName (const String& newName)
  61977. {
  61978. if (newName != getName())
  61979. {
  61980. Component::setName (newName);
  61981. repaintTitleBar();
  61982. }
  61983. }
  61984. void DocumentWindow::setIcon (const Image* imageToUse)
  61985. {
  61986. titleBarIcon = imageToUse != 0 ? imageToUse->createCopy() : 0;
  61987. repaintTitleBar();
  61988. }
  61989. void DocumentWindow::setTitleBarHeight (const int newHeight)
  61990. {
  61991. titleBarHeight = newHeight;
  61992. resized();
  61993. repaintTitleBar();
  61994. }
  61995. void DocumentWindow::setTitleBarButtonsRequired (const int requiredButtons_,
  61996. const bool positionTitleBarButtonsOnLeft_)
  61997. {
  61998. requiredButtons = requiredButtons_;
  61999. positionTitleBarButtonsOnLeft = positionTitleBarButtonsOnLeft_;
  62000. lookAndFeelChanged();
  62001. }
  62002. void DocumentWindow::setTitleBarTextCentred (const bool textShouldBeCentred)
  62003. {
  62004. drawTitleTextCentred = textShouldBeCentred;
  62005. repaintTitleBar();
  62006. }
  62007. void DocumentWindow::setMenuBar (MenuBarModel* menuBarModel_,
  62008. const int menuBarHeight_)
  62009. {
  62010. if (menuBarModel != menuBarModel_)
  62011. {
  62012. menuBar = 0;
  62013. menuBarModel = menuBarModel_;
  62014. menuBarHeight = (menuBarHeight_ > 0) ? menuBarHeight_
  62015. : getLookAndFeel().getDefaultMenuBarHeight();
  62016. if (menuBarModel != 0)
  62017. {
  62018. // (call the Component method directly to avoid the assertion in ResizableWindow)
  62019. Component::addAndMakeVisible (menuBar = new MenuBarComponent (menuBarModel));
  62020. menuBar->setEnabled (isActiveWindow());
  62021. }
  62022. resized();
  62023. }
  62024. }
  62025. void DocumentWindow::closeButtonPressed()
  62026. {
  62027. /* If you've got a close button, you have to override this method to get
  62028. rid of your window!
  62029. If the window is just a pop-up, you should override this method and make
  62030. it delete the window in whatever way is appropriate for your app. E.g. you
  62031. might just want to call "delete this".
  62032. If your app is centred around this window such that the whole app should quit when
  62033. the window is closed, then you will probably want to use this method as an opportunity
  62034. to call JUCEApplication::quit(), and leave the window to be deleted later by your
  62035. JUCEApplication::shutdown() method. (Doing it this way means that your window will
  62036. still get cleaned-up if the app is quit by some other means (e.g. a cmd-Q on the mac
  62037. or closing it via the taskbar icon on Windows).
  62038. */
  62039. jassertfalse
  62040. }
  62041. void DocumentWindow::minimiseButtonPressed()
  62042. {
  62043. setMinimised (true);
  62044. }
  62045. void DocumentWindow::maximiseButtonPressed()
  62046. {
  62047. setFullScreen (! isFullScreen());
  62048. }
  62049. void DocumentWindow::paint (Graphics& g)
  62050. {
  62051. ResizableWindow::paint (g);
  62052. if (resizableBorder == 0)
  62053. {
  62054. g.setColour (getBackgroundColour().overlaidWith (Colour (0x80000000)));
  62055. const BorderSize border (getBorderThickness());
  62056. g.fillRect (0, 0, getWidth(), border.getTop());
  62057. g.fillRect (0, border.getTop(), border.getLeft(), getHeight() - border.getTopAndBottom());
  62058. g.fillRect (getWidth() - border.getRight(), border.getTop(), border.getRight(), getHeight() - border.getTopAndBottom());
  62059. g.fillRect (0, getHeight() - border.getBottom(), getWidth(), border.getBottom());
  62060. }
  62061. const Rectangle<int> titleBarArea (getTitleBarArea());
  62062. g.setOrigin (titleBarArea.getX(), titleBarArea.getY());
  62063. g.reduceClipRegion (0, 0, titleBarArea.getWidth(), titleBarArea.getHeight());
  62064. int titleSpaceX1 = 6;
  62065. int titleSpaceX2 = titleBarArea.getWidth() - 6;
  62066. for (int i = 0; i < 3; ++i)
  62067. {
  62068. if (titleBarButtons[i] != 0)
  62069. {
  62070. if (positionTitleBarButtonsOnLeft)
  62071. titleSpaceX1 = jmax (titleSpaceX1, titleBarButtons[i]->getRight() + (getWidth() - titleBarButtons[i]->getRight()) / 8);
  62072. else
  62073. titleSpaceX2 = jmin (titleSpaceX2, titleBarButtons[i]->getX() - (titleBarButtons[i]->getX() / 8));
  62074. }
  62075. }
  62076. getLookAndFeel().drawDocumentWindowTitleBar (*this, g,
  62077. titleBarArea.getWidth(),
  62078. titleBarArea.getHeight(),
  62079. titleSpaceX1,
  62080. jmax (1, titleSpaceX2 - titleSpaceX1),
  62081. titleBarIcon,
  62082. ! drawTitleTextCentred);
  62083. }
  62084. void DocumentWindow::resized()
  62085. {
  62086. ResizableWindow::resized();
  62087. if (titleBarButtons[1] != 0)
  62088. titleBarButtons[1]->setToggleState (isFullScreen(), false);
  62089. const Rectangle<int> titleBarArea (getTitleBarArea());
  62090. getLookAndFeel()
  62091. .positionDocumentWindowButtons (*this,
  62092. titleBarArea.getX(), titleBarArea.getY(),
  62093. titleBarArea.getWidth(), titleBarArea.getHeight(),
  62094. titleBarButtons[0],
  62095. titleBarButtons[1],
  62096. titleBarButtons[2],
  62097. positionTitleBarButtonsOnLeft);
  62098. if (menuBar != 0)
  62099. menuBar->setBounds (titleBarArea.getX(), titleBarArea.getBottom(),
  62100. titleBarArea.getWidth(), menuBarHeight);
  62101. }
  62102. const BorderSize DocumentWindow::getBorderThickness()
  62103. {
  62104. return BorderSize ((isFullScreen() || isUsingNativeTitleBar())
  62105. ? 0 : (resizableBorder != 0 ? 4 : 1));
  62106. }
  62107. const BorderSize DocumentWindow::getContentComponentBorder()
  62108. {
  62109. BorderSize border (getBorderThickness());
  62110. border.setTop (border.getTop()
  62111. + (isUsingNativeTitleBar() ? 0 : titleBarHeight)
  62112. + (menuBar != 0 ? menuBarHeight : 0));
  62113. return border;
  62114. }
  62115. int DocumentWindow::getTitleBarHeight() const
  62116. {
  62117. return isUsingNativeTitleBar() ? 0 : jmin (titleBarHeight, getHeight() - 4);
  62118. }
  62119. const Rectangle<int> DocumentWindow::getTitleBarArea()
  62120. {
  62121. const BorderSize border (getBorderThickness());
  62122. return Rectangle<int> (border.getLeft(), border.getTop(),
  62123. getWidth() - border.getLeftAndRight(),
  62124. getTitleBarHeight());
  62125. }
  62126. Button* DocumentWindow::getCloseButton() const throw()
  62127. {
  62128. return titleBarButtons[2];
  62129. }
  62130. Button* DocumentWindow::getMinimiseButton() const throw()
  62131. {
  62132. return titleBarButtons[0];
  62133. }
  62134. Button* DocumentWindow::getMaximiseButton() const throw()
  62135. {
  62136. return titleBarButtons[1];
  62137. }
  62138. int DocumentWindow::getDesktopWindowStyleFlags() const
  62139. {
  62140. int styleFlags = ResizableWindow::getDesktopWindowStyleFlags();
  62141. if ((requiredButtons & minimiseButton) != 0)
  62142. styleFlags |= ComponentPeer::windowHasMinimiseButton;
  62143. if ((requiredButtons & maximiseButton) != 0)
  62144. styleFlags |= ComponentPeer::windowHasMaximiseButton;
  62145. if ((requiredButtons & closeButton) != 0)
  62146. styleFlags |= ComponentPeer::windowHasCloseButton;
  62147. return styleFlags;
  62148. }
  62149. void DocumentWindow::lookAndFeelChanged()
  62150. {
  62151. int i;
  62152. for (i = numElementsInArray (titleBarButtons); --i >= 0;)
  62153. titleBarButtons[i] = 0;
  62154. if (! isUsingNativeTitleBar())
  62155. {
  62156. titleBarButtons[0] = ((requiredButtons & minimiseButton) != 0)
  62157. ? getLookAndFeel().createDocumentWindowButton (minimiseButton) : 0;
  62158. titleBarButtons[1] = ((requiredButtons & maximiseButton) != 0)
  62159. ? getLookAndFeel().createDocumentWindowButton (maximiseButton) : 0;
  62160. titleBarButtons[2] = ((requiredButtons & closeButton) != 0)
  62161. ? getLookAndFeel().createDocumentWindowButton (closeButton) : 0;
  62162. for (i = 0; i < 3; ++i)
  62163. {
  62164. if (titleBarButtons[i] != 0)
  62165. {
  62166. if (buttonListener == 0)
  62167. buttonListener = new ButtonListenerProxy (*this);
  62168. titleBarButtons[i]->addButtonListener (buttonListener);
  62169. titleBarButtons[i]->setWantsKeyboardFocus (false);
  62170. // (call the Component method directly to avoid the assertion in ResizableWindow)
  62171. Component::addAndMakeVisible (titleBarButtons[i]);
  62172. }
  62173. }
  62174. if (getCloseButton() != 0)
  62175. {
  62176. #if JUCE_MAC
  62177. getCloseButton()->addShortcut (KeyPress ('w', ModifierKeys::commandModifier, 0));
  62178. #else
  62179. getCloseButton()->addShortcut (KeyPress (KeyPress::F4Key, ModifierKeys::altModifier, 0));
  62180. #endif
  62181. }
  62182. }
  62183. activeWindowStatusChanged();
  62184. ResizableWindow::lookAndFeelChanged();
  62185. }
  62186. void DocumentWindow::parentHierarchyChanged()
  62187. {
  62188. lookAndFeelChanged();
  62189. }
  62190. void DocumentWindow::activeWindowStatusChanged()
  62191. {
  62192. ResizableWindow::activeWindowStatusChanged();
  62193. for (int i = numElementsInArray (titleBarButtons); --i >= 0;)
  62194. if (titleBarButtons[i] != 0)
  62195. titleBarButtons[i]->setEnabled (isActiveWindow());
  62196. if (menuBar != 0)
  62197. menuBar->setEnabled (isActiveWindow());
  62198. }
  62199. void DocumentWindow::mouseDoubleClick (const MouseEvent& e)
  62200. {
  62201. if (getTitleBarArea().contains (e.x, e.y)
  62202. && getMaximiseButton() != 0)
  62203. {
  62204. getMaximiseButton()->triggerClick();
  62205. }
  62206. }
  62207. void DocumentWindow::userTriedToCloseWindow()
  62208. {
  62209. closeButtonPressed();
  62210. }
  62211. END_JUCE_NAMESPACE
  62212. /*** End of inlined file: juce_DocumentWindow.cpp ***/
  62213. /*** Start of inlined file: juce_ResizableWindow.cpp ***/
  62214. BEGIN_JUCE_NAMESPACE
  62215. ResizableWindow::ResizableWindow (const String& name,
  62216. const bool addToDesktop_)
  62217. : TopLevelWindow (name, addToDesktop_),
  62218. resizeToFitContent (false),
  62219. fullscreen (false),
  62220. lastNonFullScreenPos (50, 50, 256, 256),
  62221. constrainer (0)
  62222. #if JUCE_DEBUG
  62223. , hasBeenResized (false)
  62224. #endif
  62225. {
  62226. defaultConstrainer.setMinimumOnscreenAmounts (0x10000, 16, 24, 16);
  62227. lastNonFullScreenPos.setBounds (50, 50, 256, 256);
  62228. if (addToDesktop_)
  62229. Component::addToDesktop (getDesktopWindowStyleFlags());
  62230. }
  62231. ResizableWindow::ResizableWindow (const String& name,
  62232. const Colour& backgroundColour_,
  62233. const bool addToDesktop_)
  62234. : TopLevelWindow (name, addToDesktop_),
  62235. resizeToFitContent (false),
  62236. fullscreen (false),
  62237. lastNonFullScreenPos (50, 50, 256, 256),
  62238. constrainer (0)
  62239. #if JUCE_DEBUG
  62240. , hasBeenResized (false)
  62241. #endif
  62242. {
  62243. setBackgroundColour (backgroundColour_);
  62244. defaultConstrainer.setMinimumOnscreenAmounts (0x10000, 16, 24, 16);
  62245. if (addToDesktop_)
  62246. Component::addToDesktop (getDesktopWindowStyleFlags());
  62247. }
  62248. ResizableWindow::~ResizableWindow()
  62249. {
  62250. resizableCorner = 0;
  62251. resizableBorder = 0;
  62252. contentComponent = 0;
  62253. // have you been adding your own components directly to this window..? tut tut tut.
  62254. // Read the instructions for using a ResizableWindow!
  62255. jassert (getNumChildComponents() == 0);
  62256. }
  62257. int ResizableWindow::getDesktopWindowStyleFlags() const
  62258. {
  62259. int styleFlags = TopLevelWindow::getDesktopWindowStyleFlags();
  62260. if (isResizable() && (styleFlags & ComponentPeer::windowHasTitleBar) != 0)
  62261. styleFlags |= ComponentPeer::windowIsResizable;
  62262. return styleFlags;
  62263. }
  62264. void ResizableWindow::setContentComponent (Component* const newContentComponent,
  62265. const bool deleteOldOne,
  62266. const bool resizeToFit)
  62267. {
  62268. resizeToFitContent = resizeToFit;
  62269. if (newContentComponent != static_cast <Component*> (contentComponent))
  62270. {
  62271. if (! deleteOldOne)
  62272. removeChildComponent (contentComponent.release());
  62273. contentComponent = newContentComponent;
  62274. Component::addAndMakeVisible (contentComponent);
  62275. }
  62276. if (resizeToFit)
  62277. childBoundsChanged (contentComponent);
  62278. resized(); // must always be called to position the new content comp
  62279. }
  62280. void ResizableWindow::setContentComponentSize (int width, int height)
  62281. {
  62282. jassert (width > 0 && height > 0); // not a great idea to give it a zero size..
  62283. const BorderSize border (getContentComponentBorder());
  62284. setSize (width + border.getLeftAndRight(),
  62285. height + border.getTopAndBottom());
  62286. }
  62287. const BorderSize ResizableWindow::getBorderThickness()
  62288. {
  62289. return BorderSize (isUsingNativeTitleBar() ? 0 : ((resizableBorder != 0 && ! isFullScreen()) ? 5 : 3));
  62290. }
  62291. const BorderSize ResizableWindow::getContentComponentBorder()
  62292. {
  62293. return getBorderThickness();
  62294. }
  62295. void ResizableWindow::moved()
  62296. {
  62297. updateLastPos();
  62298. }
  62299. void ResizableWindow::visibilityChanged()
  62300. {
  62301. TopLevelWindow::visibilityChanged();
  62302. updateLastPos();
  62303. }
  62304. void ResizableWindow::resized()
  62305. {
  62306. if (resizableBorder != 0)
  62307. {
  62308. resizableBorder->setVisible (! isFullScreen());
  62309. resizableBorder->setBorderThickness (getBorderThickness());
  62310. resizableBorder->setSize (getWidth(), getHeight());
  62311. resizableBorder->toBack();
  62312. }
  62313. if (resizableCorner != 0)
  62314. {
  62315. resizableCorner->setVisible (! isFullScreen());
  62316. const int resizerSize = 18;
  62317. resizableCorner->setBounds (getWidth() - resizerSize,
  62318. getHeight() - resizerSize,
  62319. resizerSize, resizerSize);
  62320. }
  62321. if (contentComponent != 0)
  62322. contentComponent->setBoundsInset (getContentComponentBorder());
  62323. updateLastPos();
  62324. #if JUCE_DEBUG
  62325. hasBeenResized = true;
  62326. #endif
  62327. }
  62328. void ResizableWindow::childBoundsChanged (Component* child)
  62329. {
  62330. if ((child == contentComponent) && (child != 0) && resizeToFitContent)
  62331. {
  62332. // not going to look very good if this component has a zero size..
  62333. jassert (child->getWidth() > 0);
  62334. jassert (child->getHeight() > 0);
  62335. const BorderSize borders (getContentComponentBorder());
  62336. setSize (child->getWidth() + borders.getLeftAndRight(),
  62337. child->getHeight() + borders.getTopAndBottom());
  62338. }
  62339. }
  62340. void ResizableWindow::activeWindowStatusChanged()
  62341. {
  62342. const BorderSize borders (getContentComponentBorder());
  62343. repaint (0, 0, getWidth(), borders.getTop());
  62344. repaint (0, borders.getTop(), borders.getLeft(), getHeight() - borders.getBottom() - borders.getTop());
  62345. repaint (0, getHeight() - borders.getBottom(), getWidth(), borders.getBottom());
  62346. repaint (getWidth() - borders.getRight(), borders.getTop(), borders.getRight(), getHeight() - borders.getBottom() - borders.getTop());
  62347. }
  62348. void ResizableWindow::setResizable (const bool shouldBeResizable,
  62349. const bool useBottomRightCornerResizer)
  62350. {
  62351. if (shouldBeResizable)
  62352. {
  62353. if (useBottomRightCornerResizer)
  62354. {
  62355. resizableBorder = 0;
  62356. if (resizableCorner == 0)
  62357. {
  62358. Component::addChildComponent (resizableCorner = new ResizableCornerComponent (this, constrainer));
  62359. resizableCorner->setAlwaysOnTop (true);
  62360. }
  62361. }
  62362. else
  62363. {
  62364. resizableCorner = 0;
  62365. if (resizableBorder == 0)
  62366. Component::addChildComponent (resizableBorder = new ResizableBorderComponent (this, constrainer));
  62367. }
  62368. }
  62369. else
  62370. {
  62371. resizableCorner = 0;
  62372. resizableBorder = 0;
  62373. }
  62374. if (isUsingNativeTitleBar())
  62375. recreateDesktopWindow();
  62376. childBoundsChanged (contentComponent);
  62377. resized();
  62378. }
  62379. bool ResizableWindow::isResizable() const throw()
  62380. {
  62381. return resizableCorner != 0
  62382. || resizableBorder != 0;
  62383. }
  62384. void ResizableWindow::setResizeLimits (const int newMinimumWidth,
  62385. const int newMinimumHeight,
  62386. const int newMaximumWidth,
  62387. const int newMaximumHeight) throw()
  62388. {
  62389. // if you've set up a custom constrainer then these settings won't have any effect..
  62390. jassert (constrainer == &defaultConstrainer || constrainer == 0);
  62391. if (constrainer == 0)
  62392. setConstrainer (&defaultConstrainer);
  62393. defaultConstrainer.setSizeLimits (newMinimumWidth, newMinimumHeight,
  62394. newMaximumWidth, newMaximumHeight);
  62395. setBoundsConstrained (getBounds());
  62396. }
  62397. void ResizableWindow::setConstrainer (ComponentBoundsConstrainer* newConstrainer)
  62398. {
  62399. if (constrainer != newConstrainer)
  62400. {
  62401. constrainer = newConstrainer;
  62402. const bool useBottomRightCornerResizer = resizableCorner != 0;
  62403. const bool shouldBeResizable = useBottomRightCornerResizer || resizableBorder != 0;
  62404. resizableCorner = 0;
  62405. resizableBorder = 0;
  62406. setResizable (shouldBeResizable, useBottomRightCornerResizer);
  62407. ComponentPeer* const peer = getPeer();
  62408. if (peer != 0)
  62409. peer->setConstrainer (newConstrainer);
  62410. }
  62411. }
  62412. void ResizableWindow::setBoundsConstrained (const Rectangle<int>& bounds)
  62413. {
  62414. if (constrainer != 0)
  62415. constrainer->setBoundsForComponent (this, bounds, false, false, false, false);
  62416. else
  62417. setBounds (bounds);
  62418. }
  62419. void ResizableWindow::paint (Graphics& g)
  62420. {
  62421. getLookAndFeel().fillResizableWindowBackground (g, getWidth(), getHeight(),
  62422. getBorderThickness(), *this);
  62423. if (! isFullScreen())
  62424. {
  62425. getLookAndFeel().drawResizableWindowBorder (g, getWidth(), getHeight(),
  62426. getBorderThickness(), *this);
  62427. }
  62428. #if JUCE_DEBUG
  62429. /* If this fails, then you've probably written a subclass with a resized()
  62430. callback but forgotten to make it call its parent class's resized() method.
  62431. It's important when you override methods like resized(), moved(),
  62432. etc., that you make sure the base class methods also get called.
  62433. Of course you shouldn't really be overriding ResizableWindow::resized() anyway,
  62434. because your content should all be inside the content component - and it's the
  62435. content component's resized() method that you should be using to do your
  62436. layout.
  62437. */
  62438. jassert (hasBeenResized || (getWidth() == 0 && getHeight() == 0));
  62439. #endif
  62440. }
  62441. void ResizableWindow::lookAndFeelChanged()
  62442. {
  62443. resized();
  62444. if (isOnDesktop())
  62445. {
  62446. Component::addToDesktop (getDesktopWindowStyleFlags());
  62447. ComponentPeer* const peer = getPeer();
  62448. if (peer != 0)
  62449. peer->setConstrainer (constrainer);
  62450. }
  62451. }
  62452. const Colour ResizableWindow::getBackgroundColour() const throw()
  62453. {
  62454. return findColour (backgroundColourId, false);
  62455. }
  62456. void ResizableWindow::setBackgroundColour (const Colour& newColour)
  62457. {
  62458. Colour backgroundColour (newColour);
  62459. if (! Desktop::canUseSemiTransparentWindows())
  62460. backgroundColour = newColour.withAlpha (1.0f);
  62461. setColour (backgroundColourId, backgroundColour);
  62462. setOpaque (backgroundColour.isOpaque());
  62463. repaint();
  62464. }
  62465. bool ResizableWindow::isFullScreen() const
  62466. {
  62467. if (isOnDesktop())
  62468. {
  62469. ComponentPeer* const peer = getPeer();
  62470. return peer != 0 && peer->isFullScreen();
  62471. }
  62472. return fullscreen;
  62473. }
  62474. void ResizableWindow::setFullScreen (const bool shouldBeFullScreen)
  62475. {
  62476. if (shouldBeFullScreen != isFullScreen())
  62477. {
  62478. updateLastPos();
  62479. fullscreen = shouldBeFullScreen;
  62480. if (isOnDesktop())
  62481. {
  62482. ComponentPeer* const peer = getPeer();
  62483. if (peer != 0)
  62484. {
  62485. // keep a copy of this intact in case the real one gets messed-up while we're un-maximising
  62486. const Rectangle<int> lastPos (lastNonFullScreenPos);
  62487. peer->setFullScreen (shouldBeFullScreen);
  62488. if (! shouldBeFullScreen)
  62489. setBounds (lastPos);
  62490. }
  62491. else
  62492. {
  62493. jassertfalse
  62494. }
  62495. }
  62496. else
  62497. {
  62498. if (shouldBeFullScreen)
  62499. setBounds (0, 0, getParentWidth(), getParentHeight());
  62500. else
  62501. setBounds (lastNonFullScreenPos);
  62502. }
  62503. resized();
  62504. }
  62505. }
  62506. bool ResizableWindow::isMinimised() const
  62507. {
  62508. ComponentPeer* const peer = getPeer();
  62509. return (peer != 0) && peer->isMinimised();
  62510. }
  62511. void ResizableWindow::setMinimised (const bool shouldMinimise)
  62512. {
  62513. if (shouldMinimise != isMinimised())
  62514. {
  62515. ComponentPeer* const peer = getPeer();
  62516. if (peer != 0)
  62517. {
  62518. updateLastPos();
  62519. peer->setMinimised (shouldMinimise);
  62520. }
  62521. else
  62522. {
  62523. jassertfalse
  62524. }
  62525. }
  62526. }
  62527. void ResizableWindow::updateLastPos()
  62528. {
  62529. if (isShowing() && ! (isFullScreen() || isMinimised()))
  62530. {
  62531. lastNonFullScreenPos = getBounds();
  62532. }
  62533. }
  62534. void ResizableWindow::parentSizeChanged()
  62535. {
  62536. if (isFullScreen() && getParentComponent() != 0)
  62537. {
  62538. setBounds (0, 0, getParentWidth(), getParentHeight());
  62539. }
  62540. }
  62541. const String ResizableWindow::getWindowStateAsString()
  62542. {
  62543. updateLastPos();
  62544. return (isFullScreen() ? "fs " : "") + lastNonFullScreenPos.toString();
  62545. }
  62546. bool ResizableWindow::restoreWindowStateFromString (const String& s)
  62547. {
  62548. StringArray tokens;
  62549. tokens.addTokens (s, false);
  62550. tokens.removeEmptyStrings();
  62551. tokens.trim();
  62552. const bool fs = tokens[0].startsWithIgnoreCase ("fs");
  62553. const int firstCoord = fs ? 1 : 0;
  62554. if (tokens.size() != firstCoord + 4)
  62555. return false;
  62556. Rectangle<int> newPos (tokens[firstCoord].getIntValue(),
  62557. tokens[firstCoord + 1].getIntValue(),
  62558. tokens[firstCoord + 2].getIntValue(),
  62559. tokens[firstCoord + 3].getIntValue());
  62560. if (newPos.isEmpty())
  62561. return false;
  62562. const Rectangle<int> screen (Desktop::getInstance().getMonitorAreaContaining (newPos.getCentre()));
  62563. ComponentPeer* const peer = isOnDesktop() ? getPeer() : 0;
  62564. if (peer != 0)
  62565. peer->getFrameSize().addTo (newPos);
  62566. if (! screen.contains (newPos))
  62567. {
  62568. newPos.setSize (jmin (newPos.getWidth(), screen.getWidth()),
  62569. jmin (newPos.getHeight(), screen.getHeight()));
  62570. newPos.setPosition (jlimit (screen.getX(), screen.getRight() - newPos.getWidth(), newPos.getX()),
  62571. jlimit (screen.getY(), screen.getBottom() - newPos.getHeight(), newPos.getY()));
  62572. }
  62573. if (peer != 0)
  62574. {
  62575. peer->getFrameSize().subtractFrom (newPos);
  62576. peer->setNonFullScreenBounds (newPos);
  62577. }
  62578. lastNonFullScreenPos = newPos;
  62579. setFullScreen (fs);
  62580. if (! fs)
  62581. setBoundsConstrained (newPos);
  62582. return true;
  62583. }
  62584. void ResizableWindow::mouseDown (const MouseEvent&)
  62585. {
  62586. if (! isFullScreen())
  62587. dragger.startDraggingComponent (this, constrainer);
  62588. }
  62589. void ResizableWindow::mouseDrag (const MouseEvent& e)
  62590. {
  62591. if (! isFullScreen())
  62592. dragger.dragComponent (this, e);
  62593. }
  62594. #if JUCE_DEBUG
  62595. void ResizableWindow::addChildComponent (Component* const child, int zOrder)
  62596. {
  62597. /* Agh! You shouldn't add components directly to a ResizableWindow - this class
  62598. manages its child components automatically, and if you add your own it'll cause
  62599. trouble. Instead, use setContentComponent() to give it a component which
  62600. will be automatically resized and kept in the right place - then you can add
  62601. subcomponents to the content comp. See the notes for the ResizableWindow class
  62602. for more info.
  62603. If you really know what you're doing and want to avoid this assertion, just call
  62604. Component::addChildComponent directly.
  62605. */
  62606. jassertfalse
  62607. Component::addChildComponent (child, zOrder);
  62608. }
  62609. void ResizableWindow::addAndMakeVisible (Component* const child, int zOrder)
  62610. {
  62611. /* Agh! You shouldn't add components directly to a ResizableWindow - this class
  62612. manages its child components automatically, and if you add your own it'll cause
  62613. trouble. Instead, use setContentComponent() to give it a component which
  62614. will be automatically resized and kept in the right place - then you can add
  62615. subcomponents to the content comp. See the notes for the ResizableWindow class
  62616. for more info.
  62617. If you really know what you're doing and want to avoid this assertion, just call
  62618. Component::addAndMakeVisible directly.
  62619. */
  62620. jassertfalse
  62621. Component::addAndMakeVisible (child, zOrder);
  62622. }
  62623. #endif
  62624. END_JUCE_NAMESPACE
  62625. /*** End of inlined file: juce_ResizableWindow.cpp ***/
  62626. /*** Start of inlined file: juce_SplashScreen.cpp ***/
  62627. BEGIN_JUCE_NAMESPACE
  62628. SplashScreen::SplashScreen()
  62629. : backgroundImage (0)
  62630. {
  62631. setOpaque (true);
  62632. }
  62633. SplashScreen::~SplashScreen()
  62634. {
  62635. ImageCache::releaseOrDelete (backgroundImage);
  62636. }
  62637. void SplashScreen::show (const String& title,
  62638. Image* const backgroundImage_,
  62639. const int minimumTimeToDisplayFor,
  62640. const bool useDropShadow,
  62641. const bool removeOnMouseClick)
  62642. {
  62643. backgroundImage = backgroundImage_;
  62644. jassert (backgroundImage_ != 0);
  62645. if (backgroundImage_ != 0)
  62646. {
  62647. setOpaque (! backgroundImage_->hasAlphaChannel());
  62648. show (title,
  62649. backgroundImage_->getWidth(),
  62650. backgroundImage_->getHeight(),
  62651. minimumTimeToDisplayFor,
  62652. useDropShadow,
  62653. removeOnMouseClick);
  62654. }
  62655. }
  62656. void SplashScreen::show (const String& title,
  62657. const int width,
  62658. const int height,
  62659. const int minimumTimeToDisplayFor,
  62660. const bool useDropShadow,
  62661. const bool removeOnMouseClick)
  62662. {
  62663. setName (title);
  62664. setAlwaysOnTop (true);
  62665. setVisible (true);
  62666. centreWithSize (width, height);
  62667. addToDesktop (useDropShadow ? ComponentPeer::windowHasDropShadow : 0);
  62668. toFront (false);
  62669. MessageManager::getInstance()->runDispatchLoopUntil (300);
  62670. repaint();
  62671. originalClickCounter = removeOnMouseClick
  62672. ? Desktop::getMouseButtonClickCounter()
  62673. : std::numeric_limits<int>::max();
  62674. earliestTimeToDelete = Time::getCurrentTime() + RelativeTime::milliseconds (minimumTimeToDisplayFor);
  62675. startTimer (50);
  62676. }
  62677. void SplashScreen::paint (Graphics& g)
  62678. {
  62679. if (backgroundImage != 0)
  62680. {
  62681. g.setOpacity (1.0f);
  62682. g.drawImage (backgroundImage,
  62683. 0, 0, getWidth(), getHeight(),
  62684. 0, 0, backgroundImage->getWidth(), backgroundImage->getHeight());
  62685. }
  62686. }
  62687. void SplashScreen::timerCallback()
  62688. {
  62689. if (Time::getCurrentTime() > earliestTimeToDelete
  62690. || Desktop::getMouseButtonClickCounter() > originalClickCounter)
  62691. {
  62692. delete this;
  62693. }
  62694. }
  62695. END_JUCE_NAMESPACE
  62696. /*** End of inlined file: juce_SplashScreen.cpp ***/
  62697. /*** Start of inlined file: juce_ThreadWithProgressWindow.cpp ***/
  62698. BEGIN_JUCE_NAMESPACE
  62699. ThreadWithProgressWindow::ThreadWithProgressWindow (const String& title,
  62700. const bool hasProgressBar,
  62701. const bool hasCancelButton,
  62702. const int timeOutMsWhenCancelling_,
  62703. const String& cancelButtonText)
  62704. : Thread ("Juce Progress Window"),
  62705. progress (0.0),
  62706. timeOutMsWhenCancelling (timeOutMsWhenCancelling_)
  62707. {
  62708. alertWindow = LookAndFeel::getDefaultLookAndFeel()
  62709. .createAlertWindow (title, String::empty, cancelButtonText,
  62710. String::empty, String::empty,
  62711. AlertWindow::NoIcon, hasCancelButton ? 1 : 0, 0);
  62712. if (hasProgressBar)
  62713. alertWindow->addProgressBarComponent (progress);
  62714. }
  62715. ThreadWithProgressWindow::~ThreadWithProgressWindow()
  62716. {
  62717. stopThread (timeOutMsWhenCancelling);
  62718. }
  62719. bool ThreadWithProgressWindow::runThread (const int priority)
  62720. {
  62721. startThread (priority);
  62722. startTimer (100);
  62723. {
  62724. const ScopedLock sl (messageLock);
  62725. alertWindow->setMessage (message);
  62726. }
  62727. const bool finishedNaturally = alertWindow->runModalLoop() != 0;
  62728. stopThread (timeOutMsWhenCancelling);
  62729. alertWindow->setVisible (false);
  62730. return finishedNaturally;
  62731. }
  62732. void ThreadWithProgressWindow::setProgress (const double newProgress)
  62733. {
  62734. progress = newProgress;
  62735. }
  62736. void ThreadWithProgressWindow::setStatusMessage (const String& newStatusMessage)
  62737. {
  62738. const ScopedLock sl (messageLock);
  62739. message = newStatusMessage;
  62740. }
  62741. void ThreadWithProgressWindow::timerCallback()
  62742. {
  62743. if (! isThreadRunning())
  62744. {
  62745. // thread has finished normally..
  62746. alertWindow->exitModalState (1);
  62747. alertWindow->setVisible (false);
  62748. }
  62749. else
  62750. {
  62751. const ScopedLock sl (messageLock);
  62752. alertWindow->setMessage (message);
  62753. }
  62754. }
  62755. END_JUCE_NAMESPACE
  62756. /*** End of inlined file: juce_ThreadWithProgressWindow.cpp ***/
  62757. /*** Start of inlined file: juce_TooltipWindow.cpp ***/
  62758. BEGIN_JUCE_NAMESPACE
  62759. TooltipWindow::TooltipWindow (Component* const parentComponent,
  62760. const int millisecondsBeforeTipAppears_)
  62761. : Component ("tooltip"),
  62762. millisecondsBeforeTipAppears (millisecondsBeforeTipAppears_),
  62763. mouseClicks (0),
  62764. lastHideTime (0),
  62765. lastComponentUnderMouse (0),
  62766. changedCompsSinceShown (true)
  62767. {
  62768. if (Desktop::getInstance().getMainMouseSource().canHover())
  62769. startTimer (123);
  62770. setAlwaysOnTop (true);
  62771. setOpaque (true);
  62772. if (parentComponent != 0)
  62773. parentComponent->addChildComponent (this);
  62774. }
  62775. TooltipWindow::~TooltipWindow()
  62776. {
  62777. hide();
  62778. }
  62779. void TooltipWindow::setMillisecondsBeforeTipAppears (const int newTimeMs) throw()
  62780. {
  62781. millisecondsBeforeTipAppears = newTimeMs;
  62782. }
  62783. void TooltipWindow::paint (Graphics& g)
  62784. {
  62785. getLookAndFeel().drawTooltip (g, tipShowing, getWidth(), getHeight());
  62786. }
  62787. void TooltipWindow::mouseEnter (const MouseEvent&)
  62788. {
  62789. hide();
  62790. }
  62791. void TooltipWindow::showFor (const String& tip)
  62792. {
  62793. jassert (tip.isNotEmpty());
  62794. tipShowing = tip;
  62795. Point<int> mousePos (Desktop::getMousePosition());
  62796. if (getParentComponent() != 0)
  62797. mousePos = getParentComponent()->globalPositionToRelative (mousePos);
  62798. int x, y, w, h;
  62799. getLookAndFeel().getTooltipSize (tip, w, h);
  62800. if (mousePos.getX() > getParentWidth() / 2)
  62801. x = mousePos.getX() - (w + 12);
  62802. else
  62803. x = mousePos.getX() + 24;
  62804. if (mousePos.getY() > getParentHeight() / 2)
  62805. y = mousePos.getY() - (h + 6);
  62806. else
  62807. y = mousePos.getY() + 6;
  62808. setBounds (x, y, w, h);
  62809. setVisible (true);
  62810. if (getParentComponent() == 0)
  62811. {
  62812. addToDesktop (ComponentPeer::windowHasDropShadow
  62813. | ComponentPeer::windowIsTemporary
  62814. | ComponentPeer::windowIgnoresKeyPresses);
  62815. }
  62816. toFront (false);
  62817. }
  62818. const String TooltipWindow::getTipFor (Component* const c)
  62819. {
  62820. if (c != 0
  62821. && Process::isForegroundProcess()
  62822. && ! Component::isMouseButtonDownAnywhere())
  62823. {
  62824. TooltipClient* const ttc = dynamic_cast <TooltipClient*> (c);
  62825. if (ttc != 0 && ! c->isCurrentlyBlockedByAnotherModalComponent())
  62826. return ttc->getTooltip();
  62827. }
  62828. return String::empty;
  62829. }
  62830. void TooltipWindow::hide()
  62831. {
  62832. tipShowing = String::empty;
  62833. removeFromDesktop();
  62834. setVisible (false);
  62835. }
  62836. void TooltipWindow::timerCallback()
  62837. {
  62838. const unsigned int now = Time::getApproximateMillisecondCounter();
  62839. Component* const newComp = Desktop::getInstance().getMainMouseSource().getComponentUnderMouse();
  62840. const String newTip (getTipFor (newComp));
  62841. const bool tipChanged = (newTip != lastTipUnderMouse || newComp != lastComponentUnderMouse);
  62842. lastComponentUnderMouse = newComp;
  62843. lastTipUnderMouse = newTip;
  62844. const int clickCount = Desktop::getInstance().getMouseButtonClickCounter();
  62845. const bool mouseWasClicked = clickCount > mouseClicks;
  62846. mouseClicks = clickCount;
  62847. const Point<int> mousePos (Desktop::getMousePosition());
  62848. const bool mouseMovedQuickly = mousePos.getDistanceFrom (lastMousePos) > 12;
  62849. lastMousePos = mousePos;
  62850. if (tipChanged || mouseWasClicked || mouseMovedQuickly)
  62851. lastCompChangeTime = now;
  62852. if (isVisible() || now < lastHideTime + 500)
  62853. {
  62854. // if a tip is currently visible (or has just disappeared), update to a new one
  62855. // immediately if needed..
  62856. if (newComp == 0 || mouseWasClicked || newTip.isEmpty())
  62857. {
  62858. if (isVisible())
  62859. {
  62860. lastHideTime = now;
  62861. hide();
  62862. }
  62863. }
  62864. else if (tipChanged)
  62865. {
  62866. showFor (newTip);
  62867. }
  62868. }
  62869. else
  62870. {
  62871. // if there isn't currently a tip, but one is needed, only let it
  62872. // appear after a timeout..
  62873. if (newTip.isNotEmpty()
  62874. && newTip != tipShowing
  62875. && now > lastCompChangeTime + millisecondsBeforeTipAppears)
  62876. {
  62877. showFor (newTip);
  62878. }
  62879. }
  62880. }
  62881. END_JUCE_NAMESPACE
  62882. /*** End of inlined file: juce_TooltipWindow.cpp ***/
  62883. /*** Start of inlined file: juce_TopLevelWindow.cpp ***/
  62884. BEGIN_JUCE_NAMESPACE
  62885. /** Keeps track of the active top level window.
  62886. */
  62887. class TopLevelWindowManager : public Timer,
  62888. public DeletedAtShutdown
  62889. {
  62890. public:
  62891. TopLevelWindowManager()
  62892. : currentActive (0)
  62893. {
  62894. }
  62895. ~TopLevelWindowManager()
  62896. {
  62897. clearSingletonInstance();
  62898. }
  62899. juce_DeclareSingleton_SingleThreaded_Minimal (TopLevelWindowManager)
  62900. void timerCallback()
  62901. {
  62902. startTimer (jmin (1731, getTimerInterval() * 2));
  62903. TopLevelWindow* active = 0;
  62904. if (Process::isForegroundProcess())
  62905. {
  62906. active = currentActive;
  62907. Component* const c = Component::getCurrentlyFocusedComponent();
  62908. TopLevelWindow* tlw = dynamic_cast <TopLevelWindow*> (c);
  62909. if (tlw == 0 && c != 0)
  62910. // (unable to use the syntax findParentComponentOfClass <TopLevelWindow> () because of a VC6 compiler bug)
  62911. tlw = c->findParentComponentOfClass ((TopLevelWindow*) 0);
  62912. if (tlw != 0)
  62913. active = tlw;
  62914. }
  62915. if (active != currentActive)
  62916. {
  62917. currentActive = active;
  62918. for (int i = windows.size(); --i >= 0;)
  62919. {
  62920. TopLevelWindow* const tlw = (TopLevelWindow*) windows.getUnchecked (i);
  62921. tlw->setWindowActive (isWindowActive (tlw));
  62922. i = jmin (i, windows.size() - 1);
  62923. }
  62924. Desktop::getInstance().triggerFocusCallback();
  62925. }
  62926. }
  62927. bool addWindow (TopLevelWindow* const w)
  62928. {
  62929. windows.add (w);
  62930. startTimer (10);
  62931. return isWindowActive (w);
  62932. }
  62933. void removeWindow (TopLevelWindow* const w)
  62934. {
  62935. startTimer (10);
  62936. if (currentActive == w)
  62937. currentActive = 0;
  62938. windows.removeValue (w);
  62939. if (windows.size() == 0)
  62940. deleteInstance();
  62941. }
  62942. VoidArray windows;
  62943. private:
  62944. TopLevelWindow* currentActive;
  62945. bool isWindowActive (TopLevelWindow* const tlw) const
  62946. {
  62947. return (tlw == currentActive
  62948. || tlw->isParentOf (currentActive)
  62949. || tlw->hasKeyboardFocus (true))
  62950. && tlw->isShowing();
  62951. }
  62952. TopLevelWindowManager (const TopLevelWindowManager&);
  62953. TopLevelWindowManager& operator= (const TopLevelWindowManager&);
  62954. };
  62955. juce_ImplementSingleton_SingleThreaded (TopLevelWindowManager)
  62956. void juce_CheckCurrentlyFocusedTopLevelWindow()
  62957. {
  62958. if (TopLevelWindowManager::getInstanceWithoutCreating() != 0)
  62959. TopLevelWindowManager::getInstanceWithoutCreating()->startTimer (20);
  62960. }
  62961. TopLevelWindow::TopLevelWindow (const String& name,
  62962. const bool addToDesktop_)
  62963. : Component (name),
  62964. useDropShadow (true),
  62965. useNativeTitleBar (false),
  62966. windowIsActive_ (false)
  62967. {
  62968. setOpaque (true);
  62969. if (addToDesktop_)
  62970. Component::addToDesktop (getDesktopWindowStyleFlags());
  62971. else
  62972. setDropShadowEnabled (true);
  62973. setWantsKeyboardFocus (true);
  62974. setBroughtToFrontOnMouseClick (true);
  62975. windowIsActive_ = TopLevelWindowManager::getInstance()->addWindow (this);
  62976. }
  62977. TopLevelWindow::~TopLevelWindow()
  62978. {
  62979. shadower = 0;
  62980. TopLevelWindowManager::getInstance()->removeWindow (this);
  62981. }
  62982. void TopLevelWindow::focusOfChildComponentChanged (FocusChangeType)
  62983. {
  62984. if (hasKeyboardFocus (true))
  62985. TopLevelWindowManager::getInstance()->timerCallback();
  62986. else
  62987. TopLevelWindowManager::getInstance()->startTimer (10);
  62988. }
  62989. void TopLevelWindow::setWindowActive (const bool isNowActive)
  62990. {
  62991. if (windowIsActive_ != isNowActive)
  62992. {
  62993. windowIsActive_ = isNowActive;
  62994. activeWindowStatusChanged();
  62995. }
  62996. }
  62997. void TopLevelWindow::activeWindowStatusChanged()
  62998. {
  62999. }
  63000. void TopLevelWindow::parentHierarchyChanged()
  63001. {
  63002. setDropShadowEnabled (useDropShadow);
  63003. }
  63004. void TopLevelWindow::visibilityChanged()
  63005. {
  63006. if (isShowing())
  63007. toFront (true);
  63008. }
  63009. int TopLevelWindow::getDesktopWindowStyleFlags() const
  63010. {
  63011. int styleFlags = ComponentPeer::windowAppearsOnTaskbar;
  63012. if (useDropShadow)
  63013. styleFlags |= ComponentPeer::windowHasDropShadow;
  63014. if (useNativeTitleBar)
  63015. styleFlags |= ComponentPeer::windowHasTitleBar;
  63016. return styleFlags;
  63017. }
  63018. void TopLevelWindow::setDropShadowEnabled (const bool useShadow)
  63019. {
  63020. useDropShadow = useShadow;
  63021. if (isOnDesktop())
  63022. {
  63023. shadower = 0;
  63024. Component::addToDesktop (getDesktopWindowStyleFlags());
  63025. }
  63026. else
  63027. {
  63028. if (useShadow && isOpaque())
  63029. {
  63030. if (shadower == 0)
  63031. {
  63032. shadower = getLookAndFeel().createDropShadowerForComponent (this);
  63033. if (shadower != 0)
  63034. shadower->setOwner (this);
  63035. }
  63036. }
  63037. else
  63038. {
  63039. shadower = 0;
  63040. }
  63041. }
  63042. }
  63043. void TopLevelWindow::setUsingNativeTitleBar (const bool useNativeTitleBar_)
  63044. {
  63045. if (useNativeTitleBar != useNativeTitleBar_)
  63046. {
  63047. useNativeTitleBar = useNativeTitleBar_;
  63048. recreateDesktopWindow();
  63049. sendLookAndFeelChange();
  63050. }
  63051. }
  63052. void TopLevelWindow::recreateDesktopWindow()
  63053. {
  63054. if (isOnDesktop())
  63055. {
  63056. Component::addToDesktop (getDesktopWindowStyleFlags());
  63057. toFront (true);
  63058. }
  63059. }
  63060. void TopLevelWindow::addToDesktop (int windowStyleFlags, void* nativeWindowToAttachTo)
  63061. {
  63062. /* It's not recommended to change the desktop window flags directly for a TopLevelWindow,
  63063. because this class needs to make sure its layout corresponds with settings like whether
  63064. it's got a native title bar or not.
  63065. If you need custom flags for your window, you can override the getDesktopWindowStyleFlags()
  63066. method. If you do this, it's best to call the base class's getDesktopWindowStyleFlags()
  63067. method, then add or remove whatever flags are necessary from this value before returning it.
  63068. */
  63069. jassert ((windowStyleFlags & ~ComponentPeer::windowIsSemiTransparent)
  63070. == (getDesktopWindowStyleFlags() & ~ComponentPeer::windowIsSemiTransparent));
  63071. Component::addToDesktop (windowStyleFlags, nativeWindowToAttachTo);
  63072. if (windowStyleFlags != getDesktopWindowStyleFlags())
  63073. sendLookAndFeelChange();
  63074. }
  63075. void TopLevelWindow::centreAroundComponent (Component* c, const int width, const int height)
  63076. {
  63077. if (c == 0)
  63078. c = TopLevelWindow::getActiveTopLevelWindow();
  63079. if (c == 0)
  63080. {
  63081. centreWithSize (width, height);
  63082. }
  63083. else
  63084. {
  63085. Point<int> p (c->relativePositionToGlobal (Point<int> ((c->getWidth() - width) / 2,
  63086. (c->getHeight() - height) / 2)));
  63087. Rectangle<int> parentArea (c->getParentMonitorArea());
  63088. if (getParentComponent() != 0)
  63089. {
  63090. p = getParentComponent()->globalPositionToRelative (p);
  63091. parentArea.setBounds (0, 0, getParentWidth(), getParentHeight());
  63092. }
  63093. parentArea.reduce (12, 12);
  63094. setBounds (jlimit (parentArea.getX(), jmax (parentArea.getX(), parentArea.getRight() - width), p.getX()),
  63095. jlimit (parentArea.getY(), jmax (parentArea.getY(), parentArea.getBottom() - height), p.getY()),
  63096. width, height);
  63097. }
  63098. }
  63099. int TopLevelWindow::getNumTopLevelWindows() throw()
  63100. {
  63101. return TopLevelWindowManager::getInstance()->windows.size();
  63102. }
  63103. TopLevelWindow* TopLevelWindow::getTopLevelWindow (const int index) throw()
  63104. {
  63105. return static_cast <TopLevelWindow*> (TopLevelWindowManager::getInstance()->windows [index]);
  63106. }
  63107. TopLevelWindow* TopLevelWindow::getActiveTopLevelWindow() throw()
  63108. {
  63109. TopLevelWindow* best = 0;
  63110. int bestNumTWLParents = -1;
  63111. for (int i = TopLevelWindow::getNumTopLevelWindows(); --i >= 0;)
  63112. {
  63113. TopLevelWindow* const tlw = TopLevelWindow::getTopLevelWindow (i);
  63114. if (tlw->isActiveWindow())
  63115. {
  63116. int numTWLParents = 0;
  63117. const Component* c = tlw->getParentComponent();
  63118. while (c != 0)
  63119. {
  63120. if (dynamic_cast <const TopLevelWindow*> (c) != 0)
  63121. ++numTWLParents;
  63122. c = c->getParentComponent();
  63123. }
  63124. if (bestNumTWLParents < numTWLParents)
  63125. {
  63126. best = tlw;
  63127. bestNumTWLParents = numTWLParents;
  63128. }
  63129. }
  63130. }
  63131. return best;
  63132. }
  63133. END_JUCE_NAMESPACE
  63134. /*** End of inlined file: juce_TopLevelWindow.cpp ***/
  63135. #endif
  63136. #if JUCE_BUILD_MISC // (put these in misc to balance the file sizes and avoid problems in iphone build)
  63137. /*** Start of inlined file: juce_Colour.cpp ***/
  63138. BEGIN_JUCE_NAMESPACE
  63139. namespace ColourHelpers
  63140. {
  63141. static uint8 floatAlphaToInt (const float alpha) throw()
  63142. {
  63143. return (uint8) jlimit (0, 0xff, roundToInt (alpha * 255.0f));
  63144. }
  63145. static void convertHSBtoRGB (float h, float s, float v,
  63146. uint8& r, uint8& g, uint8& b) throw()
  63147. {
  63148. v = jlimit (0.0f, 1.0f, v);
  63149. v *= 255.0f;
  63150. const uint8 intV = (uint8) roundToInt (v);
  63151. if (s <= 0)
  63152. {
  63153. r = intV;
  63154. g = intV;
  63155. b = intV;
  63156. }
  63157. else
  63158. {
  63159. s = jmin (1.0f, s);
  63160. h = jlimit (0.0f, 1.0f, h);
  63161. h = (h - std::floor (h)) * 6.0f + 0.00001f; // need a small adjustment to compensate for rounding errors
  63162. const float f = h - std::floor (h);
  63163. const uint8 x = (uint8) roundToInt (v * (1.0f - s));
  63164. const float y = v * (1.0f - s * f);
  63165. const float z = v * (1.0f - (s * (1.0f - f)));
  63166. if (h < 1.0f)
  63167. {
  63168. r = intV;
  63169. g = (uint8) roundToInt (z);
  63170. b = x;
  63171. }
  63172. else if (h < 2.0f)
  63173. {
  63174. r = (uint8) roundToInt (y);
  63175. g = intV;
  63176. b = x;
  63177. }
  63178. else if (h < 3.0f)
  63179. {
  63180. r = x;
  63181. g = intV;
  63182. b = (uint8) roundToInt (z);
  63183. }
  63184. else if (h < 4.0f)
  63185. {
  63186. r = x;
  63187. g = (uint8) roundToInt (y);
  63188. b = intV;
  63189. }
  63190. else if (h < 5.0f)
  63191. {
  63192. r = (uint8) roundToInt (z);
  63193. g = x;
  63194. b = intV;
  63195. }
  63196. else if (h < 6.0f)
  63197. {
  63198. r = intV;
  63199. g = x;
  63200. b = (uint8) roundToInt (y);
  63201. }
  63202. else
  63203. {
  63204. r = 0;
  63205. g = 0;
  63206. b = 0;
  63207. }
  63208. }
  63209. }
  63210. }
  63211. Colour::Colour() throw()
  63212. : argb (0)
  63213. {
  63214. }
  63215. Colour::Colour (const Colour& other) throw()
  63216. : argb (other.argb)
  63217. {
  63218. }
  63219. Colour& Colour::operator= (const Colour& other) throw()
  63220. {
  63221. argb = other.argb;
  63222. return *this;
  63223. }
  63224. bool Colour::operator== (const Colour& other) const throw()
  63225. {
  63226. return argb.getARGB() == other.argb.getARGB();
  63227. }
  63228. bool Colour::operator!= (const Colour& other) const throw()
  63229. {
  63230. return argb.getARGB() != other.argb.getARGB();
  63231. }
  63232. Colour::Colour (const uint32 argb_) throw()
  63233. : argb (argb_)
  63234. {
  63235. }
  63236. Colour::Colour (const uint8 red,
  63237. const uint8 green,
  63238. const uint8 blue) throw()
  63239. {
  63240. argb.setARGB (0xff, red, green, blue);
  63241. }
  63242. const Colour Colour::fromRGB (const uint8 red,
  63243. const uint8 green,
  63244. const uint8 blue) throw()
  63245. {
  63246. return Colour (red, green, blue);
  63247. }
  63248. Colour::Colour (const uint8 red,
  63249. const uint8 green,
  63250. const uint8 blue,
  63251. const uint8 alpha) throw()
  63252. {
  63253. argb.setARGB (alpha, red, green, blue);
  63254. }
  63255. const Colour Colour::fromRGBA (const uint8 red,
  63256. const uint8 green,
  63257. const uint8 blue,
  63258. const uint8 alpha) throw()
  63259. {
  63260. return Colour (red, green, blue, alpha);
  63261. }
  63262. Colour::Colour (const uint8 red,
  63263. const uint8 green,
  63264. const uint8 blue,
  63265. const float alpha) throw()
  63266. {
  63267. argb.setARGB (ColourHelpers::floatAlphaToInt (alpha), red, green, blue);
  63268. }
  63269. const Colour Colour::fromRGBAFloat (const uint8 red,
  63270. const uint8 green,
  63271. const uint8 blue,
  63272. const float alpha) throw()
  63273. {
  63274. return Colour (red, green, blue, alpha);
  63275. }
  63276. Colour::Colour (const float hue,
  63277. const float saturation,
  63278. const float brightness,
  63279. const float alpha) throw()
  63280. {
  63281. uint8 r = getRed(), g = getGreen(), b = getBlue();
  63282. ColourHelpers::convertHSBtoRGB (hue, saturation, brightness, r, g, b);
  63283. argb.setARGB (ColourHelpers::floatAlphaToInt (alpha), r, g, b);
  63284. }
  63285. const Colour Colour::fromHSV (const float hue,
  63286. const float saturation,
  63287. const float brightness,
  63288. const float alpha) throw()
  63289. {
  63290. return Colour (hue, saturation, brightness, alpha);
  63291. }
  63292. Colour::Colour (const float hue,
  63293. const float saturation,
  63294. const float brightness,
  63295. const uint8 alpha) throw()
  63296. {
  63297. uint8 r = getRed(), g = getGreen(), b = getBlue();
  63298. ColourHelpers::convertHSBtoRGB (hue, saturation, brightness, r, g, b);
  63299. argb.setARGB (alpha, r, g, b);
  63300. }
  63301. Colour::~Colour() throw()
  63302. {
  63303. }
  63304. const PixelARGB Colour::getPixelARGB() const throw()
  63305. {
  63306. PixelARGB p (argb);
  63307. p.premultiply();
  63308. return p;
  63309. }
  63310. uint32 Colour::getARGB() const throw()
  63311. {
  63312. return argb.getARGB();
  63313. }
  63314. bool Colour::isTransparent() const throw()
  63315. {
  63316. return getAlpha() == 0;
  63317. }
  63318. bool Colour::isOpaque() const throw()
  63319. {
  63320. return getAlpha() == 0xff;
  63321. }
  63322. const Colour Colour::withAlpha (const uint8 newAlpha) const throw()
  63323. {
  63324. PixelARGB newCol (argb);
  63325. newCol.setAlpha (newAlpha);
  63326. return Colour (newCol.getARGB());
  63327. }
  63328. const Colour Colour::withAlpha (const float newAlpha) const throw()
  63329. {
  63330. jassert (newAlpha >= 0 && newAlpha <= 1.0f);
  63331. PixelARGB newCol (argb);
  63332. newCol.setAlpha (ColourHelpers::floatAlphaToInt (newAlpha));
  63333. return Colour (newCol.getARGB());
  63334. }
  63335. const Colour Colour::withMultipliedAlpha (const float alphaMultiplier) const throw()
  63336. {
  63337. jassert (alphaMultiplier >= 0);
  63338. PixelARGB newCol (argb);
  63339. newCol.setAlpha ((uint8) jmin (0xff, roundToInt (alphaMultiplier * newCol.getAlpha())));
  63340. return Colour (newCol.getARGB());
  63341. }
  63342. const Colour Colour::overlaidWith (const Colour& src) const throw()
  63343. {
  63344. const int destAlpha = getAlpha();
  63345. if (destAlpha > 0)
  63346. {
  63347. const int invA = 0xff - (int) src.getAlpha();
  63348. const int resA = 0xff - (((0xff - destAlpha) * invA) >> 8);
  63349. if (resA > 0)
  63350. {
  63351. const int da = (invA * destAlpha) / resA;
  63352. return Colour ((uint8) (src.getRed() + ((((int) getRed() - src.getRed()) * da) >> 8)),
  63353. (uint8) (src.getGreen() + ((((int) getGreen() - src.getGreen()) * da) >> 8)),
  63354. (uint8) (src.getBlue() + ((((int) getBlue() - src.getBlue()) * da) >> 8)),
  63355. (uint8) resA);
  63356. }
  63357. return *this;
  63358. }
  63359. else
  63360. {
  63361. return src;
  63362. }
  63363. }
  63364. const Colour Colour::interpolatedWith (const Colour& other, float proportionOfOther) const throw()
  63365. {
  63366. if (proportionOfOther <= 0)
  63367. return *this;
  63368. if (proportionOfOther >= 1.0f)
  63369. return other;
  63370. PixelARGB c1 (getPixelARGB());
  63371. const PixelARGB c2 (other.getPixelARGB());
  63372. c1.tween (c2, roundToInt (proportionOfOther * 255.0f));
  63373. c1.unpremultiply();
  63374. return Colour (c1.getARGB());
  63375. }
  63376. float Colour::getFloatRed() const throw()
  63377. {
  63378. return getRed() / 255.0f;
  63379. }
  63380. float Colour::getFloatGreen() const throw()
  63381. {
  63382. return getGreen() / 255.0f;
  63383. }
  63384. float Colour::getFloatBlue() const throw()
  63385. {
  63386. return getBlue() / 255.0f;
  63387. }
  63388. float Colour::getFloatAlpha() const throw()
  63389. {
  63390. return getAlpha() / 255.0f;
  63391. }
  63392. void Colour::getHSB (float& h, float& s, float& v) const throw()
  63393. {
  63394. const int r = getRed();
  63395. const int g = getGreen();
  63396. const int b = getBlue();
  63397. const int hi = jmax (r, g, b);
  63398. const int lo = jmin (r, g, b);
  63399. if (hi != 0)
  63400. {
  63401. s = (hi - lo) / (float) hi;
  63402. if (s != 0)
  63403. {
  63404. const float invDiff = 1.0f / (hi - lo);
  63405. const float red = (hi - r) * invDiff;
  63406. const float green = (hi - g) * invDiff;
  63407. const float blue = (hi - b) * invDiff;
  63408. if (r == hi)
  63409. h = blue - green;
  63410. else if (g == hi)
  63411. h = 2.0f + red - blue;
  63412. else
  63413. h = 4.0f + green - red;
  63414. h *= 1.0f / 6.0f;
  63415. if (h < 0)
  63416. ++h;
  63417. }
  63418. else
  63419. {
  63420. h = 0;
  63421. }
  63422. }
  63423. else
  63424. {
  63425. s = 0;
  63426. h = 0;
  63427. }
  63428. v = hi / 255.0f;
  63429. }
  63430. float Colour::getHue() const throw()
  63431. {
  63432. float h, s, b;
  63433. getHSB (h, s, b);
  63434. return h;
  63435. }
  63436. const Colour Colour::withHue (const float hue) const throw()
  63437. {
  63438. float h, s, b;
  63439. getHSB (h, s, b);
  63440. return Colour (hue, s, b, getAlpha());
  63441. }
  63442. const Colour Colour::withRotatedHue (const float amountToRotate) const throw()
  63443. {
  63444. float h, s, b;
  63445. getHSB (h, s, b);
  63446. h += amountToRotate;
  63447. h -= std::floor (h);
  63448. return Colour (h, s, b, getAlpha());
  63449. }
  63450. float Colour::getSaturation() const throw()
  63451. {
  63452. float h, s, b;
  63453. getHSB (h, s, b);
  63454. return s;
  63455. }
  63456. const Colour Colour::withSaturation (const float saturation) const throw()
  63457. {
  63458. float h, s, b;
  63459. getHSB (h, s, b);
  63460. return Colour (h, saturation, b, getAlpha());
  63461. }
  63462. const Colour Colour::withMultipliedSaturation (const float amount) const throw()
  63463. {
  63464. float h, s, b;
  63465. getHSB (h, s, b);
  63466. return Colour (h, jmin (1.0f, s * amount), b, getAlpha());
  63467. }
  63468. float Colour::getBrightness() const throw()
  63469. {
  63470. float h, s, b;
  63471. getHSB (h, s, b);
  63472. return b;
  63473. }
  63474. const Colour Colour::withBrightness (const float brightness) const throw()
  63475. {
  63476. float h, s, b;
  63477. getHSB (h, s, b);
  63478. return Colour (h, s, brightness, getAlpha());
  63479. }
  63480. const Colour Colour::withMultipliedBrightness (const float amount) const throw()
  63481. {
  63482. float h, s, b;
  63483. getHSB (h, s, b);
  63484. b *= amount;
  63485. if (b > 1.0f)
  63486. b = 1.0f;
  63487. return Colour (h, s, b, getAlpha());
  63488. }
  63489. const Colour Colour::brighter (float amount) const throw()
  63490. {
  63491. amount = 1.0f / (1.0f + amount);
  63492. return Colour ((uint8) (255 - (amount * (255 - getRed()))),
  63493. (uint8) (255 - (amount * (255 - getGreen()))),
  63494. (uint8) (255 - (amount * (255 - getBlue()))),
  63495. getAlpha());
  63496. }
  63497. const Colour Colour::darker (float amount) const throw()
  63498. {
  63499. amount = 1.0f / (1.0f + amount);
  63500. return Colour ((uint8) (amount * getRed()),
  63501. (uint8) (amount * getGreen()),
  63502. (uint8) (amount * getBlue()),
  63503. getAlpha());
  63504. }
  63505. const Colour Colour::greyLevel (const float brightness) throw()
  63506. {
  63507. const uint8 level
  63508. = (uint8) jlimit (0x00, 0xff, roundToInt (brightness * 255.0f));
  63509. return Colour (level, level, level);
  63510. }
  63511. const Colour Colour::contrasting (const float amount) const throw()
  63512. {
  63513. return overlaidWith ((((int) getRed() + (int) getGreen() + (int) getBlue() >= 3 * 128)
  63514. ? Colours::black
  63515. : Colours::white).withAlpha (amount));
  63516. }
  63517. const Colour Colour::contrasting (const Colour& colour1,
  63518. const Colour& colour2) throw()
  63519. {
  63520. const float b1 = colour1.getBrightness();
  63521. const float b2 = colour2.getBrightness();
  63522. float best = 0.0f;
  63523. float bestDist = 0.0f;
  63524. for (float i = 0.0f; i < 1.0f; i += 0.02f)
  63525. {
  63526. const float d1 = std::abs (i - b1);
  63527. const float d2 = std::abs (i - b2);
  63528. const float dist = jmin (d1, d2, 1.0f - d1, 1.0f - d2);
  63529. if (dist > bestDist)
  63530. {
  63531. best = i;
  63532. bestDist = dist;
  63533. }
  63534. }
  63535. return colour1.overlaidWith (colour2.withMultipliedAlpha (0.5f))
  63536. .withBrightness (best);
  63537. }
  63538. const String Colour::toString() const
  63539. {
  63540. return String::toHexString ((int) argb.getARGB());
  63541. }
  63542. const Colour Colour::fromString (const String& encodedColourString)
  63543. {
  63544. return Colour ((uint32) encodedColourString.getHexValue32());
  63545. }
  63546. const String Colour::toDisplayString (const bool includeAlphaValue) const
  63547. {
  63548. return String::toHexString ((int) (argb.getARGB() & (includeAlphaValue ? 0xffffffff : 0xffffff)))
  63549. .paddedLeft ('0', includeAlphaValue ? 8 : 6)
  63550. .toUpperCase();
  63551. }
  63552. END_JUCE_NAMESPACE
  63553. /*** End of inlined file: juce_Colour.cpp ***/
  63554. /*** Start of inlined file: juce_ColourGradient.cpp ***/
  63555. BEGIN_JUCE_NAMESPACE
  63556. ColourGradient::ColourGradient() throw()
  63557. {
  63558. #if JUCE_DEBUG
  63559. x1 = 987654.0f;
  63560. #endif
  63561. }
  63562. ColourGradient::ColourGradient (const Colour& colour1,
  63563. const float x1_,
  63564. const float y1_,
  63565. const Colour& colour2,
  63566. const float x2_,
  63567. const float y2_,
  63568. const bool isRadial_)
  63569. : x1 (x1_),
  63570. y1 (y1_),
  63571. x2 (x2_),
  63572. y2 (y2_),
  63573. isRadial (isRadial_)
  63574. {
  63575. colours.add (0);
  63576. colours.add (colour1.getARGB());
  63577. colours.add (1 << 16);
  63578. colours.add (colour2.getARGB());
  63579. }
  63580. ColourGradient::~ColourGradient()
  63581. {
  63582. }
  63583. void ColourGradient::clearColours()
  63584. {
  63585. colours.clear();
  63586. }
  63587. void ColourGradient::addColour (const double proportionAlongGradient,
  63588. const Colour& colour)
  63589. {
  63590. // must be within the two end-points
  63591. jassert (proportionAlongGradient >= 0 && proportionAlongGradient <= 1.0);
  63592. const uint32 pos = jlimit (0, 65535, roundToInt (proportionAlongGradient * 65536.0));
  63593. int i;
  63594. for (i = 0; i < colours.size(); i += 2)
  63595. if (colours.getUnchecked(i) > pos)
  63596. break;
  63597. colours.insert (i, pos);
  63598. colours.insert (i + 1, colour.getARGB());
  63599. }
  63600. void ColourGradient::multiplyOpacity (const float multiplier) throw()
  63601. {
  63602. for (int i = 1; i < colours.size(); i += 2)
  63603. {
  63604. const Colour c (colours.getUnchecked(i));
  63605. colours.set (i, c.withMultipliedAlpha (multiplier).getARGB());
  63606. }
  63607. }
  63608. int ColourGradient::getNumColours() const throw()
  63609. {
  63610. return colours.size() >> 1;
  63611. }
  63612. double ColourGradient::getColourPosition (const int index) const throw()
  63613. {
  63614. return jlimit (0.0, 1.0, colours [index << 1] / 65535.0);
  63615. }
  63616. const Colour ColourGradient::getColour (const int index) const throw()
  63617. {
  63618. return Colour (colours [(index << 1) + 1]);
  63619. }
  63620. const Colour ColourGradient::getColourAtPosition (const float position) const throw()
  63621. {
  63622. jassert (colours.getUnchecked (0) == 0); // the first colour specified has to go at position 0
  63623. const int integerPos = jlimit (0, 65535, roundToInt (position * 65536.0f));
  63624. if (integerPos <= 0 || colours.size() <= 2)
  63625. return getColour (0);
  63626. int i = colours.size() - 2;
  63627. while (integerPos < (int) colours.getUnchecked(i))
  63628. i -= 2;
  63629. if (i >= colours.size() - 2)
  63630. return Colour (colours.getUnchecked(i));
  63631. const int pos1 = colours.getUnchecked (i);
  63632. const Colour col1 (colours.getUnchecked (i + 1));
  63633. const int pos2 = colours.getUnchecked (i + 2);
  63634. const Colour col2 (colours.getUnchecked (i + 3));
  63635. return col1.interpolatedWith (col2, (integerPos - pos1) / (float) (pos2 - pos1));
  63636. }
  63637. int ColourGradient::createLookupTable (const AffineTransform& transform, HeapBlock <PixelARGB>& lookupTable) const
  63638. {
  63639. #if JUCE_DEBUG
  63640. // trying to use the object without setting its co-ordinates? Have a careful read of
  63641. // the comments for the constructors.
  63642. jassert (x1 != 987654.0f);
  63643. #endif
  63644. const int numColours = colours.size() >> 1;
  63645. float tx1 = x1, ty1 = y1, tx2 = x2, ty2 = y2;
  63646. transform.transformPoint (tx1, ty1);
  63647. transform.transformPoint (tx2, ty2);
  63648. const double distance = juce_hypot (tx1 - tx2, ty1 - ty2);
  63649. const int numEntries = jlimit (1, (numColours - 1) << 8, 3 * (int) distance);
  63650. lookupTable.malloc (numEntries);
  63651. if (numColours >= 2)
  63652. {
  63653. jassert (colours.getUnchecked (0) == 0); // the first colour specified has to go at position 0
  63654. PixelARGB pix1 (colours.getUnchecked (1));
  63655. pix1.premultiply();
  63656. int index = 0;
  63657. for (int j = 2; j < colours.size(); j += 2)
  63658. {
  63659. const int numToDo = ((colours.getUnchecked (j) * (numEntries - 1)) >> 16) - index;
  63660. PixelARGB pix2 (colours.getUnchecked (j + 1));
  63661. pix2.premultiply();
  63662. for (int i = 0; i < numToDo; ++i)
  63663. {
  63664. jassert (index >= 0 && index < numEntries);
  63665. lookupTable[index] = pix1;
  63666. lookupTable[index].tween (pix2, (i << 8) / numToDo);
  63667. ++index;
  63668. }
  63669. pix1 = pix2;
  63670. }
  63671. while (index < numEntries)
  63672. lookupTable [index++] = pix1;
  63673. }
  63674. else
  63675. {
  63676. jassertfalse // no colours specified!
  63677. }
  63678. return numEntries;
  63679. }
  63680. bool ColourGradient::isOpaque() const throw()
  63681. {
  63682. for (int i = 1; i < colours.size(); i += 2)
  63683. if (PixelARGB (colours.getUnchecked(i)).getAlpha() < 0xff)
  63684. return false;
  63685. return true;
  63686. }
  63687. bool ColourGradient::isInvisible() const throw()
  63688. {
  63689. for (int i = 1; i < colours.size(); i += 2)
  63690. if (PixelARGB (colours.getUnchecked(i)).getAlpha() > 0)
  63691. return false;
  63692. return true;
  63693. }
  63694. END_JUCE_NAMESPACE
  63695. /*** End of inlined file: juce_ColourGradient.cpp ***/
  63696. /*** Start of inlined file: juce_Colours.cpp ***/
  63697. BEGIN_JUCE_NAMESPACE
  63698. const Colour Colours::transparentBlack (0);
  63699. const Colour Colours::transparentWhite (0x00ffffff);
  63700. const Colour Colours::aliceblue (0xfff0f8ff);
  63701. const Colour Colours::antiquewhite (0xfffaebd7);
  63702. const Colour Colours::aqua (0xff00ffff);
  63703. const Colour Colours::aquamarine (0xff7fffd4);
  63704. const Colour Colours::azure (0xfff0ffff);
  63705. const Colour Colours::beige (0xfff5f5dc);
  63706. const Colour Colours::bisque (0xffffe4c4);
  63707. const Colour Colours::black (0xff000000);
  63708. const Colour Colours::blanchedalmond (0xffffebcd);
  63709. const Colour Colours::blue (0xff0000ff);
  63710. const Colour Colours::blueviolet (0xff8a2be2);
  63711. const Colour Colours::brown (0xffa52a2a);
  63712. const Colour Colours::burlywood (0xffdeb887);
  63713. const Colour Colours::cadetblue (0xff5f9ea0);
  63714. const Colour Colours::chartreuse (0xff7fff00);
  63715. const Colour Colours::chocolate (0xffd2691e);
  63716. const Colour Colours::coral (0xffff7f50);
  63717. const Colour Colours::cornflowerblue (0xff6495ed);
  63718. const Colour Colours::cornsilk (0xfffff8dc);
  63719. const Colour Colours::crimson (0xffdc143c);
  63720. const Colour Colours::cyan (0xff00ffff);
  63721. const Colour Colours::darkblue (0xff00008b);
  63722. const Colour Colours::darkcyan (0xff008b8b);
  63723. const Colour Colours::darkgoldenrod (0xffb8860b);
  63724. const Colour Colours::darkgrey (0xff555555);
  63725. const Colour Colours::darkgreen (0xff006400);
  63726. const Colour Colours::darkkhaki (0xffbdb76b);
  63727. const Colour Colours::darkmagenta (0xff8b008b);
  63728. const Colour Colours::darkolivegreen (0xff556b2f);
  63729. const Colour Colours::darkorange (0xffff8c00);
  63730. const Colour Colours::darkorchid (0xff9932cc);
  63731. const Colour Colours::darkred (0xff8b0000);
  63732. const Colour Colours::darksalmon (0xffe9967a);
  63733. const Colour Colours::darkseagreen (0xff8fbc8f);
  63734. const Colour Colours::darkslateblue (0xff483d8b);
  63735. const Colour Colours::darkslategrey (0xff2f4f4f);
  63736. const Colour Colours::darkturquoise (0xff00ced1);
  63737. const Colour Colours::darkviolet (0xff9400d3);
  63738. const Colour Colours::deeppink (0xffff1493);
  63739. const Colour Colours::deepskyblue (0xff00bfff);
  63740. const Colour Colours::dimgrey (0xff696969);
  63741. const Colour Colours::dodgerblue (0xff1e90ff);
  63742. const Colour Colours::firebrick (0xffb22222);
  63743. const Colour Colours::floralwhite (0xfffffaf0);
  63744. const Colour Colours::forestgreen (0xff228b22);
  63745. const Colour Colours::fuchsia (0xffff00ff);
  63746. const Colour Colours::gainsboro (0xffdcdcdc);
  63747. const Colour Colours::gold (0xffffd700);
  63748. const Colour Colours::goldenrod (0xffdaa520);
  63749. const Colour Colours::grey (0xff808080);
  63750. const Colour Colours::green (0xff008000);
  63751. const Colour Colours::greenyellow (0xffadff2f);
  63752. const Colour Colours::honeydew (0xfff0fff0);
  63753. const Colour Colours::hotpink (0xffff69b4);
  63754. const Colour Colours::indianred (0xffcd5c5c);
  63755. const Colour Colours::indigo (0xff4b0082);
  63756. const Colour Colours::ivory (0xfffffff0);
  63757. const Colour Colours::khaki (0xfff0e68c);
  63758. const Colour Colours::lavender (0xffe6e6fa);
  63759. const Colour Colours::lavenderblush (0xfffff0f5);
  63760. const Colour Colours::lemonchiffon (0xfffffacd);
  63761. const Colour Colours::lightblue (0xffadd8e6);
  63762. const Colour Colours::lightcoral (0xfff08080);
  63763. const Colour Colours::lightcyan (0xffe0ffff);
  63764. const Colour Colours::lightgoldenrodyellow (0xfffafad2);
  63765. const Colour Colours::lightgreen (0xff90ee90);
  63766. const Colour Colours::lightgrey (0xffd3d3d3);
  63767. const Colour Colours::lightpink (0xffffb6c1);
  63768. const Colour Colours::lightsalmon (0xffffa07a);
  63769. const Colour Colours::lightseagreen (0xff20b2aa);
  63770. const Colour Colours::lightskyblue (0xff87cefa);
  63771. const Colour Colours::lightslategrey (0xff778899);
  63772. const Colour Colours::lightsteelblue (0xffb0c4de);
  63773. const Colour Colours::lightyellow (0xffffffe0);
  63774. const Colour Colours::lime (0xff00ff00);
  63775. const Colour Colours::limegreen (0xff32cd32);
  63776. const Colour Colours::linen (0xfffaf0e6);
  63777. const Colour Colours::magenta (0xffff00ff);
  63778. const Colour Colours::maroon (0xff800000);
  63779. const Colour Colours::mediumaquamarine (0xff66cdaa);
  63780. const Colour Colours::mediumblue (0xff0000cd);
  63781. const Colour Colours::mediumorchid (0xffba55d3);
  63782. const Colour Colours::mediumpurple (0xff9370db);
  63783. const Colour Colours::mediumseagreen (0xff3cb371);
  63784. const Colour Colours::mediumslateblue (0xff7b68ee);
  63785. const Colour Colours::mediumspringgreen (0xff00fa9a);
  63786. const Colour Colours::mediumturquoise (0xff48d1cc);
  63787. const Colour Colours::mediumvioletred (0xffc71585);
  63788. const Colour Colours::midnightblue (0xff191970);
  63789. const Colour Colours::mintcream (0xfff5fffa);
  63790. const Colour Colours::mistyrose (0xffffe4e1);
  63791. const Colour Colours::navajowhite (0xffffdead);
  63792. const Colour Colours::navy (0xff000080);
  63793. const Colour Colours::oldlace (0xfffdf5e6);
  63794. const Colour Colours::olive (0xff808000);
  63795. const Colour Colours::olivedrab (0xff6b8e23);
  63796. const Colour Colours::orange (0xffffa500);
  63797. const Colour Colours::orangered (0xffff4500);
  63798. const Colour Colours::orchid (0xffda70d6);
  63799. const Colour Colours::palegoldenrod (0xffeee8aa);
  63800. const Colour Colours::palegreen (0xff98fb98);
  63801. const Colour Colours::paleturquoise (0xffafeeee);
  63802. const Colour Colours::palevioletred (0xffdb7093);
  63803. const Colour Colours::papayawhip (0xffffefd5);
  63804. const Colour Colours::peachpuff (0xffffdab9);
  63805. const Colour Colours::peru (0xffcd853f);
  63806. const Colour Colours::pink (0xffffc0cb);
  63807. const Colour Colours::plum (0xffdda0dd);
  63808. const Colour Colours::powderblue (0xffb0e0e6);
  63809. const Colour Colours::purple (0xff800080);
  63810. const Colour Colours::red (0xffff0000);
  63811. const Colour Colours::rosybrown (0xffbc8f8f);
  63812. const Colour Colours::royalblue (0xff4169e1);
  63813. const Colour Colours::saddlebrown (0xff8b4513);
  63814. const Colour Colours::salmon (0xfffa8072);
  63815. const Colour Colours::sandybrown (0xfff4a460);
  63816. const Colour Colours::seagreen (0xff2e8b57);
  63817. const Colour Colours::seashell (0xfffff5ee);
  63818. const Colour Colours::sienna (0xffa0522d);
  63819. const Colour Colours::silver (0xffc0c0c0);
  63820. const Colour Colours::skyblue (0xff87ceeb);
  63821. const Colour Colours::slateblue (0xff6a5acd);
  63822. const Colour Colours::slategrey (0xff708090);
  63823. const Colour Colours::snow (0xfffffafa);
  63824. const Colour Colours::springgreen (0xff00ff7f);
  63825. const Colour Colours::steelblue (0xff4682b4);
  63826. const Colour Colours::tan (0xffd2b48c);
  63827. const Colour Colours::teal (0xff008080);
  63828. const Colour Colours::thistle (0xffd8bfd8);
  63829. const Colour Colours::tomato (0xffff6347);
  63830. const Colour Colours::turquoise (0xff40e0d0);
  63831. const Colour Colours::violet (0xffee82ee);
  63832. const Colour Colours::wheat (0xfff5deb3);
  63833. const Colour Colours::white (0xffffffff);
  63834. const Colour Colours::whitesmoke (0xfff5f5f5);
  63835. const Colour Colours::yellow (0xffffff00);
  63836. const Colour Colours::yellowgreen (0xff9acd32);
  63837. const Colour Colours::findColourForName (const String& colourName,
  63838. const Colour& defaultColour)
  63839. {
  63840. static const int presets[] =
  63841. {
  63842. // (first value is the string's hashcode, second is ARGB)
  63843. 0x05978fff, 0xff000000, /* black */
  63844. 0x06bdcc29, 0xffffffff, /* white */
  63845. 0x002e305a, 0xff0000ff, /* blue */
  63846. 0x00308adf, 0xff808080, /* grey */
  63847. 0x05e0cf03, 0xff008000, /* green */
  63848. 0x0001b891, 0xffff0000, /* red */
  63849. 0xd43c6474, 0xffffff00, /* yellow */
  63850. 0x620886da, 0xfff0f8ff, /* aliceblue */
  63851. 0x20a2676a, 0xfffaebd7, /* antiquewhite */
  63852. 0x002dcebc, 0xff00ffff, /* aqua */
  63853. 0x46bb5f7e, 0xff7fffd4, /* aquamarine */
  63854. 0x0590228f, 0xfff0ffff, /* azure */
  63855. 0x05947fe4, 0xfff5f5dc, /* beige */
  63856. 0xad388e35, 0xffffe4c4, /* bisque */
  63857. 0x00674f7e, 0xffffebcd, /* blanchedalmond */
  63858. 0x39129959, 0xff8a2be2, /* blueviolet */
  63859. 0x059a8136, 0xffa52a2a, /* brown */
  63860. 0x89cea8f9, 0xffdeb887, /* burlywood */
  63861. 0x0fa260cf, 0xff5f9ea0, /* cadetblue */
  63862. 0x6b748956, 0xff7fff00, /* chartreuse */
  63863. 0x2903623c, 0xffd2691e, /* chocolate */
  63864. 0x05a74431, 0xffff7f50, /* coral */
  63865. 0x618d42dd, 0xff6495ed, /* cornflowerblue */
  63866. 0xe4b479fd, 0xfffff8dc, /* cornsilk */
  63867. 0x3d8c4edf, 0xffdc143c, /* crimson */
  63868. 0x002ed323, 0xff00ffff, /* cyan */
  63869. 0x67cc74d0, 0xff00008b, /* darkblue */
  63870. 0x67cd1799, 0xff008b8b, /* darkcyan */
  63871. 0x31bbd168, 0xffb8860b, /* darkgoldenrod */
  63872. 0x67cecf55, 0xff555555, /* darkgrey */
  63873. 0x920b194d, 0xff006400, /* darkgreen */
  63874. 0x923edd4c, 0xffbdb76b, /* darkkhaki */
  63875. 0x5c293873, 0xff8b008b, /* darkmagenta */
  63876. 0x6b6671fe, 0xff556b2f, /* darkolivegreen */
  63877. 0xbcfd2524, 0xffff8c00, /* darkorange */
  63878. 0xbcfdf799, 0xff9932cc, /* darkorchid */
  63879. 0x55ee0d5b, 0xff8b0000, /* darkred */
  63880. 0xc2e5f564, 0xffe9967a, /* darksalmon */
  63881. 0x61be858a, 0xff8fbc8f, /* darkseagreen */
  63882. 0xc2b0f2bd, 0xff483d8b, /* darkslateblue */
  63883. 0xc2b34d42, 0xff2f4f4f, /* darkslategrey */
  63884. 0x7cf2b06b, 0xff00ced1, /* darkturquoise */
  63885. 0xc8769375, 0xff9400d3, /* darkviolet */
  63886. 0x25832862, 0xffff1493, /* deeppink */
  63887. 0xfcad568f, 0xff00bfff, /* deepskyblue */
  63888. 0x634c8b67, 0xff696969, /* dimgrey */
  63889. 0x45c1ce55, 0xff1e90ff, /* dodgerblue */
  63890. 0xef19e3cb, 0xffb22222, /* firebrick */
  63891. 0xb852b195, 0xfffffaf0, /* floralwhite */
  63892. 0xd086fd06, 0xff228b22, /* forestgreen */
  63893. 0xe106b6d7, 0xffff00ff, /* fuchsia */
  63894. 0x7880d61e, 0xffdcdcdc, /* gainsboro */
  63895. 0x00308060, 0xffffd700, /* gold */
  63896. 0xb3b3bc1e, 0xffdaa520, /* goldenrod */
  63897. 0xbab8a537, 0xffadff2f, /* greenyellow */
  63898. 0xe4cacafb, 0xfff0fff0, /* honeydew */
  63899. 0x41892743, 0xffff69b4, /* hotpink */
  63900. 0xd5796f1a, 0xffcd5c5c, /* indianred */
  63901. 0xb969fed2, 0xff4b0082, /* indigo */
  63902. 0x05fef6a9, 0xfffffff0, /* ivory */
  63903. 0x06149302, 0xfff0e68c, /* khaki */
  63904. 0xad5a05c7, 0xffe6e6fa, /* lavender */
  63905. 0x7c4d5b99, 0xfffff0f5, /* lavenderblush */
  63906. 0x195756f0, 0xfffffacd, /* lemonchiffon */
  63907. 0x28e4ea70, 0xffadd8e6, /* lightblue */
  63908. 0xf3c7ccdb, 0xfff08080, /* lightcoral */
  63909. 0x28e58d39, 0xffe0ffff, /* lightcyan */
  63910. 0x21234e3c, 0xfffafad2, /* lightgoldenrodyellow */
  63911. 0xf40157ad, 0xff90ee90, /* lightgreen */
  63912. 0x28e744f5, 0xffd3d3d3, /* lightgrey */
  63913. 0x28eb3b8c, 0xffffb6c1, /* lightpink */
  63914. 0x9fb78304, 0xffffa07a, /* lightsalmon */
  63915. 0x50632b2a, 0xff20b2aa, /* lightseagreen */
  63916. 0x68fb7b25, 0xff87cefa, /* lightskyblue */
  63917. 0xa8a35ba2, 0xff778899, /* lightslategrey */
  63918. 0xa20d484f, 0xffb0c4de, /* lightsteelblue */
  63919. 0xaa2cf10a, 0xffffffe0, /* lightyellow */
  63920. 0x0032afd5, 0xff00ff00, /* lime */
  63921. 0x607bbc4e, 0xff32cd32, /* limegreen */
  63922. 0x06234efa, 0xfffaf0e6, /* linen */
  63923. 0x316858a9, 0xffff00ff, /* magenta */
  63924. 0xbf8ca470, 0xff800000, /* maroon */
  63925. 0xbd58e0b3, 0xff66cdaa, /* mediumaquamarine */
  63926. 0x967dfd4f, 0xff0000cd, /* mediumblue */
  63927. 0x056f5c58, 0xffba55d3, /* mediumorchid */
  63928. 0x07556b71, 0xff9370db, /* mediumpurple */
  63929. 0x5369b689, 0xff3cb371, /* mediumseagreen */
  63930. 0x066be19e, 0xff7b68ee, /* mediumslateblue */
  63931. 0x3256b281, 0xff00fa9a, /* mediumspringgreen */
  63932. 0xc0ad9f4c, 0xff48d1cc, /* mediumturquoise */
  63933. 0x628e63dd, 0xffc71585, /* mediumvioletred */
  63934. 0x168eb32a, 0xff191970, /* midnightblue */
  63935. 0x4306b960, 0xfff5fffa, /* mintcream */
  63936. 0x4cbc0e6b, 0xffffe4e1, /* mistyrose */
  63937. 0xe97218a6, 0xffffdead, /* navajowhite */
  63938. 0x00337bb6, 0xff000080, /* navy */
  63939. 0xadd2d33e, 0xfffdf5e6, /* oldlace */
  63940. 0x064ee1db, 0xff808000, /* olive */
  63941. 0x9e33a98a, 0xff6b8e23, /* olivedrab */
  63942. 0xc3de262e, 0xffffa500, /* orange */
  63943. 0x58bebba3, 0xffff4500, /* orangered */
  63944. 0xc3def8a3, 0xffda70d6, /* orchid */
  63945. 0x28cb4834, 0xffeee8aa, /* palegoldenrod */
  63946. 0x3d9dd619, 0xff98fb98, /* palegreen */
  63947. 0x74022737, 0xffafeeee, /* paleturquoise */
  63948. 0x15e2ebc8, 0xffdb7093, /* palevioletred */
  63949. 0x5fd898e2, 0xffffefd5, /* papayawhip */
  63950. 0x93e1b776, 0xffffdab9, /* peachpuff */
  63951. 0x003472f8, 0xffcd853f, /* peru */
  63952. 0x00348176, 0xffffc0cb, /* pink */
  63953. 0x00348d94, 0xffdda0dd, /* plum */
  63954. 0xd036be93, 0xffb0e0e6, /* powderblue */
  63955. 0xc5c507bc, 0xff800080, /* purple */
  63956. 0xa89d65b3, 0xffbc8f8f, /* rosybrown */
  63957. 0xbd9413e1, 0xff4169e1, /* royalblue */
  63958. 0xf456044f, 0xff8b4513, /* saddlebrown */
  63959. 0xc9c6f66e, 0xfffa8072, /* salmon */
  63960. 0x0bb131e1, 0xfff4a460, /* sandybrown */
  63961. 0x34636c14, 0xff2e8b57, /* seagreen */
  63962. 0x3507fb41, 0xfffff5ee, /* seashell */
  63963. 0xca348772, 0xffa0522d, /* sienna */
  63964. 0xca37d30d, 0xffc0c0c0, /* silver */
  63965. 0x80da74fb, 0xff87ceeb, /* skyblue */
  63966. 0x44a8dd73, 0xff6a5acd, /* slateblue */
  63967. 0x44ab37f8, 0xff708090, /* slategrey */
  63968. 0x0035f183, 0xfffffafa, /* snow */
  63969. 0xd5440d16, 0xff00ff7f, /* springgreen */
  63970. 0x3e1524a5, 0xff4682b4, /* steelblue */
  63971. 0x0001bfa1, 0xffd2b48c, /* tan */
  63972. 0x0036425c, 0xff008080, /* teal */
  63973. 0xafc8858f, 0xffd8bfd8, /* thistle */
  63974. 0xcc41600a, 0xffff6347, /* tomato */
  63975. 0xfeea9b21, 0xff40e0d0, /* turquoise */
  63976. 0xcf57947f, 0xffee82ee, /* violet */
  63977. 0x06bdbae7, 0xfff5deb3, /* wheat */
  63978. 0x10802ee6, 0xfff5f5f5, /* whitesmoke */
  63979. 0xe1b5130f, 0xff9acd32 /* yellowgreen */
  63980. };
  63981. const int hash = colourName.trim().toLowerCase().hashCode();
  63982. for (int i = 0; i < numElementsInArray (presets); i += 2)
  63983. if (presets [i] == hash)
  63984. return Colour (presets [i + 1]);
  63985. return defaultColour;
  63986. }
  63987. END_JUCE_NAMESPACE
  63988. /*** End of inlined file: juce_Colours.cpp ***/
  63989. /*** Start of inlined file: juce_EdgeTable.cpp ***/
  63990. BEGIN_JUCE_NAMESPACE
  63991. const int juce_edgeTableDefaultEdgesPerLine = 32;
  63992. EdgeTable::EdgeTable (const Rectangle<int>& bounds_,
  63993. const Path& path, const AffineTransform& transform)
  63994. : bounds (bounds_),
  63995. maxEdgesPerLine (juce_edgeTableDefaultEdgesPerLine),
  63996. lineStrideElements ((juce_edgeTableDefaultEdgesPerLine << 1) + 1),
  63997. needToCheckEmptinesss (true)
  63998. {
  63999. table.malloc ((bounds.getHeight() + 1) * lineStrideElements);
  64000. int* t = table;
  64001. for (int i = bounds.getHeight(); --i >= 0;)
  64002. {
  64003. *t = 0;
  64004. t += lineStrideElements;
  64005. }
  64006. const int topLimit = bounds.getY() << 8;
  64007. const int heightLimit = bounds.getHeight() << 8;
  64008. const int leftLimit = bounds.getX() << 8;
  64009. const int rightLimit = bounds.getRight() << 8;
  64010. PathFlatteningIterator iter (path, transform);
  64011. while (iter.next())
  64012. {
  64013. int y1 = roundToInt (iter.y1 * 256.0f);
  64014. int y2 = roundToInt (iter.y2 * 256.0f);
  64015. if (y1 != y2)
  64016. {
  64017. y1 -= topLimit;
  64018. y2 -= topLimit;
  64019. const int startY = y1;
  64020. int direction = -1;
  64021. if (y1 > y2)
  64022. {
  64023. swapVariables (y1, y2);
  64024. direction = 1;
  64025. }
  64026. if (y1 < 0)
  64027. y1 = 0;
  64028. if (y2 > heightLimit)
  64029. y2 = heightLimit;
  64030. if (y1 < y2)
  64031. {
  64032. const double startX = 256.0f * iter.x1;
  64033. const double multiplier = (iter.x2 - iter.x1) / (iter.y2 - iter.y1);
  64034. const int stepSize = jlimit (1, 256, 256 / (1 + (int) std::abs (multiplier)));
  64035. do
  64036. {
  64037. const int step = jmin (stepSize, y2 - y1, 256 - (y1 & 255));
  64038. int x = roundToInt (startX + multiplier * ((y1 + (step >> 1)) - startY));
  64039. if (x < leftLimit)
  64040. x = leftLimit;
  64041. else if (x >= rightLimit)
  64042. x = rightLimit - 1;
  64043. addEdgePoint (x, y1 >> 8, direction * step);
  64044. y1 += step;
  64045. }
  64046. while (y1 < y2);
  64047. }
  64048. }
  64049. }
  64050. sanitiseLevels (path.isUsingNonZeroWinding());
  64051. }
  64052. EdgeTable::EdgeTable (const Rectangle<int>& rectangleToAdd)
  64053. : bounds (rectangleToAdd),
  64054. maxEdgesPerLine (juce_edgeTableDefaultEdgesPerLine),
  64055. lineStrideElements ((juce_edgeTableDefaultEdgesPerLine << 1) + 1),
  64056. needToCheckEmptinesss (true)
  64057. {
  64058. table.malloc (jmax (1, bounds.getHeight()) * lineStrideElements);
  64059. table[0] = 0;
  64060. const int x1 = rectangleToAdd.getX() << 8;
  64061. const int x2 = rectangleToAdd.getRight() << 8;
  64062. int* t = table;
  64063. for (int i = rectangleToAdd.getHeight(); --i >= 0;)
  64064. {
  64065. t[0] = 2;
  64066. t[1] = x1;
  64067. t[2] = 255;
  64068. t[3] = x2;
  64069. t[4] = 0;
  64070. t += lineStrideElements;
  64071. }
  64072. }
  64073. EdgeTable::EdgeTable (const RectangleList& rectanglesToAdd)
  64074. : bounds (rectanglesToAdd.getBounds()),
  64075. maxEdgesPerLine (juce_edgeTableDefaultEdgesPerLine),
  64076. lineStrideElements ((juce_edgeTableDefaultEdgesPerLine << 1) + 1),
  64077. needToCheckEmptinesss (true)
  64078. {
  64079. table.malloc (jmax (1, bounds.getHeight()) * lineStrideElements);
  64080. int* t = table;
  64081. for (int i = bounds.getHeight(); --i >= 0;)
  64082. {
  64083. *t = 0;
  64084. t += lineStrideElements;
  64085. }
  64086. for (RectangleList::Iterator iter (rectanglesToAdd); iter.next();)
  64087. {
  64088. const Rectangle<int>* const r = iter.getRectangle();
  64089. const int x1 = r->getX() << 8;
  64090. const int x2 = r->getRight() << 8;
  64091. int y = r->getY() - bounds.getY();
  64092. for (int j = r->getHeight(); --j >= 0;)
  64093. {
  64094. addEdgePoint (x1, y, 255);
  64095. addEdgePoint (x2, y, -255);
  64096. ++y;
  64097. }
  64098. }
  64099. sanitiseLevels (true);
  64100. }
  64101. EdgeTable::EdgeTable (const Rectangle<float>& rectangleToAdd)
  64102. : bounds (Rectangle<int> ((int) std::floor (rectangleToAdd.getX()),
  64103. roundToInt (rectangleToAdd.getY() * 256.0f) >> 8,
  64104. 2 + (int) rectangleToAdd.getWidth(),
  64105. 2 + (int) rectangleToAdd.getHeight())),
  64106. maxEdgesPerLine (juce_edgeTableDefaultEdgesPerLine),
  64107. lineStrideElements ((juce_edgeTableDefaultEdgesPerLine << 1) + 1),
  64108. needToCheckEmptinesss (true)
  64109. {
  64110. jassert (! rectangleToAdd.isEmpty());
  64111. table.malloc (jmax (1, bounds.getHeight()) * lineStrideElements);
  64112. table[0] = 0;
  64113. const int x1 = roundToInt (rectangleToAdd.getX() * 256.0f);
  64114. const int x2 = roundToInt (rectangleToAdd.getRight() * 256.0f);
  64115. int y1 = roundToInt (rectangleToAdd.getY() * 256.0f) - (bounds.getY() << 8);
  64116. jassert (y1 < 256);
  64117. int y2 = roundToInt (rectangleToAdd.getBottom() * 256.0f) - (bounds.getY() << 8);
  64118. if (x2 <= x1 || y2 <= y1)
  64119. {
  64120. bounds.setHeight (0);
  64121. return;
  64122. }
  64123. int lineY = 0;
  64124. int* t = table;
  64125. if ((y1 >> 8) == (y2 >> 8))
  64126. {
  64127. t[0] = 2;
  64128. t[1] = x1;
  64129. t[2] = y2 - y1;
  64130. t[3] = x2;
  64131. t[4] = 0;
  64132. ++lineY;
  64133. t += lineStrideElements;
  64134. }
  64135. else
  64136. {
  64137. t[0] = 2;
  64138. t[1] = x1;
  64139. t[2] = 255 - (y1 & 255);
  64140. t[3] = x2;
  64141. t[4] = 0;
  64142. ++lineY;
  64143. t += lineStrideElements;
  64144. while (lineY < (y2 >> 8))
  64145. {
  64146. t[0] = 2;
  64147. t[1] = x1;
  64148. t[2] = 255;
  64149. t[3] = x2;
  64150. t[4] = 0;
  64151. ++lineY;
  64152. t += lineStrideElements;
  64153. }
  64154. jassert (lineY < bounds.getHeight());
  64155. t[0] = 2;
  64156. t[1] = x1;
  64157. t[2] = y2 & 255;
  64158. t[3] = x2;
  64159. t[4] = 0;
  64160. ++lineY;
  64161. t += lineStrideElements;
  64162. }
  64163. while (lineY < bounds.getHeight())
  64164. {
  64165. t[0] = 0;
  64166. t += lineStrideElements;
  64167. ++lineY;
  64168. }
  64169. }
  64170. EdgeTable::EdgeTable (const EdgeTable& other)
  64171. {
  64172. operator= (other);
  64173. }
  64174. EdgeTable& EdgeTable::operator= (const EdgeTable& other)
  64175. {
  64176. bounds = other.bounds;
  64177. maxEdgesPerLine = other.maxEdgesPerLine;
  64178. lineStrideElements = other.lineStrideElements;
  64179. needToCheckEmptinesss = other.needToCheckEmptinesss;
  64180. table.malloc (jmax (1, bounds.getHeight()) * lineStrideElements);
  64181. copyEdgeTableData (table, lineStrideElements, other.table, lineStrideElements, bounds.getHeight());
  64182. return *this;
  64183. }
  64184. EdgeTable::~EdgeTable()
  64185. {
  64186. }
  64187. void EdgeTable::copyEdgeTableData (int* dest, const int destLineStride, const int* src, const int srcLineStride, int numLines) throw()
  64188. {
  64189. while (--numLines >= 0)
  64190. {
  64191. memcpy (dest, src, (src[0] * 2 + 1) * sizeof (int));
  64192. src += srcLineStride;
  64193. dest += destLineStride;
  64194. }
  64195. }
  64196. void EdgeTable::sanitiseLevels (const bool useNonZeroWinding) throw()
  64197. {
  64198. // Convert the table from relative windings to absolute levels..
  64199. int* lineStart = table;
  64200. for (int i = bounds.getHeight(); --i >= 0;)
  64201. {
  64202. int* line = lineStart;
  64203. lineStart += lineStrideElements;
  64204. int num = *line;
  64205. if (num == 0)
  64206. continue;
  64207. int level = 0;
  64208. if (useNonZeroWinding)
  64209. {
  64210. while (--num > 0)
  64211. {
  64212. line += 2;
  64213. level += *line;
  64214. int corrected = abs (level);
  64215. if (corrected >> 8)
  64216. corrected = 255;
  64217. *line = corrected;
  64218. }
  64219. }
  64220. else
  64221. {
  64222. while (--num > 0)
  64223. {
  64224. line += 2;
  64225. level += *line;
  64226. int corrected = abs (level);
  64227. if (corrected >> 8)
  64228. {
  64229. corrected &= 511;
  64230. if (corrected >> 8)
  64231. corrected = 511 - corrected;
  64232. }
  64233. *line = corrected;
  64234. }
  64235. }
  64236. line[2] = 0; // force the last level to 0, just in case something went wrong in creating the table
  64237. }
  64238. }
  64239. void EdgeTable::remapTableForNumEdges (const int newNumEdgesPerLine) throw()
  64240. {
  64241. if (newNumEdgesPerLine != maxEdgesPerLine)
  64242. {
  64243. maxEdgesPerLine = newNumEdgesPerLine;
  64244. jassert (bounds.getHeight() > 0);
  64245. const int newLineStrideElements = maxEdgesPerLine * 2 + 1;
  64246. HeapBlock <int> newTable (bounds.getHeight() * newLineStrideElements);
  64247. copyEdgeTableData (newTable, newLineStrideElements, table, lineStrideElements, bounds.getHeight());
  64248. table.swapWith (newTable);
  64249. lineStrideElements = newLineStrideElements;
  64250. }
  64251. }
  64252. void EdgeTable::optimiseTable() throw()
  64253. {
  64254. int maxLineElements = 0;
  64255. for (int i = bounds.getHeight(); --i >= 0;)
  64256. maxLineElements = jmax (maxLineElements, table [i * lineStrideElements]);
  64257. remapTableForNumEdges (maxLineElements);
  64258. }
  64259. void EdgeTable::addEdgePoint (const int x, const int y, const int winding) throw()
  64260. {
  64261. jassert (y >= 0 && y < bounds.getHeight());
  64262. int* line = table + lineStrideElements * y;
  64263. const int numPoints = line[0];
  64264. int n = numPoints << 1;
  64265. if (n > 0)
  64266. {
  64267. while (n > 0)
  64268. {
  64269. const int cx = line [n - 1];
  64270. if (cx <= x)
  64271. {
  64272. if (cx == x)
  64273. {
  64274. line [n] += winding;
  64275. return;
  64276. }
  64277. break;
  64278. }
  64279. n -= 2;
  64280. }
  64281. if (numPoints >= maxEdgesPerLine)
  64282. {
  64283. remapTableForNumEdges (maxEdgesPerLine + juce_edgeTableDefaultEdgesPerLine);
  64284. jassert (numPoints < maxEdgesPerLine);
  64285. line = table + lineStrideElements * y;
  64286. }
  64287. memmove (line + (n + 3), line + (n + 1), sizeof (int) * ((numPoints << 1) - n));
  64288. }
  64289. line [n + 1] = x;
  64290. line [n + 2] = winding;
  64291. line[0]++;
  64292. }
  64293. void EdgeTable::translate (float dx, const int dy) throw()
  64294. {
  64295. bounds.translate ((int) std::floor (dx), dy);
  64296. int* lineStart = table;
  64297. const int intDx = (int) (dx * 256.0f);
  64298. for (int i = bounds.getHeight(); --i >= 0;)
  64299. {
  64300. int* line = lineStart;
  64301. lineStart += lineStrideElements;
  64302. int num = *line++;
  64303. while (--num >= 0)
  64304. {
  64305. *line += intDx;
  64306. line += 2;
  64307. }
  64308. }
  64309. }
  64310. void EdgeTable::intersectWithEdgeTableLine (const int y, const int* otherLine) throw()
  64311. {
  64312. jassert (y >= 0 && y < bounds.getHeight());
  64313. int* dest = table + lineStrideElements * y;
  64314. if (dest[0] == 0)
  64315. return;
  64316. int otherNumPoints = *otherLine;
  64317. if (otherNumPoints == 0)
  64318. {
  64319. *dest = 0;
  64320. return;
  64321. }
  64322. const int right = bounds.getRight() << 8;
  64323. // optimise for the common case where our line lies entirely within a
  64324. // single pair of points, as happens when clipping to a simple rect.
  64325. if (otherNumPoints == 2 && otherLine[2] >= 255)
  64326. {
  64327. clipEdgeTableLineToRange (dest, otherLine[1], jmin (right, otherLine[3]));
  64328. return;
  64329. }
  64330. ++otherLine;
  64331. const size_t lineSizeBytes = (dest[0] * 2 + 1) * sizeof (int);
  64332. int* temp = (int*) alloca (lineSizeBytes);
  64333. memcpy (temp, dest, lineSizeBytes);
  64334. const int* src1 = temp;
  64335. int srcNum1 = *src1++;
  64336. int x1 = *src1++;
  64337. const int* src2 = otherLine;
  64338. int srcNum2 = otherNumPoints;
  64339. int x2 = *src2++;
  64340. int destIndex = 0, destTotal = 0;
  64341. int level1 = 0, level2 = 0;
  64342. int lastX = std::numeric_limits<int>::min(), lastLevel = 0;
  64343. while (srcNum1 > 0 && srcNum2 > 0)
  64344. {
  64345. int nextX;
  64346. if (x1 < x2)
  64347. {
  64348. nextX = x1;
  64349. level1 = *src1++;
  64350. x1 = *src1++;
  64351. --srcNum1;
  64352. }
  64353. else if (x1 == x2)
  64354. {
  64355. nextX = x1;
  64356. level1 = *src1++;
  64357. level2 = *src2++;
  64358. x1 = *src1++;
  64359. x2 = *src2++;
  64360. --srcNum1;
  64361. --srcNum2;
  64362. }
  64363. else
  64364. {
  64365. nextX = x2;
  64366. level2 = *src2++;
  64367. x2 = *src2++;
  64368. --srcNum2;
  64369. }
  64370. if (nextX > lastX)
  64371. {
  64372. if (nextX >= right)
  64373. break;
  64374. lastX = nextX;
  64375. const int nextLevel = (level1 * (level2 + 1)) >> 8;
  64376. jassert (((unsigned int) nextLevel) < (unsigned int) 256);
  64377. if (nextLevel != lastLevel)
  64378. {
  64379. if (destTotal >= maxEdgesPerLine)
  64380. {
  64381. dest[0] = destTotal;
  64382. remapTableForNumEdges (maxEdgesPerLine + juce_edgeTableDefaultEdgesPerLine);
  64383. dest = table + lineStrideElements * y;
  64384. }
  64385. ++destTotal;
  64386. lastLevel = nextLevel;
  64387. dest[++destIndex] = nextX;
  64388. dest[++destIndex] = nextLevel;
  64389. }
  64390. }
  64391. }
  64392. if (lastLevel > 0)
  64393. {
  64394. if (destTotal >= maxEdgesPerLine)
  64395. {
  64396. dest[0] = destTotal;
  64397. remapTableForNumEdges (maxEdgesPerLine + juce_edgeTableDefaultEdgesPerLine);
  64398. dest = table + lineStrideElements * y;
  64399. }
  64400. ++destTotal;
  64401. dest[++destIndex] = right;
  64402. dest[++destIndex] = 0;
  64403. }
  64404. dest[0] = destTotal;
  64405. #if JUCE_DEBUG
  64406. int last = std::numeric_limits<int>::min();
  64407. for (int i = 0; i < dest[0]; ++i)
  64408. {
  64409. jassert (dest[i * 2 + 1] > last);
  64410. last = dest[i * 2 + 1];
  64411. }
  64412. jassert (dest [dest[0] * 2] == 0);
  64413. #endif
  64414. }
  64415. void EdgeTable::clipEdgeTableLineToRange (int* dest, const int x1, const int x2) throw()
  64416. {
  64417. int* lastItem = dest + (dest[0] * 2 - 1);
  64418. if (x2 < lastItem[0])
  64419. {
  64420. if (x2 <= dest[1])
  64421. {
  64422. dest[0] = 0;
  64423. return;
  64424. }
  64425. while (x2 < lastItem[-2])
  64426. {
  64427. --(dest[0]);
  64428. lastItem -= 2;
  64429. }
  64430. lastItem[0] = x2;
  64431. lastItem[1] = 0;
  64432. }
  64433. if (x1 > dest[1])
  64434. {
  64435. while (lastItem[0] > x1)
  64436. lastItem -= 2;
  64437. const int itemsRemoved = (int) (lastItem - (dest + 1)) / 2;
  64438. if (itemsRemoved > 0)
  64439. {
  64440. dest[0] -= itemsRemoved;
  64441. memmove (dest + 1, lastItem, dest[0] * (sizeof (int) * 2));
  64442. }
  64443. dest[1] = x1;
  64444. }
  64445. }
  64446. void EdgeTable::clipToRectangle (const Rectangle<int>& r) throw()
  64447. {
  64448. const Rectangle<int> clipped (r.getIntersection (bounds));
  64449. if (clipped.isEmpty())
  64450. {
  64451. needToCheckEmptinesss = false;
  64452. bounds.setHeight (0);
  64453. }
  64454. else
  64455. {
  64456. const int top = clipped.getY() - bounds.getY();
  64457. const int bottom = clipped.getBottom() - bounds.getY();
  64458. if (bottom < bounds.getHeight())
  64459. bounds.setHeight (bottom);
  64460. if (clipped.getRight() < bounds.getRight())
  64461. bounds.setRight (clipped.getRight());
  64462. for (int i = top; --i >= 0;)
  64463. table [lineStrideElements * i] = 0;
  64464. if (clipped.getX() > bounds.getX())
  64465. {
  64466. const int x1 = clipped.getX() << 8;
  64467. const int x2 = jmin (bounds.getRight(), clipped.getRight()) << 8;
  64468. int* line = table + lineStrideElements * top;
  64469. for (int i = bottom - top; --i >= 0;)
  64470. {
  64471. if (line[0] != 0)
  64472. clipEdgeTableLineToRange (line, x1, x2);
  64473. line += lineStrideElements;
  64474. }
  64475. }
  64476. needToCheckEmptinesss = true;
  64477. }
  64478. }
  64479. void EdgeTable::excludeRectangle (const Rectangle<int>& r) throw()
  64480. {
  64481. const Rectangle<int> clipped (r.getIntersection (bounds));
  64482. if (! clipped.isEmpty())
  64483. {
  64484. const int top = clipped.getY() - bounds.getY();
  64485. const int bottom = clipped.getBottom() - bounds.getY();
  64486. //XXX optimise here by shortening the table if it fills top or bottom
  64487. const int rectLine[] = { 4, std::numeric_limits<int>::min(), 255,
  64488. clipped.getX() << 8, 0,
  64489. clipped.getRight() << 8, 255,
  64490. std::numeric_limits<int>::max(), 0 };
  64491. for (int i = top; i < bottom; ++i)
  64492. intersectWithEdgeTableLine (i, rectLine);
  64493. needToCheckEmptinesss = true;
  64494. }
  64495. }
  64496. void EdgeTable::clipToEdgeTable (const EdgeTable& other)
  64497. {
  64498. const Rectangle<int> clipped (other.bounds.getIntersection (bounds));
  64499. if (clipped.isEmpty())
  64500. {
  64501. needToCheckEmptinesss = false;
  64502. bounds.setHeight (0);
  64503. }
  64504. else
  64505. {
  64506. const int top = clipped.getY() - bounds.getY();
  64507. const int bottom = clipped.getBottom() - bounds.getY();
  64508. if (bottom < bounds.getHeight())
  64509. bounds.setHeight (bottom);
  64510. if (clipped.getRight() < bounds.getRight())
  64511. bounds.setRight (clipped.getRight());
  64512. int i = 0;
  64513. for (i = top; --i >= 0;)
  64514. table [lineStrideElements * i] = 0;
  64515. const int* otherLine = other.table + other.lineStrideElements * (clipped.getY() - other.bounds.getY());
  64516. for (i = top; i < bottom; ++i)
  64517. {
  64518. intersectWithEdgeTableLine (i, otherLine);
  64519. otherLine += other.lineStrideElements;
  64520. }
  64521. needToCheckEmptinesss = true;
  64522. }
  64523. }
  64524. void EdgeTable::clipLineToMask (int x, int y, const uint8* mask, int maskStride, int numPixels) throw()
  64525. {
  64526. y -= bounds.getY();
  64527. if (y < 0 || y >= bounds.getHeight())
  64528. return;
  64529. needToCheckEmptinesss = true;
  64530. if (numPixels <= 0)
  64531. {
  64532. table [lineStrideElements * y] = 0;
  64533. return;
  64534. }
  64535. int* tempLine = (int*) alloca ((numPixels * 2 + 4) * sizeof (int));
  64536. int destIndex = 0, lastLevel = 0;
  64537. while (--numPixels >= 0)
  64538. {
  64539. const int alpha = *mask;
  64540. mask += maskStride;
  64541. if (alpha != lastLevel)
  64542. {
  64543. tempLine[++destIndex] = (x << 8);
  64544. tempLine[++destIndex] = alpha;
  64545. lastLevel = alpha;
  64546. }
  64547. ++x;
  64548. }
  64549. if (lastLevel > 0)
  64550. {
  64551. tempLine[++destIndex] = (x << 8);
  64552. tempLine[++destIndex] = 0;
  64553. }
  64554. tempLine[0] = destIndex >> 1;
  64555. intersectWithEdgeTableLine (y, tempLine);
  64556. }
  64557. bool EdgeTable::isEmpty() throw()
  64558. {
  64559. if (needToCheckEmptinesss)
  64560. {
  64561. needToCheckEmptinesss = false;
  64562. int* t = table;
  64563. for (int i = bounds.getHeight(); --i >= 0;)
  64564. {
  64565. if (t[0] > 1)
  64566. return false;
  64567. t += lineStrideElements;
  64568. }
  64569. bounds.setHeight (0);
  64570. }
  64571. return bounds.getHeight() == 0;
  64572. }
  64573. END_JUCE_NAMESPACE
  64574. /*** End of inlined file: juce_EdgeTable.cpp ***/
  64575. /*** Start of inlined file: juce_FillType.cpp ***/
  64576. BEGIN_JUCE_NAMESPACE
  64577. FillType::FillType() throw()
  64578. : colour (0xff000000), image (0)
  64579. {
  64580. }
  64581. FillType::FillType (const Colour& colour_) throw()
  64582. : colour (colour_), image (0)
  64583. {
  64584. }
  64585. FillType::FillType (const ColourGradient& gradient_)
  64586. : colour (0xff000000), gradient (new ColourGradient (gradient_)), image (0)
  64587. {
  64588. }
  64589. FillType::FillType (const Image& image_, const AffineTransform& transform_) throw()
  64590. : colour (0xff000000), image (&image_), transform (transform_)
  64591. {
  64592. }
  64593. FillType::FillType (const FillType& other)
  64594. : colour (other.colour),
  64595. gradient (other.gradient != 0 ? new ColourGradient (*other.gradient) : 0),
  64596. image (other.image), transform (other.transform)
  64597. {
  64598. }
  64599. FillType& FillType::operator= (const FillType& other)
  64600. {
  64601. if (this != &other)
  64602. {
  64603. colour = other.colour;
  64604. gradient = (other.gradient != 0 ? new ColourGradient (*other.gradient) : 0);
  64605. image = other.image;
  64606. transform = other.transform;
  64607. }
  64608. return *this;
  64609. }
  64610. FillType::~FillType() throw()
  64611. {
  64612. }
  64613. void FillType::setColour (const Colour& newColour) throw()
  64614. {
  64615. gradient = 0;
  64616. image = 0;
  64617. colour = newColour;
  64618. }
  64619. void FillType::setGradient (const ColourGradient& newGradient)
  64620. {
  64621. if (gradient != 0)
  64622. {
  64623. *gradient = newGradient;
  64624. }
  64625. else
  64626. {
  64627. image = 0;
  64628. gradient = new ColourGradient (newGradient);
  64629. colour = Colours::black;
  64630. }
  64631. }
  64632. void FillType::setTiledImage (const Image& image_, const AffineTransform& transform_) throw()
  64633. {
  64634. gradient = 0;
  64635. image = &image_;
  64636. transform = transform_;
  64637. colour = Colours::black;
  64638. }
  64639. void FillType::setOpacity (const float newOpacity) throw()
  64640. {
  64641. colour = colour.withAlpha (newOpacity);
  64642. }
  64643. END_JUCE_NAMESPACE
  64644. /*** End of inlined file: juce_FillType.cpp ***/
  64645. /*** Start of inlined file: juce_Graphics.cpp ***/
  64646. BEGIN_JUCE_NAMESPACE
  64647. static const Graphics::ResamplingQuality defaultQuality = Graphics::mediumResamplingQuality;
  64648. template <typename Type>
  64649. static bool areCoordsSensibleNumbers (Type x, Type y, Type w, Type h)
  64650. {
  64651. const int maxVal = 0x3fffffff;
  64652. return (int) x >= -maxVal && (int) x <= maxVal
  64653. && (int) y >= -maxVal && (int) y <= maxVal
  64654. && (int) w >= -maxVal && (int) w <= maxVal
  64655. && (int) h >= -maxVal && (int) h <= maxVal;
  64656. }
  64657. LowLevelGraphicsContext::LowLevelGraphicsContext()
  64658. {
  64659. }
  64660. LowLevelGraphicsContext::~LowLevelGraphicsContext()
  64661. {
  64662. }
  64663. Graphics::Graphics (Image& imageToDrawOnto)
  64664. : context (imageToDrawOnto.createLowLevelContext()),
  64665. contextToDelete (context),
  64666. saveStatePending (false)
  64667. {
  64668. }
  64669. Graphics::Graphics (LowLevelGraphicsContext* const internalContext) throw()
  64670. : context (internalContext),
  64671. saveStatePending (false)
  64672. {
  64673. }
  64674. Graphics::~Graphics()
  64675. {
  64676. }
  64677. void Graphics::resetToDefaultState()
  64678. {
  64679. saveStateIfPending();
  64680. context->setFill (FillType());
  64681. context->setFont (Font());
  64682. context->setInterpolationQuality (defaultQuality);
  64683. }
  64684. bool Graphics::isVectorDevice() const
  64685. {
  64686. return context->isVectorDevice();
  64687. }
  64688. bool Graphics::reduceClipRegion (const int x, const int y, const int w, const int h)
  64689. {
  64690. saveStateIfPending();
  64691. return context->clipToRectangle (Rectangle<int> (x, y, w, h));
  64692. }
  64693. bool Graphics::reduceClipRegion (const RectangleList& clipRegion)
  64694. {
  64695. saveStateIfPending();
  64696. return context->clipToRectangleList (clipRegion);
  64697. }
  64698. bool Graphics::reduceClipRegion (const Path& path, const AffineTransform& transform)
  64699. {
  64700. saveStateIfPending();
  64701. context->clipToPath (path, transform);
  64702. return ! context->isClipEmpty();
  64703. }
  64704. bool Graphics::reduceClipRegion (const Image& image, const Rectangle<int>& sourceClipRegion, const AffineTransform& transform)
  64705. {
  64706. saveStateIfPending();
  64707. context->clipToImageAlpha (image, sourceClipRegion, transform);
  64708. return ! context->isClipEmpty();
  64709. }
  64710. void Graphics::excludeClipRegion (const Rectangle<int>& rectangleToExclude)
  64711. {
  64712. saveStateIfPending();
  64713. context->excludeClipRectangle (rectangleToExclude);
  64714. }
  64715. bool Graphics::isClipEmpty() const
  64716. {
  64717. return context->isClipEmpty();
  64718. }
  64719. const Rectangle<int> Graphics::getClipBounds() const
  64720. {
  64721. return context->getClipBounds();
  64722. }
  64723. void Graphics::saveState()
  64724. {
  64725. saveStateIfPending();
  64726. saveStatePending = true;
  64727. }
  64728. void Graphics::restoreState()
  64729. {
  64730. if (saveStatePending)
  64731. saveStatePending = false;
  64732. else
  64733. context->restoreState();
  64734. }
  64735. void Graphics::saveStateIfPending()
  64736. {
  64737. if (saveStatePending)
  64738. {
  64739. saveStatePending = false;
  64740. context->saveState();
  64741. }
  64742. }
  64743. void Graphics::setOrigin (const int newOriginX, const int newOriginY)
  64744. {
  64745. saveStateIfPending();
  64746. context->setOrigin (newOriginX, newOriginY);
  64747. }
  64748. bool Graphics::clipRegionIntersects (const int x, const int y, const int w, const int h) const
  64749. {
  64750. return context->clipRegionIntersects (Rectangle<int> (x, y, w, h));
  64751. }
  64752. void Graphics::setColour (const Colour& newColour)
  64753. {
  64754. saveStateIfPending();
  64755. context->setFill (newColour);
  64756. }
  64757. void Graphics::setOpacity (const float newOpacity)
  64758. {
  64759. saveStateIfPending();
  64760. context->setOpacity (newOpacity);
  64761. }
  64762. void Graphics::setGradientFill (const ColourGradient& gradient)
  64763. {
  64764. setFillType (gradient);
  64765. }
  64766. void Graphics::setTiledImageFill (const Image& imageToUse, const int anchorX, const int anchorY, const float opacity)
  64767. {
  64768. saveStateIfPending();
  64769. context->setFill (FillType (imageToUse, AffineTransform::translation ((float) anchorX, (float) anchorY)));
  64770. context->setOpacity (opacity);
  64771. }
  64772. void Graphics::setFillType (const FillType& newFill)
  64773. {
  64774. saveStateIfPending();
  64775. context->setFill (newFill);
  64776. }
  64777. void Graphics::setFont (const Font& newFont)
  64778. {
  64779. saveStateIfPending();
  64780. context->setFont (newFont);
  64781. }
  64782. void Graphics::setFont (const float newFontHeight, const int newFontStyleFlags)
  64783. {
  64784. saveStateIfPending();
  64785. Font f (context->getFont());
  64786. f.setSizeAndStyle (newFontHeight, newFontStyleFlags, 1.0f, 0);
  64787. context->setFont (f);
  64788. }
  64789. void Graphics::drawSingleLineText (const String& text, const int startX, const int baselineY) const
  64790. {
  64791. if (text.isNotEmpty()
  64792. && startX < context->getClipBounds().getRight())
  64793. {
  64794. GlyphArrangement arr;
  64795. arr.addLineOfText (context->getFont(), text, (float) startX, (float) baselineY);
  64796. arr.draw (*this);
  64797. }
  64798. }
  64799. void Graphics::drawTextAsPath (const String& text, const AffineTransform& transform) const
  64800. {
  64801. if (text.isNotEmpty())
  64802. {
  64803. GlyphArrangement arr;
  64804. arr.addLineOfText (context->getFont(), text, 0.0f, 0.0f);
  64805. arr.draw (*this, transform);
  64806. }
  64807. }
  64808. void Graphics::drawMultiLineText (const String& text, const int startX, const int baselineY, const int maximumLineWidth) const
  64809. {
  64810. if (text.isNotEmpty()
  64811. && startX < context->getClipBounds().getRight())
  64812. {
  64813. GlyphArrangement arr;
  64814. arr.addJustifiedText (context->getFont(), text,
  64815. (float) startX, (float) baselineY, (float) maximumLineWidth,
  64816. Justification::left);
  64817. arr.draw (*this);
  64818. }
  64819. }
  64820. void Graphics::drawText (const String& text,
  64821. const int x, const int y, const int width, const int height,
  64822. const Justification& justificationType,
  64823. const bool useEllipsesIfTooBig) const
  64824. {
  64825. if (text.isNotEmpty() && context->clipRegionIntersects (Rectangle<int> (x, y, width, height)))
  64826. {
  64827. GlyphArrangement arr;
  64828. arr.addCurtailedLineOfText (context->getFont(), text,
  64829. 0.0f, 0.0f, (float) width,
  64830. useEllipsesIfTooBig);
  64831. arr.justifyGlyphs (0, arr.getNumGlyphs(),
  64832. (float) x, (float) y, (float) width, (float) height,
  64833. justificationType);
  64834. arr.draw (*this);
  64835. }
  64836. }
  64837. void Graphics::drawFittedText (const String& text,
  64838. const int x, const int y, const int width, const int height,
  64839. const Justification& justification,
  64840. const int maximumNumberOfLines,
  64841. const float minimumHorizontalScale) const
  64842. {
  64843. if (text.isNotEmpty()
  64844. && width > 0 && height > 0
  64845. && context->clipRegionIntersects (Rectangle<int> (x, y, width, height)))
  64846. {
  64847. GlyphArrangement arr;
  64848. arr.addFittedText (context->getFont(), text,
  64849. (float) x, (float) y, (float) width, (float) height,
  64850. justification,
  64851. maximumNumberOfLines,
  64852. minimumHorizontalScale);
  64853. arr.draw (*this);
  64854. }
  64855. }
  64856. void Graphics::fillRect (int x, int y, int width, int height) const
  64857. {
  64858. // passing in a silly number can cause maths problems in rendering!
  64859. jassert (areCoordsSensibleNumbers (x, y, width, height));
  64860. context->fillRect (Rectangle<int> (x, y, width, height), false);
  64861. }
  64862. void Graphics::fillRect (const Rectangle<int>& r) const
  64863. {
  64864. context->fillRect (r, false);
  64865. }
  64866. void Graphics::fillRect (const float x, const float y, const float width, const float height) const
  64867. {
  64868. // passing in a silly number can cause maths problems in rendering!
  64869. jassert (areCoordsSensibleNumbers (x, y, width, height));
  64870. Path p;
  64871. p.addRectangle (x, y, width, height);
  64872. fillPath (p);
  64873. }
  64874. void Graphics::setPixel (int x, int y) const
  64875. {
  64876. context->fillRect (Rectangle<int> (x, y, 1, 1), false);
  64877. }
  64878. void Graphics::fillAll() const
  64879. {
  64880. fillRect (context->getClipBounds());
  64881. }
  64882. void Graphics::fillAll (const Colour& colourToUse) const
  64883. {
  64884. if (! colourToUse.isTransparent())
  64885. {
  64886. const Rectangle<int> clip (context->getClipBounds());
  64887. context->saveState();
  64888. context->setFill (colourToUse);
  64889. context->fillRect (clip, false);
  64890. context->restoreState();
  64891. }
  64892. }
  64893. void Graphics::fillPath (const Path& path, const AffineTransform& transform) const
  64894. {
  64895. if ((! context->isClipEmpty()) && ! path.isEmpty())
  64896. context->fillPath (path, transform);
  64897. }
  64898. void Graphics::strokePath (const Path& path,
  64899. const PathStrokeType& strokeType,
  64900. const AffineTransform& transform) const
  64901. {
  64902. Path stroke;
  64903. strokeType.createStrokedPath (stroke, path, transform);
  64904. fillPath (stroke);
  64905. }
  64906. void Graphics::drawRect (const int x, const int y, const int width, const int height,
  64907. const int lineThickness) const
  64908. {
  64909. // passing in a silly number can cause maths problems in rendering!
  64910. jassert (areCoordsSensibleNumbers (x, y, width, height));
  64911. context->fillRect (Rectangle<int> (x, y, width, lineThickness), false);
  64912. context->fillRect (Rectangle<int> (x, y + lineThickness, lineThickness, height - lineThickness * 2), false);
  64913. context->fillRect (Rectangle<int> (x + width - lineThickness, y + lineThickness, lineThickness, height - lineThickness * 2), false);
  64914. context->fillRect (Rectangle<int> (x, y + height - lineThickness, width, lineThickness), false);
  64915. }
  64916. void Graphics::drawRect (const float x, const float y, const float width, const float height, const float lineThickness) const
  64917. {
  64918. // passing in a silly number can cause maths problems in rendering!
  64919. jassert (areCoordsSensibleNumbers (x, y, width, height));
  64920. Path p;
  64921. p.addRectangle (x, y, width, lineThickness);
  64922. p.addRectangle (x, y + lineThickness, lineThickness, height - lineThickness * 2.0f);
  64923. p.addRectangle (x + width - lineThickness, y + lineThickness, lineThickness, height - lineThickness * 2.0f);
  64924. p.addRectangle (x, y + height - lineThickness, width, lineThickness);
  64925. fillPath (p);
  64926. }
  64927. void Graphics::drawRect (const Rectangle<int>& r, const int lineThickness) const
  64928. {
  64929. drawRect (r.getX(), r.getY(), r.getWidth(), r.getHeight(), lineThickness);
  64930. }
  64931. void Graphics::drawBevel (const int x, const int y, const int width, const int height,
  64932. const int bevelThickness, const Colour& topLeftColour, const Colour& bottomRightColour,
  64933. const bool useGradient, const bool sharpEdgeOnOutside) const
  64934. {
  64935. // passing in a silly number can cause maths problems in rendering!
  64936. jassert (areCoordsSensibleNumbers (x, y, width, height));
  64937. if (clipRegionIntersects (x, y, width, height))
  64938. {
  64939. context->saveState();
  64940. const float oldOpacity = 1.0f;//xxx state->colour.getFloatAlpha();
  64941. const float ramp = oldOpacity / bevelThickness;
  64942. for (int i = bevelThickness; --i >= 0;)
  64943. {
  64944. const float op = useGradient ? ramp * (sharpEdgeOnOutside ? bevelThickness - i : i)
  64945. : oldOpacity;
  64946. context->setFill (topLeftColour.withMultipliedAlpha (op));
  64947. context->fillRect (Rectangle<int> (x + i, y + i, width - i * 2, 1), false);
  64948. context->setFill (topLeftColour.withMultipliedAlpha (op * 0.75f));
  64949. context->fillRect (Rectangle<int> (x + i, y + i + 1, 1, height - i * 2 - 2), false);
  64950. context->setFill (bottomRightColour.withMultipliedAlpha (op));
  64951. context->fillRect (Rectangle<int> (x + i, y + height - i - 1, width - i * 2, 1), false);
  64952. context->setFill (bottomRightColour.withMultipliedAlpha (op * 0.75f));
  64953. context->fillRect (Rectangle<int> (x + width - i - 1, y + i + 1, 1, height - i * 2 - 2), false);
  64954. }
  64955. context->restoreState();
  64956. }
  64957. }
  64958. void Graphics::fillEllipse (const float x, const float y, const float width, const float height) const
  64959. {
  64960. // passing in a silly number can cause maths problems in rendering!
  64961. jassert (areCoordsSensibleNumbers (x, y, width, height));
  64962. Path p;
  64963. p.addEllipse (x, y, width, height);
  64964. fillPath (p);
  64965. }
  64966. void Graphics::drawEllipse (const float x, const float y, const float width, const float height,
  64967. const float lineThickness) const
  64968. {
  64969. // passing in a silly number can cause maths problems in rendering!
  64970. jassert (areCoordsSensibleNumbers (x, y, width, height));
  64971. Path p;
  64972. p.addEllipse (x, y, width, height);
  64973. strokePath (p, PathStrokeType (lineThickness));
  64974. }
  64975. void Graphics::fillRoundedRectangle (const float x, const float y, const float width, const float height, const float cornerSize) const
  64976. {
  64977. // passing in a silly number can cause maths problems in rendering!
  64978. jassert (areCoordsSensibleNumbers (x, y, width, height));
  64979. Path p;
  64980. p.addRoundedRectangle (x, y, width, height, cornerSize);
  64981. fillPath (p);
  64982. }
  64983. void Graphics::fillRoundedRectangle (const Rectangle<float>& r, const float cornerSize) const
  64984. {
  64985. fillRoundedRectangle (r.getX(), r.getY(), r.getWidth(), r.getHeight(), cornerSize);
  64986. }
  64987. void Graphics::drawRoundedRectangle (const float x, const float y, const float width, const float height,
  64988. const float cornerSize, const float lineThickness) const
  64989. {
  64990. // passing in a silly number can cause maths problems in rendering!
  64991. jassert (areCoordsSensibleNumbers (x, y, width, height));
  64992. Path p;
  64993. p.addRoundedRectangle (x, y, width, height, cornerSize);
  64994. strokePath (p, PathStrokeType (lineThickness));
  64995. }
  64996. void Graphics::drawRoundedRectangle (const Rectangle<float>& r, const float cornerSize, const float lineThickness) const
  64997. {
  64998. drawRoundedRectangle (r.getX(), r.getY(), r.getWidth(), r.getHeight(), cornerSize, lineThickness);
  64999. }
  65000. void Graphics::drawArrow (const float startX, const float startY, const float endX, const float endY,
  65001. const float lineThickness, const float arrowheadWidth, const float arrowheadLength) const
  65002. {
  65003. Path p;
  65004. p.addArrow (startX, startY, endX, endY,
  65005. lineThickness, arrowheadWidth, arrowheadLength);
  65006. fillPath (p);
  65007. }
  65008. void Graphics::fillCheckerBoard (int x, int y, int width, int height,
  65009. const int checkWidth, const int checkHeight,
  65010. const Colour& colour1, const Colour& colour2) const
  65011. {
  65012. jassert (checkWidth > 0 && checkHeight > 0); // can't be zero or less!
  65013. if (checkWidth > 0 && checkHeight > 0)
  65014. {
  65015. context->saveState();
  65016. if (colour1 == colour2)
  65017. {
  65018. context->setFill (colour1);
  65019. context->fillRect (Rectangle<int> (x, y, width, height), false);
  65020. }
  65021. else
  65022. {
  65023. const Rectangle<int> clip (context->getClipBounds());
  65024. const int right = jmin (x + width, clip.getRight());
  65025. const int bottom = jmin (y + height, clip.getBottom());
  65026. int cy = 0;
  65027. while (y < bottom)
  65028. {
  65029. int cx = cy;
  65030. for (int xx = x; xx < right; xx += checkWidth)
  65031. {
  65032. context->setFill (((cx++ & 1) == 0) ? colour1 : colour2);
  65033. context->fillRect (Rectangle<int> (xx, y, jmin (checkWidth, right - xx), jmin (checkHeight, bottom - y)),
  65034. false);
  65035. }
  65036. ++cy;
  65037. y += checkHeight;
  65038. }
  65039. }
  65040. context->restoreState();
  65041. }
  65042. }
  65043. void Graphics::drawVerticalLine (const int x, float top, float bottom) const
  65044. {
  65045. context->drawVerticalLine (x, top, bottom);
  65046. }
  65047. void Graphics::drawHorizontalLine (const int y, float left, float right) const
  65048. {
  65049. context->drawHorizontalLine (y, left, right);
  65050. }
  65051. void Graphics::drawLine (float x1, float y1, float x2, float y2) const
  65052. {
  65053. context->drawLine (x1, y1, x2, y2);
  65054. }
  65055. void Graphics::drawLine (const float startX, const float startY,
  65056. const float endX, const float endY,
  65057. const float lineThickness) const
  65058. {
  65059. Path p;
  65060. p.addLineSegment (startX, startY, endX, endY, lineThickness);
  65061. fillPath (p);
  65062. }
  65063. void Graphics::drawLine (const Line<float>& line) const
  65064. {
  65065. drawLine (line.getStartX(), line.getStartY(), line.getEndX(), line.getEndY());
  65066. }
  65067. void Graphics::drawLine (const Line<float>& line, const float lineThickness) const
  65068. {
  65069. drawLine (line.getStartX(), line.getStartY(), line.getEndX(), line.getEndY(), lineThickness);
  65070. }
  65071. void Graphics::drawDashedLine (const float startX, const float startY,
  65072. const float endX, const float endY,
  65073. const float* const dashLengths,
  65074. const int numDashLengths,
  65075. const float lineThickness) const
  65076. {
  65077. const double dx = endX - startX;
  65078. const double dy = endY - startY;
  65079. const double totalLen = juce_hypot (dx, dy);
  65080. if (totalLen >= 0.5)
  65081. {
  65082. const double onePixAlpha = 1.0 / totalLen;
  65083. double alpha = 0.0;
  65084. float x = startX;
  65085. float y = startY;
  65086. int n = 0;
  65087. while (alpha < 1.0f)
  65088. {
  65089. alpha = jmin (1.0, alpha + dashLengths[n++] * onePixAlpha);
  65090. n = n % numDashLengths;
  65091. const float oldX = x;
  65092. const float oldY = y;
  65093. x = (float) (startX + dx * alpha);
  65094. y = (float) (startY + dy * alpha);
  65095. if ((n & 1) != 0)
  65096. {
  65097. if (lineThickness != 1.0f)
  65098. drawLine (oldX, oldY, x, y, lineThickness);
  65099. else
  65100. drawLine (oldX, oldY, x, y);
  65101. }
  65102. }
  65103. }
  65104. }
  65105. void Graphics::setImageResamplingQuality (const Graphics::ResamplingQuality newQuality)
  65106. {
  65107. saveStateIfPending();
  65108. context->setInterpolationQuality (newQuality);
  65109. }
  65110. void Graphics::drawImageAt (const Image* const imageToDraw,
  65111. const int topLeftX, const int topLeftY,
  65112. const bool fillAlphaChannelWithCurrentBrush) const
  65113. {
  65114. if (imageToDraw != 0)
  65115. {
  65116. const int imageW = imageToDraw->getWidth();
  65117. const int imageH = imageToDraw->getHeight();
  65118. drawImage (imageToDraw,
  65119. topLeftX, topLeftY, imageW, imageH,
  65120. 0, 0, imageW, imageH,
  65121. fillAlphaChannelWithCurrentBrush);
  65122. }
  65123. }
  65124. void Graphics::drawImageWithin (const Image* const imageToDraw,
  65125. const int destX, const int destY,
  65126. const int destW, const int destH,
  65127. const RectanglePlacement& placementWithinTarget,
  65128. const bool fillAlphaChannelWithCurrentBrush) const
  65129. {
  65130. // passing in a silly number can cause maths problems in rendering!
  65131. jassert (areCoordsSensibleNumbers (destX, destY, destW, destH));
  65132. if (imageToDraw != 0)
  65133. {
  65134. const int imageW = imageToDraw->getWidth();
  65135. const int imageH = imageToDraw->getHeight();
  65136. if (imageW > 0 && imageH > 0)
  65137. {
  65138. double newX = 0.0, newY = 0.0;
  65139. double newW = imageW;
  65140. double newH = imageH;
  65141. placementWithinTarget.applyTo (newX, newY, newW, newH,
  65142. destX, destY, destW, destH);
  65143. if (newW > 0 && newH > 0)
  65144. {
  65145. drawImage (imageToDraw,
  65146. roundToInt (newX), roundToInt (newY),
  65147. roundToInt (newW), roundToInt (newH),
  65148. 0, 0, imageW, imageH,
  65149. fillAlphaChannelWithCurrentBrush);
  65150. }
  65151. }
  65152. }
  65153. }
  65154. void Graphics::drawImage (const Image* const imageToDraw,
  65155. int dx, int dy, int dw, int dh,
  65156. int sx, int sy, int sw, int sh,
  65157. const bool fillAlphaChannelWithCurrentBrush) const
  65158. {
  65159. // passing in a silly number can cause maths problems in rendering!
  65160. jassert (areCoordsSensibleNumbers (dx, dy, dw, dh));
  65161. jassert (areCoordsSensibleNumbers (sx, sy, sw, sh));
  65162. if (context->clipRegionIntersects (Rectangle<int> (dx, dy, dw, dh)))
  65163. {
  65164. drawImageTransformed (imageToDraw, Rectangle<int> (sx, sy, sw, sh),
  65165. AffineTransform::scale (dw / (float) sw, dh / (float) sh)
  65166. .translated ((float) dx, (float) dy),
  65167. fillAlphaChannelWithCurrentBrush);
  65168. }
  65169. }
  65170. void Graphics::drawImageTransformed (const Image* const imageToDraw,
  65171. const Rectangle<int>& imageSubRegion,
  65172. const AffineTransform& transform,
  65173. const bool fillAlphaChannelWithCurrentBrush) const
  65174. {
  65175. if (imageToDraw != 0 && ! context->isClipEmpty())
  65176. {
  65177. const Rectangle<int> srcClip (imageSubRegion.getIntersection (imageToDraw->getBounds()));
  65178. if (fillAlphaChannelWithCurrentBrush)
  65179. {
  65180. context->saveState();
  65181. context->clipToImageAlpha (*imageToDraw, srcClip, transform);
  65182. fillAll();
  65183. context->restoreState();
  65184. }
  65185. else
  65186. {
  65187. context->drawImage (*imageToDraw, srcClip, transform, false);
  65188. }
  65189. }
  65190. }
  65191. END_JUCE_NAMESPACE
  65192. /*** End of inlined file: juce_Graphics.cpp ***/
  65193. /*** Start of inlined file: juce_Justification.cpp ***/
  65194. BEGIN_JUCE_NAMESPACE
  65195. Justification::Justification (const Justification& other) throw()
  65196. : flags (other.flags)
  65197. {
  65198. }
  65199. Justification& Justification::operator= (const Justification& other) throw()
  65200. {
  65201. flags = other.flags;
  65202. return *this;
  65203. }
  65204. int Justification::getOnlyVerticalFlags() const throw()
  65205. {
  65206. return flags & (top | bottom | verticallyCentred);
  65207. }
  65208. int Justification::getOnlyHorizontalFlags() const throw()
  65209. {
  65210. return flags & (left | right | horizontallyCentred | horizontallyJustified);
  65211. }
  65212. void Justification::applyToRectangle (int& x, int& y,
  65213. const int w, const int h,
  65214. const int spaceX, const int spaceY,
  65215. const int spaceW, const int spaceH) const throw()
  65216. {
  65217. if ((flags & horizontallyCentred) != 0)
  65218. {
  65219. x = spaceX + ((spaceW - w) >> 1);
  65220. }
  65221. else if ((flags & right) != 0)
  65222. {
  65223. x = spaceX + spaceW - w;
  65224. }
  65225. else
  65226. {
  65227. x = spaceX;
  65228. }
  65229. if ((flags & verticallyCentred) != 0)
  65230. {
  65231. y = spaceY + ((spaceH - h) >> 1);
  65232. }
  65233. else if ((flags & bottom) != 0)
  65234. {
  65235. y = spaceY + spaceH - h;
  65236. }
  65237. else
  65238. {
  65239. y = spaceY;
  65240. }
  65241. }
  65242. END_JUCE_NAMESPACE
  65243. /*** End of inlined file: juce_Justification.cpp ***/
  65244. /*** Start of inlined file: juce_LowLevelGraphicsPostScriptRenderer.cpp ***/
  65245. BEGIN_JUCE_NAMESPACE
  65246. // this will throw an assertion if you try to draw something that's not
  65247. // possible in postscript
  65248. #define WARN_ABOUT_NON_POSTSCRIPT_OPERATIONS 0
  65249. #if JUCE_DEBUG && WARN_ABOUT_NON_POSTSCRIPT_OPERATIONS
  65250. #define notPossibleInPostscriptAssert jassertfalse
  65251. #else
  65252. #define notPossibleInPostscriptAssert
  65253. #endif
  65254. LowLevelGraphicsPostScriptRenderer::LowLevelGraphicsPostScriptRenderer (OutputStream& resultingPostScript,
  65255. const String& documentTitle,
  65256. const int totalWidth_,
  65257. const int totalHeight_)
  65258. : out (resultingPostScript),
  65259. totalWidth (totalWidth_),
  65260. totalHeight (totalHeight_),
  65261. needToClip (true)
  65262. {
  65263. stateStack.add (new SavedState());
  65264. stateStack.getLast()->clip = Rectangle<int> (0, 0, totalWidth_, totalHeight_);
  65265. const float scale = jmin ((520.0f / totalWidth_), (750.0f / totalHeight));
  65266. out << "%!PS-Adobe-3.0 EPSF-3.0"
  65267. "\n%%BoundingBox: 0 0 600 824"
  65268. "\n%%Pages: 0"
  65269. "\n%%Creator: Raw Material Software JUCE"
  65270. "\n%%Title: " << documentTitle <<
  65271. "\n%%CreationDate: none"
  65272. "\n%%LanguageLevel: 2"
  65273. "\n%%EndComments"
  65274. "\n%%BeginProlog"
  65275. "\n%%BeginResource: JRes"
  65276. "\n/bd {bind def} bind def"
  65277. "\n/c {setrgbcolor} bd"
  65278. "\n/m {moveto} bd"
  65279. "\n/l {lineto} bd"
  65280. "\n/rl {rlineto} bd"
  65281. "\n/ct {curveto} bd"
  65282. "\n/cp {closepath} bd"
  65283. "\n/pr {3 index 3 index moveto 1 index 0 rlineto 0 1 index rlineto pop neg 0 rlineto pop pop closepath} bd"
  65284. "\n/doclip {initclip newpath} bd"
  65285. "\n/endclip {clip newpath} bd"
  65286. "\n%%EndResource"
  65287. "\n%%EndProlog"
  65288. "\n%%BeginSetup"
  65289. "\n%%EndSetup"
  65290. "\n%%Page: 1 1"
  65291. "\n%%BeginPageSetup"
  65292. "\n%%EndPageSetup\n\n"
  65293. << "40 800 translate\n"
  65294. << scale << ' ' << scale << " scale\n\n";
  65295. }
  65296. LowLevelGraphicsPostScriptRenderer::~LowLevelGraphicsPostScriptRenderer()
  65297. {
  65298. }
  65299. bool LowLevelGraphicsPostScriptRenderer::isVectorDevice() const
  65300. {
  65301. return true;
  65302. }
  65303. void LowLevelGraphicsPostScriptRenderer::setOrigin (int x, int y)
  65304. {
  65305. if (x != 0 || y != 0)
  65306. {
  65307. stateStack.getLast()->xOffset += x;
  65308. stateStack.getLast()->yOffset += y;
  65309. needToClip = true;
  65310. }
  65311. }
  65312. bool LowLevelGraphicsPostScriptRenderer::clipToRectangle (const Rectangle<int>& r)
  65313. {
  65314. needToClip = true;
  65315. return stateStack.getLast()->clip.clipTo (r.translated (stateStack.getLast()->xOffset, stateStack.getLast()->yOffset));
  65316. }
  65317. bool LowLevelGraphicsPostScriptRenderer::clipToRectangleList (const RectangleList& clipRegion)
  65318. {
  65319. needToClip = true;
  65320. return stateStack.getLast()->clip.clipTo (clipRegion);
  65321. }
  65322. void LowLevelGraphicsPostScriptRenderer::excludeClipRectangle (const Rectangle<int>& r)
  65323. {
  65324. needToClip = true;
  65325. stateStack.getLast()->clip.subtract (r.translated (stateStack.getLast()->xOffset, stateStack.getLast()->yOffset));
  65326. }
  65327. void LowLevelGraphicsPostScriptRenderer::clipToPath (const Path& path, const AffineTransform& transform)
  65328. {
  65329. writeClip();
  65330. Path p (path);
  65331. p.applyTransform (transform.translated ((float) stateStack.getLast()->xOffset, (float) stateStack.getLast()->yOffset));
  65332. writePath (p);
  65333. out << "clip\n";
  65334. }
  65335. void LowLevelGraphicsPostScriptRenderer::clipToImageAlpha (const Image& /*sourceImage*/, const Rectangle<int>& /*srcClip*/, const AffineTransform& /*transform*/)
  65336. {
  65337. needToClip = true;
  65338. jassertfalse // xxx
  65339. }
  65340. bool LowLevelGraphicsPostScriptRenderer::clipRegionIntersects (const Rectangle<int>& r)
  65341. {
  65342. return stateStack.getLast()->clip.intersectsRectangle (r.translated (stateStack.getLast()->xOffset, stateStack.getLast()->yOffset));
  65343. }
  65344. const Rectangle<int> LowLevelGraphicsPostScriptRenderer::getClipBounds() const
  65345. {
  65346. return stateStack.getLast()->clip.getBounds().translated (-stateStack.getLast()->xOffset,
  65347. -stateStack.getLast()->yOffset);
  65348. }
  65349. bool LowLevelGraphicsPostScriptRenderer::isClipEmpty() const
  65350. {
  65351. return stateStack.getLast()->clip.isEmpty();
  65352. }
  65353. LowLevelGraphicsPostScriptRenderer::SavedState::SavedState()
  65354. : xOffset (0),
  65355. yOffset (0)
  65356. {
  65357. }
  65358. LowLevelGraphicsPostScriptRenderer::SavedState::~SavedState()
  65359. {
  65360. }
  65361. void LowLevelGraphicsPostScriptRenderer::saveState()
  65362. {
  65363. stateStack.add (new SavedState (*stateStack.getLast()));
  65364. }
  65365. void LowLevelGraphicsPostScriptRenderer::restoreState()
  65366. {
  65367. jassert (stateStack.size() > 0);
  65368. if (stateStack.size() > 0)
  65369. stateStack.removeLast();
  65370. }
  65371. void LowLevelGraphicsPostScriptRenderer::writeClip()
  65372. {
  65373. if (needToClip)
  65374. {
  65375. needToClip = false;
  65376. out << "doclip ";
  65377. int itemsOnLine = 0;
  65378. for (RectangleList::Iterator i (stateStack.getLast()->clip); i.next();)
  65379. {
  65380. if (++itemsOnLine == 6)
  65381. {
  65382. itemsOnLine = 0;
  65383. out << '\n';
  65384. }
  65385. const Rectangle<int>& r = *i.getRectangle();
  65386. out << r.getX() << ' ' << -r.getY() << ' '
  65387. << r.getWidth() << ' ' << -r.getHeight() << " pr ";
  65388. }
  65389. out << "endclip\n";
  65390. }
  65391. }
  65392. void LowLevelGraphicsPostScriptRenderer::writeColour (const Colour& colour)
  65393. {
  65394. Colour c (Colours::white.overlaidWith (colour));
  65395. if (lastColour != c)
  65396. {
  65397. lastColour = c;
  65398. out << String (c.getFloatRed(), 3) << ' '
  65399. << String (c.getFloatGreen(), 3) << ' '
  65400. << String (c.getFloatBlue(), 3) << " c\n";
  65401. }
  65402. }
  65403. void LowLevelGraphicsPostScriptRenderer::writeXY (const float x, const float y) const
  65404. {
  65405. out << String (x, 2) << ' '
  65406. << String (-y, 2) << ' ';
  65407. }
  65408. void LowLevelGraphicsPostScriptRenderer::writePath (const Path& path) const
  65409. {
  65410. out << "newpath ";
  65411. float lastX = 0.0f;
  65412. float lastY = 0.0f;
  65413. int itemsOnLine = 0;
  65414. Path::Iterator i (path);
  65415. while (i.next())
  65416. {
  65417. if (++itemsOnLine == 4)
  65418. {
  65419. itemsOnLine = 0;
  65420. out << '\n';
  65421. }
  65422. switch (i.elementType)
  65423. {
  65424. case Path::Iterator::startNewSubPath:
  65425. writeXY (i.x1, i.y1);
  65426. lastX = i.x1;
  65427. lastY = i.y1;
  65428. out << "m ";
  65429. break;
  65430. case Path::Iterator::lineTo:
  65431. writeXY (i.x1, i.y1);
  65432. lastX = i.x1;
  65433. lastY = i.y1;
  65434. out << "l ";
  65435. break;
  65436. case Path::Iterator::quadraticTo:
  65437. {
  65438. const float cp1x = lastX + (i.x1 - lastX) * 2.0f / 3.0f;
  65439. const float cp1y = lastY + (i.y1 - lastY) * 2.0f / 3.0f;
  65440. const float cp2x = cp1x + (i.x2 - lastX) / 3.0f;
  65441. const float cp2y = cp1y + (i.y2 - lastY) / 3.0f;
  65442. writeXY (cp1x, cp1y);
  65443. writeXY (cp2x, cp2y);
  65444. writeXY (i.x2, i.y2);
  65445. out << "ct ";
  65446. lastX = i.x2;
  65447. lastY = i.y2;
  65448. }
  65449. break;
  65450. case Path::Iterator::cubicTo:
  65451. writeXY (i.x1, i.y1);
  65452. writeXY (i.x2, i.y2);
  65453. writeXY (i.x3, i.y3);
  65454. out << "ct ";
  65455. lastX = i.x3;
  65456. lastY = i.y3;
  65457. break;
  65458. case Path::Iterator::closePath:
  65459. out << "cp ";
  65460. break;
  65461. default:
  65462. jassertfalse
  65463. break;
  65464. }
  65465. }
  65466. out << '\n';
  65467. }
  65468. void LowLevelGraphicsPostScriptRenderer::writeTransform (const AffineTransform& trans) const
  65469. {
  65470. out << "[ "
  65471. << trans.mat00 << ' '
  65472. << trans.mat10 << ' '
  65473. << trans.mat01 << ' '
  65474. << trans.mat11 << ' '
  65475. << trans.mat02 << ' '
  65476. << trans.mat12 << " ] concat ";
  65477. }
  65478. void LowLevelGraphicsPostScriptRenderer::setFill (const FillType& fillType)
  65479. {
  65480. stateStack.getLast()->fillType = fillType;
  65481. }
  65482. void LowLevelGraphicsPostScriptRenderer::setOpacity (float /*opacity*/)
  65483. {
  65484. }
  65485. void LowLevelGraphicsPostScriptRenderer::setInterpolationQuality (Graphics::ResamplingQuality /*quality*/)
  65486. {
  65487. }
  65488. void LowLevelGraphicsPostScriptRenderer::fillRect (const Rectangle<int>& r, const bool /*replaceExistingContents*/)
  65489. {
  65490. if (stateStack.getLast()->fillType.isColour())
  65491. {
  65492. writeClip();
  65493. writeColour (stateStack.getLast()->fillType.colour);
  65494. Rectangle<int> r2 (r.translated (stateStack.getLast()->xOffset, stateStack.getLast()->yOffset));
  65495. out << r2.getX() << ' ' << -r2.getBottom() << ' ' << r2.getWidth() << ' ' << r2.getHeight() << " rectfill\n";
  65496. }
  65497. else
  65498. {
  65499. Path p;
  65500. p.addRectangle (r);
  65501. fillPath (p, AffineTransform::identity);
  65502. }
  65503. }
  65504. void LowLevelGraphicsPostScriptRenderer::fillPath (const Path& path, const AffineTransform& t)
  65505. {
  65506. if (stateStack.getLast()->fillType.isColour())
  65507. {
  65508. writeClip();
  65509. Path p (path);
  65510. p.applyTransform (t.translated ((float) stateStack.getLast()->xOffset,
  65511. (float) stateStack.getLast()->yOffset));
  65512. writePath (p);
  65513. writeColour (stateStack.getLast()->fillType.colour);
  65514. out << "fill\n";
  65515. }
  65516. else if (stateStack.getLast()->fillType.isGradient())
  65517. {
  65518. // this doesn't work correctly yet - it could be improved to handle solid gradients, but
  65519. // postscript can't do semi-transparent ones.
  65520. notPossibleInPostscriptAssert // you can disable this warning by setting the WARN_ABOUT_NON_POSTSCRIPT_OPERATIONS flag at the top of this file
  65521. writeClip();
  65522. out << "gsave ";
  65523. {
  65524. Path p (path);
  65525. p.applyTransform (t.translated ((float) stateStack.getLast()->xOffset, (float) stateStack.getLast()->yOffset));
  65526. writePath (p);
  65527. out << "clip\n";
  65528. }
  65529. const Rectangle<int> bounds (stateStack.getLast()->clip.getBounds());
  65530. // ideally this would draw lots of lines or ellipses to approximate the gradient, but for the
  65531. // time-being, this just fills it with the average colour..
  65532. writeColour (stateStack.getLast()->fillType.gradient->getColourAtPosition (0.5f));
  65533. out << bounds.getX() << ' ' << -bounds.getBottom() << ' ' << bounds.getWidth() << ' ' << bounds.getHeight() << " rectfill\n";
  65534. out << "grestore\n";
  65535. }
  65536. }
  65537. void LowLevelGraphicsPostScriptRenderer::writeImage (const Image& im,
  65538. const int sx, const int sy,
  65539. const int maxW, const int maxH) const
  65540. {
  65541. out << "{<\n";
  65542. const int w = jmin (maxW, im.getWidth());
  65543. const int h = jmin (maxH, im.getHeight());
  65544. int charsOnLine = 0;
  65545. const Image::BitmapData srcData (im, 0, 0, w, h);
  65546. Colour pixel;
  65547. for (int y = h; --y >= 0;)
  65548. {
  65549. for (int x = 0; x < w; ++x)
  65550. {
  65551. const uint8* pixelData = srcData.getPixelPointer (x, y);
  65552. if (x >= sx && y >= sy)
  65553. {
  65554. if (im.isARGB())
  65555. {
  65556. PixelARGB p (*(const PixelARGB*) pixelData);
  65557. p.unpremultiply();
  65558. pixel = Colours::white.overlaidWith (Colour (p.getARGB()));
  65559. }
  65560. else if (im.isRGB())
  65561. {
  65562. pixel = Colour (((const PixelRGB*) pixelData)->getARGB());
  65563. }
  65564. else
  65565. {
  65566. pixel = Colour ((uint8) 0, (uint8) 0, (uint8) 0, *pixelData);
  65567. }
  65568. }
  65569. else
  65570. {
  65571. pixel = Colours::transparentWhite;
  65572. }
  65573. const uint8 pixelValues[3] = { pixel.getRed(), pixel.getGreen(), pixel.getBlue() };
  65574. out << String::toHexString (pixelValues, 3, 0);
  65575. charsOnLine += 3;
  65576. if (charsOnLine > 100)
  65577. {
  65578. out << '\n';
  65579. charsOnLine = 0;
  65580. }
  65581. }
  65582. }
  65583. out << "\n>}\n";
  65584. }
  65585. void LowLevelGraphicsPostScriptRenderer::drawImage (const Image& sourceImage, const Rectangle<int>& srcClip,
  65586. const AffineTransform& transform, const bool /*fillEntireClipAsTiles*/)
  65587. {
  65588. const int w = jmin (sourceImage.getWidth(), srcClip.getRight());
  65589. const int h = jmin (sourceImage.getHeight(), srcClip.getBottom());
  65590. writeClip();
  65591. out << "gsave ";
  65592. writeTransform (transform.translated ((float) stateStack.getLast()->xOffset, (float) stateStack.getLast()->yOffset)
  65593. .scaled (1.0f, -1.0f));
  65594. RectangleList imageClip;
  65595. sourceImage.createSolidAreaMask (imageClip, 0.5f);
  65596. imageClip.clipTo (srcClip);
  65597. out << "newpath ";
  65598. int itemsOnLine = 0;
  65599. for (RectangleList::Iterator i (imageClip); i.next();)
  65600. {
  65601. if (++itemsOnLine == 6)
  65602. {
  65603. out << '\n';
  65604. itemsOnLine = 0;
  65605. }
  65606. const Rectangle<int>& r = *i.getRectangle();
  65607. out << r.getX() << ' ' << r.getY() << ' ' << r.getWidth() << ' ' << r.getHeight() << " pr ";
  65608. }
  65609. out << " clip newpath\n";
  65610. out << w << ' ' << h << " scale\n";
  65611. out << w << ' ' << h << " 8 [" << w << " 0 0 -" << h << ' ' << (int) 0 << ' ' << h << " ]\n";
  65612. writeImage (sourceImage, srcClip.getX(), srcClip.getY(), srcClip.getWidth(), srcClip.getHeight());
  65613. out << "false 3 colorimage grestore\n";
  65614. needToClip = true;
  65615. }
  65616. void LowLevelGraphicsPostScriptRenderer::drawLine (double x1, double y1, double x2, double y2)
  65617. {
  65618. Path p;
  65619. p.addLineSegment ((float) x1, (float) y1, (float) x2, (float) y2, 1.0f);
  65620. fillPath (p, AffineTransform::identity);
  65621. }
  65622. void LowLevelGraphicsPostScriptRenderer::drawVerticalLine (const int x, double top, double bottom)
  65623. {
  65624. drawLine (x, top, x, bottom);
  65625. }
  65626. void LowLevelGraphicsPostScriptRenderer::drawHorizontalLine (const int y, double left, double right)
  65627. {
  65628. drawLine (left, y, right, y);
  65629. }
  65630. void LowLevelGraphicsPostScriptRenderer::setFont (const Font& newFont)
  65631. {
  65632. stateStack.getLast()->font = newFont;
  65633. }
  65634. const Font LowLevelGraphicsPostScriptRenderer::getFont()
  65635. {
  65636. return stateStack.getLast()->font;
  65637. }
  65638. void LowLevelGraphicsPostScriptRenderer::drawGlyph (int glyphNumber, const AffineTransform& transform)
  65639. {
  65640. Path p;
  65641. Font& font = stateStack.getLast()->font;
  65642. font.getTypeface()->getOutlineForGlyph (glyphNumber, p);
  65643. fillPath (p, AffineTransform::scale (font.getHeight() * font.getHorizontalScale(), font.getHeight()).followedBy (transform));
  65644. }
  65645. END_JUCE_NAMESPACE
  65646. /*** End of inlined file: juce_LowLevelGraphicsPostScriptRenderer.cpp ***/
  65647. /*** Start of inlined file: juce_LowLevelGraphicsSoftwareRenderer.cpp ***/
  65648. BEGIN_JUCE_NAMESPACE
  65649. #if (JUCE_WINDOWS || JUCE_LINUX) && ! JUCE_64BIT
  65650. #define JUCE_USE_SSE_INSTRUCTIONS 1
  65651. #endif
  65652. #if JUCE_MSVC
  65653. #if JUCE_DEBUG
  65654. #pragma optimize ("t", on) // optimise just this file, to avoid sluggish graphics when debugging
  65655. #pragma warning (disable: 4714) // warning about forcedinline methods not being inlined
  65656. #endif
  65657. #pragma warning (push)
  65658. #pragma warning (disable: 4127) // "expression is constant" warning
  65659. #endif
  65660. template <class PixelType, bool replaceExisting = false>
  65661. class SolidColourEdgeTableRenderer
  65662. {
  65663. public:
  65664. SolidColourEdgeTableRenderer (const Image::BitmapData& data_, const PixelARGB& colour)
  65665. : data (data_),
  65666. sourceColour (colour)
  65667. {
  65668. if (sizeof (PixelType) == 3)
  65669. {
  65670. areRGBComponentsEqual = sourceColour.getRed() == sourceColour.getGreen()
  65671. && sourceColour.getGreen() == sourceColour.getBlue();
  65672. filler[0].set (sourceColour);
  65673. filler[1].set (sourceColour);
  65674. filler[2].set (sourceColour);
  65675. filler[3].set (sourceColour);
  65676. }
  65677. }
  65678. forcedinline void setEdgeTableYPos (const int y) throw()
  65679. {
  65680. linePixels = (PixelType*) data.getLinePointer (y);
  65681. }
  65682. forcedinline void handleEdgeTablePixel (const int x, const int alphaLevel) const throw()
  65683. {
  65684. if (replaceExisting)
  65685. linePixels[x].set (sourceColour);
  65686. else
  65687. linePixels[x].blend (sourceColour, alphaLevel);
  65688. }
  65689. forcedinline void handleEdgeTableLine (const int x, int width, const int alphaLevel) const throw()
  65690. {
  65691. PixelARGB p (sourceColour);
  65692. p.multiplyAlpha (alphaLevel);
  65693. PixelType* dest = linePixels + x;
  65694. if (replaceExisting || p.getAlpha() >= 0xff)
  65695. replaceLine (dest, p, width);
  65696. else
  65697. blendLine (dest, p, width);
  65698. }
  65699. private:
  65700. const Image::BitmapData& data;
  65701. PixelType* linePixels;
  65702. PixelARGB sourceColour;
  65703. PixelRGB filler [4];
  65704. bool areRGBComponentsEqual;
  65705. inline void blendLine (PixelType* dest, const PixelARGB& colour, int width) const throw()
  65706. {
  65707. do
  65708. {
  65709. dest->blend (colour);
  65710. ++dest;
  65711. } while (--width > 0);
  65712. }
  65713. forcedinline void replaceLine (PixelRGB* dest, const PixelARGB& colour, int width) const throw()
  65714. {
  65715. if (areRGBComponentsEqual) // if all the component values are the same, we can cheat..
  65716. {
  65717. memset (dest, colour.getRed(), width * 3);
  65718. }
  65719. else
  65720. {
  65721. if (width >> 5)
  65722. {
  65723. const int* const intFiller = (const int*) filler;
  65724. while (width > 8 && (((pointer_sized_int) dest) & 7) != 0)
  65725. {
  65726. dest->set (colour);
  65727. ++dest;
  65728. --width;
  65729. }
  65730. while (width > 4)
  65731. {
  65732. ((int*) dest) [0] = intFiller[0];
  65733. ((int*) dest) [1] = intFiller[1];
  65734. ((int*) dest) [2] = intFiller[2];
  65735. dest = (PixelRGB*) (((uint8*) dest) + 12);
  65736. width -= 4;
  65737. }
  65738. }
  65739. while (--width >= 0)
  65740. {
  65741. dest->set (colour);
  65742. ++dest;
  65743. }
  65744. }
  65745. }
  65746. forcedinline void replaceLine (PixelAlpha* dest, const PixelARGB& colour, int width) const throw()
  65747. {
  65748. memset (dest, colour.getAlpha(), width);
  65749. }
  65750. forcedinline void replaceLine (PixelARGB* dest, const PixelARGB& colour, int width) const throw()
  65751. {
  65752. do
  65753. {
  65754. dest->set (colour);
  65755. ++dest;
  65756. } while (--width > 0);
  65757. }
  65758. SolidColourEdgeTableRenderer (const SolidColourEdgeTableRenderer&);
  65759. SolidColourEdgeTableRenderer& operator= (const SolidColourEdgeTableRenderer&);
  65760. };
  65761. class LinearGradientPixelGenerator
  65762. {
  65763. public:
  65764. LinearGradientPixelGenerator (const ColourGradient& gradient, const AffineTransform& transform, const PixelARGB* const lookupTable_, const int numEntries_)
  65765. : lookupTable (lookupTable_), numEntries (numEntries_)
  65766. {
  65767. jassert (numEntries_ >= 0);
  65768. Point<float> p1 (gradient.x1, gradient.y1);
  65769. Point<float> p2 (gradient.x2, gradient.y2);
  65770. if (! transform.isIdentity())
  65771. {
  65772. const Line<float> l (p2, p1);
  65773. Point<float> p3 = l.getPointAlongLine (0.0f, 100.0f);
  65774. p1.applyTransform (transform);
  65775. p2.applyTransform (transform);
  65776. p3.applyTransform (transform);
  65777. const Line<float> l2 (p2, p3);
  65778. p2 = l2.getPointAlongLineProportionally (l2.findNearestPointTo (p1));
  65779. }
  65780. vertical = std::abs (p1.getX() - p2.getX()) < 0.001f;
  65781. horizontal = std::abs (p1.getY() - p2.getY()) < 0.001f;
  65782. if (vertical)
  65783. {
  65784. scale = roundToInt ((numEntries << (int) numScaleBits) / (double) (p2.getY() - p1.getY()));
  65785. start = roundToInt (p1.getY() * scale);
  65786. }
  65787. else if (horizontal)
  65788. {
  65789. scale = roundToInt ((numEntries << (int) numScaleBits) / (double) (p2.getX() - p1.getX()));
  65790. start = roundToInt (p1.getX() * scale);
  65791. }
  65792. else
  65793. {
  65794. grad = (p2.getY() - p1.getY()) / (double) (p1.getX() - p2.getX());
  65795. yTerm = p1.getY() - p1.getX() / grad;
  65796. scale = roundToInt ((numEntries << (int) numScaleBits) / (yTerm * grad - (p2.getY() * grad - p2.getX())));
  65797. grad *= scale;
  65798. }
  65799. }
  65800. forcedinline void setY (const int y) throw()
  65801. {
  65802. if (vertical)
  65803. linePix = lookupTable [jlimit (0, numEntries, (y * scale - start) >> (int) numScaleBits)];
  65804. else if (! horizontal)
  65805. start = roundToInt ((y - yTerm) * grad);
  65806. }
  65807. inline const PixelARGB getPixel (const int x) const throw()
  65808. {
  65809. return vertical ? linePix
  65810. : lookupTable [jlimit (0, numEntries, (x * scale - start) >> (int) numScaleBits)];
  65811. }
  65812. private:
  65813. const PixelARGB* const lookupTable;
  65814. const int numEntries;
  65815. PixelARGB linePix;
  65816. int start, scale;
  65817. double grad, yTerm;
  65818. bool vertical, horizontal;
  65819. enum { numScaleBits = 12 };
  65820. LinearGradientPixelGenerator (const LinearGradientPixelGenerator&);
  65821. LinearGradientPixelGenerator& operator= (const LinearGradientPixelGenerator&);
  65822. };
  65823. class RadialGradientPixelGenerator
  65824. {
  65825. public:
  65826. RadialGradientPixelGenerator (const ColourGradient& gradient, const AffineTransform&,
  65827. const PixelARGB* const lookupTable_, const int numEntries_)
  65828. : lookupTable (lookupTable_),
  65829. numEntries (numEntries_),
  65830. gx1 (gradient.x1),
  65831. gy1 (gradient.y1)
  65832. {
  65833. jassert (numEntries_ >= 0);
  65834. const float gdx = gradient.x1 - gradient.x2;
  65835. const float gdy = gradient.y1 - gradient.y2;
  65836. maxDist = gdx * gdx + gdy * gdy;
  65837. invScale = numEntries / std::sqrt (maxDist);
  65838. jassert (roundToInt (std::sqrt (maxDist) * invScale) <= numEntries);
  65839. }
  65840. forcedinline void setY (const int y) throw()
  65841. {
  65842. dy = y - gy1;
  65843. dy *= dy;
  65844. }
  65845. inline const PixelARGB getPixel (const int px) const throw()
  65846. {
  65847. double x = px - gx1;
  65848. x *= x;
  65849. x += dy;
  65850. return lookupTable [x >= maxDist ? numEntries : roundToInt (std::sqrt (x) * invScale)];
  65851. }
  65852. protected:
  65853. const PixelARGB* const lookupTable;
  65854. const int numEntries;
  65855. const double gx1, gy1;
  65856. double maxDist, invScale, dy;
  65857. RadialGradientPixelGenerator (const RadialGradientPixelGenerator&);
  65858. RadialGradientPixelGenerator& operator= (const RadialGradientPixelGenerator&);
  65859. };
  65860. class TransformedRadialGradientPixelGenerator : public RadialGradientPixelGenerator
  65861. {
  65862. public:
  65863. TransformedRadialGradientPixelGenerator (const ColourGradient& gradient, const AffineTransform& transform,
  65864. const PixelARGB* const lookupTable_, const int numEntries_)
  65865. : RadialGradientPixelGenerator (gradient, transform, lookupTable_, numEntries_),
  65866. inverseTransform (transform.inverted())
  65867. {
  65868. tM10 = inverseTransform.mat10;
  65869. tM00 = inverseTransform.mat00;
  65870. }
  65871. forcedinline void setY (const int y) throw()
  65872. {
  65873. lineYM01 = inverseTransform.mat01 * y + inverseTransform.mat02 - gx1;
  65874. lineYM11 = inverseTransform.mat11 * y + inverseTransform.mat12 - gy1;
  65875. }
  65876. inline const PixelARGB getPixel (const int px) const throw()
  65877. {
  65878. double x = px;
  65879. const double y = tM10 * x + lineYM11;
  65880. x = tM00 * x + lineYM01;
  65881. x *= x;
  65882. x += y * y;
  65883. if (x >= maxDist)
  65884. return lookupTable [numEntries];
  65885. else
  65886. return lookupTable [jmin (numEntries, roundToInt (std::sqrt (x) * invScale))];
  65887. }
  65888. private:
  65889. double tM10, tM00, lineYM01, lineYM11;
  65890. const AffineTransform inverseTransform;
  65891. TransformedRadialGradientPixelGenerator (const TransformedRadialGradientPixelGenerator&);
  65892. TransformedRadialGradientPixelGenerator& operator= (const TransformedRadialGradientPixelGenerator&);
  65893. };
  65894. template <class PixelType, class GradientType>
  65895. class GradientEdgeTableRenderer : public GradientType
  65896. {
  65897. public:
  65898. GradientEdgeTableRenderer (const Image::BitmapData& destData_, const ColourGradient& gradient, const AffineTransform& transform,
  65899. const PixelARGB* const lookupTable_, const int numEntries_)
  65900. : GradientType (gradient, transform, lookupTable_, numEntries_ - 1),
  65901. destData (destData_)
  65902. {
  65903. }
  65904. forcedinline void setEdgeTableYPos (const int y) throw()
  65905. {
  65906. linePixels = (PixelType*) destData.getLinePointer (y);
  65907. GradientType::setY (y);
  65908. }
  65909. forcedinline void handleEdgeTablePixel (const int x, const int alphaLevel) const throw()
  65910. {
  65911. linePixels[x].blend (GradientType::getPixel (x), alphaLevel);
  65912. }
  65913. forcedinline void handleEdgeTableLine (int x, int width, const int alphaLevel) const throw()
  65914. {
  65915. PixelType* dest = linePixels + x;
  65916. if (alphaLevel < 0xff)
  65917. {
  65918. do
  65919. {
  65920. (dest++)->blend (GradientType::getPixel (x++), alphaLevel);
  65921. } while (--width > 0);
  65922. }
  65923. else
  65924. {
  65925. do
  65926. {
  65927. (dest++)->blend (GradientType::getPixel (x++));
  65928. } while (--width > 0);
  65929. }
  65930. }
  65931. private:
  65932. const Image::BitmapData& destData;
  65933. PixelType* linePixels;
  65934. GradientEdgeTableRenderer (const GradientEdgeTableRenderer&);
  65935. GradientEdgeTableRenderer& operator= (const GradientEdgeTableRenderer&);
  65936. };
  65937. static forcedinline int safeModulo (int n, const int divisor) throw()
  65938. {
  65939. jassert (divisor > 0);
  65940. n %= divisor;
  65941. return (n < 0) ? (n + divisor) : n;
  65942. }
  65943. template <class DestPixelType, class SrcPixelType, bool repeatPattern>
  65944. class ImageFillEdgeTableRenderer
  65945. {
  65946. public:
  65947. ImageFillEdgeTableRenderer (const Image::BitmapData& destData_,
  65948. const Image::BitmapData& srcData_,
  65949. const int extraAlpha_,
  65950. const int x, const int y)
  65951. : destData (destData_),
  65952. srcData (srcData_),
  65953. extraAlpha (extraAlpha_ + 1),
  65954. xOffset (repeatPattern ? safeModulo (x, srcData_.width) - srcData_.width : x),
  65955. yOffset (repeatPattern ? safeModulo (y, srcData_.height) - srcData_.height : y)
  65956. {
  65957. }
  65958. forcedinline void setEdgeTableYPos (int y) throw()
  65959. {
  65960. linePixels = (DestPixelType*) destData.getLinePointer (y);
  65961. y -= yOffset;
  65962. if (repeatPattern)
  65963. {
  65964. jassert (y >= 0);
  65965. y %= srcData.height;
  65966. }
  65967. sourceLineStart = (SrcPixelType*) srcData.getLinePointer (y);
  65968. }
  65969. forcedinline void handleEdgeTablePixel (int x, int alphaLevel) const throw()
  65970. {
  65971. alphaLevel = (alphaLevel * extraAlpha) >> 8;
  65972. linePixels[x].blend (sourceLineStart [repeatPattern ? ((x - xOffset) % srcData.width) : (x - xOffset)], alphaLevel);
  65973. }
  65974. forcedinline void handleEdgeTableLine (int x, int width, int alphaLevel) const throw()
  65975. {
  65976. DestPixelType* dest = linePixels + x;
  65977. alphaLevel = (alphaLevel * extraAlpha) >> 8;
  65978. x -= xOffset;
  65979. jassert (repeatPattern || (x >= 0 && x + width <= srcData.width));
  65980. if (alphaLevel < 0xfe)
  65981. {
  65982. do
  65983. {
  65984. dest++ ->blend (sourceLineStart [repeatPattern ? (x++ % srcData.width) : x++], alphaLevel);
  65985. } while (--width > 0);
  65986. }
  65987. else
  65988. {
  65989. if (repeatPattern)
  65990. {
  65991. do
  65992. {
  65993. dest++ ->blend (sourceLineStart [x++ % srcData.width]);
  65994. } while (--width > 0);
  65995. }
  65996. else
  65997. {
  65998. copyRow (dest, sourceLineStart + x, width);
  65999. }
  66000. }
  66001. }
  66002. void clipEdgeTableLine (EdgeTable& et, int x, int y, int width)
  66003. {
  66004. jassert (x - xOffset >= 0 && x + width - xOffset <= srcData.width);
  66005. SrcPixelType* s = (SrcPixelType*) srcData.getLinePointer (y - yOffset);
  66006. uint8* mask = (uint8*) (s + x - xOffset);
  66007. if (sizeof (SrcPixelType) == sizeof (PixelARGB))
  66008. mask += PixelARGB::indexA;
  66009. et.clipLineToMask (x, y, mask, sizeof (SrcPixelType), width);
  66010. }
  66011. private:
  66012. const Image::BitmapData& destData;
  66013. const Image::BitmapData& srcData;
  66014. const int extraAlpha, xOffset, yOffset;
  66015. DestPixelType* linePixels;
  66016. SrcPixelType* sourceLineStart;
  66017. template <class PixelType1, class PixelType2>
  66018. forcedinline static void copyRow (PixelType1* dest, PixelType2* src, int width) throw()
  66019. {
  66020. do
  66021. {
  66022. dest++ ->blend (*src++);
  66023. } while (--width > 0);
  66024. }
  66025. forcedinline static void copyRow (PixelRGB* dest, PixelRGB* src, int width) throw()
  66026. {
  66027. memcpy (dest, src, width * sizeof (PixelRGB));
  66028. }
  66029. ImageFillEdgeTableRenderer (const ImageFillEdgeTableRenderer&);
  66030. ImageFillEdgeTableRenderer& operator= (const ImageFillEdgeTableRenderer&);
  66031. };
  66032. template <class DestPixelType, class SrcPixelType, bool repeatPattern>
  66033. class TransformedImageFillEdgeTableRenderer
  66034. {
  66035. public:
  66036. TransformedImageFillEdgeTableRenderer (const Image::BitmapData& destData_,
  66037. const Image::BitmapData& srcData_,
  66038. const AffineTransform& transform,
  66039. const int extraAlpha_,
  66040. const bool betterQuality_)
  66041. : interpolator (transform),
  66042. destData (destData_),
  66043. srcData (srcData_),
  66044. extraAlpha (extraAlpha_ + 1),
  66045. betterQuality (betterQuality_),
  66046. pixelOffset (betterQuality_ ? 0.5f : 0.0f),
  66047. pixelOffsetInt (betterQuality_ ? -128 : 0),
  66048. maxX (srcData_.width - 1),
  66049. maxY (srcData_.height - 1),
  66050. scratchSize (2048)
  66051. {
  66052. scratchBuffer.malloc (scratchSize);
  66053. }
  66054. ~TransformedImageFillEdgeTableRenderer()
  66055. {
  66056. }
  66057. forcedinline void setEdgeTableYPos (const int newY) throw()
  66058. {
  66059. y = newY;
  66060. linePixels = (DestPixelType*) destData.getLinePointer (newY);
  66061. }
  66062. forcedinline void handleEdgeTablePixel (const int x, int alphaLevel) throw()
  66063. {
  66064. alphaLevel *= extraAlpha;
  66065. alphaLevel >>= 8;
  66066. SrcPixelType p;
  66067. generate (&p, x, 1);
  66068. linePixels[x].blend (p, alphaLevel);
  66069. }
  66070. forcedinline void handleEdgeTableLine (const int x, int width, int alphaLevel) throw()
  66071. {
  66072. if (width > scratchSize)
  66073. {
  66074. scratchSize = width;
  66075. scratchBuffer.malloc (scratchSize);
  66076. }
  66077. SrcPixelType* span = scratchBuffer;
  66078. generate (span, x, width);
  66079. DestPixelType* dest = linePixels + x;
  66080. alphaLevel *= extraAlpha;
  66081. alphaLevel >>= 8;
  66082. if (alphaLevel < 0xfe)
  66083. {
  66084. do
  66085. {
  66086. dest++ ->blend (*span++, alphaLevel);
  66087. } while (--width > 0);
  66088. }
  66089. else
  66090. {
  66091. do
  66092. {
  66093. dest++ ->blend (*span++);
  66094. } while (--width > 0);
  66095. }
  66096. }
  66097. void clipEdgeTableLine (EdgeTable& et, int x, int y_, int width)
  66098. {
  66099. if (width > scratchSize)
  66100. {
  66101. scratchSize = width;
  66102. scratchBuffer.malloc (scratchSize);
  66103. }
  66104. y = y_;
  66105. generate (scratchBuffer, x, width);
  66106. et.clipLineToMask (x, y_,
  66107. reinterpret_cast<uint8*> (scratchBuffer.getData()) + SrcPixelType::indexA,
  66108. sizeof (SrcPixelType), width);
  66109. }
  66110. private:
  66111. void generate (PixelARGB* dest, const int x, int numPixels) throw()
  66112. {
  66113. this->interpolator.setStartOfLine (x + pixelOffset, y + pixelOffset, numPixels);
  66114. do
  66115. {
  66116. int hiResX, hiResY;
  66117. this->interpolator.next (hiResX, hiResY);
  66118. hiResX += pixelOffsetInt;
  66119. hiResY += pixelOffsetInt;
  66120. int loResX = hiResX >> 8;
  66121. int loResY = hiResY >> 8;
  66122. if (repeatPattern)
  66123. {
  66124. loResX = safeModulo (loResX, srcData.width);
  66125. loResY = safeModulo (loResY, srcData.height);
  66126. }
  66127. if (betterQuality
  66128. && ((unsigned int) loResX) < (unsigned int) maxX
  66129. && ((unsigned int) loResY) < (unsigned int) maxY)
  66130. {
  66131. uint32 c[4] = { 256 * 128, 256 * 128, 256 * 128, 256 * 128 };
  66132. hiResX &= 255;
  66133. hiResY &= 255;
  66134. const uint8* src = this->srcData.getPixelPointer (loResX, loResY);
  66135. uint32 weight = (256 - hiResX) * (256 - hiResY);
  66136. c[0] += weight * src[0];
  66137. c[1] += weight * src[1];
  66138. c[2] += weight * src[2];
  66139. c[3] += weight * src[3];
  66140. weight = hiResX * (256 - hiResY);
  66141. c[0] += weight * src[4];
  66142. c[1] += weight * src[5];
  66143. c[2] += weight * src[6];
  66144. c[3] += weight * src[7];
  66145. src += this->srcData.lineStride;
  66146. weight = (256 - hiResX) * hiResY;
  66147. c[0] += weight * src[0];
  66148. c[1] += weight * src[1];
  66149. c[2] += weight * src[2];
  66150. c[3] += weight * src[3];
  66151. weight = hiResX * hiResY;
  66152. c[0] += weight * src[4];
  66153. c[1] += weight * src[5];
  66154. c[2] += weight * src[6];
  66155. c[3] += weight * src[7];
  66156. dest->setARGB ((uint8) (c[PixelARGB::indexA] >> 16),
  66157. (uint8) (c[PixelARGB::indexR] >> 16),
  66158. (uint8) (c[PixelARGB::indexG] >> 16),
  66159. (uint8) (c[PixelARGB::indexB] >> 16));
  66160. }
  66161. else
  66162. {
  66163. if (! repeatPattern)
  66164. {
  66165. // Beyond the edges, just repeat the edge pixels and leave the anti-aliasing to be handled by the edgetable
  66166. if (loResX < 0) loResX = 0;
  66167. if (loResY < 0) loResY = 0;
  66168. if (loResX > maxX) loResX = maxX;
  66169. if (loResY > maxY) loResY = maxY;
  66170. }
  66171. dest->set (*(const PixelARGB*) this->srcData.getPixelPointer (loResX, loResY));
  66172. }
  66173. ++dest;
  66174. } while (--numPixels > 0);
  66175. }
  66176. void generate (PixelRGB* dest, const int x, int numPixels) throw()
  66177. {
  66178. this->interpolator.setStartOfLine (x + pixelOffset, y + pixelOffset, numPixels);
  66179. do
  66180. {
  66181. int hiResX, hiResY;
  66182. this->interpolator.next (hiResX, hiResY);
  66183. hiResX += pixelOffsetInt;
  66184. hiResY += pixelOffsetInt;
  66185. int loResX = hiResX >> 8;
  66186. int loResY = hiResY >> 8;
  66187. if (repeatPattern)
  66188. {
  66189. loResX = safeModulo (loResX, srcData.width);
  66190. loResY = safeModulo (loResY, srcData.height);
  66191. }
  66192. if (betterQuality
  66193. && ((unsigned int) loResX) < (unsigned int) maxX
  66194. && ((unsigned int) loResY) < (unsigned int) maxY)
  66195. {
  66196. uint32 c[3] = { 256 * 128, 256 * 128, 256 * 128 };
  66197. hiResX &= 255;
  66198. hiResY &= 255;
  66199. const uint8* src = this->srcData.getPixelPointer (loResX, loResY);
  66200. unsigned int weight = (256 - hiResX) * (256 - hiResY);
  66201. c[0] += weight * src[0];
  66202. c[1] += weight * src[1];
  66203. c[2] += weight * src[2];
  66204. weight = hiResX * (256 - hiResY);
  66205. c[0] += weight * src[3];
  66206. c[1] += weight * src[4];
  66207. c[2] += weight * src[5];
  66208. src += this->srcData.lineStride;
  66209. weight = (256 - hiResX) * hiResY;
  66210. c[0] += weight * src[0];
  66211. c[1] += weight * src[1];
  66212. c[2] += weight * src[2];
  66213. weight = hiResX * hiResY;
  66214. c[0] += weight * src[3];
  66215. c[1] += weight * src[4];
  66216. c[2] += weight * src[5];
  66217. dest->setARGB ((uint8) 255,
  66218. (uint8) (c[PixelRGB::indexR] >> 16),
  66219. (uint8) (c[PixelRGB::indexG] >> 16),
  66220. (uint8) (c[PixelRGB::indexB] >> 16));
  66221. }
  66222. else
  66223. {
  66224. if (! repeatPattern)
  66225. {
  66226. // Beyond the edges, just repeat the edge pixels and leave the anti-aliasing to be handled by the edgetable
  66227. if (loResX < 0) loResX = 0;
  66228. if (loResY < 0) loResY = 0;
  66229. if (loResX > maxX) loResX = maxX;
  66230. if (loResY > maxY) loResY = maxY;
  66231. }
  66232. dest->set (*(const PixelRGB*) this->srcData.getPixelPointer (loResX, loResY));
  66233. }
  66234. ++dest;
  66235. } while (--numPixels > 0);
  66236. }
  66237. void generate (PixelAlpha* dest, const int x, int numPixels) throw()
  66238. {
  66239. this->interpolator.setStartOfLine (x + pixelOffset, y + pixelOffset, numPixels);
  66240. do
  66241. {
  66242. int hiResX, hiResY;
  66243. this->interpolator.next (hiResX, hiResY);
  66244. hiResX += pixelOffsetInt;
  66245. hiResY += pixelOffsetInt;
  66246. int loResX = hiResX >> 8;
  66247. int loResY = hiResY >> 8;
  66248. if (repeatPattern)
  66249. {
  66250. loResX = safeModulo (loResX, srcData.width);
  66251. loResY = safeModulo (loResY, srcData.height);
  66252. }
  66253. if (betterQuality
  66254. && ((unsigned int) loResX) < (unsigned int) maxX
  66255. && ((unsigned int) loResY) < (unsigned int) maxY)
  66256. {
  66257. hiResX &= 255;
  66258. hiResY &= 255;
  66259. const uint8* src = this->srcData.getPixelPointer (loResX, loResY);
  66260. uint32 c = 256 * 128;
  66261. c += src[0] * ((256 - hiResX) * (256 - hiResY));
  66262. c += src[1] * (hiResX * (256 - hiResY));
  66263. src += this->srcData.lineStride;
  66264. c += src[0] * ((256 - hiResX) * hiResY);
  66265. c += src[1] * (hiResX * hiResY);
  66266. *((uint8*) dest) = (uint8) c;
  66267. }
  66268. else
  66269. {
  66270. if (! repeatPattern)
  66271. {
  66272. // Beyond the edges, just repeat the edge pixels and leave the anti-aliasing to be handled by the edgetable
  66273. if (loResX < 0) loResX = 0;
  66274. if (loResY < 0) loResY = 0;
  66275. if (loResX > maxX) loResX = maxX;
  66276. if (loResY > maxY) loResY = maxY;
  66277. }
  66278. *((uint8*) dest) = *(this->srcData.getPixelPointer (loResX, loResY));
  66279. }
  66280. ++dest;
  66281. } while (--numPixels > 0);
  66282. }
  66283. class TransformedImageSpanInterpolator
  66284. {
  66285. public:
  66286. TransformedImageSpanInterpolator (const AffineTransform& transform) throw()
  66287. : inverseTransform (transform.inverted())
  66288. {}
  66289. void setStartOfLine (float x, float y, const int numPixels) throw()
  66290. {
  66291. float x1 = x, y1 = y;
  66292. inverseTransform.transformPoint (x1, y1);
  66293. x += numPixels;
  66294. inverseTransform.transformPoint (x, y);
  66295. xBresenham.set ((int) (x1 * 256.0f), (int) (x * 256.0f), numPixels);
  66296. yBresenham.set ((int) (y1 * 256.0f), (int) (y * 256.0f), numPixels);
  66297. }
  66298. void next (int& x, int& y) throw()
  66299. {
  66300. x = xBresenham.n;
  66301. xBresenham.stepToNext();
  66302. y = yBresenham.n;
  66303. yBresenham.stepToNext();
  66304. }
  66305. private:
  66306. class BresenhamInterpolator
  66307. {
  66308. public:
  66309. BresenhamInterpolator() throw() {}
  66310. void set (const int n1, const int n2, const int numSteps_) throw()
  66311. {
  66312. numSteps = jmax (1, numSteps_);
  66313. step = (n2 - n1) / numSteps;
  66314. remainder = modulo = (n2 - n1) % numSteps;
  66315. n = n1;
  66316. if (modulo <= 0)
  66317. {
  66318. modulo += numSteps;
  66319. remainder += numSteps;
  66320. --step;
  66321. }
  66322. modulo -= numSteps;
  66323. }
  66324. forcedinline void stepToNext() throw()
  66325. {
  66326. modulo += remainder;
  66327. n += step;
  66328. if (modulo > 0)
  66329. {
  66330. modulo -= numSteps;
  66331. ++n;
  66332. }
  66333. }
  66334. int n;
  66335. private:
  66336. int numSteps, step, modulo, remainder;
  66337. };
  66338. const AffineTransform inverseTransform;
  66339. BresenhamInterpolator xBresenham, yBresenham;
  66340. TransformedImageSpanInterpolator (const TransformedImageSpanInterpolator&);
  66341. TransformedImageSpanInterpolator& operator= (const TransformedImageSpanInterpolator&);
  66342. };
  66343. TransformedImageSpanInterpolator interpolator;
  66344. const Image::BitmapData& destData;
  66345. const Image::BitmapData& srcData;
  66346. const int extraAlpha;
  66347. const bool betterQuality;
  66348. const float pixelOffset;
  66349. const int pixelOffsetInt, maxX, maxY;
  66350. int y;
  66351. DestPixelType* linePixels;
  66352. HeapBlock <SrcPixelType> scratchBuffer;
  66353. int scratchSize;
  66354. TransformedImageFillEdgeTableRenderer (const TransformedImageFillEdgeTableRenderer&);
  66355. TransformedImageFillEdgeTableRenderer& operator= (const TransformedImageFillEdgeTableRenderer&);
  66356. };
  66357. class ClipRegionBase : public ReferenceCountedObject
  66358. {
  66359. public:
  66360. ClipRegionBase() {}
  66361. virtual ~ClipRegionBase() {}
  66362. typedef ReferenceCountedObjectPtr<ClipRegionBase> Ptr;
  66363. virtual const Ptr clone() const = 0;
  66364. const Ptr clipTo (ClipRegionBase* other);
  66365. virtual const Ptr clipToRectangle (const Rectangle<int>& r) = 0;
  66366. virtual const Ptr clipToRectangleList (const RectangleList& r) = 0;
  66367. virtual const Ptr excludeClipRectangle (const Rectangle<int>& r) = 0;
  66368. virtual const Ptr clipToPath (const Path& p, const AffineTransform& transform) = 0;
  66369. virtual const Ptr clipToEdgeTable (const EdgeTable& et) = 0;
  66370. virtual const Ptr clipToImageAlpha (const Image& image, const Rectangle<int>& srcClip, const AffineTransform& t, const bool betterQuality) = 0;
  66371. virtual bool clipRegionIntersects (const Rectangle<int>& r) const = 0;
  66372. virtual const Rectangle<int> getClipBounds() const = 0;
  66373. virtual void fillRectWithColour (Image::BitmapData& destData, const Rectangle<int>& area, const PixelARGB& colour, bool replaceContents) const = 0;
  66374. virtual void fillRectWithColour (Image::BitmapData& destData, const Rectangle<float>& area, const PixelARGB& colour) const = 0;
  66375. virtual void fillAllWithColour (Image::BitmapData& destData, const PixelARGB& colour, bool replaceContents) const = 0;
  66376. virtual void fillAllWithGradient (Image::BitmapData& destData, ColourGradient& gradient, const AffineTransform& transform, bool isIdentity) const = 0;
  66377. virtual void renderImageTransformed (const Image::BitmapData& destData, const Image::BitmapData& srcData, const Rectangle<int>& srcClip, const int alpha, const AffineTransform& t, bool betterQuality, bool tiledFill) const = 0;
  66378. virtual void renderImageUntransformed (const Image::BitmapData& destData, const Image::BitmapData& srcData, const Rectangle<int>& srcClip, const int alpha, int x, int y, bool tiledFill) const = 0;
  66379. protected:
  66380. template <class Iterator>
  66381. static void renderImageTransformedInternal (Iterator& iter, const Image::BitmapData& destData, const Image::BitmapData& srcData,
  66382. const Rectangle<int>& srcClip, const int alpha, const AffineTransform& transform, bool betterQuality, bool tiledFill)
  66383. {
  66384. switch (destData.pixelFormat)
  66385. {
  66386. case Image::ARGB:
  66387. switch (srcData.pixelFormat)
  66388. {
  66389. case Image::ARGB:
  66390. if (tiledFill) { TransformedImageFillEdgeTableRenderer <PixelARGB, PixelARGB, true> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  66391. else { TransformedImageFillEdgeTableRenderer <PixelARGB, PixelARGB, false> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  66392. break;
  66393. case Image::RGB:
  66394. if (tiledFill) { TransformedImageFillEdgeTableRenderer <PixelARGB, PixelRGB, true> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  66395. else { TransformedImageFillEdgeTableRenderer <PixelARGB, PixelRGB, false> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  66396. break;
  66397. default:
  66398. if (tiledFill) { TransformedImageFillEdgeTableRenderer <PixelARGB, PixelAlpha, true> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  66399. else { TransformedImageFillEdgeTableRenderer <PixelARGB, PixelAlpha, false> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  66400. break;
  66401. }
  66402. break;
  66403. case Image::RGB:
  66404. switch (srcData.pixelFormat)
  66405. {
  66406. case Image::ARGB:
  66407. if (tiledFill) { TransformedImageFillEdgeTableRenderer <PixelRGB, PixelARGB, true> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  66408. else { TransformedImageFillEdgeTableRenderer <PixelRGB, PixelARGB, false> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  66409. break;
  66410. case Image::RGB:
  66411. if (tiledFill) { TransformedImageFillEdgeTableRenderer <PixelRGB, PixelRGB, true> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  66412. else { TransformedImageFillEdgeTableRenderer <PixelRGB, PixelRGB, false> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  66413. break;
  66414. default:
  66415. if (tiledFill) { TransformedImageFillEdgeTableRenderer <PixelRGB, PixelAlpha, true> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  66416. else { TransformedImageFillEdgeTableRenderer <PixelRGB, PixelAlpha, false> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  66417. break;
  66418. }
  66419. break;
  66420. default:
  66421. switch (srcData.pixelFormat)
  66422. {
  66423. case Image::ARGB:
  66424. if (tiledFill) { TransformedImageFillEdgeTableRenderer <PixelAlpha, PixelARGB, true> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  66425. else { TransformedImageFillEdgeTableRenderer <PixelAlpha, PixelARGB, false> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  66426. break;
  66427. case Image::RGB:
  66428. if (tiledFill) { TransformedImageFillEdgeTableRenderer <PixelAlpha, PixelRGB, true> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  66429. else { TransformedImageFillEdgeTableRenderer <PixelAlpha, PixelRGB, false> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  66430. break;
  66431. default:
  66432. if (tiledFill) { TransformedImageFillEdgeTableRenderer <PixelAlpha, PixelAlpha, true> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  66433. else { TransformedImageFillEdgeTableRenderer <PixelAlpha, PixelAlpha, false> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  66434. break;
  66435. }
  66436. break;
  66437. }
  66438. }
  66439. template <class Iterator>
  66440. static void renderImageUntransformedInternal (Iterator& iter, const Image::BitmapData& destData, const Image::BitmapData& srcData, const Rectangle<int>& srcClip, const int alpha, int x, int y, bool tiledFill)
  66441. {
  66442. switch (destData.pixelFormat)
  66443. {
  66444. case Image::ARGB:
  66445. switch (srcData.pixelFormat)
  66446. {
  66447. case Image::ARGB:
  66448. if (tiledFill) { ImageFillEdgeTableRenderer <PixelARGB, PixelARGB, true> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  66449. else { ImageFillEdgeTableRenderer <PixelARGB, PixelARGB, false> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  66450. break;
  66451. case Image::RGB:
  66452. if (tiledFill) { ImageFillEdgeTableRenderer <PixelARGB, PixelRGB, true> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  66453. else { ImageFillEdgeTableRenderer <PixelARGB, PixelRGB, false> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  66454. break;
  66455. default:
  66456. if (tiledFill) { ImageFillEdgeTableRenderer <PixelARGB, PixelAlpha, true> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  66457. else { ImageFillEdgeTableRenderer <PixelARGB, PixelAlpha, false> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  66458. break;
  66459. }
  66460. break;
  66461. case Image::RGB:
  66462. switch (srcData.pixelFormat)
  66463. {
  66464. case Image::ARGB:
  66465. if (tiledFill) { ImageFillEdgeTableRenderer <PixelRGB, PixelARGB, true> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  66466. else { ImageFillEdgeTableRenderer <PixelRGB, PixelARGB, false> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  66467. break;
  66468. case Image::RGB:
  66469. if (tiledFill) { ImageFillEdgeTableRenderer <PixelRGB, PixelRGB, true> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  66470. else { ImageFillEdgeTableRenderer <PixelRGB, PixelRGB, false> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  66471. break;
  66472. default:
  66473. if (tiledFill) { ImageFillEdgeTableRenderer <PixelRGB, PixelAlpha, true> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  66474. else { ImageFillEdgeTableRenderer <PixelRGB, PixelAlpha, false> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  66475. break;
  66476. }
  66477. break;
  66478. default:
  66479. switch (srcData.pixelFormat)
  66480. {
  66481. case Image::ARGB:
  66482. if (tiledFill) { ImageFillEdgeTableRenderer <PixelAlpha, PixelARGB, true> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  66483. else { ImageFillEdgeTableRenderer <PixelAlpha, PixelARGB, false> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  66484. break;
  66485. case Image::RGB:
  66486. if (tiledFill) { ImageFillEdgeTableRenderer <PixelAlpha, PixelRGB, true> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  66487. else { ImageFillEdgeTableRenderer <PixelAlpha, PixelRGB, false> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  66488. break;
  66489. default:
  66490. if (tiledFill) { ImageFillEdgeTableRenderer <PixelAlpha, PixelAlpha, true> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  66491. else { ImageFillEdgeTableRenderer <PixelAlpha, PixelAlpha, false> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  66492. break;
  66493. }
  66494. break;
  66495. }
  66496. }
  66497. template <class Iterator, class DestPixelType>
  66498. static void renderSolidFill (Iterator& iter, const Image::BitmapData& destData, const PixelARGB& fillColour, const bool replaceContents, DestPixelType*)
  66499. {
  66500. jassert (destData.pixelStride == sizeof (DestPixelType));
  66501. if (replaceContents)
  66502. {
  66503. SolidColourEdgeTableRenderer <DestPixelType, true> r (destData, fillColour);
  66504. iter.iterate (r);
  66505. }
  66506. else
  66507. {
  66508. SolidColourEdgeTableRenderer <DestPixelType, false> r (destData, fillColour);
  66509. iter.iterate (r);
  66510. }
  66511. }
  66512. template <class Iterator, class DestPixelType>
  66513. static void renderGradient (Iterator& iter, const Image::BitmapData& destData, const ColourGradient& g, const AffineTransform& transform,
  66514. const PixelARGB* const lookupTable, const int numLookupEntries, const bool isIdentity, DestPixelType*)
  66515. {
  66516. jassert (destData.pixelStride == sizeof (DestPixelType));
  66517. if (g.isRadial)
  66518. {
  66519. if (isIdentity)
  66520. {
  66521. GradientEdgeTableRenderer <DestPixelType, RadialGradientPixelGenerator> renderer (destData, g, transform, lookupTable, numLookupEntries);
  66522. iter.iterate (renderer);
  66523. }
  66524. else
  66525. {
  66526. GradientEdgeTableRenderer <DestPixelType, TransformedRadialGradientPixelGenerator> renderer (destData, g, transform, lookupTable, numLookupEntries);
  66527. iter.iterate (renderer);
  66528. }
  66529. }
  66530. else
  66531. {
  66532. GradientEdgeTableRenderer <DestPixelType, LinearGradientPixelGenerator> renderer (destData, g, transform, lookupTable, numLookupEntries);
  66533. iter.iterate (renderer);
  66534. }
  66535. }
  66536. };
  66537. class ClipRegion_EdgeTable : public ClipRegionBase
  66538. {
  66539. public:
  66540. ClipRegion_EdgeTable (const EdgeTable& e) : edgeTable (e) {}
  66541. ClipRegion_EdgeTable (const Rectangle<int>& r) : edgeTable (r) {}
  66542. ClipRegion_EdgeTable (const Rectangle<float>& r) : edgeTable (r) {}
  66543. ClipRegion_EdgeTable (const RectangleList& r) : edgeTable (r) {}
  66544. ClipRegion_EdgeTable (const Rectangle<int>& bounds, const Path& p, const AffineTransform& t) : edgeTable (bounds, p, t) {}
  66545. ClipRegion_EdgeTable (const ClipRegion_EdgeTable& other) : edgeTable (other.edgeTable) {}
  66546. ~ClipRegion_EdgeTable() {}
  66547. const Ptr clone() const
  66548. {
  66549. return new ClipRegion_EdgeTable (*this);
  66550. }
  66551. const Ptr clipToRectangle (const Rectangle<int>& r)
  66552. {
  66553. edgeTable.clipToRectangle (r);
  66554. return edgeTable.isEmpty() ? 0 : this;
  66555. }
  66556. const Ptr clipToRectangleList (const RectangleList& r)
  66557. {
  66558. EdgeTable et (r);
  66559. edgeTable.clipToEdgeTable (et);
  66560. return edgeTable.isEmpty() ? 0 : this;
  66561. }
  66562. const Ptr excludeClipRectangle (const Rectangle<int>& r)
  66563. {
  66564. edgeTable.excludeRectangle (r);
  66565. return edgeTable.isEmpty() ? 0 : this;
  66566. }
  66567. const Ptr clipToPath (const Path& p, const AffineTransform& transform)
  66568. {
  66569. EdgeTable et (edgeTable.getMaximumBounds(), p, transform);
  66570. edgeTable.clipToEdgeTable (et);
  66571. return edgeTable.isEmpty() ? 0 : this;
  66572. }
  66573. const Ptr clipToEdgeTable (const EdgeTable& et)
  66574. {
  66575. edgeTable.clipToEdgeTable (et);
  66576. return edgeTable.isEmpty() ? 0 : this;
  66577. }
  66578. const Ptr clipToImageAlpha (const Image& image, const Rectangle<int>& srcClip, const AffineTransform& transform, const bool betterQuality)
  66579. {
  66580. const Image::BitmapData srcData (image, srcClip.getX(), srcClip.getY(), srcClip.getWidth(), srcClip.getHeight());
  66581. if (transform.isOnlyTranslation())
  66582. {
  66583. // If our translation doesn't involve any distortion, just use a simple blit..
  66584. const int tx = (int) (transform.getTranslationX() * 256.0f);
  66585. const int ty = (int) (transform.getTranslationY() * 256.0f);
  66586. if ((! betterQuality) || ((tx | ty) & 224) == 0)
  66587. {
  66588. const int imageX = ((tx + 128) >> 8);
  66589. const int imageY = ((ty + 128) >> 8);
  66590. if (image.getFormat() == Image::ARGB)
  66591. straightClipImage (srcData, imageX, imageY, (PixelARGB*) 0);
  66592. else
  66593. straightClipImage (srcData, imageX, imageY, (PixelAlpha*) 0);
  66594. return edgeTable.isEmpty() ? 0 : this;
  66595. }
  66596. }
  66597. if (transform.isSingularity())
  66598. return 0;
  66599. {
  66600. Path p;
  66601. p.addRectangle (0, 0, (float) srcData.width, (float) srcData.height);
  66602. EdgeTable et2 (edgeTable.getMaximumBounds(), p, transform);
  66603. edgeTable.clipToEdgeTable (et2);
  66604. }
  66605. if (! edgeTable.isEmpty())
  66606. {
  66607. if (image.getFormat() == Image::ARGB)
  66608. transformedClipImage (srcData, transform, betterQuality, (PixelARGB*) 0);
  66609. else
  66610. transformedClipImage (srcData, transform, betterQuality, (PixelAlpha*) 0);
  66611. }
  66612. return edgeTable.isEmpty() ? 0 : this;
  66613. }
  66614. bool clipRegionIntersects (const Rectangle<int>& r) const
  66615. {
  66616. return edgeTable.getMaximumBounds().intersects (r);
  66617. }
  66618. const Rectangle<int> getClipBounds() const
  66619. {
  66620. return edgeTable.getMaximumBounds();
  66621. }
  66622. void fillRectWithColour (Image::BitmapData& destData, const Rectangle<int>& area, const PixelARGB& colour, bool replaceContents) const
  66623. {
  66624. const Rectangle<int> totalClip (edgeTable.getMaximumBounds());
  66625. const Rectangle<int> clipped (totalClip.getIntersection (area));
  66626. if (! clipped.isEmpty())
  66627. {
  66628. ClipRegion_EdgeTable et (clipped);
  66629. et.edgeTable.clipToEdgeTable (edgeTable);
  66630. et.fillAllWithColour (destData, colour, replaceContents);
  66631. }
  66632. }
  66633. void fillRectWithColour (Image::BitmapData& destData, const Rectangle<float>& area, const PixelARGB& colour) const
  66634. {
  66635. const Rectangle<float> totalClip (edgeTable.getMaximumBounds().toFloat());
  66636. const Rectangle<float> clipped (totalClip.getIntersection (area));
  66637. if (! clipped.isEmpty())
  66638. {
  66639. ClipRegion_EdgeTable et (clipped);
  66640. et.edgeTable.clipToEdgeTable (edgeTable);
  66641. et.fillAllWithColour (destData, colour, false);
  66642. }
  66643. }
  66644. void fillAllWithColour (Image::BitmapData& destData, const PixelARGB& colour, bool replaceContents) const
  66645. {
  66646. switch (destData.pixelFormat)
  66647. {
  66648. case Image::ARGB: renderSolidFill (edgeTable, destData, colour, replaceContents, (PixelARGB*) 0); break;
  66649. case Image::RGB: renderSolidFill (edgeTable, destData, colour, replaceContents, (PixelRGB*) 0); break;
  66650. default: renderSolidFill (edgeTable, destData, colour, replaceContents, (PixelAlpha*) 0); break;
  66651. }
  66652. }
  66653. void fillAllWithGradient (Image::BitmapData& destData, ColourGradient& gradient, const AffineTransform& transform, bool isIdentity) const
  66654. {
  66655. HeapBlock <PixelARGB> lookupTable;
  66656. const int numLookupEntries = gradient.createLookupTable (transform, lookupTable);
  66657. jassert (numLookupEntries > 0);
  66658. switch (destData.pixelFormat)
  66659. {
  66660. case Image::ARGB: renderGradient (edgeTable, destData, gradient, transform, lookupTable, numLookupEntries, isIdentity, (PixelARGB*) 0); break;
  66661. case Image::RGB: renderGradient (edgeTable, destData, gradient, transform, lookupTable, numLookupEntries, isIdentity, (PixelRGB*) 0); break;
  66662. default: renderGradient (edgeTable, destData, gradient, transform, lookupTable, numLookupEntries, isIdentity, (PixelAlpha*) 0); break;
  66663. }
  66664. }
  66665. void renderImageTransformed (const Image::BitmapData& destData, const Image::BitmapData& srcData, const Rectangle<int>& srcClip, const int alpha, const AffineTransform& transform, bool betterQuality, bool tiledFill) const
  66666. {
  66667. renderImageTransformedInternal (edgeTable, destData, srcData, srcClip, alpha, transform, betterQuality, tiledFill);
  66668. }
  66669. void renderImageUntransformed (const Image::BitmapData& destData, const Image::BitmapData& srcData, const Rectangle<int>& srcClip, const int alpha, int x, int y, bool tiledFill) const
  66670. {
  66671. renderImageUntransformedInternal (edgeTable, destData, srcData, srcClip, alpha, x, y, tiledFill);
  66672. }
  66673. EdgeTable edgeTable;
  66674. private:
  66675. template <class SrcPixelType>
  66676. void transformedClipImage (const Image::BitmapData& srcData, const AffineTransform& transform, const bool betterQuality, const SrcPixelType*)
  66677. {
  66678. TransformedImageFillEdgeTableRenderer <SrcPixelType, SrcPixelType, false> renderer (srcData, srcData, transform, 255, betterQuality);
  66679. for (int y = 0; y < edgeTable.getMaximumBounds().getHeight(); ++y)
  66680. renderer.clipEdgeTableLine (edgeTable, edgeTable.getMaximumBounds().getX(), y + edgeTable.getMaximumBounds().getY(),
  66681. edgeTable.getMaximumBounds().getWidth());
  66682. }
  66683. template <class SrcPixelType>
  66684. void straightClipImage (const Image::BitmapData& srcData, int imageX, int imageY, const SrcPixelType*)
  66685. {
  66686. Rectangle<int> r (imageX, imageY, srcData.width, srcData.height);
  66687. edgeTable.clipToRectangle (r);
  66688. ImageFillEdgeTableRenderer <SrcPixelType, SrcPixelType, false> renderer (srcData, srcData, 255, imageX, imageY);
  66689. for (int y = 0; y < r.getHeight(); ++y)
  66690. renderer.clipEdgeTableLine (edgeTable, r.getX(), y + r.getY(), r.getWidth());
  66691. }
  66692. ClipRegion_EdgeTable& operator= (const ClipRegion_EdgeTable&);
  66693. };
  66694. class ClipRegion_RectangleList : public ClipRegionBase
  66695. {
  66696. public:
  66697. ClipRegion_RectangleList (const Rectangle<int>& r) : clip (r) {}
  66698. ClipRegion_RectangleList (const RectangleList& r) : clip (r) {}
  66699. ClipRegion_RectangleList (const ClipRegion_RectangleList& other) : clip (other.clip) {}
  66700. ~ClipRegion_RectangleList() {}
  66701. const Ptr clone() const
  66702. {
  66703. return new ClipRegion_RectangleList (*this);
  66704. }
  66705. const Ptr clipToRectangle (const Rectangle<int>& r)
  66706. {
  66707. clip.clipTo (r);
  66708. return clip.isEmpty() ? 0 : this;
  66709. }
  66710. const Ptr clipToRectangleList (const RectangleList& r)
  66711. {
  66712. clip.clipTo (r);
  66713. return clip.isEmpty() ? 0 : this;
  66714. }
  66715. const Ptr excludeClipRectangle (const Rectangle<int>& r)
  66716. {
  66717. clip.subtract (r);
  66718. return clip.isEmpty() ? 0 : this;
  66719. }
  66720. const Ptr clipToPath (const Path& p, const AffineTransform& transform)
  66721. {
  66722. return Ptr (new ClipRegion_EdgeTable (clip))->clipToPath (p, transform);
  66723. }
  66724. const Ptr clipToEdgeTable (const EdgeTable& et)
  66725. {
  66726. return Ptr (new ClipRegion_EdgeTable (clip))->clipToEdgeTable (et);
  66727. }
  66728. const Ptr clipToImageAlpha (const Image& image, const Rectangle<int>& srcClip, const AffineTransform& transform, const bool betterQuality)
  66729. {
  66730. return Ptr (new ClipRegion_EdgeTable (clip))->clipToImageAlpha (image, srcClip, transform, betterQuality);
  66731. }
  66732. bool clipRegionIntersects (const Rectangle<int>& r) const
  66733. {
  66734. return clip.intersects (r);
  66735. }
  66736. const Rectangle<int> getClipBounds() const
  66737. {
  66738. return clip.getBounds();
  66739. }
  66740. void fillRectWithColour (Image::BitmapData& destData, const Rectangle<int>& area, const PixelARGB& colour, bool replaceContents) const
  66741. {
  66742. SubRectangleIterator iter (clip, area);
  66743. switch (destData.pixelFormat)
  66744. {
  66745. case Image::ARGB: renderSolidFill (iter, destData, colour, replaceContents, (PixelARGB*) 0); break;
  66746. case Image::RGB: renderSolidFill (iter, destData, colour, replaceContents, (PixelRGB*) 0); break;
  66747. default: renderSolidFill (iter, destData, colour, replaceContents, (PixelAlpha*) 0); break;
  66748. }
  66749. }
  66750. void fillRectWithColour (Image::BitmapData& destData, const Rectangle<float>& area, const PixelARGB& colour) const
  66751. {
  66752. SubRectangleIteratorFloat iter (clip, area);
  66753. switch (destData.pixelFormat)
  66754. {
  66755. case Image::ARGB: renderSolidFill (iter, destData, colour, false, (PixelARGB*) 0); break;
  66756. case Image::RGB: renderSolidFill (iter, destData, colour, false, (PixelRGB*) 0); break;
  66757. default: renderSolidFill (iter, destData, colour, false, (PixelAlpha*) 0); break;
  66758. }
  66759. }
  66760. void fillAllWithColour (Image::BitmapData& destData, const PixelARGB& colour, bool replaceContents) const
  66761. {
  66762. switch (destData.pixelFormat)
  66763. {
  66764. case Image::ARGB: renderSolidFill (*this, destData, colour, replaceContents, (PixelARGB*) 0); break;
  66765. case Image::RGB: renderSolidFill (*this, destData, colour, replaceContents, (PixelRGB*) 0); break;
  66766. default: renderSolidFill (*this, destData, colour, replaceContents, (PixelAlpha*) 0); break;
  66767. }
  66768. }
  66769. void fillAllWithGradient (Image::BitmapData& destData, ColourGradient& gradient, const AffineTransform& transform, bool isIdentity) const
  66770. {
  66771. HeapBlock <PixelARGB> lookupTable;
  66772. const int numLookupEntries = gradient.createLookupTable (transform, lookupTable);
  66773. jassert (numLookupEntries > 0);
  66774. switch (destData.pixelFormat)
  66775. {
  66776. case Image::ARGB: renderGradient (*this, destData, gradient, transform, lookupTable, numLookupEntries, isIdentity, (PixelARGB*) 0); break;
  66777. case Image::RGB: renderGradient (*this, destData, gradient, transform, lookupTable, numLookupEntries, isIdentity, (PixelRGB*) 0); break;
  66778. default: renderGradient (*this, destData, gradient, transform, lookupTable, numLookupEntries, isIdentity, (PixelAlpha*) 0); break;
  66779. }
  66780. }
  66781. void renderImageTransformed (const Image::BitmapData& destData, const Image::BitmapData& srcData, const Rectangle<int>& srcClip, const int alpha, const AffineTransform& transform, bool betterQuality, bool tiledFill) const
  66782. {
  66783. renderImageTransformedInternal (*this, destData, srcData, srcClip, alpha, transform, betterQuality, tiledFill);
  66784. }
  66785. void renderImageUntransformed (const Image::BitmapData& destData, const Image::BitmapData& srcData, const Rectangle<int>& srcClip, const int alpha, int x, int y, bool tiledFill) const
  66786. {
  66787. renderImageUntransformedInternal (*this, destData, srcData, srcClip, alpha, x, y, tiledFill);
  66788. }
  66789. RectangleList clip;
  66790. template <class Renderer>
  66791. void iterate (Renderer& r) const throw()
  66792. {
  66793. RectangleList::Iterator iter (clip);
  66794. while (iter.next())
  66795. {
  66796. const Rectangle<int> rect (*iter.getRectangle());
  66797. const int x = rect.getX();
  66798. const int w = rect.getWidth();
  66799. jassert (w > 0);
  66800. const int bottom = rect.getBottom();
  66801. for (int y = rect.getY(); y < bottom; ++y)
  66802. {
  66803. r.setEdgeTableYPos (y);
  66804. r.handleEdgeTableLine (x, w, 255);
  66805. }
  66806. }
  66807. }
  66808. private:
  66809. class SubRectangleIterator
  66810. {
  66811. public:
  66812. SubRectangleIterator (const RectangleList& clip_, const Rectangle<int>& area_)
  66813. : clip (clip_), area (area_)
  66814. {
  66815. }
  66816. template <class Renderer>
  66817. void iterate (Renderer& r) const throw()
  66818. {
  66819. RectangleList::Iterator iter (clip);
  66820. while (iter.next())
  66821. {
  66822. const Rectangle<int> rect (iter.getRectangle()->getIntersection (area));
  66823. if (! rect.isEmpty())
  66824. {
  66825. const int x = rect.getX();
  66826. const int w = rect.getWidth();
  66827. const int bottom = rect.getBottom();
  66828. for (int y = rect.getY(); y < bottom; ++y)
  66829. {
  66830. r.setEdgeTableYPos (y);
  66831. r.handleEdgeTableLine (x, w, 255);
  66832. }
  66833. }
  66834. }
  66835. }
  66836. private:
  66837. const RectangleList& clip;
  66838. const Rectangle<int> area;
  66839. };
  66840. class SubRectangleIteratorFloat
  66841. {
  66842. public:
  66843. SubRectangleIteratorFloat (const RectangleList& clip_, const Rectangle<float>& area_)
  66844. : clip (clip_), area (area_)
  66845. {
  66846. }
  66847. template <class Renderer>
  66848. void iterate (Renderer& r) const throw()
  66849. {
  66850. int left = roundToInt (area.getX() * 256.0f);
  66851. int top = roundToInt (area.getY() * 256.0f);
  66852. int right = roundToInt (area.getRight() * 256.0f);
  66853. int bottom = roundToInt (area.getBottom() * 256.0f);
  66854. int totalTop, totalLeft, totalBottom, totalRight;
  66855. int topAlpha, leftAlpha, bottomAlpha, rightAlpha;
  66856. if ((top >> 8) == (bottom >> 8))
  66857. {
  66858. topAlpha = bottom - top;
  66859. bottomAlpha = 0;
  66860. totalTop = top >> 8;
  66861. totalBottom = bottom = top = totalTop + 1;
  66862. }
  66863. else
  66864. {
  66865. if ((top & 255) == 0)
  66866. {
  66867. topAlpha = 0;
  66868. top = totalTop = (top >> 8);
  66869. }
  66870. else
  66871. {
  66872. topAlpha = 255 - (top & 255);
  66873. totalTop = (top >> 8);
  66874. top = totalTop + 1;
  66875. }
  66876. bottomAlpha = bottom & 255;
  66877. bottom >>= 8;
  66878. totalBottom = bottom + (bottomAlpha != 0 ? 1 : 0);
  66879. }
  66880. if ((left >> 8) == (right >> 8))
  66881. {
  66882. leftAlpha = right - left;
  66883. rightAlpha = 0;
  66884. totalLeft = (left >> 8);
  66885. totalRight = right = left = totalLeft + 1;
  66886. }
  66887. else
  66888. {
  66889. if ((left & 255) == 0)
  66890. {
  66891. leftAlpha = 0;
  66892. left = totalLeft = (left >> 8);
  66893. }
  66894. else
  66895. {
  66896. leftAlpha = 255 - (left & 255);
  66897. totalLeft = (left >> 8);
  66898. left = totalLeft + 1;
  66899. }
  66900. rightAlpha = right & 255;
  66901. right >>= 8;
  66902. totalRight = right + (rightAlpha != 0 ? 1 : 0);
  66903. }
  66904. RectangleList::Iterator iter (clip);
  66905. while (iter.next())
  66906. {
  66907. const int clipLeft = iter.getRectangle()->getX();
  66908. const int clipRight = iter.getRectangle()->getRight();
  66909. const int clipTop = iter.getRectangle()->getY();
  66910. const int clipBottom = iter.getRectangle()->getBottom();
  66911. if (totalBottom > clipTop && totalTop < clipBottom && totalRight > clipLeft && totalLeft < clipRight)
  66912. {
  66913. if (right - left == 1 && leftAlpha + rightAlpha == 0) // special case for 1-pix vertical lines
  66914. {
  66915. if (topAlpha != 0 && totalTop >= clipTop)
  66916. {
  66917. r.setEdgeTableYPos (totalTop);
  66918. r.handleEdgeTablePixel (left, topAlpha);
  66919. }
  66920. const int endY = jmin (bottom, clipBottom);
  66921. for (int y = jmax (clipTop, top); y < endY; ++y)
  66922. {
  66923. r.setEdgeTableYPos (y);
  66924. r.handleEdgeTablePixel (left, 255);
  66925. }
  66926. if (bottomAlpha != 0 && bottom < clipBottom)
  66927. {
  66928. r.setEdgeTableYPos (bottom);
  66929. r.handleEdgeTablePixel (left, bottomAlpha);
  66930. }
  66931. }
  66932. else
  66933. {
  66934. const int clippedLeft = jmax (left, clipLeft);
  66935. const int clippedWidth = jmin (right, clipRight) - clippedLeft;
  66936. const bool doLeftAlpha = leftAlpha != 0 && totalLeft >= clipLeft;
  66937. const bool doRightAlpha = rightAlpha != 0 && right < clipRight;
  66938. if (topAlpha != 0 && totalTop >= clipTop)
  66939. {
  66940. r.setEdgeTableYPos (totalTop);
  66941. if (doLeftAlpha)
  66942. r.handleEdgeTablePixel (totalLeft, (leftAlpha * topAlpha) >> 8);
  66943. if (clippedWidth > 0)
  66944. r.handleEdgeTableLine (clippedLeft, clippedWidth, topAlpha);
  66945. if (doRightAlpha)
  66946. r.handleEdgeTablePixel (right, (rightAlpha * topAlpha) >> 8);
  66947. }
  66948. const int endY = jmin (bottom, clipBottom);
  66949. for (int y = jmax (clipTop, top); y < endY; ++y)
  66950. {
  66951. r.setEdgeTableYPos (y);
  66952. if (doLeftAlpha)
  66953. r.handleEdgeTablePixel (totalLeft, leftAlpha);
  66954. if (clippedWidth > 0)
  66955. r.handleEdgeTableLine (clippedLeft, clippedWidth, 255);
  66956. if (doRightAlpha)
  66957. r.handleEdgeTablePixel (right, rightAlpha);
  66958. }
  66959. if (bottomAlpha != 0 && bottom < clipBottom)
  66960. {
  66961. r.setEdgeTableYPos (bottom);
  66962. if (doLeftAlpha)
  66963. r.handleEdgeTablePixel (totalLeft, (leftAlpha * bottomAlpha) >> 8);
  66964. if (clippedWidth > 0)
  66965. r.handleEdgeTableLine (clippedLeft, clippedWidth, bottomAlpha);
  66966. if (doRightAlpha)
  66967. r.handleEdgeTablePixel (right, (rightAlpha * bottomAlpha) >> 8);
  66968. }
  66969. }
  66970. }
  66971. }
  66972. }
  66973. private:
  66974. const RectangleList& clip;
  66975. const Rectangle<float>& area;
  66976. };
  66977. ClipRegion_RectangleList& operator= (const ClipRegion_RectangleList&);
  66978. };
  66979. const ClipRegionBase::Ptr ClipRegionBase::clipTo (ClipRegionBase* const other)
  66980. {
  66981. ClipRegion_EdgeTable* et = dynamic_cast <ClipRegion_EdgeTable*> (other);
  66982. if (et != 0)
  66983. return clipToEdgeTable (et->edgeTable);
  66984. ClipRegion_RectangleList* rl = dynamic_cast <ClipRegion_RectangleList*> (other);
  66985. if (rl != 0)
  66986. return clipToRectangleList (rl->clip);
  66987. jassertfalse
  66988. return 0;
  66989. }
  66990. class LLGCSavedState
  66991. {
  66992. public:
  66993. LLGCSavedState (const Rectangle<int>& clip_, const int xOffset_, const int yOffset_)
  66994. : clip (new ClipRegion_RectangleList (clip_)),
  66995. xOffset (xOffset_), yOffset (yOffset_),
  66996. interpolationQuality (Graphics::mediumResamplingQuality)
  66997. {
  66998. }
  66999. LLGCSavedState (const RectangleList& clip_, const int xOffset_, const int yOffset_)
  67000. : clip (new ClipRegion_RectangleList (clip_)),
  67001. xOffset (xOffset_), yOffset (yOffset_),
  67002. interpolationQuality (Graphics::mediumResamplingQuality)
  67003. {
  67004. }
  67005. LLGCSavedState (const LLGCSavedState& other)
  67006. : clip (other.clip), xOffset (other.xOffset),
  67007. yOffset (other.yOffset), font (other.font),
  67008. fillType (other.fillType), interpolationQuality (other.interpolationQuality)
  67009. {
  67010. }
  67011. ~LLGCSavedState()
  67012. {
  67013. }
  67014. void setOrigin (const int x, const int y) throw()
  67015. {
  67016. xOffset += x;
  67017. yOffset += y;
  67018. }
  67019. bool clipToRectangle (const Rectangle<int>& r)
  67020. {
  67021. if (clip != 0)
  67022. {
  67023. cloneClipIfMultiplyReferenced();
  67024. clip = clip->clipToRectangle (r.translated (xOffset, yOffset));
  67025. }
  67026. return clip != 0;
  67027. }
  67028. bool clipToRectangleList (const RectangleList& r)
  67029. {
  67030. if (clip != 0)
  67031. {
  67032. cloneClipIfMultiplyReferenced();
  67033. RectangleList offsetList (r);
  67034. offsetList.offsetAll (xOffset, yOffset);
  67035. clip = clip->clipToRectangleList (offsetList);
  67036. }
  67037. return clip != 0;
  67038. }
  67039. bool excludeClipRectangle (const Rectangle<int>& r)
  67040. {
  67041. if (clip != 0)
  67042. {
  67043. cloneClipIfMultiplyReferenced();
  67044. clip = clip->excludeClipRectangle (r.translated (xOffset, yOffset));
  67045. }
  67046. return clip != 0;
  67047. }
  67048. void clipToPath (const Path& p, const AffineTransform& transform)
  67049. {
  67050. if (clip != 0)
  67051. {
  67052. cloneClipIfMultiplyReferenced();
  67053. clip = clip->clipToPath (p, transform.translated ((float) xOffset, (float) yOffset));
  67054. }
  67055. }
  67056. void clipToImageAlpha (const Image& image, const Rectangle<int>& srcClip, const AffineTransform& t)
  67057. {
  67058. if (clip != 0)
  67059. {
  67060. if (image.hasAlphaChannel())
  67061. {
  67062. cloneClipIfMultiplyReferenced();
  67063. clip = clip->clipToImageAlpha (image, srcClip, t.translated ((float) xOffset, (float) yOffset),
  67064. interpolationQuality != Graphics::lowResamplingQuality);
  67065. }
  67066. else
  67067. {
  67068. Path p;
  67069. p.addRectangle (srcClip);
  67070. clipToPath (p, t);
  67071. }
  67072. }
  67073. }
  67074. bool clipRegionIntersects (const Rectangle<int>& r) const
  67075. {
  67076. return clip != 0 && clip->clipRegionIntersects (r.translated (xOffset, yOffset));
  67077. }
  67078. const Rectangle<int> getClipBounds() const
  67079. {
  67080. return clip == 0 ? Rectangle<int>() : clip->getClipBounds().translated (-xOffset, -yOffset);
  67081. }
  67082. void fillRect (Image& image, const Rectangle<int>& r, const bool replaceContents)
  67083. {
  67084. if (clip != 0)
  67085. {
  67086. if (fillType.isColour())
  67087. {
  67088. Image::BitmapData destData (image, 0, 0, image.getWidth(), image.getHeight(), true);
  67089. clip->fillRectWithColour (destData, r.translated (xOffset, yOffset), fillType.colour.getPixelARGB(), replaceContents);
  67090. }
  67091. else
  67092. {
  67093. const Rectangle<int> totalClip (clip->getClipBounds());
  67094. const Rectangle<int> clipped (totalClip.getIntersection (r.translated (xOffset, yOffset)));
  67095. if (! clipped.isEmpty())
  67096. fillShape (image, new ClipRegion_RectangleList (clipped), false);
  67097. }
  67098. }
  67099. }
  67100. void fillRect (Image& image, const Rectangle<float>& r)
  67101. {
  67102. if (clip != 0)
  67103. {
  67104. if (fillType.isColour())
  67105. {
  67106. Image::BitmapData destData (image, 0, 0, image.getWidth(), image.getHeight(), true);
  67107. clip->fillRectWithColour (destData, r.translated ((float) xOffset, (float) yOffset), fillType.colour.getPixelARGB());
  67108. }
  67109. else
  67110. {
  67111. const Rectangle<float> totalClip (clip->getClipBounds().toFloat());
  67112. const Rectangle<float> clipped (totalClip.getIntersection (r.translated ((float) xOffset, (float) yOffset)));
  67113. if (! clipped.isEmpty())
  67114. fillShape (image, new ClipRegion_EdgeTable (clipped), false);
  67115. }
  67116. }
  67117. }
  67118. void fillPath (Image& image, const Path& path, const AffineTransform& transform)
  67119. {
  67120. if (clip != 0)
  67121. fillShape (image, new ClipRegion_EdgeTable (clip->getClipBounds(), path, transform.translated ((float) xOffset, (float) yOffset)), false);
  67122. }
  67123. void fillEdgeTable (Image& image, const EdgeTable& edgeTable, const float x, const int y)
  67124. {
  67125. if (clip != 0)
  67126. {
  67127. ClipRegion_EdgeTable* edgeTableClip = new ClipRegion_EdgeTable (edgeTable);
  67128. ClipRegionBase::Ptr shapeToFill (edgeTableClip);
  67129. edgeTableClip->edgeTable.translate (x + xOffset, y + yOffset);
  67130. fillShape (image, shapeToFill, false);
  67131. }
  67132. }
  67133. void fillShape (Image& image, ClipRegionBase::Ptr shapeToFill, const bool replaceContents)
  67134. {
  67135. jassert (clip != 0);
  67136. shapeToFill = shapeToFill->clipTo (clip);
  67137. if (shapeToFill != 0)
  67138. fillShapeWithoutClipping (image, shapeToFill, replaceContents);
  67139. }
  67140. void fillShapeWithoutClipping (Image& image, const ClipRegionBase::Ptr& shapeToFill, const bool replaceContents)
  67141. {
  67142. Image::BitmapData destData (image, 0, 0, image.getWidth(), image.getHeight(), true);
  67143. if (fillType.isGradient())
  67144. {
  67145. jassert (! replaceContents); // that option is just for solid colours
  67146. ColourGradient g2 (*(fillType.gradient));
  67147. g2.multiplyOpacity (fillType.getOpacity());
  67148. g2.x1 -= 0.5f; g2.y1 -= 0.5f;
  67149. g2.x2 -= 0.5f; g2.y2 -= 0.5f;
  67150. AffineTransform transform (fillType.transform.translated ((float) xOffset, (float) yOffset));
  67151. const bool isIdentity = transform.isOnlyTranslation();
  67152. if (isIdentity)
  67153. {
  67154. // If our translation doesn't involve any distortion, we can speed it up..
  67155. transform.transformPoint (g2.x1, g2.y1);
  67156. transform.transformPoint (g2.x2, g2.y2);
  67157. transform = AffineTransform::identity;
  67158. }
  67159. shapeToFill->fillAllWithGradient (destData, g2, transform, isIdentity);
  67160. }
  67161. else if (fillType.isTiledImage())
  67162. {
  67163. renderImage (image, *(fillType.image), fillType.image->getBounds(), fillType.transform, shapeToFill);
  67164. }
  67165. else
  67166. {
  67167. shapeToFill->fillAllWithColour (destData, fillType.colour.getPixelARGB(), replaceContents);
  67168. }
  67169. }
  67170. void renderImage (Image& destImage, const Image& sourceImage, const Rectangle<int>& srcClip,
  67171. const AffineTransform& t, const ClipRegionBase* const tiledFillClipRegion)
  67172. {
  67173. const AffineTransform transform (t.translated ((float) xOffset, (float) yOffset));
  67174. const Image::BitmapData destData (destImage, 0, 0, destImage.getWidth(), destImage.getHeight(), true);
  67175. const Image::BitmapData srcData (sourceImage, srcClip.getX(), srcClip.getY(), srcClip.getWidth(), srcClip.getHeight());
  67176. const int alpha = fillType.colour.getAlpha();
  67177. const bool betterQuality = (interpolationQuality != Graphics::lowResamplingQuality);
  67178. if (transform.isOnlyTranslation())
  67179. {
  67180. // If our translation doesn't involve any distortion, just use a simple blit..
  67181. int tx = (int) (transform.getTranslationX() * 256.0f);
  67182. int ty = (int) (transform.getTranslationY() * 256.0f);
  67183. if ((! betterQuality) || ((tx | ty) & 224) == 0)
  67184. {
  67185. tx = ((tx + 128) >> 8);
  67186. ty = ((ty + 128) >> 8);
  67187. if (tiledFillClipRegion != 0)
  67188. {
  67189. tiledFillClipRegion->renderImageUntransformed (destData, srcData, srcClip, alpha, tx, ty, true);
  67190. }
  67191. else
  67192. {
  67193. ClipRegionBase::Ptr c (new ClipRegion_EdgeTable (Rectangle<int> (tx, ty, srcClip.getWidth(), srcClip.getHeight()).getIntersection (destImage.getBounds())));
  67194. c = c->clipTo (clip);
  67195. if (c != 0)
  67196. c->renderImageUntransformed (destData, srcData, srcClip, alpha, tx, ty, false);
  67197. }
  67198. return;
  67199. }
  67200. }
  67201. if (transform.isSingularity())
  67202. return;
  67203. if (tiledFillClipRegion != 0)
  67204. {
  67205. tiledFillClipRegion->renderImageTransformed (destData, srcData, srcClip, alpha, transform, betterQuality, true);
  67206. }
  67207. else
  67208. {
  67209. Path p;
  67210. p.addRectangle (0.0f, 0.0f, (float) srcClip.getWidth(), (float) srcClip.getHeight());
  67211. ClipRegionBase::Ptr c (clip->clone());
  67212. c = c->clipToPath (p, transform);
  67213. if (c != 0)
  67214. c->renderImageTransformed (destData, srcData, srcClip, alpha, transform, betterQuality, true);
  67215. }
  67216. }
  67217. ClipRegionBase::Ptr clip;
  67218. int xOffset, yOffset;
  67219. Font font;
  67220. FillType fillType;
  67221. Graphics::ResamplingQuality interpolationQuality;
  67222. private:
  67223. void cloneClipIfMultiplyReferenced()
  67224. {
  67225. if (clip->getReferenceCount() > 1)
  67226. clip = clip->clone();
  67227. }
  67228. LLGCSavedState& operator= (const LLGCSavedState&);
  67229. };
  67230. LowLevelGraphicsSoftwareRenderer::LowLevelGraphicsSoftwareRenderer (Image& image_)
  67231. : image (image_)
  67232. {
  67233. currentState = new LLGCSavedState (image_.getBounds(), 0, 0);
  67234. }
  67235. LowLevelGraphicsSoftwareRenderer::LowLevelGraphicsSoftwareRenderer (Image& image_, const int xOffset, const int yOffset,
  67236. const RectangleList& initialClip)
  67237. : image (image_)
  67238. {
  67239. currentState = new LLGCSavedState (initialClip, xOffset, yOffset);
  67240. }
  67241. LowLevelGraphicsSoftwareRenderer::~LowLevelGraphicsSoftwareRenderer()
  67242. {
  67243. }
  67244. bool LowLevelGraphicsSoftwareRenderer::isVectorDevice() const
  67245. {
  67246. return false;
  67247. }
  67248. void LowLevelGraphicsSoftwareRenderer::setOrigin (int x, int y)
  67249. {
  67250. currentState->setOrigin (x, y);
  67251. }
  67252. bool LowLevelGraphicsSoftwareRenderer::clipToRectangle (const Rectangle<int>& r)
  67253. {
  67254. return currentState->clipToRectangle (r);
  67255. }
  67256. bool LowLevelGraphicsSoftwareRenderer::clipToRectangleList (const RectangleList& clipRegion)
  67257. {
  67258. return currentState->clipToRectangleList (clipRegion);
  67259. }
  67260. void LowLevelGraphicsSoftwareRenderer::excludeClipRectangle (const Rectangle<int>& r)
  67261. {
  67262. currentState->excludeClipRectangle (r);
  67263. }
  67264. void LowLevelGraphicsSoftwareRenderer::clipToPath (const Path& path, const AffineTransform& transform)
  67265. {
  67266. currentState->clipToPath (path, transform);
  67267. }
  67268. void LowLevelGraphicsSoftwareRenderer::clipToImageAlpha (const Image& sourceImage, const Rectangle<int>& srcClip, const AffineTransform& transform)
  67269. {
  67270. currentState->clipToImageAlpha (sourceImage, srcClip, transform);
  67271. }
  67272. bool LowLevelGraphicsSoftwareRenderer::clipRegionIntersects (const Rectangle<int>& r)
  67273. {
  67274. return currentState->clipRegionIntersects (r);
  67275. }
  67276. const Rectangle<int> LowLevelGraphicsSoftwareRenderer::getClipBounds() const
  67277. {
  67278. return currentState->getClipBounds();
  67279. }
  67280. bool LowLevelGraphicsSoftwareRenderer::isClipEmpty() const
  67281. {
  67282. return currentState->clip == 0;
  67283. }
  67284. void LowLevelGraphicsSoftwareRenderer::saveState()
  67285. {
  67286. stateStack.add (new LLGCSavedState (*currentState));
  67287. }
  67288. void LowLevelGraphicsSoftwareRenderer::restoreState()
  67289. {
  67290. LLGCSavedState* const top = stateStack.getLast();
  67291. if (top != 0)
  67292. {
  67293. currentState = top;
  67294. stateStack.removeLast (1, false);
  67295. }
  67296. else
  67297. {
  67298. jassertfalse // trying to pop with an empty stack!
  67299. }
  67300. }
  67301. void LowLevelGraphicsSoftwareRenderer::setFill (const FillType& fillType)
  67302. {
  67303. currentState->fillType = fillType;
  67304. }
  67305. void LowLevelGraphicsSoftwareRenderer::setOpacity (float newOpacity)
  67306. {
  67307. currentState->fillType.setOpacity (newOpacity);
  67308. }
  67309. void LowLevelGraphicsSoftwareRenderer::setInterpolationQuality (Graphics::ResamplingQuality quality)
  67310. {
  67311. currentState->interpolationQuality = quality;
  67312. }
  67313. void LowLevelGraphicsSoftwareRenderer::fillRect (const Rectangle<int>& r, const bool replaceExistingContents)
  67314. {
  67315. currentState->fillRect (image, r, replaceExistingContents);
  67316. }
  67317. void LowLevelGraphicsSoftwareRenderer::fillPath (const Path& path, const AffineTransform& transform)
  67318. {
  67319. currentState->fillPath (image, path, transform);
  67320. }
  67321. void LowLevelGraphicsSoftwareRenderer::drawImage (const Image& sourceImage, const Rectangle<int>& srcClip,
  67322. const AffineTransform& transform, const bool fillEntireClipAsTiles)
  67323. {
  67324. jassert (sourceImage.getBounds().contains (srcClip));
  67325. currentState->renderImage (image, sourceImage, srcClip, transform,
  67326. fillEntireClipAsTiles ? currentState->clip : 0);
  67327. }
  67328. void LowLevelGraphicsSoftwareRenderer::drawLine (double x1, double y1, double x2, double y2)
  67329. {
  67330. Path p;
  67331. p.addLineSegment ((float) x1, (float) y1, (float) x2, (float) y2, 1.0f);
  67332. fillPath (p, AffineTransform::identity);
  67333. }
  67334. void LowLevelGraphicsSoftwareRenderer::drawVerticalLine (const int x, double top, double bottom)
  67335. {
  67336. if (bottom > top)
  67337. currentState->fillRect (image, Rectangle<float> ((float) x, (float) top, 1.0f, (float) (bottom - top)));
  67338. }
  67339. void LowLevelGraphicsSoftwareRenderer::drawHorizontalLine (const int y, double left, double right)
  67340. {
  67341. if (right > left)
  67342. currentState->fillRect (image, Rectangle<float> ((float) left, (float) y, (float) (right - left), 1.0f));
  67343. }
  67344. class GlyphCache : private DeletedAtShutdown
  67345. {
  67346. public:
  67347. GlyphCache()
  67348. : accessCounter (0), hits (0), misses (0)
  67349. {
  67350. for (int i = 120; --i >= 0;)
  67351. glyphs.add (new CachedGlyph());
  67352. }
  67353. ~GlyphCache()
  67354. {
  67355. clearSingletonInstance();
  67356. }
  67357. juce_DeclareSingleton_SingleThreaded_Minimal (GlyphCache);
  67358. void drawGlyph (LLGCSavedState& state, Image& image, const Font& font, const int glyphNumber, float x, float y)
  67359. {
  67360. ++accessCounter;
  67361. int oldestCounter = std::numeric_limits<int>::max();
  67362. CachedGlyph* oldest = 0;
  67363. for (int i = glyphs.size(); --i >= 0;)
  67364. {
  67365. CachedGlyph* const glyph = glyphs.getUnchecked (i);
  67366. if (glyph->glyph == glyphNumber && glyph->font == font)
  67367. {
  67368. ++hits;
  67369. glyph->lastAccessCount = accessCounter;
  67370. glyph->draw (state, image, x, y);
  67371. return;
  67372. }
  67373. if (glyph->lastAccessCount <= oldestCounter)
  67374. {
  67375. oldestCounter = glyph->lastAccessCount;
  67376. oldest = glyph;
  67377. }
  67378. }
  67379. if (hits + ++misses > (glyphs.size() << 4))
  67380. {
  67381. if (misses * 2 > hits)
  67382. {
  67383. for (int i = 32; --i >= 0;)
  67384. glyphs.add (new CachedGlyph());
  67385. }
  67386. hits = misses = 0;
  67387. oldest = glyphs.getLast();
  67388. }
  67389. jassert (oldest != 0);
  67390. oldest->lastAccessCount = accessCounter;
  67391. oldest->generate (font, glyphNumber);
  67392. oldest->draw (state, image, x, y);
  67393. }
  67394. class CachedGlyph
  67395. {
  67396. public:
  67397. CachedGlyph() : glyph (0), lastAccessCount (0) {}
  67398. ~CachedGlyph() {}
  67399. void draw (LLGCSavedState& state, Image& image, const float x, const float y) const
  67400. {
  67401. if (edgeTable != 0)
  67402. state.fillEdgeTable (image, *edgeTable, x, roundToInt (y));
  67403. }
  67404. void generate (const Font& newFont, const int glyphNumber)
  67405. {
  67406. font = newFont;
  67407. glyph = glyphNumber;
  67408. edgeTable = 0;
  67409. Path glyphPath;
  67410. font.getTypeface()->getOutlineForGlyph (glyphNumber, glyphPath);
  67411. if (! glyphPath.isEmpty())
  67412. {
  67413. const float fontHeight = font.getHeight();
  67414. const AffineTransform transform (AffineTransform::scale (fontHeight * font.getHorizontalScale(), fontHeight)
  67415. .translated (0.0f, -0.5f));
  67416. edgeTable = new EdgeTable (glyphPath.getBoundsTransformed (transform).getSmallestIntegerContainer().expanded (1, 0),
  67417. glyphPath, transform);
  67418. }
  67419. }
  67420. int glyph, lastAccessCount;
  67421. Font font;
  67422. juce_UseDebuggingNewOperator
  67423. private:
  67424. ScopedPointer <EdgeTable> edgeTable;
  67425. CachedGlyph (const CachedGlyph&);
  67426. CachedGlyph& operator= (const CachedGlyph&);
  67427. };
  67428. juce_UseDebuggingNewOperator
  67429. private:
  67430. OwnedArray <CachedGlyph> glyphs;
  67431. int accessCounter, hits, misses;
  67432. GlyphCache (const GlyphCache&);
  67433. GlyphCache& operator= (const GlyphCache&);
  67434. };
  67435. juce_ImplementSingleton_SingleThreaded (GlyphCache);
  67436. void LowLevelGraphicsSoftwareRenderer::setFont (const Font& newFont)
  67437. {
  67438. currentState->font = newFont;
  67439. }
  67440. const Font LowLevelGraphicsSoftwareRenderer::getFont()
  67441. {
  67442. return currentState->font;
  67443. }
  67444. void LowLevelGraphicsSoftwareRenderer::drawGlyph (int glyphNumber, const AffineTransform& transform)
  67445. {
  67446. Font& f = currentState->font;
  67447. if (transform.isOnlyTranslation())
  67448. {
  67449. GlyphCache::getInstance()->drawGlyph (*currentState, image, f, glyphNumber,
  67450. transform.getTranslationX(),
  67451. transform.getTranslationY());
  67452. }
  67453. else
  67454. {
  67455. Path p;
  67456. f.getTypeface()->getOutlineForGlyph (glyphNumber, p);
  67457. fillPath (p, AffineTransform::scale (f.getHeight() * f.getHorizontalScale(), f.getHeight()).followedBy (transform));
  67458. }
  67459. }
  67460. #if JUCE_MSVC
  67461. #pragma warning (pop)
  67462. #if JUCE_DEBUG
  67463. #pragma optimize ("", on) // resets optimisations to the project defaults
  67464. #endif
  67465. #endif
  67466. END_JUCE_NAMESPACE
  67467. /*** End of inlined file: juce_LowLevelGraphicsSoftwareRenderer.cpp ***/
  67468. /*** Start of inlined file: juce_RectanglePlacement.cpp ***/
  67469. BEGIN_JUCE_NAMESPACE
  67470. RectanglePlacement::RectanglePlacement (const RectanglePlacement& other) throw()
  67471. : flags (other.flags)
  67472. {
  67473. }
  67474. RectanglePlacement& RectanglePlacement::operator= (const RectanglePlacement& other) throw()
  67475. {
  67476. flags = other.flags;
  67477. return *this;
  67478. }
  67479. void RectanglePlacement::applyTo (double& x, double& y,
  67480. double& w, double& h,
  67481. const double dx, const double dy,
  67482. const double dw, const double dh) const throw()
  67483. {
  67484. if (w == 0 || h == 0)
  67485. return;
  67486. if ((flags & stretchToFit) != 0)
  67487. {
  67488. x = dx;
  67489. y = dy;
  67490. w = dw;
  67491. h = dh;
  67492. }
  67493. else
  67494. {
  67495. double scale = (flags & fillDestination) != 0 ? jmax (dw / w, dh / h)
  67496. : jmin (dw / w, dh / h);
  67497. if ((flags & onlyReduceInSize) != 0)
  67498. scale = jmin (scale, 1.0);
  67499. if ((flags & onlyIncreaseInSize) != 0)
  67500. scale = jmax (scale, 1.0);
  67501. w *= scale;
  67502. h *= scale;
  67503. if ((flags & xLeft) != 0)
  67504. x = dx;
  67505. else if ((flags & xRight) != 0)
  67506. x = dx + dw - w;
  67507. else
  67508. x = dx + (dw - w) * 0.5;
  67509. if ((flags & yTop) != 0)
  67510. y = dy;
  67511. else if ((flags & yBottom) != 0)
  67512. y = dy + dh - h;
  67513. else
  67514. y = dy + (dh - h) * 0.5;
  67515. }
  67516. }
  67517. const AffineTransform RectanglePlacement::getTransformToFit (float x, float y,
  67518. float w, float h,
  67519. const float dx, const float dy,
  67520. const float dw, const float dh) const throw()
  67521. {
  67522. if (w == 0 || h == 0)
  67523. return AffineTransform::identity;
  67524. const float scaleX = dw / w;
  67525. const float scaleY = dh / h;
  67526. if ((flags & stretchToFit) != 0)
  67527. return AffineTransform::translation (-x, -y)
  67528. .scaled (scaleX, scaleY)
  67529. .translated (dx, dy);
  67530. float scale = (flags & fillDestination) != 0 ? jmax (scaleX, scaleY)
  67531. : jmin (scaleX, scaleY);
  67532. if ((flags & onlyReduceInSize) != 0)
  67533. scale = jmin (scale, 1.0f);
  67534. if ((flags & onlyIncreaseInSize) != 0)
  67535. scale = jmax (scale, 1.0f);
  67536. w *= scale;
  67537. h *= scale;
  67538. float newX = dx;
  67539. if ((flags & xRight) != 0)
  67540. newX += dw - w; // right
  67541. else if ((flags & xLeft) == 0)
  67542. newX += (dw - w) / 2.0f; // centre
  67543. float newY = dy;
  67544. if ((flags & yBottom) != 0)
  67545. newY += dh - h; // bottom
  67546. else if ((flags & yTop) == 0)
  67547. newY += (dh - h) / 2.0f; // centre
  67548. return AffineTransform::translation (-x, -y)
  67549. .scaled (scale, scale)
  67550. .translated (newX, newY);
  67551. }
  67552. END_JUCE_NAMESPACE
  67553. /*** End of inlined file: juce_RectanglePlacement.cpp ***/
  67554. /*** Start of inlined file: juce_Drawable.cpp ***/
  67555. BEGIN_JUCE_NAMESPACE
  67556. Drawable::RenderingContext::RenderingContext (Graphics& g_,
  67557. const AffineTransform& transform_,
  67558. const float opacity_) throw()
  67559. : g (g_),
  67560. transform (transform_),
  67561. opacity (opacity_)
  67562. {
  67563. }
  67564. Drawable::Drawable()
  67565. {
  67566. }
  67567. Drawable::~Drawable()
  67568. {
  67569. }
  67570. void Drawable::draw (Graphics& g, const float opacity,
  67571. const AffineTransform& transform) const
  67572. {
  67573. render (RenderingContext (g, transform, opacity));
  67574. }
  67575. void Drawable::drawAt (Graphics& g, const float x, const float y, const float opacity) const
  67576. {
  67577. draw (g, opacity, AffineTransform::translation (x, y));
  67578. }
  67579. void Drawable::drawWithin (Graphics& g,
  67580. const int destX,
  67581. const int destY,
  67582. const int destW,
  67583. const int destH,
  67584. const RectanglePlacement& placement,
  67585. const float opacity) const
  67586. {
  67587. if (destW > 0 && destH > 0)
  67588. {
  67589. Rectangle<float> bounds (getBounds());
  67590. draw (g, opacity,
  67591. placement.getTransformToFit (bounds.getX(), bounds.getY(), bounds.getWidth(), bounds.getHeight(),
  67592. (float) destX, (float) destY,
  67593. (float) destW, (float) destH));
  67594. }
  67595. }
  67596. Drawable* Drawable::createFromImageData (const void* data, const size_t numBytes)
  67597. {
  67598. Drawable* result = 0;
  67599. Image* const image = ImageFileFormat::loadFrom (data, (int) numBytes);
  67600. if (image != 0)
  67601. {
  67602. DrawableImage* const di = new DrawableImage();
  67603. di->setImage (image, true);
  67604. result = di;
  67605. }
  67606. else
  67607. {
  67608. const String asString (String::createStringFromData (data, (int) numBytes));
  67609. XmlDocument doc (asString);
  67610. ScopedPointer <XmlElement> outer (doc.getDocumentElement (true));
  67611. if (outer != 0 && outer->hasTagName ("svg"))
  67612. {
  67613. ScopedPointer <XmlElement> svg (doc.getDocumentElement());
  67614. if (svg != 0)
  67615. result = Drawable::createFromSVG (*svg);
  67616. }
  67617. }
  67618. return result;
  67619. }
  67620. Drawable* Drawable::createFromImageDataStream (InputStream& dataSource)
  67621. {
  67622. MemoryBlock mb;
  67623. dataSource.readIntoMemoryBlock (mb);
  67624. return createFromImageData (mb.getData(), mb.getSize());
  67625. }
  67626. Drawable* Drawable::createFromImageFile (const File& file)
  67627. {
  67628. const ScopedPointer <FileInputStream> fin (file.createInputStream());
  67629. return fin != 0 ? createFromImageDataStream (*fin) : 0;
  67630. }
  67631. Drawable* Drawable::createFromValueTree (const ValueTree& tree)
  67632. {
  67633. Drawable* d = DrawablePath::createFromValueTree (tree);
  67634. if (d == 0)
  67635. {
  67636. d = DrawableComposite::createFromValueTree (tree);
  67637. if (d == 0)
  67638. {
  67639. d = DrawableImage::createFromValueTree (tree);
  67640. if (d == 0)
  67641. d = DrawableText::createFromValueTree (tree);
  67642. }
  67643. }
  67644. return d;
  67645. }
  67646. END_JUCE_NAMESPACE
  67647. /*** End of inlined file: juce_Drawable.cpp ***/
  67648. /*** Start of inlined file: juce_DrawableComposite.cpp ***/
  67649. BEGIN_JUCE_NAMESPACE
  67650. DrawableComposite::DrawableComposite()
  67651. {
  67652. }
  67653. DrawableComposite::~DrawableComposite()
  67654. {
  67655. }
  67656. void DrawableComposite::insertDrawable (Drawable* drawable,
  67657. const AffineTransform& transform,
  67658. const int index)
  67659. {
  67660. if (drawable != 0)
  67661. {
  67662. if (! drawables.contains (drawable))
  67663. {
  67664. drawables.insert (index, drawable);
  67665. if (transform.isIdentity())
  67666. transforms.insert (index, 0);
  67667. else
  67668. transforms.insert (index, new AffineTransform (transform));
  67669. }
  67670. else
  67671. {
  67672. jassertfalse // trying to add a drawable that's already in here!
  67673. }
  67674. }
  67675. }
  67676. void DrawableComposite::insertDrawable (const Drawable& drawable,
  67677. const AffineTransform& transform,
  67678. const int index)
  67679. {
  67680. insertDrawable (drawable.createCopy(), transform, index);
  67681. }
  67682. void DrawableComposite::removeDrawable (const int index, const bool deleteDrawable)
  67683. {
  67684. drawables.remove (index, deleteDrawable);
  67685. transforms.remove (index);
  67686. }
  67687. void DrawableComposite::bringToFront (const int index)
  67688. {
  67689. if (index >= 0 && index < drawables.size() - 1)
  67690. {
  67691. drawables.move (index, -1);
  67692. transforms.move (index, -1);
  67693. }
  67694. }
  67695. void DrawableComposite::render (const Drawable::RenderingContext& context) const
  67696. {
  67697. if (drawables.size() > 0 && context.opacity > 0)
  67698. {
  67699. if (context.opacity >= 1.0f || drawables.size() == 1)
  67700. {
  67701. Drawable::RenderingContext contextCopy (context);
  67702. for (int i = 0; i < drawables.size(); ++i)
  67703. {
  67704. const AffineTransform* const t = transforms.getUnchecked(i);
  67705. contextCopy.transform = (t == 0) ? context.transform
  67706. : t->followedBy (context.transform);
  67707. drawables.getUnchecked(i)->render (contextCopy);
  67708. }
  67709. }
  67710. else
  67711. {
  67712. // To correctly render a whole composite layer with an overall transparency,
  67713. // we need to render everything opaquely into a temp buffer, then blend that
  67714. // with the target opacity...
  67715. const Rectangle<int> clipBounds (context.g.getClipBounds());
  67716. Image tempImage (Image::ARGB, clipBounds.getWidth(), clipBounds.getHeight(), true);
  67717. {
  67718. Graphics tempG (tempImage);
  67719. tempG.setOrigin (-clipBounds.getX(), -clipBounds.getY());
  67720. Drawable::RenderingContext tempContext (tempG, context.transform, 1.0f);
  67721. render (tempContext);
  67722. }
  67723. context.g.setOpacity (context.opacity);
  67724. context.g.drawImageAt (&tempImage, clipBounds.getX(), clipBounds.getY());
  67725. }
  67726. }
  67727. }
  67728. const Rectangle<float> DrawableComposite::getBounds() const
  67729. {
  67730. Rectangle<float> bounds;
  67731. for (int i = 0; i < drawables.size(); ++i)
  67732. {
  67733. const Drawable* const d = drawables.getUnchecked(i);
  67734. const AffineTransform* const t = transforms.getUnchecked(i);
  67735. const Rectangle<float> childBounds (t == 0 ? d->getBounds()
  67736. : d->getBounds().transformed (*t));
  67737. if (bounds.isEmpty())
  67738. bounds = childBounds;
  67739. else if (! childBounds.isEmpty())
  67740. bounds = bounds.getUnion (childBounds);
  67741. }
  67742. return bounds;
  67743. }
  67744. bool DrawableComposite::hitTest (float x, float y) const
  67745. {
  67746. for (int i = 0; i < drawables.size(); ++i)
  67747. {
  67748. float tx = x;
  67749. float ty = y;
  67750. const AffineTransform* const t = transforms.getUnchecked(i);
  67751. if (t != 0)
  67752. t->inverted().transformPoint (tx, ty);
  67753. if (drawables.getUnchecked(i)->hitTest (tx, ty))
  67754. return true;
  67755. }
  67756. return false;
  67757. }
  67758. Drawable* DrawableComposite::createCopy() const
  67759. {
  67760. DrawableComposite* const dc = new DrawableComposite();
  67761. for (int i = 0; i < drawables.size(); ++i)
  67762. {
  67763. dc->drawables.add (drawables.getUnchecked(i)->createCopy());
  67764. const AffineTransform* const t = transforms.getUnchecked(i);
  67765. dc->transforms.add (t != 0 ? new AffineTransform (*t) : 0);
  67766. }
  67767. return dc;
  67768. }
  67769. ValueTree DrawableComposite::createValueTree() const
  67770. {
  67771. ValueTree v ("Group");
  67772. if (getName().isNotEmpty())
  67773. v.setProperty ("id", getName(), 0);
  67774. for (int i = 0; i < drawables.size(); ++i)
  67775. {
  67776. Drawable* const d = drawables.getUnchecked(i);
  67777. ValueTree child (d->createValueTree());
  67778. AffineTransform* transform = transforms.getUnchecked(i);
  67779. if (transform != 0)
  67780. {
  67781. String t;
  67782. t << transform->mat00 << " " << transform->mat01 << " " << transform->mat02 << " "
  67783. << transform->mat10 << " " << transform->mat11 << " " << transform->mat12;
  67784. child.setProperty ("transform", t, 0);
  67785. }
  67786. v.addChild (child, -1, 0);
  67787. }
  67788. return v;
  67789. }
  67790. DrawableComposite* DrawableComposite::createFromValueTree (const ValueTree& tree)
  67791. {
  67792. if (! tree.hasType ("Group"))
  67793. return 0;
  67794. DrawableComposite* dc = new DrawableComposite();
  67795. dc->setName (tree ["id"]);
  67796. for (int i = 0; i < tree.getNumChildren(); ++i)
  67797. {
  67798. ValueTree childTree (tree.getChild (i));
  67799. Drawable* d = Drawable::createFromValueTree (childTree);
  67800. if (d != 0)
  67801. {
  67802. AffineTransform transform;
  67803. const String transformAtt (childTree ["transform"].toString());
  67804. if (transformAtt.isNotEmpty())
  67805. {
  67806. StringArray tokens;
  67807. tokens.addTokens (transformAtt.trim(), false);
  67808. tokens.removeEmptyStrings (true);
  67809. if (tokens.size() == 6)
  67810. {
  67811. float f[6];
  67812. for (int j = 0; j < 6; ++j)
  67813. f[j] = (float) tokens[j].getDoubleValue();
  67814. transform = AffineTransform (f[0], f[1], f[2], f[3], f[4], f[5]);
  67815. }
  67816. }
  67817. dc->insertDrawable (d, transform);
  67818. }
  67819. }
  67820. return dc;
  67821. }
  67822. END_JUCE_NAMESPACE
  67823. /*** End of inlined file: juce_DrawableComposite.cpp ***/
  67824. /*** Start of inlined file: juce_DrawableImage.cpp ***/
  67825. BEGIN_JUCE_NAMESPACE
  67826. DrawableImage::DrawableImage()
  67827. : image (0),
  67828. canDeleteImage (false),
  67829. opacity (1.0f),
  67830. overlayColour (0x00000000)
  67831. {
  67832. }
  67833. DrawableImage::~DrawableImage()
  67834. {
  67835. clearImage();
  67836. }
  67837. void DrawableImage::clearImage()
  67838. {
  67839. if (canDeleteImage && image != 0)
  67840. ImageCache::releaseOrDelete (image);
  67841. image = 0;
  67842. }
  67843. void DrawableImage::setImage (const Image& imageToCopy)
  67844. {
  67845. clearImage();
  67846. image = new Image (imageToCopy);
  67847. canDeleteImage = true;
  67848. }
  67849. void DrawableImage::setImage (Image* imageToUse,
  67850. const bool releaseWhenNotNeeded)
  67851. {
  67852. clearImage();
  67853. image = imageToUse;
  67854. canDeleteImage = releaseWhenNotNeeded;
  67855. }
  67856. void DrawableImage::setOpacity (const float newOpacity)
  67857. {
  67858. opacity = newOpacity;
  67859. }
  67860. void DrawableImage::setOverlayColour (const Colour& newOverlayColour)
  67861. {
  67862. overlayColour = newOverlayColour;
  67863. }
  67864. void DrawableImage::render (const Drawable::RenderingContext& context) const
  67865. {
  67866. if (image != 0)
  67867. {
  67868. if (opacity > 0.0f && ! overlayColour.isOpaque())
  67869. {
  67870. context.g.setOpacity (context.opacity * opacity);
  67871. context.g.drawImageTransformed (image, image->getBounds(),
  67872. context.transform, false);
  67873. }
  67874. if (! overlayColour.isTransparent())
  67875. {
  67876. context.g.setColour (overlayColour.withMultipliedAlpha (context.opacity));
  67877. context.g.drawImageTransformed (image, image->getBounds(),
  67878. context.transform, true);
  67879. }
  67880. }
  67881. }
  67882. const Rectangle<float> DrawableImage::getBounds() const
  67883. {
  67884. if (image == 0)
  67885. return Rectangle<float>();
  67886. return Rectangle<float> (0, 0, (float) image->getWidth(), (float) image->getHeight());
  67887. }
  67888. bool DrawableImage::hitTest (float x, float y) const
  67889. {
  67890. return image != 0
  67891. && x >= 0.0f
  67892. && y >= 0.0f
  67893. && x < image->getWidth()
  67894. && y < image->getHeight()
  67895. && image->getPixelAt (roundToInt (x), roundToInt (y)).getAlpha() >= 127;
  67896. }
  67897. Drawable* DrawableImage::createCopy() const
  67898. {
  67899. DrawableImage* const di = new DrawableImage();
  67900. di->opacity = opacity;
  67901. di->overlayColour = overlayColour;
  67902. if (image != 0)
  67903. {
  67904. if ((! canDeleteImage) || ! ImageCache::isImageInCache (image))
  67905. {
  67906. di->setImage (*image);
  67907. }
  67908. else
  67909. {
  67910. ImageCache::incReferenceCount (image);
  67911. di->setImage (image, true);
  67912. }
  67913. }
  67914. return di;
  67915. }
  67916. ValueTree DrawableImage::createValueTree() const
  67917. {
  67918. ValueTree v ("Image");
  67919. if (getName().isNotEmpty())
  67920. v.setProperty ("id", getName(), 0);
  67921. if (opacity < 1.0f)
  67922. v.setProperty ("opacity", (double) opacity, 0);
  67923. if (! overlayColour.isTransparent())
  67924. v.setProperty ("overlay", String::toHexString ((int) overlayColour.getARGB()), 0);
  67925. if (image != 0)
  67926. {
  67927. MemoryOutputStream imageData;
  67928. PNGImageFormat pngFormat;
  67929. if (pngFormat.writeImageToStream (*image, imageData))
  67930. {
  67931. String base64 (MemoryBlock (imageData.getData(), imageData.getDataSize()).toBase64Encoding());
  67932. for (int i = (base64.length() & ~127); i >= 0; i -= 128)
  67933. base64 = base64.substring (0, i) + "\n" + base64.substring (i);
  67934. v.setProperty ("data", base64, 0);
  67935. }
  67936. }
  67937. return v;
  67938. }
  67939. DrawableImage* DrawableImage::createFromValueTree (const ValueTree& tree)
  67940. {
  67941. if (! tree.hasType ("Image"))
  67942. return 0;
  67943. DrawableImage* di = new DrawableImage();
  67944. di->setName (tree ["id"]);
  67945. di->opacity = tree.hasProperty ("opacity") ? (float) tree ["opacity"] : 1.0f;
  67946. di->overlayColour = Colour (tree ["overlay"].toString().getHexValue32());
  67947. MemoryBlock imageData;
  67948. if (imageData.fromBase64Encoding (tree ["data"]))
  67949. {
  67950. Image* const im = ImageFileFormat::loadFrom (imageData.getData(), (int) imageData.getSize());
  67951. if (im == 0)
  67952. return false;
  67953. di->setImage (im, true);
  67954. }
  67955. return di;
  67956. }
  67957. END_JUCE_NAMESPACE
  67958. /*** End of inlined file: juce_DrawableImage.cpp ***/
  67959. /*** Start of inlined file: juce_DrawablePath.cpp ***/
  67960. BEGIN_JUCE_NAMESPACE
  67961. DrawablePath::DrawablePath()
  67962. : mainFill (Colours::black),
  67963. strokeFill (Colours::transparentBlack),
  67964. strokeType (0.0f)
  67965. {
  67966. }
  67967. DrawablePath::~DrawablePath()
  67968. {
  67969. }
  67970. void DrawablePath::setPath (const Path& newPath)
  67971. {
  67972. path = newPath;
  67973. updateOutline();
  67974. }
  67975. void DrawablePath::setFill (const FillType& newFill)
  67976. {
  67977. mainFill = newFill;
  67978. }
  67979. void DrawablePath::setStrokeFill (const FillType& newFill)
  67980. {
  67981. strokeFill = newFill;
  67982. }
  67983. void DrawablePath::setStrokeType (const PathStrokeType& newStrokeType)
  67984. {
  67985. strokeType = newStrokeType;
  67986. updateOutline();
  67987. }
  67988. void DrawablePath::setStrokeThickness (const float newThickness)
  67989. {
  67990. setStrokeType (PathStrokeType (newThickness, strokeType.getJointStyle(), strokeType.getEndStyle()));
  67991. }
  67992. void DrawablePath::render (const Drawable::RenderingContext& context) const
  67993. {
  67994. {
  67995. FillType f (mainFill);
  67996. if (f.isGradient())
  67997. f.gradient->multiplyOpacity (context.opacity);
  67998. f.transform = f.transform.followedBy (context.transform);
  67999. context.g.setFillType (f);
  68000. context.g.fillPath (path, context.transform);
  68001. }
  68002. if (strokeType.getStrokeThickness() > 0.0f)
  68003. {
  68004. FillType f (strokeFill);
  68005. if (f.isGradient())
  68006. f.gradient->multiplyOpacity (context.opacity);
  68007. f.transform = f.transform.followedBy (context.transform);
  68008. context.g.setFillType (f);
  68009. context.g.fillPath (stroke, context.transform);
  68010. }
  68011. }
  68012. void DrawablePath::updateOutline()
  68013. {
  68014. stroke.clear();
  68015. strokeType.createStrokedPath (stroke, path, AffineTransform::identity, 4.0f);
  68016. }
  68017. const Rectangle<float> DrawablePath::getBounds() const
  68018. {
  68019. if (strokeType.getStrokeThickness() > 0.0f)
  68020. return stroke.getBounds();
  68021. else
  68022. return path.getBounds();
  68023. }
  68024. bool DrawablePath::hitTest (float x, float y) const
  68025. {
  68026. return path.contains (x, y)
  68027. || stroke.contains (x, y);
  68028. }
  68029. Drawable* DrawablePath::createCopy() const
  68030. {
  68031. DrawablePath* const dp = new DrawablePath();
  68032. dp->path = path;
  68033. dp->stroke = stroke;
  68034. dp->mainFill = mainFill;
  68035. dp->strokeFill = strokeFill;
  68036. dp->strokeType = strokeType;
  68037. return dp;
  68038. }
  68039. static const FillType readFillTypeFromTree (const ValueTree& v)
  68040. {
  68041. const String type (v["type"].toString());
  68042. if (type.equalsIgnoreCase ("solid"))
  68043. {
  68044. const String colour (v ["colour"].toString());
  68045. return Colour (colour.isEmpty() ? (uint32) 0xff000000
  68046. : (uint32) colour.getHexValue32());
  68047. }
  68048. else if (type.equalsIgnoreCase ("gradient"))
  68049. {
  68050. ColourGradient g;
  68051. g.x1 = v["x1"];
  68052. g.y1 = v["y1"];
  68053. g.x2 = v["x2"];
  68054. g.y2 = v["y2"];
  68055. g.isRadial = v["radial"];
  68056. StringArray colours;
  68057. colours.addTokens (v["colours"].toString(), false);
  68058. for (int i = 0; i < colours.size() / 2; ++i)
  68059. g.addColour (colours[i * 2].getDoubleValue(),
  68060. Colour ((uint32) colours[i * 2 + 1].getHexValue32()));
  68061. return g;
  68062. }
  68063. jassertfalse
  68064. return FillType();
  68065. }
  68066. static ValueTree createTreeForFillType (const String& tagName, const FillType& fillType)
  68067. {
  68068. ValueTree v (tagName);
  68069. if (fillType.isColour())
  68070. {
  68071. v.setProperty ("type", "solid", 0);
  68072. v.setProperty ("colour", String::toHexString ((int) fillType.colour.getARGB()), 0);
  68073. }
  68074. else if (fillType.isGradient())
  68075. {
  68076. v.setProperty ("type", "gradient", 0);
  68077. v.setProperty ("x1", fillType.gradient->x1, 0);
  68078. v.setProperty ("y1", fillType.gradient->y1, 0);
  68079. v.setProperty ("x2", fillType.gradient->x2, 0);
  68080. v.setProperty ("y2", fillType.gradient->y2, 0);
  68081. v.setProperty ("radial", fillType.gradient->isRadial, 0);
  68082. String s;
  68083. for (int i = 0; i < fillType.gradient->getNumColours(); ++i)
  68084. s << " " << fillType.gradient->getColourPosition (i)
  68085. << " " << String::toHexString ((int) fillType.gradient->getColour(i).getARGB());
  68086. v.setProperty ("colours", s.trimStart(), 0);
  68087. }
  68088. else
  68089. {
  68090. jassertfalse //xxx
  68091. }
  68092. return v;
  68093. }
  68094. ValueTree DrawablePath::createValueTree() const
  68095. {
  68096. ValueTree v ("Path");
  68097. v.addChild (createTreeForFillType ("fill", mainFill), -1, 0);
  68098. v.addChild (createTreeForFillType ("stroke", strokeFill), -1, 0);
  68099. if (getName().isNotEmpty())
  68100. v.setProperty ("id", getName(), 0);
  68101. v.setProperty ("strokeWidth", (double) strokeType.getStrokeThickness(), 0);
  68102. v.setProperty ("jointStyle", strokeType.getJointStyle() == PathStrokeType::mitered
  68103. ? "miter" : (strokeType.getJointStyle() == PathStrokeType::curved ? "curved" : "bevel"), 0);
  68104. v.setProperty ("capStyle", strokeType.getEndStyle() == PathStrokeType::butt
  68105. ? "butt" : (strokeType.getEndStyle() == PathStrokeType::square ? "square" : "round"), 0);
  68106. v.setProperty ("path", path.toString(), 0);
  68107. return v;
  68108. }
  68109. DrawablePath* DrawablePath::createFromValueTree (const ValueTree& tree)
  68110. {
  68111. if (! tree.hasType ("Path"))
  68112. return 0;
  68113. DrawablePath* p = new DrawablePath();
  68114. p->setName (tree ["id"]);
  68115. p->mainFill = readFillTypeFromTree (tree.getChildWithName ("fill"));
  68116. p->strokeFill = readFillTypeFromTree (tree.getChildWithName ("stroke"));
  68117. const String jointStyle (tree ["jointStyle"].toString());
  68118. const String endStyle (tree ["capStyle"].toString());
  68119. p->strokeType
  68120. = PathStrokeType (tree ["strokeWidth"],
  68121. jointStyle.equalsIgnoreCase ("curved") ? PathStrokeType::curved
  68122. : (jointStyle.equalsIgnoreCase ("bevel") ? PathStrokeType::beveled
  68123. : PathStrokeType::mitered),
  68124. endStyle.equalsIgnoreCase ("square") ? PathStrokeType::square
  68125. : (endStyle.equalsIgnoreCase ("round") ? PathStrokeType::rounded
  68126. : PathStrokeType::butt));
  68127. p->path.clear();
  68128. p->path.restoreFromString (tree ["path"]);
  68129. p->updateOutline();
  68130. return p;
  68131. }
  68132. END_JUCE_NAMESPACE
  68133. /*** End of inlined file: juce_DrawablePath.cpp ***/
  68134. /*** Start of inlined file: juce_DrawableText.cpp ***/
  68135. BEGIN_JUCE_NAMESPACE
  68136. DrawableText::DrawableText()
  68137. : colour (Colours::white)
  68138. {
  68139. }
  68140. DrawableText::~DrawableText()
  68141. {
  68142. }
  68143. void DrawableText::setText (const GlyphArrangement& newText)
  68144. {
  68145. text = newText;
  68146. }
  68147. void DrawableText::setText (const String& newText, const Font& fontToUse)
  68148. {
  68149. text.clear();
  68150. text.addLineOfText (fontToUse, newText, 0.0f, 0.0f);
  68151. }
  68152. void DrawableText::setColour (const Colour& newColour)
  68153. {
  68154. colour = newColour;
  68155. }
  68156. void DrawableText::render (const Drawable::RenderingContext& context) const
  68157. {
  68158. context.g.setColour (colour.withMultipliedAlpha (context.opacity));
  68159. text.draw (context.g, context.transform);
  68160. }
  68161. const Rectangle<float> DrawableText::getBounds() const
  68162. {
  68163. return text.getBoundingBox (0, -1, false);
  68164. }
  68165. bool DrawableText::hitTest (float x, float y) const
  68166. {
  68167. return text.findGlyphIndexAt (x, y) >= 0;
  68168. }
  68169. Drawable* DrawableText::createCopy() const
  68170. {
  68171. DrawableText* const dt = new DrawableText();
  68172. dt->text = text;
  68173. dt->colour = colour;
  68174. return dt;
  68175. }
  68176. ValueTree DrawableText::createValueTree() const
  68177. {
  68178. ValueTree v ("Text");
  68179. if (getName().isNotEmpty())
  68180. v.setProperty ("id", getName(), 0);
  68181. jassertfalse // xxx not finished!
  68182. return v;
  68183. }
  68184. DrawableText* DrawableText::createFromValueTree (const ValueTree& tree)
  68185. {
  68186. if (! tree.hasType ("Text"))
  68187. return 0;
  68188. DrawableText* dt = new DrawableText();
  68189. dt->setName (tree ["id"]);
  68190. jassertfalse // xxx not finished!
  68191. return dt;
  68192. }
  68193. END_JUCE_NAMESPACE
  68194. /*** End of inlined file: juce_DrawableText.cpp ***/
  68195. /*** Start of inlined file: juce_SVGParser.cpp ***/
  68196. BEGIN_JUCE_NAMESPACE
  68197. class SVGState
  68198. {
  68199. public:
  68200. SVGState (const XmlElement* const topLevel)
  68201. : topLevelXml (topLevel),
  68202. elementX (0), elementY (0),
  68203. width (512), height (512),
  68204. viewBoxW (0), viewBoxH (0)
  68205. {
  68206. }
  68207. ~SVGState()
  68208. {
  68209. }
  68210. Drawable* parseSVGElement (const XmlElement& xml)
  68211. {
  68212. if (! xml.hasTagName ("svg"))
  68213. return 0;
  68214. DrawableComposite* const drawable = new DrawableComposite();
  68215. drawable->setName (xml.getStringAttribute ("id"));
  68216. SVGState newState (*this);
  68217. if (xml.hasAttribute ("transform"))
  68218. newState.addTransform (xml);
  68219. newState.elementX = getCoordLength (xml.getStringAttribute ("x", String (newState.elementX)), viewBoxW);
  68220. newState.elementY = getCoordLength (xml.getStringAttribute ("y", String (newState.elementY)), viewBoxH);
  68221. newState.width = getCoordLength (xml.getStringAttribute ("width", String (newState.width)), viewBoxW);
  68222. newState.height = getCoordLength (xml.getStringAttribute ("height", String (newState.height)), viewBoxH);
  68223. if (xml.hasAttribute ("viewBox"))
  68224. {
  68225. const String viewParams (xml.getStringAttribute ("viewBox"));
  68226. int i = 0;
  68227. float vx, vy, vw, vh;
  68228. if (parseCoords (viewParams, vx, vy, i, true)
  68229. && parseCoords (viewParams, vw, vh, i, true)
  68230. && vw > 0
  68231. && vh > 0)
  68232. {
  68233. newState.viewBoxW = vw;
  68234. newState.viewBoxH = vh;
  68235. int placementFlags = 0;
  68236. const String aspect (xml.getStringAttribute ("preserveAspectRatio"));
  68237. if (aspect.containsIgnoreCase ("none"))
  68238. {
  68239. placementFlags = RectanglePlacement::stretchToFit;
  68240. }
  68241. else
  68242. {
  68243. if (aspect.containsIgnoreCase ("slice"))
  68244. placementFlags |= RectanglePlacement::fillDestination;
  68245. if (aspect.containsIgnoreCase ("xMin"))
  68246. placementFlags |= RectanglePlacement::xLeft;
  68247. else if (aspect.containsIgnoreCase ("xMax"))
  68248. placementFlags |= RectanglePlacement::xRight;
  68249. else
  68250. placementFlags |= RectanglePlacement::xMid;
  68251. if (aspect.containsIgnoreCase ("yMin"))
  68252. placementFlags |= RectanglePlacement::yTop;
  68253. else if (aspect.containsIgnoreCase ("yMax"))
  68254. placementFlags |= RectanglePlacement::yBottom;
  68255. else
  68256. placementFlags |= RectanglePlacement::yMid;
  68257. }
  68258. const RectanglePlacement placement (placementFlags);
  68259. newState.transform
  68260. = placement.getTransformToFit (vx, vy, vw, vh,
  68261. 0.0f, 0.0f, newState.width, newState.height)
  68262. .followedBy (newState.transform);
  68263. }
  68264. }
  68265. else
  68266. {
  68267. if (viewBoxW == 0)
  68268. newState.viewBoxW = newState.width;
  68269. if (viewBoxH == 0)
  68270. newState.viewBoxH = newState.height;
  68271. }
  68272. newState.parseSubElements (xml, drawable);
  68273. return drawable;
  68274. }
  68275. private:
  68276. const XmlElement* const topLevelXml;
  68277. float elementX, elementY, width, height, viewBoxW, viewBoxH;
  68278. AffineTransform transform;
  68279. String cssStyleText;
  68280. void parseSubElements (const XmlElement& xml, DrawableComposite* const parentDrawable)
  68281. {
  68282. forEachXmlChildElement (xml, e)
  68283. {
  68284. Drawable* d = 0;
  68285. if (e->hasTagName ("g"))
  68286. d = parseGroupElement (*e);
  68287. else if (e->hasTagName ("svg"))
  68288. d = parseSVGElement (*e);
  68289. else if (e->hasTagName ("path"))
  68290. d = parsePath (*e);
  68291. else if (e->hasTagName ("rect"))
  68292. d = parseRect (*e);
  68293. else if (e->hasTagName ("circle"))
  68294. d = parseCircle (*e);
  68295. else if (e->hasTagName ("ellipse"))
  68296. d = parseEllipse (*e);
  68297. else if (e->hasTagName ("line"))
  68298. d = parseLine (*e);
  68299. else if (e->hasTagName ("polyline"))
  68300. d = parsePolygon (*e, true);
  68301. else if (e->hasTagName ("polygon"))
  68302. d = parsePolygon (*e, false);
  68303. else if (e->hasTagName ("text"))
  68304. d = parseText (*e);
  68305. else if (e->hasTagName ("switch"))
  68306. d = parseSwitch (*e);
  68307. else if (e->hasTagName ("style"))
  68308. parseCSSStyle (*e);
  68309. parentDrawable->insertDrawable (d);
  68310. }
  68311. }
  68312. DrawableComposite* parseSwitch (const XmlElement& xml)
  68313. {
  68314. const XmlElement* const group = xml.getChildByName ("g");
  68315. if (group != 0)
  68316. return parseGroupElement (*group);
  68317. return 0;
  68318. }
  68319. DrawableComposite* parseGroupElement (const XmlElement& xml)
  68320. {
  68321. DrawableComposite* const drawable = new DrawableComposite();
  68322. drawable->setName (xml.getStringAttribute ("id"));
  68323. if (xml.hasAttribute ("transform"))
  68324. {
  68325. SVGState newState (*this);
  68326. newState.addTransform (xml);
  68327. newState.parseSubElements (xml, drawable);
  68328. }
  68329. else
  68330. {
  68331. parseSubElements (xml, drawable);
  68332. }
  68333. return drawable;
  68334. }
  68335. Drawable* parsePath (const XmlElement& xml) const
  68336. {
  68337. const String d (xml.getStringAttribute ("d").trimStart());
  68338. Path path;
  68339. if (getStyleAttribute (&xml, "fill-rule").trim().equalsIgnoreCase ("evenodd"))
  68340. path.setUsingNonZeroWinding (false);
  68341. int index = 0;
  68342. float lastX = 0, lastY = 0;
  68343. float lastX2 = 0, lastY2 = 0;
  68344. juce_wchar lastCommandChar = 0;
  68345. bool isRelative = true;
  68346. bool carryOn = true;
  68347. const String validCommandChars ("MmLlHhVvCcSsQqTtAaZz");
  68348. while (d[index] != 0)
  68349. {
  68350. float x, y, x2, y2, x3, y3;
  68351. if (validCommandChars.containsChar (d[index]))
  68352. {
  68353. lastCommandChar = d [index++];
  68354. isRelative = (lastCommandChar >= 'a' && lastCommandChar <= 'z');
  68355. }
  68356. switch (lastCommandChar)
  68357. {
  68358. case 'M':
  68359. case 'm':
  68360. case 'L':
  68361. case 'l':
  68362. if (parseCoords (d, x, y, index, false))
  68363. {
  68364. if (isRelative)
  68365. {
  68366. x += lastX;
  68367. y += lastY;
  68368. }
  68369. if (lastCommandChar == 'M' || lastCommandChar == 'm')
  68370. {
  68371. path.startNewSubPath (x, y);
  68372. lastCommandChar = 'l';
  68373. }
  68374. else
  68375. path.lineTo (x, y);
  68376. lastX2 = lastX;
  68377. lastY2 = lastY;
  68378. lastX = x;
  68379. lastY = y;
  68380. }
  68381. else
  68382. {
  68383. ++index;
  68384. }
  68385. break;
  68386. case 'H':
  68387. case 'h':
  68388. if (parseCoord (d, x, index, false, true))
  68389. {
  68390. if (isRelative)
  68391. x += lastX;
  68392. path.lineTo (x, lastY);
  68393. lastX2 = lastX;
  68394. lastX = x;
  68395. }
  68396. else
  68397. {
  68398. ++index;
  68399. }
  68400. break;
  68401. case 'V':
  68402. case 'v':
  68403. if (parseCoord (d, y, index, false, false))
  68404. {
  68405. if (isRelative)
  68406. y += lastY;
  68407. path.lineTo (lastX, y);
  68408. lastY2 = lastY;
  68409. lastY = y;
  68410. }
  68411. else
  68412. {
  68413. ++index;
  68414. }
  68415. break;
  68416. case 'C':
  68417. case 'c':
  68418. if (parseCoords (d, x, y, index, false)
  68419. && parseCoords (d, x2, y2, index, false)
  68420. && parseCoords (d, x3, y3, index, false))
  68421. {
  68422. if (isRelative)
  68423. {
  68424. x += lastX;
  68425. y += lastY;
  68426. x2 += lastX;
  68427. y2 += lastY;
  68428. x3 += lastX;
  68429. y3 += lastY;
  68430. }
  68431. path.cubicTo (x, y, x2, y2, x3, y3);
  68432. lastX2 = x2;
  68433. lastY2 = y2;
  68434. lastX = x3;
  68435. lastY = y3;
  68436. }
  68437. else
  68438. {
  68439. ++index;
  68440. }
  68441. break;
  68442. case 'S':
  68443. case 's':
  68444. if (parseCoords (d, x, y, index, false)
  68445. && parseCoords (d, x3, y3, index, false))
  68446. {
  68447. if (isRelative)
  68448. {
  68449. x += lastX;
  68450. y += lastY;
  68451. x3 += lastX;
  68452. y3 += lastY;
  68453. }
  68454. x2 = lastX + (lastX - lastX2);
  68455. y2 = lastY + (lastY - lastY2);
  68456. path.cubicTo (x2, y2, x, y, x3, y3);
  68457. lastX2 = x;
  68458. lastY2 = y;
  68459. lastX = x3;
  68460. lastY = y3;
  68461. }
  68462. else
  68463. {
  68464. ++index;
  68465. }
  68466. break;
  68467. case 'Q':
  68468. case 'q':
  68469. if (parseCoords (d, x, y, index, false)
  68470. && parseCoords (d, x2, y2, index, false))
  68471. {
  68472. if (isRelative)
  68473. {
  68474. x += lastX;
  68475. y += lastY;
  68476. x2 += lastX;
  68477. y2 += lastY;
  68478. }
  68479. path.quadraticTo (x, y, x2, y2);
  68480. lastX2 = x;
  68481. lastY2 = y;
  68482. lastX = x2;
  68483. lastY = y2;
  68484. }
  68485. else
  68486. {
  68487. ++index;
  68488. }
  68489. break;
  68490. case 'T':
  68491. case 't':
  68492. if (parseCoords (d, x, y, index, false))
  68493. {
  68494. if (isRelative)
  68495. {
  68496. x += lastX;
  68497. y += lastY;
  68498. }
  68499. x2 = lastX + (lastX - lastX2);
  68500. y2 = lastY + (lastY - lastY2);
  68501. path.quadraticTo (x2, y2, x, y);
  68502. lastX2 = x2;
  68503. lastY2 = y2;
  68504. lastX = x;
  68505. lastY = y;
  68506. }
  68507. else
  68508. {
  68509. ++index;
  68510. }
  68511. break;
  68512. case 'A':
  68513. case 'a':
  68514. if (parseCoords (d, x, y, index, false))
  68515. {
  68516. String num;
  68517. if (parseNextNumber (d, num, index, false))
  68518. {
  68519. const float angle = num.getFloatValue() * (180.0f / float_Pi);
  68520. if (parseNextNumber (d, num, index, false))
  68521. {
  68522. const bool largeArc = num.getIntValue() != 0;
  68523. if (parseNextNumber (d, num, index, false))
  68524. {
  68525. const bool sweep = num.getIntValue() != 0;
  68526. if (parseCoords (d, x2, y2, index, false))
  68527. {
  68528. if (isRelative)
  68529. {
  68530. x2 += lastX;
  68531. y2 += lastY;
  68532. }
  68533. if (lastX != x2 || lastY != y2)
  68534. {
  68535. double centreX, centreY, startAngle, deltaAngle;
  68536. double rx = x, ry = y;
  68537. endpointToCentreParameters (lastX, lastY, x2, y2,
  68538. angle, largeArc, sweep,
  68539. rx, ry, centreX, centreY,
  68540. startAngle, deltaAngle);
  68541. path.addCentredArc ((float) centreX, (float) centreY,
  68542. (float) rx, (float) ry,
  68543. angle, (float) startAngle, (float) (startAngle + deltaAngle),
  68544. false);
  68545. path.lineTo (x2, y2);
  68546. }
  68547. lastX2 = lastX;
  68548. lastY2 = lastY;
  68549. lastX = x2;
  68550. lastY = y2;
  68551. }
  68552. }
  68553. }
  68554. }
  68555. }
  68556. else
  68557. {
  68558. ++index;
  68559. }
  68560. break;
  68561. case 'Z':
  68562. case 'z':
  68563. path.closeSubPath();
  68564. while (CharacterFunctions::isWhitespace (d [index]))
  68565. ++index;
  68566. break;
  68567. default:
  68568. carryOn = false;
  68569. break;
  68570. }
  68571. if (! carryOn)
  68572. break;
  68573. }
  68574. return parseShape (xml, path);
  68575. }
  68576. Drawable* parseRect (const XmlElement& xml) const
  68577. {
  68578. Path rect;
  68579. const bool hasRX = xml.hasAttribute ("rx");
  68580. const bool hasRY = xml.hasAttribute ("ry");
  68581. if (hasRX || hasRY)
  68582. {
  68583. float rx = getCoordLength (xml.getStringAttribute ("rx"), viewBoxW);
  68584. float ry = getCoordLength (xml.getStringAttribute ("ry"), viewBoxH);
  68585. if (! hasRX)
  68586. rx = ry;
  68587. else if (! hasRY)
  68588. ry = rx;
  68589. rect.addRoundedRectangle (getCoordLength (xml.getStringAttribute ("x"), viewBoxW),
  68590. getCoordLength (xml.getStringAttribute ("y"), viewBoxH),
  68591. getCoordLength (xml.getStringAttribute ("width"), viewBoxW),
  68592. getCoordLength (xml.getStringAttribute ("height"), viewBoxH),
  68593. rx, ry);
  68594. }
  68595. else
  68596. {
  68597. rect.addRectangle (getCoordLength (xml.getStringAttribute ("x"), viewBoxW),
  68598. getCoordLength (xml.getStringAttribute ("y"), viewBoxH),
  68599. getCoordLength (xml.getStringAttribute ("width"), viewBoxW),
  68600. getCoordLength (xml.getStringAttribute ("height"), viewBoxH));
  68601. }
  68602. return parseShape (xml, rect);
  68603. }
  68604. Drawable* parseCircle (const XmlElement& xml) const
  68605. {
  68606. Path circle;
  68607. const float cx = getCoordLength (xml.getStringAttribute ("cx"), viewBoxW);
  68608. const float cy = getCoordLength (xml.getStringAttribute ("cy"), viewBoxH);
  68609. const float radius = getCoordLength (xml.getStringAttribute ("r"), viewBoxW);
  68610. circle.addEllipse (cx - radius, cy - radius, radius * 2.0f, radius * 2.0f);
  68611. return parseShape (xml, circle);
  68612. }
  68613. Drawable* parseEllipse (const XmlElement& xml) const
  68614. {
  68615. Path ellipse;
  68616. const float cx = getCoordLength (xml.getStringAttribute ("cx"), viewBoxW);
  68617. const float cy = getCoordLength (xml.getStringAttribute ("cy"), viewBoxH);
  68618. const float radiusX = getCoordLength (xml.getStringAttribute ("rx"), viewBoxW);
  68619. const float radiusY = getCoordLength (xml.getStringAttribute ("ry"), viewBoxH);
  68620. ellipse.addEllipse (cx - radiusX, cy - radiusY, radiusX * 2.0f, radiusY * 2.0f);
  68621. return parseShape (xml, ellipse);
  68622. }
  68623. Drawable* parseLine (const XmlElement& xml) const
  68624. {
  68625. Path line;
  68626. const float x1 = getCoordLength (xml.getStringAttribute ("x1"), viewBoxW);
  68627. const float y1 = getCoordLength (xml.getStringAttribute ("y1"), viewBoxH);
  68628. const float x2 = getCoordLength (xml.getStringAttribute ("x2"), viewBoxW);
  68629. const float y2 = getCoordLength (xml.getStringAttribute ("y2"), viewBoxH);
  68630. line.startNewSubPath (x1, y1);
  68631. line.lineTo (x2, y2);
  68632. return parseShape (xml, line);
  68633. }
  68634. Drawable* parsePolygon (const XmlElement& xml, const bool isPolyline) const
  68635. {
  68636. const String points (xml.getStringAttribute ("points"));
  68637. Path path;
  68638. int index = 0;
  68639. float x, y;
  68640. if (parseCoords (points, x, y, index, true))
  68641. {
  68642. float firstX = x;
  68643. float firstY = y;
  68644. float lastX = 0, lastY = 0;
  68645. path.startNewSubPath (x, y);
  68646. while (parseCoords (points, x, y, index, true))
  68647. {
  68648. lastX = x;
  68649. lastY = y;
  68650. path.lineTo (x, y);
  68651. }
  68652. if ((! isPolyline) || (firstX == lastX && firstY == lastY))
  68653. path.closeSubPath();
  68654. }
  68655. return parseShape (xml, path);
  68656. }
  68657. Drawable* parseShape (const XmlElement& xml, Path& path,
  68658. const bool shouldParseTransform = true) const
  68659. {
  68660. if (shouldParseTransform && xml.hasAttribute ("transform"))
  68661. {
  68662. SVGState newState (*this);
  68663. newState.addTransform (xml);
  68664. return newState.parseShape (xml, path, false);
  68665. }
  68666. DrawablePath* dp = new DrawablePath();
  68667. dp->setName (xml.getStringAttribute ("id"));
  68668. dp->setFill (Colours::transparentBlack);
  68669. path.applyTransform (transform);
  68670. dp->setPath (path);
  68671. Path::Iterator iter (path);
  68672. bool containsClosedSubPath = false;
  68673. while (iter.next())
  68674. {
  68675. if (iter.elementType == Path::Iterator::closePath)
  68676. {
  68677. containsClosedSubPath = true;
  68678. break;
  68679. }
  68680. }
  68681. dp->setFill (getPathFillType (path,
  68682. getStyleAttribute (&xml, "fill"),
  68683. getStyleAttribute (&xml, "fill-opacity"),
  68684. getStyleAttribute (&xml, "opacity"),
  68685. containsClosedSubPath ? Colours::black
  68686. : Colours::transparentBlack));
  68687. const String strokeType (getStyleAttribute (&xml, "stroke"));
  68688. if (strokeType.isNotEmpty() && ! strokeType.equalsIgnoreCase ("none"))
  68689. {
  68690. dp->setStrokeFill (getPathFillType (path, strokeType,
  68691. getStyleAttribute (&xml, "stroke-opacity"),
  68692. getStyleAttribute (&xml, "opacity"),
  68693. Colours::transparentBlack));
  68694. dp->setStrokeType (getStrokeFor (&xml));
  68695. }
  68696. return dp;
  68697. }
  68698. const XmlElement* findLinkedElement (const XmlElement* e) const
  68699. {
  68700. const String id (e->getStringAttribute ("xlink:href"));
  68701. if (! id.startsWithChar ('#'))
  68702. return 0;
  68703. return findElementForId (topLevelXml, id.substring (1));
  68704. }
  68705. void addGradientStopsIn (ColourGradient& cg, const XmlElement* const fillXml) const
  68706. {
  68707. if (fillXml == 0)
  68708. return;
  68709. forEachXmlChildElementWithTagName (*fillXml, e, "stop")
  68710. {
  68711. int index = 0;
  68712. Colour col (parseColour (getStyleAttribute (e, "stop-color"), index, Colours::black));
  68713. const String opacity (getStyleAttribute (e, "stop-opacity", "1"));
  68714. col = col.withMultipliedAlpha (jlimit (0.0f, 1.0f, opacity.getFloatValue()));
  68715. double offset = e->getDoubleAttribute ("offset");
  68716. if (e->getStringAttribute ("offset").containsChar ('%'))
  68717. offset *= 0.01;
  68718. cg.addColour (jlimit (0.0, 1.0, offset), col);
  68719. }
  68720. }
  68721. const FillType getPathFillType (const Path& path,
  68722. const String& fill,
  68723. const String& fillOpacity,
  68724. const String& overallOpacity,
  68725. const Colour& defaultColour) const
  68726. {
  68727. float opacity = 1.0f;
  68728. if (overallOpacity.isNotEmpty())
  68729. opacity = jlimit (0.0f, 1.0f, overallOpacity.getFloatValue());
  68730. if (fillOpacity.isNotEmpty())
  68731. opacity *= (jlimit (0.0f, 1.0f, fillOpacity.getFloatValue()));
  68732. if (fill.startsWithIgnoreCase ("url"))
  68733. {
  68734. const String id (fill.fromFirstOccurrenceOf ("#", false, false)
  68735. .upToLastOccurrenceOf (")", false, false).trim());
  68736. const XmlElement* const fillXml = findElementForId (topLevelXml, id);
  68737. if (fillXml != 0
  68738. && (fillXml->hasTagName ("linearGradient")
  68739. || fillXml->hasTagName ("radialGradient")))
  68740. {
  68741. const XmlElement* inheritedFrom = findLinkedElement (fillXml);
  68742. ColourGradient gradient;
  68743. addGradientStopsIn (gradient, inheritedFrom);
  68744. addGradientStopsIn (gradient, fillXml);
  68745. if (gradient.getNumColours() > 0)
  68746. {
  68747. gradient.addColour (0.0, gradient.getColour (0));
  68748. gradient.addColour (1.0, gradient.getColour (gradient.getNumColours() - 1));
  68749. }
  68750. else
  68751. {
  68752. gradient.addColour (0.0, Colours::black);
  68753. gradient.addColour (1.0, Colours::black);
  68754. }
  68755. if (overallOpacity.isNotEmpty())
  68756. gradient.multiplyOpacity (overallOpacity.getFloatValue());
  68757. jassert (gradient.getNumColours() > 0);
  68758. gradient.isRadial = fillXml->hasTagName ("radialGradient");
  68759. float gradientWidth = viewBoxW;
  68760. float gradientHeight = viewBoxH;
  68761. float dx = 0.0f;
  68762. float dy = 0.0f;
  68763. const bool userSpace = fillXml->getStringAttribute ("gradientUnits").equalsIgnoreCase ("userSpaceOnUse");
  68764. if (! userSpace)
  68765. {
  68766. const Rectangle<float> bounds (path.getBounds());
  68767. dx = bounds.getX();
  68768. dy = bounds.getY();
  68769. gradientWidth = bounds.getWidth();
  68770. gradientHeight = bounds.getHeight();
  68771. }
  68772. if (gradient.isRadial)
  68773. {
  68774. gradient.x1 = dx + getCoordLength (fillXml->getStringAttribute ("cx", "50%"), gradientWidth);
  68775. gradient.y1 = dy + getCoordLength (fillXml->getStringAttribute ("cy", "50%"), gradientHeight);
  68776. const float radius = getCoordLength (fillXml->getStringAttribute ("r", "50%"), gradientWidth);
  68777. gradient.x2 = gradient.x1 + radius;
  68778. gradient.y2 = gradient.y1;
  68779. //xxx (the fx, fy focal point isn't handled properly here..)
  68780. }
  68781. else
  68782. {
  68783. gradient.x1 = dx + getCoordLength (fillXml->getStringAttribute ("x1", "0%"), gradientWidth);
  68784. gradient.y1 = dy + getCoordLength (fillXml->getStringAttribute ("y1", "0%"), gradientHeight);
  68785. gradient.x2 = dx + getCoordLength (fillXml->getStringAttribute ("x2", "100%"), gradientWidth);
  68786. gradient.y2 = dy + getCoordLength (fillXml->getStringAttribute ("y2", "0%"), gradientHeight);
  68787. if (gradient.x1 == gradient.x2 && gradient.y1 == gradient.y2)
  68788. return Colour (gradient.getColour (gradient.getNumColours() - 1));
  68789. }
  68790. FillType type (gradient);
  68791. type.transform = parseTransform (fillXml->getStringAttribute ("gradientTransform"))
  68792. .followedBy (transform);
  68793. return type;
  68794. }
  68795. }
  68796. if (fill.equalsIgnoreCase ("none"))
  68797. return Colours::transparentBlack;
  68798. int i = 0;
  68799. const Colour colour (parseColour (fill, i, defaultColour));
  68800. return colour.withMultipliedAlpha (opacity);
  68801. }
  68802. const PathStrokeType getStrokeFor (const XmlElement* const xml) const
  68803. {
  68804. const String strokeWidth (getStyleAttribute (xml, "stroke-width"));
  68805. const String cap (getStyleAttribute (xml, "stroke-linecap"));
  68806. const String join (getStyleAttribute (xml, "stroke-linejoin"));
  68807. //const String mitreLimit (getStyleAttribute (xml, "stroke-miterlimit"));
  68808. //const String dashArray (getStyleAttribute (xml, "stroke-dasharray"));
  68809. //const String dashOffset (getStyleAttribute (xml, "stroke-dashoffset"));
  68810. PathStrokeType::JointStyle joinStyle = PathStrokeType::mitered;
  68811. PathStrokeType::EndCapStyle capStyle = PathStrokeType::butt;
  68812. if (join.equalsIgnoreCase ("round"))
  68813. joinStyle = PathStrokeType::curved;
  68814. else if (join.equalsIgnoreCase ("bevel"))
  68815. joinStyle = PathStrokeType::beveled;
  68816. if (cap.equalsIgnoreCase ("round"))
  68817. capStyle = PathStrokeType::rounded;
  68818. else if (cap.equalsIgnoreCase ("square"))
  68819. capStyle = PathStrokeType::square;
  68820. float ox = 0.0f, oy = 0.0f;
  68821. transform.transformPoint (ox, oy);
  68822. float x = getCoordLength (strokeWidth, viewBoxW), y = 0.0f;
  68823. transform.transformPoint (x, y);
  68824. return PathStrokeType (strokeWidth.isNotEmpty() ? juce_hypotf (x - ox, y - oy) : 1.0f,
  68825. joinStyle, capStyle);
  68826. }
  68827. Drawable* parseText (const XmlElement& xml)
  68828. {
  68829. Array <float> xCoords, yCoords, dxCoords, dyCoords;
  68830. getCoordList (xCoords, getInheritedAttribute (&xml, "x"), true, true);
  68831. getCoordList (yCoords, getInheritedAttribute (&xml, "y"), true, false);
  68832. getCoordList (dxCoords, getInheritedAttribute (&xml, "dx"), true, true);
  68833. getCoordList (dyCoords, getInheritedAttribute (&xml, "dy"), true, false);
  68834. //xxx not done text yet!
  68835. forEachXmlChildElement (xml, e)
  68836. {
  68837. if (e->isTextElement())
  68838. {
  68839. const String text (e->getText());
  68840. Path path;
  68841. Drawable* s = parseShape (*e, path);
  68842. delete s;
  68843. }
  68844. else if (e->hasTagName ("tspan"))
  68845. {
  68846. Drawable* s = parseText (*e);
  68847. delete s;
  68848. }
  68849. }
  68850. return 0;
  68851. }
  68852. void addTransform (const XmlElement& xml)
  68853. {
  68854. transform = parseTransform (xml.getStringAttribute ("transform"))
  68855. .followedBy (transform);
  68856. }
  68857. bool parseCoord (const String& s, float& value, int& index,
  68858. const bool allowUnits, const bool isX) const
  68859. {
  68860. String number;
  68861. if (! parseNextNumber (s, number, index, allowUnits))
  68862. {
  68863. value = 0;
  68864. return false;
  68865. }
  68866. value = getCoordLength (number, isX ? viewBoxW : viewBoxH);
  68867. return true;
  68868. }
  68869. bool parseCoords (const String& s, float& x, float& y,
  68870. int& index, const bool allowUnits) const
  68871. {
  68872. return parseCoord (s, x, index, allowUnits, true)
  68873. && parseCoord (s, y, index, allowUnits, false);
  68874. }
  68875. float getCoordLength (const String& s, const float sizeForProportions) const
  68876. {
  68877. float n = s.getFloatValue();
  68878. const int len = s.length();
  68879. if (len > 2)
  68880. {
  68881. const float dpi = 96.0f;
  68882. const juce_wchar n1 = s [len - 2];
  68883. const juce_wchar n2 = s [len - 1];
  68884. if (n1 == 'i' && n2 == 'n')
  68885. n *= dpi;
  68886. else if (n1 == 'm' && n2 == 'm')
  68887. n *= dpi / 25.4f;
  68888. else if (n1 == 'c' && n2 == 'm')
  68889. n *= dpi / 2.54f;
  68890. else if (n1 == 'p' && n2 == 'c')
  68891. n *= 15.0f;
  68892. else if (n2 == '%')
  68893. n *= 0.01f * sizeForProportions;
  68894. }
  68895. return n;
  68896. }
  68897. void getCoordList (Array <float>& coords, const String& list,
  68898. const bool allowUnits, const bool isX) const
  68899. {
  68900. int index = 0;
  68901. float value;
  68902. while (parseCoord (list, value, index, allowUnits, isX))
  68903. coords.add (value);
  68904. }
  68905. void parseCSSStyle (const XmlElement& xml)
  68906. {
  68907. cssStyleText = xml.getAllSubText() + "\n" + cssStyleText;
  68908. }
  68909. const String getStyleAttribute (const XmlElement* xml, const String& attributeName,
  68910. const String& defaultValue = String::empty) const
  68911. {
  68912. if (xml->hasAttribute (attributeName))
  68913. return xml->getStringAttribute (attributeName, defaultValue);
  68914. const String styleAtt (xml->getStringAttribute ("style"));
  68915. if (styleAtt.isNotEmpty())
  68916. {
  68917. const String value (getAttributeFromStyleList (styleAtt, attributeName, String::empty));
  68918. if (value.isNotEmpty())
  68919. return value;
  68920. }
  68921. else if (xml->hasAttribute ("class"))
  68922. {
  68923. const String className ("." + xml->getStringAttribute ("class"));
  68924. int index = cssStyleText.indexOfIgnoreCase (className + " ");
  68925. if (index < 0)
  68926. index = cssStyleText.indexOfIgnoreCase (className + "{");
  68927. if (index >= 0)
  68928. {
  68929. const int openBracket = cssStyleText.indexOfChar (index, '{');
  68930. if (openBracket > index)
  68931. {
  68932. const int closeBracket = cssStyleText.indexOfChar (openBracket, '}');
  68933. if (closeBracket > openBracket)
  68934. {
  68935. const String value (getAttributeFromStyleList (cssStyleText.substring (openBracket + 1, closeBracket), attributeName, defaultValue));
  68936. if (value.isNotEmpty())
  68937. return value;
  68938. }
  68939. }
  68940. }
  68941. }
  68942. xml = const_cast <XmlElement*> (topLevelXml)->findParentElementOf (xml);
  68943. if (xml != 0)
  68944. return getStyleAttribute (xml, attributeName, defaultValue);
  68945. return defaultValue;
  68946. }
  68947. const String getInheritedAttribute (const XmlElement* xml, const String& attributeName) const
  68948. {
  68949. if (xml->hasAttribute (attributeName))
  68950. return xml->getStringAttribute (attributeName);
  68951. xml = const_cast <XmlElement*> (topLevelXml)->findParentElementOf (xml);
  68952. if (xml != 0)
  68953. return getInheritedAttribute (xml, attributeName);
  68954. return String::empty;
  68955. }
  68956. static bool isIdentifierChar (const juce_wchar c)
  68957. {
  68958. return CharacterFunctions::isLetter (c) || c == '-';
  68959. }
  68960. static const String getAttributeFromStyleList (const String& list, const String& attributeName, const String& defaultValue)
  68961. {
  68962. int i = 0;
  68963. for (;;)
  68964. {
  68965. i = list.indexOf (i, attributeName);
  68966. if (i < 0)
  68967. break;
  68968. if ((i == 0 || (i > 0 && ! isIdentifierChar (list [i - 1])))
  68969. && ! isIdentifierChar (list [i + attributeName.length()]))
  68970. {
  68971. i = list.indexOfChar (i, ':');
  68972. if (i < 0)
  68973. break;
  68974. int end = list.indexOfChar (i, ';');
  68975. if (end < 0)
  68976. end = 0x7ffff;
  68977. return list.substring (i + 1, end).trim();
  68978. }
  68979. ++i;
  68980. }
  68981. return defaultValue;
  68982. }
  68983. static bool parseNextNumber (const String& source, String& value, int& index, const bool allowUnits)
  68984. {
  68985. const juce_wchar* const s = source;
  68986. while (CharacterFunctions::isWhitespace (s[index]) || s[index] == ',')
  68987. ++index;
  68988. int start = index;
  68989. if (CharacterFunctions::isDigit (s[index]) || s[index] == '.' || s[index] == '-')
  68990. ++index;
  68991. while (CharacterFunctions::isDigit (s[index]) || s[index] == '.')
  68992. ++index;
  68993. if ((s[index] == 'e' || s[index] == 'E')
  68994. && (CharacterFunctions::isDigit (s[index + 1])
  68995. || s[index + 1] == '-'
  68996. || s[index + 1] == '+'))
  68997. {
  68998. index += 2;
  68999. while (CharacterFunctions::isDigit (s[index]))
  69000. ++index;
  69001. }
  69002. if (allowUnits)
  69003. {
  69004. while (CharacterFunctions::isLetter (s[index]))
  69005. ++index;
  69006. }
  69007. if (index == start)
  69008. return false;
  69009. value = String (s + start, index - start);
  69010. while (CharacterFunctions::isWhitespace (s[index]) || s[index] == ',')
  69011. ++index;
  69012. return true;
  69013. }
  69014. static const Colour parseColour (const String& s, int& index, const Colour& defaultColour)
  69015. {
  69016. if (s [index] == '#')
  69017. {
  69018. uint32 hex [6];
  69019. zeromem (hex, sizeof (hex));
  69020. int numChars = 0;
  69021. for (int i = 6; --i >= 0;)
  69022. {
  69023. const int hexValue = CharacterFunctions::getHexDigitValue (s [++index]);
  69024. if (hexValue >= 0)
  69025. hex [numChars++] = hexValue;
  69026. else
  69027. break;
  69028. }
  69029. if (numChars <= 3)
  69030. return Colour ((uint8) (hex [0] * 0x11),
  69031. (uint8) (hex [1] * 0x11),
  69032. (uint8) (hex [2] * 0x11));
  69033. else
  69034. return Colour ((uint8) ((hex [0] << 4) + hex [1]),
  69035. (uint8) ((hex [2] << 4) + hex [3]),
  69036. (uint8) ((hex [4] << 4) + hex [5]));
  69037. }
  69038. else if (s [index] == 'r'
  69039. && s [index + 1] == 'g'
  69040. && s [index + 2] == 'b')
  69041. {
  69042. const int openBracket = s.indexOfChar (index, '(');
  69043. const int closeBracket = s.indexOfChar (openBracket, ')');
  69044. if (openBracket >= 3 && closeBracket > openBracket)
  69045. {
  69046. index = closeBracket;
  69047. StringArray tokens;
  69048. tokens.addTokens (s.substring (openBracket + 1, closeBracket), ",", "");
  69049. tokens.trim();
  69050. tokens.removeEmptyStrings();
  69051. if (tokens[0].containsChar ('%'))
  69052. return Colour ((uint8) roundToInt (2.55 * tokens[0].getDoubleValue()),
  69053. (uint8) roundToInt (2.55 * tokens[1].getDoubleValue()),
  69054. (uint8) roundToInt (2.55 * tokens[2].getDoubleValue()));
  69055. else
  69056. return Colour ((uint8) tokens[0].getIntValue(),
  69057. (uint8) tokens[1].getIntValue(),
  69058. (uint8) tokens[2].getIntValue());
  69059. }
  69060. }
  69061. return Colours::findColourForName (s, defaultColour);
  69062. }
  69063. static const AffineTransform parseTransform (String t)
  69064. {
  69065. AffineTransform result;
  69066. while (t.isNotEmpty())
  69067. {
  69068. StringArray tokens;
  69069. tokens.addTokens (t.fromFirstOccurrenceOf ("(", false, false)
  69070. .upToFirstOccurrenceOf (")", false, false),
  69071. ", ", String::empty);
  69072. tokens.removeEmptyStrings (true);
  69073. float numbers [6];
  69074. for (int i = 0; i < 6; ++i)
  69075. numbers[i] = tokens[i].getFloatValue();
  69076. AffineTransform trans;
  69077. if (t.startsWithIgnoreCase ("matrix"))
  69078. {
  69079. trans = AffineTransform (numbers[0], numbers[2], numbers[4],
  69080. numbers[1], numbers[3], numbers[5]);
  69081. }
  69082. else if (t.startsWithIgnoreCase ("translate"))
  69083. {
  69084. jassert (tokens.size() == 2);
  69085. trans = AffineTransform::translation (numbers[0], numbers[1]);
  69086. }
  69087. else if (t.startsWithIgnoreCase ("scale"))
  69088. {
  69089. if (tokens.size() == 1)
  69090. trans = AffineTransform::scale (numbers[0], numbers[0]);
  69091. else
  69092. trans = AffineTransform::scale (numbers[0], numbers[1]);
  69093. }
  69094. else if (t.startsWithIgnoreCase ("rotate"))
  69095. {
  69096. if (tokens.size() != 3)
  69097. trans = AffineTransform::rotation (numbers[0] / (180.0f / float_Pi));
  69098. else
  69099. trans = AffineTransform::rotation (numbers[0] / (180.0f / float_Pi),
  69100. numbers[1], numbers[2]);
  69101. }
  69102. else if (t.startsWithIgnoreCase ("skewX"))
  69103. {
  69104. trans = AffineTransform (1.0f, std::tan (numbers[0] * (float_Pi / 180.0f)), 0.0f,
  69105. 0.0f, 1.0f, 0.0f);
  69106. }
  69107. else if (t.startsWithIgnoreCase ("skewY"))
  69108. {
  69109. trans = AffineTransform (1.0f, 0.0f, 0.0f,
  69110. std::tan (numbers[0] * (float_Pi / 180.0f)), 1.0f, 0.0f);
  69111. }
  69112. result = trans.followedBy (result);
  69113. t = t.fromFirstOccurrenceOf (")", false, false).trimStart();
  69114. }
  69115. return result;
  69116. }
  69117. static void endpointToCentreParameters (const double x1, const double y1,
  69118. const double x2, const double y2,
  69119. const double angle,
  69120. const bool largeArc, const bool sweep,
  69121. double& rx, double& ry,
  69122. double& centreX, double& centreY,
  69123. double& startAngle, double& deltaAngle)
  69124. {
  69125. const double midX = (x1 - x2) * 0.5;
  69126. const double midY = (y1 - y2) * 0.5;
  69127. const double cosAngle = cos (angle);
  69128. const double sinAngle = sin (angle);
  69129. const double xp = cosAngle * midX + sinAngle * midY;
  69130. const double yp = cosAngle * midY - sinAngle * midX;
  69131. const double xp2 = xp * xp;
  69132. const double yp2 = yp * yp;
  69133. double rx2 = rx * rx;
  69134. double ry2 = ry * ry;
  69135. const double s = (xp2 / rx2) + (yp2 / ry2);
  69136. double c;
  69137. if (s <= 1.0)
  69138. {
  69139. c = std::sqrt (jmax (0.0, ((rx2 * ry2) - (rx2 * yp2) - (ry2 * xp2))
  69140. / (( rx2 * yp2) + (ry2 * xp2))));
  69141. if (largeArc == sweep)
  69142. c = -c;
  69143. }
  69144. else
  69145. {
  69146. const double s2 = std::sqrt (s);
  69147. rx *= s2;
  69148. ry *= s2;
  69149. rx2 = rx * rx;
  69150. ry2 = ry * ry;
  69151. c = 0;
  69152. }
  69153. const double cpx = ((rx * yp) / ry) * c;
  69154. const double cpy = ((-ry * xp) / rx) * c;
  69155. centreX = ((x1 + x2) * 0.5) + (cosAngle * cpx) - (sinAngle * cpy);
  69156. centreY = ((y1 + y2) * 0.5) + (sinAngle * cpx) + (cosAngle * cpy);
  69157. const double ux = (xp - cpx) / rx;
  69158. const double uy = (yp - cpy) / ry;
  69159. const double vx = (-xp - cpx) / rx;
  69160. const double vy = (-yp - cpy) / ry;
  69161. const double length = juce_hypot (ux, uy);
  69162. startAngle = acos (jlimit (-1.0, 1.0, ux / length));
  69163. if (uy < 0)
  69164. startAngle = -startAngle;
  69165. startAngle += double_Pi * 0.5;
  69166. deltaAngle = acos (jlimit (-1.0, 1.0, ((ux * vx) + (uy * vy))
  69167. / (length * juce_hypot (vx, vy))));
  69168. if ((ux * vy) - (uy * vx) < 0)
  69169. deltaAngle = -deltaAngle;
  69170. if (sweep)
  69171. {
  69172. if (deltaAngle < 0)
  69173. deltaAngle += double_Pi * 2.0;
  69174. }
  69175. else
  69176. {
  69177. if (deltaAngle > 0)
  69178. deltaAngle -= double_Pi * 2.0;
  69179. }
  69180. deltaAngle = fmod (deltaAngle, double_Pi * 2.0);
  69181. }
  69182. static const XmlElement* findElementForId (const XmlElement* const parent, const String& id)
  69183. {
  69184. forEachXmlChildElement (*parent, e)
  69185. {
  69186. if (e->compareAttribute ("id", id))
  69187. return e;
  69188. const XmlElement* const found = findElementForId (e, id);
  69189. if (found != 0)
  69190. return found;
  69191. }
  69192. return 0;
  69193. }
  69194. SVGState& operator= (const SVGState&);
  69195. };
  69196. Drawable* Drawable::createFromSVG (const XmlElement& svgDocument)
  69197. {
  69198. SVGState state (&svgDocument);
  69199. return state.parseSVGElement (svgDocument);
  69200. }
  69201. END_JUCE_NAMESPACE
  69202. /*** End of inlined file: juce_SVGParser.cpp ***/
  69203. /*** Start of inlined file: juce_DropShadowEffect.cpp ***/
  69204. BEGIN_JUCE_NAMESPACE
  69205. #if JUCE_MSVC
  69206. #pragma optimize ("t", on) // try to avoid slowing everything down in debug builds
  69207. #endif
  69208. DropShadowEffect::DropShadowEffect()
  69209. : offsetX (0),
  69210. offsetY (0),
  69211. radius (4),
  69212. opacity (0.6f)
  69213. {
  69214. }
  69215. DropShadowEffect::~DropShadowEffect()
  69216. {
  69217. }
  69218. void DropShadowEffect::setShadowProperties (const float newRadius,
  69219. const float newOpacity,
  69220. const int newShadowOffsetX,
  69221. const int newShadowOffsetY)
  69222. {
  69223. radius = jmax (1.1f, newRadius);
  69224. offsetX = newShadowOffsetX;
  69225. offsetY = newShadowOffsetY;
  69226. opacity = newOpacity;
  69227. }
  69228. void DropShadowEffect::applyEffect (Image& image, Graphics& g)
  69229. {
  69230. const int w = image.getWidth();
  69231. const int h = image.getHeight();
  69232. Image shadowImage (Image::SingleChannel, w, h, false);
  69233. const Image::BitmapData srcData (image, 0, 0, w, h);
  69234. const Image::BitmapData destData (shadowImage, 0, 0, w, h, true);
  69235. const int filter = roundToInt (63.0f / radius);
  69236. const int radiusMinus1 = roundToInt ((radius - 1.0f) * 63.0f);
  69237. for (int x = w; --x >= 0;)
  69238. {
  69239. int shadowAlpha = 0;
  69240. const PixelARGB* src = ((const PixelARGB*) srcData.data) + x;
  69241. uint8* shadowPix = destData.data + x;
  69242. for (int y = h; --y >= 0;)
  69243. {
  69244. shadowAlpha = ((shadowAlpha * radiusMinus1 + (src->getAlpha() << 6)) * filter) >> 12;
  69245. *shadowPix = (uint8) shadowAlpha;
  69246. src = (const PixelARGB*) (((const uint8*) src) + srcData.lineStride);
  69247. shadowPix += destData.lineStride;
  69248. }
  69249. }
  69250. for (int y = h; --y >= 0;)
  69251. {
  69252. int shadowAlpha = 0;
  69253. uint8* shadowPix = destData.getLinePointer (y);
  69254. for (int x = w; --x >= 0;)
  69255. {
  69256. shadowAlpha = ((shadowAlpha * radiusMinus1 + (*shadowPix << 6)) * filter) >> 12;
  69257. *shadowPix++ = (uint8) shadowAlpha;
  69258. }
  69259. }
  69260. g.setColour (Colours::black.withAlpha (opacity));
  69261. g.drawImageAt (&shadowImage, offsetX, offsetY, true);
  69262. g.setOpacity (1.0f);
  69263. g.drawImageAt (&image, 0, 0);
  69264. }
  69265. END_JUCE_NAMESPACE
  69266. /*** End of inlined file: juce_DropShadowEffect.cpp ***/
  69267. /*** Start of inlined file: juce_GlowEffect.cpp ***/
  69268. BEGIN_JUCE_NAMESPACE
  69269. GlowEffect::GlowEffect()
  69270. : radius (2.0f),
  69271. colour (Colours::white)
  69272. {
  69273. }
  69274. GlowEffect::~GlowEffect()
  69275. {
  69276. }
  69277. void GlowEffect::setGlowProperties (const float newRadius,
  69278. const Colour& newColour)
  69279. {
  69280. radius = newRadius;
  69281. colour = newColour;
  69282. }
  69283. void GlowEffect::applyEffect (Image& image, Graphics& g)
  69284. {
  69285. Image temp (image.getFormat(), image.getWidth(), image.getHeight(), true);
  69286. ImageConvolutionKernel blurKernel (roundToInt (radius * 2.0f));
  69287. blurKernel.createGaussianBlur (radius);
  69288. blurKernel.rescaleAllValues (radius);
  69289. blurKernel.applyToImage (temp, &image, image.getBounds());
  69290. g.setColour (colour);
  69291. g.drawImageAt (&temp, 0, 0, true);
  69292. g.setOpacity (1.0f);
  69293. g.drawImageAt (&image, 0, 0, false);
  69294. }
  69295. END_JUCE_NAMESPACE
  69296. /*** End of inlined file: juce_GlowEffect.cpp ***/
  69297. /*** Start of inlined file: juce_ReduceOpacityEffect.cpp ***/
  69298. BEGIN_JUCE_NAMESPACE
  69299. ReduceOpacityEffect::ReduceOpacityEffect (const float opacity_)
  69300. : opacity (opacity_)
  69301. {
  69302. }
  69303. ReduceOpacityEffect::~ReduceOpacityEffect()
  69304. {
  69305. }
  69306. void ReduceOpacityEffect::setOpacity (const float newOpacity)
  69307. {
  69308. opacity = jlimit (0.0f, 1.0f, newOpacity);
  69309. }
  69310. void ReduceOpacityEffect::applyEffect (Image& image, Graphics& g)
  69311. {
  69312. g.setOpacity (opacity);
  69313. g.drawImageAt (&image, 0, 0);
  69314. }
  69315. END_JUCE_NAMESPACE
  69316. /*** End of inlined file: juce_ReduceOpacityEffect.cpp ***/
  69317. /*** Start of inlined file: juce_Font.cpp ***/
  69318. BEGIN_JUCE_NAMESPACE
  69319. namespace FontValues
  69320. {
  69321. static float limitFontHeight (const float height) throw()
  69322. {
  69323. return jlimit (0.1f, 10000.0f, height);
  69324. }
  69325. static const float defaultFontHeight = 14.0f;
  69326. static String fallbackFont;
  69327. }
  69328. Font::SharedFontInternal::SharedFontInternal (const String& typefaceName_, const float height_, const float horizontalScale_,
  69329. const float kerning_, const float ascent_, const int styleFlags_,
  69330. Typeface* const typeface_) throw()
  69331. : typefaceName (typefaceName_),
  69332. height (height_),
  69333. horizontalScale (horizontalScale_),
  69334. kerning (kerning_),
  69335. ascent (ascent_),
  69336. styleFlags (styleFlags_),
  69337. typeface (typeface_)
  69338. {
  69339. }
  69340. Font::SharedFontInternal::SharedFontInternal (const SharedFontInternal& other) throw()
  69341. : typefaceName (other.typefaceName),
  69342. height (other.height),
  69343. horizontalScale (other.horizontalScale),
  69344. kerning (other.kerning),
  69345. ascent (other.ascent),
  69346. styleFlags (other.styleFlags),
  69347. typeface (other.typeface)
  69348. {
  69349. }
  69350. Font::Font() throw()
  69351. : font (new SharedFontInternal (getDefaultSansSerifFontName(), FontValues::defaultFontHeight,
  69352. 1.0f, 0, 0, Font::plain, 0))
  69353. {
  69354. }
  69355. Font::Font (const float fontHeight, const int styleFlags_) throw()
  69356. : font (new SharedFontInternal (getDefaultSansSerifFontName(), FontValues::limitFontHeight (fontHeight),
  69357. 1.0f, 0, 0, styleFlags_, 0))
  69358. {
  69359. }
  69360. Font::Font (const String& typefaceName_,
  69361. const float fontHeight,
  69362. const int styleFlags_) throw()
  69363. : font (new SharedFontInternal (typefaceName_, FontValues::limitFontHeight (fontHeight),
  69364. 1.0f, 0, 0, styleFlags_, 0))
  69365. {
  69366. }
  69367. Font::Font (const Font& other) throw()
  69368. : font (other.font)
  69369. {
  69370. }
  69371. Font& Font::operator= (const Font& other) throw()
  69372. {
  69373. font = other.font;
  69374. return *this;
  69375. }
  69376. Font::~Font() throw()
  69377. {
  69378. }
  69379. Font::Font (const Typeface::Ptr& typeface) throw()
  69380. : font (new SharedFontInternal (typeface->getName(), FontValues::defaultFontHeight,
  69381. 1.0f, 0, 0, Font::plain, typeface))
  69382. {
  69383. }
  69384. bool Font::operator== (const Font& other) const throw()
  69385. {
  69386. return font == other.font
  69387. || (font->height == other.font->height
  69388. && font->styleFlags == other.font->styleFlags
  69389. && font->horizontalScale == other.font->horizontalScale
  69390. && font->kerning == other.font->kerning
  69391. && font->typefaceName == other.font->typefaceName);
  69392. }
  69393. bool Font::operator!= (const Font& other) const throw()
  69394. {
  69395. return ! operator== (other);
  69396. }
  69397. void Font::dupeInternalIfShared() throw()
  69398. {
  69399. if (font->getReferenceCount() > 1)
  69400. font = new SharedFontInternal (*font);
  69401. }
  69402. const String Font::getDefaultSansSerifFontName() throw()
  69403. {
  69404. static const String name ("<Sans-Serif>");
  69405. return name;
  69406. }
  69407. const String Font::getDefaultSerifFontName() throw()
  69408. {
  69409. static const String name ("<Serif>");
  69410. return name;
  69411. }
  69412. const String Font::getDefaultMonospacedFontName() throw()
  69413. {
  69414. static const String name ("<Monospaced>");
  69415. return name;
  69416. }
  69417. void Font::setTypefaceName (const String& faceName) throw()
  69418. {
  69419. if (faceName != font->typefaceName)
  69420. {
  69421. dupeInternalIfShared();
  69422. font->typefaceName = faceName;
  69423. font->typeface = 0;
  69424. font->ascent = 0;
  69425. }
  69426. }
  69427. const String Font::getFallbackFontName() throw()
  69428. {
  69429. return FontValues::fallbackFont;
  69430. }
  69431. void Font::setFallbackFontName (const String& name) throw()
  69432. {
  69433. FontValues::fallbackFont = name;
  69434. }
  69435. void Font::setHeight (float newHeight) throw()
  69436. {
  69437. newHeight = FontValues::limitFontHeight (newHeight);
  69438. if (font->height != newHeight)
  69439. {
  69440. dupeInternalIfShared();
  69441. font->height = newHeight;
  69442. }
  69443. }
  69444. void Font::setHeightWithoutChangingWidth (float newHeight) throw()
  69445. {
  69446. newHeight = FontValues::limitFontHeight (newHeight);
  69447. if (font->height != newHeight)
  69448. {
  69449. dupeInternalIfShared();
  69450. font->horizontalScale *= (font->height / newHeight);
  69451. font->height = newHeight;
  69452. }
  69453. }
  69454. void Font::setStyleFlags (const int newFlags) throw()
  69455. {
  69456. if (font->styleFlags != newFlags)
  69457. {
  69458. dupeInternalIfShared();
  69459. font->styleFlags = newFlags;
  69460. font->typeface = 0;
  69461. font->ascent = 0;
  69462. }
  69463. }
  69464. void Font::setSizeAndStyle (float newHeight,
  69465. const int newStyleFlags,
  69466. const float newHorizontalScale,
  69467. const float newKerningAmount) throw()
  69468. {
  69469. newHeight = FontValues::limitFontHeight (newHeight);
  69470. if (font->height != newHeight
  69471. || font->horizontalScale != newHorizontalScale
  69472. || font->kerning != newKerningAmount)
  69473. {
  69474. dupeInternalIfShared();
  69475. font->height = newHeight;
  69476. font->horizontalScale = newHorizontalScale;
  69477. font->kerning = newKerningAmount;
  69478. }
  69479. setStyleFlags (newStyleFlags);
  69480. }
  69481. void Font::setHorizontalScale (const float scaleFactor) throw()
  69482. {
  69483. dupeInternalIfShared();
  69484. font->horizontalScale = scaleFactor;
  69485. }
  69486. void Font::setExtraKerningFactor (const float extraKerning) throw()
  69487. {
  69488. dupeInternalIfShared();
  69489. font->kerning = extraKerning;
  69490. }
  69491. void Font::setBold (const bool shouldBeBold) throw()
  69492. {
  69493. setStyleFlags (shouldBeBold ? (font->styleFlags | bold)
  69494. : (font->styleFlags & ~bold));
  69495. }
  69496. bool Font::isBold() const throw()
  69497. {
  69498. return (font->styleFlags & bold) != 0;
  69499. }
  69500. void Font::setItalic (const bool shouldBeItalic) throw()
  69501. {
  69502. setStyleFlags (shouldBeItalic ? (font->styleFlags | italic)
  69503. : (font->styleFlags & ~italic));
  69504. }
  69505. bool Font::isItalic() const throw()
  69506. {
  69507. return (font->styleFlags & italic) != 0;
  69508. }
  69509. void Font::setUnderline (const bool shouldBeUnderlined) throw()
  69510. {
  69511. setStyleFlags (shouldBeUnderlined ? (font->styleFlags | underlined)
  69512. : (font->styleFlags & ~underlined));
  69513. }
  69514. bool Font::isUnderlined() const throw()
  69515. {
  69516. return (font->styleFlags & underlined) != 0;
  69517. }
  69518. float Font::getAscent() const throw()
  69519. {
  69520. if (font->ascent == 0)
  69521. font->ascent = getTypeface()->getAscent();
  69522. return font->height * font->ascent;
  69523. }
  69524. float Font::getDescent() const throw()
  69525. {
  69526. return font->height - getAscent();
  69527. }
  69528. int Font::getStringWidth (const String& text) const throw()
  69529. {
  69530. return roundToInt (getStringWidthFloat (text));
  69531. }
  69532. float Font::getStringWidthFloat (const String& text) const throw()
  69533. {
  69534. float w = getTypeface()->getStringWidth (text);
  69535. if (font->kerning != 0)
  69536. w += font->kerning * text.length();
  69537. return w * font->height * font->horizontalScale;
  69538. }
  69539. void Font::getGlyphPositions (const String& text, Array <int>& glyphs, Array <float>& xOffsets) const throw()
  69540. {
  69541. getTypeface()->getGlyphPositions (text, glyphs, xOffsets);
  69542. const float scale = font->height * font->horizontalScale;
  69543. const int num = xOffsets.size();
  69544. if (num > 0)
  69545. {
  69546. float* const x = &(xOffsets.getReference(0));
  69547. if (font->kerning != 0)
  69548. {
  69549. for (int i = 0; i < num; ++i)
  69550. x[i] = (x[i] + i * font->kerning) * scale;
  69551. }
  69552. else
  69553. {
  69554. for (int i = 0; i < num; ++i)
  69555. x[i] *= scale;
  69556. }
  69557. }
  69558. }
  69559. void Font::findFonts (Array<Font>& destArray) throw()
  69560. {
  69561. const StringArray names (findAllTypefaceNames());
  69562. for (int i = 0; i < names.size(); ++i)
  69563. destArray.add (Font (names[i], FontValues::defaultFontHeight, Font::plain));
  69564. }
  69565. class TypefaceCache : public DeletedAtShutdown
  69566. {
  69567. public:
  69568. TypefaceCache (int numToCache = 10) throw()
  69569. : counter (1)
  69570. {
  69571. while (--numToCache >= 0)
  69572. faces.add (new CachedFace());
  69573. }
  69574. ~TypefaceCache()
  69575. {
  69576. clearSingletonInstance();
  69577. }
  69578. juce_DeclareSingleton_SingleThreaded_Minimal (TypefaceCache)
  69579. const Typeface::Ptr findTypefaceFor (const Font& font) throw()
  69580. {
  69581. const int flags = font.getStyleFlags() & (Font::bold | Font::italic);
  69582. const String faceName (font.getTypefaceName());
  69583. int i;
  69584. for (i = faces.size(); --i >= 0;)
  69585. {
  69586. CachedFace* const face = faces.getUnchecked(i);
  69587. if (face->flags == flags
  69588. && face->typefaceName == faceName)
  69589. {
  69590. face->lastUsageCount = ++counter;
  69591. return face->typeFace;
  69592. }
  69593. }
  69594. int replaceIndex = 0;
  69595. int bestLastUsageCount = std::numeric_limits<int>::max();
  69596. for (i = faces.size(); --i >= 0;)
  69597. {
  69598. const int lu = faces.getUnchecked(i)->lastUsageCount;
  69599. if (bestLastUsageCount > lu)
  69600. {
  69601. bestLastUsageCount = lu;
  69602. replaceIndex = i;
  69603. }
  69604. }
  69605. CachedFace* const face = faces.getUnchecked (replaceIndex);
  69606. face->typefaceName = faceName;
  69607. face->flags = flags;
  69608. face->lastUsageCount = ++counter;
  69609. face->typeFace = LookAndFeel::getDefaultLookAndFeel().getTypefaceForFont (font);
  69610. jassert (face->typeFace != 0); // the look and feel must return a typeface!
  69611. return face->typeFace;
  69612. }
  69613. juce_UseDebuggingNewOperator
  69614. private:
  69615. struct CachedFace
  69616. {
  69617. CachedFace() throw()
  69618. : lastUsageCount (0), flags (-1)
  69619. {
  69620. }
  69621. String typefaceName;
  69622. int lastUsageCount;
  69623. int flags;
  69624. Typeface::Ptr typeFace;
  69625. };
  69626. int counter;
  69627. OwnedArray <CachedFace> faces;
  69628. TypefaceCache (const TypefaceCache&);
  69629. TypefaceCache& operator= (const TypefaceCache&);
  69630. };
  69631. juce_ImplementSingleton_SingleThreaded (TypefaceCache)
  69632. Typeface* Font::getTypeface() const throw()
  69633. {
  69634. if (font->typeface == 0)
  69635. font->typeface = TypefaceCache::getInstance()->findTypefaceFor (*this);
  69636. return font->typeface;
  69637. }
  69638. END_JUCE_NAMESPACE
  69639. /*** End of inlined file: juce_Font.cpp ***/
  69640. /*** Start of inlined file: juce_GlyphArrangement.cpp ***/
  69641. BEGIN_JUCE_NAMESPACE
  69642. PositionedGlyph::PositionedGlyph (const float x_, const float y_, const float w_, const Font& font_,
  69643. const juce_wchar character_, const int glyph_)
  69644. : x (x_),
  69645. y (y_),
  69646. w (w_),
  69647. font (font_),
  69648. character (character_),
  69649. glyph (glyph_)
  69650. {
  69651. }
  69652. PositionedGlyph::PositionedGlyph (const PositionedGlyph& other)
  69653. : x (other.x),
  69654. y (other.y),
  69655. w (other.w),
  69656. font (other.font),
  69657. character (other.character),
  69658. glyph (other.glyph)
  69659. {
  69660. }
  69661. void PositionedGlyph::draw (const Graphics& g) const
  69662. {
  69663. if (! isWhitespace())
  69664. {
  69665. g.getInternalContext()->setFont (font);
  69666. g.getInternalContext()->drawGlyph (glyph, AffineTransform::translation (x, y));
  69667. }
  69668. }
  69669. void PositionedGlyph::draw (const Graphics& g,
  69670. const AffineTransform& transform) const
  69671. {
  69672. if (! isWhitespace())
  69673. {
  69674. g.getInternalContext()->setFont (font);
  69675. g.getInternalContext()->drawGlyph (glyph, AffineTransform::translation (x, y)
  69676. .followedBy (transform));
  69677. }
  69678. }
  69679. void PositionedGlyph::createPath (Path& path) const
  69680. {
  69681. if (! isWhitespace())
  69682. {
  69683. Typeface* const t = font.getTypeface();
  69684. if (t != 0)
  69685. {
  69686. Path p;
  69687. t->getOutlineForGlyph (glyph, p);
  69688. path.addPath (p, AffineTransform::scale (font.getHeight() * font.getHorizontalScale(), font.getHeight())
  69689. .translated (x, y));
  69690. }
  69691. }
  69692. }
  69693. bool PositionedGlyph::hitTest (float px, float py) const
  69694. {
  69695. if (getBounds().contains (px, py) && ! isWhitespace())
  69696. {
  69697. Typeface* const t = font.getTypeface();
  69698. if (t != 0)
  69699. {
  69700. Path p;
  69701. t->getOutlineForGlyph (glyph, p);
  69702. AffineTransform::translation (-x, -y)
  69703. .scaled (1.0f / (font.getHeight() * font.getHorizontalScale()), 1.0f / font.getHeight())
  69704. .transformPoint (px, py);
  69705. return p.contains (px, py);
  69706. }
  69707. }
  69708. return false;
  69709. }
  69710. void PositionedGlyph::moveBy (const float deltaX,
  69711. const float deltaY)
  69712. {
  69713. x += deltaX;
  69714. y += deltaY;
  69715. }
  69716. GlyphArrangement::GlyphArrangement()
  69717. {
  69718. glyphs.ensureStorageAllocated (128);
  69719. }
  69720. GlyphArrangement::GlyphArrangement (const GlyphArrangement& other)
  69721. {
  69722. addGlyphArrangement (other);
  69723. }
  69724. GlyphArrangement& GlyphArrangement::operator= (const GlyphArrangement& other)
  69725. {
  69726. if (this != &other)
  69727. {
  69728. clear();
  69729. addGlyphArrangement (other);
  69730. }
  69731. return *this;
  69732. }
  69733. GlyphArrangement::~GlyphArrangement()
  69734. {
  69735. }
  69736. void GlyphArrangement::clear()
  69737. {
  69738. glyphs.clear();
  69739. }
  69740. PositionedGlyph& GlyphArrangement::getGlyph (const int index) const
  69741. {
  69742. jassert (((unsigned int) index) < (unsigned int) glyphs.size());
  69743. return *glyphs [index];
  69744. }
  69745. void GlyphArrangement::addGlyphArrangement (const GlyphArrangement& other)
  69746. {
  69747. glyphs.ensureStorageAllocated (glyphs.size() + other.glyphs.size());
  69748. for (int i = 0; i < other.glyphs.size(); ++i)
  69749. glyphs.add (new PositionedGlyph (*other.glyphs.getUnchecked (i)));
  69750. }
  69751. void GlyphArrangement::removeRangeOfGlyphs (int startIndex, const int num)
  69752. {
  69753. glyphs.removeRange (startIndex, num < 0 ? glyphs.size() : num);
  69754. }
  69755. void GlyphArrangement::addLineOfText (const Font& font,
  69756. const String& text,
  69757. const float xOffset,
  69758. const float yOffset)
  69759. {
  69760. addCurtailedLineOfText (font, text,
  69761. xOffset, yOffset,
  69762. 1.0e10f, false);
  69763. }
  69764. void GlyphArrangement::addCurtailedLineOfText (const Font& font,
  69765. const String& text,
  69766. float xOffset,
  69767. const float yOffset,
  69768. const float maxWidthPixels,
  69769. const bool useEllipsis)
  69770. {
  69771. if (text.isNotEmpty())
  69772. {
  69773. Array <int> newGlyphs;
  69774. Array <float> xOffsets;
  69775. font.getGlyphPositions (text, newGlyphs, xOffsets);
  69776. const int textLen = newGlyphs.size();
  69777. const juce_wchar* const unicodeText = text;
  69778. for (int i = 0; i < textLen; ++i)
  69779. {
  69780. const float thisX = xOffsets.getUnchecked (i);
  69781. const float nextX = xOffsets.getUnchecked (i + 1);
  69782. if (nextX > maxWidthPixels + 1.0f)
  69783. {
  69784. // curtail the string if it's too wide..
  69785. if (useEllipsis && textLen > 3 && glyphs.size() >= 3)
  69786. insertEllipsis (font, xOffset + maxWidthPixels, 0, glyphs.size());
  69787. break;
  69788. }
  69789. else
  69790. {
  69791. glyphs.add (new PositionedGlyph (xOffset + thisX, yOffset, nextX - thisX,
  69792. font, unicodeText[i], newGlyphs.getUnchecked(i)));
  69793. }
  69794. }
  69795. }
  69796. }
  69797. int GlyphArrangement::insertEllipsis (const Font& font, const float maxXPos,
  69798. const int startIndex, int endIndex)
  69799. {
  69800. int numDeleted = 0;
  69801. if (glyphs.size() > 0)
  69802. {
  69803. Array<int> dotGlyphs;
  69804. Array<float> dotXs;
  69805. font.getGlyphPositions ("..", dotGlyphs, dotXs);
  69806. const float dx = dotXs[1];
  69807. float xOffset = 0.0f, yOffset = 0.0f;
  69808. while (endIndex > startIndex)
  69809. {
  69810. const PositionedGlyph* pg = glyphs.getUnchecked (--endIndex);
  69811. xOffset = pg->x;
  69812. yOffset = pg->y;
  69813. glyphs.remove (endIndex);
  69814. ++numDeleted;
  69815. if (xOffset + dx * 3 <= maxXPos)
  69816. break;
  69817. }
  69818. for (int i = 3; --i >= 0;)
  69819. {
  69820. glyphs.insert (endIndex++, new PositionedGlyph (xOffset, yOffset, dx,
  69821. font, '.', dotGlyphs.getFirst()));
  69822. --numDeleted;
  69823. xOffset += dx;
  69824. if (xOffset > maxXPos)
  69825. break;
  69826. }
  69827. }
  69828. return numDeleted;
  69829. }
  69830. void GlyphArrangement::addJustifiedText (const Font& font,
  69831. const String& text,
  69832. float x, float y,
  69833. const float maxLineWidth,
  69834. const Justification& horizontalLayout)
  69835. {
  69836. int lineStartIndex = glyphs.size();
  69837. addLineOfText (font, text, x, y);
  69838. const float originalY = y;
  69839. while (lineStartIndex < glyphs.size())
  69840. {
  69841. int i = lineStartIndex;
  69842. if (glyphs.getUnchecked(i)->getCharacter() != '\n'
  69843. && glyphs.getUnchecked(i)->getCharacter() != '\r')
  69844. ++i;
  69845. const float lineMaxX = glyphs.getUnchecked (lineStartIndex)->getLeft() + maxLineWidth;
  69846. int lastWordBreakIndex = -1;
  69847. while (i < glyphs.size())
  69848. {
  69849. const PositionedGlyph* pg = glyphs.getUnchecked (i);
  69850. const juce_wchar c = pg->getCharacter();
  69851. if (c == '\r' || c == '\n')
  69852. {
  69853. ++i;
  69854. if (c == '\r' && i < glyphs.size()
  69855. && glyphs.getUnchecked(i)->getCharacter() == '\n')
  69856. ++i;
  69857. break;
  69858. }
  69859. else if (pg->isWhitespace())
  69860. {
  69861. lastWordBreakIndex = i + 1;
  69862. }
  69863. else if (pg->getRight() - 0.0001f >= lineMaxX)
  69864. {
  69865. if (lastWordBreakIndex >= 0)
  69866. i = lastWordBreakIndex;
  69867. break;
  69868. }
  69869. ++i;
  69870. }
  69871. const float currentLineStartX = glyphs.getUnchecked (lineStartIndex)->getLeft();
  69872. float currentLineEndX = currentLineStartX;
  69873. for (int j = i; --j >= lineStartIndex;)
  69874. {
  69875. if (! glyphs.getUnchecked (j)->isWhitespace())
  69876. {
  69877. currentLineEndX = glyphs.getUnchecked (j)->getRight();
  69878. break;
  69879. }
  69880. }
  69881. float deltaX = 0.0f;
  69882. if (horizontalLayout.testFlags (Justification::horizontallyJustified))
  69883. spreadOutLine (lineStartIndex, i - lineStartIndex, maxLineWidth);
  69884. else if (horizontalLayout.testFlags (Justification::horizontallyCentred))
  69885. deltaX = (maxLineWidth - (currentLineEndX - currentLineStartX)) * 0.5f;
  69886. else if (horizontalLayout.testFlags (Justification::right))
  69887. deltaX = maxLineWidth - (currentLineEndX - currentLineStartX);
  69888. moveRangeOfGlyphs (lineStartIndex, i - lineStartIndex,
  69889. x + deltaX - currentLineStartX, y - originalY);
  69890. lineStartIndex = i;
  69891. y += font.getHeight();
  69892. }
  69893. }
  69894. void GlyphArrangement::addFittedText (const Font& f,
  69895. const String& text,
  69896. const float x, const float y,
  69897. const float width, const float height,
  69898. const Justification& layout,
  69899. int maximumLines,
  69900. const float minimumHorizontalScale)
  69901. {
  69902. // doesn't make much sense if this is outside a sensible range of 0.5 to 1.0
  69903. jassert (minimumHorizontalScale > 0 && minimumHorizontalScale <= 1.0f);
  69904. if (text.containsAnyOf ("\r\n"))
  69905. {
  69906. GlyphArrangement ga;
  69907. ga.addJustifiedText (f, text, x, y, width, layout);
  69908. const Rectangle<float> bb (ga.getBoundingBox (0, -1, false));
  69909. float dy = y - bb.getY();
  69910. if (layout.testFlags (Justification::verticallyCentred))
  69911. dy += (height - bb.getHeight()) * 0.5f;
  69912. else if (layout.testFlags (Justification::bottom))
  69913. dy += height - bb.getHeight();
  69914. ga.moveRangeOfGlyphs (0, -1, 0.0f, dy);
  69915. glyphs.ensureStorageAllocated (glyphs.size() + ga.glyphs.size());
  69916. for (int i = 0; i < ga.glyphs.size(); ++i)
  69917. glyphs.add (ga.glyphs.getUnchecked (i));
  69918. ga.glyphs.clear (false);
  69919. return;
  69920. }
  69921. int startIndex = glyphs.size();
  69922. addLineOfText (f, text.trim(), x, y);
  69923. if (glyphs.size() > startIndex)
  69924. {
  69925. float lineWidth = glyphs.getUnchecked (glyphs.size() - 1)->getRight()
  69926. - glyphs.getUnchecked (startIndex)->getLeft();
  69927. if (lineWidth <= 0)
  69928. return;
  69929. if (lineWidth * minimumHorizontalScale < width)
  69930. {
  69931. if (lineWidth > width)
  69932. stretchRangeOfGlyphs (startIndex, glyphs.size() - startIndex,
  69933. width / lineWidth);
  69934. justifyGlyphs (startIndex, glyphs.size() - startIndex,
  69935. x, y, width, height, layout);
  69936. }
  69937. else if (maximumLines <= 1)
  69938. {
  69939. fitLineIntoSpace (startIndex, glyphs.size() - startIndex,
  69940. x, y, width, height, f, layout, minimumHorizontalScale);
  69941. }
  69942. else
  69943. {
  69944. Font font (f);
  69945. String txt (text.trim());
  69946. const int length = txt.length();
  69947. const int originalStartIndex = startIndex;
  69948. int numLines = 1;
  69949. if (length <= 12 && ! txt.containsAnyOf (" -\t\r\n"))
  69950. maximumLines = 1;
  69951. maximumLines = jmin (maximumLines, length);
  69952. while (numLines < maximumLines)
  69953. {
  69954. ++numLines;
  69955. const float newFontHeight = height / (float) numLines;
  69956. if (newFontHeight < font.getHeight())
  69957. {
  69958. font.setHeight (jmax (8.0f, newFontHeight));
  69959. removeRangeOfGlyphs (startIndex, -1);
  69960. addLineOfText (font, txt, x, y);
  69961. lineWidth = glyphs.getUnchecked (glyphs.size() - 1)->getRight()
  69962. - glyphs.getUnchecked (startIndex)->getLeft();
  69963. }
  69964. if (numLines > lineWidth / width || newFontHeight < 8.0f)
  69965. break;
  69966. }
  69967. if (numLines < 1)
  69968. numLines = 1;
  69969. float lineY = y;
  69970. float widthPerLine = lineWidth / numLines;
  69971. int lastLineStartIndex = 0;
  69972. for (int line = 0; line < numLines; ++line)
  69973. {
  69974. int i = startIndex;
  69975. lastLineStartIndex = i;
  69976. float lineStartX = glyphs.getUnchecked (startIndex)->getLeft();
  69977. if (line == numLines - 1)
  69978. {
  69979. widthPerLine = width;
  69980. i = glyphs.size();
  69981. }
  69982. else
  69983. {
  69984. while (i < glyphs.size())
  69985. {
  69986. lineWidth = (glyphs.getUnchecked (i)->getRight() - lineStartX);
  69987. if (lineWidth > widthPerLine)
  69988. {
  69989. // got to a point where the line's too long, so skip forward to find a
  69990. // good place to break it..
  69991. const int searchStartIndex = i;
  69992. while (i < glyphs.size())
  69993. {
  69994. if ((glyphs.getUnchecked (i)->getRight() - lineStartX) * minimumHorizontalScale < width)
  69995. {
  69996. if (glyphs.getUnchecked (i)->isWhitespace()
  69997. || glyphs.getUnchecked (i)->getCharacter() == '-')
  69998. {
  69999. ++i;
  70000. break;
  70001. }
  70002. }
  70003. else
  70004. {
  70005. // can't find a suitable break, so try looking backwards..
  70006. i = searchStartIndex;
  70007. for (int back = 1; back < jmin (5, i - startIndex - 1); ++back)
  70008. {
  70009. if (glyphs.getUnchecked (i - back)->isWhitespace()
  70010. || glyphs.getUnchecked (i - back)->getCharacter() == '-')
  70011. {
  70012. i -= back - 1;
  70013. break;
  70014. }
  70015. }
  70016. break;
  70017. }
  70018. ++i;
  70019. }
  70020. break;
  70021. }
  70022. ++i;
  70023. }
  70024. int wsStart = i;
  70025. while (wsStart > 0 && glyphs.getUnchecked (wsStart - 1)->isWhitespace())
  70026. --wsStart;
  70027. int wsEnd = i;
  70028. while (wsEnd < glyphs.size() && glyphs.getUnchecked (wsEnd)->isWhitespace())
  70029. ++wsEnd;
  70030. removeRangeOfGlyphs (wsStart, wsEnd - wsStart);
  70031. i = jmax (wsStart, startIndex + 1);
  70032. }
  70033. i -= fitLineIntoSpace (startIndex, i - startIndex,
  70034. x, lineY, width, font.getHeight(), font,
  70035. layout.getOnlyHorizontalFlags() | Justification::verticallyCentred,
  70036. minimumHorizontalScale);
  70037. startIndex = i;
  70038. lineY += font.getHeight();
  70039. if (startIndex >= glyphs.size())
  70040. break;
  70041. }
  70042. justifyGlyphs (originalStartIndex, glyphs.size() - originalStartIndex,
  70043. x, y, width, height, layout.getFlags() & ~Justification::horizontallyJustified);
  70044. }
  70045. }
  70046. }
  70047. void GlyphArrangement::moveRangeOfGlyphs (int startIndex, int num,
  70048. const float dx, const float dy)
  70049. {
  70050. jassert (startIndex >= 0);
  70051. if (dx != 0.0f || dy != 0.0f)
  70052. {
  70053. if (num < 0 || startIndex + num > glyphs.size())
  70054. num = glyphs.size() - startIndex;
  70055. while (--num >= 0)
  70056. glyphs.getUnchecked (startIndex++)->moveBy (dx, dy);
  70057. }
  70058. }
  70059. int GlyphArrangement::fitLineIntoSpace (int start, int numGlyphs, float x, float y, float w, float h, const Font& font,
  70060. const Justification& justification, float minimumHorizontalScale)
  70061. {
  70062. int numDeleted = 0;
  70063. const float lineStartX = glyphs.getUnchecked (start)->getLeft();
  70064. float lineWidth = glyphs.getUnchecked (start + numGlyphs - 1)->getRight() - lineStartX;
  70065. if (lineWidth > w)
  70066. {
  70067. if (minimumHorizontalScale < 1.0f)
  70068. {
  70069. stretchRangeOfGlyphs (start, numGlyphs, jmax (minimumHorizontalScale, w / lineWidth));
  70070. lineWidth = glyphs.getUnchecked (start + numGlyphs - 1)->getRight() - lineStartX - 0.5f;
  70071. }
  70072. if (lineWidth > w)
  70073. {
  70074. numDeleted = insertEllipsis (font, lineStartX + w, start, start + numGlyphs);
  70075. numGlyphs -= numDeleted;
  70076. }
  70077. }
  70078. justifyGlyphs (start, numGlyphs, x, y, w, h, justification);
  70079. return numDeleted;
  70080. }
  70081. void GlyphArrangement::stretchRangeOfGlyphs (int startIndex, int num,
  70082. const float horizontalScaleFactor)
  70083. {
  70084. jassert (startIndex >= 0);
  70085. if (num < 0 || startIndex + num > glyphs.size())
  70086. num = glyphs.size() - startIndex;
  70087. if (num > 0)
  70088. {
  70089. const float xAnchor = glyphs.getUnchecked (startIndex)->getLeft();
  70090. while (--num >= 0)
  70091. {
  70092. PositionedGlyph* const pg = glyphs.getUnchecked (startIndex++);
  70093. pg->x = xAnchor + (pg->x - xAnchor) * horizontalScaleFactor;
  70094. pg->font.setHorizontalScale (pg->font.getHorizontalScale() * horizontalScaleFactor);
  70095. pg->w *= horizontalScaleFactor;
  70096. }
  70097. }
  70098. }
  70099. const Rectangle<float> GlyphArrangement::getBoundingBox (int startIndex, int num, const bool includeWhitespace) const
  70100. {
  70101. jassert (startIndex >= 0);
  70102. if (num < 0 || startIndex + num > glyphs.size())
  70103. num = glyphs.size() - startIndex;
  70104. Rectangle<float> result;
  70105. bool isFirst = true;
  70106. while (--num >= 0)
  70107. {
  70108. const PositionedGlyph* const pg = glyphs.getUnchecked (startIndex++);
  70109. if (includeWhitespace || ! pg->isWhitespace())
  70110. {
  70111. if (isFirst)
  70112. {
  70113. isFirst = false;
  70114. result = pg->getBounds();
  70115. }
  70116. else
  70117. {
  70118. result = result.getUnion (pg->getBounds());
  70119. }
  70120. }
  70121. }
  70122. return result;
  70123. }
  70124. void GlyphArrangement::justifyGlyphs (const int startIndex, const int num,
  70125. const float x, const float y, const float width, const float height,
  70126. const Justification& justification)
  70127. {
  70128. jassert (num >= 0 && startIndex >= 0);
  70129. if (glyphs.size() > 0 && num > 0)
  70130. {
  70131. const Rectangle<float> bb (getBoundingBox (startIndex, num, ! justification.testFlags (Justification::horizontallyJustified
  70132. | Justification::horizontallyCentred)));
  70133. float deltaX = 0.0f;
  70134. if (justification.testFlags (Justification::horizontallyJustified))
  70135. deltaX = x - bb.getX();
  70136. else if (justification.testFlags (Justification::horizontallyCentred))
  70137. deltaX = x + (width - bb.getWidth()) * 0.5f - bb.getX();
  70138. else if (justification.testFlags (Justification::right))
  70139. deltaX = (x + width) - bb.getRight();
  70140. else
  70141. deltaX = x - bb.getX();
  70142. float deltaY = 0.0f;
  70143. if (justification.testFlags (Justification::top))
  70144. deltaY = y - bb.getY();
  70145. else if (justification.testFlags (Justification::bottom))
  70146. deltaY = (y + height) - bb.getBottom();
  70147. else
  70148. deltaY = y + (height - bb.getHeight()) * 0.5f - bb.getY();
  70149. moveRangeOfGlyphs (startIndex, num, deltaX, deltaY);
  70150. if (justification.testFlags (Justification::horizontallyJustified))
  70151. {
  70152. int lineStart = 0;
  70153. float baseY = glyphs.getUnchecked (startIndex)->getBaselineY();
  70154. int i;
  70155. for (i = 0; i < num; ++i)
  70156. {
  70157. const float glyphY = glyphs.getUnchecked (startIndex + i)->getBaselineY();
  70158. if (glyphY != baseY)
  70159. {
  70160. spreadOutLine (startIndex + lineStart, i - lineStart, width);
  70161. lineStart = i;
  70162. baseY = glyphY;
  70163. }
  70164. }
  70165. if (i > lineStart)
  70166. spreadOutLine (startIndex + lineStart, i - lineStart, width);
  70167. }
  70168. }
  70169. }
  70170. void GlyphArrangement::spreadOutLine (const int start, const int num, const float targetWidth)
  70171. {
  70172. if (start + num < glyphs.size()
  70173. && glyphs.getUnchecked (start + num - 1)->getCharacter() != '\r'
  70174. && glyphs.getUnchecked (start + num - 1)->getCharacter() != '\n')
  70175. {
  70176. int numSpaces = 0;
  70177. int spacesAtEnd = 0;
  70178. for (int i = 0; i < num; ++i)
  70179. {
  70180. if (glyphs.getUnchecked (start + i)->isWhitespace())
  70181. {
  70182. ++spacesAtEnd;
  70183. ++numSpaces;
  70184. }
  70185. else
  70186. {
  70187. spacesAtEnd = 0;
  70188. }
  70189. }
  70190. numSpaces -= spacesAtEnd;
  70191. if (numSpaces > 0)
  70192. {
  70193. const float startX = glyphs.getUnchecked (start)->getLeft();
  70194. const float endX = glyphs.getUnchecked (start + num - 1 - spacesAtEnd)->getRight();
  70195. const float extraPaddingBetweenWords
  70196. = (targetWidth - (endX - startX)) / (float) numSpaces;
  70197. float deltaX = 0.0f;
  70198. for (int i = 0; i < num; ++i)
  70199. {
  70200. glyphs.getUnchecked (start + i)->moveBy (deltaX, 0.0f);
  70201. if (glyphs.getUnchecked (start + i)->isWhitespace())
  70202. deltaX += extraPaddingBetweenWords;
  70203. }
  70204. }
  70205. }
  70206. }
  70207. void GlyphArrangement::draw (const Graphics& g) const
  70208. {
  70209. for (int i = 0; i < glyphs.size(); ++i)
  70210. {
  70211. const PositionedGlyph* const pg = glyphs.getUnchecked(i);
  70212. if (pg->font.isUnderlined())
  70213. {
  70214. const float lineThickness = (pg->font.getDescent()) * 0.3f;
  70215. float nextX = pg->x + pg->w;
  70216. if (i < glyphs.size() - 1 && glyphs.getUnchecked (i + 1)->y == pg->y)
  70217. nextX = glyphs.getUnchecked (i + 1)->x;
  70218. g.fillRect (pg->x, pg->y + lineThickness * 2.0f,
  70219. nextX - pg->x, lineThickness);
  70220. }
  70221. pg->draw (g);
  70222. }
  70223. }
  70224. void GlyphArrangement::draw (const Graphics& g, const AffineTransform& transform) const
  70225. {
  70226. for (int i = 0; i < glyphs.size(); ++i)
  70227. {
  70228. const PositionedGlyph* const pg = glyphs.getUnchecked(i);
  70229. if (pg->font.isUnderlined())
  70230. {
  70231. const float lineThickness = (pg->font.getDescent()) * 0.3f;
  70232. float nextX = pg->x + pg->w;
  70233. if (i < glyphs.size() - 1 && glyphs.getUnchecked (i + 1)->y == pg->y)
  70234. nextX = glyphs.getUnchecked (i + 1)->x;
  70235. Path p;
  70236. p.addLineSegment (pg->x, pg->y + lineThickness * 2.0f,
  70237. nextX, pg->y + lineThickness * 2.0f,
  70238. lineThickness);
  70239. g.fillPath (p, transform);
  70240. }
  70241. pg->draw (g, transform);
  70242. }
  70243. }
  70244. void GlyphArrangement::createPath (Path& path) const
  70245. {
  70246. for (int i = 0; i < glyphs.size(); ++i)
  70247. glyphs.getUnchecked (i)->createPath (path);
  70248. }
  70249. int GlyphArrangement::findGlyphIndexAt (float x, float y) const
  70250. {
  70251. for (int i = 0; i < glyphs.size(); ++i)
  70252. if (glyphs.getUnchecked (i)->hitTest (x, y))
  70253. return i;
  70254. return -1;
  70255. }
  70256. END_JUCE_NAMESPACE
  70257. /*** End of inlined file: juce_GlyphArrangement.cpp ***/
  70258. /*** Start of inlined file: juce_TextLayout.cpp ***/
  70259. BEGIN_JUCE_NAMESPACE
  70260. class TextLayout::Token
  70261. {
  70262. public:
  70263. String text;
  70264. Font font;
  70265. int x, y, w, h;
  70266. int line, lineHeight;
  70267. bool isWhitespace, isNewLine;
  70268. Token (const String& t,
  70269. const Font& f,
  70270. const bool isWhitespace_)
  70271. : text (t),
  70272. font (f),
  70273. x(0),
  70274. y(0),
  70275. isWhitespace (isWhitespace_)
  70276. {
  70277. w = font.getStringWidth (t);
  70278. h = roundToInt (f.getHeight());
  70279. isNewLine = t.containsChar ('\n') || t.containsChar ('\r');
  70280. }
  70281. Token (const Token& other)
  70282. : text (other.text),
  70283. font (other.font),
  70284. x (other.x),
  70285. y (other.y),
  70286. w (other.w),
  70287. h (other.h),
  70288. line (other.line),
  70289. lineHeight (other.lineHeight),
  70290. isWhitespace (other.isWhitespace),
  70291. isNewLine (other.isNewLine)
  70292. {
  70293. }
  70294. ~Token()
  70295. {
  70296. }
  70297. void draw (Graphics& g,
  70298. const int xOffset,
  70299. const int yOffset)
  70300. {
  70301. if (! isWhitespace)
  70302. {
  70303. g.setFont (font);
  70304. g.drawSingleLineText (text.trimEnd(),
  70305. xOffset + x,
  70306. yOffset + y + (lineHeight - h)
  70307. + roundToInt (font.getAscent()));
  70308. }
  70309. }
  70310. juce_UseDebuggingNewOperator
  70311. };
  70312. TextLayout::TextLayout()
  70313. : totalLines (0)
  70314. {
  70315. tokens.ensureStorageAllocated (64);
  70316. }
  70317. TextLayout::TextLayout (const String& text, const Font& font)
  70318. : totalLines (0)
  70319. {
  70320. tokens.ensureStorageAllocated (64);
  70321. appendText (text, font);
  70322. }
  70323. TextLayout::TextLayout (const TextLayout& other)
  70324. : totalLines (0)
  70325. {
  70326. *this = other;
  70327. }
  70328. TextLayout& TextLayout::operator= (const TextLayout& other)
  70329. {
  70330. if (this != &other)
  70331. {
  70332. clear();
  70333. totalLines = other.totalLines;
  70334. for (int i = 0; i < other.tokens.size(); ++i)
  70335. tokens.add (new Token (*other.tokens.getUnchecked(i)));
  70336. }
  70337. return *this;
  70338. }
  70339. TextLayout::~TextLayout()
  70340. {
  70341. clear();
  70342. }
  70343. void TextLayout::clear()
  70344. {
  70345. tokens.clear();
  70346. totalLines = 0;
  70347. }
  70348. void TextLayout::appendText (const String& text, const Font& font)
  70349. {
  70350. const juce_wchar* t = text;
  70351. String currentString;
  70352. int lastCharType = 0;
  70353. for (;;)
  70354. {
  70355. const juce_wchar c = *t++;
  70356. if (c == 0)
  70357. break;
  70358. int charType;
  70359. if (c == '\r' || c == '\n')
  70360. {
  70361. charType = 0;
  70362. }
  70363. else if (CharacterFunctions::isWhitespace (c))
  70364. {
  70365. charType = 2;
  70366. }
  70367. else
  70368. {
  70369. charType = 1;
  70370. }
  70371. if (charType == 0 || charType != lastCharType)
  70372. {
  70373. if (currentString.isNotEmpty())
  70374. {
  70375. tokens.add (new Token (currentString, font,
  70376. lastCharType == 2 || lastCharType == 0));
  70377. }
  70378. currentString = String::charToString (c);
  70379. if (c == '\r' && *t == '\n')
  70380. currentString += *t++;
  70381. }
  70382. else
  70383. {
  70384. currentString += c;
  70385. }
  70386. lastCharType = charType;
  70387. }
  70388. if (currentString.isNotEmpty())
  70389. tokens.add (new Token (currentString, font, lastCharType == 2));
  70390. }
  70391. void TextLayout::setText (const String& text, const Font& font)
  70392. {
  70393. clear();
  70394. appendText (text, font);
  70395. }
  70396. void TextLayout::layout (int maxWidth,
  70397. const Justification& justification,
  70398. const bool attemptToBalanceLineLengths)
  70399. {
  70400. if (attemptToBalanceLineLengths)
  70401. {
  70402. const int originalW = maxWidth;
  70403. int bestWidth = maxWidth;
  70404. float bestLineProportion = 0.0f;
  70405. while (maxWidth > originalW / 2)
  70406. {
  70407. layout (maxWidth, justification, false);
  70408. if (getNumLines() <= 1)
  70409. return;
  70410. const int lastLineW = getLineWidth (getNumLines() - 1);
  70411. const int lastButOneLineW = getLineWidth (getNumLines() - 2);
  70412. const float prop = lastLineW / (float) lastButOneLineW;
  70413. if (prop > 0.9f)
  70414. return;
  70415. if (prop > bestLineProportion)
  70416. {
  70417. bestLineProportion = prop;
  70418. bestWidth = maxWidth;
  70419. }
  70420. maxWidth -= 10;
  70421. }
  70422. layout (bestWidth, justification, false);
  70423. }
  70424. else
  70425. {
  70426. int x = 0;
  70427. int y = 0;
  70428. int h = 0;
  70429. totalLines = 0;
  70430. int i;
  70431. for (i = 0; i < tokens.size(); ++i)
  70432. {
  70433. Token* const t = tokens.getUnchecked(i);
  70434. t->x = x;
  70435. t->y = y;
  70436. t->line = totalLines;
  70437. x += t->w;
  70438. h = jmax (h, t->h);
  70439. const Token* nextTok = tokens [i + 1];
  70440. if (nextTok == 0)
  70441. break;
  70442. if (t->isNewLine || ((! nextTok->isWhitespace) && x + nextTok->w > maxWidth))
  70443. {
  70444. // finished a line, so go back and update the heights of the things on it
  70445. for (int j = i; j >= 0; --j)
  70446. {
  70447. Token* const tok = tokens.getUnchecked(j);
  70448. if (tok->line == totalLines)
  70449. tok->lineHeight = h;
  70450. else
  70451. break;
  70452. }
  70453. x = 0;
  70454. y += h;
  70455. h = 0;
  70456. ++totalLines;
  70457. }
  70458. }
  70459. // finished a line, so go back and update the heights of the things on it
  70460. for (int j = jmin (i, tokens.size() - 1); j >= 0; --j)
  70461. {
  70462. Token* const t = tokens.getUnchecked(j);
  70463. if (t->line == totalLines)
  70464. t->lineHeight = h;
  70465. else
  70466. break;
  70467. }
  70468. ++totalLines;
  70469. if (! justification.testFlags (Justification::left))
  70470. {
  70471. int totalW = getWidth();
  70472. for (i = totalLines; --i >= 0;)
  70473. {
  70474. const int lineW = getLineWidth (i);
  70475. int dx = 0;
  70476. if (justification.testFlags (Justification::horizontallyCentred))
  70477. dx = (totalW - lineW) / 2;
  70478. else if (justification.testFlags (Justification::right))
  70479. dx = totalW - lineW;
  70480. for (int j = tokens.size(); --j >= 0;)
  70481. {
  70482. Token* const t = tokens.getUnchecked(j);
  70483. if (t->line == i)
  70484. t->x += dx;
  70485. }
  70486. }
  70487. }
  70488. }
  70489. }
  70490. int TextLayout::getLineWidth (const int lineNumber) const
  70491. {
  70492. int maxW = 0;
  70493. for (int i = tokens.size(); --i >= 0;)
  70494. {
  70495. const Token* const t = tokens.getUnchecked(i);
  70496. if (t->line == lineNumber && ! t->isWhitespace)
  70497. maxW = jmax (maxW, t->x + t->w);
  70498. }
  70499. return maxW;
  70500. }
  70501. int TextLayout::getWidth() const
  70502. {
  70503. int maxW = 0;
  70504. for (int i = tokens.size(); --i >= 0;)
  70505. {
  70506. const Token* const t = tokens.getUnchecked(i);
  70507. if (! t->isWhitespace)
  70508. maxW = jmax (maxW, t->x + t->w);
  70509. }
  70510. return maxW;
  70511. }
  70512. int TextLayout::getHeight() const
  70513. {
  70514. int maxH = 0;
  70515. for (int i = tokens.size(); --i >= 0;)
  70516. {
  70517. const Token* const t = tokens.getUnchecked(i);
  70518. if (! t->isWhitespace)
  70519. maxH = jmax (maxH, t->y + t->h);
  70520. }
  70521. return maxH;
  70522. }
  70523. void TextLayout::draw (Graphics& g,
  70524. const int xOffset,
  70525. const int yOffset) const
  70526. {
  70527. for (int i = tokens.size(); --i >= 0;)
  70528. tokens.getUnchecked(i)->draw (g, xOffset, yOffset);
  70529. }
  70530. void TextLayout::drawWithin (Graphics& g,
  70531. int x, int y, int w, int h,
  70532. const Justification& justification) const
  70533. {
  70534. justification.applyToRectangle (x, y, getWidth(), getHeight(),
  70535. x, y, w, h);
  70536. draw (g, x, y);
  70537. }
  70538. END_JUCE_NAMESPACE
  70539. /*** End of inlined file: juce_TextLayout.cpp ***/
  70540. /*** Start of inlined file: juce_Typeface.cpp ***/
  70541. BEGIN_JUCE_NAMESPACE
  70542. Typeface::Typeface (const String& name_) throw()
  70543. : name (name_)
  70544. {
  70545. }
  70546. Typeface::~Typeface()
  70547. {
  70548. }
  70549. class CustomTypeface::GlyphInfo
  70550. {
  70551. public:
  70552. GlyphInfo (const juce_wchar character_, const Path& path_, const float width_) throw()
  70553. : character (character_), path (path_), width (width_)
  70554. {
  70555. }
  70556. ~GlyphInfo() throw()
  70557. {
  70558. }
  70559. struct KerningPair
  70560. {
  70561. juce_wchar character2;
  70562. float kerningAmount;
  70563. };
  70564. void addKerningPair (const juce_wchar subsequentCharacter,
  70565. const float extraKerningAmount) throw()
  70566. {
  70567. KerningPair kp;
  70568. kp.character2 = subsequentCharacter;
  70569. kp.kerningAmount = extraKerningAmount;
  70570. kerningPairs.add (kp);
  70571. }
  70572. float getHorizontalSpacing (const juce_wchar subsequentCharacter) const throw()
  70573. {
  70574. if (subsequentCharacter != 0)
  70575. {
  70576. for (int i = kerningPairs.size(); --i >= 0;)
  70577. if (kerningPairs.getReference(i).character2 == subsequentCharacter)
  70578. return width + kerningPairs.getReference(i).kerningAmount;
  70579. }
  70580. return width;
  70581. }
  70582. const juce_wchar character;
  70583. const Path path;
  70584. float width;
  70585. Array <KerningPair> kerningPairs;
  70586. juce_UseDebuggingNewOperator
  70587. private:
  70588. GlyphInfo (const GlyphInfo&);
  70589. GlyphInfo& operator= (const GlyphInfo&);
  70590. };
  70591. CustomTypeface::CustomTypeface()
  70592. : Typeface (String::empty)
  70593. {
  70594. clear();
  70595. }
  70596. CustomTypeface::CustomTypeface (InputStream& serialisedTypefaceStream)
  70597. : Typeface (String::empty)
  70598. {
  70599. clear();
  70600. GZIPDecompressorInputStream gzin (&serialisedTypefaceStream, false);
  70601. BufferedInputStream in (&gzin, 32768, false);
  70602. name = in.readString();
  70603. isBold = in.readBool();
  70604. isItalic = in.readBool();
  70605. ascent = in.readFloat();
  70606. defaultCharacter = (juce_wchar) in.readShort();
  70607. int i, numChars = in.readInt();
  70608. for (i = 0; i < numChars; ++i)
  70609. {
  70610. const juce_wchar c = (juce_wchar) in.readShort();
  70611. const float width = in.readFloat();
  70612. Path p;
  70613. p.loadPathFromStream (in);
  70614. addGlyph (c, p, width);
  70615. }
  70616. const int numKerningPairs = in.readInt();
  70617. for (i = 0; i < numKerningPairs; ++i)
  70618. {
  70619. const juce_wchar char1 = (juce_wchar) in.readShort();
  70620. const juce_wchar char2 = (juce_wchar) in.readShort();
  70621. addKerningPair (char1, char2, in.readFloat());
  70622. }
  70623. }
  70624. CustomTypeface::~CustomTypeface()
  70625. {
  70626. }
  70627. void CustomTypeface::clear()
  70628. {
  70629. defaultCharacter = 0;
  70630. ascent = 1.0f;
  70631. isBold = isItalic = false;
  70632. zeromem (lookupTable, sizeof (lookupTable));
  70633. glyphs.clear();
  70634. }
  70635. void CustomTypeface::setCharacteristics (const String& name_, const float ascent_, const bool isBold_,
  70636. const bool isItalic_, const juce_wchar defaultCharacter_) throw()
  70637. {
  70638. name = name_;
  70639. defaultCharacter = defaultCharacter_;
  70640. ascent = ascent_;
  70641. isBold = isBold_;
  70642. isItalic = isItalic_;
  70643. }
  70644. void CustomTypeface::addGlyph (const juce_wchar character, const Path& path, const float width) throw()
  70645. {
  70646. // Check that you're not trying to add the same character twice..
  70647. jassert (findGlyph (character, false) == 0);
  70648. if (((unsigned int) character) < (unsigned int) numElementsInArray (lookupTable))
  70649. lookupTable [character] = (short) glyphs.size();
  70650. glyphs.add (new GlyphInfo (character, path, width));
  70651. }
  70652. void CustomTypeface::addKerningPair (const juce_wchar char1, const juce_wchar char2, const float extraAmount) throw()
  70653. {
  70654. if (extraAmount != 0)
  70655. {
  70656. GlyphInfo* const g = findGlyph (char1, true);
  70657. jassert (g != 0); // can only add kerning pairs for characters that exist!
  70658. if (g != 0)
  70659. g->addKerningPair (char2, extraAmount);
  70660. }
  70661. }
  70662. CustomTypeface::GlyphInfo* CustomTypeface::findGlyph (const juce_wchar character, const bool loadIfNeeded) throw()
  70663. {
  70664. if (((unsigned int) character) < (unsigned int) numElementsInArray (lookupTable) && lookupTable [character] > 0)
  70665. return glyphs [(int) lookupTable [(int) character]];
  70666. for (int i = 0; i < glyphs.size(); ++i)
  70667. {
  70668. GlyphInfo* const g = glyphs.getUnchecked(i);
  70669. if (g->character == character)
  70670. return g;
  70671. }
  70672. if (loadIfNeeded && loadGlyphIfPossible (character))
  70673. return findGlyph (character, false);
  70674. return 0;
  70675. }
  70676. CustomTypeface::GlyphInfo* CustomTypeface::findGlyphSubstituting (const juce_wchar character) throw()
  70677. {
  70678. GlyphInfo* glyph = findGlyph (character, true);
  70679. if (glyph == 0)
  70680. {
  70681. if (CharacterFunctions::isWhitespace (character) && character != L' ')
  70682. glyph = findGlyph (L' ', true);
  70683. if (glyph == 0)
  70684. {
  70685. const Font fallbackFont (Font::getFallbackFontName(), 10, 0);
  70686. Typeface* const fallbackTypeface = fallbackFont.getTypeface();
  70687. if (fallbackTypeface != 0 && fallbackTypeface != this)
  70688. {
  70689. //xxx
  70690. }
  70691. if (glyph == 0)
  70692. glyph = findGlyph (defaultCharacter, true);
  70693. }
  70694. }
  70695. return glyph;
  70696. }
  70697. bool CustomTypeface::loadGlyphIfPossible (const juce_wchar /*characterNeeded*/)
  70698. {
  70699. return false;
  70700. }
  70701. void CustomTypeface::addGlyphsFromOtherTypeface (Typeface& typefaceToCopy, juce_wchar characterStartIndex, int numCharacters) throw()
  70702. {
  70703. setCharacteristics (name, typefaceToCopy.getAscent(), isBold, isItalic, defaultCharacter);
  70704. for (int i = 0; i < numCharacters; ++i)
  70705. {
  70706. const juce_wchar c = (juce_wchar) (characterStartIndex + i);
  70707. Array <int> glyphIndexes;
  70708. Array <float> offsets;
  70709. typefaceToCopy.getGlyphPositions (String::charToString (c), glyphIndexes, offsets);
  70710. const int glyphIndex = glyphIndexes.getFirst();
  70711. if (glyphIndex >= 0 && glyphIndexes.size() > 0)
  70712. {
  70713. const float glyphWidth = offsets[1];
  70714. Path p;
  70715. typefaceToCopy.getOutlineForGlyph (glyphIndex, p);
  70716. addGlyph (c, p, glyphWidth);
  70717. for (int j = glyphs.size() - 1; --j >= 0;)
  70718. {
  70719. const juce_wchar char2 = glyphs.getUnchecked (j)->character;
  70720. glyphIndexes.clearQuick();
  70721. offsets.clearQuick();
  70722. typefaceToCopy.getGlyphPositions (String::charToString (c) + String::charToString (char2), glyphIndexes, offsets);
  70723. if (offsets.size() > 1)
  70724. addKerningPair (c, char2, offsets[1] - glyphWidth);
  70725. }
  70726. }
  70727. }
  70728. }
  70729. bool CustomTypeface::writeToStream (OutputStream& outputStream)
  70730. {
  70731. GZIPCompressorOutputStream out (&outputStream);
  70732. out.writeString (name);
  70733. out.writeBool (isBold);
  70734. out.writeBool (isItalic);
  70735. out.writeFloat (ascent);
  70736. out.writeShort ((short) (unsigned short) defaultCharacter);
  70737. out.writeInt (glyphs.size());
  70738. int i, numKerningPairs = 0;
  70739. for (i = 0; i < glyphs.size(); ++i)
  70740. {
  70741. const GlyphInfo* const g = glyphs.getUnchecked (i);
  70742. out.writeShort ((short) (unsigned short) g->character);
  70743. out.writeFloat (g->width);
  70744. g->path.writePathToStream (out);
  70745. numKerningPairs += g->kerningPairs.size();
  70746. }
  70747. out.writeInt (numKerningPairs);
  70748. for (i = 0; i < glyphs.size(); ++i)
  70749. {
  70750. const GlyphInfo* const g = glyphs.getUnchecked (i);
  70751. for (int j = 0; j < g->kerningPairs.size(); ++j)
  70752. {
  70753. const GlyphInfo::KerningPair& p = g->kerningPairs.getReference (j);
  70754. out.writeShort ((short) (unsigned short) g->character);
  70755. out.writeShort ((short) (unsigned short) p.character2);
  70756. out.writeFloat (p.kerningAmount);
  70757. }
  70758. }
  70759. return true;
  70760. }
  70761. float CustomTypeface::getAscent() const
  70762. {
  70763. return ascent;
  70764. }
  70765. float CustomTypeface::getDescent() const
  70766. {
  70767. return 1.0f - ascent;
  70768. }
  70769. float CustomTypeface::getStringWidth (const String& text)
  70770. {
  70771. float x = 0;
  70772. const juce_wchar* t = text;
  70773. while (*t != 0)
  70774. {
  70775. const GlyphInfo* const glyph = findGlyphSubstituting (*t++);
  70776. if (glyph != 0)
  70777. x += glyph->getHorizontalSpacing (*t);
  70778. }
  70779. return x;
  70780. }
  70781. void CustomTypeface::getGlyphPositions (const String& text, Array <int>& resultGlyphs, Array<float>& xOffsets)
  70782. {
  70783. xOffsets.add (0);
  70784. float x = 0;
  70785. const juce_wchar* t = text;
  70786. while (*t != 0)
  70787. {
  70788. const juce_wchar c = *t++;
  70789. const GlyphInfo* const glyph = findGlyphSubstituting (c);
  70790. if (glyph != 0)
  70791. {
  70792. x += glyph->getHorizontalSpacing (*t);
  70793. resultGlyphs.add ((int) glyph->character);
  70794. xOffsets.add (x);
  70795. }
  70796. }
  70797. }
  70798. bool CustomTypeface::getOutlineForGlyph (int glyphNumber, Path& path)
  70799. {
  70800. const GlyphInfo* const glyph = findGlyphSubstituting ((juce_wchar) glyphNumber);
  70801. if (glyph != 0)
  70802. {
  70803. path = glyph->path;
  70804. return true;
  70805. }
  70806. return false;
  70807. }
  70808. END_JUCE_NAMESPACE
  70809. /*** End of inlined file: juce_Typeface.cpp ***/
  70810. /*** Start of inlined file: juce_AffineTransform.cpp ***/
  70811. BEGIN_JUCE_NAMESPACE
  70812. AffineTransform::AffineTransform() throw()
  70813. : mat00 (1.0f),
  70814. mat01 (0),
  70815. mat02 (0),
  70816. mat10 (0),
  70817. mat11 (1.0f),
  70818. mat12 (0)
  70819. {
  70820. }
  70821. AffineTransform::AffineTransform (const AffineTransform& other) throw()
  70822. : mat00 (other.mat00),
  70823. mat01 (other.mat01),
  70824. mat02 (other.mat02),
  70825. mat10 (other.mat10),
  70826. mat11 (other.mat11),
  70827. mat12 (other.mat12)
  70828. {
  70829. }
  70830. AffineTransform::AffineTransform (const float mat00_,
  70831. const float mat01_,
  70832. const float mat02_,
  70833. const float mat10_,
  70834. const float mat11_,
  70835. const float mat12_) throw()
  70836. : mat00 (mat00_),
  70837. mat01 (mat01_),
  70838. mat02 (mat02_),
  70839. mat10 (mat10_),
  70840. mat11 (mat11_),
  70841. mat12 (mat12_)
  70842. {
  70843. }
  70844. AffineTransform& AffineTransform::operator= (const AffineTransform& other) throw()
  70845. {
  70846. mat00 = other.mat00;
  70847. mat01 = other.mat01;
  70848. mat02 = other.mat02;
  70849. mat10 = other.mat10;
  70850. mat11 = other.mat11;
  70851. mat12 = other.mat12;
  70852. return *this;
  70853. }
  70854. bool AffineTransform::operator== (const AffineTransform& other) const throw()
  70855. {
  70856. return mat00 == other.mat00
  70857. && mat01 == other.mat01
  70858. && mat02 == other.mat02
  70859. && mat10 == other.mat10
  70860. && mat11 == other.mat11
  70861. && mat12 == other.mat12;
  70862. }
  70863. bool AffineTransform::operator!= (const AffineTransform& other) const throw()
  70864. {
  70865. return ! operator== (other);
  70866. }
  70867. bool AffineTransform::isIdentity() const throw()
  70868. {
  70869. return (mat01 == 0)
  70870. && (mat02 == 0)
  70871. && (mat10 == 0)
  70872. && (mat12 == 0)
  70873. && (mat00 == 1.0f)
  70874. && (mat11 == 1.0f);
  70875. }
  70876. const AffineTransform AffineTransform::identity;
  70877. const AffineTransform AffineTransform::followedBy (const AffineTransform& other) const throw()
  70878. {
  70879. return AffineTransform (other.mat00 * mat00 + other.mat01 * mat10,
  70880. other.mat00 * mat01 + other.mat01 * mat11,
  70881. other.mat00 * mat02 + other.mat01 * mat12 + other.mat02,
  70882. other.mat10 * mat00 + other.mat11 * mat10,
  70883. other.mat10 * mat01 + other.mat11 * mat11,
  70884. other.mat10 * mat02 + other.mat11 * mat12 + other.mat12);
  70885. }
  70886. const AffineTransform AffineTransform::followedBy (const float omat00,
  70887. const float omat01,
  70888. const float omat02,
  70889. const float omat10,
  70890. const float omat11,
  70891. const float omat12) const throw()
  70892. {
  70893. return AffineTransform (omat00 * mat00 + omat01 * mat10,
  70894. omat00 * mat01 + omat01 * mat11,
  70895. omat00 * mat02 + omat01 * mat12 + omat02,
  70896. omat10 * mat00 + omat11 * mat10,
  70897. omat10 * mat01 + omat11 * mat11,
  70898. omat10 * mat02 + omat11 * mat12 + omat12);
  70899. }
  70900. const AffineTransform AffineTransform::translated (const float dx,
  70901. const float dy) const throw()
  70902. {
  70903. return AffineTransform (mat00, mat01, mat02 + dx,
  70904. mat10, mat11, mat12 + dy);
  70905. }
  70906. const AffineTransform AffineTransform::translation (const float dx,
  70907. const float dy) throw()
  70908. {
  70909. return AffineTransform (1.0f, 0, dx,
  70910. 0, 1.0f, dy);
  70911. }
  70912. const AffineTransform AffineTransform::rotated (const float rad) const throw()
  70913. {
  70914. const float cosRad = std::cos (rad);
  70915. const float sinRad = std::sin (rad);
  70916. return followedBy (cosRad, -sinRad, 0,
  70917. sinRad, cosRad, 0);
  70918. }
  70919. const AffineTransform AffineTransform::rotation (const float rad) throw()
  70920. {
  70921. const float cosRad = std::cos (rad);
  70922. const float sinRad = std::sin (rad);
  70923. return AffineTransform (cosRad, -sinRad, 0,
  70924. sinRad, cosRad, 0);
  70925. }
  70926. const AffineTransform AffineTransform::rotated (const float angle,
  70927. const float pivotX,
  70928. const float pivotY) const throw()
  70929. {
  70930. return translated (-pivotX, -pivotY)
  70931. .rotated (angle)
  70932. .translated (pivotX, pivotY);
  70933. }
  70934. const AffineTransform AffineTransform::rotation (const float angle,
  70935. const float pivotX,
  70936. const float pivotY) throw()
  70937. {
  70938. return translation (-pivotX, -pivotY)
  70939. .rotated (angle)
  70940. .translated (pivotX, pivotY);
  70941. }
  70942. const AffineTransform AffineTransform::scaled (const float factorX,
  70943. const float factorY) const throw()
  70944. {
  70945. return AffineTransform (factorX * mat00, factorX * mat01, factorX * mat02,
  70946. factorY * mat10, factorY * mat11, factorY * mat12);
  70947. }
  70948. const AffineTransform AffineTransform::scale (const float factorX,
  70949. const float factorY) throw()
  70950. {
  70951. return AffineTransform (factorX, 0, 0,
  70952. 0, factorY, 0);
  70953. }
  70954. const AffineTransform AffineTransform::sheared (const float shearX,
  70955. const float shearY) const throw()
  70956. {
  70957. return followedBy (1.0f, shearX, 0,
  70958. shearY, 1.0f, 0);
  70959. }
  70960. const AffineTransform AffineTransform::inverted() const throw()
  70961. {
  70962. double determinant = (mat00 * mat11 - mat10 * mat01);
  70963. if (determinant != 0.0)
  70964. {
  70965. determinant = 1.0 / determinant;
  70966. const float dst00 = (float) (mat11 * determinant);
  70967. const float dst10 = (float) (-mat10 * determinant);
  70968. const float dst01 = (float) (-mat01 * determinant);
  70969. const float dst11 = (float) (mat00 * determinant);
  70970. return AffineTransform (dst00, dst01, -mat02 * dst00 - mat12 * dst01,
  70971. dst10, dst11, -mat02 * dst10 - mat12 * dst11);
  70972. }
  70973. else
  70974. {
  70975. // singularity..
  70976. return *this;
  70977. }
  70978. }
  70979. bool AffineTransform::isSingularity() const throw()
  70980. {
  70981. return (mat00 * mat11 - mat10 * mat01) == 0.0;
  70982. }
  70983. bool AffineTransform::isOnlyTranslation() const throw()
  70984. {
  70985. return (mat01 == 0)
  70986. && (mat10 == 0)
  70987. && (mat00 == 1.0f)
  70988. && (mat11 == 1.0f);
  70989. }
  70990. void AffineTransform::transformPoint (float& x,
  70991. float& y) const throw()
  70992. {
  70993. const float oldX = x;
  70994. x = mat00 * oldX + mat01 * y + mat02;
  70995. y = mat10 * oldX + mat11 * y + mat12;
  70996. }
  70997. void AffineTransform::transformPoint (double& x,
  70998. double& y) const throw()
  70999. {
  71000. const double oldX = x;
  71001. x = mat00 * oldX + mat01 * y + mat02;
  71002. y = mat10 * oldX + mat11 * y + mat12;
  71003. }
  71004. END_JUCE_NAMESPACE
  71005. /*** End of inlined file: juce_AffineTransform.cpp ***/
  71006. /*** Start of inlined file: juce_BorderSize.cpp ***/
  71007. BEGIN_JUCE_NAMESPACE
  71008. BorderSize::BorderSize() throw()
  71009. : top (0),
  71010. left (0),
  71011. bottom (0),
  71012. right (0)
  71013. {
  71014. }
  71015. BorderSize::BorderSize (const BorderSize& other) throw()
  71016. : top (other.top),
  71017. left (other.left),
  71018. bottom (other.bottom),
  71019. right (other.right)
  71020. {
  71021. }
  71022. BorderSize::BorderSize (const int topGap,
  71023. const int leftGap,
  71024. const int bottomGap,
  71025. const int rightGap) throw()
  71026. : top (topGap),
  71027. left (leftGap),
  71028. bottom (bottomGap),
  71029. right (rightGap)
  71030. {
  71031. }
  71032. BorderSize::BorderSize (const int allGaps) throw()
  71033. : top (allGaps),
  71034. left (allGaps),
  71035. bottom (allGaps),
  71036. right (allGaps)
  71037. {
  71038. }
  71039. BorderSize::~BorderSize() throw()
  71040. {
  71041. }
  71042. void BorderSize::setTop (const int newTopGap) throw()
  71043. {
  71044. top = newTopGap;
  71045. }
  71046. void BorderSize::setLeft (const int newLeftGap) throw()
  71047. {
  71048. left = newLeftGap;
  71049. }
  71050. void BorderSize::setBottom (const int newBottomGap) throw()
  71051. {
  71052. bottom = newBottomGap;
  71053. }
  71054. void BorderSize::setRight (const int newRightGap) throw()
  71055. {
  71056. right = newRightGap;
  71057. }
  71058. const Rectangle<int> BorderSize::subtractedFrom (const Rectangle<int>& r) const throw()
  71059. {
  71060. return Rectangle<int> (r.getX() + left,
  71061. r.getY() + top,
  71062. r.getWidth() - (left + right),
  71063. r.getHeight() - (top + bottom));
  71064. }
  71065. void BorderSize::subtractFrom (Rectangle<int>& r) const throw()
  71066. {
  71067. r.setBounds (r.getX() + left,
  71068. r.getY() + top,
  71069. r.getWidth() - (left + right),
  71070. r.getHeight() - (top + bottom));
  71071. }
  71072. const Rectangle<int> BorderSize::addedTo (const Rectangle<int>& r) const throw()
  71073. {
  71074. return Rectangle<int> (r.getX() - left,
  71075. r.getY() - top,
  71076. r.getWidth() + (left + right),
  71077. r.getHeight() + (top + bottom));
  71078. }
  71079. void BorderSize::addTo (Rectangle<int>& r) const throw()
  71080. {
  71081. r.setBounds (r.getX() - left,
  71082. r.getY() - top,
  71083. r.getWidth() + (left + right),
  71084. r.getHeight() + (top + bottom));
  71085. }
  71086. bool BorderSize::operator== (const BorderSize& other) const throw()
  71087. {
  71088. return top == other.top
  71089. && left == other.left
  71090. && bottom == other.bottom
  71091. && right == other.right;
  71092. }
  71093. bool BorderSize::operator!= (const BorderSize& other) const throw()
  71094. {
  71095. return ! operator== (other);
  71096. }
  71097. END_JUCE_NAMESPACE
  71098. /*** End of inlined file: juce_BorderSize.cpp ***/
  71099. /*** Start of inlined file: juce_Line.cpp ***/
  71100. BEGIN_JUCE_NAMESPACE
  71101. END_JUCE_NAMESPACE
  71102. /*** End of inlined file: juce_Line.cpp ***/
  71103. /*** Start of inlined file: juce_Path.cpp ***/
  71104. BEGIN_JUCE_NAMESPACE
  71105. // tests that some co-ords aren't NaNs
  71106. #define CHECK_COORDS_ARE_VALID(x, y) \
  71107. jassert (x == x && y == y);
  71108. namespace PathHelpers
  71109. {
  71110. static const float ellipseAngularIncrement = 0.05f;
  71111. static void perpendicularOffset (const float x1, const float y1,
  71112. const float x2, const float y2,
  71113. const float offsetX, const float offsetY,
  71114. float& resultX, float& resultY) throw()
  71115. {
  71116. const float dx = x2 - x1;
  71117. const float dy = y2 - y1;
  71118. const float len = juce_hypotf (dx, dy);
  71119. if (len == 0)
  71120. {
  71121. resultX = x1;
  71122. resultY = y1;
  71123. }
  71124. else
  71125. {
  71126. resultX = x1 + ((dx * offsetX) - (dy * offsetY)) / len;
  71127. resultY = y1 + ((dy * offsetX) + (dx * offsetY)) / len;
  71128. }
  71129. }
  71130. static const String nextToken (const juce_wchar*& t)
  71131. {
  71132. while (CharacterFunctions::isWhitespace (*t))
  71133. ++t;
  71134. const juce_wchar* const start = t;
  71135. while (*t != 0 && ! CharacterFunctions::isWhitespace (*t))
  71136. ++t;
  71137. const int length = (int) (t - start);
  71138. while (CharacterFunctions::isWhitespace (*t))
  71139. ++t;
  71140. return String (start, length);
  71141. }
  71142. }
  71143. const float Path::lineMarker = 100001.0f;
  71144. const float Path::moveMarker = 100002.0f;
  71145. const float Path::quadMarker = 100003.0f;
  71146. const float Path::cubicMarker = 100004.0f;
  71147. const float Path::closeSubPathMarker = 100005.0f;
  71148. Path::Path()
  71149. : numElements (0),
  71150. pathXMin (0),
  71151. pathXMax (0),
  71152. pathYMin (0),
  71153. pathYMax (0),
  71154. useNonZeroWinding (true)
  71155. {
  71156. }
  71157. Path::~Path()
  71158. {
  71159. }
  71160. Path::Path (const Path& other)
  71161. : numElements (other.numElements),
  71162. pathXMin (other.pathXMin),
  71163. pathXMax (other.pathXMax),
  71164. pathYMin (other.pathYMin),
  71165. pathYMax (other.pathYMax),
  71166. useNonZeroWinding (other.useNonZeroWinding)
  71167. {
  71168. if (numElements > 0)
  71169. {
  71170. data.setAllocatedSize ((int) numElements);
  71171. memcpy (data.elements, other.data.elements, numElements * sizeof (float));
  71172. }
  71173. }
  71174. Path& Path::operator= (const Path& other)
  71175. {
  71176. if (this != &other)
  71177. {
  71178. data.ensureAllocatedSize ((int) other.numElements);
  71179. numElements = other.numElements;
  71180. pathXMin = other.pathXMin;
  71181. pathXMax = other.pathXMax;
  71182. pathYMin = other.pathYMin;
  71183. pathYMax = other.pathYMax;
  71184. useNonZeroWinding = other.useNonZeroWinding;
  71185. if (numElements > 0)
  71186. memcpy (data.elements, other.data.elements, numElements * sizeof (float));
  71187. }
  71188. return *this;
  71189. }
  71190. void Path::clear() throw()
  71191. {
  71192. numElements = 0;
  71193. pathXMin = 0;
  71194. pathYMin = 0;
  71195. pathYMax = 0;
  71196. pathXMax = 0;
  71197. }
  71198. void Path::swapWithPath (Path& other)
  71199. {
  71200. data.swapWith (other.data);
  71201. swapVariables <size_t> (numElements, other.numElements);
  71202. swapVariables <float> (pathXMin, other.pathXMin);
  71203. swapVariables <float> (pathXMax, other.pathXMax);
  71204. swapVariables <float> (pathYMin, other.pathYMin);
  71205. swapVariables <float> (pathYMax, other.pathYMax);
  71206. swapVariables <bool> (useNonZeroWinding, other.useNonZeroWinding);
  71207. }
  71208. void Path::setUsingNonZeroWinding (const bool isNonZero) throw()
  71209. {
  71210. useNonZeroWinding = isNonZero;
  71211. }
  71212. void Path::scaleToFit (const float x, const float y, const float w, const float h,
  71213. const bool preserveProportions) throw()
  71214. {
  71215. applyTransform (getTransformToScaleToFit (x, y, w, h, preserveProportions));
  71216. }
  71217. bool Path::isEmpty() const throw()
  71218. {
  71219. size_t i = 0;
  71220. while (i < numElements)
  71221. {
  71222. const float type = data.elements [i++];
  71223. if (type == moveMarker)
  71224. {
  71225. i += 2;
  71226. }
  71227. else if (type == lineMarker
  71228. || type == quadMarker
  71229. || type == cubicMarker)
  71230. {
  71231. return false;
  71232. }
  71233. }
  71234. return true;
  71235. }
  71236. const Rectangle<float> Path::getBounds() const throw()
  71237. {
  71238. return Rectangle<float> (pathXMin, pathYMin,
  71239. pathXMax - pathXMin,
  71240. pathYMax - pathYMin);
  71241. }
  71242. const Rectangle<float> Path::getBoundsTransformed (const AffineTransform& transform) const throw()
  71243. {
  71244. return getBounds().transformed (transform);
  71245. }
  71246. void Path::startNewSubPath (const float x, const float y)
  71247. {
  71248. CHECK_COORDS_ARE_VALID (x, y);
  71249. if (numElements == 0)
  71250. {
  71251. pathXMin = pathXMax = x;
  71252. pathYMin = pathYMax = y;
  71253. }
  71254. else
  71255. {
  71256. pathXMin = jmin (pathXMin, x);
  71257. pathXMax = jmax (pathXMax, x);
  71258. pathYMin = jmin (pathYMin, y);
  71259. pathYMax = jmax (pathYMax, y);
  71260. }
  71261. data.ensureAllocatedSize ((int) numElements + 3);
  71262. data.elements [numElements++] = moveMarker;
  71263. data.elements [numElements++] = x;
  71264. data.elements [numElements++] = y;
  71265. }
  71266. void Path::lineTo (const float x, const float y)
  71267. {
  71268. CHECK_COORDS_ARE_VALID (x, y);
  71269. if (numElements == 0)
  71270. startNewSubPath (0, 0);
  71271. data.ensureAllocatedSize ((int) numElements + 3);
  71272. data.elements [numElements++] = lineMarker;
  71273. data.elements [numElements++] = x;
  71274. data.elements [numElements++] = y;
  71275. pathXMin = jmin (pathXMin, x);
  71276. pathXMax = jmax (pathXMax, x);
  71277. pathYMin = jmin (pathYMin, y);
  71278. pathYMax = jmax (pathYMax, y);
  71279. }
  71280. void Path::quadraticTo (const float x1, const float y1,
  71281. const float x2, const float y2)
  71282. {
  71283. CHECK_COORDS_ARE_VALID (x1, y1);
  71284. CHECK_COORDS_ARE_VALID (x2, y2);
  71285. if (numElements == 0)
  71286. startNewSubPath (0, 0);
  71287. data.ensureAllocatedSize ((int) numElements + 5);
  71288. data.elements [numElements++] = quadMarker;
  71289. data.elements [numElements++] = x1;
  71290. data.elements [numElements++] = y1;
  71291. data.elements [numElements++] = x2;
  71292. data.elements [numElements++] = y2;
  71293. pathXMin = jmin (pathXMin, x1, x2);
  71294. pathXMax = jmax (pathXMax, x1, x2);
  71295. pathYMin = jmin (pathYMin, y1, y2);
  71296. pathYMax = jmax (pathYMax, y1, y2);
  71297. }
  71298. void Path::cubicTo (const float x1, const float y1,
  71299. const float x2, const float y2,
  71300. const float x3, const float y3)
  71301. {
  71302. CHECK_COORDS_ARE_VALID (x1, y1);
  71303. CHECK_COORDS_ARE_VALID (x2, y2);
  71304. CHECK_COORDS_ARE_VALID (x3, y3);
  71305. if (numElements == 0)
  71306. startNewSubPath (0, 0);
  71307. data.ensureAllocatedSize ((int) numElements + 7);
  71308. data.elements [numElements++] = cubicMarker;
  71309. data.elements [numElements++] = x1;
  71310. data.elements [numElements++] = y1;
  71311. data.elements [numElements++] = x2;
  71312. data.elements [numElements++] = y2;
  71313. data.elements [numElements++] = x3;
  71314. data.elements [numElements++] = y3;
  71315. pathXMin = jmin (pathXMin, x1, x2, x3);
  71316. pathXMax = jmax (pathXMax, x1, x2, x3);
  71317. pathYMin = jmin (pathYMin, y1, y2, y3);
  71318. pathYMax = jmax (pathYMax, y1, y2, y3);
  71319. }
  71320. void Path::closeSubPath()
  71321. {
  71322. if (numElements > 0
  71323. && data.elements [numElements - 1] != closeSubPathMarker)
  71324. {
  71325. data.ensureAllocatedSize ((int) numElements + 1);
  71326. data.elements [numElements++] = closeSubPathMarker;
  71327. }
  71328. }
  71329. const Point<float> Path::getCurrentPosition() const
  71330. {
  71331. size_t i = numElements - 1;
  71332. if (i > 0 && data.elements[i] == closeSubPathMarker)
  71333. {
  71334. while (i >= 0)
  71335. {
  71336. if (data.elements[i] == moveMarker)
  71337. {
  71338. i += 2;
  71339. break;
  71340. }
  71341. --i;
  71342. }
  71343. }
  71344. if (i > 0)
  71345. return Point<float> (data.elements [i - 1], data.elements [i]);
  71346. return Point<float>();
  71347. }
  71348. void Path::addRectangle (const float x, const float y,
  71349. const float w, const float h)
  71350. {
  71351. float x1 = x, y1 = y, x2 = x + w, y2 = y + h;
  71352. if (w < 0)
  71353. swapVariables (x1, x2);
  71354. if (h < 0)
  71355. swapVariables (y1, y2);
  71356. data.ensureAllocatedSize ((int) numElements + 13);
  71357. if (numElements == 0)
  71358. {
  71359. pathXMin = x1;
  71360. pathXMax = x2;
  71361. pathYMin = y1;
  71362. pathYMax = y2;
  71363. }
  71364. else
  71365. {
  71366. pathXMin = jmin (pathXMin, x1);
  71367. pathXMax = jmax (pathXMax, x2);
  71368. pathYMin = jmin (pathYMin, y1);
  71369. pathYMax = jmax (pathYMax, y2);
  71370. }
  71371. data.elements [numElements++] = moveMarker;
  71372. data.elements [numElements++] = x1;
  71373. data.elements [numElements++] = y2;
  71374. data.elements [numElements++] = lineMarker;
  71375. data.elements [numElements++] = x1;
  71376. data.elements [numElements++] = y1;
  71377. data.elements [numElements++] = lineMarker;
  71378. data.elements [numElements++] = x2;
  71379. data.elements [numElements++] = y1;
  71380. data.elements [numElements++] = lineMarker;
  71381. data.elements [numElements++] = x2;
  71382. data.elements [numElements++] = y2;
  71383. data.elements [numElements++] = closeSubPathMarker;
  71384. }
  71385. void Path::addRectangle (const Rectangle<int>& rectangle)
  71386. {
  71387. addRectangle ((float) rectangle.getX(), (float) rectangle.getY(),
  71388. (float) rectangle.getWidth(), (float) rectangle.getHeight());
  71389. }
  71390. void Path::addRoundedRectangle (const float x, const float y,
  71391. const float w, const float h,
  71392. float csx,
  71393. float csy)
  71394. {
  71395. csx = jmin (csx, w * 0.5f);
  71396. csy = jmin (csy, h * 0.5f);
  71397. const float cs45x = csx * 0.45f;
  71398. const float cs45y = csy * 0.45f;
  71399. const float x2 = x + w;
  71400. const float y2 = y + h;
  71401. startNewSubPath (x + csx, y);
  71402. lineTo (x2 - csx, y);
  71403. cubicTo (x2 - cs45x, y, x2, y + cs45y, x2, y + csy);
  71404. lineTo (x2, y2 - csy);
  71405. cubicTo (x2, y2 - cs45y, x2 - cs45x, y2, x2 - csx, y2);
  71406. lineTo (x + csx, y2);
  71407. cubicTo (x + cs45x, y2, x, y2 - cs45y, x, y2 - csy);
  71408. lineTo (x, y + csy);
  71409. cubicTo (x, y + cs45y, x + cs45x, y, x + csx, y);
  71410. closeSubPath();
  71411. }
  71412. void Path::addRoundedRectangle (const float x, const float y,
  71413. const float w, const float h,
  71414. float cs)
  71415. {
  71416. addRoundedRectangle (x, y, w, h, cs, cs);
  71417. }
  71418. void Path::addTriangle (const float x1, const float y1,
  71419. const float x2, const float y2,
  71420. const float x3, const float y3)
  71421. {
  71422. startNewSubPath (x1, y1);
  71423. lineTo (x2, y2);
  71424. lineTo (x3, y3);
  71425. closeSubPath();
  71426. }
  71427. void Path::addQuadrilateral (const float x1, const float y1,
  71428. const float x2, const float y2,
  71429. const float x3, const float y3,
  71430. const float x4, const float y4)
  71431. {
  71432. startNewSubPath (x1, y1);
  71433. lineTo (x2, y2);
  71434. lineTo (x3, y3);
  71435. lineTo (x4, y4);
  71436. closeSubPath();
  71437. }
  71438. void Path::addEllipse (const float x, const float y,
  71439. const float w, const float h)
  71440. {
  71441. const float hw = w * 0.5f;
  71442. const float hw55 = hw * 0.55f;
  71443. const float hh = h * 0.5f;
  71444. const float hh45 = hh * 0.55f;
  71445. const float cx = x + hw;
  71446. const float cy = y + hh;
  71447. startNewSubPath (cx, cy - hh);
  71448. cubicTo (cx + hw55, cy - hh, cx + hw, cy - hh45, cx + hw, cy);
  71449. cubicTo (cx + hw, cy + hh45, cx + hw55, cy + hh, cx, cy + hh);
  71450. cubicTo (cx - hw55, cy + hh, cx - hw, cy + hh45, cx - hw, cy);
  71451. cubicTo (cx - hw, cy - hh45, cx - hw55, cy - hh, cx, cy - hh);
  71452. closeSubPath();
  71453. }
  71454. void Path::addArc (const float x, const float y,
  71455. const float w, const float h,
  71456. const float fromRadians,
  71457. const float toRadians,
  71458. const bool startAsNewSubPath)
  71459. {
  71460. const float radiusX = w / 2.0f;
  71461. const float radiusY = h / 2.0f;
  71462. addCentredArc (x + radiusX,
  71463. y + radiusY,
  71464. radiusX, radiusY,
  71465. 0.0f,
  71466. fromRadians, toRadians,
  71467. startAsNewSubPath);
  71468. }
  71469. void Path::addCentredArc (const float centreX, const float centreY,
  71470. const float radiusX, const float radiusY,
  71471. const float rotationOfEllipse,
  71472. const float fromRadians,
  71473. const float toRadians,
  71474. const bool startAsNewSubPath)
  71475. {
  71476. if (radiusX > 0.0f && radiusY > 0.0f)
  71477. {
  71478. const AffineTransform rotation (AffineTransform::rotation (rotationOfEllipse, centreX, centreY));
  71479. float angle = fromRadians;
  71480. if (startAsNewSubPath)
  71481. {
  71482. float x = centreX + radiusX * std::sin (angle);
  71483. float y = centreY - radiusY * std::cos (angle);
  71484. if (rotationOfEllipse != 0)
  71485. rotation.transformPoint (x, y);
  71486. startNewSubPath (x, y);
  71487. }
  71488. if (fromRadians < toRadians)
  71489. {
  71490. if (startAsNewSubPath)
  71491. angle += PathHelpers::ellipseAngularIncrement;
  71492. while (angle < toRadians)
  71493. {
  71494. float x = centreX + radiusX * std::sin (angle);
  71495. float y = centreY - radiusY * std::cos (angle);
  71496. if (rotationOfEllipse != 0)
  71497. rotation.transformPoint (x, y);
  71498. lineTo (x, y);
  71499. angle += PathHelpers::ellipseAngularIncrement;
  71500. }
  71501. }
  71502. else
  71503. {
  71504. if (startAsNewSubPath)
  71505. angle -= PathHelpers::ellipseAngularIncrement;
  71506. while (angle > toRadians)
  71507. {
  71508. float x = centreX + radiusX * std::sin (angle);
  71509. float y = centreY - radiusY * std::cos (angle);
  71510. if (rotationOfEllipse != 0)
  71511. rotation.transformPoint (x, y);
  71512. lineTo (x, y);
  71513. angle -= PathHelpers::ellipseAngularIncrement;
  71514. }
  71515. }
  71516. float x = centreX + radiusX * std::sin (toRadians);
  71517. float y = centreY - radiusY * std::cos (toRadians);
  71518. if (rotationOfEllipse != 0)
  71519. rotation.transformPoint (x, y);
  71520. lineTo (x, y);
  71521. }
  71522. }
  71523. void Path::addPieSegment (const float x, const float y,
  71524. const float width, const float height,
  71525. const float fromRadians,
  71526. const float toRadians,
  71527. const float innerCircleProportionalSize)
  71528. {
  71529. float hw = width * 0.5f;
  71530. float hh = height * 0.5f;
  71531. const float centreX = x + hw;
  71532. const float centreY = y + hh;
  71533. startNewSubPath (centreX + hw * std::sin (fromRadians),
  71534. centreY - hh * std::cos (fromRadians));
  71535. addArc (x, y, width, height, fromRadians, toRadians);
  71536. if (std::abs (fromRadians - toRadians) > float_Pi * 1.999f)
  71537. {
  71538. closeSubPath();
  71539. if (innerCircleProportionalSize > 0)
  71540. {
  71541. hw *= innerCircleProportionalSize;
  71542. hh *= innerCircleProportionalSize;
  71543. startNewSubPath (centreX + hw * std::sin (toRadians),
  71544. centreY - hh * std::cos (toRadians));
  71545. addArc (centreX - hw, centreY - hh, hw * 2.0f, hh * 2.0f,
  71546. toRadians, fromRadians);
  71547. }
  71548. }
  71549. else
  71550. {
  71551. if (innerCircleProportionalSize > 0)
  71552. {
  71553. hw *= innerCircleProportionalSize;
  71554. hh *= innerCircleProportionalSize;
  71555. addArc (centreX - hw, centreY - hh, hw * 2.0f, hh * 2.0f,
  71556. toRadians, fromRadians);
  71557. }
  71558. else
  71559. {
  71560. lineTo (centreX, centreY);
  71561. }
  71562. }
  71563. closeSubPath();
  71564. }
  71565. void Path::addLineSegment (const float startX, const float startY,
  71566. const float endX, const float endY,
  71567. float lineThickness)
  71568. {
  71569. lineThickness *= 0.5f;
  71570. float x, y;
  71571. PathHelpers::perpendicularOffset (startX, startY, endX, endY,
  71572. 0, lineThickness, x, y);
  71573. startNewSubPath (x, y);
  71574. PathHelpers::perpendicularOffset (startX, startY, endX, endY,
  71575. 0, -lineThickness, x, y);
  71576. lineTo (x, y);
  71577. PathHelpers::perpendicularOffset (endX, endY, startX, startY,
  71578. 0, lineThickness, x, y);
  71579. lineTo (x, y);
  71580. PathHelpers::perpendicularOffset (endX, endY, startX, startY,
  71581. 0, -lineThickness, x, y);
  71582. lineTo (x, y);
  71583. closeSubPath();
  71584. }
  71585. void Path::addArrow (const float startX, const float startY,
  71586. const float endX, const float endY,
  71587. float lineThickness,
  71588. float arrowheadWidth,
  71589. float arrowheadLength)
  71590. {
  71591. lineThickness *= 0.5f;
  71592. arrowheadWidth *= 0.5f;
  71593. arrowheadLength = jmin (arrowheadLength, 0.8f * juce_hypotf (startX - endX,
  71594. startY - endY));
  71595. float x, y;
  71596. PathHelpers::perpendicularOffset (startX, startY, endX, endY,
  71597. 0, lineThickness, x, y);
  71598. startNewSubPath (x, y);
  71599. PathHelpers::perpendicularOffset (startX, startY, endX, endY,
  71600. 0, -lineThickness, x, y);
  71601. lineTo (x, y);
  71602. PathHelpers::perpendicularOffset (endX, endY, startX, startY,
  71603. arrowheadLength, lineThickness, x, y);
  71604. lineTo (x, y);
  71605. PathHelpers::perpendicularOffset (endX, endY, startX, startY,
  71606. arrowheadLength, arrowheadWidth, x, y);
  71607. lineTo (x, y);
  71608. PathHelpers::perpendicularOffset (endX, endY, startX, startY,
  71609. 0, 0, x, y);
  71610. lineTo (x, y);
  71611. PathHelpers::perpendicularOffset (endX, endY, startX, startY,
  71612. arrowheadLength, -arrowheadWidth, x, y);
  71613. lineTo (x, y);
  71614. PathHelpers::perpendicularOffset (endX, endY, startX, startY,
  71615. arrowheadLength, -lineThickness, x, y);
  71616. lineTo (x, y);
  71617. closeSubPath();
  71618. }
  71619. void Path::addStar (const float centreX,
  71620. const float centreY,
  71621. const int numberOfPoints,
  71622. const float innerRadius,
  71623. const float outerRadius,
  71624. const float startAngle)
  71625. {
  71626. jassert (numberOfPoints > 1); // this would be silly.
  71627. if (numberOfPoints > 1)
  71628. {
  71629. const float angleBetweenPoints = float_Pi * 2.0f / numberOfPoints;
  71630. for (int i = 0; i < numberOfPoints; ++i)
  71631. {
  71632. float angle = startAngle + i * angleBetweenPoints;
  71633. const float x = centreX + outerRadius * std::sin (angle);
  71634. const float y = centreY - outerRadius * std::cos (angle);
  71635. if (i == 0)
  71636. startNewSubPath (x, y);
  71637. else
  71638. lineTo (x, y);
  71639. angle += angleBetweenPoints * 0.5f;
  71640. lineTo (centreX + innerRadius * std::sin (angle),
  71641. centreY - innerRadius * std::cos (angle));
  71642. }
  71643. closeSubPath();
  71644. }
  71645. }
  71646. void Path::addBubble (float x, float y,
  71647. float w, float h,
  71648. float cs,
  71649. float tipX,
  71650. float tipY,
  71651. int whichSide,
  71652. float arrowPos,
  71653. float arrowWidth)
  71654. {
  71655. if (w > 1.0f && h > 1.0f)
  71656. {
  71657. cs = jmin (cs, w * 0.5f, h * 0.5f);
  71658. const float cs2 = 2.0f * cs;
  71659. startNewSubPath (x + cs, y);
  71660. if (whichSide == 0)
  71661. {
  71662. const float halfArrowW = jmin (arrowWidth, w - cs2) * 0.5f;
  71663. const float arrowX1 = x + cs + jmax (0.0f, (w - cs2) * arrowPos - halfArrowW);
  71664. lineTo (arrowX1, y);
  71665. lineTo (tipX, tipY);
  71666. lineTo (arrowX1 + halfArrowW * 2.0f, y);
  71667. }
  71668. lineTo (x + w - cs, y);
  71669. if (cs > 0.0f)
  71670. addArc (x + w - cs2, y, cs2, cs2, 0, float_Pi * 0.5f);
  71671. if (whichSide == 3)
  71672. {
  71673. const float halfArrowH = jmin (arrowWidth, h - cs2) * 0.5f;
  71674. const float arrowY1 = y + cs + jmax (0.0f, (h - cs2) * arrowPos - halfArrowH);
  71675. lineTo (x + w, arrowY1);
  71676. lineTo (tipX, tipY);
  71677. lineTo (x + w, arrowY1 + halfArrowH * 2.0f);
  71678. }
  71679. lineTo (x + w, y + h - cs);
  71680. if (cs > 0.0f)
  71681. addArc (x + w - cs2, y + h - cs2, cs2, cs2, float_Pi * 0.5f, float_Pi);
  71682. if (whichSide == 2)
  71683. {
  71684. const float halfArrowW = jmin (arrowWidth, w - cs2) * 0.5f;
  71685. const float arrowX1 = x + cs + jmax (0.0f, (w - cs2) * arrowPos - halfArrowW);
  71686. lineTo (arrowX1 + halfArrowW * 2.0f, y + h);
  71687. lineTo (tipX, tipY);
  71688. lineTo (arrowX1, y + h);
  71689. }
  71690. lineTo (x + cs, y + h);
  71691. if (cs > 0.0f)
  71692. addArc (x, y + h - cs2, cs2, cs2, float_Pi, float_Pi * 1.5f);
  71693. if (whichSide == 1)
  71694. {
  71695. const float halfArrowH = jmin (arrowWidth, h - cs2) * 0.5f;
  71696. const float arrowY1 = y + cs + jmax (0.0f, (h - cs2) * arrowPos - halfArrowH);
  71697. lineTo (x, arrowY1 + halfArrowH * 2.0f);
  71698. lineTo (tipX, tipY);
  71699. lineTo (x, arrowY1);
  71700. }
  71701. lineTo (x, y + cs);
  71702. if (cs > 0.0f)
  71703. addArc (x, y, cs2, cs2, float_Pi * 1.5f, float_Pi * 2.0f - PathHelpers::ellipseAngularIncrement);
  71704. closeSubPath();
  71705. }
  71706. }
  71707. void Path::addPath (const Path& other)
  71708. {
  71709. size_t i = 0;
  71710. while (i < other.numElements)
  71711. {
  71712. const float type = other.data.elements [i++];
  71713. if (type == moveMarker)
  71714. {
  71715. startNewSubPath (other.data.elements [i],
  71716. other.data.elements [i + 1]);
  71717. i += 2;
  71718. }
  71719. else if (type == lineMarker)
  71720. {
  71721. lineTo (other.data.elements [i],
  71722. other.data.elements [i + 1]);
  71723. i += 2;
  71724. }
  71725. else if (type == quadMarker)
  71726. {
  71727. quadraticTo (other.data.elements [i],
  71728. other.data.elements [i + 1],
  71729. other.data.elements [i + 2],
  71730. other.data.elements [i + 3]);
  71731. i += 4;
  71732. }
  71733. else if (type == cubicMarker)
  71734. {
  71735. cubicTo (other.data.elements [i],
  71736. other.data.elements [i + 1],
  71737. other.data.elements [i + 2],
  71738. other.data.elements [i + 3],
  71739. other.data.elements [i + 4],
  71740. other.data.elements [i + 5]);
  71741. i += 6;
  71742. }
  71743. else if (type == closeSubPathMarker)
  71744. {
  71745. closeSubPath();
  71746. }
  71747. else
  71748. {
  71749. // something's gone wrong with the element list!
  71750. jassertfalse
  71751. }
  71752. }
  71753. }
  71754. void Path::addPath (const Path& other,
  71755. const AffineTransform& transformToApply)
  71756. {
  71757. size_t i = 0;
  71758. while (i < other.numElements)
  71759. {
  71760. const float type = other.data.elements [i++];
  71761. if (type == closeSubPathMarker)
  71762. {
  71763. closeSubPath();
  71764. }
  71765. else
  71766. {
  71767. float x = other.data.elements [i++];
  71768. float y = other.data.elements [i++];
  71769. transformToApply.transformPoint (x, y);
  71770. if (type == moveMarker)
  71771. {
  71772. startNewSubPath (x, y);
  71773. }
  71774. else if (type == lineMarker)
  71775. {
  71776. lineTo (x, y);
  71777. }
  71778. else if (type == quadMarker)
  71779. {
  71780. float x2 = other.data.elements [i++];
  71781. float y2 = other.data.elements [i++];
  71782. transformToApply.transformPoint (x2, y2);
  71783. quadraticTo (x, y, x2, y2);
  71784. }
  71785. else if (type == cubicMarker)
  71786. {
  71787. float x2 = other.data.elements [i++];
  71788. float y2 = other.data.elements [i++];
  71789. float x3 = other.data.elements [i++];
  71790. float y3 = other.data.elements [i++];
  71791. transformToApply.transformPoint (x2, y2);
  71792. transformToApply.transformPoint (x3, y3);
  71793. cubicTo (x, y, x2, y2, x3, y3);
  71794. }
  71795. else
  71796. {
  71797. // something's gone wrong with the element list!
  71798. jassertfalse
  71799. }
  71800. }
  71801. }
  71802. }
  71803. void Path::applyTransform (const AffineTransform& transform) throw()
  71804. {
  71805. size_t i = 0;
  71806. pathYMin = pathXMin = 0;
  71807. pathYMax = pathXMax = 0;
  71808. bool setMaxMin = false;
  71809. while (i < numElements)
  71810. {
  71811. const float type = data.elements [i++];
  71812. if (type == moveMarker)
  71813. {
  71814. transform.transformPoint (data.elements [i],
  71815. data.elements [i + 1]);
  71816. if (setMaxMin)
  71817. {
  71818. pathXMin = jmin (pathXMin, data.elements [i]);
  71819. pathXMax = jmax (pathXMax, data.elements [i]);
  71820. pathYMin = jmin (pathYMin, data.elements [i + 1]);
  71821. pathYMax = jmax (pathYMax, data.elements [i + 1]);
  71822. }
  71823. else
  71824. {
  71825. pathXMin = pathXMax = data.elements [i];
  71826. pathYMin = pathYMax = data.elements [i + 1];
  71827. setMaxMin = true;
  71828. }
  71829. i += 2;
  71830. }
  71831. else if (type == lineMarker)
  71832. {
  71833. transform.transformPoint (data.elements [i],
  71834. data.elements [i + 1]);
  71835. pathXMin = jmin (pathXMin, data.elements [i]);
  71836. pathXMax = jmax (pathXMax, data.elements [i]);
  71837. pathYMin = jmin (pathYMin, data.elements [i + 1]);
  71838. pathYMax = jmax (pathYMax, data.elements [i + 1]);
  71839. i += 2;
  71840. }
  71841. else if (type == quadMarker)
  71842. {
  71843. transform.transformPoint (data.elements [i],
  71844. data.elements [i + 1]);
  71845. transform.transformPoint (data.elements [i + 2],
  71846. data.elements [i + 3]);
  71847. pathXMin = jmin (pathXMin, data.elements [i], data.elements [i + 2]);
  71848. pathXMax = jmax (pathXMax, data.elements [i], data.elements [i + 2]);
  71849. pathYMin = jmin (pathYMin, data.elements [i + 1], data.elements [i + 3]);
  71850. pathYMax = jmax (pathYMax, data.elements [i + 1], data.elements [i + 3]);
  71851. i += 4;
  71852. }
  71853. else if (type == cubicMarker)
  71854. {
  71855. transform.transformPoint (data.elements [i],
  71856. data.elements [i + 1]);
  71857. transform.transformPoint (data.elements [i + 2],
  71858. data.elements [i + 3]);
  71859. transform.transformPoint (data.elements [i + 4],
  71860. data.elements [i + 5]);
  71861. pathXMin = jmin (pathXMin, data.elements [i], data.elements [i + 2], data.elements [i + 4]);
  71862. pathXMax = jmax (pathXMax, data.elements [i], data.elements [i + 2], data.elements [i + 4]);
  71863. pathYMin = jmin (pathYMin, data.elements [i + 1], data.elements [i + 3], data.elements [i + 5]);
  71864. pathYMax = jmax (pathYMax, data.elements [i + 1], data.elements [i + 3], data.elements [i + 5]);
  71865. i += 6;
  71866. }
  71867. }
  71868. }
  71869. const AffineTransform Path::getTransformToScaleToFit (const float x, const float y,
  71870. const float w, const float h,
  71871. const bool preserveProportions,
  71872. const Justification& justification) const
  71873. {
  71874. Rectangle<float> bounds (getBounds());
  71875. if (preserveProportions)
  71876. {
  71877. if (w <= 0 || h <= 0 || bounds.isEmpty())
  71878. return AffineTransform::identity;
  71879. float newW, newH;
  71880. const float srcRatio = bounds.getHeight() / bounds.getWidth();
  71881. if (srcRatio > h / w)
  71882. {
  71883. newW = h / srcRatio;
  71884. newH = h;
  71885. }
  71886. else
  71887. {
  71888. newW = w;
  71889. newH = w * srcRatio;
  71890. }
  71891. float newXCentre = x;
  71892. float newYCentre = y;
  71893. if (justification.testFlags (Justification::left))
  71894. newXCentre += newW * 0.5f;
  71895. else if (justification.testFlags (Justification::right))
  71896. newXCentre += w - newW * 0.5f;
  71897. else
  71898. newXCentre += w * 0.5f;
  71899. if (justification.testFlags (Justification::top))
  71900. newYCentre += newH * 0.5f;
  71901. else if (justification.testFlags (Justification::bottom))
  71902. newYCentre += h - newH * 0.5f;
  71903. else
  71904. newYCentre += h * 0.5f;
  71905. return AffineTransform::translation (bounds.getWidth() * -0.5f - bounds.getX(),
  71906. bounds.getHeight() * -0.5f - bounds.getY())
  71907. .scaled (newW / bounds.getWidth(), newH / bounds.getHeight())
  71908. .translated (newXCentre, newYCentre);
  71909. }
  71910. else
  71911. {
  71912. return AffineTransform::translation (-bounds.getX(), -bounds.getY())
  71913. .scaled (w / bounds.getWidth(), h / bounds.getHeight())
  71914. .translated (x, y);
  71915. }
  71916. }
  71917. bool Path::contains (const float x, const float y, const float tolerence) const
  71918. {
  71919. if (x <= pathXMin || x >= pathXMax
  71920. || y <= pathYMin || y >= pathYMax)
  71921. return false;
  71922. PathFlatteningIterator i (*this, AffineTransform::identity, tolerence);
  71923. int positiveCrossings = 0;
  71924. int negativeCrossings = 0;
  71925. while (i.next())
  71926. {
  71927. if ((i.y1 <= y && i.y2 > y) || (i.y2 <= y && i.y1 > y))
  71928. {
  71929. const float intersectX = i.x1 + (i.x2 - i.x1) * (y - i.y1) / (i.y2 - i.y1);
  71930. if (intersectX <= x)
  71931. {
  71932. if (i.y1 < i.y2)
  71933. ++positiveCrossings;
  71934. else
  71935. ++negativeCrossings;
  71936. }
  71937. }
  71938. }
  71939. return useNonZeroWinding ? (negativeCrossings != positiveCrossings)
  71940. : ((negativeCrossings + positiveCrossings) & 1) != 0;
  71941. }
  71942. bool Path::contains (const Point<float>& point, const float tolerence) const
  71943. {
  71944. return contains (point.getX(), point.getY(), tolerence);
  71945. }
  71946. bool Path::intersectsLine (const Line<float>& line, const float tolerence)
  71947. {
  71948. PathFlatteningIterator i (*this, AffineTransform::identity, tolerence);
  71949. Point<float> intersection;
  71950. while (i.next())
  71951. if (line.intersects (Line<float> (i.x1, i.y1, i.x2, i.y2), intersection))
  71952. return true;
  71953. return false;
  71954. }
  71955. const Line<float> Path::getClippedLine (const Line<float>& line, const bool keepSectionOutsidePath) const
  71956. {
  71957. Line<float> result (line);
  71958. const bool startInside = contains (line.getStart());
  71959. const bool endInside = contains (line.getEnd());
  71960. if (startInside == endInside)
  71961. {
  71962. if (keepSectionOutsidePath == startInside)
  71963. result = Line<float>();
  71964. }
  71965. else
  71966. {
  71967. PathFlatteningIterator i (*this, AffineTransform::identity);
  71968. Point<float> intersection;
  71969. while (i.next())
  71970. {
  71971. if (line.intersects (Line<float> (i.x1, i.y1, i.x2, i.y2), intersection))
  71972. {
  71973. if ((startInside && keepSectionOutsidePath) || (endInside && ! keepSectionOutsidePath))
  71974. result.setStart (intersection);
  71975. else
  71976. result.setEnd (intersection);
  71977. }
  71978. }
  71979. }
  71980. return result;
  71981. }
  71982. const Path Path::createPathWithRoundedCorners (const float cornerRadius) const
  71983. {
  71984. if (cornerRadius <= 0.01f)
  71985. return *this;
  71986. size_t indexOfPathStart = 0, indexOfPathStartThis = 0;
  71987. size_t n = 0;
  71988. bool lastWasLine = false, firstWasLine = false;
  71989. Path p;
  71990. while (n < numElements)
  71991. {
  71992. const float type = data.elements [n++];
  71993. if (type == moveMarker)
  71994. {
  71995. indexOfPathStart = p.numElements;
  71996. indexOfPathStartThis = n - 1;
  71997. const float x = data.elements [n++];
  71998. const float y = data.elements [n++];
  71999. p.startNewSubPath (x, y);
  72000. lastWasLine = false;
  72001. firstWasLine = (data.elements [n] == lineMarker);
  72002. }
  72003. else if (type == lineMarker || type == closeSubPathMarker)
  72004. {
  72005. float startX = 0, startY = 0, joinX = 0, joinY = 0, endX, endY;
  72006. if (type == lineMarker)
  72007. {
  72008. endX = data.elements [n++];
  72009. endY = data.elements [n++];
  72010. if (n > 8)
  72011. {
  72012. startX = data.elements [n - 8];
  72013. startY = data.elements [n - 7];
  72014. joinX = data.elements [n - 5];
  72015. joinY = data.elements [n - 4];
  72016. }
  72017. }
  72018. else
  72019. {
  72020. endX = data.elements [indexOfPathStartThis + 1];
  72021. endY = data.elements [indexOfPathStartThis + 2];
  72022. if (n > 6)
  72023. {
  72024. startX = data.elements [n - 6];
  72025. startY = data.elements [n - 5];
  72026. joinX = data.elements [n - 3];
  72027. joinY = data.elements [n - 2];
  72028. }
  72029. }
  72030. if (lastWasLine)
  72031. {
  72032. const double len1 = juce_hypot (startX - joinX,
  72033. startY - joinY);
  72034. if (len1 > 0)
  72035. {
  72036. const double propNeeded = jmin (0.5, cornerRadius / len1);
  72037. p.data.elements [p.numElements - 2] = (float) (joinX - (joinX - startX) * propNeeded);
  72038. p.data.elements [p.numElements - 1] = (float) (joinY - (joinY - startY) * propNeeded);
  72039. }
  72040. const double len2 = juce_hypot (endX - joinX,
  72041. endY - joinY);
  72042. if (len2 > 0)
  72043. {
  72044. const double propNeeded = jmin (0.5, cornerRadius / len2);
  72045. p.quadraticTo (joinX, joinY,
  72046. (float) (joinX + (endX - joinX) * propNeeded),
  72047. (float) (joinY + (endY - joinY) * propNeeded));
  72048. }
  72049. p.lineTo (endX, endY);
  72050. }
  72051. else if (type == lineMarker)
  72052. {
  72053. p.lineTo (endX, endY);
  72054. lastWasLine = true;
  72055. }
  72056. if (type == closeSubPathMarker)
  72057. {
  72058. if (firstWasLine)
  72059. {
  72060. startX = data.elements [n - 3];
  72061. startY = data.elements [n - 2];
  72062. joinX = endX;
  72063. joinY = endY;
  72064. endX = data.elements [indexOfPathStartThis + 4];
  72065. endY = data.elements [indexOfPathStartThis + 5];
  72066. const double len1 = juce_hypot (startX - joinX,
  72067. startY - joinY);
  72068. if (len1 > 0)
  72069. {
  72070. const double propNeeded = jmin (0.5, cornerRadius / len1);
  72071. p.data.elements [p.numElements - 2] = (float) (joinX - (joinX - startX) * propNeeded);
  72072. p.data.elements [p.numElements - 1] = (float) (joinY - (joinY - startY) * propNeeded);
  72073. }
  72074. const double len2 = juce_hypot (endX - joinX,
  72075. endY - joinY);
  72076. if (len2 > 0)
  72077. {
  72078. const double propNeeded = jmin (0.5, cornerRadius / len2);
  72079. endX = (float) (joinX + (endX - joinX) * propNeeded);
  72080. endY = (float) (joinY + (endY - joinY) * propNeeded);
  72081. p.quadraticTo (joinX, joinY, endX, endY);
  72082. p.data.elements [indexOfPathStart + 1] = endX;
  72083. p.data.elements [indexOfPathStart + 2] = endY;
  72084. }
  72085. }
  72086. p.closeSubPath();
  72087. }
  72088. }
  72089. else if (type == quadMarker)
  72090. {
  72091. lastWasLine = false;
  72092. const float x1 = data.elements [n++];
  72093. const float y1 = data.elements [n++];
  72094. const float x2 = data.elements [n++];
  72095. const float y2 = data.elements [n++];
  72096. p.quadraticTo (x1, y1, x2, y2);
  72097. }
  72098. else if (type == cubicMarker)
  72099. {
  72100. lastWasLine = false;
  72101. const float x1 = data.elements [n++];
  72102. const float y1 = data.elements [n++];
  72103. const float x2 = data.elements [n++];
  72104. const float y2 = data.elements [n++];
  72105. const float x3 = data.elements [n++];
  72106. const float y3 = data.elements [n++];
  72107. p.cubicTo (x1, y1, x2, y2, x3, y3);
  72108. }
  72109. }
  72110. return p;
  72111. }
  72112. void Path::loadPathFromStream (InputStream& source)
  72113. {
  72114. while (! source.isExhausted())
  72115. {
  72116. switch (source.readByte())
  72117. {
  72118. case 'm':
  72119. {
  72120. const float x = source.readFloat();
  72121. const float y = source.readFloat();
  72122. startNewSubPath (x, y);
  72123. break;
  72124. }
  72125. case 'l':
  72126. {
  72127. const float x = source.readFloat();
  72128. const float y = source.readFloat();
  72129. lineTo (x, y);
  72130. break;
  72131. }
  72132. case 'q':
  72133. {
  72134. const float x1 = source.readFloat();
  72135. const float y1 = source.readFloat();
  72136. const float x2 = source.readFloat();
  72137. const float y2 = source.readFloat();
  72138. quadraticTo (x1, y1, x2, y2);
  72139. break;
  72140. }
  72141. case 'b':
  72142. {
  72143. const float x1 = source.readFloat();
  72144. const float y1 = source.readFloat();
  72145. const float x2 = source.readFloat();
  72146. const float y2 = source.readFloat();
  72147. const float x3 = source.readFloat();
  72148. const float y3 = source.readFloat();
  72149. cubicTo (x1, y1, x2, y2, x3, y3);
  72150. break;
  72151. }
  72152. case 'c':
  72153. closeSubPath();
  72154. break;
  72155. case 'n':
  72156. useNonZeroWinding = true;
  72157. break;
  72158. case 'z':
  72159. useNonZeroWinding = false;
  72160. break;
  72161. case 'e':
  72162. return; // end of path marker
  72163. default:
  72164. jassertfalse // illegal char in the stream
  72165. break;
  72166. }
  72167. }
  72168. }
  72169. void Path::loadPathFromData (const void* const pathData, const int numberOfBytes)
  72170. {
  72171. MemoryInputStream in (pathData, numberOfBytes, false);
  72172. loadPathFromStream (in);
  72173. }
  72174. void Path::writePathToStream (OutputStream& dest) const
  72175. {
  72176. dest.writeByte (useNonZeroWinding ? 'n' : 'z');
  72177. size_t i = 0;
  72178. while (i < numElements)
  72179. {
  72180. const float type = data.elements [i++];
  72181. if (type == moveMarker)
  72182. {
  72183. dest.writeByte ('m');
  72184. dest.writeFloat (data.elements [i++]);
  72185. dest.writeFloat (data.elements [i++]);
  72186. }
  72187. else if (type == lineMarker)
  72188. {
  72189. dest.writeByte ('l');
  72190. dest.writeFloat (data.elements [i++]);
  72191. dest.writeFloat (data.elements [i++]);
  72192. }
  72193. else if (type == quadMarker)
  72194. {
  72195. dest.writeByte ('q');
  72196. dest.writeFloat (data.elements [i++]);
  72197. dest.writeFloat (data.elements [i++]);
  72198. dest.writeFloat (data.elements [i++]);
  72199. dest.writeFloat (data.elements [i++]);
  72200. }
  72201. else if (type == cubicMarker)
  72202. {
  72203. dest.writeByte ('b');
  72204. dest.writeFloat (data.elements [i++]);
  72205. dest.writeFloat (data.elements [i++]);
  72206. dest.writeFloat (data.elements [i++]);
  72207. dest.writeFloat (data.elements [i++]);
  72208. dest.writeFloat (data.elements [i++]);
  72209. dest.writeFloat (data.elements [i++]);
  72210. }
  72211. else if (type == closeSubPathMarker)
  72212. {
  72213. dest.writeByte ('c');
  72214. }
  72215. }
  72216. dest.writeByte ('e'); // marks the end-of-path
  72217. }
  72218. const String Path::toString() const
  72219. {
  72220. MemoryOutputStream s (2048, 2048);
  72221. if (! useNonZeroWinding)
  72222. s << 'a';
  72223. size_t i = 0;
  72224. float lastMarker = 0.0f;
  72225. while (i < numElements)
  72226. {
  72227. const float marker = data.elements [i++];
  72228. char markerChar = 0;
  72229. int numCoords = 0;
  72230. if (marker == moveMarker)
  72231. {
  72232. markerChar = 'm';
  72233. numCoords = 2;
  72234. }
  72235. else if (marker == lineMarker)
  72236. {
  72237. markerChar = 'l';
  72238. numCoords = 2;
  72239. }
  72240. else if (marker == quadMarker)
  72241. {
  72242. markerChar = 'q';
  72243. numCoords = 4;
  72244. }
  72245. else if (marker == cubicMarker)
  72246. {
  72247. markerChar = 'c';
  72248. numCoords = 6;
  72249. }
  72250. else
  72251. {
  72252. jassert (marker == closeSubPathMarker);
  72253. markerChar = 'z';
  72254. }
  72255. if (marker != lastMarker)
  72256. {
  72257. if (s.getDataSize() != 0)
  72258. s << ' ';
  72259. s << markerChar;
  72260. lastMarker = marker;
  72261. }
  72262. while (--numCoords >= 0 && i < numElements)
  72263. {
  72264. String coord (data.elements [i++], 3);
  72265. while (coord.endsWithChar ('0') && coord != "0")
  72266. coord = coord.dropLastCharacters (1);
  72267. if (coord.endsWithChar ('.'))
  72268. coord = coord.dropLastCharacters (1);
  72269. if (s.getDataSize() != 0)
  72270. s << ' ';
  72271. s << coord;
  72272. }
  72273. }
  72274. return s.toUTF8();
  72275. }
  72276. void Path::restoreFromString (const String& stringVersion)
  72277. {
  72278. clear();
  72279. setUsingNonZeroWinding (true);
  72280. const juce_wchar* t = stringVersion;
  72281. juce_wchar marker = 'm';
  72282. int numValues = 2;
  72283. float values [6];
  72284. while (*t != 0)
  72285. {
  72286. const String token (PathHelpers::nextToken (t));
  72287. const juce_wchar firstChar = token[0];
  72288. int startNum = 0;
  72289. if (firstChar == 'm' || firstChar == 'l')
  72290. {
  72291. marker = firstChar;
  72292. numValues = 2;
  72293. }
  72294. else if (firstChar == 'q')
  72295. {
  72296. marker = firstChar;
  72297. numValues = 4;
  72298. }
  72299. else if (firstChar == 'c')
  72300. {
  72301. marker = firstChar;
  72302. numValues = 6;
  72303. }
  72304. else if (firstChar == 'z')
  72305. {
  72306. marker = firstChar;
  72307. numValues = 0;
  72308. }
  72309. else if (firstChar == 'a')
  72310. {
  72311. setUsingNonZeroWinding (false);
  72312. continue;
  72313. }
  72314. else
  72315. {
  72316. ++startNum;
  72317. values [0] = token.getFloatValue();
  72318. }
  72319. for (int i = startNum; i < numValues; ++i)
  72320. values [i] = PathHelpers::nextToken (t).getFloatValue();
  72321. switch (marker)
  72322. {
  72323. case 'm':
  72324. startNewSubPath (values[0], values[1]);
  72325. break;
  72326. case 'l':
  72327. lineTo (values[0], values[1]);
  72328. break;
  72329. case 'q':
  72330. quadraticTo (values[0], values[1],
  72331. values[2], values[3]);
  72332. break;
  72333. case 'c':
  72334. cubicTo (values[0], values[1],
  72335. values[2], values[3],
  72336. values[4], values[5]);
  72337. break;
  72338. case 'z':
  72339. closeSubPath();
  72340. break;
  72341. default:
  72342. jassertfalse // illegal string format?
  72343. break;
  72344. }
  72345. }
  72346. }
  72347. Path::Iterator::Iterator (const Path& path_)
  72348. : path (path_),
  72349. index (0)
  72350. {
  72351. }
  72352. Path::Iterator::~Iterator()
  72353. {
  72354. }
  72355. bool Path::Iterator::next()
  72356. {
  72357. const float* const elements = path.data.elements;
  72358. if (index < path.numElements)
  72359. {
  72360. const float type = elements [index++];
  72361. if (type == moveMarker)
  72362. {
  72363. elementType = startNewSubPath;
  72364. x1 = elements [index++];
  72365. y1 = elements [index++];
  72366. }
  72367. else if (type == lineMarker)
  72368. {
  72369. elementType = lineTo;
  72370. x1 = elements [index++];
  72371. y1 = elements [index++];
  72372. }
  72373. else if (type == quadMarker)
  72374. {
  72375. elementType = quadraticTo;
  72376. x1 = elements [index++];
  72377. y1 = elements [index++];
  72378. x2 = elements [index++];
  72379. y2 = elements [index++];
  72380. }
  72381. else if (type == cubicMarker)
  72382. {
  72383. elementType = cubicTo;
  72384. x1 = elements [index++];
  72385. y1 = elements [index++];
  72386. x2 = elements [index++];
  72387. y2 = elements [index++];
  72388. x3 = elements [index++];
  72389. y3 = elements [index++];
  72390. }
  72391. else if (type == closeSubPathMarker)
  72392. {
  72393. elementType = closePath;
  72394. }
  72395. return true;
  72396. }
  72397. return false;
  72398. }
  72399. END_JUCE_NAMESPACE
  72400. /*** End of inlined file: juce_Path.cpp ***/
  72401. /*** Start of inlined file: juce_PathIterator.cpp ***/
  72402. BEGIN_JUCE_NAMESPACE
  72403. #if JUCE_MSVC
  72404. #pragma optimize ("t", on)
  72405. #endif
  72406. PathFlatteningIterator::PathFlatteningIterator (const Path& path_,
  72407. const AffineTransform& transform_,
  72408. float tolerence_)
  72409. : x2 (0),
  72410. y2 (0),
  72411. closesSubPath (false),
  72412. subPathIndex (-1),
  72413. path (path_),
  72414. transform (transform_),
  72415. points (path_.data.elements),
  72416. tolerence (tolerence_ * tolerence_),
  72417. subPathCloseX (0),
  72418. subPathCloseY (0),
  72419. isIdentityTransform (transform_.isIdentity()),
  72420. stackBase (32),
  72421. index (0),
  72422. stackSize (32)
  72423. {
  72424. stackPos = stackBase;
  72425. }
  72426. PathFlatteningIterator::~PathFlatteningIterator()
  72427. {
  72428. }
  72429. bool PathFlatteningIterator::next()
  72430. {
  72431. x1 = x2;
  72432. y1 = y2;
  72433. float x3 = 0;
  72434. float y3 = 0;
  72435. float x4 = 0;
  72436. float y4 = 0;
  72437. float type;
  72438. for (;;)
  72439. {
  72440. if (stackPos == stackBase)
  72441. {
  72442. if (index >= path.numElements)
  72443. {
  72444. return false;
  72445. }
  72446. else
  72447. {
  72448. type = points [index++];
  72449. if (type != Path::closeSubPathMarker)
  72450. {
  72451. x2 = points [index++];
  72452. y2 = points [index++];
  72453. if (! isIdentityTransform)
  72454. transform.transformPoint (x2, y2);
  72455. if (type == Path::quadMarker)
  72456. {
  72457. x3 = points [index++];
  72458. y3 = points [index++];
  72459. if (! isIdentityTransform)
  72460. transform.transformPoint (x3, y3);
  72461. }
  72462. else if (type == Path::cubicMarker)
  72463. {
  72464. x3 = points [index++];
  72465. y3 = points [index++];
  72466. x4 = points [index++];
  72467. y4 = points [index++];
  72468. if (! isIdentityTransform)
  72469. {
  72470. transform.transformPoint (x3, y3);
  72471. transform.transformPoint (x4, y4);
  72472. }
  72473. }
  72474. }
  72475. }
  72476. }
  72477. else
  72478. {
  72479. type = *--stackPos;
  72480. if (type != Path::closeSubPathMarker)
  72481. {
  72482. x2 = *--stackPos;
  72483. y2 = *--stackPos;
  72484. if (type == Path::quadMarker)
  72485. {
  72486. x3 = *--stackPos;
  72487. y3 = *--stackPos;
  72488. }
  72489. else if (type == Path::cubicMarker)
  72490. {
  72491. x3 = *--stackPos;
  72492. y3 = *--stackPos;
  72493. x4 = *--stackPos;
  72494. y4 = *--stackPos;
  72495. }
  72496. }
  72497. }
  72498. if (type == Path::lineMarker)
  72499. {
  72500. ++subPathIndex;
  72501. closesSubPath = (stackPos == stackBase)
  72502. && (index < path.numElements)
  72503. && (points [index] == Path::closeSubPathMarker)
  72504. && x2 == subPathCloseX
  72505. && y2 == subPathCloseY;
  72506. return true;
  72507. }
  72508. else if (type == Path::quadMarker)
  72509. {
  72510. const size_t offset = (size_t) (stackPos - stackBase);
  72511. if (offset >= stackSize - 10)
  72512. {
  72513. stackSize <<= 1;
  72514. stackBase.realloc (stackSize);
  72515. stackPos = stackBase + offset;
  72516. }
  72517. const float dx1 = x1 - x2;
  72518. const float dy1 = y1 - y2;
  72519. const float dx2 = x2 - x3;
  72520. const float dy2 = y2 - y3;
  72521. const float m1x = (x1 + x2) * 0.5f;
  72522. const float m1y = (y1 + y2) * 0.5f;
  72523. const float m2x = (x2 + x3) * 0.5f;
  72524. const float m2y = (y2 + y3) * 0.5f;
  72525. const float m3x = (m1x + m2x) * 0.5f;
  72526. const float m3y = (m1y + m2y) * 0.5f;
  72527. if (dx1*dx1 + dy1*dy1 + dx2*dx2 + dy2*dy2 > tolerence)
  72528. {
  72529. *stackPos++ = y3;
  72530. *stackPos++ = x3;
  72531. *stackPos++ = m2y;
  72532. *stackPos++ = m2x;
  72533. *stackPos++ = Path::quadMarker;
  72534. *stackPos++ = m3y;
  72535. *stackPos++ = m3x;
  72536. *stackPos++ = m1y;
  72537. *stackPos++ = m1x;
  72538. *stackPos++ = Path::quadMarker;
  72539. }
  72540. else
  72541. {
  72542. *stackPos++ = y3;
  72543. *stackPos++ = x3;
  72544. *stackPos++ = Path::lineMarker;
  72545. *stackPos++ = m3y;
  72546. *stackPos++ = m3x;
  72547. *stackPos++ = Path::lineMarker;
  72548. }
  72549. jassert (stackPos < stackBase + stackSize);
  72550. }
  72551. else if (type == Path::cubicMarker)
  72552. {
  72553. const size_t offset = (size_t) (stackPos - stackBase);
  72554. if (offset >= stackSize - 16)
  72555. {
  72556. stackSize <<= 1;
  72557. stackBase.realloc (stackSize);
  72558. stackPos = stackBase + offset;
  72559. }
  72560. const float dx1 = x1 - x2;
  72561. const float dy1 = y1 - y2;
  72562. const float dx2 = x2 - x3;
  72563. const float dy2 = y2 - y3;
  72564. const float dx3 = x3 - x4;
  72565. const float dy3 = y3 - y4;
  72566. const float m1x = (x1 + x2) * 0.5f;
  72567. const float m1y = (y1 + y2) * 0.5f;
  72568. const float m2x = (x3 + x2) * 0.5f;
  72569. const float m2y = (y3 + y2) * 0.5f;
  72570. const float m3x = (x3 + x4) * 0.5f;
  72571. const float m3y = (y3 + y4) * 0.5f;
  72572. const float m4x = (m1x + m2x) * 0.5f;
  72573. const float m4y = (m1y + m2y) * 0.5f;
  72574. const float m5x = (m3x + m2x) * 0.5f;
  72575. const float m5y = (m3y + m2y) * 0.5f;
  72576. if (dx1*dx1 + dy1*dy1 + dx2*dx2
  72577. + dy2*dy2 + dx3*dx3 + dy3*dy3 > tolerence)
  72578. {
  72579. *stackPos++ = y4;
  72580. *stackPos++ = x4;
  72581. *stackPos++ = m3y;
  72582. *stackPos++ = m3x;
  72583. *stackPos++ = m5y;
  72584. *stackPos++ = m5x;
  72585. *stackPos++ = Path::cubicMarker;
  72586. *stackPos++ = (m4y + m5y) * 0.5f;
  72587. *stackPos++ = (m4x + m5x) * 0.5f;
  72588. *stackPos++ = m4y;
  72589. *stackPos++ = m4x;
  72590. *stackPos++ = m1y;
  72591. *stackPos++ = m1x;
  72592. *stackPos++ = Path::cubicMarker;
  72593. }
  72594. else
  72595. {
  72596. *stackPos++ = y4;
  72597. *stackPos++ = x4;
  72598. *stackPos++ = Path::lineMarker;
  72599. *stackPos++ = m5y;
  72600. *stackPos++ = m5x;
  72601. *stackPos++ = Path::lineMarker;
  72602. *stackPos++ = m4y;
  72603. *stackPos++ = m4x;
  72604. *stackPos++ = Path::lineMarker;
  72605. }
  72606. }
  72607. else if (type == Path::closeSubPathMarker)
  72608. {
  72609. if (x2 != subPathCloseX || y2 != subPathCloseY)
  72610. {
  72611. x1 = x2;
  72612. y1 = y2;
  72613. x2 = subPathCloseX;
  72614. y2 = subPathCloseY;
  72615. closesSubPath = true;
  72616. return true;
  72617. }
  72618. }
  72619. else
  72620. {
  72621. jassert (type == Path::moveMarker);
  72622. subPathIndex = -1;
  72623. subPathCloseX = x1 = x2;
  72624. subPathCloseY = y1 = y2;
  72625. }
  72626. }
  72627. }
  72628. END_JUCE_NAMESPACE
  72629. /*** End of inlined file: juce_PathIterator.cpp ***/
  72630. /*** Start of inlined file: juce_PathStrokeType.cpp ***/
  72631. BEGIN_JUCE_NAMESPACE
  72632. PathStrokeType::PathStrokeType (const float strokeThickness,
  72633. const JointStyle jointStyle_,
  72634. const EndCapStyle endStyle_) throw()
  72635. : thickness (strokeThickness),
  72636. jointStyle (jointStyle_),
  72637. endStyle (endStyle_)
  72638. {
  72639. }
  72640. PathStrokeType::PathStrokeType (const PathStrokeType& other) throw()
  72641. : thickness (other.thickness),
  72642. jointStyle (other.jointStyle),
  72643. endStyle (other.endStyle)
  72644. {
  72645. }
  72646. PathStrokeType& PathStrokeType::operator= (const PathStrokeType& other) throw()
  72647. {
  72648. thickness = other.thickness;
  72649. jointStyle = other.jointStyle;
  72650. endStyle = other.endStyle;
  72651. return *this;
  72652. }
  72653. PathStrokeType::~PathStrokeType() throw()
  72654. {
  72655. }
  72656. bool PathStrokeType::operator== (const PathStrokeType& other) const throw()
  72657. {
  72658. return thickness == other.thickness
  72659. && jointStyle == other.jointStyle
  72660. && endStyle == other.endStyle;
  72661. }
  72662. bool PathStrokeType::operator!= (const PathStrokeType& other) const throw()
  72663. {
  72664. return ! operator== (other);
  72665. }
  72666. static bool lineIntersection (const float x1, const float y1,
  72667. const float x2, const float y2,
  72668. const float x3, const float y3,
  72669. const float x4, const float y4,
  72670. float& intersectionX,
  72671. float& intersectionY,
  72672. float& distanceBeyondLine1EndSquared) throw()
  72673. {
  72674. if (x2 != x3 || y2 != y3)
  72675. {
  72676. const float dx1 = x2 - x1;
  72677. const float dy1 = y2 - y1;
  72678. const float dx2 = x4 - x3;
  72679. const float dy2 = y4 - y3;
  72680. const float divisor = dx1 * dy2 - dx2 * dy1;
  72681. if (divisor == 0)
  72682. {
  72683. if (! ((dx1 == 0 && dy1 == 0) || (dx2 == 0 && dy2 == 0)))
  72684. {
  72685. if (dy1 == 0 && dy2 != 0)
  72686. {
  72687. const float along = (y1 - y3) / dy2;
  72688. intersectionX = x3 + along * dx2;
  72689. intersectionY = y1;
  72690. distanceBeyondLine1EndSquared = intersectionX - x2;
  72691. distanceBeyondLine1EndSquared *= distanceBeyondLine1EndSquared;
  72692. if ((x2 > x1) == (intersectionX < x2))
  72693. distanceBeyondLine1EndSquared = -distanceBeyondLine1EndSquared;
  72694. return along >= 0 && along <= 1.0f;
  72695. }
  72696. else if (dy2 == 0 && dy1 != 0)
  72697. {
  72698. const float along = (y3 - y1) / dy1;
  72699. intersectionX = x1 + along * dx1;
  72700. intersectionY = y3;
  72701. distanceBeyondLine1EndSquared = (along - 1.0f) * dx1;
  72702. distanceBeyondLine1EndSquared *= distanceBeyondLine1EndSquared;
  72703. if (along < 1.0f)
  72704. distanceBeyondLine1EndSquared = -distanceBeyondLine1EndSquared;
  72705. return along >= 0 && along <= 1.0f;
  72706. }
  72707. else if (dx1 == 0 && dx2 != 0)
  72708. {
  72709. const float along = (x1 - x3) / dx2;
  72710. intersectionX = x1;
  72711. intersectionY = y3 + along * dy2;
  72712. distanceBeyondLine1EndSquared = intersectionY - y2;
  72713. distanceBeyondLine1EndSquared *= distanceBeyondLine1EndSquared;
  72714. if ((y2 > y1) == (intersectionY < y2))
  72715. distanceBeyondLine1EndSquared = -distanceBeyondLine1EndSquared;
  72716. return along >= 0 && along <= 1.0f;
  72717. }
  72718. else if (dx2 == 0 && dx1 != 0)
  72719. {
  72720. const float along = (x3 - x1) / dx1;
  72721. intersectionX = x3;
  72722. intersectionY = y1 + along * dy1;
  72723. distanceBeyondLine1EndSquared = (along - 1.0f) * dy1;
  72724. distanceBeyondLine1EndSquared *= distanceBeyondLine1EndSquared;
  72725. if (along < 1.0f)
  72726. distanceBeyondLine1EndSquared = -distanceBeyondLine1EndSquared;
  72727. return along >= 0 && along <= 1.0f;
  72728. }
  72729. }
  72730. intersectionX = 0.5f * (x2 + x3);
  72731. intersectionY = 0.5f * (y2 + y3);
  72732. distanceBeyondLine1EndSquared = 0.0f;
  72733. return false;
  72734. }
  72735. else
  72736. {
  72737. const float along1 = ((y1 - y3) * dx2 - (x1 - x3) * dy2) / divisor;
  72738. intersectionX = x1 + along1 * dx1;
  72739. intersectionY = y1 + along1 * dy1;
  72740. if (along1 >= 0 && along1 <= 1.0f)
  72741. {
  72742. const float along2 = ((y1 - y3) * dx1 - (x1 - x3) * dy1);
  72743. if (along2 >= 0 && along2 <= divisor)
  72744. {
  72745. distanceBeyondLine1EndSquared = 0.0f;
  72746. return true;
  72747. }
  72748. }
  72749. distanceBeyondLine1EndSquared = along1 - 1.0f;
  72750. distanceBeyondLine1EndSquared *= distanceBeyondLine1EndSquared;
  72751. distanceBeyondLine1EndSquared *= (dx1 * dx1 + dy1 * dy1);
  72752. if (along1 < 1.0f)
  72753. distanceBeyondLine1EndSquared = -distanceBeyondLine1EndSquared;
  72754. return false;
  72755. }
  72756. }
  72757. intersectionX = x2;
  72758. intersectionY = y2;
  72759. distanceBeyondLine1EndSquared = 0.0f;
  72760. return true;
  72761. }
  72762. namespace PathFunctions
  72763. {
  72764. // part of stroke drawing stuff
  72765. static void addEdgeAndJoint (Path& destPath,
  72766. const PathStrokeType::JointStyle style,
  72767. const float maxMiterExtensionSquared, const float width,
  72768. const float x1, const float y1,
  72769. const float x2, const float y2,
  72770. const float x3, const float y3,
  72771. const float x4, const float y4,
  72772. const float midX, const float midY)
  72773. {
  72774. if (style == PathStrokeType::beveled
  72775. || (x3 == x4 && y3 == y4)
  72776. || (x1 == x2 && y1 == y2))
  72777. {
  72778. destPath.lineTo (x2, y2);
  72779. destPath.lineTo (x3, y3);
  72780. }
  72781. else
  72782. {
  72783. float jx, jy, distanceBeyondLine1EndSquared;
  72784. // if they intersect, use this point..
  72785. if (lineIntersection (x1, y1, x2, y2,
  72786. x3, y3, x4, y4,
  72787. jx, jy, distanceBeyondLine1EndSquared))
  72788. {
  72789. destPath.lineTo (jx, jy);
  72790. }
  72791. else
  72792. {
  72793. if (style == PathStrokeType::mitered)
  72794. {
  72795. if (distanceBeyondLine1EndSquared < maxMiterExtensionSquared
  72796. && distanceBeyondLine1EndSquared > 0.0f)
  72797. {
  72798. destPath.lineTo (jx, jy);
  72799. }
  72800. else
  72801. {
  72802. // the end sticks out too far, so just use a blunt joint
  72803. destPath.lineTo (x2, y2);
  72804. destPath.lineTo (x3, y3);
  72805. }
  72806. }
  72807. else
  72808. {
  72809. // curved joints
  72810. float angle1 = std::atan2 (x2 - midX, y2 - midY);
  72811. float angle2 = std::atan2 (x3 - midX, y3 - midY);
  72812. const float angleIncrement = 0.1f;
  72813. destPath.lineTo (x2, y2);
  72814. if (std::abs (angle1 - angle2) > angleIncrement)
  72815. {
  72816. if (angle2 > angle1 + float_Pi
  72817. || (angle2 < angle1 && angle2 >= angle1 - float_Pi))
  72818. {
  72819. if (angle2 > angle1)
  72820. angle2 -= float_Pi * 2.0f;
  72821. jassert (angle1 <= angle2 + float_Pi);
  72822. angle1 -= angleIncrement;
  72823. while (angle1 > angle2)
  72824. {
  72825. destPath.lineTo (midX + width * std::sin (angle1),
  72826. midY + width * std::cos (angle1));
  72827. angle1 -= angleIncrement;
  72828. }
  72829. }
  72830. else
  72831. {
  72832. if (angle1 > angle2)
  72833. angle1 -= float_Pi * 2.0f;
  72834. jassert (angle1 >= angle2 - float_Pi);
  72835. angle1 += angleIncrement;
  72836. while (angle1 < angle2)
  72837. {
  72838. destPath.lineTo (midX + width * std::sin (angle1),
  72839. midY + width * std::cos (angle1));
  72840. angle1 += angleIncrement;
  72841. }
  72842. }
  72843. }
  72844. destPath.lineTo (x3, y3);
  72845. }
  72846. }
  72847. }
  72848. }
  72849. static void addLineEnd (Path& destPath,
  72850. const PathStrokeType::EndCapStyle style,
  72851. const float x1, const float y1,
  72852. const float x2, const float y2,
  72853. const float width)
  72854. {
  72855. if (style == PathStrokeType::butt)
  72856. {
  72857. destPath.lineTo (x2, y2);
  72858. }
  72859. else
  72860. {
  72861. float offx1, offy1, offx2, offy2;
  72862. float dx = x2 - x1;
  72863. float dy = y2 - y1;
  72864. const float len = juce_hypotf (dx, dy);
  72865. if (len == 0)
  72866. {
  72867. offx1 = offx2 = x1;
  72868. offy1 = offy2 = y1;
  72869. }
  72870. else
  72871. {
  72872. const float offset = width / len;
  72873. dx *= offset;
  72874. dy *= offset;
  72875. offx1 = x1 + dy;
  72876. offy1 = y1 - dx;
  72877. offx2 = x2 + dy;
  72878. offy2 = y2 - dx;
  72879. }
  72880. if (style == PathStrokeType::square)
  72881. {
  72882. // sqaure ends
  72883. destPath.lineTo (offx1, offy1);
  72884. destPath.lineTo (offx2, offy2);
  72885. destPath.lineTo (x2, y2);
  72886. }
  72887. else
  72888. {
  72889. // rounded ends
  72890. const float midx = (offx1 + offx2) * 0.5f;
  72891. const float midy = (offy1 + offy2) * 0.5f;
  72892. destPath.cubicTo (x1 + (offx1 - x1) * 0.55f, y1 + (offy1 - y1) * 0.55f,
  72893. offx1 + (midx - offx1) * 0.45f, offy1 + (midy - offy1) * 0.45f,
  72894. midx, midy);
  72895. destPath.cubicTo (midx + (offx2 - midx) * 0.55f, midy + (offy2 - midy) * 0.55f,
  72896. offx2 + (x2 - offx2) * 0.45f, offy2 + (y2 - offy2) * 0.45f,
  72897. x2, y2);
  72898. }
  72899. }
  72900. }
  72901. struct LineSection
  72902. {
  72903. LineSection() {}
  72904. LineSection (int) {}
  72905. float x1, y1, x2, y2; // original line
  72906. float lx1, ly1, lx2, ly2; // the left-hand stroke
  72907. float rx1, ry1, rx2, ry2; // the right-hand stroke
  72908. };
  72909. static void addSubPath (Path& destPath, const Array <LineSection>& subPath,
  72910. const bool isClosed,
  72911. const float width, const float maxMiterExtensionSquared,
  72912. const PathStrokeType::JointStyle jointStyle, const PathStrokeType::EndCapStyle endStyle)
  72913. {
  72914. jassert (subPath.size() > 0);
  72915. const LineSection& firstLine = subPath.getReference (0);
  72916. float lastX1 = firstLine.lx1;
  72917. float lastY1 = firstLine.ly1;
  72918. float lastX2 = firstLine.lx2;
  72919. float lastY2 = firstLine.ly2;
  72920. if (isClosed)
  72921. {
  72922. destPath.startNewSubPath (lastX1, lastY1);
  72923. }
  72924. else
  72925. {
  72926. destPath.startNewSubPath (firstLine.rx2, firstLine.ry2);
  72927. addLineEnd (destPath, endStyle,
  72928. firstLine.rx2, firstLine.ry2,
  72929. lastX1, lastY1,
  72930. width);
  72931. }
  72932. int i;
  72933. for (i = 1; i < subPath.size(); ++i)
  72934. {
  72935. const LineSection& l = subPath.getReference (i);
  72936. addEdgeAndJoint (destPath, jointStyle,
  72937. maxMiterExtensionSquared, width,
  72938. lastX1, lastY1, lastX2, lastY2,
  72939. l.lx1, l.ly1, l.lx2, l.ly2,
  72940. l.x1, l.y1);
  72941. lastX1 = l.lx1;
  72942. lastY1 = l.ly1;
  72943. lastX2 = l.lx2;
  72944. lastY2 = l.ly2;
  72945. }
  72946. const LineSection& lastLine = subPath.getReference (subPath.size() - 1);
  72947. if (isClosed)
  72948. {
  72949. const LineSection& l = subPath.getReference (0);
  72950. addEdgeAndJoint (destPath, jointStyle,
  72951. maxMiterExtensionSquared, width,
  72952. lastX1, lastY1, lastX2, lastY2,
  72953. l.lx1, l.ly1, l.lx2, l.ly2,
  72954. l.x1, l.y1);
  72955. destPath.closeSubPath();
  72956. destPath.startNewSubPath (lastLine.rx1, lastLine.ry1);
  72957. }
  72958. else
  72959. {
  72960. destPath.lineTo (lastX2, lastY2);
  72961. addLineEnd (destPath, endStyle,
  72962. lastX2, lastY2,
  72963. lastLine.rx1, lastLine.ry1,
  72964. width);
  72965. }
  72966. lastX1 = lastLine.rx1;
  72967. lastY1 = lastLine.ry1;
  72968. lastX2 = lastLine.rx2;
  72969. lastY2 = lastLine.ry2;
  72970. for (i = subPath.size() - 1; --i >= 0;)
  72971. {
  72972. const LineSection& l = subPath.getReference (i);
  72973. addEdgeAndJoint (destPath, jointStyle,
  72974. maxMiterExtensionSquared, width,
  72975. lastX1, lastY1, lastX2, lastY2,
  72976. l.rx1, l.ry1, l.rx2, l.ry2,
  72977. l.x2, l.y2);
  72978. lastX1 = l.rx1;
  72979. lastY1 = l.ry1;
  72980. lastX2 = l.rx2;
  72981. lastY2 = l.ry2;
  72982. }
  72983. if (isClosed)
  72984. {
  72985. addEdgeAndJoint (destPath, jointStyle,
  72986. maxMiterExtensionSquared, width,
  72987. lastX1, lastY1, lastX2, lastY2,
  72988. lastLine.rx1, lastLine.ry1, lastLine.rx2, lastLine.ry2,
  72989. lastLine.x2, lastLine.y2);
  72990. }
  72991. else
  72992. {
  72993. // do the last line
  72994. destPath.lineTo (lastX2, lastY2);
  72995. }
  72996. destPath.closeSubPath();
  72997. }
  72998. }
  72999. void PathStrokeType::createStrokedPath (Path& destPath,
  73000. const Path& source,
  73001. const AffineTransform& transform,
  73002. const float extraAccuracy) const
  73003. {
  73004. if (thickness <= 0)
  73005. {
  73006. destPath.clear();
  73007. return;
  73008. }
  73009. const Path* sourcePath = &source;
  73010. Path temp;
  73011. if (sourcePath == &destPath)
  73012. {
  73013. destPath.swapWithPath (temp);
  73014. sourcePath = &temp;
  73015. }
  73016. else
  73017. {
  73018. destPath.clear();
  73019. }
  73020. destPath.setUsingNonZeroWinding (true);
  73021. const float maxMiterExtensionSquared = 9.0f * thickness * thickness;
  73022. const float width = 0.5f * thickness;
  73023. // Iterate the path, creating a list of the
  73024. // left/right-hand lines along either side of it...
  73025. PathFlatteningIterator it (*sourcePath, transform, 9.0f / extraAccuracy);
  73026. using namespace PathFunctions;
  73027. Array <LineSection> subPath;
  73028. LineSection l;
  73029. l.x1 = 0;
  73030. l.y1 = 0;
  73031. const float minSegmentLength = 2.0f / (extraAccuracy * extraAccuracy);
  73032. while (it.next())
  73033. {
  73034. if (it.subPathIndex == 0)
  73035. {
  73036. if (subPath.size() > 0)
  73037. {
  73038. addSubPath (destPath, subPath, false, width, maxMiterExtensionSquared, jointStyle, endStyle);
  73039. subPath.clearQuick();
  73040. }
  73041. l.x1 = it.x1;
  73042. l.y1 = it.y1;
  73043. }
  73044. l.x2 = it.x2;
  73045. l.y2 = it.y2;
  73046. float dx = l.x2 - l.x1;
  73047. float dy = l.y2 - l.y1;
  73048. const float hypotSquared = dx*dx + dy*dy;
  73049. if (it.closesSubPath || hypotSquared > minSegmentLength || it.isLastInSubpath())
  73050. {
  73051. const float len = std::sqrt (hypotSquared);
  73052. if (len == 0)
  73053. {
  73054. l.rx1 = l.rx2 = l.lx1 = l.lx2 = l.x1;
  73055. l.ry1 = l.ry2 = l.ly1 = l.ly2 = l.y1;
  73056. }
  73057. else
  73058. {
  73059. const float offset = width / len;
  73060. dx *= offset;
  73061. dy *= offset;
  73062. l.rx2 = l.x1 - dy;
  73063. l.ry2 = l.y1 + dx;
  73064. l.lx1 = l.x1 + dy;
  73065. l.ly1 = l.y1 - dx;
  73066. l.lx2 = l.x2 + dy;
  73067. l.ly2 = l.y2 - dx;
  73068. l.rx1 = l.x2 - dy;
  73069. l.ry1 = l.y2 + dx;
  73070. }
  73071. subPath.add (l);
  73072. if (it.closesSubPath)
  73073. {
  73074. addSubPath (destPath, subPath, true, width, maxMiterExtensionSquared, jointStyle, endStyle);
  73075. subPath.clearQuick();
  73076. }
  73077. else
  73078. {
  73079. l.x1 = it.x2;
  73080. l.y1 = it.y2;
  73081. }
  73082. }
  73083. }
  73084. if (subPath.size() > 0)
  73085. addSubPath (destPath, subPath, false, width, maxMiterExtensionSquared, jointStyle, endStyle);
  73086. }
  73087. void PathStrokeType::createDashedStroke (Path& destPath,
  73088. const Path& sourcePath,
  73089. const float* dashLengths,
  73090. int numDashLengths,
  73091. const AffineTransform& transform,
  73092. const float extraAccuracy) const
  73093. {
  73094. if (thickness <= 0)
  73095. return;
  73096. // this should really be an even number..
  73097. jassert ((numDashLengths & 1) == 0);
  73098. Path newDestPath;
  73099. PathFlatteningIterator it (sourcePath, transform, 9.0f / extraAccuracy);
  73100. bool first = true;
  73101. int dashNum = 0;
  73102. float pos = 0.0f, lineLen = 0.0f, lineEndPos = 0.0f;
  73103. float dx = 0.0f, dy = 0.0f;
  73104. for (;;)
  73105. {
  73106. const bool isSolid = ((dashNum & 1) == 0);
  73107. const float dashLen = dashLengths [dashNum++ % numDashLengths];
  73108. jassert (dashLen > 0); // must be a positive increment!
  73109. if (dashLen <= 0)
  73110. break;
  73111. pos += dashLen;
  73112. while (pos > lineEndPos)
  73113. {
  73114. if (! it.next())
  73115. {
  73116. if (isSolid && ! first)
  73117. newDestPath.lineTo (it.x2, it.y2);
  73118. createStrokedPath (destPath, newDestPath, AffineTransform::identity, extraAccuracy);
  73119. return;
  73120. }
  73121. if (isSolid && ! first)
  73122. newDestPath.lineTo (it.x1, it.y1);
  73123. else
  73124. newDestPath.startNewSubPath (it.x1, it.y1);
  73125. dx = it.x2 - it.x1;
  73126. dy = it.y2 - it.y1;
  73127. lineLen = juce_hypotf (dx, dy);
  73128. lineEndPos += lineLen;
  73129. first = it.closesSubPath;
  73130. }
  73131. const float alpha = (pos - (lineEndPos - lineLen)) / lineLen;
  73132. if (isSolid)
  73133. newDestPath.lineTo (it.x1 + dx * alpha,
  73134. it.y1 + dy * alpha);
  73135. else
  73136. newDestPath.startNewSubPath (it.x1 + dx * alpha,
  73137. it.y1 + dy * alpha);
  73138. }
  73139. }
  73140. END_JUCE_NAMESPACE
  73141. /*** End of inlined file: juce_PathStrokeType.cpp ***/
  73142. /*** Start of inlined file: juce_PositionedRectangle.cpp ***/
  73143. BEGIN_JUCE_NAMESPACE
  73144. PositionedRectangle::PositionedRectangle() throw()
  73145. : x (0.0),
  73146. y (0.0),
  73147. w (0.0),
  73148. h (0.0),
  73149. xMode (anchorAtLeftOrTop | absoluteFromParentTopLeft),
  73150. yMode (anchorAtLeftOrTop | absoluteFromParentTopLeft),
  73151. wMode (absoluteSize),
  73152. hMode (absoluteSize)
  73153. {
  73154. }
  73155. PositionedRectangle::PositionedRectangle (const PositionedRectangle& other) throw()
  73156. : x (other.x),
  73157. y (other.y),
  73158. w (other.w),
  73159. h (other.h),
  73160. xMode (other.xMode),
  73161. yMode (other.yMode),
  73162. wMode (other.wMode),
  73163. hMode (other.hMode)
  73164. {
  73165. }
  73166. PositionedRectangle& PositionedRectangle::operator= (const PositionedRectangle& other) throw()
  73167. {
  73168. x = other.x;
  73169. y = other.y;
  73170. w = other.w;
  73171. h = other.h;
  73172. xMode = other.xMode;
  73173. yMode = other.yMode;
  73174. wMode = other.wMode;
  73175. hMode = other.hMode;
  73176. return *this;
  73177. }
  73178. PositionedRectangle::~PositionedRectangle() throw()
  73179. {
  73180. }
  73181. bool PositionedRectangle::operator== (const PositionedRectangle& other) const throw()
  73182. {
  73183. return x == other.x
  73184. && y == other.y
  73185. && w == other.w
  73186. && h == other.h
  73187. && xMode == other.xMode
  73188. && yMode == other.yMode
  73189. && wMode == other.wMode
  73190. && hMode == other.hMode;
  73191. }
  73192. bool PositionedRectangle::operator!= (const PositionedRectangle& other) const throw()
  73193. {
  73194. return ! operator== (other);
  73195. }
  73196. PositionedRectangle::PositionedRectangle (const String& stringVersion) throw()
  73197. {
  73198. StringArray tokens;
  73199. tokens.addTokens (stringVersion, false);
  73200. decodePosString (tokens [0], xMode, x);
  73201. decodePosString (tokens [1], yMode, y);
  73202. decodeSizeString (tokens [2], wMode, w);
  73203. decodeSizeString (tokens [3], hMode, h);
  73204. }
  73205. const String PositionedRectangle::toString() const throw()
  73206. {
  73207. String s;
  73208. s.preallocateStorage (12);
  73209. addPosDescription (s, xMode, x);
  73210. s << ' ';
  73211. addPosDescription (s, yMode, y);
  73212. s << ' ';
  73213. addSizeDescription (s, wMode, w);
  73214. s << ' ';
  73215. addSizeDescription (s, hMode, h);
  73216. return s;
  73217. }
  73218. const Rectangle<int> PositionedRectangle::getRectangle (const Rectangle<int>& target) const throw()
  73219. {
  73220. jassert (! target.isEmpty());
  73221. double x_, y_, w_, h_;
  73222. applyPosAndSize (x_, w_, x, w, xMode, wMode, target.getX(), target.getWidth());
  73223. applyPosAndSize (y_, h_, y, h, yMode, hMode, target.getY(), target.getHeight());
  73224. return Rectangle<int> (roundToInt (x_), roundToInt (y_),
  73225. roundToInt (w_), roundToInt (h_));
  73226. }
  73227. void PositionedRectangle::getRectangleDouble (const Rectangle<int>& target,
  73228. double& x_, double& y_,
  73229. double& w_, double& h_) const throw()
  73230. {
  73231. jassert (! target.isEmpty());
  73232. applyPosAndSize (x_, w_, x, w, xMode, wMode, target.getX(), target.getWidth());
  73233. applyPosAndSize (y_, h_, y, h, yMode, hMode, target.getY(), target.getHeight());
  73234. }
  73235. void PositionedRectangle::applyToComponent (Component& comp) const throw()
  73236. {
  73237. comp.setBounds (getRectangle (Rectangle<int> (0, 0, comp.getParentWidth(), comp.getParentHeight())));
  73238. }
  73239. void PositionedRectangle::updateFrom (const Rectangle<int>& rectangle,
  73240. const Rectangle<int>& target) throw()
  73241. {
  73242. updatePosAndSize (x, w, rectangle.getX(), rectangle.getWidth(), xMode, wMode, target.getX(), target.getWidth());
  73243. updatePosAndSize (y, h, rectangle.getY(), rectangle.getHeight(), yMode, hMode, target.getY(), target.getHeight());
  73244. }
  73245. void PositionedRectangle::updateFromDouble (const double newX, const double newY,
  73246. const double newW, const double newH,
  73247. const Rectangle<int>& target) throw()
  73248. {
  73249. updatePosAndSize (x, w, newX, newW, xMode, wMode, target.getX(), target.getWidth());
  73250. updatePosAndSize (y, h, newY, newH, yMode, hMode, target.getY(), target.getHeight());
  73251. }
  73252. void PositionedRectangle::updateFromComponent (const Component& comp) throw()
  73253. {
  73254. if (comp.getParentComponent() == 0 && ! comp.isOnDesktop())
  73255. updateFrom (comp.getBounds(), Rectangle<int>());
  73256. else
  73257. updateFrom (comp.getBounds(), Rectangle<int> (0, 0, comp.getParentWidth(), comp.getParentHeight()));
  73258. }
  73259. PositionedRectangle::AnchorPoint PositionedRectangle::getAnchorPointX() const throw()
  73260. {
  73261. return (AnchorPoint) (xMode & (anchorAtLeftOrTop | anchorAtRightOrBottom | anchorAtCentre));
  73262. }
  73263. PositionedRectangle::PositionMode PositionedRectangle::getPositionModeX() const throw()
  73264. {
  73265. return (PositionMode) (xMode & (absoluteFromParentTopLeft
  73266. | absoluteFromParentBottomRight
  73267. | absoluteFromParentCentre
  73268. | proportionOfParentSize));
  73269. }
  73270. PositionedRectangle::AnchorPoint PositionedRectangle::getAnchorPointY() const throw()
  73271. {
  73272. return (AnchorPoint) (yMode & (anchorAtLeftOrTop | anchorAtRightOrBottom | anchorAtCentre));
  73273. }
  73274. PositionedRectangle::PositionMode PositionedRectangle::getPositionModeY() const throw()
  73275. {
  73276. return (PositionMode) (yMode & (absoluteFromParentTopLeft
  73277. | absoluteFromParentBottomRight
  73278. | absoluteFromParentCentre
  73279. | proportionOfParentSize));
  73280. }
  73281. PositionedRectangle::SizeMode PositionedRectangle::getWidthMode() const throw()
  73282. {
  73283. return (SizeMode) wMode;
  73284. }
  73285. PositionedRectangle::SizeMode PositionedRectangle::getHeightMode() const throw()
  73286. {
  73287. return (SizeMode) hMode;
  73288. }
  73289. void PositionedRectangle::setModes (const AnchorPoint xAnchor,
  73290. const PositionMode xMode_,
  73291. const AnchorPoint yAnchor,
  73292. const PositionMode yMode_,
  73293. const SizeMode widthMode,
  73294. const SizeMode heightMode,
  73295. const Rectangle<int>& target) throw()
  73296. {
  73297. if (xMode != (xAnchor | xMode_) || wMode != widthMode)
  73298. {
  73299. double tx, tw;
  73300. applyPosAndSize (tx, tw, x, w, xMode, wMode, target.getX(), target.getWidth());
  73301. xMode = (uint8) (xAnchor | xMode_);
  73302. wMode = (uint8) widthMode;
  73303. updatePosAndSize (x, w, tx, tw, xMode, wMode, target.getX(), target.getWidth());
  73304. }
  73305. if (yMode != (yAnchor | yMode_) || hMode != heightMode)
  73306. {
  73307. double ty, th;
  73308. applyPosAndSize (ty, th, y, h, yMode, hMode, target.getY(), target.getHeight());
  73309. yMode = (uint8) (yAnchor | yMode_);
  73310. hMode = (uint8) heightMode;
  73311. updatePosAndSize (y, h, ty, th, yMode, hMode, target.getY(), target.getHeight());
  73312. }
  73313. }
  73314. bool PositionedRectangle::isPositionAbsolute() const throw()
  73315. {
  73316. return xMode == absoluteFromParentTopLeft
  73317. && yMode == absoluteFromParentTopLeft
  73318. && wMode == absoluteSize
  73319. && hMode == absoluteSize;
  73320. }
  73321. void PositionedRectangle::addPosDescription (String& s, const uint8 mode, const double value) const throw()
  73322. {
  73323. if ((mode & proportionOfParentSize) != 0)
  73324. {
  73325. s << (roundToInt (value * 100000.0) / 1000.0) << '%';
  73326. }
  73327. else
  73328. {
  73329. s << (roundToInt (value * 100.0) / 100.0);
  73330. if ((mode & absoluteFromParentBottomRight) != 0)
  73331. s << 'R';
  73332. else if ((mode & absoluteFromParentCentre) != 0)
  73333. s << 'C';
  73334. }
  73335. if ((mode & anchorAtRightOrBottom) != 0)
  73336. s << 'r';
  73337. else if ((mode & anchorAtCentre) != 0)
  73338. s << 'c';
  73339. }
  73340. void PositionedRectangle::addSizeDescription (String& s, const uint8 mode, const double value) const throw()
  73341. {
  73342. if (mode == proportionalSize)
  73343. s << (roundToInt (value * 100000.0) / 1000.0) << '%';
  73344. else if (mode == parentSizeMinusAbsolute)
  73345. s << (roundToInt (value * 100.0) / 100.0) << 'M';
  73346. else
  73347. s << (roundToInt (value * 100.0) / 100.0);
  73348. }
  73349. void PositionedRectangle::decodePosString (const String& s, uint8& mode, double& value) throw()
  73350. {
  73351. if (s.containsChar ('r'))
  73352. mode = anchorAtRightOrBottom;
  73353. else if (s.containsChar ('c'))
  73354. mode = anchorAtCentre;
  73355. else
  73356. mode = anchorAtLeftOrTop;
  73357. if (s.containsChar ('%'))
  73358. {
  73359. mode |= proportionOfParentSize;
  73360. value = s.removeCharacters ("%rcRC").getDoubleValue() / 100.0;
  73361. }
  73362. else
  73363. {
  73364. if (s.containsChar ('R'))
  73365. mode |= absoluteFromParentBottomRight;
  73366. else if (s.containsChar ('C'))
  73367. mode |= absoluteFromParentCentre;
  73368. else
  73369. mode |= absoluteFromParentTopLeft;
  73370. value = s.removeCharacters ("rcRC").getDoubleValue();
  73371. }
  73372. }
  73373. void PositionedRectangle::decodeSizeString (const String& s, uint8& mode, double& value) throw()
  73374. {
  73375. if (s.containsChar ('%'))
  73376. {
  73377. mode = proportionalSize;
  73378. value = s.upToFirstOccurrenceOf ("%", false, false).getDoubleValue() / 100.0;
  73379. }
  73380. else if (s.containsChar ('M'))
  73381. {
  73382. mode = parentSizeMinusAbsolute;
  73383. value = s.getDoubleValue();
  73384. }
  73385. else
  73386. {
  73387. mode = absoluteSize;
  73388. value = s.getDoubleValue();
  73389. }
  73390. }
  73391. void PositionedRectangle::applyPosAndSize (double& xOut, double& wOut,
  73392. const double x_, const double w_,
  73393. const uint8 xMode_, const uint8 wMode_,
  73394. const int parentPos,
  73395. const int parentSize) const throw()
  73396. {
  73397. if (wMode_ == proportionalSize)
  73398. wOut = roundToInt (w_ * parentSize);
  73399. else if (wMode_ == parentSizeMinusAbsolute)
  73400. wOut = jmax (0, parentSize - roundToInt (w_));
  73401. else
  73402. wOut = roundToInt (w_);
  73403. if ((xMode_ & proportionOfParentSize) != 0)
  73404. xOut = parentPos + x_ * parentSize;
  73405. else if ((xMode_ & absoluteFromParentBottomRight) != 0)
  73406. xOut = (parentPos + parentSize) - x_;
  73407. else if ((xMode_ & absoluteFromParentCentre) != 0)
  73408. xOut = x_ + (parentPos + parentSize / 2);
  73409. else
  73410. xOut = x_ + parentPos;
  73411. if ((xMode_ & anchorAtRightOrBottom) != 0)
  73412. xOut -= wOut;
  73413. else if ((xMode_ & anchorAtCentre) != 0)
  73414. xOut -= wOut / 2;
  73415. }
  73416. void PositionedRectangle::updatePosAndSize (double& xOut, double& wOut,
  73417. double x_, const double w_,
  73418. const uint8 xMode_, const uint8 wMode_,
  73419. const int parentPos,
  73420. const int parentSize) const throw()
  73421. {
  73422. if (wMode_ == proportionalSize)
  73423. {
  73424. if (parentSize > 0)
  73425. wOut = w_ / parentSize;
  73426. }
  73427. else if (wMode_ == parentSizeMinusAbsolute)
  73428. wOut = parentSize - w_;
  73429. else
  73430. wOut = w_;
  73431. if ((xMode_ & anchorAtRightOrBottom) != 0)
  73432. x_ += w_;
  73433. else if ((xMode_ & anchorAtCentre) != 0)
  73434. x_ += w_ / 2;
  73435. if ((xMode_ & proportionOfParentSize) != 0)
  73436. {
  73437. if (parentSize > 0)
  73438. xOut = (x_ - parentPos) / parentSize;
  73439. }
  73440. else if ((xMode_ & absoluteFromParentBottomRight) != 0)
  73441. xOut = (parentPos + parentSize) - x_;
  73442. else if ((xMode_ & absoluteFromParentCentre) != 0)
  73443. xOut = x_ - (parentPos + parentSize / 2);
  73444. else
  73445. xOut = x_ - parentPos;
  73446. }
  73447. END_JUCE_NAMESPACE
  73448. /*** End of inlined file: juce_PositionedRectangle.cpp ***/
  73449. /*** Start of inlined file: juce_RectangleList.cpp ***/
  73450. BEGIN_JUCE_NAMESPACE
  73451. RectangleList::RectangleList() throw()
  73452. {
  73453. }
  73454. RectangleList::RectangleList (const Rectangle<int>& rect)
  73455. {
  73456. if (! rect.isEmpty())
  73457. rects.add (rect);
  73458. }
  73459. RectangleList::RectangleList (const RectangleList& other)
  73460. : rects (other.rects)
  73461. {
  73462. }
  73463. RectangleList& RectangleList::operator= (const RectangleList& other)
  73464. {
  73465. rects = other.rects;
  73466. return *this;
  73467. }
  73468. RectangleList::~RectangleList()
  73469. {
  73470. }
  73471. void RectangleList::clear()
  73472. {
  73473. rects.clearQuick();
  73474. }
  73475. const Rectangle<int> RectangleList::getRectangle (const int index) const throw()
  73476. {
  73477. if (((unsigned int) index) < (unsigned int) rects.size())
  73478. return rects.getReference (index);
  73479. return Rectangle<int>();
  73480. }
  73481. bool RectangleList::isEmpty() const throw()
  73482. {
  73483. return rects.size() == 0;
  73484. }
  73485. RectangleList::Iterator::Iterator (const RectangleList& list) throw()
  73486. : current (0),
  73487. owner (list),
  73488. index (list.rects.size())
  73489. {
  73490. }
  73491. RectangleList::Iterator::~Iterator()
  73492. {
  73493. }
  73494. bool RectangleList::Iterator::next() throw()
  73495. {
  73496. if (--index >= 0)
  73497. {
  73498. current = & (owner.rects.getReference (index));
  73499. return true;
  73500. }
  73501. return false;
  73502. }
  73503. void RectangleList::add (const Rectangle<int>& rect)
  73504. {
  73505. if (! rect.isEmpty())
  73506. {
  73507. if (rects.size() == 0)
  73508. {
  73509. rects.add (rect);
  73510. }
  73511. else
  73512. {
  73513. bool anyOverlaps = false;
  73514. int i;
  73515. for (i = rects.size(); --i >= 0;)
  73516. {
  73517. Rectangle<int>& ourRect = rects.getReference (i);
  73518. if (rect.intersects (ourRect))
  73519. {
  73520. if (rect.contains (ourRect))
  73521. rects.remove (i);
  73522. else if (! ourRect.reduceIfPartlyContainedIn (rect))
  73523. anyOverlaps = true;
  73524. }
  73525. }
  73526. if (anyOverlaps && rects.size() > 0)
  73527. {
  73528. RectangleList r (rect);
  73529. for (i = rects.size(); --i >= 0;)
  73530. {
  73531. const Rectangle<int>& ourRect = rects.getReference (i);
  73532. if (rect.intersects (ourRect))
  73533. {
  73534. r.subtract (ourRect);
  73535. if (r.rects.size() == 0)
  73536. return;
  73537. }
  73538. }
  73539. for (i = r.getNumRectangles(); --i >= 0;)
  73540. rects.add (r.rects.getReference (i));
  73541. }
  73542. else
  73543. {
  73544. rects.add (rect);
  73545. }
  73546. }
  73547. }
  73548. }
  73549. void RectangleList::addWithoutMerging (const Rectangle<int>& rect)
  73550. {
  73551. if (! rect.isEmpty())
  73552. rects.add (rect);
  73553. }
  73554. void RectangleList::add (const int x, const int y, const int w, const int h)
  73555. {
  73556. if (rects.size() == 0)
  73557. {
  73558. if (w > 0 && h > 0)
  73559. rects.add (Rectangle<int> (x, y, w, h));
  73560. }
  73561. else
  73562. {
  73563. add (Rectangle<int> (x, y, w, h));
  73564. }
  73565. }
  73566. void RectangleList::add (const RectangleList& other)
  73567. {
  73568. for (int i = 0; i < other.rects.size(); ++i)
  73569. add (other.rects.getReference (i));
  73570. }
  73571. void RectangleList::subtract (const Rectangle<int>& rect)
  73572. {
  73573. const int originalNumRects = rects.size();
  73574. if (originalNumRects > 0)
  73575. {
  73576. const int x1 = rect.x;
  73577. const int y1 = rect.y;
  73578. const int x2 = x1 + rect.w;
  73579. const int y2 = y1 + rect.h;
  73580. for (int i = getNumRectangles(); --i >= 0;)
  73581. {
  73582. Rectangle<int>& r = rects.getReference (i);
  73583. const int rx1 = r.x;
  73584. const int ry1 = r.y;
  73585. const int rx2 = rx1 + r.w;
  73586. const int ry2 = ry1 + r.h;
  73587. if (! (x2 <= rx1 || x1 >= rx2 || y2 <= ry1 || y1 >= ry2))
  73588. {
  73589. if (x1 > rx1 && x1 < rx2)
  73590. {
  73591. if (y1 <= ry1 && y2 >= ry2 && x2 >= rx2)
  73592. {
  73593. r.w = x1 - rx1;
  73594. }
  73595. else
  73596. {
  73597. r.x = x1;
  73598. r.w = rx2 - x1;
  73599. rects.insert (i + 1, Rectangle<int> (rx1, ry1, x1 - rx1, ry2 - ry1));
  73600. i += 2;
  73601. }
  73602. }
  73603. else if (x2 > rx1 && x2 < rx2)
  73604. {
  73605. r.x = x2;
  73606. r.w = rx2 - x2;
  73607. if (y1 > ry1 || y2 < ry2 || x1 > rx1)
  73608. {
  73609. rects.insert (i + 1, Rectangle<int> (rx1, ry1, x2 - rx1, ry2 - ry1));
  73610. i += 2;
  73611. }
  73612. }
  73613. else if (y1 > ry1 && y1 < ry2)
  73614. {
  73615. if (x1 <= rx1 && x2 >= rx2 && y2 >= ry2)
  73616. {
  73617. r.h = y1 - ry1;
  73618. }
  73619. else
  73620. {
  73621. r.y = y1;
  73622. r.h = ry2 - y1;
  73623. rects.insert (i + 1, Rectangle<int> (rx1, ry1, rx2 - rx1, y1 - ry1));
  73624. i += 2;
  73625. }
  73626. }
  73627. else if (y2 > ry1 && y2 < ry2)
  73628. {
  73629. r.y = y2;
  73630. r.h = ry2 - y2;
  73631. if (x1 > rx1 || x2 < rx2 || y1 > ry1)
  73632. {
  73633. rects.insert (i + 1, Rectangle<int> (rx1, ry1, rx2 - rx1, y2 - ry1));
  73634. i += 2;
  73635. }
  73636. }
  73637. else
  73638. {
  73639. rects.remove (i);
  73640. }
  73641. }
  73642. }
  73643. if (rects.size() > originalNumRects + 10)
  73644. consolidate();
  73645. }
  73646. }
  73647. void RectangleList::subtract (const RectangleList& otherList)
  73648. {
  73649. for (int i = otherList.rects.size(); --i >= 0;)
  73650. subtract (otherList.rects.getReference (i));
  73651. }
  73652. bool RectangleList::clipTo (const Rectangle<int>& rect)
  73653. {
  73654. bool notEmpty = false;
  73655. if (rect.isEmpty())
  73656. {
  73657. clear();
  73658. }
  73659. else
  73660. {
  73661. for (int i = rects.size(); --i >= 0;)
  73662. {
  73663. Rectangle<int>& r = rects.getReference (i);
  73664. if (! rect.intersectRectangle (r.x, r.y, r.w, r.h))
  73665. rects.remove (i);
  73666. else
  73667. notEmpty = true;
  73668. }
  73669. }
  73670. return notEmpty;
  73671. }
  73672. bool RectangleList::clipTo (const RectangleList& other)
  73673. {
  73674. if (rects.size() == 0)
  73675. return false;
  73676. RectangleList result;
  73677. for (int j = 0; j < rects.size(); ++j)
  73678. {
  73679. const Rectangle<int>& rect = rects.getReference (j);
  73680. for (int i = other.rects.size(); --i >= 0;)
  73681. {
  73682. Rectangle<int> r (other.rects.getReference (i));
  73683. if (rect.intersectRectangle (r.x, r.y, r.w, r.h))
  73684. result.rects.add (r);
  73685. }
  73686. }
  73687. swapWith (result);
  73688. return ! isEmpty();
  73689. }
  73690. bool RectangleList::getIntersectionWith (const Rectangle<int>& rect, RectangleList& destRegion) const
  73691. {
  73692. destRegion.clear();
  73693. if (! rect.isEmpty())
  73694. {
  73695. for (int i = rects.size(); --i >= 0;)
  73696. {
  73697. Rectangle<int> r (rects.getReference (i));
  73698. if (rect.intersectRectangle (r.x, r.y, r.w, r.h))
  73699. destRegion.rects.add (r);
  73700. }
  73701. }
  73702. return destRegion.rects.size() > 0;
  73703. }
  73704. void RectangleList::swapWith (RectangleList& otherList) throw()
  73705. {
  73706. rects.swapWithArray (otherList.rects);
  73707. }
  73708. void RectangleList::consolidate()
  73709. {
  73710. int i;
  73711. for (i = 0; i < getNumRectangles() - 1; ++i)
  73712. {
  73713. Rectangle<int>& r = rects.getReference (i);
  73714. const int rx1 = r.x;
  73715. const int ry1 = r.y;
  73716. const int rx2 = rx1 + r.w;
  73717. const int ry2 = ry1 + r.h;
  73718. for (int j = rects.size(); --j > i;)
  73719. {
  73720. Rectangle<int>& r2 = rects.getReference (j);
  73721. const int jrx1 = r2.x;
  73722. const int jry1 = r2.y;
  73723. const int jrx2 = jrx1 + r2.w;
  73724. const int jry2 = jry1 + r2.h;
  73725. // if the vertical edges of any blocks are touching and their horizontals don't
  73726. // line up, split them horizontally..
  73727. if (jrx1 == rx2 || jrx2 == rx1)
  73728. {
  73729. if (jry1 > ry1 && jry1 < ry2)
  73730. {
  73731. r.h = jry1 - ry1;
  73732. rects.add (Rectangle<int> (rx1, jry1, rx2 - rx1, ry2 - jry1));
  73733. i = -1;
  73734. break;
  73735. }
  73736. if (jry2 > ry1 && jry2 < ry2)
  73737. {
  73738. r.h = jry2 - ry1;
  73739. rects.add (Rectangle<int> (rx1, jry2, rx2 - rx1, ry2 - jry2));
  73740. i = -1;
  73741. break;
  73742. }
  73743. else if (ry1 > jry1 && ry1 < jry2)
  73744. {
  73745. r2.h = ry1 - jry1;
  73746. rects.add (Rectangle<int> (jrx1, ry1, jrx2 - jrx1, jry2 - ry1));
  73747. i = -1;
  73748. break;
  73749. }
  73750. else if (ry2 > jry1 && ry2 < jry2)
  73751. {
  73752. r2.h = ry2 - jry1;
  73753. rects.add (Rectangle<int> (jrx1, ry2, jrx2 - jrx1, jry2 - ry2));
  73754. i = -1;
  73755. break;
  73756. }
  73757. }
  73758. }
  73759. }
  73760. for (i = 0; i < rects.size() - 1; ++i)
  73761. {
  73762. Rectangle<int>& r = rects.getReference (i);
  73763. for (int j = rects.size(); --j > i;)
  73764. {
  73765. if (r.enlargeIfAdjacent (rects.getReference (j)))
  73766. {
  73767. rects.remove (j);
  73768. i = -1;
  73769. break;
  73770. }
  73771. }
  73772. }
  73773. }
  73774. bool RectangleList::containsPoint (const int x, const int y) const throw()
  73775. {
  73776. for (int i = getNumRectangles(); --i >= 0;)
  73777. if (rects.getReference (i).contains (x, y))
  73778. return true;
  73779. return false;
  73780. }
  73781. bool RectangleList::containsRectangle (const Rectangle<int>& rectangleToCheck) const
  73782. {
  73783. if (rects.size() > 1)
  73784. {
  73785. RectangleList r (rectangleToCheck);
  73786. for (int i = rects.size(); --i >= 0;)
  73787. {
  73788. r.subtract (rects.getReference (i));
  73789. if (r.rects.size() == 0)
  73790. return true;
  73791. }
  73792. }
  73793. else if (rects.size() > 0)
  73794. {
  73795. return rects.getReference (0).contains (rectangleToCheck);
  73796. }
  73797. return false;
  73798. }
  73799. bool RectangleList::intersectsRectangle (const Rectangle<int>& rectangleToCheck) const throw()
  73800. {
  73801. for (int i = rects.size(); --i >= 0;)
  73802. if (rects.getReference (i).intersects (rectangleToCheck))
  73803. return true;
  73804. return false;
  73805. }
  73806. bool RectangleList::intersects (const RectangleList& other) const throw()
  73807. {
  73808. for (int i = rects.size(); --i >= 0;)
  73809. if (other.intersectsRectangle (rects.getReference (i)))
  73810. return true;
  73811. return false;
  73812. }
  73813. const Rectangle<int> RectangleList::getBounds() const throw()
  73814. {
  73815. if (rects.size() <= 1)
  73816. {
  73817. if (rects.size() == 0)
  73818. return Rectangle<int>();
  73819. else
  73820. return rects.getReference (0);
  73821. }
  73822. else
  73823. {
  73824. const Rectangle<int>& r = rects.getReference (0);
  73825. int minX = r.x;
  73826. int minY = r.y;
  73827. int maxX = minX + r.w;
  73828. int maxY = minY + r.h;
  73829. for (int i = rects.size(); --i > 0;)
  73830. {
  73831. const Rectangle<int>& r2 = rects.getReference (i);
  73832. minX = jmin (minX, r2.x);
  73833. minY = jmin (minY, r2.y);
  73834. maxX = jmax (maxX, r2.getRight());
  73835. maxY = jmax (maxY, r2.getBottom());
  73836. }
  73837. return Rectangle<int> (minX, minY, maxX - minX, maxY - minY);
  73838. }
  73839. }
  73840. void RectangleList::offsetAll (const int dx, const int dy) throw()
  73841. {
  73842. for (int i = rects.size(); --i >= 0;)
  73843. {
  73844. Rectangle<int>& r = rects.getReference (i);
  73845. r.x += dx;
  73846. r.y += dy;
  73847. }
  73848. }
  73849. const Path RectangleList::toPath() const
  73850. {
  73851. Path p;
  73852. for (int i = rects.size(); --i >= 0;)
  73853. {
  73854. const Rectangle<int>& r = rects.getReference (i);
  73855. p.addRectangle ((float) r.x,
  73856. (float) r.y,
  73857. (float) r.w,
  73858. (float) r.h);
  73859. }
  73860. return p;
  73861. }
  73862. END_JUCE_NAMESPACE
  73863. /*** End of inlined file: juce_RectangleList.cpp ***/
  73864. /*** Start of inlined file: juce_Image.cpp ***/
  73865. BEGIN_JUCE_NAMESPACE
  73866. static const int fullAlphaThreshold = 253;
  73867. Image::Image (const PixelFormat format_,
  73868. const int imageWidth_,
  73869. const int imageHeight_)
  73870. : format (format_),
  73871. imageWidth (imageWidth_),
  73872. imageHeight (imageHeight_),
  73873. imageData (0)
  73874. {
  73875. jassert (format_ == RGB || format_ == ARGB || format_ == SingleChannel);
  73876. jassert (imageWidth_ > 0 && imageHeight_ > 0); // it's illegal to create a zero-sized image - the
  73877. // actual image will be at least 1x1.
  73878. }
  73879. Image::Image (const PixelFormat format_,
  73880. const int imageWidth_,
  73881. const int imageHeight_,
  73882. const bool clearImage)
  73883. : format (format_),
  73884. imageWidth (imageWidth_),
  73885. imageHeight (imageHeight_)
  73886. {
  73887. jassert (format_ == RGB || format_ == ARGB || format_ == SingleChannel);
  73888. jassert (imageWidth_ > 0 && imageHeight_ > 0); // it's illegal to create a zero-sized image - the
  73889. // actual image will be at least 1x1.
  73890. pixelStride = (format == RGB) ? 3 : ((format == ARGB) ? 4 : 1);
  73891. lineStride = (pixelStride * jmax (1, imageWidth_) + 3) & ~3;
  73892. imageDataAllocated.allocate (lineStride * jmax (1, imageHeight_), clearImage);
  73893. imageData = imageDataAllocated;
  73894. }
  73895. Image::Image (const Image& other)
  73896. : format (other.format),
  73897. imageWidth (other.imageWidth),
  73898. imageHeight (other.imageHeight)
  73899. {
  73900. pixelStride = (format == RGB) ? 3 : ((format == ARGB) ? 4 : 1);
  73901. lineStride = (pixelStride * jmax (1, imageWidth) + 3) & ~3;
  73902. imageDataAllocated.malloc (lineStride * jmax (1, imageHeight));
  73903. imageData = imageDataAllocated;
  73904. BitmapData srcData (other, 0, 0, imageWidth, imageHeight);
  73905. setPixelData (0, 0, imageWidth, imageHeight, srcData.data, srcData.lineStride);
  73906. }
  73907. Image::~Image()
  73908. {
  73909. }
  73910. LowLevelGraphicsContext* Image::createLowLevelContext()
  73911. {
  73912. return new LowLevelGraphicsSoftwareRenderer (*this);
  73913. }
  73914. Image::BitmapData::BitmapData (Image& image, const int x, const int y, const int w, const int h, const bool /*makeWritable*/)
  73915. : data (image.imageData + image.lineStride * y + image.pixelStride * x),
  73916. pixelFormat (image.getFormat()),
  73917. lineStride (image.lineStride),
  73918. pixelStride (image.pixelStride),
  73919. width (w),
  73920. height (h)
  73921. {
  73922. jassert (x >= 0 && y >= 0 && w > 0 && h > 0 && x + w <= image.getWidth() && y + h <= image.getHeight());
  73923. }
  73924. Image::BitmapData::BitmapData (const Image& image, const int x, const int y, const int w, const int h)
  73925. : data (image.imageData + image.lineStride * y + image.pixelStride * x),
  73926. pixelFormat (image.getFormat()),
  73927. lineStride (image.lineStride),
  73928. pixelStride (image.pixelStride),
  73929. width (w),
  73930. height (h)
  73931. {
  73932. jassert (x >= 0 && y >= 0 && w > 0 && h > 0 && x + w <= image.getWidth() && y + h <= image.getHeight());
  73933. }
  73934. Image::BitmapData::~BitmapData()
  73935. {
  73936. }
  73937. void Image::setPixelData (int x, int y, int w, int h,
  73938. const uint8* const sourcePixelData, const int sourceLineStride)
  73939. {
  73940. jassert (x >= 0 && y >= 0 && w > 0 && h > 0 && x + w <= imageWidth && y + h <= imageHeight);
  73941. if (Rectangle<int>::intersectRectangles (x, y, w, h, 0, 0, imageWidth, imageHeight))
  73942. {
  73943. const BitmapData dest (*this, x, y, w, h, true);
  73944. for (int i = 0; i < h; ++i)
  73945. {
  73946. memcpy (dest.getLinePointer(i),
  73947. sourcePixelData + sourceLineStride * i,
  73948. w * dest.pixelStride);
  73949. }
  73950. }
  73951. }
  73952. void Image::clear (const Rectangle<int>& area, const Colour& colourToClearTo)
  73953. {
  73954. const Rectangle<int> clipped (area.getIntersection (getBounds()));
  73955. if (! clipped.isEmpty())
  73956. {
  73957. const PixelARGB col (colourToClearTo.getPixelARGB());
  73958. const BitmapData destData (*this, clipped.getX(), clipped.getY(), clipped.getWidth(), clipped.getHeight(), true);
  73959. uint8* dest = destData.data;
  73960. int dh = clipped.getHeight();
  73961. while (--dh >= 0)
  73962. {
  73963. uint8* line = dest;
  73964. dest += destData.lineStride;
  73965. if (isARGB())
  73966. {
  73967. for (int x = clipped.getWidth(); --x >= 0;)
  73968. {
  73969. ((PixelARGB*) line)->set (col);
  73970. line += destData.pixelStride;
  73971. }
  73972. }
  73973. else if (isRGB())
  73974. {
  73975. for (int x = clipped.getWidth(); --x >= 0;)
  73976. {
  73977. ((PixelRGB*) line)->set (col);
  73978. line += destData.pixelStride;
  73979. }
  73980. }
  73981. else
  73982. {
  73983. for (int x = clipped.getWidth(); --x >= 0;)
  73984. {
  73985. *line = col.getAlpha();
  73986. line += destData.pixelStride;
  73987. }
  73988. }
  73989. }
  73990. }
  73991. }
  73992. Image* Image::createCopy (int newWidth, int newHeight,
  73993. const Graphics::ResamplingQuality quality) const
  73994. {
  73995. if (newWidth < 0)
  73996. newWidth = imageWidth;
  73997. if (newHeight < 0)
  73998. newHeight = imageHeight;
  73999. Image* const newImage = Image::createNativeImage (format, newWidth, newHeight, true);
  74000. Graphics g (*newImage);
  74001. g.setImageResamplingQuality (quality);
  74002. g.drawImage (this,
  74003. 0, 0, newWidth, newHeight,
  74004. 0, 0, imageWidth, imageHeight,
  74005. false);
  74006. return newImage;
  74007. }
  74008. Image* Image::createCopyOfAlphaChannel() const
  74009. {
  74010. jassert (format != SingleChannel);
  74011. Image* const newImage = Image::createNativeImage (SingleChannel, imageWidth, imageHeight, false);
  74012. if (! hasAlphaChannel())
  74013. {
  74014. newImage->clear (getBounds(), Colours::black);
  74015. }
  74016. else
  74017. {
  74018. const BitmapData destData (*newImage, 0, 0, imageWidth, imageHeight, true);
  74019. const BitmapData srcData (*this, 0, 0, imageWidth, imageHeight);
  74020. for (int y = 0; y < imageHeight; ++y)
  74021. {
  74022. const PixelARGB* src = (const PixelARGB*) srcData.getLinePointer(y);
  74023. uint8* dst = destData.getLinePointer (y);
  74024. for (int x = imageWidth; --x >= 0;)
  74025. {
  74026. *dst++ = src->getAlpha();
  74027. ++src;
  74028. }
  74029. }
  74030. }
  74031. return newImage;
  74032. }
  74033. const Colour Image::getPixelAt (const int x, const int y) const
  74034. {
  74035. Colour c;
  74036. if (((unsigned int) x) < (unsigned int) imageWidth
  74037. && ((unsigned int) y) < (unsigned int) imageHeight)
  74038. {
  74039. const BitmapData srcData (*this, x, y, 1, 1);
  74040. if (isARGB())
  74041. {
  74042. PixelARGB p (*(const PixelARGB*) srcData.data);
  74043. p.unpremultiply();
  74044. c = Colour (p.getARGB());
  74045. }
  74046. else if (isRGB())
  74047. c = Colour (((const PixelRGB*) srcData.data)->getARGB());
  74048. else
  74049. c = Colour ((uint8) 0, (uint8) 0, (uint8) 0, *(srcData.data));
  74050. }
  74051. return c;
  74052. }
  74053. void Image::setPixelAt (const int x, const int y,
  74054. const Colour& colour)
  74055. {
  74056. if (((unsigned int) x) < (unsigned int) imageWidth
  74057. && ((unsigned int) y) < (unsigned int) imageHeight)
  74058. {
  74059. const BitmapData destData (*this, x, y, 1, 1, true);
  74060. const PixelARGB col (colour.getPixelARGB());
  74061. if (isARGB())
  74062. ((PixelARGB*) destData.data)->set (col);
  74063. else if (isRGB())
  74064. ((PixelRGB*) destData.data)->set (col);
  74065. else
  74066. *(destData.data) = col.getAlpha();
  74067. }
  74068. }
  74069. void Image::multiplyAlphaAt (const int x, const int y,
  74070. const float multiplier)
  74071. {
  74072. if (((unsigned int) x) < (unsigned int) imageWidth
  74073. && ((unsigned int) y) < (unsigned int) imageHeight
  74074. && hasAlphaChannel())
  74075. {
  74076. const BitmapData destData (*this, x, y, 1, 1, true);
  74077. if (isARGB())
  74078. ((PixelARGB*) destData.data)->multiplyAlpha (multiplier);
  74079. else
  74080. *(destData.data) = (uint8) (*(destData.data) * multiplier);
  74081. }
  74082. }
  74083. void Image::multiplyAllAlphas (const float amountToMultiplyBy)
  74084. {
  74085. if (hasAlphaChannel())
  74086. {
  74087. const BitmapData destData (*this, 0, 0, getWidth(), getHeight(), true);
  74088. if (isARGB())
  74089. {
  74090. for (int y = 0; y < imageHeight; ++y)
  74091. {
  74092. uint8* p = destData.getLinePointer (y);
  74093. for (int x = 0; x < imageWidth; ++x)
  74094. {
  74095. ((PixelARGB*) p)->multiplyAlpha (amountToMultiplyBy);
  74096. p += destData.pixelStride;
  74097. }
  74098. }
  74099. }
  74100. else
  74101. {
  74102. for (int y = 0; y < imageHeight; ++y)
  74103. {
  74104. uint8* p = destData.getLinePointer (y);
  74105. for (int x = 0; x < imageWidth; ++x)
  74106. {
  74107. *p = (uint8) (*p * amountToMultiplyBy);
  74108. p += destData.pixelStride;
  74109. }
  74110. }
  74111. }
  74112. }
  74113. else
  74114. {
  74115. jassertfalse // can't do this without an alpha-channel!
  74116. }
  74117. }
  74118. void Image::desaturate()
  74119. {
  74120. if (isARGB() || isRGB())
  74121. {
  74122. const BitmapData destData (*this, 0, 0, getWidth(), getHeight(), true);
  74123. if (isARGB())
  74124. {
  74125. for (int y = 0; y < imageHeight; ++y)
  74126. {
  74127. uint8* p = destData.getLinePointer (y);
  74128. for (int x = 0; x < imageWidth; ++x)
  74129. {
  74130. ((PixelARGB*) p)->desaturate();
  74131. p += destData.pixelStride;
  74132. }
  74133. }
  74134. }
  74135. else
  74136. {
  74137. for (int y = 0; y < imageHeight; ++y)
  74138. {
  74139. uint8* p = destData.getLinePointer (y);
  74140. for (int x = 0; x < imageWidth; ++x)
  74141. {
  74142. ((PixelRGB*) p)->desaturate();
  74143. p += destData.pixelStride;
  74144. }
  74145. }
  74146. }
  74147. }
  74148. }
  74149. void Image::createSolidAreaMask (RectangleList& result, const float alphaThreshold) const
  74150. {
  74151. if (hasAlphaChannel())
  74152. {
  74153. const uint8 threshold = (uint8) jlimit (0, 255, roundToInt (alphaThreshold * 255.0f));
  74154. SparseSet<int> pixelsOnRow;
  74155. const BitmapData srcData (*this, 0, 0, getWidth(), getHeight());
  74156. for (int y = 0; y < imageHeight; ++y)
  74157. {
  74158. pixelsOnRow.clear();
  74159. const uint8* lineData = srcData.getLinePointer (y);
  74160. if (isARGB())
  74161. {
  74162. for (int x = 0; x < imageWidth; ++x)
  74163. {
  74164. if (((const PixelARGB*) lineData)->getAlpha() >= threshold)
  74165. pixelsOnRow.addRange (Range<int> (x, x + 1));
  74166. lineData += srcData.pixelStride;
  74167. }
  74168. }
  74169. else
  74170. {
  74171. for (int x = 0; x < imageWidth; ++x)
  74172. {
  74173. if (*lineData >= threshold)
  74174. pixelsOnRow.addRange (Range<int> (x, x + 1));
  74175. lineData += srcData.pixelStride;
  74176. }
  74177. }
  74178. for (int i = 0; i < pixelsOnRow.getNumRanges(); ++i)
  74179. {
  74180. const Range<int> range (pixelsOnRow.getRange (i));
  74181. result.add (Rectangle<int> (range.getStart(), y, range.getLength(), 1));
  74182. }
  74183. result.consolidate();
  74184. }
  74185. }
  74186. else
  74187. {
  74188. result.add (0, 0, imageWidth, imageHeight);
  74189. }
  74190. }
  74191. void Image::moveImageSection (int dx, int dy,
  74192. int sx, int sy,
  74193. int w, int h)
  74194. {
  74195. if (dx < 0)
  74196. {
  74197. w += dx;
  74198. sx -= dx;
  74199. dx = 0;
  74200. }
  74201. if (dy < 0)
  74202. {
  74203. h += dy;
  74204. sy -= dy;
  74205. dy = 0;
  74206. }
  74207. if (sx < 0)
  74208. {
  74209. w += sx;
  74210. dx -= sx;
  74211. sx = 0;
  74212. }
  74213. if (sy < 0)
  74214. {
  74215. h += sy;
  74216. dy -= sy;
  74217. sy = 0;
  74218. }
  74219. const int minX = jmin (dx, sx);
  74220. const int minY = jmin (dy, sy);
  74221. w = jmin (w, getWidth() - jmax (sx, dx));
  74222. h = jmin (h, getHeight() - jmax (sy, dy));
  74223. if (w > 0 && h > 0)
  74224. {
  74225. const int maxX = jmax (dx, sx) + w;
  74226. const int maxY = jmax (dy, sy) + h;
  74227. const BitmapData destData (*this, minX, minY, maxX - minX, maxY - minY, true);
  74228. uint8* dst = destData.getPixelPointer (dx - minX, dy - minY);
  74229. const uint8* src = destData.getPixelPointer (sx - minX, sy - minY);
  74230. const int lineSize = destData.pixelStride * w;
  74231. if (dy > sy)
  74232. {
  74233. while (--h >= 0)
  74234. {
  74235. const int offset = h * destData.lineStride;
  74236. memmove (dst + offset, src + offset, lineSize);
  74237. }
  74238. }
  74239. else if (dst != src)
  74240. {
  74241. while (--h >= 0)
  74242. {
  74243. memmove (dst, src, lineSize);
  74244. dst += destData.lineStride;
  74245. src += destData.lineStride;
  74246. }
  74247. }
  74248. }
  74249. }
  74250. END_JUCE_NAMESPACE
  74251. /*** End of inlined file: juce_Image.cpp ***/
  74252. /*** Start of inlined file: juce_ImageCache.cpp ***/
  74253. BEGIN_JUCE_NAMESPACE
  74254. struct ImageCache::Item
  74255. {
  74256. ScopedPointer <Image> image;
  74257. int64 hashCode;
  74258. int refCount;
  74259. uint32 releaseTime;
  74260. juce_UseDebuggingNewOperator
  74261. };
  74262. ImageCache* ImageCache::instance = 0;
  74263. int ImageCache::cacheTimeout = 5000;
  74264. ImageCache::ImageCache()
  74265. {
  74266. }
  74267. ImageCache::~ImageCache()
  74268. {
  74269. jassert (instance == this);
  74270. instance = 0;
  74271. }
  74272. Image* ImageCache::getFromHashCode (const int64 hashCode)
  74273. {
  74274. if (instance != 0)
  74275. {
  74276. const ScopedLock sl (instance->lock);
  74277. for (int i = instance->images.size(); --i >= 0;)
  74278. {
  74279. Item* const ci = instance->images.getUnchecked(i);
  74280. if (ci->hashCode == hashCode)
  74281. {
  74282. ci->refCount++;
  74283. return ci->image;
  74284. }
  74285. }
  74286. }
  74287. return 0;
  74288. }
  74289. void ImageCache::addImageToCache (Image* const image, const int64 hashCode)
  74290. {
  74291. if (image != 0)
  74292. {
  74293. if (instance == 0)
  74294. instance = new ImageCache();
  74295. Item* const newC = new Item();
  74296. newC->hashCode = hashCode;
  74297. newC->image = image;
  74298. newC->refCount = 1;
  74299. newC->releaseTime = 0;
  74300. const ScopedLock sl (instance->lock);
  74301. instance->images.add (newC);
  74302. }
  74303. }
  74304. void ImageCache::release (Image* const imageToRelease)
  74305. {
  74306. if (imageToRelease != 0 && instance != 0)
  74307. {
  74308. const ScopedLock sl (instance->lock);
  74309. for (int i = instance->images.size(); --i >= 0;)
  74310. {
  74311. Item* const ci = instance->images.getUnchecked(i);
  74312. if (static_cast <Image*> (ci->image) == imageToRelease)
  74313. {
  74314. if (--(ci->refCount) == 0)
  74315. ci->releaseTime = Time::getApproximateMillisecondCounter();
  74316. if (! instance->isTimerRunning())
  74317. instance->startTimer (999);
  74318. break;
  74319. }
  74320. }
  74321. }
  74322. }
  74323. void ImageCache::releaseOrDelete (Image* const imageToRelease)
  74324. {
  74325. if (isImageInCache (imageToRelease))
  74326. release (imageToRelease);
  74327. else
  74328. delete imageToRelease;
  74329. }
  74330. bool ImageCache::isImageInCache (Image* const imageToLookFor)
  74331. {
  74332. if (instance != 0)
  74333. {
  74334. const ScopedLock sl (instance->lock);
  74335. for (int i = instance->images.size(); --i >= 0;)
  74336. if (static_cast <Image*> (instance->images.getUnchecked(i)->image) == imageToLookFor)
  74337. return true;
  74338. }
  74339. return false;
  74340. }
  74341. void ImageCache::incReferenceCount (Image* const image)
  74342. {
  74343. if (instance != 0)
  74344. {
  74345. const ScopedLock sl (instance->lock);
  74346. for (int i = instance->images.size(); --i >= 0;)
  74347. {
  74348. Item* const ci = instance->images.getUnchecked(i);
  74349. if (static_cast <Image*> (ci->image) == image)
  74350. {
  74351. ci->refCount++;
  74352. return;
  74353. }
  74354. }
  74355. }
  74356. jassertfalse // (trying to inc the ref count of an image that's not in the cache)
  74357. }
  74358. void ImageCache::timerCallback()
  74359. {
  74360. int numberStillNeedingReleasing = 0;
  74361. const uint32 now = Time::getApproximateMillisecondCounter();
  74362. const ScopedLock sl (lock);
  74363. for (int i = images.size(); --i >= 0;)
  74364. {
  74365. Item* const ci = images.getUnchecked(i);
  74366. if (ci->refCount <= 0)
  74367. {
  74368. if (now > ci->releaseTime + cacheTimeout
  74369. || now < ci->releaseTime - 1000)
  74370. {
  74371. images.remove (i);
  74372. }
  74373. else
  74374. {
  74375. ++numberStillNeedingReleasing;
  74376. }
  74377. }
  74378. }
  74379. if (numberStillNeedingReleasing == 0)
  74380. stopTimer();
  74381. }
  74382. Image* ImageCache::getFromFile (const File& file)
  74383. {
  74384. const int64 hashCode = file.hashCode64();
  74385. Image* image = getFromHashCode (hashCode);
  74386. if (image == 0)
  74387. {
  74388. image = ImageFileFormat::loadFrom (file);
  74389. addImageToCache (image, hashCode);
  74390. }
  74391. return image;
  74392. }
  74393. Image* ImageCache::getFromMemory (const void* imageData, const int dataSize)
  74394. {
  74395. const int64 hashCode = (int64) (pointer_sized_int) imageData;
  74396. Image* image = getFromHashCode (hashCode);
  74397. if (image == 0)
  74398. {
  74399. image = ImageFileFormat::loadFrom (imageData, dataSize);
  74400. addImageToCache (image, hashCode);
  74401. }
  74402. return image;
  74403. }
  74404. void ImageCache::setCacheTimeout (const int millisecs)
  74405. {
  74406. cacheTimeout = millisecs;
  74407. }
  74408. END_JUCE_NAMESPACE
  74409. /*** End of inlined file: juce_ImageCache.cpp ***/
  74410. /*** Start of inlined file: juce_ImageConvolutionKernel.cpp ***/
  74411. BEGIN_JUCE_NAMESPACE
  74412. ImageConvolutionKernel::ImageConvolutionKernel (const int size_)
  74413. : values (size_ * size_),
  74414. size (size_)
  74415. {
  74416. clear();
  74417. }
  74418. ImageConvolutionKernel::~ImageConvolutionKernel()
  74419. {
  74420. }
  74421. float ImageConvolutionKernel::getKernelValue (const int x, const int y) const throw()
  74422. {
  74423. if (((unsigned int) x) < (unsigned int) size
  74424. && ((unsigned int) y) < (unsigned int) size)
  74425. {
  74426. return values [x + y * size];
  74427. }
  74428. else
  74429. {
  74430. jassertfalse;
  74431. return 0;
  74432. }
  74433. }
  74434. void ImageConvolutionKernel::setKernelValue (const int x, const int y, const float value) throw()
  74435. {
  74436. if (((unsigned int) x) < (unsigned int) size
  74437. && ((unsigned int) y) < (unsigned int) size)
  74438. {
  74439. values [x + y * size] = value;
  74440. }
  74441. else
  74442. {
  74443. jassertfalse;
  74444. }
  74445. }
  74446. void ImageConvolutionKernel::clear()
  74447. {
  74448. for (int i = size * size; --i >= 0;)
  74449. values[i] = 0;
  74450. }
  74451. void ImageConvolutionKernel::setOverallSum (const float desiredTotalSum)
  74452. {
  74453. double currentTotal = 0.0;
  74454. for (int i = size * size; --i >= 0;)
  74455. currentTotal += values[i];
  74456. rescaleAllValues ((float) (desiredTotalSum / currentTotal));
  74457. }
  74458. void ImageConvolutionKernel::rescaleAllValues (const float multiplier)
  74459. {
  74460. for (int i = size * size; --i >= 0;)
  74461. values[i] *= multiplier;
  74462. }
  74463. void ImageConvolutionKernel::createGaussianBlur (const float radius)
  74464. {
  74465. const double radiusFactor = -1.0 / (radius * radius * 2);
  74466. const int centre = size >> 1;
  74467. for (int y = size; --y >= 0;)
  74468. {
  74469. for (int x = size; --x >= 0;)
  74470. {
  74471. const int cx = x - centre;
  74472. const int cy = y - centre;
  74473. values [x + y * size] = (float) exp (radiusFactor * (cx * cx + cy * cy));
  74474. }
  74475. }
  74476. setOverallSum (1.0f);
  74477. }
  74478. void ImageConvolutionKernel::applyToImage (Image& destImage,
  74479. const Image* sourceImage,
  74480. const Rectangle<int>& destinationArea) const
  74481. {
  74482. ScopedPointer <Image> imageCreated;
  74483. if (sourceImage == 0)
  74484. {
  74485. sourceImage = imageCreated = destImage.createCopy();
  74486. }
  74487. else
  74488. {
  74489. jassert (sourceImage->getWidth() == destImage.getWidth()
  74490. && sourceImage->getHeight() == destImage.getHeight()
  74491. && sourceImage->getFormat() == destImage.getFormat());
  74492. if (sourceImage->getWidth() != destImage.getWidth()
  74493. || sourceImage->getHeight() != destImage.getHeight()
  74494. || sourceImage->getFormat() != destImage.getFormat())
  74495. return;
  74496. }
  74497. const Rectangle<int> area (destinationArea.getIntersection (destImage.getBounds()));
  74498. if (area.isEmpty())
  74499. return;
  74500. const int right = area.getRight();
  74501. const int bottom = area.getBottom();
  74502. const Image::BitmapData destData (destImage, area.getX(), area.getY(), area.getWidth(), area.getHeight(), true);
  74503. uint8* line = destData.data;
  74504. const Image::BitmapData srcData (*sourceImage, 0, 0, sourceImage->getWidth(), sourceImage->getHeight());
  74505. if (destData.pixelStride == 4)
  74506. {
  74507. for (int y = area.getY(); y < bottom; ++y)
  74508. {
  74509. uint8* dest = line;
  74510. line += destData.lineStride;
  74511. for (int x = area.getX(); x < right; ++x)
  74512. {
  74513. float c1 = 0;
  74514. float c2 = 0;
  74515. float c3 = 0;
  74516. float c4 = 0;
  74517. for (int yy = 0; yy < size; ++yy)
  74518. {
  74519. const int sy = y + yy - (size >> 1);
  74520. if (sy >= srcData.height)
  74521. break;
  74522. if (sy >= 0)
  74523. {
  74524. int sx = x - (size >> 1);
  74525. const uint8* src = srcData.getPixelPointer (sx, sy);
  74526. for (int xx = 0; xx < size; ++xx)
  74527. {
  74528. if (sx >= srcData.width)
  74529. break;
  74530. if (sx >= 0)
  74531. {
  74532. const float kernelMult = values [xx + yy * size];
  74533. c1 += kernelMult * *src++;
  74534. c2 += kernelMult * *src++;
  74535. c3 += kernelMult * *src++;
  74536. c4 += kernelMult * *src++;
  74537. }
  74538. else
  74539. {
  74540. src += 4;
  74541. }
  74542. ++sx;
  74543. }
  74544. }
  74545. }
  74546. *dest++ = (uint8) jmin (0xff, roundToInt (c1));
  74547. *dest++ = (uint8) jmin (0xff, roundToInt (c2));
  74548. *dest++ = (uint8) jmin (0xff, roundToInt (c3));
  74549. *dest++ = (uint8) jmin (0xff, roundToInt (c4));
  74550. }
  74551. }
  74552. }
  74553. else if (destData.pixelStride == 3)
  74554. {
  74555. for (int y = area.getY(); y < bottom; ++y)
  74556. {
  74557. uint8* dest = line;
  74558. line += destData.lineStride;
  74559. for (int x = area.getX(); x < right; ++x)
  74560. {
  74561. float c1 = 0;
  74562. float c2 = 0;
  74563. float c3 = 0;
  74564. for (int yy = 0; yy < size; ++yy)
  74565. {
  74566. const int sy = y + yy - (size >> 1);
  74567. if (sy >= srcData.height)
  74568. break;
  74569. if (sy >= 0)
  74570. {
  74571. int sx = x - (size >> 1);
  74572. const uint8* src = srcData.getPixelPointer (sx, sy);
  74573. for (int xx = 0; xx < size; ++xx)
  74574. {
  74575. if (sx >= srcData.width)
  74576. break;
  74577. if (sx >= 0)
  74578. {
  74579. const float kernelMult = values [xx + yy * size];
  74580. c1 += kernelMult * *src++;
  74581. c2 += kernelMult * *src++;
  74582. c3 += kernelMult * *src++;
  74583. }
  74584. else
  74585. {
  74586. src += 3;
  74587. }
  74588. ++sx;
  74589. }
  74590. }
  74591. }
  74592. *dest++ = (uint8) roundToInt (c1);
  74593. *dest++ = (uint8) roundToInt (c2);
  74594. *dest++ = (uint8) roundToInt (c3);
  74595. }
  74596. }
  74597. }
  74598. }
  74599. END_JUCE_NAMESPACE
  74600. /*** End of inlined file: juce_ImageConvolutionKernel.cpp ***/
  74601. /*** Start of inlined file: juce_ImageFileFormat.cpp ***/
  74602. BEGIN_JUCE_NAMESPACE
  74603. /*** Start of inlined file: juce_GIFLoader.h ***/
  74604. #ifndef __JUCE_GIFLOADER_JUCEHEADER__
  74605. #define __JUCE_GIFLOADER_JUCEHEADER__
  74606. #ifndef DOXYGEN
  74607. /**
  74608. Used internally by ImageFileFormat - don't use this class directly in your
  74609. application.
  74610. @see ImageFileFormat
  74611. */
  74612. class GIFLoader
  74613. {
  74614. public:
  74615. GIFLoader (InputStream& in);
  74616. ~GIFLoader();
  74617. Image* getImage() const { return image; }
  74618. private:
  74619. Image* image;
  74620. InputStream& input;
  74621. uint8 buffer [300];
  74622. uint8 palette [256][4];
  74623. bool dataBlockIsZero, fresh, finished;
  74624. int currentBit, lastBit, lastByteIndex;
  74625. int codeSize, setCodeSize;
  74626. int maxCode, maxCodeSize;
  74627. int firstcode, oldcode;
  74628. int clearCode, end_code;
  74629. enum { maxGifCode = 1 << 12 };
  74630. int table [2] [maxGifCode];
  74631. int stack [2 * maxGifCode];
  74632. int *sp;
  74633. bool getSizeFromHeader (int& width, int& height);
  74634. bool readPalette (const int numCols);
  74635. int readDataBlock (unsigned char* dest);
  74636. int processExtension (int type, int& transparent);
  74637. int readLZWByte (bool initialise, int input_code_size);
  74638. int getCode (int code_size, bool initialise);
  74639. bool readImage (int width, int height, int interlace, int transparent);
  74640. static inline int makeWord (const uint8 a, const uint8 b) { return (b << 8) | a; }
  74641. GIFLoader (const GIFLoader&);
  74642. GIFLoader& operator= (const GIFLoader&);
  74643. };
  74644. #endif // DOXYGEN
  74645. #endif // __JUCE_GIFLOADER_JUCEHEADER__
  74646. /*** End of inlined file: juce_GIFLoader.h ***/
  74647. class GIFImageFormat : public ImageFileFormat
  74648. {
  74649. public:
  74650. GIFImageFormat() {}
  74651. ~GIFImageFormat() {}
  74652. const String getFormatName()
  74653. {
  74654. return "GIF";
  74655. }
  74656. bool canUnderstand (InputStream& in)
  74657. {
  74658. const int bytesNeeded = 4;
  74659. char header [bytesNeeded];
  74660. return (in.read (header, bytesNeeded) == bytesNeeded)
  74661. && header[0] == 'G'
  74662. && header[1] == 'I'
  74663. && header[2] == 'F';
  74664. }
  74665. Image* decodeImage (InputStream& in)
  74666. {
  74667. const ScopedPointer <GIFLoader> loader (new GIFLoader (in));
  74668. return loader->getImage();
  74669. }
  74670. bool writeImageToStream (const Image& /*sourceImage*/, OutputStream& /*destStream*/)
  74671. {
  74672. return false;
  74673. }
  74674. };
  74675. ImageFileFormat* ImageFileFormat::findImageFormatForStream (InputStream& input)
  74676. {
  74677. static PNGImageFormat png;
  74678. static JPEGImageFormat jpg;
  74679. static GIFImageFormat gif;
  74680. ImageFileFormat* formats[4];
  74681. int numFormats = 0;
  74682. formats [numFormats++] = &png;
  74683. formats [numFormats++] = &jpg;
  74684. formats [numFormats++] = &gif;
  74685. const int64 streamPos = input.getPosition();
  74686. for (int i = 0; i < numFormats; ++i)
  74687. {
  74688. const bool found = formats[i]->canUnderstand (input);
  74689. input.setPosition (streamPos);
  74690. if (found)
  74691. return formats[i];
  74692. }
  74693. return 0;
  74694. }
  74695. Image* ImageFileFormat::loadFrom (InputStream& input)
  74696. {
  74697. ImageFileFormat* const format = findImageFormatForStream (input);
  74698. if (format != 0)
  74699. return format->decodeImage (input);
  74700. return 0;
  74701. }
  74702. Image* ImageFileFormat::loadFrom (const File& file)
  74703. {
  74704. InputStream* const in = file.createInputStream();
  74705. if (in != 0)
  74706. {
  74707. BufferedInputStream b (in, 8192, true);
  74708. return loadFrom (b);
  74709. }
  74710. return 0;
  74711. }
  74712. Image* ImageFileFormat::loadFrom (const void* rawData, const int numBytes)
  74713. {
  74714. if (rawData != 0 && numBytes > 4)
  74715. {
  74716. MemoryInputStream stream (rawData, numBytes, false);
  74717. return loadFrom (stream);
  74718. }
  74719. return 0;
  74720. }
  74721. END_JUCE_NAMESPACE
  74722. /*** End of inlined file: juce_ImageFileFormat.cpp ***/
  74723. /*** Start of inlined file: juce_GIFLoader.cpp ***/
  74724. BEGIN_JUCE_NAMESPACE
  74725. GIFLoader::GIFLoader (InputStream& in)
  74726. : image (0),
  74727. input (in),
  74728. dataBlockIsZero (false),
  74729. fresh (false),
  74730. finished (false)
  74731. {
  74732. currentBit = lastBit = lastByteIndex = 0;
  74733. maxCode = maxCodeSize = codeSize = setCodeSize = 0;
  74734. firstcode = oldcode = 0;
  74735. clearCode = end_code = 0;
  74736. int imageWidth, imageHeight;
  74737. int transparent = -1;
  74738. if (! getSizeFromHeader (imageWidth, imageHeight))
  74739. return;
  74740. if ((imageWidth <= 0) || (imageHeight <= 0))
  74741. return;
  74742. unsigned char buf [16];
  74743. if (in.read (buf, 3) != 3)
  74744. return;
  74745. int numColours = 2 << (buf[0] & 7);
  74746. if ((buf[0] & 0x80) != 0)
  74747. readPalette (numColours);
  74748. for (;;)
  74749. {
  74750. if (input.read (buf, 1) != 1)
  74751. break;
  74752. if (buf[0] == ';')
  74753. break;
  74754. if (buf[0] == '!')
  74755. {
  74756. if (input.read (buf, 1) != 1)
  74757. break;
  74758. if (processExtension (buf[0], transparent) < 0)
  74759. break;
  74760. continue;
  74761. }
  74762. if (buf[0] != ',')
  74763. continue;
  74764. if (input.read (buf, 9) != 9)
  74765. break;
  74766. imageWidth = makeWord (buf[4], buf[5]);
  74767. imageHeight = makeWord (buf[6], buf[7]);
  74768. numColours = 2 << (buf[8] & 7);
  74769. if ((buf[8] & 0x80) != 0)
  74770. if (! readPalette (numColours))
  74771. break;
  74772. image = Image::createNativeImage ((transparent >= 0) ? Image::ARGB : Image::RGB,
  74773. imageWidth, imageHeight, (transparent >= 0));
  74774. readImage (imageWidth, imageHeight,
  74775. (buf[8] & 0x40) != 0,
  74776. transparent);
  74777. break;
  74778. }
  74779. }
  74780. GIFLoader::~GIFLoader()
  74781. {
  74782. }
  74783. bool GIFLoader::getSizeFromHeader (int& w, int& h)
  74784. {
  74785. char b[8];
  74786. if (input.read (b, 6) == 6)
  74787. {
  74788. if ((strncmp ("GIF87a", b, 6) == 0)
  74789. || (strncmp ("GIF89a", b, 6) == 0))
  74790. {
  74791. if (input.read (b, 4) == 4)
  74792. {
  74793. w = makeWord (b[0], b[1]);
  74794. h = makeWord (b[2], b[3]);
  74795. return true;
  74796. }
  74797. }
  74798. }
  74799. return false;
  74800. }
  74801. bool GIFLoader::readPalette (const int numCols)
  74802. {
  74803. unsigned char rgb[4];
  74804. for (int i = 0; i < numCols; ++i)
  74805. {
  74806. input.read (rgb, 3);
  74807. palette [i][0] = rgb[0];
  74808. palette [i][1] = rgb[1];
  74809. palette [i][2] = rgb[2];
  74810. palette [i][3] = 0xff;
  74811. }
  74812. return true;
  74813. }
  74814. int GIFLoader::readDataBlock (unsigned char* const dest)
  74815. {
  74816. unsigned char n;
  74817. if (input.read (&n, 1) == 1)
  74818. {
  74819. dataBlockIsZero = (n == 0);
  74820. if (dataBlockIsZero || (input.read (dest, n) == n))
  74821. return n;
  74822. }
  74823. return -1;
  74824. }
  74825. int GIFLoader::processExtension (const int type, int& transparent)
  74826. {
  74827. unsigned char b [300];
  74828. int n = 0;
  74829. if (type == 0xf9)
  74830. {
  74831. n = readDataBlock (b);
  74832. if (n < 0)
  74833. return 1;
  74834. if ((b[0] & 0x1) != 0)
  74835. transparent = b[3];
  74836. }
  74837. do
  74838. {
  74839. n = readDataBlock (b);
  74840. }
  74841. while (n > 0);
  74842. return n;
  74843. }
  74844. int GIFLoader::getCode (const int codeSize_, const bool initialise)
  74845. {
  74846. if (initialise)
  74847. {
  74848. currentBit = 0;
  74849. lastBit = 0;
  74850. finished = false;
  74851. return 0;
  74852. }
  74853. if ((currentBit + codeSize_) >= lastBit)
  74854. {
  74855. if (finished)
  74856. return -1;
  74857. buffer[0] = buffer [lastByteIndex - 2];
  74858. buffer[1] = buffer [lastByteIndex - 1];
  74859. const int n = readDataBlock (&buffer[2]);
  74860. if (n == 0)
  74861. finished = true;
  74862. lastByteIndex = 2 + n;
  74863. currentBit = (currentBit - lastBit) + 16;
  74864. lastBit = (2 + n) * 8 ;
  74865. }
  74866. int result = 0;
  74867. int i = currentBit;
  74868. for (int j = 0; j < codeSize_; ++j)
  74869. {
  74870. result |= ((buffer[i >> 3] & (1 << (i & 7))) != 0) << j;
  74871. ++i;
  74872. }
  74873. currentBit += codeSize_;
  74874. return result;
  74875. }
  74876. int GIFLoader::readLZWByte (const bool initialise, const int inputCodeSize)
  74877. {
  74878. int code, incode, i;
  74879. if (initialise)
  74880. {
  74881. setCodeSize = inputCodeSize;
  74882. codeSize = setCodeSize + 1;
  74883. clearCode = 1 << setCodeSize;
  74884. end_code = clearCode + 1;
  74885. maxCodeSize = 2 * clearCode;
  74886. maxCode = clearCode + 2;
  74887. getCode (0, true);
  74888. fresh = true;
  74889. for (i = 0; i < clearCode; ++i)
  74890. {
  74891. table[0][i] = 0;
  74892. table[1][i] = i;
  74893. }
  74894. for (; i < maxGifCode; ++i)
  74895. {
  74896. table[0][i] = 0;
  74897. table[1][i] = 0;
  74898. }
  74899. sp = stack;
  74900. return 0;
  74901. }
  74902. else if (fresh)
  74903. {
  74904. fresh = false;
  74905. do
  74906. {
  74907. firstcode = oldcode
  74908. = getCode (codeSize, false);
  74909. }
  74910. while (firstcode == clearCode);
  74911. return firstcode;
  74912. }
  74913. if (sp > stack)
  74914. return *--sp;
  74915. while ((code = getCode (codeSize, false)) >= 0)
  74916. {
  74917. if (code == clearCode)
  74918. {
  74919. for (i = 0; i < clearCode; ++i)
  74920. {
  74921. table[0][i] = 0;
  74922. table[1][i] = i;
  74923. }
  74924. for (; i < maxGifCode; ++i)
  74925. {
  74926. table[0][i] = 0;
  74927. table[1][i] = 0;
  74928. }
  74929. codeSize = setCodeSize + 1;
  74930. maxCodeSize = 2 * clearCode;
  74931. maxCode = clearCode + 2;
  74932. sp = stack;
  74933. firstcode = oldcode = getCode (codeSize, false);
  74934. return firstcode;
  74935. }
  74936. else if (code == end_code)
  74937. {
  74938. if (dataBlockIsZero)
  74939. return -2;
  74940. unsigned char buf [260];
  74941. int n;
  74942. while ((n = readDataBlock (buf)) > 0)
  74943. {}
  74944. if (n != 0)
  74945. return -2;
  74946. }
  74947. incode = code;
  74948. if (code >= maxCode)
  74949. {
  74950. *sp++ = firstcode;
  74951. code = oldcode;
  74952. }
  74953. while (code >= clearCode)
  74954. {
  74955. *sp++ = table[1][code];
  74956. if (code == table[0][code])
  74957. return -2;
  74958. code = table[0][code];
  74959. }
  74960. *sp++ = firstcode = table[1][code];
  74961. if ((code = maxCode) < maxGifCode)
  74962. {
  74963. table[0][code] = oldcode;
  74964. table[1][code] = firstcode;
  74965. ++maxCode;
  74966. if ((maxCode >= maxCodeSize)
  74967. && (maxCodeSize < maxGifCode))
  74968. {
  74969. maxCodeSize <<= 1;
  74970. ++codeSize;
  74971. }
  74972. }
  74973. oldcode = incode;
  74974. if (sp > stack)
  74975. return *--sp;
  74976. }
  74977. return code;
  74978. }
  74979. bool GIFLoader::readImage (const int width, const int height,
  74980. const int interlace, const int transparent)
  74981. {
  74982. unsigned char c;
  74983. if (input.read (&c, 1) != 1
  74984. || readLZWByte (true, c) < 0)
  74985. return false;
  74986. if (transparent >= 0)
  74987. {
  74988. palette [transparent][0] = 0;
  74989. palette [transparent][1] = 0;
  74990. palette [transparent][2] = 0;
  74991. palette [transparent][3] = 0;
  74992. }
  74993. int index;
  74994. int xpos = 0, ypos = 0, pass = 0;
  74995. const Image::BitmapData destData (*image, 0, 0, width, height, true);
  74996. uint8* p = destData.data;
  74997. const bool hasAlpha = image->hasAlphaChannel();
  74998. while ((index = readLZWByte (false, c)) >= 0)
  74999. {
  75000. const uint8* const paletteEntry = palette [index];
  75001. if (hasAlpha)
  75002. {
  75003. ((PixelARGB*) p)->setARGB (paletteEntry[3],
  75004. paletteEntry[0],
  75005. paletteEntry[1],
  75006. paletteEntry[2]);
  75007. ((PixelARGB*) p)->premultiply();
  75008. }
  75009. else
  75010. {
  75011. ((PixelRGB*) p)->setARGB (0,
  75012. paletteEntry[0],
  75013. paletteEntry[1],
  75014. paletteEntry[2]);
  75015. }
  75016. p += destData.pixelStride;
  75017. ++xpos;
  75018. if (xpos == width)
  75019. {
  75020. xpos = 0;
  75021. if (interlace)
  75022. {
  75023. switch (pass)
  75024. {
  75025. case 0:
  75026. case 1: ypos += 8; break;
  75027. case 2: ypos += 4; break;
  75028. case 3: ypos += 2; break;
  75029. }
  75030. while (ypos >= height)
  75031. {
  75032. ++pass;
  75033. switch (pass)
  75034. {
  75035. case 1: ypos = 4; break;
  75036. case 2: ypos = 2; break;
  75037. case 3: ypos = 1; break;
  75038. default: return true;
  75039. }
  75040. }
  75041. }
  75042. else
  75043. {
  75044. ++ypos;
  75045. }
  75046. p = destData.getPixelPointer (xpos, ypos);
  75047. }
  75048. if (ypos >= height)
  75049. break;
  75050. }
  75051. return true;
  75052. }
  75053. END_JUCE_NAMESPACE
  75054. /*** End of inlined file: juce_GIFLoader.cpp ***/
  75055. #endif
  75056. //==============================================================================
  75057. // some files include lots of library code, so leave them to the end to avoid cluttering
  75058. // up the build for the clean files.
  75059. #if JUCE_BUILD_CORE
  75060. /*** Start of inlined file: juce_GZIPCompressorOutputStream.cpp ***/
  75061. namespace zlibNamespace
  75062. {
  75063. #if JUCE_INCLUDE_ZLIB_CODE
  75064. #undef OS_CODE
  75065. #undef fdopen
  75066. /*** Start of inlined file: zlib.h ***/
  75067. #ifndef ZLIB_H
  75068. #define ZLIB_H
  75069. /*** Start of inlined file: zconf.h ***/
  75070. /* @(#) $Id: zconf.h,v 1.1 2007/06/07 17:54:37 jules_rms Exp $ */
  75071. #ifndef ZCONF_H
  75072. #define ZCONF_H
  75073. // *** Just a few hacks here to make it compile nicely with Juce..
  75074. #define Z_PREFIX 1
  75075. #undef __MACTYPES__
  75076. #ifdef _MSC_VER
  75077. #pragma warning (disable : 4131 4127 4244 4267)
  75078. #endif
  75079. /*
  75080. * If you *really* need a unique prefix for all types and library functions,
  75081. * compile with -DZ_PREFIX. The "standard" zlib should be compiled without it.
  75082. */
  75083. #ifdef Z_PREFIX
  75084. # define deflateInit_ z_deflateInit_
  75085. # define deflate z_deflate
  75086. # define deflateEnd z_deflateEnd
  75087. # define inflateInit_ z_inflateInit_
  75088. # define inflate z_inflate
  75089. # define inflateEnd z_inflateEnd
  75090. # define inflatePrime z_inflatePrime
  75091. # define inflateGetHeader z_inflateGetHeader
  75092. # define adler32_combine z_adler32_combine
  75093. # define crc32_combine z_crc32_combine
  75094. # define deflateInit2_ z_deflateInit2_
  75095. # define deflateSetDictionary z_deflateSetDictionary
  75096. # define deflateCopy z_deflateCopy
  75097. # define deflateReset z_deflateReset
  75098. # define deflateParams z_deflateParams
  75099. # define deflateBound z_deflateBound
  75100. # define deflatePrime z_deflatePrime
  75101. # define inflateInit2_ z_inflateInit2_
  75102. # define inflateSetDictionary z_inflateSetDictionary
  75103. # define inflateSync z_inflateSync
  75104. # define inflateSyncPoint z_inflateSyncPoint
  75105. # define inflateCopy z_inflateCopy
  75106. # define inflateReset z_inflateReset
  75107. # define inflateBack z_inflateBack
  75108. # define inflateBackEnd z_inflateBackEnd
  75109. # define compress z_compress
  75110. # define compress2 z_compress2
  75111. # define compressBound z_compressBound
  75112. # define uncompress z_uncompress
  75113. # define adler32 z_adler32
  75114. # define crc32 z_crc32
  75115. # define get_crc_table z_get_crc_table
  75116. # define zError z_zError
  75117. # define alloc_func z_alloc_func
  75118. # define free_func z_free_func
  75119. # define in_func z_in_func
  75120. # define out_func z_out_func
  75121. # define Byte z_Byte
  75122. # define uInt z_uInt
  75123. # define uLong z_uLong
  75124. # define Bytef z_Bytef
  75125. # define charf z_charf
  75126. # define intf z_intf
  75127. # define uIntf z_uIntf
  75128. # define uLongf z_uLongf
  75129. # define voidpf z_voidpf
  75130. # define voidp z_voidp
  75131. #endif
  75132. #if defined(__MSDOS__) && !defined(MSDOS)
  75133. # define MSDOS
  75134. #endif
  75135. #if (defined(OS_2) || defined(__OS2__)) && !defined(OS2)
  75136. # define OS2
  75137. #endif
  75138. #if defined(_WINDOWS) && !defined(WINDOWS)
  75139. # define WINDOWS
  75140. #endif
  75141. #if defined(_WIN32) || defined(_WIN32_WCE) || defined(__WIN32__)
  75142. # ifndef WIN32
  75143. # define WIN32
  75144. # endif
  75145. #endif
  75146. #if (defined(MSDOS) || defined(OS2) || defined(WINDOWS)) && !defined(WIN32)
  75147. # if !defined(__GNUC__) && !defined(__FLAT__) && !defined(__386__)
  75148. # ifndef SYS16BIT
  75149. # define SYS16BIT
  75150. # endif
  75151. # endif
  75152. #endif
  75153. /*
  75154. * Compile with -DMAXSEG_64K if the alloc function cannot allocate more
  75155. * than 64k bytes at a time (needed on systems with 16-bit int).
  75156. */
  75157. #ifdef SYS16BIT
  75158. # define MAXSEG_64K
  75159. #endif
  75160. #ifdef MSDOS
  75161. # define UNALIGNED_OK
  75162. #endif
  75163. #ifdef __STDC_VERSION__
  75164. # ifndef STDC
  75165. # define STDC
  75166. # endif
  75167. # if __STDC_VERSION__ >= 199901L
  75168. # ifndef STDC99
  75169. # define STDC99
  75170. # endif
  75171. # endif
  75172. #endif
  75173. #if !defined(STDC) && (defined(__STDC__) || defined(__cplusplus))
  75174. # define STDC
  75175. #endif
  75176. #if !defined(STDC) && (defined(__GNUC__) || defined(__BORLANDC__))
  75177. # define STDC
  75178. #endif
  75179. #if !defined(STDC) && (defined(MSDOS) || defined(WINDOWS) || defined(WIN32))
  75180. # define STDC
  75181. #endif
  75182. #if !defined(STDC) && (defined(OS2) || defined(__HOS_AIX__))
  75183. # define STDC
  75184. #endif
  75185. #if defined(__OS400__) && !defined(STDC) /* iSeries (formerly AS/400). */
  75186. # define STDC
  75187. #endif
  75188. #ifndef STDC
  75189. # ifndef const /* cannot use !defined(STDC) && !defined(const) on Mac */
  75190. # define const /* note: need a more gentle solution here */
  75191. # endif
  75192. #endif
  75193. /* Some Mac compilers merge all .h files incorrectly: */
  75194. #if defined(__MWERKS__)||defined(applec)||defined(THINK_C)||defined(__SC__)
  75195. # define NO_DUMMY_DECL
  75196. #endif
  75197. /* Maximum value for memLevel in deflateInit2 */
  75198. #ifndef MAX_MEM_LEVEL
  75199. # ifdef MAXSEG_64K
  75200. # define MAX_MEM_LEVEL 8
  75201. # else
  75202. # define MAX_MEM_LEVEL 9
  75203. # endif
  75204. #endif
  75205. /* Maximum value for windowBits in deflateInit2 and inflateInit2.
  75206. * WARNING: reducing MAX_WBITS makes minigzip unable to extract .gz files
  75207. * created by gzip. (Files created by minigzip can still be extracted by
  75208. * gzip.)
  75209. */
  75210. #ifndef MAX_WBITS
  75211. # define MAX_WBITS 15 /* 32K LZ77 window */
  75212. #endif
  75213. /* The memory requirements for deflate are (in bytes):
  75214. (1 << (windowBits+2)) + (1 << (memLevel+9))
  75215. that is: 128K for windowBits=15 + 128K for memLevel = 8 (default values)
  75216. plus a few kilobytes for small objects. For example, if you want to reduce
  75217. the default memory requirements from 256K to 128K, compile with
  75218. make CFLAGS="-O -DMAX_WBITS=14 -DMAX_MEM_LEVEL=7"
  75219. Of course this will generally degrade compression (there's no free lunch).
  75220. The memory requirements for inflate are (in bytes) 1 << windowBits
  75221. that is, 32K for windowBits=15 (default value) plus a few kilobytes
  75222. for small objects.
  75223. */
  75224. /* Type declarations */
  75225. #ifndef OF /* function prototypes */
  75226. # ifdef STDC
  75227. # define OF(args) args
  75228. # else
  75229. # define OF(args) ()
  75230. # endif
  75231. #endif
  75232. /* The following definitions for FAR are needed only for MSDOS mixed
  75233. * model programming (small or medium model with some far allocations).
  75234. * This was tested only with MSC; for other MSDOS compilers you may have
  75235. * to define NO_MEMCPY in zutil.h. If you don't need the mixed model,
  75236. * just define FAR to be empty.
  75237. */
  75238. #ifdef SYS16BIT
  75239. # if defined(M_I86SM) || defined(M_I86MM)
  75240. /* MSC small or medium model */
  75241. # define SMALL_MEDIUM
  75242. # ifdef _MSC_VER
  75243. # define FAR _far
  75244. # else
  75245. # define FAR far
  75246. # endif
  75247. # endif
  75248. # if (defined(__SMALL__) || defined(__MEDIUM__))
  75249. /* Turbo C small or medium model */
  75250. # define SMALL_MEDIUM
  75251. # ifdef __BORLANDC__
  75252. # define FAR _far
  75253. # else
  75254. # define FAR far
  75255. # endif
  75256. # endif
  75257. #endif
  75258. #if defined(WINDOWS) || defined(WIN32)
  75259. /* If building or using zlib as a DLL, define ZLIB_DLL.
  75260. * This is not mandatory, but it offers a little performance increase.
  75261. */
  75262. # ifdef ZLIB_DLL
  75263. # if defined(WIN32) && (!defined(__BORLANDC__) || (__BORLANDC__ >= 0x500))
  75264. # ifdef ZLIB_INTERNAL
  75265. # define ZEXTERN extern __declspec(dllexport)
  75266. # else
  75267. # define ZEXTERN extern __declspec(dllimport)
  75268. # endif
  75269. # endif
  75270. # endif /* ZLIB_DLL */
  75271. /* If building or using zlib with the WINAPI/WINAPIV calling convention,
  75272. * define ZLIB_WINAPI.
  75273. * Caution: the standard ZLIB1.DLL is NOT compiled using ZLIB_WINAPI.
  75274. */
  75275. # ifdef ZLIB_WINAPI
  75276. # ifdef FAR
  75277. # undef FAR
  75278. # endif
  75279. # include <windows.h>
  75280. /* No need for _export, use ZLIB.DEF instead. */
  75281. /* For complete Windows compatibility, use WINAPI, not __stdcall. */
  75282. # define ZEXPORT WINAPI
  75283. # ifdef WIN32
  75284. # define ZEXPORTVA WINAPIV
  75285. # else
  75286. # define ZEXPORTVA FAR CDECL
  75287. # endif
  75288. # endif
  75289. #endif
  75290. #if defined (__BEOS__)
  75291. # ifdef ZLIB_DLL
  75292. # ifdef ZLIB_INTERNAL
  75293. # define ZEXPORT __declspec(dllexport)
  75294. # define ZEXPORTVA __declspec(dllexport)
  75295. # else
  75296. # define ZEXPORT __declspec(dllimport)
  75297. # define ZEXPORTVA __declspec(dllimport)
  75298. # endif
  75299. # endif
  75300. #endif
  75301. #ifndef ZEXTERN
  75302. # define ZEXTERN extern
  75303. #endif
  75304. #ifndef ZEXPORT
  75305. # define ZEXPORT
  75306. #endif
  75307. #ifndef ZEXPORTVA
  75308. # define ZEXPORTVA
  75309. #endif
  75310. #ifndef FAR
  75311. # define FAR
  75312. #endif
  75313. #if !defined(__MACTYPES__)
  75314. typedef unsigned char Byte; /* 8 bits */
  75315. #endif
  75316. typedef unsigned int uInt; /* 16 bits or more */
  75317. typedef unsigned long uLong; /* 32 bits or more */
  75318. #ifdef SMALL_MEDIUM
  75319. /* Borland C/C++ and some old MSC versions ignore FAR inside typedef */
  75320. # define Bytef Byte FAR
  75321. #else
  75322. typedef Byte FAR Bytef;
  75323. #endif
  75324. typedef char FAR charf;
  75325. typedef int FAR intf;
  75326. typedef uInt FAR uIntf;
  75327. typedef uLong FAR uLongf;
  75328. #ifdef STDC
  75329. typedef void const *voidpc;
  75330. typedef void FAR *voidpf;
  75331. typedef void *voidp;
  75332. #else
  75333. typedef Byte const *voidpc;
  75334. typedef Byte FAR *voidpf;
  75335. typedef Byte *voidp;
  75336. #endif
  75337. #if 0 /* HAVE_UNISTD_H -- this line is updated by ./configure */
  75338. # include <sys/types.h> /* for off_t */
  75339. # include <unistd.h> /* for SEEK_* and off_t */
  75340. # ifdef VMS
  75341. # include <unixio.h> /* for off_t */
  75342. # endif
  75343. # define z_off_t off_t
  75344. #endif
  75345. #ifndef SEEK_SET
  75346. # define SEEK_SET 0 /* Seek from beginning of file. */
  75347. # define SEEK_CUR 1 /* Seek from current position. */
  75348. # define SEEK_END 2 /* Set file pointer to EOF plus "offset" */
  75349. #endif
  75350. #ifndef z_off_t
  75351. # define z_off_t long
  75352. #endif
  75353. #if defined(__OS400__)
  75354. # define NO_vsnprintf
  75355. #endif
  75356. #if defined(__MVS__)
  75357. # define NO_vsnprintf
  75358. # ifdef FAR
  75359. # undef FAR
  75360. # endif
  75361. #endif
  75362. /* MVS linker does not support external names larger than 8 bytes */
  75363. #if defined(__MVS__)
  75364. # pragma map(deflateInit_,"DEIN")
  75365. # pragma map(deflateInit2_,"DEIN2")
  75366. # pragma map(deflateEnd,"DEEND")
  75367. # pragma map(deflateBound,"DEBND")
  75368. # pragma map(inflateInit_,"ININ")
  75369. # pragma map(inflateInit2_,"ININ2")
  75370. # pragma map(inflateEnd,"INEND")
  75371. # pragma map(inflateSync,"INSY")
  75372. # pragma map(inflateSetDictionary,"INSEDI")
  75373. # pragma map(compressBound,"CMBND")
  75374. # pragma map(inflate_table,"INTABL")
  75375. # pragma map(inflate_fast,"INFA")
  75376. # pragma map(inflate_copyright,"INCOPY")
  75377. #endif
  75378. #endif /* ZCONF_H */
  75379. /*** End of inlined file: zconf.h ***/
  75380. #ifdef __cplusplus
  75381. extern "C" {
  75382. #endif
  75383. #define ZLIB_VERSION "1.2.3"
  75384. #define ZLIB_VERNUM 0x1230
  75385. /*
  75386. The 'zlib' compression library provides in-memory compression and
  75387. decompression functions, including integrity checks of the uncompressed
  75388. data. This version of the library supports only one compression method
  75389. (deflation) but other algorithms will be added later and will have the same
  75390. stream interface.
  75391. Compression can be done in a single step if the buffers are large
  75392. enough (for example if an input file is mmap'ed), or can be done by
  75393. repeated calls of the compression function. In the latter case, the
  75394. application must provide more input and/or consume the output
  75395. (providing more output space) before each call.
  75396. The compressed data format used by default by the in-memory functions is
  75397. the zlib format, which is a zlib wrapper documented in RFC 1950, wrapped
  75398. around a deflate stream, which is itself documented in RFC 1951.
  75399. The library also supports reading and writing files in gzip (.gz) format
  75400. with an interface similar to that of stdio using the functions that start
  75401. with "gz". The gzip format is different from the zlib format. gzip is a
  75402. gzip wrapper, documented in RFC 1952, wrapped around a deflate stream.
  75403. This library can optionally read and write gzip streams in memory as well.
  75404. The zlib format was designed to be compact and fast for use in memory
  75405. and on communications channels. The gzip format was designed for single-
  75406. file compression on file systems, has a larger header than zlib to maintain
  75407. directory information, and uses a different, slower check method than zlib.
  75408. The library does not install any signal handler. The decoder checks
  75409. the consistency of the compressed data, so the library should never
  75410. crash even in case of corrupted input.
  75411. */
  75412. typedef voidpf (*alloc_func) OF((voidpf opaque, uInt items, uInt size));
  75413. typedef void (*free_func) OF((voidpf opaque, voidpf address));
  75414. struct internal_state;
  75415. typedef struct z_stream_s {
  75416. Bytef *next_in; /* next input byte */
  75417. uInt avail_in; /* number of bytes available at next_in */
  75418. uLong total_in; /* total nb of input bytes read so far */
  75419. Bytef *next_out; /* next output byte should be put there */
  75420. uInt avail_out; /* remaining free space at next_out */
  75421. uLong total_out; /* total nb of bytes output so far */
  75422. char *msg; /* last error message, NULL if no error */
  75423. struct internal_state FAR *state; /* not visible by applications */
  75424. alloc_func zalloc; /* used to allocate the internal state */
  75425. free_func zfree; /* used to free the internal state */
  75426. voidpf opaque; /* private data object passed to zalloc and zfree */
  75427. int data_type; /* best guess about the data type: binary or text */
  75428. uLong adler; /* adler32 value of the uncompressed data */
  75429. uLong reserved; /* reserved for future use */
  75430. } z_stream;
  75431. typedef z_stream FAR *z_streamp;
  75432. /*
  75433. gzip header information passed to and from zlib routines. See RFC 1952
  75434. for more details on the meanings of these fields.
  75435. */
  75436. typedef struct gz_header_s {
  75437. int text; /* true if compressed data believed to be text */
  75438. uLong time; /* modification time */
  75439. int xflags; /* extra flags (not used when writing a gzip file) */
  75440. int os; /* operating system */
  75441. Bytef *extra; /* pointer to extra field or Z_NULL if none */
  75442. uInt extra_len; /* extra field length (valid if extra != Z_NULL) */
  75443. uInt extra_max; /* space at extra (only when reading header) */
  75444. Bytef *name; /* pointer to zero-terminated file name or Z_NULL */
  75445. uInt name_max; /* space at name (only when reading header) */
  75446. Bytef *comment; /* pointer to zero-terminated comment or Z_NULL */
  75447. uInt comm_max; /* space at comment (only when reading header) */
  75448. int hcrc; /* true if there was or will be a header crc */
  75449. int done; /* true when done reading gzip header (not used
  75450. when writing a gzip file) */
  75451. } gz_header;
  75452. typedef gz_header FAR *gz_headerp;
  75453. /*
  75454. The application must update next_in and avail_in when avail_in has
  75455. dropped to zero. It must update next_out and avail_out when avail_out
  75456. has dropped to zero. The application must initialize zalloc, zfree and
  75457. opaque before calling the init function. All other fields are set by the
  75458. compression library and must not be updated by the application.
  75459. The opaque value provided by the application will be passed as the first
  75460. parameter for calls of zalloc and zfree. This can be useful for custom
  75461. memory management. The compression library attaches no meaning to the
  75462. opaque value.
  75463. zalloc must return Z_NULL if there is not enough memory for the object.
  75464. If zlib is used in a multi-threaded application, zalloc and zfree must be
  75465. thread safe.
  75466. On 16-bit systems, the functions zalloc and zfree must be able to allocate
  75467. exactly 65536 bytes, but will not be required to allocate more than this
  75468. if the symbol MAXSEG_64K is defined (see zconf.h). WARNING: On MSDOS,
  75469. pointers returned by zalloc for objects of exactly 65536 bytes *must*
  75470. have their offset normalized to zero. The default allocation function
  75471. provided by this library ensures this (see zutil.c). To reduce memory
  75472. requirements and avoid any allocation of 64K objects, at the expense of
  75473. compression ratio, compile the library with -DMAX_WBITS=14 (see zconf.h).
  75474. The fields total_in and total_out can be used for statistics or
  75475. progress reports. After compression, total_in holds the total size of
  75476. the uncompressed data and may be saved for use in the decompressor
  75477. (particularly if the decompressor wants to decompress everything in
  75478. a single step).
  75479. */
  75480. /* constants */
  75481. #define Z_NO_FLUSH 0
  75482. #define Z_PARTIAL_FLUSH 1 /* will be removed, use Z_SYNC_FLUSH instead */
  75483. #define Z_SYNC_FLUSH 2
  75484. #define Z_FULL_FLUSH 3
  75485. #define Z_FINISH 4
  75486. #define Z_BLOCK 5
  75487. /* Allowed flush values; see deflate() and inflate() below for details */
  75488. #define Z_OK 0
  75489. #define Z_STREAM_END 1
  75490. #define Z_NEED_DICT 2
  75491. #define Z_ERRNO (-1)
  75492. #define Z_STREAM_ERROR (-2)
  75493. #define Z_DATA_ERROR (-3)
  75494. #define Z_MEM_ERROR (-4)
  75495. #define Z_BUF_ERROR (-5)
  75496. #define Z_VERSION_ERROR (-6)
  75497. /* Return codes for the compression/decompression functions. Negative
  75498. * values are errors, positive values are used for special but normal events.
  75499. */
  75500. #define Z_NO_COMPRESSION 0
  75501. #define Z_BEST_SPEED 1
  75502. #define Z_BEST_COMPRESSION 9
  75503. #define Z_DEFAULT_COMPRESSION (-1)
  75504. /* compression levels */
  75505. #define Z_FILTERED 1
  75506. #define Z_HUFFMAN_ONLY 2
  75507. #define Z_RLE 3
  75508. #define Z_FIXED 4
  75509. #define Z_DEFAULT_STRATEGY 0
  75510. /* compression strategy; see deflateInit2() below for details */
  75511. #define Z_BINARY 0
  75512. #define Z_TEXT 1
  75513. #define Z_ASCII Z_TEXT /* for compatibility with 1.2.2 and earlier */
  75514. #define Z_UNKNOWN 2
  75515. /* Possible values of the data_type field (though see inflate()) */
  75516. #define Z_DEFLATED 8
  75517. /* The deflate compression method (the only one supported in this version) */
  75518. #define Z_NULL 0 /* for initializing zalloc, zfree, opaque */
  75519. #define zlib_version zlibVersion()
  75520. /* for compatibility with versions < 1.0.2 */
  75521. /* basic functions */
  75522. //ZEXTERN const char * ZEXPORT zlibVersion OF((void));
  75523. /* The application can compare zlibVersion and ZLIB_VERSION for consistency.
  75524. If the first character differs, the library code actually used is
  75525. not compatible with the zlib.h header file used by the application.
  75526. This check is automatically made by deflateInit and inflateInit.
  75527. */
  75528. /*
  75529. ZEXTERN int ZEXPORT deflateInit OF((z_streamp strm, int level));
  75530. Initializes the internal stream state for compression. The fields
  75531. zalloc, zfree and opaque must be initialized before by the caller.
  75532. If zalloc and zfree are set to Z_NULL, deflateInit updates them to
  75533. use default allocation functions.
  75534. The compression level must be Z_DEFAULT_COMPRESSION, or between 0 and 9:
  75535. 1 gives best speed, 9 gives best compression, 0 gives no compression at
  75536. all (the input data is simply copied a block at a time).
  75537. Z_DEFAULT_COMPRESSION requests a default compromise between speed and
  75538. compression (currently equivalent to level 6).
  75539. deflateInit returns Z_OK if success, Z_MEM_ERROR if there was not
  75540. enough memory, Z_STREAM_ERROR if level is not a valid compression level,
  75541. Z_VERSION_ERROR if the zlib library version (zlib_version) is incompatible
  75542. with the version assumed by the caller (ZLIB_VERSION).
  75543. msg is set to null if there is no error message. deflateInit does not
  75544. perform any compression: this will be done by deflate().
  75545. */
  75546. ZEXTERN int ZEXPORT deflate OF((z_streamp strm, int flush));
  75547. /*
  75548. deflate compresses as much data as possible, and stops when the input
  75549. buffer becomes empty or the output buffer becomes full. It may introduce some
  75550. output latency (reading input without producing any output) except when
  75551. forced to flush.
  75552. The detailed semantics are as follows. deflate performs one or both of the
  75553. following actions:
  75554. - Compress more input starting at next_in and update next_in and avail_in
  75555. accordingly. If not all input can be processed (because there is not
  75556. enough room in the output buffer), next_in and avail_in are updated and
  75557. processing will resume at this point for the next call of deflate().
  75558. - Provide more output starting at next_out and update next_out and avail_out
  75559. accordingly. This action is forced if the parameter flush is non zero.
  75560. Forcing flush frequently degrades the compression ratio, so this parameter
  75561. should be set only when necessary (in interactive applications).
  75562. Some output may be provided even if flush is not set.
  75563. Before the call of deflate(), the application should ensure that at least
  75564. one of the actions is possible, by providing more input and/or consuming
  75565. more output, and updating avail_in or avail_out accordingly; avail_out
  75566. should never be zero before the call. The application can consume the
  75567. compressed output when it wants, for example when the output buffer is full
  75568. (avail_out == 0), or after each call of deflate(). If deflate returns Z_OK
  75569. and with zero avail_out, it must be called again after making room in the
  75570. output buffer because there might be more output pending.
  75571. Normally the parameter flush is set to Z_NO_FLUSH, which allows deflate to
  75572. decide how much data to accumualte before producing output, in order to
  75573. maximize compression.
  75574. If the parameter flush is set to Z_SYNC_FLUSH, all pending output is
  75575. flushed to the output buffer and the output is aligned on a byte boundary, so
  75576. that the decompressor can get all input data available so far. (In particular
  75577. avail_in is zero after the call if enough output space has been provided
  75578. before the call.) Flushing may degrade compression for some compression
  75579. algorithms and so it should be used only when necessary.
  75580. If flush is set to Z_FULL_FLUSH, all output is flushed as with
  75581. Z_SYNC_FLUSH, and the compression state is reset so that decompression can
  75582. restart from this point if previous compressed data has been damaged or if
  75583. random access is desired. Using Z_FULL_FLUSH too often can seriously degrade
  75584. compression.
  75585. If deflate returns with avail_out == 0, this function must be called again
  75586. with the same value of the flush parameter and more output space (updated
  75587. avail_out), until the flush is complete (deflate returns with non-zero
  75588. avail_out). In the case of a Z_FULL_FLUSH or Z_SYNC_FLUSH, make sure that
  75589. avail_out is greater than six to avoid repeated flush markers due to
  75590. avail_out == 0 on return.
  75591. If the parameter flush is set to Z_FINISH, pending input is processed,
  75592. pending output is flushed and deflate returns with Z_STREAM_END if there
  75593. was enough output space; if deflate returns with Z_OK, this function must be
  75594. called again with Z_FINISH and more output space (updated avail_out) but no
  75595. more input data, until it returns with Z_STREAM_END or an error. After
  75596. deflate has returned Z_STREAM_END, the only possible operations on the
  75597. stream are deflateReset or deflateEnd.
  75598. Z_FINISH can be used immediately after deflateInit if all the compression
  75599. is to be done in a single step. In this case, avail_out must be at least
  75600. the value returned by deflateBound (see below). If deflate does not return
  75601. Z_STREAM_END, then it must be called again as described above.
  75602. deflate() sets strm->adler to the adler32 checksum of all input read
  75603. so far (that is, total_in bytes).
  75604. deflate() may update strm->data_type if it can make a good guess about
  75605. the input data type (Z_BINARY or Z_TEXT). In doubt, the data is considered
  75606. binary. This field is only for information purposes and does not affect
  75607. the compression algorithm in any manner.
  75608. deflate() returns Z_OK if some progress has been made (more input
  75609. processed or more output produced), Z_STREAM_END if all input has been
  75610. consumed and all output has been produced (only when flush is set to
  75611. Z_FINISH), Z_STREAM_ERROR if the stream state was inconsistent (for example
  75612. if next_in or next_out was NULL), Z_BUF_ERROR if no progress is possible
  75613. (for example avail_in or avail_out was zero). Note that Z_BUF_ERROR is not
  75614. fatal, and deflate() can be called again with more input and more output
  75615. space to continue compressing.
  75616. */
  75617. ZEXTERN int ZEXPORT deflateEnd OF((z_streamp strm));
  75618. /*
  75619. All dynamically allocated data structures for this stream are freed.
  75620. This function discards any unprocessed input and does not flush any
  75621. pending output.
  75622. deflateEnd returns Z_OK if success, Z_STREAM_ERROR if the
  75623. stream state was inconsistent, Z_DATA_ERROR if the stream was freed
  75624. prematurely (some input or output was discarded). In the error case,
  75625. msg may be set but then points to a static string (which must not be
  75626. deallocated).
  75627. */
  75628. /*
  75629. ZEXTERN int ZEXPORT inflateInit OF((z_streamp strm));
  75630. Initializes the internal stream state for decompression. The fields
  75631. next_in, avail_in, zalloc, zfree and opaque must be initialized before by
  75632. the caller. If next_in is not Z_NULL and avail_in is large enough (the exact
  75633. value depends on the compression method), inflateInit determines the
  75634. compression method from the zlib header and allocates all data structures
  75635. accordingly; otherwise the allocation will be deferred to the first call of
  75636. inflate. If zalloc and zfree are set to Z_NULL, inflateInit updates them to
  75637. use default allocation functions.
  75638. inflateInit returns Z_OK if success, Z_MEM_ERROR if there was not enough
  75639. memory, Z_VERSION_ERROR if the zlib library version is incompatible with the
  75640. version assumed by the caller. msg is set to null if there is no error
  75641. message. inflateInit does not perform any decompression apart from reading
  75642. the zlib header if present: this will be done by inflate(). (So next_in and
  75643. avail_in may be modified, but next_out and avail_out are unchanged.)
  75644. */
  75645. ZEXTERN int ZEXPORT inflate OF((z_streamp strm, int flush));
  75646. /*
  75647. inflate decompresses as much data as possible, and stops when the input
  75648. buffer becomes empty or the output buffer becomes full. It may introduce
  75649. some output latency (reading input without producing any output) except when
  75650. forced to flush.
  75651. The detailed semantics are as follows. inflate performs one or both of the
  75652. following actions:
  75653. - Decompress more input starting at next_in and update next_in and avail_in
  75654. accordingly. If not all input can be processed (because there is not
  75655. enough room in the output buffer), next_in is updated and processing
  75656. will resume at this point for the next call of inflate().
  75657. - Provide more output starting at next_out and update next_out and avail_out
  75658. accordingly. inflate() provides as much output as possible, until there
  75659. is no more input data or no more space in the output buffer (see below
  75660. about the flush parameter).
  75661. Before the call of inflate(), the application should ensure that at least
  75662. one of the actions is possible, by providing more input and/or consuming
  75663. more output, and updating the next_* and avail_* values accordingly.
  75664. The application can consume the uncompressed output when it wants, for
  75665. example when the output buffer is full (avail_out == 0), or after each
  75666. call of inflate(). If inflate returns Z_OK and with zero avail_out, it
  75667. must be called again after making room in the output buffer because there
  75668. might be more output pending.
  75669. The flush parameter of inflate() can be Z_NO_FLUSH, Z_SYNC_FLUSH,
  75670. Z_FINISH, or Z_BLOCK. Z_SYNC_FLUSH requests that inflate() flush as much
  75671. output as possible to the output buffer. Z_BLOCK requests that inflate() stop
  75672. if and when it gets to the next deflate block boundary. When decoding the
  75673. zlib or gzip format, this will cause inflate() to return immediately after
  75674. the header and before the first block. When doing a raw inflate, inflate()
  75675. will go ahead and process the first block, and will return when it gets to
  75676. the end of that block, or when it runs out of data.
  75677. The Z_BLOCK option assists in appending to or combining deflate streams.
  75678. Also to assist in this, on return inflate() will set strm->data_type to the
  75679. number of unused bits in the last byte taken from strm->next_in, plus 64
  75680. if inflate() is currently decoding the last block in the deflate stream,
  75681. plus 128 if inflate() returned immediately after decoding an end-of-block
  75682. code or decoding the complete header up to just before the first byte of the
  75683. deflate stream. The end-of-block will not be indicated until all of the
  75684. uncompressed data from that block has been written to strm->next_out. The
  75685. number of unused bits may in general be greater than seven, except when
  75686. bit 7 of data_type is set, in which case the number of unused bits will be
  75687. less than eight.
  75688. inflate() should normally be called until it returns Z_STREAM_END or an
  75689. error. However if all decompression is to be performed in a single step
  75690. (a single call of inflate), the parameter flush should be set to
  75691. Z_FINISH. In this case all pending input is processed and all pending
  75692. output is flushed; avail_out must be large enough to hold all the
  75693. uncompressed data. (The size of the uncompressed data may have been saved
  75694. by the compressor for this purpose.) The next operation on this stream must
  75695. be inflateEnd to deallocate the decompression state. The use of Z_FINISH
  75696. is never required, but can be used to inform inflate that a faster approach
  75697. may be used for the single inflate() call.
  75698. In this implementation, inflate() always flushes as much output as
  75699. possible to the output buffer, and always uses the faster approach on the
  75700. first call. So the only effect of the flush parameter in this implementation
  75701. is on the return value of inflate(), as noted below, or when it returns early
  75702. because Z_BLOCK is used.
  75703. If a preset dictionary is needed after this call (see inflateSetDictionary
  75704. below), inflate sets strm->adler to the adler32 checksum of the dictionary
  75705. chosen by the compressor and returns Z_NEED_DICT; otherwise it sets
  75706. strm->adler to the adler32 checksum of all output produced so far (that is,
  75707. total_out bytes) and returns Z_OK, Z_STREAM_END or an error code as described
  75708. below. At the end of the stream, inflate() checks that its computed adler32
  75709. checksum is equal to that saved by the compressor and returns Z_STREAM_END
  75710. only if the checksum is correct.
  75711. inflate() will decompress and check either zlib-wrapped or gzip-wrapped
  75712. deflate data. The header type is detected automatically. Any information
  75713. contained in the gzip header is not retained, so applications that need that
  75714. information should instead use raw inflate, see inflateInit2() below, or
  75715. inflateBack() and perform their own processing of the gzip header and
  75716. trailer.
  75717. inflate() returns Z_OK if some progress has been made (more input processed
  75718. or more output produced), Z_STREAM_END if the end of the compressed data has
  75719. been reached and all uncompressed output has been produced, Z_NEED_DICT if a
  75720. preset dictionary is needed at this point, Z_DATA_ERROR if the input data was
  75721. corrupted (input stream not conforming to the zlib format or incorrect check
  75722. value), Z_STREAM_ERROR if the stream structure was inconsistent (for example
  75723. if next_in or next_out was NULL), Z_MEM_ERROR if there was not enough memory,
  75724. Z_BUF_ERROR if no progress is possible or if there was not enough room in the
  75725. output buffer when Z_FINISH is used. Note that Z_BUF_ERROR is not fatal, and
  75726. inflate() can be called again with more input and more output space to
  75727. continue decompressing. If Z_DATA_ERROR is returned, the application may then
  75728. call inflateSync() to look for a good compression block if a partial recovery
  75729. of the data is desired.
  75730. */
  75731. ZEXTERN int ZEXPORT inflateEnd OF((z_streamp strm));
  75732. /*
  75733. All dynamically allocated data structures for this stream are freed.
  75734. This function discards any unprocessed input and does not flush any
  75735. pending output.
  75736. inflateEnd returns Z_OK if success, Z_STREAM_ERROR if the stream state
  75737. was inconsistent. In the error case, msg may be set but then points to a
  75738. static string (which must not be deallocated).
  75739. */
  75740. /* Advanced functions */
  75741. /*
  75742. The following functions are needed only in some special applications.
  75743. */
  75744. /*
  75745. ZEXTERN int ZEXPORT deflateInit2 OF((z_streamp strm,
  75746. int level,
  75747. int method,
  75748. int windowBits,
  75749. int memLevel,
  75750. int strategy));
  75751. This is another version of deflateInit with more compression options. The
  75752. fields next_in, zalloc, zfree and opaque must be initialized before by
  75753. the caller.
  75754. The method parameter is the compression method. It must be Z_DEFLATED in
  75755. this version of the library.
  75756. The windowBits parameter is the base two logarithm of the window size
  75757. (the size of the history buffer). It should be in the range 8..15 for this
  75758. version of the library. Larger values of this parameter result in better
  75759. compression at the expense of memory usage. The default value is 15 if
  75760. deflateInit is used instead.
  75761. windowBits can also be -8..-15 for raw deflate. In this case, -windowBits
  75762. determines the window size. deflate() will then generate raw deflate data
  75763. with no zlib header or trailer, and will not compute an adler32 check value.
  75764. windowBits can also be greater than 15 for optional gzip encoding. Add
  75765. 16 to windowBits to write a simple gzip header and trailer around the
  75766. compressed data instead of a zlib wrapper. The gzip header will have no
  75767. file name, no extra data, no comment, no modification time (set to zero),
  75768. no header crc, and the operating system will be set to 255 (unknown). If a
  75769. gzip stream is being written, strm->adler is a crc32 instead of an adler32.
  75770. The memLevel parameter specifies how much memory should be allocated
  75771. for the internal compression state. memLevel=1 uses minimum memory but
  75772. is slow and reduces compression ratio; memLevel=9 uses maximum memory
  75773. for optimal speed. The default value is 8. See zconf.h for total memory
  75774. usage as a function of windowBits and memLevel.
  75775. The strategy parameter is used to tune the compression algorithm. Use the
  75776. value Z_DEFAULT_STRATEGY for normal data, Z_FILTERED for data produced by a
  75777. filter (or predictor), Z_HUFFMAN_ONLY to force Huffman encoding only (no
  75778. string match), or Z_RLE to limit match distances to one (run-length
  75779. encoding). Filtered data consists mostly of small values with a somewhat
  75780. random distribution. In this case, the compression algorithm is tuned to
  75781. compress them better. The effect of Z_FILTERED is to force more Huffman
  75782. coding and less string matching; it is somewhat intermediate between
  75783. Z_DEFAULT and Z_HUFFMAN_ONLY. Z_RLE is designed to be almost as fast as
  75784. Z_HUFFMAN_ONLY, but give better compression for PNG image data. The strategy
  75785. parameter only affects the compression ratio but not the correctness of the
  75786. compressed output even if it is not set appropriately. Z_FIXED prevents the
  75787. use of dynamic Huffman codes, allowing for a simpler decoder for special
  75788. applications.
  75789. deflateInit2 returns Z_OK if success, Z_MEM_ERROR if there was not enough
  75790. memory, Z_STREAM_ERROR if a parameter is invalid (such as an invalid
  75791. method). msg is set to null if there is no error message. deflateInit2 does
  75792. not perform any compression: this will be done by deflate().
  75793. */
  75794. ZEXTERN int ZEXPORT deflateSetDictionary OF((z_streamp strm,
  75795. const Bytef *dictionary,
  75796. uInt dictLength));
  75797. /*
  75798. Initializes the compression dictionary from the given byte sequence
  75799. without producing any compressed output. This function must be called
  75800. immediately after deflateInit, deflateInit2 or deflateReset, before any
  75801. call of deflate. The compressor and decompressor must use exactly the same
  75802. dictionary (see inflateSetDictionary).
  75803. The dictionary should consist of strings (byte sequences) that are likely
  75804. to be encountered later in the data to be compressed, with the most commonly
  75805. used strings preferably put towards the end of the dictionary. Using a
  75806. dictionary is most useful when the data to be compressed is short and can be
  75807. predicted with good accuracy; the data can then be compressed better than
  75808. with the default empty dictionary.
  75809. Depending on the size of the compression data structures selected by
  75810. deflateInit or deflateInit2, a part of the dictionary may in effect be
  75811. discarded, for example if the dictionary is larger than the window size in
  75812. deflate or deflate2. Thus the strings most likely to be useful should be
  75813. put at the end of the dictionary, not at the front. In addition, the
  75814. current implementation of deflate will use at most the window size minus
  75815. 262 bytes of the provided dictionary.
  75816. Upon return of this function, strm->adler is set to the adler32 value
  75817. of the dictionary; the decompressor may later use this value to determine
  75818. which dictionary has been used by the compressor. (The adler32 value
  75819. applies to the whole dictionary even if only a subset of the dictionary is
  75820. actually used by the compressor.) If a raw deflate was requested, then the
  75821. adler32 value is not computed and strm->adler is not set.
  75822. deflateSetDictionary returns Z_OK if success, or Z_STREAM_ERROR if a
  75823. parameter is invalid (such as NULL dictionary) or the stream state is
  75824. inconsistent (for example if deflate has already been called for this stream
  75825. or if the compression method is bsort). deflateSetDictionary does not
  75826. perform any compression: this will be done by deflate().
  75827. */
  75828. ZEXTERN int ZEXPORT deflateCopy OF((z_streamp dest,
  75829. z_streamp source));
  75830. /*
  75831. Sets the destination stream as a complete copy of the source stream.
  75832. This function can be useful when several compression strategies will be
  75833. tried, for example when there are several ways of pre-processing the input
  75834. data with a filter. The streams that will be discarded should then be freed
  75835. by calling deflateEnd. Note that deflateCopy duplicates the internal
  75836. compression state which can be quite large, so this strategy is slow and
  75837. can consume lots of memory.
  75838. deflateCopy returns Z_OK if success, Z_MEM_ERROR if there was not
  75839. enough memory, Z_STREAM_ERROR if the source stream state was inconsistent
  75840. (such as zalloc being NULL). msg is left unchanged in both source and
  75841. destination.
  75842. */
  75843. ZEXTERN int ZEXPORT deflateReset OF((z_streamp strm));
  75844. /*
  75845. This function is equivalent to deflateEnd followed by deflateInit,
  75846. but does not free and reallocate all the internal compression state.
  75847. The stream will keep the same compression level and any other attributes
  75848. that may have been set by deflateInit2.
  75849. deflateReset returns Z_OK if success, or Z_STREAM_ERROR if the source
  75850. stream state was inconsistent (such as zalloc or state being NULL).
  75851. */
  75852. ZEXTERN int ZEXPORT deflateParams OF((z_streamp strm,
  75853. int level,
  75854. int strategy));
  75855. /*
  75856. Dynamically update the compression level and compression strategy. The
  75857. interpretation of level and strategy is as in deflateInit2. This can be
  75858. used to switch between compression and straight copy of the input data, or
  75859. to switch to a different kind of input data requiring a different
  75860. strategy. If the compression level is changed, the input available so far
  75861. is compressed with the old level (and may be flushed); the new level will
  75862. take effect only at the next call of deflate().
  75863. Before the call of deflateParams, the stream state must be set as for
  75864. a call of deflate(), since the currently available input may have to
  75865. be compressed and flushed. In particular, strm->avail_out must be non-zero.
  75866. deflateParams returns Z_OK if success, Z_STREAM_ERROR if the source
  75867. stream state was inconsistent or if a parameter was invalid, Z_BUF_ERROR
  75868. if strm->avail_out was zero.
  75869. */
  75870. ZEXTERN int ZEXPORT deflateTune OF((z_streamp strm,
  75871. int good_length,
  75872. int max_lazy,
  75873. int nice_length,
  75874. int max_chain));
  75875. /*
  75876. Fine tune deflate's internal compression parameters. This should only be
  75877. used by someone who understands the algorithm used by zlib's deflate for
  75878. searching for the best matching string, and even then only by the most
  75879. fanatic optimizer trying to squeeze out the last compressed bit for their
  75880. specific input data. Read the deflate.c source code for the meaning of the
  75881. max_lazy, good_length, nice_length, and max_chain parameters.
  75882. deflateTune() can be called after deflateInit() or deflateInit2(), and
  75883. returns Z_OK on success, or Z_STREAM_ERROR for an invalid deflate stream.
  75884. */
  75885. ZEXTERN uLong ZEXPORT deflateBound OF((z_streamp strm,
  75886. uLong sourceLen));
  75887. /*
  75888. deflateBound() returns an upper bound on the compressed size after
  75889. deflation of sourceLen bytes. It must be called after deflateInit()
  75890. or deflateInit2(). This would be used to allocate an output buffer
  75891. for deflation in a single pass, and so would be called before deflate().
  75892. */
  75893. ZEXTERN int ZEXPORT deflatePrime OF((z_streamp strm,
  75894. int bits,
  75895. int value));
  75896. /*
  75897. deflatePrime() inserts bits in the deflate output stream. The intent
  75898. is that this function is used to start off the deflate output with the
  75899. bits leftover from a previous deflate stream when appending to it. As such,
  75900. this function can only be used for raw deflate, and must be used before the
  75901. first deflate() call after a deflateInit2() or deflateReset(). bits must be
  75902. less than or equal to 16, and that many of the least significant bits of
  75903. value will be inserted in the output.
  75904. deflatePrime returns Z_OK if success, or Z_STREAM_ERROR if the source
  75905. stream state was inconsistent.
  75906. */
  75907. ZEXTERN int ZEXPORT deflateSetHeader OF((z_streamp strm,
  75908. gz_headerp head));
  75909. /*
  75910. deflateSetHeader() provides gzip header information for when a gzip
  75911. stream is requested by deflateInit2(). deflateSetHeader() may be called
  75912. after deflateInit2() or deflateReset() and before the first call of
  75913. deflate(). The text, time, os, extra field, name, and comment information
  75914. in the provided gz_header structure are written to the gzip header (xflag is
  75915. ignored -- the extra flags are set according to the compression level). The
  75916. caller must assure that, if not Z_NULL, name and comment are terminated with
  75917. a zero byte, and that if extra is not Z_NULL, that extra_len bytes are
  75918. available there. If hcrc is true, a gzip header crc is included. Note that
  75919. the current versions of the command-line version of gzip (up through version
  75920. 1.3.x) do not support header crc's, and will report that it is a "multi-part
  75921. gzip file" and give up.
  75922. If deflateSetHeader is not used, the default gzip header has text false,
  75923. the time set to zero, and os set to 255, with no extra, name, or comment
  75924. fields. The gzip header is returned to the default state by deflateReset().
  75925. deflateSetHeader returns Z_OK if success, or Z_STREAM_ERROR if the source
  75926. stream state was inconsistent.
  75927. */
  75928. /*
  75929. ZEXTERN int ZEXPORT inflateInit2 OF((z_streamp strm,
  75930. int windowBits));
  75931. This is another version of inflateInit with an extra parameter. The
  75932. fields next_in, avail_in, zalloc, zfree and opaque must be initialized
  75933. before by the caller.
  75934. The windowBits parameter is the base two logarithm of the maximum window
  75935. size (the size of the history buffer). It should be in the range 8..15 for
  75936. this version of the library. The default value is 15 if inflateInit is used
  75937. instead. windowBits must be greater than or equal to the windowBits value
  75938. provided to deflateInit2() while compressing, or it must be equal to 15 if
  75939. deflateInit2() was not used. If a compressed stream with a larger window
  75940. size is given as input, inflate() will return with the error code
  75941. Z_DATA_ERROR instead of trying to allocate a larger window.
  75942. windowBits can also be -8..-15 for raw inflate. In this case, -windowBits
  75943. determines the window size. inflate() will then process raw deflate data,
  75944. not looking for a zlib or gzip header, not generating a check value, and not
  75945. looking for any check values for comparison at the end of the stream. This
  75946. is for use with other formats that use the deflate compressed data format
  75947. such as zip. Those formats provide their own check values. If a custom
  75948. format is developed using the raw deflate format for compressed data, it is
  75949. recommended that a check value such as an adler32 or a crc32 be applied to
  75950. the uncompressed data as is done in the zlib, gzip, and zip formats. For
  75951. most applications, the zlib format should be used as is. Note that comments
  75952. above on the use in deflateInit2() applies to the magnitude of windowBits.
  75953. windowBits can also be greater than 15 for optional gzip decoding. Add
  75954. 32 to windowBits to enable zlib and gzip decoding with automatic header
  75955. detection, or add 16 to decode only the gzip format (the zlib format will
  75956. return a Z_DATA_ERROR). If a gzip stream is being decoded, strm->adler is
  75957. a crc32 instead of an adler32.
  75958. inflateInit2 returns Z_OK if success, Z_MEM_ERROR if there was not enough
  75959. memory, Z_STREAM_ERROR if a parameter is invalid (such as a null strm). msg
  75960. is set to null if there is no error message. inflateInit2 does not perform
  75961. any decompression apart from reading the zlib header if present: this will
  75962. be done by inflate(). (So next_in and avail_in may be modified, but next_out
  75963. and avail_out are unchanged.)
  75964. */
  75965. ZEXTERN int ZEXPORT inflateSetDictionary OF((z_streamp strm,
  75966. const Bytef *dictionary,
  75967. uInt dictLength));
  75968. /*
  75969. Initializes the decompression dictionary from the given uncompressed byte
  75970. sequence. This function must be called immediately after a call of inflate,
  75971. if that call returned Z_NEED_DICT. The dictionary chosen by the compressor
  75972. can be determined from the adler32 value returned by that call of inflate.
  75973. The compressor and decompressor must use exactly the same dictionary (see
  75974. deflateSetDictionary). For raw inflate, this function can be called
  75975. immediately after inflateInit2() or inflateReset() and before any call of
  75976. inflate() to set the dictionary. The application must insure that the
  75977. dictionary that was used for compression is provided.
  75978. inflateSetDictionary returns Z_OK if success, Z_STREAM_ERROR if a
  75979. parameter is invalid (such as NULL dictionary) or the stream state is
  75980. inconsistent, Z_DATA_ERROR if the given dictionary doesn't match the
  75981. expected one (incorrect adler32 value). inflateSetDictionary does not
  75982. perform any decompression: this will be done by subsequent calls of
  75983. inflate().
  75984. */
  75985. ZEXTERN int ZEXPORT inflateSync OF((z_streamp strm));
  75986. /*
  75987. Skips invalid compressed data until a full flush point (see above the
  75988. description of deflate with Z_FULL_FLUSH) can be found, or until all
  75989. available input is skipped. No output is provided.
  75990. inflateSync returns Z_OK if a full flush point has been found, Z_BUF_ERROR
  75991. if no more input was provided, Z_DATA_ERROR if no flush point has been found,
  75992. or Z_STREAM_ERROR if the stream structure was inconsistent. In the success
  75993. case, the application may save the current current value of total_in which
  75994. indicates where valid compressed data was found. In the error case, the
  75995. application may repeatedly call inflateSync, providing more input each time,
  75996. until success or end of the input data.
  75997. */
  75998. ZEXTERN int ZEXPORT inflateCopy OF((z_streamp dest,
  75999. z_streamp source));
  76000. /*
  76001. Sets the destination stream as a complete copy of the source stream.
  76002. This function can be useful when randomly accessing a large stream. The
  76003. first pass through the stream can periodically record the inflate state,
  76004. allowing restarting inflate at those points when randomly accessing the
  76005. stream.
  76006. inflateCopy returns Z_OK if success, Z_MEM_ERROR if there was not
  76007. enough memory, Z_STREAM_ERROR if the source stream state was inconsistent
  76008. (such as zalloc being NULL). msg is left unchanged in both source and
  76009. destination.
  76010. */
  76011. ZEXTERN int ZEXPORT inflateReset OF((z_streamp strm));
  76012. /*
  76013. This function is equivalent to inflateEnd followed by inflateInit,
  76014. but does not free and reallocate all the internal decompression state.
  76015. The stream will keep attributes that may have been set by inflateInit2.
  76016. inflateReset returns Z_OK if success, or Z_STREAM_ERROR if the source
  76017. stream state was inconsistent (such as zalloc or state being NULL).
  76018. */
  76019. ZEXTERN int ZEXPORT inflatePrime OF((z_streamp strm,
  76020. int bits,
  76021. int value));
  76022. /*
  76023. This function inserts bits in the inflate input stream. The intent is
  76024. that this function is used to start inflating at a bit position in the
  76025. middle of a byte. The provided bits will be used before any bytes are used
  76026. from next_in. This function should only be used with raw inflate, and
  76027. should be used before the first inflate() call after inflateInit2() or
  76028. inflateReset(). bits must be less than or equal to 16, and that many of the
  76029. least significant bits of value will be inserted in the input.
  76030. inflatePrime returns Z_OK if success, or Z_STREAM_ERROR if the source
  76031. stream state was inconsistent.
  76032. */
  76033. ZEXTERN int ZEXPORT inflateGetHeader OF((z_streamp strm,
  76034. gz_headerp head));
  76035. /*
  76036. inflateGetHeader() requests that gzip header information be stored in the
  76037. provided gz_header structure. inflateGetHeader() may be called after
  76038. inflateInit2() or inflateReset(), and before the first call of inflate().
  76039. As inflate() processes the gzip stream, head->done is zero until the header
  76040. is completed, at which time head->done is set to one. If a zlib stream is
  76041. being decoded, then head->done is set to -1 to indicate that there will be
  76042. no gzip header information forthcoming. Note that Z_BLOCK can be used to
  76043. force inflate() to return immediately after header processing is complete
  76044. and before any actual data is decompressed.
  76045. The text, time, xflags, and os fields are filled in with the gzip header
  76046. contents. hcrc is set to true if there is a header CRC. (The header CRC
  76047. was valid if done is set to one.) If extra is not Z_NULL, then extra_max
  76048. contains the maximum number of bytes to write to extra. Once done is true,
  76049. extra_len contains the actual extra field length, and extra contains the
  76050. extra field, or that field truncated if extra_max is less than extra_len.
  76051. If name is not Z_NULL, then up to name_max characters are written there,
  76052. terminated with a zero unless the length is greater than name_max. If
  76053. comment is not Z_NULL, then up to comm_max characters are written there,
  76054. terminated with a zero unless the length is greater than comm_max. When
  76055. any of extra, name, or comment are not Z_NULL and the respective field is
  76056. not present in the header, then that field is set to Z_NULL to signal its
  76057. absence. This allows the use of deflateSetHeader() with the returned
  76058. structure to duplicate the header. However if those fields are set to
  76059. allocated memory, then the application will need to save those pointers
  76060. elsewhere so that they can be eventually freed.
  76061. If inflateGetHeader is not used, then the header information is simply
  76062. discarded. The header is always checked for validity, including the header
  76063. CRC if present. inflateReset() will reset the process to discard the header
  76064. information. The application would need to call inflateGetHeader() again to
  76065. retrieve the header from the next gzip stream.
  76066. inflateGetHeader returns Z_OK if success, or Z_STREAM_ERROR if the source
  76067. stream state was inconsistent.
  76068. */
  76069. /*
  76070. ZEXTERN int ZEXPORT inflateBackInit OF((z_streamp strm, int windowBits,
  76071. unsigned char FAR *window));
  76072. Initialize the internal stream state for decompression using inflateBack()
  76073. calls. The fields zalloc, zfree and opaque in strm must be initialized
  76074. before the call. If zalloc and zfree are Z_NULL, then the default library-
  76075. derived memory allocation routines are used. windowBits is the base two
  76076. logarithm of the window size, in the range 8..15. window is a caller
  76077. supplied buffer of that size. Except for special applications where it is
  76078. assured that deflate was used with small window sizes, windowBits must be 15
  76079. and a 32K byte window must be supplied to be able to decompress general
  76080. deflate streams.
  76081. See inflateBack() for the usage of these routines.
  76082. inflateBackInit will return Z_OK on success, Z_STREAM_ERROR if any of
  76083. the paramaters are invalid, Z_MEM_ERROR if the internal state could not
  76084. be allocated, or Z_VERSION_ERROR if the version of the library does not
  76085. match the version of the header file.
  76086. */
  76087. typedef unsigned (*in_func) OF((void FAR *, unsigned char FAR * FAR *));
  76088. typedef int (*out_func) OF((void FAR *, unsigned char FAR *, unsigned));
  76089. ZEXTERN int ZEXPORT inflateBack OF((z_streamp strm,
  76090. in_func in, void FAR *in_desc,
  76091. out_func out, void FAR *out_desc));
  76092. /*
  76093. inflateBack() does a raw inflate with a single call using a call-back
  76094. interface for input and output. This is more efficient than inflate() for
  76095. file i/o applications in that it avoids copying between the output and the
  76096. sliding window by simply making the window itself the output buffer. This
  76097. function trusts the application to not change the output buffer passed by
  76098. the output function, at least until inflateBack() returns.
  76099. inflateBackInit() must be called first to allocate the internal state
  76100. and to initialize the state with the user-provided window buffer.
  76101. inflateBack() may then be used multiple times to inflate a complete, raw
  76102. deflate stream with each call. inflateBackEnd() is then called to free
  76103. the allocated state.
  76104. A raw deflate stream is one with no zlib or gzip header or trailer.
  76105. This routine would normally be used in a utility that reads zip or gzip
  76106. files and writes out uncompressed files. The utility would decode the
  76107. header and process the trailer on its own, hence this routine expects
  76108. only the raw deflate stream to decompress. This is different from the
  76109. normal behavior of inflate(), which expects either a zlib or gzip header and
  76110. trailer around the deflate stream.
  76111. inflateBack() uses two subroutines supplied by the caller that are then
  76112. called by inflateBack() for input and output. inflateBack() calls those
  76113. routines until it reads a complete deflate stream and writes out all of the
  76114. uncompressed data, or until it encounters an error. The function's
  76115. parameters and return types are defined above in the in_func and out_func
  76116. typedefs. inflateBack() will call in(in_desc, &buf) which should return the
  76117. number of bytes of provided input, and a pointer to that input in buf. If
  76118. there is no input available, in() must return zero--buf is ignored in that
  76119. case--and inflateBack() will return a buffer error. inflateBack() will call
  76120. out(out_desc, buf, len) to write the uncompressed data buf[0..len-1]. out()
  76121. should return zero on success, or non-zero on failure. If out() returns
  76122. non-zero, inflateBack() will return with an error. Neither in() nor out()
  76123. are permitted to change the contents of the window provided to
  76124. inflateBackInit(), which is also the buffer that out() uses to write from.
  76125. The length written by out() will be at most the window size. Any non-zero
  76126. amount of input may be provided by in().
  76127. For convenience, inflateBack() can be provided input on the first call by
  76128. setting strm->next_in and strm->avail_in. If that input is exhausted, then
  76129. in() will be called. Therefore strm->next_in must be initialized before
  76130. calling inflateBack(). If strm->next_in is Z_NULL, then in() will be called
  76131. immediately for input. If strm->next_in is not Z_NULL, then strm->avail_in
  76132. must also be initialized, and then if strm->avail_in is not zero, input will
  76133. initially be taken from strm->next_in[0 .. strm->avail_in - 1].
  76134. The in_desc and out_desc parameters of inflateBack() is passed as the
  76135. first parameter of in() and out() respectively when they are called. These
  76136. descriptors can be optionally used to pass any information that the caller-
  76137. supplied in() and out() functions need to do their job.
  76138. On return, inflateBack() will set strm->next_in and strm->avail_in to
  76139. pass back any unused input that was provided by the last in() call. The
  76140. return values of inflateBack() can be Z_STREAM_END on success, Z_BUF_ERROR
  76141. if in() or out() returned an error, Z_DATA_ERROR if there was a format
  76142. error in the deflate stream (in which case strm->msg is set to indicate the
  76143. nature of the error), or Z_STREAM_ERROR if the stream was not properly
  76144. initialized. In the case of Z_BUF_ERROR, an input or output error can be
  76145. distinguished using strm->next_in which will be Z_NULL only if in() returned
  76146. an error. If strm->next is not Z_NULL, then the Z_BUF_ERROR was due to
  76147. out() returning non-zero. (in() will always be called before out(), so
  76148. strm->next_in is assured to be defined if out() returns non-zero.) Note
  76149. that inflateBack() cannot return Z_OK.
  76150. */
  76151. ZEXTERN int ZEXPORT inflateBackEnd OF((z_streamp strm));
  76152. /*
  76153. All memory allocated by inflateBackInit() is freed.
  76154. inflateBackEnd() returns Z_OK on success, or Z_STREAM_ERROR if the stream
  76155. state was inconsistent.
  76156. */
  76157. //ZEXTERN uLong ZEXPORT zlibCompileFlags OF((void));
  76158. /* Return flags indicating compile-time options.
  76159. Type sizes, two bits each, 00 = 16 bits, 01 = 32, 10 = 64, 11 = other:
  76160. 1.0: size of uInt
  76161. 3.2: size of uLong
  76162. 5.4: size of voidpf (pointer)
  76163. 7.6: size of z_off_t
  76164. Compiler, assembler, and debug options:
  76165. 8: DEBUG
  76166. 9: ASMV or ASMINF -- use ASM code
  76167. 10: ZLIB_WINAPI -- exported functions use the WINAPI calling convention
  76168. 11: 0 (reserved)
  76169. One-time table building (smaller code, but not thread-safe if true):
  76170. 12: BUILDFIXED -- build static block decoding tables when needed
  76171. 13: DYNAMIC_CRC_TABLE -- build CRC calculation tables when needed
  76172. 14,15: 0 (reserved)
  76173. Library content (indicates missing functionality):
  76174. 16: NO_GZCOMPRESS -- gz* functions cannot compress (to avoid linking
  76175. deflate code when not needed)
  76176. 17: NO_GZIP -- deflate can't write gzip streams, and inflate can't detect
  76177. and decode gzip streams (to avoid linking crc code)
  76178. 18-19: 0 (reserved)
  76179. Operation variations (changes in library functionality):
  76180. 20: PKZIP_BUG_WORKAROUND -- slightly more permissive inflate
  76181. 21: FASTEST -- deflate algorithm with only one, lowest compression level
  76182. 22,23: 0 (reserved)
  76183. The sprintf variant used by gzprintf (zero is best):
  76184. 24: 0 = vs*, 1 = s* -- 1 means limited to 20 arguments after the format
  76185. 25: 0 = *nprintf, 1 = *printf -- 1 means gzprintf() not secure!
  76186. 26: 0 = returns value, 1 = void -- 1 means inferred string length returned
  76187. Remainder:
  76188. 27-31: 0 (reserved)
  76189. */
  76190. /* utility functions */
  76191. /*
  76192. The following utility functions are implemented on top of the
  76193. basic stream-oriented functions. To simplify the interface, some
  76194. default options are assumed (compression level and memory usage,
  76195. standard memory allocation functions). The source code of these
  76196. utility functions can easily be modified if you need special options.
  76197. */
  76198. ZEXTERN int ZEXPORT compress OF((Bytef *dest, uLongf *destLen,
  76199. const Bytef *source, uLong sourceLen));
  76200. /*
  76201. Compresses the source buffer into the destination buffer. sourceLen is
  76202. the byte length of the source buffer. Upon entry, destLen is the total
  76203. size of the destination buffer, which must be at least the value returned
  76204. by compressBound(sourceLen). Upon exit, destLen is the actual size of the
  76205. compressed buffer.
  76206. This function can be used to compress a whole file at once if the
  76207. input file is mmap'ed.
  76208. compress returns Z_OK if success, Z_MEM_ERROR if there was not
  76209. enough memory, Z_BUF_ERROR if there was not enough room in the output
  76210. buffer.
  76211. */
  76212. ZEXTERN int ZEXPORT compress2 OF((Bytef *dest, uLongf *destLen,
  76213. const Bytef *source, uLong sourceLen,
  76214. int level));
  76215. /*
  76216. Compresses the source buffer into the destination buffer. The level
  76217. parameter has the same meaning as in deflateInit. sourceLen is the byte
  76218. length of the source buffer. Upon entry, destLen is the total size of the
  76219. destination buffer, which must be at least the value returned by
  76220. compressBound(sourceLen). Upon exit, destLen is the actual size of the
  76221. compressed buffer.
  76222. compress2 returns Z_OK if success, Z_MEM_ERROR if there was not enough
  76223. memory, Z_BUF_ERROR if there was not enough room in the output buffer,
  76224. Z_STREAM_ERROR if the level parameter is invalid.
  76225. */
  76226. ZEXTERN uLong ZEXPORT compressBound OF((uLong sourceLen));
  76227. /*
  76228. compressBound() returns an upper bound on the compressed size after
  76229. compress() or compress2() on sourceLen bytes. It would be used before
  76230. a compress() or compress2() call to allocate the destination buffer.
  76231. */
  76232. ZEXTERN int ZEXPORT uncompress OF((Bytef *dest, uLongf *destLen,
  76233. const Bytef *source, uLong sourceLen));
  76234. /*
  76235. Decompresses the source buffer into the destination buffer. sourceLen is
  76236. the byte length of the source buffer. Upon entry, destLen is the total
  76237. size of the destination buffer, which must be large enough to hold the
  76238. entire uncompressed data. (The size of the uncompressed data must have
  76239. been saved previously by the compressor and transmitted to the decompressor
  76240. by some mechanism outside the scope of this compression library.)
  76241. Upon exit, destLen is the actual size of the compressed buffer.
  76242. This function can be used to decompress a whole file at once if the
  76243. input file is mmap'ed.
  76244. uncompress returns Z_OK if success, Z_MEM_ERROR if there was not
  76245. enough memory, Z_BUF_ERROR if there was not enough room in the output
  76246. buffer, or Z_DATA_ERROR if the input data was corrupted or incomplete.
  76247. */
  76248. typedef voidp gzFile;
  76249. ZEXTERN gzFile ZEXPORT gzopen OF((const char *path, const char *mode));
  76250. /*
  76251. Opens a gzip (.gz) file for reading or writing. The mode parameter
  76252. is as in fopen ("rb" or "wb") but can also include a compression level
  76253. ("wb9") or a strategy: 'f' for filtered data as in "wb6f", 'h' for
  76254. Huffman only compression as in "wb1h", or 'R' for run-length encoding
  76255. as in "wb1R". (See the description of deflateInit2 for more information
  76256. about the strategy parameter.)
  76257. gzopen can be used to read a file which is not in gzip format; in this
  76258. case gzread will directly read from the file without decompression.
  76259. gzopen returns NULL if the file could not be opened or if there was
  76260. insufficient memory to allocate the (de)compression state; errno
  76261. can be checked to distinguish the two cases (if errno is zero, the
  76262. zlib error is Z_MEM_ERROR). */
  76263. ZEXTERN gzFile ZEXPORT gzdopen OF((int fd, const char *mode));
  76264. /*
  76265. gzdopen() associates a gzFile with the file descriptor fd. File
  76266. descriptors are obtained from calls like open, dup, creat, pipe or
  76267. fileno (in the file has been previously opened with fopen).
  76268. The mode parameter is as in gzopen.
  76269. The next call of gzclose on the returned gzFile will also close the
  76270. file descriptor fd, just like fclose(fdopen(fd), mode) closes the file
  76271. descriptor fd. If you want to keep fd open, use gzdopen(dup(fd), mode).
  76272. gzdopen returns NULL if there was insufficient memory to allocate
  76273. the (de)compression state.
  76274. */
  76275. ZEXTERN int ZEXPORT gzsetparams OF((gzFile file, int level, int strategy));
  76276. /*
  76277. Dynamically update the compression level or strategy. See the description
  76278. of deflateInit2 for the meaning of these parameters.
  76279. gzsetparams returns Z_OK if success, or Z_STREAM_ERROR if the file was not
  76280. opened for writing.
  76281. */
  76282. ZEXTERN int ZEXPORT gzread OF((gzFile file, voidp buf, unsigned len));
  76283. /*
  76284. Reads the given number of uncompressed bytes from the compressed file.
  76285. If the input file was not in gzip format, gzread copies the given number
  76286. of bytes into the buffer.
  76287. gzread returns the number of uncompressed bytes actually read (0 for
  76288. end of file, -1 for error). */
  76289. ZEXTERN int ZEXPORT gzwrite OF((gzFile file,
  76290. voidpc buf, unsigned len));
  76291. /*
  76292. Writes the given number of uncompressed bytes into the compressed file.
  76293. gzwrite returns the number of uncompressed bytes actually written
  76294. (0 in case of error).
  76295. */
  76296. ZEXTERN int ZEXPORTVA gzprintf OF((gzFile file, const char *format, ...));
  76297. /*
  76298. Converts, formats, and writes the args to the compressed file under
  76299. control of the format string, as in fprintf. gzprintf returns the number of
  76300. uncompressed bytes actually written (0 in case of error). The number of
  76301. uncompressed bytes written is limited to 4095. The caller should assure that
  76302. this limit is not exceeded. If it is exceeded, then gzprintf() will return
  76303. return an error (0) with nothing written. In this case, there may also be a
  76304. buffer overflow with unpredictable consequences, which is possible only if
  76305. zlib was compiled with the insecure functions sprintf() or vsprintf()
  76306. because the secure snprintf() or vsnprintf() functions were not available.
  76307. */
  76308. ZEXTERN int ZEXPORT gzputs OF((gzFile file, const char *s));
  76309. /*
  76310. Writes the given null-terminated string to the compressed file, excluding
  76311. the terminating null character.
  76312. gzputs returns the number of characters written, or -1 in case of error.
  76313. */
  76314. ZEXTERN char * ZEXPORT gzgets OF((gzFile file, char *buf, int len));
  76315. /*
  76316. Reads bytes from the compressed file until len-1 characters are read, or
  76317. a newline character is read and transferred to buf, or an end-of-file
  76318. condition is encountered. The string is then terminated with a null
  76319. character.
  76320. gzgets returns buf, or Z_NULL in case of error.
  76321. */
  76322. ZEXTERN int ZEXPORT gzputc OF((gzFile file, int c));
  76323. /*
  76324. Writes c, converted to an unsigned char, into the compressed file.
  76325. gzputc returns the value that was written, or -1 in case of error.
  76326. */
  76327. ZEXTERN int ZEXPORT gzgetc OF((gzFile file));
  76328. /*
  76329. Reads one byte from the compressed file. gzgetc returns this byte
  76330. or -1 in case of end of file or error.
  76331. */
  76332. ZEXTERN int ZEXPORT gzungetc OF((int c, gzFile file));
  76333. /*
  76334. Push one character back onto the stream to be read again later.
  76335. Only one character of push-back is allowed. gzungetc() returns the
  76336. character pushed, or -1 on failure. gzungetc() will fail if a
  76337. character has been pushed but not read yet, or if c is -1. The pushed
  76338. character will be discarded if the stream is repositioned with gzseek()
  76339. or gzrewind().
  76340. */
  76341. ZEXTERN int ZEXPORT gzflush OF((gzFile file, int flush));
  76342. /*
  76343. Flushes all pending output into the compressed file. The parameter
  76344. flush is as in the deflate() function. The return value is the zlib
  76345. error number (see function gzerror below). gzflush returns Z_OK if
  76346. the flush parameter is Z_FINISH and all output could be flushed.
  76347. gzflush should be called only when strictly necessary because it can
  76348. degrade compression.
  76349. */
  76350. ZEXTERN z_off_t ZEXPORT gzseek OF((gzFile file,
  76351. z_off_t offset, int whence));
  76352. /*
  76353. Sets the starting position for the next gzread or gzwrite on the
  76354. given compressed file. The offset represents a number of bytes in the
  76355. uncompressed data stream. The whence parameter is defined as in lseek(2);
  76356. the value SEEK_END is not supported.
  76357. If the file is opened for reading, this function is emulated but can be
  76358. extremely slow. If the file is opened for writing, only forward seeks are
  76359. supported; gzseek then compresses a sequence of zeroes up to the new
  76360. starting position.
  76361. gzseek returns the resulting offset location as measured in bytes from
  76362. the beginning of the uncompressed stream, or -1 in case of error, in
  76363. particular if the file is opened for writing and the new starting position
  76364. would be before the current position.
  76365. */
  76366. ZEXTERN int ZEXPORT gzrewind OF((gzFile file));
  76367. /*
  76368. Rewinds the given file. This function is supported only for reading.
  76369. gzrewind(file) is equivalent to (int)gzseek(file, 0L, SEEK_SET)
  76370. */
  76371. ZEXTERN z_off_t ZEXPORT gztell OF((gzFile file));
  76372. /*
  76373. Returns the starting position for the next gzread or gzwrite on the
  76374. given compressed file. This position represents a number of bytes in the
  76375. uncompressed data stream.
  76376. gztell(file) is equivalent to gzseek(file, 0L, SEEK_CUR)
  76377. */
  76378. ZEXTERN int ZEXPORT gzeof OF((gzFile file));
  76379. /*
  76380. Returns 1 when EOF has previously been detected reading the given
  76381. input stream, otherwise zero.
  76382. */
  76383. ZEXTERN int ZEXPORT gzdirect OF((gzFile file));
  76384. /*
  76385. Returns 1 if file is being read directly without decompression, otherwise
  76386. zero.
  76387. */
  76388. ZEXTERN int ZEXPORT gzclose OF((gzFile file));
  76389. /*
  76390. Flushes all pending output if necessary, closes the compressed file
  76391. and deallocates all the (de)compression state. The return value is the zlib
  76392. error number (see function gzerror below).
  76393. */
  76394. ZEXTERN const char * ZEXPORT gzerror OF((gzFile file, int *errnum));
  76395. /*
  76396. Returns the error message for the last error which occurred on the
  76397. given compressed file. errnum is set to zlib error number. If an
  76398. error occurred in the file system and not in the compression library,
  76399. errnum is set to Z_ERRNO and the application may consult errno
  76400. to get the exact error code.
  76401. */
  76402. ZEXTERN void ZEXPORT gzclearerr OF((gzFile file));
  76403. /*
  76404. Clears the error and end-of-file flags for file. This is analogous to the
  76405. clearerr() function in stdio. This is useful for continuing to read a gzip
  76406. file that is being written concurrently.
  76407. */
  76408. /* checksum functions */
  76409. /*
  76410. These functions are not related to compression but are exported
  76411. anyway because they might be useful in applications using the
  76412. compression library.
  76413. */
  76414. ZEXTERN uLong ZEXPORT adler32 OF((uLong adler, const Bytef *buf, uInt len));
  76415. /*
  76416. Update a running Adler-32 checksum with the bytes buf[0..len-1] and
  76417. return the updated checksum. If buf is NULL, this function returns
  76418. the required initial value for the checksum.
  76419. An Adler-32 checksum is almost as reliable as a CRC32 but can be computed
  76420. much faster. Usage example:
  76421. uLong adler = adler32(0L, Z_NULL, 0);
  76422. while (read_buffer(buffer, length) != EOF) {
  76423. adler = adler32(adler, buffer, length);
  76424. }
  76425. if (adler != original_adler) error();
  76426. */
  76427. ZEXTERN uLong ZEXPORT adler32_combine OF((uLong adler1, uLong adler2,
  76428. z_off_t len2));
  76429. /*
  76430. Combine two Adler-32 checksums into one. For two sequences of bytes, seq1
  76431. and seq2 with lengths len1 and len2, Adler-32 checksums were calculated for
  76432. each, adler1 and adler2. adler32_combine() returns the Adler-32 checksum of
  76433. seq1 and seq2 concatenated, requiring only adler1, adler2, and len2.
  76434. */
  76435. ZEXTERN uLong ZEXPORT crc32 OF((uLong crc, const Bytef *buf, uInt len));
  76436. /*
  76437. Update a running CRC-32 with the bytes buf[0..len-1] and return the
  76438. updated CRC-32. If buf is NULL, this function returns the required initial
  76439. value for the for the crc. Pre- and post-conditioning (one's complement) is
  76440. performed within this function so it shouldn't be done by the application.
  76441. Usage example:
  76442. uLong crc = crc32(0L, Z_NULL, 0);
  76443. while (read_buffer(buffer, length) != EOF) {
  76444. crc = crc32(crc, buffer, length);
  76445. }
  76446. if (crc != original_crc) error();
  76447. */
  76448. ZEXTERN uLong ZEXPORT crc32_combine OF((uLong crc1, uLong crc2, z_off_t len2));
  76449. /*
  76450. Combine two CRC-32 check values into one. For two sequences of bytes,
  76451. seq1 and seq2 with lengths len1 and len2, CRC-32 check values were
  76452. calculated for each, crc1 and crc2. crc32_combine() returns the CRC-32
  76453. check value of seq1 and seq2 concatenated, requiring only crc1, crc2, and
  76454. len2.
  76455. */
  76456. /* various hacks, don't look :) */
  76457. /* deflateInit and inflateInit are macros to allow checking the zlib version
  76458. * and the compiler's view of z_stream:
  76459. */
  76460. ZEXTERN int ZEXPORT deflateInit_ OF((z_streamp strm, int level,
  76461. const char *version, int stream_size));
  76462. ZEXTERN int ZEXPORT inflateInit_ OF((z_streamp strm,
  76463. const char *version, int stream_size));
  76464. ZEXTERN int ZEXPORT deflateInit2_ OF((z_streamp strm, int level, int method,
  76465. int windowBits, int memLevel,
  76466. int strategy, const char *version,
  76467. int stream_size));
  76468. ZEXTERN int ZEXPORT inflateInit2_ OF((z_streamp strm, int windowBits,
  76469. const char *version, int stream_size));
  76470. ZEXTERN int ZEXPORT inflateBackInit_ OF((z_streamp strm, int windowBits,
  76471. unsigned char FAR *window,
  76472. const char *version,
  76473. int stream_size));
  76474. #define deflateInit(strm, level) \
  76475. deflateInit_((strm), (level), ZLIB_VERSION, sizeof(z_stream))
  76476. #define inflateInit(strm) \
  76477. inflateInit_((strm), ZLIB_VERSION, sizeof(z_stream))
  76478. #define deflateInit2(strm, level, method, windowBits, memLevel, strategy) \
  76479. deflateInit2_((strm),(level),(method),(windowBits),(memLevel),\
  76480. (strategy), ZLIB_VERSION, sizeof(z_stream))
  76481. #define inflateInit2(strm, windowBits) \
  76482. inflateInit2_((strm), (windowBits), ZLIB_VERSION, sizeof(z_stream))
  76483. #define inflateBackInit(strm, windowBits, window) \
  76484. inflateBackInit_((strm), (windowBits), (window), \
  76485. ZLIB_VERSION, sizeof(z_stream))
  76486. #if !defined(ZUTIL_H) && !defined(NO_DUMMY_DECL)
  76487. struct internal_state {int dummy;}; /* hack for buggy compilers */
  76488. #endif
  76489. ZEXTERN const char * ZEXPORT zError OF((int));
  76490. ZEXTERN int ZEXPORT inflateSyncPoint OF((z_streamp z));
  76491. ZEXTERN const uLongf * ZEXPORT get_crc_table OF((void));
  76492. #ifdef __cplusplus
  76493. }
  76494. #endif
  76495. #endif /* ZLIB_H */
  76496. /*** End of inlined file: zlib.h ***/
  76497. #undef OS_CODE
  76498. #else
  76499. #include <zlib.h>
  76500. #endif
  76501. }
  76502. BEGIN_JUCE_NAMESPACE
  76503. // internal helper object that holds the zlib structures so they don't have to be
  76504. // included publicly.
  76505. class GZIPCompressorHelper
  76506. {
  76507. public:
  76508. GZIPCompressorHelper (const int compressionLevel, const bool nowrap)
  76509. : data (0),
  76510. dataSize (0),
  76511. compLevel (compressionLevel),
  76512. strategy (0),
  76513. setParams (true),
  76514. streamIsValid (false),
  76515. finished (false),
  76516. shouldFinish (false)
  76517. {
  76518. using namespace zlibNamespace;
  76519. zerostruct (stream);
  76520. streamIsValid = (deflateInit2 (&stream, compLevel, Z_DEFLATED,
  76521. nowrap ? -MAX_WBITS : MAX_WBITS,
  76522. 8, strategy) == Z_OK);
  76523. }
  76524. ~GZIPCompressorHelper()
  76525. {
  76526. using namespace zlibNamespace;
  76527. if (streamIsValid)
  76528. deflateEnd (&stream);
  76529. }
  76530. bool needsInput() const throw()
  76531. {
  76532. return dataSize <= 0;
  76533. }
  76534. void setInput (const uint8* const newData, const int size) throw()
  76535. {
  76536. data = newData;
  76537. dataSize = size;
  76538. }
  76539. int doNextBlock (uint8* const dest, const int destSize) throw()
  76540. {
  76541. using namespace zlibNamespace;
  76542. if (streamIsValid)
  76543. {
  76544. stream.next_in = const_cast <uint8*> (data);
  76545. stream.next_out = dest;
  76546. stream.avail_in = dataSize;
  76547. stream.avail_out = destSize;
  76548. const int result = setParams ? deflateParams (&stream, compLevel, strategy)
  76549. : deflate (&stream, shouldFinish ? Z_FINISH : Z_NO_FLUSH);
  76550. setParams = false;
  76551. switch (result)
  76552. {
  76553. case Z_STREAM_END:
  76554. finished = true;
  76555. // Deliberate fall-through..
  76556. case Z_OK:
  76557. data += dataSize - stream.avail_in;
  76558. dataSize = stream.avail_in;
  76559. return destSize - stream.avail_out;
  76560. default:
  76561. break;
  76562. }
  76563. }
  76564. return 0;
  76565. }
  76566. private:
  76567. zlibNamespace::z_stream stream;
  76568. const uint8* data;
  76569. int dataSize, compLevel, strategy;
  76570. bool setParams, streamIsValid;
  76571. public:
  76572. bool finished, shouldFinish;
  76573. };
  76574. const int gzipCompBufferSize = 32768;
  76575. GZIPCompressorOutputStream::GZIPCompressorOutputStream (OutputStream* const destStream_,
  76576. int compressionLevel,
  76577. const bool deleteDestStream,
  76578. const bool noWrap)
  76579. : destStream (destStream_),
  76580. streamToDelete (deleteDestStream ? destStream_ : 0),
  76581. buffer (gzipCompBufferSize)
  76582. {
  76583. if (compressionLevel < 1 || compressionLevel > 9)
  76584. compressionLevel = -1;
  76585. helper = new GZIPCompressorHelper (compressionLevel, noWrap);
  76586. }
  76587. GZIPCompressorOutputStream::~GZIPCompressorOutputStream()
  76588. {
  76589. flush();
  76590. }
  76591. void GZIPCompressorOutputStream::flush()
  76592. {
  76593. if (! helper->finished)
  76594. {
  76595. helper->shouldFinish = true;
  76596. while (! helper->finished)
  76597. doNextBlock();
  76598. }
  76599. destStream->flush();
  76600. }
  76601. bool GZIPCompressorOutputStream::write (const void* destBuffer, int howMany)
  76602. {
  76603. if (! helper->finished)
  76604. {
  76605. helper->setInput (static_cast <const uint8*> (destBuffer), howMany);
  76606. while (! helper->needsInput())
  76607. {
  76608. if (! doNextBlock())
  76609. return false;
  76610. }
  76611. }
  76612. return true;
  76613. }
  76614. bool GZIPCompressorOutputStream::doNextBlock()
  76615. {
  76616. const int len = helper->doNextBlock (buffer, gzipCompBufferSize);
  76617. if (len > 0)
  76618. return destStream->write (buffer, len);
  76619. else
  76620. return true;
  76621. }
  76622. int64 GZIPCompressorOutputStream::getPosition()
  76623. {
  76624. return destStream->getPosition();
  76625. }
  76626. bool GZIPCompressorOutputStream::setPosition (int64 /*newPosition*/)
  76627. {
  76628. jassertfalse // can't do it!
  76629. return false;
  76630. }
  76631. END_JUCE_NAMESPACE
  76632. /*** End of inlined file: juce_GZIPCompressorOutputStream.cpp ***/
  76633. /*** Start of inlined file: juce_GZIPDecompressorInputStream.cpp ***/
  76634. #if JUCE_MSVC
  76635. #pragma warning (push)
  76636. #pragma warning (disable: 4309 4305)
  76637. #endif
  76638. namespace zlibNamespace
  76639. {
  76640. #if JUCE_INCLUDE_ZLIB_CODE
  76641. extern "C"
  76642. {
  76643. #undef OS_CODE
  76644. #undef fdopen
  76645. #define ZLIB_INTERNAL
  76646. #define NO_DUMMY_DECL
  76647. /*** Start of inlined file: adler32.c ***/
  76648. /* @(#) $Id: adler32.c,v 1.1 2007/06/07 17:54:37 jules_rms Exp $ */
  76649. #define ZLIB_INTERNAL
  76650. #define BASE 65521UL /* largest prime smaller than 65536 */
  76651. #define NMAX 5552
  76652. /* NMAX is the largest n such that 255n(n+1)/2 + (n+1)(BASE-1) <= 2^32-1 */
  76653. #define DO1(buf,i) {adler += (buf)[i]; sum2 += adler;}
  76654. #define DO2(buf,i) DO1(buf,i); DO1(buf,i+1);
  76655. #define DO4(buf,i) DO2(buf,i); DO2(buf,i+2);
  76656. #define DO8(buf,i) DO4(buf,i); DO4(buf,i+4);
  76657. #define DO16(buf) DO8(buf,0); DO8(buf,8);
  76658. /* use NO_DIVIDE if your processor does not do division in hardware */
  76659. #ifdef NO_DIVIDE
  76660. # define MOD(a) \
  76661. do { \
  76662. if (a >= (BASE << 16)) a -= (BASE << 16); \
  76663. if (a >= (BASE << 15)) a -= (BASE << 15); \
  76664. if (a >= (BASE << 14)) a -= (BASE << 14); \
  76665. if (a >= (BASE << 13)) a -= (BASE << 13); \
  76666. if (a >= (BASE << 12)) a -= (BASE << 12); \
  76667. if (a >= (BASE << 11)) a -= (BASE << 11); \
  76668. if (a >= (BASE << 10)) a -= (BASE << 10); \
  76669. if (a >= (BASE << 9)) a -= (BASE << 9); \
  76670. if (a >= (BASE << 8)) a -= (BASE << 8); \
  76671. if (a >= (BASE << 7)) a -= (BASE << 7); \
  76672. if (a >= (BASE << 6)) a -= (BASE << 6); \
  76673. if (a >= (BASE << 5)) a -= (BASE << 5); \
  76674. if (a >= (BASE << 4)) a -= (BASE << 4); \
  76675. if (a >= (BASE << 3)) a -= (BASE << 3); \
  76676. if (a >= (BASE << 2)) a -= (BASE << 2); \
  76677. if (a >= (BASE << 1)) a -= (BASE << 1); \
  76678. if (a >= BASE) a -= BASE; \
  76679. } while (0)
  76680. # define MOD4(a) \
  76681. do { \
  76682. if (a >= (BASE << 4)) a -= (BASE << 4); \
  76683. if (a >= (BASE << 3)) a -= (BASE << 3); \
  76684. if (a >= (BASE << 2)) a -= (BASE << 2); \
  76685. if (a >= (BASE << 1)) a -= (BASE << 1); \
  76686. if (a >= BASE) a -= BASE; \
  76687. } while (0)
  76688. #else
  76689. # define MOD(a) a %= BASE
  76690. # define MOD4(a) a %= BASE
  76691. #endif
  76692. /* ========================================================================= */
  76693. uLong ZEXPORT adler32(uLong adler, const Bytef *buf, uInt len)
  76694. {
  76695. unsigned long sum2;
  76696. unsigned n;
  76697. /* split Adler-32 into component sums */
  76698. sum2 = (adler >> 16) & 0xffff;
  76699. adler &= 0xffff;
  76700. /* in case user likes doing a byte at a time, keep it fast */
  76701. if (len == 1) {
  76702. adler += buf[0];
  76703. if (adler >= BASE)
  76704. adler -= BASE;
  76705. sum2 += adler;
  76706. if (sum2 >= BASE)
  76707. sum2 -= BASE;
  76708. return adler | (sum2 << 16);
  76709. }
  76710. /* initial Adler-32 value (deferred check for len == 1 speed) */
  76711. if (buf == Z_NULL)
  76712. return 1L;
  76713. /* in case short lengths are provided, keep it somewhat fast */
  76714. if (len < 16) {
  76715. while (len--) {
  76716. adler += *buf++;
  76717. sum2 += adler;
  76718. }
  76719. if (adler >= BASE)
  76720. adler -= BASE;
  76721. MOD4(sum2); /* only added so many BASE's */
  76722. return adler | (sum2 << 16);
  76723. }
  76724. /* do length NMAX blocks -- requires just one modulo operation */
  76725. while (len >= NMAX) {
  76726. len -= NMAX;
  76727. n = NMAX / 16; /* NMAX is divisible by 16 */
  76728. do {
  76729. DO16(buf); /* 16 sums unrolled */
  76730. buf += 16;
  76731. } while (--n);
  76732. MOD(adler);
  76733. MOD(sum2);
  76734. }
  76735. /* do remaining bytes (less than NMAX, still just one modulo) */
  76736. if (len) { /* avoid modulos if none remaining */
  76737. while (len >= 16) {
  76738. len -= 16;
  76739. DO16(buf);
  76740. buf += 16;
  76741. }
  76742. while (len--) {
  76743. adler += *buf++;
  76744. sum2 += adler;
  76745. }
  76746. MOD(adler);
  76747. MOD(sum2);
  76748. }
  76749. /* return recombined sums */
  76750. return adler | (sum2 << 16);
  76751. }
  76752. /* ========================================================================= */
  76753. uLong ZEXPORT adler32_combine(uLong adler1, uLong adler2, z_off_t len2)
  76754. {
  76755. unsigned long sum1;
  76756. unsigned long sum2;
  76757. unsigned rem;
  76758. /* the derivation of this formula is left as an exercise for the reader */
  76759. rem = (unsigned)(len2 % BASE);
  76760. sum1 = adler1 & 0xffff;
  76761. sum2 = rem * sum1;
  76762. MOD(sum2);
  76763. sum1 += (adler2 & 0xffff) + BASE - 1;
  76764. sum2 += ((adler1 >> 16) & 0xffff) + ((adler2 >> 16) & 0xffff) + BASE - rem;
  76765. if (sum1 > BASE) sum1 -= BASE;
  76766. if (sum1 > BASE) sum1 -= BASE;
  76767. if (sum2 > (BASE << 1)) sum2 -= (BASE << 1);
  76768. if (sum2 > BASE) sum2 -= BASE;
  76769. return sum1 | (sum2 << 16);
  76770. }
  76771. /*** End of inlined file: adler32.c ***/
  76772. /*** Start of inlined file: compress.c ***/
  76773. /* @(#) $Id: compress.c,v 1.1 2007/06/07 17:54:37 jules_rms Exp $ */
  76774. #define ZLIB_INTERNAL
  76775. /* ===========================================================================
  76776. Compresses the source buffer into the destination buffer. The level
  76777. parameter has the same meaning as in deflateInit. sourceLen is the byte
  76778. length of the source buffer. Upon entry, destLen is the total size of the
  76779. destination buffer, which must be at least 0.1% larger than sourceLen plus
  76780. 12 bytes. Upon exit, destLen is the actual size of the compressed buffer.
  76781. compress2 returns Z_OK if success, Z_MEM_ERROR if there was not enough
  76782. memory, Z_BUF_ERROR if there was not enough room in the output buffer,
  76783. Z_STREAM_ERROR if the level parameter is invalid.
  76784. */
  76785. int ZEXPORT compress2 (Bytef *dest, uLongf *destLen, const Bytef *source,
  76786. uLong sourceLen, int level)
  76787. {
  76788. z_stream stream;
  76789. int err;
  76790. stream.next_in = (Bytef*)source;
  76791. stream.avail_in = (uInt)sourceLen;
  76792. #ifdef MAXSEG_64K
  76793. /* Check for source > 64K on 16-bit machine: */
  76794. if ((uLong)stream.avail_in != sourceLen) return Z_BUF_ERROR;
  76795. #endif
  76796. stream.next_out = dest;
  76797. stream.avail_out = (uInt)*destLen;
  76798. if ((uLong)stream.avail_out != *destLen) return Z_BUF_ERROR;
  76799. stream.zalloc = (alloc_func)0;
  76800. stream.zfree = (free_func)0;
  76801. stream.opaque = (voidpf)0;
  76802. err = deflateInit(&stream, level);
  76803. if (err != Z_OK) return err;
  76804. err = deflate(&stream, Z_FINISH);
  76805. if (err != Z_STREAM_END) {
  76806. deflateEnd(&stream);
  76807. return err == Z_OK ? Z_BUF_ERROR : err;
  76808. }
  76809. *destLen = stream.total_out;
  76810. err = deflateEnd(&stream);
  76811. return err;
  76812. }
  76813. /* ===========================================================================
  76814. */
  76815. int ZEXPORT compress (Bytef *dest, uLongf *destLen, const Bytef *source, uLong sourceLen)
  76816. {
  76817. return compress2(dest, destLen, source, sourceLen, Z_DEFAULT_COMPRESSION);
  76818. }
  76819. /* ===========================================================================
  76820. If the default memLevel or windowBits for deflateInit() is changed, then
  76821. this function needs to be updated.
  76822. */
  76823. uLong ZEXPORT compressBound (uLong sourceLen)
  76824. {
  76825. return sourceLen + (sourceLen >> 12) + (sourceLen >> 14) + 11;
  76826. }
  76827. /*** End of inlined file: compress.c ***/
  76828. #undef DO1
  76829. #undef DO8
  76830. /*** Start of inlined file: crc32.c ***/
  76831. /* @(#) $Id: crc32.c,v 1.1 2007/06/07 17:54:37 jules_rms Exp $ */
  76832. /*
  76833. Note on the use of DYNAMIC_CRC_TABLE: there is no mutex or semaphore
  76834. protection on the static variables used to control the first-use generation
  76835. of the crc tables. Therefore, if you #define DYNAMIC_CRC_TABLE, you should
  76836. first call get_crc_table() to initialize the tables before allowing more than
  76837. one thread to use crc32().
  76838. */
  76839. #ifdef MAKECRCH
  76840. # include <stdio.h>
  76841. # ifndef DYNAMIC_CRC_TABLE
  76842. # define DYNAMIC_CRC_TABLE
  76843. # endif /* !DYNAMIC_CRC_TABLE */
  76844. #endif /* MAKECRCH */
  76845. /*** Start of inlined file: zutil.h ***/
  76846. /* WARNING: this file should *not* be used by applications. It is
  76847. part of the implementation of the compression library and is
  76848. subject to change. Applications should only use zlib.h.
  76849. */
  76850. /* @(#) $Id: zutil.h,v 1.1 2007/06/07 17:54:37 jules_rms Exp $ */
  76851. #ifndef ZUTIL_H
  76852. #define ZUTIL_H
  76853. #define ZLIB_INTERNAL
  76854. #ifdef STDC
  76855. # ifndef _WIN32_WCE
  76856. # include <stddef.h>
  76857. # endif
  76858. # include <string.h>
  76859. # include <stdlib.h>
  76860. #endif
  76861. #ifdef NO_ERRNO_H
  76862. # ifdef _WIN32_WCE
  76863. /* The Microsoft C Run-Time Library for Windows CE doesn't have
  76864. * errno. We define it as a global variable to simplify porting.
  76865. * Its value is always 0 and should not be used. We rename it to
  76866. * avoid conflict with other libraries that use the same workaround.
  76867. */
  76868. # define errno z_errno
  76869. # endif
  76870. extern int errno;
  76871. #else
  76872. # ifndef _WIN32_WCE
  76873. # include <errno.h>
  76874. # endif
  76875. #endif
  76876. #ifndef local
  76877. # define local static
  76878. #endif
  76879. /* compile with -Dlocal if your debugger can't find static symbols */
  76880. typedef unsigned char uch;
  76881. typedef uch FAR uchf;
  76882. typedef unsigned short ush;
  76883. typedef ush FAR ushf;
  76884. typedef unsigned long ulg;
  76885. extern const char * const z_errmsg[10]; /* indexed by 2-zlib_error */
  76886. /* (size given to avoid silly warnings with Visual C++) */
  76887. #define ERR_MSG(err) z_errmsg[Z_NEED_DICT-(err)]
  76888. #define ERR_RETURN(strm,err) \
  76889. return (strm->msg = (char*)ERR_MSG(err), (err))
  76890. /* To be used only when the state is known to be valid */
  76891. /* common constants */
  76892. #ifndef DEF_WBITS
  76893. # define DEF_WBITS MAX_WBITS
  76894. #endif
  76895. /* default windowBits for decompression. MAX_WBITS is for compression only */
  76896. #if MAX_MEM_LEVEL >= 8
  76897. # define DEF_MEM_LEVEL 8
  76898. #else
  76899. # define DEF_MEM_LEVEL MAX_MEM_LEVEL
  76900. #endif
  76901. /* default memLevel */
  76902. #define STORED_BLOCK 0
  76903. #define STATIC_TREES 1
  76904. #define DYN_TREES 2
  76905. /* The three kinds of block type */
  76906. #define MIN_MATCH 3
  76907. #define MAX_MATCH 258
  76908. /* The minimum and maximum match lengths */
  76909. #define PRESET_DICT 0x20 /* preset dictionary flag in zlib header */
  76910. /* target dependencies */
  76911. #if defined(MSDOS) || (defined(WINDOWS) && !defined(WIN32))
  76912. # define OS_CODE 0x00
  76913. # if defined(__TURBOC__) || defined(__BORLANDC__)
  76914. # if(__STDC__ == 1) && (defined(__LARGE__) || defined(__COMPACT__))
  76915. /* Allow compilation with ANSI keywords only enabled */
  76916. void _Cdecl farfree( void *block );
  76917. void *_Cdecl farmalloc( unsigned long nbytes );
  76918. # else
  76919. # include <alloc.h>
  76920. # endif
  76921. # else /* MSC or DJGPP */
  76922. # include <malloc.h>
  76923. # endif
  76924. #endif
  76925. #ifdef AMIGA
  76926. # define OS_CODE 0x01
  76927. #endif
  76928. #if defined(VAXC) || defined(VMS)
  76929. # define OS_CODE 0x02
  76930. # define F_OPEN(name, mode) \
  76931. fopen((name), (mode), "mbc=60", "ctx=stm", "rfm=fix", "mrs=512")
  76932. #endif
  76933. #if defined(ATARI) || defined(atarist)
  76934. # define OS_CODE 0x05
  76935. #endif
  76936. #ifdef OS2
  76937. # define OS_CODE 0x06
  76938. # ifdef M_I86
  76939. #include <malloc.h>
  76940. # endif
  76941. #endif
  76942. #if defined(MACOS) || TARGET_OS_MAC
  76943. # define OS_CODE 0x07
  76944. # if defined(__MWERKS__) && __dest_os != __be_os && __dest_os != __win32_os
  76945. # include <unix.h> /* for fdopen */
  76946. # else
  76947. # ifndef fdopen
  76948. # define fdopen(fd,mode) NULL /* No fdopen() */
  76949. # endif
  76950. # endif
  76951. #endif
  76952. #ifdef TOPS20
  76953. # define OS_CODE 0x0a
  76954. #endif
  76955. #ifdef WIN32
  76956. # ifndef __CYGWIN__ /* Cygwin is Unix, not Win32 */
  76957. # define OS_CODE 0x0b
  76958. # endif
  76959. #endif
  76960. #ifdef __50SERIES /* Prime/PRIMOS */
  76961. # define OS_CODE 0x0f
  76962. #endif
  76963. #if defined(_BEOS_) || defined(RISCOS)
  76964. # define fdopen(fd,mode) NULL /* No fdopen() */
  76965. #endif
  76966. #if (defined(_MSC_VER) && (_MSC_VER > 600))
  76967. # if defined(_WIN32_WCE)
  76968. # define fdopen(fd,mode) NULL /* No fdopen() */
  76969. # ifndef _PTRDIFF_T_DEFINED
  76970. typedef int ptrdiff_t;
  76971. # define _PTRDIFF_T_DEFINED
  76972. # endif
  76973. # else
  76974. # define fdopen(fd,type) _fdopen(fd,type)
  76975. # endif
  76976. #endif
  76977. /* common defaults */
  76978. #ifndef OS_CODE
  76979. # define OS_CODE 0x03 /* assume Unix */
  76980. #endif
  76981. #ifndef F_OPEN
  76982. # define F_OPEN(name, mode) fopen((name), (mode))
  76983. #endif
  76984. /* functions */
  76985. #if defined(STDC99) || (defined(__TURBOC__) && __TURBOC__ >= 0x550)
  76986. # ifndef HAVE_VSNPRINTF
  76987. # define HAVE_VSNPRINTF
  76988. # endif
  76989. #endif
  76990. #if defined(__CYGWIN__)
  76991. # ifndef HAVE_VSNPRINTF
  76992. # define HAVE_VSNPRINTF
  76993. # endif
  76994. #endif
  76995. #ifndef HAVE_VSNPRINTF
  76996. # ifdef MSDOS
  76997. /* vsnprintf may exist on some MS-DOS compilers (DJGPP?),
  76998. but for now we just assume it doesn't. */
  76999. # define NO_vsnprintf
  77000. # endif
  77001. # ifdef __TURBOC__
  77002. # define NO_vsnprintf
  77003. # endif
  77004. # ifdef WIN32
  77005. /* In Win32, vsnprintf is available as the "non-ANSI" _vsnprintf. */
  77006. # if !defined(vsnprintf) && !defined(NO_vsnprintf)
  77007. # define vsnprintf _vsnprintf
  77008. # endif
  77009. # endif
  77010. # ifdef __SASC
  77011. # define NO_vsnprintf
  77012. # endif
  77013. #endif
  77014. #ifdef VMS
  77015. # define NO_vsnprintf
  77016. #endif
  77017. #if defined(pyr)
  77018. # define NO_MEMCPY
  77019. #endif
  77020. #if defined(SMALL_MEDIUM) && !defined(_MSC_VER) && !defined(__SC__)
  77021. /* Use our own functions for small and medium model with MSC <= 5.0.
  77022. * You may have to use the same strategy for Borland C (untested).
  77023. * The __SC__ check is for Symantec.
  77024. */
  77025. # define NO_MEMCPY
  77026. #endif
  77027. #if defined(STDC) && !defined(HAVE_MEMCPY) && !defined(NO_MEMCPY)
  77028. # define HAVE_MEMCPY
  77029. #endif
  77030. #ifdef HAVE_MEMCPY
  77031. # ifdef SMALL_MEDIUM /* MSDOS small or medium model */
  77032. # define zmemcpy _fmemcpy
  77033. # define zmemcmp _fmemcmp
  77034. # define zmemzero(dest, len) _fmemset(dest, 0, len)
  77035. # else
  77036. # define zmemcpy memcpy
  77037. # define zmemcmp memcmp
  77038. # define zmemzero(dest, len) memset(dest, 0, len)
  77039. # endif
  77040. #else
  77041. extern void zmemcpy OF((Bytef* dest, const Bytef* source, uInt len));
  77042. extern int zmemcmp OF((const Bytef* s1, const Bytef* s2, uInt len));
  77043. extern void zmemzero OF((Bytef* dest, uInt len));
  77044. #endif
  77045. /* Diagnostic functions */
  77046. #ifdef DEBUG
  77047. # include <stdio.h>
  77048. extern int z_verbose;
  77049. extern void z_error OF((const char *m));
  77050. # define Assert(cond,msg) {if(!(cond)) z_error(msg);}
  77051. # define Trace(x) {if (z_verbose>=0) fprintf x ;}
  77052. # define Tracev(x) {if (z_verbose>0) fprintf x ;}
  77053. # define Tracevv(x) {if (z_verbose>1) fprintf x ;}
  77054. # define Tracec(c,x) {if (z_verbose>0 && (c)) fprintf x ;}
  77055. # define Tracecv(c,x) {if (z_verbose>1 && (c)) fprintf x ;}
  77056. #else
  77057. # define Assert(cond,msg)
  77058. # define Trace(x)
  77059. # define Tracev(x)
  77060. # define Tracevv(x)
  77061. # define Tracec(c,x)
  77062. # define Tracecv(c,x)
  77063. #endif
  77064. voidpf zcalloc OF((voidpf opaque, unsigned items, unsigned size));
  77065. void zcfree OF((voidpf opaque, voidpf ptr));
  77066. #define ZALLOC(strm, items, size) \
  77067. (*((strm)->zalloc))((strm)->opaque, (items), (size))
  77068. #define ZFREE(strm, addr) (*((strm)->zfree))((strm)->opaque, (voidpf)(addr))
  77069. #define TRY_FREE(s, p) {if (p) ZFREE(s, p);}
  77070. #endif /* ZUTIL_H */
  77071. /*** End of inlined file: zutil.h ***/
  77072. /* for STDC and FAR definitions */
  77073. #define local static
  77074. /* Find a four-byte integer type for crc32_little() and crc32_big(). */
  77075. #ifndef NOBYFOUR
  77076. # ifdef STDC /* need ANSI C limits.h to determine sizes */
  77077. # include <limits.h>
  77078. # define BYFOUR
  77079. # if (UINT_MAX == 0xffffffffUL)
  77080. typedef unsigned int u4;
  77081. # else
  77082. # if (ULONG_MAX == 0xffffffffUL)
  77083. typedef unsigned long u4;
  77084. # else
  77085. # if (USHRT_MAX == 0xffffffffUL)
  77086. typedef unsigned short u4;
  77087. # else
  77088. # undef BYFOUR /* can't find a four-byte integer type! */
  77089. # endif
  77090. # endif
  77091. # endif
  77092. # endif /* STDC */
  77093. #endif /* !NOBYFOUR */
  77094. /* Definitions for doing the crc four data bytes at a time. */
  77095. #ifdef BYFOUR
  77096. # define REV(w) (((w)>>24)+(((w)>>8)&0xff00)+ \
  77097. (((w)&0xff00)<<8)+(((w)&0xff)<<24))
  77098. local unsigned long crc32_little OF((unsigned long,
  77099. const unsigned char FAR *, unsigned));
  77100. local unsigned long crc32_big OF((unsigned long,
  77101. const unsigned char FAR *, unsigned));
  77102. # define TBLS 8
  77103. #else
  77104. # define TBLS 1
  77105. #endif /* BYFOUR */
  77106. /* Local functions for crc concatenation */
  77107. local unsigned long gf2_matrix_times OF((unsigned long *mat,
  77108. unsigned long vec));
  77109. local void gf2_matrix_square OF((unsigned long *square, unsigned long *mat));
  77110. #ifdef DYNAMIC_CRC_TABLE
  77111. local volatile int crc_table_empty = 1;
  77112. local unsigned long FAR crc_table[TBLS][256];
  77113. local void make_crc_table OF((void));
  77114. #ifdef MAKECRCH
  77115. local void write_table OF((FILE *, const unsigned long FAR *));
  77116. #endif /* MAKECRCH */
  77117. /*
  77118. Generate tables for a byte-wise 32-bit CRC calculation on the polynomial:
  77119. 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.
  77120. Polynomials over GF(2) are represented in binary, one bit per coefficient,
  77121. with the lowest powers in the most significant bit. Then adding polynomials
  77122. is just exclusive-or, and multiplying a polynomial by x is a right shift by
  77123. one. If we call the above polynomial p, and represent a byte as the
  77124. polynomial q, also with the lowest power in the most significant bit (so the
  77125. byte 0xb1 is the polynomial x^7+x^3+x+1), then the CRC is (q*x^32) mod p,
  77126. where a mod b means the remainder after dividing a by b.
  77127. This calculation is done using the shift-register method of multiplying and
  77128. taking the remainder. The register is initialized to zero, and for each
  77129. incoming bit, x^32 is added mod p to the register if the bit is a one (where
  77130. x^32 mod p is p+x^32 = x^26+...+1), and the register is multiplied mod p by
  77131. x (which is shifting right by one and adding x^32 mod p if the bit shifted
  77132. out is a one). We start with the highest power (least significant bit) of
  77133. q and repeat for all eight bits of q.
  77134. The first table is simply the CRC of all possible eight bit values. This is
  77135. all the information needed to generate CRCs on data a byte at a time for all
  77136. combinations of CRC register values and incoming bytes. The remaining tables
  77137. allow for word-at-a-time CRC calculation for both big-endian and little-
  77138. endian machines, where a word is four bytes.
  77139. */
  77140. local void make_crc_table()
  77141. {
  77142. unsigned long c;
  77143. int n, k;
  77144. unsigned long poly; /* polynomial exclusive-or pattern */
  77145. /* terms of polynomial defining this crc (except x^32): */
  77146. static volatile int first = 1; /* flag to limit concurrent making */
  77147. static const unsigned char p[] = {0,1,2,4,5,7,8,10,11,12,16,22,23,26};
  77148. /* See if another task is already doing this (not thread-safe, but better
  77149. than nothing -- significantly reduces duration of vulnerability in
  77150. case the advice about DYNAMIC_CRC_TABLE is ignored) */
  77151. if (first) {
  77152. first = 0;
  77153. /* make exclusive-or pattern from polynomial (0xedb88320UL) */
  77154. poly = 0UL;
  77155. for (n = 0; n < sizeof(p)/sizeof(unsigned char); n++)
  77156. poly |= 1UL << (31 - p[n]);
  77157. /* generate a crc for every 8-bit value */
  77158. for (n = 0; n < 256; n++) {
  77159. c = (unsigned long)n;
  77160. for (k = 0; k < 8; k++)
  77161. c = c & 1 ? poly ^ (c >> 1) : c >> 1;
  77162. crc_table[0][n] = c;
  77163. }
  77164. #ifdef BYFOUR
  77165. /* generate crc for each value followed by one, two, and three zeros,
  77166. and then the byte reversal of those as well as the first table */
  77167. for (n = 0; n < 256; n++) {
  77168. c = crc_table[0][n];
  77169. crc_table[4][n] = REV(c);
  77170. for (k = 1; k < 4; k++) {
  77171. c = crc_table[0][c & 0xff] ^ (c >> 8);
  77172. crc_table[k][n] = c;
  77173. crc_table[k + 4][n] = REV(c);
  77174. }
  77175. }
  77176. #endif /* BYFOUR */
  77177. crc_table_empty = 0;
  77178. }
  77179. else { /* not first */
  77180. /* wait for the other guy to finish (not efficient, but rare) */
  77181. while (crc_table_empty)
  77182. ;
  77183. }
  77184. #ifdef MAKECRCH
  77185. /* write out CRC tables to crc32.h */
  77186. {
  77187. FILE *out;
  77188. out = fopen("crc32.h", "w");
  77189. if (out == NULL) return;
  77190. fprintf(out, "/* crc32.h -- tables for rapid CRC calculation\n");
  77191. fprintf(out, " * Generated automatically by crc32.c\n */\n\n");
  77192. fprintf(out, "local const unsigned long FAR ");
  77193. fprintf(out, "crc_table[TBLS][256] =\n{\n {\n");
  77194. write_table(out, crc_table[0]);
  77195. # ifdef BYFOUR
  77196. fprintf(out, "#ifdef BYFOUR\n");
  77197. for (k = 1; k < 8; k++) {
  77198. fprintf(out, " },\n {\n");
  77199. write_table(out, crc_table[k]);
  77200. }
  77201. fprintf(out, "#endif\n");
  77202. # endif /* BYFOUR */
  77203. fprintf(out, " }\n};\n");
  77204. fclose(out);
  77205. }
  77206. #endif /* MAKECRCH */
  77207. }
  77208. #ifdef MAKECRCH
  77209. local void write_table(out, table)
  77210. FILE *out;
  77211. const unsigned long FAR *table;
  77212. {
  77213. int n;
  77214. for (n = 0; n < 256; n++)
  77215. fprintf(out, "%s0x%08lxUL%s", n % 5 ? "" : " ", table[n],
  77216. n == 255 ? "\n" : (n % 5 == 4 ? ",\n" : ", "));
  77217. }
  77218. #endif /* MAKECRCH */
  77219. #else /* !DYNAMIC_CRC_TABLE */
  77220. /* ========================================================================
  77221. * Tables of CRC-32s of all single-byte values, made by make_crc_table().
  77222. */
  77223. /*** Start of inlined file: crc32.h ***/
  77224. local const unsigned long FAR crc_table[TBLS][256] =
  77225. {
  77226. {
  77227. 0x00000000UL, 0x77073096UL, 0xee0e612cUL, 0x990951baUL, 0x076dc419UL,
  77228. 0x706af48fUL, 0xe963a535UL, 0x9e6495a3UL, 0x0edb8832UL, 0x79dcb8a4UL,
  77229. 0xe0d5e91eUL, 0x97d2d988UL, 0x09b64c2bUL, 0x7eb17cbdUL, 0xe7b82d07UL,
  77230. 0x90bf1d91UL, 0x1db71064UL, 0x6ab020f2UL, 0xf3b97148UL, 0x84be41deUL,
  77231. 0x1adad47dUL, 0x6ddde4ebUL, 0xf4d4b551UL, 0x83d385c7UL, 0x136c9856UL,
  77232. 0x646ba8c0UL, 0xfd62f97aUL, 0x8a65c9ecUL, 0x14015c4fUL, 0x63066cd9UL,
  77233. 0xfa0f3d63UL, 0x8d080df5UL, 0x3b6e20c8UL, 0x4c69105eUL, 0xd56041e4UL,
  77234. 0xa2677172UL, 0x3c03e4d1UL, 0x4b04d447UL, 0xd20d85fdUL, 0xa50ab56bUL,
  77235. 0x35b5a8faUL, 0x42b2986cUL, 0xdbbbc9d6UL, 0xacbcf940UL, 0x32d86ce3UL,
  77236. 0x45df5c75UL, 0xdcd60dcfUL, 0xabd13d59UL, 0x26d930acUL, 0x51de003aUL,
  77237. 0xc8d75180UL, 0xbfd06116UL, 0x21b4f4b5UL, 0x56b3c423UL, 0xcfba9599UL,
  77238. 0xb8bda50fUL, 0x2802b89eUL, 0x5f058808UL, 0xc60cd9b2UL, 0xb10be924UL,
  77239. 0x2f6f7c87UL, 0x58684c11UL, 0xc1611dabUL, 0xb6662d3dUL, 0x76dc4190UL,
  77240. 0x01db7106UL, 0x98d220bcUL, 0xefd5102aUL, 0x71b18589UL, 0x06b6b51fUL,
  77241. 0x9fbfe4a5UL, 0xe8b8d433UL, 0x7807c9a2UL, 0x0f00f934UL, 0x9609a88eUL,
  77242. 0xe10e9818UL, 0x7f6a0dbbUL, 0x086d3d2dUL, 0x91646c97UL, 0xe6635c01UL,
  77243. 0x6b6b51f4UL, 0x1c6c6162UL, 0x856530d8UL, 0xf262004eUL, 0x6c0695edUL,
  77244. 0x1b01a57bUL, 0x8208f4c1UL, 0xf50fc457UL, 0x65b0d9c6UL, 0x12b7e950UL,
  77245. 0x8bbeb8eaUL, 0xfcb9887cUL, 0x62dd1ddfUL, 0x15da2d49UL, 0x8cd37cf3UL,
  77246. 0xfbd44c65UL, 0x4db26158UL, 0x3ab551ceUL, 0xa3bc0074UL, 0xd4bb30e2UL,
  77247. 0x4adfa541UL, 0x3dd895d7UL, 0xa4d1c46dUL, 0xd3d6f4fbUL, 0x4369e96aUL,
  77248. 0x346ed9fcUL, 0xad678846UL, 0xda60b8d0UL, 0x44042d73UL, 0x33031de5UL,
  77249. 0xaa0a4c5fUL, 0xdd0d7cc9UL, 0x5005713cUL, 0x270241aaUL, 0xbe0b1010UL,
  77250. 0xc90c2086UL, 0x5768b525UL, 0x206f85b3UL, 0xb966d409UL, 0xce61e49fUL,
  77251. 0x5edef90eUL, 0x29d9c998UL, 0xb0d09822UL, 0xc7d7a8b4UL, 0x59b33d17UL,
  77252. 0x2eb40d81UL, 0xb7bd5c3bUL, 0xc0ba6cadUL, 0xedb88320UL, 0x9abfb3b6UL,
  77253. 0x03b6e20cUL, 0x74b1d29aUL, 0xead54739UL, 0x9dd277afUL, 0x04db2615UL,
  77254. 0x73dc1683UL, 0xe3630b12UL, 0x94643b84UL, 0x0d6d6a3eUL, 0x7a6a5aa8UL,
  77255. 0xe40ecf0bUL, 0x9309ff9dUL, 0x0a00ae27UL, 0x7d079eb1UL, 0xf00f9344UL,
  77256. 0x8708a3d2UL, 0x1e01f268UL, 0x6906c2feUL, 0xf762575dUL, 0x806567cbUL,
  77257. 0x196c3671UL, 0x6e6b06e7UL, 0xfed41b76UL, 0x89d32be0UL, 0x10da7a5aUL,
  77258. 0x67dd4accUL, 0xf9b9df6fUL, 0x8ebeeff9UL, 0x17b7be43UL, 0x60b08ed5UL,
  77259. 0xd6d6a3e8UL, 0xa1d1937eUL, 0x38d8c2c4UL, 0x4fdff252UL, 0xd1bb67f1UL,
  77260. 0xa6bc5767UL, 0x3fb506ddUL, 0x48b2364bUL, 0xd80d2bdaUL, 0xaf0a1b4cUL,
  77261. 0x36034af6UL, 0x41047a60UL, 0xdf60efc3UL, 0xa867df55UL, 0x316e8eefUL,
  77262. 0x4669be79UL, 0xcb61b38cUL, 0xbc66831aUL, 0x256fd2a0UL, 0x5268e236UL,
  77263. 0xcc0c7795UL, 0xbb0b4703UL, 0x220216b9UL, 0x5505262fUL, 0xc5ba3bbeUL,
  77264. 0xb2bd0b28UL, 0x2bb45a92UL, 0x5cb36a04UL, 0xc2d7ffa7UL, 0xb5d0cf31UL,
  77265. 0x2cd99e8bUL, 0x5bdeae1dUL, 0x9b64c2b0UL, 0xec63f226UL, 0x756aa39cUL,
  77266. 0x026d930aUL, 0x9c0906a9UL, 0xeb0e363fUL, 0x72076785UL, 0x05005713UL,
  77267. 0x95bf4a82UL, 0xe2b87a14UL, 0x7bb12baeUL, 0x0cb61b38UL, 0x92d28e9bUL,
  77268. 0xe5d5be0dUL, 0x7cdcefb7UL, 0x0bdbdf21UL, 0x86d3d2d4UL, 0xf1d4e242UL,
  77269. 0x68ddb3f8UL, 0x1fda836eUL, 0x81be16cdUL, 0xf6b9265bUL, 0x6fb077e1UL,
  77270. 0x18b74777UL, 0x88085ae6UL, 0xff0f6a70UL, 0x66063bcaUL, 0x11010b5cUL,
  77271. 0x8f659effUL, 0xf862ae69UL, 0x616bffd3UL, 0x166ccf45UL, 0xa00ae278UL,
  77272. 0xd70dd2eeUL, 0x4e048354UL, 0x3903b3c2UL, 0xa7672661UL, 0xd06016f7UL,
  77273. 0x4969474dUL, 0x3e6e77dbUL, 0xaed16a4aUL, 0xd9d65adcUL, 0x40df0b66UL,
  77274. 0x37d83bf0UL, 0xa9bcae53UL, 0xdebb9ec5UL, 0x47b2cf7fUL, 0x30b5ffe9UL,
  77275. 0xbdbdf21cUL, 0xcabac28aUL, 0x53b39330UL, 0x24b4a3a6UL, 0xbad03605UL,
  77276. 0xcdd70693UL, 0x54de5729UL, 0x23d967bfUL, 0xb3667a2eUL, 0xc4614ab8UL,
  77277. 0x5d681b02UL, 0x2a6f2b94UL, 0xb40bbe37UL, 0xc30c8ea1UL, 0x5a05df1bUL,
  77278. 0x2d02ef8dUL
  77279. #ifdef BYFOUR
  77280. },
  77281. {
  77282. 0x00000000UL, 0x191b3141UL, 0x32366282UL, 0x2b2d53c3UL, 0x646cc504UL,
  77283. 0x7d77f445UL, 0x565aa786UL, 0x4f4196c7UL, 0xc8d98a08UL, 0xd1c2bb49UL,
  77284. 0xfaefe88aUL, 0xe3f4d9cbUL, 0xacb54f0cUL, 0xb5ae7e4dUL, 0x9e832d8eUL,
  77285. 0x87981ccfUL, 0x4ac21251UL, 0x53d92310UL, 0x78f470d3UL, 0x61ef4192UL,
  77286. 0x2eaed755UL, 0x37b5e614UL, 0x1c98b5d7UL, 0x05838496UL, 0x821b9859UL,
  77287. 0x9b00a918UL, 0xb02dfadbUL, 0xa936cb9aUL, 0xe6775d5dUL, 0xff6c6c1cUL,
  77288. 0xd4413fdfUL, 0xcd5a0e9eUL, 0x958424a2UL, 0x8c9f15e3UL, 0xa7b24620UL,
  77289. 0xbea97761UL, 0xf1e8e1a6UL, 0xe8f3d0e7UL, 0xc3de8324UL, 0xdac5b265UL,
  77290. 0x5d5daeaaUL, 0x44469febUL, 0x6f6bcc28UL, 0x7670fd69UL, 0x39316baeUL,
  77291. 0x202a5aefUL, 0x0b07092cUL, 0x121c386dUL, 0xdf4636f3UL, 0xc65d07b2UL,
  77292. 0xed705471UL, 0xf46b6530UL, 0xbb2af3f7UL, 0xa231c2b6UL, 0x891c9175UL,
  77293. 0x9007a034UL, 0x179fbcfbUL, 0x0e848dbaUL, 0x25a9de79UL, 0x3cb2ef38UL,
  77294. 0x73f379ffUL, 0x6ae848beUL, 0x41c51b7dUL, 0x58de2a3cUL, 0xf0794f05UL,
  77295. 0xe9627e44UL, 0xc24f2d87UL, 0xdb541cc6UL, 0x94158a01UL, 0x8d0ebb40UL,
  77296. 0xa623e883UL, 0xbf38d9c2UL, 0x38a0c50dUL, 0x21bbf44cUL, 0x0a96a78fUL,
  77297. 0x138d96ceUL, 0x5ccc0009UL, 0x45d73148UL, 0x6efa628bUL, 0x77e153caUL,
  77298. 0xbabb5d54UL, 0xa3a06c15UL, 0x888d3fd6UL, 0x91960e97UL, 0xded79850UL,
  77299. 0xc7cca911UL, 0xece1fad2UL, 0xf5facb93UL, 0x7262d75cUL, 0x6b79e61dUL,
  77300. 0x4054b5deUL, 0x594f849fUL, 0x160e1258UL, 0x0f152319UL, 0x243870daUL,
  77301. 0x3d23419bUL, 0x65fd6ba7UL, 0x7ce65ae6UL, 0x57cb0925UL, 0x4ed03864UL,
  77302. 0x0191aea3UL, 0x188a9fe2UL, 0x33a7cc21UL, 0x2abcfd60UL, 0xad24e1afUL,
  77303. 0xb43fd0eeUL, 0x9f12832dUL, 0x8609b26cUL, 0xc94824abUL, 0xd05315eaUL,
  77304. 0xfb7e4629UL, 0xe2657768UL, 0x2f3f79f6UL, 0x362448b7UL, 0x1d091b74UL,
  77305. 0x04122a35UL, 0x4b53bcf2UL, 0x52488db3UL, 0x7965de70UL, 0x607eef31UL,
  77306. 0xe7e6f3feUL, 0xfefdc2bfUL, 0xd5d0917cUL, 0xcccba03dUL, 0x838a36faUL,
  77307. 0x9a9107bbUL, 0xb1bc5478UL, 0xa8a76539UL, 0x3b83984bUL, 0x2298a90aUL,
  77308. 0x09b5fac9UL, 0x10aecb88UL, 0x5fef5d4fUL, 0x46f46c0eUL, 0x6dd93fcdUL,
  77309. 0x74c20e8cUL, 0xf35a1243UL, 0xea412302UL, 0xc16c70c1UL, 0xd8774180UL,
  77310. 0x9736d747UL, 0x8e2de606UL, 0xa500b5c5UL, 0xbc1b8484UL, 0x71418a1aUL,
  77311. 0x685abb5bUL, 0x4377e898UL, 0x5a6cd9d9UL, 0x152d4f1eUL, 0x0c367e5fUL,
  77312. 0x271b2d9cUL, 0x3e001cddUL, 0xb9980012UL, 0xa0833153UL, 0x8bae6290UL,
  77313. 0x92b553d1UL, 0xddf4c516UL, 0xc4eff457UL, 0xefc2a794UL, 0xf6d996d5UL,
  77314. 0xae07bce9UL, 0xb71c8da8UL, 0x9c31de6bUL, 0x852aef2aUL, 0xca6b79edUL,
  77315. 0xd37048acUL, 0xf85d1b6fUL, 0xe1462a2eUL, 0x66de36e1UL, 0x7fc507a0UL,
  77316. 0x54e85463UL, 0x4df36522UL, 0x02b2f3e5UL, 0x1ba9c2a4UL, 0x30849167UL,
  77317. 0x299fa026UL, 0xe4c5aeb8UL, 0xfdde9ff9UL, 0xd6f3cc3aUL, 0xcfe8fd7bUL,
  77318. 0x80a96bbcUL, 0x99b25afdUL, 0xb29f093eUL, 0xab84387fUL, 0x2c1c24b0UL,
  77319. 0x350715f1UL, 0x1e2a4632UL, 0x07317773UL, 0x4870e1b4UL, 0x516bd0f5UL,
  77320. 0x7a468336UL, 0x635db277UL, 0xcbfad74eUL, 0xd2e1e60fUL, 0xf9ccb5ccUL,
  77321. 0xe0d7848dUL, 0xaf96124aUL, 0xb68d230bUL, 0x9da070c8UL, 0x84bb4189UL,
  77322. 0x03235d46UL, 0x1a386c07UL, 0x31153fc4UL, 0x280e0e85UL, 0x674f9842UL,
  77323. 0x7e54a903UL, 0x5579fac0UL, 0x4c62cb81UL, 0x8138c51fUL, 0x9823f45eUL,
  77324. 0xb30ea79dUL, 0xaa1596dcUL, 0xe554001bUL, 0xfc4f315aUL, 0xd7626299UL,
  77325. 0xce7953d8UL, 0x49e14f17UL, 0x50fa7e56UL, 0x7bd72d95UL, 0x62cc1cd4UL,
  77326. 0x2d8d8a13UL, 0x3496bb52UL, 0x1fbbe891UL, 0x06a0d9d0UL, 0x5e7ef3ecUL,
  77327. 0x4765c2adUL, 0x6c48916eUL, 0x7553a02fUL, 0x3a1236e8UL, 0x230907a9UL,
  77328. 0x0824546aUL, 0x113f652bUL, 0x96a779e4UL, 0x8fbc48a5UL, 0xa4911b66UL,
  77329. 0xbd8a2a27UL, 0xf2cbbce0UL, 0xebd08da1UL, 0xc0fdde62UL, 0xd9e6ef23UL,
  77330. 0x14bce1bdUL, 0x0da7d0fcUL, 0x268a833fUL, 0x3f91b27eUL, 0x70d024b9UL,
  77331. 0x69cb15f8UL, 0x42e6463bUL, 0x5bfd777aUL, 0xdc656bb5UL, 0xc57e5af4UL,
  77332. 0xee530937UL, 0xf7483876UL, 0xb809aeb1UL, 0xa1129ff0UL, 0x8a3fcc33UL,
  77333. 0x9324fd72UL
  77334. },
  77335. {
  77336. 0x00000000UL, 0x01c26a37UL, 0x0384d46eUL, 0x0246be59UL, 0x0709a8dcUL,
  77337. 0x06cbc2ebUL, 0x048d7cb2UL, 0x054f1685UL, 0x0e1351b8UL, 0x0fd13b8fUL,
  77338. 0x0d9785d6UL, 0x0c55efe1UL, 0x091af964UL, 0x08d89353UL, 0x0a9e2d0aUL,
  77339. 0x0b5c473dUL, 0x1c26a370UL, 0x1de4c947UL, 0x1fa2771eUL, 0x1e601d29UL,
  77340. 0x1b2f0bacUL, 0x1aed619bUL, 0x18abdfc2UL, 0x1969b5f5UL, 0x1235f2c8UL,
  77341. 0x13f798ffUL, 0x11b126a6UL, 0x10734c91UL, 0x153c5a14UL, 0x14fe3023UL,
  77342. 0x16b88e7aUL, 0x177ae44dUL, 0x384d46e0UL, 0x398f2cd7UL, 0x3bc9928eUL,
  77343. 0x3a0bf8b9UL, 0x3f44ee3cUL, 0x3e86840bUL, 0x3cc03a52UL, 0x3d025065UL,
  77344. 0x365e1758UL, 0x379c7d6fUL, 0x35dac336UL, 0x3418a901UL, 0x3157bf84UL,
  77345. 0x3095d5b3UL, 0x32d36beaUL, 0x331101ddUL, 0x246be590UL, 0x25a98fa7UL,
  77346. 0x27ef31feUL, 0x262d5bc9UL, 0x23624d4cUL, 0x22a0277bUL, 0x20e69922UL,
  77347. 0x2124f315UL, 0x2a78b428UL, 0x2bbade1fUL, 0x29fc6046UL, 0x283e0a71UL,
  77348. 0x2d711cf4UL, 0x2cb376c3UL, 0x2ef5c89aUL, 0x2f37a2adUL, 0x709a8dc0UL,
  77349. 0x7158e7f7UL, 0x731e59aeUL, 0x72dc3399UL, 0x7793251cUL, 0x76514f2bUL,
  77350. 0x7417f172UL, 0x75d59b45UL, 0x7e89dc78UL, 0x7f4bb64fUL, 0x7d0d0816UL,
  77351. 0x7ccf6221UL, 0x798074a4UL, 0x78421e93UL, 0x7a04a0caUL, 0x7bc6cafdUL,
  77352. 0x6cbc2eb0UL, 0x6d7e4487UL, 0x6f38fadeUL, 0x6efa90e9UL, 0x6bb5866cUL,
  77353. 0x6a77ec5bUL, 0x68315202UL, 0x69f33835UL, 0x62af7f08UL, 0x636d153fUL,
  77354. 0x612bab66UL, 0x60e9c151UL, 0x65a6d7d4UL, 0x6464bde3UL, 0x662203baUL,
  77355. 0x67e0698dUL, 0x48d7cb20UL, 0x4915a117UL, 0x4b531f4eUL, 0x4a917579UL,
  77356. 0x4fde63fcUL, 0x4e1c09cbUL, 0x4c5ab792UL, 0x4d98dda5UL, 0x46c49a98UL,
  77357. 0x4706f0afUL, 0x45404ef6UL, 0x448224c1UL, 0x41cd3244UL, 0x400f5873UL,
  77358. 0x4249e62aUL, 0x438b8c1dUL, 0x54f16850UL, 0x55330267UL, 0x5775bc3eUL,
  77359. 0x56b7d609UL, 0x53f8c08cUL, 0x523aaabbUL, 0x507c14e2UL, 0x51be7ed5UL,
  77360. 0x5ae239e8UL, 0x5b2053dfUL, 0x5966ed86UL, 0x58a487b1UL, 0x5deb9134UL,
  77361. 0x5c29fb03UL, 0x5e6f455aUL, 0x5fad2f6dUL, 0xe1351b80UL, 0xe0f771b7UL,
  77362. 0xe2b1cfeeUL, 0xe373a5d9UL, 0xe63cb35cUL, 0xe7fed96bUL, 0xe5b86732UL,
  77363. 0xe47a0d05UL, 0xef264a38UL, 0xeee4200fUL, 0xeca29e56UL, 0xed60f461UL,
  77364. 0xe82fe2e4UL, 0xe9ed88d3UL, 0xebab368aUL, 0xea695cbdUL, 0xfd13b8f0UL,
  77365. 0xfcd1d2c7UL, 0xfe976c9eUL, 0xff5506a9UL, 0xfa1a102cUL, 0xfbd87a1bUL,
  77366. 0xf99ec442UL, 0xf85cae75UL, 0xf300e948UL, 0xf2c2837fUL, 0xf0843d26UL,
  77367. 0xf1465711UL, 0xf4094194UL, 0xf5cb2ba3UL, 0xf78d95faUL, 0xf64fffcdUL,
  77368. 0xd9785d60UL, 0xd8ba3757UL, 0xdafc890eUL, 0xdb3ee339UL, 0xde71f5bcUL,
  77369. 0xdfb39f8bUL, 0xddf521d2UL, 0xdc374be5UL, 0xd76b0cd8UL, 0xd6a966efUL,
  77370. 0xd4efd8b6UL, 0xd52db281UL, 0xd062a404UL, 0xd1a0ce33UL, 0xd3e6706aUL,
  77371. 0xd2241a5dUL, 0xc55efe10UL, 0xc49c9427UL, 0xc6da2a7eUL, 0xc7184049UL,
  77372. 0xc25756ccUL, 0xc3953cfbUL, 0xc1d382a2UL, 0xc011e895UL, 0xcb4dafa8UL,
  77373. 0xca8fc59fUL, 0xc8c97bc6UL, 0xc90b11f1UL, 0xcc440774UL, 0xcd866d43UL,
  77374. 0xcfc0d31aUL, 0xce02b92dUL, 0x91af9640UL, 0x906dfc77UL, 0x922b422eUL,
  77375. 0x93e92819UL, 0x96a63e9cUL, 0x976454abUL, 0x9522eaf2UL, 0x94e080c5UL,
  77376. 0x9fbcc7f8UL, 0x9e7eadcfUL, 0x9c381396UL, 0x9dfa79a1UL, 0x98b56f24UL,
  77377. 0x99770513UL, 0x9b31bb4aUL, 0x9af3d17dUL, 0x8d893530UL, 0x8c4b5f07UL,
  77378. 0x8e0de15eUL, 0x8fcf8b69UL, 0x8a809decUL, 0x8b42f7dbUL, 0x89044982UL,
  77379. 0x88c623b5UL, 0x839a6488UL, 0x82580ebfUL, 0x801eb0e6UL, 0x81dcdad1UL,
  77380. 0x8493cc54UL, 0x8551a663UL, 0x8717183aUL, 0x86d5720dUL, 0xa9e2d0a0UL,
  77381. 0xa820ba97UL, 0xaa6604ceUL, 0xaba46ef9UL, 0xaeeb787cUL, 0xaf29124bUL,
  77382. 0xad6fac12UL, 0xacadc625UL, 0xa7f18118UL, 0xa633eb2fUL, 0xa4755576UL,
  77383. 0xa5b73f41UL, 0xa0f829c4UL, 0xa13a43f3UL, 0xa37cfdaaUL, 0xa2be979dUL,
  77384. 0xb5c473d0UL, 0xb40619e7UL, 0xb640a7beUL, 0xb782cd89UL, 0xb2cddb0cUL,
  77385. 0xb30fb13bUL, 0xb1490f62UL, 0xb08b6555UL, 0xbbd72268UL, 0xba15485fUL,
  77386. 0xb853f606UL, 0xb9919c31UL, 0xbcde8ab4UL, 0xbd1ce083UL, 0xbf5a5edaUL,
  77387. 0xbe9834edUL
  77388. },
  77389. {
  77390. 0x00000000UL, 0xb8bc6765UL, 0xaa09c88bUL, 0x12b5afeeUL, 0x8f629757UL,
  77391. 0x37def032UL, 0x256b5fdcUL, 0x9dd738b9UL, 0xc5b428efUL, 0x7d084f8aUL,
  77392. 0x6fbde064UL, 0xd7018701UL, 0x4ad6bfb8UL, 0xf26ad8ddUL, 0xe0df7733UL,
  77393. 0x58631056UL, 0x5019579fUL, 0xe8a530faUL, 0xfa109f14UL, 0x42acf871UL,
  77394. 0xdf7bc0c8UL, 0x67c7a7adUL, 0x75720843UL, 0xcdce6f26UL, 0x95ad7f70UL,
  77395. 0x2d111815UL, 0x3fa4b7fbUL, 0x8718d09eUL, 0x1acfe827UL, 0xa2738f42UL,
  77396. 0xb0c620acUL, 0x087a47c9UL, 0xa032af3eUL, 0x188ec85bUL, 0x0a3b67b5UL,
  77397. 0xb28700d0UL, 0x2f503869UL, 0x97ec5f0cUL, 0x8559f0e2UL, 0x3de59787UL,
  77398. 0x658687d1UL, 0xdd3ae0b4UL, 0xcf8f4f5aUL, 0x7733283fUL, 0xeae41086UL,
  77399. 0x525877e3UL, 0x40edd80dUL, 0xf851bf68UL, 0xf02bf8a1UL, 0x48979fc4UL,
  77400. 0x5a22302aUL, 0xe29e574fUL, 0x7f496ff6UL, 0xc7f50893UL, 0xd540a77dUL,
  77401. 0x6dfcc018UL, 0x359fd04eUL, 0x8d23b72bUL, 0x9f9618c5UL, 0x272a7fa0UL,
  77402. 0xbafd4719UL, 0x0241207cUL, 0x10f48f92UL, 0xa848e8f7UL, 0x9b14583dUL,
  77403. 0x23a83f58UL, 0x311d90b6UL, 0x89a1f7d3UL, 0x1476cf6aUL, 0xaccaa80fUL,
  77404. 0xbe7f07e1UL, 0x06c36084UL, 0x5ea070d2UL, 0xe61c17b7UL, 0xf4a9b859UL,
  77405. 0x4c15df3cUL, 0xd1c2e785UL, 0x697e80e0UL, 0x7bcb2f0eUL, 0xc377486bUL,
  77406. 0xcb0d0fa2UL, 0x73b168c7UL, 0x6104c729UL, 0xd9b8a04cUL, 0x446f98f5UL,
  77407. 0xfcd3ff90UL, 0xee66507eUL, 0x56da371bUL, 0x0eb9274dUL, 0xb6054028UL,
  77408. 0xa4b0efc6UL, 0x1c0c88a3UL, 0x81dbb01aUL, 0x3967d77fUL, 0x2bd27891UL,
  77409. 0x936e1ff4UL, 0x3b26f703UL, 0x839a9066UL, 0x912f3f88UL, 0x299358edUL,
  77410. 0xb4446054UL, 0x0cf80731UL, 0x1e4da8dfUL, 0xa6f1cfbaUL, 0xfe92dfecUL,
  77411. 0x462eb889UL, 0x549b1767UL, 0xec277002UL, 0x71f048bbUL, 0xc94c2fdeUL,
  77412. 0xdbf98030UL, 0x6345e755UL, 0x6b3fa09cUL, 0xd383c7f9UL, 0xc1366817UL,
  77413. 0x798a0f72UL, 0xe45d37cbUL, 0x5ce150aeUL, 0x4e54ff40UL, 0xf6e89825UL,
  77414. 0xae8b8873UL, 0x1637ef16UL, 0x048240f8UL, 0xbc3e279dUL, 0x21e91f24UL,
  77415. 0x99557841UL, 0x8be0d7afUL, 0x335cb0caUL, 0xed59b63bUL, 0x55e5d15eUL,
  77416. 0x47507eb0UL, 0xffec19d5UL, 0x623b216cUL, 0xda874609UL, 0xc832e9e7UL,
  77417. 0x708e8e82UL, 0x28ed9ed4UL, 0x9051f9b1UL, 0x82e4565fUL, 0x3a58313aUL,
  77418. 0xa78f0983UL, 0x1f336ee6UL, 0x0d86c108UL, 0xb53aa66dUL, 0xbd40e1a4UL,
  77419. 0x05fc86c1UL, 0x1749292fUL, 0xaff54e4aUL, 0x322276f3UL, 0x8a9e1196UL,
  77420. 0x982bbe78UL, 0x2097d91dUL, 0x78f4c94bUL, 0xc048ae2eUL, 0xd2fd01c0UL,
  77421. 0x6a4166a5UL, 0xf7965e1cUL, 0x4f2a3979UL, 0x5d9f9697UL, 0xe523f1f2UL,
  77422. 0x4d6b1905UL, 0xf5d77e60UL, 0xe762d18eUL, 0x5fdeb6ebUL, 0xc2098e52UL,
  77423. 0x7ab5e937UL, 0x680046d9UL, 0xd0bc21bcUL, 0x88df31eaUL, 0x3063568fUL,
  77424. 0x22d6f961UL, 0x9a6a9e04UL, 0x07bda6bdUL, 0xbf01c1d8UL, 0xadb46e36UL,
  77425. 0x15080953UL, 0x1d724e9aUL, 0xa5ce29ffUL, 0xb77b8611UL, 0x0fc7e174UL,
  77426. 0x9210d9cdUL, 0x2aacbea8UL, 0x38191146UL, 0x80a57623UL, 0xd8c66675UL,
  77427. 0x607a0110UL, 0x72cfaefeUL, 0xca73c99bUL, 0x57a4f122UL, 0xef189647UL,
  77428. 0xfdad39a9UL, 0x45115eccUL, 0x764dee06UL, 0xcef18963UL, 0xdc44268dUL,
  77429. 0x64f841e8UL, 0xf92f7951UL, 0x41931e34UL, 0x5326b1daUL, 0xeb9ad6bfUL,
  77430. 0xb3f9c6e9UL, 0x0b45a18cUL, 0x19f00e62UL, 0xa14c6907UL, 0x3c9b51beUL,
  77431. 0x842736dbUL, 0x96929935UL, 0x2e2efe50UL, 0x2654b999UL, 0x9ee8defcUL,
  77432. 0x8c5d7112UL, 0x34e11677UL, 0xa9362eceUL, 0x118a49abUL, 0x033fe645UL,
  77433. 0xbb838120UL, 0xe3e09176UL, 0x5b5cf613UL, 0x49e959fdUL, 0xf1553e98UL,
  77434. 0x6c820621UL, 0xd43e6144UL, 0xc68bceaaUL, 0x7e37a9cfUL, 0xd67f4138UL,
  77435. 0x6ec3265dUL, 0x7c7689b3UL, 0xc4caeed6UL, 0x591dd66fUL, 0xe1a1b10aUL,
  77436. 0xf3141ee4UL, 0x4ba87981UL, 0x13cb69d7UL, 0xab770eb2UL, 0xb9c2a15cUL,
  77437. 0x017ec639UL, 0x9ca9fe80UL, 0x241599e5UL, 0x36a0360bUL, 0x8e1c516eUL,
  77438. 0x866616a7UL, 0x3eda71c2UL, 0x2c6fde2cUL, 0x94d3b949UL, 0x090481f0UL,
  77439. 0xb1b8e695UL, 0xa30d497bUL, 0x1bb12e1eUL, 0x43d23e48UL, 0xfb6e592dUL,
  77440. 0xe9dbf6c3UL, 0x516791a6UL, 0xccb0a91fUL, 0x740cce7aUL, 0x66b96194UL,
  77441. 0xde0506f1UL
  77442. },
  77443. {
  77444. 0x00000000UL, 0x96300777UL, 0x2c610eeeUL, 0xba510999UL, 0x19c46d07UL,
  77445. 0x8ff46a70UL, 0x35a563e9UL, 0xa395649eUL, 0x3288db0eUL, 0xa4b8dc79UL,
  77446. 0x1ee9d5e0UL, 0x88d9d297UL, 0x2b4cb609UL, 0xbd7cb17eUL, 0x072db8e7UL,
  77447. 0x911dbf90UL, 0x6410b71dUL, 0xf220b06aUL, 0x4871b9f3UL, 0xde41be84UL,
  77448. 0x7dd4da1aUL, 0xebe4dd6dUL, 0x51b5d4f4UL, 0xc785d383UL, 0x56986c13UL,
  77449. 0xc0a86b64UL, 0x7af962fdUL, 0xecc9658aUL, 0x4f5c0114UL, 0xd96c0663UL,
  77450. 0x633d0ffaUL, 0xf50d088dUL, 0xc8206e3bUL, 0x5e10694cUL, 0xe44160d5UL,
  77451. 0x727167a2UL, 0xd1e4033cUL, 0x47d4044bUL, 0xfd850dd2UL, 0x6bb50aa5UL,
  77452. 0xfaa8b535UL, 0x6c98b242UL, 0xd6c9bbdbUL, 0x40f9bcacUL, 0xe36cd832UL,
  77453. 0x755cdf45UL, 0xcf0dd6dcUL, 0x593dd1abUL, 0xac30d926UL, 0x3a00de51UL,
  77454. 0x8051d7c8UL, 0x1661d0bfUL, 0xb5f4b421UL, 0x23c4b356UL, 0x9995bacfUL,
  77455. 0x0fa5bdb8UL, 0x9eb80228UL, 0x0888055fUL, 0xb2d90cc6UL, 0x24e90bb1UL,
  77456. 0x877c6f2fUL, 0x114c6858UL, 0xab1d61c1UL, 0x3d2d66b6UL, 0x9041dc76UL,
  77457. 0x0671db01UL, 0xbc20d298UL, 0x2a10d5efUL, 0x8985b171UL, 0x1fb5b606UL,
  77458. 0xa5e4bf9fUL, 0x33d4b8e8UL, 0xa2c90778UL, 0x34f9000fUL, 0x8ea80996UL,
  77459. 0x18980ee1UL, 0xbb0d6a7fUL, 0x2d3d6d08UL, 0x976c6491UL, 0x015c63e6UL,
  77460. 0xf4516b6bUL, 0x62616c1cUL, 0xd8306585UL, 0x4e0062f2UL, 0xed95066cUL,
  77461. 0x7ba5011bUL, 0xc1f40882UL, 0x57c40ff5UL, 0xc6d9b065UL, 0x50e9b712UL,
  77462. 0xeab8be8bUL, 0x7c88b9fcUL, 0xdf1ddd62UL, 0x492dda15UL, 0xf37cd38cUL,
  77463. 0x654cd4fbUL, 0x5861b24dUL, 0xce51b53aUL, 0x7400bca3UL, 0xe230bbd4UL,
  77464. 0x41a5df4aUL, 0xd795d83dUL, 0x6dc4d1a4UL, 0xfbf4d6d3UL, 0x6ae96943UL,
  77465. 0xfcd96e34UL, 0x468867adUL, 0xd0b860daUL, 0x732d0444UL, 0xe51d0333UL,
  77466. 0x5f4c0aaaUL, 0xc97c0dddUL, 0x3c710550UL, 0xaa410227UL, 0x10100bbeUL,
  77467. 0x86200cc9UL, 0x25b56857UL, 0xb3856f20UL, 0x09d466b9UL, 0x9fe461ceUL,
  77468. 0x0ef9de5eUL, 0x98c9d929UL, 0x2298d0b0UL, 0xb4a8d7c7UL, 0x173db359UL,
  77469. 0x810db42eUL, 0x3b5cbdb7UL, 0xad6cbac0UL, 0x2083b8edUL, 0xb6b3bf9aUL,
  77470. 0x0ce2b603UL, 0x9ad2b174UL, 0x3947d5eaUL, 0xaf77d29dUL, 0x1526db04UL,
  77471. 0x8316dc73UL, 0x120b63e3UL, 0x843b6494UL, 0x3e6a6d0dUL, 0xa85a6a7aUL,
  77472. 0x0bcf0ee4UL, 0x9dff0993UL, 0x27ae000aUL, 0xb19e077dUL, 0x44930ff0UL,
  77473. 0xd2a30887UL, 0x68f2011eUL, 0xfec20669UL, 0x5d5762f7UL, 0xcb676580UL,
  77474. 0x71366c19UL, 0xe7066b6eUL, 0x761bd4feUL, 0xe02bd389UL, 0x5a7ada10UL,
  77475. 0xcc4add67UL, 0x6fdfb9f9UL, 0xf9efbe8eUL, 0x43beb717UL, 0xd58eb060UL,
  77476. 0xe8a3d6d6UL, 0x7e93d1a1UL, 0xc4c2d838UL, 0x52f2df4fUL, 0xf167bbd1UL,
  77477. 0x6757bca6UL, 0xdd06b53fUL, 0x4b36b248UL, 0xda2b0dd8UL, 0x4c1b0aafUL,
  77478. 0xf64a0336UL, 0x607a0441UL, 0xc3ef60dfUL, 0x55df67a8UL, 0xef8e6e31UL,
  77479. 0x79be6946UL, 0x8cb361cbUL, 0x1a8366bcUL, 0xa0d26f25UL, 0x36e26852UL,
  77480. 0x95770cccUL, 0x03470bbbUL, 0xb9160222UL, 0x2f260555UL, 0xbe3bbac5UL,
  77481. 0x280bbdb2UL, 0x925ab42bUL, 0x046ab35cUL, 0xa7ffd7c2UL, 0x31cfd0b5UL,
  77482. 0x8b9ed92cUL, 0x1daede5bUL, 0xb0c2649bUL, 0x26f263ecUL, 0x9ca36a75UL,
  77483. 0x0a936d02UL, 0xa906099cUL, 0x3f360eebUL, 0x85670772UL, 0x13570005UL,
  77484. 0x824abf95UL, 0x147ab8e2UL, 0xae2bb17bUL, 0x381bb60cUL, 0x9b8ed292UL,
  77485. 0x0dbed5e5UL, 0xb7efdc7cUL, 0x21dfdb0bUL, 0xd4d2d386UL, 0x42e2d4f1UL,
  77486. 0xf8b3dd68UL, 0x6e83da1fUL, 0xcd16be81UL, 0x5b26b9f6UL, 0xe177b06fUL,
  77487. 0x7747b718UL, 0xe65a0888UL, 0x706a0fffUL, 0xca3b0666UL, 0x5c0b0111UL,
  77488. 0xff9e658fUL, 0x69ae62f8UL, 0xd3ff6b61UL, 0x45cf6c16UL, 0x78e20aa0UL,
  77489. 0xeed20dd7UL, 0x5483044eUL, 0xc2b30339UL, 0x612667a7UL, 0xf71660d0UL,
  77490. 0x4d476949UL, 0xdb776e3eUL, 0x4a6ad1aeUL, 0xdc5ad6d9UL, 0x660bdf40UL,
  77491. 0xf03bd837UL, 0x53aebca9UL, 0xc59ebbdeUL, 0x7fcfb247UL, 0xe9ffb530UL,
  77492. 0x1cf2bdbdUL, 0x8ac2bacaUL, 0x3093b353UL, 0xa6a3b424UL, 0x0536d0baUL,
  77493. 0x9306d7cdUL, 0x2957de54UL, 0xbf67d923UL, 0x2e7a66b3UL, 0xb84a61c4UL,
  77494. 0x021b685dUL, 0x942b6f2aUL, 0x37be0bb4UL, 0xa18e0cc3UL, 0x1bdf055aUL,
  77495. 0x8def022dUL
  77496. },
  77497. {
  77498. 0x00000000UL, 0x41311b19UL, 0x82623632UL, 0xc3532d2bUL, 0x04c56c64UL,
  77499. 0x45f4777dUL, 0x86a75a56UL, 0xc796414fUL, 0x088ad9c8UL, 0x49bbc2d1UL,
  77500. 0x8ae8effaUL, 0xcbd9f4e3UL, 0x0c4fb5acUL, 0x4d7eaeb5UL, 0x8e2d839eUL,
  77501. 0xcf1c9887UL, 0x5112c24aUL, 0x1023d953UL, 0xd370f478UL, 0x9241ef61UL,
  77502. 0x55d7ae2eUL, 0x14e6b537UL, 0xd7b5981cUL, 0x96848305UL, 0x59981b82UL,
  77503. 0x18a9009bUL, 0xdbfa2db0UL, 0x9acb36a9UL, 0x5d5d77e6UL, 0x1c6c6cffUL,
  77504. 0xdf3f41d4UL, 0x9e0e5acdUL, 0xa2248495UL, 0xe3159f8cUL, 0x2046b2a7UL,
  77505. 0x6177a9beUL, 0xa6e1e8f1UL, 0xe7d0f3e8UL, 0x2483dec3UL, 0x65b2c5daUL,
  77506. 0xaaae5d5dUL, 0xeb9f4644UL, 0x28cc6b6fUL, 0x69fd7076UL, 0xae6b3139UL,
  77507. 0xef5a2a20UL, 0x2c09070bUL, 0x6d381c12UL, 0xf33646dfUL, 0xb2075dc6UL,
  77508. 0x715470edUL, 0x30656bf4UL, 0xf7f32abbUL, 0xb6c231a2UL, 0x75911c89UL,
  77509. 0x34a00790UL, 0xfbbc9f17UL, 0xba8d840eUL, 0x79dea925UL, 0x38efb23cUL,
  77510. 0xff79f373UL, 0xbe48e86aUL, 0x7d1bc541UL, 0x3c2ade58UL, 0x054f79f0UL,
  77511. 0x447e62e9UL, 0x872d4fc2UL, 0xc61c54dbUL, 0x018a1594UL, 0x40bb0e8dUL,
  77512. 0x83e823a6UL, 0xc2d938bfUL, 0x0dc5a038UL, 0x4cf4bb21UL, 0x8fa7960aUL,
  77513. 0xce968d13UL, 0x0900cc5cUL, 0x4831d745UL, 0x8b62fa6eUL, 0xca53e177UL,
  77514. 0x545dbbbaUL, 0x156ca0a3UL, 0xd63f8d88UL, 0x970e9691UL, 0x5098d7deUL,
  77515. 0x11a9ccc7UL, 0xd2fae1ecUL, 0x93cbfaf5UL, 0x5cd76272UL, 0x1de6796bUL,
  77516. 0xdeb55440UL, 0x9f844f59UL, 0x58120e16UL, 0x1923150fUL, 0xda703824UL,
  77517. 0x9b41233dUL, 0xa76bfd65UL, 0xe65ae67cUL, 0x2509cb57UL, 0x6438d04eUL,
  77518. 0xa3ae9101UL, 0xe29f8a18UL, 0x21cca733UL, 0x60fdbc2aUL, 0xafe124adUL,
  77519. 0xeed03fb4UL, 0x2d83129fUL, 0x6cb20986UL, 0xab2448c9UL, 0xea1553d0UL,
  77520. 0x29467efbUL, 0x687765e2UL, 0xf6793f2fUL, 0xb7482436UL, 0x741b091dUL,
  77521. 0x352a1204UL, 0xf2bc534bUL, 0xb38d4852UL, 0x70de6579UL, 0x31ef7e60UL,
  77522. 0xfef3e6e7UL, 0xbfc2fdfeUL, 0x7c91d0d5UL, 0x3da0cbccUL, 0xfa368a83UL,
  77523. 0xbb07919aUL, 0x7854bcb1UL, 0x3965a7a8UL, 0x4b98833bUL, 0x0aa99822UL,
  77524. 0xc9fab509UL, 0x88cbae10UL, 0x4f5def5fUL, 0x0e6cf446UL, 0xcd3fd96dUL,
  77525. 0x8c0ec274UL, 0x43125af3UL, 0x022341eaUL, 0xc1706cc1UL, 0x804177d8UL,
  77526. 0x47d73697UL, 0x06e62d8eUL, 0xc5b500a5UL, 0x84841bbcUL, 0x1a8a4171UL,
  77527. 0x5bbb5a68UL, 0x98e87743UL, 0xd9d96c5aUL, 0x1e4f2d15UL, 0x5f7e360cUL,
  77528. 0x9c2d1b27UL, 0xdd1c003eUL, 0x120098b9UL, 0x533183a0UL, 0x9062ae8bUL,
  77529. 0xd153b592UL, 0x16c5f4ddUL, 0x57f4efc4UL, 0x94a7c2efUL, 0xd596d9f6UL,
  77530. 0xe9bc07aeUL, 0xa88d1cb7UL, 0x6bde319cUL, 0x2aef2a85UL, 0xed796bcaUL,
  77531. 0xac4870d3UL, 0x6f1b5df8UL, 0x2e2a46e1UL, 0xe136de66UL, 0xa007c57fUL,
  77532. 0x6354e854UL, 0x2265f34dUL, 0xe5f3b202UL, 0xa4c2a91bUL, 0x67918430UL,
  77533. 0x26a09f29UL, 0xb8aec5e4UL, 0xf99fdefdUL, 0x3accf3d6UL, 0x7bfde8cfUL,
  77534. 0xbc6ba980UL, 0xfd5ab299UL, 0x3e099fb2UL, 0x7f3884abUL, 0xb0241c2cUL,
  77535. 0xf1150735UL, 0x32462a1eUL, 0x73773107UL, 0xb4e17048UL, 0xf5d06b51UL,
  77536. 0x3683467aUL, 0x77b25d63UL, 0x4ed7facbUL, 0x0fe6e1d2UL, 0xccb5ccf9UL,
  77537. 0x8d84d7e0UL, 0x4a1296afUL, 0x0b238db6UL, 0xc870a09dUL, 0x8941bb84UL,
  77538. 0x465d2303UL, 0x076c381aUL, 0xc43f1531UL, 0x850e0e28UL, 0x42984f67UL,
  77539. 0x03a9547eUL, 0xc0fa7955UL, 0x81cb624cUL, 0x1fc53881UL, 0x5ef42398UL,
  77540. 0x9da70eb3UL, 0xdc9615aaUL, 0x1b0054e5UL, 0x5a314ffcUL, 0x996262d7UL,
  77541. 0xd85379ceUL, 0x174fe149UL, 0x567efa50UL, 0x952dd77bUL, 0xd41ccc62UL,
  77542. 0x138a8d2dUL, 0x52bb9634UL, 0x91e8bb1fUL, 0xd0d9a006UL, 0xecf37e5eUL,
  77543. 0xadc26547UL, 0x6e91486cUL, 0x2fa05375UL, 0xe836123aUL, 0xa9070923UL,
  77544. 0x6a542408UL, 0x2b653f11UL, 0xe479a796UL, 0xa548bc8fUL, 0x661b91a4UL,
  77545. 0x272a8abdUL, 0xe0bccbf2UL, 0xa18dd0ebUL, 0x62defdc0UL, 0x23efe6d9UL,
  77546. 0xbde1bc14UL, 0xfcd0a70dUL, 0x3f838a26UL, 0x7eb2913fUL, 0xb924d070UL,
  77547. 0xf815cb69UL, 0x3b46e642UL, 0x7a77fd5bUL, 0xb56b65dcUL, 0xf45a7ec5UL,
  77548. 0x370953eeUL, 0x763848f7UL, 0xb1ae09b8UL, 0xf09f12a1UL, 0x33cc3f8aUL,
  77549. 0x72fd2493UL
  77550. },
  77551. {
  77552. 0x00000000UL, 0x376ac201UL, 0x6ed48403UL, 0x59be4602UL, 0xdca80907UL,
  77553. 0xebc2cb06UL, 0xb27c8d04UL, 0x85164f05UL, 0xb851130eUL, 0x8f3bd10fUL,
  77554. 0xd685970dUL, 0xe1ef550cUL, 0x64f91a09UL, 0x5393d808UL, 0x0a2d9e0aUL,
  77555. 0x3d475c0bUL, 0x70a3261cUL, 0x47c9e41dUL, 0x1e77a21fUL, 0x291d601eUL,
  77556. 0xac0b2f1bUL, 0x9b61ed1aUL, 0xc2dfab18UL, 0xf5b56919UL, 0xc8f23512UL,
  77557. 0xff98f713UL, 0xa626b111UL, 0x914c7310UL, 0x145a3c15UL, 0x2330fe14UL,
  77558. 0x7a8eb816UL, 0x4de47a17UL, 0xe0464d38UL, 0xd72c8f39UL, 0x8e92c93bUL,
  77559. 0xb9f80b3aUL, 0x3cee443fUL, 0x0b84863eUL, 0x523ac03cUL, 0x6550023dUL,
  77560. 0x58175e36UL, 0x6f7d9c37UL, 0x36c3da35UL, 0x01a91834UL, 0x84bf5731UL,
  77561. 0xb3d59530UL, 0xea6bd332UL, 0xdd011133UL, 0x90e56b24UL, 0xa78fa925UL,
  77562. 0xfe31ef27UL, 0xc95b2d26UL, 0x4c4d6223UL, 0x7b27a022UL, 0x2299e620UL,
  77563. 0x15f32421UL, 0x28b4782aUL, 0x1fdeba2bUL, 0x4660fc29UL, 0x710a3e28UL,
  77564. 0xf41c712dUL, 0xc376b32cUL, 0x9ac8f52eUL, 0xada2372fUL, 0xc08d9a70UL,
  77565. 0xf7e75871UL, 0xae591e73UL, 0x9933dc72UL, 0x1c259377UL, 0x2b4f5176UL,
  77566. 0x72f11774UL, 0x459bd575UL, 0x78dc897eUL, 0x4fb64b7fUL, 0x16080d7dUL,
  77567. 0x2162cf7cUL, 0xa4748079UL, 0x931e4278UL, 0xcaa0047aUL, 0xfdcac67bUL,
  77568. 0xb02ebc6cUL, 0x87447e6dUL, 0xdefa386fUL, 0xe990fa6eUL, 0x6c86b56bUL,
  77569. 0x5bec776aUL, 0x02523168UL, 0x3538f369UL, 0x087faf62UL, 0x3f156d63UL,
  77570. 0x66ab2b61UL, 0x51c1e960UL, 0xd4d7a665UL, 0xe3bd6464UL, 0xba032266UL,
  77571. 0x8d69e067UL, 0x20cbd748UL, 0x17a11549UL, 0x4e1f534bUL, 0x7975914aUL,
  77572. 0xfc63de4fUL, 0xcb091c4eUL, 0x92b75a4cUL, 0xa5dd984dUL, 0x989ac446UL,
  77573. 0xaff00647UL, 0xf64e4045UL, 0xc1248244UL, 0x4432cd41UL, 0x73580f40UL,
  77574. 0x2ae64942UL, 0x1d8c8b43UL, 0x5068f154UL, 0x67023355UL, 0x3ebc7557UL,
  77575. 0x09d6b756UL, 0x8cc0f853UL, 0xbbaa3a52UL, 0xe2147c50UL, 0xd57ebe51UL,
  77576. 0xe839e25aUL, 0xdf53205bUL, 0x86ed6659UL, 0xb187a458UL, 0x3491eb5dUL,
  77577. 0x03fb295cUL, 0x5a456f5eUL, 0x6d2fad5fUL, 0x801b35e1UL, 0xb771f7e0UL,
  77578. 0xeecfb1e2UL, 0xd9a573e3UL, 0x5cb33ce6UL, 0x6bd9fee7UL, 0x3267b8e5UL,
  77579. 0x050d7ae4UL, 0x384a26efUL, 0x0f20e4eeUL, 0x569ea2ecUL, 0x61f460edUL,
  77580. 0xe4e22fe8UL, 0xd388ede9UL, 0x8a36abebUL, 0xbd5c69eaUL, 0xf0b813fdUL,
  77581. 0xc7d2d1fcUL, 0x9e6c97feUL, 0xa90655ffUL, 0x2c101afaUL, 0x1b7ad8fbUL,
  77582. 0x42c49ef9UL, 0x75ae5cf8UL, 0x48e900f3UL, 0x7f83c2f2UL, 0x263d84f0UL,
  77583. 0x115746f1UL, 0x944109f4UL, 0xa32bcbf5UL, 0xfa958df7UL, 0xcdff4ff6UL,
  77584. 0x605d78d9UL, 0x5737bad8UL, 0x0e89fcdaUL, 0x39e33edbUL, 0xbcf571deUL,
  77585. 0x8b9fb3dfUL, 0xd221f5ddUL, 0xe54b37dcUL, 0xd80c6bd7UL, 0xef66a9d6UL,
  77586. 0xb6d8efd4UL, 0x81b22dd5UL, 0x04a462d0UL, 0x33cea0d1UL, 0x6a70e6d3UL,
  77587. 0x5d1a24d2UL, 0x10fe5ec5UL, 0x27949cc4UL, 0x7e2adac6UL, 0x494018c7UL,
  77588. 0xcc5657c2UL, 0xfb3c95c3UL, 0xa282d3c1UL, 0x95e811c0UL, 0xa8af4dcbUL,
  77589. 0x9fc58fcaUL, 0xc67bc9c8UL, 0xf1110bc9UL, 0x740744ccUL, 0x436d86cdUL,
  77590. 0x1ad3c0cfUL, 0x2db902ceUL, 0x4096af91UL, 0x77fc6d90UL, 0x2e422b92UL,
  77591. 0x1928e993UL, 0x9c3ea696UL, 0xab546497UL, 0xf2ea2295UL, 0xc580e094UL,
  77592. 0xf8c7bc9fUL, 0xcfad7e9eUL, 0x9613389cUL, 0xa179fa9dUL, 0x246fb598UL,
  77593. 0x13057799UL, 0x4abb319bUL, 0x7dd1f39aUL, 0x3035898dUL, 0x075f4b8cUL,
  77594. 0x5ee10d8eUL, 0x698bcf8fUL, 0xec9d808aUL, 0xdbf7428bUL, 0x82490489UL,
  77595. 0xb523c688UL, 0x88649a83UL, 0xbf0e5882UL, 0xe6b01e80UL, 0xd1dadc81UL,
  77596. 0x54cc9384UL, 0x63a65185UL, 0x3a181787UL, 0x0d72d586UL, 0xa0d0e2a9UL,
  77597. 0x97ba20a8UL, 0xce0466aaUL, 0xf96ea4abUL, 0x7c78ebaeUL, 0x4b1229afUL,
  77598. 0x12ac6fadUL, 0x25c6adacUL, 0x1881f1a7UL, 0x2feb33a6UL, 0x765575a4UL,
  77599. 0x413fb7a5UL, 0xc429f8a0UL, 0xf3433aa1UL, 0xaafd7ca3UL, 0x9d97bea2UL,
  77600. 0xd073c4b5UL, 0xe71906b4UL, 0xbea740b6UL, 0x89cd82b7UL, 0x0cdbcdb2UL,
  77601. 0x3bb10fb3UL, 0x620f49b1UL, 0x55658bb0UL, 0x6822d7bbUL, 0x5f4815baUL,
  77602. 0x06f653b8UL, 0x319c91b9UL, 0xb48adebcUL, 0x83e01cbdUL, 0xda5e5abfUL,
  77603. 0xed3498beUL
  77604. },
  77605. {
  77606. 0x00000000UL, 0x6567bcb8UL, 0x8bc809aaUL, 0xeeafb512UL, 0x5797628fUL,
  77607. 0x32f0de37UL, 0xdc5f6b25UL, 0xb938d79dUL, 0xef28b4c5UL, 0x8a4f087dUL,
  77608. 0x64e0bd6fUL, 0x018701d7UL, 0xb8bfd64aUL, 0xddd86af2UL, 0x3377dfe0UL,
  77609. 0x56106358UL, 0x9f571950UL, 0xfa30a5e8UL, 0x149f10faUL, 0x71f8ac42UL,
  77610. 0xc8c07bdfUL, 0xada7c767UL, 0x43087275UL, 0x266fcecdUL, 0x707fad95UL,
  77611. 0x1518112dUL, 0xfbb7a43fUL, 0x9ed01887UL, 0x27e8cf1aUL, 0x428f73a2UL,
  77612. 0xac20c6b0UL, 0xc9477a08UL, 0x3eaf32a0UL, 0x5bc88e18UL, 0xb5673b0aUL,
  77613. 0xd00087b2UL, 0x6938502fUL, 0x0c5fec97UL, 0xe2f05985UL, 0x8797e53dUL,
  77614. 0xd1878665UL, 0xb4e03addUL, 0x5a4f8fcfUL, 0x3f283377UL, 0x8610e4eaUL,
  77615. 0xe3775852UL, 0x0dd8ed40UL, 0x68bf51f8UL, 0xa1f82bf0UL, 0xc49f9748UL,
  77616. 0x2a30225aUL, 0x4f579ee2UL, 0xf66f497fUL, 0x9308f5c7UL, 0x7da740d5UL,
  77617. 0x18c0fc6dUL, 0x4ed09f35UL, 0x2bb7238dUL, 0xc518969fUL, 0xa07f2a27UL,
  77618. 0x1947fdbaUL, 0x7c204102UL, 0x928ff410UL, 0xf7e848a8UL, 0x3d58149bUL,
  77619. 0x583fa823UL, 0xb6901d31UL, 0xd3f7a189UL, 0x6acf7614UL, 0x0fa8caacUL,
  77620. 0xe1077fbeUL, 0x8460c306UL, 0xd270a05eUL, 0xb7171ce6UL, 0x59b8a9f4UL,
  77621. 0x3cdf154cUL, 0x85e7c2d1UL, 0xe0807e69UL, 0x0e2fcb7bUL, 0x6b4877c3UL,
  77622. 0xa20f0dcbUL, 0xc768b173UL, 0x29c70461UL, 0x4ca0b8d9UL, 0xf5986f44UL,
  77623. 0x90ffd3fcUL, 0x7e5066eeUL, 0x1b37da56UL, 0x4d27b90eUL, 0x284005b6UL,
  77624. 0xc6efb0a4UL, 0xa3880c1cUL, 0x1ab0db81UL, 0x7fd76739UL, 0x9178d22bUL,
  77625. 0xf41f6e93UL, 0x03f7263bUL, 0x66909a83UL, 0x883f2f91UL, 0xed589329UL,
  77626. 0x546044b4UL, 0x3107f80cUL, 0xdfa84d1eUL, 0xbacff1a6UL, 0xecdf92feUL,
  77627. 0x89b82e46UL, 0x67179b54UL, 0x027027ecUL, 0xbb48f071UL, 0xde2f4cc9UL,
  77628. 0x3080f9dbUL, 0x55e74563UL, 0x9ca03f6bUL, 0xf9c783d3UL, 0x176836c1UL,
  77629. 0x720f8a79UL, 0xcb375de4UL, 0xae50e15cUL, 0x40ff544eUL, 0x2598e8f6UL,
  77630. 0x73888baeUL, 0x16ef3716UL, 0xf8408204UL, 0x9d273ebcUL, 0x241fe921UL,
  77631. 0x41785599UL, 0xafd7e08bUL, 0xcab05c33UL, 0x3bb659edUL, 0x5ed1e555UL,
  77632. 0xb07e5047UL, 0xd519ecffUL, 0x6c213b62UL, 0x094687daUL, 0xe7e932c8UL,
  77633. 0x828e8e70UL, 0xd49eed28UL, 0xb1f95190UL, 0x5f56e482UL, 0x3a31583aUL,
  77634. 0x83098fa7UL, 0xe66e331fUL, 0x08c1860dUL, 0x6da63ab5UL, 0xa4e140bdUL,
  77635. 0xc186fc05UL, 0x2f294917UL, 0x4a4ef5afUL, 0xf3762232UL, 0x96119e8aUL,
  77636. 0x78be2b98UL, 0x1dd99720UL, 0x4bc9f478UL, 0x2eae48c0UL, 0xc001fdd2UL,
  77637. 0xa566416aUL, 0x1c5e96f7UL, 0x79392a4fUL, 0x97969f5dUL, 0xf2f123e5UL,
  77638. 0x05196b4dUL, 0x607ed7f5UL, 0x8ed162e7UL, 0xebb6de5fUL, 0x528e09c2UL,
  77639. 0x37e9b57aUL, 0xd9460068UL, 0xbc21bcd0UL, 0xea31df88UL, 0x8f566330UL,
  77640. 0x61f9d622UL, 0x049e6a9aUL, 0xbda6bd07UL, 0xd8c101bfUL, 0x366eb4adUL,
  77641. 0x53090815UL, 0x9a4e721dUL, 0xff29cea5UL, 0x11867bb7UL, 0x74e1c70fUL,
  77642. 0xcdd91092UL, 0xa8beac2aUL, 0x46111938UL, 0x2376a580UL, 0x7566c6d8UL,
  77643. 0x10017a60UL, 0xfeaecf72UL, 0x9bc973caUL, 0x22f1a457UL, 0x479618efUL,
  77644. 0xa939adfdUL, 0xcc5e1145UL, 0x06ee4d76UL, 0x6389f1ceUL, 0x8d2644dcUL,
  77645. 0xe841f864UL, 0x51792ff9UL, 0x341e9341UL, 0xdab12653UL, 0xbfd69aebUL,
  77646. 0xe9c6f9b3UL, 0x8ca1450bUL, 0x620ef019UL, 0x07694ca1UL, 0xbe519b3cUL,
  77647. 0xdb362784UL, 0x35999296UL, 0x50fe2e2eUL, 0x99b95426UL, 0xfcdee89eUL,
  77648. 0x12715d8cUL, 0x7716e134UL, 0xce2e36a9UL, 0xab498a11UL, 0x45e63f03UL,
  77649. 0x208183bbUL, 0x7691e0e3UL, 0x13f65c5bUL, 0xfd59e949UL, 0x983e55f1UL,
  77650. 0x2106826cUL, 0x44613ed4UL, 0xaace8bc6UL, 0xcfa9377eUL, 0x38417fd6UL,
  77651. 0x5d26c36eUL, 0xb389767cUL, 0xd6eecac4UL, 0x6fd61d59UL, 0x0ab1a1e1UL,
  77652. 0xe41e14f3UL, 0x8179a84bUL, 0xd769cb13UL, 0xb20e77abUL, 0x5ca1c2b9UL,
  77653. 0x39c67e01UL, 0x80fea99cUL, 0xe5991524UL, 0x0b36a036UL, 0x6e511c8eUL,
  77654. 0xa7166686UL, 0xc271da3eUL, 0x2cde6f2cUL, 0x49b9d394UL, 0xf0810409UL,
  77655. 0x95e6b8b1UL, 0x7b490da3UL, 0x1e2eb11bUL, 0x483ed243UL, 0x2d596efbUL,
  77656. 0xc3f6dbe9UL, 0xa6916751UL, 0x1fa9b0ccUL, 0x7ace0c74UL, 0x9461b966UL,
  77657. 0xf10605deUL
  77658. #endif
  77659. }
  77660. };
  77661. /*** End of inlined file: crc32.h ***/
  77662. #endif /* DYNAMIC_CRC_TABLE */
  77663. /* =========================================================================
  77664. * This function can be used by asm versions of crc32()
  77665. */
  77666. const unsigned long FAR * ZEXPORT get_crc_table()
  77667. {
  77668. #ifdef DYNAMIC_CRC_TABLE
  77669. if (crc_table_empty)
  77670. make_crc_table();
  77671. #endif /* DYNAMIC_CRC_TABLE */
  77672. return (const unsigned long FAR *)crc_table;
  77673. }
  77674. /* ========================================================================= */
  77675. #define DO1 crc = crc_table[0][((int)crc ^ (*buf++)) & 0xff] ^ (crc >> 8)
  77676. #define DO8 DO1; DO1; DO1; DO1; DO1; DO1; DO1; DO1
  77677. /* ========================================================================= */
  77678. unsigned long ZEXPORT crc32 (unsigned long crc, const unsigned char FAR *buf, unsigned len)
  77679. {
  77680. if (buf == Z_NULL) return 0UL;
  77681. #ifdef DYNAMIC_CRC_TABLE
  77682. if (crc_table_empty)
  77683. make_crc_table();
  77684. #endif /* DYNAMIC_CRC_TABLE */
  77685. #ifdef BYFOUR
  77686. if (sizeof(void *) == sizeof(ptrdiff_t)) {
  77687. u4 endian;
  77688. endian = 1;
  77689. if (*((unsigned char *)(&endian)))
  77690. return crc32_little(crc, buf, len);
  77691. else
  77692. return crc32_big(crc, buf, len);
  77693. }
  77694. #endif /* BYFOUR */
  77695. crc = crc ^ 0xffffffffUL;
  77696. while (len >= 8) {
  77697. DO8;
  77698. len -= 8;
  77699. }
  77700. if (len) do {
  77701. DO1;
  77702. } while (--len);
  77703. return crc ^ 0xffffffffUL;
  77704. }
  77705. #ifdef BYFOUR
  77706. /* ========================================================================= */
  77707. #define DOLIT4 c ^= *buf4++; \
  77708. c = crc_table[3][c & 0xff] ^ crc_table[2][(c >> 8) & 0xff] ^ \
  77709. crc_table[1][(c >> 16) & 0xff] ^ crc_table[0][c >> 24]
  77710. #define DOLIT32 DOLIT4; DOLIT4; DOLIT4; DOLIT4; DOLIT4; DOLIT4; DOLIT4; DOLIT4
  77711. /* ========================================================================= */
  77712. local unsigned long crc32_little(unsigned long crc, const unsigned char FAR *buf, unsigned len)
  77713. {
  77714. register u4 c;
  77715. register const u4 FAR *buf4;
  77716. c = (u4)crc;
  77717. c = ~c;
  77718. while (len && ((ptrdiff_t)buf & 3)) {
  77719. c = crc_table[0][(c ^ *buf++) & 0xff] ^ (c >> 8);
  77720. len--;
  77721. }
  77722. buf4 = (const u4 FAR *)(const void FAR *)buf;
  77723. while (len >= 32) {
  77724. DOLIT32;
  77725. len -= 32;
  77726. }
  77727. while (len >= 4) {
  77728. DOLIT4;
  77729. len -= 4;
  77730. }
  77731. buf = (const unsigned char FAR *)buf4;
  77732. if (len) do {
  77733. c = crc_table[0][(c ^ *buf++) & 0xff] ^ (c >> 8);
  77734. } while (--len);
  77735. c = ~c;
  77736. return (unsigned long)c;
  77737. }
  77738. /* ========================================================================= */
  77739. #define DOBIG4 c ^= *++buf4; \
  77740. c = crc_table[4][c & 0xff] ^ crc_table[5][(c >> 8) & 0xff] ^ \
  77741. crc_table[6][(c >> 16) & 0xff] ^ crc_table[7][c >> 24]
  77742. #define DOBIG32 DOBIG4; DOBIG4; DOBIG4; DOBIG4; DOBIG4; DOBIG4; DOBIG4; DOBIG4
  77743. /* ========================================================================= */
  77744. local unsigned long crc32_big (unsigned long crc, const unsigned char FAR *buf, unsigned len)
  77745. {
  77746. register u4 c;
  77747. register const u4 FAR *buf4;
  77748. c = REV((u4)crc);
  77749. c = ~c;
  77750. while (len && ((ptrdiff_t)buf & 3)) {
  77751. c = crc_table[4][(c >> 24) ^ *buf++] ^ (c << 8);
  77752. len--;
  77753. }
  77754. buf4 = (const u4 FAR *)(const void FAR *)buf;
  77755. buf4--;
  77756. while (len >= 32) {
  77757. DOBIG32;
  77758. len -= 32;
  77759. }
  77760. while (len >= 4) {
  77761. DOBIG4;
  77762. len -= 4;
  77763. }
  77764. buf4++;
  77765. buf = (const unsigned char FAR *)buf4;
  77766. if (len) do {
  77767. c = crc_table[4][(c >> 24) ^ *buf++] ^ (c << 8);
  77768. } while (--len);
  77769. c = ~c;
  77770. return (unsigned long)(REV(c));
  77771. }
  77772. #endif /* BYFOUR */
  77773. #define GF2_DIM 32 /* dimension of GF(2) vectors (length of CRC) */
  77774. /* ========================================================================= */
  77775. local unsigned long gf2_matrix_times (unsigned long *mat, unsigned long vec)
  77776. {
  77777. unsigned long sum;
  77778. sum = 0;
  77779. while (vec) {
  77780. if (vec & 1)
  77781. sum ^= *mat;
  77782. vec >>= 1;
  77783. mat++;
  77784. }
  77785. return sum;
  77786. }
  77787. /* ========================================================================= */
  77788. local void gf2_matrix_square (unsigned long *square, unsigned long *mat)
  77789. {
  77790. int n;
  77791. for (n = 0; n < GF2_DIM; n++)
  77792. square[n] = gf2_matrix_times(mat, mat[n]);
  77793. }
  77794. /* ========================================================================= */
  77795. uLong ZEXPORT crc32_combine (uLong crc1, uLong crc2, z_off_t len2)
  77796. {
  77797. int n;
  77798. unsigned long row;
  77799. unsigned long even[GF2_DIM]; /* even-power-of-two zeros operator */
  77800. unsigned long odd[GF2_DIM]; /* odd-power-of-two zeros operator */
  77801. /* degenerate case */
  77802. if (len2 == 0)
  77803. return crc1;
  77804. /* put operator for one zero bit in odd */
  77805. odd[0] = 0xedb88320L; /* CRC-32 polynomial */
  77806. row = 1;
  77807. for (n = 1; n < GF2_DIM; n++) {
  77808. odd[n] = row;
  77809. row <<= 1;
  77810. }
  77811. /* put operator for two zero bits in even */
  77812. gf2_matrix_square(even, odd);
  77813. /* put operator for four zero bits in odd */
  77814. gf2_matrix_square(odd, even);
  77815. /* apply len2 zeros to crc1 (first square will put the operator for one
  77816. zero byte, eight zero bits, in even) */
  77817. do {
  77818. /* apply zeros operator for this bit of len2 */
  77819. gf2_matrix_square(even, odd);
  77820. if (len2 & 1)
  77821. crc1 = gf2_matrix_times(even, crc1);
  77822. len2 >>= 1;
  77823. /* if no more bits set, then done */
  77824. if (len2 == 0)
  77825. break;
  77826. /* another iteration of the loop with odd and even swapped */
  77827. gf2_matrix_square(odd, even);
  77828. if (len2 & 1)
  77829. crc1 = gf2_matrix_times(odd, crc1);
  77830. len2 >>= 1;
  77831. /* if no more bits set, then done */
  77832. } while (len2 != 0);
  77833. /* return combined crc */
  77834. crc1 ^= crc2;
  77835. return crc1;
  77836. }
  77837. /*** End of inlined file: crc32.c ***/
  77838. /*** Start of inlined file: deflate.c ***/
  77839. /*
  77840. * ALGORITHM
  77841. *
  77842. * The "deflation" process depends on being able to identify portions
  77843. * of the input text which are identical to earlier input (within a
  77844. * sliding window trailing behind the input currently being processed).
  77845. *
  77846. * The most straightforward technique turns out to be the fastest for
  77847. * most input files: try all possible matches and select the longest.
  77848. * The key feature of this algorithm is that insertions into the string
  77849. * dictionary are very simple and thus fast, and deletions are avoided
  77850. * completely. Insertions are performed at each input character, whereas
  77851. * string matches are performed only when the previous match ends. So it
  77852. * is preferable to spend more time in matches to allow very fast string
  77853. * insertions and avoid deletions. The matching algorithm for small
  77854. * strings is inspired from that of Rabin & Karp. A brute force approach
  77855. * is used to find longer strings when a small match has been found.
  77856. * A similar algorithm is used in comic (by Jan-Mark Wams) and freeze
  77857. * (by Leonid Broukhis).
  77858. * A previous version of this file used a more sophisticated algorithm
  77859. * (by Fiala and Greene) which is guaranteed to run in linear amortized
  77860. * time, but has a larger average cost, uses more memory and is patented.
  77861. * However the F&G algorithm may be faster for some highly redundant
  77862. * files if the parameter max_chain_length (described below) is too large.
  77863. *
  77864. * ACKNOWLEDGEMENTS
  77865. *
  77866. * The idea of lazy evaluation of matches is due to Jan-Mark Wams, and
  77867. * I found it in 'freeze' written by Leonid Broukhis.
  77868. * Thanks to many people for bug reports and testing.
  77869. *
  77870. * REFERENCES
  77871. *
  77872. * Deutsch, L.P.,"DEFLATE Compressed Data Format Specification".
  77873. * Available in http://www.ietf.org/rfc/rfc1951.txt
  77874. *
  77875. * A description of the Rabin and Karp algorithm is given in the book
  77876. * "Algorithms" by R. Sedgewick, Addison-Wesley, p252.
  77877. *
  77878. * Fiala,E.R., and Greene,D.H.
  77879. * Data Compression with Finite Windows, Comm.ACM, 32,4 (1989) 490-595
  77880. *
  77881. */
  77882. /* @(#) $Id: deflate.c,v 1.1 2007/06/07 17:54:37 jules_rms Exp $ */
  77883. /*** Start of inlined file: deflate.h ***/
  77884. /* WARNING: this file should *not* be used by applications. It is
  77885. part of the implementation of the compression library and is
  77886. subject to change. Applications should only use zlib.h.
  77887. */
  77888. /* @(#) $Id: deflate.h,v 1.1 2007/06/07 17:54:37 jules_rms Exp $ */
  77889. #ifndef DEFLATE_H
  77890. #define DEFLATE_H
  77891. /* define NO_GZIP when compiling if you want to disable gzip header and
  77892. trailer creation by deflate(). NO_GZIP would be used to avoid linking in
  77893. the crc code when it is not needed. For shared libraries, gzip encoding
  77894. should be left enabled. */
  77895. #ifndef NO_GZIP
  77896. # define GZIP
  77897. #endif
  77898. #define NO_DUMMY_DECL
  77899. /* ===========================================================================
  77900. * Internal compression state.
  77901. */
  77902. #define LENGTH_CODES 29
  77903. /* number of length codes, not counting the special END_BLOCK code */
  77904. #define LITERALS 256
  77905. /* number of literal bytes 0..255 */
  77906. #define L_CODES (LITERALS+1+LENGTH_CODES)
  77907. /* number of Literal or Length codes, including the END_BLOCK code */
  77908. #define D_CODES 30
  77909. /* number of distance codes */
  77910. #define BL_CODES 19
  77911. /* number of codes used to transfer the bit lengths */
  77912. #define HEAP_SIZE (2*L_CODES+1)
  77913. /* maximum heap size */
  77914. #define MAX_BITS 15
  77915. /* All codes must not exceed MAX_BITS bits */
  77916. #define INIT_STATE 42
  77917. #define EXTRA_STATE 69
  77918. #define NAME_STATE 73
  77919. #define COMMENT_STATE 91
  77920. #define HCRC_STATE 103
  77921. #define BUSY_STATE 113
  77922. #define FINISH_STATE 666
  77923. /* Stream status */
  77924. /* Data structure describing a single value and its code string. */
  77925. typedef struct ct_data_s {
  77926. union {
  77927. ush freq; /* frequency count */
  77928. ush code; /* bit string */
  77929. } fc;
  77930. union {
  77931. ush dad; /* father node in Huffman tree */
  77932. ush len; /* length of bit string */
  77933. } dl;
  77934. } FAR ct_data;
  77935. #define Freq fc.freq
  77936. #define Code fc.code
  77937. #define Dad dl.dad
  77938. #define Len dl.len
  77939. typedef struct static_tree_desc_s static_tree_desc;
  77940. typedef struct tree_desc_s {
  77941. ct_data *dyn_tree; /* the dynamic tree */
  77942. int max_code; /* largest code with non zero frequency */
  77943. static_tree_desc *stat_desc; /* the corresponding static tree */
  77944. } FAR tree_desc;
  77945. typedef ush Pos;
  77946. typedef Pos FAR Posf;
  77947. typedef unsigned IPos;
  77948. /* A Pos is an index in the character window. We use short instead of int to
  77949. * save space in the various tables. IPos is used only for parameter passing.
  77950. */
  77951. typedef struct internal_state {
  77952. z_streamp strm; /* pointer back to this zlib stream */
  77953. int status; /* as the name implies */
  77954. Bytef *pending_buf; /* output still pending */
  77955. ulg pending_buf_size; /* size of pending_buf */
  77956. Bytef *pending_out; /* next pending byte to output to the stream */
  77957. uInt pending; /* nb of bytes in the pending buffer */
  77958. int wrap; /* bit 0 true for zlib, bit 1 true for gzip */
  77959. gz_headerp gzhead; /* gzip header information to write */
  77960. uInt gzindex; /* where in extra, name, or comment */
  77961. Byte method; /* STORED (for zip only) or DEFLATED */
  77962. int last_flush; /* value of flush param for previous deflate call */
  77963. /* used by deflate.c: */
  77964. uInt w_size; /* LZ77 window size (32K by default) */
  77965. uInt w_bits; /* log2(w_size) (8..16) */
  77966. uInt w_mask; /* w_size - 1 */
  77967. Bytef *window;
  77968. /* Sliding window. Input bytes are read into the second half of the window,
  77969. * and move to the first half later to keep a dictionary of at least wSize
  77970. * bytes. With this organization, matches are limited to a distance of
  77971. * wSize-MAX_MATCH bytes, but this ensures that IO is always
  77972. * performed with a length multiple of the block size. Also, it limits
  77973. * the window size to 64K, which is quite useful on MSDOS.
  77974. * To do: use the user input buffer as sliding window.
  77975. */
  77976. ulg window_size;
  77977. /* Actual size of window: 2*wSize, except when the user input buffer
  77978. * is directly used as sliding window.
  77979. */
  77980. Posf *prev;
  77981. /* Link to older string with same hash index. To limit the size of this
  77982. * array to 64K, this link is maintained only for the last 32K strings.
  77983. * An index in this array is thus a window index modulo 32K.
  77984. */
  77985. Posf *head; /* Heads of the hash chains or NIL. */
  77986. uInt ins_h; /* hash index of string to be inserted */
  77987. uInt hash_size; /* number of elements in hash table */
  77988. uInt hash_bits; /* log2(hash_size) */
  77989. uInt hash_mask; /* hash_size-1 */
  77990. uInt hash_shift;
  77991. /* Number of bits by which ins_h must be shifted at each input
  77992. * step. It must be such that after MIN_MATCH steps, the oldest
  77993. * byte no longer takes part in the hash key, that is:
  77994. * hash_shift * MIN_MATCH >= hash_bits
  77995. */
  77996. long block_start;
  77997. /* Window position at the beginning of the current output block. Gets
  77998. * negative when the window is moved backwards.
  77999. */
  78000. uInt match_length; /* length of best match */
  78001. IPos prev_match; /* previous match */
  78002. int match_available; /* set if previous match exists */
  78003. uInt strstart; /* start of string to insert */
  78004. uInt match_start; /* start of matching string */
  78005. uInt lookahead; /* number of valid bytes ahead in window */
  78006. uInt prev_length;
  78007. /* Length of the best match at previous step. Matches not greater than this
  78008. * are discarded. This is used in the lazy match evaluation.
  78009. */
  78010. uInt max_chain_length;
  78011. /* To speed up deflation, hash chains are never searched beyond this
  78012. * length. A higher limit improves compression ratio but degrades the
  78013. * speed.
  78014. */
  78015. uInt max_lazy_match;
  78016. /* Attempt to find a better match only when the current match is strictly
  78017. * smaller than this value. This mechanism is used only for compression
  78018. * levels >= 4.
  78019. */
  78020. # define max_insert_length max_lazy_match
  78021. /* Insert new strings in the hash table only if the match length is not
  78022. * greater than this length. This saves time but degrades compression.
  78023. * max_insert_length is used only for compression levels <= 3.
  78024. */
  78025. int level; /* compression level (1..9) */
  78026. int strategy; /* favor or force Huffman coding*/
  78027. uInt good_match;
  78028. /* Use a faster search when the previous match is longer than this */
  78029. int nice_match; /* Stop searching when current match exceeds this */
  78030. /* used by trees.c: */
  78031. /* Didn't use ct_data typedef below to supress compiler warning */
  78032. struct ct_data_s dyn_ltree[HEAP_SIZE]; /* literal and length tree */
  78033. struct ct_data_s dyn_dtree[2*D_CODES+1]; /* distance tree */
  78034. struct ct_data_s bl_tree[2*BL_CODES+1]; /* Huffman tree for bit lengths */
  78035. struct tree_desc_s l_desc; /* desc. for literal tree */
  78036. struct tree_desc_s d_desc; /* desc. for distance tree */
  78037. struct tree_desc_s bl_desc; /* desc. for bit length tree */
  78038. ush bl_count[MAX_BITS+1];
  78039. /* number of codes at each bit length for an optimal tree */
  78040. int heap[2*L_CODES+1]; /* heap used to build the Huffman trees */
  78041. int heap_len; /* number of elements in the heap */
  78042. int heap_max; /* element of largest frequency */
  78043. /* The sons of heap[n] are heap[2*n] and heap[2*n+1]. heap[0] is not used.
  78044. * The same heap array is used to build all trees.
  78045. */
  78046. uch depth[2*L_CODES+1];
  78047. /* Depth of each subtree used as tie breaker for trees of equal frequency
  78048. */
  78049. uchf *l_buf; /* buffer for literals or lengths */
  78050. uInt lit_bufsize;
  78051. /* Size of match buffer for literals/lengths. There are 4 reasons for
  78052. * limiting lit_bufsize to 64K:
  78053. * - frequencies can be kept in 16 bit counters
  78054. * - if compression is not successful for the first block, all input
  78055. * data is still in the window so we can still emit a stored block even
  78056. * when input comes from standard input. (This can also be done for
  78057. * all blocks if lit_bufsize is not greater than 32K.)
  78058. * - if compression is not successful for a file smaller than 64K, we can
  78059. * even emit a stored file instead of a stored block (saving 5 bytes).
  78060. * This is applicable only for zip (not gzip or zlib).
  78061. * - creating new Huffman trees less frequently may not provide fast
  78062. * adaptation to changes in the input data statistics. (Take for
  78063. * example a binary file with poorly compressible code followed by
  78064. * a highly compressible string table.) Smaller buffer sizes give
  78065. * fast adaptation but have of course the overhead of transmitting
  78066. * trees more frequently.
  78067. * - I can't count above 4
  78068. */
  78069. uInt last_lit; /* running index in l_buf */
  78070. ushf *d_buf;
  78071. /* Buffer for distances. To simplify the code, d_buf and l_buf have
  78072. * the same number of elements. To use different lengths, an extra flag
  78073. * array would be necessary.
  78074. */
  78075. ulg opt_len; /* bit length of current block with optimal trees */
  78076. ulg static_len; /* bit length of current block with static trees */
  78077. uInt matches; /* number of string matches in current block */
  78078. int last_eob_len; /* bit length of EOB code for last block */
  78079. #ifdef DEBUG
  78080. ulg compressed_len; /* total bit length of compressed file mod 2^32 */
  78081. ulg bits_sent; /* bit length of compressed data sent mod 2^32 */
  78082. #endif
  78083. ush bi_buf;
  78084. /* Output buffer. bits are inserted starting at the bottom (least
  78085. * significant bits).
  78086. */
  78087. int bi_valid;
  78088. /* Number of valid bits in bi_buf. All bits above the last valid bit
  78089. * are always zero.
  78090. */
  78091. } FAR deflate_state;
  78092. /* Output a byte on the stream.
  78093. * IN assertion: there is enough room in pending_buf.
  78094. */
  78095. #define put_byte(s, c) {s->pending_buf[s->pending++] = (c);}
  78096. #define MIN_LOOKAHEAD (MAX_MATCH+MIN_MATCH+1)
  78097. /* Minimum amount of lookahead, except at the end of the input file.
  78098. * See deflate.c for comments about the MIN_MATCH+1.
  78099. */
  78100. #define MAX_DIST(s) ((s)->w_size-MIN_LOOKAHEAD)
  78101. /* In order to simplify the code, particularly on 16 bit machines, match
  78102. * distances are limited to MAX_DIST instead of WSIZE.
  78103. */
  78104. /* in trees.c */
  78105. void _tr_init OF((deflate_state *s));
  78106. int _tr_tally OF((deflate_state *s, unsigned dist, unsigned lc));
  78107. void _tr_flush_block OF((deflate_state *s, charf *buf, ulg stored_len,
  78108. int eof));
  78109. void _tr_align OF((deflate_state *s));
  78110. void _tr_stored_block OF((deflate_state *s, charf *buf, ulg stored_len,
  78111. int eof));
  78112. #define d_code(dist) \
  78113. ((dist) < 256 ? _dist_code[dist] : _dist_code[256+((dist)>>7)])
  78114. /* Mapping from a distance to a distance code. dist is the distance - 1 and
  78115. * must not have side effects. _dist_code[256] and _dist_code[257] are never
  78116. * used.
  78117. */
  78118. #ifndef DEBUG
  78119. /* Inline versions of _tr_tally for speed: */
  78120. #if defined(GEN_TREES_H) || !defined(STDC)
  78121. extern uch _length_code[];
  78122. extern uch _dist_code[];
  78123. #else
  78124. extern const uch _length_code[];
  78125. extern const uch _dist_code[];
  78126. #endif
  78127. # define _tr_tally_lit(s, c, flush) \
  78128. { uch cc = (c); \
  78129. s->d_buf[s->last_lit] = 0; \
  78130. s->l_buf[s->last_lit++] = cc; \
  78131. s->dyn_ltree[cc].Freq++; \
  78132. flush = (s->last_lit == s->lit_bufsize-1); \
  78133. }
  78134. # define _tr_tally_dist(s, distance, length, flush) \
  78135. { uch len = (length); \
  78136. ush dist = (distance); \
  78137. s->d_buf[s->last_lit] = dist; \
  78138. s->l_buf[s->last_lit++] = len; \
  78139. dist--; \
  78140. s->dyn_ltree[_length_code[len]+LITERALS+1].Freq++; \
  78141. s->dyn_dtree[d_code(dist)].Freq++; \
  78142. flush = (s->last_lit == s->lit_bufsize-1); \
  78143. }
  78144. #else
  78145. # define _tr_tally_lit(s, c, flush) flush = _tr_tally(s, 0, c)
  78146. # define _tr_tally_dist(s, distance, length, flush) \
  78147. flush = _tr_tally(s, distance, length)
  78148. #endif
  78149. #endif /* DEFLATE_H */
  78150. /*** End of inlined file: deflate.h ***/
  78151. const char deflate_copyright[] =
  78152. " deflate 1.2.3 Copyright 1995-2005 Jean-loup Gailly ";
  78153. /*
  78154. If you use the zlib library in a product, an acknowledgment is welcome
  78155. in the documentation of your product. If for some reason you cannot
  78156. include such an acknowledgment, I would appreciate that you keep this
  78157. copyright string in the executable of your product.
  78158. */
  78159. /* ===========================================================================
  78160. * Function prototypes.
  78161. */
  78162. typedef enum {
  78163. need_more, /* block not completed, need more input or more output */
  78164. block_done, /* block flush performed */
  78165. finish_started, /* finish started, need only more output at next deflate */
  78166. finish_done /* finish done, accept no more input or output */
  78167. } block_state;
  78168. typedef block_state (*compress_func) OF((deflate_state *s, int flush));
  78169. /* Compression function. Returns the block state after the call. */
  78170. local void fill_window OF((deflate_state *s));
  78171. local block_state deflate_stored OF((deflate_state *s, int flush));
  78172. local block_state deflate_fast OF((deflate_state *s, int flush));
  78173. #ifndef FASTEST
  78174. local block_state deflate_slow OF((deflate_state *s, int flush));
  78175. #endif
  78176. local void lm_init OF((deflate_state *s));
  78177. local void putShortMSB OF((deflate_state *s, uInt b));
  78178. local void flush_pending OF((z_streamp strm));
  78179. local int read_buf OF((z_streamp strm, Bytef *buf, unsigned size));
  78180. #ifndef FASTEST
  78181. #ifdef ASMV
  78182. void match_init OF((void)); /* asm code initialization */
  78183. uInt longest_match OF((deflate_state *s, IPos cur_match));
  78184. #else
  78185. local uInt longest_match OF((deflate_state *s, IPos cur_match));
  78186. #endif
  78187. #endif
  78188. local uInt longest_match_fast OF((deflate_state *s, IPos cur_match));
  78189. #ifdef DEBUG
  78190. local void check_match OF((deflate_state *s, IPos start, IPos match,
  78191. int length));
  78192. #endif
  78193. /* ===========================================================================
  78194. * Local data
  78195. */
  78196. #define NIL 0
  78197. /* Tail of hash chains */
  78198. #ifndef TOO_FAR
  78199. # define TOO_FAR 4096
  78200. #endif
  78201. /* Matches of length 3 are discarded if their distance exceeds TOO_FAR */
  78202. #define MIN_LOOKAHEAD (MAX_MATCH+MIN_MATCH+1)
  78203. /* Minimum amount of lookahead, except at the end of the input file.
  78204. * See deflate.c for comments about the MIN_MATCH+1.
  78205. */
  78206. /* Values for max_lazy_match, good_match and max_chain_length, depending on
  78207. * the desired pack level (0..9). The values given below have been tuned to
  78208. * exclude worst case performance for pathological files. Better values may be
  78209. * found for specific files.
  78210. */
  78211. typedef struct config_s {
  78212. ush good_length; /* reduce lazy search above this match length */
  78213. ush max_lazy; /* do not perform lazy search above this match length */
  78214. ush nice_length; /* quit search above this match length */
  78215. ush max_chain;
  78216. compress_func func;
  78217. } config;
  78218. #ifdef FASTEST
  78219. local const config configuration_table[2] = {
  78220. /* good lazy nice chain */
  78221. /* 0 */ {0, 0, 0, 0, deflate_stored}, /* store only */
  78222. /* 1 */ {4, 4, 8, 4, deflate_fast}}; /* max speed, no lazy matches */
  78223. #else
  78224. local const config configuration_table[10] = {
  78225. /* good lazy nice chain */
  78226. /* 0 */ {0, 0, 0, 0, deflate_stored}, /* store only */
  78227. /* 1 */ {4, 4, 8, 4, deflate_fast}, /* max speed, no lazy matches */
  78228. /* 2 */ {4, 5, 16, 8, deflate_fast},
  78229. /* 3 */ {4, 6, 32, 32, deflate_fast},
  78230. /* 4 */ {4, 4, 16, 16, deflate_slow}, /* lazy matches */
  78231. /* 5 */ {8, 16, 32, 32, deflate_slow},
  78232. /* 6 */ {8, 16, 128, 128, deflate_slow},
  78233. /* 7 */ {8, 32, 128, 256, deflate_slow},
  78234. /* 8 */ {32, 128, 258, 1024, deflate_slow},
  78235. /* 9 */ {32, 258, 258, 4096, deflate_slow}}; /* max compression */
  78236. #endif
  78237. /* Note: the deflate() code requires max_lazy >= MIN_MATCH and max_chain >= 4
  78238. * For deflate_fast() (levels <= 3) good is ignored and lazy has a different
  78239. * meaning.
  78240. */
  78241. #define EQUAL 0
  78242. /* result of memcmp for equal strings */
  78243. #ifndef NO_DUMMY_DECL
  78244. struct static_tree_desc_s {int dummy;}; /* for buggy compilers */
  78245. #endif
  78246. /* ===========================================================================
  78247. * Update a hash value with the given input byte
  78248. * IN assertion: all calls to to UPDATE_HASH are made with consecutive
  78249. * input characters, so that a running hash key can be computed from the
  78250. * previous key instead of complete recalculation each time.
  78251. */
  78252. #define UPDATE_HASH(s,h,c) (h = (((h)<<s->hash_shift) ^ (c)) & s->hash_mask)
  78253. /* ===========================================================================
  78254. * Insert string str in the dictionary and set match_head to the previous head
  78255. * of the hash chain (the most recent string with same hash key). Return
  78256. * the previous length of the hash chain.
  78257. * If this file is compiled with -DFASTEST, the compression level is forced
  78258. * to 1, and no hash chains are maintained.
  78259. * IN assertion: all calls to to INSERT_STRING are made with consecutive
  78260. * input characters and the first MIN_MATCH bytes of str are valid
  78261. * (except for the last MIN_MATCH-1 bytes of the input file).
  78262. */
  78263. #ifdef FASTEST
  78264. #define INSERT_STRING(s, str, match_head) \
  78265. (UPDATE_HASH(s, s->ins_h, s->window[(str) + (MIN_MATCH-1)]), \
  78266. match_head = s->head[s->ins_h], \
  78267. s->head[s->ins_h] = (Pos)(str))
  78268. #else
  78269. #define INSERT_STRING(s, str, match_head) \
  78270. (UPDATE_HASH(s, s->ins_h, s->window[(str) + (MIN_MATCH-1)]), \
  78271. match_head = s->prev[(str) & s->w_mask] = s->head[s->ins_h], \
  78272. s->head[s->ins_h] = (Pos)(str))
  78273. #endif
  78274. /* ===========================================================================
  78275. * Initialize the hash table (avoiding 64K overflow for 16 bit systems).
  78276. * prev[] will be initialized on the fly.
  78277. */
  78278. #define CLEAR_HASH(s) \
  78279. s->head[s->hash_size-1] = NIL; \
  78280. zmemzero((Bytef *)s->head, (unsigned)(s->hash_size-1)*sizeof(*s->head));
  78281. /* ========================================================================= */
  78282. int ZEXPORT deflateInit_(z_streamp strm, int level, const char *version, int stream_size)
  78283. {
  78284. return deflateInit2_(strm, level, Z_DEFLATED, MAX_WBITS, DEF_MEM_LEVEL,
  78285. Z_DEFAULT_STRATEGY, version, stream_size);
  78286. /* To do: ignore strm->next_in if we use it as window */
  78287. }
  78288. /* ========================================================================= */
  78289. int ZEXPORT deflateInit2_ (z_streamp strm, int level, int method, int windowBits, int memLevel, int strategy, const char *version, int stream_size)
  78290. {
  78291. deflate_state *s;
  78292. int wrap = 1;
  78293. static const char my_version[] = ZLIB_VERSION;
  78294. ushf *overlay;
  78295. /* We overlay pending_buf and d_buf+l_buf. This works since the average
  78296. * output size for (length,distance) codes is <= 24 bits.
  78297. */
  78298. if (version == Z_NULL || version[0] != my_version[0] ||
  78299. stream_size != sizeof(z_stream)) {
  78300. return Z_VERSION_ERROR;
  78301. }
  78302. if (strm == Z_NULL) return Z_STREAM_ERROR;
  78303. strm->msg = Z_NULL;
  78304. if (strm->zalloc == (alloc_func)0) {
  78305. strm->zalloc = zcalloc;
  78306. strm->opaque = (voidpf)0;
  78307. }
  78308. if (strm->zfree == (free_func)0) strm->zfree = zcfree;
  78309. #ifdef FASTEST
  78310. if (level != 0) level = 1;
  78311. #else
  78312. if (level == Z_DEFAULT_COMPRESSION) level = 6;
  78313. #endif
  78314. if (windowBits < 0) { /* suppress zlib wrapper */
  78315. wrap = 0;
  78316. windowBits = -windowBits;
  78317. }
  78318. #ifdef GZIP
  78319. else if (windowBits > 15) {
  78320. wrap = 2; /* write gzip wrapper instead */
  78321. windowBits -= 16;
  78322. }
  78323. #endif
  78324. if (memLevel < 1 || memLevel > MAX_MEM_LEVEL || method != Z_DEFLATED ||
  78325. windowBits < 8 || windowBits > 15 || level < 0 || level > 9 ||
  78326. strategy < 0 || strategy > Z_FIXED) {
  78327. return Z_STREAM_ERROR;
  78328. }
  78329. if (windowBits == 8) windowBits = 9; /* until 256-byte window bug fixed */
  78330. s = (deflate_state *) ZALLOC(strm, 1, sizeof(deflate_state));
  78331. if (s == Z_NULL) return Z_MEM_ERROR;
  78332. strm->state = (struct internal_state FAR *)s;
  78333. s->strm = strm;
  78334. s->wrap = wrap;
  78335. s->gzhead = Z_NULL;
  78336. s->w_bits = windowBits;
  78337. s->w_size = 1 << s->w_bits;
  78338. s->w_mask = s->w_size - 1;
  78339. s->hash_bits = memLevel + 7;
  78340. s->hash_size = 1 << s->hash_bits;
  78341. s->hash_mask = s->hash_size - 1;
  78342. s->hash_shift = ((s->hash_bits+MIN_MATCH-1)/MIN_MATCH);
  78343. s->window = (Bytef *) ZALLOC(strm, s->w_size, 2*sizeof(Byte));
  78344. s->prev = (Posf *) ZALLOC(strm, s->w_size, sizeof(Pos));
  78345. s->head = (Posf *) ZALLOC(strm, s->hash_size, sizeof(Pos));
  78346. s->lit_bufsize = 1 << (memLevel + 6); /* 16K elements by default */
  78347. overlay = (ushf *) ZALLOC(strm, s->lit_bufsize, sizeof(ush)+2);
  78348. s->pending_buf = (uchf *) overlay;
  78349. s->pending_buf_size = (ulg)s->lit_bufsize * (sizeof(ush)+2L);
  78350. if (s->window == Z_NULL || s->prev == Z_NULL || s->head == Z_NULL ||
  78351. s->pending_buf == Z_NULL) {
  78352. s->status = FINISH_STATE;
  78353. strm->msg = (char*)ERR_MSG(Z_MEM_ERROR);
  78354. deflateEnd (strm);
  78355. return Z_MEM_ERROR;
  78356. }
  78357. s->d_buf = overlay + s->lit_bufsize/sizeof(ush);
  78358. s->l_buf = s->pending_buf + (1+sizeof(ush))*s->lit_bufsize;
  78359. s->level = level;
  78360. s->strategy = strategy;
  78361. s->method = (Byte)method;
  78362. return deflateReset(strm);
  78363. }
  78364. /* ========================================================================= */
  78365. int ZEXPORT deflateSetDictionary (z_streamp strm, const Bytef *dictionary, uInt dictLength)
  78366. {
  78367. deflate_state *s;
  78368. uInt length = dictLength;
  78369. uInt n;
  78370. IPos hash_head = 0;
  78371. if (strm == Z_NULL || strm->state == Z_NULL || dictionary == Z_NULL ||
  78372. strm->state->wrap == 2 ||
  78373. (strm->state->wrap == 1 && strm->state->status != INIT_STATE))
  78374. return Z_STREAM_ERROR;
  78375. s = strm->state;
  78376. if (s->wrap)
  78377. strm->adler = adler32(strm->adler, dictionary, dictLength);
  78378. if (length < MIN_MATCH) return Z_OK;
  78379. if (length > MAX_DIST(s)) {
  78380. length = MAX_DIST(s);
  78381. dictionary += dictLength - length; /* use the tail of the dictionary */
  78382. }
  78383. zmemcpy(s->window, dictionary, length);
  78384. s->strstart = length;
  78385. s->block_start = (long)length;
  78386. /* Insert all strings in the hash table (except for the last two bytes).
  78387. * s->lookahead stays null, so s->ins_h will be recomputed at the next
  78388. * call of fill_window.
  78389. */
  78390. s->ins_h = s->window[0];
  78391. UPDATE_HASH(s, s->ins_h, s->window[1]);
  78392. for (n = 0; n <= length - MIN_MATCH; n++) {
  78393. INSERT_STRING(s, n, hash_head);
  78394. }
  78395. if (hash_head) hash_head = 0; /* to make compiler happy */
  78396. return Z_OK;
  78397. }
  78398. /* ========================================================================= */
  78399. int ZEXPORT deflateReset (z_streamp strm)
  78400. {
  78401. deflate_state *s;
  78402. if (strm == Z_NULL || strm->state == Z_NULL ||
  78403. strm->zalloc == (alloc_func)0 || strm->zfree == (free_func)0) {
  78404. return Z_STREAM_ERROR;
  78405. }
  78406. strm->total_in = strm->total_out = 0;
  78407. strm->msg = Z_NULL; /* use zfree if we ever allocate msg dynamically */
  78408. strm->data_type = Z_UNKNOWN;
  78409. s = (deflate_state *)strm->state;
  78410. s->pending = 0;
  78411. s->pending_out = s->pending_buf;
  78412. if (s->wrap < 0) {
  78413. s->wrap = -s->wrap; /* was made negative by deflate(..., Z_FINISH); */
  78414. }
  78415. s->status = s->wrap ? INIT_STATE : BUSY_STATE;
  78416. strm->adler =
  78417. #ifdef GZIP
  78418. s->wrap == 2 ? crc32(0L, Z_NULL, 0) :
  78419. #endif
  78420. adler32(0L, Z_NULL, 0);
  78421. s->last_flush = Z_NO_FLUSH;
  78422. _tr_init(s);
  78423. lm_init(s);
  78424. return Z_OK;
  78425. }
  78426. /* ========================================================================= */
  78427. int ZEXPORT deflateSetHeader (z_streamp strm, gz_headerp head)
  78428. {
  78429. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  78430. if (strm->state->wrap != 2) return Z_STREAM_ERROR;
  78431. strm->state->gzhead = head;
  78432. return Z_OK;
  78433. }
  78434. /* ========================================================================= */
  78435. int ZEXPORT deflatePrime (z_streamp strm, int bits, int value)
  78436. {
  78437. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  78438. strm->state->bi_valid = bits;
  78439. strm->state->bi_buf = (ush)(value & ((1 << bits) - 1));
  78440. return Z_OK;
  78441. }
  78442. /* ========================================================================= */
  78443. int ZEXPORT deflateParams (z_streamp strm, int level, int strategy)
  78444. {
  78445. deflate_state *s;
  78446. compress_func func;
  78447. int err = Z_OK;
  78448. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  78449. s = strm->state;
  78450. #ifdef FASTEST
  78451. if (level != 0) level = 1;
  78452. #else
  78453. if (level == Z_DEFAULT_COMPRESSION) level = 6;
  78454. #endif
  78455. if (level < 0 || level > 9 || strategy < 0 || strategy > Z_FIXED) {
  78456. return Z_STREAM_ERROR;
  78457. }
  78458. func = configuration_table[s->level].func;
  78459. if (func != configuration_table[level].func && strm->total_in != 0) {
  78460. /* Flush the last buffer: */
  78461. err = deflate(strm, Z_PARTIAL_FLUSH);
  78462. }
  78463. if (s->level != level) {
  78464. s->level = level;
  78465. s->max_lazy_match = configuration_table[level].max_lazy;
  78466. s->good_match = configuration_table[level].good_length;
  78467. s->nice_match = configuration_table[level].nice_length;
  78468. s->max_chain_length = configuration_table[level].max_chain;
  78469. }
  78470. s->strategy = strategy;
  78471. return err;
  78472. }
  78473. /* ========================================================================= */
  78474. int ZEXPORT deflateTune (z_streamp strm, int good_length, int max_lazy, int nice_length, int max_chain)
  78475. {
  78476. deflate_state *s;
  78477. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  78478. s = strm->state;
  78479. s->good_match = good_length;
  78480. s->max_lazy_match = max_lazy;
  78481. s->nice_match = nice_length;
  78482. s->max_chain_length = max_chain;
  78483. return Z_OK;
  78484. }
  78485. /* =========================================================================
  78486. * For the default windowBits of 15 and memLevel of 8, this function returns
  78487. * a close to exact, as well as small, upper bound on the compressed size.
  78488. * They are coded as constants here for a reason--if the #define's are
  78489. * changed, then this function needs to be changed as well. The return
  78490. * value for 15 and 8 only works for those exact settings.
  78491. *
  78492. * For any setting other than those defaults for windowBits and memLevel,
  78493. * the value returned is a conservative worst case for the maximum expansion
  78494. * resulting from using fixed blocks instead of stored blocks, which deflate
  78495. * can emit on compressed data for some combinations of the parameters.
  78496. *
  78497. * This function could be more sophisticated to provide closer upper bounds
  78498. * for every combination of windowBits and memLevel, as well as wrap.
  78499. * But even the conservative upper bound of about 14% expansion does not
  78500. * seem onerous for output buffer allocation.
  78501. */
  78502. uLong ZEXPORT deflateBound (z_streamp strm, uLong sourceLen)
  78503. {
  78504. deflate_state *s;
  78505. uLong destLen;
  78506. /* conservative upper bound */
  78507. destLen = sourceLen +
  78508. ((sourceLen + 7) >> 3) + ((sourceLen + 63) >> 6) + 11;
  78509. /* if can't get parameters, return conservative bound */
  78510. if (strm == Z_NULL || strm->state == Z_NULL)
  78511. return destLen;
  78512. /* if not default parameters, return conservative bound */
  78513. s = strm->state;
  78514. if (s->w_bits != 15 || s->hash_bits != 8 + 7)
  78515. return destLen;
  78516. /* default settings: return tight bound for that case */
  78517. return compressBound(sourceLen);
  78518. }
  78519. /* =========================================================================
  78520. * Put a short in the pending buffer. The 16-bit value is put in MSB order.
  78521. * IN assertion: the stream state is correct and there is enough room in
  78522. * pending_buf.
  78523. */
  78524. local void putShortMSB (deflate_state *s, uInt b)
  78525. {
  78526. put_byte(s, (Byte)(b >> 8));
  78527. put_byte(s, (Byte)(b & 0xff));
  78528. }
  78529. /* =========================================================================
  78530. * Flush as much pending output as possible. All deflate() output goes
  78531. * through this function so some applications may wish to modify it
  78532. * to avoid allocating a large strm->next_out buffer and copying into it.
  78533. * (See also read_buf()).
  78534. */
  78535. local void flush_pending (z_streamp strm)
  78536. {
  78537. unsigned len = strm->state->pending;
  78538. if (len > strm->avail_out) len = strm->avail_out;
  78539. if (len == 0) return;
  78540. zmemcpy(strm->next_out, strm->state->pending_out, len);
  78541. strm->next_out += len;
  78542. strm->state->pending_out += len;
  78543. strm->total_out += len;
  78544. strm->avail_out -= len;
  78545. strm->state->pending -= len;
  78546. if (strm->state->pending == 0) {
  78547. strm->state->pending_out = strm->state->pending_buf;
  78548. }
  78549. }
  78550. /* ========================================================================= */
  78551. int ZEXPORT deflate (z_streamp strm, int flush)
  78552. {
  78553. int old_flush; /* value of flush param for previous deflate call */
  78554. deflate_state *s;
  78555. if (strm == Z_NULL || strm->state == Z_NULL ||
  78556. flush > Z_FINISH || flush < 0) {
  78557. return Z_STREAM_ERROR;
  78558. }
  78559. s = strm->state;
  78560. if (strm->next_out == Z_NULL ||
  78561. (strm->next_in == Z_NULL && strm->avail_in != 0) ||
  78562. (s->status == FINISH_STATE && flush != Z_FINISH)) {
  78563. ERR_RETURN(strm, Z_STREAM_ERROR);
  78564. }
  78565. if (strm->avail_out == 0) ERR_RETURN(strm, Z_BUF_ERROR);
  78566. s->strm = strm; /* just in case */
  78567. old_flush = s->last_flush;
  78568. s->last_flush = flush;
  78569. /* Write the header */
  78570. if (s->status == INIT_STATE) {
  78571. #ifdef GZIP
  78572. if (s->wrap == 2) {
  78573. strm->adler = crc32(0L, Z_NULL, 0);
  78574. put_byte(s, 31);
  78575. put_byte(s, 139);
  78576. put_byte(s, 8);
  78577. if (s->gzhead == NULL) {
  78578. put_byte(s, 0);
  78579. put_byte(s, 0);
  78580. put_byte(s, 0);
  78581. put_byte(s, 0);
  78582. put_byte(s, 0);
  78583. put_byte(s, s->level == 9 ? 2 :
  78584. (s->strategy >= Z_HUFFMAN_ONLY || s->level < 2 ?
  78585. 4 : 0));
  78586. put_byte(s, OS_CODE);
  78587. s->status = BUSY_STATE;
  78588. }
  78589. else {
  78590. put_byte(s, (s->gzhead->text ? 1 : 0) +
  78591. (s->gzhead->hcrc ? 2 : 0) +
  78592. (s->gzhead->extra == Z_NULL ? 0 : 4) +
  78593. (s->gzhead->name == Z_NULL ? 0 : 8) +
  78594. (s->gzhead->comment == Z_NULL ? 0 : 16)
  78595. );
  78596. put_byte(s, (Byte)(s->gzhead->time & 0xff));
  78597. put_byte(s, (Byte)((s->gzhead->time >> 8) & 0xff));
  78598. put_byte(s, (Byte)((s->gzhead->time >> 16) & 0xff));
  78599. put_byte(s, (Byte)((s->gzhead->time >> 24) & 0xff));
  78600. put_byte(s, s->level == 9 ? 2 :
  78601. (s->strategy >= Z_HUFFMAN_ONLY || s->level < 2 ?
  78602. 4 : 0));
  78603. put_byte(s, s->gzhead->os & 0xff);
  78604. if (s->gzhead->extra != NULL) {
  78605. put_byte(s, s->gzhead->extra_len & 0xff);
  78606. put_byte(s, (s->gzhead->extra_len >> 8) & 0xff);
  78607. }
  78608. if (s->gzhead->hcrc)
  78609. strm->adler = crc32(strm->adler, s->pending_buf,
  78610. s->pending);
  78611. s->gzindex = 0;
  78612. s->status = EXTRA_STATE;
  78613. }
  78614. }
  78615. else
  78616. #endif
  78617. {
  78618. uInt header = (Z_DEFLATED + ((s->w_bits-8)<<4)) << 8;
  78619. uInt level_flags;
  78620. if (s->strategy >= Z_HUFFMAN_ONLY || s->level < 2)
  78621. level_flags = 0;
  78622. else if (s->level < 6)
  78623. level_flags = 1;
  78624. else if (s->level == 6)
  78625. level_flags = 2;
  78626. else
  78627. level_flags = 3;
  78628. header |= (level_flags << 6);
  78629. if (s->strstart != 0) header |= PRESET_DICT;
  78630. header += 31 - (header % 31);
  78631. s->status = BUSY_STATE;
  78632. putShortMSB(s, header);
  78633. /* Save the adler32 of the preset dictionary: */
  78634. if (s->strstart != 0) {
  78635. putShortMSB(s, (uInt)(strm->adler >> 16));
  78636. putShortMSB(s, (uInt)(strm->adler & 0xffff));
  78637. }
  78638. strm->adler = adler32(0L, Z_NULL, 0);
  78639. }
  78640. }
  78641. #ifdef GZIP
  78642. if (s->status == EXTRA_STATE) {
  78643. if (s->gzhead->extra != NULL) {
  78644. uInt beg = s->pending; /* start of bytes to update crc */
  78645. while (s->gzindex < (s->gzhead->extra_len & 0xffff)) {
  78646. if (s->pending == s->pending_buf_size) {
  78647. if (s->gzhead->hcrc && s->pending > beg)
  78648. strm->adler = crc32(strm->adler, s->pending_buf + beg,
  78649. s->pending - beg);
  78650. flush_pending(strm);
  78651. beg = s->pending;
  78652. if (s->pending == s->pending_buf_size)
  78653. break;
  78654. }
  78655. put_byte(s, s->gzhead->extra[s->gzindex]);
  78656. s->gzindex++;
  78657. }
  78658. if (s->gzhead->hcrc && s->pending > beg)
  78659. strm->adler = crc32(strm->adler, s->pending_buf + beg,
  78660. s->pending - beg);
  78661. if (s->gzindex == s->gzhead->extra_len) {
  78662. s->gzindex = 0;
  78663. s->status = NAME_STATE;
  78664. }
  78665. }
  78666. else
  78667. s->status = NAME_STATE;
  78668. }
  78669. if (s->status == NAME_STATE) {
  78670. if (s->gzhead->name != NULL) {
  78671. uInt beg = s->pending; /* start of bytes to update crc */
  78672. int val;
  78673. do {
  78674. if (s->pending == s->pending_buf_size) {
  78675. if (s->gzhead->hcrc && s->pending > beg)
  78676. strm->adler = crc32(strm->adler, s->pending_buf + beg,
  78677. s->pending - beg);
  78678. flush_pending(strm);
  78679. beg = s->pending;
  78680. if (s->pending == s->pending_buf_size) {
  78681. val = 1;
  78682. break;
  78683. }
  78684. }
  78685. val = s->gzhead->name[s->gzindex++];
  78686. put_byte(s, val);
  78687. } while (val != 0);
  78688. if (s->gzhead->hcrc && s->pending > beg)
  78689. strm->adler = crc32(strm->adler, s->pending_buf + beg,
  78690. s->pending - beg);
  78691. if (val == 0) {
  78692. s->gzindex = 0;
  78693. s->status = COMMENT_STATE;
  78694. }
  78695. }
  78696. else
  78697. s->status = COMMENT_STATE;
  78698. }
  78699. if (s->status == COMMENT_STATE) {
  78700. if (s->gzhead->comment != NULL) {
  78701. uInt beg = s->pending; /* start of bytes to update crc */
  78702. int val;
  78703. do {
  78704. if (s->pending == s->pending_buf_size) {
  78705. if (s->gzhead->hcrc && s->pending > beg)
  78706. strm->adler = crc32(strm->adler, s->pending_buf + beg,
  78707. s->pending - beg);
  78708. flush_pending(strm);
  78709. beg = s->pending;
  78710. if (s->pending == s->pending_buf_size) {
  78711. val = 1;
  78712. break;
  78713. }
  78714. }
  78715. val = s->gzhead->comment[s->gzindex++];
  78716. put_byte(s, val);
  78717. } while (val != 0);
  78718. if (s->gzhead->hcrc && s->pending > beg)
  78719. strm->adler = crc32(strm->adler, s->pending_buf + beg,
  78720. s->pending - beg);
  78721. if (val == 0)
  78722. s->status = HCRC_STATE;
  78723. }
  78724. else
  78725. s->status = HCRC_STATE;
  78726. }
  78727. if (s->status == HCRC_STATE) {
  78728. if (s->gzhead->hcrc) {
  78729. if (s->pending + 2 > s->pending_buf_size)
  78730. flush_pending(strm);
  78731. if (s->pending + 2 <= s->pending_buf_size) {
  78732. put_byte(s, (Byte)(strm->adler & 0xff));
  78733. put_byte(s, (Byte)((strm->adler >> 8) & 0xff));
  78734. strm->adler = crc32(0L, Z_NULL, 0);
  78735. s->status = BUSY_STATE;
  78736. }
  78737. }
  78738. else
  78739. s->status = BUSY_STATE;
  78740. }
  78741. #endif
  78742. /* Flush as much pending output as possible */
  78743. if (s->pending != 0) {
  78744. flush_pending(strm);
  78745. if (strm->avail_out == 0) {
  78746. /* Since avail_out is 0, deflate will be called again with
  78747. * more output space, but possibly with both pending and
  78748. * avail_in equal to zero. There won't be anything to do,
  78749. * but this is not an error situation so make sure we
  78750. * return OK instead of BUF_ERROR at next call of deflate:
  78751. */
  78752. s->last_flush = -1;
  78753. return Z_OK;
  78754. }
  78755. /* Make sure there is something to do and avoid duplicate consecutive
  78756. * flushes. For repeated and useless calls with Z_FINISH, we keep
  78757. * returning Z_STREAM_END instead of Z_BUF_ERROR.
  78758. */
  78759. } else if (strm->avail_in == 0 && flush <= old_flush &&
  78760. flush != Z_FINISH) {
  78761. ERR_RETURN(strm, Z_BUF_ERROR);
  78762. }
  78763. /* User must not provide more input after the first FINISH: */
  78764. if (s->status == FINISH_STATE && strm->avail_in != 0) {
  78765. ERR_RETURN(strm, Z_BUF_ERROR);
  78766. }
  78767. /* Start a new block or continue the current one.
  78768. */
  78769. if (strm->avail_in != 0 || s->lookahead != 0 ||
  78770. (flush != Z_NO_FLUSH && s->status != FINISH_STATE)) {
  78771. block_state bstate;
  78772. bstate = (*(configuration_table[s->level].func))(s, flush);
  78773. if (bstate == finish_started || bstate == finish_done) {
  78774. s->status = FINISH_STATE;
  78775. }
  78776. if (bstate == need_more || bstate == finish_started) {
  78777. if (strm->avail_out == 0) {
  78778. s->last_flush = -1; /* avoid BUF_ERROR next call, see above */
  78779. }
  78780. return Z_OK;
  78781. /* If flush != Z_NO_FLUSH && avail_out == 0, the next call
  78782. * of deflate should use the same flush parameter to make sure
  78783. * that the flush is complete. So we don't have to output an
  78784. * empty block here, this will be done at next call. This also
  78785. * ensures that for a very small output buffer, we emit at most
  78786. * one empty block.
  78787. */
  78788. }
  78789. if (bstate == block_done) {
  78790. if (flush == Z_PARTIAL_FLUSH) {
  78791. _tr_align(s);
  78792. } else { /* FULL_FLUSH or SYNC_FLUSH */
  78793. _tr_stored_block(s, (char*)0, 0L, 0);
  78794. /* For a full flush, this empty block will be recognized
  78795. * as a special marker by inflate_sync().
  78796. */
  78797. if (flush == Z_FULL_FLUSH) {
  78798. CLEAR_HASH(s); /* forget history */
  78799. }
  78800. }
  78801. flush_pending(strm);
  78802. if (strm->avail_out == 0) {
  78803. s->last_flush = -1; /* avoid BUF_ERROR at next call, see above */
  78804. return Z_OK;
  78805. }
  78806. }
  78807. }
  78808. Assert(strm->avail_out > 0, "bug2");
  78809. if (flush != Z_FINISH) return Z_OK;
  78810. if (s->wrap <= 0) return Z_STREAM_END;
  78811. /* Write the trailer */
  78812. #ifdef GZIP
  78813. if (s->wrap == 2) {
  78814. put_byte(s, (Byte)(strm->adler & 0xff));
  78815. put_byte(s, (Byte)((strm->adler >> 8) & 0xff));
  78816. put_byte(s, (Byte)((strm->adler >> 16) & 0xff));
  78817. put_byte(s, (Byte)((strm->adler >> 24) & 0xff));
  78818. put_byte(s, (Byte)(strm->total_in & 0xff));
  78819. put_byte(s, (Byte)((strm->total_in >> 8) & 0xff));
  78820. put_byte(s, (Byte)((strm->total_in >> 16) & 0xff));
  78821. put_byte(s, (Byte)((strm->total_in >> 24) & 0xff));
  78822. }
  78823. else
  78824. #endif
  78825. {
  78826. putShortMSB(s, (uInt)(strm->adler >> 16));
  78827. putShortMSB(s, (uInt)(strm->adler & 0xffff));
  78828. }
  78829. flush_pending(strm);
  78830. /* If avail_out is zero, the application will call deflate again
  78831. * to flush the rest.
  78832. */
  78833. if (s->wrap > 0) s->wrap = -s->wrap; /* write the trailer only once! */
  78834. return s->pending != 0 ? Z_OK : Z_STREAM_END;
  78835. }
  78836. /* ========================================================================= */
  78837. int ZEXPORT deflateEnd (z_streamp strm)
  78838. {
  78839. int status;
  78840. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  78841. status = strm->state->status;
  78842. if (status != INIT_STATE &&
  78843. status != EXTRA_STATE &&
  78844. status != NAME_STATE &&
  78845. status != COMMENT_STATE &&
  78846. status != HCRC_STATE &&
  78847. status != BUSY_STATE &&
  78848. status != FINISH_STATE) {
  78849. return Z_STREAM_ERROR;
  78850. }
  78851. /* Deallocate in reverse order of allocations: */
  78852. TRY_FREE(strm, strm->state->pending_buf);
  78853. TRY_FREE(strm, strm->state->head);
  78854. TRY_FREE(strm, strm->state->prev);
  78855. TRY_FREE(strm, strm->state->window);
  78856. ZFREE(strm, strm->state);
  78857. strm->state = Z_NULL;
  78858. return status == BUSY_STATE ? Z_DATA_ERROR : Z_OK;
  78859. }
  78860. /* =========================================================================
  78861. * Copy the source state to the destination state.
  78862. * To simplify the source, this is not supported for 16-bit MSDOS (which
  78863. * doesn't have enough memory anyway to duplicate compression states).
  78864. */
  78865. int ZEXPORT deflateCopy (z_streamp dest, z_streamp source)
  78866. {
  78867. #ifdef MAXSEG_64K
  78868. return Z_STREAM_ERROR;
  78869. #else
  78870. deflate_state *ds;
  78871. deflate_state *ss;
  78872. ushf *overlay;
  78873. if (source == Z_NULL || dest == Z_NULL || source->state == Z_NULL) {
  78874. return Z_STREAM_ERROR;
  78875. }
  78876. ss = source->state;
  78877. zmemcpy(dest, source, sizeof(z_stream));
  78878. ds = (deflate_state *) ZALLOC(dest, 1, sizeof(deflate_state));
  78879. if (ds == Z_NULL) return Z_MEM_ERROR;
  78880. dest->state = (struct internal_state FAR *) ds;
  78881. zmemcpy(ds, ss, sizeof(deflate_state));
  78882. ds->strm = dest;
  78883. ds->window = (Bytef *) ZALLOC(dest, ds->w_size, 2*sizeof(Byte));
  78884. ds->prev = (Posf *) ZALLOC(dest, ds->w_size, sizeof(Pos));
  78885. ds->head = (Posf *) ZALLOC(dest, ds->hash_size, sizeof(Pos));
  78886. overlay = (ushf *) ZALLOC(dest, ds->lit_bufsize, sizeof(ush)+2);
  78887. ds->pending_buf = (uchf *) overlay;
  78888. if (ds->window == Z_NULL || ds->prev == Z_NULL || ds->head == Z_NULL ||
  78889. ds->pending_buf == Z_NULL) {
  78890. deflateEnd (dest);
  78891. return Z_MEM_ERROR;
  78892. }
  78893. /* following zmemcpy do not work for 16-bit MSDOS */
  78894. zmemcpy(ds->window, ss->window, ds->w_size * 2 * sizeof(Byte));
  78895. zmemcpy(ds->prev, ss->prev, ds->w_size * sizeof(Pos));
  78896. zmemcpy(ds->head, ss->head, ds->hash_size * sizeof(Pos));
  78897. zmemcpy(ds->pending_buf, ss->pending_buf, (uInt)ds->pending_buf_size);
  78898. ds->pending_out = ds->pending_buf + (ss->pending_out - ss->pending_buf);
  78899. ds->d_buf = overlay + ds->lit_bufsize/sizeof(ush);
  78900. ds->l_buf = ds->pending_buf + (1+sizeof(ush))*ds->lit_bufsize;
  78901. ds->l_desc.dyn_tree = ds->dyn_ltree;
  78902. ds->d_desc.dyn_tree = ds->dyn_dtree;
  78903. ds->bl_desc.dyn_tree = ds->bl_tree;
  78904. return Z_OK;
  78905. #endif /* MAXSEG_64K */
  78906. }
  78907. /* ===========================================================================
  78908. * Read a new buffer from the current input stream, update the adler32
  78909. * and total number of bytes read. All deflate() input goes through
  78910. * this function so some applications may wish to modify it to avoid
  78911. * allocating a large strm->next_in buffer and copying from it.
  78912. * (See also flush_pending()).
  78913. */
  78914. local int read_buf (z_streamp strm, Bytef *buf, unsigned size)
  78915. {
  78916. unsigned len = strm->avail_in;
  78917. if (len > size) len = size;
  78918. if (len == 0) return 0;
  78919. strm->avail_in -= len;
  78920. if (strm->state->wrap == 1) {
  78921. strm->adler = adler32(strm->adler, strm->next_in, len);
  78922. }
  78923. #ifdef GZIP
  78924. else if (strm->state->wrap == 2) {
  78925. strm->adler = crc32(strm->adler, strm->next_in, len);
  78926. }
  78927. #endif
  78928. zmemcpy(buf, strm->next_in, len);
  78929. strm->next_in += len;
  78930. strm->total_in += len;
  78931. return (int)len;
  78932. }
  78933. /* ===========================================================================
  78934. * Initialize the "longest match" routines for a new zlib stream
  78935. */
  78936. local void lm_init (deflate_state *s)
  78937. {
  78938. s->window_size = (ulg)2L*s->w_size;
  78939. CLEAR_HASH(s);
  78940. /* Set the default configuration parameters:
  78941. */
  78942. s->max_lazy_match = configuration_table[s->level].max_lazy;
  78943. s->good_match = configuration_table[s->level].good_length;
  78944. s->nice_match = configuration_table[s->level].nice_length;
  78945. s->max_chain_length = configuration_table[s->level].max_chain;
  78946. s->strstart = 0;
  78947. s->block_start = 0L;
  78948. s->lookahead = 0;
  78949. s->match_length = s->prev_length = MIN_MATCH-1;
  78950. s->match_available = 0;
  78951. s->ins_h = 0;
  78952. #ifndef FASTEST
  78953. #ifdef ASMV
  78954. match_init(); /* initialize the asm code */
  78955. #endif
  78956. #endif
  78957. }
  78958. #ifndef FASTEST
  78959. /* ===========================================================================
  78960. * Set match_start to the longest match starting at the given string and
  78961. * return its length. Matches shorter or equal to prev_length are discarded,
  78962. * in which case the result is equal to prev_length and match_start is
  78963. * garbage.
  78964. * IN assertions: cur_match is the head of the hash chain for the current
  78965. * string (strstart) and its distance is <= MAX_DIST, and prev_length >= 1
  78966. * OUT assertion: the match length is not greater than s->lookahead.
  78967. */
  78968. #ifndef ASMV
  78969. /* For 80x86 and 680x0, an optimized version will be provided in match.asm or
  78970. * match.S. The code will be functionally equivalent.
  78971. */
  78972. local uInt longest_match(deflate_state *s, IPos cur_match)
  78973. {
  78974. unsigned chain_length = s->max_chain_length;/* max hash chain length */
  78975. register Bytef *scan = s->window + s->strstart; /* current string */
  78976. register Bytef *match; /* matched string */
  78977. register int len; /* length of current match */
  78978. int best_len = s->prev_length; /* best match length so far */
  78979. int nice_match = s->nice_match; /* stop if match long enough */
  78980. IPos limit = s->strstart > (IPos)MAX_DIST(s) ?
  78981. s->strstart - (IPos)MAX_DIST(s) : NIL;
  78982. /* Stop when cur_match becomes <= limit. To simplify the code,
  78983. * we prevent matches with the string of window index 0.
  78984. */
  78985. Posf *prev = s->prev;
  78986. uInt wmask = s->w_mask;
  78987. #ifdef UNALIGNED_OK
  78988. /* Compare two bytes at a time. Note: this is not always beneficial.
  78989. * Try with and without -DUNALIGNED_OK to check.
  78990. */
  78991. register Bytef *strend = s->window + s->strstart + MAX_MATCH - 1;
  78992. register ush scan_start = *(ushf*)scan;
  78993. register ush scan_end = *(ushf*)(scan+best_len-1);
  78994. #else
  78995. register Bytef *strend = s->window + s->strstart + MAX_MATCH;
  78996. register Byte scan_end1 = scan[best_len-1];
  78997. register Byte scan_end = scan[best_len];
  78998. #endif
  78999. /* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16.
  79000. * It is easy to get rid of this optimization if necessary.
  79001. */
  79002. Assert(s->hash_bits >= 8 && MAX_MATCH == 258, "Code too clever");
  79003. /* Do not waste too much time if we already have a good match: */
  79004. if (s->prev_length >= s->good_match) {
  79005. chain_length >>= 2;
  79006. }
  79007. /* Do not look for matches beyond the end of the input. This is necessary
  79008. * to make deflate deterministic.
  79009. */
  79010. if ((uInt)nice_match > s->lookahead) nice_match = s->lookahead;
  79011. Assert((ulg)s->strstart <= s->window_size-MIN_LOOKAHEAD, "need lookahead");
  79012. do {
  79013. Assert(cur_match < s->strstart, "no future");
  79014. match = s->window + cur_match;
  79015. /* Skip to next match if the match length cannot increase
  79016. * or if the match length is less than 2. Note that the checks below
  79017. * for insufficient lookahead only occur occasionally for performance
  79018. * reasons. Therefore uninitialized memory will be accessed, and
  79019. * conditional jumps will be made that depend on those values.
  79020. * However the length of the match is limited to the lookahead, so
  79021. * the output of deflate is not affected by the uninitialized values.
  79022. */
  79023. #if (defined(UNALIGNED_OK) && MAX_MATCH == 258)
  79024. /* This code assumes sizeof(unsigned short) == 2. Do not use
  79025. * UNALIGNED_OK if your compiler uses a different size.
  79026. */
  79027. if (*(ushf*)(match+best_len-1) != scan_end ||
  79028. *(ushf*)match != scan_start) continue;
  79029. /* It is not necessary to compare scan[2] and match[2] since they are
  79030. * always equal when the other bytes match, given that the hash keys
  79031. * are equal and that HASH_BITS >= 8. Compare 2 bytes at a time at
  79032. * strstart+3, +5, ... up to strstart+257. We check for insufficient
  79033. * lookahead only every 4th comparison; the 128th check will be made
  79034. * at strstart+257. If MAX_MATCH-2 is not a multiple of 8, it is
  79035. * necessary to put more guard bytes at the end of the window, or
  79036. * to check more often for insufficient lookahead.
  79037. */
  79038. Assert(scan[2] == match[2], "scan[2]?");
  79039. scan++, match++;
  79040. do {
  79041. } while (*(ushf*)(scan+=2) == *(ushf*)(match+=2) &&
  79042. *(ushf*)(scan+=2) == *(ushf*)(match+=2) &&
  79043. *(ushf*)(scan+=2) == *(ushf*)(match+=2) &&
  79044. *(ushf*)(scan+=2) == *(ushf*)(match+=2) &&
  79045. scan < strend);
  79046. /* The funny "do {}" generates better code on most compilers */
  79047. /* Here, scan <= window+strstart+257 */
  79048. Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan");
  79049. if (*scan == *match) scan++;
  79050. len = (MAX_MATCH - 1) - (int)(strend-scan);
  79051. scan = strend - (MAX_MATCH-1);
  79052. #else /* UNALIGNED_OK */
  79053. if (match[best_len] != scan_end ||
  79054. match[best_len-1] != scan_end1 ||
  79055. *match != *scan ||
  79056. *++match != scan[1]) continue;
  79057. /* The check at best_len-1 can be removed because it will be made
  79058. * again later. (This heuristic is not always a win.)
  79059. * It is not necessary to compare scan[2] and match[2] since they
  79060. * are always equal when the other bytes match, given that
  79061. * the hash keys are equal and that HASH_BITS >= 8.
  79062. */
  79063. scan += 2, match++;
  79064. Assert(*scan == *match, "match[2]?");
  79065. /* We check for insufficient lookahead only every 8th comparison;
  79066. * the 256th check will be made at strstart+258.
  79067. */
  79068. do {
  79069. } while (*++scan == *++match && *++scan == *++match &&
  79070. *++scan == *++match && *++scan == *++match &&
  79071. *++scan == *++match && *++scan == *++match &&
  79072. *++scan == *++match && *++scan == *++match &&
  79073. scan < strend);
  79074. Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan");
  79075. len = MAX_MATCH - (int)(strend - scan);
  79076. scan = strend - MAX_MATCH;
  79077. #endif /* UNALIGNED_OK */
  79078. if (len > best_len) {
  79079. s->match_start = cur_match;
  79080. best_len = len;
  79081. if (len >= nice_match) break;
  79082. #ifdef UNALIGNED_OK
  79083. scan_end = *(ushf*)(scan+best_len-1);
  79084. #else
  79085. scan_end1 = scan[best_len-1];
  79086. scan_end = scan[best_len];
  79087. #endif
  79088. }
  79089. } while ((cur_match = prev[cur_match & wmask]) > limit
  79090. && --chain_length != 0);
  79091. if ((uInt)best_len <= s->lookahead) return (uInt)best_len;
  79092. return s->lookahead;
  79093. }
  79094. #endif /* ASMV */
  79095. #endif /* FASTEST */
  79096. /* ---------------------------------------------------------------------------
  79097. * Optimized version for level == 1 or strategy == Z_RLE only
  79098. */
  79099. local uInt longest_match_fast (deflate_state *s, IPos cur_match)
  79100. {
  79101. register Bytef *scan = s->window + s->strstart; /* current string */
  79102. register Bytef *match; /* matched string */
  79103. register int len; /* length of current match */
  79104. register Bytef *strend = s->window + s->strstart + MAX_MATCH;
  79105. /* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16.
  79106. * It is easy to get rid of this optimization if necessary.
  79107. */
  79108. Assert(s->hash_bits >= 8 && MAX_MATCH == 258, "Code too clever");
  79109. Assert((ulg)s->strstart <= s->window_size-MIN_LOOKAHEAD, "need lookahead");
  79110. Assert(cur_match < s->strstart, "no future");
  79111. match = s->window + cur_match;
  79112. /* Return failure if the match length is less than 2:
  79113. */
  79114. if (match[0] != scan[0] || match[1] != scan[1]) return MIN_MATCH-1;
  79115. /* The check at best_len-1 can be removed because it will be made
  79116. * again later. (This heuristic is not always a win.)
  79117. * It is not necessary to compare scan[2] and match[2] since they
  79118. * are always equal when the other bytes match, given that
  79119. * the hash keys are equal and that HASH_BITS >= 8.
  79120. */
  79121. scan += 2, match += 2;
  79122. Assert(*scan == *match, "match[2]?");
  79123. /* We check for insufficient lookahead only every 8th comparison;
  79124. * the 256th check will be made at strstart+258.
  79125. */
  79126. do {
  79127. } while (*++scan == *++match && *++scan == *++match &&
  79128. *++scan == *++match && *++scan == *++match &&
  79129. *++scan == *++match && *++scan == *++match &&
  79130. *++scan == *++match && *++scan == *++match &&
  79131. scan < strend);
  79132. Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan");
  79133. len = MAX_MATCH - (int)(strend - scan);
  79134. if (len < MIN_MATCH) return MIN_MATCH - 1;
  79135. s->match_start = cur_match;
  79136. return (uInt)len <= s->lookahead ? (uInt)len : s->lookahead;
  79137. }
  79138. #ifdef DEBUG
  79139. /* ===========================================================================
  79140. * Check that the match at match_start is indeed a match.
  79141. */
  79142. local void check_match(deflate_state *s, IPos start, IPos match, int length)
  79143. {
  79144. /* check that the match is indeed a match */
  79145. if (zmemcmp(s->window + match,
  79146. s->window + start, length) != EQUAL) {
  79147. fprintf(stderr, " start %u, match %u, length %d\n",
  79148. start, match, length);
  79149. do {
  79150. fprintf(stderr, "%c%c", s->window[match++], s->window[start++]);
  79151. } while (--length != 0);
  79152. z_error("invalid match");
  79153. }
  79154. if (z_verbose > 1) {
  79155. fprintf(stderr,"\\[%d,%d]", start-match, length);
  79156. do { putc(s->window[start++], stderr); } while (--length != 0);
  79157. }
  79158. }
  79159. #else
  79160. # define check_match(s, start, match, length)
  79161. #endif /* DEBUG */
  79162. /* ===========================================================================
  79163. * Fill the window when the lookahead becomes insufficient.
  79164. * Updates strstart and lookahead.
  79165. *
  79166. * IN assertion: lookahead < MIN_LOOKAHEAD
  79167. * OUT assertions: strstart <= window_size-MIN_LOOKAHEAD
  79168. * At least one byte has been read, or avail_in == 0; reads are
  79169. * performed for at least two bytes (required for the zip translate_eol
  79170. * option -- not supported here).
  79171. */
  79172. local void fill_window (deflate_state *s)
  79173. {
  79174. register unsigned n, m;
  79175. register Posf *p;
  79176. unsigned more; /* Amount of free space at the end of the window. */
  79177. uInt wsize = s->w_size;
  79178. do {
  79179. more = (unsigned)(s->window_size -(ulg)s->lookahead -(ulg)s->strstart);
  79180. /* Deal with !@#$% 64K limit: */
  79181. if (sizeof(int) <= 2) {
  79182. if (more == 0 && s->strstart == 0 && s->lookahead == 0) {
  79183. more = wsize;
  79184. } else if (more == (unsigned)(-1)) {
  79185. /* Very unlikely, but possible on 16 bit machine if
  79186. * strstart == 0 && lookahead == 1 (input done a byte at time)
  79187. */
  79188. more--;
  79189. }
  79190. }
  79191. /* If the window is almost full and there is insufficient lookahead,
  79192. * move the upper half to the lower one to make room in the upper half.
  79193. */
  79194. if (s->strstart >= wsize+MAX_DIST(s)) {
  79195. zmemcpy(s->window, s->window+wsize, (unsigned)wsize);
  79196. s->match_start -= wsize;
  79197. s->strstart -= wsize; /* we now have strstart >= MAX_DIST */
  79198. s->block_start -= (long) wsize;
  79199. /* Slide the hash table (could be avoided with 32 bit values
  79200. at the expense of memory usage). We slide even when level == 0
  79201. to keep the hash table consistent if we switch back to level > 0
  79202. later. (Using level 0 permanently is not an optimal usage of
  79203. zlib, so we don't care about this pathological case.)
  79204. */
  79205. /* %%% avoid this when Z_RLE */
  79206. n = s->hash_size;
  79207. p = &s->head[n];
  79208. do {
  79209. m = *--p;
  79210. *p = (Pos)(m >= wsize ? m-wsize : NIL);
  79211. } while (--n);
  79212. n = wsize;
  79213. #ifndef FASTEST
  79214. p = &s->prev[n];
  79215. do {
  79216. m = *--p;
  79217. *p = (Pos)(m >= wsize ? m-wsize : NIL);
  79218. /* If n is not on any hash chain, prev[n] is garbage but
  79219. * its value will never be used.
  79220. */
  79221. } while (--n);
  79222. #endif
  79223. more += wsize;
  79224. }
  79225. if (s->strm->avail_in == 0) return;
  79226. /* If there was no sliding:
  79227. * strstart <= WSIZE+MAX_DIST-1 && lookahead <= MIN_LOOKAHEAD - 1 &&
  79228. * more == window_size - lookahead - strstart
  79229. * => more >= window_size - (MIN_LOOKAHEAD-1 + WSIZE + MAX_DIST-1)
  79230. * => more >= window_size - 2*WSIZE + 2
  79231. * In the BIG_MEM or MMAP case (not yet supported),
  79232. * window_size == input_size + MIN_LOOKAHEAD &&
  79233. * strstart + s->lookahead <= input_size => more >= MIN_LOOKAHEAD.
  79234. * Otherwise, window_size == 2*WSIZE so more >= 2.
  79235. * If there was sliding, more >= WSIZE. So in all cases, more >= 2.
  79236. */
  79237. Assert(more >= 2, "more < 2");
  79238. n = read_buf(s->strm, s->window + s->strstart + s->lookahead, more);
  79239. s->lookahead += n;
  79240. /* Initialize the hash value now that we have some input: */
  79241. if (s->lookahead >= MIN_MATCH) {
  79242. s->ins_h = s->window[s->strstart];
  79243. UPDATE_HASH(s, s->ins_h, s->window[s->strstart+1]);
  79244. #if MIN_MATCH != 3
  79245. Call UPDATE_HASH() MIN_MATCH-3 more times
  79246. #endif
  79247. }
  79248. /* If the whole input has less than MIN_MATCH bytes, ins_h is garbage,
  79249. * but this is not important since only literal bytes will be emitted.
  79250. */
  79251. } while (s->lookahead < MIN_LOOKAHEAD && s->strm->avail_in != 0);
  79252. }
  79253. /* ===========================================================================
  79254. * Flush the current block, with given end-of-file flag.
  79255. * IN assertion: strstart is set to the end of the current match.
  79256. */
  79257. #define FLUSH_BLOCK_ONLY(s, eof) { \
  79258. _tr_flush_block(s, (s->block_start >= 0L ? \
  79259. (charf *)&s->window[(unsigned)s->block_start] : \
  79260. (charf *)Z_NULL), \
  79261. (ulg)((long)s->strstart - s->block_start), \
  79262. (eof)); \
  79263. s->block_start = s->strstart; \
  79264. flush_pending(s->strm); \
  79265. Tracev((stderr,"[FLUSH]")); \
  79266. }
  79267. /* Same but force premature exit if necessary. */
  79268. #define FLUSH_BLOCK(s, eof) { \
  79269. FLUSH_BLOCK_ONLY(s, eof); \
  79270. if (s->strm->avail_out == 0) return (eof) ? finish_started : need_more; \
  79271. }
  79272. /* ===========================================================================
  79273. * Copy without compression as much as possible from the input stream, return
  79274. * the current block state.
  79275. * This function does not insert new strings in the dictionary since
  79276. * uncompressible data is probably not useful. This function is used
  79277. * only for the level=0 compression option.
  79278. * NOTE: this function should be optimized to avoid extra copying from
  79279. * window to pending_buf.
  79280. */
  79281. local block_state deflate_stored(deflate_state *s, int flush)
  79282. {
  79283. /* Stored blocks are limited to 0xffff bytes, pending_buf is limited
  79284. * to pending_buf_size, and each stored block has a 5 byte header:
  79285. */
  79286. ulg max_block_size = 0xffff;
  79287. ulg max_start;
  79288. if (max_block_size > s->pending_buf_size - 5) {
  79289. max_block_size = s->pending_buf_size - 5;
  79290. }
  79291. /* Copy as much as possible from input to output: */
  79292. for (;;) {
  79293. /* Fill the window as much as possible: */
  79294. if (s->lookahead <= 1) {
  79295. Assert(s->strstart < s->w_size+MAX_DIST(s) ||
  79296. s->block_start >= (long)s->w_size, "slide too late");
  79297. fill_window(s);
  79298. if (s->lookahead == 0 && flush == Z_NO_FLUSH) return need_more;
  79299. if (s->lookahead == 0) break; /* flush the current block */
  79300. }
  79301. Assert(s->block_start >= 0L, "block gone");
  79302. s->strstart += s->lookahead;
  79303. s->lookahead = 0;
  79304. /* Emit a stored block if pending_buf will be full: */
  79305. max_start = s->block_start + max_block_size;
  79306. if (s->strstart == 0 || (ulg)s->strstart >= max_start) {
  79307. /* strstart == 0 is possible when wraparound on 16-bit machine */
  79308. s->lookahead = (uInt)(s->strstart - max_start);
  79309. s->strstart = (uInt)max_start;
  79310. FLUSH_BLOCK(s, 0);
  79311. }
  79312. /* Flush if we may have to slide, otherwise block_start may become
  79313. * negative and the data will be gone:
  79314. */
  79315. if (s->strstart - (uInt)s->block_start >= MAX_DIST(s)) {
  79316. FLUSH_BLOCK(s, 0);
  79317. }
  79318. }
  79319. FLUSH_BLOCK(s, flush == Z_FINISH);
  79320. return flush == Z_FINISH ? finish_done : block_done;
  79321. }
  79322. /* ===========================================================================
  79323. * Compress as much as possible from the input stream, return the current
  79324. * block state.
  79325. * This function does not perform lazy evaluation of matches and inserts
  79326. * new strings in the dictionary only for unmatched strings or for short
  79327. * matches. It is used only for the fast compression options.
  79328. */
  79329. local block_state deflate_fast(deflate_state *s, int flush)
  79330. {
  79331. IPos hash_head = NIL; /* head of the hash chain */
  79332. int bflush; /* set if current block must be flushed */
  79333. for (;;) {
  79334. /* Make sure that we always have enough lookahead, except
  79335. * at the end of the input file. We need MAX_MATCH bytes
  79336. * for the next match, plus MIN_MATCH bytes to insert the
  79337. * string following the next match.
  79338. */
  79339. if (s->lookahead < MIN_LOOKAHEAD) {
  79340. fill_window(s);
  79341. if (s->lookahead < MIN_LOOKAHEAD && flush == Z_NO_FLUSH) {
  79342. return need_more;
  79343. }
  79344. if (s->lookahead == 0) break; /* flush the current block */
  79345. }
  79346. /* Insert the string window[strstart .. strstart+2] in the
  79347. * dictionary, and set hash_head to the head of the hash chain:
  79348. */
  79349. if (s->lookahead >= MIN_MATCH) {
  79350. INSERT_STRING(s, s->strstart, hash_head);
  79351. }
  79352. /* Find the longest match, discarding those <= prev_length.
  79353. * At this point we have always match_length < MIN_MATCH
  79354. */
  79355. if (hash_head != NIL && s->strstart - hash_head <= MAX_DIST(s)) {
  79356. /* To simplify the code, we prevent matches with the string
  79357. * of window index 0 (in particular we have to avoid a match
  79358. * of the string with itself at the start of the input file).
  79359. */
  79360. #ifdef FASTEST
  79361. if ((s->strategy != Z_HUFFMAN_ONLY && s->strategy != Z_RLE) ||
  79362. (s->strategy == Z_RLE && s->strstart - hash_head == 1)) {
  79363. s->match_length = longest_match_fast (s, hash_head);
  79364. }
  79365. #else
  79366. if (s->strategy != Z_HUFFMAN_ONLY && s->strategy != Z_RLE) {
  79367. s->match_length = longest_match (s, hash_head);
  79368. } else if (s->strategy == Z_RLE && s->strstart - hash_head == 1) {
  79369. s->match_length = longest_match_fast (s, hash_head);
  79370. }
  79371. #endif
  79372. /* longest_match() or longest_match_fast() sets match_start */
  79373. }
  79374. if (s->match_length >= MIN_MATCH) {
  79375. check_match(s, s->strstart, s->match_start, s->match_length);
  79376. _tr_tally_dist(s, s->strstart - s->match_start,
  79377. s->match_length - MIN_MATCH, bflush);
  79378. s->lookahead -= s->match_length;
  79379. /* Insert new strings in the hash table only if the match length
  79380. * is not too large. This saves time but degrades compression.
  79381. */
  79382. #ifndef FASTEST
  79383. if (s->match_length <= s->max_insert_length &&
  79384. s->lookahead >= MIN_MATCH) {
  79385. s->match_length--; /* string at strstart already in table */
  79386. do {
  79387. s->strstart++;
  79388. INSERT_STRING(s, s->strstart, hash_head);
  79389. /* strstart never exceeds WSIZE-MAX_MATCH, so there are
  79390. * always MIN_MATCH bytes ahead.
  79391. */
  79392. } while (--s->match_length != 0);
  79393. s->strstart++;
  79394. } else
  79395. #endif
  79396. {
  79397. s->strstart += s->match_length;
  79398. s->match_length = 0;
  79399. s->ins_h = s->window[s->strstart];
  79400. UPDATE_HASH(s, s->ins_h, s->window[s->strstart+1]);
  79401. #if MIN_MATCH != 3
  79402. Call UPDATE_HASH() MIN_MATCH-3 more times
  79403. #endif
  79404. /* If lookahead < MIN_MATCH, ins_h is garbage, but it does not
  79405. * matter since it will be recomputed at next deflate call.
  79406. */
  79407. }
  79408. } else {
  79409. /* No match, output a literal byte */
  79410. Tracevv((stderr,"%c", s->window[s->strstart]));
  79411. _tr_tally_lit (s, s->window[s->strstart], bflush);
  79412. s->lookahead--;
  79413. s->strstart++;
  79414. }
  79415. if (bflush) FLUSH_BLOCK(s, 0);
  79416. }
  79417. FLUSH_BLOCK(s, flush == Z_FINISH);
  79418. return flush == Z_FINISH ? finish_done : block_done;
  79419. }
  79420. #ifndef FASTEST
  79421. /* ===========================================================================
  79422. * Same as above, but achieves better compression. We use a lazy
  79423. * evaluation for matches: a match is finally adopted only if there is
  79424. * no better match at the next window position.
  79425. */
  79426. local block_state deflate_slow(deflate_state *s, int flush)
  79427. {
  79428. IPos hash_head = NIL; /* head of hash chain */
  79429. int bflush; /* set if current block must be flushed */
  79430. /* Process the input block. */
  79431. for (;;) {
  79432. /* Make sure that we always have enough lookahead, except
  79433. * at the end of the input file. We need MAX_MATCH bytes
  79434. * for the next match, plus MIN_MATCH bytes to insert the
  79435. * string following the next match.
  79436. */
  79437. if (s->lookahead < MIN_LOOKAHEAD) {
  79438. fill_window(s);
  79439. if (s->lookahead < MIN_LOOKAHEAD && flush == Z_NO_FLUSH) {
  79440. return need_more;
  79441. }
  79442. if (s->lookahead == 0) break; /* flush the current block */
  79443. }
  79444. /* Insert the string window[strstart .. strstart+2] in the
  79445. * dictionary, and set hash_head to the head of the hash chain:
  79446. */
  79447. if (s->lookahead >= MIN_MATCH) {
  79448. INSERT_STRING(s, s->strstart, hash_head);
  79449. }
  79450. /* Find the longest match, discarding those <= prev_length.
  79451. */
  79452. s->prev_length = s->match_length, s->prev_match = s->match_start;
  79453. s->match_length = MIN_MATCH-1;
  79454. if (hash_head != NIL && s->prev_length < s->max_lazy_match &&
  79455. s->strstart - hash_head <= MAX_DIST(s)) {
  79456. /* To simplify the code, we prevent matches with the string
  79457. * of window index 0 (in particular we have to avoid a match
  79458. * of the string with itself at the start of the input file).
  79459. */
  79460. if (s->strategy != Z_HUFFMAN_ONLY && s->strategy != Z_RLE) {
  79461. s->match_length = longest_match (s, hash_head);
  79462. } else if (s->strategy == Z_RLE && s->strstart - hash_head == 1) {
  79463. s->match_length = longest_match_fast (s, hash_head);
  79464. }
  79465. /* longest_match() or longest_match_fast() sets match_start */
  79466. if (s->match_length <= 5 && (s->strategy == Z_FILTERED
  79467. #if TOO_FAR <= 32767
  79468. || (s->match_length == MIN_MATCH &&
  79469. s->strstart - s->match_start > TOO_FAR)
  79470. #endif
  79471. )) {
  79472. /* If prev_match is also MIN_MATCH, match_start is garbage
  79473. * but we will ignore the current match anyway.
  79474. */
  79475. s->match_length = MIN_MATCH-1;
  79476. }
  79477. }
  79478. /* If there was a match at the previous step and the current
  79479. * match is not better, output the previous match:
  79480. */
  79481. if (s->prev_length >= MIN_MATCH && s->match_length <= s->prev_length) {
  79482. uInt max_insert = s->strstart + s->lookahead - MIN_MATCH;
  79483. /* Do not insert strings in hash table beyond this. */
  79484. check_match(s, s->strstart-1, s->prev_match, s->prev_length);
  79485. _tr_tally_dist(s, s->strstart -1 - s->prev_match,
  79486. s->prev_length - MIN_MATCH, bflush);
  79487. /* Insert in hash table all strings up to the end of the match.
  79488. * strstart-1 and strstart are already inserted. If there is not
  79489. * enough lookahead, the last two strings are not inserted in
  79490. * the hash table.
  79491. */
  79492. s->lookahead -= s->prev_length-1;
  79493. s->prev_length -= 2;
  79494. do {
  79495. if (++s->strstart <= max_insert) {
  79496. INSERT_STRING(s, s->strstart, hash_head);
  79497. }
  79498. } while (--s->prev_length != 0);
  79499. s->match_available = 0;
  79500. s->match_length = MIN_MATCH-1;
  79501. s->strstart++;
  79502. if (bflush) FLUSH_BLOCK(s, 0);
  79503. } else if (s->match_available) {
  79504. /* If there was no match at the previous position, output a
  79505. * single literal. If there was a match but the current match
  79506. * is longer, truncate the previous match to a single literal.
  79507. */
  79508. Tracevv((stderr,"%c", s->window[s->strstart-1]));
  79509. _tr_tally_lit(s, s->window[s->strstart-1], bflush);
  79510. if (bflush) {
  79511. FLUSH_BLOCK_ONLY(s, 0);
  79512. }
  79513. s->strstart++;
  79514. s->lookahead--;
  79515. if (s->strm->avail_out == 0) return need_more;
  79516. } else {
  79517. /* There is no previous match to compare with, wait for
  79518. * the next step to decide.
  79519. */
  79520. s->match_available = 1;
  79521. s->strstart++;
  79522. s->lookahead--;
  79523. }
  79524. }
  79525. Assert (flush != Z_NO_FLUSH, "no flush?");
  79526. if (s->match_available) {
  79527. Tracevv((stderr,"%c", s->window[s->strstart-1]));
  79528. _tr_tally_lit(s, s->window[s->strstart-1], bflush);
  79529. s->match_available = 0;
  79530. }
  79531. FLUSH_BLOCK(s, flush == Z_FINISH);
  79532. return flush == Z_FINISH ? finish_done : block_done;
  79533. }
  79534. #endif /* FASTEST */
  79535. #if 0
  79536. /* ===========================================================================
  79537. * For Z_RLE, simply look for runs of bytes, generate matches only of distance
  79538. * one. Do not maintain a hash table. (It will be regenerated if this run of
  79539. * deflate switches away from Z_RLE.)
  79540. */
  79541. local block_state deflate_rle(s, flush)
  79542. deflate_state *s;
  79543. int flush;
  79544. {
  79545. int bflush; /* set if current block must be flushed */
  79546. uInt run; /* length of run */
  79547. uInt max; /* maximum length of run */
  79548. uInt prev; /* byte at distance one to match */
  79549. Bytef *scan; /* scan for end of run */
  79550. for (;;) {
  79551. /* Make sure that we always have enough lookahead, except
  79552. * at the end of the input file. We need MAX_MATCH bytes
  79553. * for the longest encodable run.
  79554. */
  79555. if (s->lookahead < MAX_MATCH) {
  79556. fill_window(s);
  79557. if (s->lookahead < MAX_MATCH && flush == Z_NO_FLUSH) {
  79558. return need_more;
  79559. }
  79560. if (s->lookahead == 0) break; /* flush the current block */
  79561. }
  79562. /* See how many times the previous byte repeats */
  79563. run = 0;
  79564. if (s->strstart > 0) { /* if there is a previous byte, that is */
  79565. max = s->lookahead < MAX_MATCH ? s->lookahead : MAX_MATCH;
  79566. scan = s->window + s->strstart - 1;
  79567. prev = *scan++;
  79568. do {
  79569. if (*scan++ != prev)
  79570. break;
  79571. } while (++run < max);
  79572. }
  79573. /* Emit match if have run of MIN_MATCH or longer, else emit literal */
  79574. if (run >= MIN_MATCH) {
  79575. check_match(s, s->strstart, s->strstart - 1, run);
  79576. _tr_tally_dist(s, 1, run - MIN_MATCH, bflush);
  79577. s->lookahead -= run;
  79578. s->strstart += run;
  79579. } else {
  79580. /* No match, output a literal byte */
  79581. Tracevv((stderr,"%c", s->window[s->strstart]));
  79582. _tr_tally_lit (s, s->window[s->strstart], bflush);
  79583. s->lookahead--;
  79584. s->strstart++;
  79585. }
  79586. if (bflush) FLUSH_BLOCK(s, 0);
  79587. }
  79588. FLUSH_BLOCK(s, flush == Z_FINISH);
  79589. return flush == Z_FINISH ? finish_done : block_done;
  79590. }
  79591. #endif
  79592. /*** End of inlined file: deflate.c ***/
  79593. /*** Start of inlined file: inffast.c ***/
  79594. /*** Start of inlined file: inftrees.h ***/
  79595. /* WARNING: this file should *not* be used by applications. It is
  79596. part of the implementation of the compression library and is
  79597. subject to change. Applications should only use zlib.h.
  79598. */
  79599. #ifndef _INFTREES_H_
  79600. #define _INFTREES_H_
  79601. /* Structure for decoding tables. Each entry provides either the
  79602. information needed to do the operation requested by the code that
  79603. indexed that table entry, or it provides a pointer to another
  79604. table that indexes more bits of the code. op indicates whether
  79605. the entry is a pointer to another table, a literal, a length or
  79606. distance, an end-of-block, or an invalid code. For a table
  79607. pointer, the low four bits of op is the number of index bits of
  79608. that table. For a length or distance, the low four bits of op
  79609. is the number of extra bits to get after the code. bits is
  79610. the number of bits in this code or part of the code to drop off
  79611. of the bit buffer. val is the actual byte to output in the case
  79612. of a literal, the base length or distance, or the offset from
  79613. the current table to the next table. Each entry is four bytes. */
  79614. typedef struct {
  79615. unsigned char op; /* operation, extra bits, table bits */
  79616. unsigned char bits; /* bits in this part of the code */
  79617. unsigned short val; /* offset in table or code value */
  79618. } code;
  79619. /* op values as set by inflate_table():
  79620. 00000000 - literal
  79621. 0000tttt - table link, tttt != 0 is the number of table index bits
  79622. 0001eeee - length or distance, eeee is the number of extra bits
  79623. 01100000 - end of block
  79624. 01000000 - invalid code
  79625. */
  79626. /* Maximum size of dynamic tree. The maximum found in a long but non-
  79627. exhaustive search was 1444 code structures (852 for length/literals
  79628. and 592 for distances, the latter actually the result of an
  79629. exhaustive search). The true maximum is not known, but the value
  79630. below is more than safe. */
  79631. #define ENOUGH 2048
  79632. #define MAXD 592
  79633. /* Type of code to build for inftable() */
  79634. typedef enum {
  79635. CODES,
  79636. LENS,
  79637. DISTS
  79638. } codetype;
  79639. extern int inflate_table OF((codetype type, unsigned short FAR *lens,
  79640. unsigned codes, code FAR * FAR *table,
  79641. unsigned FAR *bits, unsigned short FAR *work));
  79642. #endif
  79643. /*** End of inlined file: inftrees.h ***/
  79644. /*** Start of inlined file: inflate.h ***/
  79645. /* WARNING: this file should *not* be used by applications. It is
  79646. part of the implementation of the compression library and is
  79647. subject to change. Applications should only use zlib.h.
  79648. */
  79649. #ifndef _INFLATE_H_
  79650. #define _INFLATE_H_
  79651. /* define NO_GZIP when compiling if you want to disable gzip header and
  79652. trailer decoding by inflate(). NO_GZIP would be used to avoid linking in
  79653. the crc code when it is not needed. For shared libraries, gzip decoding
  79654. should be left enabled. */
  79655. #ifndef NO_GZIP
  79656. # define GUNZIP
  79657. #endif
  79658. /* Possible inflate modes between inflate() calls */
  79659. typedef enum {
  79660. HEAD, /* i: waiting for magic header */
  79661. FLAGS, /* i: waiting for method and flags (gzip) */
  79662. TIME, /* i: waiting for modification time (gzip) */
  79663. OS, /* i: waiting for extra flags and operating system (gzip) */
  79664. EXLEN, /* i: waiting for extra length (gzip) */
  79665. EXTRA, /* i: waiting for extra bytes (gzip) */
  79666. NAME, /* i: waiting for end of file name (gzip) */
  79667. COMMENT, /* i: waiting for end of comment (gzip) */
  79668. HCRC, /* i: waiting for header crc (gzip) */
  79669. DICTID, /* i: waiting for dictionary check value */
  79670. DICT, /* waiting for inflateSetDictionary() call */
  79671. TYPE, /* i: waiting for type bits, including last-flag bit */
  79672. TYPEDO, /* i: same, but skip check to exit inflate on new block */
  79673. STORED, /* i: waiting for stored size (length and complement) */
  79674. COPY, /* i/o: waiting for input or output to copy stored block */
  79675. TABLE, /* i: waiting for dynamic block table lengths */
  79676. LENLENS, /* i: waiting for code length code lengths */
  79677. CODELENS, /* i: waiting for length/lit and distance code lengths */
  79678. LEN, /* i: waiting for length/lit code */
  79679. LENEXT, /* i: waiting for length extra bits */
  79680. DIST, /* i: waiting for distance code */
  79681. DISTEXT, /* i: waiting for distance extra bits */
  79682. MATCH, /* o: waiting for output space to copy string */
  79683. LIT, /* o: waiting for output space to write literal */
  79684. CHECK, /* i: waiting for 32-bit check value */
  79685. LENGTH, /* i: waiting for 32-bit length (gzip) */
  79686. DONE, /* finished check, done -- remain here until reset */
  79687. BAD, /* got a data error -- remain here until reset */
  79688. MEM, /* got an inflate() memory error -- remain here until reset */
  79689. SYNC /* looking for synchronization bytes to restart inflate() */
  79690. } inflate_mode;
  79691. /*
  79692. State transitions between above modes -
  79693. (most modes can go to the BAD or MEM mode -- not shown for clarity)
  79694. Process header:
  79695. HEAD -> (gzip) or (zlib)
  79696. (gzip) -> FLAGS -> TIME -> OS -> EXLEN -> EXTRA -> NAME
  79697. NAME -> COMMENT -> HCRC -> TYPE
  79698. (zlib) -> DICTID or TYPE
  79699. DICTID -> DICT -> TYPE
  79700. Read deflate blocks:
  79701. TYPE -> STORED or TABLE or LEN or CHECK
  79702. STORED -> COPY -> TYPE
  79703. TABLE -> LENLENS -> CODELENS -> LEN
  79704. Read deflate codes:
  79705. LEN -> LENEXT or LIT or TYPE
  79706. LENEXT -> DIST -> DISTEXT -> MATCH -> LEN
  79707. LIT -> LEN
  79708. Process trailer:
  79709. CHECK -> LENGTH -> DONE
  79710. */
  79711. /* state maintained between inflate() calls. Approximately 7K bytes. */
  79712. struct inflate_state {
  79713. inflate_mode mode; /* current inflate mode */
  79714. int last; /* true if processing last block */
  79715. int wrap; /* bit 0 true for zlib, bit 1 true for gzip */
  79716. int havedict; /* true if dictionary provided */
  79717. int flags; /* gzip header method and flags (0 if zlib) */
  79718. unsigned dmax; /* zlib header max distance (INFLATE_STRICT) */
  79719. unsigned long check; /* protected copy of check value */
  79720. unsigned long total; /* protected copy of output count */
  79721. gz_headerp head; /* where to save gzip header information */
  79722. /* sliding window */
  79723. unsigned wbits; /* log base 2 of requested window size */
  79724. unsigned wsize; /* window size or zero if not using window */
  79725. unsigned whave; /* valid bytes in the window */
  79726. unsigned write; /* window write index */
  79727. unsigned char FAR *window; /* allocated sliding window, if needed */
  79728. /* bit accumulator */
  79729. unsigned long hold; /* input bit accumulator */
  79730. unsigned bits; /* number of bits in "in" */
  79731. /* for string and stored block copying */
  79732. unsigned length; /* literal or length of data to copy */
  79733. unsigned offset; /* distance back to copy string from */
  79734. /* for table and code decoding */
  79735. unsigned extra; /* extra bits needed */
  79736. /* fixed and dynamic code tables */
  79737. code const FAR *lencode; /* starting table for length/literal codes */
  79738. code const FAR *distcode; /* starting table for distance codes */
  79739. unsigned lenbits; /* index bits for lencode */
  79740. unsigned distbits; /* index bits for distcode */
  79741. /* dynamic table building */
  79742. unsigned ncode; /* number of code length code lengths */
  79743. unsigned nlen; /* number of length code lengths */
  79744. unsigned ndist; /* number of distance code lengths */
  79745. unsigned have; /* number of code lengths in lens[] */
  79746. code FAR *next; /* next available space in codes[] */
  79747. unsigned short lens[320]; /* temporary storage for code lengths */
  79748. unsigned short work[288]; /* work area for code table building */
  79749. code codes[ENOUGH]; /* space for code tables */
  79750. };
  79751. #endif
  79752. /*** End of inlined file: inflate.h ***/
  79753. /*** Start of inlined file: inffast.h ***/
  79754. /* WARNING: this file should *not* be used by applications. It is
  79755. part of the implementation of the compression library and is
  79756. subject to change. Applications should only use zlib.h.
  79757. */
  79758. void inflate_fast OF((z_streamp strm, unsigned start));
  79759. /*** End of inlined file: inffast.h ***/
  79760. #ifndef ASMINF
  79761. /* Allow machine dependent optimization for post-increment or pre-increment.
  79762. Based on testing to date,
  79763. Pre-increment preferred for:
  79764. - PowerPC G3 (Adler)
  79765. - MIPS R5000 (Randers-Pehrson)
  79766. Post-increment preferred for:
  79767. - none
  79768. No measurable difference:
  79769. - Pentium III (Anderson)
  79770. - M68060 (Nikl)
  79771. */
  79772. #ifdef POSTINC
  79773. # define OFF 0
  79774. # define PUP(a) *(a)++
  79775. #else
  79776. # define OFF 1
  79777. # define PUP(a) *++(a)
  79778. #endif
  79779. /*
  79780. Decode literal, length, and distance codes and write out the resulting
  79781. literal and match bytes until either not enough input or output is
  79782. available, an end-of-block is encountered, or a data error is encountered.
  79783. When large enough input and output buffers are supplied to inflate(), for
  79784. example, a 16K input buffer and a 64K output buffer, more than 95% of the
  79785. inflate execution time is spent in this routine.
  79786. Entry assumptions:
  79787. state->mode == LEN
  79788. strm->avail_in >= 6
  79789. strm->avail_out >= 258
  79790. start >= strm->avail_out
  79791. state->bits < 8
  79792. On return, state->mode is one of:
  79793. LEN -- ran out of enough output space or enough available input
  79794. TYPE -- reached end of block code, inflate() to interpret next block
  79795. BAD -- error in block data
  79796. Notes:
  79797. - The maximum input bits used by a length/distance pair is 15 bits for the
  79798. length code, 5 bits for the length extra, 15 bits for the distance code,
  79799. and 13 bits for the distance extra. This totals 48 bits, or six bytes.
  79800. Therefore if strm->avail_in >= 6, then there is enough input to avoid
  79801. checking for available input while decoding.
  79802. - The maximum bytes that a single length/distance pair can output is 258
  79803. bytes, which is the maximum length that can be coded. inflate_fast()
  79804. requires strm->avail_out >= 258 for each loop to avoid checking for
  79805. output space.
  79806. */
  79807. void inflate_fast (z_streamp strm, unsigned start)
  79808. {
  79809. struct inflate_state FAR *state;
  79810. unsigned char FAR *in; /* local strm->next_in */
  79811. unsigned char FAR *last; /* while in < last, enough input available */
  79812. unsigned char FAR *out; /* local strm->next_out */
  79813. unsigned char FAR *beg; /* inflate()'s initial strm->next_out */
  79814. unsigned char FAR *end; /* while out < end, enough space available */
  79815. #ifdef INFLATE_STRICT
  79816. unsigned dmax; /* maximum distance from zlib header */
  79817. #endif
  79818. unsigned wsize; /* window size or zero if not using window */
  79819. unsigned whave; /* valid bytes in the window */
  79820. unsigned write; /* window write index */
  79821. unsigned char FAR *window; /* allocated sliding window, if wsize != 0 */
  79822. unsigned long hold; /* local strm->hold */
  79823. unsigned bits; /* local strm->bits */
  79824. code const FAR *lcode; /* local strm->lencode */
  79825. code const FAR *dcode; /* local strm->distcode */
  79826. unsigned lmask; /* mask for first level of length codes */
  79827. unsigned dmask; /* mask for first level of distance codes */
  79828. code thisx; /* retrieved table entry */
  79829. unsigned op; /* code bits, operation, extra bits, or */
  79830. /* window position, window bytes to copy */
  79831. unsigned len; /* match length, unused bytes */
  79832. unsigned dist; /* match distance */
  79833. unsigned char FAR *from; /* where to copy match from */
  79834. /* copy state to local variables */
  79835. state = (struct inflate_state FAR *)strm->state;
  79836. in = strm->next_in - OFF;
  79837. last = in + (strm->avail_in - 5);
  79838. out = strm->next_out - OFF;
  79839. beg = out - (start - strm->avail_out);
  79840. end = out + (strm->avail_out - 257);
  79841. #ifdef INFLATE_STRICT
  79842. dmax = state->dmax;
  79843. #endif
  79844. wsize = state->wsize;
  79845. whave = state->whave;
  79846. write = state->write;
  79847. window = state->window;
  79848. hold = state->hold;
  79849. bits = state->bits;
  79850. lcode = state->lencode;
  79851. dcode = state->distcode;
  79852. lmask = (1U << state->lenbits) - 1;
  79853. dmask = (1U << state->distbits) - 1;
  79854. /* decode literals and length/distances until end-of-block or not enough
  79855. input data or output space */
  79856. do {
  79857. if (bits < 15) {
  79858. hold += (unsigned long)(PUP(in)) << bits;
  79859. bits += 8;
  79860. hold += (unsigned long)(PUP(in)) << bits;
  79861. bits += 8;
  79862. }
  79863. thisx = lcode[hold & lmask];
  79864. dolen:
  79865. op = (unsigned)(thisx.bits);
  79866. hold >>= op;
  79867. bits -= op;
  79868. op = (unsigned)(thisx.op);
  79869. if (op == 0) { /* literal */
  79870. Tracevv((stderr, thisx.val >= 0x20 && thisx.val < 0x7f ?
  79871. "inflate: literal '%c'\n" :
  79872. "inflate: literal 0x%02x\n", thisx.val));
  79873. PUP(out) = (unsigned char)(thisx.val);
  79874. }
  79875. else if (op & 16) { /* length base */
  79876. len = (unsigned)(thisx.val);
  79877. op &= 15; /* number of extra bits */
  79878. if (op) {
  79879. if (bits < op) {
  79880. hold += (unsigned long)(PUP(in)) << bits;
  79881. bits += 8;
  79882. }
  79883. len += (unsigned)hold & ((1U << op) - 1);
  79884. hold >>= op;
  79885. bits -= op;
  79886. }
  79887. Tracevv((stderr, "inflate: length %u\n", len));
  79888. if (bits < 15) {
  79889. hold += (unsigned long)(PUP(in)) << bits;
  79890. bits += 8;
  79891. hold += (unsigned long)(PUP(in)) << bits;
  79892. bits += 8;
  79893. }
  79894. thisx = dcode[hold & dmask];
  79895. dodist:
  79896. op = (unsigned)(thisx.bits);
  79897. hold >>= op;
  79898. bits -= op;
  79899. op = (unsigned)(thisx.op);
  79900. if (op & 16) { /* distance base */
  79901. dist = (unsigned)(thisx.val);
  79902. op &= 15; /* number of extra bits */
  79903. if (bits < op) {
  79904. hold += (unsigned long)(PUP(in)) << bits;
  79905. bits += 8;
  79906. if (bits < op) {
  79907. hold += (unsigned long)(PUP(in)) << bits;
  79908. bits += 8;
  79909. }
  79910. }
  79911. dist += (unsigned)hold & ((1U << op) - 1);
  79912. #ifdef INFLATE_STRICT
  79913. if (dist > dmax) {
  79914. strm->msg = (char *)"invalid distance too far back";
  79915. state->mode = BAD;
  79916. break;
  79917. }
  79918. #endif
  79919. hold >>= op;
  79920. bits -= op;
  79921. Tracevv((stderr, "inflate: distance %u\n", dist));
  79922. op = (unsigned)(out - beg); /* max distance in output */
  79923. if (dist > op) { /* see if copy from window */
  79924. op = dist - op; /* distance back in window */
  79925. if (op > whave) {
  79926. strm->msg = (char *)"invalid distance too far back";
  79927. state->mode = BAD;
  79928. break;
  79929. }
  79930. from = window - OFF;
  79931. if (write == 0) { /* very common case */
  79932. from += wsize - op;
  79933. if (op < len) { /* some from window */
  79934. len -= op;
  79935. do {
  79936. PUP(out) = PUP(from);
  79937. } while (--op);
  79938. from = out - dist; /* rest from output */
  79939. }
  79940. }
  79941. else if (write < op) { /* wrap around window */
  79942. from += wsize + write - op;
  79943. op -= write;
  79944. if (op < len) { /* some from end of window */
  79945. len -= op;
  79946. do {
  79947. PUP(out) = PUP(from);
  79948. } while (--op);
  79949. from = window - OFF;
  79950. if (write < len) { /* some from start of window */
  79951. op = write;
  79952. len -= op;
  79953. do {
  79954. PUP(out) = PUP(from);
  79955. } while (--op);
  79956. from = out - dist; /* rest from output */
  79957. }
  79958. }
  79959. }
  79960. else { /* contiguous in window */
  79961. from += write - op;
  79962. if (op < len) { /* some from window */
  79963. len -= op;
  79964. do {
  79965. PUP(out) = PUP(from);
  79966. } while (--op);
  79967. from = out - dist; /* rest from output */
  79968. }
  79969. }
  79970. while (len > 2) {
  79971. PUP(out) = PUP(from);
  79972. PUP(out) = PUP(from);
  79973. PUP(out) = PUP(from);
  79974. len -= 3;
  79975. }
  79976. if (len) {
  79977. PUP(out) = PUP(from);
  79978. if (len > 1)
  79979. PUP(out) = PUP(from);
  79980. }
  79981. }
  79982. else {
  79983. from = out - dist; /* copy direct from output */
  79984. do { /* minimum length is three */
  79985. PUP(out) = PUP(from);
  79986. PUP(out) = PUP(from);
  79987. PUP(out) = PUP(from);
  79988. len -= 3;
  79989. } while (len > 2);
  79990. if (len) {
  79991. PUP(out) = PUP(from);
  79992. if (len > 1)
  79993. PUP(out) = PUP(from);
  79994. }
  79995. }
  79996. }
  79997. else if ((op & 64) == 0) { /* 2nd level distance code */
  79998. thisx = dcode[thisx.val + (hold & ((1U << op) - 1))];
  79999. goto dodist;
  80000. }
  80001. else {
  80002. strm->msg = (char *)"invalid distance code";
  80003. state->mode = BAD;
  80004. break;
  80005. }
  80006. }
  80007. else if ((op & 64) == 0) { /* 2nd level length code */
  80008. thisx = lcode[thisx.val + (hold & ((1U << op) - 1))];
  80009. goto dolen;
  80010. }
  80011. else if (op & 32) { /* end-of-block */
  80012. Tracevv((stderr, "inflate: end of block\n"));
  80013. state->mode = TYPE;
  80014. break;
  80015. }
  80016. else {
  80017. strm->msg = (char *)"invalid literal/length code";
  80018. state->mode = BAD;
  80019. break;
  80020. }
  80021. } while (in < last && out < end);
  80022. /* return unused bytes (on entry, bits < 8, so in won't go too far back) */
  80023. len = bits >> 3;
  80024. in -= len;
  80025. bits -= len << 3;
  80026. hold &= (1U << bits) - 1;
  80027. /* update state and return */
  80028. strm->next_in = in + OFF;
  80029. strm->next_out = out + OFF;
  80030. strm->avail_in = (unsigned)(in < last ? 5 + (last - in) : 5 - (in - last));
  80031. strm->avail_out = (unsigned)(out < end ?
  80032. 257 + (end - out) : 257 - (out - end));
  80033. state->hold = hold;
  80034. state->bits = bits;
  80035. return;
  80036. }
  80037. /*
  80038. inflate_fast() speedups that turned out slower (on a PowerPC G3 750CXe):
  80039. - Using bit fields for code structure
  80040. - Different op definition to avoid & for extra bits (do & for table bits)
  80041. - Three separate decoding do-loops for direct, window, and write == 0
  80042. - Special case for distance > 1 copies to do overlapped load and store copy
  80043. - Explicit branch predictions (based on measured branch probabilities)
  80044. - Deferring match copy and interspersed it with decoding subsequent codes
  80045. - Swapping literal/length else
  80046. - Swapping window/direct else
  80047. - Larger unrolled copy loops (three is about right)
  80048. - Moving len -= 3 statement into middle of loop
  80049. */
  80050. #endif /* !ASMINF */
  80051. /*** End of inlined file: inffast.c ***/
  80052. #undef PULLBYTE
  80053. #undef LOAD
  80054. #undef RESTORE
  80055. #undef INITBITS
  80056. #undef NEEDBITS
  80057. #undef DROPBITS
  80058. #undef BYTEBITS
  80059. /*** Start of inlined file: inflate.c ***/
  80060. /*
  80061. * Change history:
  80062. *
  80063. * 1.2.beta0 24 Nov 2002
  80064. * - First version -- complete rewrite of inflate to simplify code, avoid
  80065. * creation of window when not needed, minimize use of window when it is
  80066. * needed, make inffast.c even faster, implement gzip decoding, and to
  80067. * improve code readability and style over the previous zlib inflate code
  80068. *
  80069. * 1.2.beta1 25 Nov 2002
  80070. * - Use pointers for available input and output checking in inffast.c
  80071. * - Remove input and output counters in inffast.c
  80072. * - Change inffast.c entry and loop from avail_in >= 7 to >= 6
  80073. * - Remove unnecessary second byte pull from length extra in inffast.c
  80074. * - Unroll direct copy to three copies per loop in inffast.c
  80075. *
  80076. * 1.2.beta2 4 Dec 2002
  80077. * - Change external routine names to reduce potential conflicts
  80078. * - Correct filename to inffixed.h for fixed tables in inflate.c
  80079. * - Make hbuf[] unsigned char to match parameter type in inflate.c
  80080. * - Change strm->next_out[-state->offset] to *(strm->next_out - state->offset)
  80081. * to avoid negation problem on Alphas (64 bit) in inflate.c
  80082. *
  80083. * 1.2.beta3 22 Dec 2002
  80084. * - Add comments on state->bits assertion in inffast.c
  80085. * - Add comments on op field in inftrees.h
  80086. * - Fix bug in reuse of allocated window after inflateReset()
  80087. * - Remove bit fields--back to byte structure for speed
  80088. * - Remove distance extra == 0 check in inflate_fast()--only helps for lengths
  80089. * - Change post-increments to pre-increments in inflate_fast(), PPC biased?
  80090. * - Add compile time option, POSTINC, to use post-increments instead (Intel?)
  80091. * - Make MATCH copy in inflate() much faster for when inflate_fast() not used
  80092. * - Use local copies of stream next and avail values, as well as local bit
  80093. * buffer and bit count in inflate()--for speed when inflate_fast() not used
  80094. *
  80095. * 1.2.beta4 1 Jan 2003
  80096. * - Split ptr - 257 statements in inflate_table() to avoid compiler warnings
  80097. * - Move a comment on output buffer sizes from inffast.c to inflate.c
  80098. * - Add comments in inffast.c to introduce the inflate_fast() routine
  80099. * - Rearrange window copies in inflate_fast() for speed and simplification
  80100. * - Unroll last copy for window match in inflate_fast()
  80101. * - Use local copies of window variables in inflate_fast() for speed
  80102. * - Pull out common write == 0 case for speed in inflate_fast()
  80103. * - Make op and len in inflate_fast() unsigned for consistency
  80104. * - Add FAR to lcode and dcode declarations in inflate_fast()
  80105. * - Simplified bad distance check in inflate_fast()
  80106. * - Added inflateBackInit(), inflateBack(), and inflateBackEnd() in new
  80107. * source file infback.c to provide a call-back interface to inflate for
  80108. * programs like gzip and unzip -- uses window as output buffer to avoid
  80109. * window copying
  80110. *
  80111. * 1.2.beta5 1 Jan 2003
  80112. * - Improved inflateBack() interface to allow the caller to provide initial
  80113. * input in strm.
  80114. * - Fixed stored blocks bug in inflateBack()
  80115. *
  80116. * 1.2.beta6 4 Jan 2003
  80117. * - Added comments in inffast.c on effectiveness of POSTINC
  80118. * - Typecasting all around to reduce compiler warnings
  80119. * - Changed loops from while (1) or do {} while (1) to for (;;), again to
  80120. * make compilers happy
  80121. * - Changed type of window in inflateBackInit() to unsigned char *
  80122. *
  80123. * 1.2.beta7 27 Jan 2003
  80124. * - Changed many types to unsigned or unsigned short to avoid warnings
  80125. * - Added inflateCopy() function
  80126. *
  80127. * 1.2.0 9 Mar 2003
  80128. * - Changed inflateBack() interface to provide separate opaque descriptors
  80129. * for the in() and out() functions
  80130. * - Changed inflateBack() argument and in_func typedef to swap the length
  80131. * and buffer address return values for the input function
  80132. * - Check next_in and next_out for Z_NULL on entry to inflate()
  80133. *
  80134. * The history for versions after 1.2.0 are in ChangeLog in zlib distribution.
  80135. */
  80136. /*** Start of inlined file: inffast.h ***/
  80137. /* WARNING: this file should *not* be used by applications. It is
  80138. part of the implementation of the compression library and is
  80139. subject to change. Applications should only use zlib.h.
  80140. */
  80141. void inflate_fast OF((z_streamp strm, unsigned start));
  80142. /*** End of inlined file: inffast.h ***/
  80143. #ifdef MAKEFIXED
  80144. # ifndef BUILDFIXED
  80145. # define BUILDFIXED
  80146. # endif
  80147. #endif
  80148. /* function prototypes */
  80149. local void fixedtables OF((struct inflate_state FAR *state));
  80150. local int updatewindow OF((z_streamp strm, unsigned out));
  80151. #ifdef BUILDFIXED
  80152. void makefixed OF((void));
  80153. #endif
  80154. local unsigned syncsearch OF((unsigned FAR *have, unsigned char FAR *buf,
  80155. unsigned len));
  80156. int ZEXPORT inflateReset (z_streamp strm)
  80157. {
  80158. struct inflate_state FAR *state;
  80159. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  80160. state = (struct inflate_state FAR *)strm->state;
  80161. strm->total_in = strm->total_out = state->total = 0;
  80162. strm->msg = Z_NULL;
  80163. strm->adler = 1; /* to support ill-conceived Java test suite */
  80164. state->mode = HEAD;
  80165. state->last = 0;
  80166. state->havedict = 0;
  80167. state->dmax = 32768U;
  80168. state->head = Z_NULL;
  80169. state->wsize = 0;
  80170. state->whave = 0;
  80171. state->write = 0;
  80172. state->hold = 0;
  80173. state->bits = 0;
  80174. state->lencode = state->distcode = state->next = state->codes;
  80175. Tracev((stderr, "inflate: reset\n"));
  80176. return Z_OK;
  80177. }
  80178. int ZEXPORT inflatePrime (z_streamp strm, int bits, int value)
  80179. {
  80180. struct inflate_state FAR *state;
  80181. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  80182. state = (struct inflate_state FAR *)strm->state;
  80183. if (bits > 16 || state->bits + bits > 32) return Z_STREAM_ERROR;
  80184. value &= (1L << bits) - 1;
  80185. state->hold += value << state->bits;
  80186. state->bits += bits;
  80187. return Z_OK;
  80188. }
  80189. int ZEXPORT inflateInit2_(z_streamp strm, int windowBits, const char *version, int stream_size)
  80190. {
  80191. struct inflate_state FAR *state;
  80192. if (version == Z_NULL || version[0] != ZLIB_VERSION[0] ||
  80193. stream_size != (int)(sizeof(z_stream)))
  80194. return Z_VERSION_ERROR;
  80195. if (strm == Z_NULL) return Z_STREAM_ERROR;
  80196. strm->msg = Z_NULL; /* in case we return an error */
  80197. if (strm->zalloc == (alloc_func)0) {
  80198. strm->zalloc = zcalloc;
  80199. strm->opaque = (voidpf)0;
  80200. }
  80201. if (strm->zfree == (free_func)0) strm->zfree = zcfree;
  80202. state = (struct inflate_state FAR *)
  80203. ZALLOC(strm, 1, sizeof(struct inflate_state));
  80204. if (state == Z_NULL) return Z_MEM_ERROR;
  80205. Tracev((stderr, "inflate: allocated\n"));
  80206. strm->state = (struct internal_state FAR *)state;
  80207. if (windowBits < 0) {
  80208. state->wrap = 0;
  80209. windowBits = -windowBits;
  80210. }
  80211. else {
  80212. state->wrap = (windowBits >> 4) + 1;
  80213. #ifdef GUNZIP
  80214. if (windowBits < 48) windowBits &= 15;
  80215. #endif
  80216. }
  80217. if (windowBits < 8 || windowBits > 15) {
  80218. ZFREE(strm, state);
  80219. strm->state = Z_NULL;
  80220. return Z_STREAM_ERROR;
  80221. }
  80222. state->wbits = (unsigned)windowBits;
  80223. state->window = Z_NULL;
  80224. return inflateReset(strm);
  80225. }
  80226. int ZEXPORT inflateInit_ (z_streamp strm, const char *version, int stream_size)
  80227. {
  80228. return inflateInit2_(strm, DEF_WBITS, version, stream_size);
  80229. }
  80230. /*
  80231. Return state with length and distance decoding tables and index sizes set to
  80232. fixed code decoding. Normally this returns fixed tables from inffixed.h.
  80233. If BUILDFIXED is defined, then instead this routine builds the tables the
  80234. first time it's called, and returns those tables the first time and
  80235. thereafter. This reduces the size of the code by about 2K bytes, in
  80236. exchange for a little execution time. However, BUILDFIXED should not be
  80237. used for threaded applications, since the rewriting of the tables and virgin
  80238. may not be thread-safe.
  80239. */
  80240. local void fixedtables (struct inflate_state FAR *state)
  80241. {
  80242. #ifdef BUILDFIXED
  80243. static int virgin = 1;
  80244. static code *lenfix, *distfix;
  80245. static code fixed[544];
  80246. /* build fixed huffman tables if first call (may not be thread safe) */
  80247. if (virgin) {
  80248. unsigned sym, bits;
  80249. static code *next;
  80250. /* literal/length table */
  80251. sym = 0;
  80252. while (sym < 144) state->lens[sym++] = 8;
  80253. while (sym < 256) state->lens[sym++] = 9;
  80254. while (sym < 280) state->lens[sym++] = 7;
  80255. while (sym < 288) state->lens[sym++] = 8;
  80256. next = fixed;
  80257. lenfix = next;
  80258. bits = 9;
  80259. inflate_table(LENS, state->lens, 288, &(next), &(bits), state->work);
  80260. /* distance table */
  80261. sym = 0;
  80262. while (sym < 32) state->lens[sym++] = 5;
  80263. distfix = next;
  80264. bits = 5;
  80265. inflate_table(DISTS, state->lens, 32, &(next), &(bits), state->work);
  80266. /* do this just once */
  80267. virgin = 0;
  80268. }
  80269. #else /* !BUILDFIXED */
  80270. /*** Start of inlined file: inffixed.h ***/
  80271. /* WARNING: this file should *not* be used by applications. It
  80272. is part of the implementation of the compression library and
  80273. is subject to change. Applications should only use zlib.h.
  80274. */
  80275. static const code lenfix[512] = {
  80276. {96,7,0},{0,8,80},{0,8,16},{20,8,115},{18,7,31},{0,8,112},{0,8,48},
  80277. {0,9,192},{16,7,10},{0,8,96},{0,8,32},{0,9,160},{0,8,0},{0,8,128},
  80278. {0,8,64},{0,9,224},{16,7,6},{0,8,88},{0,8,24},{0,9,144},{19,7,59},
  80279. {0,8,120},{0,8,56},{0,9,208},{17,7,17},{0,8,104},{0,8,40},{0,9,176},
  80280. {0,8,8},{0,8,136},{0,8,72},{0,9,240},{16,7,4},{0,8,84},{0,8,20},
  80281. {21,8,227},{19,7,43},{0,8,116},{0,8,52},{0,9,200},{17,7,13},{0,8,100},
  80282. {0,8,36},{0,9,168},{0,8,4},{0,8,132},{0,8,68},{0,9,232},{16,7,8},
  80283. {0,8,92},{0,8,28},{0,9,152},{20,7,83},{0,8,124},{0,8,60},{0,9,216},
  80284. {18,7,23},{0,8,108},{0,8,44},{0,9,184},{0,8,12},{0,8,140},{0,8,76},
  80285. {0,9,248},{16,7,3},{0,8,82},{0,8,18},{21,8,163},{19,7,35},{0,8,114},
  80286. {0,8,50},{0,9,196},{17,7,11},{0,8,98},{0,8,34},{0,9,164},{0,8,2},
  80287. {0,8,130},{0,8,66},{0,9,228},{16,7,7},{0,8,90},{0,8,26},{0,9,148},
  80288. {20,7,67},{0,8,122},{0,8,58},{0,9,212},{18,7,19},{0,8,106},{0,8,42},
  80289. {0,9,180},{0,8,10},{0,8,138},{0,8,74},{0,9,244},{16,7,5},{0,8,86},
  80290. {0,8,22},{64,8,0},{19,7,51},{0,8,118},{0,8,54},{0,9,204},{17,7,15},
  80291. {0,8,102},{0,8,38},{0,9,172},{0,8,6},{0,8,134},{0,8,70},{0,9,236},
  80292. {16,7,9},{0,8,94},{0,8,30},{0,9,156},{20,7,99},{0,8,126},{0,8,62},
  80293. {0,9,220},{18,7,27},{0,8,110},{0,8,46},{0,9,188},{0,8,14},{0,8,142},
  80294. {0,8,78},{0,9,252},{96,7,0},{0,8,81},{0,8,17},{21,8,131},{18,7,31},
  80295. {0,8,113},{0,8,49},{0,9,194},{16,7,10},{0,8,97},{0,8,33},{0,9,162},
  80296. {0,8,1},{0,8,129},{0,8,65},{0,9,226},{16,7,6},{0,8,89},{0,8,25},
  80297. {0,9,146},{19,7,59},{0,8,121},{0,8,57},{0,9,210},{17,7,17},{0,8,105},
  80298. {0,8,41},{0,9,178},{0,8,9},{0,8,137},{0,8,73},{0,9,242},{16,7,4},
  80299. {0,8,85},{0,8,21},{16,8,258},{19,7,43},{0,8,117},{0,8,53},{0,9,202},
  80300. {17,7,13},{0,8,101},{0,8,37},{0,9,170},{0,8,5},{0,8,133},{0,8,69},
  80301. {0,9,234},{16,7,8},{0,8,93},{0,8,29},{0,9,154},{20,7,83},{0,8,125},
  80302. {0,8,61},{0,9,218},{18,7,23},{0,8,109},{0,8,45},{0,9,186},{0,8,13},
  80303. {0,8,141},{0,8,77},{0,9,250},{16,7,3},{0,8,83},{0,8,19},{21,8,195},
  80304. {19,7,35},{0,8,115},{0,8,51},{0,9,198},{17,7,11},{0,8,99},{0,8,35},
  80305. {0,9,166},{0,8,3},{0,8,131},{0,8,67},{0,9,230},{16,7,7},{0,8,91},
  80306. {0,8,27},{0,9,150},{20,7,67},{0,8,123},{0,8,59},{0,9,214},{18,7,19},
  80307. {0,8,107},{0,8,43},{0,9,182},{0,8,11},{0,8,139},{0,8,75},{0,9,246},
  80308. {16,7,5},{0,8,87},{0,8,23},{64,8,0},{19,7,51},{0,8,119},{0,8,55},
  80309. {0,9,206},{17,7,15},{0,8,103},{0,8,39},{0,9,174},{0,8,7},{0,8,135},
  80310. {0,8,71},{0,9,238},{16,7,9},{0,8,95},{0,8,31},{0,9,158},{20,7,99},
  80311. {0,8,127},{0,8,63},{0,9,222},{18,7,27},{0,8,111},{0,8,47},{0,9,190},
  80312. {0,8,15},{0,8,143},{0,8,79},{0,9,254},{96,7,0},{0,8,80},{0,8,16},
  80313. {20,8,115},{18,7,31},{0,8,112},{0,8,48},{0,9,193},{16,7,10},{0,8,96},
  80314. {0,8,32},{0,9,161},{0,8,0},{0,8,128},{0,8,64},{0,9,225},{16,7,6},
  80315. {0,8,88},{0,8,24},{0,9,145},{19,7,59},{0,8,120},{0,8,56},{0,9,209},
  80316. {17,7,17},{0,8,104},{0,8,40},{0,9,177},{0,8,8},{0,8,136},{0,8,72},
  80317. {0,9,241},{16,7,4},{0,8,84},{0,8,20},{21,8,227},{19,7,43},{0,8,116},
  80318. {0,8,52},{0,9,201},{17,7,13},{0,8,100},{0,8,36},{0,9,169},{0,8,4},
  80319. {0,8,132},{0,8,68},{0,9,233},{16,7,8},{0,8,92},{0,8,28},{0,9,153},
  80320. {20,7,83},{0,8,124},{0,8,60},{0,9,217},{18,7,23},{0,8,108},{0,8,44},
  80321. {0,9,185},{0,8,12},{0,8,140},{0,8,76},{0,9,249},{16,7,3},{0,8,82},
  80322. {0,8,18},{21,8,163},{19,7,35},{0,8,114},{0,8,50},{0,9,197},{17,7,11},
  80323. {0,8,98},{0,8,34},{0,9,165},{0,8,2},{0,8,130},{0,8,66},{0,9,229},
  80324. {16,7,7},{0,8,90},{0,8,26},{0,9,149},{20,7,67},{0,8,122},{0,8,58},
  80325. {0,9,213},{18,7,19},{0,8,106},{0,8,42},{0,9,181},{0,8,10},{0,8,138},
  80326. {0,8,74},{0,9,245},{16,7,5},{0,8,86},{0,8,22},{64,8,0},{19,7,51},
  80327. {0,8,118},{0,8,54},{0,9,205},{17,7,15},{0,8,102},{0,8,38},{0,9,173},
  80328. {0,8,6},{0,8,134},{0,8,70},{0,9,237},{16,7,9},{0,8,94},{0,8,30},
  80329. {0,9,157},{20,7,99},{0,8,126},{0,8,62},{0,9,221},{18,7,27},{0,8,110},
  80330. {0,8,46},{0,9,189},{0,8,14},{0,8,142},{0,8,78},{0,9,253},{96,7,0},
  80331. {0,8,81},{0,8,17},{21,8,131},{18,7,31},{0,8,113},{0,8,49},{0,9,195},
  80332. {16,7,10},{0,8,97},{0,8,33},{0,9,163},{0,8,1},{0,8,129},{0,8,65},
  80333. {0,9,227},{16,7,6},{0,8,89},{0,8,25},{0,9,147},{19,7,59},{0,8,121},
  80334. {0,8,57},{0,9,211},{17,7,17},{0,8,105},{0,8,41},{0,9,179},{0,8,9},
  80335. {0,8,137},{0,8,73},{0,9,243},{16,7,4},{0,8,85},{0,8,21},{16,8,258},
  80336. {19,7,43},{0,8,117},{0,8,53},{0,9,203},{17,7,13},{0,8,101},{0,8,37},
  80337. {0,9,171},{0,8,5},{0,8,133},{0,8,69},{0,9,235},{16,7,8},{0,8,93},
  80338. {0,8,29},{0,9,155},{20,7,83},{0,8,125},{0,8,61},{0,9,219},{18,7,23},
  80339. {0,8,109},{0,8,45},{0,9,187},{0,8,13},{0,8,141},{0,8,77},{0,9,251},
  80340. {16,7,3},{0,8,83},{0,8,19},{21,8,195},{19,7,35},{0,8,115},{0,8,51},
  80341. {0,9,199},{17,7,11},{0,8,99},{0,8,35},{0,9,167},{0,8,3},{0,8,131},
  80342. {0,8,67},{0,9,231},{16,7,7},{0,8,91},{0,8,27},{0,9,151},{20,7,67},
  80343. {0,8,123},{0,8,59},{0,9,215},{18,7,19},{0,8,107},{0,8,43},{0,9,183},
  80344. {0,8,11},{0,8,139},{0,8,75},{0,9,247},{16,7,5},{0,8,87},{0,8,23},
  80345. {64,8,0},{19,7,51},{0,8,119},{0,8,55},{0,9,207},{17,7,15},{0,8,103},
  80346. {0,8,39},{0,9,175},{0,8,7},{0,8,135},{0,8,71},{0,9,239},{16,7,9},
  80347. {0,8,95},{0,8,31},{0,9,159},{20,7,99},{0,8,127},{0,8,63},{0,9,223},
  80348. {18,7,27},{0,8,111},{0,8,47},{0,9,191},{0,8,15},{0,8,143},{0,8,79},
  80349. {0,9,255}
  80350. };
  80351. static const code distfix[32] = {
  80352. {16,5,1},{23,5,257},{19,5,17},{27,5,4097},{17,5,5},{25,5,1025},
  80353. {21,5,65},{29,5,16385},{16,5,3},{24,5,513},{20,5,33},{28,5,8193},
  80354. {18,5,9},{26,5,2049},{22,5,129},{64,5,0},{16,5,2},{23,5,385},
  80355. {19,5,25},{27,5,6145},{17,5,7},{25,5,1537},{21,5,97},{29,5,24577},
  80356. {16,5,4},{24,5,769},{20,5,49},{28,5,12289},{18,5,13},{26,5,3073},
  80357. {22,5,193},{64,5,0}
  80358. };
  80359. /*** End of inlined file: inffixed.h ***/
  80360. #endif /* BUILDFIXED */
  80361. state->lencode = lenfix;
  80362. state->lenbits = 9;
  80363. state->distcode = distfix;
  80364. state->distbits = 5;
  80365. }
  80366. #ifdef MAKEFIXED
  80367. #include <stdio.h>
  80368. /*
  80369. Write out the inffixed.h that is #include'd above. Defining MAKEFIXED also
  80370. defines BUILDFIXED, so the tables are built on the fly. makefixed() writes
  80371. those tables to stdout, which would be piped to inffixed.h. A small program
  80372. can simply call makefixed to do this:
  80373. void makefixed(void);
  80374. int main(void)
  80375. {
  80376. makefixed();
  80377. return 0;
  80378. }
  80379. Then that can be linked with zlib built with MAKEFIXED defined and run:
  80380. a.out > inffixed.h
  80381. */
  80382. void makefixed()
  80383. {
  80384. unsigned low, size;
  80385. struct inflate_state state;
  80386. fixedtables(&state);
  80387. puts(" /* inffixed.h -- table for decoding fixed codes");
  80388. puts(" * Generated automatically by makefixed().");
  80389. puts(" */");
  80390. puts("");
  80391. puts(" /* WARNING: this file should *not* be used by applications.");
  80392. puts(" It is part of the implementation of this library and is");
  80393. puts(" subject to change. Applications should only use zlib.h.");
  80394. puts(" */");
  80395. puts("");
  80396. size = 1U << 9;
  80397. printf(" static const code lenfix[%u] = {", size);
  80398. low = 0;
  80399. for (;;) {
  80400. if ((low % 7) == 0) printf("\n ");
  80401. printf("{%u,%u,%d}", state.lencode[low].op, state.lencode[low].bits,
  80402. state.lencode[low].val);
  80403. if (++low == size) break;
  80404. putchar(',');
  80405. }
  80406. puts("\n };");
  80407. size = 1U << 5;
  80408. printf("\n static const code distfix[%u] = {", size);
  80409. low = 0;
  80410. for (;;) {
  80411. if ((low % 6) == 0) printf("\n ");
  80412. printf("{%u,%u,%d}", state.distcode[low].op, state.distcode[low].bits,
  80413. state.distcode[low].val);
  80414. if (++low == size) break;
  80415. putchar(',');
  80416. }
  80417. puts("\n };");
  80418. }
  80419. #endif /* MAKEFIXED */
  80420. /*
  80421. Update the window with the last wsize (normally 32K) bytes written before
  80422. returning. If window does not exist yet, create it. This is only called
  80423. when a window is already in use, or when output has been written during this
  80424. inflate call, but the end of the deflate stream has not been reached yet.
  80425. It is also called to create a window for dictionary data when a dictionary
  80426. is loaded.
  80427. Providing output buffers larger than 32K to inflate() should provide a speed
  80428. advantage, since only the last 32K of output is copied to the sliding window
  80429. upon return from inflate(), and since all distances after the first 32K of
  80430. output will fall in the output data, making match copies simpler and faster.
  80431. The advantage may be dependent on the size of the processor's data caches.
  80432. */
  80433. local int updatewindow (z_streamp strm, unsigned out)
  80434. {
  80435. struct inflate_state FAR *state;
  80436. unsigned copy, dist;
  80437. state = (struct inflate_state FAR *)strm->state;
  80438. /* if it hasn't been done already, allocate space for the window */
  80439. if (state->window == Z_NULL) {
  80440. state->window = (unsigned char FAR *)
  80441. ZALLOC(strm, 1U << state->wbits,
  80442. sizeof(unsigned char));
  80443. if (state->window == Z_NULL) return 1;
  80444. }
  80445. /* if window not in use yet, initialize */
  80446. if (state->wsize == 0) {
  80447. state->wsize = 1U << state->wbits;
  80448. state->write = 0;
  80449. state->whave = 0;
  80450. }
  80451. /* copy state->wsize or less output bytes into the circular window */
  80452. copy = out - strm->avail_out;
  80453. if (copy >= state->wsize) {
  80454. zmemcpy(state->window, strm->next_out - state->wsize, state->wsize);
  80455. state->write = 0;
  80456. state->whave = state->wsize;
  80457. }
  80458. else {
  80459. dist = state->wsize - state->write;
  80460. if (dist > copy) dist = copy;
  80461. zmemcpy(state->window + state->write, strm->next_out - copy, dist);
  80462. copy -= dist;
  80463. if (copy) {
  80464. zmemcpy(state->window, strm->next_out - copy, copy);
  80465. state->write = copy;
  80466. state->whave = state->wsize;
  80467. }
  80468. else {
  80469. state->write += dist;
  80470. if (state->write == state->wsize) state->write = 0;
  80471. if (state->whave < state->wsize) state->whave += dist;
  80472. }
  80473. }
  80474. return 0;
  80475. }
  80476. /* Macros for inflate(): */
  80477. /* check function to use adler32() for zlib or crc32() for gzip */
  80478. #ifdef GUNZIP
  80479. # define UPDATE(check, buf, len) \
  80480. (state->flags ? crc32(check, buf, len) : adler32(check, buf, len))
  80481. #else
  80482. # define UPDATE(check, buf, len) adler32(check, buf, len)
  80483. #endif
  80484. /* check macros for header crc */
  80485. #ifdef GUNZIP
  80486. # define CRC2(check, word) \
  80487. do { \
  80488. hbuf[0] = (unsigned char)(word); \
  80489. hbuf[1] = (unsigned char)((word) >> 8); \
  80490. check = crc32(check, hbuf, 2); \
  80491. } while (0)
  80492. # define CRC4(check, word) \
  80493. do { \
  80494. hbuf[0] = (unsigned char)(word); \
  80495. hbuf[1] = (unsigned char)((word) >> 8); \
  80496. hbuf[2] = (unsigned char)((word) >> 16); \
  80497. hbuf[3] = (unsigned char)((word) >> 24); \
  80498. check = crc32(check, hbuf, 4); \
  80499. } while (0)
  80500. #endif
  80501. /* Load registers with state in inflate() for speed */
  80502. #define LOAD() \
  80503. do { \
  80504. put = strm->next_out; \
  80505. left = strm->avail_out; \
  80506. next = strm->next_in; \
  80507. have = strm->avail_in; \
  80508. hold = state->hold; \
  80509. bits = state->bits; \
  80510. } while (0)
  80511. /* Restore state from registers in inflate() */
  80512. #define RESTORE() \
  80513. do { \
  80514. strm->next_out = put; \
  80515. strm->avail_out = left; \
  80516. strm->next_in = next; \
  80517. strm->avail_in = have; \
  80518. state->hold = hold; \
  80519. state->bits = bits; \
  80520. } while (0)
  80521. /* Clear the input bit accumulator */
  80522. #define INITBITS() \
  80523. do { \
  80524. hold = 0; \
  80525. bits = 0; \
  80526. } while (0)
  80527. /* Get a byte of input into the bit accumulator, or return from inflate()
  80528. if there is no input available. */
  80529. #define PULLBYTE() \
  80530. do { \
  80531. if (have == 0) goto inf_leave; \
  80532. have--; \
  80533. hold += (unsigned long)(*next++) << bits; \
  80534. bits += 8; \
  80535. } while (0)
  80536. /* Assure that there are at least n bits in the bit accumulator. If there is
  80537. not enough available input to do that, then return from inflate(). */
  80538. #define NEEDBITS(n) \
  80539. do { \
  80540. while (bits < (unsigned)(n)) \
  80541. PULLBYTE(); \
  80542. } while (0)
  80543. /* Return the low n bits of the bit accumulator (n < 16) */
  80544. #define BITS(n) \
  80545. ((unsigned)hold & ((1U << (n)) - 1))
  80546. /* Remove n bits from the bit accumulator */
  80547. #define DROPBITS(n) \
  80548. do { \
  80549. hold >>= (n); \
  80550. bits -= (unsigned)(n); \
  80551. } while (0)
  80552. /* Remove zero to seven bits as needed to go to a byte boundary */
  80553. #define BYTEBITS() \
  80554. do { \
  80555. hold >>= bits & 7; \
  80556. bits -= bits & 7; \
  80557. } while (0)
  80558. /* Reverse the bytes in a 32-bit value */
  80559. #define REVERSE(q) \
  80560. ((((q) >> 24) & 0xff) + (((q) >> 8) & 0xff00) + \
  80561. (((q) & 0xff00) << 8) + (((q) & 0xff) << 24))
  80562. /*
  80563. inflate() uses a state machine to process as much input data and generate as
  80564. much output data as possible before returning. The state machine is
  80565. structured roughly as follows:
  80566. for (;;) switch (state) {
  80567. ...
  80568. case STATEn:
  80569. if (not enough input data or output space to make progress)
  80570. return;
  80571. ... make progress ...
  80572. state = STATEm;
  80573. break;
  80574. ...
  80575. }
  80576. so when inflate() is called again, the same case is attempted again, and
  80577. if the appropriate resources are provided, the machine proceeds to the
  80578. next state. The NEEDBITS() macro is usually the way the state evaluates
  80579. whether it can proceed or should return. NEEDBITS() does the return if
  80580. the requested bits are not available. The typical use of the BITS macros
  80581. is:
  80582. NEEDBITS(n);
  80583. ... do something with BITS(n) ...
  80584. DROPBITS(n);
  80585. where NEEDBITS(n) either returns from inflate() if there isn't enough
  80586. input left to load n bits into the accumulator, or it continues. BITS(n)
  80587. gives the low n bits in the accumulator. When done, DROPBITS(n) drops
  80588. the low n bits off the accumulator. INITBITS() clears the accumulator
  80589. and sets the number of available bits to zero. BYTEBITS() discards just
  80590. enough bits to put the accumulator on a byte boundary. After BYTEBITS()
  80591. and a NEEDBITS(8), then BITS(8) would return the next byte in the stream.
  80592. NEEDBITS(n) uses PULLBYTE() to get an available byte of input, or to return
  80593. if there is no input available. The decoding of variable length codes uses
  80594. PULLBYTE() directly in order to pull just enough bytes to decode the next
  80595. code, and no more.
  80596. Some states loop until they get enough input, making sure that enough
  80597. state information is maintained to continue the loop where it left off
  80598. if NEEDBITS() returns in the loop. For example, want, need, and keep
  80599. would all have to actually be part of the saved state in case NEEDBITS()
  80600. returns:
  80601. case STATEw:
  80602. while (want < need) {
  80603. NEEDBITS(n);
  80604. keep[want++] = BITS(n);
  80605. DROPBITS(n);
  80606. }
  80607. state = STATEx;
  80608. case STATEx:
  80609. As shown above, if the next state is also the next case, then the break
  80610. is omitted.
  80611. A state may also return if there is not enough output space available to
  80612. complete that state. Those states are copying stored data, writing a
  80613. literal byte, and copying a matching string.
  80614. When returning, a "goto inf_leave" is used to update the total counters,
  80615. update the check value, and determine whether any progress has been made
  80616. during that inflate() call in order to return the proper return code.
  80617. Progress is defined as a change in either strm->avail_in or strm->avail_out.
  80618. When there is a window, goto inf_leave will update the window with the last
  80619. output written. If a goto inf_leave occurs in the middle of decompression
  80620. and there is no window currently, goto inf_leave will create one and copy
  80621. output to the window for the next call of inflate().
  80622. In this implementation, the flush parameter of inflate() only affects the
  80623. return code (per zlib.h). inflate() always writes as much as possible to
  80624. strm->next_out, given the space available and the provided input--the effect
  80625. documented in zlib.h of Z_SYNC_FLUSH. Furthermore, inflate() always defers
  80626. the allocation of and copying into a sliding window until necessary, which
  80627. provides the effect documented in zlib.h for Z_FINISH when the entire input
  80628. stream available. So the only thing the flush parameter actually does is:
  80629. when flush is set to Z_FINISH, inflate() cannot return Z_OK. Instead it
  80630. will return Z_BUF_ERROR if it has not reached the end of the stream.
  80631. */
  80632. int ZEXPORT inflate (z_streamp strm, int flush)
  80633. {
  80634. struct inflate_state FAR *state;
  80635. unsigned char FAR *next; /* next input */
  80636. unsigned char FAR *put; /* next output */
  80637. unsigned have, left; /* available input and output */
  80638. unsigned long hold; /* bit buffer */
  80639. unsigned bits; /* bits in bit buffer */
  80640. unsigned in, out; /* save starting available input and output */
  80641. unsigned copy; /* number of stored or match bytes to copy */
  80642. unsigned char FAR *from; /* where to copy match bytes from */
  80643. code thisx; /* current decoding table entry */
  80644. code last; /* parent table entry */
  80645. unsigned len; /* length to copy for repeats, bits to drop */
  80646. int ret; /* return code */
  80647. #ifdef GUNZIP
  80648. unsigned char hbuf[4]; /* buffer for gzip header crc calculation */
  80649. #endif
  80650. static const unsigned short order[19] = /* permutation of code lengths */
  80651. {16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15};
  80652. if (strm == Z_NULL || strm->state == Z_NULL || strm->next_out == Z_NULL ||
  80653. (strm->next_in == Z_NULL && strm->avail_in != 0))
  80654. return Z_STREAM_ERROR;
  80655. state = (struct inflate_state FAR *)strm->state;
  80656. if (state->mode == TYPE) state->mode = TYPEDO; /* skip check */
  80657. LOAD();
  80658. in = have;
  80659. out = left;
  80660. ret = Z_OK;
  80661. for (;;)
  80662. switch (state->mode) {
  80663. case HEAD:
  80664. if (state->wrap == 0) {
  80665. state->mode = TYPEDO;
  80666. break;
  80667. }
  80668. NEEDBITS(16);
  80669. #ifdef GUNZIP
  80670. if ((state->wrap & 2) && hold == 0x8b1f) { /* gzip header */
  80671. state->check = crc32(0L, Z_NULL, 0);
  80672. CRC2(state->check, hold);
  80673. INITBITS();
  80674. state->mode = FLAGS;
  80675. break;
  80676. }
  80677. state->flags = 0; /* expect zlib header */
  80678. if (state->head != Z_NULL)
  80679. state->head->done = -1;
  80680. if (!(state->wrap & 1) || /* check if zlib header allowed */
  80681. #else
  80682. if (
  80683. #endif
  80684. ((BITS(8) << 8) + (hold >> 8)) % 31) {
  80685. strm->msg = (char *)"incorrect header check";
  80686. state->mode = BAD;
  80687. break;
  80688. }
  80689. if (BITS(4) != Z_DEFLATED) {
  80690. strm->msg = (char *)"unknown compression method";
  80691. state->mode = BAD;
  80692. break;
  80693. }
  80694. DROPBITS(4);
  80695. len = BITS(4) + 8;
  80696. if (len > state->wbits) {
  80697. strm->msg = (char *)"invalid window size";
  80698. state->mode = BAD;
  80699. break;
  80700. }
  80701. state->dmax = 1U << len;
  80702. Tracev((stderr, "inflate: zlib header ok\n"));
  80703. strm->adler = state->check = adler32(0L, Z_NULL, 0);
  80704. state->mode = hold & 0x200 ? DICTID : TYPE;
  80705. INITBITS();
  80706. break;
  80707. #ifdef GUNZIP
  80708. case FLAGS:
  80709. NEEDBITS(16);
  80710. state->flags = (int)(hold);
  80711. if ((state->flags & 0xff) != Z_DEFLATED) {
  80712. strm->msg = (char *)"unknown compression method";
  80713. state->mode = BAD;
  80714. break;
  80715. }
  80716. if (state->flags & 0xe000) {
  80717. strm->msg = (char *)"unknown header flags set";
  80718. state->mode = BAD;
  80719. break;
  80720. }
  80721. if (state->head != Z_NULL)
  80722. state->head->text = (int)((hold >> 8) & 1);
  80723. if (state->flags & 0x0200) CRC2(state->check, hold);
  80724. INITBITS();
  80725. state->mode = TIME;
  80726. case TIME:
  80727. NEEDBITS(32);
  80728. if (state->head != Z_NULL)
  80729. state->head->time = hold;
  80730. if (state->flags & 0x0200) CRC4(state->check, hold);
  80731. INITBITS();
  80732. state->mode = OS;
  80733. case OS:
  80734. NEEDBITS(16);
  80735. if (state->head != Z_NULL) {
  80736. state->head->xflags = (int)(hold & 0xff);
  80737. state->head->os = (int)(hold >> 8);
  80738. }
  80739. if (state->flags & 0x0200) CRC2(state->check, hold);
  80740. INITBITS();
  80741. state->mode = EXLEN;
  80742. case EXLEN:
  80743. if (state->flags & 0x0400) {
  80744. NEEDBITS(16);
  80745. state->length = (unsigned)(hold);
  80746. if (state->head != Z_NULL)
  80747. state->head->extra_len = (unsigned)hold;
  80748. if (state->flags & 0x0200) CRC2(state->check, hold);
  80749. INITBITS();
  80750. }
  80751. else if (state->head != Z_NULL)
  80752. state->head->extra = Z_NULL;
  80753. state->mode = EXTRA;
  80754. case EXTRA:
  80755. if (state->flags & 0x0400) {
  80756. copy = state->length;
  80757. if (copy > have) copy = have;
  80758. if (copy) {
  80759. if (state->head != Z_NULL &&
  80760. state->head->extra != Z_NULL) {
  80761. len = state->head->extra_len - state->length;
  80762. zmemcpy(state->head->extra + len, next,
  80763. len + copy > state->head->extra_max ?
  80764. state->head->extra_max - len : copy);
  80765. }
  80766. if (state->flags & 0x0200)
  80767. state->check = crc32(state->check, next, copy);
  80768. have -= copy;
  80769. next += copy;
  80770. state->length -= copy;
  80771. }
  80772. if (state->length) goto inf_leave;
  80773. }
  80774. state->length = 0;
  80775. state->mode = NAME;
  80776. case NAME:
  80777. if (state->flags & 0x0800) {
  80778. if (have == 0) goto inf_leave;
  80779. copy = 0;
  80780. do {
  80781. len = (unsigned)(next[copy++]);
  80782. if (state->head != Z_NULL &&
  80783. state->head->name != Z_NULL &&
  80784. state->length < state->head->name_max)
  80785. state->head->name[state->length++] = len;
  80786. } while (len && copy < have);
  80787. if (state->flags & 0x0200)
  80788. state->check = crc32(state->check, next, copy);
  80789. have -= copy;
  80790. next += copy;
  80791. if (len) goto inf_leave;
  80792. }
  80793. else if (state->head != Z_NULL)
  80794. state->head->name = Z_NULL;
  80795. state->length = 0;
  80796. state->mode = COMMENT;
  80797. case COMMENT:
  80798. if (state->flags & 0x1000) {
  80799. if (have == 0) goto inf_leave;
  80800. copy = 0;
  80801. do {
  80802. len = (unsigned)(next[copy++]);
  80803. if (state->head != Z_NULL &&
  80804. state->head->comment != Z_NULL &&
  80805. state->length < state->head->comm_max)
  80806. state->head->comment[state->length++] = len;
  80807. } while (len && copy < have);
  80808. if (state->flags & 0x0200)
  80809. state->check = crc32(state->check, next, copy);
  80810. have -= copy;
  80811. next += copy;
  80812. if (len) goto inf_leave;
  80813. }
  80814. else if (state->head != Z_NULL)
  80815. state->head->comment = Z_NULL;
  80816. state->mode = HCRC;
  80817. case HCRC:
  80818. if (state->flags & 0x0200) {
  80819. NEEDBITS(16);
  80820. if (hold != (state->check & 0xffff)) {
  80821. strm->msg = (char *)"header crc mismatch";
  80822. state->mode = BAD;
  80823. break;
  80824. }
  80825. INITBITS();
  80826. }
  80827. if (state->head != Z_NULL) {
  80828. state->head->hcrc = (int)((state->flags >> 9) & 1);
  80829. state->head->done = 1;
  80830. }
  80831. strm->adler = state->check = crc32(0L, Z_NULL, 0);
  80832. state->mode = TYPE;
  80833. break;
  80834. #endif
  80835. case DICTID:
  80836. NEEDBITS(32);
  80837. strm->adler = state->check = REVERSE(hold);
  80838. INITBITS();
  80839. state->mode = DICT;
  80840. case DICT:
  80841. if (state->havedict == 0) {
  80842. RESTORE();
  80843. return Z_NEED_DICT;
  80844. }
  80845. strm->adler = state->check = adler32(0L, Z_NULL, 0);
  80846. state->mode = TYPE;
  80847. case TYPE:
  80848. if (flush == Z_BLOCK) goto inf_leave;
  80849. case TYPEDO:
  80850. if (state->last) {
  80851. BYTEBITS();
  80852. state->mode = CHECK;
  80853. break;
  80854. }
  80855. NEEDBITS(3);
  80856. state->last = BITS(1);
  80857. DROPBITS(1);
  80858. switch (BITS(2)) {
  80859. case 0: /* stored block */
  80860. Tracev((stderr, "inflate: stored block%s\n",
  80861. state->last ? " (last)" : ""));
  80862. state->mode = STORED;
  80863. break;
  80864. case 1: /* fixed block */
  80865. fixedtables(state);
  80866. Tracev((stderr, "inflate: fixed codes block%s\n",
  80867. state->last ? " (last)" : ""));
  80868. state->mode = LEN; /* decode codes */
  80869. break;
  80870. case 2: /* dynamic block */
  80871. Tracev((stderr, "inflate: dynamic codes block%s\n",
  80872. state->last ? " (last)" : ""));
  80873. state->mode = TABLE;
  80874. break;
  80875. case 3:
  80876. strm->msg = (char *)"invalid block type";
  80877. state->mode = BAD;
  80878. }
  80879. DROPBITS(2);
  80880. break;
  80881. case STORED:
  80882. BYTEBITS(); /* go to byte boundary */
  80883. NEEDBITS(32);
  80884. if ((hold & 0xffff) != ((hold >> 16) ^ 0xffff)) {
  80885. strm->msg = (char *)"invalid stored block lengths";
  80886. state->mode = BAD;
  80887. break;
  80888. }
  80889. state->length = (unsigned)hold & 0xffff;
  80890. Tracev((stderr, "inflate: stored length %u\n",
  80891. state->length));
  80892. INITBITS();
  80893. state->mode = COPY;
  80894. case COPY:
  80895. copy = state->length;
  80896. if (copy) {
  80897. if (copy > have) copy = have;
  80898. if (copy > left) copy = left;
  80899. if (copy == 0) goto inf_leave;
  80900. zmemcpy(put, next, copy);
  80901. have -= copy;
  80902. next += copy;
  80903. left -= copy;
  80904. put += copy;
  80905. state->length -= copy;
  80906. break;
  80907. }
  80908. Tracev((stderr, "inflate: stored end\n"));
  80909. state->mode = TYPE;
  80910. break;
  80911. case TABLE:
  80912. NEEDBITS(14);
  80913. state->nlen = BITS(5) + 257;
  80914. DROPBITS(5);
  80915. state->ndist = BITS(5) + 1;
  80916. DROPBITS(5);
  80917. state->ncode = BITS(4) + 4;
  80918. DROPBITS(4);
  80919. #ifndef PKZIP_BUG_WORKAROUND
  80920. if (state->nlen > 286 || state->ndist > 30) {
  80921. strm->msg = (char *)"too many length or distance symbols";
  80922. state->mode = BAD;
  80923. break;
  80924. }
  80925. #endif
  80926. Tracev((stderr, "inflate: table sizes ok\n"));
  80927. state->have = 0;
  80928. state->mode = LENLENS;
  80929. case LENLENS:
  80930. while (state->have < state->ncode) {
  80931. NEEDBITS(3);
  80932. state->lens[order[state->have++]] = (unsigned short)BITS(3);
  80933. DROPBITS(3);
  80934. }
  80935. while (state->have < 19)
  80936. state->lens[order[state->have++]] = 0;
  80937. state->next = state->codes;
  80938. state->lencode = (code const FAR *)(state->next);
  80939. state->lenbits = 7;
  80940. ret = inflate_table(CODES, state->lens, 19, &(state->next),
  80941. &(state->lenbits), state->work);
  80942. if (ret) {
  80943. strm->msg = (char *)"invalid code lengths set";
  80944. state->mode = BAD;
  80945. break;
  80946. }
  80947. Tracev((stderr, "inflate: code lengths ok\n"));
  80948. state->have = 0;
  80949. state->mode = CODELENS;
  80950. case CODELENS:
  80951. while (state->have < state->nlen + state->ndist) {
  80952. for (;;) {
  80953. thisx = state->lencode[BITS(state->lenbits)];
  80954. if ((unsigned)(thisx.bits) <= bits) break;
  80955. PULLBYTE();
  80956. }
  80957. if (thisx.val < 16) {
  80958. NEEDBITS(thisx.bits);
  80959. DROPBITS(thisx.bits);
  80960. state->lens[state->have++] = thisx.val;
  80961. }
  80962. else {
  80963. if (thisx.val == 16) {
  80964. NEEDBITS(thisx.bits + 2);
  80965. DROPBITS(thisx.bits);
  80966. if (state->have == 0) {
  80967. strm->msg = (char *)"invalid bit length repeat";
  80968. state->mode = BAD;
  80969. break;
  80970. }
  80971. len = state->lens[state->have - 1];
  80972. copy = 3 + BITS(2);
  80973. DROPBITS(2);
  80974. }
  80975. else if (thisx.val == 17) {
  80976. NEEDBITS(thisx.bits + 3);
  80977. DROPBITS(thisx.bits);
  80978. len = 0;
  80979. copy = 3 + BITS(3);
  80980. DROPBITS(3);
  80981. }
  80982. else {
  80983. NEEDBITS(thisx.bits + 7);
  80984. DROPBITS(thisx.bits);
  80985. len = 0;
  80986. copy = 11 + BITS(7);
  80987. DROPBITS(7);
  80988. }
  80989. if (state->have + copy > state->nlen + state->ndist) {
  80990. strm->msg = (char *)"invalid bit length repeat";
  80991. state->mode = BAD;
  80992. break;
  80993. }
  80994. while (copy--)
  80995. state->lens[state->have++] = (unsigned short)len;
  80996. }
  80997. }
  80998. /* handle error breaks in while */
  80999. if (state->mode == BAD) break;
  81000. /* build code tables */
  81001. state->next = state->codes;
  81002. state->lencode = (code const FAR *)(state->next);
  81003. state->lenbits = 9;
  81004. ret = inflate_table(LENS, state->lens, state->nlen, &(state->next),
  81005. &(state->lenbits), state->work);
  81006. if (ret) {
  81007. strm->msg = (char *)"invalid literal/lengths set";
  81008. state->mode = BAD;
  81009. break;
  81010. }
  81011. state->distcode = (code const FAR *)(state->next);
  81012. state->distbits = 6;
  81013. ret = inflate_table(DISTS, state->lens + state->nlen, state->ndist,
  81014. &(state->next), &(state->distbits), state->work);
  81015. if (ret) {
  81016. strm->msg = (char *)"invalid distances set";
  81017. state->mode = BAD;
  81018. break;
  81019. }
  81020. Tracev((stderr, "inflate: codes ok\n"));
  81021. state->mode = LEN;
  81022. case LEN:
  81023. if (have >= 6 && left >= 258) {
  81024. RESTORE();
  81025. inflate_fast(strm, out);
  81026. LOAD();
  81027. break;
  81028. }
  81029. for (;;) {
  81030. thisx = state->lencode[BITS(state->lenbits)];
  81031. if ((unsigned)(thisx.bits) <= bits) break;
  81032. PULLBYTE();
  81033. }
  81034. if (thisx.op && (thisx.op & 0xf0) == 0) {
  81035. last = thisx;
  81036. for (;;) {
  81037. thisx = state->lencode[last.val +
  81038. (BITS(last.bits + last.op) >> last.bits)];
  81039. if ((unsigned)(last.bits + thisx.bits) <= bits) break;
  81040. PULLBYTE();
  81041. }
  81042. DROPBITS(last.bits);
  81043. }
  81044. DROPBITS(thisx.bits);
  81045. state->length = (unsigned)thisx.val;
  81046. if ((int)(thisx.op) == 0) {
  81047. Tracevv((stderr, thisx.val >= 0x20 && thisx.val < 0x7f ?
  81048. "inflate: literal '%c'\n" :
  81049. "inflate: literal 0x%02x\n", thisx.val));
  81050. state->mode = LIT;
  81051. break;
  81052. }
  81053. if (thisx.op & 32) {
  81054. Tracevv((stderr, "inflate: end of block\n"));
  81055. state->mode = TYPE;
  81056. break;
  81057. }
  81058. if (thisx.op & 64) {
  81059. strm->msg = (char *)"invalid literal/length code";
  81060. state->mode = BAD;
  81061. break;
  81062. }
  81063. state->extra = (unsigned)(thisx.op) & 15;
  81064. state->mode = LENEXT;
  81065. case LENEXT:
  81066. if (state->extra) {
  81067. NEEDBITS(state->extra);
  81068. state->length += BITS(state->extra);
  81069. DROPBITS(state->extra);
  81070. }
  81071. Tracevv((stderr, "inflate: length %u\n", state->length));
  81072. state->mode = DIST;
  81073. case DIST:
  81074. for (;;) {
  81075. thisx = state->distcode[BITS(state->distbits)];
  81076. if ((unsigned)(thisx.bits) <= bits) break;
  81077. PULLBYTE();
  81078. }
  81079. if ((thisx.op & 0xf0) == 0) {
  81080. last = thisx;
  81081. for (;;) {
  81082. thisx = state->distcode[last.val +
  81083. (BITS(last.bits + last.op) >> last.bits)];
  81084. if ((unsigned)(last.bits + thisx.bits) <= bits) break;
  81085. PULLBYTE();
  81086. }
  81087. DROPBITS(last.bits);
  81088. }
  81089. DROPBITS(thisx.bits);
  81090. if (thisx.op & 64) {
  81091. strm->msg = (char *)"invalid distance code";
  81092. state->mode = BAD;
  81093. break;
  81094. }
  81095. state->offset = (unsigned)thisx.val;
  81096. state->extra = (unsigned)(thisx.op) & 15;
  81097. state->mode = DISTEXT;
  81098. case DISTEXT:
  81099. if (state->extra) {
  81100. NEEDBITS(state->extra);
  81101. state->offset += BITS(state->extra);
  81102. DROPBITS(state->extra);
  81103. }
  81104. #ifdef INFLATE_STRICT
  81105. if (state->offset > state->dmax) {
  81106. strm->msg = (char *)"invalid distance too far back";
  81107. state->mode = BAD;
  81108. break;
  81109. }
  81110. #endif
  81111. if (state->offset > state->whave + out - left) {
  81112. strm->msg = (char *)"invalid distance too far back";
  81113. state->mode = BAD;
  81114. break;
  81115. }
  81116. Tracevv((stderr, "inflate: distance %u\n", state->offset));
  81117. state->mode = MATCH;
  81118. case MATCH:
  81119. if (left == 0) goto inf_leave;
  81120. copy = out - left;
  81121. if (state->offset > copy) { /* copy from window */
  81122. copy = state->offset - copy;
  81123. if (copy > state->write) {
  81124. copy -= state->write;
  81125. from = state->window + (state->wsize - copy);
  81126. }
  81127. else
  81128. from = state->window + (state->write - copy);
  81129. if (copy > state->length) copy = state->length;
  81130. }
  81131. else { /* copy from output */
  81132. from = put - state->offset;
  81133. copy = state->length;
  81134. }
  81135. if (copy > left) copy = left;
  81136. left -= copy;
  81137. state->length -= copy;
  81138. do {
  81139. *put++ = *from++;
  81140. } while (--copy);
  81141. if (state->length == 0) state->mode = LEN;
  81142. break;
  81143. case LIT:
  81144. if (left == 0) goto inf_leave;
  81145. *put++ = (unsigned char)(state->length);
  81146. left--;
  81147. state->mode = LEN;
  81148. break;
  81149. case CHECK:
  81150. if (state->wrap) {
  81151. NEEDBITS(32);
  81152. out -= left;
  81153. strm->total_out += out;
  81154. state->total += out;
  81155. if (out)
  81156. strm->adler = state->check =
  81157. UPDATE(state->check, put - out, out);
  81158. out = left;
  81159. if ((
  81160. #ifdef GUNZIP
  81161. state->flags ? hold :
  81162. #endif
  81163. REVERSE(hold)) != state->check) {
  81164. strm->msg = (char *)"incorrect data check";
  81165. state->mode = BAD;
  81166. break;
  81167. }
  81168. INITBITS();
  81169. Tracev((stderr, "inflate: check matches trailer\n"));
  81170. }
  81171. #ifdef GUNZIP
  81172. state->mode = LENGTH;
  81173. case LENGTH:
  81174. if (state->wrap && state->flags) {
  81175. NEEDBITS(32);
  81176. if (hold != (state->total & 0xffffffffUL)) {
  81177. strm->msg = (char *)"incorrect length check";
  81178. state->mode = BAD;
  81179. break;
  81180. }
  81181. INITBITS();
  81182. Tracev((stderr, "inflate: length matches trailer\n"));
  81183. }
  81184. #endif
  81185. state->mode = DONE;
  81186. case DONE:
  81187. ret = Z_STREAM_END;
  81188. goto inf_leave;
  81189. case BAD:
  81190. ret = Z_DATA_ERROR;
  81191. goto inf_leave;
  81192. case MEM:
  81193. return Z_MEM_ERROR;
  81194. case SYNC:
  81195. default:
  81196. return Z_STREAM_ERROR;
  81197. }
  81198. /*
  81199. Return from inflate(), updating the total counts and the check value.
  81200. If there was no progress during the inflate() call, return a buffer
  81201. error. Call updatewindow() to create and/or update the window state.
  81202. Note: a memory error from inflate() is non-recoverable.
  81203. */
  81204. inf_leave:
  81205. RESTORE();
  81206. if (state->wsize || (state->mode < CHECK && out != strm->avail_out))
  81207. if (updatewindow(strm, out)) {
  81208. state->mode = MEM;
  81209. return Z_MEM_ERROR;
  81210. }
  81211. in -= strm->avail_in;
  81212. out -= strm->avail_out;
  81213. strm->total_in += in;
  81214. strm->total_out += out;
  81215. state->total += out;
  81216. if (state->wrap && out)
  81217. strm->adler = state->check =
  81218. UPDATE(state->check, strm->next_out - out, out);
  81219. strm->data_type = state->bits + (state->last ? 64 : 0) +
  81220. (state->mode == TYPE ? 128 : 0);
  81221. if (((in == 0 && out == 0) || flush == Z_FINISH) && ret == Z_OK)
  81222. ret = Z_BUF_ERROR;
  81223. return ret;
  81224. }
  81225. int ZEXPORT inflateEnd (z_streamp strm)
  81226. {
  81227. struct inflate_state FAR *state;
  81228. if (strm == Z_NULL || strm->state == Z_NULL || strm->zfree == (free_func)0)
  81229. return Z_STREAM_ERROR;
  81230. state = (struct inflate_state FAR *)strm->state;
  81231. if (state->window != Z_NULL) ZFREE(strm, state->window);
  81232. ZFREE(strm, strm->state);
  81233. strm->state = Z_NULL;
  81234. Tracev((stderr, "inflate: end\n"));
  81235. return Z_OK;
  81236. }
  81237. int ZEXPORT inflateSetDictionary (z_streamp strm, const Bytef *dictionary, uInt dictLength)
  81238. {
  81239. struct inflate_state FAR *state;
  81240. unsigned long id_;
  81241. /* check state */
  81242. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  81243. state = (struct inflate_state FAR *)strm->state;
  81244. if (state->wrap != 0 && state->mode != DICT)
  81245. return Z_STREAM_ERROR;
  81246. /* check for correct dictionary id */
  81247. if (state->mode == DICT) {
  81248. id_ = adler32(0L, Z_NULL, 0);
  81249. id_ = adler32(id_, dictionary, dictLength);
  81250. if (id_ != state->check)
  81251. return Z_DATA_ERROR;
  81252. }
  81253. /* copy dictionary to window */
  81254. if (updatewindow(strm, strm->avail_out)) {
  81255. state->mode = MEM;
  81256. return Z_MEM_ERROR;
  81257. }
  81258. if (dictLength > state->wsize) {
  81259. zmemcpy(state->window, dictionary + dictLength - state->wsize,
  81260. state->wsize);
  81261. state->whave = state->wsize;
  81262. }
  81263. else {
  81264. zmemcpy(state->window + state->wsize - dictLength, dictionary,
  81265. dictLength);
  81266. state->whave = dictLength;
  81267. }
  81268. state->havedict = 1;
  81269. Tracev((stderr, "inflate: dictionary set\n"));
  81270. return Z_OK;
  81271. }
  81272. int ZEXPORT inflateGetHeader (z_streamp strm, gz_headerp head)
  81273. {
  81274. struct inflate_state FAR *state;
  81275. /* check state */
  81276. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  81277. state = (struct inflate_state FAR *)strm->state;
  81278. if ((state->wrap & 2) == 0) return Z_STREAM_ERROR;
  81279. /* save header structure */
  81280. state->head = head;
  81281. head->done = 0;
  81282. return Z_OK;
  81283. }
  81284. /*
  81285. Search buf[0..len-1] for the pattern: 0, 0, 0xff, 0xff. Return when found
  81286. or when out of input. When called, *have is the number of pattern bytes
  81287. found in order so far, in 0..3. On return *have is updated to the new
  81288. state. If on return *have equals four, then the pattern was found and the
  81289. return value is how many bytes were read including the last byte of the
  81290. pattern. If *have is less than four, then the pattern has not been found
  81291. yet and the return value is len. In the latter case, syncsearch() can be
  81292. called again with more data and the *have state. *have is initialized to
  81293. zero for the first call.
  81294. */
  81295. local unsigned syncsearch (unsigned FAR *have, unsigned char FAR *buf, unsigned len)
  81296. {
  81297. unsigned got;
  81298. unsigned next;
  81299. got = *have;
  81300. next = 0;
  81301. while (next < len && got < 4) {
  81302. if ((int)(buf[next]) == (got < 2 ? 0 : 0xff))
  81303. got++;
  81304. else if (buf[next])
  81305. got = 0;
  81306. else
  81307. got = 4 - got;
  81308. next++;
  81309. }
  81310. *have = got;
  81311. return next;
  81312. }
  81313. int ZEXPORT inflateSync (z_streamp strm)
  81314. {
  81315. unsigned len; /* number of bytes to look at or looked at */
  81316. unsigned long in, out; /* temporary to save total_in and total_out */
  81317. unsigned char buf[4]; /* to restore bit buffer to byte string */
  81318. struct inflate_state FAR *state;
  81319. /* check parameters */
  81320. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  81321. state = (struct inflate_state FAR *)strm->state;
  81322. if (strm->avail_in == 0 && state->bits < 8) return Z_BUF_ERROR;
  81323. /* if first time, start search in bit buffer */
  81324. if (state->mode != SYNC) {
  81325. state->mode = SYNC;
  81326. state->hold <<= state->bits & 7;
  81327. state->bits -= state->bits & 7;
  81328. len = 0;
  81329. while (state->bits >= 8) {
  81330. buf[len++] = (unsigned char)(state->hold);
  81331. state->hold >>= 8;
  81332. state->bits -= 8;
  81333. }
  81334. state->have = 0;
  81335. syncsearch(&(state->have), buf, len);
  81336. }
  81337. /* search available input */
  81338. len = syncsearch(&(state->have), strm->next_in, strm->avail_in);
  81339. strm->avail_in -= len;
  81340. strm->next_in += len;
  81341. strm->total_in += len;
  81342. /* return no joy or set up to restart inflate() on a new block */
  81343. if (state->have != 4) return Z_DATA_ERROR;
  81344. in = strm->total_in; out = strm->total_out;
  81345. inflateReset(strm);
  81346. strm->total_in = in; strm->total_out = out;
  81347. state->mode = TYPE;
  81348. return Z_OK;
  81349. }
  81350. /*
  81351. Returns true if inflate is currently at the end of a block generated by
  81352. Z_SYNC_FLUSH or Z_FULL_FLUSH. This function is used by one PPP
  81353. implementation to provide an additional safety check. PPP uses
  81354. Z_SYNC_FLUSH but removes the length bytes of the resulting empty stored
  81355. block. When decompressing, PPP checks that at the end of input packet,
  81356. inflate is waiting for these length bytes.
  81357. */
  81358. int ZEXPORT inflateSyncPoint (z_streamp strm)
  81359. {
  81360. struct inflate_state FAR *state;
  81361. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  81362. state = (struct inflate_state FAR *)strm->state;
  81363. return state->mode == STORED && state->bits == 0;
  81364. }
  81365. int ZEXPORT inflateCopy(z_streamp dest, z_streamp source)
  81366. {
  81367. struct inflate_state FAR *state;
  81368. struct inflate_state FAR *copy;
  81369. unsigned char FAR *window;
  81370. unsigned wsize;
  81371. /* check input */
  81372. if (dest == Z_NULL || source == Z_NULL || source->state == Z_NULL ||
  81373. source->zalloc == (alloc_func)0 || source->zfree == (free_func)0)
  81374. return Z_STREAM_ERROR;
  81375. state = (struct inflate_state FAR *)source->state;
  81376. /* allocate space */
  81377. copy = (struct inflate_state FAR *)
  81378. ZALLOC(source, 1, sizeof(struct inflate_state));
  81379. if (copy == Z_NULL) return Z_MEM_ERROR;
  81380. window = Z_NULL;
  81381. if (state->window != Z_NULL) {
  81382. window = (unsigned char FAR *)
  81383. ZALLOC(source, 1U << state->wbits, sizeof(unsigned char));
  81384. if (window == Z_NULL) {
  81385. ZFREE(source, copy);
  81386. return Z_MEM_ERROR;
  81387. }
  81388. }
  81389. /* copy state */
  81390. zmemcpy(dest, source, sizeof(z_stream));
  81391. zmemcpy(copy, state, sizeof(struct inflate_state));
  81392. if (state->lencode >= state->codes &&
  81393. state->lencode <= state->codes + ENOUGH - 1) {
  81394. copy->lencode = copy->codes + (state->lencode - state->codes);
  81395. copy->distcode = copy->codes + (state->distcode - state->codes);
  81396. }
  81397. copy->next = copy->codes + (state->next - state->codes);
  81398. if (window != Z_NULL) {
  81399. wsize = 1U << state->wbits;
  81400. zmemcpy(window, state->window, wsize);
  81401. }
  81402. copy->window = window;
  81403. dest->state = (struct internal_state FAR *)copy;
  81404. return Z_OK;
  81405. }
  81406. /*** End of inlined file: inflate.c ***/
  81407. /*** Start of inlined file: inftrees.c ***/
  81408. #define MAXBITS 15
  81409. const char inflate_copyright[] =
  81410. " inflate 1.2.3 Copyright 1995-2005 Mark Adler ";
  81411. /*
  81412. If you use the zlib library in a product, an acknowledgment is welcome
  81413. in the documentation of your product. If for some reason you cannot
  81414. include such an acknowledgment, I would appreciate that you keep this
  81415. copyright string in the executable of your product.
  81416. */
  81417. /*
  81418. Build a set of tables to decode the provided canonical Huffman code.
  81419. The code lengths are lens[0..codes-1]. The result starts at *table,
  81420. whose indices are 0..2^bits-1. work is a writable array of at least
  81421. lens shorts, which is used as a work area. type is the type of code
  81422. to be generated, CODES, LENS, or DISTS. On return, zero is success,
  81423. -1 is an invalid code, and +1 means that ENOUGH isn't enough. table
  81424. on return points to the next available entry's address. bits is the
  81425. requested root table index bits, and on return it is the actual root
  81426. table index bits. It will differ if the request is greater than the
  81427. longest code or if it is less than the shortest code.
  81428. */
  81429. int inflate_table (codetype type,
  81430. unsigned short FAR *lens,
  81431. unsigned codes,
  81432. code FAR * FAR *table,
  81433. unsigned FAR *bits,
  81434. unsigned short FAR *work)
  81435. {
  81436. unsigned len; /* a code's length in bits */
  81437. unsigned sym; /* index of code symbols */
  81438. unsigned min, max; /* minimum and maximum code lengths */
  81439. unsigned root; /* number of index bits for root table */
  81440. unsigned curr; /* number of index bits for current table */
  81441. unsigned drop; /* code bits to drop for sub-table */
  81442. int left; /* number of prefix codes available */
  81443. unsigned used; /* code entries in table used */
  81444. unsigned huff; /* Huffman code */
  81445. unsigned incr; /* for incrementing code, index */
  81446. unsigned fill; /* index for replicating entries */
  81447. unsigned low; /* low bits for current root entry */
  81448. unsigned mask; /* mask for low root bits */
  81449. code thisx; /* table entry for duplication */
  81450. code FAR *next; /* next available space in table */
  81451. const unsigned short FAR *base; /* base value table to use */
  81452. const unsigned short FAR *extra; /* extra bits table to use */
  81453. int end; /* use base and extra for symbol > end */
  81454. unsigned short count[MAXBITS+1]; /* number of codes of each length */
  81455. unsigned short offs[MAXBITS+1]; /* offsets in table for each length */
  81456. static const unsigned short lbase[31] = { /* Length codes 257..285 base */
  81457. 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31,
  81458. 35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258, 0, 0};
  81459. static const unsigned short lext[31] = { /* Length codes 257..285 extra */
  81460. 16, 16, 16, 16, 16, 16, 16, 16, 17, 17, 17, 17, 18, 18, 18, 18,
  81461. 19, 19, 19, 19, 20, 20, 20, 20, 21, 21, 21, 21, 16, 201, 196};
  81462. static const unsigned short dbase[32] = { /* Distance codes 0..29 base */
  81463. 1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193,
  81464. 257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145,
  81465. 8193, 12289, 16385, 24577, 0, 0};
  81466. static const unsigned short dext[32] = { /* Distance codes 0..29 extra */
  81467. 16, 16, 16, 16, 17, 17, 18, 18, 19, 19, 20, 20, 21, 21, 22, 22,
  81468. 23, 23, 24, 24, 25, 25, 26, 26, 27, 27,
  81469. 28, 28, 29, 29, 64, 64};
  81470. /*
  81471. Process a set of code lengths to create a canonical Huffman code. The
  81472. code lengths are lens[0..codes-1]. Each length corresponds to the
  81473. symbols 0..codes-1. The Huffman code is generated by first sorting the
  81474. symbols by length from short to long, and retaining the symbol order
  81475. for codes with equal lengths. Then the code starts with all zero bits
  81476. for the first code of the shortest length, and the codes are integer
  81477. increments for the same length, and zeros are appended as the length
  81478. increases. For the deflate format, these bits are stored backwards
  81479. from their more natural integer increment ordering, and so when the
  81480. decoding tables are built in the large loop below, the integer codes
  81481. are incremented backwards.
  81482. This routine assumes, but does not check, that all of the entries in
  81483. lens[] are in the range 0..MAXBITS. The caller must assure this.
  81484. 1..MAXBITS is interpreted as that code length. zero means that that
  81485. symbol does not occur in this code.
  81486. The codes are sorted by computing a count of codes for each length,
  81487. creating from that a table of starting indices for each length in the
  81488. sorted table, and then entering the symbols in order in the sorted
  81489. table. The sorted table is work[], with that space being provided by
  81490. the caller.
  81491. The length counts are used for other purposes as well, i.e. finding
  81492. the minimum and maximum length codes, determining if there are any
  81493. codes at all, checking for a valid set of lengths, and looking ahead
  81494. at length counts to determine sub-table sizes when building the
  81495. decoding tables.
  81496. */
  81497. /* accumulate lengths for codes (assumes lens[] all in 0..MAXBITS) */
  81498. for (len = 0; len <= MAXBITS; len++)
  81499. count[len] = 0;
  81500. for (sym = 0; sym < codes; sym++)
  81501. count[lens[sym]]++;
  81502. /* bound code lengths, force root to be within code lengths */
  81503. root = *bits;
  81504. for (max = MAXBITS; max >= 1; max--)
  81505. if (count[max] != 0) break;
  81506. if (root > max) root = max;
  81507. if (max == 0) { /* no symbols to code at all */
  81508. thisx.op = (unsigned char)64; /* invalid code marker */
  81509. thisx.bits = (unsigned char)1;
  81510. thisx.val = (unsigned short)0;
  81511. *(*table)++ = thisx; /* make a table to force an error */
  81512. *(*table)++ = thisx;
  81513. *bits = 1;
  81514. return 0; /* no symbols, but wait for decoding to report error */
  81515. }
  81516. for (min = 1; min <= MAXBITS; min++)
  81517. if (count[min] != 0) break;
  81518. if (root < min) root = min;
  81519. /* check for an over-subscribed or incomplete set of lengths */
  81520. left = 1;
  81521. for (len = 1; len <= MAXBITS; len++) {
  81522. left <<= 1;
  81523. left -= count[len];
  81524. if (left < 0) return -1; /* over-subscribed */
  81525. }
  81526. if (left > 0 && (type == CODES || max != 1))
  81527. return -1; /* incomplete set */
  81528. /* generate offsets into symbol table for each length for sorting */
  81529. offs[1] = 0;
  81530. for (len = 1; len < MAXBITS; len++)
  81531. offs[len + 1] = offs[len] + count[len];
  81532. /* sort symbols by length, by symbol order within each length */
  81533. for (sym = 0; sym < codes; sym++)
  81534. if (lens[sym] != 0) work[offs[lens[sym]]++] = (unsigned short)sym;
  81535. /*
  81536. Create and fill in decoding tables. In this loop, the table being
  81537. filled is at next and has curr index bits. The code being used is huff
  81538. with length len. That code is converted to an index by dropping drop
  81539. bits off of the bottom. For codes where len is less than drop + curr,
  81540. those top drop + curr - len bits are incremented through all values to
  81541. fill the table with replicated entries.
  81542. root is the number of index bits for the root table. When len exceeds
  81543. root, sub-tables are created pointed to by the root entry with an index
  81544. of the low root bits of huff. This is saved in low to check for when a
  81545. new sub-table should be started. drop is zero when the root table is
  81546. being filled, and drop is root when sub-tables are being filled.
  81547. When a new sub-table is needed, it is necessary to look ahead in the
  81548. code lengths to determine what size sub-table is needed. The length
  81549. counts are used for this, and so count[] is decremented as codes are
  81550. entered in the tables.
  81551. used keeps track of how many table entries have been allocated from the
  81552. provided *table space. It is checked when a LENS table is being made
  81553. against the space in *table, ENOUGH, minus the maximum space needed by
  81554. the worst case distance code, MAXD. This should never happen, but the
  81555. sufficiency of ENOUGH has not been proven exhaustively, hence the check.
  81556. This assumes that when type == LENS, bits == 9.
  81557. sym increments through all symbols, and the loop terminates when
  81558. all codes of length max, i.e. all codes, have been processed. This
  81559. routine permits incomplete codes, so another loop after this one fills
  81560. in the rest of the decoding tables with invalid code markers.
  81561. */
  81562. /* set up for code type */
  81563. switch (type) {
  81564. case CODES:
  81565. base = extra = work; /* dummy value--not used */
  81566. end = 19;
  81567. break;
  81568. case LENS:
  81569. base = lbase;
  81570. base -= 257;
  81571. extra = lext;
  81572. extra -= 257;
  81573. end = 256;
  81574. break;
  81575. default: /* DISTS */
  81576. base = dbase;
  81577. extra = dext;
  81578. end = -1;
  81579. }
  81580. /* initialize state for loop */
  81581. huff = 0; /* starting code */
  81582. sym = 0; /* starting code symbol */
  81583. len = min; /* starting code length */
  81584. next = *table; /* current table to fill in */
  81585. curr = root; /* current table index bits */
  81586. drop = 0; /* current bits to drop from code for index */
  81587. low = (unsigned)(-1); /* trigger new sub-table when len > root */
  81588. used = 1U << root; /* use root table entries */
  81589. mask = used - 1; /* mask for comparing low */
  81590. /* check available table space */
  81591. if (type == LENS && used >= ENOUGH - MAXD)
  81592. return 1;
  81593. /* process all codes and make table entries */
  81594. for (;;) {
  81595. /* create table entry */
  81596. thisx.bits = (unsigned char)(len - drop);
  81597. if ((int)(work[sym]) < end) {
  81598. thisx.op = (unsigned char)0;
  81599. thisx.val = work[sym];
  81600. }
  81601. else if ((int)(work[sym]) > end) {
  81602. thisx.op = (unsigned char)(extra[work[sym]]);
  81603. thisx.val = base[work[sym]];
  81604. }
  81605. else {
  81606. thisx.op = (unsigned char)(32 + 64); /* end of block */
  81607. thisx.val = 0;
  81608. }
  81609. /* replicate for those indices with low len bits equal to huff */
  81610. incr = 1U << (len - drop);
  81611. fill = 1U << curr;
  81612. min = fill; /* save offset to next table */
  81613. do {
  81614. fill -= incr;
  81615. next[(huff >> drop) + fill] = thisx;
  81616. } while (fill != 0);
  81617. /* backwards increment the len-bit code huff */
  81618. incr = 1U << (len - 1);
  81619. while (huff & incr)
  81620. incr >>= 1;
  81621. if (incr != 0) {
  81622. huff &= incr - 1;
  81623. huff += incr;
  81624. }
  81625. else
  81626. huff = 0;
  81627. /* go to next symbol, update count, len */
  81628. sym++;
  81629. if (--(count[len]) == 0) {
  81630. if (len == max) break;
  81631. len = lens[work[sym]];
  81632. }
  81633. /* create new sub-table if needed */
  81634. if (len > root && (huff & mask) != low) {
  81635. /* if first time, transition to sub-tables */
  81636. if (drop == 0)
  81637. drop = root;
  81638. /* increment past last table */
  81639. next += min; /* here min is 1 << curr */
  81640. /* determine length of next table */
  81641. curr = len - drop;
  81642. left = (int)(1 << curr);
  81643. while (curr + drop < max) {
  81644. left -= count[curr + drop];
  81645. if (left <= 0) break;
  81646. curr++;
  81647. left <<= 1;
  81648. }
  81649. /* check for enough space */
  81650. used += 1U << curr;
  81651. if (type == LENS && used >= ENOUGH - MAXD)
  81652. return 1;
  81653. /* point entry in root table to sub-table */
  81654. low = huff & mask;
  81655. (*table)[low].op = (unsigned char)curr;
  81656. (*table)[low].bits = (unsigned char)root;
  81657. (*table)[low].val = (unsigned short)(next - *table);
  81658. }
  81659. }
  81660. /*
  81661. Fill in rest of table for incomplete codes. This loop is similar to the
  81662. loop above in incrementing huff for table indices. It is assumed that
  81663. len is equal to curr + drop, so there is no loop needed to increment
  81664. through high index bits. When the current sub-table is filled, the loop
  81665. drops back to the root table to fill in any remaining entries there.
  81666. */
  81667. thisx.op = (unsigned char)64; /* invalid code marker */
  81668. thisx.bits = (unsigned char)(len - drop);
  81669. thisx.val = (unsigned short)0;
  81670. while (huff != 0) {
  81671. /* when done with sub-table, drop back to root table */
  81672. if (drop != 0 && (huff & mask) != low) {
  81673. drop = 0;
  81674. len = root;
  81675. next = *table;
  81676. thisx.bits = (unsigned char)len;
  81677. }
  81678. /* put invalid code marker in table */
  81679. next[huff >> drop] = thisx;
  81680. /* backwards increment the len-bit code huff */
  81681. incr = 1U << (len - 1);
  81682. while (huff & incr)
  81683. incr >>= 1;
  81684. if (incr != 0) {
  81685. huff &= incr - 1;
  81686. huff += incr;
  81687. }
  81688. else
  81689. huff = 0;
  81690. }
  81691. /* set return parameters */
  81692. *table += used;
  81693. *bits = root;
  81694. return 0;
  81695. }
  81696. /*** End of inlined file: inftrees.c ***/
  81697. /*** Start of inlined file: trees.c ***/
  81698. /*
  81699. * ALGORITHM
  81700. *
  81701. * The "deflation" process uses several Huffman trees. The more
  81702. * common source values are represented by shorter bit sequences.
  81703. *
  81704. * Each code tree is stored in a compressed form which is itself
  81705. * a Huffman encoding of the lengths of all the code strings (in
  81706. * ascending order by source values). The actual code strings are
  81707. * reconstructed from the lengths in the inflate process, as described
  81708. * in the deflate specification.
  81709. *
  81710. * REFERENCES
  81711. *
  81712. * Deutsch, L.P.,"'Deflate' Compressed Data Format Specification".
  81713. * Available in ftp.uu.net:/pub/archiving/zip/doc/deflate-1.1.doc
  81714. *
  81715. * Storer, James A.
  81716. * Data Compression: Methods and Theory, pp. 49-50.
  81717. * Computer Science Press, 1988. ISBN 0-7167-8156-5.
  81718. *
  81719. * Sedgewick, R.
  81720. * Algorithms, p290.
  81721. * Addison-Wesley, 1983. ISBN 0-201-06672-6.
  81722. */
  81723. /* @(#) $Id: trees.c,v 1.1 2007/06/07 17:54:37 jules_rms Exp $ */
  81724. /* #define GEN_TREES_H */
  81725. #ifdef DEBUG
  81726. # include <ctype.h>
  81727. #endif
  81728. /* ===========================================================================
  81729. * Constants
  81730. */
  81731. #define MAX_BL_BITS 7
  81732. /* Bit length codes must not exceed MAX_BL_BITS bits */
  81733. #define END_BLOCK 256
  81734. /* end of block literal code */
  81735. #define REP_3_6 16
  81736. /* repeat previous bit length 3-6 times (2 bits of repeat count) */
  81737. #define REPZ_3_10 17
  81738. /* repeat a zero length 3-10 times (3 bits of repeat count) */
  81739. #define REPZ_11_138 18
  81740. /* repeat a zero length 11-138 times (7 bits of repeat count) */
  81741. local const int extra_lbits[LENGTH_CODES] /* extra bits for each length code */
  81742. = {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};
  81743. local const int extra_dbits[D_CODES] /* extra bits for each distance code */
  81744. = {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};
  81745. local const int extra_blbits[BL_CODES]/* extra bits for each bit length code */
  81746. = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7};
  81747. local const uch bl_order[BL_CODES]
  81748. = {16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15};
  81749. /* The lengths of the bit length codes are sent in order of decreasing
  81750. * probability, to avoid transmitting the lengths for unused bit length codes.
  81751. */
  81752. #define Buf_size (8 * 2*sizeof(char))
  81753. /* Number of bits used within bi_buf. (bi_buf might be implemented on
  81754. * more than 16 bits on some systems.)
  81755. */
  81756. /* ===========================================================================
  81757. * Local data. These are initialized only once.
  81758. */
  81759. #define DIST_CODE_LEN 512 /* see definition of array dist_code below */
  81760. #if defined(GEN_TREES_H) || !defined(STDC)
  81761. /* non ANSI compilers may not accept trees.h */
  81762. local ct_data static_ltree[L_CODES+2];
  81763. /* The static literal tree. Since the bit lengths are imposed, there is no
  81764. * need for the L_CODES extra codes used during heap construction. However
  81765. * The codes 286 and 287 are needed to build a canonical tree (see _tr_init
  81766. * below).
  81767. */
  81768. local ct_data static_dtree[D_CODES];
  81769. /* The static distance tree. (Actually a trivial tree since all codes use
  81770. * 5 bits.)
  81771. */
  81772. uch _dist_code[DIST_CODE_LEN];
  81773. /* Distance codes. The first 256 values correspond to the distances
  81774. * 3 .. 258, the last 256 values correspond to the top 8 bits of
  81775. * the 15 bit distances.
  81776. */
  81777. uch _length_code[MAX_MATCH-MIN_MATCH+1];
  81778. /* length code for each normalized match length (0 == MIN_MATCH) */
  81779. local int base_length[LENGTH_CODES];
  81780. /* First normalized length for each code (0 = MIN_MATCH) */
  81781. local int base_dist[D_CODES];
  81782. /* First normalized distance for each code (0 = distance of 1) */
  81783. #else
  81784. /*** Start of inlined file: trees.h ***/
  81785. local const ct_data static_ltree[L_CODES+2] = {
  81786. {{ 12},{ 8}}, {{140},{ 8}}, {{ 76},{ 8}}, {{204},{ 8}}, {{ 44},{ 8}},
  81787. {{172},{ 8}}, {{108},{ 8}}, {{236},{ 8}}, {{ 28},{ 8}}, {{156},{ 8}},
  81788. {{ 92},{ 8}}, {{220},{ 8}}, {{ 60},{ 8}}, {{188},{ 8}}, {{124},{ 8}},
  81789. {{252},{ 8}}, {{ 2},{ 8}}, {{130},{ 8}}, {{ 66},{ 8}}, {{194},{ 8}},
  81790. {{ 34},{ 8}}, {{162},{ 8}}, {{ 98},{ 8}}, {{226},{ 8}}, {{ 18},{ 8}},
  81791. {{146},{ 8}}, {{ 82},{ 8}}, {{210},{ 8}}, {{ 50},{ 8}}, {{178},{ 8}},
  81792. {{114},{ 8}}, {{242},{ 8}}, {{ 10},{ 8}}, {{138},{ 8}}, {{ 74},{ 8}},
  81793. {{202},{ 8}}, {{ 42},{ 8}}, {{170},{ 8}}, {{106},{ 8}}, {{234},{ 8}},
  81794. {{ 26},{ 8}}, {{154},{ 8}}, {{ 90},{ 8}}, {{218},{ 8}}, {{ 58},{ 8}},
  81795. {{186},{ 8}}, {{122},{ 8}}, {{250},{ 8}}, {{ 6},{ 8}}, {{134},{ 8}},
  81796. {{ 70},{ 8}}, {{198},{ 8}}, {{ 38},{ 8}}, {{166},{ 8}}, {{102},{ 8}},
  81797. {{230},{ 8}}, {{ 22},{ 8}}, {{150},{ 8}}, {{ 86},{ 8}}, {{214},{ 8}},
  81798. {{ 54},{ 8}}, {{182},{ 8}}, {{118},{ 8}}, {{246},{ 8}}, {{ 14},{ 8}},
  81799. {{142},{ 8}}, {{ 78},{ 8}}, {{206},{ 8}}, {{ 46},{ 8}}, {{174},{ 8}},
  81800. {{110},{ 8}}, {{238},{ 8}}, {{ 30},{ 8}}, {{158},{ 8}}, {{ 94},{ 8}},
  81801. {{222},{ 8}}, {{ 62},{ 8}}, {{190},{ 8}}, {{126},{ 8}}, {{254},{ 8}},
  81802. {{ 1},{ 8}}, {{129},{ 8}}, {{ 65},{ 8}}, {{193},{ 8}}, {{ 33},{ 8}},
  81803. {{161},{ 8}}, {{ 97},{ 8}}, {{225},{ 8}}, {{ 17},{ 8}}, {{145},{ 8}},
  81804. {{ 81},{ 8}}, {{209},{ 8}}, {{ 49},{ 8}}, {{177},{ 8}}, {{113},{ 8}},
  81805. {{241},{ 8}}, {{ 9},{ 8}}, {{137},{ 8}}, {{ 73},{ 8}}, {{201},{ 8}},
  81806. {{ 41},{ 8}}, {{169},{ 8}}, {{105},{ 8}}, {{233},{ 8}}, {{ 25},{ 8}},
  81807. {{153},{ 8}}, {{ 89},{ 8}}, {{217},{ 8}}, {{ 57},{ 8}}, {{185},{ 8}},
  81808. {{121},{ 8}}, {{249},{ 8}}, {{ 5},{ 8}}, {{133},{ 8}}, {{ 69},{ 8}},
  81809. {{197},{ 8}}, {{ 37},{ 8}}, {{165},{ 8}}, {{101},{ 8}}, {{229},{ 8}},
  81810. {{ 21},{ 8}}, {{149},{ 8}}, {{ 85},{ 8}}, {{213},{ 8}}, {{ 53},{ 8}},
  81811. {{181},{ 8}}, {{117},{ 8}}, {{245},{ 8}}, {{ 13},{ 8}}, {{141},{ 8}},
  81812. {{ 77},{ 8}}, {{205},{ 8}}, {{ 45},{ 8}}, {{173},{ 8}}, {{109},{ 8}},
  81813. {{237},{ 8}}, {{ 29},{ 8}}, {{157},{ 8}}, {{ 93},{ 8}}, {{221},{ 8}},
  81814. {{ 61},{ 8}}, {{189},{ 8}}, {{125},{ 8}}, {{253},{ 8}}, {{ 19},{ 9}},
  81815. {{275},{ 9}}, {{147},{ 9}}, {{403},{ 9}}, {{ 83},{ 9}}, {{339},{ 9}},
  81816. {{211},{ 9}}, {{467},{ 9}}, {{ 51},{ 9}}, {{307},{ 9}}, {{179},{ 9}},
  81817. {{435},{ 9}}, {{115},{ 9}}, {{371},{ 9}}, {{243},{ 9}}, {{499},{ 9}},
  81818. {{ 11},{ 9}}, {{267},{ 9}}, {{139},{ 9}}, {{395},{ 9}}, {{ 75},{ 9}},
  81819. {{331},{ 9}}, {{203},{ 9}}, {{459},{ 9}}, {{ 43},{ 9}}, {{299},{ 9}},
  81820. {{171},{ 9}}, {{427},{ 9}}, {{107},{ 9}}, {{363},{ 9}}, {{235},{ 9}},
  81821. {{491},{ 9}}, {{ 27},{ 9}}, {{283},{ 9}}, {{155},{ 9}}, {{411},{ 9}},
  81822. {{ 91},{ 9}}, {{347},{ 9}}, {{219},{ 9}}, {{475},{ 9}}, {{ 59},{ 9}},
  81823. {{315},{ 9}}, {{187},{ 9}}, {{443},{ 9}}, {{123},{ 9}}, {{379},{ 9}},
  81824. {{251},{ 9}}, {{507},{ 9}}, {{ 7},{ 9}}, {{263},{ 9}}, {{135},{ 9}},
  81825. {{391},{ 9}}, {{ 71},{ 9}}, {{327},{ 9}}, {{199},{ 9}}, {{455},{ 9}},
  81826. {{ 39},{ 9}}, {{295},{ 9}}, {{167},{ 9}}, {{423},{ 9}}, {{103},{ 9}},
  81827. {{359},{ 9}}, {{231},{ 9}}, {{487},{ 9}}, {{ 23},{ 9}}, {{279},{ 9}},
  81828. {{151},{ 9}}, {{407},{ 9}}, {{ 87},{ 9}}, {{343},{ 9}}, {{215},{ 9}},
  81829. {{471},{ 9}}, {{ 55},{ 9}}, {{311},{ 9}}, {{183},{ 9}}, {{439},{ 9}},
  81830. {{119},{ 9}}, {{375},{ 9}}, {{247},{ 9}}, {{503},{ 9}}, {{ 15},{ 9}},
  81831. {{271},{ 9}}, {{143},{ 9}}, {{399},{ 9}}, {{ 79},{ 9}}, {{335},{ 9}},
  81832. {{207},{ 9}}, {{463},{ 9}}, {{ 47},{ 9}}, {{303},{ 9}}, {{175},{ 9}},
  81833. {{431},{ 9}}, {{111},{ 9}}, {{367},{ 9}}, {{239},{ 9}}, {{495},{ 9}},
  81834. {{ 31},{ 9}}, {{287},{ 9}}, {{159},{ 9}}, {{415},{ 9}}, {{ 95},{ 9}},
  81835. {{351},{ 9}}, {{223},{ 9}}, {{479},{ 9}}, {{ 63},{ 9}}, {{319},{ 9}},
  81836. {{191},{ 9}}, {{447},{ 9}}, {{127},{ 9}}, {{383},{ 9}}, {{255},{ 9}},
  81837. {{511},{ 9}}, {{ 0},{ 7}}, {{ 64},{ 7}}, {{ 32},{ 7}}, {{ 96},{ 7}},
  81838. {{ 16},{ 7}}, {{ 80},{ 7}}, {{ 48},{ 7}}, {{112},{ 7}}, {{ 8},{ 7}},
  81839. {{ 72},{ 7}}, {{ 40},{ 7}}, {{104},{ 7}}, {{ 24},{ 7}}, {{ 88},{ 7}},
  81840. {{ 56},{ 7}}, {{120},{ 7}}, {{ 4},{ 7}}, {{ 68},{ 7}}, {{ 36},{ 7}},
  81841. {{100},{ 7}}, {{ 20},{ 7}}, {{ 84},{ 7}}, {{ 52},{ 7}}, {{116},{ 7}},
  81842. {{ 3},{ 8}}, {{131},{ 8}}, {{ 67},{ 8}}, {{195},{ 8}}, {{ 35},{ 8}},
  81843. {{163},{ 8}}, {{ 99},{ 8}}, {{227},{ 8}}
  81844. };
  81845. local const ct_data static_dtree[D_CODES] = {
  81846. {{ 0},{ 5}}, {{16},{ 5}}, {{ 8},{ 5}}, {{24},{ 5}}, {{ 4},{ 5}},
  81847. {{20},{ 5}}, {{12},{ 5}}, {{28},{ 5}}, {{ 2},{ 5}}, {{18},{ 5}},
  81848. {{10},{ 5}}, {{26},{ 5}}, {{ 6},{ 5}}, {{22},{ 5}}, {{14},{ 5}},
  81849. {{30},{ 5}}, {{ 1},{ 5}}, {{17},{ 5}}, {{ 9},{ 5}}, {{25},{ 5}},
  81850. {{ 5},{ 5}}, {{21},{ 5}}, {{13},{ 5}}, {{29},{ 5}}, {{ 3},{ 5}},
  81851. {{19},{ 5}}, {{11},{ 5}}, {{27},{ 5}}, {{ 7},{ 5}}, {{23},{ 5}}
  81852. };
  81853. const uch _dist_code[DIST_CODE_LEN] = {
  81854. 0, 1, 2, 3, 4, 4, 5, 5, 6, 6, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8,
  81855. 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 10, 10, 10, 10, 10, 10, 10, 10,
  81856. 10, 10, 10, 10, 10, 10, 10, 10, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11,
  81857. 11, 11, 11, 11, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12,
  81858. 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 13, 13, 13, 13,
  81859. 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13,
  81860. 13, 13, 13, 13, 13, 13, 13, 13, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14,
  81861. 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14,
  81862. 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14,
  81863. 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 15, 15, 15, 15, 15, 15, 15, 15,
  81864. 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15,
  81865. 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15,
  81866. 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 0, 0, 16, 17,
  81867. 18, 18, 19, 19, 20, 20, 20, 20, 21, 21, 21, 21, 22, 22, 22, 22, 22, 22, 22, 22,
  81868. 23, 23, 23, 23, 23, 23, 23, 23, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,
  81869. 24, 24, 24, 24, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25,
  81870. 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26,
  81871. 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 27, 27, 27, 27, 27, 27, 27, 27,
  81872. 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27,
  81873. 27, 27, 27, 27, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28,
  81874. 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28,
  81875. 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28,
  81876. 28, 28, 28, 28, 28, 28, 28, 28, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29,
  81877. 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29,
  81878. 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29,
  81879. 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29
  81880. };
  81881. const uch _length_code[MAX_MATCH-MIN_MATCH+1]= {
  81882. 0, 1, 2, 3, 4, 5, 6, 7, 8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 12, 12,
  81883. 13, 13, 13, 13, 14, 14, 14, 14, 15, 15, 15, 15, 16, 16, 16, 16, 16, 16, 16, 16,
  81884. 17, 17, 17, 17, 17, 17, 17, 17, 18, 18, 18, 18, 18, 18, 18, 18, 19, 19, 19, 19,
  81885. 19, 19, 19, 19, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20,
  81886. 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 22, 22, 22, 22,
  81887. 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 23, 23, 23, 23, 23, 23, 23, 23,
  81888. 23, 23, 23, 23, 23, 23, 23, 23, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,
  81889. 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,
  81890. 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25,
  81891. 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 26, 26, 26, 26, 26, 26, 26, 26,
  81892. 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26,
  81893. 26, 26, 26, 26, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27,
  81894. 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 28
  81895. };
  81896. local const int base_length[LENGTH_CODES] = {
  81897. 0, 1, 2, 3, 4, 5, 6, 7, 8, 10, 12, 14, 16, 20, 24, 28, 32, 40, 48, 56,
  81898. 64, 80, 96, 112, 128, 160, 192, 224, 0
  81899. };
  81900. local const int base_dist[D_CODES] = {
  81901. 0, 1, 2, 3, 4, 6, 8, 12, 16, 24,
  81902. 32, 48, 64, 96, 128, 192, 256, 384, 512, 768,
  81903. 1024, 1536, 2048, 3072, 4096, 6144, 8192, 12288, 16384, 24576
  81904. };
  81905. /*** End of inlined file: trees.h ***/
  81906. #endif /* GEN_TREES_H */
  81907. struct static_tree_desc_s {
  81908. const ct_data *static_tree; /* static tree or NULL */
  81909. const intf *extra_bits; /* extra bits for each code or NULL */
  81910. int extra_base; /* base index for extra_bits */
  81911. int elems; /* max number of elements in the tree */
  81912. int max_length; /* max bit length for the codes */
  81913. };
  81914. local static_tree_desc static_l_desc =
  81915. {static_ltree, extra_lbits, LITERALS+1, L_CODES, MAX_BITS};
  81916. local static_tree_desc static_d_desc =
  81917. {static_dtree, extra_dbits, 0, D_CODES, MAX_BITS};
  81918. local static_tree_desc static_bl_desc =
  81919. {(const ct_data *)0, extra_blbits, 0, BL_CODES, MAX_BL_BITS};
  81920. /* ===========================================================================
  81921. * Local (static) routines in this file.
  81922. */
  81923. local void tr_static_init OF((void));
  81924. local void init_block OF((deflate_state *s));
  81925. local void pqdownheap OF((deflate_state *s, ct_data *tree, int k));
  81926. local void gen_bitlen OF((deflate_state *s, tree_desc *desc));
  81927. local void gen_codes OF((ct_data *tree, int max_code, ushf *bl_count));
  81928. local void build_tree OF((deflate_state *s, tree_desc *desc));
  81929. local void scan_tree OF((deflate_state *s, ct_data *tree, int max_code));
  81930. local void send_tree OF((deflate_state *s, ct_data *tree, int max_code));
  81931. local int build_bl_tree OF((deflate_state *s));
  81932. local void send_all_trees OF((deflate_state *s, int lcodes, int dcodes,
  81933. int blcodes));
  81934. local void compress_block OF((deflate_state *s, ct_data *ltree,
  81935. ct_data *dtree));
  81936. local void set_data_type OF((deflate_state *s));
  81937. local unsigned bi_reverse OF((unsigned value, int length));
  81938. local void bi_windup OF((deflate_state *s));
  81939. local void bi_flush OF((deflate_state *s));
  81940. local void copy_block OF((deflate_state *s, charf *buf, unsigned len,
  81941. int header));
  81942. #ifdef GEN_TREES_H
  81943. local void gen_trees_header OF((void));
  81944. #endif
  81945. #ifndef DEBUG
  81946. # define send_code(s, c, tree) send_bits(s, tree[c].Code, tree[c].Len)
  81947. /* Send a code of the given tree. c and tree must not have side effects */
  81948. #else /* DEBUG */
  81949. # define send_code(s, c, tree) \
  81950. { if (z_verbose>2) fprintf(stderr,"\ncd %3d ",(c)); \
  81951. send_bits(s, tree[c].Code, tree[c].Len); }
  81952. #endif
  81953. /* ===========================================================================
  81954. * Output a short LSB first on the stream.
  81955. * IN assertion: there is enough room in pendingBuf.
  81956. */
  81957. #define put_short(s, w) { \
  81958. put_byte(s, (uch)((w) & 0xff)); \
  81959. put_byte(s, (uch)((ush)(w) >> 8)); \
  81960. }
  81961. /* ===========================================================================
  81962. * Send a value on a given number of bits.
  81963. * IN assertion: length <= 16 and value fits in length bits.
  81964. */
  81965. #ifdef DEBUG
  81966. local void send_bits OF((deflate_state *s, int value, int length));
  81967. local void send_bits (deflate_state *s, int value, int length)
  81968. {
  81969. Tracevv((stderr," l %2d v %4x ", length, value));
  81970. Assert(length > 0 && length <= 15, "invalid length");
  81971. s->bits_sent += (ulg)length;
  81972. /* If not enough room in bi_buf, use (valid) bits from bi_buf and
  81973. * (16 - bi_valid) bits from value, leaving (width - (16-bi_valid))
  81974. * unused bits in value.
  81975. */
  81976. if (s->bi_valid > (int)Buf_size - length) {
  81977. s->bi_buf |= (value << s->bi_valid);
  81978. put_short(s, s->bi_buf);
  81979. s->bi_buf = (ush)value >> (Buf_size - s->bi_valid);
  81980. s->bi_valid += length - Buf_size;
  81981. } else {
  81982. s->bi_buf |= value << s->bi_valid;
  81983. s->bi_valid += length;
  81984. }
  81985. }
  81986. #else /* !DEBUG */
  81987. #define send_bits(s, value, length) \
  81988. { int len = length;\
  81989. if (s->bi_valid > (int)Buf_size - len) {\
  81990. int val = value;\
  81991. s->bi_buf |= (val << s->bi_valid);\
  81992. put_short(s, s->bi_buf);\
  81993. s->bi_buf = (ush)val >> (Buf_size - s->bi_valid);\
  81994. s->bi_valid += len - Buf_size;\
  81995. } else {\
  81996. s->bi_buf |= (value) << s->bi_valid;\
  81997. s->bi_valid += len;\
  81998. }\
  81999. }
  82000. #endif /* DEBUG */
  82001. /* the arguments must not have side effects */
  82002. /* ===========================================================================
  82003. * Initialize the various 'constant' tables.
  82004. */
  82005. local void tr_static_init()
  82006. {
  82007. #if defined(GEN_TREES_H) || !defined(STDC)
  82008. static int static_init_done = 0;
  82009. int n; /* iterates over tree elements */
  82010. int bits; /* bit counter */
  82011. int length; /* length value */
  82012. int code; /* code value */
  82013. int dist; /* distance index */
  82014. ush bl_count[MAX_BITS+1];
  82015. /* number of codes at each bit length for an optimal tree */
  82016. if (static_init_done) return;
  82017. /* For some embedded targets, global variables are not initialized: */
  82018. static_l_desc.static_tree = static_ltree;
  82019. static_l_desc.extra_bits = extra_lbits;
  82020. static_d_desc.static_tree = static_dtree;
  82021. static_d_desc.extra_bits = extra_dbits;
  82022. static_bl_desc.extra_bits = extra_blbits;
  82023. /* Initialize the mapping length (0..255) -> length code (0..28) */
  82024. length = 0;
  82025. for (code = 0; code < LENGTH_CODES-1; code++) {
  82026. base_length[code] = length;
  82027. for (n = 0; n < (1<<extra_lbits[code]); n++) {
  82028. _length_code[length++] = (uch)code;
  82029. }
  82030. }
  82031. Assert (length == 256, "tr_static_init: length != 256");
  82032. /* Note that the length 255 (match length 258) can be represented
  82033. * in two different ways: code 284 + 5 bits or code 285, so we
  82034. * overwrite length_code[255] to use the best encoding:
  82035. */
  82036. _length_code[length-1] = (uch)code;
  82037. /* Initialize the mapping dist (0..32K) -> dist code (0..29) */
  82038. dist = 0;
  82039. for (code = 0 ; code < 16; code++) {
  82040. base_dist[code] = dist;
  82041. for (n = 0; n < (1<<extra_dbits[code]); n++) {
  82042. _dist_code[dist++] = (uch)code;
  82043. }
  82044. }
  82045. Assert (dist == 256, "tr_static_init: dist != 256");
  82046. dist >>= 7; /* from now on, all distances are divided by 128 */
  82047. for ( ; code < D_CODES; code++) {
  82048. base_dist[code] = dist << 7;
  82049. for (n = 0; n < (1<<(extra_dbits[code]-7)); n++) {
  82050. _dist_code[256 + dist++] = (uch)code;
  82051. }
  82052. }
  82053. Assert (dist == 256, "tr_static_init: 256+dist != 512");
  82054. /* Construct the codes of the static literal tree */
  82055. for (bits = 0; bits <= MAX_BITS; bits++) bl_count[bits] = 0;
  82056. n = 0;
  82057. while (n <= 143) static_ltree[n++].Len = 8, bl_count[8]++;
  82058. while (n <= 255) static_ltree[n++].Len = 9, bl_count[9]++;
  82059. while (n <= 279) static_ltree[n++].Len = 7, bl_count[7]++;
  82060. while (n <= 287) static_ltree[n++].Len = 8, bl_count[8]++;
  82061. /* Codes 286 and 287 do not exist, but we must include them in the
  82062. * tree construction to get a canonical Huffman tree (longest code
  82063. * all ones)
  82064. */
  82065. gen_codes((ct_data *)static_ltree, L_CODES+1, bl_count);
  82066. /* The static distance tree is trivial: */
  82067. for (n = 0; n < D_CODES; n++) {
  82068. static_dtree[n].Len = 5;
  82069. static_dtree[n].Code = bi_reverse((unsigned)n, 5);
  82070. }
  82071. static_init_done = 1;
  82072. # ifdef GEN_TREES_H
  82073. gen_trees_header();
  82074. # endif
  82075. #endif /* defined(GEN_TREES_H) || !defined(STDC) */
  82076. }
  82077. /* ===========================================================================
  82078. * Genererate the file trees.h describing the static trees.
  82079. */
  82080. #ifdef GEN_TREES_H
  82081. # ifndef DEBUG
  82082. # include <stdio.h>
  82083. # endif
  82084. # define SEPARATOR(i, last, width) \
  82085. ((i) == (last)? "\n};\n\n" : \
  82086. ((i) % (width) == (width)-1 ? ",\n" : ", "))
  82087. void gen_trees_header()
  82088. {
  82089. FILE *header = fopen("trees.h", "w");
  82090. int i;
  82091. Assert (header != NULL, "Can't open trees.h");
  82092. fprintf(header,
  82093. "/* header created automatically with -DGEN_TREES_H */\n\n");
  82094. fprintf(header, "local const ct_data static_ltree[L_CODES+2] = {\n");
  82095. for (i = 0; i < L_CODES+2; i++) {
  82096. fprintf(header, "{{%3u},{%3u}}%s", static_ltree[i].Code,
  82097. static_ltree[i].Len, SEPARATOR(i, L_CODES+1, 5));
  82098. }
  82099. fprintf(header, "local const ct_data static_dtree[D_CODES] = {\n");
  82100. for (i = 0; i < D_CODES; i++) {
  82101. fprintf(header, "{{%2u},{%2u}}%s", static_dtree[i].Code,
  82102. static_dtree[i].Len, SEPARATOR(i, D_CODES-1, 5));
  82103. }
  82104. fprintf(header, "const uch _dist_code[DIST_CODE_LEN] = {\n");
  82105. for (i = 0; i < DIST_CODE_LEN; i++) {
  82106. fprintf(header, "%2u%s", _dist_code[i],
  82107. SEPARATOR(i, DIST_CODE_LEN-1, 20));
  82108. }
  82109. fprintf(header, "const uch _length_code[MAX_MATCH-MIN_MATCH+1]= {\n");
  82110. for (i = 0; i < MAX_MATCH-MIN_MATCH+1; i++) {
  82111. fprintf(header, "%2u%s", _length_code[i],
  82112. SEPARATOR(i, MAX_MATCH-MIN_MATCH, 20));
  82113. }
  82114. fprintf(header, "local const int base_length[LENGTH_CODES] = {\n");
  82115. for (i = 0; i < LENGTH_CODES; i++) {
  82116. fprintf(header, "%1u%s", base_length[i],
  82117. SEPARATOR(i, LENGTH_CODES-1, 20));
  82118. }
  82119. fprintf(header, "local const int base_dist[D_CODES] = {\n");
  82120. for (i = 0; i < D_CODES; i++) {
  82121. fprintf(header, "%5u%s", base_dist[i],
  82122. SEPARATOR(i, D_CODES-1, 10));
  82123. }
  82124. fclose(header);
  82125. }
  82126. #endif /* GEN_TREES_H */
  82127. /* ===========================================================================
  82128. * Initialize the tree data structures for a new zlib stream.
  82129. */
  82130. void _tr_init(deflate_state *s)
  82131. {
  82132. tr_static_init();
  82133. s->l_desc.dyn_tree = s->dyn_ltree;
  82134. s->l_desc.stat_desc = &static_l_desc;
  82135. s->d_desc.dyn_tree = s->dyn_dtree;
  82136. s->d_desc.stat_desc = &static_d_desc;
  82137. s->bl_desc.dyn_tree = s->bl_tree;
  82138. s->bl_desc.stat_desc = &static_bl_desc;
  82139. s->bi_buf = 0;
  82140. s->bi_valid = 0;
  82141. s->last_eob_len = 8; /* enough lookahead for inflate */
  82142. #ifdef DEBUG
  82143. s->compressed_len = 0L;
  82144. s->bits_sent = 0L;
  82145. #endif
  82146. /* Initialize the first block of the first file: */
  82147. init_block(s);
  82148. }
  82149. /* ===========================================================================
  82150. * Initialize a new block.
  82151. */
  82152. local void init_block (deflate_state *s)
  82153. {
  82154. int n; /* iterates over tree elements */
  82155. /* Initialize the trees. */
  82156. for (n = 0; n < L_CODES; n++) s->dyn_ltree[n].Freq = 0;
  82157. for (n = 0; n < D_CODES; n++) s->dyn_dtree[n].Freq = 0;
  82158. for (n = 0; n < BL_CODES; n++) s->bl_tree[n].Freq = 0;
  82159. s->dyn_ltree[END_BLOCK].Freq = 1;
  82160. s->opt_len = s->static_len = 0L;
  82161. s->last_lit = s->matches = 0;
  82162. }
  82163. #define SMALLEST 1
  82164. /* Index within the heap array of least frequent node in the Huffman tree */
  82165. /* ===========================================================================
  82166. * Remove the smallest element from the heap and recreate the heap with
  82167. * one less element. Updates heap and heap_len.
  82168. */
  82169. #define pqremove(s, tree, top) \
  82170. {\
  82171. top = s->heap[SMALLEST]; \
  82172. s->heap[SMALLEST] = s->heap[s->heap_len--]; \
  82173. pqdownheap(s, tree, SMALLEST); \
  82174. }
  82175. /* ===========================================================================
  82176. * Compares to subtrees, using the tree depth as tie breaker when
  82177. * the subtrees have equal frequency. This minimizes the worst case length.
  82178. */
  82179. #define smaller(tree, n, m, depth) \
  82180. (tree[n].Freq < tree[m].Freq || \
  82181. (tree[n].Freq == tree[m].Freq && depth[n] <= depth[m]))
  82182. /* ===========================================================================
  82183. * Restore the heap property by moving down the tree starting at node k,
  82184. * exchanging a node with the smallest of its two sons if necessary, stopping
  82185. * when the heap property is re-established (each father smaller than its
  82186. * two sons).
  82187. */
  82188. local void pqdownheap (deflate_state *s,
  82189. ct_data *tree, /* the tree to restore */
  82190. int k) /* node to move down */
  82191. {
  82192. int v = s->heap[k];
  82193. int j = k << 1; /* left son of k */
  82194. while (j <= s->heap_len) {
  82195. /* Set j to the smallest of the two sons: */
  82196. if (j < s->heap_len &&
  82197. smaller(tree, s->heap[j+1], s->heap[j], s->depth)) {
  82198. j++;
  82199. }
  82200. /* Exit if v is smaller than both sons */
  82201. if (smaller(tree, v, s->heap[j], s->depth)) break;
  82202. /* Exchange v with the smallest son */
  82203. s->heap[k] = s->heap[j]; k = j;
  82204. /* And continue down the tree, setting j to the left son of k */
  82205. j <<= 1;
  82206. }
  82207. s->heap[k] = v;
  82208. }
  82209. /* ===========================================================================
  82210. * Compute the optimal bit lengths for a tree and update the total bit length
  82211. * for the current block.
  82212. * IN assertion: the fields freq and dad are set, heap[heap_max] and
  82213. * above are the tree nodes sorted by increasing frequency.
  82214. * OUT assertions: the field len is set to the optimal bit length, the
  82215. * array bl_count contains the frequencies for each bit length.
  82216. * The length opt_len is updated; static_len is also updated if stree is
  82217. * not null.
  82218. */
  82219. local void gen_bitlen (deflate_state *s, tree_desc *desc)
  82220. {
  82221. ct_data *tree = desc->dyn_tree;
  82222. int max_code = desc->max_code;
  82223. const ct_data *stree = desc->stat_desc->static_tree;
  82224. const intf *extra = desc->stat_desc->extra_bits;
  82225. int base = desc->stat_desc->extra_base;
  82226. int max_length = desc->stat_desc->max_length;
  82227. int h; /* heap index */
  82228. int n, m; /* iterate over the tree elements */
  82229. int bits; /* bit length */
  82230. int xbits; /* extra bits */
  82231. ush f; /* frequency */
  82232. int overflow = 0; /* number of elements with bit length too large */
  82233. for (bits = 0; bits <= MAX_BITS; bits++) s->bl_count[bits] = 0;
  82234. /* In a first pass, compute the optimal bit lengths (which may
  82235. * overflow in the case of the bit length tree).
  82236. */
  82237. tree[s->heap[s->heap_max]].Len = 0; /* root of the heap */
  82238. for (h = s->heap_max+1; h < HEAP_SIZE; h++) {
  82239. n = s->heap[h];
  82240. bits = tree[tree[n].Dad].Len + 1;
  82241. if (bits > max_length) bits = max_length, overflow++;
  82242. tree[n].Len = (ush)bits;
  82243. /* We overwrite tree[n].Dad which is no longer needed */
  82244. if (n > max_code) continue; /* not a leaf node */
  82245. s->bl_count[bits]++;
  82246. xbits = 0;
  82247. if (n >= base) xbits = extra[n-base];
  82248. f = tree[n].Freq;
  82249. s->opt_len += (ulg)f * (bits + xbits);
  82250. if (stree) s->static_len += (ulg)f * (stree[n].Len + xbits);
  82251. }
  82252. if (overflow == 0) return;
  82253. Trace((stderr,"\nbit length overflow\n"));
  82254. /* This happens for example on obj2 and pic of the Calgary corpus */
  82255. /* Find the first bit length which could increase: */
  82256. do {
  82257. bits = max_length-1;
  82258. while (s->bl_count[bits] == 0) bits--;
  82259. s->bl_count[bits]--; /* move one leaf down the tree */
  82260. s->bl_count[bits+1] += 2; /* move one overflow item as its brother */
  82261. s->bl_count[max_length]--;
  82262. /* The brother of the overflow item also moves one step up,
  82263. * but this does not affect bl_count[max_length]
  82264. */
  82265. overflow -= 2;
  82266. } while (overflow > 0);
  82267. /* Now recompute all bit lengths, scanning in increasing frequency.
  82268. * h is still equal to HEAP_SIZE. (It is simpler to reconstruct all
  82269. * lengths instead of fixing only the wrong ones. This idea is taken
  82270. * from 'ar' written by Haruhiko Okumura.)
  82271. */
  82272. for (bits = max_length; bits != 0; bits--) {
  82273. n = s->bl_count[bits];
  82274. while (n != 0) {
  82275. m = s->heap[--h];
  82276. if (m > max_code) continue;
  82277. if ((unsigned) tree[m].Len != (unsigned) bits) {
  82278. Trace((stderr,"code %d bits %d->%d\n", m, tree[m].Len, bits));
  82279. s->opt_len += ((long)bits - (long)tree[m].Len)
  82280. *(long)tree[m].Freq;
  82281. tree[m].Len = (ush)bits;
  82282. }
  82283. n--;
  82284. }
  82285. }
  82286. }
  82287. /* ===========================================================================
  82288. * Generate the codes for a given tree and bit counts (which need not be
  82289. * optimal).
  82290. * IN assertion: the array bl_count contains the bit length statistics for
  82291. * the given tree and the field len is set for all tree elements.
  82292. * OUT assertion: the field code is set for all tree elements of non
  82293. * zero code length.
  82294. */
  82295. local void gen_codes (ct_data *tree, /* the tree to decorate */
  82296. int max_code, /* largest code with non zero frequency */
  82297. ushf *bl_count) /* number of codes at each bit length */
  82298. {
  82299. ush next_code[MAX_BITS+1]; /* next code value for each bit length */
  82300. ush code = 0; /* running code value */
  82301. int bits; /* bit index */
  82302. int n; /* code index */
  82303. /* The distribution counts are first used to generate the code values
  82304. * without bit reversal.
  82305. */
  82306. for (bits = 1; bits <= MAX_BITS; bits++) {
  82307. next_code[bits] = code = (code + bl_count[bits-1]) << 1;
  82308. }
  82309. /* Check that the bit counts in bl_count are consistent. The last code
  82310. * must be all ones.
  82311. */
  82312. Assert (code + bl_count[MAX_BITS]-1 == (1<<MAX_BITS)-1,
  82313. "inconsistent bit counts");
  82314. Tracev((stderr,"\ngen_codes: max_code %d ", max_code));
  82315. for (n = 0; n <= max_code; n++) {
  82316. int len = tree[n].Len;
  82317. if (len == 0) continue;
  82318. /* Now reverse the bits */
  82319. tree[n].Code = bi_reverse(next_code[len]++, len);
  82320. Tracecv(tree != static_ltree, (stderr,"\nn %3d %c l %2d c %4x (%x) ",
  82321. n, (isgraph(n) ? n : ' '), len, tree[n].Code, next_code[len]-1));
  82322. }
  82323. }
  82324. /* ===========================================================================
  82325. * Construct one Huffman tree and assigns the code bit strings and lengths.
  82326. * Update the total bit length for the current block.
  82327. * IN assertion: the field freq is set for all tree elements.
  82328. * OUT assertions: the fields len and code are set to the optimal bit length
  82329. * and corresponding code. The length opt_len is updated; static_len is
  82330. * also updated if stree is not null. The field max_code is set.
  82331. */
  82332. local void build_tree (deflate_state *s,
  82333. tree_desc *desc) /* the tree descriptor */
  82334. {
  82335. ct_data *tree = desc->dyn_tree;
  82336. const ct_data *stree = desc->stat_desc->static_tree;
  82337. int elems = desc->stat_desc->elems;
  82338. int n, m; /* iterate over heap elements */
  82339. int max_code = -1; /* largest code with non zero frequency */
  82340. int node; /* new node being created */
  82341. /* Construct the initial heap, with least frequent element in
  82342. * heap[SMALLEST]. The sons of heap[n] are heap[2*n] and heap[2*n+1].
  82343. * heap[0] is not used.
  82344. */
  82345. s->heap_len = 0, s->heap_max = HEAP_SIZE;
  82346. for (n = 0; n < elems; n++) {
  82347. if (tree[n].Freq != 0) {
  82348. s->heap[++(s->heap_len)] = max_code = n;
  82349. s->depth[n] = 0;
  82350. } else {
  82351. tree[n].Len = 0;
  82352. }
  82353. }
  82354. /* The pkzip format requires that at least one distance code exists,
  82355. * and that at least one bit should be sent even if there is only one
  82356. * possible code. So to avoid special checks later on we force at least
  82357. * two codes of non zero frequency.
  82358. */
  82359. while (s->heap_len < 2) {
  82360. node = s->heap[++(s->heap_len)] = (max_code < 2 ? ++max_code : 0);
  82361. tree[node].Freq = 1;
  82362. s->depth[node] = 0;
  82363. s->opt_len--; if (stree) s->static_len -= stree[node].Len;
  82364. /* node is 0 or 1 so it does not have extra bits */
  82365. }
  82366. desc->max_code = max_code;
  82367. /* The elements heap[heap_len/2+1 .. heap_len] are leaves of the tree,
  82368. * establish sub-heaps of increasing lengths:
  82369. */
  82370. for (n = s->heap_len/2; n >= 1; n--) pqdownheap(s, tree, n);
  82371. /* Construct the Huffman tree by repeatedly combining the least two
  82372. * frequent nodes.
  82373. */
  82374. node = elems; /* next internal node of the tree */
  82375. do {
  82376. pqremove(s, tree, n); /* n = node of least frequency */
  82377. m = s->heap[SMALLEST]; /* m = node of next least frequency */
  82378. s->heap[--(s->heap_max)] = n; /* keep the nodes sorted by frequency */
  82379. s->heap[--(s->heap_max)] = m;
  82380. /* Create a new node father of n and m */
  82381. tree[node].Freq = tree[n].Freq + tree[m].Freq;
  82382. s->depth[node] = (uch)((s->depth[n] >= s->depth[m] ?
  82383. s->depth[n] : s->depth[m]) + 1);
  82384. tree[n].Dad = tree[m].Dad = (ush)node;
  82385. #ifdef DUMP_BL_TREE
  82386. if (tree == s->bl_tree) {
  82387. fprintf(stderr,"\nnode %d(%d), sons %d(%d) %d(%d)",
  82388. node, tree[node].Freq, n, tree[n].Freq, m, tree[m].Freq);
  82389. }
  82390. #endif
  82391. /* and insert the new node in the heap */
  82392. s->heap[SMALLEST] = node++;
  82393. pqdownheap(s, tree, SMALLEST);
  82394. } while (s->heap_len >= 2);
  82395. s->heap[--(s->heap_max)] = s->heap[SMALLEST];
  82396. /* At this point, the fields freq and dad are set. We can now
  82397. * generate the bit lengths.
  82398. */
  82399. gen_bitlen(s, (tree_desc *)desc);
  82400. /* The field len is now set, we can generate the bit codes */
  82401. gen_codes ((ct_data *)tree, max_code, s->bl_count);
  82402. }
  82403. /* ===========================================================================
  82404. * Scan a literal or distance tree to determine the frequencies of the codes
  82405. * in the bit length tree.
  82406. */
  82407. local void scan_tree (deflate_state *s,
  82408. ct_data *tree, /* the tree to be scanned */
  82409. int max_code) /* and its largest code of non zero frequency */
  82410. {
  82411. int n; /* iterates over all tree elements */
  82412. int prevlen = -1; /* last emitted length */
  82413. int curlen; /* length of current code */
  82414. int nextlen = tree[0].Len; /* length of next code */
  82415. int count = 0; /* repeat count of the current code */
  82416. int max_count = 7; /* max repeat count */
  82417. int min_count = 4; /* min repeat count */
  82418. if (nextlen == 0) max_count = 138, min_count = 3;
  82419. tree[max_code+1].Len = (ush)0xffff; /* guard */
  82420. for (n = 0; n <= max_code; n++) {
  82421. curlen = nextlen; nextlen = tree[n+1].Len;
  82422. if (++count < max_count && curlen == nextlen) {
  82423. continue;
  82424. } else if (count < min_count) {
  82425. s->bl_tree[curlen].Freq += count;
  82426. } else if (curlen != 0) {
  82427. if (curlen != prevlen) s->bl_tree[curlen].Freq++;
  82428. s->bl_tree[REP_3_6].Freq++;
  82429. } else if (count <= 10) {
  82430. s->bl_tree[REPZ_3_10].Freq++;
  82431. } else {
  82432. s->bl_tree[REPZ_11_138].Freq++;
  82433. }
  82434. count = 0; prevlen = curlen;
  82435. if (nextlen == 0) {
  82436. max_count = 138, min_count = 3;
  82437. } else if (curlen == nextlen) {
  82438. max_count = 6, min_count = 3;
  82439. } else {
  82440. max_count = 7, min_count = 4;
  82441. }
  82442. }
  82443. }
  82444. /* ===========================================================================
  82445. * Send a literal or distance tree in compressed form, using the codes in
  82446. * bl_tree.
  82447. */
  82448. local void send_tree (deflate_state *s,
  82449. ct_data *tree, /* the tree to be scanned */
  82450. int max_code) /* and its largest code of non zero frequency */
  82451. {
  82452. int n; /* iterates over all tree elements */
  82453. int prevlen = -1; /* last emitted length */
  82454. int curlen; /* length of current code */
  82455. int nextlen = tree[0].Len; /* length of next code */
  82456. int count = 0; /* repeat count of the current code */
  82457. int max_count = 7; /* max repeat count */
  82458. int min_count = 4; /* min repeat count */
  82459. /* tree[max_code+1].Len = -1; */ /* guard already set */
  82460. if (nextlen == 0) max_count = 138, min_count = 3;
  82461. for (n = 0; n <= max_code; n++) {
  82462. curlen = nextlen; nextlen = tree[n+1].Len;
  82463. if (++count < max_count && curlen == nextlen) {
  82464. continue;
  82465. } else if (count < min_count) {
  82466. do { send_code(s, curlen, s->bl_tree); } while (--count != 0);
  82467. } else if (curlen != 0) {
  82468. if (curlen != prevlen) {
  82469. send_code(s, curlen, s->bl_tree); count--;
  82470. }
  82471. Assert(count >= 3 && count <= 6, " 3_6?");
  82472. send_code(s, REP_3_6, s->bl_tree); send_bits(s, count-3, 2);
  82473. } else if (count <= 10) {
  82474. send_code(s, REPZ_3_10, s->bl_tree); send_bits(s, count-3, 3);
  82475. } else {
  82476. send_code(s, REPZ_11_138, s->bl_tree); send_bits(s, count-11, 7);
  82477. }
  82478. count = 0; prevlen = curlen;
  82479. if (nextlen == 0) {
  82480. max_count = 138, min_count = 3;
  82481. } else if (curlen == nextlen) {
  82482. max_count = 6, min_count = 3;
  82483. } else {
  82484. max_count = 7, min_count = 4;
  82485. }
  82486. }
  82487. }
  82488. /* ===========================================================================
  82489. * Construct the Huffman tree for the bit lengths and return the index in
  82490. * bl_order of the last bit length code to send.
  82491. */
  82492. local int build_bl_tree (deflate_state *s)
  82493. {
  82494. int max_blindex; /* index of last bit length code of non zero freq */
  82495. /* Determine the bit length frequencies for literal and distance trees */
  82496. scan_tree(s, (ct_data *)s->dyn_ltree, s->l_desc.max_code);
  82497. scan_tree(s, (ct_data *)s->dyn_dtree, s->d_desc.max_code);
  82498. /* Build the bit length tree: */
  82499. build_tree(s, (tree_desc *)(&(s->bl_desc)));
  82500. /* opt_len now includes the length of the tree representations, except
  82501. * the lengths of the bit lengths codes and the 5+5+4 bits for the counts.
  82502. */
  82503. /* Determine the number of bit length codes to send. The pkzip format
  82504. * requires that at least 4 bit length codes be sent. (appnote.txt says
  82505. * 3 but the actual value used is 4.)
  82506. */
  82507. for (max_blindex = BL_CODES-1; max_blindex >= 3; max_blindex--) {
  82508. if (s->bl_tree[bl_order[max_blindex]].Len != 0) break;
  82509. }
  82510. /* Update opt_len to include the bit length tree and counts */
  82511. s->opt_len += 3*(max_blindex+1) + 5+5+4;
  82512. Tracev((stderr, "\ndyn trees: dyn %ld, stat %ld",
  82513. s->opt_len, s->static_len));
  82514. return max_blindex;
  82515. }
  82516. /* ===========================================================================
  82517. * Send the header for a block using dynamic Huffman trees: the counts, the
  82518. * lengths of the bit length codes, the literal tree and the distance tree.
  82519. * IN assertion: lcodes >= 257, dcodes >= 1, blcodes >= 4.
  82520. */
  82521. local void send_all_trees (deflate_state *s,
  82522. int lcodes, int dcodes, int blcodes) /* number of codes for each tree */
  82523. {
  82524. int rank; /* index in bl_order */
  82525. Assert (lcodes >= 257 && dcodes >= 1 && blcodes >= 4, "not enough codes");
  82526. Assert (lcodes <= L_CODES && dcodes <= D_CODES && blcodes <= BL_CODES,
  82527. "too many codes");
  82528. Tracev((stderr, "\nbl counts: "));
  82529. send_bits(s, lcodes-257, 5); /* not +255 as stated in appnote.txt */
  82530. send_bits(s, dcodes-1, 5);
  82531. send_bits(s, blcodes-4, 4); /* not -3 as stated in appnote.txt */
  82532. for (rank = 0; rank < blcodes; rank++) {
  82533. Tracev((stderr, "\nbl code %2d ", bl_order[rank]));
  82534. send_bits(s, s->bl_tree[bl_order[rank]].Len, 3);
  82535. }
  82536. Tracev((stderr, "\nbl tree: sent %ld", s->bits_sent));
  82537. send_tree(s, (ct_data *)s->dyn_ltree, lcodes-1); /* literal tree */
  82538. Tracev((stderr, "\nlit tree: sent %ld", s->bits_sent));
  82539. send_tree(s, (ct_data *)s->dyn_dtree, dcodes-1); /* distance tree */
  82540. Tracev((stderr, "\ndist tree: sent %ld", s->bits_sent));
  82541. }
  82542. /* ===========================================================================
  82543. * Send a stored block
  82544. */
  82545. void _tr_stored_block (deflate_state *s, charf *buf, ulg stored_len, int eof)
  82546. {
  82547. send_bits(s, (STORED_BLOCK<<1)+eof, 3); /* send block type */
  82548. #ifdef DEBUG
  82549. s->compressed_len = (s->compressed_len + 3 + 7) & (ulg)~7L;
  82550. s->compressed_len += (stored_len + 4) << 3;
  82551. #endif
  82552. copy_block(s, buf, (unsigned)stored_len, 1); /* with header */
  82553. }
  82554. /* ===========================================================================
  82555. * Send one empty static block to give enough lookahead for inflate.
  82556. * This takes 10 bits, of which 7 may remain in the bit buffer.
  82557. * The current inflate code requires 9 bits of lookahead. If the
  82558. * last two codes for the previous block (real code plus EOB) were coded
  82559. * on 5 bits or less, inflate may have only 5+3 bits of lookahead to decode
  82560. * the last real code. In this case we send two empty static blocks instead
  82561. * of one. (There are no problems if the previous block is stored or fixed.)
  82562. * To simplify the code, we assume the worst case of last real code encoded
  82563. * on one bit only.
  82564. */
  82565. void _tr_align (deflate_state *s)
  82566. {
  82567. send_bits(s, STATIC_TREES<<1, 3);
  82568. send_code(s, END_BLOCK, static_ltree);
  82569. #ifdef DEBUG
  82570. s->compressed_len += 10L; /* 3 for block type, 7 for EOB */
  82571. #endif
  82572. bi_flush(s);
  82573. /* Of the 10 bits for the empty block, we have already sent
  82574. * (10 - bi_valid) bits. The lookahead for the last real code (before
  82575. * the EOB of the previous block) was thus at least one plus the length
  82576. * of the EOB plus what we have just sent of the empty static block.
  82577. */
  82578. if (1 + s->last_eob_len + 10 - s->bi_valid < 9) {
  82579. send_bits(s, STATIC_TREES<<1, 3);
  82580. send_code(s, END_BLOCK, static_ltree);
  82581. #ifdef DEBUG
  82582. s->compressed_len += 10L;
  82583. #endif
  82584. bi_flush(s);
  82585. }
  82586. s->last_eob_len = 7;
  82587. }
  82588. /* ===========================================================================
  82589. * Determine the best encoding for the current block: dynamic trees, static
  82590. * trees or store, and output the encoded block to the zip file.
  82591. */
  82592. void _tr_flush_block (deflate_state *s,
  82593. charf *buf, /* input block, or NULL if too old */
  82594. ulg stored_len, /* length of input block */
  82595. int eof) /* true if this is the last block for a file */
  82596. {
  82597. ulg opt_lenb, static_lenb; /* opt_len and static_len in bytes */
  82598. int max_blindex = 0; /* index of last bit length code of non zero freq */
  82599. /* Build the Huffman trees unless a stored block is forced */
  82600. if (s->level > 0) {
  82601. /* Check if the file is binary or text */
  82602. if (stored_len > 0 && s->strm->data_type == Z_UNKNOWN)
  82603. set_data_type(s);
  82604. /* Construct the literal and distance trees */
  82605. build_tree(s, (tree_desc *)(&(s->l_desc)));
  82606. Tracev((stderr, "\nlit data: dyn %ld, stat %ld", s->opt_len,
  82607. s->static_len));
  82608. build_tree(s, (tree_desc *)(&(s->d_desc)));
  82609. Tracev((stderr, "\ndist data: dyn %ld, stat %ld", s->opt_len,
  82610. s->static_len));
  82611. /* At this point, opt_len and static_len are the total bit lengths of
  82612. * the compressed block data, excluding the tree representations.
  82613. */
  82614. /* Build the bit length tree for the above two trees, and get the index
  82615. * in bl_order of the last bit length code to send.
  82616. */
  82617. max_blindex = build_bl_tree(s);
  82618. /* Determine the best encoding. Compute the block lengths in bytes. */
  82619. opt_lenb = (s->opt_len+3+7)>>3;
  82620. static_lenb = (s->static_len+3+7)>>3;
  82621. Tracev((stderr, "\nopt %lu(%lu) stat %lu(%lu) stored %lu lit %u ",
  82622. opt_lenb, s->opt_len, static_lenb, s->static_len, stored_len,
  82623. s->last_lit));
  82624. if (static_lenb <= opt_lenb) opt_lenb = static_lenb;
  82625. } else {
  82626. Assert(buf != (char*)0, "lost buf");
  82627. opt_lenb = static_lenb = stored_len + 5; /* force a stored block */
  82628. }
  82629. #ifdef FORCE_STORED
  82630. if (buf != (char*)0) { /* force stored block */
  82631. #else
  82632. if (stored_len+4 <= opt_lenb && buf != (char*)0) {
  82633. /* 4: two words for the lengths */
  82634. #endif
  82635. /* The test buf != NULL is only necessary if LIT_BUFSIZE > WSIZE.
  82636. * Otherwise we can't have processed more than WSIZE input bytes since
  82637. * the last block flush, because compression would have been
  82638. * successful. If LIT_BUFSIZE <= WSIZE, it is never too late to
  82639. * transform a block into a stored block.
  82640. */
  82641. _tr_stored_block(s, buf, stored_len, eof);
  82642. #ifdef FORCE_STATIC
  82643. } else if (static_lenb >= 0) { /* force static trees */
  82644. #else
  82645. } else if (s->strategy == Z_FIXED || static_lenb == opt_lenb) {
  82646. #endif
  82647. send_bits(s, (STATIC_TREES<<1)+eof, 3);
  82648. compress_block(s, (ct_data *)static_ltree, (ct_data *)static_dtree);
  82649. #ifdef DEBUG
  82650. s->compressed_len += 3 + s->static_len;
  82651. #endif
  82652. } else {
  82653. send_bits(s, (DYN_TREES<<1)+eof, 3);
  82654. send_all_trees(s, s->l_desc.max_code+1, s->d_desc.max_code+1,
  82655. max_blindex+1);
  82656. compress_block(s, (ct_data *)s->dyn_ltree, (ct_data *)s->dyn_dtree);
  82657. #ifdef DEBUG
  82658. s->compressed_len += 3 + s->opt_len;
  82659. #endif
  82660. }
  82661. Assert (s->compressed_len == s->bits_sent, "bad compressed size");
  82662. /* The above check is made mod 2^32, for files larger than 512 MB
  82663. * and uLong implemented on 32 bits.
  82664. */
  82665. init_block(s);
  82666. if (eof) {
  82667. bi_windup(s);
  82668. #ifdef DEBUG
  82669. s->compressed_len += 7; /* align on byte boundary */
  82670. #endif
  82671. }
  82672. Tracev((stderr,"\ncomprlen %lu(%lu) ", s->compressed_len>>3,
  82673. s->compressed_len-7*eof));
  82674. }
  82675. /* ===========================================================================
  82676. * Save the match info and tally the frequency counts. Return true if
  82677. * the current block must be flushed.
  82678. */
  82679. int _tr_tally (deflate_state *s,
  82680. unsigned dist, /* distance of matched string */
  82681. unsigned lc) /* match length-MIN_MATCH or unmatched char (if dist==0) */
  82682. {
  82683. s->d_buf[s->last_lit] = (ush)dist;
  82684. s->l_buf[s->last_lit++] = (uch)lc;
  82685. if (dist == 0) {
  82686. /* lc is the unmatched char */
  82687. s->dyn_ltree[lc].Freq++;
  82688. } else {
  82689. s->matches++;
  82690. /* Here, lc is the match length - MIN_MATCH */
  82691. dist--; /* dist = match distance - 1 */
  82692. Assert((ush)dist < (ush)MAX_DIST(s) &&
  82693. (ush)lc <= (ush)(MAX_MATCH-MIN_MATCH) &&
  82694. (ush)d_code(dist) < (ush)D_CODES, "_tr_tally: bad match");
  82695. s->dyn_ltree[_length_code[lc]+LITERALS+1].Freq++;
  82696. s->dyn_dtree[d_code(dist)].Freq++;
  82697. }
  82698. #ifdef TRUNCATE_BLOCK
  82699. /* Try to guess if it is profitable to stop the current block here */
  82700. if ((s->last_lit & 0x1fff) == 0 && s->level > 2) {
  82701. /* Compute an upper bound for the compressed length */
  82702. ulg out_length = (ulg)s->last_lit*8L;
  82703. ulg in_length = (ulg)((long)s->strstart - s->block_start);
  82704. int dcode;
  82705. for (dcode = 0; dcode < D_CODES; dcode++) {
  82706. out_length += (ulg)s->dyn_dtree[dcode].Freq *
  82707. (5L+extra_dbits[dcode]);
  82708. }
  82709. out_length >>= 3;
  82710. Tracev((stderr,"\nlast_lit %u, in %ld, out ~%ld(%ld%%) ",
  82711. s->last_lit, in_length, out_length,
  82712. 100L - out_length*100L/in_length));
  82713. if (s->matches < s->last_lit/2 && out_length < in_length/2) return 1;
  82714. }
  82715. #endif
  82716. return (s->last_lit == s->lit_bufsize-1);
  82717. /* We avoid equality with lit_bufsize because of wraparound at 64K
  82718. * on 16 bit machines and because stored blocks are restricted to
  82719. * 64K-1 bytes.
  82720. */
  82721. }
  82722. /* ===========================================================================
  82723. * Send the block data compressed using the given Huffman trees
  82724. */
  82725. local void compress_block (deflate_state *s,
  82726. ct_data *ltree, /* literal tree */
  82727. ct_data *dtree) /* distance tree */
  82728. {
  82729. unsigned dist; /* distance of matched string */
  82730. int lc; /* match length or unmatched char (if dist == 0) */
  82731. unsigned lx = 0; /* running index in l_buf */
  82732. unsigned code; /* the code to send */
  82733. int extra; /* number of extra bits to send */
  82734. if (s->last_lit != 0) do {
  82735. dist = s->d_buf[lx];
  82736. lc = s->l_buf[lx++];
  82737. if (dist == 0) {
  82738. send_code(s, lc, ltree); /* send a literal byte */
  82739. Tracecv(isgraph(lc), (stderr," '%c' ", lc));
  82740. } else {
  82741. /* Here, lc is the match length - MIN_MATCH */
  82742. code = _length_code[lc];
  82743. send_code(s, code+LITERALS+1, ltree); /* send the length code */
  82744. extra = extra_lbits[code];
  82745. if (extra != 0) {
  82746. lc -= base_length[code];
  82747. send_bits(s, lc, extra); /* send the extra length bits */
  82748. }
  82749. dist--; /* dist is now the match distance - 1 */
  82750. code = d_code(dist);
  82751. Assert (code < D_CODES, "bad d_code");
  82752. send_code(s, code, dtree); /* send the distance code */
  82753. extra = extra_dbits[code];
  82754. if (extra != 0) {
  82755. dist -= base_dist[code];
  82756. send_bits(s, dist, extra); /* send the extra distance bits */
  82757. }
  82758. } /* literal or match pair ? */
  82759. /* Check that the overlay between pending_buf and d_buf+l_buf is ok: */
  82760. Assert((uInt)(s->pending) < s->lit_bufsize + 2*lx,
  82761. "pendingBuf overflow");
  82762. } while (lx < s->last_lit);
  82763. send_code(s, END_BLOCK, ltree);
  82764. s->last_eob_len = ltree[END_BLOCK].Len;
  82765. }
  82766. /* ===========================================================================
  82767. * Set the data type to BINARY or TEXT, using a crude approximation:
  82768. * set it to Z_TEXT if all symbols are either printable characters (33 to 255)
  82769. * or white spaces (9 to 13, or 32); or set it to Z_BINARY otherwise.
  82770. * IN assertion: the fields Freq of dyn_ltree are set.
  82771. */
  82772. local void set_data_type (deflate_state *s)
  82773. {
  82774. int n;
  82775. for (n = 0; n < 9; n++)
  82776. if (s->dyn_ltree[n].Freq != 0)
  82777. break;
  82778. if (n == 9)
  82779. for (n = 14; n < 32; n++)
  82780. if (s->dyn_ltree[n].Freq != 0)
  82781. break;
  82782. s->strm->data_type = (n == 32) ? Z_TEXT : Z_BINARY;
  82783. }
  82784. /* ===========================================================================
  82785. * Reverse the first len bits of a code, using straightforward code (a faster
  82786. * method would use a table)
  82787. * IN assertion: 1 <= len <= 15
  82788. */
  82789. local unsigned bi_reverse (unsigned code, int len)
  82790. {
  82791. register unsigned res = 0;
  82792. do {
  82793. res |= code & 1;
  82794. code >>= 1, res <<= 1;
  82795. } while (--len > 0);
  82796. return res >> 1;
  82797. }
  82798. /* ===========================================================================
  82799. * Flush the bit buffer, keeping at most 7 bits in it.
  82800. */
  82801. local void bi_flush (deflate_state *s)
  82802. {
  82803. if (s->bi_valid == 16) {
  82804. put_short(s, s->bi_buf);
  82805. s->bi_buf = 0;
  82806. s->bi_valid = 0;
  82807. } else if (s->bi_valid >= 8) {
  82808. put_byte(s, (Byte)s->bi_buf);
  82809. s->bi_buf >>= 8;
  82810. s->bi_valid -= 8;
  82811. }
  82812. }
  82813. /* ===========================================================================
  82814. * Flush the bit buffer and align the output on a byte boundary
  82815. */
  82816. local void bi_windup (deflate_state *s)
  82817. {
  82818. if (s->bi_valid > 8) {
  82819. put_short(s, s->bi_buf);
  82820. } else if (s->bi_valid > 0) {
  82821. put_byte(s, (Byte)s->bi_buf);
  82822. }
  82823. s->bi_buf = 0;
  82824. s->bi_valid = 0;
  82825. #ifdef DEBUG
  82826. s->bits_sent = (s->bits_sent+7) & ~7;
  82827. #endif
  82828. }
  82829. /* ===========================================================================
  82830. * Copy a stored block, storing first the length and its
  82831. * one's complement if requested.
  82832. */
  82833. local void copy_block(deflate_state *s,
  82834. charf *buf, /* the input data */
  82835. unsigned len, /* its length */
  82836. int header) /* true if block header must be written */
  82837. {
  82838. bi_windup(s); /* align on byte boundary */
  82839. s->last_eob_len = 8; /* enough lookahead for inflate */
  82840. if (header) {
  82841. put_short(s, (ush)len);
  82842. put_short(s, (ush)~len);
  82843. #ifdef DEBUG
  82844. s->bits_sent += 2*16;
  82845. #endif
  82846. }
  82847. #ifdef DEBUG
  82848. s->bits_sent += (ulg)len<<3;
  82849. #endif
  82850. while (len--) {
  82851. put_byte(s, *buf++);
  82852. }
  82853. }
  82854. /*** End of inlined file: trees.c ***/
  82855. /*** Start of inlined file: zutil.c ***/
  82856. /* @(#) $Id: zutil.c,v 1.1 2007/06/07 17:54:37 jules_rms Exp $ */
  82857. #ifndef NO_DUMMY_DECL
  82858. struct internal_state {int dummy;}; /* for buggy compilers */
  82859. #endif
  82860. const char * const z_errmsg[10] = {
  82861. "need dictionary", /* Z_NEED_DICT 2 */
  82862. "stream end", /* Z_STREAM_END 1 */
  82863. "", /* Z_OK 0 */
  82864. "file error", /* Z_ERRNO (-1) */
  82865. "stream error", /* Z_STREAM_ERROR (-2) */
  82866. "data error", /* Z_DATA_ERROR (-3) */
  82867. "insufficient memory", /* Z_MEM_ERROR (-4) */
  82868. "buffer error", /* Z_BUF_ERROR (-5) */
  82869. "incompatible version",/* Z_VERSION_ERROR (-6) */
  82870. ""};
  82871. /*const char * ZEXPORT zlibVersion()
  82872. {
  82873. return ZLIB_VERSION;
  82874. }
  82875. uLong ZEXPORT zlibCompileFlags()
  82876. {
  82877. uLong flags;
  82878. flags = 0;
  82879. switch (sizeof(uInt)) {
  82880. case 2: break;
  82881. case 4: flags += 1; break;
  82882. case 8: flags += 2; break;
  82883. default: flags += 3;
  82884. }
  82885. switch (sizeof(uLong)) {
  82886. case 2: break;
  82887. case 4: flags += 1 << 2; break;
  82888. case 8: flags += 2 << 2; break;
  82889. default: flags += 3 << 2;
  82890. }
  82891. switch (sizeof(voidpf)) {
  82892. case 2: break;
  82893. case 4: flags += 1 << 4; break;
  82894. case 8: flags += 2 << 4; break;
  82895. default: flags += 3 << 4;
  82896. }
  82897. switch (sizeof(z_off_t)) {
  82898. case 2: break;
  82899. case 4: flags += 1 << 6; break;
  82900. case 8: flags += 2 << 6; break;
  82901. default: flags += 3 << 6;
  82902. }
  82903. #ifdef DEBUG
  82904. flags += 1 << 8;
  82905. #endif
  82906. #if defined(ASMV) || defined(ASMINF)
  82907. flags += 1 << 9;
  82908. #endif
  82909. #ifdef ZLIB_WINAPI
  82910. flags += 1 << 10;
  82911. #endif
  82912. #ifdef BUILDFIXED
  82913. flags += 1 << 12;
  82914. #endif
  82915. #ifdef DYNAMIC_CRC_TABLE
  82916. flags += 1 << 13;
  82917. #endif
  82918. #ifdef NO_GZCOMPRESS
  82919. flags += 1L << 16;
  82920. #endif
  82921. #ifdef NO_GZIP
  82922. flags += 1L << 17;
  82923. #endif
  82924. #ifdef PKZIP_BUG_WORKAROUND
  82925. flags += 1L << 20;
  82926. #endif
  82927. #ifdef FASTEST
  82928. flags += 1L << 21;
  82929. #endif
  82930. #ifdef STDC
  82931. # ifdef NO_vsnprintf
  82932. flags += 1L << 25;
  82933. # ifdef HAS_vsprintf_void
  82934. flags += 1L << 26;
  82935. # endif
  82936. # else
  82937. # ifdef HAS_vsnprintf_void
  82938. flags += 1L << 26;
  82939. # endif
  82940. # endif
  82941. #else
  82942. flags += 1L << 24;
  82943. # ifdef NO_snprintf
  82944. flags += 1L << 25;
  82945. # ifdef HAS_sprintf_void
  82946. flags += 1L << 26;
  82947. # endif
  82948. # else
  82949. # ifdef HAS_snprintf_void
  82950. flags += 1L << 26;
  82951. # endif
  82952. # endif
  82953. #endif
  82954. return flags;
  82955. }*/
  82956. #ifdef DEBUG
  82957. # ifndef verbose
  82958. # define verbose 0
  82959. # endif
  82960. int z_verbose = verbose;
  82961. void z_error (const char *m)
  82962. {
  82963. fprintf(stderr, "%s\n", m);
  82964. exit(1);
  82965. }
  82966. #endif
  82967. /* exported to allow conversion of error code to string for compress() and
  82968. * uncompress()
  82969. */
  82970. const char * ZEXPORT zError(int err)
  82971. {
  82972. return ERR_MSG(err);
  82973. }
  82974. #if defined(_WIN32_WCE)
  82975. /* The Microsoft C Run-Time Library for Windows CE doesn't have
  82976. * errno. We define it as a global variable to simplify porting.
  82977. * Its value is always 0 and should not be used.
  82978. */
  82979. int errno = 0;
  82980. #endif
  82981. #ifndef HAVE_MEMCPY
  82982. void zmemcpy(dest, source, len)
  82983. Bytef* dest;
  82984. const Bytef* source;
  82985. uInt len;
  82986. {
  82987. if (len == 0) return;
  82988. do {
  82989. *dest++ = *source++; /* ??? to be unrolled */
  82990. } while (--len != 0);
  82991. }
  82992. int zmemcmp(s1, s2, len)
  82993. const Bytef* s1;
  82994. const Bytef* s2;
  82995. uInt len;
  82996. {
  82997. uInt j;
  82998. for (j = 0; j < len; j++) {
  82999. if (s1[j] != s2[j]) return 2*(s1[j] > s2[j])-1;
  83000. }
  83001. return 0;
  83002. }
  83003. void zmemzero(dest, len)
  83004. Bytef* dest;
  83005. uInt len;
  83006. {
  83007. if (len == 0) return;
  83008. do {
  83009. *dest++ = 0; /* ??? to be unrolled */
  83010. } while (--len != 0);
  83011. }
  83012. #endif
  83013. #ifdef SYS16BIT
  83014. #ifdef __TURBOC__
  83015. /* Turbo C in 16-bit mode */
  83016. # define MY_ZCALLOC
  83017. /* Turbo C malloc() does not allow dynamic allocation of 64K bytes
  83018. * and farmalloc(64K) returns a pointer with an offset of 8, so we
  83019. * must fix the pointer. Warning: the pointer must be put back to its
  83020. * original form in order to free it, use zcfree().
  83021. */
  83022. #define MAX_PTR 10
  83023. /* 10*64K = 640K */
  83024. local int next_ptr = 0;
  83025. typedef struct ptr_table_s {
  83026. voidpf org_ptr;
  83027. voidpf new_ptr;
  83028. } ptr_table;
  83029. local ptr_table table[MAX_PTR];
  83030. /* This table is used to remember the original form of pointers
  83031. * to large buffers (64K). Such pointers are normalized with a zero offset.
  83032. * Since MSDOS is not a preemptive multitasking OS, this table is not
  83033. * protected from concurrent access. This hack doesn't work anyway on
  83034. * a protected system like OS/2. Use Microsoft C instead.
  83035. */
  83036. voidpf zcalloc (voidpf opaque, unsigned items, unsigned size)
  83037. {
  83038. voidpf buf = opaque; /* just to make some compilers happy */
  83039. ulg bsize = (ulg)items*size;
  83040. /* If we allocate less than 65520 bytes, we assume that farmalloc
  83041. * will return a usable pointer which doesn't have to be normalized.
  83042. */
  83043. if (bsize < 65520L) {
  83044. buf = farmalloc(bsize);
  83045. if (*(ush*)&buf != 0) return buf;
  83046. } else {
  83047. buf = farmalloc(bsize + 16L);
  83048. }
  83049. if (buf == NULL || next_ptr >= MAX_PTR) return NULL;
  83050. table[next_ptr].org_ptr = buf;
  83051. /* Normalize the pointer to seg:0 */
  83052. *((ush*)&buf+1) += ((ush)((uch*)buf-0) + 15) >> 4;
  83053. *(ush*)&buf = 0;
  83054. table[next_ptr++].new_ptr = buf;
  83055. return buf;
  83056. }
  83057. void zcfree (voidpf opaque, voidpf ptr)
  83058. {
  83059. int n;
  83060. if (*(ush*)&ptr != 0) { /* object < 64K */
  83061. farfree(ptr);
  83062. return;
  83063. }
  83064. /* Find the original pointer */
  83065. for (n = 0; n < next_ptr; n++) {
  83066. if (ptr != table[n].new_ptr) continue;
  83067. farfree(table[n].org_ptr);
  83068. while (++n < next_ptr) {
  83069. table[n-1] = table[n];
  83070. }
  83071. next_ptr--;
  83072. return;
  83073. }
  83074. ptr = opaque; /* just to make some compilers happy */
  83075. Assert(0, "zcfree: ptr not found");
  83076. }
  83077. #endif /* __TURBOC__ */
  83078. #ifdef M_I86
  83079. /* Microsoft C in 16-bit mode */
  83080. # define MY_ZCALLOC
  83081. #if (!defined(_MSC_VER) || (_MSC_VER <= 600))
  83082. # define _halloc halloc
  83083. # define _hfree hfree
  83084. #endif
  83085. voidpf zcalloc (voidpf opaque, unsigned items, unsigned size)
  83086. {
  83087. if (opaque) opaque = 0; /* to make compiler happy */
  83088. return _halloc((long)items, size);
  83089. }
  83090. void zcfree (voidpf opaque, voidpf ptr)
  83091. {
  83092. if (opaque) opaque = 0; /* to make compiler happy */
  83093. _hfree(ptr);
  83094. }
  83095. #endif /* M_I86 */
  83096. #endif /* SYS16BIT */
  83097. #ifndef MY_ZCALLOC /* Any system without a special alloc function */
  83098. #ifndef STDC
  83099. extern voidp malloc OF((uInt size));
  83100. extern voidp calloc OF((uInt items, uInt size));
  83101. extern void free OF((voidpf ptr));
  83102. #endif
  83103. voidpf zcalloc (voidpf opaque, unsigned items, unsigned size)
  83104. {
  83105. if (opaque) items += size - size; /* make compiler happy */
  83106. return sizeof(uInt) > 2 ? (voidpf)malloc(items * size) :
  83107. (voidpf)calloc(items, size);
  83108. }
  83109. void zcfree (voidpf opaque, voidpf ptr)
  83110. {
  83111. free(ptr);
  83112. if (opaque) return; /* make compiler happy */
  83113. }
  83114. #endif /* MY_ZCALLOC */
  83115. /*** End of inlined file: zutil.c ***/
  83116. #undef Byte
  83117. }
  83118. #else
  83119. #include <zlib.h>
  83120. #endif
  83121. }
  83122. #if JUCE_MSVC
  83123. #pragma warning (pop)
  83124. #endif
  83125. BEGIN_JUCE_NAMESPACE
  83126. // internal helper object that holds the zlib structures so they don't have to be
  83127. // included publicly.
  83128. class GZIPDecompressHelper
  83129. {
  83130. public:
  83131. GZIPDecompressHelper (const bool noWrap)
  83132. : finished (true),
  83133. needsDictionary (false),
  83134. error (true),
  83135. streamIsValid (false),
  83136. data (0),
  83137. dataSize (0)
  83138. {
  83139. using namespace zlibNamespace;
  83140. zerostruct (stream);
  83141. streamIsValid = (inflateInit2 (&stream, noWrap ? -MAX_WBITS : MAX_WBITS) == Z_OK);
  83142. finished = error = ! streamIsValid;
  83143. }
  83144. ~GZIPDecompressHelper()
  83145. {
  83146. using namespace zlibNamespace;
  83147. if (streamIsValid)
  83148. inflateEnd (&stream);
  83149. }
  83150. bool needsInput() const throw() { return dataSize <= 0; }
  83151. void setInput (uint8* const data_, const int size) throw()
  83152. {
  83153. data = data_;
  83154. dataSize = size;
  83155. }
  83156. int doNextBlock (uint8* const dest, const int destSize)
  83157. {
  83158. using namespace zlibNamespace;
  83159. if (streamIsValid && data != 0 && ! finished)
  83160. {
  83161. stream.next_in = data;
  83162. stream.next_out = dest;
  83163. stream.avail_in = dataSize;
  83164. stream.avail_out = destSize;
  83165. switch (inflate (&stream, Z_PARTIAL_FLUSH))
  83166. {
  83167. case Z_STREAM_END:
  83168. finished = true;
  83169. // deliberate fall-through
  83170. case Z_OK:
  83171. data += dataSize - stream.avail_in;
  83172. dataSize = stream.avail_in;
  83173. return destSize - stream.avail_out;
  83174. case Z_NEED_DICT:
  83175. needsDictionary = true;
  83176. data += dataSize - stream.avail_in;
  83177. dataSize = stream.avail_in;
  83178. break;
  83179. case Z_DATA_ERROR:
  83180. case Z_MEM_ERROR:
  83181. error = true;
  83182. default:
  83183. break;
  83184. }
  83185. }
  83186. return 0;
  83187. }
  83188. bool finished, needsDictionary, error, streamIsValid;
  83189. private:
  83190. zlibNamespace::z_stream stream;
  83191. uint8* data;
  83192. int dataSize;
  83193. GZIPDecompressHelper (const GZIPDecompressHelper&);
  83194. GZIPDecompressHelper& operator= (const GZIPDecompressHelper&);
  83195. };
  83196. const int gzipDecompBufferSize = 32768;
  83197. GZIPDecompressorInputStream::GZIPDecompressorInputStream (InputStream* const sourceStream_,
  83198. const bool deleteSourceWhenDestroyed,
  83199. const bool noWrap_,
  83200. const int64 uncompressedStreamLength_)
  83201. : sourceStream (sourceStream_),
  83202. streamToDelete (deleteSourceWhenDestroyed ? sourceStream_ : 0),
  83203. uncompressedStreamLength (uncompressedStreamLength_),
  83204. noWrap (noWrap_),
  83205. isEof (false),
  83206. activeBufferSize (0),
  83207. originalSourcePos (sourceStream_->getPosition()),
  83208. currentPos (0),
  83209. buffer (gzipDecompBufferSize),
  83210. helper (new GZIPDecompressHelper (noWrap_))
  83211. {
  83212. }
  83213. GZIPDecompressorInputStream::~GZIPDecompressorInputStream()
  83214. {
  83215. }
  83216. int64 GZIPDecompressorInputStream::getTotalLength()
  83217. {
  83218. return uncompressedStreamLength;
  83219. }
  83220. int GZIPDecompressorInputStream::read (void* destBuffer, int howMany)
  83221. {
  83222. if ((howMany > 0) && ! isEof)
  83223. {
  83224. jassert (destBuffer != 0);
  83225. if (destBuffer != 0)
  83226. {
  83227. int numRead = 0;
  83228. uint8* d = static_cast <uint8*> (destBuffer);
  83229. while (! helper->error)
  83230. {
  83231. const int n = helper->doNextBlock (d, howMany);
  83232. currentPos += n;
  83233. if (n == 0)
  83234. {
  83235. if (helper->finished || helper->needsDictionary)
  83236. {
  83237. isEof = true;
  83238. return numRead;
  83239. }
  83240. if (helper->needsInput())
  83241. {
  83242. activeBufferSize = sourceStream->read (buffer, gzipDecompBufferSize);
  83243. if (activeBufferSize > 0)
  83244. {
  83245. helper->setInput (buffer, activeBufferSize);
  83246. }
  83247. else
  83248. {
  83249. isEof = true;
  83250. return numRead;
  83251. }
  83252. }
  83253. }
  83254. else
  83255. {
  83256. numRead += n;
  83257. howMany -= n;
  83258. d += n;
  83259. if (howMany <= 0)
  83260. return numRead;
  83261. }
  83262. }
  83263. }
  83264. }
  83265. return 0;
  83266. }
  83267. bool GZIPDecompressorInputStream::isExhausted()
  83268. {
  83269. return helper->error || isEof;
  83270. }
  83271. int64 GZIPDecompressorInputStream::getPosition()
  83272. {
  83273. return currentPos;
  83274. }
  83275. bool GZIPDecompressorInputStream::setPosition (int64 newPos)
  83276. {
  83277. if (newPos < currentPos)
  83278. {
  83279. // to go backwards, reset the stream and start again..
  83280. isEof = false;
  83281. activeBufferSize = 0;
  83282. currentPos = 0;
  83283. helper = new GZIPDecompressHelper (noWrap);
  83284. sourceStream->setPosition (originalSourcePos);
  83285. }
  83286. skipNextBytes (newPos - currentPos);
  83287. return true;
  83288. }
  83289. END_JUCE_NAMESPACE
  83290. /*** End of inlined file: juce_GZIPDecompressorInputStream.cpp ***/
  83291. #endif
  83292. #if JUCE_BUILD_NATIVE && ! JUCE_ONLY_BUILD_CORE_LIBRARY
  83293. /*** Start of inlined file: juce_FlacAudioFormat.cpp ***/
  83294. #if JUCE_USE_FLAC
  83295. #if JUCE_WINDOWS
  83296. #include <windows.h>
  83297. #endif
  83298. #ifdef _MSC_VER
  83299. #pragma warning (disable : 4505)
  83300. #pragma warning (push)
  83301. #endif
  83302. namespace FlacNamespace
  83303. {
  83304. #if JUCE_INCLUDE_FLAC_CODE
  83305. #define FLAC__NO_DLL 1
  83306. #if ! defined (SIZE_MAX)
  83307. #define SIZE_MAX 0xffffffff
  83308. #endif
  83309. #define __STDC_LIMIT_MACROS 1
  83310. /*** Start of inlined file: all.h ***/
  83311. #ifndef FLAC__ALL_H
  83312. #define FLAC__ALL_H
  83313. /*** Start of inlined file: export.h ***/
  83314. #ifndef FLAC__EXPORT_H
  83315. #define FLAC__EXPORT_H
  83316. /** \file include/FLAC/export.h
  83317. *
  83318. * \brief
  83319. * This module contains #defines and symbols for exporting function
  83320. * calls, and providing version information and compiled-in features.
  83321. *
  83322. * See the \link flac_export export \endlink module.
  83323. */
  83324. /** \defgroup flac_export FLAC/export.h: export symbols
  83325. * \ingroup flac
  83326. *
  83327. * \brief
  83328. * This module contains #defines and symbols for exporting function
  83329. * calls, and providing version information and compiled-in features.
  83330. *
  83331. * If you are compiling with MSVC and will link to the static library
  83332. * (libFLAC.lib) you should define FLAC__NO_DLL in your project to
  83333. * make sure the symbols are exported properly.
  83334. *
  83335. * \{
  83336. */
  83337. #if defined(FLAC__NO_DLL) || !defined(_MSC_VER)
  83338. #define FLAC_API
  83339. #else
  83340. #ifdef FLAC_API_EXPORTS
  83341. #define FLAC_API _declspec(dllexport)
  83342. #else
  83343. #define FLAC_API _declspec(dllimport)
  83344. #endif
  83345. #endif
  83346. /** These #defines will mirror the libtool-based library version number, see
  83347. * http://www.gnu.org/software/libtool/manual.html#Libtool-versioning
  83348. */
  83349. #define FLAC_API_VERSION_CURRENT 10
  83350. #define FLAC_API_VERSION_REVISION 0 /**< see above */
  83351. #define FLAC_API_VERSION_AGE 2 /**< see above */
  83352. #ifdef __cplusplus
  83353. extern "C" {
  83354. #endif
  83355. /** \c 1 if the library has been compiled with support for Ogg FLAC, else \c 0. */
  83356. extern FLAC_API int FLAC_API_SUPPORTS_OGG_FLAC;
  83357. #ifdef __cplusplus
  83358. }
  83359. #endif
  83360. /* \} */
  83361. #endif
  83362. /*** End of inlined file: export.h ***/
  83363. /*** Start of inlined file: assert.h ***/
  83364. #ifndef FLAC__ASSERT_H
  83365. #define FLAC__ASSERT_H
  83366. /* we need this since some compilers (like MSVC) leave assert()s on release code (and we don't want to use their ASSERT) */
  83367. #ifdef DEBUG
  83368. #include <assert.h>
  83369. #define FLAC__ASSERT(x) assert(x)
  83370. #define FLAC__ASSERT_DECLARATION(x) x
  83371. #else
  83372. #define FLAC__ASSERT(x)
  83373. #define FLAC__ASSERT_DECLARATION(x)
  83374. #endif
  83375. #endif
  83376. /*** End of inlined file: assert.h ***/
  83377. /*** Start of inlined file: callback.h ***/
  83378. #ifndef FLAC__CALLBACK_H
  83379. #define FLAC__CALLBACK_H
  83380. /*** Start of inlined file: ordinals.h ***/
  83381. #ifndef FLAC__ORDINALS_H
  83382. #define FLAC__ORDINALS_H
  83383. #if !(defined(_MSC_VER) || defined(__BORLANDC__) || defined(__EMX__))
  83384. #include <inttypes.h>
  83385. #endif
  83386. typedef signed char FLAC__int8;
  83387. typedef unsigned char FLAC__uint8;
  83388. #if defined(_MSC_VER) || defined(__BORLANDC__)
  83389. typedef __int16 FLAC__int16;
  83390. typedef __int32 FLAC__int32;
  83391. typedef __int64 FLAC__int64;
  83392. typedef unsigned __int16 FLAC__uint16;
  83393. typedef unsigned __int32 FLAC__uint32;
  83394. typedef unsigned __int64 FLAC__uint64;
  83395. #elif defined(__EMX__)
  83396. typedef short FLAC__int16;
  83397. typedef long FLAC__int32;
  83398. typedef long long FLAC__int64;
  83399. typedef unsigned short FLAC__uint16;
  83400. typedef unsigned long FLAC__uint32;
  83401. typedef unsigned long long FLAC__uint64;
  83402. #else
  83403. typedef int16_t FLAC__int16;
  83404. typedef int32_t FLAC__int32;
  83405. typedef int64_t FLAC__int64;
  83406. typedef uint16_t FLAC__uint16;
  83407. typedef uint32_t FLAC__uint32;
  83408. typedef uint64_t FLAC__uint64;
  83409. #endif
  83410. typedef int FLAC__bool;
  83411. typedef FLAC__uint8 FLAC__byte;
  83412. #ifdef true
  83413. #undef true
  83414. #endif
  83415. #ifdef false
  83416. #undef false
  83417. #endif
  83418. #ifndef __cplusplus
  83419. #define true 1
  83420. #define false 0
  83421. #endif
  83422. #endif
  83423. /*** End of inlined file: ordinals.h ***/
  83424. #include <stdlib.h> /* for size_t */
  83425. /** \file include/FLAC/callback.h
  83426. *
  83427. * \brief
  83428. * This module defines the structures for describing I/O callbacks
  83429. * to the other FLAC interfaces.
  83430. *
  83431. * See the detailed documentation for callbacks in the
  83432. * \link flac_callbacks callbacks \endlink module.
  83433. */
  83434. /** \defgroup flac_callbacks FLAC/callback.h: I/O callback structures
  83435. * \ingroup flac
  83436. *
  83437. * \brief
  83438. * This module defines the structures for describing I/O callbacks
  83439. * to the other FLAC interfaces.
  83440. *
  83441. * The purpose of the I/O callback functions is to create a common way
  83442. * for the metadata interfaces to handle I/O.
  83443. *
  83444. * Originally the metadata interfaces required filenames as the way of
  83445. * specifying FLAC files to operate on. This is problematic in some
  83446. * environments so there is an additional option to specify a set of
  83447. * callbacks for doing I/O on the FLAC file, instead of the filename.
  83448. *
  83449. * In addition to the callbacks, a FLAC__IOHandle type is defined as an
  83450. * opaque structure for a data source.
  83451. *
  83452. * The callback function prototypes are similar (but not identical) to the
  83453. * stdio functions fread, fwrite, fseek, ftell, feof, and fclose. If you use
  83454. * stdio streams to implement the callbacks, you can pass fread, fwrite, and
  83455. * fclose anywhere a FLAC__IOCallback_Read, FLAC__IOCallback_Write, or
  83456. * FLAC__IOCallback_Close is required, and a FILE* anywhere a FLAC__IOHandle
  83457. * is required. \warning You generally CANNOT directly use fseek or ftell
  83458. * for FLAC__IOCallback_Seek or FLAC__IOCallback_Tell since on most systems
  83459. * these use 32-bit offsets and FLAC requires 64-bit offsets to deal with
  83460. * large files. You will have to find an equivalent function (e.g. ftello),
  83461. * or write a wrapper. The same is true for feof() since this is usually
  83462. * implemented as a macro, not as a function whose address can be taken.
  83463. *
  83464. * \{
  83465. */
  83466. #ifdef __cplusplus
  83467. extern "C" {
  83468. #endif
  83469. /** This is the opaque handle type used by the callbacks. Typically
  83470. * this is a \c FILE* or address of a file descriptor.
  83471. */
  83472. typedef void* FLAC__IOHandle;
  83473. /** Signature for the read callback.
  83474. * The signature and semantics match POSIX fread() implementations
  83475. * and can generally be used interchangeably.
  83476. *
  83477. * \param ptr The address of the read buffer.
  83478. * \param size The size of the records to be read.
  83479. * \param nmemb The number of records to be read.
  83480. * \param handle The handle to the data source.
  83481. * \retval size_t
  83482. * The number of records read.
  83483. */
  83484. typedef size_t (*FLAC__IOCallback_Read) (void *ptr, size_t size, size_t nmemb, FLAC__IOHandle handle);
  83485. /** Signature for the write callback.
  83486. * The signature and semantics match POSIX fwrite() implementations
  83487. * and can generally be used interchangeably.
  83488. *
  83489. * \param ptr The address of the write buffer.
  83490. * \param size The size of the records to be written.
  83491. * \param nmemb The number of records to be written.
  83492. * \param handle The handle to the data source.
  83493. * \retval size_t
  83494. * The number of records written.
  83495. */
  83496. typedef size_t (*FLAC__IOCallback_Write) (const void *ptr, size_t size, size_t nmemb, FLAC__IOHandle handle);
  83497. /** Signature for the seek callback.
  83498. * The signature and semantics mostly match POSIX fseek() WITH ONE IMPORTANT
  83499. * EXCEPTION: the offset is a 64-bit type whereas fseek() is generally 'long'
  83500. * and 32-bits wide.
  83501. *
  83502. * \param handle The handle to the data source.
  83503. * \param offset The new position, relative to \a whence
  83504. * \param whence \c SEEK_SET, \c SEEK_CUR, or \c SEEK_END
  83505. * \retval int
  83506. * \c 0 on success, \c -1 on error.
  83507. */
  83508. typedef int (*FLAC__IOCallback_Seek) (FLAC__IOHandle handle, FLAC__int64 offset, int whence);
  83509. /** Signature for the tell callback.
  83510. * The signature and semantics mostly match POSIX ftell() WITH ONE IMPORTANT
  83511. * EXCEPTION: the offset is a 64-bit type whereas ftell() is generally 'long'
  83512. * and 32-bits wide.
  83513. *
  83514. * \param handle The handle to the data source.
  83515. * \retval FLAC__int64
  83516. * The current position on success, \c -1 on error.
  83517. */
  83518. typedef FLAC__int64 (*FLAC__IOCallback_Tell) (FLAC__IOHandle handle);
  83519. /** Signature for the EOF callback.
  83520. * The signature and semantics mostly match POSIX feof() but WATCHOUT:
  83521. * on many systems, feof() is a macro, so in this case a wrapper function
  83522. * must be provided instead.
  83523. *
  83524. * \param handle The handle to the data source.
  83525. * \retval int
  83526. * \c 0 if not at end of file, nonzero if at end of file.
  83527. */
  83528. typedef int (*FLAC__IOCallback_Eof) (FLAC__IOHandle handle);
  83529. /** Signature for the close callback.
  83530. * The signature and semantics match POSIX fclose() implementations
  83531. * and can generally be used interchangeably.
  83532. *
  83533. * \param handle The handle to the data source.
  83534. * \retval int
  83535. * \c 0 on success, \c EOF on error.
  83536. */
  83537. typedef int (*FLAC__IOCallback_Close) (FLAC__IOHandle handle);
  83538. /** A structure for holding a set of callbacks.
  83539. * Each FLAC interface that requires a FLAC__IOCallbacks structure will
  83540. * describe which of the callbacks are required. The ones that are not
  83541. * required may be set to NULL.
  83542. *
  83543. * If the seek requirement for an interface is optional, you can signify that
  83544. * a data sorce is not seekable by setting the \a seek field to \c NULL.
  83545. */
  83546. typedef struct {
  83547. FLAC__IOCallback_Read read;
  83548. FLAC__IOCallback_Write write;
  83549. FLAC__IOCallback_Seek seek;
  83550. FLAC__IOCallback_Tell tell;
  83551. FLAC__IOCallback_Eof eof;
  83552. FLAC__IOCallback_Close close;
  83553. } FLAC__IOCallbacks;
  83554. /* \} */
  83555. #ifdef __cplusplus
  83556. }
  83557. #endif
  83558. #endif
  83559. /*** End of inlined file: callback.h ***/
  83560. /*** Start of inlined file: format.h ***/
  83561. #ifndef FLAC__FORMAT_H
  83562. #define FLAC__FORMAT_H
  83563. #ifdef __cplusplus
  83564. extern "C" {
  83565. #endif
  83566. /** \file include/FLAC/format.h
  83567. *
  83568. * \brief
  83569. * This module contains structure definitions for the representation
  83570. * of FLAC format components in memory. These are the basic
  83571. * structures used by the rest of the interfaces.
  83572. *
  83573. * See the detailed documentation in the
  83574. * \link flac_format format \endlink module.
  83575. */
  83576. /** \defgroup flac_format FLAC/format.h: format components
  83577. * \ingroup flac
  83578. *
  83579. * \brief
  83580. * This module contains structure definitions for the representation
  83581. * of FLAC format components in memory. These are the basic
  83582. * structures used by the rest of the interfaces.
  83583. *
  83584. * First, you should be familiar with the
  83585. * <A HREF="../format.html">FLAC format</A>. Many of the values here
  83586. * follow directly from the specification. As a user of libFLAC, the
  83587. * interesting parts really are the structures that describe the frame
  83588. * header and metadata blocks.
  83589. *
  83590. * The format structures here are very primitive, designed to store
  83591. * information in an efficient way. Reading information from the
  83592. * structures is easy but creating or modifying them directly is
  83593. * more complex. For the most part, as a user of a library, editing
  83594. * is not necessary; however, for metadata blocks it is, so there are
  83595. * convenience functions provided in the \link flac_metadata metadata
  83596. * module \endlink to simplify the manipulation of metadata blocks.
  83597. *
  83598. * \note
  83599. * It's not the best convention, but symbols ending in _LEN are in bits
  83600. * and _LENGTH are in bytes. _LENGTH symbols are \#defines instead of
  83601. * global variables because they are usually used when declaring byte
  83602. * arrays and some compilers require compile-time knowledge of array
  83603. * sizes when declared on the stack.
  83604. *
  83605. * \{
  83606. */
  83607. /*
  83608. Most of the values described in this file are defined by the FLAC
  83609. format specification. There is nothing to tune here.
  83610. */
  83611. /** The largest legal metadata type code. */
  83612. #define FLAC__MAX_METADATA_TYPE_CODE (126u)
  83613. /** The minimum block size, in samples, permitted by the format. */
  83614. #define FLAC__MIN_BLOCK_SIZE (16u)
  83615. /** The maximum block size, in samples, permitted by the format. */
  83616. #define FLAC__MAX_BLOCK_SIZE (65535u)
  83617. /** The maximum block size, in samples, permitted by the FLAC subset for
  83618. * sample rates up to 48kHz. */
  83619. #define FLAC__SUBSET_MAX_BLOCK_SIZE_48000HZ (4608u)
  83620. /** The maximum number of channels permitted by the format. */
  83621. #define FLAC__MAX_CHANNELS (8u)
  83622. /** The minimum sample resolution permitted by the format. */
  83623. #define FLAC__MIN_BITS_PER_SAMPLE (4u)
  83624. /** The maximum sample resolution permitted by the format. */
  83625. #define FLAC__MAX_BITS_PER_SAMPLE (32u)
  83626. /** The maximum sample resolution permitted by libFLAC.
  83627. *
  83628. * \warning
  83629. * FLAC__MAX_BITS_PER_SAMPLE is the limit of the FLAC format. However,
  83630. * the reference encoder/decoder is currently limited to 24 bits because
  83631. * of prevalent 32-bit math, so make sure and use this value when
  83632. * appropriate.
  83633. */
  83634. #define FLAC__REFERENCE_CODEC_MAX_BITS_PER_SAMPLE (24u)
  83635. /** The maximum sample rate permitted by the format. The value is
  83636. * ((2 ^ 16) - 1) * 10; see <A HREF="../format.html">FLAC format</A>
  83637. * as to why.
  83638. */
  83639. #define FLAC__MAX_SAMPLE_RATE (655350u)
  83640. /** The maximum LPC order permitted by the format. */
  83641. #define FLAC__MAX_LPC_ORDER (32u)
  83642. /** The maximum LPC order permitted by the FLAC subset for sample rates
  83643. * up to 48kHz. */
  83644. #define FLAC__SUBSET_MAX_LPC_ORDER_48000HZ (12u)
  83645. /** The minimum quantized linear predictor coefficient precision
  83646. * permitted by the format.
  83647. */
  83648. #define FLAC__MIN_QLP_COEFF_PRECISION (5u)
  83649. /** The maximum quantized linear predictor coefficient precision
  83650. * permitted by the format.
  83651. */
  83652. #define FLAC__MAX_QLP_COEFF_PRECISION (15u)
  83653. /** The maximum order of the fixed predictors permitted by the format. */
  83654. #define FLAC__MAX_FIXED_ORDER (4u)
  83655. /** The maximum Rice partition order permitted by the format. */
  83656. #define FLAC__MAX_RICE_PARTITION_ORDER (15u)
  83657. /** The maximum Rice partition order permitted by the FLAC Subset. */
  83658. #define FLAC__SUBSET_MAX_RICE_PARTITION_ORDER (8u)
  83659. /** The version string of the release, stamped onto the libraries and binaries.
  83660. *
  83661. * \note
  83662. * This does not correspond to the shared library version number, which
  83663. * is used to determine binary compatibility.
  83664. */
  83665. extern FLAC_API const char *FLAC__VERSION_STRING;
  83666. /** The vendor string inserted by the encoder into the VORBIS_COMMENT block.
  83667. * This is a NUL-terminated ASCII string; when inserted into the
  83668. * VORBIS_COMMENT the trailing null is stripped.
  83669. */
  83670. extern FLAC_API const char *FLAC__VENDOR_STRING;
  83671. /** The byte string representation of the beginning of a FLAC stream. */
  83672. extern FLAC_API const FLAC__byte FLAC__STREAM_SYNC_STRING[4]; /* = "fLaC" */
  83673. /** The 32-bit integer big-endian representation of the beginning of
  83674. * a FLAC stream.
  83675. */
  83676. extern FLAC_API const unsigned FLAC__STREAM_SYNC; /* = 0x664C6143 */
  83677. /** The length of the FLAC signature in bits. */
  83678. extern FLAC_API const unsigned FLAC__STREAM_SYNC_LEN; /* = 32 bits */
  83679. /** The length of the FLAC signature in bytes. */
  83680. #define FLAC__STREAM_SYNC_LENGTH (4u)
  83681. /*****************************************************************************
  83682. *
  83683. * Subframe structures
  83684. *
  83685. *****************************************************************************/
  83686. /*****************************************************************************/
  83687. /** An enumeration of the available entropy coding methods. */
  83688. typedef enum {
  83689. FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE = 0,
  83690. /**< Residual is coded by partitioning into contexts, each with it's own
  83691. * 4-bit Rice parameter. */
  83692. FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2 = 1
  83693. /**< Residual is coded by partitioning into contexts, each with it's own
  83694. * 5-bit Rice parameter. */
  83695. } FLAC__EntropyCodingMethodType;
  83696. /** Maps a FLAC__EntropyCodingMethodType to a C string.
  83697. *
  83698. * Using a FLAC__EntropyCodingMethodType as the index to this array will
  83699. * give the string equivalent. The contents should not be modified.
  83700. */
  83701. extern FLAC_API const char * const FLAC__EntropyCodingMethodTypeString[];
  83702. /** Contents of a Rice partitioned residual
  83703. */
  83704. typedef struct {
  83705. unsigned *parameters;
  83706. /**< The Rice parameters for each context. */
  83707. unsigned *raw_bits;
  83708. /**< Widths for escape-coded partitions. Will be non-zero for escaped
  83709. * partitions and zero for unescaped partitions.
  83710. */
  83711. unsigned capacity_by_order;
  83712. /**< The capacity of the \a parameters and \a raw_bits arrays
  83713. * specified as an order, i.e. the number of array elements
  83714. * allocated is 2 ^ \a capacity_by_order.
  83715. */
  83716. } FLAC__EntropyCodingMethod_PartitionedRiceContents;
  83717. /** Header for a Rice partitioned residual. (c.f. <A HREF="../format.html#partitioned_rice">format specification</A>)
  83718. */
  83719. typedef struct {
  83720. unsigned order;
  83721. /**< The partition order, i.e. # of contexts = 2 ^ \a order. */
  83722. const FLAC__EntropyCodingMethod_PartitionedRiceContents *contents;
  83723. /**< The context's Rice parameters and/or raw bits. */
  83724. } FLAC__EntropyCodingMethod_PartitionedRice;
  83725. extern FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN; /**< == 4 (bits) */
  83726. extern FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_PARAMETER_LEN; /**< == 4 (bits) */
  83727. extern FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_PARAMETER_LEN; /**< == 5 (bits) */
  83728. extern FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_RAW_LEN; /**< == 5 (bits) */
  83729. extern FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER;
  83730. /**< == (1<<FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_PARAMETER_LEN)-1 */
  83731. extern FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_ESCAPE_PARAMETER;
  83732. /**< == (1<<FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_PARAMETER_LEN)-1 */
  83733. /** Header for the entropy coding method. (c.f. <A HREF="../format.html#residual">format specification</A>)
  83734. */
  83735. typedef struct {
  83736. FLAC__EntropyCodingMethodType type;
  83737. union {
  83738. FLAC__EntropyCodingMethod_PartitionedRice partitioned_rice;
  83739. } data;
  83740. } FLAC__EntropyCodingMethod;
  83741. extern FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_TYPE_LEN; /**< == 2 (bits) */
  83742. /*****************************************************************************/
  83743. /** An enumeration of the available subframe types. */
  83744. typedef enum {
  83745. FLAC__SUBFRAME_TYPE_CONSTANT = 0, /**< constant signal */
  83746. FLAC__SUBFRAME_TYPE_VERBATIM = 1, /**< uncompressed signal */
  83747. FLAC__SUBFRAME_TYPE_FIXED = 2, /**< fixed polynomial prediction */
  83748. FLAC__SUBFRAME_TYPE_LPC = 3 /**< linear prediction */
  83749. } FLAC__SubframeType;
  83750. /** Maps a FLAC__SubframeType to a C string.
  83751. *
  83752. * Using a FLAC__SubframeType as the index to this array will
  83753. * give the string equivalent. The contents should not be modified.
  83754. */
  83755. extern FLAC_API const char * const FLAC__SubframeTypeString[];
  83756. /** CONSTANT subframe. (c.f. <A HREF="../format.html#subframe_constant">format specification</A>)
  83757. */
  83758. typedef struct {
  83759. FLAC__int32 value; /**< The constant signal value. */
  83760. } FLAC__Subframe_Constant;
  83761. /** VERBATIM subframe. (c.f. <A HREF="../format.html#subframe_verbatim">format specification</A>)
  83762. */
  83763. typedef struct {
  83764. const FLAC__int32 *data; /**< A pointer to verbatim signal. */
  83765. } FLAC__Subframe_Verbatim;
  83766. /** FIXED subframe. (c.f. <A HREF="../format.html#subframe_fixed">format specification</A>)
  83767. */
  83768. typedef struct {
  83769. FLAC__EntropyCodingMethod entropy_coding_method;
  83770. /**< The residual coding method. */
  83771. unsigned order;
  83772. /**< The polynomial order. */
  83773. FLAC__int32 warmup[FLAC__MAX_FIXED_ORDER];
  83774. /**< Warmup samples to prime the predictor, length == order. */
  83775. const FLAC__int32 *residual;
  83776. /**< The residual signal, length == (blocksize minus order) samples. */
  83777. } FLAC__Subframe_Fixed;
  83778. /** LPC subframe. (c.f. <A HREF="../format.html#subframe_lpc">format specification</A>)
  83779. */
  83780. typedef struct {
  83781. FLAC__EntropyCodingMethod entropy_coding_method;
  83782. /**< The residual coding method. */
  83783. unsigned order;
  83784. /**< The FIR order. */
  83785. unsigned qlp_coeff_precision;
  83786. /**< Quantized FIR filter coefficient precision in bits. */
  83787. int quantization_level;
  83788. /**< The qlp coeff shift needed. */
  83789. FLAC__int32 qlp_coeff[FLAC__MAX_LPC_ORDER];
  83790. /**< FIR filter coefficients. */
  83791. FLAC__int32 warmup[FLAC__MAX_LPC_ORDER];
  83792. /**< Warmup samples to prime the predictor, length == order. */
  83793. const FLAC__int32 *residual;
  83794. /**< The residual signal, length == (blocksize minus order) samples. */
  83795. } FLAC__Subframe_LPC;
  83796. extern FLAC_API const unsigned FLAC__SUBFRAME_LPC_QLP_COEFF_PRECISION_LEN; /**< == 4 (bits) */
  83797. extern FLAC_API const unsigned FLAC__SUBFRAME_LPC_QLP_SHIFT_LEN; /**< == 5 (bits) */
  83798. /** FLAC subframe structure. (c.f. <A HREF="../format.html#subframe">format specification</A>)
  83799. */
  83800. typedef struct {
  83801. FLAC__SubframeType type;
  83802. union {
  83803. FLAC__Subframe_Constant constant;
  83804. FLAC__Subframe_Fixed fixed;
  83805. FLAC__Subframe_LPC lpc;
  83806. FLAC__Subframe_Verbatim verbatim;
  83807. } data;
  83808. unsigned wasted_bits;
  83809. } FLAC__Subframe;
  83810. /** == 1 (bit)
  83811. *
  83812. * This used to be a zero-padding bit (hence the name
  83813. * FLAC__SUBFRAME_ZERO_PAD_LEN) but is now a reserved bit. It still has a
  83814. * mandatory value of \c 0 but in the future may take on the value \c 0 or \c 1
  83815. * to mean something else.
  83816. */
  83817. extern FLAC_API const unsigned FLAC__SUBFRAME_ZERO_PAD_LEN;
  83818. extern FLAC_API const unsigned FLAC__SUBFRAME_TYPE_LEN; /**< == 6 (bits) */
  83819. extern FLAC_API const unsigned FLAC__SUBFRAME_WASTED_BITS_FLAG_LEN; /**< == 1 (bit) */
  83820. extern FLAC_API const unsigned FLAC__SUBFRAME_TYPE_CONSTANT_BYTE_ALIGNED_MASK; /**< = 0x00 */
  83821. extern FLAC_API const unsigned FLAC__SUBFRAME_TYPE_VERBATIM_BYTE_ALIGNED_MASK; /**< = 0x02 */
  83822. extern FLAC_API const unsigned FLAC__SUBFRAME_TYPE_FIXED_BYTE_ALIGNED_MASK; /**< = 0x10 */
  83823. extern FLAC_API const unsigned FLAC__SUBFRAME_TYPE_LPC_BYTE_ALIGNED_MASK; /**< = 0x40 */
  83824. /*****************************************************************************/
  83825. /*****************************************************************************
  83826. *
  83827. * Frame structures
  83828. *
  83829. *****************************************************************************/
  83830. /** An enumeration of the available channel assignments. */
  83831. typedef enum {
  83832. FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT = 0, /**< independent channels */
  83833. FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE = 1, /**< left+side stereo */
  83834. FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE = 2, /**< right+side stereo */
  83835. FLAC__CHANNEL_ASSIGNMENT_MID_SIDE = 3 /**< mid+side stereo */
  83836. } FLAC__ChannelAssignment;
  83837. /** Maps a FLAC__ChannelAssignment to a C string.
  83838. *
  83839. * Using a FLAC__ChannelAssignment as the index to this array will
  83840. * give the string equivalent. The contents should not be modified.
  83841. */
  83842. extern FLAC_API const char * const FLAC__ChannelAssignmentString[];
  83843. /** An enumeration of the possible frame numbering methods. */
  83844. typedef enum {
  83845. FLAC__FRAME_NUMBER_TYPE_FRAME_NUMBER, /**< number contains the frame number */
  83846. FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER /**< number contains the sample number of first sample in frame */
  83847. } FLAC__FrameNumberType;
  83848. /** Maps a FLAC__FrameNumberType to a C string.
  83849. *
  83850. * Using a FLAC__FrameNumberType as the index to this array will
  83851. * give the string equivalent. The contents should not be modified.
  83852. */
  83853. extern FLAC_API const char * const FLAC__FrameNumberTypeString[];
  83854. /** FLAC frame header structure. (c.f. <A HREF="../format.html#frame_header">format specification</A>)
  83855. */
  83856. typedef struct {
  83857. unsigned blocksize;
  83858. /**< The number of samples per subframe. */
  83859. unsigned sample_rate;
  83860. /**< The sample rate in Hz. */
  83861. unsigned channels;
  83862. /**< The number of channels (== number of subframes). */
  83863. FLAC__ChannelAssignment channel_assignment;
  83864. /**< The channel assignment for the frame. */
  83865. unsigned bits_per_sample;
  83866. /**< The sample resolution. */
  83867. FLAC__FrameNumberType number_type;
  83868. /**< The numbering scheme used for the frame. As a convenience, the
  83869. * decoder will always convert a frame number to a sample number because
  83870. * the rules are complex. */
  83871. union {
  83872. FLAC__uint32 frame_number;
  83873. FLAC__uint64 sample_number;
  83874. } number;
  83875. /**< The frame number or sample number of first sample in frame;
  83876. * use the \a number_type value to determine which to use. */
  83877. FLAC__uint8 crc;
  83878. /**< CRC-8 (polynomial = x^8 + x^2 + x^1 + x^0, initialized with 0)
  83879. * of the raw frame header bytes, meaning everything before the CRC byte
  83880. * including the sync code.
  83881. */
  83882. } FLAC__FrameHeader;
  83883. extern FLAC_API const unsigned FLAC__FRAME_HEADER_SYNC; /**< == 0x3ffe; the frame header sync code */
  83884. extern FLAC_API const unsigned FLAC__FRAME_HEADER_SYNC_LEN; /**< == 14 (bits) */
  83885. extern FLAC_API const unsigned FLAC__FRAME_HEADER_RESERVED_LEN; /**< == 1 (bits) */
  83886. extern FLAC_API const unsigned FLAC__FRAME_HEADER_BLOCKING_STRATEGY_LEN; /**< == 1 (bits) */
  83887. extern FLAC_API const unsigned FLAC__FRAME_HEADER_BLOCK_SIZE_LEN; /**< == 4 (bits) */
  83888. extern FLAC_API const unsigned FLAC__FRAME_HEADER_SAMPLE_RATE_LEN; /**< == 4 (bits) */
  83889. extern FLAC_API const unsigned FLAC__FRAME_HEADER_CHANNEL_ASSIGNMENT_LEN; /**< == 4 (bits) */
  83890. extern FLAC_API const unsigned FLAC__FRAME_HEADER_BITS_PER_SAMPLE_LEN; /**< == 3 (bits) */
  83891. extern FLAC_API const unsigned FLAC__FRAME_HEADER_ZERO_PAD_LEN; /**< == 1 (bit) */
  83892. extern FLAC_API const unsigned FLAC__FRAME_HEADER_CRC_LEN; /**< == 8 (bits) */
  83893. /** FLAC frame footer structure. (c.f. <A HREF="../format.html#frame_footer">format specification</A>)
  83894. */
  83895. typedef struct {
  83896. FLAC__uint16 crc;
  83897. /**< CRC-16 (polynomial = x^16 + x^15 + x^2 + x^0, initialized with
  83898. * 0) of the bytes before the crc, back to and including the frame header
  83899. * sync code.
  83900. */
  83901. } FLAC__FrameFooter;
  83902. extern FLAC_API const unsigned FLAC__FRAME_FOOTER_CRC_LEN; /**< == 16 (bits) */
  83903. /** FLAC frame structure. (c.f. <A HREF="../format.html#frame">format specification</A>)
  83904. */
  83905. typedef struct {
  83906. FLAC__FrameHeader header;
  83907. FLAC__Subframe subframes[FLAC__MAX_CHANNELS];
  83908. FLAC__FrameFooter footer;
  83909. } FLAC__Frame;
  83910. /*****************************************************************************/
  83911. /*****************************************************************************
  83912. *
  83913. * Meta-data structures
  83914. *
  83915. *****************************************************************************/
  83916. /** An enumeration of the available metadata block types. */
  83917. typedef enum {
  83918. FLAC__METADATA_TYPE_STREAMINFO = 0,
  83919. /**< <A HREF="../format.html#metadata_block_streaminfo">STREAMINFO</A> block */
  83920. FLAC__METADATA_TYPE_PADDING = 1,
  83921. /**< <A HREF="../format.html#metadata_block_padding">PADDING</A> block */
  83922. FLAC__METADATA_TYPE_APPLICATION = 2,
  83923. /**< <A HREF="../format.html#metadata_block_application">APPLICATION</A> block */
  83924. FLAC__METADATA_TYPE_SEEKTABLE = 3,
  83925. /**< <A HREF="../format.html#metadata_block_seektable">SEEKTABLE</A> block */
  83926. FLAC__METADATA_TYPE_VORBIS_COMMENT = 4,
  83927. /**< <A HREF="../format.html#metadata_block_vorbis_comment">VORBISCOMMENT</A> block (a.k.a. FLAC tags) */
  83928. FLAC__METADATA_TYPE_CUESHEET = 5,
  83929. /**< <A HREF="../format.html#metadata_block_cuesheet">CUESHEET</A> block */
  83930. FLAC__METADATA_TYPE_PICTURE = 6,
  83931. /**< <A HREF="../format.html#metadata_block_picture">PICTURE</A> block */
  83932. FLAC__METADATA_TYPE_UNDEFINED = 7
  83933. /**< marker to denote beginning of undefined type range; this number will increase as new metadata types are added */
  83934. } FLAC__MetadataType;
  83935. /** Maps a FLAC__MetadataType to a C string.
  83936. *
  83937. * Using a FLAC__MetadataType as the index to this array will
  83938. * give the string equivalent. The contents should not be modified.
  83939. */
  83940. extern FLAC_API const char * const FLAC__MetadataTypeString[];
  83941. /** FLAC STREAMINFO structure. (c.f. <A HREF="../format.html#metadata_block_streaminfo">format specification</A>)
  83942. */
  83943. typedef struct {
  83944. unsigned min_blocksize, max_blocksize;
  83945. unsigned min_framesize, max_framesize;
  83946. unsigned sample_rate;
  83947. unsigned channels;
  83948. unsigned bits_per_sample;
  83949. FLAC__uint64 total_samples;
  83950. FLAC__byte md5sum[16];
  83951. } FLAC__StreamMetadata_StreamInfo;
  83952. extern FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN; /**< == 16 (bits) */
  83953. extern FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN; /**< == 16 (bits) */
  83954. extern FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN; /**< == 24 (bits) */
  83955. extern FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN; /**< == 24 (bits) */
  83956. extern FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN; /**< == 20 (bits) */
  83957. extern FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN; /**< == 3 (bits) */
  83958. extern FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN; /**< == 5 (bits) */
  83959. extern FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_TOTAL_SAMPLES_LEN; /**< == 36 (bits) */
  83960. extern FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MD5SUM_LEN; /**< == 128 (bits) */
  83961. /** The total stream length of the STREAMINFO block in bytes. */
  83962. #define FLAC__STREAM_METADATA_STREAMINFO_LENGTH (34u)
  83963. /** FLAC PADDING structure. (c.f. <A HREF="../format.html#metadata_block_padding">format specification</A>)
  83964. */
  83965. typedef struct {
  83966. int dummy;
  83967. /**< Conceptually this is an empty struct since we don't store the
  83968. * padding bytes. Empty structs are not allowed by some C compilers,
  83969. * hence the dummy.
  83970. */
  83971. } FLAC__StreamMetadata_Padding;
  83972. /** FLAC APPLICATION structure. (c.f. <A HREF="../format.html#metadata_block_application">format specification</A>)
  83973. */
  83974. typedef struct {
  83975. FLAC__byte id[4];
  83976. FLAC__byte *data;
  83977. } FLAC__StreamMetadata_Application;
  83978. extern FLAC_API const unsigned FLAC__STREAM_METADATA_APPLICATION_ID_LEN; /**< == 32 (bits) */
  83979. /** SeekPoint structure used in SEEKTABLE blocks. (c.f. <A HREF="../format.html#seekpoint">format specification</A>)
  83980. */
  83981. typedef struct {
  83982. FLAC__uint64 sample_number;
  83983. /**< The sample number of the target frame. */
  83984. FLAC__uint64 stream_offset;
  83985. /**< The offset, in bytes, of the target frame with respect to
  83986. * beginning of the first frame. */
  83987. unsigned frame_samples;
  83988. /**< The number of samples in the target frame. */
  83989. } FLAC__StreamMetadata_SeekPoint;
  83990. extern FLAC_API const unsigned FLAC__STREAM_METADATA_SEEKPOINT_SAMPLE_NUMBER_LEN; /**< == 64 (bits) */
  83991. extern FLAC_API const unsigned FLAC__STREAM_METADATA_SEEKPOINT_STREAM_OFFSET_LEN; /**< == 64 (bits) */
  83992. extern FLAC_API const unsigned FLAC__STREAM_METADATA_SEEKPOINT_FRAME_SAMPLES_LEN; /**< == 16 (bits) */
  83993. /** The total stream length of a seek point in bytes. */
  83994. #define FLAC__STREAM_METADATA_SEEKPOINT_LENGTH (18u)
  83995. /** The value used in the \a sample_number field of
  83996. * FLAC__StreamMetadataSeekPoint used to indicate a placeholder
  83997. * point (== 0xffffffffffffffff).
  83998. */
  83999. extern FLAC_API const FLAC__uint64 FLAC__STREAM_METADATA_SEEKPOINT_PLACEHOLDER;
  84000. /** FLAC SEEKTABLE structure. (c.f. <A HREF="../format.html#metadata_block_seektable">format specification</A>)
  84001. *
  84002. * \note From the format specification:
  84003. * - The seek points must be sorted by ascending sample number.
  84004. * - Each seek point's sample number must be the first sample of the
  84005. * target frame.
  84006. * - Each seek point's sample number must be unique within the table.
  84007. * - Existence of a SEEKTABLE block implies a correct setting of
  84008. * total_samples in the stream_info block.
  84009. * - Behavior is undefined when more than one SEEKTABLE block is
  84010. * present in a stream.
  84011. */
  84012. typedef struct {
  84013. unsigned num_points;
  84014. FLAC__StreamMetadata_SeekPoint *points;
  84015. } FLAC__StreamMetadata_SeekTable;
  84016. /** Vorbis comment entry structure used in VORBIS_COMMENT blocks. (c.f. <A HREF="../format.html#metadata_block_vorbis_comment">format specification</A>)
  84017. *
  84018. * For convenience, the APIs maintain a trailing NUL character at the end of
  84019. * \a entry which is not counted toward \a length, i.e.
  84020. * \code strlen(entry) == length \endcode
  84021. */
  84022. typedef struct {
  84023. FLAC__uint32 length;
  84024. FLAC__byte *entry;
  84025. } FLAC__StreamMetadata_VorbisComment_Entry;
  84026. extern FLAC_API const unsigned FLAC__STREAM_METADATA_VORBIS_COMMENT_ENTRY_LENGTH_LEN; /**< == 32 (bits) */
  84027. /** FLAC VORBIS_COMMENT structure. (c.f. <A HREF="../format.html#metadata_block_vorbis_comment">format specification</A>)
  84028. */
  84029. typedef struct {
  84030. FLAC__StreamMetadata_VorbisComment_Entry vendor_string;
  84031. FLAC__uint32 num_comments;
  84032. FLAC__StreamMetadata_VorbisComment_Entry *comments;
  84033. } FLAC__StreamMetadata_VorbisComment;
  84034. extern FLAC_API const unsigned FLAC__STREAM_METADATA_VORBIS_COMMENT_NUM_COMMENTS_LEN; /**< == 32 (bits) */
  84035. /** FLAC CUESHEET track index structure. (See the
  84036. * <A HREF="../format.html#cuesheet_track_index">format specification</A> for
  84037. * the full description of each field.)
  84038. */
  84039. typedef struct {
  84040. FLAC__uint64 offset;
  84041. /**< Offset in samples, relative to the track offset, of the index
  84042. * point.
  84043. */
  84044. FLAC__byte number;
  84045. /**< The index point number. */
  84046. } FLAC__StreamMetadata_CueSheet_Index;
  84047. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_INDEX_OFFSET_LEN; /**< == 64 (bits) */
  84048. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_INDEX_NUMBER_LEN; /**< == 8 (bits) */
  84049. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_INDEX_RESERVED_LEN; /**< == 3*8 (bits) */
  84050. /** FLAC CUESHEET track structure. (See the
  84051. * <A HREF="../format.html#cuesheet_track">format specification</A> for
  84052. * the full description of each field.)
  84053. */
  84054. typedef struct {
  84055. FLAC__uint64 offset;
  84056. /**< Track offset in samples, relative to the beginning of the FLAC audio stream. */
  84057. FLAC__byte number;
  84058. /**< The track number. */
  84059. char isrc[13];
  84060. /**< Track ISRC. This is a 12-digit alphanumeric code plus a trailing \c NUL byte */
  84061. unsigned type:1;
  84062. /**< The track type: 0 for audio, 1 for non-audio. */
  84063. unsigned pre_emphasis:1;
  84064. /**< The pre-emphasis flag: 0 for no pre-emphasis, 1 for pre-emphasis. */
  84065. FLAC__byte num_indices;
  84066. /**< The number of track index points. */
  84067. FLAC__StreamMetadata_CueSheet_Index *indices;
  84068. /**< NULL if num_indices == 0, else pointer to array of index points. */
  84069. } FLAC__StreamMetadata_CueSheet_Track;
  84070. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_OFFSET_LEN; /**< == 64 (bits) */
  84071. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_NUMBER_LEN; /**< == 8 (bits) */
  84072. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_ISRC_LEN; /**< == 12*8 (bits) */
  84073. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_TYPE_LEN; /**< == 1 (bit) */
  84074. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_PRE_EMPHASIS_LEN; /**< == 1 (bit) */
  84075. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_RESERVED_LEN; /**< == 6+13*8 (bits) */
  84076. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_NUM_INDICES_LEN; /**< == 8 (bits) */
  84077. /** FLAC CUESHEET structure. (See the
  84078. * <A HREF="../format.html#metadata_block_cuesheet">format specification</A>
  84079. * for the full description of each field.)
  84080. */
  84081. typedef struct {
  84082. char media_catalog_number[129];
  84083. /**< Media catalog number, in ASCII printable characters 0x20-0x7e. In
  84084. * general, the media catalog number may be 0 to 128 bytes long; any
  84085. * unused characters should be right-padded with NUL characters.
  84086. */
  84087. FLAC__uint64 lead_in;
  84088. /**< The number of lead-in samples. */
  84089. FLAC__bool is_cd;
  84090. /**< \c true if CUESHEET corresponds to a Compact Disc, else \c false. */
  84091. unsigned num_tracks;
  84092. /**< The number of tracks. */
  84093. FLAC__StreamMetadata_CueSheet_Track *tracks;
  84094. /**< NULL if num_tracks == 0, else pointer to array of tracks. */
  84095. } FLAC__StreamMetadata_CueSheet;
  84096. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_MEDIA_CATALOG_NUMBER_LEN; /**< == 128*8 (bits) */
  84097. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_LEAD_IN_LEN; /**< == 64 (bits) */
  84098. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_IS_CD_LEN; /**< == 1 (bit) */
  84099. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_RESERVED_LEN; /**< == 7+258*8 (bits) */
  84100. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_NUM_TRACKS_LEN; /**< == 8 (bits) */
  84101. /** An enumeration of the PICTURE types (see FLAC__StreamMetadataPicture and id3 v2.4 APIC tag). */
  84102. typedef enum {
  84103. FLAC__STREAM_METADATA_PICTURE_TYPE_OTHER = 0, /**< Other */
  84104. FLAC__STREAM_METADATA_PICTURE_TYPE_FILE_ICON_STANDARD = 1, /**< 32x32 pixels 'file icon' (PNG only) */
  84105. FLAC__STREAM_METADATA_PICTURE_TYPE_FILE_ICON = 2, /**< Other file icon */
  84106. FLAC__STREAM_METADATA_PICTURE_TYPE_FRONT_COVER = 3, /**< Cover (front) */
  84107. FLAC__STREAM_METADATA_PICTURE_TYPE_BACK_COVER = 4, /**< Cover (back) */
  84108. FLAC__STREAM_METADATA_PICTURE_TYPE_LEAFLET_PAGE = 5, /**< Leaflet page */
  84109. FLAC__STREAM_METADATA_PICTURE_TYPE_MEDIA = 6, /**< Media (e.g. label side of CD) */
  84110. FLAC__STREAM_METADATA_PICTURE_TYPE_LEAD_ARTIST = 7, /**< Lead artist/lead performer/soloist */
  84111. FLAC__STREAM_METADATA_PICTURE_TYPE_ARTIST = 8, /**< Artist/performer */
  84112. FLAC__STREAM_METADATA_PICTURE_TYPE_CONDUCTOR = 9, /**< Conductor */
  84113. FLAC__STREAM_METADATA_PICTURE_TYPE_BAND = 10, /**< Band/Orchestra */
  84114. FLAC__STREAM_METADATA_PICTURE_TYPE_COMPOSER = 11, /**< Composer */
  84115. FLAC__STREAM_METADATA_PICTURE_TYPE_LYRICIST = 12, /**< Lyricist/text writer */
  84116. FLAC__STREAM_METADATA_PICTURE_TYPE_RECORDING_LOCATION = 13, /**< Recording Location */
  84117. FLAC__STREAM_METADATA_PICTURE_TYPE_DURING_RECORDING = 14, /**< During recording */
  84118. FLAC__STREAM_METADATA_PICTURE_TYPE_DURING_PERFORMANCE = 15, /**< During performance */
  84119. FLAC__STREAM_METADATA_PICTURE_TYPE_VIDEO_SCREEN_CAPTURE = 16, /**< Movie/video screen capture */
  84120. FLAC__STREAM_METADATA_PICTURE_TYPE_FISH = 17, /**< A bright coloured fish */
  84121. FLAC__STREAM_METADATA_PICTURE_TYPE_ILLUSTRATION = 18, /**< Illustration */
  84122. FLAC__STREAM_METADATA_PICTURE_TYPE_BAND_LOGOTYPE = 19, /**< Band/artist logotype */
  84123. FLAC__STREAM_METADATA_PICTURE_TYPE_PUBLISHER_LOGOTYPE = 20, /**< Publisher/Studio logotype */
  84124. FLAC__STREAM_METADATA_PICTURE_TYPE_UNDEFINED
  84125. } FLAC__StreamMetadata_Picture_Type;
  84126. /** Maps a FLAC__StreamMetadata_Picture_Type to a C string.
  84127. *
  84128. * Using a FLAC__StreamMetadata_Picture_Type as the index to this array
  84129. * will give the string equivalent. The contents should not be
  84130. * modified.
  84131. */
  84132. extern FLAC_API const char * const FLAC__StreamMetadata_Picture_TypeString[];
  84133. /** FLAC PICTURE structure. (See the
  84134. * <A HREF="../format.html#metadata_block_picture">format specification</A>
  84135. * for the full description of each field.)
  84136. */
  84137. typedef struct {
  84138. FLAC__StreamMetadata_Picture_Type type;
  84139. /**< The kind of picture stored. */
  84140. char *mime_type;
  84141. /**< Picture data's MIME type, in ASCII printable characters
  84142. * 0x20-0x7e, NUL terminated. For best compatibility with players,
  84143. * use picture data of MIME type \c image/jpeg or \c image/png. A
  84144. * MIME type of '-->' is also allowed, in which case the picture
  84145. * data should be a complete URL. In file storage, the MIME type is
  84146. * stored as a 32-bit length followed by the ASCII string with no NUL
  84147. * terminator, but is converted to a plain C string in this structure
  84148. * for convenience.
  84149. */
  84150. FLAC__byte *description;
  84151. /**< Picture's description in UTF-8, NUL terminated. In file storage,
  84152. * the description is stored as a 32-bit length followed by the UTF-8
  84153. * string with no NUL terminator, but is converted to a plain C string
  84154. * in this structure for convenience.
  84155. */
  84156. FLAC__uint32 width;
  84157. /**< Picture's width in pixels. */
  84158. FLAC__uint32 height;
  84159. /**< Picture's height in pixels. */
  84160. FLAC__uint32 depth;
  84161. /**< Picture's color depth in bits-per-pixel. */
  84162. FLAC__uint32 colors;
  84163. /**< For indexed palettes (like GIF), picture's number of colors (the
  84164. * number of palette entries), or \c 0 for non-indexed (i.e. 2^depth).
  84165. */
  84166. FLAC__uint32 data_length;
  84167. /**< Length of binary picture data in bytes. */
  84168. FLAC__byte *data;
  84169. /**< Binary picture data. */
  84170. } FLAC__StreamMetadata_Picture;
  84171. extern FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_TYPE_LEN; /**< == 32 (bits) */
  84172. extern FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_MIME_TYPE_LENGTH_LEN; /**< == 32 (bits) */
  84173. extern FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_DESCRIPTION_LENGTH_LEN; /**< == 32 (bits) */
  84174. extern FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_WIDTH_LEN; /**< == 32 (bits) */
  84175. extern FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_HEIGHT_LEN; /**< == 32 (bits) */
  84176. extern FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_DEPTH_LEN; /**< == 32 (bits) */
  84177. extern FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_COLORS_LEN; /**< == 32 (bits) */
  84178. extern FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_DATA_LENGTH_LEN; /**< == 32 (bits) */
  84179. /** Structure that is used when a metadata block of unknown type is loaded.
  84180. * The contents are opaque. The structure is used only internally to
  84181. * correctly handle unknown metadata.
  84182. */
  84183. typedef struct {
  84184. FLAC__byte *data;
  84185. } FLAC__StreamMetadata_Unknown;
  84186. /** FLAC metadata block structure. (c.f. <A HREF="../format.html#metadata_block">format specification</A>)
  84187. */
  84188. typedef struct {
  84189. FLAC__MetadataType type;
  84190. /**< The type of the metadata block; used determine which member of the
  84191. * \a data union to dereference. If type >= FLAC__METADATA_TYPE_UNDEFINED
  84192. * then \a data.unknown must be used. */
  84193. FLAC__bool is_last;
  84194. /**< \c true if this metadata block is the last, else \a false */
  84195. unsigned length;
  84196. /**< Length, in bytes, of the block data as it appears in the stream. */
  84197. union {
  84198. FLAC__StreamMetadata_StreamInfo stream_info;
  84199. FLAC__StreamMetadata_Padding padding;
  84200. FLAC__StreamMetadata_Application application;
  84201. FLAC__StreamMetadata_SeekTable seek_table;
  84202. FLAC__StreamMetadata_VorbisComment vorbis_comment;
  84203. FLAC__StreamMetadata_CueSheet cue_sheet;
  84204. FLAC__StreamMetadata_Picture picture;
  84205. FLAC__StreamMetadata_Unknown unknown;
  84206. } data;
  84207. /**< Polymorphic block data; use the \a type value to determine which
  84208. * to use. */
  84209. } FLAC__StreamMetadata;
  84210. extern FLAC_API const unsigned FLAC__STREAM_METADATA_IS_LAST_LEN; /**< == 1 (bit) */
  84211. extern FLAC_API const unsigned FLAC__STREAM_METADATA_TYPE_LEN; /**< == 7 (bits) */
  84212. extern FLAC_API const unsigned FLAC__STREAM_METADATA_LENGTH_LEN; /**< == 24 (bits) */
  84213. /** The total stream length of a metadata block header in bytes. */
  84214. #define FLAC__STREAM_METADATA_HEADER_LENGTH (4u)
  84215. /*****************************************************************************/
  84216. /*****************************************************************************
  84217. *
  84218. * Utility functions
  84219. *
  84220. *****************************************************************************/
  84221. /** Tests that a sample rate is valid for FLAC.
  84222. *
  84223. * \param sample_rate The sample rate to test for compliance.
  84224. * \retval FLAC__bool
  84225. * \c true if the given sample rate conforms to the specification, else
  84226. * \c false.
  84227. */
  84228. FLAC_API FLAC__bool FLAC__format_sample_rate_is_valid(unsigned sample_rate);
  84229. /** Tests that a sample rate is valid for the FLAC subset. The subset rules
  84230. * for valid sample rates are slightly more complex since the rate has to
  84231. * be expressible completely in the frame header.
  84232. *
  84233. * \param sample_rate The sample rate to test for compliance.
  84234. * \retval FLAC__bool
  84235. * \c true if the given sample rate conforms to the specification for the
  84236. * subset, else \c false.
  84237. */
  84238. FLAC_API FLAC__bool FLAC__format_sample_rate_is_subset(unsigned sample_rate);
  84239. /** Check a Vorbis comment entry name to see if it conforms to the Vorbis
  84240. * comment specification.
  84241. *
  84242. * Vorbis comment names must be composed only of characters from
  84243. * [0x20-0x3C,0x3E-0x7D].
  84244. *
  84245. * \param name A NUL-terminated string to be checked.
  84246. * \assert
  84247. * \code name != NULL \endcode
  84248. * \retval FLAC__bool
  84249. * \c false if entry name is illegal, else \c true.
  84250. */
  84251. FLAC_API FLAC__bool FLAC__format_vorbiscomment_entry_name_is_legal(const char *name);
  84252. /** Check a Vorbis comment entry value to see if it conforms to the Vorbis
  84253. * comment specification.
  84254. *
  84255. * Vorbis comment values must be valid UTF-8 sequences.
  84256. *
  84257. * \param value A string to be checked.
  84258. * \param length A the length of \a value in bytes. May be
  84259. * \c (unsigned)(-1) to indicate that \a value is a plain
  84260. * UTF-8 NUL-terminated string.
  84261. * \assert
  84262. * \code value != NULL \endcode
  84263. * \retval FLAC__bool
  84264. * \c false if entry name is illegal, else \c true.
  84265. */
  84266. FLAC_API FLAC__bool FLAC__format_vorbiscomment_entry_value_is_legal(const FLAC__byte *value, unsigned length);
  84267. /** Check a Vorbis comment entry to see if it conforms to the Vorbis
  84268. * comment specification.
  84269. *
  84270. * Vorbis comment entries must be of the form 'name=value', and 'name' and
  84271. * 'value' must be legal according to
  84272. * FLAC__format_vorbiscomment_entry_name_is_legal() and
  84273. * FLAC__format_vorbiscomment_entry_value_is_legal() respectively.
  84274. *
  84275. * \param entry An entry to be checked.
  84276. * \param length The length of \a entry in bytes.
  84277. * \assert
  84278. * \code value != NULL \endcode
  84279. * \retval FLAC__bool
  84280. * \c false if entry name is illegal, else \c true.
  84281. */
  84282. FLAC_API FLAC__bool FLAC__format_vorbiscomment_entry_is_legal(const FLAC__byte *entry, unsigned length);
  84283. /** Check a seek table to see if it conforms to the FLAC specification.
  84284. * See the format specification for limits on the contents of the
  84285. * seek table.
  84286. *
  84287. * \param seek_table A pointer to a seek table to be checked.
  84288. * \assert
  84289. * \code seek_table != NULL \endcode
  84290. * \retval FLAC__bool
  84291. * \c false if seek table is illegal, else \c true.
  84292. */
  84293. FLAC_API FLAC__bool FLAC__format_seektable_is_legal(const FLAC__StreamMetadata_SeekTable *seek_table);
  84294. /** Sort a seek table's seek points according to the format specification.
  84295. * This includes a "unique-ification" step to remove duplicates, i.e.
  84296. * seek points with identical \a sample_number values. Duplicate seek
  84297. * points are converted into placeholder points and sorted to the end of
  84298. * the table.
  84299. *
  84300. * \param seek_table A pointer to a seek table to be sorted.
  84301. * \assert
  84302. * \code seek_table != NULL \endcode
  84303. * \retval unsigned
  84304. * The number of duplicate seek points converted into placeholders.
  84305. */
  84306. FLAC_API unsigned FLAC__format_seektable_sort(FLAC__StreamMetadata_SeekTable *seek_table);
  84307. /** Check a cue sheet to see if it conforms to the FLAC specification.
  84308. * See the format specification for limits on the contents of the
  84309. * cue sheet.
  84310. *
  84311. * \param cue_sheet A pointer to an existing cue sheet to be checked.
  84312. * \param check_cd_da_subset If \c true, check CUESHEET against more
  84313. * stringent requirements for a CD-DA (audio) disc.
  84314. * \param violation Address of a pointer to a string. If there is a
  84315. * violation, a pointer to a string explanation of the
  84316. * violation will be returned here. \a violation may be
  84317. * \c NULL if you don't need the returned string. Do not
  84318. * free the returned string; it will always point to static
  84319. * data.
  84320. * \assert
  84321. * \code cue_sheet != NULL \endcode
  84322. * \retval FLAC__bool
  84323. * \c false if cue sheet is illegal, else \c true.
  84324. */
  84325. FLAC_API FLAC__bool FLAC__format_cuesheet_is_legal(const FLAC__StreamMetadata_CueSheet *cue_sheet, FLAC__bool check_cd_da_subset, const char **violation);
  84326. /** Check picture data to see if it conforms to the FLAC specification.
  84327. * See the format specification for limits on the contents of the
  84328. * PICTURE block.
  84329. *
  84330. * \param picture A pointer to existing picture data to be checked.
  84331. * \param violation Address of a pointer to a string. If there is a
  84332. * violation, a pointer to a string explanation of the
  84333. * violation will be returned here. \a violation may be
  84334. * \c NULL if you don't need the returned string. Do not
  84335. * free the returned string; it will always point to static
  84336. * data.
  84337. * \assert
  84338. * \code picture != NULL \endcode
  84339. * \retval FLAC__bool
  84340. * \c false if picture data is illegal, else \c true.
  84341. */
  84342. FLAC_API FLAC__bool FLAC__format_picture_is_legal(const FLAC__StreamMetadata_Picture *picture, const char **violation);
  84343. /* \} */
  84344. #ifdef __cplusplus
  84345. }
  84346. #endif
  84347. #endif
  84348. /*** End of inlined file: format.h ***/
  84349. /*** Start of inlined file: metadata.h ***/
  84350. #ifndef FLAC__METADATA_H
  84351. #define FLAC__METADATA_H
  84352. #include <sys/types.h> /* for off_t */
  84353. /* --------------------------------------------------------------------
  84354. (For an example of how all these routines are used, see the source
  84355. code for the unit tests in src/test_libFLAC/metadata_*.c, or
  84356. metaflac in src/metaflac/)
  84357. ------------------------------------------------------------------*/
  84358. /** \file include/FLAC/metadata.h
  84359. *
  84360. * \brief
  84361. * This module provides functions for creating and manipulating FLAC
  84362. * metadata blocks in memory, and three progressively more powerful
  84363. * interfaces for traversing and editing metadata in FLAC files.
  84364. *
  84365. * See the detailed documentation for each interface in the
  84366. * \link flac_metadata metadata \endlink module.
  84367. */
  84368. /** \defgroup flac_metadata FLAC/metadata.h: metadata interfaces
  84369. * \ingroup flac
  84370. *
  84371. * \brief
  84372. * This module provides functions for creating and manipulating FLAC
  84373. * metadata blocks in memory, and three progressively more powerful
  84374. * interfaces for traversing and editing metadata in native FLAC files.
  84375. * Note that currently only the Chain interface (level 2) supports Ogg
  84376. * FLAC files, and it is read-only i.e. no writing back changed
  84377. * metadata to file.
  84378. *
  84379. * There are three metadata interfaces of increasing complexity:
  84380. *
  84381. * Level 0:
  84382. * Read-only access to the STREAMINFO, VORBIS_COMMENT, CUESHEET, and
  84383. * PICTURE blocks.
  84384. *
  84385. * Level 1:
  84386. * Read-write access to all metadata blocks. This level is write-
  84387. * efficient in most cases (more on this below), and uses less memory
  84388. * than level 2.
  84389. *
  84390. * Level 2:
  84391. * Read-write access to all metadata blocks. This level is write-
  84392. * efficient in all cases, but uses more memory since all metadata for
  84393. * the whole file is read into memory and manipulated before writing
  84394. * out again.
  84395. *
  84396. * What do we mean by efficient? Since FLAC metadata appears at the
  84397. * beginning of the file, when writing metadata back to a FLAC file
  84398. * it is possible to grow or shrink the metadata such that the entire
  84399. * file must be rewritten. However, if the size remains the same during
  84400. * changes or PADDING blocks are utilized, only the metadata needs to be
  84401. * overwritten, which is much faster.
  84402. *
  84403. * Efficient means the whole file is rewritten at most one time, and only
  84404. * when necessary. Level 1 is not efficient only in the case that you
  84405. * cause more than one metadata block to grow or shrink beyond what can
  84406. * be accomodated by padding. In this case you should probably use level
  84407. * 2, which allows you to edit all the metadata for a file in memory and
  84408. * write it out all at once.
  84409. *
  84410. * All levels know how to skip over and not disturb an ID3v2 tag at the
  84411. * front of the file.
  84412. *
  84413. * All levels access files via their filenames. In addition, level 2
  84414. * has additional alternative read and write functions that take an I/O
  84415. * handle and callbacks, for situations where access by filename is not
  84416. * possible.
  84417. *
  84418. * In addition to the three interfaces, this module defines functions for
  84419. * creating and manipulating various metadata objects in memory. As we see
  84420. * from the Format module, FLAC metadata blocks in memory are very primitive
  84421. * structures for storing information in an efficient way. Reading
  84422. * information from the structures is easy but creating or modifying them
  84423. * directly is more complex. The metadata object routines here facilitate
  84424. * this by taking care of the consistency and memory management drudgery.
  84425. *
  84426. * Unless you will be using the level 1 or 2 interfaces to modify existing
  84427. * metadata however, you will not probably not need these.
  84428. *
  84429. * From a dependency standpoint, none of the encoders or decoders require
  84430. * the metadata module. This is so that embedded users can strip out the
  84431. * metadata module from libFLAC to reduce the size and complexity.
  84432. */
  84433. #ifdef __cplusplus
  84434. extern "C" {
  84435. #endif
  84436. /** \defgroup flac_metadata_level0 FLAC/metadata.h: metadata level 0 interface
  84437. * \ingroup flac_metadata
  84438. *
  84439. * \brief
  84440. * The level 0 interface consists of individual routines to read the
  84441. * STREAMINFO, VORBIS_COMMENT, CUESHEET, and PICTURE blocks, requiring
  84442. * only a filename.
  84443. *
  84444. * They try to skip any ID3v2 tag at the head of the file.
  84445. *
  84446. * \{
  84447. */
  84448. /** Read the STREAMINFO metadata block of the given FLAC file. This function
  84449. * will try to skip any ID3v2 tag at the head of the file.
  84450. *
  84451. * \param filename The path to the FLAC file to read.
  84452. * \param streaminfo A pointer to space for the STREAMINFO block. Since
  84453. * FLAC__StreamMetadata is a simple structure with no
  84454. * memory allocation involved, you pass the address of
  84455. * an existing structure. It need not be initialized.
  84456. * \assert
  84457. * \code filename != NULL \endcode
  84458. * \code streaminfo != NULL \endcode
  84459. * \retval FLAC__bool
  84460. * \c true if a valid STREAMINFO block was read from \a filename. Returns
  84461. * \c false if there was a memory allocation error, a file decoder error,
  84462. * or the file contained no STREAMINFO block. (A memory allocation error
  84463. * is possible because this function must set up a file decoder.)
  84464. */
  84465. FLAC_API FLAC__bool FLAC__metadata_get_streaminfo(const char *filename, FLAC__StreamMetadata *streaminfo);
  84466. /** Read the VORBIS_COMMENT metadata block of the given FLAC file. This
  84467. * function will try to skip any ID3v2 tag at the head of the file.
  84468. *
  84469. * \param filename The path to the FLAC file to read.
  84470. * \param tags The address where the returned pointer will be
  84471. * stored. The \a tags object must be deleted by
  84472. * the caller using FLAC__metadata_object_delete().
  84473. * \assert
  84474. * \code filename != NULL \endcode
  84475. * \code tags != NULL \endcode
  84476. * \retval FLAC__bool
  84477. * \c true if a valid VORBIS_COMMENT block was read from \a filename,
  84478. * and \a *tags will be set to the address of the metadata structure.
  84479. * Returns \c false if there was a memory allocation error, a file
  84480. * decoder error, or the file contained no VORBIS_COMMENT block, and
  84481. * \a *tags will be set to \c NULL.
  84482. */
  84483. FLAC_API FLAC__bool FLAC__metadata_get_tags(const char *filename, FLAC__StreamMetadata **tags);
  84484. /** Read the CUESHEET metadata block of the given FLAC file. This
  84485. * function will try to skip any ID3v2 tag at the head of the file.
  84486. *
  84487. * \param filename The path to the FLAC file to read.
  84488. * \param cuesheet The address where the returned pointer will be
  84489. * stored. The \a cuesheet object must be deleted by
  84490. * the caller using FLAC__metadata_object_delete().
  84491. * \assert
  84492. * \code filename != NULL \endcode
  84493. * \code cuesheet != NULL \endcode
  84494. * \retval FLAC__bool
  84495. * \c true if a valid CUESHEET block was read from \a filename,
  84496. * and \a *cuesheet will be set to the address of the metadata
  84497. * structure. Returns \c false if there was a memory allocation
  84498. * error, a file decoder error, or the file contained no CUESHEET
  84499. * block, and \a *cuesheet will be set to \c NULL.
  84500. */
  84501. FLAC_API FLAC__bool FLAC__metadata_get_cuesheet(const char *filename, FLAC__StreamMetadata **cuesheet);
  84502. /** Read a PICTURE metadata block of the given FLAC file. This
  84503. * function will try to skip any ID3v2 tag at the head of the file.
  84504. * Since there can be more than one PICTURE block in a file, this
  84505. * function takes a number of parameters that act as constraints to
  84506. * the search. The PICTURE block with the largest area matching all
  84507. * the constraints will be returned, or \a *picture will be set to
  84508. * \c NULL if there was no such block.
  84509. *
  84510. * \param filename The path to the FLAC file to read.
  84511. * \param picture The address where the returned pointer will be
  84512. * stored. The \a picture object must be deleted by
  84513. * the caller using FLAC__metadata_object_delete().
  84514. * \param type The desired picture type. Use \c -1 to mean
  84515. * "any type".
  84516. * \param mime_type The desired MIME type, e.g. "image/jpeg". The
  84517. * string will be matched exactly. Use \c NULL to
  84518. * mean "any MIME type".
  84519. * \param description The desired description. The string will be
  84520. * matched exactly. Use \c NULL to mean "any
  84521. * description".
  84522. * \param max_width The maximum width in pixels desired. Use
  84523. * \c (unsigned)(-1) to mean "any width".
  84524. * \param max_height The maximum height in pixels desired. Use
  84525. * \c (unsigned)(-1) to mean "any height".
  84526. * \param max_depth The maximum color depth in bits-per-pixel desired.
  84527. * Use \c (unsigned)(-1) to mean "any depth".
  84528. * \param max_colors The maximum number of colors desired. Use
  84529. * \c (unsigned)(-1) to mean "any number of colors".
  84530. * \assert
  84531. * \code filename != NULL \endcode
  84532. * \code picture != NULL \endcode
  84533. * \retval FLAC__bool
  84534. * \c true if a valid PICTURE block was read from \a filename,
  84535. * and \a *picture will be set to the address of the metadata
  84536. * structure. Returns \c false if there was a memory allocation
  84537. * error, a file decoder error, or the file contained no PICTURE
  84538. * block, and \a *picture will be set to \c NULL.
  84539. */
  84540. 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);
  84541. /* \} */
  84542. /** \defgroup flac_metadata_level1 FLAC/metadata.h: metadata level 1 interface
  84543. * \ingroup flac_metadata
  84544. *
  84545. * \brief
  84546. * The level 1 interface provides read-write access to FLAC file metadata and
  84547. * operates directly on the FLAC file.
  84548. *
  84549. * The general usage of this interface is:
  84550. *
  84551. * - Create an iterator using FLAC__metadata_simple_iterator_new()
  84552. * - Attach it to a file using FLAC__metadata_simple_iterator_init() and check
  84553. * the exit code. Call FLAC__metadata_simple_iterator_is_writable() to
  84554. * see if the file is writable, or only read access is allowed.
  84555. * - Use FLAC__metadata_simple_iterator_next() and
  84556. * FLAC__metadata_simple_iterator_prev() to traverse the blocks.
  84557. * This is does not read the actual blocks themselves.
  84558. * FLAC__metadata_simple_iterator_next() is relatively fast.
  84559. * FLAC__metadata_simple_iterator_prev() is slower since it needs to search
  84560. * forward from the front of the file.
  84561. * - Use FLAC__metadata_simple_iterator_get_block_type() or
  84562. * FLAC__metadata_simple_iterator_get_block() to access the actual data at
  84563. * the current iterator position. The returned object is yours to modify
  84564. * and free.
  84565. * - Use FLAC__metadata_simple_iterator_set_block() to write a modified block
  84566. * back. You must have write permission to the original file. Make sure to
  84567. * read the whole comment to FLAC__metadata_simple_iterator_set_block()
  84568. * below.
  84569. * - Use FLAC__metadata_simple_iterator_insert_block_after() to add new blocks.
  84570. * Use the object creation functions from
  84571. * \link flac_metadata_object here \endlink to generate new objects.
  84572. * - Use FLAC__metadata_simple_iterator_delete_block() to remove the block
  84573. * currently referred to by the iterator, or replace it with padding.
  84574. * - Destroy the iterator with FLAC__metadata_simple_iterator_delete() when
  84575. * finished.
  84576. *
  84577. * \note
  84578. * The FLAC file remains open the whole time between
  84579. * FLAC__metadata_simple_iterator_init() and
  84580. * FLAC__metadata_simple_iterator_delete(), so make sure you are not altering
  84581. * the file during this time.
  84582. *
  84583. * \note
  84584. * Do not modify the \a is_last, \a length, or \a type fields of returned
  84585. * FLAC__StreamMetadata objects. These are managed automatically.
  84586. *
  84587. * \note
  84588. * If any of the modification functions
  84589. * (FLAC__metadata_simple_iterator_set_block(),
  84590. * FLAC__metadata_simple_iterator_delete_block(),
  84591. * FLAC__metadata_simple_iterator_insert_block_after(), etc.) return \c false,
  84592. * you should delete the iterator as it may no longer be valid.
  84593. *
  84594. * \{
  84595. */
  84596. struct FLAC__Metadata_SimpleIterator;
  84597. /** The opaque structure definition for the level 1 iterator type.
  84598. * See the
  84599. * \link flac_metadata_level1 metadata level 1 module \endlink
  84600. * for a detailed description.
  84601. */
  84602. typedef struct FLAC__Metadata_SimpleIterator FLAC__Metadata_SimpleIterator;
  84603. /** Status type for FLAC__Metadata_SimpleIterator.
  84604. *
  84605. * The iterator's current status can be obtained by calling FLAC__metadata_simple_iterator_status().
  84606. */
  84607. typedef enum {
  84608. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_OK = 0,
  84609. /**< The iterator is in the normal OK state */
  84610. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_ILLEGAL_INPUT,
  84611. /**< The data passed into a function violated the function's usage criteria */
  84612. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_ERROR_OPENING_FILE,
  84613. /**< The iterator could not open the target file */
  84614. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_NOT_A_FLAC_FILE,
  84615. /**< The iterator could not find the FLAC signature at the start of the file */
  84616. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_NOT_WRITABLE,
  84617. /**< The iterator tried to write to a file that was not writable */
  84618. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_BAD_METADATA,
  84619. /**< The iterator encountered input that does not conform to the FLAC metadata specification */
  84620. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_READ_ERROR,
  84621. /**< The iterator encountered an error while reading the FLAC file */
  84622. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_SEEK_ERROR,
  84623. /**< The iterator encountered an error while seeking in the FLAC file */
  84624. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_WRITE_ERROR,
  84625. /**< The iterator encountered an error while writing the FLAC file */
  84626. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_RENAME_ERROR,
  84627. /**< The iterator encountered an error renaming the FLAC file */
  84628. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_UNLINK_ERROR,
  84629. /**< The iterator encountered an error removing the temporary file */
  84630. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_MEMORY_ALLOCATION_ERROR,
  84631. /**< Memory allocation failed */
  84632. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_INTERNAL_ERROR
  84633. /**< The caller violated an assertion or an unexpected error occurred */
  84634. } FLAC__Metadata_SimpleIteratorStatus;
  84635. /** Maps a FLAC__Metadata_SimpleIteratorStatus to a C string.
  84636. *
  84637. * Using a FLAC__Metadata_SimpleIteratorStatus as the index to this array
  84638. * will give the string equivalent. The contents should not be modified.
  84639. */
  84640. extern FLAC_API const char * const FLAC__Metadata_SimpleIteratorStatusString[];
  84641. /** Create a new iterator instance.
  84642. *
  84643. * \retval FLAC__Metadata_SimpleIterator*
  84644. * \c NULL if there was an error allocating memory, else the new instance.
  84645. */
  84646. FLAC_API FLAC__Metadata_SimpleIterator *FLAC__metadata_simple_iterator_new(void);
  84647. /** Free an iterator instance. Deletes the object pointed to by \a iterator.
  84648. *
  84649. * \param iterator A pointer to an existing iterator.
  84650. * \assert
  84651. * \code iterator != NULL \endcode
  84652. */
  84653. FLAC_API void FLAC__metadata_simple_iterator_delete(FLAC__Metadata_SimpleIterator *iterator);
  84654. /** Get the current status of the iterator. Call this after a function
  84655. * returns \c false to get the reason for the error. Also resets the status
  84656. * to FLAC__METADATA_SIMPLE_ITERATOR_STATUS_OK.
  84657. *
  84658. * \param iterator A pointer to an existing iterator.
  84659. * \assert
  84660. * \code iterator != NULL \endcode
  84661. * \retval FLAC__Metadata_SimpleIteratorStatus
  84662. * The current status of the iterator.
  84663. */
  84664. FLAC_API FLAC__Metadata_SimpleIteratorStatus FLAC__metadata_simple_iterator_status(FLAC__Metadata_SimpleIterator *iterator);
  84665. /** Initialize the iterator to point to the first metadata block in the
  84666. * given FLAC file.
  84667. *
  84668. * \param iterator A pointer to an existing iterator.
  84669. * \param filename The path to the FLAC file.
  84670. * \param read_only If \c true, the FLAC file will be opened
  84671. * in read-only mode; if \c false, the FLAC
  84672. * file will be opened for edit even if no
  84673. * edits are performed.
  84674. * \param preserve_file_stats If \c true, the owner and modification
  84675. * time will be preserved even if the FLAC
  84676. * file is written to.
  84677. * \assert
  84678. * \code iterator != NULL \endcode
  84679. * \code filename != NULL \endcode
  84680. * \retval FLAC__bool
  84681. * \c false if a memory allocation error occurs, the file can't be
  84682. * opened, or another error occurs, else \c true.
  84683. */
  84684. 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);
  84685. /** Returns \c true if the FLAC file is writable. If \c false, calls to
  84686. * FLAC__metadata_simple_iterator_set_block() and
  84687. * FLAC__metadata_simple_iterator_insert_block_after() will fail.
  84688. *
  84689. * \param iterator A pointer to an existing iterator.
  84690. * \assert
  84691. * \code iterator != NULL \endcode
  84692. * \retval FLAC__bool
  84693. * See above.
  84694. */
  84695. FLAC_API FLAC__bool FLAC__metadata_simple_iterator_is_writable(const FLAC__Metadata_SimpleIterator *iterator);
  84696. /** Moves the iterator forward one metadata block, returning \c false if
  84697. * already at the end.
  84698. *
  84699. * \param iterator A pointer to an existing initialized iterator.
  84700. * \assert
  84701. * \code iterator != NULL \endcode
  84702. * \a iterator has been successfully initialized with
  84703. * FLAC__metadata_simple_iterator_init()
  84704. * \retval FLAC__bool
  84705. * \c false if already at the last metadata block of the chain, else
  84706. * \c true.
  84707. */
  84708. FLAC_API FLAC__bool FLAC__metadata_simple_iterator_next(FLAC__Metadata_SimpleIterator *iterator);
  84709. /** Moves the iterator backward one metadata block, returning \c false if
  84710. * already at the beginning.
  84711. *
  84712. * \param iterator A pointer to an existing initialized iterator.
  84713. * \assert
  84714. * \code iterator != NULL \endcode
  84715. * \a iterator has been successfully initialized with
  84716. * FLAC__metadata_simple_iterator_init()
  84717. * \retval FLAC__bool
  84718. * \c false if already at the first metadata block of the chain, else
  84719. * \c true.
  84720. */
  84721. FLAC_API FLAC__bool FLAC__metadata_simple_iterator_prev(FLAC__Metadata_SimpleIterator *iterator);
  84722. /** Returns a flag telling if the current metadata block is the last.
  84723. *
  84724. * \param iterator A pointer to an existing initialized iterator.
  84725. * \assert
  84726. * \code iterator != NULL \endcode
  84727. * \a iterator has been successfully initialized with
  84728. * FLAC__metadata_simple_iterator_init()
  84729. * \retval FLAC__bool
  84730. * \c true if the current metadata block is the last in the file,
  84731. * else \c false.
  84732. */
  84733. FLAC_API FLAC__bool FLAC__metadata_simple_iterator_is_last(const FLAC__Metadata_SimpleIterator *iterator);
  84734. /** Get the offset of the metadata block at the current position. This
  84735. * avoids reading the actual block data which can save time for large
  84736. * blocks.
  84737. *
  84738. * \param iterator A pointer to an existing initialized iterator.
  84739. * \assert
  84740. * \code iterator != NULL \endcode
  84741. * \a iterator has been successfully initialized with
  84742. * FLAC__metadata_simple_iterator_init()
  84743. * \retval off_t
  84744. * The offset of the metadata block at the current iterator position.
  84745. * This is the byte offset relative to the beginning of the file of
  84746. * the current metadata block's header.
  84747. */
  84748. FLAC_API off_t FLAC__metadata_simple_iterator_get_block_offset(const FLAC__Metadata_SimpleIterator *iterator);
  84749. /** Get the type of the metadata block at the current position. This
  84750. * avoids reading the actual block data which can save time for large
  84751. * blocks.
  84752. *
  84753. * \param iterator A pointer to an existing initialized iterator.
  84754. * \assert
  84755. * \code iterator != NULL \endcode
  84756. * \a iterator has been successfully initialized with
  84757. * FLAC__metadata_simple_iterator_init()
  84758. * \retval FLAC__MetadataType
  84759. * The type of the metadata block at the current iterator position.
  84760. */
  84761. FLAC_API FLAC__MetadataType FLAC__metadata_simple_iterator_get_block_type(const FLAC__Metadata_SimpleIterator *iterator);
  84762. /** Get the length of the metadata block at the current position. This
  84763. * avoids reading the actual block data which can save time for large
  84764. * blocks.
  84765. *
  84766. * \param iterator A pointer to an existing initialized iterator.
  84767. * \assert
  84768. * \code iterator != NULL \endcode
  84769. * \a iterator has been successfully initialized with
  84770. * FLAC__metadata_simple_iterator_init()
  84771. * \retval unsigned
  84772. * The length of the metadata block at the current iterator position.
  84773. * The is same length as that in the
  84774. * <a href="http://flac.sourceforge.net/format.html#metadata_block_header">metadata block header</a>,
  84775. * i.e. the length of the metadata body that follows the header.
  84776. */
  84777. FLAC_API unsigned FLAC__metadata_simple_iterator_get_block_length(const FLAC__Metadata_SimpleIterator *iterator);
  84778. /** Get the application ID of the \c APPLICATION block at the current
  84779. * position. This avoids reading the actual block data which can save
  84780. * time for large blocks.
  84781. *
  84782. * \param iterator A pointer to an existing initialized iterator.
  84783. * \param id A pointer to a buffer of at least \c 4 bytes where
  84784. * the ID will be stored.
  84785. * \assert
  84786. * \code iterator != NULL \endcode
  84787. * \code id != NULL \endcode
  84788. * \a iterator has been successfully initialized with
  84789. * FLAC__metadata_simple_iterator_init()
  84790. * \retval FLAC__bool
  84791. * \c true if the ID was successfully read, else \c false, in which
  84792. * case you should check FLAC__metadata_simple_iterator_status() to
  84793. * find out why. If the status is
  84794. * \c FLAC__METADATA_SIMPLE_ITERATOR_STATUS_ILLEGAL_INPUT, then the
  84795. * current metadata block is not an \c APPLICATION block. Otherwise
  84796. * if the status is
  84797. * \c FLAC__METADATA_SIMPLE_ITERATOR_STATUS_READ_ERROR or
  84798. * \c FLAC__METADATA_SIMPLE_ITERATOR_STATUS_SEEK_ERROR, an I/O error
  84799. * occurred and the iterator can no longer be used.
  84800. */
  84801. FLAC_API FLAC__bool FLAC__metadata_simple_iterator_get_application_id(FLAC__Metadata_SimpleIterator *iterator, FLAC__byte *id);
  84802. /** Get the metadata block at the current position. You can modify the
  84803. * block but must use FLAC__metadata_simple_iterator_set_block() to
  84804. * write it back to the FLAC file.
  84805. *
  84806. * You must call FLAC__metadata_object_delete() on the returned object
  84807. * when you are finished with it.
  84808. *
  84809. * \param iterator A pointer to an existing initialized iterator.
  84810. * \assert
  84811. * \code iterator != NULL \endcode
  84812. * \a iterator has been successfully initialized with
  84813. * FLAC__metadata_simple_iterator_init()
  84814. * \retval FLAC__StreamMetadata*
  84815. * The current metadata block, or \c NULL if there was a memory
  84816. * allocation error.
  84817. */
  84818. FLAC_API FLAC__StreamMetadata *FLAC__metadata_simple_iterator_get_block(FLAC__Metadata_SimpleIterator *iterator);
  84819. /** Write a block back to the FLAC file. This function tries to be
  84820. * as efficient as possible; how the block is actually written is
  84821. * shown by the following:
  84822. *
  84823. * Existing block is a STREAMINFO block and the new block is a
  84824. * STREAMINFO block: the new block is written in place. Make sure
  84825. * you know what you're doing when changing the values of a
  84826. * STREAMINFO block.
  84827. *
  84828. * Existing block is a STREAMINFO block and the new block is a
  84829. * not a STREAMINFO block: this is an error since the first block
  84830. * must be a STREAMINFO block. Returns \c false without altering the
  84831. * file.
  84832. *
  84833. * Existing block is not a STREAMINFO block and the new block is a
  84834. * STREAMINFO block: this is an error since there may be only one
  84835. * STREAMINFO block. Returns \c false without altering the file.
  84836. *
  84837. * Existing block and new block are the same length: the existing
  84838. * block will be replaced by the new block, written in place.
  84839. *
  84840. * Existing block is longer than new block: if use_padding is \c true,
  84841. * the existing block will be overwritten in place with the new
  84842. * block followed by a PADDING block, if possible, to make the total
  84843. * size the same as the existing block. Remember that a padding
  84844. * block requires at least four bytes so if the difference in size
  84845. * between the new block and existing block is less than that, the
  84846. * entire file will have to be rewritten, using the new block's
  84847. * exact size. If use_padding is \c false, the entire file will be
  84848. * rewritten, replacing the existing block by the new block.
  84849. *
  84850. * Existing block is shorter than new block: if use_padding is \c true,
  84851. * the function will try and expand the new block into the following
  84852. * PADDING block, if it exists and doing so won't shrink the PADDING
  84853. * block to less than 4 bytes. If there is no following PADDING
  84854. * block, or it will shrink to less than 4 bytes, or use_padding is
  84855. * \c false, the entire file is rewritten, replacing the existing block
  84856. * with the new block. Note that in this case any following PADDING
  84857. * block is preserved as is.
  84858. *
  84859. * After writing the block, the iterator will remain in the same
  84860. * place, i.e. pointing to the new block.
  84861. *
  84862. * \param iterator A pointer to an existing initialized iterator.
  84863. * \param block The block to set.
  84864. * \param use_padding See above.
  84865. * \assert
  84866. * \code iterator != NULL \endcode
  84867. * \a iterator has been successfully initialized with
  84868. * FLAC__metadata_simple_iterator_init()
  84869. * \code block != NULL \endcode
  84870. * \retval FLAC__bool
  84871. * \c true if successful, else \c false.
  84872. */
  84873. FLAC_API FLAC__bool FLAC__metadata_simple_iterator_set_block(FLAC__Metadata_SimpleIterator *iterator, FLAC__StreamMetadata *block, FLAC__bool use_padding);
  84874. /** This is similar to FLAC__metadata_simple_iterator_set_block()
  84875. * except that instead of writing over an existing block, it appends
  84876. * a block after the existing block. \a use_padding is again used to
  84877. * tell the function to try an expand into following padding in an
  84878. * attempt to avoid rewriting the entire file.
  84879. *
  84880. * This function will fail and return \c false if given a STREAMINFO
  84881. * block.
  84882. *
  84883. * After writing the block, the iterator will be pointing to the
  84884. * new block.
  84885. *
  84886. * \param iterator A pointer to an existing initialized iterator.
  84887. * \param block The block to set.
  84888. * \param use_padding See above.
  84889. * \assert
  84890. * \code iterator != NULL \endcode
  84891. * \a iterator has been successfully initialized with
  84892. * FLAC__metadata_simple_iterator_init()
  84893. * \code block != NULL \endcode
  84894. * \retval FLAC__bool
  84895. * \c true if successful, else \c false.
  84896. */
  84897. FLAC_API FLAC__bool FLAC__metadata_simple_iterator_insert_block_after(FLAC__Metadata_SimpleIterator *iterator, FLAC__StreamMetadata *block, FLAC__bool use_padding);
  84898. /** Deletes the block at the current position. This will cause the
  84899. * entire FLAC file to be rewritten, unless \a use_padding is \c true,
  84900. * in which case the block will be replaced by an equal-sized PADDING
  84901. * block. The iterator will be left pointing to the block before the
  84902. * one just deleted.
  84903. *
  84904. * You may not delete the STREAMINFO block.
  84905. *
  84906. * \param iterator A pointer to an existing initialized iterator.
  84907. * \param use_padding See above.
  84908. * \assert
  84909. * \code iterator != NULL \endcode
  84910. * \a iterator has been successfully initialized with
  84911. * FLAC__metadata_simple_iterator_init()
  84912. * \retval FLAC__bool
  84913. * \c true if successful, else \c false.
  84914. */
  84915. FLAC_API FLAC__bool FLAC__metadata_simple_iterator_delete_block(FLAC__Metadata_SimpleIterator *iterator, FLAC__bool use_padding);
  84916. /* \} */
  84917. /** \defgroup flac_metadata_level2 FLAC/metadata.h: metadata level 2 interface
  84918. * \ingroup flac_metadata
  84919. *
  84920. * \brief
  84921. * The level 2 interface provides read-write access to FLAC file metadata;
  84922. * all metadata is read into memory, operated on in memory, and then written
  84923. * to file, which is more efficient than level 1 when editing multiple blocks.
  84924. *
  84925. * Currently Ogg FLAC is supported for read only, via
  84926. * FLAC__metadata_chain_read_ogg() but a subsequent
  84927. * FLAC__metadata_chain_write() will fail.
  84928. *
  84929. * The general usage of this interface is:
  84930. *
  84931. * - Create a new chain using FLAC__metadata_chain_new(). A chain is a
  84932. * linked list of FLAC metadata blocks.
  84933. * - Read all metadata into the the chain from a FLAC file using
  84934. * FLAC__metadata_chain_read() or FLAC__metadata_chain_read_ogg() and
  84935. * check the status.
  84936. * - Optionally, consolidate the padding using
  84937. * FLAC__metadata_chain_merge_padding() or
  84938. * FLAC__metadata_chain_sort_padding().
  84939. * - Create a new iterator using FLAC__metadata_iterator_new()
  84940. * - Initialize the iterator to point to the first element in the chain
  84941. * using FLAC__metadata_iterator_init()
  84942. * - Traverse the chain using FLAC__metadata_iterator_next and
  84943. * FLAC__metadata_iterator_prev().
  84944. * - Get a block for reading or modification using
  84945. * FLAC__metadata_iterator_get_block(). The pointer to the object
  84946. * inside the chain is returned, so the block is yours to modify.
  84947. * Changes will be reflected in the FLAC file when you write the
  84948. * chain. You can also add and delete blocks (see functions below).
  84949. * - When done, write out the chain using FLAC__metadata_chain_write().
  84950. * Make sure to read the whole comment to the function below.
  84951. * - Delete the chain using FLAC__metadata_chain_delete().
  84952. *
  84953. * \note
  84954. * Even though the FLAC file is not open while the chain is being
  84955. * manipulated, you must not alter the file externally during
  84956. * this time. The chain assumes the FLAC file will not change
  84957. * between the time of FLAC__metadata_chain_read()/FLAC__metadata_chain_read_ogg()
  84958. * and FLAC__metadata_chain_write().
  84959. *
  84960. * \note
  84961. * Do not modify the is_last, length, or type fields of returned
  84962. * FLAC__StreamMetadata objects. These are managed automatically.
  84963. *
  84964. * \note
  84965. * The metadata objects returned by FLAC__metadata_iterator_get_block()
  84966. * are owned by the chain; do not FLAC__metadata_object_delete() them.
  84967. * In the same way, blocks passed to FLAC__metadata_iterator_set_block()
  84968. * become owned by the chain and they will be deleted when the chain is
  84969. * deleted.
  84970. *
  84971. * \{
  84972. */
  84973. struct FLAC__Metadata_Chain;
  84974. /** The opaque structure definition for the level 2 chain type.
  84975. */
  84976. typedef struct FLAC__Metadata_Chain FLAC__Metadata_Chain;
  84977. struct FLAC__Metadata_Iterator;
  84978. /** The opaque structure definition for the level 2 iterator type.
  84979. */
  84980. typedef struct FLAC__Metadata_Iterator FLAC__Metadata_Iterator;
  84981. typedef enum {
  84982. FLAC__METADATA_CHAIN_STATUS_OK = 0,
  84983. /**< The chain is in the normal OK state */
  84984. FLAC__METADATA_CHAIN_STATUS_ILLEGAL_INPUT,
  84985. /**< The data passed into a function violated the function's usage criteria */
  84986. FLAC__METADATA_CHAIN_STATUS_ERROR_OPENING_FILE,
  84987. /**< The chain could not open the target file */
  84988. FLAC__METADATA_CHAIN_STATUS_NOT_A_FLAC_FILE,
  84989. /**< The chain could not find the FLAC signature at the start of the file */
  84990. FLAC__METADATA_CHAIN_STATUS_NOT_WRITABLE,
  84991. /**< The chain tried to write to a file that was not writable */
  84992. FLAC__METADATA_CHAIN_STATUS_BAD_METADATA,
  84993. /**< The chain encountered input that does not conform to the FLAC metadata specification */
  84994. FLAC__METADATA_CHAIN_STATUS_READ_ERROR,
  84995. /**< The chain encountered an error while reading the FLAC file */
  84996. FLAC__METADATA_CHAIN_STATUS_SEEK_ERROR,
  84997. /**< The chain encountered an error while seeking in the FLAC file */
  84998. FLAC__METADATA_CHAIN_STATUS_WRITE_ERROR,
  84999. /**< The chain encountered an error while writing the FLAC file */
  85000. FLAC__METADATA_CHAIN_STATUS_RENAME_ERROR,
  85001. /**< The chain encountered an error renaming the FLAC file */
  85002. FLAC__METADATA_CHAIN_STATUS_UNLINK_ERROR,
  85003. /**< The chain encountered an error removing the temporary file */
  85004. FLAC__METADATA_CHAIN_STATUS_MEMORY_ALLOCATION_ERROR,
  85005. /**< Memory allocation failed */
  85006. FLAC__METADATA_CHAIN_STATUS_INTERNAL_ERROR,
  85007. /**< The caller violated an assertion or an unexpected error occurred */
  85008. FLAC__METADATA_CHAIN_STATUS_INVALID_CALLBACKS,
  85009. /**< One or more of the required callbacks was NULL */
  85010. FLAC__METADATA_CHAIN_STATUS_READ_WRITE_MISMATCH,
  85011. /**< FLAC__metadata_chain_write() was called on a chain read by
  85012. * FLAC__metadata_chain_read_with_callbacks()/FLAC__metadata_chain_read_ogg_with_callbacks(),
  85013. * or
  85014. * FLAC__metadata_chain_write_with_callbacks()/FLAC__metadata_chain_write_with_callbacks_and_tempfile()
  85015. * was called on a chain read by
  85016. * FLAC__metadata_chain_read()/FLAC__metadata_chain_read_ogg().
  85017. * Matching read/write methods must always be used. */
  85018. FLAC__METADATA_CHAIN_STATUS_WRONG_WRITE_CALL
  85019. /**< FLAC__metadata_chain_write_with_callbacks() was called when the
  85020. * chain write requires a tempfile; use
  85021. * FLAC__metadata_chain_write_with_callbacks_and_tempfile() instead.
  85022. * Or, FLAC__metadata_chain_write_with_callbacks_and_tempfile() was
  85023. * called when the chain write does not require a tempfile; use
  85024. * FLAC__metadata_chain_write_with_callbacks() instead.
  85025. * Always check FLAC__metadata_chain_check_if_tempfile_needed()
  85026. * before writing via callbacks. */
  85027. } FLAC__Metadata_ChainStatus;
  85028. /** Maps a FLAC__Metadata_ChainStatus to a C string.
  85029. *
  85030. * Using a FLAC__Metadata_ChainStatus as the index to this array
  85031. * will give the string equivalent. The contents should not be modified.
  85032. */
  85033. extern FLAC_API const char * const FLAC__Metadata_ChainStatusString[];
  85034. /*********** FLAC__Metadata_Chain ***********/
  85035. /** Create a new chain instance.
  85036. *
  85037. * \retval FLAC__Metadata_Chain*
  85038. * \c NULL if there was an error allocating memory, else the new instance.
  85039. */
  85040. FLAC_API FLAC__Metadata_Chain *FLAC__metadata_chain_new(void);
  85041. /** Free a chain instance. Deletes the object pointed to by \a chain.
  85042. *
  85043. * \param chain A pointer to an existing chain.
  85044. * \assert
  85045. * \code chain != NULL \endcode
  85046. */
  85047. FLAC_API void FLAC__metadata_chain_delete(FLAC__Metadata_Chain *chain);
  85048. /** Get the current status of the chain. Call this after a function
  85049. * returns \c false to get the reason for the error. Also resets the
  85050. * status to FLAC__METADATA_CHAIN_STATUS_OK.
  85051. *
  85052. * \param chain A pointer to an existing chain.
  85053. * \assert
  85054. * \code chain != NULL \endcode
  85055. * \retval FLAC__Metadata_ChainStatus
  85056. * The current status of the chain.
  85057. */
  85058. FLAC_API FLAC__Metadata_ChainStatus FLAC__metadata_chain_status(FLAC__Metadata_Chain *chain);
  85059. /** Read all metadata from a FLAC file into the chain.
  85060. *
  85061. * \param chain A pointer to an existing chain.
  85062. * \param filename The path to the FLAC file to read.
  85063. * \assert
  85064. * \code chain != NULL \endcode
  85065. * \code filename != NULL \endcode
  85066. * \retval FLAC__bool
  85067. * \c true if a valid list of metadata blocks was read from
  85068. * \a filename, else \c false. On failure, check the status with
  85069. * FLAC__metadata_chain_status().
  85070. */
  85071. FLAC_API FLAC__bool FLAC__metadata_chain_read(FLAC__Metadata_Chain *chain, const char *filename);
  85072. /** Read all metadata from an Ogg FLAC file into the chain.
  85073. *
  85074. * \note Ogg FLAC metadata data writing is not supported yet and
  85075. * FLAC__metadata_chain_write() will fail.
  85076. *
  85077. * \param chain A pointer to an existing chain.
  85078. * \param filename The path to the Ogg FLAC file to read.
  85079. * \assert
  85080. * \code chain != NULL \endcode
  85081. * \code filename != NULL \endcode
  85082. * \retval FLAC__bool
  85083. * \c true if a valid list of metadata blocks was read from
  85084. * \a filename, else \c false. On failure, check the status with
  85085. * FLAC__metadata_chain_status().
  85086. */
  85087. FLAC_API FLAC__bool FLAC__metadata_chain_read_ogg(FLAC__Metadata_Chain *chain, const char *filename);
  85088. /** Read all metadata from a FLAC stream into the chain via I/O callbacks.
  85089. *
  85090. * The \a handle need only be open for reading, but must be seekable.
  85091. * The equivalent minimum stdio fopen() file mode is \c "r" (or \c "rb"
  85092. * for Windows).
  85093. *
  85094. * \param chain A pointer to an existing chain.
  85095. * \param handle The I/O handle of the FLAC stream to read. The
  85096. * handle will NOT be closed after the metadata is read;
  85097. * that is the duty of the caller.
  85098. * \param callbacks
  85099. * A set of callbacks to use for I/O. The mandatory
  85100. * callbacks are \a read, \a seek, and \a tell.
  85101. * \assert
  85102. * \code chain != NULL \endcode
  85103. * \retval FLAC__bool
  85104. * \c true if a valid list of metadata blocks was read from
  85105. * \a handle, else \c false. On failure, check the status with
  85106. * FLAC__metadata_chain_status().
  85107. */
  85108. FLAC_API FLAC__bool FLAC__metadata_chain_read_with_callbacks(FLAC__Metadata_Chain *chain, FLAC__IOHandle handle, FLAC__IOCallbacks callbacks);
  85109. /** Read all metadata from an Ogg FLAC stream into the chain via I/O callbacks.
  85110. *
  85111. * The \a handle need only be open for reading, but must be seekable.
  85112. * The equivalent minimum stdio fopen() file mode is \c "r" (or \c "rb"
  85113. * for Windows).
  85114. *
  85115. * \note Ogg FLAC metadata data writing is not supported yet and
  85116. * FLAC__metadata_chain_write() will fail.
  85117. *
  85118. * \param chain A pointer to an existing chain.
  85119. * \param handle The I/O handle of the Ogg FLAC stream to read. The
  85120. * handle will NOT be closed after the metadata is read;
  85121. * that is the duty of the caller.
  85122. * \param callbacks
  85123. * A set of callbacks to use for I/O. The mandatory
  85124. * callbacks are \a read, \a seek, and \a tell.
  85125. * \assert
  85126. * \code chain != NULL \endcode
  85127. * \retval FLAC__bool
  85128. * \c true if a valid list of metadata blocks was read from
  85129. * \a handle, else \c false. On failure, check the status with
  85130. * FLAC__metadata_chain_status().
  85131. */
  85132. FLAC_API FLAC__bool FLAC__metadata_chain_read_ogg_with_callbacks(FLAC__Metadata_Chain *chain, FLAC__IOHandle handle, FLAC__IOCallbacks callbacks);
  85133. /** Checks if writing the given chain would require the use of a
  85134. * temporary file, or if it could be written in place.
  85135. *
  85136. * Under certain conditions, padding can be utilized so that writing
  85137. * edited metadata back to the FLAC file does not require rewriting the
  85138. * entire file. If rewriting is required, then a temporary workfile is
  85139. * required. When writing metadata using callbacks, you must check
  85140. * this function to know whether to call
  85141. * FLAC__metadata_chain_write_with_callbacks() or
  85142. * FLAC__metadata_chain_write_with_callbacks_and_tempfile(). When
  85143. * writing with FLAC__metadata_chain_write(), the temporary file is
  85144. * handled internally.
  85145. *
  85146. * \param chain A pointer to an existing chain.
  85147. * \param use_padding
  85148. * Whether or not padding will be allowed to be used
  85149. * during the write. The value of \a use_padding given
  85150. * here must match the value later passed to
  85151. * FLAC__metadata_chain_write_with_callbacks() or
  85152. * FLAC__metadata_chain_write_with_callbacks_with_tempfile().
  85153. * \assert
  85154. * \code chain != NULL \endcode
  85155. * \retval FLAC__bool
  85156. * \c true if writing the current chain would require a tempfile, or
  85157. * \c false if metadata can be written in place.
  85158. */
  85159. FLAC_API FLAC__bool FLAC__metadata_chain_check_if_tempfile_needed(FLAC__Metadata_Chain *chain, FLAC__bool use_padding);
  85160. /** Write all metadata out to the FLAC file. This function tries to be as
  85161. * efficient as possible; how the metadata is actually written is shown by
  85162. * the following:
  85163. *
  85164. * If the current chain is the same size as the existing metadata, the new
  85165. * data is written in place.
  85166. *
  85167. * If the current chain is longer than the existing metadata, and
  85168. * \a use_padding is \c true, and the last block is a PADDING block of
  85169. * sufficient length, the function will truncate the final padding block
  85170. * so that the overall size of the metadata is the same as the existing
  85171. * metadata, and then just rewrite the metadata. Otherwise, if not all of
  85172. * the above conditions are met, the entire FLAC file must be rewritten.
  85173. * If you want to use padding this way it is a good idea to call
  85174. * FLAC__metadata_chain_sort_padding() first so that you have the maximum
  85175. * amount of padding to work with, unless you need to preserve ordering
  85176. * of the PADDING blocks for some reason.
  85177. *
  85178. * If the current chain is shorter than the existing metadata, and
  85179. * \a use_padding is \c true, and the final block is a PADDING block, the padding
  85180. * is extended to make the overall size the same as the existing data. If
  85181. * \a use_padding is \c true and the last block is not a PADDING block, a new
  85182. * PADDING block is added to the end of the new data to make it the same
  85183. * size as the existing data (if possible, see the note to
  85184. * FLAC__metadata_simple_iterator_set_block() about the four byte limit)
  85185. * and the new data is written in place. If none of the above apply or
  85186. * \a use_padding is \c false, the entire FLAC file is rewritten.
  85187. *
  85188. * If \a preserve_file_stats is \c true, the owner and modification time will
  85189. * be preserved even if the FLAC file is written.
  85190. *
  85191. * For this write function to be used, the chain must have been read with
  85192. * FLAC__metadata_chain_read()/FLAC__metadata_chain_read_ogg(), not
  85193. * FLAC__metadata_chain_read_with_callbacks()/FLAC__metadata_chain_read_ogg_with_callbacks().
  85194. *
  85195. * \param chain A pointer to an existing chain.
  85196. * \param use_padding See above.
  85197. * \param preserve_file_stats See above.
  85198. * \assert
  85199. * \code chain != NULL \endcode
  85200. * \retval FLAC__bool
  85201. * \c true if the write succeeded, else \c false. On failure,
  85202. * check the status with FLAC__metadata_chain_status().
  85203. */
  85204. FLAC_API FLAC__bool FLAC__metadata_chain_write(FLAC__Metadata_Chain *chain, FLAC__bool use_padding, FLAC__bool preserve_file_stats);
  85205. /** Write all metadata out to a FLAC stream via callbacks.
  85206. *
  85207. * (See FLAC__metadata_chain_write() for the details on how padding is
  85208. * used to write metadata in place if possible.)
  85209. *
  85210. * The \a handle must be open for updating and be seekable. The
  85211. * equivalent minimum stdio fopen() file mode is \c "r+" (or \c "r+b"
  85212. * for Windows).
  85213. *
  85214. * For this write function to be used, the chain must have been read with
  85215. * FLAC__metadata_chain_read_with_callbacks()/FLAC__metadata_chain_read_ogg_with_callbacks(),
  85216. * not FLAC__metadata_chain_read()/FLAC__metadata_chain_read_ogg().
  85217. * Also, FLAC__metadata_chain_check_if_tempfile_needed() must have returned
  85218. * \c false.
  85219. *
  85220. * \param chain A pointer to an existing chain.
  85221. * \param use_padding See FLAC__metadata_chain_write()
  85222. * \param handle The I/O handle of the FLAC stream to write. The
  85223. * handle will NOT be closed after the metadata is
  85224. * written; that is the duty of the caller.
  85225. * \param callbacks A set of callbacks to use for I/O. The mandatory
  85226. * callbacks are \a write and \a seek.
  85227. * \assert
  85228. * \code chain != NULL \endcode
  85229. * \retval FLAC__bool
  85230. * \c true if the write succeeded, else \c false. On failure,
  85231. * check the status with FLAC__metadata_chain_status().
  85232. */
  85233. FLAC_API FLAC__bool FLAC__metadata_chain_write_with_callbacks(FLAC__Metadata_Chain *chain, FLAC__bool use_padding, FLAC__IOHandle handle, FLAC__IOCallbacks callbacks);
  85234. /** Write all metadata out to a FLAC stream via callbacks.
  85235. *
  85236. * (See FLAC__metadata_chain_write() for the details on how padding is
  85237. * used to write metadata in place if possible.)
  85238. *
  85239. * This version of the write-with-callbacks function must be used when
  85240. * FLAC__metadata_chain_check_if_tempfile_needed() returns true. In
  85241. * this function, you must supply an I/O handle corresponding to the
  85242. * FLAC file to edit, and a temporary handle to which the new FLAC
  85243. * file will be written. It is the caller's job to move this temporary
  85244. * FLAC file on top of the original FLAC file to complete the metadata
  85245. * edit.
  85246. *
  85247. * The \a handle must be open for reading and be seekable. The
  85248. * equivalent minimum stdio fopen() file mode is \c "r" (or \c "rb"
  85249. * for Windows).
  85250. *
  85251. * The \a temp_handle must be open for writing. The
  85252. * equivalent minimum stdio fopen() file mode is \c "w" (or \c "wb"
  85253. * for Windows). It should be an empty stream, or at least positioned
  85254. * at the start-of-file (in which case it is the caller's duty to
  85255. * truncate it on return).
  85256. *
  85257. * For this write function to be used, the chain must have been read with
  85258. * FLAC__metadata_chain_read_with_callbacks()/FLAC__metadata_chain_read_ogg_with_callbacks(),
  85259. * not FLAC__metadata_chain_read()/FLAC__metadata_chain_read_ogg().
  85260. * Also, FLAC__metadata_chain_check_if_tempfile_needed() must have returned
  85261. * \c true.
  85262. *
  85263. * \param chain A pointer to an existing chain.
  85264. * \param use_padding See FLAC__metadata_chain_write()
  85265. * \param handle The I/O handle of the original FLAC stream to read.
  85266. * The handle will NOT be closed after the metadata is
  85267. * written; that is the duty of the caller.
  85268. * \param callbacks A set of callbacks to use for I/O on \a handle.
  85269. * The mandatory callbacks are \a read, \a seek, and
  85270. * \a eof.
  85271. * \param temp_handle The I/O handle of the FLAC stream to write. The
  85272. * handle will NOT be closed after the metadata is
  85273. * written; that is the duty of the caller.
  85274. * \param temp_callbacks
  85275. * A set of callbacks to use for I/O on temp_handle.
  85276. * The only mandatory callback is \a write.
  85277. * \assert
  85278. * \code chain != NULL \endcode
  85279. * \retval FLAC__bool
  85280. * \c true if the write succeeded, else \c false. On failure,
  85281. * check the status with FLAC__metadata_chain_status().
  85282. */
  85283. 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);
  85284. /** Merge adjacent PADDING blocks into a single block.
  85285. *
  85286. * \note This function does not write to the FLAC file, it only
  85287. * modifies the chain.
  85288. *
  85289. * \warning Any iterator on the current chain will become invalid after this
  85290. * call. You should delete the iterator and get a new one.
  85291. *
  85292. * \param chain A pointer to an existing chain.
  85293. * \assert
  85294. * \code chain != NULL \endcode
  85295. */
  85296. FLAC_API void FLAC__metadata_chain_merge_padding(FLAC__Metadata_Chain *chain);
  85297. /** This function will move all PADDING blocks to the end on the metadata,
  85298. * then merge them into a single block.
  85299. *
  85300. * \note This function does not write to the FLAC file, it only
  85301. * modifies the chain.
  85302. *
  85303. * \warning Any iterator on the current chain will become invalid after this
  85304. * call. You should delete the iterator and get a new one.
  85305. *
  85306. * \param chain A pointer to an existing chain.
  85307. * \assert
  85308. * \code chain != NULL \endcode
  85309. */
  85310. FLAC_API void FLAC__metadata_chain_sort_padding(FLAC__Metadata_Chain *chain);
  85311. /*********** FLAC__Metadata_Iterator ***********/
  85312. /** Create a new iterator instance.
  85313. *
  85314. * \retval FLAC__Metadata_Iterator*
  85315. * \c NULL if there was an error allocating memory, else the new instance.
  85316. */
  85317. FLAC_API FLAC__Metadata_Iterator *FLAC__metadata_iterator_new(void);
  85318. /** Free an iterator instance. Deletes the object pointed to by \a iterator.
  85319. *
  85320. * \param iterator A pointer to an existing iterator.
  85321. * \assert
  85322. * \code iterator != NULL \endcode
  85323. */
  85324. FLAC_API void FLAC__metadata_iterator_delete(FLAC__Metadata_Iterator *iterator);
  85325. /** Initialize the iterator to point to the first metadata block in the
  85326. * given chain.
  85327. *
  85328. * \param iterator A pointer to an existing iterator.
  85329. * \param chain A pointer to an existing and initialized (read) chain.
  85330. * \assert
  85331. * \code iterator != NULL \endcode
  85332. * \code chain != NULL \endcode
  85333. */
  85334. FLAC_API void FLAC__metadata_iterator_init(FLAC__Metadata_Iterator *iterator, FLAC__Metadata_Chain *chain);
  85335. /** Moves the iterator forward one metadata block, returning \c false if
  85336. * already at the end.
  85337. *
  85338. * \param iterator A pointer to an existing initialized iterator.
  85339. * \assert
  85340. * \code iterator != NULL \endcode
  85341. * \a iterator has been successfully initialized with
  85342. * FLAC__metadata_iterator_init()
  85343. * \retval FLAC__bool
  85344. * \c false if already at the last metadata block of the chain, else
  85345. * \c true.
  85346. */
  85347. FLAC_API FLAC__bool FLAC__metadata_iterator_next(FLAC__Metadata_Iterator *iterator);
  85348. /** Moves the iterator backward one metadata block, returning \c false if
  85349. * already at the beginning.
  85350. *
  85351. * \param iterator A pointer to an existing initialized iterator.
  85352. * \assert
  85353. * \code iterator != NULL \endcode
  85354. * \a iterator has been successfully initialized with
  85355. * FLAC__metadata_iterator_init()
  85356. * \retval FLAC__bool
  85357. * \c false if already at the first metadata block of the chain, else
  85358. * \c true.
  85359. */
  85360. FLAC_API FLAC__bool FLAC__metadata_iterator_prev(FLAC__Metadata_Iterator *iterator);
  85361. /** Get the type of the metadata block at the current position.
  85362. *
  85363. * \param iterator A pointer to an existing initialized iterator.
  85364. * \assert
  85365. * \code iterator != NULL \endcode
  85366. * \a iterator has been successfully initialized with
  85367. * FLAC__metadata_iterator_init()
  85368. * \retval FLAC__MetadataType
  85369. * The type of the metadata block at the current iterator position.
  85370. */
  85371. FLAC_API FLAC__MetadataType FLAC__metadata_iterator_get_block_type(const FLAC__Metadata_Iterator *iterator);
  85372. /** Get the metadata block at the current position. You can modify
  85373. * the block in place but must write the chain before the changes
  85374. * are reflected to the FLAC file. You do not need to call
  85375. * FLAC__metadata_iterator_set_block() to reflect the changes;
  85376. * the pointer returned by FLAC__metadata_iterator_get_block()
  85377. * points directly into the chain.
  85378. *
  85379. * \warning
  85380. * Do not call FLAC__metadata_object_delete() on the returned object;
  85381. * to delete a block use FLAC__metadata_iterator_delete_block().
  85382. *
  85383. * \param iterator A pointer to an existing initialized iterator.
  85384. * \assert
  85385. * \code iterator != NULL \endcode
  85386. * \a iterator has been successfully initialized with
  85387. * FLAC__metadata_iterator_init()
  85388. * \retval FLAC__StreamMetadata*
  85389. * The current metadata block.
  85390. */
  85391. FLAC_API FLAC__StreamMetadata *FLAC__metadata_iterator_get_block(FLAC__Metadata_Iterator *iterator);
  85392. /** Set the metadata block at the current position, replacing the existing
  85393. * block. The new block passed in becomes owned by the chain and it will be
  85394. * deleted when the chain is deleted.
  85395. *
  85396. * \param iterator A pointer to an existing initialized iterator.
  85397. * \param block A pointer to a metadata block.
  85398. * \assert
  85399. * \code iterator != NULL \endcode
  85400. * \a iterator has been successfully initialized with
  85401. * FLAC__metadata_iterator_init()
  85402. * \code block != NULL \endcode
  85403. * \retval FLAC__bool
  85404. * \c false if the conditions in the above description are not met, or
  85405. * a memory allocation error occurs, otherwise \c true.
  85406. */
  85407. FLAC_API FLAC__bool FLAC__metadata_iterator_set_block(FLAC__Metadata_Iterator *iterator, FLAC__StreamMetadata *block);
  85408. /** Removes the current block from the chain. If \a replace_with_padding is
  85409. * \c true, the block will instead be replaced with a padding block of equal
  85410. * size. You can not delete the STREAMINFO block. The iterator will be
  85411. * left pointing to the block before the one just "deleted", even if
  85412. * \a replace_with_padding is \c true.
  85413. *
  85414. * \param iterator A pointer to an existing initialized iterator.
  85415. * \param replace_with_padding See above.
  85416. * \assert
  85417. * \code iterator != NULL \endcode
  85418. * \a iterator has been successfully initialized with
  85419. * FLAC__metadata_iterator_init()
  85420. * \retval FLAC__bool
  85421. * \c false if the conditions in the above description are not met,
  85422. * otherwise \c true.
  85423. */
  85424. FLAC_API FLAC__bool FLAC__metadata_iterator_delete_block(FLAC__Metadata_Iterator *iterator, FLAC__bool replace_with_padding);
  85425. /** Insert a new block before the current block. You cannot insert a block
  85426. * before the first STREAMINFO block. You cannot insert a STREAMINFO block
  85427. * as there can be only one, the one that already exists at the head when you
  85428. * read in a chain. The chain takes ownership of the new block and it will be
  85429. * deleted when the chain is deleted. The iterator will be left pointing to
  85430. * the new block.
  85431. *
  85432. * \param iterator A pointer to an existing initialized iterator.
  85433. * \param block A pointer to a metadata block to insert.
  85434. * \assert
  85435. * \code iterator != NULL \endcode
  85436. * \a iterator has been successfully initialized with
  85437. * FLAC__metadata_iterator_init()
  85438. * \retval FLAC__bool
  85439. * \c false if the conditions in the above description are not met, or
  85440. * a memory allocation error occurs, otherwise \c true.
  85441. */
  85442. FLAC_API FLAC__bool FLAC__metadata_iterator_insert_block_before(FLAC__Metadata_Iterator *iterator, FLAC__StreamMetadata *block);
  85443. /** Insert a new block after the current block. You cannot insert a STREAMINFO
  85444. * block as there can be only one, the one that already exists at the head when
  85445. * you read in a chain. The chain takes ownership of the new block and it will
  85446. * be deleted when the chain is deleted. The iterator will be left pointing to
  85447. * the new block.
  85448. *
  85449. * \param iterator A pointer to an existing initialized iterator.
  85450. * \param block A pointer to a metadata block to insert.
  85451. * \assert
  85452. * \code iterator != NULL \endcode
  85453. * \a iterator has been successfully initialized with
  85454. * FLAC__metadata_iterator_init()
  85455. * \retval FLAC__bool
  85456. * \c false if the conditions in the above description are not met, or
  85457. * a memory allocation error occurs, otherwise \c true.
  85458. */
  85459. FLAC_API FLAC__bool FLAC__metadata_iterator_insert_block_after(FLAC__Metadata_Iterator *iterator, FLAC__StreamMetadata *block);
  85460. /* \} */
  85461. /** \defgroup flac_metadata_object FLAC/metadata.h: metadata object methods
  85462. * \ingroup flac_metadata
  85463. *
  85464. * \brief
  85465. * This module contains methods for manipulating FLAC metadata objects.
  85466. *
  85467. * Since many are variable length we have to be careful about the memory
  85468. * management. We decree that all pointers to data in the object are
  85469. * owned by the object and memory-managed by the object.
  85470. *
  85471. * Use the FLAC__metadata_object_new() and FLAC__metadata_object_delete()
  85472. * functions to create all instances. When using the
  85473. * FLAC__metadata_object_set_*() functions to set pointers to data, set
  85474. * \a copy to \c true to have the function make it's own copy of the data, or
  85475. * to \c false to give the object ownership of your data. In the latter case
  85476. * your pointer must be freeable by free() and will be free()d when the object
  85477. * is FLAC__metadata_object_delete()d. It is legal to pass a null pointer as
  85478. * the data pointer to a FLAC__metadata_object_set_*() function as long as
  85479. * the length argument is 0 and the \a copy argument is \c false.
  85480. *
  85481. * The FLAC__metadata_object_new() and FLAC__metadata_object_clone() function
  85482. * will return \c NULL in the case of a memory allocation error, otherwise a new
  85483. * object. The FLAC__metadata_object_set_*() functions return \c false in the
  85484. * case of a memory allocation error.
  85485. *
  85486. * We don't have the convenience of C++ here, so note that the library relies
  85487. * on you to keep the types straight. In other words, if you pass, for
  85488. * example, a FLAC__StreamMetadata* that represents a STREAMINFO block to
  85489. * FLAC__metadata_object_application_set_data(), you will get an assertion
  85490. * failure.
  85491. *
  85492. * For convenience the FLAC__metadata_object_vorbiscomment_*() functions
  85493. * maintain a trailing NUL on each Vorbis comment entry. This is not counted
  85494. * toward the length or stored in the stream, but it can make working with plain
  85495. * comments (those that don't contain embedded-NULs in the value) easier.
  85496. * Entries passed into these functions have trailing NULs added if missing, and
  85497. * returned entries are guaranteed to have a trailing NUL.
  85498. *
  85499. * The FLAC__metadata_object_vorbiscomment_*() functions that take a Vorbis
  85500. * comment entry/name/value will first validate that it complies with the Vorbis
  85501. * comment specification and return false if it does not.
  85502. *
  85503. * There is no need to recalculate the length field on metadata blocks you
  85504. * have modified. They will be calculated automatically before they are
  85505. * written back to a file.
  85506. *
  85507. * \{
  85508. */
  85509. /** Create a new metadata object instance of the given type.
  85510. *
  85511. * The object will be "empty"; i.e. values and data pointers will be \c 0,
  85512. * with the exception of FLAC__METADATA_TYPE_VORBIS_COMMENT, which will have
  85513. * the vendor string set (but zero comments).
  85514. *
  85515. * Do not pass in a value greater than or equal to
  85516. * \a FLAC__METADATA_TYPE_UNDEFINED unless you really know what you're
  85517. * doing.
  85518. *
  85519. * \param type Type of object to create
  85520. * \retval FLAC__StreamMetadata*
  85521. * \c NULL if there was an error allocating memory or the type code is
  85522. * greater than FLAC__MAX_METADATA_TYPE_CODE, else the new instance.
  85523. */
  85524. FLAC_API FLAC__StreamMetadata *FLAC__metadata_object_new(FLAC__MetadataType type);
  85525. /** Create a copy of an existing metadata object.
  85526. *
  85527. * The copy is a "deep" copy, i.e. dynamically allocated data within the
  85528. * object is also copied. The caller takes ownership of the new block and
  85529. * is responsible for freeing it with FLAC__metadata_object_delete().
  85530. *
  85531. * \param object Pointer to object to copy.
  85532. * \assert
  85533. * \code object != NULL \endcode
  85534. * \retval FLAC__StreamMetadata*
  85535. * \c NULL if there was an error allocating memory, else the new instance.
  85536. */
  85537. FLAC_API FLAC__StreamMetadata *FLAC__metadata_object_clone(const FLAC__StreamMetadata *object);
  85538. /** Free a metadata object. Deletes the object pointed to by \a object.
  85539. *
  85540. * The delete is a "deep" delete, i.e. dynamically allocated data within the
  85541. * object is also deleted.
  85542. *
  85543. * \param object A pointer to an existing object.
  85544. * \assert
  85545. * \code object != NULL \endcode
  85546. */
  85547. FLAC_API void FLAC__metadata_object_delete(FLAC__StreamMetadata *object);
  85548. /** Compares two metadata objects.
  85549. *
  85550. * The compare is "deep", i.e. dynamically allocated data within the
  85551. * object is also compared.
  85552. *
  85553. * \param block1 A pointer to an existing object.
  85554. * \param block2 A pointer to an existing object.
  85555. * \assert
  85556. * \code block1 != NULL \endcode
  85557. * \code block2 != NULL \endcode
  85558. * \retval FLAC__bool
  85559. * \c true if objects are identical, else \c false.
  85560. */
  85561. FLAC_API FLAC__bool FLAC__metadata_object_is_equal(const FLAC__StreamMetadata *block1, const FLAC__StreamMetadata *block2);
  85562. /** Sets the application data of an APPLICATION block.
  85563. *
  85564. * If \a copy is \c true, a copy of the data is stored; otherwise, the object
  85565. * takes ownership of the pointer. The existing data will be freed if this
  85566. * function is successful, otherwise the original data will remain if \a copy
  85567. * is \c true and malloc() fails.
  85568. *
  85569. * \note It is safe to pass a const pointer to \a data if \a copy is \c true.
  85570. *
  85571. * \param object A pointer to an existing APPLICATION object.
  85572. * \param data A pointer to the data to set.
  85573. * \param length The length of \a data in bytes.
  85574. * \param copy See above.
  85575. * \assert
  85576. * \code object != NULL \endcode
  85577. * \code object->type == FLAC__METADATA_TYPE_APPLICATION \endcode
  85578. * \code (data != NULL && length > 0) ||
  85579. * (data == NULL && length == 0 && copy == false) \endcode
  85580. * \retval FLAC__bool
  85581. * \c false if \a copy is \c true and malloc() fails, else \c true.
  85582. */
  85583. FLAC_API FLAC__bool FLAC__metadata_object_application_set_data(FLAC__StreamMetadata *object, FLAC__byte *data, unsigned length, FLAC__bool copy);
  85584. /** Resize the seekpoint array.
  85585. *
  85586. * If the size shrinks, elements will truncated; if it grows, new placeholder
  85587. * points will be added to the end.
  85588. *
  85589. * \param object A pointer to an existing SEEKTABLE object.
  85590. * \param new_num_points The desired length of the array; may be \c 0.
  85591. * \assert
  85592. * \code object != NULL \endcode
  85593. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  85594. * \code (object->data.seek_table.points == NULL && object->data.seek_table.num_points == 0) ||
  85595. * (object->data.seek_table.points != NULL && object->data.seek_table.num_points > 0) \endcode
  85596. * \retval FLAC__bool
  85597. * \c false if memory allocation error, else \c true.
  85598. */
  85599. FLAC_API FLAC__bool FLAC__metadata_object_seektable_resize_points(FLAC__StreamMetadata *object, unsigned new_num_points);
  85600. /** Set a seekpoint in a seektable.
  85601. *
  85602. * \param object A pointer to an existing SEEKTABLE object.
  85603. * \param point_num Index into seekpoint array to set.
  85604. * \param point The point to set.
  85605. * \assert
  85606. * \code object != NULL \endcode
  85607. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  85608. * \code object->data.seek_table.num_points > point_num \endcode
  85609. */
  85610. FLAC_API void FLAC__metadata_object_seektable_set_point(FLAC__StreamMetadata *object, unsigned point_num, FLAC__StreamMetadata_SeekPoint point);
  85611. /** Insert a seekpoint into a seektable.
  85612. *
  85613. * \param object A pointer to an existing SEEKTABLE object.
  85614. * \param point_num Index into seekpoint array to set.
  85615. * \param point The point to set.
  85616. * \assert
  85617. * \code object != NULL \endcode
  85618. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  85619. * \code object->data.seek_table.num_points >= point_num \endcode
  85620. * \retval FLAC__bool
  85621. * \c false if memory allocation error, else \c true.
  85622. */
  85623. FLAC_API FLAC__bool FLAC__metadata_object_seektable_insert_point(FLAC__StreamMetadata *object, unsigned point_num, FLAC__StreamMetadata_SeekPoint point);
  85624. /** Delete a seekpoint from a seektable.
  85625. *
  85626. * \param object A pointer to an existing SEEKTABLE object.
  85627. * \param point_num Index into seekpoint array to set.
  85628. * \assert
  85629. * \code object != NULL \endcode
  85630. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  85631. * \code object->data.seek_table.num_points > point_num \endcode
  85632. * \retval FLAC__bool
  85633. * \c false if memory allocation error, else \c true.
  85634. */
  85635. FLAC_API FLAC__bool FLAC__metadata_object_seektable_delete_point(FLAC__StreamMetadata *object, unsigned point_num);
  85636. /** Check a seektable to see if it conforms to the FLAC specification.
  85637. * See the format specification for limits on the contents of the
  85638. * seektable.
  85639. *
  85640. * \param object A pointer to an existing SEEKTABLE object.
  85641. * \assert
  85642. * \code object != NULL \endcode
  85643. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  85644. * \retval FLAC__bool
  85645. * \c false if seek table is illegal, else \c true.
  85646. */
  85647. FLAC_API FLAC__bool FLAC__metadata_object_seektable_is_legal(const FLAC__StreamMetadata *object);
  85648. /** Append a number of placeholder points to the end of a seek table.
  85649. *
  85650. * \note
  85651. * As with the other ..._seektable_template_... functions, you should
  85652. * call FLAC__metadata_object_seektable_template_sort() when finished
  85653. * to make the seek table legal.
  85654. *
  85655. * \param object A pointer to an existing SEEKTABLE object.
  85656. * \param num The number of placeholder points to append.
  85657. * \assert
  85658. * \code object != NULL \endcode
  85659. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  85660. * \retval FLAC__bool
  85661. * \c false if memory allocation fails, else \c true.
  85662. */
  85663. FLAC_API FLAC__bool FLAC__metadata_object_seektable_template_append_placeholders(FLAC__StreamMetadata *object, unsigned num);
  85664. /** Append a specific seek point template to the end of a seek table.
  85665. *
  85666. * \note
  85667. * As with the other ..._seektable_template_... functions, you should
  85668. * call FLAC__metadata_object_seektable_template_sort() when finished
  85669. * to make the seek table legal.
  85670. *
  85671. * \param object A pointer to an existing SEEKTABLE object.
  85672. * \param sample_number The sample number of the seek point template.
  85673. * \assert
  85674. * \code object != NULL \endcode
  85675. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  85676. * \retval FLAC__bool
  85677. * \c false if memory allocation fails, else \c true.
  85678. */
  85679. FLAC_API FLAC__bool FLAC__metadata_object_seektable_template_append_point(FLAC__StreamMetadata *object, FLAC__uint64 sample_number);
  85680. /** Append specific seek point templates to the end of a seek table.
  85681. *
  85682. * \note
  85683. * As with the other ..._seektable_template_... functions, you should
  85684. * call FLAC__metadata_object_seektable_template_sort() when finished
  85685. * to make the seek table legal.
  85686. *
  85687. * \param object A pointer to an existing SEEKTABLE object.
  85688. * \param sample_numbers An array of sample numbers for the seek points.
  85689. * \param num The number of seek point templates to append.
  85690. * \assert
  85691. * \code object != NULL \endcode
  85692. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  85693. * \retval FLAC__bool
  85694. * \c false if memory allocation fails, else \c true.
  85695. */
  85696. FLAC_API FLAC__bool FLAC__metadata_object_seektable_template_append_points(FLAC__StreamMetadata *object, FLAC__uint64 sample_numbers[], unsigned num);
  85697. /** Append a set of evenly-spaced seek point templates to the end of a
  85698. * seek table.
  85699. *
  85700. * \note
  85701. * As with the other ..._seektable_template_... functions, you should
  85702. * call FLAC__metadata_object_seektable_template_sort() when finished
  85703. * to make the seek table legal.
  85704. *
  85705. * \param object A pointer to an existing SEEKTABLE object.
  85706. * \param num The number of placeholder points to append.
  85707. * \param total_samples The total number of samples to be encoded;
  85708. * the seekpoints will be spaced approximately
  85709. * \a total_samples / \a num samples apart.
  85710. * \assert
  85711. * \code object != NULL \endcode
  85712. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  85713. * \code total_samples > 0 \endcode
  85714. * \retval FLAC__bool
  85715. * \c false if memory allocation fails, else \c true.
  85716. */
  85717. FLAC_API FLAC__bool FLAC__metadata_object_seektable_template_append_spaced_points(FLAC__StreamMetadata *object, unsigned num, FLAC__uint64 total_samples);
  85718. /** Append a set of evenly-spaced seek point templates to the end of a
  85719. * seek table.
  85720. *
  85721. * \note
  85722. * As with the other ..._seektable_template_... functions, you should
  85723. * call FLAC__metadata_object_seektable_template_sort() when finished
  85724. * to make the seek table legal.
  85725. *
  85726. * \param object A pointer to an existing SEEKTABLE object.
  85727. * \param samples The number of samples apart to space the placeholder
  85728. * points. The first point will be at sample \c 0, the
  85729. * second at sample \a samples, then 2*\a samples, and
  85730. * so on. As long as \a samples and \a total_samples
  85731. * are greater than \c 0, there will always be at least
  85732. * one seekpoint at sample \c 0.
  85733. * \param total_samples The total number of samples to be encoded;
  85734. * the seekpoints will be spaced
  85735. * \a samples samples apart.
  85736. * \assert
  85737. * \code object != NULL \endcode
  85738. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  85739. * \code samples > 0 \endcode
  85740. * \code total_samples > 0 \endcode
  85741. * \retval FLAC__bool
  85742. * \c false if memory allocation fails, else \c true.
  85743. */
  85744. FLAC_API FLAC__bool FLAC__metadata_object_seektable_template_append_spaced_points_by_samples(FLAC__StreamMetadata *object, unsigned samples, FLAC__uint64 total_samples);
  85745. /** Sort a seek table's seek points according to the format specification,
  85746. * removing duplicates.
  85747. *
  85748. * \param object A pointer to a seek table to be sorted.
  85749. * \param compact If \c false, behaves like FLAC__format_seektable_sort().
  85750. * If \c true, duplicates are deleted and the seek table is
  85751. * shrunk appropriately; the number of placeholder points
  85752. * present in the seek table will be the same after the call
  85753. * as before.
  85754. * \assert
  85755. * \code object != NULL \endcode
  85756. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  85757. * \retval FLAC__bool
  85758. * \c false if realloc() fails, else \c true.
  85759. */
  85760. FLAC_API FLAC__bool FLAC__metadata_object_seektable_template_sort(FLAC__StreamMetadata *object, FLAC__bool compact);
  85761. /** Sets the vendor string in a VORBIS_COMMENT block.
  85762. *
  85763. * For convenience, a trailing NUL is added to the entry if it doesn't have
  85764. * one already.
  85765. *
  85766. * If \a copy is \c true, a copy of the entry is stored; otherwise, the object
  85767. * takes ownership of the \c entry.entry pointer.
  85768. *
  85769. * \note If this function returns \c false, the caller still owns the
  85770. * pointer.
  85771. *
  85772. * \param object A pointer to an existing VORBIS_COMMENT object.
  85773. * \param entry The entry to set the vendor string to.
  85774. * \param copy See above.
  85775. * \assert
  85776. * \code object != NULL \endcode
  85777. * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode
  85778. * \code (entry.entry != NULL && entry.length > 0) ||
  85779. * (entry.entry == NULL && entry.length == 0) \endcode
  85780. * \retval FLAC__bool
  85781. * \c false if memory allocation fails or \a entry does not comply with the
  85782. * Vorbis comment specification, else \c true.
  85783. */
  85784. FLAC_API FLAC__bool FLAC__metadata_object_vorbiscomment_set_vendor_string(FLAC__StreamMetadata *object, FLAC__StreamMetadata_VorbisComment_Entry entry, FLAC__bool copy);
  85785. /** Resize the comment array.
  85786. *
  85787. * If the size shrinks, elements will truncated; if it grows, new empty
  85788. * fields will be added to the end.
  85789. *
  85790. * \param object A pointer to an existing VORBIS_COMMENT object.
  85791. * \param new_num_comments The desired length of the array; may be \c 0.
  85792. * \assert
  85793. * \code object != NULL \endcode
  85794. * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode
  85795. * \code (object->data.vorbis_comment.comments == NULL && object->data.vorbis_comment.num_comments == 0) ||
  85796. * (object->data.vorbis_comment.comments != NULL && object->data.vorbis_comment.num_comments > 0) \endcode
  85797. * \retval FLAC__bool
  85798. * \c false if memory allocation fails, else \c true.
  85799. */
  85800. FLAC_API FLAC__bool FLAC__metadata_object_vorbiscomment_resize_comments(FLAC__StreamMetadata *object, unsigned new_num_comments);
  85801. /** Sets a comment in a VORBIS_COMMENT block.
  85802. *
  85803. * For convenience, a trailing NUL is added to the entry if it doesn't have
  85804. * one already.
  85805. *
  85806. * If \a copy is \c true, a copy of the entry is stored; otherwise, the object
  85807. * takes ownership of the \c entry.entry pointer.
  85808. *
  85809. * \note If this function returns \c false, the caller still owns the
  85810. * pointer.
  85811. *
  85812. * \param object A pointer to an existing VORBIS_COMMENT object.
  85813. * \param comment_num Index into comment array to set.
  85814. * \param entry The entry to set the comment to.
  85815. * \param copy See above.
  85816. * \assert
  85817. * \code object != NULL \endcode
  85818. * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode
  85819. * \code comment_num < object->data.vorbis_comment.num_comments \endcode
  85820. * \code (entry.entry != NULL && entry.length > 0) ||
  85821. * (entry.entry == NULL && entry.length == 0) \endcode
  85822. * \retval FLAC__bool
  85823. * \c false if memory allocation fails or \a entry does not comply with the
  85824. * Vorbis comment specification, else \c true.
  85825. */
  85826. FLAC_API FLAC__bool FLAC__metadata_object_vorbiscomment_set_comment(FLAC__StreamMetadata *object, unsigned comment_num, FLAC__StreamMetadata_VorbisComment_Entry entry, FLAC__bool copy);
  85827. /** Insert a comment in a VORBIS_COMMENT block at the given index.
  85828. *
  85829. * For convenience, a trailing NUL is added to the entry if it doesn't have
  85830. * one already.
  85831. *
  85832. * If \a copy is \c true, a copy of the entry is stored; otherwise, the object
  85833. * takes ownership of the \c entry.entry pointer.
  85834. *
  85835. * \note If this function returns \c false, the caller still owns the
  85836. * pointer.
  85837. *
  85838. * \param object A pointer to an existing VORBIS_COMMENT object.
  85839. * \param comment_num The index at which to insert the comment. The comments
  85840. * at and after \a comment_num move right one position.
  85841. * To append a comment to the end, set \a comment_num to
  85842. * \c object->data.vorbis_comment.num_comments .
  85843. * \param entry The comment to insert.
  85844. * \param copy See above.
  85845. * \assert
  85846. * \code object != NULL \endcode
  85847. * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode
  85848. * \code object->data.vorbis_comment.num_comments >= comment_num \endcode
  85849. * \code (entry.entry != NULL && entry.length > 0) ||
  85850. * (entry.entry == NULL && entry.length == 0 && copy == false) \endcode
  85851. * \retval FLAC__bool
  85852. * \c false if memory allocation fails or \a entry does not comply with the
  85853. * Vorbis comment specification, else \c true.
  85854. */
  85855. FLAC_API FLAC__bool FLAC__metadata_object_vorbiscomment_insert_comment(FLAC__StreamMetadata *object, unsigned comment_num, FLAC__StreamMetadata_VorbisComment_Entry entry, FLAC__bool copy);
  85856. /** Appends a comment to a VORBIS_COMMENT block.
  85857. *
  85858. * For convenience, a trailing NUL is added to the entry if it doesn't have
  85859. * one already.
  85860. *
  85861. * If \a copy is \c true, a copy of the entry is stored; otherwise, the object
  85862. * takes ownership of the \c entry.entry pointer.
  85863. *
  85864. * \note If this function returns \c false, the caller still owns the
  85865. * pointer.
  85866. *
  85867. * \param object A pointer to an existing VORBIS_COMMENT object.
  85868. * \param entry The comment to insert.
  85869. * \param copy See above.
  85870. * \assert
  85871. * \code object != NULL \endcode
  85872. * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode
  85873. * \code (entry.entry != NULL && entry.length > 0) ||
  85874. * (entry.entry == NULL && entry.length == 0 && copy == false) \endcode
  85875. * \retval FLAC__bool
  85876. * \c false if memory allocation fails or \a entry does not comply with the
  85877. * Vorbis comment specification, else \c true.
  85878. */
  85879. FLAC_API FLAC__bool FLAC__metadata_object_vorbiscomment_append_comment(FLAC__StreamMetadata *object, FLAC__StreamMetadata_VorbisComment_Entry entry, FLAC__bool copy);
  85880. /** Replaces comments in a VORBIS_COMMENT block with a new one.
  85881. *
  85882. * For convenience, a trailing NUL is added to the entry if it doesn't have
  85883. * one already.
  85884. *
  85885. * Depending on the the value of \a all, either all or just the first comment
  85886. * whose field name(s) match the given entry's name will be replaced by the
  85887. * given entry. If no comments match, \a entry will simply be appended.
  85888. *
  85889. * If \a copy is \c true, a copy of the entry is stored; otherwise, the object
  85890. * takes ownership of the \c entry.entry pointer.
  85891. *
  85892. * \note If this function returns \c false, the caller still owns the
  85893. * pointer.
  85894. *
  85895. * \param object A pointer to an existing VORBIS_COMMENT object.
  85896. * \param entry The comment to insert.
  85897. * \param all If \c true, all comments whose field name matches
  85898. * \a entry's field name will be removed, and \a entry will
  85899. * be inserted at the position of the first matching
  85900. * comment. If \c false, only the first comment whose
  85901. * field name matches \a entry's field name will be
  85902. * replaced with \a entry.
  85903. * \param copy See above.
  85904. * \assert
  85905. * \code object != NULL \endcode
  85906. * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode
  85907. * \code (entry.entry != NULL && entry.length > 0) ||
  85908. * (entry.entry == NULL && entry.length == 0 && copy == false) \endcode
  85909. * \retval FLAC__bool
  85910. * \c false if memory allocation fails or \a entry does not comply with the
  85911. * Vorbis comment specification, else \c true.
  85912. */
  85913. FLAC_API FLAC__bool FLAC__metadata_object_vorbiscomment_replace_comment(FLAC__StreamMetadata *object, FLAC__StreamMetadata_VorbisComment_Entry entry, FLAC__bool all, FLAC__bool copy);
  85914. /** Delete a comment in a VORBIS_COMMENT block at the given index.
  85915. *
  85916. * \param object A pointer to an existing VORBIS_COMMENT object.
  85917. * \param comment_num The index of the comment to delete.
  85918. * \assert
  85919. * \code object != NULL \endcode
  85920. * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode
  85921. * \code object->data.vorbis_comment.num_comments > comment_num \endcode
  85922. * \retval FLAC__bool
  85923. * \c false if realloc() fails, else \c true.
  85924. */
  85925. FLAC_API FLAC__bool FLAC__metadata_object_vorbiscomment_delete_comment(FLAC__StreamMetadata *object, unsigned comment_num);
  85926. /** Creates a Vorbis comment entry from NUL-terminated name and value strings.
  85927. *
  85928. * On return, the filled-in \a entry->entry pointer will point to malloc()ed
  85929. * memory and shall be owned by the caller. For convenience the entry will
  85930. * have a terminating NUL.
  85931. *
  85932. * \param entry A pointer to a Vorbis comment entry. The entry's
  85933. * \c entry pointer should not point to allocated
  85934. * memory as it will be overwritten.
  85935. * \param field_name The field name in ASCII, \c NUL terminated.
  85936. * \param field_value The field value in UTF-8, \c NUL terminated.
  85937. * \assert
  85938. * \code entry != NULL \endcode
  85939. * \code field_name != NULL \endcode
  85940. * \code field_value != NULL \endcode
  85941. * \retval FLAC__bool
  85942. * \c false if malloc() fails, or if \a field_name or \a field_value does
  85943. * not comply with the Vorbis comment specification, else \c true.
  85944. */
  85945. 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);
  85946. /** Splits a Vorbis comment entry into NUL-terminated name and value strings.
  85947. *
  85948. * The returned pointers to name and value will be allocated by malloc()
  85949. * and shall be owned by the caller.
  85950. *
  85951. * \param entry An existing Vorbis comment entry.
  85952. * \param field_name The address of where the returned pointer to the
  85953. * field name will be stored.
  85954. * \param field_value The address of where the returned pointer to the
  85955. * field value will be stored.
  85956. * \assert
  85957. * \code (entry.entry != NULL && entry.length > 0) \endcode
  85958. * \code memchr(entry.entry, '=', entry.length) != NULL \endcode
  85959. * \code field_name != NULL \endcode
  85960. * \code field_value != NULL \endcode
  85961. * \retval FLAC__bool
  85962. * \c false if memory allocation fails or \a entry does not comply with the
  85963. * Vorbis comment specification, else \c true.
  85964. */
  85965. 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);
  85966. /** Check if the given Vorbis comment entry's field name matches the given
  85967. * field name.
  85968. *
  85969. * \param entry An existing Vorbis comment entry.
  85970. * \param field_name The field name to check.
  85971. * \param field_name_length The length of \a field_name, not including the
  85972. * terminating \c NUL.
  85973. * \assert
  85974. * \code (entry.entry != NULL && entry.length > 0) \endcode
  85975. * \retval FLAC__bool
  85976. * \c true if the field names match, else \c false
  85977. */
  85978. FLAC_API FLAC__bool FLAC__metadata_object_vorbiscomment_entry_matches(const FLAC__StreamMetadata_VorbisComment_Entry entry, const char *field_name, unsigned field_name_length);
  85979. /** Find a Vorbis comment with the given field name.
  85980. *
  85981. * The search begins at entry number \a offset; use an offset of 0 to
  85982. * search from the beginning of the comment array.
  85983. *
  85984. * \param object A pointer to an existing VORBIS_COMMENT object.
  85985. * \param offset The offset into the comment array from where to start
  85986. * the search.
  85987. * \param field_name The field name of the comment to find.
  85988. * \assert
  85989. * \code object != NULL \endcode
  85990. * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode
  85991. * \code field_name != NULL \endcode
  85992. * \retval int
  85993. * The offset in the comment array of the first comment whose field
  85994. * name matches \a field_name, or \c -1 if no match was found.
  85995. */
  85996. FLAC_API int FLAC__metadata_object_vorbiscomment_find_entry_from(const FLAC__StreamMetadata *object, unsigned offset, const char *field_name);
  85997. /** Remove first Vorbis comment matching the given field name.
  85998. *
  85999. * \param object A pointer to an existing VORBIS_COMMENT object.
  86000. * \param field_name The field name of comment to delete.
  86001. * \assert
  86002. * \code object != NULL \endcode
  86003. * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode
  86004. * \retval int
  86005. * \c -1 for memory allocation error, \c 0 for no matching entries,
  86006. * \c 1 for one matching entry deleted.
  86007. */
  86008. FLAC_API int FLAC__metadata_object_vorbiscomment_remove_entry_matching(FLAC__StreamMetadata *object, const char *field_name);
  86009. /** Remove all Vorbis comments matching the given field name.
  86010. *
  86011. * \param object A pointer to an existing VORBIS_COMMENT object.
  86012. * \param field_name The field name of comments to delete.
  86013. * \assert
  86014. * \code object != NULL \endcode
  86015. * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode
  86016. * \retval int
  86017. * \c -1 for memory allocation error, \c 0 for no matching entries,
  86018. * else the number of matching entries deleted.
  86019. */
  86020. FLAC_API int FLAC__metadata_object_vorbiscomment_remove_entries_matching(FLAC__StreamMetadata *object, const char *field_name);
  86021. /** Create a new CUESHEET track instance.
  86022. *
  86023. * The object will be "empty"; i.e. values and data pointers will be \c 0.
  86024. *
  86025. * \retval FLAC__StreamMetadata_CueSheet_Track*
  86026. * \c NULL if there was an error allocating memory, else the new instance.
  86027. */
  86028. FLAC_API FLAC__StreamMetadata_CueSheet_Track *FLAC__metadata_object_cuesheet_track_new(void);
  86029. /** Create a copy of an existing CUESHEET track object.
  86030. *
  86031. * The copy is a "deep" copy, i.e. dynamically allocated data within the
  86032. * object is also copied. The caller takes ownership of the new object and
  86033. * is responsible for freeing it with
  86034. * FLAC__metadata_object_cuesheet_track_delete().
  86035. *
  86036. * \param object Pointer to object to copy.
  86037. * \assert
  86038. * \code object != NULL \endcode
  86039. * \retval FLAC__StreamMetadata_CueSheet_Track*
  86040. * \c NULL if there was an error allocating memory, else the new instance.
  86041. */
  86042. FLAC_API FLAC__StreamMetadata_CueSheet_Track *FLAC__metadata_object_cuesheet_track_clone(const FLAC__StreamMetadata_CueSheet_Track *object);
  86043. /** Delete a CUESHEET track object
  86044. *
  86045. * \param object A pointer to an existing CUESHEET track object.
  86046. * \assert
  86047. * \code object != NULL \endcode
  86048. */
  86049. FLAC_API void FLAC__metadata_object_cuesheet_track_delete(FLAC__StreamMetadata_CueSheet_Track *object);
  86050. /** Resize a track's index point array.
  86051. *
  86052. * If the size shrinks, elements will truncated; if it grows, new blank
  86053. * indices will be added to the end.
  86054. *
  86055. * \param object A pointer to an existing CUESHEET object.
  86056. * \param track_num The index of the track to modify. NOTE: this is not
  86057. * necessarily the same as the track's \a number field.
  86058. * \param new_num_indices The desired length of the array; may be \c 0.
  86059. * \assert
  86060. * \code object != NULL \endcode
  86061. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  86062. * \code object->data.cue_sheet.num_tracks > track_num \endcode
  86063. * \code (object->data.cue_sheet.tracks[track_num].indices == NULL && object->data.cue_sheet.tracks[track_num].num_indices == 0) ||
  86064. * (object->data.cue_sheet.tracks[track_num].indices != NULL && object->data.cue_sheet.tracks[track_num].num_indices > 0) \endcode
  86065. * \retval FLAC__bool
  86066. * \c false if memory allocation error, else \c true.
  86067. */
  86068. FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_track_resize_indices(FLAC__StreamMetadata *object, unsigned track_num, unsigned new_num_indices);
  86069. /** Insert an index point in a CUESHEET track at the given index.
  86070. *
  86071. * \param object A pointer to an existing CUESHEET object.
  86072. * \param track_num The index of the track to modify. NOTE: this is not
  86073. * necessarily the same as the track's \a number field.
  86074. * \param index_num The index into the track's index array at which to
  86075. * insert the index point. NOTE: this is not necessarily
  86076. * the same as the index point's \a number field. The
  86077. * indices at and after \a index_num move right one
  86078. * position. To append an index point to the end, set
  86079. * \a index_num to
  86080. * \c object->data.cue_sheet.tracks[track_num].num_indices .
  86081. * \param index The index point to insert.
  86082. * \assert
  86083. * \code object != NULL \endcode
  86084. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  86085. * \code object->data.cue_sheet.num_tracks > track_num \endcode
  86086. * \code object->data.cue_sheet.tracks[track_num].num_indices >= index_num \endcode
  86087. * \retval FLAC__bool
  86088. * \c false if realloc() fails, else \c true.
  86089. */
  86090. 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);
  86091. /** Insert a blank index point in a CUESHEET track at the given index.
  86092. *
  86093. * A blank index point is one in which all field values are zero.
  86094. *
  86095. * \param object A pointer to an existing CUESHEET object.
  86096. * \param track_num The index of the track to modify. NOTE: this is not
  86097. * necessarily the same as the track's \a number field.
  86098. * \param index_num The index into the track's index array at which to
  86099. * insert the index point. NOTE: this is not necessarily
  86100. * the same as the index point's \a number field. The
  86101. * indices at and after \a index_num move right one
  86102. * position. To append an index point to the end, set
  86103. * \a index_num to
  86104. * \c object->data.cue_sheet.tracks[track_num].num_indices .
  86105. * \assert
  86106. * \code object != NULL \endcode
  86107. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  86108. * \code object->data.cue_sheet.num_tracks > track_num \endcode
  86109. * \code object->data.cue_sheet.tracks[track_num].num_indices >= index_num \endcode
  86110. * \retval FLAC__bool
  86111. * \c false if realloc() fails, else \c true.
  86112. */
  86113. FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_track_insert_blank_index(FLAC__StreamMetadata *object, unsigned track_num, unsigned index_num);
  86114. /** Delete an index point in a CUESHEET track at the given index.
  86115. *
  86116. * \param object A pointer to an existing CUESHEET object.
  86117. * \param track_num The index into the track array of the track to
  86118. * modify. NOTE: this is not necessarily the same
  86119. * as the track's \a number field.
  86120. * \param index_num The index into the track's index array of the index
  86121. * to delete. NOTE: this is not necessarily the same
  86122. * as the index's \a number field.
  86123. * \assert
  86124. * \code object != NULL \endcode
  86125. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  86126. * \code object->data.cue_sheet.num_tracks > track_num \endcode
  86127. * \code object->data.cue_sheet.tracks[track_num].num_indices > index_num \endcode
  86128. * \retval FLAC__bool
  86129. * \c false if realloc() fails, else \c true.
  86130. */
  86131. FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_track_delete_index(FLAC__StreamMetadata *object, unsigned track_num, unsigned index_num);
  86132. /** Resize the track array.
  86133. *
  86134. * If the size shrinks, elements will truncated; if it grows, new blank
  86135. * tracks will be added to the end.
  86136. *
  86137. * \param object A pointer to an existing CUESHEET object.
  86138. * \param new_num_tracks The desired length of the array; may be \c 0.
  86139. * \assert
  86140. * \code object != NULL \endcode
  86141. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  86142. * \code (object->data.cue_sheet.tracks == NULL && object->data.cue_sheet.num_tracks == 0) ||
  86143. * (object->data.cue_sheet.tracks != NULL && object->data.cue_sheet.num_tracks > 0) \endcode
  86144. * \retval FLAC__bool
  86145. * \c false if memory allocation error, else \c true.
  86146. */
  86147. FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_resize_tracks(FLAC__StreamMetadata *object, unsigned new_num_tracks);
  86148. /** Sets a track in a CUESHEET block.
  86149. *
  86150. * If \a copy is \c true, a copy of the track is stored; otherwise, the object
  86151. * takes ownership of the \a track pointer.
  86152. *
  86153. * \param object A pointer to an existing CUESHEET object.
  86154. * \param track_num Index into track array to set. NOTE: this is not
  86155. * necessarily the same as the track's \a number field.
  86156. * \param track The track to set the track to. You may safely pass in
  86157. * a const pointer if \a copy is \c true.
  86158. * \param copy See above.
  86159. * \assert
  86160. * \code object != NULL \endcode
  86161. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  86162. * \code track_num < object->data.cue_sheet.num_tracks \endcode
  86163. * \code (track->indices != NULL && track->num_indices > 0) ||
  86164. * (track->indices == NULL && track->num_indices == 0)
  86165. * \retval FLAC__bool
  86166. * \c false if \a copy is \c true and malloc() fails, else \c true.
  86167. */
  86168. FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_set_track(FLAC__StreamMetadata *object, unsigned track_num, FLAC__StreamMetadata_CueSheet_Track *track, FLAC__bool copy);
  86169. /** Insert a track in a CUESHEET block at the given index.
  86170. *
  86171. * If \a copy is \c true, a copy of the track is stored; otherwise, the object
  86172. * takes ownership of the \a track pointer.
  86173. *
  86174. * \param object A pointer to an existing CUESHEET object.
  86175. * \param track_num The index at which to insert the track. NOTE: this
  86176. * is not necessarily the same as the track's \a number
  86177. * field. The tracks at and after \a track_num move right
  86178. * one position. To append a track to the end, set
  86179. * \a track_num to \c object->data.cue_sheet.num_tracks .
  86180. * \param track The track to insert. You may safely pass in a const
  86181. * pointer if \a copy is \c true.
  86182. * \param copy See above.
  86183. * \assert
  86184. * \code object != NULL \endcode
  86185. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  86186. * \code object->data.cue_sheet.num_tracks >= track_num \endcode
  86187. * \retval FLAC__bool
  86188. * \c false if \a copy is \c true and malloc() fails, else \c true.
  86189. */
  86190. FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_insert_track(FLAC__StreamMetadata *object, unsigned track_num, FLAC__StreamMetadata_CueSheet_Track *track, FLAC__bool copy);
  86191. /** Insert a blank track in a CUESHEET block at the given index.
  86192. *
  86193. * A blank track is one in which all field values are zero.
  86194. *
  86195. * \param object A pointer to an existing CUESHEET object.
  86196. * \param track_num The index at which to insert the track. NOTE: this
  86197. * is not necessarily the same as the track's \a number
  86198. * field. The tracks at and after \a track_num move right
  86199. * one position. To append a track to the end, set
  86200. * \a track_num to \c object->data.cue_sheet.num_tracks .
  86201. * \assert
  86202. * \code object != NULL \endcode
  86203. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  86204. * \code object->data.cue_sheet.num_tracks >= track_num \endcode
  86205. * \retval FLAC__bool
  86206. * \c false if \a copy is \c true and malloc() fails, else \c true.
  86207. */
  86208. FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_insert_blank_track(FLAC__StreamMetadata *object, unsigned track_num);
  86209. /** Delete a track in a CUESHEET block at the given index.
  86210. *
  86211. * \param object A pointer to an existing CUESHEET object.
  86212. * \param track_num The index into the track array of the track to
  86213. * delete. NOTE: this is not necessarily the same
  86214. * as the track's \a number field.
  86215. * \assert
  86216. * \code object != NULL \endcode
  86217. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  86218. * \code object->data.cue_sheet.num_tracks > track_num \endcode
  86219. * \retval FLAC__bool
  86220. * \c false if realloc() fails, else \c true.
  86221. */
  86222. FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_delete_track(FLAC__StreamMetadata *object, unsigned track_num);
  86223. /** Check a cue sheet to see if it conforms to the FLAC specification.
  86224. * See the format specification for limits on the contents of the
  86225. * cue sheet.
  86226. *
  86227. * \param object A pointer to an existing CUESHEET object.
  86228. * \param check_cd_da_subset If \c true, check CUESHEET against more
  86229. * stringent requirements for a CD-DA (audio) disc.
  86230. * \param violation Address of a pointer to a string. If there is a
  86231. * violation, a pointer to a string explanation of the
  86232. * violation will be returned here. \a violation may be
  86233. * \c NULL if you don't need the returned string. Do not
  86234. * free the returned string; it will always point to static
  86235. * data.
  86236. * \assert
  86237. * \code object != NULL \endcode
  86238. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  86239. * \retval FLAC__bool
  86240. * \c false if cue sheet is illegal, else \c true.
  86241. */
  86242. FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_is_legal(const FLAC__StreamMetadata *object, FLAC__bool check_cd_da_subset, const char **violation);
  86243. /** Calculate and return the CDDB/freedb ID for a cue sheet. The function
  86244. * assumes the cue sheet corresponds to a CD; the result is undefined
  86245. * if the cuesheet's is_cd bit is not set.
  86246. *
  86247. * \param object A pointer to an existing CUESHEET object.
  86248. * \assert
  86249. * \code object != NULL \endcode
  86250. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  86251. * \retval FLAC__uint32
  86252. * The unsigned integer representation of the CDDB/freedb ID
  86253. */
  86254. FLAC_API FLAC__uint32 FLAC__metadata_object_cuesheet_calculate_cddb_id(const FLAC__StreamMetadata *object);
  86255. /** Sets the MIME type of a PICTURE block.
  86256. *
  86257. * If \a copy is \c true, a copy of the string is stored; otherwise, the object
  86258. * takes ownership of the pointer. The existing string will be freed if this
  86259. * function is successful, otherwise the original string will remain if \a copy
  86260. * is \c true and malloc() fails.
  86261. *
  86262. * \note It is safe to pass a const pointer to \a mime_type if \a copy is \c true.
  86263. *
  86264. * \param object A pointer to an existing PICTURE object.
  86265. * \param mime_type A pointer to the MIME type string. The string must be
  86266. * ASCII characters 0x20-0x7e, NUL-terminated. No validation
  86267. * is done.
  86268. * \param copy See above.
  86269. * \assert
  86270. * \code object != NULL \endcode
  86271. * \code object->type == FLAC__METADATA_TYPE_PICTURE \endcode
  86272. * \code (mime_type != NULL) \endcode
  86273. * \retval FLAC__bool
  86274. * \c false if \a copy is \c true and malloc() fails, else \c true.
  86275. */
  86276. FLAC_API FLAC__bool FLAC__metadata_object_picture_set_mime_type(FLAC__StreamMetadata *object, char *mime_type, FLAC__bool copy);
  86277. /** Sets the description of a PICTURE block.
  86278. *
  86279. * If \a copy is \c true, a copy of the string is stored; otherwise, the object
  86280. * takes ownership of the pointer. The existing string will be freed if this
  86281. * function is successful, otherwise the original string will remain if \a copy
  86282. * is \c true and malloc() fails.
  86283. *
  86284. * \note It is safe to pass a const pointer to \a description if \a copy is \c true.
  86285. *
  86286. * \param object A pointer to an existing PICTURE object.
  86287. * \param description A pointer to the description string. The string must be
  86288. * valid UTF-8, NUL-terminated. No validation is done.
  86289. * \param copy See above.
  86290. * \assert
  86291. * \code object != NULL \endcode
  86292. * \code object->type == FLAC__METADATA_TYPE_PICTURE \endcode
  86293. * \code (description != NULL) \endcode
  86294. * \retval FLAC__bool
  86295. * \c false if \a copy is \c true and malloc() fails, else \c true.
  86296. */
  86297. FLAC_API FLAC__bool FLAC__metadata_object_picture_set_description(FLAC__StreamMetadata *object, FLAC__byte *description, FLAC__bool copy);
  86298. /** Sets the picture data of a PICTURE block.
  86299. *
  86300. * If \a copy is \c true, a copy of the data is stored; otherwise, the object
  86301. * takes ownership of the pointer. Also sets the \a data_length field of the
  86302. * metadata object to what is passed in as the \a length parameter. The
  86303. * existing data will be freed if this function is successful, otherwise the
  86304. * original data and data_length will remain if \a copy is \c true and
  86305. * malloc() fails.
  86306. *
  86307. * \note It is safe to pass a const pointer to \a data if \a copy is \c true.
  86308. *
  86309. * \param object A pointer to an existing PICTURE object.
  86310. * \param data A pointer to the data to set.
  86311. * \param length The length of \a data in bytes.
  86312. * \param copy See above.
  86313. * \assert
  86314. * \code object != NULL \endcode
  86315. * \code object->type == FLAC__METADATA_TYPE_PICTURE \endcode
  86316. * \code (data != NULL && length > 0) ||
  86317. * (data == NULL && length == 0 && copy == false) \endcode
  86318. * \retval FLAC__bool
  86319. * \c false if \a copy is \c true and malloc() fails, else \c true.
  86320. */
  86321. FLAC_API FLAC__bool FLAC__metadata_object_picture_set_data(FLAC__StreamMetadata *object, FLAC__byte *data, FLAC__uint32 length, FLAC__bool copy);
  86322. /** Check a PICTURE block to see if it conforms to the FLAC specification.
  86323. * See the format specification for limits on the contents of the
  86324. * PICTURE block.
  86325. *
  86326. * \param object A pointer to existing PICTURE block to be checked.
  86327. * \param violation Address of a pointer to a string. If there is a
  86328. * violation, a pointer to a string explanation of the
  86329. * violation will be returned here. \a violation may be
  86330. * \c NULL if you don't need the returned string. Do not
  86331. * free the returned string; it will always point to static
  86332. * data.
  86333. * \assert
  86334. * \code object != NULL \endcode
  86335. * \code object->type == FLAC__METADATA_TYPE_PICTURE \endcode
  86336. * \retval FLAC__bool
  86337. * \c false if PICTURE block is illegal, else \c true.
  86338. */
  86339. FLAC_API FLAC__bool FLAC__metadata_object_picture_is_legal(const FLAC__StreamMetadata *object, const char **violation);
  86340. /* \} */
  86341. #ifdef __cplusplus
  86342. }
  86343. #endif
  86344. #endif
  86345. /*** End of inlined file: metadata.h ***/
  86346. /*** Start of inlined file: stream_decoder.h ***/
  86347. #ifndef FLAC__STREAM_DECODER_H
  86348. #define FLAC__STREAM_DECODER_H
  86349. #include <stdio.h> /* for FILE */
  86350. #ifdef __cplusplus
  86351. extern "C" {
  86352. #endif
  86353. /** \file include/FLAC/stream_decoder.h
  86354. *
  86355. * \brief
  86356. * This module contains the functions which implement the stream
  86357. * decoder.
  86358. *
  86359. * See the detailed documentation in the
  86360. * \link flac_stream_decoder stream decoder \endlink module.
  86361. */
  86362. /** \defgroup flac_decoder FLAC/ \*_decoder.h: decoder interfaces
  86363. * \ingroup flac
  86364. *
  86365. * \brief
  86366. * This module describes the decoder layers provided by libFLAC.
  86367. *
  86368. * The stream decoder can be used to decode complete streams either from
  86369. * the client via callbacks, or directly from a file, depending on how
  86370. * it is initialized. When decoding via callbacks, the client provides
  86371. * callbacks for reading FLAC data and writing decoded samples, and
  86372. * handling metadata and errors. If the client also supplies seek-related
  86373. * callback, the decoder function for sample-accurate seeking within the
  86374. * FLAC input is also available. When decoding from a file, the client
  86375. * needs only supply a filename or open \c FILE* and write/metadata/error
  86376. * callbacks; the rest of the callbacks are supplied internally. For more
  86377. * info see the \link flac_stream_decoder stream decoder \endlink module.
  86378. */
  86379. /** \defgroup flac_stream_decoder FLAC/stream_decoder.h: stream decoder interface
  86380. * \ingroup flac_decoder
  86381. *
  86382. * \brief
  86383. * This module contains the functions which implement the stream
  86384. * decoder.
  86385. *
  86386. * The stream decoder can decode native FLAC, and optionally Ogg FLAC
  86387. * (check FLAC_API_SUPPORTS_OGG_FLAC) streams and files.
  86388. *
  86389. * The basic usage of this decoder is as follows:
  86390. * - The program creates an instance of a decoder using
  86391. * FLAC__stream_decoder_new().
  86392. * - The program overrides the default settings using
  86393. * FLAC__stream_decoder_set_*() functions.
  86394. * - The program initializes the instance to validate the settings and
  86395. * prepare for decoding using
  86396. * - FLAC__stream_decoder_init_stream() or FLAC__stream_decoder_init_FILE()
  86397. * or FLAC__stream_decoder_init_file() for native FLAC,
  86398. * - FLAC__stream_decoder_init_ogg_stream() or FLAC__stream_decoder_init_ogg_FILE()
  86399. * or FLAC__stream_decoder_init_ogg_file() for Ogg FLAC
  86400. * - The program calls the FLAC__stream_decoder_process_*() functions
  86401. * to decode data, which subsequently calls the callbacks.
  86402. * - The program finishes the decoding with FLAC__stream_decoder_finish(),
  86403. * which flushes the input and output and resets the decoder to the
  86404. * uninitialized state.
  86405. * - The instance may be used again or deleted with
  86406. * FLAC__stream_decoder_delete().
  86407. *
  86408. * In more detail, the program will create a new instance by calling
  86409. * FLAC__stream_decoder_new(), then call FLAC__stream_decoder_set_*()
  86410. * functions to override the default decoder options, and call
  86411. * one of the FLAC__stream_decoder_init_*() functions.
  86412. *
  86413. * There are three initialization functions for native FLAC, one for
  86414. * setting up the decoder to decode FLAC data from the client via
  86415. * callbacks, and two for decoding directly from a FLAC file.
  86416. *
  86417. * For decoding via callbacks, use FLAC__stream_decoder_init_stream().
  86418. * You must also supply several callbacks for handling I/O. Some (like
  86419. * seeking) are optional, depending on the capabilities of the input.
  86420. *
  86421. * For decoding directly from a file, use FLAC__stream_decoder_init_FILE()
  86422. * or FLAC__stream_decoder_init_file(). Then you must only supply an open
  86423. * \c FILE* or filename and fewer callbacks; the decoder will handle
  86424. * the other callbacks internally.
  86425. *
  86426. * There are three similarly-named init functions for decoding from Ogg
  86427. * FLAC streams. Check \c FLAC_API_SUPPORTS_OGG_FLAC to find out if the
  86428. * library has been built with Ogg support.
  86429. *
  86430. * Once the decoder is initialized, your program will call one of several
  86431. * functions to start the decoding process:
  86432. *
  86433. * - FLAC__stream_decoder_process_single() - Tells the decoder to process at
  86434. * most one metadata block or audio frame and return, calling either the
  86435. * metadata callback or write callback, respectively, once. If the decoder
  86436. * loses sync it will return with only the error callback being called.
  86437. * - FLAC__stream_decoder_process_until_end_of_metadata() - Tells the decoder
  86438. * to process the stream from the current location and stop upon reaching
  86439. * the first audio frame. The client will get one metadata, write, or error
  86440. * callback per metadata block, audio frame, or sync error, respectively.
  86441. * - FLAC__stream_decoder_process_until_end_of_stream() - Tells the decoder
  86442. * to process the stream from the current location until the read callback
  86443. * returns FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM or
  86444. * FLAC__STREAM_DECODER_READ_STATUS_ABORT. The client will get one metadata,
  86445. * write, or error callback per metadata block, audio frame, or sync error,
  86446. * respectively.
  86447. *
  86448. * When the decoder has finished decoding (normally or through an abort),
  86449. * the instance is finished by calling FLAC__stream_decoder_finish(), which
  86450. * ensures the decoder is in the correct state and frees memory. Then the
  86451. * instance may be deleted with FLAC__stream_decoder_delete() or initialized
  86452. * again to decode another stream.
  86453. *
  86454. * Seeking is exposed through the FLAC__stream_decoder_seek_absolute() method.
  86455. * At any point after the stream decoder has been initialized, the client can
  86456. * call this function to seek to an exact sample within the stream.
  86457. * Subsequently, the first time the write callback is called it will be
  86458. * passed a (possibly partial) block starting at that sample.
  86459. *
  86460. * If the client cannot seek via the callback interface provided, but still
  86461. * has another way of seeking, it can flush the decoder using
  86462. * FLAC__stream_decoder_flush() and start feeding data from the new position
  86463. * through the read callback.
  86464. *
  86465. * The stream decoder also provides MD5 signature checking. If this is
  86466. * turned on before initialization, FLAC__stream_decoder_finish() will
  86467. * report when the decoded MD5 signature does not match the one stored
  86468. * in the STREAMINFO block. MD5 checking is automatically turned off
  86469. * (until the next FLAC__stream_decoder_reset()) if there is no signature
  86470. * in the STREAMINFO block or when a seek is attempted.
  86471. *
  86472. * The FLAC__stream_decoder_set_metadata_*() functions deserve special
  86473. * attention. By default, the decoder only calls the metadata_callback for
  86474. * the STREAMINFO block. These functions allow you to tell the decoder
  86475. * explicitly which blocks to parse and return via the metadata_callback
  86476. * and/or which to skip. Use a FLAC__stream_decoder_set_metadata_respond_all(),
  86477. * FLAC__stream_decoder_set_metadata_ignore() ... or FLAC__stream_decoder_set_metadata_ignore_all(),
  86478. * FLAC__stream_decoder_set_metadata_respond() ... sequence to exactly specify
  86479. * which blocks to return. Remember that metadata blocks can potentially
  86480. * be big (for example, cover art) so filtering out the ones you don't
  86481. * use can reduce the memory requirements of the decoder. Also note the
  86482. * special forms FLAC__stream_decoder_set_metadata_respond_application(id)
  86483. * and FLAC__stream_decoder_set_metadata_ignore_application(id) for
  86484. * filtering APPLICATION blocks based on the application ID.
  86485. *
  86486. * STREAMINFO and SEEKTABLE blocks are always parsed and used internally, but
  86487. * they still can legally be filtered from the metadata_callback.
  86488. *
  86489. * \note
  86490. * The "set" functions may only be called when the decoder is in the
  86491. * state FLAC__STREAM_DECODER_UNINITIALIZED, i.e. after
  86492. * FLAC__stream_decoder_new() or FLAC__stream_decoder_finish(), but
  86493. * before FLAC__stream_decoder_init_*(). If this is the case they will
  86494. * return \c true, otherwise \c false.
  86495. *
  86496. * \note
  86497. * FLAC__stream_decoder_finish() resets all settings to the constructor
  86498. * defaults, including the callbacks.
  86499. *
  86500. * \{
  86501. */
  86502. /** State values for a FLAC__StreamDecoder
  86503. *
  86504. * The decoder's state can be obtained by calling FLAC__stream_decoder_get_state().
  86505. */
  86506. typedef enum {
  86507. FLAC__STREAM_DECODER_SEARCH_FOR_METADATA = 0,
  86508. /**< The decoder is ready to search for metadata. */
  86509. FLAC__STREAM_DECODER_READ_METADATA,
  86510. /**< The decoder is ready to or is in the process of reading metadata. */
  86511. FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC,
  86512. /**< The decoder is ready to or is in the process of searching for the
  86513. * frame sync code.
  86514. */
  86515. FLAC__STREAM_DECODER_READ_FRAME,
  86516. /**< The decoder is ready to or is in the process of reading a frame. */
  86517. FLAC__STREAM_DECODER_END_OF_STREAM,
  86518. /**< The decoder has reached the end of the stream. */
  86519. FLAC__STREAM_DECODER_OGG_ERROR,
  86520. /**< An error occurred in the underlying Ogg layer. */
  86521. FLAC__STREAM_DECODER_SEEK_ERROR,
  86522. /**< An error occurred while seeking. The decoder must be flushed
  86523. * with FLAC__stream_decoder_flush() or reset with
  86524. * FLAC__stream_decoder_reset() before decoding can continue.
  86525. */
  86526. FLAC__STREAM_DECODER_ABORTED,
  86527. /**< The decoder was aborted by the read callback. */
  86528. FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR,
  86529. /**< An error occurred allocating memory. The decoder is in an invalid
  86530. * state and can no longer be used.
  86531. */
  86532. FLAC__STREAM_DECODER_UNINITIALIZED
  86533. /**< The decoder is in the uninitialized state; one of the
  86534. * FLAC__stream_decoder_init_*() functions must be called before samples
  86535. * can be processed.
  86536. */
  86537. } FLAC__StreamDecoderState;
  86538. /** Maps a FLAC__StreamDecoderState to a C string.
  86539. *
  86540. * Using a FLAC__StreamDecoderState as the index to this array
  86541. * will give the string equivalent. The contents should not be modified.
  86542. */
  86543. extern FLAC_API const char * const FLAC__StreamDecoderStateString[];
  86544. /** Possible return values for the FLAC__stream_decoder_init_*() functions.
  86545. */
  86546. typedef enum {
  86547. FLAC__STREAM_DECODER_INIT_STATUS_OK = 0,
  86548. /**< Initialization was successful. */
  86549. FLAC__STREAM_DECODER_INIT_STATUS_UNSUPPORTED_CONTAINER,
  86550. /**< The library was not compiled with support for the given container
  86551. * format.
  86552. */
  86553. FLAC__STREAM_DECODER_INIT_STATUS_INVALID_CALLBACKS,
  86554. /**< A required callback was not supplied. */
  86555. FLAC__STREAM_DECODER_INIT_STATUS_MEMORY_ALLOCATION_ERROR,
  86556. /**< An error occurred allocating memory. */
  86557. FLAC__STREAM_DECODER_INIT_STATUS_ERROR_OPENING_FILE,
  86558. /**< fopen() failed in FLAC__stream_decoder_init_file() or
  86559. * FLAC__stream_decoder_init_ogg_file(). */
  86560. FLAC__STREAM_DECODER_INIT_STATUS_ALREADY_INITIALIZED
  86561. /**< FLAC__stream_decoder_init_*() was called when the decoder was
  86562. * already initialized, usually because
  86563. * FLAC__stream_decoder_finish() was not called.
  86564. */
  86565. } FLAC__StreamDecoderInitStatus;
  86566. /** Maps a FLAC__StreamDecoderInitStatus to a C string.
  86567. *
  86568. * Using a FLAC__StreamDecoderInitStatus as the index to this array
  86569. * will give the string equivalent. The contents should not be modified.
  86570. */
  86571. extern FLAC_API const char * const FLAC__StreamDecoderInitStatusString[];
  86572. /** Return values for the FLAC__StreamDecoder read callback.
  86573. */
  86574. typedef enum {
  86575. FLAC__STREAM_DECODER_READ_STATUS_CONTINUE,
  86576. /**< The read was OK and decoding can continue. */
  86577. FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM,
  86578. /**< The read was attempted while at the end of the stream. Note that
  86579. * the client must only return this value when the read callback was
  86580. * called when already at the end of the stream. Otherwise, if the read
  86581. * itself moves to the end of the stream, the client should still return
  86582. * the data and \c FLAC__STREAM_DECODER_READ_STATUS_CONTINUE, and then on
  86583. * the next read callback it should return
  86584. * \c FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM with a byte count
  86585. * of \c 0.
  86586. */
  86587. FLAC__STREAM_DECODER_READ_STATUS_ABORT
  86588. /**< An unrecoverable error occurred. The decoder will return from the process call. */
  86589. } FLAC__StreamDecoderReadStatus;
  86590. /** Maps a FLAC__StreamDecoderReadStatus to a C string.
  86591. *
  86592. * Using a FLAC__StreamDecoderReadStatus as the index to this array
  86593. * will give the string equivalent. The contents should not be modified.
  86594. */
  86595. extern FLAC_API const char * const FLAC__StreamDecoderReadStatusString[];
  86596. /** Return values for the FLAC__StreamDecoder seek callback.
  86597. */
  86598. typedef enum {
  86599. FLAC__STREAM_DECODER_SEEK_STATUS_OK,
  86600. /**< The seek was OK and decoding can continue. */
  86601. FLAC__STREAM_DECODER_SEEK_STATUS_ERROR,
  86602. /**< An unrecoverable error occurred. The decoder will return from the process call. */
  86603. FLAC__STREAM_DECODER_SEEK_STATUS_UNSUPPORTED
  86604. /**< Client does not support seeking. */
  86605. } FLAC__StreamDecoderSeekStatus;
  86606. /** Maps a FLAC__StreamDecoderSeekStatus to a C string.
  86607. *
  86608. * Using a FLAC__StreamDecoderSeekStatus as the index to this array
  86609. * will give the string equivalent. The contents should not be modified.
  86610. */
  86611. extern FLAC_API const char * const FLAC__StreamDecoderSeekStatusString[];
  86612. /** Return values for the FLAC__StreamDecoder tell callback.
  86613. */
  86614. typedef enum {
  86615. FLAC__STREAM_DECODER_TELL_STATUS_OK,
  86616. /**< The tell was OK and decoding can continue. */
  86617. FLAC__STREAM_DECODER_TELL_STATUS_ERROR,
  86618. /**< An unrecoverable error occurred. The decoder will return from the process call. */
  86619. FLAC__STREAM_DECODER_TELL_STATUS_UNSUPPORTED
  86620. /**< Client does not support telling the position. */
  86621. } FLAC__StreamDecoderTellStatus;
  86622. /** Maps a FLAC__StreamDecoderTellStatus to a C string.
  86623. *
  86624. * Using a FLAC__StreamDecoderTellStatus as the index to this array
  86625. * will give the string equivalent. The contents should not be modified.
  86626. */
  86627. extern FLAC_API const char * const FLAC__StreamDecoderTellStatusString[];
  86628. /** Return values for the FLAC__StreamDecoder length callback.
  86629. */
  86630. typedef enum {
  86631. FLAC__STREAM_DECODER_LENGTH_STATUS_OK,
  86632. /**< The length call was OK and decoding can continue. */
  86633. FLAC__STREAM_DECODER_LENGTH_STATUS_ERROR,
  86634. /**< An unrecoverable error occurred. The decoder will return from the process call. */
  86635. FLAC__STREAM_DECODER_LENGTH_STATUS_UNSUPPORTED
  86636. /**< Client does not support reporting the length. */
  86637. } FLAC__StreamDecoderLengthStatus;
  86638. /** Maps a FLAC__StreamDecoderLengthStatus to a C string.
  86639. *
  86640. * Using a FLAC__StreamDecoderLengthStatus as the index to this array
  86641. * will give the string equivalent. The contents should not be modified.
  86642. */
  86643. extern FLAC_API const char * const FLAC__StreamDecoderLengthStatusString[];
  86644. /** Return values for the FLAC__StreamDecoder write callback.
  86645. */
  86646. typedef enum {
  86647. FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE,
  86648. /**< The write was OK and decoding can continue. */
  86649. FLAC__STREAM_DECODER_WRITE_STATUS_ABORT
  86650. /**< An unrecoverable error occurred. The decoder will return from the process call. */
  86651. } FLAC__StreamDecoderWriteStatus;
  86652. /** Maps a FLAC__StreamDecoderWriteStatus to a C string.
  86653. *
  86654. * Using a FLAC__StreamDecoderWriteStatus as the index to this array
  86655. * will give the string equivalent. The contents should not be modified.
  86656. */
  86657. extern FLAC_API const char * const FLAC__StreamDecoderWriteStatusString[];
  86658. /** Possible values passed back to the FLAC__StreamDecoder error callback.
  86659. * \c FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC is the generic catch-
  86660. * all. The rest could be caused by bad sync (false synchronization on
  86661. * data that is not the start of a frame) or corrupted data. The error
  86662. * itself is the decoder's best guess at what happened assuming a correct
  86663. * sync. For example \c FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER
  86664. * could be caused by a correct sync on the start of a frame, but some
  86665. * data in the frame header was corrupted. Or it could be the result of
  86666. * syncing on a point the stream that looked like the starting of a frame
  86667. * but was not. \c FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM
  86668. * could be because the decoder encountered a valid frame made by a future
  86669. * version of the encoder which it cannot parse, or because of a false
  86670. * sync making it appear as though an encountered frame was generated by
  86671. * a future encoder.
  86672. */
  86673. typedef enum {
  86674. FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC,
  86675. /**< An error in the stream caused the decoder to lose synchronization. */
  86676. FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER,
  86677. /**< The decoder encountered a corrupted frame header. */
  86678. FLAC__STREAM_DECODER_ERROR_STATUS_FRAME_CRC_MISMATCH,
  86679. /**< The frame's data did not match the CRC in the footer. */
  86680. FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM
  86681. /**< The decoder encountered reserved fields in use in the stream. */
  86682. } FLAC__StreamDecoderErrorStatus;
  86683. /** Maps a FLAC__StreamDecoderErrorStatus to a C string.
  86684. *
  86685. * Using a FLAC__StreamDecoderErrorStatus as the index to this array
  86686. * will give the string equivalent. The contents should not be modified.
  86687. */
  86688. extern FLAC_API const char * const FLAC__StreamDecoderErrorStatusString[];
  86689. /***********************************************************************
  86690. *
  86691. * class FLAC__StreamDecoder
  86692. *
  86693. ***********************************************************************/
  86694. struct FLAC__StreamDecoderProtected;
  86695. struct FLAC__StreamDecoderPrivate;
  86696. /** The opaque structure definition for the stream decoder type.
  86697. * See the \link flac_stream_decoder stream decoder module \endlink
  86698. * for a detailed description.
  86699. */
  86700. typedef struct {
  86701. struct FLAC__StreamDecoderProtected *protected_; /* avoid the C++ keyword 'protected' */
  86702. struct FLAC__StreamDecoderPrivate *private_; /* avoid the C++ keyword 'private' */
  86703. } FLAC__StreamDecoder;
  86704. /** Signature for the read callback.
  86705. *
  86706. * A function pointer matching this signature must be passed to
  86707. * FLAC__stream_decoder_init*_stream(). The supplied function will be
  86708. * called when the decoder needs more input data. The address of the
  86709. * buffer to be filled is supplied, along with the number of bytes the
  86710. * buffer can hold. The callback may choose to supply less data and
  86711. * modify the byte count but must be careful not to overflow the buffer.
  86712. * The callback then returns a status code chosen from
  86713. * FLAC__StreamDecoderReadStatus.
  86714. *
  86715. * Here is an example of a read callback for stdio streams:
  86716. * \code
  86717. * FLAC__StreamDecoderReadStatus read_cb(const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes, void *client_data)
  86718. * {
  86719. * FILE *file = ((MyClientData*)client_data)->file;
  86720. * if(*bytes > 0) {
  86721. * *bytes = fread(buffer, sizeof(FLAC__byte), *bytes, file);
  86722. * if(ferror(file))
  86723. * return FLAC__STREAM_DECODER_READ_STATUS_ABORT;
  86724. * else if(*bytes == 0)
  86725. * return FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM;
  86726. * else
  86727. * return FLAC__STREAM_DECODER_READ_STATUS_CONTINUE;
  86728. * }
  86729. * else
  86730. * return FLAC__STREAM_DECODER_READ_STATUS_ABORT;
  86731. * }
  86732. * \endcode
  86733. *
  86734. * \note In general, FLAC__StreamDecoder functions which change the
  86735. * state should not be called on the \a decoder while in the callback.
  86736. *
  86737. * \param decoder The decoder instance calling the callback.
  86738. * \param buffer A pointer to a location for the callee to store
  86739. * data to be decoded.
  86740. * \param bytes A pointer to the size of the buffer. On entry
  86741. * to the callback, it contains the maximum number
  86742. * of bytes that may be stored in \a buffer. The
  86743. * callee must set it to the actual number of bytes
  86744. * stored (0 in case of error or end-of-stream) before
  86745. * returning.
  86746. * \param client_data The callee's client data set through
  86747. * FLAC__stream_decoder_init_*().
  86748. * \retval FLAC__StreamDecoderReadStatus
  86749. * The callee's return status. Note that the callback should return
  86750. * \c FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM if and only if
  86751. * zero bytes were read and there is no more data to be read.
  86752. */
  86753. typedef FLAC__StreamDecoderReadStatus (*FLAC__StreamDecoderReadCallback)(const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes, void *client_data);
  86754. /** Signature for the seek callback.
  86755. *
  86756. * A function pointer matching this signature may be passed to
  86757. * FLAC__stream_decoder_init*_stream(). The supplied function will be
  86758. * called when the decoder needs to seek the input stream. The decoder
  86759. * will pass the absolute byte offset to seek to, 0 meaning the
  86760. * beginning of the stream.
  86761. *
  86762. * Here is an example of a seek callback for stdio streams:
  86763. * \code
  86764. * FLAC__StreamDecoderSeekStatus seek_cb(const FLAC__StreamDecoder *decoder, FLAC__uint64 absolute_byte_offset, void *client_data)
  86765. * {
  86766. * FILE *file = ((MyClientData*)client_data)->file;
  86767. * if(file == stdin)
  86768. * return FLAC__STREAM_DECODER_SEEK_STATUS_UNSUPPORTED;
  86769. * else if(fseeko(file, (off_t)absolute_byte_offset, SEEK_SET) < 0)
  86770. * return FLAC__STREAM_DECODER_SEEK_STATUS_ERROR;
  86771. * else
  86772. * return FLAC__STREAM_DECODER_SEEK_STATUS_OK;
  86773. * }
  86774. * \endcode
  86775. *
  86776. * \note In general, FLAC__StreamDecoder functions which change the
  86777. * state should not be called on the \a decoder while in the callback.
  86778. *
  86779. * \param decoder The decoder instance calling the callback.
  86780. * \param absolute_byte_offset The offset from the beginning of the stream
  86781. * to seek to.
  86782. * \param client_data The callee's client data set through
  86783. * FLAC__stream_decoder_init_*().
  86784. * \retval FLAC__StreamDecoderSeekStatus
  86785. * The callee's return status.
  86786. */
  86787. typedef FLAC__StreamDecoderSeekStatus (*FLAC__StreamDecoderSeekCallback)(const FLAC__StreamDecoder *decoder, FLAC__uint64 absolute_byte_offset, void *client_data);
  86788. /** Signature for the tell callback.
  86789. *
  86790. * A function pointer matching this signature may be passed to
  86791. * FLAC__stream_decoder_init*_stream(). The supplied function will be
  86792. * called when the decoder wants to know the current position of the
  86793. * stream. The callback should return the byte offset from the
  86794. * beginning of the stream.
  86795. *
  86796. * Here is an example of a tell callback for stdio streams:
  86797. * \code
  86798. * FLAC__StreamDecoderTellStatus tell_cb(const FLAC__StreamDecoder *decoder, FLAC__uint64 *absolute_byte_offset, void *client_data)
  86799. * {
  86800. * FILE *file = ((MyClientData*)client_data)->file;
  86801. * off_t pos;
  86802. * if(file == stdin)
  86803. * return FLAC__STREAM_DECODER_TELL_STATUS_UNSUPPORTED;
  86804. * else if((pos = ftello(file)) < 0)
  86805. * return FLAC__STREAM_DECODER_TELL_STATUS_ERROR;
  86806. * else {
  86807. * *absolute_byte_offset = (FLAC__uint64)pos;
  86808. * return FLAC__STREAM_DECODER_TELL_STATUS_OK;
  86809. * }
  86810. * }
  86811. * \endcode
  86812. *
  86813. * \note In general, FLAC__StreamDecoder functions which change the
  86814. * state should not be called on the \a decoder while in the callback.
  86815. *
  86816. * \param decoder The decoder instance calling the callback.
  86817. * \param absolute_byte_offset A pointer to storage for the current offset
  86818. * from the beginning of the stream.
  86819. * \param client_data The callee's client data set through
  86820. * FLAC__stream_decoder_init_*().
  86821. * \retval FLAC__StreamDecoderTellStatus
  86822. * The callee's return status.
  86823. */
  86824. typedef FLAC__StreamDecoderTellStatus (*FLAC__StreamDecoderTellCallback)(const FLAC__StreamDecoder *decoder, FLAC__uint64 *absolute_byte_offset, void *client_data);
  86825. /** Signature for the length callback.
  86826. *
  86827. * A function pointer matching this signature may be passed to
  86828. * FLAC__stream_decoder_init*_stream(). The supplied function will be
  86829. * called when the decoder wants to know the total length of the stream
  86830. * in bytes.
  86831. *
  86832. * Here is an example of a length callback for stdio streams:
  86833. * \code
  86834. * FLAC__StreamDecoderLengthStatus length_cb(const FLAC__StreamDecoder *decoder, FLAC__uint64 *stream_length, void *client_data)
  86835. * {
  86836. * FILE *file = ((MyClientData*)client_data)->file;
  86837. * struct stat filestats;
  86838. *
  86839. * if(file == stdin)
  86840. * return FLAC__STREAM_DECODER_LENGTH_STATUS_UNSUPPORTED;
  86841. * else if(fstat(fileno(file), &filestats) != 0)
  86842. * return FLAC__STREAM_DECODER_LENGTH_STATUS_ERROR;
  86843. * else {
  86844. * *stream_length = (FLAC__uint64)filestats.st_size;
  86845. * return FLAC__STREAM_DECODER_LENGTH_STATUS_OK;
  86846. * }
  86847. * }
  86848. * \endcode
  86849. *
  86850. * \note In general, FLAC__StreamDecoder functions which change the
  86851. * state should not be called on the \a decoder while in the callback.
  86852. *
  86853. * \param decoder The decoder instance calling the callback.
  86854. * \param stream_length A pointer to storage for the length of the stream
  86855. * in bytes.
  86856. * \param client_data The callee's client data set through
  86857. * FLAC__stream_decoder_init_*().
  86858. * \retval FLAC__StreamDecoderLengthStatus
  86859. * The callee's return status.
  86860. */
  86861. typedef FLAC__StreamDecoderLengthStatus (*FLAC__StreamDecoderLengthCallback)(const FLAC__StreamDecoder *decoder, FLAC__uint64 *stream_length, void *client_data);
  86862. /** Signature for the EOF callback.
  86863. *
  86864. * A function pointer matching this signature may be passed to
  86865. * FLAC__stream_decoder_init*_stream(). The supplied function will be
  86866. * called when the decoder needs to know if the end of the stream has
  86867. * been reached.
  86868. *
  86869. * Here is an example of a EOF callback for stdio streams:
  86870. * FLAC__bool eof_cb(const FLAC__StreamDecoder *decoder, void *client_data)
  86871. * \code
  86872. * {
  86873. * FILE *file = ((MyClientData*)client_data)->file;
  86874. * return feof(file)? true : false;
  86875. * }
  86876. * \endcode
  86877. *
  86878. * \note In general, FLAC__StreamDecoder functions which change the
  86879. * state should not be called on the \a decoder while in the callback.
  86880. *
  86881. * \param decoder The decoder instance calling the callback.
  86882. * \param client_data The callee's client data set through
  86883. * FLAC__stream_decoder_init_*().
  86884. * \retval FLAC__bool
  86885. * \c true if the currently at the end of the stream, else \c false.
  86886. */
  86887. typedef FLAC__bool (*FLAC__StreamDecoderEofCallback)(const FLAC__StreamDecoder *decoder, void *client_data);
  86888. /** Signature for the write callback.
  86889. *
  86890. * A function pointer matching this signature must be passed to one of
  86891. * the FLAC__stream_decoder_init_*() functions.
  86892. * The supplied function will be called when the decoder has decoded a
  86893. * single audio frame. The decoder will pass the frame metadata as well
  86894. * as an array of pointers (one for each channel) pointing to the
  86895. * decoded audio.
  86896. *
  86897. * \note In general, FLAC__StreamDecoder functions which change the
  86898. * state should not be called on the \a decoder while in the callback.
  86899. *
  86900. * \param decoder The decoder instance calling the callback.
  86901. * \param frame The description of the decoded frame. See
  86902. * FLAC__Frame.
  86903. * \param buffer An array of pointers to decoded channels of data.
  86904. * Each pointer will point to an array of signed
  86905. * samples of length \a frame->header.blocksize.
  86906. * Channels will be ordered according to the FLAC
  86907. * specification; see the documentation for the
  86908. * <A HREF="../format.html#frame_header">frame header</A>.
  86909. * \param client_data The callee's client data set through
  86910. * FLAC__stream_decoder_init_*().
  86911. * \retval FLAC__StreamDecoderWriteStatus
  86912. * The callee's return status.
  86913. */
  86914. typedef FLAC__StreamDecoderWriteStatus (*FLAC__StreamDecoderWriteCallback)(const FLAC__StreamDecoder *decoder, const FLAC__Frame *frame, const FLAC__int32 * const buffer[], void *client_data);
  86915. /** Signature for the metadata callback.
  86916. *
  86917. * A function pointer matching this signature must be passed to one of
  86918. * the FLAC__stream_decoder_init_*() functions.
  86919. * The supplied function will be called when the decoder has decoded a
  86920. * metadata block. In a valid FLAC file there will always be one
  86921. * \c STREAMINFO block, followed by zero or more other metadata blocks.
  86922. * These will be supplied by the decoder in the same order as they
  86923. * appear in the stream and always before the first audio frame (i.e.
  86924. * write callback). The metadata block that is passed in must not be
  86925. * modified, and it doesn't live beyond the callback, so you should make
  86926. * a copy of it with FLAC__metadata_object_clone() if you will need it
  86927. * elsewhere. Since metadata blocks can potentially be large, by
  86928. * default the decoder only calls the metadata callback for the
  86929. * \c STREAMINFO block; you can instruct the decoder to pass or filter
  86930. * other blocks with FLAC__stream_decoder_set_metadata_*() calls.
  86931. *
  86932. * \note In general, FLAC__StreamDecoder functions which change the
  86933. * state should not be called on the \a decoder while in the callback.
  86934. *
  86935. * \param decoder The decoder instance calling the callback.
  86936. * \param metadata The decoded metadata block.
  86937. * \param client_data The callee's client data set through
  86938. * FLAC__stream_decoder_init_*().
  86939. */
  86940. typedef void (*FLAC__StreamDecoderMetadataCallback)(const FLAC__StreamDecoder *decoder, const FLAC__StreamMetadata *metadata, void *client_data);
  86941. /** Signature for the error callback.
  86942. *
  86943. * A function pointer matching this signature must be passed to one of
  86944. * the FLAC__stream_decoder_init_*() functions.
  86945. * The supplied function will be called whenever an error occurs during
  86946. * decoding.
  86947. *
  86948. * \note In general, FLAC__StreamDecoder functions which change the
  86949. * state should not be called on the \a decoder while in the callback.
  86950. *
  86951. * \param decoder The decoder instance calling the callback.
  86952. * \param status The error encountered by the decoder.
  86953. * \param client_data The callee's client data set through
  86954. * FLAC__stream_decoder_init_*().
  86955. */
  86956. typedef void (*FLAC__StreamDecoderErrorCallback)(const FLAC__StreamDecoder *decoder, FLAC__StreamDecoderErrorStatus status, void *client_data);
  86957. /***********************************************************************
  86958. *
  86959. * Class constructor/destructor
  86960. *
  86961. ***********************************************************************/
  86962. /** Create a new stream decoder instance. The instance is created with
  86963. * default settings; see the individual FLAC__stream_decoder_set_*()
  86964. * functions for each setting's default.
  86965. *
  86966. * \retval FLAC__StreamDecoder*
  86967. * \c NULL if there was an error allocating memory, else the new instance.
  86968. */
  86969. FLAC_API FLAC__StreamDecoder *FLAC__stream_decoder_new(void);
  86970. /** Free a decoder instance. Deletes the object pointed to by \a decoder.
  86971. *
  86972. * \param decoder A pointer to an existing decoder.
  86973. * \assert
  86974. * \code decoder != NULL \endcode
  86975. */
  86976. FLAC_API void FLAC__stream_decoder_delete(FLAC__StreamDecoder *decoder);
  86977. /***********************************************************************
  86978. *
  86979. * Public class method prototypes
  86980. *
  86981. ***********************************************************************/
  86982. /** Set the serial number for the FLAC stream within the Ogg container.
  86983. * The default behavior is to use the serial number of the first Ogg
  86984. * page. Setting a serial number here will explicitly specify which
  86985. * stream is to be decoded.
  86986. *
  86987. * \note
  86988. * This does not need to be set for native FLAC decoding.
  86989. *
  86990. * \default \c use serial number of first page
  86991. * \param decoder A decoder instance to set.
  86992. * \param serial_number See above.
  86993. * \assert
  86994. * \code decoder != NULL \endcode
  86995. * \retval FLAC__bool
  86996. * \c false if the decoder is already initialized, else \c true.
  86997. */
  86998. FLAC_API FLAC__bool FLAC__stream_decoder_set_ogg_serial_number(FLAC__StreamDecoder *decoder, long serial_number);
  86999. /** Set the "MD5 signature checking" flag. If \c true, the decoder will
  87000. * compute the MD5 signature of the unencoded audio data while decoding
  87001. * and compare it to the signature from the STREAMINFO block, if it
  87002. * exists, during FLAC__stream_decoder_finish().
  87003. *
  87004. * MD5 signature checking will be turned off (until the next
  87005. * FLAC__stream_decoder_reset()) if there is no signature in the
  87006. * STREAMINFO block or when a seek is attempted.
  87007. *
  87008. * Clients that do not use the MD5 check should leave this off to speed
  87009. * up decoding.
  87010. *
  87011. * \default \c false
  87012. * \param decoder A decoder instance to set.
  87013. * \param value Flag value (see above).
  87014. * \assert
  87015. * \code decoder != NULL \endcode
  87016. * \retval FLAC__bool
  87017. * \c false if the decoder is already initialized, else \c true.
  87018. */
  87019. FLAC_API FLAC__bool FLAC__stream_decoder_set_md5_checking(FLAC__StreamDecoder *decoder, FLAC__bool value);
  87020. /** Direct the decoder to pass on all metadata blocks of type \a type.
  87021. *
  87022. * \default By default, only the \c STREAMINFO block is returned via the
  87023. * metadata callback.
  87024. * \param decoder A decoder instance to set.
  87025. * \param type See above.
  87026. * \assert
  87027. * \code decoder != NULL \endcode
  87028. * \a type is valid
  87029. * \retval FLAC__bool
  87030. * \c false if the decoder is already initialized, else \c true.
  87031. */
  87032. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_respond(FLAC__StreamDecoder *decoder, FLAC__MetadataType type);
  87033. /** Direct the decoder to pass on all APPLICATION metadata blocks of the
  87034. * given \a id.
  87035. *
  87036. * \default By default, only the \c STREAMINFO block is returned via the
  87037. * metadata callback.
  87038. * \param decoder A decoder instance to set.
  87039. * \param id See above.
  87040. * \assert
  87041. * \code decoder != NULL \endcode
  87042. * \code id != NULL \endcode
  87043. * \retval FLAC__bool
  87044. * \c false if the decoder is already initialized, else \c true.
  87045. */
  87046. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_respond_application(FLAC__StreamDecoder *decoder, const FLAC__byte id[4]);
  87047. /** Direct the decoder to pass on all metadata blocks of any type.
  87048. *
  87049. * \default By default, only the \c STREAMINFO block is returned via the
  87050. * metadata callback.
  87051. * \param decoder A decoder instance to set.
  87052. * \assert
  87053. * \code decoder != NULL \endcode
  87054. * \retval FLAC__bool
  87055. * \c false if the decoder is already initialized, else \c true.
  87056. */
  87057. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_respond_all(FLAC__StreamDecoder *decoder);
  87058. /** Direct the decoder to filter out all metadata blocks of type \a type.
  87059. *
  87060. * \default By default, only the \c STREAMINFO block is returned via the
  87061. * metadata callback.
  87062. * \param decoder A decoder instance to set.
  87063. * \param type See above.
  87064. * \assert
  87065. * \code decoder != NULL \endcode
  87066. * \a type is valid
  87067. * \retval FLAC__bool
  87068. * \c false if the decoder is already initialized, else \c true.
  87069. */
  87070. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_ignore(FLAC__StreamDecoder *decoder, FLAC__MetadataType type);
  87071. /** Direct the decoder to filter out all APPLICATION metadata blocks of
  87072. * the given \a id.
  87073. *
  87074. * \default By default, only the \c STREAMINFO block is returned via the
  87075. * metadata callback.
  87076. * \param decoder A decoder instance to set.
  87077. * \param id See above.
  87078. * \assert
  87079. * \code decoder != NULL \endcode
  87080. * \code id != NULL \endcode
  87081. * \retval FLAC__bool
  87082. * \c false if the decoder is already initialized, else \c true.
  87083. */
  87084. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_ignore_application(FLAC__StreamDecoder *decoder, const FLAC__byte id[4]);
  87085. /** Direct the decoder to filter out all metadata blocks of any type.
  87086. *
  87087. * \default By default, only the \c STREAMINFO block is returned via the
  87088. * metadata callback.
  87089. * \param decoder A decoder instance to set.
  87090. * \assert
  87091. * \code decoder != NULL \endcode
  87092. * \retval FLAC__bool
  87093. * \c false if the decoder is already initialized, else \c true.
  87094. */
  87095. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_ignore_all(FLAC__StreamDecoder *decoder);
  87096. /** Get the current decoder state.
  87097. *
  87098. * \param decoder A decoder instance to query.
  87099. * \assert
  87100. * \code decoder != NULL \endcode
  87101. * \retval FLAC__StreamDecoderState
  87102. * The current decoder state.
  87103. */
  87104. FLAC_API FLAC__StreamDecoderState FLAC__stream_decoder_get_state(const FLAC__StreamDecoder *decoder);
  87105. /** Get the current decoder state as a C string.
  87106. *
  87107. * \param decoder A decoder instance to query.
  87108. * \assert
  87109. * \code decoder != NULL \endcode
  87110. * \retval const char *
  87111. * The decoder state as a C string. Do not modify the contents.
  87112. */
  87113. FLAC_API const char *FLAC__stream_decoder_get_resolved_state_string(const FLAC__StreamDecoder *decoder);
  87114. /** Get the "MD5 signature checking" flag.
  87115. * This is the value of the setting, not whether or not the decoder is
  87116. * currently checking the MD5 (remember, it can be turned off automatically
  87117. * by a seek). When the decoder is reset the flag will be restored to the
  87118. * value returned by this function.
  87119. *
  87120. * \param decoder A decoder instance to query.
  87121. * \assert
  87122. * \code decoder != NULL \endcode
  87123. * \retval FLAC__bool
  87124. * See above.
  87125. */
  87126. FLAC_API FLAC__bool FLAC__stream_decoder_get_md5_checking(const FLAC__StreamDecoder *decoder);
  87127. /** Get the total number of samples in the stream being decoded.
  87128. * Will only be valid after decoding has started and will contain the
  87129. * value from the \c STREAMINFO block. A value of \c 0 means "unknown".
  87130. *
  87131. * \param decoder A decoder instance to query.
  87132. * \assert
  87133. * \code decoder != NULL \endcode
  87134. * \retval unsigned
  87135. * See above.
  87136. */
  87137. FLAC_API FLAC__uint64 FLAC__stream_decoder_get_total_samples(const FLAC__StreamDecoder *decoder);
  87138. /** Get the current number of channels in the stream being decoded.
  87139. * Will only be valid after decoding has started and will contain the
  87140. * value from the most recently decoded frame header.
  87141. *
  87142. * \param decoder A decoder instance to query.
  87143. * \assert
  87144. * \code decoder != NULL \endcode
  87145. * \retval unsigned
  87146. * See above.
  87147. */
  87148. FLAC_API unsigned FLAC__stream_decoder_get_channels(const FLAC__StreamDecoder *decoder);
  87149. /** Get the current channel assignment in the stream being decoded.
  87150. * Will only be valid after decoding has started and will contain the
  87151. * value from the most recently decoded frame header.
  87152. *
  87153. * \param decoder A decoder instance to query.
  87154. * \assert
  87155. * \code decoder != NULL \endcode
  87156. * \retval FLAC__ChannelAssignment
  87157. * See above.
  87158. */
  87159. FLAC_API FLAC__ChannelAssignment FLAC__stream_decoder_get_channel_assignment(const FLAC__StreamDecoder *decoder);
  87160. /** Get the current sample resolution in the stream being decoded.
  87161. * Will only be valid after decoding has started and will contain the
  87162. * value from the most recently decoded frame header.
  87163. *
  87164. * \param decoder A decoder instance to query.
  87165. * \assert
  87166. * \code decoder != NULL \endcode
  87167. * \retval unsigned
  87168. * See above.
  87169. */
  87170. FLAC_API unsigned FLAC__stream_decoder_get_bits_per_sample(const FLAC__StreamDecoder *decoder);
  87171. /** Get the current sample rate in Hz of the stream being decoded.
  87172. * Will only be valid after decoding has started and will contain the
  87173. * value from the most recently decoded frame header.
  87174. *
  87175. * \param decoder A decoder instance to query.
  87176. * \assert
  87177. * \code decoder != NULL \endcode
  87178. * \retval unsigned
  87179. * See above.
  87180. */
  87181. FLAC_API unsigned FLAC__stream_decoder_get_sample_rate(const FLAC__StreamDecoder *decoder);
  87182. /** Get the current blocksize of the stream being decoded.
  87183. * Will only be valid after decoding has started and will contain the
  87184. * value from the most recently decoded frame header.
  87185. *
  87186. * \param decoder A decoder instance to query.
  87187. * \assert
  87188. * \code decoder != NULL \endcode
  87189. * \retval unsigned
  87190. * See above.
  87191. */
  87192. FLAC_API unsigned FLAC__stream_decoder_get_blocksize(const FLAC__StreamDecoder *decoder);
  87193. /** Returns the decoder's current read position within the stream.
  87194. * The position is the byte offset from the start of the stream.
  87195. * Bytes before this position have been fully decoded. Note that
  87196. * there may still be undecoded bytes in the decoder's read FIFO.
  87197. * The returned position is correct even after a seek.
  87198. *
  87199. * \warning This function currently only works for native FLAC,
  87200. * not Ogg FLAC streams.
  87201. *
  87202. * \param decoder A decoder instance to query.
  87203. * \param position Address at which to return the desired position.
  87204. * \assert
  87205. * \code decoder != NULL \endcode
  87206. * \code position != NULL \endcode
  87207. * \retval FLAC__bool
  87208. * \c true if successful, \c false if the stream is not native FLAC,
  87209. * or there was an error from the 'tell' callback or it returned
  87210. * \c FLAC__STREAM_DECODER_TELL_STATUS_UNSUPPORTED.
  87211. */
  87212. FLAC_API FLAC__bool FLAC__stream_decoder_get_decode_position(const FLAC__StreamDecoder *decoder, FLAC__uint64 *position);
  87213. /** Initialize the decoder instance to decode native FLAC streams.
  87214. *
  87215. * This flavor of initialization sets up the decoder to decode from a
  87216. * native FLAC stream. I/O is performed via callbacks to the client.
  87217. * For decoding from a plain file via filename or open FILE*,
  87218. * FLAC__stream_decoder_init_file() and FLAC__stream_decoder_init_FILE()
  87219. * provide a simpler interface.
  87220. *
  87221. * This function should be called after FLAC__stream_decoder_new() and
  87222. * FLAC__stream_decoder_set_*() but before any of the
  87223. * FLAC__stream_decoder_process_*() functions. Will set and return the
  87224. * decoder state, which will be FLAC__STREAM_DECODER_SEARCH_FOR_METADATA
  87225. * if initialization succeeded.
  87226. *
  87227. * \param decoder An uninitialized decoder instance.
  87228. * \param read_callback See FLAC__StreamDecoderReadCallback. This
  87229. * pointer must not be \c NULL.
  87230. * \param seek_callback See FLAC__StreamDecoderSeekCallback. This
  87231. * pointer may be \c NULL if seeking is not
  87232. * supported. If \a seek_callback is not \c NULL then a
  87233. * \a tell_callback, \a length_callback, and \a eof_callback must also be supplied.
  87234. * Alternatively, a dummy seek callback that just
  87235. * returns \c FLAC__STREAM_DECODER_SEEK_STATUS_UNSUPPORTED
  87236. * may also be supplied, all though this is slightly
  87237. * less efficient for the decoder.
  87238. * \param tell_callback See FLAC__StreamDecoderTellCallback. This
  87239. * pointer may be \c NULL if not supported by the client. If
  87240. * \a seek_callback is not \c NULL then a
  87241. * \a tell_callback must also be supplied.
  87242. * Alternatively, a dummy tell callback that just
  87243. * returns \c FLAC__STREAM_DECODER_TELL_STATUS_UNSUPPORTED
  87244. * may also be supplied, all though this is slightly
  87245. * less efficient for the decoder.
  87246. * \param length_callback See FLAC__StreamDecoderLengthCallback. This
  87247. * pointer may be \c NULL if not supported by the client. If
  87248. * \a seek_callback is not \c NULL then a
  87249. * \a length_callback must also be supplied.
  87250. * Alternatively, a dummy length callback that just
  87251. * returns \c FLAC__STREAM_DECODER_LENGTH_STATUS_UNSUPPORTED
  87252. * may also be supplied, all though this is slightly
  87253. * less efficient for the decoder.
  87254. * \param eof_callback See FLAC__StreamDecoderEofCallback. This
  87255. * pointer may be \c NULL if not supported by the client. If
  87256. * \a seek_callback is not \c NULL then a
  87257. * \a eof_callback must also be supplied.
  87258. * Alternatively, a dummy length callback that just
  87259. * returns \c false
  87260. * may also be supplied, all though this is slightly
  87261. * less efficient for the decoder.
  87262. * \param write_callback See FLAC__StreamDecoderWriteCallback. This
  87263. * pointer must not be \c NULL.
  87264. * \param metadata_callback See FLAC__StreamDecoderMetadataCallback. This
  87265. * pointer may be \c NULL if the callback is not
  87266. * desired.
  87267. * \param error_callback See FLAC__StreamDecoderErrorCallback. This
  87268. * pointer must not be \c NULL.
  87269. * \param client_data This value will be supplied to callbacks in their
  87270. * \a client_data argument.
  87271. * \assert
  87272. * \code decoder != NULL \endcode
  87273. * \retval FLAC__StreamDecoderInitStatus
  87274. * \c FLAC__STREAM_DECODER_INIT_STATUS_OK if initialization was successful;
  87275. * see FLAC__StreamDecoderInitStatus for the meanings of other return values.
  87276. */
  87277. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_stream(
  87278. FLAC__StreamDecoder *decoder,
  87279. FLAC__StreamDecoderReadCallback read_callback,
  87280. FLAC__StreamDecoderSeekCallback seek_callback,
  87281. FLAC__StreamDecoderTellCallback tell_callback,
  87282. FLAC__StreamDecoderLengthCallback length_callback,
  87283. FLAC__StreamDecoderEofCallback eof_callback,
  87284. FLAC__StreamDecoderWriteCallback write_callback,
  87285. FLAC__StreamDecoderMetadataCallback metadata_callback,
  87286. FLAC__StreamDecoderErrorCallback error_callback,
  87287. void *client_data
  87288. );
  87289. /** Initialize the decoder instance to decode Ogg FLAC streams.
  87290. *
  87291. * This flavor of initialization sets up the decoder to decode from a
  87292. * FLAC stream in an Ogg container. I/O is performed via callbacks to the
  87293. * client. For decoding from a plain file via filename or open FILE*,
  87294. * FLAC__stream_decoder_init_ogg_file() and FLAC__stream_decoder_init_ogg_FILE()
  87295. * provide a simpler interface.
  87296. *
  87297. * This function should be called after FLAC__stream_decoder_new() and
  87298. * FLAC__stream_decoder_set_*() but before any of the
  87299. * FLAC__stream_decoder_process_*() functions. Will set and return the
  87300. * decoder state, which will be FLAC__STREAM_DECODER_SEARCH_FOR_METADATA
  87301. * if initialization succeeded.
  87302. *
  87303. * \note Support for Ogg FLAC in the library is optional. If this
  87304. * library has been built without support for Ogg FLAC, this function
  87305. * will return \c FLAC__STREAM_DECODER_INIT_STATUS_UNSUPPORTED_CONTAINER.
  87306. *
  87307. * \param decoder An uninitialized decoder instance.
  87308. * \param read_callback See FLAC__StreamDecoderReadCallback. This
  87309. * pointer must not be \c NULL.
  87310. * \param seek_callback See FLAC__StreamDecoderSeekCallback. This
  87311. * pointer may be \c NULL if seeking is not
  87312. * supported. If \a seek_callback is not \c NULL then a
  87313. * \a tell_callback, \a length_callback, and \a eof_callback must also be supplied.
  87314. * Alternatively, a dummy seek callback that just
  87315. * returns \c FLAC__STREAM_DECODER_SEEK_STATUS_UNSUPPORTED
  87316. * may also be supplied, all though this is slightly
  87317. * less efficient for the decoder.
  87318. * \param tell_callback See FLAC__StreamDecoderTellCallback. This
  87319. * pointer may be \c NULL if not supported by the client. If
  87320. * \a seek_callback is not \c NULL then a
  87321. * \a tell_callback must also be supplied.
  87322. * Alternatively, a dummy tell callback that just
  87323. * returns \c FLAC__STREAM_DECODER_TELL_STATUS_UNSUPPORTED
  87324. * may also be supplied, all though this is slightly
  87325. * less efficient for the decoder.
  87326. * \param length_callback See FLAC__StreamDecoderLengthCallback. This
  87327. * pointer may be \c NULL if not supported by the client. If
  87328. * \a seek_callback is not \c NULL then a
  87329. * \a length_callback must also be supplied.
  87330. * Alternatively, a dummy length callback that just
  87331. * returns \c FLAC__STREAM_DECODER_LENGTH_STATUS_UNSUPPORTED
  87332. * may also be supplied, all though this is slightly
  87333. * less efficient for the decoder.
  87334. * \param eof_callback See FLAC__StreamDecoderEofCallback. This
  87335. * pointer may be \c NULL if not supported by the client. If
  87336. * \a seek_callback is not \c NULL then a
  87337. * \a eof_callback must also be supplied.
  87338. * Alternatively, a dummy length callback that just
  87339. * returns \c false
  87340. * may also be supplied, all though this is slightly
  87341. * less efficient for the decoder.
  87342. * \param write_callback See FLAC__StreamDecoderWriteCallback. This
  87343. * pointer must not be \c NULL.
  87344. * \param metadata_callback See FLAC__StreamDecoderMetadataCallback. This
  87345. * pointer may be \c NULL if the callback is not
  87346. * desired.
  87347. * \param error_callback See FLAC__StreamDecoderErrorCallback. This
  87348. * pointer must not be \c NULL.
  87349. * \param client_data This value will be supplied to callbacks in their
  87350. * \a client_data argument.
  87351. * \assert
  87352. * \code decoder != NULL \endcode
  87353. * \retval FLAC__StreamDecoderInitStatus
  87354. * \c FLAC__STREAM_DECODER_INIT_STATUS_OK if initialization was successful;
  87355. * see FLAC__StreamDecoderInitStatus for the meanings of other return values.
  87356. */
  87357. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_ogg_stream(
  87358. FLAC__StreamDecoder *decoder,
  87359. FLAC__StreamDecoderReadCallback read_callback,
  87360. FLAC__StreamDecoderSeekCallback seek_callback,
  87361. FLAC__StreamDecoderTellCallback tell_callback,
  87362. FLAC__StreamDecoderLengthCallback length_callback,
  87363. FLAC__StreamDecoderEofCallback eof_callback,
  87364. FLAC__StreamDecoderWriteCallback write_callback,
  87365. FLAC__StreamDecoderMetadataCallback metadata_callback,
  87366. FLAC__StreamDecoderErrorCallback error_callback,
  87367. void *client_data
  87368. );
  87369. /** Initialize the decoder instance to decode native FLAC files.
  87370. *
  87371. * This flavor of initialization sets up the decoder to decode from a
  87372. * plain native FLAC file. For non-stdio streams, you must use
  87373. * FLAC__stream_decoder_init_stream() and provide callbacks for the I/O.
  87374. *
  87375. * This function should be called after FLAC__stream_decoder_new() and
  87376. * FLAC__stream_decoder_set_*() but before any of the
  87377. * FLAC__stream_decoder_process_*() functions. Will set and return the
  87378. * decoder state, which will be FLAC__STREAM_DECODER_SEARCH_FOR_METADATA
  87379. * if initialization succeeded.
  87380. *
  87381. * \param decoder An uninitialized decoder instance.
  87382. * \param file An open FLAC file. The file should have been
  87383. * opened with mode \c "rb" and rewound. The file
  87384. * becomes owned by the decoder and should not be
  87385. * manipulated by the client while decoding.
  87386. * Unless \a file is \c stdin, it will be closed
  87387. * when FLAC__stream_decoder_finish() is called.
  87388. * Note however that seeking will not work when
  87389. * decoding from \c stdout since it is not seekable.
  87390. * \param write_callback See FLAC__StreamDecoderWriteCallback. This
  87391. * pointer must not be \c NULL.
  87392. * \param metadata_callback See FLAC__StreamDecoderMetadataCallback. This
  87393. * pointer may be \c NULL if the callback is not
  87394. * desired.
  87395. * \param error_callback See FLAC__StreamDecoderErrorCallback. This
  87396. * pointer must not be \c NULL.
  87397. * \param client_data This value will be supplied to callbacks in their
  87398. * \a client_data argument.
  87399. * \assert
  87400. * \code decoder != NULL \endcode
  87401. * \code file != NULL \endcode
  87402. * \retval FLAC__StreamDecoderInitStatus
  87403. * \c FLAC__STREAM_DECODER_INIT_STATUS_OK if initialization was successful;
  87404. * see FLAC__StreamDecoderInitStatus for the meanings of other return values.
  87405. */
  87406. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_FILE(
  87407. FLAC__StreamDecoder *decoder,
  87408. FILE *file,
  87409. FLAC__StreamDecoderWriteCallback write_callback,
  87410. FLAC__StreamDecoderMetadataCallback metadata_callback,
  87411. FLAC__StreamDecoderErrorCallback error_callback,
  87412. void *client_data
  87413. );
  87414. /** Initialize the decoder instance to decode Ogg FLAC files.
  87415. *
  87416. * This flavor of initialization sets up the decoder to decode from a
  87417. * plain Ogg FLAC file. For non-stdio streams, you must use
  87418. * FLAC__stream_decoder_init_ogg_stream() and provide callbacks for the I/O.
  87419. *
  87420. * This function should be called after FLAC__stream_decoder_new() and
  87421. * FLAC__stream_decoder_set_*() but before any of the
  87422. * FLAC__stream_decoder_process_*() functions. Will set and return the
  87423. * decoder state, which will be FLAC__STREAM_DECODER_SEARCH_FOR_METADATA
  87424. * if initialization succeeded.
  87425. *
  87426. * \note Support for Ogg FLAC in the library is optional. If this
  87427. * library has been built without support for Ogg FLAC, this function
  87428. * will return \c FLAC__STREAM_DECODER_INIT_STATUS_UNSUPPORTED_CONTAINER.
  87429. *
  87430. * \param decoder An uninitialized decoder instance.
  87431. * \param file An open FLAC file. The file should have been
  87432. * opened with mode \c "rb" and rewound. The file
  87433. * becomes owned by the decoder and should not be
  87434. * manipulated by the client while decoding.
  87435. * Unless \a file is \c stdin, it will be closed
  87436. * when FLAC__stream_decoder_finish() is called.
  87437. * Note however that seeking will not work when
  87438. * decoding from \c stdout since it is not seekable.
  87439. * \param write_callback See FLAC__StreamDecoderWriteCallback. This
  87440. * pointer must not be \c NULL.
  87441. * \param metadata_callback See FLAC__StreamDecoderMetadataCallback. This
  87442. * pointer may be \c NULL if the callback is not
  87443. * desired.
  87444. * \param error_callback See FLAC__StreamDecoderErrorCallback. This
  87445. * pointer must not be \c NULL.
  87446. * \param client_data This value will be supplied to callbacks in their
  87447. * \a client_data argument.
  87448. * \assert
  87449. * \code decoder != NULL \endcode
  87450. * \code file != NULL \endcode
  87451. * \retval FLAC__StreamDecoderInitStatus
  87452. * \c FLAC__STREAM_DECODER_INIT_STATUS_OK if initialization was successful;
  87453. * see FLAC__StreamDecoderInitStatus for the meanings of other return values.
  87454. */
  87455. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_ogg_FILE(
  87456. FLAC__StreamDecoder *decoder,
  87457. FILE *file,
  87458. FLAC__StreamDecoderWriteCallback write_callback,
  87459. FLAC__StreamDecoderMetadataCallback metadata_callback,
  87460. FLAC__StreamDecoderErrorCallback error_callback,
  87461. void *client_data
  87462. );
  87463. /** Initialize the decoder instance to decode native FLAC files.
  87464. *
  87465. * This flavor of initialization sets up the decoder to decode from a plain
  87466. * native FLAC file. If POSIX fopen() semantics are not sufficient, (for
  87467. * example, with Unicode filenames on Windows), you must use
  87468. * FLAC__stream_decoder_init_FILE(), or FLAC__stream_decoder_init_stream()
  87469. * and provide callbacks for the I/O.
  87470. *
  87471. * This function should be called after FLAC__stream_decoder_new() and
  87472. * FLAC__stream_decoder_set_*() but before any of the
  87473. * FLAC__stream_decoder_process_*() functions. Will set and return the
  87474. * decoder state, which will be FLAC__STREAM_DECODER_SEARCH_FOR_METADATA
  87475. * if initialization succeeded.
  87476. *
  87477. * \param decoder An uninitialized decoder instance.
  87478. * \param filename The name of the file to decode from. The file will
  87479. * be opened with fopen(). Use \c NULL to decode from
  87480. * \c stdin. Note that \c stdin is not seekable.
  87481. * \param write_callback See FLAC__StreamDecoderWriteCallback. This
  87482. * pointer must not be \c NULL.
  87483. * \param metadata_callback See FLAC__StreamDecoderMetadataCallback. This
  87484. * pointer may be \c NULL if the callback is not
  87485. * desired.
  87486. * \param error_callback See FLAC__StreamDecoderErrorCallback. This
  87487. * pointer must not be \c NULL.
  87488. * \param client_data This value will be supplied to callbacks in their
  87489. * \a client_data argument.
  87490. * \assert
  87491. * \code decoder != NULL \endcode
  87492. * \retval FLAC__StreamDecoderInitStatus
  87493. * \c FLAC__STREAM_DECODER_INIT_STATUS_OK if initialization was successful;
  87494. * see FLAC__StreamDecoderInitStatus for the meanings of other return values.
  87495. */
  87496. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_file(
  87497. FLAC__StreamDecoder *decoder,
  87498. const char *filename,
  87499. FLAC__StreamDecoderWriteCallback write_callback,
  87500. FLAC__StreamDecoderMetadataCallback metadata_callback,
  87501. FLAC__StreamDecoderErrorCallback error_callback,
  87502. void *client_data
  87503. );
  87504. /** Initialize the decoder instance to decode Ogg FLAC files.
  87505. *
  87506. * This flavor of initialization sets up the decoder to decode from a plain
  87507. * Ogg FLAC file. If POSIX fopen() semantics are not sufficient, (for
  87508. * example, with Unicode filenames on Windows), you must use
  87509. * FLAC__stream_decoder_init_ogg_FILE(), or FLAC__stream_decoder_init_ogg_stream()
  87510. * and provide callbacks for the I/O.
  87511. *
  87512. * This function should be called after FLAC__stream_decoder_new() and
  87513. * FLAC__stream_decoder_set_*() but before any of the
  87514. * FLAC__stream_decoder_process_*() functions. Will set and return the
  87515. * decoder state, which will be FLAC__STREAM_DECODER_SEARCH_FOR_METADATA
  87516. * if initialization succeeded.
  87517. *
  87518. * \note Support for Ogg FLAC in the library is optional. If this
  87519. * library has been built without support for Ogg FLAC, this function
  87520. * will return \c FLAC__STREAM_DECODER_INIT_STATUS_UNSUPPORTED_CONTAINER.
  87521. *
  87522. * \param decoder An uninitialized decoder instance.
  87523. * \param filename The name of the file to decode from. The file will
  87524. * be opened with fopen(). Use \c NULL to decode from
  87525. * \c stdin. Note that \c stdin is not seekable.
  87526. * \param write_callback See FLAC__StreamDecoderWriteCallback. This
  87527. * pointer must not be \c NULL.
  87528. * \param metadata_callback See FLAC__StreamDecoderMetadataCallback. This
  87529. * pointer may be \c NULL if the callback is not
  87530. * desired.
  87531. * \param error_callback See FLAC__StreamDecoderErrorCallback. This
  87532. * pointer must not be \c NULL.
  87533. * \param client_data This value will be supplied to callbacks in their
  87534. * \a client_data argument.
  87535. * \assert
  87536. * \code decoder != NULL \endcode
  87537. * \retval FLAC__StreamDecoderInitStatus
  87538. * \c FLAC__STREAM_DECODER_INIT_STATUS_OK if initialization was successful;
  87539. * see FLAC__StreamDecoderInitStatus for the meanings of other return values.
  87540. */
  87541. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_ogg_file(
  87542. FLAC__StreamDecoder *decoder,
  87543. const char *filename,
  87544. FLAC__StreamDecoderWriteCallback write_callback,
  87545. FLAC__StreamDecoderMetadataCallback metadata_callback,
  87546. FLAC__StreamDecoderErrorCallback error_callback,
  87547. void *client_data
  87548. );
  87549. /** Finish the decoding process.
  87550. * Flushes the decoding buffer, releases resources, resets the decoder
  87551. * settings to their defaults, and returns the decoder state to
  87552. * FLAC__STREAM_DECODER_UNINITIALIZED.
  87553. *
  87554. * In the event of a prematurely-terminated decode, it is not strictly
  87555. * necessary to call this immediately before FLAC__stream_decoder_delete()
  87556. * but it is good practice to match every FLAC__stream_decoder_init_*()
  87557. * with a FLAC__stream_decoder_finish().
  87558. *
  87559. * \param decoder An uninitialized decoder instance.
  87560. * \assert
  87561. * \code decoder != NULL \endcode
  87562. * \retval FLAC__bool
  87563. * \c false if MD5 checking is on AND a STREAMINFO block was available
  87564. * AND the MD5 signature in the STREAMINFO block was non-zero AND the
  87565. * signature does not match the one computed by the decoder; else
  87566. * \c true.
  87567. */
  87568. FLAC_API FLAC__bool FLAC__stream_decoder_finish(FLAC__StreamDecoder *decoder);
  87569. /** Flush the stream input.
  87570. * The decoder's input buffer will be cleared and the state set to
  87571. * \c FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC. This will also turn
  87572. * off MD5 checking.
  87573. *
  87574. * \param decoder A decoder instance.
  87575. * \assert
  87576. * \code decoder != NULL \endcode
  87577. * \retval FLAC__bool
  87578. * \c true if successful, else \c false if a memory allocation
  87579. * error occurs (in which case the state will be set to
  87580. * \c FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR).
  87581. */
  87582. FLAC_API FLAC__bool FLAC__stream_decoder_flush(FLAC__StreamDecoder *decoder);
  87583. /** Reset the decoding process.
  87584. * The decoder's input buffer will be cleared and the state set to
  87585. * \c FLAC__STREAM_DECODER_SEARCH_FOR_METADATA. This is similar to
  87586. * FLAC__stream_decoder_finish() except that the settings are
  87587. * preserved; there is no need to call FLAC__stream_decoder_init_*()
  87588. * before decoding again. MD5 checking will be restored to its original
  87589. * setting.
  87590. *
  87591. * If the decoder is seekable, or was initialized with
  87592. * FLAC__stream_decoder_init*_FILE() or FLAC__stream_decoder_init*_file(),
  87593. * the decoder will also attempt to seek to the beginning of the file.
  87594. * If this rewind fails, this function will return \c false. It follows
  87595. * that FLAC__stream_decoder_reset() cannot be used when decoding from
  87596. * \c stdin.
  87597. *
  87598. * If the decoder was initialized with FLAC__stream_encoder_init*_stream()
  87599. * and is not seekable (i.e. no seek callback was provided or the seek
  87600. * callback returns \c FLAC__STREAM_DECODER_SEEK_STATUS_UNSUPPORTED), it
  87601. * is the duty of the client to start feeding data from the beginning of
  87602. * the stream on the next FLAC__stream_decoder_process() or
  87603. * FLAC__stream_decoder_process_interleaved() call.
  87604. *
  87605. * \param decoder A decoder instance.
  87606. * \assert
  87607. * \code decoder != NULL \endcode
  87608. * \retval FLAC__bool
  87609. * \c true if successful, else \c false if a memory allocation occurs
  87610. * (in which case the state will be set to
  87611. * \c FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR) or a seek error
  87612. * occurs (the state will be unchanged).
  87613. */
  87614. FLAC_API FLAC__bool FLAC__stream_decoder_reset(FLAC__StreamDecoder *decoder);
  87615. /** Decode one metadata block or audio frame.
  87616. * This version instructs the decoder to decode a either a single metadata
  87617. * block or a single frame and stop, unless the callbacks return a fatal
  87618. * error or the read callback returns
  87619. * \c FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM.
  87620. *
  87621. * As the decoder needs more input it will call the read callback.
  87622. * Depending on what was decoded, the metadata or write callback will be
  87623. * called with the decoded metadata block or audio frame.
  87624. *
  87625. * Unless there is a fatal read error or end of stream, this function
  87626. * will return once one whole frame is decoded. In other words, if the
  87627. * stream is not synchronized or points to a corrupt frame header, the
  87628. * decoder will continue to try and resync until it gets to a valid
  87629. * frame, then decode one frame, then return. If the decoder points to
  87630. * a frame whose frame CRC in the frame footer does not match the
  87631. * computed frame CRC, this function will issue a
  87632. * FLAC__STREAM_DECODER_ERROR_STATUS_FRAME_CRC_MISMATCH error to the
  87633. * error callback, and return, having decoded one complete, although
  87634. * corrupt, frame. (Such corrupted frames are sent as silence of the
  87635. * correct length to the write callback.)
  87636. *
  87637. * \param decoder An initialized decoder instance.
  87638. * \assert
  87639. * \code decoder != NULL \endcode
  87640. * \retval FLAC__bool
  87641. * \c false if any fatal read, write, or memory allocation error
  87642. * occurred (meaning decoding must stop), else \c true; for more
  87643. * information about the decoder, check the decoder state with
  87644. * FLAC__stream_decoder_get_state().
  87645. */
  87646. FLAC_API FLAC__bool FLAC__stream_decoder_process_single(FLAC__StreamDecoder *decoder);
  87647. /** Decode until the end of the metadata.
  87648. * This version instructs the decoder to decode from the current position
  87649. * and continue until all the metadata has been read, or until the
  87650. * callbacks return a fatal error or the read callback returns
  87651. * \c FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM.
  87652. *
  87653. * As the decoder needs more input it will call the read callback.
  87654. * As each metadata block is decoded, the metadata callback will be called
  87655. * with the decoded metadata.
  87656. *
  87657. * \param decoder An initialized decoder instance.
  87658. * \assert
  87659. * \code decoder != NULL \endcode
  87660. * \retval FLAC__bool
  87661. * \c false if any fatal read, write, or memory allocation error
  87662. * occurred (meaning decoding must stop), else \c true; for more
  87663. * information about the decoder, check the decoder state with
  87664. * FLAC__stream_decoder_get_state().
  87665. */
  87666. FLAC_API FLAC__bool FLAC__stream_decoder_process_until_end_of_metadata(FLAC__StreamDecoder *decoder);
  87667. /** Decode until the end of the stream.
  87668. * This version instructs the decoder to decode from the current position
  87669. * and continue until the end of stream (the read callback returns
  87670. * \c FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM), or until the
  87671. * callbacks return a fatal error.
  87672. *
  87673. * As the decoder needs more input it will call the read callback.
  87674. * As each metadata block and frame is decoded, the metadata or write
  87675. * callback will be called with the decoded metadata or frame.
  87676. *
  87677. * \param decoder An initialized decoder instance.
  87678. * \assert
  87679. * \code decoder != NULL \endcode
  87680. * \retval FLAC__bool
  87681. * \c false if any fatal read, write, or memory allocation error
  87682. * occurred (meaning decoding must stop), else \c true; for more
  87683. * information about the decoder, check the decoder state with
  87684. * FLAC__stream_decoder_get_state().
  87685. */
  87686. FLAC_API FLAC__bool FLAC__stream_decoder_process_until_end_of_stream(FLAC__StreamDecoder *decoder);
  87687. /** Skip one audio frame.
  87688. * This version instructs the decoder to 'skip' a single frame and stop,
  87689. * unless the callbacks return a fatal error or the read callback returns
  87690. * \c FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM.
  87691. *
  87692. * The decoding flow is the same as what occurs when
  87693. * FLAC__stream_decoder_process_single() is called to process an audio
  87694. * frame, except that this function does not decode the parsed data into
  87695. * PCM or call the write callback. The integrity of the frame is still
  87696. * checked the same way as in the other process functions.
  87697. *
  87698. * This function will return once one whole frame is skipped, in the
  87699. * same way that FLAC__stream_decoder_process_single() will return once
  87700. * one whole frame is decoded.
  87701. *
  87702. * This function can be used in more quickly determining FLAC frame
  87703. * boundaries when decoding of the actual data is not needed, for
  87704. * example when an application is separating a FLAC stream into frames
  87705. * for editing or storing in a container. To do this, the application
  87706. * can use FLAC__stream_decoder_skip_single_frame() to quickly advance
  87707. * to the next frame, then use
  87708. * FLAC__stream_decoder_get_decode_position() to find the new frame
  87709. * boundary.
  87710. *
  87711. * This function should only be called when the stream has advanced
  87712. * past all the metadata, otherwise it will return \c false.
  87713. *
  87714. * \param decoder An initialized decoder instance not in a metadata
  87715. * state.
  87716. * \assert
  87717. * \code decoder != NULL \endcode
  87718. * \retval FLAC__bool
  87719. * \c false if any fatal read, write, or memory allocation error
  87720. * occurred (meaning decoding must stop), or if the decoder
  87721. * is in the FLAC__STREAM_DECODER_SEARCH_FOR_METADATA or
  87722. * FLAC__STREAM_DECODER_READ_METADATA state, else \c true; for more
  87723. * information about the decoder, check the decoder state with
  87724. * FLAC__stream_decoder_get_state().
  87725. */
  87726. FLAC_API FLAC__bool FLAC__stream_decoder_skip_single_frame(FLAC__StreamDecoder *decoder);
  87727. /** Flush the input and seek to an absolute sample.
  87728. * Decoding will resume at the given sample. Note that because of
  87729. * this, the next write callback may contain a partial block. The
  87730. * client must support seeking the input or this function will fail
  87731. * and return \c false. Furthermore, if the decoder state is
  87732. * \c FLAC__STREAM_DECODER_SEEK_ERROR, then the decoder must be flushed
  87733. * with FLAC__stream_decoder_flush() or reset with
  87734. * FLAC__stream_decoder_reset() before decoding can continue.
  87735. *
  87736. * \param decoder A decoder instance.
  87737. * \param sample The target sample number to seek to.
  87738. * \assert
  87739. * \code decoder != NULL \endcode
  87740. * \retval FLAC__bool
  87741. * \c true if successful, else \c false.
  87742. */
  87743. FLAC_API FLAC__bool FLAC__stream_decoder_seek_absolute(FLAC__StreamDecoder *decoder, FLAC__uint64 sample);
  87744. /* \} */
  87745. #ifdef __cplusplus
  87746. }
  87747. #endif
  87748. #endif
  87749. /*** End of inlined file: stream_decoder.h ***/
  87750. /*** Start of inlined file: stream_encoder.h ***/
  87751. #ifndef FLAC__STREAM_ENCODER_H
  87752. #define FLAC__STREAM_ENCODER_H
  87753. #include <stdio.h> /* for FILE */
  87754. #ifdef __cplusplus
  87755. extern "C" {
  87756. #endif
  87757. /** \file include/FLAC/stream_encoder.h
  87758. *
  87759. * \brief
  87760. * This module contains the functions which implement the stream
  87761. * encoder.
  87762. *
  87763. * See the detailed documentation in the
  87764. * \link flac_stream_encoder stream encoder \endlink module.
  87765. */
  87766. /** \defgroup flac_encoder FLAC/ \*_encoder.h: encoder interfaces
  87767. * \ingroup flac
  87768. *
  87769. * \brief
  87770. * This module describes the encoder layers provided by libFLAC.
  87771. *
  87772. * The stream encoder can be used to encode complete streams either to the
  87773. * client via callbacks, or directly to a file, depending on how it is
  87774. * initialized. When encoding via callbacks, the client provides a write
  87775. * callback which will be called whenever FLAC data is ready to be written.
  87776. * If the client also supplies a seek callback, the encoder will also
  87777. * automatically handle the writing back of metadata discovered while
  87778. * encoding, like stream info, seek points offsets, etc. When encoding to
  87779. * a file, the client needs only supply a filename or open \c FILE* and an
  87780. * optional progress callback for periodic notification of progress; the
  87781. * write and seek callbacks are supplied internally. For more info see the
  87782. * \link flac_stream_encoder stream encoder \endlink module.
  87783. */
  87784. /** \defgroup flac_stream_encoder FLAC/stream_encoder.h: stream encoder interface
  87785. * \ingroup flac_encoder
  87786. *
  87787. * \brief
  87788. * This module contains the functions which implement the stream
  87789. * encoder.
  87790. *
  87791. * The stream encoder can encode to native FLAC, and optionally Ogg FLAC
  87792. * (check FLAC_API_SUPPORTS_OGG_FLAC) streams and files.
  87793. *
  87794. * The basic usage of this encoder is as follows:
  87795. * - The program creates an instance of an encoder using
  87796. * FLAC__stream_encoder_new().
  87797. * - The program overrides the default settings using
  87798. * FLAC__stream_encoder_set_*() functions. At a minimum, the following
  87799. * functions should be called:
  87800. * - FLAC__stream_encoder_set_channels()
  87801. * - FLAC__stream_encoder_set_bits_per_sample()
  87802. * - FLAC__stream_encoder_set_sample_rate()
  87803. * - FLAC__stream_encoder_set_ogg_serial_number() (if encoding to Ogg FLAC)
  87804. * - FLAC__stream_encoder_set_total_samples_estimate() (if known)
  87805. * - If the application wants to control the compression level or set its own
  87806. * metadata, then the following should also be called:
  87807. * - FLAC__stream_encoder_set_compression_level()
  87808. * - FLAC__stream_encoder_set_verify()
  87809. * - FLAC__stream_encoder_set_metadata()
  87810. * - The rest of the set functions should only be called if the client needs
  87811. * exact control over how the audio is compressed; thorough understanding
  87812. * of the FLAC format is necessary to achieve good results.
  87813. * - The program initializes the instance to validate the settings and
  87814. * prepare for encoding using
  87815. * - FLAC__stream_encoder_init_stream() or FLAC__stream_encoder_init_FILE()
  87816. * or FLAC__stream_encoder_init_file() for native FLAC
  87817. * - FLAC__stream_encoder_init_ogg_stream() or FLAC__stream_encoder_init_ogg_FILE()
  87818. * or FLAC__stream_encoder_init_ogg_file() for Ogg FLAC
  87819. * - The program calls FLAC__stream_encoder_process() or
  87820. * FLAC__stream_encoder_process_interleaved() to encode data, which
  87821. * subsequently calls the callbacks when there is encoder data ready
  87822. * to be written.
  87823. * - The program finishes the encoding with FLAC__stream_encoder_finish(),
  87824. * which causes the encoder to encode any data still in its input pipe,
  87825. * update the metadata with the final encoding statistics if output
  87826. * seeking is possible, and finally reset the encoder to the
  87827. * uninitialized state.
  87828. * - The instance may be used again or deleted with
  87829. * FLAC__stream_encoder_delete().
  87830. *
  87831. * In more detail, the stream encoder functions similarly to the
  87832. * \link flac_stream_decoder stream decoder \endlink, but has fewer
  87833. * callbacks and more options. Typically the client will create a new
  87834. * instance by calling FLAC__stream_encoder_new(), then set the necessary
  87835. * parameters with FLAC__stream_encoder_set_*(), and initialize it by
  87836. * calling one of the FLAC__stream_encoder_init_*() functions.
  87837. *
  87838. * Unlike the decoders, the stream encoder has many options that can
  87839. * affect the speed and compression ratio. When setting these parameters
  87840. * you should have some basic knowledge of the format (see the
  87841. * <A HREF="../documentation.html#format">user-level documentation</A>
  87842. * or the <A HREF="../format.html">formal description</A>). The
  87843. * FLAC__stream_encoder_set_*() functions themselves do not validate the
  87844. * values as many are interdependent. The FLAC__stream_encoder_init_*()
  87845. * functions will do this, so make sure to pay attention to the state
  87846. * returned by FLAC__stream_encoder_init_*() to make sure that it is
  87847. * FLAC__STREAM_ENCODER_INIT_STATUS_OK. Any parameters that are not set
  87848. * before FLAC__stream_encoder_init_*() will take on the defaults from
  87849. * the constructor.
  87850. *
  87851. * There are three initialization functions for native FLAC, one for
  87852. * setting up the encoder to encode FLAC data to the client via
  87853. * callbacks, and two for encoding directly to a file.
  87854. *
  87855. * For encoding via callbacks, use FLAC__stream_encoder_init_stream().
  87856. * You must also supply a write callback which will be called anytime
  87857. * there is raw encoded data to write. If the client can seek the output
  87858. * it is best to also supply seek and tell callbacks, as this allows the
  87859. * encoder to go back after encoding is finished to write back
  87860. * information that was collected while encoding, like seek point offsets,
  87861. * frame sizes, etc.
  87862. *
  87863. * For encoding directly to a file, use FLAC__stream_encoder_init_FILE()
  87864. * or FLAC__stream_encoder_init_file(). Then you must only supply a
  87865. * filename or open \c FILE*; the encoder will handle all the callbacks
  87866. * internally. You may also supply a progress callback for periodic
  87867. * notification of the encoding progress.
  87868. *
  87869. * There are three similarly-named init functions for encoding to Ogg
  87870. * FLAC streams. Check \c FLAC_API_SUPPORTS_OGG_FLAC to find out if the
  87871. * library has been built with Ogg support.
  87872. *
  87873. * The call to FLAC__stream_encoder_init_*() currently will also immediately
  87874. * call the write callback several times, once with the \c fLaC signature,
  87875. * and once for each encoded metadata block. Note that for Ogg FLAC
  87876. * encoding you will usually get at least twice the number of callbacks than
  87877. * with native FLAC, one for the Ogg page header and one for the page body.
  87878. *
  87879. * After initializing the instance, the client may feed audio data to the
  87880. * encoder in one of two ways:
  87881. *
  87882. * - Channel separate, through FLAC__stream_encoder_process() - The client
  87883. * will pass an array of pointers to buffers, one for each channel, to
  87884. * the encoder, each of the same length. The samples need not be
  87885. * block-aligned, but each channel should have the same number of samples.
  87886. * - Channel interleaved, through
  87887. * FLAC__stream_encoder_process_interleaved() - The client will pass a single
  87888. * pointer to data that is channel-interleaved (i.e. channel0_sample0,
  87889. * channel1_sample0, ... , channelN_sample0, channel0_sample1, ...).
  87890. * Again, the samples need not be block-aligned but they must be
  87891. * sample-aligned, i.e. the first value should be channel0_sample0 and
  87892. * the last value channelN_sampleM.
  87893. *
  87894. * Note that for either process call, each sample in the buffers should be a
  87895. * signed integer, right-justified to the resolution set by
  87896. * FLAC__stream_encoder_set_bits_per_sample(). For example, if the resolution
  87897. * is 16 bits per sample, the samples should all be in the range [-32768,32767].
  87898. *
  87899. * When the client is finished encoding data, it calls
  87900. * FLAC__stream_encoder_finish(), which causes the encoder to encode any
  87901. * data still in its input pipe, and call the metadata callback with the
  87902. * final encoding statistics. Then the instance may be deleted with
  87903. * FLAC__stream_encoder_delete() or initialized again to encode another
  87904. * stream.
  87905. *
  87906. * For programs that write their own metadata, but that do not know the
  87907. * actual metadata until after encoding, it is advantageous to instruct
  87908. * the encoder to write a PADDING block of the correct size, so that
  87909. * instead of rewriting the whole stream after encoding, the program can
  87910. * just overwrite the PADDING block. If only the maximum size of the
  87911. * metadata is known, the program can write a slightly larger padding
  87912. * block, then split it after encoding.
  87913. *
  87914. * Make sure you understand how lengths are calculated. All FLAC metadata
  87915. * blocks have a 4 byte header which contains the type and length. This
  87916. * length does not include the 4 bytes of the header. See the format page
  87917. * for the specification of metadata blocks and their lengths.
  87918. *
  87919. * \note
  87920. * If you are writing the FLAC data to a file via callbacks, make sure it
  87921. * is open for update (e.g. mode "w+" for stdio streams). This is because
  87922. * after the first encoding pass, the encoder will try to seek back to the
  87923. * beginning of the stream, to the STREAMINFO block, to write some data
  87924. * there. (If using FLAC__stream_encoder_init*_file() or
  87925. * FLAC__stream_encoder_init*_FILE(), the file is managed internally.)
  87926. *
  87927. * \note
  87928. * The "set" functions may only be called when the encoder is in the
  87929. * state FLAC__STREAM_ENCODER_UNINITIALIZED, i.e. after
  87930. * FLAC__stream_encoder_new() or FLAC__stream_encoder_finish(), but
  87931. * before FLAC__stream_encoder_init_*(). If this is the case they will
  87932. * return \c true, otherwise \c false.
  87933. *
  87934. * \note
  87935. * FLAC__stream_encoder_finish() resets all settings to the constructor
  87936. * defaults.
  87937. *
  87938. * \{
  87939. */
  87940. /** State values for a FLAC__StreamEncoder.
  87941. *
  87942. * The encoder's state can be obtained by calling FLAC__stream_encoder_get_state().
  87943. *
  87944. * If the encoder gets into any other state besides \c FLAC__STREAM_ENCODER_OK
  87945. * or \c FLAC__STREAM_ENCODER_UNINITIALIZED, it becomes invalid for encoding and
  87946. * must be deleted with FLAC__stream_encoder_delete().
  87947. */
  87948. typedef enum {
  87949. FLAC__STREAM_ENCODER_OK = 0,
  87950. /**< The encoder is in the normal OK state and samples can be processed. */
  87951. FLAC__STREAM_ENCODER_UNINITIALIZED,
  87952. /**< The encoder is in the uninitialized state; one of the
  87953. * FLAC__stream_encoder_init_*() functions must be called before samples
  87954. * can be processed.
  87955. */
  87956. FLAC__STREAM_ENCODER_OGG_ERROR,
  87957. /**< An error occurred in the underlying Ogg layer. */
  87958. FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR,
  87959. /**< An error occurred in the underlying verify stream decoder;
  87960. * check FLAC__stream_encoder_get_verify_decoder_state().
  87961. */
  87962. FLAC__STREAM_ENCODER_VERIFY_MISMATCH_IN_AUDIO_DATA,
  87963. /**< The verify decoder detected a mismatch between the original
  87964. * audio signal and the decoded audio signal.
  87965. */
  87966. FLAC__STREAM_ENCODER_CLIENT_ERROR,
  87967. /**< One of the callbacks returned a fatal error. */
  87968. FLAC__STREAM_ENCODER_IO_ERROR,
  87969. /**< An I/O error occurred while opening/reading/writing a file.
  87970. * Check \c errno.
  87971. */
  87972. FLAC__STREAM_ENCODER_FRAMING_ERROR,
  87973. /**< An error occurred while writing the stream; usually, the
  87974. * write_callback returned an error.
  87975. */
  87976. FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR
  87977. /**< Memory allocation failed. */
  87978. } FLAC__StreamEncoderState;
  87979. /** Maps a FLAC__StreamEncoderState to a C string.
  87980. *
  87981. * Using a FLAC__StreamEncoderState as the index to this array
  87982. * will give the string equivalent. The contents should not be modified.
  87983. */
  87984. extern FLAC_API const char * const FLAC__StreamEncoderStateString[];
  87985. /** Possible return values for the FLAC__stream_encoder_init_*() functions.
  87986. */
  87987. typedef enum {
  87988. FLAC__STREAM_ENCODER_INIT_STATUS_OK = 0,
  87989. /**< Initialization was successful. */
  87990. FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR,
  87991. /**< General failure to set up encoder; call FLAC__stream_encoder_get_state() for cause. */
  87992. FLAC__STREAM_ENCODER_INIT_STATUS_UNSUPPORTED_CONTAINER,
  87993. /**< The library was not compiled with support for the given container
  87994. * format.
  87995. */
  87996. FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_CALLBACKS,
  87997. /**< A required callback was not supplied. */
  87998. FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_NUMBER_OF_CHANNELS,
  87999. /**< The encoder has an invalid setting for number of channels. */
  88000. FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_BITS_PER_SAMPLE,
  88001. /**< The encoder has an invalid setting for bits-per-sample.
  88002. * FLAC supports 4-32 bps but the reference encoder currently supports
  88003. * only up to 24 bps.
  88004. */
  88005. FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_SAMPLE_RATE,
  88006. /**< The encoder has an invalid setting for the input sample rate. */
  88007. FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_BLOCK_SIZE,
  88008. /**< The encoder has an invalid setting for the block size. */
  88009. FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_MAX_LPC_ORDER,
  88010. /**< The encoder has an invalid setting for the maximum LPC order. */
  88011. FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_QLP_COEFF_PRECISION,
  88012. /**< The encoder has an invalid setting for the precision of the quantized linear predictor coefficients. */
  88013. FLAC__STREAM_ENCODER_INIT_STATUS_BLOCK_SIZE_TOO_SMALL_FOR_LPC_ORDER,
  88014. /**< The specified block size is less than the maximum LPC order. */
  88015. FLAC__STREAM_ENCODER_INIT_STATUS_NOT_STREAMABLE,
  88016. /**< The encoder is bound to the <A HREF="../format.html#subset">Subset</A> but other settings violate it. */
  88017. FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA,
  88018. /**< The metadata input to the encoder is invalid, in one of the following ways:
  88019. * - FLAC__stream_encoder_set_metadata() was called with a null pointer but a block count > 0
  88020. * - One of the metadata blocks contains an undefined type
  88021. * - It contains an illegal CUESHEET as checked by FLAC__format_cuesheet_is_legal()
  88022. * - It contains an illegal SEEKTABLE as checked by FLAC__format_seektable_is_legal()
  88023. * - It contains more than one SEEKTABLE block or more than one VORBIS_COMMENT block
  88024. */
  88025. FLAC__STREAM_ENCODER_INIT_STATUS_ALREADY_INITIALIZED
  88026. /**< FLAC__stream_encoder_init_*() was called when the encoder was
  88027. * already initialized, usually because
  88028. * FLAC__stream_encoder_finish() was not called.
  88029. */
  88030. } FLAC__StreamEncoderInitStatus;
  88031. /** Maps a FLAC__StreamEncoderInitStatus to a C string.
  88032. *
  88033. * Using a FLAC__StreamEncoderInitStatus as the index to this array
  88034. * will give the string equivalent. The contents should not be modified.
  88035. */
  88036. extern FLAC_API const char * const FLAC__StreamEncoderInitStatusString[];
  88037. /** Return values for the FLAC__StreamEncoder read callback.
  88038. */
  88039. typedef enum {
  88040. FLAC__STREAM_ENCODER_READ_STATUS_CONTINUE,
  88041. /**< The read was OK and decoding can continue. */
  88042. FLAC__STREAM_ENCODER_READ_STATUS_END_OF_STREAM,
  88043. /**< The read was attempted at the end of the stream. */
  88044. FLAC__STREAM_ENCODER_READ_STATUS_ABORT,
  88045. /**< An unrecoverable error occurred. */
  88046. FLAC__STREAM_ENCODER_READ_STATUS_UNSUPPORTED
  88047. /**< Client does not support reading back from the output. */
  88048. } FLAC__StreamEncoderReadStatus;
  88049. /** Maps a FLAC__StreamEncoderReadStatus to a C string.
  88050. *
  88051. * Using a FLAC__StreamEncoderReadStatus as the index to this array
  88052. * will give the string equivalent. The contents should not be modified.
  88053. */
  88054. extern FLAC_API const char * const FLAC__StreamEncoderReadStatusString[];
  88055. /** Return values for the FLAC__StreamEncoder write callback.
  88056. */
  88057. typedef enum {
  88058. FLAC__STREAM_ENCODER_WRITE_STATUS_OK = 0,
  88059. /**< The write was OK and encoding can continue. */
  88060. FLAC__STREAM_ENCODER_WRITE_STATUS_FATAL_ERROR
  88061. /**< An unrecoverable error occurred. The encoder will return from the process call. */
  88062. } FLAC__StreamEncoderWriteStatus;
  88063. /** Maps a FLAC__StreamEncoderWriteStatus to a C string.
  88064. *
  88065. * Using a FLAC__StreamEncoderWriteStatus as the index to this array
  88066. * will give the string equivalent. The contents should not be modified.
  88067. */
  88068. extern FLAC_API const char * const FLAC__StreamEncoderWriteStatusString[];
  88069. /** Return values for the FLAC__StreamEncoder seek callback.
  88070. */
  88071. typedef enum {
  88072. FLAC__STREAM_ENCODER_SEEK_STATUS_OK,
  88073. /**< The seek was OK and encoding can continue. */
  88074. FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR,
  88075. /**< An unrecoverable error occurred. */
  88076. FLAC__STREAM_ENCODER_SEEK_STATUS_UNSUPPORTED
  88077. /**< Client does not support seeking. */
  88078. } FLAC__StreamEncoderSeekStatus;
  88079. /** Maps a FLAC__StreamEncoderSeekStatus to a C string.
  88080. *
  88081. * Using a FLAC__StreamEncoderSeekStatus as the index to this array
  88082. * will give the string equivalent. The contents should not be modified.
  88083. */
  88084. extern FLAC_API const char * const FLAC__StreamEncoderSeekStatusString[];
  88085. /** Return values for the FLAC__StreamEncoder tell callback.
  88086. */
  88087. typedef enum {
  88088. FLAC__STREAM_ENCODER_TELL_STATUS_OK,
  88089. /**< The tell was OK and encoding can continue. */
  88090. FLAC__STREAM_ENCODER_TELL_STATUS_ERROR,
  88091. /**< An unrecoverable error occurred. */
  88092. FLAC__STREAM_ENCODER_TELL_STATUS_UNSUPPORTED
  88093. /**< Client does not support seeking. */
  88094. } FLAC__StreamEncoderTellStatus;
  88095. /** Maps a FLAC__StreamEncoderTellStatus to a C string.
  88096. *
  88097. * Using a FLAC__StreamEncoderTellStatus as the index to this array
  88098. * will give the string equivalent. The contents should not be modified.
  88099. */
  88100. extern FLAC_API const char * const FLAC__StreamEncoderTellStatusString[];
  88101. /***********************************************************************
  88102. *
  88103. * class FLAC__StreamEncoder
  88104. *
  88105. ***********************************************************************/
  88106. struct FLAC__StreamEncoderProtected;
  88107. struct FLAC__StreamEncoderPrivate;
  88108. /** The opaque structure definition for the stream encoder type.
  88109. * See the \link flac_stream_encoder stream encoder module \endlink
  88110. * for a detailed description.
  88111. */
  88112. typedef struct {
  88113. struct FLAC__StreamEncoderProtected *protected_; /* avoid the C++ keyword 'protected' */
  88114. struct FLAC__StreamEncoderPrivate *private_; /* avoid the C++ keyword 'private' */
  88115. } FLAC__StreamEncoder;
  88116. /** Signature for the read callback.
  88117. *
  88118. * A function pointer matching this signature must be passed to
  88119. * FLAC__stream_encoder_init_ogg_stream() if seeking is supported.
  88120. * The supplied function will be called when the encoder needs to read back
  88121. * encoded data. This happens during the metadata callback, when the encoder
  88122. * has to read, modify, and rewrite the metadata (e.g. seekpoints) gathered
  88123. * while encoding. The address of the buffer to be filled is supplied, along
  88124. * with the number of bytes the buffer can hold. The callback may choose to
  88125. * supply less data and modify the byte count but must be careful not to
  88126. * overflow the buffer. The callback then returns a status code chosen from
  88127. * FLAC__StreamEncoderReadStatus.
  88128. *
  88129. * Here is an example of a read callback for stdio streams:
  88130. * \code
  88131. * FLAC__StreamEncoderReadStatus read_cb(const FLAC__StreamEncoder *encoder, FLAC__byte buffer[], size_t *bytes, void *client_data)
  88132. * {
  88133. * FILE *file = ((MyClientData*)client_data)->file;
  88134. * if(*bytes > 0) {
  88135. * *bytes = fread(buffer, sizeof(FLAC__byte), *bytes, file);
  88136. * if(ferror(file))
  88137. * return FLAC__STREAM_ENCODER_READ_STATUS_ABORT;
  88138. * else if(*bytes == 0)
  88139. * return FLAC__STREAM_ENCODER_READ_STATUS_END_OF_STREAM;
  88140. * else
  88141. * return FLAC__STREAM_ENCODER_READ_STATUS_CONTINUE;
  88142. * }
  88143. * else
  88144. * return FLAC__STREAM_ENCODER_READ_STATUS_ABORT;
  88145. * }
  88146. * \endcode
  88147. *
  88148. * \note In general, FLAC__StreamEncoder functions which change the
  88149. * state should not be called on the \a encoder while in the callback.
  88150. *
  88151. * \param encoder The encoder instance calling the callback.
  88152. * \param buffer A pointer to a location for the callee to store
  88153. * data to be encoded.
  88154. * \param bytes A pointer to the size of the buffer. On entry
  88155. * to the callback, it contains the maximum number
  88156. * of bytes that may be stored in \a buffer. The
  88157. * callee must set it to the actual number of bytes
  88158. * stored (0 in case of error or end-of-stream) before
  88159. * returning.
  88160. * \param client_data The callee's client data set through
  88161. * FLAC__stream_encoder_set_client_data().
  88162. * \retval FLAC__StreamEncoderReadStatus
  88163. * The callee's return status.
  88164. */
  88165. typedef FLAC__StreamEncoderReadStatus (*FLAC__StreamEncoderReadCallback)(const FLAC__StreamEncoder *encoder, FLAC__byte buffer[], size_t *bytes, void *client_data);
  88166. /** Signature for the write callback.
  88167. *
  88168. * A function pointer matching this signature must be passed to
  88169. * FLAC__stream_encoder_init*_stream(). The supplied function will be called
  88170. * by the encoder anytime there is raw encoded data ready to write. It may
  88171. * include metadata mixed with encoded audio frames and the data is not
  88172. * guaranteed to be aligned on frame or metadata block boundaries.
  88173. *
  88174. * The only duty of the callback is to write out the \a bytes worth of data
  88175. * in \a buffer to the current position in the output stream. The arguments
  88176. * \a samples and \a current_frame are purely informational. If \a samples
  88177. * is greater than \c 0, then \a current_frame will hold the current frame
  88178. * number that is being written; otherwise it indicates that the write
  88179. * callback is being called to write metadata.
  88180. *
  88181. * \note
  88182. * Unlike when writing to native FLAC, when writing to Ogg FLAC the
  88183. * write callback will be called twice when writing each audio
  88184. * frame; once for the page header, and once for the page body.
  88185. * When writing the page header, the \a samples argument to the
  88186. * write callback will be \c 0.
  88187. *
  88188. * \note In general, FLAC__StreamEncoder functions which change the
  88189. * state should not be called on the \a encoder while in the callback.
  88190. *
  88191. * \param encoder The encoder instance calling the callback.
  88192. * \param buffer An array of encoded data of length \a bytes.
  88193. * \param bytes The byte length of \a buffer.
  88194. * \param samples The number of samples encoded by \a buffer.
  88195. * \c 0 has a special meaning; see above.
  88196. * \param current_frame The number of the current frame being encoded.
  88197. * \param client_data The callee's client data set through
  88198. * FLAC__stream_encoder_init_*().
  88199. * \retval FLAC__StreamEncoderWriteStatus
  88200. * The callee's return status.
  88201. */
  88202. typedef FLAC__StreamEncoderWriteStatus (*FLAC__StreamEncoderWriteCallback)(const FLAC__StreamEncoder *encoder, const FLAC__byte buffer[], size_t bytes, unsigned samples, unsigned current_frame, void *client_data);
  88203. /** Signature for the seek callback.
  88204. *
  88205. * A function pointer matching this signature may be passed to
  88206. * FLAC__stream_encoder_init*_stream(). The supplied function will be called
  88207. * when the encoder needs to seek the output stream. The encoder will pass
  88208. * the absolute byte offset to seek to, 0 meaning the beginning of the stream.
  88209. *
  88210. * Here is an example of a seek callback for stdio streams:
  88211. * \code
  88212. * FLAC__StreamEncoderSeekStatus seek_cb(const FLAC__StreamEncoder *encoder, FLAC__uint64 absolute_byte_offset, void *client_data)
  88213. * {
  88214. * FILE *file = ((MyClientData*)client_data)->file;
  88215. * if(file == stdin)
  88216. * return FLAC__STREAM_ENCODER_SEEK_STATUS_UNSUPPORTED;
  88217. * else if(fseeko(file, (off_t)absolute_byte_offset, SEEK_SET) < 0)
  88218. * return FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR;
  88219. * else
  88220. * return FLAC__STREAM_ENCODER_SEEK_STATUS_OK;
  88221. * }
  88222. * \endcode
  88223. *
  88224. * \note In general, FLAC__StreamEncoder functions which change the
  88225. * state should not be called on the \a encoder while in the callback.
  88226. *
  88227. * \param encoder The encoder instance calling the callback.
  88228. * \param absolute_byte_offset The offset from the beginning of the stream
  88229. * to seek to.
  88230. * \param client_data The callee's client data set through
  88231. * FLAC__stream_encoder_init_*().
  88232. * \retval FLAC__StreamEncoderSeekStatus
  88233. * The callee's return status.
  88234. */
  88235. typedef FLAC__StreamEncoderSeekStatus (*FLAC__StreamEncoderSeekCallback)(const FLAC__StreamEncoder *encoder, FLAC__uint64 absolute_byte_offset, void *client_data);
  88236. /** Signature for the tell callback.
  88237. *
  88238. * A function pointer matching this signature may be passed to
  88239. * FLAC__stream_encoder_init*_stream(). The supplied function will be called
  88240. * when the encoder needs to know the current position of the output stream.
  88241. *
  88242. * \warning
  88243. * The callback must return the true current byte offset of the output to
  88244. * which the encoder is writing. If you are buffering the output, make
  88245. * sure and take this into account. If you are writing directly to a
  88246. * FILE* from your write callback, ftell() is sufficient. If you are
  88247. * writing directly to a file descriptor from your write callback, you
  88248. * can use lseek(fd, SEEK_CUR, 0). The encoder may later seek back to
  88249. * these points to rewrite metadata after encoding.
  88250. *
  88251. * Here is an example of a tell callback for stdio streams:
  88252. * \code
  88253. * FLAC__StreamEncoderTellStatus tell_cb(const FLAC__StreamEncoder *encoder, FLAC__uint64 *absolute_byte_offset, void *client_data)
  88254. * {
  88255. * FILE *file = ((MyClientData*)client_data)->file;
  88256. * off_t pos;
  88257. * if(file == stdin)
  88258. * return FLAC__STREAM_ENCODER_TELL_STATUS_UNSUPPORTED;
  88259. * else if((pos = ftello(file)) < 0)
  88260. * return FLAC__STREAM_ENCODER_TELL_STATUS_ERROR;
  88261. * else {
  88262. * *absolute_byte_offset = (FLAC__uint64)pos;
  88263. * return FLAC__STREAM_ENCODER_TELL_STATUS_OK;
  88264. * }
  88265. * }
  88266. * \endcode
  88267. *
  88268. * \note In general, FLAC__StreamEncoder functions which change the
  88269. * state should not be called on the \a encoder while in the callback.
  88270. *
  88271. * \param encoder The encoder instance calling the callback.
  88272. * \param absolute_byte_offset The address at which to store the current
  88273. * position of the output.
  88274. * \param client_data The callee's client data set through
  88275. * FLAC__stream_encoder_init_*().
  88276. * \retval FLAC__StreamEncoderTellStatus
  88277. * The callee's return status.
  88278. */
  88279. typedef FLAC__StreamEncoderTellStatus (*FLAC__StreamEncoderTellCallback)(const FLAC__StreamEncoder *encoder, FLAC__uint64 *absolute_byte_offset, void *client_data);
  88280. /** Signature for the metadata callback.
  88281. *
  88282. * A function pointer matching this signature may be passed to
  88283. * FLAC__stream_encoder_init*_stream(). The supplied function will be called
  88284. * once at the end of encoding with the populated STREAMINFO structure. This
  88285. * is so the client can seek back to the beginning of the file and write the
  88286. * STREAMINFO block with the correct statistics after encoding (like
  88287. * minimum/maximum frame size and total samples).
  88288. *
  88289. * \note In general, FLAC__StreamEncoder functions which change the
  88290. * state should not be called on the \a encoder while in the callback.
  88291. *
  88292. * \param encoder The encoder instance calling the callback.
  88293. * \param metadata The final populated STREAMINFO block.
  88294. * \param client_data The callee's client data set through
  88295. * FLAC__stream_encoder_init_*().
  88296. */
  88297. typedef void (*FLAC__StreamEncoderMetadataCallback)(const FLAC__StreamEncoder *encoder, const FLAC__StreamMetadata *metadata, void *client_data);
  88298. /** Signature for the progress callback.
  88299. *
  88300. * A function pointer matching this signature may be passed to
  88301. * FLAC__stream_encoder_init*_file() or FLAC__stream_encoder_init*_FILE().
  88302. * The supplied function will be called when the encoder has finished
  88303. * writing a frame. The \c total_frames_estimate argument to the
  88304. * callback will be based on the value from
  88305. * FLAC__stream_encoder_set_total_samples_estimate().
  88306. *
  88307. * \note In general, FLAC__StreamEncoder functions which change the
  88308. * state should not be called on the \a encoder while in the callback.
  88309. *
  88310. * \param encoder The encoder instance calling the callback.
  88311. * \param bytes_written Bytes written so far.
  88312. * \param samples_written Samples written so far.
  88313. * \param frames_written Frames written so far.
  88314. * \param total_frames_estimate The estimate of the total number of
  88315. * frames to be written.
  88316. * \param client_data The callee's client data set through
  88317. * FLAC__stream_encoder_init_*().
  88318. */
  88319. 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);
  88320. /***********************************************************************
  88321. *
  88322. * Class constructor/destructor
  88323. *
  88324. ***********************************************************************/
  88325. /** Create a new stream encoder instance. The instance is created with
  88326. * default settings; see the individual FLAC__stream_encoder_set_*()
  88327. * functions for each setting's default.
  88328. *
  88329. * \retval FLAC__StreamEncoder*
  88330. * \c NULL if there was an error allocating memory, else the new instance.
  88331. */
  88332. FLAC_API FLAC__StreamEncoder *FLAC__stream_encoder_new(void);
  88333. /** Free an encoder instance. Deletes the object pointed to by \a encoder.
  88334. *
  88335. * \param encoder A pointer to an existing encoder.
  88336. * \assert
  88337. * \code encoder != NULL \endcode
  88338. */
  88339. FLAC_API void FLAC__stream_encoder_delete(FLAC__StreamEncoder *encoder);
  88340. /***********************************************************************
  88341. *
  88342. * Public class method prototypes
  88343. *
  88344. ***********************************************************************/
  88345. /** Set the serial number for the FLAC stream to use in the Ogg container.
  88346. *
  88347. * \note
  88348. * This does not need to be set for native FLAC encoding.
  88349. *
  88350. * \note
  88351. * It is recommended to set a serial number explicitly as the default of '0'
  88352. * may collide with other streams.
  88353. *
  88354. * \default \c 0
  88355. * \param encoder An encoder instance to set.
  88356. * \param serial_number See above.
  88357. * \assert
  88358. * \code encoder != NULL \endcode
  88359. * \retval FLAC__bool
  88360. * \c false if the encoder is already initialized, else \c true.
  88361. */
  88362. FLAC_API FLAC__bool FLAC__stream_encoder_set_ogg_serial_number(FLAC__StreamEncoder *encoder, long serial_number);
  88363. /** Set the "verify" flag. If \c true, the encoder will verify it's own
  88364. * encoded output by feeding it through an internal decoder and comparing
  88365. * the original signal against the decoded signal. If a mismatch occurs,
  88366. * the process call will return \c false. Note that this will slow the
  88367. * encoding process by the extra time required for decoding and comparison.
  88368. *
  88369. * \default \c false
  88370. * \param encoder An encoder instance to set.
  88371. * \param value Flag value (see above).
  88372. * \assert
  88373. * \code encoder != NULL \endcode
  88374. * \retval FLAC__bool
  88375. * \c false if the encoder is already initialized, else \c true.
  88376. */
  88377. FLAC_API FLAC__bool FLAC__stream_encoder_set_verify(FLAC__StreamEncoder *encoder, FLAC__bool value);
  88378. /** Set the <A HREF="../format.html#subset">Subset</A> flag. If \c true,
  88379. * the encoder will comply with the Subset and will check the
  88380. * settings during FLAC__stream_encoder_init_*() to see if all settings
  88381. * comply. If \c false, the settings may take advantage of the full
  88382. * range that the format allows.
  88383. *
  88384. * Make sure you know what it entails before setting this to \c false.
  88385. *
  88386. * \default \c true
  88387. * \param encoder An encoder instance to set.
  88388. * \param value Flag value (see above).
  88389. * \assert
  88390. * \code encoder != NULL \endcode
  88391. * \retval FLAC__bool
  88392. * \c false if the encoder is already initialized, else \c true.
  88393. */
  88394. FLAC_API FLAC__bool FLAC__stream_encoder_set_streamable_subset(FLAC__StreamEncoder *encoder, FLAC__bool value);
  88395. /** Set the number of channels to be encoded.
  88396. *
  88397. * \default \c 2
  88398. * \param encoder An encoder instance to set.
  88399. * \param value See above.
  88400. * \assert
  88401. * \code encoder != NULL \endcode
  88402. * \retval FLAC__bool
  88403. * \c false if the encoder is already initialized, else \c true.
  88404. */
  88405. FLAC_API FLAC__bool FLAC__stream_encoder_set_channels(FLAC__StreamEncoder *encoder, unsigned value);
  88406. /** Set the sample resolution of the input to be encoded.
  88407. *
  88408. * \warning
  88409. * Do not feed the encoder data that is wider than the value you
  88410. * set here or you will generate an invalid stream.
  88411. *
  88412. * \default \c 16
  88413. * \param encoder An encoder instance to set.
  88414. * \param value See above.
  88415. * \assert
  88416. * \code encoder != NULL \endcode
  88417. * \retval FLAC__bool
  88418. * \c false if the encoder is already initialized, else \c true.
  88419. */
  88420. FLAC_API FLAC__bool FLAC__stream_encoder_set_bits_per_sample(FLAC__StreamEncoder *encoder, unsigned value);
  88421. /** Set the sample rate (in Hz) of the input to be encoded.
  88422. *
  88423. * \default \c 44100
  88424. * \param encoder An encoder instance to set.
  88425. * \param value See above.
  88426. * \assert
  88427. * \code encoder != NULL \endcode
  88428. * \retval FLAC__bool
  88429. * \c false if the encoder is already initialized, else \c true.
  88430. */
  88431. FLAC_API FLAC__bool FLAC__stream_encoder_set_sample_rate(FLAC__StreamEncoder *encoder, unsigned value);
  88432. /** Set the compression level
  88433. *
  88434. * The compression level is roughly proportional to the amount of effort
  88435. * the encoder expends to compress the file. A higher level usually
  88436. * means more computation but higher compression. The default level is
  88437. * suitable for most applications.
  88438. *
  88439. * Currently the levels range from \c 0 (fastest, least compression) to
  88440. * \c 8 (slowest, most compression). A value larger than \c 8 will be
  88441. * treated as \c 8.
  88442. *
  88443. * This function automatically calls the following other \c _set_
  88444. * functions with appropriate values, so the client does not need to
  88445. * unless it specifically wants to override them:
  88446. * - FLAC__stream_encoder_set_do_mid_side_stereo()
  88447. * - FLAC__stream_encoder_set_loose_mid_side_stereo()
  88448. * - FLAC__stream_encoder_set_apodization()
  88449. * - FLAC__stream_encoder_set_max_lpc_order()
  88450. * - FLAC__stream_encoder_set_qlp_coeff_precision()
  88451. * - FLAC__stream_encoder_set_do_qlp_coeff_prec_search()
  88452. * - FLAC__stream_encoder_set_do_escape_coding()
  88453. * - FLAC__stream_encoder_set_do_exhaustive_model_search()
  88454. * - FLAC__stream_encoder_set_min_residual_partition_order()
  88455. * - FLAC__stream_encoder_set_max_residual_partition_order()
  88456. * - FLAC__stream_encoder_set_rice_parameter_search_dist()
  88457. *
  88458. * The actual values set for each level are:
  88459. * <table>
  88460. * <tr>
  88461. * <td><b>level</b><td>
  88462. * <td>do mid-side stereo<td>
  88463. * <td>loose mid-side stereo<td>
  88464. * <td>apodization<td>
  88465. * <td>max lpc order<td>
  88466. * <td>qlp coeff precision<td>
  88467. * <td>qlp coeff prec search<td>
  88468. * <td>escape coding<td>
  88469. * <td>exhaustive model search<td>
  88470. * <td>min residual partition order<td>
  88471. * <td>max residual partition order<td>
  88472. * <td>rice parameter search dist<td>
  88473. * </tr>
  88474. * <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>
  88475. * <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>
  88476. * <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>
  88477. * <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>
  88478. * <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>
  88479. * <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>
  88480. * <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>
  88481. * <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>
  88482. * <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>
  88483. * </table>
  88484. *
  88485. * \default \c 5
  88486. * \param encoder An encoder instance to set.
  88487. * \param value See above.
  88488. * \assert
  88489. * \code encoder != NULL \endcode
  88490. * \retval FLAC__bool
  88491. * \c false if the encoder is already initialized, else \c true.
  88492. */
  88493. FLAC_API FLAC__bool FLAC__stream_encoder_set_compression_level(FLAC__StreamEncoder *encoder, unsigned value);
  88494. /** Set the blocksize to use while encoding.
  88495. *
  88496. * The number of samples to use per frame. Use \c 0 to let the encoder
  88497. * estimate a blocksize; this is usually best.
  88498. *
  88499. * \default \c 0
  88500. * \param encoder An encoder instance to set.
  88501. * \param value See above.
  88502. * \assert
  88503. * \code encoder != NULL \endcode
  88504. * \retval FLAC__bool
  88505. * \c false if the encoder is already initialized, else \c true.
  88506. */
  88507. FLAC_API FLAC__bool FLAC__stream_encoder_set_blocksize(FLAC__StreamEncoder *encoder, unsigned value);
  88508. /** Set to \c true to enable mid-side encoding on stereo input. The
  88509. * number of channels must be 2 for this to have any effect. Set to
  88510. * \c false to use only independent channel coding.
  88511. *
  88512. * \default \c false
  88513. * \param encoder An encoder instance to set.
  88514. * \param value Flag value (see above).
  88515. * \assert
  88516. * \code encoder != NULL \endcode
  88517. * \retval FLAC__bool
  88518. * \c false if the encoder is already initialized, else \c true.
  88519. */
  88520. FLAC_API FLAC__bool FLAC__stream_encoder_set_do_mid_side_stereo(FLAC__StreamEncoder *encoder, FLAC__bool value);
  88521. /** Set to \c true to enable adaptive switching between mid-side and
  88522. * left-right encoding on stereo input. Set to \c false to use
  88523. * exhaustive searching. Setting this to \c true requires
  88524. * FLAC__stream_encoder_set_do_mid_side_stereo() to also be set to
  88525. * \c true in order to have any effect.
  88526. *
  88527. * \default \c false
  88528. * \param encoder An encoder instance to set.
  88529. * \param value Flag value (see above).
  88530. * \assert
  88531. * \code encoder != NULL \endcode
  88532. * \retval FLAC__bool
  88533. * \c false if the encoder is already initialized, else \c true.
  88534. */
  88535. FLAC_API FLAC__bool FLAC__stream_encoder_set_loose_mid_side_stereo(FLAC__StreamEncoder *encoder, FLAC__bool value);
  88536. /** Sets the apodization function(s) the encoder will use when windowing
  88537. * audio data for LPC analysis.
  88538. *
  88539. * The \a specification is a plain ASCII string which specifies exactly
  88540. * which functions to use. There may be more than one (up to 32),
  88541. * separated by \c ';' characters. Some functions take one or more
  88542. * comma-separated arguments in parentheses.
  88543. *
  88544. * The available functions are \c bartlett, \c bartlett_hann,
  88545. * \c blackman, \c blackman_harris_4term_92db, \c connes, \c flattop,
  88546. * \c gauss(STDDEV), \c hamming, \c hann, \c kaiser_bessel, \c nuttall,
  88547. * \c rectangle, \c triangle, \c tukey(P), \c welch.
  88548. *
  88549. * For \c gauss(STDDEV), STDDEV specifies the standard deviation
  88550. * (0<STDDEV<=0.5).
  88551. *
  88552. * For \c tukey(P), P specifies the fraction of the window that is
  88553. * tapered (0<=P<=1). P=0 corresponds to \c rectangle and P=1
  88554. * corresponds to \c hann.
  88555. *
  88556. * Example specifications are \c "blackman" or
  88557. * \c "hann;triangle;tukey(0.5);tukey(0.25);tukey(0.125)"
  88558. *
  88559. * Any function that is specified erroneously is silently dropped. Up
  88560. * to 32 functions are kept, the rest are dropped. If the specification
  88561. * is empty the encoder defaults to \c "tukey(0.5)".
  88562. *
  88563. * When more than one function is specified, then for every subframe the
  88564. * encoder will try each of them separately and choose the window that
  88565. * results in the smallest compressed subframe.
  88566. *
  88567. * Note that each function specified causes the encoder to occupy a
  88568. * floating point array in which to store the window.
  88569. *
  88570. * \default \c "tukey(0.5)"
  88571. * \param encoder An encoder instance to set.
  88572. * \param specification See above.
  88573. * \assert
  88574. * \code encoder != NULL \endcode
  88575. * \code specification != NULL \endcode
  88576. * \retval FLAC__bool
  88577. * \c false if the encoder is already initialized, else \c true.
  88578. */
  88579. FLAC_API FLAC__bool FLAC__stream_encoder_set_apodization(FLAC__StreamEncoder *encoder, const char *specification);
  88580. /** Set the maximum LPC order, or \c 0 to use only the fixed predictors.
  88581. *
  88582. * \default \c 0
  88583. * \param encoder An encoder instance to set.
  88584. * \param value See above.
  88585. * \assert
  88586. * \code encoder != NULL \endcode
  88587. * \retval FLAC__bool
  88588. * \c false if the encoder is already initialized, else \c true.
  88589. */
  88590. FLAC_API FLAC__bool FLAC__stream_encoder_set_max_lpc_order(FLAC__StreamEncoder *encoder, unsigned value);
  88591. /** Set the precision, in bits, of the quantized linear predictor
  88592. * coefficients, or \c 0 to let the encoder select it based on the
  88593. * blocksize.
  88594. *
  88595. * \note
  88596. * In the current implementation, qlp_coeff_precision + bits_per_sample must
  88597. * be less than 32.
  88598. *
  88599. * \default \c 0
  88600. * \param encoder An encoder instance to set.
  88601. * \param value See above.
  88602. * \assert
  88603. * \code encoder != NULL \endcode
  88604. * \retval FLAC__bool
  88605. * \c false if the encoder is already initialized, else \c true.
  88606. */
  88607. FLAC_API FLAC__bool FLAC__stream_encoder_set_qlp_coeff_precision(FLAC__StreamEncoder *encoder, unsigned value);
  88608. /** Set to \c false to use only the specified quantized linear predictor
  88609. * coefficient precision, or \c true to search neighboring precision
  88610. * values and use the best one.
  88611. *
  88612. * \default \c false
  88613. * \param encoder An encoder instance to set.
  88614. * \param value See above.
  88615. * \assert
  88616. * \code encoder != NULL \endcode
  88617. * \retval FLAC__bool
  88618. * \c false if the encoder is already initialized, else \c true.
  88619. */
  88620. FLAC_API FLAC__bool FLAC__stream_encoder_set_do_qlp_coeff_prec_search(FLAC__StreamEncoder *encoder, FLAC__bool value);
  88621. /** Deprecated. Setting this value has no effect.
  88622. *
  88623. * \default \c false
  88624. * \param encoder An encoder instance to set.
  88625. * \param value See above.
  88626. * \assert
  88627. * \code encoder != NULL \endcode
  88628. * \retval FLAC__bool
  88629. * \c false if the encoder is already initialized, else \c true.
  88630. */
  88631. FLAC_API FLAC__bool FLAC__stream_encoder_set_do_escape_coding(FLAC__StreamEncoder *encoder, FLAC__bool value);
  88632. /** Set to \c false to let the encoder estimate the best model order
  88633. * based on the residual signal energy, or \c true to force the
  88634. * encoder to evaluate all order models and select the best.
  88635. *
  88636. * \default \c false
  88637. * \param encoder An encoder instance to set.
  88638. * \param value See above.
  88639. * \assert
  88640. * \code encoder != NULL \endcode
  88641. * \retval FLAC__bool
  88642. * \c false if the encoder is already initialized, else \c true.
  88643. */
  88644. FLAC_API FLAC__bool FLAC__stream_encoder_set_do_exhaustive_model_search(FLAC__StreamEncoder *encoder, FLAC__bool value);
  88645. /** Set the minimum partition order to search when coding the residual.
  88646. * This is used in tandem with
  88647. * FLAC__stream_encoder_set_max_residual_partition_order().
  88648. *
  88649. * The partition order determines the context size in the residual.
  88650. * The context size will be approximately <tt>blocksize / (2 ^ order)</tt>.
  88651. *
  88652. * Set both min and max values to \c 0 to force a single context,
  88653. * whose Rice parameter is based on the residual signal variance.
  88654. * Otherwise, set a min and max order, and the encoder will search
  88655. * all orders, using the mean of each context for its Rice parameter,
  88656. * and use the best.
  88657. *
  88658. * \default \c 0
  88659. * \param encoder An encoder instance to set.
  88660. * \param value See above.
  88661. * \assert
  88662. * \code encoder != NULL \endcode
  88663. * \retval FLAC__bool
  88664. * \c false if the encoder is already initialized, else \c true.
  88665. */
  88666. FLAC_API FLAC__bool FLAC__stream_encoder_set_min_residual_partition_order(FLAC__StreamEncoder *encoder, unsigned value);
  88667. /** Set the maximum partition order to search when coding the residual.
  88668. * This is used in tandem with
  88669. * FLAC__stream_encoder_set_min_residual_partition_order().
  88670. *
  88671. * The partition order determines the context size in the residual.
  88672. * The context size will be approximately <tt>blocksize / (2 ^ order)</tt>.
  88673. *
  88674. * Set both min and max values to \c 0 to force a single context,
  88675. * whose Rice parameter is based on the residual signal variance.
  88676. * Otherwise, set a min and max order, and the encoder will search
  88677. * all orders, using the mean of each context for its Rice parameter,
  88678. * and use the best.
  88679. *
  88680. * \default \c 0
  88681. * \param encoder An encoder instance to set.
  88682. * \param value See above.
  88683. * \assert
  88684. * \code encoder != NULL \endcode
  88685. * \retval FLAC__bool
  88686. * \c false if the encoder is already initialized, else \c true.
  88687. */
  88688. FLAC_API FLAC__bool FLAC__stream_encoder_set_max_residual_partition_order(FLAC__StreamEncoder *encoder, unsigned value);
  88689. /** Deprecated. Setting this value has no effect.
  88690. *
  88691. * \default \c 0
  88692. * \param encoder An encoder instance to set.
  88693. * \param value See above.
  88694. * \assert
  88695. * \code encoder != NULL \endcode
  88696. * \retval FLAC__bool
  88697. * \c false if the encoder is already initialized, else \c true.
  88698. */
  88699. FLAC_API FLAC__bool FLAC__stream_encoder_set_rice_parameter_search_dist(FLAC__StreamEncoder *encoder, unsigned value);
  88700. /** Set an estimate of the total samples that will be encoded.
  88701. * This is merely an estimate and may be set to \c 0 if unknown.
  88702. * This value will be written to the STREAMINFO block before encoding,
  88703. * and can remove the need for the caller to rewrite the value later
  88704. * if the value is known before encoding.
  88705. *
  88706. * \default \c 0
  88707. * \param encoder An encoder instance to set.
  88708. * \param value See above.
  88709. * \assert
  88710. * \code encoder != NULL \endcode
  88711. * \retval FLAC__bool
  88712. * \c false if the encoder is already initialized, else \c true.
  88713. */
  88714. FLAC_API FLAC__bool FLAC__stream_encoder_set_total_samples_estimate(FLAC__StreamEncoder *encoder, FLAC__uint64 value);
  88715. /** Set the metadata blocks to be emitted to the stream before encoding.
  88716. * A value of \c NULL, \c 0 implies no metadata; otherwise, supply an
  88717. * array of pointers to metadata blocks. The array is non-const since
  88718. * the encoder may need to change the \a is_last flag inside them, and
  88719. * in some cases update seek point offsets. Otherwise, the encoder will
  88720. * not modify or free the blocks. It is up to the caller to free the
  88721. * metadata blocks after encoding finishes.
  88722. *
  88723. * \note
  88724. * The encoder stores only copies of the pointers in the \a metadata array;
  88725. * the metadata blocks themselves must survive at least until after
  88726. * FLAC__stream_encoder_finish() returns. Do not free the blocks until then.
  88727. *
  88728. * \note
  88729. * The STREAMINFO block is always written and no STREAMINFO block may
  88730. * occur in the supplied array.
  88731. *
  88732. * \note
  88733. * By default the encoder does not create a SEEKTABLE. If one is supplied
  88734. * in the \a metadata array, but the client has specified that it does not
  88735. * support seeking, then the SEEKTABLE will be written verbatim. However
  88736. * by itself this is not very useful as the client will not know the stream
  88737. * offsets for the seekpoints ahead of time. In order to get a proper
  88738. * seektable the client must support seeking. See next note.
  88739. *
  88740. * \note
  88741. * SEEKTABLE blocks are handled specially. Since you will not know
  88742. * the values for the seek point stream offsets, you should pass in
  88743. * a SEEKTABLE 'template', that is, a SEEKTABLE object with the
  88744. * required sample numbers (or placeholder points), with \c 0 for the
  88745. * \a frame_samples and \a stream_offset fields for each point. If the
  88746. * client has specified that it supports seeking by providing a seek
  88747. * callback to FLAC__stream_encoder_init_stream() or both seek AND read
  88748. * callback to FLAC__stream_encoder_init_ogg_stream() (or by using
  88749. * FLAC__stream_encoder_init*_file() or FLAC__stream_encoder_init*_FILE()),
  88750. * then while it is encoding the encoder will fill the stream offsets in
  88751. * for you and when encoding is finished, it will seek back and write the
  88752. * real values into the SEEKTABLE block in the stream. There are helper
  88753. * routines for manipulating seektable template blocks; see metadata.h:
  88754. * FLAC__metadata_object_seektable_template_*(). If the client does
  88755. * not support seeking, the SEEKTABLE will have inaccurate offsets which
  88756. * will slow down or remove the ability to seek in the FLAC stream.
  88757. *
  88758. * \note
  88759. * The encoder instance \b will modify the first \c SEEKTABLE block
  88760. * as it transforms the template to a valid seektable while encoding,
  88761. * but it is still up to the caller to free all metadata blocks after
  88762. * encoding.
  88763. *
  88764. * \note
  88765. * A VORBIS_COMMENT block may be supplied. The vendor string in it
  88766. * will be ignored. libFLAC will use it's own vendor string. libFLAC
  88767. * will not modify the passed-in VORBIS_COMMENT's vendor string, it
  88768. * will simply write it's own into the stream. If no VORBIS_COMMENT
  88769. * block is present in the \a metadata array, libFLAC will write an
  88770. * empty one, containing only the vendor string.
  88771. *
  88772. * \note The Ogg FLAC mapping requires that the VORBIS_COMMENT block be
  88773. * the second metadata block of the stream. The encoder already supplies
  88774. * the STREAMINFO block automatically. If \a metadata does not contain a
  88775. * VORBIS_COMMENT block, the encoder will supply that too. Otherwise, if
  88776. * \a metadata does contain a VORBIS_COMMENT block and it is not the
  88777. * first, the init function will reorder \a metadata by moving the
  88778. * VORBIS_COMMENT block to the front; the relative ordering of the other
  88779. * blocks will remain as they were.
  88780. *
  88781. * \note The Ogg FLAC mapping limits the number of metadata blocks per
  88782. * stream to \c 65535. If \a num_blocks exceeds this the function will
  88783. * return \c false.
  88784. *
  88785. * \default \c NULL, 0
  88786. * \param encoder An encoder instance to set.
  88787. * \param metadata See above.
  88788. * \param num_blocks See above.
  88789. * \assert
  88790. * \code encoder != NULL \endcode
  88791. * \retval FLAC__bool
  88792. * \c false if the encoder is already initialized, else \c true.
  88793. * \c false if the encoder is already initialized, or if
  88794. * \a num_blocks > 65535 if encoding to Ogg FLAC, else \c true.
  88795. */
  88796. FLAC_API FLAC__bool FLAC__stream_encoder_set_metadata(FLAC__StreamEncoder *encoder, FLAC__StreamMetadata **metadata, unsigned num_blocks);
  88797. /** Get the current encoder state.
  88798. *
  88799. * \param encoder An encoder instance to query.
  88800. * \assert
  88801. * \code encoder != NULL \endcode
  88802. * \retval FLAC__StreamEncoderState
  88803. * The current encoder state.
  88804. */
  88805. FLAC_API FLAC__StreamEncoderState FLAC__stream_encoder_get_state(const FLAC__StreamEncoder *encoder);
  88806. /** Get the state of the verify stream decoder.
  88807. * Useful when the stream encoder state is
  88808. * \c FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR.
  88809. *
  88810. * \param encoder An encoder instance to query.
  88811. * \assert
  88812. * \code encoder != NULL \endcode
  88813. * \retval FLAC__StreamDecoderState
  88814. * The verify stream decoder state.
  88815. */
  88816. FLAC_API FLAC__StreamDecoderState FLAC__stream_encoder_get_verify_decoder_state(const FLAC__StreamEncoder *encoder);
  88817. /** Get the current encoder state as a C string.
  88818. * This version automatically resolves
  88819. * \c FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR by getting the
  88820. * verify decoder's state.
  88821. *
  88822. * \param encoder A encoder instance to query.
  88823. * \assert
  88824. * \code encoder != NULL \endcode
  88825. * \retval const char *
  88826. * The encoder state as a C string. Do not modify the contents.
  88827. */
  88828. FLAC_API const char *FLAC__stream_encoder_get_resolved_state_string(const FLAC__StreamEncoder *encoder);
  88829. /** Get relevant values about the nature of a verify decoder error.
  88830. * Useful when the stream encoder state is
  88831. * \c FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR. The arguments should
  88832. * be addresses in which the stats will be returned, or NULL if value
  88833. * is not desired.
  88834. *
  88835. * \param encoder An encoder instance to query.
  88836. * \param absolute_sample The absolute sample number of the mismatch.
  88837. * \param frame_number The number of the frame in which the mismatch occurred.
  88838. * \param channel The channel in which the mismatch occurred.
  88839. * \param sample The number of the sample (relative to the frame) in
  88840. * which the mismatch occurred.
  88841. * \param expected The expected value for the sample in question.
  88842. * \param got The actual value returned by the decoder.
  88843. * \assert
  88844. * \code encoder != NULL \endcode
  88845. */
  88846. 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);
  88847. /** Get the "verify" flag.
  88848. *
  88849. * \param encoder An encoder instance to query.
  88850. * \assert
  88851. * \code encoder != NULL \endcode
  88852. * \retval FLAC__bool
  88853. * See FLAC__stream_encoder_set_verify().
  88854. */
  88855. FLAC_API FLAC__bool FLAC__stream_encoder_get_verify(const FLAC__StreamEncoder *encoder);
  88856. /** Get the <A HREF="../format.html#subset>Subset</A> flag.
  88857. *
  88858. * \param encoder An encoder instance to query.
  88859. * \assert
  88860. * \code encoder != NULL \endcode
  88861. * \retval FLAC__bool
  88862. * See FLAC__stream_encoder_set_streamable_subset().
  88863. */
  88864. FLAC_API FLAC__bool FLAC__stream_encoder_get_streamable_subset(const FLAC__StreamEncoder *encoder);
  88865. /** Get the number of input channels being processed.
  88866. *
  88867. * \param encoder An encoder instance to query.
  88868. * \assert
  88869. * \code encoder != NULL \endcode
  88870. * \retval unsigned
  88871. * See FLAC__stream_encoder_set_channels().
  88872. */
  88873. FLAC_API unsigned FLAC__stream_encoder_get_channels(const FLAC__StreamEncoder *encoder);
  88874. /** Get the input sample resolution setting.
  88875. *
  88876. * \param encoder An encoder instance to query.
  88877. * \assert
  88878. * \code encoder != NULL \endcode
  88879. * \retval unsigned
  88880. * See FLAC__stream_encoder_set_bits_per_sample().
  88881. */
  88882. FLAC_API unsigned FLAC__stream_encoder_get_bits_per_sample(const FLAC__StreamEncoder *encoder);
  88883. /** Get the input sample rate setting.
  88884. *
  88885. * \param encoder An encoder instance to query.
  88886. * \assert
  88887. * \code encoder != NULL \endcode
  88888. * \retval unsigned
  88889. * See FLAC__stream_encoder_set_sample_rate().
  88890. */
  88891. FLAC_API unsigned FLAC__stream_encoder_get_sample_rate(const FLAC__StreamEncoder *encoder);
  88892. /** Get the blocksize setting.
  88893. *
  88894. * \param encoder An encoder instance to query.
  88895. * \assert
  88896. * \code encoder != NULL \endcode
  88897. * \retval unsigned
  88898. * See FLAC__stream_encoder_set_blocksize().
  88899. */
  88900. FLAC_API unsigned FLAC__stream_encoder_get_blocksize(const FLAC__StreamEncoder *encoder);
  88901. /** Get the "mid/side stereo coding" flag.
  88902. *
  88903. * \param encoder An encoder instance to query.
  88904. * \assert
  88905. * \code encoder != NULL \endcode
  88906. * \retval FLAC__bool
  88907. * See FLAC__stream_encoder_get_do_mid_side_stereo().
  88908. */
  88909. FLAC_API FLAC__bool FLAC__stream_encoder_get_do_mid_side_stereo(const FLAC__StreamEncoder *encoder);
  88910. /** Get the "adaptive mid/side switching" flag.
  88911. *
  88912. * \param encoder An encoder instance to query.
  88913. * \assert
  88914. * \code encoder != NULL \endcode
  88915. * \retval FLAC__bool
  88916. * See FLAC__stream_encoder_set_loose_mid_side_stereo().
  88917. */
  88918. FLAC_API FLAC__bool FLAC__stream_encoder_get_loose_mid_side_stereo(const FLAC__StreamEncoder *encoder);
  88919. /** Get the maximum LPC order setting.
  88920. *
  88921. * \param encoder An encoder instance to query.
  88922. * \assert
  88923. * \code encoder != NULL \endcode
  88924. * \retval unsigned
  88925. * See FLAC__stream_encoder_set_max_lpc_order().
  88926. */
  88927. FLAC_API unsigned FLAC__stream_encoder_get_max_lpc_order(const FLAC__StreamEncoder *encoder);
  88928. /** Get the quantized linear predictor coefficient precision setting.
  88929. *
  88930. * \param encoder An encoder instance to query.
  88931. * \assert
  88932. * \code encoder != NULL \endcode
  88933. * \retval unsigned
  88934. * See FLAC__stream_encoder_set_qlp_coeff_precision().
  88935. */
  88936. FLAC_API unsigned FLAC__stream_encoder_get_qlp_coeff_precision(const FLAC__StreamEncoder *encoder);
  88937. /** Get the qlp coefficient precision search flag.
  88938. *
  88939. * \param encoder An encoder instance to query.
  88940. * \assert
  88941. * \code encoder != NULL \endcode
  88942. * \retval FLAC__bool
  88943. * See FLAC__stream_encoder_set_do_qlp_coeff_prec_search().
  88944. */
  88945. FLAC_API FLAC__bool FLAC__stream_encoder_get_do_qlp_coeff_prec_search(const FLAC__StreamEncoder *encoder);
  88946. /** Get the "escape coding" flag.
  88947. *
  88948. * \param encoder An encoder instance to query.
  88949. * \assert
  88950. * \code encoder != NULL \endcode
  88951. * \retval FLAC__bool
  88952. * See FLAC__stream_encoder_set_do_escape_coding().
  88953. */
  88954. FLAC_API FLAC__bool FLAC__stream_encoder_get_do_escape_coding(const FLAC__StreamEncoder *encoder);
  88955. /** Get the exhaustive model search flag.
  88956. *
  88957. * \param encoder An encoder instance to query.
  88958. * \assert
  88959. * \code encoder != NULL \endcode
  88960. * \retval FLAC__bool
  88961. * See FLAC__stream_encoder_set_do_exhaustive_model_search().
  88962. */
  88963. FLAC_API FLAC__bool FLAC__stream_encoder_get_do_exhaustive_model_search(const FLAC__StreamEncoder *encoder);
  88964. /** Get the minimum residual partition order setting.
  88965. *
  88966. * \param encoder An encoder instance to query.
  88967. * \assert
  88968. * \code encoder != NULL \endcode
  88969. * \retval unsigned
  88970. * See FLAC__stream_encoder_set_min_residual_partition_order().
  88971. */
  88972. FLAC_API unsigned FLAC__stream_encoder_get_min_residual_partition_order(const FLAC__StreamEncoder *encoder);
  88973. /** Get maximum residual partition order setting.
  88974. *
  88975. * \param encoder An encoder instance to query.
  88976. * \assert
  88977. * \code encoder != NULL \endcode
  88978. * \retval unsigned
  88979. * See FLAC__stream_encoder_set_max_residual_partition_order().
  88980. */
  88981. FLAC_API unsigned FLAC__stream_encoder_get_max_residual_partition_order(const FLAC__StreamEncoder *encoder);
  88982. /** Get the Rice parameter search distance setting.
  88983. *
  88984. * \param encoder An encoder instance to query.
  88985. * \assert
  88986. * \code encoder != NULL \endcode
  88987. * \retval unsigned
  88988. * See FLAC__stream_encoder_set_rice_parameter_search_dist().
  88989. */
  88990. FLAC_API unsigned FLAC__stream_encoder_get_rice_parameter_search_dist(const FLAC__StreamEncoder *encoder);
  88991. /** Get the previously set estimate of the total samples to be encoded.
  88992. * The encoder merely mimics back the value given to
  88993. * FLAC__stream_encoder_set_total_samples_estimate() since it has no
  88994. * other way of knowing how many samples the client will encode.
  88995. *
  88996. * \param encoder An encoder instance to set.
  88997. * \assert
  88998. * \code encoder != NULL \endcode
  88999. * \retval FLAC__uint64
  89000. * See FLAC__stream_encoder_get_total_samples_estimate().
  89001. */
  89002. FLAC_API FLAC__uint64 FLAC__stream_encoder_get_total_samples_estimate(const FLAC__StreamEncoder *encoder);
  89003. /** Initialize the encoder instance to encode native FLAC streams.
  89004. *
  89005. * This flavor of initialization sets up the encoder to encode to a
  89006. * native FLAC stream. I/O is performed via callbacks to the client.
  89007. * For encoding to a plain file via filename or open \c FILE*,
  89008. * FLAC__stream_encoder_init_file() and FLAC__stream_encoder_init_FILE()
  89009. * provide a simpler interface.
  89010. *
  89011. * This function should be called after FLAC__stream_encoder_new() and
  89012. * FLAC__stream_encoder_set_*() but before FLAC__stream_encoder_process()
  89013. * or FLAC__stream_encoder_process_interleaved().
  89014. * initialization succeeded.
  89015. *
  89016. * The call to FLAC__stream_encoder_init_stream() currently will also
  89017. * immediately call the write callback several times, once with the \c fLaC
  89018. * signature, and once for each encoded metadata block.
  89019. *
  89020. * \param encoder An uninitialized encoder instance.
  89021. * \param write_callback See FLAC__StreamEncoderWriteCallback. This
  89022. * pointer must not be \c NULL.
  89023. * \param seek_callback See FLAC__StreamEncoderSeekCallback. This
  89024. * pointer may be \c NULL if seeking is not
  89025. * supported. The encoder uses seeking to go back
  89026. * and write some some stream statistics to the
  89027. * STREAMINFO block; this is recommended but not
  89028. * necessary to create a valid FLAC stream. If
  89029. * \a seek_callback is not \c NULL then a
  89030. * \a tell_callback must also be supplied.
  89031. * Alternatively, a dummy seek callback that just
  89032. * returns \c FLAC__STREAM_ENCODER_SEEK_STATUS_UNSUPPORTED
  89033. * may also be supplied, all though this is slightly
  89034. * less efficient for the encoder.
  89035. * \param tell_callback See FLAC__StreamEncoderTellCallback. This
  89036. * pointer may be \c NULL if seeking is not
  89037. * supported. If \a seek_callback is \c NULL then
  89038. * this argument will be ignored. If
  89039. * \a seek_callback is not \c NULL then a
  89040. * \a tell_callback must also be supplied.
  89041. * Alternatively, a dummy tell callback that just
  89042. * returns \c FLAC__STREAM_ENCODER_TELL_STATUS_UNSUPPORTED
  89043. * may also be supplied, all though this is slightly
  89044. * less efficient for the encoder.
  89045. * \param metadata_callback See FLAC__StreamEncoderMetadataCallback. This
  89046. * pointer may be \c NULL if the callback is not
  89047. * desired. If the client provides a seek callback,
  89048. * this function is not necessary as the encoder
  89049. * will automatically seek back and update the
  89050. * STREAMINFO block. It may also be \c NULL if the
  89051. * client does not support seeking, since it will
  89052. * have no way of going back to update the
  89053. * STREAMINFO. However the client can still supply
  89054. * a callback if it would like to know the details
  89055. * from the STREAMINFO.
  89056. * \param client_data This value will be supplied to callbacks in their
  89057. * \a client_data argument.
  89058. * \assert
  89059. * \code encoder != NULL \endcode
  89060. * \retval FLAC__StreamEncoderInitStatus
  89061. * \c FLAC__STREAM_ENCODER_INIT_STATUS_OK if initialization was successful;
  89062. * see FLAC__StreamEncoderInitStatus for the meanings of other return values.
  89063. */
  89064. 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);
  89065. /** Initialize the encoder instance to encode Ogg FLAC streams.
  89066. *
  89067. * This flavor of initialization sets up the encoder to encode to a FLAC
  89068. * stream in an Ogg container. I/O is performed via callbacks to the
  89069. * client. For encoding to a plain file via filename or open \c FILE*,
  89070. * FLAC__stream_encoder_init_ogg_file() and FLAC__stream_encoder_init_ogg_FILE()
  89071. * provide a simpler interface.
  89072. *
  89073. * This function should be called after FLAC__stream_encoder_new() and
  89074. * FLAC__stream_encoder_set_*() but before FLAC__stream_encoder_process()
  89075. * or FLAC__stream_encoder_process_interleaved().
  89076. * initialization succeeded.
  89077. *
  89078. * The call to FLAC__stream_encoder_init_ogg_stream() currently will also
  89079. * immediately call the write callback several times to write the metadata
  89080. * packets.
  89081. *
  89082. * \param encoder An uninitialized encoder instance.
  89083. * \param read_callback See FLAC__StreamEncoderReadCallback. This
  89084. * pointer must not be \c NULL if \a seek_callback
  89085. * is non-NULL since they are both needed to be
  89086. * able to write data back to the Ogg FLAC stream
  89087. * in the post-encode phase.
  89088. * \param write_callback See FLAC__StreamEncoderWriteCallback. This
  89089. * pointer must not be \c NULL.
  89090. * \param seek_callback See FLAC__StreamEncoderSeekCallback. This
  89091. * pointer may be \c NULL if seeking is not
  89092. * supported. The encoder uses seeking to go back
  89093. * and write some some stream statistics to the
  89094. * STREAMINFO block; this is recommended but not
  89095. * necessary to create a valid FLAC stream. If
  89096. * \a seek_callback is not \c NULL then a
  89097. * \a tell_callback must also be supplied.
  89098. * Alternatively, a dummy seek callback that just
  89099. * returns \c FLAC__STREAM_ENCODER_SEEK_STATUS_UNSUPPORTED
  89100. * may also be supplied, all though this is slightly
  89101. * less efficient for the encoder.
  89102. * \param tell_callback See FLAC__StreamEncoderTellCallback. This
  89103. * pointer may be \c NULL if seeking is not
  89104. * supported. If \a seek_callback is \c NULL then
  89105. * this argument will be ignored. If
  89106. * \a seek_callback is not \c NULL then a
  89107. * \a tell_callback must also be supplied.
  89108. * Alternatively, a dummy tell callback that just
  89109. * returns \c FLAC__STREAM_ENCODER_TELL_STATUS_UNSUPPORTED
  89110. * may also be supplied, all though this is slightly
  89111. * less efficient for the encoder.
  89112. * \param metadata_callback See FLAC__StreamEncoderMetadataCallback. This
  89113. * pointer may be \c NULL if the callback is not
  89114. * desired. If the client provides a seek callback,
  89115. * this function is not necessary as the encoder
  89116. * will automatically seek back and update the
  89117. * STREAMINFO block. It may also be \c NULL if the
  89118. * client does not support seeking, since it will
  89119. * have no way of going back to update the
  89120. * STREAMINFO. However the client can still supply
  89121. * a callback if it would like to know the details
  89122. * from the STREAMINFO.
  89123. * \param client_data This value will be supplied to callbacks in their
  89124. * \a client_data argument.
  89125. * \assert
  89126. * \code encoder != NULL \endcode
  89127. * \retval FLAC__StreamEncoderInitStatus
  89128. * \c FLAC__STREAM_ENCODER_INIT_STATUS_OK if initialization was successful;
  89129. * see FLAC__StreamEncoderInitStatus for the meanings of other return values.
  89130. */
  89131. 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);
  89132. /** Initialize the encoder instance to encode native FLAC files.
  89133. *
  89134. * This flavor of initialization sets up the encoder to encode to a
  89135. * plain native FLAC file. For non-stdio streams, you must use
  89136. * FLAC__stream_encoder_init_stream() and provide callbacks for the I/O.
  89137. *
  89138. * This function should be called after FLAC__stream_encoder_new() and
  89139. * FLAC__stream_encoder_set_*() but before FLAC__stream_encoder_process()
  89140. * or FLAC__stream_encoder_process_interleaved().
  89141. * initialization succeeded.
  89142. *
  89143. * \param encoder An uninitialized encoder instance.
  89144. * \param file An open file. The file should have been opened
  89145. * with mode \c "w+b" and rewound. The file
  89146. * becomes owned by the encoder and should not be
  89147. * manipulated by the client while encoding.
  89148. * Unless \a file is \c stdout, it will be closed
  89149. * when FLAC__stream_encoder_finish() is called.
  89150. * Note however that a proper SEEKTABLE cannot be
  89151. * created when encoding to \c stdout since it is
  89152. * not seekable.
  89153. * \param progress_callback See FLAC__StreamEncoderProgressCallback. This
  89154. * pointer may be \c NULL if the callback is not
  89155. * desired.
  89156. * \param client_data This value will be supplied to callbacks in their
  89157. * \a client_data argument.
  89158. * \assert
  89159. * \code encoder != NULL \endcode
  89160. * \code file != NULL \endcode
  89161. * \retval FLAC__StreamEncoderInitStatus
  89162. * \c FLAC__STREAM_ENCODER_INIT_STATUS_OK if initialization was successful;
  89163. * see FLAC__StreamEncoderInitStatus for the meanings of other return values.
  89164. */
  89165. FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_FILE(FLAC__StreamEncoder *encoder, FILE *file, FLAC__StreamEncoderProgressCallback progress_callback, void *client_data);
  89166. /** Initialize the encoder instance to encode Ogg FLAC files.
  89167. *
  89168. * This flavor of initialization sets up the encoder to encode to a
  89169. * plain Ogg FLAC file. For non-stdio streams, you must use
  89170. * FLAC__stream_encoder_init_ogg_stream() and provide callbacks for the I/O.
  89171. *
  89172. * This function should be called after FLAC__stream_encoder_new() and
  89173. * FLAC__stream_encoder_set_*() but before FLAC__stream_encoder_process()
  89174. * or FLAC__stream_encoder_process_interleaved().
  89175. * initialization succeeded.
  89176. *
  89177. * \param encoder An uninitialized encoder instance.
  89178. * \param file An open file. The file should have been opened
  89179. * with mode \c "w+b" and rewound. The file
  89180. * becomes owned by the encoder and should not be
  89181. * manipulated by the client while encoding.
  89182. * Unless \a file is \c stdout, it will be closed
  89183. * when FLAC__stream_encoder_finish() is called.
  89184. * Note however that a proper SEEKTABLE cannot be
  89185. * created when encoding to \c stdout since it is
  89186. * not seekable.
  89187. * \param progress_callback See FLAC__StreamEncoderProgressCallback. This
  89188. * pointer may be \c NULL if the callback is not
  89189. * desired.
  89190. * \param client_data This value will be supplied to callbacks in their
  89191. * \a client_data argument.
  89192. * \assert
  89193. * \code encoder != NULL \endcode
  89194. * \code file != NULL \endcode
  89195. * \retval FLAC__StreamEncoderInitStatus
  89196. * \c FLAC__STREAM_ENCODER_INIT_STATUS_OK if initialization was successful;
  89197. * see FLAC__StreamEncoderInitStatus for the meanings of other return values.
  89198. */
  89199. FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_ogg_FILE(FLAC__StreamEncoder *encoder, FILE *file, FLAC__StreamEncoderProgressCallback progress_callback, void *client_data);
  89200. /** Initialize the encoder instance to encode native FLAC files.
  89201. *
  89202. * This flavor of initialization sets up the encoder to encode to a plain
  89203. * FLAC file. If POSIX fopen() semantics are not sufficient (for example,
  89204. * with Unicode filenames on Windows), you must use
  89205. * FLAC__stream_encoder_init_FILE(), or FLAC__stream_encoder_init_stream()
  89206. * and provide callbacks for the I/O.
  89207. *
  89208. * This function should be called after FLAC__stream_encoder_new() and
  89209. * FLAC__stream_encoder_set_*() but before FLAC__stream_encoder_process()
  89210. * or FLAC__stream_encoder_process_interleaved().
  89211. * initialization succeeded.
  89212. *
  89213. * \param encoder An uninitialized encoder instance.
  89214. * \param filename The name of the file to encode to. The file will
  89215. * be opened with fopen(). Use \c NULL to encode to
  89216. * \c stdout. Note however that a proper SEEKTABLE
  89217. * cannot be created when encoding to \c stdout since
  89218. * it is not seekable.
  89219. * \param progress_callback See FLAC__StreamEncoderProgressCallback. This
  89220. * pointer may be \c NULL if the callback is not
  89221. * desired.
  89222. * \param client_data This value will be supplied to callbacks in their
  89223. * \a client_data argument.
  89224. * \assert
  89225. * \code encoder != NULL \endcode
  89226. * \retval FLAC__StreamEncoderInitStatus
  89227. * \c FLAC__STREAM_ENCODER_INIT_STATUS_OK if initialization was successful;
  89228. * see FLAC__StreamEncoderInitStatus for the meanings of other return values.
  89229. */
  89230. FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_file(FLAC__StreamEncoder *encoder, const char *filename, FLAC__StreamEncoderProgressCallback progress_callback, void *client_data);
  89231. /** Initialize the encoder instance to encode Ogg FLAC files.
  89232. *
  89233. * This flavor of initialization sets up the encoder to encode to a plain
  89234. * Ogg FLAC file. If POSIX fopen() semantics are not sufficient (for example,
  89235. * with Unicode filenames on Windows), you must use
  89236. * FLAC__stream_encoder_init_ogg_FILE(), or FLAC__stream_encoder_init_ogg_stream()
  89237. * and provide callbacks for the I/O.
  89238. *
  89239. * This function should be called after FLAC__stream_encoder_new() and
  89240. * FLAC__stream_encoder_set_*() but before FLAC__stream_encoder_process()
  89241. * or FLAC__stream_encoder_process_interleaved().
  89242. * initialization succeeded.
  89243. *
  89244. * \param encoder An uninitialized encoder instance.
  89245. * \param filename The name of the file to encode to. The file will
  89246. * be opened with fopen(). Use \c NULL to encode to
  89247. * \c stdout. Note however that a proper SEEKTABLE
  89248. * cannot be created when encoding to \c stdout since
  89249. * it is not seekable.
  89250. * \param progress_callback See FLAC__StreamEncoderProgressCallback. This
  89251. * pointer may be \c NULL if the callback is not
  89252. * desired.
  89253. * \param client_data This value will be supplied to callbacks in their
  89254. * \a client_data argument.
  89255. * \assert
  89256. * \code encoder != NULL \endcode
  89257. * \retval FLAC__StreamEncoderInitStatus
  89258. * \c FLAC__STREAM_ENCODER_INIT_STATUS_OK if initialization was successful;
  89259. * see FLAC__StreamEncoderInitStatus for the meanings of other return values.
  89260. */
  89261. FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_ogg_file(FLAC__StreamEncoder *encoder, const char *filename, FLAC__StreamEncoderProgressCallback progress_callback, void *client_data);
  89262. /** Finish the encoding process.
  89263. * Flushes the encoding buffer, releases resources, resets the encoder
  89264. * settings to their defaults, and returns the encoder state to
  89265. * FLAC__STREAM_ENCODER_UNINITIALIZED. Note that this can generate
  89266. * one or more write callbacks before returning, and will generate
  89267. * a metadata callback.
  89268. *
  89269. * Note that in the course of processing the last frame, errors can
  89270. * occur, so the caller should be sure to check the return value to
  89271. * ensure the file was encoded properly.
  89272. *
  89273. * In the event of a prematurely-terminated encode, it is not strictly
  89274. * necessary to call this immediately before FLAC__stream_encoder_delete()
  89275. * but it is good practice to match every FLAC__stream_encoder_init_*()
  89276. * with a FLAC__stream_encoder_finish().
  89277. *
  89278. * \param encoder An uninitialized encoder instance.
  89279. * \assert
  89280. * \code encoder != NULL \endcode
  89281. * \retval FLAC__bool
  89282. * \c false if an error occurred processing the last frame; or if verify
  89283. * mode is set (see FLAC__stream_encoder_set_verify()), there was a
  89284. * verify mismatch; else \c true. If \c false, caller should check the
  89285. * state with FLAC__stream_encoder_get_state() for more information
  89286. * about the error.
  89287. */
  89288. FLAC_API FLAC__bool FLAC__stream_encoder_finish(FLAC__StreamEncoder *encoder);
  89289. /** Submit data for encoding.
  89290. * This version allows you to supply the input data via an array of
  89291. * pointers, each pointer pointing to an array of \a samples samples
  89292. * representing one channel. The samples need not be block-aligned,
  89293. * but each channel should have the same number of samples. Each sample
  89294. * should be a signed integer, right-justified to the resolution set by
  89295. * FLAC__stream_encoder_set_bits_per_sample(). For example, if the
  89296. * resolution is 16 bits per sample, the samples should all be in the
  89297. * range [-32768,32767].
  89298. *
  89299. * For applications where channel order is important, channels must
  89300. * follow the order as described in the
  89301. * <A HREF="../format.html#frame_header">frame header</A>.
  89302. *
  89303. * \param encoder An initialized encoder instance in the OK state.
  89304. * \param buffer An array of pointers to each channel's signal.
  89305. * \param samples The number of samples in one channel.
  89306. * \assert
  89307. * \code encoder != NULL \endcode
  89308. * \code FLAC__stream_encoder_get_state(encoder) == FLAC__STREAM_ENCODER_OK \endcode
  89309. * \retval FLAC__bool
  89310. * \c true if successful, else \c false; in this case, check the
  89311. * encoder state with FLAC__stream_encoder_get_state() to see what
  89312. * went wrong.
  89313. */
  89314. FLAC_API FLAC__bool FLAC__stream_encoder_process(FLAC__StreamEncoder *encoder, const FLAC__int32 * const buffer[], unsigned samples);
  89315. /** Submit data for encoding.
  89316. * This version allows you to supply the input data where the channels
  89317. * are interleaved into a single array (i.e. channel0_sample0,
  89318. * channel1_sample0, ... , channelN_sample0, channel0_sample1, ...).
  89319. * The samples need not be block-aligned but they must be
  89320. * sample-aligned, i.e. the first value should be channel0_sample0
  89321. * and the last value channelN_sampleM. Each sample should be a signed
  89322. * integer, right-justified to the resolution set by
  89323. * FLAC__stream_encoder_set_bits_per_sample(). For example, if the
  89324. * resolution is 16 bits per sample, the samples should all be in the
  89325. * range [-32768,32767].
  89326. *
  89327. * For applications where channel order is important, channels must
  89328. * follow the order as described in the
  89329. * <A HREF="../format.html#frame_header">frame header</A>.
  89330. *
  89331. * \param encoder An initialized encoder instance in the OK state.
  89332. * \param buffer An array of channel-interleaved data (see above).
  89333. * \param samples The number of samples in one channel, the same as for
  89334. * FLAC__stream_encoder_process(). For example, if
  89335. * encoding two channels, \c 1000 \a samples corresponds
  89336. * to a \a buffer of 2000 values.
  89337. * \assert
  89338. * \code encoder != NULL \endcode
  89339. * \code FLAC__stream_encoder_get_state(encoder) == FLAC__STREAM_ENCODER_OK \endcode
  89340. * \retval FLAC__bool
  89341. * \c true if successful, else \c false; in this case, check the
  89342. * encoder state with FLAC__stream_encoder_get_state() to see what
  89343. * went wrong.
  89344. */
  89345. FLAC_API FLAC__bool FLAC__stream_encoder_process_interleaved(FLAC__StreamEncoder *encoder, const FLAC__int32 buffer[], unsigned samples);
  89346. /* \} */
  89347. #ifdef __cplusplus
  89348. }
  89349. #endif
  89350. #endif
  89351. /*** End of inlined file: stream_encoder.h ***/
  89352. #ifdef _MSC_VER
  89353. /* OPT: an MSVC built-in would be better */
  89354. static _inline FLAC__uint32 local_swap32_(FLAC__uint32 x)
  89355. {
  89356. x = ((x<<8)&0xFF00FF00) | ((x>>8)&0x00FF00FF);
  89357. return (x>>16) | (x<<16);
  89358. }
  89359. #endif
  89360. #if defined(_MSC_VER) && defined(_X86_)
  89361. /* OPT: an MSVC built-in would be better */
  89362. static void local_swap32_block_(FLAC__uint32 *start, FLAC__uint32 len)
  89363. {
  89364. __asm {
  89365. mov edx, start
  89366. mov ecx, len
  89367. test ecx, ecx
  89368. loop1:
  89369. jz done1
  89370. mov eax, [edx]
  89371. bswap eax
  89372. mov [edx], eax
  89373. add edx, 4
  89374. dec ecx
  89375. jmp short loop1
  89376. done1:
  89377. }
  89378. }
  89379. #endif
  89380. /** \mainpage
  89381. *
  89382. * \section intro Introduction
  89383. *
  89384. * This is the documentation for the FLAC C and C++ APIs. It is
  89385. * highly interconnected; this introduction should give you a top
  89386. * level idea of the structure and how to find the information you
  89387. * need. As a prerequisite you should have at least a basic
  89388. * knowledge of the FLAC format, documented
  89389. * <A HREF="../format.html">here</A>.
  89390. *
  89391. * \section c_api FLAC C API
  89392. *
  89393. * The FLAC C API is the interface to libFLAC, a set of structures
  89394. * describing the components of FLAC streams, and functions for
  89395. * encoding and decoding streams, as well as manipulating FLAC
  89396. * metadata in files. The public include files will be installed
  89397. * in your include area (for example /usr/include/FLAC/...).
  89398. *
  89399. * By writing a little code and linking against libFLAC, it is
  89400. * relatively easy to add FLAC support to another program. The
  89401. * library is licensed under <A HREF="../license.html">Xiph's BSD license</A>.
  89402. * Complete source code of libFLAC as well as the command-line
  89403. * encoder and plugins is available and is a useful source of
  89404. * examples.
  89405. *
  89406. * Aside from encoders and decoders, libFLAC provides a powerful
  89407. * metadata interface for manipulating metadata in FLAC files. It
  89408. * allows the user to add, delete, and modify FLAC metadata blocks
  89409. * and it can automatically take advantage of PADDING blocks to avoid
  89410. * rewriting the entire FLAC file when changing the size of the
  89411. * metadata.
  89412. *
  89413. * libFLAC usually only requires the standard C library and C math
  89414. * library. In particular, threading is not used so there is no
  89415. * dependency on a thread library. However, libFLAC does not use
  89416. * global variables and should be thread-safe.
  89417. *
  89418. * libFLAC also supports encoding to and decoding from Ogg FLAC.
  89419. * However the metadata editing interfaces currently have limited
  89420. * read-only support for Ogg FLAC files.
  89421. *
  89422. * \section cpp_api FLAC C++ API
  89423. *
  89424. * The FLAC C++ API is a set of classes that encapsulate the
  89425. * structures and functions in libFLAC. They provide slightly more
  89426. * functionality with respect to metadata but are otherwise
  89427. * equivalent. For the most part, they share the same usage as
  89428. * their counterparts in libFLAC, and the FLAC C API documentation
  89429. * can be used as a supplement. The public include files
  89430. * for the C++ API will be installed in your include area (for
  89431. * example /usr/include/FLAC++/...).
  89432. *
  89433. * libFLAC++ is also licensed under
  89434. * <A HREF="../license.html">Xiph's BSD license</A>.
  89435. *
  89436. * \section getting_started Getting Started
  89437. *
  89438. * A good starting point for learning the API is to browse through
  89439. * the <A HREF="modules.html">modules</A>. Modules are logical
  89440. * groupings of related functions or classes, which correspond roughly
  89441. * to header files or sections of header files. Each module includes a
  89442. * detailed description of the general usage of its functions or
  89443. * classes.
  89444. *
  89445. * From there you can go on to look at the documentation of
  89446. * individual functions. You can see different views of the individual
  89447. * functions through the links in top bar across this page.
  89448. *
  89449. * If you prefer a more hands-on approach, you can jump right to some
  89450. * <A HREF="../documentation_example_code.html">example code</A>.
  89451. *
  89452. * \section porting_guide Porting Guide
  89453. *
  89454. * Starting with FLAC 1.1.3 a \link porting Porting Guide \endlink
  89455. * has been introduced which gives detailed instructions on how to
  89456. * port your code to newer versions of FLAC.
  89457. *
  89458. * \section embedded_developers Embedded Developers
  89459. *
  89460. * libFLAC has grown larger over time as more functionality has been
  89461. * included, but much of it may be unnecessary for a particular embedded
  89462. * implementation. Unused parts may be pruned by some simple editing of
  89463. * src/libFLAC/Makefile.am. In general, the decoders, encoders, and
  89464. * metadata interface are all independent from each other.
  89465. *
  89466. * It is easiest to just describe the dependencies:
  89467. *
  89468. * - All modules depend on the \link flac_format Format \endlink module.
  89469. * - The decoders and encoders depend on the bitbuffer.
  89470. * - The decoder is independent of the encoder. The encoder uses the
  89471. * decoder because of the verify feature, but this can be removed if
  89472. * not needed.
  89473. * - Parts of the metadata interface require the stream decoder (but not
  89474. * the encoder).
  89475. * - Ogg support is selectable through the compile time macro
  89476. * \c FLAC__HAS_OGG.
  89477. *
  89478. * For example, if your application only requires the stream decoder, no
  89479. * encoder, and no metadata interface, you can remove the stream encoder
  89480. * and the metadata interface, which will greatly reduce the size of the
  89481. * library.
  89482. *
  89483. * Also, there are several places in the libFLAC code with comments marked
  89484. * with "OPT:" where a #define can be changed to enable code that might be
  89485. * faster on a specific platform. Experimenting with these can yield faster
  89486. * binaries.
  89487. */
  89488. /** \defgroup porting Porting Guide for New Versions
  89489. *
  89490. * This module describes differences in the library interfaces from
  89491. * version to version. It assists in the porting of code that uses
  89492. * the libraries to newer versions of FLAC.
  89493. *
  89494. * One simple facility for making porting easier that has been added
  89495. * in FLAC 1.1.3 is a set of \c #defines in \c export.h of each
  89496. * library's includes (e.g. \c include/FLAC/export.h). The
  89497. * \c #defines mirror the libraries'
  89498. * <A HREF="http://www.gnu.org/software/libtool/manual.html#Libtool-versioning">libtool version numbers</A>,
  89499. * e.g. in libFLAC there are \c FLAC_API_VERSION_CURRENT,
  89500. * \c FLAC_API_VERSION_REVISION, and \c FLAC_API_VERSION_AGE.
  89501. * These can be used to support multiple versions of an API during the
  89502. * transition phase, e.g.
  89503. *
  89504. * \code
  89505. * #if !defined(FLAC_API_VERSION_CURRENT) || FLAC_API_VERSION_CURRENT <= 7
  89506. * legacy code
  89507. * #else
  89508. * new code
  89509. * #endif
  89510. * \endcode
  89511. *
  89512. * The the source will work for multiple versions and the legacy code can
  89513. * easily be removed when the transition is complete.
  89514. *
  89515. * Another available symbol is FLAC_API_SUPPORTS_OGG_FLAC (defined in
  89516. * include/FLAC/export.h), which can be used to determine whether or not
  89517. * the library has been compiled with support for Ogg FLAC. This is
  89518. * simpler than trying to call an Ogg init function and catching the
  89519. * error.
  89520. */
  89521. /** \defgroup porting_1_1_2_to_1_1_3 Porting from FLAC 1.1.2 to 1.1.3
  89522. * \ingroup porting
  89523. *
  89524. * \brief
  89525. * This module describes porting from FLAC 1.1.2 to FLAC 1.1.3.
  89526. *
  89527. * The main change between the APIs in 1.1.2 and 1.1.3 is that they have
  89528. * been simplified. First, libOggFLAC has been merged into libFLAC and
  89529. * libOggFLAC++ has been merged into libFLAC++. Second, both the three
  89530. * decoding layers and three encoding layers have been merged into a
  89531. * single stream decoder and stream encoder. That is, the functionality
  89532. * of FLAC__SeekableStreamDecoder and FLAC__FileDecoder has been merged
  89533. * into FLAC__StreamDecoder, and FLAC__SeekableStreamEncoder and
  89534. * FLAC__FileEncoder into FLAC__StreamEncoder. Only the
  89535. * FLAC__StreamDecoder and FLAC__StreamEncoder remain. What this means
  89536. * is there is now a single API that can be used to encode or decode
  89537. * streams to/from native FLAC or Ogg FLAC and the single API can work
  89538. * on both seekable and non-seekable streams.
  89539. *
  89540. * Instead of creating an encoder or decoder of a certain layer, now the
  89541. * client will always create a FLAC__StreamEncoder or
  89542. * FLAC__StreamDecoder. The old layers are now differentiated by the
  89543. * initialization function. For example, for the decoder,
  89544. * FLAC__stream_decoder_init() has been replaced by
  89545. * FLAC__stream_decoder_init_stream(). This init function takes
  89546. * callbacks for the I/O, and the seeking callbacks are optional. This
  89547. * allows the client to use the same object for seekable and
  89548. * non-seekable streams. For decoding a FLAC file directly, the client
  89549. * can use FLAC__stream_decoder_init_file() and pass just a filename
  89550. * and fewer callbacks; most of the other callbacks are supplied
  89551. * internally. For situations where fopen()ing by filename is not
  89552. * possible (e.g. Unicode filenames on Windows) the client can instead
  89553. * open the file itself and supply the FILE* to
  89554. * FLAC__stream_decoder_init_FILE(). The init functions now returns a
  89555. * FLAC__StreamDecoderInitStatus instead of FLAC__StreamDecoderState.
  89556. * Since the callbacks and client data are now passed to the init
  89557. * function, the FLAC__stream_decoder_set_*_callback() functions and
  89558. * FLAC__stream_decoder_set_client_data() are no longer needed. The
  89559. * rest of the calls to the decoder are the same as before.
  89560. *
  89561. * There are counterpart init functions for Ogg FLAC, e.g.
  89562. * FLAC__stream_decoder_init_ogg_stream(). All the rest of the calls
  89563. * and callbacks are the same as for native FLAC.
  89564. *
  89565. * As an example, in FLAC 1.1.2 a seekable stream decoder would have
  89566. * been set up like so:
  89567. *
  89568. * \code
  89569. * FLAC__SeekableStreamDecoder *decoder = FLAC__seekable_stream_decoder_new();
  89570. * if(decoder == NULL) do_something;
  89571. * FLAC__seekable_stream_decoder_set_md5_checking(decoder, true);
  89572. * [... other settings ...]
  89573. * FLAC__seekable_stream_decoder_set_read_callback(decoder, my_read_callback);
  89574. * FLAC__seekable_stream_decoder_set_seek_callback(decoder, my_seek_callback);
  89575. * FLAC__seekable_stream_decoder_set_tell_callback(decoder, my_tell_callback);
  89576. * FLAC__seekable_stream_decoder_set_length_callback(decoder, my_length_callback);
  89577. * FLAC__seekable_stream_decoder_set_eof_callback(decoder, my_eof_callback);
  89578. * FLAC__seekable_stream_decoder_set_write_callback(decoder, my_write_callback);
  89579. * FLAC__seekable_stream_decoder_set_metadata_callback(decoder, my_metadata_callback);
  89580. * FLAC__seekable_stream_decoder_set_error_callback(decoder, my_error_callback);
  89581. * FLAC__seekable_stream_decoder_set_client_data(decoder, my_client_data);
  89582. * if(FLAC__seekable_stream_decoder_init(decoder) != FLAC__SEEKABLE_STREAM_DECODER_OK) do_something;
  89583. * \endcode
  89584. *
  89585. * In FLAC 1.1.3 it is like this:
  89586. *
  89587. * \code
  89588. * FLAC__StreamDecoder *decoder = FLAC__stream_decoder_new();
  89589. * if(decoder == NULL) do_something;
  89590. * FLAC__stream_decoder_set_md5_checking(decoder, true);
  89591. * [... other settings ...]
  89592. * if(FLAC__stream_decoder_init_stream(
  89593. * decoder,
  89594. * my_read_callback,
  89595. * my_seek_callback, // or NULL
  89596. * my_tell_callback, // or NULL
  89597. * my_length_callback, // or NULL
  89598. * my_eof_callback, // or NULL
  89599. * my_write_callback,
  89600. * my_metadata_callback, // or NULL
  89601. * my_error_callback,
  89602. * my_client_data
  89603. * ) != FLAC__STREAM_DECODER_INIT_STATUS_OK) do_something;
  89604. * \endcode
  89605. *
  89606. * or you could do;
  89607. *
  89608. * \code
  89609. * [...]
  89610. * FILE *file = fopen("somefile.flac","rb");
  89611. * if(file == NULL) do_somthing;
  89612. * if(FLAC__stream_decoder_init_FILE(
  89613. * decoder,
  89614. * file,
  89615. * my_write_callback,
  89616. * my_metadata_callback, // or NULL
  89617. * my_error_callback,
  89618. * my_client_data
  89619. * ) != FLAC__STREAM_DECODER_INIT_STATUS_OK) do_something;
  89620. * \endcode
  89621. *
  89622. * or just:
  89623. *
  89624. * \code
  89625. * [...]
  89626. * if(FLAC__stream_decoder_init_file(
  89627. * decoder,
  89628. * "somefile.flac",
  89629. * my_write_callback,
  89630. * my_metadata_callback, // or NULL
  89631. * my_error_callback,
  89632. * my_client_data
  89633. * ) != FLAC__STREAM_DECODER_INIT_STATUS_OK) do_something;
  89634. * \endcode
  89635. *
  89636. * Another small change to the decoder is in how it handles unparseable
  89637. * streams. Before, when the decoder found an unparseable stream
  89638. * (reserved for when the decoder encounters a stream from a future
  89639. * encoder that it can't parse), it changed the state to
  89640. * \c FLAC__STREAM_DECODER_UNPARSEABLE_STREAM. Now the decoder instead
  89641. * drops sync and calls the error callback with a new error code
  89642. * \c FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM. This is
  89643. * more robust. If your error callback does not discriminate on the the
  89644. * error state, your code does not need to be changed.
  89645. *
  89646. * The encoder now has a new setting:
  89647. * FLAC__stream_encoder_set_apodization(). This is for setting the
  89648. * method used to window the data before LPC analysis. You only need to
  89649. * add a call to this function if the default is not suitable. There
  89650. * are also two new convenience functions that may be useful:
  89651. * FLAC__metadata_object_cuesheet_calculate_cddb_id() and
  89652. * FLAC__metadata_get_cuesheet().
  89653. *
  89654. * The \a bytes parameter to FLAC__StreamDecoderReadCallback,
  89655. * FLAC__StreamEncoderReadCallback, and FLAC__StreamEncoderWriteCallback
  89656. * is now \c size_t instead of \c unsigned.
  89657. */
  89658. /** \defgroup porting_1_1_3_to_1_1_4 Porting from FLAC 1.1.3 to 1.1.4
  89659. * \ingroup porting
  89660. *
  89661. * \brief
  89662. * This module describes porting from FLAC 1.1.3 to FLAC 1.1.4.
  89663. *
  89664. * There were no changes to any of the interfaces from 1.1.3 to 1.1.4.
  89665. * There was a slight change in the implementation of
  89666. * FLAC__stream_encoder_set_metadata(); the function now makes a copy
  89667. * of the \a metadata array of pointers so the client no longer needs
  89668. * to maintain it after the call. The objects themselves that are
  89669. * pointed to by the array are still not copied though and must be
  89670. * maintained until the call to FLAC__stream_encoder_finish().
  89671. */
  89672. /** \defgroup porting_1_1_4_to_1_2_0 Porting from FLAC 1.1.4 to 1.2.0
  89673. * \ingroup porting
  89674. *
  89675. * \brief
  89676. * This module describes porting from FLAC 1.1.4 to FLAC 1.2.0.
  89677. *
  89678. * There were only very minor changes to the interfaces from 1.1.4 to 1.2.0.
  89679. * In libFLAC, \c FLAC__format_sample_rate_is_subset() was added.
  89680. * In libFLAC++, \c FLAC::Decoder::Stream::get_decode_position() was added.
  89681. *
  89682. * Finally, value of the constant \c FLAC__FRAME_HEADER_RESERVED_LEN
  89683. * has changed to reflect the conversion of one of the reserved bits
  89684. * into active use. It used to be \c 2 and now is \c 1. However the
  89685. * FLAC frame header length has not changed, so to skip the proper
  89686. * number of bits, use \c FLAC__FRAME_HEADER_RESERVED_LEN +
  89687. * \c FLAC__FRAME_HEADER_BLOCKING_STRATEGY_LEN
  89688. */
  89689. /** \defgroup flac FLAC C API
  89690. *
  89691. * The FLAC C API is the interface to libFLAC, a set of structures
  89692. * describing the components of FLAC streams, and functions for
  89693. * encoding and decoding streams, as well as manipulating FLAC
  89694. * metadata in files.
  89695. *
  89696. * You should start with the format components as all other modules
  89697. * are dependent on it.
  89698. */
  89699. #endif
  89700. /*** End of inlined file: all.h ***/
  89701. /*** Start of inlined file: bitmath.c ***/
  89702. /*** Start of inlined file: juce_FlacHeader.h ***/
  89703. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  89704. // tasks..
  89705. #define VERSION "1.2.1"
  89706. #define FLAC__NO_DLL 1
  89707. #if JUCE_MSVC
  89708. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  89709. #endif
  89710. #if JUCE_MAC
  89711. #define FLAC__SYS_DARWIN 1
  89712. #endif
  89713. /*** End of inlined file: juce_FlacHeader.h ***/
  89714. #if JUCE_USE_FLAC
  89715. #if HAVE_CONFIG_H
  89716. # include <config.h>
  89717. #endif
  89718. /*** Start of inlined file: bitmath.h ***/
  89719. #ifndef FLAC__PRIVATE__BITMATH_H
  89720. #define FLAC__PRIVATE__BITMATH_H
  89721. unsigned FLAC__bitmath_ilog2(FLAC__uint32 v);
  89722. unsigned FLAC__bitmath_ilog2_wide(FLAC__uint64 v);
  89723. unsigned FLAC__bitmath_silog2(int v);
  89724. unsigned FLAC__bitmath_silog2_wide(FLAC__int64 v);
  89725. #endif
  89726. /*** End of inlined file: bitmath.h ***/
  89727. /* An example of what FLAC__bitmath_ilog2() computes:
  89728. *
  89729. * ilog2( 0) = assertion failure
  89730. * ilog2( 1) = 0
  89731. * ilog2( 2) = 1
  89732. * ilog2( 3) = 1
  89733. * ilog2( 4) = 2
  89734. * ilog2( 5) = 2
  89735. * ilog2( 6) = 2
  89736. * ilog2( 7) = 2
  89737. * ilog2( 8) = 3
  89738. * ilog2( 9) = 3
  89739. * ilog2(10) = 3
  89740. * ilog2(11) = 3
  89741. * ilog2(12) = 3
  89742. * ilog2(13) = 3
  89743. * ilog2(14) = 3
  89744. * ilog2(15) = 3
  89745. * ilog2(16) = 4
  89746. * ilog2(17) = 4
  89747. * ilog2(18) = 4
  89748. */
  89749. unsigned FLAC__bitmath_ilog2(FLAC__uint32 v)
  89750. {
  89751. unsigned l = 0;
  89752. FLAC__ASSERT(v > 0);
  89753. while(v >>= 1)
  89754. l++;
  89755. return l;
  89756. }
  89757. unsigned FLAC__bitmath_ilog2_wide(FLAC__uint64 v)
  89758. {
  89759. unsigned l = 0;
  89760. FLAC__ASSERT(v > 0);
  89761. while(v >>= 1)
  89762. l++;
  89763. return l;
  89764. }
  89765. /* An example of what FLAC__bitmath_silog2() computes:
  89766. *
  89767. * silog2(-10) = 5
  89768. * silog2(- 9) = 5
  89769. * silog2(- 8) = 4
  89770. * silog2(- 7) = 4
  89771. * silog2(- 6) = 4
  89772. * silog2(- 5) = 4
  89773. * silog2(- 4) = 3
  89774. * silog2(- 3) = 3
  89775. * silog2(- 2) = 2
  89776. * silog2(- 1) = 2
  89777. * silog2( 0) = 0
  89778. * silog2( 1) = 2
  89779. * silog2( 2) = 3
  89780. * silog2( 3) = 3
  89781. * silog2( 4) = 4
  89782. * silog2( 5) = 4
  89783. * silog2( 6) = 4
  89784. * silog2( 7) = 4
  89785. * silog2( 8) = 5
  89786. * silog2( 9) = 5
  89787. * silog2( 10) = 5
  89788. */
  89789. unsigned FLAC__bitmath_silog2(int v)
  89790. {
  89791. while(1) {
  89792. if(v == 0) {
  89793. return 0;
  89794. }
  89795. else if(v > 0) {
  89796. unsigned l = 0;
  89797. while(v) {
  89798. l++;
  89799. v >>= 1;
  89800. }
  89801. return l+1;
  89802. }
  89803. else if(v == -1) {
  89804. return 2;
  89805. }
  89806. else {
  89807. v++;
  89808. v = -v;
  89809. }
  89810. }
  89811. }
  89812. unsigned FLAC__bitmath_silog2_wide(FLAC__int64 v)
  89813. {
  89814. while(1) {
  89815. if(v == 0) {
  89816. return 0;
  89817. }
  89818. else if(v > 0) {
  89819. unsigned l = 0;
  89820. while(v) {
  89821. l++;
  89822. v >>= 1;
  89823. }
  89824. return l+1;
  89825. }
  89826. else if(v == -1) {
  89827. return 2;
  89828. }
  89829. else {
  89830. v++;
  89831. v = -v;
  89832. }
  89833. }
  89834. }
  89835. #endif
  89836. /*** End of inlined file: bitmath.c ***/
  89837. /*** Start of inlined file: bitreader.c ***/
  89838. /*** Start of inlined file: juce_FlacHeader.h ***/
  89839. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  89840. // tasks..
  89841. #define VERSION "1.2.1"
  89842. #define FLAC__NO_DLL 1
  89843. #if JUCE_MSVC
  89844. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  89845. #endif
  89846. #if JUCE_MAC
  89847. #define FLAC__SYS_DARWIN 1
  89848. #endif
  89849. /*** End of inlined file: juce_FlacHeader.h ***/
  89850. #if JUCE_USE_FLAC
  89851. #if HAVE_CONFIG_H
  89852. # include <config.h>
  89853. #endif
  89854. #include <stdlib.h> /* for malloc() */
  89855. #include <string.h> /* for memcpy(), memset() */
  89856. #ifdef _MSC_VER
  89857. #include <winsock.h> /* for ntohl() */
  89858. #elif defined FLAC__SYS_DARWIN
  89859. #include <machine/endian.h> /* for ntohl() */
  89860. #elif defined __MINGW32__
  89861. #include <winsock.h> /* for ntohl() */
  89862. #else
  89863. #include <netinet/in.h> /* for ntohl() */
  89864. #endif
  89865. /*** Start of inlined file: bitreader.h ***/
  89866. #ifndef FLAC__PRIVATE__BITREADER_H
  89867. #define FLAC__PRIVATE__BITREADER_H
  89868. #include <stdio.h> /* for FILE */
  89869. /*** Start of inlined file: cpu.h ***/
  89870. #ifndef FLAC__PRIVATE__CPU_H
  89871. #define FLAC__PRIVATE__CPU_H
  89872. #ifdef HAVE_CONFIG_H
  89873. #include <config.h>
  89874. #endif
  89875. typedef enum {
  89876. FLAC__CPUINFO_TYPE_IA32,
  89877. FLAC__CPUINFO_TYPE_PPC,
  89878. FLAC__CPUINFO_TYPE_UNKNOWN
  89879. } FLAC__CPUInfo_Type;
  89880. typedef struct {
  89881. FLAC__bool cpuid;
  89882. FLAC__bool bswap;
  89883. FLAC__bool cmov;
  89884. FLAC__bool mmx;
  89885. FLAC__bool fxsr;
  89886. FLAC__bool sse;
  89887. FLAC__bool sse2;
  89888. FLAC__bool sse3;
  89889. FLAC__bool ssse3;
  89890. FLAC__bool _3dnow;
  89891. FLAC__bool ext3dnow;
  89892. FLAC__bool extmmx;
  89893. } FLAC__CPUInfo_IA32;
  89894. typedef struct {
  89895. FLAC__bool altivec;
  89896. FLAC__bool ppc64;
  89897. } FLAC__CPUInfo_PPC;
  89898. typedef struct {
  89899. FLAC__bool use_asm;
  89900. FLAC__CPUInfo_Type type;
  89901. union {
  89902. FLAC__CPUInfo_IA32 ia32;
  89903. FLAC__CPUInfo_PPC ppc;
  89904. } data;
  89905. } FLAC__CPUInfo;
  89906. void FLAC__cpu_info(FLAC__CPUInfo *info);
  89907. #ifndef FLAC__NO_ASM
  89908. #ifdef FLAC__CPU_IA32
  89909. #ifdef FLAC__HAS_NASM
  89910. FLAC__uint32 FLAC__cpu_have_cpuid_asm_ia32(void);
  89911. void FLAC__cpu_info_asm_ia32(FLAC__uint32 *flags_edx, FLAC__uint32 *flags_ecx);
  89912. FLAC__uint32 FLAC__cpu_info_extended_amd_asm_ia32(void);
  89913. #endif
  89914. #endif
  89915. #endif
  89916. #endif
  89917. /*** End of inlined file: cpu.h ***/
  89918. /*
  89919. * opaque structure definition
  89920. */
  89921. struct FLAC__BitReader;
  89922. typedef struct FLAC__BitReader FLAC__BitReader;
  89923. typedef FLAC__bool (*FLAC__BitReaderReadCallback)(FLAC__byte buffer[], size_t *bytes, void *client_data);
  89924. /*
  89925. * construction, deletion, initialization, etc functions
  89926. */
  89927. FLAC__BitReader *FLAC__bitreader_new(void);
  89928. void FLAC__bitreader_delete(FLAC__BitReader *br);
  89929. FLAC__bool FLAC__bitreader_init(FLAC__BitReader *br, FLAC__CPUInfo cpu, FLAC__BitReaderReadCallback rcb, void *cd);
  89930. void FLAC__bitreader_free(FLAC__BitReader *br); /* does not 'free(br)' */
  89931. FLAC__bool FLAC__bitreader_clear(FLAC__BitReader *br);
  89932. void FLAC__bitreader_dump(const FLAC__BitReader *br, FILE *out);
  89933. /*
  89934. * CRC functions
  89935. */
  89936. void FLAC__bitreader_reset_read_crc16(FLAC__BitReader *br, FLAC__uint16 seed);
  89937. FLAC__uint16 FLAC__bitreader_get_read_crc16(FLAC__BitReader *br);
  89938. /*
  89939. * info functions
  89940. */
  89941. FLAC__bool FLAC__bitreader_is_consumed_byte_aligned(const FLAC__BitReader *br);
  89942. unsigned FLAC__bitreader_bits_left_for_byte_alignment(const FLAC__BitReader *br);
  89943. unsigned FLAC__bitreader_get_input_bits_unconsumed(const FLAC__BitReader *br);
  89944. /*
  89945. * read functions
  89946. */
  89947. FLAC__bool FLAC__bitreader_read_raw_uint32(FLAC__BitReader *br, FLAC__uint32 *val, unsigned bits);
  89948. FLAC__bool FLAC__bitreader_read_raw_int32(FLAC__BitReader *br, FLAC__int32 *val, unsigned bits);
  89949. FLAC__bool FLAC__bitreader_read_raw_uint64(FLAC__BitReader *br, FLAC__uint64 *val, unsigned bits);
  89950. FLAC__bool FLAC__bitreader_read_uint32_little_endian(FLAC__BitReader *br, FLAC__uint32 *val); /*only for bits=32*/
  89951. FLAC__bool FLAC__bitreader_skip_bits_no_crc(FLAC__BitReader *br, unsigned bits); /* WATCHOUT: does not CRC the skipped data! */ /*@@@@ add to unit tests */
  89952. FLAC__bool FLAC__bitreader_skip_byte_block_aligned_no_crc(FLAC__BitReader *br, unsigned nvals); /* WATCHOUT: does not CRC the read data! */
  89953. 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! */
  89954. FLAC__bool FLAC__bitreader_read_unary_unsigned(FLAC__BitReader *br, unsigned *val);
  89955. FLAC__bool FLAC__bitreader_read_rice_signed(FLAC__BitReader *br, int *val, unsigned parameter);
  89956. FLAC__bool FLAC__bitreader_read_rice_signed_block(FLAC__BitReader *br, int vals[], unsigned nvals, unsigned parameter);
  89957. #ifndef FLAC__NO_ASM
  89958. # ifdef FLAC__CPU_IA32
  89959. # ifdef FLAC__HAS_NASM
  89960. FLAC__bool FLAC__bitreader_read_rice_signed_block_asm_ia32_bswap(FLAC__BitReader *br, int vals[], unsigned nvals, unsigned parameter);
  89961. # endif
  89962. # endif
  89963. #endif
  89964. #if 0 /* UNUSED */
  89965. FLAC__bool FLAC__bitreader_read_golomb_signed(FLAC__BitReader *br, int *val, unsigned parameter);
  89966. FLAC__bool FLAC__bitreader_read_golomb_unsigned(FLAC__BitReader *br, unsigned *val, unsigned parameter);
  89967. #endif
  89968. FLAC__bool FLAC__bitreader_read_utf8_uint32(FLAC__BitReader *br, FLAC__uint32 *val, FLAC__byte *raw, unsigned *rawlen);
  89969. FLAC__bool FLAC__bitreader_read_utf8_uint64(FLAC__BitReader *br, FLAC__uint64 *val, FLAC__byte *raw, unsigned *rawlen);
  89970. FLAC__bool bitreader_read_from_client_(FLAC__BitReader *br);
  89971. #endif
  89972. /*** End of inlined file: bitreader.h ***/
  89973. /*** Start of inlined file: crc.h ***/
  89974. #ifndef FLAC__PRIVATE__CRC_H
  89975. #define FLAC__PRIVATE__CRC_H
  89976. /* 8 bit CRC generator, MSB shifted first
  89977. ** polynomial = x^8 + x^2 + x^1 + x^0
  89978. ** init = 0
  89979. */
  89980. extern FLAC__byte const FLAC__crc8_table[256];
  89981. #define FLAC__CRC8_UPDATE(data, crc) (crc) = FLAC__crc8_table[(crc) ^ (data)];
  89982. void FLAC__crc8_update(const FLAC__byte data, FLAC__uint8 *crc);
  89983. void FLAC__crc8_update_block(const FLAC__byte *data, unsigned len, FLAC__uint8 *crc);
  89984. FLAC__uint8 FLAC__crc8(const FLAC__byte *data, unsigned len);
  89985. /* 16 bit CRC generator, MSB shifted first
  89986. ** polynomial = x^16 + x^15 + x^2 + x^0
  89987. ** init = 0
  89988. */
  89989. extern unsigned FLAC__crc16_table[256];
  89990. #define FLAC__CRC16_UPDATE(data, crc) (((((crc)<<8) & 0xffff) ^ FLAC__crc16_table[((crc)>>8) ^ (data)]))
  89991. /* this alternate may be faster on some systems/compilers */
  89992. #if 0
  89993. #define FLAC__CRC16_UPDATE(data, crc) ((((crc)<<8) ^ FLAC__crc16_table[((crc)>>8) ^ (data)]) & 0xffff)
  89994. #endif
  89995. unsigned FLAC__crc16(const FLAC__byte *data, unsigned len);
  89996. #endif
  89997. /*** End of inlined file: crc.h ***/
  89998. /* Things should be fastest when this matches the machine word size */
  89999. /* WATCHOUT: if you change this you must also change the following #defines down to COUNT_ZERO_MSBS below to match */
  90000. /* WATCHOUT: there are a few places where the code will not work unless brword is >= 32 bits wide */
  90001. /* also, some sections currently only have fast versions for 4 or 8 bytes per word */
  90002. typedef FLAC__uint32 brword;
  90003. #define FLAC__BYTES_PER_WORD 4
  90004. #define FLAC__BITS_PER_WORD 32
  90005. #define FLAC__WORD_ALL_ONES ((FLAC__uint32)0xffffffff)
  90006. /* SWAP_BE_WORD_TO_HOST swaps bytes in a brword (which is always big-endian) if necessary to match host byte order */
  90007. #if WORDS_BIGENDIAN
  90008. #define SWAP_BE_WORD_TO_HOST(x) (x)
  90009. #else
  90010. #if defined (_MSC_VER) && defined (_X86_)
  90011. #define SWAP_BE_WORD_TO_HOST(x) local_swap32_(x)
  90012. #else
  90013. #define SWAP_BE_WORD_TO_HOST(x) ntohl(x)
  90014. #endif
  90015. #endif
  90016. /* counts the # of zero MSBs in a word */
  90017. #define COUNT_ZERO_MSBS(word) ( \
  90018. (word) <= 0xffff ? \
  90019. ( (word) <= 0xff? byte_to_unary_table[word] + 24 : byte_to_unary_table[(word) >> 8] + 16 ) : \
  90020. ( (word) <= 0xffffff? byte_to_unary_table[word >> 16] + 8 : byte_to_unary_table[(word) >> 24] ) \
  90021. )
  90022. /* this alternate might be slightly faster on some systems/compilers: */
  90023. #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])) )
  90024. /*
  90025. * This should be at least twice as large as the largest number of words
  90026. * required to represent any 'number' (in any encoding) you are going to
  90027. * read. With FLAC this is on the order of maybe a few hundred bits.
  90028. * If the buffer is smaller than that, the decoder won't be able to read
  90029. * in a whole number that is in a variable length encoding (e.g. Rice).
  90030. * But to be practical it should be at least 1K bytes.
  90031. *
  90032. * Increase this number to decrease the number of read callbacks, at the
  90033. * expense of using more memory. Or decrease for the reverse effect,
  90034. * keeping in mind the limit from the first paragraph. The optimal size
  90035. * also depends on the CPU cache size and other factors; some twiddling
  90036. * may be necessary to squeeze out the best performance.
  90037. */
  90038. static const unsigned FLAC__BITREADER_DEFAULT_CAPACITY = 65536u / FLAC__BITS_PER_WORD; /* in words */
  90039. static const unsigned char byte_to_unary_table[] = {
  90040. 8, 7, 6, 6, 5, 5, 5, 5, 4, 4, 4, 4, 4, 4, 4, 4,
  90041. 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
  90042. 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
  90043. 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
  90044. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
  90045. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
  90046. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
  90047. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
  90048. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  90049. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  90050. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  90051. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  90052. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  90053. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  90054. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  90055. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
  90056. };
  90057. #ifdef min
  90058. #undef min
  90059. #endif
  90060. #define min(x,y) ((x)<(y)?(x):(y))
  90061. #ifdef max
  90062. #undef max
  90063. #endif
  90064. #define max(x,y) ((x)>(y)?(x):(y))
  90065. /* adjust for compilers that can't understand using LLU suffix for uint64_t literals */
  90066. #ifdef _MSC_VER
  90067. #define FLAC__U64L(x) x
  90068. #else
  90069. #define FLAC__U64L(x) x##LLU
  90070. #endif
  90071. #ifndef FLaC__INLINE
  90072. #define FLaC__INLINE
  90073. #endif
  90074. /* WATCHOUT: assembly routines rely on the order in which these fields are declared */
  90075. struct FLAC__BitReader {
  90076. /* any partially-consumed word at the head will stay right-justified as bits are consumed from the left */
  90077. /* any incomplete word at the tail will be left-justified, and bytes from the read callback are added on the right */
  90078. brword *buffer;
  90079. unsigned capacity; /* in words */
  90080. unsigned words; /* # of completed words in buffer */
  90081. unsigned bytes; /* # of bytes in incomplete word at buffer[words] */
  90082. unsigned consumed_words; /* #words ... */
  90083. unsigned consumed_bits; /* ... + (#bits of head word) already consumed from the front of buffer */
  90084. unsigned read_crc16; /* the running frame CRC */
  90085. unsigned crc16_align; /* the number of bits in the current consumed word that should not be CRC'd */
  90086. FLAC__BitReaderReadCallback read_callback;
  90087. void *client_data;
  90088. FLAC__CPUInfo cpu_info;
  90089. };
  90090. static FLaC__INLINE void crc16_update_word_(FLAC__BitReader *br, brword word)
  90091. {
  90092. register unsigned crc = br->read_crc16;
  90093. #if FLAC__BYTES_PER_WORD == 4
  90094. switch(br->crc16_align) {
  90095. case 0: crc = FLAC__CRC16_UPDATE((unsigned)(word >> 24), crc);
  90096. case 8: crc = FLAC__CRC16_UPDATE((unsigned)((word >> 16) & 0xff), crc);
  90097. case 16: crc = FLAC__CRC16_UPDATE((unsigned)((word >> 8) & 0xff), crc);
  90098. case 24: br->read_crc16 = FLAC__CRC16_UPDATE((unsigned)(word & 0xff), crc);
  90099. }
  90100. #elif FLAC__BYTES_PER_WORD == 8
  90101. switch(br->crc16_align) {
  90102. case 0: crc = FLAC__CRC16_UPDATE((unsigned)(word >> 56), crc);
  90103. case 8: crc = FLAC__CRC16_UPDATE((unsigned)((word >> 48) & 0xff), crc);
  90104. case 16: crc = FLAC__CRC16_UPDATE((unsigned)((word >> 40) & 0xff), crc);
  90105. case 24: crc = FLAC__CRC16_UPDATE((unsigned)((word >> 32) & 0xff), crc);
  90106. case 32: crc = FLAC__CRC16_UPDATE((unsigned)((word >> 24) & 0xff), crc);
  90107. case 40: crc = FLAC__CRC16_UPDATE((unsigned)((word >> 16) & 0xff), crc);
  90108. case 48: crc = FLAC__CRC16_UPDATE((unsigned)((word >> 8) & 0xff), crc);
  90109. case 56: br->read_crc16 = FLAC__CRC16_UPDATE((unsigned)(word & 0xff), crc);
  90110. }
  90111. #else
  90112. for( ; br->crc16_align < FLAC__BITS_PER_WORD; br->crc16_align += 8)
  90113. crc = FLAC__CRC16_UPDATE((unsigned)((word >> (FLAC__BITS_PER_WORD-8-br->crc16_align)) & 0xff), crc);
  90114. br->read_crc16 = crc;
  90115. #endif
  90116. br->crc16_align = 0;
  90117. }
  90118. /* would be static except it needs to be called by asm routines */
  90119. FLAC__bool bitreader_read_from_client_(FLAC__BitReader *br)
  90120. {
  90121. unsigned start, end;
  90122. size_t bytes;
  90123. FLAC__byte *target;
  90124. /* first shift the unconsumed buffer data toward the front as much as possible */
  90125. if(br->consumed_words > 0) {
  90126. start = br->consumed_words;
  90127. end = br->words + (br->bytes? 1:0);
  90128. memmove(br->buffer, br->buffer+start, FLAC__BYTES_PER_WORD * (end - start));
  90129. br->words -= start;
  90130. br->consumed_words = 0;
  90131. }
  90132. /*
  90133. * set the target for reading, taking into account word alignment and endianness
  90134. */
  90135. bytes = (br->capacity - br->words) * FLAC__BYTES_PER_WORD - br->bytes;
  90136. if(bytes == 0)
  90137. return false; /* no space left, buffer is too small; see note for FLAC__BITREADER_DEFAULT_CAPACITY */
  90138. target = ((FLAC__byte*)(br->buffer+br->words)) + br->bytes;
  90139. /* before reading, if the existing reader looks like this (say brword is 32 bits wide)
  90140. * bitstream : 11 22 33 44 55 br->words=1 br->bytes=1 (partial tail word is left-justified)
  90141. * buffer[BE]: 11 22 33 44 55 ?? ?? ?? (shown layed out as bytes sequentially in memory)
  90142. * buffer[LE]: 44 33 22 11 ?? ?? ?? 55 (?? being don't-care)
  90143. * ^^-------target, bytes=3
  90144. * on LE machines, have to byteswap the odd tail word so nothing is
  90145. * overwritten:
  90146. */
  90147. #if WORDS_BIGENDIAN
  90148. #else
  90149. if(br->bytes)
  90150. br->buffer[br->words] = SWAP_BE_WORD_TO_HOST(br->buffer[br->words]);
  90151. #endif
  90152. /* now it looks like:
  90153. * bitstream : 11 22 33 44 55 br->words=1 br->bytes=1
  90154. * buffer[BE]: 11 22 33 44 55 ?? ?? ??
  90155. * buffer[LE]: 44 33 22 11 55 ?? ?? ??
  90156. * ^^-------target, bytes=3
  90157. */
  90158. /* read in the data; note that the callback may return a smaller number of bytes */
  90159. if(!br->read_callback(target, &bytes, br->client_data))
  90160. return false;
  90161. /* after reading bytes 66 77 88 99 AA BB CC DD EE FF from the client:
  90162. * bitstream : 11 22 33 44 55 66 77 88 99 AA BB CC DD EE FF
  90163. * buffer[BE]: 11 22 33 44 55 66 77 88 99 AA BB CC DD EE FF ??
  90164. * buffer[LE]: 44 33 22 11 55 66 77 88 99 AA BB CC DD EE FF ??
  90165. * now have to byteswap on LE machines:
  90166. */
  90167. #if WORDS_BIGENDIAN
  90168. #else
  90169. end = (br->words*FLAC__BYTES_PER_WORD + br->bytes + bytes + (FLAC__BYTES_PER_WORD-1)) / FLAC__BYTES_PER_WORD;
  90170. # if defined(_MSC_VER) && defined (_X86_) && (FLAC__BYTES_PER_WORD == 4)
  90171. if(br->cpu_info.type == FLAC__CPUINFO_TYPE_IA32 && br->cpu_info.data.ia32.bswap) {
  90172. start = br->words;
  90173. local_swap32_block_(br->buffer + start, end - start);
  90174. }
  90175. else
  90176. # endif
  90177. for(start = br->words; start < end; start++)
  90178. br->buffer[start] = SWAP_BE_WORD_TO_HOST(br->buffer[start]);
  90179. #endif
  90180. /* now it looks like:
  90181. * bitstream : 11 22 33 44 55 66 77 88 99 AA BB CC DD EE FF
  90182. * buffer[BE]: 11 22 33 44 55 66 77 88 99 AA BB CC DD EE FF ??
  90183. * buffer[LE]: 44 33 22 11 88 77 66 55 CC BB AA 99 ?? FF EE DD
  90184. * finally we'll update the reader values:
  90185. */
  90186. end = br->words*FLAC__BYTES_PER_WORD + br->bytes + bytes;
  90187. br->words = end / FLAC__BYTES_PER_WORD;
  90188. br->bytes = end % FLAC__BYTES_PER_WORD;
  90189. return true;
  90190. }
  90191. /***********************************************************************
  90192. *
  90193. * Class constructor/destructor
  90194. *
  90195. ***********************************************************************/
  90196. FLAC__BitReader *FLAC__bitreader_new(void)
  90197. {
  90198. FLAC__BitReader *br = (FLAC__BitReader*)calloc(1, sizeof(FLAC__BitReader));
  90199. /* calloc() implies:
  90200. memset(br, 0, sizeof(FLAC__BitReader));
  90201. br->buffer = 0;
  90202. br->capacity = 0;
  90203. br->words = br->bytes = 0;
  90204. br->consumed_words = br->consumed_bits = 0;
  90205. br->read_callback = 0;
  90206. br->client_data = 0;
  90207. */
  90208. return br;
  90209. }
  90210. void FLAC__bitreader_delete(FLAC__BitReader *br)
  90211. {
  90212. FLAC__ASSERT(0 != br);
  90213. FLAC__bitreader_free(br);
  90214. free(br);
  90215. }
  90216. /***********************************************************************
  90217. *
  90218. * Public class methods
  90219. *
  90220. ***********************************************************************/
  90221. FLAC__bool FLAC__bitreader_init(FLAC__BitReader *br, FLAC__CPUInfo cpu, FLAC__BitReaderReadCallback rcb, void *cd)
  90222. {
  90223. FLAC__ASSERT(0 != br);
  90224. br->words = br->bytes = 0;
  90225. br->consumed_words = br->consumed_bits = 0;
  90226. br->capacity = FLAC__BITREADER_DEFAULT_CAPACITY;
  90227. br->buffer = (brword*)malloc(sizeof(brword) * br->capacity);
  90228. if(br->buffer == 0)
  90229. return false;
  90230. br->read_callback = rcb;
  90231. br->client_data = cd;
  90232. br->cpu_info = cpu;
  90233. return true;
  90234. }
  90235. void FLAC__bitreader_free(FLAC__BitReader *br)
  90236. {
  90237. FLAC__ASSERT(0 != br);
  90238. if(0 != br->buffer)
  90239. free(br->buffer);
  90240. br->buffer = 0;
  90241. br->capacity = 0;
  90242. br->words = br->bytes = 0;
  90243. br->consumed_words = br->consumed_bits = 0;
  90244. br->read_callback = 0;
  90245. br->client_data = 0;
  90246. }
  90247. FLAC__bool FLAC__bitreader_clear(FLAC__BitReader *br)
  90248. {
  90249. br->words = br->bytes = 0;
  90250. br->consumed_words = br->consumed_bits = 0;
  90251. return true;
  90252. }
  90253. void FLAC__bitreader_dump(const FLAC__BitReader *br, FILE *out)
  90254. {
  90255. unsigned i, j;
  90256. if(br == 0) {
  90257. fprintf(out, "bitreader is NULL\n");
  90258. }
  90259. else {
  90260. 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);
  90261. for(i = 0; i < br->words; i++) {
  90262. fprintf(out, "%08X: ", i);
  90263. for(j = 0; j < FLAC__BITS_PER_WORD; j++)
  90264. if(i < br->consumed_words || (i == br->consumed_words && j < br->consumed_bits))
  90265. fprintf(out, ".");
  90266. else
  90267. fprintf(out, "%01u", br->buffer[i] & (1 << (FLAC__BITS_PER_WORD-j-1)) ? 1:0);
  90268. fprintf(out, "\n");
  90269. }
  90270. if(br->bytes > 0) {
  90271. fprintf(out, "%08X: ", i);
  90272. for(j = 0; j < br->bytes*8; j++)
  90273. if(i < br->consumed_words || (i == br->consumed_words && j < br->consumed_bits))
  90274. fprintf(out, ".");
  90275. else
  90276. fprintf(out, "%01u", br->buffer[i] & (1 << (br->bytes*8-j-1)) ? 1:0);
  90277. fprintf(out, "\n");
  90278. }
  90279. }
  90280. }
  90281. void FLAC__bitreader_reset_read_crc16(FLAC__BitReader *br, FLAC__uint16 seed)
  90282. {
  90283. FLAC__ASSERT(0 != br);
  90284. FLAC__ASSERT(0 != br->buffer);
  90285. FLAC__ASSERT((br->consumed_bits & 7) == 0);
  90286. br->read_crc16 = (unsigned)seed;
  90287. br->crc16_align = br->consumed_bits;
  90288. }
  90289. FLAC__uint16 FLAC__bitreader_get_read_crc16(FLAC__BitReader *br)
  90290. {
  90291. FLAC__ASSERT(0 != br);
  90292. FLAC__ASSERT(0 != br->buffer);
  90293. FLAC__ASSERT((br->consumed_bits & 7) == 0);
  90294. FLAC__ASSERT(br->crc16_align <= br->consumed_bits);
  90295. /* CRC any tail bytes in a partially-consumed word */
  90296. if(br->consumed_bits) {
  90297. const brword tail = br->buffer[br->consumed_words];
  90298. for( ; br->crc16_align < br->consumed_bits; br->crc16_align += 8)
  90299. br->read_crc16 = FLAC__CRC16_UPDATE((unsigned)((tail >> (FLAC__BITS_PER_WORD-8-br->crc16_align)) & 0xff), br->read_crc16);
  90300. }
  90301. return br->read_crc16;
  90302. }
  90303. FLaC__INLINE FLAC__bool FLAC__bitreader_is_consumed_byte_aligned(const FLAC__BitReader *br)
  90304. {
  90305. return ((br->consumed_bits & 7) == 0);
  90306. }
  90307. FLaC__INLINE unsigned FLAC__bitreader_bits_left_for_byte_alignment(const FLAC__BitReader *br)
  90308. {
  90309. return 8 - (br->consumed_bits & 7);
  90310. }
  90311. FLaC__INLINE unsigned FLAC__bitreader_get_input_bits_unconsumed(const FLAC__BitReader *br)
  90312. {
  90313. return (br->words-br->consumed_words)*FLAC__BITS_PER_WORD + br->bytes*8 - br->consumed_bits;
  90314. }
  90315. FLaC__INLINE FLAC__bool FLAC__bitreader_read_raw_uint32(FLAC__BitReader *br, FLAC__uint32 *val, unsigned bits)
  90316. {
  90317. FLAC__ASSERT(0 != br);
  90318. FLAC__ASSERT(0 != br->buffer);
  90319. FLAC__ASSERT(bits <= 32);
  90320. FLAC__ASSERT((br->capacity*FLAC__BITS_PER_WORD) * 2 >= bits);
  90321. FLAC__ASSERT(br->consumed_words <= br->words);
  90322. /* WATCHOUT: code does not work with <32bit words; we can make things much faster with this assertion */
  90323. FLAC__ASSERT(FLAC__BITS_PER_WORD >= 32);
  90324. if(bits == 0) { /* OPT: investigate if this can ever happen, maybe change to assertion */
  90325. *val = 0;
  90326. return true;
  90327. }
  90328. while((br->words-br->consumed_words)*FLAC__BITS_PER_WORD + br->bytes*8 - br->consumed_bits < bits) {
  90329. if(!bitreader_read_from_client_(br))
  90330. return false;
  90331. }
  90332. if(br->consumed_words < br->words) { /* if we've not consumed up to a partial tail word... */
  90333. /* OPT: taking out the consumed_bits==0 "else" case below might make things faster if less code allows the compiler to inline this function */
  90334. if(br->consumed_bits) {
  90335. /* this also works when consumed_bits==0, it's just a little slower than necessary for that case */
  90336. const unsigned n = FLAC__BITS_PER_WORD - br->consumed_bits;
  90337. const brword word = br->buffer[br->consumed_words];
  90338. if(bits < n) {
  90339. *val = (word & (FLAC__WORD_ALL_ONES >> br->consumed_bits)) >> (n-bits);
  90340. br->consumed_bits += bits;
  90341. return true;
  90342. }
  90343. *val = word & (FLAC__WORD_ALL_ONES >> br->consumed_bits);
  90344. bits -= n;
  90345. crc16_update_word_(br, word);
  90346. br->consumed_words++;
  90347. br->consumed_bits = 0;
  90348. 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 */
  90349. *val <<= bits;
  90350. *val |= (br->buffer[br->consumed_words] >> (FLAC__BITS_PER_WORD-bits));
  90351. br->consumed_bits = bits;
  90352. }
  90353. return true;
  90354. }
  90355. else {
  90356. const brword word = br->buffer[br->consumed_words];
  90357. if(bits < FLAC__BITS_PER_WORD) {
  90358. *val = word >> (FLAC__BITS_PER_WORD-bits);
  90359. br->consumed_bits = bits;
  90360. return true;
  90361. }
  90362. /* at this point 'bits' must be == FLAC__BITS_PER_WORD; because of previous assertions, it can't be larger */
  90363. *val = word;
  90364. crc16_update_word_(br, word);
  90365. br->consumed_words++;
  90366. return true;
  90367. }
  90368. }
  90369. else {
  90370. /* in this case we're starting our read at a partial tail word;
  90371. * the reader has guaranteed that we have at least 'bits' bits
  90372. * available to read, which makes this case simpler.
  90373. */
  90374. /* OPT: taking out the consumed_bits==0 "else" case below might make things faster if less code allows the compiler to inline this function */
  90375. if(br->consumed_bits) {
  90376. /* this also works when consumed_bits==0, it's just a little slower than necessary for that case */
  90377. FLAC__ASSERT(br->consumed_bits + bits <= br->bytes*8);
  90378. *val = (br->buffer[br->consumed_words] & (FLAC__WORD_ALL_ONES >> br->consumed_bits)) >> (FLAC__BITS_PER_WORD-br->consumed_bits-bits);
  90379. br->consumed_bits += bits;
  90380. return true;
  90381. }
  90382. else {
  90383. *val = br->buffer[br->consumed_words] >> (FLAC__BITS_PER_WORD-bits);
  90384. br->consumed_bits += bits;
  90385. return true;
  90386. }
  90387. }
  90388. }
  90389. FLAC__bool FLAC__bitreader_read_raw_int32(FLAC__BitReader *br, FLAC__int32 *val, unsigned bits)
  90390. {
  90391. /* OPT: inline raw uint32 code here, or make into a macro if possible in the .h file */
  90392. if(!FLAC__bitreader_read_raw_uint32(br, (FLAC__uint32*)val, bits))
  90393. return false;
  90394. /* sign-extend: */
  90395. *val <<= (32-bits);
  90396. *val >>= (32-bits);
  90397. return true;
  90398. }
  90399. FLAC__bool FLAC__bitreader_read_raw_uint64(FLAC__BitReader *br, FLAC__uint64 *val, unsigned bits)
  90400. {
  90401. FLAC__uint32 hi, lo;
  90402. if(bits > 32) {
  90403. if(!FLAC__bitreader_read_raw_uint32(br, &hi, bits-32))
  90404. return false;
  90405. if(!FLAC__bitreader_read_raw_uint32(br, &lo, 32))
  90406. return false;
  90407. *val = hi;
  90408. *val <<= 32;
  90409. *val |= lo;
  90410. }
  90411. else {
  90412. if(!FLAC__bitreader_read_raw_uint32(br, &lo, bits))
  90413. return false;
  90414. *val = lo;
  90415. }
  90416. return true;
  90417. }
  90418. FLaC__INLINE FLAC__bool FLAC__bitreader_read_uint32_little_endian(FLAC__BitReader *br, FLAC__uint32 *val)
  90419. {
  90420. FLAC__uint32 x8, x32 = 0;
  90421. /* this doesn't need to be that fast as currently it is only used for vorbis comments */
  90422. if(!FLAC__bitreader_read_raw_uint32(br, &x32, 8))
  90423. return false;
  90424. if(!FLAC__bitreader_read_raw_uint32(br, &x8, 8))
  90425. return false;
  90426. x32 |= (x8 << 8);
  90427. if(!FLAC__bitreader_read_raw_uint32(br, &x8, 8))
  90428. return false;
  90429. x32 |= (x8 << 16);
  90430. if(!FLAC__bitreader_read_raw_uint32(br, &x8, 8))
  90431. return false;
  90432. x32 |= (x8 << 24);
  90433. *val = x32;
  90434. return true;
  90435. }
  90436. FLAC__bool FLAC__bitreader_skip_bits_no_crc(FLAC__BitReader *br, unsigned bits)
  90437. {
  90438. /*
  90439. * OPT: a faster implementation is possible but probably not that useful
  90440. * since this is only called a couple of times in the metadata readers.
  90441. */
  90442. FLAC__ASSERT(0 != br);
  90443. FLAC__ASSERT(0 != br->buffer);
  90444. if(bits > 0) {
  90445. const unsigned n = br->consumed_bits & 7;
  90446. unsigned m;
  90447. FLAC__uint32 x;
  90448. if(n != 0) {
  90449. m = min(8-n, bits);
  90450. if(!FLAC__bitreader_read_raw_uint32(br, &x, m))
  90451. return false;
  90452. bits -= m;
  90453. }
  90454. m = bits / 8;
  90455. if(m > 0) {
  90456. if(!FLAC__bitreader_skip_byte_block_aligned_no_crc(br, m))
  90457. return false;
  90458. bits %= 8;
  90459. }
  90460. if(bits > 0) {
  90461. if(!FLAC__bitreader_read_raw_uint32(br, &x, bits))
  90462. return false;
  90463. }
  90464. }
  90465. return true;
  90466. }
  90467. FLAC__bool FLAC__bitreader_skip_byte_block_aligned_no_crc(FLAC__BitReader *br, unsigned nvals)
  90468. {
  90469. FLAC__uint32 x;
  90470. FLAC__ASSERT(0 != br);
  90471. FLAC__ASSERT(0 != br->buffer);
  90472. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(br));
  90473. /* step 1: skip over partial head word to get word aligned */
  90474. while(nvals && br->consumed_bits) { /* i.e. run until we read 'nvals' bytes or we hit the end of the head word */
  90475. if(!FLAC__bitreader_read_raw_uint32(br, &x, 8))
  90476. return false;
  90477. nvals--;
  90478. }
  90479. if(0 == nvals)
  90480. return true;
  90481. /* step 2: skip whole words in chunks */
  90482. while(nvals >= FLAC__BYTES_PER_WORD) {
  90483. if(br->consumed_words < br->words) {
  90484. br->consumed_words++;
  90485. nvals -= FLAC__BYTES_PER_WORD;
  90486. }
  90487. else if(!bitreader_read_from_client_(br))
  90488. return false;
  90489. }
  90490. /* step 3: skip any remainder from partial tail bytes */
  90491. while(nvals) {
  90492. if(!FLAC__bitreader_read_raw_uint32(br, &x, 8))
  90493. return false;
  90494. nvals--;
  90495. }
  90496. return true;
  90497. }
  90498. FLAC__bool FLAC__bitreader_read_byte_block_aligned_no_crc(FLAC__BitReader *br, FLAC__byte *val, unsigned nvals)
  90499. {
  90500. FLAC__uint32 x;
  90501. FLAC__ASSERT(0 != br);
  90502. FLAC__ASSERT(0 != br->buffer);
  90503. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(br));
  90504. /* step 1: read from partial head word to get word aligned */
  90505. while(nvals && br->consumed_bits) { /* i.e. run until we read 'nvals' bytes or we hit the end of the head word */
  90506. if(!FLAC__bitreader_read_raw_uint32(br, &x, 8))
  90507. return false;
  90508. *val++ = (FLAC__byte)x;
  90509. nvals--;
  90510. }
  90511. if(0 == nvals)
  90512. return true;
  90513. /* step 2: read whole words in chunks */
  90514. while(nvals >= FLAC__BYTES_PER_WORD) {
  90515. if(br->consumed_words < br->words) {
  90516. const brword word = br->buffer[br->consumed_words++];
  90517. #if FLAC__BYTES_PER_WORD == 4
  90518. val[0] = (FLAC__byte)(word >> 24);
  90519. val[1] = (FLAC__byte)(word >> 16);
  90520. val[2] = (FLAC__byte)(word >> 8);
  90521. val[3] = (FLAC__byte)word;
  90522. #elif FLAC__BYTES_PER_WORD == 8
  90523. val[0] = (FLAC__byte)(word >> 56);
  90524. val[1] = (FLAC__byte)(word >> 48);
  90525. val[2] = (FLAC__byte)(word >> 40);
  90526. val[3] = (FLAC__byte)(word >> 32);
  90527. val[4] = (FLAC__byte)(word >> 24);
  90528. val[5] = (FLAC__byte)(word >> 16);
  90529. val[6] = (FLAC__byte)(word >> 8);
  90530. val[7] = (FLAC__byte)word;
  90531. #else
  90532. for(x = 0; x < FLAC__BYTES_PER_WORD; x++)
  90533. val[x] = (FLAC__byte)(word >> (8*(FLAC__BYTES_PER_WORD-x-1)));
  90534. #endif
  90535. val += FLAC__BYTES_PER_WORD;
  90536. nvals -= FLAC__BYTES_PER_WORD;
  90537. }
  90538. else if(!bitreader_read_from_client_(br))
  90539. return false;
  90540. }
  90541. /* step 3: read any remainder from partial tail bytes */
  90542. while(nvals) {
  90543. if(!FLAC__bitreader_read_raw_uint32(br, &x, 8))
  90544. return false;
  90545. *val++ = (FLAC__byte)x;
  90546. nvals--;
  90547. }
  90548. return true;
  90549. }
  90550. FLaC__INLINE FLAC__bool FLAC__bitreader_read_unary_unsigned(FLAC__BitReader *br, unsigned *val)
  90551. #if 0 /* slow but readable version */
  90552. {
  90553. unsigned bit;
  90554. FLAC__ASSERT(0 != br);
  90555. FLAC__ASSERT(0 != br->buffer);
  90556. *val = 0;
  90557. while(1) {
  90558. if(!FLAC__bitreader_read_bit(br, &bit))
  90559. return false;
  90560. if(bit)
  90561. break;
  90562. else
  90563. *val++;
  90564. }
  90565. return true;
  90566. }
  90567. #else
  90568. {
  90569. unsigned i;
  90570. FLAC__ASSERT(0 != br);
  90571. FLAC__ASSERT(0 != br->buffer);
  90572. *val = 0;
  90573. while(1) {
  90574. while(br->consumed_words < br->words) { /* if we've not consumed up to a partial tail word... */
  90575. brword b = br->buffer[br->consumed_words] << br->consumed_bits;
  90576. if(b) {
  90577. i = COUNT_ZERO_MSBS(b);
  90578. *val += i;
  90579. i++;
  90580. br->consumed_bits += i;
  90581. if(br->consumed_bits >= FLAC__BITS_PER_WORD) { /* faster way of testing if(br->consumed_bits == FLAC__BITS_PER_WORD) */
  90582. crc16_update_word_(br, br->buffer[br->consumed_words]);
  90583. br->consumed_words++;
  90584. br->consumed_bits = 0;
  90585. }
  90586. return true;
  90587. }
  90588. else {
  90589. *val += FLAC__BITS_PER_WORD - br->consumed_bits;
  90590. crc16_update_word_(br, br->buffer[br->consumed_words]);
  90591. br->consumed_words++;
  90592. br->consumed_bits = 0;
  90593. /* didn't find stop bit yet, have to keep going... */
  90594. }
  90595. }
  90596. /* at this point we've eaten up all the whole words; have to try
  90597. * reading through any tail bytes before calling the read callback.
  90598. * this is a repeat of the above logic adjusted for the fact we
  90599. * don't have a whole word. note though if the client is feeding
  90600. * us data a byte at a time (unlikely), br->consumed_bits may not
  90601. * be zero.
  90602. */
  90603. if(br->bytes) {
  90604. const unsigned end = br->bytes * 8;
  90605. brword b = (br->buffer[br->consumed_words] & (FLAC__WORD_ALL_ONES << (FLAC__BITS_PER_WORD-end))) << br->consumed_bits;
  90606. if(b) {
  90607. i = COUNT_ZERO_MSBS(b);
  90608. *val += i;
  90609. i++;
  90610. br->consumed_bits += i;
  90611. FLAC__ASSERT(br->consumed_bits < FLAC__BITS_PER_WORD);
  90612. return true;
  90613. }
  90614. else {
  90615. *val += end - br->consumed_bits;
  90616. br->consumed_bits += end;
  90617. FLAC__ASSERT(br->consumed_bits < FLAC__BITS_PER_WORD);
  90618. /* didn't find stop bit yet, have to keep going... */
  90619. }
  90620. }
  90621. if(!bitreader_read_from_client_(br))
  90622. return false;
  90623. }
  90624. }
  90625. #endif
  90626. FLAC__bool FLAC__bitreader_read_rice_signed(FLAC__BitReader *br, int *val, unsigned parameter)
  90627. {
  90628. FLAC__uint32 lsbs = 0, msbs = 0;
  90629. unsigned uval;
  90630. FLAC__ASSERT(0 != br);
  90631. FLAC__ASSERT(0 != br->buffer);
  90632. FLAC__ASSERT(parameter <= 31);
  90633. /* read the unary MSBs and end bit */
  90634. if(!FLAC__bitreader_read_unary_unsigned(br, (unsigned int*) &msbs))
  90635. return false;
  90636. /* read the binary LSBs */
  90637. if(!FLAC__bitreader_read_raw_uint32(br, &lsbs, parameter))
  90638. return false;
  90639. /* compose the value */
  90640. uval = (msbs << parameter) | lsbs;
  90641. if(uval & 1)
  90642. *val = -((int)(uval >> 1)) - 1;
  90643. else
  90644. *val = (int)(uval >> 1);
  90645. return true;
  90646. }
  90647. /* this is by far the most heavily used reader call. it ain't pretty but it's fast */
  90648. /* a lot of the logic is copied, then adapted, from FLAC__bitreader_read_unary_unsigned() and FLAC__bitreader_read_raw_uint32() */
  90649. FLAC__bool FLAC__bitreader_read_rice_signed_block(FLAC__BitReader *br, int vals[], unsigned nvals, unsigned parameter)
  90650. /* OPT: possibly faster version for use with MSVC */
  90651. #ifdef _MSC_VER
  90652. {
  90653. unsigned i;
  90654. unsigned uval = 0;
  90655. unsigned bits; /* the # of binary LSBs left to read to finish a rice codeword */
  90656. /* try and get br->consumed_words and br->consumed_bits into register;
  90657. * must remember to flush them back to *br before calling other
  90658. * bitwriter functions that use them, and before returning */
  90659. register unsigned cwords;
  90660. register unsigned cbits;
  90661. FLAC__ASSERT(0 != br);
  90662. FLAC__ASSERT(0 != br->buffer);
  90663. /* WATCHOUT: code does not work with <32bit words; we can make things much faster with this assertion */
  90664. FLAC__ASSERT(FLAC__BITS_PER_WORD >= 32);
  90665. FLAC__ASSERT(parameter < 32);
  90666. /* 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 */
  90667. if(nvals == 0)
  90668. return true;
  90669. cbits = br->consumed_bits;
  90670. cwords = br->consumed_words;
  90671. while(1) {
  90672. /* read unary part */
  90673. while(1) {
  90674. while(cwords < br->words) { /* if we've not consumed up to a partial tail word... */
  90675. brword b = br->buffer[cwords] << cbits;
  90676. if(b) {
  90677. #if 0 /* slower, probably due to bad register allocation... */ && defined FLAC__CPU_IA32 && !defined FLAC__NO_ASM && FLAC__BITS_PER_WORD == 32
  90678. __asm {
  90679. bsr eax, b
  90680. not eax
  90681. and eax, 31
  90682. mov i, eax
  90683. }
  90684. #else
  90685. i = COUNT_ZERO_MSBS(b);
  90686. #endif
  90687. uval += i;
  90688. bits = parameter;
  90689. i++;
  90690. cbits += i;
  90691. if(cbits == FLAC__BITS_PER_WORD) {
  90692. crc16_update_word_(br, br->buffer[cwords]);
  90693. cwords++;
  90694. cbits = 0;
  90695. }
  90696. goto break1;
  90697. }
  90698. else {
  90699. uval += FLAC__BITS_PER_WORD - cbits;
  90700. crc16_update_word_(br, br->buffer[cwords]);
  90701. cwords++;
  90702. cbits = 0;
  90703. /* didn't find stop bit yet, have to keep going... */
  90704. }
  90705. }
  90706. /* at this point we've eaten up all the whole words; have to try
  90707. * reading through any tail bytes before calling the read callback.
  90708. * this is a repeat of the above logic adjusted for the fact we
  90709. * don't have a whole word. note though if the client is feeding
  90710. * us data a byte at a time (unlikely), br->consumed_bits may not
  90711. * be zero.
  90712. */
  90713. if(br->bytes) {
  90714. const unsigned end = br->bytes * 8;
  90715. brword b = (br->buffer[cwords] & (FLAC__WORD_ALL_ONES << (FLAC__BITS_PER_WORD-end))) << cbits;
  90716. if(b) {
  90717. i = COUNT_ZERO_MSBS(b);
  90718. uval += i;
  90719. bits = parameter;
  90720. i++;
  90721. cbits += i;
  90722. FLAC__ASSERT(cbits < FLAC__BITS_PER_WORD);
  90723. goto break1;
  90724. }
  90725. else {
  90726. uval += end - cbits;
  90727. cbits += end;
  90728. FLAC__ASSERT(cbits < FLAC__BITS_PER_WORD);
  90729. /* didn't find stop bit yet, have to keep going... */
  90730. }
  90731. }
  90732. /* flush registers and read; bitreader_read_from_client_() does
  90733. * not touch br->consumed_bits at all but we still need to set
  90734. * it in case it fails and we have to return false.
  90735. */
  90736. br->consumed_bits = cbits;
  90737. br->consumed_words = cwords;
  90738. if(!bitreader_read_from_client_(br))
  90739. return false;
  90740. cwords = br->consumed_words;
  90741. }
  90742. break1:
  90743. /* read binary part */
  90744. FLAC__ASSERT(cwords <= br->words);
  90745. if(bits) {
  90746. while((br->words-cwords)*FLAC__BITS_PER_WORD + br->bytes*8 - cbits < bits) {
  90747. /* flush registers and read; bitreader_read_from_client_() does
  90748. * not touch br->consumed_bits at all but we still need to set
  90749. * it in case it fails and we have to return false.
  90750. */
  90751. br->consumed_bits = cbits;
  90752. br->consumed_words = cwords;
  90753. if(!bitreader_read_from_client_(br))
  90754. return false;
  90755. cwords = br->consumed_words;
  90756. }
  90757. if(cwords < br->words) { /* if we've not consumed up to a partial tail word... */
  90758. if(cbits) {
  90759. /* this also works when consumed_bits==0, it's just a little slower than necessary for that case */
  90760. const unsigned n = FLAC__BITS_PER_WORD - cbits;
  90761. const brword word = br->buffer[cwords];
  90762. if(bits < n) {
  90763. uval <<= bits;
  90764. uval |= (word & (FLAC__WORD_ALL_ONES >> cbits)) >> (n-bits);
  90765. cbits += bits;
  90766. goto break2;
  90767. }
  90768. uval <<= n;
  90769. uval |= word & (FLAC__WORD_ALL_ONES >> cbits);
  90770. bits -= n;
  90771. crc16_update_word_(br, word);
  90772. cwords++;
  90773. cbits = 0;
  90774. 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 */
  90775. uval <<= bits;
  90776. uval |= (br->buffer[cwords] >> (FLAC__BITS_PER_WORD-bits));
  90777. cbits = bits;
  90778. }
  90779. goto break2;
  90780. }
  90781. else {
  90782. FLAC__ASSERT(bits < FLAC__BITS_PER_WORD);
  90783. uval <<= bits;
  90784. uval |= br->buffer[cwords] >> (FLAC__BITS_PER_WORD-bits);
  90785. cbits = bits;
  90786. goto break2;
  90787. }
  90788. }
  90789. else {
  90790. /* in this case we're starting our read at a partial tail word;
  90791. * the reader has guaranteed that we have at least 'bits' bits
  90792. * available to read, which makes this case simpler.
  90793. */
  90794. uval <<= bits;
  90795. if(cbits) {
  90796. /* this also works when consumed_bits==0, it's just a little slower than necessary for that case */
  90797. FLAC__ASSERT(cbits + bits <= br->bytes*8);
  90798. uval |= (br->buffer[cwords] & (FLAC__WORD_ALL_ONES >> cbits)) >> (FLAC__BITS_PER_WORD-cbits-bits);
  90799. cbits += bits;
  90800. goto break2;
  90801. }
  90802. else {
  90803. uval |= br->buffer[cwords] >> (FLAC__BITS_PER_WORD-bits);
  90804. cbits += bits;
  90805. goto break2;
  90806. }
  90807. }
  90808. }
  90809. break2:
  90810. /* compose the value */
  90811. *vals = (int)(uval >> 1 ^ -(int)(uval & 1));
  90812. /* are we done? */
  90813. --nvals;
  90814. if(nvals == 0) {
  90815. br->consumed_bits = cbits;
  90816. br->consumed_words = cwords;
  90817. return true;
  90818. }
  90819. uval = 0;
  90820. ++vals;
  90821. }
  90822. }
  90823. #else
  90824. {
  90825. unsigned i;
  90826. unsigned uval = 0;
  90827. /* try and get br->consumed_words and br->consumed_bits into register;
  90828. * must remember to flush them back to *br before calling other
  90829. * bitwriter functions that use them, and before returning */
  90830. register unsigned cwords;
  90831. register unsigned cbits;
  90832. unsigned ucbits; /* keep track of the number of unconsumed bits in the buffer */
  90833. FLAC__ASSERT(0 != br);
  90834. FLAC__ASSERT(0 != br->buffer);
  90835. /* WATCHOUT: code does not work with <32bit words; we can make things much faster with this assertion */
  90836. FLAC__ASSERT(FLAC__BITS_PER_WORD >= 32);
  90837. FLAC__ASSERT(parameter < 32);
  90838. /* 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 */
  90839. if(nvals == 0)
  90840. return true;
  90841. cbits = br->consumed_bits;
  90842. cwords = br->consumed_words;
  90843. ucbits = (br->words-cwords)*FLAC__BITS_PER_WORD + br->bytes*8 - cbits;
  90844. while(1) {
  90845. /* read unary part */
  90846. while(1) {
  90847. while(cwords < br->words) { /* if we've not consumed up to a partial tail word... */
  90848. brword b = br->buffer[cwords] << cbits;
  90849. if(b) {
  90850. #if 0 /* is not discernably faster... */ && defined FLAC__CPU_IA32 && !defined FLAC__NO_ASM && FLAC__BITS_PER_WORD == 32 && defined __GNUC__
  90851. asm volatile (
  90852. "bsrl %1, %0;"
  90853. "notl %0;"
  90854. "andl $31, %0;"
  90855. : "=r"(i)
  90856. : "r"(b)
  90857. );
  90858. #else
  90859. i = COUNT_ZERO_MSBS(b);
  90860. #endif
  90861. uval += i;
  90862. cbits += i;
  90863. cbits++; /* skip over stop bit */
  90864. if(cbits >= FLAC__BITS_PER_WORD) { /* faster way of testing if(cbits == FLAC__BITS_PER_WORD) */
  90865. crc16_update_word_(br, br->buffer[cwords]);
  90866. cwords++;
  90867. cbits = 0;
  90868. }
  90869. goto break1;
  90870. }
  90871. else {
  90872. uval += FLAC__BITS_PER_WORD - cbits;
  90873. crc16_update_word_(br, br->buffer[cwords]);
  90874. cwords++;
  90875. cbits = 0;
  90876. /* didn't find stop bit yet, have to keep going... */
  90877. }
  90878. }
  90879. /* at this point we've eaten up all the whole words; have to try
  90880. * reading through any tail bytes before calling the read callback.
  90881. * this is a repeat of the above logic adjusted for the fact we
  90882. * don't have a whole word. note though if the client is feeding
  90883. * us data a byte at a time (unlikely), br->consumed_bits may not
  90884. * be zero.
  90885. */
  90886. if(br->bytes) {
  90887. const unsigned end = br->bytes * 8;
  90888. brword b = (br->buffer[cwords] & ~(FLAC__WORD_ALL_ONES >> end)) << cbits;
  90889. if(b) {
  90890. i = COUNT_ZERO_MSBS(b);
  90891. uval += i;
  90892. cbits += i;
  90893. cbits++; /* skip over stop bit */
  90894. FLAC__ASSERT(cbits < FLAC__BITS_PER_WORD);
  90895. goto break1;
  90896. }
  90897. else {
  90898. uval += end - cbits;
  90899. cbits += end;
  90900. FLAC__ASSERT(cbits < FLAC__BITS_PER_WORD);
  90901. /* didn't find stop bit yet, have to keep going... */
  90902. }
  90903. }
  90904. /* flush registers and read; bitreader_read_from_client_() does
  90905. * not touch br->consumed_bits at all but we still need to set
  90906. * it in case it fails and we have to return false.
  90907. */
  90908. br->consumed_bits = cbits;
  90909. br->consumed_words = cwords;
  90910. if(!bitreader_read_from_client_(br))
  90911. return false;
  90912. cwords = br->consumed_words;
  90913. ucbits = (br->words-cwords)*FLAC__BITS_PER_WORD + br->bytes*8 - cbits + uval;
  90914. /* + uval to offset our count by the # of unary bits already
  90915. * consumed before the read, because we will add these back
  90916. * in all at once at break1
  90917. */
  90918. }
  90919. break1:
  90920. ucbits -= uval;
  90921. ucbits--; /* account for stop bit */
  90922. /* read binary part */
  90923. FLAC__ASSERT(cwords <= br->words);
  90924. if(parameter) {
  90925. while(ucbits < parameter) {
  90926. /* flush registers and read; bitreader_read_from_client_() does
  90927. * not touch br->consumed_bits at all but we still need to set
  90928. * it in case it fails and we have to return false.
  90929. */
  90930. br->consumed_bits = cbits;
  90931. br->consumed_words = cwords;
  90932. if(!bitreader_read_from_client_(br))
  90933. return false;
  90934. cwords = br->consumed_words;
  90935. ucbits = (br->words-cwords)*FLAC__BITS_PER_WORD + br->bytes*8 - cbits;
  90936. }
  90937. if(cwords < br->words) { /* if we've not consumed up to a partial tail word... */
  90938. if(cbits) {
  90939. /* this also works when consumed_bits==0, it's just slower than necessary for that case */
  90940. const unsigned n = FLAC__BITS_PER_WORD - cbits;
  90941. const brword word = br->buffer[cwords];
  90942. if(parameter < n) {
  90943. uval <<= parameter;
  90944. uval |= (word & (FLAC__WORD_ALL_ONES >> cbits)) >> (n-parameter);
  90945. cbits += parameter;
  90946. }
  90947. else {
  90948. uval <<= n;
  90949. uval |= word & (FLAC__WORD_ALL_ONES >> cbits);
  90950. crc16_update_word_(br, word);
  90951. cwords++;
  90952. cbits = parameter - n;
  90953. 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 */
  90954. uval <<= cbits;
  90955. uval |= (br->buffer[cwords] >> (FLAC__BITS_PER_WORD-cbits));
  90956. }
  90957. }
  90958. }
  90959. else {
  90960. cbits = parameter;
  90961. uval <<= parameter;
  90962. uval |= br->buffer[cwords] >> (FLAC__BITS_PER_WORD-cbits);
  90963. }
  90964. }
  90965. else {
  90966. /* in this case we're starting our read at a partial tail word;
  90967. * the reader has guaranteed that we have at least 'parameter'
  90968. * bits available to read, which makes this case simpler.
  90969. */
  90970. uval <<= parameter;
  90971. if(cbits) {
  90972. /* this also works when consumed_bits==0, it's just a little slower than necessary for that case */
  90973. FLAC__ASSERT(cbits + parameter <= br->bytes*8);
  90974. uval |= (br->buffer[cwords] & (FLAC__WORD_ALL_ONES >> cbits)) >> (FLAC__BITS_PER_WORD-cbits-parameter);
  90975. cbits += parameter;
  90976. }
  90977. else {
  90978. cbits = parameter;
  90979. uval |= br->buffer[cwords] >> (FLAC__BITS_PER_WORD-cbits);
  90980. }
  90981. }
  90982. }
  90983. ucbits -= parameter;
  90984. /* compose the value */
  90985. *vals = (int)(uval >> 1 ^ -(int)(uval & 1));
  90986. /* are we done? */
  90987. --nvals;
  90988. if(nvals == 0) {
  90989. br->consumed_bits = cbits;
  90990. br->consumed_words = cwords;
  90991. return true;
  90992. }
  90993. uval = 0;
  90994. ++vals;
  90995. }
  90996. }
  90997. #endif
  90998. #if 0 /* UNUSED */
  90999. FLAC__bool FLAC__bitreader_read_golomb_signed(FLAC__BitReader *br, int *val, unsigned parameter)
  91000. {
  91001. FLAC__uint32 lsbs = 0, msbs = 0;
  91002. unsigned bit, uval, k;
  91003. FLAC__ASSERT(0 != br);
  91004. FLAC__ASSERT(0 != br->buffer);
  91005. k = FLAC__bitmath_ilog2(parameter);
  91006. /* read the unary MSBs and end bit */
  91007. if(!FLAC__bitreader_read_unary_unsigned(br, &msbs))
  91008. return false;
  91009. /* read the binary LSBs */
  91010. if(!FLAC__bitreader_read_raw_uint32(br, &lsbs, k))
  91011. return false;
  91012. if(parameter == 1u<<k) {
  91013. /* compose the value */
  91014. uval = (msbs << k) | lsbs;
  91015. }
  91016. else {
  91017. unsigned d = (1 << (k+1)) - parameter;
  91018. if(lsbs >= d) {
  91019. if(!FLAC__bitreader_read_bit(br, &bit))
  91020. return false;
  91021. lsbs <<= 1;
  91022. lsbs |= bit;
  91023. lsbs -= d;
  91024. }
  91025. /* compose the value */
  91026. uval = msbs * parameter + lsbs;
  91027. }
  91028. /* unfold unsigned to signed */
  91029. if(uval & 1)
  91030. *val = -((int)(uval >> 1)) - 1;
  91031. else
  91032. *val = (int)(uval >> 1);
  91033. return true;
  91034. }
  91035. FLAC__bool FLAC__bitreader_read_golomb_unsigned(FLAC__BitReader *br, unsigned *val, unsigned parameter)
  91036. {
  91037. FLAC__uint32 lsbs, msbs = 0;
  91038. unsigned bit, k;
  91039. FLAC__ASSERT(0 != br);
  91040. FLAC__ASSERT(0 != br->buffer);
  91041. k = FLAC__bitmath_ilog2(parameter);
  91042. /* read the unary MSBs and end bit */
  91043. if(!FLAC__bitreader_read_unary_unsigned(br, &msbs))
  91044. return false;
  91045. /* read the binary LSBs */
  91046. if(!FLAC__bitreader_read_raw_uint32(br, &lsbs, k))
  91047. return false;
  91048. if(parameter == 1u<<k) {
  91049. /* compose the value */
  91050. *val = (msbs << k) | lsbs;
  91051. }
  91052. else {
  91053. unsigned d = (1 << (k+1)) - parameter;
  91054. if(lsbs >= d) {
  91055. if(!FLAC__bitreader_read_bit(br, &bit))
  91056. return false;
  91057. lsbs <<= 1;
  91058. lsbs |= bit;
  91059. lsbs -= d;
  91060. }
  91061. /* compose the value */
  91062. *val = msbs * parameter + lsbs;
  91063. }
  91064. return true;
  91065. }
  91066. #endif /* UNUSED */
  91067. /* on return, if *val == 0xffffffff then the utf-8 sequence was invalid, but the return value will be true */
  91068. FLAC__bool FLAC__bitreader_read_utf8_uint32(FLAC__BitReader *br, FLAC__uint32 *val, FLAC__byte *raw, unsigned *rawlen)
  91069. {
  91070. FLAC__uint32 v = 0;
  91071. FLAC__uint32 x;
  91072. unsigned i;
  91073. if(!FLAC__bitreader_read_raw_uint32(br, &x, 8))
  91074. return false;
  91075. if(raw)
  91076. raw[(*rawlen)++] = (FLAC__byte)x;
  91077. if(!(x & 0x80)) { /* 0xxxxxxx */
  91078. v = x;
  91079. i = 0;
  91080. }
  91081. else if(x & 0xC0 && !(x & 0x20)) { /* 110xxxxx */
  91082. v = x & 0x1F;
  91083. i = 1;
  91084. }
  91085. else if(x & 0xE0 && !(x & 0x10)) { /* 1110xxxx */
  91086. v = x & 0x0F;
  91087. i = 2;
  91088. }
  91089. else if(x & 0xF0 && !(x & 0x08)) { /* 11110xxx */
  91090. v = x & 0x07;
  91091. i = 3;
  91092. }
  91093. else if(x & 0xF8 && !(x & 0x04)) { /* 111110xx */
  91094. v = x & 0x03;
  91095. i = 4;
  91096. }
  91097. else if(x & 0xFC && !(x & 0x02)) { /* 1111110x */
  91098. v = x & 0x01;
  91099. i = 5;
  91100. }
  91101. else {
  91102. *val = 0xffffffff;
  91103. return true;
  91104. }
  91105. for( ; i; i--) {
  91106. if(!FLAC__bitreader_read_raw_uint32(br, &x, 8))
  91107. return false;
  91108. if(raw)
  91109. raw[(*rawlen)++] = (FLAC__byte)x;
  91110. if(!(x & 0x80) || (x & 0x40)) { /* 10xxxxxx */
  91111. *val = 0xffffffff;
  91112. return true;
  91113. }
  91114. v <<= 6;
  91115. v |= (x & 0x3F);
  91116. }
  91117. *val = v;
  91118. return true;
  91119. }
  91120. /* on return, if *val == 0xffffffffffffffff then the utf-8 sequence was invalid, but the return value will be true */
  91121. FLAC__bool FLAC__bitreader_read_utf8_uint64(FLAC__BitReader *br, FLAC__uint64 *val, FLAC__byte *raw, unsigned *rawlen)
  91122. {
  91123. FLAC__uint64 v = 0;
  91124. FLAC__uint32 x;
  91125. unsigned i;
  91126. if(!FLAC__bitreader_read_raw_uint32(br, &x, 8))
  91127. return false;
  91128. if(raw)
  91129. raw[(*rawlen)++] = (FLAC__byte)x;
  91130. if(!(x & 0x80)) { /* 0xxxxxxx */
  91131. v = x;
  91132. i = 0;
  91133. }
  91134. else if(x & 0xC0 && !(x & 0x20)) { /* 110xxxxx */
  91135. v = x & 0x1F;
  91136. i = 1;
  91137. }
  91138. else if(x & 0xE0 && !(x & 0x10)) { /* 1110xxxx */
  91139. v = x & 0x0F;
  91140. i = 2;
  91141. }
  91142. else if(x & 0xF0 && !(x & 0x08)) { /* 11110xxx */
  91143. v = x & 0x07;
  91144. i = 3;
  91145. }
  91146. else if(x & 0xF8 && !(x & 0x04)) { /* 111110xx */
  91147. v = x & 0x03;
  91148. i = 4;
  91149. }
  91150. else if(x & 0xFC && !(x & 0x02)) { /* 1111110x */
  91151. v = x & 0x01;
  91152. i = 5;
  91153. }
  91154. else if(x & 0xFE && !(x & 0x01)) { /* 11111110 */
  91155. v = 0;
  91156. i = 6;
  91157. }
  91158. else {
  91159. *val = FLAC__U64L(0xffffffffffffffff);
  91160. return true;
  91161. }
  91162. for( ; i; i--) {
  91163. if(!FLAC__bitreader_read_raw_uint32(br, &x, 8))
  91164. return false;
  91165. if(raw)
  91166. raw[(*rawlen)++] = (FLAC__byte)x;
  91167. if(!(x & 0x80) || (x & 0x40)) { /* 10xxxxxx */
  91168. *val = FLAC__U64L(0xffffffffffffffff);
  91169. return true;
  91170. }
  91171. v <<= 6;
  91172. v |= (x & 0x3F);
  91173. }
  91174. *val = v;
  91175. return true;
  91176. }
  91177. #endif
  91178. /*** End of inlined file: bitreader.c ***/
  91179. /*** Start of inlined file: bitwriter.c ***/
  91180. /*** Start of inlined file: juce_FlacHeader.h ***/
  91181. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  91182. // tasks..
  91183. #define VERSION "1.2.1"
  91184. #define FLAC__NO_DLL 1
  91185. #if JUCE_MSVC
  91186. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  91187. #endif
  91188. #if JUCE_MAC
  91189. #define FLAC__SYS_DARWIN 1
  91190. #endif
  91191. /*** End of inlined file: juce_FlacHeader.h ***/
  91192. #if JUCE_USE_FLAC
  91193. #if HAVE_CONFIG_H
  91194. # include <config.h>
  91195. #endif
  91196. #include <stdlib.h> /* for malloc() */
  91197. #include <string.h> /* for memcpy(), memset() */
  91198. #ifdef _MSC_VER
  91199. #include <winsock.h> /* for ntohl() */
  91200. #elif defined FLAC__SYS_DARWIN
  91201. #include <machine/endian.h> /* for ntohl() */
  91202. #elif defined __MINGW32__
  91203. #include <winsock.h> /* for ntohl() */
  91204. #else
  91205. #include <netinet/in.h> /* for ntohl() */
  91206. #endif
  91207. #if 0 /* UNUSED */
  91208. #endif
  91209. /*** Start of inlined file: bitwriter.h ***/
  91210. #ifndef FLAC__PRIVATE__BITWRITER_H
  91211. #define FLAC__PRIVATE__BITWRITER_H
  91212. #include <stdio.h> /* for FILE */
  91213. /*
  91214. * opaque structure definition
  91215. */
  91216. struct FLAC__BitWriter;
  91217. typedef struct FLAC__BitWriter FLAC__BitWriter;
  91218. /*
  91219. * construction, deletion, initialization, etc functions
  91220. */
  91221. FLAC__BitWriter *FLAC__bitwriter_new(void);
  91222. void FLAC__bitwriter_delete(FLAC__BitWriter *bw);
  91223. FLAC__bool FLAC__bitwriter_init(FLAC__BitWriter *bw);
  91224. void FLAC__bitwriter_free(FLAC__BitWriter *bw); /* does not 'free(buffer)' */
  91225. void FLAC__bitwriter_clear(FLAC__BitWriter *bw);
  91226. void FLAC__bitwriter_dump(const FLAC__BitWriter *bw, FILE *out);
  91227. /*
  91228. * CRC functions
  91229. *
  91230. * non-const *bw because they have to cal FLAC__bitwriter_get_buffer()
  91231. */
  91232. FLAC__bool FLAC__bitwriter_get_write_crc16(FLAC__BitWriter *bw, FLAC__uint16 *crc);
  91233. FLAC__bool FLAC__bitwriter_get_write_crc8(FLAC__BitWriter *bw, FLAC__byte *crc);
  91234. /*
  91235. * info functions
  91236. */
  91237. FLAC__bool FLAC__bitwriter_is_byte_aligned(const FLAC__BitWriter *bw);
  91238. unsigned FLAC__bitwriter_get_input_bits_unconsumed(const FLAC__BitWriter *bw); /* can be called anytime, returns total # of bits unconsumed */
  91239. /*
  91240. * direct buffer access
  91241. *
  91242. * there may be no calls on the bitwriter between get and release.
  91243. * the bitwriter continues to own the returned buffer.
  91244. * before get, bitwriter MUST be byte aligned: check with FLAC__bitwriter_is_byte_aligned()
  91245. */
  91246. FLAC__bool FLAC__bitwriter_get_buffer(FLAC__BitWriter *bw, const FLAC__byte **buffer, size_t *bytes);
  91247. void FLAC__bitwriter_release_buffer(FLAC__BitWriter *bw);
  91248. /*
  91249. * write functions
  91250. */
  91251. FLAC__bool FLAC__bitwriter_write_zeroes(FLAC__BitWriter *bw, unsigned bits);
  91252. FLAC__bool FLAC__bitwriter_write_raw_uint32(FLAC__BitWriter *bw, FLAC__uint32 val, unsigned bits);
  91253. FLAC__bool FLAC__bitwriter_write_raw_int32(FLAC__BitWriter *bw, FLAC__int32 val, unsigned bits);
  91254. FLAC__bool FLAC__bitwriter_write_raw_uint64(FLAC__BitWriter *bw, FLAC__uint64 val, unsigned bits);
  91255. FLAC__bool FLAC__bitwriter_write_raw_uint32_little_endian(FLAC__BitWriter *bw, FLAC__uint32 val); /*only for bits=32*/
  91256. FLAC__bool FLAC__bitwriter_write_byte_block(FLAC__BitWriter *bw, const FLAC__byte vals[], unsigned nvals);
  91257. FLAC__bool FLAC__bitwriter_write_unary_unsigned(FLAC__BitWriter *bw, unsigned val);
  91258. unsigned FLAC__bitwriter_rice_bits(FLAC__int32 val, unsigned parameter);
  91259. #if 0 /* UNUSED */
  91260. unsigned FLAC__bitwriter_golomb_bits_signed(int val, unsigned parameter);
  91261. unsigned FLAC__bitwriter_golomb_bits_unsigned(unsigned val, unsigned parameter);
  91262. #endif
  91263. FLAC__bool FLAC__bitwriter_write_rice_signed(FLAC__BitWriter *bw, FLAC__int32 val, unsigned parameter);
  91264. FLAC__bool FLAC__bitwriter_write_rice_signed_block(FLAC__BitWriter *bw, const FLAC__int32 *vals, unsigned nvals, unsigned parameter);
  91265. #if 0 /* UNUSED */
  91266. FLAC__bool FLAC__bitwriter_write_golomb_signed(FLAC__BitWriter *bw, int val, unsigned parameter);
  91267. FLAC__bool FLAC__bitwriter_write_golomb_unsigned(FLAC__BitWriter *bw, unsigned val, unsigned parameter);
  91268. #endif
  91269. FLAC__bool FLAC__bitwriter_write_utf8_uint32(FLAC__BitWriter *bw, FLAC__uint32 val);
  91270. FLAC__bool FLAC__bitwriter_write_utf8_uint64(FLAC__BitWriter *bw, FLAC__uint64 val);
  91271. FLAC__bool FLAC__bitwriter_zero_pad_to_byte_boundary(FLAC__BitWriter *bw);
  91272. #endif
  91273. /*** End of inlined file: bitwriter.h ***/
  91274. /*** Start of inlined file: alloc.h ***/
  91275. #ifndef FLAC__SHARE__ALLOC_H
  91276. #define FLAC__SHARE__ALLOC_H
  91277. #if HAVE_CONFIG_H
  91278. # include <config.h>
  91279. #endif
  91280. /* WATCHOUT: for c++ you may have to #define __STDC_LIMIT_MACROS 1 real early
  91281. * before #including this file, otherwise SIZE_MAX might not be defined
  91282. */
  91283. #include <limits.h> /* for SIZE_MAX */
  91284. #if !defined _MSC_VER && !defined __MINGW32__ && !defined __EMX__
  91285. #include <stdint.h> /* for SIZE_MAX in case limits.h didn't get it */
  91286. #endif
  91287. #include <stdlib.h> /* for size_t, malloc(), etc */
  91288. #ifndef SIZE_MAX
  91289. # ifndef SIZE_T_MAX
  91290. # ifdef _MSC_VER
  91291. # define SIZE_T_MAX UINT_MAX
  91292. # else
  91293. # error
  91294. # endif
  91295. # endif
  91296. # define SIZE_MAX SIZE_T_MAX
  91297. #endif
  91298. #ifndef FLaC__INLINE
  91299. #define FLaC__INLINE
  91300. #endif
  91301. /* avoid malloc()ing 0 bytes, see:
  91302. * https://www.securecoding.cert.org/confluence/display/seccode/MEM04-A.+Do+not+make+assumptions+about+the+result+of+allocating+0+bytes?focusedCommentId=5407003
  91303. */
  91304. static FLaC__INLINE void *safe_malloc_(size_t size)
  91305. {
  91306. /* malloc(0) is undefined; FLAC src convention is to always allocate */
  91307. if(!size)
  91308. size++;
  91309. return malloc(size);
  91310. }
  91311. static FLaC__INLINE void *safe_calloc_(size_t nmemb, size_t size)
  91312. {
  91313. if(!nmemb || !size)
  91314. return malloc(1); /* malloc(0) is undefined; FLAC src convention is to always allocate */
  91315. return calloc(nmemb, size);
  91316. }
  91317. /*@@@@ there's probably a better way to prevent overflows when allocating untrusted sums but this works for now */
  91318. static FLaC__INLINE void *safe_malloc_add_2op_(size_t size1, size_t size2)
  91319. {
  91320. size2 += size1;
  91321. if(size2 < size1)
  91322. return 0;
  91323. return safe_malloc_(size2);
  91324. }
  91325. static FLaC__INLINE void *safe_malloc_add_3op_(size_t size1, size_t size2, size_t size3)
  91326. {
  91327. size2 += size1;
  91328. if(size2 < size1)
  91329. return 0;
  91330. size3 += size2;
  91331. if(size3 < size2)
  91332. return 0;
  91333. return safe_malloc_(size3);
  91334. }
  91335. static FLaC__INLINE void *safe_malloc_add_4op_(size_t size1, size_t size2, size_t size3, size_t size4)
  91336. {
  91337. size2 += size1;
  91338. if(size2 < size1)
  91339. return 0;
  91340. size3 += size2;
  91341. if(size3 < size2)
  91342. return 0;
  91343. size4 += size3;
  91344. if(size4 < size3)
  91345. return 0;
  91346. return safe_malloc_(size4);
  91347. }
  91348. static FLaC__INLINE void *safe_malloc_mul_2op_(size_t size1, size_t size2)
  91349. #if 0
  91350. needs support for cases where sizeof(size_t) != 4
  91351. {
  91352. /* could be faster #ifdef'ing off SIZEOF_SIZE_T */
  91353. if(sizeof(size_t) == 4) {
  91354. if ((double)size1 * (double)size2 < 4294967296.0)
  91355. return malloc(size1*size2);
  91356. }
  91357. return 0;
  91358. }
  91359. #else
  91360. /* better? */
  91361. {
  91362. if(!size1 || !size2)
  91363. return malloc(1); /* malloc(0) is undefined; FLAC src convention is to always allocate */
  91364. if(size1 > SIZE_MAX / size2)
  91365. return 0;
  91366. return malloc(size1*size2);
  91367. }
  91368. #endif
  91369. static FLaC__INLINE void *safe_malloc_mul_3op_(size_t size1, size_t size2, size_t size3)
  91370. {
  91371. if(!size1 || !size2 || !size3)
  91372. return malloc(1); /* malloc(0) is undefined; FLAC src convention is to always allocate */
  91373. if(size1 > SIZE_MAX / size2)
  91374. return 0;
  91375. size1 *= size2;
  91376. if(size1 > SIZE_MAX / size3)
  91377. return 0;
  91378. return malloc(size1*size3);
  91379. }
  91380. /* size1*size2 + size3 */
  91381. static FLaC__INLINE void *safe_malloc_mul2add_(size_t size1, size_t size2, size_t size3)
  91382. {
  91383. if(!size1 || !size2)
  91384. return safe_malloc_(size3);
  91385. if(size1 > SIZE_MAX / size2)
  91386. return 0;
  91387. return safe_malloc_add_2op_(size1*size2, size3);
  91388. }
  91389. /* size1 * (size2 + size3) */
  91390. static FLaC__INLINE void *safe_malloc_muladd2_(size_t size1, size_t size2, size_t size3)
  91391. {
  91392. if(!size1 || (!size2 && !size3))
  91393. return malloc(1); /* malloc(0) is undefined; FLAC src convention is to always allocate */
  91394. size2 += size3;
  91395. if(size2 < size3)
  91396. return 0;
  91397. return safe_malloc_mul_2op_(size1, size2);
  91398. }
  91399. static FLaC__INLINE void *safe_realloc_add_2op_(void *ptr, size_t size1, size_t size2)
  91400. {
  91401. size2 += size1;
  91402. if(size2 < size1)
  91403. return 0;
  91404. return realloc(ptr, size2);
  91405. }
  91406. static FLaC__INLINE void *safe_realloc_add_3op_(void *ptr, size_t size1, size_t size2, size_t size3)
  91407. {
  91408. size2 += size1;
  91409. if(size2 < size1)
  91410. return 0;
  91411. size3 += size2;
  91412. if(size3 < size2)
  91413. return 0;
  91414. return realloc(ptr, size3);
  91415. }
  91416. static FLaC__INLINE void *safe_realloc_add_4op_(void *ptr, size_t size1, size_t size2, size_t size3, size_t size4)
  91417. {
  91418. size2 += size1;
  91419. if(size2 < size1)
  91420. return 0;
  91421. size3 += size2;
  91422. if(size3 < size2)
  91423. return 0;
  91424. size4 += size3;
  91425. if(size4 < size3)
  91426. return 0;
  91427. return realloc(ptr, size4);
  91428. }
  91429. static FLaC__INLINE void *safe_realloc_mul_2op_(void *ptr, size_t size1, size_t size2)
  91430. {
  91431. if(!size1 || !size2)
  91432. return realloc(ptr, 0); /* preserve POSIX realloc(ptr, 0) semantics */
  91433. if(size1 > SIZE_MAX / size2)
  91434. return 0;
  91435. return realloc(ptr, size1*size2);
  91436. }
  91437. /* size1 * (size2 + size3) */
  91438. static FLaC__INLINE void *safe_realloc_muladd2_(void *ptr, size_t size1, size_t size2, size_t size3)
  91439. {
  91440. if(!size1 || (!size2 && !size3))
  91441. return realloc(ptr, 0); /* preserve POSIX realloc(ptr, 0) semantics */
  91442. size2 += size3;
  91443. if(size2 < size3)
  91444. return 0;
  91445. return safe_realloc_mul_2op_(ptr, size1, size2);
  91446. }
  91447. #endif
  91448. /*** End of inlined file: alloc.h ***/
  91449. /* Things should be fastest when this matches the machine word size */
  91450. /* WATCHOUT: if you change this you must also change the following #defines down to SWAP_BE_WORD_TO_HOST below to match */
  91451. /* WATCHOUT: there are a few places where the code will not work unless bwword is >= 32 bits wide */
  91452. typedef FLAC__uint32 bwword;
  91453. #define FLAC__BYTES_PER_WORD 4
  91454. #define FLAC__BITS_PER_WORD 32
  91455. #define FLAC__WORD_ALL_ONES ((FLAC__uint32)0xffffffff)
  91456. /* SWAP_BE_WORD_TO_HOST swaps bytes in a bwword (which is always big-endian) if necessary to match host byte order */
  91457. #if WORDS_BIGENDIAN
  91458. #define SWAP_BE_WORD_TO_HOST(x) (x)
  91459. #else
  91460. #ifdef _MSC_VER
  91461. #define SWAP_BE_WORD_TO_HOST(x) local_swap32_(x)
  91462. #else
  91463. #define SWAP_BE_WORD_TO_HOST(x) ntohl(x)
  91464. #endif
  91465. #endif
  91466. /*
  91467. * The default capacity here doesn't matter too much. The buffer always grows
  91468. * to hold whatever is written to it. Usually the encoder will stop adding at
  91469. * a frame or metadata block, then write that out and clear the buffer for the
  91470. * next one.
  91471. */
  91472. static const unsigned FLAC__BITWRITER_DEFAULT_CAPACITY = 32768u / sizeof(bwword); /* size in words */
  91473. /* When growing, increment 4K at a time */
  91474. static const unsigned FLAC__BITWRITER_DEFAULT_INCREMENT = 4096u / sizeof(bwword); /* size in words */
  91475. #define FLAC__WORDS_TO_BITS(words) ((words) * FLAC__BITS_PER_WORD)
  91476. #define FLAC__TOTAL_BITS(bw) (FLAC__WORDS_TO_BITS((bw)->words) + (bw)->bits)
  91477. #ifdef min
  91478. #undef min
  91479. #endif
  91480. #define min(x,y) ((x)<(y)?(x):(y))
  91481. /* adjust for compilers that can't understand using LLU suffix for uint64_t literals */
  91482. #ifdef _MSC_VER
  91483. #define FLAC__U64L(x) x
  91484. #else
  91485. #define FLAC__U64L(x) x##LLU
  91486. #endif
  91487. #ifndef FLaC__INLINE
  91488. #define FLaC__INLINE
  91489. #endif
  91490. struct FLAC__BitWriter {
  91491. bwword *buffer;
  91492. bwword accum; /* accumulator; bits are right-justified; when full, accum is appended to buffer */
  91493. unsigned capacity; /* capacity of buffer in words */
  91494. unsigned words; /* # of complete words in buffer */
  91495. unsigned bits; /* # of used bits in accum */
  91496. };
  91497. /* * WATCHOUT: The current implementation only grows the buffer. */
  91498. static FLAC__bool bitwriter_grow_(FLAC__BitWriter *bw, unsigned bits_to_add)
  91499. {
  91500. unsigned new_capacity;
  91501. bwword *new_buffer;
  91502. FLAC__ASSERT(0 != bw);
  91503. FLAC__ASSERT(0 != bw->buffer);
  91504. /* calculate total words needed to store 'bits_to_add' additional bits */
  91505. new_capacity = bw->words + ((bw->bits + bits_to_add + FLAC__BITS_PER_WORD - 1) / FLAC__BITS_PER_WORD);
  91506. /* it's possible (due to pessimism in the growth estimation that
  91507. * leads to this call) that we don't actually need to grow
  91508. */
  91509. if(bw->capacity >= new_capacity)
  91510. return true;
  91511. /* round up capacity increase to the nearest FLAC__BITWRITER_DEFAULT_INCREMENT */
  91512. if((new_capacity - bw->capacity) % FLAC__BITWRITER_DEFAULT_INCREMENT)
  91513. new_capacity += FLAC__BITWRITER_DEFAULT_INCREMENT - ((new_capacity - bw->capacity) % FLAC__BITWRITER_DEFAULT_INCREMENT);
  91514. /* make sure we got everything right */
  91515. FLAC__ASSERT(0 == (new_capacity - bw->capacity) % FLAC__BITWRITER_DEFAULT_INCREMENT);
  91516. FLAC__ASSERT(new_capacity > bw->capacity);
  91517. FLAC__ASSERT(new_capacity >= bw->words + ((bw->bits + bits_to_add + FLAC__BITS_PER_WORD - 1) / FLAC__BITS_PER_WORD));
  91518. new_buffer = (bwword*)safe_realloc_mul_2op_(bw->buffer, sizeof(bwword), /*times*/new_capacity);
  91519. if(new_buffer == 0)
  91520. return false;
  91521. bw->buffer = new_buffer;
  91522. bw->capacity = new_capacity;
  91523. return true;
  91524. }
  91525. /***********************************************************************
  91526. *
  91527. * Class constructor/destructor
  91528. *
  91529. ***********************************************************************/
  91530. FLAC__BitWriter *FLAC__bitwriter_new(void)
  91531. {
  91532. FLAC__BitWriter *bw = (FLAC__BitWriter*)calloc(1, sizeof(FLAC__BitWriter));
  91533. /* note that calloc() sets all members to 0 for us */
  91534. return bw;
  91535. }
  91536. void FLAC__bitwriter_delete(FLAC__BitWriter *bw)
  91537. {
  91538. FLAC__ASSERT(0 != bw);
  91539. FLAC__bitwriter_free(bw);
  91540. free(bw);
  91541. }
  91542. /***********************************************************************
  91543. *
  91544. * Public class methods
  91545. *
  91546. ***********************************************************************/
  91547. FLAC__bool FLAC__bitwriter_init(FLAC__BitWriter *bw)
  91548. {
  91549. FLAC__ASSERT(0 != bw);
  91550. bw->words = bw->bits = 0;
  91551. bw->capacity = FLAC__BITWRITER_DEFAULT_CAPACITY;
  91552. bw->buffer = (bwword*)malloc(sizeof(bwword) * bw->capacity);
  91553. if(bw->buffer == 0)
  91554. return false;
  91555. return true;
  91556. }
  91557. void FLAC__bitwriter_free(FLAC__BitWriter *bw)
  91558. {
  91559. FLAC__ASSERT(0 != bw);
  91560. if(0 != bw->buffer)
  91561. free(bw->buffer);
  91562. bw->buffer = 0;
  91563. bw->capacity = 0;
  91564. bw->words = bw->bits = 0;
  91565. }
  91566. void FLAC__bitwriter_clear(FLAC__BitWriter *bw)
  91567. {
  91568. bw->words = bw->bits = 0;
  91569. }
  91570. void FLAC__bitwriter_dump(const FLAC__BitWriter *bw, FILE *out)
  91571. {
  91572. unsigned i, j;
  91573. if(bw == 0) {
  91574. fprintf(out, "bitwriter is NULL\n");
  91575. }
  91576. else {
  91577. fprintf(out, "bitwriter: capacity=%u words=%u bits=%u total_bits=%u\n", bw->capacity, bw->words, bw->bits, FLAC__TOTAL_BITS(bw));
  91578. for(i = 0; i < bw->words; i++) {
  91579. fprintf(out, "%08X: ", i);
  91580. for(j = 0; j < FLAC__BITS_PER_WORD; j++)
  91581. fprintf(out, "%01u", bw->buffer[i] & (1 << (FLAC__BITS_PER_WORD-j-1)) ? 1:0);
  91582. fprintf(out, "\n");
  91583. }
  91584. if(bw->bits > 0) {
  91585. fprintf(out, "%08X: ", i);
  91586. for(j = 0; j < bw->bits; j++)
  91587. fprintf(out, "%01u", bw->accum & (1 << (bw->bits-j-1)) ? 1:0);
  91588. fprintf(out, "\n");
  91589. }
  91590. }
  91591. }
  91592. FLAC__bool FLAC__bitwriter_get_write_crc16(FLAC__BitWriter *bw, FLAC__uint16 *crc)
  91593. {
  91594. const FLAC__byte *buffer;
  91595. size_t bytes;
  91596. FLAC__ASSERT((bw->bits & 7) == 0); /* assert that we're byte-aligned */
  91597. if(!FLAC__bitwriter_get_buffer(bw, &buffer, &bytes))
  91598. return false;
  91599. *crc = (FLAC__uint16)FLAC__crc16(buffer, bytes);
  91600. FLAC__bitwriter_release_buffer(bw);
  91601. return true;
  91602. }
  91603. FLAC__bool FLAC__bitwriter_get_write_crc8(FLAC__BitWriter *bw, FLAC__byte *crc)
  91604. {
  91605. const FLAC__byte *buffer;
  91606. size_t bytes;
  91607. FLAC__ASSERT((bw->bits & 7) == 0); /* assert that we're byte-aligned */
  91608. if(!FLAC__bitwriter_get_buffer(bw, &buffer, &bytes))
  91609. return false;
  91610. *crc = FLAC__crc8(buffer, bytes);
  91611. FLAC__bitwriter_release_buffer(bw);
  91612. return true;
  91613. }
  91614. FLAC__bool FLAC__bitwriter_is_byte_aligned(const FLAC__BitWriter *bw)
  91615. {
  91616. return ((bw->bits & 7) == 0);
  91617. }
  91618. unsigned FLAC__bitwriter_get_input_bits_unconsumed(const FLAC__BitWriter *bw)
  91619. {
  91620. return FLAC__TOTAL_BITS(bw);
  91621. }
  91622. FLAC__bool FLAC__bitwriter_get_buffer(FLAC__BitWriter *bw, const FLAC__byte **buffer, size_t *bytes)
  91623. {
  91624. FLAC__ASSERT((bw->bits & 7) == 0);
  91625. /* double protection */
  91626. if(bw->bits & 7)
  91627. return false;
  91628. /* if we have bits in the accumulator we have to flush those to the buffer first */
  91629. if(bw->bits) {
  91630. FLAC__ASSERT(bw->words <= bw->capacity);
  91631. if(bw->words == bw->capacity && !bitwriter_grow_(bw, FLAC__BITS_PER_WORD))
  91632. return false;
  91633. /* append bits as complete word to buffer, but don't change bw->accum or bw->bits */
  91634. bw->buffer[bw->words] = SWAP_BE_WORD_TO_HOST(bw->accum << (FLAC__BITS_PER_WORD-bw->bits));
  91635. }
  91636. /* now we can just return what we have */
  91637. *buffer = (FLAC__byte*)bw->buffer;
  91638. *bytes = (FLAC__BYTES_PER_WORD * bw->words) + (bw->bits >> 3);
  91639. return true;
  91640. }
  91641. void FLAC__bitwriter_release_buffer(FLAC__BitWriter *bw)
  91642. {
  91643. /* nothing to do. in the future, strict checking of a 'writer-is-in-
  91644. * get-mode' flag could be added everywhere and then cleared here
  91645. */
  91646. (void)bw;
  91647. }
  91648. FLaC__INLINE FLAC__bool FLAC__bitwriter_write_zeroes(FLAC__BitWriter *bw, unsigned bits)
  91649. {
  91650. unsigned n;
  91651. FLAC__ASSERT(0 != bw);
  91652. FLAC__ASSERT(0 != bw->buffer);
  91653. if(bits == 0)
  91654. return true;
  91655. /* slightly pessimistic size check but faster than "<= bw->words + (bw->bits+bits+FLAC__BITS_PER_WORD-1)/FLAC__BITS_PER_WORD" */
  91656. if(bw->capacity <= bw->words + bits && !bitwriter_grow_(bw, bits))
  91657. return false;
  91658. /* first part gets to word alignment */
  91659. if(bw->bits) {
  91660. n = min(FLAC__BITS_PER_WORD - bw->bits, bits);
  91661. bw->accum <<= n;
  91662. bits -= n;
  91663. bw->bits += n;
  91664. if(bw->bits == FLAC__BITS_PER_WORD) {
  91665. bw->buffer[bw->words++] = SWAP_BE_WORD_TO_HOST(bw->accum);
  91666. bw->bits = 0;
  91667. }
  91668. else
  91669. return true;
  91670. }
  91671. /* do whole words */
  91672. while(bits >= FLAC__BITS_PER_WORD) {
  91673. bw->buffer[bw->words++] = 0;
  91674. bits -= FLAC__BITS_PER_WORD;
  91675. }
  91676. /* do any leftovers */
  91677. if(bits > 0) {
  91678. bw->accum = 0;
  91679. bw->bits = bits;
  91680. }
  91681. return true;
  91682. }
  91683. FLaC__INLINE FLAC__bool FLAC__bitwriter_write_raw_uint32(FLAC__BitWriter *bw, FLAC__uint32 val, unsigned bits)
  91684. {
  91685. register unsigned left;
  91686. /* WATCHOUT: code does not work with <32bit words; we can make things much faster with this assertion */
  91687. FLAC__ASSERT(FLAC__BITS_PER_WORD >= 32);
  91688. FLAC__ASSERT(0 != bw);
  91689. FLAC__ASSERT(0 != bw->buffer);
  91690. FLAC__ASSERT(bits <= 32);
  91691. if(bits == 0)
  91692. return true;
  91693. /* slightly pessimistic size check but faster than "<= bw->words + (bw->bits+bits+FLAC__BITS_PER_WORD-1)/FLAC__BITS_PER_WORD" */
  91694. if(bw->capacity <= bw->words + bits && !bitwriter_grow_(bw, bits))
  91695. return false;
  91696. left = FLAC__BITS_PER_WORD - bw->bits;
  91697. if(bits < left) {
  91698. bw->accum <<= bits;
  91699. bw->accum |= val;
  91700. bw->bits += bits;
  91701. }
  91702. 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 */
  91703. bw->accum <<= left;
  91704. bw->accum |= val >> (bw->bits = bits - left);
  91705. bw->buffer[bw->words++] = SWAP_BE_WORD_TO_HOST(bw->accum);
  91706. bw->accum = val;
  91707. }
  91708. else {
  91709. bw->accum = val;
  91710. bw->bits = 0;
  91711. bw->buffer[bw->words++] = SWAP_BE_WORD_TO_HOST(val);
  91712. }
  91713. return true;
  91714. }
  91715. FLaC__INLINE FLAC__bool FLAC__bitwriter_write_raw_int32(FLAC__BitWriter *bw, FLAC__int32 val, unsigned bits)
  91716. {
  91717. /* zero-out unused bits */
  91718. if(bits < 32)
  91719. val &= (~(0xffffffff << bits));
  91720. return FLAC__bitwriter_write_raw_uint32(bw, (FLAC__uint32)val, bits);
  91721. }
  91722. FLaC__INLINE FLAC__bool FLAC__bitwriter_write_raw_uint64(FLAC__BitWriter *bw, FLAC__uint64 val, unsigned bits)
  91723. {
  91724. /* this could be a little faster but it's not used for much */
  91725. if(bits > 32) {
  91726. return
  91727. FLAC__bitwriter_write_raw_uint32(bw, (FLAC__uint32)(val>>32), bits-32) &&
  91728. FLAC__bitwriter_write_raw_uint32(bw, (FLAC__uint32)val, 32);
  91729. }
  91730. else
  91731. return FLAC__bitwriter_write_raw_uint32(bw, (FLAC__uint32)val, bits);
  91732. }
  91733. FLaC__INLINE FLAC__bool FLAC__bitwriter_write_raw_uint32_little_endian(FLAC__BitWriter *bw, FLAC__uint32 val)
  91734. {
  91735. /* this doesn't need to be that fast as currently it is only used for vorbis comments */
  91736. if(!FLAC__bitwriter_write_raw_uint32(bw, val & 0xff, 8))
  91737. return false;
  91738. if(!FLAC__bitwriter_write_raw_uint32(bw, (val>>8) & 0xff, 8))
  91739. return false;
  91740. if(!FLAC__bitwriter_write_raw_uint32(bw, (val>>16) & 0xff, 8))
  91741. return false;
  91742. if(!FLAC__bitwriter_write_raw_uint32(bw, val>>24, 8))
  91743. return false;
  91744. return true;
  91745. }
  91746. FLaC__INLINE FLAC__bool FLAC__bitwriter_write_byte_block(FLAC__BitWriter *bw, const FLAC__byte vals[], unsigned nvals)
  91747. {
  91748. unsigned i;
  91749. /* this could be faster but currently we don't need it to be since it's only used for writing metadata */
  91750. for(i = 0; i < nvals; i++) {
  91751. if(!FLAC__bitwriter_write_raw_uint32(bw, (FLAC__uint32)(vals[i]), 8))
  91752. return false;
  91753. }
  91754. return true;
  91755. }
  91756. FLAC__bool FLAC__bitwriter_write_unary_unsigned(FLAC__BitWriter *bw, unsigned val)
  91757. {
  91758. if(val < 32)
  91759. return FLAC__bitwriter_write_raw_uint32(bw, 1, ++val);
  91760. else
  91761. return
  91762. FLAC__bitwriter_write_zeroes(bw, val) &&
  91763. FLAC__bitwriter_write_raw_uint32(bw, 1, 1);
  91764. }
  91765. unsigned FLAC__bitwriter_rice_bits(FLAC__int32 val, unsigned parameter)
  91766. {
  91767. FLAC__uint32 uval;
  91768. FLAC__ASSERT(parameter < sizeof(unsigned)*8);
  91769. /* fold signed to unsigned; actual formula is: negative(v)? -2v-1 : 2v */
  91770. uval = (val<<1) ^ (val>>31);
  91771. return 1 + parameter + (uval >> parameter);
  91772. }
  91773. #if 0 /* UNUSED */
  91774. unsigned FLAC__bitwriter_golomb_bits_signed(int val, unsigned parameter)
  91775. {
  91776. unsigned bits, msbs, uval;
  91777. unsigned k;
  91778. FLAC__ASSERT(parameter > 0);
  91779. /* fold signed to unsigned */
  91780. if(val < 0)
  91781. uval = (unsigned)(((-(++val)) << 1) + 1);
  91782. else
  91783. uval = (unsigned)(val << 1);
  91784. k = FLAC__bitmath_ilog2(parameter);
  91785. if(parameter == 1u<<k) {
  91786. FLAC__ASSERT(k <= 30);
  91787. msbs = uval >> k;
  91788. bits = 1 + k + msbs;
  91789. }
  91790. else {
  91791. unsigned q, r, d;
  91792. d = (1 << (k+1)) - parameter;
  91793. q = uval / parameter;
  91794. r = uval - (q * parameter);
  91795. bits = 1 + q + k;
  91796. if(r >= d)
  91797. bits++;
  91798. }
  91799. return bits;
  91800. }
  91801. unsigned FLAC__bitwriter_golomb_bits_unsigned(unsigned uval, unsigned parameter)
  91802. {
  91803. unsigned bits, msbs;
  91804. unsigned k;
  91805. FLAC__ASSERT(parameter > 0);
  91806. k = FLAC__bitmath_ilog2(parameter);
  91807. if(parameter == 1u<<k) {
  91808. FLAC__ASSERT(k <= 30);
  91809. msbs = uval >> k;
  91810. bits = 1 + k + msbs;
  91811. }
  91812. else {
  91813. unsigned q, r, d;
  91814. d = (1 << (k+1)) - parameter;
  91815. q = uval / parameter;
  91816. r = uval - (q * parameter);
  91817. bits = 1 + q + k;
  91818. if(r >= d)
  91819. bits++;
  91820. }
  91821. return bits;
  91822. }
  91823. #endif /* UNUSED */
  91824. FLAC__bool FLAC__bitwriter_write_rice_signed(FLAC__BitWriter *bw, FLAC__int32 val, unsigned parameter)
  91825. {
  91826. unsigned total_bits, interesting_bits, msbs;
  91827. FLAC__uint32 uval, pattern;
  91828. FLAC__ASSERT(0 != bw);
  91829. FLAC__ASSERT(0 != bw->buffer);
  91830. FLAC__ASSERT(parameter < 8*sizeof(uval));
  91831. /* fold signed to unsigned; actual formula is: negative(v)? -2v-1 : 2v */
  91832. uval = (val<<1) ^ (val>>31);
  91833. msbs = uval >> parameter;
  91834. interesting_bits = 1 + parameter;
  91835. total_bits = interesting_bits + msbs;
  91836. pattern = 1 << parameter; /* the unary end bit */
  91837. pattern |= (uval & ((1<<parameter)-1)); /* the binary LSBs */
  91838. if(total_bits <= 32)
  91839. return FLAC__bitwriter_write_raw_uint32(bw, pattern, total_bits);
  91840. else
  91841. return
  91842. FLAC__bitwriter_write_zeroes(bw, msbs) && /* write the unary MSBs */
  91843. FLAC__bitwriter_write_raw_uint32(bw, pattern, interesting_bits); /* write the unary end bit and binary LSBs */
  91844. }
  91845. FLAC__bool FLAC__bitwriter_write_rice_signed_block(FLAC__BitWriter *bw, const FLAC__int32 *vals, unsigned nvals, unsigned parameter)
  91846. {
  91847. const FLAC__uint32 mask1 = FLAC__WORD_ALL_ONES << parameter; /* we val|=mask1 to set the stop bit above it... */
  91848. const FLAC__uint32 mask2 = FLAC__WORD_ALL_ONES >> (31-parameter); /* ...then mask off the bits above the stop bit with val&=mask2*/
  91849. FLAC__uint32 uval;
  91850. unsigned left;
  91851. const unsigned lsbits = 1 + parameter;
  91852. unsigned msbits;
  91853. FLAC__ASSERT(0 != bw);
  91854. FLAC__ASSERT(0 != bw->buffer);
  91855. FLAC__ASSERT(parameter < 8*sizeof(bwword)-1);
  91856. /* WATCHOUT: code does not work with <32bit words; we can make things much faster with this assertion */
  91857. FLAC__ASSERT(FLAC__BITS_PER_WORD >= 32);
  91858. while(nvals) {
  91859. /* fold signed to unsigned; actual formula is: negative(v)? -2v-1 : 2v */
  91860. uval = (*vals<<1) ^ (*vals>>31);
  91861. msbits = uval >> parameter;
  91862. #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) */
  91863. if(bw->bits && bw->bits + msbits + lsbits <= FLAC__BITS_PER_WORD) { /* i.e. if the whole thing fits in the current bwword */
  91864. /* ^^^ if bw->bits is 0 then we may have filled the buffer and have no free bwword to work in */
  91865. bw->bits = bw->bits + msbits + lsbits;
  91866. uval |= mask1; /* set stop bit */
  91867. uval &= mask2; /* mask off unused top bits */
  91868. /* NOT: bw->accum <<= msbits + lsbits because msbits+lsbits could be 32, then the shift would be a NOP */
  91869. bw->accum <<= msbits;
  91870. bw->accum <<= lsbits;
  91871. bw->accum |= uval;
  91872. if(bw->bits == FLAC__BITS_PER_WORD) {
  91873. bw->buffer[bw->words++] = SWAP_BE_WORD_TO_HOST(bw->accum);
  91874. bw->bits = 0;
  91875. /* burying the capacity check down here means we have to grow the buffer a little if there are more vals to do */
  91876. if(bw->capacity <= bw->words && nvals > 1 && !bitwriter_grow_(bw, 1)) {
  91877. FLAC__ASSERT(bw->capacity == bw->words);
  91878. return false;
  91879. }
  91880. }
  91881. }
  91882. else {
  91883. #elif 1 /*@@@@@@ OPT: try this version with MSVC6 to see if better, not much difference for gcc-4 */
  91884. if(bw->bits && bw->bits + msbits + lsbits < FLAC__BITS_PER_WORD) { /* i.e. if the whole thing fits in the current bwword */
  91885. /* ^^^ if bw->bits is 0 then we may have filled the buffer and have no free bwword to work in */
  91886. bw->bits = bw->bits + msbits + lsbits;
  91887. uval |= mask1; /* set stop bit */
  91888. uval &= mask2; /* mask off unused top bits */
  91889. bw->accum <<= msbits + lsbits;
  91890. bw->accum |= uval;
  91891. }
  91892. else {
  91893. #endif
  91894. /* slightly pessimistic size check but faster than "<= bw->words + (bw->bits+msbits+lsbits+FLAC__BITS_PER_WORD-1)/FLAC__BITS_PER_WORD" */
  91895. /* OPT: pessimism may cause flurry of false calls to grow_ which eat up all savings before it */
  91896. if(bw->capacity <= bw->words + bw->bits + msbits + 1/*lsbits always fit in 1 bwword*/ && !bitwriter_grow_(bw, msbits+lsbits))
  91897. return false;
  91898. if(msbits) {
  91899. /* first part gets to word alignment */
  91900. if(bw->bits) {
  91901. left = FLAC__BITS_PER_WORD - bw->bits;
  91902. if(msbits < left) {
  91903. bw->accum <<= msbits;
  91904. bw->bits += msbits;
  91905. goto break1;
  91906. }
  91907. else {
  91908. bw->accum <<= left;
  91909. msbits -= left;
  91910. bw->buffer[bw->words++] = SWAP_BE_WORD_TO_HOST(bw->accum);
  91911. bw->bits = 0;
  91912. }
  91913. }
  91914. /* do whole words */
  91915. while(msbits >= FLAC__BITS_PER_WORD) {
  91916. bw->buffer[bw->words++] = 0;
  91917. msbits -= FLAC__BITS_PER_WORD;
  91918. }
  91919. /* do any leftovers */
  91920. if(msbits > 0) {
  91921. bw->accum = 0;
  91922. bw->bits = msbits;
  91923. }
  91924. }
  91925. break1:
  91926. uval |= mask1; /* set stop bit */
  91927. uval &= mask2; /* mask off unused top bits */
  91928. left = FLAC__BITS_PER_WORD - bw->bits;
  91929. if(lsbits < left) {
  91930. bw->accum <<= lsbits;
  91931. bw->accum |= uval;
  91932. bw->bits += lsbits;
  91933. }
  91934. else {
  91935. /* if bw->bits == 0, left==FLAC__BITS_PER_WORD which will always
  91936. * be > lsbits (because of previous assertions) so it would have
  91937. * triggered the (lsbits<left) case above.
  91938. */
  91939. FLAC__ASSERT(bw->bits);
  91940. FLAC__ASSERT(left < FLAC__BITS_PER_WORD);
  91941. bw->accum <<= left;
  91942. bw->accum |= uval >> (bw->bits = lsbits - left);
  91943. bw->buffer[bw->words++] = SWAP_BE_WORD_TO_HOST(bw->accum);
  91944. bw->accum = uval;
  91945. }
  91946. #if 1
  91947. }
  91948. #endif
  91949. vals++;
  91950. nvals--;
  91951. }
  91952. return true;
  91953. }
  91954. #if 0 /* UNUSED */
  91955. FLAC__bool FLAC__bitwriter_write_golomb_signed(FLAC__BitWriter *bw, int val, unsigned parameter)
  91956. {
  91957. unsigned total_bits, msbs, uval;
  91958. unsigned k;
  91959. FLAC__ASSERT(0 != bw);
  91960. FLAC__ASSERT(0 != bw->buffer);
  91961. FLAC__ASSERT(parameter > 0);
  91962. /* fold signed to unsigned */
  91963. if(val < 0)
  91964. uval = (unsigned)(((-(++val)) << 1) + 1);
  91965. else
  91966. uval = (unsigned)(val << 1);
  91967. k = FLAC__bitmath_ilog2(parameter);
  91968. if(parameter == 1u<<k) {
  91969. unsigned pattern;
  91970. FLAC__ASSERT(k <= 30);
  91971. msbs = uval >> k;
  91972. total_bits = 1 + k + msbs;
  91973. pattern = 1 << k; /* the unary end bit */
  91974. pattern |= (uval & ((1u<<k)-1)); /* the binary LSBs */
  91975. if(total_bits <= 32) {
  91976. if(!FLAC__bitwriter_write_raw_uint32(bw, pattern, total_bits))
  91977. return false;
  91978. }
  91979. else {
  91980. /* write the unary MSBs */
  91981. if(!FLAC__bitwriter_write_zeroes(bw, msbs))
  91982. return false;
  91983. /* write the unary end bit and binary LSBs */
  91984. if(!FLAC__bitwriter_write_raw_uint32(bw, pattern, k+1))
  91985. return false;
  91986. }
  91987. }
  91988. else {
  91989. unsigned q, r, d;
  91990. d = (1 << (k+1)) - parameter;
  91991. q = uval / parameter;
  91992. r = uval - (q * parameter);
  91993. /* write the unary MSBs */
  91994. if(!FLAC__bitwriter_write_zeroes(bw, q))
  91995. return false;
  91996. /* write the unary end bit */
  91997. if(!FLAC__bitwriter_write_raw_uint32(bw, 1, 1))
  91998. return false;
  91999. /* write the binary LSBs */
  92000. if(r >= d) {
  92001. if(!FLAC__bitwriter_write_raw_uint32(bw, r+d, k+1))
  92002. return false;
  92003. }
  92004. else {
  92005. if(!FLAC__bitwriter_write_raw_uint32(bw, r, k))
  92006. return false;
  92007. }
  92008. }
  92009. return true;
  92010. }
  92011. FLAC__bool FLAC__bitwriter_write_golomb_unsigned(FLAC__BitWriter *bw, unsigned uval, unsigned parameter)
  92012. {
  92013. unsigned total_bits, msbs;
  92014. unsigned k;
  92015. FLAC__ASSERT(0 != bw);
  92016. FLAC__ASSERT(0 != bw->buffer);
  92017. FLAC__ASSERT(parameter > 0);
  92018. k = FLAC__bitmath_ilog2(parameter);
  92019. if(parameter == 1u<<k) {
  92020. unsigned pattern;
  92021. FLAC__ASSERT(k <= 30);
  92022. msbs = uval >> k;
  92023. total_bits = 1 + k + msbs;
  92024. pattern = 1 << k; /* the unary end bit */
  92025. pattern |= (uval & ((1u<<k)-1)); /* the binary LSBs */
  92026. if(total_bits <= 32) {
  92027. if(!FLAC__bitwriter_write_raw_uint32(bw, pattern, total_bits))
  92028. return false;
  92029. }
  92030. else {
  92031. /* write the unary MSBs */
  92032. if(!FLAC__bitwriter_write_zeroes(bw, msbs))
  92033. return false;
  92034. /* write the unary end bit and binary LSBs */
  92035. if(!FLAC__bitwriter_write_raw_uint32(bw, pattern, k+1))
  92036. return false;
  92037. }
  92038. }
  92039. else {
  92040. unsigned q, r, d;
  92041. d = (1 << (k+1)) - parameter;
  92042. q = uval / parameter;
  92043. r = uval - (q * parameter);
  92044. /* write the unary MSBs */
  92045. if(!FLAC__bitwriter_write_zeroes(bw, q))
  92046. return false;
  92047. /* write the unary end bit */
  92048. if(!FLAC__bitwriter_write_raw_uint32(bw, 1, 1))
  92049. return false;
  92050. /* write the binary LSBs */
  92051. if(r >= d) {
  92052. if(!FLAC__bitwriter_write_raw_uint32(bw, r+d, k+1))
  92053. return false;
  92054. }
  92055. else {
  92056. if(!FLAC__bitwriter_write_raw_uint32(bw, r, k))
  92057. return false;
  92058. }
  92059. }
  92060. return true;
  92061. }
  92062. #endif /* UNUSED */
  92063. FLAC__bool FLAC__bitwriter_write_utf8_uint32(FLAC__BitWriter *bw, FLAC__uint32 val)
  92064. {
  92065. FLAC__bool ok = 1;
  92066. FLAC__ASSERT(0 != bw);
  92067. FLAC__ASSERT(0 != bw->buffer);
  92068. FLAC__ASSERT(!(val & 0x80000000)); /* this version only handles 31 bits */
  92069. if(val < 0x80) {
  92070. return FLAC__bitwriter_write_raw_uint32(bw, val, 8);
  92071. }
  92072. else if(val < 0x800) {
  92073. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xC0 | (val>>6), 8);
  92074. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (val&0x3F), 8);
  92075. }
  92076. else if(val < 0x10000) {
  92077. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xE0 | (val>>12), 8);
  92078. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>6)&0x3F), 8);
  92079. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (val&0x3F), 8);
  92080. }
  92081. else if(val < 0x200000) {
  92082. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xF0 | (val>>18), 8);
  92083. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>12)&0x3F), 8);
  92084. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>6)&0x3F), 8);
  92085. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (val&0x3F), 8);
  92086. }
  92087. else if(val < 0x4000000) {
  92088. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xF8 | (val>>24), 8);
  92089. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>18)&0x3F), 8);
  92090. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>12)&0x3F), 8);
  92091. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>6)&0x3F), 8);
  92092. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (val&0x3F), 8);
  92093. }
  92094. else {
  92095. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xFC | (val>>30), 8);
  92096. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>24)&0x3F), 8);
  92097. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>18)&0x3F), 8);
  92098. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>12)&0x3F), 8);
  92099. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>6)&0x3F), 8);
  92100. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (val&0x3F), 8);
  92101. }
  92102. return ok;
  92103. }
  92104. FLAC__bool FLAC__bitwriter_write_utf8_uint64(FLAC__BitWriter *bw, FLAC__uint64 val)
  92105. {
  92106. FLAC__bool ok = 1;
  92107. FLAC__ASSERT(0 != bw);
  92108. FLAC__ASSERT(0 != bw->buffer);
  92109. FLAC__ASSERT(!(val & FLAC__U64L(0xFFFFFFF000000000))); /* this version only handles 36 bits */
  92110. if(val < 0x80) {
  92111. return FLAC__bitwriter_write_raw_uint32(bw, (FLAC__uint32)val, 8);
  92112. }
  92113. else if(val < 0x800) {
  92114. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xC0 | (FLAC__uint32)(val>>6), 8);
  92115. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)(val&0x3F), 8);
  92116. }
  92117. else if(val < 0x10000) {
  92118. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xE0 | (FLAC__uint32)(val>>12), 8);
  92119. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>6)&0x3F), 8);
  92120. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)(val&0x3F), 8);
  92121. }
  92122. else if(val < 0x200000) {
  92123. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xF0 | (FLAC__uint32)(val>>18), 8);
  92124. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>12)&0x3F), 8);
  92125. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>6)&0x3F), 8);
  92126. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)(val&0x3F), 8);
  92127. }
  92128. else if(val < 0x4000000) {
  92129. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xF8 | (FLAC__uint32)(val>>24), 8);
  92130. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>18)&0x3F), 8);
  92131. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>12)&0x3F), 8);
  92132. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>6)&0x3F), 8);
  92133. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)(val&0x3F), 8);
  92134. }
  92135. else if(val < 0x80000000) {
  92136. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xFC | (FLAC__uint32)(val>>30), 8);
  92137. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>24)&0x3F), 8);
  92138. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>18)&0x3F), 8);
  92139. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>12)&0x3F), 8);
  92140. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>6)&0x3F), 8);
  92141. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)(val&0x3F), 8);
  92142. }
  92143. else {
  92144. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xFE, 8);
  92145. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>30)&0x3F), 8);
  92146. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>24)&0x3F), 8);
  92147. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>18)&0x3F), 8);
  92148. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>12)&0x3F), 8);
  92149. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>6)&0x3F), 8);
  92150. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)(val&0x3F), 8);
  92151. }
  92152. return ok;
  92153. }
  92154. FLAC__bool FLAC__bitwriter_zero_pad_to_byte_boundary(FLAC__BitWriter *bw)
  92155. {
  92156. /* 0-pad to byte boundary */
  92157. if(bw->bits & 7u)
  92158. return FLAC__bitwriter_write_zeroes(bw, 8 - (bw->bits & 7u));
  92159. else
  92160. return true;
  92161. }
  92162. #endif
  92163. /*** End of inlined file: bitwriter.c ***/
  92164. /*** Start of inlined file: cpu.c ***/
  92165. /*** Start of inlined file: juce_FlacHeader.h ***/
  92166. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  92167. // tasks..
  92168. #define VERSION "1.2.1"
  92169. #define FLAC__NO_DLL 1
  92170. #if JUCE_MSVC
  92171. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  92172. #endif
  92173. #if JUCE_MAC
  92174. #define FLAC__SYS_DARWIN 1
  92175. #endif
  92176. /*** End of inlined file: juce_FlacHeader.h ***/
  92177. #if JUCE_USE_FLAC
  92178. #if HAVE_CONFIG_H
  92179. # include <config.h>
  92180. #endif
  92181. #include <stdlib.h>
  92182. #include <stdio.h>
  92183. #if defined FLAC__CPU_IA32
  92184. # include <signal.h>
  92185. #elif defined FLAC__CPU_PPC
  92186. # if !defined FLAC__NO_ASM
  92187. # if defined FLAC__SYS_DARWIN
  92188. # include <sys/sysctl.h>
  92189. # include <mach/mach.h>
  92190. # include <mach/mach_host.h>
  92191. # include <mach/host_info.h>
  92192. # include <mach/machine.h>
  92193. # ifndef CPU_SUBTYPE_POWERPC_970
  92194. # define CPU_SUBTYPE_POWERPC_970 ((cpu_subtype_t) 100)
  92195. # endif
  92196. # else /* FLAC__SYS_DARWIN */
  92197. # include <signal.h>
  92198. # include <setjmp.h>
  92199. static sigjmp_buf jmpbuf;
  92200. static volatile sig_atomic_t canjump = 0;
  92201. static void sigill_handler (int sig)
  92202. {
  92203. if (!canjump) {
  92204. signal (sig, SIG_DFL);
  92205. raise (sig);
  92206. }
  92207. canjump = 0;
  92208. siglongjmp (jmpbuf, 1);
  92209. }
  92210. # endif /* FLAC__SYS_DARWIN */
  92211. # endif /* FLAC__NO_ASM */
  92212. #endif /* FLAC__CPU_PPC */
  92213. #if defined (__NetBSD__) || defined(__OpenBSD__)
  92214. #include <sys/param.h>
  92215. #include <sys/sysctl.h>
  92216. #include <machine/cpu.h>
  92217. #endif
  92218. #if defined(__FreeBSD__) || defined(__FreeBSD_kernel__) || defined(__DragonFly__)
  92219. #include <sys/types.h>
  92220. #include <sys/sysctl.h>
  92221. #endif
  92222. #if defined(__APPLE__)
  92223. /* how to get sysctlbyname()? */
  92224. #endif
  92225. /* these are flags in EDX of CPUID AX=00000001 */
  92226. static const unsigned FLAC__CPUINFO_IA32_CPUID_CMOV = 0x00008000;
  92227. static const unsigned FLAC__CPUINFO_IA32_CPUID_MMX = 0x00800000;
  92228. static const unsigned FLAC__CPUINFO_IA32_CPUID_FXSR = 0x01000000;
  92229. static const unsigned FLAC__CPUINFO_IA32_CPUID_SSE = 0x02000000;
  92230. static const unsigned FLAC__CPUINFO_IA32_CPUID_SSE2 = 0x04000000;
  92231. /* these are flags in ECX of CPUID AX=00000001 */
  92232. static const unsigned FLAC__CPUINFO_IA32_CPUID_SSE3 = 0x00000001;
  92233. static const unsigned FLAC__CPUINFO_IA32_CPUID_SSSE3 = 0x00000200;
  92234. /* these are flags in EDX of CPUID AX=80000001 */
  92235. static const unsigned FLAC__CPUINFO_IA32_CPUID_EXTENDED_AMD_3DNOW = 0x80000000;
  92236. static const unsigned FLAC__CPUINFO_IA32_CPUID_EXTENDED_AMD_EXT3DNOW = 0x40000000;
  92237. static const unsigned FLAC__CPUINFO_IA32_CPUID_EXTENDED_AMD_EXTMMX = 0x00400000;
  92238. /*
  92239. * Extra stuff needed for detection of OS support for SSE on IA-32
  92240. */
  92241. #if defined(FLAC__CPU_IA32) && !defined FLAC__NO_ASM && defined FLAC__HAS_NASM && !defined FLAC__NO_SSE_OS && !defined FLAC__SSE_OS
  92242. # if defined(__linux__)
  92243. /*
  92244. * If the OS doesn't support SSE, we will get here with a SIGILL. We
  92245. * modify the return address to jump over the offending SSE instruction
  92246. * and also the operation following it that indicates the instruction
  92247. * executed successfully. In this way we use no global variables and
  92248. * stay thread-safe.
  92249. *
  92250. * 3 + 3 + 6:
  92251. * 3 bytes for "xorps xmm0,xmm0"
  92252. * 3 bytes for estimate of how long the follwing "inc var" instruction is
  92253. * 6 bytes extra in case our estimate is wrong
  92254. * 12 bytes puts us in the NOP "landing zone"
  92255. */
  92256. # undef USE_OBSOLETE_SIGCONTEXT_FLAVOR /* #define this to use the older signal handler method */
  92257. # ifdef USE_OBSOLETE_SIGCONTEXT_FLAVOR
  92258. static void sigill_handler_sse_os(int signal, struct sigcontext sc)
  92259. {
  92260. (void)signal;
  92261. sc.eip += 3 + 3 + 6;
  92262. }
  92263. # else
  92264. # include <sys/ucontext.h>
  92265. static void sigill_handler_sse_os(int signal, siginfo_t *si, void *uc)
  92266. {
  92267. (void)signal, (void)si;
  92268. ((ucontext_t*)uc)->uc_mcontext.gregs[14/*REG_EIP*/] += 3 + 3 + 6;
  92269. }
  92270. # endif
  92271. # elif defined(_MSC_VER)
  92272. # include <windows.h>
  92273. # undef USE_TRY_CATCH_FLAVOR /* #define this to use the try/catch method for catching illegal opcode exception */
  92274. # ifdef USE_TRY_CATCH_FLAVOR
  92275. # else
  92276. LONG CALLBACK sigill_handler_sse_os(EXCEPTION_POINTERS *ep)
  92277. {
  92278. if(ep->ExceptionRecord->ExceptionCode == EXCEPTION_ILLEGAL_INSTRUCTION) {
  92279. ep->ContextRecord->Eip += 3 + 3 + 6;
  92280. return EXCEPTION_CONTINUE_EXECUTION;
  92281. }
  92282. return EXCEPTION_CONTINUE_SEARCH;
  92283. }
  92284. # endif
  92285. # endif
  92286. #endif
  92287. void FLAC__cpu_info(FLAC__CPUInfo *info)
  92288. {
  92289. /*
  92290. * IA32-specific
  92291. */
  92292. #ifdef FLAC__CPU_IA32
  92293. info->type = FLAC__CPUINFO_TYPE_IA32;
  92294. #if !defined FLAC__NO_ASM && defined FLAC__HAS_NASM
  92295. info->use_asm = true; /* we assume a minimum of 80386 with FLAC__CPU_IA32 */
  92296. info->data.ia32.cpuid = FLAC__cpu_have_cpuid_asm_ia32()? true : false;
  92297. info->data.ia32.bswap = info->data.ia32.cpuid; /* CPUID => BSWAP since it came after */
  92298. info->data.ia32.cmov = false;
  92299. info->data.ia32.mmx = false;
  92300. info->data.ia32.fxsr = false;
  92301. info->data.ia32.sse = false;
  92302. info->data.ia32.sse2 = false;
  92303. info->data.ia32.sse3 = false;
  92304. info->data.ia32.ssse3 = false;
  92305. info->data.ia32._3dnow = false;
  92306. info->data.ia32.ext3dnow = false;
  92307. info->data.ia32.extmmx = false;
  92308. if(info->data.ia32.cpuid) {
  92309. /* http://www.sandpile.org/ia32/cpuid.htm */
  92310. FLAC__uint32 flags_edx, flags_ecx;
  92311. FLAC__cpu_info_asm_ia32(&flags_edx, &flags_ecx);
  92312. info->data.ia32.cmov = (flags_edx & FLAC__CPUINFO_IA32_CPUID_CMOV )? true : false;
  92313. info->data.ia32.mmx = (flags_edx & FLAC__CPUINFO_IA32_CPUID_MMX )? true : false;
  92314. info->data.ia32.fxsr = (flags_edx & FLAC__CPUINFO_IA32_CPUID_FXSR )? true : false;
  92315. info->data.ia32.sse = (flags_edx & FLAC__CPUINFO_IA32_CPUID_SSE )? true : false;
  92316. info->data.ia32.sse2 = (flags_edx & FLAC__CPUINFO_IA32_CPUID_SSE2 )? true : false;
  92317. info->data.ia32.sse3 = (flags_ecx & FLAC__CPUINFO_IA32_CPUID_SSE3 )? true : false;
  92318. info->data.ia32.ssse3 = (flags_ecx & FLAC__CPUINFO_IA32_CPUID_SSSE3)? true : false;
  92319. #ifdef FLAC__USE_3DNOW
  92320. flags_edx = FLAC__cpu_info_extended_amd_asm_ia32();
  92321. info->data.ia32._3dnow = (flags_edx & FLAC__CPUINFO_IA32_CPUID_EXTENDED_AMD_3DNOW )? true : false;
  92322. info->data.ia32.ext3dnow = (flags_edx & FLAC__CPUINFO_IA32_CPUID_EXTENDED_AMD_EXT3DNOW)? true : false;
  92323. info->data.ia32.extmmx = (flags_edx & FLAC__CPUINFO_IA32_CPUID_EXTENDED_AMD_EXTMMX )? true : false;
  92324. #else
  92325. info->data.ia32._3dnow = info->data.ia32.ext3dnow = info->data.ia32.extmmx = false;
  92326. #endif
  92327. #ifdef DEBUG
  92328. fprintf(stderr, "CPU info (IA-32):\n");
  92329. fprintf(stderr, " CPUID ...... %c\n", info->data.ia32.cpuid ? 'Y' : 'n');
  92330. fprintf(stderr, " BSWAP ...... %c\n", info->data.ia32.bswap ? 'Y' : 'n');
  92331. fprintf(stderr, " CMOV ....... %c\n", info->data.ia32.cmov ? 'Y' : 'n');
  92332. fprintf(stderr, " MMX ........ %c\n", info->data.ia32.mmx ? 'Y' : 'n');
  92333. fprintf(stderr, " FXSR ....... %c\n", info->data.ia32.fxsr ? 'Y' : 'n');
  92334. fprintf(stderr, " SSE ........ %c\n", info->data.ia32.sse ? 'Y' : 'n');
  92335. fprintf(stderr, " SSE2 ....... %c\n", info->data.ia32.sse2 ? 'Y' : 'n');
  92336. fprintf(stderr, " SSE3 ....... %c\n", info->data.ia32.sse3 ? 'Y' : 'n');
  92337. fprintf(stderr, " SSSE3 ...... %c\n", info->data.ia32.ssse3 ? 'Y' : 'n');
  92338. fprintf(stderr, " 3DNow! ..... %c\n", info->data.ia32._3dnow ? 'Y' : 'n');
  92339. fprintf(stderr, " 3DNow!-ext . %c\n", info->data.ia32.ext3dnow? 'Y' : 'n');
  92340. fprintf(stderr, " 3DNow!-MMX . %c\n", info->data.ia32.extmmx ? 'Y' : 'n');
  92341. #endif
  92342. /*
  92343. * now have to check for OS support of SSE/SSE2
  92344. */
  92345. if(info->data.ia32.fxsr || info->data.ia32.sse || info->data.ia32.sse2) {
  92346. #if defined FLAC__NO_SSE_OS
  92347. /* assume user knows better than us; turn it off */
  92348. info->data.ia32.fxsr = info->data.ia32.sse = info->data.ia32.sse2 = info->data.ia32.sse3 = info->data.ia32.ssse3 = false;
  92349. #elif defined FLAC__SSE_OS
  92350. /* assume user knows better than us; leave as detected above */
  92351. #elif defined(__FreeBSD__) || defined(__FreeBSD_kernel__) || defined(__DragonFly__) || defined(__APPLE__)
  92352. int sse = 0;
  92353. size_t len;
  92354. /* at least one of these must work: */
  92355. len = sizeof(sse); sse = sse || (sysctlbyname("hw.instruction_sse", &sse, &len, NULL, 0) == 0 && sse);
  92356. len = sizeof(sse); sse = sse || (sysctlbyname("hw.optional.sse" , &sse, &len, NULL, 0) == 0 && sse); /* __APPLE__ ? */
  92357. if(!sse)
  92358. info->data.ia32.fxsr = info->data.ia32.sse = info->data.ia32.sse2 = info->data.ia32.sse3 = info->data.ia32.ssse3 = false;
  92359. #elif defined(__NetBSD__) || defined (__OpenBSD__)
  92360. # if __NetBSD_Version__ >= 105250000 || (defined __OpenBSD__)
  92361. int val = 0, mib[2] = { CTL_MACHDEP, CPU_SSE };
  92362. size_t len = sizeof(val);
  92363. if(sysctl(mib, 2, &val, &len, NULL, 0) < 0 || !val)
  92364. info->data.ia32.fxsr = info->data.ia32.sse = info->data.ia32.sse2 = info->data.ia32.sse3 = info->data.ia32.ssse3 = false;
  92365. else { /* double-check SSE2 */
  92366. mib[1] = CPU_SSE2;
  92367. len = sizeof(val);
  92368. if(sysctl(mib, 2, &val, &len, NULL, 0) < 0 || !val)
  92369. info->data.ia32.sse2 = info->data.ia32.sse3 = info->data.ia32.ssse3 = false;
  92370. }
  92371. # else
  92372. info->data.ia32.fxsr = info->data.ia32.sse = info->data.ia32.sse2 = info->data.ia32.sse3 = info->data.ia32.ssse3 = false;
  92373. # endif
  92374. #elif defined(__linux__)
  92375. int sse = 0;
  92376. struct sigaction sigill_save;
  92377. #ifdef USE_OBSOLETE_SIGCONTEXT_FLAVOR
  92378. if(0 == sigaction(SIGILL, NULL, &sigill_save) && signal(SIGILL, (void (*)(int))sigill_handler_sse_os) != SIG_ERR)
  92379. #else
  92380. struct sigaction sigill_sse;
  92381. sigill_sse.sa_sigaction = sigill_handler_sse_os;
  92382. __sigemptyset(&sigill_sse.sa_mask);
  92383. 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 */
  92384. if(0 == sigaction(SIGILL, &sigill_sse, &sigill_save))
  92385. #endif
  92386. {
  92387. /* http://www.ibiblio.org/gferg/ldp/GCC-Inline-Assembly-HOWTO.html */
  92388. /* see sigill_handler_sse_os() for an explanation of the following: */
  92389. asm volatile (
  92390. "xorl %0,%0\n\t" /* for some reason, still need to do this to clear 'sse' var */
  92391. "xorps %%xmm0,%%xmm0\n\t" /* will cause SIGILL if unsupported by OS */
  92392. "incl %0\n\t" /* SIGILL handler will jump over this */
  92393. /* landing zone */
  92394. "nop\n\t" /* SIGILL jump lands here if "inc" is 9 bytes */
  92395. "nop\n\t"
  92396. "nop\n\t"
  92397. "nop\n\t"
  92398. "nop\n\t"
  92399. "nop\n\t"
  92400. "nop\n\t" /* SIGILL jump lands here if "inc" is 3 bytes (expected) */
  92401. "nop\n\t"
  92402. "nop" /* SIGILL jump lands here if "inc" is 1 byte */
  92403. : "=r"(sse)
  92404. : "r"(sse)
  92405. );
  92406. sigaction(SIGILL, &sigill_save, NULL);
  92407. }
  92408. if(!sse)
  92409. info->data.ia32.fxsr = info->data.ia32.sse = info->data.ia32.sse2 = info->data.ia32.sse3 = info->data.ia32.ssse3 = false;
  92410. #elif defined(_MSC_VER)
  92411. # ifdef USE_TRY_CATCH_FLAVOR
  92412. _try {
  92413. __asm {
  92414. # if _MSC_VER <= 1200
  92415. /* VC6 assembler doesn't know SSE, have to emit bytecode instead */
  92416. _emit 0x0F
  92417. _emit 0x57
  92418. _emit 0xC0
  92419. # else
  92420. xorps xmm0,xmm0
  92421. # endif
  92422. }
  92423. }
  92424. _except(EXCEPTION_EXECUTE_HANDLER) {
  92425. if (_exception_code() == STATUS_ILLEGAL_INSTRUCTION)
  92426. info->data.ia32.fxsr = info->data.ia32.sse = info->data.ia32.sse2 = info->data.ia32.sse3 = info->data.ia32.ssse3 = false;
  92427. }
  92428. # else
  92429. int sse = 0;
  92430. LPTOP_LEVEL_EXCEPTION_FILTER save = SetUnhandledExceptionFilter(sigill_handler_sse_os);
  92431. /* see GCC version above for explanation */
  92432. /* http://msdn2.microsoft.com/en-us/library/4ks26t93.aspx */
  92433. /* http://www.codeproject.com/cpp/gccasm.asp */
  92434. /* http://www.hick.org/~mmiller/msvc_inline_asm.html */
  92435. __asm {
  92436. # if _MSC_VER <= 1200
  92437. /* VC6 assembler doesn't know SSE, have to emit bytecode instead */
  92438. _emit 0x0F
  92439. _emit 0x57
  92440. _emit 0xC0
  92441. # else
  92442. xorps xmm0,xmm0
  92443. # endif
  92444. inc sse
  92445. nop
  92446. nop
  92447. nop
  92448. nop
  92449. nop
  92450. nop
  92451. nop
  92452. nop
  92453. nop
  92454. }
  92455. SetUnhandledExceptionFilter(save);
  92456. if(!sse)
  92457. info->data.ia32.fxsr = info->data.ia32.sse = info->data.ia32.sse2 = info->data.ia32.sse3 = info->data.ia32.ssse3 = false;
  92458. # endif
  92459. #else
  92460. /* no way to test, disable to be safe */
  92461. info->data.ia32.fxsr = info->data.ia32.sse = info->data.ia32.sse2 = info->data.ia32.sse3 = info->data.ia32.ssse3 = false;
  92462. #endif
  92463. #ifdef DEBUG
  92464. fprintf(stderr, " SSE OS sup . %c\n", info->data.ia32.sse ? 'Y' : 'n');
  92465. #endif
  92466. }
  92467. }
  92468. #else
  92469. info->use_asm = false;
  92470. #endif
  92471. /*
  92472. * PPC-specific
  92473. */
  92474. #elif defined FLAC__CPU_PPC
  92475. info->type = FLAC__CPUINFO_TYPE_PPC;
  92476. # if !defined FLAC__NO_ASM
  92477. info->use_asm = true;
  92478. # ifdef FLAC__USE_ALTIVEC
  92479. # if defined FLAC__SYS_DARWIN
  92480. {
  92481. int val = 0, mib[2] = { CTL_HW, HW_VECTORUNIT };
  92482. size_t len = sizeof(val);
  92483. info->data.ppc.altivec = !(sysctl(mib, 2, &val, &len, NULL, 0) || !val);
  92484. }
  92485. {
  92486. host_basic_info_data_t hostInfo;
  92487. mach_msg_type_number_t infoCount;
  92488. infoCount = HOST_BASIC_INFO_COUNT;
  92489. host_info(mach_host_self(), HOST_BASIC_INFO, (host_info_t)&hostInfo, &infoCount);
  92490. info->data.ppc.ppc64 = (hostInfo.cpu_type == CPU_TYPE_POWERPC) && (hostInfo.cpu_subtype == CPU_SUBTYPE_POWERPC_970);
  92491. }
  92492. # else /* FLAC__USE_ALTIVEC && !FLAC__SYS_DARWIN */
  92493. {
  92494. /* no Darwin, do it the brute-force way */
  92495. /* @@@@@@ this is not thread-safe; replace with SSE OS method above or remove */
  92496. info->data.ppc.altivec = 0;
  92497. info->data.ppc.ppc64 = 0;
  92498. signal (SIGILL, sigill_handler);
  92499. canjump = 0;
  92500. if (!sigsetjmp (jmpbuf, 1)) {
  92501. canjump = 1;
  92502. asm volatile (
  92503. "mtspr 256, %0\n\t"
  92504. "vand %%v0, %%v0, %%v0"
  92505. :
  92506. : "r" (-1)
  92507. );
  92508. info->data.ppc.altivec = 1;
  92509. }
  92510. canjump = 0;
  92511. if (!sigsetjmp (jmpbuf, 1)) {
  92512. int x = 0;
  92513. canjump = 1;
  92514. /* PPC64 hardware implements the cntlzd instruction */
  92515. asm volatile ("cntlzd %0, %1" : "=r" (x) : "r" (x) );
  92516. info->data.ppc.ppc64 = 1;
  92517. }
  92518. signal (SIGILL, SIG_DFL); /*@@@@@@ should save and restore old signal */
  92519. }
  92520. # endif
  92521. # else /* !FLAC__USE_ALTIVEC */
  92522. info->data.ppc.altivec = 0;
  92523. info->data.ppc.ppc64 = 0;
  92524. # endif
  92525. # else
  92526. info->use_asm = false;
  92527. # endif
  92528. /*
  92529. * unknown CPI
  92530. */
  92531. #else
  92532. info->type = FLAC__CPUINFO_TYPE_UNKNOWN;
  92533. info->use_asm = false;
  92534. #endif
  92535. }
  92536. #endif
  92537. /*** End of inlined file: cpu.c ***/
  92538. /*** Start of inlined file: crc.c ***/
  92539. /*** Start of inlined file: juce_FlacHeader.h ***/
  92540. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  92541. // tasks..
  92542. #define VERSION "1.2.1"
  92543. #define FLAC__NO_DLL 1
  92544. #if JUCE_MSVC
  92545. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  92546. #endif
  92547. #if JUCE_MAC
  92548. #define FLAC__SYS_DARWIN 1
  92549. #endif
  92550. /*** End of inlined file: juce_FlacHeader.h ***/
  92551. #if JUCE_USE_FLAC
  92552. #if HAVE_CONFIG_H
  92553. # include <config.h>
  92554. #endif
  92555. /* CRC-8, poly = x^8 + x^2 + x^1 + x^0, init = 0 */
  92556. FLAC__byte const FLAC__crc8_table[256] = {
  92557. 0x00, 0x07, 0x0E, 0x09, 0x1C, 0x1B, 0x12, 0x15,
  92558. 0x38, 0x3F, 0x36, 0x31, 0x24, 0x23, 0x2A, 0x2D,
  92559. 0x70, 0x77, 0x7E, 0x79, 0x6C, 0x6B, 0x62, 0x65,
  92560. 0x48, 0x4F, 0x46, 0x41, 0x54, 0x53, 0x5A, 0x5D,
  92561. 0xE0, 0xE7, 0xEE, 0xE9, 0xFC, 0xFB, 0xF2, 0xF5,
  92562. 0xD8, 0xDF, 0xD6, 0xD1, 0xC4, 0xC3, 0xCA, 0xCD,
  92563. 0x90, 0x97, 0x9E, 0x99, 0x8C, 0x8B, 0x82, 0x85,
  92564. 0xA8, 0xAF, 0xA6, 0xA1, 0xB4, 0xB3, 0xBA, 0xBD,
  92565. 0xC7, 0xC0, 0xC9, 0xCE, 0xDB, 0xDC, 0xD5, 0xD2,
  92566. 0xFF, 0xF8, 0xF1, 0xF6, 0xE3, 0xE4, 0xED, 0xEA,
  92567. 0xB7, 0xB0, 0xB9, 0xBE, 0xAB, 0xAC, 0xA5, 0xA2,
  92568. 0x8F, 0x88, 0x81, 0x86, 0x93, 0x94, 0x9D, 0x9A,
  92569. 0x27, 0x20, 0x29, 0x2E, 0x3B, 0x3C, 0x35, 0x32,
  92570. 0x1F, 0x18, 0x11, 0x16, 0x03, 0x04, 0x0D, 0x0A,
  92571. 0x57, 0x50, 0x59, 0x5E, 0x4B, 0x4C, 0x45, 0x42,
  92572. 0x6F, 0x68, 0x61, 0x66, 0x73, 0x74, 0x7D, 0x7A,
  92573. 0x89, 0x8E, 0x87, 0x80, 0x95, 0x92, 0x9B, 0x9C,
  92574. 0xB1, 0xB6, 0xBF, 0xB8, 0xAD, 0xAA, 0xA3, 0xA4,
  92575. 0xF9, 0xFE, 0xF7, 0xF0, 0xE5, 0xE2, 0xEB, 0xEC,
  92576. 0xC1, 0xC6, 0xCF, 0xC8, 0xDD, 0xDA, 0xD3, 0xD4,
  92577. 0x69, 0x6E, 0x67, 0x60, 0x75, 0x72, 0x7B, 0x7C,
  92578. 0x51, 0x56, 0x5F, 0x58, 0x4D, 0x4A, 0x43, 0x44,
  92579. 0x19, 0x1E, 0x17, 0x10, 0x05, 0x02, 0x0B, 0x0C,
  92580. 0x21, 0x26, 0x2F, 0x28, 0x3D, 0x3A, 0x33, 0x34,
  92581. 0x4E, 0x49, 0x40, 0x47, 0x52, 0x55, 0x5C, 0x5B,
  92582. 0x76, 0x71, 0x78, 0x7F, 0x6A, 0x6D, 0x64, 0x63,
  92583. 0x3E, 0x39, 0x30, 0x37, 0x22, 0x25, 0x2C, 0x2B,
  92584. 0x06, 0x01, 0x08, 0x0F, 0x1A, 0x1D, 0x14, 0x13,
  92585. 0xAE, 0xA9, 0xA0, 0xA7, 0xB2, 0xB5, 0xBC, 0xBB,
  92586. 0x96, 0x91, 0x98, 0x9F, 0x8A, 0x8D, 0x84, 0x83,
  92587. 0xDE, 0xD9, 0xD0, 0xD7, 0xC2, 0xC5, 0xCC, 0xCB,
  92588. 0xE6, 0xE1, 0xE8, 0xEF, 0xFA, 0xFD, 0xF4, 0xF3
  92589. };
  92590. /* CRC-16, poly = x^16 + x^15 + x^2 + x^0, init = 0 */
  92591. unsigned FLAC__crc16_table[256] = {
  92592. 0x0000, 0x8005, 0x800f, 0x000a, 0x801b, 0x001e, 0x0014, 0x8011,
  92593. 0x8033, 0x0036, 0x003c, 0x8039, 0x0028, 0x802d, 0x8027, 0x0022,
  92594. 0x8063, 0x0066, 0x006c, 0x8069, 0x0078, 0x807d, 0x8077, 0x0072,
  92595. 0x0050, 0x8055, 0x805f, 0x005a, 0x804b, 0x004e, 0x0044, 0x8041,
  92596. 0x80c3, 0x00c6, 0x00cc, 0x80c9, 0x00d8, 0x80dd, 0x80d7, 0x00d2,
  92597. 0x00f0, 0x80f5, 0x80ff, 0x00fa, 0x80eb, 0x00ee, 0x00e4, 0x80e1,
  92598. 0x00a0, 0x80a5, 0x80af, 0x00aa, 0x80bb, 0x00be, 0x00b4, 0x80b1,
  92599. 0x8093, 0x0096, 0x009c, 0x8099, 0x0088, 0x808d, 0x8087, 0x0082,
  92600. 0x8183, 0x0186, 0x018c, 0x8189, 0x0198, 0x819d, 0x8197, 0x0192,
  92601. 0x01b0, 0x81b5, 0x81bf, 0x01ba, 0x81ab, 0x01ae, 0x01a4, 0x81a1,
  92602. 0x01e0, 0x81e5, 0x81ef, 0x01ea, 0x81fb, 0x01fe, 0x01f4, 0x81f1,
  92603. 0x81d3, 0x01d6, 0x01dc, 0x81d9, 0x01c8, 0x81cd, 0x81c7, 0x01c2,
  92604. 0x0140, 0x8145, 0x814f, 0x014a, 0x815b, 0x015e, 0x0154, 0x8151,
  92605. 0x8173, 0x0176, 0x017c, 0x8179, 0x0168, 0x816d, 0x8167, 0x0162,
  92606. 0x8123, 0x0126, 0x012c, 0x8129, 0x0138, 0x813d, 0x8137, 0x0132,
  92607. 0x0110, 0x8115, 0x811f, 0x011a, 0x810b, 0x010e, 0x0104, 0x8101,
  92608. 0x8303, 0x0306, 0x030c, 0x8309, 0x0318, 0x831d, 0x8317, 0x0312,
  92609. 0x0330, 0x8335, 0x833f, 0x033a, 0x832b, 0x032e, 0x0324, 0x8321,
  92610. 0x0360, 0x8365, 0x836f, 0x036a, 0x837b, 0x037e, 0x0374, 0x8371,
  92611. 0x8353, 0x0356, 0x035c, 0x8359, 0x0348, 0x834d, 0x8347, 0x0342,
  92612. 0x03c0, 0x83c5, 0x83cf, 0x03ca, 0x83db, 0x03de, 0x03d4, 0x83d1,
  92613. 0x83f3, 0x03f6, 0x03fc, 0x83f9, 0x03e8, 0x83ed, 0x83e7, 0x03e2,
  92614. 0x83a3, 0x03a6, 0x03ac, 0x83a9, 0x03b8, 0x83bd, 0x83b7, 0x03b2,
  92615. 0x0390, 0x8395, 0x839f, 0x039a, 0x838b, 0x038e, 0x0384, 0x8381,
  92616. 0x0280, 0x8285, 0x828f, 0x028a, 0x829b, 0x029e, 0x0294, 0x8291,
  92617. 0x82b3, 0x02b6, 0x02bc, 0x82b9, 0x02a8, 0x82ad, 0x82a7, 0x02a2,
  92618. 0x82e3, 0x02e6, 0x02ec, 0x82e9, 0x02f8, 0x82fd, 0x82f7, 0x02f2,
  92619. 0x02d0, 0x82d5, 0x82df, 0x02da, 0x82cb, 0x02ce, 0x02c4, 0x82c1,
  92620. 0x8243, 0x0246, 0x024c, 0x8249, 0x0258, 0x825d, 0x8257, 0x0252,
  92621. 0x0270, 0x8275, 0x827f, 0x027a, 0x826b, 0x026e, 0x0264, 0x8261,
  92622. 0x0220, 0x8225, 0x822f, 0x022a, 0x823b, 0x023e, 0x0234, 0x8231,
  92623. 0x8213, 0x0216, 0x021c, 0x8219, 0x0208, 0x820d, 0x8207, 0x0202
  92624. };
  92625. void FLAC__crc8_update(const FLAC__byte data, FLAC__uint8 *crc)
  92626. {
  92627. *crc = FLAC__crc8_table[*crc ^ data];
  92628. }
  92629. void FLAC__crc8_update_block(const FLAC__byte *data, unsigned len, FLAC__uint8 *crc)
  92630. {
  92631. while(len--)
  92632. *crc = FLAC__crc8_table[*crc ^ *data++];
  92633. }
  92634. FLAC__uint8 FLAC__crc8(const FLAC__byte *data, unsigned len)
  92635. {
  92636. FLAC__uint8 crc = 0;
  92637. while(len--)
  92638. crc = FLAC__crc8_table[crc ^ *data++];
  92639. return crc;
  92640. }
  92641. unsigned FLAC__crc16(const FLAC__byte *data, unsigned len)
  92642. {
  92643. unsigned crc = 0;
  92644. while(len--)
  92645. crc = ((crc<<8) ^ FLAC__crc16_table[(crc>>8) ^ *data++]) & 0xffff;
  92646. return crc;
  92647. }
  92648. #endif
  92649. /*** End of inlined file: crc.c ***/
  92650. /*** Start of inlined file: fixed.c ***/
  92651. /*** Start of inlined file: juce_FlacHeader.h ***/
  92652. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  92653. // tasks..
  92654. #define VERSION "1.2.1"
  92655. #define FLAC__NO_DLL 1
  92656. #if JUCE_MSVC
  92657. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  92658. #endif
  92659. #if JUCE_MAC
  92660. #define FLAC__SYS_DARWIN 1
  92661. #endif
  92662. /*** End of inlined file: juce_FlacHeader.h ***/
  92663. #if JUCE_USE_FLAC
  92664. #if HAVE_CONFIG_H
  92665. # include <config.h>
  92666. #endif
  92667. #include <math.h>
  92668. #include <string.h>
  92669. /*** Start of inlined file: fixed.h ***/
  92670. #ifndef FLAC__PRIVATE__FIXED_H
  92671. #define FLAC__PRIVATE__FIXED_H
  92672. #ifdef HAVE_CONFIG_H
  92673. #include <config.h>
  92674. #endif
  92675. /*** Start of inlined file: float.h ***/
  92676. #ifndef FLAC__PRIVATE__FLOAT_H
  92677. #define FLAC__PRIVATE__FLOAT_H
  92678. #ifdef HAVE_CONFIG_H
  92679. #include <config.h>
  92680. #endif
  92681. /*
  92682. * These typedefs make it easier to ensure that integer versions of
  92683. * the library really only contain integer operations. All the code
  92684. * in libFLAC should use FLAC__float and FLAC__double in place of
  92685. * float and double, and be protected by checks of the macro
  92686. * FLAC__INTEGER_ONLY_LIBRARY.
  92687. *
  92688. * FLAC__real is the basic floating point type used in LPC analysis.
  92689. */
  92690. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  92691. typedef double FLAC__double;
  92692. typedef float FLAC__float;
  92693. /*
  92694. * WATCHOUT: changing FLAC__real will change the signatures of many
  92695. * functions that have assembly language equivalents and break them.
  92696. */
  92697. typedef float FLAC__real;
  92698. #else
  92699. /*
  92700. * The convention for FLAC__fixedpoint is to use the upper 16 bits
  92701. * for the integer part and lower 16 bits for the fractional part.
  92702. */
  92703. typedef FLAC__int32 FLAC__fixedpoint;
  92704. extern const FLAC__fixedpoint FLAC__FP_ZERO;
  92705. extern const FLAC__fixedpoint FLAC__FP_ONE_HALF;
  92706. extern const FLAC__fixedpoint FLAC__FP_ONE;
  92707. extern const FLAC__fixedpoint FLAC__FP_LN2;
  92708. extern const FLAC__fixedpoint FLAC__FP_E;
  92709. #define FLAC__fixedpoint_trunc(x) ((x)>>16)
  92710. #define FLAC__fixedpoint_mul(x, y) ( (FLAC__fixedpoint) ( ((FLAC__int64)(x)*(FLAC__int64)(y)) >> 16 ) )
  92711. #define FLAC__fixedpoint_div(x, y) ( (FLAC__fixedpoint) ( ( ((FLAC__int64)(x)<<32) / (FLAC__int64)(y) ) >> 16 ) )
  92712. /*
  92713. * FLAC__fixedpoint_log2()
  92714. * --------------------------------------------------------------------
  92715. * Returns the base-2 logarithm of the fixed-point number 'x' using an
  92716. * algorithm by Knuth for x >= 1.0
  92717. *
  92718. * 'fracbits' is the number of fractional bits of 'x'. 'fracbits' must
  92719. * be < 32 and evenly divisible by 4 (0 is OK but not very precise).
  92720. *
  92721. * 'precision' roughly limits the number of iterations that are done;
  92722. * use (unsigned)(-1) for maximum precision.
  92723. *
  92724. * If 'x' is less than one -- that is, x < (1<<fracbits) -- then this
  92725. * function will punt and return 0.
  92726. *
  92727. * The return value will also have 'fracbits' fractional bits.
  92728. */
  92729. FLAC__uint32 FLAC__fixedpoint_log2(FLAC__uint32 x, unsigned fracbits, unsigned precision);
  92730. #endif
  92731. #endif
  92732. /*** End of inlined file: float.h ***/
  92733. /*** Start of inlined file: format.h ***/
  92734. #ifndef FLAC__PRIVATE__FORMAT_H
  92735. #define FLAC__PRIVATE__FORMAT_H
  92736. unsigned FLAC__format_get_max_rice_partition_order(unsigned blocksize, unsigned predictor_order);
  92737. unsigned FLAC__format_get_max_rice_partition_order_from_blocksize(unsigned blocksize);
  92738. unsigned FLAC__format_get_max_rice_partition_order_from_blocksize_limited_max_and_predictor_order(unsigned limit, unsigned blocksize, unsigned predictor_order);
  92739. void FLAC__format_entropy_coding_method_partitioned_rice_contents_init(FLAC__EntropyCodingMethod_PartitionedRiceContents *object);
  92740. void FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(FLAC__EntropyCodingMethod_PartitionedRiceContents *object);
  92741. FLAC__bool FLAC__format_entropy_coding_method_partitioned_rice_contents_ensure_size(FLAC__EntropyCodingMethod_PartitionedRiceContents *object, unsigned max_partition_order);
  92742. #endif
  92743. /*** End of inlined file: format.h ***/
  92744. /*
  92745. * FLAC__fixed_compute_best_predictor()
  92746. * --------------------------------------------------------------------
  92747. * Compute the best fixed predictor and the expected bits-per-sample
  92748. * of the residual signal for each order. The _wide() version uses
  92749. * 64-bit integers which is statistically necessary when bits-per-
  92750. * sample + log2(blocksize) > 30
  92751. *
  92752. * IN data[0,data_len-1]
  92753. * IN data_len
  92754. * OUT residual_bits_per_sample[0,FLAC__MAX_FIXED_ORDER]
  92755. */
  92756. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  92757. unsigned FLAC__fixed_compute_best_predictor(const FLAC__int32 data[], unsigned data_len, FLAC__float residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1]);
  92758. # ifndef FLAC__NO_ASM
  92759. # ifdef FLAC__CPU_IA32
  92760. # ifdef FLAC__HAS_NASM
  92761. 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]);
  92762. # endif
  92763. # endif
  92764. # endif
  92765. 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]);
  92766. #else
  92767. unsigned FLAC__fixed_compute_best_predictor(const FLAC__int32 data[], unsigned data_len, FLAC__fixedpoint residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1]);
  92768. 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]);
  92769. #endif
  92770. /*
  92771. * FLAC__fixed_compute_residual()
  92772. * --------------------------------------------------------------------
  92773. * Compute the residual signal obtained from sutracting the predicted
  92774. * signal from the original.
  92775. *
  92776. * IN data[-order,data_len-1] original signal (NOTE THE INDICES!)
  92777. * IN data_len length of original signal
  92778. * IN order <= FLAC__MAX_FIXED_ORDER fixed-predictor order
  92779. * OUT residual[0,data_len-1] residual signal
  92780. */
  92781. void FLAC__fixed_compute_residual(const FLAC__int32 data[], unsigned data_len, unsigned order, FLAC__int32 residual[]);
  92782. /*
  92783. * FLAC__fixed_restore_signal()
  92784. * --------------------------------------------------------------------
  92785. * Restore the original signal by summing the residual and the
  92786. * predictor.
  92787. *
  92788. * IN residual[0,data_len-1] residual signal
  92789. * IN data_len length of original signal
  92790. * IN order <= FLAC__MAX_FIXED_ORDER fixed-predictor order
  92791. * *** IMPORTANT: the caller must pass in the historical samples:
  92792. * IN data[-order,-1] previously-reconstructed historical samples
  92793. * OUT data[0,data_len-1] original signal
  92794. */
  92795. void FLAC__fixed_restore_signal(const FLAC__int32 residual[], unsigned data_len, unsigned order, FLAC__int32 data[]);
  92796. #endif
  92797. /*** End of inlined file: fixed.h ***/
  92798. #ifndef M_LN2
  92799. /* math.h in VC++ doesn't seem to have this (how Microsoft is that?) */
  92800. #define M_LN2 0.69314718055994530942
  92801. #endif
  92802. #ifdef min
  92803. #undef min
  92804. #endif
  92805. #define min(x,y) ((x) < (y)? (x) : (y))
  92806. #ifdef local_abs
  92807. #undef local_abs
  92808. #endif
  92809. #define local_abs(x) ((unsigned)((x)<0? -(x) : (x)))
  92810. #ifdef FLAC__INTEGER_ONLY_LIBRARY
  92811. /* rbps stands for residual bits per sample
  92812. *
  92813. * (ln(2) * err)
  92814. * rbps = log (-----------)
  92815. * 2 ( n )
  92816. */
  92817. static FLAC__fixedpoint local__compute_rbps_integerized(FLAC__uint32 err, FLAC__uint32 n)
  92818. {
  92819. FLAC__uint32 rbps;
  92820. unsigned bits; /* the number of bits required to represent a number */
  92821. int fracbits; /* the number of bits of rbps that comprise the fractional part */
  92822. FLAC__ASSERT(sizeof(rbps) == sizeof(FLAC__fixedpoint));
  92823. FLAC__ASSERT(err > 0);
  92824. FLAC__ASSERT(n > 0);
  92825. FLAC__ASSERT(n <= FLAC__MAX_BLOCK_SIZE);
  92826. if(err <= n)
  92827. return 0;
  92828. /*
  92829. * The above two things tell us 1) n fits in 16 bits; 2) err/n > 1.
  92830. * These allow us later to know we won't lose too much precision in the
  92831. * fixed-point division (err<<fracbits)/n.
  92832. */
  92833. fracbits = (8*sizeof(err)) - (FLAC__bitmath_ilog2(err)+1);
  92834. err <<= fracbits;
  92835. err /= n;
  92836. /* err now holds err/n with fracbits fractional bits */
  92837. /*
  92838. * Whittle err down to 16 bits max. 16 significant bits is enough for
  92839. * our purposes.
  92840. */
  92841. FLAC__ASSERT(err > 0);
  92842. bits = FLAC__bitmath_ilog2(err)+1;
  92843. if(bits > 16) {
  92844. err >>= (bits-16);
  92845. fracbits -= (bits-16);
  92846. }
  92847. rbps = (FLAC__uint32)err;
  92848. /* Multiply by fixed-point version of ln(2), with 16 fractional bits */
  92849. rbps *= FLAC__FP_LN2;
  92850. fracbits += 16;
  92851. FLAC__ASSERT(fracbits >= 0);
  92852. /* FLAC__fixedpoint_log2 requires fracbits%4 to be 0 */
  92853. {
  92854. const int f = fracbits & 3;
  92855. if(f) {
  92856. rbps >>= f;
  92857. fracbits -= f;
  92858. }
  92859. }
  92860. rbps = FLAC__fixedpoint_log2(rbps, fracbits, (unsigned)(-1));
  92861. if(rbps == 0)
  92862. return 0;
  92863. /*
  92864. * The return value must have 16 fractional bits. Since the whole part
  92865. * of the base-2 log of a 32 bit number must fit in 5 bits, and fracbits
  92866. * must be >= -3, these assertion allows us to be able to shift rbps
  92867. * left if necessary to get 16 fracbits without losing any bits of the
  92868. * whole part of rbps.
  92869. *
  92870. * There is a slight chance due to accumulated error that the whole part
  92871. * will require 6 bits, so we use 6 in the assertion. Really though as
  92872. * long as it fits in 13 bits (32 - (16 - (-3))) we are fine.
  92873. */
  92874. FLAC__ASSERT((int)FLAC__bitmath_ilog2(rbps)+1 <= fracbits + 6);
  92875. FLAC__ASSERT(fracbits >= -3);
  92876. /* now shift the decimal point into place */
  92877. if(fracbits < 16)
  92878. return rbps << (16-fracbits);
  92879. else if(fracbits > 16)
  92880. return rbps >> (fracbits-16);
  92881. else
  92882. return rbps;
  92883. }
  92884. static FLAC__fixedpoint local__compute_rbps_wide_integerized(FLAC__uint64 err, FLAC__uint32 n)
  92885. {
  92886. FLAC__uint32 rbps;
  92887. unsigned bits; /* the number of bits required to represent a number */
  92888. int fracbits; /* the number of bits of rbps that comprise the fractional part */
  92889. FLAC__ASSERT(sizeof(rbps) == sizeof(FLAC__fixedpoint));
  92890. FLAC__ASSERT(err > 0);
  92891. FLAC__ASSERT(n > 0);
  92892. FLAC__ASSERT(n <= FLAC__MAX_BLOCK_SIZE);
  92893. if(err <= n)
  92894. return 0;
  92895. /*
  92896. * The above two things tell us 1) n fits in 16 bits; 2) err/n > 1.
  92897. * These allow us later to know we won't lose too much precision in the
  92898. * fixed-point division (err<<fracbits)/n.
  92899. */
  92900. fracbits = (8*sizeof(err)) - (FLAC__bitmath_ilog2_wide(err)+1);
  92901. err <<= fracbits;
  92902. err /= n;
  92903. /* err now holds err/n with fracbits fractional bits */
  92904. /*
  92905. * Whittle err down to 16 bits max. 16 significant bits is enough for
  92906. * our purposes.
  92907. */
  92908. FLAC__ASSERT(err > 0);
  92909. bits = FLAC__bitmath_ilog2_wide(err)+1;
  92910. if(bits > 16) {
  92911. err >>= (bits-16);
  92912. fracbits -= (bits-16);
  92913. }
  92914. rbps = (FLAC__uint32)err;
  92915. /* Multiply by fixed-point version of ln(2), with 16 fractional bits */
  92916. rbps *= FLAC__FP_LN2;
  92917. fracbits += 16;
  92918. FLAC__ASSERT(fracbits >= 0);
  92919. /* FLAC__fixedpoint_log2 requires fracbits%4 to be 0 */
  92920. {
  92921. const int f = fracbits & 3;
  92922. if(f) {
  92923. rbps >>= f;
  92924. fracbits -= f;
  92925. }
  92926. }
  92927. rbps = FLAC__fixedpoint_log2(rbps, fracbits, (unsigned)(-1));
  92928. if(rbps == 0)
  92929. return 0;
  92930. /*
  92931. * The return value must have 16 fractional bits. Since the whole part
  92932. * of the base-2 log of a 32 bit number must fit in 5 bits, and fracbits
  92933. * must be >= -3, these assertion allows us to be able to shift rbps
  92934. * left if necessary to get 16 fracbits without losing any bits of the
  92935. * whole part of rbps.
  92936. *
  92937. * There is a slight chance due to accumulated error that the whole part
  92938. * will require 6 bits, so we use 6 in the assertion. Really though as
  92939. * long as it fits in 13 bits (32 - (16 - (-3))) we are fine.
  92940. */
  92941. FLAC__ASSERT((int)FLAC__bitmath_ilog2(rbps)+1 <= fracbits + 6);
  92942. FLAC__ASSERT(fracbits >= -3);
  92943. /* now shift the decimal point into place */
  92944. if(fracbits < 16)
  92945. return rbps << (16-fracbits);
  92946. else if(fracbits > 16)
  92947. return rbps >> (fracbits-16);
  92948. else
  92949. return rbps;
  92950. }
  92951. #endif
  92952. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  92953. unsigned FLAC__fixed_compute_best_predictor(const FLAC__int32 data[], unsigned data_len, FLAC__float residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1])
  92954. #else
  92955. unsigned FLAC__fixed_compute_best_predictor(const FLAC__int32 data[], unsigned data_len, FLAC__fixedpoint residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1])
  92956. #endif
  92957. {
  92958. FLAC__int32 last_error_0 = data[-1];
  92959. FLAC__int32 last_error_1 = data[-1] - data[-2];
  92960. FLAC__int32 last_error_2 = last_error_1 - (data[-2] - data[-3]);
  92961. FLAC__int32 last_error_3 = last_error_2 - (data[-2] - 2*data[-3] + data[-4]);
  92962. FLAC__int32 error, save;
  92963. FLAC__uint32 total_error_0 = 0, total_error_1 = 0, total_error_2 = 0, total_error_3 = 0, total_error_4 = 0;
  92964. unsigned i, order;
  92965. for(i = 0; i < data_len; i++) {
  92966. error = data[i] ; total_error_0 += local_abs(error); save = error;
  92967. error -= last_error_0; total_error_1 += local_abs(error); last_error_0 = save; save = error;
  92968. error -= last_error_1; total_error_2 += local_abs(error); last_error_1 = save; save = error;
  92969. error -= last_error_2; total_error_3 += local_abs(error); last_error_2 = save; save = error;
  92970. error -= last_error_3; total_error_4 += local_abs(error); last_error_3 = save;
  92971. }
  92972. if(total_error_0 < min(min(min(total_error_1, total_error_2), total_error_3), total_error_4))
  92973. order = 0;
  92974. else if(total_error_1 < min(min(total_error_2, total_error_3), total_error_4))
  92975. order = 1;
  92976. else if(total_error_2 < min(total_error_3, total_error_4))
  92977. order = 2;
  92978. else if(total_error_3 < total_error_4)
  92979. order = 3;
  92980. else
  92981. order = 4;
  92982. /* Estimate the expected number of bits per residual signal sample. */
  92983. /* 'total_error*' is linearly related to the variance of the residual */
  92984. /* signal, so we use it directly to compute E(|x|) */
  92985. FLAC__ASSERT(data_len > 0 || total_error_0 == 0);
  92986. FLAC__ASSERT(data_len > 0 || total_error_1 == 0);
  92987. FLAC__ASSERT(data_len > 0 || total_error_2 == 0);
  92988. FLAC__ASSERT(data_len > 0 || total_error_3 == 0);
  92989. FLAC__ASSERT(data_len > 0 || total_error_4 == 0);
  92990. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  92991. 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);
  92992. 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);
  92993. 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);
  92994. 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);
  92995. 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);
  92996. #else
  92997. residual_bits_per_sample[0] = (total_error_0 > 0) ? local__compute_rbps_integerized(total_error_0, data_len) : 0;
  92998. residual_bits_per_sample[1] = (total_error_1 > 0) ? local__compute_rbps_integerized(total_error_1, data_len) : 0;
  92999. residual_bits_per_sample[2] = (total_error_2 > 0) ? local__compute_rbps_integerized(total_error_2, data_len) : 0;
  93000. residual_bits_per_sample[3] = (total_error_3 > 0) ? local__compute_rbps_integerized(total_error_3, data_len) : 0;
  93001. residual_bits_per_sample[4] = (total_error_4 > 0) ? local__compute_rbps_integerized(total_error_4, data_len) : 0;
  93002. #endif
  93003. return order;
  93004. }
  93005. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  93006. 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])
  93007. #else
  93008. 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])
  93009. #endif
  93010. {
  93011. FLAC__int32 last_error_0 = data[-1];
  93012. FLAC__int32 last_error_1 = data[-1] - data[-2];
  93013. FLAC__int32 last_error_2 = last_error_1 - (data[-2] - data[-3]);
  93014. FLAC__int32 last_error_3 = last_error_2 - (data[-2] - 2*data[-3] + data[-4]);
  93015. FLAC__int32 error, save;
  93016. /* total_error_* are 64-bits to avoid overflow when encoding
  93017. * erratic signals when the bits-per-sample and blocksize are
  93018. * large.
  93019. */
  93020. FLAC__uint64 total_error_0 = 0, total_error_1 = 0, total_error_2 = 0, total_error_3 = 0, total_error_4 = 0;
  93021. unsigned i, order;
  93022. for(i = 0; i < data_len; i++) {
  93023. error = data[i] ; total_error_0 += local_abs(error); save = error;
  93024. error -= last_error_0; total_error_1 += local_abs(error); last_error_0 = save; save = error;
  93025. error -= last_error_1; total_error_2 += local_abs(error); last_error_1 = save; save = error;
  93026. error -= last_error_2; total_error_3 += local_abs(error); last_error_2 = save; save = error;
  93027. error -= last_error_3; total_error_4 += local_abs(error); last_error_3 = save;
  93028. }
  93029. if(total_error_0 < min(min(min(total_error_1, total_error_2), total_error_3), total_error_4))
  93030. order = 0;
  93031. else if(total_error_1 < min(min(total_error_2, total_error_3), total_error_4))
  93032. order = 1;
  93033. else if(total_error_2 < min(total_error_3, total_error_4))
  93034. order = 2;
  93035. else if(total_error_3 < total_error_4)
  93036. order = 3;
  93037. else
  93038. order = 4;
  93039. /* Estimate the expected number of bits per residual signal sample. */
  93040. /* 'total_error*' is linearly related to the variance of the residual */
  93041. /* signal, so we use it directly to compute E(|x|) */
  93042. FLAC__ASSERT(data_len > 0 || total_error_0 == 0);
  93043. FLAC__ASSERT(data_len > 0 || total_error_1 == 0);
  93044. FLAC__ASSERT(data_len > 0 || total_error_2 == 0);
  93045. FLAC__ASSERT(data_len > 0 || total_error_3 == 0);
  93046. FLAC__ASSERT(data_len > 0 || total_error_4 == 0);
  93047. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  93048. #if defined _MSC_VER || defined __MINGW32__
  93049. /* with MSVC you have to spoon feed it the casting */
  93050. 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);
  93051. 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);
  93052. 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);
  93053. 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);
  93054. 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);
  93055. #else
  93056. 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);
  93057. 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);
  93058. 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);
  93059. 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);
  93060. 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);
  93061. #endif
  93062. #else
  93063. residual_bits_per_sample[0] = (total_error_0 > 0) ? local__compute_rbps_wide_integerized(total_error_0, data_len) : 0;
  93064. residual_bits_per_sample[1] = (total_error_1 > 0) ? local__compute_rbps_wide_integerized(total_error_1, data_len) : 0;
  93065. residual_bits_per_sample[2] = (total_error_2 > 0) ? local__compute_rbps_wide_integerized(total_error_2, data_len) : 0;
  93066. residual_bits_per_sample[3] = (total_error_3 > 0) ? local__compute_rbps_wide_integerized(total_error_3, data_len) : 0;
  93067. residual_bits_per_sample[4] = (total_error_4 > 0) ? local__compute_rbps_wide_integerized(total_error_4, data_len) : 0;
  93068. #endif
  93069. return order;
  93070. }
  93071. void FLAC__fixed_compute_residual(const FLAC__int32 data[], unsigned data_len, unsigned order, FLAC__int32 residual[])
  93072. {
  93073. const int idata_len = (int)data_len;
  93074. int i;
  93075. switch(order) {
  93076. case 0:
  93077. FLAC__ASSERT(sizeof(residual[0]) == sizeof(data[0]));
  93078. memcpy(residual, data, sizeof(residual[0])*data_len);
  93079. break;
  93080. case 1:
  93081. for(i = 0; i < idata_len; i++)
  93082. residual[i] = data[i] - data[i-1];
  93083. break;
  93084. case 2:
  93085. for(i = 0; i < idata_len; i++)
  93086. #if 1 /* OPT: may be faster with some compilers on some systems */
  93087. residual[i] = data[i] - (data[i-1] << 1) + data[i-2];
  93088. #else
  93089. residual[i] = data[i] - 2*data[i-1] + data[i-2];
  93090. #endif
  93091. break;
  93092. case 3:
  93093. for(i = 0; i < idata_len; i++)
  93094. #if 1 /* OPT: may be faster with some compilers on some systems */
  93095. residual[i] = data[i] - (((data[i-1]-data[i-2])<<1) + (data[i-1]-data[i-2])) - data[i-3];
  93096. #else
  93097. residual[i] = data[i] - 3*data[i-1] + 3*data[i-2] - data[i-3];
  93098. #endif
  93099. break;
  93100. case 4:
  93101. for(i = 0; i < idata_len; i++)
  93102. #if 1 /* OPT: may be faster with some compilers on some systems */
  93103. residual[i] = data[i] - ((data[i-1]+data[i-3])<<2) + ((data[i-2]<<2) + (data[i-2]<<1)) + data[i-4];
  93104. #else
  93105. residual[i] = data[i] - 4*data[i-1] + 6*data[i-2] - 4*data[i-3] + data[i-4];
  93106. #endif
  93107. break;
  93108. default:
  93109. FLAC__ASSERT(0);
  93110. }
  93111. }
  93112. void FLAC__fixed_restore_signal(const FLAC__int32 residual[], unsigned data_len, unsigned order, FLAC__int32 data[])
  93113. {
  93114. int i, idata_len = (int)data_len;
  93115. switch(order) {
  93116. case 0:
  93117. FLAC__ASSERT(sizeof(residual[0]) == sizeof(data[0]));
  93118. memcpy(data, residual, sizeof(residual[0])*data_len);
  93119. break;
  93120. case 1:
  93121. for(i = 0; i < idata_len; i++)
  93122. data[i] = residual[i] + data[i-1];
  93123. break;
  93124. case 2:
  93125. for(i = 0; i < idata_len; i++)
  93126. #if 1 /* OPT: may be faster with some compilers on some systems */
  93127. data[i] = residual[i] + (data[i-1]<<1) - data[i-2];
  93128. #else
  93129. data[i] = residual[i] + 2*data[i-1] - data[i-2];
  93130. #endif
  93131. break;
  93132. case 3:
  93133. for(i = 0; i < idata_len; i++)
  93134. #if 1 /* OPT: may be faster with some compilers on some systems */
  93135. data[i] = residual[i] + (((data[i-1]-data[i-2])<<1) + (data[i-1]-data[i-2])) + data[i-3];
  93136. #else
  93137. data[i] = residual[i] + 3*data[i-1] - 3*data[i-2] + data[i-3];
  93138. #endif
  93139. break;
  93140. case 4:
  93141. for(i = 0; i < idata_len; i++)
  93142. #if 1 /* OPT: may be faster with some compilers on some systems */
  93143. data[i] = residual[i] + ((data[i-1]+data[i-3])<<2) - ((data[i-2]<<2) + (data[i-2]<<1)) - data[i-4];
  93144. #else
  93145. data[i] = residual[i] + 4*data[i-1] - 6*data[i-2] + 4*data[i-3] - data[i-4];
  93146. #endif
  93147. break;
  93148. default:
  93149. FLAC__ASSERT(0);
  93150. }
  93151. }
  93152. #endif
  93153. /*** End of inlined file: fixed.c ***/
  93154. /*** Start of inlined file: float.c ***/
  93155. /*** Start of inlined file: juce_FlacHeader.h ***/
  93156. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  93157. // tasks..
  93158. #define VERSION "1.2.1"
  93159. #define FLAC__NO_DLL 1
  93160. #if JUCE_MSVC
  93161. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  93162. #endif
  93163. #if JUCE_MAC
  93164. #define FLAC__SYS_DARWIN 1
  93165. #endif
  93166. /*** End of inlined file: juce_FlacHeader.h ***/
  93167. #if JUCE_USE_FLAC
  93168. #if HAVE_CONFIG_H
  93169. # include <config.h>
  93170. #endif
  93171. #ifdef FLAC__INTEGER_ONLY_LIBRARY
  93172. /* adjust for compilers that can't understand using LLU suffix for uint64_t literals */
  93173. #ifdef _MSC_VER
  93174. #define FLAC__U64L(x) x
  93175. #else
  93176. #define FLAC__U64L(x) x##LLU
  93177. #endif
  93178. const FLAC__fixedpoint FLAC__FP_ZERO = 0;
  93179. const FLAC__fixedpoint FLAC__FP_ONE_HALF = 0x00008000;
  93180. const FLAC__fixedpoint FLAC__FP_ONE = 0x00010000;
  93181. const FLAC__fixedpoint FLAC__FP_LN2 = 45426;
  93182. const FLAC__fixedpoint FLAC__FP_E = 178145;
  93183. /* Lookup tables for Knuth's logarithm algorithm */
  93184. #define LOG2_LOOKUP_PRECISION 16
  93185. static const FLAC__uint32 log2_lookup[][LOG2_LOOKUP_PRECISION] = {
  93186. {
  93187. /*
  93188. * 0 fraction bits
  93189. */
  93190. /* undefined */ 0x00000000,
  93191. /* lg(2/1) = */ 0x00000001,
  93192. /* lg(4/3) = */ 0x00000000,
  93193. /* lg(8/7) = */ 0x00000000,
  93194. /* lg(16/15) = */ 0x00000000,
  93195. /* lg(32/31) = */ 0x00000000,
  93196. /* lg(64/63) = */ 0x00000000,
  93197. /* lg(128/127) = */ 0x00000000,
  93198. /* lg(256/255) = */ 0x00000000,
  93199. /* lg(512/511) = */ 0x00000000,
  93200. /* lg(1024/1023) = */ 0x00000000,
  93201. /* lg(2048/2047) = */ 0x00000000,
  93202. /* lg(4096/4095) = */ 0x00000000,
  93203. /* lg(8192/8191) = */ 0x00000000,
  93204. /* lg(16384/16383) = */ 0x00000000,
  93205. /* lg(32768/32767) = */ 0x00000000
  93206. },
  93207. {
  93208. /*
  93209. * 4 fraction bits
  93210. */
  93211. /* undefined */ 0x00000000,
  93212. /* lg(2/1) = */ 0x00000010,
  93213. /* lg(4/3) = */ 0x00000007,
  93214. /* lg(8/7) = */ 0x00000003,
  93215. /* lg(16/15) = */ 0x00000001,
  93216. /* lg(32/31) = */ 0x00000001,
  93217. /* lg(64/63) = */ 0x00000000,
  93218. /* lg(128/127) = */ 0x00000000,
  93219. /* lg(256/255) = */ 0x00000000,
  93220. /* lg(512/511) = */ 0x00000000,
  93221. /* lg(1024/1023) = */ 0x00000000,
  93222. /* lg(2048/2047) = */ 0x00000000,
  93223. /* lg(4096/4095) = */ 0x00000000,
  93224. /* lg(8192/8191) = */ 0x00000000,
  93225. /* lg(16384/16383) = */ 0x00000000,
  93226. /* lg(32768/32767) = */ 0x00000000
  93227. },
  93228. {
  93229. /*
  93230. * 8 fraction bits
  93231. */
  93232. /* undefined */ 0x00000000,
  93233. /* lg(2/1) = */ 0x00000100,
  93234. /* lg(4/3) = */ 0x0000006a,
  93235. /* lg(8/7) = */ 0x00000031,
  93236. /* lg(16/15) = */ 0x00000018,
  93237. /* lg(32/31) = */ 0x0000000c,
  93238. /* lg(64/63) = */ 0x00000006,
  93239. /* lg(128/127) = */ 0x00000003,
  93240. /* lg(256/255) = */ 0x00000001,
  93241. /* lg(512/511) = */ 0x00000001,
  93242. /* lg(1024/1023) = */ 0x00000000,
  93243. /* lg(2048/2047) = */ 0x00000000,
  93244. /* lg(4096/4095) = */ 0x00000000,
  93245. /* lg(8192/8191) = */ 0x00000000,
  93246. /* lg(16384/16383) = */ 0x00000000,
  93247. /* lg(32768/32767) = */ 0x00000000
  93248. },
  93249. {
  93250. /*
  93251. * 12 fraction bits
  93252. */
  93253. /* undefined */ 0x00000000,
  93254. /* lg(2/1) = */ 0x00001000,
  93255. /* lg(4/3) = */ 0x000006a4,
  93256. /* lg(8/7) = */ 0x00000315,
  93257. /* lg(16/15) = */ 0x0000017d,
  93258. /* lg(32/31) = */ 0x000000bc,
  93259. /* lg(64/63) = */ 0x0000005d,
  93260. /* lg(128/127) = */ 0x0000002e,
  93261. /* lg(256/255) = */ 0x00000017,
  93262. /* lg(512/511) = */ 0x0000000c,
  93263. /* lg(1024/1023) = */ 0x00000006,
  93264. /* lg(2048/2047) = */ 0x00000003,
  93265. /* lg(4096/4095) = */ 0x00000001,
  93266. /* lg(8192/8191) = */ 0x00000001,
  93267. /* lg(16384/16383) = */ 0x00000000,
  93268. /* lg(32768/32767) = */ 0x00000000
  93269. },
  93270. {
  93271. /*
  93272. * 16 fraction bits
  93273. */
  93274. /* undefined */ 0x00000000,
  93275. /* lg(2/1) = */ 0x00010000,
  93276. /* lg(4/3) = */ 0x00006a40,
  93277. /* lg(8/7) = */ 0x00003151,
  93278. /* lg(16/15) = */ 0x000017d6,
  93279. /* lg(32/31) = */ 0x00000bba,
  93280. /* lg(64/63) = */ 0x000005d1,
  93281. /* lg(128/127) = */ 0x000002e6,
  93282. /* lg(256/255) = */ 0x00000172,
  93283. /* lg(512/511) = */ 0x000000b9,
  93284. /* lg(1024/1023) = */ 0x0000005c,
  93285. /* lg(2048/2047) = */ 0x0000002e,
  93286. /* lg(4096/4095) = */ 0x00000017,
  93287. /* lg(8192/8191) = */ 0x0000000c,
  93288. /* lg(16384/16383) = */ 0x00000006,
  93289. /* lg(32768/32767) = */ 0x00000003
  93290. },
  93291. {
  93292. /*
  93293. * 20 fraction bits
  93294. */
  93295. /* undefined */ 0x00000000,
  93296. /* lg(2/1) = */ 0x00100000,
  93297. /* lg(4/3) = */ 0x0006a3fe,
  93298. /* lg(8/7) = */ 0x00031513,
  93299. /* lg(16/15) = */ 0x00017d60,
  93300. /* lg(32/31) = */ 0x0000bb9d,
  93301. /* lg(64/63) = */ 0x00005d10,
  93302. /* lg(128/127) = */ 0x00002e59,
  93303. /* lg(256/255) = */ 0x00001721,
  93304. /* lg(512/511) = */ 0x00000b8e,
  93305. /* lg(1024/1023) = */ 0x000005c6,
  93306. /* lg(2048/2047) = */ 0x000002e3,
  93307. /* lg(4096/4095) = */ 0x00000171,
  93308. /* lg(8192/8191) = */ 0x000000b9,
  93309. /* lg(16384/16383) = */ 0x0000005c,
  93310. /* lg(32768/32767) = */ 0x0000002e
  93311. },
  93312. {
  93313. /*
  93314. * 24 fraction bits
  93315. */
  93316. /* undefined */ 0x00000000,
  93317. /* lg(2/1) = */ 0x01000000,
  93318. /* lg(4/3) = */ 0x006a3fe6,
  93319. /* lg(8/7) = */ 0x00315130,
  93320. /* lg(16/15) = */ 0x0017d605,
  93321. /* lg(32/31) = */ 0x000bb9ca,
  93322. /* lg(64/63) = */ 0x0005d0fc,
  93323. /* lg(128/127) = */ 0x0002e58f,
  93324. /* lg(256/255) = */ 0x0001720e,
  93325. /* lg(512/511) = */ 0x0000b8d8,
  93326. /* lg(1024/1023) = */ 0x00005c61,
  93327. /* lg(2048/2047) = */ 0x00002e2d,
  93328. /* lg(4096/4095) = */ 0x00001716,
  93329. /* lg(8192/8191) = */ 0x00000b8b,
  93330. /* lg(16384/16383) = */ 0x000005c5,
  93331. /* lg(32768/32767) = */ 0x000002e3
  93332. },
  93333. {
  93334. /*
  93335. * 28 fraction bits
  93336. */
  93337. /* undefined */ 0x00000000,
  93338. /* lg(2/1) = */ 0x10000000,
  93339. /* lg(4/3) = */ 0x06a3fe5c,
  93340. /* lg(8/7) = */ 0x03151301,
  93341. /* lg(16/15) = */ 0x017d6049,
  93342. /* lg(32/31) = */ 0x00bb9ca6,
  93343. /* lg(64/63) = */ 0x005d0fba,
  93344. /* lg(128/127) = */ 0x002e58f7,
  93345. /* lg(256/255) = */ 0x001720da,
  93346. /* lg(512/511) = */ 0x000b8d87,
  93347. /* lg(1024/1023) = */ 0x0005c60b,
  93348. /* lg(2048/2047) = */ 0x0002e2d7,
  93349. /* lg(4096/4095) = */ 0x00017160,
  93350. /* lg(8192/8191) = */ 0x0000b8ad,
  93351. /* lg(16384/16383) = */ 0x00005c56,
  93352. /* lg(32768/32767) = */ 0x00002e2b
  93353. }
  93354. };
  93355. #if 0
  93356. static const FLAC__uint64 log2_lookup_wide[] = {
  93357. {
  93358. /*
  93359. * 32 fraction bits
  93360. */
  93361. /* undefined */ 0x00000000,
  93362. /* lg(2/1) = */ FLAC__U64L(0x100000000),
  93363. /* lg(4/3) = */ FLAC__U64L(0x6a3fe5c6),
  93364. /* lg(8/7) = */ FLAC__U64L(0x31513015),
  93365. /* lg(16/15) = */ FLAC__U64L(0x17d60497),
  93366. /* lg(32/31) = */ FLAC__U64L(0x0bb9ca65),
  93367. /* lg(64/63) = */ FLAC__U64L(0x05d0fba2),
  93368. /* lg(128/127) = */ FLAC__U64L(0x02e58f74),
  93369. /* lg(256/255) = */ FLAC__U64L(0x01720d9c),
  93370. /* lg(512/511) = */ FLAC__U64L(0x00b8d875),
  93371. /* lg(1024/1023) = */ FLAC__U64L(0x005c60aa),
  93372. /* lg(2048/2047) = */ FLAC__U64L(0x002e2d72),
  93373. /* lg(4096/4095) = */ FLAC__U64L(0x00171600),
  93374. /* lg(8192/8191) = */ FLAC__U64L(0x000b8ad2),
  93375. /* lg(16384/16383) = */ FLAC__U64L(0x0005c55d),
  93376. /* lg(32768/32767) = */ FLAC__U64L(0x0002e2ac)
  93377. },
  93378. {
  93379. /*
  93380. * 48 fraction bits
  93381. */
  93382. /* undefined */ 0x00000000,
  93383. /* lg(2/1) = */ FLAC__U64L(0x1000000000000),
  93384. /* lg(4/3) = */ FLAC__U64L(0x6a3fe5c60429),
  93385. /* lg(8/7) = */ FLAC__U64L(0x315130157f7a),
  93386. /* lg(16/15) = */ FLAC__U64L(0x17d60496cfbb),
  93387. /* lg(32/31) = */ FLAC__U64L(0xbb9ca64ecac),
  93388. /* lg(64/63) = */ FLAC__U64L(0x5d0fba187cd),
  93389. /* lg(128/127) = */ FLAC__U64L(0x2e58f7441ee),
  93390. /* lg(256/255) = */ FLAC__U64L(0x1720d9c06a8),
  93391. /* lg(512/511) = */ FLAC__U64L(0xb8d8752173),
  93392. /* lg(1024/1023) = */ FLAC__U64L(0x5c60aa252e),
  93393. /* lg(2048/2047) = */ FLAC__U64L(0x2e2d71b0d8),
  93394. /* lg(4096/4095) = */ FLAC__U64L(0x1716001719),
  93395. /* lg(8192/8191) = */ FLAC__U64L(0xb8ad1de1b),
  93396. /* lg(16384/16383) = */ FLAC__U64L(0x5c55d640d),
  93397. /* lg(32768/32767) = */ FLAC__U64L(0x2e2abcf52)
  93398. }
  93399. };
  93400. #endif
  93401. FLAC__uint32 FLAC__fixedpoint_log2(FLAC__uint32 x, unsigned fracbits, unsigned precision)
  93402. {
  93403. const FLAC__uint32 ONE = (1u << fracbits);
  93404. const FLAC__uint32 *table = log2_lookup[fracbits >> 2];
  93405. FLAC__ASSERT(fracbits < 32);
  93406. FLAC__ASSERT((fracbits & 0x3) == 0);
  93407. if(x < ONE)
  93408. return 0;
  93409. if(precision > LOG2_LOOKUP_PRECISION)
  93410. precision = LOG2_LOOKUP_PRECISION;
  93411. /* Knuth's algorithm for computing logarithms, optimized for base-2 with lookup tables */
  93412. {
  93413. FLAC__uint32 y = 0;
  93414. FLAC__uint32 z = x >> 1, k = 1;
  93415. while (x > ONE && k < precision) {
  93416. if (x - z >= ONE) {
  93417. x -= z;
  93418. z = x >> k;
  93419. y += table[k];
  93420. }
  93421. else {
  93422. z >>= 1;
  93423. k++;
  93424. }
  93425. }
  93426. return y;
  93427. }
  93428. }
  93429. #endif /* defined FLAC__INTEGER_ONLY_LIBRARY */
  93430. #endif
  93431. /*** End of inlined file: float.c ***/
  93432. /*** Start of inlined file: format.c ***/
  93433. /*** Start of inlined file: juce_FlacHeader.h ***/
  93434. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  93435. // tasks..
  93436. #define VERSION "1.2.1"
  93437. #define FLAC__NO_DLL 1
  93438. #if JUCE_MSVC
  93439. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  93440. #endif
  93441. #if JUCE_MAC
  93442. #define FLAC__SYS_DARWIN 1
  93443. #endif
  93444. /*** End of inlined file: juce_FlacHeader.h ***/
  93445. #if JUCE_USE_FLAC
  93446. #if HAVE_CONFIG_H
  93447. # include <config.h>
  93448. #endif
  93449. #include <stdio.h>
  93450. #include <stdlib.h> /* for qsort() */
  93451. #include <string.h> /* for memset() */
  93452. #ifndef FLaC__INLINE
  93453. #define FLaC__INLINE
  93454. #endif
  93455. #ifdef min
  93456. #undef min
  93457. #endif
  93458. #define min(a,b) ((a)<(b)?(a):(b))
  93459. /* adjust for compilers that can't understand using LLU suffix for uint64_t literals */
  93460. #ifdef _MSC_VER
  93461. #define FLAC__U64L(x) x
  93462. #else
  93463. #define FLAC__U64L(x) x##LLU
  93464. #endif
  93465. /* VERSION should come from configure */
  93466. FLAC_API const char *FLAC__VERSION_STRING = VERSION
  93467. ;
  93468. #if defined _MSC_VER || defined __BORLANDC__ || defined __MINW32__
  93469. /* yet one more hack because of MSVC6: */
  93470. FLAC_API const char *FLAC__VENDOR_STRING = "reference libFLAC 1.2.1 20070917";
  93471. #else
  93472. FLAC_API const char *FLAC__VENDOR_STRING = "reference libFLAC " VERSION " 20070917";
  93473. #endif
  93474. FLAC_API const FLAC__byte FLAC__STREAM_SYNC_STRING[4] = { 'f','L','a','C' };
  93475. FLAC_API const unsigned FLAC__STREAM_SYNC = 0x664C6143;
  93476. FLAC_API const unsigned FLAC__STREAM_SYNC_LEN = 32; /* bits */
  93477. FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN = 16; /* bits */
  93478. FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN = 16; /* bits */
  93479. FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN = 24; /* bits */
  93480. FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN = 24; /* bits */
  93481. FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN = 20; /* bits */
  93482. FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN = 3; /* bits */
  93483. FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN = 5; /* bits */
  93484. FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_TOTAL_SAMPLES_LEN = 36; /* bits */
  93485. FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MD5SUM_LEN = 128; /* bits */
  93486. FLAC_API const unsigned FLAC__STREAM_METADATA_APPLICATION_ID_LEN = 32; /* bits */
  93487. FLAC_API const unsigned FLAC__STREAM_METADATA_SEEKPOINT_SAMPLE_NUMBER_LEN = 64; /* bits */
  93488. FLAC_API const unsigned FLAC__STREAM_METADATA_SEEKPOINT_STREAM_OFFSET_LEN = 64; /* bits */
  93489. FLAC_API const unsigned FLAC__STREAM_METADATA_SEEKPOINT_FRAME_SAMPLES_LEN = 16; /* bits */
  93490. FLAC_API const FLAC__uint64 FLAC__STREAM_METADATA_SEEKPOINT_PLACEHOLDER = FLAC__U64L(0xffffffffffffffff);
  93491. FLAC_API const unsigned FLAC__STREAM_METADATA_VORBIS_COMMENT_ENTRY_LENGTH_LEN = 32; /* bits */
  93492. FLAC_API const unsigned FLAC__STREAM_METADATA_VORBIS_COMMENT_NUM_COMMENTS_LEN = 32; /* bits */
  93493. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_INDEX_OFFSET_LEN = 64; /* bits */
  93494. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_INDEX_NUMBER_LEN = 8; /* bits */
  93495. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_INDEX_RESERVED_LEN = 3*8; /* bits */
  93496. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_OFFSET_LEN = 64; /* bits */
  93497. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_NUMBER_LEN = 8; /* bits */
  93498. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_ISRC_LEN = 12*8; /* bits */
  93499. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_TYPE_LEN = 1; /* bit */
  93500. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_PRE_EMPHASIS_LEN = 1; /* bit */
  93501. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_RESERVED_LEN = 6+13*8; /* bits */
  93502. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_NUM_INDICES_LEN = 8; /* bits */
  93503. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_MEDIA_CATALOG_NUMBER_LEN = 128*8; /* bits */
  93504. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_LEAD_IN_LEN = 64; /* bits */
  93505. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_IS_CD_LEN = 1; /* bit */
  93506. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_RESERVED_LEN = 7+258*8; /* bits */
  93507. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_NUM_TRACKS_LEN = 8; /* bits */
  93508. FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_TYPE_LEN = 32; /* bits */
  93509. FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_MIME_TYPE_LENGTH_LEN = 32; /* bits */
  93510. FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_DESCRIPTION_LENGTH_LEN = 32; /* bits */
  93511. FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_WIDTH_LEN = 32; /* bits */
  93512. FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_HEIGHT_LEN = 32; /* bits */
  93513. FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_DEPTH_LEN = 32; /* bits */
  93514. FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_COLORS_LEN = 32; /* bits */
  93515. FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_DATA_LENGTH_LEN = 32; /* bits */
  93516. FLAC_API const unsigned FLAC__STREAM_METADATA_IS_LAST_LEN = 1; /* bits */
  93517. FLAC_API const unsigned FLAC__STREAM_METADATA_TYPE_LEN = 7; /* bits */
  93518. FLAC_API const unsigned FLAC__STREAM_METADATA_LENGTH_LEN = 24; /* bits */
  93519. FLAC_API const unsigned FLAC__FRAME_HEADER_SYNC = 0x3ffe;
  93520. FLAC_API const unsigned FLAC__FRAME_HEADER_SYNC_LEN = 14; /* bits */
  93521. FLAC_API const unsigned FLAC__FRAME_HEADER_RESERVED_LEN = 1; /* bits */
  93522. FLAC_API const unsigned FLAC__FRAME_HEADER_BLOCKING_STRATEGY_LEN = 1; /* bits */
  93523. FLAC_API const unsigned FLAC__FRAME_HEADER_BLOCK_SIZE_LEN = 4; /* bits */
  93524. FLAC_API const unsigned FLAC__FRAME_HEADER_SAMPLE_RATE_LEN = 4; /* bits */
  93525. FLAC_API const unsigned FLAC__FRAME_HEADER_CHANNEL_ASSIGNMENT_LEN = 4; /* bits */
  93526. FLAC_API const unsigned FLAC__FRAME_HEADER_BITS_PER_SAMPLE_LEN = 3; /* bits */
  93527. FLAC_API const unsigned FLAC__FRAME_HEADER_ZERO_PAD_LEN = 1; /* bits */
  93528. FLAC_API const unsigned FLAC__FRAME_HEADER_CRC_LEN = 8; /* bits */
  93529. FLAC_API const unsigned FLAC__FRAME_FOOTER_CRC_LEN = 16; /* bits */
  93530. FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_TYPE_LEN = 2; /* bits */
  93531. FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN = 4; /* bits */
  93532. FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_PARAMETER_LEN = 4; /* bits */
  93533. FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_PARAMETER_LEN = 5; /* bits */
  93534. FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_RAW_LEN = 5; /* bits */
  93535. FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER = 15; /* == (1<<FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_PARAMETER_LEN)-1 */
  93536. FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_ESCAPE_PARAMETER = 31; /* == (1<<FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_PARAMETER_LEN)-1 */
  93537. FLAC_API const char * const FLAC__EntropyCodingMethodTypeString[] = {
  93538. "PARTITIONED_RICE",
  93539. "PARTITIONED_RICE2"
  93540. };
  93541. FLAC_API const unsigned FLAC__SUBFRAME_LPC_QLP_COEFF_PRECISION_LEN = 4; /* bits */
  93542. FLAC_API const unsigned FLAC__SUBFRAME_LPC_QLP_SHIFT_LEN = 5; /* bits */
  93543. FLAC_API const unsigned FLAC__SUBFRAME_ZERO_PAD_LEN = 1; /* bits */
  93544. FLAC_API const unsigned FLAC__SUBFRAME_TYPE_LEN = 6; /* bits */
  93545. FLAC_API const unsigned FLAC__SUBFRAME_WASTED_BITS_FLAG_LEN = 1; /* bits */
  93546. FLAC_API const unsigned FLAC__SUBFRAME_TYPE_CONSTANT_BYTE_ALIGNED_MASK = 0x00;
  93547. FLAC_API const unsigned FLAC__SUBFRAME_TYPE_VERBATIM_BYTE_ALIGNED_MASK = 0x02;
  93548. FLAC_API const unsigned FLAC__SUBFRAME_TYPE_FIXED_BYTE_ALIGNED_MASK = 0x10;
  93549. FLAC_API const unsigned FLAC__SUBFRAME_TYPE_LPC_BYTE_ALIGNED_MASK = 0x40;
  93550. FLAC_API const char * const FLAC__SubframeTypeString[] = {
  93551. "CONSTANT",
  93552. "VERBATIM",
  93553. "FIXED",
  93554. "LPC"
  93555. };
  93556. FLAC_API const char * const FLAC__ChannelAssignmentString[] = {
  93557. "INDEPENDENT",
  93558. "LEFT_SIDE",
  93559. "RIGHT_SIDE",
  93560. "MID_SIDE"
  93561. };
  93562. FLAC_API const char * const FLAC__FrameNumberTypeString[] = {
  93563. "FRAME_NUMBER_TYPE_FRAME_NUMBER",
  93564. "FRAME_NUMBER_TYPE_SAMPLE_NUMBER"
  93565. };
  93566. FLAC_API const char * const FLAC__MetadataTypeString[] = {
  93567. "STREAMINFO",
  93568. "PADDING",
  93569. "APPLICATION",
  93570. "SEEKTABLE",
  93571. "VORBIS_COMMENT",
  93572. "CUESHEET",
  93573. "PICTURE"
  93574. };
  93575. FLAC_API const char * const FLAC__StreamMetadata_Picture_TypeString[] = {
  93576. "Other",
  93577. "32x32 pixels 'file icon' (PNG only)",
  93578. "Other file icon",
  93579. "Cover (front)",
  93580. "Cover (back)",
  93581. "Leaflet page",
  93582. "Media (e.g. label side of CD)",
  93583. "Lead artist/lead performer/soloist",
  93584. "Artist/performer",
  93585. "Conductor",
  93586. "Band/Orchestra",
  93587. "Composer",
  93588. "Lyricist/text writer",
  93589. "Recording Location",
  93590. "During recording",
  93591. "During performance",
  93592. "Movie/video screen capture",
  93593. "A bright coloured fish",
  93594. "Illustration",
  93595. "Band/artist logotype",
  93596. "Publisher/Studio logotype"
  93597. };
  93598. FLAC_API FLAC__bool FLAC__format_sample_rate_is_valid(unsigned sample_rate)
  93599. {
  93600. if(sample_rate == 0 || sample_rate > FLAC__MAX_SAMPLE_RATE) {
  93601. return false;
  93602. }
  93603. else
  93604. return true;
  93605. }
  93606. FLAC_API FLAC__bool FLAC__format_sample_rate_is_subset(unsigned sample_rate)
  93607. {
  93608. if(
  93609. !FLAC__format_sample_rate_is_valid(sample_rate) ||
  93610. (
  93611. sample_rate >= (1u << 16) &&
  93612. !(sample_rate % 1000 == 0 || sample_rate % 10 == 0)
  93613. )
  93614. ) {
  93615. return false;
  93616. }
  93617. else
  93618. return true;
  93619. }
  93620. /* @@@@ add to unit tests; it is already indirectly tested by the metadata_object tests */
  93621. FLAC_API FLAC__bool FLAC__format_seektable_is_legal(const FLAC__StreamMetadata_SeekTable *seek_table)
  93622. {
  93623. unsigned i;
  93624. FLAC__uint64 prev_sample_number = 0;
  93625. FLAC__bool got_prev = false;
  93626. FLAC__ASSERT(0 != seek_table);
  93627. for(i = 0; i < seek_table->num_points; i++) {
  93628. if(got_prev) {
  93629. if(
  93630. seek_table->points[i].sample_number != FLAC__STREAM_METADATA_SEEKPOINT_PLACEHOLDER &&
  93631. seek_table->points[i].sample_number <= prev_sample_number
  93632. )
  93633. return false;
  93634. }
  93635. prev_sample_number = seek_table->points[i].sample_number;
  93636. got_prev = true;
  93637. }
  93638. return true;
  93639. }
  93640. /* used as the sort predicate for qsort() */
  93641. static int seekpoint_compare_(const FLAC__StreamMetadata_SeekPoint *l, const FLAC__StreamMetadata_SeekPoint *r)
  93642. {
  93643. /* we don't just 'return l->sample_number - r->sample_number' since the result (FLAC__int64) might overflow an 'int' */
  93644. if(l->sample_number == r->sample_number)
  93645. return 0;
  93646. else if(l->sample_number < r->sample_number)
  93647. return -1;
  93648. else
  93649. return 1;
  93650. }
  93651. /* @@@@ add to unit tests; it is already indirectly tested by the metadata_object tests */
  93652. FLAC_API unsigned FLAC__format_seektable_sort(FLAC__StreamMetadata_SeekTable *seek_table)
  93653. {
  93654. unsigned i, j;
  93655. FLAC__bool first;
  93656. FLAC__ASSERT(0 != seek_table);
  93657. /* sort the seekpoints */
  93658. qsort(seek_table->points, seek_table->num_points, sizeof(FLAC__StreamMetadata_SeekPoint), (int (*)(const void *, const void *))seekpoint_compare_);
  93659. /* uniquify the seekpoints */
  93660. first = true;
  93661. for(i = j = 0; i < seek_table->num_points; i++) {
  93662. if(seek_table->points[i].sample_number != FLAC__STREAM_METADATA_SEEKPOINT_PLACEHOLDER) {
  93663. if(!first) {
  93664. if(seek_table->points[i].sample_number == seek_table->points[j-1].sample_number)
  93665. continue;
  93666. }
  93667. }
  93668. first = false;
  93669. seek_table->points[j++] = seek_table->points[i];
  93670. }
  93671. for(i = j; i < seek_table->num_points; i++) {
  93672. seek_table->points[i].sample_number = FLAC__STREAM_METADATA_SEEKPOINT_PLACEHOLDER;
  93673. seek_table->points[i].stream_offset = 0;
  93674. seek_table->points[i].frame_samples = 0;
  93675. }
  93676. return j;
  93677. }
  93678. /*
  93679. * also disallows non-shortest-form encodings, c.f.
  93680. * http://www.unicode.org/versions/corrigendum1.html
  93681. * and a more clear explanation at the end of this section:
  93682. * http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
  93683. */
  93684. static FLaC__INLINE unsigned utf8len_(const FLAC__byte *utf8)
  93685. {
  93686. FLAC__ASSERT(0 != utf8);
  93687. if ((utf8[0] & 0x80) == 0) {
  93688. return 1;
  93689. }
  93690. else if ((utf8[0] & 0xE0) == 0xC0 && (utf8[1] & 0xC0) == 0x80) {
  93691. if ((utf8[0] & 0xFE) == 0xC0) /* overlong sequence check */
  93692. return 0;
  93693. return 2;
  93694. }
  93695. else if ((utf8[0] & 0xF0) == 0xE0 && (utf8[1] & 0xC0) == 0x80 && (utf8[2] & 0xC0) == 0x80) {
  93696. if (utf8[0] == 0xE0 && (utf8[1] & 0xE0) == 0x80) /* overlong sequence check */
  93697. return 0;
  93698. /* illegal surrogates check (U+D800...U+DFFF and U+FFFE...U+FFFF) */
  93699. if (utf8[0] == 0xED && (utf8[1] & 0xE0) == 0xA0) /* D800-DFFF */
  93700. return 0;
  93701. if (utf8[0] == 0xEF && utf8[1] == 0xBF && (utf8[2] & 0xFE) == 0xBE) /* FFFE-FFFF */
  93702. return 0;
  93703. return 3;
  93704. }
  93705. else if ((utf8[0] & 0xF8) == 0xF0 && (utf8[1] & 0xC0) == 0x80 && (utf8[2] & 0xC0) == 0x80 && (utf8[3] & 0xC0) == 0x80) {
  93706. if (utf8[0] == 0xF0 && (utf8[1] & 0xF0) == 0x80) /* overlong sequence check */
  93707. return 0;
  93708. return 4;
  93709. }
  93710. else if ((utf8[0] & 0xFC) == 0xF8 && (utf8[1] & 0xC0) == 0x80 && (utf8[2] & 0xC0) == 0x80 && (utf8[3] & 0xC0) == 0x80 && (utf8[4] & 0xC0) == 0x80) {
  93711. if (utf8[0] == 0xF8 && (utf8[1] & 0xF8) == 0x80) /* overlong sequence check */
  93712. return 0;
  93713. return 5;
  93714. }
  93715. 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) {
  93716. if (utf8[0] == 0xFC && (utf8[1] & 0xFC) == 0x80) /* overlong sequence check */
  93717. return 0;
  93718. return 6;
  93719. }
  93720. else {
  93721. return 0;
  93722. }
  93723. }
  93724. FLAC_API FLAC__bool FLAC__format_vorbiscomment_entry_name_is_legal(const char *name)
  93725. {
  93726. char c;
  93727. for(c = *name; c; c = *(++name))
  93728. if(c < 0x20 || c == 0x3d || c > 0x7d)
  93729. return false;
  93730. return true;
  93731. }
  93732. FLAC_API FLAC__bool FLAC__format_vorbiscomment_entry_value_is_legal(const FLAC__byte *value, unsigned length)
  93733. {
  93734. if(length == (unsigned)(-1)) {
  93735. while(*value) {
  93736. unsigned n = utf8len_(value);
  93737. if(n == 0)
  93738. return false;
  93739. value += n;
  93740. }
  93741. }
  93742. else {
  93743. const FLAC__byte *end = value + length;
  93744. while(value < end) {
  93745. unsigned n = utf8len_(value);
  93746. if(n == 0)
  93747. return false;
  93748. value += n;
  93749. }
  93750. if(value != end)
  93751. return false;
  93752. }
  93753. return true;
  93754. }
  93755. FLAC_API FLAC__bool FLAC__format_vorbiscomment_entry_is_legal(const FLAC__byte *entry, unsigned length)
  93756. {
  93757. const FLAC__byte *s, *end;
  93758. for(s = entry, end = s + length; s < end && *s != '='; s++) {
  93759. if(*s < 0x20 || *s > 0x7D)
  93760. return false;
  93761. }
  93762. if(s == end)
  93763. return false;
  93764. s++; /* skip '=' */
  93765. while(s < end) {
  93766. unsigned n = utf8len_(s);
  93767. if(n == 0)
  93768. return false;
  93769. s += n;
  93770. }
  93771. if(s != end)
  93772. return false;
  93773. return true;
  93774. }
  93775. /* @@@@ add to unit tests; it is already indirectly tested by the metadata_object tests */
  93776. FLAC_API FLAC__bool FLAC__format_cuesheet_is_legal(const FLAC__StreamMetadata_CueSheet *cue_sheet, FLAC__bool check_cd_da_subset, const char **violation)
  93777. {
  93778. unsigned i, j;
  93779. if(check_cd_da_subset) {
  93780. if(cue_sheet->lead_in < 2 * 44100) {
  93781. if(violation) *violation = "CD-DA cue sheet must have a lead-in length of at least 2 seconds";
  93782. return false;
  93783. }
  93784. if(cue_sheet->lead_in % 588 != 0) {
  93785. if(violation) *violation = "CD-DA cue sheet lead-in length must be evenly divisible by 588 samples";
  93786. return false;
  93787. }
  93788. }
  93789. if(cue_sheet->num_tracks == 0) {
  93790. if(violation) *violation = "cue sheet must have at least one track (the lead-out)";
  93791. return false;
  93792. }
  93793. if(check_cd_da_subset && cue_sheet->tracks[cue_sheet->num_tracks-1].number != 170) {
  93794. if(violation) *violation = "CD-DA cue sheet must have a lead-out track number 170 (0xAA)";
  93795. return false;
  93796. }
  93797. for(i = 0; i < cue_sheet->num_tracks; i++) {
  93798. if(cue_sheet->tracks[i].number == 0) {
  93799. if(violation) *violation = "cue sheet may not have a track number 0";
  93800. return false;
  93801. }
  93802. if(check_cd_da_subset) {
  93803. if(!((cue_sheet->tracks[i].number >= 1 && cue_sheet->tracks[i].number <= 99) || cue_sheet->tracks[i].number == 170)) {
  93804. if(violation) *violation = "CD-DA cue sheet track number must be 1-99 or 170";
  93805. return false;
  93806. }
  93807. }
  93808. if(check_cd_da_subset && cue_sheet->tracks[i].offset % 588 != 0) {
  93809. if(violation) {
  93810. if(i == cue_sheet->num_tracks-1) /* the lead-out track... */
  93811. *violation = "CD-DA cue sheet lead-out offset must be evenly divisible by 588 samples";
  93812. else
  93813. *violation = "CD-DA cue sheet track offset must be evenly divisible by 588 samples";
  93814. }
  93815. return false;
  93816. }
  93817. if(i < cue_sheet->num_tracks - 1) {
  93818. if(cue_sheet->tracks[i].num_indices == 0) {
  93819. if(violation) *violation = "cue sheet track must have at least one index point";
  93820. return false;
  93821. }
  93822. if(cue_sheet->tracks[i].indices[0].number > 1) {
  93823. if(violation) *violation = "cue sheet track's first index number must be 0 or 1";
  93824. return false;
  93825. }
  93826. }
  93827. for(j = 0; j < cue_sheet->tracks[i].num_indices; j++) {
  93828. if(check_cd_da_subset && cue_sheet->tracks[i].indices[j].offset % 588 != 0) {
  93829. if(violation) *violation = "CD-DA cue sheet track index offset must be evenly divisible by 588 samples";
  93830. return false;
  93831. }
  93832. if(j > 0) {
  93833. if(cue_sheet->tracks[i].indices[j].number != cue_sheet->tracks[i].indices[j-1].number + 1) {
  93834. if(violation) *violation = "cue sheet track index numbers must increase by 1";
  93835. return false;
  93836. }
  93837. }
  93838. }
  93839. }
  93840. return true;
  93841. }
  93842. /* @@@@ add to unit tests; it is already indirectly tested by the metadata_object tests */
  93843. FLAC_API FLAC__bool FLAC__format_picture_is_legal(const FLAC__StreamMetadata_Picture *picture, const char **violation)
  93844. {
  93845. char *p;
  93846. FLAC__byte *b;
  93847. for(p = picture->mime_type; *p; p++) {
  93848. if(*p < 0x20 || *p > 0x7e) {
  93849. if(violation) *violation = "MIME type string must contain only printable ASCII characters (0x20-0x7e)";
  93850. return false;
  93851. }
  93852. }
  93853. for(b = picture->description; *b; ) {
  93854. unsigned n = utf8len_(b);
  93855. if(n == 0) {
  93856. if(violation) *violation = "description string must be valid UTF-8";
  93857. return false;
  93858. }
  93859. b += n;
  93860. }
  93861. return true;
  93862. }
  93863. /*
  93864. * These routines are private to libFLAC
  93865. */
  93866. unsigned FLAC__format_get_max_rice_partition_order(unsigned blocksize, unsigned predictor_order)
  93867. {
  93868. return
  93869. FLAC__format_get_max_rice_partition_order_from_blocksize_limited_max_and_predictor_order(
  93870. FLAC__format_get_max_rice_partition_order_from_blocksize(blocksize),
  93871. blocksize,
  93872. predictor_order
  93873. );
  93874. }
  93875. unsigned FLAC__format_get_max_rice_partition_order_from_blocksize(unsigned blocksize)
  93876. {
  93877. unsigned max_rice_partition_order = 0;
  93878. while(!(blocksize & 1)) {
  93879. max_rice_partition_order++;
  93880. blocksize >>= 1;
  93881. }
  93882. return min(FLAC__MAX_RICE_PARTITION_ORDER, max_rice_partition_order);
  93883. }
  93884. unsigned FLAC__format_get_max_rice_partition_order_from_blocksize_limited_max_and_predictor_order(unsigned limit, unsigned blocksize, unsigned predictor_order)
  93885. {
  93886. unsigned max_rice_partition_order = limit;
  93887. while(max_rice_partition_order > 0 && (blocksize >> max_rice_partition_order) <= predictor_order)
  93888. max_rice_partition_order--;
  93889. FLAC__ASSERT(
  93890. (max_rice_partition_order == 0 && blocksize >= predictor_order) ||
  93891. (max_rice_partition_order > 0 && blocksize >> max_rice_partition_order > predictor_order)
  93892. );
  93893. return max_rice_partition_order;
  93894. }
  93895. void FLAC__format_entropy_coding_method_partitioned_rice_contents_init(FLAC__EntropyCodingMethod_PartitionedRiceContents *object)
  93896. {
  93897. FLAC__ASSERT(0 != object);
  93898. object->parameters = 0;
  93899. object->raw_bits = 0;
  93900. object->capacity_by_order = 0;
  93901. }
  93902. void FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(FLAC__EntropyCodingMethod_PartitionedRiceContents *object)
  93903. {
  93904. FLAC__ASSERT(0 != object);
  93905. if(0 != object->parameters)
  93906. free(object->parameters);
  93907. if(0 != object->raw_bits)
  93908. free(object->raw_bits);
  93909. FLAC__format_entropy_coding_method_partitioned_rice_contents_init(object);
  93910. }
  93911. FLAC__bool FLAC__format_entropy_coding_method_partitioned_rice_contents_ensure_size(FLAC__EntropyCodingMethod_PartitionedRiceContents *object, unsigned max_partition_order)
  93912. {
  93913. FLAC__ASSERT(0 != object);
  93914. FLAC__ASSERT(object->capacity_by_order > 0 || (0 == object->parameters && 0 == object->raw_bits));
  93915. if(object->capacity_by_order < max_partition_order) {
  93916. if(0 == (object->parameters = (unsigned*)realloc(object->parameters, sizeof(unsigned)*(1 << max_partition_order))))
  93917. return false;
  93918. if(0 == (object->raw_bits = (unsigned*)realloc(object->raw_bits, sizeof(unsigned)*(1 << max_partition_order))))
  93919. return false;
  93920. memset(object->raw_bits, 0, sizeof(unsigned)*(1 << max_partition_order));
  93921. object->capacity_by_order = max_partition_order;
  93922. }
  93923. return true;
  93924. }
  93925. #endif
  93926. /*** End of inlined file: format.c ***/
  93927. /*** Start of inlined file: lpc_flac.c ***/
  93928. /*** Start of inlined file: juce_FlacHeader.h ***/
  93929. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  93930. // tasks..
  93931. #define VERSION "1.2.1"
  93932. #define FLAC__NO_DLL 1
  93933. #if JUCE_MSVC
  93934. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  93935. #endif
  93936. #if JUCE_MAC
  93937. #define FLAC__SYS_DARWIN 1
  93938. #endif
  93939. /*** End of inlined file: juce_FlacHeader.h ***/
  93940. #if JUCE_USE_FLAC
  93941. #if HAVE_CONFIG_H
  93942. # include <config.h>
  93943. #endif
  93944. #include <math.h>
  93945. /*** Start of inlined file: lpc.h ***/
  93946. #ifndef FLAC__PRIVATE__LPC_H
  93947. #define FLAC__PRIVATE__LPC_H
  93948. #ifdef HAVE_CONFIG_H
  93949. #include <config.h>
  93950. #endif
  93951. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  93952. /*
  93953. * FLAC__lpc_window_data()
  93954. * --------------------------------------------------------------------
  93955. * Applies the given window to the data.
  93956. * OPT: asm implementation
  93957. *
  93958. * IN in[0,data_len-1]
  93959. * IN window[0,data_len-1]
  93960. * OUT out[0,lag-1]
  93961. * IN data_len
  93962. */
  93963. void FLAC__lpc_window_data(const FLAC__int32 in[], const FLAC__real window[], FLAC__real out[], unsigned data_len);
  93964. /*
  93965. * FLAC__lpc_compute_autocorrelation()
  93966. * --------------------------------------------------------------------
  93967. * Compute the autocorrelation for lags between 0 and lag-1.
  93968. * Assumes data[] outside of [0,data_len-1] == 0.
  93969. * Asserts that lag > 0.
  93970. *
  93971. * IN data[0,data_len-1]
  93972. * IN data_len
  93973. * IN 0 < lag <= data_len
  93974. * OUT autoc[0,lag-1]
  93975. */
  93976. void FLAC__lpc_compute_autocorrelation(const FLAC__real data[], unsigned data_len, unsigned lag, FLAC__real autoc[]);
  93977. #ifndef FLAC__NO_ASM
  93978. # ifdef FLAC__CPU_IA32
  93979. # ifdef FLAC__HAS_NASM
  93980. void FLAC__lpc_compute_autocorrelation_asm_ia32(const FLAC__real data[], unsigned data_len, unsigned lag, FLAC__real autoc[]);
  93981. void FLAC__lpc_compute_autocorrelation_asm_ia32_sse_lag_4(const FLAC__real data[], unsigned data_len, unsigned lag, FLAC__real autoc[]);
  93982. void FLAC__lpc_compute_autocorrelation_asm_ia32_sse_lag_8(const FLAC__real data[], unsigned data_len, unsigned lag, FLAC__real autoc[]);
  93983. void FLAC__lpc_compute_autocorrelation_asm_ia32_sse_lag_12(const FLAC__real data[], unsigned data_len, unsigned lag, FLAC__real autoc[]);
  93984. void FLAC__lpc_compute_autocorrelation_asm_ia32_3dnow(const FLAC__real data[], unsigned data_len, unsigned lag, FLAC__real autoc[]);
  93985. # endif
  93986. # endif
  93987. #endif
  93988. /*
  93989. * FLAC__lpc_compute_lp_coefficients()
  93990. * --------------------------------------------------------------------
  93991. * Computes LP coefficients for orders 1..max_order.
  93992. * Do not call if autoc[0] == 0.0. This means the signal is zero
  93993. * and there is no point in calculating a predictor.
  93994. *
  93995. * IN autoc[0,max_order] autocorrelation values
  93996. * IN 0 < max_order <= FLAC__MAX_LPC_ORDER max LP order to compute
  93997. * OUT lp_coeff[0,max_order-1][0,max_order-1] LP coefficients for each order
  93998. * *** IMPORTANT:
  93999. * *** lp_coeff[0,max_order-1][max_order,FLAC__MAX_LPC_ORDER-1] are untouched
  94000. * OUT error[0,max_order-1] error for each order (more
  94001. * specifically, the variance of
  94002. * the error signal times # of
  94003. * samples in the signal)
  94004. *
  94005. * Example: if max_order is 9, the LP coefficients for order 9 will be
  94006. * in lp_coeff[8][0,8], the LP coefficients for order 8 will be
  94007. * in lp_coeff[7][0,7], etc.
  94008. */
  94009. void FLAC__lpc_compute_lp_coefficients(const FLAC__real autoc[], unsigned *max_order, FLAC__real lp_coeff[][FLAC__MAX_LPC_ORDER], FLAC__double error[]);
  94010. /*
  94011. * FLAC__lpc_quantize_coefficients()
  94012. * --------------------------------------------------------------------
  94013. * Quantizes the LP coefficients. NOTE: precision + bits_per_sample
  94014. * must be less than 32 (sizeof(FLAC__int32)*8).
  94015. *
  94016. * IN lp_coeff[0,order-1] LP coefficients
  94017. * IN order LP order
  94018. * IN FLAC__MIN_QLP_COEFF_PRECISION < precision
  94019. * desired precision (in bits, including sign
  94020. * bit) of largest coefficient
  94021. * OUT qlp_coeff[0,order-1] quantized coefficients
  94022. * OUT shift # of bits to shift right to get approximated
  94023. * LP coefficients. NOTE: could be negative.
  94024. * RETURN 0 => quantization OK
  94025. * 1 => coefficients require too much shifting for *shift to
  94026. * fit in the LPC subframe header. 'shift' is unset.
  94027. * 2 => coefficients are all zero, which is bad. 'shift' is
  94028. * unset.
  94029. */
  94030. int FLAC__lpc_quantize_coefficients(const FLAC__real lp_coeff[], unsigned order, unsigned precision, FLAC__int32 qlp_coeff[], int *shift);
  94031. /*
  94032. * FLAC__lpc_compute_residual_from_qlp_coefficients()
  94033. * --------------------------------------------------------------------
  94034. * Compute the residual signal obtained from sutracting the predicted
  94035. * signal from the original.
  94036. *
  94037. * IN data[-order,data_len-1] original signal (NOTE THE INDICES!)
  94038. * IN data_len length of original signal
  94039. * IN qlp_coeff[0,order-1] quantized LP coefficients
  94040. * IN order > 0 LP order
  94041. * IN lp_quantization quantization of LP coefficients in bits
  94042. * OUT residual[0,data_len-1] residual signal
  94043. */
  94044. 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[]);
  94045. 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[]);
  94046. #ifndef FLAC__NO_ASM
  94047. # ifdef FLAC__CPU_IA32
  94048. # ifdef FLAC__HAS_NASM
  94049. 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[]);
  94050. 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[]);
  94051. # endif
  94052. # endif
  94053. #endif
  94054. #endif /* !defined FLAC__INTEGER_ONLY_LIBRARY */
  94055. /*
  94056. * FLAC__lpc_restore_signal()
  94057. * --------------------------------------------------------------------
  94058. * Restore the original signal by summing the residual and the
  94059. * predictor.
  94060. *
  94061. * IN residual[0,data_len-1] residual signal
  94062. * IN data_len length of original signal
  94063. * IN qlp_coeff[0,order-1] quantized LP coefficients
  94064. * IN order > 0 LP order
  94065. * IN lp_quantization quantization of LP coefficients in bits
  94066. * *** IMPORTANT: the caller must pass in the historical samples:
  94067. * IN data[-order,-1] previously-reconstructed historical samples
  94068. * OUT data[0,data_len-1] original signal
  94069. */
  94070. 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[]);
  94071. 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[]);
  94072. #ifndef FLAC__NO_ASM
  94073. # ifdef FLAC__CPU_IA32
  94074. # ifdef FLAC__HAS_NASM
  94075. 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[]);
  94076. 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[]);
  94077. # endif /* FLAC__HAS_NASM */
  94078. # elif defined FLAC__CPU_PPC
  94079. 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[]);
  94080. 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[]);
  94081. # endif/* FLAC__CPU_IA32 || FLAC__CPU_PPC */
  94082. #endif /* FLAC__NO_ASM */
  94083. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  94084. /*
  94085. * FLAC__lpc_compute_expected_bits_per_residual_sample()
  94086. * --------------------------------------------------------------------
  94087. * Compute the expected number of bits per residual signal sample
  94088. * based on the LP error (which is related to the residual variance).
  94089. *
  94090. * IN lpc_error >= 0.0 error returned from calculating LP coefficients
  94091. * IN total_samples > 0 # of samples in residual signal
  94092. * RETURN expected bits per sample
  94093. */
  94094. FLAC__double FLAC__lpc_compute_expected_bits_per_residual_sample(FLAC__double lpc_error, unsigned total_samples);
  94095. FLAC__double FLAC__lpc_compute_expected_bits_per_residual_sample_with_error_scale(FLAC__double lpc_error, FLAC__double error_scale);
  94096. /*
  94097. * FLAC__lpc_compute_best_order()
  94098. * --------------------------------------------------------------------
  94099. * Compute the best order from the array of signal errors returned
  94100. * during coefficient computation.
  94101. *
  94102. * IN lpc_error[0,max_order-1] >= 0.0 error returned from calculating LP coefficients
  94103. * IN max_order > 0 max LP order
  94104. * IN total_samples > 0 # of samples in residual signal
  94105. * IN overhead_bits_per_order # of bits overhead for each increased LP order
  94106. * (includes warmup sample size and quantized LP coefficient)
  94107. * RETURN [1,max_order] best order
  94108. */
  94109. unsigned FLAC__lpc_compute_best_order(const FLAC__double lpc_error[], unsigned max_order, unsigned total_samples, unsigned overhead_bits_per_order);
  94110. #endif /* !defined FLAC__INTEGER_ONLY_LIBRARY */
  94111. #endif
  94112. /*** End of inlined file: lpc.h ***/
  94113. #if defined DEBUG || defined FLAC__OVERFLOW_DETECT || defined FLAC__OVERFLOW_DETECT_VERBOSE
  94114. #include <stdio.h>
  94115. #endif
  94116. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  94117. #ifndef M_LN2
  94118. /* math.h in VC++ doesn't seem to have this (how Microsoft is that?) */
  94119. #define M_LN2 0.69314718055994530942
  94120. #endif
  94121. /* OPT: #undef'ing this may improve the speed on some architectures */
  94122. #define FLAC__LPC_UNROLLED_FILTER_LOOPS
  94123. void FLAC__lpc_window_data(const FLAC__int32 in[], const FLAC__real window[], FLAC__real out[], unsigned data_len)
  94124. {
  94125. unsigned i;
  94126. for(i = 0; i < data_len; i++)
  94127. out[i] = in[i] * window[i];
  94128. }
  94129. void FLAC__lpc_compute_autocorrelation(const FLAC__real data[], unsigned data_len, unsigned lag, FLAC__real autoc[])
  94130. {
  94131. /* a readable, but slower, version */
  94132. #if 0
  94133. FLAC__real d;
  94134. unsigned i;
  94135. FLAC__ASSERT(lag > 0);
  94136. FLAC__ASSERT(lag <= data_len);
  94137. /*
  94138. * Technically we should subtract the mean first like so:
  94139. * for(i = 0; i < data_len; i++)
  94140. * data[i] -= mean;
  94141. * but it appears not to make enough of a difference to matter, and
  94142. * most signals are already closely centered around zero
  94143. */
  94144. while(lag--) {
  94145. for(i = lag, d = 0.0; i < data_len; i++)
  94146. d += data[i] * data[i - lag];
  94147. autoc[lag] = d;
  94148. }
  94149. #endif
  94150. /*
  94151. * this version tends to run faster because of better data locality
  94152. * ('data_len' is usually much larger than 'lag')
  94153. */
  94154. FLAC__real d;
  94155. unsigned sample, coeff;
  94156. const unsigned limit = data_len - lag;
  94157. FLAC__ASSERT(lag > 0);
  94158. FLAC__ASSERT(lag <= data_len);
  94159. for(coeff = 0; coeff < lag; coeff++)
  94160. autoc[coeff] = 0.0;
  94161. for(sample = 0; sample <= limit; sample++) {
  94162. d = data[sample];
  94163. for(coeff = 0; coeff < lag; coeff++)
  94164. autoc[coeff] += d * data[sample+coeff];
  94165. }
  94166. for(; sample < data_len; sample++) {
  94167. d = data[sample];
  94168. for(coeff = 0; coeff < data_len - sample; coeff++)
  94169. autoc[coeff] += d * data[sample+coeff];
  94170. }
  94171. }
  94172. void FLAC__lpc_compute_lp_coefficients(const FLAC__real autoc[], unsigned *max_order, FLAC__real lp_coeff[][FLAC__MAX_LPC_ORDER], FLAC__double error[])
  94173. {
  94174. unsigned i, j;
  94175. FLAC__double r, err, ref[FLAC__MAX_LPC_ORDER], lpc[FLAC__MAX_LPC_ORDER];
  94176. FLAC__ASSERT(0 != max_order);
  94177. FLAC__ASSERT(0 < *max_order);
  94178. FLAC__ASSERT(*max_order <= FLAC__MAX_LPC_ORDER);
  94179. FLAC__ASSERT(autoc[0] != 0.0);
  94180. err = autoc[0];
  94181. for(i = 0; i < *max_order; i++) {
  94182. /* Sum up this iteration's reflection coefficient. */
  94183. r = -autoc[i+1];
  94184. for(j = 0; j < i; j++)
  94185. r -= lpc[j] * autoc[i-j];
  94186. ref[i] = (r/=err);
  94187. /* Update LPC coefficients and total error. */
  94188. lpc[i]=r;
  94189. for(j = 0; j < (i>>1); j++) {
  94190. FLAC__double tmp = lpc[j];
  94191. lpc[j] += r * lpc[i-1-j];
  94192. lpc[i-1-j] += r * tmp;
  94193. }
  94194. if(i & 1)
  94195. lpc[j] += lpc[j] * r;
  94196. err *= (1.0 - r * r);
  94197. /* save this order */
  94198. for(j = 0; j <= i; j++)
  94199. lp_coeff[i][j] = (FLAC__real)(-lpc[j]); /* negate FIR filter coeff to get predictor coeff */
  94200. error[i] = err;
  94201. /* see SF bug #1601812 http://sourceforge.net/tracker/index.php?func=detail&aid=1601812&group_id=13478&atid=113478 */
  94202. if(err == 0.0) {
  94203. *max_order = i+1;
  94204. return;
  94205. }
  94206. }
  94207. }
  94208. int FLAC__lpc_quantize_coefficients(const FLAC__real lp_coeff[], unsigned order, unsigned precision, FLAC__int32 qlp_coeff[], int *shift)
  94209. {
  94210. unsigned i;
  94211. FLAC__double cmax;
  94212. FLAC__int32 qmax, qmin;
  94213. FLAC__ASSERT(precision > 0);
  94214. FLAC__ASSERT(precision >= FLAC__MIN_QLP_COEFF_PRECISION);
  94215. /* drop one bit for the sign; from here on out we consider only |lp_coeff[i]| */
  94216. precision--;
  94217. qmax = 1 << precision;
  94218. qmin = -qmax;
  94219. qmax--;
  94220. /* calc cmax = max( |lp_coeff[i]| ) */
  94221. cmax = 0.0;
  94222. for(i = 0; i < order; i++) {
  94223. const FLAC__double d = fabs(lp_coeff[i]);
  94224. if(d > cmax)
  94225. cmax = d;
  94226. }
  94227. if(cmax <= 0.0) {
  94228. /* => coefficients are all 0, which means our constant-detect didn't work */
  94229. return 2;
  94230. }
  94231. else {
  94232. const int max_shiftlimit = (1 << (FLAC__SUBFRAME_LPC_QLP_SHIFT_LEN-1)) - 1;
  94233. const int min_shiftlimit = -max_shiftlimit - 1;
  94234. int log2cmax;
  94235. (void)frexp(cmax, &log2cmax);
  94236. log2cmax--;
  94237. *shift = (int)precision - log2cmax - 1;
  94238. if(*shift > max_shiftlimit)
  94239. *shift = max_shiftlimit;
  94240. else if(*shift < min_shiftlimit)
  94241. return 1;
  94242. }
  94243. if(*shift >= 0) {
  94244. FLAC__double error = 0.0;
  94245. FLAC__int32 q;
  94246. for(i = 0; i < order; i++) {
  94247. error += lp_coeff[i] * (1 << *shift);
  94248. #if 1 /* unfortunately lround() is C99 */
  94249. if(error >= 0.0)
  94250. q = (FLAC__int32)(error + 0.5);
  94251. else
  94252. q = (FLAC__int32)(error - 0.5);
  94253. #else
  94254. q = lround(error);
  94255. #endif
  94256. #ifdef FLAC__OVERFLOW_DETECT
  94257. if(q > qmax+1) /* we expect q==qmax+1 occasionally due to rounding */
  94258. 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]);
  94259. else if(q < qmin)
  94260. 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]);
  94261. #endif
  94262. if(q > qmax)
  94263. q = qmax;
  94264. else if(q < qmin)
  94265. q = qmin;
  94266. error -= q;
  94267. qlp_coeff[i] = q;
  94268. }
  94269. }
  94270. /* negative shift is very rare but due to design flaw, negative shift is
  94271. * a NOP in the decoder, so it must be handled specially by scaling down
  94272. * coeffs
  94273. */
  94274. else {
  94275. const int nshift = -(*shift);
  94276. FLAC__double error = 0.0;
  94277. FLAC__int32 q;
  94278. #ifdef DEBUG
  94279. fprintf(stderr,"FLAC__lpc_quantize_coefficients: negative shift=%d order=%u cmax=%f\n", *shift, order, cmax);
  94280. #endif
  94281. for(i = 0; i < order; i++) {
  94282. error += lp_coeff[i] / (1 << nshift);
  94283. #if 1 /* unfortunately lround() is C99 */
  94284. if(error >= 0.0)
  94285. q = (FLAC__int32)(error + 0.5);
  94286. else
  94287. q = (FLAC__int32)(error - 0.5);
  94288. #else
  94289. q = lround(error);
  94290. #endif
  94291. #ifdef FLAC__OVERFLOW_DETECT
  94292. if(q > qmax+1) /* we expect q==qmax+1 occasionally due to rounding */
  94293. 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]);
  94294. else if(q < qmin)
  94295. 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]);
  94296. #endif
  94297. if(q > qmax)
  94298. q = qmax;
  94299. else if(q < qmin)
  94300. q = qmin;
  94301. error -= q;
  94302. qlp_coeff[i] = q;
  94303. }
  94304. *shift = 0;
  94305. }
  94306. return 0;
  94307. }
  94308. 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[])
  94309. #if defined(FLAC__OVERFLOW_DETECT) || !defined(FLAC__LPC_UNROLLED_FILTER_LOOPS)
  94310. {
  94311. FLAC__int64 sumo;
  94312. unsigned i, j;
  94313. FLAC__int32 sum;
  94314. const FLAC__int32 *history;
  94315. #ifdef FLAC__OVERFLOW_DETECT_VERBOSE
  94316. fprintf(stderr,"FLAC__lpc_compute_residual_from_qlp_coefficients: data_len=%d, order=%u, lpq=%d",data_len,order,lp_quantization);
  94317. for(i=0;i<order;i++)
  94318. fprintf(stderr,", q[%u]=%d",i,qlp_coeff[i]);
  94319. fprintf(stderr,"\n");
  94320. #endif
  94321. FLAC__ASSERT(order > 0);
  94322. for(i = 0; i < data_len; i++) {
  94323. sumo = 0;
  94324. sum = 0;
  94325. history = data;
  94326. for(j = 0; j < order; j++) {
  94327. sum += qlp_coeff[j] * (*(--history));
  94328. sumo += (FLAC__int64)qlp_coeff[j] * (FLAC__int64)(*history);
  94329. #if defined _MSC_VER
  94330. if(sumo > 2147483647I64 || sumo < -2147483648I64)
  94331. 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);
  94332. #else
  94333. if(sumo > 2147483647ll || sumo < -2147483648ll)
  94334. 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);
  94335. #endif
  94336. }
  94337. *(residual++) = *(data++) - (sum >> lp_quantization);
  94338. }
  94339. /* Here's a slower but clearer version:
  94340. for(i = 0; i < data_len; i++) {
  94341. sum = 0;
  94342. for(j = 0; j < order; j++)
  94343. sum += qlp_coeff[j] * data[i-j-1];
  94344. residual[i] = data[i] - (sum >> lp_quantization);
  94345. }
  94346. */
  94347. }
  94348. #else /* fully unrolled version for normal use */
  94349. {
  94350. int i;
  94351. FLAC__int32 sum;
  94352. FLAC__ASSERT(order > 0);
  94353. FLAC__ASSERT(order <= 32);
  94354. /*
  94355. * We do unique versions up to 12th order since that's the subset limit.
  94356. * Also they are roughly ordered to match frequency of occurrence to
  94357. * minimize branching.
  94358. */
  94359. if(order <= 12) {
  94360. if(order > 8) {
  94361. if(order > 10) {
  94362. if(order == 12) {
  94363. for(i = 0; i < (int)data_len; i++) {
  94364. sum = 0;
  94365. sum += qlp_coeff[11] * data[i-12];
  94366. sum += qlp_coeff[10] * data[i-11];
  94367. sum += qlp_coeff[9] * data[i-10];
  94368. sum += qlp_coeff[8] * data[i-9];
  94369. sum += qlp_coeff[7] * data[i-8];
  94370. sum += qlp_coeff[6] * data[i-7];
  94371. sum += qlp_coeff[5] * data[i-6];
  94372. sum += qlp_coeff[4] * data[i-5];
  94373. sum += qlp_coeff[3] * data[i-4];
  94374. sum += qlp_coeff[2] * data[i-3];
  94375. sum += qlp_coeff[1] * data[i-2];
  94376. sum += qlp_coeff[0] * data[i-1];
  94377. residual[i] = data[i] - (sum >> lp_quantization);
  94378. }
  94379. }
  94380. else { /* order == 11 */
  94381. for(i = 0; i < (int)data_len; i++) {
  94382. sum = 0;
  94383. sum += qlp_coeff[10] * data[i-11];
  94384. sum += qlp_coeff[9] * data[i-10];
  94385. sum += qlp_coeff[8] * data[i-9];
  94386. sum += qlp_coeff[7] * data[i-8];
  94387. sum += qlp_coeff[6] * data[i-7];
  94388. sum += qlp_coeff[5] * data[i-6];
  94389. sum += qlp_coeff[4] * data[i-5];
  94390. sum += qlp_coeff[3] * data[i-4];
  94391. sum += qlp_coeff[2] * data[i-3];
  94392. sum += qlp_coeff[1] * data[i-2];
  94393. sum += qlp_coeff[0] * data[i-1];
  94394. residual[i] = data[i] - (sum >> lp_quantization);
  94395. }
  94396. }
  94397. }
  94398. else {
  94399. if(order == 10) {
  94400. for(i = 0; i < (int)data_len; i++) {
  94401. sum = 0;
  94402. sum += qlp_coeff[9] * data[i-10];
  94403. sum += qlp_coeff[8] * data[i-9];
  94404. sum += qlp_coeff[7] * data[i-8];
  94405. sum += qlp_coeff[6] * data[i-7];
  94406. sum += qlp_coeff[5] * data[i-6];
  94407. sum += qlp_coeff[4] * data[i-5];
  94408. sum += qlp_coeff[3] * data[i-4];
  94409. sum += qlp_coeff[2] * data[i-3];
  94410. sum += qlp_coeff[1] * data[i-2];
  94411. sum += qlp_coeff[0] * data[i-1];
  94412. residual[i] = data[i] - (sum >> lp_quantization);
  94413. }
  94414. }
  94415. else { /* order == 9 */
  94416. for(i = 0; i < (int)data_len; i++) {
  94417. sum = 0;
  94418. sum += qlp_coeff[8] * data[i-9];
  94419. sum += qlp_coeff[7] * data[i-8];
  94420. sum += qlp_coeff[6] * data[i-7];
  94421. sum += qlp_coeff[5] * data[i-6];
  94422. sum += qlp_coeff[4] * data[i-5];
  94423. sum += qlp_coeff[3] * data[i-4];
  94424. sum += qlp_coeff[2] * data[i-3];
  94425. sum += qlp_coeff[1] * data[i-2];
  94426. sum += qlp_coeff[0] * data[i-1];
  94427. residual[i] = data[i] - (sum >> lp_quantization);
  94428. }
  94429. }
  94430. }
  94431. }
  94432. else if(order > 4) {
  94433. if(order > 6) {
  94434. if(order == 8) {
  94435. for(i = 0; i < (int)data_len; i++) {
  94436. sum = 0;
  94437. sum += qlp_coeff[7] * data[i-8];
  94438. sum += qlp_coeff[6] * data[i-7];
  94439. sum += qlp_coeff[5] * data[i-6];
  94440. sum += qlp_coeff[4] * data[i-5];
  94441. sum += qlp_coeff[3] * data[i-4];
  94442. sum += qlp_coeff[2] * data[i-3];
  94443. sum += qlp_coeff[1] * data[i-2];
  94444. sum += qlp_coeff[0] * data[i-1];
  94445. residual[i] = data[i] - (sum >> lp_quantization);
  94446. }
  94447. }
  94448. else { /* order == 7 */
  94449. for(i = 0; i < (int)data_len; i++) {
  94450. sum = 0;
  94451. sum += qlp_coeff[6] * data[i-7];
  94452. sum += qlp_coeff[5] * data[i-6];
  94453. sum += qlp_coeff[4] * data[i-5];
  94454. sum += qlp_coeff[3] * data[i-4];
  94455. sum += qlp_coeff[2] * data[i-3];
  94456. sum += qlp_coeff[1] * data[i-2];
  94457. sum += qlp_coeff[0] * data[i-1];
  94458. residual[i] = data[i] - (sum >> lp_quantization);
  94459. }
  94460. }
  94461. }
  94462. else {
  94463. if(order == 6) {
  94464. for(i = 0; i < (int)data_len; i++) {
  94465. sum = 0;
  94466. sum += qlp_coeff[5] * data[i-6];
  94467. sum += qlp_coeff[4] * data[i-5];
  94468. sum += qlp_coeff[3] * data[i-4];
  94469. sum += qlp_coeff[2] * data[i-3];
  94470. sum += qlp_coeff[1] * data[i-2];
  94471. sum += qlp_coeff[0] * data[i-1];
  94472. residual[i] = data[i] - (sum >> lp_quantization);
  94473. }
  94474. }
  94475. else { /* order == 5 */
  94476. for(i = 0; i < (int)data_len; i++) {
  94477. sum = 0;
  94478. sum += qlp_coeff[4] * data[i-5];
  94479. sum += qlp_coeff[3] * data[i-4];
  94480. sum += qlp_coeff[2] * data[i-3];
  94481. sum += qlp_coeff[1] * data[i-2];
  94482. sum += qlp_coeff[0] * data[i-1];
  94483. residual[i] = data[i] - (sum >> lp_quantization);
  94484. }
  94485. }
  94486. }
  94487. }
  94488. else {
  94489. if(order > 2) {
  94490. if(order == 4) {
  94491. for(i = 0; i < (int)data_len; i++) {
  94492. sum = 0;
  94493. sum += qlp_coeff[3] * data[i-4];
  94494. sum += qlp_coeff[2] * data[i-3];
  94495. sum += qlp_coeff[1] * data[i-2];
  94496. sum += qlp_coeff[0] * data[i-1];
  94497. residual[i] = data[i] - (sum >> lp_quantization);
  94498. }
  94499. }
  94500. else { /* order == 3 */
  94501. for(i = 0; i < (int)data_len; i++) {
  94502. sum = 0;
  94503. sum += qlp_coeff[2] * data[i-3];
  94504. sum += qlp_coeff[1] * data[i-2];
  94505. sum += qlp_coeff[0] * data[i-1];
  94506. residual[i] = data[i] - (sum >> lp_quantization);
  94507. }
  94508. }
  94509. }
  94510. else {
  94511. if(order == 2) {
  94512. for(i = 0; i < (int)data_len; i++) {
  94513. sum = 0;
  94514. sum += qlp_coeff[1] * data[i-2];
  94515. sum += qlp_coeff[0] * data[i-1];
  94516. residual[i] = data[i] - (sum >> lp_quantization);
  94517. }
  94518. }
  94519. else { /* order == 1 */
  94520. for(i = 0; i < (int)data_len; i++)
  94521. residual[i] = data[i] - ((qlp_coeff[0] * data[i-1]) >> lp_quantization);
  94522. }
  94523. }
  94524. }
  94525. }
  94526. else { /* order > 12 */
  94527. for(i = 0; i < (int)data_len; i++) {
  94528. sum = 0;
  94529. switch(order) {
  94530. case 32: sum += qlp_coeff[31] * data[i-32];
  94531. case 31: sum += qlp_coeff[30] * data[i-31];
  94532. case 30: sum += qlp_coeff[29] * data[i-30];
  94533. case 29: sum += qlp_coeff[28] * data[i-29];
  94534. case 28: sum += qlp_coeff[27] * data[i-28];
  94535. case 27: sum += qlp_coeff[26] * data[i-27];
  94536. case 26: sum += qlp_coeff[25] * data[i-26];
  94537. case 25: sum += qlp_coeff[24] * data[i-25];
  94538. case 24: sum += qlp_coeff[23] * data[i-24];
  94539. case 23: sum += qlp_coeff[22] * data[i-23];
  94540. case 22: sum += qlp_coeff[21] * data[i-22];
  94541. case 21: sum += qlp_coeff[20] * data[i-21];
  94542. case 20: sum += qlp_coeff[19] * data[i-20];
  94543. case 19: sum += qlp_coeff[18] * data[i-19];
  94544. case 18: sum += qlp_coeff[17] * data[i-18];
  94545. case 17: sum += qlp_coeff[16] * data[i-17];
  94546. case 16: sum += qlp_coeff[15] * data[i-16];
  94547. case 15: sum += qlp_coeff[14] * data[i-15];
  94548. case 14: sum += qlp_coeff[13] * data[i-14];
  94549. case 13: sum += qlp_coeff[12] * data[i-13];
  94550. sum += qlp_coeff[11] * data[i-12];
  94551. sum += qlp_coeff[10] * data[i-11];
  94552. sum += qlp_coeff[ 9] * data[i-10];
  94553. sum += qlp_coeff[ 8] * data[i- 9];
  94554. sum += qlp_coeff[ 7] * data[i- 8];
  94555. sum += qlp_coeff[ 6] * data[i- 7];
  94556. sum += qlp_coeff[ 5] * data[i- 6];
  94557. sum += qlp_coeff[ 4] * data[i- 5];
  94558. sum += qlp_coeff[ 3] * data[i- 4];
  94559. sum += qlp_coeff[ 2] * data[i- 3];
  94560. sum += qlp_coeff[ 1] * data[i- 2];
  94561. sum += qlp_coeff[ 0] * data[i- 1];
  94562. }
  94563. residual[i] = data[i] - (sum >> lp_quantization);
  94564. }
  94565. }
  94566. }
  94567. #endif
  94568. 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[])
  94569. #if defined(FLAC__OVERFLOW_DETECT) || !defined(FLAC__LPC_UNROLLED_FILTER_LOOPS)
  94570. {
  94571. unsigned i, j;
  94572. FLAC__int64 sum;
  94573. const FLAC__int32 *history;
  94574. #ifdef FLAC__OVERFLOW_DETECT_VERBOSE
  94575. fprintf(stderr,"FLAC__lpc_compute_residual_from_qlp_coefficients_wide: data_len=%d, order=%u, lpq=%d",data_len,order,lp_quantization);
  94576. for(i=0;i<order;i++)
  94577. fprintf(stderr,", q[%u]=%d",i,qlp_coeff[i]);
  94578. fprintf(stderr,"\n");
  94579. #endif
  94580. FLAC__ASSERT(order > 0);
  94581. for(i = 0; i < data_len; i++) {
  94582. sum = 0;
  94583. history = data;
  94584. for(j = 0; j < order; j++)
  94585. sum += (FLAC__int64)qlp_coeff[j] * (FLAC__int64)(*(--history));
  94586. if(FLAC__bitmath_silog2_wide(sum >> lp_quantization) > 32) {
  94587. #if defined _MSC_VER
  94588. fprintf(stderr,"FLAC__lpc_compute_residual_from_qlp_coefficients_wide: OVERFLOW, i=%u, sum=%I64d\n", i, sum >> lp_quantization);
  94589. #else
  94590. fprintf(stderr,"FLAC__lpc_compute_residual_from_qlp_coefficients_wide: OVERFLOW, i=%u, sum=%lld\n", i, (long long)(sum >> lp_quantization));
  94591. #endif
  94592. break;
  94593. }
  94594. if(FLAC__bitmath_silog2_wide((FLAC__int64)(*data) - (sum >> lp_quantization)) > 32) {
  94595. #if defined _MSC_VER
  94596. 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));
  94597. #else
  94598. 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)));
  94599. #endif
  94600. break;
  94601. }
  94602. *(residual++) = *(data++) - (FLAC__int32)(sum >> lp_quantization);
  94603. }
  94604. }
  94605. #else /* fully unrolled version for normal use */
  94606. {
  94607. int i;
  94608. FLAC__int64 sum;
  94609. FLAC__ASSERT(order > 0);
  94610. FLAC__ASSERT(order <= 32);
  94611. /*
  94612. * We do unique versions up to 12th order since that's the subset limit.
  94613. * Also they are roughly ordered to match frequency of occurrence to
  94614. * minimize branching.
  94615. */
  94616. if(order <= 12) {
  94617. if(order > 8) {
  94618. if(order > 10) {
  94619. if(order == 12) {
  94620. for(i = 0; i < (int)data_len; i++) {
  94621. sum = 0;
  94622. sum += qlp_coeff[11] * (FLAC__int64)data[i-12];
  94623. sum += qlp_coeff[10] * (FLAC__int64)data[i-11];
  94624. sum += qlp_coeff[9] * (FLAC__int64)data[i-10];
  94625. sum += qlp_coeff[8] * (FLAC__int64)data[i-9];
  94626. sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
  94627. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  94628. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  94629. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  94630. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  94631. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  94632. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  94633. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  94634. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  94635. }
  94636. }
  94637. else { /* order == 11 */
  94638. for(i = 0; i < (int)data_len; i++) {
  94639. sum = 0;
  94640. sum += qlp_coeff[10] * (FLAC__int64)data[i-11];
  94641. sum += qlp_coeff[9] * (FLAC__int64)data[i-10];
  94642. sum += qlp_coeff[8] * (FLAC__int64)data[i-9];
  94643. sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
  94644. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  94645. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  94646. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  94647. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  94648. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  94649. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  94650. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  94651. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  94652. }
  94653. }
  94654. }
  94655. else {
  94656. if(order == 10) {
  94657. for(i = 0; i < (int)data_len; i++) {
  94658. sum = 0;
  94659. sum += qlp_coeff[9] * (FLAC__int64)data[i-10];
  94660. sum += qlp_coeff[8] * (FLAC__int64)data[i-9];
  94661. sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
  94662. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  94663. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  94664. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  94665. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  94666. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  94667. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  94668. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  94669. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  94670. }
  94671. }
  94672. else { /* order == 9 */
  94673. for(i = 0; i < (int)data_len; i++) {
  94674. sum = 0;
  94675. sum += qlp_coeff[8] * (FLAC__int64)data[i-9];
  94676. sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
  94677. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  94678. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  94679. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  94680. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  94681. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  94682. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  94683. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  94684. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  94685. }
  94686. }
  94687. }
  94688. }
  94689. else if(order > 4) {
  94690. if(order > 6) {
  94691. if(order == 8) {
  94692. for(i = 0; i < (int)data_len; i++) {
  94693. sum = 0;
  94694. sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
  94695. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  94696. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  94697. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  94698. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  94699. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  94700. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  94701. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  94702. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  94703. }
  94704. }
  94705. else { /* order == 7 */
  94706. for(i = 0; i < (int)data_len; i++) {
  94707. sum = 0;
  94708. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  94709. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  94710. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  94711. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  94712. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  94713. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  94714. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  94715. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  94716. }
  94717. }
  94718. }
  94719. else {
  94720. if(order == 6) {
  94721. for(i = 0; i < (int)data_len; i++) {
  94722. sum = 0;
  94723. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  94724. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  94725. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  94726. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  94727. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  94728. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  94729. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  94730. }
  94731. }
  94732. else { /* order == 5 */
  94733. for(i = 0; i < (int)data_len; i++) {
  94734. sum = 0;
  94735. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  94736. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  94737. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  94738. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  94739. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  94740. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  94741. }
  94742. }
  94743. }
  94744. }
  94745. else {
  94746. if(order > 2) {
  94747. if(order == 4) {
  94748. for(i = 0; i < (int)data_len; i++) {
  94749. sum = 0;
  94750. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  94751. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  94752. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  94753. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  94754. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  94755. }
  94756. }
  94757. else { /* order == 3 */
  94758. for(i = 0; i < (int)data_len; i++) {
  94759. sum = 0;
  94760. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  94761. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  94762. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  94763. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  94764. }
  94765. }
  94766. }
  94767. else {
  94768. if(order == 2) {
  94769. for(i = 0; i < (int)data_len; i++) {
  94770. sum = 0;
  94771. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  94772. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  94773. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  94774. }
  94775. }
  94776. else { /* order == 1 */
  94777. for(i = 0; i < (int)data_len; i++)
  94778. residual[i] = data[i] - (FLAC__int32)((qlp_coeff[0] * (FLAC__int64)data[i-1]) >> lp_quantization);
  94779. }
  94780. }
  94781. }
  94782. }
  94783. else { /* order > 12 */
  94784. for(i = 0; i < (int)data_len; i++) {
  94785. sum = 0;
  94786. switch(order) {
  94787. case 32: sum += qlp_coeff[31] * (FLAC__int64)data[i-32];
  94788. case 31: sum += qlp_coeff[30] * (FLAC__int64)data[i-31];
  94789. case 30: sum += qlp_coeff[29] * (FLAC__int64)data[i-30];
  94790. case 29: sum += qlp_coeff[28] * (FLAC__int64)data[i-29];
  94791. case 28: sum += qlp_coeff[27] * (FLAC__int64)data[i-28];
  94792. case 27: sum += qlp_coeff[26] * (FLAC__int64)data[i-27];
  94793. case 26: sum += qlp_coeff[25] * (FLAC__int64)data[i-26];
  94794. case 25: sum += qlp_coeff[24] * (FLAC__int64)data[i-25];
  94795. case 24: sum += qlp_coeff[23] * (FLAC__int64)data[i-24];
  94796. case 23: sum += qlp_coeff[22] * (FLAC__int64)data[i-23];
  94797. case 22: sum += qlp_coeff[21] * (FLAC__int64)data[i-22];
  94798. case 21: sum += qlp_coeff[20] * (FLAC__int64)data[i-21];
  94799. case 20: sum += qlp_coeff[19] * (FLAC__int64)data[i-20];
  94800. case 19: sum += qlp_coeff[18] * (FLAC__int64)data[i-19];
  94801. case 18: sum += qlp_coeff[17] * (FLAC__int64)data[i-18];
  94802. case 17: sum += qlp_coeff[16] * (FLAC__int64)data[i-17];
  94803. case 16: sum += qlp_coeff[15] * (FLAC__int64)data[i-16];
  94804. case 15: sum += qlp_coeff[14] * (FLAC__int64)data[i-15];
  94805. case 14: sum += qlp_coeff[13] * (FLAC__int64)data[i-14];
  94806. case 13: sum += qlp_coeff[12] * (FLAC__int64)data[i-13];
  94807. sum += qlp_coeff[11] * (FLAC__int64)data[i-12];
  94808. sum += qlp_coeff[10] * (FLAC__int64)data[i-11];
  94809. sum += qlp_coeff[ 9] * (FLAC__int64)data[i-10];
  94810. sum += qlp_coeff[ 8] * (FLAC__int64)data[i- 9];
  94811. sum += qlp_coeff[ 7] * (FLAC__int64)data[i- 8];
  94812. sum += qlp_coeff[ 6] * (FLAC__int64)data[i- 7];
  94813. sum += qlp_coeff[ 5] * (FLAC__int64)data[i- 6];
  94814. sum += qlp_coeff[ 4] * (FLAC__int64)data[i- 5];
  94815. sum += qlp_coeff[ 3] * (FLAC__int64)data[i- 4];
  94816. sum += qlp_coeff[ 2] * (FLAC__int64)data[i- 3];
  94817. sum += qlp_coeff[ 1] * (FLAC__int64)data[i- 2];
  94818. sum += qlp_coeff[ 0] * (FLAC__int64)data[i- 1];
  94819. }
  94820. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  94821. }
  94822. }
  94823. }
  94824. #endif
  94825. #endif /* !defined FLAC__INTEGER_ONLY_LIBRARY */
  94826. 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[])
  94827. #if defined(FLAC__OVERFLOW_DETECT) || !defined(FLAC__LPC_UNROLLED_FILTER_LOOPS)
  94828. {
  94829. FLAC__int64 sumo;
  94830. unsigned i, j;
  94831. FLAC__int32 sum;
  94832. const FLAC__int32 *r = residual, *history;
  94833. #ifdef FLAC__OVERFLOW_DETECT_VERBOSE
  94834. fprintf(stderr,"FLAC__lpc_restore_signal: data_len=%d, order=%u, lpq=%d",data_len,order,lp_quantization);
  94835. for(i=0;i<order;i++)
  94836. fprintf(stderr,", q[%u]=%d",i,qlp_coeff[i]);
  94837. fprintf(stderr,"\n");
  94838. #endif
  94839. FLAC__ASSERT(order > 0);
  94840. for(i = 0; i < data_len; i++) {
  94841. sumo = 0;
  94842. sum = 0;
  94843. history = data;
  94844. for(j = 0; j < order; j++) {
  94845. sum += qlp_coeff[j] * (*(--history));
  94846. sumo += (FLAC__int64)qlp_coeff[j] * (FLAC__int64)(*history);
  94847. #if defined _MSC_VER
  94848. if(sumo > 2147483647I64 || sumo < -2147483648I64)
  94849. 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);
  94850. #else
  94851. if(sumo > 2147483647ll || sumo < -2147483648ll)
  94852. 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);
  94853. #endif
  94854. }
  94855. *(data++) = *(r++) + (sum >> lp_quantization);
  94856. }
  94857. /* Here's a slower but clearer version:
  94858. for(i = 0; i < data_len; i++) {
  94859. sum = 0;
  94860. for(j = 0; j < order; j++)
  94861. sum += qlp_coeff[j] * data[i-j-1];
  94862. data[i] = residual[i] + (sum >> lp_quantization);
  94863. }
  94864. */
  94865. }
  94866. #else /* fully unrolled version for normal use */
  94867. {
  94868. int i;
  94869. FLAC__int32 sum;
  94870. FLAC__ASSERT(order > 0);
  94871. FLAC__ASSERT(order <= 32);
  94872. /*
  94873. * We do unique versions up to 12th order since that's the subset limit.
  94874. * Also they are roughly ordered to match frequency of occurrence to
  94875. * minimize branching.
  94876. */
  94877. if(order <= 12) {
  94878. if(order > 8) {
  94879. if(order > 10) {
  94880. if(order == 12) {
  94881. for(i = 0; i < (int)data_len; i++) {
  94882. sum = 0;
  94883. sum += qlp_coeff[11] * data[i-12];
  94884. sum += qlp_coeff[10] * data[i-11];
  94885. sum += qlp_coeff[9] * data[i-10];
  94886. sum += qlp_coeff[8] * data[i-9];
  94887. sum += qlp_coeff[7] * data[i-8];
  94888. sum += qlp_coeff[6] * data[i-7];
  94889. sum += qlp_coeff[5] * data[i-6];
  94890. sum += qlp_coeff[4] * data[i-5];
  94891. sum += qlp_coeff[3] * data[i-4];
  94892. sum += qlp_coeff[2] * data[i-3];
  94893. sum += qlp_coeff[1] * data[i-2];
  94894. sum += qlp_coeff[0] * data[i-1];
  94895. data[i] = residual[i] + (sum >> lp_quantization);
  94896. }
  94897. }
  94898. else { /* order == 11 */
  94899. for(i = 0; i < (int)data_len; i++) {
  94900. sum = 0;
  94901. sum += qlp_coeff[10] * data[i-11];
  94902. sum += qlp_coeff[9] * data[i-10];
  94903. sum += qlp_coeff[8] * data[i-9];
  94904. sum += qlp_coeff[7] * data[i-8];
  94905. sum += qlp_coeff[6] * data[i-7];
  94906. sum += qlp_coeff[5] * data[i-6];
  94907. sum += qlp_coeff[4] * data[i-5];
  94908. sum += qlp_coeff[3] * data[i-4];
  94909. sum += qlp_coeff[2] * data[i-3];
  94910. sum += qlp_coeff[1] * data[i-2];
  94911. sum += qlp_coeff[0] * data[i-1];
  94912. data[i] = residual[i] + (sum >> lp_quantization);
  94913. }
  94914. }
  94915. }
  94916. else {
  94917. if(order == 10) {
  94918. for(i = 0; i < (int)data_len; i++) {
  94919. sum = 0;
  94920. sum += qlp_coeff[9] * data[i-10];
  94921. sum += qlp_coeff[8] * data[i-9];
  94922. sum += qlp_coeff[7] * data[i-8];
  94923. sum += qlp_coeff[6] * data[i-7];
  94924. sum += qlp_coeff[5] * data[i-6];
  94925. sum += qlp_coeff[4] * data[i-5];
  94926. sum += qlp_coeff[3] * data[i-4];
  94927. sum += qlp_coeff[2] * data[i-3];
  94928. sum += qlp_coeff[1] * data[i-2];
  94929. sum += qlp_coeff[0] * data[i-1];
  94930. data[i] = residual[i] + (sum >> lp_quantization);
  94931. }
  94932. }
  94933. else { /* order == 9 */
  94934. for(i = 0; i < (int)data_len; i++) {
  94935. sum = 0;
  94936. sum += qlp_coeff[8] * data[i-9];
  94937. sum += qlp_coeff[7] * data[i-8];
  94938. sum += qlp_coeff[6] * data[i-7];
  94939. sum += qlp_coeff[5] * data[i-6];
  94940. sum += qlp_coeff[4] * data[i-5];
  94941. sum += qlp_coeff[3] * data[i-4];
  94942. sum += qlp_coeff[2] * data[i-3];
  94943. sum += qlp_coeff[1] * data[i-2];
  94944. sum += qlp_coeff[0] * data[i-1];
  94945. data[i] = residual[i] + (sum >> lp_quantization);
  94946. }
  94947. }
  94948. }
  94949. }
  94950. else if(order > 4) {
  94951. if(order > 6) {
  94952. if(order == 8) {
  94953. for(i = 0; i < (int)data_len; i++) {
  94954. sum = 0;
  94955. sum += qlp_coeff[7] * data[i-8];
  94956. sum += qlp_coeff[6] * data[i-7];
  94957. sum += qlp_coeff[5] * data[i-6];
  94958. sum += qlp_coeff[4] * data[i-5];
  94959. sum += qlp_coeff[3] * data[i-4];
  94960. sum += qlp_coeff[2] * data[i-3];
  94961. sum += qlp_coeff[1] * data[i-2];
  94962. sum += qlp_coeff[0] * data[i-1];
  94963. data[i] = residual[i] + (sum >> lp_quantization);
  94964. }
  94965. }
  94966. else { /* order == 7 */
  94967. for(i = 0; i < (int)data_len; i++) {
  94968. sum = 0;
  94969. sum += qlp_coeff[6] * data[i-7];
  94970. sum += qlp_coeff[5] * data[i-6];
  94971. sum += qlp_coeff[4] * data[i-5];
  94972. sum += qlp_coeff[3] * data[i-4];
  94973. sum += qlp_coeff[2] * data[i-3];
  94974. sum += qlp_coeff[1] * data[i-2];
  94975. sum += qlp_coeff[0] * data[i-1];
  94976. data[i] = residual[i] + (sum >> lp_quantization);
  94977. }
  94978. }
  94979. }
  94980. else {
  94981. if(order == 6) {
  94982. for(i = 0; i < (int)data_len; i++) {
  94983. sum = 0;
  94984. sum += qlp_coeff[5] * data[i-6];
  94985. sum += qlp_coeff[4] * data[i-5];
  94986. sum += qlp_coeff[3] * data[i-4];
  94987. sum += qlp_coeff[2] * data[i-3];
  94988. sum += qlp_coeff[1] * data[i-2];
  94989. sum += qlp_coeff[0] * data[i-1];
  94990. data[i] = residual[i] + (sum >> lp_quantization);
  94991. }
  94992. }
  94993. else { /* order == 5 */
  94994. for(i = 0; i < (int)data_len; i++) {
  94995. sum = 0;
  94996. sum += qlp_coeff[4] * data[i-5];
  94997. sum += qlp_coeff[3] * data[i-4];
  94998. sum += qlp_coeff[2] * data[i-3];
  94999. sum += qlp_coeff[1] * data[i-2];
  95000. sum += qlp_coeff[0] * data[i-1];
  95001. data[i] = residual[i] + (sum >> lp_quantization);
  95002. }
  95003. }
  95004. }
  95005. }
  95006. else {
  95007. if(order > 2) {
  95008. if(order == 4) {
  95009. for(i = 0; i < (int)data_len; i++) {
  95010. sum = 0;
  95011. sum += qlp_coeff[3] * data[i-4];
  95012. sum += qlp_coeff[2] * data[i-3];
  95013. sum += qlp_coeff[1] * data[i-2];
  95014. sum += qlp_coeff[0] * data[i-1];
  95015. data[i] = residual[i] + (sum >> lp_quantization);
  95016. }
  95017. }
  95018. else { /* order == 3 */
  95019. for(i = 0; i < (int)data_len; i++) {
  95020. sum = 0;
  95021. sum += qlp_coeff[2] * data[i-3];
  95022. sum += qlp_coeff[1] * data[i-2];
  95023. sum += qlp_coeff[0] * data[i-1];
  95024. data[i] = residual[i] + (sum >> lp_quantization);
  95025. }
  95026. }
  95027. }
  95028. else {
  95029. if(order == 2) {
  95030. for(i = 0; i < (int)data_len; i++) {
  95031. sum = 0;
  95032. sum += qlp_coeff[1] * data[i-2];
  95033. sum += qlp_coeff[0] * data[i-1];
  95034. data[i] = residual[i] + (sum >> lp_quantization);
  95035. }
  95036. }
  95037. else { /* order == 1 */
  95038. for(i = 0; i < (int)data_len; i++)
  95039. data[i] = residual[i] + ((qlp_coeff[0] * data[i-1]) >> lp_quantization);
  95040. }
  95041. }
  95042. }
  95043. }
  95044. else { /* order > 12 */
  95045. for(i = 0; i < (int)data_len; i++) {
  95046. sum = 0;
  95047. switch(order) {
  95048. case 32: sum += qlp_coeff[31] * data[i-32];
  95049. case 31: sum += qlp_coeff[30] * data[i-31];
  95050. case 30: sum += qlp_coeff[29] * data[i-30];
  95051. case 29: sum += qlp_coeff[28] * data[i-29];
  95052. case 28: sum += qlp_coeff[27] * data[i-28];
  95053. case 27: sum += qlp_coeff[26] * data[i-27];
  95054. case 26: sum += qlp_coeff[25] * data[i-26];
  95055. case 25: sum += qlp_coeff[24] * data[i-25];
  95056. case 24: sum += qlp_coeff[23] * data[i-24];
  95057. case 23: sum += qlp_coeff[22] * data[i-23];
  95058. case 22: sum += qlp_coeff[21] * data[i-22];
  95059. case 21: sum += qlp_coeff[20] * data[i-21];
  95060. case 20: sum += qlp_coeff[19] * data[i-20];
  95061. case 19: sum += qlp_coeff[18] * data[i-19];
  95062. case 18: sum += qlp_coeff[17] * data[i-18];
  95063. case 17: sum += qlp_coeff[16] * data[i-17];
  95064. case 16: sum += qlp_coeff[15] * data[i-16];
  95065. case 15: sum += qlp_coeff[14] * data[i-15];
  95066. case 14: sum += qlp_coeff[13] * data[i-14];
  95067. case 13: sum += qlp_coeff[12] * data[i-13];
  95068. sum += qlp_coeff[11] * data[i-12];
  95069. sum += qlp_coeff[10] * data[i-11];
  95070. sum += qlp_coeff[ 9] * data[i-10];
  95071. sum += qlp_coeff[ 8] * data[i- 9];
  95072. sum += qlp_coeff[ 7] * data[i- 8];
  95073. sum += qlp_coeff[ 6] * data[i- 7];
  95074. sum += qlp_coeff[ 5] * data[i- 6];
  95075. sum += qlp_coeff[ 4] * data[i- 5];
  95076. sum += qlp_coeff[ 3] * data[i- 4];
  95077. sum += qlp_coeff[ 2] * data[i- 3];
  95078. sum += qlp_coeff[ 1] * data[i- 2];
  95079. sum += qlp_coeff[ 0] * data[i- 1];
  95080. }
  95081. data[i] = residual[i] + (sum >> lp_quantization);
  95082. }
  95083. }
  95084. }
  95085. #endif
  95086. 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[])
  95087. #if defined(FLAC__OVERFLOW_DETECT) || !defined(FLAC__LPC_UNROLLED_FILTER_LOOPS)
  95088. {
  95089. unsigned i, j;
  95090. FLAC__int64 sum;
  95091. const FLAC__int32 *r = residual, *history;
  95092. #ifdef FLAC__OVERFLOW_DETECT_VERBOSE
  95093. fprintf(stderr,"FLAC__lpc_restore_signal_wide: data_len=%d, order=%u, lpq=%d",data_len,order,lp_quantization);
  95094. for(i=0;i<order;i++)
  95095. fprintf(stderr,", q[%u]=%d",i,qlp_coeff[i]);
  95096. fprintf(stderr,"\n");
  95097. #endif
  95098. FLAC__ASSERT(order > 0);
  95099. for(i = 0; i < data_len; i++) {
  95100. sum = 0;
  95101. history = data;
  95102. for(j = 0; j < order; j++)
  95103. sum += (FLAC__int64)qlp_coeff[j] * (FLAC__int64)(*(--history));
  95104. if(FLAC__bitmath_silog2_wide(sum >> lp_quantization) > 32) {
  95105. #ifdef _MSC_VER
  95106. fprintf(stderr,"FLAC__lpc_restore_signal_wide: OVERFLOW, i=%u, sum=%I64d\n", i, sum >> lp_quantization);
  95107. #else
  95108. fprintf(stderr,"FLAC__lpc_restore_signal_wide: OVERFLOW, i=%u, sum=%lld\n", i, (long long)(sum >> lp_quantization));
  95109. #endif
  95110. break;
  95111. }
  95112. if(FLAC__bitmath_silog2_wide((FLAC__int64)(*r) + (sum >> lp_quantization)) > 32) {
  95113. #ifdef _MSC_VER
  95114. 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));
  95115. #else
  95116. 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)));
  95117. #endif
  95118. break;
  95119. }
  95120. *(data++) = *(r++) + (FLAC__int32)(sum >> lp_quantization);
  95121. }
  95122. }
  95123. #else /* fully unrolled version for normal use */
  95124. {
  95125. int i;
  95126. FLAC__int64 sum;
  95127. FLAC__ASSERT(order > 0);
  95128. FLAC__ASSERT(order <= 32);
  95129. /*
  95130. * We do unique versions up to 12th order since that's the subset limit.
  95131. * Also they are roughly ordered to match frequency of occurrence to
  95132. * minimize branching.
  95133. */
  95134. if(order <= 12) {
  95135. if(order > 8) {
  95136. if(order > 10) {
  95137. if(order == 12) {
  95138. for(i = 0; i < (int)data_len; i++) {
  95139. sum = 0;
  95140. sum += qlp_coeff[11] * (FLAC__int64)data[i-12];
  95141. sum += qlp_coeff[10] * (FLAC__int64)data[i-11];
  95142. sum += qlp_coeff[9] * (FLAC__int64)data[i-10];
  95143. sum += qlp_coeff[8] * (FLAC__int64)data[i-9];
  95144. sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
  95145. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  95146. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  95147. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  95148. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  95149. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  95150. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  95151. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  95152. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  95153. }
  95154. }
  95155. else { /* order == 11 */
  95156. for(i = 0; i < (int)data_len; i++) {
  95157. sum = 0;
  95158. sum += qlp_coeff[10] * (FLAC__int64)data[i-11];
  95159. sum += qlp_coeff[9] * (FLAC__int64)data[i-10];
  95160. sum += qlp_coeff[8] * (FLAC__int64)data[i-9];
  95161. sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
  95162. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  95163. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  95164. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  95165. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  95166. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  95167. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  95168. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  95169. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  95170. }
  95171. }
  95172. }
  95173. else {
  95174. if(order == 10) {
  95175. for(i = 0; i < (int)data_len; i++) {
  95176. sum = 0;
  95177. sum += qlp_coeff[9] * (FLAC__int64)data[i-10];
  95178. sum += qlp_coeff[8] * (FLAC__int64)data[i-9];
  95179. sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
  95180. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  95181. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  95182. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  95183. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  95184. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  95185. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  95186. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  95187. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  95188. }
  95189. }
  95190. else { /* order == 9 */
  95191. for(i = 0; i < (int)data_len; i++) {
  95192. sum = 0;
  95193. sum += qlp_coeff[8] * (FLAC__int64)data[i-9];
  95194. sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
  95195. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  95196. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  95197. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  95198. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  95199. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  95200. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  95201. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  95202. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  95203. }
  95204. }
  95205. }
  95206. }
  95207. else if(order > 4) {
  95208. if(order > 6) {
  95209. if(order == 8) {
  95210. for(i = 0; i < (int)data_len; i++) {
  95211. sum = 0;
  95212. sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
  95213. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  95214. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  95215. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  95216. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  95217. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  95218. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  95219. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  95220. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  95221. }
  95222. }
  95223. else { /* order == 7 */
  95224. for(i = 0; i < (int)data_len; i++) {
  95225. sum = 0;
  95226. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  95227. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  95228. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  95229. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  95230. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  95231. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  95232. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  95233. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  95234. }
  95235. }
  95236. }
  95237. else {
  95238. if(order == 6) {
  95239. for(i = 0; i < (int)data_len; i++) {
  95240. sum = 0;
  95241. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  95242. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  95243. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  95244. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  95245. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  95246. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  95247. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  95248. }
  95249. }
  95250. else { /* order == 5 */
  95251. for(i = 0; i < (int)data_len; i++) {
  95252. sum = 0;
  95253. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  95254. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  95255. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  95256. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  95257. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  95258. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  95259. }
  95260. }
  95261. }
  95262. }
  95263. else {
  95264. if(order > 2) {
  95265. if(order == 4) {
  95266. for(i = 0; i < (int)data_len; i++) {
  95267. sum = 0;
  95268. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  95269. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  95270. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  95271. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  95272. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  95273. }
  95274. }
  95275. else { /* order == 3 */
  95276. for(i = 0; i < (int)data_len; i++) {
  95277. sum = 0;
  95278. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  95279. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  95280. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  95281. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  95282. }
  95283. }
  95284. }
  95285. else {
  95286. if(order == 2) {
  95287. for(i = 0; i < (int)data_len; i++) {
  95288. sum = 0;
  95289. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  95290. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  95291. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  95292. }
  95293. }
  95294. else { /* order == 1 */
  95295. for(i = 0; i < (int)data_len; i++)
  95296. data[i] = residual[i] + (FLAC__int32)((qlp_coeff[0] * (FLAC__int64)data[i-1]) >> lp_quantization);
  95297. }
  95298. }
  95299. }
  95300. }
  95301. else { /* order > 12 */
  95302. for(i = 0; i < (int)data_len; i++) {
  95303. sum = 0;
  95304. switch(order) {
  95305. case 32: sum += qlp_coeff[31] * (FLAC__int64)data[i-32];
  95306. case 31: sum += qlp_coeff[30] * (FLAC__int64)data[i-31];
  95307. case 30: sum += qlp_coeff[29] * (FLAC__int64)data[i-30];
  95308. case 29: sum += qlp_coeff[28] * (FLAC__int64)data[i-29];
  95309. case 28: sum += qlp_coeff[27] * (FLAC__int64)data[i-28];
  95310. case 27: sum += qlp_coeff[26] * (FLAC__int64)data[i-27];
  95311. case 26: sum += qlp_coeff[25] * (FLAC__int64)data[i-26];
  95312. case 25: sum += qlp_coeff[24] * (FLAC__int64)data[i-25];
  95313. case 24: sum += qlp_coeff[23] * (FLAC__int64)data[i-24];
  95314. case 23: sum += qlp_coeff[22] * (FLAC__int64)data[i-23];
  95315. case 22: sum += qlp_coeff[21] * (FLAC__int64)data[i-22];
  95316. case 21: sum += qlp_coeff[20] * (FLAC__int64)data[i-21];
  95317. case 20: sum += qlp_coeff[19] * (FLAC__int64)data[i-20];
  95318. case 19: sum += qlp_coeff[18] * (FLAC__int64)data[i-19];
  95319. case 18: sum += qlp_coeff[17] * (FLAC__int64)data[i-18];
  95320. case 17: sum += qlp_coeff[16] * (FLAC__int64)data[i-17];
  95321. case 16: sum += qlp_coeff[15] * (FLAC__int64)data[i-16];
  95322. case 15: sum += qlp_coeff[14] * (FLAC__int64)data[i-15];
  95323. case 14: sum += qlp_coeff[13] * (FLAC__int64)data[i-14];
  95324. case 13: sum += qlp_coeff[12] * (FLAC__int64)data[i-13];
  95325. sum += qlp_coeff[11] * (FLAC__int64)data[i-12];
  95326. sum += qlp_coeff[10] * (FLAC__int64)data[i-11];
  95327. sum += qlp_coeff[ 9] * (FLAC__int64)data[i-10];
  95328. sum += qlp_coeff[ 8] * (FLAC__int64)data[i- 9];
  95329. sum += qlp_coeff[ 7] * (FLAC__int64)data[i- 8];
  95330. sum += qlp_coeff[ 6] * (FLAC__int64)data[i- 7];
  95331. sum += qlp_coeff[ 5] * (FLAC__int64)data[i- 6];
  95332. sum += qlp_coeff[ 4] * (FLAC__int64)data[i- 5];
  95333. sum += qlp_coeff[ 3] * (FLAC__int64)data[i- 4];
  95334. sum += qlp_coeff[ 2] * (FLAC__int64)data[i- 3];
  95335. sum += qlp_coeff[ 1] * (FLAC__int64)data[i- 2];
  95336. sum += qlp_coeff[ 0] * (FLAC__int64)data[i- 1];
  95337. }
  95338. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  95339. }
  95340. }
  95341. }
  95342. #endif
  95343. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  95344. FLAC__double FLAC__lpc_compute_expected_bits_per_residual_sample(FLAC__double lpc_error, unsigned total_samples)
  95345. {
  95346. FLAC__double error_scale;
  95347. FLAC__ASSERT(total_samples > 0);
  95348. error_scale = 0.5 * M_LN2 * M_LN2 / (FLAC__double)total_samples;
  95349. return FLAC__lpc_compute_expected_bits_per_residual_sample_with_error_scale(lpc_error, error_scale);
  95350. }
  95351. FLAC__double FLAC__lpc_compute_expected_bits_per_residual_sample_with_error_scale(FLAC__double lpc_error, FLAC__double error_scale)
  95352. {
  95353. if(lpc_error > 0.0) {
  95354. FLAC__double bps = (FLAC__double)0.5 * log(error_scale * lpc_error) / M_LN2;
  95355. if(bps >= 0.0)
  95356. return bps;
  95357. else
  95358. return 0.0;
  95359. }
  95360. else if(lpc_error < 0.0) { /* error should not be negative but can happen due to inadequate floating-point resolution */
  95361. return 1e32;
  95362. }
  95363. else {
  95364. return 0.0;
  95365. }
  95366. }
  95367. unsigned FLAC__lpc_compute_best_order(const FLAC__double lpc_error[], unsigned max_order, unsigned total_samples, unsigned overhead_bits_per_order)
  95368. {
  95369. 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 */
  95370. FLAC__double bits, best_bits, error_scale;
  95371. FLAC__ASSERT(max_order > 0);
  95372. FLAC__ASSERT(total_samples > 0);
  95373. error_scale = 0.5 * M_LN2 * M_LN2 / (FLAC__double)total_samples;
  95374. best_index = 0;
  95375. best_bits = (unsigned)(-1);
  95376. for(index = 0, order = 1; index < max_order; index++, order++) {
  95377. 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);
  95378. if(bits < best_bits) {
  95379. best_index = index;
  95380. best_bits = bits;
  95381. }
  95382. }
  95383. return best_index+1; /* +1 since index of lpc_error[] is order-1 */
  95384. }
  95385. #endif /* !defined FLAC__INTEGER_ONLY_LIBRARY */
  95386. #endif
  95387. /*** End of inlined file: lpc_flac.c ***/
  95388. /*** Start of inlined file: md5.c ***/
  95389. /*** Start of inlined file: juce_FlacHeader.h ***/
  95390. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  95391. // tasks..
  95392. #define VERSION "1.2.1"
  95393. #define FLAC__NO_DLL 1
  95394. #if JUCE_MSVC
  95395. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  95396. #endif
  95397. #if JUCE_MAC
  95398. #define FLAC__SYS_DARWIN 1
  95399. #endif
  95400. /*** End of inlined file: juce_FlacHeader.h ***/
  95401. #if JUCE_USE_FLAC
  95402. #if HAVE_CONFIG_H
  95403. # include <config.h>
  95404. #endif
  95405. #include <stdlib.h> /* for malloc() */
  95406. #include <string.h> /* for memcpy() */
  95407. /*** Start of inlined file: md5.h ***/
  95408. #ifndef FLAC__PRIVATE__MD5_H
  95409. #define FLAC__PRIVATE__MD5_H
  95410. /*
  95411. * This is the header file for the MD5 message-digest algorithm.
  95412. * The algorithm is due to Ron Rivest. This code was
  95413. * written by Colin Plumb in 1993, no copyright is claimed.
  95414. * This code is in the public domain; do with it what you wish.
  95415. *
  95416. * Equivalent code is available from RSA Data Security, Inc.
  95417. * This code has been tested against that, and is equivalent,
  95418. * except that you don't need to include two pages of legalese
  95419. * with every copy.
  95420. *
  95421. * To compute the message digest of a chunk of bytes, declare an
  95422. * MD5Context structure, pass it to MD5Init, call MD5Update as
  95423. * needed on buffers full of bytes, and then call MD5Final, which
  95424. * will fill a supplied 16-byte array with the digest.
  95425. *
  95426. * Changed so as no longer to depend on Colin Plumb's `usual.h'
  95427. * header definitions; now uses stuff from dpkg's config.h
  95428. * - Ian Jackson <ijackson@nyx.cs.du.edu>.
  95429. * Still in the public domain.
  95430. *
  95431. * Josh Coalson: made some changes to integrate with libFLAC.
  95432. * Still in the public domain, with no warranty.
  95433. */
  95434. typedef struct {
  95435. FLAC__uint32 in[16];
  95436. FLAC__uint32 buf[4];
  95437. FLAC__uint32 bytes[2];
  95438. FLAC__byte *internal_buf;
  95439. size_t capacity;
  95440. } FLAC__MD5Context;
  95441. void FLAC__MD5Init(FLAC__MD5Context *context);
  95442. void FLAC__MD5Final(FLAC__byte digest[16], FLAC__MD5Context *context);
  95443. FLAC__bool FLAC__MD5Accumulate(FLAC__MD5Context *ctx, const FLAC__int32 * const signal[], unsigned channels, unsigned samples, unsigned bytes_per_sample);
  95444. #endif
  95445. /*** End of inlined file: md5.h ***/
  95446. #ifndef FLaC__INLINE
  95447. #define FLaC__INLINE
  95448. #endif
  95449. /*
  95450. * This code implements the MD5 message-digest algorithm.
  95451. * The algorithm is due to Ron Rivest. This code was
  95452. * written by Colin Plumb in 1993, no copyright is claimed.
  95453. * This code is in the public domain; do with it what you wish.
  95454. *
  95455. * Equivalent code is available from RSA Data Security, Inc.
  95456. * This code has been tested against that, and is equivalent,
  95457. * except that you don't need to include two pages of legalese
  95458. * with every copy.
  95459. *
  95460. * To compute the message digest of a chunk of bytes, declare an
  95461. * MD5Context structure, pass it to MD5Init, call MD5Update as
  95462. * needed on buffers full of bytes, and then call MD5Final, which
  95463. * will fill a supplied 16-byte array with the digest.
  95464. *
  95465. * Changed so as no longer to depend on Colin Plumb's `usual.h' header
  95466. * definitions; now uses stuff from dpkg's config.h.
  95467. * - Ian Jackson <ijackson@nyx.cs.du.edu>.
  95468. * Still in the public domain.
  95469. *
  95470. * Josh Coalson: made some changes to integrate with libFLAC.
  95471. * Still in the public domain.
  95472. */
  95473. /* The four core functions - F1 is optimized somewhat */
  95474. /* #define F1(x, y, z) (x & y | ~x & z) */
  95475. #define F1(x, y, z) (z ^ (x & (y ^ z)))
  95476. #define F2(x, y, z) F1(z, x, y)
  95477. #define F3(x, y, z) (x ^ y ^ z)
  95478. #define F4(x, y, z) (y ^ (x | ~z))
  95479. /* This is the central step in the MD5 algorithm. */
  95480. #define MD5STEP(f,w,x,y,z,in,s) \
  95481. (w += f(x,y,z) + in, w = (w<<s | w>>(32-s)) + x)
  95482. /*
  95483. * The core of the MD5 algorithm, this alters an existing MD5 hash to
  95484. * reflect the addition of 16 longwords of new data. MD5Update blocks
  95485. * the data and converts bytes into longwords for this routine.
  95486. */
  95487. static void FLAC__MD5Transform(FLAC__uint32 buf[4], FLAC__uint32 const in[16])
  95488. {
  95489. register FLAC__uint32 a, b, c, d;
  95490. a = buf[0];
  95491. b = buf[1];
  95492. c = buf[2];
  95493. d = buf[3];
  95494. MD5STEP(F1, a, b, c, d, in[0] + 0xd76aa478, 7);
  95495. MD5STEP(F1, d, a, b, c, in[1] + 0xe8c7b756, 12);
  95496. MD5STEP(F1, c, d, a, b, in[2] + 0x242070db, 17);
  95497. MD5STEP(F1, b, c, d, a, in[3] + 0xc1bdceee, 22);
  95498. MD5STEP(F1, a, b, c, d, in[4] + 0xf57c0faf, 7);
  95499. MD5STEP(F1, d, a, b, c, in[5] + 0x4787c62a, 12);
  95500. MD5STEP(F1, c, d, a, b, in[6] + 0xa8304613, 17);
  95501. MD5STEP(F1, b, c, d, a, in[7] + 0xfd469501, 22);
  95502. MD5STEP(F1, a, b, c, d, in[8] + 0x698098d8, 7);
  95503. MD5STEP(F1, d, a, b, c, in[9] + 0x8b44f7af, 12);
  95504. MD5STEP(F1, c, d, a, b, in[10] + 0xffff5bb1, 17);
  95505. MD5STEP(F1, b, c, d, a, in[11] + 0x895cd7be, 22);
  95506. MD5STEP(F1, a, b, c, d, in[12] + 0x6b901122, 7);
  95507. MD5STEP(F1, d, a, b, c, in[13] + 0xfd987193, 12);
  95508. MD5STEP(F1, c, d, a, b, in[14] + 0xa679438e, 17);
  95509. MD5STEP(F1, b, c, d, a, in[15] + 0x49b40821, 22);
  95510. MD5STEP(F2, a, b, c, d, in[1] + 0xf61e2562, 5);
  95511. MD5STEP(F2, d, a, b, c, in[6] + 0xc040b340, 9);
  95512. MD5STEP(F2, c, d, a, b, in[11] + 0x265e5a51, 14);
  95513. MD5STEP(F2, b, c, d, a, in[0] + 0xe9b6c7aa, 20);
  95514. MD5STEP(F2, a, b, c, d, in[5] + 0xd62f105d, 5);
  95515. MD5STEP(F2, d, a, b, c, in[10] + 0x02441453, 9);
  95516. MD5STEP(F2, c, d, a, b, in[15] + 0xd8a1e681, 14);
  95517. MD5STEP(F2, b, c, d, a, in[4] + 0xe7d3fbc8, 20);
  95518. MD5STEP(F2, a, b, c, d, in[9] + 0x21e1cde6, 5);
  95519. MD5STEP(F2, d, a, b, c, in[14] + 0xc33707d6, 9);
  95520. MD5STEP(F2, c, d, a, b, in[3] + 0xf4d50d87, 14);
  95521. MD5STEP(F2, b, c, d, a, in[8] + 0x455a14ed, 20);
  95522. MD5STEP(F2, a, b, c, d, in[13] + 0xa9e3e905, 5);
  95523. MD5STEP(F2, d, a, b, c, in[2] + 0xfcefa3f8, 9);
  95524. MD5STEP(F2, c, d, a, b, in[7] + 0x676f02d9, 14);
  95525. MD5STEP(F2, b, c, d, a, in[12] + 0x8d2a4c8a, 20);
  95526. MD5STEP(F3, a, b, c, d, in[5] + 0xfffa3942, 4);
  95527. MD5STEP(F3, d, a, b, c, in[8] + 0x8771f681, 11);
  95528. MD5STEP(F3, c, d, a, b, in[11] + 0x6d9d6122, 16);
  95529. MD5STEP(F3, b, c, d, a, in[14] + 0xfde5380c, 23);
  95530. MD5STEP(F3, a, b, c, d, in[1] + 0xa4beea44, 4);
  95531. MD5STEP(F3, d, a, b, c, in[4] + 0x4bdecfa9, 11);
  95532. MD5STEP(F3, c, d, a, b, in[7] + 0xf6bb4b60, 16);
  95533. MD5STEP(F3, b, c, d, a, in[10] + 0xbebfbc70, 23);
  95534. MD5STEP(F3, a, b, c, d, in[13] + 0x289b7ec6, 4);
  95535. MD5STEP(F3, d, a, b, c, in[0] + 0xeaa127fa, 11);
  95536. MD5STEP(F3, c, d, a, b, in[3] + 0xd4ef3085, 16);
  95537. MD5STEP(F3, b, c, d, a, in[6] + 0x04881d05, 23);
  95538. MD5STEP(F3, a, b, c, d, in[9] + 0xd9d4d039, 4);
  95539. MD5STEP(F3, d, a, b, c, in[12] + 0xe6db99e5, 11);
  95540. MD5STEP(F3, c, d, a, b, in[15] + 0x1fa27cf8, 16);
  95541. MD5STEP(F3, b, c, d, a, in[2] + 0xc4ac5665, 23);
  95542. MD5STEP(F4, a, b, c, d, in[0] + 0xf4292244, 6);
  95543. MD5STEP(F4, d, a, b, c, in[7] + 0x432aff97, 10);
  95544. MD5STEP(F4, c, d, a, b, in[14] + 0xab9423a7, 15);
  95545. MD5STEP(F4, b, c, d, a, in[5] + 0xfc93a039, 21);
  95546. MD5STEP(F4, a, b, c, d, in[12] + 0x655b59c3, 6);
  95547. MD5STEP(F4, d, a, b, c, in[3] + 0x8f0ccc92, 10);
  95548. MD5STEP(F4, c, d, a, b, in[10] + 0xffeff47d, 15);
  95549. MD5STEP(F4, b, c, d, a, in[1] + 0x85845dd1, 21);
  95550. MD5STEP(F4, a, b, c, d, in[8] + 0x6fa87e4f, 6);
  95551. MD5STEP(F4, d, a, b, c, in[15] + 0xfe2ce6e0, 10);
  95552. MD5STEP(F4, c, d, a, b, in[6] + 0xa3014314, 15);
  95553. MD5STEP(F4, b, c, d, a, in[13] + 0x4e0811a1, 21);
  95554. MD5STEP(F4, a, b, c, d, in[4] + 0xf7537e82, 6);
  95555. MD5STEP(F4, d, a, b, c, in[11] + 0xbd3af235, 10);
  95556. MD5STEP(F4, c, d, a, b, in[2] + 0x2ad7d2bb, 15);
  95557. MD5STEP(F4, b, c, d, a, in[9] + 0xeb86d391, 21);
  95558. buf[0] += a;
  95559. buf[1] += b;
  95560. buf[2] += c;
  95561. buf[3] += d;
  95562. }
  95563. #if WORDS_BIGENDIAN
  95564. //@@@@@@ OPT: use bswap/intrinsics
  95565. static void byteSwap(FLAC__uint32 *buf, unsigned words)
  95566. {
  95567. register FLAC__uint32 x;
  95568. do {
  95569. x = *buf;
  95570. x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff);
  95571. *buf++ = (x >> 16) | (x << 16);
  95572. } while (--words);
  95573. }
  95574. static void byteSwapX16(FLAC__uint32 *buf)
  95575. {
  95576. register FLAC__uint32 x;
  95577. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  95578. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  95579. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  95580. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  95581. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  95582. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  95583. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  95584. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  95585. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  95586. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  95587. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  95588. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  95589. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  95590. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  95591. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  95592. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf = (x >> 16) | (x << 16);
  95593. }
  95594. #else
  95595. #define byteSwap(buf, words)
  95596. #define byteSwapX16(buf)
  95597. #endif
  95598. /*
  95599. * Update context to reflect the concatenation of another buffer full
  95600. * of bytes.
  95601. */
  95602. static void FLAC__MD5Update(FLAC__MD5Context *ctx, FLAC__byte const *buf, unsigned len)
  95603. {
  95604. FLAC__uint32 t;
  95605. /* Update byte count */
  95606. t = ctx->bytes[0];
  95607. if ((ctx->bytes[0] = t + len) < t)
  95608. ctx->bytes[1]++; /* Carry from low to high */
  95609. t = 64 - (t & 0x3f); /* Space available in ctx->in (at least 1) */
  95610. if (t > len) {
  95611. memcpy((FLAC__byte *)ctx->in + 64 - t, buf, len);
  95612. return;
  95613. }
  95614. /* First chunk is an odd size */
  95615. memcpy((FLAC__byte *)ctx->in + 64 - t, buf, t);
  95616. byteSwapX16(ctx->in);
  95617. FLAC__MD5Transform(ctx->buf, ctx->in);
  95618. buf += t;
  95619. len -= t;
  95620. /* Process data in 64-byte chunks */
  95621. while (len >= 64) {
  95622. memcpy(ctx->in, buf, 64);
  95623. byteSwapX16(ctx->in);
  95624. FLAC__MD5Transform(ctx->buf, ctx->in);
  95625. buf += 64;
  95626. len -= 64;
  95627. }
  95628. /* Handle any remaining bytes of data. */
  95629. memcpy(ctx->in, buf, len);
  95630. }
  95631. /*
  95632. * Start MD5 accumulation. Set bit count to 0 and buffer to mysterious
  95633. * initialization constants.
  95634. */
  95635. void FLAC__MD5Init(FLAC__MD5Context *ctx)
  95636. {
  95637. ctx->buf[0] = 0x67452301;
  95638. ctx->buf[1] = 0xefcdab89;
  95639. ctx->buf[2] = 0x98badcfe;
  95640. ctx->buf[3] = 0x10325476;
  95641. ctx->bytes[0] = 0;
  95642. ctx->bytes[1] = 0;
  95643. ctx->internal_buf = 0;
  95644. ctx->capacity = 0;
  95645. }
  95646. /*
  95647. * Final wrapup - pad to 64-byte boundary with the bit pattern
  95648. * 1 0* (64-bit count of bits processed, MSB-first)
  95649. */
  95650. void FLAC__MD5Final(FLAC__byte digest[16], FLAC__MD5Context *ctx)
  95651. {
  95652. int count = ctx->bytes[0] & 0x3f; /* Number of bytes in ctx->in */
  95653. FLAC__byte *p = (FLAC__byte *)ctx->in + count;
  95654. /* Set the first char of padding to 0x80. There is always room. */
  95655. *p++ = 0x80;
  95656. /* Bytes of padding needed to make 56 bytes (-8..55) */
  95657. count = 56 - 1 - count;
  95658. if (count < 0) { /* Padding forces an extra block */
  95659. memset(p, 0, count + 8);
  95660. byteSwapX16(ctx->in);
  95661. FLAC__MD5Transform(ctx->buf, ctx->in);
  95662. p = (FLAC__byte *)ctx->in;
  95663. count = 56;
  95664. }
  95665. memset(p, 0, count);
  95666. byteSwap(ctx->in, 14);
  95667. /* Append length in bits and transform */
  95668. ctx->in[14] = ctx->bytes[0] << 3;
  95669. ctx->in[15] = ctx->bytes[1] << 3 | ctx->bytes[0] >> 29;
  95670. FLAC__MD5Transform(ctx->buf, ctx->in);
  95671. byteSwap(ctx->buf, 4);
  95672. memcpy(digest, ctx->buf, 16);
  95673. memset(ctx, 0, sizeof(ctx)); /* In case it's sensitive */
  95674. if(0 != ctx->internal_buf) {
  95675. free(ctx->internal_buf);
  95676. ctx->internal_buf = 0;
  95677. ctx->capacity = 0;
  95678. }
  95679. }
  95680. /*
  95681. * Convert the incoming audio signal to a byte stream
  95682. */
  95683. static void format_input_(FLAC__byte *buf, const FLAC__int32 * const signal[], unsigned channels, unsigned samples, unsigned bytes_per_sample)
  95684. {
  95685. unsigned channel, sample;
  95686. register FLAC__int32 a_word;
  95687. register FLAC__byte *buf_ = buf;
  95688. #if WORDS_BIGENDIAN
  95689. #else
  95690. if(channels == 2 && bytes_per_sample == 2) {
  95691. FLAC__int16 *buf1_ = ((FLAC__int16*)buf_) + 1;
  95692. memcpy(buf_, signal[0], sizeof(FLAC__int32) * samples);
  95693. for(sample = 0; sample < samples; sample++, buf1_+=2)
  95694. *buf1_ = (FLAC__int16)signal[1][sample];
  95695. }
  95696. else if(channels == 1 && bytes_per_sample == 2) {
  95697. FLAC__int16 *buf1_ = (FLAC__int16*)buf_;
  95698. for(sample = 0; sample < samples; sample++)
  95699. *buf1_++ = (FLAC__int16)signal[0][sample];
  95700. }
  95701. else
  95702. #endif
  95703. if(bytes_per_sample == 2) {
  95704. if(channels == 2) {
  95705. for(sample = 0; sample < samples; sample++) {
  95706. a_word = signal[0][sample];
  95707. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  95708. *buf_++ = (FLAC__byte)a_word;
  95709. a_word = signal[1][sample];
  95710. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  95711. *buf_++ = (FLAC__byte)a_word;
  95712. }
  95713. }
  95714. else if(channels == 1) {
  95715. for(sample = 0; sample < samples; sample++) {
  95716. a_word = signal[0][sample];
  95717. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  95718. *buf_++ = (FLAC__byte)a_word;
  95719. }
  95720. }
  95721. else {
  95722. for(sample = 0; sample < samples; sample++) {
  95723. for(channel = 0; channel < channels; channel++) {
  95724. a_word = signal[channel][sample];
  95725. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  95726. *buf_++ = (FLAC__byte)a_word;
  95727. }
  95728. }
  95729. }
  95730. }
  95731. else if(bytes_per_sample == 3) {
  95732. if(channels == 2) {
  95733. for(sample = 0; sample < samples; sample++) {
  95734. a_word = signal[0][sample];
  95735. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  95736. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  95737. *buf_++ = (FLAC__byte)a_word;
  95738. a_word = signal[1][sample];
  95739. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  95740. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  95741. *buf_++ = (FLAC__byte)a_word;
  95742. }
  95743. }
  95744. else if(channels == 1) {
  95745. for(sample = 0; sample < samples; sample++) {
  95746. a_word = signal[0][sample];
  95747. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  95748. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  95749. *buf_++ = (FLAC__byte)a_word;
  95750. }
  95751. }
  95752. else {
  95753. for(sample = 0; sample < samples; sample++) {
  95754. for(channel = 0; channel < channels; channel++) {
  95755. a_word = signal[channel][sample];
  95756. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  95757. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  95758. *buf_++ = (FLAC__byte)a_word;
  95759. }
  95760. }
  95761. }
  95762. }
  95763. else if(bytes_per_sample == 1) {
  95764. if(channels == 2) {
  95765. for(sample = 0; sample < samples; sample++) {
  95766. a_word = signal[0][sample];
  95767. *buf_++ = (FLAC__byte)a_word;
  95768. a_word = signal[1][sample];
  95769. *buf_++ = (FLAC__byte)a_word;
  95770. }
  95771. }
  95772. else if(channels == 1) {
  95773. for(sample = 0; sample < samples; sample++) {
  95774. a_word = signal[0][sample];
  95775. *buf_++ = (FLAC__byte)a_word;
  95776. }
  95777. }
  95778. else {
  95779. for(sample = 0; sample < samples; sample++) {
  95780. for(channel = 0; channel < channels; channel++) {
  95781. a_word = signal[channel][sample];
  95782. *buf_++ = (FLAC__byte)a_word;
  95783. }
  95784. }
  95785. }
  95786. }
  95787. else { /* bytes_per_sample == 4, maybe optimize more later */
  95788. for(sample = 0; sample < samples; sample++) {
  95789. for(channel = 0; channel < channels; channel++) {
  95790. a_word = signal[channel][sample];
  95791. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  95792. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  95793. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  95794. *buf_++ = (FLAC__byte)a_word;
  95795. }
  95796. }
  95797. }
  95798. }
  95799. /*
  95800. * Convert the incoming audio signal to a byte stream and FLAC__MD5Update it.
  95801. */
  95802. FLAC__bool FLAC__MD5Accumulate(FLAC__MD5Context *ctx, const FLAC__int32 * const signal[], unsigned channels, unsigned samples, unsigned bytes_per_sample)
  95803. {
  95804. const size_t bytes_needed = (size_t)channels * (size_t)samples * (size_t)bytes_per_sample;
  95805. /* overflow check */
  95806. if((size_t)channels > SIZE_MAX / (size_t)bytes_per_sample)
  95807. return false;
  95808. if((size_t)channels * (size_t)bytes_per_sample > SIZE_MAX / (size_t)samples)
  95809. return false;
  95810. if(ctx->capacity < bytes_needed) {
  95811. FLAC__byte *tmp = (FLAC__byte*)realloc(ctx->internal_buf, bytes_needed);
  95812. if(0 == tmp) {
  95813. free(ctx->internal_buf);
  95814. if(0 == (ctx->internal_buf = (FLAC__byte*)safe_malloc_(bytes_needed)))
  95815. return false;
  95816. }
  95817. ctx->internal_buf = tmp;
  95818. ctx->capacity = bytes_needed;
  95819. }
  95820. format_input_(ctx->internal_buf, signal, channels, samples, bytes_per_sample);
  95821. FLAC__MD5Update(ctx, ctx->internal_buf, bytes_needed);
  95822. return true;
  95823. }
  95824. #endif
  95825. /*** End of inlined file: md5.c ***/
  95826. /*** Start of inlined file: memory.c ***/
  95827. /*** Start of inlined file: juce_FlacHeader.h ***/
  95828. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  95829. // tasks..
  95830. #define VERSION "1.2.1"
  95831. #define FLAC__NO_DLL 1
  95832. #if JUCE_MSVC
  95833. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  95834. #endif
  95835. #if JUCE_MAC
  95836. #define FLAC__SYS_DARWIN 1
  95837. #endif
  95838. /*** End of inlined file: juce_FlacHeader.h ***/
  95839. #if JUCE_USE_FLAC
  95840. #if HAVE_CONFIG_H
  95841. # include <config.h>
  95842. #endif
  95843. /*** Start of inlined file: memory.h ***/
  95844. #ifndef FLAC__PRIVATE__MEMORY_H
  95845. #define FLAC__PRIVATE__MEMORY_H
  95846. #ifdef HAVE_CONFIG_H
  95847. #include <config.h>
  95848. #endif
  95849. #include <stdlib.h> /* for size_t */
  95850. /* Returns the unaligned address returned by malloc.
  95851. * Use free() on this address to deallocate.
  95852. */
  95853. void *FLAC__memory_alloc_aligned(size_t bytes, void **aligned_address);
  95854. FLAC__bool FLAC__memory_alloc_aligned_int32_array(unsigned elements, FLAC__int32 **unaligned_pointer, FLAC__int32 **aligned_pointer);
  95855. FLAC__bool FLAC__memory_alloc_aligned_uint32_array(unsigned elements, FLAC__uint32 **unaligned_pointer, FLAC__uint32 **aligned_pointer);
  95856. FLAC__bool FLAC__memory_alloc_aligned_uint64_array(unsigned elements, FLAC__uint64 **unaligned_pointer, FLAC__uint64 **aligned_pointer);
  95857. FLAC__bool FLAC__memory_alloc_aligned_unsigned_array(unsigned elements, unsigned **unaligned_pointer, unsigned **aligned_pointer);
  95858. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  95859. FLAC__bool FLAC__memory_alloc_aligned_real_array(unsigned elements, FLAC__real **unaligned_pointer, FLAC__real **aligned_pointer);
  95860. #endif
  95861. #endif
  95862. /*** End of inlined file: memory.h ***/
  95863. void *FLAC__memory_alloc_aligned(size_t bytes, void **aligned_address)
  95864. {
  95865. void *x;
  95866. FLAC__ASSERT(0 != aligned_address);
  95867. #ifdef FLAC__ALIGN_MALLOC_DATA
  95868. /* align on 32-byte (256-bit) boundary */
  95869. x = safe_malloc_add_2op_(bytes, /*+*/31);
  95870. #ifdef SIZEOF_VOIDP
  95871. #if SIZEOF_VOIDP == 4
  95872. /* could do *aligned_address = x + ((unsigned) (32 - (((unsigned)x) & 31))) & 31; */
  95873. *aligned_address = (void*)(((unsigned)x + 31) & -32);
  95874. #elif SIZEOF_VOIDP == 8
  95875. *aligned_address = (void*)(((FLAC__uint64)x + 31) & (FLAC__uint64)(-((FLAC__int64)32)));
  95876. #else
  95877. # error Unsupported sizeof(void*)
  95878. #endif
  95879. #else
  95880. /* there's got to be a better way to do this right for all archs */
  95881. if(sizeof(void*) == sizeof(unsigned))
  95882. *aligned_address = (void*)(((unsigned)x + 31) & -32);
  95883. else if(sizeof(void*) == sizeof(FLAC__uint64))
  95884. *aligned_address = (void*)(((FLAC__uint64)x + 31) & (FLAC__uint64)(-((FLAC__int64)32)));
  95885. else
  95886. return 0;
  95887. #endif
  95888. #else
  95889. x = safe_malloc_(bytes);
  95890. *aligned_address = x;
  95891. #endif
  95892. return x;
  95893. }
  95894. FLAC__bool FLAC__memory_alloc_aligned_int32_array(unsigned elements, FLAC__int32 **unaligned_pointer, FLAC__int32 **aligned_pointer)
  95895. {
  95896. FLAC__int32 *pu; /* unaligned pointer */
  95897. union { /* union needed to comply with C99 pointer aliasing rules */
  95898. FLAC__int32 *pa; /* aligned pointer */
  95899. void *pv; /* aligned pointer alias */
  95900. } u;
  95901. FLAC__ASSERT(elements > 0);
  95902. FLAC__ASSERT(0 != unaligned_pointer);
  95903. FLAC__ASSERT(0 != aligned_pointer);
  95904. FLAC__ASSERT(unaligned_pointer != aligned_pointer);
  95905. pu = (FLAC__int32*)FLAC__memory_alloc_aligned(sizeof(*pu) * (size_t)elements, &u.pv);
  95906. if(0 == pu) {
  95907. return false;
  95908. }
  95909. else {
  95910. if(*unaligned_pointer != 0)
  95911. free(*unaligned_pointer);
  95912. *unaligned_pointer = pu;
  95913. *aligned_pointer = u.pa;
  95914. return true;
  95915. }
  95916. }
  95917. FLAC__bool FLAC__memory_alloc_aligned_uint32_array(unsigned elements, FLAC__uint32 **unaligned_pointer, FLAC__uint32 **aligned_pointer)
  95918. {
  95919. FLAC__uint32 *pu; /* unaligned pointer */
  95920. union { /* union needed to comply with C99 pointer aliasing rules */
  95921. FLAC__uint32 *pa; /* aligned pointer */
  95922. void *pv; /* aligned pointer alias */
  95923. } u;
  95924. FLAC__ASSERT(elements > 0);
  95925. FLAC__ASSERT(0 != unaligned_pointer);
  95926. FLAC__ASSERT(0 != aligned_pointer);
  95927. FLAC__ASSERT(unaligned_pointer != aligned_pointer);
  95928. pu = (FLAC__uint32*)FLAC__memory_alloc_aligned(sizeof(*pu) * elements, &u.pv);
  95929. if(0 == pu) {
  95930. return false;
  95931. }
  95932. else {
  95933. if(*unaligned_pointer != 0)
  95934. free(*unaligned_pointer);
  95935. *unaligned_pointer = pu;
  95936. *aligned_pointer = u.pa;
  95937. return true;
  95938. }
  95939. }
  95940. FLAC__bool FLAC__memory_alloc_aligned_uint64_array(unsigned elements, FLAC__uint64 **unaligned_pointer, FLAC__uint64 **aligned_pointer)
  95941. {
  95942. FLAC__uint64 *pu; /* unaligned pointer */
  95943. union { /* union needed to comply with C99 pointer aliasing rules */
  95944. FLAC__uint64 *pa; /* aligned pointer */
  95945. void *pv; /* aligned pointer alias */
  95946. } u;
  95947. FLAC__ASSERT(elements > 0);
  95948. FLAC__ASSERT(0 != unaligned_pointer);
  95949. FLAC__ASSERT(0 != aligned_pointer);
  95950. FLAC__ASSERT(unaligned_pointer != aligned_pointer);
  95951. pu = (FLAC__uint64*)FLAC__memory_alloc_aligned(sizeof(*pu) * elements, &u.pv);
  95952. if(0 == pu) {
  95953. return false;
  95954. }
  95955. else {
  95956. if(*unaligned_pointer != 0)
  95957. free(*unaligned_pointer);
  95958. *unaligned_pointer = pu;
  95959. *aligned_pointer = u.pa;
  95960. return true;
  95961. }
  95962. }
  95963. FLAC__bool FLAC__memory_alloc_aligned_unsigned_array(unsigned elements, unsigned **unaligned_pointer, unsigned **aligned_pointer)
  95964. {
  95965. unsigned *pu; /* unaligned pointer */
  95966. union { /* union needed to comply with C99 pointer aliasing rules */
  95967. unsigned *pa; /* aligned pointer */
  95968. void *pv; /* aligned pointer alias */
  95969. } u;
  95970. FLAC__ASSERT(elements > 0);
  95971. FLAC__ASSERT(0 != unaligned_pointer);
  95972. FLAC__ASSERT(0 != aligned_pointer);
  95973. FLAC__ASSERT(unaligned_pointer != aligned_pointer);
  95974. pu = (unsigned*)FLAC__memory_alloc_aligned(sizeof(*pu) * elements, &u.pv);
  95975. if(0 == pu) {
  95976. return false;
  95977. }
  95978. else {
  95979. if(*unaligned_pointer != 0)
  95980. free(*unaligned_pointer);
  95981. *unaligned_pointer = pu;
  95982. *aligned_pointer = u.pa;
  95983. return true;
  95984. }
  95985. }
  95986. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  95987. FLAC__bool FLAC__memory_alloc_aligned_real_array(unsigned elements, FLAC__real **unaligned_pointer, FLAC__real **aligned_pointer)
  95988. {
  95989. FLAC__real *pu; /* unaligned pointer */
  95990. union { /* union needed to comply with C99 pointer aliasing rules */
  95991. FLAC__real *pa; /* aligned pointer */
  95992. void *pv; /* aligned pointer alias */
  95993. } u;
  95994. FLAC__ASSERT(elements > 0);
  95995. FLAC__ASSERT(0 != unaligned_pointer);
  95996. FLAC__ASSERT(0 != aligned_pointer);
  95997. FLAC__ASSERT(unaligned_pointer != aligned_pointer);
  95998. pu = (FLAC__real*)FLAC__memory_alloc_aligned(sizeof(*pu) * elements, &u.pv);
  95999. if(0 == pu) {
  96000. return false;
  96001. }
  96002. else {
  96003. if(*unaligned_pointer != 0)
  96004. free(*unaligned_pointer);
  96005. *unaligned_pointer = pu;
  96006. *aligned_pointer = u.pa;
  96007. return true;
  96008. }
  96009. }
  96010. #endif
  96011. #endif
  96012. /*** End of inlined file: memory.c ***/
  96013. /*** Start of inlined file: stream_decoder.c ***/
  96014. /*** Start of inlined file: juce_FlacHeader.h ***/
  96015. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  96016. // tasks..
  96017. #define VERSION "1.2.1"
  96018. #define FLAC__NO_DLL 1
  96019. #if JUCE_MSVC
  96020. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  96021. #endif
  96022. #if JUCE_MAC
  96023. #define FLAC__SYS_DARWIN 1
  96024. #endif
  96025. /*** End of inlined file: juce_FlacHeader.h ***/
  96026. #if JUCE_USE_FLAC
  96027. #if HAVE_CONFIG_H
  96028. # include <config.h>
  96029. #endif
  96030. #if defined _MSC_VER || defined __MINGW32__
  96031. #include <io.h> /* for _setmode() */
  96032. #include <fcntl.h> /* for _O_BINARY */
  96033. #endif
  96034. #if defined __CYGWIN__ || defined __EMX__
  96035. #include <io.h> /* for setmode(), O_BINARY */
  96036. #include <fcntl.h> /* for _O_BINARY */
  96037. #endif
  96038. #include <stdio.h>
  96039. #include <stdlib.h> /* for malloc() */
  96040. #include <string.h> /* for memset/memcpy() */
  96041. #include <sys/stat.h> /* for stat() */
  96042. #include <sys/types.h> /* for off_t */
  96043. #if defined _MSC_VER || defined __BORLANDC__ || defined __MINGW32__
  96044. #if _MSC_VER <= 1600 || defined __BORLANDC__ /* @@@ [2G limit] */
  96045. #define fseeko fseek
  96046. #define ftello ftell
  96047. #endif
  96048. #endif
  96049. /*** Start of inlined file: stream_decoder.h ***/
  96050. #ifndef FLAC__PROTECTED__STREAM_DECODER_H
  96051. #define FLAC__PROTECTED__STREAM_DECODER_H
  96052. #if FLAC__HAS_OGG
  96053. #include "include/private/ogg_decoder_aspect.h"
  96054. #endif
  96055. typedef struct FLAC__StreamDecoderProtected {
  96056. FLAC__StreamDecoderState state;
  96057. unsigned channels;
  96058. FLAC__ChannelAssignment channel_assignment;
  96059. unsigned bits_per_sample;
  96060. unsigned sample_rate; /* in Hz */
  96061. unsigned blocksize; /* in samples (per channel) */
  96062. FLAC__bool md5_checking; /* if true, generate MD5 signature of decoded data and compare against signature in the STREAMINFO metadata block */
  96063. #if FLAC__HAS_OGG
  96064. FLAC__OggDecoderAspect ogg_decoder_aspect;
  96065. #endif
  96066. } FLAC__StreamDecoderProtected;
  96067. /*
  96068. * return the number of input bytes consumed
  96069. */
  96070. unsigned FLAC__stream_decoder_get_input_bytes_unconsumed(const FLAC__StreamDecoder *decoder);
  96071. #endif
  96072. /*** End of inlined file: stream_decoder.h ***/
  96073. #ifdef max
  96074. #undef max
  96075. #endif
  96076. #define max(a,b) ((a)>(b)?(a):(b))
  96077. /* adjust for compilers that can't understand using LLU suffix for uint64_t literals */
  96078. #ifdef _MSC_VER
  96079. #define FLAC__U64L(x) x
  96080. #else
  96081. #define FLAC__U64L(x) x##LLU
  96082. #endif
  96083. /* technically this should be in an "export.c" but this is convenient enough */
  96084. FLAC_API int FLAC_API_SUPPORTS_OGG_FLAC =
  96085. #if FLAC__HAS_OGG
  96086. 1
  96087. #else
  96088. 0
  96089. #endif
  96090. ;
  96091. /***********************************************************************
  96092. *
  96093. * Private static data
  96094. *
  96095. ***********************************************************************/
  96096. static FLAC__byte ID3V2_TAG_[3] = { 'I', 'D', '3' };
  96097. /***********************************************************************
  96098. *
  96099. * Private class method prototypes
  96100. *
  96101. ***********************************************************************/
  96102. static void set_defaults_dec(FLAC__StreamDecoder *decoder);
  96103. static FILE *get_binary_stdin_(void);
  96104. static FLAC__bool allocate_output_(FLAC__StreamDecoder *decoder, unsigned size, unsigned channels);
  96105. static FLAC__bool has_id_filtered_(FLAC__StreamDecoder *decoder, FLAC__byte *id);
  96106. static FLAC__bool find_metadata_(FLAC__StreamDecoder *decoder);
  96107. static FLAC__bool read_metadata_(FLAC__StreamDecoder *decoder);
  96108. static FLAC__bool read_metadata_streaminfo_(FLAC__StreamDecoder *decoder, FLAC__bool is_last, unsigned length);
  96109. static FLAC__bool read_metadata_seektable_(FLAC__StreamDecoder *decoder, FLAC__bool is_last, unsigned length);
  96110. static FLAC__bool read_metadata_vorbiscomment_(FLAC__StreamDecoder *decoder, FLAC__StreamMetadata_VorbisComment *obj);
  96111. static FLAC__bool read_metadata_cuesheet_(FLAC__StreamDecoder *decoder, FLAC__StreamMetadata_CueSheet *obj);
  96112. static FLAC__bool read_metadata_picture_(FLAC__StreamDecoder *decoder, FLAC__StreamMetadata_Picture *obj);
  96113. static FLAC__bool skip_id3v2_tag_(FLAC__StreamDecoder *decoder);
  96114. static FLAC__bool frame_sync_(FLAC__StreamDecoder *decoder);
  96115. static FLAC__bool read_frame_(FLAC__StreamDecoder *decoder, FLAC__bool *got_a_frame, FLAC__bool do_full_decode);
  96116. static FLAC__bool read_frame_header_(FLAC__StreamDecoder *decoder);
  96117. static FLAC__bool read_subframe_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, FLAC__bool do_full_decode);
  96118. static FLAC__bool read_subframe_constant_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, FLAC__bool do_full_decode);
  96119. static FLAC__bool read_subframe_fixed_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, const unsigned order, FLAC__bool do_full_decode);
  96120. static FLAC__bool read_subframe_lpc_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, const unsigned order, FLAC__bool do_full_decode);
  96121. static FLAC__bool read_subframe_verbatim_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, FLAC__bool do_full_decode);
  96122. 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);
  96123. static FLAC__bool read_zero_padding_(FLAC__StreamDecoder *decoder);
  96124. static FLAC__bool read_callback_(FLAC__byte buffer[], size_t *bytes, void *client_data);
  96125. #if FLAC__HAS_OGG
  96126. static FLAC__StreamDecoderReadStatus read_callback_ogg_aspect_(const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes);
  96127. static FLAC__OggDecoderAspectReadStatus read_callback_proxy_(const void *void_decoder, FLAC__byte buffer[], size_t *bytes, void *client_data);
  96128. #endif
  96129. static FLAC__StreamDecoderWriteStatus write_audio_frame_to_client_(FLAC__StreamDecoder *decoder, const FLAC__Frame *frame, const FLAC__int32 * const buffer[]);
  96130. static void send_error_to_client_(const FLAC__StreamDecoder *decoder, FLAC__StreamDecoderErrorStatus status);
  96131. static FLAC__bool seek_to_absolute_sample_(FLAC__StreamDecoder *decoder, FLAC__uint64 stream_length, FLAC__uint64 target_sample);
  96132. #if FLAC__HAS_OGG
  96133. static FLAC__bool seek_to_absolute_sample_ogg_(FLAC__StreamDecoder *decoder, FLAC__uint64 stream_length, FLAC__uint64 target_sample);
  96134. #endif
  96135. static FLAC__StreamDecoderReadStatus file_read_callback_dec (const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes, void *client_data);
  96136. static FLAC__StreamDecoderSeekStatus file_seek_callback_dec (const FLAC__StreamDecoder *decoder, FLAC__uint64 absolute_byte_offset, void *client_data);
  96137. static FLAC__StreamDecoderTellStatus file_tell_callback_dec (const FLAC__StreamDecoder *decoder, FLAC__uint64 *absolute_byte_offset, void *client_data);
  96138. static FLAC__StreamDecoderLengthStatus file_length_callback_(const FLAC__StreamDecoder *decoder, FLAC__uint64 *stream_length, void *client_data);
  96139. static FLAC__bool file_eof_callback_(const FLAC__StreamDecoder *decoder, void *client_data);
  96140. /***********************************************************************
  96141. *
  96142. * Private class data
  96143. *
  96144. ***********************************************************************/
  96145. typedef struct FLAC__StreamDecoderPrivate {
  96146. #if FLAC__HAS_OGG
  96147. FLAC__bool is_ogg;
  96148. #endif
  96149. FLAC__StreamDecoderReadCallback read_callback;
  96150. FLAC__StreamDecoderSeekCallback seek_callback;
  96151. FLAC__StreamDecoderTellCallback tell_callback;
  96152. FLAC__StreamDecoderLengthCallback length_callback;
  96153. FLAC__StreamDecoderEofCallback eof_callback;
  96154. FLAC__StreamDecoderWriteCallback write_callback;
  96155. FLAC__StreamDecoderMetadataCallback metadata_callback;
  96156. FLAC__StreamDecoderErrorCallback error_callback;
  96157. /* generic 32-bit datapath: */
  96158. 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[]);
  96159. /* generic 64-bit datapath: */
  96160. 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[]);
  96161. /* for use when the signal is <= 16 bits-per-sample, or <= 15 bits-per-sample on a side channel (which requires 1 extra bit): */
  96162. 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[]);
  96163. /* 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: */
  96164. 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[]);
  96165. FLAC__bool (*local_bitreader_read_rice_signed_block)(FLAC__BitReader *br, int* vals, unsigned nvals, unsigned parameter);
  96166. void *client_data;
  96167. FILE *file; /* only used if FLAC__stream_decoder_init_file()/FLAC__stream_decoder_init_file() called, else NULL */
  96168. FLAC__BitReader *input;
  96169. FLAC__int32 *output[FLAC__MAX_CHANNELS];
  96170. FLAC__int32 *residual[FLAC__MAX_CHANNELS]; /* WATCHOUT: these are the aligned pointers; the real pointers that should be free()'d are residual_unaligned[] below */
  96171. FLAC__EntropyCodingMethod_PartitionedRiceContents partitioned_rice_contents[FLAC__MAX_CHANNELS];
  96172. unsigned output_capacity, output_channels;
  96173. FLAC__uint32 fixed_block_size, next_fixed_block_size;
  96174. FLAC__uint64 samples_decoded;
  96175. FLAC__bool has_stream_info, has_seek_table;
  96176. FLAC__StreamMetadata stream_info;
  96177. FLAC__StreamMetadata seek_table;
  96178. FLAC__bool metadata_filter[128]; /* MAGIC number 128 == total number of metadata block types == 1 << 7 */
  96179. FLAC__byte *metadata_filter_ids;
  96180. size_t metadata_filter_ids_count, metadata_filter_ids_capacity; /* units for both are IDs, not bytes */
  96181. FLAC__Frame frame;
  96182. FLAC__bool cached; /* true if there is a byte in lookahead */
  96183. FLAC__CPUInfo cpuinfo;
  96184. FLAC__byte header_warmup[2]; /* contains the sync code and reserved bits */
  96185. FLAC__byte lookahead; /* temp storage when we need to look ahead one byte in the stream */
  96186. /* unaligned (original) pointers to allocated data */
  96187. FLAC__int32 *residual_unaligned[FLAC__MAX_CHANNELS];
  96188. 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 */
  96189. FLAC__bool internal_reset_hack; /* used only during init() so we can call reset to set up the decoder without rewinding the input */
  96190. FLAC__bool is_seeking;
  96191. FLAC__MD5Context md5context;
  96192. FLAC__byte computed_md5sum[16]; /* this is the sum we computed from the decoded data */
  96193. /* (the rest of these are only used for seeking) */
  96194. FLAC__Frame last_frame; /* holds the info of the last frame we seeked to */
  96195. FLAC__uint64 first_frame_offset; /* hint to the seek routine of where in the stream the first audio frame starts */
  96196. FLAC__uint64 target_sample;
  96197. unsigned unparseable_frame_count; /* used to tell whether we're decoding a future version of FLAC or just got a bad sync */
  96198. #if FLAC__HAS_OGG
  96199. FLAC__bool got_a_frame; /* hack needed in Ogg FLAC seek routine to check when process_single() actually writes a frame */
  96200. #endif
  96201. } FLAC__StreamDecoderPrivate;
  96202. /***********************************************************************
  96203. *
  96204. * Public static class data
  96205. *
  96206. ***********************************************************************/
  96207. FLAC_API const char * const FLAC__StreamDecoderStateString[] = {
  96208. "FLAC__STREAM_DECODER_SEARCH_FOR_METADATA",
  96209. "FLAC__STREAM_DECODER_READ_METADATA",
  96210. "FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC",
  96211. "FLAC__STREAM_DECODER_READ_FRAME",
  96212. "FLAC__STREAM_DECODER_END_OF_STREAM",
  96213. "FLAC__STREAM_DECODER_OGG_ERROR",
  96214. "FLAC__STREAM_DECODER_SEEK_ERROR",
  96215. "FLAC__STREAM_DECODER_ABORTED",
  96216. "FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR",
  96217. "FLAC__STREAM_DECODER_UNINITIALIZED"
  96218. };
  96219. FLAC_API const char * const FLAC__StreamDecoderInitStatusString[] = {
  96220. "FLAC__STREAM_DECODER_INIT_STATUS_OK",
  96221. "FLAC__STREAM_DECODER_INIT_STATUS_UNSUPPORTED_CONTAINER",
  96222. "FLAC__STREAM_DECODER_INIT_STATUS_INVALID_CALLBACKS",
  96223. "FLAC__STREAM_DECODER_INIT_STATUS_MEMORY_ALLOCATION_ERROR",
  96224. "FLAC__STREAM_DECODER_INIT_STATUS_ERROR_OPENING_FILE",
  96225. "FLAC__STREAM_DECODER_INIT_STATUS_ALREADY_INITIALIZED"
  96226. };
  96227. FLAC_API const char * const FLAC__StreamDecoderReadStatusString[] = {
  96228. "FLAC__STREAM_DECODER_READ_STATUS_CONTINUE",
  96229. "FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM",
  96230. "FLAC__STREAM_DECODER_READ_STATUS_ABORT"
  96231. };
  96232. FLAC_API const char * const FLAC__StreamDecoderSeekStatusString[] = {
  96233. "FLAC__STREAM_DECODER_SEEK_STATUS_OK",
  96234. "FLAC__STREAM_DECODER_SEEK_STATUS_ERROR",
  96235. "FLAC__STREAM_DECODER_SEEK_STATUS_UNSUPPORTED"
  96236. };
  96237. FLAC_API const char * const FLAC__StreamDecoderTellStatusString[] = {
  96238. "FLAC__STREAM_DECODER_TELL_STATUS_OK",
  96239. "FLAC__STREAM_DECODER_TELL_STATUS_ERROR",
  96240. "FLAC__STREAM_DECODER_TELL_STATUS_UNSUPPORTED"
  96241. };
  96242. FLAC_API const char * const FLAC__StreamDecoderLengthStatusString[] = {
  96243. "FLAC__STREAM_DECODER_LENGTH_STATUS_OK",
  96244. "FLAC__STREAM_DECODER_LENGTH_STATUS_ERROR",
  96245. "FLAC__STREAM_DECODER_LENGTH_STATUS_UNSUPPORTED"
  96246. };
  96247. FLAC_API const char * const FLAC__StreamDecoderWriteStatusString[] = {
  96248. "FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE",
  96249. "FLAC__STREAM_DECODER_WRITE_STATUS_ABORT"
  96250. };
  96251. FLAC_API const char * const FLAC__StreamDecoderErrorStatusString[] = {
  96252. "FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC",
  96253. "FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER",
  96254. "FLAC__STREAM_DECODER_ERROR_STATUS_FRAME_CRC_MISMATCH",
  96255. "FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM"
  96256. };
  96257. /***********************************************************************
  96258. *
  96259. * Class constructor/destructor
  96260. *
  96261. ***********************************************************************/
  96262. FLAC_API FLAC__StreamDecoder *FLAC__stream_decoder_new(void)
  96263. {
  96264. FLAC__StreamDecoder *decoder;
  96265. unsigned i;
  96266. FLAC__ASSERT(sizeof(int) >= 4); /* we want to die right away if this is not true */
  96267. decoder = (FLAC__StreamDecoder*)calloc(1, sizeof(FLAC__StreamDecoder));
  96268. if(decoder == 0) {
  96269. return 0;
  96270. }
  96271. decoder->protected_ = (FLAC__StreamDecoderProtected*)calloc(1, sizeof(FLAC__StreamDecoderProtected));
  96272. if(decoder->protected_ == 0) {
  96273. free(decoder);
  96274. return 0;
  96275. }
  96276. decoder->private_ = (FLAC__StreamDecoderPrivate*)calloc(1, sizeof(FLAC__StreamDecoderPrivate));
  96277. if(decoder->private_ == 0) {
  96278. free(decoder->protected_);
  96279. free(decoder);
  96280. return 0;
  96281. }
  96282. decoder->private_->input = FLAC__bitreader_new();
  96283. if(decoder->private_->input == 0) {
  96284. free(decoder->private_);
  96285. free(decoder->protected_);
  96286. free(decoder);
  96287. return 0;
  96288. }
  96289. decoder->private_->metadata_filter_ids_capacity = 16;
  96290. if(0 == (decoder->private_->metadata_filter_ids = (FLAC__byte*)malloc((FLAC__STREAM_METADATA_APPLICATION_ID_LEN/8) * decoder->private_->metadata_filter_ids_capacity))) {
  96291. FLAC__bitreader_delete(decoder->private_->input);
  96292. free(decoder->private_);
  96293. free(decoder->protected_);
  96294. free(decoder);
  96295. return 0;
  96296. }
  96297. for(i = 0; i < FLAC__MAX_CHANNELS; i++) {
  96298. decoder->private_->output[i] = 0;
  96299. decoder->private_->residual_unaligned[i] = decoder->private_->residual[i] = 0;
  96300. }
  96301. decoder->private_->output_capacity = 0;
  96302. decoder->private_->output_channels = 0;
  96303. decoder->private_->has_seek_table = false;
  96304. for(i = 0; i < FLAC__MAX_CHANNELS; i++)
  96305. FLAC__format_entropy_coding_method_partitioned_rice_contents_init(&decoder->private_->partitioned_rice_contents[i]);
  96306. decoder->private_->file = 0;
  96307. set_defaults_dec(decoder);
  96308. decoder->protected_->state = FLAC__STREAM_DECODER_UNINITIALIZED;
  96309. return decoder;
  96310. }
  96311. FLAC_API void FLAC__stream_decoder_delete(FLAC__StreamDecoder *decoder)
  96312. {
  96313. unsigned i;
  96314. FLAC__ASSERT(0 != decoder);
  96315. FLAC__ASSERT(0 != decoder->protected_);
  96316. FLAC__ASSERT(0 != decoder->private_);
  96317. FLAC__ASSERT(0 != decoder->private_->input);
  96318. (void)FLAC__stream_decoder_finish(decoder);
  96319. if(0 != decoder->private_->metadata_filter_ids)
  96320. free(decoder->private_->metadata_filter_ids);
  96321. FLAC__bitreader_delete(decoder->private_->input);
  96322. for(i = 0; i < FLAC__MAX_CHANNELS; i++)
  96323. FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(&decoder->private_->partitioned_rice_contents[i]);
  96324. free(decoder->private_);
  96325. free(decoder->protected_);
  96326. free(decoder);
  96327. }
  96328. /***********************************************************************
  96329. *
  96330. * Public class methods
  96331. *
  96332. ***********************************************************************/
  96333. static FLAC__StreamDecoderInitStatus init_stream_internal_dec(
  96334. FLAC__StreamDecoder *decoder,
  96335. FLAC__StreamDecoderReadCallback read_callback,
  96336. FLAC__StreamDecoderSeekCallback seek_callback,
  96337. FLAC__StreamDecoderTellCallback tell_callback,
  96338. FLAC__StreamDecoderLengthCallback length_callback,
  96339. FLAC__StreamDecoderEofCallback eof_callback,
  96340. FLAC__StreamDecoderWriteCallback write_callback,
  96341. FLAC__StreamDecoderMetadataCallback metadata_callback,
  96342. FLAC__StreamDecoderErrorCallback error_callback,
  96343. void *client_data,
  96344. FLAC__bool is_ogg
  96345. )
  96346. {
  96347. FLAC__ASSERT(0 != decoder);
  96348. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  96349. return FLAC__STREAM_DECODER_INIT_STATUS_ALREADY_INITIALIZED;
  96350. #if !FLAC__HAS_OGG
  96351. if(is_ogg)
  96352. return FLAC__STREAM_DECODER_INIT_STATUS_UNSUPPORTED_CONTAINER;
  96353. #endif
  96354. if(
  96355. 0 == read_callback ||
  96356. 0 == write_callback ||
  96357. 0 == error_callback ||
  96358. (seek_callback && (0 == tell_callback || 0 == length_callback || 0 == eof_callback))
  96359. )
  96360. return FLAC__STREAM_DECODER_INIT_STATUS_INVALID_CALLBACKS;
  96361. #if FLAC__HAS_OGG
  96362. decoder->private_->is_ogg = is_ogg;
  96363. if(is_ogg && !FLAC__ogg_decoder_aspect_init(&decoder->protected_->ogg_decoder_aspect))
  96364. return decoder->protected_->state = FLAC__STREAM_DECODER_OGG_ERROR;
  96365. #endif
  96366. /*
  96367. * get the CPU info and set the function pointers
  96368. */
  96369. FLAC__cpu_info(&decoder->private_->cpuinfo);
  96370. /* first default to the non-asm routines */
  96371. decoder->private_->local_lpc_restore_signal = FLAC__lpc_restore_signal;
  96372. decoder->private_->local_lpc_restore_signal_64bit = FLAC__lpc_restore_signal_wide;
  96373. decoder->private_->local_lpc_restore_signal_16bit = FLAC__lpc_restore_signal;
  96374. decoder->private_->local_lpc_restore_signal_16bit_order8 = FLAC__lpc_restore_signal;
  96375. decoder->private_->local_bitreader_read_rice_signed_block = FLAC__bitreader_read_rice_signed_block;
  96376. /* now override with asm where appropriate */
  96377. #ifndef FLAC__NO_ASM
  96378. if(decoder->private_->cpuinfo.use_asm) {
  96379. #ifdef FLAC__CPU_IA32
  96380. FLAC__ASSERT(decoder->private_->cpuinfo.type == FLAC__CPUINFO_TYPE_IA32);
  96381. #ifdef FLAC__HAS_NASM
  96382. #if 1 /*@@@@@@ OPT: not clearly faster, needs more testing */
  96383. if(decoder->private_->cpuinfo.data.ia32.bswap)
  96384. decoder->private_->local_bitreader_read_rice_signed_block = FLAC__bitreader_read_rice_signed_block_asm_ia32_bswap;
  96385. #endif
  96386. if(decoder->private_->cpuinfo.data.ia32.mmx) {
  96387. decoder->private_->local_lpc_restore_signal = FLAC__lpc_restore_signal_asm_ia32;
  96388. decoder->private_->local_lpc_restore_signal_16bit = FLAC__lpc_restore_signal_asm_ia32_mmx;
  96389. decoder->private_->local_lpc_restore_signal_16bit_order8 = FLAC__lpc_restore_signal_asm_ia32_mmx;
  96390. }
  96391. else {
  96392. decoder->private_->local_lpc_restore_signal = FLAC__lpc_restore_signal_asm_ia32;
  96393. decoder->private_->local_lpc_restore_signal_16bit = FLAC__lpc_restore_signal_asm_ia32;
  96394. decoder->private_->local_lpc_restore_signal_16bit_order8 = FLAC__lpc_restore_signal_asm_ia32;
  96395. }
  96396. #endif
  96397. #elif defined FLAC__CPU_PPC
  96398. FLAC__ASSERT(decoder->private_->cpuinfo.type == FLAC__CPUINFO_TYPE_PPC);
  96399. if(decoder->private_->cpuinfo.data.ppc.altivec) {
  96400. decoder->private_->local_lpc_restore_signal_16bit = FLAC__lpc_restore_signal_asm_ppc_altivec_16;
  96401. decoder->private_->local_lpc_restore_signal_16bit_order8 = FLAC__lpc_restore_signal_asm_ppc_altivec_16_order8;
  96402. }
  96403. #endif
  96404. }
  96405. #endif
  96406. /* from here on, errors are fatal */
  96407. if(!FLAC__bitreader_init(decoder->private_->input, decoder->private_->cpuinfo, read_callback_, decoder)) {
  96408. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  96409. return FLAC__STREAM_DECODER_INIT_STATUS_MEMORY_ALLOCATION_ERROR;
  96410. }
  96411. decoder->private_->read_callback = read_callback;
  96412. decoder->private_->seek_callback = seek_callback;
  96413. decoder->private_->tell_callback = tell_callback;
  96414. decoder->private_->length_callback = length_callback;
  96415. decoder->private_->eof_callback = eof_callback;
  96416. decoder->private_->write_callback = write_callback;
  96417. decoder->private_->metadata_callback = metadata_callback;
  96418. decoder->private_->error_callback = error_callback;
  96419. decoder->private_->client_data = client_data;
  96420. decoder->private_->fixed_block_size = decoder->private_->next_fixed_block_size = 0;
  96421. decoder->private_->samples_decoded = 0;
  96422. decoder->private_->has_stream_info = false;
  96423. decoder->private_->cached = false;
  96424. decoder->private_->do_md5_checking = decoder->protected_->md5_checking;
  96425. decoder->private_->is_seeking = false;
  96426. decoder->private_->internal_reset_hack = true; /* so the following reset does not try to rewind the input */
  96427. if(!FLAC__stream_decoder_reset(decoder)) {
  96428. /* above call sets the state for us */
  96429. return FLAC__STREAM_DECODER_INIT_STATUS_MEMORY_ALLOCATION_ERROR;
  96430. }
  96431. return FLAC__STREAM_DECODER_INIT_STATUS_OK;
  96432. }
  96433. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_stream(
  96434. FLAC__StreamDecoder *decoder,
  96435. FLAC__StreamDecoderReadCallback read_callback,
  96436. FLAC__StreamDecoderSeekCallback seek_callback,
  96437. FLAC__StreamDecoderTellCallback tell_callback,
  96438. FLAC__StreamDecoderLengthCallback length_callback,
  96439. FLAC__StreamDecoderEofCallback eof_callback,
  96440. FLAC__StreamDecoderWriteCallback write_callback,
  96441. FLAC__StreamDecoderMetadataCallback metadata_callback,
  96442. FLAC__StreamDecoderErrorCallback error_callback,
  96443. void *client_data
  96444. )
  96445. {
  96446. return init_stream_internal_dec(
  96447. decoder,
  96448. read_callback,
  96449. seek_callback,
  96450. tell_callback,
  96451. length_callback,
  96452. eof_callback,
  96453. write_callback,
  96454. metadata_callback,
  96455. error_callback,
  96456. client_data,
  96457. /*is_ogg=*/false
  96458. );
  96459. }
  96460. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_ogg_stream(
  96461. FLAC__StreamDecoder *decoder,
  96462. FLAC__StreamDecoderReadCallback read_callback,
  96463. FLAC__StreamDecoderSeekCallback seek_callback,
  96464. FLAC__StreamDecoderTellCallback tell_callback,
  96465. FLAC__StreamDecoderLengthCallback length_callback,
  96466. FLAC__StreamDecoderEofCallback eof_callback,
  96467. FLAC__StreamDecoderWriteCallback write_callback,
  96468. FLAC__StreamDecoderMetadataCallback metadata_callback,
  96469. FLAC__StreamDecoderErrorCallback error_callback,
  96470. void *client_data
  96471. )
  96472. {
  96473. return init_stream_internal_dec(
  96474. decoder,
  96475. read_callback,
  96476. seek_callback,
  96477. tell_callback,
  96478. length_callback,
  96479. eof_callback,
  96480. write_callback,
  96481. metadata_callback,
  96482. error_callback,
  96483. client_data,
  96484. /*is_ogg=*/true
  96485. );
  96486. }
  96487. static FLAC__StreamDecoderInitStatus init_FILE_internal_(
  96488. FLAC__StreamDecoder *decoder,
  96489. FILE *file,
  96490. FLAC__StreamDecoderWriteCallback write_callback,
  96491. FLAC__StreamDecoderMetadataCallback metadata_callback,
  96492. FLAC__StreamDecoderErrorCallback error_callback,
  96493. void *client_data,
  96494. FLAC__bool is_ogg
  96495. )
  96496. {
  96497. FLAC__ASSERT(0 != decoder);
  96498. FLAC__ASSERT(0 != file);
  96499. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  96500. return (FLAC__StreamDecoderInitStatus) (decoder->protected_->state = (FLAC__StreamDecoderState) FLAC__STREAM_DECODER_INIT_STATUS_ALREADY_INITIALIZED);
  96501. if(0 == write_callback || 0 == error_callback)
  96502. return (FLAC__StreamDecoderInitStatus) (decoder->protected_->state = (FLAC__StreamDecoderState) FLAC__STREAM_DECODER_INIT_STATUS_INVALID_CALLBACKS);
  96503. /*
  96504. * To make sure that our file does not go unclosed after an error, we
  96505. * must assign the FILE pointer before any further error can occur in
  96506. * this routine.
  96507. */
  96508. if(file == stdin)
  96509. file = get_binary_stdin_(); /* just to be safe */
  96510. decoder->private_->file = file;
  96511. return init_stream_internal_dec(
  96512. decoder,
  96513. file_read_callback_dec,
  96514. decoder->private_->file == stdin? 0: file_seek_callback_dec,
  96515. decoder->private_->file == stdin? 0: file_tell_callback_dec,
  96516. decoder->private_->file == stdin? 0: file_length_callback_,
  96517. file_eof_callback_,
  96518. write_callback,
  96519. metadata_callback,
  96520. error_callback,
  96521. client_data,
  96522. is_ogg
  96523. );
  96524. }
  96525. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_FILE(
  96526. FLAC__StreamDecoder *decoder,
  96527. FILE *file,
  96528. FLAC__StreamDecoderWriteCallback write_callback,
  96529. FLAC__StreamDecoderMetadataCallback metadata_callback,
  96530. FLAC__StreamDecoderErrorCallback error_callback,
  96531. void *client_data
  96532. )
  96533. {
  96534. return init_FILE_internal_(decoder, file, write_callback, metadata_callback, error_callback, client_data, /*is_ogg=*/false);
  96535. }
  96536. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_ogg_FILE(
  96537. FLAC__StreamDecoder *decoder,
  96538. FILE *file,
  96539. FLAC__StreamDecoderWriteCallback write_callback,
  96540. FLAC__StreamDecoderMetadataCallback metadata_callback,
  96541. FLAC__StreamDecoderErrorCallback error_callback,
  96542. void *client_data
  96543. )
  96544. {
  96545. return init_FILE_internal_(decoder, file, write_callback, metadata_callback, error_callback, client_data, /*is_ogg=*/true);
  96546. }
  96547. static FLAC__StreamDecoderInitStatus init_file_internal_(
  96548. FLAC__StreamDecoder *decoder,
  96549. const char *filename,
  96550. FLAC__StreamDecoderWriteCallback write_callback,
  96551. FLAC__StreamDecoderMetadataCallback metadata_callback,
  96552. FLAC__StreamDecoderErrorCallback error_callback,
  96553. void *client_data,
  96554. FLAC__bool is_ogg
  96555. )
  96556. {
  96557. FILE *file;
  96558. FLAC__ASSERT(0 != decoder);
  96559. /*
  96560. * To make sure that our file does not go unclosed after an error, we
  96561. * have to do the same entrance checks here that are later performed
  96562. * in FLAC__stream_decoder_init_FILE() before the FILE* is assigned.
  96563. */
  96564. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  96565. return (FLAC__StreamDecoderInitStatus) (decoder->protected_->state = (FLAC__StreamDecoderState) FLAC__STREAM_DECODER_INIT_STATUS_ALREADY_INITIALIZED);
  96566. if(0 == write_callback || 0 == error_callback)
  96567. return (FLAC__StreamDecoderInitStatus) (decoder->protected_->state = (FLAC__StreamDecoderState) FLAC__STREAM_DECODER_INIT_STATUS_INVALID_CALLBACKS);
  96568. file = filename? fopen(filename, "rb") : stdin;
  96569. if(0 == file)
  96570. return FLAC__STREAM_DECODER_INIT_STATUS_ERROR_OPENING_FILE;
  96571. return init_FILE_internal_(decoder, file, write_callback, metadata_callback, error_callback, client_data, is_ogg);
  96572. }
  96573. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_file(
  96574. FLAC__StreamDecoder *decoder,
  96575. const char *filename,
  96576. FLAC__StreamDecoderWriteCallback write_callback,
  96577. FLAC__StreamDecoderMetadataCallback metadata_callback,
  96578. FLAC__StreamDecoderErrorCallback error_callback,
  96579. void *client_data
  96580. )
  96581. {
  96582. return init_file_internal_(decoder, filename, write_callback, metadata_callback, error_callback, client_data, /*is_ogg=*/false);
  96583. }
  96584. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_ogg_file(
  96585. FLAC__StreamDecoder *decoder,
  96586. const char *filename,
  96587. FLAC__StreamDecoderWriteCallback write_callback,
  96588. FLAC__StreamDecoderMetadataCallback metadata_callback,
  96589. FLAC__StreamDecoderErrorCallback error_callback,
  96590. void *client_data
  96591. )
  96592. {
  96593. return init_file_internal_(decoder, filename, write_callback, metadata_callback, error_callback, client_data, /*is_ogg=*/true);
  96594. }
  96595. FLAC_API FLAC__bool FLAC__stream_decoder_finish(FLAC__StreamDecoder *decoder)
  96596. {
  96597. FLAC__bool md5_failed = false;
  96598. unsigned i;
  96599. FLAC__ASSERT(0 != decoder);
  96600. FLAC__ASSERT(0 != decoder->private_);
  96601. FLAC__ASSERT(0 != decoder->protected_);
  96602. if(decoder->protected_->state == FLAC__STREAM_DECODER_UNINITIALIZED)
  96603. return true;
  96604. /* see the comment in FLAC__seekable_stream_decoder_reset() as to why we
  96605. * always call FLAC__MD5Final()
  96606. */
  96607. FLAC__MD5Final(decoder->private_->computed_md5sum, &decoder->private_->md5context);
  96608. if(decoder->private_->has_seek_table && 0 != decoder->private_->seek_table.data.seek_table.points) {
  96609. free(decoder->private_->seek_table.data.seek_table.points);
  96610. decoder->private_->seek_table.data.seek_table.points = 0;
  96611. decoder->private_->has_seek_table = false;
  96612. }
  96613. FLAC__bitreader_free(decoder->private_->input);
  96614. for(i = 0; i < FLAC__MAX_CHANNELS; i++) {
  96615. /* WATCHOUT:
  96616. * FLAC__lpc_restore_signal_asm_ia32_mmx() requires that the
  96617. * output arrays have a buffer of up to 3 zeroes in front
  96618. * (at negative indices) for alignment purposes; we use 4
  96619. * to keep the data well-aligned.
  96620. */
  96621. if(0 != decoder->private_->output[i]) {
  96622. free(decoder->private_->output[i]-4);
  96623. decoder->private_->output[i] = 0;
  96624. }
  96625. if(0 != decoder->private_->residual_unaligned[i]) {
  96626. free(decoder->private_->residual_unaligned[i]);
  96627. decoder->private_->residual_unaligned[i] = decoder->private_->residual[i] = 0;
  96628. }
  96629. }
  96630. decoder->private_->output_capacity = 0;
  96631. decoder->private_->output_channels = 0;
  96632. #if FLAC__HAS_OGG
  96633. if(decoder->private_->is_ogg)
  96634. FLAC__ogg_decoder_aspect_finish(&decoder->protected_->ogg_decoder_aspect);
  96635. #endif
  96636. if(0 != decoder->private_->file) {
  96637. if(decoder->private_->file != stdin)
  96638. fclose(decoder->private_->file);
  96639. decoder->private_->file = 0;
  96640. }
  96641. if(decoder->private_->do_md5_checking) {
  96642. if(memcmp(decoder->private_->stream_info.data.stream_info.md5sum, decoder->private_->computed_md5sum, 16))
  96643. md5_failed = true;
  96644. }
  96645. decoder->private_->is_seeking = false;
  96646. set_defaults_dec(decoder);
  96647. decoder->protected_->state = FLAC__STREAM_DECODER_UNINITIALIZED;
  96648. return !md5_failed;
  96649. }
  96650. FLAC_API FLAC__bool FLAC__stream_decoder_set_ogg_serial_number(FLAC__StreamDecoder *decoder, long value)
  96651. {
  96652. FLAC__ASSERT(0 != decoder);
  96653. FLAC__ASSERT(0 != decoder->private_);
  96654. FLAC__ASSERT(0 != decoder->protected_);
  96655. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  96656. return false;
  96657. #if FLAC__HAS_OGG
  96658. /* can't check decoder->private_->is_ogg since that's not set until init time */
  96659. FLAC__ogg_decoder_aspect_set_serial_number(&decoder->protected_->ogg_decoder_aspect, value);
  96660. return true;
  96661. #else
  96662. (void)value;
  96663. return false;
  96664. #endif
  96665. }
  96666. FLAC_API FLAC__bool FLAC__stream_decoder_set_md5_checking(FLAC__StreamDecoder *decoder, FLAC__bool value)
  96667. {
  96668. FLAC__ASSERT(0 != decoder);
  96669. FLAC__ASSERT(0 != decoder->protected_);
  96670. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  96671. return false;
  96672. decoder->protected_->md5_checking = value;
  96673. return true;
  96674. }
  96675. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_respond(FLAC__StreamDecoder *decoder, FLAC__MetadataType type)
  96676. {
  96677. FLAC__ASSERT(0 != decoder);
  96678. FLAC__ASSERT(0 != decoder->private_);
  96679. FLAC__ASSERT(0 != decoder->protected_);
  96680. FLAC__ASSERT((unsigned)type <= FLAC__MAX_METADATA_TYPE_CODE);
  96681. /* double protection */
  96682. if((unsigned)type > FLAC__MAX_METADATA_TYPE_CODE)
  96683. return false;
  96684. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  96685. return false;
  96686. decoder->private_->metadata_filter[type] = true;
  96687. if(type == FLAC__METADATA_TYPE_APPLICATION)
  96688. decoder->private_->metadata_filter_ids_count = 0;
  96689. return true;
  96690. }
  96691. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_respond_application(FLAC__StreamDecoder *decoder, const FLAC__byte id[4])
  96692. {
  96693. FLAC__ASSERT(0 != decoder);
  96694. FLAC__ASSERT(0 != decoder->private_);
  96695. FLAC__ASSERT(0 != decoder->protected_);
  96696. FLAC__ASSERT(0 != id);
  96697. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  96698. return false;
  96699. if(decoder->private_->metadata_filter[FLAC__METADATA_TYPE_APPLICATION])
  96700. return true;
  96701. FLAC__ASSERT(0 != decoder->private_->metadata_filter_ids);
  96702. if(decoder->private_->metadata_filter_ids_count == decoder->private_->metadata_filter_ids_capacity) {
  96703. 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))) {
  96704. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  96705. return false;
  96706. }
  96707. decoder->private_->metadata_filter_ids_capacity *= 2;
  96708. }
  96709. 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));
  96710. decoder->private_->metadata_filter_ids_count++;
  96711. return true;
  96712. }
  96713. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_respond_all(FLAC__StreamDecoder *decoder)
  96714. {
  96715. unsigned i;
  96716. FLAC__ASSERT(0 != decoder);
  96717. FLAC__ASSERT(0 != decoder->private_);
  96718. FLAC__ASSERT(0 != decoder->protected_);
  96719. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  96720. return false;
  96721. for(i = 0; i < sizeof(decoder->private_->metadata_filter) / sizeof(decoder->private_->metadata_filter[0]); i++)
  96722. decoder->private_->metadata_filter[i] = true;
  96723. decoder->private_->metadata_filter_ids_count = 0;
  96724. return true;
  96725. }
  96726. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_ignore(FLAC__StreamDecoder *decoder, FLAC__MetadataType type)
  96727. {
  96728. FLAC__ASSERT(0 != decoder);
  96729. FLAC__ASSERT(0 != decoder->private_);
  96730. FLAC__ASSERT(0 != decoder->protected_);
  96731. FLAC__ASSERT((unsigned)type <= FLAC__MAX_METADATA_TYPE_CODE);
  96732. /* double protection */
  96733. if((unsigned)type > FLAC__MAX_METADATA_TYPE_CODE)
  96734. return false;
  96735. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  96736. return false;
  96737. decoder->private_->metadata_filter[type] = false;
  96738. if(type == FLAC__METADATA_TYPE_APPLICATION)
  96739. decoder->private_->metadata_filter_ids_count = 0;
  96740. return true;
  96741. }
  96742. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_ignore_application(FLAC__StreamDecoder *decoder, const FLAC__byte id[4])
  96743. {
  96744. FLAC__ASSERT(0 != decoder);
  96745. FLAC__ASSERT(0 != decoder->private_);
  96746. FLAC__ASSERT(0 != decoder->protected_);
  96747. FLAC__ASSERT(0 != id);
  96748. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  96749. return false;
  96750. if(!decoder->private_->metadata_filter[FLAC__METADATA_TYPE_APPLICATION])
  96751. return true;
  96752. FLAC__ASSERT(0 != decoder->private_->metadata_filter_ids);
  96753. if(decoder->private_->metadata_filter_ids_count == decoder->private_->metadata_filter_ids_capacity) {
  96754. 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))) {
  96755. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  96756. return false;
  96757. }
  96758. decoder->private_->metadata_filter_ids_capacity *= 2;
  96759. }
  96760. 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));
  96761. decoder->private_->metadata_filter_ids_count++;
  96762. return true;
  96763. }
  96764. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_ignore_all(FLAC__StreamDecoder *decoder)
  96765. {
  96766. FLAC__ASSERT(0 != decoder);
  96767. FLAC__ASSERT(0 != decoder->private_);
  96768. FLAC__ASSERT(0 != decoder->protected_);
  96769. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  96770. return false;
  96771. memset(decoder->private_->metadata_filter, 0, sizeof(decoder->private_->metadata_filter));
  96772. decoder->private_->metadata_filter_ids_count = 0;
  96773. return true;
  96774. }
  96775. FLAC_API FLAC__StreamDecoderState FLAC__stream_decoder_get_state(const FLAC__StreamDecoder *decoder)
  96776. {
  96777. FLAC__ASSERT(0 != decoder);
  96778. FLAC__ASSERT(0 != decoder->protected_);
  96779. return decoder->protected_->state;
  96780. }
  96781. FLAC_API const char *FLAC__stream_decoder_get_resolved_state_string(const FLAC__StreamDecoder *decoder)
  96782. {
  96783. return FLAC__StreamDecoderStateString[decoder->protected_->state];
  96784. }
  96785. FLAC_API FLAC__bool FLAC__stream_decoder_get_md5_checking(const FLAC__StreamDecoder *decoder)
  96786. {
  96787. FLAC__ASSERT(0 != decoder);
  96788. FLAC__ASSERT(0 != decoder->protected_);
  96789. return decoder->protected_->md5_checking;
  96790. }
  96791. FLAC_API FLAC__uint64 FLAC__stream_decoder_get_total_samples(const FLAC__StreamDecoder *decoder)
  96792. {
  96793. FLAC__ASSERT(0 != decoder);
  96794. FLAC__ASSERT(0 != decoder->protected_);
  96795. return decoder->private_->has_stream_info? decoder->private_->stream_info.data.stream_info.total_samples : 0;
  96796. }
  96797. FLAC_API unsigned FLAC__stream_decoder_get_channels(const FLAC__StreamDecoder *decoder)
  96798. {
  96799. FLAC__ASSERT(0 != decoder);
  96800. FLAC__ASSERT(0 != decoder->protected_);
  96801. return decoder->protected_->channels;
  96802. }
  96803. FLAC_API FLAC__ChannelAssignment FLAC__stream_decoder_get_channel_assignment(const FLAC__StreamDecoder *decoder)
  96804. {
  96805. FLAC__ASSERT(0 != decoder);
  96806. FLAC__ASSERT(0 != decoder->protected_);
  96807. return decoder->protected_->channel_assignment;
  96808. }
  96809. FLAC_API unsigned FLAC__stream_decoder_get_bits_per_sample(const FLAC__StreamDecoder *decoder)
  96810. {
  96811. FLAC__ASSERT(0 != decoder);
  96812. FLAC__ASSERT(0 != decoder->protected_);
  96813. return decoder->protected_->bits_per_sample;
  96814. }
  96815. FLAC_API unsigned FLAC__stream_decoder_get_sample_rate(const FLAC__StreamDecoder *decoder)
  96816. {
  96817. FLAC__ASSERT(0 != decoder);
  96818. FLAC__ASSERT(0 != decoder->protected_);
  96819. return decoder->protected_->sample_rate;
  96820. }
  96821. FLAC_API unsigned FLAC__stream_decoder_get_blocksize(const FLAC__StreamDecoder *decoder)
  96822. {
  96823. FLAC__ASSERT(0 != decoder);
  96824. FLAC__ASSERT(0 != decoder->protected_);
  96825. return decoder->protected_->blocksize;
  96826. }
  96827. FLAC_API FLAC__bool FLAC__stream_decoder_get_decode_position(const FLAC__StreamDecoder *decoder, FLAC__uint64 *position)
  96828. {
  96829. FLAC__ASSERT(0 != decoder);
  96830. FLAC__ASSERT(0 != decoder->private_);
  96831. FLAC__ASSERT(0 != position);
  96832. #if FLAC__HAS_OGG
  96833. if(decoder->private_->is_ogg)
  96834. return false;
  96835. #endif
  96836. if(0 == decoder->private_->tell_callback)
  96837. return false;
  96838. if(decoder->private_->tell_callback(decoder, position, decoder->private_->client_data) != FLAC__STREAM_DECODER_TELL_STATUS_OK)
  96839. return false;
  96840. /* should never happen since all FLAC frames and metadata blocks are byte aligned, but check just in case */
  96841. if(!FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input))
  96842. return false;
  96843. FLAC__ASSERT(*position >= FLAC__stream_decoder_get_input_bytes_unconsumed(decoder));
  96844. *position -= FLAC__stream_decoder_get_input_bytes_unconsumed(decoder);
  96845. return true;
  96846. }
  96847. FLAC_API FLAC__bool FLAC__stream_decoder_flush(FLAC__StreamDecoder *decoder)
  96848. {
  96849. FLAC__ASSERT(0 != decoder);
  96850. FLAC__ASSERT(0 != decoder->private_);
  96851. FLAC__ASSERT(0 != decoder->protected_);
  96852. decoder->private_->samples_decoded = 0;
  96853. decoder->private_->do_md5_checking = false;
  96854. #if FLAC__HAS_OGG
  96855. if(decoder->private_->is_ogg)
  96856. FLAC__ogg_decoder_aspect_flush(&decoder->protected_->ogg_decoder_aspect);
  96857. #endif
  96858. if(!FLAC__bitreader_clear(decoder->private_->input)) {
  96859. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  96860. return false;
  96861. }
  96862. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  96863. return true;
  96864. }
  96865. FLAC_API FLAC__bool FLAC__stream_decoder_reset(FLAC__StreamDecoder *decoder)
  96866. {
  96867. FLAC__ASSERT(0 != decoder);
  96868. FLAC__ASSERT(0 != decoder->private_);
  96869. FLAC__ASSERT(0 != decoder->protected_);
  96870. if(!FLAC__stream_decoder_flush(decoder)) {
  96871. /* above call sets the state for us */
  96872. return false;
  96873. }
  96874. #if FLAC__HAS_OGG
  96875. /*@@@ could go in !internal_reset_hack block below */
  96876. if(decoder->private_->is_ogg)
  96877. FLAC__ogg_decoder_aspect_reset(&decoder->protected_->ogg_decoder_aspect);
  96878. #endif
  96879. /* Rewind if necessary. If FLAC__stream_decoder_init() is calling us,
  96880. * (internal_reset_hack) don't try to rewind since we are already at
  96881. * the beginning of the stream and don't want to fail if the input is
  96882. * not seekable.
  96883. */
  96884. if(!decoder->private_->internal_reset_hack) {
  96885. if(decoder->private_->file == stdin)
  96886. return false; /* can't rewind stdin, reset fails */
  96887. if(decoder->private_->seek_callback && decoder->private_->seek_callback(decoder, 0, decoder->private_->client_data) == FLAC__STREAM_DECODER_SEEK_STATUS_ERROR)
  96888. return false; /* seekable and seek fails, reset fails */
  96889. }
  96890. else
  96891. decoder->private_->internal_reset_hack = false;
  96892. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_METADATA;
  96893. decoder->private_->has_stream_info = false;
  96894. if(decoder->private_->has_seek_table && 0 != decoder->private_->seek_table.data.seek_table.points) {
  96895. free(decoder->private_->seek_table.data.seek_table.points);
  96896. decoder->private_->seek_table.data.seek_table.points = 0;
  96897. decoder->private_->has_seek_table = false;
  96898. }
  96899. decoder->private_->do_md5_checking = decoder->protected_->md5_checking;
  96900. /*
  96901. * This goes in reset() and not flush() because according to the spec, a
  96902. * fixed-blocksize stream must stay that way through the whole stream.
  96903. */
  96904. decoder->private_->fixed_block_size = decoder->private_->next_fixed_block_size = 0;
  96905. /* We initialize the FLAC__MD5Context even though we may never use it. This
  96906. * is because md5 checking may be turned on to start and then turned off if
  96907. * a seek occurs. So we init the context here and finalize it in
  96908. * FLAC__stream_decoder_finish() to make sure things are always cleaned up
  96909. * properly.
  96910. */
  96911. FLAC__MD5Init(&decoder->private_->md5context);
  96912. decoder->private_->first_frame_offset = 0;
  96913. decoder->private_->unparseable_frame_count = 0;
  96914. return true;
  96915. }
  96916. FLAC_API FLAC__bool FLAC__stream_decoder_process_single(FLAC__StreamDecoder *decoder)
  96917. {
  96918. FLAC__bool got_a_frame;
  96919. FLAC__ASSERT(0 != decoder);
  96920. FLAC__ASSERT(0 != decoder->protected_);
  96921. while(1) {
  96922. switch(decoder->protected_->state) {
  96923. case FLAC__STREAM_DECODER_SEARCH_FOR_METADATA:
  96924. if(!find_metadata_(decoder))
  96925. return false; /* above function sets the status for us */
  96926. break;
  96927. case FLAC__STREAM_DECODER_READ_METADATA:
  96928. if(!read_metadata_(decoder))
  96929. return false; /* above function sets the status for us */
  96930. else
  96931. return true;
  96932. case FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC:
  96933. if(!frame_sync_(decoder))
  96934. return true; /* above function sets the status for us */
  96935. break;
  96936. case FLAC__STREAM_DECODER_READ_FRAME:
  96937. if(!read_frame_(decoder, &got_a_frame, /*do_full_decode=*/true))
  96938. return false; /* above function sets the status for us */
  96939. if(got_a_frame)
  96940. return true; /* above function sets the status for us */
  96941. break;
  96942. case FLAC__STREAM_DECODER_END_OF_STREAM:
  96943. case FLAC__STREAM_DECODER_ABORTED:
  96944. return true;
  96945. default:
  96946. FLAC__ASSERT(0);
  96947. return false;
  96948. }
  96949. }
  96950. }
  96951. FLAC_API FLAC__bool FLAC__stream_decoder_process_until_end_of_metadata(FLAC__StreamDecoder *decoder)
  96952. {
  96953. FLAC__ASSERT(0 != decoder);
  96954. FLAC__ASSERT(0 != decoder->protected_);
  96955. while(1) {
  96956. switch(decoder->protected_->state) {
  96957. case FLAC__STREAM_DECODER_SEARCH_FOR_METADATA:
  96958. if(!find_metadata_(decoder))
  96959. return false; /* above function sets the status for us */
  96960. break;
  96961. case FLAC__STREAM_DECODER_READ_METADATA:
  96962. if(!read_metadata_(decoder))
  96963. return false; /* above function sets the status for us */
  96964. break;
  96965. case FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC:
  96966. case FLAC__STREAM_DECODER_READ_FRAME:
  96967. case FLAC__STREAM_DECODER_END_OF_STREAM:
  96968. case FLAC__STREAM_DECODER_ABORTED:
  96969. return true;
  96970. default:
  96971. FLAC__ASSERT(0);
  96972. return false;
  96973. }
  96974. }
  96975. }
  96976. FLAC_API FLAC__bool FLAC__stream_decoder_process_until_end_of_stream(FLAC__StreamDecoder *decoder)
  96977. {
  96978. FLAC__bool dummy;
  96979. FLAC__ASSERT(0 != decoder);
  96980. FLAC__ASSERT(0 != decoder->protected_);
  96981. while(1) {
  96982. switch(decoder->protected_->state) {
  96983. case FLAC__STREAM_DECODER_SEARCH_FOR_METADATA:
  96984. if(!find_metadata_(decoder))
  96985. return false; /* above function sets the status for us */
  96986. break;
  96987. case FLAC__STREAM_DECODER_READ_METADATA:
  96988. if(!read_metadata_(decoder))
  96989. return false; /* above function sets the status for us */
  96990. break;
  96991. case FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC:
  96992. if(!frame_sync_(decoder))
  96993. return true; /* above function sets the status for us */
  96994. break;
  96995. case FLAC__STREAM_DECODER_READ_FRAME:
  96996. if(!read_frame_(decoder, &dummy, /*do_full_decode=*/true))
  96997. return false; /* above function sets the status for us */
  96998. break;
  96999. case FLAC__STREAM_DECODER_END_OF_STREAM:
  97000. case FLAC__STREAM_DECODER_ABORTED:
  97001. return true;
  97002. default:
  97003. FLAC__ASSERT(0);
  97004. return false;
  97005. }
  97006. }
  97007. }
  97008. FLAC_API FLAC__bool FLAC__stream_decoder_skip_single_frame(FLAC__StreamDecoder *decoder)
  97009. {
  97010. FLAC__bool got_a_frame;
  97011. FLAC__ASSERT(0 != decoder);
  97012. FLAC__ASSERT(0 != decoder->protected_);
  97013. while(1) {
  97014. switch(decoder->protected_->state) {
  97015. case FLAC__STREAM_DECODER_SEARCH_FOR_METADATA:
  97016. case FLAC__STREAM_DECODER_READ_METADATA:
  97017. return false; /* above function sets the status for us */
  97018. case FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC:
  97019. if(!frame_sync_(decoder))
  97020. return true; /* above function sets the status for us */
  97021. break;
  97022. case FLAC__STREAM_DECODER_READ_FRAME:
  97023. if(!read_frame_(decoder, &got_a_frame, /*do_full_decode=*/false))
  97024. return false; /* above function sets the status for us */
  97025. if(got_a_frame)
  97026. return true; /* above function sets the status for us */
  97027. break;
  97028. case FLAC__STREAM_DECODER_END_OF_STREAM:
  97029. case FLAC__STREAM_DECODER_ABORTED:
  97030. return true;
  97031. default:
  97032. FLAC__ASSERT(0);
  97033. return false;
  97034. }
  97035. }
  97036. }
  97037. FLAC_API FLAC__bool FLAC__stream_decoder_seek_absolute(FLAC__StreamDecoder *decoder, FLAC__uint64 sample)
  97038. {
  97039. FLAC__uint64 length;
  97040. FLAC__ASSERT(0 != decoder);
  97041. if(
  97042. decoder->protected_->state != FLAC__STREAM_DECODER_SEARCH_FOR_METADATA &&
  97043. decoder->protected_->state != FLAC__STREAM_DECODER_READ_METADATA &&
  97044. decoder->protected_->state != FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC &&
  97045. decoder->protected_->state != FLAC__STREAM_DECODER_READ_FRAME &&
  97046. decoder->protected_->state != FLAC__STREAM_DECODER_END_OF_STREAM
  97047. )
  97048. return false;
  97049. if(0 == decoder->private_->seek_callback)
  97050. return false;
  97051. FLAC__ASSERT(decoder->private_->seek_callback);
  97052. FLAC__ASSERT(decoder->private_->tell_callback);
  97053. FLAC__ASSERT(decoder->private_->length_callback);
  97054. FLAC__ASSERT(decoder->private_->eof_callback);
  97055. if(FLAC__stream_decoder_get_total_samples(decoder) > 0 && sample >= FLAC__stream_decoder_get_total_samples(decoder))
  97056. return false;
  97057. decoder->private_->is_seeking = true;
  97058. /* turn off md5 checking if a seek is attempted */
  97059. decoder->private_->do_md5_checking = false;
  97060. /* 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) */
  97061. if(decoder->private_->length_callback(decoder, &length, decoder->private_->client_data) != FLAC__STREAM_DECODER_LENGTH_STATUS_OK) {
  97062. decoder->private_->is_seeking = false;
  97063. return false;
  97064. }
  97065. /* if we haven't finished processing the metadata yet, do that so we have the STREAMINFO, SEEK_TABLE, and first_frame_offset */
  97066. if(
  97067. decoder->protected_->state == FLAC__STREAM_DECODER_SEARCH_FOR_METADATA ||
  97068. decoder->protected_->state == FLAC__STREAM_DECODER_READ_METADATA
  97069. ) {
  97070. if(!FLAC__stream_decoder_process_until_end_of_metadata(decoder)) {
  97071. /* above call sets the state for us */
  97072. decoder->private_->is_seeking = false;
  97073. return false;
  97074. }
  97075. /* check this again in case we didn't know total_samples the first time */
  97076. if(FLAC__stream_decoder_get_total_samples(decoder) > 0 && sample >= FLAC__stream_decoder_get_total_samples(decoder)) {
  97077. decoder->private_->is_seeking = false;
  97078. return false;
  97079. }
  97080. }
  97081. {
  97082. const FLAC__bool ok =
  97083. #if FLAC__HAS_OGG
  97084. decoder->private_->is_ogg?
  97085. seek_to_absolute_sample_ogg_(decoder, length, sample) :
  97086. #endif
  97087. seek_to_absolute_sample_(decoder, length, sample)
  97088. ;
  97089. decoder->private_->is_seeking = false;
  97090. return ok;
  97091. }
  97092. }
  97093. /***********************************************************************
  97094. *
  97095. * Protected class methods
  97096. *
  97097. ***********************************************************************/
  97098. unsigned FLAC__stream_decoder_get_input_bytes_unconsumed(const FLAC__StreamDecoder *decoder)
  97099. {
  97100. FLAC__ASSERT(0 != decoder);
  97101. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input));
  97102. FLAC__ASSERT(!(FLAC__bitreader_get_input_bits_unconsumed(decoder->private_->input) & 7));
  97103. return FLAC__bitreader_get_input_bits_unconsumed(decoder->private_->input) / 8;
  97104. }
  97105. /***********************************************************************
  97106. *
  97107. * Private class methods
  97108. *
  97109. ***********************************************************************/
  97110. void set_defaults_dec(FLAC__StreamDecoder *decoder)
  97111. {
  97112. #if FLAC__HAS_OGG
  97113. decoder->private_->is_ogg = false;
  97114. #endif
  97115. decoder->private_->read_callback = 0;
  97116. decoder->private_->seek_callback = 0;
  97117. decoder->private_->tell_callback = 0;
  97118. decoder->private_->length_callback = 0;
  97119. decoder->private_->eof_callback = 0;
  97120. decoder->private_->write_callback = 0;
  97121. decoder->private_->metadata_callback = 0;
  97122. decoder->private_->error_callback = 0;
  97123. decoder->private_->client_data = 0;
  97124. memset(decoder->private_->metadata_filter, 0, sizeof(decoder->private_->metadata_filter));
  97125. decoder->private_->metadata_filter[FLAC__METADATA_TYPE_STREAMINFO] = true;
  97126. decoder->private_->metadata_filter_ids_count = 0;
  97127. decoder->protected_->md5_checking = false;
  97128. #if FLAC__HAS_OGG
  97129. FLAC__ogg_decoder_aspect_set_defaults(&decoder->protected_->ogg_decoder_aspect);
  97130. #endif
  97131. }
  97132. /*
  97133. * This will forcibly set stdin to binary mode (for OSes that require it)
  97134. */
  97135. FILE *get_binary_stdin_(void)
  97136. {
  97137. /* if something breaks here it is probably due to the presence or
  97138. * absence of an underscore before the identifiers 'setmode',
  97139. * 'fileno', and/or 'O_BINARY'; check your system header files.
  97140. */
  97141. #if defined _MSC_VER || defined __MINGW32__
  97142. _setmode(_fileno(stdin), _O_BINARY);
  97143. #elif defined __CYGWIN__
  97144. /* almost certainly not needed for any modern Cygwin, but let's be safe... */
  97145. setmode(_fileno(stdin), _O_BINARY);
  97146. #elif defined __EMX__
  97147. setmode(fileno(stdin), O_BINARY);
  97148. #endif
  97149. return stdin;
  97150. }
  97151. FLAC__bool allocate_output_(FLAC__StreamDecoder *decoder, unsigned size, unsigned channels)
  97152. {
  97153. unsigned i;
  97154. FLAC__int32 *tmp;
  97155. if(size <= decoder->private_->output_capacity && channels <= decoder->private_->output_channels)
  97156. return true;
  97157. /* simply using realloc() is not practical because the number of channels may change mid-stream */
  97158. for(i = 0; i < FLAC__MAX_CHANNELS; i++) {
  97159. if(0 != decoder->private_->output[i]) {
  97160. free(decoder->private_->output[i]-4);
  97161. decoder->private_->output[i] = 0;
  97162. }
  97163. if(0 != decoder->private_->residual_unaligned[i]) {
  97164. free(decoder->private_->residual_unaligned[i]);
  97165. decoder->private_->residual_unaligned[i] = decoder->private_->residual[i] = 0;
  97166. }
  97167. }
  97168. for(i = 0; i < channels; i++) {
  97169. /* WATCHOUT:
  97170. * FLAC__lpc_restore_signal_asm_ia32_mmx() requires that the
  97171. * output arrays have a buffer of up to 3 zeroes in front
  97172. * (at negative indices) for alignment purposes; we use 4
  97173. * to keep the data well-aligned.
  97174. */
  97175. tmp = (FLAC__int32*)safe_malloc_muladd2_(sizeof(FLAC__int32), /*times (*/size, /*+*/4/*)*/);
  97176. if(tmp == 0) {
  97177. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  97178. return false;
  97179. }
  97180. memset(tmp, 0, sizeof(FLAC__int32)*4);
  97181. decoder->private_->output[i] = tmp + 4;
  97182. /* WATCHOUT:
  97183. * minimum of quadword alignment for PPC vector optimizations is REQUIRED:
  97184. */
  97185. if(!FLAC__memory_alloc_aligned_int32_array(size, &decoder->private_->residual_unaligned[i], &decoder->private_->residual[i])) {
  97186. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  97187. return false;
  97188. }
  97189. }
  97190. decoder->private_->output_capacity = size;
  97191. decoder->private_->output_channels = channels;
  97192. return true;
  97193. }
  97194. FLAC__bool has_id_filtered_(FLAC__StreamDecoder *decoder, FLAC__byte *id)
  97195. {
  97196. size_t i;
  97197. FLAC__ASSERT(0 != decoder);
  97198. FLAC__ASSERT(0 != decoder->private_);
  97199. for(i = 0; i < decoder->private_->metadata_filter_ids_count; i++)
  97200. if(0 == memcmp(decoder->private_->metadata_filter_ids + i * (FLAC__STREAM_METADATA_APPLICATION_ID_LEN/8), id, (FLAC__STREAM_METADATA_APPLICATION_ID_LEN/8)))
  97201. return true;
  97202. return false;
  97203. }
  97204. FLAC__bool find_metadata_(FLAC__StreamDecoder *decoder)
  97205. {
  97206. FLAC__uint32 x;
  97207. unsigned i, id_;
  97208. FLAC__bool first = true;
  97209. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input));
  97210. for(i = id_ = 0; i < 4; ) {
  97211. if(decoder->private_->cached) {
  97212. x = (FLAC__uint32)decoder->private_->lookahead;
  97213. decoder->private_->cached = false;
  97214. }
  97215. else {
  97216. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8))
  97217. return false; /* read_callback_ sets the state for us */
  97218. }
  97219. if(x == FLAC__STREAM_SYNC_STRING[i]) {
  97220. first = true;
  97221. i++;
  97222. id_ = 0;
  97223. continue;
  97224. }
  97225. if(x == ID3V2_TAG_[id_]) {
  97226. id_++;
  97227. i = 0;
  97228. if(id_ == 3) {
  97229. if(!skip_id3v2_tag_(decoder))
  97230. return false; /* skip_id3v2_tag_ sets the state for us */
  97231. }
  97232. continue;
  97233. }
  97234. id_ = 0;
  97235. if(x == 0xff) { /* MAGIC NUMBER for the first 8 frame sync bits */
  97236. decoder->private_->header_warmup[0] = (FLAC__byte)x;
  97237. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8))
  97238. return false; /* read_callback_ sets the state for us */
  97239. /* 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 */
  97240. /* else we have to check if the second byte is the end of a sync code */
  97241. if(x == 0xff) { /* MAGIC NUMBER for the first 8 frame sync bits */
  97242. decoder->private_->lookahead = (FLAC__byte)x;
  97243. decoder->private_->cached = true;
  97244. }
  97245. else if(x >> 2 == 0x3e) { /* MAGIC NUMBER for the last 6 sync bits */
  97246. decoder->private_->header_warmup[1] = (FLAC__byte)x;
  97247. decoder->protected_->state = FLAC__STREAM_DECODER_READ_FRAME;
  97248. return true;
  97249. }
  97250. }
  97251. i = 0;
  97252. if(first) {
  97253. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC);
  97254. first = false;
  97255. }
  97256. }
  97257. decoder->protected_->state = FLAC__STREAM_DECODER_READ_METADATA;
  97258. return true;
  97259. }
  97260. FLAC__bool read_metadata_(FLAC__StreamDecoder *decoder)
  97261. {
  97262. FLAC__bool is_last;
  97263. FLAC__uint32 i, x, type, length;
  97264. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input));
  97265. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_IS_LAST_LEN))
  97266. return false; /* read_callback_ sets the state for us */
  97267. is_last = x? true : false;
  97268. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &type, FLAC__STREAM_METADATA_TYPE_LEN))
  97269. return false; /* read_callback_ sets the state for us */
  97270. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &length, FLAC__STREAM_METADATA_LENGTH_LEN))
  97271. return false; /* read_callback_ sets the state for us */
  97272. if(type == FLAC__METADATA_TYPE_STREAMINFO) {
  97273. if(!read_metadata_streaminfo_(decoder, is_last, length))
  97274. return false;
  97275. decoder->private_->has_stream_info = true;
  97276. 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))
  97277. decoder->private_->do_md5_checking = false;
  97278. if(!decoder->private_->is_seeking && decoder->private_->metadata_filter[FLAC__METADATA_TYPE_STREAMINFO] && decoder->private_->metadata_callback)
  97279. decoder->private_->metadata_callback(decoder, &decoder->private_->stream_info, decoder->private_->client_data);
  97280. }
  97281. else if(type == FLAC__METADATA_TYPE_SEEKTABLE) {
  97282. if(!read_metadata_seektable_(decoder, is_last, length))
  97283. return false;
  97284. decoder->private_->has_seek_table = true;
  97285. if(!decoder->private_->is_seeking && decoder->private_->metadata_filter[FLAC__METADATA_TYPE_SEEKTABLE] && decoder->private_->metadata_callback)
  97286. decoder->private_->metadata_callback(decoder, &decoder->private_->seek_table, decoder->private_->client_data);
  97287. }
  97288. else {
  97289. FLAC__bool skip_it = !decoder->private_->metadata_filter[type];
  97290. unsigned real_length = length;
  97291. FLAC__StreamMetadata block;
  97292. block.is_last = is_last;
  97293. block.type = (FLAC__MetadataType)type;
  97294. block.length = length;
  97295. if(type == FLAC__METADATA_TYPE_APPLICATION) {
  97296. if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, block.data.application.id, FLAC__STREAM_METADATA_APPLICATION_ID_LEN/8))
  97297. return false; /* read_callback_ sets the state for us */
  97298. if(real_length < FLAC__STREAM_METADATA_APPLICATION_ID_LEN/8) { /* underflow check */
  97299. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;/*@@@@@@ maybe wrong error? need to resync?*/
  97300. return false;
  97301. }
  97302. real_length -= FLAC__STREAM_METADATA_APPLICATION_ID_LEN/8;
  97303. if(decoder->private_->metadata_filter_ids_count > 0 && has_id_filtered_(decoder, block.data.application.id))
  97304. skip_it = !skip_it;
  97305. }
  97306. if(skip_it) {
  97307. if(!FLAC__bitreader_skip_byte_block_aligned_no_crc(decoder->private_->input, real_length))
  97308. return false; /* read_callback_ sets the state for us */
  97309. }
  97310. else {
  97311. switch(type) {
  97312. case FLAC__METADATA_TYPE_PADDING:
  97313. /* skip the padding bytes */
  97314. if(!FLAC__bitreader_skip_byte_block_aligned_no_crc(decoder->private_->input, real_length))
  97315. return false; /* read_callback_ sets the state for us */
  97316. break;
  97317. case FLAC__METADATA_TYPE_APPLICATION:
  97318. /* remember, we read the ID already */
  97319. if(real_length > 0) {
  97320. if(0 == (block.data.application.data = (FLAC__byte*)malloc(real_length))) {
  97321. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  97322. return false;
  97323. }
  97324. if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, block.data.application.data, real_length))
  97325. return false; /* read_callback_ sets the state for us */
  97326. }
  97327. else
  97328. block.data.application.data = 0;
  97329. break;
  97330. case FLAC__METADATA_TYPE_VORBIS_COMMENT:
  97331. if(!read_metadata_vorbiscomment_(decoder, &block.data.vorbis_comment))
  97332. return false;
  97333. break;
  97334. case FLAC__METADATA_TYPE_CUESHEET:
  97335. if(!read_metadata_cuesheet_(decoder, &block.data.cue_sheet))
  97336. return false;
  97337. break;
  97338. case FLAC__METADATA_TYPE_PICTURE:
  97339. if(!read_metadata_picture_(decoder, &block.data.picture))
  97340. return false;
  97341. break;
  97342. case FLAC__METADATA_TYPE_STREAMINFO:
  97343. case FLAC__METADATA_TYPE_SEEKTABLE:
  97344. FLAC__ASSERT(0);
  97345. break;
  97346. default:
  97347. if(real_length > 0) {
  97348. if(0 == (block.data.unknown.data = (FLAC__byte*)malloc(real_length))) {
  97349. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  97350. return false;
  97351. }
  97352. if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, block.data.unknown.data, real_length))
  97353. return false; /* read_callback_ sets the state for us */
  97354. }
  97355. else
  97356. block.data.unknown.data = 0;
  97357. break;
  97358. }
  97359. if(!decoder->private_->is_seeking && decoder->private_->metadata_callback)
  97360. decoder->private_->metadata_callback(decoder, &block, decoder->private_->client_data);
  97361. /* now we have to free any malloc()ed data in the block */
  97362. switch(type) {
  97363. case FLAC__METADATA_TYPE_PADDING:
  97364. break;
  97365. case FLAC__METADATA_TYPE_APPLICATION:
  97366. if(0 != block.data.application.data)
  97367. free(block.data.application.data);
  97368. break;
  97369. case FLAC__METADATA_TYPE_VORBIS_COMMENT:
  97370. if(0 != block.data.vorbis_comment.vendor_string.entry)
  97371. free(block.data.vorbis_comment.vendor_string.entry);
  97372. if(block.data.vorbis_comment.num_comments > 0)
  97373. for(i = 0; i < block.data.vorbis_comment.num_comments; i++)
  97374. if(0 != block.data.vorbis_comment.comments[i].entry)
  97375. free(block.data.vorbis_comment.comments[i].entry);
  97376. if(0 != block.data.vorbis_comment.comments)
  97377. free(block.data.vorbis_comment.comments);
  97378. break;
  97379. case FLAC__METADATA_TYPE_CUESHEET:
  97380. if(block.data.cue_sheet.num_tracks > 0)
  97381. for(i = 0; i < block.data.cue_sheet.num_tracks; i++)
  97382. if(0 != block.data.cue_sheet.tracks[i].indices)
  97383. free(block.data.cue_sheet.tracks[i].indices);
  97384. if(0 != block.data.cue_sheet.tracks)
  97385. free(block.data.cue_sheet.tracks);
  97386. break;
  97387. case FLAC__METADATA_TYPE_PICTURE:
  97388. if(0 != block.data.picture.mime_type)
  97389. free(block.data.picture.mime_type);
  97390. if(0 != block.data.picture.description)
  97391. free(block.data.picture.description);
  97392. if(0 != block.data.picture.data)
  97393. free(block.data.picture.data);
  97394. break;
  97395. case FLAC__METADATA_TYPE_STREAMINFO:
  97396. case FLAC__METADATA_TYPE_SEEKTABLE:
  97397. FLAC__ASSERT(0);
  97398. default:
  97399. if(0 != block.data.unknown.data)
  97400. free(block.data.unknown.data);
  97401. break;
  97402. }
  97403. }
  97404. }
  97405. if(is_last) {
  97406. /* if this fails, it's OK, it's just a hint for the seek routine */
  97407. if(!FLAC__stream_decoder_get_decode_position(decoder, &decoder->private_->first_frame_offset))
  97408. decoder->private_->first_frame_offset = 0;
  97409. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  97410. }
  97411. return true;
  97412. }
  97413. FLAC__bool read_metadata_streaminfo_(FLAC__StreamDecoder *decoder, FLAC__bool is_last, unsigned length)
  97414. {
  97415. FLAC__uint32 x;
  97416. unsigned bits, used_bits = 0;
  97417. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input));
  97418. decoder->private_->stream_info.type = FLAC__METADATA_TYPE_STREAMINFO;
  97419. decoder->private_->stream_info.is_last = is_last;
  97420. decoder->private_->stream_info.length = length;
  97421. bits = FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN;
  97422. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, bits))
  97423. return false; /* read_callback_ sets the state for us */
  97424. decoder->private_->stream_info.data.stream_info.min_blocksize = x;
  97425. used_bits += bits;
  97426. bits = FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN;
  97427. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN))
  97428. return false; /* read_callback_ sets the state for us */
  97429. decoder->private_->stream_info.data.stream_info.max_blocksize = x;
  97430. used_bits += bits;
  97431. bits = FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN;
  97432. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN))
  97433. return false; /* read_callback_ sets the state for us */
  97434. decoder->private_->stream_info.data.stream_info.min_framesize = x;
  97435. used_bits += bits;
  97436. bits = FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN;
  97437. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN))
  97438. return false; /* read_callback_ sets the state for us */
  97439. decoder->private_->stream_info.data.stream_info.max_framesize = x;
  97440. used_bits += bits;
  97441. bits = FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN;
  97442. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN))
  97443. return false; /* read_callback_ sets the state for us */
  97444. decoder->private_->stream_info.data.stream_info.sample_rate = x;
  97445. used_bits += bits;
  97446. bits = FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN;
  97447. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN))
  97448. return false; /* read_callback_ sets the state for us */
  97449. decoder->private_->stream_info.data.stream_info.channels = x+1;
  97450. used_bits += bits;
  97451. bits = FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN;
  97452. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN))
  97453. return false; /* read_callback_ sets the state for us */
  97454. decoder->private_->stream_info.data.stream_info.bits_per_sample = x+1;
  97455. used_bits += bits;
  97456. bits = FLAC__STREAM_METADATA_STREAMINFO_TOTAL_SAMPLES_LEN;
  97457. 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))
  97458. return false; /* read_callback_ sets the state for us */
  97459. used_bits += bits;
  97460. if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, decoder->private_->stream_info.data.stream_info.md5sum, 16))
  97461. return false; /* read_callback_ sets the state for us */
  97462. used_bits += 16*8;
  97463. /* skip the rest of the block */
  97464. FLAC__ASSERT(used_bits % 8 == 0);
  97465. length -= (used_bits / 8);
  97466. if(!FLAC__bitreader_skip_byte_block_aligned_no_crc(decoder->private_->input, length))
  97467. return false; /* read_callback_ sets the state for us */
  97468. return true;
  97469. }
  97470. FLAC__bool read_metadata_seektable_(FLAC__StreamDecoder *decoder, FLAC__bool is_last, unsigned length)
  97471. {
  97472. FLAC__uint32 i, x;
  97473. FLAC__uint64 xx;
  97474. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input));
  97475. decoder->private_->seek_table.type = FLAC__METADATA_TYPE_SEEKTABLE;
  97476. decoder->private_->seek_table.is_last = is_last;
  97477. decoder->private_->seek_table.length = length;
  97478. decoder->private_->seek_table.data.seek_table.num_points = length / FLAC__STREAM_METADATA_SEEKPOINT_LENGTH;
  97479. /* use realloc since we may pass through here several times (e.g. after seeking) */
  97480. 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)))) {
  97481. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  97482. return false;
  97483. }
  97484. for(i = 0; i < decoder->private_->seek_table.data.seek_table.num_points; i++) {
  97485. if(!FLAC__bitreader_read_raw_uint64(decoder->private_->input, &xx, FLAC__STREAM_METADATA_SEEKPOINT_SAMPLE_NUMBER_LEN))
  97486. return false; /* read_callback_ sets the state for us */
  97487. decoder->private_->seek_table.data.seek_table.points[i].sample_number = xx;
  97488. if(!FLAC__bitreader_read_raw_uint64(decoder->private_->input, &xx, FLAC__STREAM_METADATA_SEEKPOINT_STREAM_OFFSET_LEN))
  97489. return false; /* read_callback_ sets the state for us */
  97490. decoder->private_->seek_table.data.seek_table.points[i].stream_offset = xx;
  97491. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_SEEKPOINT_FRAME_SAMPLES_LEN))
  97492. return false; /* read_callback_ sets the state for us */
  97493. decoder->private_->seek_table.data.seek_table.points[i].frame_samples = x;
  97494. }
  97495. length -= (decoder->private_->seek_table.data.seek_table.num_points * FLAC__STREAM_METADATA_SEEKPOINT_LENGTH);
  97496. /* if there is a partial point left, skip over it */
  97497. if(length > 0) {
  97498. /*@@@ do a send_error_to_client_() here? there's an argument for either way */
  97499. if(!FLAC__bitreader_skip_byte_block_aligned_no_crc(decoder->private_->input, length))
  97500. return false; /* read_callback_ sets the state for us */
  97501. }
  97502. return true;
  97503. }
  97504. FLAC__bool read_metadata_vorbiscomment_(FLAC__StreamDecoder *decoder, FLAC__StreamMetadata_VorbisComment *obj)
  97505. {
  97506. FLAC__uint32 i;
  97507. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input));
  97508. /* read vendor string */
  97509. FLAC__ASSERT(FLAC__STREAM_METADATA_VORBIS_COMMENT_ENTRY_LENGTH_LEN == 32);
  97510. if(!FLAC__bitreader_read_uint32_little_endian(decoder->private_->input, &obj->vendor_string.length))
  97511. return false; /* read_callback_ sets the state for us */
  97512. if(obj->vendor_string.length > 0) {
  97513. if(0 == (obj->vendor_string.entry = (FLAC__byte*)safe_malloc_add_2op_(obj->vendor_string.length, /*+*/1))) {
  97514. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  97515. return false;
  97516. }
  97517. if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, obj->vendor_string.entry, obj->vendor_string.length))
  97518. return false; /* read_callback_ sets the state for us */
  97519. obj->vendor_string.entry[obj->vendor_string.length] = '\0';
  97520. }
  97521. else
  97522. obj->vendor_string.entry = 0;
  97523. /* read num comments */
  97524. FLAC__ASSERT(FLAC__STREAM_METADATA_VORBIS_COMMENT_NUM_COMMENTS_LEN == 32);
  97525. if(!FLAC__bitreader_read_uint32_little_endian(decoder->private_->input, &obj->num_comments))
  97526. return false; /* read_callback_ sets the state for us */
  97527. /* read comments */
  97528. if(obj->num_comments > 0) {
  97529. if(0 == (obj->comments = (FLAC__StreamMetadata_VorbisComment_Entry*)safe_malloc_mul_2op_(obj->num_comments, /*times*/sizeof(FLAC__StreamMetadata_VorbisComment_Entry)))) {
  97530. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  97531. return false;
  97532. }
  97533. for(i = 0; i < obj->num_comments; i++) {
  97534. FLAC__ASSERT(FLAC__STREAM_METADATA_VORBIS_COMMENT_ENTRY_LENGTH_LEN == 32);
  97535. if(!FLAC__bitreader_read_uint32_little_endian(decoder->private_->input, &obj->comments[i].length))
  97536. return false; /* read_callback_ sets the state for us */
  97537. if(obj->comments[i].length > 0) {
  97538. if(0 == (obj->comments[i].entry = (FLAC__byte*)safe_malloc_add_2op_(obj->comments[i].length, /*+*/1))) {
  97539. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  97540. return false;
  97541. }
  97542. if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, obj->comments[i].entry, obj->comments[i].length))
  97543. return false; /* read_callback_ sets the state for us */
  97544. obj->comments[i].entry[obj->comments[i].length] = '\0';
  97545. }
  97546. else
  97547. obj->comments[i].entry = 0;
  97548. }
  97549. }
  97550. else {
  97551. obj->comments = 0;
  97552. }
  97553. return true;
  97554. }
  97555. FLAC__bool read_metadata_cuesheet_(FLAC__StreamDecoder *decoder, FLAC__StreamMetadata_CueSheet *obj)
  97556. {
  97557. FLAC__uint32 i, j, x;
  97558. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input));
  97559. memset(obj, 0, sizeof(FLAC__StreamMetadata_CueSheet));
  97560. FLAC__ASSERT(FLAC__STREAM_METADATA_CUESHEET_MEDIA_CATALOG_NUMBER_LEN % 8 == 0);
  97561. 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))
  97562. return false; /* read_callback_ sets the state for us */
  97563. if(!FLAC__bitreader_read_raw_uint64(decoder->private_->input, &obj->lead_in, FLAC__STREAM_METADATA_CUESHEET_LEAD_IN_LEN))
  97564. return false; /* read_callback_ sets the state for us */
  97565. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_CUESHEET_IS_CD_LEN))
  97566. return false; /* read_callback_ sets the state for us */
  97567. obj->is_cd = x? true : false;
  97568. if(!FLAC__bitreader_skip_bits_no_crc(decoder->private_->input, FLAC__STREAM_METADATA_CUESHEET_RESERVED_LEN))
  97569. return false; /* read_callback_ sets the state for us */
  97570. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_CUESHEET_NUM_TRACKS_LEN))
  97571. return false; /* read_callback_ sets the state for us */
  97572. obj->num_tracks = x;
  97573. if(obj->num_tracks > 0) {
  97574. if(0 == (obj->tracks = (FLAC__StreamMetadata_CueSheet_Track*)safe_calloc_(obj->num_tracks, sizeof(FLAC__StreamMetadata_CueSheet_Track)))) {
  97575. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  97576. return false;
  97577. }
  97578. for(i = 0; i < obj->num_tracks; i++) {
  97579. FLAC__StreamMetadata_CueSheet_Track *track = &obj->tracks[i];
  97580. if(!FLAC__bitreader_read_raw_uint64(decoder->private_->input, &track->offset, FLAC__STREAM_METADATA_CUESHEET_TRACK_OFFSET_LEN))
  97581. return false; /* read_callback_ sets the state for us */
  97582. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_CUESHEET_TRACK_NUMBER_LEN))
  97583. return false; /* read_callback_ sets the state for us */
  97584. track->number = (FLAC__byte)x;
  97585. FLAC__ASSERT(FLAC__STREAM_METADATA_CUESHEET_TRACK_ISRC_LEN % 8 == 0);
  97586. if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, (FLAC__byte*)track->isrc, FLAC__STREAM_METADATA_CUESHEET_TRACK_ISRC_LEN/8))
  97587. return false; /* read_callback_ sets the state for us */
  97588. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_CUESHEET_TRACK_TYPE_LEN))
  97589. return false; /* read_callback_ sets the state for us */
  97590. track->type = x;
  97591. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_CUESHEET_TRACK_PRE_EMPHASIS_LEN))
  97592. return false; /* read_callback_ sets the state for us */
  97593. track->pre_emphasis = x;
  97594. if(!FLAC__bitreader_skip_bits_no_crc(decoder->private_->input, FLAC__STREAM_METADATA_CUESHEET_TRACK_RESERVED_LEN))
  97595. return false; /* read_callback_ sets the state for us */
  97596. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_CUESHEET_TRACK_NUM_INDICES_LEN))
  97597. return false; /* read_callback_ sets the state for us */
  97598. track->num_indices = (FLAC__byte)x;
  97599. if(track->num_indices > 0) {
  97600. if(0 == (track->indices = (FLAC__StreamMetadata_CueSheet_Index*)safe_calloc_(track->num_indices, sizeof(FLAC__StreamMetadata_CueSheet_Index)))) {
  97601. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  97602. return false;
  97603. }
  97604. for(j = 0; j < track->num_indices; j++) {
  97605. FLAC__StreamMetadata_CueSheet_Index *index = &track->indices[j];
  97606. if(!FLAC__bitreader_read_raw_uint64(decoder->private_->input, &index->offset, FLAC__STREAM_METADATA_CUESHEET_INDEX_OFFSET_LEN))
  97607. return false; /* read_callback_ sets the state for us */
  97608. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_CUESHEET_INDEX_NUMBER_LEN))
  97609. return false; /* read_callback_ sets the state for us */
  97610. index->number = (FLAC__byte)x;
  97611. if(!FLAC__bitreader_skip_bits_no_crc(decoder->private_->input, FLAC__STREAM_METADATA_CUESHEET_INDEX_RESERVED_LEN))
  97612. return false; /* read_callback_ sets the state for us */
  97613. }
  97614. }
  97615. }
  97616. }
  97617. return true;
  97618. }
  97619. FLAC__bool read_metadata_picture_(FLAC__StreamDecoder *decoder, FLAC__StreamMetadata_Picture *obj)
  97620. {
  97621. FLAC__uint32 x;
  97622. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input));
  97623. /* read type */
  97624. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_PICTURE_TYPE_LEN))
  97625. return false; /* read_callback_ sets the state for us */
  97626. obj->type = (FLAC__StreamMetadata_Picture_Type) x;
  97627. /* read MIME type */
  97628. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_PICTURE_MIME_TYPE_LENGTH_LEN))
  97629. return false; /* read_callback_ sets the state for us */
  97630. if(0 == (obj->mime_type = (char*)safe_malloc_add_2op_(x, /*+*/1))) {
  97631. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  97632. return false;
  97633. }
  97634. if(x > 0) {
  97635. if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, (FLAC__byte*)obj->mime_type, x))
  97636. return false; /* read_callback_ sets the state for us */
  97637. }
  97638. obj->mime_type[x] = '\0';
  97639. /* read description */
  97640. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_PICTURE_DESCRIPTION_LENGTH_LEN))
  97641. return false; /* read_callback_ sets the state for us */
  97642. if(0 == (obj->description = (FLAC__byte*)safe_malloc_add_2op_(x, /*+*/1))) {
  97643. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  97644. return false;
  97645. }
  97646. if(x > 0) {
  97647. if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, obj->description, x))
  97648. return false; /* read_callback_ sets the state for us */
  97649. }
  97650. obj->description[x] = '\0';
  97651. /* read width */
  97652. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &obj->width, FLAC__STREAM_METADATA_PICTURE_WIDTH_LEN))
  97653. return false; /* read_callback_ sets the state for us */
  97654. /* read height */
  97655. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &obj->height, FLAC__STREAM_METADATA_PICTURE_HEIGHT_LEN))
  97656. return false; /* read_callback_ sets the state for us */
  97657. /* read depth */
  97658. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &obj->depth, FLAC__STREAM_METADATA_PICTURE_DEPTH_LEN))
  97659. return false; /* read_callback_ sets the state for us */
  97660. /* read colors */
  97661. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &obj->colors, FLAC__STREAM_METADATA_PICTURE_COLORS_LEN))
  97662. return false; /* read_callback_ sets the state for us */
  97663. /* read data */
  97664. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &(obj->data_length), FLAC__STREAM_METADATA_PICTURE_DATA_LENGTH_LEN))
  97665. return false; /* read_callback_ sets the state for us */
  97666. if(0 == (obj->data = (FLAC__byte*)safe_malloc_(obj->data_length))) {
  97667. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  97668. return false;
  97669. }
  97670. if(obj->data_length > 0) {
  97671. if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, obj->data, obj->data_length))
  97672. return false; /* read_callback_ sets the state for us */
  97673. }
  97674. return true;
  97675. }
  97676. FLAC__bool skip_id3v2_tag_(FLAC__StreamDecoder *decoder)
  97677. {
  97678. FLAC__uint32 x;
  97679. unsigned i, skip;
  97680. /* skip the version and flags bytes */
  97681. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 24))
  97682. return false; /* read_callback_ sets the state for us */
  97683. /* get the size (in bytes) to skip */
  97684. skip = 0;
  97685. for(i = 0; i < 4; i++) {
  97686. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8))
  97687. return false; /* read_callback_ sets the state for us */
  97688. skip <<= 7;
  97689. skip |= (x & 0x7f);
  97690. }
  97691. /* skip the rest of the tag */
  97692. if(!FLAC__bitreader_skip_byte_block_aligned_no_crc(decoder->private_->input, skip))
  97693. return false; /* read_callback_ sets the state for us */
  97694. return true;
  97695. }
  97696. FLAC__bool frame_sync_(FLAC__StreamDecoder *decoder)
  97697. {
  97698. FLAC__uint32 x;
  97699. FLAC__bool first = true;
  97700. /* If we know the total number of samples in the stream, stop if we've read that many. */
  97701. /* This will stop us, for example, from wasting time trying to sync on an ID3V1 tag. */
  97702. if(FLAC__stream_decoder_get_total_samples(decoder) > 0) {
  97703. if(decoder->private_->samples_decoded >= FLAC__stream_decoder_get_total_samples(decoder)) {
  97704. decoder->protected_->state = FLAC__STREAM_DECODER_END_OF_STREAM;
  97705. return true;
  97706. }
  97707. }
  97708. /* make sure we're byte aligned */
  97709. if(!FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input)) {
  97710. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__bitreader_bits_left_for_byte_alignment(decoder->private_->input)))
  97711. return false; /* read_callback_ sets the state for us */
  97712. }
  97713. while(1) {
  97714. if(decoder->private_->cached) {
  97715. x = (FLAC__uint32)decoder->private_->lookahead;
  97716. decoder->private_->cached = false;
  97717. }
  97718. else {
  97719. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8))
  97720. return false; /* read_callback_ sets the state for us */
  97721. }
  97722. if(x == 0xff) { /* MAGIC NUMBER for the first 8 frame sync bits */
  97723. decoder->private_->header_warmup[0] = (FLAC__byte)x;
  97724. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8))
  97725. return false; /* read_callback_ sets the state for us */
  97726. /* 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 */
  97727. /* else we have to check if the second byte is the end of a sync code */
  97728. if(x == 0xff) { /* MAGIC NUMBER for the first 8 frame sync bits */
  97729. decoder->private_->lookahead = (FLAC__byte)x;
  97730. decoder->private_->cached = true;
  97731. }
  97732. else if(x >> 2 == 0x3e) { /* MAGIC NUMBER for the last 6 sync bits */
  97733. decoder->private_->header_warmup[1] = (FLAC__byte)x;
  97734. decoder->protected_->state = FLAC__STREAM_DECODER_READ_FRAME;
  97735. return true;
  97736. }
  97737. }
  97738. if(first) {
  97739. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC);
  97740. first = false;
  97741. }
  97742. }
  97743. return true;
  97744. }
  97745. FLAC__bool read_frame_(FLAC__StreamDecoder *decoder, FLAC__bool *got_a_frame, FLAC__bool do_full_decode)
  97746. {
  97747. unsigned channel;
  97748. unsigned i;
  97749. FLAC__int32 mid, side;
  97750. unsigned frame_crc; /* the one we calculate from the input stream */
  97751. FLAC__uint32 x;
  97752. *got_a_frame = false;
  97753. /* init the CRC */
  97754. frame_crc = 0;
  97755. frame_crc = FLAC__CRC16_UPDATE(decoder->private_->header_warmup[0], frame_crc);
  97756. frame_crc = FLAC__CRC16_UPDATE(decoder->private_->header_warmup[1], frame_crc);
  97757. FLAC__bitreader_reset_read_crc16(decoder->private_->input, (FLAC__uint16)frame_crc);
  97758. if(!read_frame_header_(decoder))
  97759. return false;
  97760. if(decoder->protected_->state == FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC) /* means we didn't sync on a valid header */
  97761. return true;
  97762. if(!allocate_output_(decoder, decoder->private_->frame.header.blocksize, decoder->private_->frame.header.channels))
  97763. return false;
  97764. for(channel = 0; channel < decoder->private_->frame.header.channels; channel++) {
  97765. /*
  97766. * first figure the correct bits-per-sample of the subframe
  97767. */
  97768. unsigned bps = decoder->private_->frame.header.bits_per_sample;
  97769. switch(decoder->private_->frame.header.channel_assignment) {
  97770. case FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT:
  97771. /* no adjustment needed */
  97772. break;
  97773. case FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE:
  97774. FLAC__ASSERT(decoder->private_->frame.header.channels == 2);
  97775. if(channel == 1)
  97776. bps++;
  97777. break;
  97778. case FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE:
  97779. FLAC__ASSERT(decoder->private_->frame.header.channels == 2);
  97780. if(channel == 0)
  97781. bps++;
  97782. break;
  97783. case FLAC__CHANNEL_ASSIGNMENT_MID_SIDE:
  97784. FLAC__ASSERT(decoder->private_->frame.header.channels == 2);
  97785. if(channel == 1)
  97786. bps++;
  97787. break;
  97788. default:
  97789. FLAC__ASSERT(0);
  97790. }
  97791. /*
  97792. * now read it
  97793. */
  97794. if(!read_subframe_(decoder, channel, bps, do_full_decode))
  97795. return false;
  97796. if(decoder->protected_->state == FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC) /* means bad sync or got corruption */
  97797. return true;
  97798. }
  97799. if(!read_zero_padding_(decoder))
  97800. return false;
  97801. 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) */
  97802. return true;
  97803. /*
  97804. * Read the frame CRC-16 from the footer and check
  97805. */
  97806. frame_crc = FLAC__bitreader_get_read_crc16(decoder->private_->input);
  97807. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__FRAME_FOOTER_CRC_LEN))
  97808. return false; /* read_callback_ sets the state for us */
  97809. if(frame_crc == x) {
  97810. if(do_full_decode) {
  97811. /* Undo any special channel coding */
  97812. switch(decoder->private_->frame.header.channel_assignment) {
  97813. case FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT:
  97814. /* do nothing */
  97815. break;
  97816. case FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE:
  97817. FLAC__ASSERT(decoder->private_->frame.header.channels == 2);
  97818. for(i = 0; i < decoder->private_->frame.header.blocksize; i++)
  97819. decoder->private_->output[1][i] = decoder->private_->output[0][i] - decoder->private_->output[1][i];
  97820. break;
  97821. case FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE:
  97822. FLAC__ASSERT(decoder->private_->frame.header.channels == 2);
  97823. for(i = 0; i < decoder->private_->frame.header.blocksize; i++)
  97824. decoder->private_->output[0][i] += decoder->private_->output[1][i];
  97825. break;
  97826. case FLAC__CHANNEL_ASSIGNMENT_MID_SIDE:
  97827. FLAC__ASSERT(decoder->private_->frame.header.channels == 2);
  97828. for(i = 0; i < decoder->private_->frame.header.blocksize; i++) {
  97829. #if 1
  97830. mid = decoder->private_->output[0][i];
  97831. side = decoder->private_->output[1][i];
  97832. mid <<= 1;
  97833. mid |= (side & 1); /* i.e. if 'side' is odd... */
  97834. decoder->private_->output[0][i] = (mid + side) >> 1;
  97835. decoder->private_->output[1][i] = (mid - side) >> 1;
  97836. #else
  97837. /* OPT: without 'side' temp variable */
  97838. mid = (decoder->private_->output[0][i] << 1) | (decoder->private_->output[1][i] & 1); /* i.e. if 'side' is odd... */
  97839. decoder->private_->output[0][i] = (mid + decoder->private_->output[1][i]) >> 1;
  97840. decoder->private_->output[1][i] = (mid - decoder->private_->output[1][i]) >> 1;
  97841. #endif
  97842. }
  97843. break;
  97844. default:
  97845. FLAC__ASSERT(0);
  97846. break;
  97847. }
  97848. }
  97849. }
  97850. else {
  97851. /* Bad frame, emit error and zero the output signal */
  97852. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_FRAME_CRC_MISMATCH);
  97853. if(do_full_decode) {
  97854. for(channel = 0; channel < decoder->private_->frame.header.channels; channel++) {
  97855. memset(decoder->private_->output[channel], 0, sizeof(FLAC__int32) * decoder->private_->frame.header.blocksize);
  97856. }
  97857. }
  97858. }
  97859. *got_a_frame = true;
  97860. /* we wait to update fixed_block_size until here, when we're sure we've got a proper frame and hence a correct blocksize */
  97861. if(decoder->private_->next_fixed_block_size)
  97862. decoder->private_->fixed_block_size = decoder->private_->next_fixed_block_size;
  97863. /* put the latest values into the public section of the decoder instance */
  97864. decoder->protected_->channels = decoder->private_->frame.header.channels;
  97865. decoder->protected_->channel_assignment = decoder->private_->frame.header.channel_assignment;
  97866. decoder->protected_->bits_per_sample = decoder->private_->frame.header.bits_per_sample;
  97867. decoder->protected_->sample_rate = decoder->private_->frame.header.sample_rate;
  97868. decoder->protected_->blocksize = decoder->private_->frame.header.blocksize;
  97869. FLAC__ASSERT(decoder->private_->frame.header.number_type == FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER);
  97870. decoder->private_->samples_decoded = decoder->private_->frame.header.number.sample_number + decoder->private_->frame.header.blocksize;
  97871. /* write it */
  97872. if(do_full_decode) {
  97873. if(write_audio_frame_to_client_(decoder, &decoder->private_->frame, (const FLAC__int32 * const *)decoder->private_->output) != FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE)
  97874. return false;
  97875. }
  97876. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  97877. return true;
  97878. }
  97879. FLAC__bool read_frame_header_(FLAC__StreamDecoder *decoder)
  97880. {
  97881. FLAC__uint32 x;
  97882. FLAC__uint64 xx;
  97883. unsigned i, blocksize_hint = 0, sample_rate_hint = 0;
  97884. FLAC__byte crc8, raw_header[16]; /* MAGIC NUMBER based on the maximum frame header size, including CRC */
  97885. unsigned raw_header_len;
  97886. FLAC__bool is_unparseable = false;
  97887. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input));
  97888. /* init the raw header with the saved bits from synchronization */
  97889. raw_header[0] = decoder->private_->header_warmup[0];
  97890. raw_header[1] = decoder->private_->header_warmup[1];
  97891. raw_header_len = 2;
  97892. /* check to make sure that reserved bit is 0 */
  97893. if(raw_header[1] & 0x02) /* MAGIC NUMBER */
  97894. is_unparseable = true;
  97895. /*
  97896. * Note that along the way as we read the header, we look for a sync
  97897. * code inside. If we find one it would indicate that our original
  97898. * sync was bad since there cannot be a sync code in a valid header.
  97899. *
  97900. * Three kinds of things can go wrong when reading the frame header:
  97901. * 1) We may have sync'ed incorrectly and not landed on a frame header.
  97902. * If we don't find a sync code, it can end up looking like we read
  97903. * a valid but unparseable header, until getting to the frame header
  97904. * CRC. Even then we could get a false positive on the CRC.
  97905. * 2) We may have sync'ed correctly but on an unparseable frame (from a
  97906. * future encoder).
  97907. * 3) We may be on a damaged frame which appears valid but unparseable.
  97908. *
  97909. * For all these reasons, we try and read a complete frame header as
  97910. * long as it seems valid, even if unparseable, up until the frame
  97911. * header CRC.
  97912. */
  97913. /*
  97914. * read in the raw header as bytes so we can CRC it, and parse it on the way
  97915. */
  97916. for(i = 0; i < 2; i++) {
  97917. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8))
  97918. return false; /* read_callback_ sets the state for us */
  97919. if(x == 0xff) { /* MAGIC NUMBER for the first 8 frame sync bits */
  97920. /* if we get here it means our original sync was erroneous since the sync code cannot appear in the header */
  97921. decoder->private_->lookahead = (FLAC__byte)x;
  97922. decoder->private_->cached = true;
  97923. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER);
  97924. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  97925. return true;
  97926. }
  97927. raw_header[raw_header_len++] = (FLAC__byte)x;
  97928. }
  97929. switch(x = raw_header[2] >> 4) {
  97930. case 0:
  97931. is_unparseable = true;
  97932. break;
  97933. case 1:
  97934. decoder->private_->frame.header.blocksize = 192;
  97935. break;
  97936. case 2:
  97937. case 3:
  97938. case 4:
  97939. case 5:
  97940. decoder->private_->frame.header.blocksize = 576 << (x-2);
  97941. break;
  97942. case 6:
  97943. case 7:
  97944. blocksize_hint = x;
  97945. break;
  97946. case 8:
  97947. case 9:
  97948. case 10:
  97949. case 11:
  97950. case 12:
  97951. case 13:
  97952. case 14:
  97953. case 15:
  97954. decoder->private_->frame.header.blocksize = 256 << (x-8);
  97955. break;
  97956. default:
  97957. FLAC__ASSERT(0);
  97958. break;
  97959. }
  97960. switch(x = raw_header[2] & 0x0f) {
  97961. case 0:
  97962. if(decoder->private_->has_stream_info)
  97963. decoder->private_->frame.header.sample_rate = decoder->private_->stream_info.data.stream_info.sample_rate;
  97964. else
  97965. is_unparseable = true;
  97966. break;
  97967. case 1:
  97968. decoder->private_->frame.header.sample_rate = 88200;
  97969. break;
  97970. case 2:
  97971. decoder->private_->frame.header.sample_rate = 176400;
  97972. break;
  97973. case 3:
  97974. decoder->private_->frame.header.sample_rate = 192000;
  97975. break;
  97976. case 4:
  97977. decoder->private_->frame.header.sample_rate = 8000;
  97978. break;
  97979. case 5:
  97980. decoder->private_->frame.header.sample_rate = 16000;
  97981. break;
  97982. case 6:
  97983. decoder->private_->frame.header.sample_rate = 22050;
  97984. break;
  97985. case 7:
  97986. decoder->private_->frame.header.sample_rate = 24000;
  97987. break;
  97988. case 8:
  97989. decoder->private_->frame.header.sample_rate = 32000;
  97990. break;
  97991. case 9:
  97992. decoder->private_->frame.header.sample_rate = 44100;
  97993. break;
  97994. case 10:
  97995. decoder->private_->frame.header.sample_rate = 48000;
  97996. break;
  97997. case 11:
  97998. decoder->private_->frame.header.sample_rate = 96000;
  97999. break;
  98000. case 12:
  98001. case 13:
  98002. case 14:
  98003. sample_rate_hint = x;
  98004. break;
  98005. case 15:
  98006. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER);
  98007. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  98008. return true;
  98009. default:
  98010. FLAC__ASSERT(0);
  98011. }
  98012. x = (unsigned)(raw_header[3] >> 4);
  98013. if(x & 8) {
  98014. decoder->private_->frame.header.channels = 2;
  98015. switch(x & 7) {
  98016. case 0:
  98017. decoder->private_->frame.header.channel_assignment = FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE;
  98018. break;
  98019. case 1:
  98020. decoder->private_->frame.header.channel_assignment = FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE;
  98021. break;
  98022. case 2:
  98023. decoder->private_->frame.header.channel_assignment = FLAC__CHANNEL_ASSIGNMENT_MID_SIDE;
  98024. break;
  98025. default:
  98026. is_unparseable = true;
  98027. break;
  98028. }
  98029. }
  98030. else {
  98031. decoder->private_->frame.header.channels = (unsigned)x + 1;
  98032. decoder->private_->frame.header.channel_assignment = FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT;
  98033. }
  98034. switch(x = (unsigned)(raw_header[3] & 0x0e) >> 1) {
  98035. case 0:
  98036. if(decoder->private_->has_stream_info)
  98037. decoder->private_->frame.header.bits_per_sample = decoder->private_->stream_info.data.stream_info.bits_per_sample;
  98038. else
  98039. is_unparseable = true;
  98040. break;
  98041. case 1:
  98042. decoder->private_->frame.header.bits_per_sample = 8;
  98043. break;
  98044. case 2:
  98045. decoder->private_->frame.header.bits_per_sample = 12;
  98046. break;
  98047. case 4:
  98048. decoder->private_->frame.header.bits_per_sample = 16;
  98049. break;
  98050. case 5:
  98051. decoder->private_->frame.header.bits_per_sample = 20;
  98052. break;
  98053. case 6:
  98054. decoder->private_->frame.header.bits_per_sample = 24;
  98055. break;
  98056. case 3:
  98057. case 7:
  98058. is_unparseable = true;
  98059. break;
  98060. default:
  98061. FLAC__ASSERT(0);
  98062. break;
  98063. }
  98064. /* check to make sure that reserved bit is 0 */
  98065. if(raw_header[3] & 0x01) /* MAGIC NUMBER */
  98066. is_unparseable = true;
  98067. /* read the frame's starting sample number (or frame number as the case may be) */
  98068. if(
  98069. raw_header[1] & 0x01 ||
  98070. /*@@@ 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 */
  98071. (decoder->private_->has_stream_info && decoder->private_->stream_info.data.stream_info.min_blocksize != decoder->private_->stream_info.data.stream_info.max_blocksize)
  98072. ) { /* variable blocksize */
  98073. if(!FLAC__bitreader_read_utf8_uint64(decoder->private_->input, &xx, raw_header, &raw_header_len))
  98074. return false; /* read_callback_ sets the state for us */
  98075. if(xx == FLAC__U64L(0xffffffffffffffff)) { /* i.e. non-UTF8 code... */
  98076. decoder->private_->lookahead = raw_header[raw_header_len-1]; /* back up as much as we can */
  98077. decoder->private_->cached = true;
  98078. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER);
  98079. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  98080. return true;
  98081. }
  98082. decoder->private_->frame.header.number_type = FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER;
  98083. decoder->private_->frame.header.number.sample_number = xx;
  98084. }
  98085. else { /* fixed blocksize */
  98086. if(!FLAC__bitreader_read_utf8_uint32(decoder->private_->input, &x, raw_header, &raw_header_len))
  98087. return false; /* read_callback_ sets the state for us */
  98088. if(x == 0xffffffff) { /* i.e. non-UTF8 code... */
  98089. decoder->private_->lookahead = raw_header[raw_header_len-1]; /* back up as much as we can */
  98090. decoder->private_->cached = true;
  98091. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER);
  98092. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  98093. return true;
  98094. }
  98095. decoder->private_->frame.header.number_type = FLAC__FRAME_NUMBER_TYPE_FRAME_NUMBER;
  98096. decoder->private_->frame.header.number.frame_number = x;
  98097. }
  98098. if(blocksize_hint) {
  98099. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8))
  98100. return false; /* read_callback_ sets the state for us */
  98101. raw_header[raw_header_len++] = (FLAC__byte)x;
  98102. if(blocksize_hint == 7) {
  98103. FLAC__uint32 _x;
  98104. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &_x, 8))
  98105. return false; /* read_callback_ sets the state for us */
  98106. raw_header[raw_header_len++] = (FLAC__byte)_x;
  98107. x = (x << 8) | _x;
  98108. }
  98109. decoder->private_->frame.header.blocksize = x+1;
  98110. }
  98111. if(sample_rate_hint) {
  98112. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8))
  98113. return false; /* read_callback_ sets the state for us */
  98114. raw_header[raw_header_len++] = (FLAC__byte)x;
  98115. if(sample_rate_hint != 12) {
  98116. FLAC__uint32 _x;
  98117. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &_x, 8))
  98118. return false; /* read_callback_ sets the state for us */
  98119. raw_header[raw_header_len++] = (FLAC__byte)_x;
  98120. x = (x << 8) | _x;
  98121. }
  98122. if(sample_rate_hint == 12)
  98123. decoder->private_->frame.header.sample_rate = x*1000;
  98124. else if(sample_rate_hint == 13)
  98125. decoder->private_->frame.header.sample_rate = x;
  98126. else
  98127. decoder->private_->frame.header.sample_rate = x*10;
  98128. }
  98129. /* read the CRC-8 byte */
  98130. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8))
  98131. return false; /* read_callback_ sets the state for us */
  98132. crc8 = (FLAC__byte)x;
  98133. if(FLAC__crc8(raw_header, raw_header_len) != crc8) {
  98134. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER);
  98135. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  98136. return true;
  98137. }
  98138. /* calculate the sample number from the frame number if needed */
  98139. decoder->private_->next_fixed_block_size = 0;
  98140. if(decoder->private_->frame.header.number_type == FLAC__FRAME_NUMBER_TYPE_FRAME_NUMBER) {
  98141. x = decoder->private_->frame.header.number.frame_number;
  98142. decoder->private_->frame.header.number_type = FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER;
  98143. if(decoder->private_->fixed_block_size)
  98144. decoder->private_->frame.header.number.sample_number = (FLAC__uint64)decoder->private_->fixed_block_size * (FLAC__uint64)x;
  98145. else if(decoder->private_->has_stream_info) {
  98146. if(decoder->private_->stream_info.data.stream_info.min_blocksize == decoder->private_->stream_info.data.stream_info.max_blocksize) {
  98147. decoder->private_->frame.header.number.sample_number = (FLAC__uint64)decoder->private_->stream_info.data.stream_info.min_blocksize * (FLAC__uint64)x;
  98148. decoder->private_->next_fixed_block_size = decoder->private_->stream_info.data.stream_info.max_blocksize;
  98149. }
  98150. else
  98151. is_unparseable = true;
  98152. }
  98153. else if(x == 0) {
  98154. decoder->private_->frame.header.number.sample_number = 0;
  98155. decoder->private_->next_fixed_block_size = decoder->private_->frame.header.blocksize;
  98156. }
  98157. else {
  98158. /* can only get here if the stream has invalid frame numbering and no STREAMINFO, so assume it's not the last (possibly short) frame */
  98159. decoder->private_->frame.header.number.sample_number = (FLAC__uint64)decoder->private_->frame.header.blocksize * (FLAC__uint64)x;
  98160. }
  98161. }
  98162. if(is_unparseable) {
  98163. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM);
  98164. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  98165. return true;
  98166. }
  98167. return true;
  98168. }
  98169. FLAC__bool read_subframe_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, FLAC__bool do_full_decode)
  98170. {
  98171. FLAC__uint32 x;
  98172. FLAC__bool wasted_bits;
  98173. unsigned i;
  98174. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8)) /* MAGIC NUMBER */
  98175. return false; /* read_callback_ sets the state for us */
  98176. wasted_bits = (x & 1);
  98177. x &= 0xfe;
  98178. if(wasted_bits) {
  98179. unsigned u;
  98180. if(!FLAC__bitreader_read_unary_unsigned(decoder->private_->input, &u))
  98181. return false; /* read_callback_ sets the state for us */
  98182. decoder->private_->frame.subframes[channel].wasted_bits = u+1;
  98183. bps -= decoder->private_->frame.subframes[channel].wasted_bits;
  98184. }
  98185. else
  98186. decoder->private_->frame.subframes[channel].wasted_bits = 0;
  98187. /*
  98188. * Lots of magic numbers here
  98189. */
  98190. if(x & 0x80) {
  98191. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC);
  98192. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  98193. return true;
  98194. }
  98195. else if(x == 0) {
  98196. if(!read_subframe_constant_(decoder, channel, bps, do_full_decode))
  98197. return false;
  98198. }
  98199. else if(x == 2) {
  98200. if(!read_subframe_verbatim_(decoder, channel, bps, do_full_decode))
  98201. return false;
  98202. }
  98203. else if(x < 16) {
  98204. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM);
  98205. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  98206. return true;
  98207. }
  98208. else if(x <= 24) {
  98209. if(!read_subframe_fixed_(decoder, channel, bps, (x>>1)&7, do_full_decode))
  98210. return false;
  98211. if(decoder->protected_->state == FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC) /* means bad sync or got corruption */
  98212. return true;
  98213. }
  98214. else if(x < 64) {
  98215. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM);
  98216. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  98217. return true;
  98218. }
  98219. else {
  98220. if(!read_subframe_lpc_(decoder, channel, bps, ((x>>1)&31)+1, do_full_decode))
  98221. return false;
  98222. if(decoder->protected_->state == FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC) /* means bad sync or got corruption */
  98223. return true;
  98224. }
  98225. if(wasted_bits && do_full_decode) {
  98226. x = decoder->private_->frame.subframes[channel].wasted_bits;
  98227. for(i = 0; i < decoder->private_->frame.header.blocksize; i++)
  98228. decoder->private_->output[channel][i] <<= x;
  98229. }
  98230. return true;
  98231. }
  98232. FLAC__bool read_subframe_constant_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, FLAC__bool do_full_decode)
  98233. {
  98234. FLAC__Subframe_Constant *subframe = &decoder->private_->frame.subframes[channel].data.constant;
  98235. FLAC__int32 x;
  98236. unsigned i;
  98237. FLAC__int32 *output = decoder->private_->output[channel];
  98238. decoder->private_->frame.subframes[channel].type = FLAC__SUBFRAME_TYPE_CONSTANT;
  98239. if(!FLAC__bitreader_read_raw_int32(decoder->private_->input, &x, bps))
  98240. return false; /* read_callback_ sets the state for us */
  98241. subframe->value = x;
  98242. /* decode the subframe */
  98243. if(do_full_decode) {
  98244. for(i = 0; i < decoder->private_->frame.header.blocksize; i++)
  98245. output[i] = x;
  98246. }
  98247. return true;
  98248. }
  98249. FLAC__bool read_subframe_fixed_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, const unsigned order, FLAC__bool do_full_decode)
  98250. {
  98251. FLAC__Subframe_Fixed *subframe = &decoder->private_->frame.subframes[channel].data.fixed;
  98252. FLAC__int32 i32;
  98253. FLAC__uint32 u32;
  98254. unsigned u;
  98255. decoder->private_->frame.subframes[channel].type = FLAC__SUBFRAME_TYPE_FIXED;
  98256. subframe->residual = decoder->private_->residual[channel];
  98257. subframe->order = order;
  98258. /* read warm-up samples */
  98259. for(u = 0; u < order; u++) {
  98260. if(!FLAC__bitreader_read_raw_int32(decoder->private_->input, &i32, bps))
  98261. return false; /* read_callback_ sets the state for us */
  98262. subframe->warmup[u] = i32;
  98263. }
  98264. /* read entropy coding method info */
  98265. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &u32, FLAC__ENTROPY_CODING_METHOD_TYPE_LEN))
  98266. return false; /* read_callback_ sets the state for us */
  98267. subframe->entropy_coding_method.type = (FLAC__EntropyCodingMethodType)u32;
  98268. switch(subframe->entropy_coding_method.type) {
  98269. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE:
  98270. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2:
  98271. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &u32, FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN))
  98272. return false; /* read_callback_ sets the state for us */
  98273. subframe->entropy_coding_method.data.partitioned_rice.order = u32;
  98274. subframe->entropy_coding_method.data.partitioned_rice.contents = &decoder->private_->partitioned_rice_contents[channel];
  98275. break;
  98276. default:
  98277. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM);
  98278. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  98279. return true;
  98280. }
  98281. /* read residual */
  98282. switch(subframe->entropy_coding_method.type) {
  98283. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE:
  98284. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2:
  98285. 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))
  98286. return false;
  98287. break;
  98288. default:
  98289. FLAC__ASSERT(0);
  98290. }
  98291. /* decode the subframe */
  98292. if(do_full_decode) {
  98293. memcpy(decoder->private_->output[channel], subframe->warmup, sizeof(FLAC__int32) * order);
  98294. FLAC__fixed_restore_signal(decoder->private_->residual[channel], decoder->private_->frame.header.blocksize-order, order, decoder->private_->output[channel]+order);
  98295. }
  98296. return true;
  98297. }
  98298. FLAC__bool read_subframe_lpc_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, const unsigned order, FLAC__bool do_full_decode)
  98299. {
  98300. FLAC__Subframe_LPC *subframe = &decoder->private_->frame.subframes[channel].data.lpc;
  98301. FLAC__int32 i32;
  98302. FLAC__uint32 u32;
  98303. unsigned u;
  98304. decoder->private_->frame.subframes[channel].type = FLAC__SUBFRAME_TYPE_LPC;
  98305. subframe->residual = decoder->private_->residual[channel];
  98306. subframe->order = order;
  98307. /* read warm-up samples */
  98308. for(u = 0; u < order; u++) {
  98309. if(!FLAC__bitreader_read_raw_int32(decoder->private_->input, &i32, bps))
  98310. return false; /* read_callback_ sets the state for us */
  98311. subframe->warmup[u] = i32;
  98312. }
  98313. /* read qlp coeff precision */
  98314. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &u32, FLAC__SUBFRAME_LPC_QLP_COEFF_PRECISION_LEN))
  98315. return false; /* read_callback_ sets the state for us */
  98316. if(u32 == (1u << FLAC__SUBFRAME_LPC_QLP_COEFF_PRECISION_LEN) - 1) {
  98317. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC);
  98318. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  98319. return true;
  98320. }
  98321. subframe->qlp_coeff_precision = u32+1;
  98322. /* read qlp shift */
  98323. if(!FLAC__bitreader_read_raw_int32(decoder->private_->input, &i32, FLAC__SUBFRAME_LPC_QLP_SHIFT_LEN))
  98324. return false; /* read_callback_ sets the state for us */
  98325. subframe->quantization_level = i32;
  98326. /* read quantized lp coefficiencts */
  98327. for(u = 0; u < order; u++) {
  98328. if(!FLAC__bitreader_read_raw_int32(decoder->private_->input, &i32, subframe->qlp_coeff_precision))
  98329. return false; /* read_callback_ sets the state for us */
  98330. subframe->qlp_coeff[u] = i32;
  98331. }
  98332. /* read entropy coding method info */
  98333. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &u32, FLAC__ENTROPY_CODING_METHOD_TYPE_LEN))
  98334. return false; /* read_callback_ sets the state for us */
  98335. subframe->entropy_coding_method.type = (FLAC__EntropyCodingMethodType)u32;
  98336. switch(subframe->entropy_coding_method.type) {
  98337. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE:
  98338. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2:
  98339. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &u32, FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN))
  98340. return false; /* read_callback_ sets the state for us */
  98341. subframe->entropy_coding_method.data.partitioned_rice.order = u32;
  98342. subframe->entropy_coding_method.data.partitioned_rice.contents = &decoder->private_->partitioned_rice_contents[channel];
  98343. break;
  98344. default:
  98345. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM);
  98346. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  98347. return true;
  98348. }
  98349. /* read residual */
  98350. switch(subframe->entropy_coding_method.type) {
  98351. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE:
  98352. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2:
  98353. 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))
  98354. return false;
  98355. break;
  98356. default:
  98357. FLAC__ASSERT(0);
  98358. }
  98359. /* decode the subframe */
  98360. if(do_full_decode) {
  98361. memcpy(decoder->private_->output[channel], subframe->warmup, sizeof(FLAC__int32) * order);
  98362. /*@@@@@@ technically not pessimistic enough, should be more like
  98363. if( (FLAC__uint64)order * ((((FLAC__uint64)1)<<bps)-1) * ((1<<subframe->qlp_coeff_precision)-1) < (((FLAC__uint64)-1) << 32) )
  98364. */
  98365. if(bps + subframe->qlp_coeff_precision + FLAC__bitmath_ilog2(order) <= 32)
  98366. if(bps <= 16 && subframe->qlp_coeff_precision <= 16) {
  98367. if(order <= 8)
  98368. 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);
  98369. else
  98370. 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);
  98371. }
  98372. else
  98373. 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);
  98374. else
  98375. 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);
  98376. }
  98377. return true;
  98378. }
  98379. FLAC__bool read_subframe_verbatim_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, FLAC__bool do_full_decode)
  98380. {
  98381. FLAC__Subframe_Verbatim *subframe = &decoder->private_->frame.subframes[channel].data.verbatim;
  98382. FLAC__int32 x, *residual = decoder->private_->residual[channel];
  98383. unsigned i;
  98384. decoder->private_->frame.subframes[channel].type = FLAC__SUBFRAME_TYPE_VERBATIM;
  98385. subframe->data = residual;
  98386. for(i = 0; i < decoder->private_->frame.header.blocksize; i++) {
  98387. if(!FLAC__bitreader_read_raw_int32(decoder->private_->input, &x, bps))
  98388. return false; /* read_callback_ sets the state for us */
  98389. residual[i] = x;
  98390. }
  98391. /* decode the subframe */
  98392. if(do_full_decode)
  98393. memcpy(decoder->private_->output[channel], subframe->data, sizeof(FLAC__int32) * decoder->private_->frame.header.blocksize);
  98394. return true;
  98395. }
  98396. 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)
  98397. {
  98398. FLAC__uint32 rice_parameter;
  98399. int i;
  98400. unsigned partition, sample, u;
  98401. const unsigned partitions = 1u << partition_order;
  98402. const unsigned partition_samples = partition_order > 0? decoder->private_->frame.header.blocksize >> partition_order : decoder->private_->frame.header.blocksize - predictor_order;
  98403. const unsigned plen = is_extended? FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_PARAMETER_LEN : FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_PARAMETER_LEN;
  98404. const unsigned pesc = is_extended? FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_ESCAPE_PARAMETER : FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER;
  98405. /* sanity checks */
  98406. if(partition_order == 0) {
  98407. if(decoder->private_->frame.header.blocksize < predictor_order) {
  98408. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC);
  98409. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  98410. return true;
  98411. }
  98412. }
  98413. else {
  98414. if(partition_samples < predictor_order) {
  98415. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC);
  98416. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  98417. return true;
  98418. }
  98419. }
  98420. if(!FLAC__format_entropy_coding_method_partitioned_rice_contents_ensure_size(partitioned_rice_contents, max(6, partition_order))) {
  98421. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  98422. return false;
  98423. }
  98424. sample = 0;
  98425. for(partition = 0; partition < partitions; partition++) {
  98426. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &rice_parameter, plen))
  98427. return false; /* read_callback_ sets the state for us */
  98428. partitioned_rice_contents->parameters[partition] = rice_parameter;
  98429. if(rice_parameter < pesc) {
  98430. partitioned_rice_contents->raw_bits[partition] = 0;
  98431. u = (partition_order == 0 || partition > 0)? partition_samples : partition_samples - predictor_order;
  98432. if(!decoder->private_->local_bitreader_read_rice_signed_block(decoder->private_->input, (int*) residual + sample, u, rice_parameter))
  98433. return false; /* read_callback_ sets the state for us */
  98434. sample += u;
  98435. }
  98436. else {
  98437. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &rice_parameter, FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_RAW_LEN))
  98438. return false; /* read_callback_ sets the state for us */
  98439. partitioned_rice_contents->raw_bits[partition] = rice_parameter;
  98440. for(u = (partition_order == 0 || partition > 0)? 0 : predictor_order; u < partition_samples; u++, sample++) {
  98441. if(!FLAC__bitreader_read_raw_int32(decoder->private_->input, (FLAC__int32*) &i, rice_parameter))
  98442. return false; /* read_callback_ sets the state for us */
  98443. residual[sample] = i;
  98444. }
  98445. }
  98446. }
  98447. return true;
  98448. }
  98449. FLAC__bool read_zero_padding_(FLAC__StreamDecoder *decoder)
  98450. {
  98451. if(!FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input)) {
  98452. FLAC__uint32 zero = 0;
  98453. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &zero, FLAC__bitreader_bits_left_for_byte_alignment(decoder->private_->input)))
  98454. return false; /* read_callback_ sets the state for us */
  98455. if(zero != 0) {
  98456. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC);
  98457. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  98458. }
  98459. }
  98460. return true;
  98461. }
  98462. FLAC__bool read_callback_(FLAC__byte buffer[], size_t *bytes, void *client_data)
  98463. {
  98464. FLAC__StreamDecoder *decoder = (FLAC__StreamDecoder *)client_data;
  98465. if(
  98466. #if FLAC__HAS_OGG
  98467. /* see [1] HACK NOTE below for why we don't call the eof_callback when decoding Ogg FLAC */
  98468. !decoder->private_->is_ogg &&
  98469. #endif
  98470. decoder->private_->eof_callback && decoder->private_->eof_callback(decoder, decoder->private_->client_data)
  98471. ) {
  98472. *bytes = 0;
  98473. decoder->protected_->state = FLAC__STREAM_DECODER_END_OF_STREAM;
  98474. return false;
  98475. }
  98476. else if(*bytes > 0) {
  98477. /* While seeking, it is possible for our seek to land in the
  98478. * middle of audio data that looks exactly like a frame header
  98479. * from a future version of an encoder. When that happens, our
  98480. * error callback will get an
  98481. * FLAC__STREAM_DECODER_UNPARSEABLE_STREAM and increment its
  98482. * unparseable_frame_count. But there is a remote possibility
  98483. * that it is properly synced at such a "future-codec frame",
  98484. * so to make sure, we wait to see many "unparseable" errors in
  98485. * a row before bailing out.
  98486. */
  98487. if(decoder->private_->is_seeking && decoder->private_->unparseable_frame_count > 20) {
  98488. decoder->protected_->state = FLAC__STREAM_DECODER_ABORTED;
  98489. return false;
  98490. }
  98491. else {
  98492. const FLAC__StreamDecoderReadStatus status =
  98493. #if FLAC__HAS_OGG
  98494. decoder->private_->is_ogg?
  98495. read_callback_ogg_aspect_(decoder, buffer, bytes) :
  98496. #endif
  98497. decoder->private_->read_callback(decoder, buffer, bytes, decoder->private_->client_data)
  98498. ;
  98499. if(status == FLAC__STREAM_DECODER_READ_STATUS_ABORT) {
  98500. decoder->protected_->state = FLAC__STREAM_DECODER_ABORTED;
  98501. return false;
  98502. }
  98503. else if(*bytes == 0) {
  98504. if(
  98505. status == FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM ||
  98506. (
  98507. #if FLAC__HAS_OGG
  98508. /* see [1] HACK NOTE below for why we don't call the eof_callback when decoding Ogg FLAC */
  98509. !decoder->private_->is_ogg &&
  98510. #endif
  98511. decoder->private_->eof_callback && decoder->private_->eof_callback(decoder, decoder->private_->client_data)
  98512. )
  98513. ) {
  98514. decoder->protected_->state = FLAC__STREAM_DECODER_END_OF_STREAM;
  98515. return false;
  98516. }
  98517. else
  98518. return true;
  98519. }
  98520. else
  98521. return true;
  98522. }
  98523. }
  98524. else {
  98525. /* abort to avoid a deadlock */
  98526. decoder->protected_->state = FLAC__STREAM_DECODER_ABORTED;
  98527. return false;
  98528. }
  98529. /* [1] @@@ HACK NOTE: The end-of-stream checking has to be hacked around
  98530. * for Ogg FLAC. This is because the ogg decoder aspect can lose sync
  98531. * and at the same time hit the end of the stream (for example, seeking
  98532. * to a point that is after the beginning of the last Ogg page). There
  98533. * is no way to report an Ogg sync loss through the callbacks (see note
  98534. * in read_callback_ogg_aspect_()) so it returns CONTINUE with *bytes==0.
  98535. * So to keep the decoder from stopping at this point we gate the call
  98536. * to the eof_callback and let the Ogg decoder aspect set the
  98537. * end-of-stream state when it is needed.
  98538. */
  98539. }
  98540. #if FLAC__HAS_OGG
  98541. FLAC__StreamDecoderReadStatus read_callback_ogg_aspect_(const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes)
  98542. {
  98543. switch(FLAC__ogg_decoder_aspect_read_callback_wrapper(&decoder->protected_->ogg_decoder_aspect, buffer, bytes, read_callback_proxy_, decoder, decoder->private_->client_data)) {
  98544. case FLAC__OGG_DECODER_ASPECT_READ_STATUS_OK:
  98545. return FLAC__STREAM_DECODER_READ_STATUS_CONTINUE;
  98546. /* we don't really have a way to handle lost sync via read
  98547. * callback so we'll let it pass and let the underlying
  98548. * FLAC decoder catch the error
  98549. */
  98550. case FLAC__OGG_DECODER_ASPECT_READ_STATUS_LOST_SYNC:
  98551. return FLAC__STREAM_DECODER_READ_STATUS_CONTINUE;
  98552. case FLAC__OGG_DECODER_ASPECT_READ_STATUS_END_OF_STREAM:
  98553. return FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM;
  98554. case FLAC__OGG_DECODER_ASPECT_READ_STATUS_NOT_FLAC:
  98555. case FLAC__OGG_DECODER_ASPECT_READ_STATUS_UNSUPPORTED_MAPPING_VERSION:
  98556. case FLAC__OGG_DECODER_ASPECT_READ_STATUS_ABORT:
  98557. case FLAC__OGG_DECODER_ASPECT_READ_STATUS_ERROR:
  98558. case FLAC__OGG_DECODER_ASPECT_READ_STATUS_MEMORY_ALLOCATION_ERROR:
  98559. return FLAC__STREAM_DECODER_READ_STATUS_ABORT;
  98560. default:
  98561. FLAC__ASSERT(0);
  98562. /* double protection */
  98563. return FLAC__STREAM_DECODER_READ_STATUS_ABORT;
  98564. }
  98565. }
  98566. FLAC__OggDecoderAspectReadStatus read_callback_proxy_(const void *void_decoder, FLAC__byte buffer[], size_t *bytes, void *client_data)
  98567. {
  98568. FLAC__StreamDecoder *decoder = (FLAC__StreamDecoder*)void_decoder;
  98569. switch(decoder->private_->read_callback(decoder, buffer, bytes, client_data)) {
  98570. case FLAC__STREAM_DECODER_READ_STATUS_CONTINUE:
  98571. return FLAC__OGG_DECODER_ASPECT_READ_STATUS_OK;
  98572. case FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM:
  98573. return FLAC__OGG_DECODER_ASPECT_READ_STATUS_END_OF_STREAM;
  98574. case FLAC__STREAM_DECODER_READ_STATUS_ABORT:
  98575. return FLAC__OGG_DECODER_ASPECT_READ_STATUS_ABORT;
  98576. default:
  98577. /* double protection: */
  98578. FLAC__ASSERT(0);
  98579. return FLAC__OGG_DECODER_ASPECT_READ_STATUS_ABORT;
  98580. }
  98581. }
  98582. #endif
  98583. FLAC__StreamDecoderWriteStatus write_audio_frame_to_client_(FLAC__StreamDecoder *decoder, const FLAC__Frame *frame, const FLAC__int32 * const buffer[])
  98584. {
  98585. if(decoder->private_->is_seeking) {
  98586. FLAC__uint64 this_frame_sample = frame->header.number.sample_number;
  98587. FLAC__uint64 next_frame_sample = this_frame_sample + (FLAC__uint64)frame->header.blocksize;
  98588. FLAC__uint64 target_sample = decoder->private_->target_sample;
  98589. FLAC__ASSERT(frame->header.number_type == FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER);
  98590. #if FLAC__HAS_OGG
  98591. decoder->private_->got_a_frame = true;
  98592. #endif
  98593. decoder->private_->last_frame = *frame; /* save the frame */
  98594. if(this_frame_sample <= target_sample && target_sample < next_frame_sample) { /* we hit our target frame */
  98595. unsigned delta = (unsigned)(target_sample - this_frame_sample);
  98596. /* kick out of seek mode */
  98597. decoder->private_->is_seeking = false;
  98598. /* shift out the samples before target_sample */
  98599. if(delta > 0) {
  98600. unsigned channel;
  98601. const FLAC__int32 *newbuffer[FLAC__MAX_CHANNELS];
  98602. for(channel = 0; channel < frame->header.channels; channel++)
  98603. newbuffer[channel] = buffer[channel] + delta;
  98604. decoder->private_->last_frame.header.blocksize -= delta;
  98605. decoder->private_->last_frame.header.number.sample_number += (FLAC__uint64)delta;
  98606. /* write the relevant samples */
  98607. return decoder->private_->write_callback(decoder, &decoder->private_->last_frame, newbuffer, decoder->private_->client_data);
  98608. }
  98609. else {
  98610. /* write the relevant samples */
  98611. return decoder->private_->write_callback(decoder, frame, buffer, decoder->private_->client_data);
  98612. }
  98613. }
  98614. return FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE;
  98615. }
  98616. /*
  98617. * If we never got STREAMINFO, turn off MD5 checking to save
  98618. * cycles since we don't have a sum to compare to anyway
  98619. */
  98620. if(!decoder->private_->has_stream_info)
  98621. decoder->private_->do_md5_checking = false;
  98622. if(decoder->private_->do_md5_checking) {
  98623. if(!FLAC__MD5Accumulate(&decoder->private_->md5context, buffer, frame->header.channels, frame->header.blocksize, (frame->header.bits_per_sample+7) / 8))
  98624. return FLAC__STREAM_DECODER_WRITE_STATUS_ABORT;
  98625. }
  98626. return decoder->private_->write_callback(decoder, frame, buffer, decoder->private_->client_data);
  98627. }
  98628. void send_error_to_client_(const FLAC__StreamDecoder *decoder, FLAC__StreamDecoderErrorStatus status)
  98629. {
  98630. if(!decoder->private_->is_seeking)
  98631. decoder->private_->error_callback(decoder, status, decoder->private_->client_data);
  98632. else if(status == FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM)
  98633. decoder->private_->unparseable_frame_count++;
  98634. }
  98635. FLAC__bool seek_to_absolute_sample_(FLAC__StreamDecoder *decoder, FLAC__uint64 stream_length, FLAC__uint64 target_sample)
  98636. {
  98637. FLAC__uint64 first_frame_offset = decoder->private_->first_frame_offset, lower_bound, upper_bound, lower_bound_sample, upper_bound_sample, this_frame_sample;
  98638. FLAC__int64 pos = -1;
  98639. int i;
  98640. unsigned approx_bytes_per_frame;
  98641. FLAC__bool first_seek = true;
  98642. const FLAC__uint64 total_samples = FLAC__stream_decoder_get_total_samples(decoder);
  98643. const unsigned min_blocksize = decoder->private_->stream_info.data.stream_info.min_blocksize;
  98644. const unsigned max_blocksize = decoder->private_->stream_info.data.stream_info.max_blocksize;
  98645. const unsigned max_framesize = decoder->private_->stream_info.data.stream_info.max_framesize;
  98646. const unsigned min_framesize = decoder->private_->stream_info.data.stream_info.min_framesize;
  98647. /* take these from the current frame in case they've changed mid-stream */
  98648. unsigned channels = FLAC__stream_decoder_get_channels(decoder);
  98649. unsigned bps = FLAC__stream_decoder_get_bits_per_sample(decoder);
  98650. const FLAC__StreamMetadata_SeekTable *seek_table = decoder->private_->has_seek_table? &decoder->private_->seek_table.data.seek_table : 0;
  98651. /* use values from stream info if we didn't decode a frame */
  98652. if(channels == 0)
  98653. channels = decoder->private_->stream_info.data.stream_info.channels;
  98654. if(bps == 0)
  98655. bps = decoder->private_->stream_info.data.stream_info.bits_per_sample;
  98656. /* we are just guessing here */
  98657. if(max_framesize > 0)
  98658. approx_bytes_per_frame = (max_framesize + min_framesize) / 2 + 1;
  98659. /*
  98660. * Check if it's a known fixed-blocksize stream. Note that though
  98661. * the spec doesn't allow zeroes in the STREAMINFO block, we may
  98662. * never get a STREAMINFO block when decoding so the value of
  98663. * min_blocksize might be zero.
  98664. */
  98665. else if(min_blocksize == max_blocksize && min_blocksize > 0) {
  98666. /* note there are no () around 'bps/8' to keep precision up since it's an integer calulation */
  98667. approx_bytes_per_frame = min_blocksize * channels * bps/8 + 64;
  98668. }
  98669. else
  98670. approx_bytes_per_frame = 4096 * channels * bps/8 + 64;
  98671. /*
  98672. * First, we set an upper and lower bound on where in the
  98673. * stream we will search. For now we assume the worst case
  98674. * scenario, which is our best guess at the beginning of
  98675. * the first frame and end of the stream.
  98676. */
  98677. lower_bound = first_frame_offset;
  98678. lower_bound_sample = 0;
  98679. upper_bound = stream_length;
  98680. upper_bound_sample = total_samples > 0 ? total_samples : target_sample /*estimate it*/;
  98681. /*
  98682. * Now we refine the bounds if we have a seektable with
  98683. * suitable points. Note that according to the spec they
  98684. * must be ordered by ascending sample number.
  98685. *
  98686. * Note: to protect against invalid seek tables we will ignore points
  98687. * that have frame_samples==0 or sample_number>=total_samples
  98688. */
  98689. if(seek_table) {
  98690. FLAC__uint64 new_lower_bound = lower_bound;
  98691. FLAC__uint64 new_upper_bound = upper_bound;
  98692. FLAC__uint64 new_lower_bound_sample = lower_bound_sample;
  98693. FLAC__uint64 new_upper_bound_sample = upper_bound_sample;
  98694. /* find the closest seek point <= target_sample, if it exists */
  98695. for(i = (int)seek_table->num_points - 1; i >= 0; i--) {
  98696. if(
  98697. seek_table->points[i].sample_number != FLAC__STREAM_METADATA_SEEKPOINT_PLACEHOLDER &&
  98698. seek_table->points[i].frame_samples > 0 && /* defense against bad seekpoints */
  98699. (total_samples <= 0 || seek_table->points[i].sample_number < total_samples) && /* defense against bad seekpoints */
  98700. seek_table->points[i].sample_number <= target_sample
  98701. )
  98702. break;
  98703. }
  98704. if(i >= 0) { /* i.e. we found a suitable seek point... */
  98705. new_lower_bound = first_frame_offset + seek_table->points[i].stream_offset;
  98706. new_lower_bound_sample = seek_table->points[i].sample_number;
  98707. }
  98708. /* find the closest seek point > target_sample, if it exists */
  98709. for(i = 0; i < (int)seek_table->num_points; i++) {
  98710. if(
  98711. seek_table->points[i].sample_number != FLAC__STREAM_METADATA_SEEKPOINT_PLACEHOLDER &&
  98712. seek_table->points[i].frame_samples > 0 && /* defense against bad seekpoints */
  98713. (total_samples <= 0 || seek_table->points[i].sample_number < total_samples) && /* defense against bad seekpoints */
  98714. seek_table->points[i].sample_number > target_sample
  98715. )
  98716. break;
  98717. }
  98718. if(i < (int)seek_table->num_points) { /* i.e. we found a suitable seek point... */
  98719. new_upper_bound = first_frame_offset + seek_table->points[i].stream_offset;
  98720. new_upper_bound_sample = seek_table->points[i].sample_number;
  98721. }
  98722. /* final protection against unsorted seek tables; keep original values if bogus */
  98723. if(new_upper_bound >= new_lower_bound) {
  98724. lower_bound = new_lower_bound;
  98725. upper_bound = new_upper_bound;
  98726. lower_bound_sample = new_lower_bound_sample;
  98727. upper_bound_sample = new_upper_bound_sample;
  98728. }
  98729. }
  98730. FLAC__ASSERT(upper_bound_sample >= lower_bound_sample);
  98731. /* there are 2 insidious ways that the following equality occurs, which
  98732. * we need to fix:
  98733. * 1) total_samples is 0 (unknown) and target_sample is 0
  98734. * 2) total_samples is 0 (unknown) and target_sample happens to be
  98735. * exactly equal to the last seek point in the seek table; this
  98736. * means there is no seek point above it, and upper_bound_samples
  98737. * remains equal to the estimate (of target_samples) we made above
  98738. * in either case it does not hurt to move upper_bound_sample up by 1
  98739. */
  98740. if(upper_bound_sample == lower_bound_sample)
  98741. upper_bound_sample++;
  98742. decoder->private_->target_sample = target_sample;
  98743. while(1) {
  98744. /* check if the bounds are still ok */
  98745. if (lower_bound_sample >= upper_bound_sample || lower_bound > upper_bound) {
  98746. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  98747. return false;
  98748. }
  98749. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  98750. #if defined _MSC_VER || defined __MINGW32__
  98751. /* with VC++ you have to spoon feed it the casting */
  98752. 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;
  98753. #else
  98754. 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;
  98755. #endif
  98756. #else
  98757. /* a little less accurate: */
  98758. if(upper_bound - lower_bound < 0xffffffff)
  98759. 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;
  98760. else /* @@@ WATCHOUT, ~2TB limit */
  98761. 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;
  98762. #endif
  98763. if(pos >= (FLAC__int64)upper_bound)
  98764. pos = (FLAC__int64)upper_bound - 1;
  98765. if(pos < (FLAC__int64)lower_bound)
  98766. pos = (FLAC__int64)lower_bound;
  98767. if(decoder->private_->seek_callback(decoder, (FLAC__uint64)pos, decoder->private_->client_data) != FLAC__STREAM_DECODER_SEEK_STATUS_OK) {
  98768. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  98769. return false;
  98770. }
  98771. if(!FLAC__stream_decoder_flush(decoder)) {
  98772. /* above call sets the state for us */
  98773. return false;
  98774. }
  98775. /* Now we need to get a frame. First we need to reset our
  98776. * unparseable_frame_count; if we get too many unparseable
  98777. * frames in a row, the read callback will return
  98778. * FLAC__STREAM_DECODER_READ_STATUS_ABORT, causing
  98779. * FLAC__stream_decoder_process_single() to return false.
  98780. */
  98781. decoder->private_->unparseable_frame_count = 0;
  98782. if(!FLAC__stream_decoder_process_single(decoder)) {
  98783. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  98784. return false;
  98785. }
  98786. /* our write callback will change the state when it gets to the target frame */
  98787. /* 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 */
  98788. #if 0
  98789. /*@@@@@@ used to be the following; not clear if the check for end of stream is needed anymore */
  98790. if(decoder->protected_->state != FLAC__SEEKABLE_STREAM_DECODER_SEEKING && decoder->protected_->state != FLAC__STREAM_DECODER_END_OF_STREAM)
  98791. break;
  98792. #endif
  98793. if(!decoder->private_->is_seeking)
  98794. break;
  98795. FLAC__ASSERT(decoder->private_->last_frame.header.number_type == FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER);
  98796. this_frame_sample = decoder->private_->last_frame.header.number.sample_number;
  98797. if (0 == decoder->private_->samples_decoded || (this_frame_sample + decoder->private_->last_frame.header.blocksize >= upper_bound_sample && !first_seek)) {
  98798. if (pos == (FLAC__int64)lower_bound) {
  98799. /* can't move back any more than the first frame, something is fatally wrong */
  98800. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  98801. return false;
  98802. }
  98803. /* our last move backwards wasn't big enough, try again */
  98804. approx_bytes_per_frame = approx_bytes_per_frame? approx_bytes_per_frame * 2 : 16;
  98805. continue;
  98806. }
  98807. /* allow one seek over upper bound, so we can get a correct upper_bound_sample for streams with unknown total_samples */
  98808. first_seek = false;
  98809. /* make sure we are not seeking in corrupted stream */
  98810. if (this_frame_sample < lower_bound_sample) {
  98811. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  98812. return false;
  98813. }
  98814. /* we need to narrow the search */
  98815. if(target_sample < this_frame_sample) {
  98816. upper_bound_sample = this_frame_sample + decoder->private_->last_frame.header.blocksize;
  98817. /*@@@@@@ what will decode position be if at end of stream? */
  98818. if(!FLAC__stream_decoder_get_decode_position(decoder, &upper_bound)) {
  98819. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  98820. return false;
  98821. }
  98822. approx_bytes_per_frame = (unsigned)(2 * (upper_bound - pos) / 3 + 16);
  98823. }
  98824. else { /* target_sample >= this_frame_sample + this frame's blocksize */
  98825. lower_bound_sample = this_frame_sample + decoder->private_->last_frame.header.blocksize;
  98826. if(!FLAC__stream_decoder_get_decode_position(decoder, &lower_bound)) {
  98827. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  98828. return false;
  98829. }
  98830. approx_bytes_per_frame = (unsigned)(2 * (lower_bound - pos) / 3 + 16);
  98831. }
  98832. }
  98833. return true;
  98834. }
  98835. #if FLAC__HAS_OGG
  98836. FLAC__bool seek_to_absolute_sample_ogg_(FLAC__StreamDecoder *decoder, FLAC__uint64 stream_length, FLAC__uint64 target_sample)
  98837. {
  98838. FLAC__uint64 left_pos = 0, right_pos = stream_length;
  98839. FLAC__uint64 left_sample = 0, right_sample = FLAC__stream_decoder_get_total_samples(decoder);
  98840. FLAC__uint64 this_frame_sample = (FLAC__uint64)0 - 1;
  98841. FLAC__uint64 pos = 0; /* only initialized to avoid compiler warning */
  98842. FLAC__bool did_a_seek;
  98843. unsigned iteration = 0;
  98844. /* In the first iterations, we will calculate the target byte position
  98845. * by the distance from the target sample to left_sample and
  98846. * right_sample (let's call it "proportional search"). After that, we
  98847. * will switch to binary search.
  98848. */
  98849. unsigned BINARY_SEARCH_AFTER_ITERATION = 2;
  98850. /* We will switch to a linear search once our current sample is less
  98851. * than this number of samples ahead of the target sample
  98852. */
  98853. static const FLAC__uint64 LINEAR_SEARCH_WITHIN_SAMPLES = FLAC__MAX_BLOCK_SIZE * 2;
  98854. /* If the total number of samples is unknown, use a large value, and
  98855. * force binary search immediately.
  98856. */
  98857. if(right_sample == 0) {
  98858. right_sample = (FLAC__uint64)(-1);
  98859. BINARY_SEARCH_AFTER_ITERATION = 0;
  98860. }
  98861. decoder->private_->target_sample = target_sample;
  98862. for( ; ; iteration++) {
  98863. if (iteration == 0 || this_frame_sample > target_sample || target_sample - this_frame_sample > LINEAR_SEARCH_WITHIN_SAMPLES) {
  98864. if (iteration >= BINARY_SEARCH_AFTER_ITERATION) {
  98865. pos = (right_pos + left_pos) / 2;
  98866. }
  98867. else {
  98868. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  98869. #if defined _MSC_VER || defined __MINGW32__
  98870. /* with MSVC you have to spoon feed it the casting */
  98871. 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));
  98872. #else
  98873. pos = (FLAC__uint64)((FLAC__double)(target_sample - left_sample) / (FLAC__double)(right_sample - left_sample) * (FLAC__double)(right_pos - left_pos));
  98874. #endif
  98875. #else
  98876. /* a little less accurate: */
  98877. if ((target_sample-left_sample <= 0xffffffff) && (right_pos-left_pos <= 0xffffffff))
  98878. pos = (FLAC__int64)(((target_sample-left_sample) * (right_pos-left_pos)) / (right_sample-left_sample));
  98879. else /* @@@ WATCHOUT, ~2TB limit */
  98880. pos = (FLAC__int64)((((target_sample-left_sample)>>8) * ((right_pos-left_pos)>>8)) / ((right_sample-left_sample)>>16));
  98881. #endif
  98882. /* @@@ TODO: might want to limit pos to some distance
  98883. * before EOF, to make sure we land before the last frame,
  98884. * thereby getting a this_frame_sample and so having a better
  98885. * estimate.
  98886. */
  98887. }
  98888. /* physical seek */
  98889. if(decoder->private_->seek_callback((FLAC__StreamDecoder*)decoder, (FLAC__uint64)pos, decoder->private_->client_data) != FLAC__STREAM_DECODER_SEEK_STATUS_OK) {
  98890. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  98891. return false;
  98892. }
  98893. if(!FLAC__stream_decoder_flush(decoder)) {
  98894. /* above call sets the state for us */
  98895. return false;
  98896. }
  98897. did_a_seek = true;
  98898. }
  98899. else
  98900. did_a_seek = false;
  98901. decoder->private_->got_a_frame = false;
  98902. if(!FLAC__stream_decoder_process_single(decoder)) {
  98903. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  98904. return false;
  98905. }
  98906. if(!decoder->private_->got_a_frame) {
  98907. if(did_a_seek) {
  98908. /* this can happen if we seek to a point after the last frame; we drop
  98909. * to binary search right away in this case to avoid any wasted
  98910. * iterations of proportional search.
  98911. */
  98912. right_pos = pos;
  98913. BINARY_SEARCH_AFTER_ITERATION = 0;
  98914. }
  98915. else {
  98916. /* this can probably only happen if total_samples is unknown and the
  98917. * target_sample is past the end of the stream
  98918. */
  98919. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  98920. return false;
  98921. }
  98922. }
  98923. /* our write callback will change the state when it gets to the target frame */
  98924. else if(!decoder->private_->is_seeking) {
  98925. break;
  98926. }
  98927. else {
  98928. this_frame_sample = decoder->private_->last_frame.header.number.sample_number;
  98929. FLAC__ASSERT(decoder->private_->last_frame.header.number_type == FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER);
  98930. if (did_a_seek) {
  98931. if (this_frame_sample <= target_sample) {
  98932. /* The 'equal' case should not happen, since
  98933. * FLAC__stream_decoder_process_single()
  98934. * should recognize that it has hit the
  98935. * target sample and we would exit through
  98936. * the 'break' above.
  98937. */
  98938. FLAC__ASSERT(this_frame_sample != target_sample);
  98939. left_sample = this_frame_sample;
  98940. /* sanity check to avoid infinite loop */
  98941. if (left_pos == pos) {
  98942. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  98943. return false;
  98944. }
  98945. left_pos = pos;
  98946. }
  98947. else if(this_frame_sample > target_sample) {
  98948. right_sample = this_frame_sample;
  98949. /* sanity check to avoid infinite loop */
  98950. if (right_pos == pos) {
  98951. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  98952. return false;
  98953. }
  98954. right_pos = pos;
  98955. }
  98956. }
  98957. }
  98958. }
  98959. return true;
  98960. }
  98961. #endif
  98962. FLAC__StreamDecoderReadStatus file_read_callback_dec(const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes, void *client_data)
  98963. {
  98964. (void)client_data;
  98965. if(*bytes > 0) {
  98966. *bytes = fread(buffer, sizeof(FLAC__byte), *bytes, decoder->private_->file);
  98967. if(ferror(decoder->private_->file))
  98968. return FLAC__STREAM_DECODER_READ_STATUS_ABORT;
  98969. else if(*bytes == 0)
  98970. return FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM;
  98971. else
  98972. return FLAC__STREAM_DECODER_READ_STATUS_CONTINUE;
  98973. }
  98974. else
  98975. return FLAC__STREAM_DECODER_READ_STATUS_ABORT; /* abort to avoid a deadlock */
  98976. }
  98977. FLAC__StreamDecoderSeekStatus file_seek_callback_dec(const FLAC__StreamDecoder *decoder, FLAC__uint64 absolute_byte_offset, void *client_data)
  98978. {
  98979. (void)client_data;
  98980. if(decoder->private_->file == stdin)
  98981. return FLAC__STREAM_DECODER_SEEK_STATUS_UNSUPPORTED;
  98982. else if(fseeko(decoder->private_->file, (off_t)absolute_byte_offset, SEEK_SET) < 0)
  98983. return FLAC__STREAM_DECODER_SEEK_STATUS_ERROR;
  98984. else
  98985. return FLAC__STREAM_DECODER_SEEK_STATUS_OK;
  98986. }
  98987. FLAC__StreamDecoderTellStatus file_tell_callback_dec(const FLAC__StreamDecoder *decoder, FLAC__uint64 *absolute_byte_offset, void *client_data)
  98988. {
  98989. off_t pos;
  98990. (void)client_data;
  98991. if(decoder->private_->file == stdin)
  98992. return FLAC__STREAM_DECODER_TELL_STATUS_UNSUPPORTED;
  98993. else if((pos = ftello(decoder->private_->file)) < 0)
  98994. return FLAC__STREAM_DECODER_TELL_STATUS_ERROR;
  98995. else {
  98996. *absolute_byte_offset = (FLAC__uint64)pos;
  98997. return FLAC__STREAM_DECODER_TELL_STATUS_OK;
  98998. }
  98999. }
  99000. FLAC__StreamDecoderLengthStatus file_length_callback_(const FLAC__StreamDecoder *decoder, FLAC__uint64 *stream_length, void *client_data)
  99001. {
  99002. struct stat filestats;
  99003. (void)client_data;
  99004. if(decoder->private_->file == stdin)
  99005. return FLAC__STREAM_DECODER_LENGTH_STATUS_UNSUPPORTED;
  99006. else if(fstat(fileno(decoder->private_->file), &filestats) != 0)
  99007. return FLAC__STREAM_DECODER_LENGTH_STATUS_ERROR;
  99008. else {
  99009. *stream_length = (FLAC__uint64)filestats.st_size;
  99010. return FLAC__STREAM_DECODER_LENGTH_STATUS_OK;
  99011. }
  99012. }
  99013. FLAC__bool file_eof_callback_(const FLAC__StreamDecoder *decoder, void *client_data)
  99014. {
  99015. (void)client_data;
  99016. return feof(decoder->private_->file)? true : false;
  99017. }
  99018. #endif
  99019. /*** End of inlined file: stream_decoder.c ***/
  99020. /*** Start of inlined file: stream_encoder.c ***/
  99021. /*** Start of inlined file: juce_FlacHeader.h ***/
  99022. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  99023. // tasks..
  99024. #define VERSION "1.2.1"
  99025. #define FLAC__NO_DLL 1
  99026. #if JUCE_MSVC
  99027. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  99028. #endif
  99029. #if JUCE_MAC
  99030. #define FLAC__SYS_DARWIN 1
  99031. #endif
  99032. /*** End of inlined file: juce_FlacHeader.h ***/
  99033. #if JUCE_USE_FLAC
  99034. #if HAVE_CONFIG_H
  99035. # include <config.h>
  99036. #endif
  99037. #if defined _MSC_VER || defined __MINGW32__
  99038. #include <io.h> /* for _setmode() */
  99039. #include <fcntl.h> /* for _O_BINARY */
  99040. #endif
  99041. #if defined __CYGWIN__ || defined __EMX__
  99042. #include <io.h> /* for setmode(), O_BINARY */
  99043. #include <fcntl.h> /* for _O_BINARY */
  99044. #endif
  99045. #include <limits.h>
  99046. #include <stdio.h>
  99047. #include <stdlib.h> /* for malloc() */
  99048. #include <string.h> /* for memcpy() */
  99049. #include <sys/types.h> /* for off_t */
  99050. #if defined _MSC_VER || defined __BORLANDC__ || defined __MINGW32__
  99051. #if _MSC_VER <= 1600 || defined __BORLANDC__ /* @@@ [2G limit] */
  99052. #define fseeko fseek
  99053. #define ftello ftell
  99054. #endif
  99055. #endif
  99056. /*** Start of inlined file: stream_encoder.h ***/
  99057. #ifndef FLAC__PROTECTED__STREAM_ENCODER_H
  99058. #define FLAC__PROTECTED__STREAM_ENCODER_H
  99059. #if FLAC__HAS_OGG
  99060. #include "private/ogg_encoder_aspect.h"
  99061. #endif
  99062. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  99063. #define FLAC__MAX_APODIZATION_FUNCTIONS 32
  99064. typedef enum {
  99065. FLAC__APODIZATION_BARTLETT,
  99066. FLAC__APODIZATION_BARTLETT_HANN,
  99067. FLAC__APODIZATION_BLACKMAN,
  99068. FLAC__APODIZATION_BLACKMAN_HARRIS_4TERM_92DB_SIDELOBE,
  99069. FLAC__APODIZATION_CONNES,
  99070. FLAC__APODIZATION_FLATTOP,
  99071. FLAC__APODIZATION_GAUSS,
  99072. FLAC__APODIZATION_HAMMING,
  99073. FLAC__APODIZATION_HANN,
  99074. FLAC__APODIZATION_KAISER_BESSEL,
  99075. FLAC__APODIZATION_NUTTALL,
  99076. FLAC__APODIZATION_RECTANGLE,
  99077. FLAC__APODIZATION_TRIANGLE,
  99078. FLAC__APODIZATION_TUKEY,
  99079. FLAC__APODIZATION_WELCH
  99080. } FLAC__ApodizationFunction;
  99081. typedef struct {
  99082. FLAC__ApodizationFunction type;
  99083. union {
  99084. struct {
  99085. FLAC__real stddev;
  99086. } gauss;
  99087. struct {
  99088. FLAC__real p;
  99089. } tukey;
  99090. } parameters;
  99091. } FLAC__ApodizationSpecification;
  99092. #endif // #ifndef FLAC__INTEGER_ONLY_LIBRARY
  99093. typedef struct FLAC__StreamEncoderProtected {
  99094. FLAC__StreamEncoderState state;
  99095. FLAC__bool verify;
  99096. FLAC__bool streamable_subset;
  99097. FLAC__bool do_md5;
  99098. FLAC__bool do_mid_side_stereo;
  99099. FLAC__bool loose_mid_side_stereo;
  99100. unsigned channels;
  99101. unsigned bits_per_sample;
  99102. unsigned sample_rate;
  99103. unsigned blocksize;
  99104. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  99105. unsigned num_apodizations;
  99106. FLAC__ApodizationSpecification apodizations[FLAC__MAX_APODIZATION_FUNCTIONS];
  99107. #endif
  99108. unsigned max_lpc_order;
  99109. unsigned qlp_coeff_precision;
  99110. FLAC__bool do_qlp_coeff_prec_search;
  99111. FLAC__bool do_exhaustive_model_search;
  99112. FLAC__bool do_escape_coding;
  99113. unsigned min_residual_partition_order;
  99114. unsigned max_residual_partition_order;
  99115. unsigned rice_parameter_search_dist;
  99116. FLAC__uint64 total_samples_estimate;
  99117. FLAC__StreamMetadata **metadata;
  99118. unsigned num_metadata_blocks;
  99119. FLAC__uint64 streaminfo_offset, seektable_offset, audio_offset;
  99120. #if FLAC__HAS_OGG
  99121. FLAC__OggEncoderAspect ogg_encoder_aspect;
  99122. #endif
  99123. } FLAC__StreamEncoderProtected;
  99124. #endif
  99125. /*** End of inlined file: stream_encoder.h ***/
  99126. #if FLAC__HAS_OGG
  99127. #include "include/private/ogg_helper.h"
  99128. #include "include/private/ogg_mapping.h"
  99129. #endif
  99130. /*** Start of inlined file: stream_encoder_framing.h ***/
  99131. #ifndef FLAC__PRIVATE__STREAM_ENCODER_FRAMING_H
  99132. #define FLAC__PRIVATE__STREAM_ENCODER_FRAMING_H
  99133. FLAC__bool FLAC__add_metadata_block(const FLAC__StreamMetadata *metadata, FLAC__BitWriter *bw);
  99134. FLAC__bool FLAC__frame_add_header(const FLAC__FrameHeader *header, FLAC__BitWriter *bw);
  99135. FLAC__bool FLAC__subframe_add_constant(const FLAC__Subframe_Constant *subframe, unsigned subframe_bps, unsigned wasted_bits, FLAC__BitWriter *bw);
  99136. FLAC__bool FLAC__subframe_add_fixed(const FLAC__Subframe_Fixed *subframe, unsigned residual_samples, unsigned subframe_bps, unsigned wasted_bits, FLAC__BitWriter *bw);
  99137. FLAC__bool FLAC__subframe_add_lpc(const FLAC__Subframe_LPC *subframe, unsigned residual_samples, unsigned subframe_bps, unsigned wasted_bits, FLAC__BitWriter *bw);
  99138. FLAC__bool FLAC__subframe_add_verbatim(const FLAC__Subframe_Verbatim *subframe, unsigned samples, unsigned subframe_bps, unsigned wasted_bits, FLAC__BitWriter *bw);
  99139. #endif
  99140. /*** End of inlined file: stream_encoder_framing.h ***/
  99141. /*** Start of inlined file: window.h ***/
  99142. #ifndef FLAC__PRIVATE__WINDOW_H
  99143. #define FLAC__PRIVATE__WINDOW_H
  99144. #ifdef HAVE_CONFIG_H
  99145. #include <config.h>
  99146. #endif
  99147. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  99148. /*
  99149. * FLAC__window_*()
  99150. * --------------------------------------------------------------------
  99151. * Calculates window coefficients according to different apodization
  99152. * functions.
  99153. *
  99154. * OUT window[0,L-1]
  99155. * IN L (number of points in window)
  99156. */
  99157. void FLAC__window_bartlett(FLAC__real *window, const FLAC__int32 L);
  99158. void FLAC__window_bartlett_hann(FLAC__real *window, const FLAC__int32 L);
  99159. void FLAC__window_blackman(FLAC__real *window, const FLAC__int32 L);
  99160. void FLAC__window_blackman_harris_4term_92db_sidelobe(FLAC__real *window, const FLAC__int32 L);
  99161. void FLAC__window_connes(FLAC__real *window, const FLAC__int32 L);
  99162. void FLAC__window_flattop(FLAC__real *window, const FLAC__int32 L);
  99163. void FLAC__window_gauss(FLAC__real *window, const FLAC__int32 L, const FLAC__real stddev); /* 0.0 < stddev <= 0.5 */
  99164. void FLAC__window_hamming(FLAC__real *window, const FLAC__int32 L);
  99165. void FLAC__window_hann(FLAC__real *window, const FLAC__int32 L);
  99166. void FLAC__window_kaiser_bessel(FLAC__real *window, const FLAC__int32 L);
  99167. void FLAC__window_nuttall(FLAC__real *window, const FLAC__int32 L);
  99168. void FLAC__window_rectangle(FLAC__real *window, const FLAC__int32 L);
  99169. void FLAC__window_triangle(FLAC__real *window, const FLAC__int32 L);
  99170. void FLAC__window_tukey(FLAC__real *window, const FLAC__int32 L, const FLAC__real p);
  99171. void FLAC__window_welch(FLAC__real *window, const FLAC__int32 L);
  99172. #endif /* !defined FLAC__INTEGER_ONLY_LIBRARY */
  99173. #endif
  99174. /*** End of inlined file: window.h ***/
  99175. #ifndef FLaC__INLINE
  99176. #define FLaC__INLINE
  99177. #endif
  99178. #ifdef min
  99179. #undef min
  99180. #endif
  99181. #define min(x,y) ((x)<(y)?(x):(y))
  99182. #ifdef max
  99183. #undef max
  99184. #endif
  99185. #define max(x,y) ((x)>(y)?(x):(y))
  99186. /* Exact Rice codeword length calculation is off by default. The simple
  99187. * (and fast) estimation (of how many bits a residual value will be
  99188. * encoded with) in this encoder is very good, almost always yielding
  99189. * compression within 0.1% of exact calculation.
  99190. */
  99191. #undef EXACT_RICE_BITS_CALCULATION
  99192. /* Rice parameter searching is off by default. The simple (and fast)
  99193. * parameter estimation in this encoder is very good, almost always
  99194. * yielding compression within 0.1% of the optimal parameters.
  99195. */
  99196. #undef ENABLE_RICE_PARAMETER_SEARCH
  99197. typedef struct {
  99198. FLAC__int32 *data[FLAC__MAX_CHANNELS];
  99199. unsigned size; /* of each data[] in samples */
  99200. unsigned tail;
  99201. } verify_input_fifo;
  99202. typedef struct {
  99203. const FLAC__byte *data;
  99204. unsigned capacity;
  99205. unsigned bytes;
  99206. } verify_output;
  99207. typedef enum {
  99208. ENCODER_IN_MAGIC = 0,
  99209. ENCODER_IN_METADATA = 1,
  99210. ENCODER_IN_AUDIO = 2
  99211. } EncoderStateHint;
  99212. static struct CompressionLevels {
  99213. FLAC__bool do_mid_side_stereo;
  99214. FLAC__bool loose_mid_side_stereo;
  99215. unsigned max_lpc_order;
  99216. unsigned qlp_coeff_precision;
  99217. FLAC__bool do_qlp_coeff_prec_search;
  99218. FLAC__bool do_escape_coding;
  99219. FLAC__bool do_exhaustive_model_search;
  99220. unsigned min_residual_partition_order;
  99221. unsigned max_residual_partition_order;
  99222. unsigned rice_parameter_search_dist;
  99223. } compression_levels_[] = {
  99224. { false, false, 0, 0, false, false, false, 0, 3, 0 },
  99225. { true , true , 0, 0, false, false, false, 0, 3, 0 },
  99226. { true , false, 0, 0, false, false, false, 0, 3, 0 },
  99227. { false, false, 6, 0, false, false, false, 0, 4, 0 },
  99228. { true , true , 8, 0, false, false, false, 0, 4, 0 },
  99229. { true , false, 8, 0, false, false, false, 0, 5, 0 },
  99230. { true , false, 8, 0, false, false, false, 0, 6, 0 },
  99231. { true , false, 8, 0, false, false, true , 0, 6, 0 },
  99232. { true , false, 12, 0, false, false, true , 0, 6, 0 }
  99233. };
  99234. /***********************************************************************
  99235. *
  99236. * Private class method prototypes
  99237. *
  99238. ***********************************************************************/
  99239. static void set_defaults_enc(FLAC__StreamEncoder *encoder);
  99240. static void free_(FLAC__StreamEncoder *encoder);
  99241. static FLAC__bool resize_buffers_(FLAC__StreamEncoder *encoder, unsigned new_blocksize);
  99242. static FLAC__bool write_bitbuffer_(FLAC__StreamEncoder *encoder, unsigned samples, FLAC__bool is_last_block);
  99243. static FLAC__StreamEncoderWriteStatus write_frame_(FLAC__StreamEncoder *encoder, const FLAC__byte buffer[], size_t bytes, unsigned samples, FLAC__bool is_last_block);
  99244. static void update_metadata_(const FLAC__StreamEncoder *encoder);
  99245. #if FLAC__HAS_OGG
  99246. static void update_ogg_metadata_(FLAC__StreamEncoder *encoder);
  99247. #endif
  99248. static FLAC__bool process_frame_(FLAC__StreamEncoder *encoder, FLAC__bool is_fractional_block, FLAC__bool is_last_block);
  99249. static FLAC__bool process_subframes_(FLAC__StreamEncoder *encoder, FLAC__bool is_fractional_block);
  99250. static FLAC__bool process_subframe_(
  99251. FLAC__StreamEncoder *encoder,
  99252. unsigned min_partition_order,
  99253. unsigned max_partition_order,
  99254. const FLAC__FrameHeader *frame_header,
  99255. unsigned subframe_bps,
  99256. const FLAC__int32 integer_signal[],
  99257. FLAC__Subframe *subframe[2],
  99258. FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents[2],
  99259. FLAC__int32 *residual[2],
  99260. unsigned *best_subframe,
  99261. unsigned *best_bits
  99262. );
  99263. static FLAC__bool add_subframe_(
  99264. FLAC__StreamEncoder *encoder,
  99265. unsigned blocksize,
  99266. unsigned subframe_bps,
  99267. const FLAC__Subframe *subframe,
  99268. FLAC__BitWriter *frame
  99269. );
  99270. static unsigned evaluate_constant_subframe_(
  99271. FLAC__StreamEncoder *encoder,
  99272. const FLAC__int32 signal,
  99273. unsigned blocksize,
  99274. unsigned subframe_bps,
  99275. FLAC__Subframe *subframe
  99276. );
  99277. static unsigned evaluate_fixed_subframe_(
  99278. FLAC__StreamEncoder *encoder,
  99279. const FLAC__int32 signal[],
  99280. FLAC__int32 residual[],
  99281. FLAC__uint64 abs_residual_partition_sums[],
  99282. unsigned raw_bits_per_partition[],
  99283. unsigned blocksize,
  99284. unsigned subframe_bps,
  99285. unsigned order,
  99286. unsigned rice_parameter,
  99287. unsigned rice_parameter_limit,
  99288. unsigned min_partition_order,
  99289. unsigned max_partition_order,
  99290. FLAC__bool do_escape_coding,
  99291. unsigned rice_parameter_search_dist,
  99292. FLAC__Subframe *subframe,
  99293. FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents
  99294. );
  99295. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  99296. static unsigned evaluate_lpc_subframe_(
  99297. FLAC__StreamEncoder *encoder,
  99298. const FLAC__int32 signal[],
  99299. FLAC__int32 residual[],
  99300. FLAC__uint64 abs_residual_partition_sums[],
  99301. unsigned raw_bits_per_partition[],
  99302. const FLAC__real lp_coeff[],
  99303. unsigned blocksize,
  99304. unsigned subframe_bps,
  99305. unsigned order,
  99306. unsigned qlp_coeff_precision,
  99307. unsigned rice_parameter,
  99308. unsigned rice_parameter_limit,
  99309. unsigned min_partition_order,
  99310. unsigned max_partition_order,
  99311. FLAC__bool do_escape_coding,
  99312. unsigned rice_parameter_search_dist,
  99313. FLAC__Subframe *subframe,
  99314. FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents
  99315. );
  99316. #endif
  99317. static unsigned evaluate_verbatim_subframe_(
  99318. FLAC__StreamEncoder *encoder,
  99319. const FLAC__int32 signal[],
  99320. unsigned blocksize,
  99321. unsigned subframe_bps,
  99322. FLAC__Subframe *subframe
  99323. );
  99324. static unsigned find_best_partition_order_(
  99325. struct FLAC__StreamEncoderPrivate *private_,
  99326. const FLAC__int32 residual[],
  99327. FLAC__uint64 abs_residual_partition_sums[],
  99328. unsigned raw_bits_per_partition[],
  99329. unsigned residual_samples,
  99330. unsigned predictor_order,
  99331. unsigned rice_parameter,
  99332. unsigned rice_parameter_limit,
  99333. unsigned min_partition_order,
  99334. unsigned max_partition_order,
  99335. unsigned bps,
  99336. FLAC__bool do_escape_coding,
  99337. unsigned rice_parameter_search_dist,
  99338. FLAC__EntropyCodingMethod *best_ecm
  99339. );
  99340. static void precompute_partition_info_sums_(
  99341. const FLAC__int32 residual[],
  99342. FLAC__uint64 abs_residual_partition_sums[],
  99343. unsigned residual_samples,
  99344. unsigned predictor_order,
  99345. unsigned min_partition_order,
  99346. unsigned max_partition_order,
  99347. unsigned bps
  99348. );
  99349. static void precompute_partition_info_escapes_(
  99350. const FLAC__int32 residual[],
  99351. unsigned raw_bits_per_partition[],
  99352. unsigned residual_samples,
  99353. unsigned predictor_order,
  99354. unsigned min_partition_order,
  99355. unsigned max_partition_order
  99356. );
  99357. static FLAC__bool set_partitioned_rice_(
  99358. #ifdef EXACT_RICE_BITS_CALCULATION
  99359. const FLAC__int32 residual[],
  99360. #endif
  99361. const FLAC__uint64 abs_residual_partition_sums[],
  99362. const unsigned raw_bits_per_partition[],
  99363. const unsigned residual_samples,
  99364. const unsigned predictor_order,
  99365. const unsigned suggested_rice_parameter,
  99366. const unsigned rice_parameter_limit,
  99367. const unsigned rice_parameter_search_dist,
  99368. const unsigned partition_order,
  99369. const FLAC__bool search_for_escapes,
  99370. FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents,
  99371. unsigned *bits
  99372. );
  99373. static unsigned get_wasted_bits_(FLAC__int32 signal[], unsigned samples);
  99374. /* verify-related routines: */
  99375. static void append_to_verify_fifo_(
  99376. verify_input_fifo *fifo,
  99377. const FLAC__int32 * const input[],
  99378. unsigned input_offset,
  99379. unsigned channels,
  99380. unsigned wide_samples
  99381. );
  99382. static void append_to_verify_fifo_interleaved_(
  99383. verify_input_fifo *fifo,
  99384. const FLAC__int32 input[],
  99385. unsigned input_offset,
  99386. unsigned channels,
  99387. unsigned wide_samples
  99388. );
  99389. static FLAC__StreamDecoderReadStatus verify_read_callback_(const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes, void *client_data);
  99390. static FLAC__StreamDecoderWriteStatus verify_write_callback_(const FLAC__StreamDecoder *decoder, const FLAC__Frame *frame, const FLAC__int32 * const buffer[], void *client_data);
  99391. static void verify_metadata_callback_(const FLAC__StreamDecoder *decoder, const FLAC__StreamMetadata *metadata, void *client_data);
  99392. static void verify_error_callback_(const FLAC__StreamDecoder *decoder, FLAC__StreamDecoderErrorStatus status, void *client_data);
  99393. static FLAC__StreamEncoderReadStatus file_read_callback_enc(const FLAC__StreamEncoder *encoder, FLAC__byte buffer[], size_t *bytes, void *client_data);
  99394. static FLAC__StreamEncoderSeekStatus file_seek_callback_enc(const FLAC__StreamEncoder *encoder, FLAC__uint64 absolute_byte_offset, void *client_data);
  99395. static FLAC__StreamEncoderTellStatus file_tell_callback_enc(const FLAC__StreamEncoder *encoder, FLAC__uint64 *absolute_byte_offset, void *client_data);
  99396. 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);
  99397. static FILE *get_binary_stdout_(void);
  99398. /***********************************************************************
  99399. *
  99400. * Private class data
  99401. *
  99402. ***********************************************************************/
  99403. typedef struct FLAC__StreamEncoderPrivate {
  99404. unsigned input_capacity; /* current size (in samples) of the signal and residual buffers */
  99405. FLAC__int32 *integer_signal[FLAC__MAX_CHANNELS]; /* the integer version of the input signal */
  99406. FLAC__int32 *integer_signal_mid_side[2]; /* the integer version of the mid-side input signal (stereo only) */
  99407. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  99408. FLAC__real *real_signal[FLAC__MAX_CHANNELS]; /* (@@@ currently unused) the floating-point version of the input signal */
  99409. FLAC__real *real_signal_mid_side[2]; /* (@@@ currently unused) the floating-point version of the mid-side input signal (stereo only) */
  99410. FLAC__real *window[FLAC__MAX_APODIZATION_FUNCTIONS]; /* the pre-computed floating-point window for each apodization function */
  99411. FLAC__real *windowed_signal; /* the integer_signal[] * current window[] */
  99412. #endif
  99413. unsigned subframe_bps[FLAC__MAX_CHANNELS]; /* the effective bits per sample of the input signal (stream bps - wasted bits) */
  99414. unsigned subframe_bps_mid_side[2]; /* the effective bits per sample of the mid-side input signal (stream bps - wasted bits + 0/1) */
  99415. FLAC__int32 *residual_workspace[FLAC__MAX_CHANNELS][2]; /* each channel has a candidate and best workspace where the subframe residual signals will be stored */
  99416. FLAC__int32 *residual_workspace_mid_side[2][2];
  99417. FLAC__Subframe subframe_workspace[FLAC__MAX_CHANNELS][2];
  99418. FLAC__Subframe subframe_workspace_mid_side[2][2];
  99419. FLAC__Subframe *subframe_workspace_ptr[FLAC__MAX_CHANNELS][2];
  99420. FLAC__Subframe *subframe_workspace_ptr_mid_side[2][2];
  99421. FLAC__EntropyCodingMethod_PartitionedRiceContents partitioned_rice_contents_workspace[FLAC__MAX_CHANNELS][2];
  99422. FLAC__EntropyCodingMethod_PartitionedRiceContents partitioned_rice_contents_workspace_mid_side[FLAC__MAX_CHANNELS][2];
  99423. FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents_workspace_ptr[FLAC__MAX_CHANNELS][2];
  99424. FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents_workspace_ptr_mid_side[FLAC__MAX_CHANNELS][2];
  99425. unsigned best_subframe[FLAC__MAX_CHANNELS]; /* index (0 or 1) into 2nd dimension of the above workspaces */
  99426. unsigned best_subframe_mid_side[2];
  99427. unsigned best_subframe_bits[FLAC__MAX_CHANNELS]; /* size in bits of the best subframe for each channel */
  99428. unsigned best_subframe_bits_mid_side[2];
  99429. FLAC__uint64 *abs_residual_partition_sums; /* workspace where the sum of abs(candidate residual) for each partition is stored */
  99430. unsigned *raw_bits_per_partition; /* workspace where the sum of silog2(candidate residual) for each partition is stored */
  99431. FLAC__BitWriter *frame; /* the current frame being worked on */
  99432. unsigned loose_mid_side_stereo_frames; /* rounded number of frames the encoder will use before trying both independent and mid/side frames again */
  99433. unsigned loose_mid_side_stereo_frame_count; /* number of frames using the current channel assignment */
  99434. FLAC__ChannelAssignment last_channel_assignment;
  99435. FLAC__StreamMetadata streaminfo; /* scratchpad for STREAMINFO as it is built */
  99436. FLAC__StreamMetadata_SeekTable *seek_table; /* pointer into encoder->protected_->metadata_ where the seek table is */
  99437. unsigned current_sample_number;
  99438. unsigned current_frame_number;
  99439. FLAC__MD5Context md5context;
  99440. FLAC__CPUInfo cpuinfo;
  99441. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  99442. unsigned (*local_fixed_compute_best_predictor)(const FLAC__int32 data[], unsigned data_len, FLAC__float residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1]);
  99443. #else
  99444. unsigned (*local_fixed_compute_best_predictor)(const FLAC__int32 data[], unsigned data_len, FLAC__fixedpoint residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1]);
  99445. #endif
  99446. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  99447. void (*local_lpc_compute_autocorrelation)(const FLAC__real data[], unsigned data_len, unsigned lag, FLAC__real autoc[]);
  99448. 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[]);
  99449. 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[]);
  99450. 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[]);
  99451. #endif
  99452. FLAC__bool use_wide_by_block; /* use slow 64-bit versions of some functions because of the block size */
  99453. FLAC__bool use_wide_by_partition; /* use slow 64-bit versions of some functions because of the min partition order and blocksize */
  99454. FLAC__bool use_wide_by_order; /* use slow 64-bit versions of some functions because of the lpc order */
  99455. FLAC__bool disable_constant_subframes;
  99456. FLAC__bool disable_fixed_subframes;
  99457. FLAC__bool disable_verbatim_subframes;
  99458. #if FLAC__HAS_OGG
  99459. FLAC__bool is_ogg;
  99460. #endif
  99461. FLAC__StreamEncoderReadCallback read_callback; /* currently only needed for Ogg FLAC */
  99462. FLAC__StreamEncoderSeekCallback seek_callback;
  99463. FLAC__StreamEncoderTellCallback tell_callback;
  99464. FLAC__StreamEncoderWriteCallback write_callback;
  99465. FLAC__StreamEncoderMetadataCallback metadata_callback;
  99466. FLAC__StreamEncoderProgressCallback progress_callback;
  99467. void *client_data;
  99468. unsigned first_seekpoint_to_check;
  99469. FILE *file; /* only used when encoding to a file */
  99470. FLAC__uint64 bytes_written;
  99471. FLAC__uint64 samples_written;
  99472. unsigned frames_written;
  99473. unsigned total_frames_estimate;
  99474. /* unaligned (original) pointers to allocated data */
  99475. FLAC__int32 *integer_signal_unaligned[FLAC__MAX_CHANNELS];
  99476. FLAC__int32 *integer_signal_mid_side_unaligned[2];
  99477. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  99478. FLAC__real *real_signal_unaligned[FLAC__MAX_CHANNELS]; /* (@@@ currently unused) */
  99479. FLAC__real *real_signal_mid_side_unaligned[2]; /* (@@@ currently unused) */
  99480. FLAC__real *window_unaligned[FLAC__MAX_APODIZATION_FUNCTIONS];
  99481. FLAC__real *windowed_signal_unaligned;
  99482. #endif
  99483. FLAC__int32 *residual_workspace_unaligned[FLAC__MAX_CHANNELS][2];
  99484. FLAC__int32 *residual_workspace_mid_side_unaligned[2][2];
  99485. FLAC__uint64 *abs_residual_partition_sums_unaligned;
  99486. unsigned *raw_bits_per_partition_unaligned;
  99487. /*
  99488. * These fields have been moved here from private function local
  99489. * declarations merely to save stack space during encoding.
  99490. */
  99491. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  99492. FLAC__real lp_coeff[FLAC__MAX_LPC_ORDER][FLAC__MAX_LPC_ORDER]; /* from process_subframe_() */
  99493. #endif
  99494. FLAC__EntropyCodingMethod_PartitionedRiceContents partitioned_rice_contents_extra[2]; /* from find_best_partition_order_() */
  99495. /*
  99496. * The data for the verify section
  99497. */
  99498. struct {
  99499. FLAC__StreamDecoder *decoder;
  99500. EncoderStateHint state_hint;
  99501. FLAC__bool needs_magic_hack;
  99502. verify_input_fifo input_fifo;
  99503. verify_output output;
  99504. struct {
  99505. FLAC__uint64 absolute_sample;
  99506. unsigned frame_number;
  99507. unsigned channel;
  99508. unsigned sample;
  99509. FLAC__int32 expected;
  99510. FLAC__int32 got;
  99511. } error_stats;
  99512. } verify;
  99513. FLAC__bool is_being_deleted; /* if true, call to ..._finish() from ..._delete() will not call the callbacks */
  99514. } FLAC__StreamEncoderPrivate;
  99515. /***********************************************************************
  99516. *
  99517. * Public static class data
  99518. *
  99519. ***********************************************************************/
  99520. FLAC_API const char * const FLAC__StreamEncoderStateString[] = {
  99521. "FLAC__STREAM_ENCODER_OK",
  99522. "FLAC__STREAM_ENCODER_UNINITIALIZED",
  99523. "FLAC__STREAM_ENCODER_OGG_ERROR",
  99524. "FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR",
  99525. "FLAC__STREAM_ENCODER_VERIFY_MISMATCH_IN_AUDIO_DATA",
  99526. "FLAC__STREAM_ENCODER_CLIENT_ERROR",
  99527. "FLAC__STREAM_ENCODER_IO_ERROR",
  99528. "FLAC__STREAM_ENCODER_FRAMING_ERROR",
  99529. "FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR"
  99530. };
  99531. FLAC_API const char * const FLAC__StreamEncoderInitStatusString[] = {
  99532. "FLAC__STREAM_ENCODER_INIT_STATUS_OK",
  99533. "FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR",
  99534. "FLAC__STREAM_ENCODER_INIT_STATUS_UNSUPPORTED_CONTAINER",
  99535. "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_CALLBACKS",
  99536. "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_NUMBER_OF_CHANNELS",
  99537. "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_BITS_PER_SAMPLE",
  99538. "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_SAMPLE_RATE",
  99539. "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_BLOCK_SIZE",
  99540. "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_MAX_LPC_ORDER",
  99541. "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_QLP_COEFF_PRECISION",
  99542. "FLAC__STREAM_ENCODER_INIT_STATUS_BLOCK_SIZE_TOO_SMALL_FOR_LPC_ORDER",
  99543. "FLAC__STREAM_ENCODER_INIT_STATUS_NOT_STREAMABLE",
  99544. "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA",
  99545. "FLAC__STREAM_ENCODER_INIT_STATUS_ALREADY_INITIALIZED"
  99546. };
  99547. FLAC_API const char * const FLAC__treamEncoderReadStatusString[] = {
  99548. "FLAC__STREAM_ENCODER_READ_STATUS_CONTINUE",
  99549. "FLAC__STREAM_ENCODER_READ_STATUS_END_OF_STREAM",
  99550. "FLAC__STREAM_ENCODER_READ_STATUS_ABORT",
  99551. "FLAC__STREAM_ENCODER_READ_STATUS_UNSUPPORTED"
  99552. };
  99553. FLAC_API const char * const FLAC__StreamEncoderWriteStatusString[] = {
  99554. "FLAC__STREAM_ENCODER_WRITE_STATUS_OK",
  99555. "FLAC__STREAM_ENCODER_WRITE_STATUS_FATAL_ERROR"
  99556. };
  99557. FLAC_API const char * const FLAC__StreamEncoderSeekStatusString[] = {
  99558. "FLAC__STREAM_ENCODER_SEEK_STATUS_OK",
  99559. "FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR",
  99560. "FLAC__STREAM_ENCODER_SEEK_STATUS_UNSUPPORTED"
  99561. };
  99562. FLAC_API const char * const FLAC__StreamEncoderTellStatusString[] = {
  99563. "FLAC__STREAM_ENCODER_TELL_STATUS_OK",
  99564. "FLAC__STREAM_ENCODER_TELL_STATUS_ERROR",
  99565. "FLAC__STREAM_ENCODER_TELL_STATUS_UNSUPPORTED"
  99566. };
  99567. /* Number of samples that will be overread to watch for end of stream. By
  99568. * 'overread', we mean that the FLAC__stream_encoder_process*() calls will
  99569. * always try to read blocksize+1 samples before encoding a block, so that
  99570. * even if the stream has a total sample count that is an integral multiple
  99571. * of the blocksize, we will still notice when we are encoding the last
  99572. * block. This is needed, for example, to correctly set the end-of-stream
  99573. * marker in Ogg FLAC.
  99574. *
  99575. * WATCHOUT: some parts of the code assert that OVERREAD_ == 1 and there's
  99576. * not really any reason to change it.
  99577. */
  99578. static const unsigned OVERREAD_ = 1;
  99579. /***********************************************************************
  99580. *
  99581. * Class constructor/destructor
  99582. *
  99583. */
  99584. FLAC_API FLAC__StreamEncoder *FLAC__stream_encoder_new(void)
  99585. {
  99586. FLAC__StreamEncoder *encoder;
  99587. unsigned i;
  99588. FLAC__ASSERT(sizeof(int) >= 4); /* we want to die right away if this is not true */
  99589. encoder = (FLAC__StreamEncoder*)calloc(1, sizeof(FLAC__StreamEncoder));
  99590. if(encoder == 0) {
  99591. return 0;
  99592. }
  99593. encoder->protected_ = (FLAC__StreamEncoderProtected*)calloc(1, sizeof(FLAC__StreamEncoderProtected));
  99594. if(encoder->protected_ == 0) {
  99595. free(encoder);
  99596. return 0;
  99597. }
  99598. encoder->private_ = (FLAC__StreamEncoderPrivate*)calloc(1, sizeof(FLAC__StreamEncoderPrivate));
  99599. if(encoder->private_ == 0) {
  99600. free(encoder->protected_);
  99601. free(encoder);
  99602. return 0;
  99603. }
  99604. encoder->private_->frame = FLAC__bitwriter_new();
  99605. if(encoder->private_->frame == 0) {
  99606. free(encoder->private_);
  99607. free(encoder->protected_);
  99608. free(encoder);
  99609. return 0;
  99610. }
  99611. encoder->private_->file = 0;
  99612. set_defaults_enc(encoder);
  99613. encoder->private_->is_being_deleted = false;
  99614. for(i = 0; i < FLAC__MAX_CHANNELS; i++) {
  99615. encoder->private_->subframe_workspace_ptr[i][0] = &encoder->private_->subframe_workspace[i][0];
  99616. encoder->private_->subframe_workspace_ptr[i][1] = &encoder->private_->subframe_workspace[i][1];
  99617. }
  99618. for(i = 0; i < 2; i++) {
  99619. encoder->private_->subframe_workspace_ptr_mid_side[i][0] = &encoder->private_->subframe_workspace_mid_side[i][0];
  99620. encoder->private_->subframe_workspace_ptr_mid_side[i][1] = &encoder->private_->subframe_workspace_mid_side[i][1];
  99621. }
  99622. for(i = 0; i < FLAC__MAX_CHANNELS; i++) {
  99623. encoder->private_->partitioned_rice_contents_workspace_ptr[i][0] = &encoder->private_->partitioned_rice_contents_workspace[i][0];
  99624. encoder->private_->partitioned_rice_contents_workspace_ptr[i][1] = &encoder->private_->partitioned_rice_contents_workspace[i][1];
  99625. }
  99626. for(i = 0; i < 2; i++) {
  99627. encoder->private_->partitioned_rice_contents_workspace_ptr_mid_side[i][0] = &encoder->private_->partitioned_rice_contents_workspace_mid_side[i][0];
  99628. encoder->private_->partitioned_rice_contents_workspace_ptr_mid_side[i][1] = &encoder->private_->partitioned_rice_contents_workspace_mid_side[i][1];
  99629. }
  99630. for(i = 0; i < FLAC__MAX_CHANNELS; i++) {
  99631. FLAC__format_entropy_coding_method_partitioned_rice_contents_init(&encoder->private_->partitioned_rice_contents_workspace[i][0]);
  99632. FLAC__format_entropy_coding_method_partitioned_rice_contents_init(&encoder->private_->partitioned_rice_contents_workspace[i][1]);
  99633. }
  99634. for(i = 0; i < 2; i++) {
  99635. FLAC__format_entropy_coding_method_partitioned_rice_contents_init(&encoder->private_->partitioned_rice_contents_workspace_mid_side[i][0]);
  99636. FLAC__format_entropy_coding_method_partitioned_rice_contents_init(&encoder->private_->partitioned_rice_contents_workspace_mid_side[i][1]);
  99637. }
  99638. for(i = 0; i < 2; i++)
  99639. FLAC__format_entropy_coding_method_partitioned_rice_contents_init(&encoder->private_->partitioned_rice_contents_extra[i]);
  99640. encoder->protected_->state = FLAC__STREAM_ENCODER_UNINITIALIZED;
  99641. return encoder;
  99642. }
  99643. FLAC_API void FLAC__stream_encoder_delete(FLAC__StreamEncoder *encoder)
  99644. {
  99645. unsigned i;
  99646. FLAC__ASSERT(0 != encoder);
  99647. FLAC__ASSERT(0 != encoder->protected_);
  99648. FLAC__ASSERT(0 != encoder->private_);
  99649. FLAC__ASSERT(0 != encoder->private_->frame);
  99650. encoder->private_->is_being_deleted = true;
  99651. (void)FLAC__stream_encoder_finish(encoder);
  99652. if(0 != encoder->private_->verify.decoder)
  99653. FLAC__stream_decoder_delete(encoder->private_->verify.decoder);
  99654. for(i = 0; i < FLAC__MAX_CHANNELS; i++) {
  99655. FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(&encoder->private_->partitioned_rice_contents_workspace[i][0]);
  99656. FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(&encoder->private_->partitioned_rice_contents_workspace[i][1]);
  99657. }
  99658. for(i = 0; i < 2; i++) {
  99659. FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(&encoder->private_->partitioned_rice_contents_workspace_mid_side[i][0]);
  99660. FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(&encoder->private_->partitioned_rice_contents_workspace_mid_side[i][1]);
  99661. }
  99662. for(i = 0; i < 2; i++)
  99663. FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(&encoder->private_->partitioned_rice_contents_extra[i]);
  99664. FLAC__bitwriter_delete(encoder->private_->frame);
  99665. free(encoder->private_);
  99666. free(encoder->protected_);
  99667. free(encoder);
  99668. }
  99669. /***********************************************************************
  99670. *
  99671. * Public class methods
  99672. *
  99673. ***********************************************************************/
  99674. static FLAC__StreamEncoderInitStatus init_stream_internal_enc(
  99675. FLAC__StreamEncoder *encoder,
  99676. FLAC__StreamEncoderReadCallback read_callback,
  99677. FLAC__StreamEncoderWriteCallback write_callback,
  99678. FLAC__StreamEncoderSeekCallback seek_callback,
  99679. FLAC__StreamEncoderTellCallback tell_callback,
  99680. FLAC__StreamEncoderMetadataCallback metadata_callback,
  99681. void *client_data,
  99682. FLAC__bool is_ogg
  99683. )
  99684. {
  99685. unsigned i;
  99686. FLAC__bool metadata_has_seektable, metadata_has_vorbis_comment, metadata_picture_has_type1, metadata_picture_has_type2;
  99687. FLAC__ASSERT(0 != encoder);
  99688. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  99689. return FLAC__STREAM_ENCODER_INIT_STATUS_ALREADY_INITIALIZED;
  99690. #if !FLAC__HAS_OGG
  99691. if(is_ogg)
  99692. return FLAC__STREAM_ENCODER_INIT_STATUS_UNSUPPORTED_CONTAINER;
  99693. #endif
  99694. if(0 == write_callback || (seek_callback && 0 == tell_callback))
  99695. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_CALLBACKS;
  99696. if(encoder->protected_->channels == 0 || encoder->protected_->channels > FLAC__MAX_CHANNELS)
  99697. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_NUMBER_OF_CHANNELS;
  99698. if(encoder->protected_->channels != 2) {
  99699. encoder->protected_->do_mid_side_stereo = false;
  99700. encoder->protected_->loose_mid_side_stereo = false;
  99701. }
  99702. else if(!encoder->protected_->do_mid_side_stereo)
  99703. encoder->protected_->loose_mid_side_stereo = false;
  99704. if(encoder->protected_->bits_per_sample >= 32)
  99705. encoder->protected_->do_mid_side_stereo = false; /* since we currenty do 32-bit math, the side channel would have 33 bps and overflow */
  99706. if(encoder->protected_->bits_per_sample < FLAC__MIN_BITS_PER_SAMPLE || encoder->protected_->bits_per_sample > FLAC__REFERENCE_CODEC_MAX_BITS_PER_SAMPLE)
  99707. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_BITS_PER_SAMPLE;
  99708. if(!FLAC__format_sample_rate_is_valid(encoder->protected_->sample_rate))
  99709. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_SAMPLE_RATE;
  99710. if(encoder->protected_->blocksize == 0) {
  99711. if(encoder->protected_->max_lpc_order == 0)
  99712. encoder->protected_->blocksize = 1152;
  99713. else
  99714. encoder->protected_->blocksize = 4096;
  99715. }
  99716. if(encoder->protected_->blocksize < FLAC__MIN_BLOCK_SIZE || encoder->protected_->blocksize > FLAC__MAX_BLOCK_SIZE)
  99717. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_BLOCK_SIZE;
  99718. if(encoder->protected_->max_lpc_order > FLAC__MAX_LPC_ORDER)
  99719. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_MAX_LPC_ORDER;
  99720. if(encoder->protected_->blocksize < encoder->protected_->max_lpc_order)
  99721. return FLAC__STREAM_ENCODER_INIT_STATUS_BLOCK_SIZE_TOO_SMALL_FOR_LPC_ORDER;
  99722. if(encoder->protected_->qlp_coeff_precision == 0) {
  99723. if(encoder->protected_->bits_per_sample < 16) {
  99724. /* @@@ need some data about how to set this here w.r.t. blocksize and sample rate */
  99725. /* @@@ until then we'll make a guess */
  99726. encoder->protected_->qlp_coeff_precision = max(FLAC__MIN_QLP_COEFF_PRECISION, 2 + encoder->protected_->bits_per_sample / 2);
  99727. }
  99728. else if(encoder->protected_->bits_per_sample == 16) {
  99729. if(encoder->protected_->blocksize <= 192)
  99730. encoder->protected_->qlp_coeff_precision = 7;
  99731. else if(encoder->protected_->blocksize <= 384)
  99732. encoder->protected_->qlp_coeff_precision = 8;
  99733. else if(encoder->protected_->blocksize <= 576)
  99734. encoder->protected_->qlp_coeff_precision = 9;
  99735. else if(encoder->protected_->blocksize <= 1152)
  99736. encoder->protected_->qlp_coeff_precision = 10;
  99737. else if(encoder->protected_->blocksize <= 2304)
  99738. encoder->protected_->qlp_coeff_precision = 11;
  99739. else if(encoder->protected_->blocksize <= 4608)
  99740. encoder->protected_->qlp_coeff_precision = 12;
  99741. else
  99742. encoder->protected_->qlp_coeff_precision = 13;
  99743. }
  99744. else {
  99745. if(encoder->protected_->blocksize <= 384)
  99746. encoder->protected_->qlp_coeff_precision = FLAC__MAX_QLP_COEFF_PRECISION-2;
  99747. else if(encoder->protected_->blocksize <= 1152)
  99748. encoder->protected_->qlp_coeff_precision = FLAC__MAX_QLP_COEFF_PRECISION-1;
  99749. else
  99750. encoder->protected_->qlp_coeff_precision = FLAC__MAX_QLP_COEFF_PRECISION;
  99751. }
  99752. FLAC__ASSERT(encoder->protected_->qlp_coeff_precision <= FLAC__MAX_QLP_COEFF_PRECISION);
  99753. }
  99754. else if(encoder->protected_->qlp_coeff_precision < FLAC__MIN_QLP_COEFF_PRECISION || encoder->protected_->qlp_coeff_precision > FLAC__MAX_QLP_COEFF_PRECISION)
  99755. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_QLP_COEFF_PRECISION;
  99756. if(encoder->protected_->streamable_subset) {
  99757. if(
  99758. encoder->protected_->blocksize != 192 &&
  99759. encoder->protected_->blocksize != 576 &&
  99760. encoder->protected_->blocksize != 1152 &&
  99761. encoder->protected_->blocksize != 2304 &&
  99762. encoder->protected_->blocksize != 4608 &&
  99763. encoder->protected_->blocksize != 256 &&
  99764. encoder->protected_->blocksize != 512 &&
  99765. encoder->protected_->blocksize != 1024 &&
  99766. encoder->protected_->blocksize != 2048 &&
  99767. encoder->protected_->blocksize != 4096 &&
  99768. encoder->protected_->blocksize != 8192 &&
  99769. encoder->protected_->blocksize != 16384
  99770. )
  99771. return FLAC__STREAM_ENCODER_INIT_STATUS_NOT_STREAMABLE;
  99772. if(!FLAC__format_sample_rate_is_subset(encoder->protected_->sample_rate))
  99773. return FLAC__STREAM_ENCODER_INIT_STATUS_NOT_STREAMABLE;
  99774. if(
  99775. encoder->protected_->bits_per_sample != 8 &&
  99776. encoder->protected_->bits_per_sample != 12 &&
  99777. encoder->protected_->bits_per_sample != 16 &&
  99778. encoder->protected_->bits_per_sample != 20 &&
  99779. encoder->protected_->bits_per_sample != 24
  99780. )
  99781. return FLAC__STREAM_ENCODER_INIT_STATUS_NOT_STREAMABLE;
  99782. if(encoder->protected_->max_residual_partition_order > FLAC__SUBSET_MAX_RICE_PARTITION_ORDER)
  99783. return FLAC__STREAM_ENCODER_INIT_STATUS_NOT_STREAMABLE;
  99784. if(
  99785. encoder->protected_->sample_rate <= 48000 &&
  99786. (
  99787. encoder->protected_->blocksize > FLAC__SUBSET_MAX_BLOCK_SIZE_48000HZ ||
  99788. encoder->protected_->max_lpc_order > FLAC__SUBSET_MAX_LPC_ORDER_48000HZ
  99789. )
  99790. ) {
  99791. return FLAC__STREAM_ENCODER_INIT_STATUS_NOT_STREAMABLE;
  99792. }
  99793. }
  99794. if(encoder->protected_->max_residual_partition_order >= (1u << FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN))
  99795. encoder->protected_->max_residual_partition_order = (1u << FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN) - 1;
  99796. if(encoder->protected_->min_residual_partition_order >= encoder->protected_->max_residual_partition_order)
  99797. encoder->protected_->min_residual_partition_order = encoder->protected_->max_residual_partition_order;
  99798. #if FLAC__HAS_OGG
  99799. /* reorder metadata if necessary to ensure that any VORBIS_COMMENT is the first, according to the mapping spec */
  99800. if(is_ogg && 0 != encoder->protected_->metadata && encoder->protected_->num_metadata_blocks > 1) {
  99801. unsigned i;
  99802. for(i = 1; i < encoder->protected_->num_metadata_blocks; i++) {
  99803. if(0 != encoder->protected_->metadata[i] && encoder->protected_->metadata[i]->type == FLAC__METADATA_TYPE_VORBIS_COMMENT) {
  99804. FLAC__StreamMetadata *vc = encoder->protected_->metadata[i];
  99805. for( ; i > 0; i--)
  99806. encoder->protected_->metadata[i] = encoder->protected_->metadata[i-1];
  99807. encoder->protected_->metadata[0] = vc;
  99808. break;
  99809. }
  99810. }
  99811. }
  99812. #endif
  99813. /* keep track of any SEEKTABLE block */
  99814. if(0 != encoder->protected_->metadata && encoder->protected_->num_metadata_blocks > 0) {
  99815. unsigned i;
  99816. for(i = 0; i < encoder->protected_->num_metadata_blocks; i++) {
  99817. if(0 != encoder->protected_->metadata[i] && encoder->protected_->metadata[i]->type == FLAC__METADATA_TYPE_SEEKTABLE) {
  99818. encoder->private_->seek_table = &encoder->protected_->metadata[i]->data.seek_table;
  99819. break; /* take only the first one */
  99820. }
  99821. }
  99822. }
  99823. /* validate metadata */
  99824. if(0 == encoder->protected_->metadata && encoder->protected_->num_metadata_blocks > 0)
  99825. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
  99826. metadata_has_seektable = false;
  99827. metadata_has_vorbis_comment = false;
  99828. metadata_picture_has_type1 = false;
  99829. metadata_picture_has_type2 = false;
  99830. for(i = 0; i < encoder->protected_->num_metadata_blocks; i++) {
  99831. const FLAC__StreamMetadata *m = encoder->protected_->metadata[i];
  99832. if(m->type == FLAC__METADATA_TYPE_STREAMINFO)
  99833. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
  99834. else if(m->type == FLAC__METADATA_TYPE_SEEKTABLE) {
  99835. if(metadata_has_seektable) /* only one is allowed */
  99836. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
  99837. metadata_has_seektable = true;
  99838. if(!FLAC__format_seektable_is_legal(&m->data.seek_table))
  99839. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
  99840. }
  99841. else if(m->type == FLAC__METADATA_TYPE_VORBIS_COMMENT) {
  99842. if(metadata_has_vorbis_comment) /* only one is allowed */
  99843. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
  99844. metadata_has_vorbis_comment = true;
  99845. }
  99846. else if(m->type == FLAC__METADATA_TYPE_CUESHEET) {
  99847. if(!FLAC__format_cuesheet_is_legal(&m->data.cue_sheet, m->data.cue_sheet.is_cd, /*violation=*/0))
  99848. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
  99849. }
  99850. else if(m->type == FLAC__METADATA_TYPE_PICTURE) {
  99851. if(!FLAC__format_picture_is_legal(&m->data.picture, /*violation=*/0))
  99852. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
  99853. if(m->data.picture.type == FLAC__STREAM_METADATA_PICTURE_TYPE_FILE_ICON_STANDARD) {
  99854. if(metadata_picture_has_type1) /* there should only be 1 per stream */
  99855. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
  99856. metadata_picture_has_type1 = true;
  99857. /* standard icon must be 32x32 pixel PNG */
  99858. if(
  99859. m->data.picture.type == FLAC__STREAM_METADATA_PICTURE_TYPE_FILE_ICON_STANDARD &&
  99860. (
  99861. (strcmp(m->data.picture.mime_type, "image/png") && strcmp(m->data.picture.mime_type, "-->")) ||
  99862. m->data.picture.width != 32 ||
  99863. m->data.picture.height != 32
  99864. )
  99865. )
  99866. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
  99867. }
  99868. else if(m->data.picture.type == FLAC__STREAM_METADATA_PICTURE_TYPE_FILE_ICON) {
  99869. if(metadata_picture_has_type2) /* there should only be 1 per stream */
  99870. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
  99871. metadata_picture_has_type2 = true;
  99872. }
  99873. }
  99874. }
  99875. encoder->private_->input_capacity = 0;
  99876. for(i = 0; i < encoder->protected_->channels; i++) {
  99877. encoder->private_->integer_signal_unaligned[i] = encoder->private_->integer_signal[i] = 0;
  99878. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  99879. encoder->private_->real_signal_unaligned[i] = encoder->private_->real_signal[i] = 0;
  99880. #endif
  99881. }
  99882. for(i = 0; i < 2; i++) {
  99883. encoder->private_->integer_signal_mid_side_unaligned[i] = encoder->private_->integer_signal_mid_side[i] = 0;
  99884. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  99885. encoder->private_->real_signal_mid_side_unaligned[i] = encoder->private_->real_signal_mid_side[i] = 0;
  99886. #endif
  99887. }
  99888. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  99889. for(i = 0; i < encoder->protected_->num_apodizations; i++)
  99890. encoder->private_->window_unaligned[i] = encoder->private_->window[i] = 0;
  99891. encoder->private_->windowed_signal_unaligned = encoder->private_->windowed_signal = 0;
  99892. #endif
  99893. for(i = 0; i < encoder->protected_->channels; i++) {
  99894. encoder->private_->residual_workspace_unaligned[i][0] = encoder->private_->residual_workspace[i][0] = 0;
  99895. encoder->private_->residual_workspace_unaligned[i][1] = encoder->private_->residual_workspace[i][1] = 0;
  99896. encoder->private_->best_subframe[i] = 0;
  99897. }
  99898. for(i = 0; i < 2; i++) {
  99899. encoder->private_->residual_workspace_mid_side_unaligned[i][0] = encoder->private_->residual_workspace_mid_side[i][0] = 0;
  99900. encoder->private_->residual_workspace_mid_side_unaligned[i][1] = encoder->private_->residual_workspace_mid_side[i][1] = 0;
  99901. encoder->private_->best_subframe_mid_side[i] = 0;
  99902. }
  99903. encoder->private_->abs_residual_partition_sums_unaligned = encoder->private_->abs_residual_partition_sums = 0;
  99904. encoder->private_->raw_bits_per_partition_unaligned = encoder->private_->raw_bits_per_partition = 0;
  99905. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  99906. encoder->private_->loose_mid_side_stereo_frames = (unsigned)((FLAC__double)encoder->protected_->sample_rate * 0.4 / (FLAC__double)encoder->protected_->blocksize + 0.5);
  99907. #else
  99908. /* 26214 is the approximate fixed-point equivalent to 0.4 (0.4 * 2^16) */
  99909. /* sample rate can be up to 655350 Hz, and thus use 20 bits, so we do the multiply&divide by hand */
  99910. FLAC__ASSERT(FLAC__MAX_SAMPLE_RATE <= 655350);
  99911. FLAC__ASSERT(FLAC__MAX_BLOCK_SIZE <= 65535);
  99912. FLAC__ASSERT(encoder->protected_->sample_rate <= 655350);
  99913. FLAC__ASSERT(encoder->protected_->blocksize <= 65535);
  99914. 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);
  99915. #endif
  99916. if(encoder->private_->loose_mid_side_stereo_frames == 0)
  99917. encoder->private_->loose_mid_side_stereo_frames = 1;
  99918. encoder->private_->loose_mid_side_stereo_frame_count = 0;
  99919. encoder->private_->current_sample_number = 0;
  99920. encoder->private_->current_frame_number = 0;
  99921. encoder->private_->use_wide_by_block = (encoder->protected_->bits_per_sample + FLAC__bitmath_ilog2(encoder->protected_->blocksize)+1 > 30);
  99922. 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? */
  99923. encoder->private_->use_wide_by_partition = (false); /*@@@ need to set this */
  99924. /*
  99925. * get the CPU info and set the function pointers
  99926. */
  99927. FLAC__cpu_info(&encoder->private_->cpuinfo);
  99928. /* first default to the non-asm routines */
  99929. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  99930. encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation;
  99931. #endif
  99932. encoder->private_->local_fixed_compute_best_predictor = FLAC__fixed_compute_best_predictor;
  99933. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  99934. encoder->private_->local_lpc_compute_residual_from_qlp_coefficients = FLAC__lpc_compute_residual_from_qlp_coefficients;
  99935. encoder->private_->local_lpc_compute_residual_from_qlp_coefficients_64bit = FLAC__lpc_compute_residual_from_qlp_coefficients_wide;
  99936. encoder->private_->local_lpc_compute_residual_from_qlp_coefficients_16bit = FLAC__lpc_compute_residual_from_qlp_coefficients;
  99937. #endif
  99938. /* now override with asm where appropriate */
  99939. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  99940. # ifndef FLAC__NO_ASM
  99941. if(encoder->private_->cpuinfo.use_asm) {
  99942. # ifdef FLAC__CPU_IA32
  99943. FLAC__ASSERT(encoder->private_->cpuinfo.type == FLAC__CPUINFO_TYPE_IA32);
  99944. # ifdef FLAC__HAS_NASM
  99945. if(encoder->private_->cpuinfo.data.ia32.sse) {
  99946. if(encoder->protected_->max_lpc_order < 4)
  99947. encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_asm_ia32_sse_lag_4;
  99948. else if(encoder->protected_->max_lpc_order < 8)
  99949. encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_asm_ia32_sse_lag_8;
  99950. else if(encoder->protected_->max_lpc_order < 12)
  99951. encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_asm_ia32_sse_lag_12;
  99952. else
  99953. encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_asm_ia32;
  99954. }
  99955. else if(encoder->private_->cpuinfo.data.ia32._3dnow)
  99956. encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_asm_ia32_3dnow;
  99957. else
  99958. encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_asm_ia32;
  99959. if(encoder->private_->cpuinfo.data.ia32.mmx) {
  99960. encoder->private_->local_lpc_compute_residual_from_qlp_coefficients = FLAC__lpc_compute_residual_from_qlp_coefficients_asm_ia32;
  99961. encoder->private_->local_lpc_compute_residual_from_qlp_coefficients_16bit = FLAC__lpc_compute_residual_from_qlp_coefficients_asm_ia32_mmx;
  99962. }
  99963. else {
  99964. encoder->private_->local_lpc_compute_residual_from_qlp_coefficients = FLAC__lpc_compute_residual_from_qlp_coefficients_asm_ia32;
  99965. encoder->private_->local_lpc_compute_residual_from_qlp_coefficients_16bit = FLAC__lpc_compute_residual_from_qlp_coefficients_asm_ia32;
  99966. }
  99967. if(encoder->private_->cpuinfo.data.ia32.mmx && encoder->private_->cpuinfo.data.ia32.cmov)
  99968. encoder->private_->local_fixed_compute_best_predictor = FLAC__fixed_compute_best_predictor_asm_ia32_mmx_cmov;
  99969. # endif /* FLAC__HAS_NASM */
  99970. # endif /* FLAC__CPU_IA32 */
  99971. }
  99972. # endif /* !FLAC__NO_ASM */
  99973. #endif /* !FLAC__INTEGER_ONLY_LIBRARY */
  99974. /* finally override based on wide-ness if necessary */
  99975. if(encoder->private_->use_wide_by_block) {
  99976. encoder->private_->local_fixed_compute_best_predictor = FLAC__fixed_compute_best_predictor_wide;
  99977. }
  99978. /* set state to OK; from here on, errors are fatal and we'll override the state then */
  99979. encoder->protected_->state = FLAC__STREAM_ENCODER_OK;
  99980. #if FLAC__HAS_OGG
  99981. encoder->private_->is_ogg = is_ogg;
  99982. if(is_ogg && !FLAC__ogg_encoder_aspect_init(&encoder->protected_->ogg_encoder_aspect)) {
  99983. encoder->protected_->state = FLAC__STREAM_ENCODER_OGG_ERROR;
  99984. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  99985. }
  99986. #endif
  99987. encoder->private_->read_callback = read_callback;
  99988. encoder->private_->write_callback = write_callback;
  99989. encoder->private_->seek_callback = seek_callback;
  99990. encoder->private_->tell_callback = tell_callback;
  99991. encoder->private_->metadata_callback = metadata_callback;
  99992. encoder->private_->client_data = client_data;
  99993. if(!resize_buffers_(encoder, encoder->protected_->blocksize)) {
  99994. /* the above function sets the state for us in case of an error */
  99995. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  99996. }
  99997. if(!FLAC__bitwriter_init(encoder->private_->frame)) {
  99998. encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
  99999. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  100000. }
  100001. /*
  100002. * Set up the verify stuff if necessary
  100003. */
  100004. if(encoder->protected_->verify) {
  100005. /*
  100006. * First, set up the fifo which will hold the
  100007. * original signal to compare against
  100008. */
  100009. encoder->private_->verify.input_fifo.size = encoder->protected_->blocksize+OVERREAD_;
  100010. for(i = 0; i < encoder->protected_->channels; i++) {
  100011. 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))) {
  100012. encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
  100013. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  100014. }
  100015. }
  100016. encoder->private_->verify.input_fifo.tail = 0;
  100017. /*
  100018. * Now set up a stream decoder for verification
  100019. */
  100020. encoder->private_->verify.decoder = FLAC__stream_decoder_new();
  100021. if(0 == encoder->private_->verify.decoder) {
  100022. encoder->protected_->state = FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR;
  100023. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  100024. }
  100025. 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) {
  100026. encoder->protected_->state = FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR;
  100027. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  100028. }
  100029. }
  100030. encoder->private_->verify.error_stats.absolute_sample = 0;
  100031. encoder->private_->verify.error_stats.frame_number = 0;
  100032. encoder->private_->verify.error_stats.channel = 0;
  100033. encoder->private_->verify.error_stats.sample = 0;
  100034. encoder->private_->verify.error_stats.expected = 0;
  100035. encoder->private_->verify.error_stats.got = 0;
  100036. /*
  100037. * These must be done before we write any metadata, because that
  100038. * calls the write_callback, which uses these values.
  100039. */
  100040. encoder->private_->first_seekpoint_to_check = 0;
  100041. encoder->private_->samples_written = 0;
  100042. encoder->protected_->streaminfo_offset = 0;
  100043. encoder->protected_->seektable_offset = 0;
  100044. encoder->protected_->audio_offset = 0;
  100045. /*
  100046. * write the stream header
  100047. */
  100048. if(encoder->protected_->verify)
  100049. encoder->private_->verify.state_hint = ENCODER_IN_MAGIC;
  100050. if(!FLAC__bitwriter_write_raw_uint32(encoder->private_->frame, FLAC__STREAM_SYNC, FLAC__STREAM_SYNC_LEN)) {
  100051. encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
  100052. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  100053. }
  100054. if(!write_bitbuffer_(encoder, 0, /*is_last_block=*/false)) {
  100055. /* the above function sets the state for us in case of an error */
  100056. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  100057. }
  100058. /*
  100059. * write the STREAMINFO metadata block
  100060. */
  100061. if(encoder->protected_->verify)
  100062. encoder->private_->verify.state_hint = ENCODER_IN_METADATA;
  100063. encoder->private_->streaminfo.type = FLAC__METADATA_TYPE_STREAMINFO;
  100064. encoder->private_->streaminfo.is_last = false; /* we will have at a minimum a VORBIS_COMMENT afterwards */
  100065. encoder->private_->streaminfo.length = FLAC__STREAM_METADATA_STREAMINFO_LENGTH;
  100066. encoder->private_->streaminfo.data.stream_info.min_blocksize = encoder->protected_->blocksize; /* this encoder uses the same blocksize for the whole stream */
  100067. encoder->private_->streaminfo.data.stream_info.max_blocksize = encoder->protected_->blocksize;
  100068. encoder->private_->streaminfo.data.stream_info.min_framesize = 0; /* we don't know this yet; have to fill it in later */
  100069. encoder->private_->streaminfo.data.stream_info.max_framesize = 0; /* we don't know this yet; have to fill it in later */
  100070. encoder->private_->streaminfo.data.stream_info.sample_rate = encoder->protected_->sample_rate;
  100071. encoder->private_->streaminfo.data.stream_info.channels = encoder->protected_->channels;
  100072. encoder->private_->streaminfo.data.stream_info.bits_per_sample = encoder->protected_->bits_per_sample;
  100073. encoder->private_->streaminfo.data.stream_info.total_samples = encoder->protected_->total_samples_estimate; /* we will replace this later with the real total */
  100074. memset(encoder->private_->streaminfo.data.stream_info.md5sum, 0, 16); /* we don't know this yet; have to fill it in later */
  100075. if(encoder->protected_->do_md5)
  100076. FLAC__MD5Init(&encoder->private_->md5context);
  100077. if(!FLAC__add_metadata_block(&encoder->private_->streaminfo, encoder->private_->frame)) {
  100078. encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
  100079. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  100080. }
  100081. if(!write_bitbuffer_(encoder, 0, /*is_last_block=*/false)) {
  100082. /* the above function sets the state for us in case of an error */
  100083. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  100084. }
  100085. /*
  100086. * Now that the STREAMINFO block is written, we can init this to an
  100087. * absurdly-high value...
  100088. */
  100089. encoder->private_->streaminfo.data.stream_info.min_framesize = (1u << FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN) - 1;
  100090. /* ... and clear this to 0 */
  100091. encoder->private_->streaminfo.data.stream_info.total_samples = 0;
  100092. /*
  100093. * Check to see if the supplied metadata contains a VORBIS_COMMENT;
  100094. * if not, we will write an empty one (FLAC__add_metadata_block()
  100095. * automatically supplies the vendor string).
  100096. *
  100097. * WATCHOUT: the Ogg FLAC mapping requires us to write this block after
  100098. * the STREAMINFO. (In the case that metadata_has_vorbis_comment is
  100099. * true it will have already insured that the metadata list is properly
  100100. * ordered.)
  100101. */
  100102. if(!metadata_has_vorbis_comment) {
  100103. FLAC__StreamMetadata vorbis_comment;
  100104. vorbis_comment.type = FLAC__METADATA_TYPE_VORBIS_COMMENT;
  100105. vorbis_comment.is_last = (encoder->protected_->num_metadata_blocks == 0);
  100106. vorbis_comment.length = 4 + 4; /* MAGIC NUMBER */
  100107. vorbis_comment.data.vorbis_comment.vendor_string.length = 0;
  100108. vorbis_comment.data.vorbis_comment.vendor_string.entry = 0;
  100109. vorbis_comment.data.vorbis_comment.num_comments = 0;
  100110. vorbis_comment.data.vorbis_comment.comments = 0;
  100111. if(!FLAC__add_metadata_block(&vorbis_comment, encoder->private_->frame)) {
  100112. encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
  100113. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  100114. }
  100115. if(!write_bitbuffer_(encoder, 0, /*is_last_block=*/false)) {
  100116. /* the above function sets the state for us in case of an error */
  100117. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  100118. }
  100119. }
  100120. /*
  100121. * write the user's metadata blocks
  100122. */
  100123. for(i = 0; i < encoder->protected_->num_metadata_blocks; i++) {
  100124. encoder->protected_->metadata[i]->is_last = (i == encoder->protected_->num_metadata_blocks - 1);
  100125. if(!FLAC__add_metadata_block(encoder->protected_->metadata[i], encoder->private_->frame)) {
  100126. encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
  100127. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  100128. }
  100129. if(!write_bitbuffer_(encoder, 0, /*is_last_block=*/false)) {
  100130. /* the above function sets the state for us in case of an error */
  100131. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  100132. }
  100133. }
  100134. /* now that all the metadata is written, we save the stream offset */
  100135. 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 */
  100136. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  100137. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  100138. }
  100139. if(encoder->protected_->verify)
  100140. encoder->private_->verify.state_hint = ENCODER_IN_AUDIO;
  100141. return FLAC__STREAM_ENCODER_INIT_STATUS_OK;
  100142. }
  100143. FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_stream(
  100144. FLAC__StreamEncoder *encoder,
  100145. FLAC__StreamEncoderWriteCallback write_callback,
  100146. FLAC__StreamEncoderSeekCallback seek_callback,
  100147. FLAC__StreamEncoderTellCallback tell_callback,
  100148. FLAC__StreamEncoderMetadataCallback metadata_callback,
  100149. void *client_data
  100150. )
  100151. {
  100152. return init_stream_internal_enc(
  100153. encoder,
  100154. /*read_callback=*/0,
  100155. write_callback,
  100156. seek_callback,
  100157. tell_callback,
  100158. metadata_callback,
  100159. client_data,
  100160. /*is_ogg=*/false
  100161. );
  100162. }
  100163. FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_ogg_stream(
  100164. FLAC__StreamEncoder *encoder,
  100165. FLAC__StreamEncoderReadCallback read_callback,
  100166. FLAC__StreamEncoderWriteCallback write_callback,
  100167. FLAC__StreamEncoderSeekCallback seek_callback,
  100168. FLAC__StreamEncoderTellCallback tell_callback,
  100169. FLAC__StreamEncoderMetadataCallback metadata_callback,
  100170. void *client_data
  100171. )
  100172. {
  100173. return init_stream_internal_enc(
  100174. encoder,
  100175. read_callback,
  100176. write_callback,
  100177. seek_callback,
  100178. tell_callback,
  100179. metadata_callback,
  100180. client_data,
  100181. /*is_ogg=*/true
  100182. );
  100183. }
  100184. static FLAC__StreamEncoderInitStatus init_FILE_internal_enc(
  100185. FLAC__StreamEncoder *encoder,
  100186. FILE *file,
  100187. FLAC__StreamEncoderProgressCallback progress_callback,
  100188. void *client_data,
  100189. FLAC__bool is_ogg
  100190. )
  100191. {
  100192. FLAC__StreamEncoderInitStatus init_status;
  100193. FLAC__ASSERT(0 != encoder);
  100194. FLAC__ASSERT(0 != file);
  100195. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  100196. return FLAC__STREAM_ENCODER_INIT_STATUS_ALREADY_INITIALIZED;
  100197. /* double protection */
  100198. if(file == 0) {
  100199. encoder->protected_->state = FLAC__STREAM_ENCODER_IO_ERROR;
  100200. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  100201. }
  100202. /*
  100203. * To make sure that our file does not go unclosed after an error, we
  100204. * must assign the FILE pointer before any further error can occur in
  100205. * this routine.
  100206. */
  100207. if(file == stdout)
  100208. file = get_binary_stdout_(); /* just to be safe */
  100209. encoder->private_->file = file;
  100210. encoder->private_->progress_callback = progress_callback;
  100211. encoder->private_->bytes_written = 0;
  100212. encoder->private_->samples_written = 0;
  100213. encoder->private_->frames_written = 0;
  100214. init_status = init_stream_internal_enc(
  100215. encoder,
  100216. encoder->private_->file == stdout? 0 : is_ogg? file_read_callback_enc : 0,
  100217. file_write_callback_,
  100218. encoder->private_->file == stdout? 0 : file_seek_callback_enc,
  100219. encoder->private_->file == stdout? 0 : file_tell_callback_enc,
  100220. /*metadata_callback=*/0,
  100221. client_data,
  100222. is_ogg
  100223. );
  100224. if(init_status != FLAC__STREAM_ENCODER_INIT_STATUS_OK) {
  100225. /* the above function sets the state for us in case of an error */
  100226. return init_status;
  100227. }
  100228. {
  100229. unsigned blocksize = FLAC__stream_encoder_get_blocksize(encoder);
  100230. FLAC__ASSERT(blocksize != 0);
  100231. encoder->private_->total_frames_estimate = (unsigned)((FLAC__stream_encoder_get_total_samples_estimate(encoder) + blocksize - 1) / blocksize);
  100232. }
  100233. return init_status;
  100234. }
  100235. FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_FILE(
  100236. FLAC__StreamEncoder *encoder,
  100237. FILE *file,
  100238. FLAC__StreamEncoderProgressCallback progress_callback,
  100239. void *client_data
  100240. )
  100241. {
  100242. return init_FILE_internal_enc(encoder, file, progress_callback, client_data, /*is_ogg=*/false);
  100243. }
  100244. FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_ogg_FILE(
  100245. FLAC__StreamEncoder *encoder,
  100246. FILE *file,
  100247. FLAC__StreamEncoderProgressCallback progress_callback,
  100248. void *client_data
  100249. )
  100250. {
  100251. return init_FILE_internal_enc(encoder, file, progress_callback, client_data, /*is_ogg=*/true);
  100252. }
  100253. static FLAC__StreamEncoderInitStatus init_file_internal_enc(
  100254. FLAC__StreamEncoder *encoder,
  100255. const char *filename,
  100256. FLAC__StreamEncoderProgressCallback progress_callback,
  100257. void *client_data,
  100258. FLAC__bool is_ogg
  100259. )
  100260. {
  100261. FILE *file;
  100262. FLAC__ASSERT(0 != encoder);
  100263. /*
  100264. * To make sure that our file does not go unclosed after an error, we
  100265. * have to do the same entrance checks here that are later performed
  100266. * in FLAC__stream_encoder_init_FILE() before the FILE* is assigned.
  100267. */
  100268. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  100269. return FLAC__STREAM_ENCODER_INIT_STATUS_ALREADY_INITIALIZED;
  100270. file = filename? fopen(filename, "w+b") : stdout;
  100271. if(file == 0) {
  100272. encoder->protected_->state = FLAC__STREAM_ENCODER_IO_ERROR;
  100273. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  100274. }
  100275. return init_FILE_internal_enc(encoder, file, progress_callback, client_data, is_ogg);
  100276. }
  100277. FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_file(
  100278. FLAC__StreamEncoder *encoder,
  100279. const char *filename,
  100280. FLAC__StreamEncoderProgressCallback progress_callback,
  100281. void *client_data
  100282. )
  100283. {
  100284. return init_file_internal_enc(encoder, filename, progress_callback, client_data, /*is_ogg=*/false);
  100285. }
  100286. FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_ogg_file(
  100287. FLAC__StreamEncoder *encoder,
  100288. const char *filename,
  100289. FLAC__StreamEncoderProgressCallback progress_callback,
  100290. void *client_data
  100291. )
  100292. {
  100293. return init_file_internal_enc(encoder, filename, progress_callback, client_data, /*is_ogg=*/true);
  100294. }
  100295. FLAC_API FLAC__bool FLAC__stream_encoder_finish(FLAC__StreamEncoder *encoder)
  100296. {
  100297. FLAC__bool error = false;
  100298. FLAC__ASSERT(0 != encoder);
  100299. FLAC__ASSERT(0 != encoder->private_);
  100300. FLAC__ASSERT(0 != encoder->protected_);
  100301. if(encoder->protected_->state == FLAC__STREAM_ENCODER_UNINITIALIZED)
  100302. return true;
  100303. if(encoder->protected_->state == FLAC__STREAM_ENCODER_OK && !encoder->private_->is_being_deleted) {
  100304. if(encoder->private_->current_sample_number != 0) {
  100305. const FLAC__bool is_fractional_block = encoder->protected_->blocksize != encoder->private_->current_sample_number;
  100306. encoder->protected_->blocksize = encoder->private_->current_sample_number;
  100307. if(!process_frame_(encoder, is_fractional_block, /*is_last_block=*/true))
  100308. error = true;
  100309. }
  100310. }
  100311. if(encoder->protected_->do_md5)
  100312. FLAC__MD5Final(encoder->private_->streaminfo.data.stream_info.md5sum, &encoder->private_->md5context);
  100313. if(!encoder->private_->is_being_deleted) {
  100314. if(encoder->protected_->state == FLAC__STREAM_ENCODER_OK) {
  100315. if(encoder->private_->seek_callback) {
  100316. #if FLAC__HAS_OGG
  100317. if(encoder->private_->is_ogg)
  100318. update_ogg_metadata_(encoder);
  100319. else
  100320. #endif
  100321. update_metadata_(encoder);
  100322. /* check if an error occurred while updating metadata */
  100323. if(encoder->protected_->state != FLAC__STREAM_ENCODER_OK)
  100324. error = true;
  100325. }
  100326. if(encoder->private_->metadata_callback)
  100327. encoder->private_->metadata_callback(encoder, &encoder->private_->streaminfo, encoder->private_->client_data);
  100328. }
  100329. if(encoder->protected_->verify && 0 != encoder->private_->verify.decoder && !FLAC__stream_decoder_finish(encoder->private_->verify.decoder)) {
  100330. if(!error)
  100331. encoder->protected_->state = FLAC__STREAM_ENCODER_VERIFY_MISMATCH_IN_AUDIO_DATA;
  100332. error = true;
  100333. }
  100334. }
  100335. if(0 != encoder->private_->file) {
  100336. if(encoder->private_->file != stdout)
  100337. fclose(encoder->private_->file);
  100338. encoder->private_->file = 0;
  100339. }
  100340. #if FLAC__HAS_OGG
  100341. if(encoder->private_->is_ogg)
  100342. FLAC__ogg_encoder_aspect_finish(&encoder->protected_->ogg_encoder_aspect);
  100343. #endif
  100344. free_(encoder);
  100345. set_defaults_enc(encoder);
  100346. if(!error)
  100347. encoder->protected_->state = FLAC__STREAM_ENCODER_UNINITIALIZED;
  100348. return !error;
  100349. }
  100350. FLAC_API FLAC__bool FLAC__stream_encoder_set_ogg_serial_number(FLAC__StreamEncoder *encoder, long value)
  100351. {
  100352. FLAC__ASSERT(0 != encoder);
  100353. FLAC__ASSERT(0 != encoder->private_);
  100354. FLAC__ASSERT(0 != encoder->protected_);
  100355. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  100356. return false;
  100357. #if FLAC__HAS_OGG
  100358. /* can't check encoder->private_->is_ogg since that's not set until init time */
  100359. FLAC__ogg_encoder_aspect_set_serial_number(&encoder->protected_->ogg_encoder_aspect, value);
  100360. return true;
  100361. #else
  100362. (void)value;
  100363. return false;
  100364. #endif
  100365. }
  100366. FLAC_API FLAC__bool FLAC__stream_encoder_set_verify(FLAC__StreamEncoder *encoder, FLAC__bool value)
  100367. {
  100368. FLAC__ASSERT(0 != encoder);
  100369. FLAC__ASSERT(0 != encoder->private_);
  100370. FLAC__ASSERT(0 != encoder->protected_);
  100371. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  100372. return false;
  100373. #ifndef FLAC__MANDATORY_VERIFY_WHILE_ENCODING
  100374. encoder->protected_->verify = value;
  100375. #endif
  100376. return true;
  100377. }
  100378. FLAC_API FLAC__bool FLAC__stream_encoder_set_streamable_subset(FLAC__StreamEncoder *encoder, FLAC__bool value)
  100379. {
  100380. FLAC__ASSERT(0 != encoder);
  100381. FLAC__ASSERT(0 != encoder->private_);
  100382. FLAC__ASSERT(0 != encoder->protected_);
  100383. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  100384. return false;
  100385. encoder->protected_->streamable_subset = value;
  100386. return true;
  100387. }
  100388. FLAC_API FLAC__bool FLAC__stream_encoder_set_do_md5(FLAC__StreamEncoder *encoder, FLAC__bool value)
  100389. {
  100390. FLAC__ASSERT(0 != encoder);
  100391. FLAC__ASSERT(0 != encoder->private_);
  100392. FLAC__ASSERT(0 != encoder->protected_);
  100393. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  100394. return false;
  100395. encoder->protected_->do_md5 = value;
  100396. return true;
  100397. }
  100398. FLAC_API FLAC__bool FLAC__stream_encoder_set_channels(FLAC__StreamEncoder *encoder, unsigned value)
  100399. {
  100400. FLAC__ASSERT(0 != encoder);
  100401. FLAC__ASSERT(0 != encoder->private_);
  100402. FLAC__ASSERT(0 != encoder->protected_);
  100403. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  100404. return false;
  100405. encoder->protected_->channels = value;
  100406. return true;
  100407. }
  100408. FLAC_API FLAC__bool FLAC__stream_encoder_set_bits_per_sample(FLAC__StreamEncoder *encoder, unsigned value)
  100409. {
  100410. FLAC__ASSERT(0 != encoder);
  100411. FLAC__ASSERT(0 != encoder->private_);
  100412. FLAC__ASSERT(0 != encoder->protected_);
  100413. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  100414. return false;
  100415. encoder->protected_->bits_per_sample = value;
  100416. return true;
  100417. }
  100418. FLAC_API FLAC__bool FLAC__stream_encoder_set_sample_rate(FLAC__StreamEncoder *encoder, unsigned value)
  100419. {
  100420. FLAC__ASSERT(0 != encoder);
  100421. FLAC__ASSERT(0 != encoder->private_);
  100422. FLAC__ASSERT(0 != encoder->protected_);
  100423. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  100424. return false;
  100425. encoder->protected_->sample_rate = value;
  100426. return true;
  100427. }
  100428. FLAC_API FLAC__bool FLAC__stream_encoder_set_compression_level(FLAC__StreamEncoder *encoder, unsigned value)
  100429. {
  100430. FLAC__bool ok = true;
  100431. FLAC__ASSERT(0 != encoder);
  100432. FLAC__ASSERT(0 != encoder->private_);
  100433. FLAC__ASSERT(0 != encoder->protected_);
  100434. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  100435. return false;
  100436. if(value >= sizeof(compression_levels_)/sizeof(compression_levels_[0]))
  100437. value = sizeof(compression_levels_)/sizeof(compression_levels_[0]) - 1;
  100438. ok &= FLAC__stream_encoder_set_do_mid_side_stereo (encoder, compression_levels_[value].do_mid_side_stereo);
  100439. ok &= FLAC__stream_encoder_set_loose_mid_side_stereo (encoder, compression_levels_[value].loose_mid_side_stereo);
  100440. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  100441. #if 0
  100442. /* was: */
  100443. ok &= FLAC__stream_encoder_set_apodization (encoder, compression_levels_[value].apodization);
  100444. /* but it's too hard to specify the string in a locale-specific way */
  100445. #else
  100446. encoder->protected_->num_apodizations = 1;
  100447. encoder->protected_->apodizations[0].type = FLAC__APODIZATION_TUKEY;
  100448. encoder->protected_->apodizations[0].parameters.tukey.p = 0.5;
  100449. #endif
  100450. #endif
  100451. ok &= FLAC__stream_encoder_set_max_lpc_order (encoder, compression_levels_[value].max_lpc_order);
  100452. ok &= FLAC__stream_encoder_set_qlp_coeff_precision (encoder, compression_levels_[value].qlp_coeff_precision);
  100453. ok &= FLAC__stream_encoder_set_do_qlp_coeff_prec_search (encoder, compression_levels_[value].do_qlp_coeff_prec_search);
  100454. ok &= FLAC__stream_encoder_set_do_escape_coding (encoder, compression_levels_[value].do_escape_coding);
  100455. ok &= FLAC__stream_encoder_set_do_exhaustive_model_search (encoder, compression_levels_[value].do_exhaustive_model_search);
  100456. ok &= FLAC__stream_encoder_set_min_residual_partition_order(encoder, compression_levels_[value].min_residual_partition_order);
  100457. ok &= FLAC__stream_encoder_set_max_residual_partition_order(encoder, compression_levels_[value].max_residual_partition_order);
  100458. ok &= FLAC__stream_encoder_set_rice_parameter_search_dist (encoder, compression_levels_[value].rice_parameter_search_dist);
  100459. return ok;
  100460. }
  100461. FLAC_API FLAC__bool FLAC__stream_encoder_set_blocksize(FLAC__StreamEncoder *encoder, unsigned value)
  100462. {
  100463. FLAC__ASSERT(0 != encoder);
  100464. FLAC__ASSERT(0 != encoder->private_);
  100465. FLAC__ASSERT(0 != encoder->protected_);
  100466. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  100467. return false;
  100468. encoder->protected_->blocksize = value;
  100469. return true;
  100470. }
  100471. FLAC_API FLAC__bool FLAC__stream_encoder_set_do_mid_side_stereo(FLAC__StreamEncoder *encoder, FLAC__bool value)
  100472. {
  100473. FLAC__ASSERT(0 != encoder);
  100474. FLAC__ASSERT(0 != encoder->private_);
  100475. FLAC__ASSERT(0 != encoder->protected_);
  100476. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  100477. return false;
  100478. encoder->protected_->do_mid_side_stereo = value;
  100479. return true;
  100480. }
  100481. FLAC_API FLAC__bool FLAC__stream_encoder_set_loose_mid_side_stereo(FLAC__StreamEncoder *encoder, FLAC__bool value)
  100482. {
  100483. FLAC__ASSERT(0 != encoder);
  100484. FLAC__ASSERT(0 != encoder->private_);
  100485. FLAC__ASSERT(0 != encoder->protected_);
  100486. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  100487. return false;
  100488. encoder->protected_->loose_mid_side_stereo = value;
  100489. return true;
  100490. }
  100491. /*@@@@add to tests*/
  100492. FLAC_API FLAC__bool FLAC__stream_encoder_set_apodization(FLAC__StreamEncoder *encoder, const char *specification)
  100493. {
  100494. FLAC__ASSERT(0 != encoder);
  100495. FLAC__ASSERT(0 != encoder->private_);
  100496. FLAC__ASSERT(0 != encoder->protected_);
  100497. FLAC__ASSERT(0 != specification);
  100498. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  100499. return false;
  100500. #ifdef FLAC__INTEGER_ONLY_LIBRARY
  100501. (void)specification; /* silently ignore since we haven't integerized; will always use a rectangular window */
  100502. #else
  100503. encoder->protected_->num_apodizations = 0;
  100504. while(1) {
  100505. const char *s = strchr(specification, ';');
  100506. const size_t n = s? (size_t)(s - specification) : strlen(specification);
  100507. if (n==8 && 0 == strncmp("bartlett" , specification, n))
  100508. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_BARTLETT;
  100509. else if(n==13 && 0 == strncmp("bartlett_hann", specification, n))
  100510. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_BARTLETT_HANN;
  100511. else if(n==8 && 0 == strncmp("blackman" , specification, n))
  100512. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_BLACKMAN;
  100513. else if(n==26 && 0 == strncmp("blackman_harris_4term_92db", specification, n))
  100514. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_BLACKMAN_HARRIS_4TERM_92DB_SIDELOBE;
  100515. else if(n==6 && 0 == strncmp("connes" , specification, n))
  100516. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_CONNES;
  100517. else if(n==7 && 0 == strncmp("flattop" , specification, n))
  100518. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_FLATTOP;
  100519. else if(n>7 && 0 == strncmp("gauss(" , specification, 6)) {
  100520. FLAC__real stddev = (FLAC__real)strtod(specification+6, 0);
  100521. if (stddev > 0.0 && stddev <= 0.5) {
  100522. encoder->protected_->apodizations[encoder->protected_->num_apodizations].parameters.gauss.stddev = stddev;
  100523. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_GAUSS;
  100524. }
  100525. }
  100526. else if(n==7 && 0 == strncmp("hamming" , specification, n))
  100527. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_HAMMING;
  100528. else if(n==4 && 0 == strncmp("hann" , specification, n))
  100529. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_HANN;
  100530. else if(n==13 && 0 == strncmp("kaiser_bessel", specification, n))
  100531. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_KAISER_BESSEL;
  100532. else if(n==7 && 0 == strncmp("nuttall" , specification, n))
  100533. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_NUTTALL;
  100534. else if(n==9 && 0 == strncmp("rectangle" , specification, n))
  100535. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_RECTANGLE;
  100536. else if(n==8 && 0 == strncmp("triangle" , specification, n))
  100537. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_TRIANGLE;
  100538. else if(n>7 && 0 == strncmp("tukey(" , specification, 6)) {
  100539. FLAC__real p = (FLAC__real)strtod(specification+6, 0);
  100540. if (p >= 0.0 && p <= 1.0) {
  100541. encoder->protected_->apodizations[encoder->protected_->num_apodizations].parameters.tukey.p = p;
  100542. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_TUKEY;
  100543. }
  100544. }
  100545. else if(n==5 && 0 == strncmp("welch" , specification, n))
  100546. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_WELCH;
  100547. if (encoder->protected_->num_apodizations == 32)
  100548. break;
  100549. if (s)
  100550. specification = s+1;
  100551. else
  100552. break;
  100553. }
  100554. if(encoder->protected_->num_apodizations == 0) {
  100555. encoder->protected_->num_apodizations = 1;
  100556. encoder->protected_->apodizations[0].type = FLAC__APODIZATION_TUKEY;
  100557. encoder->protected_->apodizations[0].parameters.tukey.p = 0.5;
  100558. }
  100559. #endif
  100560. return true;
  100561. }
  100562. FLAC_API FLAC__bool FLAC__stream_encoder_set_max_lpc_order(FLAC__StreamEncoder *encoder, unsigned value)
  100563. {
  100564. FLAC__ASSERT(0 != encoder);
  100565. FLAC__ASSERT(0 != encoder->private_);
  100566. FLAC__ASSERT(0 != encoder->protected_);
  100567. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  100568. return false;
  100569. encoder->protected_->max_lpc_order = value;
  100570. return true;
  100571. }
  100572. FLAC_API FLAC__bool FLAC__stream_encoder_set_qlp_coeff_precision(FLAC__StreamEncoder *encoder, unsigned value)
  100573. {
  100574. FLAC__ASSERT(0 != encoder);
  100575. FLAC__ASSERT(0 != encoder->private_);
  100576. FLAC__ASSERT(0 != encoder->protected_);
  100577. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  100578. return false;
  100579. encoder->protected_->qlp_coeff_precision = value;
  100580. return true;
  100581. }
  100582. FLAC_API FLAC__bool FLAC__stream_encoder_set_do_qlp_coeff_prec_search(FLAC__StreamEncoder *encoder, FLAC__bool value)
  100583. {
  100584. FLAC__ASSERT(0 != encoder);
  100585. FLAC__ASSERT(0 != encoder->private_);
  100586. FLAC__ASSERT(0 != encoder->protected_);
  100587. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  100588. return false;
  100589. encoder->protected_->do_qlp_coeff_prec_search = value;
  100590. return true;
  100591. }
  100592. FLAC_API FLAC__bool FLAC__stream_encoder_set_do_escape_coding(FLAC__StreamEncoder *encoder, FLAC__bool value)
  100593. {
  100594. FLAC__ASSERT(0 != encoder);
  100595. FLAC__ASSERT(0 != encoder->private_);
  100596. FLAC__ASSERT(0 != encoder->protected_);
  100597. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  100598. return false;
  100599. #if 0
  100600. /*@@@ deprecated: */
  100601. encoder->protected_->do_escape_coding = value;
  100602. #else
  100603. (void)value;
  100604. #endif
  100605. return true;
  100606. }
  100607. FLAC_API FLAC__bool FLAC__stream_encoder_set_do_exhaustive_model_search(FLAC__StreamEncoder *encoder, FLAC__bool value)
  100608. {
  100609. FLAC__ASSERT(0 != encoder);
  100610. FLAC__ASSERT(0 != encoder->private_);
  100611. FLAC__ASSERT(0 != encoder->protected_);
  100612. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  100613. return false;
  100614. encoder->protected_->do_exhaustive_model_search = value;
  100615. return true;
  100616. }
  100617. FLAC_API FLAC__bool FLAC__stream_encoder_set_min_residual_partition_order(FLAC__StreamEncoder *encoder, unsigned value)
  100618. {
  100619. FLAC__ASSERT(0 != encoder);
  100620. FLAC__ASSERT(0 != encoder->private_);
  100621. FLAC__ASSERT(0 != encoder->protected_);
  100622. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  100623. return false;
  100624. encoder->protected_->min_residual_partition_order = value;
  100625. return true;
  100626. }
  100627. FLAC_API FLAC__bool FLAC__stream_encoder_set_max_residual_partition_order(FLAC__StreamEncoder *encoder, unsigned value)
  100628. {
  100629. FLAC__ASSERT(0 != encoder);
  100630. FLAC__ASSERT(0 != encoder->private_);
  100631. FLAC__ASSERT(0 != encoder->protected_);
  100632. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  100633. return false;
  100634. encoder->protected_->max_residual_partition_order = value;
  100635. return true;
  100636. }
  100637. FLAC_API FLAC__bool FLAC__stream_encoder_set_rice_parameter_search_dist(FLAC__StreamEncoder *encoder, unsigned value)
  100638. {
  100639. FLAC__ASSERT(0 != encoder);
  100640. FLAC__ASSERT(0 != encoder->private_);
  100641. FLAC__ASSERT(0 != encoder->protected_);
  100642. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  100643. return false;
  100644. #if 0
  100645. /*@@@ deprecated: */
  100646. encoder->protected_->rice_parameter_search_dist = value;
  100647. #else
  100648. (void)value;
  100649. #endif
  100650. return true;
  100651. }
  100652. FLAC_API FLAC__bool FLAC__stream_encoder_set_total_samples_estimate(FLAC__StreamEncoder *encoder, FLAC__uint64 value)
  100653. {
  100654. FLAC__ASSERT(0 != encoder);
  100655. FLAC__ASSERT(0 != encoder->private_);
  100656. FLAC__ASSERT(0 != encoder->protected_);
  100657. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  100658. return false;
  100659. encoder->protected_->total_samples_estimate = value;
  100660. return true;
  100661. }
  100662. FLAC_API FLAC__bool FLAC__stream_encoder_set_metadata(FLAC__StreamEncoder *encoder, FLAC__StreamMetadata **metadata, unsigned num_blocks)
  100663. {
  100664. FLAC__ASSERT(0 != encoder);
  100665. FLAC__ASSERT(0 != encoder->private_);
  100666. FLAC__ASSERT(0 != encoder->protected_);
  100667. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  100668. return false;
  100669. if(0 == metadata)
  100670. num_blocks = 0;
  100671. if(0 == num_blocks)
  100672. metadata = 0;
  100673. /* realloc() does not do exactly what we want so... */
  100674. if(encoder->protected_->metadata) {
  100675. free(encoder->protected_->metadata);
  100676. encoder->protected_->metadata = 0;
  100677. encoder->protected_->num_metadata_blocks = 0;
  100678. }
  100679. if(num_blocks) {
  100680. FLAC__StreamMetadata **m;
  100681. if(0 == (m = (FLAC__StreamMetadata**)safe_malloc_mul_2op_(sizeof(m[0]), /*times*/num_blocks)))
  100682. return false;
  100683. memcpy(m, metadata, sizeof(m[0]) * num_blocks);
  100684. encoder->protected_->metadata = m;
  100685. encoder->protected_->num_metadata_blocks = num_blocks;
  100686. }
  100687. #if FLAC__HAS_OGG
  100688. if(!FLAC__ogg_encoder_aspect_set_num_metadata(&encoder->protected_->ogg_encoder_aspect, num_blocks))
  100689. return false;
  100690. #endif
  100691. return true;
  100692. }
  100693. /*
  100694. * These three functions are not static, but not publically exposed in
  100695. * include/FLAC/ either. They are used by the test suite.
  100696. */
  100697. FLAC_API FLAC__bool FLAC__stream_encoder_disable_constant_subframes(FLAC__StreamEncoder *encoder, FLAC__bool value)
  100698. {
  100699. FLAC__ASSERT(0 != encoder);
  100700. FLAC__ASSERT(0 != encoder->private_);
  100701. FLAC__ASSERT(0 != encoder->protected_);
  100702. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  100703. return false;
  100704. encoder->private_->disable_constant_subframes = value;
  100705. return true;
  100706. }
  100707. FLAC_API FLAC__bool FLAC__stream_encoder_disable_fixed_subframes(FLAC__StreamEncoder *encoder, FLAC__bool value)
  100708. {
  100709. FLAC__ASSERT(0 != encoder);
  100710. FLAC__ASSERT(0 != encoder->private_);
  100711. FLAC__ASSERT(0 != encoder->protected_);
  100712. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  100713. return false;
  100714. encoder->private_->disable_fixed_subframes = value;
  100715. return true;
  100716. }
  100717. FLAC_API FLAC__bool FLAC__stream_encoder_disable_verbatim_subframes(FLAC__StreamEncoder *encoder, FLAC__bool value)
  100718. {
  100719. FLAC__ASSERT(0 != encoder);
  100720. FLAC__ASSERT(0 != encoder->private_);
  100721. FLAC__ASSERT(0 != encoder->protected_);
  100722. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  100723. return false;
  100724. encoder->private_->disable_verbatim_subframes = value;
  100725. return true;
  100726. }
  100727. FLAC_API FLAC__StreamEncoderState FLAC__stream_encoder_get_state(const FLAC__StreamEncoder *encoder)
  100728. {
  100729. FLAC__ASSERT(0 != encoder);
  100730. FLAC__ASSERT(0 != encoder->private_);
  100731. FLAC__ASSERT(0 != encoder->protected_);
  100732. return encoder->protected_->state;
  100733. }
  100734. FLAC_API FLAC__StreamDecoderState FLAC__stream_encoder_get_verify_decoder_state(const FLAC__StreamEncoder *encoder)
  100735. {
  100736. FLAC__ASSERT(0 != encoder);
  100737. FLAC__ASSERT(0 != encoder->private_);
  100738. FLAC__ASSERT(0 != encoder->protected_);
  100739. if(encoder->protected_->verify)
  100740. return FLAC__stream_decoder_get_state(encoder->private_->verify.decoder);
  100741. else
  100742. return FLAC__STREAM_DECODER_UNINITIALIZED;
  100743. }
  100744. FLAC_API const char *FLAC__stream_encoder_get_resolved_state_string(const FLAC__StreamEncoder *encoder)
  100745. {
  100746. FLAC__ASSERT(0 != encoder);
  100747. FLAC__ASSERT(0 != encoder->private_);
  100748. FLAC__ASSERT(0 != encoder->protected_);
  100749. if(encoder->protected_->state != FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR)
  100750. return FLAC__StreamEncoderStateString[encoder->protected_->state];
  100751. else
  100752. return FLAC__stream_decoder_get_resolved_state_string(encoder->private_->verify.decoder);
  100753. }
  100754. 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)
  100755. {
  100756. FLAC__ASSERT(0 != encoder);
  100757. FLAC__ASSERT(0 != encoder->private_);
  100758. FLAC__ASSERT(0 != encoder->protected_);
  100759. if(0 != absolute_sample)
  100760. *absolute_sample = encoder->private_->verify.error_stats.absolute_sample;
  100761. if(0 != frame_number)
  100762. *frame_number = encoder->private_->verify.error_stats.frame_number;
  100763. if(0 != channel)
  100764. *channel = encoder->private_->verify.error_stats.channel;
  100765. if(0 != sample)
  100766. *sample = encoder->private_->verify.error_stats.sample;
  100767. if(0 != expected)
  100768. *expected = encoder->private_->verify.error_stats.expected;
  100769. if(0 != got)
  100770. *got = encoder->private_->verify.error_stats.got;
  100771. }
  100772. FLAC_API FLAC__bool FLAC__stream_encoder_get_verify(const FLAC__StreamEncoder *encoder)
  100773. {
  100774. FLAC__ASSERT(0 != encoder);
  100775. FLAC__ASSERT(0 != encoder->private_);
  100776. FLAC__ASSERT(0 != encoder->protected_);
  100777. return encoder->protected_->verify;
  100778. }
  100779. FLAC_API FLAC__bool FLAC__stream_encoder_get_streamable_subset(const FLAC__StreamEncoder *encoder)
  100780. {
  100781. FLAC__ASSERT(0 != encoder);
  100782. FLAC__ASSERT(0 != encoder->private_);
  100783. FLAC__ASSERT(0 != encoder->protected_);
  100784. return encoder->protected_->streamable_subset;
  100785. }
  100786. FLAC_API FLAC__bool FLAC__stream_encoder_get_do_md5(const FLAC__StreamEncoder *encoder)
  100787. {
  100788. FLAC__ASSERT(0 != encoder);
  100789. FLAC__ASSERT(0 != encoder->private_);
  100790. FLAC__ASSERT(0 != encoder->protected_);
  100791. return encoder->protected_->do_md5;
  100792. }
  100793. FLAC_API unsigned FLAC__stream_encoder_get_channels(const FLAC__StreamEncoder *encoder)
  100794. {
  100795. FLAC__ASSERT(0 != encoder);
  100796. FLAC__ASSERT(0 != encoder->private_);
  100797. FLAC__ASSERT(0 != encoder->protected_);
  100798. return encoder->protected_->channels;
  100799. }
  100800. FLAC_API unsigned FLAC__stream_encoder_get_bits_per_sample(const FLAC__StreamEncoder *encoder)
  100801. {
  100802. FLAC__ASSERT(0 != encoder);
  100803. FLAC__ASSERT(0 != encoder->private_);
  100804. FLAC__ASSERT(0 != encoder->protected_);
  100805. return encoder->protected_->bits_per_sample;
  100806. }
  100807. FLAC_API unsigned FLAC__stream_encoder_get_sample_rate(const FLAC__StreamEncoder *encoder)
  100808. {
  100809. FLAC__ASSERT(0 != encoder);
  100810. FLAC__ASSERT(0 != encoder->private_);
  100811. FLAC__ASSERT(0 != encoder->protected_);
  100812. return encoder->protected_->sample_rate;
  100813. }
  100814. FLAC_API unsigned FLAC__stream_encoder_get_blocksize(const FLAC__StreamEncoder *encoder)
  100815. {
  100816. FLAC__ASSERT(0 != encoder);
  100817. FLAC__ASSERT(0 != encoder->private_);
  100818. FLAC__ASSERT(0 != encoder->protected_);
  100819. return encoder->protected_->blocksize;
  100820. }
  100821. FLAC_API FLAC__bool FLAC__stream_encoder_get_do_mid_side_stereo(const FLAC__StreamEncoder *encoder)
  100822. {
  100823. FLAC__ASSERT(0 != encoder);
  100824. FLAC__ASSERT(0 != encoder->private_);
  100825. FLAC__ASSERT(0 != encoder->protected_);
  100826. return encoder->protected_->do_mid_side_stereo;
  100827. }
  100828. FLAC_API FLAC__bool FLAC__stream_encoder_get_loose_mid_side_stereo(const FLAC__StreamEncoder *encoder)
  100829. {
  100830. FLAC__ASSERT(0 != encoder);
  100831. FLAC__ASSERT(0 != encoder->private_);
  100832. FLAC__ASSERT(0 != encoder->protected_);
  100833. return encoder->protected_->loose_mid_side_stereo;
  100834. }
  100835. FLAC_API unsigned FLAC__stream_encoder_get_max_lpc_order(const FLAC__StreamEncoder *encoder)
  100836. {
  100837. FLAC__ASSERT(0 != encoder);
  100838. FLAC__ASSERT(0 != encoder->private_);
  100839. FLAC__ASSERT(0 != encoder->protected_);
  100840. return encoder->protected_->max_lpc_order;
  100841. }
  100842. FLAC_API unsigned FLAC__stream_encoder_get_qlp_coeff_precision(const FLAC__StreamEncoder *encoder)
  100843. {
  100844. FLAC__ASSERT(0 != encoder);
  100845. FLAC__ASSERT(0 != encoder->private_);
  100846. FLAC__ASSERT(0 != encoder->protected_);
  100847. return encoder->protected_->qlp_coeff_precision;
  100848. }
  100849. FLAC_API FLAC__bool FLAC__stream_encoder_get_do_qlp_coeff_prec_search(const FLAC__StreamEncoder *encoder)
  100850. {
  100851. FLAC__ASSERT(0 != encoder);
  100852. FLAC__ASSERT(0 != encoder->private_);
  100853. FLAC__ASSERT(0 != encoder->protected_);
  100854. return encoder->protected_->do_qlp_coeff_prec_search;
  100855. }
  100856. FLAC_API FLAC__bool FLAC__stream_encoder_get_do_escape_coding(const FLAC__StreamEncoder *encoder)
  100857. {
  100858. FLAC__ASSERT(0 != encoder);
  100859. FLAC__ASSERT(0 != encoder->private_);
  100860. FLAC__ASSERT(0 != encoder->protected_);
  100861. return encoder->protected_->do_escape_coding;
  100862. }
  100863. FLAC_API FLAC__bool FLAC__stream_encoder_get_do_exhaustive_model_search(const FLAC__StreamEncoder *encoder)
  100864. {
  100865. FLAC__ASSERT(0 != encoder);
  100866. FLAC__ASSERT(0 != encoder->private_);
  100867. FLAC__ASSERT(0 != encoder->protected_);
  100868. return encoder->protected_->do_exhaustive_model_search;
  100869. }
  100870. FLAC_API unsigned FLAC__stream_encoder_get_min_residual_partition_order(const FLAC__StreamEncoder *encoder)
  100871. {
  100872. FLAC__ASSERT(0 != encoder);
  100873. FLAC__ASSERT(0 != encoder->private_);
  100874. FLAC__ASSERT(0 != encoder->protected_);
  100875. return encoder->protected_->min_residual_partition_order;
  100876. }
  100877. FLAC_API unsigned FLAC__stream_encoder_get_max_residual_partition_order(const FLAC__StreamEncoder *encoder)
  100878. {
  100879. FLAC__ASSERT(0 != encoder);
  100880. FLAC__ASSERT(0 != encoder->private_);
  100881. FLAC__ASSERT(0 != encoder->protected_);
  100882. return encoder->protected_->max_residual_partition_order;
  100883. }
  100884. FLAC_API unsigned FLAC__stream_encoder_get_rice_parameter_search_dist(const FLAC__StreamEncoder *encoder)
  100885. {
  100886. FLAC__ASSERT(0 != encoder);
  100887. FLAC__ASSERT(0 != encoder->private_);
  100888. FLAC__ASSERT(0 != encoder->protected_);
  100889. return encoder->protected_->rice_parameter_search_dist;
  100890. }
  100891. FLAC_API FLAC__uint64 FLAC__stream_encoder_get_total_samples_estimate(const FLAC__StreamEncoder *encoder)
  100892. {
  100893. FLAC__ASSERT(0 != encoder);
  100894. FLAC__ASSERT(0 != encoder->private_);
  100895. FLAC__ASSERT(0 != encoder->protected_);
  100896. return encoder->protected_->total_samples_estimate;
  100897. }
  100898. FLAC_API FLAC__bool FLAC__stream_encoder_process(FLAC__StreamEncoder *encoder, const FLAC__int32 * const buffer[], unsigned samples)
  100899. {
  100900. unsigned i, j = 0, channel;
  100901. const unsigned channels = encoder->protected_->channels, blocksize = encoder->protected_->blocksize;
  100902. FLAC__ASSERT(0 != encoder);
  100903. FLAC__ASSERT(0 != encoder->private_);
  100904. FLAC__ASSERT(0 != encoder->protected_);
  100905. FLAC__ASSERT(encoder->protected_->state == FLAC__STREAM_ENCODER_OK);
  100906. do {
  100907. const unsigned n = min(blocksize+OVERREAD_-encoder->private_->current_sample_number, samples-j);
  100908. if(encoder->protected_->verify)
  100909. append_to_verify_fifo_(&encoder->private_->verify.input_fifo, buffer, j, channels, n);
  100910. for(channel = 0; channel < channels; channel++)
  100911. memcpy(&encoder->private_->integer_signal[channel][encoder->private_->current_sample_number], &buffer[channel][j], sizeof(buffer[channel][0]) * n);
  100912. if(encoder->protected_->do_mid_side_stereo) {
  100913. FLAC__ASSERT(channels == 2);
  100914. /* "i <= blocksize" to overread 1 sample; see comment in OVERREAD_ decl */
  100915. for(i = encoder->private_->current_sample_number; i <= blocksize && j < samples; i++, j++) {
  100916. encoder->private_->integer_signal_mid_side[1][i] = buffer[0][j] - buffer[1][j];
  100917. 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' ! */
  100918. }
  100919. }
  100920. else
  100921. j += n;
  100922. encoder->private_->current_sample_number += n;
  100923. /* we only process if we have a full block + 1 extra sample; final block is always handled by FLAC__stream_encoder_finish() */
  100924. if(encoder->private_->current_sample_number > blocksize) {
  100925. FLAC__ASSERT(encoder->private_->current_sample_number == blocksize+OVERREAD_);
  100926. FLAC__ASSERT(OVERREAD_ == 1); /* assert we only overread 1 sample which simplifies the rest of the code below */
  100927. if(!process_frame_(encoder, /*is_fractional_block=*/false, /*is_last_block=*/false))
  100928. return false;
  100929. /* move unprocessed overread samples to beginnings of arrays */
  100930. for(channel = 0; channel < channels; channel++)
  100931. encoder->private_->integer_signal[channel][0] = encoder->private_->integer_signal[channel][blocksize];
  100932. if(encoder->protected_->do_mid_side_stereo) {
  100933. encoder->private_->integer_signal_mid_side[0][0] = encoder->private_->integer_signal_mid_side[0][blocksize];
  100934. encoder->private_->integer_signal_mid_side[1][0] = encoder->private_->integer_signal_mid_side[1][blocksize];
  100935. }
  100936. encoder->private_->current_sample_number = 1;
  100937. }
  100938. } while(j < samples);
  100939. return true;
  100940. }
  100941. FLAC_API FLAC__bool FLAC__stream_encoder_process_interleaved(FLAC__StreamEncoder *encoder, const FLAC__int32 buffer[], unsigned samples)
  100942. {
  100943. unsigned i, j, k, channel;
  100944. FLAC__int32 x, mid, side;
  100945. const unsigned channels = encoder->protected_->channels, blocksize = encoder->protected_->blocksize;
  100946. FLAC__ASSERT(0 != encoder);
  100947. FLAC__ASSERT(0 != encoder->private_);
  100948. FLAC__ASSERT(0 != encoder->protected_);
  100949. FLAC__ASSERT(encoder->protected_->state == FLAC__STREAM_ENCODER_OK);
  100950. j = k = 0;
  100951. /*
  100952. * we have several flavors of the same basic loop, optimized for
  100953. * different conditions:
  100954. */
  100955. if(encoder->protected_->do_mid_side_stereo && channels == 2) {
  100956. /*
  100957. * stereo coding: unroll channel loop
  100958. */
  100959. do {
  100960. if(encoder->protected_->verify)
  100961. append_to_verify_fifo_interleaved_(&encoder->private_->verify.input_fifo, buffer, j, channels, min(blocksize+OVERREAD_-encoder->private_->current_sample_number, samples-j));
  100962. /* "i <= blocksize" to overread 1 sample; see comment in OVERREAD_ decl */
  100963. for(i = encoder->private_->current_sample_number; i <= blocksize && j < samples; i++, j++) {
  100964. encoder->private_->integer_signal[0][i] = mid = side = buffer[k++];
  100965. x = buffer[k++];
  100966. encoder->private_->integer_signal[1][i] = x;
  100967. mid += x;
  100968. side -= x;
  100969. mid >>= 1; /* NOTE: not the same as 'mid = (left + right) / 2' ! */
  100970. encoder->private_->integer_signal_mid_side[1][i] = side;
  100971. encoder->private_->integer_signal_mid_side[0][i] = mid;
  100972. }
  100973. encoder->private_->current_sample_number = i;
  100974. /* we only process if we have a full block + 1 extra sample; final block is always handled by FLAC__stream_encoder_finish() */
  100975. if(i > blocksize) {
  100976. if(!process_frame_(encoder, /*is_fractional_block=*/false, /*is_last_block=*/false))
  100977. return false;
  100978. /* move unprocessed overread samples to beginnings of arrays */
  100979. FLAC__ASSERT(i == blocksize+OVERREAD_);
  100980. FLAC__ASSERT(OVERREAD_ == 1); /* assert we only overread 1 sample which simplifies the rest of the code below */
  100981. encoder->private_->integer_signal[0][0] = encoder->private_->integer_signal[0][blocksize];
  100982. encoder->private_->integer_signal[1][0] = encoder->private_->integer_signal[1][blocksize];
  100983. encoder->private_->integer_signal_mid_side[0][0] = encoder->private_->integer_signal_mid_side[0][blocksize];
  100984. encoder->private_->integer_signal_mid_side[1][0] = encoder->private_->integer_signal_mid_side[1][blocksize];
  100985. encoder->private_->current_sample_number = 1;
  100986. }
  100987. } while(j < samples);
  100988. }
  100989. else {
  100990. /*
  100991. * independent channel coding: buffer each channel in inner loop
  100992. */
  100993. do {
  100994. if(encoder->protected_->verify)
  100995. append_to_verify_fifo_interleaved_(&encoder->private_->verify.input_fifo, buffer, j, channels, min(blocksize+OVERREAD_-encoder->private_->current_sample_number, samples-j));
  100996. /* "i <= blocksize" to overread 1 sample; see comment in OVERREAD_ decl */
  100997. for(i = encoder->private_->current_sample_number; i <= blocksize && j < samples; i++, j++) {
  100998. for(channel = 0; channel < channels; channel++)
  100999. encoder->private_->integer_signal[channel][i] = buffer[k++];
  101000. }
  101001. encoder->private_->current_sample_number = i;
  101002. /* we only process if we have a full block + 1 extra sample; final block is always handled by FLAC__stream_encoder_finish() */
  101003. if(i > blocksize) {
  101004. if(!process_frame_(encoder, /*is_fractional_block=*/false, /*is_last_block=*/false))
  101005. return false;
  101006. /* move unprocessed overread samples to beginnings of arrays */
  101007. FLAC__ASSERT(i == blocksize+OVERREAD_);
  101008. FLAC__ASSERT(OVERREAD_ == 1); /* assert we only overread 1 sample which simplifies the rest of the code below */
  101009. for(channel = 0; channel < channels; channel++)
  101010. encoder->private_->integer_signal[channel][0] = encoder->private_->integer_signal[channel][blocksize];
  101011. encoder->private_->current_sample_number = 1;
  101012. }
  101013. } while(j < samples);
  101014. }
  101015. return true;
  101016. }
  101017. /***********************************************************************
  101018. *
  101019. * Private class methods
  101020. *
  101021. ***********************************************************************/
  101022. void set_defaults_enc(FLAC__StreamEncoder *encoder)
  101023. {
  101024. FLAC__ASSERT(0 != encoder);
  101025. #ifdef FLAC__MANDATORY_VERIFY_WHILE_ENCODING
  101026. encoder->protected_->verify = true;
  101027. #else
  101028. encoder->protected_->verify = false;
  101029. #endif
  101030. encoder->protected_->streamable_subset = true;
  101031. encoder->protected_->do_md5 = true;
  101032. encoder->protected_->do_mid_side_stereo = false;
  101033. encoder->protected_->loose_mid_side_stereo = false;
  101034. encoder->protected_->channels = 2;
  101035. encoder->protected_->bits_per_sample = 16;
  101036. encoder->protected_->sample_rate = 44100;
  101037. encoder->protected_->blocksize = 0;
  101038. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  101039. encoder->protected_->num_apodizations = 1;
  101040. encoder->protected_->apodizations[0].type = FLAC__APODIZATION_TUKEY;
  101041. encoder->protected_->apodizations[0].parameters.tukey.p = 0.5;
  101042. #endif
  101043. encoder->protected_->max_lpc_order = 0;
  101044. encoder->protected_->qlp_coeff_precision = 0;
  101045. encoder->protected_->do_qlp_coeff_prec_search = false;
  101046. encoder->protected_->do_exhaustive_model_search = false;
  101047. encoder->protected_->do_escape_coding = false;
  101048. encoder->protected_->min_residual_partition_order = 0;
  101049. encoder->protected_->max_residual_partition_order = 0;
  101050. encoder->protected_->rice_parameter_search_dist = 0;
  101051. encoder->protected_->total_samples_estimate = 0;
  101052. encoder->protected_->metadata = 0;
  101053. encoder->protected_->num_metadata_blocks = 0;
  101054. encoder->private_->seek_table = 0;
  101055. encoder->private_->disable_constant_subframes = false;
  101056. encoder->private_->disable_fixed_subframes = false;
  101057. encoder->private_->disable_verbatim_subframes = false;
  101058. #if FLAC__HAS_OGG
  101059. encoder->private_->is_ogg = false;
  101060. #endif
  101061. encoder->private_->read_callback = 0;
  101062. encoder->private_->write_callback = 0;
  101063. encoder->private_->seek_callback = 0;
  101064. encoder->private_->tell_callback = 0;
  101065. encoder->private_->metadata_callback = 0;
  101066. encoder->private_->progress_callback = 0;
  101067. encoder->private_->client_data = 0;
  101068. #if FLAC__HAS_OGG
  101069. FLAC__ogg_encoder_aspect_set_defaults(&encoder->protected_->ogg_encoder_aspect);
  101070. #endif
  101071. }
  101072. void free_(FLAC__StreamEncoder *encoder)
  101073. {
  101074. unsigned i, channel;
  101075. FLAC__ASSERT(0 != encoder);
  101076. if(encoder->protected_->metadata) {
  101077. free(encoder->protected_->metadata);
  101078. encoder->protected_->metadata = 0;
  101079. encoder->protected_->num_metadata_blocks = 0;
  101080. }
  101081. for(i = 0; i < encoder->protected_->channels; i++) {
  101082. if(0 != encoder->private_->integer_signal_unaligned[i]) {
  101083. free(encoder->private_->integer_signal_unaligned[i]);
  101084. encoder->private_->integer_signal_unaligned[i] = 0;
  101085. }
  101086. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  101087. if(0 != encoder->private_->real_signal_unaligned[i]) {
  101088. free(encoder->private_->real_signal_unaligned[i]);
  101089. encoder->private_->real_signal_unaligned[i] = 0;
  101090. }
  101091. #endif
  101092. }
  101093. for(i = 0; i < 2; i++) {
  101094. if(0 != encoder->private_->integer_signal_mid_side_unaligned[i]) {
  101095. free(encoder->private_->integer_signal_mid_side_unaligned[i]);
  101096. encoder->private_->integer_signal_mid_side_unaligned[i] = 0;
  101097. }
  101098. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  101099. if(0 != encoder->private_->real_signal_mid_side_unaligned[i]) {
  101100. free(encoder->private_->real_signal_mid_side_unaligned[i]);
  101101. encoder->private_->real_signal_mid_side_unaligned[i] = 0;
  101102. }
  101103. #endif
  101104. }
  101105. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  101106. for(i = 0; i < encoder->protected_->num_apodizations; i++) {
  101107. if(0 != encoder->private_->window_unaligned[i]) {
  101108. free(encoder->private_->window_unaligned[i]);
  101109. encoder->private_->window_unaligned[i] = 0;
  101110. }
  101111. }
  101112. if(0 != encoder->private_->windowed_signal_unaligned) {
  101113. free(encoder->private_->windowed_signal_unaligned);
  101114. encoder->private_->windowed_signal_unaligned = 0;
  101115. }
  101116. #endif
  101117. for(channel = 0; channel < encoder->protected_->channels; channel++) {
  101118. for(i = 0; i < 2; i++) {
  101119. if(0 != encoder->private_->residual_workspace_unaligned[channel][i]) {
  101120. free(encoder->private_->residual_workspace_unaligned[channel][i]);
  101121. encoder->private_->residual_workspace_unaligned[channel][i] = 0;
  101122. }
  101123. }
  101124. }
  101125. for(channel = 0; channel < 2; channel++) {
  101126. for(i = 0; i < 2; i++) {
  101127. if(0 != encoder->private_->residual_workspace_mid_side_unaligned[channel][i]) {
  101128. free(encoder->private_->residual_workspace_mid_side_unaligned[channel][i]);
  101129. encoder->private_->residual_workspace_mid_side_unaligned[channel][i] = 0;
  101130. }
  101131. }
  101132. }
  101133. if(0 != encoder->private_->abs_residual_partition_sums_unaligned) {
  101134. free(encoder->private_->abs_residual_partition_sums_unaligned);
  101135. encoder->private_->abs_residual_partition_sums_unaligned = 0;
  101136. }
  101137. if(0 != encoder->private_->raw_bits_per_partition_unaligned) {
  101138. free(encoder->private_->raw_bits_per_partition_unaligned);
  101139. encoder->private_->raw_bits_per_partition_unaligned = 0;
  101140. }
  101141. if(encoder->protected_->verify) {
  101142. for(i = 0; i < encoder->protected_->channels; i++) {
  101143. if(0 != encoder->private_->verify.input_fifo.data[i]) {
  101144. free(encoder->private_->verify.input_fifo.data[i]);
  101145. encoder->private_->verify.input_fifo.data[i] = 0;
  101146. }
  101147. }
  101148. }
  101149. FLAC__bitwriter_free(encoder->private_->frame);
  101150. }
  101151. FLAC__bool resize_buffers_(FLAC__StreamEncoder *encoder, unsigned new_blocksize)
  101152. {
  101153. FLAC__bool ok;
  101154. unsigned i, channel;
  101155. FLAC__ASSERT(new_blocksize > 0);
  101156. FLAC__ASSERT(encoder->protected_->state == FLAC__STREAM_ENCODER_OK);
  101157. FLAC__ASSERT(encoder->private_->current_sample_number == 0);
  101158. /* To avoid excessive malloc'ing, we only grow the buffer; no shrinking. */
  101159. if(new_blocksize <= encoder->private_->input_capacity)
  101160. return true;
  101161. ok = true;
  101162. /* WATCHOUT: FLAC__lpc_compute_residual_from_qlp_coefficients_asm_ia32_mmx()
  101163. * requires that the input arrays (in our case the integer signals)
  101164. * have a buffer of up to 3 zeroes in front (at negative indices) for
  101165. * alignment purposes; we use 4 in front to keep the data well-aligned.
  101166. */
  101167. for(i = 0; ok && i < encoder->protected_->channels; i++) {
  101168. ok = ok && FLAC__memory_alloc_aligned_int32_array(new_blocksize+4+OVERREAD_, &encoder->private_->integer_signal_unaligned[i], &encoder->private_->integer_signal[i]);
  101169. memset(encoder->private_->integer_signal[i], 0, sizeof(FLAC__int32)*4);
  101170. encoder->private_->integer_signal[i] += 4;
  101171. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  101172. #if 0 /* @@@ currently unused */
  101173. if(encoder->protected_->max_lpc_order > 0)
  101174. ok = ok && FLAC__memory_alloc_aligned_real_array(new_blocksize+OVERREAD_, &encoder->private_->real_signal_unaligned[i], &encoder->private_->real_signal[i]);
  101175. #endif
  101176. #endif
  101177. }
  101178. for(i = 0; ok && i < 2; i++) {
  101179. 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]);
  101180. memset(encoder->private_->integer_signal_mid_side[i], 0, sizeof(FLAC__int32)*4);
  101181. encoder->private_->integer_signal_mid_side[i] += 4;
  101182. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  101183. #if 0 /* @@@ currently unused */
  101184. if(encoder->protected_->max_lpc_order > 0)
  101185. 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]);
  101186. #endif
  101187. #endif
  101188. }
  101189. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  101190. if(ok && encoder->protected_->max_lpc_order > 0) {
  101191. for(i = 0; ok && i < encoder->protected_->num_apodizations; i++)
  101192. ok = ok && FLAC__memory_alloc_aligned_real_array(new_blocksize, &encoder->private_->window_unaligned[i], &encoder->private_->window[i]);
  101193. ok = ok && FLAC__memory_alloc_aligned_real_array(new_blocksize, &encoder->private_->windowed_signal_unaligned, &encoder->private_->windowed_signal);
  101194. }
  101195. #endif
  101196. for(channel = 0; ok && channel < encoder->protected_->channels; channel++) {
  101197. for(i = 0; ok && i < 2; i++) {
  101198. ok = ok && FLAC__memory_alloc_aligned_int32_array(new_blocksize, &encoder->private_->residual_workspace_unaligned[channel][i], &encoder->private_->residual_workspace[channel][i]);
  101199. }
  101200. }
  101201. for(channel = 0; ok && channel < 2; channel++) {
  101202. for(i = 0; ok && i < 2; i++) {
  101203. 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]);
  101204. }
  101205. }
  101206. /* the *2 is an approximation to the series 1 + 1/2 + 1/4 + ... that sums tree occupies in a flat array */
  101207. /*@@@ 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) */
  101208. ok = ok && FLAC__memory_alloc_aligned_uint64_array(new_blocksize * 2, &encoder->private_->abs_residual_partition_sums_unaligned, &encoder->private_->abs_residual_partition_sums);
  101209. if(encoder->protected_->do_escape_coding)
  101210. ok = ok && FLAC__memory_alloc_aligned_unsigned_array(new_blocksize * 2, &encoder->private_->raw_bits_per_partition_unaligned, &encoder->private_->raw_bits_per_partition);
  101211. /* now adjust the windows if the blocksize has changed */
  101212. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  101213. if(ok && new_blocksize != encoder->private_->input_capacity && encoder->protected_->max_lpc_order > 0) {
  101214. for(i = 0; ok && i < encoder->protected_->num_apodizations; i++) {
  101215. switch(encoder->protected_->apodizations[i].type) {
  101216. case FLAC__APODIZATION_BARTLETT:
  101217. FLAC__window_bartlett(encoder->private_->window[i], new_blocksize);
  101218. break;
  101219. case FLAC__APODIZATION_BARTLETT_HANN:
  101220. FLAC__window_bartlett_hann(encoder->private_->window[i], new_blocksize);
  101221. break;
  101222. case FLAC__APODIZATION_BLACKMAN:
  101223. FLAC__window_blackman(encoder->private_->window[i], new_blocksize);
  101224. break;
  101225. case FLAC__APODIZATION_BLACKMAN_HARRIS_4TERM_92DB_SIDELOBE:
  101226. FLAC__window_blackman_harris_4term_92db_sidelobe(encoder->private_->window[i], new_blocksize);
  101227. break;
  101228. case FLAC__APODIZATION_CONNES:
  101229. FLAC__window_connes(encoder->private_->window[i], new_blocksize);
  101230. break;
  101231. case FLAC__APODIZATION_FLATTOP:
  101232. FLAC__window_flattop(encoder->private_->window[i], new_blocksize);
  101233. break;
  101234. case FLAC__APODIZATION_GAUSS:
  101235. FLAC__window_gauss(encoder->private_->window[i], new_blocksize, encoder->protected_->apodizations[i].parameters.gauss.stddev);
  101236. break;
  101237. case FLAC__APODIZATION_HAMMING:
  101238. FLAC__window_hamming(encoder->private_->window[i], new_blocksize);
  101239. break;
  101240. case FLAC__APODIZATION_HANN:
  101241. FLAC__window_hann(encoder->private_->window[i], new_blocksize);
  101242. break;
  101243. case FLAC__APODIZATION_KAISER_BESSEL:
  101244. FLAC__window_kaiser_bessel(encoder->private_->window[i], new_blocksize);
  101245. break;
  101246. case FLAC__APODIZATION_NUTTALL:
  101247. FLAC__window_nuttall(encoder->private_->window[i], new_blocksize);
  101248. break;
  101249. case FLAC__APODIZATION_RECTANGLE:
  101250. FLAC__window_rectangle(encoder->private_->window[i], new_blocksize);
  101251. break;
  101252. case FLAC__APODIZATION_TRIANGLE:
  101253. FLAC__window_triangle(encoder->private_->window[i], new_blocksize);
  101254. break;
  101255. case FLAC__APODIZATION_TUKEY:
  101256. FLAC__window_tukey(encoder->private_->window[i], new_blocksize, encoder->protected_->apodizations[i].parameters.tukey.p);
  101257. break;
  101258. case FLAC__APODIZATION_WELCH:
  101259. FLAC__window_welch(encoder->private_->window[i], new_blocksize);
  101260. break;
  101261. default:
  101262. FLAC__ASSERT(0);
  101263. /* double protection */
  101264. FLAC__window_hann(encoder->private_->window[i], new_blocksize);
  101265. break;
  101266. }
  101267. }
  101268. }
  101269. #endif
  101270. if(ok)
  101271. encoder->private_->input_capacity = new_blocksize;
  101272. else
  101273. encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
  101274. return ok;
  101275. }
  101276. FLAC__bool write_bitbuffer_(FLAC__StreamEncoder *encoder, unsigned samples, FLAC__bool is_last_block)
  101277. {
  101278. const FLAC__byte *buffer;
  101279. size_t bytes;
  101280. FLAC__ASSERT(FLAC__bitwriter_is_byte_aligned(encoder->private_->frame));
  101281. if(!FLAC__bitwriter_get_buffer(encoder->private_->frame, &buffer, &bytes)) {
  101282. encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
  101283. return false;
  101284. }
  101285. if(encoder->protected_->verify) {
  101286. encoder->private_->verify.output.data = buffer;
  101287. encoder->private_->verify.output.bytes = bytes;
  101288. if(encoder->private_->verify.state_hint == ENCODER_IN_MAGIC) {
  101289. encoder->private_->verify.needs_magic_hack = true;
  101290. }
  101291. else {
  101292. if(!FLAC__stream_decoder_process_single(encoder->private_->verify.decoder)) {
  101293. FLAC__bitwriter_release_buffer(encoder->private_->frame);
  101294. FLAC__bitwriter_clear(encoder->private_->frame);
  101295. if(encoder->protected_->state != FLAC__STREAM_ENCODER_VERIFY_MISMATCH_IN_AUDIO_DATA)
  101296. encoder->protected_->state = FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR;
  101297. return false;
  101298. }
  101299. }
  101300. }
  101301. if(write_frame_(encoder, buffer, bytes, samples, is_last_block) != FLAC__STREAM_ENCODER_WRITE_STATUS_OK) {
  101302. FLAC__bitwriter_release_buffer(encoder->private_->frame);
  101303. FLAC__bitwriter_clear(encoder->private_->frame);
  101304. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  101305. return false;
  101306. }
  101307. FLAC__bitwriter_release_buffer(encoder->private_->frame);
  101308. FLAC__bitwriter_clear(encoder->private_->frame);
  101309. if(samples > 0) {
  101310. encoder->private_->streaminfo.data.stream_info.min_framesize = min(bytes, encoder->private_->streaminfo.data.stream_info.min_framesize);
  101311. encoder->private_->streaminfo.data.stream_info.max_framesize = max(bytes, encoder->private_->streaminfo.data.stream_info.max_framesize);
  101312. }
  101313. return true;
  101314. }
  101315. FLAC__StreamEncoderWriteStatus write_frame_(FLAC__StreamEncoder *encoder, const FLAC__byte buffer[], size_t bytes, unsigned samples, FLAC__bool is_last_block)
  101316. {
  101317. FLAC__StreamEncoderWriteStatus status;
  101318. FLAC__uint64 output_position = 0;
  101319. /* FLAC__STREAM_ENCODER_TELL_STATUS_UNSUPPORTED just means we didn't get the offset; no error */
  101320. if(encoder->private_->tell_callback && encoder->private_->tell_callback(encoder, &output_position, encoder->private_->client_data) == FLAC__STREAM_ENCODER_TELL_STATUS_ERROR) {
  101321. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  101322. return FLAC__STREAM_ENCODER_WRITE_STATUS_FATAL_ERROR;
  101323. }
  101324. /*
  101325. * Watch for the STREAMINFO block and first SEEKTABLE block to go by and store their offsets.
  101326. */
  101327. if(samples == 0) {
  101328. FLAC__MetadataType type = (FLAC__MetadataType) (buffer[0] & 0x7f);
  101329. if(type == FLAC__METADATA_TYPE_STREAMINFO)
  101330. encoder->protected_->streaminfo_offset = output_position;
  101331. else if(type == FLAC__METADATA_TYPE_SEEKTABLE && encoder->protected_->seektable_offset == 0)
  101332. encoder->protected_->seektable_offset = output_position;
  101333. }
  101334. /*
  101335. * Mark the current seek point if hit (if audio_offset == 0 that
  101336. * means we're still writing metadata and haven't hit the first
  101337. * frame yet)
  101338. */
  101339. if(0 != encoder->private_->seek_table && encoder->protected_->audio_offset > 0 && encoder->private_->seek_table->num_points > 0) {
  101340. const unsigned blocksize = FLAC__stream_encoder_get_blocksize(encoder);
  101341. const FLAC__uint64 frame_first_sample = encoder->private_->samples_written;
  101342. const FLAC__uint64 frame_last_sample = frame_first_sample + (FLAC__uint64)blocksize - 1;
  101343. FLAC__uint64 test_sample;
  101344. unsigned i;
  101345. for(i = encoder->private_->first_seekpoint_to_check; i < encoder->private_->seek_table->num_points; i++) {
  101346. test_sample = encoder->private_->seek_table->points[i].sample_number;
  101347. if(test_sample > frame_last_sample) {
  101348. break;
  101349. }
  101350. else if(test_sample >= frame_first_sample) {
  101351. encoder->private_->seek_table->points[i].sample_number = frame_first_sample;
  101352. encoder->private_->seek_table->points[i].stream_offset = output_position - encoder->protected_->audio_offset;
  101353. encoder->private_->seek_table->points[i].frame_samples = blocksize;
  101354. encoder->private_->first_seekpoint_to_check++;
  101355. /* DO NOT: "break;" and here's why:
  101356. * The seektable template may contain more than one target
  101357. * sample for any given frame; we will keep looping, generating
  101358. * duplicate seekpoints for them, and we'll clean it up later,
  101359. * just before writing the seektable back to the metadata.
  101360. */
  101361. }
  101362. else {
  101363. encoder->private_->first_seekpoint_to_check++;
  101364. }
  101365. }
  101366. }
  101367. #if FLAC__HAS_OGG
  101368. if(encoder->private_->is_ogg) {
  101369. status = FLAC__ogg_encoder_aspect_write_callback_wrapper(
  101370. &encoder->protected_->ogg_encoder_aspect,
  101371. buffer,
  101372. bytes,
  101373. samples,
  101374. encoder->private_->current_frame_number,
  101375. is_last_block,
  101376. (FLAC__OggEncoderAspectWriteCallbackProxy)encoder->private_->write_callback,
  101377. encoder,
  101378. encoder->private_->client_data
  101379. );
  101380. }
  101381. else
  101382. #endif
  101383. status = encoder->private_->write_callback(encoder, buffer, bytes, samples, encoder->private_->current_frame_number, encoder->private_->client_data);
  101384. if(status == FLAC__STREAM_ENCODER_WRITE_STATUS_OK) {
  101385. encoder->private_->bytes_written += bytes;
  101386. encoder->private_->samples_written += samples;
  101387. /* we keep a high watermark on the number of frames written because
  101388. * when the encoder goes back to write metadata, 'current_frame'
  101389. * will drop back to 0.
  101390. */
  101391. encoder->private_->frames_written = max(encoder->private_->frames_written, encoder->private_->current_frame_number+1);
  101392. }
  101393. else
  101394. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  101395. return status;
  101396. }
  101397. /* Gets called when the encoding process has finished so that we can update the STREAMINFO and SEEKTABLE blocks. */
  101398. void update_metadata_(const FLAC__StreamEncoder *encoder)
  101399. {
  101400. FLAC__byte b[max(6, FLAC__STREAM_METADATA_SEEKPOINT_LENGTH)];
  101401. const FLAC__StreamMetadata *metadata = &encoder->private_->streaminfo;
  101402. const FLAC__uint64 samples = metadata->data.stream_info.total_samples;
  101403. const unsigned min_framesize = metadata->data.stream_info.min_framesize;
  101404. const unsigned max_framesize = metadata->data.stream_info.max_framesize;
  101405. const unsigned bps = metadata->data.stream_info.bits_per_sample;
  101406. FLAC__StreamEncoderSeekStatus seek_status;
  101407. FLAC__ASSERT(metadata->type == FLAC__METADATA_TYPE_STREAMINFO);
  101408. /* All this is based on intimate knowledge of the stream header
  101409. * layout, but a change to the header format that would break this
  101410. * would also break all streams encoded in the previous format.
  101411. */
  101412. /*
  101413. * Write MD5 signature
  101414. */
  101415. {
  101416. const unsigned md5_offset =
  101417. FLAC__STREAM_METADATA_HEADER_LENGTH +
  101418. (
  101419. FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN +
  101420. FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN +
  101421. FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN +
  101422. FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN +
  101423. FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN +
  101424. FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN +
  101425. FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN +
  101426. FLAC__STREAM_METADATA_STREAMINFO_TOTAL_SAMPLES_LEN
  101427. ) / 8;
  101428. if((seek_status = encoder->private_->seek_callback(encoder, encoder->protected_->streaminfo_offset + md5_offset, encoder->private_->client_data)) != FLAC__STREAM_ENCODER_SEEK_STATUS_OK) {
  101429. if(seek_status == FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR)
  101430. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  101431. return;
  101432. }
  101433. if(encoder->private_->write_callback(encoder, metadata->data.stream_info.md5sum, 16, 0, 0, encoder->private_->client_data) != FLAC__STREAM_ENCODER_WRITE_STATUS_OK) {
  101434. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  101435. return;
  101436. }
  101437. }
  101438. /*
  101439. * Write total samples
  101440. */
  101441. {
  101442. const unsigned total_samples_byte_offset =
  101443. FLAC__STREAM_METADATA_HEADER_LENGTH +
  101444. (
  101445. FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN +
  101446. FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN +
  101447. FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN +
  101448. FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN +
  101449. FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN +
  101450. FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN +
  101451. FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN
  101452. - 4
  101453. ) / 8;
  101454. b[0] = ((FLAC__byte)(bps-1) << 4) | (FLAC__byte)((samples >> 32) & 0x0F);
  101455. b[1] = (FLAC__byte)((samples >> 24) & 0xFF);
  101456. b[2] = (FLAC__byte)((samples >> 16) & 0xFF);
  101457. b[3] = (FLAC__byte)((samples >> 8) & 0xFF);
  101458. b[4] = (FLAC__byte)(samples & 0xFF);
  101459. 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) {
  101460. if(seek_status == FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR)
  101461. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  101462. return;
  101463. }
  101464. if(encoder->private_->write_callback(encoder, b, 5, 0, 0, encoder->private_->client_data) != FLAC__STREAM_ENCODER_WRITE_STATUS_OK) {
  101465. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  101466. return;
  101467. }
  101468. }
  101469. /*
  101470. * Write min/max framesize
  101471. */
  101472. {
  101473. const unsigned min_framesize_offset =
  101474. FLAC__STREAM_METADATA_HEADER_LENGTH +
  101475. (
  101476. FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN +
  101477. FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN
  101478. ) / 8;
  101479. b[0] = (FLAC__byte)((min_framesize >> 16) & 0xFF);
  101480. b[1] = (FLAC__byte)((min_framesize >> 8) & 0xFF);
  101481. b[2] = (FLAC__byte)(min_framesize & 0xFF);
  101482. b[3] = (FLAC__byte)((max_framesize >> 16) & 0xFF);
  101483. b[4] = (FLAC__byte)((max_framesize >> 8) & 0xFF);
  101484. b[5] = (FLAC__byte)(max_framesize & 0xFF);
  101485. 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) {
  101486. if(seek_status == FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR)
  101487. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  101488. return;
  101489. }
  101490. if(encoder->private_->write_callback(encoder, b, 6, 0, 0, encoder->private_->client_data) != FLAC__STREAM_ENCODER_WRITE_STATUS_OK) {
  101491. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  101492. return;
  101493. }
  101494. }
  101495. /*
  101496. * Write seektable
  101497. */
  101498. if(0 != encoder->private_->seek_table && encoder->private_->seek_table->num_points > 0 && encoder->protected_->seektable_offset > 0) {
  101499. unsigned i;
  101500. FLAC__format_seektable_sort(encoder->private_->seek_table);
  101501. FLAC__ASSERT(FLAC__format_seektable_is_legal(encoder->private_->seek_table));
  101502. 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) {
  101503. if(seek_status == FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR)
  101504. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  101505. return;
  101506. }
  101507. for(i = 0; i < encoder->private_->seek_table->num_points; i++) {
  101508. FLAC__uint64 xx;
  101509. unsigned x;
  101510. xx = encoder->private_->seek_table->points[i].sample_number;
  101511. b[7] = (FLAC__byte)xx; xx >>= 8;
  101512. b[6] = (FLAC__byte)xx; xx >>= 8;
  101513. b[5] = (FLAC__byte)xx; xx >>= 8;
  101514. b[4] = (FLAC__byte)xx; xx >>= 8;
  101515. b[3] = (FLAC__byte)xx; xx >>= 8;
  101516. b[2] = (FLAC__byte)xx; xx >>= 8;
  101517. b[1] = (FLAC__byte)xx; xx >>= 8;
  101518. b[0] = (FLAC__byte)xx; xx >>= 8;
  101519. xx = encoder->private_->seek_table->points[i].stream_offset;
  101520. b[15] = (FLAC__byte)xx; xx >>= 8;
  101521. b[14] = (FLAC__byte)xx; xx >>= 8;
  101522. b[13] = (FLAC__byte)xx; xx >>= 8;
  101523. b[12] = (FLAC__byte)xx; xx >>= 8;
  101524. b[11] = (FLAC__byte)xx; xx >>= 8;
  101525. b[10] = (FLAC__byte)xx; xx >>= 8;
  101526. b[9] = (FLAC__byte)xx; xx >>= 8;
  101527. b[8] = (FLAC__byte)xx; xx >>= 8;
  101528. x = encoder->private_->seek_table->points[i].frame_samples;
  101529. b[17] = (FLAC__byte)x; x >>= 8;
  101530. b[16] = (FLAC__byte)x; x >>= 8;
  101531. if(encoder->private_->write_callback(encoder, b, 18, 0, 0, encoder->private_->client_data) != FLAC__STREAM_ENCODER_WRITE_STATUS_OK) {
  101532. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  101533. return;
  101534. }
  101535. }
  101536. }
  101537. }
  101538. #if FLAC__HAS_OGG
  101539. /* Gets called when the encoding process has finished so that we can update the STREAMINFO and SEEKTABLE blocks. */
  101540. void update_ogg_metadata_(FLAC__StreamEncoder *encoder)
  101541. {
  101542. /* the # of bytes in the 1st packet that precede the STREAMINFO */
  101543. static const unsigned FIRST_OGG_PACKET_STREAMINFO_PREFIX_LENGTH =
  101544. FLAC__OGG_MAPPING_PACKET_TYPE_LENGTH +
  101545. FLAC__OGG_MAPPING_MAGIC_LENGTH +
  101546. FLAC__OGG_MAPPING_VERSION_MAJOR_LENGTH +
  101547. FLAC__OGG_MAPPING_VERSION_MINOR_LENGTH +
  101548. FLAC__OGG_MAPPING_NUM_HEADERS_LENGTH +
  101549. FLAC__STREAM_SYNC_LENGTH
  101550. ;
  101551. FLAC__byte b[max(6, FLAC__STREAM_METADATA_SEEKPOINT_LENGTH)];
  101552. const FLAC__StreamMetadata *metadata = &encoder->private_->streaminfo;
  101553. const FLAC__uint64 samples = metadata->data.stream_info.total_samples;
  101554. const unsigned min_framesize = metadata->data.stream_info.min_framesize;
  101555. const unsigned max_framesize = metadata->data.stream_info.max_framesize;
  101556. ogg_page page;
  101557. FLAC__ASSERT(metadata->type == FLAC__METADATA_TYPE_STREAMINFO);
  101558. FLAC__ASSERT(0 != encoder->private_->seek_callback);
  101559. /* Pre-check that client supports seeking, since we don't want the
  101560. * ogg_helper code to ever have to deal with this condition.
  101561. */
  101562. if(encoder->private_->seek_callback(encoder, 0, encoder->private_->client_data) == FLAC__STREAM_ENCODER_SEEK_STATUS_UNSUPPORTED)
  101563. return;
  101564. /* All this is based on intimate knowledge of the stream header
  101565. * layout, but a change to the header format that would break this
  101566. * would also break all streams encoded in the previous format.
  101567. */
  101568. /**
  101569. ** Write STREAMINFO stats
  101570. **/
  101571. simple_ogg_page__init(&page);
  101572. if(!simple_ogg_page__get_at(encoder, encoder->protected_->streaminfo_offset, &page, encoder->private_->seek_callback, encoder->private_->read_callback, encoder->private_->client_data)) {
  101573. simple_ogg_page__clear(&page);
  101574. return; /* state already set */
  101575. }
  101576. /*
  101577. * Write MD5 signature
  101578. */
  101579. {
  101580. const unsigned md5_offset =
  101581. FIRST_OGG_PACKET_STREAMINFO_PREFIX_LENGTH +
  101582. FLAC__STREAM_METADATA_HEADER_LENGTH +
  101583. (
  101584. FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN +
  101585. FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN +
  101586. FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN +
  101587. FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN +
  101588. FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN +
  101589. FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN +
  101590. FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN +
  101591. FLAC__STREAM_METADATA_STREAMINFO_TOTAL_SAMPLES_LEN
  101592. ) / 8;
  101593. if(md5_offset + 16 > (unsigned)page.body_len) {
  101594. encoder->protected_->state = FLAC__STREAM_ENCODER_OGG_ERROR;
  101595. simple_ogg_page__clear(&page);
  101596. return;
  101597. }
  101598. memcpy(page.body + md5_offset, metadata->data.stream_info.md5sum, 16);
  101599. }
  101600. /*
  101601. * Write total samples
  101602. */
  101603. {
  101604. const unsigned total_samples_byte_offset =
  101605. FIRST_OGG_PACKET_STREAMINFO_PREFIX_LENGTH +
  101606. FLAC__STREAM_METADATA_HEADER_LENGTH +
  101607. (
  101608. FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN +
  101609. FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN +
  101610. FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN +
  101611. FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN +
  101612. FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN +
  101613. FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN +
  101614. FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN
  101615. - 4
  101616. ) / 8;
  101617. if(total_samples_byte_offset + 5 > (unsigned)page.body_len) {
  101618. encoder->protected_->state = FLAC__STREAM_ENCODER_OGG_ERROR;
  101619. simple_ogg_page__clear(&page);
  101620. return;
  101621. }
  101622. b[0] = (FLAC__byte)page.body[total_samples_byte_offset] & 0xF0;
  101623. b[0] |= (FLAC__byte)((samples >> 32) & 0x0F);
  101624. b[1] = (FLAC__byte)((samples >> 24) & 0xFF);
  101625. b[2] = (FLAC__byte)((samples >> 16) & 0xFF);
  101626. b[3] = (FLAC__byte)((samples >> 8) & 0xFF);
  101627. b[4] = (FLAC__byte)(samples & 0xFF);
  101628. memcpy(page.body + total_samples_byte_offset, b, 5);
  101629. }
  101630. /*
  101631. * Write min/max framesize
  101632. */
  101633. {
  101634. const unsigned min_framesize_offset =
  101635. FIRST_OGG_PACKET_STREAMINFO_PREFIX_LENGTH +
  101636. FLAC__STREAM_METADATA_HEADER_LENGTH +
  101637. (
  101638. FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN +
  101639. FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN
  101640. ) / 8;
  101641. if(min_framesize_offset + 6 > (unsigned)page.body_len) {
  101642. encoder->protected_->state = FLAC__STREAM_ENCODER_OGG_ERROR;
  101643. simple_ogg_page__clear(&page);
  101644. return;
  101645. }
  101646. b[0] = (FLAC__byte)((min_framesize >> 16) & 0xFF);
  101647. b[1] = (FLAC__byte)((min_framesize >> 8) & 0xFF);
  101648. b[2] = (FLAC__byte)(min_framesize & 0xFF);
  101649. b[3] = (FLAC__byte)((max_framesize >> 16) & 0xFF);
  101650. b[4] = (FLAC__byte)((max_framesize >> 8) & 0xFF);
  101651. b[5] = (FLAC__byte)(max_framesize & 0xFF);
  101652. memcpy(page.body + min_framesize_offset, b, 6);
  101653. }
  101654. if(!simple_ogg_page__set_at(encoder, encoder->protected_->streaminfo_offset, &page, encoder->private_->seek_callback, encoder->private_->write_callback, encoder->private_->client_data)) {
  101655. simple_ogg_page__clear(&page);
  101656. return; /* state already set */
  101657. }
  101658. simple_ogg_page__clear(&page);
  101659. /*
  101660. * Write seektable
  101661. */
  101662. if(0 != encoder->private_->seek_table && encoder->private_->seek_table->num_points > 0 && encoder->protected_->seektable_offset > 0) {
  101663. unsigned i;
  101664. FLAC__byte *p;
  101665. FLAC__format_seektable_sort(encoder->private_->seek_table);
  101666. FLAC__ASSERT(FLAC__format_seektable_is_legal(encoder->private_->seek_table));
  101667. simple_ogg_page__init(&page);
  101668. if(!simple_ogg_page__get_at(encoder, encoder->protected_->seektable_offset, &page, encoder->private_->seek_callback, encoder->private_->read_callback, encoder->private_->client_data)) {
  101669. simple_ogg_page__clear(&page);
  101670. return; /* state already set */
  101671. }
  101672. if((FLAC__STREAM_METADATA_HEADER_LENGTH + 18*encoder->private_->seek_table->num_points) != (unsigned)page.body_len) {
  101673. encoder->protected_->state = FLAC__STREAM_ENCODER_OGG_ERROR;
  101674. simple_ogg_page__clear(&page);
  101675. return;
  101676. }
  101677. for(i = 0, p = page.body + FLAC__STREAM_METADATA_HEADER_LENGTH; i < encoder->private_->seek_table->num_points; i++, p += 18) {
  101678. FLAC__uint64 xx;
  101679. unsigned x;
  101680. xx = encoder->private_->seek_table->points[i].sample_number;
  101681. b[7] = (FLAC__byte)xx; xx >>= 8;
  101682. b[6] = (FLAC__byte)xx; xx >>= 8;
  101683. b[5] = (FLAC__byte)xx; xx >>= 8;
  101684. b[4] = (FLAC__byte)xx; xx >>= 8;
  101685. b[3] = (FLAC__byte)xx; xx >>= 8;
  101686. b[2] = (FLAC__byte)xx; xx >>= 8;
  101687. b[1] = (FLAC__byte)xx; xx >>= 8;
  101688. b[0] = (FLAC__byte)xx; xx >>= 8;
  101689. xx = encoder->private_->seek_table->points[i].stream_offset;
  101690. b[15] = (FLAC__byte)xx; xx >>= 8;
  101691. b[14] = (FLAC__byte)xx; xx >>= 8;
  101692. b[13] = (FLAC__byte)xx; xx >>= 8;
  101693. b[12] = (FLAC__byte)xx; xx >>= 8;
  101694. b[11] = (FLAC__byte)xx; xx >>= 8;
  101695. b[10] = (FLAC__byte)xx; xx >>= 8;
  101696. b[9] = (FLAC__byte)xx; xx >>= 8;
  101697. b[8] = (FLAC__byte)xx; xx >>= 8;
  101698. x = encoder->private_->seek_table->points[i].frame_samples;
  101699. b[17] = (FLAC__byte)x; x >>= 8;
  101700. b[16] = (FLAC__byte)x; x >>= 8;
  101701. memcpy(p, b, 18);
  101702. }
  101703. if(!simple_ogg_page__set_at(encoder, encoder->protected_->seektable_offset, &page, encoder->private_->seek_callback, encoder->private_->write_callback, encoder->private_->client_data)) {
  101704. simple_ogg_page__clear(&page);
  101705. return; /* state already set */
  101706. }
  101707. simple_ogg_page__clear(&page);
  101708. }
  101709. }
  101710. #endif
  101711. FLAC__bool process_frame_(FLAC__StreamEncoder *encoder, FLAC__bool is_fractional_block, FLAC__bool is_last_block)
  101712. {
  101713. FLAC__uint16 crc;
  101714. FLAC__ASSERT(encoder->protected_->state == FLAC__STREAM_ENCODER_OK);
  101715. /*
  101716. * Accumulate raw signal to the MD5 signature
  101717. */
  101718. 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)) {
  101719. encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
  101720. return false;
  101721. }
  101722. /*
  101723. * Process the frame header and subframes into the frame bitbuffer
  101724. */
  101725. if(!process_subframes_(encoder, is_fractional_block)) {
  101726. /* the above function sets the state for us in case of an error */
  101727. return false;
  101728. }
  101729. /*
  101730. * Zero-pad the frame to a byte_boundary
  101731. */
  101732. if(!FLAC__bitwriter_zero_pad_to_byte_boundary(encoder->private_->frame)) {
  101733. encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
  101734. return false;
  101735. }
  101736. /*
  101737. * CRC-16 the whole thing
  101738. */
  101739. FLAC__ASSERT(FLAC__bitwriter_is_byte_aligned(encoder->private_->frame));
  101740. if(
  101741. !FLAC__bitwriter_get_write_crc16(encoder->private_->frame, &crc) ||
  101742. !FLAC__bitwriter_write_raw_uint32(encoder->private_->frame, crc, FLAC__FRAME_FOOTER_CRC_LEN)
  101743. ) {
  101744. encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
  101745. return false;
  101746. }
  101747. /*
  101748. * Write it
  101749. */
  101750. if(!write_bitbuffer_(encoder, encoder->protected_->blocksize, is_last_block)) {
  101751. /* the above function sets the state for us in case of an error */
  101752. return false;
  101753. }
  101754. /*
  101755. * Get ready for the next frame
  101756. */
  101757. encoder->private_->current_sample_number = 0;
  101758. encoder->private_->current_frame_number++;
  101759. encoder->private_->streaminfo.data.stream_info.total_samples += (FLAC__uint64)encoder->protected_->blocksize;
  101760. return true;
  101761. }
  101762. FLAC__bool process_subframes_(FLAC__StreamEncoder *encoder, FLAC__bool is_fractional_block)
  101763. {
  101764. FLAC__FrameHeader frame_header;
  101765. unsigned channel, min_partition_order = encoder->protected_->min_residual_partition_order, max_partition_order;
  101766. FLAC__bool do_independent, do_mid_side;
  101767. /*
  101768. * Calculate the min,max Rice partition orders
  101769. */
  101770. if(is_fractional_block) {
  101771. max_partition_order = 0;
  101772. }
  101773. else {
  101774. max_partition_order = FLAC__format_get_max_rice_partition_order_from_blocksize(encoder->protected_->blocksize);
  101775. max_partition_order = min(max_partition_order, encoder->protected_->max_residual_partition_order);
  101776. }
  101777. min_partition_order = min(min_partition_order, max_partition_order);
  101778. /*
  101779. * Setup the frame
  101780. */
  101781. frame_header.blocksize = encoder->protected_->blocksize;
  101782. frame_header.sample_rate = encoder->protected_->sample_rate;
  101783. frame_header.channels = encoder->protected_->channels;
  101784. frame_header.channel_assignment = FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT; /* the default unless the encoder determines otherwise */
  101785. frame_header.bits_per_sample = encoder->protected_->bits_per_sample;
  101786. frame_header.number_type = FLAC__FRAME_NUMBER_TYPE_FRAME_NUMBER;
  101787. frame_header.number.frame_number = encoder->private_->current_frame_number;
  101788. /*
  101789. * Figure out what channel assignments to try
  101790. */
  101791. if(encoder->protected_->do_mid_side_stereo) {
  101792. if(encoder->protected_->loose_mid_side_stereo) {
  101793. if(encoder->private_->loose_mid_side_stereo_frame_count == 0) {
  101794. do_independent = true;
  101795. do_mid_side = true;
  101796. }
  101797. else {
  101798. do_independent = (encoder->private_->last_channel_assignment == FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT);
  101799. do_mid_side = !do_independent;
  101800. }
  101801. }
  101802. else {
  101803. do_independent = true;
  101804. do_mid_side = true;
  101805. }
  101806. }
  101807. else {
  101808. do_independent = true;
  101809. do_mid_side = false;
  101810. }
  101811. FLAC__ASSERT(do_independent || do_mid_side);
  101812. /*
  101813. * Check for wasted bits; set effective bps for each subframe
  101814. */
  101815. if(do_independent) {
  101816. for(channel = 0; channel < encoder->protected_->channels; channel++) {
  101817. const unsigned w = get_wasted_bits_(encoder->private_->integer_signal[channel], encoder->protected_->blocksize);
  101818. encoder->private_->subframe_workspace[channel][0].wasted_bits = encoder->private_->subframe_workspace[channel][1].wasted_bits = w;
  101819. encoder->private_->subframe_bps[channel] = encoder->protected_->bits_per_sample - w;
  101820. }
  101821. }
  101822. if(do_mid_side) {
  101823. FLAC__ASSERT(encoder->protected_->channels == 2);
  101824. for(channel = 0; channel < 2; channel++) {
  101825. const unsigned w = get_wasted_bits_(encoder->private_->integer_signal_mid_side[channel], encoder->protected_->blocksize);
  101826. encoder->private_->subframe_workspace_mid_side[channel][0].wasted_bits = encoder->private_->subframe_workspace_mid_side[channel][1].wasted_bits = w;
  101827. encoder->private_->subframe_bps_mid_side[channel] = encoder->protected_->bits_per_sample - w + (channel==0? 0:1);
  101828. }
  101829. }
  101830. /*
  101831. * First do a normal encoding pass of each independent channel
  101832. */
  101833. if(do_independent) {
  101834. for(channel = 0; channel < encoder->protected_->channels; channel++) {
  101835. if(!
  101836. process_subframe_(
  101837. encoder,
  101838. min_partition_order,
  101839. max_partition_order,
  101840. &frame_header,
  101841. encoder->private_->subframe_bps[channel],
  101842. encoder->private_->integer_signal[channel],
  101843. encoder->private_->subframe_workspace_ptr[channel],
  101844. encoder->private_->partitioned_rice_contents_workspace_ptr[channel],
  101845. encoder->private_->residual_workspace[channel],
  101846. encoder->private_->best_subframe+channel,
  101847. encoder->private_->best_subframe_bits+channel
  101848. )
  101849. )
  101850. return false;
  101851. }
  101852. }
  101853. /*
  101854. * Now do mid and side channels if requested
  101855. */
  101856. if(do_mid_side) {
  101857. FLAC__ASSERT(encoder->protected_->channels == 2);
  101858. for(channel = 0; channel < 2; channel++) {
  101859. if(!
  101860. process_subframe_(
  101861. encoder,
  101862. min_partition_order,
  101863. max_partition_order,
  101864. &frame_header,
  101865. encoder->private_->subframe_bps_mid_side[channel],
  101866. encoder->private_->integer_signal_mid_side[channel],
  101867. encoder->private_->subframe_workspace_ptr_mid_side[channel],
  101868. encoder->private_->partitioned_rice_contents_workspace_ptr_mid_side[channel],
  101869. encoder->private_->residual_workspace_mid_side[channel],
  101870. encoder->private_->best_subframe_mid_side+channel,
  101871. encoder->private_->best_subframe_bits_mid_side+channel
  101872. )
  101873. )
  101874. return false;
  101875. }
  101876. }
  101877. /*
  101878. * Compose the frame bitbuffer
  101879. */
  101880. if(do_mid_side) {
  101881. unsigned left_bps = 0, right_bps = 0; /* initialized only to prevent superfluous compiler warning */
  101882. FLAC__Subframe *left_subframe = 0, *right_subframe = 0; /* initialized only to prevent superfluous compiler warning */
  101883. FLAC__ChannelAssignment channel_assignment;
  101884. FLAC__ASSERT(encoder->protected_->channels == 2);
  101885. if(encoder->protected_->loose_mid_side_stereo && encoder->private_->loose_mid_side_stereo_frame_count > 0) {
  101886. channel_assignment = (encoder->private_->last_channel_assignment == FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT? FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT : FLAC__CHANNEL_ASSIGNMENT_MID_SIDE);
  101887. }
  101888. else {
  101889. unsigned bits[4]; /* WATCHOUT - indexed by FLAC__ChannelAssignment */
  101890. unsigned min_bits;
  101891. int ca;
  101892. FLAC__ASSERT(FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT == 0);
  101893. FLAC__ASSERT(FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE == 1);
  101894. FLAC__ASSERT(FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE == 2);
  101895. FLAC__ASSERT(FLAC__CHANNEL_ASSIGNMENT_MID_SIDE == 3);
  101896. FLAC__ASSERT(do_independent && do_mid_side);
  101897. /* We have to figure out which channel assignent results in the smallest frame */
  101898. bits[FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT] = encoder->private_->best_subframe_bits [0] + encoder->private_->best_subframe_bits [1];
  101899. bits[FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE ] = encoder->private_->best_subframe_bits [0] + encoder->private_->best_subframe_bits_mid_side[1];
  101900. bits[FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE ] = encoder->private_->best_subframe_bits [1] + encoder->private_->best_subframe_bits_mid_side[1];
  101901. bits[FLAC__CHANNEL_ASSIGNMENT_MID_SIDE ] = encoder->private_->best_subframe_bits_mid_side[0] + encoder->private_->best_subframe_bits_mid_side[1];
  101902. channel_assignment = FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT;
  101903. min_bits = bits[channel_assignment];
  101904. for(ca = 1; ca <= 3; ca++) {
  101905. if(bits[ca] < min_bits) {
  101906. min_bits = bits[ca];
  101907. channel_assignment = (FLAC__ChannelAssignment)ca;
  101908. }
  101909. }
  101910. }
  101911. frame_header.channel_assignment = channel_assignment;
  101912. if(!FLAC__frame_add_header(&frame_header, encoder->private_->frame)) {
  101913. encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
  101914. return false;
  101915. }
  101916. switch(channel_assignment) {
  101917. case FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT:
  101918. left_subframe = &encoder->private_->subframe_workspace [0][encoder->private_->best_subframe [0]];
  101919. right_subframe = &encoder->private_->subframe_workspace [1][encoder->private_->best_subframe [1]];
  101920. break;
  101921. case FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE:
  101922. left_subframe = &encoder->private_->subframe_workspace [0][encoder->private_->best_subframe [0]];
  101923. right_subframe = &encoder->private_->subframe_workspace_mid_side[1][encoder->private_->best_subframe_mid_side[1]];
  101924. break;
  101925. case FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE:
  101926. left_subframe = &encoder->private_->subframe_workspace_mid_side[1][encoder->private_->best_subframe_mid_side[1]];
  101927. right_subframe = &encoder->private_->subframe_workspace [1][encoder->private_->best_subframe [1]];
  101928. break;
  101929. case FLAC__CHANNEL_ASSIGNMENT_MID_SIDE:
  101930. left_subframe = &encoder->private_->subframe_workspace_mid_side[0][encoder->private_->best_subframe_mid_side[0]];
  101931. right_subframe = &encoder->private_->subframe_workspace_mid_side[1][encoder->private_->best_subframe_mid_side[1]];
  101932. break;
  101933. default:
  101934. FLAC__ASSERT(0);
  101935. }
  101936. switch(channel_assignment) {
  101937. case FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT:
  101938. left_bps = encoder->private_->subframe_bps [0];
  101939. right_bps = encoder->private_->subframe_bps [1];
  101940. break;
  101941. case FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE:
  101942. left_bps = encoder->private_->subframe_bps [0];
  101943. right_bps = encoder->private_->subframe_bps_mid_side[1];
  101944. break;
  101945. case FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE:
  101946. left_bps = encoder->private_->subframe_bps_mid_side[1];
  101947. right_bps = encoder->private_->subframe_bps [1];
  101948. break;
  101949. case FLAC__CHANNEL_ASSIGNMENT_MID_SIDE:
  101950. left_bps = encoder->private_->subframe_bps_mid_side[0];
  101951. right_bps = encoder->private_->subframe_bps_mid_side[1];
  101952. break;
  101953. default:
  101954. FLAC__ASSERT(0);
  101955. }
  101956. /* note that encoder_add_subframe_ sets the state for us in case of an error */
  101957. if(!add_subframe_(encoder, frame_header.blocksize, left_bps , left_subframe , encoder->private_->frame))
  101958. return false;
  101959. if(!add_subframe_(encoder, frame_header.blocksize, right_bps, right_subframe, encoder->private_->frame))
  101960. return false;
  101961. }
  101962. else {
  101963. if(!FLAC__frame_add_header(&frame_header, encoder->private_->frame)) {
  101964. encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
  101965. return false;
  101966. }
  101967. for(channel = 0; channel < encoder->protected_->channels; channel++) {
  101968. 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)) {
  101969. /* the above function sets the state for us in case of an error */
  101970. return false;
  101971. }
  101972. }
  101973. }
  101974. if(encoder->protected_->loose_mid_side_stereo) {
  101975. encoder->private_->loose_mid_side_stereo_frame_count++;
  101976. if(encoder->private_->loose_mid_side_stereo_frame_count >= encoder->private_->loose_mid_side_stereo_frames)
  101977. encoder->private_->loose_mid_side_stereo_frame_count = 0;
  101978. }
  101979. encoder->private_->last_channel_assignment = frame_header.channel_assignment;
  101980. return true;
  101981. }
  101982. FLAC__bool process_subframe_(
  101983. FLAC__StreamEncoder *encoder,
  101984. unsigned min_partition_order,
  101985. unsigned max_partition_order,
  101986. const FLAC__FrameHeader *frame_header,
  101987. unsigned subframe_bps,
  101988. const FLAC__int32 integer_signal[],
  101989. FLAC__Subframe *subframe[2],
  101990. FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents[2],
  101991. FLAC__int32 *residual[2],
  101992. unsigned *best_subframe,
  101993. unsigned *best_bits
  101994. )
  101995. {
  101996. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  101997. FLAC__float fixed_residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1];
  101998. #else
  101999. FLAC__fixedpoint fixed_residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1];
  102000. #endif
  102001. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  102002. FLAC__double lpc_residual_bits_per_sample;
  102003. 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 */
  102004. FLAC__double lpc_error[FLAC__MAX_LPC_ORDER];
  102005. unsigned min_lpc_order, max_lpc_order, lpc_order;
  102006. unsigned min_qlp_coeff_precision, max_qlp_coeff_precision, qlp_coeff_precision;
  102007. #endif
  102008. unsigned min_fixed_order, max_fixed_order, guess_fixed_order, fixed_order;
  102009. unsigned rice_parameter;
  102010. unsigned _candidate_bits, _best_bits;
  102011. unsigned _best_subframe;
  102012. /* only use RICE2 partitions if stream bps > 16 */
  102013. 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;
  102014. FLAC__ASSERT(frame_header->blocksize > 0);
  102015. /* verbatim subframe is the baseline against which we measure other compressed subframes */
  102016. _best_subframe = 0;
  102017. if(encoder->private_->disable_verbatim_subframes && frame_header->blocksize >= FLAC__MAX_FIXED_ORDER)
  102018. _best_bits = UINT_MAX;
  102019. else
  102020. _best_bits = evaluate_verbatim_subframe_(encoder, integer_signal, frame_header->blocksize, subframe_bps, subframe[_best_subframe]);
  102021. if(frame_header->blocksize >= FLAC__MAX_FIXED_ORDER) {
  102022. unsigned signal_is_constant = false;
  102023. 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);
  102024. /* check for constant subframe */
  102025. if(
  102026. !encoder->private_->disable_constant_subframes &&
  102027. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  102028. fixed_residual_bits_per_sample[1] == 0.0
  102029. #else
  102030. fixed_residual_bits_per_sample[1] == FLAC__FP_ZERO
  102031. #endif
  102032. ) {
  102033. /* the above means it's possible all samples are the same value; now double-check it: */
  102034. unsigned i;
  102035. signal_is_constant = true;
  102036. for(i = 1; i < frame_header->blocksize; i++) {
  102037. if(integer_signal[0] != integer_signal[i]) {
  102038. signal_is_constant = false;
  102039. break;
  102040. }
  102041. }
  102042. }
  102043. if(signal_is_constant) {
  102044. _candidate_bits = evaluate_constant_subframe_(encoder, integer_signal[0], frame_header->blocksize, subframe_bps, subframe[!_best_subframe]);
  102045. if(_candidate_bits < _best_bits) {
  102046. _best_subframe = !_best_subframe;
  102047. _best_bits = _candidate_bits;
  102048. }
  102049. }
  102050. else {
  102051. if(!encoder->private_->disable_fixed_subframes || (encoder->protected_->max_lpc_order == 0 && _best_bits == UINT_MAX)) {
  102052. /* encode fixed */
  102053. if(encoder->protected_->do_exhaustive_model_search) {
  102054. min_fixed_order = 0;
  102055. max_fixed_order = FLAC__MAX_FIXED_ORDER;
  102056. }
  102057. else {
  102058. min_fixed_order = max_fixed_order = guess_fixed_order;
  102059. }
  102060. if(max_fixed_order >= frame_header->blocksize)
  102061. max_fixed_order = frame_header->blocksize - 1;
  102062. for(fixed_order = min_fixed_order; fixed_order <= max_fixed_order; fixed_order++) {
  102063. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  102064. if(fixed_residual_bits_per_sample[fixed_order] >= (FLAC__float)subframe_bps)
  102065. continue; /* don't even try */
  102066. 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 */
  102067. #else
  102068. if(FLAC__fixedpoint_trunc(fixed_residual_bits_per_sample[fixed_order]) >= (int)subframe_bps)
  102069. continue; /* don't even try */
  102070. 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 */
  102071. #endif
  102072. rice_parameter++; /* to account for the signed->unsigned conversion during rice coding */
  102073. if(rice_parameter >= rice_parameter_limit) {
  102074. #ifdef DEBUG_VERBOSE
  102075. fprintf(stderr, "clipping rice_parameter (%u -> %u) @0\n", rice_parameter, rice_parameter_limit - 1);
  102076. #endif
  102077. rice_parameter = rice_parameter_limit - 1;
  102078. }
  102079. _candidate_bits =
  102080. evaluate_fixed_subframe_(
  102081. encoder,
  102082. integer_signal,
  102083. residual[!_best_subframe],
  102084. encoder->private_->abs_residual_partition_sums,
  102085. encoder->private_->raw_bits_per_partition,
  102086. frame_header->blocksize,
  102087. subframe_bps,
  102088. fixed_order,
  102089. rice_parameter,
  102090. rice_parameter_limit,
  102091. min_partition_order,
  102092. max_partition_order,
  102093. encoder->protected_->do_escape_coding,
  102094. encoder->protected_->rice_parameter_search_dist,
  102095. subframe[!_best_subframe],
  102096. partitioned_rice_contents[!_best_subframe]
  102097. );
  102098. if(_candidate_bits < _best_bits) {
  102099. _best_subframe = !_best_subframe;
  102100. _best_bits = _candidate_bits;
  102101. }
  102102. }
  102103. }
  102104. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  102105. /* encode lpc */
  102106. if(encoder->protected_->max_lpc_order > 0) {
  102107. if(encoder->protected_->max_lpc_order >= frame_header->blocksize)
  102108. max_lpc_order = frame_header->blocksize-1;
  102109. else
  102110. max_lpc_order = encoder->protected_->max_lpc_order;
  102111. if(max_lpc_order > 0) {
  102112. unsigned a;
  102113. for (a = 0; a < encoder->protected_->num_apodizations; a++) {
  102114. FLAC__lpc_window_data(integer_signal, encoder->private_->window[a], encoder->private_->windowed_signal, frame_header->blocksize);
  102115. encoder->private_->local_lpc_compute_autocorrelation(encoder->private_->windowed_signal, frame_header->blocksize, max_lpc_order+1, autoc);
  102116. /* if autoc[0] == 0.0, the signal is constant and we usually won't get here, but it can happen */
  102117. if(autoc[0] != 0.0) {
  102118. FLAC__lpc_compute_lp_coefficients(autoc, &max_lpc_order, encoder->private_->lp_coeff, lpc_error);
  102119. if(encoder->protected_->do_exhaustive_model_search) {
  102120. min_lpc_order = 1;
  102121. }
  102122. else {
  102123. const unsigned guess_lpc_order =
  102124. FLAC__lpc_compute_best_order(
  102125. lpc_error,
  102126. max_lpc_order,
  102127. frame_header->blocksize,
  102128. subframe_bps + (
  102129. encoder->protected_->do_qlp_coeff_prec_search?
  102130. FLAC__MIN_QLP_COEFF_PRECISION : /* have to guess; use the min possible size to avoid accidentally favoring lower orders */
  102131. encoder->protected_->qlp_coeff_precision
  102132. )
  102133. );
  102134. min_lpc_order = max_lpc_order = guess_lpc_order;
  102135. }
  102136. if(max_lpc_order >= frame_header->blocksize)
  102137. max_lpc_order = frame_header->blocksize - 1;
  102138. for(lpc_order = min_lpc_order; lpc_order <= max_lpc_order; lpc_order++) {
  102139. lpc_residual_bits_per_sample = FLAC__lpc_compute_expected_bits_per_residual_sample(lpc_error[lpc_order-1], frame_header->blocksize-lpc_order);
  102140. if(lpc_residual_bits_per_sample >= (FLAC__double)subframe_bps)
  102141. continue; /* don't even try */
  102142. rice_parameter = (lpc_residual_bits_per_sample > 0.0)? (unsigned)(lpc_residual_bits_per_sample+0.5) : 0; /* 0.5 is for rounding */
  102143. rice_parameter++; /* to account for the signed->unsigned conversion during rice coding */
  102144. if(rice_parameter >= rice_parameter_limit) {
  102145. #ifdef DEBUG_VERBOSE
  102146. fprintf(stderr, "clipping rice_parameter (%u -> %u) @1\n", rice_parameter, rice_parameter_limit - 1);
  102147. #endif
  102148. rice_parameter = rice_parameter_limit - 1;
  102149. }
  102150. if(encoder->protected_->do_qlp_coeff_prec_search) {
  102151. min_qlp_coeff_precision = FLAC__MIN_QLP_COEFF_PRECISION;
  102152. /* try to ensure a 32-bit datapath throughout for 16bps(+1bps for side channel) or less */
  102153. if(subframe_bps <= 17) {
  102154. max_qlp_coeff_precision = min(32 - subframe_bps - lpc_order, FLAC__MAX_QLP_COEFF_PRECISION);
  102155. max_qlp_coeff_precision = max(max_qlp_coeff_precision, min_qlp_coeff_precision);
  102156. }
  102157. else
  102158. max_qlp_coeff_precision = FLAC__MAX_QLP_COEFF_PRECISION;
  102159. }
  102160. else {
  102161. min_qlp_coeff_precision = max_qlp_coeff_precision = encoder->protected_->qlp_coeff_precision;
  102162. }
  102163. for(qlp_coeff_precision = min_qlp_coeff_precision; qlp_coeff_precision <= max_qlp_coeff_precision; qlp_coeff_precision++) {
  102164. _candidate_bits =
  102165. evaluate_lpc_subframe_(
  102166. encoder,
  102167. integer_signal,
  102168. residual[!_best_subframe],
  102169. encoder->private_->abs_residual_partition_sums,
  102170. encoder->private_->raw_bits_per_partition,
  102171. encoder->private_->lp_coeff[lpc_order-1],
  102172. frame_header->blocksize,
  102173. subframe_bps,
  102174. lpc_order,
  102175. qlp_coeff_precision,
  102176. rice_parameter,
  102177. rice_parameter_limit,
  102178. min_partition_order,
  102179. max_partition_order,
  102180. encoder->protected_->do_escape_coding,
  102181. encoder->protected_->rice_parameter_search_dist,
  102182. subframe[!_best_subframe],
  102183. partitioned_rice_contents[!_best_subframe]
  102184. );
  102185. if(_candidate_bits > 0) { /* if == 0, there was a problem quantizing the lpcoeffs */
  102186. if(_candidate_bits < _best_bits) {
  102187. _best_subframe = !_best_subframe;
  102188. _best_bits = _candidate_bits;
  102189. }
  102190. }
  102191. }
  102192. }
  102193. }
  102194. }
  102195. }
  102196. }
  102197. #endif /* !defined FLAC__INTEGER_ONLY_LIBRARY */
  102198. }
  102199. }
  102200. /* under rare circumstances this can happen when all but lpc subframe types are disabled: */
  102201. if(_best_bits == UINT_MAX) {
  102202. FLAC__ASSERT(_best_subframe == 0);
  102203. _best_bits = evaluate_verbatim_subframe_(encoder, integer_signal, frame_header->blocksize, subframe_bps, subframe[_best_subframe]);
  102204. }
  102205. *best_subframe = _best_subframe;
  102206. *best_bits = _best_bits;
  102207. return true;
  102208. }
  102209. FLAC__bool add_subframe_(
  102210. FLAC__StreamEncoder *encoder,
  102211. unsigned blocksize,
  102212. unsigned subframe_bps,
  102213. const FLAC__Subframe *subframe,
  102214. FLAC__BitWriter *frame
  102215. )
  102216. {
  102217. switch(subframe->type) {
  102218. case FLAC__SUBFRAME_TYPE_CONSTANT:
  102219. if(!FLAC__subframe_add_constant(&(subframe->data.constant), subframe_bps, subframe->wasted_bits, frame)) {
  102220. encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
  102221. return false;
  102222. }
  102223. break;
  102224. case FLAC__SUBFRAME_TYPE_FIXED:
  102225. if(!FLAC__subframe_add_fixed(&(subframe->data.fixed), blocksize - subframe->data.fixed.order, subframe_bps, subframe->wasted_bits, frame)) {
  102226. encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
  102227. return false;
  102228. }
  102229. break;
  102230. case FLAC__SUBFRAME_TYPE_LPC:
  102231. if(!FLAC__subframe_add_lpc(&(subframe->data.lpc), blocksize - subframe->data.lpc.order, subframe_bps, subframe->wasted_bits, frame)) {
  102232. encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
  102233. return false;
  102234. }
  102235. break;
  102236. case FLAC__SUBFRAME_TYPE_VERBATIM:
  102237. if(!FLAC__subframe_add_verbatim(&(subframe->data.verbatim), blocksize, subframe_bps, subframe->wasted_bits, frame)) {
  102238. encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
  102239. return false;
  102240. }
  102241. break;
  102242. default:
  102243. FLAC__ASSERT(0);
  102244. }
  102245. return true;
  102246. }
  102247. #define SPOTCHECK_ESTIMATE 0
  102248. #if SPOTCHECK_ESTIMATE
  102249. static void spotcheck_subframe_estimate_(
  102250. FLAC__StreamEncoder *encoder,
  102251. unsigned blocksize,
  102252. unsigned subframe_bps,
  102253. const FLAC__Subframe *subframe,
  102254. unsigned estimate
  102255. )
  102256. {
  102257. FLAC__bool ret;
  102258. FLAC__BitWriter *frame = FLAC__bitwriter_new();
  102259. if(frame == 0) {
  102260. fprintf(stderr, "EST: can't allocate frame\n");
  102261. return;
  102262. }
  102263. if(!FLAC__bitwriter_init(frame)) {
  102264. fprintf(stderr, "EST: can't init frame\n");
  102265. return;
  102266. }
  102267. ret = add_subframe_(encoder, blocksize, subframe_bps, subframe, frame);
  102268. FLAC__ASSERT(ret);
  102269. {
  102270. const unsigned actual = FLAC__bitwriter_get_input_bits_unconsumed(frame);
  102271. if(estimate != actual)
  102272. 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);
  102273. }
  102274. FLAC__bitwriter_delete(frame);
  102275. }
  102276. #endif
  102277. unsigned evaluate_constant_subframe_(
  102278. FLAC__StreamEncoder *encoder,
  102279. const FLAC__int32 signal,
  102280. unsigned blocksize,
  102281. unsigned subframe_bps,
  102282. FLAC__Subframe *subframe
  102283. )
  102284. {
  102285. unsigned estimate;
  102286. subframe->type = FLAC__SUBFRAME_TYPE_CONSTANT;
  102287. subframe->data.constant.value = signal;
  102288. estimate = FLAC__SUBFRAME_ZERO_PAD_LEN + FLAC__SUBFRAME_TYPE_LEN + FLAC__SUBFRAME_WASTED_BITS_FLAG_LEN + subframe->wasted_bits + subframe_bps;
  102289. #if SPOTCHECK_ESTIMATE
  102290. spotcheck_subframe_estimate_(encoder, blocksize, subframe_bps, subframe, estimate);
  102291. #else
  102292. (void)encoder, (void)blocksize;
  102293. #endif
  102294. return estimate;
  102295. }
  102296. unsigned evaluate_fixed_subframe_(
  102297. FLAC__StreamEncoder *encoder,
  102298. const FLAC__int32 signal[],
  102299. FLAC__int32 residual[],
  102300. FLAC__uint64 abs_residual_partition_sums[],
  102301. unsigned raw_bits_per_partition[],
  102302. unsigned blocksize,
  102303. unsigned subframe_bps,
  102304. unsigned order,
  102305. unsigned rice_parameter,
  102306. unsigned rice_parameter_limit,
  102307. unsigned min_partition_order,
  102308. unsigned max_partition_order,
  102309. FLAC__bool do_escape_coding,
  102310. unsigned rice_parameter_search_dist,
  102311. FLAC__Subframe *subframe,
  102312. FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents
  102313. )
  102314. {
  102315. unsigned i, residual_bits, estimate;
  102316. const unsigned residual_samples = blocksize - order;
  102317. FLAC__fixed_compute_residual(signal+order, residual_samples, order, residual);
  102318. subframe->type = FLAC__SUBFRAME_TYPE_FIXED;
  102319. subframe->data.fixed.entropy_coding_method.type = FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE;
  102320. subframe->data.fixed.entropy_coding_method.data.partitioned_rice.contents = partitioned_rice_contents;
  102321. subframe->data.fixed.residual = residual;
  102322. residual_bits =
  102323. find_best_partition_order_(
  102324. encoder->private_,
  102325. residual,
  102326. abs_residual_partition_sums,
  102327. raw_bits_per_partition,
  102328. residual_samples,
  102329. order,
  102330. rice_parameter,
  102331. rice_parameter_limit,
  102332. min_partition_order,
  102333. max_partition_order,
  102334. subframe_bps,
  102335. do_escape_coding,
  102336. rice_parameter_search_dist,
  102337. &subframe->data.fixed.entropy_coding_method
  102338. );
  102339. subframe->data.fixed.order = order;
  102340. for(i = 0; i < order; i++)
  102341. subframe->data.fixed.warmup[i] = signal[i];
  102342. estimate = FLAC__SUBFRAME_ZERO_PAD_LEN + FLAC__SUBFRAME_TYPE_LEN + FLAC__SUBFRAME_WASTED_BITS_FLAG_LEN + subframe->wasted_bits + (order * subframe_bps) + residual_bits;
  102343. #if SPOTCHECK_ESTIMATE
  102344. spotcheck_subframe_estimate_(encoder, blocksize, subframe_bps, subframe, estimate);
  102345. #endif
  102346. return estimate;
  102347. }
  102348. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  102349. unsigned evaluate_lpc_subframe_(
  102350. FLAC__StreamEncoder *encoder,
  102351. const FLAC__int32 signal[],
  102352. FLAC__int32 residual[],
  102353. FLAC__uint64 abs_residual_partition_sums[],
  102354. unsigned raw_bits_per_partition[],
  102355. const FLAC__real lp_coeff[],
  102356. unsigned blocksize,
  102357. unsigned subframe_bps,
  102358. unsigned order,
  102359. unsigned qlp_coeff_precision,
  102360. unsigned rice_parameter,
  102361. unsigned rice_parameter_limit,
  102362. unsigned min_partition_order,
  102363. unsigned max_partition_order,
  102364. FLAC__bool do_escape_coding,
  102365. unsigned rice_parameter_search_dist,
  102366. FLAC__Subframe *subframe,
  102367. FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents
  102368. )
  102369. {
  102370. FLAC__int32 qlp_coeff[FLAC__MAX_LPC_ORDER];
  102371. unsigned i, residual_bits, estimate;
  102372. int quantization, ret;
  102373. const unsigned residual_samples = blocksize - order;
  102374. /* try to keep qlp coeff precision such that only 32-bit math is required for decode of <=16bps streams */
  102375. if(subframe_bps <= 16) {
  102376. FLAC__ASSERT(order > 0);
  102377. FLAC__ASSERT(order <= FLAC__MAX_LPC_ORDER);
  102378. qlp_coeff_precision = min(qlp_coeff_precision, 32 - subframe_bps - FLAC__bitmath_ilog2(order));
  102379. }
  102380. ret = FLAC__lpc_quantize_coefficients(lp_coeff, order, qlp_coeff_precision, qlp_coeff, &quantization);
  102381. if(ret != 0)
  102382. return 0; /* this is a hack to indicate to the caller that we can't do lp at this order on this subframe */
  102383. if(subframe_bps + qlp_coeff_precision + FLAC__bitmath_ilog2(order) <= 32)
  102384. if(subframe_bps <= 16 && qlp_coeff_precision <= 16)
  102385. encoder->private_->local_lpc_compute_residual_from_qlp_coefficients_16bit(signal+order, residual_samples, qlp_coeff, order, quantization, residual);
  102386. else
  102387. encoder->private_->local_lpc_compute_residual_from_qlp_coefficients(signal+order, residual_samples, qlp_coeff, order, quantization, residual);
  102388. else
  102389. encoder->private_->local_lpc_compute_residual_from_qlp_coefficients_64bit(signal+order, residual_samples, qlp_coeff, order, quantization, residual);
  102390. subframe->type = FLAC__SUBFRAME_TYPE_LPC;
  102391. subframe->data.lpc.entropy_coding_method.type = FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE;
  102392. subframe->data.lpc.entropy_coding_method.data.partitioned_rice.contents = partitioned_rice_contents;
  102393. subframe->data.lpc.residual = residual;
  102394. residual_bits =
  102395. find_best_partition_order_(
  102396. encoder->private_,
  102397. residual,
  102398. abs_residual_partition_sums,
  102399. raw_bits_per_partition,
  102400. residual_samples,
  102401. order,
  102402. rice_parameter,
  102403. rice_parameter_limit,
  102404. min_partition_order,
  102405. max_partition_order,
  102406. subframe_bps,
  102407. do_escape_coding,
  102408. rice_parameter_search_dist,
  102409. &subframe->data.lpc.entropy_coding_method
  102410. );
  102411. subframe->data.lpc.order = order;
  102412. subframe->data.lpc.qlp_coeff_precision = qlp_coeff_precision;
  102413. subframe->data.lpc.quantization_level = quantization;
  102414. memcpy(subframe->data.lpc.qlp_coeff, qlp_coeff, sizeof(FLAC__int32)*FLAC__MAX_LPC_ORDER);
  102415. for(i = 0; i < order; i++)
  102416. subframe->data.lpc.warmup[i] = signal[i];
  102417. 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;
  102418. #if SPOTCHECK_ESTIMATE
  102419. spotcheck_subframe_estimate_(encoder, blocksize, subframe_bps, subframe, estimate);
  102420. #endif
  102421. return estimate;
  102422. }
  102423. #endif
  102424. unsigned evaluate_verbatim_subframe_(
  102425. FLAC__StreamEncoder *encoder,
  102426. const FLAC__int32 signal[],
  102427. unsigned blocksize,
  102428. unsigned subframe_bps,
  102429. FLAC__Subframe *subframe
  102430. )
  102431. {
  102432. unsigned estimate;
  102433. subframe->type = FLAC__SUBFRAME_TYPE_VERBATIM;
  102434. subframe->data.verbatim.data = signal;
  102435. estimate = FLAC__SUBFRAME_ZERO_PAD_LEN + FLAC__SUBFRAME_TYPE_LEN + FLAC__SUBFRAME_WASTED_BITS_FLAG_LEN + subframe->wasted_bits + (blocksize * subframe_bps);
  102436. #if SPOTCHECK_ESTIMATE
  102437. spotcheck_subframe_estimate_(encoder, blocksize, subframe_bps, subframe, estimate);
  102438. #else
  102439. (void)encoder;
  102440. #endif
  102441. return estimate;
  102442. }
  102443. unsigned find_best_partition_order_(
  102444. FLAC__StreamEncoderPrivate *private_,
  102445. const FLAC__int32 residual[],
  102446. FLAC__uint64 abs_residual_partition_sums[],
  102447. unsigned raw_bits_per_partition[],
  102448. unsigned residual_samples,
  102449. unsigned predictor_order,
  102450. unsigned rice_parameter,
  102451. unsigned rice_parameter_limit,
  102452. unsigned min_partition_order,
  102453. unsigned max_partition_order,
  102454. unsigned bps,
  102455. FLAC__bool do_escape_coding,
  102456. unsigned rice_parameter_search_dist,
  102457. FLAC__EntropyCodingMethod *best_ecm
  102458. )
  102459. {
  102460. unsigned residual_bits, best_residual_bits = 0;
  102461. unsigned best_parameters_index = 0;
  102462. unsigned best_partition_order = 0;
  102463. const unsigned blocksize = residual_samples + predictor_order;
  102464. max_partition_order = FLAC__format_get_max_rice_partition_order_from_blocksize_limited_max_and_predictor_order(max_partition_order, blocksize, predictor_order);
  102465. min_partition_order = min(min_partition_order, max_partition_order);
  102466. precompute_partition_info_sums_(residual, abs_residual_partition_sums, residual_samples, predictor_order, min_partition_order, max_partition_order, bps);
  102467. if(do_escape_coding)
  102468. precompute_partition_info_escapes_(residual, raw_bits_per_partition, residual_samples, predictor_order, min_partition_order, max_partition_order);
  102469. {
  102470. int partition_order;
  102471. unsigned sum;
  102472. for(partition_order = (int)max_partition_order, sum = 0; partition_order >= (int)min_partition_order; partition_order--) {
  102473. if(!
  102474. set_partitioned_rice_(
  102475. #ifdef EXACT_RICE_BITS_CALCULATION
  102476. residual,
  102477. #endif
  102478. abs_residual_partition_sums+sum,
  102479. raw_bits_per_partition+sum,
  102480. residual_samples,
  102481. predictor_order,
  102482. rice_parameter,
  102483. rice_parameter_limit,
  102484. rice_parameter_search_dist,
  102485. (unsigned)partition_order,
  102486. do_escape_coding,
  102487. &private_->partitioned_rice_contents_extra[!best_parameters_index],
  102488. &residual_bits
  102489. )
  102490. )
  102491. {
  102492. FLAC__ASSERT(best_residual_bits != 0);
  102493. break;
  102494. }
  102495. sum += 1u << partition_order;
  102496. if(best_residual_bits == 0 || residual_bits < best_residual_bits) {
  102497. best_residual_bits = residual_bits;
  102498. best_parameters_index = !best_parameters_index;
  102499. best_partition_order = partition_order;
  102500. }
  102501. }
  102502. }
  102503. best_ecm->data.partitioned_rice.order = best_partition_order;
  102504. {
  102505. /*
  102506. * We are allowed to de-const the pointer based on our special
  102507. * knowledge; it is const to the outside world.
  102508. */
  102509. FLAC__EntropyCodingMethod_PartitionedRiceContents* prc = (FLAC__EntropyCodingMethod_PartitionedRiceContents*)best_ecm->data.partitioned_rice.contents;
  102510. unsigned partition;
  102511. /* save best parameters and raw_bits */
  102512. FLAC__format_entropy_coding_method_partitioned_rice_contents_ensure_size(prc, max(6, best_partition_order));
  102513. memcpy(prc->parameters, private_->partitioned_rice_contents_extra[best_parameters_index].parameters, sizeof(unsigned)*(1<<(best_partition_order)));
  102514. if(do_escape_coding)
  102515. memcpy(prc->raw_bits, private_->partitioned_rice_contents_extra[best_parameters_index].raw_bits, sizeof(unsigned)*(1<<(best_partition_order)));
  102516. /*
  102517. * Now need to check if the type should be changed to
  102518. * FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2 based on the
  102519. * size of the rice parameters.
  102520. */
  102521. for(partition = 0; partition < (1u<<best_partition_order); partition++) {
  102522. if(prc->parameters[partition] >= FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER) {
  102523. best_ecm->type = FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2;
  102524. break;
  102525. }
  102526. }
  102527. }
  102528. return best_residual_bits;
  102529. }
  102530. #if defined(FLAC__CPU_IA32) && !defined FLAC__NO_ASM && defined FLAC__HAS_NASM
  102531. extern void precompute_partition_info_sums_32bit_asm_ia32_(
  102532. const FLAC__int32 residual[],
  102533. FLAC__uint64 abs_residual_partition_sums[],
  102534. unsigned blocksize,
  102535. unsigned predictor_order,
  102536. unsigned min_partition_order,
  102537. unsigned max_partition_order
  102538. );
  102539. #endif
  102540. void precompute_partition_info_sums_(
  102541. const FLAC__int32 residual[],
  102542. FLAC__uint64 abs_residual_partition_sums[],
  102543. unsigned residual_samples,
  102544. unsigned predictor_order,
  102545. unsigned min_partition_order,
  102546. unsigned max_partition_order,
  102547. unsigned bps
  102548. )
  102549. {
  102550. const unsigned default_partition_samples = (residual_samples + predictor_order) >> max_partition_order;
  102551. unsigned partitions = 1u << max_partition_order;
  102552. FLAC__ASSERT(default_partition_samples > predictor_order);
  102553. #if defined(FLAC__CPU_IA32) && !defined FLAC__NO_ASM && defined FLAC__HAS_NASM
  102554. /* slightly pessimistic but still catches all common cases */
  102555. /* WATCHOUT: "+ bps" is an assumption that the average residual magnitude will not be more than "bps" bits */
  102556. if(FLAC__bitmath_ilog2(default_partition_samples) + bps < 32) {
  102557. precompute_partition_info_sums_32bit_asm_ia32_(residual, abs_residual_partition_sums, residual_samples + predictor_order, predictor_order, min_partition_order, max_partition_order);
  102558. return;
  102559. }
  102560. #endif
  102561. /* first do max_partition_order */
  102562. {
  102563. unsigned partition, residual_sample, end = (unsigned)(-(int)predictor_order);
  102564. /* slightly pessimistic but still catches all common cases */
  102565. /* WATCHOUT: "+ bps" is an assumption that the average residual magnitude will not be more than "bps" bits */
  102566. if(FLAC__bitmath_ilog2(default_partition_samples) + bps < 32) {
  102567. FLAC__uint32 abs_residual_partition_sum;
  102568. for(partition = residual_sample = 0; partition < partitions; partition++) {
  102569. end += default_partition_samples;
  102570. abs_residual_partition_sum = 0;
  102571. for( ; residual_sample < end; residual_sample++)
  102572. abs_residual_partition_sum += abs(residual[residual_sample]); /* abs(INT_MIN) is undefined, but if the residual is INT_MIN we have bigger problems */
  102573. abs_residual_partition_sums[partition] = abs_residual_partition_sum;
  102574. }
  102575. }
  102576. else { /* have to pessimistically use 64 bits for accumulator */
  102577. FLAC__uint64 abs_residual_partition_sum;
  102578. for(partition = residual_sample = 0; partition < partitions; partition++) {
  102579. end += default_partition_samples;
  102580. abs_residual_partition_sum = 0;
  102581. for( ; residual_sample < end; residual_sample++)
  102582. abs_residual_partition_sum += abs(residual[residual_sample]); /* abs(INT_MIN) is undefined, but if the residual is INT_MIN we have bigger problems */
  102583. abs_residual_partition_sums[partition] = abs_residual_partition_sum;
  102584. }
  102585. }
  102586. }
  102587. /* now merge partitions for lower orders */
  102588. {
  102589. unsigned from_partition = 0, to_partition = partitions;
  102590. int partition_order;
  102591. for(partition_order = (int)max_partition_order - 1; partition_order >= (int)min_partition_order; partition_order--) {
  102592. unsigned i;
  102593. partitions >>= 1;
  102594. for(i = 0; i < partitions; i++) {
  102595. abs_residual_partition_sums[to_partition++] =
  102596. abs_residual_partition_sums[from_partition ] +
  102597. abs_residual_partition_sums[from_partition+1];
  102598. from_partition += 2;
  102599. }
  102600. }
  102601. }
  102602. }
  102603. void precompute_partition_info_escapes_(
  102604. const FLAC__int32 residual[],
  102605. unsigned raw_bits_per_partition[],
  102606. unsigned residual_samples,
  102607. unsigned predictor_order,
  102608. unsigned min_partition_order,
  102609. unsigned max_partition_order
  102610. )
  102611. {
  102612. int partition_order;
  102613. unsigned from_partition, to_partition = 0;
  102614. const unsigned blocksize = residual_samples + predictor_order;
  102615. /* first do max_partition_order */
  102616. for(partition_order = (int)max_partition_order; partition_order >= 0; partition_order--) {
  102617. FLAC__int32 r;
  102618. FLAC__uint32 rmax;
  102619. unsigned partition, partition_sample, partition_samples, residual_sample;
  102620. const unsigned partitions = 1u << partition_order;
  102621. const unsigned default_partition_samples = blocksize >> partition_order;
  102622. FLAC__ASSERT(default_partition_samples > predictor_order);
  102623. for(partition = residual_sample = 0; partition < partitions; partition++) {
  102624. partition_samples = default_partition_samples;
  102625. if(partition == 0)
  102626. partition_samples -= predictor_order;
  102627. rmax = 0;
  102628. for(partition_sample = 0; partition_sample < partition_samples; partition_sample++) {
  102629. r = residual[residual_sample++];
  102630. /* OPT: maybe faster: rmax |= r ^ (r>>31) */
  102631. if(r < 0)
  102632. rmax |= ~r;
  102633. else
  102634. rmax |= r;
  102635. }
  102636. /* now we know all residual values are in the range [-rmax-1,rmax] */
  102637. raw_bits_per_partition[partition] = rmax? FLAC__bitmath_ilog2(rmax) + 2 : 1;
  102638. }
  102639. to_partition = partitions;
  102640. break; /*@@@ yuck, should remove the 'for' loop instead */
  102641. }
  102642. /* now merge partitions for lower orders */
  102643. for(from_partition = 0, --partition_order; partition_order >= (int)min_partition_order; partition_order--) {
  102644. unsigned m;
  102645. unsigned i;
  102646. const unsigned partitions = 1u << partition_order;
  102647. for(i = 0; i < partitions; i++) {
  102648. m = raw_bits_per_partition[from_partition];
  102649. from_partition++;
  102650. raw_bits_per_partition[to_partition] = max(m, raw_bits_per_partition[from_partition]);
  102651. from_partition++;
  102652. to_partition++;
  102653. }
  102654. }
  102655. }
  102656. #ifdef EXACT_RICE_BITS_CALCULATION
  102657. static FLaC__INLINE unsigned count_rice_bits_in_partition_(
  102658. const unsigned rice_parameter,
  102659. const unsigned partition_samples,
  102660. const FLAC__int32 *residual
  102661. )
  102662. {
  102663. unsigned i, partition_bits =
  102664. 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 */
  102665. (1+rice_parameter) * partition_samples /* 1 for unary stop bit + rice_parameter for the binary portion */
  102666. ;
  102667. for(i = 0; i < partition_samples; i++)
  102668. partition_bits += ( (FLAC__uint32)((residual[i]<<1)^(residual[i]>>31)) >> rice_parameter );
  102669. return partition_bits;
  102670. }
  102671. #else
  102672. static FLaC__INLINE unsigned count_rice_bits_in_partition_(
  102673. const unsigned rice_parameter,
  102674. const unsigned partition_samples,
  102675. const FLAC__uint64 abs_residual_partition_sum
  102676. )
  102677. {
  102678. return
  102679. 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 */
  102680. (1+rice_parameter) * partition_samples + /* 1 for unary stop bit + rice_parameter for the binary portion */
  102681. (
  102682. rice_parameter?
  102683. (unsigned)(abs_residual_partition_sum >> (rice_parameter-1)) /* rice_parameter-1 because the real coder sign-folds instead of using a sign bit */
  102684. : (unsigned)(abs_residual_partition_sum << 1) /* can't shift by negative number, so reverse */
  102685. )
  102686. - (partition_samples >> 1)
  102687. /* -(partition_samples>>1) to subtract out extra contributions to the abs_residual_partition_sum.
  102688. * The actual number of bits used is closer to the sum(for all i in the partition) of abs(residual[i])>>(rice_parameter-1)
  102689. * By using the abs_residual_partition sum, we also add in bits in the LSBs that would normally be shifted out.
  102690. * So the subtraction term tries to guess how many extra bits were contributed.
  102691. * If the LSBs are randomly distributed, this should average to 0.5 extra bits per sample.
  102692. */
  102693. ;
  102694. }
  102695. #endif
  102696. FLAC__bool set_partitioned_rice_(
  102697. #ifdef EXACT_RICE_BITS_CALCULATION
  102698. const FLAC__int32 residual[],
  102699. #endif
  102700. const FLAC__uint64 abs_residual_partition_sums[],
  102701. const unsigned raw_bits_per_partition[],
  102702. const unsigned residual_samples,
  102703. const unsigned predictor_order,
  102704. const unsigned suggested_rice_parameter,
  102705. const unsigned rice_parameter_limit,
  102706. const unsigned rice_parameter_search_dist,
  102707. const unsigned partition_order,
  102708. const FLAC__bool search_for_escapes,
  102709. FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents,
  102710. unsigned *bits
  102711. )
  102712. {
  102713. unsigned rice_parameter, partition_bits;
  102714. unsigned best_partition_bits, best_rice_parameter = 0;
  102715. unsigned bits_ = FLAC__ENTROPY_CODING_METHOD_TYPE_LEN + FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN;
  102716. unsigned *parameters, *raw_bits;
  102717. #ifdef ENABLE_RICE_PARAMETER_SEARCH
  102718. unsigned min_rice_parameter, max_rice_parameter;
  102719. #else
  102720. (void)rice_parameter_search_dist;
  102721. #endif
  102722. FLAC__ASSERT(suggested_rice_parameter < FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_ESCAPE_PARAMETER);
  102723. FLAC__ASSERT(rice_parameter_limit <= FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_ESCAPE_PARAMETER);
  102724. FLAC__format_entropy_coding_method_partitioned_rice_contents_ensure_size(partitioned_rice_contents, max(6, partition_order));
  102725. parameters = partitioned_rice_contents->parameters;
  102726. raw_bits = partitioned_rice_contents->raw_bits;
  102727. if(partition_order == 0) {
  102728. best_partition_bits = (unsigned)(-1);
  102729. #ifdef ENABLE_RICE_PARAMETER_SEARCH
  102730. if(rice_parameter_search_dist) {
  102731. if(suggested_rice_parameter < rice_parameter_search_dist)
  102732. min_rice_parameter = 0;
  102733. else
  102734. min_rice_parameter = suggested_rice_parameter - rice_parameter_search_dist;
  102735. max_rice_parameter = suggested_rice_parameter + rice_parameter_search_dist;
  102736. if(max_rice_parameter >= rice_parameter_limit) {
  102737. #ifdef DEBUG_VERBOSE
  102738. fprintf(stderr, "clipping rice_parameter (%u -> %u) @5\n", max_rice_parameter, rice_parameter_limit - 1);
  102739. #endif
  102740. max_rice_parameter = rice_parameter_limit - 1;
  102741. }
  102742. }
  102743. else
  102744. min_rice_parameter = max_rice_parameter = suggested_rice_parameter;
  102745. for(rice_parameter = min_rice_parameter; rice_parameter <= max_rice_parameter; rice_parameter++) {
  102746. #else
  102747. rice_parameter = suggested_rice_parameter;
  102748. #endif
  102749. #ifdef EXACT_RICE_BITS_CALCULATION
  102750. partition_bits = count_rice_bits_in_partition_(rice_parameter, residual_samples, residual);
  102751. #else
  102752. partition_bits = count_rice_bits_in_partition_(rice_parameter, residual_samples, abs_residual_partition_sums[0]);
  102753. #endif
  102754. if(partition_bits < best_partition_bits) {
  102755. best_rice_parameter = rice_parameter;
  102756. best_partition_bits = partition_bits;
  102757. }
  102758. #ifdef ENABLE_RICE_PARAMETER_SEARCH
  102759. }
  102760. #endif
  102761. if(search_for_escapes) {
  102762. 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;
  102763. if(partition_bits <= best_partition_bits) {
  102764. raw_bits[0] = raw_bits_per_partition[0];
  102765. best_rice_parameter = 0; /* will be converted to appropriate escape parameter later */
  102766. best_partition_bits = partition_bits;
  102767. }
  102768. else
  102769. raw_bits[0] = 0;
  102770. }
  102771. parameters[0] = best_rice_parameter;
  102772. bits_ += best_partition_bits;
  102773. }
  102774. else {
  102775. unsigned partition, residual_sample;
  102776. unsigned partition_samples;
  102777. FLAC__uint64 mean, k;
  102778. const unsigned partitions = 1u << partition_order;
  102779. for(partition = residual_sample = 0; partition < partitions; partition++) {
  102780. partition_samples = (residual_samples+predictor_order) >> partition_order;
  102781. if(partition == 0) {
  102782. if(partition_samples <= predictor_order)
  102783. return false;
  102784. else
  102785. partition_samples -= predictor_order;
  102786. }
  102787. mean = abs_residual_partition_sums[partition];
  102788. /* we are basically calculating the size in bits of the
  102789. * average residual magnitude in the partition:
  102790. * rice_parameter = floor(log2(mean/partition_samples))
  102791. * 'mean' is not a good name for the variable, it is
  102792. * actually the sum of magnitudes of all residual values
  102793. * in the partition, so the actual mean is
  102794. * mean/partition_samples
  102795. */
  102796. for(rice_parameter = 0, k = partition_samples; k < mean; rice_parameter++, k <<= 1)
  102797. ;
  102798. if(rice_parameter >= rice_parameter_limit) {
  102799. #ifdef DEBUG_VERBOSE
  102800. fprintf(stderr, "clipping rice_parameter (%u -> %u) @6\n", rice_parameter, rice_parameter_limit - 1);
  102801. #endif
  102802. rice_parameter = rice_parameter_limit - 1;
  102803. }
  102804. best_partition_bits = (unsigned)(-1);
  102805. #ifdef ENABLE_RICE_PARAMETER_SEARCH
  102806. if(rice_parameter_search_dist) {
  102807. if(rice_parameter < rice_parameter_search_dist)
  102808. min_rice_parameter = 0;
  102809. else
  102810. min_rice_parameter = rice_parameter - rice_parameter_search_dist;
  102811. max_rice_parameter = rice_parameter + rice_parameter_search_dist;
  102812. if(max_rice_parameter >= rice_parameter_limit) {
  102813. #ifdef DEBUG_VERBOSE
  102814. fprintf(stderr, "clipping rice_parameter (%u -> %u) @7\n", max_rice_parameter, rice_parameter_limit - 1);
  102815. #endif
  102816. max_rice_parameter = rice_parameter_limit - 1;
  102817. }
  102818. }
  102819. else
  102820. min_rice_parameter = max_rice_parameter = rice_parameter;
  102821. for(rice_parameter = min_rice_parameter; rice_parameter <= max_rice_parameter; rice_parameter++) {
  102822. #endif
  102823. #ifdef EXACT_RICE_BITS_CALCULATION
  102824. partition_bits = count_rice_bits_in_partition_(rice_parameter, partition_samples, residual+residual_sample);
  102825. #else
  102826. partition_bits = count_rice_bits_in_partition_(rice_parameter, partition_samples, abs_residual_partition_sums[partition]);
  102827. #endif
  102828. if(partition_bits < best_partition_bits) {
  102829. best_rice_parameter = rice_parameter;
  102830. best_partition_bits = partition_bits;
  102831. }
  102832. #ifdef ENABLE_RICE_PARAMETER_SEARCH
  102833. }
  102834. #endif
  102835. if(search_for_escapes) {
  102836. 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;
  102837. if(partition_bits <= best_partition_bits) {
  102838. raw_bits[partition] = raw_bits_per_partition[partition];
  102839. best_rice_parameter = 0; /* will be converted to appropriate escape parameter later */
  102840. best_partition_bits = partition_bits;
  102841. }
  102842. else
  102843. raw_bits[partition] = 0;
  102844. }
  102845. parameters[partition] = best_rice_parameter;
  102846. bits_ += best_partition_bits;
  102847. residual_sample += partition_samples;
  102848. }
  102849. }
  102850. *bits = bits_;
  102851. return true;
  102852. }
  102853. unsigned get_wasted_bits_(FLAC__int32 signal[], unsigned samples)
  102854. {
  102855. unsigned i, shift;
  102856. FLAC__int32 x = 0;
  102857. for(i = 0; i < samples && !(x&1); i++)
  102858. x |= signal[i];
  102859. if(x == 0) {
  102860. shift = 0;
  102861. }
  102862. else {
  102863. for(shift = 0; !(x&1); shift++)
  102864. x >>= 1;
  102865. }
  102866. if(shift > 0) {
  102867. for(i = 0; i < samples; i++)
  102868. signal[i] >>= shift;
  102869. }
  102870. return shift;
  102871. }
  102872. void append_to_verify_fifo_(verify_input_fifo *fifo, const FLAC__int32 * const input[], unsigned input_offset, unsigned channels, unsigned wide_samples)
  102873. {
  102874. unsigned channel;
  102875. for(channel = 0; channel < channels; channel++)
  102876. memcpy(&fifo->data[channel][fifo->tail], &input[channel][input_offset], sizeof(FLAC__int32) * wide_samples);
  102877. fifo->tail += wide_samples;
  102878. FLAC__ASSERT(fifo->tail <= fifo->size);
  102879. }
  102880. void append_to_verify_fifo_interleaved_(verify_input_fifo *fifo, const FLAC__int32 input[], unsigned input_offset, unsigned channels, unsigned wide_samples)
  102881. {
  102882. unsigned channel;
  102883. unsigned sample, wide_sample;
  102884. unsigned tail = fifo->tail;
  102885. sample = input_offset * channels;
  102886. for(wide_sample = 0; wide_sample < wide_samples; wide_sample++) {
  102887. for(channel = 0; channel < channels; channel++)
  102888. fifo->data[channel][tail] = input[sample++];
  102889. tail++;
  102890. }
  102891. fifo->tail = tail;
  102892. FLAC__ASSERT(fifo->tail <= fifo->size);
  102893. }
  102894. FLAC__StreamDecoderReadStatus verify_read_callback_(const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes, void *client_data)
  102895. {
  102896. FLAC__StreamEncoder *encoder = (FLAC__StreamEncoder*)client_data;
  102897. const size_t encoded_bytes = encoder->private_->verify.output.bytes;
  102898. (void)decoder;
  102899. if(encoder->private_->verify.needs_magic_hack) {
  102900. FLAC__ASSERT(*bytes >= FLAC__STREAM_SYNC_LENGTH);
  102901. *bytes = FLAC__STREAM_SYNC_LENGTH;
  102902. memcpy(buffer, FLAC__STREAM_SYNC_STRING, *bytes);
  102903. encoder->private_->verify.needs_magic_hack = false;
  102904. }
  102905. else {
  102906. if(encoded_bytes == 0) {
  102907. /*
  102908. * If we get here, a FIFO underflow has occurred,
  102909. * which means there is a bug somewhere.
  102910. */
  102911. FLAC__ASSERT(0);
  102912. return FLAC__STREAM_DECODER_READ_STATUS_ABORT;
  102913. }
  102914. else if(encoded_bytes < *bytes)
  102915. *bytes = encoded_bytes;
  102916. memcpy(buffer, encoder->private_->verify.output.data, *bytes);
  102917. encoder->private_->verify.output.data += *bytes;
  102918. encoder->private_->verify.output.bytes -= *bytes;
  102919. }
  102920. return FLAC__STREAM_DECODER_READ_STATUS_CONTINUE;
  102921. }
  102922. FLAC__StreamDecoderWriteStatus verify_write_callback_(const FLAC__StreamDecoder *decoder, const FLAC__Frame *frame, const FLAC__int32 * const buffer[], void *client_data)
  102923. {
  102924. FLAC__StreamEncoder *encoder = (FLAC__StreamEncoder *)client_data;
  102925. unsigned channel;
  102926. const unsigned channels = frame->header.channels;
  102927. const unsigned blocksize = frame->header.blocksize;
  102928. const unsigned bytes_per_block = sizeof(FLAC__int32) * blocksize;
  102929. (void)decoder;
  102930. for(channel = 0; channel < channels; channel++) {
  102931. if(0 != memcmp(buffer[channel], encoder->private_->verify.input_fifo.data[channel], bytes_per_block)) {
  102932. unsigned i, sample = 0;
  102933. FLAC__int32 expect = 0, got = 0;
  102934. for(i = 0; i < blocksize; i++) {
  102935. if(buffer[channel][i] != encoder->private_->verify.input_fifo.data[channel][i]) {
  102936. sample = i;
  102937. expect = (FLAC__int32)encoder->private_->verify.input_fifo.data[channel][i];
  102938. got = (FLAC__int32)buffer[channel][i];
  102939. break;
  102940. }
  102941. }
  102942. FLAC__ASSERT(i < blocksize);
  102943. FLAC__ASSERT(frame->header.number_type == FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER);
  102944. encoder->private_->verify.error_stats.absolute_sample = frame->header.number.sample_number + sample;
  102945. encoder->private_->verify.error_stats.frame_number = (unsigned)(frame->header.number.sample_number / blocksize);
  102946. encoder->private_->verify.error_stats.channel = channel;
  102947. encoder->private_->verify.error_stats.sample = sample;
  102948. encoder->private_->verify.error_stats.expected = expect;
  102949. encoder->private_->verify.error_stats.got = got;
  102950. encoder->protected_->state = FLAC__STREAM_ENCODER_VERIFY_MISMATCH_IN_AUDIO_DATA;
  102951. return FLAC__STREAM_DECODER_WRITE_STATUS_ABORT;
  102952. }
  102953. }
  102954. /* dequeue the frame from the fifo */
  102955. encoder->private_->verify.input_fifo.tail -= blocksize;
  102956. FLAC__ASSERT(encoder->private_->verify.input_fifo.tail <= OVERREAD_);
  102957. for(channel = 0; channel < channels; channel++)
  102958. 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]));
  102959. return FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE;
  102960. }
  102961. void verify_metadata_callback_(const FLAC__StreamDecoder *decoder, const FLAC__StreamMetadata *metadata, void *client_data)
  102962. {
  102963. (void)decoder, (void)metadata, (void)client_data;
  102964. }
  102965. void verify_error_callback_(const FLAC__StreamDecoder *decoder, FLAC__StreamDecoderErrorStatus status, void *client_data)
  102966. {
  102967. FLAC__StreamEncoder *encoder = (FLAC__StreamEncoder*)client_data;
  102968. (void)decoder, (void)status;
  102969. encoder->protected_->state = FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR;
  102970. }
  102971. FLAC__StreamEncoderReadStatus file_read_callback_enc(const FLAC__StreamEncoder *encoder, FLAC__byte buffer[], size_t *bytes, void *client_data)
  102972. {
  102973. (void)client_data;
  102974. *bytes = fread(buffer, 1, *bytes, encoder->private_->file);
  102975. if (*bytes == 0) {
  102976. if (feof(encoder->private_->file))
  102977. return FLAC__STREAM_ENCODER_READ_STATUS_END_OF_STREAM;
  102978. else if (ferror(encoder->private_->file))
  102979. return FLAC__STREAM_ENCODER_READ_STATUS_ABORT;
  102980. }
  102981. return FLAC__STREAM_ENCODER_READ_STATUS_CONTINUE;
  102982. }
  102983. FLAC__StreamEncoderSeekStatus file_seek_callback_enc(const FLAC__StreamEncoder *encoder, FLAC__uint64 absolute_byte_offset, void *client_data)
  102984. {
  102985. (void)client_data;
  102986. if(fseeko(encoder->private_->file, (off_t)absolute_byte_offset, SEEK_SET) < 0)
  102987. return FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR;
  102988. else
  102989. return FLAC__STREAM_ENCODER_SEEK_STATUS_OK;
  102990. }
  102991. FLAC__StreamEncoderTellStatus file_tell_callback_enc(const FLAC__StreamEncoder *encoder, FLAC__uint64 *absolute_byte_offset, void *client_data)
  102992. {
  102993. off_t offset;
  102994. (void)client_data;
  102995. offset = ftello(encoder->private_->file);
  102996. if(offset < 0) {
  102997. return FLAC__STREAM_ENCODER_TELL_STATUS_ERROR;
  102998. }
  102999. else {
  103000. *absolute_byte_offset = (FLAC__uint64)offset;
  103001. return FLAC__STREAM_ENCODER_TELL_STATUS_OK;
  103002. }
  103003. }
  103004. #ifdef FLAC__VALGRIND_TESTING
  103005. static size_t local__fwrite(const void *ptr, size_t size, size_t nmemb, FILE *stream)
  103006. {
  103007. size_t ret = fwrite(ptr, size, nmemb, stream);
  103008. if(!ferror(stream))
  103009. fflush(stream);
  103010. return ret;
  103011. }
  103012. #else
  103013. #define local__fwrite fwrite
  103014. #endif
  103015. FLAC__StreamEncoderWriteStatus file_write_callback_(const FLAC__StreamEncoder *encoder, const FLAC__byte buffer[], size_t bytes, unsigned samples, unsigned current_frame, void *client_data)
  103016. {
  103017. (void)client_data, (void)current_frame;
  103018. if(local__fwrite(buffer, sizeof(FLAC__byte), bytes, encoder->private_->file) == bytes) {
  103019. FLAC__bool call_it = 0 != encoder->private_->progress_callback && (
  103020. #if FLAC__HAS_OGG
  103021. /* We would like to be able to use 'samples > 0' in the
  103022. * clause here but currently because of the nature of our
  103023. * Ogg writing implementation, 'samples' is always 0 (see
  103024. * ogg_encoder_aspect.c). The downside is extra progress
  103025. * callbacks.
  103026. */
  103027. encoder->private_->is_ogg? true :
  103028. #endif
  103029. samples > 0
  103030. );
  103031. if(call_it) {
  103032. /* NOTE: We have to add +bytes, +samples, and +1 to the stats
  103033. * because at this point in the callback chain, the stats
  103034. * have not been updated. Only after we return and control
  103035. * gets back to write_frame_() are the stats updated
  103036. */
  103037. 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);
  103038. }
  103039. return FLAC__STREAM_ENCODER_WRITE_STATUS_OK;
  103040. }
  103041. else
  103042. return FLAC__STREAM_ENCODER_WRITE_STATUS_FATAL_ERROR;
  103043. }
  103044. /*
  103045. * This will forcibly set stdout to binary mode (for OSes that require it)
  103046. */
  103047. FILE *get_binary_stdout_(void)
  103048. {
  103049. /* if something breaks here it is probably due to the presence or
  103050. * absence of an underscore before the identifiers 'setmode',
  103051. * 'fileno', and/or 'O_BINARY'; check your system header files.
  103052. */
  103053. #if defined _MSC_VER || defined __MINGW32__
  103054. _setmode(_fileno(stdout), _O_BINARY);
  103055. #elif defined __CYGWIN__
  103056. /* almost certainly not needed for any modern Cygwin, but let's be safe... */
  103057. setmode(_fileno(stdout), _O_BINARY);
  103058. #elif defined __EMX__
  103059. setmode(fileno(stdout), O_BINARY);
  103060. #endif
  103061. return stdout;
  103062. }
  103063. #endif
  103064. /*** End of inlined file: stream_encoder.c ***/
  103065. /*** Start of inlined file: stream_encoder_framing.c ***/
  103066. /*** Start of inlined file: juce_FlacHeader.h ***/
  103067. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  103068. // tasks..
  103069. #define VERSION "1.2.1"
  103070. #define FLAC__NO_DLL 1
  103071. #if JUCE_MSVC
  103072. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  103073. #endif
  103074. #if JUCE_MAC
  103075. #define FLAC__SYS_DARWIN 1
  103076. #endif
  103077. /*** End of inlined file: juce_FlacHeader.h ***/
  103078. #if JUCE_USE_FLAC
  103079. #if HAVE_CONFIG_H
  103080. # include <config.h>
  103081. #endif
  103082. #include <stdio.h>
  103083. #include <string.h> /* for strlen() */
  103084. #ifdef max
  103085. #undef max
  103086. #endif
  103087. #define max(x,y) ((x)>(y)?(x):(y))
  103088. static FLAC__bool add_entropy_coding_method_(FLAC__BitWriter *bw, const FLAC__EntropyCodingMethod *method);
  103089. 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);
  103090. FLAC__bool FLAC__add_metadata_block(const FLAC__StreamMetadata *metadata, FLAC__BitWriter *bw)
  103091. {
  103092. unsigned i, j;
  103093. const unsigned vendor_string_length = (unsigned)strlen(FLAC__VENDOR_STRING);
  103094. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->is_last, FLAC__STREAM_METADATA_IS_LAST_LEN))
  103095. return false;
  103096. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->type, FLAC__STREAM_METADATA_TYPE_LEN))
  103097. return false;
  103098. /*
  103099. * First, for VORBIS_COMMENTs, adjust the length to reflect our vendor string
  103100. */
  103101. i = metadata->length;
  103102. if(metadata->type == FLAC__METADATA_TYPE_VORBIS_COMMENT) {
  103103. FLAC__ASSERT(metadata->data.vorbis_comment.vendor_string.length == 0 || 0 != metadata->data.vorbis_comment.vendor_string.entry);
  103104. i -= metadata->data.vorbis_comment.vendor_string.length;
  103105. i += vendor_string_length;
  103106. }
  103107. FLAC__ASSERT(i < (1u << FLAC__STREAM_METADATA_LENGTH_LEN));
  103108. if(!FLAC__bitwriter_write_raw_uint32(bw, i, FLAC__STREAM_METADATA_LENGTH_LEN))
  103109. return false;
  103110. switch(metadata->type) {
  103111. case FLAC__METADATA_TYPE_STREAMINFO:
  103112. FLAC__ASSERT(metadata->data.stream_info.min_blocksize < (1u << FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN));
  103113. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.stream_info.min_blocksize, FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN))
  103114. return false;
  103115. FLAC__ASSERT(metadata->data.stream_info.max_blocksize < (1u << FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN));
  103116. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.stream_info.max_blocksize, FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN))
  103117. return false;
  103118. FLAC__ASSERT(metadata->data.stream_info.min_framesize < (1u << FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN));
  103119. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.stream_info.min_framesize, FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN))
  103120. return false;
  103121. FLAC__ASSERT(metadata->data.stream_info.max_framesize < (1u << FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN));
  103122. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.stream_info.max_framesize, FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN))
  103123. return false;
  103124. FLAC__ASSERT(FLAC__format_sample_rate_is_valid(metadata->data.stream_info.sample_rate));
  103125. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.stream_info.sample_rate, FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN))
  103126. return false;
  103127. FLAC__ASSERT(metadata->data.stream_info.channels > 0);
  103128. FLAC__ASSERT(metadata->data.stream_info.channels <= (1u << FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN));
  103129. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.stream_info.channels-1, FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN))
  103130. return false;
  103131. FLAC__ASSERT(metadata->data.stream_info.bits_per_sample > 0);
  103132. FLAC__ASSERT(metadata->data.stream_info.bits_per_sample <= (1u << FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN));
  103133. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.stream_info.bits_per_sample-1, FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN))
  103134. return false;
  103135. if(!FLAC__bitwriter_write_raw_uint64(bw, metadata->data.stream_info.total_samples, FLAC__STREAM_METADATA_STREAMINFO_TOTAL_SAMPLES_LEN))
  103136. return false;
  103137. if(!FLAC__bitwriter_write_byte_block(bw, metadata->data.stream_info.md5sum, 16))
  103138. return false;
  103139. break;
  103140. case FLAC__METADATA_TYPE_PADDING:
  103141. if(!FLAC__bitwriter_write_zeroes(bw, metadata->length * 8))
  103142. return false;
  103143. break;
  103144. case FLAC__METADATA_TYPE_APPLICATION:
  103145. if(!FLAC__bitwriter_write_byte_block(bw, metadata->data.application.id, FLAC__STREAM_METADATA_APPLICATION_ID_LEN / 8))
  103146. return false;
  103147. if(!FLAC__bitwriter_write_byte_block(bw, metadata->data.application.data, metadata->length - (FLAC__STREAM_METADATA_APPLICATION_ID_LEN / 8)))
  103148. return false;
  103149. break;
  103150. case FLAC__METADATA_TYPE_SEEKTABLE:
  103151. for(i = 0; i < metadata->data.seek_table.num_points; i++) {
  103152. if(!FLAC__bitwriter_write_raw_uint64(bw, metadata->data.seek_table.points[i].sample_number, FLAC__STREAM_METADATA_SEEKPOINT_SAMPLE_NUMBER_LEN))
  103153. return false;
  103154. if(!FLAC__bitwriter_write_raw_uint64(bw, metadata->data.seek_table.points[i].stream_offset, FLAC__STREAM_METADATA_SEEKPOINT_STREAM_OFFSET_LEN))
  103155. return false;
  103156. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.seek_table.points[i].frame_samples, FLAC__STREAM_METADATA_SEEKPOINT_FRAME_SAMPLES_LEN))
  103157. return false;
  103158. }
  103159. break;
  103160. case FLAC__METADATA_TYPE_VORBIS_COMMENT:
  103161. if(!FLAC__bitwriter_write_raw_uint32_little_endian(bw, vendor_string_length))
  103162. return false;
  103163. if(!FLAC__bitwriter_write_byte_block(bw, (const FLAC__byte*)FLAC__VENDOR_STRING, vendor_string_length))
  103164. return false;
  103165. if(!FLAC__bitwriter_write_raw_uint32_little_endian(bw, metadata->data.vorbis_comment.num_comments))
  103166. return false;
  103167. for(i = 0; i < metadata->data.vorbis_comment.num_comments; i++) {
  103168. if(!FLAC__bitwriter_write_raw_uint32_little_endian(bw, metadata->data.vorbis_comment.comments[i].length))
  103169. return false;
  103170. if(!FLAC__bitwriter_write_byte_block(bw, metadata->data.vorbis_comment.comments[i].entry, metadata->data.vorbis_comment.comments[i].length))
  103171. return false;
  103172. }
  103173. break;
  103174. case FLAC__METADATA_TYPE_CUESHEET:
  103175. FLAC__ASSERT(FLAC__STREAM_METADATA_CUESHEET_MEDIA_CATALOG_NUMBER_LEN % 8 == 0);
  103176. 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))
  103177. return false;
  103178. if(!FLAC__bitwriter_write_raw_uint64(bw, metadata->data.cue_sheet.lead_in, FLAC__STREAM_METADATA_CUESHEET_LEAD_IN_LEN))
  103179. return false;
  103180. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.cue_sheet.is_cd? 1 : 0, FLAC__STREAM_METADATA_CUESHEET_IS_CD_LEN))
  103181. return false;
  103182. if(!FLAC__bitwriter_write_zeroes(bw, FLAC__STREAM_METADATA_CUESHEET_RESERVED_LEN))
  103183. return false;
  103184. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.cue_sheet.num_tracks, FLAC__STREAM_METADATA_CUESHEET_NUM_TRACKS_LEN))
  103185. return false;
  103186. for(i = 0; i < metadata->data.cue_sheet.num_tracks; i++) {
  103187. const FLAC__StreamMetadata_CueSheet_Track *track = metadata->data.cue_sheet.tracks + i;
  103188. if(!FLAC__bitwriter_write_raw_uint64(bw, track->offset, FLAC__STREAM_METADATA_CUESHEET_TRACK_OFFSET_LEN))
  103189. return false;
  103190. if(!FLAC__bitwriter_write_raw_uint32(bw, track->number, FLAC__STREAM_METADATA_CUESHEET_TRACK_NUMBER_LEN))
  103191. return false;
  103192. FLAC__ASSERT(FLAC__STREAM_METADATA_CUESHEET_TRACK_ISRC_LEN % 8 == 0);
  103193. if(!FLAC__bitwriter_write_byte_block(bw, (const FLAC__byte*)track->isrc, FLAC__STREAM_METADATA_CUESHEET_TRACK_ISRC_LEN/8))
  103194. return false;
  103195. if(!FLAC__bitwriter_write_raw_uint32(bw, track->type, FLAC__STREAM_METADATA_CUESHEET_TRACK_TYPE_LEN))
  103196. return false;
  103197. if(!FLAC__bitwriter_write_raw_uint32(bw, track->pre_emphasis, FLAC__STREAM_METADATA_CUESHEET_TRACK_PRE_EMPHASIS_LEN))
  103198. return false;
  103199. if(!FLAC__bitwriter_write_zeroes(bw, FLAC__STREAM_METADATA_CUESHEET_TRACK_RESERVED_LEN))
  103200. return false;
  103201. if(!FLAC__bitwriter_write_raw_uint32(bw, track->num_indices, FLAC__STREAM_METADATA_CUESHEET_TRACK_NUM_INDICES_LEN))
  103202. return false;
  103203. for(j = 0; j < track->num_indices; j++) {
  103204. const FLAC__StreamMetadata_CueSheet_Index *index = track->indices + j;
  103205. if(!FLAC__bitwriter_write_raw_uint64(bw, index->offset, FLAC__STREAM_METADATA_CUESHEET_INDEX_OFFSET_LEN))
  103206. return false;
  103207. if(!FLAC__bitwriter_write_raw_uint32(bw, index->number, FLAC__STREAM_METADATA_CUESHEET_INDEX_NUMBER_LEN))
  103208. return false;
  103209. if(!FLAC__bitwriter_write_zeroes(bw, FLAC__STREAM_METADATA_CUESHEET_INDEX_RESERVED_LEN))
  103210. return false;
  103211. }
  103212. }
  103213. break;
  103214. case FLAC__METADATA_TYPE_PICTURE:
  103215. {
  103216. size_t len;
  103217. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.picture.type, FLAC__STREAM_METADATA_PICTURE_TYPE_LEN))
  103218. return false;
  103219. len = strlen(metadata->data.picture.mime_type);
  103220. if(!FLAC__bitwriter_write_raw_uint32(bw, len, FLAC__STREAM_METADATA_PICTURE_MIME_TYPE_LENGTH_LEN))
  103221. return false;
  103222. if(!FLAC__bitwriter_write_byte_block(bw, (const FLAC__byte*)metadata->data.picture.mime_type, len))
  103223. return false;
  103224. len = strlen((const char *)metadata->data.picture.description);
  103225. if(!FLAC__bitwriter_write_raw_uint32(bw, len, FLAC__STREAM_METADATA_PICTURE_DESCRIPTION_LENGTH_LEN))
  103226. return false;
  103227. if(!FLAC__bitwriter_write_byte_block(bw, metadata->data.picture.description, len))
  103228. return false;
  103229. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.picture.width, FLAC__STREAM_METADATA_PICTURE_WIDTH_LEN))
  103230. return false;
  103231. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.picture.height, FLAC__STREAM_METADATA_PICTURE_HEIGHT_LEN))
  103232. return false;
  103233. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.picture.depth, FLAC__STREAM_METADATA_PICTURE_DEPTH_LEN))
  103234. return false;
  103235. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.picture.colors, FLAC__STREAM_METADATA_PICTURE_COLORS_LEN))
  103236. return false;
  103237. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.picture.data_length, FLAC__STREAM_METADATA_PICTURE_DATA_LENGTH_LEN))
  103238. return false;
  103239. if(!FLAC__bitwriter_write_byte_block(bw, metadata->data.picture.data, metadata->data.picture.data_length))
  103240. return false;
  103241. }
  103242. break;
  103243. default:
  103244. if(!FLAC__bitwriter_write_byte_block(bw, metadata->data.unknown.data, metadata->length))
  103245. return false;
  103246. break;
  103247. }
  103248. FLAC__ASSERT(FLAC__bitwriter_is_byte_aligned(bw));
  103249. return true;
  103250. }
  103251. FLAC__bool FLAC__frame_add_header(const FLAC__FrameHeader *header, FLAC__BitWriter *bw)
  103252. {
  103253. unsigned u, blocksize_hint, sample_rate_hint;
  103254. FLAC__byte crc;
  103255. FLAC__ASSERT(FLAC__bitwriter_is_byte_aligned(bw));
  103256. if(!FLAC__bitwriter_write_raw_uint32(bw, FLAC__FRAME_HEADER_SYNC, FLAC__FRAME_HEADER_SYNC_LEN))
  103257. return false;
  103258. if(!FLAC__bitwriter_write_raw_uint32(bw, 0, FLAC__FRAME_HEADER_RESERVED_LEN))
  103259. return false;
  103260. if(!FLAC__bitwriter_write_raw_uint32(bw, (header->number_type == FLAC__FRAME_NUMBER_TYPE_FRAME_NUMBER)? 0 : 1, FLAC__FRAME_HEADER_BLOCKING_STRATEGY_LEN))
  103261. return false;
  103262. FLAC__ASSERT(header->blocksize > 0 && header->blocksize <= FLAC__MAX_BLOCK_SIZE);
  103263. /* when this assertion holds true, any legal blocksize can be expressed in the frame header */
  103264. FLAC__ASSERT(FLAC__MAX_BLOCK_SIZE <= 65535u);
  103265. blocksize_hint = 0;
  103266. switch(header->blocksize) {
  103267. case 192: u = 1; break;
  103268. case 576: u = 2; break;
  103269. case 1152: u = 3; break;
  103270. case 2304: u = 4; break;
  103271. case 4608: u = 5; break;
  103272. case 256: u = 8; break;
  103273. case 512: u = 9; break;
  103274. case 1024: u = 10; break;
  103275. case 2048: u = 11; break;
  103276. case 4096: u = 12; break;
  103277. case 8192: u = 13; break;
  103278. case 16384: u = 14; break;
  103279. case 32768: u = 15; break;
  103280. default:
  103281. if(header->blocksize <= 0x100)
  103282. blocksize_hint = u = 6;
  103283. else
  103284. blocksize_hint = u = 7;
  103285. break;
  103286. }
  103287. if(!FLAC__bitwriter_write_raw_uint32(bw, u, FLAC__FRAME_HEADER_BLOCK_SIZE_LEN))
  103288. return false;
  103289. FLAC__ASSERT(FLAC__format_sample_rate_is_valid(header->sample_rate));
  103290. sample_rate_hint = 0;
  103291. switch(header->sample_rate) {
  103292. case 88200: u = 1; break;
  103293. case 176400: u = 2; break;
  103294. case 192000: u = 3; break;
  103295. case 8000: u = 4; break;
  103296. case 16000: u = 5; break;
  103297. case 22050: u = 6; break;
  103298. case 24000: u = 7; break;
  103299. case 32000: u = 8; break;
  103300. case 44100: u = 9; break;
  103301. case 48000: u = 10; break;
  103302. case 96000: u = 11; break;
  103303. default:
  103304. if(header->sample_rate <= 255000 && header->sample_rate % 1000 == 0)
  103305. sample_rate_hint = u = 12;
  103306. else if(header->sample_rate % 10 == 0)
  103307. sample_rate_hint = u = 14;
  103308. else if(header->sample_rate <= 0xffff)
  103309. sample_rate_hint = u = 13;
  103310. else
  103311. u = 0;
  103312. break;
  103313. }
  103314. if(!FLAC__bitwriter_write_raw_uint32(bw, u, FLAC__FRAME_HEADER_SAMPLE_RATE_LEN))
  103315. return false;
  103316. FLAC__ASSERT(header->channels > 0 && header->channels <= (1u << FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN) && header->channels <= FLAC__MAX_CHANNELS);
  103317. switch(header->channel_assignment) {
  103318. case FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT:
  103319. u = header->channels - 1;
  103320. break;
  103321. case FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE:
  103322. FLAC__ASSERT(header->channels == 2);
  103323. u = 8;
  103324. break;
  103325. case FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE:
  103326. FLAC__ASSERT(header->channels == 2);
  103327. u = 9;
  103328. break;
  103329. case FLAC__CHANNEL_ASSIGNMENT_MID_SIDE:
  103330. FLAC__ASSERT(header->channels == 2);
  103331. u = 10;
  103332. break;
  103333. default:
  103334. FLAC__ASSERT(0);
  103335. }
  103336. if(!FLAC__bitwriter_write_raw_uint32(bw, u, FLAC__FRAME_HEADER_CHANNEL_ASSIGNMENT_LEN))
  103337. return false;
  103338. FLAC__ASSERT(header->bits_per_sample > 0 && header->bits_per_sample <= (1u << FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN));
  103339. switch(header->bits_per_sample) {
  103340. case 8 : u = 1; break;
  103341. case 12: u = 2; break;
  103342. case 16: u = 4; break;
  103343. case 20: u = 5; break;
  103344. case 24: u = 6; break;
  103345. default: u = 0; break;
  103346. }
  103347. if(!FLAC__bitwriter_write_raw_uint32(bw, u, FLAC__FRAME_HEADER_BITS_PER_SAMPLE_LEN))
  103348. return false;
  103349. if(!FLAC__bitwriter_write_raw_uint32(bw, 0, FLAC__FRAME_HEADER_ZERO_PAD_LEN))
  103350. return false;
  103351. if(header->number_type == FLAC__FRAME_NUMBER_TYPE_FRAME_NUMBER) {
  103352. if(!FLAC__bitwriter_write_utf8_uint32(bw, header->number.frame_number))
  103353. return false;
  103354. }
  103355. else {
  103356. if(!FLAC__bitwriter_write_utf8_uint64(bw, header->number.sample_number))
  103357. return false;
  103358. }
  103359. if(blocksize_hint)
  103360. if(!FLAC__bitwriter_write_raw_uint32(bw, header->blocksize-1, (blocksize_hint==6)? 8:16))
  103361. return false;
  103362. switch(sample_rate_hint) {
  103363. case 12:
  103364. if(!FLAC__bitwriter_write_raw_uint32(bw, header->sample_rate / 1000, 8))
  103365. return false;
  103366. break;
  103367. case 13:
  103368. if(!FLAC__bitwriter_write_raw_uint32(bw, header->sample_rate, 16))
  103369. return false;
  103370. break;
  103371. case 14:
  103372. if(!FLAC__bitwriter_write_raw_uint32(bw, header->sample_rate / 10, 16))
  103373. return false;
  103374. break;
  103375. }
  103376. /* write the CRC */
  103377. if(!FLAC__bitwriter_get_write_crc8(bw, &crc))
  103378. return false;
  103379. if(!FLAC__bitwriter_write_raw_uint32(bw, crc, FLAC__FRAME_HEADER_CRC_LEN))
  103380. return false;
  103381. return true;
  103382. }
  103383. FLAC__bool FLAC__subframe_add_constant(const FLAC__Subframe_Constant *subframe, unsigned subframe_bps, unsigned wasted_bits, FLAC__BitWriter *bw)
  103384. {
  103385. FLAC__bool ok;
  103386. ok =
  103387. 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) &&
  103388. (wasted_bits? FLAC__bitwriter_write_unary_unsigned(bw, wasted_bits-1) : true) &&
  103389. FLAC__bitwriter_write_raw_int32(bw, subframe->value, subframe_bps)
  103390. ;
  103391. return ok;
  103392. }
  103393. FLAC__bool FLAC__subframe_add_fixed(const FLAC__Subframe_Fixed *subframe, unsigned residual_samples, unsigned subframe_bps, unsigned wasted_bits, FLAC__BitWriter *bw)
  103394. {
  103395. unsigned i;
  103396. 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))
  103397. return false;
  103398. if(wasted_bits)
  103399. if(!FLAC__bitwriter_write_unary_unsigned(bw, wasted_bits-1))
  103400. return false;
  103401. for(i = 0; i < subframe->order; i++)
  103402. if(!FLAC__bitwriter_write_raw_int32(bw, subframe->warmup[i], subframe_bps))
  103403. return false;
  103404. if(!add_entropy_coding_method_(bw, &subframe->entropy_coding_method))
  103405. return false;
  103406. switch(subframe->entropy_coding_method.type) {
  103407. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE:
  103408. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2:
  103409. if(!add_residual_partitioned_rice_(
  103410. bw,
  103411. subframe->residual,
  103412. residual_samples,
  103413. subframe->order,
  103414. subframe->entropy_coding_method.data.partitioned_rice.contents->parameters,
  103415. subframe->entropy_coding_method.data.partitioned_rice.contents->raw_bits,
  103416. subframe->entropy_coding_method.data.partitioned_rice.order,
  103417. /*is_extended=*/subframe->entropy_coding_method.type == FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2
  103418. ))
  103419. return false;
  103420. break;
  103421. default:
  103422. FLAC__ASSERT(0);
  103423. }
  103424. return true;
  103425. }
  103426. FLAC__bool FLAC__subframe_add_lpc(const FLAC__Subframe_LPC *subframe, unsigned residual_samples, unsigned subframe_bps, unsigned wasted_bits, FLAC__BitWriter *bw)
  103427. {
  103428. unsigned i;
  103429. 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))
  103430. return false;
  103431. if(wasted_bits)
  103432. if(!FLAC__bitwriter_write_unary_unsigned(bw, wasted_bits-1))
  103433. return false;
  103434. for(i = 0; i < subframe->order; i++)
  103435. if(!FLAC__bitwriter_write_raw_int32(bw, subframe->warmup[i], subframe_bps))
  103436. return false;
  103437. if(!FLAC__bitwriter_write_raw_uint32(bw, subframe->qlp_coeff_precision-1, FLAC__SUBFRAME_LPC_QLP_COEFF_PRECISION_LEN))
  103438. return false;
  103439. if(!FLAC__bitwriter_write_raw_int32(bw, subframe->quantization_level, FLAC__SUBFRAME_LPC_QLP_SHIFT_LEN))
  103440. return false;
  103441. for(i = 0; i < subframe->order; i++)
  103442. if(!FLAC__bitwriter_write_raw_int32(bw, subframe->qlp_coeff[i], subframe->qlp_coeff_precision))
  103443. return false;
  103444. if(!add_entropy_coding_method_(bw, &subframe->entropy_coding_method))
  103445. return false;
  103446. switch(subframe->entropy_coding_method.type) {
  103447. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE:
  103448. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2:
  103449. if(!add_residual_partitioned_rice_(
  103450. bw,
  103451. subframe->residual,
  103452. residual_samples,
  103453. subframe->order,
  103454. subframe->entropy_coding_method.data.partitioned_rice.contents->parameters,
  103455. subframe->entropy_coding_method.data.partitioned_rice.contents->raw_bits,
  103456. subframe->entropy_coding_method.data.partitioned_rice.order,
  103457. /*is_extended=*/subframe->entropy_coding_method.type == FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2
  103458. ))
  103459. return false;
  103460. break;
  103461. default:
  103462. FLAC__ASSERT(0);
  103463. }
  103464. return true;
  103465. }
  103466. FLAC__bool FLAC__subframe_add_verbatim(const FLAC__Subframe_Verbatim *subframe, unsigned samples, unsigned subframe_bps, unsigned wasted_bits, FLAC__BitWriter *bw)
  103467. {
  103468. unsigned i;
  103469. const FLAC__int32 *signal = subframe->data;
  103470. 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))
  103471. return false;
  103472. if(wasted_bits)
  103473. if(!FLAC__bitwriter_write_unary_unsigned(bw, wasted_bits-1))
  103474. return false;
  103475. for(i = 0; i < samples; i++)
  103476. if(!FLAC__bitwriter_write_raw_int32(bw, signal[i], subframe_bps))
  103477. return false;
  103478. return true;
  103479. }
  103480. FLAC__bool add_entropy_coding_method_(FLAC__BitWriter *bw, const FLAC__EntropyCodingMethod *method)
  103481. {
  103482. if(!FLAC__bitwriter_write_raw_uint32(bw, method->type, FLAC__ENTROPY_CODING_METHOD_TYPE_LEN))
  103483. return false;
  103484. switch(method->type) {
  103485. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE:
  103486. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2:
  103487. if(!FLAC__bitwriter_write_raw_uint32(bw, method->data.partitioned_rice.order, FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN))
  103488. return false;
  103489. break;
  103490. default:
  103491. FLAC__ASSERT(0);
  103492. }
  103493. return true;
  103494. }
  103495. 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)
  103496. {
  103497. const unsigned plen = is_extended? FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_PARAMETER_LEN : FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_PARAMETER_LEN;
  103498. const unsigned pesc = is_extended? FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_ESCAPE_PARAMETER : FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER;
  103499. if(partition_order == 0) {
  103500. unsigned i;
  103501. if(raw_bits[0] == 0) {
  103502. if(!FLAC__bitwriter_write_raw_uint32(bw, rice_parameters[0], plen))
  103503. return false;
  103504. if(!FLAC__bitwriter_write_rice_signed_block(bw, residual, residual_samples, rice_parameters[0]))
  103505. return false;
  103506. }
  103507. else {
  103508. FLAC__ASSERT(rice_parameters[0] == 0);
  103509. if(!FLAC__bitwriter_write_raw_uint32(bw, pesc, plen))
  103510. return false;
  103511. if(!FLAC__bitwriter_write_raw_uint32(bw, raw_bits[0], FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_RAW_LEN))
  103512. return false;
  103513. for(i = 0; i < residual_samples; i++) {
  103514. if(!FLAC__bitwriter_write_raw_int32(bw, residual[i], raw_bits[0]))
  103515. return false;
  103516. }
  103517. }
  103518. return true;
  103519. }
  103520. else {
  103521. unsigned i, j, k = 0, k_last = 0;
  103522. unsigned partition_samples;
  103523. const unsigned default_partition_samples = (residual_samples+predictor_order) >> partition_order;
  103524. for(i = 0; i < (1u<<partition_order); i++) {
  103525. partition_samples = default_partition_samples;
  103526. if(i == 0)
  103527. partition_samples -= predictor_order;
  103528. k += partition_samples;
  103529. if(raw_bits[i] == 0) {
  103530. if(!FLAC__bitwriter_write_raw_uint32(bw, rice_parameters[i], plen))
  103531. return false;
  103532. if(!FLAC__bitwriter_write_rice_signed_block(bw, residual+k_last, k-k_last, rice_parameters[i]))
  103533. return false;
  103534. }
  103535. else {
  103536. if(!FLAC__bitwriter_write_raw_uint32(bw, pesc, plen))
  103537. return false;
  103538. if(!FLAC__bitwriter_write_raw_uint32(bw, raw_bits[i], FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_RAW_LEN))
  103539. return false;
  103540. for(j = k_last; j < k; j++) {
  103541. if(!FLAC__bitwriter_write_raw_int32(bw, residual[j], raw_bits[i]))
  103542. return false;
  103543. }
  103544. }
  103545. k_last = k;
  103546. }
  103547. return true;
  103548. }
  103549. }
  103550. #endif
  103551. /*** End of inlined file: stream_encoder_framing.c ***/
  103552. /*** Start of inlined file: window_flac.c ***/
  103553. /*** Start of inlined file: juce_FlacHeader.h ***/
  103554. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  103555. // tasks..
  103556. #define VERSION "1.2.1"
  103557. #define FLAC__NO_DLL 1
  103558. #if JUCE_MSVC
  103559. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  103560. #endif
  103561. #if JUCE_MAC
  103562. #define FLAC__SYS_DARWIN 1
  103563. #endif
  103564. /*** End of inlined file: juce_FlacHeader.h ***/
  103565. #if JUCE_USE_FLAC
  103566. #if HAVE_CONFIG_H
  103567. # include <config.h>
  103568. #endif
  103569. #include <math.h>
  103570. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  103571. #ifndef M_PI
  103572. /* math.h in VC++ doesn't seem to have this (how Microsoft is that?) */
  103573. #define M_PI 3.14159265358979323846
  103574. #endif
  103575. void FLAC__window_bartlett(FLAC__real *window, const FLAC__int32 L)
  103576. {
  103577. const FLAC__int32 N = L - 1;
  103578. FLAC__int32 n;
  103579. if (L & 1) {
  103580. for (n = 0; n <= N/2; n++)
  103581. window[n] = 2.0f * n / (float)N;
  103582. for (; n <= N; n++)
  103583. window[n] = 2.0f - 2.0f * n / (float)N;
  103584. }
  103585. else {
  103586. for (n = 0; n <= L/2-1; n++)
  103587. window[n] = 2.0f * n / (float)N;
  103588. for (; n <= N; n++)
  103589. window[n] = 2.0f - 2.0f * (N-n) / (float)N;
  103590. }
  103591. }
  103592. void FLAC__window_bartlett_hann(FLAC__real *window, const FLAC__int32 L)
  103593. {
  103594. const FLAC__int32 N = L - 1;
  103595. FLAC__int32 n;
  103596. for (n = 0; n < L; n++)
  103597. 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)));
  103598. }
  103599. void FLAC__window_blackman(FLAC__real *window, const FLAC__int32 L)
  103600. {
  103601. const FLAC__int32 N = L - 1;
  103602. FLAC__int32 n;
  103603. for (n = 0; n < L; n++)
  103604. window[n] = (FLAC__real)(0.42f - 0.5f * cos(2.0f * M_PI * n / N) + 0.08f * cos(4.0f * M_PI * n / N));
  103605. }
  103606. /* 4-term -92dB side-lobe */
  103607. void FLAC__window_blackman_harris_4term_92db_sidelobe(FLAC__real *window, const FLAC__int32 L)
  103608. {
  103609. const FLAC__int32 N = L - 1;
  103610. FLAC__int32 n;
  103611. for (n = 0; n <= N; n++)
  103612. 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));
  103613. }
  103614. void FLAC__window_connes(FLAC__real *window, const FLAC__int32 L)
  103615. {
  103616. const FLAC__int32 N = L - 1;
  103617. const double N2 = (double)N / 2.;
  103618. FLAC__int32 n;
  103619. for (n = 0; n <= N; n++) {
  103620. double k = ((double)n - N2) / N2;
  103621. k = 1.0f - k * k;
  103622. window[n] = (FLAC__real)(k * k);
  103623. }
  103624. }
  103625. void FLAC__window_flattop(FLAC__real *window, const FLAC__int32 L)
  103626. {
  103627. const FLAC__int32 N = L - 1;
  103628. FLAC__int32 n;
  103629. for (n = 0; n < L; n++)
  103630. 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));
  103631. }
  103632. void FLAC__window_gauss(FLAC__real *window, const FLAC__int32 L, const FLAC__real stddev)
  103633. {
  103634. const FLAC__int32 N = L - 1;
  103635. const double N2 = (double)N / 2.;
  103636. FLAC__int32 n;
  103637. for (n = 0; n <= N; n++) {
  103638. const double k = ((double)n - N2) / (stddev * N2);
  103639. window[n] = (FLAC__real)exp(-0.5f * k * k);
  103640. }
  103641. }
  103642. void FLAC__window_hamming(FLAC__real *window, const FLAC__int32 L)
  103643. {
  103644. const FLAC__int32 N = L - 1;
  103645. FLAC__int32 n;
  103646. for (n = 0; n < L; n++)
  103647. window[n] = (FLAC__real)(0.54f - 0.46f * cos(2.0f * M_PI * n / N));
  103648. }
  103649. void FLAC__window_hann(FLAC__real *window, const FLAC__int32 L)
  103650. {
  103651. const FLAC__int32 N = L - 1;
  103652. FLAC__int32 n;
  103653. for (n = 0; n < L; n++)
  103654. window[n] = (FLAC__real)(0.5f - 0.5f * cos(2.0f * M_PI * n / N));
  103655. }
  103656. void FLAC__window_kaiser_bessel(FLAC__real *window, const FLAC__int32 L)
  103657. {
  103658. const FLAC__int32 N = L - 1;
  103659. FLAC__int32 n;
  103660. for (n = 0; n < L; n++)
  103661. 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));
  103662. }
  103663. void FLAC__window_nuttall(FLAC__real *window, const FLAC__int32 L)
  103664. {
  103665. const FLAC__int32 N = L - 1;
  103666. FLAC__int32 n;
  103667. for (n = 0; n < L; n++)
  103668. 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));
  103669. }
  103670. void FLAC__window_rectangle(FLAC__real *window, const FLAC__int32 L)
  103671. {
  103672. FLAC__int32 n;
  103673. for (n = 0; n < L; n++)
  103674. window[n] = 1.0f;
  103675. }
  103676. void FLAC__window_triangle(FLAC__real *window, const FLAC__int32 L)
  103677. {
  103678. FLAC__int32 n;
  103679. if (L & 1) {
  103680. for (n = 1; n <= L+1/2; n++)
  103681. window[n-1] = 2.0f * n / ((float)L + 1.0f);
  103682. for (; n <= L; n++)
  103683. window[n-1] = - (float)(2 * (L - n + 1)) / ((float)L + 1.0f);
  103684. }
  103685. else {
  103686. for (n = 1; n <= L/2; n++)
  103687. window[n-1] = 2.0f * n / (float)L;
  103688. for (; n <= L; n++)
  103689. window[n-1] = ((float)(2 * (L - n)) + 1.0f) / (float)L;
  103690. }
  103691. }
  103692. void FLAC__window_tukey(FLAC__real *window, const FLAC__int32 L, const FLAC__real p)
  103693. {
  103694. if (p <= 0.0)
  103695. FLAC__window_rectangle(window, L);
  103696. else if (p >= 1.0)
  103697. FLAC__window_hann(window, L);
  103698. else {
  103699. const FLAC__int32 Np = (FLAC__int32)(p / 2.0f * L) - 1;
  103700. FLAC__int32 n;
  103701. /* start with rectangle... */
  103702. FLAC__window_rectangle(window, L);
  103703. /* ...replace ends with hann */
  103704. if (Np > 0) {
  103705. for (n = 0; n <= Np; n++) {
  103706. window[n] = (FLAC__real)(0.5f - 0.5f * cos(M_PI * n / Np));
  103707. window[L-Np-1+n] = (FLAC__real)(0.5f - 0.5f * cos(M_PI * (n+Np) / Np));
  103708. }
  103709. }
  103710. }
  103711. }
  103712. void FLAC__window_welch(FLAC__real *window, const FLAC__int32 L)
  103713. {
  103714. const FLAC__int32 N = L - 1;
  103715. const double N2 = (double)N / 2.;
  103716. FLAC__int32 n;
  103717. for (n = 0; n <= N; n++) {
  103718. const double k = ((double)n - N2) / N2;
  103719. window[n] = (FLAC__real)(1.0f - k * k);
  103720. }
  103721. }
  103722. #endif /* !defined FLAC__INTEGER_ONLY_LIBRARY */
  103723. #endif
  103724. /*** End of inlined file: window_flac.c ***/
  103725. #else
  103726. #include <FLAC/all.h>
  103727. #endif
  103728. }
  103729. #undef max
  103730. #undef min
  103731. #ifdef _MSC_VER
  103732. #pragma warning (pop)
  103733. #endif
  103734. BEGIN_JUCE_NAMESPACE
  103735. static const char* const flacFormatName = "FLAC file";
  103736. static const char* const flacExtensions[] = { ".flac", 0 };
  103737. class FlacReader : public AudioFormatReader
  103738. {
  103739. public:
  103740. FlacReader (InputStream* const in)
  103741. : AudioFormatReader (in, TRANS (flacFormatName)),
  103742. reservoir (2, 0),
  103743. reservoirStart (0),
  103744. samplesInReservoir (0),
  103745. scanningForLength (false)
  103746. {
  103747. using namespace FlacNamespace;
  103748. lengthInSamples = 0;
  103749. decoder = FLAC__stream_decoder_new();
  103750. ok = FLAC__stream_decoder_init_stream (decoder,
  103751. readCallback_, seekCallback_, tellCallback_, lengthCallback_,
  103752. eofCallback_, writeCallback_, metadataCallback_, errorCallback_,
  103753. this) == FLAC__STREAM_DECODER_INIT_STATUS_OK;
  103754. if (ok)
  103755. {
  103756. FLAC__stream_decoder_process_until_end_of_metadata (decoder);
  103757. if (lengthInSamples == 0 && sampleRate > 0)
  103758. {
  103759. // the length hasn't been stored in the metadata, so we'll need to
  103760. // work it out the length the hard way, by scanning the whole file..
  103761. scanningForLength = true;
  103762. FLAC__stream_decoder_process_until_end_of_stream (decoder);
  103763. scanningForLength = false;
  103764. const int64 tempLength = lengthInSamples;
  103765. FLAC__stream_decoder_reset (decoder);
  103766. FLAC__stream_decoder_process_until_end_of_metadata (decoder);
  103767. lengthInSamples = tempLength;
  103768. }
  103769. }
  103770. }
  103771. ~FlacReader()
  103772. {
  103773. FlacNamespace::FLAC__stream_decoder_delete (decoder);
  103774. }
  103775. void useMetadata (const FlacNamespace::FLAC__StreamMetadata_StreamInfo& info)
  103776. {
  103777. sampleRate = info.sample_rate;
  103778. bitsPerSample = info.bits_per_sample;
  103779. lengthInSamples = (unsigned int) info.total_samples;
  103780. numChannels = info.channels;
  103781. reservoir.setSize (numChannels, 2 * info.max_blocksize, false, false, true);
  103782. }
  103783. // returns the number of samples read
  103784. bool readSamples (int** destSamples, int numDestChannels, int startOffsetInDestBuffer,
  103785. int64 startSampleInFile, int numSamples)
  103786. {
  103787. using namespace FlacNamespace;
  103788. if (! ok)
  103789. return false;
  103790. while (numSamples > 0)
  103791. {
  103792. if (startSampleInFile >= reservoirStart
  103793. && startSampleInFile < reservoirStart + samplesInReservoir)
  103794. {
  103795. const int num = (int) jmin ((int64) numSamples,
  103796. reservoirStart + samplesInReservoir - startSampleInFile);
  103797. jassert (num > 0);
  103798. for (int i = jmin (numDestChannels, reservoir.getNumChannels()); --i >= 0;)
  103799. if (destSamples[i] != 0)
  103800. memcpy (destSamples[i] + startOffsetInDestBuffer,
  103801. reservoir.getSampleData (i, (int) (startSampleInFile - reservoirStart)),
  103802. sizeof (int) * num);
  103803. startOffsetInDestBuffer += num;
  103804. startSampleInFile += num;
  103805. numSamples -= num;
  103806. }
  103807. else
  103808. {
  103809. if (startSampleInFile >= (int) lengthInSamples)
  103810. {
  103811. samplesInReservoir = 0;
  103812. }
  103813. else if (startSampleInFile < reservoirStart
  103814. || startSampleInFile > reservoirStart + jmax (samplesInReservoir, 511))
  103815. {
  103816. // had some problems with flac crashing if the read pos is aligned more
  103817. // accurately than this. Probably fixed in newer versions of the library, though.
  103818. reservoirStart = (int) (startSampleInFile & ~511);
  103819. samplesInReservoir = 0;
  103820. FLAC__stream_decoder_seek_absolute (decoder, (FLAC__uint64) reservoirStart);
  103821. }
  103822. else
  103823. {
  103824. reservoirStart += samplesInReservoir;
  103825. samplesInReservoir = 0;
  103826. FLAC__stream_decoder_process_single (decoder);
  103827. }
  103828. if (samplesInReservoir == 0)
  103829. break;
  103830. }
  103831. }
  103832. if (numSamples > 0)
  103833. {
  103834. for (int i = numDestChannels; --i >= 0;)
  103835. if (destSamples[i] != 0)
  103836. zeromem (destSamples[i] + startOffsetInDestBuffer,
  103837. sizeof (int) * numSamples);
  103838. }
  103839. return true;
  103840. }
  103841. void useSamples (const FlacNamespace::FLAC__int32* const buffer[], int numSamples)
  103842. {
  103843. if (scanningForLength)
  103844. {
  103845. lengthInSamples += numSamples;
  103846. }
  103847. else
  103848. {
  103849. if (numSamples > reservoir.getNumSamples())
  103850. reservoir.setSize (numChannels, numSamples, false, false, true);
  103851. const int bitsToShift = 32 - bitsPerSample;
  103852. for (int i = 0; i < (int) numChannels; ++i)
  103853. {
  103854. const FlacNamespace::FLAC__int32* src = buffer[i];
  103855. int n = i;
  103856. while (src == 0 && n > 0)
  103857. src = buffer [--n];
  103858. if (src != 0)
  103859. {
  103860. int* dest = (int*) reservoir.getSampleData(i);
  103861. for (int j = 0; j < numSamples; ++j)
  103862. dest[j] = src[j] << bitsToShift;
  103863. }
  103864. }
  103865. samplesInReservoir = numSamples;
  103866. }
  103867. }
  103868. static FlacNamespace::FLAC__StreamDecoderReadStatus readCallback_ (const FlacNamespace::FLAC__StreamDecoder*, FlacNamespace::FLAC__byte buffer[], size_t* bytes, void* client_data)
  103869. {
  103870. using namespace FlacNamespace;
  103871. *bytes = (size_t) static_cast <const FlacReader*> (client_data)->input->read (buffer, (int) *bytes);
  103872. return FLAC__STREAM_DECODER_READ_STATUS_CONTINUE;
  103873. }
  103874. static FlacNamespace::FLAC__StreamDecoderSeekStatus seekCallback_ (const FlacNamespace::FLAC__StreamDecoder*, FlacNamespace::FLAC__uint64 absolute_byte_offset, void* client_data)
  103875. {
  103876. using namespace FlacNamespace;
  103877. static_cast <const FlacReader*> (client_data)->input->setPosition ((int) absolute_byte_offset);
  103878. return FLAC__STREAM_DECODER_SEEK_STATUS_OK;
  103879. }
  103880. static FlacNamespace::FLAC__StreamDecoderTellStatus tellCallback_ (const FlacNamespace::FLAC__StreamDecoder*, FlacNamespace::FLAC__uint64* absolute_byte_offset, void* client_data)
  103881. {
  103882. using namespace FlacNamespace;
  103883. *absolute_byte_offset = static_cast <const FlacReader*> (client_data)->input->getPosition();
  103884. return FLAC__STREAM_DECODER_TELL_STATUS_OK;
  103885. }
  103886. static FlacNamespace::FLAC__StreamDecoderLengthStatus lengthCallback_ (const FlacNamespace::FLAC__StreamDecoder*, FlacNamespace::FLAC__uint64* stream_length, void* client_data)
  103887. {
  103888. using namespace FlacNamespace;
  103889. *stream_length = static_cast <const FlacReader*> (client_data)->input->getTotalLength();
  103890. return FLAC__STREAM_DECODER_LENGTH_STATUS_OK;
  103891. }
  103892. static FlacNamespace::FLAC__bool eofCallback_ (const FlacNamespace::FLAC__StreamDecoder*, void* client_data)
  103893. {
  103894. return static_cast <const FlacReader*> (client_data)->input->isExhausted();
  103895. }
  103896. static FlacNamespace::FLAC__StreamDecoderWriteStatus writeCallback_ (const FlacNamespace::FLAC__StreamDecoder*,
  103897. const FlacNamespace::FLAC__Frame* frame,
  103898. const FlacNamespace::FLAC__int32* const buffer[],
  103899. void* client_data)
  103900. {
  103901. using namespace FlacNamespace;
  103902. static_cast <FlacReader*> (client_data)->useSamples (buffer, frame->header.blocksize);
  103903. return FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE;
  103904. }
  103905. static void metadataCallback_ (const FlacNamespace::FLAC__StreamDecoder*,
  103906. const FlacNamespace::FLAC__StreamMetadata* metadata,
  103907. void* client_data)
  103908. {
  103909. static_cast <FlacReader*> (client_data)->useMetadata (metadata->data.stream_info);
  103910. }
  103911. static void errorCallback_ (const FlacNamespace::FLAC__StreamDecoder*, FlacNamespace::FLAC__StreamDecoderErrorStatus, void*)
  103912. {
  103913. }
  103914. juce_UseDebuggingNewOperator
  103915. private:
  103916. FlacNamespace::FLAC__StreamDecoder* decoder;
  103917. AudioSampleBuffer reservoir;
  103918. int reservoirStart, samplesInReservoir;
  103919. bool ok, scanningForLength;
  103920. FlacReader (const FlacReader&);
  103921. FlacReader& operator= (const FlacReader&);
  103922. };
  103923. class FlacWriter : public AudioFormatWriter
  103924. {
  103925. public:
  103926. FlacWriter (OutputStream* const out,
  103927. const double sampleRate_,
  103928. const int numChannels_,
  103929. const int bitsPerSample_)
  103930. : AudioFormatWriter (out, TRANS (flacFormatName),
  103931. sampleRate_,
  103932. numChannels_,
  103933. bitsPerSample_)
  103934. {
  103935. using namespace FlacNamespace;
  103936. encoder = FLAC__stream_encoder_new();
  103937. FLAC__stream_encoder_set_do_mid_side_stereo (encoder, numChannels == 2);
  103938. FLAC__stream_encoder_set_loose_mid_side_stereo (encoder, numChannels == 2);
  103939. FLAC__stream_encoder_set_channels (encoder, numChannels);
  103940. FLAC__stream_encoder_set_bits_per_sample (encoder, jmin ((unsigned int) 24, bitsPerSample));
  103941. FLAC__stream_encoder_set_sample_rate (encoder, (unsigned int) sampleRate);
  103942. FLAC__stream_encoder_set_blocksize (encoder, 2048);
  103943. FLAC__stream_encoder_set_do_escape_coding (encoder, true);
  103944. ok = FLAC__stream_encoder_init_stream (encoder,
  103945. encodeWriteCallback, encodeSeekCallback,
  103946. encodeTellCallback, encodeMetadataCallback,
  103947. this) == FLAC__STREAM_ENCODER_INIT_STATUS_OK;
  103948. }
  103949. ~FlacWriter()
  103950. {
  103951. if (ok)
  103952. {
  103953. FlacNamespace::FLAC__stream_encoder_finish (encoder);
  103954. output->flush();
  103955. }
  103956. else
  103957. {
  103958. output = 0; // to stop the base class deleting this, as it needs to be returned
  103959. // to the caller of createWriter()
  103960. }
  103961. FlacNamespace::FLAC__stream_encoder_delete (encoder);
  103962. }
  103963. bool write (const int** samplesToWrite, int numSamples)
  103964. {
  103965. using namespace FlacNamespace;
  103966. if (! ok)
  103967. return false;
  103968. int* buf[3];
  103969. const int bitsToShift = 32 - bitsPerSample;
  103970. if (bitsToShift > 0)
  103971. {
  103972. const int numChannelsToWrite = (samplesToWrite[1] == 0) ? 1 : 2;
  103973. temp.setSize (sizeof (int) * numSamples * numChannelsToWrite);
  103974. buf[0] = (int*) temp.getData();
  103975. buf[1] = buf[0] + numSamples;
  103976. buf[2] = 0;
  103977. for (int i = numChannelsToWrite; --i >= 0;)
  103978. {
  103979. if (samplesToWrite[i] != 0)
  103980. {
  103981. for (int j = 0; j < numSamples; ++j)
  103982. buf [i][j] = (samplesToWrite [i][j] >> bitsToShift);
  103983. }
  103984. }
  103985. samplesToWrite = (const int**) buf;
  103986. }
  103987. return FLAC__stream_encoder_process (encoder,
  103988. (const FLAC__int32**) samplesToWrite,
  103989. numSamples) != 0;
  103990. }
  103991. bool writeData (const void* const data, const int size) const
  103992. {
  103993. return output->write (data, size);
  103994. }
  103995. static void packUint32 (FlacNamespace::FLAC__uint32 val, FlacNamespace::FLAC__byte* b, const int bytes)
  103996. {
  103997. using namespace FlacNamespace;
  103998. b += bytes;
  103999. for (int i = 0; i < bytes; ++i)
  104000. {
  104001. *(--b) = (FLAC__byte) (val & 0xff);
  104002. val >>= 8;
  104003. }
  104004. }
  104005. void writeMetaData (const FlacNamespace::FLAC__StreamMetadata* metadata)
  104006. {
  104007. using namespace FlacNamespace;
  104008. const FLAC__StreamMetadata_StreamInfo& info = metadata->data.stream_info;
  104009. unsigned char buffer [FLAC__STREAM_METADATA_STREAMINFO_LENGTH];
  104010. const unsigned int channelsMinus1 = info.channels - 1;
  104011. const unsigned int bitsMinus1 = info.bits_per_sample - 1;
  104012. packUint32 (info.min_blocksize, buffer, 2);
  104013. packUint32 (info.max_blocksize, buffer + 2, 2);
  104014. packUint32 (info.min_framesize, buffer + 4, 3);
  104015. packUint32 (info.max_framesize, buffer + 7, 3);
  104016. buffer[10] = (uint8) ((info.sample_rate >> 12) & 0xff);
  104017. buffer[11] = (uint8) ((info.sample_rate >> 4) & 0xff);
  104018. buffer[12] = (uint8) (((info.sample_rate & 0x0f) << 4) | (channelsMinus1 << 1) | (bitsMinus1 >> 4));
  104019. buffer[13] = (FLAC__byte) (((bitsMinus1 & 0x0f) << 4) | (unsigned int) ((info.total_samples >> 32) & 0x0f));
  104020. packUint32 ((FLAC__uint32) info.total_samples, buffer + 14, 4);
  104021. memcpy (buffer + 18, info.md5sum, 16);
  104022. const bool seekOk = output->setPosition (4);
  104023. (void) seekOk;
  104024. // if this fails, you've given it an output stream that can't seek! It needs
  104025. // to be able to seek back to write the header
  104026. jassert (seekOk);
  104027. output->writeIntBigEndian (FLAC__STREAM_METADATA_STREAMINFO_LENGTH);
  104028. output->write (buffer, FLAC__STREAM_METADATA_STREAMINFO_LENGTH);
  104029. }
  104030. static FlacNamespace::FLAC__StreamEncoderWriteStatus encodeWriteCallback (const FlacNamespace::FLAC__StreamEncoder*,
  104031. const FlacNamespace::FLAC__byte buffer[],
  104032. size_t bytes,
  104033. unsigned int /*samples*/,
  104034. unsigned int /*current_frame*/,
  104035. void* client_data)
  104036. {
  104037. using namespace FlacNamespace;
  104038. return static_cast <FlacWriter*> (client_data)->writeData (buffer, (int) bytes)
  104039. ? FLAC__STREAM_ENCODER_WRITE_STATUS_OK
  104040. : FLAC__STREAM_ENCODER_WRITE_STATUS_FATAL_ERROR;
  104041. }
  104042. static FlacNamespace::FLAC__StreamEncoderSeekStatus encodeSeekCallback (const FlacNamespace::FLAC__StreamEncoder*, FlacNamespace::FLAC__uint64, void*)
  104043. {
  104044. using namespace FlacNamespace;
  104045. return FLAC__STREAM_ENCODER_SEEK_STATUS_UNSUPPORTED;
  104046. }
  104047. static FlacNamespace::FLAC__StreamEncoderTellStatus encodeTellCallback (const FlacNamespace::FLAC__StreamEncoder*, FlacNamespace::FLAC__uint64* absolute_byte_offset, void* client_data)
  104048. {
  104049. using namespace FlacNamespace;
  104050. if (client_data == 0)
  104051. return FLAC__STREAM_ENCODER_TELL_STATUS_UNSUPPORTED;
  104052. *absolute_byte_offset = (FLAC__uint64) static_cast <FlacWriter*> (client_data)->output->getPosition();
  104053. return FLAC__STREAM_ENCODER_TELL_STATUS_OK;
  104054. }
  104055. static void encodeMetadataCallback (const FlacNamespace::FLAC__StreamEncoder*, const FlacNamespace::FLAC__StreamMetadata* metadata, void* client_data)
  104056. {
  104057. static_cast <FlacWriter*> (client_data)->writeMetaData (metadata);
  104058. }
  104059. juce_UseDebuggingNewOperator
  104060. bool ok;
  104061. private:
  104062. FlacNamespace::FLAC__StreamEncoder* encoder;
  104063. MemoryBlock temp;
  104064. FlacWriter (const FlacWriter&);
  104065. FlacWriter& operator= (const FlacWriter&);
  104066. };
  104067. FlacAudioFormat::FlacAudioFormat()
  104068. : AudioFormat (TRANS (flacFormatName), StringArray (flacExtensions))
  104069. {
  104070. }
  104071. FlacAudioFormat::~FlacAudioFormat()
  104072. {
  104073. }
  104074. const Array <int> FlacAudioFormat::getPossibleSampleRates()
  104075. {
  104076. const int rates[] = { 22050, 32000, 44100, 48000, 88200, 96000, 0 };
  104077. return Array <int> (rates);
  104078. }
  104079. const Array <int> FlacAudioFormat::getPossibleBitDepths()
  104080. {
  104081. const int depths[] = { 16, 24, 0 };
  104082. return Array <int> (depths);
  104083. }
  104084. bool FlacAudioFormat::canDoStereo()
  104085. {
  104086. return true;
  104087. }
  104088. bool FlacAudioFormat::canDoMono()
  104089. {
  104090. return true;
  104091. }
  104092. bool FlacAudioFormat::isCompressed()
  104093. {
  104094. return true;
  104095. }
  104096. AudioFormatReader* FlacAudioFormat::createReaderFor (InputStream* in,
  104097. const bool deleteStreamIfOpeningFails)
  104098. {
  104099. ScopedPointer<FlacReader> r (new FlacReader (in));
  104100. if (r->sampleRate != 0)
  104101. return r.release();
  104102. if (! deleteStreamIfOpeningFails)
  104103. r->input = 0;
  104104. return 0;
  104105. }
  104106. AudioFormatWriter* FlacAudioFormat::createWriterFor (OutputStream* out,
  104107. double sampleRate,
  104108. unsigned int numberOfChannels,
  104109. int bitsPerSample,
  104110. const StringPairArray& /*metadataValues*/,
  104111. int /*qualityOptionIndex*/)
  104112. {
  104113. if (getPossibleBitDepths().contains (bitsPerSample))
  104114. {
  104115. ScopedPointer<FlacWriter> w (new FlacWriter (out, sampleRate, numberOfChannels, bitsPerSample));
  104116. if (w->ok)
  104117. return w.release();
  104118. }
  104119. return 0;
  104120. }
  104121. END_JUCE_NAMESPACE
  104122. #endif
  104123. /*** End of inlined file: juce_FlacAudioFormat.cpp ***/
  104124. /*** Start of inlined file: juce_OggVorbisAudioFormat.cpp ***/
  104125. #if JUCE_USE_OGGVORBIS
  104126. #if JUCE_MAC
  104127. #define __MACOSX__ 1
  104128. #endif
  104129. namespace OggVorbisNamespace
  104130. {
  104131. #if JUCE_INCLUDE_OGGVORBIS_CODE
  104132. /*** Start of inlined file: vorbisenc.h ***/
  104133. #ifndef _OV_ENC_H_
  104134. #define _OV_ENC_H_
  104135. #ifdef __cplusplus
  104136. extern "C"
  104137. {
  104138. #endif /* __cplusplus */
  104139. /*** Start of inlined file: codec.h ***/
  104140. #ifndef _vorbis_codec_h_
  104141. #define _vorbis_codec_h_
  104142. #ifdef __cplusplus
  104143. extern "C"
  104144. {
  104145. #endif /* __cplusplus */
  104146. /*** Start of inlined file: ogg.h ***/
  104147. #ifndef _OGG_H
  104148. #define _OGG_H
  104149. #ifdef __cplusplus
  104150. extern "C" {
  104151. #endif
  104152. /*** Start of inlined file: os_types.h ***/
  104153. #ifndef _OS_TYPES_H
  104154. #define _OS_TYPES_H
  104155. /* make it easy on the folks that want to compile the libs with a
  104156. different malloc than stdlib */
  104157. #define _ogg_malloc malloc
  104158. #define _ogg_calloc calloc
  104159. #define _ogg_realloc realloc
  104160. #define _ogg_free free
  104161. #if defined(_WIN32)
  104162. # if defined(__CYGWIN__)
  104163. # include <_G_config.h>
  104164. typedef _G_int64_t ogg_int64_t;
  104165. typedef _G_int32_t ogg_int32_t;
  104166. typedef _G_uint32_t ogg_uint32_t;
  104167. typedef _G_int16_t ogg_int16_t;
  104168. typedef _G_uint16_t ogg_uint16_t;
  104169. # elif defined(__MINGW32__)
  104170. typedef short ogg_int16_t;
  104171. typedef unsigned short ogg_uint16_t;
  104172. typedef int ogg_int32_t;
  104173. typedef unsigned int ogg_uint32_t;
  104174. typedef long long ogg_int64_t;
  104175. typedef unsigned long long ogg_uint64_t;
  104176. # elif defined(__MWERKS__)
  104177. typedef long long ogg_int64_t;
  104178. typedef int ogg_int32_t;
  104179. typedef unsigned int ogg_uint32_t;
  104180. typedef short ogg_int16_t;
  104181. typedef unsigned short ogg_uint16_t;
  104182. # else
  104183. /* MSVC/Borland */
  104184. typedef __int64 ogg_int64_t;
  104185. typedef __int32 ogg_int32_t;
  104186. typedef unsigned __int32 ogg_uint32_t;
  104187. typedef __int16 ogg_int16_t;
  104188. typedef unsigned __int16 ogg_uint16_t;
  104189. # endif
  104190. #elif defined(__MACOS__)
  104191. # include <sys/types.h>
  104192. typedef SInt16 ogg_int16_t;
  104193. typedef UInt16 ogg_uint16_t;
  104194. typedef SInt32 ogg_int32_t;
  104195. typedef UInt32 ogg_uint32_t;
  104196. typedef SInt64 ogg_int64_t;
  104197. #elif defined(__MACOSX__) /* MacOS X Framework build */
  104198. # include <sys/types.h>
  104199. typedef int16_t ogg_int16_t;
  104200. typedef u_int16_t ogg_uint16_t;
  104201. typedef int32_t ogg_int32_t;
  104202. typedef u_int32_t ogg_uint32_t;
  104203. typedef int64_t ogg_int64_t;
  104204. #elif defined(__BEOS__)
  104205. /* Be */
  104206. # include <inttypes.h>
  104207. typedef int16_t ogg_int16_t;
  104208. typedef u_int16_t ogg_uint16_t;
  104209. typedef int32_t ogg_int32_t;
  104210. typedef u_int32_t ogg_uint32_t;
  104211. typedef int64_t ogg_int64_t;
  104212. #elif defined (__EMX__)
  104213. /* OS/2 GCC */
  104214. typedef short ogg_int16_t;
  104215. typedef unsigned short ogg_uint16_t;
  104216. typedef int ogg_int32_t;
  104217. typedef unsigned int ogg_uint32_t;
  104218. typedef long long ogg_int64_t;
  104219. #elif defined (DJGPP)
  104220. /* DJGPP */
  104221. typedef short ogg_int16_t;
  104222. typedef int ogg_int32_t;
  104223. typedef unsigned int ogg_uint32_t;
  104224. typedef long long ogg_int64_t;
  104225. #elif defined(R5900)
  104226. /* PS2 EE */
  104227. typedef long ogg_int64_t;
  104228. typedef int ogg_int32_t;
  104229. typedef unsigned ogg_uint32_t;
  104230. typedef short ogg_int16_t;
  104231. #elif defined(__SYMBIAN32__)
  104232. /* Symbian GCC */
  104233. typedef signed short ogg_int16_t;
  104234. typedef unsigned short ogg_uint16_t;
  104235. typedef signed int ogg_int32_t;
  104236. typedef unsigned int ogg_uint32_t;
  104237. typedef long long int ogg_int64_t;
  104238. #else
  104239. # include <sys/types.h>
  104240. /*** Start of inlined file: config_types.h ***/
  104241. #ifndef __CONFIG_TYPES_H__
  104242. #define __CONFIG_TYPES_H__
  104243. typedef int16_t ogg_int16_t;
  104244. typedef unsigned short ogg_uint16_t;
  104245. typedef int32_t ogg_int32_t;
  104246. typedef unsigned int ogg_uint32_t;
  104247. typedef int64_t ogg_int64_t;
  104248. #endif
  104249. /*** End of inlined file: config_types.h ***/
  104250. #endif
  104251. #endif /* _OS_TYPES_H */
  104252. /*** End of inlined file: os_types.h ***/
  104253. typedef struct {
  104254. long endbyte;
  104255. int endbit;
  104256. unsigned char *buffer;
  104257. unsigned char *ptr;
  104258. long storage;
  104259. } oggpack_buffer;
  104260. /* ogg_page is used to encapsulate the data in one Ogg bitstream page *****/
  104261. typedef struct {
  104262. unsigned char *header;
  104263. long header_len;
  104264. unsigned char *body;
  104265. long body_len;
  104266. } ogg_page;
  104267. ogg_uint32_t ogg_bitreverse(ogg_uint32_t x){
  104268. x= ((x>>16)&0x0000ffffUL) | ((x<<16)&0xffff0000UL);
  104269. x= ((x>> 8)&0x00ff00ffUL) | ((x<< 8)&0xff00ff00UL);
  104270. x= ((x>> 4)&0x0f0f0f0fUL) | ((x<< 4)&0xf0f0f0f0UL);
  104271. x= ((x>> 2)&0x33333333UL) | ((x<< 2)&0xccccccccUL);
  104272. return((x>> 1)&0x55555555UL) | ((x<< 1)&0xaaaaaaaaUL);
  104273. }
  104274. /* ogg_stream_state contains the current encode/decode state of a logical
  104275. Ogg bitstream **********************************************************/
  104276. typedef struct {
  104277. unsigned char *body_data; /* bytes from packet bodies */
  104278. long body_storage; /* storage elements allocated */
  104279. long body_fill; /* elements stored; fill mark */
  104280. long body_returned; /* elements of fill returned */
  104281. int *lacing_vals; /* The values that will go to the segment table */
  104282. ogg_int64_t *granule_vals; /* granulepos values for headers. Not compact
  104283. this way, but it is simple coupled to the
  104284. lacing fifo */
  104285. long lacing_storage;
  104286. long lacing_fill;
  104287. long lacing_packet;
  104288. long lacing_returned;
  104289. unsigned char header[282]; /* working space for header encode */
  104290. int header_fill;
  104291. int e_o_s; /* set when we have buffered the last packet in the
  104292. logical bitstream */
  104293. int b_o_s; /* set after we've written the initial page
  104294. of a logical bitstream */
  104295. long serialno;
  104296. long pageno;
  104297. ogg_int64_t packetno; /* sequence number for decode; the framing
  104298. knows where there's a hole in the data,
  104299. but we need coupling so that the codec
  104300. (which is in a seperate abstraction
  104301. layer) also knows about the gap */
  104302. ogg_int64_t granulepos;
  104303. } ogg_stream_state;
  104304. /* ogg_packet is used to encapsulate the data and metadata belonging
  104305. to a single raw Ogg/Vorbis packet *************************************/
  104306. typedef struct {
  104307. unsigned char *packet;
  104308. long bytes;
  104309. long b_o_s;
  104310. long e_o_s;
  104311. ogg_int64_t granulepos;
  104312. ogg_int64_t packetno; /* sequence number for decode; the framing
  104313. knows where there's a hole in the data,
  104314. but we need coupling so that the codec
  104315. (which is in a seperate abstraction
  104316. layer) also knows about the gap */
  104317. } ogg_packet;
  104318. typedef struct {
  104319. unsigned char *data;
  104320. int storage;
  104321. int fill;
  104322. int returned;
  104323. int unsynced;
  104324. int headerbytes;
  104325. int bodybytes;
  104326. } ogg_sync_state;
  104327. /* Ogg BITSTREAM PRIMITIVES: bitstream ************************/
  104328. extern void oggpack_writeinit(oggpack_buffer *b);
  104329. extern void oggpack_writetrunc(oggpack_buffer *b,long bits);
  104330. extern void oggpack_writealign(oggpack_buffer *b);
  104331. extern void oggpack_writecopy(oggpack_buffer *b,void *source,long bits);
  104332. extern void oggpack_reset(oggpack_buffer *b);
  104333. extern void oggpack_writeclear(oggpack_buffer *b);
  104334. extern void oggpack_readinit(oggpack_buffer *b,unsigned char *buf,int bytes);
  104335. extern void oggpack_write(oggpack_buffer *b,unsigned long value,int bits);
  104336. extern long oggpack_look(oggpack_buffer *b,int bits);
  104337. extern long oggpack_look1(oggpack_buffer *b);
  104338. extern void oggpack_adv(oggpack_buffer *b,int bits);
  104339. extern void oggpack_adv1(oggpack_buffer *b);
  104340. extern long oggpack_read(oggpack_buffer *b,int bits);
  104341. extern long oggpack_read1(oggpack_buffer *b);
  104342. extern long oggpack_bytes(oggpack_buffer *b);
  104343. extern long oggpack_bits(oggpack_buffer *b);
  104344. extern unsigned char *oggpack_get_buffer(oggpack_buffer *b);
  104345. extern void oggpackB_writeinit(oggpack_buffer *b);
  104346. extern void oggpackB_writetrunc(oggpack_buffer *b,long bits);
  104347. extern void oggpackB_writealign(oggpack_buffer *b);
  104348. extern void oggpackB_writecopy(oggpack_buffer *b,void *source,long bits);
  104349. extern void oggpackB_reset(oggpack_buffer *b);
  104350. extern void oggpackB_writeclear(oggpack_buffer *b);
  104351. extern void oggpackB_readinit(oggpack_buffer *b,unsigned char *buf,int bytes);
  104352. extern void oggpackB_write(oggpack_buffer *b,unsigned long value,int bits);
  104353. extern long oggpackB_look(oggpack_buffer *b,int bits);
  104354. extern long oggpackB_look1(oggpack_buffer *b);
  104355. extern void oggpackB_adv(oggpack_buffer *b,int bits);
  104356. extern void oggpackB_adv1(oggpack_buffer *b);
  104357. extern long oggpackB_read(oggpack_buffer *b,int bits);
  104358. extern long oggpackB_read1(oggpack_buffer *b);
  104359. extern long oggpackB_bytes(oggpack_buffer *b);
  104360. extern long oggpackB_bits(oggpack_buffer *b);
  104361. extern unsigned char *oggpackB_get_buffer(oggpack_buffer *b);
  104362. /* Ogg BITSTREAM PRIMITIVES: encoding **************************/
  104363. extern int ogg_stream_packetin(ogg_stream_state *os, ogg_packet *op);
  104364. extern int ogg_stream_pageout(ogg_stream_state *os, ogg_page *og);
  104365. extern int ogg_stream_flush(ogg_stream_state *os, ogg_page *og);
  104366. /* Ogg BITSTREAM PRIMITIVES: decoding **************************/
  104367. extern int ogg_sync_init(ogg_sync_state *oy);
  104368. extern int ogg_sync_clear(ogg_sync_state *oy);
  104369. extern int ogg_sync_reset(ogg_sync_state *oy);
  104370. extern int ogg_sync_destroy(ogg_sync_state *oy);
  104371. extern char *ogg_sync_buffer(ogg_sync_state *oy, long size);
  104372. extern int ogg_sync_wrote(ogg_sync_state *oy, long bytes);
  104373. extern long ogg_sync_pageseek(ogg_sync_state *oy,ogg_page *og);
  104374. extern int ogg_sync_pageout(ogg_sync_state *oy, ogg_page *og);
  104375. extern int ogg_stream_pagein(ogg_stream_state *os, ogg_page *og);
  104376. extern int ogg_stream_packetout(ogg_stream_state *os,ogg_packet *op);
  104377. extern int ogg_stream_packetpeek(ogg_stream_state *os,ogg_packet *op);
  104378. /* Ogg BITSTREAM PRIMITIVES: general ***************************/
  104379. extern int ogg_stream_init(ogg_stream_state *os,int serialno);
  104380. extern int ogg_stream_clear(ogg_stream_state *os);
  104381. extern int ogg_stream_reset(ogg_stream_state *os);
  104382. extern int ogg_stream_reset_serialno(ogg_stream_state *os,int serialno);
  104383. extern int ogg_stream_destroy(ogg_stream_state *os);
  104384. extern int ogg_stream_eos(ogg_stream_state *os);
  104385. extern void ogg_page_checksum_set(ogg_page *og);
  104386. extern int ogg_page_version(ogg_page *og);
  104387. extern int ogg_page_continued(ogg_page *og);
  104388. extern int ogg_page_bos(ogg_page *og);
  104389. extern int ogg_page_eos(ogg_page *og);
  104390. extern ogg_int64_t ogg_page_granulepos(ogg_page *og);
  104391. extern int ogg_page_serialno(ogg_page *og);
  104392. extern long ogg_page_pageno(ogg_page *og);
  104393. extern int ogg_page_packets(ogg_page *og);
  104394. extern void ogg_packet_clear(ogg_packet *op);
  104395. #ifdef __cplusplus
  104396. }
  104397. #endif
  104398. #endif /* _OGG_H */
  104399. /*** End of inlined file: ogg.h ***/
  104400. typedef struct vorbis_info{
  104401. int version;
  104402. int channels;
  104403. long rate;
  104404. /* The below bitrate declarations are *hints*.
  104405. Combinations of the three values carry the following implications:
  104406. all three set to the same value:
  104407. implies a fixed rate bitstream
  104408. only nominal set:
  104409. implies a VBR stream that averages the nominal bitrate. No hard
  104410. upper/lower limit
  104411. upper and or lower set:
  104412. implies a VBR bitstream that obeys the bitrate limits. nominal
  104413. may also be set to give a nominal rate.
  104414. none set:
  104415. the coder does not care to speculate.
  104416. */
  104417. long bitrate_upper;
  104418. long bitrate_nominal;
  104419. long bitrate_lower;
  104420. long bitrate_window;
  104421. void *codec_setup;
  104422. } vorbis_info;
  104423. /* vorbis_dsp_state buffers the current vorbis audio
  104424. analysis/synthesis state. The DSP state belongs to a specific
  104425. logical bitstream ****************************************************/
  104426. typedef struct vorbis_dsp_state{
  104427. int analysisp;
  104428. vorbis_info *vi;
  104429. float **pcm;
  104430. float **pcmret;
  104431. int pcm_storage;
  104432. int pcm_current;
  104433. int pcm_returned;
  104434. int preextrapolate;
  104435. int eofflag;
  104436. long lW;
  104437. long W;
  104438. long nW;
  104439. long centerW;
  104440. ogg_int64_t granulepos;
  104441. ogg_int64_t sequence;
  104442. ogg_int64_t glue_bits;
  104443. ogg_int64_t time_bits;
  104444. ogg_int64_t floor_bits;
  104445. ogg_int64_t res_bits;
  104446. void *backend_state;
  104447. } vorbis_dsp_state;
  104448. typedef struct vorbis_block{
  104449. /* necessary stream state for linking to the framing abstraction */
  104450. float **pcm; /* this is a pointer into local storage */
  104451. oggpack_buffer opb;
  104452. long lW;
  104453. long W;
  104454. long nW;
  104455. int pcmend;
  104456. int mode;
  104457. int eofflag;
  104458. ogg_int64_t granulepos;
  104459. ogg_int64_t sequence;
  104460. vorbis_dsp_state *vd; /* For read-only access of configuration */
  104461. /* local storage to avoid remallocing; it's up to the mapping to
  104462. structure it */
  104463. void *localstore;
  104464. long localtop;
  104465. long localalloc;
  104466. long totaluse;
  104467. struct alloc_chain *reap;
  104468. /* bitmetrics for the frame */
  104469. long glue_bits;
  104470. long time_bits;
  104471. long floor_bits;
  104472. long res_bits;
  104473. void *internal;
  104474. } vorbis_block;
  104475. /* vorbis_block is a single block of data to be processed as part of
  104476. the analysis/synthesis stream; it belongs to a specific logical
  104477. bitstream, but is independant from other vorbis_blocks belonging to
  104478. that logical bitstream. *************************************************/
  104479. struct alloc_chain{
  104480. void *ptr;
  104481. struct alloc_chain *next;
  104482. };
  104483. /* vorbis_info contains all the setup information specific to the
  104484. specific compression/decompression mode in progress (eg,
  104485. psychoacoustic settings, channel setup, options, codebook
  104486. etc). vorbis_info and substructures are in backends.h.
  104487. *********************************************************************/
  104488. /* the comments are not part of vorbis_info so that vorbis_info can be
  104489. static storage */
  104490. typedef struct vorbis_comment{
  104491. /* unlimited user comment fields. libvorbis writes 'libvorbis'
  104492. whatever vendor is set to in encode */
  104493. char **user_comments;
  104494. int *comment_lengths;
  104495. int comments;
  104496. char *vendor;
  104497. } vorbis_comment;
  104498. /* libvorbis encodes in two abstraction layers; first we perform DSP
  104499. and produce a packet (see docs/analysis.txt). The packet is then
  104500. coded into a framed OggSquish bitstream by the second layer (see
  104501. docs/framing.txt). Decode is the reverse process; we sync/frame
  104502. the bitstream and extract individual packets, then decode the
  104503. packet back into PCM audio.
  104504. The extra framing/packetizing is used in streaming formats, such as
  104505. files. Over the net (such as with UDP), the framing and
  104506. packetization aren't necessary as they're provided by the transport
  104507. and the streaming layer is not used */
  104508. /* Vorbis PRIMITIVES: general ***************************************/
  104509. extern void vorbis_info_init(vorbis_info *vi);
  104510. extern void vorbis_info_clear(vorbis_info *vi);
  104511. extern int vorbis_info_blocksize(vorbis_info *vi,int zo);
  104512. extern void vorbis_comment_init(vorbis_comment *vc);
  104513. extern void vorbis_comment_add(vorbis_comment *vc, char *comment);
  104514. extern void vorbis_comment_add_tag(vorbis_comment *vc,
  104515. const char *tag, char *contents);
  104516. extern char *vorbis_comment_query(vorbis_comment *vc, char *tag, int count);
  104517. extern int vorbis_comment_query_count(vorbis_comment *vc, char *tag);
  104518. extern void vorbis_comment_clear(vorbis_comment *vc);
  104519. extern int vorbis_block_init(vorbis_dsp_state *v, vorbis_block *vb);
  104520. extern int vorbis_block_clear(vorbis_block *vb);
  104521. extern void vorbis_dsp_clear(vorbis_dsp_state *v);
  104522. extern double vorbis_granule_time(vorbis_dsp_state *v,
  104523. ogg_int64_t granulepos);
  104524. /* Vorbis PRIMITIVES: analysis/DSP layer ****************************/
  104525. extern int vorbis_analysis_init(vorbis_dsp_state *v,vorbis_info *vi);
  104526. extern int vorbis_commentheader_out(vorbis_comment *vc, ogg_packet *op);
  104527. extern int vorbis_analysis_headerout(vorbis_dsp_state *v,
  104528. vorbis_comment *vc,
  104529. ogg_packet *op,
  104530. ogg_packet *op_comm,
  104531. ogg_packet *op_code);
  104532. extern float **vorbis_analysis_buffer(vorbis_dsp_state *v,int vals);
  104533. extern int vorbis_analysis_wrote(vorbis_dsp_state *v,int vals);
  104534. extern int vorbis_analysis_blockout(vorbis_dsp_state *v,vorbis_block *vb);
  104535. extern int vorbis_analysis(vorbis_block *vb,ogg_packet *op);
  104536. extern int vorbis_bitrate_addblock(vorbis_block *vb);
  104537. extern int vorbis_bitrate_flushpacket(vorbis_dsp_state *vd,
  104538. ogg_packet *op);
  104539. /* Vorbis PRIMITIVES: synthesis layer *******************************/
  104540. extern int vorbis_synthesis_headerin(vorbis_info *vi,vorbis_comment *vc,
  104541. ogg_packet *op);
  104542. extern int vorbis_synthesis_init(vorbis_dsp_state *v,vorbis_info *vi);
  104543. extern int vorbis_synthesis_restart(vorbis_dsp_state *v);
  104544. extern int vorbis_synthesis(vorbis_block *vb,ogg_packet *op);
  104545. extern int vorbis_synthesis_trackonly(vorbis_block *vb,ogg_packet *op);
  104546. extern int vorbis_synthesis_blockin(vorbis_dsp_state *v,vorbis_block *vb);
  104547. extern int vorbis_synthesis_pcmout(vorbis_dsp_state *v,float ***pcm);
  104548. extern int vorbis_synthesis_lapout(vorbis_dsp_state *v,float ***pcm);
  104549. extern int vorbis_synthesis_read(vorbis_dsp_state *v,int samples);
  104550. extern long vorbis_packet_blocksize(vorbis_info *vi,ogg_packet *op);
  104551. extern int vorbis_synthesis_halfrate(vorbis_info *v,int flag);
  104552. extern int vorbis_synthesis_halfrate_p(vorbis_info *v);
  104553. /* Vorbis ERRORS and return codes ***********************************/
  104554. #define OV_FALSE -1
  104555. #define OV_EOF -2
  104556. #define OV_HOLE -3
  104557. #define OV_EREAD -128
  104558. #define OV_EFAULT -129
  104559. #define OV_EIMPL -130
  104560. #define OV_EINVAL -131
  104561. #define OV_ENOTVORBIS -132
  104562. #define OV_EBADHEADER -133
  104563. #define OV_EVERSION -134
  104564. #define OV_ENOTAUDIO -135
  104565. #define OV_EBADPACKET -136
  104566. #define OV_EBADLINK -137
  104567. #define OV_ENOSEEK -138
  104568. #ifdef __cplusplus
  104569. }
  104570. #endif /* __cplusplus */
  104571. #endif
  104572. /*** End of inlined file: codec.h ***/
  104573. extern int vorbis_encode_init(vorbis_info *vi,
  104574. long channels,
  104575. long rate,
  104576. long max_bitrate,
  104577. long nominal_bitrate,
  104578. long min_bitrate);
  104579. extern int vorbis_encode_setup_managed(vorbis_info *vi,
  104580. long channels,
  104581. long rate,
  104582. long max_bitrate,
  104583. long nominal_bitrate,
  104584. long min_bitrate);
  104585. extern int vorbis_encode_setup_vbr(vorbis_info *vi,
  104586. long channels,
  104587. long rate,
  104588. float quality /* quality level from 0. (lo) to 1. (hi) */
  104589. );
  104590. extern int vorbis_encode_init_vbr(vorbis_info *vi,
  104591. long channels,
  104592. long rate,
  104593. float base_quality /* quality level from 0. (lo) to 1. (hi) */
  104594. );
  104595. extern int vorbis_encode_setup_init(vorbis_info *vi);
  104596. extern int vorbis_encode_ctl(vorbis_info *vi,int number,void *arg);
  104597. /* deprecated rate management supported only for compatability */
  104598. #define OV_ECTL_RATEMANAGE_GET 0x10
  104599. #define OV_ECTL_RATEMANAGE_SET 0x11
  104600. #define OV_ECTL_RATEMANAGE_AVG 0x12
  104601. #define OV_ECTL_RATEMANAGE_HARD 0x13
  104602. struct ovectl_ratemanage_arg {
  104603. int management_active;
  104604. long bitrate_hard_min;
  104605. long bitrate_hard_max;
  104606. double bitrate_hard_window;
  104607. long bitrate_av_lo;
  104608. long bitrate_av_hi;
  104609. double bitrate_av_window;
  104610. double bitrate_av_window_center;
  104611. };
  104612. /* new rate setup */
  104613. #define OV_ECTL_RATEMANAGE2_GET 0x14
  104614. #define OV_ECTL_RATEMANAGE2_SET 0x15
  104615. struct ovectl_ratemanage2_arg {
  104616. int management_active;
  104617. long bitrate_limit_min_kbps;
  104618. long bitrate_limit_max_kbps;
  104619. long bitrate_limit_reservoir_bits;
  104620. double bitrate_limit_reservoir_bias;
  104621. long bitrate_average_kbps;
  104622. double bitrate_average_damping;
  104623. };
  104624. #define OV_ECTL_LOWPASS_GET 0x20
  104625. #define OV_ECTL_LOWPASS_SET 0x21
  104626. #define OV_ECTL_IBLOCK_GET 0x30
  104627. #define OV_ECTL_IBLOCK_SET 0x31
  104628. #ifdef __cplusplus
  104629. }
  104630. #endif /* __cplusplus */
  104631. #endif
  104632. /*** End of inlined file: vorbisenc.h ***/
  104633. /*** Start of inlined file: vorbisfile.h ***/
  104634. #ifndef _OV_FILE_H_
  104635. #define _OV_FILE_H_
  104636. #ifdef __cplusplus
  104637. extern "C"
  104638. {
  104639. #endif /* __cplusplus */
  104640. #include <stdio.h>
  104641. /* The function prototypes for the callbacks are basically the same as for
  104642. * the stdio functions fread, fseek, fclose, ftell.
  104643. * The one difference is that the FILE * arguments have been replaced with
  104644. * a void * - this is to be used as a pointer to whatever internal data these
  104645. * functions might need. In the stdio case, it's just a FILE * cast to a void *
  104646. *
  104647. * If you use other functions, check the docs for these functions and return
  104648. * the right values. For seek_func(), you *MUST* return -1 if the stream is
  104649. * unseekable
  104650. */
  104651. typedef struct {
  104652. size_t (*read_func) (void *ptr, size_t size, size_t nmemb, void *datasource);
  104653. int (*seek_func) (void *datasource, ogg_int64_t offset, int whence);
  104654. int (*close_func) (void *datasource);
  104655. long (*tell_func) (void *datasource);
  104656. } ov_callbacks;
  104657. #define NOTOPEN 0
  104658. #define PARTOPEN 1
  104659. #define OPENED 2
  104660. #define STREAMSET 3
  104661. #define INITSET 4
  104662. typedef struct OggVorbis_File {
  104663. void *datasource; /* Pointer to a FILE *, etc. */
  104664. int seekable;
  104665. ogg_int64_t offset;
  104666. ogg_int64_t end;
  104667. ogg_sync_state oy;
  104668. /* If the FILE handle isn't seekable (eg, a pipe), only the current
  104669. stream appears */
  104670. int links;
  104671. ogg_int64_t *offsets;
  104672. ogg_int64_t *dataoffsets;
  104673. long *serialnos;
  104674. ogg_int64_t *pcmlengths; /* overloaded to maintain binary
  104675. compatability; x2 size, stores both
  104676. beginning and end values */
  104677. vorbis_info *vi;
  104678. vorbis_comment *vc;
  104679. /* Decoding working state local storage */
  104680. ogg_int64_t pcm_offset;
  104681. int ready_state;
  104682. long current_serialno;
  104683. int current_link;
  104684. double bittrack;
  104685. double samptrack;
  104686. ogg_stream_state os; /* take physical pages, weld into a logical
  104687. stream of packets */
  104688. vorbis_dsp_state vd; /* central working state for the packet->PCM decoder */
  104689. vorbis_block vb; /* local working space for packet->PCM decode */
  104690. ov_callbacks callbacks;
  104691. } OggVorbis_File;
  104692. extern int ov_clear(OggVorbis_File *vf);
  104693. extern int ov_open(FILE *f,OggVorbis_File *vf,char *initial,long ibytes);
  104694. extern int ov_open_callbacks(void *datasource, OggVorbis_File *vf,
  104695. char *initial, long ibytes, ov_callbacks callbacks);
  104696. extern int ov_test(FILE *f,OggVorbis_File *vf,char *initial,long ibytes);
  104697. extern int ov_test_callbacks(void *datasource, OggVorbis_File *vf,
  104698. char *initial, long ibytes, ov_callbacks callbacks);
  104699. extern int ov_test_open(OggVorbis_File *vf);
  104700. extern long ov_bitrate(OggVorbis_File *vf,int i);
  104701. extern long ov_bitrate_instant(OggVorbis_File *vf);
  104702. extern long ov_streams(OggVorbis_File *vf);
  104703. extern long ov_seekable(OggVorbis_File *vf);
  104704. extern long ov_serialnumber(OggVorbis_File *vf,int i);
  104705. extern ogg_int64_t ov_raw_total(OggVorbis_File *vf,int i);
  104706. extern ogg_int64_t ov_pcm_total(OggVorbis_File *vf,int i);
  104707. extern double ov_time_total(OggVorbis_File *vf,int i);
  104708. extern int ov_raw_seek(OggVorbis_File *vf,ogg_int64_t pos);
  104709. extern int ov_pcm_seek(OggVorbis_File *vf,ogg_int64_t pos);
  104710. extern int ov_pcm_seek_page(OggVorbis_File *vf,ogg_int64_t pos);
  104711. extern int ov_time_seek(OggVorbis_File *vf,double pos);
  104712. extern int ov_time_seek_page(OggVorbis_File *vf,double pos);
  104713. extern int ov_raw_seek_lap(OggVorbis_File *vf,ogg_int64_t pos);
  104714. extern int ov_pcm_seek_lap(OggVorbis_File *vf,ogg_int64_t pos);
  104715. extern int ov_pcm_seek_page_lap(OggVorbis_File *vf,ogg_int64_t pos);
  104716. extern int ov_time_seek_lap(OggVorbis_File *vf,double pos);
  104717. extern int ov_time_seek_page_lap(OggVorbis_File *vf,double pos);
  104718. extern ogg_int64_t ov_raw_tell(OggVorbis_File *vf);
  104719. extern ogg_int64_t ov_pcm_tell(OggVorbis_File *vf);
  104720. extern double ov_time_tell(OggVorbis_File *vf);
  104721. extern vorbis_info *ov_info(OggVorbis_File *vf,int link);
  104722. extern vorbis_comment *ov_comment(OggVorbis_File *vf,int link);
  104723. extern long ov_read_float(OggVorbis_File *vf,float ***pcm_channels,int samples,
  104724. int *bitstream);
  104725. extern long ov_read(OggVorbis_File *vf,char *buffer,int length,
  104726. int bigendianp,int word,int sgned,int *bitstream);
  104727. extern int ov_crosslap(OggVorbis_File *vf1,OggVorbis_File *vf2);
  104728. extern int ov_halfrate(OggVorbis_File *vf,int flag);
  104729. extern int ov_halfrate_p(OggVorbis_File *vf);
  104730. #ifdef __cplusplus
  104731. }
  104732. #endif /* __cplusplus */
  104733. #endif
  104734. /*** End of inlined file: vorbisfile.h ***/
  104735. /*** Start of inlined file: bitwise.c ***/
  104736. /* We're 'LSb' endian; if we write a word but read individual bits,
  104737. then we'll read the lsb first */
  104738. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  104739. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  104740. // tasks..
  104741. #if JUCE_MSVC
  104742. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  104743. #endif
  104744. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  104745. #if JUCE_USE_OGGVORBIS
  104746. #include <string.h>
  104747. #include <stdlib.h>
  104748. #define BUFFER_INCREMENT 256
  104749. static const unsigned long mask[]=
  104750. {0x00000000,0x00000001,0x00000003,0x00000007,0x0000000f,
  104751. 0x0000001f,0x0000003f,0x0000007f,0x000000ff,0x000001ff,
  104752. 0x000003ff,0x000007ff,0x00000fff,0x00001fff,0x00003fff,
  104753. 0x00007fff,0x0000ffff,0x0001ffff,0x0003ffff,0x0007ffff,
  104754. 0x000fffff,0x001fffff,0x003fffff,0x007fffff,0x00ffffff,
  104755. 0x01ffffff,0x03ffffff,0x07ffffff,0x0fffffff,0x1fffffff,
  104756. 0x3fffffff,0x7fffffff,0xffffffff };
  104757. static const unsigned int mask8B[]=
  104758. {0x00,0x80,0xc0,0xe0,0xf0,0xf8,0xfc,0xfe,0xff};
  104759. void oggpack_writeinit(oggpack_buffer *b){
  104760. memset(b,0,sizeof(*b));
  104761. b->ptr=b->buffer=(unsigned char*) _ogg_malloc(BUFFER_INCREMENT);
  104762. b->buffer[0]='\0';
  104763. b->storage=BUFFER_INCREMENT;
  104764. }
  104765. void oggpackB_writeinit(oggpack_buffer *b){
  104766. oggpack_writeinit(b);
  104767. }
  104768. void oggpack_writetrunc(oggpack_buffer *b,long bits){
  104769. long bytes=bits>>3;
  104770. bits-=bytes*8;
  104771. b->ptr=b->buffer+bytes;
  104772. b->endbit=bits;
  104773. b->endbyte=bytes;
  104774. *b->ptr&=mask[bits];
  104775. }
  104776. void oggpackB_writetrunc(oggpack_buffer *b,long bits){
  104777. long bytes=bits>>3;
  104778. bits-=bytes*8;
  104779. b->ptr=b->buffer+bytes;
  104780. b->endbit=bits;
  104781. b->endbyte=bytes;
  104782. *b->ptr&=mask8B[bits];
  104783. }
  104784. /* Takes only up to 32 bits. */
  104785. void oggpack_write(oggpack_buffer *b,unsigned long value,int bits){
  104786. if(b->endbyte+4>=b->storage){
  104787. b->buffer=(unsigned char*) _ogg_realloc(b->buffer,b->storage+BUFFER_INCREMENT);
  104788. b->storage+=BUFFER_INCREMENT;
  104789. b->ptr=b->buffer+b->endbyte;
  104790. }
  104791. value&=mask[bits];
  104792. bits+=b->endbit;
  104793. b->ptr[0]|=value<<b->endbit;
  104794. if(bits>=8){
  104795. b->ptr[1]=(unsigned char)(value>>(8-b->endbit));
  104796. if(bits>=16){
  104797. b->ptr[2]=(unsigned char)(value>>(16-b->endbit));
  104798. if(bits>=24){
  104799. b->ptr[3]=(unsigned char)(value>>(24-b->endbit));
  104800. if(bits>=32){
  104801. if(b->endbit)
  104802. b->ptr[4]=(unsigned char)(value>>(32-b->endbit));
  104803. else
  104804. b->ptr[4]=0;
  104805. }
  104806. }
  104807. }
  104808. }
  104809. b->endbyte+=bits/8;
  104810. b->ptr+=bits/8;
  104811. b->endbit=bits&7;
  104812. }
  104813. /* Takes only up to 32 bits. */
  104814. void oggpackB_write(oggpack_buffer *b,unsigned long value,int bits){
  104815. if(b->endbyte+4>=b->storage){
  104816. b->buffer=(unsigned char*) _ogg_realloc(b->buffer,b->storage+BUFFER_INCREMENT);
  104817. b->storage+=BUFFER_INCREMENT;
  104818. b->ptr=b->buffer+b->endbyte;
  104819. }
  104820. value=(value&mask[bits])<<(32-bits);
  104821. bits+=b->endbit;
  104822. b->ptr[0]|=value>>(24+b->endbit);
  104823. if(bits>=8){
  104824. b->ptr[1]=(unsigned char)(value>>(16+b->endbit));
  104825. if(bits>=16){
  104826. b->ptr[2]=(unsigned char)(value>>(8+b->endbit));
  104827. if(bits>=24){
  104828. b->ptr[3]=(unsigned char)(value>>(b->endbit));
  104829. if(bits>=32){
  104830. if(b->endbit)
  104831. b->ptr[4]=(unsigned char)(value<<(8-b->endbit));
  104832. else
  104833. b->ptr[4]=0;
  104834. }
  104835. }
  104836. }
  104837. }
  104838. b->endbyte+=bits/8;
  104839. b->ptr+=bits/8;
  104840. b->endbit=bits&7;
  104841. }
  104842. void oggpack_writealign(oggpack_buffer *b){
  104843. int bits=8-b->endbit;
  104844. if(bits<8)
  104845. oggpack_write(b,0,bits);
  104846. }
  104847. void oggpackB_writealign(oggpack_buffer *b){
  104848. int bits=8-b->endbit;
  104849. if(bits<8)
  104850. oggpackB_write(b,0,bits);
  104851. }
  104852. static void oggpack_writecopy_helper(oggpack_buffer *b,
  104853. void *source,
  104854. long bits,
  104855. void (*w)(oggpack_buffer *,
  104856. unsigned long,
  104857. int),
  104858. int msb){
  104859. unsigned char *ptr=(unsigned char *)source;
  104860. long bytes=bits/8;
  104861. bits-=bytes*8;
  104862. if(b->endbit){
  104863. int i;
  104864. /* unaligned copy. Do it the hard way. */
  104865. for(i=0;i<bytes;i++)
  104866. w(b,(unsigned long)(ptr[i]),8);
  104867. }else{
  104868. /* aligned block copy */
  104869. if(b->endbyte+bytes+1>=b->storage){
  104870. b->storage=b->endbyte+bytes+BUFFER_INCREMENT;
  104871. b->buffer=(unsigned char*) _ogg_realloc(b->buffer,b->storage);
  104872. b->ptr=b->buffer+b->endbyte;
  104873. }
  104874. memmove(b->ptr,source,bytes);
  104875. b->ptr+=bytes;
  104876. b->endbyte+=bytes;
  104877. *b->ptr=0;
  104878. }
  104879. if(bits){
  104880. if(msb)
  104881. w(b,(unsigned long)(ptr[bytes]>>(8-bits)),bits);
  104882. else
  104883. w(b,(unsigned long)(ptr[bytes]),bits);
  104884. }
  104885. }
  104886. void oggpack_writecopy(oggpack_buffer *b,void *source,long bits){
  104887. oggpack_writecopy_helper(b,source,bits,oggpack_write,0);
  104888. }
  104889. void oggpackB_writecopy(oggpack_buffer *b,void *source,long bits){
  104890. oggpack_writecopy_helper(b,source,bits,oggpackB_write,1);
  104891. }
  104892. void oggpack_reset(oggpack_buffer *b){
  104893. b->ptr=b->buffer;
  104894. b->buffer[0]=0;
  104895. b->endbit=b->endbyte=0;
  104896. }
  104897. void oggpackB_reset(oggpack_buffer *b){
  104898. oggpack_reset(b);
  104899. }
  104900. void oggpack_writeclear(oggpack_buffer *b){
  104901. _ogg_free(b->buffer);
  104902. memset(b,0,sizeof(*b));
  104903. }
  104904. void oggpackB_writeclear(oggpack_buffer *b){
  104905. oggpack_writeclear(b);
  104906. }
  104907. void oggpack_readinit(oggpack_buffer *b,unsigned char *buf,int bytes){
  104908. memset(b,0,sizeof(*b));
  104909. b->buffer=b->ptr=buf;
  104910. b->storage=bytes;
  104911. }
  104912. void oggpackB_readinit(oggpack_buffer *b,unsigned char *buf,int bytes){
  104913. oggpack_readinit(b,buf,bytes);
  104914. }
  104915. /* Read in bits without advancing the bitptr; bits <= 32 */
  104916. long oggpack_look(oggpack_buffer *b,int bits){
  104917. unsigned long ret;
  104918. unsigned long m=mask[bits];
  104919. bits+=b->endbit;
  104920. if(b->endbyte+4>=b->storage){
  104921. /* not the main path */
  104922. if(b->endbyte*8+bits>b->storage*8)return(-1);
  104923. }
  104924. ret=b->ptr[0]>>b->endbit;
  104925. if(bits>8){
  104926. ret|=b->ptr[1]<<(8-b->endbit);
  104927. if(bits>16){
  104928. ret|=b->ptr[2]<<(16-b->endbit);
  104929. if(bits>24){
  104930. ret|=b->ptr[3]<<(24-b->endbit);
  104931. if(bits>32 && b->endbit)
  104932. ret|=b->ptr[4]<<(32-b->endbit);
  104933. }
  104934. }
  104935. }
  104936. return(m&ret);
  104937. }
  104938. /* Read in bits without advancing the bitptr; bits <= 32 */
  104939. long oggpackB_look(oggpack_buffer *b,int bits){
  104940. unsigned long ret;
  104941. int m=32-bits;
  104942. bits+=b->endbit;
  104943. if(b->endbyte+4>=b->storage){
  104944. /* not the main path */
  104945. if(b->endbyte*8+bits>b->storage*8)return(-1);
  104946. }
  104947. ret=b->ptr[0]<<(24+b->endbit);
  104948. if(bits>8){
  104949. ret|=b->ptr[1]<<(16+b->endbit);
  104950. if(bits>16){
  104951. ret|=b->ptr[2]<<(8+b->endbit);
  104952. if(bits>24){
  104953. ret|=b->ptr[3]<<(b->endbit);
  104954. if(bits>32 && b->endbit)
  104955. ret|=b->ptr[4]>>(8-b->endbit);
  104956. }
  104957. }
  104958. }
  104959. return ((ret&0xffffffff)>>(m>>1))>>((m+1)>>1);
  104960. }
  104961. long oggpack_look1(oggpack_buffer *b){
  104962. if(b->endbyte>=b->storage)return(-1);
  104963. return((b->ptr[0]>>b->endbit)&1);
  104964. }
  104965. long oggpackB_look1(oggpack_buffer *b){
  104966. if(b->endbyte>=b->storage)return(-1);
  104967. return((b->ptr[0]>>(7-b->endbit))&1);
  104968. }
  104969. void oggpack_adv(oggpack_buffer *b,int bits){
  104970. bits+=b->endbit;
  104971. b->ptr+=bits/8;
  104972. b->endbyte+=bits/8;
  104973. b->endbit=bits&7;
  104974. }
  104975. void oggpackB_adv(oggpack_buffer *b,int bits){
  104976. oggpack_adv(b,bits);
  104977. }
  104978. void oggpack_adv1(oggpack_buffer *b){
  104979. if(++(b->endbit)>7){
  104980. b->endbit=0;
  104981. b->ptr++;
  104982. b->endbyte++;
  104983. }
  104984. }
  104985. void oggpackB_adv1(oggpack_buffer *b){
  104986. oggpack_adv1(b);
  104987. }
  104988. /* bits <= 32 */
  104989. long oggpack_read(oggpack_buffer *b,int bits){
  104990. long ret;
  104991. unsigned long m=mask[bits];
  104992. bits+=b->endbit;
  104993. if(b->endbyte+4>=b->storage){
  104994. /* not the main path */
  104995. ret=-1L;
  104996. if(b->endbyte*8+bits>b->storage*8)goto overflow;
  104997. }
  104998. ret=b->ptr[0]>>b->endbit;
  104999. if(bits>8){
  105000. ret|=b->ptr[1]<<(8-b->endbit);
  105001. if(bits>16){
  105002. ret|=b->ptr[2]<<(16-b->endbit);
  105003. if(bits>24){
  105004. ret|=b->ptr[3]<<(24-b->endbit);
  105005. if(bits>32 && b->endbit){
  105006. ret|=b->ptr[4]<<(32-b->endbit);
  105007. }
  105008. }
  105009. }
  105010. }
  105011. ret&=m;
  105012. overflow:
  105013. b->ptr+=bits/8;
  105014. b->endbyte+=bits/8;
  105015. b->endbit=bits&7;
  105016. return(ret);
  105017. }
  105018. /* bits <= 32 */
  105019. long oggpackB_read(oggpack_buffer *b,int bits){
  105020. long ret;
  105021. long m=32-bits;
  105022. bits+=b->endbit;
  105023. if(b->endbyte+4>=b->storage){
  105024. /* not the main path */
  105025. ret=-1L;
  105026. if(b->endbyte*8+bits>b->storage*8)goto overflow;
  105027. }
  105028. ret=b->ptr[0]<<(24+b->endbit);
  105029. if(bits>8){
  105030. ret|=b->ptr[1]<<(16+b->endbit);
  105031. if(bits>16){
  105032. ret|=b->ptr[2]<<(8+b->endbit);
  105033. if(bits>24){
  105034. ret|=b->ptr[3]<<(b->endbit);
  105035. if(bits>32 && b->endbit)
  105036. ret|=b->ptr[4]>>(8-b->endbit);
  105037. }
  105038. }
  105039. }
  105040. ret=((ret&0xffffffffUL)>>(m>>1))>>((m+1)>>1);
  105041. overflow:
  105042. b->ptr+=bits/8;
  105043. b->endbyte+=bits/8;
  105044. b->endbit=bits&7;
  105045. return(ret);
  105046. }
  105047. long oggpack_read1(oggpack_buffer *b){
  105048. long ret;
  105049. if(b->endbyte>=b->storage){
  105050. /* not the main path */
  105051. ret=-1L;
  105052. goto overflow;
  105053. }
  105054. ret=(b->ptr[0]>>b->endbit)&1;
  105055. overflow:
  105056. b->endbit++;
  105057. if(b->endbit>7){
  105058. b->endbit=0;
  105059. b->ptr++;
  105060. b->endbyte++;
  105061. }
  105062. return(ret);
  105063. }
  105064. long oggpackB_read1(oggpack_buffer *b){
  105065. long ret;
  105066. if(b->endbyte>=b->storage){
  105067. /* not the main path */
  105068. ret=-1L;
  105069. goto overflow;
  105070. }
  105071. ret=(b->ptr[0]>>(7-b->endbit))&1;
  105072. overflow:
  105073. b->endbit++;
  105074. if(b->endbit>7){
  105075. b->endbit=0;
  105076. b->ptr++;
  105077. b->endbyte++;
  105078. }
  105079. return(ret);
  105080. }
  105081. long oggpack_bytes(oggpack_buffer *b){
  105082. return(b->endbyte+(b->endbit+7)/8);
  105083. }
  105084. long oggpack_bits(oggpack_buffer *b){
  105085. return(b->endbyte*8+b->endbit);
  105086. }
  105087. long oggpackB_bytes(oggpack_buffer *b){
  105088. return oggpack_bytes(b);
  105089. }
  105090. long oggpackB_bits(oggpack_buffer *b){
  105091. return oggpack_bits(b);
  105092. }
  105093. unsigned char *oggpack_get_buffer(oggpack_buffer *b){
  105094. return(b->buffer);
  105095. }
  105096. unsigned char *oggpackB_get_buffer(oggpack_buffer *b){
  105097. return oggpack_get_buffer(b);
  105098. }
  105099. /* Self test of the bitwise routines; everything else is based on
  105100. them, so they damned well better be solid. */
  105101. #ifdef _V_SELFTEST
  105102. #include <stdio.h>
  105103. static int ilog(unsigned int v){
  105104. int ret=0;
  105105. while(v){
  105106. ret++;
  105107. v>>=1;
  105108. }
  105109. return(ret);
  105110. }
  105111. oggpack_buffer o;
  105112. oggpack_buffer r;
  105113. void report(char *in){
  105114. fprintf(stderr,"%s",in);
  105115. exit(1);
  105116. }
  105117. void cliptest(unsigned long *b,int vals,int bits,int *comp,int compsize){
  105118. long bytes,i;
  105119. unsigned char *buffer;
  105120. oggpack_reset(&o);
  105121. for(i=0;i<vals;i++)
  105122. oggpack_write(&o,b[i],bits?bits:ilog(b[i]));
  105123. buffer=oggpack_get_buffer(&o);
  105124. bytes=oggpack_bytes(&o);
  105125. if(bytes!=compsize)report("wrong number of bytes!\n");
  105126. for(i=0;i<bytes;i++)if(buffer[i]!=comp[i]){
  105127. for(i=0;i<bytes;i++)fprintf(stderr,"%x %x\n",(int)buffer[i],(int)comp[i]);
  105128. report("wrote incorrect value!\n");
  105129. }
  105130. oggpack_readinit(&r,buffer,bytes);
  105131. for(i=0;i<vals;i++){
  105132. int tbit=bits?bits:ilog(b[i]);
  105133. if(oggpack_look(&r,tbit)==-1)
  105134. report("out of data!\n");
  105135. if(oggpack_look(&r,tbit)!=(b[i]&mask[tbit]))
  105136. report("looked at incorrect value!\n");
  105137. if(tbit==1)
  105138. if(oggpack_look1(&r)!=(b[i]&mask[tbit]))
  105139. report("looked at single bit incorrect value!\n");
  105140. if(tbit==1){
  105141. if(oggpack_read1(&r)!=(b[i]&mask[tbit]))
  105142. report("read incorrect single bit value!\n");
  105143. }else{
  105144. if(oggpack_read(&r,tbit)!=(b[i]&mask[tbit]))
  105145. report("read incorrect value!\n");
  105146. }
  105147. }
  105148. if(oggpack_bytes(&r)!=bytes)report("leftover bytes after read!\n");
  105149. }
  105150. void cliptestB(unsigned long *b,int vals,int bits,int *comp,int compsize){
  105151. long bytes,i;
  105152. unsigned char *buffer;
  105153. oggpackB_reset(&o);
  105154. for(i=0;i<vals;i++)
  105155. oggpackB_write(&o,b[i],bits?bits:ilog(b[i]));
  105156. buffer=oggpackB_get_buffer(&o);
  105157. bytes=oggpackB_bytes(&o);
  105158. if(bytes!=compsize)report("wrong number of bytes!\n");
  105159. for(i=0;i<bytes;i++)if(buffer[i]!=comp[i]){
  105160. for(i=0;i<bytes;i++)fprintf(stderr,"%x %x\n",(int)buffer[i],(int)comp[i]);
  105161. report("wrote incorrect value!\n");
  105162. }
  105163. oggpackB_readinit(&r,buffer,bytes);
  105164. for(i=0;i<vals;i++){
  105165. int tbit=bits?bits:ilog(b[i]);
  105166. if(oggpackB_look(&r,tbit)==-1)
  105167. report("out of data!\n");
  105168. if(oggpackB_look(&r,tbit)!=(b[i]&mask[tbit]))
  105169. report("looked at incorrect value!\n");
  105170. if(tbit==1)
  105171. if(oggpackB_look1(&r)!=(b[i]&mask[tbit]))
  105172. report("looked at single bit incorrect value!\n");
  105173. if(tbit==1){
  105174. if(oggpackB_read1(&r)!=(b[i]&mask[tbit]))
  105175. report("read incorrect single bit value!\n");
  105176. }else{
  105177. if(oggpackB_read(&r,tbit)!=(b[i]&mask[tbit]))
  105178. report("read incorrect value!\n");
  105179. }
  105180. }
  105181. if(oggpackB_bytes(&r)!=bytes)report("leftover bytes after read!\n");
  105182. }
  105183. int main(void){
  105184. unsigned char *buffer;
  105185. long bytes,i;
  105186. static unsigned long testbuffer1[]=
  105187. {18,12,103948,4325,543,76,432,52,3,65,4,56,32,42,34,21,1,23,32,546,456,7,
  105188. 567,56,8,8,55,3,52,342,341,4,265,7,67,86,2199,21,7,1,5,1,4};
  105189. int test1size=43;
  105190. static unsigned long testbuffer2[]=
  105191. {216531625L,1237861823,56732452,131,3212421,12325343,34547562,12313212,
  105192. 1233432,534,5,346435231,14436467,7869299,76326614,167548585,
  105193. 85525151,0,12321,1,349528352};
  105194. int test2size=21;
  105195. static unsigned long testbuffer3[]=
  105196. {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,
  105197. 0,1,30,1,1,1,0,0,1,0,0,0,12,0,11,0,1,0,0,1};
  105198. int test3size=56;
  105199. static unsigned long large[]=
  105200. {2136531625L,2137861823,56732452,131,3212421,12325343,34547562,12313212,
  105201. 1233432,534,5,2146435231,14436467,7869299,76326614,167548585,
  105202. 85525151,0,12321,1,2146528352};
  105203. int onesize=33;
  105204. static int one[33]={146,25,44,151,195,15,153,176,233,131,196,65,85,172,47,40,
  105205. 34,242,223,136,35,222,211,86,171,50,225,135,214,75,172,
  105206. 223,4};
  105207. static int oneB[33]={150,101,131,33,203,15,204,216,105,193,156,65,84,85,222,
  105208. 8,139,145,227,126,34,55,244,171,85,100,39,195,173,18,
  105209. 245,251,128};
  105210. int twosize=6;
  105211. static int two[6]={61,255,255,251,231,29};
  105212. static int twoB[6]={247,63,255,253,249,120};
  105213. int threesize=54;
  105214. static int three[54]={169,2,232,252,91,132,156,36,89,13,123,176,144,32,254,
  105215. 142,224,85,59,121,144,79,124,23,67,90,90,216,79,23,83,
  105216. 58,135,196,61,55,129,183,54,101,100,170,37,127,126,10,
  105217. 100,52,4,14,18,86,77,1};
  105218. static int threeB[54]={206,128,42,153,57,8,183,251,13,89,36,30,32,144,183,
  105219. 130,59,240,121,59,85,223,19,228,180,134,33,107,74,98,
  105220. 233,253,196,135,63,2,110,114,50,155,90,127,37,170,104,
  105221. 200,20,254,4,58,106,176,144,0};
  105222. int foursize=38;
  105223. static int four[38]={18,6,163,252,97,194,104,131,32,1,7,82,137,42,129,11,72,
  105224. 132,60,220,112,8,196,109,64,179,86,9,137,195,208,122,169,
  105225. 28,2,133,0,1};
  105226. static int fourB[38]={36,48,102,83,243,24,52,7,4,35,132,10,145,21,2,93,2,41,
  105227. 1,219,184,16,33,184,54,149,170,132,18,30,29,98,229,67,
  105228. 129,10,4,32};
  105229. int fivesize=45;
  105230. static int five[45]={169,2,126,139,144,172,30,4,80,72,240,59,130,218,73,62,
  105231. 241,24,210,44,4,20,0,248,116,49,135,100,110,130,181,169,
  105232. 84,75,159,2,1,0,132,192,8,0,0,18,22};
  105233. static int fiveB[45]={1,84,145,111,245,100,128,8,56,36,40,71,126,78,213,226,
  105234. 124,105,12,0,133,128,0,162,233,242,67,152,77,205,77,
  105235. 172,150,169,129,79,128,0,6,4,32,0,27,9,0};
  105236. int sixsize=7;
  105237. static int six[7]={17,177,170,242,169,19,148};
  105238. static int sixB[7]={136,141,85,79,149,200,41};
  105239. /* Test read/write together */
  105240. /* Later we test against pregenerated bitstreams */
  105241. oggpack_writeinit(&o);
  105242. fprintf(stderr,"\nSmall preclipped packing (LSb): ");
  105243. cliptest(testbuffer1,test1size,0,one,onesize);
  105244. fprintf(stderr,"ok.");
  105245. fprintf(stderr,"\nNull bit call (LSb): ");
  105246. cliptest(testbuffer3,test3size,0,two,twosize);
  105247. fprintf(stderr,"ok.");
  105248. fprintf(stderr,"\nLarge preclipped packing (LSb): ");
  105249. cliptest(testbuffer2,test2size,0,three,threesize);
  105250. fprintf(stderr,"ok.");
  105251. fprintf(stderr,"\n32 bit preclipped packing (LSb): ");
  105252. oggpack_reset(&o);
  105253. for(i=0;i<test2size;i++)
  105254. oggpack_write(&o,large[i],32);
  105255. buffer=oggpack_get_buffer(&o);
  105256. bytes=oggpack_bytes(&o);
  105257. oggpack_readinit(&r,buffer,bytes);
  105258. for(i=0;i<test2size;i++){
  105259. if(oggpack_look(&r,32)==-1)report("out of data. failed!");
  105260. if(oggpack_look(&r,32)!=large[i]){
  105261. fprintf(stderr,"%ld != %ld (%lx!=%lx):",oggpack_look(&r,32),large[i],
  105262. oggpack_look(&r,32),large[i]);
  105263. report("read incorrect value!\n");
  105264. }
  105265. oggpack_adv(&r,32);
  105266. }
  105267. if(oggpack_bytes(&r)!=bytes)report("leftover bytes after read!\n");
  105268. fprintf(stderr,"ok.");
  105269. fprintf(stderr,"\nSmall unclipped packing (LSb): ");
  105270. cliptest(testbuffer1,test1size,7,four,foursize);
  105271. fprintf(stderr,"ok.");
  105272. fprintf(stderr,"\nLarge unclipped packing (LSb): ");
  105273. cliptest(testbuffer2,test2size,17,five,fivesize);
  105274. fprintf(stderr,"ok.");
  105275. fprintf(stderr,"\nSingle bit unclipped packing (LSb): ");
  105276. cliptest(testbuffer3,test3size,1,six,sixsize);
  105277. fprintf(stderr,"ok.");
  105278. fprintf(stderr,"\nTesting read past end (LSb): ");
  105279. oggpack_readinit(&r,"\0\0\0\0\0\0\0\0",8);
  105280. for(i=0;i<64;i++){
  105281. if(oggpack_read(&r,1)!=0){
  105282. fprintf(stderr,"failed; got -1 prematurely.\n");
  105283. exit(1);
  105284. }
  105285. }
  105286. if(oggpack_look(&r,1)!=-1 ||
  105287. oggpack_read(&r,1)!=-1){
  105288. fprintf(stderr,"failed; read past end without -1.\n");
  105289. exit(1);
  105290. }
  105291. oggpack_readinit(&r,"\0\0\0\0\0\0\0\0",8);
  105292. if(oggpack_read(&r,30)!=0 || oggpack_read(&r,16)!=0){
  105293. fprintf(stderr,"failed 2; got -1 prematurely.\n");
  105294. exit(1);
  105295. }
  105296. if(oggpack_look(&r,18)!=0 ||
  105297. oggpack_look(&r,18)!=0){
  105298. fprintf(stderr,"failed 3; got -1 prematurely.\n");
  105299. exit(1);
  105300. }
  105301. if(oggpack_look(&r,19)!=-1 ||
  105302. oggpack_look(&r,19)!=-1){
  105303. fprintf(stderr,"failed; read past end without -1.\n");
  105304. exit(1);
  105305. }
  105306. if(oggpack_look(&r,32)!=-1 ||
  105307. oggpack_look(&r,32)!=-1){
  105308. fprintf(stderr,"failed; read past end without -1.\n");
  105309. exit(1);
  105310. }
  105311. oggpack_writeclear(&o);
  105312. fprintf(stderr,"ok.\n");
  105313. /********** lazy, cut-n-paste retest with MSb packing ***********/
  105314. /* Test read/write together */
  105315. /* Later we test against pregenerated bitstreams */
  105316. oggpackB_writeinit(&o);
  105317. fprintf(stderr,"\nSmall preclipped packing (MSb): ");
  105318. cliptestB(testbuffer1,test1size,0,oneB,onesize);
  105319. fprintf(stderr,"ok.");
  105320. fprintf(stderr,"\nNull bit call (MSb): ");
  105321. cliptestB(testbuffer3,test3size,0,twoB,twosize);
  105322. fprintf(stderr,"ok.");
  105323. fprintf(stderr,"\nLarge preclipped packing (MSb): ");
  105324. cliptestB(testbuffer2,test2size,0,threeB,threesize);
  105325. fprintf(stderr,"ok.");
  105326. fprintf(stderr,"\n32 bit preclipped packing (MSb): ");
  105327. oggpackB_reset(&o);
  105328. for(i=0;i<test2size;i++)
  105329. oggpackB_write(&o,large[i],32);
  105330. buffer=oggpackB_get_buffer(&o);
  105331. bytes=oggpackB_bytes(&o);
  105332. oggpackB_readinit(&r,buffer,bytes);
  105333. for(i=0;i<test2size;i++){
  105334. if(oggpackB_look(&r,32)==-1)report("out of data. failed!");
  105335. if(oggpackB_look(&r,32)!=large[i]){
  105336. fprintf(stderr,"%ld != %ld (%lx!=%lx):",oggpackB_look(&r,32),large[i],
  105337. oggpackB_look(&r,32),large[i]);
  105338. report("read incorrect value!\n");
  105339. }
  105340. oggpackB_adv(&r,32);
  105341. }
  105342. if(oggpackB_bytes(&r)!=bytes)report("leftover bytes after read!\n");
  105343. fprintf(stderr,"ok.");
  105344. fprintf(stderr,"\nSmall unclipped packing (MSb): ");
  105345. cliptestB(testbuffer1,test1size,7,fourB,foursize);
  105346. fprintf(stderr,"ok.");
  105347. fprintf(stderr,"\nLarge unclipped packing (MSb): ");
  105348. cliptestB(testbuffer2,test2size,17,fiveB,fivesize);
  105349. fprintf(stderr,"ok.");
  105350. fprintf(stderr,"\nSingle bit unclipped packing (MSb): ");
  105351. cliptestB(testbuffer3,test3size,1,sixB,sixsize);
  105352. fprintf(stderr,"ok.");
  105353. fprintf(stderr,"\nTesting read past end (MSb): ");
  105354. oggpackB_readinit(&r,"\0\0\0\0\0\0\0\0",8);
  105355. for(i=0;i<64;i++){
  105356. if(oggpackB_read(&r,1)!=0){
  105357. fprintf(stderr,"failed; got -1 prematurely.\n");
  105358. exit(1);
  105359. }
  105360. }
  105361. if(oggpackB_look(&r,1)!=-1 ||
  105362. oggpackB_read(&r,1)!=-1){
  105363. fprintf(stderr,"failed; read past end without -1.\n");
  105364. exit(1);
  105365. }
  105366. oggpackB_readinit(&r,"\0\0\0\0\0\0\0\0",8);
  105367. if(oggpackB_read(&r,30)!=0 || oggpackB_read(&r,16)!=0){
  105368. fprintf(stderr,"failed 2; got -1 prematurely.\n");
  105369. exit(1);
  105370. }
  105371. if(oggpackB_look(&r,18)!=0 ||
  105372. oggpackB_look(&r,18)!=0){
  105373. fprintf(stderr,"failed 3; got -1 prematurely.\n");
  105374. exit(1);
  105375. }
  105376. if(oggpackB_look(&r,19)!=-1 ||
  105377. oggpackB_look(&r,19)!=-1){
  105378. fprintf(stderr,"failed; read past end without -1.\n");
  105379. exit(1);
  105380. }
  105381. if(oggpackB_look(&r,32)!=-1 ||
  105382. oggpackB_look(&r,32)!=-1){
  105383. fprintf(stderr,"failed; read past end without -1.\n");
  105384. exit(1);
  105385. }
  105386. oggpackB_writeclear(&o);
  105387. fprintf(stderr,"ok.\n\n");
  105388. return(0);
  105389. }
  105390. #endif /* _V_SELFTEST */
  105391. #undef BUFFER_INCREMENT
  105392. #endif
  105393. /*** End of inlined file: bitwise.c ***/
  105394. /*** Start of inlined file: framing.c ***/
  105395. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  105396. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  105397. // tasks..
  105398. #if JUCE_MSVC
  105399. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  105400. #endif
  105401. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  105402. #if JUCE_USE_OGGVORBIS
  105403. #include <stdlib.h>
  105404. #include <string.h>
  105405. /* A complete description of Ogg framing exists in docs/framing.html */
  105406. int ogg_page_version(ogg_page *og){
  105407. return((int)(og->header[4]));
  105408. }
  105409. int ogg_page_continued(ogg_page *og){
  105410. return((int)(og->header[5]&0x01));
  105411. }
  105412. int ogg_page_bos(ogg_page *og){
  105413. return((int)(og->header[5]&0x02));
  105414. }
  105415. int ogg_page_eos(ogg_page *og){
  105416. return((int)(og->header[5]&0x04));
  105417. }
  105418. ogg_int64_t ogg_page_granulepos(ogg_page *og){
  105419. unsigned char *page=og->header;
  105420. ogg_int64_t granulepos=page[13]&(0xff);
  105421. granulepos= (granulepos<<8)|(page[12]&0xff);
  105422. granulepos= (granulepos<<8)|(page[11]&0xff);
  105423. granulepos= (granulepos<<8)|(page[10]&0xff);
  105424. granulepos= (granulepos<<8)|(page[9]&0xff);
  105425. granulepos= (granulepos<<8)|(page[8]&0xff);
  105426. granulepos= (granulepos<<8)|(page[7]&0xff);
  105427. granulepos= (granulepos<<8)|(page[6]&0xff);
  105428. return(granulepos);
  105429. }
  105430. int ogg_page_serialno(ogg_page *og){
  105431. return(og->header[14] |
  105432. (og->header[15]<<8) |
  105433. (og->header[16]<<16) |
  105434. (og->header[17]<<24));
  105435. }
  105436. long ogg_page_pageno(ogg_page *og){
  105437. return(og->header[18] |
  105438. (og->header[19]<<8) |
  105439. (og->header[20]<<16) |
  105440. (og->header[21]<<24));
  105441. }
  105442. /* returns the number of packets that are completed on this page (if
  105443. the leading packet is begun on a previous page, but ends on this
  105444. page, it's counted */
  105445. /* NOTE:
  105446. If a page consists of a packet begun on a previous page, and a new
  105447. packet begun (but not completed) on this page, the return will be:
  105448. ogg_page_packets(page) ==1,
  105449. ogg_page_continued(page) !=0
  105450. If a page happens to be a single packet that was begun on a
  105451. previous page, and spans to the next page (in the case of a three or
  105452. more page packet), the return will be:
  105453. ogg_page_packets(page) ==0,
  105454. ogg_page_continued(page) !=0
  105455. */
  105456. int ogg_page_packets(ogg_page *og){
  105457. int i,n=og->header[26],count=0;
  105458. for(i=0;i<n;i++)
  105459. if(og->header[27+i]<255)count++;
  105460. return(count);
  105461. }
  105462. #if 0
  105463. /* helper to initialize lookup for direct-table CRC (illustrative; we
  105464. use the static init below) */
  105465. static ogg_uint32_t _ogg_crc_entry(unsigned long index){
  105466. int i;
  105467. unsigned long r;
  105468. r = index << 24;
  105469. for (i=0; i<8; i++)
  105470. if (r & 0x80000000UL)
  105471. r = (r << 1) ^ 0x04c11db7; /* The same as the ethernet generator
  105472. polynomial, although we use an
  105473. unreflected alg and an init/final
  105474. of 0, not 0xffffffff */
  105475. else
  105476. r<<=1;
  105477. return (r & 0xffffffffUL);
  105478. }
  105479. #endif
  105480. static const ogg_uint32_t crc_lookup[256]={
  105481. 0x00000000,0x04c11db7,0x09823b6e,0x0d4326d9,
  105482. 0x130476dc,0x17c56b6b,0x1a864db2,0x1e475005,
  105483. 0x2608edb8,0x22c9f00f,0x2f8ad6d6,0x2b4bcb61,
  105484. 0x350c9b64,0x31cd86d3,0x3c8ea00a,0x384fbdbd,
  105485. 0x4c11db70,0x48d0c6c7,0x4593e01e,0x4152fda9,
  105486. 0x5f15adac,0x5bd4b01b,0x569796c2,0x52568b75,
  105487. 0x6a1936c8,0x6ed82b7f,0x639b0da6,0x675a1011,
  105488. 0x791d4014,0x7ddc5da3,0x709f7b7a,0x745e66cd,
  105489. 0x9823b6e0,0x9ce2ab57,0x91a18d8e,0x95609039,
  105490. 0x8b27c03c,0x8fe6dd8b,0x82a5fb52,0x8664e6e5,
  105491. 0xbe2b5b58,0xbaea46ef,0xb7a96036,0xb3687d81,
  105492. 0xad2f2d84,0xa9ee3033,0xa4ad16ea,0xa06c0b5d,
  105493. 0xd4326d90,0xd0f37027,0xddb056fe,0xd9714b49,
  105494. 0xc7361b4c,0xc3f706fb,0xceb42022,0xca753d95,
  105495. 0xf23a8028,0xf6fb9d9f,0xfbb8bb46,0xff79a6f1,
  105496. 0xe13ef6f4,0xe5ffeb43,0xe8bccd9a,0xec7dd02d,
  105497. 0x34867077,0x30476dc0,0x3d044b19,0x39c556ae,
  105498. 0x278206ab,0x23431b1c,0x2e003dc5,0x2ac12072,
  105499. 0x128e9dcf,0x164f8078,0x1b0ca6a1,0x1fcdbb16,
  105500. 0x018aeb13,0x054bf6a4,0x0808d07d,0x0cc9cdca,
  105501. 0x7897ab07,0x7c56b6b0,0x71159069,0x75d48dde,
  105502. 0x6b93dddb,0x6f52c06c,0x6211e6b5,0x66d0fb02,
  105503. 0x5e9f46bf,0x5a5e5b08,0x571d7dd1,0x53dc6066,
  105504. 0x4d9b3063,0x495a2dd4,0x44190b0d,0x40d816ba,
  105505. 0xaca5c697,0xa864db20,0xa527fdf9,0xa1e6e04e,
  105506. 0xbfa1b04b,0xbb60adfc,0xb6238b25,0xb2e29692,
  105507. 0x8aad2b2f,0x8e6c3698,0x832f1041,0x87ee0df6,
  105508. 0x99a95df3,0x9d684044,0x902b669d,0x94ea7b2a,
  105509. 0xe0b41de7,0xe4750050,0xe9362689,0xedf73b3e,
  105510. 0xf3b06b3b,0xf771768c,0xfa325055,0xfef34de2,
  105511. 0xc6bcf05f,0xc27dede8,0xcf3ecb31,0xcbffd686,
  105512. 0xd5b88683,0xd1799b34,0xdc3abded,0xd8fba05a,
  105513. 0x690ce0ee,0x6dcdfd59,0x608edb80,0x644fc637,
  105514. 0x7a089632,0x7ec98b85,0x738aad5c,0x774bb0eb,
  105515. 0x4f040d56,0x4bc510e1,0x46863638,0x42472b8f,
  105516. 0x5c007b8a,0x58c1663d,0x558240e4,0x51435d53,
  105517. 0x251d3b9e,0x21dc2629,0x2c9f00f0,0x285e1d47,
  105518. 0x36194d42,0x32d850f5,0x3f9b762c,0x3b5a6b9b,
  105519. 0x0315d626,0x07d4cb91,0x0a97ed48,0x0e56f0ff,
  105520. 0x1011a0fa,0x14d0bd4d,0x19939b94,0x1d528623,
  105521. 0xf12f560e,0xf5ee4bb9,0xf8ad6d60,0xfc6c70d7,
  105522. 0xe22b20d2,0xe6ea3d65,0xeba91bbc,0xef68060b,
  105523. 0xd727bbb6,0xd3e6a601,0xdea580d8,0xda649d6f,
  105524. 0xc423cd6a,0xc0e2d0dd,0xcda1f604,0xc960ebb3,
  105525. 0xbd3e8d7e,0xb9ff90c9,0xb4bcb610,0xb07daba7,
  105526. 0xae3afba2,0xaafbe615,0xa7b8c0cc,0xa379dd7b,
  105527. 0x9b3660c6,0x9ff77d71,0x92b45ba8,0x9675461f,
  105528. 0x8832161a,0x8cf30bad,0x81b02d74,0x857130c3,
  105529. 0x5d8a9099,0x594b8d2e,0x5408abf7,0x50c9b640,
  105530. 0x4e8ee645,0x4a4ffbf2,0x470cdd2b,0x43cdc09c,
  105531. 0x7b827d21,0x7f436096,0x7200464f,0x76c15bf8,
  105532. 0x68860bfd,0x6c47164a,0x61043093,0x65c52d24,
  105533. 0x119b4be9,0x155a565e,0x18197087,0x1cd86d30,
  105534. 0x029f3d35,0x065e2082,0x0b1d065b,0x0fdc1bec,
  105535. 0x3793a651,0x3352bbe6,0x3e119d3f,0x3ad08088,
  105536. 0x2497d08d,0x2056cd3a,0x2d15ebe3,0x29d4f654,
  105537. 0xc5a92679,0xc1683bce,0xcc2b1d17,0xc8ea00a0,
  105538. 0xd6ad50a5,0xd26c4d12,0xdf2f6bcb,0xdbee767c,
  105539. 0xe3a1cbc1,0xe760d676,0xea23f0af,0xeee2ed18,
  105540. 0xf0a5bd1d,0xf464a0aa,0xf9278673,0xfde69bc4,
  105541. 0x89b8fd09,0x8d79e0be,0x803ac667,0x84fbdbd0,
  105542. 0x9abc8bd5,0x9e7d9662,0x933eb0bb,0x97ffad0c,
  105543. 0xafb010b1,0xab710d06,0xa6322bdf,0xa2f33668,
  105544. 0xbcb4666d,0xb8757bda,0xb5365d03,0xb1f740b4};
  105545. /* init the encode/decode logical stream state */
  105546. int ogg_stream_init(ogg_stream_state *os,int serialno){
  105547. if(os){
  105548. memset(os,0,sizeof(*os));
  105549. os->body_storage=16*1024;
  105550. os->body_data=(unsigned char*) _ogg_malloc(os->body_storage*sizeof(*os->body_data));
  105551. os->lacing_storage=1024;
  105552. os->lacing_vals=(int*) _ogg_malloc(os->lacing_storage*sizeof(*os->lacing_vals));
  105553. os->granule_vals=(ogg_int64_t*) _ogg_malloc(os->lacing_storage*sizeof(*os->granule_vals));
  105554. os->serialno=serialno;
  105555. return(0);
  105556. }
  105557. return(-1);
  105558. }
  105559. /* _clear does not free os, only the non-flat storage within */
  105560. int ogg_stream_clear(ogg_stream_state *os){
  105561. if(os){
  105562. if(os->body_data)_ogg_free(os->body_data);
  105563. if(os->lacing_vals)_ogg_free(os->lacing_vals);
  105564. if(os->granule_vals)_ogg_free(os->granule_vals);
  105565. memset(os,0,sizeof(*os));
  105566. }
  105567. return(0);
  105568. }
  105569. int ogg_stream_destroy(ogg_stream_state *os){
  105570. if(os){
  105571. ogg_stream_clear(os);
  105572. _ogg_free(os);
  105573. }
  105574. return(0);
  105575. }
  105576. /* Helpers for ogg_stream_encode; this keeps the structure and
  105577. what's happening fairly clear */
  105578. static void _os_body_expand(ogg_stream_state *os,int needed){
  105579. if(os->body_storage<=os->body_fill+needed){
  105580. os->body_storage+=(needed+1024);
  105581. os->body_data=(unsigned char*) _ogg_realloc(os->body_data,os->body_storage*sizeof(*os->body_data));
  105582. }
  105583. }
  105584. static void _os_lacing_expand(ogg_stream_state *os,int needed){
  105585. if(os->lacing_storage<=os->lacing_fill+needed){
  105586. os->lacing_storage+=(needed+32);
  105587. os->lacing_vals=(int*)_ogg_realloc(os->lacing_vals,os->lacing_storage*sizeof(*os->lacing_vals));
  105588. os->granule_vals=(ogg_int64_t*)_ogg_realloc(os->granule_vals,os->lacing_storage*sizeof(*os->granule_vals));
  105589. }
  105590. }
  105591. /* checksum the page */
  105592. /* Direct table CRC; note that this will be faster in the future if we
  105593. perform the checksum silmultaneously with other copies */
  105594. void ogg_page_checksum_set(ogg_page *og){
  105595. if(og){
  105596. ogg_uint32_t crc_reg=0;
  105597. int i;
  105598. /* safety; needed for API behavior, but not framing code */
  105599. og->header[22]=0;
  105600. og->header[23]=0;
  105601. og->header[24]=0;
  105602. og->header[25]=0;
  105603. for(i=0;i<og->header_len;i++)
  105604. crc_reg=(crc_reg<<8)^crc_lookup[((crc_reg >> 24)&0xff)^og->header[i]];
  105605. for(i=0;i<og->body_len;i++)
  105606. crc_reg=(crc_reg<<8)^crc_lookup[((crc_reg >> 24)&0xff)^og->body[i]];
  105607. og->header[22]=(unsigned char)(crc_reg&0xff);
  105608. og->header[23]=(unsigned char)((crc_reg>>8)&0xff);
  105609. og->header[24]=(unsigned char)((crc_reg>>16)&0xff);
  105610. og->header[25]=(unsigned char)((crc_reg>>24)&0xff);
  105611. }
  105612. }
  105613. /* submit data to the internal buffer of the framing engine */
  105614. int ogg_stream_packetin(ogg_stream_state *os,ogg_packet *op){
  105615. int lacing_vals=op->bytes/255+1,i;
  105616. if(os->body_returned){
  105617. /* advance packet data according to the body_returned pointer. We
  105618. had to keep it around to return a pointer into the buffer last
  105619. call */
  105620. os->body_fill-=os->body_returned;
  105621. if(os->body_fill)
  105622. memmove(os->body_data,os->body_data+os->body_returned,
  105623. os->body_fill);
  105624. os->body_returned=0;
  105625. }
  105626. /* make sure we have the buffer storage */
  105627. _os_body_expand(os,op->bytes);
  105628. _os_lacing_expand(os,lacing_vals);
  105629. /* Copy in the submitted packet. Yes, the copy is a waste; this is
  105630. the liability of overly clean abstraction for the time being. It
  105631. will actually be fairly easy to eliminate the extra copy in the
  105632. future */
  105633. memcpy(os->body_data+os->body_fill,op->packet,op->bytes);
  105634. os->body_fill+=op->bytes;
  105635. /* Store lacing vals for this packet */
  105636. for(i=0;i<lacing_vals-1;i++){
  105637. os->lacing_vals[os->lacing_fill+i]=255;
  105638. os->granule_vals[os->lacing_fill+i]=os->granulepos;
  105639. }
  105640. os->lacing_vals[os->lacing_fill+i]=(op->bytes)%255;
  105641. os->granulepos=os->granule_vals[os->lacing_fill+i]=op->granulepos;
  105642. /* flag the first segment as the beginning of the packet */
  105643. os->lacing_vals[os->lacing_fill]|= 0x100;
  105644. os->lacing_fill+=lacing_vals;
  105645. /* for the sake of completeness */
  105646. os->packetno++;
  105647. if(op->e_o_s)os->e_o_s=1;
  105648. return(0);
  105649. }
  105650. /* This will flush remaining packets into a page (returning nonzero),
  105651. even if there is not enough data to trigger a flush normally
  105652. (undersized page). If there are no packets or partial packets to
  105653. flush, ogg_stream_flush returns 0. Note that ogg_stream_flush will
  105654. try to flush a normal sized page like ogg_stream_pageout; a call to
  105655. ogg_stream_flush does not guarantee that all packets have flushed.
  105656. Only a return value of 0 from ogg_stream_flush indicates all packet
  105657. data is flushed into pages.
  105658. since ogg_stream_flush will flush the last page in a stream even if
  105659. it's undersized, you almost certainly want to use ogg_stream_pageout
  105660. (and *not* ogg_stream_flush) unless you specifically need to flush
  105661. an page regardless of size in the middle of a stream. */
  105662. int ogg_stream_flush(ogg_stream_state *os,ogg_page *og){
  105663. int i;
  105664. int vals=0;
  105665. int maxvals=(os->lacing_fill>255?255:os->lacing_fill);
  105666. int bytes=0;
  105667. long acc=0;
  105668. ogg_int64_t granule_pos=-1;
  105669. if(maxvals==0)return(0);
  105670. /* construct a page */
  105671. /* decide how many segments to include */
  105672. /* If this is the initial header case, the first page must only include
  105673. the initial header packet */
  105674. if(os->b_o_s==0){ /* 'initial header page' case */
  105675. granule_pos=0;
  105676. for(vals=0;vals<maxvals;vals++){
  105677. if((os->lacing_vals[vals]&0x0ff)<255){
  105678. vals++;
  105679. break;
  105680. }
  105681. }
  105682. }else{
  105683. for(vals=0;vals<maxvals;vals++){
  105684. if(acc>4096)break;
  105685. acc+=os->lacing_vals[vals]&0x0ff;
  105686. if((os->lacing_vals[vals]&0xff)<255)
  105687. granule_pos=os->granule_vals[vals];
  105688. }
  105689. }
  105690. /* construct the header in temp storage */
  105691. memcpy(os->header,"OggS",4);
  105692. /* stream structure version */
  105693. os->header[4]=0x00;
  105694. /* continued packet flag? */
  105695. os->header[5]=0x00;
  105696. if((os->lacing_vals[0]&0x100)==0)os->header[5]|=0x01;
  105697. /* first page flag? */
  105698. if(os->b_o_s==0)os->header[5]|=0x02;
  105699. /* last page flag? */
  105700. if(os->e_o_s && os->lacing_fill==vals)os->header[5]|=0x04;
  105701. os->b_o_s=1;
  105702. /* 64 bits of PCM position */
  105703. for(i=6;i<14;i++){
  105704. os->header[i]=(unsigned char)(granule_pos&0xff);
  105705. granule_pos>>=8;
  105706. }
  105707. /* 32 bits of stream serial number */
  105708. {
  105709. long serialno=os->serialno;
  105710. for(i=14;i<18;i++){
  105711. os->header[i]=(unsigned char)(serialno&0xff);
  105712. serialno>>=8;
  105713. }
  105714. }
  105715. /* 32 bits of page counter (we have both counter and page header
  105716. because this val can roll over) */
  105717. if(os->pageno==-1)os->pageno=0; /* because someone called
  105718. stream_reset; this would be a
  105719. strange thing to do in an
  105720. encode stream, but it has
  105721. plausible uses */
  105722. {
  105723. long pageno=os->pageno++;
  105724. for(i=18;i<22;i++){
  105725. os->header[i]=(unsigned char)(pageno&0xff);
  105726. pageno>>=8;
  105727. }
  105728. }
  105729. /* zero for computation; filled in later */
  105730. os->header[22]=0;
  105731. os->header[23]=0;
  105732. os->header[24]=0;
  105733. os->header[25]=0;
  105734. /* segment table */
  105735. os->header[26]=(unsigned char)(vals&0xff);
  105736. for(i=0;i<vals;i++)
  105737. bytes+=os->header[i+27]=(unsigned char)(os->lacing_vals[i]&0xff);
  105738. /* set pointers in the ogg_page struct */
  105739. og->header=os->header;
  105740. og->header_len=os->header_fill=vals+27;
  105741. og->body=os->body_data+os->body_returned;
  105742. og->body_len=bytes;
  105743. /* advance the lacing data and set the body_returned pointer */
  105744. os->lacing_fill-=vals;
  105745. memmove(os->lacing_vals,os->lacing_vals+vals,os->lacing_fill*sizeof(*os->lacing_vals));
  105746. memmove(os->granule_vals,os->granule_vals+vals,os->lacing_fill*sizeof(*os->granule_vals));
  105747. os->body_returned+=bytes;
  105748. /* calculate the checksum */
  105749. ogg_page_checksum_set(og);
  105750. /* done */
  105751. return(1);
  105752. }
  105753. /* This constructs pages from buffered packet segments. The pointers
  105754. returned are to static buffers; do not free. The returned buffers are
  105755. good only until the next call (using the same ogg_stream_state) */
  105756. int ogg_stream_pageout(ogg_stream_state *os, ogg_page *og){
  105757. if((os->e_o_s&&os->lacing_fill) || /* 'were done, now flush' case */
  105758. os->body_fill-os->body_returned > 4096 ||/* 'page nominal size' case */
  105759. os->lacing_fill>=255 || /* 'segment table full' case */
  105760. (os->lacing_fill&&!os->b_o_s)){ /* 'initial header page' case */
  105761. return(ogg_stream_flush(os,og));
  105762. }
  105763. /* not enough data to construct a page and not end of stream */
  105764. return(0);
  105765. }
  105766. int ogg_stream_eos(ogg_stream_state *os){
  105767. return os->e_o_s;
  105768. }
  105769. /* DECODING PRIMITIVES: packet streaming layer **********************/
  105770. /* This has two layers to place more of the multi-serialno and paging
  105771. control in the application's hands. First, we expose a data buffer
  105772. using ogg_sync_buffer(). The app either copies into the
  105773. buffer, or passes it directly to read(), etc. We then call
  105774. ogg_sync_wrote() to tell how many bytes we just added.
  105775. Pages are returned (pointers into the buffer in ogg_sync_state)
  105776. by ogg_sync_pageout(). The page is then submitted to
  105777. ogg_stream_pagein() along with the appropriate
  105778. ogg_stream_state* (ie, matching serialno). We then get raw
  105779. packets out calling ogg_stream_packetout() with a
  105780. ogg_stream_state. */
  105781. /* initialize the struct to a known state */
  105782. int ogg_sync_init(ogg_sync_state *oy){
  105783. if(oy){
  105784. memset(oy,0,sizeof(*oy));
  105785. }
  105786. return(0);
  105787. }
  105788. /* clear non-flat storage within */
  105789. int ogg_sync_clear(ogg_sync_state *oy){
  105790. if(oy){
  105791. if(oy->data)_ogg_free(oy->data);
  105792. ogg_sync_init(oy);
  105793. }
  105794. return(0);
  105795. }
  105796. int ogg_sync_destroy(ogg_sync_state *oy){
  105797. if(oy){
  105798. ogg_sync_clear(oy);
  105799. _ogg_free(oy);
  105800. }
  105801. return(0);
  105802. }
  105803. char *ogg_sync_buffer(ogg_sync_state *oy, long size){
  105804. /* first, clear out any space that has been previously returned */
  105805. if(oy->returned){
  105806. oy->fill-=oy->returned;
  105807. if(oy->fill>0)
  105808. memmove(oy->data,oy->data+oy->returned,oy->fill);
  105809. oy->returned=0;
  105810. }
  105811. if(size>oy->storage-oy->fill){
  105812. /* We need to extend the internal buffer */
  105813. long newsize=size+oy->fill+4096; /* an extra page to be nice */
  105814. if(oy->data)
  105815. oy->data=(unsigned char*) _ogg_realloc(oy->data,newsize);
  105816. else
  105817. oy->data=(unsigned char*) _ogg_malloc(newsize);
  105818. oy->storage=newsize;
  105819. }
  105820. /* expose a segment at least as large as requested at the fill mark */
  105821. return((char *)oy->data+oy->fill);
  105822. }
  105823. int ogg_sync_wrote(ogg_sync_state *oy, long bytes){
  105824. if(oy->fill+bytes>oy->storage)return(-1);
  105825. oy->fill+=bytes;
  105826. return(0);
  105827. }
  105828. /* sync the stream. This is meant to be useful for finding page
  105829. boundaries.
  105830. return values for this:
  105831. -n) skipped n bytes
  105832. 0) page not ready; more data (no bytes skipped)
  105833. n) page synced at current location; page length n bytes
  105834. */
  105835. long ogg_sync_pageseek(ogg_sync_state *oy,ogg_page *og){
  105836. unsigned char *page=oy->data+oy->returned;
  105837. unsigned char *next;
  105838. long bytes=oy->fill-oy->returned;
  105839. if(oy->headerbytes==0){
  105840. int headerbytes,i;
  105841. if(bytes<27)return(0); /* not enough for a header */
  105842. /* verify capture pattern */
  105843. if(memcmp(page,"OggS",4))goto sync_fail;
  105844. headerbytes=page[26]+27;
  105845. if(bytes<headerbytes)return(0); /* not enough for header + seg table */
  105846. /* count up body length in the segment table */
  105847. for(i=0;i<page[26];i++)
  105848. oy->bodybytes+=page[27+i];
  105849. oy->headerbytes=headerbytes;
  105850. }
  105851. if(oy->bodybytes+oy->headerbytes>bytes)return(0);
  105852. /* The whole test page is buffered. Verify the checksum */
  105853. {
  105854. /* Grab the checksum bytes, set the header field to zero */
  105855. char chksum[4];
  105856. ogg_page log;
  105857. memcpy(chksum,page+22,4);
  105858. memset(page+22,0,4);
  105859. /* set up a temp page struct and recompute the checksum */
  105860. log.header=page;
  105861. log.header_len=oy->headerbytes;
  105862. log.body=page+oy->headerbytes;
  105863. log.body_len=oy->bodybytes;
  105864. ogg_page_checksum_set(&log);
  105865. /* Compare */
  105866. if(memcmp(chksum,page+22,4)){
  105867. /* D'oh. Mismatch! Corrupt page (or miscapture and not a page
  105868. at all) */
  105869. /* replace the computed checksum with the one actually read in */
  105870. memcpy(page+22,chksum,4);
  105871. /* Bad checksum. Lose sync */
  105872. goto sync_fail;
  105873. }
  105874. }
  105875. /* yes, have a whole page all ready to go */
  105876. {
  105877. unsigned char *page=oy->data+oy->returned;
  105878. long bytes;
  105879. if(og){
  105880. og->header=page;
  105881. og->header_len=oy->headerbytes;
  105882. og->body=page+oy->headerbytes;
  105883. og->body_len=oy->bodybytes;
  105884. }
  105885. oy->unsynced=0;
  105886. oy->returned+=(bytes=oy->headerbytes+oy->bodybytes);
  105887. oy->headerbytes=0;
  105888. oy->bodybytes=0;
  105889. return(bytes);
  105890. }
  105891. sync_fail:
  105892. oy->headerbytes=0;
  105893. oy->bodybytes=0;
  105894. /* search for possible capture */
  105895. next=(unsigned char*)memchr(page+1,'O',bytes-1);
  105896. if(!next)
  105897. next=oy->data+oy->fill;
  105898. oy->returned=next-oy->data;
  105899. return(-(next-page));
  105900. }
  105901. /* sync the stream and get a page. Keep trying until we find a page.
  105902. Supress 'sync errors' after reporting the first.
  105903. return values:
  105904. -1) recapture (hole in data)
  105905. 0) need more data
  105906. 1) page returned
  105907. Returns pointers into buffered data; invalidated by next call to
  105908. _stream, _clear, _init, or _buffer */
  105909. int ogg_sync_pageout(ogg_sync_state *oy, ogg_page *og){
  105910. /* all we need to do is verify a page at the head of the stream
  105911. buffer. If it doesn't verify, we look for the next potential
  105912. frame */
  105913. for(;;){
  105914. long ret=ogg_sync_pageseek(oy,og);
  105915. if(ret>0){
  105916. /* have a page */
  105917. return(1);
  105918. }
  105919. if(ret==0){
  105920. /* need more data */
  105921. return(0);
  105922. }
  105923. /* head did not start a synced page... skipped some bytes */
  105924. if(!oy->unsynced){
  105925. oy->unsynced=1;
  105926. return(-1);
  105927. }
  105928. /* loop. keep looking */
  105929. }
  105930. }
  105931. /* add the incoming page to the stream state; we decompose the page
  105932. into packet segments here as well. */
  105933. int ogg_stream_pagein(ogg_stream_state *os, ogg_page *og){
  105934. unsigned char *header=og->header;
  105935. unsigned char *body=og->body;
  105936. long bodysize=og->body_len;
  105937. int segptr=0;
  105938. int version=ogg_page_version(og);
  105939. int continued=ogg_page_continued(og);
  105940. int bos=ogg_page_bos(og);
  105941. int eos=ogg_page_eos(og);
  105942. ogg_int64_t granulepos=ogg_page_granulepos(og);
  105943. int serialno=ogg_page_serialno(og);
  105944. long pageno=ogg_page_pageno(og);
  105945. int segments=header[26];
  105946. /* clean up 'returned data' */
  105947. {
  105948. long lr=os->lacing_returned;
  105949. long br=os->body_returned;
  105950. /* body data */
  105951. if(br){
  105952. os->body_fill-=br;
  105953. if(os->body_fill)
  105954. memmove(os->body_data,os->body_data+br,os->body_fill);
  105955. os->body_returned=0;
  105956. }
  105957. if(lr){
  105958. /* segment table */
  105959. if(os->lacing_fill-lr){
  105960. memmove(os->lacing_vals,os->lacing_vals+lr,
  105961. (os->lacing_fill-lr)*sizeof(*os->lacing_vals));
  105962. memmove(os->granule_vals,os->granule_vals+lr,
  105963. (os->lacing_fill-lr)*sizeof(*os->granule_vals));
  105964. }
  105965. os->lacing_fill-=lr;
  105966. os->lacing_packet-=lr;
  105967. os->lacing_returned=0;
  105968. }
  105969. }
  105970. /* check the serial number */
  105971. if(serialno!=os->serialno)return(-1);
  105972. if(version>0)return(-1);
  105973. _os_lacing_expand(os,segments+1);
  105974. /* are we in sequence? */
  105975. if(pageno!=os->pageno){
  105976. int i;
  105977. /* unroll previous partial packet (if any) */
  105978. for(i=os->lacing_packet;i<os->lacing_fill;i++)
  105979. os->body_fill-=os->lacing_vals[i]&0xff;
  105980. os->lacing_fill=os->lacing_packet;
  105981. /* make a note of dropped data in segment table */
  105982. if(os->pageno!=-1){
  105983. os->lacing_vals[os->lacing_fill++]=0x400;
  105984. os->lacing_packet++;
  105985. }
  105986. }
  105987. /* are we a 'continued packet' page? If so, we may need to skip
  105988. some segments */
  105989. if(continued){
  105990. if(os->lacing_fill<1 ||
  105991. os->lacing_vals[os->lacing_fill-1]==0x400){
  105992. bos=0;
  105993. for(;segptr<segments;segptr++){
  105994. int val=header[27+segptr];
  105995. body+=val;
  105996. bodysize-=val;
  105997. if(val<255){
  105998. segptr++;
  105999. break;
  106000. }
  106001. }
  106002. }
  106003. }
  106004. if(bodysize){
  106005. _os_body_expand(os,bodysize);
  106006. memcpy(os->body_data+os->body_fill,body,bodysize);
  106007. os->body_fill+=bodysize;
  106008. }
  106009. {
  106010. int saved=-1;
  106011. while(segptr<segments){
  106012. int val=header[27+segptr];
  106013. os->lacing_vals[os->lacing_fill]=val;
  106014. os->granule_vals[os->lacing_fill]=-1;
  106015. if(bos){
  106016. os->lacing_vals[os->lacing_fill]|=0x100;
  106017. bos=0;
  106018. }
  106019. if(val<255)saved=os->lacing_fill;
  106020. os->lacing_fill++;
  106021. segptr++;
  106022. if(val<255)os->lacing_packet=os->lacing_fill;
  106023. }
  106024. /* set the granulepos on the last granuleval of the last full packet */
  106025. if(saved!=-1){
  106026. os->granule_vals[saved]=granulepos;
  106027. }
  106028. }
  106029. if(eos){
  106030. os->e_o_s=1;
  106031. if(os->lacing_fill>0)
  106032. os->lacing_vals[os->lacing_fill-1]|=0x200;
  106033. }
  106034. os->pageno=pageno+1;
  106035. return(0);
  106036. }
  106037. /* clear things to an initial state. Good to call, eg, before seeking */
  106038. int ogg_sync_reset(ogg_sync_state *oy){
  106039. oy->fill=0;
  106040. oy->returned=0;
  106041. oy->unsynced=0;
  106042. oy->headerbytes=0;
  106043. oy->bodybytes=0;
  106044. return(0);
  106045. }
  106046. int ogg_stream_reset(ogg_stream_state *os){
  106047. os->body_fill=0;
  106048. os->body_returned=0;
  106049. os->lacing_fill=0;
  106050. os->lacing_packet=0;
  106051. os->lacing_returned=0;
  106052. os->header_fill=0;
  106053. os->e_o_s=0;
  106054. os->b_o_s=0;
  106055. os->pageno=-1;
  106056. os->packetno=0;
  106057. os->granulepos=0;
  106058. return(0);
  106059. }
  106060. int ogg_stream_reset_serialno(ogg_stream_state *os,int serialno){
  106061. ogg_stream_reset(os);
  106062. os->serialno=serialno;
  106063. return(0);
  106064. }
  106065. static int _packetout(ogg_stream_state *os,ogg_packet *op,int adv){
  106066. /* The last part of decode. We have the stream broken into packet
  106067. segments. Now we need to group them into packets (or return the
  106068. out of sync markers) */
  106069. int ptr=os->lacing_returned;
  106070. if(os->lacing_packet<=ptr)return(0);
  106071. if(os->lacing_vals[ptr]&0x400){
  106072. /* we need to tell the codec there's a gap; it might need to
  106073. handle previous packet dependencies. */
  106074. os->lacing_returned++;
  106075. os->packetno++;
  106076. return(-1);
  106077. }
  106078. if(!op && !adv)return(1); /* just using peek as an inexpensive way
  106079. to ask if there's a whole packet
  106080. waiting */
  106081. /* Gather the whole packet. We'll have no holes or a partial packet */
  106082. {
  106083. int size=os->lacing_vals[ptr]&0xff;
  106084. int bytes=size;
  106085. int eos=os->lacing_vals[ptr]&0x200; /* last packet of the stream? */
  106086. int bos=os->lacing_vals[ptr]&0x100; /* first packet of the stream? */
  106087. while(size==255){
  106088. int val=os->lacing_vals[++ptr];
  106089. size=val&0xff;
  106090. if(val&0x200)eos=0x200;
  106091. bytes+=size;
  106092. }
  106093. if(op){
  106094. op->e_o_s=eos;
  106095. op->b_o_s=bos;
  106096. op->packet=os->body_data+os->body_returned;
  106097. op->packetno=os->packetno;
  106098. op->granulepos=os->granule_vals[ptr];
  106099. op->bytes=bytes;
  106100. }
  106101. if(adv){
  106102. os->body_returned+=bytes;
  106103. os->lacing_returned=ptr+1;
  106104. os->packetno++;
  106105. }
  106106. }
  106107. return(1);
  106108. }
  106109. int ogg_stream_packetout(ogg_stream_state *os,ogg_packet *op){
  106110. return _packetout(os,op,1);
  106111. }
  106112. int ogg_stream_packetpeek(ogg_stream_state *os,ogg_packet *op){
  106113. return _packetout(os,op,0);
  106114. }
  106115. void ogg_packet_clear(ogg_packet *op) {
  106116. _ogg_free(op->packet);
  106117. memset(op, 0, sizeof(*op));
  106118. }
  106119. #ifdef _V_SELFTEST
  106120. #include <stdio.h>
  106121. ogg_stream_state os_en, os_de;
  106122. ogg_sync_state oy;
  106123. void checkpacket(ogg_packet *op,int len, int no, int pos){
  106124. long j;
  106125. static int sequence=0;
  106126. static int lastno=0;
  106127. if(op->bytes!=len){
  106128. fprintf(stderr,"incorrect packet length!\n");
  106129. exit(1);
  106130. }
  106131. if(op->granulepos!=pos){
  106132. fprintf(stderr,"incorrect packet position!\n");
  106133. exit(1);
  106134. }
  106135. /* packet number just follows sequence/gap; adjust the input number
  106136. for that */
  106137. if(no==0){
  106138. sequence=0;
  106139. }else{
  106140. sequence++;
  106141. if(no>lastno+1)
  106142. sequence++;
  106143. }
  106144. lastno=no;
  106145. if(op->packetno!=sequence){
  106146. fprintf(stderr,"incorrect packet sequence %ld != %d\n",
  106147. (long)(op->packetno),sequence);
  106148. exit(1);
  106149. }
  106150. /* Test data */
  106151. for(j=0;j<op->bytes;j++)
  106152. if(op->packet[j]!=((j+no)&0xff)){
  106153. fprintf(stderr,"body data mismatch (1) at pos %ld: %x!=%lx!\n\n",
  106154. j,op->packet[j],(j+no)&0xff);
  106155. exit(1);
  106156. }
  106157. }
  106158. void check_page(unsigned char *data,const int *header,ogg_page *og){
  106159. long j;
  106160. /* Test data */
  106161. for(j=0;j<og->body_len;j++)
  106162. if(og->body[j]!=data[j]){
  106163. fprintf(stderr,"body data mismatch (2) at pos %ld: %x!=%x!\n\n",
  106164. j,data[j],og->body[j]);
  106165. exit(1);
  106166. }
  106167. /* Test header */
  106168. for(j=0;j<og->header_len;j++){
  106169. if(og->header[j]!=header[j]){
  106170. fprintf(stderr,"header content mismatch at pos %ld:\n",j);
  106171. for(j=0;j<header[26]+27;j++)
  106172. fprintf(stderr," (%ld)%02x:%02x",j,header[j],og->header[j]);
  106173. fprintf(stderr,"\n");
  106174. exit(1);
  106175. }
  106176. }
  106177. if(og->header_len!=header[26]+27){
  106178. fprintf(stderr,"header length incorrect! (%ld!=%d)\n",
  106179. og->header_len,header[26]+27);
  106180. exit(1);
  106181. }
  106182. }
  106183. void print_header(ogg_page *og){
  106184. int j;
  106185. fprintf(stderr,"\nHEADER:\n");
  106186. fprintf(stderr," capture: %c %c %c %c version: %d flags: %x\n",
  106187. og->header[0],og->header[1],og->header[2],og->header[3],
  106188. (int)og->header[4],(int)og->header[5]);
  106189. fprintf(stderr," granulepos: %d serialno: %d pageno: %ld\n",
  106190. (og->header[9]<<24)|(og->header[8]<<16)|
  106191. (og->header[7]<<8)|og->header[6],
  106192. (og->header[17]<<24)|(og->header[16]<<16)|
  106193. (og->header[15]<<8)|og->header[14],
  106194. ((long)(og->header[21])<<24)|(og->header[20]<<16)|
  106195. (og->header[19]<<8)|og->header[18]);
  106196. fprintf(stderr," checksum: %02x:%02x:%02x:%02x\n segments: %d (",
  106197. (int)og->header[22],(int)og->header[23],
  106198. (int)og->header[24],(int)og->header[25],
  106199. (int)og->header[26]);
  106200. for(j=27;j<og->header_len;j++)
  106201. fprintf(stderr,"%d ",(int)og->header[j]);
  106202. fprintf(stderr,")\n\n");
  106203. }
  106204. void copy_page(ogg_page *og){
  106205. unsigned char *temp=_ogg_malloc(og->header_len);
  106206. memcpy(temp,og->header,og->header_len);
  106207. og->header=temp;
  106208. temp=_ogg_malloc(og->body_len);
  106209. memcpy(temp,og->body,og->body_len);
  106210. og->body=temp;
  106211. }
  106212. void free_page(ogg_page *og){
  106213. _ogg_free (og->header);
  106214. _ogg_free (og->body);
  106215. }
  106216. void error(void){
  106217. fprintf(stderr,"error!\n");
  106218. exit(1);
  106219. }
  106220. /* 17 only */
  106221. const int head1_0[] = {0x4f,0x67,0x67,0x53,0,0x06,
  106222. 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
  106223. 0x01,0x02,0x03,0x04,0,0,0,0,
  106224. 0x15,0xed,0xec,0x91,
  106225. 1,
  106226. 17};
  106227. /* 17, 254, 255, 256, 500, 510, 600 byte, pad */
  106228. const int head1_1[] = {0x4f,0x67,0x67,0x53,0,0x02,
  106229. 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
  106230. 0x01,0x02,0x03,0x04,0,0,0,0,
  106231. 0x59,0x10,0x6c,0x2c,
  106232. 1,
  106233. 17};
  106234. const int head2_1[] = {0x4f,0x67,0x67,0x53,0,0x04,
  106235. 0x07,0x18,0x00,0x00,0x00,0x00,0x00,0x00,
  106236. 0x01,0x02,0x03,0x04,1,0,0,0,
  106237. 0x89,0x33,0x85,0xce,
  106238. 13,
  106239. 254,255,0,255,1,255,245,255,255,0,
  106240. 255,255,90};
  106241. /* nil packets; beginning,middle,end */
  106242. const int head1_2[] = {0x4f,0x67,0x67,0x53,0,0x02,
  106243. 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
  106244. 0x01,0x02,0x03,0x04,0,0,0,0,
  106245. 0xff,0x7b,0x23,0x17,
  106246. 1,
  106247. 0};
  106248. const int head2_2[] = {0x4f,0x67,0x67,0x53,0,0x04,
  106249. 0x07,0x28,0x00,0x00,0x00,0x00,0x00,0x00,
  106250. 0x01,0x02,0x03,0x04,1,0,0,0,
  106251. 0x5c,0x3f,0x66,0xcb,
  106252. 17,
  106253. 17,254,255,0,0,255,1,0,255,245,255,255,0,
  106254. 255,255,90,0};
  106255. /* large initial packet */
  106256. const int head1_3[] = {0x4f,0x67,0x67,0x53,0,0x02,
  106257. 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
  106258. 0x01,0x02,0x03,0x04,0,0,0,0,
  106259. 0x01,0x27,0x31,0xaa,
  106260. 18,
  106261. 255,255,255,255,255,255,255,255,
  106262. 255,255,255,255,255,255,255,255,255,10};
  106263. const int head2_3[] = {0x4f,0x67,0x67,0x53,0,0x04,
  106264. 0x07,0x08,0x00,0x00,0x00,0x00,0x00,0x00,
  106265. 0x01,0x02,0x03,0x04,1,0,0,0,
  106266. 0x7f,0x4e,0x8a,0xd2,
  106267. 4,
  106268. 255,4,255,0};
  106269. /* continuing packet test */
  106270. const int head1_4[] = {0x4f,0x67,0x67,0x53,0,0x02,
  106271. 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
  106272. 0x01,0x02,0x03,0x04,0,0,0,0,
  106273. 0xff,0x7b,0x23,0x17,
  106274. 1,
  106275. 0};
  106276. const int head2_4[] = {0x4f,0x67,0x67,0x53,0,0x00,
  106277. 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,
  106278. 0x01,0x02,0x03,0x04,1,0,0,0,
  106279. 0x54,0x05,0x51,0xc8,
  106280. 17,
  106281. 255,255,255,255,255,255,255,255,
  106282. 255,255,255,255,255,255,255,255,255};
  106283. const int head3_4[] = {0x4f,0x67,0x67,0x53,0,0x05,
  106284. 0x07,0x0c,0x00,0x00,0x00,0x00,0x00,0x00,
  106285. 0x01,0x02,0x03,0x04,2,0,0,0,
  106286. 0xc8,0xc3,0xcb,0xed,
  106287. 5,
  106288. 10,255,4,255,0};
  106289. /* page with the 255 segment limit */
  106290. const int head1_5[] = {0x4f,0x67,0x67,0x53,0,0x02,
  106291. 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
  106292. 0x01,0x02,0x03,0x04,0,0,0,0,
  106293. 0xff,0x7b,0x23,0x17,
  106294. 1,
  106295. 0};
  106296. const int head2_5[] = {0x4f,0x67,0x67,0x53,0,0x00,
  106297. 0x07,0xfc,0x03,0x00,0x00,0x00,0x00,0x00,
  106298. 0x01,0x02,0x03,0x04,1,0,0,0,
  106299. 0xed,0x2a,0x2e,0xa7,
  106300. 255,
  106301. 10,10,10,10,10,10,10,10,
  106302. 10,10,10,10,10,10,10,10,
  106303. 10,10,10,10,10,10,10,10,
  106304. 10,10,10,10,10,10,10,10,
  106305. 10,10,10,10,10,10,10,10,
  106306. 10,10,10,10,10,10,10,10,
  106307. 10,10,10,10,10,10,10,10,
  106308. 10,10,10,10,10,10,10,10,
  106309. 10,10,10,10,10,10,10,10,
  106310. 10,10,10,10,10,10,10,10,
  106311. 10,10,10,10,10,10,10,10,
  106312. 10,10,10,10,10,10,10,10,
  106313. 10,10,10,10,10,10,10,10,
  106314. 10,10,10,10,10,10,10,10,
  106315. 10,10,10,10,10,10,10,10,
  106316. 10,10,10,10,10,10,10,10,
  106317. 10,10,10,10,10,10,10,10,
  106318. 10,10,10,10,10,10,10,10,
  106319. 10,10,10,10,10,10,10,10,
  106320. 10,10,10,10,10,10,10,10,
  106321. 10,10,10,10,10,10,10,10,
  106322. 10,10,10,10,10,10,10,10,
  106323. 10,10,10,10,10,10,10,10,
  106324. 10,10,10,10,10,10,10,10,
  106325. 10,10,10,10,10,10,10,10,
  106326. 10,10,10,10,10,10,10,10,
  106327. 10,10,10,10,10,10,10,10,
  106328. 10,10,10,10,10,10,10,10,
  106329. 10,10,10,10,10,10,10,10,
  106330. 10,10,10,10,10,10,10,10,
  106331. 10,10,10,10,10,10,10,10,
  106332. 10,10,10,10,10,10,10};
  106333. const int head3_5[] = {0x4f,0x67,0x67,0x53,0,0x04,
  106334. 0x07,0x00,0x04,0x00,0x00,0x00,0x00,0x00,
  106335. 0x01,0x02,0x03,0x04,2,0,0,0,
  106336. 0x6c,0x3b,0x82,0x3d,
  106337. 1,
  106338. 50};
  106339. /* packet that overspans over an entire page */
  106340. const int head1_6[] = {0x4f,0x67,0x67,0x53,0,0x02,
  106341. 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
  106342. 0x01,0x02,0x03,0x04,0,0,0,0,
  106343. 0xff,0x7b,0x23,0x17,
  106344. 1,
  106345. 0};
  106346. const int head2_6[] = {0x4f,0x67,0x67,0x53,0,0x00,
  106347. 0x07,0x04,0x00,0x00,0x00,0x00,0x00,0x00,
  106348. 0x01,0x02,0x03,0x04,1,0,0,0,
  106349. 0x3c,0xd9,0x4d,0x3f,
  106350. 17,
  106351. 100,255,255,255,255,255,255,255,255,
  106352. 255,255,255,255,255,255,255,255};
  106353. const int head3_6[] = {0x4f,0x67,0x67,0x53,0,0x01,
  106354. 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,
  106355. 0x01,0x02,0x03,0x04,2,0,0,0,
  106356. 0x01,0xd2,0xe5,0xe5,
  106357. 17,
  106358. 255,255,255,255,255,255,255,255,
  106359. 255,255,255,255,255,255,255,255,255};
  106360. const int head4_6[] = {0x4f,0x67,0x67,0x53,0,0x05,
  106361. 0x07,0x10,0x00,0x00,0x00,0x00,0x00,0x00,
  106362. 0x01,0x02,0x03,0x04,3,0,0,0,
  106363. 0xef,0xdd,0x88,0xde,
  106364. 7,
  106365. 255,255,75,255,4,255,0};
  106366. /* packet that overspans over an entire page */
  106367. const int head1_7[] = {0x4f,0x67,0x67,0x53,0,0x02,
  106368. 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
  106369. 0x01,0x02,0x03,0x04,0,0,0,0,
  106370. 0xff,0x7b,0x23,0x17,
  106371. 1,
  106372. 0};
  106373. const int head2_7[] = {0x4f,0x67,0x67,0x53,0,0x00,
  106374. 0x07,0x04,0x00,0x00,0x00,0x00,0x00,0x00,
  106375. 0x01,0x02,0x03,0x04,1,0,0,0,
  106376. 0x3c,0xd9,0x4d,0x3f,
  106377. 17,
  106378. 100,255,255,255,255,255,255,255,255,
  106379. 255,255,255,255,255,255,255,255};
  106380. const int head3_7[] = {0x4f,0x67,0x67,0x53,0,0x05,
  106381. 0x07,0x08,0x00,0x00,0x00,0x00,0x00,0x00,
  106382. 0x01,0x02,0x03,0x04,2,0,0,0,
  106383. 0xd4,0xe0,0x60,0xe5,
  106384. 1,0};
  106385. void test_pack(const int *pl, const int **headers, int byteskip,
  106386. int pageskip, int packetskip){
  106387. unsigned char *data=_ogg_malloc(1024*1024); /* for scripted test cases only */
  106388. long inptr=0;
  106389. long outptr=0;
  106390. long deptr=0;
  106391. long depacket=0;
  106392. long granule_pos=7,pageno=0;
  106393. int i,j,packets,pageout=pageskip;
  106394. int eosflag=0;
  106395. int bosflag=0;
  106396. int byteskipcount=0;
  106397. ogg_stream_reset(&os_en);
  106398. ogg_stream_reset(&os_de);
  106399. ogg_sync_reset(&oy);
  106400. for(packets=0;packets<packetskip;packets++)
  106401. depacket+=pl[packets];
  106402. for(packets=0;;packets++)if(pl[packets]==-1)break;
  106403. for(i=0;i<packets;i++){
  106404. /* construct a test packet */
  106405. ogg_packet op;
  106406. int len=pl[i];
  106407. op.packet=data+inptr;
  106408. op.bytes=len;
  106409. op.e_o_s=(pl[i+1]<0?1:0);
  106410. op.granulepos=granule_pos;
  106411. granule_pos+=1024;
  106412. for(j=0;j<len;j++)data[inptr++]=i+j;
  106413. /* submit the test packet */
  106414. ogg_stream_packetin(&os_en,&op);
  106415. /* retrieve any finished pages */
  106416. {
  106417. ogg_page og;
  106418. while(ogg_stream_pageout(&os_en,&og)){
  106419. /* We have a page. Check it carefully */
  106420. fprintf(stderr,"%ld, ",pageno);
  106421. if(headers[pageno]==NULL){
  106422. fprintf(stderr,"coded too many pages!\n");
  106423. exit(1);
  106424. }
  106425. check_page(data+outptr,headers[pageno],&og);
  106426. outptr+=og.body_len;
  106427. pageno++;
  106428. if(pageskip){
  106429. bosflag=1;
  106430. pageskip--;
  106431. deptr+=og.body_len;
  106432. }
  106433. /* have a complete page; submit it to sync/decode */
  106434. {
  106435. ogg_page og_de;
  106436. ogg_packet op_de,op_de2;
  106437. char *buf=ogg_sync_buffer(&oy,og.header_len+og.body_len);
  106438. char *next=buf;
  106439. byteskipcount+=og.header_len;
  106440. if(byteskipcount>byteskip){
  106441. memcpy(next,og.header,byteskipcount-byteskip);
  106442. next+=byteskipcount-byteskip;
  106443. byteskipcount=byteskip;
  106444. }
  106445. byteskipcount+=og.body_len;
  106446. if(byteskipcount>byteskip){
  106447. memcpy(next,og.body,byteskipcount-byteskip);
  106448. next+=byteskipcount-byteskip;
  106449. byteskipcount=byteskip;
  106450. }
  106451. ogg_sync_wrote(&oy,next-buf);
  106452. while(1){
  106453. int ret=ogg_sync_pageout(&oy,&og_de);
  106454. if(ret==0)break;
  106455. if(ret<0)continue;
  106456. /* got a page. Happy happy. Verify that it's good. */
  106457. fprintf(stderr,"(%ld), ",pageout);
  106458. check_page(data+deptr,headers[pageout],&og_de);
  106459. deptr+=og_de.body_len;
  106460. pageout++;
  106461. /* submit it to deconstitution */
  106462. ogg_stream_pagein(&os_de,&og_de);
  106463. /* packets out? */
  106464. while(ogg_stream_packetpeek(&os_de,&op_de2)>0){
  106465. ogg_stream_packetpeek(&os_de,NULL);
  106466. ogg_stream_packetout(&os_de,&op_de); /* just catching them all */
  106467. /* verify peek and out match */
  106468. if(memcmp(&op_de,&op_de2,sizeof(op_de))){
  106469. fprintf(stderr,"packetout != packetpeek! pos=%ld\n",
  106470. depacket);
  106471. exit(1);
  106472. }
  106473. /* verify the packet! */
  106474. /* check data */
  106475. if(memcmp(data+depacket,op_de.packet,op_de.bytes)){
  106476. fprintf(stderr,"packet data mismatch in decode! pos=%ld\n",
  106477. depacket);
  106478. exit(1);
  106479. }
  106480. /* check bos flag */
  106481. if(bosflag==0 && op_de.b_o_s==0){
  106482. fprintf(stderr,"b_o_s flag not set on packet!\n");
  106483. exit(1);
  106484. }
  106485. if(bosflag && op_de.b_o_s){
  106486. fprintf(stderr,"b_o_s flag incorrectly set on packet!\n");
  106487. exit(1);
  106488. }
  106489. bosflag=1;
  106490. depacket+=op_de.bytes;
  106491. /* check eos flag */
  106492. if(eosflag){
  106493. fprintf(stderr,"Multiple decoded packets with eos flag!\n");
  106494. exit(1);
  106495. }
  106496. if(op_de.e_o_s)eosflag=1;
  106497. /* check granulepos flag */
  106498. if(op_de.granulepos!=-1){
  106499. fprintf(stderr," granule:%ld ",(long)op_de.granulepos);
  106500. }
  106501. }
  106502. }
  106503. }
  106504. }
  106505. }
  106506. }
  106507. _ogg_free(data);
  106508. if(headers[pageno]!=NULL){
  106509. fprintf(stderr,"did not write last page!\n");
  106510. exit(1);
  106511. }
  106512. if(headers[pageout]!=NULL){
  106513. fprintf(stderr,"did not decode last page!\n");
  106514. exit(1);
  106515. }
  106516. if(inptr!=outptr){
  106517. fprintf(stderr,"encoded page data incomplete!\n");
  106518. exit(1);
  106519. }
  106520. if(inptr!=deptr){
  106521. fprintf(stderr,"decoded page data incomplete!\n");
  106522. exit(1);
  106523. }
  106524. if(inptr!=depacket){
  106525. fprintf(stderr,"decoded packet data incomplete!\n");
  106526. exit(1);
  106527. }
  106528. if(!eosflag){
  106529. fprintf(stderr,"Never got a packet with EOS set!\n");
  106530. exit(1);
  106531. }
  106532. fprintf(stderr,"ok.\n");
  106533. }
  106534. int main(void){
  106535. ogg_stream_init(&os_en,0x04030201);
  106536. ogg_stream_init(&os_de,0x04030201);
  106537. ogg_sync_init(&oy);
  106538. /* Exercise each code path in the framing code. Also verify that
  106539. the checksums are working. */
  106540. {
  106541. /* 17 only */
  106542. const int packets[]={17, -1};
  106543. const int *headret[]={head1_0,NULL};
  106544. fprintf(stderr,"testing single page encoding... ");
  106545. test_pack(packets,headret,0,0,0);
  106546. }
  106547. {
  106548. /* 17, 254, 255, 256, 500, 510, 600 byte, pad */
  106549. const int packets[]={17, 254, 255, 256, 500, 510, 600, -1};
  106550. const int *headret[]={head1_1,head2_1,NULL};
  106551. fprintf(stderr,"testing basic page encoding... ");
  106552. test_pack(packets,headret,0,0,0);
  106553. }
  106554. {
  106555. /* nil packets; beginning,middle,end */
  106556. const int packets[]={0,17, 254, 255, 0, 256, 0, 500, 510, 600, 0, -1};
  106557. const int *headret[]={head1_2,head2_2,NULL};
  106558. fprintf(stderr,"testing basic nil packets... ");
  106559. test_pack(packets,headret,0,0,0);
  106560. }
  106561. {
  106562. /* large initial packet */
  106563. const int packets[]={4345,259,255,-1};
  106564. const int *headret[]={head1_3,head2_3,NULL};
  106565. fprintf(stderr,"testing initial-packet lacing > 4k... ");
  106566. test_pack(packets,headret,0,0,0);
  106567. }
  106568. {
  106569. /* continuing packet test */
  106570. const int packets[]={0,4345,259,255,-1};
  106571. const int *headret[]={head1_4,head2_4,head3_4,NULL};
  106572. fprintf(stderr,"testing single packet page span... ");
  106573. test_pack(packets,headret,0,0,0);
  106574. }
  106575. /* page with the 255 segment limit */
  106576. {
  106577. const int packets[]={0,10,10,10,10,10,10,10,10,
  106578. 10,10,10,10,10,10,10,10,
  106579. 10,10,10,10,10,10,10,10,
  106580. 10,10,10,10,10,10,10,10,
  106581. 10,10,10,10,10,10,10,10,
  106582. 10,10,10,10,10,10,10,10,
  106583. 10,10,10,10,10,10,10,10,
  106584. 10,10,10,10,10,10,10,10,
  106585. 10,10,10,10,10,10,10,10,
  106586. 10,10,10,10,10,10,10,10,
  106587. 10,10,10,10,10,10,10,10,
  106588. 10,10,10,10,10,10,10,10,
  106589. 10,10,10,10,10,10,10,10,
  106590. 10,10,10,10,10,10,10,10,
  106591. 10,10,10,10,10,10,10,10,
  106592. 10,10,10,10,10,10,10,10,
  106593. 10,10,10,10,10,10,10,10,
  106594. 10,10,10,10,10,10,10,10,
  106595. 10,10,10,10,10,10,10,10,
  106596. 10,10,10,10,10,10,10,10,
  106597. 10,10,10,10,10,10,10,10,
  106598. 10,10,10,10,10,10,10,10,
  106599. 10,10,10,10,10,10,10,10,
  106600. 10,10,10,10,10,10,10,10,
  106601. 10,10,10,10,10,10,10,10,
  106602. 10,10,10,10,10,10,10,10,
  106603. 10,10,10,10,10,10,10,10,
  106604. 10,10,10,10,10,10,10,10,
  106605. 10,10,10,10,10,10,10,10,
  106606. 10,10,10,10,10,10,10,10,
  106607. 10,10,10,10,10,10,10,10,
  106608. 10,10,10,10,10,10,10,50,-1};
  106609. const int *headret[]={head1_5,head2_5,head3_5,NULL};
  106610. fprintf(stderr,"testing max packet segments... ");
  106611. test_pack(packets,headret,0,0,0);
  106612. }
  106613. {
  106614. /* packet that overspans over an entire page */
  106615. const int packets[]={0,100,9000,259,255,-1};
  106616. const int *headret[]={head1_6,head2_6,head3_6,head4_6,NULL};
  106617. fprintf(stderr,"testing very large packets... ");
  106618. test_pack(packets,headret,0,0,0);
  106619. }
  106620. {
  106621. /* test for the libogg 1.1.1 resync in large continuation bug
  106622. found by Josh Coalson) */
  106623. const int packets[]={0,100,9000,259,255,-1};
  106624. const int *headret[]={head1_6,head2_6,head3_6,head4_6,NULL};
  106625. fprintf(stderr,"testing continuation resync in very large packets... ");
  106626. test_pack(packets,headret,100,2,3);
  106627. }
  106628. {
  106629. /* term only page. why not? */
  106630. const int packets[]={0,100,4080,-1};
  106631. const int *headret[]={head1_7,head2_7,head3_7,NULL};
  106632. fprintf(stderr,"testing zero data page (1 nil packet)... ");
  106633. test_pack(packets,headret,0,0,0);
  106634. }
  106635. {
  106636. /* build a bunch of pages for testing */
  106637. unsigned char *data=_ogg_malloc(1024*1024);
  106638. int pl[]={0,100,4079,2956,2057,76,34,912,0,234,1000,1000,1000,300,-1};
  106639. int inptr=0,i,j;
  106640. ogg_page og[5];
  106641. ogg_stream_reset(&os_en);
  106642. for(i=0;pl[i]!=-1;i++){
  106643. ogg_packet op;
  106644. int len=pl[i];
  106645. op.packet=data+inptr;
  106646. op.bytes=len;
  106647. op.e_o_s=(pl[i+1]<0?1:0);
  106648. op.granulepos=(i+1)*1000;
  106649. for(j=0;j<len;j++)data[inptr++]=i+j;
  106650. ogg_stream_packetin(&os_en,&op);
  106651. }
  106652. _ogg_free(data);
  106653. /* retrieve finished pages */
  106654. for(i=0;i<5;i++){
  106655. if(ogg_stream_pageout(&os_en,&og[i])==0){
  106656. fprintf(stderr,"Too few pages output building sync tests!\n");
  106657. exit(1);
  106658. }
  106659. copy_page(&og[i]);
  106660. }
  106661. /* Test lost pages on pagein/packetout: no rollback */
  106662. {
  106663. ogg_page temp;
  106664. ogg_packet test;
  106665. fprintf(stderr,"Testing loss of pages... ");
  106666. ogg_sync_reset(&oy);
  106667. ogg_stream_reset(&os_de);
  106668. for(i=0;i<5;i++){
  106669. memcpy(ogg_sync_buffer(&oy,og[i].header_len),og[i].header,
  106670. og[i].header_len);
  106671. ogg_sync_wrote(&oy,og[i].header_len);
  106672. memcpy(ogg_sync_buffer(&oy,og[i].body_len),og[i].body,og[i].body_len);
  106673. ogg_sync_wrote(&oy,og[i].body_len);
  106674. }
  106675. ogg_sync_pageout(&oy,&temp);
  106676. ogg_stream_pagein(&os_de,&temp);
  106677. ogg_sync_pageout(&oy,&temp);
  106678. ogg_stream_pagein(&os_de,&temp);
  106679. ogg_sync_pageout(&oy,&temp);
  106680. /* skip */
  106681. ogg_sync_pageout(&oy,&temp);
  106682. ogg_stream_pagein(&os_de,&temp);
  106683. /* do we get the expected results/packets? */
  106684. if(ogg_stream_packetout(&os_de,&test)!=1)error();
  106685. checkpacket(&test,0,0,0);
  106686. if(ogg_stream_packetout(&os_de,&test)!=1)error();
  106687. checkpacket(&test,100,1,-1);
  106688. if(ogg_stream_packetout(&os_de,&test)!=1)error();
  106689. checkpacket(&test,4079,2,3000);
  106690. if(ogg_stream_packetout(&os_de,&test)!=-1){
  106691. fprintf(stderr,"Error: loss of page did not return error\n");
  106692. exit(1);
  106693. }
  106694. if(ogg_stream_packetout(&os_de,&test)!=1)error();
  106695. checkpacket(&test,76,5,-1);
  106696. if(ogg_stream_packetout(&os_de,&test)!=1)error();
  106697. checkpacket(&test,34,6,-1);
  106698. fprintf(stderr,"ok.\n");
  106699. }
  106700. /* Test lost pages on pagein/packetout: rollback with continuation */
  106701. {
  106702. ogg_page temp;
  106703. ogg_packet test;
  106704. fprintf(stderr,"Testing loss of pages (rollback required)... ");
  106705. ogg_sync_reset(&oy);
  106706. ogg_stream_reset(&os_de);
  106707. for(i=0;i<5;i++){
  106708. memcpy(ogg_sync_buffer(&oy,og[i].header_len),og[i].header,
  106709. og[i].header_len);
  106710. ogg_sync_wrote(&oy,og[i].header_len);
  106711. memcpy(ogg_sync_buffer(&oy,og[i].body_len),og[i].body,og[i].body_len);
  106712. ogg_sync_wrote(&oy,og[i].body_len);
  106713. }
  106714. ogg_sync_pageout(&oy,&temp);
  106715. ogg_stream_pagein(&os_de,&temp);
  106716. ogg_sync_pageout(&oy,&temp);
  106717. ogg_stream_pagein(&os_de,&temp);
  106718. ogg_sync_pageout(&oy,&temp);
  106719. ogg_stream_pagein(&os_de,&temp);
  106720. ogg_sync_pageout(&oy,&temp);
  106721. /* skip */
  106722. ogg_sync_pageout(&oy,&temp);
  106723. ogg_stream_pagein(&os_de,&temp);
  106724. /* do we get the expected results/packets? */
  106725. if(ogg_stream_packetout(&os_de,&test)!=1)error();
  106726. checkpacket(&test,0,0,0);
  106727. if(ogg_stream_packetout(&os_de,&test)!=1)error();
  106728. checkpacket(&test,100,1,-1);
  106729. if(ogg_stream_packetout(&os_de,&test)!=1)error();
  106730. checkpacket(&test,4079,2,3000);
  106731. if(ogg_stream_packetout(&os_de,&test)!=1)error();
  106732. checkpacket(&test,2956,3,4000);
  106733. if(ogg_stream_packetout(&os_de,&test)!=-1){
  106734. fprintf(stderr,"Error: loss of page did not return error\n");
  106735. exit(1);
  106736. }
  106737. if(ogg_stream_packetout(&os_de,&test)!=1)error();
  106738. checkpacket(&test,300,13,14000);
  106739. fprintf(stderr,"ok.\n");
  106740. }
  106741. /* the rest only test sync */
  106742. {
  106743. ogg_page og_de;
  106744. /* Test fractional page inputs: incomplete capture */
  106745. fprintf(stderr,"Testing sync on partial inputs... ");
  106746. ogg_sync_reset(&oy);
  106747. memcpy(ogg_sync_buffer(&oy,og[1].header_len),og[1].header,
  106748. 3);
  106749. ogg_sync_wrote(&oy,3);
  106750. if(ogg_sync_pageout(&oy,&og_de)>0)error();
  106751. /* Test fractional page inputs: incomplete fixed header */
  106752. memcpy(ogg_sync_buffer(&oy,og[1].header_len),og[1].header+3,
  106753. 20);
  106754. ogg_sync_wrote(&oy,20);
  106755. if(ogg_sync_pageout(&oy,&og_de)>0)error();
  106756. /* Test fractional page inputs: incomplete header */
  106757. memcpy(ogg_sync_buffer(&oy,og[1].header_len),og[1].header+23,
  106758. 5);
  106759. ogg_sync_wrote(&oy,5);
  106760. if(ogg_sync_pageout(&oy,&og_de)>0)error();
  106761. /* Test fractional page inputs: incomplete body */
  106762. memcpy(ogg_sync_buffer(&oy,og[1].header_len),og[1].header+28,
  106763. og[1].header_len-28);
  106764. ogg_sync_wrote(&oy,og[1].header_len-28);
  106765. if(ogg_sync_pageout(&oy,&og_de)>0)error();
  106766. memcpy(ogg_sync_buffer(&oy,og[1].body_len),og[1].body,1000);
  106767. ogg_sync_wrote(&oy,1000);
  106768. if(ogg_sync_pageout(&oy,&og_de)>0)error();
  106769. memcpy(ogg_sync_buffer(&oy,og[1].body_len),og[1].body+1000,
  106770. og[1].body_len-1000);
  106771. ogg_sync_wrote(&oy,og[1].body_len-1000);
  106772. if(ogg_sync_pageout(&oy,&og_de)<=0)error();
  106773. fprintf(stderr,"ok.\n");
  106774. }
  106775. /* Test fractional page inputs: page + incomplete capture */
  106776. {
  106777. ogg_page og_de;
  106778. fprintf(stderr,"Testing sync on 1+partial inputs... ");
  106779. ogg_sync_reset(&oy);
  106780. memcpy(ogg_sync_buffer(&oy,og[1].header_len),og[1].header,
  106781. og[1].header_len);
  106782. ogg_sync_wrote(&oy,og[1].header_len);
  106783. memcpy(ogg_sync_buffer(&oy,og[1].body_len),og[1].body,
  106784. og[1].body_len);
  106785. ogg_sync_wrote(&oy,og[1].body_len);
  106786. memcpy(ogg_sync_buffer(&oy,og[1].header_len),og[1].header,
  106787. 20);
  106788. ogg_sync_wrote(&oy,20);
  106789. if(ogg_sync_pageout(&oy,&og_de)<=0)error();
  106790. if(ogg_sync_pageout(&oy,&og_de)>0)error();
  106791. memcpy(ogg_sync_buffer(&oy,og[1].header_len),og[1].header+20,
  106792. og[1].header_len-20);
  106793. ogg_sync_wrote(&oy,og[1].header_len-20);
  106794. memcpy(ogg_sync_buffer(&oy,og[1].body_len),og[1].body,
  106795. og[1].body_len);
  106796. ogg_sync_wrote(&oy,og[1].body_len);
  106797. if(ogg_sync_pageout(&oy,&og_de)<=0)error();
  106798. fprintf(stderr,"ok.\n");
  106799. }
  106800. /* Test recapture: garbage + page */
  106801. {
  106802. ogg_page og_de;
  106803. fprintf(stderr,"Testing search for capture... ");
  106804. ogg_sync_reset(&oy);
  106805. /* 'garbage' */
  106806. memcpy(ogg_sync_buffer(&oy,og[1].body_len),og[1].body,
  106807. og[1].body_len);
  106808. ogg_sync_wrote(&oy,og[1].body_len);
  106809. memcpy(ogg_sync_buffer(&oy,og[1].header_len),og[1].header,
  106810. og[1].header_len);
  106811. ogg_sync_wrote(&oy,og[1].header_len);
  106812. memcpy(ogg_sync_buffer(&oy,og[1].body_len),og[1].body,
  106813. og[1].body_len);
  106814. ogg_sync_wrote(&oy,og[1].body_len);
  106815. memcpy(ogg_sync_buffer(&oy,og[2].header_len),og[2].header,
  106816. 20);
  106817. ogg_sync_wrote(&oy,20);
  106818. if(ogg_sync_pageout(&oy,&og_de)>0)error();
  106819. if(ogg_sync_pageout(&oy,&og_de)<=0)error();
  106820. if(ogg_sync_pageout(&oy,&og_de)>0)error();
  106821. memcpy(ogg_sync_buffer(&oy,og[2].header_len),og[2].header+20,
  106822. og[2].header_len-20);
  106823. ogg_sync_wrote(&oy,og[2].header_len-20);
  106824. memcpy(ogg_sync_buffer(&oy,og[2].body_len),og[2].body,
  106825. og[2].body_len);
  106826. ogg_sync_wrote(&oy,og[2].body_len);
  106827. if(ogg_sync_pageout(&oy,&og_de)<=0)error();
  106828. fprintf(stderr,"ok.\n");
  106829. }
  106830. /* Test recapture: page + garbage + page */
  106831. {
  106832. ogg_page og_de;
  106833. fprintf(stderr,"Testing recapture... ");
  106834. ogg_sync_reset(&oy);
  106835. memcpy(ogg_sync_buffer(&oy,og[1].header_len),og[1].header,
  106836. og[1].header_len);
  106837. ogg_sync_wrote(&oy,og[1].header_len);
  106838. memcpy(ogg_sync_buffer(&oy,og[1].body_len),og[1].body,
  106839. og[1].body_len);
  106840. ogg_sync_wrote(&oy,og[1].body_len);
  106841. memcpy(ogg_sync_buffer(&oy,og[2].header_len),og[2].header,
  106842. og[2].header_len);
  106843. ogg_sync_wrote(&oy,og[2].header_len);
  106844. memcpy(ogg_sync_buffer(&oy,og[2].header_len),og[2].header,
  106845. og[2].header_len);
  106846. ogg_sync_wrote(&oy,og[2].header_len);
  106847. if(ogg_sync_pageout(&oy,&og_de)<=0)error();
  106848. memcpy(ogg_sync_buffer(&oy,og[2].body_len),og[2].body,
  106849. og[2].body_len-5);
  106850. ogg_sync_wrote(&oy,og[2].body_len-5);
  106851. memcpy(ogg_sync_buffer(&oy,og[3].header_len),og[3].header,
  106852. og[3].header_len);
  106853. ogg_sync_wrote(&oy,og[3].header_len);
  106854. memcpy(ogg_sync_buffer(&oy,og[3].body_len),og[3].body,
  106855. og[3].body_len);
  106856. ogg_sync_wrote(&oy,og[3].body_len);
  106857. if(ogg_sync_pageout(&oy,&og_de)>0)error();
  106858. if(ogg_sync_pageout(&oy,&og_de)<=0)error();
  106859. fprintf(stderr,"ok.\n");
  106860. }
  106861. /* Free page data that was previously copied */
  106862. {
  106863. for(i=0;i<5;i++){
  106864. free_page(&og[i]);
  106865. }
  106866. }
  106867. }
  106868. return(0);
  106869. }
  106870. #endif
  106871. #endif
  106872. /*** End of inlined file: framing.c ***/
  106873. /*** Start of inlined file: analysis.c ***/
  106874. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  106875. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  106876. // tasks..
  106877. #if JUCE_MSVC
  106878. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  106879. #endif
  106880. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  106881. #if JUCE_USE_OGGVORBIS
  106882. #include <stdio.h>
  106883. #include <string.h>
  106884. #include <math.h>
  106885. /*** Start of inlined file: codec_internal.h ***/
  106886. #ifndef _V_CODECI_H_
  106887. #define _V_CODECI_H_
  106888. /*** Start of inlined file: envelope.h ***/
  106889. #ifndef _V_ENVELOPE_
  106890. #define _V_ENVELOPE_
  106891. /*** Start of inlined file: mdct.h ***/
  106892. #ifndef _OGG_mdct_H_
  106893. #define _OGG_mdct_H_
  106894. /*#define MDCT_INTEGERIZED <- be warned there could be some hurt left here*/
  106895. #ifdef MDCT_INTEGERIZED
  106896. #define DATA_TYPE int
  106897. #define REG_TYPE register int
  106898. #define TRIGBITS 14
  106899. #define cPI3_8 6270
  106900. #define cPI2_8 11585
  106901. #define cPI1_8 15137
  106902. #define FLOAT_CONV(x) ((int)((x)*(1<<TRIGBITS)+.5))
  106903. #define MULT_NORM(x) ((x)>>TRIGBITS)
  106904. #define HALVE(x) ((x)>>1)
  106905. #else
  106906. #define DATA_TYPE float
  106907. #define REG_TYPE float
  106908. #define cPI3_8 .38268343236508977175F
  106909. #define cPI2_8 .70710678118654752441F
  106910. #define cPI1_8 .92387953251128675613F
  106911. #define FLOAT_CONV(x) (x)
  106912. #define MULT_NORM(x) (x)
  106913. #define HALVE(x) ((x)*.5f)
  106914. #endif
  106915. typedef struct {
  106916. int n;
  106917. int log2n;
  106918. DATA_TYPE *trig;
  106919. int *bitrev;
  106920. DATA_TYPE scale;
  106921. } mdct_lookup;
  106922. extern void mdct_init(mdct_lookup *lookup,int n);
  106923. extern void mdct_clear(mdct_lookup *l);
  106924. extern void mdct_forward(mdct_lookup *init, DATA_TYPE *in, DATA_TYPE *out);
  106925. extern void mdct_backward(mdct_lookup *init, DATA_TYPE *in, DATA_TYPE *out);
  106926. #endif
  106927. /*** End of inlined file: mdct.h ***/
  106928. #define VE_PRE 16
  106929. #define VE_WIN 4
  106930. #define VE_POST 2
  106931. #define VE_AMP (VE_PRE+VE_POST-1)
  106932. #define VE_BANDS 7
  106933. #define VE_NEARDC 15
  106934. #define VE_MINSTRETCH 2 /* a bit less than short block */
  106935. #define VE_MAXSTRETCH 12 /* one-third full block */
  106936. typedef struct {
  106937. float ampbuf[VE_AMP];
  106938. int ampptr;
  106939. float nearDC[VE_NEARDC];
  106940. float nearDC_acc;
  106941. float nearDC_partialacc;
  106942. int nearptr;
  106943. } envelope_filter_state;
  106944. typedef struct {
  106945. int begin;
  106946. int end;
  106947. float *window;
  106948. float total;
  106949. } envelope_band;
  106950. typedef struct {
  106951. int ch;
  106952. int winlength;
  106953. int searchstep;
  106954. float minenergy;
  106955. mdct_lookup mdct;
  106956. float *mdct_win;
  106957. envelope_band band[VE_BANDS];
  106958. envelope_filter_state *filter;
  106959. int stretch;
  106960. int *mark;
  106961. long storage;
  106962. long current;
  106963. long curmark;
  106964. long cursor;
  106965. } envelope_lookup;
  106966. extern void _ve_envelope_init(envelope_lookup *e,vorbis_info *vi);
  106967. extern void _ve_envelope_clear(envelope_lookup *e);
  106968. extern long _ve_envelope_search(vorbis_dsp_state *v);
  106969. extern void _ve_envelope_shift(envelope_lookup *e,long shift);
  106970. extern int _ve_envelope_mark(vorbis_dsp_state *v);
  106971. #endif
  106972. /*** End of inlined file: envelope.h ***/
  106973. /*** Start of inlined file: codebook.h ***/
  106974. #ifndef _V_CODEBOOK_H_
  106975. #define _V_CODEBOOK_H_
  106976. /* This structure encapsulates huffman and VQ style encoding books; it
  106977. doesn't do anything specific to either.
  106978. valuelist/quantlist are nonNULL (and q_* significant) only if
  106979. there's entry->value mapping to be done.
  106980. If encode-side mapping must be done (and thus the entry needs to be
  106981. hunted), the auxiliary encode pointer will point to a decision
  106982. tree. This is true of both VQ and huffman, but is mostly useful
  106983. with VQ.
  106984. */
  106985. typedef struct static_codebook{
  106986. long dim; /* codebook dimensions (elements per vector) */
  106987. long entries; /* codebook entries */
  106988. long *lengthlist; /* codeword lengths in bits */
  106989. /* mapping ***************************************************************/
  106990. int maptype; /* 0=none
  106991. 1=implicitly populated values from map column
  106992. 2=listed arbitrary values */
  106993. /* The below does a linear, single monotonic sequence mapping. */
  106994. long q_min; /* packed 32 bit float; quant value 0 maps to minval */
  106995. long q_delta; /* packed 32 bit float; val 1 - val 0 == delta */
  106996. int q_quant; /* bits: 0 < quant <= 16 */
  106997. int q_sequencep; /* bitflag */
  106998. long *quantlist; /* map == 1: (int)(entries^(1/dim)) element column map
  106999. map == 2: list of dim*entries quantized entry vals
  107000. */
  107001. /* encode helpers ********************************************************/
  107002. struct encode_aux_nearestmatch *nearest_tree;
  107003. struct encode_aux_threshmatch *thresh_tree;
  107004. struct encode_aux_pigeonhole *pigeon_tree;
  107005. int allocedp;
  107006. } static_codebook;
  107007. /* this structures an arbitrary trained book to quickly find the
  107008. nearest cell match */
  107009. typedef struct encode_aux_nearestmatch{
  107010. /* pre-calculated partitioning tree */
  107011. long *ptr0;
  107012. long *ptr1;
  107013. long *p; /* decision points (each is an entry) */
  107014. long *q; /* decision points (each is an entry) */
  107015. long aux; /* number of tree entries */
  107016. long alloc;
  107017. } encode_aux_nearestmatch;
  107018. /* assumes a maptype of 1; encode side only, so that's OK */
  107019. typedef struct encode_aux_threshmatch{
  107020. float *quantthresh;
  107021. long *quantmap;
  107022. int quantvals;
  107023. int threshvals;
  107024. } encode_aux_threshmatch;
  107025. typedef struct encode_aux_pigeonhole{
  107026. float min;
  107027. float del;
  107028. int mapentries;
  107029. int quantvals;
  107030. long *pigeonmap;
  107031. long fittotal;
  107032. long *fitlist;
  107033. long *fitmap;
  107034. long *fitlength;
  107035. } encode_aux_pigeonhole;
  107036. typedef struct codebook{
  107037. long dim; /* codebook dimensions (elements per vector) */
  107038. long entries; /* codebook entries */
  107039. long used_entries; /* populated codebook entries */
  107040. const static_codebook *c;
  107041. /* for encode, the below are entry-ordered, fully populated */
  107042. /* for decode, the below are ordered by bitreversed codeword and only
  107043. used entries are populated */
  107044. float *valuelist; /* list of dim*entries actual entry values */
  107045. ogg_uint32_t *codelist; /* list of bitstream codewords for each entry */
  107046. int *dec_index; /* only used if sparseness collapsed */
  107047. char *dec_codelengths;
  107048. ogg_uint32_t *dec_firsttable;
  107049. int dec_firsttablen;
  107050. int dec_maxlength;
  107051. } codebook;
  107052. extern void vorbis_staticbook_clear(static_codebook *b);
  107053. extern void vorbis_staticbook_destroy(static_codebook *b);
  107054. extern int vorbis_book_init_encode(codebook *dest,const static_codebook *source);
  107055. extern int vorbis_book_init_decode(codebook *dest,const static_codebook *source);
  107056. extern void vorbis_book_clear(codebook *b);
  107057. extern float *_book_unquantize(const static_codebook *b,int n,int *map);
  107058. extern float *_book_logdist(const static_codebook *b,float *vals);
  107059. extern float _float32_unpack(long val);
  107060. extern long _float32_pack(float val);
  107061. extern int _best(codebook *book, float *a, int step);
  107062. extern int _ilog(unsigned int v);
  107063. extern long _book_maptype1_quantvals(const static_codebook *b);
  107064. extern int vorbis_book_besterror(codebook *book,float *a,int step,int addmul);
  107065. extern long vorbis_book_codeword(codebook *book,int entry);
  107066. extern long vorbis_book_codelen(codebook *book,int entry);
  107067. extern int vorbis_staticbook_pack(const static_codebook *c,oggpack_buffer *b);
  107068. extern int vorbis_staticbook_unpack(oggpack_buffer *b,static_codebook *c);
  107069. extern int vorbis_book_encode(codebook *book, int a, oggpack_buffer *b);
  107070. extern int vorbis_book_errorv(codebook *book, float *a);
  107071. extern int vorbis_book_encodev(codebook *book, int best,float *a,
  107072. oggpack_buffer *b);
  107073. extern long vorbis_book_decode(codebook *book, oggpack_buffer *b);
  107074. extern long vorbis_book_decodevs_add(codebook *book, float *a,
  107075. oggpack_buffer *b,int n);
  107076. extern long vorbis_book_decodev_set(codebook *book, float *a,
  107077. oggpack_buffer *b,int n);
  107078. extern long vorbis_book_decodev_add(codebook *book, float *a,
  107079. oggpack_buffer *b,int n);
  107080. extern long vorbis_book_decodevv_add(codebook *book, float **a,
  107081. long off,int ch,
  107082. oggpack_buffer *b,int n);
  107083. #endif
  107084. /*** End of inlined file: codebook.h ***/
  107085. #define BLOCKTYPE_IMPULSE 0
  107086. #define BLOCKTYPE_PADDING 1
  107087. #define BLOCKTYPE_TRANSITION 0
  107088. #define BLOCKTYPE_LONG 1
  107089. #define PACKETBLOBS 15
  107090. typedef struct vorbis_block_internal{
  107091. float **pcmdelay; /* this is a pointer into local storage */
  107092. float ampmax;
  107093. int blocktype;
  107094. oggpack_buffer *packetblob[PACKETBLOBS]; /* initialized, must be freed;
  107095. blob [PACKETBLOBS/2] points to
  107096. the oggpack_buffer in the
  107097. main vorbis_block */
  107098. } vorbis_block_internal;
  107099. typedef void vorbis_look_floor;
  107100. typedef void vorbis_look_residue;
  107101. typedef void vorbis_look_transform;
  107102. /* mode ************************************************************/
  107103. typedef struct {
  107104. int blockflag;
  107105. int windowtype;
  107106. int transformtype;
  107107. int mapping;
  107108. } vorbis_info_mode;
  107109. typedef void vorbis_info_floor;
  107110. typedef void vorbis_info_residue;
  107111. typedef void vorbis_info_mapping;
  107112. /*** Start of inlined file: psy.h ***/
  107113. #ifndef _V_PSY_H_
  107114. #define _V_PSY_H_
  107115. /*** Start of inlined file: smallft.h ***/
  107116. #ifndef _V_SMFT_H_
  107117. #define _V_SMFT_H_
  107118. typedef struct {
  107119. int n;
  107120. float *trigcache;
  107121. int *splitcache;
  107122. } drft_lookup;
  107123. extern void drft_forward(drft_lookup *l,float *data);
  107124. extern void drft_backward(drft_lookup *l,float *data);
  107125. extern void drft_init(drft_lookup *l,int n);
  107126. extern void drft_clear(drft_lookup *l);
  107127. #endif
  107128. /*** End of inlined file: smallft.h ***/
  107129. /*** Start of inlined file: backends.h ***/
  107130. /* this is exposed up here because we need it for static modes.
  107131. Lookups for each backend aren't exposed because there's no reason
  107132. to do so */
  107133. #ifndef _vorbis_backend_h_
  107134. #define _vorbis_backend_h_
  107135. /* this would all be simpler/shorter with templates, but.... */
  107136. /* Floor backend generic *****************************************/
  107137. typedef struct{
  107138. void (*pack) (vorbis_info_floor *,oggpack_buffer *);
  107139. vorbis_info_floor *(*unpack)(vorbis_info *,oggpack_buffer *);
  107140. vorbis_look_floor *(*look) (vorbis_dsp_state *,vorbis_info_floor *);
  107141. void (*free_info) (vorbis_info_floor *);
  107142. void (*free_look) (vorbis_look_floor *);
  107143. void *(*inverse1) (struct vorbis_block *,vorbis_look_floor *);
  107144. int (*inverse2) (struct vorbis_block *,vorbis_look_floor *,
  107145. void *buffer,float *);
  107146. } vorbis_func_floor;
  107147. typedef struct{
  107148. int order;
  107149. long rate;
  107150. long barkmap;
  107151. int ampbits;
  107152. int ampdB;
  107153. int numbooks; /* <= 16 */
  107154. int books[16];
  107155. float lessthan; /* encode-only config setting hacks for libvorbis */
  107156. float greaterthan; /* encode-only config setting hacks for libvorbis */
  107157. } vorbis_info_floor0;
  107158. #define VIF_POSIT 63
  107159. #define VIF_CLASS 16
  107160. #define VIF_PARTS 31
  107161. typedef struct{
  107162. int partitions; /* 0 to 31 */
  107163. int partitionclass[VIF_PARTS]; /* 0 to 15 */
  107164. int class_dim[VIF_CLASS]; /* 1 to 8 */
  107165. int class_subs[VIF_CLASS]; /* 0,1,2,3 (bits: 1<<n poss) */
  107166. int class_book[VIF_CLASS]; /* subs ^ dim entries */
  107167. int class_subbook[VIF_CLASS][8]; /* [VIF_CLASS][subs] */
  107168. int mult; /* 1 2 3 or 4 */
  107169. int postlist[VIF_POSIT+2]; /* first two implicit */
  107170. /* encode side analysis parameters */
  107171. float maxover;
  107172. float maxunder;
  107173. float maxerr;
  107174. float twofitweight;
  107175. float twofitatten;
  107176. int n;
  107177. } vorbis_info_floor1;
  107178. /* Residue backend generic *****************************************/
  107179. typedef struct{
  107180. void (*pack) (vorbis_info_residue *,oggpack_buffer *);
  107181. vorbis_info_residue *(*unpack)(vorbis_info *,oggpack_buffer *);
  107182. vorbis_look_residue *(*look) (vorbis_dsp_state *,
  107183. vorbis_info_residue *);
  107184. void (*free_info) (vorbis_info_residue *);
  107185. void (*free_look) (vorbis_look_residue *);
  107186. long **(*classx) (struct vorbis_block *,vorbis_look_residue *,
  107187. float **,int *,int);
  107188. int (*forward) (oggpack_buffer *,struct vorbis_block *,
  107189. vorbis_look_residue *,
  107190. float **,float **,int *,int,long **);
  107191. int (*inverse) (struct vorbis_block *,vorbis_look_residue *,
  107192. float **,int *,int);
  107193. } vorbis_func_residue;
  107194. typedef struct vorbis_info_residue0{
  107195. /* block-partitioned VQ coded straight residue */
  107196. long begin;
  107197. long end;
  107198. /* first stage (lossless partitioning) */
  107199. int grouping; /* group n vectors per partition */
  107200. int partitions; /* possible codebooks for a partition */
  107201. int groupbook; /* huffbook for partitioning */
  107202. int secondstages[64]; /* expanded out to pointers in lookup */
  107203. int booklist[256]; /* list of second stage books */
  107204. float classmetric1[64];
  107205. float classmetric2[64];
  107206. } vorbis_info_residue0;
  107207. /* Mapping backend generic *****************************************/
  107208. typedef struct{
  107209. void (*pack) (vorbis_info *,vorbis_info_mapping *,
  107210. oggpack_buffer *);
  107211. vorbis_info_mapping *(*unpack)(vorbis_info *,oggpack_buffer *);
  107212. void (*free_info) (vorbis_info_mapping *);
  107213. int (*forward) (struct vorbis_block *vb);
  107214. int (*inverse) (struct vorbis_block *vb,vorbis_info_mapping *);
  107215. } vorbis_func_mapping;
  107216. typedef struct vorbis_info_mapping0{
  107217. int submaps; /* <= 16 */
  107218. int chmuxlist[256]; /* up to 256 channels in a Vorbis stream */
  107219. int floorsubmap[16]; /* [mux] submap to floors */
  107220. int residuesubmap[16]; /* [mux] submap to residue */
  107221. int coupling_steps;
  107222. int coupling_mag[256];
  107223. int coupling_ang[256];
  107224. } vorbis_info_mapping0;
  107225. #endif
  107226. /*** End of inlined file: backends.h ***/
  107227. #ifndef EHMER_MAX
  107228. #define EHMER_MAX 56
  107229. #endif
  107230. /* psychoacoustic setup ********************************************/
  107231. #define P_BANDS 17 /* 62Hz to 16kHz */
  107232. #define P_LEVELS 8 /* 30dB to 100dB */
  107233. #define P_LEVEL_0 30. /* 30 dB */
  107234. #define P_NOISECURVES 3
  107235. #define NOISE_COMPAND_LEVELS 40
  107236. typedef struct vorbis_info_psy{
  107237. int blockflag;
  107238. float ath_adjatt;
  107239. float ath_maxatt;
  107240. float tone_masteratt[P_NOISECURVES];
  107241. float tone_centerboost;
  107242. float tone_decay;
  107243. float tone_abs_limit;
  107244. float toneatt[P_BANDS];
  107245. int noisemaskp;
  107246. float noisemaxsupp;
  107247. float noisewindowlo;
  107248. float noisewindowhi;
  107249. int noisewindowlomin;
  107250. int noisewindowhimin;
  107251. int noisewindowfixed;
  107252. float noiseoff[P_NOISECURVES][P_BANDS];
  107253. float noisecompand[NOISE_COMPAND_LEVELS];
  107254. float max_curve_dB;
  107255. int normal_channel_p;
  107256. int normal_point_p;
  107257. int normal_start;
  107258. int normal_partition;
  107259. double normal_thresh;
  107260. } vorbis_info_psy;
  107261. typedef struct{
  107262. int eighth_octave_lines;
  107263. /* for block long/short tuning; encode only */
  107264. float preecho_thresh[VE_BANDS];
  107265. float postecho_thresh[VE_BANDS];
  107266. float stretch_penalty;
  107267. float preecho_minenergy;
  107268. float ampmax_att_per_sec;
  107269. /* channel coupling config */
  107270. int coupling_pkHz[PACKETBLOBS];
  107271. int coupling_pointlimit[2][PACKETBLOBS];
  107272. int coupling_prepointamp[PACKETBLOBS];
  107273. int coupling_postpointamp[PACKETBLOBS];
  107274. int sliding_lowpass[2][PACKETBLOBS];
  107275. } vorbis_info_psy_global;
  107276. typedef struct {
  107277. float ampmax;
  107278. int channels;
  107279. vorbis_info_psy_global *gi;
  107280. int coupling_pointlimit[2][P_NOISECURVES];
  107281. } vorbis_look_psy_global;
  107282. typedef struct {
  107283. int n;
  107284. struct vorbis_info_psy *vi;
  107285. float ***tonecurves;
  107286. float **noiseoffset;
  107287. float *ath;
  107288. long *octave; /* in n.ocshift format */
  107289. long *bark;
  107290. long firstoc;
  107291. long shiftoc;
  107292. int eighth_octave_lines; /* power of two, please */
  107293. int total_octave_lines;
  107294. long rate; /* cache it */
  107295. float m_val; /* Masking compensation value */
  107296. } vorbis_look_psy;
  107297. extern void _vp_psy_init(vorbis_look_psy *p,vorbis_info_psy *vi,
  107298. vorbis_info_psy_global *gi,int n,long rate);
  107299. extern void _vp_psy_clear(vorbis_look_psy *p);
  107300. extern void *_vi_psy_dup(void *source);
  107301. extern void _vi_psy_free(vorbis_info_psy *i);
  107302. extern vorbis_info_psy *_vi_psy_copy(vorbis_info_psy *i);
  107303. extern void _vp_remove_floor(vorbis_look_psy *p,
  107304. float *mdct,
  107305. int *icodedflr,
  107306. float *residue,
  107307. int sliding_lowpass);
  107308. extern void _vp_noisemask(vorbis_look_psy *p,
  107309. float *logmdct,
  107310. float *logmask);
  107311. extern void _vp_tonemask(vorbis_look_psy *p,
  107312. float *logfft,
  107313. float *logmask,
  107314. float global_specmax,
  107315. float local_specmax);
  107316. extern void _vp_offset_and_mix(vorbis_look_psy *p,
  107317. float *noise,
  107318. float *tone,
  107319. int offset_select,
  107320. float *logmask,
  107321. float *mdct,
  107322. float *logmdct);
  107323. extern float _vp_ampmax_decay(float amp,vorbis_dsp_state *vd);
  107324. extern float **_vp_quantize_couple_memo(vorbis_block *vb,
  107325. vorbis_info_psy_global *g,
  107326. vorbis_look_psy *p,
  107327. vorbis_info_mapping0 *vi,
  107328. float **mdct);
  107329. extern void _vp_couple(int blobno,
  107330. vorbis_info_psy_global *g,
  107331. vorbis_look_psy *p,
  107332. vorbis_info_mapping0 *vi,
  107333. float **res,
  107334. float **mag_memo,
  107335. int **mag_sort,
  107336. int **ifloor,
  107337. int *nonzero,
  107338. int sliding_lowpass);
  107339. extern void _vp_noise_normalize(vorbis_look_psy *p,
  107340. float *in,float *out,int *sortedindex);
  107341. extern void _vp_noise_normalize_sort(vorbis_look_psy *p,
  107342. float *magnitudes,int *sortedindex);
  107343. extern int **_vp_quantize_couple_sort(vorbis_block *vb,
  107344. vorbis_look_psy *p,
  107345. vorbis_info_mapping0 *vi,
  107346. float **mags);
  107347. extern void hf_reduction(vorbis_info_psy_global *g,
  107348. vorbis_look_psy *p,
  107349. vorbis_info_mapping0 *vi,
  107350. float **mdct);
  107351. #endif
  107352. /*** End of inlined file: psy.h ***/
  107353. /*** Start of inlined file: bitrate.h ***/
  107354. #ifndef _V_BITRATE_H_
  107355. #define _V_BITRATE_H_
  107356. /*** Start of inlined file: os.h ***/
  107357. #ifndef _OS_H
  107358. #define _OS_H
  107359. /********************************************************************
  107360. * *
  107361. * THIS FILE IS PART OF THE OggVorbis SOFTWARE CODEC SOURCE CODE. *
  107362. * USE, DISTRIBUTION AND REPRODUCTION OF THIS LIBRARY SOURCE IS *
  107363. * GOVERNED BY A BSD-STYLE SOURCE LICENSE INCLUDED WITH THIS SOURCE *
  107364. * IN 'COPYING'. PLEASE READ THESE TERMS BEFORE DISTRIBUTING. *
  107365. * *
  107366. * THE OggVorbis SOURCE CODE IS (C) COPYRIGHT 1994-2002 *
  107367. * by the XIPHOPHORUS Company http://www.xiph.org/ *
  107368. * *
  107369. ********************************************************************
  107370. function: #ifdef jail to whip a few platforms into the UNIX ideal.
  107371. last mod: $Id: os.h,v 1.1 2007/06/07 17:49:18 jules_rms Exp $
  107372. ********************************************************************/
  107373. #ifdef HAVE_CONFIG_H
  107374. #include "config.h"
  107375. #endif
  107376. #include <math.h>
  107377. /*** Start of inlined file: misc.h ***/
  107378. #ifndef _V_RANDOM_H_
  107379. #define _V_RANDOM_H_
  107380. extern int analysis_noisy;
  107381. extern void *_vorbis_block_alloc(vorbis_block *vb,long bytes);
  107382. extern void _vorbis_block_ripcord(vorbis_block *vb);
  107383. extern void _analysis_output(char *base,int i,float *v,int n,int bark,int dB,
  107384. ogg_int64_t off);
  107385. #ifdef DEBUG_MALLOC
  107386. #define _VDBG_GRAPHFILE "malloc.m"
  107387. extern void *_VDBG_malloc(void *ptr,long bytes,char *file,long line);
  107388. extern void _VDBG_free(void *ptr,char *file,long line);
  107389. #ifndef MISC_C
  107390. #undef _ogg_malloc
  107391. #undef _ogg_calloc
  107392. #undef _ogg_realloc
  107393. #undef _ogg_free
  107394. #define _ogg_malloc(x) _VDBG_malloc(NULL,(x),__FILE__,__LINE__)
  107395. #define _ogg_calloc(x,y) _VDBG_malloc(NULL,(x)*(y),__FILE__,__LINE__)
  107396. #define _ogg_realloc(x,y) _VDBG_malloc((x),(y),__FILE__,__LINE__)
  107397. #define _ogg_free(x) _VDBG_free((x),__FILE__,__LINE__)
  107398. #endif
  107399. #endif
  107400. #endif
  107401. /*** End of inlined file: misc.h ***/
  107402. #ifndef _V_IFDEFJAIL_H_
  107403. # define _V_IFDEFJAIL_H_
  107404. # ifdef __GNUC__
  107405. # define STIN static __inline__
  107406. # elif _WIN32
  107407. # define STIN static __inline
  107408. # else
  107409. # define STIN static
  107410. # endif
  107411. #ifdef DJGPP
  107412. # define rint(x) (floor((x)+0.5f))
  107413. #endif
  107414. #ifndef M_PI
  107415. # define M_PI (3.1415926536f)
  107416. #endif
  107417. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  107418. # include <malloc.h>
  107419. # define rint(x) (floor((x)+0.5f))
  107420. # define NO_FLOAT_MATH_LIB
  107421. # define FAST_HYPOT(a, b) sqrt((a)*(a) + (b)*(b))
  107422. #endif
  107423. #if defined(__SYMBIAN32__) && defined(__WINS__)
  107424. void *_alloca(size_t size);
  107425. # define alloca _alloca
  107426. #endif
  107427. #ifndef FAST_HYPOT
  107428. # define FAST_HYPOT hypot
  107429. #endif
  107430. #endif
  107431. #ifdef HAVE_ALLOCA_H
  107432. # include <alloca.h>
  107433. #endif
  107434. #ifdef USE_MEMORY_H
  107435. # include <memory.h>
  107436. #endif
  107437. #ifndef min
  107438. # define min(x,y) ((x)>(y)?(y):(x))
  107439. #endif
  107440. #ifndef max
  107441. # define max(x,y) ((x)<(y)?(y):(x))
  107442. #endif
  107443. #if defined(__i386__) && defined(__GNUC__) && !defined(__BEOS__)
  107444. # define VORBIS_FPU_CONTROL
  107445. /* both GCC and MSVC are kinda stupid about rounding/casting to int.
  107446. Because of encapsulation constraints (GCC can't see inside the asm
  107447. block and so we end up doing stupid things like a store/load that
  107448. is collectively a noop), we do it this way */
  107449. /* we must set up the fpu before this works!! */
  107450. typedef ogg_int16_t vorbis_fpu_control;
  107451. static inline void vorbis_fpu_setround(vorbis_fpu_control *fpu){
  107452. ogg_int16_t ret;
  107453. ogg_int16_t temp;
  107454. __asm__ __volatile__("fnstcw %0\n\t"
  107455. "movw %0,%%dx\n\t"
  107456. "orw $62463,%%dx\n\t"
  107457. "movw %%dx,%1\n\t"
  107458. "fldcw %1\n\t":"=m"(ret):"m"(temp): "dx");
  107459. *fpu=ret;
  107460. }
  107461. static inline void vorbis_fpu_restore(vorbis_fpu_control fpu){
  107462. __asm__ __volatile__("fldcw %0":: "m"(fpu));
  107463. }
  107464. /* assumes the FPU is in round mode! */
  107465. static inline int vorbis_ftoi(double f){ /* yes, double! Otherwise,
  107466. we get extra fst/fld to
  107467. truncate precision */
  107468. int i;
  107469. __asm__("fistl %0": "=m"(i) : "t"(f));
  107470. return(i);
  107471. }
  107472. #endif
  107473. #if defined(_WIN32) && defined(_X86_) && !defined(__GNUC__) && !defined(__BORLANDC__)
  107474. # define VORBIS_FPU_CONTROL
  107475. typedef ogg_int16_t vorbis_fpu_control;
  107476. static __inline int vorbis_ftoi(double f){
  107477. int i;
  107478. __asm{
  107479. fld f
  107480. fistp i
  107481. }
  107482. return i;
  107483. }
  107484. static __inline void vorbis_fpu_setround(vorbis_fpu_control *fpu){
  107485. }
  107486. static __inline void vorbis_fpu_restore(vorbis_fpu_control fpu){
  107487. }
  107488. #endif
  107489. #ifndef VORBIS_FPU_CONTROL
  107490. typedef int vorbis_fpu_control;
  107491. static int vorbis_ftoi(double f){
  107492. return (int)(f+.5);
  107493. }
  107494. /* We don't have special code for this compiler/arch, so do it the slow way */
  107495. # define vorbis_fpu_setround(vorbis_fpu_control) {}
  107496. # define vorbis_fpu_restore(vorbis_fpu_control) {}
  107497. #endif
  107498. #endif /* _OS_H */
  107499. /*** End of inlined file: os.h ***/
  107500. /* encode side bitrate tracking */
  107501. typedef struct bitrate_manager_state {
  107502. int managed;
  107503. long avg_reservoir;
  107504. long minmax_reservoir;
  107505. long avg_bitsper;
  107506. long min_bitsper;
  107507. long max_bitsper;
  107508. long short_per_long;
  107509. double avgfloat;
  107510. vorbis_block *vb;
  107511. int choice;
  107512. } bitrate_manager_state;
  107513. typedef struct bitrate_manager_info{
  107514. long avg_rate;
  107515. long min_rate;
  107516. long max_rate;
  107517. long reservoir_bits;
  107518. double reservoir_bias;
  107519. double slew_damp;
  107520. } bitrate_manager_info;
  107521. extern void vorbis_bitrate_init(vorbis_info *vi,bitrate_manager_state *bs);
  107522. extern void vorbis_bitrate_clear(bitrate_manager_state *bs);
  107523. extern int vorbis_bitrate_managed(vorbis_block *vb);
  107524. extern int vorbis_bitrate_addblock(vorbis_block *vb);
  107525. extern int vorbis_bitrate_flushpacket(vorbis_dsp_state *vd, ogg_packet *op);
  107526. #endif
  107527. /*** End of inlined file: bitrate.h ***/
  107528. static int ilog(unsigned int v){
  107529. int ret=0;
  107530. while(v){
  107531. ret++;
  107532. v>>=1;
  107533. }
  107534. return(ret);
  107535. }
  107536. static int ilog2(unsigned int v){
  107537. int ret=0;
  107538. if(v)--v;
  107539. while(v){
  107540. ret++;
  107541. v>>=1;
  107542. }
  107543. return(ret);
  107544. }
  107545. typedef struct private_state {
  107546. /* local lookup storage */
  107547. envelope_lookup *ve; /* envelope lookup */
  107548. int window[2];
  107549. vorbis_look_transform **transform[2]; /* block, type */
  107550. drft_lookup fft_look[2];
  107551. int modebits;
  107552. vorbis_look_floor **flr;
  107553. vorbis_look_residue **residue;
  107554. vorbis_look_psy *psy;
  107555. vorbis_look_psy_global *psy_g_look;
  107556. /* local storage, only used on the encoding side. This way the
  107557. application does not need to worry about freeing some packets'
  107558. memory and not others'; packet storage is always tracked.
  107559. Cleared next call to a _dsp_ function */
  107560. unsigned char *header;
  107561. unsigned char *header1;
  107562. unsigned char *header2;
  107563. bitrate_manager_state bms;
  107564. ogg_int64_t sample_count;
  107565. } private_state;
  107566. /* codec_setup_info contains all the setup information specific to the
  107567. specific compression/decompression mode in progress (eg,
  107568. psychoacoustic settings, channel setup, options, codebook
  107569. etc).
  107570. *********************************************************************/
  107571. /*** Start of inlined file: highlevel.h ***/
  107572. typedef struct highlevel_byblocktype {
  107573. double tone_mask_setting;
  107574. double tone_peaklimit_setting;
  107575. double noise_bias_setting;
  107576. double noise_compand_setting;
  107577. } highlevel_byblocktype;
  107578. typedef struct highlevel_encode_setup {
  107579. void *setup;
  107580. int set_in_stone;
  107581. double base_setting;
  107582. double long_setting;
  107583. double short_setting;
  107584. double impulse_noisetune;
  107585. int managed;
  107586. long bitrate_min;
  107587. long bitrate_av;
  107588. double bitrate_av_damp;
  107589. long bitrate_max;
  107590. long bitrate_reservoir;
  107591. double bitrate_reservoir_bias;
  107592. int impulse_block_p;
  107593. int noise_normalize_p;
  107594. double stereo_point_setting;
  107595. double lowpass_kHz;
  107596. double ath_floating_dB;
  107597. double ath_absolute_dB;
  107598. double amplitude_track_dBpersec;
  107599. double trigger_setting;
  107600. highlevel_byblocktype block[4]; /* padding, impulse, transition, long */
  107601. } highlevel_encode_setup;
  107602. /*** End of inlined file: highlevel.h ***/
  107603. typedef struct codec_setup_info {
  107604. /* Vorbis supports only short and long blocks, but allows the
  107605. encoder to choose the sizes */
  107606. long blocksizes[2];
  107607. /* modes are the primary means of supporting on-the-fly different
  107608. blocksizes, different channel mappings (LR or M/A),
  107609. different residue backends, etc. Each mode consists of a
  107610. blocksize flag and a mapping (along with the mapping setup */
  107611. int modes;
  107612. int maps;
  107613. int floors;
  107614. int residues;
  107615. int books;
  107616. int psys; /* encode only */
  107617. vorbis_info_mode *mode_param[64];
  107618. int map_type[64];
  107619. vorbis_info_mapping *map_param[64];
  107620. int floor_type[64];
  107621. vorbis_info_floor *floor_param[64];
  107622. int residue_type[64];
  107623. vorbis_info_residue *residue_param[64];
  107624. static_codebook *book_param[256];
  107625. codebook *fullbooks;
  107626. vorbis_info_psy *psy_param[4]; /* encode only */
  107627. vorbis_info_psy_global psy_g_param;
  107628. bitrate_manager_info bi;
  107629. highlevel_encode_setup hi; /* used only by vorbisenc.c. It's a
  107630. highly redundant structure, but
  107631. improves clarity of program flow. */
  107632. int halfrate_flag; /* painless downsample for decode */
  107633. } codec_setup_info;
  107634. extern vorbis_look_psy_global *_vp_global_look(vorbis_info *vi);
  107635. extern void _vp_global_free(vorbis_look_psy_global *look);
  107636. #endif
  107637. /*** End of inlined file: codec_internal.h ***/
  107638. /*** Start of inlined file: registry.h ***/
  107639. #ifndef _V_REG_H_
  107640. #define _V_REG_H_
  107641. #define VI_TRANSFORMB 1
  107642. #define VI_WINDOWB 1
  107643. #define VI_TIMEB 1
  107644. #define VI_FLOORB 2
  107645. #define VI_RESB 3
  107646. #define VI_MAPB 1
  107647. extern vorbis_func_floor *_floor_P[];
  107648. extern vorbis_func_residue *_residue_P[];
  107649. extern vorbis_func_mapping *_mapping_P[];
  107650. #endif
  107651. /*** End of inlined file: registry.h ***/
  107652. /*** Start of inlined file: scales.h ***/
  107653. #ifndef _V_SCALES_H_
  107654. #define _V_SCALES_H_
  107655. #include <math.h>
  107656. /* 20log10(x) */
  107657. #define VORBIS_IEEE_FLOAT32 1
  107658. #ifdef VORBIS_IEEE_FLOAT32
  107659. static float unitnorm(float x){
  107660. union {
  107661. ogg_uint32_t i;
  107662. float f;
  107663. } ix;
  107664. ix.f = x;
  107665. ix.i = (ix.i & 0x80000000U) | (0x3f800000U);
  107666. return ix.f;
  107667. }
  107668. /* Segher was off (too high) by ~ .3 decibel. Center the conversion correctly. */
  107669. static float todB(const float *x){
  107670. union {
  107671. ogg_uint32_t i;
  107672. float f;
  107673. } ix;
  107674. ix.f = *x;
  107675. ix.i = ix.i&0x7fffffff;
  107676. return (float)(ix.i * 7.17711438e-7f -764.6161886f);
  107677. }
  107678. #define todB_nn(x) todB(x)
  107679. #else
  107680. static float unitnorm(float x){
  107681. if(x<0)return(-1.f);
  107682. return(1.f);
  107683. }
  107684. #define todB(x) (*(x)==0?-400.f:log(*(x)**(x))*4.34294480f)
  107685. #define todB_nn(x) (*(x)==0.f?-400.f:log(*(x))*8.6858896f)
  107686. #endif
  107687. #define fromdB(x) (exp((x)*.11512925f))
  107688. /* The bark scale equations are approximations, since the original
  107689. table was somewhat hand rolled. The below are chosen to have the
  107690. best possible fit to the rolled tables, thus their somewhat odd
  107691. appearance (these are more accurate and over a longer range than
  107692. the oft-quoted bark equations found in the texts I have). The
  107693. approximations are valid from 0 - 30kHz (nyquist) or so.
  107694. all f in Hz, z in Bark */
  107695. #define toBARK(n) (13.1f*atan(.00074f*(n))+2.24f*atan((n)*(n)*1.85e-8f)+1e-4f*(n))
  107696. #define fromBARK(z) (102.f*(z)-2.f*pow(z,2.f)+.4f*pow(z,3.f)+pow(1.46f,z)-1.f)
  107697. #define toMEL(n) (log(1.f+(n)*.001f)*1442.695f)
  107698. #define fromMEL(m) (1000.f*exp((m)/1442.695f)-1000.f)
  107699. /* Frequency to octave. We arbitrarily declare 63.5 Hz to be octave
  107700. 0.0 */
  107701. #define toOC(n) (log(n)*1.442695f-5.965784f)
  107702. #define fromOC(o) (exp(((o)+5.965784f)*.693147f))
  107703. #endif
  107704. /*** End of inlined file: scales.h ***/
  107705. int analysis_noisy=1;
  107706. /* decides between modes, dispatches to the appropriate mapping. */
  107707. int vorbis_analysis(vorbis_block *vb, ogg_packet *op){
  107708. int ret,i;
  107709. vorbis_block_internal *vbi=(vorbis_block_internal *)vb->internal;
  107710. vb->glue_bits=0;
  107711. vb->time_bits=0;
  107712. vb->floor_bits=0;
  107713. vb->res_bits=0;
  107714. /* first things first. Make sure encode is ready */
  107715. for(i=0;i<PACKETBLOBS;i++)
  107716. oggpack_reset(vbi->packetblob[i]);
  107717. /* we only have one mapping type (0), and we let the mapping code
  107718. itself figure out what soft mode to use. This allows easier
  107719. bitrate management */
  107720. if((ret=_mapping_P[0]->forward(vb)))
  107721. return(ret);
  107722. if(op){
  107723. if(vorbis_bitrate_managed(vb))
  107724. /* The app is using a bitmanaged mode... but not using the
  107725. bitrate management interface. */
  107726. return(OV_EINVAL);
  107727. op->packet=oggpack_get_buffer(&vb->opb);
  107728. op->bytes=oggpack_bytes(&vb->opb);
  107729. op->b_o_s=0;
  107730. op->e_o_s=vb->eofflag;
  107731. op->granulepos=vb->granulepos;
  107732. op->packetno=vb->sequence; /* for sake of completeness */
  107733. }
  107734. return(0);
  107735. }
  107736. /* there was no great place to put this.... */
  107737. void _analysis_output_always(const char *base,int i,float *v,int n,int bark,int dB,ogg_int64_t off){
  107738. int j;
  107739. FILE *of;
  107740. char buffer[80];
  107741. /* if(i==5870){*/
  107742. sprintf(buffer,"%s_%d.m",base,i);
  107743. of=fopen(buffer,"w");
  107744. if(!of)perror("failed to open data dump file");
  107745. for(j=0;j<n;j++){
  107746. if(bark){
  107747. float b=toBARK((4000.f*j/n)+.25);
  107748. fprintf(of,"%f ",b);
  107749. }else
  107750. if(off!=0)
  107751. fprintf(of,"%f ",(double)(j+off)/8000.);
  107752. else
  107753. fprintf(of,"%f ",(double)j);
  107754. if(dB){
  107755. float val;
  107756. if(v[j]==0.)
  107757. val=-140.;
  107758. else
  107759. val=todB(v+j);
  107760. fprintf(of,"%f\n",val);
  107761. }else{
  107762. fprintf(of,"%f\n",v[j]);
  107763. }
  107764. }
  107765. fclose(of);
  107766. /* } */
  107767. }
  107768. void _analysis_output(char *base,int i,float *v,int n,int bark,int dB,
  107769. ogg_int64_t off){
  107770. if(analysis_noisy)_analysis_output_always(base,i,v,n,bark,dB,off);
  107771. }
  107772. #endif
  107773. /*** End of inlined file: analysis.c ***/
  107774. /*** Start of inlined file: bitrate.c ***/
  107775. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  107776. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  107777. // tasks..
  107778. #if JUCE_MSVC
  107779. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  107780. #endif
  107781. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  107782. #if JUCE_USE_OGGVORBIS
  107783. #include <stdlib.h>
  107784. #include <string.h>
  107785. #include <math.h>
  107786. /* compute bitrate tracking setup */
  107787. void vorbis_bitrate_init(vorbis_info *vi,bitrate_manager_state *bm){
  107788. codec_setup_info *ci=(codec_setup_info *)vi->codec_setup;
  107789. bitrate_manager_info *bi=&ci->bi;
  107790. memset(bm,0,sizeof(*bm));
  107791. if(bi && (bi->reservoir_bits>0)){
  107792. long ratesamples=vi->rate;
  107793. int halfsamples=ci->blocksizes[0]>>1;
  107794. bm->short_per_long=ci->blocksizes[1]/ci->blocksizes[0];
  107795. bm->managed=1;
  107796. bm->avg_bitsper= rint(1.*bi->avg_rate*halfsamples/ratesamples);
  107797. bm->min_bitsper= rint(1.*bi->min_rate*halfsamples/ratesamples);
  107798. bm->max_bitsper= rint(1.*bi->max_rate*halfsamples/ratesamples);
  107799. bm->avgfloat=PACKETBLOBS/2;
  107800. /* not a necessary fix, but one that leads to a more balanced
  107801. typical initialization */
  107802. {
  107803. long desired_fill=bi->reservoir_bits*bi->reservoir_bias;
  107804. bm->minmax_reservoir=desired_fill;
  107805. bm->avg_reservoir=desired_fill;
  107806. }
  107807. }
  107808. }
  107809. void vorbis_bitrate_clear(bitrate_manager_state *bm){
  107810. memset(bm,0,sizeof(*bm));
  107811. return;
  107812. }
  107813. int vorbis_bitrate_managed(vorbis_block *vb){
  107814. vorbis_dsp_state *vd=vb->vd;
  107815. private_state *b=(private_state*)vd->backend_state;
  107816. bitrate_manager_state *bm=&b->bms;
  107817. if(bm && bm->managed)return(1);
  107818. return(0);
  107819. }
  107820. /* finish taking in the block we just processed */
  107821. int vorbis_bitrate_addblock(vorbis_block *vb){
  107822. vorbis_block_internal *vbi=(vorbis_block_internal*)vb->internal;
  107823. vorbis_dsp_state *vd=vb->vd;
  107824. private_state *b=(private_state*)vd->backend_state;
  107825. bitrate_manager_state *bm=&b->bms;
  107826. vorbis_info *vi=vd->vi;
  107827. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  107828. bitrate_manager_info *bi=&ci->bi;
  107829. int choice=rint(bm->avgfloat);
  107830. long this_bits=oggpack_bytes(vbi->packetblob[choice])*8;
  107831. long min_target_bits=(vb->W?bm->min_bitsper*bm->short_per_long:bm->min_bitsper);
  107832. long max_target_bits=(vb->W?bm->max_bitsper*bm->short_per_long:bm->max_bitsper);
  107833. int samples=ci->blocksizes[vb->W]>>1;
  107834. long desired_fill=bi->reservoir_bits*bi->reservoir_bias;
  107835. if(!bm->managed){
  107836. /* not a bitrate managed stream, but for API simplicity, we'll
  107837. buffer the packet to keep the code path clean */
  107838. if(bm->vb)return(-1); /* one has been submitted without
  107839. being claimed */
  107840. bm->vb=vb;
  107841. return(0);
  107842. }
  107843. bm->vb=vb;
  107844. /* look ahead for avg floater */
  107845. if(bm->avg_bitsper>0){
  107846. double slew=0.;
  107847. long avg_target_bits=(vb->W?bm->avg_bitsper*bm->short_per_long:bm->avg_bitsper);
  107848. double slewlimit= 15./bi->slew_damp;
  107849. /* choosing a new floater:
  107850. if we're over target, we slew down
  107851. if we're under target, we slew up
  107852. choose slew as follows: look through packetblobs of this frame
  107853. and set slew as the first in the appropriate direction that
  107854. gives us the slew we want. This may mean no slew if delta is
  107855. already favorable.
  107856. Then limit slew to slew max */
  107857. if(bm->avg_reservoir+(this_bits-avg_target_bits)>desired_fill){
  107858. while(choice>0 && this_bits>avg_target_bits &&
  107859. bm->avg_reservoir+(this_bits-avg_target_bits)>desired_fill){
  107860. choice--;
  107861. this_bits=oggpack_bytes(vbi->packetblob[choice])*8;
  107862. }
  107863. }else if(bm->avg_reservoir+(this_bits-avg_target_bits)<desired_fill){
  107864. while(choice+1<PACKETBLOBS && this_bits<avg_target_bits &&
  107865. bm->avg_reservoir+(this_bits-avg_target_bits)<desired_fill){
  107866. choice++;
  107867. this_bits=oggpack_bytes(vbi->packetblob[choice])*8;
  107868. }
  107869. }
  107870. slew=rint(choice-bm->avgfloat)/samples*vi->rate;
  107871. if(slew<-slewlimit)slew=-slewlimit;
  107872. if(slew>slewlimit)slew=slewlimit;
  107873. choice=rint(bm->avgfloat+= slew/vi->rate*samples);
  107874. this_bits=oggpack_bytes(vbi->packetblob[choice])*8;
  107875. }
  107876. /* enforce min(if used) on the current floater (if used) */
  107877. if(bm->min_bitsper>0){
  107878. /* do we need to force the bitrate up? */
  107879. if(this_bits<min_target_bits){
  107880. while(bm->minmax_reservoir-(min_target_bits-this_bits)<0){
  107881. choice++;
  107882. if(choice>=PACKETBLOBS)break;
  107883. this_bits=oggpack_bytes(vbi->packetblob[choice])*8;
  107884. }
  107885. }
  107886. }
  107887. /* enforce max (if used) on the current floater (if used) */
  107888. if(bm->max_bitsper>0){
  107889. /* do we need to force the bitrate down? */
  107890. if(this_bits>max_target_bits){
  107891. while(bm->minmax_reservoir+(this_bits-max_target_bits)>bi->reservoir_bits){
  107892. choice--;
  107893. if(choice<0)break;
  107894. this_bits=oggpack_bytes(vbi->packetblob[choice])*8;
  107895. }
  107896. }
  107897. }
  107898. /* Choice of packetblobs now made based on floater, and min/max
  107899. requirements. Now boundary check extreme choices */
  107900. if(choice<0){
  107901. /* choosing a smaller packetblob is insufficient to trim bitrate.
  107902. frame will need to be truncated */
  107903. long maxsize=(max_target_bits+(bi->reservoir_bits-bm->minmax_reservoir))/8;
  107904. bm->choice=choice=0;
  107905. if(oggpack_bytes(vbi->packetblob[choice])>maxsize){
  107906. oggpack_writetrunc(vbi->packetblob[choice],maxsize*8);
  107907. this_bits=oggpack_bytes(vbi->packetblob[choice])*8;
  107908. }
  107909. }else{
  107910. long minsize=(min_target_bits-bm->minmax_reservoir+7)/8;
  107911. if(choice>=PACKETBLOBS)
  107912. choice=PACKETBLOBS-1;
  107913. bm->choice=choice;
  107914. /* prop up bitrate according to demand. pad this frame out with zeroes */
  107915. minsize-=oggpack_bytes(vbi->packetblob[choice]);
  107916. while(minsize-->0)oggpack_write(vbi->packetblob[choice],0,8);
  107917. this_bits=oggpack_bytes(vbi->packetblob[choice])*8;
  107918. }
  107919. /* now we have the final packet and the final packet size. Update statistics */
  107920. /* min and max reservoir */
  107921. if(bm->min_bitsper>0 || bm->max_bitsper>0){
  107922. if(max_target_bits>0 && this_bits>max_target_bits){
  107923. bm->minmax_reservoir+=(this_bits-max_target_bits);
  107924. }else if(min_target_bits>0 && this_bits<min_target_bits){
  107925. bm->minmax_reservoir+=(this_bits-min_target_bits);
  107926. }else{
  107927. /* inbetween; we want to take reservoir toward but not past desired_fill */
  107928. if(bm->minmax_reservoir>desired_fill){
  107929. if(max_target_bits>0){ /* logical bulletproofing against initialization state */
  107930. bm->minmax_reservoir+=(this_bits-max_target_bits);
  107931. if(bm->minmax_reservoir<desired_fill)bm->minmax_reservoir=desired_fill;
  107932. }else{
  107933. bm->minmax_reservoir=desired_fill;
  107934. }
  107935. }else{
  107936. if(min_target_bits>0){ /* logical bulletproofing against initialization state */
  107937. bm->minmax_reservoir+=(this_bits-min_target_bits);
  107938. if(bm->minmax_reservoir>desired_fill)bm->minmax_reservoir=desired_fill;
  107939. }else{
  107940. bm->minmax_reservoir=desired_fill;
  107941. }
  107942. }
  107943. }
  107944. }
  107945. /* avg reservoir */
  107946. if(bm->avg_bitsper>0){
  107947. long avg_target_bits=(vb->W?bm->avg_bitsper*bm->short_per_long:bm->avg_bitsper);
  107948. bm->avg_reservoir+=this_bits-avg_target_bits;
  107949. }
  107950. return(0);
  107951. }
  107952. int vorbis_bitrate_flushpacket(vorbis_dsp_state *vd,ogg_packet *op){
  107953. private_state *b=(private_state*)vd->backend_state;
  107954. bitrate_manager_state *bm=&b->bms;
  107955. vorbis_block *vb=bm->vb;
  107956. int choice=PACKETBLOBS/2;
  107957. if(!vb)return 0;
  107958. if(op){
  107959. vorbis_block_internal *vbi=(vorbis_block_internal*)vb->internal;
  107960. if(vorbis_bitrate_managed(vb))
  107961. choice=bm->choice;
  107962. op->packet=oggpack_get_buffer(vbi->packetblob[choice]);
  107963. op->bytes=oggpack_bytes(vbi->packetblob[choice]);
  107964. op->b_o_s=0;
  107965. op->e_o_s=vb->eofflag;
  107966. op->granulepos=vb->granulepos;
  107967. op->packetno=vb->sequence; /* for sake of completeness */
  107968. }
  107969. bm->vb=0;
  107970. return(1);
  107971. }
  107972. #endif
  107973. /*** End of inlined file: bitrate.c ***/
  107974. /*** Start of inlined file: block.c ***/
  107975. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  107976. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  107977. // tasks..
  107978. #if JUCE_MSVC
  107979. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  107980. #endif
  107981. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  107982. #if JUCE_USE_OGGVORBIS
  107983. #include <stdio.h>
  107984. #include <stdlib.h>
  107985. #include <string.h>
  107986. /*** Start of inlined file: window.h ***/
  107987. #ifndef _V_WINDOW_
  107988. #define _V_WINDOW_
  107989. extern float *_vorbis_window_get(int n);
  107990. extern void _vorbis_apply_window(float *d,int *winno,long *blocksizes,
  107991. int lW,int W,int nW);
  107992. #endif
  107993. /*** End of inlined file: window.h ***/
  107994. /*** Start of inlined file: lpc.h ***/
  107995. #ifndef _V_LPC_H_
  107996. #define _V_LPC_H_
  107997. /* simple linear scale LPC code */
  107998. extern float vorbis_lpc_from_data(float *data,float *lpc,int n,int m);
  107999. extern void vorbis_lpc_predict(float *coeff,float *prime,int m,
  108000. float *data,long n);
  108001. #endif
  108002. /*** End of inlined file: lpc.h ***/
  108003. /* pcm accumulator examples (not exhaustive):
  108004. <-------------- lW ---------------->
  108005. <--------------- W ---------------->
  108006. : .....|..... _______________ |
  108007. : .''' | '''_--- | |\ |
  108008. :.....''' |_____--- '''......| | \_______|
  108009. :.................|__________________|_______|__|______|
  108010. |<------ Sl ------>| > Sr < |endW
  108011. |beginSl |endSl | |endSr
  108012. |beginW |endlW |beginSr
  108013. |< lW >|
  108014. <--------------- W ---------------->
  108015. | | .. ______________ |
  108016. | | ' `/ | ---_ |
  108017. |___.'___/`. | ---_____|
  108018. |_______|__|_______|_________________|
  108019. | >|Sl|< |<------ Sr ----->|endW
  108020. | | |endSl |beginSr |endSr
  108021. |beginW | |endlW
  108022. mult[0] |beginSl mult[n]
  108023. <-------------- lW ----------------->
  108024. |<--W-->|
  108025. : .............. ___ | |
  108026. : .''' |`/ \ | |
  108027. :.....''' |/`....\|...|
  108028. :.........................|___|___|___|
  108029. |Sl |Sr |endW
  108030. | | |endSr
  108031. | |beginSr
  108032. | |endSl
  108033. |beginSl
  108034. |beginW
  108035. */
  108036. /* block abstraction setup *********************************************/
  108037. #ifndef WORD_ALIGN
  108038. #define WORD_ALIGN 8
  108039. #endif
  108040. int vorbis_block_init(vorbis_dsp_state *v, vorbis_block *vb){
  108041. int i;
  108042. memset(vb,0,sizeof(*vb));
  108043. vb->vd=v;
  108044. vb->localalloc=0;
  108045. vb->localstore=NULL;
  108046. if(v->analysisp){
  108047. vorbis_block_internal *vbi=(vorbis_block_internal*)
  108048. (vb->internal=(vorbis_block_internal*)_ogg_calloc(1,sizeof(vorbis_block_internal)));
  108049. vbi->ampmax=-9999;
  108050. for(i=0;i<PACKETBLOBS;i++){
  108051. if(i==PACKETBLOBS/2){
  108052. vbi->packetblob[i]=&vb->opb;
  108053. }else{
  108054. vbi->packetblob[i]=
  108055. (oggpack_buffer*) _ogg_calloc(1,sizeof(oggpack_buffer));
  108056. }
  108057. oggpack_writeinit(vbi->packetblob[i]);
  108058. }
  108059. }
  108060. return(0);
  108061. }
  108062. void *_vorbis_block_alloc(vorbis_block *vb,long bytes){
  108063. bytes=(bytes+(WORD_ALIGN-1)) & ~(WORD_ALIGN-1);
  108064. if(bytes+vb->localtop>vb->localalloc){
  108065. /* can't just _ogg_realloc... there are outstanding pointers */
  108066. if(vb->localstore){
  108067. struct alloc_chain *link=(struct alloc_chain*)_ogg_malloc(sizeof(*link));
  108068. vb->totaluse+=vb->localtop;
  108069. link->next=vb->reap;
  108070. link->ptr=vb->localstore;
  108071. vb->reap=link;
  108072. }
  108073. /* highly conservative */
  108074. vb->localalloc=bytes;
  108075. vb->localstore=_ogg_malloc(vb->localalloc);
  108076. vb->localtop=0;
  108077. }
  108078. {
  108079. void *ret=(void *)(((char *)vb->localstore)+vb->localtop);
  108080. vb->localtop+=bytes;
  108081. return ret;
  108082. }
  108083. }
  108084. /* reap the chain, pull the ripcord */
  108085. void _vorbis_block_ripcord(vorbis_block *vb){
  108086. /* reap the chain */
  108087. struct alloc_chain *reap=vb->reap;
  108088. while(reap){
  108089. struct alloc_chain *next=reap->next;
  108090. _ogg_free(reap->ptr);
  108091. memset(reap,0,sizeof(*reap));
  108092. _ogg_free(reap);
  108093. reap=next;
  108094. }
  108095. /* consolidate storage */
  108096. if(vb->totaluse){
  108097. vb->localstore=_ogg_realloc(vb->localstore,vb->totaluse+vb->localalloc);
  108098. vb->localalloc+=vb->totaluse;
  108099. vb->totaluse=0;
  108100. }
  108101. /* pull the ripcord */
  108102. vb->localtop=0;
  108103. vb->reap=NULL;
  108104. }
  108105. int vorbis_block_clear(vorbis_block *vb){
  108106. int i;
  108107. vorbis_block_internal *vbi=(vorbis_block_internal*)vb->internal;
  108108. _vorbis_block_ripcord(vb);
  108109. if(vb->localstore)_ogg_free(vb->localstore);
  108110. if(vbi){
  108111. for(i=0;i<PACKETBLOBS;i++){
  108112. oggpack_writeclear(vbi->packetblob[i]);
  108113. if(i!=PACKETBLOBS/2)_ogg_free(vbi->packetblob[i]);
  108114. }
  108115. _ogg_free(vbi);
  108116. }
  108117. memset(vb,0,sizeof(*vb));
  108118. return(0);
  108119. }
  108120. /* Analysis side code, but directly related to blocking. Thus it's
  108121. here and not in analysis.c (which is for analysis transforms only).
  108122. The init is here because some of it is shared */
  108123. static int _vds_shared_init(vorbis_dsp_state *v,vorbis_info *vi,int encp){
  108124. int i;
  108125. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  108126. private_state *b=NULL;
  108127. int hs;
  108128. if(ci==NULL) return 1;
  108129. hs=ci->halfrate_flag;
  108130. memset(v,0,sizeof(*v));
  108131. b=(private_state*) (v->backend_state=(private_state*)_ogg_calloc(1,sizeof(*b)));
  108132. v->vi=vi;
  108133. b->modebits=ilog2(ci->modes);
  108134. b->transform[0]=(vorbis_look_transform**)_ogg_calloc(VI_TRANSFORMB,sizeof(*b->transform[0]));
  108135. b->transform[1]=(vorbis_look_transform**)_ogg_calloc(VI_TRANSFORMB,sizeof(*b->transform[1]));
  108136. /* MDCT is tranform 0 */
  108137. b->transform[0][0]=_ogg_calloc(1,sizeof(mdct_lookup));
  108138. b->transform[1][0]=_ogg_calloc(1,sizeof(mdct_lookup));
  108139. mdct_init((mdct_lookup*)b->transform[0][0],ci->blocksizes[0]>>hs);
  108140. mdct_init((mdct_lookup*)b->transform[1][0],ci->blocksizes[1]>>hs);
  108141. /* Vorbis I uses only window type 0 */
  108142. b->window[0]=ilog2(ci->blocksizes[0])-6;
  108143. b->window[1]=ilog2(ci->blocksizes[1])-6;
  108144. if(encp){ /* encode/decode differ here */
  108145. /* analysis always needs an fft */
  108146. drft_init(&b->fft_look[0],ci->blocksizes[0]);
  108147. drft_init(&b->fft_look[1],ci->blocksizes[1]);
  108148. /* finish the codebooks */
  108149. if(!ci->fullbooks){
  108150. ci->fullbooks=(codebook*) _ogg_calloc(ci->books,sizeof(*ci->fullbooks));
  108151. for(i=0;i<ci->books;i++)
  108152. vorbis_book_init_encode(ci->fullbooks+i,ci->book_param[i]);
  108153. }
  108154. b->psy=(vorbis_look_psy*)_ogg_calloc(ci->psys,sizeof(*b->psy));
  108155. for(i=0;i<ci->psys;i++){
  108156. _vp_psy_init(b->psy+i,
  108157. ci->psy_param[i],
  108158. &ci->psy_g_param,
  108159. ci->blocksizes[ci->psy_param[i]->blockflag]/2,
  108160. vi->rate);
  108161. }
  108162. v->analysisp=1;
  108163. }else{
  108164. /* finish the codebooks */
  108165. if(!ci->fullbooks){
  108166. ci->fullbooks=(codebook*) _ogg_calloc(ci->books,sizeof(*ci->fullbooks));
  108167. for(i=0;i<ci->books;i++){
  108168. vorbis_book_init_decode(ci->fullbooks+i,ci->book_param[i]);
  108169. /* decode codebooks are now standalone after init */
  108170. vorbis_staticbook_destroy(ci->book_param[i]);
  108171. ci->book_param[i]=NULL;
  108172. }
  108173. }
  108174. }
  108175. /* initialize the storage vectors. blocksize[1] is small for encode,
  108176. but the correct size for decode */
  108177. v->pcm_storage=ci->blocksizes[1];
  108178. v->pcm=(float**)_ogg_malloc(vi->channels*sizeof(*v->pcm));
  108179. v->pcmret=(float**)_ogg_malloc(vi->channels*sizeof(*v->pcmret));
  108180. {
  108181. int i;
  108182. for(i=0;i<vi->channels;i++)
  108183. v->pcm[i]=(float*)_ogg_calloc(v->pcm_storage,sizeof(*v->pcm[i]));
  108184. }
  108185. /* all 1 (large block) or 0 (small block) */
  108186. /* explicitly set for the sake of clarity */
  108187. v->lW=0; /* previous window size */
  108188. v->W=0; /* current window size */
  108189. /* all vector indexes */
  108190. v->centerW=ci->blocksizes[1]/2;
  108191. v->pcm_current=v->centerW;
  108192. /* initialize all the backend lookups */
  108193. b->flr=(vorbis_look_floor**)_ogg_calloc(ci->floors,sizeof(*b->flr));
  108194. b->residue=(vorbis_look_residue**)_ogg_calloc(ci->residues,sizeof(*b->residue));
  108195. for(i=0;i<ci->floors;i++)
  108196. b->flr[i]=_floor_P[ci->floor_type[i]]->
  108197. look(v,ci->floor_param[i]);
  108198. for(i=0;i<ci->residues;i++)
  108199. b->residue[i]=_residue_P[ci->residue_type[i]]->
  108200. look(v,ci->residue_param[i]);
  108201. return 0;
  108202. }
  108203. /* arbitrary settings and spec-mandated numbers get filled in here */
  108204. int vorbis_analysis_init(vorbis_dsp_state *v,vorbis_info *vi){
  108205. private_state *b=NULL;
  108206. if(_vds_shared_init(v,vi,1))return 1;
  108207. b=(private_state*)v->backend_state;
  108208. b->psy_g_look=_vp_global_look(vi);
  108209. /* Initialize the envelope state storage */
  108210. b->ve=(envelope_lookup*)_ogg_calloc(1,sizeof(*b->ve));
  108211. _ve_envelope_init(b->ve,vi);
  108212. vorbis_bitrate_init(vi,&b->bms);
  108213. /* compressed audio packets start after the headers
  108214. with sequence number 3 */
  108215. v->sequence=3;
  108216. return(0);
  108217. }
  108218. void vorbis_dsp_clear(vorbis_dsp_state *v){
  108219. int i;
  108220. if(v){
  108221. vorbis_info *vi=v->vi;
  108222. codec_setup_info *ci=(codec_setup_info*)(vi?vi->codec_setup:NULL);
  108223. private_state *b=(private_state*)v->backend_state;
  108224. if(b){
  108225. if(b->ve){
  108226. _ve_envelope_clear(b->ve);
  108227. _ogg_free(b->ve);
  108228. }
  108229. if(b->transform[0]){
  108230. mdct_clear((mdct_lookup*) b->transform[0][0]);
  108231. _ogg_free(b->transform[0][0]);
  108232. _ogg_free(b->transform[0]);
  108233. }
  108234. if(b->transform[1]){
  108235. mdct_clear((mdct_lookup*) b->transform[1][0]);
  108236. _ogg_free(b->transform[1][0]);
  108237. _ogg_free(b->transform[1]);
  108238. }
  108239. if(b->flr){
  108240. for(i=0;i<ci->floors;i++)
  108241. _floor_P[ci->floor_type[i]]->
  108242. free_look(b->flr[i]);
  108243. _ogg_free(b->flr);
  108244. }
  108245. if(b->residue){
  108246. for(i=0;i<ci->residues;i++)
  108247. _residue_P[ci->residue_type[i]]->
  108248. free_look(b->residue[i]);
  108249. _ogg_free(b->residue);
  108250. }
  108251. if(b->psy){
  108252. for(i=0;i<ci->psys;i++)
  108253. _vp_psy_clear(b->psy+i);
  108254. _ogg_free(b->psy);
  108255. }
  108256. if(b->psy_g_look)_vp_global_free(b->psy_g_look);
  108257. vorbis_bitrate_clear(&b->bms);
  108258. drft_clear(&b->fft_look[0]);
  108259. drft_clear(&b->fft_look[1]);
  108260. }
  108261. if(v->pcm){
  108262. for(i=0;i<vi->channels;i++)
  108263. if(v->pcm[i])_ogg_free(v->pcm[i]);
  108264. _ogg_free(v->pcm);
  108265. if(v->pcmret)_ogg_free(v->pcmret);
  108266. }
  108267. if(b){
  108268. /* free header, header1, header2 */
  108269. if(b->header)_ogg_free(b->header);
  108270. if(b->header1)_ogg_free(b->header1);
  108271. if(b->header2)_ogg_free(b->header2);
  108272. _ogg_free(b);
  108273. }
  108274. memset(v,0,sizeof(*v));
  108275. }
  108276. }
  108277. float **vorbis_analysis_buffer(vorbis_dsp_state *v, int vals){
  108278. int i;
  108279. vorbis_info *vi=v->vi;
  108280. private_state *b=(private_state*)v->backend_state;
  108281. /* free header, header1, header2 */
  108282. if(b->header)_ogg_free(b->header);b->header=NULL;
  108283. if(b->header1)_ogg_free(b->header1);b->header1=NULL;
  108284. if(b->header2)_ogg_free(b->header2);b->header2=NULL;
  108285. /* Do we have enough storage space for the requested buffer? If not,
  108286. expand the PCM (and envelope) storage */
  108287. if(v->pcm_current+vals>=v->pcm_storage){
  108288. v->pcm_storage=v->pcm_current+vals*2;
  108289. for(i=0;i<vi->channels;i++){
  108290. v->pcm[i]=(float*)_ogg_realloc(v->pcm[i],v->pcm_storage*sizeof(*v->pcm[i]));
  108291. }
  108292. }
  108293. for(i=0;i<vi->channels;i++)
  108294. v->pcmret[i]=v->pcm[i]+v->pcm_current;
  108295. return(v->pcmret);
  108296. }
  108297. static void _preextrapolate_helper(vorbis_dsp_state *v){
  108298. int i;
  108299. int order=32;
  108300. float *lpc=(float*)alloca(order*sizeof(*lpc));
  108301. float *work=(float*)alloca(v->pcm_current*sizeof(*work));
  108302. long j;
  108303. v->preextrapolate=1;
  108304. if(v->pcm_current-v->centerW>order*2){ /* safety */
  108305. for(i=0;i<v->vi->channels;i++){
  108306. /* need to run the extrapolation in reverse! */
  108307. for(j=0;j<v->pcm_current;j++)
  108308. work[j]=v->pcm[i][v->pcm_current-j-1];
  108309. /* prime as above */
  108310. vorbis_lpc_from_data(work,lpc,v->pcm_current-v->centerW,order);
  108311. /* run the predictor filter */
  108312. vorbis_lpc_predict(lpc,work+v->pcm_current-v->centerW-order,
  108313. order,
  108314. work+v->pcm_current-v->centerW,
  108315. v->centerW);
  108316. for(j=0;j<v->pcm_current;j++)
  108317. v->pcm[i][v->pcm_current-j-1]=work[j];
  108318. }
  108319. }
  108320. }
  108321. /* call with val<=0 to set eof */
  108322. int vorbis_analysis_wrote(vorbis_dsp_state *v, int vals){
  108323. vorbis_info *vi=v->vi;
  108324. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  108325. if(vals<=0){
  108326. int order=32;
  108327. int i;
  108328. float *lpc=(float*) alloca(order*sizeof(*lpc));
  108329. /* if it wasn't done earlier (very short sample) */
  108330. if(!v->preextrapolate)
  108331. _preextrapolate_helper(v);
  108332. /* We're encoding the end of the stream. Just make sure we have
  108333. [at least] a few full blocks of zeroes at the end. */
  108334. /* actually, we don't want zeroes; that could drop a large
  108335. amplitude off a cliff, creating spread spectrum noise that will
  108336. suck to encode. Extrapolate for the sake of cleanliness. */
  108337. vorbis_analysis_buffer(v,ci->blocksizes[1]*3);
  108338. v->eofflag=v->pcm_current;
  108339. v->pcm_current+=ci->blocksizes[1]*3;
  108340. for(i=0;i<vi->channels;i++){
  108341. if(v->eofflag>order*2){
  108342. /* extrapolate with LPC to fill in */
  108343. long n;
  108344. /* make a predictor filter */
  108345. n=v->eofflag;
  108346. if(n>ci->blocksizes[1])n=ci->blocksizes[1];
  108347. vorbis_lpc_from_data(v->pcm[i]+v->eofflag-n,lpc,n,order);
  108348. /* run the predictor filter */
  108349. vorbis_lpc_predict(lpc,v->pcm[i]+v->eofflag-order,order,
  108350. v->pcm[i]+v->eofflag,v->pcm_current-v->eofflag);
  108351. }else{
  108352. /* not enough data to extrapolate (unlikely to happen due to
  108353. guarding the overlap, but bulletproof in case that
  108354. assumtion goes away). zeroes will do. */
  108355. memset(v->pcm[i]+v->eofflag,0,
  108356. (v->pcm_current-v->eofflag)*sizeof(*v->pcm[i]));
  108357. }
  108358. }
  108359. }else{
  108360. if(v->pcm_current+vals>v->pcm_storage)
  108361. return(OV_EINVAL);
  108362. v->pcm_current+=vals;
  108363. /* we may want to reverse extrapolate the beginning of a stream
  108364. too... in case we're beginning on a cliff! */
  108365. /* clumsy, but simple. It only runs once, so simple is good. */
  108366. if(!v->preextrapolate && v->pcm_current-v->centerW>ci->blocksizes[1])
  108367. _preextrapolate_helper(v);
  108368. }
  108369. return(0);
  108370. }
  108371. /* do the deltas, envelope shaping, pre-echo and determine the size of
  108372. the next block on which to continue analysis */
  108373. int vorbis_analysis_blockout(vorbis_dsp_state *v,vorbis_block *vb){
  108374. int i;
  108375. vorbis_info *vi=v->vi;
  108376. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  108377. private_state *b=(private_state*)v->backend_state;
  108378. vorbis_look_psy_global *g=b->psy_g_look;
  108379. long beginW=v->centerW-ci->blocksizes[v->W]/2,centerNext;
  108380. vorbis_block_internal *vbi=(vorbis_block_internal *)vb->internal;
  108381. /* check to see if we're started... */
  108382. if(!v->preextrapolate)return(0);
  108383. /* check to see if we're done... */
  108384. if(v->eofflag==-1)return(0);
  108385. /* By our invariant, we have lW, W and centerW set. Search for
  108386. the next boundary so we can determine nW (the next window size)
  108387. which lets us compute the shape of the current block's window */
  108388. /* we do an envelope search even on a single blocksize; we may still
  108389. be throwing more bits at impulses, and envelope search handles
  108390. marking impulses too. */
  108391. {
  108392. long bp=_ve_envelope_search(v);
  108393. if(bp==-1){
  108394. if(v->eofflag==0)return(0); /* not enough data currently to search for a
  108395. full long block */
  108396. v->nW=0;
  108397. }else{
  108398. if(ci->blocksizes[0]==ci->blocksizes[1])
  108399. v->nW=0;
  108400. else
  108401. v->nW=bp;
  108402. }
  108403. }
  108404. centerNext=v->centerW+ci->blocksizes[v->W]/4+ci->blocksizes[v->nW]/4;
  108405. {
  108406. /* center of next block + next block maximum right side. */
  108407. long blockbound=centerNext+ci->blocksizes[v->nW]/2;
  108408. if(v->pcm_current<blockbound)return(0); /* not enough data yet;
  108409. although this check is
  108410. less strict that the
  108411. _ve_envelope_search,
  108412. the search is not run
  108413. if we only use one
  108414. block size */
  108415. }
  108416. /* fill in the block. Note that for a short window, lW and nW are *short*
  108417. regardless of actual settings in the stream */
  108418. _vorbis_block_ripcord(vb);
  108419. vb->lW=v->lW;
  108420. vb->W=v->W;
  108421. vb->nW=v->nW;
  108422. if(v->W){
  108423. if(!v->lW || !v->nW){
  108424. vbi->blocktype=BLOCKTYPE_TRANSITION;
  108425. /*fprintf(stderr,"-");*/
  108426. }else{
  108427. vbi->blocktype=BLOCKTYPE_LONG;
  108428. /*fprintf(stderr,"_");*/
  108429. }
  108430. }else{
  108431. if(_ve_envelope_mark(v)){
  108432. vbi->blocktype=BLOCKTYPE_IMPULSE;
  108433. /*fprintf(stderr,"|");*/
  108434. }else{
  108435. vbi->blocktype=BLOCKTYPE_PADDING;
  108436. /*fprintf(stderr,".");*/
  108437. }
  108438. }
  108439. vb->vd=v;
  108440. vb->sequence=v->sequence++;
  108441. vb->granulepos=v->granulepos;
  108442. vb->pcmend=ci->blocksizes[v->W];
  108443. /* copy the vectors; this uses the local storage in vb */
  108444. /* this tracks 'strongest peak' for later psychoacoustics */
  108445. /* moved to the global psy state; clean this mess up */
  108446. if(vbi->ampmax>g->ampmax)g->ampmax=vbi->ampmax;
  108447. g->ampmax=_vp_ampmax_decay(g->ampmax,v);
  108448. vbi->ampmax=g->ampmax;
  108449. vb->pcm=(float**)_vorbis_block_alloc(vb,sizeof(*vb->pcm)*vi->channels);
  108450. vbi->pcmdelay=(float**)_vorbis_block_alloc(vb,sizeof(*vbi->pcmdelay)*vi->channels);
  108451. for(i=0;i<vi->channels;i++){
  108452. vbi->pcmdelay[i]=
  108453. (float*) _vorbis_block_alloc(vb,(vb->pcmend+beginW)*sizeof(*vbi->pcmdelay[i]));
  108454. memcpy(vbi->pcmdelay[i],v->pcm[i],(vb->pcmend+beginW)*sizeof(*vbi->pcmdelay[i]));
  108455. vb->pcm[i]=vbi->pcmdelay[i]+beginW;
  108456. /* before we added the delay
  108457. vb->pcm[i]=_vorbis_block_alloc(vb,vb->pcmend*sizeof(*vb->pcm[i]));
  108458. memcpy(vb->pcm[i],v->pcm[i]+beginW,ci->blocksizes[v->W]*sizeof(*vb->pcm[i]));
  108459. */
  108460. }
  108461. /* handle eof detection: eof==0 means that we've not yet received EOF
  108462. eof>0 marks the last 'real' sample in pcm[]
  108463. eof<0 'no more to do'; doesn't get here */
  108464. if(v->eofflag){
  108465. if(v->centerW>=v->eofflag){
  108466. v->eofflag=-1;
  108467. vb->eofflag=1;
  108468. return(1);
  108469. }
  108470. }
  108471. /* advance storage vectors and clean up */
  108472. {
  108473. int new_centerNext=ci->blocksizes[1]/2;
  108474. int movementW=centerNext-new_centerNext;
  108475. if(movementW>0){
  108476. _ve_envelope_shift(b->ve,movementW);
  108477. v->pcm_current-=movementW;
  108478. for(i=0;i<vi->channels;i++)
  108479. memmove(v->pcm[i],v->pcm[i]+movementW,
  108480. v->pcm_current*sizeof(*v->pcm[i]));
  108481. v->lW=v->W;
  108482. v->W=v->nW;
  108483. v->centerW=new_centerNext;
  108484. if(v->eofflag){
  108485. v->eofflag-=movementW;
  108486. if(v->eofflag<=0)v->eofflag=-1;
  108487. /* do not add padding to end of stream! */
  108488. if(v->centerW>=v->eofflag){
  108489. v->granulepos+=movementW-(v->centerW-v->eofflag);
  108490. }else{
  108491. v->granulepos+=movementW;
  108492. }
  108493. }else{
  108494. v->granulepos+=movementW;
  108495. }
  108496. }
  108497. }
  108498. /* done */
  108499. return(1);
  108500. }
  108501. int vorbis_synthesis_restart(vorbis_dsp_state *v){
  108502. vorbis_info *vi=v->vi;
  108503. codec_setup_info *ci;
  108504. int hs;
  108505. if(!v->backend_state)return -1;
  108506. if(!vi)return -1;
  108507. ci=(codec_setup_info*) vi->codec_setup;
  108508. if(!ci)return -1;
  108509. hs=ci->halfrate_flag;
  108510. v->centerW=ci->blocksizes[1]>>(hs+1);
  108511. v->pcm_current=v->centerW>>hs;
  108512. v->pcm_returned=-1;
  108513. v->granulepos=-1;
  108514. v->sequence=-1;
  108515. v->eofflag=0;
  108516. ((private_state *)(v->backend_state))->sample_count=-1;
  108517. return(0);
  108518. }
  108519. int vorbis_synthesis_init(vorbis_dsp_state *v,vorbis_info *vi){
  108520. if(_vds_shared_init(v,vi,0)) return 1;
  108521. vorbis_synthesis_restart(v);
  108522. return 0;
  108523. }
  108524. /* Unlike in analysis, the window is only partially applied for each
  108525. block. The time domain envelope is not yet handled at the point of
  108526. calling (as it relies on the previous block). */
  108527. int vorbis_synthesis_blockin(vorbis_dsp_state *v,vorbis_block *vb){
  108528. vorbis_info *vi=v->vi;
  108529. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  108530. private_state *b=(private_state*)v->backend_state;
  108531. int hs=ci->halfrate_flag;
  108532. int i,j;
  108533. if(!vb)return(OV_EINVAL);
  108534. if(v->pcm_current>v->pcm_returned && v->pcm_returned!=-1)return(OV_EINVAL);
  108535. v->lW=v->W;
  108536. v->W=vb->W;
  108537. v->nW=-1;
  108538. if((v->sequence==-1)||
  108539. (v->sequence+1 != vb->sequence)){
  108540. v->granulepos=-1; /* out of sequence; lose count */
  108541. b->sample_count=-1;
  108542. }
  108543. v->sequence=vb->sequence;
  108544. if(vb->pcm){ /* no pcm to process if vorbis_synthesis_trackonly
  108545. was called on block */
  108546. int n=ci->blocksizes[v->W]>>(hs+1);
  108547. int n0=ci->blocksizes[0]>>(hs+1);
  108548. int n1=ci->blocksizes[1]>>(hs+1);
  108549. int thisCenter;
  108550. int prevCenter;
  108551. v->glue_bits+=vb->glue_bits;
  108552. v->time_bits+=vb->time_bits;
  108553. v->floor_bits+=vb->floor_bits;
  108554. v->res_bits+=vb->res_bits;
  108555. if(v->centerW){
  108556. thisCenter=n1;
  108557. prevCenter=0;
  108558. }else{
  108559. thisCenter=0;
  108560. prevCenter=n1;
  108561. }
  108562. /* v->pcm is now used like a two-stage double buffer. We don't want
  108563. to have to constantly shift *or* adjust memory usage. Don't
  108564. accept a new block until the old is shifted out */
  108565. for(j=0;j<vi->channels;j++){
  108566. /* the overlap/add section */
  108567. if(v->lW){
  108568. if(v->W){
  108569. /* large/large */
  108570. float *w=_vorbis_window_get(b->window[1]-hs);
  108571. float *pcm=v->pcm[j]+prevCenter;
  108572. float *p=vb->pcm[j];
  108573. for(i=0;i<n1;i++)
  108574. pcm[i]=pcm[i]*w[n1-i-1] + p[i]*w[i];
  108575. }else{
  108576. /* large/small */
  108577. float *w=_vorbis_window_get(b->window[0]-hs);
  108578. float *pcm=v->pcm[j]+prevCenter+n1/2-n0/2;
  108579. float *p=vb->pcm[j];
  108580. for(i=0;i<n0;i++)
  108581. pcm[i]=pcm[i]*w[n0-i-1] +p[i]*w[i];
  108582. }
  108583. }else{
  108584. if(v->W){
  108585. /* small/large */
  108586. float *w=_vorbis_window_get(b->window[0]-hs);
  108587. float *pcm=v->pcm[j]+prevCenter;
  108588. float *p=vb->pcm[j]+n1/2-n0/2;
  108589. for(i=0;i<n0;i++)
  108590. pcm[i]=pcm[i]*w[n0-i-1] +p[i]*w[i];
  108591. for(;i<n1/2+n0/2;i++)
  108592. pcm[i]=p[i];
  108593. }else{
  108594. /* small/small */
  108595. float *w=_vorbis_window_get(b->window[0]-hs);
  108596. float *pcm=v->pcm[j]+prevCenter;
  108597. float *p=vb->pcm[j];
  108598. for(i=0;i<n0;i++)
  108599. pcm[i]=pcm[i]*w[n0-i-1] +p[i]*w[i];
  108600. }
  108601. }
  108602. /* the copy section */
  108603. {
  108604. float *pcm=v->pcm[j]+thisCenter;
  108605. float *p=vb->pcm[j]+n;
  108606. for(i=0;i<n;i++)
  108607. pcm[i]=p[i];
  108608. }
  108609. }
  108610. if(v->centerW)
  108611. v->centerW=0;
  108612. else
  108613. v->centerW=n1;
  108614. /* deal with initial packet state; we do this using the explicit
  108615. pcm_returned==-1 flag otherwise we're sensitive to first block
  108616. being short or long */
  108617. if(v->pcm_returned==-1){
  108618. v->pcm_returned=thisCenter;
  108619. v->pcm_current=thisCenter;
  108620. }else{
  108621. v->pcm_returned=prevCenter;
  108622. v->pcm_current=prevCenter+
  108623. ((ci->blocksizes[v->lW]/4+
  108624. ci->blocksizes[v->W]/4)>>hs);
  108625. }
  108626. }
  108627. /* track the frame number... This is for convenience, but also
  108628. making sure our last packet doesn't end with added padding. If
  108629. the last packet is partial, the number of samples we'll have to
  108630. return will be past the vb->granulepos.
  108631. This is not foolproof! It will be confused if we begin
  108632. decoding at the last page after a seek or hole. In that case,
  108633. we don't have a starting point to judge where the last frame
  108634. is. For this reason, vorbisfile will always try to make sure
  108635. it reads the last two marked pages in proper sequence */
  108636. if(b->sample_count==-1){
  108637. b->sample_count=0;
  108638. }else{
  108639. b->sample_count+=ci->blocksizes[v->lW]/4+ci->blocksizes[v->W]/4;
  108640. }
  108641. if(v->granulepos==-1){
  108642. if(vb->granulepos!=-1){ /* only set if we have a position to set to */
  108643. v->granulepos=vb->granulepos;
  108644. /* is this a short page? */
  108645. if(b->sample_count>v->granulepos){
  108646. /* corner case; if this is both the first and last audio page,
  108647. then spec says the end is cut, not beginning */
  108648. if(vb->eofflag){
  108649. /* trim the end */
  108650. /* no preceeding granulepos; assume we started at zero (we'd
  108651. have to in a short single-page stream) */
  108652. /* granulepos could be -1 due to a seek, but that would result
  108653. in a long count, not short count */
  108654. v->pcm_current-=(b->sample_count-v->granulepos)>>hs;
  108655. }else{
  108656. /* trim the beginning */
  108657. v->pcm_returned+=(b->sample_count-v->granulepos)>>hs;
  108658. if(v->pcm_returned>v->pcm_current)
  108659. v->pcm_returned=v->pcm_current;
  108660. }
  108661. }
  108662. }
  108663. }else{
  108664. v->granulepos+=ci->blocksizes[v->lW]/4+ci->blocksizes[v->W]/4;
  108665. if(vb->granulepos!=-1 && v->granulepos!=vb->granulepos){
  108666. if(v->granulepos>vb->granulepos){
  108667. long extra=v->granulepos-vb->granulepos;
  108668. if(extra)
  108669. if(vb->eofflag){
  108670. /* partial last frame. Strip the extra samples off */
  108671. v->pcm_current-=extra>>hs;
  108672. } /* else {Shouldn't happen *unless* the bitstream is out of
  108673. spec. Either way, believe the bitstream } */
  108674. } /* else {Shouldn't happen *unless* the bitstream is out of
  108675. spec. Either way, believe the bitstream } */
  108676. v->granulepos=vb->granulepos;
  108677. }
  108678. }
  108679. /* Update, cleanup */
  108680. if(vb->eofflag)v->eofflag=1;
  108681. return(0);
  108682. }
  108683. /* pcm==NULL indicates we just want the pending samples, no more */
  108684. int vorbis_synthesis_pcmout(vorbis_dsp_state *v,float ***pcm){
  108685. vorbis_info *vi=v->vi;
  108686. if(v->pcm_returned>-1 && v->pcm_returned<v->pcm_current){
  108687. if(pcm){
  108688. int i;
  108689. for(i=0;i<vi->channels;i++)
  108690. v->pcmret[i]=v->pcm[i]+v->pcm_returned;
  108691. *pcm=v->pcmret;
  108692. }
  108693. return(v->pcm_current-v->pcm_returned);
  108694. }
  108695. return(0);
  108696. }
  108697. int vorbis_synthesis_read(vorbis_dsp_state *v,int n){
  108698. if(n && v->pcm_returned+n>v->pcm_current)return(OV_EINVAL);
  108699. v->pcm_returned+=n;
  108700. return(0);
  108701. }
  108702. /* intended for use with a specific vorbisfile feature; we want access
  108703. to the [usually synthetic/postextrapolated] buffer and lapping at
  108704. the end of a decode cycle, specifically, a half-short-block worth.
  108705. This funtion works like pcmout above, except it will also expose
  108706. this implicit buffer data not normally decoded. */
  108707. int vorbis_synthesis_lapout(vorbis_dsp_state *v,float ***pcm){
  108708. vorbis_info *vi=v->vi;
  108709. codec_setup_info *ci=(codec_setup_info *)vi->codec_setup;
  108710. int hs=ci->halfrate_flag;
  108711. int n=ci->blocksizes[v->W]>>(hs+1);
  108712. int n0=ci->blocksizes[0]>>(hs+1);
  108713. int n1=ci->blocksizes[1]>>(hs+1);
  108714. int i,j;
  108715. if(v->pcm_returned<0)return 0;
  108716. /* our returned data ends at pcm_returned; because the synthesis pcm
  108717. buffer is a two-fragment ring, that means our data block may be
  108718. fragmented by buffering, wrapping or a short block not filling
  108719. out a buffer. To simplify things, we unfragment if it's at all
  108720. possibly needed. Otherwise, we'd need to call lapout more than
  108721. once as well as hold additional dsp state. Opt for
  108722. simplicity. */
  108723. /* centerW was advanced by blockin; it would be the center of the
  108724. *next* block */
  108725. if(v->centerW==n1){
  108726. /* the data buffer wraps; swap the halves */
  108727. /* slow, sure, small */
  108728. for(j=0;j<vi->channels;j++){
  108729. float *p=v->pcm[j];
  108730. for(i=0;i<n1;i++){
  108731. float temp=p[i];
  108732. p[i]=p[i+n1];
  108733. p[i+n1]=temp;
  108734. }
  108735. }
  108736. v->pcm_current-=n1;
  108737. v->pcm_returned-=n1;
  108738. v->centerW=0;
  108739. }
  108740. /* solidify buffer into contiguous space */
  108741. if((v->lW^v->W)==1){
  108742. /* long/short or short/long */
  108743. for(j=0;j<vi->channels;j++){
  108744. float *s=v->pcm[j];
  108745. float *d=v->pcm[j]+(n1-n0)/2;
  108746. for(i=(n1+n0)/2-1;i>=0;--i)
  108747. d[i]=s[i];
  108748. }
  108749. v->pcm_returned+=(n1-n0)/2;
  108750. v->pcm_current+=(n1-n0)/2;
  108751. }else{
  108752. if(v->lW==0){
  108753. /* short/short */
  108754. for(j=0;j<vi->channels;j++){
  108755. float *s=v->pcm[j];
  108756. float *d=v->pcm[j]+n1-n0;
  108757. for(i=n0-1;i>=0;--i)
  108758. d[i]=s[i];
  108759. }
  108760. v->pcm_returned+=n1-n0;
  108761. v->pcm_current+=n1-n0;
  108762. }
  108763. }
  108764. if(pcm){
  108765. int i;
  108766. for(i=0;i<vi->channels;i++)
  108767. v->pcmret[i]=v->pcm[i]+v->pcm_returned;
  108768. *pcm=v->pcmret;
  108769. }
  108770. return(n1+n-v->pcm_returned);
  108771. }
  108772. float *vorbis_window(vorbis_dsp_state *v,int W){
  108773. vorbis_info *vi=v->vi;
  108774. codec_setup_info *ci=(codec_setup_info*) vi->codec_setup;
  108775. int hs=ci->halfrate_flag;
  108776. private_state *b=(private_state*)v->backend_state;
  108777. if(b->window[W]-1<0)return NULL;
  108778. return _vorbis_window_get(b->window[W]-hs);
  108779. }
  108780. #endif
  108781. /*** End of inlined file: block.c ***/
  108782. /*** Start of inlined file: codebook.c ***/
  108783. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  108784. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  108785. // tasks..
  108786. #if JUCE_MSVC
  108787. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  108788. #endif
  108789. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  108790. #if JUCE_USE_OGGVORBIS
  108791. #include <stdlib.h>
  108792. #include <string.h>
  108793. #include <math.h>
  108794. /* packs the given codebook into the bitstream **************************/
  108795. int vorbis_staticbook_pack(const static_codebook *c,oggpack_buffer *opb){
  108796. long i,j;
  108797. int ordered=0;
  108798. /* first the basic parameters */
  108799. oggpack_write(opb,0x564342,24);
  108800. oggpack_write(opb,c->dim,16);
  108801. oggpack_write(opb,c->entries,24);
  108802. /* pack the codewords. There are two packings; length ordered and
  108803. length random. Decide between the two now. */
  108804. for(i=1;i<c->entries;i++)
  108805. if(c->lengthlist[i-1]==0 || c->lengthlist[i]<c->lengthlist[i-1])break;
  108806. if(i==c->entries)ordered=1;
  108807. if(ordered){
  108808. /* length ordered. We only need to say how many codewords of
  108809. each length. The actual codewords are generated
  108810. deterministically */
  108811. long count=0;
  108812. oggpack_write(opb,1,1); /* ordered */
  108813. oggpack_write(opb,c->lengthlist[0]-1,5); /* 1 to 32 */
  108814. for(i=1;i<c->entries;i++){
  108815. long thisx=c->lengthlist[i];
  108816. long last=c->lengthlist[i-1];
  108817. if(thisx>last){
  108818. for(j=last;j<thisx;j++){
  108819. oggpack_write(opb,i-count,_ilog(c->entries-count));
  108820. count=i;
  108821. }
  108822. }
  108823. }
  108824. oggpack_write(opb,i-count,_ilog(c->entries-count));
  108825. }else{
  108826. /* length random. Again, we don't code the codeword itself, just
  108827. the length. This time, though, we have to encode each length */
  108828. oggpack_write(opb,0,1); /* unordered */
  108829. /* algortihmic mapping has use for 'unused entries', which we tag
  108830. here. The algorithmic mapping happens as usual, but the unused
  108831. entry has no codeword. */
  108832. for(i=0;i<c->entries;i++)
  108833. if(c->lengthlist[i]==0)break;
  108834. if(i==c->entries){
  108835. oggpack_write(opb,0,1); /* no unused entries */
  108836. for(i=0;i<c->entries;i++)
  108837. oggpack_write(opb,c->lengthlist[i]-1,5);
  108838. }else{
  108839. oggpack_write(opb,1,1); /* we have unused entries; thus we tag */
  108840. for(i=0;i<c->entries;i++){
  108841. if(c->lengthlist[i]==0){
  108842. oggpack_write(opb,0,1);
  108843. }else{
  108844. oggpack_write(opb,1,1);
  108845. oggpack_write(opb,c->lengthlist[i]-1,5);
  108846. }
  108847. }
  108848. }
  108849. }
  108850. /* is the entry number the desired return value, or do we have a
  108851. mapping? If we have a mapping, what type? */
  108852. oggpack_write(opb,c->maptype,4);
  108853. switch(c->maptype){
  108854. case 0:
  108855. /* no mapping */
  108856. break;
  108857. case 1:case 2:
  108858. /* implicitly populated value mapping */
  108859. /* explicitly populated value mapping */
  108860. if(!c->quantlist){
  108861. /* no quantlist? error */
  108862. return(-1);
  108863. }
  108864. /* values that define the dequantization */
  108865. oggpack_write(opb,c->q_min,32);
  108866. oggpack_write(opb,c->q_delta,32);
  108867. oggpack_write(opb,c->q_quant-1,4);
  108868. oggpack_write(opb,c->q_sequencep,1);
  108869. {
  108870. int quantvals;
  108871. switch(c->maptype){
  108872. case 1:
  108873. /* a single column of (c->entries/c->dim) quantized values for
  108874. building a full value list algorithmically (square lattice) */
  108875. quantvals=_book_maptype1_quantvals(c);
  108876. break;
  108877. case 2:
  108878. /* every value (c->entries*c->dim total) specified explicitly */
  108879. quantvals=c->entries*c->dim;
  108880. break;
  108881. default: /* NOT_REACHABLE */
  108882. quantvals=-1;
  108883. }
  108884. /* quantized values */
  108885. for(i=0;i<quantvals;i++)
  108886. oggpack_write(opb,labs(c->quantlist[i]),c->q_quant);
  108887. }
  108888. break;
  108889. default:
  108890. /* error case; we don't have any other map types now */
  108891. return(-1);
  108892. }
  108893. return(0);
  108894. }
  108895. /* unpacks a codebook from the packet buffer into the codebook struct,
  108896. readies the codebook auxiliary structures for decode *************/
  108897. int vorbis_staticbook_unpack(oggpack_buffer *opb,static_codebook *s){
  108898. long i,j;
  108899. memset(s,0,sizeof(*s));
  108900. s->allocedp=1;
  108901. /* make sure alignment is correct */
  108902. if(oggpack_read(opb,24)!=0x564342)goto _eofout;
  108903. /* first the basic parameters */
  108904. s->dim=oggpack_read(opb,16);
  108905. s->entries=oggpack_read(opb,24);
  108906. if(s->entries==-1)goto _eofout;
  108907. /* codeword ordering.... length ordered or unordered? */
  108908. switch((int)oggpack_read(opb,1)){
  108909. case 0:
  108910. /* unordered */
  108911. s->lengthlist=(long*)_ogg_malloc(sizeof(*s->lengthlist)*s->entries);
  108912. /* allocated but unused entries? */
  108913. if(oggpack_read(opb,1)){
  108914. /* yes, unused entries */
  108915. for(i=0;i<s->entries;i++){
  108916. if(oggpack_read(opb,1)){
  108917. long num=oggpack_read(opb,5);
  108918. if(num==-1)goto _eofout;
  108919. s->lengthlist[i]=num+1;
  108920. }else
  108921. s->lengthlist[i]=0;
  108922. }
  108923. }else{
  108924. /* all entries used; no tagging */
  108925. for(i=0;i<s->entries;i++){
  108926. long num=oggpack_read(opb,5);
  108927. if(num==-1)goto _eofout;
  108928. s->lengthlist[i]=num+1;
  108929. }
  108930. }
  108931. break;
  108932. case 1:
  108933. /* ordered */
  108934. {
  108935. long length=oggpack_read(opb,5)+1;
  108936. s->lengthlist=(long*)_ogg_malloc(sizeof(*s->lengthlist)*s->entries);
  108937. for(i=0;i<s->entries;){
  108938. long num=oggpack_read(opb,_ilog(s->entries-i));
  108939. if(num==-1)goto _eofout;
  108940. for(j=0;j<num && i<s->entries;j++,i++)
  108941. s->lengthlist[i]=length;
  108942. length++;
  108943. }
  108944. }
  108945. break;
  108946. default:
  108947. /* EOF */
  108948. return(-1);
  108949. }
  108950. /* Do we have a mapping to unpack? */
  108951. switch((s->maptype=oggpack_read(opb,4))){
  108952. case 0:
  108953. /* no mapping */
  108954. break;
  108955. case 1: case 2:
  108956. /* implicitly populated value mapping */
  108957. /* explicitly populated value mapping */
  108958. s->q_min=oggpack_read(opb,32);
  108959. s->q_delta=oggpack_read(opb,32);
  108960. s->q_quant=oggpack_read(opb,4)+1;
  108961. s->q_sequencep=oggpack_read(opb,1);
  108962. {
  108963. int quantvals=0;
  108964. switch(s->maptype){
  108965. case 1:
  108966. quantvals=_book_maptype1_quantvals(s);
  108967. break;
  108968. case 2:
  108969. quantvals=s->entries*s->dim;
  108970. break;
  108971. }
  108972. /* quantized values */
  108973. s->quantlist=(long*)_ogg_malloc(sizeof(*s->quantlist)*quantvals);
  108974. for(i=0;i<quantvals;i++)
  108975. s->quantlist[i]=oggpack_read(opb,s->q_quant);
  108976. if(quantvals&&s->quantlist[quantvals-1]==-1)goto _eofout;
  108977. }
  108978. break;
  108979. default:
  108980. goto _errout;
  108981. }
  108982. /* all set */
  108983. return(0);
  108984. _errout:
  108985. _eofout:
  108986. vorbis_staticbook_clear(s);
  108987. return(-1);
  108988. }
  108989. /* returns the number of bits ************************************************/
  108990. int vorbis_book_encode(codebook *book, int a, oggpack_buffer *b){
  108991. oggpack_write(b,book->codelist[a],book->c->lengthlist[a]);
  108992. return(book->c->lengthlist[a]);
  108993. }
  108994. /* One the encode side, our vector writers are each designed for a
  108995. specific purpose, and the encoder is not flexible without modification:
  108996. The LSP vector coder uses a single stage nearest-match with no
  108997. interleave, so no step and no error return. This is specced by floor0
  108998. and doesn't change.
  108999. Residue0 encoding interleaves, uses multiple stages, and each stage
  109000. peels of a specific amount of resolution from a lattice (thus we want
  109001. to match by threshold, not nearest match). Residue doesn't *have* to
  109002. be encoded that way, but to change it, one will need to add more
  109003. infrastructure on the encode side (decode side is specced and simpler) */
  109004. /* floor0 LSP (single stage, non interleaved, nearest match) */
  109005. /* returns entry number and *modifies a* to the quantization value *****/
  109006. int vorbis_book_errorv(codebook *book,float *a){
  109007. int dim=book->dim,k;
  109008. int best=_best(book,a,1);
  109009. for(k=0;k<dim;k++)
  109010. a[k]=(book->valuelist+best*dim)[k];
  109011. return(best);
  109012. }
  109013. /* returns the number of bits and *modifies a* to the quantization value *****/
  109014. int vorbis_book_encodev(codebook *book,int best,float *a,oggpack_buffer *b){
  109015. int k,dim=book->dim;
  109016. for(k=0;k<dim;k++)
  109017. a[k]=(book->valuelist+best*dim)[k];
  109018. return(vorbis_book_encode(book,best,b));
  109019. }
  109020. /* the 'eliminate the decode tree' optimization actually requires the
  109021. codewords to be MSb first, not LSb. This is an annoying inelegancy
  109022. (and one of the first places where carefully thought out design
  109023. turned out to be wrong; Vorbis II and future Ogg codecs should go
  109024. to an MSb bitpacker), but not actually the huge hit it appears to
  109025. be. The first-stage decode table catches most words so that
  109026. bitreverse is not in the main execution path. */
  109027. STIN long decode_packed_entry_number(codebook *book, oggpack_buffer *b){
  109028. int read=book->dec_maxlength;
  109029. long lo,hi;
  109030. long lok = oggpack_look(b,book->dec_firsttablen);
  109031. if (lok >= 0) {
  109032. long entry = book->dec_firsttable[lok];
  109033. if(entry&0x80000000UL){
  109034. lo=(entry>>15)&0x7fff;
  109035. hi=book->used_entries-(entry&0x7fff);
  109036. }else{
  109037. oggpack_adv(b, book->dec_codelengths[entry-1]);
  109038. return(entry-1);
  109039. }
  109040. }else{
  109041. lo=0;
  109042. hi=book->used_entries;
  109043. }
  109044. lok = oggpack_look(b, read);
  109045. while(lok<0 && read>1)
  109046. lok = oggpack_look(b, --read);
  109047. if(lok<0)return -1;
  109048. /* bisect search for the codeword in the ordered list */
  109049. {
  109050. ogg_uint32_t testword=ogg_bitreverse((ogg_uint32_t)lok);
  109051. while(hi-lo>1){
  109052. long p=(hi-lo)>>1;
  109053. long test=book->codelist[lo+p]>testword;
  109054. lo+=p&(test-1);
  109055. hi-=p&(-test);
  109056. }
  109057. if(book->dec_codelengths[lo]<=read){
  109058. oggpack_adv(b, book->dec_codelengths[lo]);
  109059. return(lo);
  109060. }
  109061. }
  109062. oggpack_adv(b, read);
  109063. return(-1);
  109064. }
  109065. /* Decode side is specced and easier, because we don't need to find
  109066. matches using different criteria; we simply read and map. There are
  109067. two things we need to do 'depending':
  109068. We may need to support interleave. We don't really, but it's
  109069. convenient to do it here rather than rebuild the vector later.
  109070. Cascades may be additive or multiplicitive; this is not inherent in
  109071. the codebook, but set in the code using the codebook. Like
  109072. interleaving, it's easiest to do it here.
  109073. addmul==0 -> declarative (set the value)
  109074. addmul==1 -> additive
  109075. addmul==2 -> multiplicitive */
  109076. /* returns the [original, not compacted] entry number or -1 on eof *********/
  109077. long vorbis_book_decode(codebook *book, oggpack_buffer *b){
  109078. long packed_entry=decode_packed_entry_number(book,b);
  109079. if(packed_entry>=0)
  109080. return(book->dec_index[packed_entry]);
  109081. /* if there's no dec_index, the codebook unpacking isn't collapsed */
  109082. return(packed_entry);
  109083. }
  109084. /* returns 0 on OK or -1 on eof *************************************/
  109085. long vorbis_book_decodevs_add(codebook *book,float *a,oggpack_buffer *b,int n){
  109086. int step=n/book->dim;
  109087. long *entry = (long*)alloca(sizeof(*entry)*step);
  109088. float **t = (float**)alloca(sizeof(*t)*step);
  109089. int i,j,o;
  109090. for (i = 0; i < step; i++) {
  109091. entry[i]=decode_packed_entry_number(book,b);
  109092. if(entry[i]==-1)return(-1);
  109093. t[i] = book->valuelist+entry[i]*book->dim;
  109094. }
  109095. for(i=0,o=0;i<book->dim;i++,o+=step)
  109096. for (j=0;j<step;j++)
  109097. a[o+j]+=t[j][i];
  109098. return(0);
  109099. }
  109100. long vorbis_book_decodev_add(codebook *book,float *a,oggpack_buffer *b,int n){
  109101. int i,j,entry;
  109102. float *t;
  109103. if(book->dim>8){
  109104. for(i=0;i<n;){
  109105. entry = decode_packed_entry_number(book,b);
  109106. if(entry==-1)return(-1);
  109107. t = book->valuelist+entry*book->dim;
  109108. for (j=0;j<book->dim;)
  109109. a[i++]+=t[j++];
  109110. }
  109111. }else{
  109112. for(i=0;i<n;){
  109113. entry = decode_packed_entry_number(book,b);
  109114. if(entry==-1)return(-1);
  109115. t = book->valuelist+entry*book->dim;
  109116. j=0;
  109117. switch((int)book->dim){
  109118. case 8:
  109119. a[i++]+=t[j++];
  109120. case 7:
  109121. a[i++]+=t[j++];
  109122. case 6:
  109123. a[i++]+=t[j++];
  109124. case 5:
  109125. a[i++]+=t[j++];
  109126. case 4:
  109127. a[i++]+=t[j++];
  109128. case 3:
  109129. a[i++]+=t[j++];
  109130. case 2:
  109131. a[i++]+=t[j++];
  109132. case 1:
  109133. a[i++]+=t[j++];
  109134. case 0:
  109135. break;
  109136. }
  109137. }
  109138. }
  109139. return(0);
  109140. }
  109141. long vorbis_book_decodev_set(codebook *book,float *a,oggpack_buffer *b,int n){
  109142. int i,j,entry;
  109143. float *t;
  109144. for(i=0;i<n;){
  109145. entry = decode_packed_entry_number(book,b);
  109146. if(entry==-1)return(-1);
  109147. t = book->valuelist+entry*book->dim;
  109148. for (j=0;j<book->dim;)
  109149. a[i++]=t[j++];
  109150. }
  109151. return(0);
  109152. }
  109153. long vorbis_book_decodevv_add(codebook *book,float **a,long offset,int ch,
  109154. oggpack_buffer *b,int n){
  109155. long i,j,entry;
  109156. int chptr=0;
  109157. for(i=offset/ch;i<(offset+n)/ch;){
  109158. entry = decode_packed_entry_number(book,b);
  109159. if(entry==-1)return(-1);
  109160. {
  109161. const float *t = book->valuelist+entry*book->dim;
  109162. for (j=0;j<book->dim;j++){
  109163. a[chptr++][i]+=t[j];
  109164. if(chptr==ch){
  109165. chptr=0;
  109166. i++;
  109167. }
  109168. }
  109169. }
  109170. }
  109171. return(0);
  109172. }
  109173. #ifdef _V_SELFTEST
  109174. /* Simple enough; pack a few candidate codebooks, unpack them. Code a
  109175. number of vectors through (keeping track of the quantized values),
  109176. and decode using the unpacked book. quantized version of in should
  109177. exactly equal out */
  109178. #include <stdio.h>
  109179. #include "vorbis/book/lsp20_0.vqh"
  109180. #include "vorbis/book/res0a_13.vqh"
  109181. #define TESTSIZE 40
  109182. float test1[TESTSIZE]={
  109183. 0.105939f,
  109184. 0.215373f,
  109185. 0.429117f,
  109186. 0.587974f,
  109187. 0.181173f,
  109188. 0.296583f,
  109189. 0.515707f,
  109190. 0.715261f,
  109191. 0.162327f,
  109192. 0.263834f,
  109193. 0.342876f,
  109194. 0.406025f,
  109195. 0.103571f,
  109196. 0.223561f,
  109197. 0.368513f,
  109198. 0.540313f,
  109199. 0.136672f,
  109200. 0.395882f,
  109201. 0.587183f,
  109202. 0.652476f,
  109203. 0.114338f,
  109204. 0.417300f,
  109205. 0.525486f,
  109206. 0.698679f,
  109207. 0.147492f,
  109208. 0.324481f,
  109209. 0.643089f,
  109210. 0.757582f,
  109211. 0.139556f,
  109212. 0.215795f,
  109213. 0.324559f,
  109214. 0.399387f,
  109215. 0.120236f,
  109216. 0.267420f,
  109217. 0.446940f,
  109218. 0.608760f,
  109219. 0.115587f,
  109220. 0.287234f,
  109221. 0.571081f,
  109222. 0.708603f,
  109223. };
  109224. float test3[TESTSIZE]={
  109225. 0,1,-2,3,4,-5,6,7,8,9,
  109226. 8,-2,7,-1,4,6,8,3,1,-9,
  109227. 10,11,12,13,14,15,26,17,18,19,
  109228. 30,-25,-30,-1,-5,-32,4,3,-2,0};
  109229. static_codebook *testlist[]={&_vq_book_lsp20_0,
  109230. &_vq_book_res0a_13,NULL};
  109231. float *testvec[]={test1,test3};
  109232. int main(){
  109233. oggpack_buffer write;
  109234. oggpack_buffer read;
  109235. long ptr=0,i;
  109236. oggpack_writeinit(&write);
  109237. fprintf(stderr,"Testing codebook abstraction...:\n");
  109238. while(testlist[ptr]){
  109239. codebook c;
  109240. static_codebook s;
  109241. float *qv=alloca(sizeof(*qv)*TESTSIZE);
  109242. float *iv=alloca(sizeof(*iv)*TESTSIZE);
  109243. memcpy(qv,testvec[ptr],sizeof(*qv)*TESTSIZE);
  109244. memset(iv,0,sizeof(*iv)*TESTSIZE);
  109245. fprintf(stderr,"\tpacking/coding %ld... ",ptr);
  109246. /* pack the codebook, write the testvector */
  109247. oggpack_reset(&write);
  109248. vorbis_book_init_encode(&c,testlist[ptr]); /* get it into memory
  109249. we can write */
  109250. vorbis_staticbook_pack(testlist[ptr],&write);
  109251. fprintf(stderr,"Codebook size %ld bytes... ",oggpack_bytes(&write));
  109252. for(i=0;i<TESTSIZE;i+=c.dim){
  109253. int best=_best(&c,qv+i,1);
  109254. vorbis_book_encodev(&c,best,qv+i,&write);
  109255. }
  109256. vorbis_book_clear(&c);
  109257. fprintf(stderr,"OK.\n");
  109258. fprintf(stderr,"\tunpacking/decoding %ld... ",ptr);
  109259. /* transfer the write data to a read buffer and unpack/read */
  109260. oggpack_readinit(&read,oggpack_get_buffer(&write),oggpack_bytes(&write));
  109261. if(vorbis_staticbook_unpack(&read,&s)){
  109262. fprintf(stderr,"Error unpacking codebook.\n");
  109263. exit(1);
  109264. }
  109265. if(vorbis_book_init_decode(&c,&s)){
  109266. fprintf(stderr,"Error initializing codebook.\n");
  109267. exit(1);
  109268. }
  109269. for(i=0;i<TESTSIZE;i+=c.dim)
  109270. if(vorbis_book_decodev_set(&c,iv+i,&read,c.dim)==-1){
  109271. fprintf(stderr,"Error reading codebook test data (EOP).\n");
  109272. exit(1);
  109273. }
  109274. for(i=0;i<TESTSIZE;i++)
  109275. if(fabs(qv[i]-iv[i])>.000001){
  109276. fprintf(stderr,"read (%g) != written (%g) at position (%ld)\n",
  109277. iv[i],qv[i],i);
  109278. exit(1);
  109279. }
  109280. fprintf(stderr,"OK\n");
  109281. ptr++;
  109282. }
  109283. /* The above is the trivial stuff; now try unquantizing a log scale codebook */
  109284. exit(0);
  109285. }
  109286. #endif
  109287. #endif
  109288. /*** End of inlined file: codebook.c ***/
  109289. /*** Start of inlined file: envelope.c ***/
  109290. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  109291. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  109292. // tasks..
  109293. #if JUCE_MSVC
  109294. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  109295. #endif
  109296. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  109297. #if JUCE_USE_OGGVORBIS
  109298. #include <stdlib.h>
  109299. #include <string.h>
  109300. #include <stdio.h>
  109301. #include <math.h>
  109302. void _ve_envelope_init(envelope_lookup *e,vorbis_info *vi){
  109303. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  109304. vorbis_info_psy_global *gi=&ci->psy_g_param;
  109305. int ch=vi->channels;
  109306. int i,j;
  109307. int n=e->winlength=128;
  109308. e->searchstep=64; /* not random */
  109309. e->minenergy=gi->preecho_minenergy;
  109310. e->ch=ch;
  109311. e->storage=128;
  109312. e->cursor=ci->blocksizes[1]/2;
  109313. e->mdct_win=(float*)_ogg_calloc(n,sizeof(*e->mdct_win));
  109314. mdct_init(&e->mdct,n);
  109315. for(i=0;i<n;i++){
  109316. e->mdct_win[i]=sin(i/(n-1.)*M_PI);
  109317. e->mdct_win[i]*=e->mdct_win[i];
  109318. }
  109319. /* magic follows */
  109320. e->band[0].begin=2; e->band[0].end=4;
  109321. e->band[1].begin=4; e->band[1].end=5;
  109322. e->band[2].begin=6; e->band[2].end=6;
  109323. e->band[3].begin=9; e->band[3].end=8;
  109324. e->band[4].begin=13; e->band[4].end=8;
  109325. e->band[5].begin=17; e->band[5].end=8;
  109326. e->band[6].begin=22; e->band[6].end=8;
  109327. for(j=0;j<VE_BANDS;j++){
  109328. n=e->band[j].end;
  109329. e->band[j].window=(float*)_ogg_malloc(n*sizeof(*e->band[0].window));
  109330. for(i=0;i<n;i++){
  109331. e->band[j].window[i]=sin((i+.5)/n*M_PI);
  109332. e->band[j].total+=e->band[j].window[i];
  109333. }
  109334. e->band[j].total=1./e->band[j].total;
  109335. }
  109336. e->filter=(envelope_filter_state*)_ogg_calloc(VE_BANDS*ch,sizeof(*e->filter));
  109337. e->mark=(int*)_ogg_calloc(e->storage,sizeof(*e->mark));
  109338. }
  109339. void _ve_envelope_clear(envelope_lookup *e){
  109340. int i;
  109341. mdct_clear(&e->mdct);
  109342. for(i=0;i<VE_BANDS;i++)
  109343. _ogg_free(e->band[i].window);
  109344. _ogg_free(e->mdct_win);
  109345. _ogg_free(e->filter);
  109346. _ogg_free(e->mark);
  109347. memset(e,0,sizeof(*e));
  109348. }
  109349. /* fairly straight threshhold-by-band based until we find something
  109350. that works better and isn't patented. */
  109351. static int _ve_amp(envelope_lookup *ve,
  109352. vorbis_info_psy_global *gi,
  109353. float *data,
  109354. envelope_band *bands,
  109355. envelope_filter_state *filters,
  109356. long pos){
  109357. long n=ve->winlength;
  109358. int ret=0;
  109359. long i,j;
  109360. float decay;
  109361. /* we want to have a 'minimum bar' for energy, else we're just
  109362. basing blocks on quantization noise that outweighs the signal
  109363. itself (for low power signals) */
  109364. float minV=ve->minenergy;
  109365. float *vec=(float*) alloca(n*sizeof(*vec));
  109366. /* stretch is used to gradually lengthen the number of windows
  109367. considered prevoius-to-potential-trigger */
  109368. int stretch=max(VE_MINSTRETCH,ve->stretch/2);
  109369. float penalty=gi->stretch_penalty-(ve->stretch/2-VE_MINSTRETCH);
  109370. if(penalty<0.f)penalty=0.f;
  109371. if(penalty>gi->stretch_penalty)penalty=gi->stretch_penalty;
  109372. /*_analysis_output_always("lpcm",seq2,data,n,0,0,
  109373. totalshift+pos*ve->searchstep);*/
  109374. /* window and transform */
  109375. for(i=0;i<n;i++)
  109376. vec[i]=data[i]*ve->mdct_win[i];
  109377. mdct_forward(&ve->mdct,vec,vec);
  109378. /*_analysis_output_always("mdct",seq2,vec,n/2,0,1,0); */
  109379. /* near-DC spreading function; this has nothing to do with
  109380. psychoacoustics, just sidelobe leakage and window size */
  109381. {
  109382. float temp=vec[0]*vec[0]+.7*vec[1]*vec[1]+.2*vec[2]*vec[2];
  109383. int ptr=filters->nearptr;
  109384. /* the accumulation is regularly refreshed from scratch to avoid
  109385. floating point creep */
  109386. if(ptr==0){
  109387. decay=filters->nearDC_acc=filters->nearDC_partialacc+temp;
  109388. filters->nearDC_partialacc=temp;
  109389. }else{
  109390. decay=filters->nearDC_acc+=temp;
  109391. filters->nearDC_partialacc+=temp;
  109392. }
  109393. filters->nearDC_acc-=filters->nearDC[ptr];
  109394. filters->nearDC[ptr]=temp;
  109395. decay*=(1./(VE_NEARDC+1));
  109396. filters->nearptr++;
  109397. if(filters->nearptr>=VE_NEARDC)filters->nearptr=0;
  109398. decay=todB(&decay)*.5-15.f;
  109399. }
  109400. /* perform spreading and limiting, also smooth the spectrum. yes,
  109401. the MDCT results in all real coefficients, but it still *behaves*
  109402. like real/imaginary pairs */
  109403. for(i=0;i<n/2;i+=2){
  109404. float val=vec[i]*vec[i]+vec[i+1]*vec[i+1];
  109405. val=todB(&val)*.5f;
  109406. if(val<decay)val=decay;
  109407. if(val<minV)val=minV;
  109408. vec[i>>1]=val;
  109409. decay-=8.;
  109410. }
  109411. /*_analysis_output_always("spread",seq2++,vec,n/4,0,0,0);*/
  109412. /* perform preecho/postecho triggering by band */
  109413. for(j=0;j<VE_BANDS;j++){
  109414. float acc=0.;
  109415. float valmax,valmin;
  109416. /* accumulate amplitude */
  109417. for(i=0;i<bands[j].end;i++)
  109418. acc+=vec[i+bands[j].begin]*bands[j].window[i];
  109419. acc*=bands[j].total;
  109420. /* convert amplitude to delta */
  109421. {
  109422. int p,thisx=filters[j].ampptr;
  109423. float postmax,postmin,premax=-99999.f,premin=99999.f;
  109424. p=thisx;
  109425. p--;
  109426. if(p<0)p+=VE_AMP;
  109427. postmax=max(acc,filters[j].ampbuf[p]);
  109428. postmin=min(acc,filters[j].ampbuf[p]);
  109429. for(i=0;i<stretch;i++){
  109430. p--;
  109431. if(p<0)p+=VE_AMP;
  109432. premax=max(premax,filters[j].ampbuf[p]);
  109433. premin=min(premin,filters[j].ampbuf[p]);
  109434. }
  109435. valmin=postmin-premin;
  109436. valmax=postmax-premax;
  109437. /*filters[j].markers[pos]=valmax;*/
  109438. filters[j].ampbuf[thisx]=acc;
  109439. filters[j].ampptr++;
  109440. if(filters[j].ampptr>=VE_AMP)filters[j].ampptr=0;
  109441. }
  109442. /* look at min/max, decide trigger */
  109443. if(valmax>gi->preecho_thresh[j]+penalty){
  109444. ret|=1;
  109445. ret|=4;
  109446. }
  109447. if(valmin<gi->postecho_thresh[j]-penalty)ret|=2;
  109448. }
  109449. return(ret);
  109450. }
  109451. #if 0
  109452. static int seq=0;
  109453. static ogg_int64_t totalshift=-1024;
  109454. #endif
  109455. long _ve_envelope_search(vorbis_dsp_state *v){
  109456. vorbis_info *vi=v->vi;
  109457. codec_setup_info *ci=(codec_setup_info *)vi->codec_setup;
  109458. vorbis_info_psy_global *gi=&ci->psy_g_param;
  109459. envelope_lookup *ve=((private_state *)(v->backend_state))->ve;
  109460. long i,j;
  109461. int first=ve->current/ve->searchstep;
  109462. int last=v->pcm_current/ve->searchstep-VE_WIN;
  109463. if(first<0)first=0;
  109464. /* make sure we have enough storage to match the PCM */
  109465. if(last+VE_WIN+VE_POST>ve->storage){
  109466. ve->storage=last+VE_WIN+VE_POST; /* be sure */
  109467. ve->mark=(int*)_ogg_realloc(ve->mark,ve->storage*sizeof(*ve->mark));
  109468. }
  109469. for(j=first;j<last;j++){
  109470. int ret=0;
  109471. ve->stretch++;
  109472. if(ve->stretch>VE_MAXSTRETCH*2)
  109473. ve->stretch=VE_MAXSTRETCH*2;
  109474. for(i=0;i<ve->ch;i++){
  109475. float *pcm=v->pcm[i]+ve->searchstep*(j);
  109476. ret|=_ve_amp(ve,gi,pcm,ve->band,ve->filter+i*VE_BANDS,j);
  109477. }
  109478. ve->mark[j+VE_POST]=0;
  109479. if(ret&1){
  109480. ve->mark[j]=1;
  109481. ve->mark[j+1]=1;
  109482. }
  109483. if(ret&2){
  109484. ve->mark[j]=1;
  109485. if(j>0)ve->mark[j-1]=1;
  109486. }
  109487. if(ret&4)ve->stretch=-1;
  109488. }
  109489. ve->current=last*ve->searchstep;
  109490. {
  109491. long centerW=v->centerW;
  109492. long testW=
  109493. centerW+
  109494. ci->blocksizes[v->W]/4+
  109495. ci->blocksizes[1]/2+
  109496. ci->blocksizes[0]/4;
  109497. j=ve->cursor;
  109498. while(j<ve->current-(ve->searchstep)){/* account for postecho
  109499. working back one window */
  109500. if(j>=testW)return(1);
  109501. ve->cursor=j;
  109502. if(ve->mark[j/ve->searchstep]){
  109503. if(j>centerW){
  109504. #if 0
  109505. if(j>ve->curmark){
  109506. float *marker=alloca(v->pcm_current*sizeof(*marker));
  109507. int l,m;
  109508. memset(marker,0,sizeof(*marker)*v->pcm_current);
  109509. fprintf(stderr,"mark! seq=%d, cursor:%fs time:%fs\n",
  109510. seq,
  109511. (totalshift+ve->cursor)/44100.,
  109512. (totalshift+j)/44100.);
  109513. _analysis_output_always("pcmL",seq,v->pcm[0],v->pcm_current,0,0,totalshift);
  109514. _analysis_output_always("pcmR",seq,v->pcm[1],v->pcm_current,0,0,totalshift);
  109515. _analysis_output_always("markL",seq,v->pcm[0],j,0,0,totalshift);
  109516. _analysis_output_always("markR",seq,v->pcm[1],j,0,0,totalshift);
  109517. for(m=0;m<VE_BANDS;m++){
  109518. char buf[80];
  109519. sprintf(buf,"delL%d",m);
  109520. for(l=0;l<last;l++)marker[l*ve->searchstep]=ve->filter[m].markers[l]*.1;
  109521. _analysis_output_always(buf,seq,marker,v->pcm_current,0,0,totalshift);
  109522. }
  109523. for(m=0;m<VE_BANDS;m++){
  109524. char buf[80];
  109525. sprintf(buf,"delR%d",m);
  109526. for(l=0;l<last;l++)marker[l*ve->searchstep]=ve->filter[m+VE_BANDS].markers[l]*.1;
  109527. _analysis_output_always(buf,seq,marker,v->pcm_current,0,0,totalshift);
  109528. }
  109529. for(l=0;l<last;l++)marker[l*ve->searchstep]=ve->mark[l]*.4;
  109530. _analysis_output_always("mark",seq,marker,v->pcm_current,0,0,totalshift);
  109531. seq++;
  109532. }
  109533. #endif
  109534. ve->curmark=j;
  109535. if(j>=testW)return(1);
  109536. return(0);
  109537. }
  109538. }
  109539. j+=ve->searchstep;
  109540. }
  109541. }
  109542. return(-1);
  109543. }
  109544. int _ve_envelope_mark(vorbis_dsp_state *v){
  109545. envelope_lookup *ve=((private_state *)(v->backend_state))->ve;
  109546. vorbis_info *vi=v->vi;
  109547. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  109548. long centerW=v->centerW;
  109549. long beginW=centerW-ci->blocksizes[v->W]/4;
  109550. long endW=centerW+ci->blocksizes[v->W]/4;
  109551. if(v->W){
  109552. beginW-=ci->blocksizes[v->lW]/4;
  109553. endW+=ci->blocksizes[v->nW]/4;
  109554. }else{
  109555. beginW-=ci->blocksizes[0]/4;
  109556. endW+=ci->blocksizes[0]/4;
  109557. }
  109558. if(ve->curmark>=beginW && ve->curmark<endW)return(1);
  109559. {
  109560. long first=beginW/ve->searchstep;
  109561. long last=endW/ve->searchstep;
  109562. long i;
  109563. for(i=first;i<last;i++)
  109564. if(ve->mark[i])return(1);
  109565. }
  109566. return(0);
  109567. }
  109568. void _ve_envelope_shift(envelope_lookup *e,long shift){
  109569. int smallsize=e->current/e->searchstep+VE_POST; /* adjust for placing marks
  109570. ahead of ve->current */
  109571. int smallshift=shift/e->searchstep;
  109572. memmove(e->mark,e->mark+smallshift,(smallsize-smallshift)*sizeof(*e->mark));
  109573. #if 0
  109574. for(i=0;i<VE_BANDS*e->ch;i++)
  109575. memmove(e->filter[i].markers,
  109576. e->filter[i].markers+smallshift,
  109577. (1024-smallshift)*sizeof(*(*e->filter).markers));
  109578. totalshift+=shift;
  109579. #endif
  109580. e->current-=shift;
  109581. if(e->curmark>=0)
  109582. e->curmark-=shift;
  109583. e->cursor-=shift;
  109584. }
  109585. #endif
  109586. /*** End of inlined file: envelope.c ***/
  109587. /*** Start of inlined file: floor0.c ***/
  109588. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  109589. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  109590. // tasks..
  109591. #if JUCE_MSVC
  109592. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  109593. #endif
  109594. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  109595. #if JUCE_USE_OGGVORBIS
  109596. #include <stdlib.h>
  109597. #include <string.h>
  109598. #include <math.h>
  109599. /*** Start of inlined file: lsp.h ***/
  109600. #ifndef _V_LSP_H_
  109601. #define _V_LSP_H_
  109602. extern int vorbis_lpc_to_lsp(float *lpc,float *lsp,int m);
  109603. extern void vorbis_lsp_to_curve(float *curve,int *map,int n,int ln,
  109604. float *lsp,int m,
  109605. float amp,float ampoffset);
  109606. #endif
  109607. /*** End of inlined file: lsp.h ***/
  109608. #include <stdio.h>
  109609. typedef struct {
  109610. int ln;
  109611. int m;
  109612. int **linearmap;
  109613. int n[2];
  109614. vorbis_info_floor0 *vi;
  109615. long bits;
  109616. long frames;
  109617. } vorbis_look_floor0;
  109618. /***********************************************/
  109619. static void floor0_free_info(vorbis_info_floor *i){
  109620. vorbis_info_floor0 *info=(vorbis_info_floor0 *)i;
  109621. if(info){
  109622. memset(info,0,sizeof(*info));
  109623. _ogg_free(info);
  109624. }
  109625. }
  109626. static void floor0_free_look(vorbis_look_floor *i){
  109627. vorbis_look_floor0 *look=(vorbis_look_floor0 *)i;
  109628. if(look){
  109629. if(look->linearmap){
  109630. if(look->linearmap[0])_ogg_free(look->linearmap[0]);
  109631. if(look->linearmap[1])_ogg_free(look->linearmap[1]);
  109632. _ogg_free(look->linearmap);
  109633. }
  109634. memset(look,0,sizeof(*look));
  109635. _ogg_free(look);
  109636. }
  109637. }
  109638. static vorbis_info_floor *floor0_unpack (vorbis_info *vi,oggpack_buffer *opb){
  109639. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  109640. int j;
  109641. vorbis_info_floor0 *info=(vorbis_info_floor0*)_ogg_malloc(sizeof(*info));
  109642. info->order=oggpack_read(opb,8);
  109643. info->rate=oggpack_read(opb,16);
  109644. info->barkmap=oggpack_read(opb,16);
  109645. info->ampbits=oggpack_read(opb,6);
  109646. info->ampdB=oggpack_read(opb,8);
  109647. info->numbooks=oggpack_read(opb,4)+1;
  109648. if(info->order<1)goto err_out;
  109649. if(info->rate<1)goto err_out;
  109650. if(info->barkmap<1)goto err_out;
  109651. if(info->numbooks<1)goto err_out;
  109652. for(j=0;j<info->numbooks;j++){
  109653. info->books[j]=oggpack_read(opb,8);
  109654. if(info->books[j]<0 || info->books[j]>=ci->books)goto err_out;
  109655. }
  109656. return(info);
  109657. err_out:
  109658. floor0_free_info(info);
  109659. return(NULL);
  109660. }
  109661. /* initialize Bark scale and normalization lookups. We could do this
  109662. with static tables, but Vorbis allows a number of possible
  109663. combinations, so it's best to do it computationally.
  109664. The below is authoritative in terms of defining scale mapping.
  109665. Note that the scale depends on the sampling rate as well as the
  109666. linear block and mapping sizes */
  109667. static void floor0_map_lazy_init(vorbis_block *vb,
  109668. vorbis_info_floor *infoX,
  109669. vorbis_look_floor0 *look){
  109670. if(!look->linearmap[vb->W]){
  109671. vorbis_dsp_state *vd=vb->vd;
  109672. vorbis_info *vi=vd->vi;
  109673. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  109674. vorbis_info_floor0 *info=(vorbis_info_floor0 *)infoX;
  109675. int W=vb->W;
  109676. int n=ci->blocksizes[W]/2,j;
  109677. /* we choose a scaling constant so that:
  109678. floor(bark(rate/2-1)*C)=mapped-1
  109679. floor(bark(rate/2)*C)=mapped */
  109680. float scale=look->ln/toBARK(info->rate/2.f);
  109681. /* the mapping from a linear scale to a smaller bark scale is
  109682. straightforward. We do *not* make sure that the linear mapping
  109683. does not skip bark-scale bins; the decoder simply skips them and
  109684. the encoder may do what it wishes in filling them. They're
  109685. necessary in some mapping combinations to keep the scale spacing
  109686. accurate */
  109687. look->linearmap[W]=(int*)_ogg_malloc((n+1)*sizeof(**look->linearmap));
  109688. for(j=0;j<n;j++){
  109689. int val=floor( toBARK((info->rate/2.f)/n*j)
  109690. *scale); /* bark numbers represent band edges */
  109691. if(val>=look->ln)val=look->ln-1; /* guard against the approximation */
  109692. look->linearmap[W][j]=val;
  109693. }
  109694. look->linearmap[W][j]=-1;
  109695. look->n[W]=n;
  109696. }
  109697. }
  109698. static vorbis_look_floor *floor0_look(vorbis_dsp_state *vd,
  109699. vorbis_info_floor *i){
  109700. vorbis_info_floor0 *info=(vorbis_info_floor0*)i;
  109701. vorbis_look_floor0 *look=(vorbis_look_floor0*)_ogg_calloc(1,sizeof(*look));
  109702. look->m=info->order;
  109703. look->ln=info->barkmap;
  109704. look->vi=info;
  109705. look->linearmap=(int**)_ogg_calloc(2,sizeof(*look->linearmap));
  109706. return look;
  109707. }
  109708. static void *floor0_inverse1(vorbis_block *vb,vorbis_look_floor *i){
  109709. vorbis_look_floor0 *look=(vorbis_look_floor0 *)i;
  109710. vorbis_info_floor0 *info=look->vi;
  109711. int j,k;
  109712. int ampraw=oggpack_read(&vb->opb,info->ampbits);
  109713. if(ampraw>0){ /* also handles the -1 out of data case */
  109714. long maxval=(1<<info->ampbits)-1;
  109715. float amp=(float)ampraw/maxval*info->ampdB;
  109716. int booknum=oggpack_read(&vb->opb,_ilog(info->numbooks));
  109717. if(booknum!=-1 && booknum<info->numbooks){ /* be paranoid */
  109718. codec_setup_info *ci=(codec_setup_info *)vb->vd->vi->codec_setup;
  109719. codebook *b=ci->fullbooks+info->books[booknum];
  109720. float last=0.f;
  109721. /* the additional b->dim is a guard against any possible stack
  109722. smash; b->dim is provably more than we can overflow the
  109723. vector */
  109724. float *lsp=(float*)_vorbis_block_alloc(vb,sizeof(*lsp)*(look->m+b->dim+1));
  109725. for(j=0;j<look->m;j+=b->dim)
  109726. if(vorbis_book_decodev_set(b,lsp+j,&vb->opb,b->dim)==-1)goto eop;
  109727. for(j=0;j<look->m;){
  109728. for(k=0;k<b->dim;k++,j++)lsp[j]+=last;
  109729. last=lsp[j-1];
  109730. }
  109731. lsp[look->m]=amp;
  109732. return(lsp);
  109733. }
  109734. }
  109735. eop:
  109736. return(NULL);
  109737. }
  109738. static int floor0_inverse2(vorbis_block *vb,vorbis_look_floor *i,
  109739. void *memo,float *out){
  109740. vorbis_look_floor0 *look=(vorbis_look_floor0 *)i;
  109741. vorbis_info_floor0 *info=look->vi;
  109742. floor0_map_lazy_init(vb,info,look);
  109743. if(memo){
  109744. float *lsp=(float *)memo;
  109745. float amp=lsp[look->m];
  109746. /* take the coefficients back to a spectral envelope curve */
  109747. vorbis_lsp_to_curve(out,
  109748. look->linearmap[vb->W],
  109749. look->n[vb->W],
  109750. look->ln,
  109751. lsp,look->m,amp,(float)info->ampdB);
  109752. return(1);
  109753. }
  109754. memset(out,0,sizeof(*out)*look->n[vb->W]);
  109755. return(0);
  109756. }
  109757. /* export hooks */
  109758. vorbis_func_floor floor0_exportbundle={
  109759. NULL,&floor0_unpack,&floor0_look,&floor0_free_info,
  109760. &floor0_free_look,&floor0_inverse1,&floor0_inverse2
  109761. };
  109762. #endif
  109763. /*** End of inlined file: floor0.c ***/
  109764. /*** Start of inlined file: floor1.c ***/
  109765. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  109766. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  109767. // tasks..
  109768. #if JUCE_MSVC
  109769. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  109770. #endif
  109771. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  109772. #if JUCE_USE_OGGVORBIS
  109773. #include <stdlib.h>
  109774. #include <string.h>
  109775. #include <math.h>
  109776. #include <stdio.h>
  109777. #define floor1_rangedB 140 /* floor 1 fixed at -140dB to 0dB range */
  109778. typedef struct {
  109779. int sorted_index[VIF_POSIT+2];
  109780. int forward_index[VIF_POSIT+2];
  109781. int reverse_index[VIF_POSIT+2];
  109782. int hineighbor[VIF_POSIT];
  109783. int loneighbor[VIF_POSIT];
  109784. int posts;
  109785. int n;
  109786. int quant_q;
  109787. vorbis_info_floor1 *vi;
  109788. long phrasebits;
  109789. long postbits;
  109790. long frames;
  109791. } vorbis_look_floor1;
  109792. typedef struct lsfit_acc{
  109793. long x0;
  109794. long x1;
  109795. long xa;
  109796. long ya;
  109797. long x2a;
  109798. long y2a;
  109799. long xya;
  109800. long an;
  109801. } lsfit_acc;
  109802. /***********************************************/
  109803. static void floor1_free_info(vorbis_info_floor *i){
  109804. vorbis_info_floor1 *info=(vorbis_info_floor1 *)i;
  109805. if(info){
  109806. memset(info,0,sizeof(*info));
  109807. _ogg_free(info);
  109808. }
  109809. }
  109810. static void floor1_free_look(vorbis_look_floor *i){
  109811. vorbis_look_floor1 *look=(vorbis_look_floor1 *)i;
  109812. if(look){
  109813. /*fprintf(stderr,"floor 1 bit usage %f:%f (%f total)\n",
  109814. (float)look->phrasebits/look->frames,
  109815. (float)look->postbits/look->frames,
  109816. (float)(look->postbits+look->phrasebits)/look->frames);*/
  109817. memset(look,0,sizeof(*look));
  109818. _ogg_free(look);
  109819. }
  109820. }
  109821. static void floor1_pack (vorbis_info_floor *i,oggpack_buffer *opb){
  109822. vorbis_info_floor1 *info=(vorbis_info_floor1 *)i;
  109823. int j,k;
  109824. int count=0;
  109825. int rangebits;
  109826. int maxposit=info->postlist[1];
  109827. int maxclass=-1;
  109828. /* save out partitions */
  109829. oggpack_write(opb,info->partitions,5); /* only 0 to 31 legal */
  109830. for(j=0;j<info->partitions;j++){
  109831. oggpack_write(opb,info->partitionclass[j],4); /* only 0 to 15 legal */
  109832. if(maxclass<info->partitionclass[j])maxclass=info->partitionclass[j];
  109833. }
  109834. /* save out partition classes */
  109835. for(j=0;j<maxclass+1;j++){
  109836. oggpack_write(opb,info->class_dim[j]-1,3); /* 1 to 8 */
  109837. oggpack_write(opb,info->class_subs[j],2); /* 0 to 3 */
  109838. if(info->class_subs[j])oggpack_write(opb,info->class_book[j],8);
  109839. for(k=0;k<(1<<info->class_subs[j]);k++)
  109840. oggpack_write(opb,info->class_subbook[j][k]+1,8);
  109841. }
  109842. /* save out the post list */
  109843. oggpack_write(opb,info->mult-1,2); /* only 1,2,3,4 legal now */
  109844. oggpack_write(opb,ilog2(maxposit),4);
  109845. rangebits=ilog2(maxposit);
  109846. for(j=0,k=0;j<info->partitions;j++){
  109847. count+=info->class_dim[info->partitionclass[j]];
  109848. for(;k<count;k++)
  109849. oggpack_write(opb,info->postlist[k+2],rangebits);
  109850. }
  109851. }
  109852. static vorbis_info_floor *floor1_unpack (vorbis_info *vi,oggpack_buffer *opb){
  109853. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  109854. int j,k,count=0,maxclass=-1,rangebits;
  109855. vorbis_info_floor1 *info=(vorbis_info_floor1*)_ogg_calloc(1,sizeof(*info));
  109856. /* read partitions */
  109857. info->partitions=oggpack_read(opb,5); /* only 0 to 31 legal */
  109858. for(j=0;j<info->partitions;j++){
  109859. info->partitionclass[j]=oggpack_read(opb,4); /* only 0 to 15 legal */
  109860. if(maxclass<info->partitionclass[j])maxclass=info->partitionclass[j];
  109861. }
  109862. /* read partition classes */
  109863. for(j=0;j<maxclass+1;j++){
  109864. info->class_dim[j]=oggpack_read(opb,3)+1; /* 1 to 8 */
  109865. info->class_subs[j]=oggpack_read(opb,2); /* 0,1,2,3 bits */
  109866. if(info->class_subs[j]<0)
  109867. goto err_out;
  109868. if(info->class_subs[j])info->class_book[j]=oggpack_read(opb,8);
  109869. if(info->class_book[j]<0 || info->class_book[j]>=ci->books)
  109870. goto err_out;
  109871. for(k=0;k<(1<<info->class_subs[j]);k++){
  109872. info->class_subbook[j][k]=oggpack_read(opb,8)-1;
  109873. if(info->class_subbook[j][k]<-1 || info->class_subbook[j][k]>=ci->books)
  109874. goto err_out;
  109875. }
  109876. }
  109877. /* read the post list */
  109878. info->mult=oggpack_read(opb,2)+1; /* only 1,2,3,4 legal now */
  109879. rangebits=oggpack_read(opb,4);
  109880. for(j=0,k=0;j<info->partitions;j++){
  109881. count+=info->class_dim[info->partitionclass[j]];
  109882. for(;k<count;k++){
  109883. int t=info->postlist[k+2]=oggpack_read(opb,rangebits);
  109884. if(t<0 || t>=(1<<rangebits))
  109885. goto err_out;
  109886. }
  109887. }
  109888. info->postlist[0]=0;
  109889. info->postlist[1]=1<<rangebits;
  109890. return(info);
  109891. err_out:
  109892. floor1_free_info(info);
  109893. return(NULL);
  109894. }
  109895. static int icomp(const void *a,const void *b){
  109896. return(**(int **)a-**(int **)b);
  109897. }
  109898. static vorbis_look_floor *floor1_look(vorbis_dsp_state *vd,
  109899. vorbis_info_floor *in){
  109900. int *sortpointer[VIF_POSIT+2];
  109901. vorbis_info_floor1 *info=(vorbis_info_floor1*)in;
  109902. vorbis_look_floor1 *look=(vorbis_look_floor1*)_ogg_calloc(1,sizeof(*look));
  109903. int i,j,n=0;
  109904. look->vi=info;
  109905. look->n=info->postlist[1];
  109906. /* we drop each position value in-between already decoded values,
  109907. and use linear interpolation to predict each new value past the
  109908. edges. The positions are read in the order of the position
  109909. list... we precompute the bounding positions in the lookup. Of
  109910. course, the neighbors can change (if a position is declined), but
  109911. this is an initial mapping */
  109912. for(i=0;i<info->partitions;i++)n+=info->class_dim[info->partitionclass[i]];
  109913. n+=2;
  109914. look->posts=n;
  109915. /* also store a sorted position index */
  109916. for(i=0;i<n;i++)sortpointer[i]=info->postlist+i;
  109917. qsort(sortpointer,n,sizeof(*sortpointer),icomp);
  109918. /* points from sort order back to range number */
  109919. for(i=0;i<n;i++)look->forward_index[i]=sortpointer[i]-info->postlist;
  109920. /* points from range order to sorted position */
  109921. for(i=0;i<n;i++)look->reverse_index[look->forward_index[i]]=i;
  109922. /* we actually need the post values too */
  109923. for(i=0;i<n;i++)look->sorted_index[i]=info->postlist[look->forward_index[i]];
  109924. /* quantize values to multiplier spec */
  109925. switch(info->mult){
  109926. case 1: /* 1024 -> 256 */
  109927. look->quant_q=256;
  109928. break;
  109929. case 2: /* 1024 -> 128 */
  109930. look->quant_q=128;
  109931. break;
  109932. case 3: /* 1024 -> 86 */
  109933. look->quant_q=86;
  109934. break;
  109935. case 4: /* 1024 -> 64 */
  109936. look->quant_q=64;
  109937. break;
  109938. }
  109939. /* discover our neighbors for decode where we don't use fit flags
  109940. (that would push the neighbors outward) */
  109941. for(i=0;i<n-2;i++){
  109942. int lo=0;
  109943. int hi=1;
  109944. int lx=0;
  109945. int hx=look->n;
  109946. int currentx=info->postlist[i+2];
  109947. for(j=0;j<i+2;j++){
  109948. int x=info->postlist[j];
  109949. if(x>lx && x<currentx){
  109950. lo=j;
  109951. lx=x;
  109952. }
  109953. if(x<hx && x>currentx){
  109954. hi=j;
  109955. hx=x;
  109956. }
  109957. }
  109958. look->loneighbor[i]=lo;
  109959. look->hineighbor[i]=hi;
  109960. }
  109961. return(look);
  109962. }
  109963. static int render_point(int x0,int x1,int y0,int y1,int x){
  109964. y0&=0x7fff; /* mask off flag */
  109965. y1&=0x7fff;
  109966. {
  109967. int dy=y1-y0;
  109968. int adx=x1-x0;
  109969. int ady=abs(dy);
  109970. int err=ady*(x-x0);
  109971. int off=err/adx;
  109972. if(dy<0)return(y0-off);
  109973. return(y0+off);
  109974. }
  109975. }
  109976. static int vorbis_dBquant(const float *x){
  109977. int i= *x*7.3142857f+1023.5f;
  109978. if(i>1023)return(1023);
  109979. if(i<0)return(0);
  109980. return i;
  109981. }
  109982. static float FLOOR1_fromdB_LOOKUP[256]={
  109983. 1.0649863e-07F, 1.1341951e-07F, 1.2079015e-07F, 1.2863978e-07F,
  109984. 1.3699951e-07F, 1.4590251e-07F, 1.5538408e-07F, 1.6548181e-07F,
  109985. 1.7623575e-07F, 1.8768855e-07F, 1.9988561e-07F, 2.128753e-07F,
  109986. 2.2670913e-07F, 2.4144197e-07F, 2.5713223e-07F, 2.7384213e-07F,
  109987. 2.9163793e-07F, 3.1059021e-07F, 3.3077411e-07F, 3.5226968e-07F,
  109988. 3.7516214e-07F, 3.9954229e-07F, 4.2550680e-07F, 4.5315863e-07F,
  109989. 4.8260743e-07F, 5.1396998e-07F, 5.4737065e-07F, 5.8294187e-07F,
  109990. 6.2082472e-07F, 6.6116941e-07F, 7.0413592e-07F, 7.4989464e-07F,
  109991. 7.9862701e-07F, 8.5052630e-07F, 9.0579828e-07F, 9.6466216e-07F,
  109992. 1.0273513e-06F, 1.0941144e-06F, 1.1652161e-06F, 1.2409384e-06F,
  109993. 1.3215816e-06F, 1.4074654e-06F, 1.4989305e-06F, 1.5963394e-06F,
  109994. 1.7000785e-06F, 1.8105592e-06F, 1.9282195e-06F, 2.0535261e-06F,
  109995. 2.1869758e-06F, 2.3290978e-06F, 2.4804557e-06F, 2.6416497e-06F,
  109996. 2.8133190e-06F, 2.9961443e-06F, 3.1908506e-06F, 3.3982101e-06F,
  109997. 3.6190449e-06F, 3.8542308e-06F, 4.1047004e-06F, 4.3714470e-06F,
  109998. 4.6555282e-06F, 4.9580707e-06F, 5.2802740e-06F, 5.6234160e-06F,
  109999. 5.9888572e-06F, 6.3780469e-06F, 6.7925283e-06F, 7.2339451e-06F,
  110000. 7.7040476e-06F, 8.2047000e-06F, 8.7378876e-06F, 9.3057248e-06F,
  110001. 9.9104632e-06F, 1.0554501e-05F, 1.1240392e-05F, 1.1970856e-05F,
  110002. 1.2748789e-05F, 1.3577278e-05F, 1.4459606e-05F, 1.5399272e-05F,
  110003. 1.6400004e-05F, 1.7465768e-05F, 1.8600792e-05F, 1.9809576e-05F,
  110004. 2.1096914e-05F, 2.2467911e-05F, 2.3928002e-05F, 2.5482978e-05F,
  110005. 2.7139006e-05F, 2.8902651e-05F, 3.0780908e-05F, 3.2781225e-05F,
  110006. 3.4911534e-05F, 3.7180282e-05F, 3.9596466e-05F, 4.2169667e-05F,
  110007. 4.4910090e-05F, 4.7828601e-05F, 5.0936773e-05F, 5.4246931e-05F,
  110008. 5.7772202e-05F, 6.1526565e-05F, 6.5524908e-05F, 6.9783085e-05F,
  110009. 7.4317983e-05F, 7.9147585e-05F, 8.4291040e-05F, 8.9768747e-05F,
  110010. 9.5602426e-05F, 0.00010181521F, 0.00010843174F, 0.00011547824F,
  110011. 0.00012298267F, 0.00013097477F, 0.00013948625F, 0.00014855085F,
  110012. 0.00015820453F, 0.00016848555F, 0.00017943469F, 0.00019109536F,
  110013. 0.00020351382F, 0.00021673929F, 0.00023082423F, 0.00024582449F,
  110014. 0.00026179955F, 0.00027881276F, 0.00029693158F, 0.00031622787F,
  110015. 0.00033677814F, 0.00035866388F, 0.00038197188F, 0.00040679456F,
  110016. 0.00043323036F, 0.00046138411F, 0.00049136745F, 0.00052329927F,
  110017. 0.00055730621F, 0.00059352311F, 0.00063209358F, 0.00067317058F,
  110018. 0.00071691700F, 0.00076350630F, 0.00081312324F, 0.00086596457F,
  110019. 0.00092223983F, 0.00098217216F, 0.0010459992F, 0.0011139742F,
  110020. 0.0011863665F, 0.0012634633F, 0.0013455702F, 0.0014330129F,
  110021. 0.0015261382F, 0.0016253153F, 0.0017309374F, 0.0018434235F,
  110022. 0.0019632195F, 0.0020908006F, 0.0022266726F, 0.0023713743F,
  110023. 0.0025254795F, 0.0026895994F, 0.0028643847F, 0.0030505286F,
  110024. 0.0032487691F, 0.0034598925F, 0.0036847358F, 0.0039241906F,
  110025. 0.0041792066F, 0.0044507950F, 0.0047400328F, 0.0050480668F,
  110026. 0.0053761186F, 0.0057254891F, 0.0060975636F, 0.0064938176F,
  110027. 0.0069158225F, 0.0073652516F, 0.0078438871F, 0.0083536271F,
  110028. 0.0088964928F, 0.009474637F, 0.010090352F, 0.010746080F,
  110029. 0.011444421F, 0.012188144F, 0.012980198F, 0.013823725F,
  110030. 0.014722068F, 0.015678791F, 0.016697687F, 0.017782797F,
  110031. 0.018938423F, 0.020169149F, 0.021479854F, 0.022875735F,
  110032. 0.024362330F, 0.025945531F, 0.027631618F, 0.029427276F,
  110033. 0.031339626F, 0.033376252F, 0.035545228F, 0.037855157F,
  110034. 0.040315199F, 0.042935108F, 0.045725273F, 0.048696758F,
  110035. 0.051861348F, 0.055231591F, 0.058820850F, 0.062643361F,
  110036. 0.066714279F, 0.071049749F, 0.075666962F, 0.080584227F,
  110037. 0.085821044F, 0.091398179F, 0.097337747F, 0.10366330F,
  110038. 0.11039993F, 0.11757434F, 0.12521498F, 0.13335215F,
  110039. 0.14201813F, 0.15124727F, 0.16107617F, 0.17154380F,
  110040. 0.18269168F, 0.19456402F, 0.20720788F, 0.22067342F,
  110041. 0.23501402F, 0.25028656F, 0.26655159F, 0.28387361F,
  110042. 0.30232132F, 0.32196786F, 0.34289114F, 0.36517414F,
  110043. 0.38890521F, 0.41417847F, 0.44109412F, 0.46975890F,
  110044. 0.50028648F, 0.53279791F, 0.56742212F, 0.60429640F,
  110045. 0.64356699F, 0.68538959F, 0.72993007F, 0.77736504F,
  110046. 0.82788260F, 0.88168307F, 0.9389798F, 1.F,
  110047. };
  110048. static void render_line(int x0,int x1,int y0,int y1,float *d){
  110049. int dy=y1-y0;
  110050. int adx=x1-x0;
  110051. int ady=abs(dy);
  110052. int base=dy/adx;
  110053. int sy=(dy<0?base-1:base+1);
  110054. int x=x0;
  110055. int y=y0;
  110056. int err=0;
  110057. ady-=abs(base*adx);
  110058. d[x]*=FLOOR1_fromdB_LOOKUP[y];
  110059. while(++x<x1){
  110060. err=err+ady;
  110061. if(err>=adx){
  110062. err-=adx;
  110063. y+=sy;
  110064. }else{
  110065. y+=base;
  110066. }
  110067. d[x]*=FLOOR1_fromdB_LOOKUP[y];
  110068. }
  110069. }
  110070. static void render_line0(int x0,int x1,int y0,int y1,int *d){
  110071. int dy=y1-y0;
  110072. int adx=x1-x0;
  110073. int ady=abs(dy);
  110074. int base=dy/adx;
  110075. int sy=(dy<0?base-1:base+1);
  110076. int x=x0;
  110077. int y=y0;
  110078. int err=0;
  110079. ady-=abs(base*adx);
  110080. d[x]=y;
  110081. while(++x<x1){
  110082. err=err+ady;
  110083. if(err>=adx){
  110084. err-=adx;
  110085. y+=sy;
  110086. }else{
  110087. y+=base;
  110088. }
  110089. d[x]=y;
  110090. }
  110091. }
  110092. /* the floor has already been filtered to only include relevant sections */
  110093. static int accumulate_fit(const float *flr,const float *mdct,
  110094. int x0, int x1,lsfit_acc *a,
  110095. int n,vorbis_info_floor1 *info){
  110096. long i;
  110097. 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;
  110098. memset(a,0,sizeof(*a));
  110099. a->x0=x0;
  110100. a->x1=x1;
  110101. if(x1>=n)x1=n-1;
  110102. for(i=x0;i<=x1;i++){
  110103. int quantized=vorbis_dBquant(flr+i);
  110104. if(quantized){
  110105. if(mdct[i]+info->twofitatten>=flr[i]){
  110106. xa += i;
  110107. ya += quantized;
  110108. x2a += i*i;
  110109. y2a += quantized*quantized;
  110110. xya += i*quantized;
  110111. na++;
  110112. }else{
  110113. xb += i;
  110114. yb += quantized;
  110115. x2b += i*i;
  110116. y2b += quantized*quantized;
  110117. xyb += i*quantized;
  110118. nb++;
  110119. }
  110120. }
  110121. }
  110122. xb+=xa;
  110123. yb+=ya;
  110124. x2b+=x2a;
  110125. y2b+=y2a;
  110126. xyb+=xya;
  110127. nb+=na;
  110128. /* weight toward the actually used frequencies if we meet the threshhold */
  110129. {
  110130. int weight=nb*info->twofitweight/(na+1);
  110131. a->xa=xa*weight+xb;
  110132. a->ya=ya*weight+yb;
  110133. a->x2a=x2a*weight+x2b;
  110134. a->y2a=y2a*weight+y2b;
  110135. a->xya=xya*weight+xyb;
  110136. a->an=na*weight+nb;
  110137. }
  110138. return(na);
  110139. }
  110140. static void fit_line(lsfit_acc *a,int fits,int *y0,int *y1){
  110141. long x=0,y=0,x2=0,y2=0,xy=0,an=0,i;
  110142. long x0=a[0].x0;
  110143. long x1=a[fits-1].x1;
  110144. for(i=0;i<fits;i++){
  110145. x+=a[i].xa;
  110146. y+=a[i].ya;
  110147. x2+=a[i].x2a;
  110148. y2+=a[i].y2a;
  110149. xy+=a[i].xya;
  110150. an+=a[i].an;
  110151. }
  110152. if(*y0>=0){
  110153. x+= x0;
  110154. y+= *y0;
  110155. x2+= x0 * x0;
  110156. y2+= *y0 * *y0;
  110157. xy+= *y0 * x0;
  110158. an++;
  110159. }
  110160. if(*y1>=0){
  110161. x+= x1;
  110162. y+= *y1;
  110163. x2+= x1 * x1;
  110164. y2+= *y1 * *y1;
  110165. xy+= *y1 * x1;
  110166. an++;
  110167. }
  110168. if(an){
  110169. /* need 64 bit multiplies, which C doesn't give portably as int */
  110170. double fx=x;
  110171. double fy=y;
  110172. double fx2=x2;
  110173. double fxy=xy;
  110174. double denom=1./(an*fx2-fx*fx);
  110175. double a=(fy*fx2-fxy*fx)*denom;
  110176. double b=(an*fxy-fx*fy)*denom;
  110177. *y0=rint(a+b*x0);
  110178. *y1=rint(a+b*x1);
  110179. /* limit to our range! */
  110180. if(*y0>1023)*y0=1023;
  110181. if(*y1>1023)*y1=1023;
  110182. if(*y0<0)*y0=0;
  110183. if(*y1<0)*y1=0;
  110184. }else{
  110185. *y0=0;
  110186. *y1=0;
  110187. }
  110188. }
  110189. /*static void fit_line_point(lsfit_acc *a,int fits,int *y0,int *y1){
  110190. long y=0;
  110191. int i;
  110192. for(i=0;i<fits && y==0;i++)
  110193. y+=a[i].ya;
  110194. *y0=*y1=y;
  110195. }*/
  110196. static int inspect_error(int x0,int x1,int y0,int y1,const float *mask,
  110197. const float *mdct,
  110198. vorbis_info_floor1 *info){
  110199. int dy=y1-y0;
  110200. int adx=x1-x0;
  110201. int ady=abs(dy);
  110202. int base=dy/adx;
  110203. int sy=(dy<0?base-1:base+1);
  110204. int x=x0;
  110205. int y=y0;
  110206. int err=0;
  110207. int val=vorbis_dBquant(mask+x);
  110208. int mse=0;
  110209. int n=0;
  110210. ady-=abs(base*adx);
  110211. mse=(y-val);
  110212. mse*=mse;
  110213. n++;
  110214. if(mdct[x]+info->twofitatten>=mask[x]){
  110215. if(y+info->maxover<val)return(1);
  110216. if(y-info->maxunder>val)return(1);
  110217. }
  110218. while(++x<x1){
  110219. err=err+ady;
  110220. if(err>=adx){
  110221. err-=adx;
  110222. y+=sy;
  110223. }else{
  110224. y+=base;
  110225. }
  110226. val=vorbis_dBquant(mask+x);
  110227. mse+=((y-val)*(y-val));
  110228. n++;
  110229. if(mdct[x]+info->twofitatten>=mask[x]){
  110230. if(val){
  110231. if(y+info->maxover<val)return(1);
  110232. if(y-info->maxunder>val)return(1);
  110233. }
  110234. }
  110235. }
  110236. if(info->maxover*info->maxover/n>info->maxerr)return(0);
  110237. if(info->maxunder*info->maxunder/n>info->maxerr)return(0);
  110238. if(mse/n>info->maxerr)return(1);
  110239. return(0);
  110240. }
  110241. static int post_Y(int *A,int *B,int pos){
  110242. if(A[pos]<0)
  110243. return B[pos];
  110244. if(B[pos]<0)
  110245. return A[pos];
  110246. return (A[pos]+B[pos])>>1;
  110247. }
  110248. int *floor1_fit(vorbis_block *vb,void *look_,
  110249. const float *logmdct, /* in */
  110250. const float *logmask){
  110251. long i,j;
  110252. vorbis_look_floor1 *look = (vorbis_look_floor1*) look_;
  110253. vorbis_info_floor1 *info=look->vi;
  110254. long n=look->n;
  110255. long posts=look->posts;
  110256. long nonzero=0;
  110257. lsfit_acc fits[VIF_POSIT+1];
  110258. int fit_valueA[VIF_POSIT+2]; /* index by range list position */
  110259. int fit_valueB[VIF_POSIT+2]; /* index by range list position */
  110260. int loneighbor[VIF_POSIT+2]; /* sorted index of range list position (+2) */
  110261. int hineighbor[VIF_POSIT+2];
  110262. int *output=NULL;
  110263. int memo[VIF_POSIT+2];
  110264. for(i=0;i<posts;i++)fit_valueA[i]=-200; /* mark all unused */
  110265. for(i=0;i<posts;i++)fit_valueB[i]=-200; /* mark all unused */
  110266. for(i=0;i<posts;i++)loneighbor[i]=0; /* 0 for the implicit 0 post */
  110267. for(i=0;i<posts;i++)hineighbor[i]=1; /* 1 for the implicit post at n */
  110268. for(i=0;i<posts;i++)memo[i]=-1; /* no neighbor yet */
  110269. /* quantize the relevant floor points and collect them into line fit
  110270. structures (one per minimal division) at the same time */
  110271. if(posts==0){
  110272. nonzero+=accumulate_fit(logmask,logmdct,0,n,fits,n,info);
  110273. }else{
  110274. for(i=0;i<posts-1;i++)
  110275. nonzero+=accumulate_fit(logmask,logmdct,look->sorted_index[i],
  110276. look->sorted_index[i+1],fits+i,
  110277. n,info);
  110278. }
  110279. if(nonzero){
  110280. /* start by fitting the implicit base case.... */
  110281. int y0=-200;
  110282. int y1=-200;
  110283. fit_line(fits,posts-1,&y0,&y1);
  110284. fit_valueA[0]=y0;
  110285. fit_valueB[0]=y0;
  110286. fit_valueB[1]=y1;
  110287. fit_valueA[1]=y1;
  110288. /* Non degenerate case */
  110289. /* start progressive splitting. This is a greedy, non-optimal
  110290. algorithm, but simple and close enough to the best
  110291. answer. */
  110292. for(i=2;i<posts;i++){
  110293. int sortpos=look->reverse_index[i];
  110294. int ln=loneighbor[sortpos];
  110295. int hn=hineighbor[sortpos];
  110296. /* eliminate repeat searches of a particular range with a memo */
  110297. if(memo[ln]!=hn){
  110298. /* haven't performed this error search yet */
  110299. int lsortpos=look->reverse_index[ln];
  110300. int hsortpos=look->reverse_index[hn];
  110301. memo[ln]=hn;
  110302. {
  110303. /* A note: we want to bound/minimize *local*, not global, error */
  110304. int lx=info->postlist[ln];
  110305. int hx=info->postlist[hn];
  110306. int ly=post_Y(fit_valueA,fit_valueB,ln);
  110307. int hy=post_Y(fit_valueA,fit_valueB,hn);
  110308. if(ly==-1 || hy==-1){
  110309. exit(1);
  110310. }
  110311. if(inspect_error(lx,hx,ly,hy,logmask,logmdct,info)){
  110312. /* outside error bounds/begin search area. Split it. */
  110313. int ly0=-200;
  110314. int ly1=-200;
  110315. int hy0=-200;
  110316. int hy1=-200;
  110317. fit_line(fits+lsortpos,sortpos-lsortpos,&ly0,&ly1);
  110318. fit_line(fits+sortpos,hsortpos-sortpos,&hy0,&hy1);
  110319. /* store new edge values */
  110320. fit_valueB[ln]=ly0;
  110321. if(ln==0)fit_valueA[ln]=ly0;
  110322. fit_valueA[i]=ly1;
  110323. fit_valueB[i]=hy0;
  110324. fit_valueA[hn]=hy1;
  110325. if(hn==1)fit_valueB[hn]=hy1;
  110326. if(ly1>=0 || hy0>=0){
  110327. /* store new neighbor values */
  110328. for(j=sortpos-1;j>=0;j--)
  110329. if(hineighbor[j]==hn)
  110330. hineighbor[j]=i;
  110331. else
  110332. break;
  110333. for(j=sortpos+1;j<posts;j++)
  110334. if(loneighbor[j]==ln)
  110335. loneighbor[j]=i;
  110336. else
  110337. break;
  110338. }
  110339. }else{
  110340. fit_valueA[i]=-200;
  110341. fit_valueB[i]=-200;
  110342. }
  110343. }
  110344. }
  110345. }
  110346. output=(int*)_vorbis_block_alloc(vb,sizeof(*output)*posts);
  110347. output[0]=post_Y(fit_valueA,fit_valueB,0);
  110348. output[1]=post_Y(fit_valueA,fit_valueB,1);
  110349. /* fill in posts marked as not using a fit; we will zero
  110350. back out to 'unused' when encoding them so long as curve
  110351. interpolation doesn't force them into use */
  110352. for(i=2;i<posts;i++){
  110353. int ln=look->loneighbor[i-2];
  110354. int hn=look->hineighbor[i-2];
  110355. int x0=info->postlist[ln];
  110356. int x1=info->postlist[hn];
  110357. int y0=output[ln];
  110358. int y1=output[hn];
  110359. int predicted=render_point(x0,x1,y0,y1,info->postlist[i]);
  110360. int vx=post_Y(fit_valueA,fit_valueB,i);
  110361. if(vx>=0 && predicted!=vx){
  110362. output[i]=vx;
  110363. }else{
  110364. output[i]= predicted|0x8000;
  110365. }
  110366. }
  110367. }
  110368. return(output);
  110369. }
  110370. int *floor1_interpolate_fit(vorbis_block *vb,void *look_,
  110371. int *A,int *B,
  110372. int del){
  110373. long i;
  110374. vorbis_look_floor1* look = (vorbis_look_floor1*) look_;
  110375. long posts=look->posts;
  110376. int *output=NULL;
  110377. if(A && B){
  110378. output=(int*)_vorbis_block_alloc(vb,sizeof(*output)*posts);
  110379. for(i=0;i<posts;i++){
  110380. output[i]=((65536-del)*(A[i]&0x7fff)+del*(B[i]&0x7fff)+32768)>>16;
  110381. if(A[i]&0x8000 && B[i]&0x8000)output[i]|=0x8000;
  110382. }
  110383. }
  110384. return(output);
  110385. }
  110386. int floor1_encode(oggpack_buffer *opb,vorbis_block *vb,
  110387. void*look_,
  110388. int *post,int *ilogmask){
  110389. long i,j;
  110390. vorbis_look_floor1 *look = (vorbis_look_floor1 *) look_;
  110391. vorbis_info_floor1 *info=look->vi;
  110392. long posts=look->posts;
  110393. codec_setup_info *ci=(codec_setup_info*)vb->vd->vi->codec_setup;
  110394. int out[VIF_POSIT+2];
  110395. static_codebook **sbooks=ci->book_param;
  110396. codebook *books=ci->fullbooks;
  110397. static long seq=0;
  110398. /* quantize values to multiplier spec */
  110399. if(post){
  110400. for(i=0;i<posts;i++){
  110401. int val=post[i]&0x7fff;
  110402. switch(info->mult){
  110403. case 1: /* 1024 -> 256 */
  110404. val>>=2;
  110405. break;
  110406. case 2: /* 1024 -> 128 */
  110407. val>>=3;
  110408. break;
  110409. case 3: /* 1024 -> 86 */
  110410. val/=12;
  110411. break;
  110412. case 4: /* 1024 -> 64 */
  110413. val>>=4;
  110414. break;
  110415. }
  110416. post[i]=val | (post[i]&0x8000);
  110417. }
  110418. out[0]=post[0];
  110419. out[1]=post[1];
  110420. /* find prediction values for each post and subtract them */
  110421. for(i=2;i<posts;i++){
  110422. int ln=look->loneighbor[i-2];
  110423. int hn=look->hineighbor[i-2];
  110424. int x0=info->postlist[ln];
  110425. int x1=info->postlist[hn];
  110426. int y0=post[ln];
  110427. int y1=post[hn];
  110428. int predicted=render_point(x0,x1,y0,y1,info->postlist[i]);
  110429. if((post[i]&0x8000) || (predicted==post[i])){
  110430. post[i]=predicted|0x8000; /* in case there was roundoff jitter
  110431. in interpolation */
  110432. out[i]=0;
  110433. }else{
  110434. int headroom=(look->quant_q-predicted<predicted?
  110435. look->quant_q-predicted:predicted);
  110436. int val=post[i]-predicted;
  110437. /* at this point the 'deviation' value is in the range +/- max
  110438. range, but the real, unique range can always be mapped to
  110439. only [0-maxrange). So we want to wrap the deviation into
  110440. this limited range, but do it in the way that least screws
  110441. an essentially gaussian probability distribution. */
  110442. if(val<0)
  110443. if(val<-headroom)
  110444. val=headroom-val-1;
  110445. else
  110446. val=-1-(val<<1);
  110447. else
  110448. if(val>=headroom)
  110449. val= val+headroom;
  110450. else
  110451. val<<=1;
  110452. out[i]=val;
  110453. post[ln]&=0x7fff;
  110454. post[hn]&=0x7fff;
  110455. }
  110456. }
  110457. /* we have everything we need. pack it out */
  110458. /* mark nontrivial floor */
  110459. oggpack_write(opb,1,1);
  110460. /* beginning/end post */
  110461. look->frames++;
  110462. look->postbits+=ilog(look->quant_q-1)*2;
  110463. oggpack_write(opb,out[0],ilog(look->quant_q-1));
  110464. oggpack_write(opb,out[1],ilog(look->quant_q-1));
  110465. /* partition by partition */
  110466. for(i=0,j=2;i<info->partitions;i++){
  110467. int classx=info->partitionclass[i];
  110468. int cdim=info->class_dim[classx];
  110469. int csubbits=info->class_subs[classx];
  110470. int csub=1<<csubbits;
  110471. int bookas[8]={0,0,0,0,0,0,0,0};
  110472. int cval=0;
  110473. int cshift=0;
  110474. int k,l;
  110475. /* generate the partition's first stage cascade value */
  110476. if(csubbits){
  110477. int maxval[8];
  110478. for(k=0;k<csub;k++){
  110479. int booknum=info->class_subbook[classx][k];
  110480. if(booknum<0){
  110481. maxval[k]=1;
  110482. }else{
  110483. maxval[k]=sbooks[info->class_subbook[classx][k]]->entries;
  110484. }
  110485. }
  110486. for(k=0;k<cdim;k++){
  110487. for(l=0;l<csub;l++){
  110488. int val=out[j+k];
  110489. if(val<maxval[l]){
  110490. bookas[k]=l;
  110491. break;
  110492. }
  110493. }
  110494. cval|= bookas[k]<<cshift;
  110495. cshift+=csubbits;
  110496. }
  110497. /* write it */
  110498. look->phrasebits+=
  110499. vorbis_book_encode(books+info->class_book[classx],cval,opb);
  110500. #ifdef TRAIN_FLOOR1
  110501. {
  110502. FILE *of;
  110503. char buffer[80];
  110504. sprintf(buffer,"line_%dx%ld_class%d.vqd",
  110505. vb->pcmend/2,posts-2,class);
  110506. of=fopen(buffer,"a");
  110507. fprintf(of,"%d\n",cval);
  110508. fclose(of);
  110509. }
  110510. #endif
  110511. }
  110512. /* write post values */
  110513. for(k=0;k<cdim;k++){
  110514. int book=info->class_subbook[classx][bookas[k]];
  110515. if(book>=0){
  110516. /* hack to allow training with 'bad' books */
  110517. if(out[j+k]<(books+book)->entries)
  110518. look->postbits+=vorbis_book_encode(books+book,
  110519. out[j+k],opb);
  110520. /*else
  110521. fprintf(stderr,"+!");*/
  110522. #ifdef TRAIN_FLOOR1
  110523. {
  110524. FILE *of;
  110525. char buffer[80];
  110526. sprintf(buffer,"line_%dx%ld_%dsub%d.vqd",
  110527. vb->pcmend/2,posts-2,class,bookas[k]);
  110528. of=fopen(buffer,"a");
  110529. fprintf(of,"%d\n",out[j+k]);
  110530. fclose(of);
  110531. }
  110532. #endif
  110533. }
  110534. }
  110535. j+=cdim;
  110536. }
  110537. {
  110538. /* generate quantized floor equivalent to what we'd unpack in decode */
  110539. /* render the lines */
  110540. int hx=0;
  110541. int lx=0;
  110542. int ly=post[0]*info->mult;
  110543. for(j=1;j<look->posts;j++){
  110544. int current=look->forward_index[j];
  110545. int hy=post[current]&0x7fff;
  110546. if(hy==post[current]){
  110547. hy*=info->mult;
  110548. hx=info->postlist[current];
  110549. render_line0(lx,hx,ly,hy,ilogmask);
  110550. lx=hx;
  110551. ly=hy;
  110552. }
  110553. }
  110554. for(j=hx;j<vb->pcmend/2;j++)ilogmask[j]=ly; /* be certain */
  110555. seq++;
  110556. return(1);
  110557. }
  110558. }else{
  110559. oggpack_write(opb,0,1);
  110560. memset(ilogmask,0,vb->pcmend/2*sizeof(*ilogmask));
  110561. seq++;
  110562. return(0);
  110563. }
  110564. }
  110565. static void *floor1_inverse1(vorbis_block *vb,vorbis_look_floor *in){
  110566. vorbis_look_floor1 *look=(vorbis_look_floor1 *)in;
  110567. vorbis_info_floor1 *info=look->vi;
  110568. codec_setup_info *ci=(codec_setup_info*)vb->vd->vi->codec_setup;
  110569. int i,j,k;
  110570. codebook *books=ci->fullbooks;
  110571. /* unpack wrapped/predicted values from stream */
  110572. if(oggpack_read(&vb->opb,1)==1){
  110573. int *fit_value=(int*)_vorbis_block_alloc(vb,(look->posts)*sizeof(*fit_value));
  110574. fit_value[0]=oggpack_read(&vb->opb,ilog(look->quant_q-1));
  110575. fit_value[1]=oggpack_read(&vb->opb,ilog(look->quant_q-1));
  110576. /* partition by partition */
  110577. for(i=0,j=2;i<info->partitions;i++){
  110578. int classx=info->partitionclass[i];
  110579. int cdim=info->class_dim[classx];
  110580. int csubbits=info->class_subs[classx];
  110581. int csub=1<<csubbits;
  110582. int cval=0;
  110583. /* decode the partition's first stage cascade value */
  110584. if(csubbits){
  110585. cval=vorbis_book_decode(books+info->class_book[classx],&vb->opb);
  110586. if(cval==-1)goto eop;
  110587. }
  110588. for(k=0;k<cdim;k++){
  110589. int book=info->class_subbook[classx][cval&(csub-1)];
  110590. cval>>=csubbits;
  110591. if(book>=0){
  110592. if((fit_value[j+k]=vorbis_book_decode(books+book,&vb->opb))==-1)
  110593. goto eop;
  110594. }else{
  110595. fit_value[j+k]=0;
  110596. }
  110597. }
  110598. j+=cdim;
  110599. }
  110600. /* unwrap positive values and reconsitute via linear interpolation */
  110601. for(i=2;i<look->posts;i++){
  110602. int predicted=render_point(info->postlist[look->loneighbor[i-2]],
  110603. info->postlist[look->hineighbor[i-2]],
  110604. fit_value[look->loneighbor[i-2]],
  110605. fit_value[look->hineighbor[i-2]],
  110606. info->postlist[i]);
  110607. int hiroom=look->quant_q-predicted;
  110608. int loroom=predicted;
  110609. int room=(hiroom<loroom?hiroom:loroom)<<1;
  110610. int val=fit_value[i];
  110611. if(val){
  110612. if(val>=room){
  110613. if(hiroom>loroom){
  110614. val = val-loroom;
  110615. }else{
  110616. val = -1-(val-hiroom);
  110617. }
  110618. }else{
  110619. if(val&1){
  110620. val= -((val+1)>>1);
  110621. }else{
  110622. val>>=1;
  110623. }
  110624. }
  110625. fit_value[i]=val+predicted;
  110626. fit_value[look->loneighbor[i-2]]&=0x7fff;
  110627. fit_value[look->hineighbor[i-2]]&=0x7fff;
  110628. }else{
  110629. fit_value[i]=predicted|0x8000;
  110630. }
  110631. }
  110632. return(fit_value);
  110633. }
  110634. eop:
  110635. return(NULL);
  110636. }
  110637. static int floor1_inverse2(vorbis_block *vb,vorbis_look_floor *in,void *memo,
  110638. float *out){
  110639. vorbis_look_floor1 *look=(vorbis_look_floor1 *)in;
  110640. vorbis_info_floor1 *info=look->vi;
  110641. codec_setup_info *ci=(codec_setup_info*)vb->vd->vi->codec_setup;
  110642. int n=ci->blocksizes[vb->W]/2;
  110643. int j;
  110644. if(memo){
  110645. /* render the lines */
  110646. int *fit_value=(int *)memo;
  110647. int hx=0;
  110648. int lx=0;
  110649. int ly=fit_value[0]*info->mult;
  110650. for(j=1;j<look->posts;j++){
  110651. int current=look->forward_index[j];
  110652. int hy=fit_value[current]&0x7fff;
  110653. if(hy==fit_value[current]){
  110654. hy*=info->mult;
  110655. hx=info->postlist[current];
  110656. render_line(lx,hx,ly,hy,out);
  110657. lx=hx;
  110658. ly=hy;
  110659. }
  110660. }
  110661. for(j=hx;j<n;j++)out[j]*=FLOOR1_fromdB_LOOKUP[ly]; /* be certain */
  110662. return(1);
  110663. }
  110664. memset(out,0,sizeof(*out)*n);
  110665. return(0);
  110666. }
  110667. /* export hooks */
  110668. vorbis_func_floor floor1_exportbundle={
  110669. &floor1_pack,&floor1_unpack,&floor1_look,&floor1_free_info,
  110670. &floor1_free_look,&floor1_inverse1,&floor1_inverse2
  110671. };
  110672. #endif
  110673. /*** End of inlined file: floor1.c ***/
  110674. /*** Start of inlined file: info.c ***/
  110675. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  110676. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  110677. // tasks..
  110678. #if JUCE_MSVC
  110679. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  110680. #endif
  110681. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  110682. #if JUCE_USE_OGGVORBIS
  110683. /* general handling of the header and the vorbis_info structure (and
  110684. substructures) */
  110685. #include <stdlib.h>
  110686. #include <string.h>
  110687. #include <ctype.h>
  110688. static void _v_writestring(oggpack_buffer *o, const char *s, int bytes){
  110689. while(bytes--){
  110690. oggpack_write(o,*s++,8);
  110691. }
  110692. }
  110693. static void _v_readstring(oggpack_buffer *o,char *buf,int bytes){
  110694. while(bytes--){
  110695. *buf++=oggpack_read(o,8);
  110696. }
  110697. }
  110698. void vorbis_comment_init(vorbis_comment *vc){
  110699. memset(vc,0,sizeof(*vc));
  110700. }
  110701. void vorbis_comment_add(vorbis_comment *vc,char *comment){
  110702. vc->user_comments=(char**)_ogg_realloc(vc->user_comments,
  110703. (vc->comments+2)*sizeof(*vc->user_comments));
  110704. vc->comment_lengths=(int*)_ogg_realloc(vc->comment_lengths,
  110705. (vc->comments+2)*sizeof(*vc->comment_lengths));
  110706. vc->comment_lengths[vc->comments]=strlen(comment);
  110707. vc->user_comments[vc->comments]=(char*)_ogg_malloc(vc->comment_lengths[vc->comments]+1);
  110708. strcpy(vc->user_comments[vc->comments], comment);
  110709. vc->comments++;
  110710. vc->user_comments[vc->comments]=NULL;
  110711. }
  110712. void vorbis_comment_add_tag(vorbis_comment *vc, const char *tag, char *contents){
  110713. char *comment=(char*)alloca(strlen(tag)+strlen(contents)+2); /* +2 for = and \0 */
  110714. strcpy(comment, tag);
  110715. strcat(comment, "=");
  110716. strcat(comment, contents);
  110717. vorbis_comment_add(vc, comment);
  110718. }
  110719. /* This is more or less the same as strncasecmp - but that doesn't exist
  110720. * everywhere, and this is a fairly trivial function, so we include it */
  110721. static int tagcompare(const char *s1, const char *s2, int n){
  110722. int c=0;
  110723. while(c < n){
  110724. if(toupper(s1[c]) != toupper(s2[c]))
  110725. return !0;
  110726. c++;
  110727. }
  110728. return 0;
  110729. }
  110730. char *vorbis_comment_query(vorbis_comment *vc, char *tag, int count){
  110731. long i;
  110732. int found = 0;
  110733. int taglen = strlen(tag)+1; /* +1 for the = we append */
  110734. char *fulltag = (char*)alloca(taglen+ 1);
  110735. strcpy(fulltag, tag);
  110736. strcat(fulltag, "=");
  110737. for(i=0;i<vc->comments;i++){
  110738. if(!tagcompare(vc->user_comments[i], fulltag, taglen)){
  110739. if(count == found)
  110740. /* We return a pointer to the data, not a copy */
  110741. return vc->user_comments[i] + taglen;
  110742. else
  110743. found++;
  110744. }
  110745. }
  110746. return NULL; /* didn't find anything */
  110747. }
  110748. int vorbis_comment_query_count(vorbis_comment *vc, char *tag){
  110749. int i,count=0;
  110750. int taglen = strlen(tag)+1; /* +1 for the = we append */
  110751. char *fulltag = (char*)alloca(taglen+1);
  110752. strcpy(fulltag,tag);
  110753. strcat(fulltag, "=");
  110754. for(i=0;i<vc->comments;i++){
  110755. if(!tagcompare(vc->user_comments[i], fulltag, taglen))
  110756. count++;
  110757. }
  110758. return count;
  110759. }
  110760. void vorbis_comment_clear(vorbis_comment *vc){
  110761. if(vc){
  110762. long i;
  110763. for(i=0;i<vc->comments;i++)
  110764. if(vc->user_comments[i])_ogg_free(vc->user_comments[i]);
  110765. if(vc->user_comments)_ogg_free(vc->user_comments);
  110766. if(vc->comment_lengths)_ogg_free(vc->comment_lengths);
  110767. if(vc->vendor)_ogg_free(vc->vendor);
  110768. }
  110769. memset(vc,0,sizeof(*vc));
  110770. }
  110771. /* blocksize 0 is guaranteed to be short, 1 is guarantted to be long.
  110772. They may be equal, but short will never ge greater than long */
  110773. int vorbis_info_blocksize(vorbis_info *vi,int zo){
  110774. codec_setup_info *ci = (codec_setup_info*)vi->codec_setup;
  110775. return ci ? ci->blocksizes[zo] : -1;
  110776. }
  110777. /* used by synthesis, which has a full, alloced vi */
  110778. void vorbis_info_init(vorbis_info *vi){
  110779. memset(vi,0,sizeof(*vi));
  110780. vi->codec_setup=_ogg_calloc(1,sizeof(codec_setup_info));
  110781. }
  110782. void vorbis_info_clear(vorbis_info *vi){
  110783. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  110784. int i;
  110785. if(ci){
  110786. for(i=0;i<ci->modes;i++)
  110787. if(ci->mode_param[i])_ogg_free(ci->mode_param[i]);
  110788. for(i=0;i<ci->maps;i++) /* unpack does the range checking */
  110789. _mapping_P[ci->map_type[i]]->free_info(ci->map_param[i]);
  110790. for(i=0;i<ci->floors;i++) /* unpack does the range checking */
  110791. _floor_P[ci->floor_type[i]]->free_info(ci->floor_param[i]);
  110792. for(i=0;i<ci->residues;i++) /* unpack does the range checking */
  110793. _residue_P[ci->residue_type[i]]->free_info(ci->residue_param[i]);
  110794. for(i=0;i<ci->books;i++){
  110795. if(ci->book_param[i]){
  110796. /* knows if the book was not alloced */
  110797. vorbis_staticbook_destroy(ci->book_param[i]);
  110798. }
  110799. if(ci->fullbooks)
  110800. vorbis_book_clear(ci->fullbooks+i);
  110801. }
  110802. if(ci->fullbooks)
  110803. _ogg_free(ci->fullbooks);
  110804. for(i=0;i<ci->psys;i++)
  110805. _vi_psy_free(ci->psy_param[i]);
  110806. _ogg_free(ci);
  110807. }
  110808. memset(vi,0,sizeof(*vi));
  110809. }
  110810. /* Header packing/unpacking ********************************************/
  110811. static int _vorbis_unpack_info(vorbis_info *vi,oggpack_buffer *opb){
  110812. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  110813. if(!ci)return(OV_EFAULT);
  110814. vi->version=oggpack_read(opb,32);
  110815. if(vi->version!=0)return(OV_EVERSION);
  110816. vi->channels=oggpack_read(opb,8);
  110817. vi->rate=oggpack_read(opb,32);
  110818. vi->bitrate_upper=oggpack_read(opb,32);
  110819. vi->bitrate_nominal=oggpack_read(opb,32);
  110820. vi->bitrate_lower=oggpack_read(opb,32);
  110821. ci->blocksizes[0]=1<<oggpack_read(opb,4);
  110822. ci->blocksizes[1]=1<<oggpack_read(opb,4);
  110823. if(vi->rate<1)goto err_out;
  110824. if(vi->channels<1)goto err_out;
  110825. if(ci->blocksizes[0]<8)goto err_out;
  110826. if(ci->blocksizes[1]<ci->blocksizes[0])goto err_out;
  110827. if(oggpack_read(opb,1)!=1)goto err_out; /* EOP check */
  110828. return(0);
  110829. err_out:
  110830. vorbis_info_clear(vi);
  110831. return(OV_EBADHEADER);
  110832. }
  110833. static int _vorbis_unpack_comment(vorbis_comment *vc,oggpack_buffer *opb){
  110834. int i;
  110835. int vendorlen=oggpack_read(opb,32);
  110836. if(vendorlen<0)goto err_out;
  110837. vc->vendor=(char*)_ogg_calloc(vendorlen+1,1);
  110838. _v_readstring(opb,vc->vendor,vendorlen);
  110839. vc->comments=oggpack_read(opb,32);
  110840. if(vc->comments<0)goto err_out;
  110841. vc->user_comments=(char**)_ogg_calloc(vc->comments+1,sizeof(*vc->user_comments));
  110842. vc->comment_lengths=(int*)_ogg_calloc(vc->comments+1, sizeof(*vc->comment_lengths));
  110843. for(i=0;i<vc->comments;i++){
  110844. int len=oggpack_read(opb,32);
  110845. if(len<0)goto err_out;
  110846. vc->comment_lengths[i]=len;
  110847. vc->user_comments[i]=(char*)_ogg_calloc(len+1,1);
  110848. _v_readstring(opb,vc->user_comments[i],len);
  110849. }
  110850. if(oggpack_read(opb,1)!=1)goto err_out; /* EOP check */
  110851. return(0);
  110852. err_out:
  110853. vorbis_comment_clear(vc);
  110854. return(OV_EBADHEADER);
  110855. }
  110856. /* all of the real encoding details are here. The modes, books,
  110857. everything */
  110858. static int _vorbis_unpack_books(vorbis_info *vi,oggpack_buffer *opb){
  110859. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  110860. int i;
  110861. if(!ci)return(OV_EFAULT);
  110862. /* codebooks */
  110863. ci->books=oggpack_read(opb,8)+1;
  110864. /*ci->book_param=_ogg_calloc(ci->books,sizeof(*ci->book_param));*/
  110865. for(i=0;i<ci->books;i++){
  110866. ci->book_param[i]=(static_codebook*)_ogg_calloc(1,sizeof(*ci->book_param[i]));
  110867. if(vorbis_staticbook_unpack(opb,ci->book_param[i]))goto err_out;
  110868. }
  110869. /* time backend settings; hooks are unused */
  110870. {
  110871. int times=oggpack_read(opb,6)+1;
  110872. for(i=0;i<times;i++){
  110873. int test=oggpack_read(opb,16);
  110874. if(test<0 || test>=VI_TIMEB)goto err_out;
  110875. }
  110876. }
  110877. /* floor backend settings */
  110878. ci->floors=oggpack_read(opb,6)+1;
  110879. /*ci->floor_type=_ogg_malloc(ci->floors*sizeof(*ci->floor_type));*/
  110880. /*ci->floor_param=_ogg_calloc(ci->floors,sizeof(void *));*/
  110881. for(i=0;i<ci->floors;i++){
  110882. ci->floor_type[i]=oggpack_read(opb,16);
  110883. if(ci->floor_type[i]<0 || ci->floor_type[i]>=VI_FLOORB)goto err_out;
  110884. ci->floor_param[i]=_floor_P[ci->floor_type[i]]->unpack(vi,opb);
  110885. if(!ci->floor_param[i])goto err_out;
  110886. }
  110887. /* residue backend settings */
  110888. ci->residues=oggpack_read(opb,6)+1;
  110889. /*ci->residue_type=_ogg_malloc(ci->residues*sizeof(*ci->residue_type));*/
  110890. /*ci->residue_param=_ogg_calloc(ci->residues,sizeof(void *));*/
  110891. for(i=0;i<ci->residues;i++){
  110892. ci->residue_type[i]=oggpack_read(opb,16);
  110893. if(ci->residue_type[i]<0 || ci->residue_type[i]>=VI_RESB)goto err_out;
  110894. ci->residue_param[i]=_residue_P[ci->residue_type[i]]->unpack(vi,opb);
  110895. if(!ci->residue_param[i])goto err_out;
  110896. }
  110897. /* map backend settings */
  110898. ci->maps=oggpack_read(opb,6)+1;
  110899. /*ci->map_type=_ogg_malloc(ci->maps*sizeof(*ci->map_type));*/
  110900. /*ci->map_param=_ogg_calloc(ci->maps,sizeof(void *));*/
  110901. for(i=0;i<ci->maps;i++){
  110902. ci->map_type[i]=oggpack_read(opb,16);
  110903. if(ci->map_type[i]<0 || ci->map_type[i]>=VI_MAPB)goto err_out;
  110904. ci->map_param[i]=_mapping_P[ci->map_type[i]]->unpack(vi,opb);
  110905. if(!ci->map_param[i])goto err_out;
  110906. }
  110907. /* mode settings */
  110908. ci->modes=oggpack_read(opb,6)+1;
  110909. /*vi->mode_param=_ogg_calloc(vi->modes,sizeof(void *));*/
  110910. for(i=0;i<ci->modes;i++){
  110911. ci->mode_param[i]=(vorbis_info_mode*)_ogg_calloc(1,sizeof(*ci->mode_param[i]));
  110912. ci->mode_param[i]->blockflag=oggpack_read(opb,1);
  110913. ci->mode_param[i]->windowtype=oggpack_read(opb,16);
  110914. ci->mode_param[i]->transformtype=oggpack_read(opb,16);
  110915. ci->mode_param[i]->mapping=oggpack_read(opb,8);
  110916. if(ci->mode_param[i]->windowtype>=VI_WINDOWB)goto err_out;
  110917. if(ci->mode_param[i]->transformtype>=VI_WINDOWB)goto err_out;
  110918. if(ci->mode_param[i]->mapping>=ci->maps)goto err_out;
  110919. }
  110920. if(oggpack_read(opb,1)!=1)goto err_out; /* top level EOP check */
  110921. return(0);
  110922. err_out:
  110923. vorbis_info_clear(vi);
  110924. return(OV_EBADHEADER);
  110925. }
  110926. /* The Vorbis header is in three packets; the initial small packet in
  110927. the first page that identifies basic parameters, a second packet
  110928. with bitstream comments and a third packet that holds the
  110929. codebook. */
  110930. int vorbis_synthesis_headerin(vorbis_info *vi,vorbis_comment *vc,ogg_packet *op){
  110931. oggpack_buffer opb;
  110932. if(op){
  110933. oggpack_readinit(&opb,op->packet,op->bytes);
  110934. /* Which of the three types of header is this? */
  110935. /* Also verify header-ness, vorbis */
  110936. {
  110937. char buffer[6];
  110938. int packtype=oggpack_read(&opb,8);
  110939. memset(buffer,0,6);
  110940. _v_readstring(&opb,buffer,6);
  110941. if(memcmp(buffer,"vorbis",6)){
  110942. /* not a vorbis header */
  110943. return(OV_ENOTVORBIS);
  110944. }
  110945. switch(packtype){
  110946. case 0x01: /* least significant *bit* is read first */
  110947. if(!op->b_o_s){
  110948. /* Not the initial packet */
  110949. return(OV_EBADHEADER);
  110950. }
  110951. if(vi->rate!=0){
  110952. /* previously initialized info header */
  110953. return(OV_EBADHEADER);
  110954. }
  110955. return(_vorbis_unpack_info(vi,&opb));
  110956. case 0x03: /* least significant *bit* is read first */
  110957. if(vi->rate==0){
  110958. /* um... we didn't get the initial header */
  110959. return(OV_EBADHEADER);
  110960. }
  110961. return(_vorbis_unpack_comment(vc,&opb));
  110962. case 0x05: /* least significant *bit* is read first */
  110963. if(vi->rate==0 || vc->vendor==NULL){
  110964. /* um... we didn;t get the initial header or comments yet */
  110965. return(OV_EBADHEADER);
  110966. }
  110967. return(_vorbis_unpack_books(vi,&opb));
  110968. default:
  110969. /* Not a valid vorbis header type */
  110970. return(OV_EBADHEADER);
  110971. break;
  110972. }
  110973. }
  110974. }
  110975. return(OV_EBADHEADER);
  110976. }
  110977. /* pack side **********************************************************/
  110978. static int _vorbis_pack_info(oggpack_buffer *opb,vorbis_info *vi){
  110979. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  110980. if(!ci)return(OV_EFAULT);
  110981. /* preamble */
  110982. oggpack_write(opb,0x01,8);
  110983. _v_writestring(opb,"vorbis", 6);
  110984. /* basic information about the stream */
  110985. oggpack_write(opb,0x00,32);
  110986. oggpack_write(opb,vi->channels,8);
  110987. oggpack_write(opb,vi->rate,32);
  110988. oggpack_write(opb,vi->bitrate_upper,32);
  110989. oggpack_write(opb,vi->bitrate_nominal,32);
  110990. oggpack_write(opb,vi->bitrate_lower,32);
  110991. oggpack_write(opb,ilog2(ci->blocksizes[0]),4);
  110992. oggpack_write(opb,ilog2(ci->blocksizes[1]),4);
  110993. oggpack_write(opb,1,1);
  110994. return(0);
  110995. }
  110996. static int _vorbis_pack_comment(oggpack_buffer *opb,vorbis_comment *vc){
  110997. char temp[]="Xiph.Org libVorbis I 20050304";
  110998. int bytes = strlen(temp);
  110999. /* preamble */
  111000. oggpack_write(opb,0x03,8);
  111001. _v_writestring(opb,"vorbis", 6);
  111002. /* vendor */
  111003. oggpack_write(opb,bytes,32);
  111004. _v_writestring(opb,temp, bytes);
  111005. /* comments */
  111006. oggpack_write(opb,vc->comments,32);
  111007. if(vc->comments){
  111008. int i;
  111009. for(i=0;i<vc->comments;i++){
  111010. if(vc->user_comments[i]){
  111011. oggpack_write(opb,vc->comment_lengths[i],32);
  111012. _v_writestring(opb,vc->user_comments[i], vc->comment_lengths[i]);
  111013. }else{
  111014. oggpack_write(opb,0,32);
  111015. }
  111016. }
  111017. }
  111018. oggpack_write(opb,1,1);
  111019. return(0);
  111020. }
  111021. static int _vorbis_pack_books(oggpack_buffer *opb,vorbis_info *vi){
  111022. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  111023. int i;
  111024. if(!ci)return(OV_EFAULT);
  111025. oggpack_write(opb,0x05,8);
  111026. _v_writestring(opb,"vorbis", 6);
  111027. /* books */
  111028. oggpack_write(opb,ci->books-1,8);
  111029. for(i=0;i<ci->books;i++)
  111030. if(vorbis_staticbook_pack(ci->book_param[i],opb))goto err_out;
  111031. /* times; hook placeholders */
  111032. oggpack_write(opb,0,6);
  111033. oggpack_write(opb,0,16);
  111034. /* floors */
  111035. oggpack_write(opb,ci->floors-1,6);
  111036. for(i=0;i<ci->floors;i++){
  111037. oggpack_write(opb,ci->floor_type[i],16);
  111038. if(_floor_P[ci->floor_type[i]]->pack)
  111039. _floor_P[ci->floor_type[i]]->pack(ci->floor_param[i],opb);
  111040. else
  111041. goto err_out;
  111042. }
  111043. /* residues */
  111044. oggpack_write(opb,ci->residues-1,6);
  111045. for(i=0;i<ci->residues;i++){
  111046. oggpack_write(opb,ci->residue_type[i],16);
  111047. _residue_P[ci->residue_type[i]]->pack(ci->residue_param[i],opb);
  111048. }
  111049. /* maps */
  111050. oggpack_write(opb,ci->maps-1,6);
  111051. for(i=0;i<ci->maps;i++){
  111052. oggpack_write(opb,ci->map_type[i],16);
  111053. _mapping_P[ci->map_type[i]]->pack(vi,ci->map_param[i],opb);
  111054. }
  111055. /* modes */
  111056. oggpack_write(opb,ci->modes-1,6);
  111057. for(i=0;i<ci->modes;i++){
  111058. oggpack_write(opb,ci->mode_param[i]->blockflag,1);
  111059. oggpack_write(opb,ci->mode_param[i]->windowtype,16);
  111060. oggpack_write(opb,ci->mode_param[i]->transformtype,16);
  111061. oggpack_write(opb,ci->mode_param[i]->mapping,8);
  111062. }
  111063. oggpack_write(opb,1,1);
  111064. return(0);
  111065. err_out:
  111066. return(-1);
  111067. }
  111068. int vorbis_commentheader_out(vorbis_comment *vc,
  111069. ogg_packet *op){
  111070. oggpack_buffer opb;
  111071. oggpack_writeinit(&opb);
  111072. if(_vorbis_pack_comment(&opb,vc)) return OV_EIMPL;
  111073. op->packet = (unsigned char*) _ogg_malloc(oggpack_bytes(&opb));
  111074. memcpy(op->packet, opb.buffer, oggpack_bytes(&opb));
  111075. op->bytes=oggpack_bytes(&opb);
  111076. op->b_o_s=0;
  111077. op->e_o_s=0;
  111078. op->granulepos=0;
  111079. op->packetno=1;
  111080. return 0;
  111081. }
  111082. int vorbis_analysis_headerout(vorbis_dsp_state *v,
  111083. vorbis_comment *vc,
  111084. ogg_packet *op,
  111085. ogg_packet *op_comm,
  111086. ogg_packet *op_code){
  111087. int ret=OV_EIMPL;
  111088. vorbis_info *vi=v->vi;
  111089. oggpack_buffer opb;
  111090. private_state *b=(private_state*)v->backend_state;
  111091. if(!b){
  111092. ret=OV_EFAULT;
  111093. goto err_out;
  111094. }
  111095. /* first header packet **********************************************/
  111096. oggpack_writeinit(&opb);
  111097. if(_vorbis_pack_info(&opb,vi))goto err_out;
  111098. /* build the packet */
  111099. if(b->header)_ogg_free(b->header);
  111100. b->header=(unsigned char*) _ogg_malloc(oggpack_bytes(&opb));
  111101. memcpy(b->header,opb.buffer,oggpack_bytes(&opb));
  111102. op->packet=b->header;
  111103. op->bytes=oggpack_bytes(&opb);
  111104. op->b_o_s=1;
  111105. op->e_o_s=0;
  111106. op->granulepos=0;
  111107. op->packetno=0;
  111108. /* second header packet (comments) **********************************/
  111109. oggpack_reset(&opb);
  111110. if(_vorbis_pack_comment(&opb,vc))goto err_out;
  111111. if(b->header1)_ogg_free(b->header1);
  111112. b->header1=(unsigned char*) _ogg_malloc(oggpack_bytes(&opb));
  111113. memcpy(b->header1,opb.buffer,oggpack_bytes(&opb));
  111114. op_comm->packet=b->header1;
  111115. op_comm->bytes=oggpack_bytes(&opb);
  111116. op_comm->b_o_s=0;
  111117. op_comm->e_o_s=0;
  111118. op_comm->granulepos=0;
  111119. op_comm->packetno=1;
  111120. /* third header packet (modes/codebooks) ****************************/
  111121. oggpack_reset(&opb);
  111122. if(_vorbis_pack_books(&opb,vi))goto err_out;
  111123. if(b->header2)_ogg_free(b->header2);
  111124. b->header2=(unsigned char*) _ogg_malloc(oggpack_bytes(&opb));
  111125. memcpy(b->header2,opb.buffer,oggpack_bytes(&opb));
  111126. op_code->packet=b->header2;
  111127. op_code->bytes=oggpack_bytes(&opb);
  111128. op_code->b_o_s=0;
  111129. op_code->e_o_s=0;
  111130. op_code->granulepos=0;
  111131. op_code->packetno=2;
  111132. oggpack_writeclear(&opb);
  111133. return(0);
  111134. err_out:
  111135. oggpack_writeclear(&opb);
  111136. memset(op,0,sizeof(*op));
  111137. memset(op_comm,0,sizeof(*op_comm));
  111138. memset(op_code,0,sizeof(*op_code));
  111139. if(b->header)_ogg_free(b->header);
  111140. if(b->header1)_ogg_free(b->header1);
  111141. if(b->header2)_ogg_free(b->header2);
  111142. b->header=NULL;
  111143. b->header1=NULL;
  111144. b->header2=NULL;
  111145. return(ret);
  111146. }
  111147. double vorbis_granule_time(vorbis_dsp_state *v,ogg_int64_t granulepos){
  111148. if(granulepos>=0)
  111149. return((double)granulepos/v->vi->rate);
  111150. return(-1);
  111151. }
  111152. #endif
  111153. /*** End of inlined file: info.c ***/
  111154. /*** Start of inlined file: lpc.c ***/
  111155. /* Some of these routines (autocorrelator, LPC coefficient estimator)
  111156. are derived from code written by Jutta Degener and Carsten Bormann;
  111157. thus we include their copyright below. The entirety of this file
  111158. is freely redistributable on the condition that both of these
  111159. copyright notices are preserved without modification. */
  111160. /* Preserved Copyright: *********************************************/
  111161. /* Copyright 1992, 1993, 1994 by Jutta Degener and Carsten Bormann,
  111162. Technische Universita"t Berlin
  111163. Any use of this software is permitted provided that this notice is not
  111164. removed and that neither the authors nor the Technische Universita"t
  111165. Berlin are deemed to have made any representations as to the
  111166. suitability of this software for any purpose nor are held responsible
  111167. for any defects of this software. THERE IS ABSOLUTELY NO WARRANTY FOR
  111168. THIS SOFTWARE.
  111169. As a matter of courtesy, the authors request to be informed about uses
  111170. this software has found, about bugs in this software, and about any
  111171. improvements that may be of general interest.
  111172. Berlin, 28.11.1994
  111173. Jutta Degener
  111174. Carsten Bormann
  111175. *********************************************************************/
  111176. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  111177. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  111178. // tasks..
  111179. #if JUCE_MSVC
  111180. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  111181. #endif
  111182. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  111183. #if JUCE_USE_OGGVORBIS
  111184. #include <stdlib.h>
  111185. #include <string.h>
  111186. #include <math.h>
  111187. /* Autocorrelation LPC coeff generation algorithm invented by
  111188. N. Levinson in 1947, modified by J. Durbin in 1959. */
  111189. /* Input : n elements of time doamin data
  111190. Output: m lpc coefficients, excitation energy */
  111191. float vorbis_lpc_from_data(float *data,float *lpci,int n,int m){
  111192. double *aut=(double*)alloca(sizeof(*aut)*(m+1));
  111193. double *lpc=(double*)alloca(sizeof(*lpc)*(m));
  111194. double error;
  111195. int i,j;
  111196. /* autocorrelation, p+1 lag coefficients */
  111197. j=m+1;
  111198. while(j--){
  111199. double d=0; /* double needed for accumulator depth */
  111200. for(i=j;i<n;i++)d+=(double)data[i]*data[i-j];
  111201. aut[j]=d;
  111202. }
  111203. /* Generate lpc coefficients from autocorr values */
  111204. error=aut[0];
  111205. for(i=0;i<m;i++){
  111206. double r= -aut[i+1];
  111207. if(error==0){
  111208. memset(lpci,0,m*sizeof(*lpci));
  111209. return 0;
  111210. }
  111211. /* Sum up this iteration's reflection coefficient; note that in
  111212. Vorbis we don't save it. If anyone wants to recycle this code
  111213. and needs reflection coefficients, save the results of 'r' from
  111214. each iteration. */
  111215. for(j=0;j<i;j++)r-=lpc[j]*aut[i-j];
  111216. r/=error;
  111217. /* Update LPC coefficients and total error */
  111218. lpc[i]=r;
  111219. for(j=0;j<i/2;j++){
  111220. double tmp=lpc[j];
  111221. lpc[j]+=r*lpc[i-1-j];
  111222. lpc[i-1-j]+=r*tmp;
  111223. }
  111224. if(i%2)lpc[j]+=lpc[j]*r;
  111225. error*=1.f-r*r;
  111226. }
  111227. for(j=0;j<m;j++)lpci[j]=(float)lpc[j];
  111228. /* we need the error value to know how big an impulse to hit the
  111229. filter with later */
  111230. return error;
  111231. }
  111232. void vorbis_lpc_predict(float *coeff,float *prime,int m,
  111233. float *data,long n){
  111234. /* in: coeff[0...m-1] LPC coefficients
  111235. prime[0...m-1] initial values (allocated size of n+m-1)
  111236. out: data[0...n-1] data samples */
  111237. long i,j,o,p;
  111238. float y;
  111239. float *work=(float*)alloca(sizeof(*work)*(m+n));
  111240. if(!prime)
  111241. for(i=0;i<m;i++)
  111242. work[i]=0.f;
  111243. else
  111244. for(i=0;i<m;i++)
  111245. work[i]=prime[i];
  111246. for(i=0;i<n;i++){
  111247. y=0;
  111248. o=i;
  111249. p=m;
  111250. for(j=0;j<m;j++)
  111251. y-=work[o++]*coeff[--p];
  111252. data[i]=work[o]=y;
  111253. }
  111254. }
  111255. #endif
  111256. /*** End of inlined file: lpc.c ***/
  111257. /*** Start of inlined file: lsp.c ***/
  111258. /* Note that the lpc-lsp conversion finds the roots of polynomial with
  111259. an iterative root polisher (CACM algorithm 283). It *is* possible
  111260. to confuse this algorithm into not converging; that should only
  111261. happen with absurdly closely spaced roots (very sharp peaks in the
  111262. LPC f response) which in turn should be impossible in our use of
  111263. the code. If this *does* happen anyway, it's a bug in the floor
  111264. finder; find the cause of the confusion (probably a single bin
  111265. spike or accidental near-float-limit resolution problems) and
  111266. correct it. */
  111267. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  111268. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  111269. // tasks..
  111270. #if JUCE_MSVC
  111271. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  111272. #endif
  111273. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  111274. #if JUCE_USE_OGGVORBIS
  111275. #include <math.h>
  111276. #include <string.h>
  111277. #include <stdlib.h>
  111278. /*** Start of inlined file: lookup.h ***/
  111279. #ifndef _V_LOOKUP_H_
  111280. #ifdef FLOAT_LOOKUP
  111281. extern float vorbis_coslook(float a);
  111282. extern float vorbis_invsqlook(float a);
  111283. extern float vorbis_invsq2explook(int a);
  111284. extern float vorbis_fromdBlook(float a);
  111285. #endif
  111286. #ifdef INT_LOOKUP
  111287. extern long vorbis_invsqlook_i(long a,long e);
  111288. extern long vorbis_coslook_i(long a);
  111289. extern float vorbis_fromdBlook_i(long a);
  111290. #endif
  111291. #endif
  111292. /*** End of inlined file: lookup.h ***/
  111293. /* three possible LSP to f curve functions; the exact computation
  111294. (float), a lookup based float implementation, and an integer
  111295. implementation. The float lookup is likely the optimal choice on
  111296. any machine with an FPU. The integer implementation is *not* fixed
  111297. point (due to the need for a large dynamic range and thus a
  111298. seperately tracked exponent) and thus much more complex than the
  111299. relatively simple float implementations. It's mostly for future
  111300. work on a fully fixed point implementation for processors like the
  111301. ARM family. */
  111302. /* undefine both for the 'old' but more precise implementation */
  111303. #define FLOAT_LOOKUP
  111304. #undef INT_LOOKUP
  111305. #ifdef FLOAT_LOOKUP
  111306. /*** Start of inlined file: lookup.c ***/
  111307. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  111308. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  111309. // tasks..
  111310. #if JUCE_MSVC
  111311. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  111312. #endif
  111313. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  111314. #if JUCE_USE_OGGVORBIS
  111315. #include <math.h>
  111316. /*** Start of inlined file: lookup.h ***/
  111317. #ifndef _V_LOOKUP_H_
  111318. #ifdef FLOAT_LOOKUP
  111319. extern float vorbis_coslook(float a);
  111320. extern float vorbis_invsqlook(float a);
  111321. extern float vorbis_invsq2explook(int a);
  111322. extern float vorbis_fromdBlook(float a);
  111323. #endif
  111324. #ifdef INT_LOOKUP
  111325. extern long vorbis_invsqlook_i(long a,long e);
  111326. extern long vorbis_coslook_i(long a);
  111327. extern float vorbis_fromdBlook_i(long a);
  111328. #endif
  111329. #endif
  111330. /*** End of inlined file: lookup.h ***/
  111331. /*** Start of inlined file: lookup_data.h ***/
  111332. #ifndef _V_LOOKUP_DATA_H_
  111333. #ifdef FLOAT_LOOKUP
  111334. #define COS_LOOKUP_SZ 128
  111335. static float COS_LOOKUP[COS_LOOKUP_SZ+1]={
  111336. +1.0000000000000f,+0.9996988186962f,+0.9987954562052f,+0.9972904566787f,
  111337. +0.9951847266722f,+0.9924795345987f,+0.9891765099648f,+0.9852776423889f,
  111338. +0.9807852804032f,+0.9757021300385f,+0.9700312531945f,+0.9637760657954f,
  111339. +0.9569403357322f,+0.9495281805930f,+0.9415440651830f,+0.9329927988347f,
  111340. +0.9238795325113f,+0.9142097557035f,+0.9039892931234f,+0.8932243011955f,
  111341. +0.8819212643484f,+0.8700869911087f,+0.8577286100003f,+0.8448535652497f,
  111342. +0.8314696123025f,+0.8175848131516f,+0.8032075314806f,+0.7883464276266f,
  111343. +0.7730104533627f,+0.7572088465065f,+0.7409511253550f,+0.7242470829515f,
  111344. +0.7071067811865f,+0.6895405447371f,+0.6715589548470f,+0.6531728429538f,
  111345. +0.6343932841636f,+0.6152315905806f,+0.5956993044924f,+0.5758081914178f,
  111346. +0.5555702330196f,+0.5349976198871f,+0.5141027441932f,+0.4928981922298f,
  111347. +0.4713967368260f,+0.4496113296546f,+0.4275550934303f,+0.4052413140050f,
  111348. +0.3826834323651f,+0.3598950365350f,+0.3368898533922f,+0.3136817403989f,
  111349. +0.2902846772545f,+0.2667127574749f,+0.2429801799033f,+0.2191012401569f,
  111350. +0.1950903220161f,+0.1709618887603f,+0.1467304744554f,+0.1224106751992f,
  111351. +0.0980171403296f,+0.0735645635997f,+0.0490676743274f,+0.0245412285229f,
  111352. +0.0000000000000f,-0.0245412285229f,-0.0490676743274f,-0.0735645635997f,
  111353. -0.0980171403296f,-0.1224106751992f,-0.1467304744554f,-0.1709618887603f,
  111354. -0.1950903220161f,-0.2191012401569f,-0.2429801799033f,-0.2667127574749f,
  111355. -0.2902846772545f,-0.3136817403989f,-0.3368898533922f,-0.3598950365350f,
  111356. -0.3826834323651f,-0.4052413140050f,-0.4275550934303f,-0.4496113296546f,
  111357. -0.4713967368260f,-0.4928981922298f,-0.5141027441932f,-0.5349976198871f,
  111358. -0.5555702330196f,-0.5758081914178f,-0.5956993044924f,-0.6152315905806f,
  111359. -0.6343932841636f,-0.6531728429538f,-0.6715589548470f,-0.6895405447371f,
  111360. -0.7071067811865f,-0.7242470829515f,-0.7409511253550f,-0.7572088465065f,
  111361. -0.7730104533627f,-0.7883464276266f,-0.8032075314806f,-0.8175848131516f,
  111362. -0.8314696123025f,-0.8448535652497f,-0.8577286100003f,-0.8700869911087f,
  111363. -0.8819212643484f,-0.8932243011955f,-0.9039892931234f,-0.9142097557035f,
  111364. -0.9238795325113f,-0.9329927988347f,-0.9415440651830f,-0.9495281805930f,
  111365. -0.9569403357322f,-0.9637760657954f,-0.9700312531945f,-0.9757021300385f,
  111366. -0.9807852804032f,-0.9852776423889f,-0.9891765099648f,-0.9924795345987f,
  111367. -0.9951847266722f,-0.9972904566787f,-0.9987954562052f,-0.9996988186962f,
  111368. -1.0000000000000f,
  111369. };
  111370. #define INVSQ_LOOKUP_SZ 32
  111371. static float INVSQ_LOOKUP[INVSQ_LOOKUP_SZ+1]={
  111372. 1.414213562373f,1.392621247646f,1.371988681140f,1.352246807566f,
  111373. 1.333333333333f,1.315191898443f,1.297771369046f,1.281025230441f,
  111374. 1.264911064067f,1.249390095109f,1.234426799697f,1.219988562661f,
  111375. 1.206045378311f,1.192569588000f,1.179535649239f,1.166919931983f,
  111376. 1.154700538379f,1.142857142857f,1.131370849898f,1.120224067222f,
  111377. 1.109400392450f,1.098884511590f,1.088662107904f,1.078719779941f,
  111378. 1.069044967650f,1.059625885652f,1.050451462878f,1.041511287847f,
  111379. 1.032795558989f,1.024295039463f,1.016001016002f,1.007905261358f,
  111380. 1.000000000000f,
  111381. };
  111382. #define INVSQ2EXP_LOOKUP_MIN (-32)
  111383. #define INVSQ2EXP_LOOKUP_MAX 32
  111384. static float INVSQ2EXP_LOOKUP[INVSQ2EXP_LOOKUP_MAX-\
  111385. INVSQ2EXP_LOOKUP_MIN+1]={
  111386. 65536.f, 46340.95001f, 32768.f, 23170.47501f,
  111387. 16384.f, 11585.2375f, 8192.f, 5792.618751f,
  111388. 4096.f, 2896.309376f, 2048.f, 1448.154688f,
  111389. 1024.f, 724.0773439f, 512.f, 362.038672f,
  111390. 256.f, 181.019336f, 128.f, 90.50966799f,
  111391. 64.f, 45.254834f, 32.f, 22.627417f,
  111392. 16.f, 11.3137085f, 8.f, 5.656854249f,
  111393. 4.f, 2.828427125f, 2.f, 1.414213562f,
  111394. 1.f, 0.7071067812f, 0.5f, 0.3535533906f,
  111395. 0.25f, 0.1767766953f, 0.125f, 0.08838834765f,
  111396. 0.0625f, 0.04419417382f, 0.03125f, 0.02209708691f,
  111397. 0.015625f, 0.01104854346f, 0.0078125f, 0.005524271728f,
  111398. 0.00390625f, 0.002762135864f, 0.001953125f, 0.001381067932f,
  111399. 0.0009765625f, 0.000690533966f, 0.00048828125f, 0.000345266983f,
  111400. 0.000244140625f,0.0001726334915f,0.0001220703125f,8.631674575e-05f,
  111401. 6.103515625e-05f,4.315837288e-05f,3.051757812e-05f,2.157918644e-05f,
  111402. 1.525878906e-05f,
  111403. };
  111404. #endif
  111405. #define FROMdB_LOOKUP_SZ 35
  111406. #define FROMdB2_LOOKUP_SZ 32
  111407. #define FROMdB_SHIFT 5
  111408. #define FROMdB2_SHIFT 3
  111409. #define FROMdB2_MASK 31
  111410. static float FROMdB_LOOKUP[FROMdB_LOOKUP_SZ]={
  111411. 1.f, 0.6309573445f, 0.3981071706f, 0.2511886432f,
  111412. 0.1584893192f, 0.1f, 0.06309573445f, 0.03981071706f,
  111413. 0.02511886432f, 0.01584893192f, 0.01f, 0.006309573445f,
  111414. 0.003981071706f, 0.002511886432f, 0.001584893192f, 0.001f,
  111415. 0.0006309573445f,0.0003981071706f,0.0002511886432f,0.0001584893192f,
  111416. 0.0001f,6.309573445e-05f,3.981071706e-05f,2.511886432e-05f,
  111417. 1.584893192e-05f, 1e-05f,6.309573445e-06f,3.981071706e-06f,
  111418. 2.511886432e-06f,1.584893192e-06f, 1e-06f,6.309573445e-07f,
  111419. 3.981071706e-07f,2.511886432e-07f,1.584893192e-07f,
  111420. };
  111421. static float FROMdB2_LOOKUP[FROMdB2_LOOKUP_SZ]={
  111422. 0.9928302478f, 0.9786445908f, 0.9646616199f, 0.9508784391f,
  111423. 0.9372921937f, 0.92390007f, 0.9106992942f, 0.8976871324f,
  111424. 0.8848608897f, 0.8722179097f, 0.8597555737f, 0.8474713009f,
  111425. 0.835362547f, 0.8234268041f, 0.8116616003f, 0.8000644989f,
  111426. 0.7886330981f, 0.7773650302f, 0.7662579617f, 0.755309592f,
  111427. 0.7445176537f, 0.7338799116f, 0.7233941627f, 0.7130582353f,
  111428. 0.7028699885f, 0.6928273125f, 0.6829281272f, 0.6731703824f,
  111429. 0.6635520573f, 0.6540711597f, 0.6447257262f, 0.6355138211f,
  111430. };
  111431. #ifdef INT_LOOKUP
  111432. #define INVSQ_LOOKUP_I_SHIFT 10
  111433. #define INVSQ_LOOKUP_I_MASK 1023
  111434. static long INVSQ_LOOKUP_I[64+1]={
  111435. 92682l, 91966l, 91267l, 90583l,
  111436. 89915l, 89261l, 88621l, 87995l,
  111437. 87381l, 86781l, 86192l, 85616l,
  111438. 85051l, 84497l, 83953l, 83420l,
  111439. 82897l, 82384l, 81880l, 81385l,
  111440. 80899l, 80422l, 79953l, 79492l,
  111441. 79039l, 78594l, 78156l, 77726l,
  111442. 77302l, 76885l, 76475l, 76072l,
  111443. 75674l, 75283l, 74898l, 74519l,
  111444. 74146l, 73778l, 73415l, 73058l,
  111445. 72706l, 72359l, 72016l, 71679l,
  111446. 71347l, 71019l, 70695l, 70376l,
  111447. 70061l, 69750l, 69444l, 69141l,
  111448. 68842l, 68548l, 68256l, 67969l,
  111449. 67685l, 67405l, 67128l, 66855l,
  111450. 66585l, 66318l, 66054l, 65794l,
  111451. 65536l,
  111452. };
  111453. #define COS_LOOKUP_I_SHIFT 9
  111454. #define COS_LOOKUP_I_MASK 511
  111455. #define COS_LOOKUP_I_SZ 128
  111456. static long COS_LOOKUP_I[COS_LOOKUP_I_SZ+1]={
  111457. 16384l, 16379l, 16364l, 16340l,
  111458. 16305l, 16261l, 16207l, 16143l,
  111459. 16069l, 15986l, 15893l, 15791l,
  111460. 15679l, 15557l, 15426l, 15286l,
  111461. 15137l, 14978l, 14811l, 14635l,
  111462. 14449l, 14256l, 14053l, 13842l,
  111463. 13623l, 13395l, 13160l, 12916l,
  111464. 12665l, 12406l, 12140l, 11866l,
  111465. 11585l, 11297l, 11003l, 10702l,
  111466. 10394l, 10080l, 9760l, 9434l,
  111467. 9102l, 8765l, 8423l, 8076l,
  111468. 7723l, 7366l, 7005l, 6639l,
  111469. 6270l, 5897l, 5520l, 5139l,
  111470. 4756l, 4370l, 3981l, 3590l,
  111471. 3196l, 2801l, 2404l, 2006l,
  111472. 1606l, 1205l, 804l, 402l,
  111473. 0l, -401l, -803l, -1204l,
  111474. -1605l, -2005l, -2403l, -2800l,
  111475. -3195l, -3589l, -3980l, -4369l,
  111476. -4755l, -5138l, -5519l, -5896l,
  111477. -6269l, -6638l, -7004l, -7365l,
  111478. -7722l, -8075l, -8422l, -8764l,
  111479. -9101l, -9433l, -9759l, -10079l,
  111480. -10393l, -10701l, -11002l, -11296l,
  111481. -11584l, -11865l, -12139l, -12405l,
  111482. -12664l, -12915l, -13159l, -13394l,
  111483. -13622l, -13841l, -14052l, -14255l,
  111484. -14448l, -14634l, -14810l, -14977l,
  111485. -15136l, -15285l, -15425l, -15556l,
  111486. -15678l, -15790l, -15892l, -15985l,
  111487. -16068l, -16142l, -16206l, -16260l,
  111488. -16304l, -16339l, -16363l, -16378l,
  111489. -16383l,
  111490. };
  111491. #endif
  111492. #endif
  111493. /*** End of inlined file: lookup_data.h ***/
  111494. #ifdef FLOAT_LOOKUP
  111495. /* interpolated lookup based cos function, domain 0 to PI only */
  111496. float vorbis_coslook(float a){
  111497. double d=a*(.31830989*(float)COS_LOOKUP_SZ);
  111498. int i=vorbis_ftoi(d-.5);
  111499. return COS_LOOKUP[i]+ (d-i)*(COS_LOOKUP[i+1]-COS_LOOKUP[i]);
  111500. }
  111501. /* interpolated 1./sqrt(p) where .5 <= p < 1. */
  111502. float vorbis_invsqlook(float a){
  111503. double d=a*(2.f*(float)INVSQ_LOOKUP_SZ)-(float)INVSQ_LOOKUP_SZ;
  111504. int i=vorbis_ftoi(d-.5f);
  111505. return INVSQ_LOOKUP[i]+ (d-i)*(INVSQ_LOOKUP[i+1]-INVSQ_LOOKUP[i]);
  111506. }
  111507. /* interpolated 1./sqrt(p) where .5 <= p < 1. */
  111508. float vorbis_invsq2explook(int a){
  111509. return INVSQ2EXP_LOOKUP[a-INVSQ2EXP_LOOKUP_MIN];
  111510. }
  111511. #include <stdio.h>
  111512. /* interpolated lookup based fromdB function, domain -140dB to 0dB only */
  111513. float vorbis_fromdBlook(float a){
  111514. int i=vorbis_ftoi(a*((float)(-(1<<FROMdB2_SHIFT)))-.5f);
  111515. return (i<0)?1.f:
  111516. ((i>=(FROMdB_LOOKUP_SZ<<FROMdB_SHIFT))?0.f:
  111517. FROMdB_LOOKUP[i>>FROMdB_SHIFT]*FROMdB2_LOOKUP[i&FROMdB2_MASK]);
  111518. }
  111519. #endif
  111520. #ifdef INT_LOOKUP
  111521. /* interpolated 1./sqrt(p) where .5 <= a < 1. (.100000... to .111111...) in
  111522. 16.16 format
  111523. returns in m.8 format */
  111524. long vorbis_invsqlook_i(long a,long e){
  111525. long i=(a&0x7fff)>>(INVSQ_LOOKUP_I_SHIFT-1);
  111526. long d=(a&INVSQ_LOOKUP_I_MASK)<<(16-INVSQ_LOOKUP_I_SHIFT); /* 0.16 */
  111527. long val=INVSQ_LOOKUP_I[i]- /* 1.16 */
  111528. (((INVSQ_LOOKUP_I[i]-INVSQ_LOOKUP_I[i+1])* /* 0.16 */
  111529. d)>>16); /* result 1.16 */
  111530. e+=32;
  111531. if(e&1)val=(val*5792)>>13; /* multiply val by 1/sqrt(2) */
  111532. e=(e>>1)-8;
  111533. return(val>>e);
  111534. }
  111535. /* interpolated lookup based fromdB function, domain -140dB to 0dB only */
  111536. /* a is in n.12 format */
  111537. float vorbis_fromdBlook_i(long a){
  111538. int i=(-a)>>(12-FROMdB2_SHIFT);
  111539. return (i<0)?1.f:
  111540. ((i>=(FROMdB_LOOKUP_SZ<<FROMdB_SHIFT))?0.f:
  111541. FROMdB_LOOKUP[i>>FROMdB_SHIFT]*FROMdB2_LOOKUP[i&FROMdB2_MASK]);
  111542. }
  111543. /* interpolated lookup based cos function, domain 0 to PI only */
  111544. /* a is in 0.16 format, where 0==0, 2^^16-1==PI, return 0.14 */
  111545. long vorbis_coslook_i(long a){
  111546. int i=a>>COS_LOOKUP_I_SHIFT;
  111547. int d=a&COS_LOOKUP_I_MASK;
  111548. return COS_LOOKUP_I[i]- ((d*(COS_LOOKUP_I[i]-COS_LOOKUP_I[i+1]))>>
  111549. COS_LOOKUP_I_SHIFT);
  111550. }
  111551. #endif
  111552. #endif
  111553. /*** End of inlined file: lookup.c ***/
  111554. /* catch this in the build system; we #include for
  111555. compilers (like gcc) that can't inline across
  111556. modules */
  111557. /* side effect: changes *lsp to cosines of lsp */
  111558. void vorbis_lsp_to_curve(float *curve,int *map,int n,int ln,float *lsp,int m,
  111559. float amp,float ampoffset){
  111560. int i;
  111561. float wdel=M_PI/ln;
  111562. vorbis_fpu_control fpu;
  111563. (void) fpu; // to avoid an unused variable warning
  111564. vorbis_fpu_setround(&fpu);
  111565. for(i=0;i<m;i++)lsp[i]=vorbis_coslook(lsp[i]);
  111566. i=0;
  111567. while(i<n){
  111568. int k=map[i];
  111569. int qexp;
  111570. float p=.7071067812f;
  111571. float q=.7071067812f;
  111572. float w=vorbis_coslook(wdel*k);
  111573. float *ftmp=lsp;
  111574. int c=m>>1;
  111575. do{
  111576. q*=ftmp[0]-w;
  111577. p*=ftmp[1]-w;
  111578. ftmp+=2;
  111579. }while(--c);
  111580. if(m&1){
  111581. /* odd order filter; slightly assymetric */
  111582. /* the last coefficient */
  111583. q*=ftmp[0]-w;
  111584. q*=q;
  111585. p*=p*(1.f-w*w);
  111586. }else{
  111587. /* even order filter; still symmetric */
  111588. q*=q*(1.f+w);
  111589. p*=p*(1.f-w);
  111590. }
  111591. q=frexp(p+q,&qexp);
  111592. q=vorbis_fromdBlook(amp*
  111593. vorbis_invsqlook(q)*
  111594. vorbis_invsq2explook(qexp+m)-
  111595. ampoffset);
  111596. do{
  111597. curve[i++]*=q;
  111598. }while(map[i]==k);
  111599. }
  111600. vorbis_fpu_restore(fpu);
  111601. }
  111602. #else
  111603. #ifdef INT_LOOKUP
  111604. /*** Start of inlined file: lookup.c ***/
  111605. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  111606. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  111607. // tasks..
  111608. #if JUCE_MSVC
  111609. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  111610. #endif
  111611. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  111612. #if JUCE_USE_OGGVORBIS
  111613. #include <math.h>
  111614. /*** Start of inlined file: lookup.h ***/
  111615. #ifndef _V_LOOKUP_H_
  111616. #ifdef FLOAT_LOOKUP
  111617. extern float vorbis_coslook(float a);
  111618. extern float vorbis_invsqlook(float a);
  111619. extern float vorbis_invsq2explook(int a);
  111620. extern float vorbis_fromdBlook(float a);
  111621. #endif
  111622. #ifdef INT_LOOKUP
  111623. extern long vorbis_invsqlook_i(long a,long e);
  111624. extern long vorbis_coslook_i(long a);
  111625. extern float vorbis_fromdBlook_i(long a);
  111626. #endif
  111627. #endif
  111628. /*** End of inlined file: lookup.h ***/
  111629. /*** Start of inlined file: lookup_data.h ***/
  111630. #ifndef _V_LOOKUP_DATA_H_
  111631. #ifdef FLOAT_LOOKUP
  111632. #define COS_LOOKUP_SZ 128
  111633. static float COS_LOOKUP[COS_LOOKUP_SZ+1]={
  111634. +1.0000000000000f,+0.9996988186962f,+0.9987954562052f,+0.9972904566787f,
  111635. +0.9951847266722f,+0.9924795345987f,+0.9891765099648f,+0.9852776423889f,
  111636. +0.9807852804032f,+0.9757021300385f,+0.9700312531945f,+0.9637760657954f,
  111637. +0.9569403357322f,+0.9495281805930f,+0.9415440651830f,+0.9329927988347f,
  111638. +0.9238795325113f,+0.9142097557035f,+0.9039892931234f,+0.8932243011955f,
  111639. +0.8819212643484f,+0.8700869911087f,+0.8577286100003f,+0.8448535652497f,
  111640. +0.8314696123025f,+0.8175848131516f,+0.8032075314806f,+0.7883464276266f,
  111641. +0.7730104533627f,+0.7572088465065f,+0.7409511253550f,+0.7242470829515f,
  111642. +0.7071067811865f,+0.6895405447371f,+0.6715589548470f,+0.6531728429538f,
  111643. +0.6343932841636f,+0.6152315905806f,+0.5956993044924f,+0.5758081914178f,
  111644. +0.5555702330196f,+0.5349976198871f,+0.5141027441932f,+0.4928981922298f,
  111645. +0.4713967368260f,+0.4496113296546f,+0.4275550934303f,+0.4052413140050f,
  111646. +0.3826834323651f,+0.3598950365350f,+0.3368898533922f,+0.3136817403989f,
  111647. +0.2902846772545f,+0.2667127574749f,+0.2429801799033f,+0.2191012401569f,
  111648. +0.1950903220161f,+0.1709618887603f,+0.1467304744554f,+0.1224106751992f,
  111649. +0.0980171403296f,+0.0735645635997f,+0.0490676743274f,+0.0245412285229f,
  111650. +0.0000000000000f,-0.0245412285229f,-0.0490676743274f,-0.0735645635997f,
  111651. -0.0980171403296f,-0.1224106751992f,-0.1467304744554f,-0.1709618887603f,
  111652. -0.1950903220161f,-0.2191012401569f,-0.2429801799033f,-0.2667127574749f,
  111653. -0.2902846772545f,-0.3136817403989f,-0.3368898533922f,-0.3598950365350f,
  111654. -0.3826834323651f,-0.4052413140050f,-0.4275550934303f,-0.4496113296546f,
  111655. -0.4713967368260f,-0.4928981922298f,-0.5141027441932f,-0.5349976198871f,
  111656. -0.5555702330196f,-0.5758081914178f,-0.5956993044924f,-0.6152315905806f,
  111657. -0.6343932841636f,-0.6531728429538f,-0.6715589548470f,-0.6895405447371f,
  111658. -0.7071067811865f,-0.7242470829515f,-0.7409511253550f,-0.7572088465065f,
  111659. -0.7730104533627f,-0.7883464276266f,-0.8032075314806f,-0.8175848131516f,
  111660. -0.8314696123025f,-0.8448535652497f,-0.8577286100003f,-0.8700869911087f,
  111661. -0.8819212643484f,-0.8932243011955f,-0.9039892931234f,-0.9142097557035f,
  111662. -0.9238795325113f,-0.9329927988347f,-0.9415440651830f,-0.9495281805930f,
  111663. -0.9569403357322f,-0.9637760657954f,-0.9700312531945f,-0.9757021300385f,
  111664. -0.9807852804032f,-0.9852776423889f,-0.9891765099648f,-0.9924795345987f,
  111665. -0.9951847266722f,-0.9972904566787f,-0.9987954562052f,-0.9996988186962f,
  111666. -1.0000000000000f,
  111667. };
  111668. #define INVSQ_LOOKUP_SZ 32
  111669. static float INVSQ_LOOKUP[INVSQ_LOOKUP_SZ+1]={
  111670. 1.414213562373f,1.392621247646f,1.371988681140f,1.352246807566f,
  111671. 1.333333333333f,1.315191898443f,1.297771369046f,1.281025230441f,
  111672. 1.264911064067f,1.249390095109f,1.234426799697f,1.219988562661f,
  111673. 1.206045378311f,1.192569588000f,1.179535649239f,1.166919931983f,
  111674. 1.154700538379f,1.142857142857f,1.131370849898f,1.120224067222f,
  111675. 1.109400392450f,1.098884511590f,1.088662107904f,1.078719779941f,
  111676. 1.069044967650f,1.059625885652f,1.050451462878f,1.041511287847f,
  111677. 1.032795558989f,1.024295039463f,1.016001016002f,1.007905261358f,
  111678. 1.000000000000f,
  111679. };
  111680. #define INVSQ2EXP_LOOKUP_MIN (-32)
  111681. #define INVSQ2EXP_LOOKUP_MAX 32
  111682. static float INVSQ2EXP_LOOKUP[INVSQ2EXP_LOOKUP_MAX-\
  111683. INVSQ2EXP_LOOKUP_MIN+1]={
  111684. 65536.f, 46340.95001f, 32768.f, 23170.47501f,
  111685. 16384.f, 11585.2375f, 8192.f, 5792.618751f,
  111686. 4096.f, 2896.309376f, 2048.f, 1448.154688f,
  111687. 1024.f, 724.0773439f, 512.f, 362.038672f,
  111688. 256.f, 181.019336f, 128.f, 90.50966799f,
  111689. 64.f, 45.254834f, 32.f, 22.627417f,
  111690. 16.f, 11.3137085f, 8.f, 5.656854249f,
  111691. 4.f, 2.828427125f, 2.f, 1.414213562f,
  111692. 1.f, 0.7071067812f, 0.5f, 0.3535533906f,
  111693. 0.25f, 0.1767766953f, 0.125f, 0.08838834765f,
  111694. 0.0625f, 0.04419417382f, 0.03125f, 0.02209708691f,
  111695. 0.015625f, 0.01104854346f, 0.0078125f, 0.005524271728f,
  111696. 0.00390625f, 0.002762135864f, 0.001953125f, 0.001381067932f,
  111697. 0.0009765625f, 0.000690533966f, 0.00048828125f, 0.000345266983f,
  111698. 0.000244140625f,0.0001726334915f,0.0001220703125f,8.631674575e-05f,
  111699. 6.103515625e-05f,4.315837288e-05f,3.051757812e-05f,2.157918644e-05f,
  111700. 1.525878906e-05f,
  111701. };
  111702. #endif
  111703. #define FROMdB_LOOKUP_SZ 35
  111704. #define FROMdB2_LOOKUP_SZ 32
  111705. #define FROMdB_SHIFT 5
  111706. #define FROMdB2_SHIFT 3
  111707. #define FROMdB2_MASK 31
  111708. static float FROMdB_LOOKUP[FROMdB_LOOKUP_SZ]={
  111709. 1.f, 0.6309573445f, 0.3981071706f, 0.2511886432f,
  111710. 0.1584893192f, 0.1f, 0.06309573445f, 0.03981071706f,
  111711. 0.02511886432f, 0.01584893192f, 0.01f, 0.006309573445f,
  111712. 0.003981071706f, 0.002511886432f, 0.001584893192f, 0.001f,
  111713. 0.0006309573445f,0.0003981071706f,0.0002511886432f,0.0001584893192f,
  111714. 0.0001f,6.309573445e-05f,3.981071706e-05f,2.511886432e-05f,
  111715. 1.584893192e-05f, 1e-05f,6.309573445e-06f,3.981071706e-06f,
  111716. 2.511886432e-06f,1.584893192e-06f, 1e-06f,6.309573445e-07f,
  111717. 3.981071706e-07f,2.511886432e-07f,1.584893192e-07f,
  111718. };
  111719. static float FROMdB2_LOOKUP[FROMdB2_LOOKUP_SZ]={
  111720. 0.9928302478f, 0.9786445908f, 0.9646616199f, 0.9508784391f,
  111721. 0.9372921937f, 0.92390007f, 0.9106992942f, 0.8976871324f,
  111722. 0.8848608897f, 0.8722179097f, 0.8597555737f, 0.8474713009f,
  111723. 0.835362547f, 0.8234268041f, 0.8116616003f, 0.8000644989f,
  111724. 0.7886330981f, 0.7773650302f, 0.7662579617f, 0.755309592f,
  111725. 0.7445176537f, 0.7338799116f, 0.7233941627f, 0.7130582353f,
  111726. 0.7028699885f, 0.6928273125f, 0.6829281272f, 0.6731703824f,
  111727. 0.6635520573f, 0.6540711597f, 0.6447257262f, 0.6355138211f,
  111728. };
  111729. #ifdef INT_LOOKUP
  111730. #define INVSQ_LOOKUP_I_SHIFT 10
  111731. #define INVSQ_LOOKUP_I_MASK 1023
  111732. static long INVSQ_LOOKUP_I[64+1]={
  111733. 92682l, 91966l, 91267l, 90583l,
  111734. 89915l, 89261l, 88621l, 87995l,
  111735. 87381l, 86781l, 86192l, 85616l,
  111736. 85051l, 84497l, 83953l, 83420l,
  111737. 82897l, 82384l, 81880l, 81385l,
  111738. 80899l, 80422l, 79953l, 79492l,
  111739. 79039l, 78594l, 78156l, 77726l,
  111740. 77302l, 76885l, 76475l, 76072l,
  111741. 75674l, 75283l, 74898l, 74519l,
  111742. 74146l, 73778l, 73415l, 73058l,
  111743. 72706l, 72359l, 72016l, 71679l,
  111744. 71347l, 71019l, 70695l, 70376l,
  111745. 70061l, 69750l, 69444l, 69141l,
  111746. 68842l, 68548l, 68256l, 67969l,
  111747. 67685l, 67405l, 67128l, 66855l,
  111748. 66585l, 66318l, 66054l, 65794l,
  111749. 65536l,
  111750. };
  111751. #define COS_LOOKUP_I_SHIFT 9
  111752. #define COS_LOOKUP_I_MASK 511
  111753. #define COS_LOOKUP_I_SZ 128
  111754. static long COS_LOOKUP_I[COS_LOOKUP_I_SZ+1]={
  111755. 16384l, 16379l, 16364l, 16340l,
  111756. 16305l, 16261l, 16207l, 16143l,
  111757. 16069l, 15986l, 15893l, 15791l,
  111758. 15679l, 15557l, 15426l, 15286l,
  111759. 15137l, 14978l, 14811l, 14635l,
  111760. 14449l, 14256l, 14053l, 13842l,
  111761. 13623l, 13395l, 13160l, 12916l,
  111762. 12665l, 12406l, 12140l, 11866l,
  111763. 11585l, 11297l, 11003l, 10702l,
  111764. 10394l, 10080l, 9760l, 9434l,
  111765. 9102l, 8765l, 8423l, 8076l,
  111766. 7723l, 7366l, 7005l, 6639l,
  111767. 6270l, 5897l, 5520l, 5139l,
  111768. 4756l, 4370l, 3981l, 3590l,
  111769. 3196l, 2801l, 2404l, 2006l,
  111770. 1606l, 1205l, 804l, 402l,
  111771. 0l, -401l, -803l, -1204l,
  111772. -1605l, -2005l, -2403l, -2800l,
  111773. -3195l, -3589l, -3980l, -4369l,
  111774. -4755l, -5138l, -5519l, -5896l,
  111775. -6269l, -6638l, -7004l, -7365l,
  111776. -7722l, -8075l, -8422l, -8764l,
  111777. -9101l, -9433l, -9759l, -10079l,
  111778. -10393l, -10701l, -11002l, -11296l,
  111779. -11584l, -11865l, -12139l, -12405l,
  111780. -12664l, -12915l, -13159l, -13394l,
  111781. -13622l, -13841l, -14052l, -14255l,
  111782. -14448l, -14634l, -14810l, -14977l,
  111783. -15136l, -15285l, -15425l, -15556l,
  111784. -15678l, -15790l, -15892l, -15985l,
  111785. -16068l, -16142l, -16206l, -16260l,
  111786. -16304l, -16339l, -16363l, -16378l,
  111787. -16383l,
  111788. };
  111789. #endif
  111790. #endif
  111791. /*** End of inlined file: lookup_data.h ***/
  111792. #ifdef FLOAT_LOOKUP
  111793. /* interpolated lookup based cos function, domain 0 to PI only */
  111794. float vorbis_coslook(float a){
  111795. double d=a*(.31830989*(float)COS_LOOKUP_SZ);
  111796. int i=vorbis_ftoi(d-.5);
  111797. return COS_LOOKUP[i]+ (d-i)*(COS_LOOKUP[i+1]-COS_LOOKUP[i]);
  111798. }
  111799. /* interpolated 1./sqrt(p) where .5 <= p < 1. */
  111800. float vorbis_invsqlook(float a){
  111801. double d=a*(2.f*(float)INVSQ_LOOKUP_SZ)-(float)INVSQ_LOOKUP_SZ;
  111802. int i=vorbis_ftoi(d-.5f);
  111803. return INVSQ_LOOKUP[i]+ (d-i)*(INVSQ_LOOKUP[i+1]-INVSQ_LOOKUP[i]);
  111804. }
  111805. /* interpolated 1./sqrt(p) where .5 <= p < 1. */
  111806. float vorbis_invsq2explook(int a){
  111807. return INVSQ2EXP_LOOKUP[a-INVSQ2EXP_LOOKUP_MIN];
  111808. }
  111809. #include <stdio.h>
  111810. /* interpolated lookup based fromdB function, domain -140dB to 0dB only */
  111811. float vorbis_fromdBlook(float a){
  111812. int i=vorbis_ftoi(a*((float)(-(1<<FROMdB2_SHIFT)))-.5f);
  111813. return (i<0)?1.f:
  111814. ((i>=(FROMdB_LOOKUP_SZ<<FROMdB_SHIFT))?0.f:
  111815. FROMdB_LOOKUP[i>>FROMdB_SHIFT]*FROMdB2_LOOKUP[i&FROMdB2_MASK]);
  111816. }
  111817. #endif
  111818. #ifdef INT_LOOKUP
  111819. /* interpolated 1./sqrt(p) where .5 <= a < 1. (.100000... to .111111...) in
  111820. 16.16 format
  111821. returns in m.8 format */
  111822. long vorbis_invsqlook_i(long a,long e){
  111823. long i=(a&0x7fff)>>(INVSQ_LOOKUP_I_SHIFT-1);
  111824. long d=(a&INVSQ_LOOKUP_I_MASK)<<(16-INVSQ_LOOKUP_I_SHIFT); /* 0.16 */
  111825. long val=INVSQ_LOOKUP_I[i]- /* 1.16 */
  111826. (((INVSQ_LOOKUP_I[i]-INVSQ_LOOKUP_I[i+1])* /* 0.16 */
  111827. d)>>16); /* result 1.16 */
  111828. e+=32;
  111829. if(e&1)val=(val*5792)>>13; /* multiply val by 1/sqrt(2) */
  111830. e=(e>>1)-8;
  111831. return(val>>e);
  111832. }
  111833. /* interpolated lookup based fromdB function, domain -140dB to 0dB only */
  111834. /* a is in n.12 format */
  111835. float vorbis_fromdBlook_i(long a){
  111836. int i=(-a)>>(12-FROMdB2_SHIFT);
  111837. return (i<0)?1.f:
  111838. ((i>=(FROMdB_LOOKUP_SZ<<FROMdB_SHIFT))?0.f:
  111839. FROMdB_LOOKUP[i>>FROMdB_SHIFT]*FROMdB2_LOOKUP[i&FROMdB2_MASK]);
  111840. }
  111841. /* interpolated lookup based cos function, domain 0 to PI only */
  111842. /* a is in 0.16 format, where 0==0, 2^^16-1==PI, return 0.14 */
  111843. long vorbis_coslook_i(long a){
  111844. int i=a>>COS_LOOKUP_I_SHIFT;
  111845. int d=a&COS_LOOKUP_I_MASK;
  111846. return COS_LOOKUP_I[i]- ((d*(COS_LOOKUP_I[i]-COS_LOOKUP_I[i+1]))>>
  111847. COS_LOOKUP_I_SHIFT);
  111848. }
  111849. #endif
  111850. #endif
  111851. /*** End of inlined file: lookup.c ***/
  111852. /* catch this in the build system; we #include for
  111853. compilers (like gcc) that can't inline across
  111854. modules */
  111855. static int MLOOP_1[64]={
  111856. 0,10,11,11, 12,12,12,12, 13,13,13,13, 13,13,13,13,
  111857. 14,14,14,14, 14,14,14,14, 14,14,14,14, 14,14,14,14,
  111858. 15,15,15,15, 15,15,15,15, 15,15,15,15, 15,15,15,15,
  111859. 15,15,15,15, 15,15,15,15, 15,15,15,15, 15,15,15,15,
  111860. };
  111861. static int MLOOP_2[64]={
  111862. 0,4,5,5, 6,6,6,6, 7,7,7,7, 7,7,7,7,
  111863. 8,8,8,8, 8,8,8,8, 8,8,8,8, 8,8,8,8,
  111864. 9,9,9,9, 9,9,9,9, 9,9,9,9, 9,9,9,9,
  111865. 9,9,9,9, 9,9,9,9, 9,9,9,9, 9,9,9,9,
  111866. };
  111867. static int MLOOP_3[8]={0,1,2,2,3,3,3,3};
  111868. /* side effect: changes *lsp to cosines of lsp */
  111869. void vorbis_lsp_to_curve(float *curve,int *map,int n,int ln,float *lsp,int m,
  111870. float amp,float ampoffset){
  111871. /* 0 <= m < 256 */
  111872. /* set up for using all int later */
  111873. int i;
  111874. int ampoffseti=rint(ampoffset*4096.f);
  111875. int ampi=rint(amp*16.f);
  111876. long *ilsp=alloca(m*sizeof(*ilsp));
  111877. for(i=0;i<m;i++)ilsp[i]=vorbis_coslook_i(lsp[i]/M_PI*65536.f+.5f);
  111878. i=0;
  111879. while(i<n){
  111880. int j,k=map[i];
  111881. unsigned long pi=46341; /* 2**-.5 in 0.16 */
  111882. unsigned long qi=46341;
  111883. int qexp=0,shift;
  111884. long wi=vorbis_coslook_i(k*65536/ln);
  111885. qi*=labs(ilsp[0]-wi);
  111886. pi*=labs(ilsp[1]-wi);
  111887. for(j=3;j<m;j+=2){
  111888. if(!(shift=MLOOP_1[(pi|qi)>>25]))
  111889. if(!(shift=MLOOP_2[(pi|qi)>>19]))
  111890. shift=MLOOP_3[(pi|qi)>>16];
  111891. qi=(qi>>shift)*labs(ilsp[j-1]-wi);
  111892. pi=(pi>>shift)*labs(ilsp[j]-wi);
  111893. qexp+=shift;
  111894. }
  111895. if(!(shift=MLOOP_1[(pi|qi)>>25]))
  111896. if(!(shift=MLOOP_2[(pi|qi)>>19]))
  111897. shift=MLOOP_3[(pi|qi)>>16];
  111898. /* pi,qi normalized collectively, both tracked using qexp */
  111899. if(m&1){
  111900. /* odd order filter; slightly assymetric */
  111901. /* the last coefficient */
  111902. qi=(qi>>shift)*labs(ilsp[j-1]-wi);
  111903. pi=(pi>>shift)<<14;
  111904. qexp+=shift;
  111905. if(!(shift=MLOOP_1[(pi|qi)>>25]))
  111906. if(!(shift=MLOOP_2[(pi|qi)>>19]))
  111907. shift=MLOOP_3[(pi|qi)>>16];
  111908. pi>>=shift;
  111909. qi>>=shift;
  111910. qexp+=shift-14*((m+1)>>1);
  111911. pi=((pi*pi)>>16);
  111912. qi=((qi*qi)>>16);
  111913. qexp=qexp*2+m;
  111914. pi*=(1<<14)-((wi*wi)>>14);
  111915. qi+=pi>>14;
  111916. }else{
  111917. /* even order filter; still symmetric */
  111918. /* p*=p(1-w), q*=q(1+w), let normalization drift because it isn't
  111919. worth tracking step by step */
  111920. pi>>=shift;
  111921. qi>>=shift;
  111922. qexp+=shift-7*m;
  111923. pi=((pi*pi)>>16);
  111924. qi=((qi*qi)>>16);
  111925. qexp=qexp*2+m;
  111926. pi*=(1<<14)-wi;
  111927. qi*=(1<<14)+wi;
  111928. qi=(qi+pi)>>14;
  111929. }
  111930. /* we've let the normalization drift because it wasn't important;
  111931. however, for the lookup, things must be normalized again. We
  111932. need at most one right shift or a number of left shifts */
  111933. if(qi&0xffff0000){ /* checks for 1.xxxxxxxxxxxxxxxx */
  111934. qi>>=1; qexp++;
  111935. }else
  111936. while(qi && !(qi&0x8000)){ /* checks for 0.0xxxxxxxxxxxxxxx or less*/
  111937. qi<<=1; qexp--;
  111938. }
  111939. amp=vorbis_fromdBlook_i(ampi* /* n.4 */
  111940. vorbis_invsqlook_i(qi,qexp)-
  111941. /* m.8, m+n<=8 */
  111942. ampoffseti); /* 8.12[0] */
  111943. curve[i]*=amp;
  111944. while(map[++i]==k)curve[i]*=amp;
  111945. }
  111946. }
  111947. #else
  111948. /* old, nonoptimized but simple version for any poor sap who needs to
  111949. figure out what the hell this code does, or wants the other
  111950. fraction of a dB precision */
  111951. /* side effect: changes *lsp to cosines of lsp */
  111952. void vorbis_lsp_to_curve(float *curve,int *map,int n,int ln,float *lsp,int m,
  111953. float amp,float ampoffset){
  111954. int i;
  111955. float wdel=M_PI/ln;
  111956. for(i=0;i<m;i++)lsp[i]=2.f*cos(lsp[i]);
  111957. i=0;
  111958. while(i<n){
  111959. int j,k=map[i];
  111960. float p=.5f;
  111961. float q=.5f;
  111962. float w=2.f*cos(wdel*k);
  111963. for(j=1;j<m;j+=2){
  111964. q *= w-lsp[j-1];
  111965. p *= w-lsp[j];
  111966. }
  111967. if(j==m){
  111968. /* odd order filter; slightly assymetric */
  111969. /* the last coefficient */
  111970. q*=w-lsp[j-1];
  111971. p*=p*(4.f-w*w);
  111972. q*=q;
  111973. }else{
  111974. /* even order filter; still symmetric */
  111975. p*=p*(2.f-w);
  111976. q*=q*(2.f+w);
  111977. }
  111978. q=fromdB(amp/sqrt(p+q)-ampoffset);
  111979. curve[i]*=q;
  111980. while(map[++i]==k)curve[i]*=q;
  111981. }
  111982. }
  111983. #endif
  111984. #endif
  111985. static void cheby(float *g, int ord) {
  111986. int i, j;
  111987. g[0] *= .5f;
  111988. for(i=2; i<= ord; i++) {
  111989. for(j=ord; j >= i; j--) {
  111990. g[j-2] -= g[j];
  111991. g[j] += g[j];
  111992. }
  111993. }
  111994. }
  111995. static int comp(const void *a,const void *b){
  111996. return (*(float *)a<*(float *)b)-(*(float *)a>*(float *)b);
  111997. }
  111998. /* Newton-Raphson-Maehly actually functioned as a decent root finder,
  111999. but there are root sets for which it gets into limit cycles
  112000. (exacerbated by zero suppression) and fails. We can't afford to
  112001. fail, even if the failure is 1 in 100,000,000, so we now use
  112002. Laguerre and later polish with Newton-Raphson (which can then
  112003. afford to fail) */
  112004. #define EPSILON 10e-7
  112005. static int Laguerre_With_Deflation(float *a,int ord,float *r){
  112006. int i,m;
  112007. double lastdelta=0.f;
  112008. double *defl=(double*)alloca(sizeof(*defl)*(ord+1));
  112009. for(i=0;i<=ord;i++)defl[i]=a[i];
  112010. for(m=ord;m>0;m--){
  112011. double newx=0.f,delta;
  112012. /* iterate a root */
  112013. while(1){
  112014. double p=defl[m],pp=0.f,ppp=0.f,denom;
  112015. /* eval the polynomial and its first two derivatives */
  112016. for(i=m;i>0;i--){
  112017. ppp = newx*ppp + pp;
  112018. pp = newx*pp + p;
  112019. p = newx*p + defl[i-1];
  112020. }
  112021. /* Laguerre's method */
  112022. denom=(m-1) * ((m-1)*pp*pp - m*p*ppp);
  112023. if(denom<0)
  112024. return(-1); /* complex root! The LPC generator handed us a bad filter */
  112025. if(pp>0){
  112026. denom = pp + sqrt(denom);
  112027. if(denom<EPSILON)denom=EPSILON;
  112028. }else{
  112029. denom = pp - sqrt(denom);
  112030. if(denom>-(EPSILON))denom=-(EPSILON);
  112031. }
  112032. delta = m*p/denom;
  112033. newx -= delta;
  112034. if(delta<0.f)delta*=-1;
  112035. if(fabs(delta/newx)<10e-12)break;
  112036. lastdelta=delta;
  112037. }
  112038. r[m-1]=newx;
  112039. /* forward deflation */
  112040. for(i=m;i>0;i--)
  112041. defl[i-1]+=newx*defl[i];
  112042. defl++;
  112043. }
  112044. return(0);
  112045. }
  112046. /* for spit-and-polish only */
  112047. static int Newton_Raphson(float *a,int ord,float *r){
  112048. int i, k, count=0;
  112049. double error=1.f;
  112050. double *root=(double*)alloca(ord*sizeof(*root));
  112051. for(i=0; i<ord;i++) root[i] = r[i];
  112052. while(error>1e-20){
  112053. error=0;
  112054. for(i=0; i<ord; i++) { /* Update each point. */
  112055. double pp=0.,delta;
  112056. double rooti=root[i];
  112057. double p=a[ord];
  112058. for(k=ord-1; k>= 0; k--) {
  112059. pp= pp* rooti + p;
  112060. p = p * rooti + a[k];
  112061. }
  112062. delta = p/pp;
  112063. root[i] -= delta;
  112064. error+= delta*delta;
  112065. }
  112066. if(count>40)return(-1);
  112067. count++;
  112068. }
  112069. /* Replaced the original bubble sort with a real sort. With your
  112070. help, we can eliminate the bubble sort in our lifetime. --Monty */
  112071. for(i=0; i<ord;i++) r[i] = root[i];
  112072. return(0);
  112073. }
  112074. /* Convert lpc coefficients to lsp coefficients */
  112075. int vorbis_lpc_to_lsp(float *lpc,float *lsp,int m){
  112076. int order2=(m+1)>>1;
  112077. int g1_order,g2_order;
  112078. float *g1=(float*)alloca(sizeof(*g1)*(order2+1));
  112079. float *g2=(float*)alloca(sizeof(*g2)*(order2+1));
  112080. float *g1r=(float*)alloca(sizeof(*g1r)*(order2+1));
  112081. float *g2r=(float*)alloca(sizeof(*g2r)*(order2+1));
  112082. int i;
  112083. /* even and odd are slightly different base cases */
  112084. g1_order=(m+1)>>1;
  112085. g2_order=(m) >>1;
  112086. /* Compute the lengths of the x polynomials. */
  112087. /* Compute the first half of K & R F1 & F2 polynomials. */
  112088. /* Compute half of the symmetric and antisymmetric polynomials. */
  112089. /* Remove the roots at +1 and -1. */
  112090. g1[g1_order] = 1.f;
  112091. for(i=1;i<=g1_order;i++) g1[g1_order-i] = lpc[i-1]+lpc[m-i];
  112092. g2[g2_order] = 1.f;
  112093. for(i=1;i<=g2_order;i++) g2[g2_order-i] = lpc[i-1]-lpc[m-i];
  112094. if(g1_order>g2_order){
  112095. for(i=2; i<=g2_order;i++) g2[g2_order-i] += g2[g2_order-i+2];
  112096. }else{
  112097. for(i=1; i<=g1_order;i++) g1[g1_order-i] -= g1[g1_order-i+1];
  112098. for(i=1; i<=g2_order;i++) g2[g2_order-i] += g2[g2_order-i+1];
  112099. }
  112100. /* Convert into polynomials in cos(alpha) */
  112101. cheby(g1,g1_order);
  112102. cheby(g2,g2_order);
  112103. /* Find the roots of the 2 even polynomials.*/
  112104. if(Laguerre_With_Deflation(g1,g1_order,g1r) ||
  112105. Laguerre_With_Deflation(g2,g2_order,g2r))
  112106. return(-1);
  112107. Newton_Raphson(g1,g1_order,g1r); /* if it fails, it leaves g1r alone */
  112108. Newton_Raphson(g2,g2_order,g2r); /* if it fails, it leaves g2r alone */
  112109. qsort(g1r,g1_order,sizeof(*g1r),comp);
  112110. qsort(g2r,g2_order,sizeof(*g2r),comp);
  112111. for(i=0;i<g1_order;i++)
  112112. lsp[i*2] = acos(g1r[i]);
  112113. for(i=0;i<g2_order;i++)
  112114. lsp[i*2+1] = acos(g2r[i]);
  112115. return(0);
  112116. }
  112117. #endif
  112118. /*** End of inlined file: lsp.c ***/
  112119. /*** Start of inlined file: mapping0.c ***/
  112120. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  112121. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  112122. // tasks..
  112123. #if JUCE_MSVC
  112124. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  112125. #endif
  112126. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  112127. #if JUCE_USE_OGGVORBIS
  112128. #include <stdlib.h>
  112129. #include <stdio.h>
  112130. #include <string.h>
  112131. #include <math.h>
  112132. /* simplistic, wasteful way of doing this (unique lookup for each
  112133. mode/submapping); there should be a central repository for
  112134. identical lookups. That will require minor work, so I'm putting it
  112135. off as low priority.
  112136. Why a lookup for each backend in a given mode? Because the
  112137. blocksize is set by the mode, and low backend lookups may require
  112138. parameters from other areas of the mode/mapping */
  112139. static void mapping0_free_info(vorbis_info_mapping *i){
  112140. vorbis_info_mapping0 *info=(vorbis_info_mapping0 *)i;
  112141. if(info){
  112142. memset(info,0,sizeof(*info));
  112143. _ogg_free(info);
  112144. }
  112145. }
  112146. static int ilog3(unsigned int v){
  112147. int ret=0;
  112148. if(v)--v;
  112149. while(v){
  112150. ret++;
  112151. v>>=1;
  112152. }
  112153. return(ret);
  112154. }
  112155. static void mapping0_pack(vorbis_info *vi,vorbis_info_mapping *vm,
  112156. oggpack_buffer *opb){
  112157. int i;
  112158. vorbis_info_mapping0 *info=(vorbis_info_mapping0 *)vm;
  112159. /* another 'we meant to do it this way' hack... up to beta 4, we
  112160. packed 4 binary zeros here to signify one submapping in use. We
  112161. now redefine that to mean four bitflags that indicate use of
  112162. deeper features; bit0:submappings, bit1:coupling,
  112163. bit2,3:reserved. This is backward compatable with all actual uses
  112164. of the beta code. */
  112165. if(info->submaps>1){
  112166. oggpack_write(opb,1,1);
  112167. oggpack_write(opb,info->submaps-1,4);
  112168. }else
  112169. oggpack_write(opb,0,1);
  112170. if(info->coupling_steps>0){
  112171. oggpack_write(opb,1,1);
  112172. oggpack_write(opb,info->coupling_steps-1,8);
  112173. for(i=0;i<info->coupling_steps;i++){
  112174. oggpack_write(opb,info->coupling_mag[i],ilog3(vi->channels));
  112175. oggpack_write(opb,info->coupling_ang[i],ilog3(vi->channels));
  112176. }
  112177. }else
  112178. oggpack_write(opb,0,1);
  112179. oggpack_write(opb,0,2); /* 2,3:reserved */
  112180. /* we don't write the channel submappings if we only have one... */
  112181. if(info->submaps>1){
  112182. for(i=0;i<vi->channels;i++)
  112183. oggpack_write(opb,info->chmuxlist[i],4);
  112184. }
  112185. for(i=0;i<info->submaps;i++){
  112186. oggpack_write(opb,0,8); /* time submap unused */
  112187. oggpack_write(opb,info->floorsubmap[i],8);
  112188. oggpack_write(opb,info->residuesubmap[i],8);
  112189. }
  112190. }
  112191. /* also responsible for range checking */
  112192. static vorbis_info_mapping *mapping0_unpack(vorbis_info *vi,oggpack_buffer *opb){
  112193. int i;
  112194. vorbis_info_mapping0 *info=(vorbis_info_mapping0*)_ogg_calloc(1,sizeof(*info));
  112195. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  112196. memset(info,0,sizeof(*info));
  112197. if(oggpack_read(opb,1))
  112198. info->submaps=oggpack_read(opb,4)+1;
  112199. else
  112200. info->submaps=1;
  112201. if(oggpack_read(opb,1)){
  112202. info->coupling_steps=oggpack_read(opb,8)+1;
  112203. for(i=0;i<info->coupling_steps;i++){
  112204. int testM=info->coupling_mag[i]=oggpack_read(opb,ilog3(vi->channels));
  112205. int testA=info->coupling_ang[i]=oggpack_read(opb,ilog3(vi->channels));
  112206. if(testM<0 ||
  112207. testA<0 ||
  112208. testM==testA ||
  112209. testM>=vi->channels ||
  112210. testA>=vi->channels) goto err_out;
  112211. }
  112212. }
  112213. if(oggpack_read(opb,2)>0)goto err_out; /* 2,3:reserved */
  112214. if(info->submaps>1){
  112215. for(i=0;i<vi->channels;i++){
  112216. info->chmuxlist[i]=oggpack_read(opb,4);
  112217. if(info->chmuxlist[i]>=info->submaps)goto err_out;
  112218. }
  112219. }
  112220. for(i=0;i<info->submaps;i++){
  112221. oggpack_read(opb,8); /* time submap unused */
  112222. info->floorsubmap[i]=oggpack_read(opb,8);
  112223. if(info->floorsubmap[i]>=ci->floors)goto err_out;
  112224. info->residuesubmap[i]=oggpack_read(opb,8);
  112225. if(info->residuesubmap[i]>=ci->residues)goto err_out;
  112226. }
  112227. return info;
  112228. err_out:
  112229. mapping0_free_info(info);
  112230. return(NULL);
  112231. }
  112232. #if 0
  112233. static long seq=0;
  112234. static ogg_int64_t total=0;
  112235. static float FLOOR1_fromdB_LOOKUP[256]={
  112236. 1.0649863e-07F, 1.1341951e-07F, 1.2079015e-07F, 1.2863978e-07F,
  112237. 1.3699951e-07F, 1.4590251e-07F, 1.5538408e-07F, 1.6548181e-07F,
  112238. 1.7623575e-07F, 1.8768855e-07F, 1.9988561e-07F, 2.128753e-07F,
  112239. 2.2670913e-07F, 2.4144197e-07F, 2.5713223e-07F, 2.7384213e-07F,
  112240. 2.9163793e-07F, 3.1059021e-07F, 3.3077411e-07F, 3.5226968e-07F,
  112241. 3.7516214e-07F, 3.9954229e-07F, 4.2550680e-07F, 4.5315863e-07F,
  112242. 4.8260743e-07F, 5.1396998e-07F, 5.4737065e-07F, 5.8294187e-07F,
  112243. 6.2082472e-07F, 6.6116941e-07F, 7.0413592e-07F, 7.4989464e-07F,
  112244. 7.9862701e-07F, 8.5052630e-07F, 9.0579828e-07F, 9.6466216e-07F,
  112245. 1.0273513e-06F, 1.0941144e-06F, 1.1652161e-06F, 1.2409384e-06F,
  112246. 1.3215816e-06F, 1.4074654e-06F, 1.4989305e-06F, 1.5963394e-06F,
  112247. 1.7000785e-06F, 1.8105592e-06F, 1.9282195e-06F, 2.0535261e-06F,
  112248. 2.1869758e-06F, 2.3290978e-06F, 2.4804557e-06F, 2.6416497e-06F,
  112249. 2.8133190e-06F, 2.9961443e-06F, 3.1908506e-06F, 3.3982101e-06F,
  112250. 3.6190449e-06F, 3.8542308e-06F, 4.1047004e-06F, 4.3714470e-06F,
  112251. 4.6555282e-06F, 4.9580707e-06F, 5.2802740e-06F, 5.6234160e-06F,
  112252. 5.9888572e-06F, 6.3780469e-06F, 6.7925283e-06F, 7.2339451e-06F,
  112253. 7.7040476e-06F, 8.2047000e-06F, 8.7378876e-06F, 9.3057248e-06F,
  112254. 9.9104632e-06F, 1.0554501e-05F, 1.1240392e-05F, 1.1970856e-05F,
  112255. 1.2748789e-05F, 1.3577278e-05F, 1.4459606e-05F, 1.5399272e-05F,
  112256. 1.6400004e-05F, 1.7465768e-05F, 1.8600792e-05F, 1.9809576e-05F,
  112257. 2.1096914e-05F, 2.2467911e-05F, 2.3928002e-05F, 2.5482978e-05F,
  112258. 2.7139006e-05F, 2.8902651e-05F, 3.0780908e-05F, 3.2781225e-05F,
  112259. 3.4911534e-05F, 3.7180282e-05F, 3.9596466e-05F, 4.2169667e-05F,
  112260. 4.4910090e-05F, 4.7828601e-05F, 5.0936773e-05F, 5.4246931e-05F,
  112261. 5.7772202e-05F, 6.1526565e-05F, 6.5524908e-05F, 6.9783085e-05F,
  112262. 7.4317983e-05F, 7.9147585e-05F, 8.4291040e-05F, 8.9768747e-05F,
  112263. 9.5602426e-05F, 0.00010181521F, 0.00010843174F, 0.00011547824F,
  112264. 0.00012298267F, 0.00013097477F, 0.00013948625F, 0.00014855085F,
  112265. 0.00015820453F, 0.00016848555F, 0.00017943469F, 0.00019109536F,
  112266. 0.00020351382F, 0.00021673929F, 0.00023082423F, 0.00024582449F,
  112267. 0.00026179955F, 0.00027881276F, 0.00029693158F, 0.00031622787F,
  112268. 0.00033677814F, 0.00035866388F, 0.00038197188F, 0.00040679456F,
  112269. 0.00043323036F, 0.00046138411F, 0.00049136745F, 0.00052329927F,
  112270. 0.00055730621F, 0.00059352311F, 0.00063209358F, 0.00067317058F,
  112271. 0.00071691700F, 0.00076350630F, 0.00081312324F, 0.00086596457F,
  112272. 0.00092223983F, 0.00098217216F, 0.0010459992F, 0.0011139742F,
  112273. 0.0011863665F, 0.0012634633F, 0.0013455702F, 0.0014330129F,
  112274. 0.0015261382F, 0.0016253153F, 0.0017309374F, 0.0018434235F,
  112275. 0.0019632195F, 0.0020908006F, 0.0022266726F, 0.0023713743F,
  112276. 0.0025254795F, 0.0026895994F, 0.0028643847F, 0.0030505286F,
  112277. 0.0032487691F, 0.0034598925F, 0.0036847358F, 0.0039241906F,
  112278. 0.0041792066F, 0.0044507950F, 0.0047400328F, 0.0050480668F,
  112279. 0.0053761186F, 0.0057254891F, 0.0060975636F, 0.0064938176F,
  112280. 0.0069158225F, 0.0073652516F, 0.0078438871F, 0.0083536271F,
  112281. 0.0088964928F, 0.009474637F, 0.010090352F, 0.010746080F,
  112282. 0.011444421F, 0.012188144F, 0.012980198F, 0.013823725F,
  112283. 0.014722068F, 0.015678791F, 0.016697687F, 0.017782797F,
  112284. 0.018938423F, 0.020169149F, 0.021479854F, 0.022875735F,
  112285. 0.024362330F, 0.025945531F, 0.027631618F, 0.029427276F,
  112286. 0.031339626F, 0.033376252F, 0.035545228F, 0.037855157F,
  112287. 0.040315199F, 0.042935108F, 0.045725273F, 0.048696758F,
  112288. 0.051861348F, 0.055231591F, 0.058820850F, 0.062643361F,
  112289. 0.066714279F, 0.071049749F, 0.075666962F, 0.080584227F,
  112290. 0.085821044F, 0.091398179F, 0.097337747F, 0.10366330F,
  112291. 0.11039993F, 0.11757434F, 0.12521498F, 0.13335215F,
  112292. 0.14201813F, 0.15124727F, 0.16107617F, 0.17154380F,
  112293. 0.18269168F, 0.19456402F, 0.20720788F, 0.22067342F,
  112294. 0.23501402F, 0.25028656F, 0.26655159F, 0.28387361F,
  112295. 0.30232132F, 0.32196786F, 0.34289114F, 0.36517414F,
  112296. 0.38890521F, 0.41417847F, 0.44109412F, 0.46975890F,
  112297. 0.50028648F, 0.53279791F, 0.56742212F, 0.60429640F,
  112298. 0.64356699F, 0.68538959F, 0.72993007F, 0.77736504F,
  112299. 0.82788260F, 0.88168307F, 0.9389798F, 1.F,
  112300. };
  112301. #endif
  112302. extern int *floor1_fit(vorbis_block *vb,void *look,
  112303. const float *logmdct, /* in */
  112304. const float *logmask);
  112305. extern int *floor1_interpolate_fit(vorbis_block *vb,void *look,
  112306. int *A,int *B,
  112307. int del);
  112308. extern int floor1_encode(oggpack_buffer *opb,vorbis_block *vb,
  112309. void*look,
  112310. int *post,int *ilogmask);
  112311. static int mapping0_forward(vorbis_block *vb){
  112312. vorbis_dsp_state *vd=vb->vd;
  112313. vorbis_info *vi=vd->vi;
  112314. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  112315. private_state *b=(private_state*)vb->vd->backend_state;
  112316. vorbis_block_internal *vbi=(vorbis_block_internal *)vb->internal;
  112317. int n=vb->pcmend;
  112318. int i,j,k;
  112319. int *nonzero = (int*) alloca(sizeof(*nonzero)*vi->channels);
  112320. float **gmdct = (float**) _vorbis_block_alloc(vb,vi->channels*sizeof(*gmdct));
  112321. int **ilogmaskch= (int**) _vorbis_block_alloc(vb,vi->channels*sizeof(*ilogmaskch));
  112322. int ***floor_posts = (int***) _vorbis_block_alloc(vb,vi->channels*sizeof(*floor_posts));
  112323. float global_ampmax=vbi->ampmax;
  112324. float *local_ampmax=(float*)alloca(sizeof(*local_ampmax)*vi->channels);
  112325. int blocktype=vbi->blocktype;
  112326. int modenumber=vb->W;
  112327. vorbis_info_mapping0 *info=(vorbis_info_mapping0*)ci->map_param[modenumber];
  112328. vorbis_look_psy *psy_look=
  112329. b->psy+blocktype+(vb->W?2:0);
  112330. vb->mode=modenumber;
  112331. for(i=0;i<vi->channels;i++){
  112332. float scale=4.f/n;
  112333. float scale_dB;
  112334. float *pcm =vb->pcm[i];
  112335. float *logfft =pcm;
  112336. gmdct[i]=(float*)_vorbis_block_alloc(vb,n/2*sizeof(**gmdct));
  112337. scale_dB=todB(&scale) + .345; /* + .345 is a hack; the original
  112338. todB estimation used on IEEE 754
  112339. compliant machines had a bug that
  112340. returned dB values about a third
  112341. of a decibel too high. The bug
  112342. was harmless because tunings
  112343. implicitly took that into
  112344. account. However, fixing the bug
  112345. in the estimator requires
  112346. changing all the tunings as well.
  112347. For now, it's easier to sync
  112348. things back up here, and
  112349. recalibrate the tunings in the
  112350. next major model upgrade. */
  112351. #if 0
  112352. if(vi->channels==2)
  112353. if(i==0)
  112354. _analysis_output("pcmL",seq,pcm,n,0,0,total-n/2);
  112355. else
  112356. _analysis_output("pcmR",seq,pcm,n,0,0,total-n/2);
  112357. #endif
  112358. /* window the PCM data */
  112359. _vorbis_apply_window(pcm,b->window,ci->blocksizes,vb->lW,vb->W,vb->nW);
  112360. #if 0
  112361. if(vi->channels==2)
  112362. if(i==0)
  112363. _analysis_output("windowedL",seq,pcm,n,0,0,total-n/2);
  112364. else
  112365. _analysis_output("windowedR",seq,pcm,n,0,0,total-n/2);
  112366. #endif
  112367. /* transform the PCM data */
  112368. /* only MDCT right now.... */
  112369. mdct_forward((mdct_lookup*) b->transform[vb->W][0],pcm,gmdct[i]);
  112370. /* FFT yields more accurate tonal estimation (not phase sensitive) */
  112371. drft_forward(&b->fft_look[vb->W],pcm);
  112372. logfft[0]=scale_dB+todB(pcm) + .345; /* + .345 is a hack; the
  112373. original todB estimation used on
  112374. IEEE 754 compliant machines had a
  112375. bug that returned dB values about
  112376. a third of a decibel too high.
  112377. The bug was harmless because
  112378. tunings implicitly took that into
  112379. account. However, fixing the bug
  112380. in the estimator requires
  112381. changing all the tunings as well.
  112382. For now, it's easier to sync
  112383. things back up here, and
  112384. recalibrate the tunings in the
  112385. next major model upgrade. */
  112386. local_ampmax[i]=logfft[0];
  112387. for(j=1;j<n-1;j+=2){
  112388. float temp=pcm[j]*pcm[j]+pcm[j+1]*pcm[j+1];
  112389. temp=logfft[(j+1)>>1]=scale_dB+.5f*todB(&temp) + .345; /* +
  112390. .345 is a hack; the original todB
  112391. estimation used on IEEE 754
  112392. compliant machines had a bug that
  112393. returned dB values about a third
  112394. of a decibel too high. The bug
  112395. was harmless because tunings
  112396. implicitly took that into
  112397. account. However, fixing the bug
  112398. in the estimator requires
  112399. changing all the tunings as well.
  112400. For now, it's easier to sync
  112401. things back up here, and
  112402. recalibrate the tunings in the
  112403. next major model upgrade. */
  112404. if(temp>local_ampmax[i])local_ampmax[i]=temp;
  112405. }
  112406. if(local_ampmax[i]>0.f)local_ampmax[i]=0.f;
  112407. if(local_ampmax[i]>global_ampmax)global_ampmax=local_ampmax[i];
  112408. #if 0
  112409. if(vi->channels==2){
  112410. if(i==0){
  112411. _analysis_output("fftL",seq,logfft,n/2,1,0,0);
  112412. }else{
  112413. _analysis_output("fftR",seq,logfft,n/2,1,0,0);
  112414. }
  112415. }
  112416. #endif
  112417. }
  112418. {
  112419. float *noise = (float*) _vorbis_block_alloc(vb,n/2*sizeof(*noise));
  112420. float *tone = (float*) _vorbis_block_alloc(vb,n/2*sizeof(*tone));
  112421. for(i=0;i<vi->channels;i++){
  112422. /* the encoder setup assumes that all the modes used by any
  112423. specific bitrate tweaking use the same floor */
  112424. int submap=info->chmuxlist[i];
  112425. /* the following makes things clearer to *me* anyway */
  112426. float *mdct =gmdct[i];
  112427. float *logfft =vb->pcm[i];
  112428. float *logmdct =logfft+n/2;
  112429. float *logmask =logfft;
  112430. vb->mode=modenumber;
  112431. floor_posts[i]=(int**) _vorbis_block_alloc(vb,PACKETBLOBS*sizeof(**floor_posts));
  112432. memset(floor_posts[i],0,sizeof(**floor_posts)*PACKETBLOBS);
  112433. for(j=0;j<n/2;j++)
  112434. logmdct[j]=todB(mdct+j) + .345; /* + .345 is a hack; the original
  112435. todB estimation used on IEEE 754
  112436. compliant machines had a bug that
  112437. returned dB values about a third
  112438. of a decibel too high. The bug
  112439. was harmless because tunings
  112440. implicitly took that into
  112441. account. However, fixing the bug
  112442. in the estimator requires
  112443. changing all the tunings as well.
  112444. For now, it's easier to sync
  112445. things back up here, and
  112446. recalibrate the tunings in the
  112447. next major model upgrade. */
  112448. #if 0
  112449. if(vi->channels==2){
  112450. if(i==0)
  112451. _analysis_output("mdctL",seq,logmdct,n/2,1,0,0);
  112452. else
  112453. _analysis_output("mdctR",seq,logmdct,n/2,1,0,0);
  112454. }else{
  112455. _analysis_output("mdct",seq,logmdct,n/2,1,0,0);
  112456. }
  112457. #endif
  112458. /* first step; noise masking. Not only does 'noise masking'
  112459. give us curves from which we can decide how much resolution
  112460. to give noise parts of the spectrum, it also implicitly hands
  112461. us a tonality estimate (the larger the value in the
  112462. 'noise_depth' vector, the more tonal that area is) */
  112463. _vp_noisemask(psy_look,
  112464. logmdct,
  112465. noise); /* noise does not have by-frequency offset
  112466. bias applied yet */
  112467. #if 0
  112468. if(vi->channels==2){
  112469. if(i==0)
  112470. _analysis_output("noiseL",seq,noise,n/2,1,0,0);
  112471. else
  112472. _analysis_output("noiseR",seq,noise,n/2,1,0,0);
  112473. }
  112474. #endif
  112475. /* second step: 'all the other crap'; all the stuff that isn't
  112476. computed/fit for bitrate management goes in the second psy
  112477. vector. This includes tone masking, peak limiting and ATH */
  112478. _vp_tonemask(psy_look,
  112479. logfft,
  112480. tone,
  112481. global_ampmax,
  112482. local_ampmax[i]);
  112483. #if 0
  112484. if(vi->channels==2){
  112485. if(i==0)
  112486. _analysis_output("toneL",seq,tone,n/2,1,0,0);
  112487. else
  112488. _analysis_output("toneR",seq,tone,n/2,1,0,0);
  112489. }
  112490. #endif
  112491. /* third step; we offset the noise vectors, overlay tone
  112492. masking. We then do a floor1-specific line fit. If we're
  112493. performing bitrate management, the line fit is performed
  112494. multiple times for up/down tweakage on demand. */
  112495. #if 0
  112496. {
  112497. float aotuv[psy_look->n];
  112498. #endif
  112499. _vp_offset_and_mix(psy_look,
  112500. noise,
  112501. tone,
  112502. 1,
  112503. logmask,
  112504. mdct,
  112505. logmdct);
  112506. #if 0
  112507. if(vi->channels==2){
  112508. if(i==0)
  112509. _analysis_output("aotuvM1_L",seq,aotuv,psy_look->n,1,1,0);
  112510. else
  112511. _analysis_output("aotuvM1_R",seq,aotuv,psy_look->n,1,1,0);
  112512. }
  112513. }
  112514. #endif
  112515. #if 0
  112516. if(vi->channels==2){
  112517. if(i==0)
  112518. _analysis_output("mask1L",seq,logmask,n/2,1,0,0);
  112519. else
  112520. _analysis_output("mask1R",seq,logmask,n/2,1,0,0);
  112521. }
  112522. #endif
  112523. /* this algorithm is hardwired to floor 1 for now; abort out if
  112524. we're *not* floor1. This won't happen unless someone has
  112525. broken the encode setup lib. Guard it anyway. */
  112526. if(ci->floor_type[info->floorsubmap[submap]]!=1)return(-1);
  112527. floor_posts[i][PACKETBLOBS/2]=
  112528. floor1_fit(vb,b->flr[info->floorsubmap[submap]],
  112529. logmdct,
  112530. logmask);
  112531. /* are we managing bitrate? If so, perform two more fits for
  112532. later rate tweaking (fits represent hi/lo) */
  112533. if(vorbis_bitrate_managed(vb) && floor_posts[i][PACKETBLOBS/2]){
  112534. /* higher rate by way of lower noise curve */
  112535. _vp_offset_and_mix(psy_look,
  112536. noise,
  112537. tone,
  112538. 2,
  112539. logmask,
  112540. mdct,
  112541. logmdct);
  112542. #if 0
  112543. if(vi->channels==2){
  112544. if(i==0)
  112545. _analysis_output("mask2L",seq,logmask,n/2,1,0,0);
  112546. else
  112547. _analysis_output("mask2R",seq,logmask,n/2,1,0,0);
  112548. }
  112549. #endif
  112550. floor_posts[i][PACKETBLOBS-1]=
  112551. floor1_fit(vb,b->flr[info->floorsubmap[submap]],
  112552. logmdct,
  112553. logmask);
  112554. /* lower rate by way of higher noise curve */
  112555. _vp_offset_and_mix(psy_look,
  112556. noise,
  112557. tone,
  112558. 0,
  112559. logmask,
  112560. mdct,
  112561. logmdct);
  112562. #if 0
  112563. if(vi->channels==2)
  112564. if(i==0)
  112565. _analysis_output("mask0L",seq,logmask,n/2,1,0,0);
  112566. else
  112567. _analysis_output("mask0R",seq,logmask,n/2,1,0,0);
  112568. #endif
  112569. floor_posts[i][0]=
  112570. floor1_fit(vb,b->flr[info->floorsubmap[submap]],
  112571. logmdct,
  112572. logmask);
  112573. /* we also interpolate a range of intermediate curves for
  112574. intermediate rates */
  112575. for(k=1;k<PACKETBLOBS/2;k++)
  112576. floor_posts[i][k]=
  112577. floor1_interpolate_fit(vb,b->flr[info->floorsubmap[submap]],
  112578. floor_posts[i][0],
  112579. floor_posts[i][PACKETBLOBS/2],
  112580. k*65536/(PACKETBLOBS/2));
  112581. for(k=PACKETBLOBS/2+1;k<PACKETBLOBS-1;k++)
  112582. floor_posts[i][k]=
  112583. floor1_interpolate_fit(vb,b->flr[info->floorsubmap[submap]],
  112584. floor_posts[i][PACKETBLOBS/2],
  112585. floor_posts[i][PACKETBLOBS-1],
  112586. (k-PACKETBLOBS/2)*65536/(PACKETBLOBS/2));
  112587. }
  112588. }
  112589. }
  112590. vbi->ampmax=global_ampmax;
  112591. /*
  112592. the next phases are performed once for vbr-only and PACKETBLOB
  112593. times for bitrate managed modes.
  112594. 1) encode actual mode being used
  112595. 2) encode the floor for each channel, compute coded mask curve/res
  112596. 3) normalize and couple.
  112597. 4) encode residue
  112598. 5) save packet bytes to the packetblob vector
  112599. */
  112600. /* iterate over the many masking curve fits we've created */
  112601. {
  112602. float **res_bundle=(float**) alloca(sizeof(*res_bundle)*vi->channels);
  112603. float **couple_bundle=(float**) alloca(sizeof(*couple_bundle)*vi->channels);
  112604. int *zerobundle=(int*) alloca(sizeof(*zerobundle)*vi->channels);
  112605. int **sortindex=(int**) alloca(sizeof(*sortindex)*vi->channels);
  112606. float **mag_memo;
  112607. int **mag_sort;
  112608. if(info->coupling_steps){
  112609. mag_memo=_vp_quantize_couple_memo(vb,
  112610. &ci->psy_g_param,
  112611. psy_look,
  112612. info,
  112613. gmdct);
  112614. mag_sort=_vp_quantize_couple_sort(vb,
  112615. psy_look,
  112616. info,
  112617. mag_memo);
  112618. hf_reduction(&ci->psy_g_param,
  112619. psy_look,
  112620. info,
  112621. mag_memo);
  112622. }
  112623. memset(sortindex,0,sizeof(*sortindex)*vi->channels);
  112624. if(psy_look->vi->normal_channel_p){
  112625. for(i=0;i<vi->channels;i++){
  112626. float *mdct =gmdct[i];
  112627. sortindex[i]=(int*) alloca(sizeof(**sortindex)*n/2);
  112628. _vp_noise_normalize_sort(psy_look,mdct,sortindex[i]);
  112629. }
  112630. }
  112631. for(k=(vorbis_bitrate_managed(vb)?0:PACKETBLOBS/2);
  112632. k<=(vorbis_bitrate_managed(vb)?PACKETBLOBS-1:PACKETBLOBS/2);
  112633. k++){
  112634. oggpack_buffer *opb=vbi->packetblob[k];
  112635. /* start out our new packet blob with packet type and mode */
  112636. /* Encode the packet type */
  112637. oggpack_write(opb,0,1);
  112638. /* Encode the modenumber */
  112639. /* Encode frame mode, pre,post windowsize, then dispatch */
  112640. oggpack_write(opb,modenumber,b->modebits);
  112641. if(vb->W){
  112642. oggpack_write(opb,vb->lW,1);
  112643. oggpack_write(opb,vb->nW,1);
  112644. }
  112645. /* encode floor, compute masking curve, sep out residue */
  112646. for(i=0;i<vi->channels;i++){
  112647. int submap=info->chmuxlist[i];
  112648. float *mdct =gmdct[i];
  112649. float *res =vb->pcm[i];
  112650. int *ilogmask=ilogmaskch[i]=
  112651. (int*) _vorbis_block_alloc(vb,n/2*sizeof(**gmdct));
  112652. nonzero[i]=floor1_encode(opb,vb,b->flr[info->floorsubmap[submap]],
  112653. floor_posts[i][k],
  112654. ilogmask);
  112655. #if 0
  112656. {
  112657. char buf[80];
  112658. sprintf(buf,"maskI%c%d",i?'R':'L',k);
  112659. float work[n/2];
  112660. for(j=0;j<n/2;j++)
  112661. work[j]=FLOOR1_fromdB_LOOKUP[ilogmask[j]];
  112662. _analysis_output(buf,seq,work,n/2,1,1,0);
  112663. }
  112664. #endif
  112665. _vp_remove_floor(psy_look,
  112666. mdct,
  112667. ilogmask,
  112668. res,
  112669. ci->psy_g_param.sliding_lowpass[vb->W][k]);
  112670. _vp_noise_normalize(psy_look,res,res+n/2,sortindex[i]);
  112671. #if 0
  112672. {
  112673. char buf[80];
  112674. float work[n/2];
  112675. for(j=0;j<n/2;j++)
  112676. work[j]=FLOOR1_fromdB_LOOKUP[ilogmask[j]]*(res+n/2)[j];
  112677. sprintf(buf,"resI%c%d",i?'R':'L',k);
  112678. _analysis_output(buf,seq,work,n/2,1,1,0);
  112679. }
  112680. #endif
  112681. }
  112682. /* our iteration is now based on masking curve, not prequant and
  112683. coupling. Only one prequant/coupling step */
  112684. /* quantize/couple */
  112685. /* incomplete implementation that assumes the tree is all depth
  112686. one, or no tree at all */
  112687. if(info->coupling_steps){
  112688. _vp_couple(k,
  112689. &ci->psy_g_param,
  112690. psy_look,
  112691. info,
  112692. vb->pcm,
  112693. mag_memo,
  112694. mag_sort,
  112695. ilogmaskch,
  112696. nonzero,
  112697. ci->psy_g_param.sliding_lowpass[vb->W][k]);
  112698. }
  112699. /* classify and encode by submap */
  112700. for(i=0;i<info->submaps;i++){
  112701. int ch_in_bundle=0;
  112702. long **classifications;
  112703. int resnum=info->residuesubmap[i];
  112704. for(j=0;j<vi->channels;j++){
  112705. if(info->chmuxlist[j]==i){
  112706. zerobundle[ch_in_bundle]=0;
  112707. if(nonzero[j])zerobundle[ch_in_bundle]=1;
  112708. res_bundle[ch_in_bundle]=vb->pcm[j];
  112709. couple_bundle[ch_in_bundle++]=vb->pcm[j]+n/2;
  112710. }
  112711. }
  112712. classifications=_residue_P[ci->residue_type[resnum]]->
  112713. classx(vb,b->residue[resnum],couple_bundle,zerobundle,ch_in_bundle);
  112714. _residue_P[ci->residue_type[resnum]]->
  112715. forward(opb,vb,b->residue[resnum],
  112716. couple_bundle,NULL,zerobundle,ch_in_bundle,classifications);
  112717. }
  112718. /* ok, done encoding. Next protopacket. */
  112719. }
  112720. }
  112721. #if 0
  112722. seq++;
  112723. total+=ci->blocksizes[vb->W]/4+ci->blocksizes[vb->nW]/4;
  112724. #endif
  112725. return(0);
  112726. }
  112727. static int mapping0_inverse(vorbis_block *vb,vorbis_info_mapping *l){
  112728. vorbis_dsp_state *vd=vb->vd;
  112729. vorbis_info *vi=vd->vi;
  112730. codec_setup_info *ci=(codec_setup_info*) vi->codec_setup;
  112731. private_state *b=(private_state*)vd->backend_state;
  112732. vorbis_info_mapping0 *info=(vorbis_info_mapping0 *)l;
  112733. int i,j;
  112734. long n=vb->pcmend=ci->blocksizes[vb->W];
  112735. float **pcmbundle=(float**) alloca(sizeof(*pcmbundle)*vi->channels);
  112736. int *zerobundle=(int*) alloca(sizeof(*zerobundle)*vi->channels);
  112737. int *nonzero =(int*) alloca(sizeof(*nonzero)*vi->channels);
  112738. void **floormemo=(void**) alloca(sizeof(*floormemo)*vi->channels);
  112739. /* recover the spectral envelope; store it in the PCM vector for now */
  112740. for(i=0;i<vi->channels;i++){
  112741. int submap=info->chmuxlist[i];
  112742. floormemo[i]=_floor_P[ci->floor_type[info->floorsubmap[submap]]]->
  112743. inverse1(vb,b->flr[info->floorsubmap[submap]]);
  112744. if(floormemo[i])
  112745. nonzero[i]=1;
  112746. else
  112747. nonzero[i]=0;
  112748. memset(vb->pcm[i],0,sizeof(*vb->pcm[i])*n/2);
  112749. }
  112750. /* channel coupling can 'dirty' the nonzero listing */
  112751. for(i=0;i<info->coupling_steps;i++){
  112752. if(nonzero[info->coupling_mag[i]] ||
  112753. nonzero[info->coupling_ang[i]]){
  112754. nonzero[info->coupling_mag[i]]=1;
  112755. nonzero[info->coupling_ang[i]]=1;
  112756. }
  112757. }
  112758. /* recover the residue into our working vectors */
  112759. for(i=0;i<info->submaps;i++){
  112760. int ch_in_bundle=0;
  112761. for(j=0;j<vi->channels;j++){
  112762. if(info->chmuxlist[j]==i){
  112763. if(nonzero[j])
  112764. zerobundle[ch_in_bundle]=1;
  112765. else
  112766. zerobundle[ch_in_bundle]=0;
  112767. pcmbundle[ch_in_bundle++]=vb->pcm[j];
  112768. }
  112769. }
  112770. _residue_P[ci->residue_type[info->residuesubmap[i]]]->
  112771. inverse(vb,b->residue[info->residuesubmap[i]],
  112772. pcmbundle,zerobundle,ch_in_bundle);
  112773. }
  112774. /* channel coupling */
  112775. for(i=info->coupling_steps-1;i>=0;i--){
  112776. float *pcmM=vb->pcm[info->coupling_mag[i]];
  112777. float *pcmA=vb->pcm[info->coupling_ang[i]];
  112778. for(j=0;j<n/2;j++){
  112779. float mag=pcmM[j];
  112780. float ang=pcmA[j];
  112781. if(mag>0)
  112782. if(ang>0){
  112783. pcmM[j]=mag;
  112784. pcmA[j]=mag-ang;
  112785. }else{
  112786. pcmA[j]=mag;
  112787. pcmM[j]=mag+ang;
  112788. }
  112789. else
  112790. if(ang>0){
  112791. pcmM[j]=mag;
  112792. pcmA[j]=mag+ang;
  112793. }else{
  112794. pcmA[j]=mag;
  112795. pcmM[j]=mag-ang;
  112796. }
  112797. }
  112798. }
  112799. /* compute and apply spectral envelope */
  112800. for(i=0;i<vi->channels;i++){
  112801. float *pcm=vb->pcm[i];
  112802. int submap=info->chmuxlist[i];
  112803. _floor_P[ci->floor_type[info->floorsubmap[submap]]]->
  112804. inverse2(vb,b->flr[info->floorsubmap[submap]],
  112805. floormemo[i],pcm);
  112806. }
  112807. /* transform the PCM data; takes PCM vector, vb; modifies PCM vector */
  112808. /* only MDCT right now.... */
  112809. for(i=0;i<vi->channels;i++){
  112810. float *pcm=vb->pcm[i];
  112811. mdct_backward((mdct_lookup*) b->transform[vb->W][0],pcm,pcm);
  112812. }
  112813. /* all done! */
  112814. return(0);
  112815. }
  112816. /* export hooks */
  112817. vorbis_func_mapping mapping0_exportbundle={
  112818. &mapping0_pack,
  112819. &mapping0_unpack,
  112820. &mapping0_free_info,
  112821. &mapping0_forward,
  112822. &mapping0_inverse
  112823. };
  112824. #endif
  112825. /*** End of inlined file: mapping0.c ***/
  112826. /*** Start of inlined file: mdct.c ***/
  112827. /* this can also be run as an integer transform by uncommenting a
  112828. define in mdct.h; the integerization is a first pass and although
  112829. it's likely stable for Vorbis, the dynamic range is constrained and
  112830. roundoff isn't done (so it's noisy). Consider it functional, but
  112831. only a starting point. There's no point on a machine with an FPU */
  112832. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  112833. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  112834. // tasks..
  112835. #if JUCE_MSVC
  112836. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  112837. #endif
  112838. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  112839. #if JUCE_USE_OGGVORBIS
  112840. #include <stdio.h>
  112841. #include <stdlib.h>
  112842. #include <string.h>
  112843. #include <math.h>
  112844. /* build lookups for trig functions; also pre-figure scaling and
  112845. some window function algebra. */
  112846. void mdct_init(mdct_lookup *lookup,int n){
  112847. int *bitrev=(int*) _ogg_malloc(sizeof(*bitrev)*(n/4));
  112848. DATA_TYPE *T=(DATA_TYPE*) _ogg_malloc(sizeof(*T)*(n+n/4));
  112849. int i;
  112850. int n2=n>>1;
  112851. int log2n=lookup->log2n=rint(log((float)n)/log(2.f));
  112852. lookup->n=n;
  112853. lookup->trig=T;
  112854. lookup->bitrev=bitrev;
  112855. /* trig lookups... */
  112856. for(i=0;i<n/4;i++){
  112857. T[i*2]=FLOAT_CONV(cos((M_PI/n)*(4*i)));
  112858. T[i*2+1]=FLOAT_CONV(-sin((M_PI/n)*(4*i)));
  112859. T[n2+i*2]=FLOAT_CONV(cos((M_PI/(2*n))*(2*i+1)));
  112860. T[n2+i*2+1]=FLOAT_CONV(sin((M_PI/(2*n))*(2*i+1)));
  112861. }
  112862. for(i=0;i<n/8;i++){
  112863. T[n+i*2]=FLOAT_CONV(cos((M_PI/n)*(4*i+2))*.5);
  112864. T[n+i*2+1]=FLOAT_CONV(-sin((M_PI/n)*(4*i+2))*.5);
  112865. }
  112866. /* bitreverse lookup... */
  112867. {
  112868. int mask=(1<<(log2n-1))-1,i,j;
  112869. int msb=1<<(log2n-2);
  112870. for(i=0;i<n/8;i++){
  112871. int acc=0;
  112872. for(j=0;msb>>j;j++)
  112873. if((msb>>j)&i)acc|=1<<j;
  112874. bitrev[i*2]=((~acc)&mask)-1;
  112875. bitrev[i*2+1]=acc;
  112876. }
  112877. }
  112878. lookup->scale=FLOAT_CONV(4.f/n);
  112879. }
  112880. /* 8 point butterfly (in place, 4 register) */
  112881. STIN void mdct_butterfly_8(DATA_TYPE *x){
  112882. REG_TYPE r0 = x[6] + x[2];
  112883. REG_TYPE r1 = x[6] - x[2];
  112884. REG_TYPE r2 = x[4] + x[0];
  112885. REG_TYPE r3 = x[4] - x[0];
  112886. x[6] = r0 + r2;
  112887. x[4] = r0 - r2;
  112888. r0 = x[5] - x[1];
  112889. r2 = x[7] - x[3];
  112890. x[0] = r1 + r0;
  112891. x[2] = r1 - r0;
  112892. r0 = x[5] + x[1];
  112893. r1 = x[7] + x[3];
  112894. x[3] = r2 + r3;
  112895. x[1] = r2 - r3;
  112896. x[7] = r1 + r0;
  112897. x[5] = r1 - r0;
  112898. }
  112899. /* 16 point butterfly (in place, 4 register) */
  112900. STIN void mdct_butterfly_16(DATA_TYPE *x){
  112901. REG_TYPE r0 = x[1] - x[9];
  112902. REG_TYPE r1 = x[0] - x[8];
  112903. x[8] += x[0];
  112904. x[9] += x[1];
  112905. x[0] = MULT_NORM((r0 + r1) * cPI2_8);
  112906. x[1] = MULT_NORM((r0 - r1) * cPI2_8);
  112907. r0 = x[3] - x[11];
  112908. r1 = x[10] - x[2];
  112909. x[10] += x[2];
  112910. x[11] += x[3];
  112911. x[2] = r0;
  112912. x[3] = r1;
  112913. r0 = x[12] - x[4];
  112914. r1 = x[13] - x[5];
  112915. x[12] += x[4];
  112916. x[13] += x[5];
  112917. x[4] = MULT_NORM((r0 - r1) * cPI2_8);
  112918. x[5] = MULT_NORM((r0 + r1) * cPI2_8);
  112919. r0 = x[14] - x[6];
  112920. r1 = x[15] - x[7];
  112921. x[14] += x[6];
  112922. x[15] += x[7];
  112923. x[6] = r0;
  112924. x[7] = r1;
  112925. mdct_butterfly_8(x);
  112926. mdct_butterfly_8(x+8);
  112927. }
  112928. /* 32 point butterfly (in place, 4 register) */
  112929. STIN void mdct_butterfly_32(DATA_TYPE *x){
  112930. REG_TYPE r0 = x[30] - x[14];
  112931. REG_TYPE r1 = x[31] - x[15];
  112932. x[30] += x[14];
  112933. x[31] += x[15];
  112934. x[14] = r0;
  112935. x[15] = r1;
  112936. r0 = x[28] - x[12];
  112937. r1 = x[29] - x[13];
  112938. x[28] += x[12];
  112939. x[29] += x[13];
  112940. x[12] = MULT_NORM( r0 * cPI1_8 - r1 * cPI3_8 );
  112941. x[13] = MULT_NORM( r0 * cPI3_8 + r1 * cPI1_8 );
  112942. r0 = x[26] - x[10];
  112943. r1 = x[27] - x[11];
  112944. x[26] += x[10];
  112945. x[27] += x[11];
  112946. x[10] = MULT_NORM(( r0 - r1 ) * cPI2_8);
  112947. x[11] = MULT_NORM(( r0 + r1 ) * cPI2_8);
  112948. r0 = x[24] - x[8];
  112949. r1 = x[25] - x[9];
  112950. x[24] += x[8];
  112951. x[25] += x[9];
  112952. x[8] = MULT_NORM( r0 * cPI3_8 - r1 * cPI1_8 );
  112953. x[9] = MULT_NORM( r1 * cPI3_8 + r0 * cPI1_8 );
  112954. r0 = x[22] - x[6];
  112955. r1 = x[7] - x[23];
  112956. x[22] += x[6];
  112957. x[23] += x[7];
  112958. x[6] = r1;
  112959. x[7] = r0;
  112960. r0 = x[4] - x[20];
  112961. r1 = x[5] - x[21];
  112962. x[20] += x[4];
  112963. x[21] += x[5];
  112964. x[4] = MULT_NORM( r1 * cPI1_8 + r0 * cPI3_8 );
  112965. x[5] = MULT_NORM( r1 * cPI3_8 - r0 * cPI1_8 );
  112966. r0 = x[2] - x[18];
  112967. r1 = x[3] - x[19];
  112968. x[18] += x[2];
  112969. x[19] += x[3];
  112970. x[2] = MULT_NORM(( r1 + r0 ) * cPI2_8);
  112971. x[3] = MULT_NORM(( r1 - r0 ) * cPI2_8);
  112972. r0 = x[0] - x[16];
  112973. r1 = x[1] - x[17];
  112974. x[16] += x[0];
  112975. x[17] += x[1];
  112976. x[0] = MULT_NORM( r1 * cPI3_8 + r0 * cPI1_8 );
  112977. x[1] = MULT_NORM( r1 * cPI1_8 - r0 * cPI3_8 );
  112978. mdct_butterfly_16(x);
  112979. mdct_butterfly_16(x+16);
  112980. }
  112981. /* N point first stage butterfly (in place, 2 register) */
  112982. STIN void mdct_butterfly_first(DATA_TYPE *T,
  112983. DATA_TYPE *x,
  112984. int points){
  112985. DATA_TYPE *x1 = x + points - 8;
  112986. DATA_TYPE *x2 = x + (points>>1) - 8;
  112987. REG_TYPE r0;
  112988. REG_TYPE r1;
  112989. do{
  112990. r0 = x1[6] - x2[6];
  112991. r1 = x1[7] - x2[7];
  112992. x1[6] += x2[6];
  112993. x1[7] += x2[7];
  112994. x2[6] = MULT_NORM(r1 * T[1] + r0 * T[0]);
  112995. x2[7] = MULT_NORM(r1 * T[0] - r0 * T[1]);
  112996. r0 = x1[4] - x2[4];
  112997. r1 = x1[5] - x2[5];
  112998. x1[4] += x2[4];
  112999. x1[5] += x2[5];
  113000. x2[4] = MULT_NORM(r1 * T[5] + r0 * T[4]);
  113001. x2[5] = MULT_NORM(r1 * T[4] - r0 * T[5]);
  113002. r0 = x1[2] - x2[2];
  113003. r1 = x1[3] - x2[3];
  113004. x1[2] += x2[2];
  113005. x1[3] += x2[3];
  113006. x2[2] = MULT_NORM(r1 * T[9] + r0 * T[8]);
  113007. x2[3] = MULT_NORM(r1 * T[8] - r0 * T[9]);
  113008. r0 = x1[0] - x2[0];
  113009. r1 = x1[1] - x2[1];
  113010. x1[0] += x2[0];
  113011. x1[1] += x2[1];
  113012. x2[0] = MULT_NORM(r1 * T[13] + r0 * T[12]);
  113013. x2[1] = MULT_NORM(r1 * T[12] - r0 * T[13]);
  113014. x1-=8;
  113015. x2-=8;
  113016. T+=16;
  113017. }while(x2>=x);
  113018. }
  113019. /* N/stage point generic N stage butterfly (in place, 2 register) */
  113020. STIN void mdct_butterfly_generic(DATA_TYPE *T,
  113021. DATA_TYPE *x,
  113022. int points,
  113023. int trigint){
  113024. DATA_TYPE *x1 = x + points - 8;
  113025. DATA_TYPE *x2 = x + (points>>1) - 8;
  113026. REG_TYPE r0;
  113027. REG_TYPE r1;
  113028. do{
  113029. r0 = x1[6] - x2[6];
  113030. r1 = x1[7] - x2[7];
  113031. x1[6] += x2[6];
  113032. x1[7] += x2[7];
  113033. x2[6] = MULT_NORM(r1 * T[1] + r0 * T[0]);
  113034. x2[7] = MULT_NORM(r1 * T[0] - r0 * T[1]);
  113035. T+=trigint;
  113036. r0 = x1[4] - x2[4];
  113037. r1 = x1[5] - x2[5];
  113038. x1[4] += x2[4];
  113039. x1[5] += x2[5];
  113040. x2[4] = MULT_NORM(r1 * T[1] + r0 * T[0]);
  113041. x2[5] = MULT_NORM(r1 * T[0] - r0 * T[1]);
  113042. T+=trigint;
  113043. r0 = x1[2] - x2[2];
  113044. r1 = x1[3] - x2[3];
  113045. x1[2] += x2[2];
  113046. x1[3] += x2[3];
  113047. x2[2] = MULT_NORM(r1 * T[1] + r0 * T[0]);
  113048. x2[3] = MULT_NORM(r1 * T[0] - r0 * T[1]);
  113049. T+=trigint;
  113050. r0 = x1[0] - x2[0];
  113051. r1 = x1[1] - x2[1];
  113052. x1[0] += x2[0];
  113053. x1[1] += x2[1];
  113054. x2[0] = MULT_NORM(r1 * T[1] + r0 * T[0]);
  113055. x2[1] = MULT_NORM(r1 * T[0] - r0 * T[1]);
  113056. T+=trigint;
  113057. x1-=8;
  113058. x2-=8;
  113059. }while(x2>=x);
  113060. }
  113061. STIN void mdct_butterflies(mdct_lookup *init,
  113062. DATA_TYPE *x,
  113063. int points){
  113064. DATA_TYPE *T=init->trig;
  113065. int stages=init->log2n-5;
  113066. int i,j;
  113067. if(--stages>0){
  113068. mdct_butterfly_first(T,x,points);
  113069. }
  113070. for(i=1;--stages>0;i++){
  113071. for(j=0;j<(1<<i);j++)
  113072. mdct_butterfly_generic(T,x+(points>>i)*j,points>>i,4<<i);
  113073. }
  113074. for(j=0;j<points;j+=32)
  113075. mdct_butterfly_32(x+j);
  113076. }
  113077. void mdct_clear(mdct_lookup *l){
  113078. if(l){
  113079. if(l->trig)_ogg_free(l->trig);
  113080. if(l->bitrev)_ogg_free(l->bitrev);
  113081. memset(l,0,sizeof(*l));
  113082. }
  113083. }
  113084. STIN void mdct_bitreverse(mdct_lookup *init,
  113085. DATA_TYPE *x){
  113086. int n = init->n;
  113087. int *bit = init->bitrev;
  113088. DATA_TYPE *w0 = x;
  113089. DATA_TYPE *w1 = x = w0+(n>>1);
  113090. DATA_TYPE *T = init->trig+n;
  113091. do{
  113092. DATA_TYPE *x0 = x+bit[0];
  113093. DATA_TYPE *x1 = x+bit[1];
  113094. REG_TYPE r0 = x0[1] - x1[1];
  113095. REG_TYPE r1 = x0[0] + x1[0];
  113096. REG_TYPE r2 = MULT_NORM(r1 * T[0] + r0 * T[1]);
  113097. REG_TYPE r3 = MULT_NORM(r1 * T[1] - r0 * T[0]);
  113098. w1 -= 4;
  113099. r0 = HALVE(x0[1] + x1[1]);
  113100. r1 = HALVE(x0[0] - x1[0]);
  113101. w0[0] = r0 + r2;
  113102. w1[2] = r0 - r2;
  113103. w0[1] = r1 + r3;
  113104. w1[3] = r3 - r1;
  113105. x0 = x+bit[2];
  113106. x1 = x+bit[3];
  113107. r0 = x0[1] - x1[1];
  113108. r1 = x0[0] + x1[0];
  113109. r2 = MULT_NORM(r1 * T[2] + r0 * T[3]);
  113110. r3 = MULT_NORM(r1 * T[3] - r0 * T[2]);
  113111. r0 = HALVE(x0[1] + x1[1]);
  113112. r1 = HALVE(x0[0] - x1[0]);
  113113. w0[2] = r0 + r2;
  113114. w1[0] = r0 - r2;
  113115. w0[3] = r1 + r3;
  113116. w1[1] = r3 - r1;
  113117. T += 4;
  113118. bit += 4;
  113119. w0 += 4;
  113120. }while(w0<w1);
  113121. }
  113122. void mdct_backward(mdct_lookup *init, DATA_TYPE *in, DATA_TYPE *out){
  113123. int n=init->n;
  113124. int n2=n>>1;
  113125. int n4=n>>2;
  113126. /* rotate */
  113127. DATA_TYPE *iX = in+n2-7;
  113128. DATA_TYPE *oX = out+n2+n4;
  113129. DATA_TYPE *T = init->trig+n4;
  113130. do{
  113131. oX -= 4;
  113132. oX[0] = MULT_NORM(-iX[2] * T[3] - iX[0] * T[2]);
  113133. oX[1] = MULT_NORM (iX[0] * T[3] - iX[2] * T[2]);
  113134. oX[2] = MULT_NORM(-iX[6] * T[1] - iX[4] * T[0]);
  113135. oX[3] = MULT_NORM (iX[4] * T[1] - iX[6] * T[0]);
  113136. iX -= 8;
  113137. T += 4;
  113138. }while(iX>=in);
  113139. iX = in+n2-8;
  113140. oX = out+n2+n4;
  113141. T = init->trig+n4;
  113142. do{
  113143. T -= 4;
  113144. oX[0] = MULT_NORM (iX[4] * T[3] + iX[6] * T[2]);
  113145. oX[1] = MULT_NORM (iX[4] * T[2] - iX[6] * T[3]);
  113146. oX[2] = MULT_NORM (iX[0] * T[1] + iX[2] * T[0]);
  113147. oX[3] = MULT_NORM (iX[0] * T[0] - iX[2] * T[1]);
  113148. iX -= 8;
  113149. oX += 4;
  113150. }while(iX>=in);
  113151. mdct_butterflies(init,out+n2,n2);
  113152. mdct_bitreverse(init,out);
  113153. /* roatate + window */
  113154. {
  113155. DATA_TYPE *oX1=out+n2+n4;
  113156. DATA_TYPE *oX2=out+n2+n4;
  113157. DATA_TYPE *iX =out;
  113158. T =init->trig+n2;
  113159. do{
  113160. oX1-=4;
  113161. oX1[3] = MULT_NORM (iX[0] * T[1] - iX[1] * T[0]);
  113162. oX2[0] = -MULT_NORM (iX[0] * T[0] + iX[1] * T[1]);
  113163. oX1[2] = MULT_NORM (iX[2] * T[3] - iX[3] * T[2]);
  113164. oX2[1] = -MULT_NORM (iX[2] * T[2] + iX[3] * T[3]);
  113165. oX1[1] = MULT_NORM (iX[4] * T[5] - iX[5] * T[4]);
  113166. oX2[2] = -MULT_NORM (iX[4] * T[4] + iX[5] * T[5]);
  113167. oX1[0] = MULT_NORM (iX[6] * T[7] - iX[7] * T[6]);
  113168. oX2[3] = -MULT_NORM (iX[6] * T[6] + iX[7] * T[7]);
  113169. oX2+=4;
  113170. iX += 8;
  113171. T += 8;
  113172. }while(iX<oX1);
  113173. iX=out+n2+n4;
  113174. oX1=out+n4;
  113175. oX2=oX1;
  113176. do{
  113177. oX1-=4;
  113178. iX-=4;
  113179. oX2[0] = -(oX1[3] = iX[3]);
  113180. oX2[1] = -(oX1[2] = iX[2]);
  113181. oX2[2] = -(oX1[1] = iX[1]);
  113182. oX2[3] = -(oX1[0] = iX[0]);
  113183. oX2+=4;
  113184. }while(oX2<iX);
  113185. iX=out+n2+n4;
  113186. oX1=out+n2+n4;
  113187. oX2=out+n2;
  113188. do{
  113189. oX1-=4;
  113190. oX1[0]= iX[3];
  113191. oX1[1]= iX[2];
  113192. oX1[2]= iX[1];
  113193. oX1[3]= iX[0];
  113194. iX+=4;
  113195. }while(oX1>oX2);
  113196. }
  113197. }
  113198. void mdct_forward(mdct_lookup *init, DATA_TYPE *in, DATA_TYPE *out){
  113199. int n=init->n;
  113200. int n2=n>>1;
  113201. int n4=n>>2;
  113202. int n8=n>>3;
  113203. DATA_TYPE *w=(DATA_TYPE*) alloca(n*sizeof(*w)); /* forward needs working space */
  113204. DATA_TYPE *w2=w+n2;
  113205. /* rotate */
  113206. /* window + rotate + step 1 */
  113207. REG_TYPE r0;
  113208. REG_TYPE r1;
  113209. DATA_TYPE *x0=in+n2+n4;
  113210. DATA_TYPE *x1=x0+1;
  113211. DATA_TYPE *T=init->trig+n2;
  113212. int i=0;
  113213. for(i=0;i<n8;i+=2){
  113214. x0 -=4;
  113215. T-=2;
  113216. r0= x0[2] + x1[0];
  113217. r1= x0[0] + x1[2];
  113218. w2[i]= MULT_NORM(r1*T[1] + r0*T[0]);
  113219. w2[i+1]= MULT_NORM(r1*T[0] - r0*T[1]);
  113220. x1 +=4;
  113221. }
  113222. x1=in+1;
  113223. for(;i<n2-n8;i+=2){
  113224. T-=2;
  113225. x0 -=4;
  113226. r0= x0[2] - x1[0];
  113227. r1= x0[0] - x1[2];
  113228. w2[i]= MULT_NORM(r1*T[1] + r0*T[0]);
  113229. w2[i+1]= MULT_NORM(r1*T[0] - r0*T[1]);
  113230. x1 +=4;
  113231. }
  113232. x0=in+n;
  113233. for(;i<n2;i+=2){
  113234. T-=2;
  113235. x0 -=4;
  113236. r0= -x0[2] - x1[0];
  113237. r1= -x0[0] - x1[2];
  113238. w2[i]= MULT_NORM(r1*T[1] + r0*T[0]);
  113239. w2[i+1]= MULT_NORM(r1*T[0] - r0*T[1]);
  113240. x1 +=4;
  113241. }
  113242. mdct_butterflies(init,w+n2,n2);
  113243. mdct_bitreverse(init,w);
  113244. /* roatate + window */
  113245. T=init->trig+n2;
  113246. x0=out+n2;
  113247. for(i=0;i<n4;i++){
  113248. x0--;
  113249. out[i] =MULT_NORM((w[0]*T[0]+w[1]*T[1])*init->scale);
  113250. x0[0] =MULT_NORM((w[0]*T[1]-w[1]*T[0])*init->scale);
  113251. w+=2;
  113252. T+=2;
  113253. }
  113254. }
  113255. #endif
  113256. /*** End of inlined file: mdct.c ***/
  113257. /*** Start of inlined file: psy.c ***/
  113258. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  113259. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  113260. // tasks..
  113261. #if JUCE_MSVC
  113262. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  113263. #endif
  113264. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  113265. #if JUCE_USE_OGGVORBIS
  113266. #include <stdlib.h>
  113267. #include <math.h>
  113268. #include <string.h>
  113269. /*** Start of inlined file: masking.h ***/
  113270. #ifndef _V_MASKING_H_
  113271. #define _V_MASKING_H_
  113272. /* more detailed ATH; the bass if flat to save stressing the floor
  113273. overly for only a bin or two of savings. */
  113274. #define MAX_ATH 88
  113275. static float ATH[]={
  113276. /*15*/ -51, -52, -53, -54, -55, -56, -57, -58,
  113277. /*31*/ -59, -60, -61, -62, -63, -64, -65, -66,
  113278. /*63*/ -67, -68, -69, -70, -71, -72, -73, -74,
  113279. /*125*/ -75, -76, -77, -78, -80, -81, -82, -83,
  113280. /*250*/ -84, -85, -86, -87, -88, -88, -89, -89,
  113281. /*500*/ -90, -91, -91, -92, -93, -94, -95, -96,
  113282. /*1k*/ -96, -97, -98, -98, -99, -99,-100,-100,
  113283. /*2k*/ -101,-102,-103,-104,-106,-107,-107,-107,
  113284. /*4k*/ -107,-105,-103,-102,-101, -99, -98, -96,
  113285. /*8k*/ -95, -95, -96, -97, -96, -95, -93, -90,
  113286. /*16k*/ -80, -70, -50, -40, -30, -30, -30, -30
  113287. };
  113288. /* The tone masking curves from Ehmer's and Fielder's papers have been
  113289. replaced by an empirically collected data set. The previously
  113290. published values were, far too often, simply on crack. */
  113291. #define EHMER_OFFSET 16
  113292. #define EHMER_MAX 56
  113293. /* masking tones from -50 to 0dB, 62.5 through 16kHz at half octaves
  113294. test tones from -2 octaves to +5 octaves sampled at eighth octaves */
  113295. /* (Vorbis 0dB, the loudest possible tone, is assumed to be ~100dB SPL
  113296. for collection of these curves) */
  113297. static float tonemasks[P_BANDS][6][EHMER_MAX]={
  113298. /* 62.5 Hz */
  113299. {{ -60, -60, -60, -60, -60, -60, -60, -60,
  113300. -60, -60, -60, -60, -62, -62, -65, -73,
  113301. -69, -68, -68, -67, -70, -70, -72, -74,
  113302. -75, -79, -79, -80, -83, -88, -93, -100,
  113303. -110, -999, -999, -999, -999, -999, -999, -999,
  113304. -999, -999, -999, -999, -999, -999, -999, -999,
  113305. -999, -999, -999, -999, -999, -999, -999, -999},
  113306. { -48, -48, -48, -48, -48, -48, -48, -48,
  113307. -48, -48, -48, -48, -48, -53, -61, -66,
  113308. -66, -68, -67, -70, -76, -76, -72, -73,
  113309. -75, -76, -78, -79, -83, -88, -93, -100,
  113310. -110, -999, -999, -999, -999, -999, -999, -999,
  113311. -999, -999, -999, -999, -999, -999, -999, -999,
  113312. -999, -999, -999, -999, -999, -999, -999, -999},
  113313. { -37, -37, -37, -37, -37, -37, -37, -37,
  113314. -38, -40, -42, -46, -48, -53, -55, -62,
  113315. -65, -58, -56, -56, -61, -60, -65, -67,
  113316. -69, -71, -77, -77, -78, -80, -82, -84,
  113317. -88, -93, -98, -106, -112, -999, -999, -999,
  113318. -999, -999, -999, -999, -999, -999, -999, -999,
  113319. -999, -999, -999, -999, -999, -999, -999, -999},
  113320. { -25, -25, -25, -25, -25, -25, -25, -25,
  113321. -25, -26, -27, -29, -32, -38, -48, -52,
  113322. -52, -50, -48, -48, -51, -52, -54, -60,
  113323. -67, -67, -66, -68, -69, -73, -73, -76,
  113324. -80, -81, -81, -85, -85, -86, -88, -93,
  113325. -100, -110, -999, -999, -999, -999, -999, -999,
  113326. -999, -999, -999, -999, -999, -999, -999, -999},
  113327. { -16, -16, -16, -16, -16, -16, -16, -16,
  113328. -17, -19, -20, -22, -26, -28, -31, -40,
  113329. -47, -39, -39, -40, -42, -43, -47, -51,
  113330. -57, -52, -55, -55, -60, -58, -62, -63,
  113331. -70, -67, -69, -72, -73, -77, -80, -82,
  113332. -83, -87, -90, -94, -98, -104, -115, -999,
  113333. -999, -999, -999, -999, -999, -999, -999, -999},
  113334. { -8, -8, -8, -8, -8, -8, -8, -8,
  113335. -8, -8, -10, -11, -15, -19, -25, -30,
  113336. -34, -31, -30, -31, -29, -32, -35, -42,
  113337. -48, -42, -44, -46, -50, -50, -51, -52,
  113338. -59, -54, -55, -55, -58, -62, -63, -66,
  113339. -72, -73, -76, -75, -78, -80, -80, -81,
  113340. -84, -88, -90, -94, -98, -101, -106, -110}},
  113341. /* 88Hz */
  113342. {{ -66, -66, -66, -66, -66, -66, -66, -66,
  113343. -66, -66, -66, -66, -66, -67, -67, -67,
  113344. -76, -72, -71, -74, -76, -76, -75, -78,
  113345. -79, -79, -81, -83, -86, -89, -93, -97,
  113346. -100, -105, -110, -999, -999, -999, -999, -999,
  113347. -999, -999, -999, -999, -999, -999, -999, -999,
  113348. -999, -999, -999, -999, -999, -999, -999, -999},
  113349. { -47, -47, -47, -47, -47, -47, -47, -47,
  113350. -47, -47, -47, -48, -51, -55, -59, -66,
  113351. -66, -66, -67, -66, -68, -69, -70, -74,
  113352. -79, -77, -77, -78, -80, -81, -82, -84,
  113353. -86, -88, -91, -95, -100, -108, -116, -999,
  113354. -999, -999, -999, -999, -999, -999, -999, -999,
  113355. -999, -999, -999, -999, -999, -999, -999, -999},
  113356. { -36, -36, -36, -36, -36, -36, -36, -36,
  113357. -36, -37, -37, -41, -44, -48, -51, -58,
  113358. -62, -60, -57, -59, -59, -60, -63, -65,
  113359. -72, -71, -70, -72, -74, -77, -76, -78,
  113360. -81, -81, -80, -83, -86, -91, -96, -100,
  113361. -105, -110, -999, -999, -999, -999, -999, -999,
  113362. -999, -999, -999, -999, -999, -999, -999, -999},
  113363. { -28, -28, -28, -28, -28, -28, -28, -28,
  113364. -28, -30, -32, -32, -33, -35, -41, -49,
  113365. -50, -49, -47, -48, -48, -52, -51, -57,
  113366. -65, -61, -59, -61, -64, -69, -70, -74,
  113367. -77, -77, -78, -81, -84, -85, -87, -90,
  113368. -92, -96, -100, -107, -112, -999, -999, -999,
  113369. -999, -999, -999, -999, -999, -999, -999, -999},
  113370. { -19, -19, -19, -19, -19, -19, -19, -19,
  113371. -20, -21, -23, -27, -30, -35, -36, -41,
  113372. -46, -44, -42, -40, -41, -41, -43, -48,
  113373. -55, -53, -52, -53, -56, -59, -58, -60,
  113374. -67, -66, -69, -71, -72, -75, -79, -81,
  113375. -84, -87, -90, -93, -97, -101, -107, -114,
  113376. -999, -999, -999, -999, -999, -999, -999, -999},
  113377. { -9, -9, -9, -9, -9, -9, -9, -9,
  113378. -11, -12, -12, -15, -16, -20, -23, -30,
  113379. -37, -34, -33, -34, -31, -32, -32, -38,
  113380. -47, -44, -41, -40, -47, -49, -46, -46,
  113381. -58, -50, -50, -54, -58, -62, -64, -67,
  113382. -67, -70, -72, -76, -79, -83, -87, -91,
  113383. -96, -100, -104, -110, -999, -999, -999, -999}},
  113384. /* 125 Hz */
  113385. {{ -62, -62, -62, -62, -62, -62, -62, -62,
  113386. -62, -62, -63, -64, -66, -67, -66, -68,
  113387. -75, -72, -76, -75, -76, -78, -79, -82,
  113388. -84, -85, -90, -94, -101, -110, -999, -999,
  113389. -999, -999, -999, -999, -999, -999, -999, -999,
  113390. -999, -999, -999, -999, -999, -999, -999, -999,
  113391. -999, -999, -999, -999, -999, -999, -999, -999},
  113392. { -59, -59, -59, -59, -59, -59, -59, -59,
  113393. -59, -59, -59, -60, -60, -61, -63, -66,
  113394. -71, -68, -70, -70, -71, -72, -72, -75,
  113395. -81, -78, -79, -82, -83, -86, -90, -97,
  113396. -103, -113, -999, -999, -999, -999, -999, -999,
  113397. -999, -999, -999, -999, -999, -999, -999, -999,
  113398. -999, -999, -999, -999, -999, -999, -999, -999},
  113399. { -53, -53, -53, -53, -53, -53, -53, -53,
  113400. -53, -54, -55, -57, -56, -57, -55, -61,
  113401. -65, -60, -60, -62, -63, -63, -66, -68,
  113402. -74, -73, -75, -75, -78, -80, -80, -82,
  113403. -85, -90, -96, -101, -108, -999, -999, -999,
  113404. -999, -999, -999, -999, -999, -999, -999, -999,
  113405. -999, -999, -999, -999, -999, -999, -999, -999},
  113406. { -46, -46, -46, -46, -46, -46, -46, -46,
  113407. -46, -46, -47, -47, -47, -47, -48, -51,
  113408. -57, -51, -49, -50, -51, -53, -54, -59,
  113409. -66, -60, -62, -67, -67, -70, -72, -75,
  113410. -76, -78, -81, -85, -88, -94, -97, -104,
  113411. -112, -999, -999, -999, -999, -999, -999, -999,
  113412. -999, -999, -999, -999, -999, -999, -999, -999},
  113413. { -36, -36, -36, -36, -36, -36, -36, -36,
  113414. -39, -41, -42, -42, -39, -38, -41, -43,
  113415. -52, -44, -40, -39, -37, -37, -40, -47,
  113416. -54, -50, -48, -50, -55, -61, -59, -62,
  113417. -66, -66, -66, -69, -69, -73, -74, -74,
  113418. -75, -77, -79, -82, -87, -91, -95, -100,
  113419. -108, -115, -999, -999, -999, -999, -999, -999},
  113420. { -28, -26, -24, -22, -20, -20, -23, -29,
  113421. -30, -31, -28, -27, -28, -28, -28, -35,
  113422. -40, -33, -32, -29, -30, -30, -30, -37,
  113423. -45, -41, -37, -38, -45, -47, -47, -48,
  113424. -53, -49, -48, -50, -49, -49, -51, -52,
  113425. -58, -56, -57, -56, -60, -61, -62, -70,
  113426. -72, -74, -78, -83, -88, -93, -100, -106}},
  113427. /* 177 Hz */
  113428. {{-999, -999, -999, -999, -999, -999, -999, -999,
  113429. -999, -110, -105, -100, -95, -91, -87, -83,
  113430. -80, -78, -76, -78, -78, -81, -83, -85,
  113431. -86, -85, -86, -87, -90, -97, -107, -999,
  113432. -999, -999, -999, -999, -999, -999, -999, -999,
  113433. -999, -999, -999, -999, -999, -999, -999, -999,
  113434. -999, -999, -999, -999, -999, -999, -999, -999},
  113435. {-999, -999, -999, -110, -105, -100, -95, -90,
  113436. -85, -81, -77, -73, -70, -67, -67, -68,
  113437. -75, -73, -70, -69, -70, -72, -75, -79,
  113438. -84, -83, -84, -86, -88, -89, -89, -93,
  113439. -98, -105, -112, -999, -999, -999, -999, -999,
  113440. -999, -999, -999, -999, -999, -999, -999, -999,
  113441. -999, -999, -999, -999, -999, -999, -999, -999},
  113442. {-105, -100, -95, -90, -85, -80, -76, -71,
  113443. -68, -68, -65, -63, -63, -62, -62, -64,
  113444. -65, -64, -61, -62, -63, -64, -66, -68,
  113445. -73, -73, -74, -75, -76, -81, -83, -85,
  113446. -88, -89, -92, -95, -100, -108, -999, -999,
  113447. -999, -999, -999, -999, -999, -999, -999, -999,
  113448. -999, -999, -999, -999, -999, -999, -999, -999},
  113449. { -80, -75, -71, -68, -65, -63, -62, -61,
  113450. -61, -61, -61, -59, -56, -57, -53, -50,
  113451. -58, -52, -50, -50, -52, -53, -54, -58,
  113452. -67, -63, -67, -68, -72, -75, -78, -80,
  113453. -81, -81, -82, -85, -89, -90, -93, -97,
  113454. -101, -107, -114, -999, -999, -999, -999, -999,
  113455. -999, -999, -999, -999, -999, -999, -999, -999},
  113456. { -65, -61, -59, -57, -56, -55, -55, -56,
  113457. -56, -57, -55, -53, -52, -47, -44, -44,
  113458. -50, -44, -41, -39, -39, -42, -40, -46,
  113459. -51, -49, -50, -53, -54, -63, -60, -61,
  113460. -62, -66, -66, -66, -70, -73, -74, -75,
  113461. -76, -75, -79, -85, -89, -91, -96, -102,
  113462. -110, -999, -999, -999, -999, -999, -999, -999},
  113463. { -52, -50, -49, -49, -48, -48, -48, -49,
  113464. -50, -50, -49, -46, -43, -39, -35, -33,
  113465. -38, -36, -32, -29, -32, -32, -32, -35,
  113466. -44, -39, -38, -38, -46, -50, -45, -46,
  113467. -53, -50, -50, -50, -54, -54, -53, -53,
  113468. -56, -57, -59, -66, -70, -72, -74, -79,
  113469. -83, -85, -90, -97, -114, -999, -999, -999}},
  113470. /* 250 Hz */
  113471. {{-999, -999, -999, -999, -999, -999, -110, -105,
  113472. -100, -95, -90, -86, -80, -75, -75, -79,
  113473. -80, -79, -80, -81, -82, -88, -95, -103,
  113474. -110, -999, -999, -999, -999, -999, -999, -999,
  113475. -999, -999, -999, -999, -999, -999, -999, -999,
  113476. -999, -999, -999, -999, -999, -999, -999, -999,
  113477. -999, -999, -999, -999, -999, -999, -999, -999},
  113478. {-999, -999, -999, -999, -108, -103, -98, -93,
  113479. -88, -83, -79, -78, -75, -71, -67, -68,
  113480. -73, -73, -72, -73, -75, -77, -80, -82,
  113481. -88, -93, -100, -107, -114, -999, -999, -999,
  113482. -999, -999, -999, -999, -999, -999, -999, -999,
  113483. -999, -999, -999, -999, -999, -999, -999, -999,
  113484. -999, -999, -999, -999, -999, -999, -999, -999},
  113485. {-999, -999, -999, -110, -105, -101, -96, -90,
  113486. -86, -81, -77, -73, -69, -66, -61, -62,
  113487. -66, -64, -62, -65, -66, -70, -72, -76,
  113488. -81, -80, -84, -90, -95, -102, -110, -999,
  113489. -999, -999, -999, -999, -999, -999, -999, -999,
  113490. -999, -999, -999, -999, -999, -999, -999, -999,
  113491. -999, -999, -999, -999, -999, -999, -999, -999},
  113492. {-999, -999, -999, -107, -103, -97, -92, -88,
  113493. -83, -79, -74, -70, -66, -59, -53, -58,
  113494. -62, -55, -54, -54, -54, -58, -61, -62,
  113495. -72, -70, -72, -75, -78, -80, -81, -80,
  113496. -83, -83, -88, -93, -100, -107, -115, -999,
  113497. -999, -999, -999, -999, -999, -999, -999, -999,
  113498. -999, -999, -999, -999, -999, -999, -999, -999},
  113499. {-999, -999, -999, -105, -100, -95, -90, -85,
  113500. -80, -75, -70, -66, -62, -56, -48, -44,
  113501. -48, -46, -46, -43, -46, -48, -48, -51,
  113502. -58, -58, -59, -60, -62, -62, -61, -61,
  113503. -65, -64, -65, -68, -70, -74, -75, -78,
  113504. -81, -86, -95, -110, -999, -999, -999, -999,
  113505. -999, -999, -999, -999, -999, -999, -999, -999},
  113506. {-999, -999, -105, -100, -95, -90, -85, -80,
  113507. -75, -70, -65, -61, -55, -49, -39, -33,
  113508. -40, -35, -32, -38, -40, -33, -35, -37,
  113509. -46, -41, -45, -44, -46, -42, -45, -46,
  113510. -52, -50, -50, -50, -54, -54, -55, -57,
  113511. -62, -64, -66, -68, -70, -76, -81, -90,
  113512. -100, -110, -999, -999, -999, -999, -999, -999}},
  113513. /* 354 hz */
  113514. {{-999, -999, -999, -999, -999, -999, -999, -999,
  113515. -105, -98, -90, -85, -82, -83, -80, -78,
  113516. -84, -79, -80, -83, -87, -89, -91, -93,
  113517. -99, -106, -117, -999, -999, -999, -999, -999,
  113518. -999, -999, -999, -999, -999, -999, -999, -999,
  113519. -999, -999, -999, -999, -999, -999, -999, -999,
  113520. -999, -999, -999, -999, -999, -999, -999, -999},
  113521. {-999, -999, -999, -999, -999, -999, -999, -999,
  113522. -105, -98, -90, -85, -80, -75, -70, -68,
  113523. -74, -72, -74, -77, -80, -82, -85, -87,
  113524. -92, -89, -91, -95, -100, -106, -112, -999,
  113525. -999, -999, -999, -999, -999, -999, -999, -999,
  113526. -999, -999, -999, -999, -999, -999, -999, -999,
  113527. -999, -999, -999, -999, -999, -999, -999, -999},
  113528. {-999, -999, -999, -999, -999, -999, -999, -999,
  113529. -105, -98, -90, -83, -75, -71, -63, -64,
  113530. -67, -62, -64, -67, -70, -73, -77, -81,
  113531. -84, -83, -85, -89, -90, -93, -98, -104,
  113532. -109, -114, -999, -999, -999, -999, -999, -999,
  113533. -999, -999, -999, -999, -999, -999, -999, -999,
  113534. -999, -999, -999, -999, -999, -999, -999, -999},
  113535. {-999, -999, -999, -999, -999, -999, -999, -999,
  113536. -103, -96, -88, -81, -75, -68, -58, -54,
  113537. -56, -54, -56, -56, -58, -60, -63, -66,
  113538. -74, -69, -72, -72, -75, -74, -77, -81,
  113539. -81, -82, -84, -87, -93, -96, -99, -104,
  113540. -110, -999, -999, -999, -999, -999, -999, -999,
  113541. -999, -999, -999, -999, -999, -999, -999, -999},
  113542. {-999, -999, -999, -999, -999, -108, -102, -96,
  113543. -91, -85, -80, -74, -68, -60, -51, -46,
  113544. -48, -46, -43, -45, -47, -47, -49, -48,
  113545. -56, -53, -55, -58, -57, -63, -58, -60,
  113546. -66, -64, -67, -70, -70, -74, -77, -84,
  113547. -86, -89, -91, -93, -94, -101, -109, -118,
  113548. -999, -999, -999, -999, -999, -999, -999, -999},
  113549. {-999, -999, -999, -108, -103, -98, -93, -88,
  113550. -83, -78, -73, -68, -60, -53, -44, -35,
  113551. -38, -38, -34, -34, -36, -40, -41, -44,
  113552. -51, -45, -46, -47, -46, -54, -50, -49,
  113553. -50, -50, -50, -51, -54, -57, -58, -60,
  113554. -66, -66, -66, -64, -65, -68, -77, -82,
  113555. -87, -95, -110, -999, -999, -999, -999, -999}},
  113556. /* 500 Hz */
  113557. {{-999, -999, -999, -999, -999, -999, -999, -999,
  113558. -107, -102, -97, -92, -87, -83, -78, -75,
  113559. -82, -79, -83, -85, -89, -92, -95, -98,
  113560. -101, -105, -109, -113, -999, -999, -999, -999,
  113561. -999, -999, -999, -999, -999, -999, -999, -999,
  113562. -999, -999, -999, -999, -999, -999, -999, -999,
  113563. -999, -999, -999, -999, -999, -999, -999, -999},
  113564. {-999, -999, -999, -999, -999, -999, -999, -106,
  113565. -100, -95, -90, -86, -81, -78, -74, -69,
  113566. -74, -74, -76, -79, -83, -84, -86, -89,
  113567. -92, -97, -93, -100, -103, -107, -110, -999,
  113568. -999, -999, -999, -999, -999, -999, -999, -999,
  113569. -999, -999, -999, -999, -999, -999, -999, -999,
  113570. -999, -999, -999, -999, -999, -999, -999, -999},
  113571. {-999, -999, -999, -999, -999, -999, -106, -100,
  113572. -95, -90, -87, -83, -80, -75, -69, -60,
  113573. -66, -66, -68, -70, -74, -78, -79, -81,
  113574. -81, -83, -84, -87, -93, -96, -99, -103,
  113575. -107, -110, -999, -999, -999, -999, -999, -999,
  113576. -999, -999, -999, -999, -999, -999, -999, -999,
  113577. -999, -999, -999, -999, -999, -999, -999, -999},
  113578. {-999, -999, -999, -999, -999, -108, -103, -98,
  113579. -93, -89, -85, -82, -78, -71, -62, -55,
  113580. -58, -58, -54, -54, -55, -59, -61, -62,
  113581. -70, -66, -66, -67, -70, -72, -75, -78,
  113582. -84, -84, -84, -88, -91, -90, -95, -98,
  113583. -102, -103, -106, -110, -999, -999, -999, -999,
  113584. -999, -999, -999, -999, -999, -999, -999, -999},
  113585. {-999, -999, -999, -999, -108, -103, -98, -94,
  113586. -90, -87, -82, -79, -73, -67, -58, -47,
  113587. -50, -45, -41, -45, -48, -44, -44, -49,
  113588. -54, -51, -48, -47, -49, -50, -51, -57,
  113589. -58, -60, -63, -69, -70, -69, -71, -74,
  113590. -78, -82, -90, -95, -101, -105, -110, -999,
  113591. -999, -999, -999, -999, -999, -999, -999, -999},
  113592. {-999, -999, -999, -105, -101, -97, -93, -90,
  113593. -85, -80, -77, -72, -65, -56, -48, -37,
  113594. -40, -36, -34, -40, -50, -47, -38, -41,
  113595. -47, -38, -35, -39, -38, -43, -40, -45,
  113596. -50, -45, -44, -47, -50, -55, -48, -48,
  113597. -52, -66, -70, -76, -82, -90, -97, -105,
  113598. -110, -999, -999, -999, -999, -999, -999, -999}},
  113599. /* 707 Hz */
  113600. {{-999, -999, -999, -999, -999, -999, -999, -999,
  113601. -999, -108, -103, -98, -93, -86, -79, -76,
  113602. -83, -81, -85, -87, -89, -93, -98, -102,
  113603. -107, -112, -999, -999, -999, -999, -999, -999,
  113604. -999, -999, -999, -999, -999, -999, -999, -999,
  113605. -999, -999, -999, -999, -999, -999, -999, -999,
  113606. -999, -999, -999, -999, -999, -999, -999, -999},
  113607. {-999, -999, -999, -999, -999, -999, -999, -999,
  113608. -999, -108, -103, -98, -93, -86, -79, -71,
  113609. -77, -74, -77, -79, -81, -84, -85, -90,
  113610. -92, -93, -92, -98, -101, -108, -112, -999,
  113611. -999, -999, -999, -999, -999, -999, -999, -999,
  113612. -999, -999, -999, -999, -999, -999, -999, -999,
  113613. -999, -999, -999, -999, -999, -999, -999, -999},
  113614. {-999, -999, -999, -999, -999, -999, -999, -999,
  113615. -108, -103, -98, -93, -87, -78, -68, -65,
  113616. -66, -62, -65, -67, -70, -73, -75, -78,
  113617. -82, -82, -83, -84, -91, -93, -98, -102,
  113618. -106, -110, -999, -999, -999, -999, -999, -999,
  113619. -999, -999, -999, -999, -999, -999, -999, -999,
  113620. -999, -999, -999, -999, -999, -999, -999, -999},
  113621. {-999, -999, -999, -999, -999, -999, -999, -999,
  113622. -105, -100, -95, -90, -82, -74, -62, -57,
  113623. -58, -56, -51, -52, -52, -54, -54, -58,
  113624. -66, -59, -60, -63, -66, -69, -73, -79,
  113625. -83, -84, -80, -81, -81, -82, -88, -92,
  113626. -98, -105, -113, -999, -999, -999, -999, -999,
  113627. -999, -999, -999, -999, -999, -999, -999, -999},
  113628. {-999, -999, -999, -999, -999, -999, -999, -107,
  113629. -102, -97, -92, -84, -79, -69, -57, -47,
  113630. -52, -47, -44, -45, -50, -52, -42, -42,
  113631. -53, -43, -43, -48, -51, -56, -55, -52,
  113632. -57, -59, -61, -62, -67, -71, -78, -83,
  113633. -86, -94, -98, -103, -110, -999, -999, -999,
  113634. -999, -999, -999, -999, -999, -999, -999, -999},
  113635. {-999, -999, -999, -999, -999, -999, -105, -100,
  113636. -95, -90, -84, -78, -70, -61, -51, -41,
  113637. -40, -38, -40, -46, -52, -51, -41, -40,
  113638. -46, -40, -38, -38, -41, -46, -41, -46,
  113639. -47, -43, -43, -45, -41, -45, -56, -67,
  113640. -68, -83, -87, -90, -95, -102, -107, -113,
  113641. -999, -999, -999, -999, -999, -999, -999, -999}},
  113642. /* 1000 Hz */
  113643. {{-999, -999, -999, -999, -999, -999, -999, -999,
  113644. -999, -109, -105, -101, -96, -91, -84, -77,
  113645. -82, -82, -85, -89, -94, -100, -106, -110,
  113646. -999, -999, -999, -999, -999, -999, -999, -999,
  113647. -999, -999, -999, -999, -999, -999, -999, -999,
  113648. -999, -999, -999, -999, -999, -999, -999, -999,
  113649. -999, -999, -999, -999, -999, -999, -999, -999},
  113650. {-999, -999, -999, -999, -999, -999, -999, -999,
  113651. -999, -106, -103, -98, -92, -85, -80, -71,
  113652. -75, -72, -76, -80, -84, -86, -89, -93,
  113653. -100, -107, -113, -999, -999, -999, -999, -999,
  113654. -999, -999, -999, -999, -999, -999, -999, -999,
  113655. -999, -999, -999, -999, -999, -999, -999, -999,
  113656. -999, -999, -999, -999, -999, -999, -999, -999},
  113657. {-999, -999, -999, -999, -999, -999, -999, -107,
  113658. -104, -101, -97, -92, -88, -84, -80, -64,
  113659. -66, -63, -64, -66, -69, -73, -77, -83,
  113660. -83, -86, -91, -98, -104, -111, -999, -999,
  113661. -999, -999, -999, -999, -999, -999, -999, -999,
  113662. -999, -999, -999, -999, -999, -999, -999, -999,
  113663. -999, -999, -999, -999, -999, -999, -999, -999},
  113664. {-999, -999, -999, -999, -999, -999, -999, -107,
  113665. -104, -101, -97, -92, -90, -84, -74, -57,
  113666. -58, -52, -55, -54, -50, -52, -50, -52,
  113667. -63, -62, -69, -76, -77, -78, -78, -79,
  113668. -82, -88, -94, -100, -106, -111, -999, -999,
  113669. -999, -999, -999, -999, -999, -999, -999, -999,
  113670. -999, -999, -999, -999, -999, -999, -999, -999},
  113671. {-999, -999, -999, -999, -999, -999, -106, -102,
  113672. -98, -95, -90, -85, -83, -78, -70, -50,
  113673. -50, -41, -44, -49, -47, -50, -50, -44,
  113674. -55, -46, -47, -48, -48, -54, -49, -49,
  113675. -58, -62, -71, -81, -87, -92, -97, -102,
  113676. -108, -114, -999, -999, -999, -999, -999, -999,
  113677. -999, -999, -999, -999, -999, -999, -999, -999},
  113678. {-999, -999, -999, -999, -999, -999, -106, -102,
  113679. -98, -95, -90, -85, -83, -78, -70, -45,
  113680. -43, -41, -47, -50, -51, -50, -49, -45,
  113681. -47, -41, -44, -41, -39, -43, -38, -37,
  113682. -40, -41, -44, -50, -58, -65, -73, -79,
  113683. -85, -92, -97, -101, -105, -109, -113, -999,
  113684. -999, -999, -999, -999, -999, -999, -999, -999}},
  113685. /* 1414 Hz */
  113686. {{-999, -999, -999, -999, -999, -999, -999, -999,
  113687. -999, -999, -999, -107, -100, -95, -87, -81,
  113688. -85, -83, -88, -93, -100, -107, -114, -999,
  113689. -999, -999, -999, -999, -999, -999, -999, -999,
  113690. -999, -999, -999, -999, -999, -999, -999, -999,
  113691. -999, -999, -999, -999, -999, -999, -999, -999,
  113692. -999, -999, -999, -999, -999, -999, -999, -999},
  113693. {-999, -999, -999, -999, -999, -999, -999, -999,
  113694. -999, -999, -107, -101, -95, -88, -83, -76,
  113695. -73, -72, -79, -84, -90, -95, -100, -105,
  113696. -110, -115, -999, -999, -999, -999, -999, -999,
  113697. -999, -999, -999, -999, -999, -999, -999, -999,
  113698. -999, -999, -999, -999, -999, -999, -999, -999,
  113699. -999, -999, -999, -999, -999, -999, -999, -999},
  113700. {-999, -999, -999, -999, -999, -999, -999, -999,
  113701. -999, -999, -104, -98, -92, -87, -81, -70,
  113702. -65, -62, -67, -71, -74, -80, -85, -91,
  113703. -95, -99, -103, -108, -111, -114, -999, -999,
  113704. -999, -999, -999, -999, -999, -999, -999, -999,
  113705. -999, -999, -999, -999, -999, -999, -999, -999,
  113706. -999, -999, -999, -999, -999, -999, -999, -999},
  113707. {-999, -999, -999, -999, -999, -999, -999, -999,
  113708. -999, -999, -103, -97, -90, -85, -76, -60,
  113709. -56, -54, -60, -62, -61, -56, -63, -65,
  113710. -73, -74, -77, -75, -78, -81, -86, -87,
  113711. -88, -91, -94, -98, -103, -110, -999, -999,
  113712. -999, -999, -999, -999, -999, -999, -999, -999,
  113713. -999, -999, -999, -999, -999, -999, -999, -999},
  113714. {-999, -999, -999, -999, -999, -999, -999, -105,
  113715. -100, -97, -92, -86, -81, -79, -70, -57,
  113716. -51, -47, -51, -58, -60, -56, -53, -50,
  113717. -58, -52, -50, -50, -53, -55, -64, -69,
  113718. -71, -85, -82, -78, -81, -85, -95, -102,
  113719. -112, -999, -999, -999, -999, -999, -999, -999,
  113720. -999, -999, -999, -999, -999, -999, -999, -999},
  113721. {-999, -999, -999, -999, -999, -999, -999, -105,
  113722. -100, -97, -92, -85, -83, -79, -72, -49,
  113723. -40, -43, -43, -54, -56, -51, -50, -40,
  113724. -43, -38, -36, -35, -37, -38, -37, -44,
  113725. -54, -60, -57, -60, -70, -75, -84, -92,
  113726. -103, -112, -999, -999, -999, -999, -999, -999,
  113727. -999, -999, -999, -999, -999, -999, -999, -999}},
  113728. /* 2000 Hz */
  113729. {{-999, -999, -999, -999, -999, -999, -999, -999,
  113730. -999, -999, -999, -110, -102, -95, -89, -82,
  113731. -83, -84, -90, -92, -99, -107, -113, -999,
  113732. -999, -999, -999, -999, -999, -999, -999, -999,
  113733. -999, -999, -999, -999, -999, -999, -999, -999,
  113734. -999, -999, -999, -999, -999, -999, -999, -999,
  113735. -999, -999, -999, -999, -999, -999, -999, -999},
  113736. {-999, -999, -999, -999, -999, -999, -999, -999,
  113737. -999, -999, -107, -101, -95, -89, -83, -72,
  113738. -74, -78, -85, -88, -88, -90, -92, -98,
  113739. -105, -111, -999, -999, -999, -999, -999, -999,
  113740. -999, -999, -999, -999, -999, -999, -999, -999,
  113741. -999, -999, -999, -999, -999, -999, -999, -999,
  113742. -999, -999, -999, -999, -999, -999, -999, -999},
  113743. {-999, -999, -999, -999, -999, -999, -999, -999,
  113744. -999, -109, -103, -97, -93, -87, -81, -70,
  113745. -70, -67, -75, -73, -76, -79, -81, -83,
  113746. -88, -89, -97, -103, -110, -999, -999, -999,
  113747. -999, -999, -999, -999, -999, -999, -999, -999,
  113748. -999, -999, -999, -999, -999, -999, -999, -999,
  113749. -999, -999, -999, -999, -999, -999, -999, -999},
  113750. {-999, -999, -999, -999, -999, -999, -999, -999,
  113751. -999, -107, -100, -94, -88, -83, -75, -63,
  113752. -59, -59, -63, -66, -60, -62, -67, -67,
  113753. -77, -76, -81, -88, -86, -92, -96, -102,
  113754. -109, -116, -999, -999, -999, -999, -999, -999,
  113755. -999, -999, -999, -999, -999, -999, -999, -999,
  113756. -999, -999, -999, -999, -999, -999, -999, -999},
  113757. {-999, -999, -999, -999, -999, -999, -999, -999,
  113758. -999, -105, -98, -92, -86, -81, -73, -56,
  113759. -52, -47, -55, -60, -58, -52, -51, -45,
  113760. -49, -50, -53, -54, -61, -71, -70, -69,
  113761. -78, -79, -87, -90, -96, -104, -112, -999,
  113762. -999, -999, -999, -999, -999, -999, -999, -999,
  113763. -999, -999, -999, -999, -999, -999, -999, -999},
  113764. {-999, -999, -999, -999, -999, -999, -999, -999,
  113765. -999, -103, -96, -90, -86, -78, -70, -51,
  113766. -42, -47, -48, -55, -54, -54, -53, -42,
  113767. -35, -28, -33, -38, -37, -44, -47, -49,
  113768. -54, -63, -68, -78, -82, -89, -94, -99,
  113769. -104, -109, -114, -999, -999, -999, -999, -999,
  113770. -999, -999, -999, -999, -999, -999, -999, -999}},
  113771. /* 2828 Hz */
  113772. {{-999, -999, -999, -999, -999, -999, -999, -999,
  113773. -999, -999, -999, -999, -110, -100, -90, -79,
  113774. -85, -81, -82, -82, -89, -94, -99, -103,
  113775. -109, -115, -999, -999, -999, -999, -999, -999,
  113776. -999, -999, -999, -999, -999, -999, -999, -999,
  113777. -999, -999, -999, -999, -999, -999, -999, -999,
  113778. -999, -999, -999, -999, -999, -999, -999, -999},
  113779. {-999, -999, -999, -999, -999, -999, -999, -999,
  113780. -999, -999, -999, -999, -105, -97, -85, -72,
  113781. -74, -70, -70, -70, -76, -85, -91, -93,
  113782. -97, -103, -109, -115, -999, -999, -999, -999,
  113783. -999, -999, -999, -999, -999, -999, -999, -999,
  113784. -999, -999, -999, -999, -999, -999, -999, -999,
  113785. -999, -999, -999, -999, -999, -999, -999, -999},
  113786. {-999, -999, -999, -999, -999, -999, -999, -999,
  113787. -999, -999, -999, -999, -112, -93, -81, -68,
  113788. -62, -60, -60, -57, -63, -70, -77, -82,
  113789. -90, -93, -98, -104, -109, -113, -999, -999,
  113790. -999, -999, -999, -999, -999, -999, -999, -999,
  113791. -999, -999, -999, -999, -999, -999, -999, -999,
  113792. -999, -999, -999, -999, -999, -999, -999, -999},
  113793. {-999, -999, -999, -999, -999, -999, -999, -999,
  113794. -999, -999, -999, -113, -100, -93, -84, -63,
  113795. -58, -48, -53, -54, -52, -52, -57, -64,
  113796. -66, -76, -83, -81, -85, -85, -90, -95,
  113797. -98, -101, -103, -106, -108, -111, -999, -999,
  113798. -999, -999, -999, -999, -999, -999, -999, -999,
  113799. -999, -999, -999, -999, -999, -999, -999, -999},
  113800. {-999, -999, -999, -999, -999, -999, -999, -999,
  113801. -999, -999, -999, -105, -95, -86, -74, -53,
  113802. -50, -38, -43, -49, -43, -42, -39, -39,
  113803. -46, -52, -57, -56, -72, -69, -74, -81,
  113804. -87, -92, -94, -97, -99, -102, -105, -108,
  113805. -999, -999, -999, -999, -999, -999, -999, -999,
  113806. -999, -999, -999, -999, -999, -999, -999, -999},
  113807. {-999, -999, -999, -999, -999, -999, -999, -999,
  113808. -999, -999, -108, -99, -90, -76, -66, -45,
  113809. -43, -41, -44, -47, -43, -47, -40, -30,
  113810. -31, -31, -39, -33, -40, -41, -43, -53,
  113811. -59, -70, -73, -77, -79, -82, -84, -87,
  113812. -999, -999, -999, -999, -999, -999, -999, -999,
  113813. -999, -999, -999, -999, -999, -999, -999, -999}},
  113814. /* 4000 Hz */
  113815. {{-999, -999, -999, -999, -999, -999, -999, -999,
  113816. -999, -999, -999, -999, -999, -110, -91, -76,
  113817. -75, -85, -93, -98, -104, -110, -999, -999,
  113818. -999, -999, -999, -999, -999, -999, -999, -999,
  113819. -999, -999, -999, -999, -999, -999, -999, -999,
  113820. -999, -999, -999, -999, -999, -999, -999, -999,
  113821. -999, -999, -999, -999, -999, -999, -999, -999},
  113822. {-999, -999, -999, -999, -999, -999, -999, -999,
  113823. -999, -999, -999, -999, -999, -110, -91, -70,
  113824. -70, -75, -86, -89, -94, -98, -101, -106,
  113825. -110, -999, -999, -999, -999, -999, -999, -999,
  113826. -999, -999, -999, -999, -999, -999, -999, -999,
  113827. -999, -999, -999, -999, -999, -999, -999, -999,
  113828. -999, -999, -999, -999, -999, -999, -999, -999},
  113829. {-999, -999, -999, -999, -999, -999, -999, -999,
  113830. -999, -999, -999, -999, -110, -95, -80, -60,
  113831. -65, -64, -74, -83, -88, -91, -95, -99,
  113832. -103, -107, -110, -999, -999, -999, -999, -999,
  113833. -999, -999, -999, -999, -999, -999, -999, -999,
  113834. -999, -999, -999, -999, -999, -999, -999, -999,
  113835. -999, -999, -999, -999, -999, -999, -999, -999},
  113836. {-999, -999, -999, -999, -999, -999, -999, -999,
  113837. -999, -999, -999, -999, -110, -95, -80, -58,
  113838. -55, -49, -66, -68, -71, -78, -78, -80,
  113839. -88, -85, -89, -97, -100, -105, -110, -999,
  113840. -999, -999, -999, -999, -999, -999, -999, -999,
  113841. -999, -999, -999, -999, -999, -999, -999, -999,
  113842. -999, -999, -999, -999, -999, -999, -999, -999},
  113843. {-999, -999, -999, -999, -999, -999, -999, -999,
  113844. -999, -999, -999, -999, -110, -95, -80, -53,
  113845. -52, -41, -59, -59, -49, -58, -56, -63,
  113846. -86, -79, -90, -93, -98, -103, -107, -112,
  113847. -999, -999, -999, -999, -999, -999, -999, -999,
  113848. -999, -999, -999, -999, -999, -999, -999, -999,
  113849. -999, -999, -999, -999, -999, -999, -999, -999},
  113850. {-999, -999, -999, -999, -999, -999, -999, -999,
  113851. -999, -999, -999, -110, -97, -91, -73, -45,
  113852. -40, -33, -53, -61, -49, -54, -50, -50,
  113853. -60, -52, -67, -74, -81, -92, -96, -100,
  113854. -105, -110, -999, -999, -999, -999, -999, -999,
  113855. -999, -999, -999, -999, -999, -999, -999, -999,
  113856. -999, -999, -999, -999, -999, -999, -999, -999}},
  113857. /* 5657 Hz */
  113858. {{-999, -999, -999, -999, -999, -999, -999, -999,
  113859. -999, -999, -999, -113, -106, -99, -92, -77,
  113860. -80, -88, -97, -106, -115, -999, -999, -999,
  113861. -999, -999, -999, -999, -999, -999, -999, -999,
  113862. -999, -999, -999, -999, -999, -999, -999, -999,
  113863. -999, -999, -999, -999, -999, -999, -999, -999,
  113864. -999, -999, -999, -999, -999, -999, -999, -999},
  113865. {-999, -999, -999, -999, -999, -999, -999, -999,
  113866. -999, -999, -116, -109, -102, -95, -89, -74,
  113867. -72, -88, -87, -95, -102, -109, -116, -999,
  113868. -999, -999, -999, -999, -999, -999, -999, -999,
  113869. -999, -999, -999, -999, -999, -999, -999, -999,
  113870. -999, -999, -999, -999, -999, -999, -999, -999,
  113871. -999, -999, -999, -999, -999, -999, -999, -999},
  113872. {-999, -999, -999, -999, -999, -999, -999, -999,
  113873. -999, -999, -116, -109, -102, -95, -89, -75,
  113874. -66, -74, -77, -78, -86, -87, -90, -96,
  113875. -105, -115, -999, -999, -999, -999, -999, -999,
  113876. -999, -999, -999, -999, -999, -999, -999, -999,
  113877. -999, -999, -999, -999, -999, -999, -999, -999,
  113878. -999, -999, -999, -999, -999, -999, -999, -999},
  113879. {-999, -999, -999, -999, -999, -999, -999, -999,
  113880. -999, -999, -115, -108, -101, -94, -88, -66,
  113881. -56, -61, -70, -65, -78, -72, -83, -84,
  113882. -93, -98, -105, -110, -999, -999, -999, -999,
  113883. -999, -999, -999, -999, -999, -999, -999, -999,
  113884. -999, -999, -999, -999, -999, -999, -999, -999,
  113885. -999, -999, -999, -999, -999, -999, -999, -999},
  113886. {-999, -999, -999, -999, -999, -999, -999, -999,
  113887. -999, -999, -110, -105, -95, -89, -82, -57,
  113888. -52, -52, -59, -56, -59, -58, -69, -67,
  113889. -88, -82, -82, -89, -94, -100, -108, -999,
  113890. -999, -999, -999, -999, -999, -999, -999, -999,
  113891. -999, -999, -999, -999, -999, -999, -999, -999,
  113892. -999, -999, -999, -999, -999, -999, -999, -999},
  113893. {-999, -999, -999, -999, -999, -999, -999, -999,
  113894. -999, -110, -101, -96, -90, -83, -77, -54,
  113895. -43, -38, -50, -48, -52, -48, -42, -42,
  113896. -51, -52, -53, -59, -65, -71, -78, -85,
  113897. -95, -999, -999, -999, -999, -999, -999, -999,
  113898. -999, -999, -999, -999, -999, -999, -999, -999,
  113899. -999, -999, -999, -999, -999, -999, -999, -999}},
  113900. /* 8000 Hz */
  113901. {{-999, -999, -999, -999, -999, -999, -999, -999,
  113902. -999, -999, -999, -999, -120, -105, -86, -68,
  113903. -78, -79, -90, -100, -110, -999, -999, -999,
  113904. -999, -999, -999, -999, -999, -999, -999, -999,
  113905. -999, -999, -999, -999, -999, -999, -999, -999,
  113906. -999, -999, -999, -999, -999, -999, -999, -999,
  113907. -999, -999, -999, -999, -999, -999, -999, -999},
  113908. {-999, -999, -999, -999, -999, -999, -999, -999,
  113909. -999, -999, -999, -999, -120, -105, -86, -66,
  113910. -73, -77, -88, -96, -105, -115, -999, -999,
  113911. -999, -999, -999, -999, -999, -999, -999, -999,
  113912. -999, -999, -999, -999, -999, -999, -999, -999,
  113913. -999, -999, -999, -999, -999, -999, -999, -999,
  113914. -999, -999, -999, -999, -999, -999, -999, -999},
  113915. {-999, -999, -999, -999, -999, -999, -999, -999,
  113916. -999, -999, -999, -120, -105, -92, -80, -61,
  113917. -64, -68, -80, -87, -92, -100, -110, -999,
  113918. -999, -999, -999, -999, -999, -999, -999, -999,
  113919. -999, -999, -999, -999, -999, -999, -999, -999,
  113920. -999, -999, -999, -999, -999, -999, -999, -999,
  113921. -999, -999, -999, -999, -999, -999, -999, -999},
  113922. {-999, -999, -999, -999, -999, -999, -999, -999,
  113923. -999, -999, -999, -120, -104, -91, -79, -52,
  113924. -60, -54, -64, -69, -77, -80, -82, -84,
  113925. -85, -87, -88, -90, -999, -999, -999, -999,
  113926. -999, -999, -999, -999, -999, -999, -999, -999,
  113927. -999, -999, -999, -999, -999, -999, -999, -999,
  113928. -999, -999, -999, -999, -999, -999, -999, -999},
  113929. {-999, -999, -999, -999, -999, -999, -999, -999,
  113930. -999, -999, -999, -118, -100, -87, -77, -49,
  113931. -50, -44, -58, -61, -61, -67, -65, -62,
  113932. -62, -62, -65, -68, -999, -999, -999, -999,
  113933. -999, -999, -999, -999, -999, -999, -999, -999,
  113934. -999, -999, -999, -999, -999, -999, -999, -999,
  113935. -999, -999, -999, -999, -999, -999, -999, -999},
  113936. {-999, -999, -999, -999, -999, -999, -999, -999,
  113937. -999, -999, -999, -115, -98, -84, -62, -49,
  113938. -44, -38, -46, -49, -49, -46, -39, -37,
  113939. -39, -40, -42, -43, -999, -999, -999, -999,
  113940. -999, -999, -999, -999, -999, -999, -999, -999,
  113941. -999, -999, -999, -999, -999, -999, -999, -999,
  113942. -999, -999, -999, -999, -999, -999, -999, -999}},
  113943. /* 11314 Hz */
  113944. {{-999, -999, -999, -999, -999, -999, -999, -999,
  113945. -999, -999, -999, -999, -999, -110, -88, -74,
  113946. -77, -82, -82, -85, -90, -94, -99, -104,
  113947. -999, -999, -999, -999, -999, -999, -999, -999,
  113948. -999, -999, -999, -999, -999, -999, -999, -999,
  113949. -999, -999, -999, -999, -999, -999, -999, -999,
  113950. -999, -999, -999, -999, -999, -999, -999, -999},
  113951. {-999, -999, -999, -999, -999, -999, -999, -999,
  113952. -999, -999, -999, -999, -999, -110, -88, -66,
  113953. -70, -81, -80, -81, -84, -88, -91, -93,
  113954. -999, -999, -999, -999, -999, -999, -999, -999,
  113955. -999, -999, -999, -999, -999, -999, -999, -999,
  113956. -999, -999, -999, -999, -999, -999, -999, -999,
  113957. -999, -999, -999, -999, -999, -999, -999, -999},
  113958. {-999, -999, -999, -999, -999, -999, -999, -999,
  113959. -999, -999, -999, -999, -999, -110, -88, -61,
  113960. -63, -70, -71, -74, -77, -80, -83, -85,
  113961. -999, -999, -999, -999, -999, -999, -999, -999,
  113962. -999, -999, -999, -999, -999, -999, -999, -999,
  113963. -999, -999, -999, -999, -999, -999, -999, -999,
  113964. -999, -999, -999, -999, -999, -999, -999, -999},
  113965. {-999, -999, -999, -999, -999, -999, -999, -999,
  113966. -999, -999, -999, -999, -999, -110, -86, -62,
  113967. -63, -62, -62, -58, -52, -50, -50, -52,
  113968. -54, -999, -999, -999, -999, -999, -999, -999,
  113969. -999, -999, -999, -999, -999, -999, -999, -999,
  113970. -999, -999, -999, -999, -999, -999, -999, -999,
  113971. -999, -999, -999, -999, -999, -999, -999, -999},
  113972. {-999, -999, -999, -999, -999, -999, -999, -999,
  113973. -999, -999, -999, -999, -118, -108, -84, -53,
  113974. -50, -50, -50, -55, -47, -45, -40, -40,
  113975. -40, -999, -999, -999, -999, -999, -999, -999,
  113976. -999, -999, -999, -999, -999, -999, -999, -999,
  113977. -999, -999, -999, -999, -999, -999, -999, -999,
  113978. -999, -999, -999, -999, -999, -999, -999, -999},
  113979. {-999, -999, -999, -999, -999, -999, -999, -999,
  113980. -999, -999, -999, -999, -118, -100, -73, -43,
  113981. -37, -42, -43, -53, -38, -37, -35, -35,
  113982. -38, -999, -999, -999, -999, -999, -999, -999,
  113983. -999, -999, -999, -999, -999, -999, -999, -999,
  113984. -999, -999, -999, -999, -999, -999, -999, -999,
  113985. -999, -999, -999, -999, -999, -999, -999, -999}},
  113986. /* 16000 Hz */
  113987. {{-999, -999, -999, -999, -999, -999, -999, -999,
  113988. -999, -999, -999, -110, -100, -91, -84, -74,
  113989. -80, -80, -80, -80, -80, -999, -999, -999,
  113990. -999, -999, -999, -999, -999, -999, -999, -999,
  113991. -999, -999, -999, -999, -999, -999, -999, -999,
  113992. -999, -999, -999, -999, -999, -999, -999, -999,
  113993. -999, -999, -999, -999, -999, -999, -999, -999},
  113994. {-999, -999, -999, -999, -999, -999, -999, -999,
  113995. -999, -999, -999, -110, -100, -91, -84, -74,
  113996. -68, -68, -68, -68, -68, -999, -999, -999,
  113997. -999, -999, -999, -999, -999, -999, -999, -999,
  113998. -999, -999, -999, -999, -999, -999, -999, -999,
  113999. -999, -999, -999, -999, -999, -999, -999, -999,
  114000. -999, -999, -999, -999, -999, -999, -999, -999},
  114001. {-999, -999, -999, -999, -999, -999, -999, -999,
  114002. -999, -999, -999, -110, -100, -86, -78, -70,
  114003. -60, -45, -30, -21, -999, -999, -999, -999,
  114004. -999, -999, -999, -999, -999, -999, -999, -999,
  114005. -999, -999, -999, -999, -999, -999, -999, -999,
  114006. -999, -999, -999, -999, -999, -999, -999, -999,
  114007. -999, -999, -999, -999, -999, -999, -999, -999},
  114008. {-999, -999, -999, -999, -999, -999, -999, -999,
  114009. -999, -999, -999, -110, -100, -87, -78, -67,
  114010. -48, -38, -29, -21, -999, -999, -999, -999,
  114011. -999, -999, -999, -999, -999, -999, -999, -999,
  114012. -999, -999, -999, -999, -999, -999, -999, -999,
  114013. -999, -999, -999, -999, -999, -999, -999, -999,
  114014. -999, -999, -999, -999, -999, -999, -999, -999},
  114015. {-999, -999, -999, -999, -999, -999, -999, -999,
  114016. -999, -999, -999, -110, -100, -86, -69, -56,
  114017. -45, -35, -33, -29, -999, -999, -999, -999,
  114018. -999, -999, -999, -999, -999, -999, -999, -999,
  114019. -999, -999, -999, -999, -999, -999, -999, -999,
  114020. -999, -999, -999, -999, -999, -999, -999, -999,
  114021. -999, -999, -999, -999, -999, -999, -999, -999},
  114022. {-999, -999, -999, -999, -999, -999, -999, -999,
  114023. -999, -999, -999, -110, -100, -83, -71, -48,
  114024. -27, -38, -37, -34, -999, -999, -999, -999,
  114025. -999, -999, -999, -999, -999, -999, -999, -999,
  114026. -999, -999, -999, -999, -999, -999, -999, -999,
  114027. -999, -999, -999, -999, -999, -999, -999, -999,
  114028. -999, -999, -999, -999, -999, -999, -999, -999}}
  114029. };
  114030. #endif
  114031. /*** End of inlined file: masking.h ***/
  114032. #define NEGINF -9999.f
  114033. static double stereo_threshholds[]={0.0, .5, 1.0, 1.5, 2.5, 4.5, 8.5, 16.5, 9e10};
  114034. static double stereo_threshholds_limited[]={0.0, .5, 1.0, 1.5, 2.0, 2.5, 4.5, 8.5, 9e10};
  114035. vorbis_look_psy_global *_vp_global_look(vorbis_info *vi){
  114036. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  114037. vorbis_info_psy_global *gi=&ci->psy_g_param;
  114038. vorbis_look_psy_global *look=(vorbis_look_psy_global*)_ogg_calloc(1,sizeof(*look));
  114039. look->channels=vi->channels;
  114040. look->ampmax=-9999.;
  114041. look->gi=gi;
  114042. return(look);
  114043. }
  114044. void _vp_global_free(vorbis_look_psy_global *look){
  114045. if(look){
  114046. memset(look,0,sizeof(*look));
  114047. _ogg_free(look);
  114048. }
  114049. }
  114050. void _vi_gpsy_free(vorbis_info_psy_global *i){
  114051. if(i){
  114052. memset(i,0,sizeof(*i));
  114053. _ogg_free(i);
  114054. }
  114055. }
  114056. void _vi_psy_free(vorbis_info_psy *i){
  114057. if(i){
  114058. memset(i,0,sizeof(*i));
  114059. _ogg_free(i);
  114060. }
  114061. }
  114062. static void min_curve(float *c,
  114063. float *c2){
  114064. int i;
  114065. for(i=0;i<EHMER_MAX;i++)if(c2[i]<c[i])c[i]=c2[i];
  114066. }
  114067. static void max_curve(float *c,
  114068. float *c2){
  114069. int i;
  114070. for(i=0;i<EHMER_MAX;i++)if(c2[i]>c[i])c[i]=c2[i];
  114071. }
  114072. static void attenuate_curve(float *c,float att){
  114073. int i;
  114074. for(i=0;i<EHMER_MAX;i++)
  114075. c[i]+=att;
  114076. }
  114077. static float ***setup_tone_curves(float curveatt_dB[P_BANDS],float binHz,int n,
  114078. float center_boost, float center_decay_rate){
  114079. int i,j,k,m;
  114080. float ath[EHMER_MAX];
  114081. float workc[P_BANDS][P_LEVELS][EHMER_MAX];
  114082. float athc[P_LEVELS][EHMER_MAX];
  114083. float *brute_buffer=(float*) alloca(n*sizeof(*brute_buffer));
  114084. float ***ret=(float***) _ogg_malloc(sizeof(*ret)*P_BANDS);
  114085. memset(workc,0,sizeof(workc));
  114086. for(i=0;i<P_BANDS;i++){
  114087. /* we add back in the ATH to avoid low level curves falling off to
  114088. -infinity and unnecessarily cutting off high level curves in the
  114089. curve limiting (last step). */
  114090. /* A half-band's settings must be valid over the whole band, and
  114091. it's better to mask too little than too much */
  114092. int ath_offset=i*4;
  114093. for(j=0;j<EHMER_MAX;j++){
  114094. float min=999.;
  114095. for(k=0;k<4;k++)
  114096. if(j+k+ath_offset<MAX_ATH){
  114097. if(min>ATH[j+k+ath_offset])min=ATH[j+k+ath_offset];
  114098. }else{
  114099. if(min>ATH[MAX_ATH-1])min=ATH[MAX_ATH-1];
  114100. }
  114101. ath[j]=min;
  114102. }
  114103. /* copy curves into working space, replicate the 50dB curve to 30
  114104. and 40, replicate the 100dB curve to 110 */
  114105. for(j=0;j<6;j++)
  114106. memcpy(workc[i][j+2],tonemasks[i][j],EHMER_MAX*sizeof(*tonemasks[i][j]));
  114107. memcpy(workc[i][0],tonemasks[i][0],EHMER_MAX*sizeof(*tonemasks[i][0]));
  114108. memcpy(workc[i][1],tonemasks[i][0],EHMER_MAX*sizeof(*tonemasks[i][0]));
  114109. /* apply centered curve boost/decay */
  114110. for(j=0;j<P_LEVELS;j++){
  114111. for(k=0;k<EHMER_MAX;k++){
  114112. float adj=center_boost+abs(EHMER_OFFSET-k)*center_decay_rate;
  114113. if(adj<0. && center_boost>0)adj=0.;
  114114. if(adj>0. && center_boost<0)adj=0.;
  114115. workc[i][j][k]+=adj;
  114116. }
  114117. }
  114118. /* normalize curves so the driving amplitude is 0dB */
  114119. /* make temp curves with the ATH overlayed */
  114120. for(j=0;j<P_LEVELS;j++){
  114121. attenuate_curve(workc[i][j],curveatt_dB[i]+100.-(j<2?2:j)*10.-P_LEVEL_0);
  114122. memcpy(athc[j],ath,EHMER_MAX*sizeof(**athc));
  114123. attenuate_curve(athc[j],+100.-j*10.f-P_LEVEL_0);
  114124. max_curve(athc[j],workc[i][j]);
  114125. }
  114126. /* Now limit the louder curves.
  114127. the idea is this: We don't know what the playback attenuation
  114128. will be; 0dB SL moves every time the user twiddles the volume
  114129. knob. So that means we have to use a single 'most pessimal' curve
  114130. for all masking amplitudes, right? Wrong. The *loudest* sound
  114131. can be in (we assume) a range of ...+100dB] SL. However, sounds
  114132. 20dB down will be in a range ...+80], 40dB down is from ...+60],
  114133. etc... */
  114134. for(j=1;j<P_LEVELS;j++){
  114135. min_curve(athc[j],athc[j-1]);
  114136. min_curve(workc[i][j],athc[j]);
  114137. }
  114138. }
  114139. for(i=0;i<P_BANDS;i++){
  114140. int hi_curve,lo_curve,bin;
  114141. ret[i]=(float**)_ogg_malloc(sizeof(**ret)*P_LEVELS);
  114142. /* low frequency curves are measured with greater resolution than
  114143. the MDCT/FFT will actually give us; we want the curve applied
  114144. to the tone data to be pessimistic and thus apply the minimum
  114145. masking possible for a given bin. That means that a single bin
  114146. could span more than one octave and that the curve will be a
  114147. composite of multiple octaves. It also may mean that a single
  114148. bin may span > an eighth of an octave and that the eighth
  114149. octave values may also be composited. */
  114150. /* which octave curves will we be compositing? */
  114151. bin=floor(fromOC(i*.5)/binHz);
  114152. lo_curve= ceil(toOC(bin*binHz+1)*2);
  114153. hi_curve= floor(toOC((bin+1)*binHz)*2);
  114154. if(lo_curve>i)lo_curve=i;
  114155. if(lo_curve<0)lo_curve=0;
  114156. if(hi_curve>=P_BANDS)hi_curve=P_BANDS-1;
  114157. for(m=0;m<P_LEVELS;m++){
  114158. ret[i][m]=(float*)_ogg_malloc(sizeof(***ret)*(EHMER_MAX+2));
  114159. for(j=0;j<n;j++)brute_buffer[j]=999.;
  114160. /* render the curve into bins, then pull values back into curve.
  114161. The point is that any inherent subsampling aliasing results in
  114162. a safe minimum */
  114163. for(k=lo_curve;k<=hi_curve;k++){
  114164. int l=0;
  114165. for(j=0;j<EHMER_MAX;j++){
  114166. int lo_bin= fromOC(j*.125+k*.5-2.0625)/binHz;
  114167. int hi_bin= fromOC(j*.125+k*.5-1.9375)/binHz+1;
  114168. if(lo_bin<0)lo_bin=0;
  114169. if(lo_bin>n)lo_bin=n;
  114170. if(lo_bin<l)l=lo_bin;
  114171. if(hi_bin<0)hi_bin=0;
  114172. if(hi_bin>n)hi_bin=n;
  114173. for(;l<hi_bin && l<n;l++)
  114174. if(brute_buffer[l]>workc[k][m][j])
  114175. brute_buffer[l]=workc[k][m][j];
  114176. }
  114177. for(;l<n;l++)
  114178. if(brute_buffer[l]>workc[k][m][EHMER_MAX-1])
  114179. brute_buffer[l]=workc[k][m][EHMER_MAX-1];
  114180. }
  114181. /* be equally paranoid about being valid up to next half ocatve */
  114182. if(i+1<P_BANDS){
  114183. int l=0;
  114184. k=i+1;
  114185. for(j=0;j<EHMER_MAX;j++){
  114186. int lo_bin= fromOC(j*.125+i*.5-2.0625)/binHz;
  114187. int hi_bin= fromOC(j*.125+i*.5-1.9375)/binHz+1;
  114188. if(lo_bin<0)lo_bin=0;
  114189. if(lo_bin>n)lo_bin=n;
  114190. if(lo_bin<l)l=lo_bin;
  114191. if(hi_bin<0)hi_bin=0;
  114192. if(hi_bin>n)hi_bin=n;
  114193. for(;l<hi_bin && l<n;l++)
  114194. if(brute_buffer[l]>workc[k][m][j])
  114195. brute_buffer[l]=workc[k][m][j];
  114196. }
  114197. for(;l<n;l++)
  114198. if(brute_buffer[l]>workc[k][m][EHMER_MAX-1])
  114199. brute_buffer[l]=workc[k][m][EHMER_MAX-1];
  114200. }
  114201. for(j=0;j<EHMER_MAX;j++){
  114202. int bin=fromOC(j*.125+i*.5-2.)/binHz;
  114203. if(bin<0){
  114204. ret[i][m][j+2]=-999.;
  114205. }else{
  114206. if(bin>=n){
  114207. ret[i][m][j+2]=-999.;
  114208. }else{
  114209. ret[i][m][j+2]=brute_buffer[bin];
  114210. }
  114211. }
  114212. }
  114213. /* add fenceposts */
  114214. for(j=0;j<EHMER_OFFSET;j++)
  114215. if(ret[i][m][j+2]>-200.f)break;
  114216. ret[i][m][0]=j;
  114217. for(j=EHMER_MAX-1;j>EHMER_OFFSET+1;j--)
  114218. if(ret[i][m][j+2]>-200.f)
  114219. break;
  114220. ret[i][m][1]=j;
  114221. }
  114222. }
  114223. return(ret);
  114224. }
  114225. void _vp_psy_init(vorbis_look_psy *p,vorbis_info_psy *vi,
  114226. vorbis_info_psy_global *gi,int n,long rate){
  114227. long i,j,lo=-99,hi=1;
  114228. long maxoc;
  114229. memset(p,0,sizeof(*p));
  114230. p->eighth_octave_lines=gi->eighth_octave_lines;
  114231. p->shiftoc=rint(log(gi->eighth_octave_lines*8.f)/log(2.f))-1;
  114232. p->firstoc=toOC(.25f*rate*.5/n)*(1<<(p->shiftoc+1))-gi->eighth_octave_lines;
  114233. maxoc=toOC((n+.25f)*rate*.5/n)*(1<<(p->shiftoc+1))+.5f;
  114234. p->total_octave_lines=maxoc-p->firstoc+1;
  114235. p->ath=(float*)_ogg_malloc(n*sizeof(*p->ath));
  114236. p->octave=(long*)_ogg_malloc(n*sizeof(*p->octave));
  114237. p->bark=(long*)_ogg_malloc(n*sizeof(*p->bark));
  114238. p->vi=vi;
  114239. p->n=n;
  114240. p->rate=rate;
  114241. /* AoTuV HF weighting */
  114242. p->m_val = 1.;
  114243. if(rate < 26000) p->m_val = 0;
  114244. else if(rate < 38000) p->m_val = .94; /* 32kHz */
  114245. else if(rate > 46000) p->m_val = 1.275; /* 48kHz */
  114246. /* set up the lookups for a given blocksize and sample rate */
  114247. for(i=0,j=0;i<MAX_ATH-1;i++){
  114248. int endpos=rint(fromOC((i+1)*.125-2.)*2*n/rate);
  114249. float base=ATH[i];
  114250. if(j<endpos){
  114251. float delta=(ATH[i+1]-base)/(endpos-j);
  114252. for(;j<endpos && j<n;j++){
  114253. p->ath[j]=base+100.;
  114254. base+=delta;
  114255. }
  114256. }
  114257. }
  114258. for(i=0;i<n;i++){
  114259. float bark=toBARK(rate/(2*n)*i);
  114260. for(;lo+vi->noisewindowlomin<i &&
  114261. toBARK(rate/(2*n)*lo)<(bark-vi->noisewindowlo);lo++);
  114262. for(;hi<=n && (hi<i+vi->noisewindowhimin ||
  114263. toBARK(rate/(2*n)*hi)<(bark+vi->noisewindowhi));hi++);
  114264. p->bark[i]=((lo-1)<<16)+(hi-1);
  114265. }
  114266. for(i=0;i<n;i++)
  114267. p->octave[i]=toOC((i+.25f)*.5*rate/n)*(1<<(p->shiftoc+1))+.5f;
  114268. p->tonecurves=setup_tone_curves(vi->toneatt,rate*.5/n,n,
  114269. vi->tone_centerboost,vi->tone_decay);
  114270. /* set up rolling noise median */
  114271. p->noiseoffset=(float**)_ogg_malloc(P_NOISECURVES*sizeof(*p->noiseoffset));
  114272. for(i=0;i<P_NOISECURVES;i++)
  114273. p->noiseoffset[i]=(float*)_ogg_malloc(n*sizeof(**p->noiseoffset));
  114274. for(i=0;i<n;i++){
  114275. float halfoc=toOC((i+.5)*rate/(2.*n))*2.;
  114276. int inthalfoc;
  114277. float del;
  114278. if(halfoc<0)halfoc=0;
  114279. if(halfoc>=P_BANDS-1)halfoc=P_BANDS-1;
  114280. inthalfoc=(int)halfoc;
  114281. del=halfoc-inthalfoc;
  114282. for(j=0;j<P_NOISECURVES;j++)
  114283. p->noiseoffset[j][i]=
  114284. p->vi->noiseoff[j][inthalfoc]*(1.-del) +
  114285. p->vi->noiseoff[j][inthalfoc+1]*del;
  114286. }
  114287. #if 0
  114288. {
  114289. static int ls=0;
  114290. _analysis_output_always("noiseoff0",ls,p->noiseoffset[0],n,1,0,0);
  114291. _analysis_output_always("noiseoff1",ls,p->noiseoffset[1],n,1,0,0);
  114292. _analysis_output_always("noiseoff2",ls++,p->noiseoffset[2],n,1,0,0);
  114293. }
  114294. #endif
  114295. }
  114296. void _vp_psy_clear(vorbis_look_psy *p){
  114297. int i,j;
  114298. if(p){
  114299. if(p->ath)_ogg_free(p->ath);
  114300. if(p->octave)_ogg_free(p->octave);
  114301. if(p->bark)_ogg_free(p->bark);
  114302. if(p->tonecurves){
  114303. for(i=0;i<P_BANDS;i++){
  114304. for(j=0;j<P_LEVELS;j++){
  114305. _ogg_free(p->tonecurves[i][j]);
  114306. }
  114307. _ogg_free(p->tonecurves[i]);
  114308. }
  114309. _ogg_free(p->tonecurves);
  114310. }
  114311. if(p->noiseoffset){
  114312. for(i=0;i<P_NOISECURVES;i++){
  114313. _ogg_free(p->noiseoffset[i]);
  114314. }
  114315. _ogg_free(p->noiseoffset);
  114316. }
  114317. memset(p,0,sizeof(*p));
  114318. }
  114319. }
  114320. /* octave/(8*eighth_octave_lines) x scale and dB y scale */
  114321. static void seed_curve(float *seed,
  114322. const float **curves,
  114323. float amp,
  114324. int oc, int n,
  114325. int linesper,float dBoffset){
  114326. int i,post1;
  114327. int seedptr;
  114328. const float *posts,*curve;
  114329. int choice=(int)((amp+dBoffset-P_LEVEL_0)*.1f);
  114330. choice=max(choice,0);
  114331. choice=min(choice,P_LEVELS-1);
  114332. posts=curves[choice];
  114333. curve=posts+2;
  114334. post1=(int)posts[1];
  114335. seedptr=oc+(posts[0]-EHMER_OFFSET)*linesper-(linesper>>1);
  114336. for(i=posts[0];i<post1;i++){
  114337. if(seedptr>0){
  114338. float lin=amp+curve[i];
  114339. if(seed[seedptr]<lin)seed[seedptr]=lin;
  114340. }
  114341. seedptr+=linesper;
  114342. if(seedptr>=n)break;
  114343. }
  114344. }
  114345. static void seed_loop(vorbis_look_psy *p,
  114346. const float ***curves,
  114347. const float *f,
  114348. const float *flr,
  114349. float *seed,
  114350. float specmax){
  114351. vorbis_info_psy *vi=p->vi;
  114352. long n=p->n,i;
  114353. float dBoffset=vi->max_curve_dB-specmax;
  114354. /* prime the working vector with peak values */
  114355. for(i=0;i<n;i++){
  114356. float max=f[i];
  114357. long oc=p->octave[i];
  114358. while(i+1<n && p->octave[i+1]==oc){
  114359. i++;
  114360. if(f[i]>max)max=f[i];
  114361. }
  114362. if(max+6.f>flr[i]){
  114363. oc=oc>>p->shiftoc;
  114364. if(oc>=P_BANDS)oc=P_BANDS-1;
  114365. if(oc<0)oc=0;
  114366. seed_curve(seed,
  114367. curves[oc],
  114368. max,
  114369. p->octave[i]-p->firstoc,
  114370. p->total_octave_lines,
  114371. p->eighth_octave_lines,
  114372. dBoffset);
  114373. }
  114374. }
  114375. }
  114376. static void seed_chase(float *seeds, int linesper, long n){
  114377. long *posstack=(long*)alloca(n*sizeof(*posstack));
  114378. float *ampstack=(float*)alloca(n*sizeof(*ampstack));
  114379. long stack=0;
  114380. long pos=0;
  114381. long i;
  114382. for(i=0;i<n;i++){
  114383. if(stack<2){
  114384. posstack[stack]=i;
  114385. ampstack[stack++]=seeds[i];
  114386. }else{
  114387. while(1){
  114388. if(seeds[i]<ampstack[stack-1]){
  114389. posstack[stack]=i;
  114390. ampstack[stack++]=seeds[i];
  114391. break;
  114392. }else{
  114393. if(i<posstack[stack-1]+linesper){
  114394. if(stack>1 && ampstack[stack-1]<=ampstack[stack-2] &&
  114395. i<posstack[stack-2]+linesper){
  114396. /* we completely overlap, making stack-1 irrelevant. pop it */
  114397. stack--;
  114398. continue;
  114399. }
  114400. }
  114401. posstack[stack]=i;
  114402. ampstack[stack++]=seeds[i];
  114403. break;
  114404. }
  114405. }
  114406. }
  114407. }
  114408. /* the stack now contains only the positions that are relevant. Scan
  114409. 'em straight through */
  114410. for(i=0;i<stack;i++){
  114411. long endpos;
  114412. if(i<stack-1 && ampstack[i+1]>ampstack[i]){
  114413. endpos=posstack[i+1];
  114414. }else{
  114415. endpos=posstack[i]+linesper+1; /* +1 is important, else bin 0 is
  114416. discarded in short frames */
  114417. }
  114418. if(endpos>n)endpos=n;
  114419. for(;pos<endpos;pos++)
  114420. seeds[pos]=ampstack[i];
  114421. }
  114422. /* there. Linear time. I now remember this was on a problem set I
  114423. had in Grad Skool... I didn't solve it at the time ;-) */
  114424. }
  114425. /* bleaugh, this is more complicated than it needs to be */
  114426. #include<stdio.h>
  114427. static void max_seeds(vorbis_look_psy *p,
  114428. float *seed,
  114429. float *flr){
  114430. long n=p->total_octave_lines;
  114431. int linesper=p->eighth_octave_lines;
  114432. long linpos=0;
  114433. long pos;
  114434. seed_chase(seed,linesper,n); /* for masking */
  114435. pos=p->octave[0]-p->firstoc-(linesper>>1);
  114436. while(linpos+1<p->n){
  114437. float minV=seed[pos];
  114438. long end=((p->octave[linpos]+p->octave[linpos+1])>>1)-p->firstoc;
  114439. if(minV>p->vi->tone_abs_limit)minV=p->vi->tone_abs_limit;
  114440. while(pos+1<=end){
  114441. pos++;
  114442. if((seed[pos]>NEGINF && seed[pos]<minV) || minV==NEGINF)
  114443. minV=seed[pos];
  114444. }
  114445. end=pos+p->firstoc;
  114446. for(;linpos<p->n && p->octave[linpos]<=end;linpos++)
  114447. if(flr[linpos]<minV)flr[linpos]=minV;
  114448. }
  114449. {
  114450. float minV=seed[p->total_octave_lines-1];
  114451. for(;linpos<p->n;linpos++)
  114452. if(flr[linpos]<minV)flr[linpos]=minV;
  114453. }
  114454. }
  114455. static void bark_noise_hybridmp(int n,const long *b,
  114456. const float *f,
  114457. float *noise,
  114458. const float offset,
  114459. const int fixed){
  114460. float *N=(float*) alloca(n*sizeof(*N));
  114461. float *X=(float*) alloca(n*sizeof(*N));
  114462. float *XX=(float*) alloca(n*sizeof(*N));
  114463. float *Y=(float*) alloca(n*sizeof(*N));
  114464. float *XY=(float*) alloca(n*sizeof(*N));
  114465. float tN, tX, tXX, tY, tXY;
  114466. int i;
  114467. int lo, hi;
  114468. float R, A, B, D;
  114469. float w, x, y;
  114470. tN = tX = tXX = tY = tXY = 0.f;
  114471. y = f[0] + offset;
  114472. if (y < 1.f) y = 1.f;
  114473. w = y * y * .5;
  114474. tN += w;
  114475. tX += w;
  114476. tY += w * y;
  114477. N[0] = tN;
  114478. X[0] = tX;
  114479. XX[0] = tXX;
  114480. Y[0] = tY;
  114481. XY[0] = tXY;
  114482. for (i = 1, x = 1.f; i < n; i++, x += 1.f) {
  114483. y = f[i] + offset;
  114484. if (y < 1.f) y = 1.f;
  114485. w = y * y;
  114486. tN += w;
  114487. tX += w * x;
  114488. tXX += w * x * x;
  114489. tY += w * y;
  114490. tXY += w * x * y;
  114491. N[i] = tN;
  114492. X[i] = tX;
  114493. XX[i] = tXX;
  114494. Y[i] = tY;
  114495. XY[i] = tXY;
  114496. }
  114497. for (i = 0, x = 0.f;; i++, x += 1.f) {
  114498. lo = b[i] >> 16;
  114499. if( lo>=0 ) break;
  114500. hi = b[i] & 0xffff;
  114501. tN = N[hi] + N[-lo];
  114502. tX = X[hi] - X[-lo];
  114503. tXX = XX[hi] + XX[-lo];
  114504. tY = Y[hi] + Y[-lo];
  114505. tXY = XY[hi] - XY[-lo];
  114506. A = tY * tXX - tX * tXY;
  114507. B = tN * tXY - tX * tY;
  114508. D = tN * tXX - tX * tX;
  114509. R = (A + x * B) / D;
  114510. if (R < 0.f)
  114511. R = 0.f;
  114512. noise[i] = R - offset;
  114513. }
  114514. for ( ;; i++, x += 1.f) {
  114515. lo = b[i] >> 16;
  114516. hi = b[i] & 0xffff;
  114517. if(hi>=n)break;
  114518. tN = N[hi] - N[lo];
  114519. tX = X[hi] - X[lo];
  114520. tXX = XX[hi] - XX[lo];
  114521. tY = Y[hi] - Y[lo];
  114522. tXY = XY[hi] - XY[lo];
  114523. A = tY * tXX - tX * tXY;
  114524. B = tN * tXY - tX * tY;
  114525. D = tN * tXX - tX * tX;
  114526. R = (A + x * B) / D;
  114527. if (R < 0.f) R = 0.f;
  114528. noise[i] = R - offset;
  114529. }
  114530. for ( ; i < n; i++, x += 1.f) {
  114531. R = (A + x * B) / D;
  114532. if (R < 0.f) R = 0.f;
  114533. noise[i] = R - offset;
  114534. }
  114535. if (fixed <= 0) return;
  114536. for (i = 0, x = 0.f;; i++, x += 1.f) {
  114537. hi = i + fixed / 2;
  114538. lo = hi - fixed;
  114539. if(lo>=0)break;
  114540. tN = N[hi] + N[-lo];
  114541. tX = X[hi] - X[-lo];
  114542. tXX = XX[hi] + XX[-lo];
  114543. tY = Y[hi] + Y[-lo];
  114544. tXY = XY[hi] - XY[-lo];
  114545. A = tY * tXX - tX * tXY;
  114546. B = tN * tXY - tX * tY;
  114547. D = tN * tXX - tX * tX;
  114548. R = (A + x * B) / D;
  114549. if (R - offset < noise[i]) noise[i] = R - offset;
  114550. }
  114551. for ( ;; i++, x += 1.f) {
  114552. hi = i + fixed / 2;
  114553. lo = hi - fixed;
  114554. if(hi>=n)break;
  114555. tN = N[hi] - N[lo];
  114556. tX = X[hi] - X[lo];
  114557. tXX = XX[hi] - XX[lo];
  114558. tY = Y[hi] - Y[lo];
  114559. tXY = XY[hi] - XY[lo];
  114560. A = tY * tXX - tX * tXY;
  114561. B = tN * tXY - tX * tY;
  114562. D = tN * tXX - tX * tX;
  114563. R = (A + x * B) / D;
  114564. if (R - offset < noise[i]) noise[i] = R - offset;
  114565. }
  114566. for ( ; i < n; i++, x += 1.f) {
  114567. R = (A + x * B) / D;
  114568. if (R - offset < noise[i]) noise[i] = R - offset;
  114569. }
  114570. }
  114571. static float FLOOR1_fromdB_INV_LOOKUP[256]={
  114572. 0.F, 8.81683e+06F, 8.27882e+06F, 7.77365e+06F,
  114573. 7.29930e+06F, 6.85389e+06F, 6.43567e+06F, 6.04296e+06F,
  114574. 5.67422e+06F, 5.32798e+06F, 5.00286e+06F, 4.69759e+06F,
  114575. 4.41094e+06F, 4.14178e+06F, 3.88905e+06F, 3.65174e+06F,
  114576. 3.42891e+06F, 3.21968e+06F, 3.02321e+06F, 2.83873e+06F,
  114577. 2.66551e+06F, 2.50286e+06F, 2.35014e+06F, 2.20673e+06F,
  114578. 2.07208e+06F, 1.94564e+06F, 1.82692e+06F, 1.71544e+06F,
  114579. 1.61076e+06F, 1.51247e+06F, 1.42018e+06F, 1.33352e+06F,
  114580. 1.25215e+06F, 1.17574e+06F, 1.10400e+06F, 1.03663e+06F,
  114581. 973377.F, 913981.F, 858210.F, 805842.F,
  114582. 756669.F, 710497.F, 667142.F, 626433.F,
  114583. 588208.F, 552316.F, 518613.F, 486967.F,
  114584. 457252.F, 429351.F, 403152.F, 378551.F,
  114585. 355452.F, 333762.F, 313396.F, 294273.F,
  114586. 276316.F, 259455.F, 243623.F, 228757.F,
  114587. 214798.F, 201691.F, 189384.F, 177828.F,
  114588. 166977.F, 156788.F, 147221.F, 138237.F,
  114589. 129802.F, 121881.F, 114444.F, 107461.F,
  114590. 100903.F, 94746.3F, 88964.9F, 83536.2F,
  114591. 78438.8F, 73652.5F, 69158.2F, 64938.1F,
  114592. 60975.6F, 57254.9F, 53761.2F, 50480.6F,
  114593. 47400.3F, 44507.9F, 41792.0F, 39241.9F,
  114594. 36847.3F, 34598.9F, 32487.7F, 30505.3F,
  114595. 28643.8F, 26896.0F, 25254.8F, 23713.7F,
  114596. 22266.7F, 20908.0F, 19632.2F, 18434.2F,
  114597. 17309.4F, 16253.1F, 15261.4F, 14330.1F,
  114598. 13455.7F, 12634.6F, 11863.7F, 11139.7F,
  114599. 10460.0F, 9821.72F, 9222.39F, 8659.64F,
  114600. 8131.23F, 7635.06F, 7169.17F, 6731.70F,
  114601. 6320.93F, 5935.23F, 5573.06F, 5232.99F,
  114602. 4913.67F, 4613.84F, 4332.30F, 4067.94F,
  114603. 3819.72F, 3586.64F, 3367.78F, 3162.28F,
  114604. 2969.31F, 2788.13F, 2617.99F, 2458.24F,
  114605. 2308.24F, 2167.39F, 2035.14F, 1910.95F,
  114606. 1794.35F, 1684.85F, 1582.04F, 1485.51F,
  114607. 1394.86F, 1309.75F, 1229.83F, 1154.78F,
  114608. 1084.32F, 1018.15F, 956.024F, 897.687F,
  114609. 842.910F, 791.475F, 743.179F, 697.830F,
  114610. 655.249F, 615.265F, 577.722F, 542.469F,
  114611. 509.367F, 478.286F, 449.101F, 421.696F,
  114612. 395.964F, 371.803F, 349.115F, 327.812F,
  114613. 307.809F, 289.026F, 271.390F, 254.830F,
  114614. 239.280F, 224.679F, 210.969F, 198.096F,
  114615. 186.008F, 174.658F, 164.000F, 153.993F,
  114616. 144.596F, 135.773F, 127.488F, 119.708F,
  114617. 112.404F, 105.545F, 99.1046F, 93.0572F,
  114618. 87.3788F, 82.0469F, 77.0404F, 72.3394F,
  114619. 67.9252F, 63.7804F, 59.8885F, 56.2341F,
  114620. 52.8027F, 49.5807F, 46.5553F, 43.7144F,
  114621. 41.0470F, 38.5423F, 36.1904F, 33.9821F,
  114622. 31.9085F, 29.9614F, 28.1332F, 26.4165F,
  114623. 24.8045F, 23.2910F, 21.8697F, 20.5352F,
  114624. 19.2822F, 18.1056F, 17.0008F, 15.9634F,
  114625. 14.9893F, 14.0746F, 13.2158F, 12.4094F,
  114626. 11.6522F, 10.9411F, 10.2735F, 9.64662F,
  114627. 9.05798F, 8.50526F, 7.98626F, 7.49894F,
  114628. 7.04135F, 6.61169F, 6.20824F, 5.82941F,
  114629. 5.47370F, 5.13970F, 4.82607F, 4.53158F,
  114630. 4.25507F, 3.99542F, 3.75162F, 3.52269F,
  114631. 3.30774F, 3.10590F, 2.91638F, 2.73842F,
  114632. 2.57132F, 2.41442F, 2.26709F, 2.12875F,
  114633. 1.99885F, 1.87688F, 1.76236F, 1.65482F,
  114634. 1.55384F, 1.45902F, 1.36999F, 1.28640F,
  114635. 1.20790F, 1.13419F, 1.06499F, 1.F
  114636. };
  114637. void _vp_remove_floor(vorbis_look_psy *p,
  114638. float *mdct,
  114639. int *codedflr,
  114640. float *residue,
  114641. int sliding_lowpass){
  114642. int i,n=p->n;
  114643. if(sliding_lowpass>n)sliding_lowpass=n;
  114644. for(i=0;i<sliding_lowpass;i++){
  114645. residue[i]=
  114646. mdct[i]*FLOOR1_fromdB_INV_LOOKUP[codedflr[i]];
  114647. }
  114648. for(;i<n;i++)
  114649. residue[i]=0.;
  114650. }
  114651. void _vp_noisemask(vorbis_look_psy *p,
  114652. float *logmdct,
  114653. float *logmask){
  114654. int i,n=p->n;
  114655. float *work=(float*) alloca(n*sizeof(*work));
  114656. bark_noise_hybridmp(n,p->bark,logmdct,logmask,
  114657. 140.,-1);
  114658. for(i=0;i<n;i++)work[i]=logmdct[i]-logmask[i];
  114659. bark_noise_hybridmp(n,p->bark,work,logmask,0.,
  114660. p->vi->noisewindowfixed);
  114661. for(i=0;i<n;i++)work[i]=logmdct[i]-work[i];
  114662. #if 0
  114663. {
  114664. static int seq=0;
  114665. float work2[n];
  114666. for(i=0;i<n;i++){
  114667. work2[i]=logmask[i]+work[i];
  114668. }
  114669. if(seq&1)
  114670. _analysis_output("median2R",seq/2,work,n,1,0,0);
  114671. else
  114672. _analysis_output("median2L",seq/2,work,n,1,0,0);
  114673. if(seq&1)
  114674. _analysis_output("envelope2R",seq/2,work2,n,1,0,0);
  114675. else
  114676. _analysis_output("envelope2L",seq/2,work2,n,1,0,0);
  114677. seq++;
  114678. }
  114679. #endif
  114680. for(i=0;i<n;i++){
  114681. int dB=logmask[i]+.5;
  114682. if(dB>=NOISE_COMPAND_LEVELS)dB=NOISE_COMPAND_LEVELS-1;
  114683. if(dB<0)dB=0;
  114684. logmask[i]= work[i]+p->vi->noisecompand[dB];
  114685. }
  114686. }
  114687. void _vp_tonemask(vorbis_look_psy *p,
  114688. float *logfft,
  114689. float *logmask,
  114690. float global_specmax,
  114691. float local_specmax){
  114692. int i,n=p->n;
  114693. float *seed=(float*) alloca(sizeof(*seed)*p->total_octave_lines);
  114694. float att=local_specmax+p->vi->ath_adjatt;
  114695. for(i=0;i<p->total_octave_lines;i++)seed[i]=NEGINF;
  114696. /* set the ATH (floating below localmax, not global max by a
  114697. specified att) */
  114698. if(att<p->vi->ath_maxatt)att=p->vi->ath_maxatt;
  114699. for(i=0;i<n;i++)
  114700. logmask[i]=p->ath[i]+att;
  114701. /* tone masking */
  114702. seed_loop(p,(const float ***)p->tonecurves,logfft,logmask,seed,global_specmax);
  114703. max_seeds(p,seed,logmask);
  114704. }
  114705. void _vp_offset_and_mix(vorbis_look_psy *p,
  114706. float *noise,
  114707. float *tone,
  114708. int offset_select,
  114709. float *logmask,
  114710. float *mdct,
  114711. float *logmdct){
  114712. int i,n=p->n;
  114713. float de, coeffi, cx;/* AoTuV */
  114714. float toneatt=p->vi->tone_masteratt[offset_select];
  114715. cx = p->m_val;
  114716. for(i=0;i<n;i++){
  114717. float val= noise[i]+p->noiseoffset[offset_select][i];
  114718. if(val>p->vi->noisemaxsupp)val=p->vi->noisemaxsupp;
  114719. logmask[i]=max(val,tone[i]+toneatt);
  114720. /* AoTuV */
  114721. /** @ M1 **
  114722. The following codes improve a noise problem.
  114723. A fundamental idea uses the value of masking and carries out
  114724. the relative compensation of the MDCT.
  114725. However, this code is not perfect and all noise problems cannot be solved.
  114726. by Aoyumi @ 2004/04/18
  114727. */
  114728. if(offset_select == 1) {
  114729. coeffi = -17.2; /* coeffi is a -17.2dB threshold */
  114730. val = val - logmdct[i]; /* val == mdct line value relative to floor in dB */
  114731. if(val > coeffi){
  114732. /* mdct value is > -17.2 dB below floor */
  114733. de = 1.0-((val-coeffi)*0.005*cx);
  114734. /* pro-rated attenuation:
  114735. -0.00 dB boost if mdct value is -17.2dB (relative to floor)
  114736. -0.77 dB boost if mdct value is 0dB (relative to floor)
  114737. -1.64 dB boost if mdct value is +17.2dB (relative to floor)
  114738. etc... */
  114739. if(de < 0) de = 0.0001;
  114740. }else
  114741. /* mdct value is <= -17.2 dB below floor */
  114742. de = 1.0-((val-coeffi)*0.0003*cx);
  114743. /* pro-rated attenuation:
  114744. +0.00 dB atten if mdct value is -17.2dB (relative to floor)
  114745. +0.45 dB atten if mdct value is -34.4dB (relative to floor)
  114746. etc... */
  114747. mdct[i] *= de;
  114748. }
  114749. }
  114750. }
  114751. float _vp_ampmax_decay(float amp,vorbis_dsp_state *vd){
  114752. vorbis_info *vi=vd->vi;
  114753. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  114754. vorbis_info_psy_global *gi=&ci->psy_g_param;
  114755. int n=ci->blocksizes[vd->W]/2;
  114756. float secs=(float)n/vi->rate;
  114757. amp+=secs*gi->ampmax_att_per_sec;
  114758. if(amp<-9999)amp=-9999;
  114759. return(amp);
  114760. }
  114761. static void couple_lossless(float A, float B,
  114762. float *qA, float *qB){
  114763. int test1=fabs(*qA)>fabs(*qB);
  114764. test1-= fabs(*qA)<fabs(*qB);
  114765. if(!test1)test1=((fabs(A)>fabs(B))<<1)-1;
  114766. if(test1==1){
  114767. *qB=(*qA>0.f?*qA-*qB:*qB-*qA);
  114768. }else{
  114769. float temp=*qB;
  114770. *qB=(*qB>0.f?*qA-*qB:*qB-*qA);
  114771. *qA=temp;
  114772. }
  114773. if(*qB>fabs(*qA)*1.9999f){
  114774. *qB= -fabs(*qA)*2.f;
  114775. *qA= -*qA;
  114776. }
  114777. }
  114778. static float hypot_lookup[32]={
  114779. -0.009935, -0.011245, -0.012726, -0.014397,
  114780. -0.016282, -0.018407, -0.020800, -0.023494,
  114781. -0.026522, -0.029923, -0.033737, -0.038010,
  114782. -0.042787, -0.048121, -0.054064, -0.060671,
  114783. -0.068000, -0.076109, -0.085054, -0.094892,
  114784. -0.105675, -0.117451, -0.130260, -0.144134,
  114785. -0.159093, -0.175146, -0.192286, -0.210490,
  114786. -0.229718, -0.249913, -0.271001, -0.292893};
  114787. static void precomputed_couple_point(float premag,
  114788. int floorA,int floorB,
  114789. float *mag, float *ang){
  114790. int test=(floorA>floorB)-1;
  114791. int offset=31-abs(floorA-floorB);
  114792. float floormag=hypot_lookup[((offset<0)-1)&offset]+1.f;
  114793. floormag*=FLOOR1_fromdB_INV_LOOKUP[(floorB&test)|(floorA&(~test))];
  114794. *mag=premag*floormag;
  114795. *ang=0.f;
  114796. }
  114797. /* just like below, this is currently set up to only do
  114798. single-step-depth coupling. Otherwise, we'd have to do more
  114799. copying (which will be inevitable later) */
  114800. /* doing the real circular magnitude calculation is audibly superior
  114801. to (A+B)/sqrt(2) */
  114802. static float dipole_hypot(float a, float b){
  114803. if(a>0.){
  114804. if(b>0.)return sqrt(a*a+b*b);
  114805. if(a>-b)return sqrt(a*a-b*b);
  114806. return -sqrt(b*b-a*a);
  114807. }
  114808. if(b<0.)return -sqrt(a*a+b*b);
  114809. if(-a>b)return -sqrt(a*a-b*b);
  114810. return sqrt(b*b-a*a);
  114811. }
  114812. static float round_hypot(float a, float b){
  114813. if(a>0.){
  114814. if(b>0.)return sqrt(a*a+b*b);
  114815. if(a>-b)return sqrt(a*a+b*b);
  114816. return -sqrt(b*b+a*a);
  114817. }
  114818. if(b<0.)return -sqrt(a*a+b*b);
  114819. if(-a>b)return -sqrt(a*a+b*b);
  114820. return sqrt(b*b+a*a);
  114821. }
  114822. /* revert to round hypot for now */
  114823. float **_vp_quantize_couple_memo(vorbis_block *vb,
  114824. vorbis_info_psy_global *g,
  114825. vorbis_look_psy *p,
  114826. vorbis_info_mapping0 *vi,
  114827. float **mdct){
  114828. int i,j,n=p->n;
  114829. float **ret=(float**) _vorbis_block_alloc(vb,vi->coupling_steps*sizeof(*ret));
  114830. int limit=g->coupling_pointlimit[p->vi->blockflag][PACKETBLOBS/2];
  114831. for(i=0;i<vi->coupling_steps;i++){
  114832. float *mdctM=mdct[vi->coupling_mag[i]];
  114833. float *mdctA=mdct[vi->coupling_ang[i]];
  114834. ret[i]=(float*) _vorbis_block_alloc(vb,n*sizeof(**ret));
  114835. for(j=0;j<limit;j++)
  114836. ret[i][j]=dipole_hypot(mdctM[j],mdctA[j]);
  114837. for(;j<n;j++)
  114838. ret[i][j]=round_hypot(mdctM[j],mdctA[j]);
  114839. }
  114840. return(ret);
  114841. }
  114842. /* this is for per-channel noise normalization */
  114843. static int apsort(const void *a, const void *b){
  114844. float f1=fabs(**(float**)a);
  114845. float f2=fabs(**(float**)b);
  114846. return (f1<f2)-(f1>f2);
  114847. }
  114848. int **_vp_quantize_couple_sort(vorbis_block *vb,
  114849. vorbis_look_psy *p,
  114850. vorbis_info_mapping0 *vi,
  114851. float **mags){
  114852. if(p->vi->normal_point_p){
  114853. int i,j,k,n=p->n;
  114854. int **ret=(int**) _vorbis_block_alloc(vb,vi->coupling_steps*sizeof(*ret));
  114855. int partition=p->vi->normal_partition;
  114856. float **work=(float**) alloca(sizeof(*work)*partition);
  114857. for(i=0;i<vi->coupling_steps;i++){
  114858. ret[i]=(int*) _vorbis_block_alloc(vb,n*sizeof(**ret));
  114859. for(j=0;j<n;j+=partition){
  114860. for(k=0;k<partition;k++)work[k]=mags[i]+k+j;
  114861. qsort(work,partition,sizeof(*work),apsort);
  114862. for(k=0;k<partition;k++)ret[i][k+j]=work[k]-mags[i];
  114863. }
  114864. }
  114865. return(ret);
  114866. }
  114867. return(NULL);
  114868. }
  114869. void _vp_noise_normalize_sort(vorbis_look_psy *p,
  114870. float *magnitudes,int *sortedindex){
  114871. int i,j,n=p->n;
  114872. vorbis_info_psy *vi=p->vi;
  114873. int partition=vi->normal_partition;
  114874. float **work=(float**) alloca(sizeof(*work)*partition);
  114875. int start=vi->normal_start;
  114876. for(j=start;j<n;j+=partition){
  114877. if(j+partition>n)partition=n-j;
  114878. for(i=0;i<partition;i++)work[i]=magnitudes+i+j;
  114879. qsort(work,partition,sizeof(*work),apsort);
  114880. for(i=0;i<partition;i++){
  114881. sortedindex[i+j-start]=work[i]-magnitudes;
  114882. }
  114883. }
  114884. }
  114885. void _vp_noise_normalize(vorbis_look_psy *p,
  114886. float *in,float *out,int *sortedindex){
  114887. int flag=0,i,j=0,n=p->n;
  114888. vorbis_info_psy *vi=p->vi;
  114889. int partition=vi->normal_partition;
  114890. int start=vi->normal_start;
  114891. if(start>n)start=n;
  114892. if(vi->normal_channel_p){
  114893. for(;j<start;j++)
  114894. out[j]=rint(in[j]);
  114895. for(;j+partition<=n;j+=partition){
  114896. float acc=0.;
  114897. int k;
  114898. for(i=j;i<j+partition;i++)
  114899. acc+=in[i]*in[i];
  114900. for(i=0;i<partition;i++){
  114901. k=sortedindex[i+j-start];
  114902. if(in[k]*in[k]>=.25f){
  114903. out[k]=rint(in[k]);
  114904. acc-=in[k]*in[k];
  114905. flag=1;
  114906. }else{
  114907. if(acc<vi->normal_thresh)break;
  114908. out[k]=unitnorm(in[k]);
  114909. acc-=1.;
  114910. }
  114911. }
  114912. for(;i<partition;i++){
  114913. k=sortedindex[i+j-start];
  114914. out[k]=0.;
  114915. }
  114916. }
  114917. }
  114918. for(;j<n;j++)
  114919. out[j]=rint(in[j]);
  114920. }
  114921. void _vp_couple(int blobno,
  114922. vorbis_info_psy_global *g,
  114923. vorbis_look_psy *p,
  114924. vorbis_info_mapping0 *vi,
  114925. float **res,
  114926. float **mag_memo,
  114927. int **mag_sort,
  114928. int **ifloor,
  114929. int *nonzero,
  114930. int sliding_lowpass){
  114931. int i,j,k,n=p->n;
  114932. /* perform any requested channel coupling */
  114933. /* point stereo can only be used in a first stage (in this encoder)
  114934. because of the dependency on floor lookups */
  114935. for(i=0;i<vi->coupling_steps;i++){
  114936. /* once we're doing multistage coupling in which a channel goes
  114937. through more than one coupling step, the floor vector
  114938. magnitudes will also have to be recalculated an propogated
  114939. along with PCM. Right now, we're not (that will wait until 5.1
  114940. most likely), so the code isn't here yet. The memory management
  114941. here is all assuming single depth couplings anyway. */
  114942. /* make sure coupling a zero and a nonzero channel results in two
  114943. nonzero channels. */
  114944. if(nonzero[vi->coupling_mag[i]] ||
  114945. nonzero[vi->coupling_ang[i]]){
  114946. float *rM=res[vi->coupling_mag[i]];
  114947. float *rA=res[vi->coupling_ang[i]];
  114948. float *qM=rM+n;
  114949. float *qA=rA+n;
  114950. int *floorM=ifloor[vi->coupling_mag[i]];
  114951. int *floorA=ifloor[vi->coupling_ang[i]];
  114952. float prepoint=stereo_threshholds[g->coupling_prepointamp[blobno]];
  114953. float postpoint=stereo_threshholds[g->coupling_postpointamp[blobno]];
  114954. int partition=(p->vi->normal_point_p?p->vi->normal_partition:p->n);
  114955. int limit=g->coupling_pointlimit[p->vi->blockflag][blobno];
  114956. int pointlimit=limit;
  114957. nonzero[vi->coupling_mag[i]]=1;
  114958. nonzero[vi->coupling_ang[i]]=1;
  114959. /* The threshold of a stereo is changed with the size of n */
  114960. if(n > 1000)
  114961. postpoint=stereo_threshholds_limited[g->coupling_postpointamp[blobno]];
  114962. for(j=0;j<p->n;j+=partition){
  114963. float acc=0.f;
  114964. for(k=0;k<partition;k++){
  114965. int l=k+j;
  114966. if(l<sliding_lowpass){
  114967. if((l>=limit && fabs(rM[l])<postpoint && fabs(rA[l])<postpoint) ||
  114968. (fabs(rM[l])<prepoint && fabs(rA[l])<prepoint)){
  114969. precomputed_couple_point(mag_memo[i][l],
  114970. floorM[l],floorA[l],
  114971. qM+l,qA+l);
  114972. if(rint(qM[l])==0.f)acc+=qM[l]*qM[l];
  114973. }else{
  114974. couple_lossless(rM[l],rA[l],qM+l,qA+l);
  114975. }
  114976. }else{
  114977. qM[l]=0.;
  114978. qA[l]=0.;
  114979. }
  114980. }
  114981. if(p->vi->normal_point_p){
  114982. for(k=0;k<partition && acc>=p->vi->normal_thresh;k++){
  114983. int l=mag_sort[i][j+k];
  114984. if(l<sliding_lowpass && l>=pointlimit && rint(qM[l])==0.f){
  114985. qM[l]=unitnorm(qM[l]);
  114986. acc-=1.f;
  114987. }
  114988. }
  114989. }
  114990. }
  114991. }
  114992. }
  114993. }
  114994. /* AoTuV */
  114995. /** @ M2 **
  114996. The boost problem by the combination of noise normalization and point stereo is eased.
  114997. However, this is a temporary patch.
  114998. by Aoyumi @ 2004/04/18
  114999. */
  115000. void hf_reduction(vorbis_info_psy_global *g,
  115001. vorbis_look_psy *p,
  115002. vorbis_info_mapping0 *vi,
  115003. float **mdct){
  115004. int i,j,n=p->n, de=0.3*p->m_val;
  115005. int limit=g->coupling_pointlimit[p->vi->blockflag][PACKETBLOBS/2];
  115006. for(i=0; i<vi->coupling_steps; i++){
  115007. /* for(j=start; j<limit; j++){} // ???*/
  115008. for(j=limit; j<n; j++)
  115009. mdct[i][j] *= (1.0 - de*((float)(j-limit) / (float)(n-limit)));
  115010. }
  115011. }
  115012. #endif
  115013. /*** End of inlined file: psy.c ***/
  115014. /*** Start of inlined file: registry.c ***/
  115015. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  115016. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  115017. // tasks..
  115018. #if JUCE_MSVC
  115019. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  115020. #endif
  115021. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  115022. #if JUCE_USE_OGGVORBIS
  115023. /* seems like major overkill now; the backend numbers will grow into
  115024. the infrastructure soon enough */
  115025. extern vorbis_func_floor floor0_exportbundle;
  115026. extern vorbis_func_floor floor1_exportbundle;
  115027. extern vorbis_func_residue residue0_exportbundle;
  115028. extern vorbis_func_residue residue1_exportbundle;
  115029. extern vorbis_func_residue residue2_exportbundle;
  115030. extern vorbis_func_mapping mapping0_exportbundle;
  115031. vorbis_func_floor *_floor_P[]={
  115032. &floor0_exportbundle,
  115033. &floor1_exportbundle,
  115034. };
  115035. vorbis_func_residue *_residue_P[]={
  115036. &residue0_exportbundle,
  115037. &residue1_exportbundle,
  115038. &residue2_exportbundle,
  115039. };
  115040. vorbis_func_mapping *_mapping_P[]={
  115041. &mapping0_exportbundle,
  115042. };
  115043. #endif
  115044. /*** End of inlined file: registry.c ***/
  115045. /*** Start of inlined file: res0.c ***/
  115046. /* Slow, slow, slow, simpleminded and did I mention it was slow? The
  115047. encode/decode loops are coded for clarity and performance is not
  115048. yet even a nagging little idea lurking in the shadows. Oh and BTW,
  115049. it's slow. */
  115050. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  115051. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  115052. // tasks..
  115053. #if JUCE_MSVC
  115054. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  115055. #endif
  115056. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  115057. #if JUCE_USE_OGGVORBIS
  115058. #include <stdlib.h>
  115059. #include <string.h>
  115060. #include <math.h>
  115061. #if defined(TRAIN_RES) || defined (TRAIN_RESAUX)
  115062. #include <stdio.h>
  115063. #endif
  115064. typedef struct {
  115065. vorbis_info_residue0 *info;
  115066. int parts;
  115067. int stages;
  115068. codebook *fullbooks;
  115069. codebook *phrasebook;
  115070. codebook ***partbooks;
  115071. int partvals;
  115072. int **decodemap;
  115073. long postbits;
  115074. long phrasebits;
  115075. long frames;
  115076. #if defined(TRAIN_RES) || defined(TRAIN_RESAUX)
  115077. int train_seq;
  115078. long *training_data[8][64];
  115079. float training_max[8][64];
  115080. float training_min[8][64];
  115081. float tmin;
  115082. float tmax;
  115083. #endif
  115084. } vorbis_look_residue0;
  115085. void res0_free_info(vorbis_info_residue *i){
  115086. vorbis_info_residue0 *info=(vorbis_info_residue0 *)i;
  115087. if(info){
  115088. memset(info,0,sizeof(*info));
  115089. _ogg_free(info);
  115090. }
  115091. }
  115092. void res0_free_look(vorbis_look_residue *i){
  115093. int j;
  115094. if(i){
  115095. vorbis_look_residue0 *look=(vorbis_look_residue0 *)i;
  115096. #ifdef TRAIN_RES
  115097. {
  115098. int j,k,l;
  115099. for(j=0;j<look->parts;j++){
  115100. /*fprintf(stderr,"partition %d: ",j);*/
  115101. for(k=0;k<8;k++)
  115102. if(look->training_data[k][j]){
  115103. char buffer[80];
  115104. FILE *of;
  115105. codebook *statebook=look->partbooks[j][k];
  115106. /* long and short into the same bucket by current convention */
  115107. sprintf(buffer,"res_part%d_pass%d.vqd",j,k);
  115108. of=fopen(buffer,"a");
  115109. for(l=0;l<statebook->entries;l++)
  115110. fprintf(of,"%d:%ld\n",l,look->training_data[k][j][l]);
  115111. fclose(of);
  115112. /*fprintf(stderr,"%d(%.2f|%.2f) ",k,
  115113. look->training_min[k][j],look->training_max[k][j]);*/
  115114. _ogg_free(look->training_data[k][j]);
  115115. look->training_data[k][j]=NULL;
  115116. }
  115117. /*fprintf(stderr,"\n");*/
  115118. }
  115119. }
  115120. fprintf(stderr,"min/max residue: %g::%g\n",look->tmin,look->tmax);
  115121. /*fprintf(stderr,"residue bit usage %f:%f (%f total)\n",
  115122. (float)look->phrasebits/look->frames,
  115123. (float)look->postbits/look->frames,
  115124. (float)(look->postbits+look->phrasebits)/look->frames);*/
  115125. #endif
  115126. /*vorbis_info_residue0 *info=look->info;
  115127. fprintf(stderr,
  115128. "%ld frames encoded in %ld phrasebits and %ld residue bits "
  115129. "(%g/frame) \n",look->frames,look->phrasebits,
  115130. look->resbitsflat,
  115131. (look->phrasebits+look->resbitsflat)/(float)look->frames);
  115132. for(j=0;j<look->parts;j++){
  115133. long acc=0;
  115134. fprintf(stderr,"\t[%d] == ",j);
  115135. for(k=0;k<look->stages;k++)
  115136. if((info->secondstages[j]>>k)&1){
  115137. fprintf(stderr,"%ld,",look->resbits[j][k]);
  115138. acc+=look->resbits[j][k];
  115139. }
  115140. fprintf(stderr,":: (%ld vals) %1.2fbits/sample\n",look->resvals[j],
  115141. acc?(float)acc/(look->resvals[j]*info->grouping):0);
  115142. }
  115143. fprintf(stderr,"\n");*/
  115144. for(j=0;j<look->parts;j++)
  115145. if(look->partbooks[j])_ogg_free(look->partbooks[j]);
  115146. _ogg_free(look->partbooks);
  115147. for(j=0;j<look->partvals;j++)
  115148. _ogg_free(look->decodemap[j]);
  115149. _ogg_free(look->decodemap);
  115150. memset(look,0,sizeof(*look));
  115151. _ogg_free(look);
  115152. }
  115153. }
  115154. static int icount(unsigned int v){
  115155. int ret=0;
  115156. while(v){
  115157. ret+=v&1;
  115158. v>>=1;
  115159. }
  115160. return(ret);
  115161. }
  115162. void res0_pack(vorbis_info_residue *vr,oggpack_buffer *opb){
  115163. vorbis_info_residue0 *info=(vorbis_info_residue0 *)vr;
  115164. int j,acc=0;
  115165. oggpack_write(opb,info->begin,24);
  115166. oggpack_write(opb,info->end,24);
  115167. oggpack_write(opb,info->grouping-1,24); /* residue vectors to group and
  115168. code with a partitioned book */
  115169. oggpack_write(opb,info->partitions-1,6); /* possible partition choices */
  115170. oggpack_write(opb,info->groupbook,8); /* group huffman book */
  115171. /* secondstages is a bitmask; as encoding progresses pass by pass, a
  115172. bitmask of one indicates this partition class has bits to write
  115173. this pass */
  115174. for(j=0;j<info->partitions;j++){
  115175. if(ilog(info->secondstages[j])>3){
  115176. /* yes, this is a minor hack due to not thinking ahead */
  115177. oggpack_write(opb,info->secondstages[j],3);
  115178. oggpack_write(opb,1,1);
  115179. oggpack_write(opb,info->secondstages[j]>>3,5);
  115180. }else
  115181. oggpack_write(opb,info->secondstages[j],4); /* trailing zero */
  115182. acc+=icount(info->secondstages[j]);
  115183. }
  115184. for(j=0;j<acc;j++)
  115185. oggpack_write(opb,info->booklist[j],8);
  115186. }
  115187. /* vorbis_info is for range checking */
  115188. vorbis_info_residue *res0_unpack(vorbis_info *vi,oggpack_buffer *opb){
  115189. int j,acc=0;
  115190. vorbis_info_residue0 *info=(vorbis_info_residue0*) _ogg_calloc(1,sizeof(*info));
  115191. codec_setup_info *ci=(codec_setup_info*) vi->codec_setup;
  115192. info->begin=oggpack_read(opb,24);
  115193. info->end=oggpack_read(opb,24);
  115194. info->grouping=oggpack_read(opb,24)+1;
  115195. info->partitions=oggpack_read(opb,6)+1;
  115196. info->groupbook=oggpack_read(opb,8);
  115197. for(j=0;j<info->partitions;j++){
  115198. int cascade=oggpack_read(opb,3);
  115199. if(oggpack_read(opb,1))
  115200. cascade|=(oggpack_read(opb,5)<<3);
  115201. info->secondstages[j]=cascade;
  115202. acc+=icount(cascade);
  115203. }
  115204. for(j=0;j<acc;j++)
  115205. info->booklist[j]=oggpack_read(opb,8);
  115206. if(info->groupbook>=ci->books)goto errout;
  115207. for(j=0;j<acc;j++)
  115208. if(info->booklist[j]>=ci->books)goto errout;
  115209. return(info);
  115210. errout:
  115211. res0_free_info(info);
  115212. return(NULL);
  115213. }
  115214. vorbis_look_residue *res0_look(vorbis_dsp_state *vd,
  115215. vorbis_info_residue *vr){
  115216. vorbis_info_residue0 *info=(vorbis_info_residue0 *)vr;
  115217. vorbis_look_residue0 *look=(vorbis_look_residue0 *)_ogg_calloc(1,sizeof(*look));
  115218. codec_setup_info *ci=(codec_setup_info*)vd->vi->codec_setup;
  115219. int j,k,acc=0;
  115220. int dim;
  115221. int maxstage=0;
  115222. look->info=info;
  115223. look->parts=info->partitions;
  115224. look->fullbooks=ci->fullbooks;
  115225. look->phrasebook=ci->fullbooks+info->groupbook;
  115226. dim=look->phrasebook->dim;
  115227. look->partbooks=(codebook***)_ogg_calloc(look->parts,sizeof(*look->partbooks));
  115228. for(j=0;j<look->parts;j++){
  115229. int stages=ilog(info->secondstages[j]);
  115230. if(stages){
  115231. if(stages>maxstage)maxstage=stages;
  115232. look->partbooks[j]=(codebook**) _ogg_calloc(stages,sizeof(*look->partbooks[j]));
  115233. for(k=0;k<stages;k++)
  115234. if(info->secondstages[j]&(1<<k)){
  115235. look->partbooks[j][k]=ci->fullbooks+info->booklist[acc++];
  115236. #ifdef TRAIN_RES
  115237. look->training_data[k][j]=_ogg_calloc(look->partbooks[j][k]->entries,
  115238. sizeof(***look->training_data));
  115239. #endif
  115240. }
  115241. }
  115242. }
  115243. look->partvals=rint(pow((float)look->parts,(float)dim));
  115244. look->stages=maxstage;
  115245. look->decodemap=(int**)_ogg_malloc(look->partvals*sizeof(*look->decodemap));
  115246. for(j=0;j<look->partvals;j++){
  115247. long val=j;
  115248. long mult=look->partvals/look->parts;
  115249. look->decodemap[j]=(int*)_ogg_malloc(dim*sizeof(*look->decodemap[j]));
  115250. for(k=0;k<dim;k++){
  115251. long deco=val/mult;
  115252. val-=deco*mult;
  115253. mult/=look->parts;
  115254. look->decodemap[j][k]=deco;
  115255. }
  115256. }
  115257. #if defined(TRAIN_RES) || defined (TRAIN_RESAUX)
  115258. {
  115259. static int train_seq=0;
  115260. look->train_seq=train_seq++;
  115261. }
  115262. #endif
  115263. return(look);
  115264. }
  115265. /* break an abstraction and copy some code for performance purposes */
  115266. static int local_book_besterror(codebook *book,float *a){
  115267. int dim=book->dim,i,k,o;
  115268. int best=0;
  115269. encode_aux_threshmatch *tt=book->c->thresh_tree;
  115270. /* find the quant val of each scalar */
  115271. for(k=0,o=dim;k<dim;++k){
  115272. float val=a[--o];
  115273. i=tt->threshvals>>1;
  115274. if(val<tt->quantthresh[i]){
  115275. if(val<tt->quantthresh[i-1]){
  115276. for(--i;i>0;--i)
  115277. if(val>=tt->quantthresh[i-1])
  115278. break;
  115279. }
  115280. }else{
  115281. for(++i;i<tt->threshvals-1;++i)
  115282. if(val<tt->quantthresh[i])break;
  115283. }
  115284. best=(best*tt->quantvals)+tt->quantmap[i];
  115285. }
  115286. /* regular lattices are easy :-) */
  115287. if(book->c->lengthlist[best]<=0){
  115288. const static_codebook *c=book->c;
  115289. int i,j;
  115290. float bestf=0.f;
  115291. float *e=book->valuelist;
  115292. best=-1;
  115293. for(i=0;i<book->entries;i++){
  115294. if(c->lengthlist[i]>0){
  115295. float thisx=0.f;
  115296. for(j=0;j<dim;j++){
  115297. float val=(e[j]-a[j]);
  115298. thisx+=val*val;
  115299. }
  115300. if(best==-1 || thisx<bestf){
  115301. bestf=thisx;
  115302. best=i;
  115303. }
  115304. }
  115305. e+=dim;
  115306. }
  115307. }
  115308. {
  115309. float *ptr=book->valuelist+best*dim;
  115310. for(i=0;i<dim;i++)
  115311. *a++ -= *ptr++;
  115312. }
  115313. return(best);
  115314. }
  115315. static int _encodepart(oggpack_buffer *opb,float *vec, int n,
  115316. codebook *book,long *acc){
  115317. int i,bits=0;
  115318. int dim=book->dim;
  115319. int step=n/dim;
  115320. for(i=0;i<step;i++){
  115321. int entry=local_book_besterror(book,vec+i*dim);
  115322. #ifdef TRAIN_RES
  115323. acc[entry]++;
  115324. #endif
  115325. bits+=vorbis_book_encode(book,entry,opb);
  115326. }
  115327. return(bits);
  115328. }
  115329. static long **_01class(vorbis_block *vb,vorbis_look_residue *vl,
  115330. float **in,int ch){
  115331. long i,j,k;
  115332. vorbis_look_residue0 *look=(vorbis_look_residue0 *)vl;
  115333. vorbis_info_residue0 *info=look->info;
  115334. /* move all this setup out later */
  115335. int samples_per_partition=info->grouping;
  115336. int possible_partitions=info->partitions;
  115337. int n=info->end-info->begin;
  115338. int partvals=n/samples_per_partition;
  115339. long **partword=(long**)_vorbis_block_alloc(vb,ch*sizeof(*partword));
  115340. float scale=100./samples_per_partition;
  115341. /* we find the partition type for each partition of each
  115342. channel. We'll go back and do the interleaved encoding in a
  115343. bit. For now, clarity */
  115344. for(i=0;i<ch;i++){
  115345. partword[i]=(long*)_vorbis_block_alloc(vb,n/samples_per_partition*sizeof(*partword[i]));
  115346. memset(partword[i],0,n/samples_per_partition*sizeof(*partword[i]));
  115347. }
  115348. for(i=0;i<partvals;i++){
  115349. int offset=i*samples_per_partition+info->begin;
  115350. for(j=0;j<ch;j++){
  115351. float max=0.;
  115352. float ent=0.;
  115353. for(k=0;k<samples_per_partition;k++){
  115354. if(fabs(in[j][offset+k])>max)max=fabs(in[j][offset+k]);
  115355. ent+=fabs(rint(in[j][offset+k]));
  115356. }
  115357. ent*=scale;
  115358. for(k=0;k<possible_partitions-1;k++)
  115359. if(max<=info->classmetric1[k] &&
  115360. (info->classmetric2[k]<0 || (int)ent<info->classmetric2[k]))
  115361. break;
  115362. partword[j][i]=k;
  115363. }
  115364. }
  115365. #ifdef TRAIN_RESAUX
  115366. {
  115367. FILE *of;
  115368. char buffer[80];
  115369. for(i=0;i<ch;i++){
  115370. sprintf(buffer,"resaux_%d.vqd",look->train_seq);
  115371. of=fopen(buffer,"a");
  115372. for(j=0;j<partvals;j++)
  115373. fprintf(of,"%ld, ",partword[i][j]);
  115374. fprintf(of,"\n");
  115375. fclose(of);
  115376. }
  115377. }
  115378. #endif
  115379. look->frames++;
  115380. return(partword);
  115381. }
  115382. /* designed for stereo or other modes where the partition size is an
  115383. integer multiple of the number of channels encoded in the current
  115384. submap */
  115385. static long **_2class(vorbis_block *vb,vorbis_look_residue *vl,float **in,
  115386. int ch){
  115387. long i,j,k,l;
  115388. vorbis_look_residue0 *look=(vorbis_look_residue0 *)vl;
  115389. vorbis_info_residue0 *info=look->info;
  115390. /* move all this setup out later */
  115391. int samples_per_partition=info->grouping;
  115392. int possible_partitions=info->partitions;
  115393. int n=info->end-info->begin;
  115394. int partvals=n/samples_per_partition;
  115395. long **partword=(long**)_vorbis_block_alloc(vb,sizeof(*partword));
  115396. #if defined(TRAIN_RES) || defined (TRAIN_RESAUX)
  115397. FILE *of;
  115398. char buffer[80];
  115399. #endif
  115400. partword[0]=(long*)_vorbis_block_alloc(vb,n*ch/samples_per_partition*sizeof(*partword[0]));
  115401. memset(partword[0],0,n*ch/samples_per_partition*sizeof(*partword[0]));
  115402. for(i=0,l=info->begin/ch;i<partvals;i++){
  115403. float magmax=0.f;
  115404. float angmax=0.f;
  115405. for(j=0;j<samples_per_partition;j+=ch){
  115406. if(fabs(in[0][l])>magmax)magmax=fabs(in[0][l]);
  115407. for(k=1;k<ch;k++)
  115408. if(fabs(in[k][l])>angmax)angmax=fabs(in[k][l]);
  115409. l++;
  115410. }
  115411. for(j=0;j<possible_partitions-1;j++)
  115412. if(magmax<=info->classmetric1[j] &&
  115413. angmax<=info->classmetric2[j])
  115414. break;
  115415. partword[0][i]=j;
  115416. }
  115417. #ifdef TRAIN_RESAUX
  115418. sprintf(buffer,"resaux_%d.vqd",look->train_seq);
  115419. of=fopen(buffer,"a");
  115420. for(i=0;i<partvals;i++)
  115421. fprintf(of,"%ld, ",partword[0][i]);
  115422. fprintf(of,"\n");
  115423. fclose(of);
  115424. #endif
  115425. look->frames++;
  115426. return(partword);
  115427. }
  115428. static int _01forward(oggpack_buffer *opb,
  115429. vorbis_block *vb,vorbis_look_residue *vl,
  115430. float **in,int ch,
  115431. long **partword,
  115432. int (*encode)(oggpack_buffer *,float *,int,
  115433. codebook *,long *)){
  115434. long i,j,k,s;
  115435. vorbis_look_residue0 *look=(vorbis_look_residue0 *)vl;
  115436. vorbis_info_residue0 *info=look->info;
  115437. /* move all this setup out later */
  115438. int samples_per_partition=info->grouping;
  115439. int possible_partitions=info->partitions;
  115440. int partitions_per_word=look->phrasebook->dim;
  115441. int n=info->end-info->begin;
  115442. int partvals=n/samples_per_partition;
  115443. long resbits[128];
  115444. long resvals[128];
  115445. #ifdef TRAIN_RES
  115446. for(i=0;i<ch;i++)
  115447. for(j=info->begin;j<info->end;j++){
  115448. if(in[i][j]>look->tmax)look->tmax=in[i][j];
  115449. if(in[i][j]<look->tmin)look->tmin=in[i][j];
  115450. }
  115451. #endif
  115452. memset(resbits,0,sizeof(resbits));
  115453. memset(resvals,0,sizeof(resvals));
  115454. /* we code the partition words for each channel, then the residual
  115455. words for a partition per channel until we've written all the
  115456. residual words for that partition word. Then write the next
  115457. partition channel words... */
  115458. for(s=0;s<look->stages;s++){
  115459. for(i=0;i<partvals;){
  115460. /* first we encode a partition codeword for each channel */
  115461. if(s==0){
  115462. for(j=0;j<ch;j++){
  115463. long val=partword[j][i];
  115464. for(k=1;k<partitions_per_word;k++){
  115465. val*=possible_partitions;
  115466. if(i+k<partvals)
  115467. val+=partword[j][i+k];
  115468. }
  115469. /* training hack */
  115470. if(val<look->phrasebook->entries)
  115471. look->phrasebits+=vorbis_book_encode(look->phrasebook,val,opb);
  115472. #if 0 /*def TRAIN_RES*/
  115473. else
  115474. fprintf(stderr,"!");
  115475. #endif
  115476. }
  115477. }
  115478. /* now we encode interleaved residual values for the partitions */
  115479. for(k=0;k<partitions_per_word && i<partvals;k++,i++){
  115480. long offset=i*samples_per_partition+info->begin;
  115481. for(j=0;j<ch;j++){
  115482. if(s==0)resvals[partword[j][i]]+=samples_per_partition;
  115483. if(info->secondstages[partword[j][i]]&(1<<s)){
  115484. codebook *statebook=look->partbooks[partword[j][i]][s];
  115485. if(statebook){
  115486. int ret;
  115487. long *accumulator=NULL;
  115488. #ifdef TRAIN_RES
  115489. accumulator=look->training_data[s][partword[j][i]];
  115490. {
  115491. int l;
  115492. float *samples=in[j]+offset;
  115493. for(l=0;l<samples_per_partition;l++){
  115494. if(samples[l]<look->training_min[s][partword[j][i]])
  115495. look->training_min[s][partword[j][i]]=samples[l];
  115496. if(samples[l]>look->training_max[s][partword[j][i]])
  115497. look->training_max[s][partword[j][i]]=samples[l];
  115498. }
  115499. }
  115500. #endif
  115501. ret=encode(opb,in[j]+offset,samples_per_partition,
  115502. statebook,accumulator);
  115503. look->postbits+=ret;
  115504. resbits[partword[j][i]]+=ret;
  115505. }
  115506. }
  115507. }
  115508. }
  115509. }
  115510. }
  115511. /*{
  115512. long total=0;
  115513. long totalbits=0;
  115514. fprintf(stderr,"%d :: ",vb->mode);
  115515. for(k=0;k<possible_partitions;k++){
  115516. fprintf(stderr,"%ld/%1.2g, ",resvals[k],(float)resbits[k]/resvals[k]);
  115517. total+=resvals[k];
  115518. totalbits+=resbits[k];
  115519. }
  115520. fprintf(stderr,":: %ld:%1.2g\n",total,(double)totalbits/total);
  115521. }*/
  115522. return(0);
  115523. }
  115524. /* a truncated packet here just means 'stop working'; it's not an error */
  115525. static int _01inverse(vorbis_block *vb,vorbis_look_residue *vl,
  115526. float **in,int ch,
  115527. long (*decodepart)(codebook *, float *,
  115528. oggpack_buffer *,int)){
  115529. long i,j,k,l,s;
  115530. vorbis_look_residue0 *look=(vorbis_look_residue0 *)vl;
  115531. vorbis_info_residue0 *info=look->info;
  115532. /* move all this setup out later */
  115533. int samples_per_partition=info->grouping;
  115534. int partitions_per_word=look->phrasebook->dim;
  115535. int n=info->end-info->begin;
  115536. int partvals=n/samples_per_partition;
  115537. int partwords=(partvals+partitions_per_word-1)/partitions_per_word;
  115538. int ***partword=(int***)alloca(ch*sizeof(*partword));
  115539. for(j=0;j<ch;j++)
  115540. partword[j]=(int**)_vorbis_block_alloc(vb,partwords*sizeof(*partword[j]));
  115541. for(s=0;s<look->stages;s++){
  115542. /* each loop decodes on partition codeword containing
  115543. partitions_pre_word partitions */
  115544. for(i=0,l=0;i<partvals;l++){
  115545. if(s==0){
  115546. /* fetch the partition word for each channel */
  115547. for(j=0;j<ch;j++){
  115548. int temp=vorbis_book_decode(look->phrasebook,&vb->opb);
  115549. if(temp==-1)goto eopbreak;
  115550. partword[j][l]=look->decodemap[temp];
  115551. if(partword[j][l]==NULL)goto errout;
  115552. }
  115553. }
  115554. /* now we decode residual values for the partitions */
  115555. for(k=0;k<partitions_per_word && i<partvals;k++,i++)
  115556. for(j=0;j<ch;j++){
  115557. long offset=info->begin+i*samples_per_partition;
  115558. if(info->secondstages[partword[j][l][k]]&(1<<s)){
  115559. codebook *stagebook=look->partbooks[partword[j][l][k]][s];
  115560. if(stagebook){
  115561. if(decodepart(stagebook,in[j]+offset,&vb->opb,
  115562. samples_per_partition)==-1)goto eopbreak;
  115563. }
  115564. }
  115565. }
  115566. }
  115567. }
  115568. errout:
  115569. eopbreak:
  115570. return(0);
  115571. }
  115572. #if 0
  115573. /* residue 0 and 1 are just slight variants of one another. 0 is
  115574. interleaved, 1 is not */
  115575. long **res0_class(vorbis_block *vb,vorbis_look_residue *vl,
  115576. float **in,int *nonzero,int ch){
  115577. /* we encode only the nonzero parts of a bundle */
  115578. int i,used=0;
  115579. for(i=0;i<ch;i++)
  115580. if(nonzero[i])
  115581. in[used++]=in[i];
  115582. if(used)
  115583. /*return(_01class(vb,vl,in,used,_interleaved_testhack));*/
  115584. return(_01class(vb,vl,in,used));
  115585. else
  115586. return(0);
  115587. }
  115588. int res0_forward(vorbis_block *vb,vorbis_look_residue *vl,
  115589. float **in,float **out,int *nonzero,int ch,
  115590. long **partword){
  115591. /* we encode only the nonzero parts of a bundle */
  115592. int i,j,used=0,n=vb->pcmend/2;
  115593. for(i=0;i<ch;i++)
  115594. if(nonzero[i]){
  115595. if(out)
  115596. for(j=0;j<n;j++)
  115597. out[i][j]+=in[i][j];
  115598. in[used++]=in[i];
  115599. }
  115600. if(used){
  115601. int ret=_01forward(vb,vl,in,used,partword,
  115602. _interleaved_encodepart);
  115603. if(out){
  115604. used=0;
  115605. for(i=0;i<ch;i++)
  115606. if(nonzero[i]){
  115607. for(j=0;j<n;j++)
  115608. out[i][j]-=in[used][j];
  115609. used++;
  115610. }
  115611. }
  115612. return(ret);
  115613. }else{
  115614. return(0);
  115615. }
  115616. }
  115617. #endif
  115618. int res0_inverse(vorbis_block *vb,vorbis_look_residue *vl,
  115619. float **in,int *nonzero,int ch){
  115620. int i,used=0;
  115621. for(i=0;i<ch;i++)
  115622. if(nonzero[i])
  115623. in[used++]=in[i];
  115624. if(used)
  115625. return(_01inverse(vb,vl,in,used,vorbis_book_decodevs_add));
  115626. else
  115627. return(0);
  115628. }
  115629. int res1_forward(oggpack_buffer *opb,vorbis_block *vb,vorbis_look_residue *vl,
  115630. float **in,float **out,int *nonzero,int ch,
  115631. long **partword){
  115632. int i,j,used=0,n=vb->pcmend/2;
  115633. for(i=0;i<ch;i++)
  115634. if(nonzero[i]){
  115635. if(out)
  115636. for(j=0;j<n;j++)
  115637. out[i][j]+=in[i][j];
  115638. in[used++]=in[i];
  115639. }
  115640. if(used){
  115641. int ret=_01forward(opb,vb,vl,in,used,partword,_encodepart);
  115642. if(out){
  115643. used=0;
  115644. for(i=0;i<ch;i++)
  115645. if(nonzero[i]){
  115646. for(j=0;j<n;j++)
  115647. out[i][j]-=in[used][j];
  115648. used++;
  115649. }
  115650. }
  115651. return(ret);
  115652. }else{
  115653. return(0);
  115654. }
  115655. }
  115656. long **res1_class(vorbis_block *vb,vorbis_look_residue *vl,
  115657. float **in,int *nonzero,int ch){
  115658. int i,used=0;
  115659. for(i=0;i<ch;i++)
  115660. if(nonzero[i])
  115661. in[used++]=in[i];
  115662. if(used)
  115663. return(_01class(vb,vl,in,used));
  115664. else
  115665. return(0);
  115666. }
  115667. int res1_inverse(vorbis_block *vb,vorbis_look_residue *vl,
  115668. float **in,int *nonzero,int ch){
  115669. int i,used=0;
  115670. for(i=0;i<ch;i++)
  115671. if(nonzero[i])
  115672. in[used++]=in[i];
  115673. if(used)
  115674. return(_01inverse(vb,vl,in,used,vorbis_book_decodev_add));
  115675. else
  115676. return(0);
  115677. }
  115678. long **res2_class(vorbis_block *vb,vorbis_look_residue *vl,
  115679. float **in,int *nonzero,int ch){
  115680. int i,used=0;
  115681. for(i=0;i<ch;i++)
  115682. if(nonzero[i])used++;
  115683. if(used)
  115684. return(_2class(vb,vl,in,ch));
  115685. else
  115686. return(0);
  115687. }
  115688. /* res2 is slightly more different; all the channels are interleaved
  115689. into a single vector and encoded. */
  115690. int res2_forward(oggpack_buffer *opb,
  115691. vorbis_block *vb,vorbis_look_residue *vl,
  115692. float **in,float **out,int *nonzero,int ch,
  115693. long **partword){
  115694. long i,j,k,n=vb->pcmend/2,used=0;
  115695. /* don't duplicate the code; use a working vector hack for now and
  115696. reshape ourselves into a single channel res1 */
  115697. /* ugly; reallocs for each coupling pass :-( */
  115698. float *work=(float*)_vorbis_block_alloc(vb,ch*n*sizeof(*work));
  115699. for(i=0;i<ch;i++){
  115700. float *pcm=in[i];
  115701. if(nonzero[i])used++;
  115702. for(j=0,k=i;j<n;j++,k+=ch)
  115703. work[k]=pcm[j];
  115704. }
  115705. if(used){
  115706. int ret=_01forward(opb,vb,vl,&work,1,partword,_encodepart);
  115707. /* update the sofar vector */
  115708. if(out){
  115709. for(i=0;i<ch;i++){
  115710. float *pcm=in[i];
  115711. float *sofar=out[i];
  115712. for(j=0,k=i;j<n;j++,k+=ch)
  115713. sofar[j]+=pcm[j]-work[k];
  115714. }
  115715. }
  115716. return(ret);
  115717. }else{
  115718. return(0);
  115719. }
  115720. }
  115721. /* duplicate code here as speed is somewhat more important */
  115722. int res2_inverse(vorbis_block *vb,vorbis_look_residue *vl,
  115723. float **in,int *nonzero,int ch){
  115724. long i,k,l,s;
  115725. vorbis_look_residue0 *look=(vorbis_look_residue0 *)vl;
  115726. vorbis_info_residue0 *info=look->info;
  115727. /* move all this setup out later */
  115728. int samples_per_partition=info->grouping;
  115729. int partitions_per_word=look->phrasebook->dim;
  115730. int n=info->end-info->begin;
  115731. int partvals=n/samples_per_partition;
  115732. int partwords=(partvals+partitions_per_word-1)/partitions_per_word;
  115733. int **partword=(int**)_vorbis_block_alloc(vb,partwords*sizeof(*partword));
  115734. for(i=0;i<ch;i++)if(nonzero[i])break;
  115735. if(i==ch)return(0); /* no nonzero vectors */
  115736. for(s=0;s<look->stages;s++){
  115737. for(i=0,l=0;i<partvals;l++){
  115738. if(s==0){
  115739. /* fetch the partition word */
  115740. int temp=vorbis_book_decode(look->phrasebook,&vb->opb);
  115741. if(temp==-1)goto eopbreak;
  115742. partword[l]=look->decodemap[temp];
  115743. if(partword[l]==NULL)goto errout;
  115744. }
  115745. /* now we decode residual values for the partitions */
  115746. for(k=0;k<partitions_per_word && i<partvals;k++,i++)
  115747. if(info->secondstages[partword[l][k]]&(1<<s)){
  115748. codebook *stagebook=look->partbooks[partword[l][k]][s];
  115749. if(stagebook){
  115750. if(vorbis_book_decodevv_add(stagebook,in,
  115751. i*samples_per_partition+info->begin,ch,
  115752. &vb->opb,samples_per_partition)==-1)
  115753. goto eopbreak;
  115754. }
  115755. }
  115756. }
  115757. }
  115758. errout:
  115759. eopbreak:
  115760. return(0);
  115761. }
  115762. vorbis_func_residue residue0_exportbundle={
  115763. NULL,
  115764. &res0_unpack,
  115765. &res0_look,
  115766. &res0_free_info,
  115767. &res0_free_look,
  115768. NULL,
  115769. NULL,
  115770. &res0_inverse
  115771. };
  115772. vorbis_func_residue residue1_exportbundle={
  115773. &res0_pack,
  115774. &res0_unpack,
  115775. &res0_look,
  115776. &res0_free_info,
  115777. &res0_free_look,
  115778. &res1_class,
  115779. &res1_forward,
  115780. &res1_inverse
  115781. };
  115782. vorbis_func_residue residue2_exportbundle={
  115783. &res0_pack,
  115784. &res0_unpack,
  115785. &res0_look,
  115786. &res0_free_info,
  115787. &res0_free_look,
  115788. &res2_class,
  115789. &res2_forward,
  115790. &res2_inverse
  115791. };
  115792. #endif
  115793. /*** End of inlined file: res0.c ***/
  115794. /*** Start of inlined file: sharedbook.c ***/
  115795. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  115796. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  115797. // tasks..
  115798. #if JUCE_MSVC
  115799. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  115800. #endif
  115801. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  115802. #if JUCE_USE_OGGVORBIS
  115803. #include <stdlib.h>
  115804. #include <math.h>
  115805. #include <string.h>
  115806. /**** pack/unpack helpers ******************************************/
  115807. int _ilog(unsigned int v){
  115808. int ret=0;
  115809. while(v){
  115810. ret++;
  115811. v>>=1;
  115812. }
  115813. return(ret);
  115814. }
  115815. /* 32 bit float (not IEEE; nonnormalized mantissa +
  115816. biased exponent) : neeeeeee eeemmmmm mmmmmmmm mmmmmmmm
  115817. Why not IEEE? It's just not that important here. */
  115818. #define VQ_FEXP 10
  115819. #define VQ_FMAN 21
  115820. #define VQ_FEXP_BIAS 768 /* bias toward values smaller than 1. */
  115821. /* doesn't currently guard under/overflow */
  115822. long _float32_pack(float val){
  115823. int sign=0;
  115824. long exp;
  115825. long mant;
  115826. if(val<0){
  115827. sign=0x80000000;
  115828. val= -val;
  115829. }
  115830. exp= floor(log(val)/log(2.f));
  115831. mant=rint(ldexp(val,(VQ_FMAN-1)-exp));
  115832. exp=(exp+VQ_FEXP_BIAS)<<VQ_FMAN;
  115833. return(sign|exp|mant);
  115834. }
  115835. float _float32_unpack(long val){
  115836. double mant=val&0x1fffff;
  115837. int sign=val&0x80000000;
  115838. long exp =(val&0x7fe00000L)>>VQ_FMAN;
  115839. if(sign)mant= -mant;
  115840. return(ldexp(mant,exp-(VQ_FMAN-1)-VQ_FEXP_BIAS));
  115841. }
  115842. /* given a list of word lengths, generate a list of codewords. Works
  115843. for length ordered or unordered, always assigns the lowest valued
  115844. codewords first. Extended to handle unused entries (length 0) */
  115845. ogg_uint32_t *_make_words(long *l,long n,long sparsecount){
  115846. long i,j,count=0;
  115847. ogg_uint32_t marker[33];
  115848. ogg_uint32_t *r=(ogg_uint32_t*)_ogg_malloc((sparsecount?sparsecount:n)*sizeof(*r));
  115849. memset(marker,0,sizeof(marker));
  115850. for(i=0;i<n;i++){
  115851. long length=l[i];
  115852. if(length>0){
  115853. ogg_uint32_t entry=marker[length];
  115854. /* when we claim a node for an entry, we also claim the nodes
  115855. below it (pruning off the imagined tree that may have dangled
  115856. from it) as well as blocking the use of any nodes directly
  115857. above for leaves */
  115858. /* update ourself */
  115859. if(length<32 && (entry>>length)){
  115860. /* error condition; the lengths must specify an overpopulated tree */
  115861. _ogg_free(r);
  115862. return(NULL);
  115863. }
  115864. r[count++]=entry;
  115865. /* Look to see if the next shorter marker points to the node
  115866. above. if so, update it and repeat. */
  115867. {
  115868. for(j=length;j>0;j--){
  115869. if(marker[j]&1){
  115870. /* have to jump branches */
  115871. if(j==1)
  115872. marker[1]++;
  115873. else
  115874. marker[j]=marker[j-1]<<1;
  115875. break; /* invariant says next upper marker would already
  115876. have been moved if it was on the same path */
  115877. }
  115878. marker[j]++;
  115879. }
  115880. }
  115881. /* prune the tree; the implicit invariant says all the longer
  115882. markers were dangling from our just-taken node. Dangle them
  115883. from our *new* node. */
  115884. for(j=length+1;j<33;j++)
  115885. if((marker[j]>>1) == entry){
  115886. entry=marker[j];
  115887. marker[j]=marker[j-1]<<1;
  115888. }else
  115889. break;
  115890. }else
  115891. if(sparsecount==0)count++;
  115892. }
  115893. /* bitreverse the words because our bitwise packer/unpacker is LSb
  115894. endian */
  115895. for(i=0,count=0;i<n;i++){
  115896. ogg_uint32_t temp=0;
  115897. for(j=0;j<l[i];j++){
  115898. temp<<=1;
  115899. temp|=(r[count]>>j)&1;
  115900. }
  115901. if(sparsecount){
  115902. if(l[i])
  115903. r[count++]=temp;
  115904. }else
  115905. r[count++]=temp;
  115906. }
  115907. return(r);
  115908. }
  115909. /* there might be a straightforward one-line way to do the below
  115910. that's portable and totally safe against roundoff, but I haven't
  115911. thought of it. Therefore, we opt on the side of caution */
  115912. long _book_maptype1_quantvals(const static_codebook *b){
  115913. long vals=floor(pow((float)b->entries,1.f/b->dim));
  115914. /* the above *should* be reliable, but we'll not assume that FP is
  115915. ever reliable when bitstream sync is at stake; verify via integer
  115916. means that vals really is the greatest value of dim for which
  115917. vals^b->bim <= b->entries */
  115918. /* treat the above as an initial guess */
  115919. while(1){
  115920. long acc=1;
  115921. long acc1=1;
  115922. int i;
  115923. for(i=0;i<b->dim;i++){
  115924. acc*=vals;
  115925. acc1*=vals+1;
  115926. }
  115927. if(acc<=b->entries && acc1>b->entries){
  115928. return(vals);
  115929. }else{
  115930. if(acc>b->entries){
  115931. vals--;
  115932. }else{
  115933. vals++;
  115934. }
  115935. }
  115936. }
  115937. }
  115938. /* unpack the quantized list of values for encode/decode ***********/
  115939. /* we need to deal with two map types: in map type 1, the values are
  115940. generated algorithmically (each column of the vector counts through
  115941. the values in the quant vector). in map type 2, all the values came
  115942. in in an explicit list. Both value lists must be unpacked */
  115943. float *_book_unquantize(const static_codebook *b,int n,int *sparsemap){
  115944. long j,k,count=0;
  115945. if(b->maptype==1 || b->maptype==2){
  115946. int quantvals;
  115947. float mindel=_float32_unpack(b->q_min);
  115948. float delta=_float32_unpack(b->q_delta);
  115949. float *r=(float*)_ogg_calloc(n*b->dim,sizeof(*r));
  115950. /* maptype 1 and 2 both use a quantized value vector, but
  115951. different sizes */
  115952. switch(b->maptype){
  115953. case 1:
  115954. /* most of the time, entries%dimensions == 0, but we need to be
  115955. well defined. We define that the possible vales at each
  115956. scalar is values == entries/dim. If entries%dim != 0, we'll
  115957. have 'too few' values (values*dim<entries), which means that
  115958. we'll have 'left over' entries; left over entries use zeroed
  115959. values (and are wasted). So don't generate codebooks like
  115960. that */
  115961. quantvals=_book_maptype1_quantvals(b);
  115962. for(j=0;j<b->entries;j++){
  115963. if((sparsemap && b->lengthlist[j]) || !sparsemap){
  115964. float last=0.f;
  115965. int indexdiv=1;
  115966. for(k=0;k<b->dim;k++){
  115967. int index= (j/indexdiv)%quantvals;
  115968. float val=b->quantlist[index];
  115969. val=fabs(val)*delta+mindel+last;
  115970. if(b->q_sequencep)last=val;
  115971. if(sparsemap)
  115972. r[sparsemap[count]*b->dim+k]=val;
  115973. else
  115974. r[count*b->dim+k]=val;
  115975. indexdiv*=quantvals;
  115976. }
  115977. count++;
  115978. }
  115979. }
  115980. break;
  115981. case 2:
  115982. for(j=0;j<b->entries;j++){
  115983. if((sparsemap && b->lengthlist[j]) || !sparsemap){
  115984. float last=0.f;
  115985. for(k=0;k<b->dim;k++){
  115986. float val=b->quantlist[j*b->dim+k];
  115987. val=fabs(val)*delta+mindel+last;
  115988. if(b->q_sequencep)last=val;
  115989. if(sparsemap)
  115990. r[sparsemap[count]*b->dim+k]=val;
  115991. else
  115992. r[count*b->dim+k]=val;
  115993. }
  115994. count++;
  115995. }
  115996. }
  115997. break;
  115998. }
  115999. return(r);
  116000. }
  116001. return(NULL);
  116002. }
  116003. void vorbis_staticbook_clear(static_codebook *b){
  116004. if(b->allocedp){
  116005. if(b->quantlist)_ogg_free(b->quantlist);
  116006. if(b->lengthlist)_ogg_free(b->lengthlist);
  116007. if(b->nearest_tree){
  116008. _ogg_free(b->nearest_tree->ptr0);
  116009. _ogg_free(b->nearest_tree->ptr1);
  116010. _ogg_free(b->nearest_tree->p);
  116011. _ogg_free(b->nearest_tree->q);
  116012. memset(b->nearest_tree,0,sizeof(*b->nearest_tree));
  116013. _ogg_free(b->nearest_tree);
  116014. }
  116015. if(b->thresh_tree){
  116016. _ogg_free(b->thresh_tree->quantthresh);
  116017. _ogg_free(b->thresh_tree->quantmap);
  116018. memset(b->thresh_tree,0,sizeof(*b->thresh_tree));
  116019. _ogg_free(b->thresh_tree);
  116020. }
  116021. memset(b,0,sizeof(*b));
  116022. }
  116023. }
  116024. void vorbis_staticbook_destroy(static_codebook *b){
  116025. if(b->allocedp){
  116026. vorbis_staticbook_clear(b);
  116027. _ogg_free(b);
  116028. }
  116029. }
  116030. void vorbis_book_clear(codebook *b){
  116031. /* static book is not cleared; we're likely called on the lookup and
  116032. the static codebook belongs to the info struct */
  116033. if(b->valuelist)_ogg_free(b->valuelist);
  116034. if(b->codelist)_ogg_free(b->codelist);
  116035. if(b->dec_index)_ogg_free(b->dec_index);
  116036. if(b->dec_codelengths)_ogg_free(b->dec_codelengths);
  116037. if(b->dec_firsttable)_ogg_free(b->dec_firsttable);
  116038. memset(b,0,sizeof(*b));
  116039. }
  116040. int vorbis_book_init_encode(codebook *c,const static_codebook *s){
  116041. memset(c,0,sizeof(*c));
  116042. c->c=s;
  116043. c->entries=s->entries;
  116044. c->used_entries=s->entries;
  116045. c->dim=s->dim;
  116046. c->codelist=_make_words(s->lengthlist,s->entries,0);
  116047. c->valuelist=_book_unquantize(s,s->entries,NULL);
  116048. return(0);
  116049. }
  116050. static int sort32a(const void *a,const void *b){
  116051. return ( **(ogg_uint32_t **)a>**(ogg_uint32_t **)b)-
  116052. ( **(ogg_uint32_t **)a<**(ogg_uint32_t **)b);
  116053. }
  116054. /* decode codebook arrangement is more heavily optimized than encode */
  116055. int vorbis_book_init_decode(codebook *c,const static_codebook *s){
  116056. int i,j,n=0,tabn;
  116057. int *sortindex;
  116058. memset(c,0,sizeof(*c));
  116059. /* count actually used entries */
  116060. for(i=0;i<s->entries;i++)
  116061. if(s->lengthlist[i]>0)
  116062. n++;
  116063. c->entries=s->entries;
  116064. c->used_entries=n;
  116065. c->dim=s->dim;
  116066. /* two different remappings go on here.
  116067. First, we collapse the likely sparse codebook down only to
  116068. actually represented values/words. This collapsing needs to be
  116069. indexed as map-valueless books are used to encode original entry
  116070. positions as integers.
  116071. Second, we reorder all vectors, including the entry index above,
  116072. by sorted bitreversed codeword to allow treeless decode. */
  116073. {
  116074. /* perform sort */
  116075. ogg_uint32_t *codes=_make_words(s->lengthlist,s->entries,c->used_entries);
  116076. ogg_uint32_t **codep=(ogg_uint32_t**)alloca(sizeof(*codep)*n);
  116077. if(codes==NULL)goto err_out;
  116078. for(i=0;i<n;i++){
  116079. codes[i]=ogg_bitreverse(codes[i]);
  116080. codep[i]=codes+i;
  116081. }
  116082. qsort(codep,n,sizeof(*codep),sort32a);
  116083. sortindex=(int*)alloca(n*sizeof(*sortindex));
  116084. c->codelist=(ogg_uint32_t*)_ogg_malloc(n*sizeof(*c->codelist));
  116085. /* the index is a reverse index */
  116086. for(i=0;i<n;i++){
  116087. int position=codep[i]-codes;
  116088. sortindex[position]=i;
  116089. }
  116090. for(i=0;i<n;i++)
  116091. c->codelist[sortindex[i]]=codes[i];
  116092. _ogg_free(codes);
  116093. }
  116094. c->valuelist=_book_unquantize(s,n,sortindex);
  116095. c->dec_index=(int*)_ogg_malloc(n*sizeof(*c->dec_index));
  116096. for(n=0,i=0;i<s->entries;i++)
  116097. if(s->lengthlist[i]>0)
  116098. c->dec_index[sortindex[n++]]=i;
  116099. c->dec_codelengths=(char*)_ogg_malloc(n*sizeof(*c->dec_codelengths));
  116100. for(n=0,i=0;i<s->entries;i++)
  116101. if(s->lengthlist[i]>0)
  116102. c->dec_codelengths[sortindex[n++]]=s->lengthlist[i];
  116103. c->dec_firsttablen=_ilog(c->used_entries)-4; /* this is magic */
  116104. if(c->dec_firsttablen<5)c->dec_firsttablen=5;
  116105. if(c->dec_firsttablen>8)c->dec_firsttablen=8;
  116106. tabn=1<<c->dec_firsttablen;
  116107. c->dec_firsttable=(ogg_uint32_t*)_ogg_calloc(tabn,sizeof(*c->dec_firsttable));
  116108. c->dec_maxlength=0;
  116109. for(i=0;i<n;i++){
  116110. if(c->dec_maxlength<c->dec_codelengths[i])
  116111. c->dec_maxlength=c->dec_codelengths[i];
  116112. if(c->dec_codelengths[i]<=c->dec_firsttablen){
  116113. ogg_uint32_t orig=ogg_bitreverse(c->codelist[i]);
  116114. for(j=0;j<(1<<(c->dec_firsttablen-c->dec_codelengths[i]));j++)
  116115. c->dec_firsttable[orig|(j<<c->dec_codelengths[i])]=i+1;
  116116. }
  116117. }
  116118. /* now fill in 'unused' entries in the firsttable with hi/lo search
  116119. hints for the non-direct-hits */
  116120. {
  116121. ogg_uint32_t mask=0xfffffffeUL<<(31-c->dec_firsttablen);
  116122. long lo=0,hi=0;
  116123. for(i=0;i<tabn;i++){
  116124. ogg_uint32_t word=i<<(32-c->dec_firsttablen);
  116125. if(c->dec_firsttable[ogg_bitreverse(word)]==0){
  116126. while((lo+1)<n && c->codelist[lo+1]<=word)lo++;
  116127. while( hi<n && word>=(c->codelist[hi]&mask))hi++;
  116128. /* we only actually have 15 bits per hint to play with here.
  116129. In order to overflow gracefully (nothing breaks, efficiency
  116130. just drops), encode as the difference from the extremes. */
  116131. {
  116132. unsigned long loval=lo;
  116133. unsigned long hival=n-hi;
  116134. if(loval>0x7fff)loval=0x7fff;
  116135. if(hival>0x7fff)hival=0x7fff;
  116136. c->dec_firsttable[ogg_bitreverse(word)]=
  116137. 0x80000000UL | (loval<<15) | hival;
  116138. }
  116139. }
  116140. }
  116141. }
  116142. return(0);
  116143. err_out:
  116144. vorbis_book_clear(c);
  116145. return(-1);
  116146. }
  116147. static float _dist(int el,float *ref, float *b,int step){
  116148. int i;
  116149. float acc=0.f;
  116150. for(i=0;i<el;i++){
  116151. float val=(ref[i]-b[i*step]);
  116152. acc+=val*val;
  116153. }
  116154. return(acc);
  116155. }
  116156. int _best(codebook *book, float *a, int step){
  116157. encode_aux_threshmatch *tt=book->c->thresh_tree;
  116158. #if 0
  116159. encode_aux_nearestmatch *nt=book->c->nearest_tree;
  116160. encode_aux_pigeonhole *pt=book->c->pigeon_tree;
  116161. #endif
  116162. int dim=book->dim;
  116163. int k,o;
  116164. /*int savebest=-1;
  116165. float saverr;*/
  116166. /* do we have a threshhold encode hint? */
  116167. if(tt){
  116168. int index=0,i;
  116169. /* find the quant val of each scalar */
  116170. for(k=0,o=step*(dim-1);k<dim;k++,o-=step){
  116171. i=tt->threshvals>>1;
  116172. if(a[o]<tt->quantthresh[i]){
  116173. for(;i>0;i--)
  116174. if(a[o]>=tt->quantthresh[i-1])
  116175. break;
  116176. }else{
  116177. for(i++;i<tt->threshvals-1;i++)
  116178. if(a[o]<tt->quantthresh[i])break;
  116179. }
  116180. index=(index*tt->quantvals)+tt->quantmap[i];
  116181. }
  116182. /* regular lattices are easy :-) */
  116183. if(book->c->lengthlist[index]>0) /* is this unused? If so, we'll
  116184. use a decision tree after all
  116185. and fall through*/
  116186. return(index);
  116187. }
  116188. #if 0
  116189. /* do we have a pigeonhole encode hint? */
  116190. if(pt){
  116191. const static_codebook *c=book->c;
  116192. int i,besti=-1;
  116193. float best=0.f;
  116194. int entry=0;
  116195. /* dealing with sequentialness is a pain in the ass */
  116196. if(c->q_sequencep){
  116197. int pv;
  116198. long mul=1;
  116199. float qlast=0;
  116200. for(k=0,o=0;k<dim;k++,o+=step){
  116201. pv=(int)((a[o]-qlast-pt->min)/pt->del);
  116202. if(pv<0 || pv>=pt->mapentries)break;
  116203. entry+=pt->pigeonmap[pv]*mul;
  116204. mul*=pt->quantvals;
  116205. qlast+=pv*pt->del+pt->min;
  116206. }
  116207. }else{
  116208. for(k=0,o=step*(dim-1);k<dim;k++,o-=step){
  116209. int pv=(int)((a[o]-pt->min)/pt->del);
  116210. if(pv<0 || pv>=pt->mapentries)break;
  116211. entry=entry*pt->quantvals+pt->pigeonmap[pv];
  116212. }
  116213. }
  116214. /* must be within the pigeonholable range; if we quant outside (or
  116215. in an entry that we define no list for), brute force it */
  116216. if(k==dim && pt->fitlength[entry]){
  116217. /* search the abbreviated list */
  116218. long *list=pt->fitlist+pt->fitmap[entry];
  116219. for(i=0;i<pt->fitlength[entry];i++){
  116220. float this=_dist(dim,book->valuelist+list[i]*dim,a,step);
  116221. if(besti==-1 || this<best){
  116222. best=this;
  116223. besti=list[i];
  116224. }
  116225. }
  116226. return(besti);
  116227. }
  116228. }
  116229. if(nt){
  116230. /* optimized using the decision tree */
  116231. while(1){
  116232. float c=0.f;
  116233. float *p=book->valuelist+nt->p[ptr];
  116234. float *q=book->valuelist+nt->q[ptr];
  116235. for(k=0,o=0;k<dim;k++,o+=step)
  116236. c+=(p[k]-q[k])*(a[o]-(p[k]+q[k])*.5);
  116237. if(c>0.f) /* in A */
  116238. ptr= -nt->ptr0[ptr];
  116239. else /* in B */
  116240. ptr= -nt->ptr1[ptr];
  116241. if(ptr<=0)break;
  116242. }
  116243. return(-ptr);
  116244. }
  116245. #endif
  116246. /* brute force it! */
  116247. {
  116248. const static_codebook *c=book->c;
  116249. int i,besti=-1;
  116250. float best=0.f;
  116251. float *e=book->valuelist;
  116252. for(i=0;i<book->entries;i++){
  116253. if(c->lengthlist[i]>0){
  116254. float thisx=_dist(dim,e,a,step);
  116255. if(besti==-1 || thisx<best){
  116256. best=thisx;
  116257. besti=i;
  116258. }
  116259. }
  116260. e+=dim;
  116261. }
  116262. /*if(savebest!=-1 && savebest!=besti){
  116263. fprintf(stderr,"brute force/pigeonhole disagreement:\n"
  116264. "original:");
  116265. for(i=0;i<dim*step;i+=step)fprintf(stderr,"%g,",a[i]);
  116266. fprintf(stderr,"\n"
  116267. "pigeonhole (entry %d, err %g):",savebest,saverr);
  116268. for(i=0;i<dim;i++)fprintf(stderr,"%g,",
  116269. (book->valuelist+savebest*dim)[i]);
  116270. fprintf(stderr,"\n"
  116271. "bruteforce (entry %d, err %g):",besti,best);
  116272. for(i=0;i<dim;i++)fprintf(stderr,"%g,",
  116273. (book->valuelist+besti*dim)[i]);
  116274. fprintf(stderr,"\n");
  116275. }*/
  116276. return(besti);
  116277. }
  116278. }
  116279. long vorbis_book_codeword(codebook *book,int entry){
  116280. if(book->c) /* only use with encode; decode optimizations are
  116281. allowed to break this */
  116282. return book->codelist[entry];
  116283. return -1;
  116284. }
  116285. long vorbis_book_codelen(codebook *book,int entry){
  116286. if(book->c) /* only use with encode; decode optimizations are
  116287. allowed to break this */
  116288. return book->c->lengthlist[entry];
  116289. return -1;
  116290. }
  116291. #ifdef _V_SELFTEST
  116292. /* Unit tests of the dequantizer; this stuff will be OK
  116293. cross-platform, I simply want to be sure that special mapping cases
  116294. actually work properly; a bug could go unnoticed for a while */
  116295. #include <stdio.h>
  116296. /* cases:
  116297. no mapping
  116298. full, explicit mapping
  116299. algorithmic mapping
  116300. nonsequential
  116301. sequential
  116302. */
  116303. static long full_quantlist1[]={0,1,2,3, 4,5,6,7, 8,3,6,1};
  116304. static long partial_quantlist1[]={0,7,2};
  116305. /* no mapping */
  116306. static_codebook test1={
  116307. 4,16,
  116308. NULL,
  116309. 0,
  116310. 0,0,0,0,
  116311. NULL,
  116312. NULL,NULL
  116313. };
  116314. static float *test1_result=NULL;
  116315. /* linear, full mapping, nonsequential */
  116316. static_codebook test2={
  116317. 4,3,
  116318. NULL,
  116319. 2,
  116320. -533200896,1611661312,4,0,
  116321. full_quantlist1,
  116322. NULL,NULL
  116323. };
  116324. static float test2_result[]={-3,-2,-1,0, 1,2,3,4, 5,0,3,-2};
  116325. /* linear, full mapping, sequential */
  116326. static_codebook test3={
  116327. 4,3,
  116328. NULL,
  116329. 2,
  116330. -533200896,1611661312,4,1,
  116331. full_quantlist1,
  116332. NULL,NULL
  116333. };
  116334. static float test3_result[]={-3,-5,-6,-6, 1,3,6,10, 5,5,8,6};
  116335. /* linear, algorithmic mapping, nonsequential */
  116336. static_codebook test4={
  116337. 3,27,
  116338. NULL,
  116339. 1,
  116340. -533200896,1611661312,4,0,
  116341. partial_quantlist1,
  116342. NULL,NULL
  116343. };
  116344. static float test4_result[]={-3,-3,-3, 4,-3,-3, -1,-3,-3,
  116345. -3, 4,-3, 4, 4,-3, -1, 4,-3,
  116346. -3,-1,-3, 4,-1,-3, -1,-1,-3,
  116347. -3,-3, 4, 4,-3, 4, -1,-3, 4,
  116348. -3, 4, 4, 4, 4, 4, -1, 4, 4,
  116349. -3,-1, 4, 4,-1, 4, -1,-1, 4,
  116350. -3,-3,-1, 4,-3,-1, -1,-3,-1,
  116351. -3, 4,-1, 4, 4,-1, -1, 4,-1,
  116352. -3,-1,-1, 4,-1,-1, -1,-1,-1};
  116353. /* linear, algorithmic mapping, sequential */
  116354. static_codebook test5={
  116355. 3,27,
  116356. NULL,
  116357. 1,
  116358. -533200896,1611661312,4,1,
  116359. partial_quantlist1,
  116360. NULL,NULL
  116361. };
  116362. static float test5_result[]={-3,-6,-9, 4, 1,-2, -1,-4,-7,
  116363. -3, 1,-2, 4, 8, 5, -1, 3, 0,
  116364. -3,-4,-7, 4, 3, 0, -1,-2,-5,
  116365. -3,-6,-2, 4, 1, 5, -1,-4, 0,
  116366. -3, 1, 5, 4, 8,12, -1, 3, 7,
  116367. -3,-4, 0, 4, 3, 7, -1,-2, 2,
  116368. -3,-6,-7, 4, 1, 0, -1,-4,-5,
  116369. -3, 1, 0, 4, 8, 7, -1, 3, 2,
  116370. -3,-4,-5, 4, 3, 2, -1,-2,-3};
  116371. void run_test(static_codebook *b,float *comp){
  116372. float *out=_book_unquantize(b,b->entries,NULL);
  116373. int i;
  116374. if(comp){
  116375. if(!out){
  116376. fprintf(stderr,"_book_unquantize incorrectly returned NULL\n");
  116377. exit(1);
  116378. }
  116379. for(i=0;i<b->entries*b->dim;i++)
  116380. if(fabs(out[i]-comp[i])>.0001){
  116381. fprintf(stderr,"disagreement in unquantized and reference data:\n"
  116382. "position %d, %g != %g\n",i,out[i],comp[i]);
  116383. exit(1);
  116384. }
  116385. }else{
  116386. if(out){
  116387. fprintf(stderr,"_book_unquantize returned a value array: \n"
  116388. " correct result should have been NULL\n");
  116389. exit(1);
  116390. }
  116391. }
  116392. }
  116393. int main(){
  116394. /* run the nine dequant tests, and compare to the hand-rolled results */
  116395. fprintf(stderr,"Dequant test 1... ");
  116396. run_test(&test1,test1_result);
  116397. fprintf(stderr,"OK\nDequant test 2... ");
  116398. run_test(&test2,test2_result);
  116399. fprintf(stderr,"OK\nDequant test 3... ");
  116400. run_test(&test3,test3_result);
  116401. fprintf(stderr,"OK\nDequant test 4... ");
  116402. run_test(&test4,test4_result);
  116403. fprintf(stderr,"OK\nDequant test 5... ");
  116404. run_test(&test5,test5_result);
  116405. fprintf(stderr,"OK\n\n");
  116406. return(0);
  116407. }
  116408. #endif
  116409. #endif
  116410. /*** End of inlined file: sharedbook.c ***/
  116411. /*** Start of inlined file: smallft.c ***/
  116412. /* FFT implementation from OggSquish, minus cosine transforms,
  116413. * minus all but radix 2/4 case. In Vorbis we only need this
  116414. * cut-down version.
  116415. *
  116416. * To do more than just power-of-two sized vectors, see the full
  116417. * version I wrote for NetLib.
  116418. *
  116419. * Note that the packing is a little strange; rather than the FFT r/i
  116420. * packing following R_0, I_n, R_1, I_1, R_2, I_2 ... R_n-1, I_n-1,
  116421. * it follows R_0, R_1, I_1, R_2, I_2 ... R_n-1, I_n-1, I_n like the
  116422. * FORTRAN version
  116423. */
  116424. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  116425. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  116426. // tasks..
  116427. #if JUCE_MSVC
  116428. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  116429. #endif
  116430. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  116431. #if JUCE_USE_OGGVORBIS
  116432. #include <stdlib.h>
  116433. #include <string.h>
  116434. #include <math.h>
  116435. static void drfti1(int n, float *wa, int *ifac){
  116436. static int ntryh[4] = { 4,2,3,5 };
  116437. static float tpi = 6.28318530717958648f;
  116438. float arg,argh,argld,fi;
  116439. int ntry=0,i,j=-1;
  116440. int k1, l1, l2, ib;
  116441. int ld, ii, ip, is, nq, nr;
  116442. int ido, ipm, nfm1;
  116443. int nl=n;
  116444. int nf=0;
  116445. L101:
  116446. j++;
  116447. if (j < 4)
  116448. ntry=ntryh[j];
  116449. else
  116450. ntry+=2;
  116451. L104:
  116452. nq=nl/ntry;
  116453. nr=nl-ntry*nq;
  116454. if (nr!=0) goto L101;
  116455. nf++;
  116456. ifac[nf+1]=ntry;
  116457. nl=nq;
  116458. if(ntry!=2)goto L107;
  116459. if(nf==1)goto L107;
  116460. for (i=1;i<nf;i++){
  116461. ib=nf-i+1;
  116462. ifac[ib+1]=ifac[ib];
  116463. }
  116464. ifac[2] = 2;
  116465. L107:
  116466. if(nl!=1)goto L104;
  116467. ifac[0]=n;
  116468. ifac[1]=nf;
  116469. argh=tpi/n;
  116470. is=0;
  116471. nfm1=nf-1;
  116472. l1=1;
  116473. if(nfm1==0)return;
  116474. for (k1=0;k1<nfm1;k1++){
  116475. ip=ifac[k1+2];
  116476. ld=0;
  116477. l2=l1*ip;
  116478. ido=n/l2;
  116479. ipm=ip-1;
  116480. for (j=0;j<ipm;j++){
  116481. ld+=l1;
  116482. i=is;
  116483. argld=(float)ld*argh;
  116484. fi=0.f;
  116485. for (ii=2;ii<ido;ii+=2){
  116486. fi+=1.f;
  116487. arg=fi*argld;
  116488. wa[i++]=cos(arg);
  116489. wa[i++]=sin(arg);
  116490. }
  116491. is+=ido;
  116492. }
  116493. l1=l2;
  116494. }
  116495. }
  116496. static void fdrffti(int n, float *wsave, int *ifac){
  116497. if (n == 1) return;
  116498. drfti1(n, wsave+n, ifac);
  116499. }
  116500. static void dradf2(int ido,int l1,float *cc,float *ch,float *wa1){
  116501. int i,k;
  116502. float ti2,tr2;
  116503. int t0,t1,t2,t3,t4,t5,t6;
  116504. t1=0;
  116505. t0=(t2=l1*ido);
  116506. t3=ido<<1;
  116507. for(k=0;k<l1;k++){
  116508. ch[t1<<1]=cc[t1]+cc[t2];
  116509. ch[(t1<<1)+t3-1]=cc[t1]-cc[t2];
  116510. t1+=ido;
  116511. t2+=ido;
  116512. }
  116513. if(ido<2)return;
  116514. if(ido==2)goto L105;
  116515. t1=0;
  116516. t2=t0;
  116517. for(k=0;k<l1;k++){
  116518. t3=t2;
  116519. t4=(t1<<1)+(ido<<1);
  116520. t5=t1;
  116521. t6=t1+t1;
  116522. for(i=2;i<ido;i+=2){
  116523. t3+=2;
  116524. t4-=2;
  116525. t5+=2;
  116526. t6+=2;
  116527. tr2=wa1[i-2]*cc[t3-1]+wa1[i-1]*cc[t3];
  116528. ti2=wa1[i-2]*cc[t3]-wa1[i-1]*cc[t3-1];
  116529. ch[t6]=cc[t5]+ti2;
  116530. ch[t4]=ti2-cc[t5];
  116531. ch[t6-1]=cc[t5-1]+tr2;
  116532. ch[t4-1]=cc[t5-1]-tr2;
  116533. }
  116534. t1+=ido;
  116535. t2+=ido;
  116536. }
  116537. if(ido%2==1)return;
  116538. L105:
  116539. t3=(t2=(t1=ido)-1);
  116540. t2+=t0;
  116541. for(k=0;k<l1;k++){
  116542. ch[t1]=-cc[t2];
  116543. ch[t1-1]=cc[t3];
  116544. t1+=ido<<1;
  116545. t2+=ido;
  116546. t3+=ido;
  116547. }
  116548. }
  116549. static void dradf4(int ido,int l1,float *cc,float *ch,float *wa1,
  116550. float *wa2,float *wa3){
  116551. static float hsqt2 = .70710678118654752f;
  116552. int i,k,t0,t1,t2,t3,t4,t5,t6;
  116553. float ci2,ci3,ci4,cr2,cr3,cr4,ti1,ti2,ti3,ti4,tr1,tr2,tr3,tr4;
  116554. t0=l1*ido;
  116555. t1=t0;
  116556. t4=t1<<1;
  116557. t2=t1+(t1<<1);
  116558. t3=0;
  116559. for(k=0;k<l1;k++){
  116560. tr1=cc[t1]+cc[t2];
  116561. tr2=cc[t3]+cc[t4];
  116562. ch[t5=t3<<2]=tr1+tr2;
  116563. ch[(ido<<2)+t5-1]=tr2-tr1;
  116564. ch[(t5+=(ido<<1))-1]=cc[t3]-cc[t4];
  116565. ch[t5]=cc[t2]-cc[t1];
  116566. t1+=ido;
  116567. t2+=ido;
  116568. t3+=ido;
  116569. t4+=ido;
  116570. }
  116571. if(ido<2)return;
  116572. if(ido==2)goto L105;
  116573. t1=0;
  116574. for(k=0;k<l1;k++){
  116575. t2=t1;
  116576. t4=t1<<2;
  116577. t5=(t6=ido<<1)+t4;
  116578. for(i=2;i<ido;i+=2){
  116579. t3=(t2+=2);
  116580. t4+=2;
  116581. t5-=2;
  116582. t3+=t0;
  116583. cr2=wa1[i-2]*cc[t3-1]+wa1[i-1]*cc[t3];
  116584. ci2=wa1[i-2]*cc[t3]-wa1[i-1]*cc[t3-1];
  116585. t3+=t0;
  116586. cr3=wa2[i-2]*cc[t3-1]+wa2[i-1]*cc[t3];
  116587. ci3=wa2[i-2]*cc[t3]-wa2[i-1]*cc[t3-1];
  116588. t3+=t0;
  116589. cr4=wa3[i-2]*cc[t3-1]+wa3[i-1]*cc[t3];
  116590. ci4=wa3[i-2]*cc[t3]-wa3[i-1]*cc[t3-1];
  116591. tr1=cr2+cr4;
  116592. tr4=cr4-cr2;
  116593. ti1=ci2+ci4;
  116594. ti4=ci2-ci4;
  116595. ti2=cc[t2]+ci3;
  116596. ti3=cc[t2]-ci3;
  116597. tr2=cc[t2-1]+cr3;
  116598. tr3=cc[t2-1]-cr3;
  116599. ch[t4-1]=tr1+tr2;
  116600. ch[t4]=ti1+ti2;
  116601. ch[t5-1]=tr3-ti4;
  116602. ch[t5]=tr4-ti3;
  116603. ch[t4+t6-1]=ti4+tr3;
  116604. ch[t4+t6]=tr4+ti3;
  116605. ch[t5+t6-1]=tr2-tr1;
  116606. ch[t5+t6]=ti1-ti2;
  116607. }
  116608. t1+=ido;
  116609. }
  116610. if(ido&1)return;
  116611. L105:
  116612. t2=(t1=t0+ido-1)+(t0<<1);
  116613. t3=ido<<2;
  116614. t4=ido;
  116615. t5=ido<<1;
  116616. t6=ido;
  116617. for(k=0;k<l1;k++){
  116618. ti1=-hsqt2*(cc[t1]+cc[t2]);
  116619. tr1=hsqt2*(cc[t1]-cc[t2]);
  116620. ch[t4-1]=tr1+cc[t6-1];
  116621. ch[t4+t5-1]=cc[t6-1]-tr1;
  116622. ch[t4]=ti1-cc[t1+t0];
  116623. ch[t4+t5]=ti1+cc[t1+t0];
  116624. t1+=ido;
  116625. t2+=ido;
  116626. t4+=t3;
  116627. t6+=ido;
  116628. }
  116629. }
  116630. static void dradfg(int ido,int ip,int l1,int idl1,float *cc,float *c1,
  116631. float *c2,float *ch,float *ch2,float *wa){
  116632. static float tpi=6.283185307179586f;
  116633. int idij,ipph,i,j,k,l,ic,ik,is;
  116634. int t0,t1,t2,t3,t4,t5,t6,t7,t8,t9,t10;
  116635. float dc2,ai1,ai2,ar1,ar2,ds2;
  116636. int nbd;
  116637. float dcp,arg,dsp,ar1h,ar2h;
  116638. int idp2,ipp2;
  116639. arg=tpi/(float)ip;
  116640. dcp=cos(arg);
  116641. dsp=sin(arg);
  116642. ipph=(ip+1)>>1;
  116643. ipp2=ip;
  116644. idp2=ido;
  116645. nbd=(ido-1)>>1;
  116646. t0=l1*ido;
  116647. t10=ip*ido;
  116648. if(ido==1)goto L119;
  116649. for(ik=0;ik<idl1;ik++)ch2[ik]=c2[ik];
  116650. t1=0;
  116651. for(j=1;j<ip;j++){
  116652. t1+=t0;
  116653. t2=t1;
  116654. for(k=0;k<l1;k++){
  116655. ch[t2]=c1[t2];
  116656. t2+=ido;
  116657. }
  116658. }
  116659. is=-ido;
  116660. t1=0;
  116661. if(nbd>l1){
  116662. for(j=1;j<ip;j++){
  116663. t1+=t0;
  116664. is+=ido;
  116665. t2= -ido+t1;
  116666. for(k=0;k<l1;k++){
  116667. idij=is-1;
  116668. t2+=ido;
  116669. t3=t2;
  116670. for(i=2;i<ido;i+=2){
  116671. idij+=2;
  116672. t3+=2;
  116673. ch[t3-1]=wa[idij-1]*c1[t3-1]+wa[idij]*c1[t3];
  116674. ch[t3]=wa[idij-1]*c1[t3]-wa[idij]*c1[t3-1];
  116675. }
  116676. }
  116677. }
  116678. }else{
  116679. for(j=1;j<ip;j++){
  116680. is+=ido;
  116681. idij=is-1;
  116682. t1+=t0;
  116683. t2=t1;
  116684. for(i=2;i<ido;i+=2){
  116685. idij+=2;
  116686. t2+=2;
  116687. t3=t2;
  116688. for(k=0;k<l1;k++){
  116689. ch[t3-1]=wa[idij-1]*c1[t3-1]+wa[idij]*c1[t3];
  116690. ch[t3]=wa[idij-1]*c1[t3]-wa[idij]*c1[t3-1];
  116691. t3+=ido;
  116692. }
  116693. }
  116694. }
  116695. }
  116696. t1=0;
  116697. t2=ipp2*t0;
  116698. if(nbd<l1){
  116699. for(j=1;j<ipph;j++){
  116700. t1+=t0;
  116701. t2-=t0;
  116702. t3=t1;
  116703. t4=t2;
  116704. for(i=2;i<ido;i+=2){
  116705. t3+=2;
  116706. t4+=2;
  116707. t5=t3-ido;
  116708. t6=t4-ido;
  116709. for(k=0;k<l1;k++){
  116710. t5+=ido;
  116711. t6+=ido;
  116712. c1[t5-1]=ch[t5-1]+ch[t6-1];
  116713. c1[t6-1]=ch[t5]-ch[t6];
  116714. c1[t5]=ch[t5]+ch[t6];
  116715. c1[t6]=ch[t6-1]-ch[t5-1];
  116716. }
  116717. }
  116718. }
  116719. }else{
  116720. for(j=1;j<ipph;j++){
  116721. t1+=t0;
  116722. t2-=t0;
  116723. t3=t1;
  116724. t4=t2;
  116725. for(k=0;k<l1;k++){
  116726. t5=t3;
  116727. t6=t4;
  116728. for(i=2;i<ido;i+=2){
  116729. t5+=2;
  116730. t6+=2;
  116731. c1[t5-1]=ch[t5-1]+ch[t6-1];
  116732. c1[t6-1]=ch[t5]-ch[t6];
  116733. c1[t5]=ch[t5]+ch[t6];
  116734. c1[t6]=ch[t6-1]-ch[t5-1];
  116735. }
  116736. t3+=ido;
  116737. t4+=ido;
  116738. }
  116739. }
  116740. }
  116741. L119:
  116742. for(ik=0;ik<idl1;ik++)c2[ik]=ch2[ik];
  116743. t1=0;
  116744. t2=ipp2*idl1;
  116745. for(j=1;j<ipph;j++){
  116746. t1+=t0;
  116747. t2-=t0;
  116748. t3=t1-ido;
  116749. t4=t2-ido;
  116750. for(k=0;k<l1;k++){
  116751. t3+=ido;
  116752. t4+=ido;
  116753. c1[t3]=ch[t3]+ch[t4];
  116754. c1[t4]=ch[t4]-ch[t3];
  116755. }
  116756. }
  116757. ar1=1.f;
  116758. ai1=0.f;
  116759. t1=0;
  116760. t2=ipp2*idl1;
  116761. t3=(ip-1)*idl1;
  116762. for(l=1;l<ipph;l++){
  116763. t1+=idl1;
  116764. t2-=idl1;
  116765. ar1h=dcp*ar1-dsp*ai1;
  116766. ai1=dcp*ai1+dsp*ar1;
  116767. ar1=ar1h;
  116768. t4=t1;
  116769. t5=t2;
  116770. t6=t3;
  116771. t7=idl1;
  116772. for(ik=0;ik<idl1;ik++){
  116773. ch2[t4++]=c2[ik]+ar1*c2[t7++];
  116774. ch2[t5++]=ai1*c2[t6++];
  116775. }
  116776. dc2=ar1;
  116777. ds2=ai1;
  116778. ar2=ar1;
  116779. ai2=ai1;
  116780. t4=idl1;
  116781. t5=(ipp2-1)*idl1;
  116782. for(j=2;j<ipph;j++){
  116783. t4+=idl1;
  116784. t5-=idl1;
  116785. ar2h=dc2*ar2-ds2*ai2;
  116786. ai2=dc2*ai2+ds2*ar2;
  116787. ar2=ar2h;
  116788. t6=t1;
  116789. t7=t2;
  116790. t8=t4;
  116791. t9=t5;
  116792. for(ik=0;ik<idl1;ik++){
  116793. ch2[t6++]+=ar2*c2[t8++];
  116794. ch2[t7++]+=ai2*c2[t9++];
  116795. }
  116796. }
  116797. }
  116798. t1=0;
  116799. for(j=1;j<ipph;j++){
  116800. t1+=idl1;
  116801. t2=t1;
  116802. for(ik=0;ik<idl1;ik++)ch2[ik]+=c2[t2++];
  116803. }
  116804. if(ido<l1)goto L132;
  116805. t1=0;
  116806. t2=0;
  116807. for(k=0;k<l1;k++){
  116808. t3=t1;
  116809. t4=t2;
  116810. for(i=0;i<ido;i++)cc[t4++]=ch[t3++];
  116811. t1+=ido;
  116812. t2+=t10;
  116813. }
  116814. goto L135;
  116815. L132:
  116816. for(i=0;i<ido;i++){
  116817. t1=i;
  116818. t2=i;
  116819. for(k=0;k<l1;k++){
  116820. cc[t2]=ch[t1];
  116821. t1+=ido;
  116822. t2+=t10;
  116823. }
  116824. }
  116825. L135:
  116826. t1=0;
  116827. t2=ido<<1;
  116828. t3=0;
  116829. t4=ipp2*t0;
  116830. for(j=1;j<ipph;j++){
  116831. t1+=t2;
  116832. t3+=t0;
  116833. t4-=t0;
  116834. t5=t1;
  116835. t6=t3;
  116836. t7=t4;
  116837. for(k=0;k<l1;k++){
  116838. cc[t5-1]=ch[t6];
  116839. cc[t5]=ch[t7];
  116840. t5+=t10;
  116841. t6+=ido;
  116842. t7+=ido;
  116843. }
  116844. }
  116845. if(ido==1)return;
  116846. if(nbd<l1)goto L141;
  116847. t1=-ido;
  116848. t3=0;
  116849. t4=0;
  116850. t5=ipp2*t0;
  116851. for(j=1;j<ipph;j++){
  116852. t1+=t2;
  116853. t3+=t2;
  116854. t4+=t0;
  116855. t5-=t0;
  116856. t6=t1;
  116857. t7=t3;
  116858. t8=t4;
  116859. t9=t5;
  116860. for(k=0;k<l1;k++){
  116861. for(i=2;i<ido;i+=2){
  116862. ic=idp2-i;
  116863. cc[i+t7-1]=ch[i+t8-1]+ch[i+t9-1];
  116864. cc[ic+t6-1]=ch[i+t8-1]-ch[i+t9-1];
  116865. cc[i+t7]=ch[i+t8]+ch[i+t9];
  116866. cc[ic+t6]=ch[i+t9]-ch[i+t8];
  116867. }
  116868. t6+=t10;
  116869. t7+=t10;
  116870. t8+=ido;
  116871. t9+=ido;
  116872. }
  116873. }
  116874. return;
  116875. L141:
  116876. t1=-ido;
  116877. t3=0;
  116878. t4=0;
  116879. t5=ipp2*t0;
  116880. for(j=1;j<ipph;j++){
  116881. t1+=t2;
  116882. t3+=t2;
  116883. t4+=t0;
  116884. t5-=t0;
  116885. for(i=2;i<ido;i+=2){
  116886. t6=idp2+t1-i;
  116887. t7=i+t3;
  116888. t8=i+t4;
  116889. t9=i+t5;
  116890. for(k=0;k<l1;k++){
  116891. cc[t7-1]=ch[t8-1]+ch[t9-1];
  116892. cc[t6-1]=ch[t8-1]-ch[t9-1];
  116893. cc[t7]=ch[t8]+ch[t9];
  116894. cc[t6]=ch[t9]-ch[t8];
  116895. t6+=t10;
  116896. t7+=t10;
  116897. t8+=ido;
  116898. t9+=ido;
  116899. }
  116900. }
  116901. }
  116902. }
  116903. static void drftf1(int n,float *c,float *ch,float *wa,int *ifac){
  116904. int i,k1,l1,l2;
  116905. int na,kh,nf;
  116906. int ip,iw,ido,idl1,ix2,ix3;
  116907. nf=ifac[1];
  116908. na=1;
  116909. l2=n;
  116910. iw=n;
  116911. for(k1=0;k1<nf;k1++){
  116912. kh=nf-k1;
  116913. ip=ifac[kh+1];
  116914. l1=l2/ip;
  116915. ido=n/l2;
  116916. idl1=ido*l1;
  116917. iw-=(ip-1)*ido;
  116918. na=1-na;
  116919. if(ip!=4)goto L102;
  116920. ix2=iw+ido;
  116921. ix3=ix2+ido;
  116922. if(na!=0)
  116923. dradf4(ido,l1,ch,c,wa+iw-1,wa+ix2-1,wa+ix3-1);
  116924. else
  116925. dradf4(ido,l1,c,ch,wa+iw-1,wa+ix2-1,wa+ix3-1);
  116926. goto L110;
  116927. L102:
  116928. if(ip!=2)goto L104;
  116929. if(na!=0)goto L103;
  116930. dradf2(ido,l1,c,ch,wa+iw-1);
  116931. goto L110;
  116932. L103:
  116933. dradf2(ido,l1,ch,c,wa+iw-1);
  116934. goto L110;
  116935. L104:
  116936. if(ido==1)na=1-na;
  116937. if(na!=0)goto L109;
  116938. dradfg(ido,ip,l1,idl1,c,c,c,ch,ch,wa+iw-1);
  116939. na=1;
  116940. goto L110;
  116941. L109:
  116942. dradfg(ido,ip,l1,idl1,ch,ch,ch,c,c,wa+iw-1);
  116943. na=0;
  116944. L110:
  116945. l2=l1;
  116946. }
  116947. if(na==1)return;
  116948. for(i=0;i<n;i++)c[i]=ch[i];
  116949. }
  116950. static void dradb2(int ido,int l1,float *cc,float *ch,float *wa1){
  116951. int i,k,t0,t1,t2,t3,t4,t5,t6;
  116952. float ti2,tr2;
  116953. t0=l1*ido;
  116954. t1=0;
  116955. t2=0;
  116956. t3=(ido<<1)-1;
  116957. for(k=0;k<l1;k++){
  116958. ch[t1]=cc[t2]+cc[t3+t2];
  116959. ch[t1+t0]=cc[t2]-cc[t3+t2];
  116960. t2=(t1+=ido)<<1;
  116961. }
  116962. if(ido<2)return;
  116963. if(ido==2)goto L105;
  116964. t1=0;
  116965. t2=0;
  116966. for(k=0;k<l1;k++){
  116967. t3=t1;
  116968. t5=(t4=t2)+(ido<<1);
  116969. t6=t0+t1;
  116970. for(i=2;i<ido;i+=2){
  116971. t3+=2;
  116972. t4+=2;
  116973. t5-=2;
  116974. t6+=2;
  116975. ch[t3-1]=cc[t4-1]+cc[t5-1];
  116976. tr2=cc[t4-1]-cc[t5-1];
  116977. ch[t3]=cc[t4]-cc[t5];
  116978. ti2=cc[t4]+cc[t5];
  116979. ch[t6-1]=wa1[i-2]*tr2-wa1[i-1]*ti2;
  116980. ch[t6]=wa1[i-2]*ti2+wa1[i-1]*tr2;
  116981. }
  116982. t2=(t1+=ido)<<1;
  116983. }
  116984. if(ido%2==1)return;
  116985. L105:
  116986. t1=ido-1;
  116987. t2=ido-1;
  116988. for(k=0;k<l1;k++){
  116989. ch[t1]=cc[t2]+cc[t2];
  116990. ch[t1+t0]=-(cc[t2+1]+cc[t2+1]);
  116991. t1+=ido;
  116992. t2+=ido<<1;
  116993. }
  116994. }
  116995. static void dradb3(int ido,int l1,float *cc,float *ch,float *wa1,
  116996. float *wa2){
  116997. static float taur = -.5f;
  116998. static float taui = .8660254037844386f;
  116999. int i,k,t0,t1,t2,t3,t4,t5,t6,t7,t8,t9,t10;
  117000. float ci2,ci3,di2,di3,cr2,cr3,dr2,dr3,ti2,tr2;
  117001. t0=l1*ido;
  117002. t1=0;
  117003. t2=t0<<1;
  117004. t3=ido<<1;
  117005. t4=ido+(ido<<1);
  117006. t5=0;
  117007. for(k=0;k<l1;k++){
  117008. tr2=cc[t3-1]+cc[t3-1];
  117009. cr2=cc[t5]+(taur*tr2);
  117010. ch[t1]=cc[t5]+tr2;
  117011. ci3=taui*(cc[t3]+cc[t3]);
  117012. ch[t1+t0]=cr2-ci3;
  117013. ch[t1+t2]=cr2+ci3;
  117014. t1+=ido;
  117015. t3+=t4;
  117016. t5+=t4;
  117017. }
  117018. if(ido==1)return;
  117019. t1=0;
  117020. t3=ido<<1;
  117021. for(k=0;k<l1;k++){
  117022. t7=t1+(t1<<1);
  117023. t6=(t5=t7+t3);
  117024. t8=t1;
  117025. t10=(t9=t1+t0)+t0;
  117026. for(i=2;i<ido;i+=2){
  117027. t5+=2;
  117028. t6-=2;
  117029. t7+=2;
  117030. t8+=2;
  117031. t9+=2;
  117032. t10+=2;
  117033. tr2=cc[t5-1]+cc[t6-1];
  117034. cr2=cc[t7-1]+(taur*tr2);
  117035. ch[t8-1]=cc[t7-1]+tr2;
  117036. ti2=cc[t5]-cc[t6];
  117037. ci2=cc[t7]+(taur*ti2);
  117038. ch[t8]=cc[t7]+ti2;
  117039. cr3=taui*(cc[t5-1]-cc[t6-1]);
  117040. ci3=taui*(cc[t5]+cc[t6]);
  117041. dr2=cr2-ci3;
  117042. dr3=cr2+ci3;
  117043. di2=ci2+cr3;
  117044. di3=ci2-cr3;
  117045. ch[t9-1]=wa1[i-2]*dr2-wa1[i-1]*di2;
  117046. ch[t9]=wa1[i-2]*di2+wa1[i-1]*dr2;
  117047. ch[t10-1]=wa2[i-2]*dr3-wa2[i-1]*di3;
  117048. ch[t10]=wa2[i-2]*di3+wa2[i-1]*dr3;
  117049. }
  117050. t1+=ido;
  117051. }
  117052. }
  117053. static void dradb4(int ido,int l1,float *cc,float *ch,float *wa1,
  117054. float *wa2,float *wa3){
  117055. static float sqrt2=1.414213562373095f;
  117056. int i,k,t0,t1,t2,t3,t4,t5,t6,t7,t8;
  117057. float ci2,ci3,ci4,cr2,cr3,cr4,ti1,ti2,ti3,ti4,tr1,tr2,tr3,tr4;
  117058. t0=l1*ido;
  117059. t1=0;
  117060. t2=ido<<2;
  117061. t3=0;
  117062. t6=ido<<1;
  117063. for(k=0;k<l1;k++){
  117064. t4=t3+t6;
  117065. t5=t1;
  117066. tr3=cc[t4-1]+cc[t4-1];
  117067. tr4=cc[t4]+cc[t4];
  117068. tr1=cc[t3]-cc[(t4+=t6)-1];
  117069. tr2=cc[t3]+cc[t4-1];
  117070. ch[t5]=tr2+tr3;
  117071. ch[t5+=t0]=tr1-tr4;
  117072. ch[t5+=t0]=tr2-tr3;
  117073. ch[t5+=t0]=tr1+tr4;
  117074. t1+=ido;
  117075. t3+=t2;
  117076. }
  117077. if(ido<2)return;
  117078. if(ido==2)goto L105;
  117079. t1=0;
  117080. for(k=0;k<l1;k++){
  117081. t5=(t4=(t3=(t2=t1<<2)+t6))+t6;
  117082. t7=t1;
  117083. for(i=2;i<ido;i+=2){
  117084. t2+=2;
  117085. t3+=2;
  117086. t4-=2;
  117087. t5-=2;
  117088. t7+=2;
  117089. ti1=cc[t2]+cc[t5];
  117090. ti2=cc[t2]-cc[t5];
  117091. ti3=cc[t3]-cc[t4];
  117092. tr4=cc[t3]+cc[t4];
  117093. tr1=cc[t2-1]-cc[t5-1];
  117094. tr2=cc[t2-1]+cc[t5-1];
  117095. ti4=cc[t3-1]-cc[t4-1];
  117096. tr3=cc[t3-1]+cc[t4-1];
  117097. ch[t7-1]=tr2+tr3;
  117098. cr3=tr2-tr3;
  117099. ch[t7]=ti2+ti3;
  117100. ci3=ti2-ti3;
  117101. cr2=tr1-tr4;
  117102. cr4=tr1+tr4;
  117103. ci2=ti1+ti4;
  117104. ci4=ti1-ti4;
  117105. ch[(t8=t7+t0)-1]=wa1[i-2]*cr2-wa1[i-1]*ci2;
  117106. ch[t8]=wa1[i-2]*ci2+wa1[i-1]*cr2;
  117107. ch[(t8+=t0)-1]=wa2[i-2]*cr3-wa2[i-1]*ci3;
  117108. ch[t8]=wa2[i-2]*ci3+wa2[i-1]*cr3;
  117109. ch[(t8+=t0)-1]=wa3[i-2]*cr4-wa3[i-1]*ci4;
  117110. ch[t8]=wa3[i-2]*ci4+wa3[i-1]*cr4;
  117111. }
  117112. t1+=ido;
  117113. }
  117114. if(ido%2 == 1)return;
  117115. L105:
  117116. t1=ido;
  117117. t2=ido<<2;
  117118. t3=ido-1;
  117119. t4=ido+(ido<<1);
  117120. for(k=0;k<l1;k++){
  117121. t5=t3;
  117122. ti1=cc[t1]+cc[t4];
  117123. ti2=cc[t4]-cc[t1];
  117124. tr1=cc[t1-1]-cc[t4-1];
  117125. tr2=cc[t1-1]+cc[t4-1];
  117126. ch[t5]=tr2+tr2;
  117127. ch[t5+=t0]=sqrt2*(tr1-ti1);
  117128. ch[t5+=t0]=ti2+ti2;
  117129. ch[t5+=t0]=-sqrt2*(tr1+ti1);
  117130. t3+=ido;
  117131. t1+=t2;
  117132. t4+=t2;
  117133. }
  117134. }
  117135. static void dradbg(int ido,int ip,int l1,int idl1,float *cc,float *c1,
  117136. float *c2,float *ch,float *ch2,float *wa){
  117137. static float tpi=6.283185307179586f;
  117138. int idij,ipph,i,j,k,l,ik,is,t0,t1,t2,t3,t4,t5,t6,t7,t8,t9,t10,
  117139. t11,t12;
  117140. float dc2,ai1,ai2,ar1,ar2,ds2;
  117141. int nbd;
  117142. float dcp,arg,dsp,ar1h,ar2h;
  117143. int ipp2;
  117144. t10=ip*ido;
  117145. t0=l1*ido;
  117146. arg=tpi/(float)ip;
  117147. dcp=cos(arg);
  117148. dsp=sin(arg);
  117149. nbd=(ido-1)>>1;
  117150. ipp2=ip;
  117151. ipph=(ip+1)>>1;
  117152. if(ido<l1)goto L103;
  117153. t1=0;
  117154. t2=0;
  117155. for(k=0;k<l1;k++){
  117156. t3=t1;
  117157. t4=t2;
  117158. for(i=0;i<ido;i++){
  117159. ch[t3]=cc[t4];
  117160. t3++;
  117161. t4++;
  117162. }
  117163. t1+=ido;
  117164. t2+=t10;
  117165. }
  117166. goto L106;
  117167. L103:
  117168. t1=0;
  117169. for(i=0;i<ido;i++){
  117170. t2=t1;
  117171. t3=t1;
  117172. for(k=0;k<l1;k++){
  117173. ch[t2]=cc[t3];
  117174. t2+=ido;
  117175. t3+=t10;
  117176. }
  117177. t1++;
  117178. }
  117179. L106:
  117180. t1=0;
  117181. t2=ipp2*t0;
  117182. t7=(t5=ido<<1);
  117183. for(j=1;j<ipph;j++){
  117184. t1+=t0;
  117185. t2-=t0;
  117186. t3=t1;
  117187. t4=t2;
  117188. t6=t5;
  117189. for(k=0;k<l1;k++){
  117190. ch[t3]=cc[t6-1]+cc[t6-1];
  117191. ch[t4]=cc[t6]+cc[t6];
  117192. t3+=ido;
  117193. t4+=ido;
  117194. t6+=t10;
  117195. }
  117196. t5+=t7;
  117197. }
  117198. if (ido == 1)goto L116;
  117199. if(nbd<l1)goto L112;
  117200. t1=0;
  117201. t2=ipp2*t0;
  117202. t7=0;
  117203. for(j=1;j<ipph;j++){
  117204. t1+=t0;
  117205. t2-=t0;
  117206. t3=t1;
  117207. t4=t2;
  117208. t7+=(ido<<1);
  117209. t8=t7;
  117210. for(k=0;k<l1;k++){
  117211. t5=t3;
  117212. t6=t4;
  117213. t9=t8;
  117214. t11=t8;
  117215. for(i=2;i<ido;i+=2){
  117216. t5+=2;
  117217. t6+=2;
  117218. t9+=2;
  117219. t11-=2;
  117220. ch[t5-1]=cc[t9-1]+cc[t11-1];
  117221. ch[t6-1]=cc[t9-1]-cc[t11-1];
  117222. ch[t5]=cc[t9]-cc[t11];
  117223. ch[t6]=cc[t9]+cc[t11];
  117224. }
  117225. t3+=ido;
  117226. t4+=ido;
  117227. t8+=t10;
  117228. }
  117229. }
  117230. goto L116;
  117231. L112:
  117232. t1=0;
  117233. t2=ipp2*t0;
  117234. t7=0;
  117235. for(j=1;j<ipph;j++){
  117236. t1+=t0;
  117237. t2-=t0;
  117238. t3=t1;
  117239. t4=t2;
  117240. t7+=(ido<<1);
  117241. t8=t7;
  117242. t9=t7;
  117243. for(i=2;i<ido;i+=2){
  117244. t3+=2;
  117245. t4+=2;
  117246. t8+=2;
  117247. t9-=2;
  117248. t5=t3;
  117249. t6=t4;
  117250. t11=t8;
  117251. t12=t9;
  117252. for(k=0;k<l1;k++){
  117253. ch[t5-1]=cc[t11-1]+cc[t12-1];
  117254. ch[t6-1]=cc[t11-1]-cc[t12-1];
  117255. ch[t5]=cc[t11]-cc[t12];
  117256. ch[t6]=cc[t11]+cc[t12];
  117257. t5+=ido;
  117258. t6+=ido;
  117259. t11+=t10;
  117260. t12+=t10;
  117261. }
  117262. }
  117263. }
  117264. L116:
  117265. ar1=1.f;
  117266. ai1=0.f;
  117267. t1=0;
  117268. t9=(t2=ipp2*idl1);
  117269. t3=(ip-1)*idl1;
  117270. for(l=1;l<ipph;l++){
  117271. t1+=idl1;
  117272. t2-=idl1;
  117273. ar1h=dcp*ar1-dsp*ai1;
  117274. ai1=dcp*ai1+dsp*ar1;
  117275. ar1=ar1h;
  117276. t4=t1;
  117277. t5=t2;
  117278. t6=0;
  117279. t7=idl1;
  117280. t8=t3;
  117281. for(ik=0;ik<idl1;ik++){
  117282. c2[t4++]=ch2[t6++]+ar1*ch2[t7++];
  117283. c2[t5++]=ai1*ch2[t8++];
  117284. }
  117285. dc2=ar1;
  117286. ds2=ai1;
  117287. ar2=ar1;
  117288. ai2=ai1;
  117289. t6=idl1;
  117290. t7=t9-idl1;
  117291. for(j=2;j<ipph;j++){
  117292. t6+=idl1;
  117293. t7-=idl1;
  117294. ar2h=dc2*ar2-ds2*ai2;
  117295. ai2=dc2*ai2+ds2*ar2;
  117296. ar2=ar2h;
  117297. t4=t1;
  117298. t5=t2;
  117299. t11=t6;
  117300. t12=t7;
  117301. for(ik=0;ik<idl1;ik++){
  117302. c2[t4++]+=ar2*ch2[t11++];
  117303. c2[t5++]+=ai2*ch2[t12++];
  117304. }
  117305. }
  117306. }
  117307. t1=0;
  117308. for(j=1;j<ipph;j++){
  117309. t1+=idl1;
  117310. t2=t1;
  117311. for(ik=0;ik<idl1;ik++)ch2[ik]+=ch2[t2++];
  117312. }
  117313. t1=0;
  117314. t2=ipp2*t0;
  117315. for(j=1;j<ipph;j++){
  117316. t1+=t0;
  117317. t2-=t0;
  117318. t3=t1;
  117319. t4=t2;
  117320. for(k=0;k<l1;k++){
  117321. ch[t3]=c1[t3]-c1[t4];
  117322. ch[t4]=c1[t3]+c1[t4];
  117323. t3+=ido;
  117324. t4+=ido;
  117325. }
  117326. }
  117327. if(ido==1)goto L132;
  117328. if(nbd<l1)goto L128;
  117329. t1=0;
  117330. t2=ipp2*t0;
  117331. for(j=1;j<ipph;j++){
  117332. t1+=t0;
  117333. t2-=t0;
  117334. t3=t1;
  117335. t4=t2;
  117336. for(k=0;k<l1;k++){
  117337. t5=t3;
  117338. t6=t4;
  117339. for(i=2;i<ido;i+=2){
  117340. t5+=2;
  117341. t6+=2;
  117342. ch[t5-1]=c1[t5-1]-c1[t6];
  117343. ch[t6-1]=c1[t5-1]+c1[t6];
  117344. ch[t5]=c1[t5]+c1[t6-1];
  117345. ch[t6]=c1[t5]-c1[t6-1];
  117346. }
  117347. t3+=ido;
  117348. t4+=ido;
  117349. }
  117350. }
  117351. goto L132;
  117352. L128:
  117353. t1=0;
  117354. t2=ipp2*t0;
  117355. for(j=1;j<ipph;j++){
  117356. t1+=t0;
  117357. t2-=t0;
  117358. t3=t1;
  117359. t4=t2;
  117360. for(i=2;i<ido;i+=2){
  117361. t3+=2;
  117362. t4+=2;
  117363. t5=t3;
  117364. t6=t4;
  117365. for(k=0;k<l1;k++){
  117366. ch[t5-1]=c1[t5-1]-c1[t6];
  117367. ch[t6-1]=c1[t5-1]+c1[t6];
  117368. ch[t5]=c1[t5]+c1[t6-1];
  117369. ch[t6]=c1[t5]-c1[t6-1];
  117370. t5+=ido;
  117371. t6+=ido;
  117372. }
  117373. }
  117374. }
  117375. L132:
  117376. if(ido==1)return;
  117377. for(ik=0;ik<idl1;ik++)c2[ik]=ch2[ik];
  117378. t1=0;
  117379. for(j=1;j<ip;j++){
  117380. t2=(t1+=t0);
  117381. for(k=0;k<l1;k++){
  117382. c1[t2]=ch[t2];
  117383. t2+=ido;
  117384. }
  117385. }
  117386. if(nbd>l1)goto L139;
  117387. is= -ido-1;
  117388. t1=0;
  117389. for(j=1;j<ip;j++){
  117390. is+=ido;
  117391. t1+=t0;
  117392. idij=is;
  117393. t2=t1;
  117394. for(i=2;i<ido;i+=2){
  117395. t2+=2;
  117396. idij+=2;
  117397. t3=t2;
  117398. for(k=0;k<l1;k++){
  117399. c1[t3-1]=wa[idij-1]*ch[t3-1]-wa[idij]*ch[t3];
  117400. c1[t3]=wa[idij-1]*ch[t3]+wa[idij]*ch[t3-1];
  117401. t3+=ido;
  117402. }
  117403. }
  117404. }
  117405. return;
  117406. L139:
  117407. is= -ido-1;
  117408. t1=0;
  117409. for(j=1;j<ip;j++){
  117410. is+=ido;
  117411. t1+=t0;
  117412. t2=t1;
  117413. for(k=0;k<l1;k++){
  117414. idij=is;
  117415. t3=t2;
  117416. for(i=2;i<ido;i+=2){
  117417. idij+=2;
  117418. t3+=2;
  117419. c1[t3-1]=wa[idij-1]*ch[t3-1]-wa[idij]*ch[t3];
  117420. c1[t3]=wa[idij-1]*ch[t3]+wa[idij]*ch[t3-1];
  117421. }
  117422. t2+=ido;
  117423. }
  117424. }
  117425. }
  117426. static void drftb1(int n, float *c, float *ch, float *wa, int *ifac){
  117427. int i,k1,l1,l2;
  117428. int na;
  117429. int nf,ip,iw,ix2,ix3,ido,idl1;
  117430. nf=ifac[1];
  117431. na=0;
  117432. l1=1;
  117433. iw=1;
  117434. for(k1=0;k1<nf;k1++){
  117435. ip=ifac[k1 + 2];
  117436. l2=ip*l1;
  117437. ido=n/l2;
  117438. idl1=ido*l1;
  117439. if(ip!=4)goto L103;
  117440. ix2=iw+ido;
  117441. ix3=ix2+ido;
  117442. if(na!=0)
  117443. dradb4(ido,l1,ch,c,wa+iw-1,wa+ix2-1,wa+ix3-1);
  117444. else
  117445. dradb4(ido,l1,c,ch,wa+iw-1,wa+ix2-1,wa+ix3-1);
  117446. na=1-na;
  117447. goto L115;
  117448. L103:
  117449. if(ip!=2)goto L106;
  117450. if(na!=0)
  117451. dradb2(ido,l1,ch,c,wa+iw-1);
  117452. else
  117453. dradb2(ido,l1,c,ch,wa+iw-1);
  117454. na=1-na;
  117455. goto L115;
  117456. L106:
  117457. if(ip!=3)goto L109;
  117458. ix2=iw+ido;
  117459. if(na!=0)
  117460. dradb3(ido,l1,ch,c,wa+iw-1,wa+ix2-1);
  117461. else
  117462. dradb3(ido,l1,c,ch,wa+iw-1,wa+ix2-1);
  117463. na=1-na;
  117464. goto L115;
  117465. L109:
  117466. /* The radix five case can be translated later..... */
  117467. /* if(ip!=5)goto L112;
  117468. ix2=iw+ido;
  117469. ix3=ix2+ido;
  117470. ix4=ix3+ido;
  117471. if(na!=0)
  117472. dradb5(ido,l1,ch,c,wa+iw-1,wa+ix2-1,wa+ix3-1,wa+ix4-1);
  117473. else
  117474. dradb5(ido,l1,c,ch,wa+iw-1,wa+ix2-1,wa+ix3-1,wa+ix4-1);
  117475. na=1-na;
  117476. goto L115;
  117477. L112:*/
  117478. if(na!=0)
  117479. dradbg(ido,ip,l1,idl1,ch,ch,ch,c,c,wa+iw-1);
  117480. else
  117481. dradbg(ido,ip,l1,idl1,c,c,c,ch,ch,wa+iw-1);
  117482. if(ido==1)na=1-na;
  117483. L115:
  117484. l1=l2;
  117485. iw+=(ip-1)*ido;
  117486. }
  117487. if(na==0)return;
  117488. for(i=0;i<n;i++)c[i]=ch[i];
  117489. }
  117490. void drft_forward(drft_lookup *l,float *data){
  117491. if(l->n==1)return;
  117492. drftf1(l->n,data,l->trigcache,l->trigcache+l->n,l->splitcache);
  117493. }
  117494. void drft_backward(drft_lookup *l,float *data){
  117495. if (l->n==1)return;
  117496. drftb1(l->n,data,l->trigcache,l->trigcache+l->n,l->splitcache);
  117497. }
  117498. void drft_init(drft_lookup *l,int n){
  117499. l->n=n;
  117500. l->trigcache=(float*)_ogg_calloc(3*n,sizeof(*l->trigcache));
  117501. l->splitcache=(int*)_ogg_calloc(32,sizeof(*l->splitcache));
  117502. fdrffti(n, l->trigcache, l->splitcache);
  117503. }
  117504. void drft_clear(drft_lookup *l){
  117505. if(l){
  117506. if(l->trigcache)_ogg_free(l->trigcache);
  117507. if(l->splitcache)_ogg_free(l->splitcache);
  117508. memset(l,0,sizeof(*l));
  117509. }
  117510. }
  117511. #endif
  117512. /*** End of inlined file: smallft.c ***/
  117513. /*** Start of inlined file: synthesis.c ***/
  117514. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  117515. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  117516. // tasks..
  117517. #if JUCE_MSVC
  117518. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  117519. #endif
  117520. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  117521. #if JUCE_USE_OGGVORBIS
  117522. #include <stdio.h>
  117523. int vorbis_synthesis(vorbis_block *vb,ogg_packet *op){
  117524. vorbis_dsp_state *vd=vb->vd;
  117525. private_state *b=(private_state*)vd->backend_state;
  117526. vorbis_info *vi=vd->vi;
  117527. codec_setup_info *ci=(codec_setup_info*) vi->codec_setup;
  117528. oggpack_buffer *opb=&vb->opb;
  117529. int type,mode,i;
  117530. /* first things first. Make sure decode is ready */
  117531. _vorbis_block_ripcord(vb);
  117532. oggpack_readinit(opb,op->packet,op->bytes);
  117533. /* Check the packet type */
  117534. if(oggpack_read(opb,1)!=0){
  117535. /* Oops. This is not an audio data packet */
  117536. return(OV_ENOTAUDIO);
  117537. }
  117538. /* read our mode and pre/post windowsize */
  117539. mode=oggpack_read(opb,b->modebits);
  117540. if(mode==-1)return(OV_EBADPACKET);
  117541. vb->mode=mode;
  117542. vb->W=ci->mode_param[mode]->blockflag;
  117543. if(vb->W){
  117544. /* this doesn;t get mapped through mode selection as it's used
  117545. only for window selection */
  117546. vb->lW=oggpack_read(opb,1);
  117547. vb->nW=oggpack_read(opb,1);
  117548. if(vb->nW==-1) return(OV_EBADPACKET);
  117549. }else{
  117550. vb->lW=0;
  117551. vb->nW=0;
  117552. }
  117553. /* more setup */
  117554. vb->granulepos=op->granulepos;
  117555. vb->sequence=op->packetno;
  117556. vb->eofflag=op->e_o_s;
  117557. /* alloc pcm passback storage */
  117558. vb->pcmend=ci->blocksizes[vb->W];
  117559. vb->pcm=(float**)_vorbis_block_alloc(vb,sizeof(*vb->pcm)*vi->channels);
  117560. for(i=0;i<vi->channels;i++)
  117561. vb->pcm[i]=(float*)_vorbis_block_alloc(vb,vb->pcmend*sizeof(*vb->pcm[i]));
  117562. /* unpack_header enforces range checking */
  117563. type=ci->map_type[ci->mode_param[mode]->mapping];
  117564. return(_mapping_P[type]->inverse(vb,ci->map_param[ci->mode_param[mode]->
  117565. mapping]));
  117566. }
  117567. /* used to track pcm position without actually performing decode.
  117568. Useful for sequential 'fast forward' */
  117569. int vorbis_synthesis_trackonly(vorbis_block *vb,ogg_packet *op){
  117570. vorbis_dsp_state *vd=vb->vd;
  117571. private_state *b=(private_state*)vd->backend_state;
  117572. vorbis_info *vi=vd->vi;
  117573. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  117574. oggpack_buffer *opb=&vb->opb;
  117575. int mode;
  117576. /* first things first. Make sure decode is ready */
  117577. _vorbis_block_ripcord(vb);
  117578. oggpack_readinit(opb,op->packet,op->bytes);
  117579. /* Check the packet type */
  117580. if(oggpack_read(opb,1)!=0){
  117581. /* Oops. This is not an audio data packet */
  117582. return(OV_ENOTAUDIO);
  117583. }
  117584. /* read our mode and pre/post windowsize */
  117585. mode=oggpack_read(opb,b->modebits);
  117586. if(mode==-1)return(OV_EBADPACKET);
  117587. vb->mode=mode;
  117588. vb->W=ci->mode_param[mode]->blockflag;
  117589. if(vb->W){
  117590. vb->lW=oggpack_read(opb,1);
  117591. vb->nW=oggpack_read(opb,1);
  117592. if(vb->nW==-1) return(OV_EBADPACKET);
  117593. }else{
  117594. vb->lW=0;
  117595. vb->nW=0;
  117596. }
  117597. /* more setup */
  117598. vb->granulepos=op->granulepos;
  117599. vb->sequence=op->packetno;
  117600. vb->eofflag=op->e_o_s;
  117601. /* no pcm */
  117602. vb->pcmend=0;
  117603. vb->pcm=NULL;
  117604. return(0);
  117605. }
  117606. long vorbis_packet_blocksize(vorbis_info *vi,ogg_packet *op){
  117607. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  117608. oggpack_buffer opb;
  117609. int mode;
  117610. oggpack_readinit(&opb,op->packet,op->bytes);
  117611. /* Check the packet type */
  117612. if(oggpack_read(&opb,1)!=0){
  117613. /* Oops. This is not an audio data packet */
  117614. return(OV_ENOTAUDIO);
  117615. }
  117616. {
  117617. int modebits=0;
  117618. int v=ci->modes;
  117619. while(v>1){
  117620. modebits++;
  117621. v>>=1;
  117622. }
  117623. /* read our mode and pre/post windowsize */
  117624. mode=oggpack_read(&opb,modebits);
  117625. }
  117626. if(mode==-1)return(OV_EBADPACKET);
  117627. return(ci->blocksizes[ci->mode_param[mode]->blockflag]);
  117628. }
  117629. int vorbis_synthesis_halfrate(vorbis_info *vi,int flag){
  117630. /* set / clear half-sample-rate mode */
  117631. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  117632. /* right now, our MDCT can't handle < 64 sample windows. */
  117633. if(ci->blocksizes[0]<=64 && flag)return -1;
  117634. ci->halfrate_flag=(flag?1:0);
  117635. return 0;
  117636. }
  117637. int vorbis_synthesis_halfrate_p(vorbis_info *vi){
  117638. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  117639. return ci->halfrate_flag;
  117640. }
  117641. #endif
  117642. /*** End of inlined file: synthesis.c ***/
  117643. /*** Start of inlined file: vorbisenc.c ***/
  117644. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  117645. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  117646. // tasks..
  117647. #if JUCE_MSVC
  117648. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  117649. #endif
  117650. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  117651. #if JUCE_USE_OGGVORBIS
  117652. #include <stdlib.h>
  117653. #include <string.h>
  117654. #include <math.h>
  117655. /* careful with this; it's using static array sizing to make managing
  117656. all the modes a little less annoying. If we use a residue backend
  117657. with > 12 partition types, or a different division of iteration,
  117658. this needs to be updated. */
  117659. typedef struct {
  117660. static_codebook *books[12][3];
  117661. } static_bookblock;
  117662. typedef struct {
  117663. int res_type;
  117664. int limit_type; /* 0 lowpass limited, 1 point stereo limited */
  117665. vorbis_info_residue0 *res;
  117666. static_codebook *book_aux;
  117667. static_codebook *book_aux_managed;
  117668. static_bookblock *books_base;
  117669. static_bookblock *books_base_managed;
  117670. } vorbis_residue_template;
  117671. typedef struct {
  117672. vorbis_info_mapping0 *map;
  117673. vorbis_residue_template *res;
  117674. } vorbis_mapping_template;
  117675. typedef struct vp_adjblock{
  117676. int block[P_BANDS];
  117677. } vp_adjblock;
  117678. typedef struct {
  117679. int data[NOISE_COMPAND_LEVELS];
  117680. } compandblock;
  117681. /* high level configuration information for setting things up
  117682. step-by-step with the detailed vorbis_encode_ctl interface.
  117683. There's a fair amount of redundancy such that interactive setup
  117684. does not directly deal with any vorbis_info or codec_setup_info
  117685. initialization; it's all stored (until full init) in this highlevel
  117686. setup, then flushed out to the real codec setup structs later. */
  117687. typedef struct {
  117688. int att[P_NOISECURVES];
  117689. float boost;
  117690. float decay;
  117691. } att3;
  117692. typedef struct { int data[P_NOISECURVES]; } adj3;
  117693. typedef struct {
  117694. int pre[PACKETBLOBS];
  117695. int post[PACKETBLOBS];
  117696. float kHz[PACKETBLOBS];
  117697. float lowpasskHz[PACKETBLOBS];
  117698. } adj_stereo;
  117699. typedef struct {
  117700. int lo;
  117701. int hi;
  117702. int fixed;
  117703. } noiseguard;
  117704. typedef struct {
  117705. int data[P_NOISECURVES][17];
  117706. } noise3;
  117707. typedef struct {
  117708. int mappings;
  117709. double *rate_mapping;
  117710. double *quality_mapping;
  117711. int coupling_restriction;
  117712. long samplerate_min_restriction;
  117713. long samplerate_max_restriction;
  117714. int *blocksize_short;
  117715. int *blocksize_long;
  117716. att3 *psy_tone_masteratt;
  117717. int *psy_tone_0dB;
  117718. int *psy_tone_dBsuppress;
  117719. vp_adjblock *psy_tone_adj_impulse;
  117720. vp_adjblock *psy_tone_adj_long;
  117721. vp_adjblock *psy_tone_adj_other;
  117722. noiseguard *psy_noiseguards;
  117723. noise3 *psy_noise_bias_impulse;
  117724. noise3 *psy_noise_bias_padding;
  117725. noise3 *psy_noise_bias_trans;
  117726. noise3 *psy_noise_bias_long;
  117727. int *psy_noise_dBsuppress;
  117728. compandblock *psy_noise_compand;
  117729. double *psy_noise_compand_short_mapping;
  117730. double *psy_noise_compand_long_mapping;
  117731. int *psy_noise_normal_start[2];
  117732. int *psy_noise_normal_partition[2];
  117733. double *psy_noise_normal_thresh;
  117734. int *psy_ath_float;
  117735. int *psy_ath_abs;
  117736. double *psy_lowpass;
  117737. vorbis_info_psy_global *global_params;
  117738. double *global_mapping;
  117739. adj_stereo *stereo_modes;
  117740. static_codebook ***floor_books;
  117741. vorbis_info_floor1 *floor_params;
  117742. int *floor_short_mapping;
  117743. int *floor_long_mapping;
  117744. vorbis_mapping_template *maps;
  117745. } ve_setup_data_template;
  117746. /* a few static coder conventions */
  117747. static vorbis_info_mode _mode_template[2]={
  117748. {0,0,0,0},
  117749. {1,0,0,1}
  117750. };
  117751. static vorbis_info_mapping0 _map_nominal[2]={
  117752. {1, {0,0}, {0}, {0}, 1,{0},{1}},
  117753. {1, {0,0}, {1}, {1}, 1,{0},{1}}
  117754. };
  117755. /*** Start of inlined file: setup_44.h ***/
  117756. /*** Start of inlined file: floor_all.h ***/
  117757. /*** Start of inlined file: floor_books.h ***/
  117758. static long _huff_lengthlist_line_256x7_0sub1[] = {
  117759. 0, 2, 3, 3, 3, 3, 4, 3, 4,
  117760. };
  117761. static static_codebook _huff_book_line_256x7_0sub1 = {
  117762. 1, 9,
  117763. _huff_lengthlist_line_256x7_0sub1,
  117764. 0, 0, 0, 0, 0,
  117765. NULL,
  117766. NULL,
  117767. NULL,
  117768. NULL,
  117769. 0
  117770. };
  117771. static long _huff_lengthlist_line_256x7_0sub2[] = {
  117772. 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 4, 3, 4, 3, 5, 3,
  117773. 6, 3, 6, 4, 6, 4, 7, 5, 7,
  117774. };
  117775. static static_codebook _huff_book_line_256x7_0sub2 = {
  117776. 1, 25,
  117777. _huff_lengthlist_line_256x7_0sub2,
  117778. 0, 0, 0, 0, 0,
  117779. NULL,
  117780. NULL,
  117781. NULL,
  117782. NULL,
  117783. 0
  117784. };
  117785. static long _huff_lengthlist_line_256x7_0sub3[] = {
  117786. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117787. 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 5, 2, 5, 3, 5, 3,
  117788. 6, 3, 6, 4, 7, 6, 7, 8, 7, 9, 8, 9, 9, 9,10, 9,
  117789. 11,13,11,13,10,10,13,13,13,13,13,13,12,12,12,12,
  117790. };
  117791. static static_codebook _huff_book_line_256x7_0sub3 = {
  117792. 1, 64,
  117793. _huff_lengthlist_line_256x7_0sub3,
  117794. 0, 0, 0, 0, 0,
  117795. NULL,
  117796. NULL,
  117797. NULL,
  117798. NULL,
  117799. 0
  117800. };
  117801. static long _huff_lengthlist_line_256x7_1sub1[] = {
  117802. 0, 3, 3, 3, 3, 2, 4, 3, 4,
  117803. };
  117804. static static_codebook _huff_book_line_256x7_1sub1 = {
  117805. 1, 9,
  117806. _huff_lengthlist_line_256x7_1sub1,
  117807. 0, 0, 0, 0, 0,
  117808. NULL,
  117809. NULL,
  117810. NULL,
  117811. NULL,
  117812. 0
  117813. };
  117814. static long _huff_lengthlist_line_256x7_1sub2[] = {
  117815. 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 3, 3, 4, 3, 4, 4,
  117816. 5, 4, 6, 5, 6, 7, 6, 8, 8,
  117817. };
  117818. static static_codebook _huff_book_line_256x7_1sub2 = {
  117819. 1, 25,
  117820. _huff_lengthlist_line_256x7_1sub2,
  117821. 0, 0, 0, 0, 0,
  117822. NULL,
  117823. NULL,
  117824. NULL,
  117825. NULL,
  117826. 0
  117827. };
  117828. static long _huff_lengthlist_line_256x7_1sub3[] = {
  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, 3, 2, 4, 3, 6, 3, 7,
  117831. 3, 8, 5, 8, 6, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  117832. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 7,
  117833. };
  117834. static static_codebook _huff_book_line_256x7_1sub3 = {
  117835. 1, 64,
  117836. _huff_lengthlist_line_256x7_1sub3,
  117837. 0, 0, 0, 0, 0,
  117838. NULL,
  117839. NULL,
  117840. NULL,
  117841. NULL,
  117842. 0
  117843. };
  117844. static long _huff_lengthlist_line_256x7_class0[] = {
  117845. 7, 5, 5, 9, 9, 6, 6, 9,12, 8, 7, 8,11, 8, 9,15,
  117846. 6, 3, 3, 7, 7, 4, 3, 6, 9, 6, 5, 6, 8, 6, 8,15,
  117847. 8, 5, 5, 9, 8, 5, 4, 6,10, 7, 5, 5,11, 8, 7,15,
  117848. 14,15,13,13,13,13, 8,11,15,10, 7, 6,11, 9,10,15,
  117849. };
  117850. static static_codebook _huff_book_line_256x7_class0 = {
  117851. 1, 64,
  117852. _huff_lengthlist_line_256x7_class0,
  117853. 0, 0, 0, 0, 0,
  117854. NULL,
  117855. NULL,
  117856. NULL,
  117857. NULL,
  117858. 0
  117859. };
  117860. static long _huff_lengthlist_line_256x7_class1[] = {
  117861. 5, 6, 8,15, 6, 9,10,15,10,11,12,15,15,15,15,15,
  117862. 4, 6, 7,15, 6, 7, 8,15, 9, 8, 9,15,15,15,15,15,
  117863. 6, 8, 9,15, 7, 7, 8,15,10, 9,10,15,15,15,15,15,
  117864. 15,13,15,15,15,10,11,15,15,13,13,15,15,15,15,15,
  117865. 4, 6, 7,15, 6, 8, 9,15,10,10,12,15,15,15,15,15,
  117866. 2, 5, 6,15, 5, 6, 7,15, 8, 6, 7,15,15,15,15,15,
  117867. 5, 6, 8,15, 5, 6, 7,15, 9, 6, 7,15,15,15,15,15,
  117868. 14,12,13,15,12,10,11,15,15,15,15,15,15,15,15,15,
  117869. 7, 8, 9,15, 9,10,10,15,15,14,14,15,15,15,15,15,
  117870. 5, 6, 7,15, 7, 8, 9,15,12, 9,10,15,15,15,15,15,
  117871. 7, 7, 9,15, 7, 7, 8,15,12, 8, 9,15,15,15,15,15,
  117872. 13,13,14,15,12,11,12,15,15,15,15,15,15,15,15,15,
  117873. 15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,
  117874. 13,13,13,15,15,15,15,15,15,15,15,15,15,15,15,15,
  117875. 15,12,13,15,15,12,13,15,15,14,15,15,15,15,15,15,
  117876. 15,15,15,15,15,15,13,15,15,15,15,15,15,15,15,15,
  117877. };
  117878. static static_codebook _huff_book_line_256x7_class1 = {
  117879. 1, 256,
  117880. _huff_lengthlist_line_256x7_class1,
  117881. 0, 0, 0, 0, 0,
  117882. NULL,
  117883. NULL,
  117884. NULL,
  117885. NULL,
  117886. 0
  117887. };
  117888. static long _huff_lengthlist_line_512x17_0sub0[] = {
  117889. 4, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5,
  117890. 5, 6, 5, 6, 6, 6, 6, 5, 6, 6, 7, 6, 7, 6, 7, 6,
  117891. 7, 6, 8, 7, 8, 7, 8, 7, 8, 7, 8, 7, 9, 7, 9, 7,
  117892. 9, 7, 9, 8, 9, 8,10, 8,10, 8,10, 7,10, 6,10, 8,
  117893. 10, 8,11, 7,10, 7,11, 8,11,11,12,12,11,11,12,11,
  117894. 13,11,13,11,13,12,15,12,13,13,14,14,14,14,14,15,
  117895. 15,15,16,14,17,19,19,18,18,18,18,18,18,18,18,18,
  117896. 18,18,18,18,18,18,18,18,18,18,18,18,18,18,18,18,
  117897. };
  117898. static static_codebook _huff_book_line_512x17_0sub0 = {
  117899. 1, 128,
  117900. _huff_lengthlist_line_512x17_0sub0,
  117901. 0, 0, 0, 0, 0,
  117902. NULL,
  117903. NULL,
  117904. NULL,
  117905. NULL,
  117906. 0
  117907. };
  117908. static long _huff_lengthlist_line_512x17_1sub0[] = {
  117909. 2, 4, 5, 4, 5, 4, 5, 4, 5, 5, 5, 5, 5, 5, 6, 5,
  117910. 6, 5, 6, 6, 7, 6, 7, 6, 8, 7, 8, 7, 8, 7, 8, 7,
  117911. };
  117912. static static_codebook _huff_book_line_512x17_1sub0 = {
  117913. 1, 32,
  117914. _huff_lengthlist_line_512x17_1sub0,
  117915. 0, 0, 0, 0, 0,
  117916. NULL,
  117917. NULL,
  117918. NULL,
  117919. NULL,
  117920. 0
  117921. };
  117922. static long _huff_lengthlist_line_512x17_1sub1[] = {
  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. 4, 3, 5, 3, 5, 4, 5, 4, 5, 4, 5, 5, 5, 5, 6, 5,
  117926. 6, 5, 7, 5, 8, 6, 8, 6, 8, 6, 8, 6, 8, 7, 9, 7,
  117927. 9, 7,11, 9,11,11,12,11,14,12,14,16,14,16,13,16,
  117928. 14,16,12,15,13,16,14,16,13,14,12,15,13,15,13,13,
  117929. 13,15,12,14,14,15,13,15,12,15,15,15,15,15,15,15,
  117930. 15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,
  117931. };
  117932. static static_codebook _huff_book_line_512x17_1sub1 = {
  117933. 1, 128,
  117934. _huff_lengthlist_line_512x17_1sub1,
  117935. 0, 0, 0, 0, 0,
  117936. NULL,
  117937. NULL,
  117938. NULL,
  117939. NULL,
  117940. 0
  117941. };
  117942. static long _huff_lengthlist_line_512x17_2sub1[] = {
  117943. 0, 4, 5, 4, 4, 4, 5, 4, 4, 4, 5, 4, 5, 4, 5, 3,
  117944. 5, 3,
  117945. };
  117946. static static_codebook _huff_book_line_512x17_2sub1 = {
  117947. 1, 18,
  117948. _huff_lengthlist_line_512x17_2sub1,
  117949. 0, 0, 0, 0, 0,
  117950. NULL,
  117951. NULL,
  117952. NULL,
  117953. NULL,
  117954. 0
  117955. };
  117956. static long _huff_lengthlist_line_512x17_2sub2[] = {
  117957. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117958. 0, 0, 4, 3, 4, 3, 4, 4, 5, 4, 5, 4, 6, 4, 6, 5,
  117959. 6, 5, 7, 5, 7, 6, 8, 6, 8, 6, 8, 7, 8, 7, 9, 7,
  117960. 9, 8,
  117961. };
  117962. static static_codebook _huff_book_line_512x17_2sub2 = {
  117963. 1, 50,
  117964. _huff_lengthlist_line_512x17_2sub2,
  117965. 0, 0, 0, 0, 0,
  117966. NULL,
  117967. NULL,
  117968. NULL,
  117969. NULL,
  117970. 0
  117971. };
  117972. static long _huff_lengthlist_line_512x17_2sub3[] = {
  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, 3, 3, 3, 3, 4, 3, 4, 4, 5, 5, 6, 6, 7, 7,
  117977. 7, 8, 8,11, 8, 9, 9, 9,10,11,11,11, 9,10,10,11,
  117978. 11,11,11,10,10,10,10,10,10,10,10,10,10,10,10,10,
  117979. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  117980. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  117981. };
  117982. static static_codebook _huff_book_line_512x17_2sub3 = {
  117983. 1, 128,
  117984. _huff_lengthlist_line_512x17_2sub3,
  117985. 0, 0, 0, 0, 0,
  117986. NULL,
  117987. NULL,
  117988. NULL,
  117989. NULL,
  117990. 0
  117991. };
  117992. static long _huff_lengthlist_line_512x17_3sub1[] = {
  117993. 0, 4, 4, 4, 4, 4, 4, 3, 4, 4, 4, 4, 4, 5, 4, 5,
  117994. 5, 5,
  117995. };
  117996. static static_codebook _huff_book_line_512x17_3sub1 = {
  117997. 1, 18,
  117998. _huff_lengthlist_line_512x17_3sub1,
  117999. 0, 0, 0, 0, 0,
  118000. NULL,
  118001. NULL,
  118002. NULL,
  118003. NULL,
  118004. 0
  118005. };
  118006. static long _huff_lengthlist_line_512x17_3sub2[] = {
  118007. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118008. 0, 0, 2, 3, 3, 4, 3, 5, 4, 6, 4, 6, 5, 7, 6, 7,
  118009. 6, 8, 6, 8, 7, 9, 8,10, 8,12, 9,13,10,15,10,15,
  118010. 11,14,
  118011. };
  118012. static static_codebook _huff_book_line_512x17_3sub2 = {
  118013. 1, 50,
  118014. _huff_lengthlist_line_512x17_3sub2,
  118015. 0, 0, 0, 0, 0,
  118016. NULL,
  118017. NULL,
  118018. NULL,
  118019. NULL,
  118020. 0
  118021. };
  118022. static long _huff_lengthlist_line_512x17_3sub3[] = {
  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, 4, 8, 4, 8, 4, 8, 4, 8, 5, 8, 5, 8, 6, 8,
  118027. 4, 8, 4, 8, 5, 8, 5, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  118028. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  118029. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  118030. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  118031. };
  118032. static static_codebook _huff_book_line_512x17_3sub3 = {
  118033. 1, 128,
  118034. _huff_lengthlist_line_512x17_3sub3,
  118035. 0, 0, 0, 0, 0,
  118036. NULL,
  118037. NULL,
  118038. NULL,
  118039. NULL,
  118040. 0
  118041. };
  118042. static long _huff_lengthlist_line_512x17_class1[] = {
  118043. 1, 2, 3, 6, 5, 4, 7, 7,
  118044. };
  118045. static static_codebook _huff_book_line_512x17_class1 = {
  118046. 1, 8,
  118047. _huff_lengthlist_line_512x17_class1,
  118048. 0, 0, 0, 0, 0,
  118049. NULL,
  118050. NULL,
  118051. NULL,
  118052. NULL,
  118053. 0
  118054. };
  118055. static long _huff_lengthlist_line_512x17_class2[] = {
  118056. 3, 3, 3,14, 5, 4, 4,11, 8, 6, 6,10,17,12,11,17,
  118057. 6, 5, 5,15, 5, 3, 4,11, 8, 5, 5, 8,16, 9,10,14,
  118058. 10, 8, 9,17, 8, 6, 6,13,10, 7, 7,10,16,11,13,14,
  118059. 17,17,17,17,17,16,16,16,16,15,16,16,16,16,16,16,
  118060. };
  118061. static static_codebook _huff_book_line_512x17_class2 = {
  118062. 1, 64,
  118063. _huff_lengthlist_line_512x17_class2,
  118064. 0, 0, 0, 0, 0,
  118065. NULL,
  118066. NULL,
  118067. NULL,
  118068. NULL,
  118069. 0
  118070. };
  118071. static long _huff_lengthlist_line_512x17_class3[] = {
  118072. 2, 4, 6,17, 4, 5, 7,17, 8, 7,10,17,17,17,17,17,
  118073. 3, 4, 6,15, 3, 3, 6,15, 7, 6, 9,17,17,17,17,17,
  118074. 6, 8,10,17, 6, 6, 8,16, 9, 8,10,17,17,15,16,17,
  118075. 17,17,17,17,12,15,15,16,12,15,15,16,16,16,16,16,
  118076. };
  118077. static static_codebook _huff_book_line_512x17_class3 = {
  118078. 1, 64,
  118079. _huff_lengthlist_line_512x17_class3,
  118080. 0, 0, 0, 0, 0,
  118081. NULL,
  118082. NULL,
  118083. NULL,
  118084. NULL,
  118085. 0
  118086. };
  118087. static long _huff_lengthlist_line_128x4_class0[] = {
  118088. 7, 7, 7,11, 6, 6, 7,11, 7, 6, 6,10,12,10,10,13,
  118089. 7, 7, 8,11, 7, 7, 7,11, 7, 6, 7,10,11,10,10,13,
  118090. 10,10, 9,12, 9, 9, 9,11, 8, 8, 8,11,13,11,10,14,
  118091. 15,15,14,15,15,14,13,14,15,12,12,17,17,17,17,17,
  118092. 7, 7, 6, 9, 6, 6, 6, 9, 7, 6, 6, 8,11,11,10,12,
  118093. 7, 7, 7, 9, 7, 6, 6, 9, 7, 6, 6, 9,13,10,10,11,
  118094. 10, 9, 8,10, 9, 8, 8,10, 8, 8, 7, 9,13,12,10,11,
  118095. 17,14,14,13,15,14,12,13,17,13,12,15,17,17,14,17,
  118096. 7, 6, 6, 7, 6, 6, 5, 7, 6, 6, 6, 6,11, 9, 9, 9,
  118097. 7, 7, 6, 7, 7, 6, 6, 7, 6, 6, 6, 6,10, 9, 8, 9,
  118098. 10, 9, 8, 8, 9, 8, 7, 8, 8, 7, 6, 8,11,10, 9,10,
  118099. 17,17,12,15,15,15,12,14,14,14,10,12,15,13,12,13,
  118100. 11,10, 8,10,11,10, 8, 8,10, 9, 7, 7,10, 9, 9,11,
  118101. 11,11, 9,10,11,10, 8, 9,10, 8, 6, 8,10, 9, 9,11,
  118102. 14,13,10,12,12,11,10,10, 8, 7, 8,10,10,11,11,12,
  118103. 17,17,15,17,17,17,17,17,17,13,12,17,17,17,14,17,
  118104. };
  118105. static static_codebook _huff_book_line_128x4_class0 = {
  118106. 1, 256,
  118107. _huff_lengthlist_line_128x4_class0,
  118108. 0, 0, 0, 0, 0,
  118109. NULL,
  118110. NULL,
  118111. NULL,
  118112. NULL,
  118113. 0
  118114. };
  118115. static long _huff_lengthlist_line_128x4_0sub0[] = {
  118116. 2, 2, 2, 2,
  118117. };
  118118. static static_codebook _huff_book_line_128x4_0sub0 = {
  118119. 1, 4,
  118120. _huff_lengthlist_line_128x4_0sub0,
  118121. 0, 0, 0, 0, 0,
  118122. NULL,
  118123. NULL,
  118124. NULL,
  118125. NULL,
  118126. 0
  118127. };
  118128. static long _huff_lengthlist_line_128x4_0sub1[] = {
  118129. 0, 0, 0, 0, 3, 2, 3, 2, 3, 3,
  118130. };
  118131. static static_codebook _huff_book_line_128x4_0sub1 = {
  118132. 1, 10,
  118133. _huff_lengthlist_line_128x4_0sub1,
  118134. 0, 0, 0, 0, 0,
  118135. NULL,
  118136. NULL,
  118137. NULL,
  118138. NULL,
  118139. 0
  118140. };
  118141. static long _huff_lengthlist_line_128x4_0sub2[] = {
  118142. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 3, 4, 3, 4, 3,
  118143. 4, 4, 5, 4, 5, 4, 6, 5, 6,
  118144. };
  118145. static static_codebook _huff_book_line_128x4_0sub2 = {
  118146. 1, 25,
  118147. _huff_lengthlist_line_128x4_0sub2,
  118148. 0, 0, 0, 0, 0,
  118149. NULL,
  118150. NULL,
  118151. NULL,
  118152. NULL,
  118153. 0
  118154. };
  118155. static long _huff_lengthlist_line_128x4_0sub3[] = {
  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, 2, 4, 3, 5, 3, 5, 3,
  118158. 5, 4, 6, 5, 6, 5, 7, 6, 6, 7, 7, 9, 9,11,11,16,
  118159. 11,14,10,11,11,13,16,15,15,15,15,15,15,15,15,15,
  118160. };
  118161. static static_codebook _huff_book_line_128x4_0sub3 = {
  118162. 1, 64,
  118163. _huff_lengthlist_line_128x4_0sub3,
  118164. 0, 0, 0, 0, 0,
  118165. NULL,
  118166. NULL,
  118167. NULL,
  118168. NULL,
  118169. 0
  118170. };
  118171. static long _huff_lengthlist_line_256x4_class0[] = {
  118172. 6, 7, 7,12, 6, 6, 7,12, 7, 6, 6,10,15,12,11,13,
  118173. 7, 7, 8,13, 7, 7, 8,12, 7, 7, 7,11,12,12,11,13,
  118174. 10, 9, 9,11, 9, 9, 9,10,10, 8, 8,12,14,12,12,14,
  118175. 11,11,12,14,11,12,11,15,15,12,13,15,15,15,15,15,
  118176. 6, 6, 7,10, 6, 6, 6,11, 7, 6, 6, 9,14,12,11,13,
  118177. 7, 7, 7,10, 6, 6, 7, 9, 7, 7, 6,10,13,12,10,12,
  118178. 9, 9, 9,11, 9, 9, 8, 9, 9, 8, 8,10,13,12,10,12,
  118179. 12,12,11,13,12,12,11,12,15,13,12,15,15,15,14,14,
  118180. 6, 6, 6, 8, 6, 6, 5, 6, 7, 7, 6, 5,11,10, 9, 8,
  118181. 7, 6, 6, 7, 6, 6, 5, 6, 7, 7, 6, 6,11,10, 9, 8,
  118182. 8, 8, 8, 9, 8, 8, 7, 8, 8, 8, 6, 7,11,10, 9, 9,
  118183. 14,11,10,14,14,11,10,15,13,11, 9,11,15,12,12,11,
  118184. 11, 9, 8, 8,10, 9, 8, 9,11,10, 9, 8,12,11,12,11,
  118185. 13,10, 8, 9,11,10, 8, 9,10, 9, 8, 9,10, 8,12,12,
  118186. 15,11,10,10,13,11,10,10, 8, 8, 7,12,10, 9,11,12,
  118187. 15,12,11,15,13,11,11,15,12,14,11,13,15,15,13,13,
  118188. };
  118189. static static_codebook _huff_book_line_256x4_class0 = {
  118190. 1, 256,
  118191. _huff_lengthlist_line_256x4_class0,
  118192. 0, 0, 0, 0, 0,
  118193. NULL,
  118194. NULL,
  118195. NULL,
  118196. NULL,
  118197. 0
  118198. };
  118199. static long _huff_lengthlist_line_256x4_0sub0[] = {
  118200. 2, 2, 2, 2,
  118201. };
  118202. static static_codebook _huff_book_line_256x4_0sub0 = {
  118203. 1, 4,
  118204. _huff_lengthlist_line_256x4_0sub0,
  118205. 0, 0, 0, 0, 0,
  118206. NULL,
  118207. NULL,
  118208. NULL,
  118209. NULL,
  118210. 0
  118211. };
  118212. static long _huff_lengthlist_line_256x4_0sub1[] = {
  118213. 0, 0, 0, 0, 2, 2, 3, 3, 3, 3,
  118214. };
  118215. static static_codebook _huff_book_line_256x4_0sub1 = {
  118216. 1, 10,
  118217. _huff_lengthlist_line_256x4_0sub1,
  118218. 0, 0, 0, 0, 0,
  118219. NULL,
  118220. NULL,
  118221. NULL,
  118222. NULL,
  118223. 0
  118224. };
  118225. static long _huff_lengthlist_line_256x4_0sub2[] = {
  118226. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 3, 4, 3, 4, 3,
  118227. 5, 3, 5, 4, 5, 4, 6, 4, 6,
  118228. };
  118229. static static_codebook _huff_book_line_256x4_0sub2 = {
  118230. 1, 25,
  118231. _huff_lengthlist_line_256x4_0sub2,
  118232. 0, 0, 0, 0, 0,
  118233. NULL,
  118234. NULL,
  118235. NULL,
  118236. NULL,
  118237. 0
  118238. };
  118239. static long _huff_lengthlist_line_256x4_0sub3[] = {
  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, 2, 4, 3, 5, 3, 5, 3,
  118242. 6, 4, 7, 4, 7, 5, 7, 6, 7, 6, 7, 8,10,13,13,13,
  118243. 13,13,13,13,13,13,13,13,13,13,13,12,12,12,12,12,
  118244. };
  118245. static static_codebook _huff_book_line_256x4_0sub3 = {
  118246. 1, 64,
  118247. _huff_lengthlist_line_256x4_0sub3,
  118248. 0, 0, 0, 0, 0,
  118249. NULL,
  118250. NULL,
  118251. NULL,
  118252. NULL,
  118253. 0
  118254. };
  118255. static long _huff_lengthlist_line_128x7_class0[] = {
  118256. 10, 7, 8,13, 9, 6, 7,11,10, 8, 8,12,17,17,17,17,
  118257. 7, 5, 5, 9, 6, 4, 4, 8, 8, 5, 5, 8,16,14,13,16,
  118258. 7, 5, 5, 7, 6, 3, 3, 5, 8, 5, 4, 7,14,12,12,15,
  118259. 10, 7, 8, 9, 7, 5, 5, 6, 9, 6, 5, 5,15,12, 9,10,
  118260. };
  118261. static static_codebook _huff_book_line_128x7_class0 = {
  118262. 1, 64,
  118263. _huff_lengthlist_line_128x7_class0,
  118264. 0, 0, 0, 0, 0,
  118265. NULL,
  118266. NULL,
  118267. NULL,
  118268. NULL,
  118269. 0
  118270. };
  118271. static long _huff_lengthlist_line_128x7_class1[] = {
  118272. 8,13,17,17, 8,11,17,17,11,13,17,17,17,17,17,17,
  118273. 6,10,16,17, 6,10,15,17, 8,10,16,17,17,17,17,17,
  118274. 9,13,15,17, 8,11,17,17,10,12,17,17,17,17,17,17,
  118275. 17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,
  118276. 6,11,15,17, 7,10,15,17, 8,10,17,17,17,15,17,17,
  118277. 4, 8,13,17, 4, 7,13,17, 6, 8,15,17,16,15,17,17,
  118278. 6,11,15,17, 6, 9,13,17, 8,10,17,17,15,17,17,17,
  118279. 16,17,17,17,12,14,15,17,13,14,15,17,17,17,17,17,
  118280. 5,10,14,17, 5, 9,14,17, 7, 9,15,17,15,15,17,17,
  118281. 3, 7,12,17, 3, 6,11,17, 5, 7,13,17,12,12,17,17,
  118282. 5, 9,14,17, 3, 7,11,17, 5, 8,13,17,13,11,16,17,
  118283. 12,17,17,17, 9,14,15,17,10,11,14,17,16,14,17,17,
  118284. 8,12,17,17, 8,12,17,17,10,12,17,17,17,17,17,17,
  118285. 5,10,17,17, 5, 9,15,17, 7, 9,17,17,13,13,17,17,
  118286. 7,11,17,17, 6,10,15,17, 7, 9,15,17,12,11,17,17,
  118287. 12,15,17,17,11,14,17,17,11,10,15,17,17,16,17,17,
  118288. };
  118289. static static_codebook _huff_book_line_128x7_class1 = {
  118290. 1, 256,
  118291. _huff_lengthlist_line_128x7_class1,
  118292. 0, 0, 0, 0, 0,
  118293. NULL,
  118294. NULL,
  118295. NULL,
  118296. NULL,
  118297. 0
  118298. };
  118299. static long _huff_lengthlist_line_128x7_0sub1[] = {
  118300. 0, 3, 3, 3, 3, 3, 3, 3, 3,
  118301. };
  118302. static static_codebook _huff_book_line_128x7_0sub1 = {
  118303. 1, 9,
  118304. _huff_lengthlist_line_128x7_0sub1,
  118305. 0, 0, 0, 0, 0,
  118306. NULL,
  118307. NULL,
  118308. NULL,
  118309. NULL,
  118310. 0
  118311. };
  118312. static long _huff_lengthlist_line_128x7_0sub2[] = {
  118313. 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 3, 3, 4, 4, 4, 4,
  118314. 5, 4, 5, 4, 5, 4, 6, 4, 6,
  118315. };
  118316. static static_codebook _huff_book_line_128x7_0sub2 = {
  118317. 1, 25,
  118318. _huff_lengthlist_line_128x7_0sub2,
  118319. 0, 0, 0, 0, 0,
  118320. NULL,
  118321. NULL,
  118322. NULL,
  118323. NULL,
  118324. 0
  118325. };
  118326. static long _huff_lengthlist_line_128x7_0sub3[] = {
  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, 3, 5, 3, 5, 3, 5, 4,
  118329. 5, 4, 5, 5, 5, 5, 6, 5, 6, 5, 6, 5, 6, 5, 6, 5,
  118330. 7, 8, 9,11,13,13,13,13,13,13,13,13,13,13,13,13,
  118331. };
  118332. static static_codebook _huff_book_line_128x7_0sub3 = {
  118333. 1, 64,
  118334. _huff_lengthlist_line_128x7_0sub3,
  118335. 0, 0, 0, 0, 0,
  118336. NULL,
  118337. NULL,
  118338. NULL,
  118339. NULL,
  118340. 0
  118341. };
  118342. static long _huff_lengthlist_line_128x7_1sub1[] = {
  118343. 0, 3, 3, 2, 3, 3, 4, 3, 4,
  118344. };
  118345. static static_codebook _huff_book_line_128x7_1sub1 = {
  118346. 1, 9,
  118347. _huff_lengthlist_line_128x7_1sub1,
  118348. 0, 0, 0, 0, 0,
  118349. NULL,
  118350. NULL,
  118351. NULL,
  118352. NULL,
  118353. 0
  118354. };
  118355. static long _huff_lengthlist_line_128x7_1sub2[] = {
  118356. 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 4, 3, 6, 3, 6, 3,
  118357. 6, 3, 7, 3, 8, 4, 9, 4, 9,
  118358. };
  118359. static static_codebook _huff_book_line_128x7_1sub2 = {
  118360. 1, 25,
  118361. _huff_lengthlist_line_128x7_1sub2,
  118362. 0, 0, 0, 0, 0,
  118363. NULL,
  118364. NULL,
  118365. NULL,
  118366. NULL,
  118367. 0
  118368. };
  118369. static long _huff_lengthlist_line_128x7_1sub3[] = {
  118370. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118371. 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 7, 2, 7, 3, 8, 4,
  118372. 9, 5, 9, 8,10,11,11,12,14,14,14,14,14,14,14,14,
  118373. 14,14,14,14,14,14,14,14,14,14,14,14,13,13,13,13,
  118374. };
  118375. static static_codebook _huff_book_line_128x7_1sub3 = {
  118376. 1, 64,
  118377. _huff_lengthlist_line_128x7_1sub3,
  118378. 0, 0, 0, 0, 0,
  118379. NULL,
  118380. NULL,
  118381. NULL,
  118382. NULL,
  118383. 0
  118384. };
  118385. static long _huff_lengthlist_line_128x11_class1[] = {
  118386. 1, 6, 3, 7, 2, 4, 5, 7,
  118387. };
  118388. static static_codebook _huff_book_line_128x11_class1 = {
  118389. 1, 8,
  118390. _huff_lengthlist_line_128x11_class1,
  118391. 0, 0, 0, 0, 0,
  118392. NULL,
  118393. NULL,
  118394. NULL,
  118395. NULL,
  118396. 0
  118397. };
  118398. static long _huff_lengthlist_line_128x11_class2[] = {
  118399. 1, 6,12,16, 4,12,15,16, 9,15,16,16,16,16,16,16,
  118400. 2, 5,11,16, 5,11,13,16, 9,13,16,16,16,16,16,16,
  118401. 4, 8,12,16, 5, 9,12,16, 9,13,15,16,16,16,16,16,
  118402. 15,16,16,16,11,14,13,16,12,15,16,16,16,16,16,15,
  118403. };
  118404. static static_codebook _huff_book_line_128x11_class2 = {
  118405. 1, 64,
  118406. _huff_lengthlist_line_128x11_class2,
  118407. 0, 0, 0, 0, 0,
  118408. NULL,
  118409. NULL,
  118410. NULL,
  118411. NULL,
  118412. 0
  118413. };
  118414. static long _huff_lengthlist_line_128x11_class3[] = {
  118415. 7, 6, 9,17, 7, 6, 8,17,12, 9,11,16,16,16,16,16,
  118416. 5, 4, 7,16, 5, 3, 6,14, 9, 6, 8,15,16,16,16,16,
  118417. 5, 4, 6,13, 3, 2, 4,11, 7, 4, 6,13,16,11,10,14,
  118418. 12,12,12,16, 9, 7,10,15,12, 9,11,16,16,15,15,16,
  118419. };
  118420. static static_codebook _huff_book_line_128x11_class3 = {
  118421. 1, 64,
  118422. _huff_lengthlist_line_128x11_class3,
  118423. 0, 0, 0, 0, 0,
  118424. NULL,
  118425. NULL,
  118426. NULL,
  118427. NULL,
  118428. 0
  118429. };
  118430. static long _huff_lengthlist_line_128x11_0sub0[] = {
  118431. 5, 5, 5, 5, 5, 5, 6, 5, 6, 5, 6, 5, 6, 5, 6, 5,
  118432. 6, 5, 6, 5, 6, 5, 6, 5, 6, 5, 6, 6, 6, 6, 7, 6,
  118433. 7, 6, 7, 6, 7, 6, 7, 6, 7, 6, 8, 6, 8, 6, 8, 7,
  118434. 8, 7, 8, 7, 8, 7, 9, 7, 9, 8, 9, 8, 9, 8,10, 8,
  118435. 10, 9,10, 9,10, 9,11, 9,11, 9,10,10,11,10,11,10,
  118436. 11,11,11,11,11,11,12,13,14,14,14,15,15,16,16,16,
  118437. 17,15,16,15,16,16,17,17,16,17,17,17,17,17,17,17,
  118438. 17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,
  118439. };
  118440. static static_codebook _huff_book_line_128x11_0sub0 = {
  118441. 1, 128,
  118442. _huff_lengthlist_line_128x11_0sub0,
  118443. 0, 0, 0, 0, 0,
  118444. NULL,
  118445. NULL,
  118446. NULL,
  118447. NULL,
  118448. 0
  118449. };
  118450. static long _huff_lengthlist_line_128x11_1sub0[] = {
  118451. 2, 5, 5, 5, 5, 5, 5, 4, 5, 5, 5, 5, 5, 5, 5, 5,
  118452. 6, 5, 6, 5, 6, 5, 7, 6, 7, 6, 7, 6, 8, 6, 8, 6,
  118453. };
  118454. static static_codebook _huff_book_line_128x11_1sub0 = {
  118455. 1, 32,
  118456. _huff_lengthlist_line_128x11_1sub0,
  118457. 0, 0, 0, 0, 0,
  118458. NULL,
  118459. NULL,
  118460. NULL,
  118461. NULL,
  118462. 0
  118463. };
  118464. static long _huff_lengthlist_line_128x11_1sub1[] = {
  118465. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118466. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118467. 5, 3, 5, 3, 6, 4, 6, 4, 7, 4, 7, 4, 7, 4, 8, 4,
  118468. 8, 4, 9, 5, 9, 5, 9, 5, 9, 6,10, 6,10, 6,11, 7,
  118469. 10, 7,10, 8,11, 9,11, 9,11,10,11,11,12,11,11,12,
  118470. 15,15,12,14,11,14,12,14,11,14,13,14,12,14,11,14,
  118471. 11,14,12,14,11,14,11,14,13,13,14,14,14,14,14,14,
  118472. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  118473. };
  118474. static static_codebook _huff_book_line_128x11_1sub1 = {
  118475. 1, 128,
  118476. _huff_lengthlist_line_128x11_1sub1,
  118477. 0, 0, 0, 0, 0,
  118478. NULL,
  118479. NULL,
  118480. NULL,
  118481. NULL,
  118482. 0
  118483. };
  118484. static long _huff_lengthlist_line_128x11_2sub1[] = {
  118485. 0, 4, 5, 4, 5, 4, 5, 3, 5, 3, 5, 3, 5, 4, 4, 4,
  118486. 5, 5,
  118487. };
  118488. static static_codebook _huff_book_line_128x11_2sub1 = {
  118489. 1, 18,
  118490. _huff_lengthlist_line_128x11_2sub1,
  118491. 0, 0, 0, 0, 0,
  118492. NULL,
  118493. NULL,
  118494. NULL,
  118495. NULL,
  118496. 0
  118497. };
  118498. static long _huff_lengthlist_line_128x11_2sub2[] = {
  118499. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118500. 0, 0, 3, 3, 3, 4, 4, 4, 4, 5, 4, 5, 4, 6, 5, 7,
  118501. 5, 7, 6, 8, 6, 8, 6, 9, 7, 9, 7,10, 7, 9, 8,11,
  118502. 8,11,
  118503. };
  118504. static static_codebook _huff_book_line_128x11_2sub2 = {
  118505. 1, 50,
  118506. _huff_lengthlist_line_128x11_2sub2,
  118507. 0, 0, 0, 0, 0,
  118508. NULL,
  118509. NULL,
  118510. NULL,
  118511. NULL,
  118512. 0
  118513. };
  118514. static long _huff_lengthlist_line_128x11_2sub3[] = {
  118515. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118516. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118517. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118518. 0, 0, 4, 8, 3, 8, 4, 8, 4, 8, 6, 8, 5, 8, 4, 8,
  118519. 4, 8, 6, 8, 7, 8, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  118520. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  118521. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  118522. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  118523. };
  118524. static static_codebook _huff_book_line_128x11_2sub3 = {
  118525. 1, 128,
  118526. _huff_lengthlist_line_128x11_2sub3,
  118527. 0, 0, 0, 0, 0,
  118528. NULL,
  118529. NULL,
  118530. NULL,
  118531. NULL,
  118532. 0
  118533. };
  118534. static long _huff_lengthlist_line_128x11_3sub1[] = {
  118535. 0, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 5, 4,
  118536. 5, 4,
  118537. };
  118538. static static_codebook _huff_book_line_128x11_3sub1 = {
  118539. 1, 18,
  118540. _huff_lengthlist_line_128x11_3sub1,
  118541. 0, 0, 0, 0, 0,
  118542. NULL,
  118543. NULL,
  118544. NULL,
  118545. NULL,
  118546. 0
  118547. };
  118548. static long _huff_lengthlist_line_128x11_3sub2[] = {
  118549. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118550. 0, 0, 5, 3, 5, 4, 6, 4, 6, 4, 7, 4, 7, 4, 8, 4,
  118551. 8, 4, 9, 4, 9, 4,10, 4,10, 5,10, 5,11, 5,12, 6,
  118552. 12, 6,
  118553. };
  118554. static static_codebook _huff_book_line_128x11_3sub2 = {
  118555. 1, 50,
  118556. _huff_lengthlist_line_128x11_3sub2,
  118557. 0, 0, 0, 0, 0,
  118558. NULL,
  118559. NULL,
  118560. NULL,
  118561. NULL,
  118562. 0
  118563. };
  118564. static long _huff_lengthlist_line_128x11_3sub3[] = {
  118565. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118566. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118567. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118568. 0, 0, 7, 1, 6, 3, 7, 3, 8, 4, 8, 5, 8, 8, 8, 9,
  118569. 7, 8, 8, 7, 7, 7, 8, 9,10, 9, 9,10,10,10,10,10,
  118570. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  118571. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  118572. 10,10,10,10,10,10,10,10,10,10,10,10,10,10, 9, 9,
  118573. };
  118574. static static_codebook _huff_book_line_128x11_3sub3 = {
  118575. 1, 128,
  118576. _huff_lengthlist_line_128x11_3sub3,
  118577. 0, 0, 0, 0, 0,
  118578. NULL,
  118579. NULL,
  118580. NULL,
  118581. NULL,
  118582. 0
  118583. };
  118584. static long _huff_lengthlist_line_128x17_class1[] = {
  118585. 1, 3, 4, 7, 2, 5, 6, 7,
  118586. };
  118587. static static_codebook _huff_book_line_128x17_class1 = {
  118588. 1, 8,
  118589. _huff_lengthlist_line_128x17_class1,
  118590. 0, 0, 0, 0, 0,
  118591. NULL,
  118592. NULL,
  118593. NULL,
  118594. NULL,
  118595. 0
  118596. };
  118597. static long _huff_lengthlist_line_128x17_class2[] = {
  118598. 1, 4,10,19, 3, 8,13,19, 7,12,19,19,19,19,19,19,
  118599. 2, 6,11,19, 8,13,19,19, 9,11,19,19,19,19,19,19,
  118600. 6, 7,13,19, 9,13,19,19,10,13,18,18,18,18,18,18,
  118601. 18,18,18,18,18,18,18,18,18,18,18,18,18,18,18,18,
  118602. };
  118603. static static_codebook _huff_book_line_128x17_class2 = {
  118604. 1, 64,
  118605. _huff_lengthlist_line_128x17_class2,
  118606. 0, 0, 0, 0, 0,
  118607. NULL,
  118608. NULL,
  118609. NULL,
  118610. NULL,
  118611. 0
  118612. };
  118613. static long _huff_lengthlist_line_128x17_class3[] = {
  118614. 3, 6,10,17, 4, 8,11,20, 8,10,11,20,20,20,20,20,
  118615. 2, 4, 8,18, 4, 6, 8,17, 7, 8,10,20,20,17,20,20,
  118616. 3, 5, 8,17, 3, 4, 6,17, 8, 8,10,17,17,12,16,20,
  118617. 13,13,15,20,10,10,12,20,15,14,15,20,20,20,19,19,
  118618. };
  118619. static static_codebook _huff_book_line_128x17_class3 = {
  118620. 1, 64,
  118621. _huff_lengthlist_line_128x17_class3,
  118622. 0, 0, 0, 0, 0,
  118623. NULL,
  118624. NULL,
  118625. NULL,
  118626. NULL,
  118627. 0
  118628. };
  118629. static long _huff_lengthlist_line_128x17_0sub0[] = {
  118630. 5, 5, 6, 5, 6, 5, 6, 5, 6, 5, 6, 5, 6, 5, 6, 5,
  118631. 7, 5, 7, 5, 7, 5, 7, 5, 7, 5, 7, 5, 8, 5, 8, 5,
  118632. 8, 5, 8, 5, 8, 6, 8, 6, 8, 6, 9, 6, 9, 6, 9, 6,
  118633. 9, 6, 9, 7, 9, 7, 9, 7, 9, 7,10, 7,10, 8,10, 8,
  118634. 10, 8,10, 8,10, 8,11, 8,11, 8,11, 8,11, 8,11, 9,
  118635. 12, 9,12, 9,12, 9,12, 9,12,10,12,10,13,11,13,11,
  118636. 14,12,14,13,15,14,16,14,17,15,18,16,20,20,20,20,
  118637. 20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,
  118638. };
  118639. static static_codebook _huff_book_line_128x17_0sub0 = {
  118640. 1, 128,
  118641. _huff_lengthlist_line_128x17_0sub0,
  118642. 0, 0, 0, 0, 0,
  118643. NULL,
  118644. NULL,
  118645. NULL,
  118646. NULL,
  118647. 0
  118648. };
  118649. static long _huff_lengthlist_line_128x17_1sub0[] = {
  118650. 2, 5, 5, 4, 5, 4, 5, 4, 5, 5, 5, 5, 5, 5, 6, 5,
  118651. 6, 5, 6, 5, 7, 6, 7, 6, 7, 6, 8, 6, 9, 7, 9, 7,
  118652. };
  118653. static static_codebook _huff_book_line_128x17_1sub0 = {
  118654. 1, 32,
  118655. _huff_lengthlist_line_128x17_1sub0,
  118656. 0, 0, 0, 0, 0,
  118657. NULL,
  118658. NULL,
  118659. NULL,
  118660. NULL,
  118661. 0
  118662. };
  118663. static long _huff_lengthlist_line_128x17_1sub1[] = {
  118664. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118665. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118666. 4, 3, 5, 3, 5, 3, 6, 3, 6, 4, 6, 4, 7, 4, 7, 5,
  118667. 8, 5, 8, 6, 9, 7, 9, 7, 9, 8,10, 9,10, 9,11,10,
  118668. 11,11,11,11,11,11,12,12,12,13,12,13,12,14,12,15,
  118669. 12,14,12,16,13,17,13,17,14,17,14,16,13,17,14,17,
  118670. 14,17,15,17,15,15,16,17,17,17,17,17,17,17,17,17,
  118671. 17,17,17,17,17,17,16,16,16,16,16,16,16,16,16,16,
  118672. };
  118673. static static_codebook _huff_book_line_128x17_1sub1 = {
  118674. 1, 128,
  118675. _huff_lengthlist_line_128x17_1sub1,
  118676. 0, 0, 0, 0, 0,
  118677. NULL,
  118678. NULL,
  118679. NULL,
  118680. NULL,
  118681. 0
  118682. };
  118683. static long _huff_lengthlist_line_128x17_2sub1[] = {
  118684. 0, 4, 5, 4, 6, 4, 8, 3, 9, 3, 9, 2, 9, 3, 8, 4,
  118685. 9, 4,
  118686. };
  118687. static static_codebook _huff_book_line_128x17_2sub1 = {
  118688. 1, 18,
  118689. _huff_lengthlist_line_128x17_2sub1,
  118690. 0, 0, 0, 0, 0,
  118691. NULL,
  118692. NULL,
  118693. NULL,
  118694. NULL,
  118695. 0
  118696. };
  118697. static long _huff_lengthlist_line_128x17_2sub2[] = {
  118698. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118699. 0, 0, 5, 1, 5, 3, 5, 3, 5, 4, 7, 5,10, 7,10, 7,
  118700. 12,10,14,10,14, 9,14,11,14,14,14,13,13,13,13,13,
  118701. 13,13,
  118702. };
  118703. static static_codebook _huff_book_line_128x17_2sub2 = {
  118704. 1, 50,
  118705. _huff_lengthlist_line_128x17_2sub2,
  118706. 0, 0, 0, 0, 0,
  118707. NULL,
  118708. NULL,
  118709. NULL,
  118710. NULL,
  118711. 0
  118712. };
  118713. static long _huff_lengthlist_line_128x17_2sub3[] = {
  118714. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118715. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118716. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118717. 0, 0, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  118718. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 6, 6,
  118719. 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,
  118720. 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,
  118721. 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,
  118722. };
  118723. static static_codebook _huff_book_line_128x17_2sub3 = {
  118724. 1, 128,
  118725. _huff_lengthlist_line_128x17_2sub3,
  118726. 0, 0, 0, 0, 0,
  118727. NULL,
  118728. NULL,
  118729. NULL,
  118730. NULL,
  118731. 0
  118732. };
  118733. static long _huff_lengthlist_line_128x17_3sub1[] = {
  118734. 0, 4, 4, 4, 4, 4, 4, 4, 5, 3, 5, 3, 5, 4, 6, 4,
  118735. 6, 4,
  118736. };
  118737. static static_codebook _huff_book_line_128x17_3sub1 = {
  118738. 1, 18,
  118739. _huff_lengthlist_line_128x17_3sub1,
  118740. 0, 0, 0, 0, 0,
  118741. NULL,
  118742. NULL,
  118743. NULL,
  118744. NULL,
  118745. 0
  118746. };
  118747. static long _huff_lengthlist_line_128x17_3sub2[] = {
  118748. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118749. 0, 0, 5, 3, 6, 3, 6, 4, 7, 4, 7, 4, 7, 4, 8, 4,
  118750. 8, 4, 8, 4, 8, 4, 9, 4, 9, 5,10, 5,10, 7,10, 8,
  118751. 10, 8,
  118752. };
  118753. static static_codebook _huff_book_line_128x17_3sub2 = {
  118754. 1, 50,
  118755. _huff_lengthlist_line_128x17_3sub2,
  118756. 0, 0, 0, 0, 0,
  118757. NULL,
  118758. NULL,
  118759. NULL,
  118760. NULL,
  118761. 0
  118762. };
  118763. static long _huff_lengthlist_line_128x17_3sub3[] = {
  118764. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118765. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118766. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118767. 0, 0, 3, 2, 4, 3, 4, 4, 4, 5, 4, 7, 5, 8, 5,11,
  118768. 6,10, 6,12, 7,12, 7,12, 8,12, 8,12,10,12,12,12,
  118769. 12,12,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  118770. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  118771. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  118772. };
  118773. static static_codebook _huff_book_line_128x17_3sub3 = {
  118774. 1, 128,
  118775. _huff_lengthlist_line_128x17_3sub3,
  118776. 0, 0, 0, 0, 0,
  118777. NULL,
  118778. NULL,
  118779. NULL,
  118780. NULL,
  118781. 0
  118782. };
  118783. static long _huff_lengthlist_line_1024x27_class1[] = {
  118784. 2,10, 8,14, 7,12,11,14, 1, 5, 3, 7, 4, 9, 7,13,
  118785. };
  118786. static static_codebook _huff_book_line_1024x27_class1 = {
  118787. 1, 16,
  118788. _huff_lengthlist_line_1024x27_class1,
  118789. 0, 0, 0, 0, 0,
  118790. NULL,
  118791. NULL,
  118792. NULL,
  118793. NULL,
  118794. 0
  118795. };
  118796. static long _huff_lengthlist_line_1024x27_class2[] = {
  118797. 1, 4, 2, 6, 3, 7, 5, 7,
  118798. };
  118799. static static_codebook _huff_book_line_1024x27_class2 = {
  118800. 1, 8,
  118801. _huff_lengthlist_line_1024x27_class2,
  118802. 0, 0, 0, 0, 0,
  118803. NULL,
  118804. NULL,
  118805. NULL,
  118806. NULL,
  118807. 0
  118808. };
  118809. static long _huff_lengthlist_line_1024x27_class3[] = {
  118810. 1, 5, 7,21, 5, 8, 9,21,10, 9,12,20,20,16,20,20,
  118811. 4, 8, 9,20, 6, 8, 9,20,11,11,13,20,20,15,17,20,
  118812. 9,11,14,20, 8,10,15,20,11,13,15,20,20,20,20,20,
  118813. 20,20,20,20,13,20,20,20,18,18,20,20,20,20,20,20,
  118814. 3, 6, 8,20, 6, 7, 9,20,10, 9,12,20,20,20,20,20,
  118815. 5, 7, 9,20, 6, 6, 9,20,10, 9,12,20,20,20,20,20,
  118816. 8,10,13,20, 8, 9,12,20,11,10,12,20,20,20,20,20,
  118817. 18,20,20,20,15,17,18,20,18,17,18,20,20,20,20,20,
  118818. 7,10,12,20, 8, 9,11,20,14,13,14,20,20,20,20,20,
  118819. 6, 9,12,20, 7, 8,11,20,12,11,13,20,20,20,20,20,
  118820. 9,11,15,20, 8,10,14,20,12,11,14,20,20,20,20,20,
  118821. 20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,
  118822. 11,16,18,20,15,15,17,20,20,17,20,20,20,20,20,20,
  118823. 9,14,16,20,12,12,15,20,17,15,18,20,20,20,20,20,
  118824. 16,19,18,20,15,16,20,20,17,17,20,20,20,20,20,20,
  118825. 20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,
  118826. };
  118827. static static_codebook _huff_book_line_1024x27_class3 = {
  118828. 1, 256,
  118829. _huff_lengthlist_line_1024x27_class3,
  118830. 0, 0, 0, 0, 0,
  118831. NULL,
  118832. NULL,
  118833. NULL,
  118834. NULL,
  118835. 0
  118836. };
  118837. static long _huff_lengthlist_line_1024x27_class4[] = {
  118838. 2, 3, 7,13, 4, 4, 7,15, 8, 6, 9,17,21,16,15,21,
  118839. 2, 5, 7,11, 5, 5, 7,14, 9, 7,10,16,17,15,16,21,
  118840. 4, 7,10,17, 7, 7, 9,15,11, 9,11,16,21,18,15,21,
  118841. 18,21,21,21,15,17,17,19,21,19,18,20,21,21,21,20,
  118842. };
  118843. static static_codebook _huff_book_line_1024x27_class4 = {
  118844. 1, 64,
  118845. _huff_lengthlist_line_1024x27_class4,
  118846. 0, 0, 0, 0, 0,
  118847. NULL,
  118848. NULL,
  118849. NULL,
  118850. NULL,
  118851. 0
  118852. };
  118853. static long _huff_lengthlist_line_1024x27_0sub0[] = {
  118854. 5, 5, 5, 5, 6, 5, 6, 5, 6, 5, 6, 5, 6, 5, 6, 5,
  118855. 6, 5, 6, 5, 6, 5, 6, 5, 7, 5, 7, 5, 7, 5, 7, 5,
  118856. 8, 6, 8, 6, 8, 6, 9, 6, 9, 6,10, 6,10, 6,11, 6,
  118857. 11, 7,11, 7,12, 7,12, 7,12, 7,12, 7,12, 7,12, 7,
  118858. 12, 7,12, 8,13, 8,12, 8,12, 8,13, 8,13, 9,13, 9,
  118859. 13, 9,13, 9,12,10,12,10,13,10,14,11,14,12,14,13,
  118860. 14,13,14,14,15,16,15,15,15,14,15,17,21,22,22,21,
  118861. 22,22,22,22,22,22,21,21,21,21,21,21,21,21,21,21,
  118862. };
  118863. static static_codebook _huff_book_line_1024x27_0sub0 = {
  118864. 1, 128,
  118865. _huff_lengthlist_line_1024x27_0sub0,
  118866. 0, 0, 0, 0, 0,
  118867. NULL,
  118868. NULL,
  118869. NULL,
  118870. NULL,
  118871. 0
  118872. };
  118873. static long _huff_lengthlist_line_1024x27_1sub0[] = {
  118874. 2, 5, 5, 4, 5, 4, 5, 4, 5, 4, 6, 5, 6, 5, 6, 5,
  118875. 6, 5, 7, 5, 7, 6, 8, 6, 8, 6, 8, 6, 9, 6, 9, 6,
  118876. };
  118877. static static_codebook _huff_book_line_1024x27_1sub0 = {
  118878. 1, 32,
  118879. _huff_lengthlist_line_1024x27_1sub0,
  118880. 0, 0, 0, 0, 0,
  118881. NULL,
  118882. NULL,
  118883. NULL,
  118884. NULL,
  118885. 0
  118886. };
  118887. static long _huff_lengthlist_line_1024x27_1sub1[] = {
  118888. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118889. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118890. 8, 5, 8, 4, 9, 4, 9, 4, 9, 4, 9, 4, 9, 4, 9, 4,
  118891. 9, 4, 9, 4, 9, 4, 8, 4, 8, 4, 9, 5, 9, 5, 9, 5,
  118892. 9, 5, 9, 6,10, 6,10, 7,10, 8,11, 9,11,11,12,13,
  118893. 12,14,13,15,13,15,14,16,14,17,15,17,15,15,16,16,
  118894. 15,16,16,16,15,18,16,15,17,17,19,19,19,19,19,19,
  118895. 19,19,19,19,19,19,19,19,19,19,19,19,19,19,19,19,
  118896. };
  118897. static static_codebook _huff_book_line_1024x27_1sub1 = {
  118898. 1, 128,
  118899. _huff_lengthlist_line_1024x27_1sub1,
  118900. 0, 0, 0, 0, 0,
  118901. NULL,
  118902. NULL,
  118903. NULL,
  118904. NULL,
  118905. 0
  118906. };
  118907. static long _huff_lengthlist_line_1024x27_2sub0[] = {
  118908. 1, 5, 5, 5, 5, 5, 5, 5, 6, 5, 6, 5, 6, 5, 6, 5,
  118909. 6, 6, 7, 7, 7, 7, 8, 7, 8, 8, 9, 8,10, 9,10, 9,
  118910. };
  118911. static static_codebook _huff_book_line_1024x27_2sub0 = {
  118912. 1, 32,
  118913. _huff_lengthlist_line_1024x27_2sub0,
  118914. 0, 0, 0, 0, 0,
  118915. NULL,
  118916. NULL,
  118917. NULL,
  118918. NULL,
  118919. 0
  118920. };
  118921. static long _huff_lengthlist_line_1024x27_2sub1[] = {
  118922. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118923. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118924. 4, 3, 4, 3, 4, 4, 5, 4, 5, 4, 5, 5, 6, 5, 6, 5,
  118925. 7, 5, 7, 6, 7, 6, 8, 7, 8, 7, 8, 7, 9, 8, 9, 9,
  118926. 9, 9,10,10,10,11, 9,12, 9,12, 9,15,10,14, 9,13,
  118927. 10,13,10,12,10,12,10,13,10,12,11,13,11,14,12,13,
  118928. 13,14,14,13,14,15,14,16,13,13,14,16,16,16,16,16,
  118929. 16,16,16,16,16,16,16,16,16,16,16,16,16,16,15,15,
  118930. };
  118931. static static_codebook _huff_book_line_1024x27_2sub1 = {
  118932. 1, 128,
  118933. _huff_lengthlist_line_1024x27_2sub1,
  118934. 0, 0, 0, 0, 0,
  118935. NULL,
  118936. NULL,
  118937. NULL,
  118938. NULL,
  118939. 0
  118940. };
  118941. static long _huff_lengthlist_line_1024x27_3sub1[] = {
  118942. 0, 4, 5, 4, 5, 3, 5, 3, 5, 3, 5, 4, 4, 4, 4, 5,
  118943. 5, 5,
  118944. };
  118945. static static_codebook _huff_book_line_1024x27_3sub1 = {
  118946. 1, 18,
  118947. _huff_lengthlist_line_1024x27_3sub1,
  118948. 0, 0, 0, 0, 0,
  118949. NULL,
  118950. NULL,
  118951. NULL,
  118952. NULL,
  118953. 0
  118954. };
  118955. static long _huff_lengthlist_line_1024x27_3sub2[] = {
  118956. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118957. 0, 0, 3, 3, 4, 3, 4, 4, 4, 4, 5, 5, 5, 5, 5, 6,
  118958. 5, 7, 5, 8, 6, 8, 6, 9, 7,10, 7,10, 8,10, 8,11,
  118959. 9,11,
  118960. };
  118961. static static_codebook _huff_book_line_1024x27_3sub2 = {
  118962. 1, 50,
  118963. _huff_lengthlist_line_1024x27_3sub2,
  118964. 0, 0, 0, 0, 0,
  118965. NULL,
  118966. NULL,
  118967. NULL,
  118968. NULL,
  118969. 0
  118970. };
  118971. static long _huff_lengthlist_line_1024x27_3sub3[] = {
  118972. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118973. 0, 0, 0, 0, 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, 3, 7, 3, 8, 3,10, 3, 8, 3, 9, 3, 8, 4, 9,
  118976. 4, 9, 5, 9, 6,10, 6, 9, 7,11, 7,12, 9,13,10,13,
  118977. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  118978. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  118979. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  118980. };
  118981. static static_codebook _huff_book_line_1024x27_3sub3 = {
  118982. 1, 128,
  118983. _huff_lengthlist_line_1024x27_3sub3,
  118984. 0, 0, 0, 0, 0,
  118985. NULL,
  118986. NULL,
  118987. NULL,
  118988. NULL,
  118989. 0
  118990. };
  118991. static long _huff_lengthlist_line_1024x27_4sub1[] = {
  118992. 0, 4, 5, 4, 5, 4, 5, 4, 5, 3, 5, 3, 5, 3, 5, 4,
  118993. 5, 4,
  118994. };
  118995. static static_codebook _huff_book_line_1024x27_4sub1 = {
  118996. 1, 18,
  118997. _huff_lengthlist_line_1024x27_4sub1,
  118998. 0, 0, 0, 0, 0,
  118999. NULL,
  119000. NULL,
  119001. NULL,
  119002. NULL,
  119003. 0
  119004. };
  119005. static long _huff_lengthlist_line_1024x27_4sub2[] = {
  119006. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119007. 0, 0, 4, 2, 4, 2, 5, 3, 5, 4, 6, 6, 6, 7, 7, 8,
  119008. 7, 8, 7, 8, 7, 9, 8, 9, 8, 9, 8,10, 8,11, 9,12,
  119009. 9,12,
  119010. };
  119011. static static_codebook _huff_book_line_1024x27_4sub2 = {
  119012. 1, 50,
  119013. _huff_lengthlist_line_1024x27_4sub2,
  119014. 0, 0, 0, 0, 0,
  119015. NULL,
  119016. NULL,
  119017. NULL,
  119018. NULL,
  119019. 0
  119020. };
  119021. static long _huff_lengthlist_line_1024x27_4sub3[] = {
  119022. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119023. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119024. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119025. 0, 0, 2, 5, 2, 6, 3, 6, 4, 7, 4, 7, 5, 9, 5,11,
  119026. 6,11, 6,11, 7,11, 6,11, 6,11, 9,11, 8,11,11,11,
  119027. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  119028. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  119029. 11,11,11,11,11,11,11,11,11,11,10,10,10,10,10,10,
  119030. };
  119031. static static_codebook _huff_book_line_1024x27_4sub3 = {
  119032. 1, 128,
  119033. _huff_lengthlist_line_1024x27_4sub3,
  119034. 0, 0, 0, 0, 0,
  119035. NULL,
  119036. NULL,
  119037. NULL,
  119038. NULL,
  119039. 0
  119040. };
  119041. static long _huff_lengthlist_line_2048x27_class1[] = {
  119042. 2, 6, 8, 9, 7,11,13,13, 1, 3, 5, 5, 6, 6,12,10,
  119043. };
  119044. static static_codebook _huff_book_line_2048x27_class1 = {
  119045. 1, 16,
  119046. _huff_lengthlist_line_2048x27_class1,
  119047. 0, 0, 0, 0, 0,
  119048. NULL,
  119049. NULL,
  119050. NULL,
  119051. NULL,
  119052. 0
  119053. };
  119054. static long _huff_lengthlist_line_2048x27_class2[] = {
  119055. 1, 2, 3, 6, 4, 7, 5, 7,
  119056. };
  119057. static static_codebook _huff_book_line_2048x27_class2 = {
  119058. 1, 8,
  119059. _huff_lengthlist_line_2048x27_class2,
  119060. 0, 0, 0, 0, 0,
  119061. NULL,
  119062. NULL,
  119063. NULL,
  119064. NULL,
  119065. 0
  119066. };
  119067. static long _huff_lengthlist_line_2048x27_class3[] = {
  119068. 3, 3, 6,16, 5, 5, 7,16, 9, 8,11,16,16,16,16,16,
  119069. 5, 5, 8,16, 5, 5, 7,16, 8, 7, 9,16,16,16,16,16,
  119070. 9, 9,12,16, 6, 8,11,16, 9,10,11,16,16,16,16,16,
  119071. 16,16,16,16,13,16,16,16,15,16,16,16,16,16,16,16,
  119072. 5, 4, 7,16, 6, 5, 8,16, 9, 8,10,16,16,16,16,16,
  119073. 5, 5, 7,15, 5, 4, 6,15, 7, 6, 8,16,16,16,16,16,
  119074. 9, 9,11,15, 7, 7, 9,16, 8, 8, 9,16,16,16,16,16,
  119075. 16,16,16,16,15,15,15,16,15,15,14,16,16,16,16,16,
  119076. 8, 8,11,16, 8, 9,10,16,11,10,14,16,16,16,16,16,
  119077. 6, 8,10,16, 6, 7,10,16, 8, 8,11,16,14,16,16,16,
  119078. 10,11,14,16, 9, 9,11,16,10,10,11,16,16,16,16,16,
  119079. 16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,
  119080. 16,16,16,16,15,16,16,16,16,16,16,16,16,16,16,16,
  119081. 12,16,15,16,12,14,16,16,16,16,16,16,16,16,16,16,
  119082. 16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,
  119083. 16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,
  119084. };
  119085. static static_codebook _huff_book_line_2048x27_class3 = {
  119086. 1, 256,
  119087. _huff_lengthlist_line_2048x27_class3,
  119088. 0, 0, 0, 0, 0,
  119089. NULL,
  119090. NULL,
  119091. NULL,
  119092. NULL,
  119093. 0
  119094. };
  119095. static long _huff_lengthlist_line_2048x27_class4[] = {
  119096. 2, 4, 7,13, 4, 5, 7,15, 8, 7,10,16,16,14,16,16,
  119097. 2, 4, 7,16, 3, 4, 7,14, 8, 8,10,16,16,16,15,16,
  119098. 6, 8,11,16, 7, 7, 9,16,11, 9,13,16,16,16,15,16,
  119099. 16,16,16,16,14,16,16,16,16,16,16,16,16,16,16,16,
  119100. };
  119101. static static_codebook _huff_book_line_2048x27_class4 = {
  119102. 1, 64,
  119103. _huff_lengthlist_line_2048x27_class4,
  119104. 0, 0, 0, 0, 0,
  119105. NULL,
  119106. NULL,
  119107. NULL,
  119108. NULL,
  119109. 0
  119110. };
  119111. static long _huff_lengthlist_line_2048x27_0sub0[] = {
  119112. 5, 5, 5, 5, 5, 5, 6, 5, 6, 5, 6, 5, 6, 5, 6, 5,
  119113. 6, 5, 7, 5, 7, 5, 7, 5, 8, 5, 8, 5, 8, 5, 9, 5,
  119114. 9, 6,10, 6,10, 6,11, 6,11, 6,11, 6,11, 6,11, 6,
  119115. 11, 6,11, 6,12, 7,11, 7,11, 7,11, 7,11, 7,10, 7,
  119116. 11, 7,11, 7,12, 7,11, 8,11, 8,11, 8,11, 8,13, 8,
  119117. 12, 9,11, 9,11, 9,11,10,12,10,12, 9,12,10,12,11,
  119118. 14,12,16,12,12,11,14,16,17,17,17,17,17,17,17,17,
  119119. 17,17,17,17,17,17,17,17,17,17,17,17,16,16,16,16,
  119120. };
  119121. static static_codebook _huff_book_line_2048x27_0sub0 = {
  119122. 1, 128,
  119123. _huff_lengthlist_line_2048x27_0sub0,
  119124. 0, 0, 0, 0, 0,
  119125. NULL,
  119126. NULL,
  119127. NULL,
  119128. NULL,
  119129. 0
  119130. };
  119131. static long _huff_lengthlist_line_2048x27_1sub0[] = {
  119132. 4, 4, 4, 4, 4, 4, 4, 4, 5, 5, 5, 5, 5, 5, 5, 5,
  119133. 5, 5, 6, 6, 6, 6, 6, 6, 7, 6, 7, 6, 7, 6, 7, 6,
  119134. };
  119135. static static_codebook _huff_book_line_2048x27_1sub0 = {
  119136. 1, 32,
  119137. _huff_lengthlist_line_2048x27_1sub0,
  119138. 0, 0, 0, 0, 0,
  119139. NULL,
  119140. NULL,
  119141. NULL,
  119142. NULL,
  119143. 0
  119144. };
  119145. static long _huff_lengthlist_line_2048x27_1sub1[] = {
  119146. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119147. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119148. 6, 5, 7, 5, 7, 4, 7, 4, 8, 4, 8, 4, 8, 4, 8, 3,
  119149. 8, 4, 9, 4, 9, 4, 9, 4, 9, 4, 9, 5, 9, 5, 9, 6,
  119150. 9, 7, 9, 8, 9, 9, 9,10, 9,11, 9,14, 9,15,10,15,
  119151. 10,15,10,15,10,15,11,15,10,14,12,14,11,14,13,14,
  119152. 13,15,15,15,12,15,15,15,13,15,13,15,13,15,15,15,
  119153. 15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,14,
  119154. };
  119155. static static_codebook _huff_book_line_2048x27_1sub1 = {
  119156. 1, 128,
  119157. _huff_lengthlist_line_2048x27_1sub1,
  119158. 0, 0, 0, 0, 0,
  119159. NULL,
  119160. NULL,
  119161. NULL,
  119162. NULL,
  119163. 0
  119164. };
  119165. static long _huff_lengthlist_line_2048x27_2sub0[] = {
  119166. 2, 4, 5, 4, 5, 4, 5, 4, 5, 5, 5, 5, 5, 5, 6, 5,
  119167. 6, 5, 6, 6, 6, 6, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8,
  119168. };
  119169. static static_codebook _huff_book_line_2048x27_2sub0 = {
  119170. 1, 32,
  119171. _huff_lengthlist_line_2048x27_2sub0,
  119172. 0, 0, 0, 0, 0,
  119173. NULL,
  119174. NULL,
  119175. NULL,
  119176. NULL,
  119177. 0
  119178. };
  119179. static long _huff_lengthlist_line_2048x27_2sub1[] = {
  119180. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119181. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119182. 3, 4, 3, 4, 3, 4, 4, 5, 4, 5, 5, 5, 6, 6, 6, 7,
  119183. 6, 8, 6, 8, 6, 9, 7,10, 7,10, 7,10, 7,12, 7,12,
  119184. 7,12, 9,12,11,12,10,12,10,12,11,12,12,12,10,12,
  119185. 10,12,10,12, 9,12,11,12,12,12,12,12,11,12,11,12,
  119186. 12,12,12,12,12,12,12,12,10,10,12,12,12,12,12,10,
  119187. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  119188. };
  119189. static static_codebook _huff_book_line_2048x27_2sub1 = {
  119190. 1, 128,
  119191. _huff_lengthlist_line_2048x27_2sub1,
  119192. 0, 0, 0, 0, 0,
  119193. NULL,
  119194. NULL,
  119195. NULL,
  119196. NULL,
  119197. 0
  119198. };
  119199. static long _huff_lengthlist_line_2048x27_3sub1[] = {
  119200. 0, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4,
  119201. 5, 5,
  119202. };
  119203. static static_codebook _huff_book_line_2048x27_3sub1 = {
  119204. 1, 18,
  119205. _huff_lengthlist_line_2048x27_3sub1,
  119206. 0, 0, 0, 0, 0,
  119207. NULL,
  119208. NULL,
  119209. NULL,
  119210. NULL,
  119211. 0
  119212. };
  119213. static long _huff_lengthlist_line_2048x27_3sub2[] = {
  119214. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119215. 0, 0, 3, 3, 3, 4, 4, 4, 4, 4, 4, 5, 5, 5, 5, 6,
  119216. 6, 7, 6, 7, 6, 8, 6, 9, 7, 9, 7, 9, 9,11, 9,12,
  119217. 10,12,
  119218. };
  119219. static static_codebook _huff_book_line_2048x27_3sub2 = {
  119220. 1, 50,
  119221. _huff_lengthlist_line_2048x27_3sub2,
  119222. 0, 0, 0, 0, 0,
  119223. NULL,
  119224. NULL,
  119225. NULL,
  119226. NULL,
  119227. 0
  119228. };
  119229. static long _huff_lengthlist_line_2048x27_3sub3[] = {
  119230. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119231. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119232. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119233. 0, 0, 3, 6, 3, 7, 3, 7, 5, 7, 7, 7, 7, 7, 6, 7,
  119234. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  119235. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  119236. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  119237. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  119238. };
  119239. static static_codebook _huff_book_line_2048x27_3sub3 = {
  119240. 1, 128,
  119241. _huff_lengthlist_line_2048x27_3sub3,
  119242. 0, 0, 0, 0, 0,
  119243. NULL,
  119244. NULL,
  119245. NULL,
  119246. NULL,
  119247. 0
  119248. };
  119249. static long _huff_lengthlist_line_2048x27_4sub1[] = {
  119250. 0, 3, 4, 4, 4, 4, 4, 4, 4, 4, 5, 4, 5, 4, 5, 4,
  119251. 4, 5,
  119252. };
  119253. static static_codebook _huff_book_line_2048x27_4sub1 = {
  119254. 1, 18,
  119255. _huff_lengthlist_line_2048x27_4sub1,
  119256. 0, 0, 0, 0, 0,
  119257. NULL,
  119258. NULL,
  119259. NULL,
  119260. NULL,
  119261. 0
  119262. };
  119263. static long _huff_lengthlist_line_2048x27_4sub2[] = {
  119264. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119265. 0, 0, 3, 2, 4, 3, 4, 4, 4, 5, 5, 6, 5, 6, 5, 7,
  119266. 6, 6, 6, 7, 7, 7, 8, 9, 9, 9,12,10,11,10,10,12,
  119267. 10,10,
  119268. };
  119269. static static_codebook _huff_book_line_2048x27_4sub2 = {
  119270. 1, 50,
  119271. _huff_lengthlist_line_2048x27_4sub2,
  119272. 0, 0, 0, 0, 0,
  119273. NULL,
  119274. NULL,
  119275. NULL,
  119276. NULL,
  119277. 0
  119278. };
  119279. static long _huff_lengthlist_line_2048x27_4sub3[] = {
  119280. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119281. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119282. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119283. 0, 0, 3, 6, 5, 7, 5, 7, 7, 7, 7, 7, 5, 7, 5, 7,
  119284. 5, 7, 5, 7, 7, 7, 7, 7, 4, 7, 7, 7, 7, 7, 7, 7,
  119285. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  119286. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  119287. 7, 7, 7, 7, 7, 7, 7, 6, 6, 6, 6, 6, 6, 6, 6, 6,
  119288. };
  119289. static static_codebook _huff_book_line_2048x27_4sub3 = {
  119290. 1, 128,
  119291. _huff_lengthlist_line_2048x27_4sub3,
  119292. 0, 0, 0, 0, 0,
  119293. NULL,
  119294. NULL,
  119295. NULL,
  119296. NULL,
  119297. 0
  119298. };
  119299. static long _huff_lengthlist_line_256x4low_class0[] = {
  119300. 4, 5, 6,11, 5, 5, 6,10, 7, 7, 6, 6,14,13, 9, 9,
  119301. 6, 6, 6,10, 6, 6, 6, 9, 8, 7, 7, 9,14,12, 8,11,
  119302. 8, 7, 7,11, 8, 8, 7,11, 9, 9, 7, 9,13,11, 9,13,
  119303. 19,19,18,19,15,16,16,19,11,11,10,13,10,10, 9,15,
  119304. 5, 5, 6,13, 6, 6, 6,11, 8, 7, 6, 7,14,11,10,11,
  119305. 6, 6, 6,12, 7, 6, 6,11, 8, 7, 7,11,13,11, 9,11,
  119306. 9, 7, 6,12, 8, 7, 6,12, 9, 8, 8,11,13,10, 7,13,
  119307. 19,19,17,19,17,14,14,19,12,10, 8,12,13,10, 9,16,
  119308. 7, 8, 7,12, 7, 7, 7,11, 8, 7, 7, 8,12,12,11,11,
  119309. 8, 8, 7,12, 8, 7, 6,11, 8, 7, 7,10,10,11,10,11,
  119310. 9, 8, 8,13, 9, 8, 7,12,10, 9, 7,11, 9, 8, 7,11,
  119311. 18,18,15,18,18,16,17,18,15,11,10,18,11, 9, 9,18,
  119312. 16,16,13,16,12,11,10,16,12,11, 9, 6,15,12,11,13,
  119313. 16,16,14,14,13,11,12,16,12, 9, 9,13,13,10,10,12,
  119314. 17,18,17,17,14,15,14,16,14,12,14,15,12,10,11,12,
  119315. 18,18,18,18,18,18,18,18,18,12,13,18,16,11, 9,18,
  119316. };
  119317. static static_codebook _huff_book_line_256x4low_class0 = {
  119318. 1, 256,
  119319. _huff_lengthlist_line_256x4low_class0,
  119320. 0, 0, 0, 0, 0,
  119321. NULL,
  119322. NULL,
  119323. NULL,
  119324. NULL,
  119325. 0
  119326. };
  119327. static long _huff_lengthlist_line_256x4low_0sub0[] = {
  119328. 1, 3, 2, 3,
  119329. };
  119330. static static_codebook _huff_book_line_256x4low_0sub0 = {
  119331. 1, 4,
  119332. _huff_lengthlist_line_256x4low_0sub0,
  119333. 0, 0, 0, 0, 0,
  119334. NULL,
  119335. NULL,
  119336. NULL,
  119337. NULL,
  119338. 0
  119339. };
  119340. static long _huff_lengthlist_line_256x4low_0sub1[] = {
  119341. 0, 0, 0, 0, 2, 3, 2, 3, 3, 3,
  119342. };
  119343. static static_codebook _huff_book_line_256x4low_0sub1 = {
  119344. 1, 10,
  119345. _huff_lengthlist_line_256x4low_0sub1,
  119346. 0, 0, 0, 0, 0,
  119347. NULL,
  119348. NULL,
  119349. NULL,
  119350. NULL,
  119351. 0
  119352. };
  119353. static long _huff_lengthlist_line_256x4low_0sub2[] = {
  119354. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 3, 3, 4, 3, 4,
  119355. 4, 4, 4, 4, 5, 5, 5, 6, 6,
  119356. };
  119357. static static_codebook _huff_book_line_256x4low_0sub2 = {
  119358. 1, 25,
  119359. _huff_lengthlist_line_256x4low_0sub2,
  119360. 0, 0, 0, 0, 0,
  119361. NULL,
  119362. NULL,
  119363. NULL,
  119364. NULL,
  119365. 0
  119366. };
  119367. static long _huff_lengthlist_line_256x4low_0sub3[] = {
  119368. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119369. 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 4, 2, 4, 3, 5, 4,
  119370. 5, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6, 7, 7, 8, 6, 9,
  119371. 7,12,11,16,13,16,12,15,13,15,12,14,12,15,15,15,
  119372. };
  119373. static static_codebook _huff_book_line_256x4low_0sub3 = {
  119374. 1, 64,
  119375. _huff_lengthlist_line_256x4low_0sub3,
  119376. 0, 0, 0, 0, 0,
  119377. NULL,
  119378. NULL,
  119379. NULL,
  119380. NULL,
  119381. 0
  119382. };
  119383. /*** End of inlined file: floor_books.h ***/
  119384. static static_codebook *_floor_128x4_books[]={
  119385. &_huff_book_line_128x4_class0,
  119386. &_huff_book_line_128x4_0sub0,
  119387. &_huff_book_line_128x4_0sub1,
  119388. &_huff_book_line_128x4_0sub2,
  119389. &_huff_book_line_128x4_0sub3,
  119390. };
  119391. static static_codebook *_floor_256x4_books[]={
  119392. &_huff_book_line_256x4_class0,
  119393. &_huff_book_line_256x4_0sub0,
  119394. &_huff_book_line_256x4_0sub1,
  119395. &_huff_book_line_256x4_0sub2,
  119396. &_huff_book_line_256x4_0sub3,
  119397. };
  119398. static static_codebook *_floor_128x7_books[]={
  119399. &_huff_book_line_128x7_class0,
  119400. &_huff_book_line_128x7_class1,
  119401. &_huff_book_line_128x7_0sub1,
  119402. &_huff_book_line_128x7_0sub2,
  119403. &_huff_book_line_128x7_0sub3,
  119404. &_huff_book_line_128x7_1sub1,
  119405. &_huff_book_line_128x7_1sub2,
  119406. &_huff_book_line_128x7_1sub3,
  119407. };
  119408. static static_codebook *_floor_256x7_books[]={
  119409. &_huff_book_line_256x7_class0,
  119410. &_huff_book_line_256x7_class1,
  119411. &_huff_book_line_256x7_0sub1,
  119412. &_huff_book_line_256x7_0sub2,
  119413. &_huff_book_line_256x7_0sub3,
  119414. &_huff_book_line_256x7_1sub1,
  119415. &_huff_book_line_256x7_1sub2,
  119416. &_huff_book_line_256x7_1sub3,
  119417. };
  119418. static static_codebook *_floor_128x11_books[]={
  119419. &_huff_book_line_128x11_class1,
  119420. &_huff_book_line_128x11_class2,
  119421. &_huff_book_line_128x11_class3,
  119422. &_huff_book_line_128x11_0sub0,
  119423. &_huff_book_line_128x11_1sub0,
  119424. &_huff_book_line_128x11_1sub1,
  119425. &_huff_book_line_128x11_2sub1,
  119426. &_huff_book_line_128x11_2sub2,
  119427. &_huff_book_line_128x11_2sub3,
  119428. &_huff_book_line_128x11_3sub1,
  119429. &_huff_book_line_128x11_3sub2,
  119430. &_huff_book_line_128x11_3sub3,
  119431. };
  119432. static static_codebook *_floor_128x17_books[]={
  119433. &_huff_book_line_128x17_class1,
  119434. &_huff_book_line_128x17_class2,
  119435. &_huff_book_line_128x17_class3,
  119436. &_huff_book_line_128x17_0sub0,
  119437. &_huff_book_line_128x17_1sub0,
  119438. &_huff_book_line_128x17_1sub1,
  119439. &_huff_book_line_128x17_2sub1,
  119440. &_huff_book_line_128x17_2sub2,
  119441. &_huff_book_line_128x17_2sub3,
  119442. &_huff_book_line_128x17_3sub1,
  119443. &_huff_book_line_128x17_3sub2,
  119444. &_huff_book_line_128x17_3sub3,
  119445. };
  119446. static static_codebook *_floor_256x4low_books[]={
  119447. &_huff_book_line_256x4low_class0,
  119448. &_huff_book_line_256x4low_0sub0,
  119449. &_huff_book_line_256x4low_0sub1,
  119450. &_huff_book_line_256x4low_0sub2,
  119451. &_huff_book_line_256x4low_0sub3,
  119452. };
  119453. static static_codebook *_floor_1024x27_books[]={
  119454. &_huff_book_line_1024x27_class1,
  119455. &_huff_book_line_1024x27_class2,
  119456. &_huff_book_line_1024x27_class3,
  119457. &_huff_book_line_1024x27_class4,
  119458. &_huff_book_line_1024x27_0sub0,
  119459. &_huff_book_line_1024x27_1sub0,
  119460. &_huff_book_line_1024x27_1sub1,
  119461. &_huff_book_line_1024x27_2sub0,
  119462. &_huff_book_line_1024x27_2sub1,
  119463. &_huff_book_line_1024x27_3sub1,
  119464. &_huff_book_line_1024x27_3sub2,
  119465. &_huff_book_line_1024x27_3sub3,
  119466. &_huff_book_line_1024x27_4sub1,
  119467. &_huff_book_line_1024x27_4sub2,
  119468. &_huff_book_line_1024x27_4sub3,
  119469. };
  119470. static static_codebook *_floor_2048x27_books[]={
  119471. &_huff_book_line_2048x27_class1,
  119472. &_huff_book_line_2048x27_class2,
  119473. &_huff_book_line_2048x27_class3,
  119474. &_huff_book_line_2048x27_class4,
  119475. &_huff_book_line_2048x27_0sub0,
  119476. &_huff_book_line_2048x27_1sub0,
  119477. &_huff_book_line_2048x27_1sub1,
  119478. &_huff_book_line_2048x27_2sub0,
  119479. &_huff_book_line_2048x27_2sub1,
  119480. &_huff_book_line_2048x27_3sub1,
  119481. &_huff_book_line_2048x27_3sub2,
  119482. &_huff_book_line_2048x27_3sub3,
  119483. &_huff_book_line_2048x27_4sub1,
  119484. &_huff_book_line_2048x27_4sub2,
  119485. &_huff_book_line_2048x27_4sub3,
  119486. };
  119487. static static_codebook *_floor_512x17_books[]={
  119488. &_huff_book_line_512x17_class1,
  119489. &_huff_book_line_512x17_class2,
  119490. &_huff_book_line_512x17_class3,
  119491. &_huff_book_line_512x17_0sub0,
  119492. &_huff_book_line_512x17_1sub0,
  119493. &_huff_book_line_512x17_1sub1,
  119494. &_huff_book_line_512x17_2sub1,
  119495. &_huff_book_line_512x17_2sub2,
  119496. &_huff_book_line_512x17_2sub3,
  119497. &_huff_book_line_512x17_3sub1,
  119498. &_huff_book_line_512x17_3sub2,
  119499. &_huff_book_line_512x17_3sub3,
  119500. };
  119501. static static_codebook **_floor_books[10]={
  119502. _floor_128x4_books,
  119503. _floor_256x4_books,
  119504. _floor_128x7_books,
  119505. _floor_256x7_books,
  119506. _floor_128x11_books,
  119507. _floor_128x17_books,
  119508. _floor_256x4low_books,
  119509. _floor_1024x27_books,
  119510. _floor_2048x27_books,
  119511. _floor_512x17_books,
  119512. };
  119513. static vorbis_info_floor1 _floor[10]={
  119514. /* 128 x 4 */
  119515. {
  119516. 1,{0},{4},{2},{0},
  119517. {{1,2,3,4}},
  119518. 4,{0,128, 33,8,16,70},
  119519. 60,30,500, 1.,18., -1
  119520. },
  119521. /* 256 x 4 */
  119522. {
  119523. 1,{0},{4},{2},{0},
  119524. {{1,2,3,4}},
  119525. 4,{0,256, 66,16,32,140},
  119526. 60,30,500, 1.,18., -1
  119527. },
  119528. /* 128 x 7 */
  119529. {
  119530. 2,{0,1},{3,4},{2,2},{0,1},
  119531. {{-1,2,3,4},{-1,5,6,7}},
  119532. 4,{0,128, 14,4,58, 2,8,28,90},
  119533. 60,30,500, 1.,18., -1
  119534. },
  119535. /* 256 x 7 */
  119536. {
  119537. 2,{0,1},{3,4},{2,2},{0,1},
  119538. {{-1,2,3,4},{-1,5,6,7}},
  119539. 4,{0,256, 28,8,116, 4,16,56,180},
  119540. 60,30,500, 1.,18., -1
  119541. },
  119542. /* 128 x 11 */
  119543. {
  119544. 4,{0,1,2,3},{2,3,3,3},{0,1,2,2},{-1,0,1,2},
  119545. {{3},{4,5},{-1,6,7,8},{-1,9,10,11}},
  119546. 2,{0,128, 8,33, 4,16,70, 2,6,12, 23,46,90},
  119547. 60,30,500, 1,18., -1
  119548. },
  119549. /* 128 x 17 */
  119550. {
  119551. 6,{0,1,1,2,3,3},{2,3,3,3},{0,1,2,2},{-1,0,1,2},
  119552. {{3},{4,5},{-1,6,7,8},{-1,9,10,11}},
  119553. 2,{0,128, 12,46, 4,8,16, 23,33,70, 2,6,10, 14,19,28, 39,58,90},
  119554. 60,30,500, 1,18., -1
  119555. },
  119556. /* 256 x 4 (low bitrate version) */
  119557. {
  119558. 1,{0},{4},{2},{0},
  119559. {{1,2,3,4}},
  119560. 4,{0,256, 66,16,32,140},
  119561. 60,30,500, 1.,18., -1
  119562. },
  119563. /* 1024 x 27 */
  119564. {
  119565. 8,{0,1,2,2,3,3,4,4},{3,4,3,4,3},{0,1,1,2,2},{-1,0,1,2,3},
  119566. {{4},{5,6},{7,8},{-1,9,10,11},{-1,12,13,14}},
  119567. 2,{0,1024, 93,23,372, 6,46,186,750, 14,33,65, 130,260,556,
  119568. 3,10,18,28, 39,55,79,111, 158,220,312, 464,650,850},
  119569. 60,30,500, 3,18., -1 /* lowpass */
  119570. },
  119571. /* 2048 x 27 */
  119572. {
  119573. 8,{0,1,2,2,3,3,4,4},{3,4,3,4,3},{0,1,1,2,2},{-1,0,1,2,3},
  119574. {{4},{5,6},{7,8},{-1,9,10,11},{-1,12,13,14}},
  119575. 2,{0,2048, 186,46,744, 12,92,372,1500, 28,66,130, 260,520,1112,
  119576. 6,20,36,56, 78,110,158,222, 316,440,624, 928,1300,1700},
  119577. 60,30,500, 3,18., -1 /* lowpass */
  119578. },
  119579. /* 512 x 17 */
  119580. {
  119581. 6,{0,1,1,2,3,3},{2,3,3,3},{0,1,2,2},{-1,0,1,2},
  119582. {{3},{4,5},{-1,6,7,8},{-1,9,10,11}},
  119583. 2,{0,512, 46,186, 16,33,65, 93,130,278,
  119584. 7,23,39, 55,79,110, 156,232,360},
  119585. 60,30,500, 1,18., -1 /* lowpass! */
  119586. },
  119587. };
  119588. /*** End of inlined file: floor_all.h ***/
  119589. /*** Start of inlined file: residue_44.h ***/
  119590. /*** Start of inlined file: res_books_stereo.h ***/
  119591. static long _vq_quantlist__16c0_s_p1_0[] = {
  119592. 1,
  119593. 0,
  119594. 2,
  119595. };
  119596. static long _vq_lengthlist__16c0_s_p1_0[] = {
  119597. 1, 4, 4, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  119598. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119599. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119600. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119601. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119602. 0, 5, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9,10, 0, 0, 0,
  119603. 0, 0, 0, 7, 9,10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119604. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119605. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119606. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119607. 0, 0, 5, 8, 8, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  119608. 0, 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119609. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119610. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119611. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119612. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119613. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119614. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119615. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119616. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119617. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119618. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119619. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119620. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119621. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119622. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119623. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119624. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119625. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119626. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119627. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119628. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119629. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119630. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119631. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119632. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119633. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119634. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119635. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119636. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119637. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119638. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119639. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119640. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119641. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119642. 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 8, 8, 0, 0, 0, 0,
  119643. 0, 0, 8,10,10, 0, 0, 0, 0, 0, 0, 8,10,10, 0, 0,
  119644. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119645. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119646. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119647. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7,10,10, 0, 0, 0,
  119648. 0, 0, 0, 9, 9,12, 0, 0, 0, 0, 0, 0,10,12,11, 0,
  119649. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119650. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119651. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119652. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7,10,10, 0, 0,
  119653. 0, 0, 0, 0, 9,12,10, 0, 0, 0, 0, 0, 0,10,11,12,
  119654. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119655. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119656. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119657. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119658. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119659. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119660. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119661. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119662. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119663. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119664. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119665. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119666. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119667. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119668. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119669. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119670. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119671. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119672. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119673. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119674. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119675. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119676. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119677. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119678. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119679. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119680. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119681. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119682. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119683. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119684. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119685. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119686. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119687. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119688. 0, 0, 5, 8, 8, 0, 0, 0, 0, 0, 0, 8,10,10, 0, 0,
  119689. 0, 0, 0, 0, 8,10,10, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119690. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119691. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119692. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119693. 0, 0, 0, 7,10,10, 0, 0, 0, 0, 0, 0,10,12,11, 0,
  119694. 0, 0, 0, 0, 0, 9,10,12, 0, 0, 0, 0, 0, 0, 0, 0,
  119695. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119696. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119697. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119698. 0, 0, 0, 0, 7,10,10, 0, 0, 0, 0, 0, 0,10,11,12,
  119699. 0, 0, 0, 0, 0, 0, 9,12, 9, 0, 0, 0, 0, 0, 0, 0,
  119700. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119701. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119702. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119703. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119704. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119705. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119706. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119707. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119708. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119709. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119710. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119711. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119712. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119713. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119714. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119715. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119716. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119717. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119718. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119719. 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119724. 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119729. 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0,
  119764. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0,
  119769. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0,
  119774. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119810. 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119815. 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119820. 0, 0, 0, 0, 0, 0, 0, 0, 0, 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,
  120008. };
  120009. static float _vq_quantthresh__16c0_s_p1_0[] = {
  120010. -0.5, 0.5,
  120011. };
  120012. static long _vq_quantmap__16c0_s_p1_0[] = {
  120013. 1, 0, 2,
  120014. };
  120015. static encode_aux_threshmatch _vq_auxt__16c0_s_p1_0 = {
  120016. _vq_quantthresh__16c0_s_p1_0,
  120017. _vq_quantmap__16c0_s_p1_0,
  120018. 3,
  120019. 3
  120020. };
  120021. static static_codebook _16c0_s_p1_0 = {
  120022. 8, 6561,
  120023. _vq_lengthlist__16c0_s_p1_0,
  120024. 1, -535822336, 1611661312, 2, 0,
  120025. _vq_quantlist__16c0_s_p1_0,
  120026. NULL,
  120027. &_vq_auxt__16c0_s_p1_0,
  120028. NULL,
  120029. 0
  120030. };
  120031. static long _vq_quantlist__16c0_s_p2_0[] = {
  120032. 2,
  120033. 1,
  120034. 3,
  120035. 0,
  120036. 4,
  120037. };
  120038. static long _vq_lengthlist__16c0_s_p2_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,
  120079. };
  120080. static float _vq_quantthresh__16c0_s_p2_0[] = {
  120081. -1.5, -0.5, 0.5, 1.5,
  120082. };
  120083. static long _vq_quantmap__16c0_s_p2_0[] = {
  120084. 3, 1, 0, 2, 4,
  120085. };
  120086. static encode_aux_threshmatch _vq_auxt__16c0_s_p2_0 = {
  120087. _vq_quantthresh__16c0_s_p2_0,
  120088. _vq_quantmap__16c0_s_p2_0,
  120089. 5,
  120090. 5
  120091. };
  120092. static static_codebook _16c0_s_p2_0 = {
  120093. 4, 625,
  120094. _vq_lengthlist__16c0_s_p2_0,
  120095. 1, -533725184, 1611661312, 3, 0,
  120096. _vq_quantlist__16c0_s_p2_0,
  120097. NULL,
  120098. &_vq_auxt__16c0_s_p2_0,
  120099. NULL,
  120100. 0
  120101. };
  120102. static long _vq_quantlist__16c0_s_p3_0[] = {
  120103. 2,
  120104. 1,
  120105. 3,
  120106. 0,
  120107. 4,
  120108. };
  120109. static long _vq_lengthlist__16c0_s_p3_0[] = {
  120110. 1, 4, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120111. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 6, 6, 7, 6, 0, 0,
  120112. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120113. 0, 0, 4, 6, 6, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120114. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 6, 6, 9, 9,
  120115. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120116. 0, 0, 0, 0, 6, 6, 6, 9, 9, 0, 0, 0, 0, 0, 0, 0,
  120117. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120118. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120119. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120120. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120121. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120122. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120123. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120124. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120125. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120126. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120127. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120128. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120129. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120130. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120131. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120132. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120133. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120134. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120135. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120136. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120137. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120138. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120139. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120140. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120141. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120142. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120143. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120144. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120145. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120146. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120147. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120148. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120149. 0,
  120150. };
  120151. static float _vq_quantthresh__16c0_s_p3_0[] = {
  120152. -1.5, -0.5, 0.5, 1.5,
  120153. };
  120154. static long _vq_quantmap__16c0_s_p3_0[] = {
  120155. 3, 1, 0, 2, 4,
  120156. };
  120157. static encode_aux_threshmatch _vq_auxt__16c0_s_p3_0 = {
  120158. _vq_quantthresh__16c0_s_p3_0,
  120159. _vq_quantmap__16c0_s_p3_0,
  120160. 5,
  120161. 5
  120162. };
  120163. static static_codebook _16c0_s_p3_0 = {
  120164. 4, 625,
  120165. _vq_lengthlist__16c0_s_p3_0,
  120166. 1, -533725184, 1611661312, 3, 0,
  120167. _vq_quantlist__16c0_s_p3_0,
  120168. NULL,
  120169. &_vq_auxt__16c0_s_p3_0,
  120170. NULL,
  120171. 0
  120172. };
  120173. static long _vq_quantlist__16c0_s_p4_0[] = {
  120174. 4,
  120175. 3,
  120176. 5,
  120177. 2,
  120178. 6,
  120179. 1,
  120180. 7,
  120181. 0,
  120182. 8,
  120183. };
  120184. static long _vq_lengthlist__16c0_s_p4_0[] = {
  120185. 1, 3, 2, 7, 8, 0, 0, 0, 0, 0, 0, 0, 6, 6, 0, 0,
  120186. 0, 0, 0, 0, 0, 6, 6, 0, 0, 0, 0, 0, 0, 0, 7, 7,
  120187. 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0, 0, 0,
  120188. 8, 8, 0, 0, 0, 0, 0, 0, 0, 8, 8, 0, 0, 0, 0, 0,
  120189. 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120190. 0,
  120191. };
  120192. static float _vq_quantthresh__16c0_s_p4_0[] = {
  120193. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  120194. };
  120195. static long _vq_quantmap__16c0_s_p4_0[] = {
  120196. 7, 5, 3, 1, 0, 2, 4, 6,
  120197. 8,
  120198. };
  120199. static encode_aux_threshmatch _vq_auxt__16c0_s_p4_0 = {
  120200. _vq_quantthresh__16c0_s_p4_0,
  120201. _vq_quantmap__16c0_s_p4_0,
  120202. 9,
  120203. 9
  120204. };
  120205. static static_codebook _16c0_s_p4_0 = {
  120206. 2, 81,
  120207. _vq_lengthlist__16c0_s_p4_0,
  120208. 1, -531628032, 1611661312, 4, 0,
  120209. _vq_quantlist__16c0_s_p4_0,
  120210. NULL,
  120211. &_vq_auxt__16c0_s_p4_0,
  120212. NULL,
  120213. 0
  120214. };
  120215. static long _vq_quantlist__16c0_s_p5_0[] = {
  120216. 4,
  120217. 3,
  120218. 5,
  120219. 2,
  120220. 6,
  120221. 1,
  120222. 7,
  120223. 0,
  120224. 8,
  120225. };
  120226. static long _vq_lengthlist__16c0_s_p5_0[] = {
  120227. 1, 3, 3, 6, 6, 6, 6, 8, 8, 0, 0, 0, 7, 7, 7, 7,
  120228. 8, 8, 0, 0, 0, 7, 7, 7, 7, 8, 8, 0, 0, 0, 7, 7,
  120229. 8, 8, 9, 9, 0, 0, 0, 7, 7, 8, 8, 9, 9, 0, 0, 0,
  120230. 8, 9, 8, 8,10,10, 0, 0, 0, 8, 8, 8, 8,10,10, 0,
  120231. 0, 0,10,10, 9, 9,10,10, 0, 0, 0, 0, 0, 9, 9,10,
  120232. 10,
  120233. };
  120234. static float _vq_quantthresh__16c0_s_p5_0[] = {
  120235. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  120236. };
  120237. static long _vq_quantmap__16c0_s_p5_0[] = {
  120238. 7, 5, 3, 1, 0, 2, 4, 6,
  120239. 8,
  120240. };
  120241. static encode_aux_threshmatch _vq_auxt__16c0_s_p5_0 = {
  120242. _vq_quantthresh__16c0_s_p5_0,
  120243. _vq_quantmap__16c0_s_p5_0,
  120244. 9,
  120245. 9
  120246. };
  120247. static static_codebook _16c0_s_p5_0 = {
  120248. 2, 81,
  120249. _vq_lengthlist__16c0_s_p5_0,
  120250. 1, -531628032, 1611661312, 4, 0,
  120251. _vq_quantlist__16c0_s_p5_0,
  120252. NULL,
  120253. &_vq_auxt__16c0_s_p5_0,
  120254. NULL,
  120255. 0
  120256. };
  120257. static long _vq_quantlist__16c0_s_p6_0[] = {
  120258. 8,
  120259. 7,
  120260. 9,
  120261. 6,
  120262. 10,
  120263. 5,
  120264. 11,
  120265. 4,
  120266. 12,
  120267. 3,
  120268. 13,
  120269. 2,
  120270. 14,
  120271. 1,
  120272. 15,
  120273. 0,
  120274. 16,
  120275. };
  120276. static long _vq_lengthlist__16c0_s_p6_0[] = {
  120277. 1, 3, 4, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,10,11,
  120278. 11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10,11,
  120279. 11,11, 0, 0, 0, 6, 6, 8, 8, 9, 9, 9, 9,10,10,11,
  120280. 11,11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  120281. 11,11,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,
  120282. 10,11,11,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,10,
  120283. 11,11,12,12,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,
  120284. 10,11,11,12,12,12,13, 0, 0, 0, 9, 9, 9, 9,10,10,
  120285. 10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0,10,10,10,
  120286. 10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,
  120287. 10,10,11,11,12,12,13,13,13,13, 0, 0, 0, 0, 0, 9,
  120288. 9,10,10,11,11,12,12,13,13,13,14, 0, 0, 0, 0, 0,
  120289. 10,10,10,11,11,11,12,12,13,13,13,14, 0, 0, 0, 0,
  120290. 0, 0, 0,10,10,11,11,12,12,13,13,14,14, 0, 0, 0,
  120291. 0, 0, 0, 0,11,11,12,12,13,13,13,13,14,14, 0, 0,
  120292. 0, 0, 0, 0, 0,11,11,12,12,12,13,13,14,15,14, 0,
  120293. 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,13,14,14,15,
  120294. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,13,13,14,13,14,
  120295. 14,
  120296. };
  120297. static float _vq_quantthresh__16c0_s_p6_0[] = {
  120298. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  120299. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  120300. };
  120301. static long _vq_quantmap__16c0_s_p6_0[] = {
  120302. 15, 13, 11, 9, 7, 5, 3, 1,
  120303. 0, 2, 4, 6, 8, 10, 12, 14,
  120304. 16,
  120305. };
  120306. static encode_aux_threshmatch _vq_auxt__16c0_s_p6_0 = {
  120307. _vq_quantthresh__16c0_s_p6_0,
  120308. _vq_quantmap__16c0_s_p6_0,
  120309. 17,
  120310. 17
  120311. };
  120312. static static_codebook _16c0_s_p6_0 = {
  120313. 2, 289,
  120314. _vq_lengthlist__16c0_s_p6_0,
  120315. 1, -529530880, 1611661312, 5, 0,
  120316. _vq_quantlist__16c0_s_p6_0,
  120317. NULL,
  120318. &_vq_auxt__16c0_s_p6_0,
  120319. NULL,
  120320. 0
  120321. };
  120322. static long _vq_quantlist__16c0_s_p7_0[] = {
  120323. 1,
  120324. 0,
  120325. 2,
  120326. };
  120327. static long _vq_lengthlist__16c0_s_p7_0[] = {
  120328. 1, 4, 4, 6, 6, 6, 7, 6, 6, 4, 7, 7,11,10,10,11,
  120329. 11,10, 4, 7, 7,10,10,10,11,10,10, 6,10,10,11,11,
  120330. 11,11,11,10, 6, 9, 9,11,12,12,11, 9, 9, 6, 9,10,
  120331. 11,12,12,11, 9,10, 7,11,11,11,11,11,12,13,12, 6,
  120332. 9,10,11,10,10,12,13,13, 6,10, 9,11,10,10,11,12,
  120333. 13,
  120334. };
  120335. static float _vq_quantthresh__16c0_s_p7_0[] = {
  120336. -5.5, 5.5,
  120337. };
  120338. static long _vq_quantmap__16c0_s_p7_0[] = {
  120339. 1, 0, 2,
  120340. };
  120341. static encode_aux_threshmatch _vq_auxt__16c0_s_p7_0 = {
  120342. _vq_quantthresh__16c0_s_p7_0,
  120343. _vq_quantmap__16c0_s_p7_0,
  120344. 3,
  120345. 3
  120346. };
  120347. static static_codebook _16c0_s_p7_0 = {
  120348. 4, 81,
  120349. _vq_lengthlist__16c0_s_p7_0,
  120350. 1, -529137664, 1618345984, 2, 0,
  120351. _vq_quantlist__16c0_s_p7_0,
  120352. NULL,
  120353. &_vq_auxt__16c0_s_p7_0,
  120354. NULL,
  120355. 0
  120356. };
  120357. static long _vq_quantlist__16c0_s_p7_1[] = {
  120358. 5,
  120359. 4,
  120360. 6,
  120361. 3,
  120362. 7,
  120363. 2,
  120364. 8,
  120365. 1,
  120366. 9,
  120367. 0,
  120368. 10,
  120369. };
  120370. static long _vq_lengthlist__16c0_s_p7_1[] = {
  120371. 1, 3, 4, 6, 6, 7, 7, 8, 8, 8, 8,10,10,10, 7, 7,
  120372. 8, 8, 8, 9, 9, 9,10,10,10, 6, 7, 8, 8, 8, 8, 9,
  120373. 8,10,10,10, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10, 7,
  120374. 7, 8, 8, 9, 9, 8, 9,10,10,10, 8, 8, 9, 9, 9, 9,
  120375. 9, 9,11,11,11, 8, 8, 9, 9, 9, 9, 9,10,10,11,11,
  120376. 9, 9, 9, 9, 9, 9, 9,10,11,11,11,10,11, 9, 9, 9,
  120377. 9,10, 9,11,11,11,10,11,10,10, 9, 9,10,10,11,11,
  120378. 11,11,11, 9, 9, 9, 9,10,10,
  120379. };
  120380. static float _vq_quantthresh__16c0_s_p7_1[] = {
  120381. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  120382. 3.5, 4.5,
  120383. };
  120384. static long _vq_quantmap__16c0_s_p7_1[] = {
  120385. 9, 7, 5, 3, 1, 0, 2, 4,
  120386. 6, 8, 10,
  120387. };
  120388. static encode_aux_threshmatch _vq_auxt__16c0_s_p7_1 = {
  120389. _vq_quantthresh__16c0_s_p7_1,
  120390. _vq_quantmap__16c0_s_p7_1,
  120391. 11,
  120392. 11
  120393. };
  120394. static static_codebook _16c0_s_p7_1 = {
  120395. 2, 121,
  120396. _vq_lengthlist__16c0_s_p7_1,
  120397. 1, -531365888, 1611661312, 4, 0,
  120398. _vq_quantlist__16c0_s_p7_1,
  120399. NULL,
  120400. &_vq_auxt__16c0_s_p7_1,
  120401. NULL,
  120402. 0
  120403. };
  120404. static long _vq_quantlist__16c0_s_p8_0[] = {
  120405. 6,
  120406. 5,
  120407. 7,
  120408. 4,
  120409. 8,
  120410. 3,
  120411. 9,
  120412. 2,
  120413. 10,
  120414. 1,
  120415. 11,
  120416. 0,
  120417. 12,
  120418. };
  120419. static long _vq_lengthlist__16c0_s_p8_0[] = {
  120420. 1, 4, 4, 7, 7, 7, 7, 7, 6, 8, 8,10,10, 6, 5, 6,
  120421. 8, 8, 8, 8, 8, 8, 8, 9,10,10, 7, 6, 6, 8, 8, 8,
  120422. 8, 8, 8, 8, 8,10,10, 0, 8, 8, 8, 8, 9, 8, 9, 9,
  120423. 9,10,10,10, 0, 9, 8, 8, 8, 9, 9, 8, 8, 9, 9,10,
  120424. 10, 0,12,11, 8, 8, 9, 9, 9, 9,10,10,11,10, 0,12,
  120425. 13, 8, 8, 9,10, 9, 9,11,11,11,12, 0, 0, 0, 8, 8,
  120426. 8, 8,10, 9,12,13,12,14, 0, 0, 0, 8, 8, 8, 9,10,
  120427. 10,12,12,13,14, 0, 0, 0,13,13, 9, 9,11,11, 0, 0,
  120428. 14, 0, 0, 0, 0,14,14,10,10,12,11,12,14,14,14, 0,
  120429. 0, 0, 0, 0,11,11,13,13,14,13,14,14, 0, 0, 0, 0,
  120430. 0,12,13,13,12,13,14,14,14,
  120431. };
  120432. static float _vq_quantthresh__16c0_s_p8_0[] = {
  120433. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  120434. 12.5, 17.5, 22.5, 27.5,
  120435. };
  120436. static long _vq_quantmap__16c0_s_p8_0[] = {
  120437. 11, 9, 7, 5, 3, 1, 0, 2,
  120438. 4, 6, 8, 10, 12,
  120439. };
  120440. static encode_aux_threshmatch _vq_auxt__16c0_s_p8_0 = {
  120441. _vq_quantthresh__16c0_s_p8_0,
  120442. _vq_quantmap__16c0_s_p8_0,
  120443. 13,
  120444. 13
  120445. };
  120446. static static_codebook _16c0_s_p8_0 = {
  120447. 2, 169,
  120448. _vq_lengthlist__16c0_s_p8_0,
  120449. 1, -526516224, 1616117760, 4, 0,
  120450. _vq_quantlist__16c0_s_p8_0,
  120451. NULL,
  120452. &_vq_auxt__16c0_s_p8_0,
  120453. NULL,
  120454. 0
  120455. };
  120456. static long _vq_quantlist__16c0_s_p8_1[] = {
  120457. 2,
  120458. 1,
  120459. 3,
  120460. 0,
  120461. 4,
  120462. };
  120463. static long _vq_lengthlist__16c0_s_p8_1[] = {
  120464. 1, 4, 3, 5, 5, 7, 7, 7, 6, 6, 7, 7, 7, 5, 5, 7,
  120465. 7, 7, 6, 6, 7, 7, 7, 6, 6,
  120466. };
  120467. static float _vq_quantthresh__16c0_s_p8_1[] = {
  120468. -1.5, -0.5, 0.5, 1.5,
  120469. };
  120470. static long _vq_quantmap__16c0_s_p8_1[] = {
  120471. 3, 1, 0, 2, 4,
  120472. };
  120473. static encode_aux_threshmatch _vq_auxt__16c0_s_p8_1 = {
  120474. _vq_quantthresh__16c0_s_p8_1,
  120475. _vq_quantmap__16c0_s_p8_1,
  120476. 5,
  120477. 5
  120478. };
  120479. static static_codebook _16c0_s_p8_1 = {
  120480. 2, 25,
  120481. _vq_lengthlist__16c0_s_p8_1,
  120482. 1, -533725184, 1611661312, 3, 0,
  120483. _vq_quantlist__16c0_s_p8_1,
  120484. NULL,
  120485. &_vq_auxt__16c0_s_p8_1,
  120486. NULL,
  120487. 0
  120488. };
  120489. static long _vq_quantlist__16c0_s_p9_0[] = {
  120490. 1,
  120491. 0,
  120492. 2,
  120493. };
  120494. static long _vq_lengthlist__16c0_s_p9_0[] = {
  120495. 1, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  120496. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  120497. 8, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  120498. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  120499. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  120500. 7,
  120501. };
  120502. static float _vq_quantthresh__16c0_s_p9_0[] = {
  120503. -157.5, 157.5,
  120504. };
  120505. static long _vq_quantmap__16c0_s_p9_0[] = {
  120506. 1, 0, 2,
  120507. };
  120508. static encode_aux_threshmatch _vq_auxt__16c0_s_p9_0 = {
  120509. _vq_quantthresh__16c0_s_p9_0,
  120510. _vq_quantmap__16c0_s_p9_0,
  120511. 3,
  120512. 3
  120513. };
  120514. static static_codebook _16c0_s_p9_0 = {
  120515. 4, 81,
  120516. _vq_lengthlist__16c0_s_p9_0,
  120517. 1, -518803456, 1628680192, 2, 0,
  120518. _vq_quantlist__16c0_s_p9_0,
  120519. NULL,
  120520. &_vq_auxt__16c0_s_p9_0,
  120521. NULL,
  120522. 0
  120523. };
  120524. static long _vq_quantlist__16c0_s_p9_1[] = {
  120525. 7,
  120526. 6,
  120527. 8,
  120528. 5,
  120529. 9,
  120530. 4,
  120531. 10,
  120532. 3,
  120533. 11,
  120534. 2,
  120535. 12,
  120536. 1,
  120537. 13,
  120538. 0,
  120539. 14,
  120540. };
  120541. static long _vq_lengthlist__16c0_s_p9_1[] = {
  120542. 1, 5, 5, 5, 5, 9,11,11,10,10,10,10,10,10,10, 7,
  120543. 6, 6, 6, 6,10,10,10,10,10,10,10,10,10,10, 7, 6,
  120544. 6, 6, 6,10, 9,10,10,10,10,10,10,10,10,10, 7, 7,
  120545. 8, 9,10,10,10,10,10,10,10,10,10,10,10, 8, 7,10,
  120546. 10,10, 9,10,10,10,10,10,10,10,10,10,10,10,10,10,
  120547. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  120548. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  120549. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  120550. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  120551. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  120552. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  120553. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  120554. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  120555. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  120556. 10,
  120557. };
  120558. static float _vq_quantthresh__16c0_s_p9_1[] = {
  120559. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  120560. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  120561. };
  120562. static long _vq_quantmap__16c0_s_p9_1[] = {
  120563. 13, 11, 9, 7, 5, 3, 1, 0,
  120564. 2, 4, 6, 8, 10, 12, 14,
  120565. };
  120566. static encode_aux_threshmatch _vq_auxt__16c0_s_p9_1 = {
  120567. _vq_quantthresh__16c0_s_p9_1,
  120568. _vq_quantmap__16c0_s_p9_1,
  120569. 15,
  120570. 15
  120571. };
  120572. static static_codebook _16c0_s_p9_1 = {
  120573. 2, 225,
  120574. _vq_lengthlist__16c0_s_p9_1,
  120575. 1, -520986624, 1620377600, 4, 0,
  120576. _vq_quantlist__16c0_s_p9_1,
  120577. NULL,
  120578. &_vq_auxt__16c0_s_p9_1,
  120579. NULL,
  120580. 0
  120581. };
  120582. static long _vq_quantlist__16c0_s_p9_2[] = {
  120583. 10,
  120584. 9,
  120585. 11,
  120586. 8,
  120587. 12,
  120588. 7,
  120589. 13,
  120590. 6,
  120591. 14,
  120592. 5,
  120593. 15,
  120594. 4,
  120595. 16,
  120596. 3,
  120597. 17,
  120598. 2,
  120599. 18,
  120600. 1,
  120601. 19,
  120602. 0,
  120603. 20,
  120604. };
  120605. static long _vq_lengthlist__16c0_s_p9_2[] = {
  120606. 1, 5, 5, 7, 8, 8, 7, 9, 9, 9,12,12,11,12,12,10,
  120607. 10,11,12,12,12,11,12,12, 8, 9, 8, 7, 9,10,10,11,
  120608. 11,10,11,12,10,12,10,12,12,12,11,12,11, 9, 8, 8,
  120609. 9,10, 9, 8, 9,10,12,12,11,11,12,11,10,11,12,11,
  120610. 12,12, 8, 9, 9, 9,10,11,12,11,12,11,11,11,11,12,
  120611. 12,11,11,12,12,11,11, 9, 9, 8, 9, 9,11, 9, 9,10,
  120612. 9,11,11,11,11,12,11,11,10,12,12,12, 9,12,11,10,
  120613. 11,11,11,11,12,12,12,11,11,11,12,10,12,12,12,10,
  120614. 10, 9,10, 9,10,10, 9, 9, 9,10,10,12,10,11,11, 9,
  120615. 11,11,10,11,11,11,10,10,10, 9, 9,10,10, 9, 9,10,
  120616. 11,11,10,11,10,11,10,11,11,10,11,11,11,10, 9,10,
  120617. 10, 9,10, 9, 9,11, 9, 9,11,10,10,11,11,10,10,11,
  120618. 10,11, 8, 9,11,11,10, 9,10,11,11,10,11,11,10,10,
  120619. 10,11,10, 9,10,10,11, 9,10,10, 9,11,10,10,10,10,
  120620. 11,10,11,11, 9,11,10,11,10,10,11,11,10,10,10, 9,
  120621. 10,10,11,11,11, 9,10,10,10,10,10,11,10,10,10, 9,
  120622. 10,10,11,10,10,10,10,10, 9,10,11,10,10,10,10,11,
  120623. 11,11,10,10,10,10,10,11,10,11,10,11,10,10,10, 9,
  120624. 11,11,10,10,10,11,11,10,10,10,10,10,10,10,10,11,
  120625. 11, 9,10,10,10,11,10,11,10,10,10,11, 9,10,11,10,
  120626. 11,10,10, 9,10,10,10,11,10,11,10,10,10,10,10,11,
  120627. 11,10,11,11,10,10,11,11,10, 9, 9,10,10,10,10,10,
  120628. 9,11, 9,10,10,10,11,11,10,10,10,10,11,11,11,10,
  120629. 9, 9,10,10,11,10,10,10,10,10,11,11,11,10,10,10,
  120630. 11,11,11, 9,10,10,10,10, 9,10, 9,10,11,10,11,10,
  120631. 10,11,11,10,11,11,11,11,11,10,11,10,10,10, 9,11,
  120632. 11,10,11,11,11,11,11,11,11,11,11,10,11,10,10,10,
  120633. 10,11,10,10,11, 9,10,10,10,
  120634. };
  120635. static float _vq_quantthresh__16c0_s_p9_2[] = {
  120636. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  120637. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  120638. 6.5, 7.5, 8.5, 9.5,
  120639. };
  120640. static long _vq_quantmap__16c0_s_p9_2[] = {
  120641. 19, 17, 15, 13, 11, 9, 7, 5,
  120642. 3, 1, 0, 2, 4, 6, 8, 10,
  120643. 12, 14, 16, 18, 20,
  120644. };
  120645. static encode_aux_threshmatch _vq_auxt__16c0_s_p9_2 = {
  120646. _vq_quantthresh__16c0_s_p9_2,
  120647. _vq_quantmap__16c0_s_p9_2,
  120648. 21,
  120649. 21
  120650. };
  120651. static static_codebook _16c0_s_p9_2 = {
  120652. 2, 441,
  120653. _vq_lengthlist__16c0_s_p9_2,
  120654. 1, -529268736, 1611661312, 5, 0,
  120655. _vq_quantlist__16c0_s_p9_2,
  120656. NULL,
  120657. &_vq_auxt__16c0_s_p9_2,
  120658. NULL,
  120659. 0
  120660. };
  120661. static long _huff_lengthlist__16c0_s_single[] = {
  120662. 3, 4,19, 7, 9, 7, 8,11, 9,12, 4, 1,19, 6, 7, 7,
  120663. 8,10,11,13,18,18,18,18,18,18,18,18,18,18, 8, 6,
  120664. 18, 8, 9, 9,11,12,14,18, 9, 6,18, 9, 7, 8, 9,11,
  120665. 12,18, 7, 6,18, 8, 7, 7, 7, 9,11,17, 8, 8,18, 9,
  120666. 7, 6, 6, 8,11,17,10,10,18,12, 9, 8, 7, 9,12,18,
  120667. 13,15,18,15,13,11,10,11,15,18,14,18,18,18,18,18,
  120668. 16,16,18,18,
  120669. };
  120670. static static_codebook _huff_book__16c0_s_single = {
  120671. 2, 100,
  120672. _huff_lengthlist__16c0_s_single,
  120673. 0, 0, 0, 0, 0,
  120674. NULL,
  120675. NULL,
  120676. NULL,
  120677. NULL,
  120678. 0
  120679. };
  120680. static long _huff_lengthlist__16c1_s_long[] = {
  120681. 2, 5,20, 7,10, 7, 8,10,11,11, 4, 2,20, 5, 8, 6,
  120682. 7, 9,10,10,20,20,20,20,19,19,19,19,19,19, 7, 5,
  120683. 19, 6,10, 7, 9,11,13,17,11, 8,19,10, 7, 7, 8,10,
  120684. 11,15, 7, 5,19, 7, 7, 5, 6, 9,11,16, 7, 6,19, 8,
  120685. 7, 6, 6, 7, 9,13, 9, 9,19,11, 9, 8, 6, 7, 8,13,
  120686. 12,14,19,16,13,10, 9, 8, 9,13,14,17,19,18,18,17,
  120687. 12,11,11,13,
  120688. };
  120689. static static_codebook _huff_book__16c1_s_long = {
  120690. 2, 100,
  120691. _huff_lengthlist__16c1_s_long,
  120692. 0, 0, 0, 0, 0,
  120693. NULL,
  120694. NULL,
  120695. NULL,
  120696. NULL,
  120697. 0
  120698. };
  120699. static long _vq_quantlist__16c1_s_p1_0[] = {
  120700. 1,
  120701. 0,
  120702. 2,
  120703. };
  120704. static long _vq_lengthlist__16c1_s_p1_0[] = {
  120705. 1, 5, 5, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  120706. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120707. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120708. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120709. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120710. 0, 5, 8, 7, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0, 0,
  120711. 0, 0, 0, 7, 8, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120712. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120713. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120714. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120715. 0, 0, 5, 7, 8, 0, 0, 0, 0, 0, 0, 7, 9, 8, 0, 0,
  120716. 0, 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120717. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120718. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120719. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120720. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120721. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120722. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120723. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120724. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120725. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120726. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120727. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120728. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120729. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120730. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120731. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120732. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120733. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120734. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120735. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120736. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120737. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120738. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120739. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120740. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120741. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120742. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120743. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120744. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120745. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120746. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120747. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120748. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120749. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120750. 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 8, 7, 0, 0, 0, 0,
  120751. 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  120752. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120753. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120754. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120755. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0, 0,
  120756. 0, 0, 0, 9, 9,11, 0, 0, 0, 0, 0, 0, 9,11,10, 0,
  120757. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120758. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120759. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120760. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  120761. 0, 0, 0, 0, 8,11, 9, 0, 0, 0, 0, 0, 0, 9,10,11,
  120762. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120763. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120764. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120765. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120766. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120767. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120768. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120769. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120770. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120771. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120772. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120773. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120774. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120775. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120776. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120777. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120778. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120779. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120780. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120781. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120782. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120783. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120784. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120785. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120786. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120787. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120788. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120789. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120790. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120791. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120792. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120793. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120794. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120795. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120796. 0, 0, 5, 7, 8, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  120797. 0, 0, 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120798. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120799. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120800. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120801. 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,11,10, 0,
  120802. 0, 0, 0, 0, 0, 8, 9,11, 0, 0, 0, 0, 0, 0, 0, 0,
  120803. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120804. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120805. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120806. 0, 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,10,11,
  120807. 0, 0, 0, 0, 0, 0, 9,11, 9, 0, 0, 0, 0, 0, 0, 0,
  120808. 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120813. 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120818. 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0,
  120853. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0,
  120858. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0,
  120863. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120899. 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120904. 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120909. 0, 0, 0, 0, 0, 0, 0, 0, 0, 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,
  121116. };
  121117. static float _vq_quantthresh__16c1_s_p1_0[] = {
  121118. -0.5, 0.5,
  121119. };
  121120. static long _vq_quantmap__16c1_s_p1_0[] = {
  121121. 1, 0, 2,
  121122. };
  121123. static encode_aux_threshmatch _vq_auxt__16c1_s_p1_0 = {
  121124. _vq_quantthresh__16c1_s_p1_0,
  121125. _vq_quantmap__16c1_s_p1_0,
  121126. 3,
  121127. 3
  121128. };
  121129. static static_codebook _16c1_s_p1_0 = {
  121130. 8, 6561,
  121131. _vq_lengthlist__16c1_s_p1_0,
  121132. 1, -535822336, 1611661312, 2, 0,
  121133. _vq_quantlist__16c1_s_p1_0,
  121134. NULL,
  121135. &_vq_auxt__16c1_s_p1_0,
  121136. NULL,
  121137. 0
  121138. };
  121139. static long _vq_quantlist__16c1_s_p2_0[] = {
  121140. 2,
  121141. 1,
  121142. 3,
  121143. 0,
  121144. 4,
  121145. };
  121146. static long _vq_lengthlist__16c1_s_p2_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,
  121187. };
  121188. static float _vq_quantthresh__16c1_s_p2_0[] = {
  121189. -1.5, -0.5, 0.5, 1.5,
  121190. };
  121191. static long _vq_quantmap__16c1_s_p2_0[] = {
  121192. 3, 1, 0, 2, 4,
  121193. };
  121194. static encode_aux_threshmatch _vq_auxt__16c1_s_p2_0 = {
  121195. _vq_quantthresh__16c1_s_p2_0,
  121196. _vq_quantmap__16c1_s_p2_0,
  121197. 5,
  121198. 5
  121199. };
  121200. static static_codebook _16c1_s_p2_0 = {
  121201. 4, 625,
  121202. _vq_lengthlist__16c1_s_p2_0,
  121203. 1, -533725184, 1611661312, 3, 0,
  121204. _vq_quantlist__16c1_s_p2_0,
  121205. NULL,
  121206. &_vq_auxt__16c1_s_p2_0,
  121207. NULL,
  121208. 0
  121209. };
  121210. static long _vq_quantlist__16c1_s_p3_0[] = {
  121211. 2,
  121212. 1,
  121213. 3,
  121214. 0,
  121215. 4,
  121216. };
  121217. static long _vq_lengthlist__16c1_s_p3_0[] = {
  121218. 1, 4, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121219. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 5, 5, 7, 7, 0, 0,
  121220. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121221. 0, 0, 4, 5, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121222. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 7, 7, 9, 9,
  121223. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121224. 0, 0, 0, 0, 6, 7, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0,
  121225. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121226. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121227. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121228. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121229. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121230. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121231. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121232. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121233. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121234. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121235. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121236. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121237. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121238. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121239. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121240. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121241. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121242. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121243. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121244. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121245. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121246. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121247. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121248. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121249. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121250. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121251. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121252. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121253. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121254. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121255. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121256. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121257. 0,
  121258. };
  121259. static float _vq_quantthresh__16c1_s_p3_0[] = {
  121260. -1.5, -0.5, 0.5, 1.5,
  121261. };
  121262. static long _vq_quantmap__16c1_s_p3_0[] = {
  121263. 3, 1, 0, 2, 4,
  121264. };
  121265. static encode_aux_threshmatch _vq_auxt__16c1_s_p3_0 = {
  121266. _vq_quantthresh__16c1_s_p3_0,
  121267. _vq_quantmap__16c1_s_p3_0,
  121268. 5,
  121269. 5
  121270. };
  121271. static static_codebook _16c1_s_p3_0 = {
  121272. 4, 625,
  121273. _vq_lengthlist__16c1_s_p3_0,
  121274. 1, -533725184, 1611661312, 3, 0,
  121275. _vq_quantlist__16c1_s_p3_0,
  121276. NULL,
  121277. &_vq_auxt__16c1_s_p3_0,
  121278. NULL,
  121279. 0
  121280. };
  121281. static long _vq_quantlist__16c1_s_p4_0[] = {
  121282. 4,
  121283. 3,
  121284. 5,
  121285. 2,
  121286. 6,
  121287. 1,
  121288. 7,
  121289. 0,
  121290. 8,
  121291. };
  121292. static long _vq_lengthlist__16c1_s_p4_0[] = {
  121293. 1, 2, 3, 7, 7, 0, 0, 0, 0, 0, 0, 0, 6, 6, 0, 0,
  121294. 0, 0, 0, 0, 0, 6, 6, 0, 0, 0, 0, 0, 0, 0, 7, 7,
  121295. 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0, 0, 0,
  121296. 8, 8, 0, 0, 0, 0, 0, 0, 0, 8, 9, 0, 0, 0, 0, 0,
  121297. 0, 0,10,10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121298. 0,
  121299. };
  121300. static float _vq_quantthresh__16c1_s_p4_0[] = {
  121301. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  121302. };
  121303. static long _vq_quantmap__16c1_s_p4_0[] = {
  121304. 7, 5, 3, 1, 0, 2, 4, 6,
  121305. 8,
  121306. };
  121307. static encode_aux_threshmatch _vq_auxt__16c1_s_p4_0 = {
  121308. _vq_quantthresh__16c1_s_p4_0,
  121309. _vq_quantmap__16c1_s_p4_0,
  121310. 9,
  121311. 9
  121312. };
  121313. static static_codebook _16c1_s_p4_0 = {
  121314. 2, 81,
  121315. _vq_lengthlist__16c1_s_p4_0,
  121316. 1, -531628032, 1611661312, 4, 0,
  121317. _vq_quantlist__16c1_s_p4_0,
  121318. NULL,
  121319. &_vq_auxt__16c1_s_p4_0,
  121320. NULL,
  121321. 0
  121322. };
  121323. static long _vq_quantlist__16c1_s_p5_0[] = {
  121324. 4,
  121325. 3,
  121326. 5,
  121327. 2,
  121328. 6,
  121329. 1,
  121330. 7,
  121331. 0,
  121332. 8,
  121333. };
  121334. static long _vq_lengthlist__16c1_s_p5_0[] = {
  121335. 1, 3, 3, 5, 5, 6, 6, 8, 8, 0, 0, 0, 7, 7, 7, 7,
  121336. 9, 9, 0, 0, 0, 7, 7, 7, 7, 9, 9, 0, 0, 0, 8, 8,
  121337. 8, 8, 9, 9, 0, 0, 0, 8, 8, 8, 8,10,10, 0, 0, 0,
  121338. 9, 9, 8, 8,10,10, 0, 0, 0, 9, 9, 8, 8,10,10, 0,
  121339. 0, 0,10,10, 9, 9,10,10, 0, 0, 0, 0, 0, 9, 9,10,
  121340. 10,
  121341. };
  121342. static float _vq_quantthresh__16c1_s_p5_0[] = {
  121343. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  121344. };
  121345. static long _vq_quantmap__16c1_s_p5_0[] = {
  121346. 7, 5, 3, 1, 0, 2, 4, 6,
  121347. 8,
  121348. };
  121349. static encode_aux_threshmatch _vq_auxt__16c1_s_p5_0 = {
  121350. _vq_quantthresh__16c1_s_p5_0,
  121351. _vq_quantmap__16c1_s_p5_0,
  121352. 9,
  121353. 9
  121354. };
  121355. static static_codebook _16c1_s_p5_0 = {
  121356. 2, 81,
  121357. _vq_lengthlist__16c1_s_p5_0,
  121358. 1, -531628032, 1611661312, 4, 0,
  121359. _vq_quantlist__16c1_s_p5_0,
  121360. NULL,
  121361. &_vq_auxt__16c1_s_p5_0,
  121362. NULL,
  121363. 0
  121364. };
  121365. static long _vq_quantlist__16c1_s_p6_0[] = {
  121366. 8,
  121367. 7,
  121368. 9,
  121369. 6,
  121370. 10,
  121371. 5,
  121372. 11,
  121373. 4,
  121374. 12,
  121375. 3,
  121376. 13,
  121377. 2,
  121378. 14,
  121379. 1,
  121380. 15,
  121381. 0,
  121382. 16,
  121383. };
  121384. static long _vq_lengthlist__16c1_s_p6_0[] = {
  121385. 1, 3, 3, 6, 6, 8, 8, 9, 9, 9, 9,10,10,11,11,12,
  121386. 12, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,11,11,
  121387. 12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,11,
  121388. 11,12,12, 0, 0, 0, 8, 8, 8, 9,10, 9,10,10,10,10,
  121389. 11,11,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,10,11,
  121390. 11,11,12,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,10,
  121391. 11,11,12,12,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,
  121392. 10,11,11,12,12,13,13, 0, 0, 0, 9, 9, 9, 9,10,10,
  121393. 10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,10,
  121394. 10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,
  121395. 10,10,11,11,12,12,12,12,13,13, 0, 0, 0, 0, 0, 9,
  121396. 9,10,10,11,11,12,12,12,12,13,13, 0, 0, 0, 0, 0,
  121397. 10,10,11,10,11,11,12,12,13,13,13,13, 0, 0, 0, 0,
  121398. 0, 0, 0,10,10,11,11,12,12,13,13,13,13, 0, 0, 0,
  121399. 0, 0, 0, 0,11,11,12,12,12,12,13,13,14,14, 0, 0,
  121400. 0, 0, 0, 0, 0,11,11,12,12,12,12,13,13,14,14, 0,
  121401. 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,13,13,14,14,
  121402. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,13,13,13,13,14,
  121403. 14,
  121404. };
  121405. static float _vq_quantthresh__16c1_s_p6_0[] = {
  121406. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  121407. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  121408. };
  121409. static long _vq_quantmap__16c1_s_p6_0[] = {
  121410. 15, 13, 11, 9, 7, 5, 3, 1,
  121411. 0, 2, 4, 6, 8, 10, 12, 14,
  121412. 16,
  121413. };
  121414. static encode_aux_threshmatch _vq_auxt__16c1_s_p6_0 = {
  121415. _vq_quantthresh__16c1_s_p6_0,
  121416. _vq_quantmap__16c1_s_p6_0,
  121417. 17,
  121418. 17
  121419. };
  121420. static static_codebook _16c1_s_p6_0 = {
  121421. 2, 289,
  121422. _vq_lengthlist__16c1_s_p6_0,
  121423. 1, -529530880, 1611661312, 5, 0,
  121424. _vq_quantlist__16c1_s_p6_0,
  121425. NULL,
  121426. &_vq_auxt__16c1_s_p6_0,
  121427. NULL,
  121428. 0
  121429. };
  121430. static long _vq_quantlist__16c1_s_p7_0[] = {
  121431. 1,
  121432. 0,
  121433. 2,
  121434. };
  121435. static long _vq_lengthlist__16c1_s_p7_0[] = {
  121436. 1, 4, 4, 6, 6, 6, 7, 6, 6, 4, 7, 7,10, 9,10,10,
  121437. 10, 9, 4, 7, 7,10,10,10,11,10,10, 6,10,10,11,11,
  121438. 11,11,10,10, 6,10, 9,11,11,11,11,10,10, 6,10,10,
  121439. 11,11,11,11,10,10, 7,11,11,11,11,11,12,12,11, 6,
  121440. 10,10,11,10,10,11,11,11, 6,10,10,10,11,10,11,11,
  121441. 11,
  121442. };
  121443. static float _vq_quantthresh__16c1_s_p7_0[] = {
  121444. -5.5, 5.5,
  121445. };
  121446. static long _vq_quantmap__16c1_s_p7_0[] = {
  121447. 1, 0, 2,
  121448. };
  121449. static encode_aux_threshmatch _vq_auxt__16c1_s_p7_0 = {
  121450. _vq_quantthresh__16c1_s_p7_0,
  121451. _vq_quantmap__16c1_s_p7_0,
  121452. 3,
  121453. 3
  121454. };
  121455. static static_codebook _16c1_s_p7_0 = {
  121456. 4, 81,
  121457. _vq_lengthlist__16c1_s_p7_0,
  121458. 1, -529137664, 1618345984, 2, 0,
  121459. _vq_quantlist__16c1_s_p7_0,
  121460. NULL,
  121461. &_vq_auxt__16c1_s_p7_0,
  121462. NULL,
  121463. 0
  121464. };
  121465. static long _vq_quantlist__16c1_s_p7_1[] = {
  121466. 5,
  121467. 4,
  121468. 6,
  121469. 3,
  121470. 7,
  121471. 2,
  121472. 8,
  121473. 1,
  121474. 9,
  121475. 0,
  121476. 10,
  121477. };
  121478. static long _vq_lengthlist__16c1_s_p7_1[] = {
  121479. 2, 3, 3, 5, 6, 7, 7, 7, 7, 8, 8,10,10,10, 6, 6,
  121480. 7, 7, 8, 8, 8, 8,10,10,10, 6, 6, 7, 7, 8, 8, 8,
  121481. 8,10,10,10, 7, 7, 7, 7, 8, 8, 8, 8,10,10,10, 7,
  121482. 7, 7, 7, 8, 8, 8, 8,10,10,10, 7, 7, 8, 8, 8, 8,
  121483. 8, 8,10,10,10, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10,
  121484. 8, 8, 8, 8, 8, 8, 9, 9,10,10,10,10,10, 8, 8, 8,
  121485. 8, 9, 9,10,10,10,10,10, 9, 9, 8, 8, 9, 9,10,10,
  121486. 10,10,10, 8, 8, 8, 8, 9, 9,
  121487. };
  121488. static float _vq_quantthresh__16c1_s_p7_1[] = {
  121489. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  121490. 3.5, 4.5,
  121491. };
  121492. static long _vq_quantmap__16c1_s_p7_1[] = {
  121493. 9, 7, 5, 3, 1, 0, 2, 4,
  121494. 6, 8, 10,
  121495. };
  121496. static encode_aux_threshmatch _vq_auxt__16c1_s_p7_1 = {
  121497. _vq_quantthresh__16c1_s_p7_1,
  121498. _vq_quantmap__16c1_s_p7_1,
  121499. 11,
  121500. 11
  121501. };
  121502. static static_codebook _16c1_s_p7_1 = {
  121503. 2, 121,
  121504. _vq_lengthlist__16c1_s_p7_1,
  121505. 1, -531365888, 1611661312, 4, 0,
  121506. _vq_quantlist__16c1_s_p7_1,
  121507. NULL,
  121508. &_vq_auxt__16c1_s_p7_1,
  121509. NULL,
  121510. 0
  121511. };
  121512. static long _vq_quantlist__16c1_s_p8_0[] = {
  121513. 6,
  121514. 5,
  121515. 7,
  121516. 4,
  121517. 8,
  121518. 3,
  121519. 9,
  121520. 2,
  121521. 10,
  121522. 1,
  121523. 11,
  121524. 0,
  121525. 12,
  121526. };
  121527. static long _vq_lengthlist__16c1_s_p8_0[] = {
  121528. 1, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8, 9, 9, 6, 5, 5,
  121529. 7, 8, 8, 9, 8, 8, 9, 9,10,11, 6, 5, 5, 8, 8, 9,
  121530. 9, 8, 8, 9,10,10,11, 0, 8, 8, 8, 9, 9, 9, 9, 9,
  121531. 10,10,11,11, 0, 9, 9, 9, 8, 9, 9, 9, 9,10,10,11,
  121532. 11, 0,13,13, 9, 9,10,10,10,10,11,11,12,12, 0,14,
  121533. 13, 9, 9,10,10,10,10,11,11,12,12, 0, 0, 0,10,10,
  121534. 9, 9,11,11,12,12,13,12, 0, 0, 0,10,10, 9, 9,10,
  121535. 10,12,12,13,13, 0, 0, 0,13,14,11,10,11,11,12,12,
  121536. 13,14, 0, 0, 0,14,14,10,10,11,11,12,12,13,13, 0,
  121537. 0, 0, 0, 0,12,12,12,12,13,13,14,15, 0, 0, 0, 0,
  121538. 0,12,12,12,12,13,13,14,15,
  121539. };
  121540. static float _vq_quantthresh__16c1_s_p8_0[] = {
  121541. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  121542. 12.5, 17.5, 22.5, 27.5,
  121543. };
  121544. static long _vq_quantmap__16c1_s_p8_0[] = {
  121545. 11, 9, 7, 5, 3, 1, 0, 2,
  121546. 4, 6, 8, 10, 12,
  121547. };
  121548. static encode_aux_threshmatch _vq_auxt__16c1_s_p8_0 = {
  121549. _vq_quantthresh__16c1_s_p8_0,
  121550. _vq_quantmap__16c1_s_p8_0,
  121551. 13,
  121552. 13
  121553. };
  121554. static static_codebook _16c1_s_p8_0 = {
  121555. 2, 169,
  121556. _vq_lengthlist__16c1_s_p8_0,
  121557. 1, -526516224, 1616117760, 4, 0,
  121558. _vq_quantlist__16c1_s_p8_0,
  121559. NULL,
  121560. &_vq_auxt__16c1_s_p8_0,
  121561. NULL,
  121562. 0
  121563. };
  121564. static long _vq_quantlist__16c1_s_p8_1[] = {
  121565. 2,
  121566. 1,
  121567. 3,
  121568. 0,
  121569. 4,
  121570. };
  121571. static long _vq_lengthlist__16c1_s_p8_1[] = {
  121572. 2, 3, 3, 5, 5, 6, 6, 6, 5, 5, 6, 6, 6, 5, 5, 6,
  121573. 6, 6, 5, 5, 6, 6, 6, 5, 5,
  121574. };
  121575. static float _vq_quantthresh__16c1_s_p8_1[] = {
  121576. -1.5, -0.5, 0.5, 1.5,
  121577. };
  121578. static long _vq_quantmap__16c1_s_p8_1[] = {
  121579. 3, 1, 0, 2, 4,
  121580. };
  121581. static encode_aux_threshmatch _vq_auxt__16c1_s_p8_1 = {
  121582. _vq_quantthresh__16c1_s_p8_1,
  121583. _vq_quantmap__16c1_s_p8_1,
  121584. 5,
  121585. 5
  121586. };
  121587. static static_codebook _16c1_s_p8_1 = {
  121588. 2, 25,
  121589. _vq_lengthlist__16c1_s_p8_1,
  121590. 1, -533725184, 1611661312, 3, 0,
  121591. _vq_quantlist__16c1_s_p8_1,
  121592. NULL,
  121593. &_vq_auxt__16c1_s_p8_1,
  121594. NULL,
  121595. 0
  121596. };
  121597. static long _vq_quantlist__16c1_s_p9_0[] = {
  121598. 6,
  121599. 5,
  121600. 7,
  121601. 4,
  121602. 8,
  121603. 3,
  121604. 9,
  121605. 2,
  121606. 10,
  121607. 1,
  121608. 11,
  121609. 0,
  121610. 12,
  121611. };
  121612. static long _vq_lengthlist__16c1_s_p9_0[] = {
  121613. 1, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  121614. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  121615. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  121616. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  121617. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  121618. 9, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  121619. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  121620. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  121621. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  121622. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  121623. 8, 8, 8, 8, 8, 8, 8, 8, 8,
  121624. };
  121625. static float _vq_quantthresh__16c1_s_p9_0[] = {
  121626. -1732.5, -1417.5, -1102.5, -787.5, -472.5, -157.5, 157.5, 472.5,
  121627. 787.5, 1102.5, 1417.5, 1732.5,
  121628. };
  121629. static long _vq_quantmap__16c1_s_p9_0[] = {
  121630. 11, 9, 7, 5, 3, 1, 0, 2,
  121631. 4, 6, 8, 10, 12,
  121632. };
  121633. static encode_aux_threshmatch _vq_auxt__16c1_s_p9_0 = {
  121634. _vq_quantthresh__16c1_s_p9_0,
  121635. _vq_quantmap__16c1_s_p9_0,
  121636. 13,
  121637. 13
  121638. };
  121639. static static_codebook _16c1_s_p9_0 = {
  121640. 2, 169,
  121641. _vq_lengthlist__16c1_s_p9_0,
  121642. 1, -513964032, 1628680192, 4, 0,
  121643. _vq_quantlist__16c1_s_p9_0,
  121644. NULL,
  121645. &_vq_auxt__16c1_s_p9_0,
  121646. NULL,
  121647. 0
  121648. };
  121649. static long _vq_quantlist__16c1_s_p9_1[] = {
  121650. 7,
  121651. 6,
  121652. 8,
  121653. 5,
  121654. 9,
  121655. 4,
  121656. 10,
  121657. 3,
  121658. 11,
  121659. 2,
  121660. 12,
  121661. 1,
  121662. 13,
  121663. 0,
  121664. 14,
  121665. };
  121666. static long _vq_lengthlist__16c1_s_p9_1[] = {
  121667. 1, 4, 4, 4, 4, 8, 8,12,13,14,14,14,14,14,14, 6,
  121668. 6, 6, 6, 6,10, 9,14,14,14,14,14,14,14,14, 7, 6,
  121669. 5, 6, 6,10, 9,12,13,13,13,13,13,13,13,13, 7, 7,
  121670. 9, 9,11,11,12,13,13,13,13,13,13,13,13, 7, 7, 8,
  121671. 8,11,12,13,13,13,13,13,13,13,13,13,12,12,10,10,
  121672. 13,12,13,13,13,13,13,13,13,13,13,12,12,10,10,13,
  121673. 13,13,13,13,13,13,13,13,13,13,13,13,13,12,13,12,
  121674. 13,13,13,13,13,13,13,13,13,13,13,13,12,13,13,13,
  121675. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  121676. 13,13,13,13,13,13,13,13,13,13,13,13,12,13,13,13,
  121677. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  121678. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  121679. 13,13,13,13,13,13,13,13,13,12,13,13,13,13,13,13,
  121680. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  121681. 13,
  121682. };
  121683. static float _vq_quantthresh__16c1_s_p9_1[] = {
  121684. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  121685. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  121686. };
  121687. static long _vq_quantmap__16c1_s_p9_1[] = {
  121688. 13, 11, 9, 7, 5, 3, 1, 0,
  121689. 2, 4, 6, 8, 10, 12, 14,
  121690. };
  121691. static encode_aux_threshmatch _vq_auxt__16c1_s_p9_1 = {
  121692. _vq_quantthresh__16c1_s_p9_1,
  121693. _vq_quantmap__16c1_s_p9_1,
  121694. 15,
  121695. 15
  121696. };
  121697. static static_codebook _16c1_s_p9_1 = {
  121698. 2, 225,
  121699. _vq_lengthlist__16c1_s_p9_1,
  121700. 1, -520986624, 1620377600, 4, 0,
  121701. _vq_quantlist__16c1_s_p9_1,
  121702. NULL,
  121703. &_vq_auxt__16c1_s_p9_1,
  121704. NULL,
  121705. 0
  121706. };
  121707. static long _vq_quantlist__16c1_s_p9_2[] = {
  121708. 10,
  121709. 9,
  121710. 11,
  121711. 8,
  121712. 12,
  121713. 7,
  121714. 13,
  121715. 6,
  121716. 14,
  121717. 5,
  121718. 15,
  121719. 4,
  121720. 16,
  121721. 3,
  121722. 17,
  121723. 2,
  121724. 18,
  121725. 1,
  121726. 19,
  121727. 0,
  121728. 20,
  121729. };
  121730. static long _vq_lengthlist__16c1_s_p9_2[] = {
  121731. 1, 4, 4, 6, 6, 7, 7, 8, 7, 8, 8, 9, 9, 9, 9,10,
  121732. 10,10, 9,10,10,11,12,12, 8, 8, 8, 8, 9, 9, 9, 9,
  121733. 10,10,10,10,10,11,11,10,12,11,11,13,11, 7, 7, 8,
  121734. 8, 8, 8, 9, 9, 9,10,10,10,10, 9,10,10,11,11,12,
  121735. 11,11, 8, 8, 8, 8, 9, 9,10,10,10,10,11,11,11,11,
  121736. 11,11,11,12,11,12,12, 8, 8, 9, 9, 9, 9, 9,10,10,
  121737. 10,10,10,10,11,11,11,11,11,11,12,11, 9, 9, 9, 9,
  121738. 10,10,10,10,11,10,11,11,11,11,11,11,12,12,12,12,
  121739. 11, 9, 9, 9, 9,10,10,10,10,11,11,11,11,11,11,11,
  121740. 11,11,12,12,12,13, 9,10,10, 9,11,10,10,10,10,11,
  121741. 11,11,11,11,10,11,12,11,12,12,11,12,11,10, 9,10,
  121742. 10,11,10,11,11,11,11,11,11,11,11,11,12,12,11,12,
  121743. 12,12,10,10,10,11,10,11,11,11,11,11,11,11,11,11,
  121744. 11,11,12,13,12,12,11, 9,10,10,11,11,10,11,11,11,
  121745. 12,11,11,11,11,11,12,12,13,13,12,13,10,10,12,10,
  121746. 11,11,11,11,11,11,11,11,11,12,12,11,13,12,12,12,
  121747. 12,13,12,11,11,11,11,11,11,12,11,12,11,11,11,11,
  121748. 12,12,13,12,11,12,12,11,11,11,11,11,12,11,11,11,
  121749. 11,12,11,11,12,11,12,13,13,12,12,12,12,11,11,11,
  121750. 11,11,12,11,11,12,11,12,11,11,11,11,13,12,12,12,
  121751. 12,13,11,11,11,12,12,11,11,11,12,11,12,12,12,11,
  121752. 12,13,12,11,11,12,12,11,12,11,11,11,12,12,11,12,
  121753. 11,11,11,12,12,12,12,13,12,13,12,12,12,12,11,11,
  121754. 12,11,11,11,11,11,11,12,12,12,13,12,11,13,13,12,
  121755. 12,11,12,10,11,11,11,11,12,11,12,12,11,12,12,13,
  121756. 12,12,13,12,12,12,12,12,11,12,12,12,11,12,11,11,
  121757. 11,12,13,12,13,13,13,13,13,12,13,13,12,12,13,11,
  121758. 11,11,11,11,12,11,11,12,11,
  121759. };
  121760. static float _vq_quantthresh__16c1_s_p9_2[] = {
  121761. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  121762. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  121763. 6.5, 7.5, 8.5, 9.5,
  121764. };
  121765. static long _vq_quantmap__16c1_s_p9_2[] = {
  121766. 19, 17, 15, 13, 11, 9, 7, 5,
  121767. 3, 1, 0, 2, 4, 6, 8, 10,
  121768. 12, 14, 16, 18, 20,
  121769. };
  121770. static encode_aux_threshmatch _vq_auxt__16c1_s_p9_2 = {
  121771. _vq_quantthresh__16c1_s_p9_2,
  121772. _vq_quantmap__16c1_s_p9_2,
  121773. 21,
  121774. 21
  121775. };
  121776. static static_codebook _16c1_s_p9_2 = {
  121777. 2, 441,
  121778. _vq_lengthlist__16c1_s_p9_2,
  121779. 1, -529268736, 1611661312, 5, 0,
  121780. _vq_quantlist__16c1_s_p9_2,
  121781. NULL,
  121782. &_vq_auxt__16c1_s_p9_2,
  121783. NULL,
  121784. 0
  121785. };
  121786. static long _huff_lengthlist__16c1_s_short[] = {
  121787. 5, 6,17, 8,12, 9,10,10,12,13, 5, 2,17, 4, 9, 5,
  121788. 7, 8,11,13,16,16,16,16,16,16,16,16,16,16, 6, 4,
  121789. 16, 5,10, 5, 7,10,14,16,13, 9,16,11, 8, 7, 8, 9,
  121790. 13,16, 7, 4,16, 5, 7, 4, 6, 8,11,13, 8, 6,16, 7,
  121791. 8, 5, 5, 7, 9,13, 9, 8,16, 9, 8, 6, 6, 7, 9,13,
  121792. 11,11,16,10,10, 7, 7, 7, 9,13,13,13,16,13,13, 9,
  121793. 9, 9,10,13,
  121794. };
  121795. static static_codebook _huff_book__16c1_s_short = {
  121796. 2, 100,
  121797. _huff_lengthlist__16c1_s_short,
  121798. 0, 0, 0, 0, 0,
  121799. NULL,
  121800. NULL,
  121801. NULL,
  121802. NULL,
  121803. 0
  121804. };
  121805. static long _huff_lengthlist__16c2_s_long[] = {
  121806. 4, 7, 9, 9, 9, 8, 9,10,15,19, 5, 4, 5, 6, 7, 7,
  121807. 8, 9,14,16, 6, 5, 4, 5, 6, 7, 8,10,12,19, 7, 6,
  121808. 5, 4, 5, 6, 7, 9,11,18, 8, 7, 6, 5, 5, 5, 7, 9,
  121809. 10,17, 8, 7, 7, 5, 5, 5, 6, 7,12,18, 8, 8, 8, 7,
  121810. 7, 5, 5, 7,12,18, 8, 9,10, 9, 9, 7, 6, 7,12,17,
  121811. 14,18,16,16,15,12,11,10,12,18,15,17,18,18,18,15,
  121812. 14,14,16,18,
  121813. };
  121814. static static_codebook _huff_book__16c2_s_long = {
  121815. 2, 100,
  121816. _huff_lengthlist__16c2_s_long,
  121817. 0, 0, 0, 0, 0,
  121818. NULL,
  121819. NULL,
  121820. NULL,
  121821. NULL,
  121822. 0
  121823. };
  121824. static long _vq_quantlist__16c2_s_p1_0[] = {
  121825. 1,
  121826. 0,
  121827. 2,
  121828. };
  121829. static long _vq_lengthlist__16c2_s_p1_0[] = {
  121830. 1, 3, 3, 0, 0, 0, 0, 0, 0, 4, 5, 5, 0, 0, 0, 0,
  121831. 0, 0, 4, 5, 5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121832. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121833. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121834. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121835. 0,
  121836. };
  121837. static float _vq_quantthresh__16c2_s_p1_0[] = {
  121838. -0.5, 0.5,
  121839. };
  121840. static long _vq_quantmap__16c2_s_p1_0[] = {
  121841. 1, 0, 2,
  121842. };
  121843. static encode_aux_threshmatch _vq_auxt__16c2_s_p1_0 = {
  121844. _vq_quantthresh__16c2_s_p1_0,
  121845. _vq_quantmap__16c2_s_p1_0,
  121846. 3,
  121847. 3
  121848. };
  121849. static static_codebook _16c2_s_p1_0 = {
  121850. 4, 81,
  121851. _vq_lengthlist__16c2_s_p1_0,
  121852. 1, -535822336, 1611661312, 2, 0,
  121853. _vq_quantlist__16c2_s_p1_0,
  121854. NULL,
  121855. &_vq_auxt__16c2_s_p1_0,
  121856. NULL,
  121857. 0
  121858. };
  121859. static long _vq_quantlist__16c2_s_p2_0[] = {
  121860. 2,
  121861. 1,
  121862. 3,
  121863. 0,
  121864. 4,
  121865. };
  121866. static long _vq_lengthlist__16c2_s_p2_0[] = {
  121867. 2, 4, 3, 7, 7, 0, 0, 0, 7, 8, 0, 0, 0, 8, 8, 0,
  121868. 0, 0, 8, 8, 0, 0, 0, 8, 8, 4, 5, 4, 8, 8, 0, 0,
  121869. 0, 8, 8, 0, 0, 0, 8, 8, 0, 0, 0, 9, 9, 0, 0, 0,
  121870. 9, 9, 4, 4, 5, 8, 8, 0, 0, 0, 8, 8, 0, 0, 0, 8,
  121871. 8, 0, 0, 0, 9, 9, 0, 0, 0, 9, 9, 7, 8, 8,10,10,
  121872. 0, 0, 0,12,11, 0, 0, 0,11,11, 0, 0, 0,14,13, 0,
  121873. 0, 0,14,13, 7, 8, 8, 9,10, 0, 0, 0,11,12, 0, 0,
  121874. 0,11,11, 0, 0, 0,14,14, 0, 0, 0,13,14, 0, 0, 0,
  121875. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121876. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121877. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121878. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121879. 0, 0, 0, 0, 0, 0, 0, 0, 8, 8, 8,11,11, 0, 0, 0,
  121880. 11,11, 0, 0, 0,12,11, 0, 0, 0,12,12, 0, 0, 0,13,
  121881. 13, 8, 8, 8,11,11, 0, 0, 0,11,11, 0, 0, 0,11,12,
  121882. 0, 0, 0,12,13, 0, 0, 0,13,13, 0, 0, 0, 0, 0, 0,
  121883. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121884. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121885. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121886. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121887. 0, 0, 0, 0, 0, 8, 8, 8,12,11, 0, 0, 0,12,11, 0,
  121888. 0, 0,11,11, 0, 0, 0,13,13, 0, 0, 0,13,12, 8, 8,
  121889. 8,11,12, 0, 0, 0,11,12, 0, 0, 0,11,11, 0, 0, 0,
  121890. 13,13, 0, 0, 0,12,13, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121891. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121892. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121893. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121894. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121895. 0, 0, 8, 9, 9,14,13, 0, 0, 0,13,12, 0, 0, 0,13,
  121896. 13, 0, 0, 0,13,12, 0, 0, 0,13,13, 8, 9, 9,13,14,
  121897. 0, 0, 0,12,13, 0, 0, 0,13,13, 0, 0, 0,12,13, 0,
  121898. 0, 0,13,13, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121899. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121900. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121901. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121902. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 8,
  121903. 9, 9,14,13, 0, 0, 0,13,13, 0, 0, 0,13,12, 0, 0,
  121904. 0,13,13, 0, 0, 0,13,12, 8, 9, 9,14,14, 0, 0, 0,
  121905. 13,13, 0, 0, 0,12,13, 0, 0, 0,13,13, 0, 0, 0,12,
  121906. 13,
  121907. };
  121908. static float _vq_quantthresh__16c2_s_p2_0[] = {
  121909. -1.5, -0.5, 0.5, 1.5,
  121910. };
  121911. static long _vq_quantmap__16c2_s_p2_0[] = {
  121912. 3, 1, 0, 2, 4,
  121913. };
  121914. static encode_aux_threshmatch _vq_auxt__16c2_s_p2_0 = {
  121915. _vq_quantthresh__16c2_s_p2_0,
  121916. _vq_quantmap__16c2_s_p2_0,
  121917. 5,
  121918. 5
  121919. };
  121920. static static_codebook _16c2_s_p2_0 = {
  121921. 4, 625,
  121922. _vq_lengthlist__16c2_s_p2_0,
  121923. 1, -533725184, 1611661312, 3, 0,
  121924. _vq_quantlist__16c2_s_p2_0,
  121925. NULL,
  121926. &_vq_auxt__16c2_s_p2_0,
  121927. NULL,
  121928. 0
  121929. };
  121930. static long _vq_quantlist__16c2_s_p3_0[] = {
  121931. 4,
  121932. 3,
  121933. 5,
  121934. 2,
  121935. 6,
  121936. 1,
  121937. 7,
  121938. 0,
  121939. 8,
  121940. };
  121941. static long _vq_lengthlist__16c2_s_p3_0[] = {
  121942. 1, 3, 3, 6, 6, 7, 7, 8, 8, 0, 0, 0, 6, 6, 7, 7,
  121943. 9, 9, 0, 0, 0, 6, 6, 7, 7, 9, 9, 0, 0, 0, 7, 7,
  121944. 8, 8,10,10, 0, 0, 0, 7, 7, 8, 8,10,10, 0, 0, 0,
  121945. 7, 7, 9, 9,10,10, 0, 0, 0, 7, 7, 9, 9,10,10, 0,
  121946. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121947. 0,
  121948. };
  121949. static float _vq_quantthresh__16c2_s_p3_0[] = {
  121950. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  121951. };
  121952. static long _vq_quantmap__16c2_s_p3_0[] = {
  121953. 7, 5, 3, 1, 0, 2, 4, 6,
  121954. 8,
  121955. };
  121956. static encode_aux_threshmatch _vq_auxt__16c2_s_p3_0 = {
  121957. _vq_quantthresh__16c2_s_p3_0,
  121958. _vq_quantmap__16c2_s_p3_0,
  121959. 9,
  121960. 9
  121961. };
  121962. static static_codebook _16c2_s_p3_0 = {
  121963. 2, 81,
  121964. _vq_lengthlist__16c2_s_p3_0,
  121965. 1, -531628032, 1611661312, 4, 0,
  121966. _vq_quantlist__16c2_s_p3_0,
  121967. NULL,
  121968. &_vq_auxt__16c2_s_p3_0,
  121969. NULL,
  121970. 0
  121971. };
  121972. static long _vq_quantlist__16c2_s_p4_0[] = {
  121973. 8,
  121974. 7,
  121975. 9,
  121976. 6,
  121977. 10,
  121978. 5,
  121979. 11,
  121980. 4,
  121981. 12,
  121982. 3,
  121983. 13,
  121984. 2,
  121985. 14,
  121986. 1,
  121987. 15,
  121988. 0,
  121989. 16,
  121990. };
  121991. static long _vq_lengthlist__16c2_s_p4_0[] = {
  121992. 2, 3, 3, 5, 5, 6, 6, 7, 7, 7, 7, 8, 8, 9, 9,10,
  121993. 10, 0, 0, 0, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,10,
  121994. 11,11, 0, 0, 0, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,
  121995. 10,10,11, 0, 0, 0, 6, 6, 8, 8, 8, 8, 9, 9,10,10,
  121996. 10,11,11,11, 0, 0, 0, 6, 6, 8, 8, 9, 9, 9, 9,10,
  121997. 10,11,11,11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,
  121998. 10,10,11,11,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9,
  121999. 9,10,10,11,11,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9,
  122000. 10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 8, 8, 9,
  122001. 9,10,10,11,11,12,12,12,12, 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,
  122011. };
  122012. static float _vq_quantthresh__16c2_s_p4_0[] = {
  122013. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  122014. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  122015. };
  122016. static long _vq_quantmap__16c2_s_p4_0[] = {
  122017. 15, 13, 11, 9, 7, 5, 3, 1,
  122018. 0, 2, 4, 6, 8, 10, 12, 14,
  122019. 16,
  122020. };
  122021. static encode_aux_threshmatch _vq_auxt__16c2_s_p4_0 = {
  122022. _vq_quantthresh__16c2_s_p4_0,
  122023. _vq_quantmap__16c2_s_p4_0,
  122024. 17,
  122025. 17
  122026. };
  122027. static static_codebook _16c2_s_p4_0 = {
  122028. 2, 289,
  122029. _vq_lengthlist__16c2_s_p4_0,
  122030. 1, -529530880, 1611661312, 5, 0,
  122031. _vq_quantlist__16c2_s_p4_0,
  122032. NULL,
  122033. &_vq_auxt__16c2_s_p4_0,
  122034. NULL,
  122035. 0
  122036. };
  122037. static long _vq_quantlist__16c2_s_p5_0[] = {
  122038. 1,
  122039. 0,
  122040. 2,
  122041. };
  122042. static long _vq_lengthlist__16c2_s_p5_0[] = {
  122043. 1, 4, 4, 5, 7, 7, 6, 7, 7, 4, 6, 6,10,10,10,10,
  122044. 10,10, 4, 7, 6,10,10,10,10,10,10, 5, 9, 9, 9,12,
  122045. 11,10,11,12, 7,10,10,12,12,12,12,12,12, 7,10,10,
  122046. 11,12,12,12,12,13, 6,10,10,10,12,12,10,12,12, 7,
  122047. 10,10,11,13,12,12,12,12, 7,10,10,11,12,12,12,12,
  122048. 12,
  122049. };
  122050. static float _vq_quantthresh__16c2_s_p5_0[] = {
  122051. -5.5, 5.5,
  122052. };
  122053. static long _vq_quantmap__16c2_s_p5_0[] = {
  122054. 1, 0, 2,
  122055. };
  122056. static encode_aux_threshmatch _vq_auxt__16c2_s_p5_0 = {
  122057. _vq_quantthresh__16c2_s_p5_0,
  122058. _vq_quantmap__16c2_s_p5_0,
  122059. 3,
  122060. 3
  122061. };
  122062. static static_codebook _16c2_s_p5_0 = {
  122063. 4, 81,
  122064. _vq_lengthlist__16c2_s_p5_0,
  122065. 1, -529137664, 1618345984, 2, 0,
  122066. _vq_quantlist__16c2_s_p5_0,
  122067. NULL,
  122068. &_vq_auxt__16c2_s_p5_0,
  122069. NULL,
  122070. 0
  122071. };
  122072. static long _vq_quantlist__16c2_s_p5_1[] = {
  122073. 5,
  122074. 4,
  122075. 6,
  122076. 3,
  122077. 7,
  122078. 2,
  122079. 8,
  122080. 1,
  122081. 9,
  122082. 0,
  122083. 10,
  122084. };
  122085. static long _vq_lengthlist__16c2_s_p5_1[] = {
  122086. 2, 3, 3, 6, 6, 7, 7, 7, 7, 8, 8,11,11,11, 6, 6,
  122087. 7, 7, 8, 8, 8, 8,11,11,11, 6, 6, 7, 7, 8, 8, 8,
  122088. 8,11,11,11, 6, 6, 8, 8, 8, 8, 9, 9,11,11,11, 6,
  122089. 6, 8, 8, 8, 8, 9, 9,11,11,11, 7, 7, 8, 8, 8, 8,
  122090. 8, 8,11,11,11, 7, 7, 8, 8, 8, 8, 8, 9,11,11,11,
  122091. 8, 8, 8, 8, 8, 8, 8, 8,11,11,11,11,11, 8, 8, 8,
  122092. 8, 8, 8,11,11,11,11,11, 8, 8, 8, 8, 8, 8,11,11,
  122093. 11,11,11, 7, 7, 8, 8, 8, 8,
  122094. };
  122095. static float _vq_quantthresh__16c2_s_p5_1[] = {
  122096. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  122097. 3.5, 4.5,
  122098. };
  122099. static long _vq_quantmap__16c2_s_p5_1[] = {
  122100. 9, 7, 5, 3, 1, 0, 2, 4,
  122101. 6, 8, 10,
  122102. };
  122103. static encode_aux_threshmatch _vq_auxt__16c2_s_p5_1 = {
  122104. _vq_quantthresh__16c2_s_p5_1,
  122105. _vq_quantmap__16c2_s_p5_1,
  122106. 11,
  122107. 11
  122108. };
  122109. static static_codebook _16c2_s_p5_1 = {
  122110. 2, 121,
  122111. _vq_lengthlist__16c2_s_p5_1,
  122112. 1, -531365888, 1611661312, 4, 0,
  122113. _vq_quantlist__16c2_s_p5_1,
  122114. NULL,
  122115. &_vq_auxt__16c2_s_p5_1,
  122116. NULL,
  122117. 0
  122118. };
  122119. static long _vq_quantlist__16c2_s_p6_0[] = {
  122120. 6,
  122121. 5,
  122122. 7,
  122123. 4,
  122124. 8,
  122125. 3,
  122126. 9,
  122127. 2,
  122128. 10,
  122129. 1,
  122130. 11,
  122131. 0,
  122132. 12,
  122133. };
  122134. static long _vq_lengthlist__16c2_s_p6_0[] = {
  122135. 1, 4, 4, 7, 6, 8, 8, 9, 9,10,10,11,11, 5, 5, 5,
  122136. 7, 7, 9, 9, 9, 9,11,11,12,12, 6, 5, 5, 7, 7, 9,
  122137. 9,10,10,11,11,12,12, 0, 6, 6, 7, 7, 9, 9,10,10,
  122138. 11,11,12,12, 0, 7, 7, 7, 7, 9, 9,10,10,11,12,12,
  122139. 12, 0,11,11, 8, 8,10,10,11,11,12,12,13,13, 0,11,
  122140. 12, 8, 8,10,10,11,11,12,12,13,13, 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,
  122146. };
  122147. static float _vq_quantthresh__16c2_s_p6_0[] = {
  122148. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  122149. 12.5, 17.5, 22.5, 27.5,
  122150. };
  122151. static long _vq_quantmap__16c2_s_p6_0[] = {
  122152. 11, 9, 7, 5, 3, 1, 0, 2,
  122153. 4, 6, 8, 10, 12,
  122154. };
  122155. static encode_aux_threshmatch _vq_auxt__16c2_s_p6_0 = {
  122156. _vq_quantthresh__16c2_s_p6_0,
  122157. _vq_quantmap__16c2_s_p6_0,
  122158. 13,
  122159. 13
  122160. };
  122161. static static_codebook _16c2_s_p6_0 = {
  122162. 2, 169,
  122163. _vq_lengthlist__16c2_s_p6_0,
  122164. 1, -526516224, 1616117760, 4, 0,
  122165. _vq_quantlist__16c2_s_p6_0,
  122166. NULL,
  122167. &_vq_auxt__16c2_s_p6_0,
  122168. NULL,
  122169. 0
  122170. };
  122171. static long _vq_quantlist__16c2_s_p6_1[] = {
  122172. 2,
  122173. 1,
  122174. 3,
  122175. 0,
  122176. 4,
  122177. };
  122178. static long _vq_lengthlist__16c2_s_p6_1[] = {
  122179. 2, 3, 3, 5, 5, 6, 6, 6, 5, 5, 6, 6, 6, 5, 5, 6,
  122180. 6, 6, 5, 5, 6, 6, 6, 5, 5,
  122181. };
  122182. static float _vq_quantthresh__16c2_s_p6_1[] = {
  122183. -1.5, -0.5, 0.5, 1.5,
  122184. };
  122185. static long _vq_quantmap__16c2_s_p6_1[] = {
  122186. 3, 1, 0, 2, 4,
  122187. };
  122188. static encode_aux_threshmatch _vq_auxt__16c2_s_p6_1 = {
  122189. _vq_quantthresh__16c2_s_p6_1,
  122190. _vq_quantmap__16c2_s_p6_1,
  122191. 5,
  122192. 5
  122193. };
  122194. static static_codebook _16c2_s_p6_1 = {
  122195. 2, 25,
  122196. _vq_lengthlist__16c2_s_p6_1,
  122197. 1, -533725184, 1611661312, 3, 0,
  122198. _vq_quantlist__16c2_s_p6_1,
  122199. NULL,
  122200. &_vq_auxt__16c2_s_p6_1,
  122201. NULL,
  122202. 0
  122203. };
  122204. static long _vq_quantlist__16c2_s_p7_0[] = {
  122205. 6,
  122206. 5,
  122207. 7,
  122208. 4,
  122209. 8,
  122210. 3,
  122211. 9,
  122212. 2,
  122213. 10,
  122214. 1,
  122215. 11,
  122216. 0,
  122217. 12,
  122218. };
  122219. static long _vq_lengthlist__16c2_s_p7_0[] = {
  122220. 1, 4, 4, 7, 7, 8, 8, 9, 9,10,10,11,11, 5, 5, 5,
  122221. 8, 8, 9, 9,10,10,11,11,12,12, 6, 5, 5, 8, 8, 9,
  122222. 9,10,10,11,11,12,13,18, 6, 6, 7, 7, 9, 9,10,10,
  122223. 12,12,13,13,18, 6, 6, 7, 7, 9, 9,10,10,12,12,13,
  122224. 13,18,11,10, 8, 8,10,10,11,11,12,12,13,13,18,11,
  122225. 11, 8, 8,10,10,11,11,12,13,13,13,18,18,18,10,11,
  122226. 11,11,12,12,13,13,14,14,18,18,18,11,11,11,11,12,
  122227. 12,13,13,14,14,18,18,18,14,14,12,12,12,12,14,14,
  122228. 15,14,18,18,18,15,15,11,12,12,12,13,13,15,15,18,
  122229. 18,18,18,18,13,13,13,13,13,14,17,16,18,18,18,18,
  122230. 18,13,14,13,13,14,13,15,14,
  122231. };
  122232. static float _vq_quantthresh__16c2_s_p7_0[] = {
  122233. -60.5, -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5,
  122234. 27.5, 38.5, 49.5, 60.5,
  122235. };
  122236. static long _vq_quantmap__16c2_s_p7_0[] = {
  122237. 11, 9, 7, 5, 3, 1, 0, 2,
  122238. 4, 6, 8, 10, 12,
  122239. };
  122240. static encode_aux_threshmatch _vq_auxt__16c2_s_p7_0 = {
  122241. _vq_quantthresh__16c2_s_p7_0,
  122242. _vq_quantmap__16c2_s_p7_0,
  122243. 13,
  122244. 13
  122245. };
  122246. static static_codebook _16c2_s_p7_0 = {
  122247. 2, 169,
  122248. _vq_lengthlist__16c2_s_p7_0,
  122249. 1, -523206656, 1618345984, 4, 0,
  122250. _vq_quantlist__16c2_s_p7_0,
  122251. NULL,
  122252. &_vq_auxt__16c2_s_p7_0,
  122253. NULL,
  122254. 0
  122255. };
  122256. static long _vq_quantlist__16c2_s_p7_1[] = {
  122257. 5,
  122258. 4,
  122259. 6,
  122260. 3,
  122261. 7,
  122262. 2,
  122263. 8,
  122264. 1,
  122265. 9,
  122266. 0,
  122267. 10,
  122268. };
  122269. static long _vq_lengthlist__16c2_s_p7_1[] = {
  122270. 2, 4, 4, 6, 6, 7, 7, 7, 7, 7, 7, 9, 9, 9, 6, 6,
  122271. 7, 7, 8, 8, 8, 8, 9, 9, 9, 6, 6, 7, 7, 8, 8, 8,
  122272. 8, 9, 9, 9, 7, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 7,
  122273. 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 7, 7, 7, 7, 8, 8,
  122274. 8, 8, 9, 9, 9, 7, 7, 7, 7, 7, 7, 8, 8, 9, 9, 9,
  122275. 7, 7, 8, 8, 7, 7, 8, 8, 9, 9, 9, 9, 9, 7, 7, 7,
  122276. 7, 8, 8, 9, 9, 9, 9, 9, 8, 8, 7, 7, 8, 8, 9, 9,
  122277. 9, 9, 9, 7, 7, 7, 7, 8, 8,
  122278. };
  122279. static float _vq_quantthresh__16c2_s_p7_1[] = {
  122280. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  122281. 3.5, 4.5,
  122282. };
  122283. static long _vq_quantmap__16c2_s_p7_1[] = {
  122284. 9, 7, 5, 3, 1, 0, 2, 4,
  122285. 6, 8, 10,
  122286. };
  122287. static encode_aux_threshmatch _vq_auxt__16c2_s_p7_1 = {
  122288. _vq_quantthresh__16c2_s_p7_1,
  122289. _vq_quantmap__16c2_s_p7_1,
  122290. 11,
  122291. 11
  122292. };
  122293. static static_codebook _16c2_s_p7_1 = {
  122294. 2, 121,
  122295. _vq_lengthlist__16c2_s_p7_1,
  122296. 1, -531365888, 1611661312, 4, 0,
  122297. _vq_quantlist__16c2_s_p7_1,
  122298. NULL,
  122299. &_vq_auxt__16c2_s_p7_1,
  122300. NULL,
  122301. 0
  122302. };
  122303. static long _vq_quantlist__16c2_s_p8_0[] = {
  122304. 7,
  122305. 6,
  122306. 8,
  122307. 5,
  122308. 9,
  122309. 4,
  122310. 10,
  122311. 3,
  122312. 11,
  122313. 2,
  122314. 12,
  122315. 1,
  122316. 13,
  122317. 0,
  122318. 14,
  122319. };
  122320. static long _vq_lengthlist__16c2_s_p8_0[] = {
  122321. 1, 4, 4, 7, 6, 7, 7, 6, 6, 8, 8, 9, 9,10,10, 6,
  122322. 6, 6, 8, 8, 9, 8, 8, 8, 9, 9,11,10,11,11, 7, 6,
  122323. 6, 8, 8, 9, 8, 7, 7, 9, 9,10,10,12,11,14, 8, 8,
  122324. 8, 9, 9, 9, 9, 9,10, 9,10,10,11,13,14, 8, 8, 8,
  122325. 8, 9, 9, 8, 8, 9, 9,10,10,11,12,14,13,11, 9, 9,
  122326. 9, 9, 9, 9, 9,10,11,10,13,12,14,11,13, 8, 9, 9,
  122327. 9, 9, 9,10,10,11,10,13,12,14,14,14, 8, 9, 9, 9,
  122328. 11,11,11,11,11,12,13,13,14,14,14, 9, 8, 9, 9,10,
  122329. 10,12,10,11,12,12,14,14,14,14,11,12,10,10,12,12,
  122330. 12,12,13,14,12,12,14,14,14,12,12, 9,10,11,11,12,
  122331. 14,12,14,14,14,14,14,14,14,14,11,11,12,11,12,14,
  122332. 14,14,14,14,14,14,14,14,14,12,11,11,11,11,14,14,
  122333. 14,14,14,14,14,14,14,14,14,14,13,12,14,14,14,14,
  122334. 14,14,14,14,14,14,14,14,14,12,12,12,13,14,14,13,
  122335. 13,
  122336. };
  122337. static float _vq_quantthresh__16c2_s_p8_0[] = {
  122338. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  122339. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  122340. };
  122341. static long _vq_quantmap__16c2_s_p8_0[] = {
  122342. 13, 11, 9, 7, 5, 3, 1, 0,
  122343. 2, 4, 6, 8, 10, 12, 14,
  122344. };
  122345. static encode_aux_threshmatch _vq_auxt__16c2_s_p8_0 = {
  122346. _vq_quantthresh__16c2_s_p8_0,
  122347. _vq_quantmap__16c2_s_p8_0,
  122348. 15,
  122349. 15
  122350. };
  122351. static static_codebook _16c2_s_p8_0 = {
  122352. 2, 225,
  122353. _vq_lengthlist__16c2_s_p8_0,
  122354. 1, -520986624, 1620377600, 4, 0,
  122355. _vq_quantlist__16c2_s_p8_0,
  122356. NULL,
  122357. &_vq_auxt__16c2_s_p8_0,
  122358. NULL,
  122359. 0
  122360. };
  122361. static long _vq_quantlist__16c2_s_p8_1[] = {
  122362. 10,
  122363. 9,
  122364. 11,
  122365. 8,
  122366. 12,
  122367. 7,
  122368. 13,
  122369. 6,
  122370. 14,
  122371. 5,
  122372. 15,
  122373. 4,
  122374. 16,
  122375. 3,
  122376. 17,
  122377. 2,
  122378. 18,
  122379. 1,
  122380. 19,
  122381. 0,
  122382. 20,
  122383. };
  122384. static long _vq_lengthlist__16c2_s_p8_1[] = {
  122385. 2, 4, 4, 6, 6, 7, 7, 7, 7, 8, 7, 8, 8, 8, 8, 8,
  122386. 8, 8, 8, 8, 8,11,12,11, 7, 7, 8, 8, 8, 8, 9, 9,
  122387. 9, 9, 9, 9, 9, 9, 9,10, 9, 9,11,11,10, 7, 7, 8,
  122388. 8, 8, 8, 9, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,11,
  122389. 11,11, 8, 7, 8, 8, 9, 9, 9, 9, 9, 9,10,10, 9,10,
  122390. 10, 9,10,10,11,11,12, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  122391. 9, 9, 9,10, 9,10,10,10,10,11,11,11, 8, 8, 9, 9,
  122392. 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,11,11,
  122393. 11, 8, 8, 9, 8, 9, 9, 9, 9,10, 9, 9, 9,10,10,10,
  122394. 10, 9,10,11,11,11, 9, 9, 9, 9,10, 9, 9, 9,10,10,
  122395. 9,10, 9,10,10,10,10,10,11,12,11,11,11, 9, 9, 9,
  122396. 9, 9,10,10, 9,10,10,10,10,10,10,10,10,12,11,13,
  122397. 13,11, 9, 9, 9, 9,10,10, 9,10,10,10,10,11,10,10,
  122398. 10,10,11,12,11,12,11, 9, 9, 9,10,10, 9,10,10,10,
  122399. 10,10,10,10,10,10,10,11,11,11,12,11, 9,10,10,10,
  122400. 10,10,10,10,10,10,10,10,10,10,10,10,11,12,12,12,
  122401. 11,11,11,10, 9,10,10,10,10,10,10,10,10,11,10,10,
  122402. 10,11,11,11,11,11,11,11,10,10,10,11,10,10,10,10,
  122403. 10,10,10,10,10,10,11,11,11,11,12,12,11,10,10,10,
  122404. 10,10,10,10,10,11,10,10,10,11,10,12,11,11,12,11,
  122405. 11,11,10,10,10,10,10,11,10,10,10,10,10,11,10,10,
  122406. 11,11,11,12,11,12,11,11,12,10,10,10,10,10,10,10,
  122407. 11,10,10,11,10,12,11,11,11,12,11,11,11,11,10,10,
  122408. 10,10,10,10,10,11,11,11,10,11,12,11,11,11,12,11,
  122409. 12,11,12,10,11,10,10,10,10,11,10,10,10,10,10,10,
  122410. 12,11,11,11,11,11,12,12,10,10,10,10,10,11,10,10,
  122411. 11,10,11,11,11,11,11,11,11,11,11,11,11,11,12,11,
  122412. 10,11,10,10,10,10,10,10,10,
  122413. };
  122414. static float _vq_quantthresh__16c2_s_p8_1[] = {
  122415. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  122416. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  122417. 6.5, 7.5, 8.5, 9.5,
  122418. };
  122419. static long _vq_quantmap__16c2_s_p8_1[] = {
  122420. 19, 17, 15, 13, 11, 9, 7, 5,
  122421. 3, 1, 0, 2, 4, 6, 8, 10,
  122422. 12, 14, 16, 18, 20,
  122423. };
  122424. static encode_aux_threshmatch _vq_auxt__16c2_s_p8_1 = {
  122425. _vq_quantthresh__16c2_s_p8_1,
  122426. _vq_quantmap__16c2_s_p8_1,
  122427. 21,
  122428. 21
  122429. };
  122430. static static_codebook _16c2_s_p8_1 = {
  122431. 2, 441,
  122432. _vq_lengthlist__16c2_s_p8_1,
  122433. 1, -529268736, 1611661312, 5, 0,
  122434. _vq_quantlist__16c2_s_p8_1,
  122435. NULL,
  122436. &_vq_auxt__16c2_s_p8_1,
  122437. NULL,
  122438. 0
  122439. };
  122440. static long _vq_quantlist__16c2_s_p9_0[] = {
  122441. 6,
  122442. 5,
  122443. 7,
  122444. 4,
  122445. 8,
  122446. 3,
  122447. 9,
  122448. 2,
  122449. 10,
  122450. 1,
  122451. 11,
  122452. 0,
  122453. 12,
  122454. };
  122455. static long _vq_lengthlist__16c2_s_p9_0[] = {
  122456. 1, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  122457. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  122458. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  122459. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  122460. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  122461. 9, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  122462. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  122463. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  122464. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  122465. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  122466. 8, 8, 8, 8, 8, 8, 8, 8, 8,
  122467. };
  122468. static float _vq_quantthresh__16c2_s_p9_0[] = {
  122469. -5120.5, -4189.5, -3258.5, -2327.5, -1396.5, -465.5, 465.5, 1396.5,
  122470. 2327.5, 3258.5, 4189.5, 5120.5,
  122471. };
  122472. static long _vq_quantmap__16c2_s_p9_0[] = {
  122473. 11, 9, 7, 5, 3, 1, 0, 2,
  122474. 4, 6, 8, 10, 12,
  122475. };
  122476. static encode_aux_threshmatch _vq_auxt__16c2_s_p9_0 = {
  122477. _vq_quantthresh__16c2_s_p9_0,
  122478. _vq_quantmap__16c2_s_p9_0,
  122479. 13,
  122480. 13
  122481. };
  122482. static static_codebook _16c2_s_p9_0 = {
  122483. 2, 169,
  122484. _vq_lengthlist__16c2_s_p9_0,
  122485. 1, -510275072, 1631393792, 4, 0,
  122486. _vq_quantlist__16c2_s_p9_0,
  122487. NULL,
  122488. &_vq_auxt__16c2_s_p9_0,
  122489. NULL,
  122490. 0
  122491. };
  122492. static long _vq_quantlist__16c2_s_p9_1[] = {
  122493. 8,
  122494. 7,
  122495. 9,
  122496. 6,
  122497. 10,
  122498. 5,
  122499. 11,
  122500. 4,
  122501. 12,
  122502. 3,
  122503. 13,
  122504. 2,
  122505. 14,
  122506. 1,
  122507. 15,
  122508. 0,
  122509. 16,
  122510. };
  122511. static long _vq_lengthlist__16c2_s_p9_1[] = {
  122512. 1, 5, 5, 9, 8, 7, 7, 7, 6,10,11,11,11,11,11,11,
  122513. 11, 8, 7, 6, 8, 8,10, 9,10,10,10, 9,11,10,10,10,
  122514. 10,10, 8, 6, 6, 8, 8, 9, 8, 9, 8, 9,10,10,10,10,
  122515. 10,10,10,10, 8,10, 9, 9, 9, 9,10,10,10,10,10,10,
  122516. 10,10,10,10,10, 8, 9, 9, 9,10,10, 9,10,10,10,10,
  122517. 10,10,10,10,10,10,10,10, 9, 8, 9, 9,10,10,10,10,
  122518. 10,10,10,10,10,10,10,10, 9, 8, 8, 9, 9,10,10,10,
  122519. 10,10,10,10,10,10,10,10,10,10, 9,10, 9, 9,10,10,
  122520. 10,10,10,10,10,10,10,10,10,10,10, 9, 8, 9, 9,10,
  122521. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10, 9,
  122522. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  122523. 8,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  122524. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  122525. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  122526. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  122527. 10,10,10,10, 9,10, 9,10,10,10,10,10,10,10,10,10,
  122528. 10,10,10,10,10,10,10,10,10, 9,10,10,10,10,10,10,
  122529. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  122530. 10,
  122531. };
  122532. static float _vq_quantthresh__16c2_s_p9_1[] = {
  122533. -367.5, -318.5, -269.5, -220.5, -171.5, -122.5, -73.5, -24.5,
  122534. 24.5, 73.5, 122.5, 171.5, 220.5, 269.5, 318.5, 367.5,
  122535. };
  122536. static long _vq_quantmap__16c2_s_p9_1[] = {
  122537. 15, 13, 11, 9, 7, 5, 3, 1,
  122538. 0, 2, 4, 6, 8, 10, 12, 14,
  122539. 16,
  122540. };
  122541. static encode_aux_threshmatch _vq_auxt__16c2_s_p9_1 = {
  122542. _vq_quantthresh__16c2_s_p9_1,
  122543. _vq_quantmap__16c2_s_p9_1,
  122544. 17,
  122545. 17
  122546. };
  122547. static static_codebook _16c2_s_p9_1 = {
  122548. 2, 289,
  122549. _vq_lengthlist__16c2_s_p9_1,
  122550. 1, -518488064, 1622704128, 5, 0,
  122551. _vq_quantlist__16c2_s_p9_1,
  122552. NULL,
  122553. &_vq_auxt__16c2_s_p9_1,
  122554. NULL,
  122555. 0
  122556. };
  122557. static long _vq_quantlist__16c2_s_p9_2[] = {
  122558. 13,
  122559. 12,
  122560. 14,
  122561. 11,
  122562. 15,
  122563. 10,
  122564. 16,
  122565. 9,
  122566. 17,
  122567. 8,
  122568. 18,
  122569. 7,
  122570. 19,
  122571. 6,
  122572. 20,
  122573. 5,
  122574. 21,
  122575. 4,
  122576. 22,
  122577. 3,
  122578. 23,
  122579. 2,
  122580. 24,
  122581. 1,
  122582. 25,
  122583. 0,
  122584. 26,
  122585. };
  122586. static long _vq_lengthlist__16c2_s_p9_2[] = {
  122587. 1, 4, 4, 5, 5, 6, 6, 6, 6, 6, 7, 7, 7, 7, 7, 7,
  122588. 7, 7, 7, 7, 8, 7, 8, 7, 7, 4, 4,
  122589. };
  122590. static float _vq_quantthresh__16c2_s_p9_2[] = {
  122591. -12.5, -11.5, -10.5, -9.5, -8.5, -7.5, -6.5, -5.5,
  122592. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  122593. 3.5, 4.5, 5.5, 6.5, 7.5, 8.5, 9.5, 10.5,
  122594. 11.5, 12.5,
  122595. };
  122596. static long _vq_quantmap__16c2_s_p9_2[] = {
  122597. 25, 23, 21, 19, 17, 15, 13, 11,
  122598. 9, 7, 5, 3, 1, 0, 2, 4,
  122599. 6, 8, 10, 12, 14, 16, 18, 20,
  122600. 22, 24, 26,
  122601. };
  122602. static encode_aux_threshmatch _vq_auxt__16c2_s_p9_2 = {
  122603. _vq_quantthresh__16c2_s_p9_2,
  122604. _vq_quantmap__16c2_s_p9_2,
  122605. 27,
  122606. 27
  122607. };
  122608. static static_codebook _16c2_s_p9_2 = {
  122609. 1, 27,
  122610. _vq_lengthlist__16c2_s_p9_2,
  122611. 1, -528875520, 1611661312, 5, 0,
  122612. _vq_quantlist__16c2_s_p9_2,
  122613. NULL,
  122614. &_vq_auxt__16c2_s_p9_2,
  122615. NULL,
  122616. 0
  122617. };
  122618. static long _huff_lengthlist__16c2_s_short[] = {
  122619. 7,10,11,11,11,14,15,15,17,14, 8, 6, 7, 7, 8, 9,
  122620. 11,11,14,17, 9, 6, 6, 6, 7, 7,10,11,15,16, 9, 6,
  122621. 6, 4, 4, 5, 8, 9,12,16,10, 6, 6, 4, 4, 4, 6, 9,
  122622. 13,16,10, 7, 6, 5, 4, 3, 5, 7,13,16,11, 9, 8, 7,
  122623. 6, 5, 5, 6,12,15,10,10,10, 9, 7, 6, 6, 7,11,15,
  122624. 13,13,13,13,11,10,10, 9,12,16,16,16,16,14,16,15,
  122625. 15,12,14,14,
  122626. };
  122627. static static_codebook _huff_book__16c2_s_short = {
  122628. 2, 100,
  122629. _huff_lengthlist__16c2_s_short,
  122630. 0, 0, 0, 0, 0,
  122631. NULL,
  122632. NULL,
  122633. NULL,
  122634. NULL,
  122635. 0
  122636. };
  122637. static long _vq_quantlist__8c0_s_p1_0[] = {
  122638. 1,
  122639. 0,
  122640. 2,
  122641. };
  122642. static long _vq_lengthlist__8c0_s_p1_0[] = {
  122643. 1, 5, 4, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  122644. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122645. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122646. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122647. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122648. 0, 5, 8, 8, 0, 0, 0, 0, 0, 0, 7, 8, 9, 0, 0, 0,
  122649. 0, 0, 0, 7, 8, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122650. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122651. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122652. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122653. 0, 0, 5, 8, 8, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  122654. 0, 0, 0, 0, 7, 9, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122655. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122656. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122657. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122658. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122659. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122660. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122661. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122662. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122663. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122664. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122665. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122666. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122667. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122668. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122669. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122670. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122671. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122672. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122673. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122674. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122675. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122676. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122677. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122678. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122679. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122680. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122681. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122682. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122683. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122684. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122685. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122686. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122687. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122688. 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 8, 8, 0, 0, 0, 0,
  122689. 0, 0, 8,10,10, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0,
  122690. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122691. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122692. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122693. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7,10, 9, 0, 0, 0,
  122694. 0, 0, 0, 8, 9,11, 0, 0, 0, 0, 0, 0, 9,11,11, 0,
  122695. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122696. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122697. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122698. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 9,10, 0, 0,
  122699. 0, 0, 0, 0, 9,11,10, 0, 0, 0, 0, 0, 0, 9,11,11,
  122700. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122701. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122702. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122703. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122704. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122705. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122706. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122707. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122708. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122709. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122710. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122711. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122712. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122713. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122714. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122715. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122716. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122717. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122718. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122719. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122720. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122721. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122722. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122723. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122724. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122725. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122726. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122727. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122728. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122729. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122730. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122731. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122732. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122733. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122734. 0, 0, 5, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0,
  122735. 0, 0, 0, 0, 8, 9,10, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122736. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122737. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122738. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122739. 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,11,11, 0,
  122740. 0, 0, 0, 0, 0, 9,10,11, 0, 0, 0, 0, 0, 0, 0, 0,
  122741. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122742. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122743. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122744. 0, 0, 0, 0, 7, 9,10, 0, 0, 0, 0, 0, 0, 9,11,11,
  122745. 0, 0, 0, 0, 0, 0, 8,11, 9, 0, 0, 0, 0, 0, 0, 0,
  122746. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122747. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122748. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122749. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122750. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122751. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122752. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122753. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122754. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122755. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122756. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122757. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122758. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122759. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122760. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122761. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122762. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122763. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122764. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122765. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122766. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122767. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122768. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122769. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122770. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122771. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122772. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122773. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122774. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122775. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122776. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122777. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122778. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122779. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122780. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122781. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122782. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122783. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122784. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122785. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122786. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122787. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122788. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122789. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122790. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122791. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122792. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122793. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122794. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122795. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122796. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122797. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122798. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122799. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122800. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122801. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122802. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122803. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122804. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122805. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122806. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122807. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122808. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122809. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122810. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122811. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122812. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122813. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122814. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122815. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122816. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122817. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122818. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122819. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122820. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122821. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122822. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122823. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122824. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122825. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122826. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122827. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122828. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122829. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122830. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122831. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122832. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122833. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122834. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122835. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122836. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122837. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122838. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122839. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122840. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122841. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122842. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122843. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122844. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122845. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122846. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122847. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122848. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122849. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122850. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122851. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122852. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122853. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122854. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122855. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122856. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122857. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122858. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122859. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122860. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122861. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122862. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122863. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122864. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122865. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122866. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122867. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122868. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122869. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122870. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122871. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122872. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122873. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122874. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122875. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122876. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122877. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122878. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122879. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122880. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122881. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122882. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122883. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122884. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122885. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122886. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122887. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122888. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122889. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122890. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122891. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122892. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122893. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122894. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122895. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122896. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122897. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122898. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122899. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122900. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122901. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122902. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122903. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122904. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122905. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122906. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122907. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122908. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122909. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122910. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122911. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122912. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122913. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122914. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122915. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122916. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122917. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122918. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122919. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122920. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122921. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122922. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122923. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122924. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122925. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122926. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122927. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122928. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122929. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122930. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122931. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122932. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122933. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122934. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122935. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122936. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122937. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122938. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122939. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122940. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122941. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122942. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122943. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122944. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122945. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122946. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122947. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122948. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122949. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122950. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122951. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122952. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122953. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122954. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122955. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122956. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122957. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122958. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122959. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122960. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122961. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122962. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122963. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122964. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122965. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122966. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122967. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122968. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122969. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122970. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122971. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122972. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122973. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122974. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122975. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122976. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122977. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122978. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122979. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122980. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122981. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122982. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122983. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122984. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122985. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122986. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122987. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122988. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122989. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122990. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122991. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122992. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122993. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122994. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122995. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122996. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122997. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122998. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122999. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123000. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123001. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123002. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123003. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123004. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123005. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123006. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123007. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123008. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123009. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123010. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123011. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123012. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123013. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123014. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123015. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123016. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123017. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123018. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123019. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123020. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123021. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123022. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123023. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123024. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123025. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123026. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123027. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123028. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123029. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123030. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123031. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123032. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123033. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123034. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123035. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123036. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123037. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123038. 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123043. 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123048. 0, 0, 0, 0, 0, 0, 0, 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,
  123054. };
  123055. static float _vq_quantthresh__8c0_s_p1_0[] = {
  123056. -0.5, 0.5,
  123057. };
  123058. static long _vq_quantmap__8c0_s_p1_0[] = {
  123059. 1, 0, 2,
  123060. };
  123061. static encode_aux_threshmatch _vq_auxt__8c0_s_p1_0 = {
  123062. _vq_quantthresh__8c0_s_p1_0,
  123063. _vq_quantmap__8c0_s_p1_0,
  123064. 3,
  123065. 3
  123066. };
  123067. static static_codebook _8c0_s_p1_0 = {
  123068. 8, 6561,
  123069. _vq_lengthlist__8c0_s_p1_0,
  123070. 1, -535822336, 1611661312, 2, 0,
  123071. _vq_quantlist__8c0_s_p1_0,
  123072. NULL,
  123073. &_vq_auxt__8c0_s_p1_0,
  123074. NULL,
  123075. 0
  123076. };
  123077. static long _vq_quantlist__8c0_s_p2_0[] = {
  123078. 2,
  123079. 1,
  123080. 3,
  123081. 0,
  123082. 4,
  123083. };
  123084. static long _vq_lengthlist__8c0_s_p2_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, 0, 0, 0, 0, 0, 0,
  123088. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0,
  123093. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  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,
  123125. };
  123126. static float _vq_quantthresh__8c0_s_p2_0[] = {
  123127. -1.5, -0.5, 0.5, 1.5,
  123128. };
  123129. static long _vq_quantmap__8c0_s_p2_0[] = {
  123130. 3, 1, 0, 2, 4,
  123131. };
  123132. static encode_aux_threshmatch _vq_auxt__8c0_s_p2_0 = {
  123133. _vq_quantthresh__8c0_s_p2_0,
  123134. _vq_quantmap__8c0_s_p2_0,
  123135. 5,
  123136. 5
  123137. };
  123138. static static_codebook _8c0_s_p2_0 = {
  123139. 4, 625,
  123140. _vq_lengthlist__8c0_s_p2_0,
  123141. 1, -533725184, 1611661312, 3, 0,
  123142. _vq_quantlist__8c0_s_p2_0,
  123143. NULL,
  123144. &_vq_auxt__8c0_s_p2_0,
  123145. NULL,
  123146. 0
  123147. };
  123148. static long _vq_quantlist__8c0_s_p3_0[] = {
  123149. 2,
  123150. 1,
  123151. 3,
  123152. 0,
  123153. 4,
  123154. };
  123155. static long _vq_lengthlist__8c0_s_p3_0[] = {
  123156. 1, 4, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123157. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 5, 6, 7, 7, 0, 0,
  123158. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123159. 0, 0, 4, 5, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123160. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 7, 7, 8, 8,
  123161. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123162. 0, 0, 0, 0, 6, 7, 7, 8, 8, 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,
  123196. };
  123197. static float _vq_quantthresh__8c0_s_p3_0[] = {
  123198. -1.5, -0.5, 0.5, 1.5,
  123199. };
  123200. static long _vq_quantmap__8c0_s_p3_0[] = {
  123201. 3, 1, 0, 2, 4,
  123202. };
  123203. static encode_aux_threshmatch _vq_auxt__8c0_s_p3_0 = {
  123204. _vq_quantthresh__8c0_s_p3_0,
  123205. _vq_quantmap__8c0_s_p3_0,
  123206. 5,
  123207. 5
  123208. };
  123209. static static_codebook _8c0_s_p3_0 = {
  123210. 4, 625,
  123211. _vq_lengthlist__8c0_s_p3_0,
  123212. 1, -533725184, 1611661312, 3, 0,
  123213. _vq_quantlist__8c0_s_p3_0,
  123214. NULL,
  123215. &_vq_auxt__8c0_s_p3_0,
  123216. NULL,
  123217. 0
  123218. };
  123219. static long _vq_quantlist__8c0_s_p4_0[] = {
  123220. 4,
  123221. 3,
  123222. 5,
  123223. 2,
  123224. 6,
  123225. 1,
  123226. 7,
  123227. 0,
  123228. 8,
  123229. };
  123230. static long _vq_lengthlist__8c0_s_p4_0[] = {
  123231. 1, 2, 3, 7, 7, 0, 0, 0, 0, 0, 0, 0, 6, 6, 0, 0,
  123232. 0, 0, 0, 0, 0, 6, 6, 0, 0, 0, 0, 0, 0, 0, 7, 7,
  123233. 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0, 0, 0,
  123234. 8, 8, 0, 0, 0, 0, 0, 0, 0, 9, 8, 0, 0, 0, 0, 0,
  123235. 0, 0,10,10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123236. 0,
  123237. };
  123238. static float _vq_quantthresh__8c0_s_p4_0[] = {
  123239. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  123240. };
  123241. static long _vq_quantmap__8c0_s_p4_0[] = {
  123242. 7, 5, 3, 1, 0, 2, 4, 6,
  123243. 8,
  123244. };
  123245. static encode_aux_threshmatch _vq_auxt__8c0_s_p4_0 = {
  123246. _vq_quantthresh__8c0_s_p4_0,
  123247. _vq_quantmap__8c0_s_p4_0,
  123248. 9,
  123249. 9
  123250. };
  123251. static static_codebook _8c0_s_p4_0 = {
  123252. 2, 81,
  123253. _vq_lengthlist__8c0_s_p4_0,
  123254. 1, -531628032, 1611661312, 4, 0,
  123255. _vq_quantlist__8c0_s_p4_0,
  123256. NULL,
  123257. &_vq_auxt__8c0_s_p4_0,
  123258. NULL,
  123259. 0
  123260. };
  123261. static long _vq_quantlist__8c0_s_p5_0[] = {
  123262. 4,
  123263. 3,
  123264. 5,
  123265. 2,
  123266. 6,
  123267. 1,
  123268. 7,
  123269. 0,
  123270. 8,
  123271. };
  123272. static long _vq_lengthlist__8c0_s_p5_0[] = {
  123273. 1, 3, 3, 5, 5, 7, 6, 8, 8, 0, 0, 0, 7, 7, 7, 7,
  123274. 8, 8, 0, 0, 0, 7, 7, 7, 7, 8, 9, 0, 0, 0, 8, 8,
  123275. 8, 8, 9, 9, 0, 0, 0, 8, 8, 8, 8, 9, 9, 0, 0, 0,
  123276. 9, 9, 8, 8,10,10, 0, 0, 0, 9, 9, 8, 8,10,10, 0,
  123277. 0, 0,10,10, 9, 9,10,10, 0, 0, 0, 0, 0, 9, 9,10,
  123278. 10,
  123279. };
  123280. static float _vq_quantthresh__8c0_s_p5_0[] = {
  123281. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  123282. };
  123283. static long _vq_quantmap__8c0_s_p5_0[] = {
  123284. 7, 5, 3, 1, 0, 2, 4, 6,
  123285. 8,
  123286. };
  123287. static encode_aux_threshmatch _vq_auxt__8c0_s_p5_0 = {
  123288. _vq_quantthresh__8c0_s_p5_0,
  123289. _vq_quantmap__8c0_s_p5_0,
  123290. 9,
  123291. 9
  123292. };
  123293. static static_codebook _8c0_s_p5_0 = {
  123294. 2, 81,
  123295. _vq_lengthlist__8c0_s_p5_0,
  123296. 1, -531628032, 1611661312, 4, 0,
  123297. _vq_quantlist__8c0_s_p5_0,
  123298. NULL,
  123299. &_vq_auxt__8c0_s_p5_0,
  123300. NULL,
  123301. 0
  123302. };
  123303. static long _vq_quantlist__8c0_s_p6_0[] = {
  123304. 8,
  123305. 7,
  123306. 9,
  123307. 6,
  123308. 10,
  123309. 5,
  123310. 11,
  123311. 4,
  123312. 12,
  123313. 3,
  123314. 13,
  123315. 2,
  123316. 14,
  123317. 1,
  123318. 15,
  123319. 0,
  123320. 16,
  123321. };
  123322. static long _vq_lengthlist__8c0_s_p6_0[] = {
  123323. 1, 3, 3, 6, 6, 8, 8, 9, 9, 8, 8,10, 9,10,10,11,
  123324. 11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,11,11,
  123325. 11,12, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,11,
  123326. 11,12,11, 0, 0, 0, 8, 8, 9, 9,10,10, 9, 9,10,10,
  123327. 11,11,12,12, 0, 0, 0, 8, 8, 9, 9,10,10, 9, 9,11,
  123328. 10,11,11,12,12, 0, 0, 0, 9, 9, 9, 9,10,10,10,10,
  123329. 11,11,11,12,12,12, 0, 0, 0, 9, 9, 9, 9,10,10,10,
  123330. 10,11,11,12,12,13,13, 0, 0, 0,10,10,10,10,11,11,
  123331. 10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0,10, 9,10,
  123332. 11,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,
  123333. 10, 9,10,11,12,12,13,13,14,13, 0, 0, 0, 0, 0, 9,
  123334. 9, 9,10,10,10,11,11,13,12,13,13, 0, 0, 0, 0, 0,
  123335. 10,10,10,10,11,11,12,12,13,13,14,14, 0, 0, 0, 0,
  123336. 0, 0, 0,10,10,11,11,12,12,13,13,13,14, 0, 0, 0,
  123337. 0, 0, 0, 0,11,11,11,11,12,12,13,14,14,14, 0, 0,
  123338. 0, 0, 0, 0, 0,11,11,11,11,12,12,13,13,14,13, 0,
  123339. 0, 0, 0, 0, 0, 0,11,11,12,12,13,13,14,14,14,14,
  123340. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,14,
  123341. 14,
  123342. };
  123343. static float _vq_quantthresh__8c0_s_p6_0[] = {
  123344. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  123345. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  123346. };
  123347. static long _vq_quantmap__8c0_s_p6_0[] = {
  123348. 15, 13, 11, 9, 7, 5, 3, 1,
  123349. 0, 2, 4, 6, 8, 10, 12, 14,
  123350. 16,
  123351. };
  123352. static encode_aux_threshmatch _vq_auxt__8c0_s_p6_0 = {
  123353. _vq_quantthresh__8c0_s_p6_0,
  123354. _vq_quantmap__8c0_s_p6_0,
  123355. 17,
  123356. 17
  123357. };
  123358. static static_codebook _8c0_s_p6_0 = {
  123359. 2, 289,
  123360. _vq_lengthlist__8c0_s_p6_0,
  123361. 1, -529530880, 1611661312, 5, 0,
  123362. _vq_quantlist__8c0_s_p6_0,
  123363. NULL,
  123364. &_vq_auxt__8c0_s_p6_0,
  123365. NULL,
  123366. 0
  123367. };
  123368. static long _vq_quantlist__8c0_s_p7_0[] = {
  123369. 1,
  123370. 0,
  123371. 2,
  123372. };
  123373. static long _vq_lengthlist__8c0_s_p7_0[] = {
  123374. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 7, 7,11, 9,10,12,
  123375. 9,10, 4, 7, 7,10,10,10,11, 9, 9, 6,11,10,11,11,
  123376. 12,11,11,11, 6,10,10,11,11,12,11,10,10, 6, 9,10,
  123377. 11,11,11,11,10,10, 7,10,11,12,11,11,12,11,12, 6,
  123378. 9, 9,10, 9, 9,11,10,10, 6, 9, 9,10,10,10,11,10,
  123379. 10,
  123380. };
  123381. static float _vq_quantthresh__8c0_s_p7_0[] = {
  123382. -5.5, 5.5,
  123383. };
  123384. static long _vq_quantmap__8c0_s_p7_0[] = {
  123385. 1, 0, 2,
  123386. };
  123387. static encode_aux_threshmatch _vq_auxt__8c0_s_p7_0 = {
  123388. _vq_quantthresh__8c0_s_p7_0,
  123389. _vq_quantmap__8c0_s_p7_0,
  123390. 3,
  123391. 3
  123392. };
  123393. static static_codebook _8c0_s_p7_0 = {
  123394. 4, 81,
  123395. _vq_lengthlist__8c0_s_p7_0,
  123396. 1, -529137664, 1618345984, 2, 0,
  123397. _vq_quantlist__8c0_s_p7_0,
  123398. NULL,
  123399. &_vq_auxt__8c0_s_p7_0,
  123400. NULL,
  123401. 0
  123402. };
  123403. static long _vq_quantlist__8c0_s_p7_1[] = {
  123404. 5,
  123405. 4,
  123406. 6,
  123407. 3,
  123408. 7,
  123409. 2,
  123410. 8,
  123411. 1,
  123412. 9,
  123413. 0,
  123414. 10,
  123415. };
  123416. static long _vq_lengthlist__8c0_s_p7_1[] = {
  123417. 1, 3, 3, 6, 6, 8, 8, 9, 9, 9, 9,10,10,10, 7, 7,
  123418. 8, 8, 9, 9, 9, 9,10,10, 9, 7, 7, 8, 8, 9, 9, 9,
  123419. 9,10,10,10, 8, 8, 9, 9, 9, 9, 9, 9,10,10,10, 8,
  123420. 8, 9, 9, 9, 9, 8, 9,10,10,10, 8, 8, 9, 9, 9,10,
  123421. 10,10,10,10,10, 9, 9, 9, 9, 9, 9,10,10,11,10,11,
  123422. 9, 9, 9, 9,10,10,10,10,11,11,11,10,10, 9, 9,10,
  123423. 10,10, 9,11,10,10,10,10,10,10, 9, 9,10,10,11,11,
  123424. 10,10,10, 9, 9, 9,10,10,10,
  123425. };
  123426. static float _vq_quantthresh__8c0_s_p7_1[] = {
  123427. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  123428. 3.5, 4.5,
  123429. };
  123430. static long _vq_quantmap__8c0_s_p7_1[] = {
  123431. 9, 7, 5, 3, 1, 0, 2, 4,
  123432. 6, 8, 10,
  123433. };
  123434. static encode_aux_threshmatch _vq_auxt__8c0_s_p7_1 = {
  123435. _vq_quantthresh__8c0_s_p7_1,
  123436. _vq_quantmap__8c0_s_p7_1,
  123437. 11,
  123438. 11
  123439. };
  123440. static static_codebook _8c0_s_p7_1 = {
  123441. 2, 121,
  123442. _vq_lengthlist__8c0_s_p7_1,
  123443. 1, -531365888, 1611661312, 4, 0,
  123444. _vq_quantlist__8c0_s_p7_1,
  123445. NULL,
  123446. &_vq_auxt__8c0_s_p7_1,
  123447. NULL,
  123448. 0
  123449. };
  123450. static long _vq_quantlist__8c0_s_p8_0[] = {
  123451. 6,
  123452. 5,
  123453. 7,
  123454. 4,
  123455. 8,
  123456. 3,
  123457. 9,
  123458. 2,
  123459. 10,
  123460. 1,
  123461. 11,
  123462. 0,
  123463. 12,
  123464. };
  123465. static long _vq_lengthlist__8c0_s_p8_0[] = {
  123466. 1, 4, 4, 7, 6, 7, 7, 7, 7, 8, 8, 9, 9, 7, 6, 6,
  123467. 7, 7, 8, 8, 7, 7, 8, 9,10,10, 7, 6, 6, 7, 7, 8,
  123468. 7, 7, 7, 9, 9,10,12, 0, 8, 8, 8, 8, 8, 9, 8, 8,
  123469. 9, 9,10,10, 0, 8, 8, 8, 8, 8, 9, 8, 9, 9, 9,11,
  123470. 10, 0, 0,13, 9, 8, 9, 9, 9, 9,10,10,11,11, 0,13,
  123471. 0, 9, 9, 9, 9, 9, 9,11,10,11,11, 0, 0, 0, 8, 9,
  123472. 10, 9,10,10,13,11,12,12, 0, 0, 0, 8, 9, 9, 9,10,
  123473. 10,13,12,12,13, 0, 0, 0,12, 0,10,10,12,11,10,11,
  123474. 12,12, 0, 0, 0,13,13,10,10,10,11,12, 0,13, 0, 0,
  123475. 0, 0, 0, 0,13,11, 0,12,12,12,13,12, 0, 0, 0, 0,
  123476. 0, 0,13,13,11,13,13,11,12,
  123477. };
  123478. static float _vq_quantthresh__8c0_s_p8_0[] = {
  123479. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  123480. 12.5, 17.5, 22.5, 27.5,
  123481. };
  123482. static long _vq_quantmap__8c0_s_p8_0[] = {
  123483. 11, 9, 7, 5, 3, 1, 0, 2,
  123484. 4, 6, 8, 10, 12,
  123485. };
  123486. static encode_aux_threshmatch _vq_auxt__8c0_s_p8_0 = {
  123487. _vq_quantthresh__8c0_s_p8_0,
  123488. _vq_quantmap__8c0_s_p8_0,
  123489. 13,
  123490. 13
  123491. };
  123492. static static_codebook _8c0_s_p8_0 = {
  123493. 2, 169,
  123494. _vq_lengthlist__8c0_s_p8_0,
  123495. 1, -526516224, 1616117760, 4, 0,
  123496. _vq_quantlist__8c0_s_p8_0,
  123497. NULL,
  123498. &_vq_auxt__8c0_s_p8_0,
  123499. NULL,
  123500. 0
  123501. };
  123502. static long _vq_quantlist__8c0_s_p8_1[] = {
  123503. 2,
  123504. 1,
  123505. 3,
  123506. 0,
  123507. 4,
  123508. };
  123509. static long _vq_lengthlist__8c0_s_p8_1[] = {
  123510. 1, 3, 4, 5, 5, 7, 6, 6, 6, 5, 7, 7, 7, 6, 6, 7,
  123511. 7, 7, 6, 6, 7, 7, 7, 6, 6,
  123512. };
  123513. static float _vq_quantthresh__8c0_s_p8_1[] = {
  123514. -1.5, -0.5, 0.5, 1.5,
  123515. };
  123516. static long _vq_quantmap__8c0_s_p8_1[] = {
  123517. 3, 1, 0, 2, 4,
  123518. };
  123519. static encode_aux_threshmatch _vq_auxt__8c0_s_p8_1 = {
  123520. _vq_quantthresh__8c0_s_p8_1,
  123521. _vq_quantmap__8c0_s_p8_1,
  123522. 5,
  123523. 5
  123524. };
  123525. static static_codebook _8c0_s_p8_1 = {
  123526. 2, 25,
  123527. _vq_lengthlist__8c0_s_p8_1,
  123528. 1, -533725184, 1611661312, 3, 0,
  123529. _vq_quantlist__8c0_s_p8_1,
  123530. NULL,
  123531. &_vq_auxt__8c0_s_p8_1,
  123532. NULL,
  123533. 0
  123534. };
  123535. static long _vq_quantlist__8c0_s_p9_0[] = {
  123536. 1,
  123537. 0,
  123538. 2,
  123539. };
  123540. static long _vq_lengthlist__8c0_s_p9_0[] = {
  123541. 1, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  123542. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  123543. 8, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  123544. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  123545. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  123546. 7,
  123547. };
  123548. static float _vq_quantthresh__8c0_s_p9_0[] = {
  123549. -157.5, 157.5,
  123550. };
  123551. static long _vq_quantmap__8c0_s_p9_0[] = {
  123552. 1, 0, 2,
  123553. };
  123554. static encode_aux_threshmatch _vq_auxt__8c0_s_p9_0 = {
  123555. _vq_quantthresh__8c0_s_p9_0,
  123556. _vq_quantmap__8c0_s_p9_0,
  123557. 3,
  123558. 3
  123559. };
  123560. static static_codebook _8c0_s_p9_0 = {
  123561. 4, 81,
  123562. _vq_lengthlist__8c0_s_p9_0,
  123563. 1, -518803456, 1628680192, 2, 0,
  123564. _vq_quantlist__8c0_s_p9_0,
  123565. NULL,
  123566. &_vq_auxt__8c0_s_p9_0,
  123567. NULL,
  123568. 0
  123569. };
  123570. static long _vq_quantlist__8c0_s_p9_1[] = {
  123571. 7,
  123572. 6,
  123573. 8,
  123574. 5,
  123575. 9,
  123576. 4,
  123577. 10,
  123578. 3,
  123579. 11,
  123580. 2,
  123581. 12,
  123582. 1,
  123583. 13,
  123584. 0,
  123585. 14,
  123586. };
  123587. static long _vq_lengthlist__8c0_s_p9_1[] = {
  123588. 1, 4, 4, 5, 5,10, 8,11,11,11,11,11,11,11,11, 6,
  123589. 6, 6, 7, 6,11,10,11,11,11,11,11,11,11,11, 7, 5,
  123590. 6, 6, 6, 8, 7,11,11,11,11,11,11,11,11,11, 7, 8,
  123591. 8, 8, 9, 9,11,11,11,11,11,11,11,11,11, 9, 8, 7,
  123592. 8, 9,11,11,11,11,11,11,11,11,11,11,11,10,11,11,
  123593. 11,11,11,11,11,11,11,11,11,11,11,11,11,10,11,11,
  123594. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  123595. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  123596. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  123597. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  123598. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  123599. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  123600. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  123601. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  123602. 11,
  123603. };
  123604. static float _vq_quantthresh__8c0_s_p9_1[] = {
  123605. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  123606. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  123607. };
  123608. static long _vq_quantmap__8c0_s_p9_1[] = {
  123609. 13, 11, 9, 7, 5, 3, 1, 0,
  123610. 2, 4, 6, 8, 10, 12, 14,
  123611. };
  123612. static encode_aux_threshmatch _vq_auxt__8c0_s_p9_1 = {
  123613. _vq_quantthresh__8c0_s_p9_1,
  123614. _vq_quantmap__8c0_s_p9_1,
  123615. 15,
  123616. 15
  123617. };
  123618. static static_codebook _8c0_s_p9_1 = {
  123619. 2, 225,
  123620. _vq_lengthlist__8c0_s_p9_1,
  123621. 1, -520986624, 1620377600, 4, 0,
  123622. _vq_quantlist__8c0_s_p9_1,
  123623. NULL,
  123624. &_vq_auxt__8c0_s_p9_1,
  123625. NULL,
  123626. 0
  123627. };
  123628. static long _vq_quantlist__8c0_s_p9_2[] = {
  123629. 10,
  123630. 9,
  123631. 11,
  123632. 8,
  123633. 12,
  123634. 7,
  123635. 13,
  123636. 6,
  123637. 14,
  123638. 5,
  123639. 15,
  123640. 4,
  123641. 16,
  123642. 3,
  123643. 17,
  123644. 2,
  123645. 18,
  123646. 1,
  123647. 19,
  123648. 0,
  123649. 20,
  123650. };
  123651. static long _vq_lengthlist__8c0_s_p9_2[] = {
  123652. 1, 5, 5, 7, 7, 8, 7, 8, 8,10,10, 9, 9,10,10,10,
  123653. 11,11,10,12,11,12,12,12, 9, 8, 8, 8, 8, 8, 9,10,
  123654. 10,10,10,11,11,11,10,11,11,12,12,11,12, 8, 8, 7,
  123655. 7, 8, 9,10,10,10, 9,10,10, 9,10,10,11,11,11,11,
  123656. 11,11, 9, 9, 9, 9, 8, 9,10,10,11,10,10,11,11,12,
  123657. 10,10,12,12,11,11,10, 9, 9,10, 8, 9,10,10,10, 9,
  123658. 10,10,11,11,10,11,10,10,10,12,12,12, 9,10, 9,10,
  123659. 9, 9,10,10,11,11,11,11,10,10,10,11,12,11,12,11,
  123660. 12,10,11,10,11, 9,10, 9,10, 9,10,10, 9,10,10,11,
  123661. 10,11,11,11,11,12,11, 9,10,10,10,10,11,11,11,11,
  123662. 11,10,11,11,11,11,10,12,10,12,12,11,12,10,10,11,
  123663. 10, 9,11,10,11, 9,10,11,10,10,10,11,11,11,11,12,
  123664. 12,10, 9, 9,11,10, 9,12,11,10,12,12,11,11,11,11,
  123665. 10,11,11,12,11,10,12, 9,11,10,11,10,10,11,10,11,
  123666. 9,10,10,10,11,12,11,11,12,11,10,10,11,11, 9,10,
  123667. 10,12,10,11,10,10,10, 9,10,10,10,10, 9,10,10,11,
  123668. 11,11,11,12,11,10,10,10,10,11,11,10,11,11, 9,11,
  123669. 10,12,10,12,11,10,11,10,10,10,11,10,10,11,11,10,
  123670. 11,10,10,10,10,11,11,12,10,10,10,11,10,11,12,11,
  123671. 10,11,10,10,11,11,10,12,10, 9,10,10,11,11,11,10,
  123672. 12,10,10,11,11,11,10,10,11,10,10,10,11,10,11,10,
  123673. 12,11,11,10,10,10,12,10,10,11, 9,10,11,11,11,10,
  123674. 10,11,10,10, 9,11,11,12,12,11,12,11,11,11,11,11,
  123675. 11, 9,10,11,10,12,10,10,10,10,11,10,10,11,10,10,
  123676. 12,10,10,10,10,10, 9,12,10,10,10,10,12, 9,11,10,
  123677. 10,11,10,12,12,10,12,12,12,10,10,10,10, 9,10,11,
  123678. 10,10,12,10,10,12,11,10,11,10,10,12,11,10,12,10,
  123679. 10,11, 9,11,10, 9,10, 9,10,
  123680. };
  123681. static float _vq_quantthresh__8c0_s_p9_2[] = {
  123682. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  123683. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  123684. 6.5, 7.5, 8.5, 9.5,
  123685. };
  123686. static long _vq_quantmap__8c0_s_p9_2[] = {
  123687. 19, 17, 15, 13, 11, 9, 7, 5,
  123688. 3, 1, 0, 2, 4, 6, 8, 10,
  123689. 12, 14, 16, 18, 20,
  123690. };
  123691. static encode_aux_threshmatch _vq_auxt__8c0_s_p9_2 = {
  123692. _vq_quantthresh__8c0_s_p9_2,
  123693. _vq_quantmap__8c0_s_p9_2,
  123694. 21,
  123695. 21
  123696. };
  123697. static static_codebook _8c0_s_p9_2 = {
  123698. 2, 441,
  123699. _vq_lengthlist__8c0_s_p9_2,
  123700. 1, -529268736, 1611661312, 5, 0,
  123701. _vq_quantlist__8c0_s_p9_2,
  123702. NULL,
  123703. &_vq_auxt__8c0_s_p9_2,
  123704. NULL,
  123705. 0
  123706. };
  123707. static long _huff_lengthlist__8c0_s_single[] = {
  123708. 4, 5,18, 7,10, 6, 7, 8, 9,10, 5, 2,18, 5, 7, 5,
  123709. 6, 7, 8,11,17,17,17,17,17,17,17,17,17,17, 7, 4,
  123710. 17, 6, 9, 6, 8,10,12,15,11, 7,17, 9, 6, 6, 7, 9,
  123711. 11,15, 6, 4,17, 6, 6, 4, 5, 8,11,16, 6, 6,17, 8,
  123712. 6, 5, 6, 9,13,16, 8, 9,17,11, 9, 8, 8,11,13,17,
  123713. 9,12,17,15,14,13,12,13,14,17,12,15,17,17,17,17,
  123714. 17,16,17,17,
  123715. };
  123716. static static_codebook _huff_book__8c0_s_single = {
  123717. 2, 100,
  123718. _huff_lengthlist__8c0_s_single,
  123719. 0, 0, 0, 0, 0,
  123720. NULL,
  123721. NULL,
  123722. NULL,
  123723. NULL,
  123724. 0
  123725. };
  123726. static long _vq_quantlist__8c1_s_p1_0[] = {
  123727. 1,
  123728. 0,
  123729. 2,
  123730. };
  123731. static long _vq_lengthlist__8c1_s_p1_0[] = {
  123732. 1, 5, 5, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  123733. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123734. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123735. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123736. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123737. 0, 5, 8, 7, 0, 0, 0, 0, 0, 0, 7, 8, 9, 0, 0, 0,
  123738. 0, 0, 0, 7, 8, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123739. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123740. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123741. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123742. 0, 0, 5, 7, 8, 0, 0, 0, 0, 0, 0, 7, 9, 8, 0, 0,
  123743. 0, 0, 0, 0, 7, 9, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123744. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123745. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123746. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123747. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123748. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123749. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123750. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123751. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123752. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123753. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123754. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123755. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123756. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123757. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123758. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123759. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123760. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123761. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123762. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123763. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123764. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123765. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123766. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123767. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123768. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123769. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123770. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123771. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123772. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123773. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123774. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123775. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123776. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123777. 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 8, 8, 0, 0, 0, 0,
  123778. 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0,
  123779. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123780. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123781. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123782. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0, 0,
  123783. 0, 0, 0, 8, 8,10, 0, 0, 0, 0, 0, 0, 9,10,10, 0,
  123784. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123785. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123786. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123787. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  123788. 0, 0, 0, 0, 8,10, 9, 0, 0, 0, 0, 0, 0, 9,10,10,
  123789. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123790. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123791. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123792. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123793. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123794. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123795. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123796. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123797. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123798. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123799. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123800. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123801. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123802. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123803. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123804. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123805. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123806. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123807. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123808. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123809. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123810. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123811. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123812. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123813. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123814. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123815. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123816. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123817. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123818. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123819. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123820. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123821. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123822. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123823. 0, 0, 5, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0,
  123824. 0, 0, 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123825. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123826. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123827. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123828. 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,10,10, 0,
  123829. 0, 0, 0, 0, 0, 8, 9,10, 0, 0, 0, 0, 0, 0, 0, 0,
  123830. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123831. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123832. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123833. 0, 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,10,10,
  123834. 0, 0, 0, 0, 0, 0, 8,10, 8, 0, 0, 0, 0, 0, 0, 0,
  123835. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123836. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123837. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123838. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123839. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123840. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123841. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123842. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123843. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123844. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123845. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123846. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123847. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123848. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123849. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123850. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123851. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123852. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123853. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123854. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123855. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123856. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123857. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123858. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123859. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123860. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123861. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123862. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123863. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123864. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123865. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123866. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123867. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123868. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123869. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123870. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123871. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123872. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123873. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123874. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123875. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123876. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123877. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123878. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123879. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123880. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123881. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123882. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123883. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123884. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123885. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123886. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123887. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123888. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123889. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123890. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123891. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123892. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123893. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123894. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123895. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123896. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123897. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123898. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123899. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123900. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123901. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123902. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123903. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123904. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123905. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123906. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123907. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123908. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123909. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123910. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123911. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123912. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123913. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123914. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123915. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123916. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123917. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123918. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123919. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123920. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123921. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123922. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123923. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123924. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123925. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123926. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123927. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123928. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123929. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123930. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123931. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123932. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123933. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123934. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123935. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123936. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123937. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123938. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123939. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123940. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123941. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123942. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123943. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123944. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123945. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123946. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123947. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123948. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123949. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123950. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123951. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123952. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123953. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123954. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123955. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123956. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123957. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123958. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123959. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123960. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123961. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123962. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123963. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123964. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123965. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123966. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123967. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123968. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123969. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123970. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123971. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123972. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123973. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123974. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123975. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123976. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123977. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123978. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123979. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123980. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123981. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123982. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123983. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123984. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123985. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123986. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123987. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123988. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123989. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123990. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123991. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123992. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123993. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123994. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123995. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123996. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123997. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123998. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123999. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124000. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124001. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124002. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124003. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124004. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124005. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124006. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124007. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124008. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124009. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124010. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124011. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124012. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124013. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124014. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124015. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124016. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124017. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124018. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124019. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124020. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124021. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124022. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124023. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124024. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124025. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124026. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124027. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124028. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124029. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124030. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124031. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124032. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124033. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124034. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124035. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124036. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124037. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124038. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124039. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124040. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124041. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124042. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124043. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124044. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124045. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124046. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124047. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124048. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124049. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124050. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124051. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124052. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124053. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124054. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124055. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124056. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124057. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124058. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124059. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124060. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124061. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124062. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124063. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124064. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124065. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124066. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124067. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124068. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124069. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124070. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124071. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124072. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124073. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124074. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124075. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124076. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124077. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124078. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124079. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124080. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124081. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124082. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124083. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124084. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124085. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124086. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124087. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124088. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124089. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124090. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124091. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124092. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124093. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124094. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124095. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124096. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124097. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124098. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124099. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124100. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124101. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124102. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124103. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124104. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124105. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124106. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124107. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124108. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124109. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124110. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124111. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124112. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124113. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124114. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124115. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124116. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124117. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124118. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124119. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124120. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124121. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124122. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124123. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124124. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124125. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124126. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124127. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124128. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124129. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124130. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124131. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124132. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124133. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124134. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124135. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124136. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124137. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124138. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124139. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124140. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124141. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124142. 0,
  124143. };
  124144. static float _vq_quantthresh__8c1_s_p1_0[] = {
  124145. -0.5, 0.5,
  124146. };
  124147. static long _vq_quantmap__8c1_s_p1_0[] = {
  124148. 1, 0, 2,
  124149. };
  124150. static encode_aux_threshmatch _vq_auxt__8c1_s_p1_0 = {
  124151. _vq_quantthresh__8c1_s_p1_0,
  124152. _vq_quantmap__8c1_s_p1_0,
  124153. 3,
  124154. 3
  124155. };
  124156. static static_codebook _8c1_s_p1_0 = {
  124157. 8, 6561,
  124158. _vq_lengthlist__8c1_s_p1_0,
  124159. 1, -535822336, 1611661312, 2, 0,
  124160. _vq_quantlist__8c1_s_p1_0,
  124161. NULL,
  124162. &_vq_auxt__8c1_s_p1_0,
  124163. NULL,
  124164. 0
  124165. };
  124166. static long _vq_quantlist__8c1_s_p2_0[] = {
  124167. 2,
  124168. 1,
  124169. 3,
  124170. 0,
  124171. 4,
  124172. };
  124173. static long _vq_lengthlist__8c1_s_p2_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, 0, 0, 0, 0, 0, 0, 0,
  124194. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0,
  124199. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0,
  124204. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  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,
  124214. };
  124215. static float _vq_quantthresh__8c1_s_p2_0[] = {
  124216. -1.5, -0.5, 0.5, 1.5,
  124217. };
  124218. static long _vq_quantmap__8c1_s_p2_0[] = {
  124219. 3, 1, 0, 2, 4,
  124220. };
  124221. static encode_aux_threshmatch _vq_auxt__8c1_s_p2_0 = {
  124222. _vq_quantthresh__8c1_s_p2_0,
  124223. _vq_quantmap__8c1_s_p2_0,
  124224. 5,
  124225. 5
  124226. };
  124227. static static_codebook _8c1_s_p2_0 = {
  124228. 4, 625,
  124229. _vq_lengthlist__8c1_s_p2_0,
  124230. 1, -533725184, 1611661312, 3, 0,
  124231. _vq_quantlist__8c1_s_p2_0,
  124232. NULL,
  124233. &_vq_auxt__8c1_s_p2_0,
  124234. NULL,
  124235. 0
  124236. };
  124237. static long _vq_quantlist__8c1_s_p3_0[] = {
  124238. 2,
  124239. 1,
  124240. 3,
  124241. 0,
  124242. 4,
  124243. };
  124244. static long _vq_lengthlist__8c1_s_p3_0[] = {
  124245. 2, 4, 4, 5, 5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124246. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 4, 4, 6, 6, 0, 0,
  124247. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124248. 0, 0, 4, 4, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124249. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 6, 6, 7, 7,
  124250. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124251. 0, 0, 0, 0, 6, 6, 6, 7, 7, 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,
  124285. };
  124286. static float _vq_quantthresh__8c1_s_p3_0[] = {
  124287. -1.5, -0.5, 0.5, 1.5,
  124288. };
  124289. static long _vq_quantmap__8c1_s_p3_0[] = {
  124290. 3, 1, 0, 2, 4,
  124291. };
  124292. static encode_aux_threshmatch _vq_auxt__8c1_s_p3_0 = {
  124293. _vq_quantthresh__8c1_s_p3_0,
  124294. _vq_quantmap__8c1_s_p3_0,
  124295. 5,
  124296. 5
  124297. };
  124298. static static_codebook _8c1_s_p3_0 = {
  124299. 4, 625,
  124300. _vq_lengthlist__8c1_s_p3_0,
  124301. 1, -533725184, 1611661312, 3, 0,
  124302. _vq_quantlist__8c1_s_p3_0,
  124303. NULL,
  124304. &_vq_auxt__8c1_s_p3_0,
  124305. NULL,
  124306. 0
  124307. };
  124308. static long _vq_quantlist__8c1_s_p4_0[] = {
  124309. 4,
  124310. 3,
  124311. 5,
  124312. 2,
  124313. 6,
  124314. 1,
  124315. 7,
  124316. 0,
  124317. 8,
  124318. };
  124319. static long _vq_lengthlist__8c1_s_p4_0[] = {
  124320. 1, 2, 3, 7, 7, 0, 0, 0, 0, 0, 0, 0, 6, 6, 0, 0,
  124321. 0, 0, 0, 0, 0, 6, 6, 0, 0, 0, 0, 0, 0, 0, 7, 7,
  124322. 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0, 0, 0,
  124323. 8, 8, 0, 0, 0, 0, 0, 0, 0, 9, 8, 0, 0, 0, 0, 0,
  124324. 0, 0,10,10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124325. 0,
  124326. };
  124327. static float _vq_quantthresh__8c1_s_p4_0[] = {
  124328. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  124329. };
  124330. static long _vq_quantmap__8c1_s_p4_0[] = {
  124331. 7, 5, 3, 1, 0, 2, 4, 6,
  124332. 8,
  124333. };
  124334. static encode_aux_threshmatch _vq_auxt__8c1_s_p4_0 = {
  124335. _vq_quantthresh__8c1_s_p4_0,
  124336. _vq_quantmap__8c1_s_p4_0,
  124337. 9,
  124338. 9
  124339. };
  124340. static static_codebook _8c1_s_p4_0 = {
  124341. 2, 81,
  124342. _vq_lengthlist__8c1_s_p4_0,
  124343. 1, -531628032, 1611661312, 4, 0,
  124344. _vq_quantlist__8c1_s_p4_0,
  124345. NULL,
  124346. &_vq_auxt__8c1_s_p4_0,
  124347. NULL,
  124348. 0
  124349. };
  124350. static long _vq_quantlist__8c1_s_p5_0[] = {
  124351. 4,
  124352. 3,
  124353. 5,
  124354. 2,
  124355. 6,
  124356. 1,
  124357. 7,
  124358. 0,
  124359. 8,
  124360. };
  124361. static long _vq_lengthlist__8c1_s_p5_0[] = {
  124362. 1, 3, 3, 4, 5, 6, 6, 8, 8, 0, 0, 0, 8, 8, 7, 7,
  124363. 9, 9, 0, 0, 0, 8, 8, 7, 7, 9, 9, 0, 0, 0, 9,10,
  124364. 8, 8, 9, 9, 0, 0, 0,10,10, 8, 8, 9, 9, 0, 0, 0,
  124365. 11,10, 8, 8,10,10, 0, 0, 0,11,11, 8, 8,10,10, 0,
  124366. 0, 0,12,12, 9, 9,10,10, 0, 0, 0, 0, 0, 9, 9,10,
  124367. 10,
  124368. };
  124369. static float _vq_quantthresh__8c1_s_p5_0[] = {
  124370. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  124371. };
  124372. static long _vq_quantmap__8c1_s_p5_0[] = {
  124373. 7, 5, 3, 1, 0, 2, 4, 6,
  124374. 8,
  124375. };
  124376. static encode_aux_threshmatch _vq_auxt__8c1_s_p5_0 = {
  124377. _vq_quantthresh__8c1_s_p5_0,
  124378. _vq_quantmap__8c1_s_p5_0,
  124379. 9,
  124380. 9
  124381. };
  124382. static static_codebook _8c1_s_p5_0 = {
  124383. 2, 81,
  124384. _vq_lengthlist__8c1_s_p5_0,
  124385. 1, -531628032, 1611661312, 4, 0,
  124386. _vq_quantlist__8c1_s_p5_0,
  124387. NULL,
  124388. &_vq_auxt__8c1_s_p5_0,
  124389. NULL,
  124390. 0
  124391. };
  124392. static long _vq_quantlist__8c1_s_p6_0[] = {
  124393. 8,
  124394. 7,
  124395. 9,
  124396. 6,
  124397. 10,
  124398. 5,
  124399. 11,
  124400. 4,
  124401. 12,
  124402. 3,
  124403. 13,
  124404. 2,
  124405. 14,
  124406. 1,
  124407. 15,
  124408. 0,
  124409. 16,
  124410. };
  124411. static long _vq_lengthlist__8c1_s_p6_0[] = {
  124412. 1, 3, 3, 5, 5, 8, 8, 8, 8, 9, 9,10,10,11,11,11,
  124413. 11, 0, 0, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,11,
  124414. 12,12, 0, 0, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  124415. 11,12,12, 0, 0, 0, 9, 9, 8, 8,10,10,10,10,11,11,
  124416. 12,12,12,12, 0, 0, 0, 9, 9, 8, 8,10,10,10,10,11,
  124417. 11,12,12,12,12, 0, 0, 0,10,10, 9, 9,10,10,10,10,
  124418. 11,11,12,12,13,13, 0, 0, 0,10,10, 9, 9,10,10,10,
  124419. 10,11,11,12,12,13,13, 0, 0, 0,11,11, 9, 9,10,10,
  124420. 10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,10,
  124421. 10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,
  124422. 10,10,11,11,12,12,12,12,13,13, 0, 0, 0, 0, 0, 9,
  124423. 9,10,10,11,11,12,11,12,12,13,13, 0, 0, 0, 0, 0,
  124424. 10,10,11,11,11,11,12,12,13,12,13,13, 0, 0, 0, 0,
  124425. 0, 0, 0,11,10,11,11,12,12,13,13,13,13, 0, 0, 0,
  124426. 0, 0, 0, 0,11,11,12,12,12,12,13,13,13,14, 0, 0,
  124427. 0, 0, 0, 0, 0,11,11,12,12,12,12,13,13,14,13, 0,
  124428. 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,13,13,14,14,
  124429. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,13,13,13,13,14,
  124430. 14,
  124431. };
  124432. static float _vq_quantthresh__8c1_s_p6_0[] = {
  124433. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  124434. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  124435. };
  124436. static long _vq_quantmap__8c1_s_p6_0[] = {
  124437. 15, 13, 11, 9, 7, 5, 3, 1,
  124438. 0, 2, 4, 6, 8, 10, 12, 14,
  124439. 16,
  124440. };
  124441. static encode_aux_threshmatch _vq_auxt__8c1_s_p6_0 = {
  124442. _vq_quantthresh__8c1_s_p6_0,
  124443. _vq_quantmap__8c1_s_p6_0,
  124444. 17,
  124445. 17
  124446. };
  124447. static static_codebook _8c1_s_p6_0 = {
  124448. 2, 289,
  124449. _vq_lengthlist__8c1_s_p6_0,
  124450. 1, -529530880, 1611661312, 5, 0,
  124451. _vq_quantlist__8c1_s_p6_0,
  124452. NULL,
  124453. &_vq_auxt__8c1_s_p6_0,
  124454. NULL,
  124455. 0
  124456. };
  124457. static long _vq_quantlist__8c1_s_p7_0[] = {
  124458. 1,
  124459. 0,
  124460. 2,
  124461. };
  124462. static long _vq_lengthlist__8c1_s_p7_0[] = {
  124463. 1, 4, 4, 6, 6, 6, 7, 6, 6, 4, 7, 7,10, 9, 9,10,
  124464. 9, 9, 5, 7, 7,10, 9, 9,10, 9, 9, 6,10,10,10,10,
  124465. 10,11,10,10, 6, 9, 9,10, 9,10,11,10,10, 6, 9, 9,
  124466. 10, 9, 9,11, 9,10, 7,10,10,11,11,11,11,10,10, 6,
  124467. 9, 9,10,10,10,11, 9, 9, 6, 9, 9,10,10,10,10, 9,
  124468. 9,
  124469. };
  124470. static float _vq_quantthresh__8c1_s_p7_0[] = {
  124471. -5.5, 5.5,
  124472. };
  124473. static long _vq_quantmap__8c1_s_p7_0[] = {
  124474. 1, 0, 2,
  124475. };
  124476. static encode_aux_threshmatch _vq_auxt__8c1_s_p7_0 = {
  124477. _vq_quantthresh__8c1_s_p7_0,
  124478. _vq_quantmap__8c1_s_p7_0,
  124479. 3,
  124480. 3
  124481. };
  124482. static static_codebook _8c1_s_p7_0 = {
  124483. 4, 81,
  124484. _vq_lengthlist__8c1_s_p7_0,
  124485. 1, -529137664, 1618345984, 2, 0,
  124486. _vq_quantlist__8c1_s_p7_0,
  124487. NULL,
  124488. &_vq_auxt__8c1_s_p7_0,
  124489. NULL,
  124490. 0
  124491. };
  124492. static long _vq_quantlist__8c1_s_p7_1[] = {
  124493. 5,
  124494. 4,
  124495. 6,
  124496. 3,
  124497. 7,
  124498. 2,
  124499. 8,
  124500. 1,
  124501. 9,
  124502. 0,
  124503. 10,
  124504. };
  124505. static long _vq_lengthlist__8c1_s_p7_1[] = {
  124506. 2, 3, 3, 5, 5, 7, 7, 7, 7, 7, 7,10,10, 9, 7, 7,
  124507. 7, 7, 8, 8, 8, 8, 9, 9, 9, 7, 7, 7, 7, 8, 8, 8,
  124508. 8,10,10,10, 7, 7, 7, 7, 8, 8, 8, 8,10,10,10, 7,
  124509. 7, 7, 7, 8, 8, 8, 8,10,10,10, 8, 8, 8, 8, 8, 8,
  124510. 8, 8,10,10,10, 8, 8, 8, 8, 8, 8, 8, 8,10,10,10,
  124511. 8, 8, 8, 8, 8, 8, 8, 8,10,10,10,10,10, 8, 8, 8,
  124512. 8, 8, 8,10,10,10,10,10, 8, 8, 8, 8, 8, 8,10,10,
  124513. 10,10,10, 8, 8, 8, 8, 8, 8,
  124514. };
  124515. static float _vq_quantthresh__8c1_s_p7_1[] = {
  124516. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  124517. 3.5, 4.5,
  124518. };
  124519. static long _vq_quantmap__8c1_s_p7_1[] = {
  124520. 9, 7, 5, 3, 1, 0, 2, 4,
  124521. 6, 8, 10,
  124522. };
  124523. static encode_aux_threshmatch _vq_auxt__8c1_s_p7_1 = {
  124524. _vq_quantthresh__8c1_s_p7_1,
  124525. _vq_quantmap__8c1_s_p7_1,
  124526. 11,
  124527. 11
  124528. };
  124529. static static_codebook _8c1_s_p7_1 = {
  124530. 2, 121,
  124531. _vq_lengthlist__8c1_s_p7_1,
  124532. 1, -531365888, 1611661312, 4, 0,
  124533. _vq_quantlist__8c1_s_p7_1,
  124534. NULL,
  124535. &_vq_auxt__8c1_s_p7_1,
  124536. NULL,
  124537. 0
  124538. };
  124539. static long _vq_quantlist__8c1_s_p8_0[] = {
  124540. 6,
  124541. 5,
  124542. 7,
  124543. 4,
  124544. 8,
  124545. 3,
  124546. 9,
  124547. 2,
  124548. 10,
  124549. 1,
  124550. 11,
  124551. 0,
  124552. 12,
  124553. };
  124554. static long _vq_lengthlist__8c1_s_p8_0[] = {
  124555. 1, 4, 4, 6, 6, 8, 8, 8, 8, 9, 9,10,10, 7, 5, 5,
  124556. 7, 7, 8, 8, 8, 8, 9,10,11,11, 7, 5, 5, 7, 7, 8,
  124557. 8, 9, 9,10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  124558. 9,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  124559. 11, 0,12,12, 9, 9, 9, 9,10, 9,10,11,11,11, 0,13,
  124560. 12, 9, 8, 9, 9,10,10,11,11,12,11, 0, 0, 0, 9, 9,
  124561. 9, 9,10,10,11,11,12,12, 0, 0, 0,10,10, 9, 9,10,
  124562. 10,11,11,12,12, 0, 0, 0,13,13,10,10,11,11,12,11,
  124563. 13,12, 0, 0, 0,14,14,10,10,11,10,11,11,12,12, 0,
  124564. 0, 0, 0, 0,12,12,11,11,12,12,13,13, 0, 0, 0, 0,
  124565. 0,12,12,11,10,12,11,13,12,
  124566. };
  124567. static float _vq_quantthresh__8c1_s_p8_0[] = {
  124568. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  124569. 12.5, 17.5, 22.5, 27.5,
  124570. };
  124571. static long _vq_quantmap__8c1_s_p8_0[] = {
  124572. 11, 9, 7, 5, 3, 1, 0, 2,
  124573. 4, 6, 8, 10, 12,
  124574. };
  124575. static encode_aux_threshmatch _vq_auxt__8c1_s_p8_0 = {
  124576. _vq_quantthresh__8c1_s_p8_0,
  124577. _vq_quantmap__8c1_s_p8_0,
  124578. 13,
  124579. 13
  124580. };
  124581. static static_codebook _8c1_s_p8_0 = {
  124582. 2, 169,
  124583. _vq_lengthlist__8c1_s_p8_0,
  124584. 1, -526516224, 1616117760, 4, 0,
  124585. _vq_quantlist__8c1_s_p8_0,
  124586. NULL,
  124587. &_vq_auxt__8c1_s_p8_0,
  124588. NULL,
  124589. 0
  124590. };
  124591. static long _vq_quantlist__8c1_s_p8_1[] = {
  124592. 2,
  124593. 1,
  124594. 3,
  124595. 0,
  124596. 4,
  124597. };
  124598. static long _vq_lengthlist__8c1_s_p8_1[] = {
  124599. 2, 3, 3, 5, 5, 6, 6, 6, 5, 5, 6, 6, 6, 5, 5, 6,
  124600. 6, 6, 5, 5, 6, 6, 6, 5, 5,
  124601. };
  124602. static float _vq_quantthresh__8c1_s_p8_1[] = {
  124603. -1.5, -0.5, 0.5, 1.5,
  124604. };
  124605. static long _vq_quantmap__8c1_s_p8_1[] = {
  124606. 3, 1, 0, 2, 4,
  124607. };
  124608. static encode_aux_threshmatch _vq_auxt__8c1_s_p8_1 = {
  124609. _vq_quantthresh__8c1_s_p8_1,
  124610. _vq_quantmap__8c1_s_p8_1,
  124611. 5,
  124612. 5
  124613. };
  124614. static static_codebook _8c1_s_p8_1 = {
  124615. 2, 25,
  124616. _vq_lengthlist__8c1_s_p8_1,
  124617. 1, -533725184, 1611661312, 3, 0,
  124618. _vq_quantlist__8c1_s_p8_1,
  124619. NULL,
  124620. &_vq_auxt__8c1_s_p8_1,
  124621. NULL,
  124622. 0
  124623. };
  124624. static long _vq_quantlist__8c1_s_p9_0[] = {
  124625. 6,
  124626. 5,
  124627. 7,
  124628. 4,
  124629. 8,
  124630. 3,
  124631. 9,
  124632. 2,
  124633. 10,
  124634. 1,
  124635. 11,
  124636. 0,
  124637. 12,
  124638. };
  124639. static long _vq_lengthlist__8c1_s_p9_0[] = {
  124640. 1, 3, 3,10,10,10,10,10,10,10,10,10,10, 5, 6, 6,
  124641. 10,10,10,10,10,10,10,10,10,10, 6, 7, 8,10,10,10,
  124642. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  124643. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  124644. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  124645. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  124646. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  124647. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  124648. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  124649. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  124650. 10,10,10,10,10, 9, 9, 9, 9,
  124651. };
  124652. static float _vq_quantthresh__8c1_s_p9_0[] = {
  124653. -1732.5, -1417.5, -1102.5, -787.5, -472.5, -157.5, 157.5, 472.5,
  124654. 787.5, 1102.5, 1417.5, 1732.5,
  124655. };
  124656. static long _vq_quantmap__8c1_s_p9_0[] = {
  124657. 11, 9, 7, 5, 3, 1, 0, 2,
  124658. 4, 6, 8, 10, 12,
  124659. };
  124660. static encode_aux_threshmatch _vq_auxt__8c1_s_p9_0 = {
  124661. _vq_quantthresh__8c1_s_p9_0,
  124662. _vq_quantmap__8c1_s_p9_0,
  124663. 13,
  124664. 13
  124665. };
  124666. static static_codebook _8c1_s_p9_0 = {
  124667. 2, 169,
  124668. _vq_lengthlist__8c1_s_p9_0,
  124669. 1, -513964032, 1628680192, 4, 0,
  124670. _vq_quantlist__8c1_s_p9_0,
  124671. NULL,
  124672. &_vq_auxt__8c1_s_p9_0,
  124673. NULL,
  124674. 0
  124675. };
  124676. static long _vq_quantlist__8c1_s_p9_1[] = {
  124677. 7,
  124678. 6,
  124679. 8,
  124680. 5,
  124681. 9,
  124682. 4,
  124683. 10,
  124684. 3,
  124685. 11,
  124686. 2,
  124687. 12,
  124688. 1,
  124689. 13,
  124690. 0,
  124691. 14,
  124692. };
  124693. static long _vq_lengthlist__8c1_s_p9_1[] = {
  124694. 1, 4, 4, 5, 5, 7, 7, 9, 9,11,11,12,12,13,13, 6,
  124695. 5, 5, 6, 6, 9, 9,10,10,12,12,12,13,15,14, 6, 5,
  124696. 5, 7, 7, 9, 9,10,10,12,12,12,13,14,13,17, 7, 7,
  124697. 8, 8,10,10,11,11,12,13,13,13,13,13,17, 7, 7, 8,
  124698. 8,10,10,11,11,13,13,13,13,14,14,17,11,11, 9, 9,
  124699. 11,11,12,12,12,13,13,14,15,13,17,12,12, 9, 9,11,
  124700. 11,12,12,13,13,13,13,14,16,17,17,17,11,12,12,12,
  124701. 13,13,13,14,15,14,15,15,17,17,17,12,12,11,11,13,
  124702. 13,14,14,15,14,15,15,17,17,17,15,15,13,13,14,14,
  124703. 15,14,15,15,16,15,17,17,17,15,15,13,13,13,14,14,
  124704. 15,15,15,15,16,17,17,17,17,16,14,15,14,14,15,14,
  124705. 14,15,15,15,17,17,17,17,17,14,14,16,14,15,15,15,
  124706. 15,15,15,17,17,17,17,17,17,16,16,15,17,15,15,14,
  124707. 17,15,17,16,17,17,17,17,16,15,14,15,15,15,15,15,
  124708. 15,
  124709. };
  124710. static float _vq_quantthresh__8c1_s_p9_1[] = {
  124711. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  124712. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  124713. };
  124714. static long _vq_quantmap__8c1_s_p9_1[] = {
  124715. 13, 11, 9, 7, 5, 3, 1, 0,
  124716. 2, 4, 6, 8, 10, 12, 14,
  124717. };
  124718. static encode_aux_threshmatch _vq_auxt__8c1_s_p9_1 = {
  124719. _vq_quantthresh__8c1_s_p9_1,
  124720. _vq_quantmap__8c1_s_p9_1,
  124721. 15,
  124722. 15
  124723. };
  124724. static static_codebook _8c1_s_p9_1 = {
  124725. 2, 225,
  124726. _vq_lengthlist__8c1_s_p9_1,
  124727. 1, -520986624, 1620377600, 4, 0,
  124728. _vq_quantlist__8c1_s_p9_1,
  124729. NULL,
  124730. &_vq_auxt__8c1_s_p9_1,
  124731. NULL,
  124732. 0
  124733. };
  124734. static long _vq_quantlist__8c1_s_p9_2[] = {
  124735. 10,
  124736. 9,
  124737. 11,
  124738. 8,
  124739. 12,
  124740. 7,
  124741. 13,
  124742. 6,
  124743. 14,
  124744. 5,
  124745. 15,
  124746. 4,
  124747. 16,
  124748. 3,
  124749. 17,
  124750. 2,
  124751. 18,
  124752. 1,
  124753. 19,
  124754. 0,
  124755. 20,
  124756. };
  124757. static long _vq_lengthlist__8c1_s_p9_2[] = {
  124758. 2, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8, 9, 8, 9, 9, 9,
  124759. 9, 9, 9, 9, 9,11,11,12, 7, 7, 7, 7, 8, 8, 9, 9,
  124760. 9, 9,10,10,10,10,10,10,10,10,11,11,11, 7, 7, 7,
  124761. 7, 8, 8, 9, 8, 9, 9, 9, 9, 9, 9,10,10,10,10,11,
  124762. 11,12, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9,10,10,10,10,
  124763. 10,10,10,10,11,11,11, 7, 7, 8, 8, 8, 8, 9, 9, 9,
  124764. 9,10,10,10,10,10,10,10,10,11,11,11, 8, 8, 8, 8,
  124765. 9, 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,11,11,
  124766. 11, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,10,10,10,10,10,
  124767. 10,10,10,11,12,11, 9, 9, 8, 9, 9, 9, 9, 9,10,10,
  124768. 10,10,10,10,10,10,10,10,11,11,11,11,11, 8, 8, 9,
  124769. 9, 9, 9,10,10,10,10,10,10,10,10,10,10,11,12,11,
  124770. 12,11, 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,
  124771. 10,10,11,11,11,11,11, 9, 9, 9, 9,10,10,10,10,10,
  124772. 10,10,10,10,10,10,10,12,11,12,11,11, 9, 9, 9,10,
  124773. 10,10,10,10,10,10,10,10,10,10,10,10,12,11,11,11,
  124774. 11,11,11,10,10,10,10,10,10,10,10,10,10,10,10,10,
  124775. 11,11,11,12,11,11,12,11,10,10,10,10,10,10,10,10,
  124776. 10,10,10,10,11,10,11,11,11,11,11,11,11,10,10,10,
  124777. 10,10,10,10,10,10,10,10,10,10,10,11,11,12,11,12,
  124778. 11,11,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  124779. 11,11,12,11,12,11,11,11,11,10,10,10,10,10,10,10,
  124780. 10,10,10,10,10,11,11,12,11,11,12,11,11,12,10,10,
  124781. 11,10,10,10,10,10,10,10,10,10,11,11,11,11,11,11,
  124782. 11,11,11,10,10,10,10,10,10,10,10,10,10,10,10,12,
  124783. 12,11,12,11,11,12,12,12,11,11,10,10,10,10,10,10,
  124784. 10,10,10,11,12,12,11,12,12,11,12,11,11,11,11,10,
  124785. 10,10,10,10,10,10,10,10,10,
  124786. };
  124787. static float _vq_quantthresh__8c1_s_p9_2[] = {
  124788. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  124789. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  124790. 6.5, 7.5, 8.5, 9.5,
  124791. };
  124792. static long _vq_quantmap__8c1_s_p9_2[] = {
  124793. 19, 17, 15, 13, 11, 9, 7, 5,
  124794. 3, 1, 0, 2, 4, 6, 8, 10,
  124795. 12, 14, 16, 18, 20,
  124796. };
  124797. static encode_aux_threshmatch _vq_auxt__8c1_s_p9_2 = {
  124798. _vq_quantthresh__8c1_s_p9_2,
  124799. _vq_quantmap__8c1_s_p9_2,
  124800. 21,
  124801. 21
  124802. };
  124803. static static_codebook _8c1_s_p9_2 = {
  124804. 2, 441,
  124805. _vq_lengthlist__8c1_s_p9_2,
  124806. 1, -529268736, 1611661312, 5, 0,
  124807. _vq_quantlist__8c1_s_p9_2,
  124808. NULL,
  124809. &_vq_auxt__8c1_s_p9_2,
  124810. NULL,
  124811. 0
  124812. };
  124813. static long _huff_lengthlist__8c1_s_single[] = {
  124814. 4, 6,18, 8,11, 8, 8, 9, 9,10, 4, 4,18, 5, 9, 5,
  124815. 6, 7, 8,10,18,18,18,18,17,17,17,17,17,17, 7, 5,
  124816. 17, 6,11, 6, 7, 8, 9,12,12, 9,17,12, 8, 8, 9,10,
  124817. 10,13, 7, 5,17, 6, 8, 4, 5, 6, 8,10, 6, 5,17, 6,
  124818. 8, 5, 4, 5, 7, 9, 7, 7,17, 8, 9, 6, 5, 5, 6, 8,
  124819. 8, 8,17, 9,11, 8, 6, 6, 6, 7, 9,10,17,12,12,10,
  124820. 9, 7, 7, 8,
  124821. };
  124822. static static_codebook _huff_book__8c1_s_single = {
  124823. 2, 100,
  124824. _huff_lengthlist__8c1_s_single,
  124825. 0, 0, 0, 0, 0,
  124826. NULL,
  124827. NULL,
  124828. NULL,
  124829. NULL,
  124830. 0
  124831. };
  124832. static long _huff_lengthlist__44c2_s_long[] = {
  124833. 6, 6,12,10,10,10, 9,10,12,12, 6, 1,10, 5, 6, 6,
  124834. 7, 9,11,14,12, 9, 8,11, 7, 8, 9,11,13,15,10, 5,
  124835. 12, 7, 8, 7, 9,12,14,15,10, 6, 7, 8, 5, 6, 7, 9,
  124836. 12,14, 9, 6, 8, 7, 6, 6, 7, 9,12,12, 9, 7, 9, 9,
  124837. 7, 6, 6, 7,10,10,10, 9,10,11, 8, 7, 6, 6, 8,10,
  124838. 12,11,13,13,11,10, 8, 8, 8,10,11,13,15,15,14,13,
  124839. 10, 8, 8, 9,
  124840. };
  124841. static static_codebook _huff_book__44c2_s_long = {
  124842. 2, 100,
  124843. _huff_lengthlist__44c2_s_long,
  124844. 0, 0, 0, 0, 0,
  124845. NULL,
  124846. NULL,
  124847. NULL,
  124848. NULL,
  124849. 0
  124850. };
  124851. static long _vq_quantlist__44c2_s_p1_0[] = {
  124852. 1,
  124853. 0,
  124854. 2,
  124855. };
  124856. static long _vq_lengthlist__44c2_s_p1_0[] = {
  124857. 2, 4, 4, 0, 0, 0, 0, 0, 0, 5, 6, 6, 0, 0, 0, 0,
  124858. 0, 0, 5, 6, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124859. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124860. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124861. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124862. 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0, 0,
  124863. 0, 0, 0, 6, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124864. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124865. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124866. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124867. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 6, 8, 7, 0, 0,
  124868. 0, 0, 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124869. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124870. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124871. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124872. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124873. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124874. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124875. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124876. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124877. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124878. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124879. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124880. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124881. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124882. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124883. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124884. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124885. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124886. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124887. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124888. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124889. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124890. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124891. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124892. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124893. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124894. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124895. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124896. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124897. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124898. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124899. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124900. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124901. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124902. 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  124903. 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0,
  124904. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124905. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124906. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124907. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0, 0,
  124908. 0, 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0,
  124909. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124910. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124911. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124912. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 8, 8, 0, 0,
  124913. 0, 0, 0, 0, 8, 9, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9,
  124914. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124915. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124916. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124917. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124918. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124919. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124920. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124921. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124922. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124923. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124924. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124925. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124926. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124927. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124928. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124929. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124930. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124931. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124932. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124933. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124934. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124935. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124936. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124937. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124938. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124939. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124940. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124941. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124942. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124943. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124944. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124945. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124946. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124947. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124948. 0, 0, 4, 7, 7, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0,
  124949. 0, 0, 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124950. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124951. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124952. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124953. 0, 0, 0, 6, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0,
  124954. 0, 0, 0, 0, 0, 8, 8, 9, 0, 0, 0, 0, 0, 0, 0, 0,
  124955. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124956. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124957. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124958. 0, 0, 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9,
  124959. 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 0,
  124960. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124961. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124962. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124963. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124964. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124965. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124966. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124967. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124968. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124969. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124970. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124971. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124972. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124973. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124974. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124975. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124976. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124977. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124978. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124979. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124980. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124981. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124982. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124983. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124984. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124985. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124986. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124987. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124988. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124989. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124990. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124991. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124992. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124993. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124994. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124995. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124996. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124997. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124998. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124999. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125000. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125001. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125002. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125003. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125004. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125005. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125006. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125007. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125008. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125009. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125010. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125011. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125012. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125013. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125014. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125015. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125016. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125017. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125018. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125019. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125020. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125021. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125022. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125023. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125024. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125025. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125026. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125027. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125028. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125029. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125030. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125031. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125032. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125033. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125034. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125035. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125036. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125037. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125038. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125039. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125040. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125041. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125042. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125043. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125044. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125045. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125046. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125047. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125048. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125049. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125050. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125051. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125052. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125053. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125054. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125055. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125056. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125057. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125058. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125059. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125060. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125061. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125062. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125063. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125064. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125065. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125066. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125067. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125068. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125069. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125070. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125071. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125072. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125073. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125074. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125075. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125076. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125077. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125078. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125079. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125080. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125081. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125082. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125083. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125084. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125085. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125086. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125087. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125088. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125089. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125090. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125091. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125092. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125093. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125094. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125095. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125096. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125097. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125098. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125099. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125100. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125101. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125102. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125103. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125104. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125105. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125106. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125107. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125108. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125109. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125110. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125111. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125112. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125113. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125114. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125115. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125116. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125117. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125118. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125119. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125120. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125121. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125122. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125123. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125124. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125125. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125126. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125127. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125128. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125129. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125130. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125131. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125132. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125133. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125134. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125135. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125136. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125137. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125138. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125139. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125140. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125141. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125142. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125143. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125144. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125145. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125146. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125147. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125148. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125149. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125150. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125151. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125152. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125153. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125154. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125155. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125156. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125157. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125158. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125159. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125160. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125161. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125162. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125163. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125164. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125165. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125166. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125167. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125168. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125169. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125170. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125171. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125172. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125173. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125174. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125175. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125176. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125177. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125178. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125179. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125180. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125181. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125182. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125183. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125184. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125185. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125186. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125187. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125188. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125189. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125190. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125191. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125192. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125193. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125194. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125195. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125196. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125197. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125198. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125199. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125200. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125201. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125202. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125203. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125204. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125205. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125206. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125207. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125208. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125209. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125210. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125211. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125212. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125213. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125214. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125215. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125216. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125217. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125218. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125219. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125220. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125221. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125222. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125223. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125224. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125225. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125226. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125227. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125228. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125229. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125230. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125231. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125232. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125233. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125234. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125235. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125236. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125237. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125238. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125239. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125240. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125241. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125242. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125243. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125244. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125245. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125246. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125247. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125248. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125249. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125250. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125251. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125252. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125253. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125254. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125255. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125256. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125257. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125258. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125259. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125260. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125261. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125262. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125263. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125264. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125265. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125266. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125267. 0,
  125268. };
  125269. static float _vq_quantthresh__44c2_s_p1_0[] = {
  125270. -0.5, 0.5,
  125271. };
  125272. static long _vq_quantmap__44c2_s_p1_0[] = {
  125273. 1, 0, 2,
  125274. };
  125275. static encode_aux_threshmatch _vq_auxt__44c2_s_p1_0 = {
  125276. _vq_quantthresh__44c2_s_p1_0,
  125277. _vq_quantmap__44c2_s_p1_0,
  125278. 3,
  125279. 3
  125280. };
  125281. static static_codebook _44c2_s_p1_0 = {
  125282. 8, 6561,
  125283. _vq_lengthlist__44c2_s_p1_0,
  125284. 1, -535822336, 1611661312, 2, 0,
  125285. _vq_quantlist__44c2_s_p1_0,
  125286. NULL,
  125287. &_vq_auxt__44c2_s_p1_0,
  125288. NULL,
  125289. 0
  125290. };
  125291. static long _vq_quantlist__44c2_s_p2_0[] = {
  125292. 2,
  125293. 1,
  125294. 3,
  125295. 0,
  125296. 4,
  125297. };
  125298. static long _vq_lengthlist__44c2_s_p2_0[] = {
  125299. 1, 4, 4, 0, 0, 0, 7, 7, 0, 0, 0, 7, 7, 0, 0, 0,
  125300. 8, 8, 0, 0, 0, 0, 0, 0, 0, 4, 6, 6, 0, 0, 0, 8,
  125301. 8, 0, 0, 0, 8, 8, 0, 0, 0, 9, 9, 0, 0, 0, 0, 0,
  125302. 0, 0, 4, 6, 6, 0, 0, 0, 8, 8, 0, 0, 0, 8, 8, 0,
  125303. 0, 0, 9, 9, 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, 7, 8, 8, 0, 0, 0,11,11, 0, 0,
  125309. 0,11,11, 0, 0, 0,12,11, 0, 0, 0, 0, 0, 0, 0, 7,
  125310. 8, 8, 0, 0, 0,10,11, 0, 0, 0,11,11, 0, 0, 0,11,
  125311. 12, 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, 6, 8, 8, 0, 0, 0,11,11, 0, 0, 0,11,11,
  125317. 0, 0, 0,12,12, 0, 0, 0, 0, 0, 0, 0, 6, 8, 8, 0,
  125318. 0, 0,10,11, 0, 0, 0,10,11, 0, 0, 0,11,11, 0, 0,
  125319. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0,
  125324. 8, 9, 9, 0, 0, 0,11,12, 0, 0, 0,11,12, 0, 0, 0,
  125325. 12,11, 0, 0, 0, 0, 0, 0, 0, 8,10, 9, 0, 0, 0,12,
  125326. 11, 0, 0, 0,12,11, 0, 0, 0,11,12, 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, 0, 0, 0, 0, 0,
  125329. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  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,
  125339. };
  125340. static float _vq_quantthresh__44c2_s_p2_0[] = {
  125341. -1.5, -0.5, 0.5, 1.5,
  125342. };
  125343. static long _vq_quantmap__44c2_s_p2_0[] = {
  125344. 3, 1, 0, 2, 4,
  125345. };
  125346. static encode_aux_threshmatch _vq_auxt__44c2_s_p2_0 = {
  125347. _vq_quantthresh__44c2_s_p2_0,
  125348. _vq_quantmap__44c2_s_p2_0,
  125349. 5,
  125350. 5
  125351. };
  125352. static static_codebook _44c2_s_p2_0 = {
  125353. 4, 625,
  125354. _vq_lengthlist__44c2_s_p2_0,
  125355. 1, -533725184, 1611661312, 3, 0,
  125356. _vq_quantlist__44c2_s_p2_0,
  125357. NULL,
  125358. &_vq_auxt__44c2_s_p2_0,
  125359. NULL,
  125360. 0
  125361. };
  125362. static long _vq_quantlist__44c2_s_p3_0[] = {
  125363. 2,
  125364. 1,
  125365. 3,
  125366. 0,
  125367. 4,
  125368. };
  125369. static long _vq_lengthlist__44c2_s_p3_0[] = {
  125370. 2, 4, 3, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125371. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 4, 4, 6, 6, 0, 0,
  125372. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125373. 0, 0, 4, 4, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125374. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 6, 6, 9, 9,
  125375. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125376. 0, 0, 0, 0, 6, 6, 7, 9, 9, 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,
  125410. };
  125411. static float _vq_quantthresh__44c2_s_p3_0[] = {
  125412. -1.5, -0.5, 0.5, 1.5,
  125413. };
  125414. static long _vq_quantmap__44c2_s_p3_0[] = {
  125415. 3, 1, 0, 2, 4,
  125416. };
  125417. static encode_aux_threshmatch _vq_auxt__44c2_s_p3_0 = {
  125418. _vq_quantthresh__44c2_s_p3_0,
  125419. _vq_quantmap__44c2_s_p3_0,
  125420. 5,
  125421. 5
  125422. };
  125423. static static_codebook _44c2_s_p3_0 = {
  125424. 4, 625,
  125425. _vq_lengthlist__44c2_s_p3_0,
  125426. 1, -533725184, 1611661312, 3, 0,
  125427. _vq_quantlist__44c2_s_p3_0,
  125428. NULL,
  125429. &_vq_auxt__44c2_s_p3_0,
  125430. NULL,
  125431. 0
  125432. };
  125433. static long _vq_quantlist__44c2_s_p4_0[] = {
  125434. 4,
  125435. 3,
  125436. 5,
  125437. 2,
  125438. 6,
  125439. 1,
  125440. 7,
  125441. 0,
  125442. 8,
  125443. };
  125444. static long _vq_lengthlist__44c2_s_p4_0[] = {
  125445. 1, 3, 3, 6, 6, 0, 0, 0, 0, 0, 6, 6, 6, 6, 0, 0,
  125446. 0, 0, 0, 6, 6, 6, 6, 0, 0, 0, 0, 0, 7, 7, 6, 6,
  125447. 0, 0, 0, 0, 0, 0, 0, 6, 7, 0, 0, 0, 0, 0, 0, 0,
  125448. 7, 8, 0, 0, 0, 0, 0, 0, 0, 8, 8, 0, 0, 0, 0, 0,
  125449. 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125450. 0,
  125451. };
  125452. static float _vq_quantthresh__44c2_s_p4_0[] = {
  125453. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  125454. };
  125455. static long _vq_quantmap__44c2_s_p4_0[] = {
  125456. 7, 5, 3, 1, 0, 2, 4, 6,
  125457. 8,
  125458. };
  125459. static encode_aux_threshmatch _vq_auxt__44c2_s_p4_0 = {
  125460. _vq_quantthresh__44c2_s_p4_0,
  125461. _vq_quantmap__44c2_s_p4_0,
  125462. 9,
  125463. 9
  125464. };
  125465. static static_codebook _44c2_s_p4_0 = {
  125466. 2, 81,
  125467. _vq_lengthlist__44c2_s_p4_0,
  125468. 1, -531628032, 1611661312, 4, 0,
  125469. _vq_quantlist__44c2_s_p4_0,
  125470. NULL,
  125471. &_vq_auxt__44c2_s_p4_0,
  125472. NULL,
  125473. 0
  125474. };
  125475. static long _vq_quantlist__44c2_s_p5_0[] = {
  125476. 4,
  125477. 3,
  125478. 5,
  125479. 2,
  125480. 6,
  125481. 1,
  125482. 7,
  125483. 0,
  125484. 8,
  125485. };
  125486. static long _vq_lengthlist__44c2_s_p5_0[] = {
  125487. 1, 3, 3, 6, 6, 7, 7, 9, 9, 0, 7, 7, 7, 7, 7, 7,
  125488. 9, 9, 0, 7, 7, 7, 7, 7, 7, 9, 9, 0, 8, 8, 7, 7,
  125489. 8, 8,10,10, 0, 0, 0, 7, 7, 8, 8,10,10, 0, 0, 0,
  125490. 9, 9, 8, 8,10,10, 0, 0, 0, 9, 9, 8, 8,10,10, 0,
  125491. 0, 0,10,10, 9, 9,11,11, 0, 0, 0, 0, 0, 9, 9,11,
  125492. 11,
  125493. };
  125494. static float _vq_quantthresh__44c2_s_p5_0[] = {
  125495. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  125496. };
  125497. static long _vq_quantmap__44c2_s_p5_0[] = {
  125498. 7, 5, 3, 1, 0, 2, 4, 6,
  125499. 8,
  125500. };
  125501. static encode_aux_threshmatch _vq_auxt__44c2_s_p5_0 = {
  125502. _vq_quantthresh__44c2_s_p5_0,
  125503. _vq_quantmap__44c2_s_p5_0,
  125504. 9,
  125505. 9
  125506. };
  125507. static static_codebook _44c2_s_p5_0 = {
  125508. 2, 81,
  125509. _vq_lengthlist__44c2_s_p5_0,
  125510. 1, -531628032, 1611661312, 4, 0,
  125511. _vq_quantlist__44c2_s_p5_0,
  125512. NULL,
  125513. &_vq_auxt__44c2_s_p5_0,
  125514. NULL,
  125515. 0
  125516. };
  125517. static long _vq_quantlist__44c2_s_p6_0[] = {
  125518. 8,
  125519. 7,
  125520. 9,
  125521. 6,
  125522. 10,
  125523. 5,
  125524. 11,
  125525. 4,
  125526. 12,
  125527. 3,
  125528. 13,
  125529. 2,
  125530. 14,
  125531. 1,
  125532. 15,
  125533. 0,
  125534. 16,
  125535. };
  125536. static long _vq_lengthlist__44c2_s_p6_0[] = {
  125537. 1, 4, 3, 6, 6, 8, 8, 9, 9, 9, 9, 9, 9,10,10,11,
  125538. 11, 0, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9,10,10,11,11,
  125539. 12,11, 0, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9,10,10,11,
  125540. 11,11,12, 0, 8, 8, 7, 7, 9, 9,10,10, 9, 9,10,10,
  125541. 11,11,12,12, 0, 0, 0, 7, 7, 9, 9,10,10,10, 9,10,
  125542. 10,11,11,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,10,
  125543. 11,11,11,11,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,
  125544. 10,11,11,12,12,12,12, 0, 0, 0, 9, 9, 9, 9,10,10,
  125545. 10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 9, 9,10,
  125546. 10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,
  125547. 10,10,11,11,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9,
  125548. 9,10,10,11,11,11,11,12,12,13,13, 0, 0, 0, 0, 0,
  125549. 10,10,10,10,11,11,12,12,13,12,13,13, 0, 0, 0, 0,
  125550. 0, 0, 0,10,10,11,11,12,12,13,13,13,13, 0, 0, 0,
  125551. 0, 0, 0, 0,11,11,12,12,12,12,13,13,13,14, 0, 0,
  125552. 0, 0, 0, 0, 0,11,11,12,12,12,12,13,13,13,14, 0,
  125553. 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,13,13,14,14,
  125554. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,13,13,13,13,14,
  125555. 14,
  125556. };
  125557. static float _vq_quantthresh__44c2_s_p6_0[] = {
  125558. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  125559. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  125560. };
  125561. static long _vq_quantmap__44c2_s_p6_0[] = {
  125562. 15, 13, 11, 9, 7, 5, 3, 1,
  125563. 0, 2, 4, 6, 8, 10, 12, 14,
  125564. 16,
  125565. };
  125566. static encode_aux_threshmatch _vq_auxt__44c2_s_p6_0 = {
  125567. _vq_quantthresh__44c2_s_p6_0,
  125568. _vq_quantmap__44c2_s_p6_0,
  125569. 17,
  125570. 17
  125571. };
  125572. static static_codebook _44c2_s_p6_0 = {
  125573. 2, 289,
  125574. _vq_lengthlist__44c2_s_p6_0,
  125575. 1, -529530880, 1611661312, 5, 0,
  125576. _vq_quantlist__44c2_s_p6_0,
  125577. NULL,
  125578. &_vq_auxt__44c2_s_p6_0,
  125579. NULL,
  125580. 0
  125581. };
  125582. static long _vq_quantlist__44c2_s_p7_0[] = {
  125583. 1,
  125584. 0,
  125585. 2,
  125586. };
  125587. static long _vq_lengthlist__44c2_s_p7_0[] = {
  125588. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 7, 7,10, 9, 9,11,
  125589. 9, 9, 4, 7, 7,10, 9, 9,10, 9, 9, 7,10,10,11,10,
  125590. 11,11,10,11, 6, 9, 9,11,10,10,11,10,10, 6, 9, 9,
  125591. 11,10,11,11,10,10, 7,11,10,11,11,11,12,11,11, 6,
  125592. 9, 9,11,10,10,11,11,10, 6, 9, 9,11,10,10,12,10,
  125593. 11,
  125594. };
  125595. static float _vq_quantthresh__44c2_s_p7_0[] = {
  125596. -5.5, 5.5,
  125597. };
  125598. static long _vq_quantmap__44c2_s_p7_0[] = {
  125599. 1, 0, 2,
  125600. };
  125601. static encode_aux_threshmatch _vq_auxt__44c2_s_p7_0 = {
  125602. _vq_quantthresh__44c2_s_p7_0,
  125603. _vq_quantmap__44c2_s_p7_0,
  125604. 3,
  125605. 3
  125606. };
  125607. static static_codebook _44c2_s_p7_0 = {
  125608. 4, 81,
  125609. _vq_lengthlist__44c2_s_p7_0,
  125610. 1, -529137664, 1618345984, 2, 0,
  125611. _vq_quantlist__44c2_s_p7_0,
  125612. NULL,
  125613. &_vq_auxt__44c2_s_p7_0,
  125614. NULL,
  125615. 0
  125616. };
  125617. static long _vq_quantlist__44c2_s_p7_1[] = {
  125618. 5,
  125619. 4,
  125620. 6,
  125621. 3,
  125622. 7,
  125623. 2,
  125624. 8,
  125625. 1,
  125626. 9,
  125627. 0,
  125628. 10,
  125629. };
  125630. static long _vq_lengthlist__44c2_s_p7_1[] = {
  125631. 2, 3, 4, 6, 6, 7, 7, 7, 7, 7, 7, 9, 7, 7, 6, 6,
  125632. 7, 7, 8, 8, 8, 8, 9, 6, 6, 6, 6, 7, 7, 8, 8, 8,
  125633. 8,10, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8,10,10,10, 7,
  125634. 7, 7, 7, 8, 8, 8, 8,10,10,10, 7, 7, 8, 8, 8, 8,
  125635. 8, 8,10,10,10, 7, 8, 8, 8, 8, 8, 8, 8,10,10,10,
  125636. 8, 8, 8, 8, 8, 8, 8, 8,10,10,10,10,10, 8, 8, 8,
  125637. 8, 8, 8,10,10,10,10,10, 9, 9, 8, 8, 8, 8,10,10,
  125638. 10,10,10, 8, 8, 8, 8, 8, 8,
  125639. };
  125640. static float _vq_quantthresh__44c2_s_p7_1[] = {
  125641. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  125642. 3.5, 4.5,
  125643. };
  125644. static long _vq_quantmap__44c2_s_p7_1[] = {
  125645. 9, 7, 5, 3, 1, 0, 2, 4,
  125646. 6, 8, 10,
  125647. };
  125648. static encode_aux_threshmatch _vq_auxt__44c2_s_p7_1 = {
  125649. _vq_quantthresh__44c2_s_p7_1,
  125650. _vq_quantmap__44c2_s_p7_1,
  125651. 11,
  125652. 11
  125653. };
  125654. static static_codebook _44c2_s_p7_1 = {
  125655. 2, 121,
  125656. _vq_lengthlist__44c2_s_p7_1,
  125657. 1, -531365888, 1611661312, 4, 0,
  125658. _vq_quantlist__44c2_s_p7_1,
  125659. NULL,
  125660. &_vq_auxt__44c2_s_p7_1,
  125661. NULL,
  125662. 0
  125663. };
  125664. static long _vq_quantlist__44c2_s_p8_0[] = {
  125665. 6,
  125666. 5,
  125667. 7,
  125668. 4,
  125669. 8,
  125670. 3,
  125671. 9,
  125672. 2,
  125673. 10,
  125674. 1,
  125675. 11,
  125676. 0,
  125677. 12,
  125678. };
  125679. static long _vq_lengthlist__44c2_s_p8_0[] = {
  125680. 1, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8, 9, 9, 6, 5, 5,
  125681. 7, 7, 8, 8, 8, 8, 9, 9,10,10, 7, 6, 5, 7, 7, 8,
  125682. 8, 8, 8, 9, 9,10,10, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  125683. 10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  125684. 11, 0,12,12, 9, 9,10,10,10,10,11,11,11,11, 0,13,
  125685. 13, 9, 9,10,10,10,10,11,11,12,12, 0, 0, 0,10,10,
  125686. 10,10,11,11,12,12,12,13, 0, 0, 0,10,10,10,10,11,
  125687. 11,12,12,12,12, 0, 0, 0,14,14,10,11,11,11,12,12,
  125688. 13,13, 0, 0, 0,14,14,11,10,11,11,13,12,13,13, 0,
  125689. 0, 0, 0, 0,12,12,11,12,13,12,14,14, 0, 0, 0, 0,
  125690. 0,12,12,12,12,13,12,14,14,
  125691. };
  125692. static float _vq_quantthresh__44c2_s_p8_0[] = {
  125693. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  125694. 12.5, 17.5, 22.5, 27.5,
  125695. };
  125696. static long _vq_quantmap__44c2_s_p8_0[] = {
  125697. 11, 9, 7, 5, 3, 1, 0, 2,
  125698. 4, 6, 8, 10, 12,
  125699. };
  125700. static encode_aux_threshmatch _vq_auxt__44c2_s_p8_0 = {
  125701. _vq_quantthresh__44c2_s_p8_0,
  125702. _vq_quantmap__44c2_s_p8_0,
  125703. 13,
  125704. 13
  125705. };
  125706. static static_codebook _44c2_s_p8_0 = {
  125707. 2, 169,
  125708. _vq_lengthlist__44c2_s_p8_0,
  125709. 1, -526516224, 1616117760, 4, 0,
  125710. _vq_quantlist__44c2_s_p8_0,
  125711. NULL,
  125712. &_vq_auxt__44c2_s_p8_0,
  125713. NULL,
  125714. 0
  125715. };
  125716. static long _vq_quantlist__44c2_s_p8_1[] = {
  125717. 2,
  125718. 1,
  125719. 3,
  125720. 0,
  125721. 4,
  125722. };
  125723. static long _vq_lengthlist__44c2_s_p8_1[] = {
  125724. 2, 4, 4, 5, 4, 6, 5, 5, 5, 5, 6, 5, 5, 5, 5, 6,
  125725. 5, 5, 5, 5, 6, 6, 6, 5, 5,
  125726. };
  125727. static float _vq_quantthresh__44c2_s_p8_1[] = {
  125728. -1.5, -0.5, 0.5, 1.5,
  125729. };
  125730. static long _vq_quantmap__44c2_s_p8_1[] = {
  125731. 3, 1, 0, 2, 4,
  125732. };
  125733. static encode_aux_threshmatch _vq_auxt__44c2_s_p8_1 = {
  125734. _vq_quantthresh__44c2_s_p8_1,
  125735. _vq_quantmap__44c2_s_p8_1,
  125736. 5,
  125737. 5
  125738. };
  125739. static static_codebook _44c2_s_p8_1 = {
  125740. 2, 25,
  125741. _vq_lengthlist__44c2_s_p8_1,
  125742. 1, -533725184, 1611661312, 3, 0,
  125743. _vq_quantlist__44c2_s_p8_1,
  125744. NULL,
  125745. &_vq_auxt__44c2_s_p8_1,
  125746. NULL,
  125747. 0
  125748. };
  125749. static long _vq_quantlist__44c2_s_p9_0[] = {
  125750. 6,
  125751. 5,
  125752. 7,
  125753. 4,
  125754. 8,
  125755. 3,
  125756. 9,
  125757. 2,
  125758. 10,
  125759. 1,
  125760. 11,
  125761. 0,
  125762. 12,
  125763. };
  125764. static long _vq_lengthlist__44c2_s_p9_0[] = {
  125765. 1, 5, 4,12,12,12,12,12,12,12,12,12,12, 4, 9, 8,
  125766. 11,11,11,11,11,11,11,11,11,11, 2, 8, 7,11,11,11,
  125767. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  125768. 11,11,11,11,11,11,10,11,11,11,11,11,11,11,11,11,
  125769. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  125770. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  125771. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  125772. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  125773. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  125774. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  125775. 11,11,11,11,11,11,11,11,11,
  125776. };
  125777. static float _vq_quantthresh__44c2_s_p9_0[] = {
  125778. -1215.5, -994.5, -773.5, -552.5, -331.5, -110.5, 110.5, 331.5,
  125779. 552.5, 773.5, 994.5, 1215.5,
  125780. };
  125781. static long _vq_quantmap__44c2_s_p9_0[] = {
  125782. 11, 9, 7, 5, 3, 1, 0, 2,
  125783. 4, 6, 8, 10, 12,
  125784. };
  125785. static encode_aux_threshmatch _vq_auxt__44c2_s_p9_0 = {
  125786. _vq_quantthresh__44c2_s_p9_0,
  125787. _vq_quantmap__44c2_s_p9_0,
  125788. 13,
  125789. 13
  125790. };
  125791. static static_codebook _44c2_s_p9_0 = {
  125792. 2, 169,
  125793. _vq_lengthlist__44c2_s_p9_0,
  125794. 1, -514541568, 1627103232, 4, 0,
  125795. _vq_quantlist__44c2_s_p9_0,
  125796. NULL,
  125797. &_vq_auxt__44c2_s_p9_0,
  125798. NULL,
  125799. 0
  125800. };
  125801. static long _vq_quantlist__44c2_s_p9_1[] = {
  125802. 6,
  125803. 5,
  125804. 7,
  125805. 4,
  125806. 8,
  125807. 3,
  125808. 9,
  125809. 2,
  125810. 10,
  125811. 1,
  125812. 11,
  125813. 0,
  125814. 12,
  125815. };
  125816. static long _vq_lengthlist__44c2_s_p9_1[] = {
  125817. 1, 4, 4, 6, 6, 7, 6, 8, 8,10, 9,10,10, 6, 5, 5,
  125818. 7, 7, 8, 7,10, 9,11,11,12,13, 6, 5, 5, 7, 7, 8,
  125819. 8,10,10,11,11,13,13,18, 8, 8, 8, 8, 9, 9,10,10,
  125820. 12,12,12,13,18, 8, 8, 8, 8, 9, 9,10,10,12,12,13,
  125821. 13,18,11,11, 8, 8,10,10,11,11,12,11,13,12,18,11,
  125822. 11, 9, 7,10,10,11,11,11,12,12,13,17,17,17,10,10,
  125823. 11,11,12,12,12,10,12,12,17,17,17,11,10,11,10,13,
  125824. 12,11,12,12,12,17,17,17,15,14,11,11,12,11,13,10,
  125825. 13,12,17,17,17,14,14,12,10,11,11,13,13,13,13,17,
  125826. 17,16,17,16,13,13,12,10,13,10,14,13,17,16,17,16,
  125827. 17,13,12,12,10,13,11,14,14,
  125828. };
  125829. static float _vq_quantthresh__44c2_s_p9_1[] = {
  125830. -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5, 25.5,
  125831. 42.5, 59.5, 76.5, 93.5,
  125832. };
  125833. static long _vq_quantmap__44c2_s_p9_1[] = {
  125834. 11, 9, 7, 5, 3, 1, 0, 2,
  125835. 4, 6, 8, 10, 12,
  125836. };
  125837. static encode_aux_threshmatch _vq_auxt__44c2_s_p9_1 = {
  125838. _vq_quantthresh__44c2_s_p9_1,
  125839. _vq_quantmap__44c2_s_p9_1,
  125840. 13,
  125841. 13
  125842. };
  125843. static static_codebook _44c2_s_p9_1 = {
  125844. 2, 169,
  125845. _vq_lengthlist__44c2_s_p9_1,
  125846. 1, -522616832, 1620115456, 4, 0,
  125847. _vq_quantlist__44c2_s_p9_1,
  125848. NULL,
  125849. &_vq_auxt__44c2_s_p9_1,
  125850. NULL,
  125851. 0
  125852. };
  125853. static long _vq_quantlist__44c2_s_p9_2[] = {
  125854. 8,
  125855. 7,
  125856. 9,
  125857. 6,
  125858. 10,
  125859. 5,
  125860. 11,
  125861. 4,
  125862. 12,
  125863. 3,
  125864. 13,
  125865. 2,
  125866. 14,
  125867. 1,
  125868. 15,
  125869. 0,
  125870. 16,
  125871. };
  125872. static long _vq_lengthlist__44c2_s_p9_2[] = {
  125873. 2, 4, 4, 6, 6, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8,
  125874. 8,10, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9,
  125875. 9, 9,10, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 9, 9, 9,
  125876. 9, 9, 9,10, 8, 8, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9,
  125877. 9, 9, 9, 9,10,10,10, 8, 7, 8, 8, 8, 8, 9, 9, 9,
  125878. 9, 9, 9, 9, 9,10,11,11, 8, 8, 8, 8, 9, 9, 9, 9,
  125879. 9, 9,10, 9, 9, 9,10,11,10, 8, 8, 8, 8, 9, 9, 9,
  125880. 9, 9, 9, 9,10,10,10,10,11,10, 8, 8, 9, 9, 9, 9,
  125881. 9, 9,10, 9, 9,10, 9,10,11,10,11,11,11, 8, 8, 9,
  125882. 9, 9, 9, 9, 9, 9, 9,10,10,11,11,11,11,11, 9, 9,
  125883. 9, 9, 9, 9,10, 9, 9, 9,10,10,11,11,11,11,11, 9,
  125884. 9, 9, 9, 9, 9, 9, 9, 9,10, 9,10,11,11,11,11,11,
  125885. 9, 9, 9, 9,10,10, 9, 9, 9,10,10,10,11,11,11,11,
  125886. 11,11,11, 9, 9, 9,10, 9, 9,10,10,10,10,11,11,10,
  125887. 11,11,11,11,10, 9,10,10, 9, 9, 9, 9,10,10,11,10,
  125888. 11,11,11,11,11, 9, 9, 9, 9,10, 9,10,10,10,10,11,
  125889. 10,11,11,11,11,11,10,10, 9, 9,10, 9,10,10,10,10,
  125890. 10,10,10,11,11,11,11,11,11, 9, 9,10, 9,10, 9,10,
  125891. 10,
  125892. };
  125893. static float _vq_quantthresh__44c2_s_p9_2[] = {
  125894. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  125895. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  125896. };
  125897. static long _vq_quantmap__44c2_s_p9_2[] = {
  125898. 15, 13, 11, 9, 7, 5, 3, 1,
  125899. 0, 2, 4, 6, 8, 10, 12, 14,
  125900. 16,
  125901. };
  125902. static encode_aux_threshmatch _vq_auxt__44c2_s_p9_2 = {
  125903. _vq_quantthresh__44c2_s_p9_2,
  125904. _vq_quantmap__44c2_s_p9_2,
  125905. 17,
  125906. 17
  125907. };
  125908. static static_codebook _44c2_s_p9_2 = {
  125909. 2, 289,
  125910. _vq_lengthlist__44c2_s_p9_2,
  125911. 1, -529530880, 1611661312, 5, 0,
  125912. _vq_quantlist__44c2_s_p9_2,
  125913. NULL,
  125914. &_vq_auxt__44c2_s_p9_2,
  125915. NULL,
  125916. 0
  125917. };
  125918. static long _huff_lengthlist__44c2_s_short[] = {
  125919. 11, 9,13,12,12,11,12,12,13,15, 8, 2,11, 4, 8, 5,
  125920. 7,10,12,15,13, 7,10, 9, 8, 8,10,13,17,17,11, 4,
  125921. 12, 5, 9, 5, 8,11,14,16,12, 6, 8, 7, 6, 6, 8,11,
  125922. 13,16,11, 4, 9, 5, 6, 4, 6,10,13,16,11, 6,11, 7,
  125923. 7, 6, 7,10,13,15,13, 9,12, 9, 8, 6, 8,10,12,14,
  125924. 14,10,10, 8, 6, 5, 6, 9,11,13,15,11,11, 9, 6, 5,
  125925. 6, 8, 9,12,
  125926. };
  125927. static static_codebook _huff_book__44c2_s_short = {
  125928. 2, 100,
  125929. _huff_lengthlist__44c2_s_short,
  125930. 0, 0, 0, 0, 0,
  125931. NULL,
  125932. NULL,
  125933. NULL,
  125934. NULL,
  125935. 0
  125936. };
  125937. static long _huff_lengthlist__44c3_s_long[] = {
  125938. 5, 6,11,11,11,11,10,10,12,11, 5, 2,11, 5, 6, 6,
  125939. 7, 9,11,13,13,10, 7,11, 6, 7, 8, 9,10,12,11, 5,
  125940. 11, 6, 8, 7, 9,11,14,15,11, 6, 6, 8, 4, 5, 7, 8,
  125941. 10,13,10, 5, 7, 7, 5, 5, 6, 8,10,11,10, 7, 7, 8,
  125942. 6, 5, 5, 7, 9, 9,11, 8, 8,11, 8, 7, 6, 6, 7, 9,
  125943. 12,11,10,13, 9, 9, 7, 7, 7, 9,11,13,12,15,12,11,
  125944. 9, 8, 8, 8,
  125945. };
  125946. static static_codebook _huff_book__44c3_s_long = {
  125947. 2, 100,
  125948. _huff_lengthlist__44c3_s_long,
  125949. 0, 0, 0, 0, 0,
  125950. NULL,
  125951. NULL,
  125952. NULL,
  125953. NULL,
  125954. 0
  125955. };
  125956. static long _vq_quantlist__44c3_s_p1_0[] = {
  125957. 1,
  125958. 0,
  125959. 2,
  125960. };
  125961. static long _vq_lengthlist__44c3_s_p1_0[] = {
  125962. 2, 4, 4, 0, 0, 0, 0, 0, 0, 5, 6, 6, 0, 0, 0, 0,
  125963. 0, 0, 5, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125964. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125965. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125966. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125967. 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0, 0,
  125968. 0, 0, 0, 6, 7, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125969. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125970. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125971. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125972. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 6, 8, 7, 0, 0,
  125973. 0, 0, 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125974. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125975. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125976. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125977. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125978. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125979. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125980. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125981. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125982. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125983. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125984. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125985. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125986. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125987. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125988. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125989. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125990. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125991. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125992. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125993. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125994. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125995. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125996. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125997. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125998. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125999. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126000. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126001. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126002. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126003. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126004. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126005. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126006. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126007. 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  126008. 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0,
  126009. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126010. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126011. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126012. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0, 0,
  126013. 0, 0, 0, 8, 8, 9, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0,
  126014. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126015. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126016. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126017. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 8, 8, 0, 0,
  126018. 0, 0, 0, 0, 7, 9, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9,
  126019. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126020. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126021. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126022. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126023. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126024. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126025. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126026. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126027. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126028. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126029. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126030. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126031. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126032. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126033. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126034. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126035. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126036. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126037. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126038. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126039. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126040. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126041. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126042. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126043. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126044. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126045. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126046. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126047. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126048. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126049. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126050. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126051. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126052. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126053. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0,
  126054. 0, 0, 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126055. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126056. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126057. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126058. 0, 0, 0, 6, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0,
  126059. 0, 0, 0, 0, 0, 7, 8, 9, 0, 0, 0, 0, 0, 0, 0, 0,
  126060. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126061. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126062. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126063. 0, 0, 0, 0, 6, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9,
  126064. 0, 0, 0, 0, 0, 0, 8, 9, 8, 0, 0, 0, 0, 0, 0, 0,
  126065. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126066. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126067. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126068. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126069. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126070. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126071. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126072. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126073. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126074. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126075. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126076. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126077. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126078. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126079. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126080. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126081. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126082. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126083. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126084. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126085. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126086. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126087. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126088. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126089. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126090. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126091. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126092. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126093. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126094. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126095. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126096. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126097. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126098. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126099. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126100. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126101. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126102. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126103. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126104. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126105. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126106. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126107. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126108. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126109. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126110. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126111. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126112. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126113. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126114. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126115. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126116. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126117. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126118. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126119. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126120. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126121. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126122. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126123. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126124. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126125. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126126. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126127. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126128. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126129. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126130. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126131. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126132. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126133. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126134. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126135. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126136. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126137. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126138. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126139. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126140. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126141. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126142. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126143. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126144. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126145. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126146. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126147. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126148. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126149. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126150. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126151. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126152. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126153. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126154. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126155. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126156. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126157. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126158. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126159. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126160. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126161. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126162. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126163. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126164. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126165. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126166. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126167. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126168. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126169. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126170. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126171. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126172. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126173. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126174. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126175. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126176. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126177. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126178. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126179. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126180. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126181. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126182. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126183. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126184. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126185. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126186. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126187. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126188. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126189. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126190. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126191. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126192. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126193. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126194. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126195. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126196. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126197. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126198. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126199. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126200. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126201. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126202. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126203. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126204. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126205. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126206. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126207. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126208. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126209. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126210. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126211. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126212. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126213. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126214. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126215. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126216. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126217. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126218. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126219. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126220. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126221. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126222. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126223. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126224. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126225. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126226. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126227. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126228. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126229. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126230. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126231. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126232. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126233. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126234. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126235. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126236. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126237. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126238. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126239. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126240. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126241. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126242. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126243. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126244. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126245. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126246. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126247. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126248. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126249. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126250. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126251. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126252. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126253. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126254. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126255. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126256. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126257. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126258. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126259. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126260. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126261. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126262. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126263. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126264. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126265. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126266. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126267. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126268. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126269. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126270. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126271. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126272. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126273. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126274. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126275. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126276. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126277. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126278. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126279. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126280. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126281. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126282. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126283. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126284. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126285. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126286. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126287. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126288. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126289. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126290. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126291. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126292. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126293. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126294. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126295. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126296. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126297. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126298. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126299. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126300. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126301. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126302. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126303. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126304. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126305. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126306. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126307. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126308. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126309. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126310. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126311. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126312. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126313. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126314. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126315. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126316. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126317. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126318. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126319. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126320. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126321. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126322. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126323. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126324. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126325. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126326. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126327. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126328. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126329. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126330. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126331. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126332. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126333. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126334. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126335. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126336. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126337. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126338. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126339. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126340. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126341. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126342. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126343. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126344. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126345. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126346. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126347. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126348. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126349. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126350. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126351. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126352. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126353. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126354. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126355. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126356. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126357. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126358. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126359. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126360. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126361. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126362. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126363. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126364. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126365. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126366. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126367. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126368. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126369. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126370. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126371. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126372. 0,
  126373. };
  126374. static float _vq_quantthresh__44c3_s_p1_0[] = {
  126375. -0.5, 0.5,
  126376. };
  126377. static long _vq_quantmap__44c3_s_p1_0[] = {
  126378. 1, 0, 2,
  126379. };
  126380. static encode_aux_threshmatch _vq_auxt__44c3_s_p1_0 = {
  126381. _vq_quantthresh__44c3_s_p1_0,
  126382. _vq_quantmap__44c3_s_p1_0,
  126383. 3,
  126384. 3
  126385. };
  126386. static static_codebook _44c3_s_p1_0 = {
  126387. 8, 6561,
  126388. _vq_lengthlist__44c3_s_p1_0,
  126389. 1, -535822336, 1611661312, 2, 0,
  126390. _vq_quantlist__44c3_s_p1_0,
  126391. NULL,
  126392. &_vq_auxt__44c3_s_p1_0,
  126393. NULL,
  126394. 0
  126395. };
  126396. static long _vq_quantlist__44c3_s_p2_0[] = {
  126397. 2,
  126398. 1,
  126399. 3,
  126400. 0,
  126401. 4,
  126402. };
  126403. static long _vq_lengthlist__44c3_s_p2_0[] = {
  126404. 2, 5, 5, 0, 0, 0, 5, 5, 0, 0, 0, 5, 5, 0, 0, 0,
  126405. 7, 8, 0, 0, 0, 0, 0, 0, 0, 5, 6, 6, 0, 0, 0, 7,
  126406. 7, 0, 0, 0, 7, 7, 0, 0, 0,10,10, 0, 0, 0, 0, 0,
  126407. 0, 0, 5, 6, 6, 0, 0, 0, 7, 7, 0, 0, 0, 7, 7, 0,
  126408. 0, 0,10,10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126409. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126410. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126411. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126412. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126413. 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 7, 7, 0, 0,
  126414. 0, 7, 7, 0, 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 5,
  126415. 7, 7, 0, 0, 0, 7, 7, 0, 0, 0, 7, 7, 0, 0, 0, 9,
  126416. 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126417. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126418. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126419. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126420. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126421. 0, 0, 0, 5, 7, 7, 0, 0, 0, 7, 7, 0, 0, 0, 7, 7,
  126422. 0, 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0,
  126423. 0, 0, 7, 7, 0, 0, 0, 7, 7, 0, 0, 0, 9, 9, 0, 0,
  126424. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126425. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126426. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126427. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126428. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126429. 8,10,10, 0, 0, 0, 9, 9, 0, 0, 0, 9, 9, 0, 0, 0,
  126430. 10,10, 0, 0, 0, 0, 0, 0, 0, 8,10,10, 0, 0, 0, 9,
  126431. 9, 0, 0, 0, 9, 9, 0, 0, 0,10,10, 0, 0, 0, 0, 0,
  126432. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126433. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126434. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126435. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126436. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126437. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126438. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126439. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126440. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126441. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126442. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126443. 0,
  126444. };
  126445. static float _vq_quantthresh__44c3_s_p2_0[] = {
  126446. -1.5, -0.5, 0.5, 1.5,
  126447. };
  126448. static long _vq_quantmap__44c3_s_p2_0[] = {
  126449. 3, 1, 0, 2, 4,
  126450. };
  126451. static encode_aux_threshmatch _vq_auxt__44c3_s_p2_0 = {
  126452. _vq_quantthresh__44c3_s_p2_0,
  126453. _vq_quantmap__44c3_s_p2_0,
  126454. 5,
  126455. 5
  126456. };
  126457. static static_codebook _44c3_s_p2_0 = {
  126458. 4, 625,
  126459. _vq_lengthlist__44c3_s_p2_0,
  126460. 1, -533725184, 1611661312, 3, 0,
  126461. _vq_quantlist__44c3_s_p2_0,
  126462. NULL,
  126463. &_vq_auxt__44c3_s_p2_0,
  126464. NULL,
  126465. 0
  126466. };
  126467. static long _vq_quantlist__44c3_s_p3_0[] = {
  126468. 2,
  126469. 1,
  126470. 3,
  126471. 0,
  126472. 4,
  126473. };
  126474. static long _vq_lengthlist__44c3_s_p3_0[] = {
  126475. 2, 4, 3, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126476. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 4, 4, 6, 6, 0, 0,
  126477. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126478. 0, 0, 4, 4, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126479. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 6, 6, 9, 9,
  126480. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126481. 0, 0, 0, 0, 6, 6, 7, 9, 9, 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, 0,
  126484. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126485. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126486. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126487. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126488. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126489. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126490. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126491. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126492. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126493. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126494. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126495. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126496. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126497. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126498. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126499. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126500. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126501. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126502. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126503. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126504. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126505. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126506. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126507. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126508. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126509. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126510. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126511. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126512. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126513. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126514. 0,
  126515. };
  126516. static float _vq_quantthresh__44c3_s_p3_0[] = {
  126517. -1.5, -0.5, 0.5, 1.5,
  126518. };
  126519. static long _vq_quantmap__44c3_s_p3_0[] = {
  126520. 3, 1, 0, 2, 4,
  126521. };
  126522. static encode_aux_threshmatch _vq_auxt__44c3_s_p3_0 = {
  126523. _vq_quantthresh__44c3_s_p3_0,
  126524. _vq_quantmap__44c3_s_p3_0,
  126525. 5,
  126526. 5
  126527. };
  126528. static static_codebook _44c3_s_p3_0 = {
  126529. 4, 625,
  126530. _vq_lengthlist__44c3_s_p3_0,
  126531. 1, -533725184, 1611661312, 3, 0,
  126532. _vq_quantlist__44c3_s_p3_0,
  126533. NULL,
  126534. &_vq_auxt__44c3_s_p3_0,
  126535. NULL,
  126536. 0
  126537. };
  126538. static long _vq_quantlist__44c3_s_p4_0[] = {
  126539. 4,
  126540. 3,
  126541. 5,
  126542. 2,
  126543. 6,
  126544. 1,
  126545. 7,
  126546. 0,
  126547. 8,
  126548. };
  126549. static long _vq_lengthlist__44c3_s_p4_0[] = {
  126550. 2, 3, 3, 6, 6, 0, 0, 0, 0, 0, 4, 4, 6, 6, 0, 0,
  126551. 0, 0, 0, 4, 4, 6, 6, 0, 0, 0, 0, 0, 5, 5, 6, 6,
  126552. 0, 0, 0, 0, 0, 0, 0, 6, 6, 0, 0, 0, 0, 0, 0, 0,
  126553. 7, 8, 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0,
  126554. 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126555. 0,
  126556. };
  126557. static float _vq_quantthresh__44c3_s_p4_0[] = {
  126558. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  126559. };
  126560. static long _vq_quantmap__44c3_s_p4_0[] = {
  126561. 7, 5, 3, 1, 0, 2, 4, 6,
  126562. 8,
  126563. };
  126564. static encode_aux_threshmatch _vq_auxt__44c3_s_p4_0 = {
  126565. _vq_quantthresh__44c3_s_p4_0,
  126566. _vq_quantmap__44c3_s_p4_0,
  126567. 9,
  126568. 9
  126569. };
  126570. static static_codebook _44c3_s_p4_0 = {
  126571. 2, 81,
  126572. _vq_lengthlist__44c3_s_p4_0,
  126573. 1, -531628032, 1611661312, 4, 0,
  126574. _vq_quantlist__44c3_s_p4_0,
  126575. NULL,
  126576. &_vq_auxt__44c3_s_p4_0,
  126577. NULL,
  126578. 0
  126579. };
  126580. static long _vq_quantlist__44c3_s_p5_0[] = {
  126581. 4,
  126582. 3,
  126583. 5,
  126584. 2,
  126585. 6,
  126586. 1,
  126587. 7,
  126588. 0,
  126589. 8,
  126590. };
  126591. static long _vq_lengthlist__44c3_s_p5_0[] = {
  126592. 1, 3, 4, 6, 6, 7, 7, 9, 9, 0, 5, 5, 7, 7, 7, 8,
  126593. 9, 9, 0, 5, 5, 7, 7, 8, 8, 9, 9, 0, 7, 7, 8, 8,
  126594. 8, 8,10,10, 0, 0, 0, 8, 8, 8, 8,10,10, 0, 0, 0,
  126595. 9, 9, 9, 9,10,10, 0, 0, 0, 9, 9, 9, 9,10,10, 0,
  126596. 0, 0,10,10,10,10,11,11, 0, 0, 0, 0, 0,10,10,11,
  126597. 11,
  126598. };
  126599. static float _vq_quantthresh__44c3_s_p5_0[] = {
  126600. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  126601. };
  126602. static long _vq_quantmap__44c3_s_p5_0[] = {
  126603. 7, 5, 3, 1, 0, 2, 4, 6,
  126604. 8,
  126605. };
  126606. static encode_aux_threshmatch _vq_auxt__44c3_s_p5_0 = {
  126607. _vq_quantthresh__44c3_s_p5_0,
  126608. _vq_quantmap__44c3_s_p5_0,
  126609. 9,
  126610. 9
  126611. };
  126612. static static_codebook _44c3_s_p5_0 = {
  126613. 2, 81,
  126614. _vq_lengthlist__44c3_s_p5_0,
  126615. 1, -531628032, 1611661312, 4, 0,
  126616. _vq_quantlist__44c3_s_p5_0,
  126617. NULL,
  126618. &_vq_auxt__44c3_s_p5_0,
  126619. NULL,
  126620. 0
  126621. };
  126622. static long _vq_quantlist__44c3_s_p6_0[] = {
  126623. 8,
  126624. 7,
  126625. 9,
  126626. 6,
  126627. 10,
  126628. 5,
  126629. 11,
  126630. 4,
  126631. 12,
  126632. 3,
  126633. 13,
  126634. 2,
  126635. 14,
  126636. 1,
  126637. 15,
  126638. 0,
  126639. 16,
  126640. };
  126641. static long _vq_lengthlist__44c3_s_p6_0[] = {
  126642. 2, 3, 3, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,10,11,
  126643. 10, 0, 5, 5, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10,10,
  126644. 11,11, 0, 5, 5, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10,
  126645. 10,11,11, 0, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  126646. 11,11,11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,
  126647. 10,11,11,11,12, 0, 0, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  126648. 10,10,11,11,12,12, 0, 0, 0, 8, 8, 8, 8, 9, 9, 9,
  126649. 9,10,10,11,11,12,12, 0, 0, 0, 9, 9, 9, 9,10,10,
  126650. 10,10,11,10,11,11,12,12, 0, 0, 0, 0, 0, 9, 9,10,
  126651. 10,10,10,11,11,11,11,12,12, 0, 0, 0, 0, 0, 9, 8,
  126652. 9, 9,10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 8,
  126653. 8, 9, 9,10,10,11,11,12,11,12,12, 0, 0, 0, 0, 0,
  126654. 9,10,10,10,11,11,11,11,12,12,13,13, 0, 0, 0, 0,
  126655. 0, 0, 0,10,10,10,10,11,11,12,12,13,13, 0, 0, 0,
  126656. 0, 0, 0, 0,11,11,11,11,12,12,12,12,13,13, 0, 0,
  126657. 0, 0, 0, 0, 0,11,11,11,11,12,12,12,12,13,13, 0,
  126658. 0, 0, 0, 0, 0, 0,11,11,12,12,12,12,13,13,13,13,
  126659. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,13,
  126660. 13,
  126661. };
  126662. static float _vq_quantthresh__44c3_s_p6_0[] = {
  126663. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  126664. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  126665. };
  126666. static long _vq_quantmap__44c3_s_p6_0[] = {
  126667. 15, 13, 11, 9, 7, 5, 3, 1,
  126668. 0, 2, 4, 6, 8, 10, 12, 14,
  126669. 16,
  126670. };
  126671. static encode_aux_threshmatch _vq_auxt__44c3_s_p6_0 = {
  126672. _vq_quantthresh__44c3_s_p6_0,
  126673. _vq_quantmap__44c3_s_p6_0,
  126674. 17,
  126675. 17
  126676. };
  126677. static static_codebook _44c3_s_p6_0 = {
  126678. 2, 289,
  126679. _vq_lengthlist__44c3_s_p6_0,
  126680. 1, -529530880, 1611661312, 5, 0,
  126681. _vq_quantlist__44c3_s_p6_0,
  126682. NULL,
  126683. &_vq_auxt__44c3_s_p6_0,
  126684. NULL,
  126685. 0
  126686. };
  126687. static long _vq_quantlist__44c3_s_p7_0[] = {
  126688. 1,
  126689. 0,
  126690. 2,
  126691. };
  126692. static long _vq_lengthlist__44c3_s_p7_0[] = {
  126693. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 7, 7,10, 9, 9,11,
  126694. 9, 9, 4, 7, 7,10, 9, 9,11, 9, 9, 7,10,10,11,11,
  126695. 10,12,11,11, 6, 9, 9,11,10,10,11,10,10, 6, 9, 9,
  126696. 11,10,10,11,10,10, 7,11,11,11,11,11,12,11,11, 6,
  126697. 9, 9,11,10,10,11,10,10, 6, 9, 9,11,10,10,11,10,
  126698. 10,
  126699. };
  126700. static float _vq_quantthresh__44c3_s_p7_0[] = {
  126701. -5.5, 5.5,
  126702. };
  126703. static long _vq_quantmap__44c3_s_p7_0[] = {
  126704. 1, 0, 2,
  126705. };
  126706. static encode_aux_threshmatch _vq_auxt__44c3_s_p7_0 = {
  126707. _vq_quantthresh__44c3_s_p7_0,
  126708. _vq_quantmap__44c3_s_p7_0,
  126709. 3,
  126710. 3
  126711. };
  126712. static static_codebook _44c3_s_p7_0 = {
  126713. 4, 81,
  126714. _vq_lengthlist__44c3_s_p7_0,
  126715. 1, -529137664, 1618345984, 2, 0,
  126716. _vq_quantlist__44c3_s_p7_0,
  126717. NULL,
  126718. &_vq_auxt__44c3_s_p7_0,
  126719. NULL,
  126720. 0
  126721. };
  126722. static long _vq_quantlist__44c3_s_p7_1[] = {
  126723. 5,
  126724. 4,
  126725. 6,
  126726. 3,
  126727. 7,
  126728. 2,
  126729. 8,
  126730. 1,
  126731. 9,
  126732. 0,
  126733. 10,
  126734. };
  126735. static long _vq_lengthlist__44c3_s_p7_1[] = {
  126736. 2, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8,10, 5, 5, 6, 6,
  126737. 7, 7, 8, 8, 8, 8,10, 5, 5, 6, 6, 7, 7, 8, 8, 8,
  126738. 8,10, 6, 6, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10, 7,
  126739. 7, 8, 7, 8, 8, 8, 8,10,10,10, 8, 8, 8, 8, 8, 8,
  126740. 8, 8,10,10,10, 7, 8, 8, 8, 8, 8, 8, 8,10,10,10,
  126741. 8, 8, 8, 8, 8, 8, 8, 8,10,10,10,10,10, 8, 8, 8,
  126742. 8, 8, 8,10,10,10,10,10, 9, 9, 8, 8, 9, 8,10,10,
  126743. 10,10,10, 8, 8, 8, 8, 8, 8,
  126744. };
  126745. static float _vq_quantthresh__44c3_s_p7_1[] = {
  126746. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  126747. 3.5, 4.5,
  126748. };
  126749. static long _vq_quantmap__44c3_s_p7_1[] = {
  126750. 9, 7, 5, 3, 1, 0, 2, 4,
  126751. 6, 8, 10,
  126752. };
  126753. static encode_aux_threshmatch _vq_auxt__44c3_s_p7_1 = {
  126754. _vq_quantthresh__44c3_s_p7_1,
  126755. _vq_quantmap__44c3_s_p7_1,
  126756. 11,
  126757. 11
  126758. };
  126759. static static_codebook _44c3_s_p7_1 = {
  126760. 2, 121,
  126761. _vq_lengthlist__44c3_s_p7_1,
  126762. 1, -531365888, 1611661312, 4, 0,
  126763. _vq_quantlist__44c3_s_p7_1,
  126764. NULL,
  126765. &_vq_auxt__44c3_s_p7_1,
  126766. NULL,
  126767. 0
  126768. };
  126769. static long _vq_quantlist__44c3_s_p8_0[] = {
  126770. 6,
  126771. 5,
  126772. 7,
  126773. 4,
  126774. 8,
  126775. 3,
  126776. 9,
  126777. 2,
  126778. 10,
  126779. 1,
  126780. 11,
  126781. 0,
  126782. 12,
  126783. };
  126784. static long _vq_lengthlist__44c3_s_p8_0[] = {
  126785. 1, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10, 6, 5, 5,
  126786. 7, 7, 8, 8, 8, 8, 9, 9,10,10, 7, 5, 5, 7, 7, 8,
  126787. 8, 8, 8, 9, 9,11,10, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  126788. 10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  126789. 11, 0,12,12, 9, 9,10,10,10,10,11,11,11,12, 0,13,
  126790. 13, 9, 9,10,10,10,10,11,11,12,12, 0, 0, 0,10,10,
  126791. 10,10,11,11,12,12,12,12, 0, 0, 0,10,10,10,10,11,
  126792. 11,12,12,12,12, 0, 0, 0,14,14,11,11,11,11,12,12,
  126793. 13,13, 0, 0, 0,14,14,11,11,11,11,12,12,13,13, 0,
  126794. 0, 0, 0, 0,12,12,12,12,13,13,14,13, 0, 0, 0, 0,
  126795. 0,13,13,12,12,13,12,14,13,
  126796. };
  126797. static float _vq_quantthresh__44c3_s_p8_0[] = {
  126798. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  126799. 12.5, 17.5, 22.5, 27.5,
  126800. };
  126801. static long _vq_quantmap__44c3_s_p8_0[] = {
  126802. 11, 9, 7, 5, 3, 1, 0, 2,
  126803. 4, 6, 8, 10, 12,
  126804. };
  126805. static encode_aux_threshmatch _vq_auxt__44c3_s_p8_0 = {
  126806. _vq_quantthresh__44c3_s_p8_0,
  126807. _vq_quantmap__44c3_s_p8_0,
  126808. 13,
  126809. 13
  126810. };
  126811. static static_codebook _44c3_s_p8_0 = {
  126812. 2, 169,
  126813. _vq_lengthlist__44c3_s_p8_0,
  126814. 1, -526516224, 1616117760, 4, 0,
  126815. _vq_quantlist__44c3_s_p8_0,
  126816. NULL,
  126817. &_vq_auxt__44c3_s_p8_0,
  126818. NULL,
  126819. 0
  126820. };
  126821. static long _vq_quantlist__44c3_s_p8_1[] = {
  126822. 2,
  126823. 1,
  126824. 3,
  126825. 0,
  126826. 4,
  126827. };
  126828. static long _vq_lengthlist__44c3_s_p8_1[] = {
  126829. 2, 4, 4, 5, 5, 6, 5, 5, 5, 5, 6, 4, 5, 5, 5, 6,
  126830. 5, 5, 5, 5, 6, 6, 6, 5, 5,
  126831. };
  126832. static float _vq_quantthresh__44c3_s_p8_1[] = {
  126833. -1.5, -0.5, 0.5, 1.5,
  126834. };
  126835. static long _vq_quantmap__44c3_s_p8_1[] = {
  126836. 3, 1, 0, 2, 4,
  126837. };
  126838. static encode_aux_threshmatch _vq_auxt__44c3_s_p8_1 = {
  126839. _vq_quantthresh__44c3_s_p8_1,
  126840. _vq_quantmap__44c3_s_p8_1,
  126841. 5,
  126842. 5
  126843. };
  126844. static static_codebook _44c3_s_p8_1 = {
  126845. 2, 25,
  126846. _vq_lengthlist__44c3_s_p8_1,
  126847. 1, -533725184, 1611661312, 3, 0,
  126848. _vq_quantlist__44c3_s_p8_1,
  126849. NULL,
  126850. &_vq_auxt__44c3_s_p8_1,
  126851. NULL,
  126852. 0
  126853. };
  126854. static long _vq_quantlist__44c3_s_p9_0[] = {
  126855. 6,
  126856. 5,
  126857. 7,
  126858. 4,
  126859. 8,
  126860. 3,
  126861. 9,
  126862. 2,
  126863. 10,
  126864. 1,
  126865. 11,
  126866. 0,
  126867. 12,
  126868. };
  126869. static long _vq_lengthlist__44c3_s_p9_0[] = {
  126870. 1, 4, 4,12,12,12,12,12,12,12,12,12,12, 4, 9, 8,
  126871. 12,12,12,12,12,12,12,12,12,12, 2, 9, 7,12,12,12,
  126872. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  126873. 12,12,12,12,12,12,11,12,12,12,12,12,12,12,12,12,
  126874. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  126875. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  126876. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  126877. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  126878. 12,12,12,12,12,12,12,12,12,12,11,11,11,11,11,11,
  126879. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  126880. 11,11,11,11,11,11,11,11,11,
  126881. };
  126882. static float _vq_quantthresh__44c3_s_p9_0[] = {
  126883. -1402.5, -1147.5, -892.5, -637.5, -382.5, -127.5, 127.5, 382.5,
  126884. 637.5, 892.5, 1147.5, 1402.5,
  126885. };
  126886. static long _vq_quantmap__44c3_s_p9_0[] = {
  126887. 11, 9, 7, 5, 3, 1, 0, 2,
  126888. 4, 6, 8, 10, 12,
  126889. };
  126890. static encode_aux_threshmatch _vq_auxt__44c3_s_p9_0 = {
  126891. _vq_quantthresh__44c3_s_p9_0,
  126892. _vq_quantmap__44c3_s_p9_0,
  126893. 13,
  126894. 13
  126895. };
  126896. static static_codebook _44c3_s_p9_0 = {
  126897. 2, 169,
  126898. _vq_lengthlist__44c3_s_p9_0,
  126899. 1, -514332672, 1627381760, 4, 0,
  126900. _vq_quantlist__44c3_s_p9_0,
  126901. NULL,
  126902. &_vq_auxt__44c3_s_p9_0,
  126903. NULL,
  126904. 0
  126905. };
  126906. static long _vq_quantlist__44c3_s_p9_1[] = {
  126907. 7,
  126908. 6,
  126909. 8,
  126910. 5,
  126911. 9,
  126912. 4,
  126913. 10,
  126914. 3,
  126915. 11,
  126916. 2,
  126917. 12,
  126918. 1,
  126919. 13,
  126920. 0,
  126921. 14,
  126922. };
  126923. static long _vq_lengthlist__44c3_s_p9_1[] = {
  126924. 1, 4, 4, 6, 6, 7, 7, 8, 7, 9, 9,10,10,10,10, 6,
  126925. 5, 5, 7, 7, 8, 8,10, 8,11,10,12,12,13,13, 6, 5,
  126926. 5, 7, 7, 8, 8,10, 9,11,11,12,12,13,12,18, 8, 8,
  126927. 8, 8, 9, 9,10, 9,11,10,12,12,13,13,18, 8, 8, 8,
  126928. 8, 9, 9,10,10,11,11,13,12,14,13,18,11,11, 9, 9,
  126929. 10,10,11,11,11,12,13,12,13,14,18,11,11, 9, 8,11,
  126930. 10,11,11,11,11,12,12,14,13,18,18,18,10,11,10,11,
  126931. 12,12,12,12,13,12,14,13,18,18,18,10,11,11, 9,12,
  126932. 11,12,12,12,13,13,13,18,18,17,14,14,11,11,12,12,
  126933. 13,12,14,12,14,13,18,18,18,14,14,11,10,12, 9,12,
  126934. 13,13,13,13,13,18,18,17,16,18,13,13,12,12,13,11,
  126935. 14,12,14,14,17,18,18,17,18,13,12,13,10,12,11,14,
  126936. 14,14,14,17,18,18,18,18,15,16,12,12,13,10,14,12,
  126937. 14,15,18,18,18,16,17,16,14,12,11,13,10,13,13,14,
  126938. 15,
  126939. };
  126940. static float _vq_quantthresh__44c3_s_p9_1[] = {
  126941. -110.5, -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5,
  126942. 25.5, 42.5, 59.5, 76.5, 93.5, 110.5,
  126943. };
  126944. static long _vq_quantmap__44c3_s_p9_1[] = {
  126945. 13, 11, 9, 7, 5, 3, 1, 0,
  126946. 2, 4, 6, 8, 10, 12, 14,
  126947. };
  126948. static encode_aux_threshmatch _vq_auxt__44c3_s_p9_1 = {
  126949. _vq_quantthresh__44c3_s_p9_1,
  126950. _vq_quantmap__44c3_s_p9_1,
  126951. 15,
  126952. 15
  126953. };
  126954. static static_codebook _44c3_s_p9_1 = {
  126955. 2, 225,
  126956. _vq_lengthlist__44c3_s_p9_1,
  126957. 1, -522338304, 1620115456, 4, 0,
  126958. _vq_quantlist__44c3_s_p9_1,
  126959. NULL,
  126960. &_vq_auxt__44c3_s_p9_1,
  126961. NULL,
  126962. 0
  126963. };
  126964. static long _vq_quantlist__44c3_s_p9_2[] = {
  126965. 8,
  126966. 7,
  126967. 9,
  126968. 6,
  126969. 10,
  126970. 5,
  126971. 11,
  126972. 4,
  126973. 12,
  126974. 3,
  126975. 13,
  126976. 2,
  126977. 14,
  126978. 1,
  126979. 15,
  126980. 0,
  126981. 16,
  126982. };
  126983. static long _vq_lengthlist__44c3_s_p9_2[] = {
  126984. 2, 5, 5, 6, 6, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8,
  126985. 8,10, 6, 6, 7, 7, 8, 7, 8, 8, 8, 8, 8, 9, 9, 9,
  126986. 9, 9,10, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9,
  126987. 9, 9, 9,10, 7, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9,
  126988. 9, 9, 9, 9,10,10,10, 7, 7, 8, 8, 8, 9, 9, 9, 9,
  126989. 9, 9, 9, 9, 9,11,11,11, 8, 8, 8, 8, 9, 9, 9, 9,
  126990. 9, 9, 9, 9, 9, 9,10,10,10, 8, 8, 8, 8, 9, 9, 9,
  126991. 9, 9, 9, 9, 9, 9, 9,10,10,10, 8, 9, 9, 9, 9, 9,
  126992. 9, 9, 9, 9, 9, 9,10, 9,10,10,10,11,11, 9, 9, 9,
  126993. 9, 9, 9, 9, 9, 9, 9, 9, 9,11,10,11,11,11, 9, 9,
  126994. 9, 9, 9, 9,10,10, 9, 9,10, 9,11,10,11,11,11, 9,
  126995. 9, 9, 9, 9, 9, 9, 9,10,10,10, 9,11,11,11,11,11,
  126996. 9, 9, 9, 9,10,10, 9, 9, 9, 9,10, 9,11,11,11,11,
  126997. 11,11,11, 9, 9, 9, 9, 9, 9,10,10,10,10,11,11,11,
  126998. 11,11,11,11,10, 9,10,10, 9,10, 9, 9,10, 9,11,10,
  126999. 10,11,11,11,11, 9,10, 9, 9, 9, 9,10,10,10,10,11,
  127000. 11,11,11,11,11,10,10,10, 9, 9,10, 9,10, 9,10,10,
  127001. 10,10,11,11,11,11,11,11,11, 9, 9, 9, 9, 9,10,10,
  127002. 10,
  127003. };
  127004. static float _vq_quantthresh__44c3_s_p9_2[] = {
  127005. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  127006. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  127007. };
  127008. static long _vq_quantmap__44c3_s_p9_2[] = {
  127009. 15, 13, 11, 9, 7, 5, 3, 1,
  127010. 0, 2, 4, 6, 8, 10, 12, 14,
  127011. 16,
  127012. };
  127013. static encode_aux_threshmatch _vq_auxt__44c3_s_p9_2 = {
  127014. _vq_quantthresh__44c3_s_p9_2,
  127015. _vq_quantmap__44c3_s_p9_2,
  127016. 17,
  127017. 17
  127018. };
  127019. static static_codebook _44c3_s_p9_2 = {
  127020. 2, 289,
  127021. _vq_lengthlist__44c3_s_p9_2,
  127022. 1, -529530880, 1611661312, 5, 0,
  127023. _vq_quantlist__44c3_s_p9_2,
  127024. NULL,
  127025. &_vq_auxt__44c3_s_p9_2,
  127026. NULL,
  127027. 0
  127028. };
  127029. static long _huff_lengthlist__44c3_s_short[] = {
  127030. 10, 9,13,11,14,10,12,13,13,14, 7, 2,12, 5,10, 5,
  127031. 7,10,12,14,12, 6, 9, 8, 7, 7, 9,11,13,16,10, 4,
  127032. 12, 5,10, 6, 8,12,14,16,12, 6, 8, 7, 6, 5, 7,11,
  127033. 12,16,10, 4, 8, 5, 6, 4, 6, 9,13,16,10, 6,10, 7,
  127034. 7, 6, 7, 9,13,15,12, 9,11, 9, 8, 6, 7,10,12,14,
  127035. 14,11,10, 9, 6, 5, 6, 9,11,13,15,13,11,10, 6, 5,
  127036. 6, 8, 9,11,
  127037. };
  127038. static static_codebook _huff_book__44c3_s_short = {
  127039. 2, 100,
  127040. _huff_lengthlist__44c3_s_short,
  127041. 0, 0, 0, 0, 0,
  127042. NULL,
  127043. NULL,
  127044. NULL,
  127045. NULL,
  127046. 0
  127047. };
  127048. static long _huff_lengthlist__44c4_s_long[] = {
  127049. 4, 7,11,11,11,11,10,11,12,11, 5, 2,11, 5, 6, 6,
  127050. 7, 9,11,12,11, 9, 6,10, 6, 7, 8, 9,10,11,11, 5,
  127051. 11, 7, 8, 8, 9,11,13,14,11, 6, 5, 8, 4, 5, 7, 8,
  127052. 10,11,10, 6, 7, 7, 5, 5, 6, 8, 9,11,10, 7, 8, 9,
  127053. 6, 6, 6, 7, 8, 9,11, 9, 9,11, 7, 7, 6, 6, 7, 9,
  127054. 12,12,10,13, 9, 8, 7, 7, 7, 8,11,13,11,14,11,10,
  127055. 9, 8, 7, 7,
  127056. };
  127057. static static_codebook _huff_book__44c4_s_long = {
  127058. 2, 100,
  127059. _huff_lengthlist__44c4_s_long,
  127060. 0, 0, 0, 0, 0,
  127061. NULL,
  127062. NULL,
  127063. NULL,
  127064. NULL,
  127065. 0
  127066. };
  127067. static long _vq_quantlist__44c4_s_p1_0[] = {
  127068. 1,
  127069. 0,
  127070. 2,
  127071. };
  127072. static long _vq_lengthlist__44c4_s_p1_0[] = {
  127073. 2, 4, 4, 0, 0, 0, 0, 0, 0, 5, 6, 6, 0, 0, 0, 0,
  127074. 0, 0, 5, 6, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127075. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127076. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127077. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127078. 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0, 0,
  127079. 0, 0, 0, 6, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127080. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127081. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127082. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127083. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 6, 8, 7, 0, 0,
  127084. 0, 0, 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127085. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127086. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127087. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127088. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127089. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127090. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127091. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127092. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127093. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127094. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127095. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127096. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127097. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127098. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127099. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127100. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127101. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127102. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127103. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127104. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127105. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127106. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127107. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127108. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127109. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127110. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127111. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127112. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127113. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127114. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127115. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127116. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127117. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127118. 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  127119. 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0,
  127120. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127121. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127122. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127123. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0, 0,
  127124. 0, 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0,
  127125. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127126. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127127. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127128. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 8, 8, 0, 0,
  127129. 0, 0, 0, 0, 8, 9, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9,
  127130. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127131. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127132. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127133. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127134. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127135. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127136. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127137. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127138. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127139. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127140. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127141. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127142. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127143. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127144. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127145. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127146. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127147. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127148. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127149. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127150. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127151. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127152. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127153. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127154. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127155. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127156. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127157. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127158. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127159. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127160. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127161. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127162. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127163. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127164. 0, 0, 4, 7, 7, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0,
  127165. 0, 0, 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127166. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127167. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127168. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127169. 0, 0, 0, 6, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0,
  127170. 0, 0, 0, 0, 0, 8, 8, 9, 0, 0, 0, 0, 0, 0, 0, 0,
  127171. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127172. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127173. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127174. 0, 0, 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9,
  127175. 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 0,
  127176. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127177. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127178. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127179. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127180. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127181. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127182. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127183. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127184. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127185. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127186. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127187. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127188. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127189. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127190. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127191. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127192. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127193. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127194. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127195. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127196. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127197. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127198. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127199. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127200. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127201. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127202. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127203. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127204. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127205. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127206. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127207. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127208. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127209. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127210. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127211. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127212. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127213. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127214. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127215. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127216. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127217. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127218. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127219. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127220. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127221. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127222. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127223. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127224. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127225. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127226. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127227. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127228. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127229. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127230. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127231. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127232. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127233. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127234. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127235. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127236. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127237. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127238. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127239. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127240. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127241. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127242. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127243. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127244. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127245. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127246. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127247. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127248. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127249. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127250. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127251. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127252. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127253. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127254. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127255. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127256. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127257. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127258. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127259. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127260. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127261. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127262. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127263. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127264. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127265. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127266. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127267. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127268. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127269. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127270. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127271. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127272. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127273. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127274. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127275. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127276. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127277. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127278. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127279. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127280. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127281. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127282. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127283. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127284. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127285. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127286. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127287. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127288. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127289. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127290. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127291. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127292. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127293. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127294. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127295. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127296. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127297. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127298. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127299. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127300. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127301. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127302. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127303. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127306. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127307. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127308. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127309. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127310. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127311. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127314. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127315. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127316. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127317. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127318. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127319. 0, 0, 0, 0, 0, 0, 0, 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. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127322. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127323. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127324. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127325. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127326. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127327. 0, 0, 0, 0, 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, 0,
  127332. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127333. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127334. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127335. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127336. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127337. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127338. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127339. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127340. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127341. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127342. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127343. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127344. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127345. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127346. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127347. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127348. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127349. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127350. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127351. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127352. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127353. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127354. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127355. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127356. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127357. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127358. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127359. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127360. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127361. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127362. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127363. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127364. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127365. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127366. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127367. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127368. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127369. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127370. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127371. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127372. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127373. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127374. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127375. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127376. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127377. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127378. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127379. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127380. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127381. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127382. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127383. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127384. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127385. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127386. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127387. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127388. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127389. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127390. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127391. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127392. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127393. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127394. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127395. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127396. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127397. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127398. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127399. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127400. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127401. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127402. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127403. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127404. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127405. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127406. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127407. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127408. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127409. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127410. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127411. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127412. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127413. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127414. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127415. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127416. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127417. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127418. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127419. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127420. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127421. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127422. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127423. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127424. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127425. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127426. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127427. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127428. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127429. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127430. 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127440. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127441. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127442. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127443. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127444. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127445. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127446. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127447. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127448. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127449. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127450. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127451. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127452. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127453. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127454. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127455. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127456. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127457. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127458. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127459. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127460. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127461. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127462. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127463. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127464. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127465. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127466. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127467. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127468. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127469. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127470. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127471. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127472. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127473. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127474. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127475. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127476. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127477. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127478. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127479. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127480. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127481. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127482. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127483. 0,
  127484. };
  127485. static float _vq_quantthresh__44c4_s_p1_0[] = {
  127486. -0.5, 0.5,
  127487. };
  127488. static long _vq_quantmap__44c4_s_p1_0[] = {
  127489. 1, 0, 2,
  127490. };
  127491. static encode_aux_threshmatch _vq_auxt__44c4_s_p1_0 = {
  127492. _vq_quantthresh__44c4_s_p1_0,
  127493. _vq_quantmap__44c4_s_p1_0,
  127494. 3,
  127495. 3
  127496. };
  127497. static static_codebook _44c4_s_p1_0 = {
  127498. 8, 6561,
  127499. _vq_lengthlist__44c4_s_p1_0,
  127500. 1, -535822336, 1611661312, 2, 0,
  127501. _vq_quantlist__44c4_s_p1_0,
  127502. NULL,
  127503. &_vq_auxt__44c4_s_p1_0,
  127504. NULL,
  127505. 0
  127506. };
  127507. static long _vq_quantlist__44c4_s_p2_0[] = {
  127508. 2,
  127509. 1,
  127510. 3,
  127511. 0,
  127512. 4,
  127513. };
  127514. static long _vq_lengthlist__44c4_s_p2_0[] = {
  127515. 2, 5, 5, 0, 0, 0, 5, 5, 0, 0, 0, 5, 5, 0, 0, 0,
  127516. 7, 7, 0, 0, 0, 0, 0, 0, 0, 5, 6, 6, 0, 0, 0, 7,
  127517. 7, 0, 0, 0, 7, 7, 0, 0, 0,10,10, 0, 0, 0, 0, 0,
  127518. 0, 0, 5, 6, 6, 0, 0, 0, 7, 7, 0, 0, 0, 7, 7, 0,
  127519. 0, 0,10,10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127520. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127521. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127522. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127523. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127524. 0, 0, 0, 0, 0, 0, 5, 8, 7, 0, 0, 0, 7, 7, 0, 0,
  127525. 0, 7, 7, 0, 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 5,
  127526. 7, 8, 0, 0, 0, 7, 7, 0, 0, 0, 7, 7, 0, 0, 0, 9,
  127527. 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127528. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127529. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127530. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127531. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127532. 0, 0, 0, 5, 7, 7, 0, 0, 0, 7, 7, 0, 0, 0, 7, 7,
  127533. 0, 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0,
  127534. 0, 0, 7, 7, 0, 0, 0, 7, 7, 0, 0, 0, 9, 9, 0, 0,
  127535. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127536. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127537. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127538. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127539. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127540. 7,10,10, 0, 0, 0, 9, 9, 0, 0, 0, 9, 9, 0, 0, 0,
  127541. 10,10, 0, 0, 0, 0, 0, 0, 0, 8,10,10, 0, 0, 0, 9,
  127542. 9, 0, 0, 0, 9, 9, 0, 0, 0,10,10, 0, 0, 0, 0, 0,
  127543. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127544. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127545. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127546. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127547. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127548. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127549. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127550. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127551. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127552. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127553. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127554. 0,
  127555. };
  127556. static float _vq_quantthresh__44c4_s_p2_0[] = {
  127557. -1.5, -0.5, 0.5, 1.5,
  127558. };
  127559. static long _vq_quantmap__44c4_s_p2_0[] = {
  127560. 3, 1, 0, 2, 4,
  127561. };
  127562. static encode_aux_threshmatch _vq_auxt__44c4_s_p2_0 = {
  127563. _vq_quantthresh__44c4_s_p2_0,
  127564. _vq_quantmap__44c4_s_p2_0,
  127565. 5,
  127566. 5
  127567. };
  127568. static static_codebook _44c4_s_p2_0 = {
  127569. 4, 625,
  127570. _vq_lengthlist__44c4_s_p2_0,
  127571. 1, -533725184, 1611661312, 3, 0,
  127572. _vq_quantlist__44c4_s_p2_0,
  127573. NULL,
  127574. &_vq_auxt__44c4_s_p2_0,
  127575. NULL,
  127576. 0
  127577. };
  127578. static long _vq_quantlist__44c4_s_p3_0[] = {
  127579. 2,
  127580. 1,
  127581. 3,
  127582. 0,
  127583. 4,
  127584. };
  127585. static long _vq_lengthlist__44c4_s_p3_0[] = {
  127586. 2, 3, 3, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127587. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 5, 4, 6, 6, 0, 0,
  127588. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127589. 0, 0, 4, 4, 5, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127590. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 6, 6, 9, 9,
  127591. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127592. 0, 0, 0, 0, 6, 6, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0,
  127593. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127594. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127595. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127596. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127597. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127598. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127599. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127600. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127601. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127602. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127603. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127604. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127605. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127606. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127607. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127608. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127609. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127610. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127611. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127612. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127613. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127614. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127615. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127616. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127617. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127618. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127619. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127620. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127621. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127622. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127623. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127624. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127625. 0,
  127626. };
  127627. static float _vq_quantthresh__44c4_s_p3_0[] = {
  127628. -1.5, -0.5, 0.5, 1.5,
  127629. };
  127630. static long _vq_quantmap__44c4_s_p3_0[] = {
  127631. 3, 1, 0, 2, 4,
  127632. };
  127633. static encode_aux_threshmatch _vq_auxt__44c4_s_p3_0 = {
  127634. _vq_quantthresh__44c4_s_p3_0,
  127635. _vq_quantmap__44c4_s_p3_0,
  127636. 5,
  127637. 5
  127638. };
  127639. static static_codebook _44c4_s_p3_0 = {
  127640. 4, 625,
  127641. _vq_lengthlist__44c4_s_p3_0,
  127642. 1, -533725184, 1611661312, 3, 0,
  127643. _vq_quantlist__44c4_s_p3_0,
  127644. NULL,
  127645. &_vq_auxt__44c4_s_p3_0,
  127646. NULL,
  127647. 0
  127648. };
  127649. static long _vq_quantlist__44c4_s_p4_0[] = {
  127650. 4,
  127651. 3,
  127652. 5,
  127653. 2,
  127654. 6,
  127655. 1,
  127656. 7,
  127657. 0,
  127658. 8,
  127659. };
  127660. static long _vq_lengthlist__44c4_s_p4_0[] = {
  127661. 2, 3, 3, 6, 6, 0, 0, 0, 0, 0, 4, 4, 6, 6, 0, 0,
  127662. 0, 0, 0, 4, 4, 6, 6, 0, 0, 0, 0, 0, 5, 5, 6, 6,
  127663. 0, 0, 0, 0, 0, 0, 0, 6, 6, 0, 0, 0, 0, 0, 0, 0,
  127664. 7, 8, 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0,
  127665. 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127666. 0,
  127667. };
  127668. static float _vq_quantthresh__44c4_s_p4_0[] = {
  127669. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  127670. };
  127671. static long _vq_quantmap__44c4_s_p4_0[] = {
  127672. 7, 5, 3, 1, 0, 2, 4, 6,
  127673. 8,
  127674. };
  127675. static encode_aux_threshmatch _vq_auxt__44c4_s_p4_0 = {
  127676. _vq_quantthresh__44c4_s_p4_0,
  127677. _vq_quantmap__44c4_s_p4_0,
  127678. 9,
  127679. 9
  127680. };
  127681. static static_codebook _44c4_s_p4_0 = {
  127682. 2, 81,
  127683. _vq_lengthlist__44c4_s_p4_0,
  127684. 1, -531628032, 1611661312, 4, 0,
  127685. _vq_quantlist__44c4_s_p4_0,
  127686. NULL,
  127687. &_vq_auxt__44c4_s_p4_0,
  127688. NULL,
  127689. 0
  127690. };
  127691. static long _vq_quantlist__44c4_s_p5_0[] = {
  127692. 4,
  127693. 3,
  127694. 5,
  127695. 2,
  127696. 6,
  127697. 1,
  127698. 7,
  127699. 0,
  127700. 8,
  127701. };
  127702. static long _vq_lengthlist__44c4_s_p5_0[] = {
  127703. 2, 3, 3, 6, 6, 7, 7, 9, 9, 0, 4, 4, 6, 6, 7, 7,
  127704. 9, 9, 0, 4, 5, 6, 6, 7, 7, 9, 9, 0, 6, 6, 7, 7,
  127705. 8, 8,10,10, 0, 0, 0, 7, 7, 8, 8,10, 9, 0, 0, 0,
  127706. 9, 8, 8, 8,10,10, 0, 0, 0, 8, 8, 8, 8,10,10, 0,
  127707. 0, 0,10,10, 9, 9,11,11, 0, 0, 0, 0, 0, 9, 9,10,
  127708. 10,
  127709. };
  127710. static float _vq_quantthresh__44c4_s_p5_0[] = {
  127711. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  127712. };
  127713. static long _vq_quantmap__44c4_s_p5_0[] = {
  127714. 7, 5, 3, 1, 0, 2, 4, 6,
  127715. 8,
  127716. };
  127717. static encode_aux_threshmatch _vq_auxt__44c4_s_p5_0 = {
  127718. _vq_quantthresh__44c4_s_p5_0,
  127719. _vq_quantmap__44c4_s_p5_0,
  127720. 9,
  127721. 9
  127722. };
  127723. static static_codebook _44c4_s_p5_0 = {
  127724. 2, 81,
  127725. _vq_lengthlist__44c4_s_p5_0,
  127726. 1, -531628032, 1611661312, 4, 0,
  127727. _vq_quantlist__44c4_s_p5_0,
  127728. NULL,
  127729. &_vq_auxt__44c4_s_p5_0,
  127730. NULL,
  127731. 0
  127732. };
  127733. static long _vq_quantlist__44c4_s_p6_0[] = {
  127734. 8,
  127735. 7,
  127736. 9,
  127737. 6,
  127738. 10,
  127739. 5,
  127740. 11,
  127741. 4,
  127742. 12,
  127743. 3,
  127744. 13,
  127745. 2,
  127746. 14,
  127747. 1,
  127748. 15,
  127749. 0,
  127750. 16,
  127751. };
  127752. static long _vq_lengthlist__44c4_s_p6_0[] = {
  127753. 2, 4, 4, 6, 6, 8, 8, 9, 9, 8, 8, 9, 9,10,10,11,
  127754. 11, 0, 4, 4, 6, 6, 8, 8, 9, 9, 9, 9,10,10,11,11,
  127755. 11,11, 0, 4, 4, 7, 6, 8, 8, 9, 9, 9, 9,10,10,11,
  127756. 11,11,11, 0, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  127757. 11,11,11,12, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,
  127758. 10,11,11,12,12, 0, 0, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  127759. 10,10,11,11,12,12, 0, 0, 0, 8, 8, 8, 8, 9, 9, 9,
  127760. 9,10,10,11,11,12,12, 0, 0, 0, 9, 9, 9, 9,10,10,
  127761. 10,10,11,11,11,11,12,12, 0, 0, 0, 0, 0, 9, 9,10,
  127762. 10,10,10,11,11,11,11,12,12, 0, 0, 0, 0, 0, 9, 9,
  127763. 9,10,10,10,11,11,11,11,12,12, 0, 0, 0, 0, 0, 9,
  127764. 9, 9, 9,10,10,11,11,11,12,12,12, 0, 0, 0, 0, 0,
  127765. 10,10,10,10,11,11,11,11,12,12,13,12, 0, 0, 0, 0,
  127766. 0, 0, 0,10,10,11,11,11,11,12,12,12,12, 0, 0, 0,
  127767. 0, 0, 0, 0,11,11,11,11,12,12,12,12,13,13, 0, 0,
  127768. 0, 0, 0, 0, 0,11,11,11,11,12,12,12,12,13,13, 0,
  127769. 0, 0, 0, 0, 0, 0,12,12,12,12,12,12,13,13,13,13,
  127770. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,12,12,12,13,13,
  127771. 13,
  127772. };
  127773. static float _vq_quantthresh__44c4_s_p6_0[] = {
  127774. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  127775. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  127776. };
  127777. static long _vq_quantmap__44c4_s_p6_0[] = {
  127778. 15, 13, 11, 9, 7, 5, 3, 1,
  127779. 0, 2, 4, 6, 8, 10, 12, 14,
  127780. 16,
  127781. };
  127782. static encode_aux_threshmatch _vq_auxt__44c4_s_p6_0 = {
  127783. _vq_quantthresh__44c4_s_p6_0,
  127784. _vq_quantmap__44c4_s_p6_0,
  127785. 17,
  127786. 17
  127787. };
  127788. static static_codebook _44c4_s_p6_0 = {
  127789. 2, 289,
  127790. _vq_lengthlist__44c4_s_p6_0,
  127791. 1, -529530880, 1611661312, 5, 0,
  127792. _vq_quantlist__44c4_s_p6_0,
  127793. NULL,
  127794. &_vq_auxt__44c4_s_p6_0,
  127795. NULL,
  127796. 0
  127797. };
  127798. static long _vq_quantlist__44c4_s_p7_0[] = {
  127799. 1,
  127800. 0,
  127801. 2,
  127802. };
  127803. static long _vq_lengthlist__44c4_s_p7_0[] = {
  127804. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 7, 7,10, 9, 9,11,
  127805. 9, 9, 4, 7, 7,10, 9, 9,11, 9, 9, 7,10,10,11,11,
  127806. 10,11,11,11, 6, 9, 9,11,10,10,11,10,10, 6, 9, 9,
  127807. 11,10,10,11,10,10, 7,11,11,12,11,11,12,11,11, 6,
  127808. 9, 9,11,10,10,11,10,10, 6, 9, 9,11,10,10,11,10,
  127809. 10,
  127810. };
  127811. static float _vq_quantthresh__44c4_s_p7_0[] = {
  127812. -5.5, 5.5,
  127813. };
  127814. static long _vq_quantmap__44c4_s_p7_0[] = {
  127815. 1, 0, 2,
  127816. };
  127817. static encode_aux_threshmatch _vq_auxt__44c4_s_p7_0 = {
  127818. _vq_quantthresh__44c4_s_p7_0,
  127819. _vq_quantmap__44c4_s_p7_0,
  127820. 3,
  127821. 3
  127822. };
  127823. static static_codebook _44c4_s_p7_0 = {
  127824. 4, 81,
  127825. _vq_lengthlist__44c4_s_p7_0,
  127826. 1, -529137664, 1618345984, 2, 0,
  127827. _vq_quantlist__44c4_s_p7_0,
  127828. NULL,
  127829. &_vq_auxt__44c4_s_p7_0,
  127830. NULL,
  127831. 0
  127832. };
  127833. static long _vq_quantlist__44c4_s_p7_1[] = {
  127834. 5,
  127835. 4,
  127836. 6,
  127837. 3,
  127838. 7,
  127839. 2,
  127840. 8,
  127841. 1,
  127842. 9,
  127843. 0,
  127844. 10,
  127845. };
  127846. static long _vq_lengthlist__44c4_s_p7_1[] = {
  127847. 2, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8,10, 5, 5, 6, 6,
  127848. 7, 7, 8, 8, 8, 8,10, 5, 5, 6, 6, 7, 7, 8, 8, 8,
  127849. 8,10, 6, 6, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10, 7,
  127850. 7, 8, 8, 8, 8, 8, 8,10,10,10, 8, 7, 8, 8, 8, 8,
  127851. 8, 8,10,10,10, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10,
  127852. 8, 8, 8, 8, 8, 8, 8, 8,10,10,10,10,10, 8, 8, 8,
  127853. 8, 8, 8,10,10,10,10,10, 9, 9, 8, 8, 9, 8,10,10,
  127854. 10,10,10, 8, 8, 8, 8, 9, 9,
  127855. };
  127856. static float _vq_quantthresh__44c4_s_p7_1[] = {
  127857. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  127858. 3.5, 4.5,
  127859. };
  127860. static long _vq_quantmap__44c4_s_p7_1[] = {
  127861. 9, 7, 5, 3, 1, 0, 2, 4,
  127862. 6, 8, 10,
  127863. };
  127864. static encode_aux_threshmatch _vq_auxt__44c4_s_p7_1 = {
  127865. _vq_quantthresh__44c4_s_p7_1,
  127866. _vq_quantmap__44c4_s_p7_1,
  127867. 11,
  127868. 11
  127869. };
  127870. static static_codebook _44c4_s_p7_1 = {
  127871. 2, 121,
  127872. _vq_lengthlist__44c4_s_p7_1,
  127873. 1, -531365888, 1611661312, 4, 0,
  127874. _vq_quantlist__44c4_s_p7_1,
  127875. NULL,
  127876. &_vq_auxt__44c4_s_p7_1,
  127877. NULL,
  127878. 0
  127879. };
  127880. static long _vq_quantlist__44c4_s_p8_0[] = {
  127881. 6,
  127882. 5,
  127883. 7,
  127884. 4,
  127885. 8,
  127886. 3,
  127887. 9,
  127888. 2,
  127889. 10,
  127890. 1,
  127891. 11,
  127892. 0,
  127893. 12,
  127894. };
  127895. static long _vq_lengthlist__44c4_s_p8_0[] = {
  127896. 1, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10, 6, 5, 5,
  127897. 7, 7, 8, 8, 8, 8, 9,10,11,11, 7, 5, 5, 7, 7, 8,
  127898. 8, 9, 9,10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  127899. 10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  127900. 11, 0,12,12, 9, 9, 9, 9,10,10,10,10,11,11, 0,13,
  127901. 13, 9, 9,10, 9,10,10,11,11,11,12, 0, 0, 0,10,10,
  127902. 10,10,10,10,11,11,12,12, 0, 0, 0,10,10,10,10,10,
  127903. 10,11,11,12,12, 0, 0, 0,14,14,11,11,11,11,12,12,
  127904. 12,12, 0, 0, 0,14,14,11,11,11,11,12,12,12,13, 0,
  127905. 0, 0, 0, 0,12,12,12,12,12,12,13,13, 0, 0, 0, 0,
  127906. 0,13,12,12,12,12,12,13,13,
  127907. };
  127908. static float _vq_quantthresh__44c4_s_p8_0[] = {
  127909. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  127910. 12.5, 17.5, 22.5, 27.5,
  127911. };
  127912. static long _vq_quantmap__44c4_s_p8_0[] = {
  127913. 11, 9, 7, 5, 3, 1, 0, 2,
  127914. 4, 6, 8, 10, 12,
  127915. };
  127916. static encode_aux_threshmatch _vq_auxt__44c4_s_p8_0 = {
  127917. _vq_quantthresh__44c4_s_p8_0,
  127918. _vq_quantmap__44c4_s_p8_0,
  127919. 13,
  127920. 13
  127921. };
  127922. static static_codebook _44c4_s_p8_0 = {
  127923. 2, 169,
  127924. _vq_lengthlist__44c4_s_p8_0,
  127925. 1, -526516224, 1616117760, 4, 0,
  127926. _vq_quantlist__44c4_s_p8_0,
  127927. NULL,
  127928. &_vq_auxt__44c4_s_p8_0,
  127929. NULL,
  127930. 0
  127931. };
  127932. static long _vq_quantlist__44c4_s_p8_1[] = {
  127933. 2,
  127934. 1,
  127935. 3,
  127936. 0,
  127937. 4,
  127938. };
  127939. static long _vq_lengthlist__44c4_s_p8_1[] = {
  127940. 2, 4, 4, 5, 5, 6, 5, 5, 5, 5, 6, 5, 4, 5, 5, 6,
  127941. 5, 5, 5, 5, 6, 6, 6, 5, 5,
  127942. };
  127943. static float _vq_quantthresh__44c4_s_p8_1[] = {
  127944. -1.5, -0.5, 0.5, 1.5,
  127945. };
  127946. static long _vq_quantmap__44c4_s_p8_1[] = {
  127947. 3, 1, 0, 2, 4,
  127948. };
  127949. static encode_aux_threshmatch _vq_auxt__44c4_s_p8_1 = {
  127950. _vq_quantthresh__44c4_s_p8_1,
  127951. _vq_quantmap__44c4_s_p8_1,
  127952. 5,
  127953. 5
  127954. };
  127955. static static_codebook _44c4_s_p8_1 = {
  127956. 2, 25,
  127957. _vq_lengthlist__44c4_s_p8_1,
  127958. 1, -533725184, 1611661312, 3, 0,
  127959. _vq_quantlist__44c4_s_p8_1,
  127960. NULL,
  127961. &_vq_auxt__44c4_s_p8_1,
  127962. NULL,
  127963. 0
  127964. };
  127965. static long _vq_quantlist__44c4_s_p9_0[] = {
  127966. 6,
  127967. 5,
  127968. 7,
  127969. 4,
  127970. 8,
  127971. 3,
  127972. 9,
  127973. 2,
  127974. 10,
  127975. 1,
  127976. 11,
  127977. 0,
  127978. 12,
  127979. };
  127980. static long _vq_lengthlist__44c4_s_p9_0[] = {
  127981. 1, 3, 3,12,12,12,12,12,12,12,12,12,12, 4, 7, 7,
  127982. 12,12,12,12,12,12,12,12,12,12, 3, 8, 8,12,12,12,
  127983. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  127984. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  127985. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  127986. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  127987. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  127988. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  127989. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  127990. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  127991. 12,12,12,12,12,12,12,12,12,
  127992. };
  127993. static float _vq_quantthresh__44c4_s_p9_0[] = {
  127994. -1732.5, -1417.5, -1102.5, -787.5, -472.5, -157.5, 157.5, 472.5,
  127995. 787.5, 1102.5, 1417.5, 1732.5,
  127996. };
  127997. static long _vq_quantmap__44c4_s_p9_0[] = {
  127998. 11, 9, 7, 5, 3, 1, 0, 2,
  127999. 4, 6, 8, 10, 12,
  128000. };
  128001. static encode_aux_threshmatch _vq_auxt__44c4_s_p9_0 = {
  128002. _vq_quantthresh__44c4_s_p9_0,
  128003. _vq_quantmap__44c4_s_p9_0,
  128004. 13,
  128005. 13
  128006. };
  128007. static static_codebook _44c4_s_p9_0 = {
  128008. 2, 169,
  128009. _vq_lengthlist__44c4_s_p9_0,
  128010. 1, -513964032, 1628680192, 4, 0,
  128011. _vq_quantlist__44c4_s_p9_0,
  128012. NULL,
  128013. &_vq_auxt__44c4_s_p9_0,
  128014. NULL,
  128015. 0
  128016. };
  128017. static long _vq_quantlist__44c4_s_p9_1[] = {
  128018. 7,
  128019. 6,
  128020. 8,
  128021. 5,
  128022. 9,
  128023. 4,
  128024. 10,
  128025. 3,
  128026. 11,
  128027. 2,
  128028. 12,
  128029. 1,
  128030. 13,
  128031. 0,
  128032. 14,
  128033. };
  128034. static long _vq_lengthlist__44c4_s_p9_1[] = {
  128035. 1, 4, 4, 5, 5, 7, 7, 9, 8,10, 9,10,10,10,10, 6,
  128036. 5, 5, 7, 7, 9, 8,10, 9,11,10,12,12,13,13, 6, 5,
  128037. 5, 7, 7, 9, 9,10,10,11,11,12,12,12,13,19, 8, 8,
  128038. 8, 8, 9, 9,10,10,12,11,12,12,13,13,19, 8, 8, 8,
  128039. 8, 9, 9,11,11,12,12,13,13,13,13,19,12,12, 9, 9,
  128040. 11,11,11,11,12,11,13,12,13,13,18,12,12, 9, 9,11,
  128041. 10,11,11,12,12,12,13,13,14,19,18,18,11,11,11,11,
  128042. 12,12,13,12,13,13,14,14,16,18,18,11,11,11,10,12,
  128043. 11,13,13,13,13,13,14,17,18,18,14,15,11,12,12,13,
  128044. 13,13,13,14,14,14,18,18,18,15,15,12,10,13,10,13,
  128045. 13,13,13,13,14,18,17,18,17,18,12,13,12,13,13,13,
  128046. 14,14,16,14,18,17,18,18,17,13,12,13,10,12,12,14,
  128047. 14,14,14,17,18,18,18,18,14,15,12,12,13,12,14,14,
  128048. 15,15,18,18,18,17,18,15,14,12,11,12,12,14,14,14,
  128049. 15,
  128050. };
  128051. static float _vq_quantthresh__44c4_s_p9_1[] = {
  128052. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  128053. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  128054. };
  128055. static long _vq_quantmap__44c4_s_p9_1[] = {
  128056. 13, 11, 9, 7, 5, 3, 1, 0,
  128057. 2, 4, 6, 8, 10, 12, 14,
  128058. };
  128059. static encode_aux_threshmatch _vq_auxt__44c4_s_p9_1 = {
  128060. _vq_quantthresh__44c4_s_p9_1,
  128061. _vq_quantmap__44c4_s_p9_1,
  128062. 15,
  128063. 15
  128064. };
  128065. static static_codebook _44c4_s_p9_1 = {
  128066. 2, 225,
  128067. _vq_lengthlist__44c4_s_p9_1,
  128068. 1, -520986624, 1620377600, 4, 0,
  128069. _vq_quantlist__44c4_s_p9_1,
  128070. NULL,
  128071. &_vq_auxt__44c4_s_p9_1,
  128072. NULL,
  128073. 0
  128074. };
  128075. static long _vq_quantlist__44c4_s_p9_2[] = {
  128076. 10,
  128077. 9,
  128078. 11,
  128079. 8,
  128080. 12,
  128081. 7,
  128082. 13,
  128083. 6,
  128084. 14,
  128085. 5,
  128086. 15,
  128087. 4,
  128088. 16,
  128089. 3,
  128090. 17,
  128091. 2,
  128092. 18,
  128093. 1,
  128094. 19,
  128095. 0,
  128096. 20,
  128097. };
  128098. static long _vq_lengthlist__44c4_s_p9_2[] = {
  128099. 2, 5, 5, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8,
  128100. 8, 9, 9, 9, 9,11, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,
  128101. 9, 9, 9, 9, 9, 9,10,10,10,10,11, 6, 6, 7, 7, 8,
  128102. 8, 8, 8, 9, 9, 9, 9, 9, 9,10, 9,10,10,10,10,11,
  128103. 7, 7, 7, 7, 8, 8, 9, 9, 9, 9, 9, 9, 9,10,10,10,
  128104. 10,10,10,10,12,11,11, 7, 7, 8, 8, 9, 9, 9, 9, 9,
  128105. 9,10,10,10,10,10,10,10,10,12,11,12, 8, 8, 8, 8,
  128106. 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,11,11,
  128107. 11, 8, 8, 8, 8, 9, 9, 9, 9,10,10,10,10,10,10,10,
  128108. 10,10,10,11,11,12, 9, 9, 9, 9, 9, 9,10, 9,10,10,
  128109. 10,10,10,10,10,10,10,10,11,11,11,11,11, 9, 9, 9,
  128110. 9,10,10,10,10,10,10,10,10,10,10,10,10,11,12,11,
  128111. 11,11, 9, 9, 9,10,10,10,10,10,10,10,10,10,10,10,
  128112. 10,10,11,11,11,11,11, 9, 9, 9, 9,10,10,10,10,10,
  128113. 10,10,10,10,10,10,10,11,11,11,12,12,10,10,10,10,
  128114. 10,10,10,10,10,10,10,10,10,10,10,10,11,12,11,12,
  128115. 11,11,11, 9,10,10,10,10,10,10,10,10,10,10,10,10,
  128116. 10,11,12,11,11,11,11,11,10,10,10,10,10,10,10,10,
  128117. 10,10,10,10,10,10,11,11,11,12,11,11,11,10,10,10,
  128118. 10,10,10,10,10,10,10,10,10,10,10,12,11,11,12,11,
  128119. 11,11,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  128120. 11,11,11,11,11,11,11,11,11,10,10,10,10,10,10,10,
  128121. 10,10,10,10,10,11,11,11,11,12,12,11,11,11,11,11,
  128122. 11,11,10,10,10,10,10,10,10,10,12,12,12,11,11,11,
  128123. 12,11,11,11,10,10,10,10,10,10,10,10,10,10,10,12,
  128124. 11,12,12,12,12,12,11,12,11,11,10,10,10,10,10,10,
  128125. 10,10,10,10,12,12,12,12,11,11,11,11,11,11,11,10,
  128126. 10,10,10,10,10,10,10,10,10,
  128127. };
  128128. static float _vq_quantthresh__44c4_s_p9_2[] = {
  128129. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  128130. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  128131. 6.5, 7.5, 8.5, 9.5,
  128132. };
  128133. static long _vq_quantmap__44c4_s_p9_2[] = {
  128134. 19, 17, 15, 13, 11, 9, 7, 5,
  128135. 3, 1, 0, 2, 4, 6, 8, 10,
  128136. 12, 14, 16, 18, 20,
  128137. };
  128138. static encode_aux_threshmatch _vq_auxt__44c4_s_p9_2 = {
  128139. _vq_quantthresh__44c4_s_p9_2,
  128140. _vq_quantmap__44c4_s_p9_2,
  128141. 21,
  128142. 21
  128143. };
  128144. static static_codebook _44c4_s_p9_2 = {
  128145. 2, 441,
  128146. _vq_lengthlist__44c4_s_p9_2,
  128147. 1, -529268736, 1611661312, 5, 0,
  128148. _vq_quantlist__44c4_s_p9_2,
  128149. NULL,
  128150. &_vq_auxt__44c4_s_p9_2,
  128151. NULL,
  128152. 0
  128153. };
  128154. static long _huff_lengthlist__44c4_s_short[] = {
  128155. 4, 7,14,10,15,10,12,15,16,15, 4, 2,11, 5,10, 6,
  128156. 8,11,14,14,14,10, 7,11, 6, 8,10,11,13,15, 9, 4,
  128157. 11, 5, 9, 6, 9,12,14,15,14, 9, 6, 9, 4, 5, 7,10,
  128158. 12,13, 9, 5, 7, 6, 5, 5, 7,10,13,13,10, 8, 9, 8,
  128159. 7, 6, 8,10,14,14,13,11,10,10, 7, 7, 8,11,14,15,
  128160. 13,12, 9, 9, 6, 5, 7,10,14,17,15,13,11,10, 6, 6,
  128161. 7, 9,12,17,
  128162. };
  128163. static static_codebook _huff_book__44c4_s_short = {
  128164. 2, 100,
  128165. _huff_lengthlist__44c4_s_short,
  128166. 0, 0, 0, 0, 0,
  128167. NULL,
  128168. NULL,
  128169. NULL,
  128170. NULL,
  128171. 0
  128172. };
  128173. static long _huff_lengthlist__44c5_s_long[] = {
  128174. 3, 8, 9,13,10,12,12,12,12,12, 6, 4, 6, 8, 6, 8,
  128175. 10,10,11,12, 8, 5, 4,10, 4, 7, 8, 9,10,11,13, 8,
  128176. 10, 8, 9, 9,11,12,13,14,10, 6, 4, 9, 3, 5, 6, 8,
  128177. 10,11,11, 8, 6, 9, 5, 5, 6, 7, 9,11,12, 9, 7,11,
  128178. 6, 6, 6, 7, 8,10,12,11, 9,12, 7, 7, 6, 6, 7, 9,
  128179. 13,12,10,13, 9, 8, 7, 7, 7, 8,11,15,11,15,11,10,
  128180. 9, 8, 7, 7,
  128181. };
  128182. static static_codebook _huff_book__44c5_s_long = {
  128183. 2, 100,
  128184. _huff_lengthlist__44c5_s_long,
  128185. 0, 0, 0, 0, 0,
  128186. NULL,
  128187. NULL,
  128188. NULL,
  128189. NULL,
  128190. 0
  128191. };
  128192. static long _vq_quantlist__44c5_s_p1_0[] = {
  128193. 1,
  128194. 0,
  128195. 2,
  128196. };
  128197. static long _vq_lengthlist__44c5_s_p1_0[] = {
  128198. 2, 4, 4, 0, 0, 0, 0, 0, 0, 4, 7, 7, 0, 0, 0, 0,
  128199. 0, 0, 4, 6, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128200. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128201. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128202. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128203. 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0, 0,
  128204. 0, 0, 0, 7, 8, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128205. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128206. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128207. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128208. 0, 0, 4, 7, 7, 0, 0, 0, 0, 0, 0, 7, 9, 8, 0, 0,
  128209. 0, 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128210. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128211. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128212. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128213. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128214. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128215. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128216. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128217. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128218. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128219. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128220. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128221. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128222. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128223. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128224. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128225. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128226. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128227. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128228. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128229. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128230. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128231. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128232. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128233. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128234. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128235. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128236. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128237. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128238. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128239. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128240. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128241. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128242. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128243. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 7, 7, 0, 0, 0, 0,
  128244. 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  128245. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128246. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128247. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128248. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0, 0,
  128249. 0, 0, 0, 9,10,11, 0, 0, 0, 0, 0, 0, 9,10,10, 0,
  128250. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128251. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128252. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128253. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  128254. 0, 0, 0, 0, 8,10, 9, 0, 0, 0, 0, 0, 0, 9,10,11,
  128255. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128256. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128257. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128258. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128259. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128260. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128261. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128262. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128263. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128264. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128265. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128266. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128267. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128268. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128269. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128270. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128271. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128272. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128273. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128274. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128275. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128276. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128277. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128278. 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128288. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128289. 0, 0, 4, 7, 7, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  128290. 0, 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128291. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128292. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128293. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128294. 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,11,10, 0,
  128295. 0, 0, 0, 0, 0, 8, 9,10, 0, 0, 0, 0, 0, 0, 0, 0,
  128296. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128297. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128298. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128299. 0, 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,10,10,
  128300. 0, 0, 0, 0, 0, 0, 9,11,10, 0, 0, 0, 0, 0, 0, 0,
  128301. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128302. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128303. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128304. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128305. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128306. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128307. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128308. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128309. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128310. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128311. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128312. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128313. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128314. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128315. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128316. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128317. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128318. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128319. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128320. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128321. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128322. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128323. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128324. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128325. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128326. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128327. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128328. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128329. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128330. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128331. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128332. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128333. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128334. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128335. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128336. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128337. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128338. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128339. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128340. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128341. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128342. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128343. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128344. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128345. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128346. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128347. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128348. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128349. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128350. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128351. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128352. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128353. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128354. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128355. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128356. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128357. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128358. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128359. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128360. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128361. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128362. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128363. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128364. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128365. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128366. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128367. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128368. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128369. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128370. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128371. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128372. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128373. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128374. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128375. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128376. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128377. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128378. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128379. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128380. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128381. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128382. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128383. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128384. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128385. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128386. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128387. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128388. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128389. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128390. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128391. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128392. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128393. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128394. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128395. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128396. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128397. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128398. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128399. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128400. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128401. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128402. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128403. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128404. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128405. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128406. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128407. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128408. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128409. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128410. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128411. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128412. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128413. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128414. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128415. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128416. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128417. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0,
  128423. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128424. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128425. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128426. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128427. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128428. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128429. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128430. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128431. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128432. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128433. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128434. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128435. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128436. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128437. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128438. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128439. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128440. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128441. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128442. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128443. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128444. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128445. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128446. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128447. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128448. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128449. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128450. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128451. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128452. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128453. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128454. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128455. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128456. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128457. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128458. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128459. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128460. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128461. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128462. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128463. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128464. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128465. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128466. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128467. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128468. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128469. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128470. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128471. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128472. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128473. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128474. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128475. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128476. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128477. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128478. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128479. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128480. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128481. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128482. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128483. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128484. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128485. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128486. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128487. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128488. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128489. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128490. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128491. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128492. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128493. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128494. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128495. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128496. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128497. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128498. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128499. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128500. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128501. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128502. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128503. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128504. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128505. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128506. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128507. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128508. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128509. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128510. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128511. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128512. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128513. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128514. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128515. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128516. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128517. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128518. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128519. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128520. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128521. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128522. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128523. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128524. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128525. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128526. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128527. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128528. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128529. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128530. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128531. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128532. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128533. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128534. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128535. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128536. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128537. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128538. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128539. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128540. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128541. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128542. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128543. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128544. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128545. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128546. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128547. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128548. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128549. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128550. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128551. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128552. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128553. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128554. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128555. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128556. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128557. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128558. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128559. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128560. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128561. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128562. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128563. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128564. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128565. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128566. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128567. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128568. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128569. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128570. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128571. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128572. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128573. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128574. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128575. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128576. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128577. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128578. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128579. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128580. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128581. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128582. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128583. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128584. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128585. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128586. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128587. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128588. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128589. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128590. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128591. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128592. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128593. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128594. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128595. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128596. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128597. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128598. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128599. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128600. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128601. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128602. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128603. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128604. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128605. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128606. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128607. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128608. 0,
  128609. };
  128610. static float _vq_quantthresh__44c5_s_p1_0[] = {
  128611. -0.5, 0.5,
  128612. };
  128613. static long _vq_quantmap__44c5_s_p1_0[] = {
  128614. 1, 0, 2,
  128615. };
  128616. static encode_aux_threshmatch _vq_auxt__44c5_s_p1_0 = {
  128617. _vq_quantthresh__44c5_s_p1_0,
  128618. _vq_quantmap__44c5_s_p1_0,
  128619. 3,
  128620. 3
  128621. };
  128622. static static_codebook _44c5_s_p1_0 = {
  128623. 8, 6561,
  128624. _vq_lengthlist__44c5_s_p1_0,
  128625. 1, -535822336, 1611661312, 2, 0,
  128626. _vq_quantlist__44c5_s_p1_0,
  128627. NULL,
  128628. &_vq_auxt__44c5_s_p1_0,
  128629. NULL,
  128630. 0
  128631. };
  128632. static long _vq_quantlist__44c5_s_p2_0[] = {
  128633. 2,
  128634. 1,
  128635. 3,
  128636. 0,
  128637. 4,
  128638. };
  128639. static long _vq_lengthlist__44c5_s_p2_0[] = {
  128640. 2, 4, 4, 0, 0, 0, 5, 5, 0, 0, 0, 5, 5, 0, 0, 0,
  128641. 8, 7, 0, 0, 0, 0, 0, 0, 0, 4, 6, 6, 0, 0, 0, 8,
  128642. 8, 0, 0, 0, 8, 7, 0, 0, 0,10,10, 0, 0, 0, 0, 0,
  128643. 0, 0, 4, 6, 6, 0, 0, 0, 8, 8, 0, 0, 0, 7, 8, 0,
  128644. 0, 0,10,10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128645. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128646. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128647. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128648. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128649. 0, 0, 0, 0, 0, 0, 5, 8, 7, 0, 0, 0, 8, 8, 0, 0,
  128650. 0, 8, 8, 0, 0, 0,10,10, 0, 0, 0, 0, 0, 0, 0, 5,
  128651. 7, 8, 0, 0, 0, 8, 8, 0, 0, 0, 8, 8, 0, 0, 0,10,
  128652. 10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128653. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128654. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128655. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128656. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128657. 0, 0, 0, 5, 8, 8, 0, 0, 0, 8, 8, 0, 0, 0, 8, 8,
  128658. 0, 0, 0,10,10, 0, 0, 0, 0, 0, 0, 0, 5, 8, 8, 0,
  128659. 0, 0, 8, 8, 0, 0, 0, 8, 8, 0, 0, 0,10,10, 0, 0,
  128660. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128661. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128662. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128663. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128664. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128665. 8,10,10, 0, 0, 0,10,10, 0, 0, 0, 9,10, 0, 0, 0,
  128666. 11,10, 0, 0, 0, 0, 0, 0, 0, 8,10,10, 0, 0, 0,10,
  128667. 10, 0, 0, 0,10,10, 0, 0, 0,10,11, 0, 0, 0, 0, 0,
  128668. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128669. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128670. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128671. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128672. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128673. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128674. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128675. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128676. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128677. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128678. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128679. 0,
  128680. };
  128681. static float _vq_quantthresh__44c5_s_p2_0[] = {
  128682. -1.5, -0.5, 0.5, 1.5,
  128683. };
  128684. static long _vq_quantmap__44c5_s_p2_0[] = {
  128685. 3, 1, 0, 2, 4,
  128686. };
  128687. static encode_aux_threshmatch _vq_auxt__44c5_s_p2_0 = {
  128688. _vq_quantthresh__44c5_s_p2_0,
  128689. _vq_quantmap__44c5_s_p2_0,
  128690. 5,
  128691. 5
  128692. };
  128693. static static_codebook _44c5_s_p2_0 = {
  128694. 4, 625,
  128695. _vq_lengthlist__44c5_s_p2_0,
  128696. 1, -533725184, 1611661312, 3, 0,
  128697. _vq_quantlist__44c5_s_p2_0,
  128698. NULL,
  128699. &_vq_auxt__44c5_s_p2_0,
  128700. NULL,
  128701. 0
  128702. };
  128703. static long _vq_quantlist__44c5_s_p3_0[] = {
  128704. 2,
  128705. 1,
  128706. 3,
  128707. 0,
  128708. 4,
  128709. };
  128710. static long _vq_lengthlist__44c5_s_p3_0[] = {
  128711. 2, 4, 3, 5, 5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128712. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 5, 5, 6, 6, 0, 0,
  128713. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128714. 0, 0, 3, 5, 5, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128715. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 6, 6, 8, 8,
  128716. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128717. 0, 0, 0, 0, 5, 6, 6, 8, 8, 0, 0, 0, 0, 0, 0, 0,
  128718. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128719. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128720. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128721. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128722. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128723. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128724. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128725. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128726. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128727. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128728. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128729. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128730. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128731. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128732. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128733. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128734. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128735. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128736. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128737. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128738. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128739. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128740. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128741. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128742. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128743. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128744. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128745. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128746. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128747. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128748. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128749. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128750. 0,
  128751. };
  128752. static float _vq_quantthresh__44c5_s_p3_0[] = {
  128753. -1.5, -0.5, 0.5, 1.5,
  128754. };
  128755. static long _vq_quantmap__44c5_s_p3_0[] = {
  128756. 3, 1, 0, 2, 4,
  128757. };
  128758. static encode_aux_threshmatch _vq_auxt__44c5_s_p3_0 = {
  128759. _vq_quantthresh__44c5_s_p3_0,
  128760. _vq_quantmap__44c5_s_p3_0,
  128761. 5,
  128762. 5
  128763. };
  128764. static static_codebook _44c5_s_p3_0 = {
  128765. 4, 625,
  128766. _vq_lengthlist__44c5_s_p3_0,
  128767. 1, -533725184, 1611661312, 3, 0,
  128768. _vq_quantlist__44c5_s_p3_0,
  128769. NULL,
  128770. &_vq_auxt__44c5_s_p3_0,
  128771. NULL,
  128772. 0
  128773. };
  128774. static long _vq_quantlist__44c5_s_p4_0[] = {
  128775. 4,
  128776. 3,
  128777. 5,
  128778. 2,
  128779. 6,
  128780. 1,
  128781. 7,
  128782. 0,
  128783. 8,
  128784. };
  128785. static long _vq_lengthlist__44c5_s_p4_0[] = {
  128786. 2, 3, 3, 6, 6, 0, 0, 0, 0, 0, 4, 4, 6, 6, 0, 0,
  128787. 0, 0, 0, 4, 4, 6, 6, 0, 0, 0, 0, 0, 5, 5, 6, 6,
  128788. 0, 0, 0, 0, 0, 0, 0, 6, 6, 0, 0, 0, 0, 0, 0, 0,
  128789. 7, 7, 0, 0, 0, 0, 0, 0, 0, 8, 7, 0, 0, 0, 0, 0,
  128790. 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128791. 0,
  128792. };
  128793. static float _vq_quantthresh__44c5_s_p4_0[] = {
  128794. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  128795. };
  128796. static long _vq_quantmap__44c5_s_p4_0[] = {
  128797. 7, 5, 3, 1, 0, 2, 4, 6,
  128798. 8,
  128799. };
  128800. static encode_aux_threshmatch _vq_auxt__44c5_s_p4_0 = {
  128801. _vq_quantthresh__44c5_s_p4_0,
  128802. _vq_quantmap__44c5_s_p4_0,
  128803. 9,
  128804. 9
  128805. };
  128806. static static_codebook _44c5_s_p4_0 = {
  128807. 2, 81,
  128808. _vq_lengthlist__44c5_s_p4_0,
  128809. 1, -531628032, 1611661312, 4, 0,
  128810. _vq_quantlist__44c5_s_p4_0,
  128811. NULL,
  128812. &_vq_auxt__44c5_s_p4_0,
  128813. NULL,
  128814. 0
  128815. };
  128816. static long _vq_quantlist__44c5_s_p5_0[] = {
  128817. 4,
  128818. 3,
  128819. 5,
  128820. 2,
  128821. 6,
  128822. 1,
  128823. 7,
  128824. 0,
  128825. 8,
  128826. };
  128827. static long _vq_lengthlist__44c5_s_p5_0[] = {
  128828. 2, 4, 3, 6, 6, 7, 7, 9, 9, 0, 4, 4, 6, 6, 7, 7,
  128829. 9, 9, 0, 4, 4, 6, 6, 7, 7, 9, 9, 0, 6, 6, 7, 7,
  128830. 7, 7, 9, 9, 0, 0, 0, 7, 6, 7, 7, 9, 9, 0, 0, 0,
  128831. 8, 8, 8, 8,10,10, 0, 0, 0, 8, 8, 8, 8,10,10, 0,
  128832. 0, 0, 9, 9, 9, 9,10,10, 0, 0, 0, 0, 0, 9, 9,10,
  128833. 10,
  128834. };
  128835. static float _vq_quantthresh__44c5_s_p5_0[] = {
  128836. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  128837. };
  128838. static long _vq_quantmap__44c5_s_p5_0[] = {
  128839. 7, 5, 3, 1, 0, 2, 4, 6,
  128840. 8,
  128841. };
  128842. static encode_aux_threshmatch _vq_auxt__44c5_s_p5_0 = {
  128843. _vq_quantthresh__44c5_s_p5_0,
  128844. _vq_quantmap__44c5_s_p5_0,
  128845. 9,
  128846. 9
  128847. };
  128848. static static_codebook _44c5_s_p5_0 = {
  128849. 2, 81,
  128850. _vq_lengthlist__44c5_s_p5_0,
  128851. 1, -531628032, 1611661312, 4, 0,
  128852. _vq_quantlist__44c5_s_p5_0,
  128853. NULL,
  128854. &_vq_auxt__44c5_s_p5_0,
  128855. NULL,
  128856. 0
  128857. };
  128858. static long _vq_quantlist__44c5_s_p6_0[] = {
  128859. 8,
  128860. 7,
  128861. 9,
  128862. 6,
  128863. 10,
  128864. 5,
  128865. 11,
  128866. 4,
  128867. 12,
  128868. 3,
  128869. 13,
  128870. 2,
  128871. 14,
  128872. 1,
  128873. 15,
  128874. 0,
  128875. 16,
  128876. };
  128877. static long _vq_lengthlist__44c5_s_p6_0[] = {
  128878. 2, 4, 4, 6, 6, 8, 8, 9, 9, 9, 9,10,10,10,10,11,
  128879. 11, 0, 4, 4, 6, 6, 8, 8, 9, 9, 9, 9,10,10,11,11,
  128880. 12,12, 0, 4, 4, 6, 6, 8, 8, 9, 9, 9, 9,10,10,11,
  128881. 11,12,12, 0, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  128882. 11,11,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,
  128883. 10,11,11,12,12, 0, 0, 0, 7, 7, 9, 9,10,10,10,10,
  128884. 11,11,11,11,12,12, 0, 0, 0, 7, 7, 8, 9,10,10,10,
  128885. 10,11,11,11,11,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,
  128886. 10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 9, 9,10,
  128887. 10,10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 9, 9,
  128888. 10,10,10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 9,
  128889. 9, 9,10,10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0,
  128890. 10,10,10,10,11,11,11,12,12,12,13,13, 0, 0, 0, 0,
  128891. 0, 0, 0,10,10,11,11,11,11,12,12,13,13, 0, 0, 0,
  128892. 0, 0, 0, 0,11,11,11,11,12,12,12,13,13,13, 0, 0,
  128893. 0, 0, 0, 0, 0,11,11,11,11,12,12,12,12,13,13, 0,
  128894. 0, 0, 0, 0, 0, 0,12,12,12,12,13,12,13,13,13,13,
  128895. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,13,
  128896. 13,
  128897. };
  128898. static float _vq_quantthresh__44c5_s_p6_0[] = {
  128899. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  128900. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  128901. };
  128902. static long _vq_quantmap__44c5_s_p6_0[] = {
  128903. 15, 13, 11, 9, 7, 5, 3, 1,
  128904. 0, 2, 4, 6, 8, 10, 12, 14,
  128905. 16,
  128906. };
  128907. static encode_aux_threshmatch _vq_auxt__44c5_s_p6_0 = {
  128908. _vq_quantthresh__44c5_s_p6_0,
  128909. _vq_quantmap__44c5_s_p6_0,
  128910. 17,
  128911. 17
  128912. };
  128913. static static_codebook _44c5_s_p6_0 = {
  128914. 2, 289,
  128915. _vq_lengthlist__44c5_s_p6_0,
  128916. 1, -529530880, 1611661312, 5, 0,
  128917. _vq_quantlist__44c5_s_p6_0,
  128918. NULL,
  128919. &_vq_auxt__44c5_s_p6_0,
  128920. NULL,
  128921. 0
  128922. };
  128923. static long _vq_quantlist__44c5_s_p7_0[] = {
  128924. 1,
  128925. 0,
  128926. 2,
  128927. };
  128928. static long _vq_lengthlist__44c5_s_p7_0[] = {
  128929. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 7, 7,10, 9, 9,11,
  128930. 9, 9, 4, 7, 7,10, 9, 9,11, 9, 9, 7,10,10,11,11,
  128931. 10,11,11,11, 6, 9, 9,11,10,10,11,10,10, 6, 9, 9,
  128932. 11,10,10,11,10,10, 7,11,11,12,11,11,12,11,11, 6,
  128933. 9, 9,11,10,10,11,10,10, 6, 9, 9,11,10,10,11,10,
  128934. 10,
  128935. };
  128936. static float _vq_quantthresh__44c5_s_p7_0[] = {
  128937. -5.5, 5.5,
  128938. };
  128939. static long _vq_quantmap__44c5_s_p7_0[] = {
  128940. 1, 0, 2,
  128941. };
  128942. static encode_aux_threshmatch _vq_auxt__44c5_s_p7_0 = {
  128943. _vq_quantthresh__44c5_s_p7_0,
  128944. _vq_quantmap__44c5_s_p7_0,
  128945. 3,
  128946. 3
  128947. };
  128948. static static_codebook _44c5_s_p7_0 = {
  128949. 4, 81,
  128950. _vq_lengthlist__44c5_s_p7_0,
  128951. 1, -529137664, 1618345984, 2, 0,
  128952. _vq_quantlist__44c5_s_p7_0,
  128953. NULL,
  128954. &_vq_auxt__44c5_s_p7_0,
  128955. NULL,
  128956. 0
  128957. };
  128958. static long _vq_quantlist__44c5_s_p7_1[] = {
  128959. 5,
  128960. 4,
  128961. 6,
  128962. 3,
  128963. 7,
  128964. 2,
  128965. 8,
  128966. 1,
  128967. 9,
  128968. 0,
  128969. 10,
  128970. };
  128971. static long _vq_lengthlist__44c5_s_p7_1[] = {
  128972. 2, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8,10, 5, 5, 6, 6,
  128973. 7, 7, 8, 8, 8, 8,10, 5, 5, 6, 6, 7, 7, 8, 8, 8,
  128974. 8,10, 6, 6, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10, 7,
  128975. 7, 8, 8, 8, 8, 8, 8,10,10,10, 7, 7, 8, 8, 8, 8,
  128976. 8, 8,10,10,10, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10,
  128977. 8, 8, 8, 8, 8, 8, 8, 9,10,10,10,10,10, 8, 8, 8,
  128978. 8, 8, 8,10,10,10,10,10, 9, 9, 8, 8, 8, 8,10,10,
  128979. 10,10,10, 8, 8, 8, 8, 8, 8,
  128980. };
  128981. static float _vq_quantthresh__44c5_s_p7_1[] = {
  128982. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  128983. 3.5, 4.5,
  128984. };
  128985. static long _vq_quantmap__44c5_s_p7_1[] = {
  128986. 9, 7, 5, 3, 1, 0, 2, 4,
  128987. 6, 8, 10,
  128988. };
  128989. static encode_aux_threshmatch _vq_auxt__44c5_s_p7_1 = {
  128990. _vq_quantthresh__44c5_s_p7_1,
  128991. _vq_quantmap__44c5_s_p7_1,
  128992. 11,
  128993. 11
  128994. };
  128995. static static_codebook _44c5_s_p7_1 = {
  128996. 2, 121,
  128997. _vq_lengthlist__44c5_s_p7_1,
  128998. 1, -531365888, 1611661312, 4, 0,
  128999. _vq_quantlist__44c5_s_p7_1,
  129000. NULL,
  129001. &_vq_auxt__44c5_s_p7_1,
  129002. NULL,
  129003. 0
  129004. };
  129005. static long _vq_quantlist__44c5_s_p8_0[] = {
  129006. 6,
  129007. 5,
  129008. 7,
  129009. 4,
  129010. 8,
  129011. 3,
  129012. 9,
  129013. 2,
  129014. 10,
  129015. 1,
  129016. 11,
  129017. 0,
  129018. 12,
  129019. };
  129020. static long _vq_lengthlist__44c5_s_p8_0[] = {
  129021. 1, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10, 6, 5, 5,
  129022. 7, 7, 8, 8, 8, 9,10,10,10,10, 7, 5, 5, 7, 7, 8,
  129023. 8, 9, 9,10,10,10,10, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  129024. 10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  129025. 11, 0,12,12, 9, 9, 9,10,10,10,10,10,11,11, 0,13,
  129026. 13, 9, 9, 9, 9,10,10,11,11,11,11, 0, 0, 0,10,10,
  129027. 10,10,10,10,11,11,11,11, 0, 0, 0,10,10,10,10,10,
  129028. 10,11,11,12,12, 0, 0, 0,14,14,11,11,11,11,12,12,
  129029. 12,12, 0, 0, 0,14,14,11,11,11,11,12,12,12,12, 0,
  129030. 0, 0, 0, 0,12,12,12,12,12,12,13,13, 0, 0, 0, 0,
  129031. 0,12,12,12,12,12,12,13,13,
  129032. };
  129033. static float _vq_quantthresh__44c5_s_p8_0[] = {
  129034. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  129035. 12.5, 17.5, 22.5, 27.5,
  129036. };
  129037. static long _vq_quantmap__44c5_s_p8_0[] = {
  129038. 11, 9, 7, 5, 3, 1, 0, 2,
  129039. 4, 6, 8, 10, 12,
  129040. };
  129041. static encode_aux_threshmatch _vq_auxt__44c5_s_p8_0 = {
  129042. _vq_quantthresh__44c5_s_p8_0,
  129043. _vq_quantmap__44c5_s_p8_0,
  129044. 13,
  129045. 13
  129046. };
  129047. static static_codebook _44c5_s_p8_0 = {
  129048. 2, 169,
  129049. _vq_lengthlist__44c5_s_p8_0,
  129050. 1, -526516224, 1616117760, 4, 0,
  129051. _vq_quantlist__44c5_s_p8_0,
  129052. NULL,
  129053. &_vq_auxt__44c5_s_p8_0,
  129054. NULL,
  129055. 0
  129056. };
  129057. static long _vq_quantlist__44c5_s_p8_1[] = {
  129058. 2,
  129059. 1,
  129060. 3,
  129061. 0,
  129062. 4,
  129063. };
  129064. static long _vq_lengthlist__44c5_s_p8_1[] = {
  129065. 2, 4, 4, 5, 5, 6, 5, 5, 5, 5, 6, 4, 5, 5, 5, 6,
  129066. 5, 5, 5, 5, 6, 6, 6, 5, 5,
  129067. };
  129068. static float _vq_quantthresh__44c5_s_p8_1[] = {
  129069. -1.5, -0.5, 0.5, 1.5,
  129070. };
  129071. static long _vq_quantmap__44c5_s_p8_1[] = {
  129072. 3, 1, 0, 2, 4,
  129073. };
  129074. static encode_aux_threshmatch _vq_auxt__44c5_s_p8_1 = {
  129075. _vq_quantthresh__44c5_s_p8_1,
  129076. _vq_quantmap__44c5_s_p8_1,
  129077. 5,
  129078. 5
  129079. };
  129080. static static_codebook _44c5_s_p8_1 = {
  129081. 2, 25,
  129082. _vq_lengthlist__44c5_s_p8_1,
  129083. 1, -533725184, 1611661312, 3, 0,
  129084. _vq_quantlist__44c5_s_p8_1,
  129085. NULL,
  129086. &_vq_auxt__44c5_s_p8_1,
  129087. NULL,
  129088. 0
  129089. };
  129090. static long _vq_quantlist__44c5_s_p9_0[] = {
  129091. 7,
  129092. 6,
  129093. 8,
  129094. 5,
  129095. 9,
  129096. 4,
  129097. 10,
  129098. 3,
  129099. 11,
  129100. 2,
  129101. 12,
  129102. 1,
  129103. 13,
  129104. 0,
  129105. 14,
  129106. };
  129107. static long _vq_lengthlist__44c5_s_p9_0[] = {
  129108. 1, 3, 3,13,13,13,13,13,13,13,13,13,13,13,13, 4,
  129109. 7, 7,13,13,13,13,13,13,13,13,13,13,13,13, 3, 8,
  129110. 6,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  129111. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  129112. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  129113. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  129114. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  129115. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  129116. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  129117. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  129118. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  129119. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  129120. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  129121. 13,13,13,13,13,13,13,13,13,12,12,12,12,12,12,12,
  129122. 12,
  129123. };
  129124. static float _vq_quantthresh__44c5_s_p9_0[] = {
  129125. -2320.5, -1963.5, -1606.5, -1249.5, -892.5, -535.5, -178.5, 178.5,
  129126. 535.5, 892.5, 1249.5, 1606.5, 1963.5, 2320.5,
  129127. };
  129128. static long _vq_quantmap__44c5_s_p9_0[] = {
  129129. 13, 11, 9, 7, 5, 3, 1, 0,
  129130. 2, 4, 6, 8, 10, 12, 14,
  129131. };
  129132. static encode_aux_threshmatch _vq_auxt__44c5_s_p9_0 = {
  129133. _vq_quantthresh__44c5_s_p9_0,
  129134. _vq_quantmap__44c5_s_p9_0,
  129135. 15,
  129136. 15
  129137. };
  129138. static static_codebook _44c5_s_p9_0 = {
  129139. 2, 225,
  129140. _vq_lengthlist__44c5_s_p9_0,
  129141. 1, -512522752, 1628852224, 4, 0,
  129142. _vq_quantlist__44c5_s_p9_0,
  129143. NULL,
  129144. &_vq_auxt__44c5_s_p9_0,
  129145. NULL,
  129146. 0
  129147. };
  129148. static long _vq_quantlist__44c5_s_p9_1[] = {
  129149. 8,
  129150. 7,
  129151. 9,
  129152. 6,
  129153. 10,
  129154. 5,
  129155. 11,
  129156. 4,
  129157. 12,
  129158. 3,
  129159. 13,
  129160. 2,
  129161. 14,
  129162. 1,
  129163. 15,
  129164. 0,
  129165. 16,
  129166. };
  129167. static long _vq_lengthlist__44c5_s_p9_1[] = {
  129168. 1, 4, 4, 5, 5, 7, 7, 9, 8,10, 9,10,10,11,10,11,
  129169. 11, 6, 5, 5, 7, 7, 8, 9,10,10,11,10,12,11,12,11,
  129170. 13,12, 6, 5, 5, 7, 7, 9, 9,10,10,11,11,12,12,13,
  129171. 12,13,13,18, 8, 8, 8, 8, 9, 9,10,11,11,11,12,11,
  129172. 13,11,13,12,18, 8, 8, 8, 8,10,10,11,11,12,12,13,
  129173. 13,13,13,13,14,18,12,12, 9, 9,11,11,11,11,12,12,
  129174. 13,12,13,12,13,13,20,13,12, 9, 9,11,11,11,11,12,
  129175. 12,13,13,13,14,14,13,20,18,19,11,12,11,11,12,12,
  129176. 13,13,13,13,13,13,14,13,18,19,19,12,11,11,11,12,
  129177. 12,13,12,13,13,13,14,14,13,18,17,19,14,15,12,12,
  129178. 12,13,13,13,14,14,14,14,14,14,19,19,19,16,15,12,
  129179. 11,13,12,14,14,14,13,13,14,14,14,19,18,19,18,19,
  129180. 13,13,13,13,14,14,14,13,14,14,14,14,18,17,19,19,
  129181. 19,13,13,13,11,13,11,13,14,14,14,14,14,19,17,17,
  129182. 18,18,16,16,13,13,13,13,14,13,15,15,14,14,19,19,
  129183. 17,17,18,16,16,13,11,14,10,13,12,14,14,14,14,19,
  129184. 19,19,19,19,18,17,13,14,13,11,14,13,14,14,15,15,
  129185. 19,19,19,17,19,18,18,14,13,12,11,14,11,15,15,15,
  129186. 15,
  129187. };
  129188. static float _vq_quantthresh__44c5_s_p9_1[] = {
  129189. -157.5, -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5,
  129190. 10.5, 31.5, 52.5, 73.5, 94.5, 115.5, 136.5, 157.5,
  129191. };
  129192. static long _vq_quantmap__44c5_s_p9_1[] = {
  129193. 15, 13, 11, 9, 7, 5, 3, 1,
  129194. 0, 2, 4, 6, 8, 10, 12, 14,
  129195. 16,
  129196. };
  129197. static encode_aux_threshmatch _vq_auxt__44c5_s_p9_1 = {
  129198. _vq_quantthresh__44c5_s_p9_1,
  129199. _vq_quantmap__44c5_s_p9_1,
  129200. 17,
  129201. 17
  129202. };
  129203. static static_codebook _44c5_s_p9_1 = {
  129204. 2, 289,
  129205. _vq_lengthlist__44c5_s_p9_1,
  129206. 1, -520814592, 1620377600, 5, 0,
  129207. _vq_quantlist__44c5_s_p9_1,
  129208. NULL,
  129209. &_vq_auxt__44c5_s_p9_1,
  129210. NULL,
  129211. 0
  129212. };
  129213. static long _vq_quantlist__44c5_s_p9_2[] = {
  129214. 10,
  129215. 9,
  129216. 11,
  129217. 8,
  129218. 12,
  129219. 7,
  129220. 13,
  129221. 6,
  129222. 14,
  129223. 5,
  129224. 15,
  129225. 4,
  129226. 16,
  129227. 3,
  129228. 17,
  129229. 2,
  129230. 18,
  129231. 1,
  129232. 19,
  129233. 0,
  129234. 20,
  129235. };
  129236. static long _vq_lengthlist__44c5_s_p9_2[] = {
  129237. 3, 5, 5, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8,
  129238. 8, 8, 8, 8, 9,11, 5, 6, 7, 7, 8, 7, 8, 8, 8, 8,
  129239. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,11, 5, 5, 7, 7, 7,
  129240. 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,11,
  129241. 7, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9,
  129242. 9,10, 9,10,11,11,11, 7, 7, 8, 8, 8, 8, 9, 9, 9,
  129243. 9, 9, 9,10,10,10,10,10,10,11,11,11, 8, 8, 8, 8,
  129244. 9, 9, 9, 9, 9, 9, 9,10,10,10,10,10,10,10,11,11,
  129245. 11, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,10,10,10,10,10,
  129246. 10,10,10,11,11,11, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  129247. 10,10,10,10,10,10,10,10,11,11,11,11,11, 9, 9, 9,
  129248. 9, 9, 9,10, 9,10,10,10,10,10,10,10,10,11,11,11,
  129249. 11,11, 9, 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,
  129250. 10,10,11,11,11,11,11, 9, 9, 9, 9, 9, 9,10,10,10,
  129251. 10,10,10,10,10,10,10,11,11,11,11,11, 9, 9,10, 9,
  129252. 10,10,10,10,10,10,10,10,10,10,10,10,11,11,11,11,
  129253. 11,11,11, 9, 9,10,10,10,10,10,10,10,10,10,10,10,
  129254. 10,11,11,11,11,11,11,11,10,10,10,10,10,10,10,10,
  129255. 10,10,10,10,10,10,11,11,11,11,11,11,11,10,10,10,
  129256. 10,10,10,10,10,10,10,10,10,10,10,11,11,11,11,11,
  129257. 11,11,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  129258. 11,11,11,11,11,11,11,11,11,10,10,10,10,10,10,10,
  129259. 10,10,10,10,10,11,11,11,11,11,11,11,11,11,10,10,
  129260. 10,10,10,10,10,10,10,10,10,10,11,11,11,11,11,11,
  129261. 11,11,11,10,10,10,10,10,10,10,10,10,10,10,10,11,
  129262. 11,11,11,11,11,11,11,11,10,10,10,10,10,10,10,10,
  129263. 10,10,10,10,11,11,11,11,11,11,11,11,11,11,11,10,
  129264. 10,10,10,10,10,10,10,10,10,
  129265. };
  129266. static float _vq_quantthresh__44c5_s_p9_2[] = {
  129267. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  129268. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  129269. 6.5, 7.5, 8.5, 9.5,
  129270. };
  129271. static long _vq_quantmap__44c5_s_p9_2[] = {
  129272. 19, 17, 15, 13, 11, 9, 7, 5,
  129273. 3, 1, 0, 2, 4, 6, 8, 10,
  129274. 12, 14, 16, 18, 20,
  129275. };
  129276. static encode_aux_threshmatch _vq_auxt__44c5_s_p9_2 = {
  129277. _vq_quantthresh__44c5_s_p9_2,
  129278. _vq_quantmap__44c5_s_p9_2,
  129279. 21,
  129280. 21
  129281. };
  129282. static static_codebook _44c5_s_p9_2 = {
  129283. 2, 441,
  129284. _vq_lengthlist__44c5_s_p9_2,
  129285. 1, -529268736, 1611661312, 5, 0,
  129286. _vq_quantlist__44c5_s_p9_2,
  129287. NULL,
  129288. &_vq_auxt__44c5_s_p9_2,
  129289. NULL,
  129290. 0
  129291. };
  129292. static long _huff_lengthlist__44c5_s_short[] = {
  129293. 5, 8,10,14,11,11,12,16,15,17, 5, 5, 7, 9, 7, 8,
  129294. 10,13,17,17, 7, 5, 5,10, 5, 7, 8,11,13,15,10, 8,
  129295. 10, 8, 8, 8,11,15,18,18, 8, 5, 5, 8, 3, 4, 6,10,
  129296. 14,16, 9, 7, 6, 7, 4, 3, 5, 9,14,18,10, 9, 8,10,
  129297. 6, 5, 6, 9,14,18,12,12,11,12, 8, 7, 8,11,14,18,
  129298. 14,13,12,10, 7, 5, 6, 9,14,18,14,14,13,10, 6, 5,
  129299. 6, 8,11,16,
  129300. };
  129301. static static_codebook _huff_book__44c5_s_short = {
  129302. 2, 100,
  129303. _huff_lengthlist__44c5_s_short,
  129304. 0, 0, 0, 0, 0,
  129305. NULL,
  129306. NULL,
  129307. NULL,
  129308. NULL,
  129309. 0
  129310. };
  129311. static long _huff_lengthlist__44c6_s_long[] = {
  129312. 3, 8,11,13,14,14,13,13,16,14, 6, 3, 4, 7, 9, 9,
  129313. 10,11,14,13,10, 4, 3, 5, 7, 7, 9,10,13,15,12, 7,
  129314. 4, 4, 6, 6, 8,10,13,15,12, 8, 6, 6, 6, 6, 8,10,
  129315. 13,14,11, 9, 7, 6, 6, 6, 7, 8,12,11,13,10, 9, 8,
  129316. 7, 6, 6, 7,11,11,13,11,10, 9, 9, 7, 7, 6,10,11,
  129317. 13,13,13,13,13,11, 9, 8,10,12,12,15,15,16,15,12,
  129318. 11,10,10,12,
  129319. };
  129320. static static_codebook _huff_book__44c6_s_long = {
  129321. 2, 100,
  129322. _huff_lengthlist__44c6_s_long,
  129323. 0, 0, 0, 0, 0,
  129324. NULL,
  129325. NULL,
  129326. NULL,
  129327. NULL,
  129328. 0
  129329. };
  129330. static long _vq_quantlist__44c6_s_p1_0[] = {
  129331. 1,
  129332. 0,
  129333. 2,
  129334. };
  129335. static long _vq_lengthlist__44c6_s_p1_0[] = {
  129336. 1, 5, 5, 0, 5, 5, 0, 5, 5, 5, 8, 7, 0, 9, 9, 0,
  129337. 9, 8, 5, 7, 8, 0, 9, 9, 0, 8, 9, 0, 0, 0, 0, 0,
  129338. 0, 0, 0, 0, 5, 9, 8, 0, 8, 8, 0, 8, 8, 5, 8, 9,
  129339. 0, 8, 8, 0, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5,
  129340. 9, 9, 0, 8, 8, 0, 8, 8, 5, 9, 9, 0, 8, 8, 0, 8,
  129341. 8,
  129342. };
  129343. static float _vq_quantthresh__44c6_s_p1_0[] = {
  129344. -0.5, 0.5,
  129345. };
  129346. static long _vq_quantmap__44c6_s_p1_0[] = {
  129347. 1, 0, 2,
  129348. };
  129349. static encode_aux_threshmatch _vq_auxt__44c6_s_p1_0 = {
  129350. _vq_quantthresh__44c6_s_p1_0,
  129351. _vq_quantmap__44c6_s_p1_0,
  129352. 3,
  129353. 3
  129354. };
  129355. static static_codebook _44c6_s_p1_0 = {
  129356. 4, 81,
  129357. _vq_lengthlist__44c6_s_p1_0,
  129358. 1, -535822336, 1611661312, 2, 0,
  129359. _vq_quantlist__44c6_s_p1_0,
  129360. NULL,
  129361. &_vq_auxt__44c6_s_p1_0,
  129362. NULL,
  129363. 0
  129364. };
  129365. static long _vq_quantlist__44c6_s_p2_0[] = {
  129366. 2,
  129367. 1,
  129368. 3,
  129369. 0,
  129370. 4,
  129371. };
  129372. static long _vq_lengthlist__44c6_s_p2_0[] = {
  129373. 3, 5, 5, 8, 8, 0, 5, 5, 8, 8, 0, 5, 5, 8, 8, 0,
  129374. 7, 7, 9, 9, 0, 0, 0, 9, 9, 5, 7, 7, 9, 9, 0, 8,
  129375. 8,10,10, 0, 8, 7,10, 9, 0,10,10,11,11, 0, 0, 0,
  129376. 11,11, 5, 7, 7, 9, 9, 0, 8, 8,10,10, 0, 7, 8, 9,
  129377. 10, 0,10,10,11,11, 0, 0, 0,11,11, 8, 9, 9,11,11,
  129378. 0,11,11,12,12, 0,11,10,12,12, 0,13,14,14,14, 0,
  129379. 0, 0,14,13, 8, 9, 9,11,11, 0,11,11,12,12, 0,10,
  129380. 11,12,12, 0,14,13,14,14, 0, 0, 0,13,14, 0, 0, 0,
  129381. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129382. 0, 0, 0, 0, 0, 0, 5, 8, 7,11,10, 0, 7, 7,10,10,
  129383. 0, 7, 7,10,10, 0, 9, 9,11,10, 0, 0, 0,11,11, 5,
  129384. 7, 8,10,11, 0, 7, 7,10,10, 0, 7, 7,10,10, 0, 9,
  129385. 9,10,11, 0, 0, 0,11,11, 8,10, 9,12,12, 0,10,10,
  129386. 12,12, 0,10,10,12,12, 0,12,12,13,13, 0, 0, 0,13,
  129387. 13, 8, 9,10,12,12, 0,10,10,11,12, 0,10,10,12,12,
  129388. 0,12,12,13,13, 0, 0, 0,13,13, 0, 0, 0, 0, 0, 0,
  129389. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129390. 0, 0, 0, 5, 8, 8,11,11, 0, 7, 7,10,10, 0, 7, 7,
  129391. 10,10, 0, 9, 9,10,11, 0, 0, 0,11,10, 5, 8, 8,11,
  129392. 11, 0, 7, 7,10,10, 0, 7, 7,10,10, 0, 9, 9,11,11,
  129393. 0, 0, 0,10,11, 8,10,10,12,12, 0,10,10,12,12, 0,
  129394. 10,10,12,12, 0,12,13,13,13, 0, 0, 0,14,13, 8,10,
  129395. 10,12,12, 0,10,10,12,12, 0,10,10,12,12, 0,13,12,
  129396. 13,13, 0, 0, 0,13,13, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129397. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129398. 7,10,10,14,13, 0, 9, 9,13,12, 0, 9, 9,12,12, 0,
  129399. 10,10,12,12, 0, 0, 0,12,12, 7,10,10,13,14, 0, 9,
  129400. 9,12,13, 0, 9, 9,12,12, 0,10,10,12,12, 0, 0, 0,
  129401. 12,12, 9,11,11,14,13, 0,11,10,14,13, 0,11,11,13,
  129402. 13, 0,12,12,13,13, 0, 0, 0,13,13, 9,11,11,13,14,
  129403. 0,10,11,13,14, 0,11,11,13,13, 0,12,12,13,13, 0,
  129404. 0, 0,13,13, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129405. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129406. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129407. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129408. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 9,
  129409. 11,11,14,14, 0,11,11,13,13, 0,11,10,13,13, 0,12,
  129410. 12,13,13, 0, 0, 0,13,13, 9,11,11,14,14, 0,11,11,
  129411. 13,13, 0,10,11,13,13, 0,12,12,14,13, 0, 0, 0,13,
  129412. 13,
  129413. };
  129414. static float _vq_quantthresh__44c6_s_p2_0[] = {
  129415. -1.5, -0.5, 0.5, 1.5,
  129416. };
  129417. static long _vq_quantmap__44c6_s_p2_0[] = {
  129418. 3, 1, 0, 2, 4,
  129419. };
  129420. static encode_aux_threshmatch _vq_auxt__44c6_s_p2_0 = {
  129421. _vq_quantthresh__44c6_s_p2_0,
  129422. _vq_quantmap__44c6_s_p2_0,
  129423. 5,
  129424. 5
  129425. };
  129426. static static_codebook _44c6_s_p2_0 = {
  129427. 4, 625,
  129428. _vq_lengthlist__44c6_s_p2_0,
  129429. 1, -533725184, 1611661312, 3, 0,
  129430. _vq_quantlist__44c6_s_p2_0,
  129431. NULL,
  129432. &_vq_auxt__44c6_s_p2_0,
  129433. NULL,
  129434. 0
  129435. };
  129436. static long _vq_quantlist__44c6_s_p3_0[] = {
  129437. 4,
  129438. 3,
  129439. 5,
  129440. 2,
  129441. 6,
  129442. 1,
  129443. 7,
  129444. 0,
  129445. 8,
  129446. };
  129447. static long _vq_lengthlist__44c6_s_p3_0[] = {
  129448. 2, 3, 4, 6, 6, 7, 7, 9, 9, 0, 4, 4, 6, 6, 7, 7,
  129449. 9,10, 0, 4, 4, 6, 6, 7, 7,10, 9, 0, 5, 5, 7, 7,
  129450. 8, 8,10,10, 0, 0, 0, 7, 6, 8, 8,10,10, 0, 0, 0,
  129451. 7, 7, 9, 9,11,11, 0, 0, 0, 7, 7, 9, 9,11,11, 0,
  129452. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129453. 0,
  129454. };
  129455. static float _vq_quantthresh__44c6_s_p3_0[] = {
  129456. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  129457. };
  129458. static long _vq_quantmap__44c6_s_p3_0[] = {
  129459. 7, 5, 3, 1, 0, 2, 4, 6,
  129460. 8,
  129461. };
  129462. static encode_aux_threshmatch _vq_auxt__44c6_s_p3_0 = {
  129463. _vq_quantthresh__44c6_s_p3_0,
  129464. _vq_quantmap__44c6_s_p3_0,
  129465. 9,
  129466. 9
  129467. };
  129468. static static_codebook _44c6_s_p3_0 = {
  129469. 2, 81,
  129470. _vq_lengthlist__44c6_s_p3_0,
  129471. 1, -531628032, 1611661312, 4, 0,
  129472. _vq_quantlist__44c6_s_p3_0,
  129473. NULL,
  129474. &_vq_auxt__44c6_s_p3_0,
  129475. NULL,
  129476. 0
  129477. };
  129478. static long _vq_quantlist__44c6_s_p4_0[] = {
  129479. 8,
  129480. 7,
  129481. 9,
  129482. 6,
  129483. 10,
  129484. 5,
  129485. 11,
  129486. 4,
  129487. 12,
  129488. 3,
  129489. 13,
  129490. 2,
  129491. 14,
  129492. 1,
  129493. 15,
  129494. 0,
  129495. 16,
  129496. };
  129497. static long _vq_lengthlist__44c6_s_p4_0[] = {
  129498. 2, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9,10,10,
  129499. 10, 0, 4, 4, 6, 6, 8, 8, 9, 9, 9, 9,10,10,10,10,
  129500. 11,11, 0, 4, 4, 6, 6, 8, 8, 9, 9, 9, 9,10,10,10,
  129501. 10,11,11, 0, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  129502. 11,11,11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,
  129503. 10,11,11,11,11, 0, 0, 0, 7, 7, 9, 9,10,10,10,10,
  129504. 11,11,11,11,12,12, 0, 0, 0, 7, 7, 9, 9,10,10,10,
  129505. 10,11,11,11,11,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9,
  129506. 10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 8, 8, 9,
  129507. 9,10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 0, 0,
  129508. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129509. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129510. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129511. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129512. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129513. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129514. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129515. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129516. 0,
  129517. };
  129518. static float _vq_quantthresh__44c6_s_p4_0[] = {
  129519. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  129520. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  129521. };
  129522. static long _vq_quantmap__44c6_s_p4_0[] = {
  129523. 15, 13, 11, 9, 7, 5, 3, 1,
  129524. 0, 2, 4, 6, 8, 10, 12, 14,
  129525. 16,
  129526. };
  129527. static encode_aux_threshmatch _vq_auxt__44c6_s_p4_0 = {
  129528. _vq_quantthresh__44c6_s_p4_0,
  129529. _vq_quantmap__44c6_s_p4_0,
  129530. 17,
  129531. 17
  129532. };
  129533. static static_codebook _44c6_s_p4_0 = {
  129534. 2, 289,
  129535. _vq_lengthlist__44c6_s_p4_0,
  129536. 1, -529530880, 1611661312, 5, 0,
  129537. _vq_quantlist__44c6_s_p4_0,
  129538. NULL,
  129539. &_vq_auxt__44c6_s_p4_0,
  129540. NULL,
  129541. 0
  129542. };
  129543. static long _vq_quantlist__44c6_s_p5_0[] = {
  129544. 1,
  129545. 0,
  129546. 2,
  129547. };
  129548. static long _vq_lengthlist__44c6_s_p5_0[] = {
  129549. 1, 4, 4, 5, 7, 7, 6, 7, 7, 4, 6, 6, 9, 9,10,10,
  129550. 10, 9, 4, 6, 6, 9,10, 9,10, 9,10, 6, 9, 9,10,12,
  129551. 11,10,11,11, 7,10, 9,11,12,12,12,12,12, 7,10,10,
  129552. 11,12,12,12,12,12, 6,10,10,10,12,12,11,12,12, 7,
  129553. 9,10,11,12,12,12,12,12, 7,10, 9,12,12,12,12,12,
  129554. 12,
  129555. };
  129556. static float _vq_quantthresh__44c6_s_p5_0[] = {
  129557. -5.5, 5.5,
  129558. };
  129559. static long _vq_quantmap__44c6_s_p5_0[] = {
  129560. 1, 0, 2,
  129561. };
  129562. static encode_aux_threshmatch _vq_auxt__44c6_s_p5_0 = {
  129563. _vq_quantthresh__44c6_s_p5_0,
  129564. _vq_quantmap__44c6_s_p5_0,
  129565. 3,
  129566. 3
  129567. };
  129568. static static_codebook _44c6_s_p5_0 = {
  129569. 4, 81,
  129570. _vq_lengthlist__44c6_s_p5_0,
  129571. 1, -529137664, 1618345984, 2, 0,
  129572. _vq_quantlist__44c6_s_p5_0,
  129573. NULL,
  129574. &_vq_auxt__44c6_s_p5_0,
  129575. NULL,
  129576. 0
  129577. };
  129578. static long _vq_quantlist__44c6_s_p5_1[] = {
  129579. 5,
  129580. 4,
  129581. 6,
  129582. 3,
  129583. 7,
  129584. 2,
  129585. 8,
  129586. 1,
  129587. 9,
  129588. 0,
  129589. 10,
  129590. };
  129591. static long _vq_lengthlist__44c6_s_p5_1[] = {
  129592. 3, 5, 4, 6, 6, 7, 7, 8, 8, 8, 8,11, 4, 4, 6, 6,
  129593. 7, 7, 8, 8, 8, 8,11, 4, 4, 6, 6, 7, 7, 8, 8, 8,
  129594. 8,11, 6, 6, 6, 6, 8, 8, 8, 8, 9, 9,11,11,11, 6,
  129595. 6, 7, 8, 8, 8, 8, 9,11,11,11, 7, 7, 8, 8, 8, 8,
  129596. 8, 8,11,11,11, 7, 7, 8, 8, 8, 8, 8, 8,11,11,11,
  129597. 8, 8, 8, 8, 8, 8, 8, 8,11,11,11,10,10, 8, 8, 8,
  129598. 8, 8, 8,11,11,11,10,10, 8, 8, 8, 8, 8, 8,11,11,
  129599. 11,10,10, 7, 7, 8, 8, 8, 8,
  129600. };
  129601. static float _vq_quantthresh__44c6_s_p5_1[] = {
  129602. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  129603. 3.5, 4.5,
  129604. };
  129605. static long _vq_quantmap__44c6_s_p5_1[] = {
  129606. 9, 7, 5, 3, 1, 0, 2, 4,
  129607. 6, 8, 10,
  129608. };
  129609. static encode_aux_threshmatch _vq_auxt__44c6_s_p5_1 = {
  129610. _vq_quantthresh__44c6_s_p5_1,
  129611. _vq_quantmap__44c6_s_p5_1,
  129612. 11,
  129613. 11
  129614. };
  129615. static static_codebook _44c6_s_p5_1 = {
  129616. 2, 121,
  129617. _vq_lengthlist__44c6_s_p5_1,
  129618. 1, -531365888, 1611661312, 4, 0,
  129619. _vq_quantlist__44c6_s_p5_1,
  129620. NULL,
  129621. &_vq_auxt__44c6_s_p5_1,
  129622. NULL,
  129623. 0
  129624. };
  129625. static long _vq_quantlist__44c6_s_p6_0[] = {
  129626. 6,
  129627. 5,
  129628. 7,
  129629. 4,
  129630. 8,
  129631. 3,
  129632. 9,
  129633. 2,
  129634. 10,
  129635. 1,
  129636. 11,
  129637. 0,
  129638. 12,
  129639. };
  129640. static long _vq_lengthlist__44c6_s_p6_0[] = {
  129641. 1, 4, 4, 6, 6, 8, 8, 8, 8,10, 9,10,10, 6, 5, 5,
  129642. 7, 7, 9, 9, 9, 9,10,10,11,11, 6, 5, 5, 7, 7, 9,
  129643. 9,10, 9,11,10,11,11, 0, 6, 6, 7, 7, 9, 9,10,10,
  129644. 11,11,12,12, 0, 7, 7, 7, 7, 9, 9,10,10,11,11,12,
  129645. 12, 0,11,11, 8, 8,10,10,11,11,12,12,12,12, 0,11,
  129646. 12, 9, 8,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0,
  129647. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129648. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129649. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129650. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129651. 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129652. };
  129653. static float _vq_quantthresh__44c6_s_p6_0[] = {
  129654. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  129655. 12.5, 17.5, 22.5, 27.5,
  129656. };
  129657. static long _vq_quantmap__44c6_s_p6_0[] = {
  129658. 11, 9, 7, 5, 3, 1, 0, 2,
  129659. 4, 6, 8, 10, 12,
  129660. };
  129661. static encode_aux_threshmatch _vq_auxt__44c6_s_p6_0 = {
  129662. _vq_quantthresh__44c6_s_p6_0,
  129663. _vq_quantmap__44c6_s_p6_0,
  129664. 13,
  129665. 13
  129666. };
  129667. static static_codebook _44c6_s_p6_0 = {
  129668. 2, 169,
  129669. _vq_lengthlist__44c6_s_p6_0,
  129670. 1, -526516224, 1616117760, 4, 0,
  129671. _vq_quantlist__44c6_s_p6_0,
  129672. NULL,
  129673. &_vq_auxt__44c6_s_p6_0,
  129674. NULL,
  129675. 0
  129676. };
  129677. static long _vq_quantlist__44c6_s_p6_1[] = {
  129678. 2,
  129679. 1,
  129680. 3,
  129681. 0,
  129682. 4,
  129683. };
  129684. static long _vq_lengthlist__44c6_s_p6_1[] = {
  129685. 3, 4, 4, 5, 5, 5, 4, 4, 5, 5, 5, 4, 4, 5, 5, 6,
  129686. 5, 5, 5, 5, 6, 6, 6, 5, 5,
  129687. };
  129688. static float _vq_quantthresh__44c6_s_p6_1[] = {
  129689. -1.5, -0.5, 0.5, 1.5,
  129690. };
  129691. static long _vq_quantmap__44c6_s_p6_1[] = {
  129692. 3, 1, 0, 2, 4,
  129693. };
  129694. static encode_aux_threshmatch _vq_auxt__44c6_s_p6_1 = {
  129695. _vq_quantthresh__44c6_s_p6_1,
  129696. _vq_quantmap__44c6_s_p6_1,
  129697. 5,
  129698. 5
  129699. };
  129700. static static_codebook _44c6_s_p6_1 = {
  129701. 2, 25,
  129702. _vq_lengthlist__44c6_s_p6_1,
  129703. 1, -533725184, 1611661312, 3, 0,
  129704. _vq_quantlist__44c6_s_p6_1,
  129705. NULL,
  129706. &_vq_auxt__44c6_s_p6_1,
  129707. NULL,
  129708. 0
  129709. };
  129710. static long _vq_quantlist__44c6_s_p7_0[] = {
  129711. 6,
  129712. 5,
  129713. 7,
  129714. 4,
  129715. 8,
  129716. 3,
  129717. 9,
  129718. 2,
  129719. 10,
  129720. 1,
  129721. 11,
  129722. 0,
  129723. 12,
  129724. };
  129725. static long _vq_lengthlist__44c6_s_p7_0[] = {
  129726. 1, 4, 4, 6, 6, 8, 8, 8, 8,10,10,11,10, 6, 5, 5,
  129727. 7, 7, 8, 8, 9, 9,10,10,12,11, 6, 5, 5, 7, 7, 8,
  129728. 8, 9, 9,10,10,12,11,21, 7, 7, 7, 7, 9, 9,10,10,
  129729. 11,11,12,12,21, 7, 7, 7, 7, 9, 9,10,10,11,11,12,
  129730. 12,21,12,12, 9, 9,10,10,11,11,11,11,12,12,21,12,
  129731. 12, 9, 9,10,10,11,11,12,12,12,12,21,21,21,11,11,
  129732. 10,10,11,12,12,12,13,13,21,21,21,11,11,10,10,12,
  129733. 12,12,12,13,13,21,21,21,15,15,11,11,12,12,13,13,
  129734. 13,13,21,21,21,15,16,11,11,12,12,13,13,14,14,21,
  129735. 21,21,21,20,13,13,13,13,13,13,14,14,20,20,20,20,
  129736. 20,13,13,13,13,13,13,14,14,
  129737. };
  129738. static float _vq_quantthresh__44c6_s_p7_0[] = {
  129739. -60.5, -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5,
  129740. 27.5, 38.5, 49.5, 60.5,
  129741. };
  129742. static long _vq_quantmap__44c6_s_p7_0[] = {
  129743. 11, 9, 7, 5, 3, 1, 0, 2,
  129744. 4, 6, 8, 10, 12,
  129745. };
  129746. static encode_aux_threshmatch _vq_auxt__44c6_s_p7_0 = {
  129747. _vq_quantthresh__44c6_s_p7_0,
  129748. _vq_quantmap__44c6_s_p7_0,
  129749. 13,
  129750. 13
  129751. };
  129752. static static_codebook _44c6_s_p7_0 = {
  129753. 2, 169,
  129754. _vq_lengthlist__44c6_s_p7_0,
  129755. 1, -523206656, 1618345984, 4, 0,
  129756. _vq_quantlist__44c6_s_p7_0,
  129757. NULL,
  129758. &_vq_auxt__44c6_s_p7_0,
  129759. NULL,
  129760. 0
  129761. };
  129762. static long _vq_quantlist__44c6_s_p7_1[] = {
  129763. 5,
  129764. 4,
  129765. 6,
  129766. 3,
  129767. 7,
  129768. 2,
  129769. 8,
  129770. 1,
  129771. 9,
  129772. 0,
  129773. 10,
  129774. };
  129775. static long _vq_lengthlist__44c6_s_p7_1[] = {
  129776. 3, 5, 5, 6, 6, 7, 7, 7, 7, 7, 7, 9, 5, 5, 6, 6,
  129777. 7, 7, 7, 7, 8, 7, 8, 5, 5, 6, 6, 7, 7, 7, 7, 7,
  129778. 7, 9, 6, 6, 7, 7, 7, 7, 8, 7, 7, 8, 9, 9, 9, 7,
  129779. 7, 7, 7, 7, 7, 7, 8, 9, 9, 9, 7, 7, 7, 7, 8, 8,
  129780. 8, 8, 9, 9, 9, 7, 7, 7, 7, 7, 7, 8, 8, 9, 9, 9,
  129781. 8, 8, 8, 8, 7, 7, 8, 8, 9, 9, 9, 9, 8, 8, 8, 7,
  129782. 7, 8, 8, 9, 9, 9, 8, 8, 8, 8, 7, 7, 8, 8, 9, 9,
  129783. 9, 8, 8, 7, 7, 7, 7, 8, 8,
  129784. };
  129785. static float _vq_quantthresh__44c6_s_p7_1[] = {
  129786. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  129787. 3.5, 4.5,
  129788. };
  129789. static long _vq_quantmap__44c6_s_p7_1[] = {
  129790. 9, 7, 5, 3, 1, 0, 2, 4,
  129791. 6, 8, 10,
  129792. };
  129793. static encode_aux_threshmatch _vq_auxt__44c6_s_p7_1 = {
  129794. _vq_quantthresh__44c6_s_p7_1,
  129795. _vq_quantmap__44c6_s_p7_1,
  129796. 11,
  129797. 11
  129798. };
  129799. static static_codebook _44c6_s_p7_1 = {
  129800. 2, 121,
  129801. _vq_lengthlist__44c6_s_p7_1,
  129802. 1, -531365888, 1611661312, 4, 0,
  129803. _vq_quantlist__44c6_s_p7_1,
  129804. NULL,
  129805. &_vq_auxt__44c6_s_p7_1,
  129806. NULL,
  129807. 0
  129808. };
  129809. static long _vq_quantlist__44c6_s_p8_0[] = {
  129810. 7,
  129811. 6,
  129812. 8,
  129813. 5,
  129814. 9,
  129815. 4,
  129816. 10,
  129817. 3,
  129818. 11,
  129819. 2,
  129820. 12,
  129821. 1,
  129822. 13,
  129823. 0,
  129824. 14,
  129825. };
  129826. static long _vq_lengthlist__44c6_s_p8_0[] = {
  129827. 1, 4, 4, 7, 7, 8, 8, 7, 7, 8, 7, 9, 8,10, 9, 6,
  129828. 5, 5, 8, 8, 9, 9, 8, 8, 9, 9,11,10,11,10, 6, 5,
  129829. 5, 8, 8, 9, 9, 8, 8, 9, 9,10,10,11,11,18, 8, 8,
  129830. 9, 8,10,10, 9, 9,10,10,10,10,11,10,18, 8, 8, 9,
  129831. 9,10,10, 9, 9,10,10,11,11,12,12,18,12,13, 9,10,
  129832. 10,10, 9,10,10,10,11,11,12,11,18,13,13, 9, 9,10,
  129833. 10,10,10,10,10,11,11,12,12,18,18,18,10,10, 9, 9,
  129834. 11,11,11,11,11,12,12,12,18,18,18,10, 9,10, 9,11,
  129835. 10,11,11,11,11,13,12,18,18,18,14,13,10,10,11,11,
  129836. 12,12,12,12,12,12,18,18,18,14,13,10,10,11,10,12,
  129837. 12,12,12,12,12,18,18,18,18,18,12,12,11,11,12,12,
  129838. 13,13,13,14,18,18,18,18,18,12,12,11,11,12,11,13,
  129839. 13,14,13,18,18,18,18,18,16,16,11,12,12,13,13,13,
  129840. 14,13,18,18,18,18,18,16,15,12,11,12,11,13,11,15,
  129841. 14,
  129842. };
  129843. static float _vq_quantthresh__44c6_s_p8_0[] = {
  129844. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  129845. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  129846. };
  129847. static long _vq_quantmap__44c6_s_p8_0[] = {
  129848. 13, 11, 9, 7, 5, 3, 1, 0,
  129849. 2, 4, 6, 8, 10, 12, 14,
  129850. };
  129851. static encode_aux_threshmatch _vq_auxt__44c6_s_p8_0 = {
  129852. _vq_quantthresh__44c6_s_p8_0,
  129853. _vq_quantmap__44c6_s_p8_0,
  129854. 15,
  129855. 15
  129856. };
  129857. static static_codebook _44c6_s_p8_0 = {
  129858. 2, 225,
  129859. _vq_lengthlist__44c6_s_p8_0,
  129860. 1, -520986624, 1620377600, 4, 0,
  129861. _vq_quantlist__44c6_s_p8_0,
  129862. NULL,
  129863. &_vq_auxt__44c6_s_p8_0,
  129864. NULL,
  129865. 0
  129866. };
  129867. static long _vq_quantlist__44c6_s_p8_1[] = {
  129868. 10,
  129869. 9,
  129870. 11,
  129871. 8,
  129872. 12,
  129873. 7,
  129874. 13,
  129875. 6,
  129876. 14,
  129877. 5,
  129878. 15,
  129879. 4,
  129880. 16,
  129881. 3,
  129882. 17,
  129883. 2,
  129884. 18,
  129885. 1,
  129886. 19,
  129887. 0,
  129888. 20,
  129889. };
  129890. static long _vq_lengthlist__44c6_s_p8_1[] = {
  129891. 3, 5, 5, 6, 6, 7, 7, 7, 7, 8, 7, 8, 8, 8, 8, 8,
  129892. 8, 8, 8, 8, 8,10, 6, 6, 7, 7, 8, 8, 8, 8, 8, 8,
  129893. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 6, 6, 7, 7, 8,
  129894. 8, 8, 8, 8, 8, 9, 8, 9, 9, 9, 9, 9, 9, 9, 9,10,
  129895. 7, 7, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  129896. 9, 9, 9, 9,10,11,11, 8, 7, 8, 8, 8, 9, 9, 9, 9,
  129897. 9, 9, 9, 9, 9, 9, 9, 9, 9,11,11,11, 8, 8, 8, 8,
  129898. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,11,11,
  129899. 11, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  129900. 9, 9, 9,11,11,11, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  129901. 9, 9, 9, 9, 9, 9, 9, 9,11,11,11,11,11, 9, 9, 9,
  129902. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10, 9,11,11,11,
  129903. 11,11, 9, 9, 9, 9, 9, 9,10, 9, 9,10, 9,10, 9, 9,
  129904. 10, 9,11,11,11,11,11, 9, 9, 9, 9, 9, 9, 9,10,10,
  129905. 10,10, 9,10,10, 9,10,11,11,11,11,11, 9, 9, 9, 9,
  129906. 10,10,10, 9,10,10,10,10, 9,10,10, 9,11,11,11,11,
  129907. 11,11,11, 9, 9, 9, 9,10,10,10,10, 9,10,10,10,10,
  129908. 10,11,11,11,11,11,11,11,10, 9,10,10,10,10,10,10,
  129909. 10, 9,10, 9,10,10,11,11,11,11,11,11,11,10, 9,10,
  129910. 9,10,10, 9,10,10,10,10,10,10,10,11,11,11,11,11,
  129911. 11,11,10,10,10,10,10,10,10, 9,10,10,10,10,10, 9,
  129912. 11,11,11,11,11,11,11,11,11,10,10,10,10,10,10,10,
  129913. 10,10,10,10,10,11,11,11,11,11,11,11,11,11,10,10,
  129914. 10,10,10,10,10,10,10,10,10,10,11,11,11,11,11,11,
  129915. 11,11,11,10,10,10,10,10,10,10,10,10, 9,10,10,11,
  129916. 11,11,11,11,11,11,11,11,10,10,10, 9,10,10,10,10,
  129917. 10,10,10,10,10,11,11,11,11,11,11,11,11,10,11, 9,
  129918. 10,10,10,10,10,10,10,10,10,
  129919. };
  129920. static float _vq_quantthresh__44c6_s_p8_1[] = {
  129921. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  129922. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  129923. 6.5, 7.5, 8.5, 9.5,
  129924. };
  129925. static long _vq_quantmap__44c6_s_p8_1[] = {
  129926. 19, 17, 15, 13, 11, 9, 7, 5,
  129927. 3, 1, 0, 2, 4, 6, 8, 10,
  129928. 12, 14, 16, 18, 20,
  129929. };
  129930. static encode_aux_threshmatch _vq_auxt__44c6_s_p8_1 = {
  129931. _vq_quantthresh__44c6_s_p8_1,
  129932. _vq_quantmap__44c6_s_p8_1,
  129933. 21,
  129934. 21
  129935. };
  129936. static static_codebook _44c6_s_p8_1 = {
  129937. 2, 441,
  129938. _vq_lengthlist__44c6_s_p8_1,
  129939. 1, -529268736, 1611661312, 5, 0,
  129940. _vq_quantlist__44c6_s_p8_1,
  129941. NULL,
  129942. &_vq_auxt__44c6_s_p8_1,
  129943. NULL,
  129944. 0
  129945. };
  129946. static long _vq_quantlist__44c6_s_p9_0[] = {
  129947. 6,
  129948. 5,
  129949. 7,
  129950. 4,
  129951. 8,
  129952. 3,
  129953. 9,
  129954. 2,
  129955. 10,
  129956. 1,
  129957. 11,
  129958. 0,
  129959. 12,
  129960. };
  129961. static long _vq_lengthlist__44c6_s_p9_0[] = {
  129962. 1, 3, 3,11,11,11,11,11,11,11,11,11,11, 4, 7, 7,
  129963. 11,11,11,11,11,11,11,11,11,11, 5, 8, 9,11,11,11,
  129964. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  129965. 11,11,11,11,11,10,10,10,10,10,10,10,10,10,10,10,
  129966. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  129967. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  129968. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  129969. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  129970. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  129971. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  129972. 10,10,10,10,10,10,10,10,10,
  129973. };
  129974. static float _vq_quantthresh__44c6_s_p9_0[] = {
  129975. -3503.5, -2866.5, -2229.5, -1592.5, -955.5, -318.5, 318.5, 955.5,
  129976. 1592.5, 2229.5, 2866.5, 3503.5,
  129977. };
  129978. static long _vq_quantmap__44c6_s_p9_0[] = {
  129979. 11, 9, 7, 5, 3, 1, 0, 2,
  129980. 4, 6, 8, 10, 12,
  129981. };
  129982. static encode_aux_threshmatch _vq_auxt__44c6_s_p9_0 = {
  129983. _vq_quantthresh__44c6_s_p9_0,
  129984. _vq_quantmap__44c6_s_p9_0,
  129985. 13,
  129986. 13
  129987. };
  129988. static static_codebook _44c6_s_p9_0 = {
  129989. 2, 169,
  129990. _vq_lengthlist__44c6_s_p9_0,
  129991. 1, -511845376, 1630791680, 4, 0,
  129992. _vq_quantlist__44c6_s_p9_0,
  129993. NULL,
  129994. &_vq_auxt__44c6_s_p9_0,
  129995. NULL,
  129996. 0
  129997. };
  129998. static long _vq_quantlist__44c6_s_p9_1[] = {
  129999. 6,
  130000. 5,
  130001. 7,
  130002. 4,
  130003. 8,
  130004. 3,
  130005. 9,
  130006. 2,
  130007. 10,
  130008. 1,
  130009. 11,
  130010. 0,
  130011. 12,
  130012. };
  130013. static long _vq_lengthlist__44c6_s_p9_1[] = {
  130014. 1, 4, 4, 7, 7, 7, 7, 7, 6, 8, 8, 8, 8, 6, 6, 6,
  130015. 8, 8, 8, 8, 8, 7, 9, 8,10,10, 5, 6, 6, 8, 8, 9,
  130016. 9, 8, 8,10,10,10,10,16, 9, 9, 9, 9, 9, 9, 9, 8,
  130017. 10, 9,11,11,16, 8, 9, 9, 9, 9, 9, 9, 9,10,10,11,
  130018. 11,16,13,13, 9, 9,10, 9, 9,10,11,11,11,12,16,13,
  130019. 14, 9, 8,10, 8, 9, 9,10,10,12,11,16,14,16, 9, 9,
  130020. 9, 9,11,11,12,11,12,11,16,16,16, 9, 7, 9, 6,11,
  130021. 11,11,10,11,11,16,16,16,11,12, 9,10,11,11,12,11,
  130022. 13,13,16,16,16,12,11,10, 7,12,10,12,12,12,12,16,
  130023. 16,15,16,16,10,11,10,11,13,13,14,12,16,16,16,15,
  130024. 15,12,10,11,11,13,11,12,13,
  130025. };
  130026. static float _vq_quantthresh__44c6_s_p9_1[] = {
  130027. -269.5, -220.5, -171.5, -122.5, -73.5, -24.5, 24.5, 73.5,
  130028. 122.5, 171.5, 220.5, 269.5,
  130029. };
  130030. static long _vq_quantmap__44c6_s_p9_1[] = {
  130031. 11, 9, 7, 5, 3, 1, 0, 2,
  130032. 4, 6, 8, 10, 12,
  130033. };
  130034. static encode_aux_threshmatch _vq_auxt__44c6_s_p9_1 = {
  130035. _vq_quantthresh__44c6_s_p9_1,
  130036. _vq_quantmap__44c6_s_p9_1,
  130037. 13,
  130038. 13
  130039. };
  130040. static static_codebook _44c6_s_p9_1 = {
  130041. 2, 169,
  130042. _vq_lengthlist__44c6_s_p9_1,
  130043. 1, -518889472, 1622704128, 4, 0,
  130044. _vq_quantlist__44c6_s_p9_1,
  130045. NULL,
  130046. &_vq_auxt__44c6_s_p9_1,
  130047. NULL,
  130048. 0
  130049. };
  130050. static long _vq_quantlist__44c6_s_p9_2[] = {
  130051. 24,
  130052. 23,
  130053. 25,
  130054. 22,
  130055. 26,
  130056. 21,
  130057. 27,
  130058. 20,
  130059. 28,
  130060. 19,
  130061. 29,
  130062. 18,
  130063. 30,
  130064. 17,
  130065. 31,
  130066. 16,
  130067. 32,
  130068. 15,
  130069. 33,
  130070. 14,
  130071. 34,
  130072. 13,
  130073. 35,
  130074. 12,
  130075. 36,
  130076. 11,
  130077. 37,
  130078. 10,
  130079. 38,
  130080. 9,
  130081. 39,
  130082. 8,
  130083. 40,
  130084. 7,
  130085. 41,
  130086. 6,
  130087. 42,
  130088. 5,
  130089. 43,
  130090. 4,
  130091. 44,
  130092. 3,
  130093. 45,
  130094. 2,
  130095. 46,
  130096. 1,
  130097. 47,
  130098. 0,
  130099. 48,
  130100. };
  130101. static long _vq_lengthlist__44c6_s_p9_2[] = {
  130102. 2, 4, 3, 4, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6, 6, 6,
  130103. 6, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  130104. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  130105. 7,
  130106. };
  130107. static float _vq_quantthresh__44c6_s_p9_2[] = {
  130108. -23.5, -22.5, -21.5, -20.5, -19.5, -18.5, -17.5, -16.5,
  130109. -15.5, -14.5, -13.5, -12.5, -11.5, -10.5, -9.5, -8.5,
  130110. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  130111. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  130112. 8.5, 9.5, 10.5, 11.5, 12.5, 13.5, 14.5, 15.5,
  130113. 16.5, 17.5, 18.5, 19.5, 20.5, 21.5, 22.5, 23.5,
  130114. };
  130115. static long _vq_quantmap__44c6_s_p9_2[] = {
  130116. 47, 45, 43, 41, 39, 37, 35, 33,
  130117. 31, 29, 27, 25, 23, 21, 19, 17,
  130118. 15, 13, 11, 9, 7, 5, 3, 1,
  130119. 0, 2, 4, 6, 8, 10, 12, 14,
  130120. 16, 18, 20, 22, 24, 26, 28, 30,
  130121. 32, 34, 36, 38, 40, 42, 44, 46,
  130122. 48,
  130123. };
  130124. static encode_aux_threshmatch _vq_auxt__44c6_s_p9_2 = {
  130125. _vq_quantthresh__44c6_s_p9_2,
  130126. _vq_quantmap__44c6_s_p9_2,
  130127. 49,
  130128. 49
  130129. };
  130130. static static_codebook _44c6_s_p9_2 = {
  130131. 1, 49,
  130132. _vq_lengthlist__44c6_s_p9_2,
  130133. 1, -526909440, 1611661312, 6, 0,
  130134. _vq_quantlist__44c6_s_p9_2,
  130135. NULL,
  130136. &_vq_auxt__44c6_s_p9_2,
  130137. NULL,
  130138. 0
  130139. };
  130140. static long _huff_lengthlist__44c6_s_short[] = {
  130141. 3, 9,11,11,13,14,19,17,17,19, 5, 4, 5, 8,10,10,
  130142. 13,16,18,19, 7, 4, 4, 5, 8, 9,12,14,17,19, 8, 6,
  130143. 5, 5, 7, 7,10,13,16,18,10, 8, 7, 6, 5, 5, 8,11,
  130144. 17,19,11, 9, 7, 7, 5, 4, 5, 8,17,19,13,11, 8, 7,
  130145. 7, 5, 5, 7,16,18,14,13, 8, 6, 6, 5, 5, 7,16,18,
  130146. 18,16,10, 8, 8, 7, 7, 9,16,18,18,18,12,10,10, 9,
  130147. 9,10,17,18,
  130148. };
  130149. static static_codebook _huff_book__44c6_s_short = {
  130150. 2, 100,
  130151. _huff_lengthlist__44c6_s_short,
  130152. 0, 0, 0, 0, 0,
  130153. NULL,
  130154. NULL,
  130155. NULL,
  130156. NULL,
  130157. 0
  130158. };
  130159. static long _huff_lengthlist__44c7_s_long[] = {
  130160. 3, 8,11,13,15,14,14,13,15,14, 6, 4, 5, 7, 9,10,
  130161. 11,11,14,13,10, 4, 3, 5, 7, 8, 9,10,13,13,12, 7,
  130162. 4, 4, 5, 6, 8, 9,12,14,13, 9, 6, 5, 5, 6, 8, 9,
  130163. 12,14,12, 9, 7, 6, 5, 5, 6, 8,11,11,12,11, 9, 8,
  130164. 7, 6, 6, 7,10,11,13,11,10, 9, 8, 7, 6, 6, 9,11,
  130165. 13,13,12,12,12,10, 9, 8, 9,11,12,14,15,15,14,12,
  130166. 11,10,10,12,
  130167. };
  130168. static static_codebook _huff_book__44c7_s_long = {
  130169. 2, 100,
  130170. _huff_lengthlist__44c7_s_long,
  130171. 0, 0, 0, 0, 0,
  130172. NULL,
  130173. NULL,
  130174. NULL,
  130175. NULL,
  130176. 0
  130177. };
  130178. static long _vq_quantlist__44c7_s_p1_0[] = {
  130179. 1,
  130180. 0,
  130181. 2,
  130182. };
  130183. static long _vq_lengthlist__44c7_s_p1_0[] = {
  130184. 1, 5, 5, 0, 5, 5, 0, 5, 5, 5, 8, 7, 0, 9, 9, 0,
  130185. 9, 8, 5, 7, 8, 0, 9, 9, 0, 8, 9, 0, 0, 0, 0, 0,
  130186. 0, 0, 0, 0, 5, 9, 9, 0, 8, 8, 0, 8, 8, 5, 8, 9,
  130187. 0, 8, 8, 0, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5,
  130188. 9, 9, 0, 8, 8, 0, 8, 8, 5, 8, 9, 0, 8, 8, 0, 8,
  130189. 8,
  130190. };
  130191. static float _vq_quantthresh__44c7_s_p1_0[] = {
  130192. -0.5, 0.5,
  130193. };
  130194. static long _vq_quantmap__44c7_s_p1_0[] = {
  130195. 1, 0, 2,
  130196. };
  130197. static encode_aux_threshmatch _vq_auxt__44c7_s_p1_0 = {
  130198. _vq_quantthresh__44c7_s_p1_0,
  130199. _vq_quantmap__44c7_s_p1_0,
  130200. 3,
  130201. 3
  130202. };
  130203. static static_codebook _44c7_s_p1_0 = {
  130204. 4, 81,
  130205. _vq_lengthlist__44c7_s_p1_0,
  130206. 1, -535822336, 1611661312, 2, 0,
  130207. _vq_quantlist__44c7_s_p1_0,
  130208. NULL,
  130209. &_vq_auxt__44c7_s_p1_0,
  130210. NULL,
  130211. 0
  130212. };
  130213. static long _vq_quantlist__44c7_s_p2_0[] = {
  130214. 2,
  130215. 1,
  130216. 3,
  130217. 0,
  130218. 4,
  130219. };
  130220. static long _vq_lengthlist__44c7_s_p2_0[] = {
  130221. 3, 5, 5, 8, 8, 0, 5, 5, 8, 8, 0, 5, 5, 8, 8, 0,
  130222. 7, 7, 9, 9, 0, 0, 0, 9, 9, 5, 7, 7, 9, 9, 0, 8,
  130223. 8,10,10, 0, 8, 7,10, 9, 0,10,10,11,11, 0, 0, 0,
  130224. 11,11, 5, 7, 7, 9, 9, 0, 8, 8,10,10, 0, 7, 8, 9,
  130225. 10, 0,10,10,11,11, 0, 0, 0,11,11, 8, 9, 9,11,10,
  130226. 0,11,11,12,12, 0,11,10,12,12, 0,13,14,14,14, 0,
  130227. 0, 0,14,13, 8, 9, 9,10,11, 0,11,11,12,12, 0,10,
  130228. 11,12,12, 0,13,13,14,14, 0, 0, 0,13,14, 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, 5, 8, 7,11,10, 0, 7, 7,10,10,
  130231. 0, 7, 7,10,10, 0, 9, 9,11,10, 0, 0, 0,11,11, 5,
  130232. 7, 8,10,11, 0, 7, 7,10,10, 0, 7, 7,10,10, 0, 9,
  130233. 9,10,11, 0, 0, 0,11,11, 8,10, 9,12,12, 0,10,10,
  130234. 12,12, 0,10,10,12,12, 0,12,12,13,13, 0, 0, 0,13,
  130235. 13, 8, 9,10,12,12, 0,10,10,12,12, 0,10,10,11,12,
  130236. 0,12,12,13,13, 0, 0, 0,13,13, 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, 5, 8, 8,11,11, 0, 7, 7,10,10, 0, 7, 7,
  130239. 10,10, 0, 9, 9,10,11, 0, 0, 0,11,10, 5, 8, 8,10,
  130240. 11, 0, 7, 7,10,10, 0, 7, 7,10,10, 0, 9, 9,11,10,
  130241. 0, 0, 0,10,11, 9,10,10,12,12, 0,10,10,12,12, 0,
  130242. 10,10,12,12, 0,12,13,13,13, 0, 0, 0,13,12, 9,10,
  130243. 10,12,12, 0,10,10,12,12, 0,10,10,12,12, 0,13,12,
  130244. 13,13, 0, 0, 0,12,13, 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. 7,10,10,14,13, 0, 9, 9,12,12, 0, 9, 9,12,12, 0,
  130247. 10,10,12,12, 0, 0, 0,12,12, 7,10,10,13,14, 0, 9,
  130248. 9,12,13, 0, 9, 9,12,12, 0,10,10,12,12, 0, 0, 0,
  130249. 12,12, 9,11,11,14,13, 0,11,10,13,12, 0,11,11,13,
  130250. 13, 0,12,12,13,13, 0, 0, 0,13,13, 9,11,11,13,14,
  130251. 0,10,11,12,13, 0,11,11,13,13, 0,12,12,13,13, 0,
  130252. 0, 0,13,13, 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, 9,
  130257. 11,11,14,14, 0,10,11,13,13, 0,11,10,13,13, 0,12,
  130258. 12,13,13, 0, 0, 0,13,12, 9,11,11,14,14, 0,11,10,
  130259. 13,13, 0,10,11,13,13, 0,12,12,14,13, 0, 0, 0,13,
  130260. 13,
  130261. };
  130262. static float _vq_quantthresh__44c7_s_p2_0[] = {
  130263. -1.5, -0.5, 0.5, 1.5,
  130264. };
  130265. static long _vq_quantmap__44c7_s_p2_0[] = {
  130266. 3, 1, 0, 2, 4,
  130267. };
  130268. static encode_aux_threshmatch _vq_auxt__44c7_s_p2_0 = {
  130269. _vq_quantthresh__44c7_s_p2_0,
  130270. _vq_quantmap__44c7_s_p2_0,
  130271. 5,
  130272. 5
  130273. };
  130274. static static_codebook _44c7_s_p2_0 = {
  130275. 4, 625,
  130276. _vq_lengthlist__44c7_s_p2_0,
  130277. 1, -533725184, 1611661312, 3, 0,
  130278. _vq_quantlist__44c7_s_p2_0,
  130279. NULL,
  130280. &_vq_auxt__44c7_s_p2_0,
  130281. NULL,
  130282. 0
  130283. };
  130284. static long _vq_quantlist__44c7_s_p3_0[] = {
  130285. 4,
  130286. 3,
  130287. 5,
  130288. 2,
  130289. 6,
  130290. 1,
  130291. 7,
  130292. 0,
  130293. 8,
  130294. };
  130295. static long _vq_lengthlist__44c7_s_p3_0[] = {
  130296. 2, 4, 4, 5, 5, 7, 7, 9, 9, 0, 4, 4, 6, 6, 7, 7,
  130297. 9, 9, 0, 4, 4, 6, 6, 7, 7, 9, 9, 0, 5, 5, 6, 6,
  130298. 8, 8,10,10, 0, 0, 0, 6, 6, 8, 8,10,10, 0, 0, 0,
  130299. 7, 7, 9, 9,10,10, 0, 0, 0, 7, 7, 8, 8,10,10, 0,
  130300. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130301. 0,
  130302. };
  130303. static float _vq_quantthresh__44c7_s_p3_0[] = {
  130304. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  130305. };
  130306. static long _vq_quantmap__44c7_s_p3_0[] = {
  130307. 7, 5, 3, 1, 0, 2, 4, 6,
  130308. 8,
  130309. };
  130310. static encode_aux_threshmatch _vq_auxt__44c7_s_p3_0 = {
  130311. _vq_quantthresh__44c7_s_p3_0,
  130312. _vq_quantmap__44c7_s_p3_0,
  130313. 9,
  130314. 9
  130315. };
  130316. static static_codebook _44c7_s_p3_0 = {
  130317. 2, 81,
  130318. _vq_lengthlist__44c7_s_p3_0,
  130319. 1, -531628032, 1611661312, 4, 0,
  130320. _vq_quantlist__44c7_s_p3_0,
  130321. NULL,
  130322. &_vq_auxt__44c7_s_p3_0,
  130323. NULL,
  130324. 0
  130325. };
  130326. static long _vq_quantlist__44c7_s_p4_0[] = {
  130327. 8,
  130328. 7,
  130329. 9,
  130330. 6,
  130331. 10,
  130332. 5,
  130333. 11,
  130334. 4,
  130335. 12,
  130336. 3,
  130337. 13,
  130338. 2,
  130339. 14,
  130340. 1,
  130341. 15,
  130342. 0,
  130343. 16,
  130344. };
  130345. static long _vq_lengthlist__44c7_s_p4_0[] = {
  130346. 3, 4, 4, 5, 5, 7, 7, 8, 8, 8, 8, 9, 9,10,10,11,
  130347. 11, 0, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10,11,11,
  130348. 12,12, 0, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10,11,
  130349. 11,12,12, 0, 5, 5, 6, 6, 8, 8, 9, 9, 9, 9,10,10,
  130350. 11,12,12,12, 0, 0, 0, 6, 6, 8, 7, 9, 9, 9, 9,10,
  130351. 10,11,11,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9,10,10,
  130352. 11,11,12,12,13,12, 0, 0, 0, 7, 7, 8, 8, 9, 9,10,
  130353. 10,11,11,12,12,12,13, 0, 0, 0, 7, 7, 8, 8, 9, 9,
  130354. 10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 8, 8, 9,
  130355. 9,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 0, 0,
  130356. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130357. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130358. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130359. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130360. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130361. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130362. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130363. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130364. 0,
  130365. };
  130366. static float _vq_quantthresh__44c7_s_p4_0[] = {
  130367. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  130368. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  130369. };
  130370. static long _vq_quantmap__44c7_s_p4_0[] = {
  130371. 15, 13, 11, 9, 7, 5, 3, 1,
  130372. 0, 2, 4, 6, 8, 10, 12, 14,
  130373. 16,
  130374. };
  130375. static encode_aux_threshmatch _vq_auxt__44c7_s_p4_0 = {
  130376. _vq_quantthresh__44c7_s_p4_0,
  130377. _vq_quantmap__44c7_s_p4_0,
  130378. 17,
  130379. 17
  130380. };
  130381. static static_codebook _44c7_s_p4_0 = {
  130382. 2, 289,
  130383. _vq_lengthlist__44c7_s_p4_0,
  130384. 1, -529530880, 1611661312, 5, 0,
  130385. _vq_quantlist__44c7_s_p4_0,
  130386. NULL,
  130387. &_vq_auxt__44c7_s_p4_0,
  130388. NULL,
  130389. 0
  130390. };
  130391. static long _vq_quantlist__44c7_s_p5_0[] = {
  130392. 1,
  130393. 0,
  130394. 2,
  130395. };
  130396. static long _vq_lengthlist__44c7_s_p5_0[] = {
  130397. 1, 4, 4, 5, 7, 7, 6, 7, 7, 4, 6, 7,10,10,10,10,
  130398. 10, 9, 4, 6, 6,10,10,10,10, 9,10, 5,10,10, 9,11,
  130399. 12,10,11,12, 7,10,10,11,12,12,12,12,12, 7,10,10,
  130400. 11,12,12,12,12,12, 6,10,10,10,12,12,11,12,12, 7,
  130401. 10,10,12,12,12,12,11,12, 7,10,10,11,12,12,12,12,
  130402. 12,
  130403. };
  130404. static float _vq_quantthresh__44c7_s_p5_0[] = {
  130405. -5.5, 5.5,
  130406. };
  130407. static long _vq_quantmap__44c7_s_p5_0[] = {
  130408. 1, 0, 2,
  130409. };
  130410. static encode_aux_threshmatch _vq_auxt__44c7_s_p5_0 = {
  130411. _vq_quantthresh__44c7_s_p5_0,
  130412. _vq_quantmap__44c7_s_p5_0,
  130413. 3,
  130414. 3
  130415. };
  130416. static static_codebook _44c7_s_p5_0 = {
  130417. 4, 81,
  130418. _vq_lengthlist__44c7_s_p5_0,
  130419. 1, -529137664, 1618345984, 2, 0,
  130420. _vq_quantlist__44c7_s_p5_0,
  130421. NULL,
  130422. &_vq_auxt__44c7_s_p5_0,
  130423. NULL,
  130424. 0
  130425. };
  130426. static long _vq_quantlist__44c7_s_p5_1[] = {
  130427. 5,
  130428. 4,
  130429. 6,
  130430. 3,
  130431. 7,
  130432. 2,
  130433. 8,
  130434. 1,
  130435. 9,
  130436. 0,
  130437. 10,
  130438. };
  130439. static long _vq_lengthlist__44c7_s_p5_1[] = {
  130440. 3, 5, 5, 6, 6, 7, 7, 8, 8, 8, 8,11, 4, 4, 6, 6,
  130441. 7, 7, 8, 8, 9, 9,11, 4, 4, 6, 6, 7, 7, 8, 8, 9,
  130442. 9,12, 5, 5, 6, 6, 7, 7, 9, 9, 9, 9,12,12,12, 6,
  130443. 6, 7, 7, 9, 9, 9, 9,11,11,11, 7, 7, 7, 7, 8, 8,
  130444. 9, 9,11,11,11, 7, 7, 7, 7, 8, 8, 9, 9,11,11,11,
  130445. 7, 7, 8, 8, 8, 8, 9, 9,11,11,11,11,11, 8, 8, 8,
  130446. 8, 8, 9,11,11,11,11,11, 8, 8, 8, 8, 8, 8,11,11,
  130447. 11,11,11, 7, 7, 8, 8, 8, 8,
  130448. };
  130449. static float _vq_quantthresh__44c7_s_p5_1[] = {
  130450. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  130451. 3.5, 4.5,
  130452. };
  130453. static long _vq_quantmap__44c7_s_p5_1[] = {
  130454. 9, 7, 5, 3, 1, 0, 2, 4,
  130455. 6, 8, 10,
  130456. };
  130457. static encode_aux_threshmatch _vq_auxt__44c7_s_p5_1 = {
  130458. _vq_quantthresh__44c7_s_p5_1,
  130459. _vq_quantmap__44c7_s_p5_1,
  130460. 11,
  130461. 11
  130462. };
  130463. static static_codebook _44c7_s_p5_1 = {
  130464. 2, 121,
  130465. _vq_lengthlist__44c7_s_p5_1,
  130466. 1, -531365888, 1611661312, 4, 0,
  130467. _vq_quantlist__44c7_s_p5_1,
  130468. NULL,
  130469. &_vq_auxt__44c7_s_p5_1,
  130470. NULL,
  130471. 0
  130472. };
  130473. static long _vq_quantlist__44c7_s_p6_0[] = {
  130474. 6,
  130475. 5,
  130476. 7,
  130477. 4,
  130478. 8,
  130479. 3,
  130480. 9,
  130481. 2,
  130482. 10,
  130483. 1,
  130484. 11,
  130485. 0,
  130486. 12,
  130487. };
  130488. static long _vq_lengthlist__44c7_s_p6_0[] = {
  130489. 1, 4, 4, 6, 6, 7, 7, 8, 7, 9, 8,10,10, 6, 5, 5,
  130490. 7, 7, 8, 8, 9, 9, 9,10,11,11, 7, 5, 5, 7, 7, 8,
  130491. 8, 9, 9,10,10,11,11, 0, 7, 7, 7, 7, 9, 8, 9, 9,
  130492. 10,10,11,11, 0, 8, 8, 7, 7, 8, 9, 9, 9,10,10,11,
  130493. 11, 0,11,11, 9, 9,10,10,11,10,11,11,12,12, 0,12,
  130494. 12, 9, 9,10,10,11,11,11,11,12,12, 0, 0, 0, 0, 0,
  130495. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130496. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130497. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130498. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130499. 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130500. };
  130501. static float _vq_quantthresh__44c7_s_p6_0[] = {
  130502. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  130503. 12.5, 17.5, 22.5, 27.5,
  130504. };
  130505. static long _vq_quantmap__44c7_s_p6_0[] = {
  130506. 11, 9, 7, 5, 3, 1, 0, 2,
  130507. 4, 6, 8, 10, 12,
  130508. };
  130509. static encode_aux_threshmatch _vq_auxt__44c7_s_p6_0 = {
  130510. _vq_quantthresh__44c7_s_p6_0,
  130511. _vq_quantmap__44c7_s_p6_0,
  130512. 13,
  130513. 13
  130514. };
  130515. static static_codebook _44c7_s_p6_0 = {
  130516. 2, 169,
  130517. _vq_lengthlist__44c7_s_p6_0,
  130518. 1, -526516224, 1616117760, 4, 0,
  130519. _vq_quantlist__44c7_s_p6_0,
  130520. NULL,
  130521. &_vq_auxt__44c7_s_p6_0,
  130522. NULL,
  130523. 0
  130524. };
  130525. static long _vq_quantlist__44c7_s_p6_1[] = {
  130526. 2,
  130527. 1,
  130528. 3,
  130529. 0,
  130530. 4,
  130531. };
  130532. static long _vq_lengthlist__44c7_s_p6_1[] = {
  130533. 3, 4, 4, 5, 5, 5, 4, 4, 5, 5, 5, 4, 4, 5, 5, 6,
  130534. 5, 5, 5, 5, 6, 6, 6, 5, 5,
  130535. };
  130536. static float _vq_quantthresh__44c7_s_p6_1[] = {
  130537. -1.5, -0.5, 0.5, 1.5,
  130538. };
  130539. static long _vq_quantmap__44c7_s_p6_1[] = {
  130540. 3, 1, 0, 2, 4,
  130541. };
  130542. static encode_aux_threshmatch _vq_auxt__44c7_s_p6_1 = {
  130543. _vq_quantthresh__44c7_s_p6_1,
  130544. _vq_quantmap__44c7_s_p6_1,
  130545. 5,
  130546. 5
  130547. };
  130548. static static_codebook _44c7_s_p6_1 = {
  130549. 2, 25,
  130550. _vq_lengthlist__44c7_s_p6_1,
  130551. 1, -533725184, 1611661312, 3, 0,
  130552. _vq_quantlist__44c7_s_p6_1,
  130553. NULL,
  130554. &_vq_auxt__44c7_s_p6_1,
  130555. NULL,
  130556. 0
  130557. };
  130558. static long _vq_quantlist__44c7_s_p7_0[] = {
  130559. 6,
  130560. 5,
  130561. 7,
  130562. 4,
  130563. 8,
  130564. 3,
  130565. 9,
  130566. 2,
  130567. 10,
  130568. 1,
  130569. 11,
  130570. 0,
  130571. 12,
  130572. };
  130573. static long _vq_lengthlist__44c7_s_p7_0[] = {
  130574. 1, 4, 4, 6, 6, 7, 8, 9, 9,10,10,12,11, 6, 5, 5,
  130575. 7, 7, 8, 8, 9,10,11,11,12,12, 7, 5, 5, 7, 7, 8,
  130576. 8,10,10,11,11,12,12,20, 7, 7, 7, 7, 8, 9,10,10,
  130577. 11,11,12,13,20, 7, 7, 7, 7, 9, 9,10,10,11,12,13,
  130578. 13,20,11,11, 8, 8, 9, 9,11,11,12,12,13,13,20,11,
  130579. 11, 8, 8, 9, 9,11,11,12,12,13,13,20,20,20,10,10,
  130580. 10,10,12,12,13,13,13,13,20,20,20,10,10,10,10,12,
  130581. 12,13,13,13,14,20,20,20,14,14,11,11,12,12,13,13,
  130582. 14,14,20,20,20,14,14,11,11,12,12,13,13,14,14,20,
  130583. 20,20,20,19,13,13,13,13,14,14,15,14,19,19,19,19,
  130584. 19,13,13,13,13,14,14,15,15,
  130585. };
  130586. static float _vq_quantthresh__44c7_s_p7_0[] = {
  130587. -60.5, -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5,
  130588. 27.5, 38.5, 49.5, 60.5,
  130589. };
  130590. static long _vq_quantmap__44c7_s_p7_0[] = {
  130591. 11, 9, 7, 5, 3, 1, 0, 2,
  130592. 4, 6, 8, 10, 12,
  130593. };
  130594. static encode_aux_threshmatch _vq_auxt__44c7_s_p7_0 = {
  130595. _vq_quantthresh__44c7_s_p7_0,
  130596. _vq_quantmap__44c7_s_p7_0,
  130597. 13,
  130598. 13
  130599. };
  130600. static static_codebook _44c7_s_p7_0 = {
  130601. 2, 169,
  130602. _vq_lengthlist__44c7_s_p7_0,
  130603. 1, -523206656, 1618345984, 4, 0,
  130604. _vq_quantlist__44c7_s_p7_0,
  130605. NULL,
  130606. &_vq_auxt__44c7_s_p7_0,
  130607. NULL,
  130608. 0
  130609. };
  130610. static long _vq_quantlist__44c7_s_p7_1[] = {
  130611. 5,
  130612. 4,
  130613. 6,
  130614. 3,
  130615. 7,
  130616. 2,
  130617. 8,
  130618. 1,
  130619. 9,
  130620. 0,
  130621. 10,
  130622. };
  130623. static long _vq_lengthlist__44c7_s_p7_1[] = {
  130624. 4, 5, 5, 6, 6, 7, 7, 7, 7, 7, 7, 8, 6, 6, 7, 7,
  130625. 7, 7, 7, 7, 7, 7, 8, 6, 6, 6, 7, 7, 7, 7, 7, 7,
  130626. 7, 8, 6, 6, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 7,
  130627. 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 7, 7, 7, 7, 7, 7,
  130628. 7, 7, 8, 8, 8, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8,
  130629. 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8, 7, 7, 7,
  130630. 7, 7, 7, 8, 8, 8, 8, 8, 7, 7, 7, 7, 7, 7, 8, 8,
  130631. 8, 8, 8, 7, 7, 7, 7, 7, 7,
  130632. };
  130633. static float _vq_quantthresh__44c7_s_p7_1[] = {
  130634. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  130635. 3.5, 4.5,
  130636. };
  130637. static long _vq_quantmap__44c7_s_p7_1[] = {
  130638. 9, 7, 5, 3, 1, 0, 2, 4,
  130639. 6, 8, 10,
  130640. };
  130641. static encode_aux_threshmatch _vq_auxt__44c7_s_p7_1 = {
  130642. _vq_quantthresh__44c7_s_p7_1,
  130643. _vq_quantmap__44c7_s_p7_1,
  130644. 11,
  130645. 11
  130646. };
  130647. static static_codebook _44c7_s_p7_1 = {
  130648. 2, 121,
  130649. _vq_lengthlist__44c7_s_p7_1,
  130650. 1, -531365888, 1611661312, 4, 0,
  130651. _vq_quantlist__44c7_s_p7_1,
  130652. NULL,
  130653. &_vq_auxt__44c7_s_p7_1,
  130654. NULL,
  130655. 0
  130656. };
  130657. static long _vq_quantlist__44c7_s_p8_0[] = {
  130658. 7,
  130659. 6,
  130660. 8,
  130661. 5,
  130662. 9,
  130663. 4,
  130664. 10,
  130665. 3,
  130666. 11,
  130667. 2,
  130668. 12,
  130669. 1,
  130670. 13,
  130671. 0,
  130672. 14,
  130673. };
  130674. static long _vq_lengthlist__44c7_s_p8_0[] = {
  130675. 1, 4, 4, 7, 7, 8, 8, 8, 7, 9, 8, 9, 9,10,10, 6,
  130676. 5, 5, 7, 7, 9, 9, 8, 8,10, 9,11,10,12,11, 6, 5,
  130677. 5, 8, 7, 9, 9, 8, 8,10,10,11,11,12,11,19, 8, 8,
  130678. 8, 8,10,10, 9, 9,10,10,11,11,12,11,19, 8, 8, 8,
  130679. 8,10,10, 9, 9,10,10,11,11,12,12,19,12,12, 9, 9,
  130680. 10,10, 9,10,10,10,11,11,12,12,19,12,12, 9, 9,10,
  130681. 10,10,10,10,10,12,12,12,12,19,19,19, 9, 9, 9, 9,
  130682. 11,10,11,11,12,11,13,13,19,19,19, 9, 9, 9, 9,11,
  130683. 10,11,11,11,12,13,13,19,19,19,13,13,10,10,11,11,
  130684. 12,12,12,12,13,12,19,19,19,14,13,10,10,11,11,12,
  130685. 12,12,13,13,13,19,19,19,19,19,12,12,12,11,12,13,
  130686. 14,13,13,13,19,19,19,19,19,12,12,12,11,12,12,13,
  130687. 14,13,14,19,19,19,19,19,16,16,12,13,12,13,13,14,
  130688. 15,14,19,18,18,18,18,16,15,12,11,12,11,14,12,14,
  130689. 14,
  130690. };
  130691. static float _vq_quantthresh__44c7_s_p8_0[] = {
  130692. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  130693. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  130694. };
  130695. static long _vq_quantmap__44c7_s_p8_0[] = {
  130696. 13, 11, 9, 7, 5, 3, 1, 0,
  130697. 2, 4, 6, 8, 10, 12, 14,
  130698. };
  130699. static encode_aux_threshmatch _vq_auxt__44c7_s_p8_0 = {
  130700. _vq_quantthresh__44c7_s_p8_0,
  130701. _vq_quantmap__44c7_s_p8_0,
  130702. 15,
  130703. 15
  130704. };
  130705. static static_codebook _44c7_s_p8_0 = {
  130706. 2, 225,
  130707. _vq_lengthlist__44c7_s_p8_0,
  130708. 1, -520986624, 1620377600, 4, 0,
  130709. _vq_quantlist__44c7_s_p8_0,
  130710. NULL,
  130711. &_vq_auxt__44c7_s_p8_0,
  130712. NULL,
  130713. 0
  130714. };
  130715. static long _vq_quantlist__44c7_s_p8_1[] = {
  130716. 10,
  130717. 9,
  130718. 11,
  130719. 8,
  130720. 12,
  130721. 7,
  130722. 13,
  130723. 6,
  130724. 14,
  130725. 5,
  130726. 15,
  130727. 4,
  130728. 16,
  130729. 3,
  130730. 17,
  130731. 2,
  130732. 18,
  130733. 1,
  130734. 19,
  130735. 0,
  130736. 20,
  130737. };
  130738. static long _vq_lengthlist__44c7_s_p8_1[] = {
  130739. 3, 5, 5, 7, 6, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  130740. 8, 8, 8, 8, 8,10, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,
  130741. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 6, 6, 7, 7, 8,
  130742. 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,
  130743. 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  130744. 9, 9, 9, 9,10,10,10, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  130745. 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10,10, 8, 8, 8, 9,
  130746. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10,
  130747. 10, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  130748. 9, 9, 9,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  130749. 9, 9, 9, 9, 9, 9, 9, 9,10,11,10,10,10, 9, 9, 9,
  130750. 9, 9, 9, 9, 9, 9, 9,10, 9, 9,10, 9, 9,10,11,10,
  130751. 11,10, 9, 9, 9, 9, 9, 9, 9,10,10,10, 9,10, 9, 9,
  130752. 9, 9,11,10,11,10,10, 9, 9, 9, 9, 9, 9,10, 9, 9,
  130753. 10, 9, 9,10, 9, 9,10,11,10,10,11,10, 9, 9, 9, 9,
  130754. 9,10,10, 9,10,10,10,10, 9,10,10,10,10,10,10,11,
  130755. 11,11,10, 9, 9, 9,10,10,10,10,10,10,10,10,10,10,
  130756. 10,10,10,11,11,10,10,10,10,10,10,10,10,10,10,10,
  130757. 10, 9,10,10, 9,10,11,11,10,11,10,11,10, 9,10,10,
  130758. 9,10,10,10,10,10,10,10,10,10,10,11,11,11,11,10,
  130759. 11,11,10,10,10,10,10,10, 9,10, 9,10,10, 9,10, 9,
  130760. 10,10,10,11,10,11,10,11,11,10,10,10,10,10,10, 9,
  130761. 10,10,10,10,10,10,10,11,10,10,10,10,10,10,10,10,
  130762. 10,10,10,10,10,10,10,10,10,10,10,10,10,11,10,11,
  130763. 11,10,10,10,10, 9, 9,10,10, 9, 9,10, 9,10,10,10,
  130764. 10,11,11,10,10,10,10,10,10,10, 9, 9,10,10,10, 9,
  130765. 9,10,10,10,10,10,11,10,11,10,10,10,10,10,10, 9,
  130766. 10,10,10,10,10,10,10,10,10,
  130767. };
  130768. static float _vq_quantthresh__44c7_s_p8_1[] = {
  130769. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  130770. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  130771. 6.5, 7.5, 8.5, 9.5,
  130772. };
  130773. static long _vq_quantmap__44c7_s_p8_1[] = {
  130774. 19, 17, 15, 13, 11, 9, 7, 5,
  130775. 3, 1, 0, 2, 4, 6, 8, 10,
  130776. 12, 14, 16, 18, 20,
  130777. };
  130778. static encode_aux_threshmatch _vq_auxt__44c7_s_p8_1 = {
  130779. _vq_quantthresh__44c7_s_p8_1,
  130780. _vq_quantmap__44c7_s_p8_1,
  130781. 21,
  130782. 21
  130783. };
  130784. static static_codebook _44c7_s_p8_1 = {
  130785. 2, 441,
  130786. _vq_lengthlist__44c7_s_p8_1,
  130787. 1, -529268736, 1611661312, 5, 0,
  130788. _vq_quantlist__44c7_s_p8_1,
  130789. NULL,
  130790. &_vq_auxt__44c7_s_p8_1,
  130791. NULL,
  130792. 0
  130793. };
  130794. static long _vq_quantlist__44c7_s_p9_0[] = {
  130795. 6,
  130796. 5,
  130797. 7,
  130798. 4,
  130799. 8,
  130800. 3,
  130801. 9,
  130802. 2,
  130803. 10,
  130804. 1,
  130805. 11,
  130806. 0,
  130807. 12,
  130808. };
  130809. static long _vq_lengthlist__44c7_s_p9_0[] = {
  130810. 1, 3, 3,11,11,11,11,11,11,11,11,11,11, 4, 6, 6,
  130811. 11,11,11,11,11,11,11,11,11,11, 4, 7, 7,11,11,11,
  130812. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  130813. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  130814. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  130815. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  130816. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  130817. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  130818. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  130819. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  130820. 11,11,11,11,11,11,11,11,11,
  130821. };
  130822. static float _vq_quantthresh__44c7_s_p9_0[] = {
  130823. -3503.5, -2866.5, -2229.5, -1592.5, -955.5, -318.5, 318.5, 955.5,
  130824. 1592.5, 2229.5, 2866.5, 3503.5,
  130825. };
  130826. static long _vq_quantmap__44c7_s_p9_0[] = {
  130827. 11, 9, 7, 5, 3, 1, 0, 2,
  130828. 4, 6, 8, 10, 12,
  130829. };
  130830. static encode_aux_threshmatch _vq_auxt__44c7_s_p9_0 = {
  130831. _vq_quantthresh__44c7_s_p9_0,
  130832. _vq_quantmap__44c7_s_p9_0,
  130833. 13,
  130834. 13
  130835. };
  130836. static static_codebook _44c7_s_p9_0 = {
  130837. 2, 169,
  130838. _vq_lengthlist__44c7_s_p9_0,
  130839. 1, -511845376, 1630791680, 4, 0,
  130840. _vq_quantlist__44c7_s_p9_0,
  130841. NULL,
  130842. &_vq_auxt__44c7_s_p9_0,
  130843. NULL,
  130844. 0
  130845. };
  130846. static long _vq_quantlist__44c7_s_p9_1[] = {
  130847. 6,
  130848. 5,
  130849. 7,
  130850. 4,
  130851. 8,
  130852. 3,
  130853. 9,
  130854. 2,
  130855. 10,
  130856. 1,
  130857. 11,
  130858. 0,
  130859. 12,
  130860. };
  130861. static long _vq_lengthlist__44c7_s_p9_1[] = {
  130862. 1, 4, 4, 7, 7, 7, 7, 7, 6, 8, 8, 8, 8, 6, 6, 6,
  130863. 8, 8, 9, 8, 8, 7, 9, 8,11,10, 5, 6, 6, 8, 8, 9,
  130864. 8, 8, 8,10, 9,11,11,16, 8, 8, 9, 8, 9, 9, 9, 8,
  130865. 10, 9,11,10,16, 8, 8, 9, 9,10,10, 9, 9,10,10,11,
  130866. 11,16,13,13, 9, 9,10,10, 9,10,11,11,12,11,16,13,
  130867. 13, 9, 8,10, 9,10,10,10,10,11,11,16,14,16, 8, 9,
  130868. 9, 9,11,10,11,11,12,11,16,16,16, 9, 7,10, 7,11,
  130869. 10,11,11,12,11,16,16,16,12,12, 9,10,11,11,12,11,
  130870. 12,12,16,16,16,12,10,10, 7,11, 8,12,11,12,12,16,
  130871. 16,15,16,16,11,12,10,10,12,11,12,12,16,16,16,15,
  130872. 15,11,11,10,10,12,12,12,12,
  130873. };
  130874. static float _vq_quantthresh__44c7_s_p9_1[] = {
  130875. -269.5, -220.5, -171.5, -122.5, -73.5, -24.5, 24.5, 73.5,
  130876. 122.5, 171.5, 220.5, 269.5,
  130877. };
  130878. static long _vq_quantmap__44c7_s_p9_1[] = {
  130879. 11, 9, 7, 5, 3, 1, 0, 2,
  130880. 4, 6, 8, 10, 12,
  130881. };
  130882. static encode_aux_threshmatch _vq_auxt__44c7_s_p9_1 = {
  130883. _vq_quantthresh__44c7_s_p9_1,
  130884. _vq_quantmap__44c7_s_p9_1,
  130885. 13,
  130886. 13
  130887. };
  130888. static static_codebook _44c7_s_p9_1 = {
  130889. 2, 169,
  130890. _vq_lengthlist__44c7_s_p9_1,
  130891. 1, -518889472, 1622704128, 4, 0,
  130892. _vq_quantlist__44c7_s_p9_1,
  130893. NULL,
  130894. &_vq_auxt__44c7_s_p9_1,
  130895. NULL,
  130896. 0
  130897. };
  130898. static long _vq_quantlist__44c7_s_p9_2[] = {
  130899. 24,
  130900. 23,
  130901. 25,
  130902. 22,
  130903. 26,
  130904. 21,
  130905. 27,
  130906. 20,
  130907. 28,
  130908. 19,
  130909. 29,
  130910. 18,
  130911. 30,
  130912. 17,
  130913. 31,
  130914. 16,
  130915. 32,
  130916. 15,
  130917. 33,
  130918. 14,
  130919. 34,
  130920. 13,
  130921. 35,
  130922. 12,
  130923. 36,
  130924. 11,
  130925. 37,
  130926. 10,
  130927. 38,
  130928. 9,
  130929. 39,
  130930. 8,
  130931. 40,
  130932. 7,
  130933. 41,
  130934. 6,
  130935. 42,
  130936. 5,
  130937. 43,
  130938. 4,
  130939. 44,
  130940. 3,
  130941. 45,
  130942. 2,
  130943. 46,
  130944. 1,
  130945. 47,
  130946. 0,
  130947. 48,
  130948. };
  130949. static long _vq_lengthlist__44c7_s_p9_2[] = {
  130950. 2, 4, 3, 4, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6, 6, 6,
  130951. 6, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  130952. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  130953. 7,
  130954. };
  130955. static float _vq_quantthresh__44c7_s_p9_2[] = {
  130956. -23.5, -22.5, -21.5, -20.5, -19.5, -18.5, -17.5, -16.5,
  130957. -15.5, -14.5, -13.5, -12.5, -11.5, -10.5, -9.5, -8.5,
  130958. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  130959. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  130960. 8.5, 9.5, 10.5, 11.5, 12.5, 13.5, 14.5, 15.5,
  130961. 16.5, 17.5, 18.5, 19.5, 20.5, 21.5, 22.5, 23.5,
  130962. };
  130963. static long _vq_quantmap__44c7_s_p9_2[] = {
  130964. 47, 45, 43, 41, 39, 37, 35, 33,
  130965. 31, 29, 27, 25, 23, 21, 19, 17,
  130966. 15, 13, 11, 9, 7, 5, 3, 1,
  130967. 0, 2, 4, 6, 8, 10, 12, 14,
  130968. 16, 18, 20, 22, 24, 26, 28, 30,
  130969. 32, 34, 36, 38, 40, 42, 44, 46,
  130970. 48,
  130971. };
  130972. static encode_aux_threshmatch _vq_auxt__44c7_s_p9_2 = {
  130973. _vq_quantthresh__44c7_s_p9_2,
  130974. _vq_quantmap__44c7_s_p9_2,
  130975. 49,
  130976. 49
  130977. };
  130978. static static_codebook _44c7_s_p9_2 = {
  130979. 1, 49,
  130980. _vq_lengthlist__44c7_s_p9_2,
  130981. 1, -526909440, 1611661312, 6, 0,
  130982. _vq_quantlist__44c7_s_p9_2,
  130983. NULL,
  130984. &_vq_auxt__44c7_s_p9_2,
  130985. NULL,
  130986. 0
  130987. };
  130988. static long _huff_lengthlist__44c7_s_short[] = {
  130989. 4,11,12,14,15,15,17,17,18,18, 5, 6, 6, 8, 9,10,
  130990. 13,17,18,19, 7, 5, 4, 6, 8, 9,11,15,19,19, 8, 6,
  130991. 5, 5, 6, 7,11,14,16,17, 9, 7, 7, 6, 7, 7,10,13,
  130992. 15,19,10, 8, 7, 6, 7, 6, 7, 9,14,16,12,10, 9, 7,
  130993. 7, 6, 4, 5,10,15,14,13,11, 7, 6, 6, 4, 2, 7,13,
  130994. 16,16,15, 9, 8, 8, 8, 6, 9,13,19,19,17,12,11,10,
  130995. 10, 9,11,14,
  130996. };
  130997. static static_codebook _huff_book__44c7_s_short = {
  130998. 2, 100,
  130999. _huff_lengthlist__44c7_s_short,
  131000. 0, 0, 0, 0, 0,
  131001. NULL,
  131002. NULL,
  131003. NULL,
  131004. NULL,
  131005. 0
  131006. };
  131007. static long _huff_lengthlist__44c8_s_long[] = {
  131008. 3, 8,12,13,14,14,14,13,14,14, 6, 4, 5, 8,10,10,
  131009. 11,11,14,13, 9, 5, 4, 5, 7, 8, 9,10,13,13,12, 7,
  131010. 5, 4, 5, 6, 8, 9,12,13,13, 9, 6, 5, 5, 5, 7, 9,
  131011. 11,14,12,10, 7, 6, 5, 4, 6, 7,10,11,12,11, 9, 8,
  131012. 7, 5, 5, 6,10,10,13,12,10, 9, 8, 6, 6, 5, 8,10,
  131013. 14,13,12,12,11,10, 9, 7, 8,10,12,13,14,14,13,12,
  131014. 11, 9, 9,10,
  131015. };
  131016. static static_codebook _huff_book__44c8_s_long = {
  131017. 2, 100,
  131018. _huff_lengthlist__44c8_s_long,
  131019. 0, 0, 0, 0, 0,
  131020. NULL,
  131021. NULL,
  131022. NULL,
  131023. NULL,
  131024. 0
  131025. };
  131026. static long _vq_quantlist__44c8_s_p1_0[] = {
  131027. 1,
  131028. 0,
  131029. 2,
  131030. };
  131031. static long _vq_lengthlist__44c8_s_p1_0[] = {
  131032. 1, 5, 5, 0, 5, 5, 0, 5, 5, 5, 7, 7, 0, 9, 8, 0,
  131033. 9, 8, 6, 7, 7, 0, 8, 9, 0, 8, 9, 0, 0, 0, 0, 0,
  131034. 0, 0, 0, 0, 5, 9, 8, 0, 8, 8, 0, 8, 8, 5, 8, 9,
  131035. 0, 8, 8, 0, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5,
  131036. 9, 8, 0, 8, 8, 0, 8, 8, 5, 8, 9, 0, 8, 8, 0, 8,
  131037. 8,
  131038. };
  131039. static float _vq_quantthresh__44c8_s_p1_0[] = {
  131040. -0.5, 0.5,
  131041. };
  131042. static long _vq_quantmap__44c8_s_p1_0[] = {
  131043. 1, 0, 2,
  131044. };
  131045. static encode_aux_threshmatch _vq_auxt__44c8_s_p1_0 = {
  131046. _vq_quantthresh__44c8_s_p1_0,
  131047. _vq_quantmap__44c8_s_p1_0,
  131048. 3,
  131049. 3
  131050. };
  131051. static static_codebook _44c8_s_p1_0 = {
  131052. 4, 81,
  131053. _vq_lengthlist__44c8_s_p1_0,
  131054. 1, -535822336, 1611661312, 2, 0,
  131055. _vq_quantlist__44c8_s_p1_0,
  131056. NULL,
  131057. &_vq_auxt__44c8_s_p1_0,
  131058. NULL,
  131059. 0
  131060. };
  131061. static long _vq_quantlist__44c8_s_p2_0[] = {
  131062. 2,
  131063. 1,
  131064. 3,
  131065. 0,
  131066. 4,
  131067. };
  131068. static long _vq_lengthlist__44c8_s_p2_0[] = {
  131069. 3, 5, 5, 8, 8, 0, 5, 5, 8, 8, 0, 5, 5, 8, 8, 0,
  131070. 7, 7, 9, 9, 0, 0, 0, 9, 9, 5, 7, 7, 9, 9, 0, 8,
  131071. 7,10, 9, 0, 8, 7,10, 9, 0,10,10,11,11, 0, 0, 0,
  131072. 11,11, 5, 7, 7, 9, 9, 0, 7, 8, 9,10, 0, 7, 8, 9,
  131073. 10, 0,10,10,11,11, 0, 0, 0,11,11, 8, 9, 9,11,10,
  131074. 0,11,10,12,11, 0,11,10,12,12, 0,13,13,14,14, 0,
  131075. 0, 0,14,13, 8, 9, 9,10,11, 0,10,11,12,12, 0,10,
  131076. 11,12,12, 0,13,13,14,14, 0, 0, 0,13,14, 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, 5, 8, 7,11,10, 0, 7, 7,10,10,
  131079. 0, 7, 7,10,10, 0, 9, 9,10,10, 0, 0, 0,11,10, 5,
  131080. 7, 8,10,11, 0, 7, 7,10,10, 0, 7, 7,10,10, 0, 9,
  131081. 9,10,10, 0, 0, 0,10,10, 8,10, 9,12,12, 0,10,10,
  131082. 12,11, 0,10,10,12,12, 0,12,12,13,12, 0, 0, 0,13,
  131083. 12, 8, 9,10,12,12, 0,10,10,11,12, 0,10,10,11,12,
  131084. 0,12,12,13,13, 0, 0, 0,12,13, 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, 6, 8, 7,11,10, 0, 7, 7,10,10, 0, 7, 7,
  131087. 10,10, 0, 9, 9,10,11, 0, 0, 0,10,10, 6, 7, 8,10,
  131088. 11, 0, 7, 7,10,10, 0, 7, 7,10,10, 0, 9, 9,10,10,
  131089. 0, 0, 0,10,10, 9,10, 9,12,12, 0,10,10,12,12, 0,
  131090. 10,10,12,11, 0,12,12,13,13, 0, 0, 0,13,12, 8, 9,
  131091. 10,12,12, 0,10,10,12,12, 0,10,10,11,12, 0,12,12,
  131092. 13,13, 0, 0, 0,12,13, 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. 7,10,10,13,13, 0, 9, 9,12,12, 0, 9, 9,12,12, 0,
  131095. 10,10,12,12, 0, 0, 0,12,12, 7,10,10,13,13, 0, 9,
  131096. 9,12,12, 0, 9, 9,12,12, 0,10,10,12,12, 0, 0, 0,
  131097. 12,12, 9,11,11,14,13, 0,10,10,13,12, 0,11,10,13,
  131098. 12, 0,12,12,13,12, 0, 0, 0,13,13, 9,11,11,13,14,
  131099. 0,10,11,12,13, 0,10,11,13,13, 0,12,12,12,13, 0,
  131100. 0, 0,13,13, 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, 9,
  131105. 11,11,14,14, 0,10,11,13,13, 0,11,10,13,13, 0,11,
  131106. 12,13,13, 0, 0, 0,13,12, 9,11,11,14,14, 0,11,10,
  131107. 13,13, 0,10,11,13,13, 0,12,12,13,13, 0, 0, 0,12,
  131108. 13,
  131109. };
  131110. static float _vq_quantthresh__44c8_s_p2_0[] = {
  131111. -1.5, -0.5, 0.5, 1.5,
  131112. };
  131113. static long _vq_quantmap__44c8_s_p2_0[] = {
  131114. 3, 1, 0, 2, 4,
  131115. };
  131116. static encode_aux_threshmatch _vq_auxt__44c8_s_p2_0 = {
  131117. _vq_quantthresh__44c8_s_p2_0,
  131118. _vq_quantmap__44c8_s_p2_0,
  131119. 5,
  131120. 5
  131121. };
  131122. static static_codebook _44c8_s_p2_0 = {
  131123. 4, 625,
  131124. _vq_lengthlist__44c8_s_p2_0,
  131125. 1, -533725184, 1611661312, 3, 0,
  131126. _vq_quantlist__44c8_s_p2_0,
  131127. NULL,
  131128. &_vq_auxt__44c8_s_p2_0,
  131129. NULL,
  131130. 0
  131131. };
  131132. static long _vq_quantlist__44c8_s_p3_0[] = {
  131133. 4,
  131134. 3,
  131135. 5,
  131136. 2,
  131137. 6,
  131138. 1,
  131139. 7,
  131140. 0,
  131141. 8,
  131142. };
  131143. static long _vq_lengthlist__44c8_s_p3_0[] = {
  131144. 2, 4, 4, 5, 5, 7, 7, 9, 9, 0, 4, 4, 6, 6, 7, 7,
  131145. 9, 9, 0, 4, 4, 6, 6, 7, 7, 9, 9, 0, 5, 5, 6, 6,
  131146. 8, 8,10,10, 0, 0, 0, 6, 6, 8, 8,10,10, 0, 0, 0,
  131147. 7, 7, 9, 9,10,10, 0, 0, 0, 7, 7, 8, 8,10,10, 0,
  131148. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131149. 0,
  131150. };
  131151. static float _vq_quantthresh__44c8_s_p3_0[] = {
  131152. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  131153. };
  131154. static long _vq_quantmap__44c8_s_p3_0[] = {
  131155. 7, 5, 3, 1, 0, 2, 4, 6,
  131156. 8,
  131157. };
  131158. static encode_aux_threshmatch _vq_auxt__44c8_s_p3_0 = {
  131159. _vq_quantthresh__44c8_s_p3_0,
  131160. _vq_quantmap__44c8_s_p3_0,
  131161. 9,
  131162. 9
  131163. };
  131164. static static_codebook _44c8_s_p3_0 = {
  131165. 2, 81,
  131166. _vq_lengthlist__44c8_s_p3_0,
  131167. 1, -531628032, 1611661312, 4, 0,
  131168. _vq_quantlist__44c8_s_p3_0,
  131169. NULL,
  131170. &_vq_auxt__44c8_s_p3_0,
  131171. NULL,
  131172. 0
  131173. };
  131174. static long _vq_quantlist__44c8_s_p4_0[] = {
  131175. 8,
  131176. 7,
  131177. 9,
  131178. 6,
  131179. 10,
  131180. 5,
  131181. 11,
  131182. 4,
  131183. 12,
  131184. 3,
  131185. 13,
  131186. 2,
  131187. 14,
  131188. 1,
  131189. 15,
  131190. 0,
  131191. 16,
  131192. };
  131193. static long _vq_lengthlist__44c8_s_p4_0[] = {
  131194. 3, 4, 4, 5, 5, 7, 7, 8, 8, 8, 8, 9, 9,10,10,11,
  131195. 11, 0, 4, 4, 6, 6, 7, 7, 8, 8, 9, 8,10,10,11,11,
  131196. 11,11, 0, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10,11,
  131197. 11,11,11, 0, 6, 5, 6, 6, 7, 7, 9, 9, 9, 9,10,10,
  131198. 11,11,12,12, 0, 0, 0, 6, 6, 7, 7, 9, 9, 9, 9,10,
  131199. 10,11,11,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9,10,10,
  131200. 11,11,11,12,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9,10,
  131201. 10,11,11,11,12,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9,
  131202. 10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 8, 8, 9,
  131203. 9,10,10,11,11,12,12,13,13, 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,
  131213. };
  131214. static float _vq_quantthresh__44c8_s_p4_0[] = {
  131215. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  131216. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  131217. };
  131218. static long _vq_quantmap__44c8_s_p4_0[] = {
  131219. 15, 13, 11, 9, 7, 5, 3, 1,
  131220. 0, 2, 4, 6, 8, 10, 12, 14,
  131221. 16,
  131222. };
  131223. static encode_aux_threshmatch _vq_auxt__44c8_s_p4_0 = {
  131224. _vq_quantthresh__44c8_s_p4_0,
  131225. _vq_quantmap__44c8_s_p4_0,
  131226. 17,
  131227. 17
  131228. };
  131229. static static_codebook _44c8_s_p4_0 = {
  131230. 2, 289,
  131231. _vq_lengthlist__44c8_s_p4_0,
  131232. 1, -529530880, 1611661312, 5, 0,
  131233. _vq_quantlist__44c8_s_p4_0,
  131234. NULL,
  131235. &_vq_auxt__44c8_s_p4_0,
  131236. NULL,
  131237. 0
  131238. };
  131239. static long _vq_quantlist__44c8_s_p5_0[] = {
  131240. 1,
  131241. 0,
  131242. 2,
  131243. };
  131244. static long _vq_lengthlist__44c8_s_p5_0[] = {
  131245. 1, 4, 4, 5, 7, 7, 6, 7, 7, 4, 7, 6,10,10,10,10,
  131246. 10,10, 4, 6, 6,10,10,10,10, 9,10, 5,10,10, 9,11,
  131247. 11,10,11,11, 7,10,10,11,12,12,12,12,12, 7,10,10,
  131248. 11,12,12,12,12,12, 6,10,10,10,12,12,10,12,12, 7,
  131249. 10,10,11,12,12,12,12,12, 7,10,10,11,12,12,12,12,
  131250. 12,
  131251. };
  131252. static float _vq_quantthresh__44c8_s_p5_0[] = {
  131253. -5.5, 5.5,
  131254. };
  131255. static long _vq_quantmap__44c8_s_p5_0[] = {
  131256. 1, 0, 2,
  131257. };
  131258. static encode_aux_threshmatch _vq_auxt__44c8_s_p5_0 = {
  131259. _vq_quantthresh__44c8_s_p5_0,
  131260. _vq_quantmap__44c8_s_p5_0,
  131261. 3,
  131262. 3
  131263. };
  131264. static static_codebook _44c8_s_p5_0 = {
  131265. 4, 81,
  131266. _vq_lengthlist__44c8_s_p5_0,
  131267. 1, -529137664, 1618345984, 2, 0,
  131268. _vq_quantlist__44c8_s_p5_0,
  131269. NULL,
  131270. &_vq_auxt__44c8_s_p5_0,
  131271. NULL,
  131272. 0
  131273. };
  131274. static long _vq_quantlist__44c8_s_p5_1[] = {
  131275. 5,
  131276. 4,
  131277. 6,
  131278. 3,
  131279. 7,
  131280. 2,
  131281. 8,
  131282. 1,
  131283. 9,
  131284. 0,
  131285. 10,
  131286. };
  131287. static long _vq_lengthlist__44c8_s_p5_1[] = {
  131288. 3, 5, 5, 6, 6, 7, 7, 8, 8, 8, 8,11, 4, 5, 6, 6,
  131289. 7, 7, 8, 8, 8, 8,11, 5, 5, 6, 6, 7, 7, 8, 8, 8,
  131290. 9,12, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9,12,12,12, 6,
  131291. 6, 7, 7, 8, 8, 9, 9,11,11,11, 6, 6, 7, 7, 8, 8,
  131292. 8, 8,11,11,11, 6, 6, 7, 7, 8, 8, 8, 8,11,11,11,
  131293. 7, 7, 7, 8, 8, 8, 8, 8,11,11,11,11,11, 7, 7, 8,
  131294. 8, 8, 8,11,11,11,11,11, 7, 7, 7, 7, 8, 8,11,11,
  131295. 11,11,11, 7, 7, 7, 7, 8, 8,
  131296. };
  131297. static float _vq_quantthresh__44c8_s_p5_1[] = {
  131298. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  131299. 3.5, 4.5,
  131300. };
  131301. static long _vq_quantmap__44c8_s_p5_1[] = {
  131302. 9, 7, 5, 3, 1, 0, 2, 4,
  131303. 6, 8, 10,
  131304. };
  131305. static encode_aux_threshmatch _vq_auxt__44c8_s_p5_1 = {
  131306. _vq_quantthresh__44c8_s_p5_1,
  131307. _vq_quantmap__44c8_s_p5_1,
  131308. 11,
  131309. 11
  131310. };
  131311. static static_codebook _44c8_s_p5_1 = {
  131312. 2, 121,
  131313. _vq_lengthlist__44c8_s_p5_1,
  131314. 1, -531365888, 1611661312, 4, 0,
  131315. _vq_quantlist__44c8_s_p5_1,
  131316. NULL,
  131317. &_vq_auxt__44c8_s_p5_1,
  131318. NULL,
  131319. 0
  131320. };
  131321. static long _vq_quantlist__44c8_s_p6_0[] = {
  131322. 6,
  131323. 5,
  131324. 7,
  131325. 4,
  131326. 8,
  131327. 3,
  131328. 9,
  131329. 2,
  131330. 10,
  131331. 1,
  131332. 11,
  131333. 0,
  131334. 12,
  131335. };
  131336. static long _vq_lengthlist__44c8_s_p6_0[] = {
  131337. 1, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10, 6, 5, 5,
  131338. 7, 7, 8, 8, 9, 9,10,10,11,11, 6, 5, 5, 7, 7, 8,
  131339. 8, 9, 9,10,10,11,11, 0, 7, 7, 7, 7, 9, 9,10,10,
  131340. 10,10,11,11, 0, 7, 7, 7, 7, 9, 9,10,10,10,10,11,
  131341. 11, 0,11,11, 9, 9,10,10,11,11,11,11,12,12, 0,12,
  131342. 12, 9, 9,10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0,
  131343. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131344. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131345. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131346. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131347. 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131348. };
  131349. static float _vq_quantthresh__44c8_s_p6_0[] = {
  131350. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  131351. 12.5, 17.5, 22.5, 27.5,
  131352. };
  131353. static long _vq_quantmap__44c8_s_p6_0[] = {
  131354. 11, 9, 7, 5, 3, 1, 0, 2,
  131355. 4, 6, 8, 10, 12,
  131356. };
  131357. static encode_aux_threshmatch _vq_auxt__44c8_s_p6_0 = {
  131358. _vq_quantthresh__44c8_s_p6_0,
  131359. _vq_quantmap__44c8_s_p6_0,
  131360. 13,
  131361. 13
  131362. };
  131363. static static_codebook _44c8_s_p6_0 = {
  131364. 2, 169,
  131365. _vq_lengthlist__44c8_s_p6_0,
  131366. 1, -526516224, 1616117760, 4, 0,
  131367. _vq_quantlist__44c8_s_p6_0,
  131368. NULL,
  131369. &_vq_auxt__44c8_s_p6_0,
  131370. NULL,
  131371. 0
  131372. };
  131373. static long _vq_quantlist__44c8_s_p6_1[] = {
  131374. 2,
  131375. 1,
  131376. 3,
  131377. 0,
  131378. 4,
  131379. };
  131380. static long _vq_lengthlist__44c8_s_p6_1[] = {
  131381. 3, 4, 4, 5, 5, 5, 4, 4, 5, 5, 5, 4, 4, 5, 5, 6,
  131382. 5, 5, 5, 5, 6, 6, 6, 5, 5,
  131383. };
  131384. static float _vq_quantthresh__44c8_s_p6_1[] = {
  131385. -1.5, -0.5, 0.5, 1.5,
  131386. };
  131387. static long _vq_quantmap__44c8_s_p6_1[] = {
  131388. 3, 1, 0, 2, 4,
  131389. };
  131390. static encode_aux_threshmatch _vq_auxt__44c8_s_p6_1 = {
  131391. _vq_quantthresh__44c8_s_p6_1,
  131392. _vq_quantmap__44c8_s_p6_1,
  131393. 5,
  131394. 5
  131395. };
  131396. static static_codebook _44c8_s_p6_1 = {
  131397. 2, 25,
  131398. _vq_lengthlist__44c8_s_p6_1,
  131399. 1, -533725184, 1611661312, 3, 0,
  131400. _vq_quantlist__44c8_s_p6_1,
  131401. NULL,
  131402. &_vq_auxt__44c8_s_p6_1,
  131403. NULL,
  131404. 0
  131405. };
  131406. static long _vq_quantlist__44c8_s_p7_0[] = {
  131407. 6,
  131408. 5,
  131409. 7,
  131410. 4,
  131411. 8,
  131412. 3,
  131413. 9,
  131414. 2,
  131415. 10,
  131416. 1,
  131417. 11,
  131418. 0,
  131419. 12,
  131420. };
  131421. static long _vq_lengthlist__44c8_s_p7_0[] = {
  131422. 1, 4, 4, 6, 6, 8, 7, 9, 9,10,10,12,12, 6, 5, 5,
  131423. 7, 7, 8, 8,10,10,11,11,12,12, 7, 5, 5, 7, 7, 8,
  131424. 8,10,10,11,11,12,12,21, 7, 7, 7, 7, 8, 9,10,10,
  131425. 11,11,12,12,21, 7, 7, 7, 7, 9, 9,10,10,12,12,13,
  131426. 13,21,11,11, 8, 8, 9, 9,11,11,12,12,13,13,21,11,
  131427. 11, 8, 8, 9, 9,11,11,12,12,13,13,21,21,21,10,10,
  131428. 10,10,11,11,12,13,13,13,21,21,21,10,10,10,10,11,
  131429. 11,13,13,14,13,21,21,21,13,13,11,11,12,12,13,13,
  131430. 14,14,21,21,21,14,14,11,11,12,12,13,13,14,14,21,
  131431. 21,21,21,20,13,13,13,12,14,14,16,15,20,20,20,20,
  131432. 20,13,13,13,13,14,13,15,15,
  131433. };
  131434. static float _vq_quantthresh__44c8_s_p7_0[] = {
  131435. -60.5, -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5,
  131436. 27.5, 38.5, 49.5, 60.5,
  131437. };
  131438. static long _vq_quantmap__44c8_s_p7_0[] = {
  131439. 11, 9, 7, 5, 3, 1, 0, 2,
  131440. 4, 6, 8, 10, 12,
  131441. };
  131442. static encode_aux_threshmatch _vq_auxt__44c8_s_p7_0 = {
  131443. _vq_quantthresh__44c8_s_p7_0,
  131444. _vq_quantmap__44c8_s_p7_0,
  131445. 13,
  131446. 13
  131447. };
  131448. static static_codebook _44c8_s_p7_0 = {
  131449. 2, 169,
  131450. _vq_lengthlist__44c8_s_p7_0,
  131451. 1, -523206656, 1618345984, 4, 0,
  131452. _vq_quantlist__44c8_s_p7_0,
  131453. NULL,
  131454. &_vq_auxt__44c8_s_p7_0,
  131455. NULL,
  131456. 0
  131457. };
  131458. static long _vq_quantlist__44c8_s_p7_1[] = {
  131459. 5,
  131460. 4,
  131461. 6,
  131462. 3,
  131463. 7,
  131464. 2,
  131465. 8,
  131466. 1,
  131467. 9,
  131468. 0,
  131469. 10,
  131470. };
  131471. static long _vq_lengthlist__44c8_s_p7_1[] = {
  131472. 4, 5, 6, 6, 6, 7, 7, 7, 7, 7, 7, 8, 6, 6, 6, 7,
  131473. 7, 7, 7, 7, 7, 7, 8, 6, 6, 6, 6, 7, 7, 7, 7, 7,
  131474. 7, 8, 6, 6, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 7,
  131475. 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 7, 7, 7, 7, 7, 7,
  131476. 7, 7, 8, 8, 8, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8,
  131477. 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8, 7, 7, 7,
  131478. 7, 7, 7, 8, 8, 8, 8, 8, 7, 7, 7, 7, 7, 7, 8, 8,
  131479. 8, 8, 8, 7, 7, 7, 7, 7, 7,
  131480. };
  131481. static float _vq_quantthresh__44c8_s_p7_1[] = {
  131482. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  131483. 3.5, 4.5,
  131484. };
  131485. static long _vq_quantmap__44c8_s_p7_1[] = {
  131486. 9, 7, 5, 3, 1, 0, 2, 4,
  131487. 6, 8, 10,
  131488. };
  131489. static encode_aux_threshmatch _vq_auxt__44c8_s_p7_1 = {
  131490. _vq_quantthresh__44c8_s_p7_1,
  131491. _vq_quantmap__44c8_s_p7_1,
  131492. 11,
  131493. 11
  131494. };
  131495. static static_codebook _44c8_s_p7_1 = {
  131496. 2, 121,
  131497. _vq_lengthlist__44c8_s_p7_1,
  131498. 1, -531365888, 1611661312, 4, 0,
  131499. _vq_quantlist__44c8_s_p7_1,
  131500. NULL,
  131501. &_vq_auxt__44c8_s_p7_1,
  131502. NULL,
  131503. 0
  131504. };
  131505. static long _vq_quantlist__44c8_s_p8_0[] = {
  131506. 7,
  131507. 6,
  131508. 8,
  131509. 5,
  131510. 9,
  131511. 4,
  131512. 10,
  131513. 3,
  131514. 11,
  131515. 2,
  131516. 12,
  131517. 1,
  131518. 13,
  131519. 0,
  131520. 14,
  131521. };
  131522. static long _vq_lengthlist__44c8_s_p8_0[] = {
  131523. 1, 4, 4, 7, 6, 8, 8, 8, 7, 9, 8,10,10,11,10, 6,
  131524. 5, 5, 7, 7, 9, 9, 8, 8,10,10,11,11,12,11, 6, 5,
  131525. 5, 7, 7, 9, 9, 9, 9,10,10,11,11,12,12,20, 8, 8,
  131526. 8, 8, 9, 9, 9, 9,10,10,11,11,12,12,20, 8, 8, 8,
  131527. 8,10, 9, 9, 9,10,10,11,11,12,12,20,12,12, 9, 9,
  131528. 10,10,10,10,10,11,12,12,12,12,20,12,12, 9, 9,10,
  131529. 10,10,10,11,11,12,12,13,13,20,20,20, 9, 9, 9, 9,
  131530. 11,10,11,11,12,12,12,13,20,19,19, 9, 9, 9, 9,11,
  131531. 11,11,12,12,12,13,13,19,19,19,13,13,10,10,11,11,
  131532. 12,12,13,13,13,13,19,19,19,14,13,11,10,11,11,12,
  131533. 12,12,13,13,13,19,19,19,19,19,12,12,12,12,13,13,
  131534. 13,13,14,13,19,19,19,19,19,12,12,12,11,12,12,13,
  131535. 14,14,14,19,19,19,19,19,16,15,13,12,13,13,13,14,
  131536. 14,14,19,19,19,19,19,17,17,13,12,13,11,14,13,15,
  131537. 15,
  131538. };
  131539. static float _vq_quantthresh__44c8_s_p8_0[] = {
  131540. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  131541. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  131542. };
  131543. static long _vq_quantmap__44c8_s_p8_0[] = {
  131544. 13, 11, 9, 7, 5, 3, 1, 0,
  131545. 2, 4, 6, 8, 10, 12, 14,
  131546. };
  131547. static encode_aux_threshmatch _vq_auxt__44c8_s_p8_0 = {
  131548. _vq_quantthresh__44c8_s_p8_0,
  131549. _vq_quantmap__44c8_s_p8_0,
  131550. 15,
  131551. 15
  131552. };
  131553. static static_codebook _44c8_s_p8_0 = {
  131554. 2, 225,
  131555. _vq_lengthlist__44c8_s_p8_0,
  131556. 1, -520986624, 1620377600, 4, 0,
  131557. _vq_quantlist__44c8_s_p8_0,
  131558. NULL,
  131559. &_vq_auxt__44c8_s_p8_0,
  131560. NULL,
  131561. 0
  131562. };
  131563. static long _vq_quantlist__44c8_s_p8_1[] = {
  131564. 10,
  131565. 9,
  131566. 11,
  131567. 8,
  131568. 12,
  131569. 7,
  131570. 13,
  131571. 6,
  131572. 14,
  131573. 5,
  131574. 15,
  131575. 4,
  131576. 16,
  131577. 3,
  131578. 17,
  131579. 2,
  131580. 18,
  131581. 1,
  131582. 19,
  131583. 0,
  131584. 20,
  131585. };
  131586. static long _vq_lengthlist__44c8_s_p8_1[] = {
  131587. 4, 5, 5, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  131588. 8, 8, 8, 8, 8,10, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,
  131589. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 6, 6, 7, 7, 8,
  131590. 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,
  131591. 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  131592. 9, 9, 9, 9,10,10,10, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  131593. 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10,10, 8, 8, 8, 9,
  131594. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10,
  131595. 10, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  131596. 9, 9, 9,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  131597. 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,10,10, 9, 9, 9,
  131598. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,
  131599. 10,10, 9, 9, 9, 9, 9, 9, 9, 9,10, 9, 9, 9, 9, 9,
  131600. 9, 9,10,10,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  131601. 9, 9, 9, 9, 9, 9, 9,10,10,10,10,10, 9, 9, 9, 9,
  131602. 9, 9, 9, 9,10,10,10, 9, 9, 9, 9, 9,10,10,10,10,
  131603. 10,10,10, 9, 9, 9, 9, 9,10,10,10, 9, 9, 9, 9, 9,
  131604. 9,10,10,10,10,10,10,10, 9,10,10, 9,10,10,10,10,
  131605. 9,10, 9,10,10, 9,10,10,10,10,10,10,10, 9,10,10,
  131606. 10,10,10,10, 9, 9,10,10, 9,10,10,10,10,10,10,10,
  131607. 10,10,10,10,10,10,10,10, 9, 9, 9,10, 9, 9, 9, 9,
  131608. 10,10,10,10,10,10,10,10,10,10,10,10,10,10, 9, 9,
  131609. 10, 9,10, 9,10,10,10,10,10,10,10,10,10,10,10,10,
  131610. 10,10,10,10, 9, 9,10, 9, 9, 9,10,10,10,10,10,10,
  131611. 10,10,10,10,10, 9, 9, 9, 9, 9, 9,10, 9, 9,10,10,
  131612. 10,10,10,10,10,10,10,10,10,10,10,10,10, 9,10, 9,
  131613. 9,10, 9, 9,10,10,10,10,10,10,10,10,10,10,10,10,
  131614. 10, 9, 9,10,10, 9,10, 9, 9,
  131615. };
  131616. static float _vq_quantthresh__44c8_s_p8_1[] = {
  131617. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  131618. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  131619. 6.5, 7.5, 8.5, 9.5,
  131620. };
  131621. static long _vq_quantmap__44c8_s_p8_1[] = {
  131622. 19, 17, 15, 13, 11, 9, 7, 5,
  131623. 3, 1, 0, 2, 4, 6, 8, 10,
  131624. 12, 14, 16, 18, 20,
  131625. };
  131626. static encode_aux_threshmatch _vq_auxt__44c8_s_p8_1 = {
  131627. _vq_quantthresh__44c8_s_p8_1,
  131628. _vq_quantmap__44c8_s_p8_1,
  131629. 21,
  131630. 21
  131631. };
  131632. static static_codebook _44c8_s_p8_1 = {
  131633. 2, 441,
  131634. _vq_lengthlist__44c8_s_p8_1,
  131635. 1, -529268736, 1611661312, 5, 0,
  131636. _vq_quantlist__44c8_s_p8_1,
  131637. NULL,
  131638. &_vq_auxt__44c8_s_p8_1,
  131639. NULL,
  131640. 0
  131641. };
  131642. static long _vq_quantlist__44c8_s_p9_0[] = {
  131643. 8,
  131644. 7,
  131645. 9,
  131646. 6,
  131647. 10,
  131648. 5,
  131649. 11,
  131650. 4,
  131651. 12,
  131652. 3,
  131653. 13,
  131654. 2,
  131655. 14,
  131656. 1,
  131657. 15,
  131658. 0,
  131659. 16,
  131660. };
  131661. static long _vq_lengthlist__44c8_s_p9_0[] = {
  131662. 1, 4, 3,11,11,11,11,11,11,11,11,11,11,11,11,11,
  131663. 11, 4, 7, 7,11,11,11,11,11,11,11,11,11,11,11,11,
  131664. 11,11, 4, 8,11,11,11,11,11,11,11,11,11,11,11,11,
  131665. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  131666. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  131667. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  131668. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  131669. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  131670. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  131671. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  131672. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  131673. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  131674. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  131675. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  131676. 11,11,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  131677. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  131678. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  131679. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  131680. 10,
  131681. };
  131682. static float _vq_quantthresh__44c8_s_p9_0[] = {
  131683. -6982.5, -6051.5, -5120.5, -4189.5, -3258.5, -2327.5, -1396.5, -465.5,
  131684. 465.5, 1396.5, 2327.5, 3258.5, 4189.5, 5120.5, 6051.5, 6982.5,
  131685. };
  131686. static long _vq_quantmap__44c8_s_p9_0[] = {
  131687. 15, 13, 11, 9, 7, 5, 3, 1,
  131688. 0, 2, 4, 6, 8, 10, 12, 14,
  131689. 16,
  131690. };
  131691. static encode_aux_threshmatch _vq_auxt__44c8_s_p9_0 = {
  131692. _vq_quantthresh__44c8_s_p9_0,
  131693. _vq_quantmap__44c8_s_p9_0,
  131694. 17,
  131695. 17
  131696. };
  131697. static static_codebook _44c8_s_p9_0 = {
  131698. 2, 289,
  131699. _vq_lengthlist__44c8_s_p9_0,
  131700. 1, -509798400, 1631393792, 5, 0,
  131701. _vq_quantlist__44c8_s_p9_0,
  131702. NULL,
  131703. &_vq_auxt__44c8_s_p9_0,
  131704. NULL,
  131705. 0
  131706. };
  131707. static long _vq_quantlist__44c8_s_p9_1[] = {
  131708. 9,
  131709. 8,
  131710. 10,
  131711. 7,
  131712. 11,
  131713. 6,
  131714. 12,
  131715. 5,
  131716. 13,
  131717. 4,
  131718. 14,
  131719. 3,
  131720. 15,
  131721. 2,
  131722. 16,
  131723. 1,
  131724. 17,
  131725. 0,
  131726. 18,
  131727. };
  131728. static long _vq_lengthlist__44c8_s_p9_1[] = {
  131729. 1, 4, 4, 7, 6, 7, 7, 7, 7, 8, 8, 9, 9,10,10,10,
  131730. 10,11,11, 6, 6, 6, 8, 8, 9, 8, 8, 7,10, 8,11,10,
  131731. 12,11,12,12,13,13, 5, 5, 6, 8, 8, 9, 9, 8, 8,10,
  131732. 9,11,11,12,12,13,13,13,13,17, 8, 8, 9, 9, 9, 9,
  131733. 9, 9,10, 9,12,10,12,12,13,12,13,13,17, 9, 8, 9,
  131734. 9, 9, 9, 9, 9,10,10,12,12,12,12,13,13,13,13,17,
  131735. 13,13, 9, 9,10,10,10,10,11,11,12,11,13,12,13,13,
  131736. 14,15,17,13,13, 9, 8,10, 9,10,10,11,11,12,12,14,
  131737. 13,15,13,14,15,17,17,17, 9,10, 9,10,11,11,12,12,
  131738. 12,12,13,13,14,14,15,15,17,17,17, 9, 8, 9, 8,11,
  131739. 11,12,12,12,12,14,13,14,14,14,15,17,17,17,12,14,
  131740. 9,10,11,11,12,12,14,13,13,14,15,13,15,15,17,17,
  131741. 17,13,11,10, 8,11, 9,13,12,13,13,13,13,13,14,14,
  131742. 14,17,17,17,17,17,11,12,11,11,13,13,14,13,15,14,
  131743. 13,15,16,15,17,17,17,17,17,11,11,12, 8,13,12,14,
  131744. 13,17,14,15,14,15,14,17,17,17,17,17,15,15,12,12,
  131745. 12,12,13,14,14,14,15,14,17,14,17,17,17,17,17,16,
  131746. 17,12,12,13,12,13,13,14,14,14,14,14,14,17,17,17,
  131747. 17,17,17,17,14,14,13,12,13,13,15,15,14,13,15,17,
  131748. 17,17,17,17,17,17,17,13,14,13,13,13,13,14,15,15,
  131749. 15,14,15,17,17,17,17,17,17,17,16,15,13,14,13,13,
  131750. 14,14,15,14,14,16,17,17,17,17,17,17,17,16,16,13,
  131751. 14,13,13,14,14,15,14,15,14,
  131752. };
  131753. static float _vq_quantthresh__44c8_s_p9_1[] = {
  131754. -416.5, -367.5, -318.5, -269.5, -220.5, -171.5, -122.5, -73.5,
  131755. -24.5, 24.5, 73.5, 122.5, 171.5, 220.5, 269.5, 318.5,
  131756. 367.5, 416.5,
  131757. };
  131758. static long _vq_quantmap__44c8_s_p9_1[] = {
  131759. 17, 15, 13, 11, 9, 7, 5, 3,
  131760. 1, 0, 2, 4, 6, 8, 10, 12,
  131761. 14, 16, 18,
  131762. };
  131763. static encode_aux_threshmatch _vq_auxt__44c8_s_p9_1 = {
  131764. _vq_quantthresh__44c8_s_p9_1,
  131765. _vq_quantmap__44c8_s_p9_1,
  131766. 19,
  131767. 19
  131768. };
  131769. static static_codebook _44c8_s_p9_1 = {
  131770. 2, 361,
  131771. _vq_lengthlist__44c8_s_p9_1,
  131772. 1, -518287360, 1622704128, 5, 0,
  131773. _vq_quantlist__44c8_s_p9_1,
  131774. NULL,
  131775. &_vq_auxt__44c8_s_p9_1,
  131776. NULL,
  131777. 0
  131778. };
  131779. static long _vq_quantlist__44c8_s_p9_2[] = {
  131780. 24,
  131781. 23,
  131782. 25,
  131783. 22,
  131784. 26,
  131785. 21,
  131786. 27,
  131787. 20,
  131788. 28,
  131789. 19,
  131790. 29,
  131791. 18,
  131792. 30,
  131793. 17,
  131794. 31,
  131795. 16,
  131796. 32,
  131797. 15,
  131798. 33,
  131799. 14,
  131800. 34,
  131801. 13,
  131802. 35,
  131803. 12,
  131804. 36,
  131805. 11,
  131806. 37,
  131807. 10,
  131808. 38,
  131809. 9,
  131810. 39,
  131811. 8,
  131812. 40,
  131813. 7,
  131814. 41,
  131815. 6,
  131816. 42,
  131817. 5,
  131818. 43,
  131819. 4,
  131820. 44,
  131821. 3,
  131822. 45,
  131823. 2,
  131824. 46,
  131825. 1,
  131826. 47,
  131827. 0,
  131828. 48,
  131829. };
  131830. static long _vq_lengthlist__44c8_s_p9_2[] = {
  131831. 2, 4, 4, 4, 5, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6, 6,
  131832. 6, 6, 6, 6, 6, 6, 6, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  131833. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  131834. 7,
  131835. };
  131836. static float _vq_quantthresh__44c8_s_p9_2[] = {
  131837. -23.5, -22.5, -21.5, -20.5, -19.5, -18.5, -17.5, -16.5,
  131838. -15.5, -14.5, -13.5, -12.5, -11.5, -10.5, -9.5, -8.5,
  131839. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  131840. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  131841. 8.5, 9.5, 10.5, 11.5, 12.5, 13.5, 14.5, 15.5,
  131842. 16.5, 17.5, 18.5, 19.5, 20.5, 21.5, 22.5, 23.5,
  131843. };
  131844. static long _vq_quantmap__44c8_s_p9_2[] = {
  131845. 47, 45, 43, 41, 39, 37, 35, 33,
  131846. 31, 29, 27, 25, 23, 21, 19, 17,
  131847. 15, 13, 11, 9, 7, 5, 3, 1,
  131848. 0, 2, 4, 6, 8, 10, 12, 14,
  131849. 16, 18, 20, 22, 24, 26, 28, 30,
  131850. 32, 34, 36, 38, 40, 42, 44, 46,
  131851. 48,
  131852. };
  131853. static encode_aux_threshmatch _vq_auxt__44c8_s_p9_2 = {
  131854. _vq_quantthresh__44c8_s_p9_2,
  131855. _vq_quantmap__44c8_s_p9_2,
  131856. 49,
  131857. 49
  131858. };
  131859. static static_codebook _44c8_s_p9_2 = {
  131860. 1, 49,
  131861. _vq_lengthlist__44c8_s_p9_2,
  131862. 1, -526909440, 1611661312, 6, 0,
  131863. _vq_quantlist__44c8_s_p9_2,
  131864. NULL,
  131865. &_vq_auxt__44c8_s_p9_2,
  131866. NULL,
  131867. 0
  131868. };
  131869. static long _huff_lengthlist__44c8_s_short[] = {
  131870. 4,11,13,14,15,15,18,17,19,17, 5, 6, 8, 9,10,10,
  131871. 12,15,19,19, 6, 6, 6, 6, 8, 8,11,14,18,19, 8, 6,
  131872. 5, 4, 6, 7,10,13,16,17, 9, 7, 6, 5, 6, 7, 9,12,
  131873. 15,19,10, 8, 7, 6, 6, 6, 7, 9,13,15,12,10, 9, 8,
  131874. 7, 6, 4, 5,10,15,13,13,11, 8, 6, 6, 4, 2, 7,12,
  131875. 17,15,16,10, 8, 8, 7, 6, 9,12,19,18,17,13,11,10,
  131876. 10, 9,11,14,
  131877. };
  131878. static static_codebook _huff_book__44c8_s_short = {
  131879. 2, 100,
  131880. _huff_lengthlist__44c8_s_short,
  131881. 0, 0, 0, 0, 0,
  131882. NULL,
  131883. NULL,
  131884. NULL,
  131885. NULL,
  131886. 0
  131887. };
  131888. static long _huff_lengthlist__44c9_s_long[] = {
  131889. 3, 8,12,14,15,15,15,13,15,15, 6, 5, 8,10,12,12,
  131890. 13,12,14,13,10, 6, 5, 6, 8, 9,11,11,13,13,13, 8,
  131891. 5, 4, 5, 6, 8,10,11,13,14,10, 7, 5, 4, 5, 7, 9,
  131892. 11,12,13,11, 8, 6, 5, 4, 5, 7, 9,11,12,11,10, 8,
  131893. 7, 5, 4, 5, 9,10,13,13,11,10, 8, 6, 5, 4, 7, 9,
  131894. 15,14,13,12,10, 9, 8, 7, 8, 9,12,12,14,13,12,11,
  131895. 10, 9, 8, 9,
  131896. };
  131897. static static_codebook _huff_book__44c9_s_long = {
  131898. 2, 100,
  131899. _huff_lengthlist__44c9_s_long,
  131900. 0, 0, 0, 0, 0,
  131901. NULL,
  131902. NULL,
  131903. NULL,
  131904. NULL,
  131905. 0
  131906. };
  131907. static long _vq_quantlist__44c9_s_p1_0[] = {
  131908. 1,
  131909. 0,
  131910. 2,
  131911. };
  131912. static long _vq_lengthlist__44c9_s_p1_0[] = {
  131913. 1, 5, 5, 0, 5, 5, 0, 5, 5, 6, 8, 8, 0, 9, 8, 0,
  131914. 9, 8, 6, 8, 8, 0, 8, 9, 0, 8, 9, 0, 0, 0, 0, 0,
  131915. 0, 0, 0, 0, 5, 8, 8, 0, 7, 7, 0, 8, 8, 5, 8, 8,
  131916. 0, 7, 8, 0, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5,
  131917. 9, 8, 0, 8, 8, 0, 7, 7, 5, 8, 9, 0, 8, 8, 0, 7,
  131918. 7,
  131919. };
  131920. static float _vq_quantthresh__44c9_s_p1_0[] = {
  131921. -0.5, 0.5,
  131922. };
  131923. static long _vq_quantmap__44c9_s_p1_0[] = {
  131924. 1, 0, 2,
  131925. };
  131926. static encode_aux_threshmatch _vq_auxt__44c9_s_p1_0 = {
  131927. _vq_quantthresh__44c9_s_p1_0,
  131928. _vq_quantmap__44c9_s_p1_0,
  131929. 3,
  131930. 3
  131931. };
  131932. static static_codebook _44c9_s_p1_0 = {
  131933. 4, 81,
  131934. _vq_lengthlist__44c9_s_p1_0,
  131935. 1, -535822336, 1611661312, 2, 0,
  131936. _vq_quantlist__44c9_s_p1_0,
  131937. NULL,
  131938. &_vq_auxt__44c9_s_p1_0,
  131939. NULL,
  131940. 0
  131941. };
  131942. static long _vq_quantlist__44c9_s_p2_0[] = {
  131943. 2,
  131944. 1,
  131945. 3,
  131946. 0,
  131947. 4,
  131948. };
  131949. static long _vq_lengthlist__44c9_s_p2_0[] = {
  131950. 3, 5, 5, 8, 8, 0, 5, 5, 8, 8, 0, 5, 5, 8, 8, 0,
  131951. 7, 7, 9, 9, 0, 0, 0, 9, 9, 6, 7, 7, 9, 8, 0, 8,
  131952. 8, 9, 9, 0, 8, 7, 9, 9, 0, 9,10,10,10, 0, 0, 0,
  131953. 11,10, 6, 7, 7, 8, 9, 0, 8, 8, 9, 9, 0, 7, 8, 9,
  131954. 9, 0,10, 9,11,10, 0, 0, 0,10,10, 8, 9, 8,10,10,
  131955. 0,10,10,12,11, 0,10,10,11,11, 0,12,13,13,13, 0,
  131956. 0, 0,13,12, 8, 8, 9,10,10, 0,10,10,11,12, 0,10,
  131957. 10,11,11, 0,13,12,13,13, 0, 0, 0,13,13, 0, 0, 0,
  131958. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131959. 0, 0, 0, 0, 0, 0, 6, 8, 7,10,10, 0, 7, 7,10, 9,
  131960. 0, 7, 7,10,10, 0, 9, 9,10,10, 0, 0, 0,10,10, 6,
  131961. 7, 8,10,10, 0, 7, 7, 9,10, 0, 7, 7,10,10, 0, 9,
  131962. 9,10,10, 0, 0, 0,10,10, 8, 9, 9,11,11, 0,10,10,
  131963. 11,11, 0,10,10,11,11, 0,12,12,12,12, 0, 0, 0,12,
  131964. 12, 8, 9,10,11,11, 0, 9,10,11,11, 0,10,10,11,11,
  131965. 0,12,12,12,12, 0, 0, 0,12,12, 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, 5, 8, 7,10,10, 0, 7, 7,10,10, 0, 7, 7,
  131968. 10, 9, 0, 9, 9,10,10, 0, 0, 0,10,10, 6, 7, 8,10,
  131969. 10, 0, 7, 7,10,10, 0, 7, 7, 9,10, 0, 9, 9,10,10,
  131970. 0, 0, 0,10,10, 8,10, 9,12,11, 0,10,10,12,11, 0,
  131971. 10, 9,11,11, 0,11,12,12,12, 0, 0, 0,12,12, 8, 9,
  131972. 10,11,12, 0,10,10,11,11, 0, 9,10,11,11, 0,12,11,
  131973. 12,12, 0, 0, 0,12,12, 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. 7,10, 9,12,12, 0, 9, 9,12,11, 0, 9, 9,11,11, 0,
  131976. 10,10,12,11, 0, 0, 0,11,12, 7, 9,10,12,12, 0, 9,
  131977. 9,11,12, 0, 9, 9,11,11, 0,10,10,11,12, 0, 0, 0,
  131978. 11,11, 9,11,10,13,12, 0,10,10,12,12, 0,10,10,12,
  131979. 12, 0,11,11,12,12, 0, 0, 0,13,12, 9,10,11,12,13,
  131980. 0,10,10,12,12, 0,10,10,12,12, 0,11,12,12,12, 0,
  131981. 0, 0,12,13, 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, 9,
  131986. 11,10,13,13, 0,10,10,12,12, 0,10,10,12,12, 0,11,
  131987. 12,12,12, 0, 0, 0,12,12, 9,10,11,13,13, 0,10,10,
  131988. 12,12, 0,10,10,12,12, 0,12,11,13,12, 0, 0, 0,12,
  131989. 12,
  131990. };
  131991. static float _vq_quantthresh__44c9_s_p2_0[] = {
  131992. -1.5, -0.5, 0.5, 1.5,
  131993. };
  131994. static long _vq_quantmap__44c9_s_p2_0[] = {
  131995. 3, 1, 0, 2, 4,
  131996. };
  131997. static encode_aux_threshmatch _vq_auxt__44c9_s_p2_0 = {
  131998. _vq_quantthresh__44c9_s_p2_0,
  131999. _vq_quantmap__44c9_s_p2_0,
  132000. 5,
  132001. 5
  132002. };
  132003. static static_codebook _44c9_s_p2_0 = {
  132004. 4, 625,
  132005. _vq_lengthlist__44c9_s_p2_0,
  132006. 1, -533725184, 1611661312, 3, 0,
  132007. _vq_quantlist__44c9_s_p2_0,
  132008. NULL,
  132009. &_vq_auxt__44c9_s_p2_0,
  132010. NULL,
  132011. 0
  132012. };
  132013. static long _vq_quantlist__44c9_s_p3_0[] = {
  132014. 4,
  132015. 3,
  132016. 5,
  132017. 2,
  132018. 6,
  132019. 1,
  132020. 7,
  132021. 0,
  132022. 8,
  132023. };
  132024. static long _vq_lengthlist__44c9_s_p3_0[] = {
  132025. 3, 4, 4, 5, 5, 6, 6, 8, 8, 0, 4, 4, 5, 5, 6, 7,
  132026. 8, 8, 0, 4, 4, 5, 5, 7, 7, 8, 8, 0, 5, 5, 6, 6,
  132027. 7, 7, 9, 9, 0, 0, 0, 6, 6, 7, 7, 9, 9, 0, 0, 0,
  132028. 7, 7, 8, 8, 9, 9, 0, 0, 0, 7, 7, 8, 8, 9, 9, 0,
  132029. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132030. 0,
  132031. };
  132032. static float _vq_quantthresh__44c9_s_p3_0[] = {
  132033. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  132034. };
  132035. static long _vq_quantmap__44c9_s_p3_0[] = {
  132036. 7, 5, 3, 1, 0, 2, 4, 6,
  132037. 8,
  132038. };
  132039. static encode_aux_threshmatch _vq_auxt__44c9_s_p3_0 = {
  132040. _vq_quantthresh__44c9_s_p3_0,
  132041. _vq_quantmap__44c9_s_p3_0,
  132042. 9,
  132043. 9
  132044. };
  132045. static static_codebook _44c9_s_p3_0 = {
  132046. 2, 81,
  132047. _vq_lengthlist__44c9_s_p3_0,
  132048. 1, -531628032, 1611661312, 4, 0,
  132049. _vq_quantlist__44c9_s_p3_0,
  132050. NULL,
  132051. &_vq_auxt__44c9_s_p3_0,
  132052. NULL,
  132053. 0
  132054. };
  132055. static long _vq_quantlist__44c9_s_p4_0[] = {
  132056. 8,
  132057. 7,
  132058. 9,
  132059. 6,
  132060. 10,
  132061. 5,
  132062. 11,
  132063. 4,
  132064. 12,
  132065. 3,
  132066. 13,
  132067. 2,
  132068. 14,
  132069. 1,
  132070. 15,
  132071. 0,
  132072. 16,
  132073. };
  132074. static long _vq_lengthlist__44c9_s_p4_0[] = {
  132075. 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9,10,10,10,
  132076. 10, 0, 5, 4, 5, 5, 7, 7, 8, 8, 8, 8, 9, 9,10,10,
  132077. 11,11, 0, 5, 5, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,
  132078. 10,11,11, 0, 6, 5, 6, 6, 7, 7, 8, 8, 9, 9,10,10,
  132079. 11,11,11,12, 0, 0, 0, 6, 6, 7, 7, 8, 8, 9, 9,10,
  132080. 10,11,11,12,12, 0, 0, 0, 7, 7, 7, 7, 9, 9, 9, 9,
  132081. 10,10,11,11,12,12, 0, 0, 0, 7, 7, 7, 8, 9, 9, 9,
  132082. 9,10,10,11,11,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9,
  132083. 10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 8, 8, 9,
  132084. 9,10,10,11,11,12,12,12,12, 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,
  132094. };
  132095. static float _vq_quantthresh__44c9_s_p4_0[] = {
  132096. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  132097. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  132098. };
  132099. static long _vq_quantmap__44c9_s_p4_0[] = {
  132100. 15, 13, 11, 9, 7, 5, 3, 1,
  132101. 0, 2, 4, 6, 8, 10, 12, 14,
  132102. 16,
  132103. };
  132104. static encode_aux_threshmatch _vq_auxt__44c9_s_p4_0 = {
  132105. _vq_quantthresh__44c9_s_p4_0,
  132106. _vq_quantmap__44c9_s_p4_0,
  132107. 17,
  132108. 17
  132109. };
  132110. static static_codebook _44c9_s_p4_0 = {
  132111. 2, 289,
  132112. _vq_lengthlist__44c9_s_p4_0,
  132113. 1, -529530880, 1611661312, 5, 0,
  132114. _vq_quantlist__44c9_s_p4_0,
  132115. NULL,
  132116. &_vq_auxt__44c9_s_p4_0,
  132117. NULL,
  132118. 0
  132119. };
  132120. static long _vq_quantlist__44c9_s_p5_0[] = {
  132121. 1,
  132122. 0,
  132123. 2,
  132124. };
  132125. static long _vq_lengthlist__44c9_s_p5_0[] = {
  132126. 1, 4, 4, 5, 7, 7, 6, 7, 7, 4, 7, 6, 9,10,10,10,
  132127. 10, 9, 4, 6, 7, 9,10,10,10, 9,10, 5, 9, 9, 9,11,
  132128. 11,10,11,11, 7,10, 9,11,12,11,12,12,12, 7, 9,10,
  132129. 11,11,12,12,12,12, 6,10,10,10,12,12,10,12,11, 7,
  132130. 10,10,11,12,12,11,12,12, 7,10,10,11,12,12,12,12,
  132131. 12,
  132132. };
  132133. static float _vq_quantthresh__44c9_s_p5_0[] = {
  132134. -5.5, 5.5,
  132135. };
  132136. static long _vq_quantmap__44c9_s_p5_0[] = {
  132137. 1, 0, 2,
  132138. };
  132139. static encode_aux_threshmatch _vq_auxt__44c9_s_p5_0 = {
  132140. _vq_quantthresh__44c9_s_p5_0,
  132141. _vq_quantmap__44c9_s_p5_0,
  132142. 3,
  132143. 3
  132144. };
  132145. static static_codebook _44c9_s_p5_0 = {
  132146. 4, 81,
  132147. _vq_lengthlist__44c9_s_p5_0,
  132148. 1, -529137664, 1618345984, 2, 0,
  132149. _vq_quantlist__44c9_s_p5_0,
  132150. NULL,
  132151. &_vq_auxt__44c9_s_p5_0,
  132152. NULL,
  132153. 0
  132154. };
  132155. static long _vq_quantlist__44c9_s_p5_1[] = {
  132156. 5,
  132157. 4,
  132158. 6,
  132159. 3,
  132160. 7,
  132161. 2,
  132162. 8,
  132163. 1,
  132164. 9,
  132165. 0,
  132166. 10,
  132167. };
  132168. static long _vq_lengthlist__44c9_s_p5_1[] = {
  132169. 4, 5, 5, 6, 6, 7, 7, 7, 7, 7, 7,11, 5, 5, 6, 6,
  132170. 7, 7, 7, 7, 8, 8,11, 5, 5, 6, 6, 7, 7, 7, 7, 8,
  132171. 8,11, 5, 5, 6, 6, 7, 7, 8, 8, 8, 8,11,11,11, 6,
  132172. 6, 7, 7, 7, 8, 8, 8,11,11,11, 6, 6, 7, 7, 7, 8,
  132173. 8, 8,11,11,11, 6, 6, 7, 7, 7, 7, 8, 8,11,11,11,
  132174. 7, 7, 7, 7, 7, 7, 8, 8,11,11,11,10,10, 7, 7, 7,
  132175. 7, 8, 8,11,11,11,11,11, 7, 7, 7, 7, 7, 7,11,11,
  132176. 11,11,11, 7, 7, 7, 7, 7, 7,
  132177. };
  132178. static float _vq_quantthresh__44c9_s_p5_1[] = {
  132179. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  132180. 3.5, 4.5,
  132181. };
  132182. static long _vq_quantmap__44c9_s_p5_1[] = {
  132183. 9, 7, 5, 3, 1, 0, 2, 4,
  132184. 6, 8, 10,
  132185. };
  132186. static encode_aux_threshmatch _vq_auxt__44c9_s_p5_1 = {
  132187. _vq_quantthresh__44c9_s_p5_1,
  132188. _vq_quantmap__44c9_s_p5_1,
  132189. 11,
  132190. 11
  132191. };
  132192. static static_codebook _44c9_s_p5_1 = {
  132193. 2, 121,
  132194. _vq_lengthlist__44c9_s_p5_1,
  132195. 1, -531365888, 1611661312, 4, 0,
  132196. _vq_quantlist__44c9_s_p5_1,
  132197. NULL,
  132198. &_vq_auxt__44c9_s_p5_1,
  132199. NULL,
  132200. 0
  132201. };
  132202. static long _vq_quantlist__44c9_s_p6_0[] = {
  132203. 6,
  132204. 5,
  132205. 7,
  132206. 4,
  132207. 8,
  132208. 3,
  132209. 9,
  132210. 2,
  132211. 10,
  132212. 1,
  132213. 11,
  132214. 0,
  132215. 12,
  132216. };
  132217. static long _vq_lengthlist__44c9_s_p6_0[] = {
  132218. 2, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8, 9, 9, 5, 4, 4,
  132219. 6, 6, 8, 8, 9, 9, 9, 9,10,10, 6, 4, 4, 6, 6, 8,
  132220. 8, 9, 9, 9, 9,10,10, 0, 6, 6, 7, 7, 8, 8, 9, 9,
  132221. 10,10,11,11, 0, 6, 6, 7, 7, 8, 8, 9, 9,10,10,11,
  132222. 11, 0,10,10, 8, 8, 9, 9,10,10,11,11,12,12, 0,11,
  132223. 11, 8, 8, 9, 9,10,10,11,11,12,12, 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,
  132229. };
  132230. static float _vq_quantthresh__44c9_s_p6_0[] = {
  132231. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  132232. 12.5, 17.5, 22.5, 27.5,
  132233. };
  132234. static long _vq_quantmap__44c9_s_p6_0[] = {
  132235. 11, 9, 7, 5, 3, 1, 0, 2,
  132236. 4, 6, 8, 10, 12,
  132237. };
  132238. static encode_aux_threshmatch _vq_auxt__44c9_s_p6_0 = {
  132239. _vq_quantthresh__44c9_s_p6_0,
  132240. _vq_quantmap__44c9_s_p6_0,
  132241. 13,
  132242. 13
  132243. };
  132244. static static_codebook _44c9_s_p6_0 = {
  132245. 2, 169,
  132246. _vq_lengthlist__44c9_s_p6_0,
  132247. 1, -526516224, 1616117760, 4, 0,
  132248. _vq_quantlist__44c9_s_p6_0,
  132249. NULL,
  132250. &_vq_auxt__44c9_s_p6_0,
  132251. NULL,
  132252. 0
  132253. };
  132254. static long _vq_quantlist__44c9_s_p6_1[] = {
  132255. 2,
  132256. 1,
  132257. 3,
  132258. 0,
  132259. 4,
  132260. };
  132261. static long _vq_lengthlist__44c9_s_p6_1[] = {
  132262. 4, 4, 4, 5, 5, 5, 4, 4, 5, 5, 5, 4, 4, 5, 5, 5,
  132263. 5, 5, 5, 5, 5, 5, 5, 5, 5,
  132264. };
  132265. static float _vq_quantthresh__44c9_s_p6_1[] = {
  132266. -1.5, -0.5, 0.5, 1.5,
  132267. };
  132268. static long _vq_quantmap__44c9_s_p6_1[] = {
  132269. 3, 1, 0, 2, 4,
  132270. };
  132271. static encode_aux_threshmatch _vq_auxt__44c9_s_p6_1 = {
  132272. _vq_quantthresh__44c9_s_p6_1,
  132273. _vq_quantmap__44c9_s_p6_1,
  132274. 5,
  132275. 5
  132276. };
  132277. static static_codebook _44c9_s_p6_1 = {
  132278. 2, 25,
  132279. _vq_lengthlist__44c9_s_p6_1,
  132280. 1, -533725184, 1611661312, 3, 0,
  132281. _vq_quantlist__44c9_s_p6_1,
  132282. NULL,
  132283. &_vq_auxt__44c9_s_p6_1,
  132284. NULL,
  132285. 0
  132286. };
  132287. static long _vq_quantlist__44c9_s_p7_0[] = {
  132288. 6,
  132289. 5,
  132290. 7,
  132291. 4,
  132292. 8,
  132293. 3,
  132294. 9,
  132295. 2,
  132296. 10,
  132297. 1,
  132298. 11,
  132299. 0,
  132300. 12,
  132301. };
  132302. static long _vq_lengthlist__44c9_s_p7_0[] = {
  132303. 2, 4, 4, 6, 6, 7, 7, 8, 8,10,10,11,11, 6, 4, 4,
  132304. 6, 6, 8, 8, 9, 9,10,10,12,12, 6, 4, 5, 6, 6, 8,
  132305. 8, 9, 9,10,10,12,12,20, 6, 6, 6, 6, 8, 8, 9,10,
  132306. 11,11,12,12,20, 6, 6, 6, 6, 8, 8,10,10,11,11,12,
  132307. 12,20,10,10, 7, 7, 9, 9,10,10,11,11,12,12,20,11,
  132308. 11, 7, 7, 9, 9,10,10,11,11,12,12,20,20,20, 9, 9,
  132309. 9, 9,11,11,12,12,13,13,20,20,20, 9, 9, 9, 9,11,
  132310. 11,12,12,13,13,20,20,20,13,13,10,10,11,11,12,13,
  132311. 13,13,20,20,20,13,13,10,10,11,11,12,13,13,13,20,
  132312. 20,20,20,19,12,12,12,12,13,13,14,15,19,19,19,19,
  132313. 19,12,12,12,12,13,13,14,14,
  132314. };
  132315. static float _vq_quantthresh__44c9_s_p7_0[] = {
  132316. -60.5, -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5,
  132317. 27.5, 38.5, 49.5, 60.5,
  132318. };
  132319. static long _vq_quantmap__44c9_s_p7_0[] = {
  132320. 11, 9, 7, 5, 3, 1, 0, 2,
  132321. 4, 6, 8, 10, 12,
  132322. };
  132323. static encode_aux_threshmatch _vq_auxt__44c9_s_p7_0 = {
  132324. _vq_quantthresh__44c9_s_p7_0,
  132325. _vq_quantmap__44c9_s_p7_0,
  132326. 13,
  132327. 13
  132328. };
  132329. static static_codebook _44c9_s_p7_0 = {
  132330. 2, 169,
  132331. _vq_lengthlist__44c9_s_p7_0,
  132332. 1, -523206656, 1618345984, 4, 0,
  132333. _vq_quantlist__44c9_s_p7_0,
  132334. NULL,
  132335. &_vq_auxt__44c9_s_p7_0,
  132336. NULL,
  132337. 0
  132338. };
  132339. static long _vq_quantlist__44c9_s_p7_1[] = {
  132340. 5,
  132341. 4,
  132342. 6,
  132343. 3,
  132344. 7,
  132345. 2,
  132346. 8,
  132347. 1,
  132348. 9,
  132349. 0,
  132350. 10,
  132351. };
  132352. static long _vq_lengthlist__44c9_s_p7_1[] = {
  132353. 5, 6, 6, 6, 6, 7, 7, 7, 7, 7, 7, 7, 6, 6, 6, 6,
  132354. 7, 7, 7, 7, 7, 7, 7, 6, 6, 6, 6, 7, 7, 7, 7, 7,
  132355. 7, 8, 6, 6, 6, 6, 7, 7, 7, 7, 7, 7, 8, 8, 8, 6,
  132356. 6, 7, 7, 7, 7, 7, 7, 8, 8, 8, 7, 7, 7, 7, 7, 7,
  132357. 7, 7, 8, 8, 8, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8,
  132358. 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8, 7, 7, 7,
  132359. 7, 7, 7, 8, 8, 8, 8, 8, 7, 7, 7, 7, 7, 7, 8, 8,
  132360. 8, 8, 8, 7, 7, 7, 7, 7, 7,
  132361. };
  132362. static float _vq_quantthresh__44c9_s_p7_1[] = {
  132363. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  132364. 3.5, 4.5,
  132365. };
  132366. static long _vq_quantmap__44c9_s_p7_1[] = {
  132367. 9, 7, 5, 3, 1, 0, 2, 4,
  132368. 6, 8, 10,
  132369. };
  132370. static encode_aux_threshmatch _vq_auxt__44c9_s_p7_1 = {
  132371. _vq_quantthresh__44c9_s_p7_1,
  132372. _vq_quantmap__44c9_s_p7_1,
  132373. 11,
  132374. 11
  132375. };
  132376. static static_codebook _44c9_s_p7_1 = {
  132377. 2, 121,
  132378. _vq_lengthlist__44c9_s_p7_1,
  132379. 1, -531365888, 1611661312, 4, 0,
  132380. _vq_quantlist__44c9_s_p7_1,
  132381. NULL,
  132382. &_vq_auxt__44c9_s_p7_1,
  132383. NULL,
  132384. 0
  132385. };
  132386. static long _vq_quantlist__44c9_s_p8_0[] = {
  132387. 7,
  132388. 6,
  132389. 8,
  132390. 5,
  132391. 9,
  132392. 4,
  132393. 10,
  132394. 3,
  132395. 11,
  132396. 2,
  132397. 12,
  132398. 1,
  132399. 13,
  132400. 0,
  132401. 14,
  132402. };
  132403. static long _vq_lengthlist__44c9_s_p8_0[] = {
  132404. 1, 4, 4, 7, 6, 8, 8, 8, 8, 9, 9,10,10,11,10, 6,
  132405. 5, 5, 7, 7, 9, 9, 8, 9,10,10,11,11,12,12, 6, 5,
  132406. 5, 7, 7, 9, 9, 9, 9,10,10,11,11,12,12,21, 7, 8,
  132407. 8, 8, 9, 9, 9, 9,10,10,11,11,12,12,21, 8, 8, 8,
  132408. 8, 9, 9, 9, 9,10,10,11,11,12,12,21,11,12, 9, 9,
  132409. 10,10,10,10,10,11,11,12,12,12,21,12,12, 9, 8,10,
  132410. 10,10,10,11,11,12,12,13,13,21,21,21, 9, 9, 9, 9,
  132411. 11,11,11,11,12,12,12,13,21,20,20, 9, 9, 9, 9,10,
  132412. 11,11,11,12,12,13,13,20,20,20,13,13,10,10,11,11,
  132413. 12,12,13,13,13,13,20,20,20,13,13,10,10,11,11,12,
  132414. 12,13,13,13,13,20,20,20,20,20,12,12,12,12,12,12,
  132415. 13,13,14,14,20,20,20,20,20,12,12,12,11,13,12,13,
  132416. 13,14,14,20,20,20,20,20,15,16,13,12,13,13,14,13,
  132417. 14,14,20,20,20,20,20,16,15,12,12,13,12,14,13,14,
  132418. 14,
  132419. };
  132420. static float _vq_quantthresh__44c9_s_p8_0[] = {
  132421. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  132422. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  132423. };
  132424. static long _vq_quantmap__44c9_s_p8_0[] = {
  132425. 13, 11, 9, 7, 5, 3, 1, 0,
  132426. 2, 4, 6, 8, 10, 12, 14,
  132427. };
  132428. static encode_aux_threshmatch _vq_auxt__44c9_s_p8_0 = {
  132429. _vq_quantthresh__44c9_s_p8_0,
  132430. _vq_quantmap__44c9_s_p8_0,
  132431. 15,
  132432. 15
  132433. };
  132434. static static_codebook _44c9_s_p8_0 = {
  132435. 2, 225,
  132436. _vq_lengthlist__44c9_s_p8_0,
  132437. 1, -520986624, 1620377600, 4, 0,
  132438. _vq_quantlist__44c9_s_p8_0,
  132439. NULL,
  132440. &_vq_auxt__44c9_s_p8_0,
  132441. NULL,
  132442. 0
  132443. };
  132444. static long _vq_quantlist__44c9_s_p8_1[] = {
  132445. 10,
  132446. 9,
  132447. 11,
  132448. 8,
  132449. 12,
  132450. 7,
  132451. 13,
  132452. 6,
  132453. 14,
  132454. 5,
  132455. 15,
  132456. 4,
  132457. 16,
  132458. 3,
  132459. 17,
  132460. 2,
  132461. 18,
  132462. 1,
  132463. 19,
  132464. 0,
  132465. 20,
  132466. };
  132467. static long _vq_lengthlist__44c9_s_p8_1[] = {
  132468. 4, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  132469. 8, 8, 8, 8, 8,10, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,
  132470. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 6, 6, 7, 7, 8,
  132471. 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,
  132472. 7, 7, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  132473. 9, 9, 9, 9,10,10,10, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  132474. 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10,10, 8, 8, 8, 8,
  132475. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10,
  132476. 10, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  132477. 9, 9, 9,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  132478. 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,10,10, 9, 9, 9,
  132479. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,
  132480. 10,10, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  132481. 9, 9,10,10,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  132482. 9, 9, 9, 9, 9, 9, 9,10,10,10,10,10, 9, 9, 9, 9,
  132483. 9, 9, 9, 9, 9, 9, 9, 9,10, 9, 9, 9,10,10,10,10,
  132484. 10,10,10, 9, 9, 9, 9, 9, 9,10, 9, 9, 9, 9, 9, 9,
  132485. 9,10,10,10,10,10,10,10, 9, 9, 9,10,10,10,10,10,
  132486. 9, 9, 9, 9, 9, 9,10,10,10,10,10,10,10, 9, 9,10,
  132487. 9,10, 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,10,10,10,
  132488. 10,10,10,10, 9, 9,10,10, 9, 9, 9, 9, 9, 9, 9, 9,
  132489. 10,10,10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9,
  132490. 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,10,10,
  132491. 10,10, 9, 9,10, 9, 9, 9, 9, 9,10,10,10,10,10,10,
  132492. 10,10,10,10,10, 9, 9,10,10, 9, 9,10, 9, 9, 9,10,
  132493. 10,10,10,10,10,10,10,10,10,10, 9, 9,10, 9, 9, 9,
  132494. 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,10,10, 9,
  132495. 9, 9, 9,10, 9, 9, 9, 9, 9,
  132496. };
  132497. static float _vq_quantthresh__44c9_s_p8_1[] = {
  132498. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  132499. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  132500. 6.5, 7.5, 8.5, 9.5,
  132501. };
  132502. static long _vq_quantmap__44c9_s_p8_1[] = {
  132503. 19, 17, 15, 13, 11, 9, 7, 5,
  132504. 3, 1, 0, 2, 4, 6, 8, 10,
  132505. 12, 14, 16, 18, 20,
  132506. };
  132507. static encode_aux_threshmatch _vq_auxt__44c9_s_p8_1 = {
  132508. _vq_quantthresh__44c9_s_p8_1,
  132509. _vq_quantmap__44c9_s_p8_1,
  132510. 21,
  132511. 21
  132512. };
  132513. static static_codebook _44c9_s_p8_1 = {
  132514. 2, 441,
  132515. _vq_lengthlist__44c9_s_p8_1,
  132516. 1, -529268736, 1611661312, 5, 0,
  132517. _vq_quantlist__44c9_s_p8_1,
  132518. NULL,
  132519. &_vq_auxt__44c9_s_p8_1,
  132520. NULL,
  132521. 0
  132522. };
  132523. static long _vq_quantlist__44c9_s_p9_0[] = {
  132524. 9,
  132525. 8,
  132526. 10,
  132527. 7,
  132528. 11,
  132529. 6,
  132530. 12,
  132531. 5,
  132532. 13,
  132533. 4,
  132534. 14,
  132535. 3,
  132536. 15,
  132537. 2,
  132538. 16,
  132539. 1,
  132540. 17,
  132541. 0,
  132542. 18,
  132543. };
  132544. static long _vq_lengthlist__44c9_s_p9_0[] = {
  132545. 1, 4, 3,12,12,12,12,12,12,12,12,12,12,12,12,12,
  132546. 12,12,12, 4, 5, 6,12,12,12,12,12,12,12,12,12,12,
  132547. 12,12,12,12,12,12, 4, 6, 6,12,12,12,12,12,12,12,
  132548. 12,12,12,12,12,12,12,12,12,12,12,11,12,12,12,12,
  132549. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  132550. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  132551. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  132552. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  132553. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  132554. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  132555. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  132556. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  132557. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  132558. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  132559. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  132560. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  132561. 12,12,12,12,12,12,12,12,12,12,11,11,11,11,11,11,
  132562. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  132563. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  132564. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  132565. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  132566. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  132567. 11,11,11,11,11,11,11,11,11,
  132568. };
  132569. static float _vq_quantthresh__44c9_s_p9_0[] = {
  132570. -7913.5, -6982.5, -6051.5, -5120.5, -4189.5, -3258.5, -2327.5, -1396.5,
  132571. -465.5, 465.5, 1396.5, 2327.5, 3258.5, 4189.5, 5120.5, 6051.5,
  132572. 6982.5, 7913.5,
  132573. };
  132574. static long _vq_quantmap__44c9_s_p9_0[] = {
  132575. 17, 15, 13, 11, 9, 7, 5, 3,
  132576. 1, 0, 2, 4, 6, 8, 10, 12,
  132577. 14, 16, 18,
  132578. };
  132579. static encode_aux_threshmatch _vq_auxt__44c9_s_p9_0 = {
  132580. _vq_quantthresh__44c9_s_p9_0,
  132581. _vq_quantmap__44c9_s_p9_0,
  132582. 19,
  132583. 19
  132584. };
  132585. static static_codebook _44c9_s_p9_0 = {
  132586. 2, 361,
  132587. _vq_lengthlist__44c9_s_p9_0,
  132588. 1, -508535424, 1631393792, 5, 0,
  132589. _vq_quantlist__44c9_s_p9_0,
  132590. NULL,
  132591. &_vq_auxt__44c9_s_p9_0,
  132592. NULL,
  132593. 0
  132594. };
  132595. static long _vq_quantlist__44c9_s_p9_1[] = {
  132596. 9,
  132597. 8,
  132598. 10,
  132599. 7,
  132600. 11,
  132601. 6,
  132602. 12,
  132603. 5,
  132604. 13,
  132605. 4,
  132606. 14,
  132607. 3,
  132608. 15,
  132609. 2,
  132610. 16,
  132611. 1,
  132612. 17,
  132613. 0,
  132614. 18,
  132615. };
  132616. static long _vq_lengthlist__44c9_s_p9_1[] = {
  132617. 1, 4, 4, 7, 7, 7, 7, 8, 7, 9, 8, 9, 9,10,10,11,
  132618. 11,11,11, 6, 5, 5, 8, 8, 9, 9, 9, 8,10, 9,11,10,
  132619. 12,12,13,12,13,13, 5, 5, 5, 8, 8, 9, 9, 9, 9,10,
  132620. 10,11,11,12,12,13,12,13,13,17, 8, 8, 9, 9, 9, 9,
  132621. 9, 9,10,10,12,11,13,12,13,13,13,13,18, 8, 8, 9,
  132622. 9, 9, 9, 9, 9,11,11,12,12,13,13,13,13,13,13,17,
  132623. 13,12, 9, 9,10,10,10,10,11,11,12,12,12,13,13,13,
  132624. 14,14,18,13,12, 9, 9,10,10,10,10,11,11,12,12,13,
  132625. 13,13,14,14,14,17,18,18,10,10,10,10,11,11,11,12,
  132626. 12,12,14,13,14,13,13,14,18,18,18,10, 9,10, 9,11,
  132627. 11,12,12,12,12,13,13,15,14,14,14,18,18,16,13,14,
  132628. 10,11,11,11,12,13,13,13,13,14,13,13,14,14,18,18,
  132629. 18,14,12,11, 9,11,10,13,12,13,13,13,14,14,14,13,
  132630. 14,18,18,17,18,18,11,12,12,12,13,13,14,13,14,14,
  132631. 13,14,14,14,18,18,18,18,17,12,10,12, 9,13,11,13,
  132632. 14,14,14,14,14,15,14,18,18,17,17,18,14,15,12,13,
  132633. 13,13,14,13,14,14,15,14,15,14,18,17,18,18,18,15,
  132634. 15,12,10,14,10,14,14,13,13,14,14,14,14,18,16,18,
  132635. 18,18,18,17,14,14,13,14,14,13,13,14,14,14,15,15,
  132636. 18,18,18,18,17,17,17,14,14,14,12,14,13,14,14,15,
  132637. 14,15,14,18,18,18,18,18,18,18,17,16,13,13,13,14,
  132638. 14,14,14,15,16,15,18,18,18,18,18,18,18,17,17,13,
  132639. 13,13,13,14,13,14,15,15,15,
  132640. };
  132641. static float _vq_quantthresh__44c9_s_p9_1[] = {
  132642. -416.5, -367.5, -318.5, -269.5, -220.5, -171.5, -122.5, -73.5,
  132643. -24.5, 24.5, 73.5, 122.5, 171.5, 220.5, 269.5, 318.5,
  132644. 367.5, 416.5,
  132645. };
  132646. static long _vq_quantmap__44c9_s_p9_1[] = {
  132647. 17, 15, 13, 11, 9, 7, 5, 3,
  132648. 1, 0, 2, 4, 6, 8, 10, 12,
  132649. 14, 16, 18,
  132650. };
  132651. static encode_aux_threshmatch _vq_auxt__44c9_s_p9_1 = {
  132652. _vq_quantthresh__44c9_s_p9_1,
  132653. _vq_quantmap__44c9_s_p9_1,
  132654. 19,
  132655. 19
  132656. };
  132657. static static_codebook _44c9_s_p9_1 = {
  132658. 2, 361,
  132659. _vq_lengthlist__44c9_s_p9_1,
  132660. 1, -518287360, 1622704128, 5, 0,
  132661. _vq_quantlist__44c9_s_p9_1,
  132662. NULL,
  132663. &_vq_auxt__44c9_s_p9_1,
  132664. NULL,
  132665. 0
  132666. };
  132667. static long _vq_quantlist__44c9_s_p9_2[] = {
  132668. 24,
  132669. 23,
  132670. 25,
  132671. 22,
  132672. 26,
  132673. 21,
  132674. 27,
  132675. 20,
  132676. 28,
  132677. 19,
  132678. 29,
  132679. 18,
  132680. 30,
  132681. 17,
  132682. 31,
  132683. 16,
  132684. 32,
  132685. 15,
  132686. 33,
  132687. 14,
  132688. 34,
  132689. 13,
  132690. 35,
  132691. 12,
  132692. 36,
  132693. 11,
  132694. 37,
  132695. 10,
  132696. 38,
  132697. 9,
  132698. 39,
  132699. 8,
  132700. 40,
  132701. 7,
  132702. 41,
  132703. 6,
  132704. 42,
  132705. 5,
  132706. 43,
  132707. 4,
  132708. 44,
  132709. 3,
  132710. 45,
  132711. 2,
  132712. 46,
  132713. 1,
  132714. 47,
  132715. 0,
  132716. 48,
  132717. };
  132718. static long _vq_lengthlist__44c9_s_p9_2[] = {
  132719. 2, 4, 4, 5, 5, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6, 6,
  132720. 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 7, 7, 7, 7, 7,
  132721. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  132722. 7,
  132723. };
  132724. static float _vq_quantthresh__44c9_s_p9_2[] = {
  132725. -23.5, -22.5, -21.5, -20.5, -19.5, -18.5, -17.5, -16.5,
  132726. -15.5, -14.5, -13.5, -12.5, -11.5, -10.5, -9.5, -8.5,
  132727. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  132728. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  132729. 8.5, 9.5, 10.5, 11.5, 12.5, 13.5, 14.5, 15.5,
  132730. 16.5, 17.5, 18.5, 19.5, 20.5, 21.5, 22.5, 23.5,
  132731. };
  132732. static long _vq_quantmap__44c9_s_p9_2[] = {
  132733. 47, 45, 43, 41, 39, 37, 35, 33,
  132734. 31, 29, 27, 25, 23, 21, 19, 17,
  132735. 15, 13, 11, 9, 7, 5, 3, 1,
  132736. 0, 2, 4, 6, 8, 10, 12, 14,
  132737. 16, 18, 20, 22, 24, 26, 28, 30,
  132738. 32, 34, 36, 38, 40, 42, 44, 46,
  132739. 48,
  132740. };
  132741. static encode_aux_threshmatch _vq_auxt__44c9_s_p9_2 = {
  132742. _vq_quantthresh__44c9_s_p9_2,
  132743. _vq_quantmap__44c9_s_p9_2,
  132744. 49,
  132745. 49
  132746. };
  132747. static static_codebook _44c9_s_p9_2 = {
  132748. 1, 49,
  132749. _vq_lengthlist__44c9_s_p9_2,
  132750. 1, -526909440, 1611661312, 6, 0,
  132751. _vq_quantlist__44c9_s_p9_2,
  132752. NULL,
  132753. &_vq_auxt__44c9_s_p9_2,
  132754. NULL,
  132755. 0
  132756. };
  132757. static long _huff_lengthlist__44c9_s_short[] = {
  132758. 5,13,18,16,17,17,19,18,19,19, 5, 7,10,11,12,12,
  132759. 13,16,17,18, 6, 6, 7, 7, 9, 9,10,14,17,19, 8, 7,
  132760. 6, 5, 6, 7, 9,12,19,17, 8, 7, 7, 6, 5, 6, 8,11,
  132761. 15,19, 9, 8, 7, 6, 5, 5, 6, 8,13,15,11,10, 8, 8,
  132762. 7, 5, 4, 4,10,14,12,13,11, 9, 7, 6, 4, 2, 6,12,
  132763. 18,16,16,13, 8, 7, 7, 5, 8,13,16,17,18,15,11, 9,
  132764. 9, 8,10,13,
  132765. };
  132766. static static_codebook _huff_book__44c9_s_short = {
  132767. 2, 100,
  132768. _huff_lengthlist__44c9_s_short,
  132769. 0, 0, 0, 0, 0,
  132770. NULL,
  132771. NULL,
  132772. NULL,
  132773. NULL,
  132774. 0
  132775. };
  132776. static long _huff_lengthlist__44c0_s_long[] = {
  132777. 5, 4, 8, 9, 8, 9,10,12,15, 4, 1, 5, 5, 6, 8,11,
  132778. 12,12, 8, 5, 8, 9, 9,11,13,12,12, 9, 5, 8, 5, 7,
  132779. 9,12,13,13, 8, 6, 8, 7, 7, 9,11,11,11, 9, 7, 9,
  132780. 7, 7, 7, 7,10,12,10,10,11, 9, 8, 7, 7, 9,11,11,
  132781. 12,13,12,11, 9, 8, 9,11,13,16,16,15,15,12,10,11,
  132782. 12,
  132783. };
  132784. static static_codebook _huff_book__44c0_s_long = {
  132785. 2, 81,
  132786. _huff_lengthlist__44c0_s_long,
  132787. 0, 0, 0, 0, 0,
  132788. NULL,
  132789. NULL,
  132790. NULL,
  132791. NULL,
  132792. 0
  132793. };
  132794. static long _vq_quantlist__44c0_s_p1_0[] = {
  132795. 1,
  132796. 0,
  132797. 2,
  132798. };
  132799. static long _vq_lengthlist__44c0_s_p1_0[] = {
  132800. 1, 5, 5, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  132801. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132802. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132803. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132804. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132805. 0, 5, 8, 7, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0, 0,
  132806. 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132807. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132808. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132809. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132810. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  132811. 0, 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132812. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132813. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132814. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132815. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132816. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132817. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132818. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132819. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132820. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132821. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132822. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132823. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132824. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132825. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132826. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132827. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132828. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132829. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132830. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132831. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132832. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132833. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132834. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132835. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132836. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132837. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132838. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132839. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132840. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132841. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132842. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132843. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132844. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132845. 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  132846. 0, 0, 8,10, 9, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  132847. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132848. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132849. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132850. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0, 0,
  132851. 0, 0, 0, 9,10,11, 0, 0, 0, 0, 0, 0, 9,11,10, 0,
  132852. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132853. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132854. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132855. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  132856. 0, 0, 0, 0, 9,11, 9, 0, 0, 0, 0, 0, 0, 9,10,11,
  132857. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132858. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132859. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132860. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132861. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132862. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132863. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132864. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132865. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132866. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132867. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132868. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132869. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132870. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132871. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132872. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132873. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132874. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132875. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132876. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132877. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132878. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132879. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132880. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132881. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132882. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132883. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132884. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132885. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132886. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132887. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132888. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132889. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132890. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132891. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  132892. 0, 0, 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132893. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132894. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132895. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132896. 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,11,10, 0,
  132897. 0, 0, 0, 0, 0, 9, 9,11, 0, 0, 0, 0, 0, 0, 0, 0,
  132898. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132899. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132900. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132901. 0, 0, 0, 0, 7, 9,10, 0, 0, 0, 0, 0, 0, 9,10,11,
  132902. 0, 0, 0, 0, 0, 0, 9,11,10, 0, 0, 0, 0, 0, 0, 0,
  132903. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132904. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132905. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132906. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132907. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132908. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132909. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132910. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132911. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132912. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132913. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132914. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132915. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132916. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132917. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132918. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132919. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132920. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132921. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132922. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132923. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132924. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132925. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132926. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132927. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132928. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132929. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132930. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132931. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132932. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132933. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132934. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132935. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132936. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132937. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132938. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132939. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132940. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132941. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132942. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132943. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132944. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132945. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132946. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132947. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132948. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132949. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132950. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132951. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132952. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132953. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132954. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132955. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132956. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132957. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132958. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132959. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132960. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132961. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132962. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132963. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132964. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132965. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132966. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132967. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132968. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132969. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132970. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132971. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132972. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132973. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132974. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132975. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132976. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132977. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132978. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132979. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132980. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132981. 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132986. 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132991. 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0,
  133026. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0,
  133031. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0,
  133036. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133072. 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133077. 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133082. 0, 0, 0, 0, 0, 0, 0, 0, 0, 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,
  133211. };
  133212. static float _vq_quantthresh__44c0_s_p1_0[] = {
  133213. -0.5, 0.5,
  133214. };
  133215. static long _vq_quantmap__44c0_s_p1_0[] = {
  133216. 1, 0, 2,
  133217. };
  133218. static encode_aux_threshmatch _vq_auxt__44c0_s_p1_0 = {
  133219. _vq_quantthresh__44c0_s_p1_0,
  133220. _vq_quantmap__44c0_s_p1_0,
  133221. 3,
  133222. 3
  133223. };
  133224. static static_codebook _44c0_s_p1_0 = {
  133225. 8, 6561,
  133226. _vq_lengthlist__44c0_s_p1_0,
  133227. 1, -535822336, 1611661312, 2, 0,
  133228. _vq_quantlist__44c0_s_p1_0,
  133229. NULL,
  133230. &_vq_auxt__44c0_s_p1_0,
  133231. NULL,
  133232. 0
  133233. };
  133234. static long _vq_quantlist__44c0_s_p2_0[] = {
  133235. 2,
  133236. 1,
  133237. 3,
  133238. 0,
  133239. 4,
  133240. };
  133241. static long _vq_lengthlist__44c0_s_p2_0[] = {
  133242. 1, 4, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133243. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 5, 5, 7, 6, 0, 0,
  133244. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133245. 0, 0, 4, 5, 6, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133246. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 7, 7, 9, 9,
  133247. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133248. 0, 0, 0, 0, 6, 7, 7, 9, 9, 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,
  133282. };
  133283. static float _vq_quantthresh__44c0_s_p2_0[] = {
  133284. -1.5, -0.5, 0.5, 1.5,
  133285. };
  133286. static long _vq_quantmap__44c0_s_p2_0[] = {
  133287. 3, 1, 0, 2, 4,
  133288. };
  133289. static encode_aux_threshmatch _vq_auxt__44c0_s_p2_0 = {
  133290. _vq_quantthresh__44c0_s_p2_0,
  133291. _vq_quantmap__44c0_s_p2_0,
  133292. 5,
  133293. 5
  133294. };
  133295. static static_codebook _44c0_s_p2_0 = {
  133296. 4, 625,
  133297. _vq_lengthlist__44c0_s_p2_0,
  133298. 1, -533725184, 1611661312, 3, 0,
  133299. _vq_quantlist__44c0_s_p2_0,
  133300. NULL,
  133301. &_vq_auxt__44c0_s_p2_0,
  133302. NULL,
  133303. 0
  133304. };
  133305. static long _vq_quantlist__44c0_s_p3_0[] = {
  133306. 4,
  133307. 3,
  133308. 5,
  133309. 2,
  133310. 6,
  133311. 1,
  133312. 7,
  133313. 0,
  133314. 8,
  133315. };
  133316. static long _vq_lengthlist__44c0_s_p3_0[] = {
  133317. 1, 3, 2, 8, 7, 0, 0, 0, 0, 0, 0, 0, 6, 6, 0, 0,
  133318. 0, 0, 0, 0, 0, 6, 6, 0, 0, 0, 0, 0, 0, 0, 7, 7,
  133319. 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0, 0, 0,
  133320. 8, 8, 0, 0, 0, 0, 0, 0, 0, 8, 8, 0, 0, 0, 0, 0,
  133321. 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133322. 0,
  133323. };
  133324. static float _vq_quantthresh__44c0_s_p3_0[] = {
  133325. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  133326. };
  133327. static long _vq_quantmap__44c0_s_p3_0[] = {
  133328. 7, 5, 3, 1, 0, 2, 4, 6,
  133329. 8,
  133330. };
  133331. static encode_aux_threshmatch _vq_auxt__44c0_s_p3_0 = {
  133332. _vq_quantthresh__44c0_s_p3_0,
  133333. _vq_quantmap__44c0_s_p3_0,
  133334. 9,
  133335. 9
  133336. };
  133337. static static_codebook _44c0_s_p3_0 = {
  133338. 2, 81,
  133339. _vq_lengthlist__44c0_s_p3_0,
  133340. 1, -531628032, 1611661312, 4, 0,
  133341. _vq_quantlist__44c0_s_p3_0,
  133342. NULL,
  133343. &_vq_auxt__44c0_s_p3_0,
  133344. NULL,
  133345. 0
  133346. };
  133347. static long _vq_quantlist__44c0_s_p4_0[] = {
  133348. 4,
  133349. 3,
  133350. 5,
  133351. 2,
  133352. 6,
  133353. 1,
  133354. 7,
  133355. 0,
  133356. 8,
  133357. };
  133358. static long _vq_lengthlist__44c0_s_p4_0[] = {
  133359. 1, 3, 3, 6, 6, 6, 6, 8, 8, 0, 0, 0, 7, 7, 7, 7,
  133360. 9, 9, 0, 0, 0, 7, 7, 7, 7, 9, 9, 0, 0, 0, 7, 7,
  133361. 7, 8, 9, 9, 0, 0, 0, 7, 7, 7, 7, 9, 9, 0, 0, 0,
  133362. 9, 9, 8, 8,10,10, 0, 0, 0, 8, 9, 8, 8,10,10, 0,
  133363. 0, 0,10,10, 9, 9,10,10, 0, 0, 0, 0, 0, 9, 9,10,
  133364. 10,
  133365. };
  133366. static float _vq_quantthresh__44c0_s_p4_0[] = {
  133367. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  133368. };
  133369. static long _vq_quantmap__44c0_s_p4_0[] = {
  133370. 7, 5, 3, 1, 0, 2, 4, 6,
  133371. 8,
  133372. };
  133373. static encode_aux_threshmatch _vq_auxt__44c0_s_p4_0 = {
  133374. _vq_quantthresh__44c0_s_p4_0,
  133375. _vq_quantmap__44c0_s_p4_0,
  133376. 9,
  133377. 9
  133378. };
  133379. static static_codebook _44c0_s_p4_0 = {
  133380. 2, 81,
  133381. _vq_lengthlist__44c0_s_p4_0,
  133382. 1, -531628032, 1611661312, 4, 0,
  133383. _vq_quantlist__44c0_s_p4_0,
  133384. NULL,
  133385. &_vq_auxt__44c0_s_p4_0,
  133386. NULL,
  133387. 0
  133388. };
  133389. static long _vq_quantlist__44c0_s_p5_0[] = {
  133390. 8,
  133391. 7,
  133392. 9,
  133393. 6,
  133394. 10,
  133395. 5,
  133396. 11,
  133397. 4,
  133398. 12,
  133399. 3,
  133400. 13,
  133401. 2,
  133402. 14,
  133403. 1,
  133404. 15,
  133405. 0,
  133406. 16,
  133407. };
  133408. static long _vq_lengthlist__44c0_s_p5_0[] = {
  133409. 1, 4, 3, 6, 6, 8, 7, 8, 8, 8, 8, 9, 9,10,10,11,
  133410. 11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9, 9,10,10,10,
  133411. 11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10,
  133412. 10,11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  133413. 11,11,11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,
  133414. 10,11,11,11,11, 0, 0, 0, 8, 8, 9, 9, 9, 9,10,10,
  133415. 10,10,11,11,12,12, 0, 0, 0, 8, 8, 9, 9, 9, 9,10,
  133416. 10,10,10,11,11,12,12, 0, 0, 0, 9, 9, 9, 9,10,10,
  133417. 10,10,11,11,11,12,12,12, 0, 0, 0, 0, 0, 9, 9,10,
  133418. 10,10,10,11,11,11,11,12,12, 0, 0, 0, 0, 0, 9, 9,
  133419. 10,10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9,
  133420. 9,10,10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0,
  133421. 10,10,11,11,11,11,11,12,12,12,13,13, 0, 0, 0, 0,
  133422. 0, 0, 0,11,10,11,11,11,11,12,12,13,13, 0, 0, 0,
  133423. 0, 0, 0, 0,11,11,12,11,12,12,12,12,13,13, 0, 0,
  133424. 0, 0, 0, 0, 0,11,11,11,12,12,12,12,13,13,13, 0,
  133425. 0, 0, 0, 0, 0, 0,12,12,12,12,12,13,13,13,14,14,
  133426. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,14,
  133427. 14,
  133428. };
  133429. static float _vq_quantthresh__44c0_s_p5_0[] = {
  133430. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  133431. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  133432. };
  133433. static long _vq_quantmap__44c0_s_p5_0[] = {
  133434. 15, 13, 11, 9, 7, 5, 3, 1,
  133435. 0, 2, 4, 6, 8, 10, 12, 14,
  133436. 16,
  133437. };
  133438. static encode_aux_threshmatch _vq_auxt__44c0_s_p5_0 = {
  133439. _vq_quantthresh__44c0_s_p5_0,
  133440. _vq_quantmap__44c0_s_p5_0,
  133441. 17,
  133442. 17
  133443. };
  133444. static static_codebook _44c0_s_p5_0 = {
  133445. 2, 289,
  133446. _vq_lengthlist__44c0_s_p5_0,
  133447. 1, -529530880, 1611661312, 5, 0,
  133448. _vq_quantlist__44c0_s_p5_0,
  133449. NULL,
  133450. &_vq_auxt__44c0_s_p5_0,
  133451. NULL,
  133452. 0
  133453. };
  133454. static long _vq_quantlist__44c0_s_p6_0[] = {
  133455. 1,
  133456. 0,
  133457. 2,
  133458. };
  133459. static long _vq_lengthlist__44c0_s_p6_0[] = {
  133460. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 7, 7,10, 9, 9,10,
  133461. 9, 9, 4, 6, 7,10, 9, 9,11, 9, 9, 7,10,10,11,11,
  133462. 11,12,10,11, 6, 9, 9,11,10,11,11,10,10, 6, 9, 9,
  133463. 11,10,11,11,10,10, 7,11,10,12,11,11,11,11,11, 7,
  133464. 9, 9,10,10,10,11,11,10, 6, 9, 9,11,10,10,11,10,
  133465. 10,
  133466. };
  133467. static float _vq_quantthresh__44c0_s_p6_0[] = {
  133468. -5.5, 5.5,
  133469. };
  133470. static long _vq_quantmap__44c0_s_p6_0[] = {
  133471. 1, 0, 2,
  133472. };
  133473. static encode_aux_threshmatch _vq_auxt__44c0_s_p6_0 = {
  133474. _vq_quantthresh__44c0_s_p6_0,
  133475. _vq_quantmap__44c0_s_p6_0,
  133476. 3,
  133477. 3
  133478. };
  133479. static static_codebook _44c0_s_p6_0 = {
  133480. 4, 81,
  133481. _vq_lengthlist__44c0_s_p6_0,
  133482. 1, -529137664, 1618345984, 2, 0,
  133483. _vq_quantlist__44c0_s_p6_0,
  133484. NULL,
  133485. &_vq_auxt__44c0_s_p6_0,
  133486. NULL,
  133487. 0
  133488. };
  133489. static long _vq_quantlist__44c0_s_p6_1[] = {
  133490. 5,
  133491. 4,
  133492. 6,
  133493. 3,
  133494. 7,
  133495. 2,
  133496. 8,
  133497. 1,
  133498. 9,
  133499. 0,
  133500. 10,
  133501. };
  133502. static long _vq_lengthlist__44c0_s_p6_1[] = {
  133503. 2, 3, 3, 6, 6, 7, 7, 7, 7, 7, 8,10,10,10, 6, 6,
  133504. 7, 7, 8, 8, 8, 8,10,10,10, 6, 6, 7, 7, 8, 8, 8,
  133505. 8,10,10,10, 7, 7, 7, 7, 8, 8, 8, 8,10,10,10, 7,
  133506. 7, 7, 7, 8, 8, 8, 8,10,10,10, 8, 7, 8, 8, 8, 8,
  133507. 8, 8,10,10,10, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10,
  133508. 8, 8, 8, 8, 8, 8, 8, 8,10,10,10,10,10, 8, 8, 8,
  133509. 8, 8, 8,10,10,10,10,10, 9, 9, 8, 8, 8, 8,10,10,
  133510. 10,10,10, 8, 8, 8, 8, 8, 8,
  133511. };
  133512. static float _vq_quantthresh__44c0_s_p6_1[] = {
  133513. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  133514. 3.5, 4.5,
  133515. };
  133516. static long _vq_quantmap__44c0_s_p6_1[] = {
  133517. 9, 7, 5, 3, 1, 0, 2, 4,
  133518. 6, 8, 10,
  133519. };
  133520. static encode_aux_threshmatch _vq_auxt__44c0_s_p6_1 = {
  133521. _vq_quantthresh__44c0_s_p6_1,
  133522. _vq_quantmap__44c0_s_p6_1,
  133523. 11,
  133524. 11
  133525. };
  133526. static static_codebook _44c0_s_p6_1 = {
  133527. 2, 121,
  133528. _vq_lengthlist__44c0_s_p6_1,
  133529. 1, -531365888, 1611661312, 4, 0,
  133530. _vq_quantlist__44c0_s_p6_1,
  133531. NULL,
  133532. &_vq_auxt__44c0_s_p6_1,
  133533. NULL,
  133534. 0
  133535. };
  133536. static long _vq_quantlist__44c0_s_p7_0[] = {
  133537. 6,
  133538. 5,
  133539. 7,
  133540. 4,
  133541. 8,
  133542. 3,
  133543. 9,
  133544. 2,
  133545. 10,
  133546. 1,
  133547. 11,
  133548. 0,
  133549. 12,
  133550. };
  133551. static long _vq_lengthlist__44c0_s_p7_0[] = {
  133552. 1, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8, 9, 9, 7, 5, 5,
  133553. 7, 7, 8, 8, 8, 8, 9, 9,10,10, 7, 5, 6, 7, 7, 8,
  133554. 8, 8, 8, 9, 9,10,10, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  133555. 10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  133556. 11, 0,12,12, 9, 9,10,10,10,10,11,11,11,11, 0,13,
  133557. 13, 9, 9, 9, 9,10,10,11,11,11,12, 0, 0, 0,10,10,
  133558. 10,10,11,11,11,11,12,12, 0, 0, 0,10,10, 9, 9,11,
  133559. 11,11,12,12,12, 0, 0, 0,13,13,10,10,11,11,12,12,
  133560. 13,13, 0, 0, 0,14,14,10,10,11,11,12,12,13,13, 0,
  133561. 0, 0, 0, 0,11,11,11,11,13,12,13,13, 0, 0, 0, 0,
  133562. 0,12,12,11,11,12,12,13,13,
  133563. };
  133564. static float _vq_quantthresh__44c0_s_p7_0[] = {
  133565. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  133566. 12.5, 17.5, 22.5, 27.5,
  133567. };
  133568. static long _vq_quantmap__44c0_s_p7_0[] = {
  133569. 11, 9, 7, 5, 3, 1, 0, 2,
  133570. 4, 6, 8, 10, 12,
  133571. };
  133572. static encode_aux_threshmatch _vq_auxt__44c0_s_p7_0 = {
  133573. _vq_quantthresh__44c0_s_p7_0,
  133574. _vq_quantmap__44c0_s_p7_0,
  133575. 13,
  133576. 13
  133577. };
  133578. static static_codebook _44c0_s_p7_0 = {
  133579. 2, 169,
  133580. _vq_lengthlist__44c0_s_p7_0,
  133581. 1, -526516224, 1616117760, 4, 0,
  133582. _vq_quantlist__44c0_s_p7_0,
  133583. NULL,
  133584. &_vq_auxt__44c0_s_p7_0,
  133585. NULL,
  133586. 0
  133587. };
  133588. static long _vq_quantlist__44c0_s_p7_1[] = {
  133589. 2,
  133590. 1,
  133591. 3,
  133592. 0,
  133593. 4,
  133594. };
  133595. static long _vq_lengthlist__44c0_s_p7_1[] = {
  133596. 2, 3, 3, 5, 5, 6, 6, 6, 5, 5, 6, 6, 6, 5, 5, 6,
  133597. 6, 6, 5, 5, 6, 6, 6, 5, 5,
  133598. };
  133599. static float _vq_quantthresh__44c0_s_p7_1[] = {
  133600. -1.5, -0.5, 0.5, 1.5,
  133601. };
  133602. static long _vq_quantmap__44c0_s_p7_1[] = {
  133603. 3, 1, 0, 2, 4,
  133604. };
  133605. static encode_aux_threshmatch _vq_auxt__44c0_s_p7_1 = {
  133606. _vq_quantthresh__44c0_s_p7_1,
  133607. _vq_quantmap__44c0_s_p7_1,
  133608. 5,
  133609. 5
  133610. };
  133611. static static_codebook _44c0_s_p7_1 = {
  133612. 2, 25,
  133613. _vq_lengthlist__44c0_s_p7_1,
  133614. 1, -533725184, 1611661312, 3, 0,
  133615. _vq_quantlist__44c0_s_p7_1,
  133616. NULL,
  133617. &_vq_auxt__44c0_s_p7_1,
  133618. NULL,
  133619. 0
  133620. };
  133621. static long _vq_quantlist__44c0_s_p8_0[] = {
  133622. 2,
  133623. 1,
  133624. 3,
  133625. 0,
  133626. 4,
  133627. };
  133628. static long _vq_lengthlist__44c0_s_p8_0[] = {
  133629. 1, 5, 5,10,10, 6, 9, 8,10,10, 6,10, 9,10,10,10,
  133630. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  133631. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  133632. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  133633. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  133634. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  133635. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  133636. 10,10,10,10,10,10,10,10,10,10,10,10,10, 8,10,10,
  133637. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  133638. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  133639. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  133640. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  133641. 10,10,10,10,10,10,10,10,11,11,11,11,11,11,11,11,
  133642. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  133643. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  133644. 11,11,11,11,11,11,11,11,11,11,10,11,11,11,11,11,
  133645. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  133646. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  133647. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  133648. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  133649. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  133650. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  133651. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  133652. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  133653. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  133654. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  133655. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  133656. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  133657. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  133658. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  133659. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  133660. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  133661. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  133662. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  133663. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  133664. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  133665. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  133666. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  133667. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  133668. 11,
  133669. };
  133670. static float _vq_quantthresh__44c0_s_p8_0[] = {
  133671. -331.5, -110.5, 110.5, 331.5,
  133672. };
  133673. static long _vq_quantmap__44c0_s_p8_0[] = {
  133674. 3, 1, 0, 2, 4,
  133675. };
  133676. static encode_aux_threshmatch _vq_auxt__44c0_s_p8_0 = {
  133677. _vq_quantthresh__44c0_s_p8_0,
  133678. _vq_quantmap__44c0_s_p8_0,
  133679. 5,
  133680. 5
  133681. };
  133682. static static_codebook _44c0_s_p8_0 = {
  133683. 4, 625,
  133684. _vq_lengthlist__44c0_s_p8_0,
  133685. 1, -518283264, 1627103232, 3, 0,
  133686. _vq_quantlist__44c0_s_p8_0,
  133687. NULL,
  133688. &_vq_auxt__44c0_s_p8_0,
  133689. NULL,
  133690. 0
  133691. };
  133692. static long _vq_quantlist__44c0_s_p8_1[] = {
  133693. 6,
  133694. 5,
  133695. 7,
  133696. 4,
  133697. 8,
  133698. 3,
  133699. 9,
  133700. 2,
  133701. 10,
  133702. 1,
  133703. 11,
  133704. 0,
  133705. 12,
  133706. };
  133707. static long _vq_lengthlist__44c0_s_p8_1[] = {
  133708. 1, 4, 4, 6, 6, 7, 7, 9, 9,11,12,13,12, 6, 5, 5,
  133709. 7, 7, 8, 8,10, 9,12,12,12,12, 6, 5, 5, 7, 7, 8,
  133710. 8,10, 9,12,11,11,13,16, 7, 7, 8, 8, 9, 9,10,10,
  133711. 12,12,13,12,16, 7, 7, 8, 7, 9, 9,10,10,11,12,12,
  133712. 13,16,10,10, 8, 8,10,10,11,12,12,12,13,13,16,11,
  133713. 10, 8, 7,11,10,11,11,12,11,13,13,16,16,16,10,10,
  133714. 10,10,11,11,13,12,13,13,16,16,16,11, 9,11, 9,15,
  133715. 13,12,13,13,13,16,16,16,15,13,11,11,12,13,12,12,
  133716. 14,13,16,16,16,14,13,11,11,13,12,14,13,13,13,16,
  133717. 16,16,16,16,13,13,13,12,14,13,14,14,16,16,16,16,
  133718. 16,13,13,12,12,14,14,15,13,
  133719. };
  133720. static float _vq_quantthresh__44c0_s_p8_1[] = {
  133721. -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5, 25.5,
  133722. 42.5, 59.5, 76.5, 93.5,
  133723. };
  133724. static long _vq_quantmap__44c0_s_p8_1[] = {
  133725. 11, 9, 7, 5, 3, 1, 0, 2,
  133726. 4, 6, 8, 10, 12,
  133727. };
  133728. static encode_aux_threshmatch _vq_auxt__44c0_s_p8_1 = {
  133729. _vq_quantthresh__44c0_s_p8_1,
  133730. _vq_quantmap__44c0_s_p8_1,
  133731. 13,
  133732. 13
  133733. };
  133734. static static_codebook _44c0_s_p8_1 = {
  133735. 2, 169,
  133736. _vq_lengthlist__44c0_s_p8_1,
  133737. 1, -522616832, 1620115456, 4, 0,
  133738. _vq_quantlist__44c0_s_p8_1,
  133739. NULL,
  133740. &_vq_auxt__44c0_s_p8_1,
  133741. NULL,
  133742. 0
  133743. };
  133744. static long _vq_quantlist__44c0_s_p8_2[] = {
  133745. 8,
  133746. 7,
  133747. 9,
  133748. 6,
  133749. 10,
  133750. 5,
  133751. 11,
  133752. 4,
  133753. 12,
  133754. 3,
  133755. 13,
  133756. 2,
  133757. 14,
  133758. 1,
  133759. 15,
  133760. 0,
  133761. 16,
  133762. };
  133763. static long _vq_lengthlist__44c0_s_p8_2[] = {
  133764. 2, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8,
  133765. 8,10,10,10, 7, 7, 7, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  133766. 9, 9,10,10,10, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9, 9,
  133767. 9, 9, 9,10,10,10, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9,
  133768. 9,10, 9, 9,10,10,10, 7, 7, 8, 8, 9, 8, 9, 9, 9,
  133769. 9,10, 9, 9,10,10,10,10, 8, 8, 8, 8, 9, 8, 9, 9,
  133770. 9, 9, 9,10, 9,10,10,10,10, 7, 7, 8, 8, 9, 9, 9,
  133771. 9, 9, 9,10, 9,10,10,10,10,10, 8, 8, 8, 9, 9, 9,
  133772. 9, 9, 9, 9,10,10,10, 9,11,10,10,10,10, 8, 8, 9,
  133773. 9, 9, 9, 9,10, 9, 9, 9,10,10,10,10,11,11, 9, 9,
  133774. 9, 9, 9, 9, 9, 9,10, 9, 9,10,11,10,10,11,11, 9,
  133775. 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 9,11,11,10,11,11,
  133776. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 9,11,10,10,11,
  133777. 11,11,11, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,
  133778. 11,11,11,11, 9,10, 9,10, 9, 9, 9, 9,10, 9,10,11,
  133779. 10,11,10,10,10,10,10, 9, 9, 9,10, 9, 9, 9,10,11,
  133780. 11,10,11,11,10,11,10,10,10, 9, 9, 9, 9,10, 9, 9,
  133781. 10,11,10,11,11,11,11,10,11,10,10, 9,10, 9, 9, 9,
  133782. 10,
  133783. };
  133784. static float _vq_quantthresh__44c0_s_p8_2[] = {
  133785. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  133786. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  133787. };
  133788. static long _vq_quantmap__44c0_s_p8_2[] = {
  133789. 15, 13, 11, 9, 7, 5, 3, 1,
  133790. 0, 2, 4, 6, 8, 10, 12, 14,
  133791. 16,
  133792. };
  133793. static encode_aux_threshmatch _vq_auxt__44c0_s_p8_2 = {
  133794. _vq_quantthresh__44c0_s_p8_2,
  133795. _vq_quantmap__44c0_s_p8_2,
  133796. 17,
  133797. 17
  133798. };
  133799. static static_codebook _44c0_s_p8_2 = {
  133800. 2, 289,
  133801. _vq_lengthlist__44c0_s_p8_2,
  133802. 1, -529530880, 1611661312, 5, 0,
  133803. _vq_quantlist__44c0_s_p8_2,
  133804. NULL,
  133805. &_vq_auxt__44c0_s_p8_2,
  133806. NULL,
  133807. 0
  133808. };
  133809. static long _huff_lengthlist__44c0_s_short[] = {
  133810. 9, 8,12,11,12,13,14,14,16, 6, 1, 5, 6, 6, 9,12,
  133811. 14,17, 9, 4, 5, 9, 7, 9,13,15,16, 8, 5, 8, 6, 8,
  133812. 10,13,17,17, 9, 6, 7, 7, 8, 9,13,15,17,11, 8, 9,
  133813. 9, 9,10,12,16,16,13, 7, 8, 7, 7, 9,12,14,15,13,
  133814. 6, 7, 5, 5, 7,10,13,13,14, 7, 8, 5, 6, 7, 9,10,
  133815. 12,
  133816. };
  133817. static static_codebook _huff_book__44c0_s_short = {
  133818. 2, 81,
  133819. _huff_lengthlist__44c0_s_short,
  133820. 0, 0, 0, 0, 0,
  133821. NULL,
  133822. NULL,
  133823. NULL,
  133824. NULL,
  133825. 0
  133826. };
  133827. static long _huff_lengthlist__44c0_sm_long[] = {
  133828. 5, 4, 9,10, 9,10,11,12,13, 4, 1, 5, 7, 7, 9,11,
  133829. 12,14, 8, 5, 7, 9, 8,10,13,13,13,10, 7, 9, 4, 6,
  133830. 7,10,12,14, 9, 6, 7, 6, 6, 7,10,12,12, 9, 8, 9,
  133831. 7, 6, 7, 8,11,12,11,11,11, 9, 8, 7, 8,10,12,12,
  133832. 13,14,12,11, 9, 9, 9,12,12,17,17,15,16,12,10,11,
  133833. 13,
  133834. };
  133835. static static_codebook _huff_book__44c0_sm_long = {
  133836. 2, 81,
  133837. _huff_lengthlist__44c0_sm_long,
  133838. 0, 0, 0, 0, 0,
  133839. NULL,
  133840. NULL,
  133841. NULL,
  133842. NULL,
  133843. 0
  133844. };
  133845. static long _vq_quantlist__44c0_sm_p1_0[] = {
  133846. 1,
  133847. 0,
  133848. 2,
  133849. };
  133850. static long _vq_lengthlist__44c0_sm_p1_0[] = {
  133851. 1, 5, 5, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  133852. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133853. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133854. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133855. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133856. 0, 5, 8, 7, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0, 0,
  133857. 0, 0, 0, 7, 8, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133858. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133859. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133860. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133861. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 9, 8, 0, 0,
  133862. 0, 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133863. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133864. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133865. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133866. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133867. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133868. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133869. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133870. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133871. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133872. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133873. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133874. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133875. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133876. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133877. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133878. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133879. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133880. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133881. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133882. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133883. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133884. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133885. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133886. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133887. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133888. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133889. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133890. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133891. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133892. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133893. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133894. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133895. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133896. 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 8, 7, 0, 0, 0, 0,
  133897. 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0,
  133898. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133899. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133900. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133901. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0, 0,
  133902. 0, 0, 0, 9,10,10, 0, 0, 0, 0, 0, 0, 9,10,10, 0,
  133903. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133904. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133905. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133906. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  133907. 0, 0, 0, 0, 8,10, 9, 0, 0, 0, 0, 0, 0, 9,10,10,
  133908. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133909. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133910. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133911. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133912. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133913. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133914. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133915. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133916. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133917. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133918. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133919. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133920. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133921. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133922. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133923. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133924. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133925. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133926. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133927. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133928. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133929. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133930. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133931. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133932. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133933. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133934. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133935. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133936. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133937. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133938. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133939. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133940. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133941. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133942. 0, 0, 5, 7, 8, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  133943. 0, 0, 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133944. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133945. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133946. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133947. 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,10,10, 0,
  133948. 0, 0, 0, 0, 0, 9, 9,10, 0, 0, 0, 0, 0, 0, 0, 0,
  133949. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133950. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133951. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133952. 0, 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,10,10,
  133953. 0, 0, 0, 0, 0, 0, 9,10,10, 0, 0, 0, 0, 0, 0, 0,
  133954. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133955. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133956. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133957. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133958. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133959. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133960. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133961. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133962. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133963. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133964. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133965. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133966. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133967. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133968. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133969. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133970. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133971. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133972. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133973. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133974. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133975. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133976. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133977. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133978. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133979. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133980. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133981. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133982. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133983. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133984. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133985. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133986. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133987. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133988. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133989. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133990. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133991. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133992. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133993. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133994. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133995. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133996. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133997. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133998. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133999. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134000. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134001. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134002. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134003. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134004. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134005. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134006. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134007. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134008. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134009. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134010. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134011. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134012. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134013. 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134018. 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134023. 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0,
  134058. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0,
  134063. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0,
  134068. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134104. 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134109. 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134114. 0, 0, 0, 0, 0, 0, 0, 0, 0, 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,
  134262. };
  134263. static float _vq_quantthresh__44c0_sm_p1_0[] = {
  134264. -0.5, 0.5,
  134265. };
  134266. static long _vq_quantmap__44c0_sm_p1_0[] = {
  134267. 1, 0, 2,
  134268. };
  134269. static encode_aux_threshmatch _vq_auxt__44c0_sm_p1_0 = {
  134270. _vq_quantthresh__44c0_sm_p1_0,
  134271. _vq_quantmap__44c0_sm_p1_0,
  134272. 3,
  134273. 3
  134274. };
  134275. static static_codebook _44c0_sm_p1_0 = {
  134276. 8, 6561,
  134277. _vq_lengthlist__44c0_sm_p1_0,
  134278. 1, -535822336, 1611661312, 2, 0,
  134279. _vq_quantlist__44c0_sm_p1_0,
  134280. NULL,
  134281. &_vq_auxt__44c0_sm_p1_0,
  134282. NULL,
  134283. 0
  134284. };
  134285. static long _vq_quantlist__44c0_sm_p2_0[] = {
  134286. 2,
  134287. 1,
  134288. 3,
  134289. 0,
  134290. 4,
  134291. };
  134292. static long _vq_lengthlist__44c0_sm_p2_0[] = {
  134293. 1, 4, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134294. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 5, 5, 7, 7, 0, 0,
  134295. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134296. 0, 0, 4, 5, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134297. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 7, 7, 9, 9,
  134298. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134299. 0, 0, 0, 0, 7, 7, 7, 9, 9, 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,
  134333. };
  134334. static float _vq_quantthresh__44c0_sm_p2_0[] = {
  134335. -1.5, -0.5, 0.5, 1.5,
  134336. };
  134337. static long _vq_quantmap__44c0_sm_p2_0[] = {
  134338. 3, 1, 0, 2, 4,
  134339. };
  134340. static encode_aux_threshmatch _vq_auxt__44c0_sm_p2_0 = {
  134341. _vq_quantthresh__44c0_sm_p2_0,
  134342. _vq_quantmap__44c0_sm_p2_0,
  134343. 5,
  134344. 5
  134345. };
  134346. static static_codebook _44c0_sm_p2_0 = {
  134347. 4, 625,
  134348. _vq_lengthlist__44c0_sm_p2_0,
  134349. 1, -533725184, 1611661312, 3, 0,
  134350. _vq_quantlist__44c0_sm_p2_0,
  134351. NULL,
  134352. &_vq_auxt__44c0_sm_p2_0,
  134353. NULL,
  134354. 0
  134355. };
  134356. static long _vq_quantlist__44c0_sm_p3_0[] = {
  134357. 4,
  134358. 3,
  134359. 5,
  134360. 2,
  134361. 6,
  134362. 1,
  134363. 7,
  134364. 0,
  134365. 8,
  134366. };
  134367. static long _vq_lengthlist__44c0_sm_p3_0[] = {
  134368. 1, 3, 3, 7, 7, 0, 0, 0, 0, 0, 5, 4, 7, 7, 0, 0,
  134369. 0, 0, 0, 5, 5, 7, 7, 0, 0, 0, 0, 0, 6, 7, 8, 8,
  134370. 0, 0, 0, 0, 0, 0, 0, 8, 8, 0, 0, 0, 0, 0, 0, 0,
  134371. 9,10, 0, 0, 0, 0, 0, 0, 0, 9, 9, 0, 0, 0, 0, 0,
  134372. 0, 0,11,11, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134373. 0,
  134374. };
  134375. static float _vq_quantthresh__44c0_sm_p3_0[] = {
  134376. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  134377. };
  134378. static long _vq_quantmap__44c0_sm_p3_0[] = {
  134379. 7, 5, 3, 1, 0, 2, 4, 6,
  134380. 8,
  134381. };
  134382. static encode_aux_threshmatch _vq_auxt__44c0_sm_p3_0 = {
  134383. _vq_quantthresh__44c0_sm_p3_0,
  134384. _vq_quantmap__44c0_sm_p3_0,
  134385. 9,
  134386. 9
  134387. };
  134388. static static_codebook _44c0_sm_p3_0 = {
  134389. 2, 81,
  134390. _vq_lengthlist__44c0_sm_p3_0,
  134391. 1, -531628032, 1611661312, 4, 0,
  134392. _vq_quantlist__44c0_sm_p3_0,
  134393. NULL,
  134394. &_vq_auxt__44c0_sm_p3_0,
  134395. NULL,
  134396. 0
  134397. };
  134398. static long _vq_quantlist__44c0_sm_p4_0[] = {
  134399. 4,
  134400. 3,
  134401. 5,
  134402. 2,
  134403. 6,
  134404. 1,
  134405. 7,
  134406. 0,
  134407. 8,
  134408. };
  134409. static long _vq_lengthlist__44c0_sm_p4_0[] = {
  134410. 1, 4, 3, 6, 6, 7, 7, 9, 9, 0, 5, 5, 7, 7, 8, 7,
  134411. 9, 9, 0, 5, 5, 7, 7, 8, 8, 9, 9, 0, 7, 7, 8, 8,
  134412. 8, 8,10,10, 0, 0, 0, 8, 8, 8, 8,10,10, 0, 0, 0,
  134413. 9, 9, 9, 9,11,11, 0, 0, 0, 9, 9, 9, 9,11,11, 0,
  134414. 0, 0,10,10,10,10,11,11, 0, 0, 0, 0, 0, 9, 9,11,
  134415. 11,
  134416. };
  134417. static float _vq_quantthresh__44c0_sm_p4_0[] = {
  134418. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  134419. };
  134420. static long _vq_quantmap__44c0_sm_p4_0[] = {
  134421. 7, 5, 3, 1, 0, 2, 4, 6,
  134422. 8,
  134423. };
  134424. static encode_aux_threshmatch _vq_auxt__44c0_sm_p4_0 = {
  134425. _vq_quantthresh__44c0_sm_p4_0,
  134426. _vq_quantmap__44c0_sm_p4_0,
  134427. 9,
  134428. 9
  134429. };
  134430. static static_codebook _44c0_sm_p4_0 = {
  134431. 2, 81,
  134432. _vq_lengthlist__44c0_sm_p4_0,
  134433. 1, -531628032, 1611661312, 4, 0,
  134434. _vq_quantlist__44c0_sm_p4_0,
  134435. NULL,
  134436. &_vq_auxt__44c0_sm_p4_0,
  134437. NULL,
  134438. 0
  134439. };
  134440. static long _vq_quantlist__44c0_sm_p5_0[] = {
  134441. 8,
  134442. 7,
  134443. 9,
  134444. 6,
  134445. 10,
  134446. 5,
  134447. 11,
  134448. 4,
  134449. 12,
  134450. 3,
  134451. 13,
  134452. 2,
  134453. 14,
  134454. 1,
  134455. 15,
  134456. 0,
  134457. 16,
  134458. };
  134459. static long _vq_lengthlist__44c0_sm_p5_0[] = {
  134460. 1, 4, 4, 6, 6, 8, 8, 8, 8, 8, 8, 9, 9,10,10,11,
  134461. 11, 0, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10,11,
  134462. 11,11, 0, 5, 6, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10,
  134463. 11,11,11, 0, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9,10,10,
  134464. 11,11,12,12, 0, 0, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,
  134465. 10,11,11,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,10,
  134466. 11,11,11,11,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,
  134467. 10,11,11,11,11,12,12, 0, 0, 0, 9, 9, 9, 9,10,10,
  134468. 10,10,11,11,12,12,12,13, 0, 0, 0, 0, 0, 9, 9,10,
  134469. 10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,
  134470. 10,10,11,11,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9,
  134471. 9,10,10,11,10,11,11,12,12,13,13, 0, 0, 0, 0, 0,
  134472. 10,10,10,10,11,11,12,12,12,13,13,13, 0, 0, 0, 0,
  134473. 0, 0, 0,10,10,11,11,12,12,12,13,13,13, 0, 0, 0,
  134474. 0, 0, 0, 0,11,11,12,12,12,12,13,13,14,14, 0, 0,
  134475. 0, 0, 0, 0, 0,11,11,12,11,12,12,13,13,13,13, 0,
  134476. 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,13,13,14,14,
  134477. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,14,
  134478. 14,
  134479. };
  134480. static float _vq_quantthresh__44c0_sm_p5_0[] = {
  134481. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  134482. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  134483. };
  134484. static long _vq_quantmap__44c0_sm_p5_0[] = {
  134485. 15, 13, 11, 9, 7, 5, 3, 1,
  134486. 0, 2, 4, 6, 8, 10, 12, 14,
  134487. 16,
  134488. };
  134489. static encode_aux_threshmatch _vq_auxt__44c0_sm_p5_0 = {
  134490. _vq_quantthresh__44c0_sm_p5_0,
  134491. _vq_quantmap__44c0_sm_p5_0,
  134492. 17,
  134493. 17
  134494. };
  134495. static static_codebook _44c0_sm_p5_0 = {
  134496. 2, 289,
  134497. _vq_lengthlist__44c0_sm_p5_0,
  134498. 1, -529530880, 1611661312, 5, 0,
  134499. _vq_quantlist__44c0_sm_p5_0,
  134500. NULL,
  134501. &_vq_auxt__44c0_sm_p5_0,
  134502. NULL,
  134503. 0
  134504. };
  134505. static long _vq_quantlist__44c0_sm_p6_0[] = {
  134506. 1,
  134507. 0,
  134508. 2,
  134509. };
  134510. static long _vq_lengthlist__44c0_sm_p6_0[] = {
  134511. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 7, 7,10, 9, 9,11,
  134512. 9, 9, 4, 7, 7,10, 9, 9,11, 9, 9, 7,10,10,10,11,
  134513. 11,11,10,10, 6, 9, 9,11,11,10,11,10,10, 6, 9, 9,
  134514. 11,10,11,11,10,10, 7,11,10,11,11,11,11,11,11, 6,
  134515. 9, 9,11,10,10,11,11,10, 6, 9, 9,11,10,10,11,10,
  134516. 11,
  134517. };
  134518. static float _vq_quantthresh__44c0_sm_p6_0[] = {
  134519. -5.5, 5.5,
  134520. };
  134521. static long _vq_quantmap__44c0_sm_p6_0[] = {
  134522. 1, 0, 2,
  134523. };
  134524. static encode_aux_threshmatch _vq_auxt__44c0_sm_p6_0 = {
  134525. _vq_quantthresh__44c0_sm_p6_0,
  134526. _vq_quantmap__44c0_sm_p6_0,
  134527. 3,
  134528. 3
  134529. };
  134530. static static_codebook _44c0_sm_p6_0 = {
  134531. 4, 81,
  134532. _vq_lengthlist__44c0_sm_p6_0,
  134533. 1, -529137664, 1618345984, 2, 0,
  134534. _vq_quantlist__44c0_sm_p6_0,
  134535. NULL,
  134536. &_vq_auxt__44c0_sm_p6_0,
  134537. NULL,
  134538. 0
  134539. };
  134540. static long _vq_quantlist__44c0_sm_p6_1[] = {
  134541. 5,
  134542. 4,
  134543. 6,
  134544. 3,
  134545. 7,
  134546. 2,
  134547. 8,
  134548. 1,
  134549. 9,
  134550. 0,
  134551. 10,
  134552. };
  134553. static long _vq_lengthlist__44c0_sm_p6_1[] = {
  134554. 2, 4, 4, 6, 6, 7, 7, 7, 7, 7, 8, 9, 5, 5, 6, 6,
  134555. 7, 7, 8, 8, 8, 8, 9, 5, 5, 6, 6, 7, 7, 8, 8, 8,
  134556. 8,10, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8,10,10,10, 7,
  134557. 7, 7, 7, 8, 8, 8, 8,10,10,10, 8, 8, 8, 8, 8, 8,
  134558. 8, 8,10,10,10, 8, 8, 8, 8, 8, 8, 8, 8,10,10,10,
  134559. 8, 8, 8, 8, 8, 8, 8, 8,10,10,10,10,10, 8, 8, 8,
  134560. 8, 8, 8,10,10,10,10,10, 9, 9, 8, 8, 8, 8,10,10,
  134561. 10,10,10, 8, 8, 8, 8, 8, 8,
  134562. };
  134563. static float _vq_quantthresh__44c0_sm_p6_1[] = {
  134564. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  134565. 3.5, 4.5,
  134566. };
  134567. static long _vq_quantmap__44c0_sm_p6_1[] = {
  134568. 9, 7, 5, 3, 1, 0, 2, 4,
  134569. 6, 8, 10,
  134570. };
  134571. static encode_aux_threshmatch _vq_auxt__44c0_sm_p6_1 = {
  134572. _vq_quantthresh__44c0_sm_p6_1,
  134573. _vq_quantmap__44c0_sm_p6_1,
  134574. 11,
  134575. 11
  134576. };
  134577. static static_codebook _44c0_sm_p6_1 = {
  134578. 2, 121,
  134579. _vq_lengthlist__44c0_sm_p6_1,
  134580. 1, -531365888, 1611661312, 4, 0,
  134581. _vq_quantlist__44c0_sm_p6_1,
  134582. NULL,
  134583. &_vq_auxt__44c0_sm_p6_1,
  134584. NULL,
  134585. 0
  134586. };
  134587. static long _vq_quantlist__44c0_sm_p7_0[] = {
  134588. 6,
  134589. 5,
  134590. 7,
  134591. 4,
  134592. 8,
  134593. 3,
  134594. 9,
  134595. 2,
  134596. 10,
  134597. 1,
  134598. 11,
  134599. 0,
  134600. 12,
  134601. };
  134602. static long _vq_lengthlist__44c0_sm_p7_0[] = {
  134603. 1, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8, 9, 9, 7, 5, 5,
  134604. 7, 7, 8, 8, 8, 8, 9, 9,10,10, 7, 6, 5, 7, 7, 8,
  134605. 8, 8, 8, 9, 9,10,10, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  134606. 10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  134607. 11, 0,12,12, 9, 9,10,10,10,10,11,11,11,11, 0,13,
  134608. 13, 9, 9, 9, 9,10,10,11,11,11,12, 0, 0, 0, 9,10,
  134609. 10,10,11,11,12,11,12,12, 0, 0, 0,10,10, 9, 9,11,
  134610. 11,12,12,12,12, 0, 0, 0,13,13,10,10,11,11,12,12,
  134611. 13,13, 0, 0, 0,14,14,10,10,11,11,12,12,13,13, 0,
  134612. 0, 0, 0, 0,11,12,11,11,13,12,13,13, 0, 0, 0, 0,
  134613. 0,12,12,11,11,13,12,14,14,
  134614. };
  134615. static float _vq_quantthresh__44c0_sm_p7_0[] = {
  134616. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  134617. 12.5, 17.5, 22.5, 27.5,
  134618. };
  134619. static long _vq_quantmap__44c0_sm_p7_0[] = {
  134620. 11, 9, 7, 5, 3, 1, 0, 2,
  134621. 4, 6, 8, 10, 12,
  134622. };
  134623. static encode_aux_threshmatch _vq_auxt__44c0_sm_p7_0 = {
  134624. _vq_quantthresh__44c0_sm_p7_0,
  134625. _vq_quantmap__44c0_sm_p7_0,
  134626. 13,
  134627. 13
  134628. };
  134629. static static_codebook _44c0_sm_p7_0 = {
  134630. 2, 169,
  134631. _vq_lengthlist__44c0_sm_p7_0,
  134632. 1, -526516224, 1616117760, 4, 0,
  134633. _vq_quantlist__44c0_sm_p7_0,
  134634. NULL,
  134635. &_vq_auxt__44c0_sm_p7_0,
  134636. NULL,
  134637. 0
  134638. };
  134639. static long _vq_quantlist__44c0_sm_p7_1[] = {
  134640. 2,
  134641. 1,
  134642. 3,
  134643. 0,
  134644. 4,
  134645. };
  134646. static long _vq_lengthlist__44c0_sm_p7_1[] = {
  134647. 2, 4, 4, 4, 4, 6, 5, 5, 5, 5, 6, 5, 5, 5, 5, 6,
  134648. 6, 6, 5, 5, 6, 6, 6, 5, 5,
  134649. };
  134650. static float _vq_quantthresh__44c0_sm_p7_1[] = {
  134651. -1.5, -0.5, 0.5, 1.5,
  134652. };
  134653. static long _vq_quantmap__44c0_sm_p7_1[] = {
  134654. 3, 1, 0, 2, 4,
  134655. };
  134656. static encode_aux_threshmatch _vq_auxt__44c0_sm_p7_1 = {
  134657. _vq_quantthresh__44c0_sm_p7_1,
  134658. _vq_quantmap__44c0_sm_p7_1,
  134659. 5,
  134660. 5
  134661. };
  134662. static static_codebook _44c0_sm_p7_1 = {
  134663. 2, 25,
  134664. _vq_lengthlist__44c0_sm_p7_1,
  134665. 1, -533725184, 1611661312, 3, 0,
  134666. _vq_quantlist__44c0_sm_p7_1,
  134667. NULL,
  134668. &_vq_auxt__44c0_sm_p7_1,
  134669. NULL,
  134670. 0
  134671. };
  134672. static long _vq_quantlist__44c0_sm_p8_0[] = {
  134673. 4,
  134674. 3,
  134675. 5,
  134676. 2,
  134677. 6,
  134678. 1,
  134679. 7,
  134680. 0,
  134681. 8,
  134682. };
  134683. static long _vq_lengthlist__44c0_sm_p8_0[] = {
  134684. 1, 3, 3,11,11,11,11,11,11, 3, 7, 6,11,11,11,11,
  134685. 11,11, 4, 8, 7,11,11,11,11,11,11,11,11,11,11,11,
  134686. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134687. 11,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  134688. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  134689. 12,
  134690. };
  134691. static float _vq_quantthresh__44c0_sm_p8_0[] = {
  134692. -773.5, -552.5, -331.5, -110.5, 110.5, 331.5, 552.5, 773.5,
  134693. };
  134694. static long _vq_quantmap__44c0_sm_p8_0[] = {
  134695. 7, 5, 3, 1, 0, 2, 4, 6,
  134696. 8,
  134697. };
  134698. static encode_aux_threshmatch _vq_auxt__44c0_sm_p8_0 = {
  134699. _vq_quantthresh__44c0_sm_p8_0,
  134700. _vq_quantmap__44c0_sm_p8_0,
  134701. 9,
  134702. 9
  134703. };
  134704. static static_codebook _44c0_sm_p8_0 = {
  134705. 2, 81,
  134706. _vq_lengthlist__44c0_sm_p8_0,
  134707. 1, -516186112, 1627103232, 4, 0,
  134708. _vq_quantlist__44c0_sm_p8_0,
  134709. NULL,
  134710. &_vq_auxt__44c0_sm_p8_0,
  134711. NULL,
  134712. 0
  134713. };
  134714. static long _vq_quantlist__44c0_sm_p8_1[] = {
  134715. 6,
  134716. 5,
  134717. 7,
  134718. 4,
  134719. 8,
  134720. 3,
  134721. 9,
  134722. 2,
  134723. 10,
  134724. 1,
  134725. 11,
  134726. 0,
  134727. 12,
  134728. };
  134729. static long _vq_lengthlist__44c0_sm_p8_1[] = {
  134730. 1, 4, 4, 6, 6, 7, 7, 9, 9,10,11,12,12, 6, 5, 5,
  134731. 7, 7, 8, 8,10,10,12,11,12,12, 6, 5, 5, 7, 7, 8,
  134732. 8,10,10,12,11,12,12,17, 7, 7, 8, 8, 9, 9,10,10,
  134733. 12,12,13,13,18, 7, 7, 8, 7, 9, 9,10,10,12,12,12,
  134734. 13,19,10,10, 8, 8,10,10,11,11,12,12,13,14,19,11,
  134735. 10, 8, 7,10,10,11,11,12,12,13,12,19,19,19,10,10,
  134736. 10,10,11,11,12,12,13,13,19,19,19,11, 9,11, 9,14,
  134737. 12,13,12,13,13,19,20,18,13,14,11,11,12,12,13,13,
  134738. 14,13,20,20,20,15,13,11,10,13,11,13,13,14,13,20,
  134739. 20,20,20,20,13,14,12,12,13,13,13,13,20,20,20,20,
  134740. 20,13,13,12,12,16,13,15,13,
  134741. };
  134742. static float _vq_quantthresh__44c0_sm_p8_1[] = {
  134743. -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5, 25.5,
  134744. 42.5, 59.5, 76.5, 93.5,
  134745. };
  134746. static long _vq_quantmap__44c0_sm_p8_1[] = {
  134747. 11, 9, 7, 5, 3, 1, 0, 2,
  134748. 4, 6, 8, 10, 12,
  134749. };
  134750. static encode_aux_threshmatch _vq_auxt__44c0_sm_p8_1 = {
  134751. _vq_quantthresh__44c0_sm_p8_1,
  134752. _vq_quantmap__44c0_sm_p8_1,
  134753. 13,
  134754. 13
  134755. };
  134756. static static_codebook _44c0_sm_p8_1 = {
  134757. 2, 169,
  134758. _vq_lengthlist__44c0_sm_p8_1,
  134759. 1, -522616832, 1620115456, 4, 0,
  134760. _vq_quantlist__44c0_sm_p8_1,
  134761. NULL,
  134762. &_vq_auxt__44c0_sm_p8_1,
  134763. NULL,
  134764. 0
  134765. };
  134766. static long _vq_quantlist__44c0_sm_p8_2[] = {
  134767. 8,
  134768. 7,
  134769. 9,
  134770. 6,
  134771. 10,
  134772. 5,
  134773. 11,
  134774. 4,
  134775. 12,
  134776. 3,
  134777. 13,
  134778. 2,
  134779. 14,
  134780. 1,
  134781. 15,
  134782. 0,
  134783. 16,
  134784. };
  134785. static long _vq_lengthlist__44c0_sm_p8_2[] = {
  134786. 2, 5, 5, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8,
  134787. 8,10, 6, 6, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9, 9, 9,
  134788. 9, 9,10, 6, 6, 7, 7, 8, 7, 8, 8, 9, 9, 9, 9, 9,
  134789. 9, 9, 9,10, 7, 7, 7, 7, 8, 8, 8, 9, 9, 9, 9, 9,
  134790. 9, 9, 9, 9,10,10,10, 7, 7, 8, 8, 9, 8, 9, 9, 9,
  134791. 9,10, 9, 9,10,10,10,11, 8, 8, 8, 8, 9, 9, 9, 9,
  134792. 9, 9, 9,10, 9,10,10,10,10, 8, 8, 8, 8, 9, 9, 9,
  134793. 9, 9, 9, 9, 9,10,10,11,10,10, 8, 8, 9, 9, 9, 9,
  134794. 9, 9, 9, 9, 9, 9,10,10,10,10,10,11,11, 8, 8, 9,
  134795. 9, 9, 9, 9, 9, 9, 9, 9,10,11,11,11,11,11, 9, 9,
  134796. 9, 9, 9, 9, 9, 9,10, 9,10, 9,11,11,10,11,11, 9,
  134797. 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 9,11,11,10,11,11,
  134798. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 9,11,10,11,11,
  134799. 11,11,11, 9, 9,10, 9, 9, 9, 9, 9, 9, 9,10,11,10,
  134800. 11,11,11,11,10,10,10,10, 9, 9, 9, 9, 9, 9,10,11,
  134801. 11,11,11,11,11, 9,10, 9, 9, 9, 9, 9, 9, 9, 9,11,
  134802. 11,10,11,11,11,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9,
  134803. 10,11,10,11,11,11,11,11,11, 9, 9, 9, 9, 9, 9, 9,
  134804. 9,
  134805. };
  134806. static float _vq_quantthresh__44c0_sm_p8_2[] = {
  134807. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  134808. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  134809. };
  134810. static long _vq_quantmap__44c0_sm_p8_2[] = {
  134811. 15, 13, 11, 9, 7, 5, 3, 1,
  134812. 0, 2, 4, 6, 8, 10, 12, 14,
  134813. 16,
  134814. };
  134815. static encode_aux_threshmatch _vq_auxt__44c0_sm_p8_2 = {
  134816. _vq_quantthresh__44c0_sm_p8_2,
  134817. _vq_quantmap__44c0_sm_p8_2,
  134818. 17,
  134819. 17
  134820. };
  134821. static static_codebook _44c0_sm_p8_2 = {
  134822. 2, 289,
  134823. _vq_lengthlist__44c0_sm_p8_2,
  134824. 1, -529530880, 1611661312, 5, 0,
  134825. _vq_quantlist__44c0_sm_p8_2,
  134826. NULL,
  134827. &_vq_auxt__44c0_sm_p8_2,
  134828. NULL,
  134829. 0
  134830. };
  134831. static long _huff_lengthlist__44c0_sm_short[] = {
  134832. 6, 6,12,13,13,14,16,17,17, 4, 2, 5, 8, 7, 9,12,
  134833. 15,15, 9, 4, 5, 9, 7, 9,12,16,18,11, 6, 7, 4, 6,
  134834. 8,11,14,18,10, 5, 6, 5, 5, 7,10,14,17,10, 5, 7,
  134835. 7, 6, 7,10,13,16,11, 5, 7, 7, 7, 8,10,12,15,13,
  134836. 6, 7, 5, 5, 7, 9,12,13,16, 8, 9, 6, 6, 7, 9,10,
  134837. 12,
  134838. };
  134839. static static_codebook _huff_book__44c0_sm_short = {
  134840. 2, 81,
  134841. _huff_lengthlist__44c0_sm_short,
  134842. 0, 0, 0, 0, 0,
  134843. NULL,
  134844. NULL,
  134845. NULL,
  134846. NULL,
  134847. 0
  134848. };
  134849. static long _huff_lengthlist__44c1_s_long[] = {
  134850. 5, 5, 9,10, 9, 9,10,11,12, 5, 1, 5, 6, 6, 7,10,
  134851. 12,14, 9, 5, 6, 8, 8,10,12,14,14,10, 5, 8, 5, 6,
  134852. 8,11,13,14, 9, 5, 7, 6, 6, 8,10,12,11, 9, 7, 9,
  134853. 7, 6, 6, 7,10,10,10, 9,12, 9, 8, 7, 7,10,12,11,
  134854. 11,13,12,10, 9, 8, 9,11,11,14,15,15,13,11, 9, 9,
  134855. 11,
  134856. };
  134857. static static_codebook _huff_book__44c1_s_long = {
  134858. 2, 81,
  134859. _huff_lengthlist__44c1_s_long,
  134860. 0, 0, 0, 0, 0,
  134861. NULL,
  134862. NULL,
  134863. NULL,
  134864. NULL,
  134865. 0
  134866. };
  134867. static long _vq_quantlist__44c1_s_p1_0[] = {
  134868. 1,
  134869. 0,
  134870. 2,
  134871. };
  134872. static long _vq_lengthlist__44c1_s_p1_0[] = {
  134873. 2, 4, 4, 0, 0, 0, 0, 0, 0, 5, 7, 6, 0, 0, 0, 0,
  134874. 0, 0, 5, 6, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134875. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134876. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134877. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134878. 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0, 0,
  134879. 0, 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134880. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134881. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134882. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134883. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0,
  134884. 0, 0, 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134885. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134886. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134887. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134888. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134889. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134890. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134891. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134892. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134893. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134894. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134895. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134896. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134897. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134898. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134899. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134900. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134901. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134902. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134903. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134904. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134905. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134906. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134907. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134908. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134909. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134910. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134911. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134912. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134913. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134914. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134915. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134916. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134917. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134918. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 7, 7, 0, 0, 0, 0,
  134919. 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0,
  134920. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134921. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134922. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134923. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0, 0,
  134924. 0, 0, 0, 8, 9,10, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0,
  134925. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134926. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134927. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134928. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 8, 8, 0, 0,
  134929. 0, 0, 0, 0, 8, 9, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9,
  134930. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134931. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134932. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134933. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134934. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134935. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134936. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134937. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134938. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134939. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134940. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134941. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134942. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134943. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134944. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134945. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134946. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134947. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134948. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134949. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134950. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134951. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134952. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134953. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134954. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134955. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134956. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134957. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134958. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134959. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134960. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134961. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134962. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134963. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134964. 0, 0, 4, 7, 7, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0,
  134965. 0, 0, 0, 0, 7, 8, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134966. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134967. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134968. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134969. 0, 0, 0, 6, 8, 8, 0, 0, 0, 0, 0, 0, 8,10, 9, 0,
  134970. 0, 0, 0, 0, 0, 8, 8, 9, 0, 0, 0, 0, 0, 0, 0, 0,
  134971. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134972. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134973. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134974. 0, 0, 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9,
  134975. 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 0,
  134976. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134977. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134978. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134979. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134980. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134981. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134982. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134983. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134984. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134985. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134986. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134987. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134988. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134989. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134990. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134991. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134992. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134993. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134994. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134995. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134996. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134997. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134998. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134999. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135000. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135001. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135002. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135003. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135004. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135005. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135006. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135007. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135008. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135009. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135010. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135011. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135012. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135013. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135014. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135015. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135016. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135017. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135018. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135019. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135020. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135021. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135022. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135023. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135024. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135025. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135026. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135027. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135028. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135029. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135030. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135031. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135032. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135033. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135034. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135035. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135036. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135037. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135038. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135039. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135040. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135041. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135042. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135043. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135044. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135045. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135046. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135047. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135048. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135049. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135050. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135051. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135052. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135053. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135054. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135055. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135056. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135057. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135058. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135059. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135060. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135061. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135062. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135063. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135064. 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135069. 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135074. 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0,
  135109. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0,
  135114. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0,
  135119. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135155. 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135160. 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135165. 0, 0, 0, 0, 0, 0, 0, 0, 0, 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,
  135284. };
  135285. static float _vq_quantthresh__44c1_s_p1_0[] = {
  135286. -0.5, 0.5,
  135287. };
  135288. static long _vq_quantmap__44c1_s_p1_0[] = {
  135289. 1, 0, 2,
  135290. };
  135291. static encode_aux_threshmatch _vq_auxt__44c1_s_p1_0 = {
  135292. _vq_quantthresh__44c1_s_p1_0,
  135293. _vq_quantmap__44c1_s_p1_0,
  135294. 3,
  135295. 3
  135296. };
  135297. static static_codebook _44c1_s_p1_0 = {
  135298. 8, 6561,
  135299. _vq_lengthlist__44c1_s_p1_0,
  135300. 1, -535822336, 1611661312, 2, 0,
  135301. _vq_quantlist__44c1_s_p1_0,
  135302. NULL,
  135303. &_vq_auxt__44c1_s_p1_0,
  135304. NULL,
  135305. 0
  135306. };
  135307. static long _vq_quantlist__44c1_s_p2_0[] = {
  135308. 2,
  135309. 1,
  135310. 3,
  135311. 0,
  135312. 4,
  135313. };
  135314. static long _vq_lengthlist__44c1_s_p2_0[] = {
  135315. 2, 3, 4, 6, 5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135316. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 4, 4, 6, 6, 0, 0,
  135317. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135318. 0, 0, 4, 4, 5, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135319. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 6, 6, 8, 8,
  135320. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135321. 0, 0, 0, 0, 6, 6, 6, 8, 8, 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,
  135355. };
  135356. static float _vq_quantthresh__44c1_s_p2_0[] = {
  135357. -1.5, -0.5, 0.5, 1.5,
  135358. };
  135359. static long _vq_quantmap__44c1_s_p2_0[] = {
  135360. 3, 1, 0, 2, 4,
  135361. };
  135362. static encode_aux_threshmatch _vq_auxt__44c1_s_p2_0 = {
  135363. _vq_quantthresh__44c1_s_p2_0,
  135364. _vq_quantmap__44c1_s_p2_0,
  135365. 5,
  135366. 5
  135367. };
  135368. static static_codebook _44c1_s_p2_0 = {
  135369. 4, 625,
  135370. _vq_lengthlist__44c1_s_p2_0,
  135371. 1, -533725184, 1611661312, 3, 0,
  135372. _vq_quantlist__44c1_s_p2_0,
  135373. NULL,
  135374. &_vq_auxt__44c1_s_p2_0,
  135375. NULL,
  135376. 0
  135377. };
  135378. static long _vq_quantlist__44c1_s_p3_0[] = {
  135379. 4,
  135380. 3,
  135381. 5,
  135382. 2,
  135383. 6,
  135384. 1,
  135385. 7,
  135386. 0,
  135387. 8,
  135388. };
  135389. static long _vq_lengthlist__44c1_s_p3_0[] = {
  135390. 1, 3, 2, 7, 7, 0, 0, 0, 0, 0,13,13, 6, 6, 0, 0,
  135391. 0, 0, 0,12, 0, 6, 6, 0, 0, 0, 0, 0, 0, 0, 7, 7,
  135392. 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0, 0, 0,
  135393. 8, 9, 0, 0, 0, 0, 0, 0, 0, 8, 8, 0, 0, 0, 0, 0,
  135394. 0, 0,11,10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135395. 0,
  135396. };
  135397. static float _vq_quantthresh__44c1_s_p3_0[] = {
  135398. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  135399. };
  135400. static long _vq_quantmap__44c1_s_p3_0[] = {
  135401. 7, 5, 3, 1, 0, 2, 4, 6,
  135402. 8,
  135403. };
  135404. static encode_aux_threshmatch _vq_auxt__44c1_s_p3_0 = {
  135405. _vq_quantthresh__44c1_s_p3_0,
  135406. _vq_quantmap__44c1_s_p3_0,
  135407. 9,
  135408. 9
  135409. };
  135410. static static_codebook _44c1_s_p3_0 = {
  135411. 2, 81,
  135412. _vq_lengthlist__44c1_s_p3_0,
  135413. 1, -531628032, 1611661312, 4, 0,
  135414. _vq_quantlist__44c1_s_p3_0,
  135415. NULL,
  135416. &_vq_auxt__44c1_s_p3_0,
  135417. NULL,
  135418. 0
  135419. };
  135420. static long _vq_quantlist__44c1_s_p4_0[] = {
  135421. 4,
  135422. 3,
  135423. 5,
  135424. 2,
  135425. 6,
  135426. 1,
  135427. 7,
  135428. 0,
  135429. 8,
  135430. };
  135431. static long _vq_lengthlist__44c1_s_p4_0[] = {
  135432. 1, 3, 3, 6, 5, 6, 6, 8, 8, 0, 0, 0, 7, 7, 7, 7,
  135433. 9, 9, 0, 0, 0, 7, 7, 7, 7, 9, 9, 0, 0, 0, 7, 7,
  135434. 8, 8,10,10, 0, 0, 0, 7, 7, 8, 8,10,10, 0, 0, 0,
  135435. 9, 9, 8, 8,10,10, 0, 0, 0, 8, 8, 8, 8,10,10, 0,
  135436. 0, 0,10,10, 9, 9,11,11, 0, 0, 0, 0, 0, 9, 9,11,
  135437. 11,
  135438. };
  135439. static float _vq_quantthresh__44c1_s_p4_0[] = {
  135440. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  135441. };
  135442. static long _vq_quantmap__44c1_s_p4_0[] = {
  135443. 7, 5, 3, 1, 0, 2, 4, 6,
  135444. 8,
  135445. };
  135446. static encode_aux_threshmatch _vq_auxt__44c1_s_p4_0 = {
  135447. _vq_quantthresh__44c1_s_p4_0,
  135448. _vq_quantmap__44c1_s_p4_0,
  135449. 9,
  135450. 9
  135451. };
  135452. static static_codebook _44c1_s_p4_0 = {
  135453. 2, 81,
  135454. _vq_lengthlist__44c1_s_p4_0,
  135455. 1, -531628032, 1611661312, 4, 0,
  135456. _vq_quantlist__44c1_s_p4_0,
  135457. NULL,
  135458. &_vq_auxt__44c1_s_p4_0,
  135459. NULL,
  135460. 0
  135461. };
  135462. static long _vq_quantlist__44c1_s_p5_0[] = {
  135463. 8,
  135464. 7,
  135465. 9,
  135466. 6,
  135467. 10,
  135468. 5,
  135469. 11,
  135470. 4,
  135471. 12,
  135472. 3,
  135473. 13,
  135474. 2,
  135475. 14,
  135476. 1,
  135477. 15,
  135478. 0,
  135479. 16,
  135480. };
  135481. static long _vq_lengthlist__44c1_s_p5_0[] = {
  135482. 1, 4, 3, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,10,11,
  135483. 11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10,10,
  135484. 11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10,
  135485. 10,11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  135486. 11,11,11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,
  135487. 10,11,11,12,11, 0, 0, 0, 8, 8, 9, 9, 9,10,10,10,
  135488. 10,10,11,11,12,12, 0, 0, 0, 8, 8, 9, 9,10, 9,10,
  135489. 10,10,10,11,11,12,12, 0, 0, 0, 9, 9, 9, 9,10,10,
  135490. 10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 9, 9,10,
  135491. 10,10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 9, 9,
  135492. 10,10,10,11,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9,
  135493. 9,10,10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0,
  135494. 10,10,10,10,11,11,12,12,12,12,13,13, 0, 0, 0, 0,
  135495. 0, 0, 0,10,10,11,11,12,12,12,12,13,13, 0, 0, 0,
  135496. 0, 0, 0, 0,11,11,12,12,12,12,13,13,13,13, 0, 0,
  135497. 0, 0, 0, 0, 0,11,11,11,11,12,12,13,13,13,13, 0,
  135498. 0, 0, 0, 0, 0, 0,12,12,12,12,12,12,13,13,14,14,
  135499. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,14,
  135500. 14,
  135501. };
  135502. static float _vq_quantthresh__44c1_s_p5_0[] = {
  135503. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  135504. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  135505. };
  135506. static long _vq_quantmap__44c1_s_p5_0[] = {
  135507. 15, 13, 11, 9, 7, 5, 3, 1,
  135508. 0, 2, 4, 6, 8, 10, 12, 14,
  135509. 16,
  135510. };
  135511. static encode_aux_threshmatch _vq_auxt__44c1_s_p5_0 = {
  135512. _vq_quantthresh__44c1_s_p5_0,
  135513. _vq_quantmap__44c1_s_p5_0,
  135514. 17,
  135515. 17
  135516. };
  135517. static static_codebook _44c1_s_p5_0 = {
  135518. 2, 289,
  135519. _vq_lengthlist__44c1_s_p5_0,
  135520. 1, -529530880, 1611661312, 5, 0,
  135521. _vq_quantlist__44c1_s_p5_0,
  135522. NULL,
  135523. &_vq_auxt__44c1_s_p5_0,
  135524. NULL,
  135525. 0
  135526. };
  135527. static long _vq_quantlist__44c1_s_p6_0[] = {
  135528. 1,
  135529. 0,
  135530. 2,
  135531. };
  135532. static long _vq_lengthlist__44c1_s_p6_0[] = {
  135533. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 7, 7,10, 9, 9,11,
  135534. 9, 9, 4, 7, 7,10, 9, 9,11, 9, 9, 6,10,10,11,11,
  135535. 11,11,10,10, 6, 9, 9,11,10,10,11,10,10, 6, 9, 9,
  135536. 11,10,11,11,10,10, 7,11,10,11,11,11,12,11,11, 7,
  135537. 9, 9,11,10,10,11,11,10, 6, 9, 9,10,10,10,12,10,
  135538. 11,
  135539. };
  135540. static float _vq_quantthresh__44c1_s_p6_0[] = {
  135541. -5.5, 5.5,
  135542. };
  135543. static long _vq_quantmap__44c1_s_p6_0[] = {
  135544. 1, 0, 2,
  135545. };
  135546. static encode_aux_threshmatch _vq_auxt__44c1_s_p6_0 = {
  135547. _vq_quantthresh__44c1_s_p6_0,
  135548. _vq_quantmap__44c1_s_p6_0,
  135549. 3,
  135550. 3
  135551. };
  135552. static static_codebook _44c1_s_p6_0 = {
  135553. 4, 81,
  135554. _vq_lengthlist__44c1_s_p6_0,
  135555. 1, -529137664, 1618345984, 2, 0,
  135556. _vq_quantlist__44c1_s_p6_0,
  135557. NULL,
  135558. &_vq_auxt__44c1_s_p6_0,
  135559. NULL,
  135560. 0
  135561. };
  135562. static long _vq_quantlist__44c1_s_p6_1[] = {
  135563. 5,
  135564. 4,
  135565. 6,
  135566. 3,
  135567. 7,
  135568. 2,
  135569. 8,
  135570. 1,
  135571. 9,
  135572. 0,
  135573. 10,
  135574. };
  135575. static long _vq_lengthlist__44c1_s_p6_1[] = {
  135576. 2, 3, 3, 6, 6, 7, 7, 7, 7, 8, 8,10,10,10, 6, 6,
  135577. 7, 7, 8, 8, 8, 8,10,10,10, 6, 6, 7, 7, 8, 8, 8,
  135578. 8,10,10,10, 7, 7, 7, 7, 8, 8, 8, 8,10,10,10, 7,
  135579. 7, 7, 7, 8, 8, 8, 8,10,10,10, 7, 7, 8, 8, 8, 8,
  135580. 8, 8,10,10,10, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10,
  135581. 8, 8, 8, 8, 8, 8, 8, 8,10,10,10,10,10, 8, 8, 8,
  135582. 8, 8, 8,10,10,10,10,10, 9, 9, 8, 8, 8, 8,10,10,
  135583. 10,10,10, 8, 8, 8, 8, 8, 8,
  135584. };
  135585. static float _vq_quantthresh__44c1_s_p6_1[] = {
  135586. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  135587. 3.5, 4.5,
  135588. };
  135589. static long _vq_quantmap__44c1_s_p6_1[] = {
  135590. 9, 7, 5, 3, 1, 0, 2, 4,
  135591. 6, 8, 10,
  135592. };
  135593. static encode_aux_threshmatch _vq_auxt__44c1_s_p6_1 = {
  135594. _vq_quantthresh__44c1_s_p6_1,
  135595. _vq_quantmap__44c1_s_p6_1,
  135596. 11,
  135597. 11
  135598. };
  135599. static static_codebook _44c1_s_p6_1 = {
  135600. 2, 121,
  135601. _vq_lengthlist__44c1_s_p6_1,
  135602. 1, -531365888, 1611661312, 4, 0,
  135603. _vq_quantlist__44c1_s_p6_1,
  135604. NULL,
  135605. &_vq_auxt__44c1_s_p6_1,
  135606. NULL,
  135607. 0
  135608. };
  135609. static long _vq_quantlist__44c1_s_p7_0[] = {
  135610. 6,
  135611. 5,
  135612. 7,
  135613. 4,
  135614. 8,
  135615. 3,
  135616. 9,
  135617. 2,
  135618. 10,
  135619. 1,
  135620. 11,
  135621. 0,
  135622. 12,
  135623. };
  135624. static long _vq_lengthlist__44c1_s_p7_0[] = {
  135625. 1, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8,10, 9, 7, 5, 6,
  135626. 7, 7, 8, 8, 8, 8, 9, 9,10,10, 7, 5, 5, 7, 7, 8,
  135627. 8, 8, 8, 9, 9,10,10, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  135628. 10,10,11,10, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  135629. 11, 0,12,12, 9, 9, 9,10,10,10,11,11,11,11, 0,13,
  135630. 13, 9, 9, 9, 9,10,10,11,11,11,11, 0, 0, 0,10,10,
  135631. 10,10,11,11,12,11,12,12, 0, 0, 0,10,10,10, 9,11,
  135632. 11,12,11,13,12, 0, 0, 0,13,13,10,10,11,11,12,12,
  135633. 13,13, 0, 0, 0,14,14,10,10,11,11,12,12,13,13, 0,
  135634. 0, 0, 0, 0,11,12,11,11,12,12,14,13, 0, 0, 0, 0,
  135635. 0,12,11,11,11,13,10,14,13,
  135636. };
  135637. static float _vq_quantthresh__44c1_s_p7_0[] = {
  135638. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  135639. 12.5, 17.5, 22.5, 27.5,
  135640. };
  135641. static long _vq_quantmap__44c1_s_p7_0[] = {
  135642. 11, 9, 7, 5, 3, 1, 0, 2,
  135643. 4, 6, 8, 10, 12,
  135644. };
  135645. static encode_aux_threshmatch _vq_auxt__44c1_s_p7_0 = {
  135646. _vq_quantthresh__44c1_s_p7_0,
  135647. _vq_quantmap__44c1_s_p7_0,
  135648. 13,
  135649. 13
  135650. };
  135651. static static_codebook _44c1_s_p7_0 = {
  135652. 2, 169,
  135653. _vq_lengthlist__44c1_s_p7_0,
  135654. 1, -526516224, 1616117760, 4, 0,
  135655. _vq_quantlist__44c1_s_p7_0,
  135656. NULL,
  135657. &_vq_auxt__44c1_s_p7_0,
  135658. NULL,
  135659. 0
  135660. };
  135661. static long _vq_quantlist__44c1_s_p7_1[] = {
  135662. 2,
  135663. 1,
  135664. 3,
  135665. 0,
  135666. 4,
  135667. };
  135668. static long _vq_lengthlist__44c1_s_p7_1[] = {
  135669. 2, 3, 3, 5, 5, 6, 6, 6, 5, 5, 6, 6, 6, 5, 5, 6,
  135670. 6, 6, 5, 5, 6, 6, 6, 5, 5,
  135671. };
  135672. static float _vq_quantthresh__44c1_s_p7_1[] = {
  135673. -1.5, -0.5, 0.5, 1.5,
  135674. };
  135675. static long _vq_quantmap__44c1_s_p7_1[] = {
  135676. 3, 1, 0, 2, 4,
  135677. };
  135678. static encode_aux_threshmatch _vq_auxt__44c1_s_p7_1 = {
  135679. _vq_quantthresh__44c1_s_p7_1,
  135680. _vq_quantmap__44c1_s_p7_1,
  135681. 5,
  135682. 5
  135683. };
  135684. static static_codebook _44c1_s_p7_1 = {
  135685. 2, 25,
  135686. _vq_lengthlist__44c1_s_p7_1,
  135687. 1, -533725184, 1611661312, 3, 0,
  135688. _vq_quantlist__44c1_s_p7_1,
  135689. NULL,
  135690. &_vq_auxt__44c1_s_p7_1,
  135691. NULL,
  135692. 0
  135693. };
  135694. static long _vq_quantlist__44c1_s_p8_0[] = {
  135695. 6,
  135696. 5,
  135697. 7,
  135698. 4,
  135699. 8,
  135700. 3,
  135701. 9,
  135702. 2,
  135703. 10,
  135704. 1,
  135705. 11,
  135706. 0,
  135707. 12,
  135708. };
  135709. static long _vq_lengthlist__44c1_s_p8_0[] = {
  135710. 1, 4, 3,10,10,10,10,10,10,10,10,10,10, 4, 8, 6,
  135711. 10,10,10,10,10,10,10,10,10,10, 4, 8, 7,10,10,10,
  135712. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  135713. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  135714. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  135715. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  135716. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  135717. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  135718. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  135719. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  135720. 10,10,10,10,10,10,10,10,10,
  135721. };
  135722. static float _vq_quantthresh__44c1_s_p8_0[] = {
  135723. -1215.5, -994.5, -773.5, -552.5, -331.5, -110.5, 110.5, 331.5,
  135724. 552.5, 773.5, 994.5, 1215.5,
  135725. };
  135726. static long _vq_quantmap__44c1_s_p8_0[] = {
  135727. 11, 9, 7, 5, 3, 1, 0, 2,
  135728. 4, 6, 8, 10, 12,
  135729. };
  135730. static encode_aux_threshmatch _vq_auxt__44c1_s_p8_0 = {
  135731. _vq_quantthresh__44c1_s_p8_0,
  135732. _vq_quantmap__44c1_s_p8_0,
  135733. 13,
  135734. 13
  135735. };
  135736. static static_codebook _44c1_s_p8_0 = {
  135737. 2, 169,
  135738. _vq_lengthlist__44c1_s_p8_0,
  135739. 1, -514541568, 1627103232, 4, 0,
  135740. _vq_quantlist__44c1_s_p8_0,
  135741. NULL,
  135742. &_vq_auxt__44c1_s_p8_0,
  135743. NULL,
  135744. 0
  135745. };
  135746. static long _vq_quantlist__44c1_s_p8_1[] = {
  135747. 6,
  135748. 5,
  135749. 7,
  135750. 4,
  135751. 8,
  135752. 3,
  135753. 9,
  135754. 2,
  135755. 10,
  135756. 1,
  135757. 11,
  135758. 0,
  135759. 12,
  135760. };
  135761. static long _vq_lengthlist__44c1_s_p8_1[] = {
  135762. 1, 4, 4, 6, 5, 7, 7, 9, 9,10,10,12,12, 6, 5, 5,
  135763. 7, 7, 8, 8,10,10,12,11,12,12, 6, 5, 5, 7, 7, 8,
  135764. 8,10,10,11,11,12,12,15, 7, 7, 8, 8, 9, 9,11,11,
  135765. 12,12,13,12,15, 8, 8, 8, 7, 9, 9,10,10,12,12,13,
  135766. 13,16,11,10, 8, 8,10,10,11,11,12,12,13,13,16,11,
  135767. 11, 9, 8,11,10,11,11,12,12,13,12,16,16,16,10,11,
  135768. 10,11,12,12,12,12,13,13,16,16,16,11, 9,11, 9,14,
  135769. 12,12,12,13,13,16,16,16,12,14,11,12,12,12,13,13,
  135770. 14,13,16,16,16,15,13,12,10,13,10,13,14,13,13,16,
  135771. 16,16,16,16,13,14,12,13,13,12,13,13,16,16,16,16,
  135772. 16,13,12,12,11,14,12,15,13,
  135773. };
  135774. static float _vq_quantthresh__44c1_s_p8_1[] = {
  135775. -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5, 25.5,
  135776. 42.5, 59.5, 76.5, 93.5,
  135777. };
  135778. static long _vq_quantmap__44c1_s_p8_1[] = {
  135779. 11, 9, 7, 5, 3, 1, 0, 2,
  135780. 4, 6, 8, 10, 12,
  135781. };
  135782. static encode_aux_threshmatch _vq_auxt__44c1_s_p8_1 = {
  135783. _vq_quantthresh__44c1_s_p8_1,
  135784. _vq_quantmap__44c1_s_p8_1,
  135785. 13,
  135786. 13
  135787. };
  135788. static static_codebook _44c1_s_p8_1 = {
  135789. 2, 169,
  135790. _vq_lengthlist__44c1_s_p8_1,
  135791. 1, -522616832, 1620115456, 4, 0,
  135792. _vq_quantlist__44c1_s_p8_1,
  135793. NULL,
  135794. &_vq_auxt__44c1_s_p8_1,
  135795. NULL,
  135796. 0
  135797. };
  135798. static long _vq_quantlist__44c1_s_p8_2[] = {
  135799. 8,
  135800. 7,
  135801. 9,
  135802. 6,
  135803. 10,
  135804. 5,
  135805. 11,
  135806. 4,
  135807. 12,
  135808. 3,
  135809. 13,
  135810. 2,
  135811. 14,
  135812. 1,
  135813. 15,
  135814. 0,
  135815. 16,
  135816. };
  135817. static long _vq_lengthlist__44c1_s_p8_2[] = {
  135818. 2, 4, 4, 6, 6, 6, 6, 7, 7, 8, 8, 8, 8, 8, 8, 8,
  135819. 8,10,10,10, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9, 9, 9,
  135820. 9, 9,10,10,10, 7, 7, 8, 7, 8, 8, 9, 9, 9, 9, 9,
  135821. 9, 9, 9,10,10,10, 7, 7, 8, 8, 8, 9, 9, 9, 9, 9,
  135822. 9,10, 9, 9,10,10,10, 7, 7, 8, 8, 9, 8, 9, 9, 9,
  135823. 9,10, 9, 9,10,10,11,11, 8, 8, 8, 8, 9, 9, 9, 9,
  135824. 9, 9,10, 9, 9,10,10,10,10, 8, 8, 8, 8, 9, 9, 9,
  135825. 9, 9, 9, 9, 9,10,10,11,11,11, 8, 8, 9, 9, 9, 9,
  135826. 9, 9, 9, 9, 9, 9,10,10,10,10,11,11,11, 8, 8, 9,
  135827. 9, 9, 9,10, 9, 9, 9, 9, 9,11,11,11,11,11, 9, 9,
  135828. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,11,10,10,11,11, 9,
  135829. 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,10,11,10,11,11,
  135830. 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10, 9,10,10,11,11,
  135831. 11,11,11, 9, 9, 9,10, 9, 9, 9, 9, 9, 9,10,11,11,
  135832. 11,11,11,11,10,10,10,10, 9, 9, 9, 9, 9, 9,10,11,
  135833. 11,11,11,11,11, 9,10, 9, 9, 9, 9,10, 9, 9, 9,11,
  135834. 11,11,11,11,11,11,10,10, 9, 9, 9, 9, 9, 9,10, 9,
  135835. 11,11,10,11,11,11,11,10,11, 9, 9, 9, 9, 9, 9, 9,
  135836. 9,
  135837. };
  135838. static float _vq_quantthresh__44c1_s_p8_2[] = {
  135839. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  135840. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  135841. };
  135842. static long _vq_quantmap__44c1_s_p8_2[] = {
  135843. 15, 13, 11, 9, 7, 5, 3, 1,
  135844. 0, 2, 4, 6, 8, 10, 12, 14,
  135845. 16,
  135846. };
  135847. static encode_aux_threshmatch _vq_auxt__44c1_s_p8_2 = {
  135848. _vq_quantthresh__44c1_s_p8_2,
  135849. _vq_quantmap__44c1_s_p8_2,
  135850. 17,
  135851. 17
  135852. };
  135853. static static_codebook _44c1_s_p8_2 = {
  135854. 2, 289,
  135855. _vq_lengthlist__44c1_s_p8_2,
  135856. 1, -529530880, 1611661312, 5, 0,
  135857. _vq_quantlist__44c1_s_p8_2,
  135858. NULL,
  135859. &_vq_auxt__44c1_s_p8_2,
  135860. NULL,
  135861. 0
  135862. };
  135863. static long _huff_lengthlist__44c1_s_short[] = {
  135864. 6, 8,13,12,13,14,15,16,16, 4, 2, 4, 7, 6, 8,11,
  135865. 13,15,10, 4, 4, 8, 6, 8,11,14,17,11, 5, 6, 5, 6,
  135866. 8,12,14,17,11, 5, 5, 6, 5, 7,10,13,16,12, 6, 7,
  135867. 8, 7, 8,10,13,15,13, 8, 8, 7, 7, 8,10,12,15,15,
  135868. 7, 7, 5, 5, 7, 9,12,14,15, 8, 8, 6, 6, 7, 8,10,
  135869. 11,
  135870. };
  135871. static static_codebook _huff_book__44c1_s_short = {
  135872. 2, 81,
  135873. _huff_lengthlist__44c1_s_short,
  135874. 0, 0, 0, 0, 0,
  135875. NULL,
  135876. NULL,
  135877. NULL,
  135878. NULL,
  135879. 0
  135880. };
  135881. static long _huff_lengthlist__44c1_sm_long[] = {
  135882. 5, 4, 8,10, 9, 9,10,11,12, 4, 2, 5, 6, 6, 8,10,
  135883. 11,13, 8, 4, 6, 8, 7, 9,12,12,14,10, 6, 8, 4, 5,
  135884. 6, 9,11,12, 9, 5, 6, 5, 5, 6, 9,11,11, 9, 7, 9,
  135885. 6, 5, 5, 7,10,10,10, 9,11, 8, 7, 6, 7, 9,11,11,
  135886. 12,13,10,10, 9, 8, 9,11,11,15,15,12,13,11, 9,10,
  135887. 11,
  135888. };
  135889. static static_codebook _huff_book__44c1_sm_long = {
  135890. 2, 81,
  135891. _huff_lengthlist__44c1_sm_long,
  135892. 0, 0, 0, 0, 0,
  135893. NULL,
  135894. NULL,
  135895. NULL,
  135896. NULL,
  135897. 0
  135898. };
  135899. static long _vq_quantlist__44c1_sm_p1_0[] = {
  135900. 1,
  135901. 0,
  135902. 2,
  135903. };
  135904. static long _vq_lengthlist__44c1_sm_p1_0[] = {
  135905. 1, 5, 5, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  135906. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135907. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135908. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135909. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135910. 0, 5, 8, 7, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0, 0,
  135911. 0, 0, 0, 7, 8, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135912. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135913. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135914. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135915. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 9, 8, 0, 0,
  135916. 0, 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135917. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135918. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135919. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135920. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135921. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135922. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135923. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135924. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135925. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135926. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135927. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135928. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135929. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135930. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135931. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135932. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135933. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135934. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135935. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135936. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135937. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135938. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135939. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135940. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135941. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135942. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135943. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135944. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135945. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135946. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135947. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135948. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135949. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135950. 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 8, 7, 0, 0, 0, 0,
  135951. 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0,
  135952. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135953. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135954. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135955. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0, 0,
  135956. 0, 0, 0, 9, 9,10, 0, 0, 0, 0, 0, 0, 9,10,10, 0,
  135957. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135958. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135959. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135960. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  135961. 0, 0, 0, 0, 8,10, 9, 0, 0, 0, 0, 0, 0, 9,10,10,
  135962. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135963. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135964. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135965. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135966. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135967. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135968. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135969. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135970. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135971. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135972. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135973. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135974. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135975. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135976. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135977. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135978. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135979. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135980. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135981. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135982. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135983. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135984. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135985. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135986. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135987. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135988. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135989. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135990. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135991. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135992. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135993. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135994. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135995. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135996. 0, 0, 5, 7, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0,
  135997. 0, 0, 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135998. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135999. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136000. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136001. 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,10,10, 0,
  136002. 0, 0, 0, 0, 0, 8, 9,10, 0, 0, 0, 0, 0, 0, 0, 0,
  136003. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136004. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136005. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136006. 0, 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,10,10,
  136007. 0, 0, 0, 0, 0, 0, 9,10, 9, 0, 0, 0, 0, 0, 0, 0,
  136008. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136009. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136010. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136011. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136012. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136013. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136014. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136015. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136016. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136017. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136018. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136019. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136020. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136021. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136022. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136023. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136024. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136025. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136026. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136027. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136028. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136029. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136030. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136031. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136032. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136033. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136034. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136035. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136036. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136037. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136038. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136039. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136040. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136041. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136042. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136043. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136044. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136045. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136046. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136047. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136048. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136049. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136050. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136051. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136052. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136053. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136054. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136055. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136056. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136057. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136058. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136059. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136060. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136061. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136062. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136063. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136064. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136065. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136066. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136067. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136068. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136069. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136070. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136071. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136072. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136073. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136074. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136075. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136076. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136077. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136078. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136079. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136080. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136081. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136082. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136083. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136084. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136085. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136086. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136087. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136088. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136089. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136090. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136091. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136092. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136093. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136094. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136095. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136096. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136097. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136098. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136099. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136100. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136101. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136102. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136103. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136104. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136105. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136106. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136107. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136108. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136109. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136110. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136111. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136112. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136113. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136114. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136115. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136116. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136117. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136118. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136119. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136120. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136121. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136122. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136123. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136124. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136125. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136126. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136127. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136128. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136129. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136130. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136131. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136132. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136133. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136134. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136135. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136136. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136137. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136138. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136139. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136140. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136141. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136142. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136143. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136144. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136145. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136146. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136147. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136148. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136149. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136150. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136151. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136152. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136153. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136154. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136155. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136156. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136157. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136158. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136159. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136160. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136161. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136162. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136163. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136164. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136165. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136166. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136167. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136168. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136169. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136170. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136171. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136172. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136173. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136174. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136175. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136176. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136177. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136178. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136179. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136180. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136181. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136182. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136183. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136184. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136185. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136186. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136187. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136188. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136189. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136190. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136191. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136192. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136193. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136194. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136195. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136196. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136197. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136198. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136199. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136200. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136201. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136202. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136203. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136204. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136205. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136206. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136207. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136208. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136209. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136210. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136211. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136212. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136213. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136214. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136215. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136216. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136217. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136218. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136219. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136220. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136221. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136222. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136223. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136224. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136225. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136226. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136227. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136228. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136229. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136230. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136231. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136232. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136233. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136234. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136235. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136236. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136237. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136238. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136239. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136240. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136241. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136242. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136243. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136244. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136245. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136246. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136247. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136248. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136249. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136250. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136251. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136252. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136253. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136254. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136255. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136256. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136257. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136258. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136259. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136260. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136261. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136262. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136263. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136264. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136265. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136266. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136267. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136268. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136269. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136270. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136271. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136272. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136273. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136274. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136275. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136276. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136277. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136278. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136279. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136280. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136281. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136282. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136283. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136284. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136285. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136286. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136287. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136288. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136289. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136290. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136291. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136292. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136293. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136294. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136295. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136296. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136297. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136298. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136299. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136300. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136301. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136302. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136303. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136304. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136305. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136306. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136307. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136308. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136309. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136310. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136311. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136312. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136313. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136314. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136315. 0,
  136316. };
  136317. static float _vq_quantthresh__44c1_sm_p1_0[] = {
  136318. -0.5, 0.5,
  136319. };
  136320. static long _vq_quantmap__44c1_sm_p1_0[] = {
  136321. 1, 0, 2,
  136322. };
  136323. static encode_aux_threshmatch _vq_auxt__44c1_sm_p1_0 = {
  136324. _vq_quantthresh__44c1_sm_p1_0,
  136325. _vq_quantmap__44c1_sm_p1_0,
  136326. 3,
  136327. 3
  136328. };
  136329. static static_codebook _44c1_sm_p1_0 = {
  136330. 8, 6561,
  136331. _vq_lengthlist__44c1_sm_p1_0,
  136332. 1, -535822336, 1611661312, 2, 0,
  136333. _vq_quantlist__44c1_sm_p1_0,
  136334. NULL,
  136335. &_vq_auxt__44c1_sm_p1_0,
  136336. NULL,
  136337. 0
  136338. };
  136339. static long _vq_quantlist__44c1_sm_p2_0[] = {
  136340. 2,
  136341. 1,
  136342. 3,
  136343. 0,
  136344. 4,
  136345. };
  136346. static long _vq_lengthlist__44c1_sm_p2_0[] = {
  136347. 2, 3, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136348. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 4, 4, 6, 6, 0, 0,
  136349. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136350. 0, 0, 4, 4, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136351. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 6, 6, 9, 9,
  136352. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136353. 0, 0, 0, 0, 6, 6, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0,
  136354. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136355. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136356. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136357. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136358. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136359. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136360. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136361. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136362. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136363. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136364. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136365. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136366. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136367. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136368. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136369. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136370. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136371. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136372. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136373. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136374. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136375. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136376. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136377. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136378. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136379. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136380. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136381. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136382. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136383. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136384. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136385. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136386. 0,
  136387. };
  136388. static float _vq_quantthresh__44c1_sm_p2_0[] = {
  136389. -1.5, -0.5, 0.5, 1.5,
  136390. };
  136391. static long _vq_quantmap__44c1_sm_p2_0[] = {
  136392. 3, 1, 0, 2, 4,
  136393. };
  136394. static encode_aux_threshmatch _vq_auxt__44c1_sm_p2_0 = {
  136395. _vq_quantthresh__44c1_sm_p2_0,
  136396. _vq_quantmap__44c1_sm_p2_0,
  136397. 5,
  136398. 5
  136399. };
  136400. static static_codebook _44c1_sm_p2_0 = {
  136401. 4, 625,
  136402. _vq_lengthlist__44c1_sm_p2_0,
  136403. 1, -533725184, 1611661312, 3, 0,
  136404. _vq_quantlist__44c1_sm_p2_0,
  136405. NULL,
  136406. &_vq_auxt__44c1_sm_p2_0,
  136407. NULL,
  136408. 0
  136409. };
  136410. static long _vq_quantlist__44c1_sm_p3_0[] = {
  136411. 4,
  136412. 3,
  136413. 5,
  136414. 2,
  136415. 6,
  136416. 1,
  136417. 7,
  136418. 0,
  136419. 8,
  136420. };
  136421. static long _vq_lengthlist__44c1_sm_p3_0[] = {
  136422. 1, 3, 3, 7, 7, 0, 0, 0, 0, 0, 5, 5, 6, 6, 0, 0,
  136423. 0, 0, 0, 5, 5, 7, 7, 0, 0, 0, 0, 0, 7, 7, 7, 7,
  136424. 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0, 0, 0,
  136425. 8, 9, 0, 0, 0, 0, 0, 0, 0, 8, 8, 0, 0, 0, 0, 0,
  136426. 0, 0,10,10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136427. 0,
  136428. };
  136429. static float _vq_quantthresh__44c1_sm_p3_0[] = {
  136430. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  136431. };
  136432. static long _vq_quantmap__44c1_sm_p3_0[] = {
  136433. 7, 5, 3, 1, 0, 2, 4, 6,
  136434. 8,
  136435. };
  136436. static encode_aux_threshmatch _vq_auxt__44c1_sm_p3_0 = {
  136437. _vq_quantthresh__44c1_sm_p3_0,
  136438. _vq_quantmap__44c1_sm_p3_0,
  136439. 9,
  136440. 9
  136441. };
  136442. static static_codebook _44c1_sm_p3_0 = {
  136443. 2, 81,
  136444. _vq_lengthlist__44c1_sm_p3_0,
  136445. 1, -531628032, 1611661312, 4, 0,
  136446. _vq_quantlist__44c1_sm_p3_0,
  136447. NULL,
  136448. &_vq_auxt__44c1_sm_p3_0,
  136449. NULL,
  136450. 0
  136451. };
  136452. static long _vq_quantlist__44c1_sm_p4_0[] = {
  136453. 4,
  136454. 3,
  136455. 5,
  136456. 2,
  136457. 6,
  136458. 1,
  136459. 7,
  136460. 0,
  136461. 8,
  136462. };
  136463. static long _vq_lengthlist__44c1_sm_p4_0[] = {
  136464. 1, 3, 3, 6, 6, 7, 7, 9, 9, 0, 6, 6, 7, 7, 8, 8,
  136465. 9, 9, 0, 6, 6, 7, 7, 8, 8, 9, 9, 0, 7, 7, 8, 8,
  136466. 8, 8,10,10, 0, 0, 0, 8, 8, 8, 8,10,10, 0, 0, 0,
  136467. 8, 8, 9, 9,11,11, 0, 0, 0, 9, 9, 9, 9,11,11, 0,
  136468. 0, 0,10,10,10,10,11,11, 0, 0, 0, 0, 0, 9, 9,11,
  136469. 11,
  136470. };
  136471. static float _vq_quantthresh__44c1_sm_p4_0[] = {
  136472. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  136473. };
  136474. static long _vq_quantmap__44c1_sm_p4_0[] = {
  136475. 7, 5, 3, 1, 0, 2, 4, 6,
  136476. 8,
  136477. };
  136478. static encode_aux_threshmatch _vq_auxt__44c1_sm_p4_0 = {
  136479. _vq_quantthresh__44c1_sm_p4_0,
  136480. _vq_quantmap__44c1_sm_p4_0,
  136481. 9,
  136482. 9
  136483. };
  136484. static static_codebook _44c1_sm_p4_0 = {
  136485. 2, 81,
  136486. _vq_lengthlist__44c1_sm_p4_0,
  136487. 1, -531628032, 1611661312, 4, 0,
  136488. _vq_quantlist__44c1_sm_p4_0,
  136489. NULL,
  136490. &_vq_auxt__44c1_sm_p4_0,
  136491. NULL,
  136492. 0
  136493. };
  136494. static long _vq_quantlist__44c1_sm_p5_0[] = {
  136495. 8,
  136496. 7,
  136497. 9,
  136498. 6,
  136499. 10,
  136500. 5,
  136501. 11,
  136502. 4,
  136503. 12,
  136504. 3,
  136505. 13,
  136506. 2,
  136507. 14,
  136508. 1,
  136509. 15,
  136510. 0,
  136511. 16,
  136512. };
  136513. static long _vq_lengthlist__44c1_sm_p5_0[] = {
  136514. 2, 3, 3, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,10,11,
  136515. 11, 0, 5, 5, 6, 6, 8, 8, 9, 9, 9, 9,10,10,10,10,
  136516. 11,11, 0, 5, 5, 6, 6, 8, 8, 9, 9, 9, 9,10,10,10,
  136517. 10,11,11, 0, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  136518. 11,11,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,
  136519. 10,11,11,12,12, 0, 0, 0, 8, 8, 8, 8, 9, 9,10,10,
  136520. 10,11,11,11,12,12, 0, 0, 0, 8, 8, 8, 8, 9, 9,10,
  136521. 10,10,10,11,11,12,12, 0, 0, 0, 9, 9, 9, 9,10,10,
  136522. 10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 9, 9,10,
  136523. 10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,
  136524. 9, 9,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9,
  136525. 9, 9, 9,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0,
  136526. 9, 9,10,10,11,11,12,12,12,12,13,13, 0, 0, 0, 0,
  136527. 0, 0, 0,10,10,11,11,12,12,12,12,13,13, 0, 0, 0,
  136528. 0, 0, 0, 0,11,11,11,11,12,12,13,13,13,13, 0, 0,
  136529. 0, 0, 0, 0, 0,11,11,11,11,12,12,13,13,13,13, 0,
  136530. 0, 0, 0, 0, 0, 0,11,11,12,12,12,12,13,13,14,14,
  136531. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,14,
  136532. 14,
  136533. };
  136534. static float _vq_quantthresh__44c1_sm_p5_0[] = {
  136535. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  136536. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  136537. };
  136538. static long _vq_quantmap__44c1_sm_p5_0[] = {
  136539. 15, 13, 11, 9, 7, 5, 3, 1,
  136540. 0, 2, 4, 6, 8, 10, 12, 14,
  136541. 16,
  136542. };
  136543. static encode_aux_threshmatch _vq_auxt__44c1_sm_p5_0 = {
  136544. _vq_quantthresh__44c1_sm_p5_0,
  136545. _vq_quantmap__44c1_sm_p5_0,
  136546. 17,
  136547. 17
  136548. };
  136549. static static_codebook _44c1_sm_p5_0 = {
  136550. 2, 289,
  136551. _vq_lengthlist__44c1_sm_p5_0,
  136552. 1, -529530880, 1611661312, 5, 0,
  136553. _vq_quantlist__44c1_sm_p5_0,
  136554. NULL,
  136555. &_vq_auxt__44c1_sm_p5_0,
  136556. NULL,
  136557. 0
  136558. };
  136559. static long _vq_quantlist__44c1_sm_p6_0[] = {
  136560. 1,
  136561. 0,
  136562. 2,
  136563. };
  136564. static long _vq_lengthlist__44c1_sm_p6_0[] = {
  136565. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 7, 7,10, 9, 9,11,
  136566. 9, 9, 4, 7, 7,10, 9, 9,11, 9, 9, 7,10,10,10,11,
  136567. 11,11,10,10, 6, 9, 9,11,11,10,11,10,10, 6, 9, 9,
  136568. 11,10,11,11,10,10, 7,11,11,11,11,11,11,11,11, 6,
  136569. 9, 9,11,10,10,11,11,10, 6, 9, 9,10,10,10,11,10,
  136570. 11,
  136571. };
  136572. static float _vq_quantthresh__44c1_sm_p6_0[] = {
  136573. -5.5, 5.5,
  136574. };
  136575. static long _vq_quantmap__44c1_sm_p6_0[] = {
  136576. 1, 0, 2,
  136577. };
  136578. static encode_aux_threshmatch _vq_auxt__44c1_sm_p6_0 = {
  136579. _vq_quantthresh__44c1_sm_p6_0,
  136580. _vq_quantmap__44c1_sm_p6_0,
  136581. 3,
  136582. 3
  136583. };
  136584. static static_codebook _44c1_sm_p6_0 = {
  136585. 4, 81,
  136586. _vq_lengthlist__44c1_sm_p6_0,
  136587. 1, -529137664, 1618345984, 2, 0,
  136588. _vq_quantlist__44c1_sm_p6_0,
  136589. NULL,
  136590. &_vq_auxt__44c1_sm_p6_0,
  136591. NULL,
  136592. 0
  136593. };
  136594. static long _vq_quantlist__44c1_sm_p6_1[] = {
  136595. 5,
  136596. 4,
  136597. 6,
  136598. 3,
  136599. 7,
  136600. 2,
  136601. 8,
  136602. 1,
  136603. 9,
  136604. 0,
  136605. 10,
  136606. };
  136607. static long _vq_lengthlist__44c1_sm_p6_1[] = {
  136608. 2, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8,10, 5, 5, 6, 6,
  136609. 7, 7, 8, 8, 8, 8,10, 5, 5, 6, 6, 7, 7, 8, 8, 8,
  136610. 8,10, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10, 7,
  136611. 7, 7, 7, 8, 8, 8, 8,10,10,10, 7, 7, 8, 8, 8, 8,
  136612. 8, 8,10,10,10, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10,
  136613. 8, 8, 8, 8, 8, 8, 9, 8,10,10,10,10,10, 8, 8, 8,
  136614. 8, 8, 8,10,10,10,10,10, 9, 9, 8, 8, 8, 8,10,10,
  136615. 10,10,10, 8, 8, 8, 8, 8, 8,
  136616. };
  136617. static float _vq_quantthresh__44c1_sm_p6_1[] = {
  136618. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  136619. 3.5, 4.5,
  136620. };
  136621. static long _vq_quantmap__44c1_sm_p6_1[] = {
  136622. 9, 7, 5, 3, 1, 0, 2, 4,
  136623. 6, 8, 10,
  136624. };
  136625. static encode_aux_threshmatch _vq_auxt__44c1_sm_p6_1 = {
  136626. _vq_quantthresh__44c1_sm_p6_1,
  136627. _vq_quantmap__44c1_sm_p6_1,
  136628. 11,
  136629. 11
  136630. };
  136631. static static_codebook _44c1_sm_p6_1 = {
  136632. 2, 121,
  136633. _vq_lengthlist__44c1_sm_p6_1,
  136634. 1, -531365888, 1611661312, 4, 0,
  136635. _vq_quantlist__44c1_sm_p6_1,
  136636. NULL,
  136637. &_vq_auxt__44c1_sm_p6_1,
  136638. NULL,
  136639. 0
  136640. };
  136641. static long _vq_quantlist__44c1_sm_p7_0[] = {
  136642. 6,
  136643. 5,
  136644. 7,
  136645. 4,
  136646. 8,
  136647. 3,
  136648. 9,
  136649. 2,
  136650. 10,
  136651. 1,
  136652. 11,
  136653. 0,
  136654. 12,
  136655. };
  136656. static long _vq_lengthlist__44c1_sm_p7_0[] = {
  136657. 1, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8, 9, 9, 7, 5, 5,
  136658. 7, 7, 8, 8, 8, 8, 9, 9,10,10, 7, 5, 6, 7, 7, 8,
  136659. 8, 8, 8, 9, 9,11,10, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  136660. 10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  136661. 11, 0,12,12, 9, 9,10,10,10,10,11,11,11,11, 0,13,
  136662. 13, 9, 9, 9, 9,10,10,11,11,12,12, 0, 0, 0, 9,10,
  136663. 9,10,11,11,12,11,13,12, 0, 0, 0,10,10, 9, 9,11,
  136664. 11,12,12,13,12, 0, 0, 0,13,13,10,10,11,11,12,12,
  136665. 13,13, 0, 0, 0,14,14,10,10,11,11,12,12,13,13, 0,
  136666. 0, 0, 0, 0,11,12,11,11,12,13,14,13, 0, 0, 0, 0,
  136667. 0,12,12,11,11,13,12,14,13,
  136668. };
  136669. static float _vq_quantthresh__44c1_sm_p7_0[] = {
  136670. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  136671. 12.5, 17.5, 22.5, 27.5,
  136672. };
  136673. static long _vq_quantmap__44c1_sm_p7_0[] = {
  136674. 11, 9, 7, 5, 3, 1, 0, 2,
  136675. 4, 6, 8, 10, 12,
  136676. };
  136677. static encode_aux_threshmatch _vq_auxt__44c1_sm_p7_0 = {
  136678. _vq_quantthresh__44c1_sm_p7_0,
  136679. _vq_quantmap__44c1_sm_p7_0,
  136680. 13,
  136681. 13
  136682. };
  136683. static static_codebook _44c1_sm_p7_0 = {
  136684. 2, 169,
  136685. _vq_lengthlist__44c1_sm_p7_0,
  136686. 1, -526516224, 1616117760, 4, 0,
  136687. _vq_quantlist__44c1_sm_p7_0,
  136688. NULL,
  136689. &_vq_auxt__44c1_sm_p7_0,
  136690. NULL,
  136691. 0
  136692. };
  136693. static long _vq_quantlist__44c1_sm_p7_1[] = {
  136694. 2,
  136695. 1,
  136696. 3,
  136697. 0,
  136698. 4,
  136699. };
  136700. static long _vq_lengthlist__44c1_sm_p7_1[] = {
  136701. 2, 4, 4, 4, 5, 6, 5, 5, 5, 5, 6, 5, 5, 5, 5, 6,
  136702. 5, 5, 5, 5, 6, 6, 6, 5, 5,
  136703. };
  136704. static float _vq_quantthresh__44c1_sm_p7_1[] = {
  136705. -1.5, -0.5, 0.5, 1.5,
  136706. };
  136707. static long _vq_quantmap__44c1_sm_p7_1[] = {
  136708. 3, 1, 0, 2, 4,
  136709. };
  136710. static encode_aux_threshmatch _vq_auxt__44c1_sm_p7_1 = {
  136711. _vq_quantthresh__44c1_sm_p7_1,
  136712. _vq_quantmap__44c1_sm_p7_1,
  136713. 5,
  136714. 5
  136715. };
  136716. static static_codebook _44c1_sm_p7_1 = {
  136717. 2, 25,
  136718. _vq_lengthlist__44c1_sm_p7_1,
  136719. 1, -533725184, 1611661312, 3, 0,
  136720. _vq_quantlist__44c1_sm_p7_1,
  136721. NULL,
  136722. &_vq_auxt__44c1_sm_p7_1,
  136723. NULL,
  136724. 0
  136725. };
  136726. static long _vq_quantlist__44c1_sm_p8_0[] = {
  136727. 6,
  136728. 5,
  136729. 7,
  136730. 4,
  136731. 8,
  136732. 3,
  136733. 9,
  136734. 2,
  136735. 10,
  136736. 1,
  136737. 11,
  136738. 0,
  136739. 12,
  136740. };
  136741. static long _vq_lengthlist__44c1_sm_p8_0[] = {
  136742. 1, 3, 3,13,13,13,13,13,13,13,13,13,13, 3, 6, 6,
  136743. 13,13,13,13,13,13,13,13,13,13, 4, 8, 7,13,13,13,
  136744. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  136745. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  136746. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  136747. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  136748. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  136749. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  136750. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  136751. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  136752. 13,13,13,13,13,13,13,13,13,
  136753. };
  136754. static float _vq_quantthresh__44c1_sm_p8_0[] = {
  136755. -1215.5, -994.5, -773.5, -552.5, -331.5, -110.5, 110.5, 331.5,
  136756. 552.5, 773.5, 994.5, 1215.5,
  136757. };
  136758. static long _vq_quantmap__44c1_sm_p8_0[] = {
  136759. 11, 9, 7, 5, 3, 1, 0, 2,
  136760. 4, 6, 8, 10, 12,
  136761. };
  136762. static encode_aux_threshmatch _vq_auxt__44c1_sm_p8_0 = {
  136763. _vq_quantthresh__44c1_sm_p8_0,
  136764. _vq_quantmap__44c1_sm_p8_0,
  136765. 13,
  136766. 13
  136767. };
  136768. static static_codebook _44c1_sm_p8_0 = {
  136769. 2, 169,
  136770. _vq_lengthlist__44c1_sm_p8_0,
  136771. 1, -514541568, 1627103232, 4, 0,
  136772. _vq_quantlist__44c1_sm_p8_0,
  136773. NULL,
  136774. &_vq_auxt__44c1_sm_p8_0,
  136775. NULL,
  136776. 0
  136777. };
  136778. static long _vq_quantlist__44c1_sm_p8_1[] = {
  136779. 6,
  136780. 5,
  136781. 7,
  136782. 4,
  136783. 8,
  136784. 3,
  136785. 9,
  136786. 2,
  136787. 10,
  136788. 1,
  136789. 11,
  136790. 0,
  136791. 12,
  136792. };
  136793. static long _vq_lengthlist__44c1_sm_p8_1[] = {
  136794. 1, 4, 4, 6, 6, 7, 7, 9, 9,10,11,12,12, 6, 5, 5,
  136795. 7, 7, 8, 7,10,10,11,11,12,12, 6, 5, 5, 7, 7, 8,
  136796. 8,10,10,11,11,12,12,16, 7, 7, 8, 8, 9, 9,11,11,
  136797. 12,12,13,13,17, 7, 7, 8, 7, 9, 9,11,10,12,12,13,
  136798. 13,19,11,10, 8, 8,10,10,11,11,12,12,13,13,19,11,
  136799. 11, 9, 7,11,10,11,11,12,12,13,12,19,19,19,10,10,
  136800. 10,10,11,12,12,12,13,14,18,19,19,11, 9,11, 9,13,
  136801. 12,12,12,13,13,19,20,19,13,15,11,11,12,12,13,13,
  136802. 14,13,18,19,20,15,13,12,10,13,10,13,13,13,14,20,
  136803. 20,20,20,20,13,14,12,12,13,12,13,13,20,20,20,20,
  136804. 20,13,12,12,12,14,12,14,13,
  136805. };
  136806. static float _vq_quantthresh__44c1_sm_p8_1[] = {
  136807. -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5, 25.5,
  136808. 42.5, 59.5, 76.5, 93.5,
  136809. };
  136810. static long _vq_quantmap__44c1_sm_p8_1[] = {
  136811. 11, 9, 7, 5, 3, 1, 0, 2,
  136812. 4, 6, 8, 10, 12,
  136813. };
  136814. static encode_aux_threshmatch _vq_auxt__44c1_sm_p8_1 = {
  136815. _vq_quantthresh__44c1_sm_p8_1,
  136816. _vq_quantmap__44c1_sm_p8_1,
  136817. 13,
  136818. 13
  136819. };
  136820. static static_codebook _44c1_sm_p8_1 = {
  136821. 2, 169,
  136822. _vq_lengthlist__44c1_sm_p8_1,
  136823. 1, -522616832, 1620115456, 4, 0,
  136824. _vq_quantlist__44c1_sm_p8_1,
  136825. NULL,
  136826. &_vq_auxt__44c1_sm_p8_1,
  136827. NULL,
  136828. 0
  136829. };
  136830. static long _vq_quantlist__44c1_sm_p8_2[] = {
  136831. 8,
  136832. 7,
  136833. 9,
  136834. 6,
  136835. 10,
  136836. 5,
  136837. 11,
  136838. 4,
  136839. 12,
  136840. 3,
  136841. 13,
  136842. 2,
  136843. 14,
  136844. 1,
  136845. 15,
  136846. 0,
  136847. 16,
  136848. };
  136849. static long _vq_lengthlist__44c1_sm_p8_2[] = {
  136850. 2, 5, 5, 6, 6, 7, 6, 7, 7, 8, 8, 8, 8, 8, 8, 8,
  136851. 8,10, 6, 6, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9, 9, 9,
  136852. 9, 9,10, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  136853. 9, 9, 9,10, 7, 7, 7, 7, 8, 8, 8, 9, 9, 9, 9, 9,
  136854. 9, 9, 9, 9,10,10,10, 7, 7, 8, 8, 9, 9, 9, 9, 9,
  136855. 9, 9, 9, 9, 9,10,11,11, 8, 8, 8, 8, 9, 9, 9, 9,
  136856. 9, 9,10,10, 9,10,10,10,10, 8, 8, 8, 8, 9, 9, 9,
  136857. 9, 9, 9, 9, 9,10,10,11,10,10, 8, 8, 9, 9, 9, 9,
  136858. 9, 9, 9, 9, 9, 9,10, 9,10,10,10,11,11, 8, 8, 9,
  136859. 9, 9, 9, 9, 9, 9, 9, 9, 9,11,11,11,11,11, 9, 9,
  136860. 9, 9, 9, 9, 9, 9,10, 9,10, 9,11,11,11,11,11, 9,
  136861. 8, 9, 9, 9, 9, 9, 9, 9,10,10, 9,11,11,10,11,11,
  136862. 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10, 9,11,11,11,11,
  136863. 11,11,11, 9, 9,10, 9, 9, 9, 9,10, 9,10,10,11,10,
  136864. 11,11,11,11, 9,10,10,10, 9, 9, 9, 9, 9, 9,10,11,
  136865. 11,11,11,11,11, 9, 9, 9, 9, 9, 9, 9, 9,10, 9,11,
  136866. 11,10,11,11,11,11,10,10, 9, 9, 9, 9, 9, 9,10, 9,
  136867. 10,11,10,11,11,11,11,11,11, 9, 9,10, 9, 9, 9, 9,
  136868. 9,
  136869. };
  136870. static float _vq_quantthresh__44c1_sm_p8_2[] = {
  136871. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  136872. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  136873. };
  136874. static long _vq_quantmap__44c1_sm_p8_2[] = {
  136875. 15, 13, 11, 9, 7, 5, 3, 1,
  136876. 0, 2, 4, 6, 8, 10, 12, 14,
  136877. 16,
  136878. };
  136879. static encode_aux_threshmatch _vq_auxt__44c1_sm_p8_2 = {
  136880. _vq_quantthresh__44c1_sm_p8_2,
  136881. _vq_quantmap__44c1_sm_p8_2,
  136882. 17,
  136883. 17
  136884. };
  136885. static static_codebook _44c1_sm_p8_2 = {
  136886. 2, 289,
  136887. _vq_lengthlist__44c1_sm_p8_2,
  136888. 1, -529530880, 1611661312, 5, 0,
  136889. _vq_quantlist__44c1_sm_p8_2,
  136890. NULL,
  136891. &_vq_auxt__44c1_sm_p8_2,
  136892. NULL,
  136893. 0
  136894. };
  136895. static long _huff_lengthlist__44c1_sm_short[] = {
  136896. 4, 7,13,14,14,15,16,18,18, 4, 2, 5, 8, 7, 9,12,
  136897. 15,15,10, 4, 5,10, 6, 8,11,15,17,12, 5, 7, 5, 6,
  136898. 8,11,14,17,11, 5, 6, 6, 5, 6, 9,13,17,12, 6, 7,
  136899. 6, 5, 6, 8,12,14,14, 7, 8, 6, 6, 7, 9,11,14,14,
  136900. 8, 9, 6, 5, 6, 9,11,13,16,10,10, 7, 6, 7, 8,10,
  136901. 11,
  136902. };
  136903. static static_codebook _huff_book__44c1_sm_short = {
  136904. 2, 81,
  136905. _huff_lengthlist__44c1_sm_short,
  136906. 0, 0, 0, 0, 0,
  136907. NULL,
  136908. NULL,
  136909. NULL,
  136910. NULL,
  136911. 0
  136912. };
  136913. static long _huff_lengthlist__44cn1_s_long[] = {
  136914. 4, 4, 7, 8, 7, 8,10,12,17, 3, 1, 6, 6, 7, 8,10,
  136915. 12,15, 7, 6, 9, 9, 9,11,12,14,17, 8, 6, 9, 6, 7,
  136916. 9,11,13,17, 7, 6, 9, 7, 7, 8, 9,12,15, 8, 8,10,
  136917. 8, 7, 7, 7,10,14, 9,10,12,10, 8, 8, 8,10,14,11,
  136918. 13,15,13,12,11,11,12,16,17,18,18,19,20,18,16,16,
  136919. 20,
  136920. };
  136921. static static_codebook _huff_book__44cn1_s_long = {
  136922. 2, 81,
  136923. _huff_lengthlist__44cn1_s_long,
  136924. 0, 0, 0, 0, 0,
  136925. NULL,
  136926. NULL,
  136927. NULL,
  136928. NULL,
  136929. 0
  136930. };
  136931. static long _vq_quantlist__44cn1_s_p1_0[] = {
  136932. 1,
  136933. 0,
  136934. 2,
  136935. };
  136936. static long _vq_lengthlist__44cn1_s_p1_0[] = {
  136937. 1, 4, 4, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  136938. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136939. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136940. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136941. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136942. 0, 5, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0, 0,
  136943. 0, 0, 0, 7, 9,10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136944. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136945. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136946. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136947. 0, 0, 5, 8, 8, 0, 0, 0, 0, 0, 0, 7,10, 9, 0, 0,
  136948. 0, 0, 0, 0, 8,10, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136949. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136950. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136951. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136952. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136953. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136954. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136955. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136956. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136957. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136958. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136959. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136960. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136961. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136962. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136963. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136964. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136965. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136966. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136967. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136968. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136969. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136970. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136971. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136972. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136973. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136974. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136975. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136976. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136977. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136978. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136979. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136980. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136981. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136982. 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 8, 8, 0, 0, 0, 0,
  136983. 0, 0, 8,10,10, 0, 0, 0, 0, 0, 0, 8, 9,10, 0, 0,
  136984. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136985. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136986. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136987. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7,10,10, 0, 0, 0,
  136988. 0, 0, 0, 9, 9,11, 0, 0, 0, 0, 0, 0,10,11,11, 0,
  136989. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136990. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136991. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136992. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7,10,10, 0, 0,
  136993. 0, 0, 0, 0, 9,11, 9, 0, 0, 0, 0, 0, 0,10,11,11,
  136994. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136995. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136996. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136997. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136998. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136999. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137000. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137001. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137002. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137003. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137004. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137005. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137006. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137007. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137008. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137009. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137010. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137011. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137012. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137013. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137014. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137015. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137016. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137017. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137018. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137019. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137020. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137021. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137022. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137023. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137024. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137025. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137026. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137027. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137028. 0, 0, 5, 8, 8, 0, 0, 0, 0, 0, 0, 8,10,10, 0, 0,
  137029. 0, 0, 0, 0, 8,10,10, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137030. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137031. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137032. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137033. 0, 0, 0, 7,10,10, 0, 0, 0, 0, 0, 0,10,11,11, 0,
  137034. 0, 0, 0, 0, 0, 9, 9,11, 0, 0, 0, 0, 0, 0, 0, 0,
  137035. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137036. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137037. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137038. 0, 0, 0, 0, 7,10,10, 0, 0, 0, 0, 0, 0,10,11,11,
  137039. 0, 0, 0, 0, 0, 0, 9,11, 9, 0, 0, 0, 0, 0, 0, 0,
  137040. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137041. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137042. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137043. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137044. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137045. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137046. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137047. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137048. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137049. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137050. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137051. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137052. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137053. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137054. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137055. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137056. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137057. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137058. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137059. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137060. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137061. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137062. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137063. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137064. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137065. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137066. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137067. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137068. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137069. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137070. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137071. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137072. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137073. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137074. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137075. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137076. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137077. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137078. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137079. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137080. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137081. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137082. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137083. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137084. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137085. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137086. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137087. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137088. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137089. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137090. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137091. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137092. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137093. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137094. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137095. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137096. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137097. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137098. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137099. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137100. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137101. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137102. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137103. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137104. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137105. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137106. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137107. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137108. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137109. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137110. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137111. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137112. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137113. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137114. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137115. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137116. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137117. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137118. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137119. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137120. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137121. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137122. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137123. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137124. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137125. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137126. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137127. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137128. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137129. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137130. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137131. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137132. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137133. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137134. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137135. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137136. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137137. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137138. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137139. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137140. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137141. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137142. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137143. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137144. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137145. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137146. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137147. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137148. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137149. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137150. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137151. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137152. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137153. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137154. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137155. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137156. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137157. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137158. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137159. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137160. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137161. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137162. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137163. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137164. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137165. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137166. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137167. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137168. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137169. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137170. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137171. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137172. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137173. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137174. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137175. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137176. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137177. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137178. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137179. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137180. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137181. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137182. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137183. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137184. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137185. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137186. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137187. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137188. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137189. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137190. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137191. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137192. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137193. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137194. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137195. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137196. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137197. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137198. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137199. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137200. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137201. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137202. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137203. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137204. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137205. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137206. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137207. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137208. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137209. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137210. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137211. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137212. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137213. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137214. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137215. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137216. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137217. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137218. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137219. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137220. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137221. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137222. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137223. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137224. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137225. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137226. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137227. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137228. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137229. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137230. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137231. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137232. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137233. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137234. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137235. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137236. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137237. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137238. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137239. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137240. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137241. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137242. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137243. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137244. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137245. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137246. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137247. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137248. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137249. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137250. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137251. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137252. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137253. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137254. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137255. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137256. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137257. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137258. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137259. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137260. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137261. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137262. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137263. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137264. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137265. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137266. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137267. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137268. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137269. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137270. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137271. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137272. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137273. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137274. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137275. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137276. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137277. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137278. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137279. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137280. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137281. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137282. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137283. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137284. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137285. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137286. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137287. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137288. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137289. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137290. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137291. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137292. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137293. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137294. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137295. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137296. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137297. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137298. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137299. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137300. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137301. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137302. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137303. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137304. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137305. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137306. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137307. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137308. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137309. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137310. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137311. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137312. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137313. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137314. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137315. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137316. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137317. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137318. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137319. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137320. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137321. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137322. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137323. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137324. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137325. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137326. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137327. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137328. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137329. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137330. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137331. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137332. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137333. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137334. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137335. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137336. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137337. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137338. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137339. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137340. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137341. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137342. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137343. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137344. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137345. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137346. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137347. 0,
  137348. };
  137349. static float _vq_quantthresh__44cn1_s_p1_0[] = {
  137350. -0.5, 0.5,
  137351. };
  137352. static long _vq_quantmap__44cn1_s_p1_0[] = {
  137353. 1, 0, 2,
  137354. };
  137355. static encode_aux_threshmatch _vq_auxt__44cn1_s_p1_0 = {
  137356. _vq_quantthresh__44cn1_s_p1_0,
  137357. _vq_quantmap__44cn1_s_p1_0,
  137358. 3,
  137359. 3
  137360. };
  137361. static static_codebook _44cn1_s_p1_0 = {
  137362. 8, 6561,
  137363. _vq_lengthlist__44cn1_s_p1_0,
  137364. 1, -535822336, 1611661312, 2, 0,
  137365. _vq_quantlist__44cn1_s_p1_0,
  137366. NULL,
  137367. &_vq_auxt__44cn1_s_p1_0,
  137368. NULL,
  137369. 0
  137370. };
  137371. static long _vq_quantlist__44cn1_s_p2_0[] = {
  137372. 2,
  137373. 1,
  137374. 3,
  137375. 0,
  137376. 4,
  137377. };
  137378. static long _vq_lengthlist__44cn1_s_p2_0[] = {
  137379. 1, 4, 4, 7, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137380. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 5, 5, 7, 7, 0, 0,
  137381. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137382. 0, 0, 4, 5, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137383. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 7, 7, 9, 9,
  137384. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137385. 0, 0, 0, 0, 6, 7, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0,
  137386. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137387. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137388. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137389. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137390. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137391. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137392. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137393. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137394. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137395. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137396. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137397. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137398. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137399. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137400. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137401. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137402. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137403. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137404. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137405. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137406. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137407. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137408. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137409. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137410. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137411. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137412. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137413. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137414. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137415. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137416. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137417. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137418. 0,
  137419. };
  137420. static float _vq_quantthresh__44cn1_s_p2_0[] = {
  137421. -1.5, -0.5, 0.5, 1.5,
  137422. };
  137423. static long _vq_quantmap__44cn1_s_p2_0[] = {
  137424. 3, 1, 0, 2, 4,
  137425. };
  137426. static encode_aux_threshmatch _vq_auxt__44cn1_s_p2_0 = {
  137427. _vq_quantthresh__44cn1_s_p2_0,
  137428. _vq_quantmap__44cn1_s_p2_0,
  137429. 5,
  137430. 5
  137431. };
  137432. static static_codebook _44cn1_s_p2_0 = {
  137433. 4, 625,
  137434. _vq_lengthlist__44cn1_s_p2_0,
  137435. 1, -533725184, 1611661312, 3, 0,
  137436. _vq_quantlist__44cn1_s_p2_0,
  137437. NULL,
  137438. &_vq_auxt__44cn1_s_p2_0,
  137439. NULL,
  137440. 0
  137441. };
  137442. static long _vq_quantlist__44cn1_s_p3_0[] = {
  137443. 4,
  137444. 3,
  137445. 5,
  137446. 2,
  137447. 6,
  137448. 1,
  137449. 7,
  137450. 0,
  137451. 8,
  137452. };
  137453. static long _vq_lengthlist__44cn1_s_p3_0[] = {
  137454. 1, 2, 3, 7, 7, 0, 0, 0, 0, 0, 0, 0, 6, 6, 0, 0,
  137455. 0, 0, 0, 0, 0, 6, 6, 0, 0, 0, 0, 0, 0, 0, 7, 7,
  137456. 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0, 0, 0,
  137457. 9, 8, 0, 0, 0, 0, 0, 0, 0, 8, 8, 0, 0, 0, 0, 0,
  137458. 0, 0,10,10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137459. 0,
  137460. };
  137461. static float _vq_quantthresh__44cn1_s_p3_0[] = {
  137462. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  137463. };
  137464. static long _vq_quantmap__44cn1_s_p3_0[] = {
  137465. 7, 5, 3, 1, 0, 2, 4, 6,
  137466. 8,
  137467. };
  137468. static encode_aux_threshmatch _vq_auxt__44cn1_s_p3_0 = {
  137469. _vq_quantthresh__44cn1_s_p3_0,
  137470. _vq_quantmap__44cn1_s_p3_0,
  137471. 9,
  137472. 9
  137473. };
  137474. static static_codebook _44cn1_s_p3_0 = {
  137475. 2, 81,
  137476. _vq_lengthlist__44cn1_s_p3_0,
  137477. 1, -531628032, 1611661312, 4, 0,
  137478. _vq_quantlist__44cn1_s_p3_0,
  137479. NULL,
  137480. &_vq_auxt__44cn1_s_p3_0,
  137481. NULL,
  137482. 0
  137483. };
  137484. static long _vq_quantlist__44cn1_s_p4_0[] = {
  137485. 4,
  137486. 3,
  137487. 5,
  137488. 2,
  137489. 6,
  137490. 1,
  137491. 7,
  137492. 0,
  137493. 8,
  137494. };
  137495. static long _vq_lengthlist__44cn1_s_p4_0[] = {
  137496. 1, 3, 3, 6, 6, 6, 6, 8, 8, 0, 0, 0, 6, 6, 7, 7,
  137497. 9, 9, 0, 0, 0, 6, 6, 7, 7, 9, 9, 0, 0, 0, 7, 7,
  137498. 8, 8,10,10, 0, 0, 0, 7, 7, 8, 8,10,10, 0, 0, 0,
  137499. 9, 9, 9, 9,10,10, 0, 0, 0, 9, 9, 9, 9,10,10, 0,
  137500. 0, 0,10,10,10,10,11,11, 0, 0, 0, 0, 0,10,10,11,
  137501. 11,
  137502. };
  137503. static float _vq_quantthresh__44cn1_s_p4_0[] = {
  137504. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  137505. };
  137506. static long _vq_quantmap__44cn1_s_p4_0[] = {
  137507. 7, 5, 3, 1, 0, 2, 4, 6,
  137508. 8,
  137509. };
  137510. static encode_aux_threshmatch _vq_auxt__44cn1_s_p4_0 = {
  137511. _vq_quantthresh__44cn1_s_p4_0,
  137512. _vq_quantmap__44cn1_s_p4_0,
  137513. 9,
  137514. 9
  137515. };
  137516. static static_codebook _44cn1_s_p4_0 = {
  137517. 2, 81,
  137518. _vq_lengthlist__44cn1_s_p4_0,
  137519. 1, -531628032, 1611661312, 4, 0,
  137520. _vq_quantlist__44cn1_s_p4_0,
  137521. NULL,
  137522. &_vq_auxt__44cn1_s_p4_0,
  137523. NULL,
  137524. 0
  137525. };
  137526. static long _vq_quantlist__44cn1_s_p5_0[] = {
  137527. 8,
  137528. 7,
  137529. 9,
  137530. 6,
  137531. 10,
  137532. 5,
  137533. 11,
  137534. 4,
  137535. 12,
  137536. 3,
  137537. 13,
  137538. 2,
  137539. 14,
  137540. 1,
  137541. 15,
  137542. 0,
  137543. 16,
  137544. };
  137545. static long _vq_lengthlist__44cn1_s_p5_0[] = {
  137546. 1, 4, 3, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,10,10,
  137547. 10, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10,10,
  137548. 11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10,
  137549. 10,11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  137550. 11,11,11,12, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,
  137551. 10,11,11,11,11, 0, 0, 0, 8, 8, 9, 9, 9, 9,10,10,
  137552. 10,10,11,11,12,12, 0, 0, 0, 8, 8, 9, 9, 9, 9,10,
  137553. 10,10,11,11,11,12,12, 0, 0, 0, 9, 9,10, 9,10,10,
  137554. 10,10,11,11,11,11,12,12, 0, 0, 0, 0, 0, 9, 9,10,
  137555. 10,10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 9, 9,
  137556. 10,10,10,11,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9,
  137557. 9,10,10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0,
  137558. 10,10,11,10,11,11,11,12,13,12,13,13, 0, 0, 0, 0,
  137559. 0, 0, 0,11,10,11,11,12,12,12,12,13,13, 0, 0, 0,
  137560. 0, 0, 0, 0,11,11,12,12,12,12,13,13,13,14, 0, 0,
  137561. 0, 0, 0, 0, 0,11,11,12,12,12,12,13,13,13,14, 0,
  137562. 0, 0, 0, 0, 0, 0,12,12,12,13,13,13,13,13,14,14,
  137563. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,13,12,13,13,14,
  137564. 14,
  137565. };
  137566. static float _vq_quantthresh__44cn1_s_p5_0[] = {
  137567. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  137568. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  137569. };
  137570. static long _vq_quantmap__44cn1_s_p5_0[] = {
  137571. 15, 13, 11, 9, 7, 5, 3, 1,
  137572. 0, 2, 4, 6, 8, 10, 12, 14,
  137573. 16,
  137574. };
  137575. static encode_aux_threshmatch _vq_auxt__44cn1_s_p5_0 = {
  137576. _vq_quantthresh__44cn1_s_p5_0,
  137577. _vq_quantmap__44cn1_s_p5_0,
  137578. 17,
  137579. 17
  137580. };
  137581. static static_codebook _44cn1_s_p5_0 = {
  137582. 2, 289,
  137583. _vq_lengthlist__44cn1_s_p5_0,
  137584. 1, -529530880, 1611661312, 5, 0,
  137585. _vq_quantlist__44cn1_s_p5_0,
  137586. NULL,
  137587. &_vq_auxt__44cn1_s_p5_0,
  137588. NULL,
  137589. 0
  137590. };
  137591. static long _vq_quantlist__44cn1_s_p6_0[] = {
  137592. 1,
  137593. 0,
  137594. 2,
  137595. };
  137596. static long _vq_lengthlist__44cn1_s_p6_0[] = {
  137597. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 6, 6,10, 9, 9,11,
  137598. 9, 9, 4, 6, 6,10, 9, 9,10, 9, 9, 7,10,10,11,11,
  137599. 11,12,11,11, 7, 9, 9,11,11,10,11,10,10, 7, 9, 9,
  137600. 11,10,11,11,10,10, 7,10,10,11,11,11,12,11,11, 7,
  137601. 9, 9,11,10,10,11,10,10, 7, 9, 9,11,10,10,11,10,
  137602. 10,
  137603. };
  137604. static float _vq_quantthresh__44cn1_s_p6_0[] = {
  137605. -5.5, 5.5,
  137606. };
  137607. static long _vq_quantmap__44cn1_s_p6_0[] = {
  137608. 1, 0, 2,
  137609. };
  137610. static encode_aux_threshmatch _vq_auxt__44cn1_s_p6_0 = {
  137611. _vq_quantthresh__44cn1_s_p6_0,
  137612. _vq_quantmap__44cn1_s_p6_0,
  137613. 3,
  137614. 3
  137615. };
  137616. static static_codebook _44cn1_s_p6_0 = {
  137617. 4, 81,
  137618. _vq_lengthlist__44cn1_s_p6_0,
  137619. 1, -529137664, 1618345984, 2, 0,
  137620. _vq_quantlist__44cn1_s_p6_0,
  137621. NULL,
  137622. &_vq_auxt__44cn1_s_p6_0,
  137623. NULL,
  137624. 0
  137625. };
  137626. static long _vq_quantlist__44cn1_s_p6_1[] = {
  137627. 5,
  137628. 4,
  137629. 6,
  137630. 3,
  137631. 7,
  137632. 2,
  137633. 8,
  137634. 1,
  137635. 9,
  137636. 0,
  137637. 10,
  137638. };
  137639. static long _vq_lengthlist__44cn1_s_p6_1[] = {
  137640. 1, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8,10,10,10, 7, 6,
  137641. 8, 8, 8, 8, 8, 8,10,10,10, 7, 6, 7, 7, 8, 8, 8,
  137642. 8,10,10,10, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10, 7,
  137643. 7, 8, 8, 8, 8, 8, 8,10,10,10, 8, 8, 8, 8, 9, 9,
  137644. 9, 9,10,10,10, 8, 8, 8, 8, 9, 9, 9, 9,10,10,10,
  137645. 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,10,10, 9, 9, 9,
  137646. 9, 9, 9,10,10,10,10,10, 9, 9, 9, 9, 9, 9,10,10,
  137647. 10,10,10, 9, 9, 9, 9, 9, 9,
  137648. };
  137649. static float _vq_quantthresh__44cn1_s_p6_1[] = {
  137650. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  137651. 3.5, 4.5,
  137652. };
  137653. static long _vq_quantmap__44cn1_s_p6_1[] = {
  137654. 9, 7, 5, 3, 1, 0, 2, 4,
  137655. 6, 8, 10,
  137656. };
  137657. static encode_aux_threshmatch _vq_auxt__44cn1_s_p6_1 = {
  137658. _vq_quantthresh__44cn1_s_p6_1,
  137659. _vq_quantmap__44cn1_s_p6_1,
  137660. 11,
  137661. 11
  137662. };
  137663. static static_codebook _44cn1_s_p6_1 = {
  137664. 2, 121,
  137665. _vq_lengthlist__44cn1_s_p6_1,
  137666. 1, -531365888, 1611661312, 4, 0,
  137667. _vq_quantlist__44cn1_s_p6_1,
  137668. NULL,
  137669. &_vq_auxt__44cn1_s_p6_1,
  137670. NULL,
  137671. 0
  137672. };
  137673. static long _vq_quantlist__44cn1_s_p7_0[] = {
  137674. 6,
  137675. 5,
  137676. 7,
  137677. 4,
  137678. 8,
  137679. 3,
  137680. 9,
  137681. 2,
  137682. 10,
  137683. 1,
  137684. 11,
  137685. 0,
  137686. 12,
  137687. };
  137688. static long _vq_lengthlist__44cn1_s_p7_0[] = {
  137689. 1, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10, 6, 5, 5,
  137690. 7, 7, 8, 8, 8, 8, 9, 9,11,11, 7, 5, 5, 7, 7, 8,
  137691. 8, 8, 8, 9,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  137692. 10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  137693. 11, 0,12,12, 9, 9, 9,10,10,10,11,11,11,12, 0,13,
  137694. 13, 9, 9, 9, 9,10,10,11,11,11,12, 0, 0, 0,10,10,
  137695. 10,10,11,11,12,12,12,13, 0, 0, 0,10,10,10,10,11,
  137696. 11,12,12,13,12, 0, 0, 0,14,14,11,10,11,12,12,13,
  137697. 13,14, 0, 0, 0,15,15,11,11,12,11,12,12,14,13, 0,
  137698. 0, 0, 0, 0,12,12,12,12,13,13,14,14, 0, 0, 0, 0,
  137699. 0,13,13,12,12,13,13,13,14,
  137700. };
  137701. static float _vq_quantthresh__44cn1_s_p7_0[] = {
  137702. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  137703. 12.5, 17.5, 22.5, 27.5,
  137704. };
  137705. static long _vq_quantmap__44cn1_s_p7_0[] = {
  137706. 11, 9, 7, 5, 3, 1, 0, 2,
  137707. 4, 6, 8, 10, 12,
  137708. };
  137709. static encode_aux_threshmatch _vq_auxt__44cn1_s_p7_0 = {
  137710. _vq_quantthresh__44cn1_s_p7_0,
  137711. _vq_quantmap__44cn1_s_p7_0,
  137712. 13,
  137713. 13
  137714. };
  137715. static static_codebook _44cn1_s_p7_0 = {
  137716. 2, 169,
  137717. _vq_lengthlist__44cn1_s_p7_0,
  137718. 1, -526516224, 1616117760, 4, 0,
  137719. _vq_quantlist__44cn1_s_p7_0,
  137720. NULL,
  137721. &_vq_auxt__44cn1_s_p7_0,
  137722. NULL,
  137723. 0
  137724. };
  137725. static long _vq_quantlist__44cn1_s_p7_1[] = {
  137726. 2,
  137727. 1,
  137728. 3,
  137729. 0,
  137730. 4,
  137731. };
  137732. static long _vq_lengthlist__44cn1_s_p7_1[] = {
  137733. 2, 3, 3, 5, 5, 6, 6, 6, 5, 5, 6, 6, 6, 5, 5, 6,
  137734. 6, 6, 5, 5, 6, 6, 6, 5, 5,
  137735. };
  137736. static float _vq_quantthresh__44cn1_s_p7_1[] = {
  137737. -1.5, -0.5, 0.5, 1.5,
  137738. };
  137739. static long _vq_quantmap__44cn1_s_p7_1[] = {
  137740. 3, 1, 0, 2, 4,
  137741. };
  137742. static encode_aux_threshmatch _vq_auxt__44cn1_s_p7_1 = {
  137743. _vq_quantthresh__44cn1_s_p7_1,
  137744. _vq_quantmap__44cn1_s_p7_1,
  137745. 5,
  137746. 5
  137747. };
  137748. static static_codebook _44cn1_s_p7_1 = {
  137749. 2, 25,
  137750. _vq_lengthlist__44cn1_s_p7_1,
  137751. 1, -533725184, 1611661312, 3, 0,
  137752. _vq_quantlist__44cn1_s_p7_1,
  137753. NULL,
  137754. &_vq_auxt__44cn1_s_p7_1,
  137755. NULL,
  137756. 0
  137757. };
  137758. static long _vq_quantlist__44cn1_s_p8_0[] = {
  137759. 2,
  137760. 1,
  137761. 3,
  137762. 0,
  137763. 4,
  137764. };
  137765. static long _vq_lengthlist__44cn1_s_p8_0[] = {
  137766. 1, 7, 7,11,11, 8,11,11,11,11, 4,11, 3,11,11,11,
  137767. 11,11,11,11,11,11,11,11,11,11,11,10,11,11,11,11,
  137768. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  137769. 11,11,11,10,11,11,11,11,11,11,11,11,11,11,11,11,
  137770. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  137771. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  137772. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  137773. 11,11,11,11,11,11,11,11,11,11,11,11,11, 7,11,11,
  137774. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  137775. 11,11,11,11,11,11,10,11,11,11,11,11,11,11,11,11,
  137776. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,10,
  137777. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  137778. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  137779. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  137780. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  137781. 11,11,11,11,11,11,11,11,11,11, 8,11,11,11,11,11,
  137782. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  137783. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  137784. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  137785. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  137786. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  137787. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  137788. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  137789. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  137790. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  137791. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  137792. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  137793. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  137794. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  137795. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  137796. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  137797. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  137798. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  137799. 11,11,11,11,11,11,11,12,12,12,12,12,12,12,12,12,
  137800. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  137801. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  137802. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  137803. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  137804. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  137805. 12,
  137806. };
  137807. static float _vq_quantthresh__44cn1_s_p8_0[] = {
  137808. -331.5, -110.5, 110.5, 331.5,
  137809. };
  137810. static long _vq_quantmap__44cn1_s_p8_0[] = {
  137811. 3, 1, 0, 2, 4,
  137812. };
  137813. static encode_aux_threshmatch _vq_auxt__44cn1_s_p8_0 = {
  137814. _vq_quantthresh__44cn1_s_p8_0,
  137815. _vq_quantmap__44cn1_s_p8_0,
  137816. 5,
  137817. 5
  137818. };
  137819. static static_codebook _44cn1_s_p8_0 = {
  137820. 4, 625,
  137821. _vq_lengthlist__44cn1_s_p8_0,
  137822. 1, -518283264, 1627103232, 3, 0,
  137823. _vq_quantlist__44cn1_s_p8_0,
  137824. NULL,
  137825. &_vq_auxt__44cn1_s_p8_0,
  137826. NULL,
  137827. 0
  137828. };
  137829. static long _vq_quantlist__44cn1_s_p8_1[] = {
  137830. 6,
  137831. 5,
  137832. 7,
  137833. 4,
  137834. 8,
  137835. 3,
  137836. 9,
  137837. 2,
  137838. 10,
  137839. 1,
  137840. 11,
  137841. 0,
  137842. 12,
  137843. };
  137844. static long _vq_lengthlist__44cn1_s_p8_1[] = {
  137845. 1, 4, 4, 6, 6, 8, 8, 9,10,10,11,11,11, 6, 5, 5,
  137846. 7, 7, 8, 8, 9,10, 9,11,11,12, 5, 5, 5, 7, 7, 8,
  137847. 9,10,10,12,12,14,13,15, 7, 7, 8, 8, 9,10,11,11,
  137848. 10,12,10,11,15, 7, 8, 8, 8, 9, 9,11,11,13,12,12,
  137849. 13,15,10,10, 8, 8,10,10,12,12,11,14,10,10,15,11,
  137850. 11, 8, 8,10,10,12,13,13,14,15,13,15,15,15,10,10,
  137851. 10,10,12,12,13,12,13,10,15,15,15,10,10,11,10,13,
  137852. 11,13,13,15,13,15,15,15,13,13,10,11,11,11,12,10,
  137853. 14,11,15,15,14,14,13,10,10,12,11,13,13,14,14,15,
  137854. 15,15,15,15,11,11,11,11,12,11,15,12,15,15,15,15,
  137855. 15,12,12,11,11,14,12,13,14,
  137856. };
  137857. static float _vq_quantthresh__44cn1_s_p8_1[] = {
  137858. -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5, 25.5,
  137859. 42.5, 59.5, 76.5, 93.5,
  137860. };
  137861. static long _vq_quantmap__44cn1_s_p8_1[] = {
  137862. 11, 9, 7, 5, 3, 1, 0, 2,
  137863. 4, 6, 8, 10, 12,
  137864. };
  137865. static encode_aux_threshmatch _vq_auxt__44cn1_s_p8_1 = {
  137866. _vq_quantthresh__44cn1_s_p8_1,
  137867. _vq_quantmap__44cn1_s_p8_1,
  137868. 13,
  137869. 13
  137870. };
  137871. static static_codebook _44cn1_s_p8_1 = {
  137872. 2, 169,
  137873. _vq_lengthlist__44cn1_s_p8_1,
  137874. 1, -522616832, 1620115456, 4, 0,
  137875. _vq_quantlist__44cn1_s_p8_1,
  137876. NULL,
  137877. &_vq_auxt__44cn1_s_p8_1,
  137878. NULL,
  137879. 0
  137880. };
  137881. static long _vq_quantlist__44cn1_s_p8_2[] = {
  137882. 8,
  137883. 7,
  137884. 9,
  137885. 6,
  137886. 10,
  137887. 5,
  137888. 11,
  137889. 4,
  137890. 12,
  137891. 3,
  137892. 13,
  137893. 2,
  137894. 14,
  137895. 1,
  137896. 15,
  137897. 0,
  137898. 16,
  137899. };
  137900. static long _vq_lengthlist__44cn1_s_p8_2[] = {
  137901. 3, 4, 3, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9, 9, 9, 9,
  137902. 9,10,11,11, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9, 9, 9,
  137903. 9, 9,10,10,10, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9, 9,
  137904. 9, 9, 9,10,10,10, 7, 7, 7, 8, 8, 8, 9, 9, 9, 9,
  137905. 9, 9,10, 9,10,11,10, 7, 6, 7, 7, 8, 8, 9, 9, 9,
  137906. 9, 9, 9, 9,10,10,10,11, 7, 7, 8, 8, 8, 8, 9, 9,
  137907. 9, 9, 9, 9, 9, 9,10,10,10, 7, 7, 8, 8, 8, 8, 9,
  137908. 9, 9, 9, 9, 9, 9,10,11,11,11, 8, 8, 8, 8, 8, 8,
  137909. 9, 9, 9, 9, 9, 9, 9, 9,11,10,10,11,11, 8, 8, 8,
  137910. 9, 9, 9, 9, 9, 9,10, 9,10,10,10,10,11,11, 9, 9,
  137911. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,11,11,10,11,11, 9,
  137912. 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,10,11,10,11,11,
  137913. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,11,10,10,11,
  137914. 11,11,11, 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,11,11,
  137915. 10,11,11,11, 9,10,10, 9, 9, 9, 9, 9, 9, 9,10,11,
  137916. 11,11,11,11,11, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,11,
  137917. 11,11,11,11,11,11,10,10, 9, 9, 9, 9, 9, 9, 9, 9,
  137918. 11,11,11,10,11,11,11,11,11, 9, 9, 9,10, 9, 9, 9,
  137919. 9,
  137920. };
  137921. static float _vq_quantthresh__44cn1_s_p8_2[] = {
  137922. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  137923. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  137924. };
  137925. static long _vq_quantmap__44cn1_s_p8_2[] = {
  137926. 15, 13, 11, 9, 7, 5, 3, 1,
  137927. 0, 2, 4, 6, 8, 10, 12, 14,
  137928. 16,
  137929. };
  137930. static encode_aux_threshmatch _vq_auxt__44cn1_s_p8_2 = {
  137931. _vq_quantthresh__44cn1_s_p8_2,
  137932. _vq_quantmap__44cn1_s_p8_2,
  137933. 17,
  137934. 17
  137935. };
  137936. static static_codebook _44cn1_s_p8_2 = {
  137937. 2, 289,
  137938. _vq_lengthlist__44cn1_s_p8_2,
  137939. 1, -529530880, 1611661312, 5, 0,
  137940. _vq_quantlist__44cn1_s_p8_2,
  137941. NULL,
  137942. &_vq_auxt__44cn1_s_p8_2,
  137943. NULL,
  137944. 0
  137945. };
  137946. static long _huff_lengthlist__44cn1_s_short[] = {
  137947. 10, 9,12,15,12,13,16,14,16, 7, 1, 5,14, 7,10,13,
  137948. 16,16, 9, 4, 6,16, 8,11,16,16,16,14, 4, 7,16, 9,
  137949. 12,14,16,16,10, 5, 7,14, 9,12,14,15,15,13, 8, 9,
  137950. 14,10,12,13,14,15,13, 9, 9, 7, 6, 8,11,12,12,14,
  137951. 8, 8, 5, 4, 5, 8,11,12,16,10,10, 6, 5, 6, 8, 9,
  137952. 10,
  137953. };
  137954. static static_codebook _huff_book__44cn1_s_short = {
  137955. 2, 81,
  137956. _huff_lengthlist__44cn1_s_short,
  137957. 0, 0, 0, 0, 0,
  137958. NULL,
  137959. NULL,
  137960. NULL,
  137961. NULL,
  137962. 0
  137963. };
  137964. static long _huff_lengthlist__44cn1_sm_long[] = {
  137965. 3, 3, 8, 8, 8, 8,10,12,14, 3, 2, 6, 7, 7, 8,10,
  137966. 12,16, 7, 6, 7, 9, 8,10,12,14,16, 8, 6, 8, 4, 5,
  137967. 7, 9,11,13, 7, 6, 8, 5, 6, 7, 9,11,14, 8, 8,10,
  137968. 7, 7, 6, 8,10,13, 9,11,12, 9, 9, 7, 8,10,12,10,
  137969. 13,15,11,11,10, 9,10,13,13,16,17,14,15,14,13,14,
  137970. 17,
  137971. };
  137972. static static_codebook _huff_book__44cn1_sm_long = {
  137973. 2, 81,
  137974. _huff_lengthlist__44cn1_sm_long,
  137975. 0, 0, 0, 0, 0,
  137976. NULL,
  137977. NULL,
  137978. NULL,
  137979. NULL,
  137980. 0
  137981. };
  137982. static long _vq_quantlist__44cn1_sm_p1_0[] = {
  137983. 1,
  137984. 0,
  137985. 2,
  137986. };
  137987. static long _vq_lengthlist__44cn1_sm_p1_0[] = {
  137988. 1, 4, 5, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  137989. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137990. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137991. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137992. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137993. 0, 5, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0, 0,
  137994. 0, 0, 0, 7, 8, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137995. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137996. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137997. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137998. 0, 0, 5, 8, 8, 0, 0, 0, 0, 0, 0, 7, 9, 8, 0, 0,
  137999. 0, 0, 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138000. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138001. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138002. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138003. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138004. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138005. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138006. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138007. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138008. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138009. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138010. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138011. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138012. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138013. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138014. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138015. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138016. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138017. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138018. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138019. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138020. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138021. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138022. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138023. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138024. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138025. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138026. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138027. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138028. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138029. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138030. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138031. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138032. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138033. 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 8, 8, 0, 0, 0, 0,
  138034. 0, 0, 8,10, 9, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0,
  138035. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138036. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138037. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138038. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7,10, 9, 0, 0, 0,
  138039. 0, 0, 0, 9, 9,10, 0, 0, 0, 0, 0, 0, 9,10,10, 0,
  138040. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138041. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138042. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138043. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  138044. 0, 0, 0, 0, 8,10, 9, 0, 0, 0, 0, 0, 0, 9,10,10,
  138045. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138046. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138047. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138048. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138049. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138050. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138051. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138052. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138053. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138054. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138055. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138056. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138057. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138058. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138059. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138060. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138061. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138062. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138063. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138064. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138065. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138066. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138067. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138068. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138069. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138070. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138071. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138072. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138073. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138074. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138075. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138076. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138077. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138078. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138079. 0, 0, 5, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0,
  138080. 0, 0, 0, 0, 8, 9,10, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138081. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138082. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138083. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138084. 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,10,10, 0,
  138085. 0, 0, 0, 0, 0, 8, 9,10, 0, 0, 0, 0, 0, 0, 0, 0,
  138086. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138087. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138088. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138089. 0, 0, 0, 0, 7, 9,10, 0, 0, 0, 0, 0, 0, 9,10,10,
  138090. 0, 0, 0, 0, 0, 0, 9,10, 9, 0, 0, 0, 0, 0, 0, 0,
  138091. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138092. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138093. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138094. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138095. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138096. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138097. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138098. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138099. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138100. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138101. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138102. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138103. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138104. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138105. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138106. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138107. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138108. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138109. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138110. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138111. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138112. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138113. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138114. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138115. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138116. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138117. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138118. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138119. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138120. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138121. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138122. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138123. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138124. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138125. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138126. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138127. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138128. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138129. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138130. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138131. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138132. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138133. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138134. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138135. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138136. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138137. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138138. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138139. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138140. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138141. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138142. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138143. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138144. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138145. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138146. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138147. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138148. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138149. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138150. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138151. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138152. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138153. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138154. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138155. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138156. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138157. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138158. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138159. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138160. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138161. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138162. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138163. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138164. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138165. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138166. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138167. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138168. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138169. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138170. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138171. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138172. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138173. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138174. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138175. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138176. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138177. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138178. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138179. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138180. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138181. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138182. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138183. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138184. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138185. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138186. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138187. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138188. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138189. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138190. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138191. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138192. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138193. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138194. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138195. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138196. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138197. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138198. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138199. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138200. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138201. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138202. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138203. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138204. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138205. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138206. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138207. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138208. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138209. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138210. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138211. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138212. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138213. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138214. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138215. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138216. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138217. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138218. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138219. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138220. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138221. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138222. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138223. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138224. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138225. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138226. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138227. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138228. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138229. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138230. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138231. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138232. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138233. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138234. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138235. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138236. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138237. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138238. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138239. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138240. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138241. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138242. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138243. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138244. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138245. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138246. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138247. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138248. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138249. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138250. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138251. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138252. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138253. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138254. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138255. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138256. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138257. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138258. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138259. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138260. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138261. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138262. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138263. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138264. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138265. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138266. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138267. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138268. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138269. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138270. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138271. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138272. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138273. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138274. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138275. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138276. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138277. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138278. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138279. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138280. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138281. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138282. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138283. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138284. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138285. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138286. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138287. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138288. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138289. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138290. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138291. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138292. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138293. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138294. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138295. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138296. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138297. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138298. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138299. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138300. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138301. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138302. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138303. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138304. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138305. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138306. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138307. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138308. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138309. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138310. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138311. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138312. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138313. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138314. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138315. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138316. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138317. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138318. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138319. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138320. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138321. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138322. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138323. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138324. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138325. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138326. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138327. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138328. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138329. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138330. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138331. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138332. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138333. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138334. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138335. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138336. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138337. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138338. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138339. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138340. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138341. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138342. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138343. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138344. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138345. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138346. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138347. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138348. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138349. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138350. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138351. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138352. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138353. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138354. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138355. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138356. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138357. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138358. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138359. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138360. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138361. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138362. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138363. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138364. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138365. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138366. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138367. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138368. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138369. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138370. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138371. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138372. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138373. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138374. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138375. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138376. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138377. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138378. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138379. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138380. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138381. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138382. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138383. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138384. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138385. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138386. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138387. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138388. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138389. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138390. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138391. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138392. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138393. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138394. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138395. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138396. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138397. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138398. 0,
  138399. };
  138400. static float _vq_quantthresh__44cn1_sm_p1_0[] = {
  138401. -0.5, 0.5,
  138402. };
  138403. static long _vq_quantmap__44cn1_sm_p1_0[] = {
  138404. 1, 0, 2,
  138405. };
  138406. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p1_0 = {
  138407. _vq_quantthresh__44cn1_sm_p1_0,
  138408. _vq_quantmap__44cn1_sm_p1_0,
  138409. 3,
  138410. 3
  138411. };
  138412. static static_codebook _44cn1_sm_p1_0 = {
  138413. 8, 6561,
  138414. _vq_lengthlist__44cn1_sm_p1_0,
  138415. 1, -535822336, 1611661312, 2, 0,
  138416. _vq_quantlist__44cn1_sm_p1_0,
  138417. NULL,
  138418. &_vq_auxt__44cn1_sm_p1_0,
  138419. NULL,
  138420. 0
  138421. };
  138422. static long _vq_quantlist__44cn1_sm_p2_0[] = {
  138423. 2,
  138424. 1,
  138425. 3,
  138426. 0,
  138427. 4,
  138428. };
  138429. static long _vq_lengthlist__44cn1_sm_p2_0[] = {
  138430. 1, 4, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138431. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 5, 5, 7, 7, 0, 0,
  138432. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138433. 0, 0, 4, 5, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138434. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 7, 7, 9, 9,
  138435. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138436. 0, 0, 0, 0, 7, 7, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0,
  138437. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138438. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138439. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138440. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138441. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138442. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138443. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138444. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138445. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138446. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138447. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138448. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138449. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138450. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138451. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138452. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138453. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138454. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138455. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138456. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138457. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138458. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138459. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138460. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138461. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138462. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138463. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138464. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138465. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138466. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138467. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138468. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138469. 0,
  138470. };
  138471. static float _vq_quantthresh__44cn1_sm_p2_0[] = {
  138472. -1.5, -0.5, 0.5, 1.5,
  138473. };
  138474. static long _vq_quantmap__44cn1_sm_p2_0[] = {
  138475. 3, 1, 0, 2, 4,
  138476. };
  138477. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p2_0 = {
  138478. _vq_quantthresh__44cn1_sm_p2_0,
  138479. _vq_quantmap__44cn1_sm_p2_0,
  138480. 5,
  138481. 5
  138482. };
  138483. static static_codebook _44cn1_sm_p2_0 = {
  138484. 4, 625,
  138485. _vq_lengthlist__44cn1_sm_p2_0,
  138486. 1, -533725184, 1611661312, 3, 0,
  138487. _vq_quantlist__44cn1_sm_p2_0,
  138488. NULL,
  138489. &_vq_auxt__44cn1_sm_p2_0,
  138490. NULL,
  138491. 0
  138492. };
  138493. static long _vq_quantlist__44cn1_sm_p3_0[] = {
  138494. 4,
  138495. 3,
  138496. 5,
  138497. 2,
  138498. 6,
  138499. 1,
  138500. 7,
  138501. 0,
  138502. 8,
  138503. };
  138504. static long _vq_lengthlist__44cn1_sm_p3_0[] = {
  138505. 1, 3, 4, 7, 7, 0, 0, 0, 0, 0, 4, 4, 7, 7, 0, 0,
  138506. 0, 0, 0, 4, 5, 7, 7, 0, 0, 0, 0, 0, 6, 7, 8, 8,
  138507. 0, 0, 0, 0, 0, 0, 0, 8, 8, 0, 0, 0, 0, 0, 0, 0,
  138508. 9, 9, 0, 0, 0, 0, 0, 0, 0,10, 9, 0, 0, 0, 0, 0,
  138509. 0, 0,11,11, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138510. 0,
  138511. };
  138512. static float _vq_quantthresh__44cn1_sm_p3_0[] = {
  138513. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  138514. };
  138515. static long _vq_quantmap__44cn1_sm_p3_0[] = {
  138516. 7, 5, 3, 1, 0, 2, 4, 6,
  138517. 8,
  138518. };
  138519. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p3_0 = {
  138520. _vq_quantthresh__44cn1_sm_p3_0,
  138521. _vq_quantmap__44cn1_sm_p3_0,
  138522. 9,
  138523. 9
  138524. };
  138525. static static_codebook _44cn1_sm_p3_0 = {
  138526. 2, 81,
  138527. _vq_lengthlist__44cn1_sm_p3_0,
  138528. 1, -531628032, 1611661312, 4, 0,
  138529. _vq_quantlist__44cn1_sm_p3_0,
  138530. NULL,
  138531. &_vq_auxt__44cn1_sm_p3_0,
  138532. NULL,
  138533. 0
  138534. };
  138535. static long _vq_quantlist__44cn1_sm_p4_0[] = {
  138536. 4,
  138537. 3,
  138538. 5,
  138539. 2,
  138540. 6,
  138541. 1,
  138542. 7,
  138543. 0,
  138544. 8,
  138545. };
  138546. static long _vq_lengthlist__44cn1_sm_p4_0[] = {
  138547. 1, 4, 3, 6, 6, 7, 7, 9, 9, 0, 5, 5, 7, 7, 8, 7,
  138548. 9, 9, 0, 5, 5, 7, 7, 8, 8, 9, 9, 0, 7, 7, 8, 8,
  138549. 8, 8,10,10, 0, 0, 0, 8, 8, 8, 8,10,10, 0, 0, 0,
  138550. 9, 9, 9, 9,10,10, 0, 0, 0, 9, 9, 9, 9,10,10, 0,
  138551. 0, 0,10,10,10,10,11,11, 0, 0, 0, 0, 0,10,10,11,
  138552. 11,
  138553. };
  138554. static float _vq_quantthresh__44cn1_sm_p4_0[] = {
  138555. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  138556. };
  138557. static long _vq_quantmap__44cn1_sm_p4_0[] = {
  138558. 7, 5, 3, 1, 0, 2, 4, 6,
  138559. 8,
  138560. };
  138561. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p4_0 = {
  138562. _vq_quantthresh__44cn1_sm_p4_0,
  138563. _vq_quantmap__44cn1_sm_p4_0,
  138564. 9,
  138565. 9
  138566. };
  138567. static static_codebook _44cn1_sm_p4_0 = {
  138568. 2, 81,
  138569. _vq_lengthlist__44cn1_sm_p4_0,
  138570. 1, -531628032, 1611661312, 4, 0,
  138571. _vq_quantlist__44cn1_sm_p4_0,
  138572. NULL,
  138573. &_vq_auxt__44cn1_sm_p4_0,
  138574. NULL,
  138575. 0
  138576. };
  138577. static long _vq_quantlist__44cn1_sm_p5_0[] = {
  138578. 8,
  138579. 7,
  138580. 9,
  138581. 6,
  138582. 10,
  138583. 5,
  138584. 11,
  138585. 4,
  138586. 12,
  138587. 3,
  138588. 13,
  138589. 2,
  138590. 14,
  138591. 1,
  138592. 15,
  138593. 0,
  138594. 16,
  138595. };
  138596. static long _vq_lengthlist__44cn1_sm_p5_0[] = {
  138597. 1, 4, 4, 6, 6, 8, 8, 9, 9, 8, 8, 9, 9,10,10,11,
  138598. 11, 0, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9,10,10,11,11,
  138599. 12,12, 0, 6, 5, 7, 7, 8, 8, 9, 9, 9, 9,10,10,11,
  138600. 11,12,12, 0, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  138601. 11,11,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9,10,10,11,
  138602. 11,11,11,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,10,
  138603. 11,11,12,12,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,
  138604. 10,11,11,12,12,12,12, 0, 0, 0, 9, 9, 9, 9,10,10,
  138605. 10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,10,
  138606. 10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,
  138607. 10,10,11,11,12,12,13,13,13,13, 0, 0, 0, 0, 0, 9,
  138608. 9,10,10,11,11,12,12,12,13,13,13, 0, 0, 0, 0, 0,
  138609. 10,10,11,11,11,11,12,12,13,13,14,14, 0, 0, 0, 0,
  138610. 0, 0, 0,11,11,11,11,12,12,13,13,14,14, 0, 0, 0,
  138611. 0, 0, 0, 0,11,11,12,12,13,13,13,13,14,14, 0, 0,
  138612. 0, 0, 0, 0, 0,11,11,12,12,13,13,13,13,14,14, 0,
  138613. 0, 0, 0, 0, 0, 0,12,12,12,13,13,13,14,14,14,14,
  138614. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,13,13,14,14,14,
  138615. 14,
  138616. };
  138617. static float _vq_quantthresh__44cn1_sm_p5_0[] = {
  138618. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  138619. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  138620. };
  138621. static long _vq_quantmap__44cn1_sm_p5_0[] = {
  138622. 15, 13, 11, 9, 7, 5, 3, 1,
  138623. 0, 2, 4, 6, 8, 10, 12, 14,
  138624. 16,
  138625. };
  138626. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p5_0 = {
  138627. _vq_quantthresh__44cn1_sm_p5_0,
  138628. _vq_quantmap__44cn1_sm_p5_0,
  138629. 17,
  138630. 17
  138631. };
  138632. static static_codebook _44cn1_sm_p5_0 = {
  138633. 2, 289,
  138634. _vq_lengthlist__44cn1_sm_p5_0,
  138635. 1, -529530880, 1611661312, 5, 0,
  138636. _vq_quantlist__44cn1_sm_p5_0,
  138637. NULL,
  138638. &_vq_auxt__44cn1_sm_p5_0,
  138639. NULL,
  138640. 0
  138641. };
  138642. static long _vq_quantlist__44cn1_sm_p6_0[] = {
  138643. 1,
  138644. 0,
  138645. 2,
  138646. };
  138647. static long _vq_lengthlist__44cn1_sm_p6_0[] = {
  138648. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 7, 6,10, 9, 9,11,
  138649. 9, 9, 4, 6, 7,10, 9, 9,11, 9, 9, 7,10,10,10,11,
  138650. 11,11,11,10, 6, 9, 9,11,10,10,11,10,10, 6, 9, 9,
  138651. 11,10,11,11,10,10, 7,11,11,11,11,11,12,11,11, 7,
  138652. 9, 9,11,10,10,12,10,10, 7, 9, 9,11,10,10,11,10,
  138653. 10,
  138654. };
  138655. static float _vq_quantthresh__44cn1_sm_p6_0[] = {
  138656. -5.5, 5.5,
  138657. };
  138658. static long _vq_quantmap__44cn1_sm_p6_0[] = {
  138659. 1, 0, 2,
  138660. };
  138661. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p6_0 = {
  138662. _vq_quantthresh__44cn1_sm_p6_0,
  138663. _vq_quantmap__44cn1_sm_p6_0,
  138664. 3,
  138665. 3
  138666. };
  138667. static static_codebook _44cn1_sm_p6_0 = {
  138668. 4, 81,
  138669. _vq_lengthlist__44cn1_sm_p6_0,
  138670. 1, -529137664, 1618345984, 2, 0,
  138671. _vq_quantlist__44cn1_sm_p6_0,
  138672. NULL,
  138673. &_vq_auxt__44cn1_sm_p6_0,
  138674. NULL,
  138675. 0
  138676. };
  138677. static long _vq_quantlist__44cn1_sm_p6_1[] = {
  138678. 5,
  138679. 4,
  138680. 6,
  138681. 3,
  138682. 7,
  138683. 2,
  138684. 8,
  138685. 1,
  138686. 9,
  138687. 0,
  138688. 10,
  138689. };
  138690. static long _vq_lengthlist__44cn1_sm_p6_1[] = {
  138691. 2, 4, 4, 5, 5, 7, 7, 7, 7, 8, 8,10, 5, 5, 6, 6,
  138692. 7, 7, 8, 8, 8, 8,10, 5, 5, 6, 6, 7, 7, 8, 8, 8,
  138693. 8,10, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10, 7,
  138694. 7, 7, 7, 8, 8, 8, 8,10,10,10, 8, 8, 8, 8, 8, 8,
  138695. 8, 8,10,10,10, 8, 8, 8, 8, 8, 8, 8, 8,10,10,10,
  138696. 8, 8, 8, 8, 8, 8, 9, 9,10,10,10,10,10, 8, 8, 8,
  138697. 8, 9, 9,10,10,10,10,10, 9, 9, 9, 9, 8, 9,10,10,
  138698. 10,10,10, 8, 9, 8, 8, 9, 8,
  138699. };
  138700. static float _vq_quantthresh__44cn1_sm_p6_1[] = {
  138701. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  138702. 3.5, 4.5,
  138703. };
  138704. static long _vq_quantmap__44cn1_sm_p6_1[] = {
  138705. 9, 7, 5, 3, 1, 0, 2, 4,
  138706. 6, 8, 10,
  138707. };
  138708. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p6_1 = {
  138709. _vq_quantthresh__44cn1_sm_p6_1,
  138710. _vq_quantmap__44cn1_sm_p6_1,
  138711. 11,
  138712. 11
  138713. };
  138714. static static_codebook _44cn1_sm_p6_1 = {
  138715. 2, 121,
  138716. _vq_lengthlist__44cn1_sm_p6_1,
  138717. 1, -531365888, 1611661312, 4, 0,
  138718. _vq_quantlist__44cn1_sm_p6_1,
  138719. NULL,
  138720. &_vq_auxt__44cn1_sm_p6_1,
  138721. NULL,
  138722. 0
  138723. };
  138724. static long _vq_quantlist__44cn1_sm_p7_0[] = {
  138725. 6,
  138726. 5,
  138727. 7,
  138728. 4,
  138729. 8,
  138730. 3,
  138731. 9,
  138732. 2,
  138733. 10,
  138734. 1,
  138735. 11,
  138736. 0,
  138737. 12,
  138738. };
  138739. static long _vq_lengthlist__44cn1_sm_p7_0[] = {
  138740. 1, 4, 4, 6, 6, 7, 7, 7, 7, 9, 9,10,10, 7, 5, 5,
  138741. 7, 7, 8, 8, 8, 8,10, 9,11,10, 7, 5, 5, 7, 7, 8,
  138742. 8, 8, 8, 9,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  138743. 10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  138744. 11, 0,12,12, 9, 9, 9,10,10,10,11,11,12,12, 0,13,
  138745. 13, 9, 9, 9, 9,10,10,11,11,12,12, 0, 0, 0,10,10,
  138746. 10,10,11,11,12,12,12,13, 0, 0, 0,10,10,10,10,11,
  138747. 11,12,12,12,12, 0, 0, 0,14,14,11,11,11,11,12,13,
  138748. 13,13, 0, 0, 0,14,14,11,10,11,11,12,12,13,13, 0,
  138749. 0, 0, 0, 0,12,12,12,12,13,13,13,14, 0, 0, 0, 0,
  138750. 0,13,12,12,12,13,13,13,14,
  138751. };
  138752. static float _vq_quantthresh__44cn1_sm_p7_0[] = {
  138753. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  138754. 12.5, 17.5, 22.5, 27.5,
  138755. };
  138756. static long _vq_quantmap__44cn1_sm_p7_0[] = {
  138757. 11, 9, 7, 5, 3, 1, 0, 2,
  138758. 4, 6, 8, 10, 12,
  138759. };
  138760. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p7_0 = {
  138761. _vq_quantthresh__44cn1_sm_p7_0,
  138762. _vq_quantmap__44cn1_sm_p7_0,
  138763. 13,
  138764. 13
  138765. };
  138766. static static_codebook _44cn1_sm_p7_0 = {
  138767. 2, 169,
  138768. _vq_lengthlist__44cn1_sm_p7_0,
  138769. 1, -526516224, 1616117760, 4, 0,
  138770. _vq_quantlist__44cn1_sm_p7_0,
  138771. NULL,
  138772. &_vq_auxt__44cn1_sm_p7_0,
  138773. NULL,
  138774. 0
  138775. };
  138776. static long _vq_quantlist__44cn1_sm_p7_1[] = {
  138777. 2,
  138778. 1,
  138779. 3,
  138780. 0,
  138781. 4,
  138782. };
  138783. static long _vq_lengthlist__44cn1_sm_p7_1[] = {
  138784. 2, 4, 4, 4, 5, 6, 5, 5, 5, 5, 6, 5, 5, 5, 5, 6,
  138785. 5, 5, 5, 5, 6, 6, 6, 5, 5,
  138786. };
  138787. static float _vq_quantthresh__44cn1_sm_p7_1[] = {
  138788. -1.5, -0.5, 0.5, 1.5,
  138789. };
  138790. static long _vq_quantmap__44cn1_sm_p7_1[] = {
  138791. 3, 1, 0, 2, 4,
  138792. };
  138793. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p7_1 = {
  138794. _vq_quantthresh__44cn1_sm_p7_1,
  138795. _vq_quantmap__44cn1_sm_p7_1,
  138796. 5,
  138797. 5
  138798. };
  138799. static static_codebook _44cn1_sm_p7_1 = {
  138800. 2, 25,
  138801. _vq_lengthlist__44cn1_sm_p7_1,
  138802. 1, -533725184, 1611661312, 3, 0,
  138803. _vq_quantlist__44cn1_sm_p7_1,
  138804. NULL,
  138805. &_vq_auxt__44cn1_sm_p7_1,
  138806. NULL,
  138807. 0
  138808. };
  138809. static long _vq_quantlist__44cn1_sm_p8_0[] = {
  138810. 4,
  138811. 3,
  138812. 5,
  138813. 2,
  138814. 6,
  138815. 1,
  138816. 7,
  138817. 0,
  138818. 8,
  138819. };
  138820. static long _vq_lengthlist__44cn1_sm_p8_0[] = {
  138821. 1, 4, 4,12,11,13,13,14,14, 4, 7, 7,11,13,14,14,
  138822. 14,14, 3, 8, 3,14,14,14,14,14,14,14,10,12,14,14,
  138823. 14,14,14,14,14,14, 5,14, 8,14,14,14,14,14,12,14,
  138824. 13,14,14,14,14,14,14,14,13,14,10,14,14,14,14,14,
  138825. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  138826. 14,
  138827. };
  138828. static float _vq_quantthresh__44cn1_sm_p8_0[] = {
  138829. -773.5, -552.5, -331.5, -110.5, 110.5, 331.5, 552.5, 773.5,
  138830. };
  138831. static long _vq_quantmap__44cn1_sm_p8_0[] = {
  138832. 7, 5, 3, 1, 0, 2, 4, 6,
  138833. 8,
  138834. };
  138835. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p8_0 = {
  138836. _vq_quantthresh__44cn1_sm_p8_0,
  138837. _vq_quantmap__44cn1_sm_p8_0,
  138838. 9,
  138839. 9
  138840. };
  138841. static static_codebook _44cn1_sm_p8_0 = {
  138842. 2, 81,
  138843. _vq_lengthlist__44cn1_sm_p8_0,
  138844. 1, -516186112, 1627103232, 4, 0,
  138845. _vq_quantlist__44cn1_sm_p8_0,
  138846. NULL,
  138847. &_vq_auxt__44cn1_sm_p8_0,
  138848. NULL,
  138849. 0
  138850. };
  138851. static long _vq_quantlist__44cn1_sm_p8_1[] = {
  138852. 6,
  138853. 5,
  138854. 7,
  138855. 4,
  138856. 8,
  138857. 3,
  138858. 9,
  138859. 2,
  138860. 10,
  138861. 1,
  138862. 11,
  138863. 0,
  138864. 12,
  138865. };
  138866. static long _vq_lengthlist__44cn1_sm_p8_1[] = {
  138867. 1, 4, 4, 6, 6, 8, 8, 9, 9,10,11,11,11, 6, 5, 5,
  138868. 7, 7, 8, 8,10,10,10,11,11,11, 6, 5, 5, 7, 7, 8,
  138869. 8,10,10,11,12,12,12,14, 7, 7, 7, 8, 9, 9,11,11,
  138870. 11,12,11,12,17, 7, 7, 8, 7, 9, 9,11,11,12,12,12,
  138871. 12,14,11,11, 8, 8,10,10,11,12,12,13,11,12,14,11,
  138872. 11, 8, 8,10,10,11,12,12,13,13,12,14,15,14,10,10,
  138873. 10,10,11,12,12,12,12,11,14,13,16,10,10,10, 9,12,
  138874. 11,12,12,13,14,14,15,14,14,13,10,10,11,11,12,11,
  138875. 13,11,14,12,15,13,14,11,10,12,10,12,12,13,13,13,
  138876. 13,14,15,15,12,12,11,11,12,11,13,12,14,14,14,14,
  138877. 17,12,12,11,10,13,11,13,13,
  138878. };
  138879. static float _vq_quantthresh__44cn1_sm_p8_1[] = {
  138880. -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5, 25.5,
  138881. 42.5, 59.5, 76.5, 93.5,
  138882. };
  138883. static long _vq_quantmap__44cn1_sm_p8_1[] = {
  138884. 11, 9, 7, 5, 3, 1, 0, 2,
  138885. 4, 6, 8, 10, 12,
  138886. };
  138887. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p8_1 = {
  138888. _vq_quantthresh__44cn1_sm_p8_1,
  138889. _vq_quantmap__44cn1_sm_p8_1,
  138890. 13,
  138891. 13
  138892. };
  138893. static static_codebook _44cn1_sm_p8_1 = {
  138894. 2, 169,
  138895. _vq_lengthlist__44cn1_sm_p8_1,
  138896. 1, -522616832, 1620115456, 4, 0,
  138897. _vq_quantlist__44cn1_sm_p8_1,
  138898. NULL,
  138899. &_vq_auxt__44cn1_sm_p8_1,
  138900. NULL,
  138901. 0
  138902. };
  138903. static long _vq_quantlist__44cn1_sm_p8_2[] = {
  138904. 8,
  138905. 7,
  138906. 9,
  138907. 6,
  138908. 10,
  138909. 5,
  138910. 11,
  138911. 4,
  138912. 12,
  138913. 3,
  138914. 13,
  138915. 2,
  138916. 14,
  138917. 1,
  138918. 15,
  138919. 0,
  138920. 16,
  138921. };
  138922. static long _vq_lengthlist__44cn1_sm_p8_2[] = {
  138923. 3, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  138924. 9,10, 6, 6, 6, 6, 7, 7, 8, 8, 8, 9, 9, 9, 9, 9,
  138925. 9, 9,10, 6, 6, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9,
  138926. 9, 9, 9,10, 7, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9,
  138927. 9, 9, 9, 9,10,10,10, 7, 7, 7, 8, 8, 8, 9, 9, 9,
  138928. 9, 9, 9, 9, 9,10,10,10, 8, 8, 8, 8, 8, 8, 9, 9,
  138929. 9, 9, 9, 9, 9, 9,10,10,10, 8, 8, 8, 8, 8, 8, 9,
  138930. 9, 9, 9, 9, 9, 9, 9,11,10,11, 8, 8, 8, 8, 8, 8,
  138931. 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,11,11, 8, 8, 8,
  138932. 8, 9, 9, 9, 9, 9, 9, 9, 9,11,10,11,11,11, 9, 9,
  138933. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,11,10,11,11, 9,
  138934. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,11,11,10,11,11,
  138935. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,11,10,11,11,
  138936. 11,11,11, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,11,11,
  138937. 11,11,11,11, 9,10,10,10, 9, 9, 9, 9, 9, 9,11,10,
  138938. 11,11,11,11,11, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,11,
  138939. 11,11,11,11,11,11,10,10, 9, 9, 9, 9, 9, 9, 9, 9,
  138940. 10,11,11,11,11,11,11,11,11, 9, 9, 9, 9, 9, 9, 9,
  138941. 9,
  138942. };
  138943. static float _vq_quantthresh__44cn1_sm_p8_2[] = {
  138944. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  138945. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  138946. };
  138947. static long _vq_quantmap__44cn1_sm_p8_2[] = {
  138948. 15, 13, 11, 9, 7, 5, 3, 1,
  138949. 0, 2, 4, 6, 8, 10, 12, 14,
  138950. 16,
  138951. };
  138952. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p8_2 = {
  138953. _vq_quantthresh__44cn1_sm_p8_2,
  138954. _vq_quantmap__44cn1_sm_p8_2,
  138955. 17,
  138956. 17
  138957. };
  138958. static static_codebook _44cn1_sm_p8_2 = {
  138959. 2, 289,
  138960. _vq_lengthlist__44cn1_sm_p8_2,
  138961. 1, -529530880, 1611661312, 5, 0,
  138962. _vq_quantlist__44cn1_sm_p8_2,
  138963. NULL,
  138964. &_vq_auxt__44cn1_sm_p8_2,
  138965. NULL,
  138966. 0
  138967. };
  138968. static long _huff_lengthlist__44cn1_sm_short[] = {
  138969. 5, 6,12,14,12,14,16,17,18, 4, 2, 5,11, 7,10,12,
  138970. 14,15, 9, 4, 5,11, 7,10,13,15,18,15, 6, 7, 5, 6,
  138971. 8,11,13,16,11, 5, 6, 5, 5, 6, 9,13,15,12, 5, 7,
  138972. 6, 5, 6, 9,12,14,12, 6, 7, 8, 6, 7, 9,12,13,14,
  138973. 8, 8, 7, 5, 5, 8,10,12,16, 9, 9, 8, 6, 6, 7, 9,
  138974. 9,
  138975. };
  138976. static static_codebook _huff_book__44cn1_sm_short = {
  138977. 2, 81,
  138978. _huff_lengthlist__44cn1_sm_short,
  138979. 0, 0, 0, 0, 0,
  138980. NULL,
  138981. NULL,
  138982. NULL,
  138983. NULL,
  138984. 0
  138985. };
  138986. /*** End of inlined file: res_books_stereo.h ***/
  138987. /***** residue backends *********************************************/
  138988. static vorbis_info_residue0 _residue_44_low={
  138989. 0,-1, -1, 9,-1,
  138990. /* 0 1 2 3 4 5 6 7 */
  138991. {0},
  138992. {-1},
  138993. { .5, 1.5, 2.5, 2.5, 4.5, 8.5, 16.5, 32.5},
  138994. { .5, .5, .5, 999., 4.5, 8.5, 16.5, 32.5},
  138995. };
  138996. static vorbis_info_residue0 _residue_44_mid={
  138997. 0,-1, -1, 10,-1,
  138998. /* 0 1 2 3 4 5 6 7 8 */
  138999. {0},
  139000. {-1},
  139001. { .5, 1.5, 1.5, 2.5, 2.5, 4.5, 8.5, 16.5, 32.5},
  139002. { .5, .5, 999., .5, 999., 4.5, 8.5, 16.5, 32.5},
  139003. };
  139004. static vorbis_info_residue0 _residue_44_high={
  139005. 0,-1, -1, 10,-1,
  139006. /* 0 1 2 3 4 5 6 7 8 */
  139007. {0},
  139008. {-1},
  139009. { .5, 1.5, 2.5, 4.5, 8.5, 16.5, 32.5, 71.5,157.5},
  139010. { .5, 1.5, 2.5, 3.5, 4.5, 8.5, 16.5, 71.5,157.5},
  139011. };
  139012. static static_bookblock _resbook_44s_n1={
  139013. {
  139014. {0},{0,0,&_44cn1_s_p1_0},{0,0,&_44cn1_s_p2_0},
  139015. {0,0,&_44cn1_s_p3_0},{0,0,&_44cn1_s_p4_0},{0,0,&_44cn1_s_p5_0},
  139016. {&_44cn1_s_p6_0,&_44cn1_s_p6_1},{&_44cn1_s_p7_0,&_44cn1_s_p7_1},
  139017. {&_44cn1_s_p8_0,&_44cn1_s_p8_1,&_44cn1_s_p8_2}
  139018. }
  139019. };
  139020. static static_bookblock _resbook_44sm_n1={
  139021. {
  139022. {0},{0,0,&_44cn1_sm_p1_0},{0,0,&_44cn1_sm_p2_0},
  139023. {0,0,&_44cn1_sm_p3_0},{0,0,&_44cn1_sm_p4_0},{0,0,&_44cn1_sm_p5_0},
  139024. {&_44cn1_sm_p6_0,&_44cn1_sm_p6_1},{&_44cn1_sm_p7_0,&_44cn1_sm_p7_1},
  139025. {&_44cn1_sm_p8_0,&_44cn1_sm_p8_1,&_44cn1_sm_p8_2}
  139026. }
  139027. };
  139028. static static_bookblock _resbook_44s_0={
  139029. {
  139030. {0},{0,0,&_44c0_s_p1_0},{0,0,&_44c0_s_p2_0},
  139031. {0,0,&_44c0_s_p3_0},{0,0,&_44c0_s_p4_0},{0,0,&_44c0_s_p5_0},
  139032. {&_44c0_s_p6_0,&_44c0_s_p6_1},{&_44c0_s_p7_0,&_44c0_s_p7_1},
  139033. {&_44c0_s_p8_0,&_44c0_s_p8_1,&_44c0_s_p8_2}
  139034. }
  139035. };
  139036. static static_bookblock _resbook_44sm_0={
  139037. {
  139038. {0},{0,0,&_44c0_sm_p1_0},{0,0,&_44c0_sm_p2_0},
  139039. {0,0,&_44c0_sm_p3_0},{0,0,&_44c0_sm_p4_0},{0,0,&_44c0_sm_p5_0},
  139040. {&_44c0_sm_p6_0,&_44c0_sm_p6_1},{&_44c0_sm_p7_0,&_44c0_sm_p7_1},
  139041. {&_44c0_sm_p8_0,&_44c0_sm_p8_1,&_44c0_sm_p8_2}
  139042. }
  139043. };
  139044. static static_bookblock _resbook_44s_1={
  139045. {
  139046. {0},{0,0,&_44c1_s_p1_0},{0,0,&_44c1_s_p2_0},
  139047. {0,0,&_44c1_s_p3_0},{0,0,&_44c1_s_p4_0},{0,0,&_44c1_s_p5_0},
  139048. {&_44c1_s_p6_0,&_44c1_s_p6_1},{&_44c1_s_p7_0,&_44c1_s_p7_1},
  139049. {&_44c1_s_p8_0,&_44c1_s_p8_1,&_44c1_s_p8_2}
  139050. }
  139051. };
  139052. static static_bookblock _resbook_44sm_1={
  139053. {
  139054. {0},{0,0,&_44c1_sm_p1_0},{0,0,&_44c1_sm_p2_0},
  139055. {0,0,&_44c1_sm_p3_0},{0,0,&_44c1_sm_p4_0},{0,0,&_44c1_sm_p5_0},
  139056. {&_44c1_sm_p6_0,&_44c1_sm_p6_1},{&_44c1_sm_p7_0,&_44c1_sm_p7_1},
  139057. {&_44c1_sm_p8_0,&_44c1_sm_p8_1,&_44c1_sm_p8_2}
  139058. }
  139059. };
  139060. static static_bookblock _resbook_44s_2={
  139061. {
  139062. {0},{0,0,&_44c2_s_p1_0},{0,0,&_44c2_s_p2_0},{0,0,&_44c2_s_p3_0},
  139063. {0,0,&_44c2_s_p4_0},{0,0,&_44c2_s_p5_0},{0,0,&_44c2_s_p6_0},
  139064. {&_44c2_s_p7_0,&_44c2_s_p7_1},{&_44c2_s_p8_0,&_44c2_s_p8_1},
  139065. {&_44c2_s_p9_0,&_44c2_s_p9_1,&_44c2_s_p9_2}
  139066. }
  139067. };
  139068. static static_bookblock _resbook_44s_3={
  139069. {
  139070. {0},{0,0,&_44c3_s_p1_0},{0,0,&_44c3_s_p2_0},{0,0,&_44c3_s_p3_0},
  139071. {0,0,&_44c3_s_p4_0},{0,0,&_44c3_s_p5_0},{0,0,&_44c3_s_p6_0},
  139072. {&_44c3_s_p7_0,&_44c3_s_p7_1},{&_44c3_s_p8_0,&_44c3_s_p8_1},
  139073. {&_44c3_s_p9_0,&_44c3_s_p9_1,&_44c3_s_p9_2}
  139074. }
  139075. };
  139076. static static_bookblock _resbook_44s_4={
  139077. {
  139078. {0},{0,0,&_44c4_s_p1_0},{0,0,&_44c4_s_p2_0},{0,0,&_44c4_s_p3_0},
  139079. {0,0,&_44c4_s_p4_0},{0,0,&_44c4_s_p5_0},{0,0,&_44c4_s_p6_0},
  139080. {&_44c4_s_p7_0,&_44c4_s_p7_1},{&_44c4_s_p8_0,&_44c4_s_p8_1},
  139081. {&_44c4_s_p9_0,&_44c4_s_p9_1,&_44c4_s_p9_2}
  139082. }
  139083. };
  139084. static static_bookblock _resbook_44s_5={
  139085. {
  139086. {0},{0,0,&_44c5_s_p1_0},{0,0,&_44c5_s_p2_0},{0,0,&_44c5_s_p3_0},
  139087. {0,0,&_44c5_s_p4_0},{0,0,&_44c5_s_p5_0},{0,0,&_44c5_s_p6_0},
  139088. {&_44c5_s_p7_0,&_44c5_s_p7_1},{&_44c5_s_p8_0,&_44c5_s_p8_1},
  139089. {&_44c5_s_p9_0,&_44c5_s_p9_1,&_44c5_s_p9_2}
  139090. }
  139091. };
  139092. static static_bookblock _resbook_44s_6={
  139093. {
  139094. {0},{0,0,&_44c6_s_p1_0},{0,0,&_44c6_s_p2_0},{0,0,&_44c6_s_p3_0},
  139095. {0,0,&_44c6_s_p4_0},
  139096. {&_44c6_s_p5_0,&_44c6_s_p5_1},
  139097. {&_44c6_s_p6_0,&_44c6_s_p6_1},
  139098. {&_44c6_s_p7_0,&_44c6_s_p7_1},
  139099. {&_44c6_s_p8_0,&_44c6_s_p8_1},
  139100. {&_44c6_s_p9_0,&_44c6_s_p9_1,&_44c6_s_p9_2}
  139101. }
  139102. };
  139103. static static_bookblock _resbook_44s_7={
  139104. {
  139105. {0},{0,0,&_44c7_s_p1_0},{0,0,&_44c7_s_p2_0},{0,0,&_44c7_s_p3_0},
  139106. {0,0,&_44c7_s_p4_0},
  139107. {&_44c7_s_p5_0,&_44c7_s_p5_1},
  139108. {&_44c7_s_p6_0,&_44c7_s_p6_1},
  139109. {&_44c7_s_p7_0,&_44c7_s_p7_1},
  139110. {&_44c7_s_p8_0,&_44c7_s_p8_1},
  139111. {&_44c7_s_p9_0,&_44c7_s_p9_1,&_44c7_s_p9_2}
  139112. }
  139113. };
  139114. static static_bookblock _resbook_44s_8={
  139115. {
  139116. {0},{0,0,&_44c8_s_p1_0},{0,0,&_44c8_s_p2_0},{0,0,&_44c8_s_p3_0},
  139117. {0,0,&_44c8_s_p4_0},
  139118. {&_44c8_s_p5_0,&_44c8_s_p5_1},
  139119. {&_44c8_s_p6_0,&_44c8_s_p6_1},
  139120. {&_44c8_s_p7_0,&_44c8_s_p7_1},
  139121. {&_44c8_s_p8_0,&_44c8_s_p8_1},
  139122. {&_44c8_s_p9_0,&_44c8_s_p9_1,&_44c8_s_p9_2}
  139123. }
  139124. };
  139125. static static_bookblock _resbook_44s_9={
  139126. {
  139127. {0},{0,0,&_44c9_s_p1_0},{0,0,&_44c9_s_p2_0},{0,0,&_44c9_s_p3_0},
  139128. {0,0,&_44c9_s_p4_0},
  139129. {&_44c9_s_p5_0,&_44c9_s_p5_1},
  139130. {&_44c9_s_p6_0,&_44c9_s_p6_1},
  139131. {&_44c9_s_p7_0,&_44c9_s_p7_1},
  139132. {&_44c9_s_p8_0,&_44c9_s_p8_1},
  139133. {&_44c9_s_p9_0,&_44c9_s_p9_1,&_44c9_s_p9_2}
  139134. }
  139135. };
  139136. static vorbis_residue_template _res_44s_n1[]={
  139137. {2,0, &_residue_44_low,
  139138. &_huff_book__44cn1_s_short,&_huff_book__44cn1_sm_short,
  139139. &_resbook_44s_n1,&_resbook_44sm_n1},
  139140. {2,0, &_residue_44_low,
  139141. &_huff_book__44cn1_s_long,&_huff_book__44cn1_sm_long,
  139142. &_resbook_44s_n1,&_resbook_44sm_n1}
  139143. };
  139144. static vorbis_residue_template _res_44s_0[]={
  139145. {2,0, &_residue_44_low,
  139146. &_huff_book__44c0_s_short,&_huff_book__44c0_sm_short,
  139147. &_resbook_44s_0,&_resbook_44sm_0},
  139148. {2,0, &_residue_44_low,
  139149. &_huff_book__44c0_s_long,&_huff_book__44c0_sm_long,
  139150. &_resbook_44s_0,&_resbook_44sm_0}
  139151. };
  139152. static vorbis_residue_template _res_44s_1[]={
  139153. {2,0, &_residue_44_low,
  139154. &_huff_book__44c1_s_short,&_huff_book__44c1_sm_short,
  139155. &_resbook_44s_1,&_resbook_44sm_1},
  139156. {2,0, &_residue_44_low,
  139157. &_huff_book__44c1_s_long,&_huff_book__44c1_sm_long,
  139158. &_resbook_44s_1,&_resbook_44sm_1}
  139159. };
  139160. static vorbis_residue_template _res_44s_2[]={
  139161. {2,0, &_residue_44_mid,
  139162. &_huff_book__44c2_s_short,&_huff_book__44c2_s_short,
  139163. &_resbook_44s_2,&_resbook_44s_2},
  139164. {2,0, &_residue_44_mid,
  139165. &_huff_book__44c2_s_long,&_huff_book__44c2_s_long,
  139166. &_resbook_44s_2,&_resbook_44s_2}
  139167. };
  139168. static vorbis_residue_template _res_44s_3[]={
  139169. {2,0, &_residue_44_mid,
  139170. &_huff_book__44c3_s_short,&_huff_book__44c3_s_short,
  139171. &_resbook_44s_3,&_resbook_44s_3},
  139172. {2,0, &_residue_44_mid,
  139173. &_huff_book__44c3_s_long,&_huff_book__44c3_s_long,
  139174. &_resbook_44s_3,&_resbook_44s_3}
  139175. };
  139176. static vorbis_residue_template _res_44s_4[]={
  139177. {2,0, &_residue_44_mid,
  139178. &_huff_book__44c4_s_short,&_huff_book__44c4_s_short,
  139179. &_resbook_44s_4,&_resbook_44s_4},
  139180. {2,0, &_residue_44_mid,
  139181. &_huff_book__44c4_s_long,&_huff_book__44c4_s_long,
  139182. &_resbook_44s_4,&_resbook_44s_4}
  139183. };
  139184. static vorbis_residue_template _res_44s_5[]={
  139185. {2,0, &_residue_44_mid,
  139186. &_huff_book__44c5_s_short,&_huff_book__44c5_s_short,
  139187. &_resbook_44s_5,&_resbook_44s_5},
  139188. {2,0, &_residue_44_mid,
  139189. &_huff_book__44c5_s_long,&_huff_book__44c5_s_long,
  139190. &_resbook_44s_5,&_resbook_44s_5}
  139191. };
  139192. static vorbis_residue_template _res_44s_6[]={
  139193. {2,0, &_residue_44_high,
  139194. &_huff_book__44c6_s_short,&_huff_book__44c6_s_short,
  139195. &_resbook_44s_6,&_resbook_44s_6},
  139196. {2,0, &_residue_44_high,
  139197. &_huff_book__44c6_s_long,&_huff_book__44c6_s_long,
  139198. &_resbook_44s_6,&_resbook_44s_6}
  139199. };
  139200. static vorbis_residue_template _res_44s_7[]={
  139201. {2,0, &_residue_44_high,
  139202. &_huff_book__44c7_s_short,&_huff_book__44c7_s_short,
  139203. &_resbook_44s_7,&_resbook_44s_7},
  139204. {2,0, &_residue_44_high,
  139205. &_huff_book__44c7_s_long,&_huff_book__44c7_s_long,
  139206. &_resbook_44s_7,&_resbook_44s_7}
  139207. };
  139208. static vorbis_residue_template _res_44s_8[]={
  139209. {2,0, &_residue_44_high,
  139210. &_huff_book__44c8_s_short,&_huff_book__44c8_s_short,
  139211. &_resbook_44s_8,&_resbook_44s_8},
  139212. {2,0, &_residue_44_high,
  139213. &_huff_book__44c8_s_long,&_huff_book__44c8_s_long,
  139214. &_resbook_44s_8,&_resbook_44s_8}
  139215. };
  139216. static vorbis_residue_template _res_44s_9[]={
  139217. {2,0, &_residue_44_high,
  139218. &_huff_book__44c9_s_short,&_huff_book__44c9_s_short,
  139219. &_resbook_44s_9,&_resbook_44s_9},
  139220. {2,0, &_residue_44_high,
  139221. &_huff_book__44c9_s_long,&_huff_book__44c9_s_long,
  139222. &_resbook_44s_9,&_resbook_44s_9}
  139223. };
  139224. static vorbis_mapping_template _mapres_template_44_stereo[]={
  139225. { _map_nominal, _res_44s_n1 }, /* -1 */
  139226. { _map_nominal, _res_44s_0 }, /* 0 */
  139227. { _map_nominal, _res_44s_1 }, /* 1 */
  139228. { _map_nominal, _res_44s_2 }, /* 2 */
  139229. { _map_nominal, _res_44s_3 }, /* 3 */
  139230. { _map_nominal, _res_44s_4 }, /* 4 */
  139231. { _map_nominal, _res_44s_5 }, /* 5 */
  139232. { _map_nominal, _res_44s_6 }, /* 6 */
  139233. { _map_nominal, _res_44s_7 }, /* 7 */
  139234. { _map_nominal, _res_44s_8 }, /* 8 */
  139235. { _map_nominal, _res_44s_9 }, /* 9 */
  139236. };
  139237. /*** End of inlined file: residue_44.h ***/
  139238. /*** Start of inlined file: psych_44.h ***/
  139239. /* preecho trigger settings *****************************************/
  139240. static vorbis_info_psy_global _psy_global_44[5]={
  139241. {8, /* lines per eighth octave */
  139242. {20.f,14.f,12.f,12.f,12.f,12.f,12.f},
  139243. {-60.f,-30.f,-40.f,-40.f,-40.f,-40.f,-40.f}, 2,-75.f,
  139244. -6.f,
  139245. {99.},{{99.},{99.}},{0},{0},{{0.},{0.}}
  139246. },
  139247. {8, /* lines per eighth octave */
  139248. {14.f,10.f,10.f,10.f,10.f,10.f,10.f},
  139249. {-40.f,-30.f,-25.f,-25.f,-25.f,-25.f,-25.f}, 2,-80.f,
  139250. -6.f,
  139251. {99.},{{99.},{99.}},{0},{0},{{0.},{0.}}
  139252. },
  139253. {8, /* lines per eighth octave */
  139254. {12.f,10.f,10.f,10.f,10.f,10.f,10.f},
  139255. {-20.f,-20.f,-15.f,-15.f,-15.f,-15.f,-15.f}, 0,-80.f,
  139256. -6.f,
  139257. {99.},{{99.},{99.}},{0},{0},{{0.},{0.}}
  139258. },
  139259. {8, /* lines per eighth octave */
  139260. {10.f,8.f,8.f,8.f,8.f,8.f,8.f},
  139261. {-20.f,-15.f,-12.f,-12.f,-12.f,-12.f,-12.f}, 0,-80.f,
  139262. -6.f,
  139263. {99.},{{99.},{99.}},{0},{0},{{0.},{0.}}
  139264. },
  139265. {8, /* lines per eighth octave */
  139266. {10.f,6.f,6.f,6.f,6.f,6.f,6.f},
  139267. {-15.f,-15.f,-12.f,-12.f,-12.f,-12.f,-12.f}, 0,-85.f,
  139268. -6.f,
  139269. {99.},{{99.},{99.}},{0},{0},{{0.},{0.}}
  139270. },
  139271. };
  139272. /* noise compander lookups * low, mid, high quality ****************/
  139273. static compandblock _psy_compand_44[6]={
  139274. /* sub-mode Z short */
  139275. {{
  139276. 0, 1, 2, 3, 4, 5, 6, 7, /* 7dB */
  139277. 8, 9,10,11,12,13,14, 15, /* 15dB */
  139278. 16,17,18,19,20,21,22, 23, /* 23dB */
  139279. 24,25,26,27,28,29,30, 31, /* 31dB */
  139280. 32,33,34,35,36,37,38, 39, /* 39dB */
  139281. }},
  139282. /* mode_Z nominal short */
  139283. {{
  139284. 0, 1, 2, 3, 4, 5, 6, 6, /* 7dB */
  139285. 7, 7, 7, 7, 6, 6, 6, 7, /* 15dB */
  139286. 7, 8, 9,10,11,12,13, 14, /* 23dB */
  139287. 15,16,17,17,17,18,18, 19, /* 31dB */
  139288. 19,19,20,21,22,23,24, 25, /* 39dB */
  139289. }},
  139290. /* mode A short */
  139291. {{
  139292. 0, 1, 2, 3, 4, 5, 5, 5, /* 7dB */
  139293. 6, 6, 6, 5, 4, 4, 4, 4, /* 15dB */
  139294. 4, 4, 5, 5, 5, 6, 6, 6, /* 23dB */
  139295. 7, 7, 7, 8, 8, 8, 9, 10, /* 31dB */
  139296. 11,12,13,14,15,16,17, 18, /* 39dB */
  139297. }},
  139298. /* sub-mode Z long */
  139299. {{
  139300. 0, 1, 2, 3, 4, 5, 6, 7, /* 7dB */
  139301. 8, 9,10,11,12,13,14, 15, /* 15dB */
  139302. 16,17,18,19,20,21,22, 23, /* 23dB */
  139303. 24,25,26,27,28,29,30, 31, /* 31dB */
  139304. 32,33,34,35,36,37,38, 39, /* 39dB */
  139305. }},
  139306. /* mode_Z nominal long */
  139307. {{
  139308. 0, 1, 2, 3, 4, 5, 6, 7, /* 7dB */
  139309. 8, 9,10,11,12,12,13, 13, /* 15dB */
  139310. 13,14,14,14,15,15,15, 15, /* 23dB */
  139311. 16,16,17,17,17,18,18, 19, /* 31dB */
  139312. 19,19,20,21,22,23,24, 25, /* 39dB */
  139313. }},
  139314. /* mode A long */
  139315. {{
  139316. 0, 1, 2, 3, 4, 5, 6, 7, /* 7dB */
  139317. 8, 8, 7, 6, 5, 4, 4, 4, /* 15dB */
  139318. 4, 4, 5, 5, 5, 6, 6, 6, /* 23dB */
  139319. 7, 7, 7, 8, 8, 8, 9, 10, /* 31dB */
  139320. 11,12,13,14,15,16,17, 18, /* 39dB */
  139321. }}
  139322. };
  139323. /* tonal masking curve level adjustments *************************/
  139324. static vp_adjblock _vp_tonemask_adj_longblock[12]={
  139325. /* 63 125 250 500 1 2 4 8 16 */
  139326. {{ -3, -8,-13,-15,-10,-10,-10,-10,-10,-10,-10, 0, 0, 0, 0, 0, 0}}, /* -1 */
  139327. /* {{-15,-15,-15,-15,-10, -8, -4, -2, 0, 0, 0, 10, 0, 0, 0, 0, 0}}, 0 */
  139328. {{ -4,-10,-14,-16,-15,-14,-13,-12,-12,-12,-11, -1, -1, -1, -1, -1, 0}}, /* 0 */
  139329. /* {{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 5, 0, 0, 0, 0, 0}}, 1 */
  139330. {{ -6,-12,-14,-16,-15,-15,-14,-13,-13,-12,-12, -2, -2, -1, -1, -1, 0}}, /* 1 */
  139331. /* {{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, 2 */
  139332. {{-12,-13,-14,-16,-16,-16,-15,-14,-13,-12,-12, -6, -3, -1, -1, -1, 0}}, /* 2 */
  139333. /* {{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, 3 */
  139334. {{-15,-15,-15,-16,-16,-16,-16,-14,-13,-13,-13,-10, -4, -2, -1, -1, 0}}, /* 3 */
  139335. /* {{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, *//* 4 */
  139336. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-13,-11, -7 -3, -1, -1 , 0}}, /* 4 */
  139337. /* {{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, 5 */
  139338. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-13,-11, -7 -3, -1, -1 , 0}}, /* 5 */
  139339. /* {{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, 6 */
  139340. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-14,-12, -8, -4, -2, -2, 0}}, /* 6 */
  139341. /* {{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, 7 */
  139342. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-14,-12, -9, -4, -2, -2, 0}}, /* 7 */
  139343. /* {{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, 8 */
  139344. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-14,-12, -9, -4, -2, -2, 0}}, /* 8 */
  139345. /* {{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, 9 */
  139346. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-14,-12, -9, -4, -2, -2, 0}}, /* 9 */
  139347. /* {{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, 10 */
  139348. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-14,-12, -9, -4, -2, -2, 0}}, /* 10 */
  139349. };
  139350. static vp_adjblock _vp_tonemask_adj_otherblock[12]={
  139351. /* 63 125 250 500 1 2 4 8 16 */
  139352. {{ -3, -8,-13,-15,-10,-10, -9, -9, -9, -9, -9, 1, 1, 1, 1, 1, 1}}, /* -1 */
  139353. /* {{-20,-20,-20,-20,-14,-12,-10, -8, -4, 0, 0, 10, 0, 0, 0, 0, 0}}, 0 */
  139354. {{ -4,-10,-14,-16,-14,-13,-12,-12,-11,-11,-10, 0, 0, 0, 0, 0, 0}}, /* 0 */
  139355. /* {{-20,-20,-20,-20,-20,-18,-16,-14,-10, 0, 0, 5, 0, 0, 0, 0, 0}}, 1 */
  139356. {{ -6,-12,-14,-16,-15,-15,-14,-13,-13,-12,-12, -2, -2, -1, 0, 0, 0}}, /* 1 */
  139357. /* {{-20,-20,-20,-20,-20,-18,-16,-14,-10, 0, 0, 0, 0, 0, 0, 0, 0}}, 2 */
  139358. {{-12,-13,-14,-16,-16,-16,-15,-14,-13,-12,-12, -5, -2, -1, 0, 0, 0}}, /* 2 */
  139359. /* {{-20,-20,-20,-20,-20,-18,-16,-14,-10, 0, 0, 0, 0, 0, 0, 0, 0}}, 3 */
  139360. {{-15,-15,-15,-16,-16,-16,-16,-14,-13,-13,-13,-10, -4, -2, 0, 0, 0}}, /* 3 */
  139361. /* {{-20,-20,-20,-20,-20,-18,-16,-14,-10, 0, 0, 0, 0, 0, 0, 0, 0}}, 4 */
  139362. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-13,-11, -7 -3, -1, -1 , 0}}, /* 4 */
  139363. /* {{-20,-20,-20,-20,-20,-18,-16,-14,-10, 0, 0, 0, 0, 0, 0, 0, 0}}, 5 */
  139364. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-13,-11, -7 -3, -1, -1 , 0}}, /* 5 */
  139365. /* {{-20,-20,-20,-20,-20,-18,-16,-14,-10, 0, 0, 0, 0, 0, 0, 0, 0}}, 6 */
  139366. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-14,-12, -8, -4, -2, -2, 0}}, /* 6 */
  139367. /* {{-20,-20,-20,-20,-20,-18,-16,-14,-10, 0, 0, 0, 0, 0, 0, 0, 0}}, 7 */
  139368. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-14,-12, -9, -4, -2, -2, 0}}, /* 7 */
  139369. /* {{-20,-20,-20,-20,-20,-18,-16,-14,-10, 0, 0, 0, 0, 0, 0, 0, 0}}, 8 */
  139370. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-14,-12, -9, -4, -2, -2, 0}}, /* 8 */
  139371. /* {{-20,-20,-20,-20,-20,-18,-16,-14,-10, 0, 0, 0, 0, 0, 0, 0, 0}}, 9 */
  139372. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-14,-12, -9, -4, -2, -2, 0}}, /* 9 */
  139373. /* {{-20,-20,-20,-20,-20,-18,-16,-14,-10, 0, 0, 0, 0, 0, 0, 0, 0}}, 10 */
  139374. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-14,-12, -9, -4, -2, -2, 0}}, /* 10 */
  139375. };
  139376. /* noise bias (transition block) */
  139377. static noise3 _psy_noisebias_trans[12]={
  139378. /* 63 125 250 500 1k 2k 4k 8k 16k*/
  139379. /* -1 */
  139380. {{{-10,-10,-10,-10,-10, -4, 0, 0, 4, 8, 8, 8, 8, 10, 12, 14, 20},
  139381. {-30,-30,-30,-30,-26,-20,-16, -8, -6, -6, -2, 2, 2, 3, 6, 6, 15},
  139382. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, -6, -4, -2}}},
  139383. /* 0
  139384. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 4, 4, 5, 5, 5, 8, 10},
  139385. {-30,-30,-30,-30,-26,-22,-20,-14, -8, -4, 0, 0, 0, 0, 2, 4, 10},
  139386. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -6, -6, -6, -6, -4, -4, -4, -2}}},*/
  139387. {{{-15,-15,-15,-15,-15,-12, -6, -4, 0, 2, 4, 4, 5, 5, 5, 8, 10},
  139388. {-30,-30,-30,-30,-26,-22,-20,-14, -8, -4, 0, 0, 0, 0, 2, 3, 6},
  139389. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -6, -6, -6, -6, -4, -4, -4, -2}}},
  139390. /* 1
  139391. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 4, 4, 5, 5, 5, 8, 10},
  139392. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, -2, -2, -2, -2, 0, 2, 8},
  139393. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -8, -8, -8, -8, -6, -6, -6, -4}}},*/
  139394. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 4, 4, 5, 5, 5, 8, 10},
  139395. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, -2, -2, -2, -2, 0, 1, 4},
  139396. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -8, -8, -8, -8, -6, -6, -6, -4}}},
  139397. /* 2
  139398. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 2, 2, 4, 4, 5, 6, 10},
  139399. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, -2, -2, -2, -2, 0, 2, 6},
  139400. {-30,-30,-30,-30,-26,-22,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -4}}}, */
  139401. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 2, 2, 4, 4, 5, 6, 10},
  139402. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, -3, -3, -3, -2, -1, 0, 3},
  139403. {-30,-30,-30,-30,-26,-22,-20,-14,-10,-10,-10,-10,-10, -8, -8, -7, -4}}},
  139404. /* 3
  139405. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 2, 2, 4, 4, 4, 5, 8},
  139406. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, -3, -3, -3, -3, -1, 1, 6},
  139407. {-30,-30,-30,-30,-26,-22,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -4}}},*/
  139408. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 2, 2, 4, 4, 4, 5, 8},
  139409. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, -3, -3, -3, -3, -2, 0, 2},
  139410. {-30,-30,-30,-30,-26,-22,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -4}}},
  139411. /* 4
  139412. {{{-20,-20,-20,-20,-20,-18,-14, -8, -1, 1, 1, 1, 2, 3, 3, 4, 7},
  139413. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, -3, -3, -3, -3, -1, 1, 5},
  139414. {-30,-30,-30,-30,-26,-22,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -4}}},*/
  139415. {{{-20,-20,-20,-20,-20,-18,-14, -8, -1, 1, 1, 1, 2, 3, 3, 4, 7},
  139416. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, -3, -3, -3, -3, -2, -1, 1},
  139417. {-30,-30,-30,-30,-26,-22,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -4}}},
  139418. /* 5
  139419. {{{-24,-24,-24,-24,-20,-18,-14, -8, -1, 1, 1, 1, 2, 3, 3, 4, 7},
  139420. {-32,-32,-32,-32,-28,-24,-22,-16,-12, -6, -4, -4, -4, -4, -2, -1, 2},
  139421. {-34,-34,-34,-34,-30,-24,-24,-18,-14,-12,-12,-12,-12,-10,-10, -9, -5}}}, */
  139422. {{{-24,-24,-24,-24,-20,-18,-14, -8, -1, 1, 1, 1, 2, 3, 3, 4, 7},
  139423. {-32,-32,-32,-32,-28,-24,-22,-16,-12, -6, -4, -4, -4, -4, -3, -1, 0},
  139424. {-34,-34,-34,-34,-30,-24,-24,-18,-14,-12,-12,-12,-12,-10,-10, -9, -5}}},
  139425. /* 6
  139426. {{{-24,-24,-24,-24,-20,-18,-14, -8, -1, 1, 1, 1, 2, 3, 3, 4, 7},
  139427. {-32,-32,-32,-32,-28,-24,-24,-18,-14, -8, -6, -6, -6, -6, -4, -2, 1},
  139428. {-34,-34,-34,-34,-30,-26,-24,-18,-17,-15,-15,-15,-15,-13,-13,-12, -8}}},*/
  139429. {{{-24,-24,-24,-24,-20,-18,-14, -8, -1, 1, 1, 1, 2, 3, 3, 4, 7},
  139430. {-32,-32,-32,-32,-28,-24,-24,-18,-14, -8, -6, -6, -6, -6, -5, -2, 0},
  139431. {-34,-34,-34,-34,-30,-26,-26,-24,-22,-19,-19,-19,-19,-18,-17,-16,-12}}},
  139432. /* 7
  139433. {{{-24,-24,-24,-24,-20,-18,-14, -8, -1, 1, 1, 1, 2, 3, 3, 4, 7},
  139434. {-32,-32,-32,-32,-28,-24,-24,-18,-14,-12,-10, -8, -8, -8, -6, -4, 0},
  139435. {-34,-34,-34,-34,-30,-26,-26,-24,-22,-19,-19,-19,-19,-18,-17,-16,-12}}},*/
  139436. {{{-24,-24,-24,-24,-20,-18,-14, -8, -1, 1, 1, 1, 2, 3, 3, 4, 7},
  139437. {-32,-32,-32,-32,-28,-24,-24,-24,-18,-14,-12,-10,-10,-10, -8, -6, -2},
  139438. {-34,-34,-34,-34,-30,-26,-26,-26,-24,-24,-24,-24,-24,-24,-24,-20,-16}}},
  139439. /* 8
  139440. {{{-24,-24,-24,-24,-22,-20,-15,-10, -8, -2, 0, 0, 0, 1, 2, 3, 7},
  139441. {-36,-36,-36,-36,-30,-30,-30,-24,-18,-14,-12,-10,-10,-10, -8, -6, -2},
  139442. {-36,-36,-36,-36,-34,-30,-28,-26,-24,-24,-24,-24,-24,-24,-24,-20,-16}}},*/
  139443. {{{-24,-24,-24,-24,-22,-20,-15,-10, -8, -2, 0, 0, 0, 1, 2, 3, 7},
  139444. {-36,-36,-36,-36,-30,-30,-30,-24,-20,-16,-16,-16,-16,-14,-12,-10, -7},
  139445. {-36,-36,-36,-36,-34,-30,-28,-26,-24,-30,-30,-30,-30,-30,-30,-24,-20}}},
  139446. /* 9
  139447. {{{-28,-28,-28,-28,-28,-28,-28,-20,-14, -8, -4, -4, -4, -4, -4, -2, 2},
  139448. {-36,-36,-36,-36,-34,-32,-32,-28,-20,-16,-16,-16,-16,-14,-12,-10, -7},
  139449. {-40,-40,-40,-40,-40,-40,-40,-32,-30,-30,-30,-30,-30,-30,-30,-24,-20}}},*/
  139450. {{{-28,-28,-28,-28,-28,-28,-28,-20,-14, -8, -4, -4, -4, -4, -4, -2, 2},
  139451. {-38,-38,-38,-38,-36,-34,-34,-30,-24,-20,-20,-20,-20,-18,-16,-12,-10},
  139452. {-40,-40,-40,-40,-40,-40,-40,-38,-35,-35,-35,-35,-35,-35,-35,-35,-30}}},
  139453. /* 10 */
  139454. {{{-30,-30,-30,-30,-30,-30,-30,-28,-20,-14,-14,-14,-14,-14,-14,-12,-10},
  139455. {-40,-40,-40,-40,-40,-40,-40,-40,-35,-30,-30,-30,-30,-30,-30,-30,-20},
  139456. {-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40}}},
  139457. };
  139458. /* noise bias (long block) */
  139459. static noise3 _psy_noisebias_long[12]={
  139460. /*63 125 250 500 1k 2k 4k 8k 16k*/
  139461. /* -1 */
  139462. {{{-10,-10,-10,-10,-10, -4, 0, 0, 0, 6, 6, 6, 6, 10, 10, 12, 20},
  139463. {-20,-20,-20,-20,-20,-20,-10, -2, 0, 0, 0, 0, 0, 2, 4, 6, 15},
  139464. {-20,-20,-20,-20,-20,-20,-20,-10, -6, -6, -6, -6, -6, -4, -4, -4, -2}}},
  139465. /* 0 */
  139466. /* {{{-10,-10,-10,-10,-10,-10, -8, 2, 2, 2, 4, 4, 5, 5, 5, 8, 10},
  139467. {-20,-20,-20,-20,-20,-20,-20,-14, -6, 0, 0, 0, 0, 0, 2, 4, 10},
  139468. {-20,-20,-20,-20,-20,-20,-20,-14, -8, -6, -6, -6, -6, -4, -4, -4, -2}}},*/
  139469. {{{-10,-10,-10,-10,-10,-10, -8, 2, 2, 2, 4, 4, 5, 5, 5, 8, 10},
  139470. {-20,-20,-20,-20,-20,-20,-20,-14, -6, 0, 0, 0, 0, 0, 2, 3, 6},
  139471. {-20,-20,-20,-20,-20,-20,-20,-14, -8, -6, -6, -6, -6, -4, -4, -4, -2}}},
  139472. /* 1 */
  139473. /* {{{-10,-10,-10,-10,-10,-10, -8, -4, 0, 2, 4, 4, 5, 5, 5, 8, 10},
  139474. {-20,-20,-20,-20,-20,-20,-20,-14,-10, -4, -2, -2, -2, -2, 0, 2, 8},
  139475. {-20,-20,-20,-20,-20,-20,-20,-14,-10, -8, -8, -8, -8, -6, -6, -6, -4}}},*/
  139476. {{{-10,-10,-10,-10,-10,-10, -8, -4, 0, 2, 4, 4, 5, 5, 5, 8, 10},
  139477. {-20,-20,-20,-20,-20,-20,-20,-14,-10, -4, -2, -2, -2, -2, 0, 1, 4},
  139478. {-20,-20,-20,-20,-20,-20,-20,-14,-10, -8, -8, -8, -8, -6, -6, -6, -4}}},
  139479. /* 2 */
  139480. /* {{{-10,-10,-10,-10,-10,-10,-10, -8, 0, 2, 2, 2, 4, 4, 5, 6, 10},
  139481. {-20,-20,-20,-20,-20,-20,-20,-14,-10, -4, -2, -2, -2, -2, 0, 2, 6},
  139482. {-20,-20,-20,-20,-20,-20,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -4}}},*/
  139483. {{{-10,-10,-10,-10,-10,-10,-10, -8, 0, 2, 2, 2, 4, 4, 5, 6, 10},
  139484. {-20,-20,-20,-20,-20,-20,-20,-14,-10, -4, -3, -3, -3, -2, -1, 0, 3},
  139485. {-20,-20,-20,-20,-20,-20,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -4}}},
  139486. /* 3 */
  139487. /* {{{-10,-10,-10,-10,-10,-10,-10, -8, 0, 2, 2, 2, 4, 4, 4, 5, 8},
  139488. {-20,-20,-20,-20,-20,-20,-20,-14,-10, -4, -3, -3, -3, -3, -1, 1, 6},
  139489. {-20,-20,-20,-20,-20,-20,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -4}}},*/
  139490. {{{-10,-10,-10,-10,-10,-10,-10, -8, 0, 2, 2, 2, 4, 4, 4, 5, 8},
  139491. {-20,-20,-20,-20,-20,-20,-20,-14,-10, -4, -3, -3, -3, -3, -2, 0, 2},
  139492. {-20,-20,-20,-20,-20,-20,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -5}}},
  139493. /* 4 */
  139494. /* {{{-15,-15,-15,-15,-15,-15,-15,-10, -4, 1, 1, 1, 2, 3, 3, 4, 7},
  139495. {-20,-20,-20,-20,-20,-20,-20,-14,-10, -4, -3, -3, -3, -3, -1, 1, 5},
  139496. {-20,-20,-20,-20,-20,-20,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -4}}},*/
  139497. {{{-15,-15,-15,-15,-15,-15,-15,-10, -4, 1, 1, 1, 2, 3, 3, 4, 7},
  139498. {-20,-20,-20,-20,-20,-20,-20,-14,-10, -4, -3, -3, -3, -3, -2, -1, 1},
  139499. {-20,-20,-20,-20,-20,-20,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -7}}},
  139500. /* 5 */
  139501. /* {{{-15,-15,-15,-15,-15,-15,-15,-10, -4, 1, 1, 1, 2, 3, 3, 4, 7},
  139502. {-22,-22,-22,-22,-22,-22,-22,-16,-12, -6, -4, -4, -4, -4, -2, -1, 2},
  139503. {-24,-24,-24,-24,-24,-24,-24,-18,-14,-12,-12,-12,-12,-10,-10, -9, -5}}},*/
  139504. {{{-15,-15,-15,-15,-15,-15,-15,-10, -4, 1, 1, 1, 2, 3, 3, 4, 7},
  139505. {-22,-22,-22,-22,-22,-22,-22,-16,-12, -6, -4, -4, -4, -4, -3, -1, 0},
  139506. {-24,-24,-24,-24,-24,-24,-24,-18,-14,-12,-12,-12,-12,-10,-10, -9, -8}}},
  139507. /* 6 */
  139508. /* {{{-15,-15,-15,-15,-15,-15,-15,-10, -4, 1, 1, 1, 2, 3, 3, 4, 7},
  139509. {-24,-24,-24,-24,-24,-24,-24,-18,-14, -8, -6, -6, -6, -6, -4, -2, 1},
  139510. {-26,-26,-26,-26,-26,-26,-26,-18,-16,-15,-15,-15,-15,-13,-13,-12, -8}}},*/
  139511. {{{-15,-15,-15,-15,-15,-15,-15,-10, -4, 1, 1, 1, 2, 3, 3, 4, 7},
  139512. {-24,-24,-24,-24,-24,-24,-24,-18,-14, -8, -6, -6, -6, -6, -5, -2, 0},
  139513. {-26,-26,-26,-26,-26,-26,-26,-18,-16,-15,-15,-15,-15,-13,-13,-12,-10}}},
  139514. /* 7 */
  139515. {{{-15,-15,-15,-15,-15,-15,-15,-10, -4, 1, 1, 1, 2, 3, 3, 4, 7},
  139516. {-24,-24,-24,-24,-24,-24,-24,-18,-14,-10, -8, -8, -8, -8, -6, -4, 0},
  139517. {-26,-26,-26,-26,-26,-26,-26,-22,-20,-19,-19,-19,-19,-18,-17,-16,-12}}},
  139518. /* 8 */
  139519. {{{-15,-15,-15,-15,-15,-15,-15,-10, -4, 0, 0, 0, 0, 1, 2, 3, 7},
  139520. {-26,-26,-26,-26,-26,-26,-26,-20,-16,-12,-10,-10,-10,-10, -8, -6, -2},
  139521. {-28,-28,-28,-28,-28,-28,-28,-26,-24,-24,-24,-24,-24,-24,-24,-20,-16}}},
  139522. /* 9 */
  139523. {{{-22,-22,-22,-22,-22,-22,-22,-18,-14, -8, -4, -4, -4, -4, -4, -2, 2},
  139524. {-26,-26,-26,-26,-26,-26,-26,-22,-18,-16,-16,-16,-16,-14,-12,-10, -7},
  139525. {-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-24,-20}}},
  139526. /* 10 */
  139527. {{{-24,-24,-24,-24,-24,-24,-24,-24,-24,-18,-14,-14,-14,-14,-14,-12,-10},
  139528. {-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-20},
  139529. {-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40}}},
  139530. };
  139531. /* noise bias (impulse block) */
  139532. static noise3 _psy_noisebias_impulse[12]={
  139533. /* 63 125 250 500 1k 2k 4k 8k 16k*/
  139534. /* -1 */
  139535. {{{-10,-10,-10,-10,-10, -4, 0, 0, 4, 8, 8, 8, 8, 10, 12, 14, 20},
  139536. {-30,-30,-30,-30,-26,-20,-16, -8, -6, -6, -2, 2, 2, 3, 6, 6, 15},
  139537. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, -6, -4, -2}}},
  139538. /* 0 */
  139539. /* {{{-10,-10,-10,-10,-10, -4, 0, 0, 4, 4, 8, 8, 8, 10, 12, 14, 20},
  139540. {-30,-30,-30,-30,-26,-22,-20,-14, -6, -2, 0, 0, 0, 0, 2, 4, 10},
  139541. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, -6, -4, -2}}},*/
  139542. {{{-10,-10,-10,-10,-10, -4, 0, 0, 4, 4, 8, 8, 8, 10, 12, 14, 20},
  139543. {-30,-30,-30,-30,-26,-22,-20,-14, -6, -2, 0, 0, 0, 0, 2, 3, 6},
  139544. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, -6, -4, -2}}},
  139545. /* 1 */
  139546. {{{-12,-12,-12,-12,-12, -8, -6, -4, 0, 4, 4, 4, 4, 10, 12, 14, 20},
  139547. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -6, -4, -4, -2, -2, -2, -2, 2},
  139548. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -8,-10,-10, -8, -8, -8, -6, -4}}},
  139549. /* 2 */
  139550. {{{-14,-14,-14,-14,-14,-10, -8, -6, -2, 2, 2, 2, 2, 8, 10, 10, 16},
  139551. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -6, -6, -6, -4, -4, -4, -2, 0},
  139552. {-30,-30,-30,-30,-26,-22,-20,-14,-10,-10,-10,-10,-10,-10,-10, -8, -4}}},
  139553. /* 3 */
  139554. {{{-14,-14,-14,-14,-14,-10, -8, -6, -2, 2, 2, 2, 2, 6, 8, 8, 14},
  139555. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -6, -6, -6, -4, -4, -4, -2, 0},
  139556. {-30,-30,-30,-30,-26,-22,-20,-14,-10,-10,-10,-10,-10,-10,-10, -8, -4}}},
  139557. /* 4 */
  139558. {{{-16,-16,-16,-16,-16,-12,-10, -6, -2, 0, 0, 0, 0, 4, 6, 6, 12},
  139559. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -6, -6, -6, -4, -4, -4, -2, 0},
  139560. {-30,-30,-30,-30,-26,-22,-20,-14,-10,-10,-10,-10,-10,-10,-10, -8, -4}}},
  139561. /* 5 */
  139562. {{{-20,-20,-20,-20,-20,-18,-14,-10, -4, 0, 0, 0, 0, 4, 4, 6, 11},
  139563. {-32,-32,-32,-32,-28,-24,-22,-16,-10, -6, -8, -8, -6, -6, -6, -4, -2},
  139564. {-34,-34,-34,-34,-30,-26,-24,-18,-14,-12,-12,-12,-12,-12,-10, -9, -5}}},
  139565. /* 6
  139566. {{{-20,-20,-20,-20,-20,-18,-14,-10, -4, 0, 0, 0, 0, 4, 4, 6, 11},
  139567. {-34,-34,-34,-34,-30,-30,-24,-20,-12,-12,-14,-14,-10, -9, -8, -6, -4},
  139568. {-34,-34,-34,-34,-34,-30,-26,-20,-16,-15,-15,-15,-15,-15,-13,-12, -8}}},*/
  139569. {{{-20,-20,-20,-20,-20,-18,-14,-10, -4, 0, 0, 0, 0, 4, 4, 6, 11},
  139570. {-34,-34,-34,-34,-30,-30,-30,-24,-16,-16,-16,-16,-16,-16,-14,-14,-12},
  139571. {-36,-36,-36,-36,-36,-34,-28,-24,-20,-20,-20,-20,-20,-20,-20,-18,-16}}},
  139572. /* 7 */
  139573. /* {{{-22,-22,-22,-22,-22,-20,-14,-10, -6, 0, 0, 0, 0, 4, 4, 6, 11},
  139574. {-34,-34,-34,-34,-30,-30,-24,-20,-14,-14,-16,-16,-14,-12,-10,-10,-10},
  139575. {-34,-34,-34,-34,-32,-32,-30,-24,-20,-19,-19,-19,-19,-19,-17,-16,-12}}},*/
  139576. {{{-22,-22,-22,-22,-22,-20,-14,-10, -6, 0, 0, 0, 0, 4, 4, 6, 11},
  139577. {-34,-34,-34,-34,-30,-30,-30,-30,-26,-26,-26,-26,-26,-26,-26,-24,-22},
  139578. {-40,-40,-40,-40,-40,-40,-40,-32,-30,-30,-30,-30,-30,-30,-30,-30,-24}}},
  139579. /* 8 */
  139580. /* {{{-24,-24,-24,-24,-24,-22,-14,-10, -6, -1, -1, -1, -1, 3, 3, 5, 10},
  139581. {-34,-34,-34,-34,-30,-30,-30,-24,-20,-20,-20,-20,-20,-18,-16,-16,-14},
  139582. {-36,-36,-36,-36,-36,-34,-28,-24,-24,-24,-24,-24,-24,-24,-24,-20,-16}}},*/
  139583. {{{-24,-24,-24,-24,-24,-22,-14,-10, -6, -1, -1, -1, -1, 3, 3, 5, 10},
  139584. {-34,-34,-34,-34,-34,-32,-32,-30,-26,-26,-26,-26,-26,-26,-26,-26,-24},
  139585. {-40,-40,-40,-40,-40,-40,-40,-32,-30,-30,-30,-30,-30,-30,-30,-30,-24}}},
  139586. /* 9 */
  139587. /* {{{-28,-28,-28,-28,-28,-28,-28,-20,-14, -8, -4, -4, -4, -4, -4, -2, 2},
  139588. {-36,-36,-36,-36,-34,-32,-32,-30,-26,-26,-26,-26,-26,-22,-20,-20,-18},
  139589. {-40,-40,-40,-40,-40,-40,-40,-32,-30,-30,-30,-30,-30,-30,-30,-24,-20}}},*/
  139590. {{{-28,-28,-28,-28,-28,-28,-28,-20,-14, -8, -4, -4, -4, -4, -4, -2, 2},
  139591. {-36,-36,-36,-36,-34,-32,-32,-30,-26,-26,-26,-26,-26,-26,-26,-26,-26},
  139592. {-40,-40,-40,-40,-40,-40,-40,-32,-30,-30,-30,-30,-30,-30,-30,-24,-20}}},
  139593. /* 10 */
  139594. {{{-30,-30,-30,-30,-30,-26,-24,-24,-24,-20,-16,-16,-16,-16,-16,-14,-12},
  139595. {-40,-40,-40,-40,-40,-40,-40,-40,-35,-30,-30,-30,-30,-30,-30,-30,-26},
  139596. {-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40}}},
  139597. };
  139598. /* noise bias (padding block) */
  139599. static noise3 _psy_noisebias_padding[12]={
  139600. /* 63 125 250 500 1k 2k 4k 8k 16k*/
  139601. /* -1 */
  139602. {{{-10,-10,-10,-10,-10, -4, 0, 0, 4, 8, 8, 8, 8, 10, 12, 14, 20},
  139603. {-30,-30,-30,-30,-26,-20,-16, -8, -6, -6, -2, 2, 2, 3, 6, 6, 15},
  139604. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, -6, -4, -2}}},
  139605. /* 0 */
  139606. {{{-10,-10,-10,-10,-10, -4, 0, 0, 4, 8, 8, 8, 8, 10, 12, 14, 20},
  139607. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, -2, 2, 3, 6, 6, 8, 10},
  139608. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, -4, -4, -4, -4, -2, 0, 2}}},
  139609. /* 1 */
  139610. {{{-12,-12,-12,-12,-12, -8, -6, -4, 0, 4, 4, 4, 4, 10, 12, 14, 20},
  139611. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, 0, 0, 0, 2, 2, 4, 8},
  139612. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -6, -6, -6, -6, -6, -4, -2, 0}}},
  139613. /* 2 */
  139614. /* {{{-14,-14,-14,-14,-14,-10, -8, -6, -2, 2, 2, 2, 2, 8, 10, 10, 16},
  139615. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, 0, 0, 0, 2, 2, 4, 8},
  139616. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -8, -8, -8, -8, -8, -6, -4, -2}}},*/
  139617. {{{-14,-14,-14,-14,-14,-10, -8, -6, -2, 2, 2, 2, 2, 8, 10, 10, 16},
  139618. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -6, -1, -1, -1, 0, 0, 2, 6},
  139619. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -8, -8, -8, -8, -8, -6, -4, -2}}},
  139620. /* 3 */
  139621. {{{-14,-14,-14,-14,-14,-10, -8, -6, -2, 2, 2, 2, 2, 6, 8, 8, 14},
  139622. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -6, -1, -1, -1, 0, 0, 2, 6},
  139623. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -8, -8, -8, -8, -8, -6, -4, -2}}},
  139624. /* 4 */
  139625. {{{-16,-16,-16,-16,-16,-12,-10, -6, -2, 0, 0, 0, 0, 4, 6, 6, 12},
  139626. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -6, -1, -1, -1, -1, 0, 2, 6},
  139627. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -8, -8, -8, -8, -8, -6, -4, -2}}},
  139628. /* 5 */
  139629. {{{-20,-20,-20,-20,-20,-18,-14,-10, -4, 0, 0, 0, 0, 4, 6, 6, 12},
  139630. {-32,-32,-32,-32,-28,-24,-22,-16,-12, -6, -3, -3, -3, -3, -2, 0, 4},
  139631. {-34,-34,-34,-34,-30,-26,-24,-18,-14,-10,-10,-10,-10,-10, -8, -5, -3}}},
  139632. /* 6 */
  139633. {{{-20,-20,-20,-20,-20,-18,-14,-10, -4, 0, 0, 0, 0, 4, 6, 6, 12},
  139634. {-34,-34,-34,-34,-30,-30,-24,-20,-14, -8, -4, -4, -4, -4, -3, -1, 4},
  139635. {-34,-34,-34,-34,-34,-30,-26,-20,-16,-13,-13,-13,-13,-13,-11, -8, -6}}},
  139636. /* 7 */
  139637. {{{-20,-20,-20,-20,-20,-18,-14,-10, -4, 0, 0, 0, 0, 4, 6, 6, 12},
  139638. {-34,-34,-34,-34,-30,-30,-30,-24,-16,-10, -8, -6, -6, -6, -5, -3, 1},
  139639. {-34,-34,-34,-34,-32,-32,-28,-22,-18,-16,-16,-16,-16,-16,-14,-12,-10}}},
  139640. /* 8 */
  139641. {{{-22,-22,-22,-22,-22,-20,-14,-10, -4, 0, 0, 0, 0, 3, 5, 5, 11},
  139642. {-34,-34,-34,-34,-30,-30,-30,-24,-16,-12,-10, -8, -8, -8, -7, -5, -2},
  139643. {-36,-36,-36,-36,-36,-34,-28,-22,-20,-20,-20,-20,-20,-20,-20,-16,-14}}},
  139644. /* 9 */
  139645. {{{-28,-28,-28,-28,-28,-28,-28,-20,-14, -8, -2, -2, -2, -2, 0, 2, 6},
  139646. {-36,-36,-36,-36,-34,-32,-32,-24,-16,-12,-12,-12,-12,-12,-10, -8, -5},
  139647. {-40,-40,-40,-40,-40,-40,-40,-32,-26,-24,-24,-24,-24,-24,-24,-20,-18}}},
  139648. /* 10 */
  139649. {{{-30,-30,-30,-30,-30,-26,-24,-24,-24,-20,-12,-12,-12,-12,-12,-10, -8},
  139650. {-40,-40,-40,-40,-40,-40,-40,-40,-35,-30,-25,-25,-25,-25,-25,-25,-15},
  139651. {-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40}}},
  139652. };
  139653. static noiseguard _psy_noiseguards_44[4]={
  139654. {3,3,15},
  139655. {3,3,15},
  139656. {10,10,100},
  139657. {10,10,100},
  139658. };
  139659. static int _psy_tone_suppress[12]={
  139660. -20,-20,-20,-20,-20,-24,-30,-40,-40,-45,-45,-45,
  139661. };
  139662. static int _psy_tone_0dB[12]={
  139663. 90,90,95,95,95,95,105,105,105,105,105,105,
  139664. };
  139665. static int _psy_noise_suppress[12]={
  139666. -20,-20,-24,-24,-24,-24,-30,-40,-40,-45,-45,-45,
  139667. };
  139668. static vorbis_info_psy _psy_info_template={
  139669. /* blockflag */
  139670. -1,
  139671. /* ath_adjatt, ath_maxatt */
  139672. -140.,-140.,
  139673. /* tonemask att boost/decay,suppr,curves */
  139674. {0.f,0.f,0.f}, 0.,0., -40.f, {0.},
  139675. /*noisemaskp,supp, low/high window, low/hi guard, minimum */
  139676. 1, -0.f, .5f, .5f, 0,0,0,
  139677. /* noiseoffset*3, noisecompand, max_curve_dB */
  139678. {{-1},{-1},{-1}},{-1},105.f,
  139679. /* noise normalization - channel_p, point_p, start, partition, thresh. */
  139680. 0,0,-1,-1,0.,
  139681. };
  139682. /* ath ****************/
  139683. static int _psy_ath_floater[12]={
  139684. -100,-100,-100,-100,-100,-100,-105,-105,-105,-105,-110,-120,
  139685. };
  139686. static int _psy_ath_abs[12]={
  139687. -130,-130,-130,-130,-140,-140,-140,-140,-140,-140,-140,-150,
  139688. };
  139689. /* stereo setup. These don't map directly to quality level, there's
  139690. an additional indirection as several of the below may be used in a
  139691. single bitmanaged stream
  139692. ****************/
  139693. /* various stereo possibilities */
  139694. /* stereo mode by base quality level */
  139695. static adj_stereo _psy_stereo_modes_44[12]={
  139696. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 -1 */
  139697. {{ 4, 4, 4, 4, 4, 4, 4, 3, 2, 2, 1, 0, 0, 0, 0},
  139698. { 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 5, 4, 3},
  139699. { 1, 2, 3, 4, 4, 4, 4, 4, 4, 5, 6, 7, 8, 8, 8},
  139700. { 12,12.5, 13,13.5, 14,14.5, 15, 99, 99, 99, 99, 99, 99, 99, 99}},
  139701. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 0 */
  139702. /*{{ 4, 4, 4, 4, 4, 4, 4, 3, 2, 2, 1, 0, 0, 0, 0},
  139703. { 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 5, 4, 3},
  139704. { 1, 2, 3, 4, 5, 5, 6, 6, 6, 6, 6, 7, 8, 8, 8},
  139705. { 12,12.5, 13,13.5, 14,14.5, 15, 99, 99, 99, 99, 99, 99, 99, 99}},*/
  139706. {{ 4, 4, 4, 4, 4, 4, 4, 3, 2, 1, 0, 0, 0, 0, 0},
  139707. { 8, 8, 8, 8, 6, 6, 5, 5, 5, 5, 5, 5, 5, 4, 3},
  139708. { 1, 2, 3, 4, 4, 5, 6, 6, 6, 6, 6, 8, 8, 8, 8},
  139709. { 12,12.5, 13,13.5, 14,14.5, 15, 99, 99, 99, 99, 99, 99, 99, 99}},
  139710. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 1 */
  139711. {{ 3, 3, 3, 3, 3, 3, 3, 3, 2, 1, 0, 0, 0, 0, 0},
  139712. { 8, 8, 8, 8, 6, 6, 5, 5, 5, 5, 5, 5, 5, 4, 3},
  139713. { 1, 2, 3, 4, 4, 5, 6, 6, 6, 6, 6, 8, 8, 8, 8},
  139714. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  139715. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 2 */
  139716. /* {{ 3, 3, 3, 3, 3, 3, 2, 2, 2, 1, 0, 0, 0, 0, 0},
  139717. { 8, 8, 8, 6, 5, 5, 5, 5, 5, 5, 5, 4, 3, 2, 1},
  139718. { 3, 4, 4, 4, 5, 6, 6, 6, 6, 6, 6, 8, 8, 8, 8},
  139719. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}}, */
  139720. {{ 3, 3, 3, 3, 3, 3, 3, 2, 1, 1, 0, 0, 0, 0, 0},
  139721. { 8, 8, 6, 6, 5, 5, 4, 4, 4, 4, 4, 4, 3, 2, 1},
  139722. { 3, 4, 4, 5, 5, 6, 6, 6, 6, 6, 6, 8, 8, 8, 8},
  139723. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  139724. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 3 */
  139725. {{ 2, 2, 2, 2, 2, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0},
  139726. { 5, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 3, 2, 1},
  139727. { 4, 4, 5, 6, 6, 6, 6, 6, 8, 8, 10, 10, 10, 10, 10},
  139728. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  139729. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 4 */
  139730. {{ 2, 2, 2, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  139731. { 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 3, 3, 2, 1, 0},
  139732. { 6, 6, 6, 8, 8, 8, 8, 8, 8, 8, 10, 10, 10, 10, 10},
  139733. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  139734. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 5 */
  139735. /* {{ 2, 2, 2, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  139736. { 3, 3, 3, 3, 3, 2, 2, 2, 2, 2, 2, 0, 0, 0, 0},
  139737. { 6, 6, 8, 8, 8, 8, 10, 10, 10, 10, 10, 10, 10, 10, 10},
  139738. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},*/
  139739. {{ 2, 2, 2, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  139740. { 3, 3, 3, 3, 3, 2, 2, 2, 2, 2, 2, 0, 0, 0, 0},
  139741. { 6, 7, 8, 8, 8, 10, 10, 12, 12, 12, 12, 12, 12, 12, 12},
  139742. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  139743. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 6 */
  139744. /* {{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  139745. { 3, 3, 3, 2, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  139746. { 8, 8, 8, 8, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10},
  139747. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}}, */
  139748. {{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  139749. { 3, 3, 3, 2, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  139750. { 8, 8, 8, 10, 10, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12},
  139751. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  139752. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 7 */
  139753. /* {{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  139754. { 3, 3, 3, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  139755. { 8, 8, 8, 8, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10},
  139756. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},*/
  139757. {{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  139758. { 3, 3, 3, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  139759. { 8, 8, 10, 10, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12},
  139760. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  139761. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 8 */
  139762. /* {{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  139763. { 2, 2, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  139764. { 8, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10},
  139765. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},*/
  139766. {{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  139767. { 2, 2, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  139768. { 8, 10, 10, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12},
  139769. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  139770. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 9 */
  139771. {{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  139772. { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  139773. { 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4},
  139774. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  139775. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 10 */
  139776. {{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  139777. { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  139778. { 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4},
  139779. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  139780. };
  139781. /* tone master attenuation by base quality mode and bitrate tweak */
  139782. static att3 _psy_tone_masteratt_44[12]={
  139783. {{ 35, 21, 9}, 0, 0}, /* -1 */
  139784. {{ 30, 20, 8}, -2, 1.25}, /* 0 */
  139785. /* {{ 25, 14, 4}, 0, 0}, *//* 1 */
  139786. {{ 25, 12, 2}, 0, 0}, /* 1 */
  139787. /* {{ 20, 10, -2}, 0, 0}, *//* 2 */
  139788. {{ 20, 9, -3}, 0, 0}, /* 2 */
  139789. {{ 20, 9, -4}, 0, 0}, /* 3 */
  139790. {{ 20, 9, -4}, 0, 0}, /* 4 */
  139791. {{ 20, 6, -6}, 0, 0}, /* 5 */
  139792. {{ 20, 3, -10}, 0, 0}, /* 6 */
  139793. {{ 18, 1, -14}, 0, 0}, /* 7 */
  139794. {{ 18, 0, -16}, 0, 0}, /* 8 */
  139795. {{ 18, -2, -16}, 0, 0}, /* 9 */
  139796. {{ 12, -2, -20}, 0, 0}, /* 10 */
  139797. };
  139798. /* lowpass by mode **************/
  139799. static double _psy_lowpass_44[12]={
  139800. /* 15.1,15.8,16.5,17.9,20.5,48.,999.,999.,999.,999.,999. */
  139801. 13.9,15.1,15.8,16.5,17.2,18.9,20.1,48.,999.,999.,999.,999.
  139802. };
  139803. /* noise normalization **********/
  139804. static int _noise_start_short_44[11]={
  139805. /* 16,16,16,16,32,32,9999,9999,9999,9999 */
  139806. 32,16,16,16,32,9999,9999,9999,9999,9999,9999
  139807. };
  139808. static int _noise_start_long_44[11]={
  139809. /* 128,128,128,256,512,512,9999,9999,9999,9999 */
  139810. 256,128,128,256,512,9999,9999,9999,9999,9999,9999
  139811. };
  139812. static int _noise_part_short_44[11]={
  139813. 8,8,8,8,8,8,8,8,8,8,8
  139814. };
  139815. static int _noise_part_long_44[11]={
  139816. 32,32,32,32,32,32,32,32,32,32,32
  139817. };
  139818. static double _noise_thresh_44[11]={
  139819. /* .2,.2,.3,.4,.5,.5,9999.,9999.,9999.,9999., */
  139820. .2,.2,.2,.4,.6,9999.,9999.,9999.,9999.,9999.,9999.,
  139821. };
  139822. static double _noise_thresh_5only[2]={
  139823. .5,.5,
  139824. };
  139825. /*** End of inlined file: psych_44.h ***/
  139826. static double rate_mapping_44_stereo[12]={
  139827. 22500.,32000.,40000.,48000.,56000.,64000.,
  139828. 80000.,96000.,112000.,128000.,160000.,250001.
  139829. };
  139830. static double quality_mapping_44[12]={
  139831. -.1,.0,.1,.2,.3,.4,.5,.6,.7,.8,.9,1.0
  139832. };
  139833. static int blocksize_short_44[11]={
  139834. 512,256,256,256,256,256,256,256,256,256,256
  139835. };
  139836. static int blocksize_long_44[11]={
  139837. 4096,2048,2048,2048,2048,2048,2048,2048,2048,2048,2048
  139838. };
  139839. static double _psy_compand_short_mapping[12]={
  139840. 0.5, 1., 1., 1.3, 1.6, 2., 2., 2., 2., 2., 2., 2.
  139841. };
  139842. static double _psy_compand_long_mapping[12]={
  139843. 3.5, 4., 4., 4.3, 4.6, 5., 5., 5., 5., 5., 5., 5.
  139844. };
  139845. static double _global_mapping_44[12]={
  139846. /* 1., 1., 1.5, 2., 2., 2.5, 2.7, 3.0, 3.5, 4., 4. */
  139847. 0., 1., 1., 1.5, 2., 2., 2.5, 2.7, 3.0, 3.7, 4., 4.
  139848. };
  139849. static int _floor_short_mapping_44[11]={
  139850. 1,0,0,2,2,4,5,5,5,5,5
  139851. };
  139852. static int _floor_long_mapping_44[11]={
  139853. 8,7,7,7,7,7,7,7,7,7,7
  139854. };
  139855. ve_setup_data_template ve_setup_44_stereo={
  139856. 11,
  139857. rate_mapping_44_stereo,
  139858. quality_mapping_44,
  139859. 2,
  139860. 40000,
  139861. 50000,
  139862. blocksize_short_44,
  139863. blocksize_long_44,
  139864. _psy_tone_masteratt_44,
  139865. _psy_tone_0dB,
  139866. _psy_tone_suppress,
  139867. _vp_tonemask_adj_otherblock,
  139868. _vp_tonemask_adj_longblock,
  139869. _vp_tonemask_adj_otherblock,
  139870. _psy_noiseguards_44,
  139871. _psy_noisebias_impulse,
  139872. _psy_noisebias_padding,
  139873. _psy_noisebias_trans,
  139874. _psy_noisebias_long,
  139875. _psy_noise_suppress,
  139876. _psy_compand_44,
  139877. _psy_compand_short_mapping,
  139878. _psy_compand_long_mapping,
  139879. {_noise_start_short_44,_noise_start_long_44},
  139880. {_noise_part_short_44,_noise_part_long_44},
  139881. _noise_thresh_44,
  139882. _psy_ath_floater,
  139883. _psy_ath_abs,
  139884. _psy_lowpass_44,
  139885. _psy_global_44,
  139886. _global_mapping_44,
  139887. _psy_stereo_modes_44,
  139888. _floor_books,
  139889. _floor,
  139890. _floor_short_mapping_44,
  139891. _floor_long_mapping_44,
  139892. _mapres_template_44_stereo
  139893. };
  139894. /*** End of inlined file: setup_44.h ***/
  139895. /*** Start of inlined file: setup_44u.h ***/
  139896. /*** Start of inlined file: residue_44u.h ***/
  139897. /*** Start of inlined file: res_books_uncoupled.h ***/
  139898. static long _vq_quantlist__16u0__p1_0[] = {
  139899. 1,
  139900. 0,
  139901. 2,
  139902. };
  139903. static long _vq_lengthlist__16u0__p1_0[] = {
  139904. 1, 4, 4, 5, 7, 7, 5, 7, 8, 5, 8, 8, 8,10,10, 8,
  139905. 10,11, 5, 8, 8, 8,10,10, 8,10,10, 4, 9, 9, 9,12,
  139906. 11, 8,11,11, 8,12,11,10,12,14,10,13,13, 7,11,11,
  139907. 10,14,12,11,14,14, 4, 9, 9, 8,11,11, 9,11,12, 7,
  139908. 11,11,10,13,14,10,12,14, 8,11,12,10,14,14,10,13,
  139909. 12,
  139910. };
  139911. static float _vq_quantthresh__16u0__p1_0[] = {
  139912. -0.5, 0.5,
  139913. };
  139914. static long _vq_quantmap__16u0__p1_0[] = {
  139915. 1, 0, 2,
  139916. };
  139917. static encode_aux_threshmatch _vq_auxt__16u0__p1_0 = {
  139918. _vq_quantthresh__16u0__p1_0,
  139919. _vq_quantmap__16u0__p1_0,
  139920. 3,
  139921. 3
  139922. };
  139923. static static_codebook _16u0__p1_0 = {
  139924. 4, 81,
  139925. _vq_lengthlist__16u0__p1_0,
  139926. 1, -535822336, 1611661312, 2, 0,
  139927. _vq_quantlist__16u0__p1_0,
  139928. NULL,
  139929. &_vq_auxt__16u0__p1_0,
  139930. NULL,
  139931. 0
  139932. };
  139933. static long _vq_quantlist__16u0__p2_0[] = {
  139934. 1,
  139935. 0,
  139936. 2,
  139937. };
  139938. static long _vq_lengthlist__16u0__p2_0[] = {
  139939. 2, 4, 4, 5, 6, 6, 5, 6, 6, 5, 7, 7, 7, 8, 9, 7,
  139940. 8, 9, 5, 7, 7, 7, 9, 8, 7, 9, 7, 4, 7, 7, 7, 9,
  139941. 9, 7, 8, 8, 6, 9, 8, 7, 8,11, 9,11,10, 6, 8, 9,
  139942. 8,11, 8, 9,10,11, 4, 7, 7, 7, 8, 8, 7, 9, 9, 6,
  139943. 9, 8, 9,11,10, 8, 8,11, 6, 8, 9, 9,10,11, 8,11,
  139944. 8,
  139945. };
  139946. static float _vq_quantthresh__16u0__p2_0[] = {
  139947. -0.5, 0.5,
  139948. };
  139949. static long _vq_quantmap__16u0__p2_0[] = {
  139950. 1, 0, 2,
  139951. };
  139952. static encode_aux_threshmatch _vq_auxt__16u0__p2_0 = {
  139953. _vq_quantthresh__16u0__p2_0,
  139954. _vq_quantmap__16u0__p2_0,
  139955. 3,
  139956. 3
  139957. };
  139958. static static_codebook _16u0__p2_0 = {
  139959. 4, 81,
  139960. _vq_lengthlist__16u0__p2_0,
  139961. 1, -535822336, 1611661312, 2, 0,
  139962. _vq_quantlist__16u0__p2_0,
  139963. NULL,
  139964. &_vq_auxt__16u0__p2_0,
  139965. NULL,
  139966. 0
  139967. };
  139968. static long _vq_quantlist__16u0__p3_0[] = {
  139969. 2,
  139970. 1,
  139971. 3,
  139972. 0,
  139973. 4,
  139974. };
  139975. static long _vq_lengthlist__16u0__p3_0[] = {
  139976. 1, 5, 5, 7, 7, 6, 7, 7, 8, 8, 6, 7, 8, 8, 8, 8,
  139977. 9, 9,11,11, 8, 9, 9,11,11, 6, 9, 8,10,10, 8,10,
  139978. 10,11,11, 8,10,10,11,11,10,11,10,13,12, 9,11,10,
  139979. 13,13, 6, 8, 9,10,10, 8,10,10,11,11, 8,10,10,11,
  139980. 11, 9,10,11,13,12,10,10,11,12,12, 8,11,11,14,13,
  139981. 10,12,11,15,13, 9,12,11,15,14,12,14,13,16,14,12,
  139982. 13,13,17,14, 8,11,11,13,14, 9,11,12,14,15,10,11,
  139983. 12,13,15,11,13,13,14,16,12,13,14,14,16, 5, 9, 9,
  139984. 11,11, 9,11,11,12,12, 8,11,11,12,12,11,12,12,15,
  139985. 14,10,12,12,15,15, 8,11,11,13,12,10,12,12,13,13,
  139986. 10,12,12,14,13,12,12,13,14,15,11,13,13,17,16, 7,
  139987. 11,11,13,13,10,12,12,14,13,10,12,12,13,14,12,13,
  139988. 12,15,14,11,13,13,15,14, 9,12,12,16,15,11,13,13,
  139989. 17,16,10,13,13,16,16,13,14,15,15,16,13,15,14,19,
  139990. 17, 9,12,12,14,16,11,13,13,15,16,10,13,13,17,16,
  139991. 13,14,13,17,15,12,15,15,16,17, 5, 9, 9,11,11, 8,
  139992. 11,11,13,12, 9,11,11,12,12,10,12,12,14,15,11,12,
  139993. 12,14,14, 7,11,10,13,12,10,12,12,14,13,10,11,12,
  139994. 13,13,11,13,13,15,16,12,12,13,15,15, 7,11,11,13,
  139995. 13,10,13,13,14,14,10,12,12,13,13,11,13,13,16,15,
  139996. 12,13,13,15,14, 9,12,12,15,15,10,13,13,17,16,11,
  139997. 12,13,15,15,12,15,14,18,18,13,14,14,16,17, 9,12,
  139998. 12,15,16,10,13,13,15,16,11,13,13,15,16,13,15,15,
  139999. 17,17,13,15,14,16,15, 7,11,11,15,16,10,13,12,16,
  140000. 17,10,12,13,15,17,15,16,16,18,17,13,15,15,17,18,
  140001. 8,12,12,16,16,11,13,14,17,18,11,13,13,18,16,15,
  140002. 17,16,17,19,14,15,15,17,16, 8,12,12,16,15,11,14,
  140003. 13,18,17,11,13,14,18,17,15,16,16,18,17,13,16,16,
  140004. 18,18,11,15,14,18,17,13,14,15,18, 0,12,15,15, 0,
  140005. 17,17,16,17,17,18,14,16,18,18, 0,11,14,14,17, 0,
  140006. 12,15,14,17,19,12,15,14,18, 0,15,18,16, 0,17,14,
  140007. 18,16,18, 0, 7,11,11,16,15,10,12,12,18,16,10,13,
  140008. 13,16,15,13,15,14,17,17,14,16,16,19,18, 8,12,12,
  140009. 16,16,11,13,13,18,16,11,13,14,17,16,14,15,15,19,
  140010. 18,15,16,16, 0,19, 8,12,12,16,17,11,13,13,17,17,
  140011. 11,14,13,17,17,13,15,15,17,19,15,17,17,19, 0,11,
  140012. 14,15,19,17,12,15,16,18,18,12,14,15,19,17,14,16,
  140013. 17, 0,18,16,16,19,17, 0,11,14,14,18,19,12,15,14,
  140014. 17,17,13,16,14,17,16,14,17,16,18,18,15,18,15, 0,
  140015. 18,
  140016. };
  140017. static float _vq_quantthresh__16u0__p3_0[] = {
  140018. -1.5, -0.5, 0.5, 1.5,
  140019. };
  140020. static long _vq_quantmap__16u0__p3_0[] = {
  140021. 3, 1, 0, 2, 4,
  140022. };
  140023. static encode_aux_threshmatch _vq_auxt__16u0__p3_0 = {
  140024. _vq_quantthresh__16u0__p3_0,
  140025. _vq_quantmap__16u0__p3_0,
  140026. 5,
  140027. 5
  140028. };
  140029. static static_codebook _16u0__p3_0 = {
  140030. 4, 625,
  140031. _vq_lengthlist__16u0__p3_0,
  140032. 1, -533725184, 1611661312, 3, 0,
  140033. _vq_quantlist__16u0__p3_0,
  140034. NULL,
  140035. &_vq_auxt__16u0__p3_0,
  140036. NULL,
  140037. 0
  140038. };
  140039. static long _vq_quantlist__16u0__p4_0[] = {
  140040. 2,
  140041. 1,
  140042. 3,
  140043. 0,
  140044. 4,
  140045. };
  140046. static long _vq_lengthlist__16u0__p4_0[] = {
  140047. 3, 5, 5, 8, 8, 6, 6, 6, 9, 9, 6, 6, 6, 9, 9, 9,
  140048. 10, 9,11,11, 9, 9, 9,11,11, 6, 7, 7,10,10, 7, 7,
  140049. 8,10,10, 7, 7, 8,10,10,10,10,10,11,12, 9,10,10,
  140050. 11,12, 6, 7, 7,10,10, 7, 8, 7,10,10, 7, 8, 7,10,
  140051. 10,10,11,10,12,11,10,10,10,13,10, 9,10,10,12,12,
  140052. 10,11,10,14,12, 9,11,11,13,13,11,12,13,13,13,11,
  140053. 12,12,15,13, 9,10,10,12,13, 9,11,10,12,13,10,10,
  140054. 11,12,13,11,12,12,12,13,11,12,12,13,13, 5, 7, 7,
  140055. 10,10, 7, 8, 8,10,10, 7, 8, 8,10,10,10,11,10,12,
  140056. 13,10,10,11,12,12, 6, 8, 8,11,10, 7, 8, 9,10,12,
  140057. 8, 9, 9,11,11,11,10,11,11,12,10,11,11,13,12, 7,
  140058. 8, 8,10,11, 8, 9, 8,11,10, 8, 9, 9,11,11,10,12,
  140059. 10,13,11,10,11,11,13,13,10,11,10,14,13,10,10,11,
  140060. 13,13,10,12,11,14,13,12,11,13,12,13,13,12,13,14,
  140061. 14,10,11,11,13,13,10,11,10,12,13,10,12,12,12,14,
  140062. 12,12,12,14,12,12,13,12,17,15, 5, 7, 7,10,10, 7,
  140063. 8, 8,10,10, 7, 8, 8,11,10,10,10,11,12,12,10,11,
  140064. 11,12,13, 6, 8, 8,11,10, 8, 9, 9,11,11, 7, 8, 9,
  140065. 10,11,11,11,11,12,12,10,10,11,12,13, 6, 8, 8,10,
  140066. 11, 8, 9, 9,11,11, 7, 9, 7,11,10,10,12,12,13,13,
  140067. 11,11,10,13,11, 9,11,10,14,13,11,11,11,15,13,10,
  140068. 10,11,13,13,12,13,13,14,14,12,11,12,12,13,10,11,
  140069. 11,12,13,10,11,12,13,13,10,11,10,13,12,12,12,13,
  140070. 14, 0,12,13,11,13,11, 8,10,10,13,13,10,11,11,14,
  140071. 13,10,11,11,13,12,13,14,14,14,15,12,12,12,15,14,
  140072. 9,11,10,13,12,10,10,11,13,14,11,11,11,15,12,13,
  140073. 12,14,15,16,13,13,13,14,13, 9,11,11,12,12,10,12,
  140074. 11,13,13,10,11,11,13,14,13,13,13,15,15,13,13,14,
  140075. 17,15,11,12,12,14,14,10,11,12,13,15,12,13,13, 0,
  140076. 15,13,11,14,12,16,14,16,14, 0,15,11,12,12,14,16,
  140077. 11,13,12,16,15,12,13,13,14,15,12,14,12,15,13,15,
  140078. 14,14,16,16, 8,10,10,13,13,10,11,10,13,14,10,11,
  140079. 11,13,13,13,13,12,14,14,14,13,13,16,17, 9,10,10,
  140080. 12,14,10,12,11,14,13,10,11,12,13,14,12,12,12,15,
  140081. 15,13,13,13,14,14, 9,10,10,13,13,10,11,12,12,14,
  140082. 10,11,10,13,13,13,13,13,14,16,13,13,13,14,14,11,
  140083. 12,13,15,13,12,14,13,14,16,12,12,13,13,14,13,14,
  140084. 14,17,15,13,12,17,13,16,11,12,13,14,15,12,13,14,
  140085. 14,17,11,12,11,14,14,13,16,14,16, 0,14,15,11,15,
  140086. 11,
  140087. };
  140088. static float _vq_quantthresh__16u0__p4_0[] = {
  140089. -1.5, -0.5, 0.5, 1.5,
  140090. };
  140091. static long _vq_quantmap__16u0__p4_0[] = {
  140092. 3, 1, 0, 2, 4,
  140093. };
  140094. static encode_aux_threshmatch _vq_auxt__16u0__p4_0 = {
  140095. _vq_quantthresh__16u0__p4_0,
  140096. _vq_quantmap__16u0__p4_0,
  140097. 5,
  140098. 5
  140099. };
  140100. static static_codebook _16u0__p4_0 = {
  140101. 4, 625,
  140102. _vq_lengthlist__16u0__p4_0,
  140103. 1, -533725184, 1611661312, 3, 0,
  140104. _vq_quantlist__16u0__p4_0,
  140105. NULL,
  140106. &_vq_auxt__16u0__p4_0,
  140107. NULL,
  140108. 0
  140109. };
  140110. static long _vq_quantlist__16u0__p5_0[] = {
  140111. 4,
  140112. 3,
  140113. 5,
  140114. 2,
  140115. 6,
  140116. 1,
  140117. 7,
  140118. 0,
  140119. 8,
  140120. };
  140121. static long _vq_lengthlist__16u0__p5_0[] = {
  140122. 1, 4, 4, 7, 7, 7, 7, 9, 9, 4, 6, 6, 8, 8, 8, 8,
  140123. 9, 9, 4, 6, 6, 8, 8, 8, 8, 9, 9, 7, 8, 8, 9, 9,
  140124. 9, 9,11,10, 7, 8, 8, 9, 9, 9, 9,10,11, 7, 8, 8,
  140125. 9, 9,10,10,11,11, 7, 8, 8, 9, 9,10,10,11,11, 9,
  140126. 9, 9,10,10,11,11,12,12, 9, 9, 9,10,10,11,11,12,
  140127. 12,
  140128. };
  140129. static float _vq_quantthresh__16u0__p5_0[] = {
  140130. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  140131. };
  140132. static long _vq_quantmap__16u0__p5_0[] = {
  140133. 7, 5, 3, 1, 0, 2, 4, 6,
  140134. 8,
  140135. };
  140136. static encode_aux_threshmatch _vq_auxt__16u0__p5_0 = {
  140137. _vq_quantthresh__16u0__p5_0,
  140138. _vq_quantmap__16u0__p5_0,
  140139. 9,
  140140. 9
  140141. };
  140142. static static_codebook _16u0__p5_0 = {
  140143. 2, 81,
  140144. _vq_lengthlist__16u0__p5_0,
  140145. 1, -531628032, 1611661312, 4, 0,
  140146. _vq_quantlist__16u0__p5_0,
  140147. NULL,
  140148. &_vq_auxt__16u0__p5_0,
  140149. NULL,
  140150. 0
  140151. };
  140152. static long _vq_quantlist__16u0__p6_0[] = {
  140153. 6,
  140154. 5,
  140155. 7,
  140156. 4,
  140157. 8,
  140158. 3,
  140159. 9,
  140160. 2,
  140161. 10,
  140162. 1,
  140163. 11,
  140164. 0,
  140165. 12,
  140166. };
  140167. static long _vq_lengthlist__16u0__p6_0[] = {
  140168. 1, 4, 4, 7, 7,10,10,12,12,13,13,18,17, 3, 6, 6,
  140169. 9, 9,11,11,13,13,14,14,18,17, 3, 6, 6, 9, 9,11,
  140170. 11,13,13,14,14,17,18, 7, 9, 9,11,11,13,13,14,14,
  140171. 15,15, 0, 0, 7, 9, 9,11,11,13,13,14,14,15,16,19,
  140172. 18,10,11,11,13,13,14,14,16,15,17,18, 0, 0,10,11,
  140173. 11,13,13,14,14,15,15,16,18, 0, 0,11,13,13,14,14,
  140174. 15,15,17,17, 0,19, 0, 0,11,13,13,14,14,14,15,16,
  140175. 18, 0,19, 0, 0,13,14,14,15,15,18,17,18,18, 0,19,
  140176. 0, 0,13,14,14,15,16,16,16,18,18,19, 0, 0, 0,16,
  140177. 17,17, 0,17,19,19, 0,19, 0, 0, 0, 0,16,19,16,17,
  140178. 18, 0,19, 0, 0, 0, 0, 0, 0,
  140179. };
  140180. static float _vq_quantthresh__16u0__p6_0[] = {
  140181. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  140182. 12.5, 17.5, 22.5, 27.5,
  140183. };
  140184. static long _vq_quantmap__16u0__p6_0[] = {
  140185. 11, 9, 7, 5, 3, 1, 0, 2,
  140186. 4, 6, 8, 10, 12,
  140187. };
  140188. static encode_aux_threshmatch _vq_auxt__16u0__p6_0 = {
  140189. _vq_quantthresh__16u0__p6_0,
  140190. _vq_quantmap__16u0__p6_0,
  140191. 13,
  140192. 13
  140193. };
  140194. static static_codebook _16u0__p6_0 = {
  140195. 2, 169,
  140196. _vq_lengthlist__16u0__p6_0,
  140197. 1, -526516224, 1616117760, 4, 0,
  140198. _vq_quantlist__16u0__p6_0,
  140199. NULL,
  140200. &_vq_auxt__16u0__p6_0,
  140201. NULL,
  140202. 0
  140203. };
  140204. static long _vq_quantlist__16u0__p6_1[] = {
  140205. 2,
  140206. 1,
  140207. 3,
  140208. 0,
  140209. 4,
  140210. };
  140211. static long _vq_lengthlist__16u0__p6_1[] = {
  140212. 1, 4, 5, 6, 6, 4, 6, 6, 6, 6, 4, 6, 6, 6, 6, 6,
  140213. 6, 6, 7, 7, 6, 6, 6, 7, 7,
  140214. };
  140215. static float _vq_quantthresh__16u0__p6_1[] = {
  140216. -1.5, -0.5, 0.5, 1.5,
  140217. };
  140218. static long _vq_quantmap__16u0__p6_1[] = {
  140219. 3, 1, 0, 2, 4,
  140220. };
  140221. static encode_aux_threshmatch _vq_auxt__16u0__p6_1 = {
  140222. _vq_quantthresh__16u0__p6_1,
  140223. _vq_quantmap__16u0__p6_1,
  140224. 5,
  140225. 5
  140226. };
  140227. static static_codebook _16u0__p6_1 = {
  140228. 2, 25,
  140229. _vq_lengthlist__16u0__p6_1,
  140230. 1, -533725184, 1611661312, 3, 0,
  140231. _vq_quantlist__16u0__p6_1,
  140232. NULL,
  140233. &_vq_auxt__16u0__p6_1,
  140234. NULL,
  140235. 0
  140236. };
  140237. static long _vq_quantlist__16u0__p7_0[] = {
  140238. 1,
  140239. 0,
  140240. 2,
  140241. };
  140242. static long _vq_lengthlist__16u0__p7_0[] = {
  140243. 1, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  140244. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  140245. 8, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  140246. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  140247. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  140248. 7,
  140249. };
  140250. static float _vq_quantthresh__16u0__p7_0[] = {
  140251. -157.5, 157.5,
  140252. };
  140253. static long _vq_quantmap__16u0__p7_0[] = {
  140254. 1, 0, 2,
  140255. };
  140256. static encode_aux_threshmatch _vq_auxt__16u0__p7_0 = {
  140257. _vq_quantthresh__16u0__p7_0,
  140258. _vq_quantmap__16u0__p7_0,
  140259. 3,
  140260. 3
  140261. };
  140262. static static_codebook _16u0__p7_0 = {
  140263. 4, 81,
  140264. _vq_lengthlist__16u0__p7_0,
  140265. 1, -518803456, 1628680192, 2, 0,
  140266. _vq_quantlist__16u0__p7_0,
  140267. NULL,
  140268. &_vq_auxt__16u0__p7_0,
  140269. NULL,
  140270. 0
  140271. };
  140272. static long _vq_quantlist__16u0__p7_1[] = {
  140273. 7,
  140274. 6,
  140275. 8,
  140276. 5,
  140277. 9,
  140278. 4,
  140279. 10,
  140280. 3,
  140281. 11,
  140282. 2,
  140283. 12,
  140284. 1,
  140285. 13,
  140286. 0,
  140287. 14,
  140288. };
  140289. static long _vq_lengthlist__16u0__p7_1[] = {
  140290. 1, 5, 5, 6, 5, 9,10,11,11,10,10,10,10,10,10, 5,
  140291. 8, 8, 8,10,10,10,10,10,10,10,10,10,10,10, 5, 8,
  140292. 9, 9, 9,10,10,10,10,10,10,10,10,10,10, 5,10, 8,
  140293. 10,10,10,10,10,10,10,10,10,10,10,10, 4, 8, 9,10,
  140294. 10,10,10,10,10,10,10,10,10,10,10, 9,10,10,10,10,
  140295. 10,10,10,10,10,10,10,10,10,10, 9,10,10,10,10,10,
  140296. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  140297. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  140298. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  140299. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  140300. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  140301. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  140302. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  140303. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  140304. 10,
  140305. };
  140306. static float _vq_quantthresh__16u0__p7_1[] = {
  140307. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  140308. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  140309. };
  140310. static long _vq_quantmap__16u0__p7_1[] = {
  140311. 13, 11, 9, 7, 5, 3, 1, 0,
  140312. 2, 4, 6, 8, 10, 12, 14,
  140313. };
  140314. static encode_aux_threshmatch _vq_auxt__16u0__p7_1 = {
  140315. _vq_quantthresh__16u0__p7_1,
  140316. _vq_quantmap__16u0__p7_1,
  140317. 15,
  140318. 15
  140319. };
  140320. static static_codebook _16u0__p7_1 = {
  140321. 2, 225,
  140322. _vq_lengthlist__16u0__p7_1,
  140323. 1, -520986624, 1620377600, 4, 0,
  140324. _vq_quantlist__16u0__p7_1,
  140325. NULL,
  140326. &_vq_auxt__16u0__p7_1,
  140327. NULL,
  140328. 0
  140329. };
  140330. static long _vq_quantlist__16u0__p7_2[] = {
  140331. 10,
  140332. 9,
  140333. 11,
  140334. 8,
  140335. 12,
  140336. 7,
  140337. 13,
  140338. 6,
  140339. 14,
  140340. 5,
  140341. 15,
  140342. 4,
  140343. 16,
  140344. 3,
  140345. 17,
  140346. 2,
  140347. 18,
  140348. 1,
  140349. 19,
  140350. 0,
  140351. 20,
  140352. };
  140353. static long _vq_lengthlist__16u0__p7_2[] = {
  140354. 1, 6, 6, 7, 8, 7, 7,10, 9,10, 9,11,10, 9,11,10,
  140355. 9, 9, 9, 9,10, 6, 8, 7, 9, 9, 8, 8,10,10, 9,11,
  140356. 11,12,12,10, 9,11, 9,12,10, 9, 6, 9, 8, 9,12, 8,
  140357. 8,11, 9,11,11,12,11,12,12,10,11,11,10,10,11, 7,
  140358. 10, 9, 9, 9, 9, 9,10, 9,10, 9,10,10,12,10,10,10,
  140359. 11,12,10,10, 7, 9, 9, 9,10, 9, 9,10,10, 9, 9, 9,
  140360. 11,11,10,10,10,10, 9, 9,12, 7, 9,10, 9,11, 9,10,
  140361. 9,10,11,11,11,10,11,12, 9,12,11,10,10,10, 7, 9,
  140362. 9, 9, 9,10,12,10, 9,11,12,10,11,12,12,11, 9,10,
  140363. 11,10,11, 7, 9,10,10,11,10, 9,10,11,11,11,10,12,
  140364. 12,12,11,11,10,11,11,12, 8, 9,10,12,11,10,10,12,
  140365. 12,12,12,12,10,11,11, 9,11,10,12,11,11, 8, 9,10,
  140366. 10,11,12,11,11,10,10,10,12,12,12, 9,10,12,12,12,
  140367. 12,12, 8,10,11,10,10,12, 9,11,12,12,11,12,12,12,
  140368. 12,10,12,10,10,10,10, 8,12,11,11,11,10,10,11,12,
  140369. 12,12,12,11,12,12,12,11,11,11,12,10, 9,10,10,12,
  140370. 10,12,10,12,12,10,10,10,11,12,12,12,11,12,12,12,
  140371. 11,10,11,12,12,12,11,12,12,11,12,12,11,12,12,12,
  140372. 12,11,12,12,10,10,10,10,11,11,12,11,12,12,12,12,
  140373. 12,12,12,11,12,11,10,11,11,12,11,11, 9,10,10,10,
  140374. 12,10,10,11, 9,11,12,11,12,11,12,12,10,11,10,12,
  140375. 9, 9, 9,12,11,10,11,10,12,10,12,10,12,12,12,11,
  140376. 11,11,11,11,10, 9,10,10,11,10,11,11,12,11,10,11,
  140377. 12,12,12,11,11, 9,12,10,12, 9,10,12,10,10,11,10,
  140378. 11,11,12,11,10,11,10,11,11,11,11,12,11,11,10, 9,
  140379. 10,10,10, 9,11,11,10, 9,12,10,11,12,11,12,12,11,
  140380. 12,11,12,11,10,11,10,12,11,12,11,12,11,12,10,11,
  140381. 10,10,12,11,10,11,11,11,10,
  140382. };
  140383. static float _vq_quantthresh__16u0__p7_2[] = {
  140384. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  140385. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  140386. 6.5, 7.5, 8.5, 9.5,
  140387. };
  140388. static long _vq_quantmap__16u0__p7_2[] = {
  140389. 19, 17, 15, 13, 11, 9, 7, 5,
  140390. 3, 1, 0, 2, 4, 6, 8, 10,
  140391. 12, 14, 16, 18, 20,
  140392. };
  140393. static encode_aux_threshmatch _vq_auxt__16u0__p7_2 = {
  140394. _vq_quantthresh__16u0__p7_2,
  140395. _vq_quantmap__16u0__p7_2,
  140396. 21,
  140397. 21
  140398. };
  140399. static static_codebook _16u0__p7_2 = {
  140400. 2, 441,
  140401. _vq_lengthlist__16u0__p7_2,
  140402. 1, -529268736, 1611661312, 5, 0,
  140403. _vq_quantlist__16u0__p7_2,
  140404. NULL,
  140405. &_vq_auxt__16u0__p7_2,
  140406. NULL,
  140407. 0
  140408. };
  140409. static long _huff_lengthlist__16u0__single[] = {
  140410. 3, 5, 8, 7,14, 8, 9,19, 5, 2, 5, 5, 9, 6, 9,19,
  140411. 8, 4, 5, 7, 8, 9,13,19, 7, 4, 6, 5, 9, 6, 9,19,
  140412. 12, 8, 7, 9,10,11,13,19, 8, 5, 8, 6, 9, 6, 7,19,
  140413. 8, 8,10, 7, 7, 4, 5,19,12,17,19,15,18,13,11,18,
  140414. };
  140415. static static_codebook _huff_book__16u0__single = {
  140416. 2, 64,
  140417. _huff_lengthlist__16u0__single,
  140418. 0, 0, 0, 0, 0,
  140419. NULL,
  140420. NULL,
  140421. NULL,
  140422. NULL,
  140423. 0
  140424. };
  140425. static long _huff_lengthlist__16u1__long[] = {
  140426. 3, 6,10, 8,12, 8,14, 8,14,19, 5, 3, 5, 5, 7, 6,
  140427. 11, 7,16,19, 7, 5, 6, 7, 7, 9,11,12,19,19, 6, 4,
  140428. 7, 5, 7, 6,10, 7,18,18, 8, 6, 7, 7, 7, 7, 8, 9,
  140429. 18,18, 7, 5, 8, 5, 7, 5, 8, 6,18,18,12, 9,10, 9,
  140430. 9, 9, 8, 9,18,18, 8, 7,10, 6, 8, 5, 6, 4,11,18,
  140431. 11,15,16,12,11, 8, 8, 6, 9,18,14,18,18,18,16,16,
  140432. 16,13,16,18,
  140433. };
  140434. static static_codebook _huff_book__16u1__long = {
  140435. 2, 100,
  140436. _huff_lengthlist__16u1__long,
  140437. 0, 0, 0, 0, 0,
  140438. NULL,
  140439. NULL,
  140440. NULL,
  140441. NULL,
  140442. 0
  140443. };
  140444. static long _vq_quantlist__16u1__p1_0[] = {
  140445. 1,
  140446. 0,
  140447. 2,
  140448. };
  140449. static long _vq_lengthlist__16u1__p1_0[] = {
  140450. 1, 4, 4, 5, 7, 7, 5, 7, 7, 5, 8, 7, 7,10,10, 7,
  140451. 9,10, 5, 7, 8, 7,10, 9, 7,10,10, 5, 8, 8, 8,10,
  140452. 10, 8,10,10, 7,10,10,10,11,12,10,12,13, 7,10,10,
  140453. 9,13,11,10,12,13, 5, 8, 8, 8,10,10, 8,10,10, 7,
  140454. 10,10,10,12,12, 9,11,12, 7,10,11,10,12,12,10,13,
  140455. 11,
  140456. };
  140457. static float _vq_quantthresh__16u1__p1_0[] = {
  140458. -0.5, 0.5,
  140459. };
  140460. static long _vq_quantmap__16u1__p1_0[] = {
  140461. 1, 0, 2,
  140462. };
  140463. static encode_aux_threshmatch _vq_auxt__16u1__p1_0 = {
  140464. _vq_quantthresh__16u1__p1_0,
  140465. _vq_quantmap__16u1__p1_0,
  140466. 3,
  140467. 3
  140468. };
  140469. static static_codebook _16u1__p1_0 = {
  140470. 4, 81,
  140471. _vq_lengthlist__16u1__p1_0,
  140472. 1, -535822336, 1611661312, 2, 0,
  140473. _vq_quantlist__16u1__p1_0,
  140474. NULL,
  140475. &_vq_auxt__16u1__p1_0,
  140476. NULL,
  140477. 0
  140478. };
  140479. static long _vq_quantlist__16u1__p2_0[] = {
  140480. 1,
  140481. 0,
  140482. 2,
  140483. };
  140484. static long _vq_lengthlist__16u1__p2_0[] = {
  140485. 3, 4, 4, 5, 6, 6, 5, 6, 6, 5, 6, 6, 6, 7, 8, 6,
  140486. 7, 8, 5, 6, 6, 6, 8, 7, 6, 8, 7, 5, 6, 6, 6, 8,
  140487. 8, 6, 8, 8, 6, 8, 8, 7, 7,10, 8, 9, 9, 6, 8, 8,
  140488. 7, 9, 8, 8, 9,10, 5, 6, 6, 6, 8, 8, 7, 8, 8, 6,
  140489. 8, 8, 8,10, 9, 7, 8, 9, 6, 8, 8, 8, 9, 9, 7,10,
  140490. 8,
  140491. };
  140492. static float _vq_quantthresh__16u1__p2_0[] = {
  140493. -0.5, 0.5,
  140494. };
  140495. static long _vq_quantmap__16u1__p2_0[] = {
  140496. 1, 0, 2,
  140497. };
  140498. static encode_aux_threshmatch _vq_auxt__16u1__p2_0 = {
  140499. _vq_quantthresh__16u1__p2_0,
  140500. _vq_quantmap__16u1__p2_0,
  140501. 3,
  140502. 3
  140503. };
  140504. static static_codebook _16u1__p2_0 = {
  140505. 4, 81,
  140506. _vq_lengthlist__16u1__p2_0,
  140507. 1, -535822336, 1611661312, 2, 0,
  140508. _vq_quantlist__16u1__p2_0,
  140509. NULL,
  140510. &_vq_auxt__16u1__p2_0,
  140511. NULL,
  140512. 0
  140513. };
  140514. static long _vq_quantlist__16u1__p3_0[] = {
  140515. 2,
  140516. 1,
  140517. 3,
  140518. 0,
  140519. 4,
  140520. };
  140521. static long _vq_lengthlist__16u1__p3_0[] = {
  140522. 1, 5, 5, 8, 8, 6, 7, 7, 9, 9, 5, 7, 7, 9, 9, 9,
  140523. 10, 9,11,11, 9, 9,10,11,11, 6, 8, 8,10,10, 8, 9,
  140524. 10,11,11, 8, 9,10,11,11,10,11,11,12,13,10,11,11,
  140525. 13,13, 6, 8, 8,10,10, 8,10, 9,11,11, 8,10, 9,11,
  140526. 11,10,11,11,13,13,10,11,11,13,12, 9,11,11,14,13,
  140527. 10,12,12,15,14,10,12,11,14,13,12,13,13,15,15,12,
  140528. 13,13,16,14, 9,11,11,13,14,10,11,12,14,14,10,12,
  140529. 12,14,15,12,13,13,14,15,12,13,14,15,16, 5, 8, 8,
  140530. 11,11, 8,10,10,12,12, 8,10,10,12,12,11,12,12,14,
  140531. 14,11,12,12,14,14, 8,10,10,12,12, 9,11,12,12,13,
  140532. 10,12,12,13,13,12,12,13,14,15,11,13,13,15,15, 7,
  140533. 10,10,12,12, 9,12,11,13,12,10,11,12,13,13,12,13,
  140534. 12,15,14,11,12,13,15,15,10,12,12,15,14,11,13,13,
  140535. 16,15,11,13,13,16,15,14,13,14,15,16,13,15,15,17,
  140536. 17,10,12,12,14,15,11,12,12,15,15,11,13,13,15,16,
  140537. 13,15,13,16,15,13,15,15,16,17, 5, 8, 8,11,11, 8,
  140538. 10,10,12,12, 8,10,10,12,12,11,12,12,14,14,11,12,
  140539. 12,14,14, 7,10,10,12,12,10,12,12,14,13, 9,11,12,
  140540. 12,13,12,13,13,15,15,12,12,13,13,15, 7,10,10,12,
  140541. 13,10,11,12,13,13,10,12,11,13,13,11,13,13,15,15,
  140542. 12,13,12,15,14, 9,12,12,15,14,11,13,13,15,15,11,
  140543. 12,13,15,15,13,14,14,17,19,13,13,14,16,16,10,12,
  140544. 12,14,15,11,13,13,15,16,11,13,12,16,15,13,15,15,
  140545. 17,18,14,15,13,16,15, 8,11,11,15,14,10,12,12,16,
  140546. 15,10,12,12,16,16,14,15,15,18,17,13,14,15,16,18,
  140547. 9,12,12,15,15,11,12,14,16,17,11,13,13,16,15,15,
  140548. 15,15,17,18,14,15,16,17,17, 9,12,12,15,15,11,14,
  140549. 13,16,16,11,13,13,16,16,15,16,15,17,18,14,16,15,
  140550. 17,16,12,14,14,17,16,12,14,15,18,17,13,15,15,17,
  140551. 17,15,15,18,16,20,15,16,17,18,18,11,14,14,16,17,
  140552. 13,15,14,18,17,13,15,15,17,17,15,17,15,18,17,15,
  140553. 17,16,19,18, 8,11,11,14,15,10,12,12,15,15,10,12,
  140554. 12,16,16,13,14,14,17,16,14,15,15,17,17, 9,12,12,
  140555. 15,16,11,13,13,16,16,11,12,13,16,16,14,16,15,20,
  140556. 17,14,16,16,17,17, 9,12,12,15,16,11,13,13,16,17,
  140557. 11,13,13,17,16,14,15,15,17,18,15,15,15,18,18,11,
  140558. 14,14,17,16,13,15,15,17,17,13,14,14,18,17,15,16,
  140559. 16,18,19,15,15,17,17,19,11,14,14,16,17,13,15,14,
  140560. 17,19,13,15,14,18,17,15,17,16,18,18,15,17,15,18,
  140561. 16,
  140562. };
  140563. static float _vq_quantthresh__16u1__p3_0[] = {
  140564. -1.5, -0.5, 0.5, 1.5,
  140565. };
  140566. static long _vq_quantmap__16u1__p3_0[] = {
  140567. 3, 1, 0, 2, 4,
  140568. };
  140569. static encode_aux_threshmatch _vq_auxt__16u1__p3_0 = {
  140570. _vq_quantthresh__16u1__p3_0,
  140571. _vq_quantmap__16u1__p3_0,
  140572. 5,
  140573. 5
  140574. };
  140575. static static_codebook _16u1__p3_0 = {
  140576. 4, 625,
  140577. _vq_lengthlist__16u1__p3_0,
  140578. 1, -533725184, 1611661312, 3, 0,
  140579. _vq_quantlist__16u1__p3_0,
  140580. NULL,
  140581. &_vq_auxt__16u1__p3_0,
  140582. NULL,
  140583. 0
  140584. };
  140585. static long _vq_quantlist__16u1__p4_0[] = {
  140586. 2,
  140587. 1,
  140588. 3,
  140589. 0,
  140590. 4,
  140591. };
  140592. static long _vq_lengthlist__16u1__p4_0[] = {
  140593. 4, 5, 5, 8, 8, 6, 6, 7, 9, 9, 6, 6, 6, 9, 9, 9,
  140594. 10, 9,11,11, 9, 9,10,11,11, 6, 7, 7,10, 9, 7, 7,
  140595. 8, 9,10, 7, 7, 8,10,10,10,10,10,10,12, 9, 9,10,
  140596. 11,12, 6, 7, 7, 9, 9, 7, 8, 7,10,10, 7, 8, 7,10,
  140597. 10, 9,10, 9,12,11,10,10, 9,12,10, 9,10,10,12,11,
  140598. 10,10,10,12,12, 9,10,10,12,12,12,11,12,13,13,11,
  140599. 11,12,12,13, 9,10,10,11,12, 9,10,10,12,12,10,10,
  140600. 10,12,12,11,12,11,14,13,11,12,12,14,13, 5, 7, 7,
  140601. 10,10, 7, 8, 8,10,10, 7, 8, 7,10,10,10,10,10,12,
  140602. 12,10,10,10,12,12, 6, 8, 7,10,10, 7, 7, 9,10,11,
  140603. 8, 9, 9,11,10,10,10,11,11,13,10,10,11,12,13, 6,
  140604. 8, 8,10,10, 7, 9, 8,11,10, 8, 9, 9,10,11,10,11,
  140605. 10,13,11,10,11,10,12,12,10,11,10,12,11,10,10,10,
  140606. 12,13,10,11,11,13,12,11,11,13,11,14,12,12,13,14,
  140607. 14, 9,10,10,12,13,10,11,10,13,12,10,11,11,12,13,
  140608. 11,12,11,14,12,12,13,13,15,14, 5, 7, 7,10,10, 7,
  140609. 7, 8,10,10, 7, 8, 8,10,10,10,10,10,11,12,10,10,
  140610. 10,12,12, 7, 8, 8,10,10, 8, 9, 8,11,10, 7, 8, 9,
  140611. 10,11,10,11,11,12,12,10,10,11,11,13, 7, 7, 8,10,
  140612. 10, 8, 8, 9,10,11, 7, 9, 7,11,10,10,11,11,13,12,
  140613. 11,11,10,13,11, 9,10,10,12,12,10,11,11,13,12,10,
  140614. 10,11,12,12,12,13,13,14,14,11,11,12,12,14,10,10,
  140615. 11,12,12,10,11,11,12,13,10,10,10,13,12,12,13,13,
  140616. 15,14,12,13,10,14,11, 8,10,10,12,12,10,11,10,13,
  140617. 13, 9,10,10,12,12,12,13,13,15,14,11,12,12,13,13,
  140618. 9,10,10,13,12,10,10,11,13,13,10,11,10,13,12,12,
  140619. 12,13,14,15,12,13,12,15,13, 9,10,10,12,13,10,11,
  140620. 10,13,12,10,10,11,12,13,12,14,12,15,13,12,12,13,
  140621. 14,15,11,12,11,14,13,11,11,12,14,15,12,13,12,15,
  140622. 14,13,11,15,11,16,13,14,14,16,15,11,12,12,14,14,
  140623. 11,12,11,14,13,12,12,13,14,15,13,14,12,16,12,14,
  140624. 14,14,15,15, 8,10,10,12,12, 9,10,10,12,12,10,10,
  140625. 11,13,13,11,12,12,13,13,12,13,13,14,15, 9,10,10,
  140626. 13,12,10,11,11,13,12,10,10,11,13,13,12,13,12,15,
  140627. 14,12,12,13,13,16, 9, 9,10,12,13,10,10,11,12,13,
  140628. 10,11,10,13,13,12,12,13,13,15,13,13,12,15,13,11,
  140629. 12,12,14,14,12,13,12,15,14,11,11,12,13,14,14,14,
  140630. 14,16,15,13,12,15,12,16,11,11,12,13,14,12,13,13,
  140631. 14,15,10,12,11,14,13,14,15,14,16,16,13,14,11,15,
  140632. 11,
  140633. };
  140634. static float _vq_quantthresh__16u1__p4_0[] = {
  140635. -1.5, -0.5, 0.5, 1.5,
  140636. };
  140637. static long _vq_quantmap__16u1__p4_0[] = {
  140638. 3, 1, 0, 2, 4,
  140639. };
  140640. static encode_aux_threshmatch _vq_auxt__16u1__p4_0 = {
  140641. _vq_quantthresh__16u1__p4_0,
  140642. _vq_quantmap__16u1__p4_0,
  140643. 5,
  140644. 5
  140645. };
  140646. static static_codebook _16u1__p4_0 = {
  140647. 4, 625,
  140648. _vq_lengthlist__16u1__p4_0,
  140649. 1, -533725184, 1611661312, 3, 0,
  140650. _vq_quantlist__16u1__p4_0,
  140651. NULL,
  140652. &_vq_auxt__16u1__p4_0,
  140653. NULL,
  140654. 0
  140655. };
  140656. static long _vq_quantlist__16u1__p5_0[] = {
  140657. 4,
  140658. 3,
  140659. 5,
  140660. 2,
  140661. 6,
  140662. 1,
  140663. 7,
  140664. 0,
  140665. 8,
  140666. };
  140667. static long _vq_lengthlist__16u1__p5_0[] = {
  140668. 1, 4, 4, 7, 7, 7, 7, 9, 9, 4, 6, 6, 8, 8, 8, 8,
  140669. 10,10, 4, 5, 6, 8, 8, 8, 8,10,10, 7, 8, 8, 9, 9,
  140670. 9, 9,11,11, 7, 8, 8, 9, 9, 9, 9,11,11, 7, 8, 8,
  140671. 10, 9,11,11,12,11, 7, 8, 8, 9, 9,11,11,12,12, 9,
  140672. 10,10,11,11,12,12,13,12, 9,10,10,11,11,12,12,12,
  140673. 13,
  140674. };
  140675. static float _vq_quantthresh__16u1__p5_0[] = {
  140676. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  140677. };
  140678. static long _vq_quantmap__16u1__p5_0[] = {
  140679. 7, 5, 3, 1, 0, 2, 4, 6,
  140680. 8,
  140681. };
  140682. static encode_aux_threshmatch _vq_auxt__16u1__p5_0 = {
  140683. _vq_quantthresh__16u1__p5_0,
  140684. _vq_quantmap__16u1__p5_0,
  140685. 9,
  140686. 9
  140687. };
  140688. static static_codebook _16u1__p5_0 = {
  140689. 2, 81,
  140690. _vq_lengthlist__16u1__p5_0,
  140691. 1, -531628032, 1611661312, 4, 0,
  140692. _vq_quantlist__16u1__p5_0,
  140693. NULL,
  140694. &_vq_auxt__16u1__p5_0,
  140695. NULL,
  140696. 0
  140697. };
  140698. static long _vq_quantlist__16u1__p6_0[] = {
  140699. 4,
  140700. 3,
  140701. 5,
  140702. 2,
  140703. 6,
  140704. 1,
  140705. 7,
  140706. 0,
  140707. 8,
  140708. };
  140709. static long _vq_lengthlist__16u1__p6_0[] = {
  140710. 3, 4, 4, 6, 6, 7, 7, 9, 9, 4, 4, 4, 6, 6, 8, 8,
  140711. 9, 9, 4, 4, 4, 6, 6, 7, 7, 9, 9, 6, 6, 6, 7, 7,
  140712. 8, 8,10, 9, 6, 6, 6, 7, 7, 8, 8, 9,10, 7, 8, 7,
  140713. 8, 8, 9, 9,10,10, 7, 8, 8, 8, 8, 9, 9,10,10, 9,
  140714. 9, 9,10,10,10,10,11,11, 9, 9, 9,10,10,10,10,11,
  140715. 11,
  140716. };
  140717. static float _vq_quantthresh__16u1__p6_0[] = {
  140718. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  140719. };
  140720. static long _vq_quantmap__16u1__p6_0[] = {
  140721. 7, 5, 3, 1, 0, 2, 4, 6,
  140722. 8,
  140723. };
  140724. static encode_aux_threshmatch _vq_auxt__16u1__p6_0 = {
  140725. _vq_quantthresh__16u1__p6_0,
  140726. _vq_quantmap__16u1__p6_0,
  140727. 9,
  140728. 9
  140729. };
  140730. static static_codebook _16u1__p6_0 = {
  140731. 2, 81,
  140732. _vq_lengthlist__16u1__p6_0,
  140733. 1, -531628032, 1611661312, 4, 0,
  140734. _vq_quantlist__16u1__p6_0,
  140735. NULL,
  140736. &_vq_auxt__16u1__p6_0,
  140737. NULL,
  140738. 0
  140739. };
  140740. static long _vq_quantlist__16u1__p7_0[] = {
  140741. 1,
  140742. 0,
  140743. 2,
  140744. };
  140745. static long _vq_lengthlist__16u1__p7_0[] = {
  140746. 1, 4, 4, 4, 8, 8, 4, 8, 8, 5,11, 9, 8,12,11, 8,
  140747. 12,11, 5,10,11, 8,11,12, 8,11,12, 4,11,11,11,14,
  140748. 13,10,13,13, 8,14,13,12,14,16,12,16,15, 8,14,14,
  140749. 13,16,14,12,15,16, 4,11,11,10,14,13,11,14,14, 8,
  140750. 15,14,12,15,15,12,14,16, 8,14,14,11,16,15,12,15,
  140751. 13,
  140752. };
  140753. static float _vq_quantthresh__16u1__p7_0[] = {
  140754. -5.5, 5.5,
  140755. };
  140756. static long _vq_quantmap__16u1__p7_0[] = {
  140757. 1, 0, 2,
  140758. };
  140759. static encode_aux_threshmatch _vq_auxt__16u1__p7_0 = {
  140760. _vq_quantthresh__16u1__p7_0,
  140761. _vq_quantmap__16u1__p7_0,
  140762. 3,
  140763. 3
  140764. };
  140765. static static_codebook _16u1__p7_0 = {
  140766. 4, 81,
  140767. _vq_lengthlist__16u1__p7_0,
  140768. 1, -529137664, 1618345984, 2, 0,
  140769. _vq_quantlist__16u1__p7_0,
  140770. NULL,
  140771. &_vq_auxt__16u1__p7_0,
  140772. NULL,
  140773. 0
  140774. };
  140775. static long _vq_quantlist__16u1__p7_1[] = {
  140776. 5,
  140777. 4,
  140778. 6,
  140779. 3,
  140780. 7,
  140781. 2,
  140782. 8,
  140783. 1,
  140784. 9,
  140785. 0,
  140786. 10,
  140787. };
  140788. static long _vq_lengthlist__16u1__p7_1[] = {
  140789. 2, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8, 4, 6, 5, 7, 7,
  140790. 8, 8, 8, 8, 8, 8, 4, 5, 6, 7, 7, 8, 8, 8, 8, 8,
  140791. 8, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 6, 7, 7, 8,
  140792. 8, 8, 8, 9, 9, 9, 9, 7, 8, 8, 8, 8, 9, 9, 9,10,
  140793. 9,10, 7, 8, 8, 8, 8, 9, 9, 9, 9,10, 9, 8, 8, 8,
  140794. 9, 9,10,10,10,10,10,10, 8, 8, 8, 9, 9, 9, 9,10,
  140795. 10,10,10, 8, 8, 8, 9, 9, 9,10,10,10,10,10, 8, 8,
  140796. 8, 9, 9,10,10,10,10,10,10,
  140797. };
  140798. static float _vq_quantthresh__16u1__p7_1[] = {
  140799. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  140800. 3.5, 4.5,
  140801. };
  140802. static long _vq_quantmap__16u1__p7_1[] = {
  140803. 9, 7, 5, 3, 1, 0, 2, 4,
  140804. 6, 8, 10,
  140805. };
  140806. static encode_aux_threshmatch _vq_auxt__16u1__p7_1 = {
  140807. _vq_quantthresh__16u1__p7_1,
  140808. _vq_quantmap__16u1__p7_1,
  140809. 11,
  140810. 11
  140811. };
  140812. static static_codebook _16u1__p7_1 = {
  140813. 2, 121,
  140814. _vq_lengthlist__16u1__p7_1,
  140815. 1, -531365888, 1611661312, 4, 0,
  140816. _vq_quantlist__16u1__p7_1,
  140817. NULL,
  140818. &_vq_auxt__16u1__p7_1,
  140819. NULL,
  140820. 0
  140821. };
  140822. static long _vq_quantlist__16u1__p8_0[] = {
  140823. 5,
  140824. 4,
  140825. 6,
  140826. 3,
  140827. 7,
  140828. 2,
  140829. 8,
  140830. 1,
  140831. 9,
  140832. 0,
  140833. 10,
  140834. };
  140835. static long _vq_lengthlist__16u1__p8_0[] = {
  140836. 1, 4, 4, 5, 5, 8, 8,10,10,12,12, 4, 7, 7, 8, 8,
  140837. 9, 9,12,11,14,13, 4, 7, 7, 7, 8, 9,10,11,11,13,
  140838. 12, 5, 8, 8, 9, 9,11,11,12,13,15,14, 5, 7, 8, 9,
  140839. 9,11,11,13,13,17,15, 8, 9,10,11,11,12,13,17,14,
  140840. 17,16, 8,10, 9,11,11,12,12,13,15,15,17,10,11,11,
  140841. 12,13,14,15,15,16,16,17, 9,11,11,12,12,14,15,17,
  140842. 15,15,16,11,14,12,14,15,16,15,16,16,16,15,11,13,
  140843. 13,14,14,15,15,16,16,15,16,
  140844. };
  140845. static float _vq_quantthresh__16u1__p8_0[] = {
  140846. -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5, 27.5,
  140847. 38.5, 49.5,
  140848. };
  140849. static long _vq_quantmap__16u1__p8_0[] = {
  140850. 9, 7, 5, 3, 1, 0, 2, 4,
  140851. 6, 8, 10,
  140852. };
  140853. static encode_aux_threshmatch _vq_auxt__16u1__p8_0 = {
  140854. _vq_quantthresh__16u1__p8_0,
  140855. _vq_quantmap__16u1__p8_0,
  140856. 11,
  140857. 11
  140858. };
  140859. static static_codebook _16u1__p8_0 = {
  140860. 2, 121,
  140861. _vq_lengthlist__16u1__p8_0,
  140862. 1, -524582912, 1618345984, 4, 0,
  140863. _vq_quantlist__16u1__p8_0,
  140864. NULL,
  140865. &_vq_auxt__16u1__p8_0,
  140866. NULL,
  140867. 0
  140868. };
  140869. static long _vq_quantlist__16u1__p8_1[] = {
  140870. 5,
  140871. 4,
  140872. 6,
  140873. 3,
  140874. 7,
  140875. 2,
  140876. 8,
  140877. 1,
  140878. 9,
  140879. 0,
  140880. 10,
  140881. };
  140882. static long _vq_lengthlist__16u1__p8_1[] = {
  140883. 2, 5, 5, 6, 6, 7, 7, 8, 8, 8, 8, 4, 6, 6, 7, 7,
  140884. 8, 7, 8, 8, 8, 8, 4, 6, 6, 7, 7, 7, 7, 8, 8, 8,
  140885. 8, 6, 7, 7, 7, 7, 8, 8, 8, 8, 8, 9, 6, 7, 7, 7,
  140886. 7, 8, 8, 8, 8, 9, 9, 7, 7, 7, 8, 8, 8, 8, 9, 9,
  140887. 9, 9, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 8, 8, 8,
  140888. 8, 8, 9, 9, 9, 9, 9, 9, 8, 8, 8, 8, 8, 9, 9, 9,
  140889. 9, 9, 9, 8, 8, 8, 9, 8, 9, 9, 9, 9, 9, 9, 8, 8,
  140890. 8, 9, 9, 9, 9, 9, 9, 9, 9,
  140891. };
  140892. static float _vq_quantthresh__16u1__p8_1[] = {
  140893. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  140894. 3.5, 4.5,
  140895. };
  140896. static long _vq_quantmap__16u1__p8_1[] = {
  140897. 9, 7, 5, 3, 1, 0, 2, 4,
  140898. 6, 8, 10,
  140899. };
  140900. static encode_aux_threshmatch _vq_auxt__16u1__p8_1 = {
  140901. _vq_quantthresh__16u1__p8_1,
  140902. _vq_quantmap__16u1__p8_1,
  140903. 11,
  140904. 11
  140905. };
  140906. static static_codebook _16u1__p8_1 = {
  140907. 2, 121,
  140908. _vq_lengthlist__16u1__p8_1,
  140909. 1, -531365888, 1611661312, 4, 0,
  140910. _vq_quantlist__16u1__p8_1,
  140911. NULL,
  140912. &_vq_auxt__16u1__p8_1,
  140913. NULL,
  140914. 0
  140915. };
  140916. static long _vq_quantlist__16u1__p9_0[] = {
  140917. 7,
  140918. 6,
  140919. 8,
  140920. 5,
  140921. 9,
  140922. 4,
  140923. 10,
  140924. 3,
  140925. 11,
  140926. 2,
  140927. 12,
  140928. 1,
  140929. 13,
  140930. 0,
  140931. 14,
  140932. };
  140933. static long _vq_lengthlist__16u1__p9_0[] = {
  140934. 1, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  140935. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  140936. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  140937. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  140938. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  140939. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  140940. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  140941. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  140942. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  140943. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  140944. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  140945. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  140946. 9, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  140947. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  140948. 8,
  140949. };
  140950. static float _vq_quantthresh__16u1__p9_0[] = {
  140951. -1657.5, -1402.5, -1147.5, -892.5, -637.5, -382.5, -127.5, 127.5,
  140952. 382.5, 637.5, 892.5, 1147.5, 1402.5, 1657.5,
  140953. };
  140954. static long _vq_quantmap__16u1__p9_0[] = {
  140955. 13, 11, 9, 7, 5, 3, 1, 0,
  140956. 2, 4, 6, 8, 10, 12, 14,
  140957. };
  140958. static encode_aux_threshmatch _vq_auxt__16u1__p9_0 = {
  140959. _vq_quantthresh__16u1__p9_0,
  140960. _vq_quantmap__16u1__p9_0,
  140961. 15,
  140962. 15
  140963. };
  140964. static static_codebook _16u1__p9_0 = {
  140965. 2, 225,
  140966. _vq_lengthlist__16u1__p9_0,
  140967. 1, -514071552, 1627381760, 4, 0,
  140968. _vq_quantlist__16u1__p9_0,
  140969. NULL,
  140970. &_vq_auxt__16u1__p9_0,
  140971. NULL,
  140972. 0
  140973. };
  140974. static long _vq_quantlist__16u1__p9_1[] = {
  140975. 7,
  140976. 6,
  140977. 8,
  140978. 5,
  140979. 9,
  140980. 4,
  140981. 10,
  140982. 3,
  140983. 11,
  140984. 2,
  140985. 12,
  140986. 1,
  140987. 13,
  140988. 0,
  140989. 14,
  140990. };
  140991. static long _vq_lengthlist__16u1__p9_1[] = {
  140992. 1, 6, 5, 9, 9,10,10, 6, 7, 9, 9,10,10,10,10, 5,
  140993. 10, 8,10, 8,10,10, 8, 8,10, 9,10,10,10,10, 5, 8,
  140994. 9,10,10,10,10, 8,10,10,10,10,10,10,10, 9,10,10,
  140995. 10,10,10,10, 9, 9,10,10,10,10,10,10, 9, 9, 8, 9,
  140996. 10,10,10, 9,10,10,10,10,10,10,10,10,10,10,10,10,
  140997. 10,10,10,10,10,10,10,10,10,10,10, 8,10,10,10,10,
  140998. 10,10,10,10,10,10,10,10,10, 6, 8, 8,10,10,10, 8,
  140999. 10,10,10,10,10,10,10,10, 5, 8, 8,10,10,10, 9, 9,
  141000. 10,10,10,10,10,10,10,10, 9,10,10,10,10,10,10,10,
  141001. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  141002. 10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9,
  141003. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  141004. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  141005. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  141006. 9,
  141007. };
  141008. static float _vq_quantthresh__16u1__p9_1[] = {
  141009. -110.5, -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5,
  141010. 25.5, 42.5, 59.5, 76.5, 93.5, 110.5,
  141011. };
  141012. static long _vq_quantmap__16u1__p9_1[] = {
  141013. 13, 11, 9, 7, 5, 3, 1, 0,
  141014. 2, 4, 6, 8, 10, 12, 14,
  141015. };
  141016. static encode_aux_threshmatch _vq_auxt__16u1__p9_1 = {
  141017. _vq_quantthresh__16u1__p9_1,
  141018. _vq_quantmap__16u1__p9_1,
  141019. 15,
  141020. 15
  141021. };
  141022. static static_codebook _16u1__p9_1 = {
  141023. 2, 225,
  141024. _vq_lengthlist__16u1__p9_1,
  141025. 1, -522338304, 1620115456, 4, 0,
  141026. _vq_quantlist__16u1__p9_1,
  141027. NULL,
  141028. &_vq_auxt__16u1__p9_1,
  141029. NULL,
  141030. 0
  141031. };
  141032. static long _vq_quantlist__16u1__p9_2[] = {
  141033. 8,
  141034. 7,
  141035. 9,
  141036. 6,
  141037. 10,
  141038. 5,
  141039. 11,
  141040. 4,
  141041. 12,
  141042. 3,
  141043. 13,
  141044. 2,
  141045. 14,
  141046. 1,
  141047. 15,
  141048. 0,
  141049. 16,
  141050. };
  141051. static long _vq_lengthlist__16u1__p9_2[] = {
  141052. 1, 6, 6, 7, 8, 8,11,10, 9, 9,11, 9,10, 9,11,11,
  141053. 9, 6, 7, 6,11, 8,11, 9,10,10,11, 9,11,10,10,10,
  141054. 11, 9, 5, 7, 7, 8, 8,10,11, 8, 8,11, 9, 9,10,11,
  141055. 9,10,11, 8, 9, 6, 8, 8, 9, 9,10,10,11,11,11, 9,
  141056. 11,10, 9,11, 8, 8, 8, 9, 8, 9,10,11, 9, 9,11,11,
  141057. 10, 9, 9,11,10, 8,11, 8, 9, 8,11, 9,10, 9,10,11,
  141058. 11,10,10, 9,10,10, 8, 8, 9,10,10,10, 9,11, 9,10,
  141059. 11,11,11,11,10, 9,11, 9, 9,11,11,10, 8,11,11,11,
  141060. 9,10,10,11,10,11,11, 9,11,10, 9,11,10,10,10,10,
  141061. 9,11,10,11,10, 9, 9,10,11, 9, 8,10,11,11,10,10,
  141062. 11, 9,11,10,11,11,10,11, 9, 9, 8,10, 8, 9,11, 9,
  141063. 8,10,10, 9,11,10,11,10,11, 9,11, 8,10,11,11,11,
  141064. 11,10,10,11,11,11,11,10,11,11,10, 9, 8,10,10, 9,
  141065. 11,10,11,11,11, 9, 9, 9,11,11,11,10,10, 9, 9,10,
  141066. 9,11,11,11,11, 8,10,11,10,11,11,10,11,11, 9, 9,
  141067. 9,10, 9,11, 9,11,11,11,11,11,10,11,11,10,11,10,
  141068. 11,11, 9,11,10,11,10, 9,10, 9,10,10,11,11,11,11,
  141069. 9,10, 9,10,11,11,10,11,11,11,11,11,11,10,11,11,
  141070. 10,
  141071. };
  141072. static float _vq_quantthresh__16u1__p9_2[] = {
  141073. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  141074. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  141075. };
  141076. static long _vq_quantmap__16u1__p9_2[] = {
  141077. 15, 13, 11, 9, 7, 5, 3, 1,
  141078. 0, 2, 4, 6, 8, 10, 12, 14,
  141079. 16,
  141080. };
  141081. static encode_aux_threshmatch _vq_auxt__16u1__p9_2 = {
  141082. _vq_quantthresh__16u1__p9_2,
  141083. _vq_quantmap__16u1__p9_2,
  141084. 17,
  141085. 17
  141086. };
  141087. static static_codebook _16u1__p9_2 = {
  141088. 2, 289,
  141089. _vq_lengthlist__16u1__p9_2,
  141090. 1, -529530880, 1611661312, 5, 0,
  141091. _vq_quantlist__16u1__p9_2,
  141092. NULL,
  141093. &_vq_auxt__16u1__p9_2,
  141094. NULL,
  141095. 0
  141096. };
  141097. static long _huff_lengthlist__16u1__short[] = {
  141098. 5, 7,10, 9,11,10,15,11,13,16, 6, 4, 6, 6, 7, 7,
  141099. 10, 9,12,16,10, 6, 5, 6, 6, 7,10,11,16,16, 9, 6,
  141100. 7, 6, 7, 7,10, 8,14,16,11, 6, 5, 4, 5, 6, 8, 9,
  141101. 15,16, 9, 6, 6, 5, 6, 6, 9, 8,14,16,12, 7, 6, 6,
  141102. 5, 6, 6, 7,13,16, 8, 6, 7, 6, 5, 5, 4, 4,11,16,
  141103. 9, 8, 9, 9, 7, 7, 6, 5,13,16,14,14,16,15,16,15,
  141104. 16,16,16,16,
  141105. };
  141106. static static_codebook _huff_book__16u1__short = {
  141107. 2, 100,
  141108. _huff_lengthlist__16u1__short,
  141109. 0, 0, 0, 0, 0,
  141110. NULL,
  141111. NULL,
  141112. NULL,
  141113. NULL,
  141114. 0
  141115. };
  141116. static long _huff_lengthlist__16u2__long[] = {
  141117. 5, 7,10,10,10,11,11,13,18,19, 6, 5, 5, 6, 7, 8,
  141118. 9,12,19,19, 8, 5, 4, 4, 6, 7, 9,13,19,19, 8, 5,
  141119. 4, 4, 5, 6, 8,12,17,19, 7, 5, 5, 4, 4, 5, 7,12,
  141120. 18,18, 8, 7, 7, 6, 5, 5, 6,10,18,18, 9, 9, 9, 8,
  141121. 6, 5, 6, 9,18,18,11,13,13,13, 8, 7, 7, 9,16,18,
  141122. 13,17,18,16,11, 9, 9, 9,17,18,15,18,18,18,15,13,
  141123. 13,14,18,18,
  141124. };
  141125. static static_codebook _huff_book__16u2__long = {
  141126. 2, 100,
  141127. _huff_lengthlist__16u2__long,
  141128. 0, 0, 0, 0, 0,
  141129. NULL,
  141130. NULL,
  141131. NULL,
  141132. NULL,
  141133. 0
  141134. };
  141135. static long _huff_lengthlist__16u2__short[] = {
  141136. 8,11,12,12,14,15,16,16,16,16, 9, 7, 7, 8, 9,11,
  141137. 13,14,16,16,13, 7, 6, 6, 7, 9,12,13,15,16,15, 7,
  141138. 6, 5, 4, 6,10,11,14,16,12, 8, 7, 4, 2, 4, 7,10,
  141139. 14,16,11, 9, 7, 5, 3, 4, 6, 9,14,16,11,10, 9, 7,
  141140. 5, 5, 6, 9,16,16,10,10, 9, 8, 6, 6, 7,10,16,16,
  141141. 11,11,11,10,10,10,11,14,16,16,16,14,14,13,14,16,
  141142. 16,16,16,16,
  141143. };
  141144. static static_codebook _huff_book__16u2__short = {
  141145. 2, 100,
  141146. _huff_lengthlist__16u2__short,
  141147. 0, 0, 0, 0, 0,
  141148. NULL,
  141149. NULL,
  141150. NULL,
  141151. NULL,
  141152. 0
  141153. };
  141154. static long _vq_quantlist__16u2_p1_0[] = {
  141155. 1,
  141156. 0,
  141157. 2,
  141158. };
  141159. static long _vq_lengthlist__16u2_p1_0[] = {
  141160. 1, 5, 5, 5, 7, 7, 5, 7, 7, 5, 7, 7, 7, 9, 9, 7,
  141161. 9, 9, 5, 7, 7, 7, 9, 9, 7, 9, 9, 5, 7, 7, 8, 9,
  141162. 9, 7, 9, 9, 7, 9, 9, 9,10,10, 9,10,10, 7, 9, 9,
  141163. 9,10,10, 9,10,11, 5, 7, 8, 8, 9, 9, 8, 9, 9, 7,
  141164. 9, 9, 9,10,10, 9, 9,10, 7, 9, 9, 9,10,10, 9,11,
  141165. 10,
  141166. };
  141167. static float _vq_quantthresh__16u2_p1_0[] = {
  141168. -0.5, 0.5,
  141169. };
  141170. static long _vq_quantmap__16u2_p1_0[] = {
  141171. 1, 0, 2,
  141172. };
  141173. static encode_aux_threshmatch _vq_auxt__16u2_p1_0 = {
  141174. _vq_quantthresh__16u2_p1_0,
  141175. _vq_quantmap__16u2_p1_0,
  141176. 3,
  141177. 3
  141178. };
  141179. static static_codebook _16u2_p1_0 = {
  141180. 4, 81,
  141181. _vq_lengthlist__16u2_p1_0,
  141182. 1, -535822336, 1611661312, 2, 0,
  141183. _vq_quantlist__16u2_p1_0,
  141184. NULL,
  141185. &_vq_auxt__16u2_p1_0,
  141186. NULL,
  141187. 0
  141188. };
  141189. static long _vq_quantlist__16u2_p2_0[] = {
  141190. 2,
  141191. 1,
  141192. 3,
  141193. 0,
  141194. 4,
  141195. };
  141196. static long _vq_lengthlist__16u2_p2_0[] = {
  141197. 3, 5, 5, 8, 8, 5, 7, 7, 9, 9, 5, 7, 7, 9, 9, 9,
  141198. 10, 9,11,11, 9, 9, 9,11,11, 5, 7, 7, 9, 9, 7, 8,
  141199. 8,10,10, 7, 8, 8,10,10,10,10,10,12,12, 9,10,10,
  141200. 11,12, 5, 7, 7, 9, 9, 7, 8, 8,10,10, 7, 8, 8,10,
  141201. 10, 9,10,10,12,11,10,10,10,12,12, 9,10,10,12,12,
  141202. 10,11,10,13,12, 9,10,10,12,12,12,12,12,14,14,11,
  141203. 12,12,13,14, 9,10,10,12,12, 9,10,10,12,12,10,10,
  141204. 10,12,12,11,12,12,14,13,12,13,12,14,14, 5, 7, 7,
  141205. 9, 9, 7, 8, 8,10,10, 7, 8, 8,10,10,10,11,10,12,
  141206. 12,10,10,11,12,12, 7, 8, 8,10,10, 8, 9, 9,11,11,
  141207. 8, 9, 9,11,11,11,11,11,12,13,10,11,11,12,13, 7,
  141208. 8, 8,10,10, 8, 9, 8,11,10, 8, 9, 9,11,11,10,11,
  141209. 10,13,12,10,11,11,13,13, 9,11,10,13,13,10,11,11,
  141210. 13,13,10,11,11,13,13,12,12,13,13,15,12,12,13,14,
  141211. 15, 9,10,10,12,12,10,11,10,13,12,10,11,11,13,13,
  141212. 11,13,11,14,13,12,13,13,15,15, 5, 7, 7, 9, 9, 7,
  141213. 8, 8,10,10, 7, 8, 8,10,10,10,10,10,12,12,10,10,
  141214. 11,12,12, 7, 8, 8,10,10, 8, 9, 9,11,11, 8, 8, 9,
  141215. 10,11,10,11,11,13,13,10,10,11,12,13, 7, 8, 8,10,
  141216. 11, 8, 9, 9,11,11, 8, 9, 9,11,11,10,11,11,13,12,
  141217. 11,11,11,13,12, 9,10,10,12,12,10,11,11,13,13,10,
  141218. 10,11,12,13,12,13,13,15,14,11,11,13,12,14,10,10,
  141219. 11,13,13,10,11,11,13,13,10,11,11,13,13,12,13,13,
  141220. 14,14,12,13,12,14,13, 8,10, 9,12,12, 9,11,10,13,
  141221. 13, 9,10,10,12,13,12,13,13,14,14,12,12,13,14,14,
  141222. 9,11,10,13,13,10,11,11,13,13,10,11,11,13,13,12,
  141223. 13,13,15,15,13,13,13,14,15, 9,10,10,12,13,10,11,
  141224. 10,13,12,10,11,11,13,13,12,13,12,15,14,13,13,13,
  141225. 14,15,11,12,12,15,14,12,12,13,15,15,12,13,13,15,
  141226. 14,14,13,15,14,16,13,14,15,16,16,11,12,12,14,14,
  141227. 11,12,12,15,14,12,13,13,15,15,13,14,13,16,14,14,
  141228. 14,14,16,16, 8, 9, 9,12,12, 9,10,10,13,12, 9,10,
  141229. 10,13,13,12,12,12,14,14,12,12,13,15,15, 9,10,10,
  141230. 13,12,10,11,11,13,13,10,10,11,13,14,12,13,13,15,
  141231. 15,12,12,13,14,15, 9,10,10,13,13,10,11,11,13,13,
  141232. 10,11,11,13,13,12,13,13,14,14,13,14,13,15,14,11,
  141233. 12,12,14,14,12,13,13,15,14,11,12,12,14,15,14,14,
  141234. 14,16,15,13,12,14,14,16,11,12,13,14,15,12,13,13,
  141235. 14,16,12,13,12,15,14,13,15,14,16,16,14,15,13,16,
  141236. 13,
  141237. };
  141238. static float _vq_quantthresh__16u2_p2_0[] = {
  141239. -1.5, -0.5, 0.5, 1.5,
  141240. };
  141241. static long _vq_quantmap__16u2_p2_0[] = {
  141242. 3, 1, 0, 2, 4,
  141243. };
  141244. static encode_aux_threshmatch _vq_auxt__16u2_p2_0 = {
  141245. _vq_quantthresh__16u2_p2_0,
  141246. _vq_quantmap__16u2_p2_0,
  141247. 5,
  141248. 5
  141249. };
  141250. static static_codebook _16u2_p2_0 = {
  141251. 4, 625,
  141252. _vq_lengthlist__16u2_p2_0,
  141253. 1, -533725184, 1611661312, 3, 0,
  141254. _vq_quantlist__16u2_p2_0,
  141255. NULL,
  141256. &_vq_auxt__16u2_p2_0,
  141257. NULL,
  141258. 0
  141259. };
  141260. static long _vq_quantlist__16u2_p3_0[] = {
  141261. 4,
  141262. 3,
  141263. 5,
  141264. 2,
  141265. 6,
  141266. 1,
  141267. 7,
  141268. 0,
  141269. 8,
  141270. };
  141271. static long _vq_lengthlist__16u2_p3_0[] = {
  141272. 2, 4, 4, 6, 6, 7, 7, 9, 9, 4, 5, 5, 6, 6, 8, 7,
  141273. 9, 9, 4, 5, 5, 6, 6, 7, 8, 9, 9, 6, 6, 6, 7, 7,
  141274. 8, 8,10,10, 6, 6, 6, 7, 7, 8, 8, 9,10, 7, 8, 7,
  141275. 8, 8, 9, 9,10,10, 7, 8, 8, 8, 8, 9, 9,10,10, 9,
  141276. 9, 9,10, 9,10,10,11,11, 9, 9, 9,10,10,10,10,11,
  141277. 11,
  141278. };
  141279. static float _vq_quantthresh__16u2_p3_0[] = {
  141280. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  141281. };
  141282. static long _vq_quantmap__16u2_p3_0[] = {
  141283. 7, 5, 3, 1, 0, 2, 4, 6,
  141284. 8,
  141285. };
  141286. static encode_aux_threshmatch _vq_auxt__16u2_p3_0 = {
  141287. _vq_quantthresh__16u2_p3_0,
  141288. _vq_quantmap__16u2_p3_0,
  141289. 9,
  141290. 9
  141291. };
  141292. static static_codebook _16u2_p3_0 = {
  141293. 2, 81,
  141294. _vq_lengthlist__16u2_p3_0,
  141295. 1, -531628032, 1611661312, 4, 0,
  141296. _vq_quantlist__16u2_p3_0,
  141297. NULL,
  141298. &_vq_auxt__16u2_p3_0,
  141299. NULL,
  141300. 0
  141301. };
  141302. static long _vq_quantlist__16u2_p4_0[] = {
  141303. 8,
  141304. 7,
  141305. 9,
  141306. 6,
  141307. 10,
  141308. 5,
  141309. 11,
  141310. 4,
  141311. 12,
  141312. 3,
  141313. 13,
  141314. 2,
  141315. 14,
  141316. 1,
  141317. 15,
  141318. 0,
  141319. 16,
  141320. };
  141321. static long _vq_lengthlist__16u2_p4_0[] = {
  141322. 2, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10,11,11,11,
  141323. 11, 5, 5, 5, 7, 7, 8, 8, 9, 9, 9, 9,10,10,11,11,
  141324. 12,11, 5, 5, 5, 7, 7, 8, 8, 9, 9, 9, 9,10,10,11,
  141325. 11,12,12, 6, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  141326. 11,11,12,12, 6, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9,10,
  141327. 10,11,11,12,12, 7, 8, 8, 8, 8, 9, 9, 9, 9,10,10,
  141328. 11,11,12,12,12,12, 7, 8, 8, 8, 8, 9, 9, 9, 9,10,
  141329. 10,11,11,11,12,12,12, 9, 9, 9, 9, 9, 9,10,10,10,
  141330. 10,10,11,11,12,12,13,13, 8, 9, 9, 9, 9,10, 9,10,
  141331. 10,10,10,11,11,12,12,13,13, 9, 9, 9, 9, 9,10,10,
  141332. 10,10,11,11,11,12,12,12,13,13, 9, 9, 9, 9, 9,10,
  141333. 10,10,10,11,11,12,11,12,12,13,13,10,10,10,10,10,
  141334. 11,11,11,11,11,12,12,12,12,13,13,14,10,10,10,10,
  141335. 10,11,11,11,11,12,11,12,12,13,12,13,13,11,11,11,
  141336. 11,11,12,12,12,12,12,12,13,13,13,13,14,14,11,11,
  141337. 11,11,11,12,12,12,12,12,12,13,12,13,13,14,14,11,
  141338. 12,12,12,12,12,12,13,13,13,13,13,13,14,14,14,14,
  141339. 11,12,12,12,12,12,12,13,13,13,13,14,13,14,14,14,
  141340. 14,
  141341. };
  141342. static float _vq_quantthresh__16u2_p4_0[] = {
  141343. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  141344. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  141345. };
  141346. static long _vq_quantmap__16u2_p4_0[] = {
  141347. 15, 13, 11, 9, 7, 5, 3, 1,
  141348. 0, 2, 4, 6, 8, 10, 12, 14,
  141349. 16,
  141350. };
  141351. static encode_aux_threshmatch _vq_auxt__16u2_p4_0 = {
  141352. _vq_quantthresh__16u2_p4_0,
  141353. _vq_quantmap__16u2_p4_0,
  141354. 17,
  141355. 17
  141356. };
  141357. static static_codebook _16u2_p4_0 = {
  141358. 2, 289,
  141359. _vq_lengthlist__16u2_p4_0,
  141360. 1, -529530880, 1611661312, 5, 0,
  141361. _vq_quantlist__16u2_p4_0,
  141362. NULL,
  141363. &_vq_auxt__16u2_p4_0,
  141364. NULL,
  141365. 0
  141366. };
  141367. static long _vq_quantlist__16u2_p5_0[] = {
  141368. 1,
  141369. 0,
  141370. 2,
  141371. };
  141372. static long _vq_lengthlist__16u2_p5_0[] = {
  141373. 1, 4, 4, 5, 7, 7, 5, 7, 7, 5, 9, 8, 7,10, 9, 7,
  141374. 10, 9, 5, 8, 9, 7, 9,10, 7, 9,10, 4, 9, 9, 9,11,
  141375. 11, 8,11,11, 7,11,11,10,10,13,10,14,13, 7,11,11,
  141376. 10,13,11,10,13,14, 5, 9, 9, 8,11,11, 9,11,11, 7,
  141377. 11,11,10,14,13,10,12,14, 7,11,11,10,13,13,10,13,
  141378. 10,
  141379. };
  141380. static float _vq_quantthresh__16u2_p5_0[] = {
  141381. -5.5, 5.5,
  141382. };
  141383. static long _vq_quantmap__16u2_p5_0[] = {
  141384. 1, 0, 2,
  141385. };
  141386. static encode_aux_threshmatch _vq_auxt__16u2_p5_0 = {
  141387. _vq_quantthresh__16u2_p5_0,
  141388. _vq_quantmap__16u2_p5_0,
  141389. 3,
  141390. 3
  141391. };
  141392. static static_codebook _16u2_p5_0 = {
  141393. 4, 81,
  141394. _vq_lengthlist__16u2_p5_0,
  141395. 1, -529137664, 1618345984, 2, 0,
  141396. _vq_quantlist__16u2_p5_0,
  141397. NULL,
  141398. &_vq_auxt__16u2_p5_0,
  141399. NULL,
  141400. 0
  141401. };
  141402. static long _vq_quantlist__16u2_p5_1[] = {
  141403. 5,
  141404. 4,
  141405. 6,
  141406. 3,
  141407. 7,
  141408. 2,
  141409. 8,
  141410. 1,
  141411. 9,
  141412. 0,
  141413. 10,
  141414. };
  141415. static long _vq_lengthlist__16u2_p5_1[] = {
  141416. 2, 5, 5, 6, 6, 7, 7, 8, 8, 8, 8, 5, 5, 5, 7, 7,
  141417. 7, 7, 8, 8, 8, 8, 5, 5, 6, 7, 7, 7, 7, 8, 8, 8,
  141418. 8, 6, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 6, 7, 7, 7,
  141419. 7, 8, 8, 8, 8, 8, 8, 7, 7, 7, 8, 8, 8, 8, 9, 9,
  141420. 9, 9, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 8, 8, 8,
  141421. 8, 8, 9, 9, 9, 9, 9, 9, 8, 8, 8, 8, 8, 9, 9, 9,
  141422. 9, 9, 9, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 8, 8,
  141423. 8, 8, 8, 9, 9, 9, 9, 9, 9,
  141424. };
  141425. static float _vq_quantthresh__16u2_p5_1[] = {
  141426. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  141427. 3.5, 4.5,
  141428. };
  141429. static long _vq_quantmap__16u2_p5_1[] = {
  141430. 9, 7, 5, 3, 1, 0, 2, 4,
  141431. 6, 8, 10,
  141432. };
  141433. static encode_aux_threshmatch _vq_auxt__16u2_p5_1 = {
  141434. _vq_quantthresh__16u2_p5_1,
  141435. _vq_quantmap__16u2_p5_1,
  141436. 11,
  141437. 11
  141438. };
  141439. static static_codebook _16u2_p5_1 = {
  141440. 2, 121,
  141441. _vq_lengthlist__16u2_p5_1,
  141442. 1, -531365888, 1611661312, 4, 0,
  141443. _vq_quantlist__16u2_p5_1,
  141444. NULL,
  141445. &_vq_auxt__16u2_p5_1,
  141446. NULL,
  141447. 0
  141448. };
  141449. static long _vq_quantlist__16u2_p6_0[] = {
  141450. 6,
  141451. 5,
  141452. 7,
  141453. 4,
  141454. 8,
  141455. 3,
  141456. 9,
  141457. 2,
  141458. 10,
  141459. 1,
  141460. 11,
  141461. 0,
  141462. 12,
  141463. };
  141464. static long _vq_lengthlist__16u2_p6_0[] = {
  141465. 1, 4, 4, 7, 7, 8, 8, 8, 8, 9, 9,10,10, 4, 6, 6,
  141466. 8, 8, 9, 9, 9, 9,10,10,12,11, 4, 6, 6, 8, 8, 9,
  141467. 9, 9, 9,10,10,11,12, 7, 8, 8, 9, 9,10,10,10,10,
  141468. 12,12,13,12, 7, 8, 8, 9, 9,10,10,10,10,11,12,12,
  141469. 12, 8, 9, 9,10,10,11,11,11,11,12,12,13,13, 8, 9,
  141470. 9,10,10,11,11,11,11,12,13,13,13, 8, 9, 9,10,10,
  141471. 11,11,12,12,13,13,14,14, 8, 9, 9,10,10,11,11,12,
  141472. 12,13,13,14,14, 9,10,10,11,12,13,12,13,14,14,14,
  141473. 14,14, 9,10,10,11,12,12,13,13,13,14,14,14,14,10,
  141474. 11,11,12,12,13,13,14,14,15,15,15,15,10,11,11,12,
  141475. 12,13,13,14,14,14,14,15,15,
  141476. };
  141477. static float _vq_quantthresh__16u2_p6_0[] = {
  141478. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  141479. 12.5, 17.5, 22.5, 27.5,
  141480. };
  141481. static long _vq_quantmap__16u2_p6_0[] = {
  141482. 11, 9, 7, 5, 3, 1, 0, 2,
  141483. 4, 6, 8, 10, 12,
  141484. };
  141485. static encode_aux_threshmatch _vq_auxt__16u2_p6_0 = {
  141486. _vq_quantthresh__16u2_p6_0,
  141487. _vq_quantmap__16u2_p6_0,
  141488. 13,
  141489. 13
  141490. };
  141491. static static_codebook _16u2_p6_0 = {
  141492. 2, 169,
  141493. _vq_lengthlist__16u2_p6_0,
  141494. 1, -526516224, 1616117760, 4, 0,
  141495. _vq_quantlist__16u2_p6_0,
  141496. NULL,
  141497. &_vq_auxt__16u2_p6_0,
  141498. NULL,
  141499. 0
  141500. };
  141501. static long _vq_quantlist__16u2_p6_1[] = {
  141502. 2,
  141503. 1,
  141504. 3,
  141505. 0,
  141506. 4,
  141507. };
  141508. static long _vq_lengthlist__16u2_p6_1[] = {
  141509. 2, 4, 4, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5,
  141510. 5, 5, 6, 6, 5, 5, 5, 6, 6,
  141511. };
  141512. static float _vq_quantthresh__16u2_p6_1[] = {
  141513. -1.5, -0.5, 0.5, 1.5,
  141514. };
  141515. static long _vq_quantmap__16u2_p6_1[] = {
  141516. 3, 1, 0, 2, 4,
  141517. };
  141518. static encode_aux_threshmatch _vq_auxt__16u2_p6_1 = {
  141519. _vq_quantthresh__16u2_p6_1,
  141520. _vq_quantmap__16u2_p6_1,
  141521. 5,
  141522. 5
  141523. };
  141524. static static_codebook _16u2_p6_1 = {
  141525. 2, 25,
  141526. _vq_lengthlist__16u2_p6_1,
  141527. 1, -533725184, 1611661312, 3, 0,
  141528. _vq_quantlist__16u2_p6_1,
  141529. NULL,
  141530. &_vq_auxt__16u2_p6_1,
  141531. NULL,
  141532. 0
  141533. };
  141534. static long _vq_quantlist__16u2_p7_0[] = {
  141535. 6,
  141536. 5,
  141537. 7,
  141538. 4,
  141539. 8,
  141540. 3,
  141541. 9,
  141542. 2,
  141543. 10,
  141544. 1,
  141545. 11,
  141546. 0,
  141547. 12,
  141548. };
  141549. static long _vq_lengthlist__16u2_p7_0[] = {
  141550. 1, 4, 4, 7, 7, 7, 7, 8, 8, 9, 9,10,10, 4, 6, 6,
  141551. 9, 9, 9, 9, 9, 9,10,10,11,11, 4, 6, 6, 8, 9, 9,
  141552. 9, 9, 9,10,11,12,11, 7, 8, 9,10,10,10,10,11,10,
  141553. 11,12,12,13, 7, 9, 9,10,10,10,10,10,10,11,12,13,
  141554. 13, 7, 9, 8,10,10,11,11,11,12,12,13,13,14, 7, 9,
  141555. 9,10,10,11,11,11,12,13,13,13,13, 8, 9, 9,10,11,
  141556. 11,12,12,12,13,13,13,13, 8, 9, 9,10,11,11,11,12,
  141557. 12,13,13,14,14, 9,10,10,12,11,12,13,13,13,14,13,
  141558. 13,13, 9,10,10,11,11,12,12,13,14,13,13,14,13,10,
  141559. 11,11,12,13,14,14,14,15,14,14,14,14,10,11,11,12,
  141560. 12,13,13,13,14,14,14,15,14,
  141561. };
  141562. static float _vq_quantthresh__16u2_p7_0[] = {
  141563. -60.5, -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5,
  141564. 27.5, 38.5, 49.5, 60.5,
  141565. };
  141566. static long _vq_quantmap__16u2_p7_0[] = {
  141567. 11, 9, 7, 5, 3, 1, 0, 2,
  141568. 4, 6, 8, 10, 12,
  141569. };
  141570. static encode_aux_threshmatch _vq_auxt__16u2_p7_0 = {
  141571. _vq_quantthresh__16u2_p7_0,
  141572. _vq_quantmap__16u2_p7_0,
  141573. 13,
  141574. 13
  141575. };
  141576. static static_codebook _16u2_p7_0 = {
  141577. 2, 169,
  141578. _vq_lengthlist__16u2_p7_0,
  141579. 1, -523206656, 1618345984, 4, 0,
  141580. _vq_quantlist__16u2_p7_0,
  141581. NULL,
  141582. &_vq_auxt__16u2_p7_0,
  141583. NULL,
  141584. 0
  141585. };
  141586. static long _vq_quantlist__16u2_p7_1[] = {
  141587. 5,
  141588. 4,
  141589. 6,
  141590. 3,
  141591. 7,
  141592. 2,
  141593. 8,
  141594. 1,
  141595. 9,
  141596. 0,
  141597. 10,
  141598. };
  141599. static long _vq_lengthlist__16u2_p7_1[] = {
  141600. 3, 5, 5, 6, 6, 7, 7, 7, 7, 7, 7, 5, 6, 6, 7, 7,
  141601. 7, 7, 7, 7, 8, 8, 5, 6, 6, 6, 6, 7, 7, 7, 7, 8,
  141602. 8, 6, 6, 7, 7, 7, 8, 7, 8, 8, 8, 8, 6, 7, 7, 7,
  141603. 7, 7, 7, 8, 8, 8, 8, 7, 7, 7, 7, 7, 8, 8, 8, 8,
  141604. 8, 8, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 7, 7, 7,
  141605. 8, 8, 8, 8, 8, 8, 8, 8, 7, 7, 7, 8, 8, 8, 8, 8,
  141606. 8, 8, 8, 7, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 7, 8,
  141607. 8, 8, 8, 8, 8, 8, 8, 8, 8,
  141608. };
  141609. static float _vq_quantthresh__16u2_p7_1[] = {
  141610. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  141611. 3.5, 4.5,
  141612. };
  141613. static long _vq_quantmap__16u2_p7_1[] = {
  141614. 9, 7, 5, 3, 1, 0, 2, 4,
  141615. 6, 8, 10,
  141616. };
  141617. static encode_aux_threshmatch _vq_auxt__16u2_p7_1 = {
  141618. _vq_quantthresh__16u2_p7_1,
  141619. _vq_quantmap__16u2_p7_1,
  141620. 11,
  141621. 11
  141622. };
  141623. static static_codebook _16u2_p7_1 = {
  141624. 2, 121,
  141625. _vq_lengthlist__16u2_p7_1,
  141626. 1, -531365888, 1611661312, 4, 0,
  141627. _vq_quantlist__16u2_p7_1,
  141628. NULL,
  141629. &_vq_auxt__16u2_p7_1,
  141630. NULL,
  141631. 0
  141632. };
  141633. static long _vq_quantlist__16u2_p8_0[] = {
  141634. 7,
  141635. 6,
  141636. 8,
  141637. 5,
  141638. 9,
  141639. 4,
  141640. 10,
  141641. 3,
  141642. 11,
  141643. 2,
  141644. 12,
  141645. 1,
  141646. 13,
  141647. 0,
  141648. 14,
  141649. };
  141650. static long _vq_lengthlist__16u2_p8_0[] = {
  141651. 1, 5, 5, 7, 7, 8, 8, 7, 7, 8, 8,10, 9,11,11, 4,
  141652. 6, 6, 8, 8,10, 9, 9, 8, 9, 9,10,10,12,14, 4, 6,
  141653. 7, 8, 9, 9,10, 9, 8, 9, 9,10,12,12,11, 7, 8, 8,
  141654. 10,10,10,10, 9, 9,10,10,11,13,13,12, 7, 8, 8, 9,
  141655. 11,11,10, 9, 9,11,10,12,11,11,14, 8, 9, 9,11,10,
  141656. 11,11,10,10,11,11,13,12,14,12, 8, 9, 9,11,12,11,
  141657. 11,10,10,12,11,12,12,12,14, 7, 8, 8, 9, 9,10,10,
  141658. 10,11,12,11,13,13,14,12, 7, 8, 9, 9, 9,10,10,11,
  141659. 11,11,12,12,14,14,14, 8,10, 9,10,11,11,11,11,14,
  141660. 12,12,13,14,14,13, 9, 9, 9,10,11,11,11,12,12,12,
  141661. 14,12,14,13,14,10,10,10,12,11,12,11,14,13,14,13,
  141662. 14,14,13,14, 9,10,10,11,12,11,13,12,13,13,14,14,
  141663. 14,13,14,10,13,13,12,12,11,12,14,13,14,13,14,12,
  141664. 14,13,10,11,11,12,11,12,12,14,14,14,13,14,14,14,
  141665. 14,
  141666. };
  141667. static float _vq_quantthresh__16u2_p8_0[] = {
  141668. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  141669. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  141670. };
  141671. static long _vq_quantmap__16u2_p8_0[] = {
  141672. 13, 11, 9, 7, 5, 3, 1, 0,
  141673. 2, 4, 6, 8, 10, 12, 14,
  141674. };
  141675. static encode_aux_threshmatch _vq_auxt__16u2_p8_0 = {
  141676. _vq_quantthresh__16u2_p8_0,
  141677. _vq_quantmap__16u2_p8_0,
  141678. 15,
  141679. 15
  141680. };
  141681. static static_codebook _16u2_p8_0 = {
  141682. 2, 225,
  141683. _vq_lengthlist__16u2_p8_0,
  141684. 1, -520986624, 1620377600, 4, 0,
  141685. _vq_quantlist__16u2_p8_0,
  141686. NULL,
  141687. &_vq_auxt__16u2_p8_0,
  141688. NULL,
  141689. 0
  141690. };
  141691. static long _vq_quantlist__16u2_p8_1[] = {
  141692. 10,
  141693. 9,
  141694. 11,
  141695. 8,
  141696. 12,
  141697. 7,
  141698. 13,
  141699. 6,
  141700. 14,
  141701. 5,
  141702. 15,
  141703. 4,
  141704. 16,
  141705. 3,
  141706. 17,
  141707. 2,
  141708. 18,
  141709. 1,
  141710. 19,
  141711. 0,
  141712. 20,
  141713. };
  141714. static long _vq_lengthlist__16u2_p8_1[] = {
  141715. 2, 5, 5, 7, 7, 8, 8, 8, 8, 9, 9,10, 9,10, 9, 9,
  141716. 9,10,10,10,10, 5, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9,
  141717. 10, 9,10,10,10,10,10,10,11,10, 5, 6, 6, 7, 7, 8,
  141718. 8, 8, 9, 9,10,10,10,10,10,10,10,10,10,10,10, 7,
  141719. 7, 7, 8, 8, 9, 8, 9, 9,10, 9,10,10,10,10,10,10,
  141720. 11,10,11,10, 7, 7, 7, 8, 8, 8, 9, 9, 9,10, 9,10,
  141721. 10,10,10,10,10,10,10,10,10, 8, 8, 8, 9, 9, 9, 9,
  141722. 10, 9,10,10,10,10,10,10,10,11,10,10,11,10, 8, 8,
  141723. 8, 8, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,11,
  141724. 11,10,10, 8, 9, 9, 9, 9, 9, 9,10,10,10,10,10,10,
  141725. 11,10,11,10,11,10,11,10, 8, 9, 9, 9, 9, 9,10,10,
  141726. 10,10,10,10,10,10,10,10,11,11,10,10,10, 9,10, 9,
  141727. 9,10,10,10,11,10,10,10,10,10,10,10,10,11,11,11,
  141728. 11,11, 9, 9, 9,10, 9,10,10,10,10,10,10,11,10,11,
  141729. 10,11,11,11,11,10,10, 9,10, 9,10,10,10,10,11,10,
  141730. 10,10,10,10,11,10,11,10,11,10,10,11, 9,10,10,10,
  141731. 10,10,10,10,10,10,11,10,10,11,11,10,11,11,11,11,
  141732. 11, 9, 9,10,10,10,10,10,11,10,10,11,10,10,11,10,
  141733. 10,11,11,11,11,11, 9,10,10,10,10,10,10,10,11,10,
  141734. 11,10,11,10,11,11,11,11,11,10,11,10,10,10,10,10,
  141735. 10,10,10,10,11,11,11,11,11,11,11,11,11,10,11,11,
  141736. 10,10,10,10,10,11,10,10,10,11,10,11,11,11,11,10,
  141737. 12,11,11,11,10,10,10,10,10,10,11,10,10,10,11,11,
  141738. 12,11,11,11,11,11,11,11,11,11,10,10,10,11,10,11,
  141739. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,10,
  141740. 10,10,11,10,11,10,10,11,11,11,11,11,11,11,11,11,
  141741. 11,11,11,10,10,10,10,10,10,10,11,11,10,11,11,10,
  141742. 11,11,10,11,11,11,10,11,11,
  141743. };
  141744. static float _vq_quantthresh__16u2_p8_1[] = {
  141745. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  141746. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  141747. 6.5, 7.5, 8.5, 9.5,
  141748. };
  141749. static long _vq_quantmap__16u2_p8_1[] = {
  141750. 19, 17, 15, 13, 11, 9, 7, 5,
  141751. 3, 1, 0, 2, 4, 6, 8, 10,
  141752. 12, 14, 16, 18, 20,
  141753. };
  141754. static encode_aux_threshmatch _vq_auxt__16u2_p8_1 = {
  141755. _vq_quantthresh__16u2_p8_1,
  141756. _vq_quantmap__16u2_p8_1,
  141757. 21,
  141758. 21
  141759. };
  141760. static static_codebook _16u2_p8_1 = {
  141761. 2, 441,
  141762. _vq_lengthlist__16u2_p8_1,
  141763. 1, -529268736, 1611661312, 5, 0,
  141764. _vq_quantlist__16u2_p8_1,
  141765. NULL,
  141766. &_vq_auxt__16u2_p8_1,
  141767. NULL,
  141768. 0
  141769. };
  141770. static long _vq_quantlist__16u2_p9_0[] = {
  141771. 5586,
  141772. 4655,
  141773. 6517,
  141774. 3724,
  141775. 7448,
  141776. 2793,
  141777. 8379,
  141778. 1862,
  141779. 9310,
  141780. 931,
  141781. 10241,
  141782. 0,
  141783. 11172,
  141784. 5521,
  141785. 5651,
  141786. };
  141787. static long _vq_lengthlist__16u2_p9_0[] = {
  141788. 1,10,10,10,10,10,10,10,10,10,10,10,10, 5, 4,10,
  141789. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  141790. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  141791. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  141792. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  141793. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  141794. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  141795. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  141796. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  141797. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  141798. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  141799. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  141800. 10,10,10, 4,10,10,10,10,10,10,10,10,10,10,10,10,
  141801. 6, 6, 5,10,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9, 5,
  141802. 5,
  141803. };
  141804. static float _vq_quantthresh__16u2_p9_0[] = {
  141805. -5120.5, -4189.5, -3258.5, -2327.5, -1396.5, -498, -32.5, 32.5,
  141806. 498, 1396.5, 2327.5, 3258.5, 4189.5, 5120.5,
  141807. };
  141808. static long _vq_quantmap__16u2_p9_0[] = {
  141809. 11, 9, 7, 5, 3, 1, 13, 0,
  141810. 14, 2, 4, 6, 8, 10, 12,
  141811. };
  141812. static encode_aux_threshmatch _vq_auxt__16u2_p9_0 = {
  141813. _vq_quantthresh__16u2_p9_0,
  141814. _vq_quantmap__16u2_p9_0,
  141815. 15,
  141816. 15
  141817. };
  141818. static static_codebook _16u2_p9_0 = {
  141819. 2, 225,
  141820. _vq_lengthlist__16u2_p9_0,
  141821. 1, -510275072, 1611661312, 14, 0,
  141822. _vq_quantlist__16u2_p9_0,
  141823. NULL,
  141824. &_vq_auxt__16u2_p9_0,
  141825. NULL,
  141826. 0
  141827. };
  141828. static long _vq_quantlist__16u2_p9_1[] = {
  141829. 392,
  141830. 343,
  141831. 441,
  141832. 294,
  141833. 490,
  141834. 245,
  141835. 539,
  141836. 196,
  141837. 588,
  141838. 147,
  141839. 637,
  141840. 98,
  141841. 686,
  141842. 49,
  141843. 735,
  141844. 0,
  141845. 784,
  141846. 388,
  141847. 396,
  141848. };
  141849. static long _vq_lengthlist__16u2_p9_1[] = {
  141850. 1,12,10,12,10,12,10,12,11,12,12,12,12,12,12,12,
  141851. 12, 5, 5, 9,10,12,11,11,12,12,12,12,12,12,12,12,
  141852. 12,12,12,12,10, 9, 9,11, 9,11,11,12,11,12,12,12,
  141853. 12,12,12,12,12,12,12, 8, 8,10,11, 9,12,11,12,12,
  141854. 12,12,12,12,12,12,12,12,12,12, 9, 8,10,11,12,11,
  141855. 12,11,12,12,12,12,12,12,12,12,12,12,12, 8, 9,11,
  141856. 11,10,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  141857. 9,10,11,12,11,12,11,12,12,12,12,12,12,12,12,12,
  141858. 12,12,12, 9, 9,11,12,12,12,12,12,12,12,12,12,12,
  141859. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  141860. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  141861. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  141862. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  141863. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  141864. 12,12,12,12,11,11,11,11,11,11,11,11,11,11,11,11,
  141865. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  141866. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  141867. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  141868. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  141869. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  141870. 11,11,11, 5, 8, 9, 9, 8,11, 9,11,11,11,11,11,11,
  141871. 11,11,11,11, 5, 5, 4, 8, 8, 8, 8,10, 9,10,10,11,
  141872. 11,11,11,11,11,11,11, 5, 4,
  141873. };
  141874. static float _vq_quantthresh__16u2_p9_1[] = {
  141875. -367.5, -318.5, -269.5, -220.5, -171.5, -122.5, -73.5, -26.5,
  141876. -2, 2, 26.5, 73.5, 122.5, 171.5, 220.5, 269.5,
  141877. 318.5, 367.5,
  141878. };
  141879. static long _vq_quantmap__16u2_p9_1[] = {
  141880. 15, 13, 11, 9, 7, 5, 3, 1,
  141881. 17, 0, 18, 2, 4, 6, 8, 10,
  141882. 12, 14, 16,
  141883. };
  141884. static encode_aux_threshmatch _vq_auxt__16u2_p9_1 = {
  141885. _vq_quantthresh__16u2_p9_1,
  141886. _vq_quantmap__16u2_p9_1,
  141887. 19,
  141888. 19
  141889. };
  141890. static static_codebook _16u2_p9_1 = {
  141891. 2, 361,
  141892. _vq_lengthlist__16u2_p9_1,
  141893. 1, -518488064, 1611661312, 10, 0,
  141894. _vq_quantlist__16u2_p9_1,
  141895. NULL,
  141896. &_vq_auxt__16u2_p9_1,
  141897. NULL,
  141898. 0
  141899. };
  141900. static long _vq_quantlist__16u2_p9_2[] = {
  141901. 24,
  141902. 23,
  141903. 25,
  141904. 22,
  141905. 26,
  141906. 21,
  141907. 27,
  141908. 20,
  141909. 28,
  141910. 19,
  141911. 29,
  141912. 18,
  141913. 30,
  141914. 17,
  141915. 31,
  141916. 16,
  141917. 32,
  141918. 15,
  141919. 33,
  141920. 14,
  141921. 34,
  141922. 13,
  141923. 35,
  141924. 12,
  141925. 36,
  141926. 11,
  141927. 37,
  141928. 10,
  141929. 38,
  141930. 9,
  141931. 39,
  141932. 8,
  141933. 40,
  141934. 7,
  141935. 41,
  141936. 6,
  141937. 42,
  141938. 5,
  141939. 43,
  141940. 4,
  141941. 44,
  141942. 3,
  141943. 45,
  141944. 2,
  141945. 46,
  141946. 1,
  141947. 47,
  141948. 0,
  141949. 48,
  141950. };
  141951. static long _vq_lengthlist__16u2_p9_2[] = {
  141952. 1, 3, 3, 4, 7, 7, 7, 8, 7, 7, 7, 7, 8, 8, 8, 8,
  141953. 7, 8, 8, 8, 8, 8, 8, 8, 8, 8, 7, 9, 9, 8, 9, 9,
  141954. 9, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,12,12,10,
  141955. 11,
  141956. };
  141957. static float _vq_quantthresh__16u2_p9_2[] = {
  141958. -23.5, -22.5, -21.5, -20.5, -19.5, -18.5, -17.5, -16.5,
  141959. -15.5, -14.5, -13.5, -12.5, -11.5, -10.5, -9.5, -8.5,
  141960. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  141961. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  141962. 8.5, 9.5, 10.5, 11.5, 12.5, 13.5, 14.5, 15.5,
  141963. 16.5, 17.5, 18.5, 19.5, 20.5, 21.5, 22.5, 23.5,
  141964. };
  141965. static long _vq_quantmap__16u2_p9_2[] = {
  141966. 47, 45, 43, 41, 39, 37, 35, 33,
  141967. 31, 29, 27, 25, 23, 21, 19, 17,
  141968. 15, 13, 11, 9, 7, 5, 3, 1,
  141969. 0, 2, 4, 6, 8, 10, 12, 14,
  141970. 16, 18, 20, 22, 24, 26, 28, 30,
  141971. 32, 34, 36, 38, 40, 42, 44, 46,
  141972. 48,
  141973. };
  141974. static encode_aux_threshmatch _vq_auxt__16u2_p9_2 = {
  141975. _vq_quantthresh__16u2_p9_2,
  141976. _vq_quantmap__16u2_p9_2,
  141977. 49,
  141978. 49
  141979. };
  141980. static static_codebook _16u2_p9_2 = {
  141981. 1, 49,
  141982. _vq_lengthlist__16u2_p9_2,
  141983. 1, -526909440, 1611661312, 6, 0,
  141984. _vq_quantlist__16u2_p9_2,
  141985. NULL,
  141986. &_vq_auxt__16u2_p9_2,
  141987. NULL,
  141988. 0
  141989. };
  141990. static long _vq_quantlist__8u0__p1_0[] = {
  141991. 1,
  141992. 0,
  141993. 2,
  141994. };
  141995. static long _vq_lengthlist__8u0__p1_0[] = {
  141996. 1, 4, 4, 5, 7, 7, 5, 7, 7, 5, 8, 8, 8,10,10, 7,
  141997. 10,10, 5, 8, 8, 7,10,10, 8,10,10, 4, 9, 8, 8,11,
  141998. 11, 8,11,11, 7,11,11,10,11,13,10,13,13, 7,11,11,
  141999. 10,13,12,10,13,13, 5, 9, 8, 8,11,11, 8,11,11, 7,
  142000. 11,11, 9,13,13,10,12,13, 7,11,11,10,13,13,10,13,
  142001. 11,
  142002. };
  142003. static float _vq_quantthresh__8u0__p1_0[] = {
  142004. -0.5, 0.5,
  142005. };
  142006. static long _vq_quantmap__8u0__p1_0[] = {
  142007. 1, 0, 2,
  142008. };
  142009. static encode_aux_threshmatch _vq_auxt__8u0__p1_0 = {
  142010. _vq_quantthresh__8u0__p1_0,
  142011. _vq_quantmap__8u0__p1_0,
  142012. 3,
  142013. 3
  142014. };
  142015. static static_codebook _8u0__p1_0 = {
  142016. 4, 81,
  142017. _vq_lengthlist__8u0__p1_0,
  142018. 1, -535822336, 1611661312, 2, 0,
  142019. _vq_quantlist__8u0__p1_0,
  142020. NULL,
  142021. &_vq_auxt__8u0__p1_0,
  142022. NULL,
  142023. 0
  142024. };
  142025. static long _vq_quantlist__8u0__p2_0[] = {
  142026. 1,
  142027. 0,
  142028. 2,
  142029. };
  142030. static long _vq_lengthlist__8u0__p2_0[] = {
  142031. 2, 4, 4, 5, 6, 6, 5, 6, 6, 5, 7, 7, 6, 7, 8, 6,
  142032. 7, 8, 5, 7, 7, 6, 8, 8, 7, 9, 7, 5, 7, 7, 7, 9,
  142033. 9, 7, 8, 8, 6, 9, 8, 7, 7,10, 8,10,10, 6, 8, 8,
  142034. 8,10, 8, 8,10,10, 5, 7, 7, 7, 8, 8, 7, 8, 9, 6,
  142035. 8, 8, 8,10,10, 8, 8,10, 6, 8, 9, 8,10,10, 7,10,
  142036. 8,
  142037. };
  142038. static float _vq_quantthresh__8u0__p2_0[] = {
  142039. -0.5, 0.5,
  142040. };
  142041. static long _vq_quantmap__8u0__p2_0[] = {
  142042. 1, 0, 2,
  142043. };
  142044. static encode_aux_threshmatch _vq_auxt__8u0__p2_0 = {
  142045. _vq_quantthresh__8u0__p2_0,
  142046. _vq_quantmap__8u0__p2_0,
  142047. 3,
  142048. 3
  142049. };
  142050. static static_codebook _8u0__p2_0 = {
  142051. 4, 81,
  142052. _vq_lengthlist__8u0__p2_0,
  142053. 1, -535822336, 1611661312, 2, 0,
  142054. _vq_quantlist__8u0__p2_0,
  142055. NULL,
  142056. &_vq_auxt__8u0__p2_0,
  142057. NULL,
  142058. 0
  142059. };
  142060. static long _vq_quantlist__8u0__p3_0[] = {
  142061. 2,
  142062. 1,
  142063. 3,
  142064. 0,
  142065. 4,
  142066. };
  142067. static long _vq_lengthlist__8u0__p3_0[] = {
  142068. 1, 5, 5, 7, 7, 6, 7, 7, 9, 9, 6, 7, 7, 9, 9, 8,
  142069. 10, 9,11,11, 8, 9, 9,11,11, 6, 8, 8,10,10, 8,10,
  142070. 10,11,11, 8,10,10,11,11,10,11,11,12,12,10,11,11,
  142071. 12,13, 6, 8, 8,10,10, 8,10,10,11,11, 8,10,10,11,
  142072. 11, 9,10,11,12,12,10,11,11,12,12, 8,11,11,14,13,
  142073. 10,12,11,15,13,10,12,11,14,14,12,13,12,16,14,12,
  142074. 14,12,16,15, 8,11,11,13,14,10,11,12,13,15,10,11,
  142075. 12,13,15,11,12,13,14,15,12,12,14,14,16, 5, 8, 8,
  142076. 11,11, 9,11,11,12,12, 8,10,11,12,12,11,12,12,15,
  142077. 14,11,12,12,14,14, 7,11,10,13,12,10,11,12,13,14,
  142078. 10,12,12,14,13,12,13,13,14,15,12,13,13,15,15, 7,
  142079. 10,11,12,13,10,12,11,14,13,10,12,13,13,15,12,13,
  142080. 12,14,14,11,13,13,15,16, 9,12,12,15,14,11,13,13,
  142081. 15,16,11,13,13,16,16,13,14,15,15,15,12,14,15,17,
  142082. 16, 9,12,12,14,15,11,13,13,15,16,11,13,13,16,18,
  142083. 13,14,14,17,16,13,15,15,17,18, 5, 8, 9,11,11, 8,
  142084. 11,11,12,12, 8,10,11,12,12,11,12,12,14,14,11,12,
  142085. 12,14,15, 7,11,10,12,13,10,12,12,14,13,10,11,12,
  142086. 13,14,11,13,13,15,14,12,13,13,14,15, 7,10,11,13,
  142087. 13,10,12,12,13,14,10,12,12,13,13,11,13,13,16,16,
  142088. 12,13,13,15,14, 9,12,12,16,15,10,13,13,15,15,11,
  142089. 13,13,17,15,12,15,15,18,17,13,14,14,15,16, 9,12,
  142090. 12,15,15,11,13,13,15,16,11,13,13,15,15,12,15,15,
  142091. 16,16,13,15,14,17,15, 7,11,11,15,15,10,13,13,16,
  142092. 15,10,13,13,15,16,14,15,15,17,19,13,15,14,15,18,
  142093. 9,12,12,16,16,11,13,14,17,16,11,13,13,17,16,15,
  142094. 15,16,17,19,13,15,16, 0,18, 9,12,12,16,15,11,14,
  142095. 13,17,17,11,13,14,16,16,15,16,16,19,18,13,15,15,
  142096. 17,19,11,14,14,19,16,12,14,15, 0,18,12,16,15,18,
  142097. 17,15,15,18,16,19,14,15,17,19,19,11,14,14,18,19,
  142098. 13,15,14,19,19,12,16,15,18,17,15,17,15, 0,16,14,
  142099. 17,16,19, 0, 7,11,11,14,14,10,12,12,15,15,10,13,
  142100. 13,16,15,13,15,15,17, 0,14,15,15,16,19, 9,12,12,
  142101. 16,16,11,14,14,16,16,11,13,13,16,16,14,17,16,19,
  142102. 0,14,18,17,17,19, 9,12,12,15,16,11,13,13,15,17,
  142103. 12,14,13,19,16,13,15,15,17,19,15,17,16,17,19,11,
  142104. 14,14,19,16,12,15,15,19,17,13,14,15,17,19,14,16,
  142105. 17,19,19,16,15,16,17,19,11,15,14,16,16,12,15,15,
  142106. 19, 0,12,14,15,19,19,14,16,16, 0,18,15,19,14,18,
  142107. 16,
  142108. };
  142109. static float _vq_quantthresh__8u0__p3_0[] = {
  142110. -1.5, -0.5, 0.5, 1.5,
  142111. };
  142112. static long _vq_quantmap__8u0__p3_0[] = {
  142113. 3, 1, 0, 2, 4,
  142114. };
  142115. static encode_aux_threshmatch _vq_auxt__8u0__p3_0 = {
  142116. _vq_quantthresh__8u0__p3_0,
  142117. _vq_quantmap__8u0__p3_0,
  142118. 5,
  142119. 5
  142120. };
  142121. static static_codebook _8u0__p3_0 = {
  142122. 4, 625,
  142123. _vq_lengthlist__8u0__p3_0,
  142124. 1, -533725184, 1611661312, 3, 0,
  142125. _vq_quantlist__8u0__p3_0,
  142126. NULL,
  142127. &_vq_auxt__8u0__p3_0,
  142128. NULL,
  142129. 0
  142130. };
  142131. static long _vq_quantlist__8u0__p4_0[] = {
  142132. 2,
  142133. 1,
  142134. 3,
  142135. 0,
  142136. 4,
  142137. };
  142138. static long _vq_lengthlist__8u0__p4_0[] = {
  142139. 3, 5, 5, 8, 8, 5, 6, 7, 9, 9, 6, 7, 6, 9, 9, 9,
  142140. 9, 9,10,11, 9, 9, 9,11,10, 6, 7, 7,10,10, 7, 7,
  142141. 8,10,10, 7, 8, 8,10,10,10,10,10,10,11, 9,10,10,
  142142. 11,12, 6, 7, 7,10,10, 7, 8, 8,10,10, 7, 8, 7,10,
  142143. 10, 9,10,10,12,11,10,10,10,11,10, 9,10,10,12,11,
  142144. 10,10,10,13,11, 9,10,10,12,12,11,11,12,12,13,11,
  142145. 11,11,12,13, 9,10,10,12,12,10,10,11,12,12,10,10,
  142146. 11,12,12,11,11,11,13,13,11,12,12,13,13, 5, 7, 7,
  142147. 10,10, 7, 8, 8,10,10, 7, 8, 8,10,10,10,11,11,12,
  142148. 12,10,11,10,12,12, 7, 8, 8,11,11, 7, 8, 9,10,11,
  142149. 8, 9, 9,11,11,11,10,11,10,12,10,11,11,12,13, 7,
  142150. 8, 8,10,11, 8, 9, 8,12,10, 8, 9, 9,11,12,10,11,
  142151. 10,13,11,10,11,11,13,12, 9,11,10,13,12,10,10,11,
  142152. 12,12,10,11,11,13,13,12,10,13,11,14,11,12,12,15,
  142153. 13, 9,11,11,13,13,10,11,11,13,12,10,11,11,12,14,
  142154. 12,13,11,14,12,12,12,12,14,14, 5, 7, 7,10,10, 7,
  142155. 8, 8,10,10, 7, 8, 8,11,10,10,11,11,12,12,10,11,
  142156. 10,12,12, 7, 8, 8,10,11, 8, 9, 9,12,11, 8, 8, 9,
  142157. 10,11,10,11,11,12,13,11,10,11,11,13, 6, 8, 8,10,
  142158. 11, 8, 9, 9,11,11, 7, 9, 7,11,10,10,11,11,12,12,
  142159. 10,11,10,13,10, 9,11,10,13,12,10,12,11,13,13,10,
  142160. 10,11,12,13,11,12,13,15,14,11,11,13,12,13, 9,10,
  142161. 11,12,13,10,11,11,12,13,10,11,10,13,12,12,13,13,
  142162. 13,14,12,12,11,14,11, 8,10,10,12,13,10,11,11,13,
  142163. 13,10,11,10,13,13,12,13,14,15,14,12,12,12,14,13,
  142164. 9,10,10,13,12,10,10,12,13,13,10,11,11,15,12,12,
  142165. 12,13,15,14,12,13,13,15,13, 9,10,11,12,13,10,12,
  142166. 10,13,12,10,11,11,12,13,12,14,12,15,13,12,12,12,
  142167. 15,14,11,12,11,14,13,11,11,12,14,14,12,13,13,14,
  142168. 13,13,11,15,11,15,14,14,14,16,15,11,12,12,13,14,
  142169. 11,13,11,14,14,12,12,13,14,15,12,14,12,15,12,13,
  142170. 15,14,16,15, 8,10,10,12,12,10,10,10,12,13,10,11,
  142171. 11,13,13,12,12,12,13,14,13,13,13,15,15, 9,10,10,
  142172. 12,12,10,11,11,13,12,10,10,11,13,13,12,12,12,14,
  142173. 14,12,12,13,15,14, 9,10,10,13,12,10,10,12,12,13,
  142174. 10,11,10,13,13,12,13,13,14,14,12,13,12,14,13,11,
  142175. 12,12,14,13,12,13,12,14,14,10,12,12,14,14,14,14,
  142176. 14,16,14,13,12,14,12,15,10,12,12,14,15,12,13,13,
  142177. 14,16,11,12,11,15,14,13,14,14,14,15,13,14,11,14,
  142178. 12,
  142179. };
  142180. static float _vq_quantthresh__8u0__p4_0[] = {
  142181. -1.5, -0.5, 0.5, 1.5,
  142182. };
  142183. static long _vq_quantmap__8u0__p4_0[] = {
  142184. 3, 1, 0, 2, 4,
  142185. };
  142186. static encode_aux_threshmatch _vq_auxt__8u0__p4_0 = {
  142187. _vq_quantthresh__8u0__p4_0,
  142188. _vq_quantmap__8u0__p4_0,
  142189. 5,
  142190. 5
  142191. };
  142192. static static_codebook _8u0__p4_0 = {
  142193. 4, 625,
  142194. _vq_lengthlist__8u0__p4_0,
  142195. 1, -533725184, 1611661312, 3, 0,
  142196. _vq_quantlist__8u0__p4_0,
  142197. NULL,
  142198. &_vq_auxt__8u0__p4_0,
  142199. NULL,
  142200. 0
  142201. };
  142202. static long _vq_quantlist__8u0__p5_0[] = {
  142203. 4,
  142204. 3,
  142205. 5,
  142206. 2,
  142207. 6,
  142208. 1,
  142209. 7,
  142210. 0,
  142211. 8,
  142212. };
  142213. static long _vq_lengthlist__8u0__p5_0[] = {
  142214. 1, 4, 4, 7, 7, 7, 7, 9, 9, 4, 6, 6, 8, 7, 8, 8,
  142215. 10,10, 4, 6, 6, 8, 8, 8, 8,10,10, 6, 8, 8, 9, 9,
  142216. 9, 9,11,11, 7, 8, 8, 9, 9, 9, 9,11,11, 7, 8, 8,
  142217. 9, 9,10,10,12,11, 7, 8, 8, 9, 9,10,10,11,11, 9,
  142218. 10,10,11,11,11,12,12,12, 9,10,10,11,11,12,12,12,
  142219. 12,
  142220. };
  142221. static float _vq_quantthresh__8u0__p5_0[] = {
  142222. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  142223. };
  142224. static long _vq_quantmap__8u0__p5_0[] = {
  142225. 7, 5, 3, 1, 0, 2, 4, 6,
  142226. 8,
  142227. };
  142228. static encode_aux_threshmatch _vq_auxt__8u0__p5_0 = {
  142229. _vq_quantthresh__8u0__p5_0,
  142230. _vq_quantmap__8u0__p5_0,
  142231. 9,
  142232. 9
  142233. };
  142234. static static_codebook _8u0__p5_0 = {
  142235. 2, 81,
  142236. _vq_lengthlist__8u0__p5_0,
  142237. 1, -531628032, 1611661312, 4, 0,
  142238. _vq_quantlist__8u0__p5_0,
  142239. NULL,
  142240. &_vq_auxt__8u0__p5_0,
  142241. NULL,
  142242. 0
  142243. };
  142244. static long _vq_quantlist__8u0__p6_0[] = {
  142245. 6,
  142246. 5,
  142247. 7,
  142248. 4,
  142249. 8,
  142250. 3,
  142251. 9,
  142252. 2,
  142253. 10,
  142254. 1,
  142255. 11,
  142256. 0,
  142257. 12,
  142258. };
  142259. static long _vq_lengthlist__8u0__p6_0[] = {
  142260. 1, 4, 4, 7, 7, 9, 9,11,11,12,12,16,16, 3, 6, 6,
  142261. 9, 9,11,11,12,12,13,14,18,16, 3, 6, 7, 9, 9,11,
  142262. 11,13,12,14,14,17,16, 7, 9, 9,11,11,12,12,14,14,
  142263. 14,14,17,16, 7, 9, 9,11,11,13,12,13,13,14,14,17,
  142264. 0, 9,11,11,12,13,14,14,14,13,15,14,17,17, 9,11,
  142265. 11,12,12,14,14,13,14,14,15, 0, 0,11,12,12,15,14,
  142266. 15,14,15,14,15,16,17, 0,11,12,13,13,13,14,14,15,
  142267. 14,15,15, 0, 0,12,14,14,15,15,14,16,15,15,17,16,
  142268. 0,18,13,14,14,15,14,15,14,15,16,17,16, 0, 0,17,
  142269. 17,18, 0,16,18,16, 0, 0, 0,17, 0, 0,16, 0, 0,16,
  142270. 16, 0,15, 0,17, 0, 0, 0, 0,
  142271. };
  142272. static float _vq_quantthresh__8u0__p6_0[] = {
  142273. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  142274. 12.5, 17.5, 22.5, 27.5,
  142275. };
  142276. static long _vq_quantmap__8u0__p6_0[] = {
  142277. 11, 9, 7, 5, 3, 1, 0, 2,
  142278. 4, 6, 8, 10, 12,
  142279. };
  142280. static encode_aux_threshmatch _vq_auxt__8u0__p6_0 = {
  142281. _vq_quantthresh__8u0__p6_0,
  142282. _vq_quantmap__8u0__p6_0,
  142283. 13,
  142284. 13
  142285. };
  142286. static static_codebook _8u0__p6_0 = {
  142287. 2, 169,
  142288. _vq_lengthlist__8u0__p6_0,
  142289. 1, -526516224, 1616117760, 4, 0,
  142290. _vq_quantlist__8u0__p6_0,
  142291. NULL,
  142292. &_vq_auxt__8u0__p6_0,
  142293. NULL,
  142294. 0
  142295. };
  142296. static long _vq_quantlist__8u0__p6_1[] = {
  142297. 2,
  142298. 1,
  142299. 3,
  142300. 0,
  142301. 4,
  142302. };
  142303. static long _vq_lengthlist__8u0__p6_1[] = {
  142304. 1, 4, 4, 6, 6, 4, 6, 5, 7, 7, 4, 5, 6, 7, 7, 6,
  142305. 7, 7, 7, 7, 6, 7, 7, 7, 7,
  142306. };
  142307. static float _vq_quantthresh__8u0__p6_1[] = {
  142308. -1.5, -0.5, 0.5, 1.5,
  142309. };
  142310. static long _vq_quantmap__8u0__p6_1[] = {
  142311. 3, 1, 0, 2, 4,
  142312. };
  142313. static encode_aux_threshmatch _vq_auxt__8u0__p6_1 = {
  142314. _vq_quantthresh__8u0__p6_1,
  142315. _vq_quantmap__8u0__p6_1,
  142316. 5,
  142317. 5
  142318. };
  142319. static static_codebook _8u0__p6_1 = {
  142320. 2, 25,
  142321. _vq_lengthlist__8u0__p6_1,
  142322. 1, -533725184, 1611661312, 3, 0,
  142323. _vq_quantlist__8u0__p6_1,
  142324. NULL,
  142325. &_vq_auxt__8u0__p6_1,
  142326. NULL,
  142327. 0
  142328. };
  142329. static long _vq_quantlist__8u0__p7_0[] = {
  142330. 1,
  142331. 0,
  142332. 2,
  142333. };
  142334. static long _vq_lengthlist__8u0__p7_0[] = {
  142335. 1, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  142336. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  142337. 8, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  142338. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  142339. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  142340. 7,
  142341. };
  142342. static float _vq_quantthresh__8u0__p7_0[] = {
  142343. -157.5, 157.5,
  142344. };
  142345. static long _vq_quantmap__8u0__p7_0[] = {
  142346. 1, 0, 2,
  142347. };
  142348. static encode_aux_threshmatch _vq_auxt__8u0__p7_0 = {
  142349. _vq_quantthresh__8u0__p7_0,
  142350. _vq_quantmap__8u0__p7_0,
  142351. 3,
  142352. 3
  142353. };
  142354. static static_codebook _8u0__p7_0 = {
  142355. 4, 81,
  142356. _vq_lengthlist__8u0__p7_0,
  142357. 1, -518803456, 1628680192, 2, 0,
  142358. _vq_quantlist__8u0__p7_0,
  142359. NULL,
  142360. &_vq_auxt__8u0__p7_0,
  142361. NULL,
  142362. 0
  142363. };
  142364. static long _vq_quantlist__8u0__p7_1[] = {
  142365. 7,
  142366. 6,
  142367. 8,
  142368. 5,
  142369. 9,
  142370. 4,
  142371. 10,
  142372. 3,
  142373. 11,
  142374. 2,
  142375. 12,
  142376. 1,
  142377. 13,
  142378. 0,
  142379. 14,
  142380. };
  142381. static long _vq_lengthlist__8u0__p7_1[] = {
  142382. 1, 5, 5, 5, 5,10,10,11,11,11,11,11,11,11,11, 5,
  142383. 7, 6, 8, 8, 9,10,11,11,11,11,11,11,11,11, 6, 6,
  142384. 7, 9, 7,11,10,11,11,11,11,11,11,11,11, 5, 6, 6,
  142385. 11, 8,11,11,11,11,11,11,11,11,11,11, 5, 6, 6, 9,
  142386. 10,11,10,11,11,11,11,11,11,11,11, 7,10,10,11,11,
  142387. 11,11,11,11,11,11,11,11,11,11, 7,11, 8,11,11,11,
  142388. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  142389. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  142390. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  142391. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  142392. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  142393. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  142394. 11,11,11,11,11,11,11,11,11,11,11,10,10,10,10,10,
  142395. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  142396. 10,
  142397. };
  142398. static float _vq_quantthresh__8u0__p7_1[] = {
  142399. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  142400. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  142401. };
  142402. static long _vq_quantmap__8u0__p7_1[] = {
  142403. 13, 11, 9, 7, 5, 3, 1, 0,
  142404. 2, 4, 6, 8, 10, 12, 14,
  142405. };
  142406. static encode_aux_threshmatch _vq_auxt__8u0__p7_1 = {
  142407. _vq_quantthresh__8u0__p7_1,
  142408. _vq_quantmap__8u0__p7_1,
  142409. 15,
  142410. 15
  142411. };
  142412. static static_codebook _8u0__p7_1 = {
  142413. 2, 225,
  142414. _vq_lengthlist__8u0__p7_1,
  142415. 1, -520986624, 1620377600, 4, 0,
  142416. _vq_quantlist__8u0__p7_1,
  142417. NULL,
  142418. &_vq_auxt__8u0__p7_1,
  142419. NULL,
  142420. 0
  142421. };
  142422. static long _vq_quantlist__8u0__p7_2[] = {
  142423. 10,
  142424. 9,
  142425. 11,
  142426. 8,
  142427. 12,
  142428. 7,
  142429. 13,
  142430. 6,
  142431. 14,
  142432. 5,
  142433. 15,
  142434. 4,
  142435. 16,
  142436. 3,
  142437. 17,
  142438. 2,
  142439. 18,
  142440. 1,
  142441. 19,
  142442. 0,
  142443. 20,
  142444. };
  142445. static long _vq_lengthlist__8u0__p7_2[] = {
  142446. 1, 6, 5, 7, 7, 9, 9, 9, 9,10,12,12,10,11,11,10,
  142447. 11,11,11,10,11, 6, 8, 8, 9, 9,10,10, 9,10,11,11,
  142448. 10,11,11,11,11,10,11,11,11,11, 6, 7, 8, 9, 9, 9,
  142449. 10,11,10,11,12,11,10,11,11,11,11,11,11,12,10, 8,
  142450. 9, 9,10, 9,10,10, 9,10,10,10,10,10, 9,10,10,10,
  142451. 10, 9,10,10, 9, 9, 9, 9,10,10, 9, 9,10,10,11,10,
  142452. 9,12,10,11,10, 9,10,10,10, 8, 9, 9,10, 9,10, 9,
  142453. 9,10,10, 9,10, 9,11,10,10,10,10,10, 9,10, 8, 8,
  142454. 9, 9,10, 9,11, 9, 8, 9, 9,10,11,10,10,10,11,12,
  142455. 9, 9,11, 8, 9, 8,11,10,11,10,10, 9,11,10,10,10,
  142456. 10,10,10,10,11,11,11,11, 8, 9, 9, 9,10,10,10,11,
  142457. 11,12,11,12,11,10,10,10,12,11,11,11,10, 8,10, 9,
  142458. 11,10,10,11,12,10,11,12,11,11,12,11,12,12,10,11,
  142459. 11,10, 9, 9,10,11,12,10,10,10,11,10,11,11,10,12,
  142460. 12,10,11,10,11,12,10, 9,10,10,11,10,11,11,11,11,
  142461. 11,12,11,11,11, 9,11,10,11,10,11,10, 9, 9,10,11,
  142462. 11,11,10,10,11,12,12,11,12,11,11,11,12,12,12,12,
  142463. 11, 9,11,11,12,10,11,11,11,11,11,11,12,11,11,12,
  142464. 11,11,11,10,11,11, 9,11,10,11,11,11,10,10,10,11,
  142465. 11,11,12,10,11,10,11,11,11,11,12, 9,11,10,11,11,
  142466. 10,10,11,11, 9,11,11,12,10,10,10,10,10,11,11,10,
  142467. 9,10,11,11,12,11,10,10,12,11,11,12,11,12,11,11,
  142468. 10,10,11,11,10,12,11,10,11,10,11,10,10,10,11,11,
  142469. 10,10,11,11,11,11,10,10,10,12,11,11,11,11,10, 9,
  142470. 10,11,11,11,12,11,11,11,12,10,11,11,11, 9,10,11,
  142471. 11,11,11,11,11,10,10,11,11,12,11,10,11,12,11,10,
  142472. 10,11, 9,10,11,11,11,11,11,10,11,11,10,12,11,11,
  142473. 11,12,11,11,11,10,10,11,11,
  142474. };
  142475. static float _vq_quantthresh__8u0__p7_2[] = {
  142476. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  142477. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  142478. 6.5, 7.5, 8.5, 9.5,
  142479. };
  142480. static long _vq_quantmap__8u0__p7_2[] = {
  142481. 19, 17, 15, 13, 11, 9, 7, 5,
  142482. 3, 1, 0, 2, 4, 6, 8, 10,
  142483. 12, 14, 16, 18, 20,
  142484. };
  142485. static encode_aux_threshmatch _vq_auxt__8u0__p7_2 = {
  142486. _vq_quantthresh__8u0__p7_2,
  142487. _vq_quantmap__8u0__p7_2,
  142488. 21,
  142489. 21
  142490. };
  142491. static static_codebook _8u0__p7_2 = {
  142492. 2, 441,
  142493. _vq_lengthlist__8u0__p7_2,
  142494. 1, -529268736, 1611661312, 5, 0,
  142495. _vq_quantlist__8u0__p7_2,
  142496. NULL,
  142497. &_vq_auxt__8u0__p7_2,
  142498. NULL,
  142499. 0
  142500. };
  142501. static long _huff_lengthlist__8u0__single[] = {
  142502. 4, 7,11, 9,12, 8, 7,10, 6, 4, 5, 5, 7, 5, 6,16,
  142503. 9, 5, 5, 6, 7, 7, 9,16, 7, 4, 6, 5, 7, 5, 7,17,
  142504. 10, 7, 7, 8, 7, 7, 8,18, 7, 5, 6, 4, 5, 4, 5,15,
  142505. 7, 6, 7, 5, 6, 4, 5,15,12,13,18,12,17,11, 9,17,
  142506. };
  142507. static static_codebook _huff_book__8u0__single = {
  142508. 2, 64,
  142509. _huff_lengthlist__8u0__single,
  142510. 0, 0, 0, 0, 0,
  142511. NULL,
  142512. NULL,
  142513. NULL,
  142514. NULL,
  142515. 0
  142516. };
  142517. static long _vq_quantlist__8u1__p1_0[] = {
  142518. 1,
  142519. 0,
  142520. 2,
  142521. };
  142522. static long _vq_lengthlist__8u1__p1_0[] = {
  142523. 1, 4, 4, 5, 7, 7, 5, 7, 7, 5, 8, 8, 7, 9,10, 7,
  142524. 9, 9, 5, 8, 8, 7,10, 9, 7, 9, 9, 5, 8, 8, 8,10,
  142525. 10, 8,10,10, 7,10,10, 9,10,12,10,12,12, 7,10,10,
  142526. 9,12,11,10,12,12, 5, 8, 8, 8,10,10, 8,10,10, 7,
  142527. 10,10,10,12,12, 9,11,12, 7,10,10,10,12,12, 9,12,
  142528. 10,
  142529. };
  142530. static float _vq_quantthresh__8u1__p1_0[] = {
  142531. -0.5, 0.5,
  142532. };
  142533. static long _vq_quantmap__8u1__p1_0[] = {
  142534. 1, 0, 2,
  142535. };
  142536. static encode_aux_threshmatch _vq_auxt__8u1__p1_0 = {
  142537. _vq_quantthresh__8u1__p1_0,
  142538. _vq_quantmap__8u1__p1_0,
  142539. 3,
  142540. 3
  142541. };
  142542. static static_codebook _8u1__p1_0 = {
  142543. 4, 81,
  142544. _vq_lengthlist__8u1__p1_0,
  142545. 1, -535822336, 1611661312, 2, 0,
  142546. _vq_quantlist__8u1__p1_0,
  142547. NULL,
  142548. &_vq_auxt__8u1__p1_0,
  142549. NULL,
  142550. 0
  142551. };
  142552. static long _vq_quantlist__8u1__p2_0[] = {
  142553. 1,
  142554. 0,
  142555. 2,
  142556. };
  142557. static long _vq_lengthlist__8u1__p2_0[] = {
  142558. 3, 4, 5, 5, 6, 6, 5, 6, 6, 5, 7, 6, 6, 7, 8, 6,
  142559. 7, 8, 5, 6, 6, 6, 8, 7, 6, 8, 7, 5, 6, 6, 7, 8,
  142560. 8, 6, 7, 7, 6, 8, 7, 7, 7, 9, 8, 9, 9, 6, 7, 8,
  142561. 7, 9, 7, 8, 9, 9, 5, 6, 6, 6, 7, 7, 7, 8, 8, 6,
  142562. 8, 7, 8, 9, 9, 7, 7, 9, 6, 7, 8, 8, 9, 9, 7, 9,
  142563. 7,
  142564. };
  142565. static float _vq_quantthresh__8u1__p2_0[] = {
  142566. -0.5, 0.5,
  142567. };
  142568. static long _vq_quantmap__8u1__p2_0[] = {
  142569. 1, 0, 2,
  142570. };
  142571. static encode_aux_threshmatch _vq_auxt__8u1__p2_0 = {
  142572. _vq_quantthresh__8u1__p2_0,
  142573. _vq_quantmap__8u1__p2_0,
  142574. 3,
  142575. 3
  142576. };
  142577. static static_codebook _8u1__p2_0 = {
  142578. 4, 81,
  142579. _vq_lengthlist__8u1__p2_0,
  142580. 1, -535822336, 1611661312, 2, 0,
  142581. _vq_quantlist__8u1__p2_0,
  142582. NULL,
  142583. &_vq_auxt__8u1__p2_0,
  142584. NULL,
  142585. 0
  142586. };
  142587. static long _vq_quantlist__8u1__p3_0[] = {
  142588. 2,
  142589. 1,
  142590. 3,
  142591. 0,
  142592. 4,
  142593. };
  142594. static long _vq_lengthlist__8u1__p3_0[] = {
  142595. 1, 5, 5, 7, 7, 6, 7, 7, 9, 9, 6, 7, 7, 9, 9, 8,
  142596. 10, 9,11,11, 9, 9, 9,11,11, 6, 8, 8,10,10, 8,10,
  142597. 10,11,11, 8, 9,10,11,11,10,11,11,12,12,10,11,11,
  142598. 12,13, 6, 8, 8,10,10, 8,10, 9,11,11, 8,10, 9,11,
  142599. 11,10,11,11,12,12,10,11,11,12,12, 9,11,11,14,13,
  142600. 10,12,11,14,14,10,12,11,14,13,12,13,13,15,14,12,
  142601. 13,13,15,14, 8,11,11,13,14,10,11,12,13,15,10,11,
  142602. 12,14,14,12,13,13,14,15,12,13,13,14,15, 5, 8, 8,
  142603. 11,11, 8,10,10,12,12, 8,10,10,12,12,11,12,12,14,
  142604. 13,11,12,12,13,14, 8,10,10,12,12, 9,11,12,13,14,
  142605. 10,12,12,13,13,12,12,13,14,14,11,13,13,15,15, 7,
  142606. 10,10,12,12, 9,12,11,14,12,10,11,12,13,14,12,13,
  142607. 12,14,14,12,13,13,15,16,10,12,12,15,14,11,12,13,
  142608. 15,15,11,13,13,15,16,14,14,15,15,16,13,14,15,17,
  142609. 15, 9,12,12,14,15,11,13,12,15,15,11,13,13,15,15,
  142610. 13,14,13,15,14,13,14,14,17, 0, 5, 8, 8,11,11, 8,
  142611. 10,10,12,12, 8,10,10,12,12,11,12,12,14,14,11,12,
  142612. 12,14,14, 7,10,10,12,12,10,12,12,13,13, 9,11,12,
  142613. 12,13,11,12,13,15,15,11,12,13,14,15, 8,10,10,12,
  142614. 12,10,12,11,13,13,10,12,11,13,13,11,13,13,15,14,
  142615. 12,13,12,15,13, 9,12,12,14,14,11,13,13,16,15,11,
  142616. 12,13,16,15,13,14,15,16,16,13,13,15,15,16,10,12,
  142617. 12,15,14,11,13,13,14,16,11,13,13,15,16,13,15,15,
  142618. 16,17,13,15,14,16,15, 8,11,11,14,15,10,12,12,15,
  142619. 15,10,12,12,15,16,14,15,15,16,17,13,14,14,16,16,
  142620. 9,12,12,15,15,11,13,14,15,17,11,13,13,15,16,14,
  142621. 15,16,19,17,13,15,15, 0,17, 9,12,12,15,15,11,14,
  142622. 13,16,15,11,13,13,15,16,15,15,15,18,17,13,15,15,
  142623. 17,17,11,15,14,18,16,12,14,15,17,17,12,15,15,18,
  142624. 18,15,15,16,15,19,14,16,16, 0, 0,11,14,14,16,17,
  142625. 12,15,14,18,17,12,15,15,18,18,15,17,15,18,16,14,
  142626. 16,16,18,18, 7,11,11,14,14,10,12,12,15,15,10,12,
  142627. 13,15,15,13,14,15,16,16,14,15,15,18,18, 9,12,12,
  142628. 15,15,11,13,13,16,15,11,12,13,16,16,14,15,15,17,
  142629. 16,15,16,16,17,17, 9,12,12,15,15,11,13,13,15,17,
  142630. 11,14,13,16,15,13,15,15,17,17,15,15,15,18,17,11,
  142631. 14,14,17,15,12,14,15,17,18,13,13,15,17,17,14,16,
  142632. 16,19,18,16,15,17,17, 0,11,14,14,17,17,12,15,15,
  142633. 18, 0,12,15,14,18,16,14,17,17,19, 0,16,18,15, 0,
  142634. 16,
  142635. };
  142636. static float _vq_quantthresh__8u1__p3_0[] = {
  142637. -1.5, -0.5, 0.5, 1.5,
  142638. };
  142639. static long _vq_quantmap__8u1__p3_0[] = {
  142640. 3, 1, 0, 2, 4,
  142641. };
  142642. static encode_aux_threshmatch _vq_auxt__8u1__p3_0 = {
  142643. _vq_quantthresh__8u1__p3_0,
  142644. _vq_quantmap__8u1__p3_0,
  142645. 5,
  142646. 5
  142647. };
  142648. static static_codebook _8u1__p3_0 = {
  142649. 4, 625,
  142650. _vq_lengthlist__8u1__p3_0,
  142651. 1, -533725184, 1611661312, 3, 0,
  142652. _vq_quantlist__8u1__p3_0,
  142653. NULL,
  142654. &_vq_auxt__8u1__p3_0,
  142655. NULL,
  142656. 0
  142657. };
  142658. static long _vq_quantlist__8u1__p4_0[] = {
  142659. 2,
  142660. 1,
  142661. 3,
  142662. 0,
  142663. 4,
  142664. };
  142665. static long _vq_lengthlist__8u1__p4_0[] = {
  142666. 4, 5, 5, 9, 9, 6, 7, 7, 9, 9, 6, 7, 7, 9, 9, 9,
  142667. 9, 9,11,11, 9, 9, 9,11,11, 6, 7, 7, 9, 9, 7, 7,
  142668. 8, 9,10, 7, 7, 8, 9,10, 9, 9,10,10,11, 9, 9,10,
  142669. 10,12, 6, 7, 7, 9, 9, 7, 8, 7,10, 9, 7, 8, 7,10,
  142670. 9, 9,10, 9,12,11,10,10, 9,12,10, 9,10,10,12,11,
  142671. 9,10,10,12,11, 9,10,10,12,12,11,11,12,12,13,11,
  142672. 11,12,12,13, 9, 9,10,12,11, 9,10,10,12,12,10,10,
  142673. 10,12,12,11,12,11,13,12,11,12,11,13,12, 6, 7, 7,
  142674. 9, 9, 7, 8, 8,10,10, 7, 8, 7,10, 9,10,10,10,12,
  142675. 12,10,10,10,12,11, 7, 8, 7,10,10, 7, 7, 9,10,11,
  142676. 8, 9, 9,11,10,10,10,11,10,12,10,10,11,12,12, 7,
  142677. 8, 8,10,10, 7, 9, 8,11,10, 8, 8, 9,11,11,10,11,
  142678. 10,12,11,10,11,11,12,12, 9,10,10,12,12, 9,10,10,
  142679. 12,12,10,11,11,13,12,11,10,12,10,14,12,12,12,13,
  142680. 14, 9,10,10,12,12, 9,11,10,12,12,10,11,11,12,12,
  142681. 11,12,11,14,12,12,12,12,14,14, 5, 7, 7, 9, 9, 7,
  142682. 7, 7, 9,10, 7, 8, 8,10,10,10,10,10,11,11,10,10,
  142683. 10,12,12, 7, 8, 8,10,10, 8, 9, 8,11,10, 7, 8, 9,
  142684. 10,11,10,10,10,11,12,10,10,11,11,13, 6, 7, 8,10,
  142685. 10, 8, 9, 9,10,10, 7, 9, 7,11,10,10,11,10,12,12,
  142686. 10,11,10,12,10, 9,10,10,12,12,10,11,11,13,12, 9,
  142687. 10,10,12,12,12,12,12,14,13,11,11,12,11,14, 9,10,
  142688. 10,11,12,10,11,11,12,13, 9,10,10,12,12,12,12,12,
  142689. 14,13,11,12,10,14,11, 9, 9,10,11,12, 9,10,10,12,
  142690. 12, 9,10,10,12,12,12,12,12,14,14,11,12,12,13,12,
  142691. 9,10, 9,12,12, 9,10,11,12,13,10,11,10,13,11,12,
  142692. 12,13,13,14,12,12,12,13,13, 9,10,10,12,12,10,11,
  142693. 10,13,12,10,10,11,12,13,12,13,12,14,13,12,12,12,
  142694. 13,14,11,12,11,14,13,10,10,11,13,13,12,12,12,14,
  142695. 13,12,10,14,10,15,13,14,14,14,14,11,11,12,13,14,
  142696. 10,12,11,13,13,12,12,12,13,15,12,13,11,15,12,13,
  142697. 13,14,14,14, 9,10, 9,12,12, 9,10,10,12,12,10,10,
  142698. 10,12,12,11,11,12,12,13,12,12,12,14,14, 9,10,10,
  142699. 12,12,10,11,10,13,12,10,10,11,12,13,12,12,12,14,
  142700. 13,12,12,13,13,14, 9,10,10,12,13,10,10,11,11,12,
  142701. 9,11,10,13,12,12,12,12,13,14,12,13,12,14,13,11,
  142702. 12,11,13,13,12,13,12,14,13,10,11,12,13,13,13,13,
  142703. 13,14,15,12,11,14,12,14,11,11,12,12,13,12,12,12,
  142704. 13,14,10,12,10,14,13,13,13,13,14,15,12,14,11,15,
  142705. 10,
  142706. };
  142707. static float _vq_quantthresh__8u1__p4_0[] = {
  142708. -1.5, -0.5, 0.5, 1.5,
  142709. };
  142710. static long _vq_quantmap__8u1__p4_0[] = {
  142711. 3, 1, 0, 2, 4,
  142712. };
  142713. static encode_aux_threshmatch _vq_auxt__8u1__p4_0 = {
  142714. _vq_quantthresh__8u1__p4_0,
  142715. _vq_quantmap__8u1__p4_0,
  142716. 5,
  142717. 5
  142718. };
  142719. static static_codebook _8u1__p4_0 = {
  142720. 4, 625,
  142721. _vq_lengthlist__8u1__p4_0,
  142722. 1, -533725184, 1611661312, 3, 0,
  142723. _vq_quantlist__8u1__p4_0,
  142724. NULL,
  142725. &_vq_auxt__8u1__p4_0,
  142726. NULL,
  142727. 0
  142728. };
  142729. static long _vq_quantlist__8u1__p5_0[] = {
  142730. 4,
  142731. 3,
  142732. 5,
  142733. 2,
  142734. 6,
  142735. 1,
  142736. 7,
  142737. 0,
  142738. 8,
  142739. };
  142740. static long _vq_lengthlist__8u1__p5_0[] = {
  142741. 1, 4, 4, 7, 7, 7, 7, 9, 9, 4, 6, 5, 8, 7, 8, 8,
  142742. 10,10, 4, 6, 6, 8, 8, 8, 8,10,10, 7, 8, 8, 9, 9,
  142743. 9, 9,11,11, 7, 8, 8, 9, 9, 9, 9,11,11, 8, 8, 8,
  142744. 9, 9,10,10,12,11, 8, 8, 8, 9, 9,10,10,11,11, 9,
  142745. 10,10,11,11,11,11,13,12, 9,10,10,11,11,12,12,12,
  142746. 13,
  142747. };
  142748. static float _vq_quantthresh__8u1__p5_0[] = {
  142749. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  142750. };
  142751. static long _vq_quantmap__8u1__p5_0[] = {
  142752. 7, 5, 3, 1, 0, 2, 4, 6,
  142753. 8,
  142754. };
  142755. static encode_aux_threshmatch _vq_auxt__8u1__p5_0 = {
  142756. _vq_quantthresh__8u1__p5_0,
  142757. _vq_quantmap__8u1__p5_0,
  142758. 9,
  142759. 9
  142760. };
  142761. static static_codebook _8u1__p5_0 = {
  142762. 2, 81,
  142763. _vq_lengthlist__8u1__p5_0,
  142764. 1, -531628032, 1611661312, 4, 0,
  142765. _vq_quantlist__8u1__p5_0,
  142766. NULL,
  142767. &_vq_auxt__8u1__p5_0,
  142768. NULL,
  142769. 0
  142770. };
  142771. static long _vq_quantlist__8u1__p6_0[] = {
  142772. 4,
  142773. 3,
  142774. 5,
  142775. 2,
  142776. 6,
  142777. 1,
  142778. 7,
  142779. 0,
  142780. 8,
  142781. };
  142782. static long _vq_lengthlist__8u1__p6_0[] = {
  142783. 3, 4, 4, 6, 6, 7, 7, 9, 9, 4, 4, 5, 6, 6, 7, 7,
  142784. 9, 9, 4, 4, 4, 6, 6, 7, 7, 9, 9, 6, 6, 6, 7, 7,
  142785. 8, 8, 9, 9, 6, 6, 6, 7, 7, 8, 8, 9, 9, 7, 7, 7,
  142786. 8, 8, 8, 9,10,10, 7, 7, 7, 8, 8, 9, 8,10,10, 9,
  142787. 9, 9, 9, 9,10,10,10,10, 9, 9, 9, 9, 9,10,10,10,
  142788. 10,
  142789. };
  142790. static float _vq_quantthresh__8u1__p6_0[] = {
  142791. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  142792. };
  142793. static long _vq_quantmap__8u1__p6_0[] = {
  142794. 7, 5, 3, 1, 0, 2, 4, 6,
  142795. 8,
  142796. };
  142797. static encode_aux_threshmatch _vq_auxt__8u1__p6_0 = {
  142798. _vq_quantthresh__8u1__p6_0,
  142799. _vq_quantmap__8u1__p6_0,
  142800. 9,
  142801. 9
  142802. };
  142803. static static_codebook _8u1__p6_0 = {
  142804. 2, 81,
  142805. _vq_lengthlist__8u1__p6_0,
  142806. 1, -531628032, 1611661312, 4, 0,
  142807. _vq_quantlist__8u1__p6_0,
  142808. NULL,
  142809. &_vq_auxt__8u1__p6_0,
  142810. NULL,
  142811. 0
  142812. };
  142813. static long _vq_quantlist__8u1__p7_0[] = {
  142814. 1,
  142815. 0,
  142816. 2,
  142817. };
  142818. static long _vq_lengthlist__8u1__p7_0[] = {
  142819. 1, 4, 4, 5, 7, 7, 5, 7, 7, 5, 9, 9, 8,10,10, 8,
  142820. 10,10, 5, 9, 9, 7,10,10, 8,10,10, 4,10,10, 9,12,
  142821. 12, 9,11,11, 7,12,11,10,11,13,10,13,13, 7,12,12,
  142822. 10,13,12,10,13,13, 4,10,10, 9,12,12, 9,12,12, 7,
  142823. 12,12,10,13,13,10,12,13, 7,11,12,10,13,13,10,13,
  142824. 11,
  142825. };
  142826. static float _vq_quantthresh__8u1__p7_0[] = {
  142827. -5.5, 5.5,
  142828. };
  142829. static long _vq_quantmap__8u1__p7_0[] = {
  142830. 1, 0, 2,
  142831. };
  142832. static encode_aux_threshmatch _vq_auxt__8u1__p7_0 = {
  142833. _vq_quantthresh__8u1__p7_0,
  142834. _vq_quantmap__8u1__p7_0,
  142835. 3,
  142836. 3
  142837. };
  142838. static static_codebook _8u1__p7_0 = {
  142839. 4, 81,
  142840. _vq_lengthlist__8u1__p7_0,
  142841. 1, -529137664, 1618345984, 2, 0,
  142842. _vq_quantlist__8u1__p7_0,
  142843. NULL,
  142844. &_vq_auxt__8u1__p7_0,
  142845. NULL,
  142846. 0
  142847. };
  142848. static long _vq_quantlist__8u1__p7_1[] = {
  142849. 5,
  142850. 4,
  142851. 6,
  142852. 3,
  142853. 7,
  142854. 2,
  142855. 8,
  142856. 1,
  142857. 9,
  142858. 0,
  142859. 10,
  142860. };
  142861. static long _vq_lengthlist__8u1__p7_1[] = {
  142862. 2, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8, 4, 5, 5, 7, 7,
  142863. 8, 8, 9, 9, 9, 9, 4, 5, 5, 7, 7, 8, 8, 9, 9, 9,
  142864. 9, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 6, 7, 7, 8,
  142865. 8, 8, 8, 9, 9, 9, 9, 8, 8, 8, 8, 8, 9, 9, 9, 9,
  142866. 9, 9, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 8, 9, 9,
  142867. 9, 9, 9, 9,10,10,10,10, 8, 9, 9, 9, 9, 9, 9,10,
  142868. 10,10,10, 8, 9, 9, 9, 9, 9, 9,10,10,10,10, 8, 9,
  142869. 9, 9, 9, 9, 9,10,10,10,10,
  142870. };
  142871. static float _vq_quantthresh__8u1__p7_1[] = {
  142872. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  142873. 3.5, 4.5,
  142874. };
  142875. static long _vq_quantmap__8u1__p7_1[] = {
  142876. 9, 7, 5, 3, 1, 0, 2, 4,
  142877. 6, 8, 10,
  142878. };
  142879. static encode_aux_threshmatch _vq_auxt__8u1__p7_1 = {
  142880. _vq_quantthresh__8u1__p7_1,
  142881. _vq_quantmap__8u1__p7_1,
  142882. 11,
  142883. 11
  142884. };
  142885. static static_codebook _8u1__p7_1 = {
  142886. 2, 121,
  142887. _vq_lengthlist__8u1__p7_1,
  142888. 1, -531365888, 1611661312, 4, 0,
  142889. _vq_quantlist__8u1__p7_1,
  142890. NULL,
  142891. &_vq_auxt__8u1__p7_1,
  142892. NULL,
  142893. 0
  142894. };
  142895. static long _vq_quantlist__8u1__p8_0[] = {
  142896. 5,
  142897. 4,
  142898. 6,
  142899. 3,
  142900. 7,
  142901. 2,
  142902. 8,
  142903. 1,
  142904. 9,
  142905. 0,
  142906. 10,
  142907. };
  142908. static long _vq_lengthlist__8u1__p8_0[] = {
  142909. 1, 4, 4, 6, 6, 8, 8,10,10,11,11, 4, 6, 6, 7, 7,
  142910. 9, 9,11,11,13,12, 4, 6, 6, 7, 7, 9, 9,11,11,12,
  142911. 12, 6, 7, 7, 9, 9,11,11,12,12,13,13, 6, 7, 7, 9,
  142912. 9,11,11,12,12,13,13, 8, 9, 9,11,11,12,12,13,13,
  142913. 14,14, 8, 9, 9,11,11,12,12,13,13,14,14, 9,11,11,
  142914. 12,12,13,13,14,14,15,15, 9,11,11,12,12,13,13,14,
  142915. 14,15,14,11,12,12,13,13,14,14,15,15,16,16,11,12,
  142916. 12,13,13,14,14,15,15,15,15,
  142917. };
  142918. static float _vq_quantthresh__8u1__p8_0[] = {
  142919. -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5, 27.5,
  142920. 38.5, 49.5,
  142921. };
  142922. static long _vq_quantmap__8u1__p8_0[] = {
  142923. 9, 7, 5, 3, 1, 0, 2, 4,
  142924. 6, 8, 10,
  142925. };
  142926. static encode_aux_threshmatch _vq_auxt__8u1__p8_0 = {
  142927. _vq_quantthresh__8u1__p8_0,
  142928. _vq_quantmap__8u1__p8_0,
  142929. 11,
  142930. 11
  142931. };
  142932. static static_codebook _8u1__p8_0 = {
  142933. 2, 121,
  142934. _vq_lengthlist__8u1__p8_0,
  142935. 1, -524582912, 1618345984, 4, 0,
  142936. _vq_quantlist__8u1__p8_0,
  142937. NULL,
  142938. &_vq_auxt__8u1__p8_0,
  142939. NULL,
  142940. 0
  142941. };
  142942. static long _vq_quantlist__8u1__p8_1[] = {
  142943. 5,
  142944. 4,
  142945. 6,
  142946. 3,
  142947. 7,
  142948. 2,
  142949. 8,
  142950. 1,
  142951. 9,
  142952. 0,
  142953. 10,
  142954. };
  142955. static long _vq_lengthlist__8u1__p8_1[] = {
  142956. 2, 5, 5, 6, 6, 7, 7, 7, 7, 8, 8, 5, 6, 6, 7, 7,
  142957. 7, 7, 8, 8, 8, 8, 5, 6, 6, 7, 7, 7, 7, 8, 8, 8,
  142958. 8, 6, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 6, 7, 7, 7,
  142959. 7, 8, 8, 8, 8, 8, 8, 7, 7, 7, 8, 8, 8, 8, 8, 8,
  142960. 8, 8, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  142961. 8, 8, 8, 8, 9, 8, 9, 9, 7, 8, 8, 8, 8, 8, 8, 9,
  142962. 8, 9, 9, 8, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9, 8, 8,
  142963. 8, 8, 8, 8, 8, 9, 9, 9, 9,
  142964. };
  142965. static float _vq_quantthresh__8u1__p8_1[] = {
  142966. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  142967. 3.5, 4.5,
  142968. };
  142969. static long _vq_quantmap__8u1__p8_1[] = {
  142970. 9, 7, 5, 3, 1, 0, 2, 4,
  142971. 6, 8, 10,
  142972. };
  142973. static encode_aux_threshmatch _vq_auxt__8u1__p8_1 = {
  142974. _vq_quantthresh__8u1__p8_1,
  142975. _vq_quantmap__8u1__p8_1,
  142976. 11,
  142977. 11
  142978. };
  142979. static static_codebook _8u1__p8_1 = {
  142980. 2, 121,
  142981. _vq_lengthlist__8u1__p8_1,
  142982. 1, -531365888, 1611661312, 4, 0,
  142983. _vq_quantlist__8u1__p8_1,
  142984. NULL,
  142985. &_vq_auxt__8u1__p8_1,
  142986. NULL,
  142987. 0
  142988. };
  142989. static long _vq_quantlist__8u1__p9_0[] = {
  142990. 7,
  142991. 6,
  142992. 8,
  142993. 5,
  142994. 9,
  142995. 4,
  142996. 10,
  142997. 3,
  142998. 11,
  142999. 2,
  143000. 12,
  143001. 1,
  143002. 13,
  143003. 0,
  143004. 14,
  143005. };
  143006. static long _vq_lengthlist__8u1__p9_0[] = {
  143007. 1, 4, 4,11,11,11,11,11,11,11,11,11,11,11,11, 3,
  143008. 11, 8,11,11,11,11,11,11,11,11,11,11,11,11, 3, 9,
  143009. 9,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  143010. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  143011. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  143012. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  143013. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  143014. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  143015. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  143016. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  143017. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  143018. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  143019. 11,11,11,11,11,11,11,11,11,11,10,10,10,10,10,10,
  143020. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  143021. 10,
  143022. };
  143023. static float _vq_quantthresh__8u1__p9_0[] = {
  143024. -1657.5, -1402.5, -1147.5, -892.5, -637.5, -382.5, -127.5, 127.5,
  143025. 382.5, 637.5, 892.5, 1147.5, 1402.5, 1657.5,
  143026. };
  143027. static long _vq_quantmap__8u1__p9_0[] = {
  143028. 13, 11, 9, 7, 5, 3, 1, 0,
  143029. 2, 4, 6, 8, 10, 12, 14,
  143030. };
  143031. static encode_aux_threshmatch _vq_auxt__8u1__p9_0 = {
  143032. _vq_quantthresh__8u1__p9_0,
  143033. _vq_quantmap__8u1__p9_0,
  143034. 15,
  143035. 15
  143036. };
  143037. static static_codebook _8u1__p9_0 = {
  143038. 2, 225,
  143039. _vq_lengthlist__8u1__p9_0,
  143040. 1, -514071552, 1627381760, 4, 0,
  143041. _vq_quantlist__8u1__p9_0,
  143042. NULL,
  143043. &_vq_auxt__8u1__p9_0,
  143044. NULL,
  143045. 0
  143046. };
  143047. static long _vq_quantlist__8u1__p9_1[] = {
  143048. 7,
  143049. 6,
  143050. 8,
  143051. 5,
  143052. 9,
  143053. 4,
  143054. 10,
  143055. 3,
  143056. 11,
  143057. 2,
  143058. 12,
  143059. 1,
  143060. 13,
  143061. 0,
  143062. 14,
  143063. };
  143064. static long _vq_lengthlist__8u1__p9_1[] = {
  143065. 1, 4, 4, 7, 7, 9, 9, 7, 7, 8, 8,10,10,11,11, 4,
  143066. 7, 7, 9, 9,10,10, 8, 8,10,10,10,11,10,11, 4, 7,
  143067. 7, 9, 9,10,10, 8, 8,10, 9,11,11,11,11, 7, 9, 9,
  143068. 12,12,11,12,10,10,11,10,12,11,11,11, 7, 9, 9,11,
  143069. 11,13,12, 9, 9,11,10,11,11,12,11, 9,10,10,12,12,
  143070. 14,14,10,10,11,12,12,11,11,11, 9,10,11,11,13,14,
  143071. 13,10,11,11,11,12,11,12,12, 7, 8, 8,10, 9,11,10,
  143072. 11,12,12,11,12,14,12,13, 7, 8, 8, 9,10,10,11,12,
  143073. 12,12,11,12,12,12,13, 9, 9, 9,11,11,13,12,12,12,
  143074. 12,11,12,12,13,12, 8,10,10,11,10,11,12,12,12,12,
  143075. 12,12,14,12,12, 9,11,11,11,12,12,12,12,13,13,12,
  143076. 12,13,13,12,10,11,11,12,11,12,12,12,11,12,13,12,
  143077. 12,12,13,11,11,12,12,12,13,12,12,11,12,13,13,12,
  143078. 12,13,12,11,12,12,13,13,12,13,12,13,13,13,13,14,
  143079. 13,
  143080. };
  143081. static float _vq_quantthresh__8u1__p9_1[] = {
  143082. -110.5, -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5,
  143083. 25.5, 42.5, 59.5, 76.5, 93.5, 110.5,
  143084. };
  143085. static long _vq_quantmap__8u1__p9_1[] = {
  143086. 13, 11, 9, 7, 5, 3, 1, 0,
  143087. 2, 4, 6, 8, 10, 12, 14,
  143088. };
  143089. static encode_aux_threshmatch _vq_auxt__8u1__p9_1 = {
  143090. _vq_quantthresh__8u1__p9_1,
  143091. _vq_quantmap__8u1__p9_1,
  143092. 15,
  143093. 15
  143094. };
  143095. static static_codebook _8u1__p9_1 = {
  143096. 2, 225,
  143097. _vq_lengthlist__8u1__p9_1,
  143098. 1, -522338304, 1620115456, 4, 0,
  143099. _vq_quantlist__8u1__p9_1,
  143100. NULL,
  143101. &_vq_auxt__8u1__p9_1,
  143102. NULL,
  143103. 0
  143104. };
  143105. static long _vq_quantlist__8u1__p9_2[] = {
  143106. 8,
  143107. 7,
  143108. 9,
  143109. 6,
  143110. 10,
  143111. 5,
  143112. 11,
  143113. 4,
  143114. 12,
  143115. 3,
  143116. 13,
  143117. 2,
  143118. 14,
  143119. 1,
  143120. 15,
  143121. 0,
  143122. 16,
  143123. };
  143124. static long _vq_lengthlist__8u1__p9_2[] = {
  143125. 2, 5, 4, 6, 6, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  143126. 9, 5, 6, 6, 7, 7, 8, 8, 9, 8, 9, 9, 9, 9, 9, 9,
  143127. 9, 9, 5, 6, 6, 7, 7, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  143128. 9, 9, 9, 7, 7, 7, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9,
  143129. 9,10,10, 9, 7, 7, 7, 8, 8, 9, 9, 9, 9, 9, 9, 9,
  143130. 9, 9, 9,10,10, 8, 8, 8, 9, 9, 9, 9,10,10,10, 9,
  143131. 10,10,10,10,10,10, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9,
  143132. 10,10,10,10,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9,10,
  143133. 10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9,10,10,10,
  143134. 10,10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9, 9,10,
  143135. 10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9,10,
  143136. 10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9,10,
  143137. 10,10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9,
  143138. 9,10,10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9,
  143139. 10,10,10,10,10,10,10,10,10,10,10,10,10,10, 9,10,
  143140. 9, 9, 9,10,10,10,10,10,10,10,10,10,10,10,10, 9,
  143141. 10, 9,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  143142. 9, 9,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  143143. 10,
  143144. };
  143145. static float _vq_quantthresh__8u1__p9_2[] = {
  143146. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  143147. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  143148. };
  143149. static long _vq_quantmap__8u1__p9_2[] = {
  143150. 15, 13, 11, 9, 7, 5, 3, 1,
  143151. 0, 2, 4, 6, 8, 10, 12, 14,
  143152. 16,
  143153. };
  143154. static encode_aux_threshmatch _vq_auxt__8u1__p9_2 = {
  143155. _vq_quantthresh__8u1__p9_2,
  143156. _vq_quantmap__8u1__p9_2,
  143157. 17,
  143158. 17
  143159. };
  143160. static static_codebook _8u1__p9_2 = {
  143161. 2, 289,
  143162. _vq_lengthlist__8u1__p9_2,
  143163. 1, -529530880, 1611661312, 5, 0,
  143164. _vq_quantlist__8u1__p9_2,
  143165. NULL,
  143166. &_vq_auxt__8u1__p9_2,
  143167. NULL,
  143168. 0
  143169. };
  143170. static long _huff_lengthlist__8u1__single[] = {
  143171. 4, 7,13, 9,15, 9,16, 8,10,13, 7, 5, 8, 6, 9, 7,
  143172. 10, 7,10,11,11, 6, 7, 8, 8, 9, 9, 9,12,16, 8, 5,
  143173. 8, 6, 8, 6, 9, 7,10,12,11, 7, 7, 7, 6, 7, 7, 7,
  143174. 11,15, 7, 5, 8, 6, 7, 5, 7, 6, 9,13,13, 9, 9, 8,
  143175. 6, 6, 5, 5, 9,14, 8, 6, 8, 6, 6, 4, 5, 3, 5,13,
  143176. 9, 9,11, 8,10, 7, 8, 4, 5,12,11,16,17,15,17,12,
  143177. 13, 8, 8,15,
  143178. };
  143179. static static_codebook _huff_book__8u1__single = {
  143180. 2, 100,
  143181. _huff_lengthlist__8u1__single,
  143182. 0, 0, 0, 0, 0,
  143183. NULL,
  143184. NULL,
  143185. NULL,
  143186. NULL,
  143187. 0
  143188. };
  143189. static long _huff_lengthlist__44u0__long[] = {
  143190. 5, 8,13,10,17,11,11,15, 7, 2, 4, 5, 8, 7, 9,16,
  143191. 13, 4, 3, 5, 6, 8,11,20,10, 4, 5, 5, 7, 6, 8,18,
  143192. 15, 7, 6, 7, 8,10,14,20,10, 6, 7, 6, 9, 7, 8,17,
  143193. 9, 8,10, 8,10, 5, 4,11,12,17,19,14,16,10, 7,12,
  143194. };
  143195. static static_codebook _huff_book__44u0__long = {
  143196. 2, 64,
  143197. _huff_lengthlist__44u0__long,
  143198. 0, 0, 0, 0, 0,
  143199. NULL,
  143200. NULL,
  143201. NULL,
  143202. NULL,
  143203. 0
  143204. };
  143205. static long _vq_quantlist__44u0__p1_0[] = {
  143206. 1,
  143207. 0,
  143208. 2,
  143209. };
  143210. static long _vq_lengthlist__44u0__p1_0[] = {
  143211. 1, 4, 4, 5, 8, 7, 5, 7, 8, 5, 8, 8, 8,11,11, 8,
  143212. 10,10, 5, 8, 8, 8,11,10, 8,11,11, 4, 8, 8, 8,11,
  143213. 11, 8,11,11, 8,12,11,11,13,13,11,13,14, 7,11,11,
  143214. 10,13,12,11,13,14, 4, 8, 8, 8,11,11, 8,11,12, 8,
  143215. 11,11,11,13,13,10,12,13, 8,11,11,11,14,13,11,14,
  143216. 13,
  143217. };
  143218. static float _vq_quantthresh__44u0__p1_0[] = {
  143219. -0.5, 0.5,
  143220. };
  143221. static long _vq_quantmap__44u0__p1_0[] = {
  143222. 1, 0, 2,
  143223. };
  143224. static encode_aux_threshmatch _vq_auxt__44u0__p1_0 = {
  143225. _vq_quantthresh__44u0__p1_0,
  143226. _vq_quantmap__44u0__p1_0,
  143227. 3,
  143228. 3
  143229. };
  143230. static static_codebook _44u0__p1_0 = {
  143231. 4, 81,
  143232. _vq_lengthlist__44u0__p1_0,
  143233. 1, -535822336, 1611661312, 2, 0,
  143234. _vq_quantlist__44u0__p1_0,
  143235. NULL,
  143236. &_vq_auxt__44u0__p1_0,
  143237. NULL,
  143238. 0
  143239. };
  143240. static long _vq_quantlist__44u0__p2_0[] = {
  143241. 1,
  143242. 0,
  143243. 2,
  143244. };
  143245. static long _vq_lengthlist__44u0__p2_0[] = {
  143246. 2, 4, 4, 5, 6, 6, 5, 6, 6, 5, 7, 7, 7, 8, 8, 6,
  143247. 8, 8, 5, 7, 7, 6, 8, 8, 7, 8, 8, 4, 7, 7, 7, 8,
  143248. 8, 7, 8, 8, 7, 8, 8, 8, 9,10, 8,10,10, 6, 8, 8,
  143249. 8,10, 8, 8,10,10, 5, 7, 7, 7, 8, 8, 7, 8, 8, 6,
  143250. 8, 8, 8,10,10, 8, 8,10, 6, 8, 8, 8,10,10, 8,10,
  143251. 9,
  143252. };
  143253. static float _vq_quantthresh__44u0__p2_0[] = {
  143254. -0.5, 0.5,
  143255. };
  143256. static long _vq_quantmap__44u0__p2_0[] = {
  143257. 1, 0, 2,
  143258. };
  143259. static encode_aux_threshmatch _vq_auxt__44u0__p2_0 = {
  143260. _vq_quantthresh__44u0__p2_0,
  143261. _vq_quantmap__44u0__p2_0,
  143262. 3,
  143263. 3
  143264. };
  143265. static static_codebook _44u0__p2_0 = {
  143266. 4, 81,
  143267. _vq_lengthlist__44u0__p2_0,
  143268. 1, -535822336, 1611661312, 2, 0,
  143269. _vq_quantlist__44u0__p2_0,
  143270. NULL,
  143271. &_vq_auxt__44u0__p2_0,
  143272. NULL,
  143273. 0
  143274. };
  143275. static long _vq_quantlist__44u0__p3_0[] = {
  143276. 2,
  143277. 1,
  143278. 3,
  143279. 0,
  143280. 4,
  143281. };
  143282. static long _vq_lengthlist__44u0__p3_0[] = {
  143283. 1, 5, 5, 8, 8, 5, 8, 7, 9, 9, 5, 7, 8, 9, 9, 9,
  143284. 10, 9,12,12, 9, 9,10,12,12, 6, 8, 8,11,10, 8,10,
  143285. 10,11,11, 8, 9,10,11,11,10,11,11,14,13,10,11,11,
  143286. 13,13, 5, 8, 8,10,10, 8,10,10,11,11, 8,10,10,11,
  143287. 11,10,11,11,13,13,10,11,11,13,13, 9,11,11,15,14,
  143288. 10,12,12,15,14,10,12,11,15,14,13,14,14,16,16,12,
  143289. 14,13,17,15, 9,11,11,14,15,10,11,12,14,16,10,11,
  143290. 12,14,16,12,13,14,16,16,13,13,15,15,18, 5, 8, 8,
  143291. 11,11, 8,10,10,12,12, 8,10,10,12,13,11,12,12,14,
  143292. 14,11,12,12,15,15, 8,10,10,13,13,10,12,12,13,13,
  143293. 10,12,12,14,14,12,13,13,15,15,12,13,13,16,16, 7,
  143294. 10,10,12,12,10,12,11,13,13,10,12,12,13,14,12,13,
  143295. 12,15,14,12,13,13,16,16,10,12,12,17,16,12,13,13,
  143296. 16,15,11,13,13,17,17,15,15,15,16,17,14,15,15,19,
  143297. 19,10,12,12,15,16,11,13,12,15,18,11,13,13,16,16,
  143298. 14,15,15,17,17,14,15,15,17,19, 5, 8, 8,11,11, 8,
  143299. 10,10,12,12, 8,10,10,12,12,11,12,12,16,15,11,12,
  143300. 12,14,15, 7,10,10,13,13,10,12,12,14,13,10,11,12,
  143301. 13,13,12,13,13,16,16,12,12,13,15,15, 8,10,10,13,
  143302. 13,10,12,12,14,14,10,12,12,13,13,12,13,13,16,16,
  143303. 12,13,13,15,15,10,12,12,16,15,11,13,13,17,16,11,
  143304. 12,13,16,15,13,15,15,19,17,14,15,14,17,16,10,12,
  143305. 12,16,16,11,13,13,16,17,12,13,13,15,17,14,15,15,
  143306. 17,19,14,15,15,17,17, 8,11,11,16,16,10,13,12,17,
  143307. 17,10,12,13,16,16,15,17,16,20,19,14,15,17,18,19,
  143308. 9,12,12,16,17,11,13,14,17,18,11,13,13,19,18,16,
  143309. 17,18,19,19,15,16,16,19,19, 9,12,12,16,17,11,14,
  143310. 13,18,17,11,13,13,17,17,16,17,16,20,19,14,16,16,
  143311. 18,18,12,15,15,19,17,14,15,16, 0,20,13,15,16,20,
  143312. 17,18,16,20, 0, 0,15,16,19,20, 0,12,15,14,18,19,
  143313. 13,16,15,20,19,13,16,15,20,18,17,18,17, 0,20,16,
  143314. 17,16, 0, 0, 8,11,11,16,15,10,12,12,17,17,10,13,
  143315. 13,17,16,14,16,15,18,20,15,16,16,19,19, 9,12,12,
  143316. 16,16,11,13,13,17,16,11,13,14,17,18,15,15,16,20,
  143317. 20,16,16,17,19,19, 9,13,12,16,17,11,14,13,17,17,
  143318. 11,14,14,18,17,14,16,15,18,19,16,17,18,18,19,12,
  143319. 14,15,19,18,13,15,16,18, 0,13,14,15, 0, 0,16,16,
  143320. 17,20, 0,17,17,20,20, 0,12,15,15,19,20,13,15,15,
  143321. 0, 0,14,16,15, 0, 0,15,18,16, 0, 0,17,18,16, 0,
  143322. 19,
  143323. };
  143324. static float _vq_quantthresh__44u0__p3_0[] = {
  143325. -1.5, -0.5, 0.5, 1.5,
  143326. };
  143327. static long _vq_quantmap__44u0__p3_0[] = {
  143328. 3, 1, 0, 2, 4,
  143329. };
  143330. static encode_aux_threshmatch _vq_auxt__44u0__p3_0 = {
  143331. _vq_quantthresh__44u0__p3_0,
  143332. _vq_quantmap__44u0__p3_0,
  143333. 5,
  143334. 5
  143335. };
  143336. static static_codebook _44u0__p3_0 = {
  143337. 4, 625,
  143338. _vq_lengthlist__44u0__p3_0,
  143339. 1, -533725184, 1611661312, 3, 0,
  143340. _vq_quantlist__44u0__p3_0,
  143341. NULL,
  143342. &_vq_auxt__44u0__p3_0,
  143343. NULL,
  143344. 0
  143345. };
  143346. static long _vq_quantlist__44u0__p4_0[] = {
  143347. 2,
  143348. 1,
  143349. 3,
  143350. 0,
  143351. 4,
  143352. };
  143353. static long _vq_lengthlist__44u0__p4_0[] = {
  143354. 4, 5, 5, 9, 9, 5, 6, 6, 9, 9, 5, 6, 6, 9, 9, 9,
  143355. 10, 9,12,12, 9, 9,10,12,12, 5, 7, 7,10,10, 7, 7,
  143356. 8,10,10, 6, 7, 8,10,10,10,10,10,11,13,10, 9,10,
  143357. 12,13, 5, 7, 7,10,10, 6, 8, 7,10,10, 7, 8, 7,10,
  143358. 10, 9,10,10,12,12,10,10,10,13,11, 9,10,10,13,13,
  143359. 10,11,10,13,13,10,10,10,13,13,12,12,13,14,14,12,
  143360. 12,13,14,14, 9,10,10,13,13,10,10,10,13,13,10,10,
  143361. 10,13,13,12,13,12,15,14,12,13,12,15,15, 5, 7, 6,
  143362. 10,10, 7, 8, 8,10,10, 7, 8, 8,10,10,10,11,10,13,
  143363. 13,10,10,10,12,12, 7, 8, 8,11,10, 8, 8, 9,10,11,
  143364. 8, 9, 9,11,11,11,10,11,11,14,11,11,11,13,13, 6,
  143365. 8, 8,10,10, 7, 9, 8,11,10, 8, 9, 9,11,11,10,11,
  143366. 10,14,11,10,11,11,13,13,10,11,11,14,13,10,10,11,
  143367. 14,13,10,11,11,14,14,12,11,13,12,16,13,14,14,15,
  143368. 15,10,10,11,13,14,10,11,10,14,13,10,11,11,14,14,
  143369. 12,13,12,15,13,13,13,14,15,16, 5, 7, 7,10,10, 7,
  143370. 8, 8,10,10, 7, 8, 8,10,10,10,10,10,13,13,10,10,
  143371. 11,12,13, 6, 8, 8,11,10, 8, 9, 9,11,11, 7, 8, 9,
  143372. 10,11,10,11,11,13,13,10,10,11,11,13, 6, 8, 8,10,
  143373. 11, 8, 9, 9,11,11, 8, 9, 8,12,10,10,11,11,13,13,
  143374. 10,11,10,14,11,10,10,10,14,13,10,11,11,14,13,10,
  143375. 10,11,13,13,12,14,14,16,16,12,12,13,13,15,10,11,
  143376. 11,13,14,10,11,11,14,15,10,11,10,13,13,13,14,13,
  143377. 16,16,12,13,11,15,12, 9,10,10,13,13,10,11,11,14,
  143378. 13,10,10,11,13,14,13,14,13,16,16,13,13,13,15,16,
  143379. 9,10,10,13,13,10,10,11,13,14,10,11,11,15,13,13,
  143380. 13,14,14,18,13,13,14,16,15, 9,10,10,13,14,10,11,
  143381. 10,14,13,10,11,11,13,14,13,14,13,16,15,13,13,14,
  143382. 15,16,12,13,12,16,14,11,11,13,15,15,13,14,13,16,
  143383. 15,15,12,16,12,17,14,15,15,17,17,12,13,13,14,16,
  143384. 11,13,11,16,15,12,13,14,15,16,14,15,13, 0,14,14,
  143385. 16,16, 0, 0, 9,10,10,13,13,10,11,10,14,14,10,11,
  143386. 11,13,13,12,13,13,14,16,13,14,14,16,16, 9,10,10,
  143387. 14,14,11,11,11,14,13,10,10,11,14,14,13,13,13,16,
  143388. 16,13,13,14,14,17, 9,10,10,13,14,10,11,11,13,15,
  143389. 10,11,10,14,14,13,13,13,14,17,13,14,13,17,14,12,
  143390. 13,13,16,14,13,14,13,16,15,12,12,13,15,16,15,15,
  143391. 16,18,16,15,13,15,14, 0,12,12,13,14,16,13,13,14,
  143392. 15,16,11,12,11,16,14,15,16,16,17,17,14,15,12,17,
  143393. 12,
  143394. };
  143395. static float _vq_quantthresh__44u0__p4_0[] = {
  143396. -1.5, -0.5, 0.5, 1.5,
  143397. };
  143398. static long _vq_quantmap__44u0__p4_0[] = {
  143399. 3, 1, 0, 2, 4,
  143400. };
  143401. static encode_aux_threshmatch _vq_auxt__44u0__p4_0 = {
  143402. _vq_quantthresh__44u0__p4_0,
  143403. _vq_quantmap__44u0__p4_0,
  143404. 5,
  143405. 5
  143406. };
  143407. static static_codebook _44u0__p4_0 = {
  143408. 4, 625,
  143409. _vq_lengthlist__44u0__p4_0,
  143410. 1, -533725184, 1611661312, 3, 0,
  143411. _vq_quantlist__44u0__p4_0,
  143412. NULL,
  143413. &_vq_auxt__44u0__p4_0,
  143414. NULL,
  143415. 0
  143416. };
  143417. static long _vq_quantlist__44u0__p5_0[] = {
  143418. 4,
  143419. 3,
  143420. 5,
  143421. 2,
  143422. 6,
  143423. 1,
  143424. 7,
  143425. 0,
  143426. 8,
  143427. };
  143428. static long _vq_lengthlist__44u0__p5_0[] = {
  143429. 1, 4, 4, 7, 7, 7, 7, 9, 9, 4, 6, 6, 8, 8, 8, 8,
  143430. 9, 9, 4, 6, 6, 8, 8, 8, 8, 9, 9, 7, 8, 8, 9, 9,
  143431. 9, 9,11,10, 7, 8, 8, 9, 9, 9, 9,10,10, 7, 8, 8,
  143432. 9, 9,10,10,11,11, 7, 8, 8, 9, 9,10,10,11,11, 9,
  143433. 9, 9,10,10,11,11,12,12, 9, 9, 9,10,11,11,11,12,
  143434. 12,
  143435. };
  143436. static float _vq_quantthresh__44u0__p5_0[] = {
  143437. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  143438. };
  143439. static long _vq_quantmap__44u0__p5_0[] = {
  143440. 7, 5, 3, 1, 0, 2, 4, 6,
  143441. 8,
  143442. };
  143443. static encode_aux_threshmatch _vq_auxt__44u0__p5_0 = {
  143444. _vq_quantthresh__44u0__p5_0,
  143445. _vq_quantmap__44u0__p5_0,
  143446. 9,
  143447. 9
  143448. };
  143449. static static_codebook _44u0__p5_0 = {
  143450. 2, 81,
  143451. _vq_lengthlist__44u0__p5_0,
  143452. 1, -531628032, 1611661312, 4, 0,
  143453. _vq_quantlist__44u0__p5_0,
  143454. NULL,
  143455. &_vq_auxt__44u0__p5_0,
  143456. NULL,
  143457. 0
  143458. };
  143459. static long _vq_quantlist__44u0__p6_0[] = {
  143460. 6,
  143461. 5,
  143462. 7,
  143463. 4,
  143464. 8,
  143465. 3,
  143466. 9,
  143467. 2,
  143468. 10,
  143469. 1,
  143470. 11,
  143471. 0,
  143472. 12,
  143473. };
  143474. static long _vq_lengthlist__44u0__p6_0[] = {
  143475. 1, 4, 4, 6, 6, 8, 8,10, 9,11,10,14,13, 4, 6, 5,
  143476. 8, 8, 9, 9,11,10,11,11,14,14, 4, 5, 6, 8, 8, 9,
  143477. 9,10,10,11,11,14,14, 6, 8, 8, 9, 9,10,10,11,11,
  143478. 12,12,16,15, 7, 8, 8, 9, 9,10,10,11,11,12,12,15,
  143479. 15, 9,10,10,10,10,11,11,12,12,12,12,15,15, 9,10,
  143480. 9,10,11,11,11,12,12,12,13,15,15,10,10,11,11,11,
  143481. 12,12,13,12,13,13,16,15,10,11,11,11,11,12,12,13,
  143482. 12,13,13,16,17,11,11,12,12,12,13,13,13,14,14,15,
  143483. 17,17,11,11,12,12,12,13,13,13,14,14,14,16,18,14,
  143484. 15,15,15,15,16,16,16,16,17,18, 0, 0,14,15,15,15,
  143485. 15,17,16,17,18,17,17,18, 0,
  143486. };
  143487. static float _vq_quantthresh__44u0__p6_0[] = {
  143488. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  143489. 12.5, 17.5, 22.5, 27.5,
  143490. };
  143491. static long _vq_quantmap__44u0__p6_0[] = {
  143492. 11, 9, 7, 5, 3, 1, 0, 2,
  143493. 4, 6, 8, 10, 12,
  143494. };
  143495. static encode_aux_threshmatch _vq_auxt__44u0__p6_0 = {
  143496. _vq_quantthresh__44u0__p6_0,
  143497. _vq_quantmap__44u0__p6_0,
  143498. 13,
  143499. 13
  143500. };
  143501. static static_codebook _44u0__p6_0 = {
  143502. 2, 169,
  143503. _vq_lengthlist__44u0__p6_0,
  143504. 1, -526516224, 1616117760, 4, 0,
  143505. _vq_quantlist__44u0__p6_0,
  143506. NULL,
  143507. &_vq_auxt__44u0__p6_0,
  143508. NULL,
  143509. 0
  143510. };
  143511. static long _vq_quantlist__44u0__p6_1[] = {
  143512. 2,
  143513. 1,
  143514. 3,
  143515. 0,
  143516. 4,
  143517. };
  143518. static long _vq_lengthlist__44u0__p6_1[] = {
  143519. 2, 4, 4, 5, 5, 4, 5, 5, 5, 5, 4, 5, 5, 5, 5, 5,
  143520. 6, 6, 6, 6, 5, 6, 6, 6, 6,
  143521. };
  143522. static float _vq_quantthresh__44u0__p6_1[] = {
  143523. -1.5, -0.5, 0.5, 1.5,
  143524. };
  143525. static long _vq_quantmap__44u0__p6_1[] = {
  143526. 3, 1, 0, 2, 4,
  143527. };
  143528. static encode_aux_threshmatch _vq_auxt__44u0__p6_1 = {
  143529. _vq_quantthresh__44u0__p6_1,
  143530. _vq_quantmap__44u0__p6_1,
  143531. 5,
  143532. 5
  143533. };
  143534. static static_codebook _44u0__p6_1 = {
  143535. 2, 25,
  143536. _vq_lengthlist__44u0__p6_1,
  143537. 1, -533725184, 1611661312, 3, 0,
  143538. _vq_quantlist__44u0__p6_1,
  143539. NULL,
  143540. &_vq_auxt__44u0__p6_1,
  143541. NULL,
  143542. 0
  143543. };
  143544. static long _vq_quantlist__44u0__p7_0[] = {
  143545. 2,
  143546. 1,
  143547. 3,
  143548. 0,
  143549. 4,
  143550. };
  143551. static long _vq_lengthlist__44u0__p7_0[] = {
  143552. 1, 4, 4,11,11, 9,11,11,11,11,11,11,11,11,11,11,
  143553. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  143554. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  143555. 11,11, 9,11,11,11,11,11,11,11,11,11,11,11,11,11,
  143556. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  143557. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  143558. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  143559. 11,11,11,11,11,11,11,11,11,11,11,11,11,10,11,11,
  143560. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  143561. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  143562. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  143563. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  143564. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  143565. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  143566. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  143567. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  143568. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  143569. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  143570. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  143571. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  143572. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  143573. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  143574. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  143575. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  143576. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  143577. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  143578. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  143579. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  143580. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  143581. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  143582. 11,11,11,11,11,11,10,10,10,10,10,10,10,10,10,10,
  143583. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  143584. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  143585. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  143586. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  143587. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  143588. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  143589. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  143590. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  143591. 10,
  143592. };
  143593. static float _vq_quantthresh__44u0__p7_0[] = {
  143594. -253.5, -84.5, 84.5, 253.5,
  143595. };
  143596. static long _vq_quantmap__44u0__p7_0[] = {
  143597. 3, 1, 0, 2, 4,
  143598. };
  143599. static encode_aux_threshmatch _vq_auxt__44u0__p7_0 = {
  143600. _vq_quantthresh__44u0__p7_0,
  143601. _vq_quantmap__44u0__p7_0,
  143602. 5,
  143603. 5
  143604. };
  143605. static static_codebook _44u0__p7_0 = {
  143606. 4, 625,
  143607. _vq_lengthlist__44u0__p7_0,
  143608. 1, -518709248, 1626677248, 3, 0,
  143609. _vq_quantlist__44u0__p7_0,
  143610. NULL,
  143611. &_vq_auxt__44u0__p7_0,
  143612. NULL,
  143613. 0
  143614. };
  143615. static long _vq_quantlist__44u0__p7_1[] = {
  143616. 6,
  143617. 5,
  143618. 7,
  143619. 4,
  143620. 8,
  143621. 3,
  143622. 9,
  143623. 2,
  143624. 10,
  143625. 1,
  143626. 11,
  143627. 0,
  143628. 12,
  143629. };
  143630. static long _vq_lengthlist__44u0__p7_1[] = {
  143631. 1, 4, 4, 6, 6, 6, 6, 7, 7, 8, 8, 9, 9, 5, 7, 7,
  143632. 8, 7, 7, 7, 9, 8,10, 9,10,11, 5, 7, 7, 8, 8, 7,
  143633. 7, 8, 9,10,10,11,11, 6, 8, 8, 9, 9, 9, 9,11,10,
  143634. 12,12,15,12, 6, 8, 8, 9, 9, 9, 9,11,11,12,11,14,
  143635. 12, 7, 8, 8,10,10,12,12,13,13,13,15,13,13, 7, 8,
  143636. 8,10,10,11,11,13,12,14,15,15,15, 9,10,10,11,12,
  143637. 13,13,14,15,14,15,14,15, 8,10,10,12,12,14,14,15,
  143638. 14,14,15,15,14,10,12,12,14,14,15,14,15,15,15,14,
  143639. 15,15,10,12,12,13,14,15,14,15,15,14,15,15,15,12,
  143640. 15,13,15,14,15,15,15,15,15,15,15,15,13,13,15,15,
  143641. 15,15,15,15,15,15,15,15,15,
  143642. };
  143643. static float _vq_quantthresh__44u0__p7_1[] = {
  143644. -71.5, -58.5, -45.5, -32.5, -19.5, -6.5, 6.5, 19.5,
  143645. 32.5, 45.5, 58.5, 71.5,
  143646. };
  143647. static long _vq_quantmap__44u0__p7_1[] = {
  143648. 11, 9, 7, 5, 3, 1, 0, 2,
  143649. 4, 6, 8, 10, 12,
  143650. };
  143651. static encode_aux_threshmatch _vq_auxt__44u0__p7_1 = {
  143652. _vq_quantthresh__44u0__p7_1,
  143653. _vq_quantmap__44u0__p7_1,
  143654. 13,
  143655. 13
  143656. };
  143657. static static_codebook _44u0__p7_1 = {
  143658. 2, 169,
  143659. _vq_lengthlist__44u0__p7_1,
  143660. 1, -523010048, 1618608128, 4, 0,
  143661. _vq_quantlist__44u0__p7_1,
  143662. NULL,
  143663. &_vq_auxt__44u0__p7_1,
  143664. NULL,
  143665. 0
  143666. };
  143667. static long _vq_quantlist__44u0__p7_2[] = {
  143668. 6,
  143669. 5,
  143670. 7,
  143671. 4,
  143672. 8,
  143673. 3,
  143674. 9,
  143675. 2,
  143676. 10,
  143677. 1,
  143678. 11,
  143679. 0,
  143680. 12,
  143681. };
  143682. static long _vq_lengthlist__44u0__p7_2[] = {
  143683. 2, 5, 4, 6, 6, 7, 7, 8, 8, 8, 8, 9, 8, 5, 5, 6,
  143684. 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 5, 6, 5, 7, 7, 8,
  143685. 8, 8, 8, 9, 9, 9, 9, 6, 7, 7, 8, 8, 8, 8, 9, 8,
  143686. 9, 9, 9, 9, 6, 7, 7, 8, 7, 8, 8, 9, 9, 9, 9, 9,
  143687. 9, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 7, 8,
  143688. 8, 9, 8, 9, 8, 9, 9, 9, 9, 9, 9, 8, 9, 8, 9, 9,
  143689. 9, 9, 9, 9, 9, 9,10,10, 8, 8, 9, 9, 9, 9, 9, 9,
  143690. 9, 9,10, 9,10, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  143691. 9, 9, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  143692. 9, 9, 9, 9, 9, 9, 9, 9,10,10,10, 9, 9, 9, 9, 9,
  143693. 9, 9, 9,10, 9, 9,10,10, 9,
  143694. };
  143695. static float _vq_quantthresh__44u0__p7_2[] = {
  143696. -5.5, -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5,
  143697. 2.5, 3.5, 4.5, 5.5,
  143698. };
  143699. static long _vq_quantmap__44u0__p7_2[] = {
  143700. 11, 9, 7, 5, 3, 1, 0, 2,
  143701. 4, 6, 8, 10, 12,
  143702. };
  143703. static encode_aux_threshmatch _vq_auxt__44u0__p7_2 = {
  143704. _vq_quantthresh__44u0__p7_2,
  143705. _vq_quantmap__44u0__p7_2,
  143706. 13,
  143707. 13
  143708. };
  143709. static static_codebook _44u0__p7_2 = {
  143710. 2, 169,
  143711. _vq_lengthlist__44u0__p7_2,
  143712. 1, -531103744, 1611661312, 4, 0,
  143713. _vq_quantlist__44u0__p7_2,
  143714. NULL,
  143715. &_vq_auxt__44u0__p7_2,
  143716. NULL,
  143717. 0
  143718. };
  143719. static long _huff_lengthlist__44u0__short[] = {
  143720. 12,13,14,13,17,12,15,17, 5, 5, 6,10,10,11,15,16,
  143721. 4, 3, 3, 7, 5, 7,10,16, 7, 7, 7,10, 9,11,12,16,
  143722. 6, 5, 5, 9, 5, 6,10,16, 8, 7, 7, 9, 6, 7, 9,16,
  143723. 11, 7, 3, 6, 4, 5, 8,16,12, 9, 4, 8, 5, 7, 9,16,
  143724. };
  143725. static static_codebook _huff_book__44u0__short = {
  143726. 2, 64,
  143727. _huff_lengthlist__44u0__short,
  143728. 0, 0, 0, 0, 0,
  143729. NULL,
  143730. NULL,
  143731. NULL,
  143732. NULL,
  143733. 0
  143734. };
  143735. static long _huff_lengthlist__44u1__long[] = {
  143736. 5, 8,13,10,17,11,11,15, 7, 2, 4, 5, 8, 7, 9,16,
  143737. 13, 4, 3, 5, 6, 8,11,20,10, 4, 5, 5, 7, 6, 8,18,
  143738. 15, 7, 6, 7, 8,10,14,20,10, 6, 7, 6, 9, 7, 8,17,
  143739. 9, 8,10, 8,10, 5, 4,11,12,17,19,14,16,10, 7,12,
  143740. };
  143741. static static_codebook _huff_book__44u1__long = {
  143742. 2, 64,
  143743. _huff_lengthlist__44u1__long,
  143744. 0, 0, 0, 0, 0,
  143745. NULL,
  143746. NULL,
  143747. NULL,
  143748. NULL,
  143749. 0
  143750. };
  143751. static long _vq_quantlist__44u1__p1_0[] = {
  143752. 1,
  143753. 0,
  143754. 2,
  143755. };
  143756. static long _vq_lengthlist__44u1__p1_0[] = {
  143757. 1, 4, 4, 5, 8, 7, 5, 7, 8, 5, 8, 8, 8,11,11, 8,
  143758. 10,10, 5, 8, 8, 8,11,10, 8,11,11, 4, 8, 8, 8,11,
  143759. 11, 8,11,11, 8,12,11,11,13,13,11,13,14, 7,11,11,
  143760. 10,13,12,11,13,14, 4, 8, 8, 8,11,11, 8,11,12, 8,
  143761. 11,11,11,13,13,10,12,13, 8,11,11,11,14,13,11,14,
  143762. 13,
  143763. };
  143764. static float _vq_quantthresh__44u1__p1_0[] = {
  143765. -0.5, 0.5,
  143766. };
  143767. static long _vq_quantmap__44u1__p1_0[] = {
  143768. 1, 0, 2,
  143769. };
  143770. static encode_aux_threshmatch _vq_auxt__44u1__p1_0 = {
  143771. _vq_quantthresh__44u1__p1_0,
  143772. _vq_quantmap__44u1__p1_0,
  143773. 3,
  143774. 3
  143775. };
  143776. static static_codebook _44u1__p1_0 = {
  143777. 4, 81,
  143778. _vq_lengthlist__44u1__p1_0,
  143779. 1, -535822336, 1611661312, 2, 0,
  143780. _vq_quantlist__44u1__p1_0,
  143781. NULL,
  143782. &_vq_auxt__44u1__p1_0,
  143783. NULL,
  143784. 0
  143785. };
  143786. static long _vq_quantlist__44u1__p2_0[] = {
  143787. 1,
  143788. 0,
  143789. 2,
  143790. };
  143791. static long _vq_lengthlist__44u1__p2_0[] = {
  143792. 2, 4, 4, 5, 6, 6, 5, 6, 6, 5, 7, 7, 7, 8, 8, 6,
  143793. 8, 8, 5, 7, 7, 6, 8, 8, 7, 8, 8, 4, 7, 7, 7, 8,
  143794. 8, 7, 8, 8, 7, 8, 8, 8, 9,10, 8,10,10, 6, 8, 8,
  143795. 8,10, 8, 8,10,10, 5, 7, 7, 7, 8, 8, 7, 8, 8, 6,
  143796. 8, 8, 8,10,10, 8, 8,10, 6, 8, 8, 8,10,10, 8,10,
  143797. 9,
  143798. };
  143799. static float _vq_quantthresh__44u1__p2_0[] = {
  143800. -0.5, 0.5,
  143801. };
  143802. static long _vq_quantmap__44u1__p2_0[] = {
  143803. 1, 0, 2,
  143804. };
  143805. static encode_aux_threshmatch _vq_auxt__44u1__p2_0 = {
  143806. _vq_quantthresh__44u1__p2_0,
  143807. _vq_quantmap__44u1__p2_0,
  143808. 3,
  143809. 3
  143810. };
  143811. static static_codebook _44u1__p2_0 = {
  143812. 4, 81,
  143813. _vq_lengthlist__44u1__p2_0,
  143814. 1, -535822336, 1611661312, 2, 0,
  143815. _vq_quantlist__44u1__p2_0,
  143816. NULL,
  143817. &_vq_auxt__44u1__p2_0,
  143818. NULL,
  143819. 0
  143820. };
  143821. static long _vq_quantlist__44u1__p3_0[] = {
  143822. 2,
  143823. 1,
  143824. 3,
  143825. 0,
  143826. 4,
  143827. };
  143828. static long _vq_lengthlist__44u1__p3_0[] = {
  143829. 1, 5, 5, 8, 8, 5, 8, 7, 9, 9, 5, 7, 8, 9, 9, 9,
  143830. 10, 9,12,12, 9, 9,10,12,12, 6, 8, 8,11,10, 8,10,
  143831. 10,11,11, 8, 9,10,11,11,10,11,11,14,13,10,11,11,
  143832. 13,13, 5, 8, 8,10,10, 8,10,10,11,11, 8,10,10,11,
  143833. 11,10,11,11,13,13,10,11,11,13,13, 9,11,11,15,14,
  143834. 10,12,12,15,14,10,12,11,15,14,13,14,14,16,16,12,
  143835. 14,13,17,15, 9,11,11,14,15,10,11,12,14,16,10,11,
  143836. 12,14,16,12,13,14,16,16,13,13,15,15,18, 5, 8, 8,
  143837. 11,11, 8,10,10,12,12, 8,10,10,12,13,11,12,12,14,
  143838. 14,11,12,12,15,15, 8,10,10,13,13,10,12,12,13,13,
  143839. 10,12,12,14,14,12,13,13,15,15,12,13,13,16,16, 7,
  143840. 10,10,12,12,10,12,11,13,13,10,12,12,13,14,12,13,
  143841. 12,15,14,12,13,13,16,16,10,12,12,17,16,12,13,13,
  143842. 16,15,11,13,13,17,17,15,15,15,16,17,14,15,15,19,
  143843. 19,10,12,12,15,16,11,13,12,15,18,11,13,13,16,16,
  143844. 14,15,15,17,17,14,15,15,17,19, 5, 8, 8,11,11, 8,
  143845. 10,10,12,12, 8,10,10,12,12,11,12,12,16,15,11,12,
  143846. 12,14,15, 7,10,10,13,13,10,12,12,14,13,10,11,12,
  143847. 13,13,12,13,13,16,16,12,12,13,15,15, 8,10,10,13,
  143848. 13,10,12,12,14,14,10,12,12,13,13,12,13,13,16,16,
  143849. 12,13,13,15,15,10,12,12,16,15,11,13,13,17,16,11,
  143850. 12,13,16,15,13,15,15,19,17,14,15,14,17,16,10,12,
  143851. 12,16,16,11,13,13,16,17,12,13,13,15,17,14,15,15,
  143852. 17,19,14,15,15,17,17, 8,11,11,16,16,10,13,12,17,
  143853. 17,10,12,13,16,16,15,17,16,20,19,14,15,17,18,19,
  143854. 9,12,12,16,17,11,13,14,17,18,11,13,13,19,18,16,
  143855. 17,18,19,19,15,16,16,19,19, 9,12,12,16,17,11,14,
  143856. 13,18,17,11,13,13,17,17,16,17,16,20,19,14,16,16,
  143857. 18,18,12,15,15,19,17,14,15,16, 0,20,13,15,16,20,
  143858. 17,18,16,20, 0, 0,15,16,19,20, 0,12,15,14,18,19,
  143859. 13,16,15,20,19,13,16,15,20,18,17,18,17, 0,20,16,
  143860. 17,16, 0, 0, 8,11,11,16,15,10,12,12,17,17,10,13,
  143861. 13,17,16,14,16,15,18,20,15,16,16,19,19, 9,12,12,
  143862. 16,16,11,13,13,17,16,11,13,14,17,18,15,15,16,20,
  143863. 20,16,16,17,19,19, 9,13,12,16,17,11,14,13,17,17,
  143864. 11,14,14,18,17,14,16,15,18,19,16,17,18,18,19,12,
  143865. 14,15,19,18,13,15,16,18, 0,13,14,15, 0, 0,16,16,
  143866. 17,20, 0,17,17,20,20, 0,12,15,15,19,20,13,15,15,
  143867. 0, 0,14,16,15, 0, 0,15,18,16, 0, 0,17,18,16, 0,
  143868. 19,
  143869. };
  143870. static float _vq_quantthresh__44u1__p3_0[] = {
  143871. -1.5, -0.5, 0.5, 1.5,
  143872. };
  143873. static long _vq_quantmap__44u1__p3_0[] = {
  143874. 3, 1, 0, 2, 4,
  143875. };
  143876. static encode_aux_threshmatch _vq_auxt__44u1__p3_0 = {
  143877. _vq_quantthresh__44u1__p3_0,
  143878. _vq_quantmap__44u1__p3_0,
  143879. 5,
  143880. 5
  143881. };
  143882. static static_codebook _44u1__p3_0 = {
  143883. 4, 625,
  143884. _vq_lengthlist__44u1__p3_0,
  143885. 1, -533725184, 1611661312, 3, 0,
  143886. _vq_quantlist__44u1__p3_0,
  143887. NULL,
  143888. &_vq_auxt__44u1__p3_0,
  143889. NULL,
  143890. 0
  143891. };
  143892. static long _vq_quantlist__44u1__p4_0[] = {
  143893. 2,
  143894. 1,
  143895. 3,
  143896. 0,
  143897. 4,
  143898. };
  143899. static long _vq_lengthlist__44u1__p4_0[] = {
  143900. 4, 5, 5, 9, 9, 5, 6, 6, 9, 9, 5, 6, 6, 9, 9, 9,
  143901. 10, 9,12,12, 9, 9,10,12,12, 5, 7, 7,10,10, 7, 7,
  143902. 8,10,10, 6, 7, 8,10,10,10,10,10,11,13,10, 9,10,
  143903. 12,13, 5, 7, 7,10,10, 6, 8, 7,10,10, 7, 8, 7,10,
  143904. 10, 9,10,10,12,12,10,10,10,13,11, 9,10,10,13,13,
  143905. 10,11,10,13,13,10,10,10,13,13,12,12,13,14,14,12,
  143906. 12,13,14,14, 9,10,10,13,13,10,10,10,13,13,10,10,
  143907. 10,13,13,12,13,12,15,14,12,13,12,15,15, 5, 7, 6,
  143908. 10,10, 7, 8, 8,10,10, 7, 8, 8,10,10,10,11,10,13,
  143909. 13,10,10,10,12,12, 7, 8, 8,11,10, 8, 8, 9,10,11,
  143910. 8, 9, 9,11,11,11,10,11,11,14,11,11,11,13,13, 6,
  143911. 8, 8,10,10, 7, 9, 8,11,10, 8, 9, 9,11,11,10,11,
  143912. 10,14,11,10,11,11,13,13,10,11,11,14,13,10,10,11,
  143913. 14,13,10,11,11,14,14,12,11,13,12,16,13,14,14,15,
  143914. 15,10,10,11,13,14,10,11,10,14,13,10,11,11,14,14,
  143915. 12,13,12,15,13,13,13,14,15,16, 5, 7, 7,10,10, 7,
  143916. 8, 8,10,10, 7, 8, 8,10,10,10,10,10,13,13,10,10,
  143917. 11,12,13, 6, 8, 8,11,10, 8, 9, 9,11,11, 7, 8, 9,
  143918. 10,11,10,11,11,13,13,10,10,11,11,13, 6, 8, 8,10,
  143919. 11, 8, 9, 9,11,11, 8, 9, 8,12,10,10,11,11,13,13,
  143920. 10,11,10,14,11,10,10,10,14,13,10,11,11,14,13,10,
  143921. 10,11,13,13,12,14,14,16,16,12,12,13,13,15,10,11,
  143922. 11,13,14,10,11,11,14,15,10,11,10,13,13,13,14,13,
  143923. 16,16,12,13,11,15,12, 9,10,10,13,13,10,11,11,14,
  143924. 13,10,10,11,13,14,13,14,13,16,16,13,13,13,15,16,
  143925. 9,10,10,13,13,10,10,11,13,14,10,11,11,15,13,13,
  143926. 13,14,14,18,13,13,14,16,15, 9,10,10,13,14,10,11,
  143927. 10,14,13,10,11,11,13,14,13,14,13,16,15,13,13,14,
  143928. 15,16,12,13,12,16,14,11,11,13,15,15,13,14,13,16,
  143929. 15,15,12,16,12,17,14,15,15,17,17,12,13,13,14,16,
  143930. 11,13,11,16,15,12,13,14,15,16,14,15,13, 0,14,14,
  143931. 16,16, 0, 0, 9,10,10,13,13,10,11,10,14,14,10,11,
  143932. 11,13,13,12,13,13,14,16,13,14,14,16,16, 9,10,10,
  143933. 14,14,11,11,11,14,13,10,10,11,14,14,13,13,13,16,
  143934. 16,13,13,14,14,17, 9,10,10,13,14,10,11,11,13,15,
  143935. 10,11,10,14,14,13,13,13,14,17,13,14,13,17,14,12,
  143936. 13,13,16,14,13,14,13,16,15,12,12,13,15,16,15,15,
  143937. 16,18,16,15,13,15,14, 0,12,12,13,14,16,13,13,14,
  143938. 15,16,11,12,11,16,14,15,16,16,17,17,14,15,12,17,
  143939. 12,
  143940. };
  143941. static float _vq_quantthresh__44u1__p4_0[] = {
  143942. -1.5, -0.5, 0.5, 1.5,
  143943. };
  143944. static long _vq_quantmap__44u1__p4_0[] = {
  143945. 3, 1, 0, 2, 4,
  143946. };
  143947. static encode_aux_threshmatch _vq_auxt__44u1__p4_0 = {
  143948. _vq_quantthresh__44u1__p4_0,
  143949. _vq_quantmap__44u1__p4_0,
  143950. 5,
  143951. 5
  143952. };
  143953. static static_codebook _44u1__p4_0 = {
  143954. 4, 625,
  143955. _vq_lengthlist__44u1__p4_0,
  143956. 1, -533725184, 1611661312, 3, 0,
  143957. _vq_quantlist__44u1__p4_0,
  143958. NULL,
  143959. &_vq_auxt__44u1__p4_0,
  143960. NULL,
  143961. 0
  143962. };
  143963. static long _vq_quantlist__44u1__p5_0[] = {
  143964. 4,
  143965. 3,
  143966. 5,
  143967. 2,
  143968. 6,
  143969. 1,
  143970. 7,
  143971. 0,
  143972. 8,
  143973. };
  143974. static long _vq_lengthlist__44u1__p5_0[] = {
  143975. 1, 4, 4, 7, 7, 7, 7, 9, 9, 4, 6, 6, 8, 8, 8, 8,
  143976. 9, 9, 4, 6, 6, 8, 8, 8, 8, 9, 9, 7, 8, 8, 9, 9,
  143977. 9, 9,11,10, 7, 8, 8, 9, 9, 9, 9,10,10, 7, 8, 8,
  143978. 9, 9,10,10,11,11, 7, 8, 8, 9, 9,10,10,11,11, 9,
  143979. 9, 9,10,10,11,11,12,12, 9, 9, 9,10,11,11,11,12,
  143980. 12,
  143981. };
  143982. static float _vq_quantthresh__44u1__p5_0[] = {
  143983. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  143984. };
  143985. static long _vq_quantmap__44u1__p5_0[] = {
  143986. 7, 5, 3, 1, 0, 2, 4, 6,
  143987. 8,
  143988. };
  143989. static encode_aux_threshmatch _vq_auxt__44u1__p5_0 = {
  143990. _vq_quantthresh__44u1__p5_0,
  143991. _vq_quantmap__44u1__p5_0,
  143992. 9,
  143993. 9
  143994. };
  143995. static static_codebook _44u1__p5_0 = {
  143996. 2, 81,
  143997. _vq_lengthlist__44u1__p5_0,
  143998. 1, -531628032, 1611661312, 4, 0,
  143999. _vq_quantlist__44u1__p5_0,
  144000. NULL,
  144001. &_vq_auxt__44u1__p5_0,
  144002. NULL,
  144003. 0
  144004. };
  144005. static long _vq_quantlist__44u1__p6_0[] = {
  144006. 6,
  144007. 5,
  144008. 7,
  144009. 4,
  144010. 8,
  144011. 3,
  144012. 9,
  144013. 2,
  144014. 10,
  144015. 1,
  144016. 11,
  144017. 0,
  144018. 12,
  144019. };
  144020. static long _vq_lengthlist__44u1__p6_0[] = {
  144021. 1, 4, 4, 6, 6, 8, 8,10, 9,11,10,14,13, 4, 6, 5,
  144022. 8, 8, 9, 9,11,10,11,11,14,14, 4, 5, 6, 8, 8, 9,
  144023. 9,10,10,11,11,14,14, 6, 8, 8, 9, 9,10,10,11,11,
  144024. 12,12,16,15, 7, 8, 8, 9, 9,10,10,11,11,12,12,15,
  144025. 15, 9,10,10,10,10,11,11,12,12,12,12,15,15, 9,10,
  144026. 9,10,11,11,11,12,12,12,13,15,15,10,10,11,11,11,
  144027. 12,12,13,12,13,13,16,15,10,11,11,11,11,12,12,13,
  144028. 12,13,13,16,17,11,11,12,12,12,13,13,13,14,14,15,
  144029. 17,17,11,11,12,12,12,13,13,13,14,14,14,16,18,14,
  144030. 15,15,15,15,16,16,16,16,17,18, 0, 0,14,15,15,15,
  144031. 15,17,16,17,18,17,17,18, 0,
  144032. };
  144033. static float _vq_quantthresh__44u1__p6_0[] = {
  144034. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  144035. 12.5, 17.5, 22.5, 27.5,
  144036. };
  144037. static long _vq_quantmap__44u1__p6_0[] = {
  144038. 11, 9, 7, 5, 3, 1, 0, 2,
  144039. 4, 6, 8, 10, 12,
  144040. };
  144041. static encode_aux_threshmatch _vq_auxt__44u1__p6_0 = {
  144042. _vq_quantthresh__44u1__p6_0,
  144043. _vq_quantmap__44u1__p6_0,
  144044. 13,
  144045. 13
  144046. };
  144047. static static_codebook _44u1__p6_0 = {
  144048. 2, 169,
  144049. _vq_lengthlist__44u1__p6_0,
  144050. 1, -526516224, 1616117760, 4, 0,
  144051. _vq_quantlist__44u1__p6_0,
  144052. NULL,
  144053. &_vq_auxt__44u1__p6_0,
  144054. NULL,
  144055. 0
  144056. };
  144057. static long _vq_quantlist__44u1__p6_1[] = {
  144058. 2,
  144059. 1,
  144060. 3,
  144061. 0,
  144062. 4,
  144063. };
  144064. static long _vq_lengthlist__44u1__p6_1[] = {
  144065. 2, 4, 4, 5, 5, 4, 5, 5, 5, 5, 4, 5, 5, 5, 5, 5,
  144066. 6, 6, 6, 6, 5, 6, 6, 6, 6,
  144067. };
  144068. static float _vq_quantthresh__44u1__p6_1[] = {
  144069. -1.5, -0.5, 0.5, 1.5,
  144070. };
  144071. static long _vq_quantmap__44u1__p6_1[] = {
  144072. 3, 1, 0, 2, 4,
  144073. };
  144074. static encode_aux_threshmatch _vq_auxt__44u1__p6_1 = {
  144075. _vq_quantthresh__44u1__p6_1,
  144076. _vq_quantmap__44u1__p6_1,
  144077. 5,
  144078. 5
  144079. };
  144080. static static_codebook _44u1__p6_1 = {
  144081. 2, 25,
  144082. _vq_lengthlist__44u1__p6_1,
  144083. 1, -533725184, 1611661312, 3, 0,
  144084. _vq_quantlist__44u1__p6_1,
  144085. NULL,
  144086. &_vq_auxt__44u1__p6_1,
  144087. NULL,
  144088. 0
  144089. };
  144090. static long _vq_quantlist__44u1__p7_0[] = {
  144091. 3,
  144092. 2,
  144093. 4,
  144094. 1,
  144095. 5,
  144096. 0,
  144097. 6,
  144098. };
  144099. static long _vq_lengthlist__44u1__p7_0[] = {
  144100. 1, 3, 2, 9, 9, 7, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  144101. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  144102. 9, 9, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  144103. 8,
  144104. };
  144105. static float _vq_quantthresh__44u1__p7_0[] = {
  144106. -422.5, -253.5, -84.5, 84.5, 253.5, 422.5,
  144107. };
  144108. static long _vq_quantmap__44u1__p7_0[] = {
  144109. 5, 3, 1, 0, 2, 4, 6,
  144110. };
  144111. static encode_aux_threshmatch _vq_auxt__44u1__p7_0 = {
  144112. _vq_quantthresh__44u1__p7_0,
  144113. _vq_quantmap__44u1__p7_0,
  144114. 7,
  144115. 7
  144116. };
  144117. static static_codebook _44u1__p7_0 = {
  144118. 2, 49,
  144119. _vq_lengthlist__44u1__p7_0,
  144120. 1, -518017024, 1626677248, 3, 0,
  144121. _vq_quantlist__44u1__p7_0,
  144122. NULL,
  144123. &_vq_auxt__44u1__p7_0,
  144124. NULL,
  144125. 0
  144126. };
  144127. static long _vq_quantlist__44u1__p7_1[] = {
  144128. 6,
  144129. 5,
  144130. 7,
  144131. 4,
  144132. 8,
  144133. 3,
  144134. 9,
  144135. 2,
  144136. 10,
  144137. 1,
  144138. 11,
  144139. 0,
  144140. 12,
  144141. };
  144142. static long _vq_lengthlist__44u1__p7_1[] = {
  144143. 1, 4, 4, 6, 6, 6, 6, 7, 7, 8, 8, 9, 9, 5, 7, 7,
  144144. 8, 7, 7, 7, 9, 8,10, 9,10,11, 5, 7, 7, 8, 8, 7,
  144145. 7, 8, 9,10,10,11,11, 6, 8, 8, 9, 9, 9, 9,11,10,
  144146. 12,12,15,12, 6, 8, 8, 9, 9, 9, 9,11,11,12,11,14,
  144147. 12, 7, 8, 8,10,10,12,12,13,13,13,15,13,13, 7, 8,
  144148. 8,10,10,11,11,13,12,14,15,15,15, 9,10,10,11,12,
  144149. 13,13,14,15,14,15,14,15, 8,10,10,12,12,14,14,15,
  144150. 14,14,15,15,14,10,12,12,14,14,15,14,15,15,15,14,
  144151. 15,15,10,12,12,13,14,15,14,15,15,14,15,15,15,12,
  144152. 15,13,15,14,15,15,15,15,15,15,15,15,13,13,15,15,
  144153. 15,15,15,15,15,15,15,15,15,
  144154. };
  144155. static float _vq_quantthresh__44u1__p7_1[] = {
  144156. -71.5, -58.5, -45.5, -32.5, -19.5, -6.5, 6.5, 19.5,
  144157. 32.5, 45.5, 58.5, 71.5,
  144158. };
  144159. static long _vq_quantmap__44u1__p7_1[] = {
  144160. 11, 9, 7, 5, 3, 1, 0, 2,
  144161. 4, 6, 8, 10, 12,
  144162. };
  144163. static encode_aux_threshmatch _vq_auxt__44u1__p7_1 = {
  144164. _vq_quantthresh__44u1__p7_1,
  144165. _vq_quantmap__44u1__p7_1,
  144166. 13,
  144167. 13
  144168. };
  144169. static static_codebook _44u1__p7_1 = {
  144170. 2, 169,
  144171. _vq_lengthlist__44u1__p7_1,
  144172. 1, -523010048, 1618608128, 4, 0,
  144173. _vq_quantlist__44u1__p7_1,
  144174. NULL,
  144175. &_vq_auxt__44u1__p7_1,
  144176. NULL,
  144177. 0
  144178. };
  144179. static long _vq_quantlist__44u1__p7_2[] = {
  144180. 6,
  144181. 5,
  144182. 7,
  144183. 4,
  144184. 8,
  144185. 3,
  144186. 9,
  144187. 2,
  144188. 10,
  144189. 1,
  144190. 11,
  144191. 0,
  144192. 12,
  144193. };
  144194. static long _vq_lengthlist__44u1__p7_2[] = {
  144195. 2, 5, 4, 6, 6, 7, 7, 8, 8, 8, 8, 9, 8, 5, 5, 6,
  144196. 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 5, 6, 5, 7, 7, 8,
  144197. 8, 8, 8, 9, 9, 9, 9, 6, 7, 7, 8, 8, 8, 8, 9, 8,
  144198. 9, 9, 9, 9, 6, 7, 7, 8, 7, 8, 8, 9, 9, 9, 9, 9,
  144199. 9, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 7, 8,
  144200. 8, 9, 8, 9, 8, 9, 9, 9, 9, 9, 9, 8, 9, 8, 9, 9,
  144201. 9, 9, 9, 9, 9, 9,10,10, 8, 8, 9, 9, 9, 9, 9, 9,
  144202. 9, 9,10, 9,10, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  144203. 9, 9, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  144204. 9, 9, 9, 9, 9, 9, 9, 9,10,10,10, 9, 9, 9, 9, 9,
  144205. 9, 9, 9,10, 9, 9,10,10, 9,
  144206. };
  144207. static float _vq_quantthresh__44u1__p7_2[] = {
  144208. -5.5, -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5,
  144209. 2.5, 3.5, 4.5, 5.5,
  144210. };
  144211. static long _vq_quantmap__44u1__p7_2[] = {
  144212. 11, 9, 7, 5, 3, 1, 0, 2,
  144213. 4, 6, 8, 10, 12,
  144214. };
  144215. static encode_aux_threshmatch _vq_auxt__44u1__p7_2 = {
  144216. _vq_quantthresh__44u1__p7_2,
  144217. _vq_quantmap__44u1__p7_2,
  144218. 13,
  144219. 13
  144220. };
  144221. static static_codebook _44u1__p7_2 = {
  144222. 2, 169,
  144223. _vq_lengthlist__44u1__p7_2,
  144224. 1, -531103744, 1611661312, 4, 0,
  144225. _vq_quantlist__44u1__p7_2,
  144226. NULL,
  144227. &_vq_auxt__44u1__p7_2,
  144228. NULL,
  144229. 0
  144230. };
  144231. static long _huff_lengthlist__44u1__short[] = {
  144232. 12,13,14,13,17,12,15,17, 5, 5, 6,10,10,11,15,16,
  144233. 4, 3, 3, 7, 5, 7,10,16, 7, 7, 7,10, 9,11,12,16,
  144234. 6, 5, 5, 9, 5, 6,10,16, 8, 7, 7, 9, 6, 7, 9,16,
  144235. 11, 7, 3, 6, 4, 5, 8,16,12, 9, 4, 8, 5, 7, 9,16,
  144236. };
  144237. static static_codebook _huff_book__44u1__short = {
  144238. 2, 64,
  144239. _huff_lengthlist__44u1__short,
  144240. 0, 0, 0, 0, 0,
  144241. NULL,
  144242. NULL,
  144243. NULL,
  144244. NULL,
  144245. 0
  144246. };
  144247. static long _huff_lengthlist__44u2__long[] = {
  144248. 5, 9,14,12,15,13,10,13, 7, 4, 5, 6, 8, 7, 8,12,
  144249. 13, 4, 3, 5, 5, 6, 9,15,12, 6, 5, 6, 6, 6, 7,14,
  144250. 14, 7, 4, 6, 4, 6, 8,15,12, 6, 6, 5, 5, 5, 6,14,
  144251. 9, 7, 8, 6, 7, 5, 4,10,10,13,14,14,15,10, 6, 8,
  144252. };
  144253. static static_codebook _huff_book__44u2__long = {
  144254. 2, 64,
  144255. _huff_lengthlist__44u2__long,
  144256. 0, 0, 0, 0, 0,
  144257. NULL,
  144258. NULL,
  144259. NULL,
  144260. NULL,
  144261. 0
  144262. };
  144263. static long _vq_quantlist__44u2__p1_0[] = {
  144264. 1,
  144265. 0,
  144266. 2,
  144267. };
  144268. static long _vq_lengthlist__44u2__p1_0[] = {
  144269. 1, 4, 4, 5, 8, 7, 5, 7, 8, 5, 8, 8, 8,11,11, 8,
  144270. 10,11, 5, 8, 8, 8,11,10, 8,11,11, 4, 8, 8, 8,11,
  144271. 11, 8,11,11, 8,11,11,11,13,14,11,13,13, 7,11,11,
  144272. 10,13,12,11,14,14, 4, 8, 8, 8,11,11, 8,11,11, 8,
  144273. 11,11,11,14,13,10,12,13, 8,11,11,11,13,13,11,13,
  144274. 13,
  144275. };
  144276. static float _vq_quantthresh__44u2__p1_0[] = {
  144277. -0.5, 0.5,
  144278. };
  144279. static long _vq_quantmap__44u2__p1_0[] = {
  144280. 1, 0, 2,
  144281. };
  144282. static encode_aux_threshmatch _vq_auxt__44u2__p1_0 = {
  144283. _vq_quantthresh__44u2__p1_0,
  144284. _vq_quantmap__44u2__p1_0,
  144285. 3,
  144286. 3
  144287. };
  144288. static static_codebook _44u2__p1_0 = {
  144289. 4, 81,
  144290. _vq_lengthlist__44u2__p1_0,
  144291. 1, -535822336, 1611661312, 2, 0,
  144292. _vq_quantlist__44u2__p1_0,
  144293. NULL,
  144294. &_vq_auxt__44u2__p1_0,
  144295. NULL,
  144296. 0
  144297. };
  144298. static long _vq_quantlist__44u2__p2_0[] = {
  144299. 1,
  144300. 0,
  144301. 2,
  144302. };
  144303. static long _vq_lengthlist__44u2__p2_0[] = {
  144304. 2, 5, 5, 5, 6, 6, 5, 6, 6, 5, 6, 6, 7, 8, 8, 6,
  144305. 8, 8, 5, 6, 6, 6, 8, 7, 7, 8, 8, 5, 6, 6, 7, 8,
  144306. 8, 6, 8, 8, 6, 8, 8, 8, 9,10, 8,10,10, 6, 8, 8,
  144307. 7,10, 8, 8,10,10, 5, 6, 6, 6, 8, 8, 7, 8, 8, 6,
  144308. 8, 8, 8,10,10, 8, 8,10, 6, 8, 8, 8,10,10, 8,10,
  144309. 9,
  144310. };
  144311. static float _vq_quantthresh__44u2__p2_0[] = {
  144312. -0.5, 0.5,
  144313. };
  144314. static long _vq_quantmap__44u2__p2_0[] = {
  144315. 1, 0, 2,
  144316. };
  144317. static encode_aux_threshmatch _vq_auxt__44u2__p2_0 = {
  144318. _vq_quantthresh__44u2__p2_0,
  144319. _vq_quantmap__44u2__p2_0,
  144320. 3,
  144321. 3
  144322. };
  144323. static static_codebook _44u2__p2_0 = {
  144324. 4, 81,
  144325. _vq_lengthlist__44u2__p2_0,
  144326. 1, -535822336, 1611661312, 2, 0,
  144327. _vq_quantlist__44u2__p2_0,
  144328. NULL,
  144329. &_vq_auxt__44u2__p2_0,
  144330. NULL,
  144331. 0
  144332. };
  144333. static long _vq_quantlist__44u2__p3_0[] = {
  144334. 2,
  144335. 1,
  144336. 3,
  144337. 0,
  144338. 4,
  144339. };
  144340. static long _vq_lengthlist__44u2__p3_0[] = {
  144341. 2, 4, 4, 7, 8, 5, 7, 7, 9, 9, 5, 7, 7, 9, 9, 8,
  144342. 9, 9,12,11, 8, 9, 9,11,12, 5, 7, 7,10,10, 7, 9,
  144343. 9,11,11, 7, 9, 9,10,11,10,11,11,13,13, 9,10,11,
  144344. 12,13, 5, 7, 7,10,10, 7, 9, 9,11,10, 7, 9, 9,11,
  144345. 11, 9,11,10,13,13,10,11,11,13,13, 8,10,10,14,13,
  144346. 10,11,11,15,14, 9,11,11,15,14,13,14,13,16,14,12,
  144347. 13,13,15,16, 8,10,10,13,14, 9,11,11,14,15,10,11,
  144348. 11,14,15,12,13,13,15,15,12,13,14,15,16, 5, 7, 7,
  144349. 10,10, 7, 9, 9,11,11, 7, 9, 9,11,12,10,11,11,14,
  144350. 13,10,11,11,14,14, 7, 9, 9,12,12, 9,11,11,13,13,
  144351. 9,11,11,13,13,12,13,12,14,14,11,12,13,15,15, 7,
  144352. 9, 9,12,12, 8,11,10,13,12, 9,11,11,13,13,11,13,
  144353. 12,15,13,11,13,13,15,16, 9,12,11,15,15,11,12,12,
  144354. 16,15,11,12,13,16,16,13,14,15,16,15,13,15,15,17,
  144355. 17, 9,11,11,14,15,10,12,12,15,15,11,13,12,15,16,
  144356. 13,15,14,16,16,13,15,15,17,19, 5, 7, 7,10,10, 7,
  144357. 9, 9,12,11, 7, 9, 9,11,11,10,11,11,14,14,10,11,
  144358. 11,13,14, 7, 9, 9,12,12, 9,11,11,13,13, 9,10,11,
  144359. 12,13,11,13,12,16,15,11,12,12,14,15, 7, 9, 9,12,
  144360. 12, 9,11,11,13,13, 9,11,11,13,12,11,13,12,15,16,
  144361. 12,13,13,15,14, 9,11,11,15,14,11,13,12,16,15,10,
  144362. 11,12,15,15,13,14,14,18,17,13,14,14,15,17,10,11,
  144363. 11,14,15,11,13,12,15,17,11,13,12,15,16,13,15,14,
  144364. 18,17,14,15,15,16,18, 7,10,10,14,14,10,12,12,15,
  144365. 15,10,12,12,15,15,14,15,15,18,17,13,15,15,16,16,
  144366. 9,11,11,16,15,11,13,13,16,18,11,13,13,16,16,15,
  144367. 16,16, 0, 0,14,15,16,18,17, 9,11,11,15,15,10,13,
  144368. 12,17,16,11,12,13,16,17,14,15,16,19,19,14,15,15,
  144369. 0,20,12,14,14, 0, 0,13,14,16,19,18,13,15,16,20,
  144370. 17,16,18, 0, 0, 0,15,16,17,18,19,11,14,14, 0,19,
  144371. 12,15,14,17,17,13,15,15, 0, 0,16,17,15,20,19,15,
  144372. 17,16,19, 0, 8,10,10,14,15,10,12,11,15,15,10,11,
  144373. 12,16,15,13,14,14,19,17,14,15,15, 0, 0, 9,11,11,
  144374. 16,15,11,13,13,17,16,10,12,13,16,17,14,15,15,18,
  144375. 18,14,15,16,20,19, 9,12,12, 0,15,11,13,13,16,17,
  144376. 11,13,13,19,17,14,16,16,18,17,15,16,16,17,19,11,
  144377. 14,14,18,18,13,14,15, 0, 0,12,14,15,19,18,15,16,
  144378. 19, 0,19,15,16,19,19,17,12,14,14,16,19,13,15,15,
  144379. 0,17,13,15,14,18,18,15,16,15, 0,18,16,17,17, 0,
  144380. 0,
  144381. };
  144382. static float _vq_quantthresh__44u2__p3_0[] = {
  144383. -1.5, -0.5, 0.5, 1.5,
  144384. };
  144385. static long _vq_quantmap__44u2__p3_0[] = {
  144386. 3, 1, 0, 2, 4,
  144387. };
  144388. static encode_aux_threshmatch _vq_auxt__44u2__p3_0 = {
  144389. _vq_quantthresh__44u2__p3_0,
  144390. _vq_quantmap__44u2__p3_0,
  144391. 5,
  144392. 5
  144393. };
  144394. static static_codebook _44u2__p3_0 = {
  144395. 4, 625,
  144396. _vq_lengthlist__44u2__p3_0,
  144397. 1, -533725184, 1611661312, 3, 0,
  144398. _vq_quantlist__44u2__p3_0,
  144399. NULL,
  144400. &_vq_auxt__44u2__p3_0,
  144401. NULL,
  144402. 0
  144403. };
  144404. static long _vq_quantlist__44u2__p4_0[] = {
  144405. 2,
  144406. 1,
  144407. 3,
  144408. 0,
  144409. 4,
  144410. };
  144411. static long _vq_lengthlist__44u2__p4_0[] = {
  144412. 4, 5, 5, 8, 8, 5, 7, 6, 9, 9, 5, 6, 7, 9, 9, 9,
  144413. 9, 9,11,11, 9, 9, 9,11,11, 5, 7, 7, 9, 9, 7, 8,
  144414. 8,10,10, 7, 7, 8,10,10,10,10,10,11,12, 9,10,10,
  144415. 11,12, 5, 7, 7, 9, 9, 6, 8, 7,10,10, 7, 8, 8,10,
  144416. 10, 9,10,10,12,11, 9,10,10,12,11, 9,10,10,12,12,
  144417. 10,10,10,13,12, 9,10,10,12,13,12,12,12,14,14,11,
  144418. 12,12,13,14, 9,10,10,12,12, 9,10,10,12,13,10,10,
  144419. 10,12,13,11,12,12,14,13,12,12,12,14,13, 5, 7, 7,
  144420. 10, 9, 7, 8, 8,10,10, 7, 8, 8,10,10,10,10,10,12,
  144421. 12,10,10,10,12,12, 7, 8, 8,11,10, 8, 8, 9,11,11,
  144422. 8, 9, 9,11,11,10,11,11,12,13,10,11,11,13,13, 6,
  144423. 8, 8,10,10, 7, 9, 8,11,10, 8, 9, 9,11,11,10,11,
  144424. 10,13,11,10,11,11,13,13, 9,10,10,13,13,10,11,11,
  144425. 13,13,10,11,11,14,13,12,11,13,12,15,12,13,13,15,
  144426. 15, 9,10,10,12,13,10,11,10,13,13,10,11,11,13,13,
  144427. 12,13,11,15,13,12,13,13,15,15, 5, 7, 7, 9,10, 7,
  144428. 8, 8,10,10, 7, 8, 8,10,10,10,10,10,12,12,10,10,
  144429. 11,12,12, 6, 8, 8,10,10, 8, 9, 9,11,11, 7, 8, 9,
  144430. 10,11,10,11,11,13,13,10,10,11,11,13, 7, 8, 8,10,
  144431. 11, 8, 9, 9,11,11, 8, 9, 8,11,11,10,11,11,13,13,
  144432. 10,11,11,13,12, 9,10,10,13,12,10,11,11,14,13,10,
  144433. 10,11,13,13,12,13,13,15,15,12,11,13,12,14, 9,10,
  144434. 10,12,13,10,11,11,13,14,10,11,11,13,13,12,13,13,
  144435. 15,15,12,13,12,15,12, 8, 9, 9,12,12, 9,11,10,13,
  144436. 13, 9,10,10,13,13,12,13,13,15,15,12,12,12,14,14,
  144437. 9,10,10,13,13,10,11,11,13,14,10,11,11,14,12,13,
  144438. 13,14,14,16,12,13,13,15,14, 9,10,10,13,13,10,11,
  144439. 10,14,13,10,11,11,13,14,12,14,13,16,14,13,13,13,
  144440. 14,15,11,13,12,15,14,11,12,13,14,15,12,13,13,16,
  144441. 15,14,12,15,12,16,14,15,15,17,16,11,12,12,14,15,
  144442. 11,13,11,15,14,12,13,13,15,16,13,15,12,17,13,14,
  144443. 15,15,16,16, 8, 9, 9,12,12, 9,10,10,13,13, 9,10,
  144444. 10,13,13,12,13,12,14,14,12,13,13,15,15, 9,10,10,
  144445. 13,13,10,11,11,14,13,10,10,11,13,14,12,13,13,15,
  144446. 14,12,12,14,14,16, 9,10,10,13,13,10,11,11,13,14,
  144447. 10,11,11,14,13,13,13,13,15,15,13,14,13,16,14,11,
  144448. 12,12,14,14,12,13,13,16,15,11,12,13,14,15,14,15,
  144449. 15,16,16,14,13,15,13,17,11,12,12,14,15,12,13,13,
  144450. 15,16,11,13,12,15,15,14,15,14,16,16,14,15,12,17,
  144451. 13,
  144452. };
  144453. static float _vq_quantthresh__44u2__p4_0[] = {
  144454. -1.5, -0.5, 0.5, 1.5,
  144455. };
  144456. static long _vq_quantmap__44u2__p4_0[] = {
  144457. 3, 1, 0, 2, 4,
  144458. };
  144459. static encode_aux_threshmatch _vq_auxt__44u2__p4_0 = {
  144460. _vq_quantthresh__44u2__p4_0,
  144461. _vq_quantmap__44u2__p4_0,
  144462. 5,
  144463. 5
  144464. };
  144465. static static_codebook _44u2__p4_0 = {
  144466. 4, 625,
  144467. _vq_lengthlist__44u2__p4_0,
  144468. 1, -533725184, 1611661312, 3, 0,
  144469. _vq_quantlist__44u2__p4_0,
  144470. NULL,
  144471. &_vq_auxt__44u2__p4_0,
  144472. NULL,
  144473. 0
  144474. };
  144475. static long _vq_quantlist__44u2__p5_0[] = {
  144476. 4,
  144477. 3,
  144478. 5,
  144479. 2,
  144480. 6,
  144481. 1,
  144482. 7,
  144483. 0,
  144484. 8,
  144485. };
  144486. static long _vq_lengthlist__44u2__p5_0[] = {
  144487. 1, 4, 4, 7, 7, 8, 8, 9, 9, 4, 6, 5, 8, 8, 8, 8,
  144488. 10,10, 4, 5, 6, 8, 8, 8, 8,10,10, 7, 8, 8, 9, 9,
  144489. 9, 9,11,11, 7, 8, 8, 9, 9, 9, 9,11,11, 8, 8, 8,
  144490. 9, 9,10,11,12,12, 8, 8, 8, 9, 9,10,10,12,12,10,
  144491. 10,10,11,11,12,12,13,13,10,10,10,11,11,12,12,13,
  144492. 13,
  144493. };
  144494. static float _vq_quantthresh__44u2__p5_0[] = {
  144495. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  144496. };
  144497. static long _vq_quantmap__44u2__p5_0[] = {
  144498. 7, 5, 3, 1, 0, 2, 4, 6,
  144499. 8,
  144500. };
  144501. static encode_aux_threshmatch _vq_auxt__44u2__p5_0 = {
  144502. _vq_quantthresh__44u2__p5_0,
  144503. _vq_quantmap__44u2__p5_0,
  144504. 9,
  144505. 9
  144506. };
  144507. static static_codebook _44u2__p5_0 = {
  144508. 2, 81,
  144509. _vq_lengthlist__44u2__p5_0,
  144510. 1, -531628032, 1611661312, 4, 0,
  144511. _vq_quantlist__44u2__p5_0,
  144512. NULL,
  144513. &_vq_auxt__44u2__p5_0,
  144514. NULL,
  144515. 0
  144516. };
  144517. static long _vq_quantlist__44u2__p6_0[] = {
  144518. 6,
  144519. 5,
  144520. 7,
  144521. 4,
  144522. 8,
  144523. 3,
  144524. 9,
  144525. 2,
  144526. 10,
  144527. 1,
  144528. 11,
  144529. 0,
  144530. 12,
  144531. };
  144532. static long _vq_lengthlist__44u2__p6_0[] = {
  144533. 1, 4, 4, 6, 6, 8, 8,10,10,11,11,14,13, 4, 6, 5,
  144534. 8, 8, 9, 9,11,10,12,11,15,14, 4, 5, 6, 8, 8, 9,
  144535. 9,11,11,11,11,14,14, 6, 8, 8,10, 9,11,11,11,11,
  144536. 12,12,15,15, 6, 8, 8, 9, 9,11,11,11,12,12,12,15,
  144537. 15, 8,10,10,11,11,11,11,12,12,13,13,15,16, 8,10,
  144538. 10,11,11,11,11,12,12,13,13,16,16,10,11,11,12,12,
  144539. 12,12,13,13,13,13,17,16,10,11,11,12,12,12,12,13,
  144540. 13,13,14,16,17,11,12,12,13,13,13,13,14,14,15,14,
  144541. 18,17,11,12,12,13,13,13,13,14,14,14,15,19,18,14,
  144542. 15,15,15,15,16,16,18,19,18,18, 0, 0,14,15,15,16,
  144543. 15,17,17,16,18,17,18, 0, 0,
  144544. };
  144545. static float _vq_quantthresh__44u2__p6_0[] = {
  144546. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  144547. 12.5, 17.5, 22.5, 27.5,
  144548. };
  144549. static long _vq_quantmap__44u2__p6_0[] = {
  144550. 11, 9, 7, 5, 3, 1, 0, 2,
  144551. 4, 6, 8, 10, 12,
  144552. };
  144553. static encode_aux_threshmatch _vq_auxt__44u2__p6_0 = {
  144554. _vq_quantthresh__44u2__p6_0,
  144555. _vq_quantmap__44u2__p6_0,
  144556. 13,
  144557. 13
  144558. };
  144559. static static_codebook _44u2__p6_0 = {
  144560. 2, 169,
  144561. _vq_lengthlist__44u2__p6_0,
  144562. 1, -526516224, 1616117760, 4, 0,
  144563. _vq_quantlist__44u2__p6_0,
  144564. NULL,
  144565. &_vq_auxt__44u2__p6_0,
  144566. NULL,
  144567. 0
  144568. };
  144569. static long _vq_quantlist__44u2__p6_1[] = {
  144570. 2,
  144571. 1,
  144572. 3,
  144573. 0,
  144574. 4,
  144575. };
  144576. static long _vq_lengthlist__44u2__p6_1[] = {
  144577. 2, 4, 4, 5, 5, 4, 5, 5, 6, 5, 4, 5, 5, 5, 6, 5,
  144578. 6, 5, 6, 6, 5, 5, 6, 6, 6,
  144579. };
  144580. static float _vq_quantthresh__44u2__p6_1[] = {
  144581. -1.5, -0.5, 0.5, 1.5,
  144582. };
  144583. static long _vq_quantmap__44u2__p6_1[] = {
  144584. 3, 1, 0, 2, 4,
  144585. };
  144586. static encode_aux_threshmatch _vq_auxt__44u2__p6_1 = {
  144587. _vq_quantthresh__44u2__p6_1,
  144588. _vq_quantmap__44u2__p6_1,
  144589. 5,
  144590. 5
  144591. };
  144592. static static_codebook _44u2__p6_1 = {
  144593. 2, 25,
  144594. _vq_lengthlist__44u2__p6_1,
  144595. 1, -533725184, 1611661312, 3, 0,
  144596. _vq_quantlist__44u2__p6_1,
  144597. NULL,
  144598. &_vq_auxt__44u2__p6_1,
  144599. NULL,
  144600. 0
  144601. };
  144602. static long _vq_quantlist__44u2__p7_0[] = {
  144603. 4,
  144604. 3,
  144605. 5,
  144606. 2,
  144607. 6,
  144608. 1,
  144609. 7,
  144610. 0,
  144611. 8,
  144612. };
  144613. static long _vq_lengthlist__44u2__p7_0[] = {
  144614. 1, 3, 2,12,12,12,12,12,12, 4,12,12,12,12,12,12,
  144615. 12,12, 5,12,12,12,12,12,12,12,12,12,12,11,11,11,
  144616. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  144617. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  144618. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  144619. 11,
  144620. };
  144621. static float _vq_quantthresh__44u2__p7_0[] = {
  144622. -591.5, -422.5, -253.5, -84.5, 84.5, 253.5, 422.5, 591.5,
  144623. };
  144624. static long _vq_quantmap__44u2__p7_0[] = {
  144625. 7, 5, 3, 1, 0, 2, 4, 6,
  144626. 8,
  144627. };
  144628. static encode_aux_threshmatch _vq_auxt__44u2__p7_0 = {
  144629. _vq_quantthresh__44u2__p7_0,
  144630. _vq_quantmap__44u2__p7_0,
  144631. 9,
  144632. 9
  144633. };
  144634. static static_codebook _44u2__p7_0 = {
  144635. 2, 81,
  144636. _vq_lengthlist__44u2__p7_0,
  144637. 1, -516612096, 1626677248, 4, 0,
  144638. _vq_quantlist__44u2__p7_0,
  144639. NULL,
  144640. &_vq_auxt__44u2__p7_0,
  144641. NULL,
  144642. 0
  144643. };
  144644. static long _vq_quantlist__44u2__p7_1[] = {
  144645. 6,
  144646. 5,
  144647. 7,
  144648. 4,
  144649. 8,
  144650. 3,
  144651. 9,
  144652. 2,
  144653. 10,
  144654. 1,
  144655. 11,
  144656. 0,
  144657. 12,
  144658. };
  144659. static long _vq_lengthlist__44u2__p7_1[] = {
  144660. 1, 4, 4, 7, 6, 7, 6, 8, 7, 9, 7, 9, 8, 4, 7, 6,
  144661. 8, 8, 9, 8,10, 9,10,10,11,11, 4, 7, 7, 8, 8, 8,
  144662. 8, 9,10,11,11,11,11, 6, 8, 8,10,10,10,10,11,11,
  144663. 12,12,12,12, 7, 8, 8,10,10,10,10,11,11,12,12,13,
  144664. 13, 7, 9, 9,11,10,12,12,13,13,14,13,14,14, 7, 9,
  144665. 9,10,11,11,12,13,13,13,13,16,14, 9,10,10,12,12,
  144666. 13,13,14,14,15,16,15,16, 9,10,10,12,12,12,13,14,
  144667. 14,14,15,16,15,10,12,12,13,13,15,13,16,16,15,17,
  144668. 17,17,10,11,11,12,14,14,14,15,15,17,17,15,17,11,
  144669. 12,12,14,14,14,15,15,15,17,16,17,17,10,12,12,13,
  144670. 14,14,14,17,15,17,17,17,17,
  144671. };
  144672. static float _vq_quantthresh__44u2__p7_1[] = {
  144673. -71.5, -58.5, -45.5, -32.5, -19.5, -6.5, 6.5, 19.5,
  144674. 32.5, 45.5, 58.5, 71.5,
  144675. };
  144676. static long _vq_quantmap__44u2__p7_1[] = {
  144677. 11, 9, 7, 5, 3, 1, 0, 2,
  144678. 4, 6, 8, 10, 12,
  144679. };
  144680. static encode_aux_threshmatch _vq_auxt__44u2__p7_1 = {
  144681. _vq_quantthresh__44u2__p7_1,
  144682. _vq_quantmap__44u2__p7_1,
  144683. 13,
  144684. 13
  144685. };
  144686. static static_codebook _44u2__p7_1 = {
  144687. 2, 169,
  144688. _vq_lengthlist__44u2__p7_1,
  144689. 1, -523010048, 1618608128, 4, 0,
  144690. _vq_quantlist__44u2__p7_1,
  144691. NULL,
  144692. &_vq_auxt__44u2__p7_1,
  144693. NULL,
  144694. 0
  144695. };
  144696. static long _vq_quantlist__44u2__p7_2[] = {
  144697. 6,
  144698. 5,
  144699. 7,
  144700. 4,
  144701. 8,
  144702. 3,
  144703. 9,
  144704. 2,
  144705. 10,
  144706. 1,
  144707. 11,
  144708. 0,
  144709. 12,
  144710. };
  144711. static long _vq_lengthlist__44u2__p7_2[] = {
  144712. 2, 5, 5, 6, 6, 7, 7, 8, 7, 8, 8, 8, 8, 5, 6, 6,
  144713. 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 5, 6, 6, 7, 7, 8,
  144714. 7, 8, 8, 8, 8, 8, 8, 6, 7, 7, 7, 8, 8, 8, 8, 8,
  144715. 9, 9, 9, 9, 6, 7, 7, 8, 7, 8, 8, 9, 9, 9, 9, 9,
  144716. 9, 7, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 7, 8,
  144717. 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 8, 8, 8, 8, 9,
  144718. 9, 9, 9, 9, 9, 9, 9, 9, 8, 8, 8, 9, 9, 9, 9, 9,
  144719. 9, 9, 9, 9, 9, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  144720. 9, 9, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 8,
  144721. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 8, 9, 9, 9,
  144722. 9, 9, 9, 9, 9, 9, 9, 9, 9,
  144723. };
  144724. static float _vq_quantthresh__44u2__p7_2[] = {
  144725. -5.5, -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5,
  144726. 2.5, 3.5, 4.5, 5.5,
  144727. };
  144728. static long _vq_quantmap__44u2__p7_2[] = {
  144729. 11, 9, 7, 5, 3, 1, 0, 2,
  144730. 4, 6, 8, 10, 12,
  144731. };
  144732. static encode_aux_threshmatch _vq_auxt__44u2__p7_2 = {
  144733. _vq_quantthresh__44u2__p7_2,
  144734. _vq_quantmap__44u2__p7_2,
  144735. 13,
  144736. 13
  144737. };
  144738. static static_codebook _44u2__p7_2 = {
  144739. 2, 169,
  144740. _vq_lengthlist__44u2__p7_2,
  144741. 1, -531103744, 1611661312, 4, 0,
  144742. _vq_quantlist__44u2__p7_2,
  144743. NULL,
  144744. &_vq_auxt__44u2__p7_2,
  144745. NULL,
  144746. 0
  144747. };
  144748. static long _huff_lengthlist__44u2__short[] = {
  144749. 13,15,17,17,15,15,12,17,11, 9, 7,10,10, 9,12,17,
  144750. 10, 6, 3, 6, 5, 7,10,17,15,10, 6, 9, 8, 9,11,17,
  144751. 15, 8, 4, 7, 3, 5, 9,16,16,10, 5, 8, 4, 5, 8,16,
  144752. 13,11, 5, 8, 3, 3, 5,14,13,12, 7,10, 5, 5, 7,14,
  144753. };
  144754. static static_codebook _huff_book__44u2__short = {
  144755. 2, 64,
  144756. _huff_lengthlist__44u2__short,
  144757. 0, 0, 0, 0, 0,
  144758. NULL,
  144759. NULL,
  144760. NULL,
  144761. NULL,
  144762. 0
  144763. };
  144764. static long _huff_lengthlist__44u3__long[] = {
  144765. 6, 9,13,12,14,11,10,13, 8, 4, 5, 7, 8, 7, 8,12,
  144766. 11, 4, 3, 5, 5, 7, 9,14,11, 6, 5, 6, 6, 6, 7,13,
  144767. 13, 7, 5, 6, 4, 5, 7,14,11, 7, 6, 6, 5, 5, 6,13,
  144768. 9, 7, 8, 6, 7, 5, 3, 9, 9,12,13,12,14,10, 6, 7,
  144769. };
  144770. static static_codebook _huff_book__44u3__long = {
  144771. 2, 64,
  144772. _huff_lengthlist__44u3__long,
  144773. 0, 0, 0, 0, 0,
  144774. NULL,
  144775. NULL,
  144776. NULL,
  144777. NULL,
  144778. 0
  144779. };
  144780. static long _vq_quantlist__44u3__p1_0[] = {
  144781. 1,
  144782. 0,
  144783. 2,
  144784. };
  144785. static long _vq_lengthlist__44u3__p1_0[] = {
  144786. 1, 4, 4, 5, 8, 7, 5, 7, 8, 5, 8, 8, 8,10,11, 8,
  144787. 10,11, 5, 8, 8, 8,11,10, 8,11,11, 4, 8, 8, 8,11,
  144788. 11, 8,11,11, 8,11,11,11,13,14,11,14,14, 8,11,11,
  144789. 10,14,12,11,14,14, 4, 8, 8, 8,11,11, 8,11,11, 7,
  144790. 11,11,11,14,14,10,12,14, 8,11,11,11,14,14,11,14,
  144791. 13,
  144792. };
  144793. static float _vq_quantthresh__44u3__p1_0[] = {
  144794. -0.5, 0.5,
  144795. };
  144796. static long _vq_quantmap__44u3__p1_0[] = {
  144797. 1, 0, 2,
  144798. };
  144799. static encode_aux_threshmatch _vq_auxt__44u3__p1_0 = {
  144800. _vq_quantthresh__44u3__p1_0,
  144801. _vq_quantmap__44u3__p1_0,
  144802. 3,
  144803. 3
  144804. };
  144805. static static_codebook _44u3__p1_0 = {
  144806. 4, 81,
  144807. _vq_lengthlist__44u3__p1_0,
  144808. 1, -535822336, 1611661312, 2, 0,
  144809. _vq_quantlist__44u3__p1_0,
  144810. NULL,
  144811. &_vq_auxt__44u3__p1_0,
  144812. NULL,
  144813. 0
  144814. };
  144815. static long _vq_quantlist__44u3__p2_0[] = {
  144816. 1,
  144817. 0,
  144818. 2,
  144819. };
  144820. static long _vq_lengthlist__44u3__p2_0[] = {
  144821. 2, 5, 4, 5, 6, 6, 5, 6, 6, 5, 6, 6, 7, 8, 8, 6,
  144822. 8, 8, 5, 6, 6, 6, 8, 8, 7, 8, 8, 5, 7, 6, 7, 8,
  144823. 8, 6, 8, 8, 7, 8, 8, 8, 9,10, 8,10,10, 6, 8, 8,
  144824. 8,10, 8, 8,10,10, 5, 6, 6, 6, 8, 8, 7, 8, 8, 6,
  144825. 8, 8, 8,10,10, 8, 8,10, 7, 8, 8, 8,10,10, 8,10,
  144826. 9,
  144827. };
  144828. static float _vq_quantthresh__44u3__p2_0[] = {
  144829. -0.5, 0.5,
  144830. };
  144831. static long _vq_quantmap__44u3__p2_0[] = {
  144832. 1, 0, 2,
  144833. };
  144834. static encode_aux_threshmatch _vq_auxt__44u3__p2_0 = {
  144835. _vq_quantthresh__44u3__p2_0,
  144836. _vq_quantmap__44u3__p2_0,
  144837. 3,
  144838. 3
  144839. };
  144840. static static_codebook _44u3__p2_0 = {
  144841. 4, 81,
  144842. _vq_lengthlist__44u3__p2_0,
  144843. 1, -535822336, 1611661312, 2, 0,
  144844. _vq_quantlist__44u3__p2_0,
  144845. NULL,
  144846. &_vq_auxt__44u3__p2_0,
  144847. NULL,
  144848. 0
  144849. };
  144850. static long _vq_quantlist__44u3__p3_0[] = {
  144851. 2,
  144852. 1,
  144853. 3,
  144854. 0,
  144855. 4,
  144856. };
  144857. static long _vq_lengthlist__44u3__p3_0[] = {
  144858. 2, 4, 4, 7, 7, 5, 7, 7, 9, 9, 5, 7, 7, 9, 9, 8,
  144859. 9, 9,12,12, 8, 9, 9,11,12, 5, 7, 7,10,10, 7, 9,
  144860. 9,11,11, 7, 9, 9,10,11,10,11,11,13,13, 9,10,11,
  144861. 13,13, 5, 7, 7,10,10, 7, 9, 9,11,10, 7, 9, 9,11,
  144862. 11, 9,11,10,13,13,10,11,11,14,13, 8,10,10,14,13,
  144863. 10,11,11,15,14, 9,11,11,14,14,13,14,13,16,16,12,
  144864. 13,13,15,15, 8,10,10,13,14, 9,11,11,14,14,10,11,
  144865. 11,14,15,12,13,13,15,15,13,14,14,15,16, 5, 7, 7,
  144866. 10,10, 7, 9, 9,11,11, 7, 9, 9,11,12,10,11,11,14,
  144867. 14,10,11,11,14,14, 7, 9, 9,12,12, 9,11,11,13,13,
  144868. 9,11,11,13,13,12,12,13,15,15,11,12,13,15,16, 7,
  144869. 9, 9,11,11, 8,11,10,13,12, 9,11,11,13,13,11,13,
  144870. 12,15,13,11,13,13,15,16, 9,12,11,15,14,11,12,13,
  144871. 16,15,11,13,13,15,16,14,14,15,17,16,13,15,16, 0,
  144872. 17, 9,11,11,15,15,10,13,12,15,15,11,13,13,15,16,
  144873. 13,15,13,16,15,14,16,15, 0,19, 5, 7, 7,10,10, 7,
  144874. 9, 9,11,11, 7, 9, 9,11,11,10,12,11,14,14,10,11,
  144875. 12,14,14, 7, 9, 9,12,12, 9,11,11,14,13, 9,10,11,
  144876. 12,13,11,13,13,16,16,11,12,13,13,16, 7, 9, 9,12,
  144877. 12, 9,11,11,13,13, 9,11,11,13,13,11,13,13,15,15,
  144878. 12,13,12,15,14, 9,11,11,15,14,11,13,12,16,16,10,
  144879. 12,12,15,15,13,15,15,17,19,13,14,15,16,17,10,12,
  144880. 12,15,15,11,13,13,16,16,11,13,13,15,16,13,15,15,
  144881. 0, 0,14,15,15,16,16, 8,10,10,14,14,10,12,12,15,
  144882. 15,10,12,11,15,16,14,15,15,19,20,13,14,14,18,16,
  144883. 9,11,11,15,15,11,13,13,17,16,11,13,13,16,16,15,
  144884. 17,17,20,20,14,15,16,17,20, 9,11,11,15,15,10,13,
  144885. 12,16,15,11,13,13,15,17,14,16,15,18, 0,14,16,15,
  144886. 18,20,12,14,14, 0, 0,14,14,16, 0, 0,13,16,15, 0,
  144887. 0,17,17,18, 0, 0,16,17,19,19, 0,12,14,14,18, 0,
  144888. 12,16,14, 0,17,13,15,15,18, 0,16,18,17, 0,17,16,
  144889. 18,17, 0, 0, 7,10,10,14,14,10,12,11,15,15,10,12,
  144890. 12,16,15,13,15,15,18, 0,14,15,15,17, 0, 9,11,11,
  144891. 15,15,11,13,13,16,16,11,12,13,16,16,14,15,16,17,
  144892. 17,14,16,16,16,18, 9,11,12,16,16,11,13,13,17,17,
  144893. 11,14,13,20,17,15,16,16,19, 0,15,16,17, 0,19,11,
  144894. 13,14,17,16,14,15,15,20,18,13,14,15,17,19,16,18,
  144895. 18, 0,20,16,16,19,17, 0,12,15,14,17, 0,14,15,15,
  144896. 18,19,13,16,15,19,20,15,18,18, 0,20,17, 0,16, 0,
  144897. 0,
  144898. };
  144899. static float _vq_quantthresh__44u3__p3_0[] = {
  144900. -1.5, -0.5, 0.5, 1.5,
  144901. };
  144902. static long _vq_quantmap__44u3__p3_0[] = {
  144903. 3, 1, 0, 2, 4,
  144904. };
  144905. static encode_aux_threshmatch _vq_auxt__44u3__p3_0 = {
  144906. _vq_quantthresh__44u3__p3_0,
  144907. _vq_quantmap__44u3__p3_0,
  144908. 5,
  144909. 5
  144910. };
  144911. static static_codebook _44u3__p3_0 = {
  144912. 4, 625,
  144913. _vq_lengthlist__44u3__p3_0,
  144914. 1, -533725184, 1611661312, 3, 0,
  144915. _vq_quantlist__44u3__p3_0,
  144916. NULL,
  144917. &_vq_auxt__44u3__p3_0,
  144918. NULL,
  144919. 0
  144920. };
  144921. static long _vq_quantlist__44u3__p4_0[] = {
  144922. 2,
  144923. 1,
  144924. 3,
  144925. 0,
  144926. 4,
  144927. };
  144928. static long _vq_lengthlist__44u3__p4_0[] = {
  144929. 4, 5, 5, 8, 8, 5, 7, 6, 9, 9, 5, 6, 7, 9, 9, 9,
  144930. 9, 9,11,11, 9, 9, 9,11,11, 5, 7, 7, 9, 9, 7, 8,
  144931. 8,10,10, 7, 7, 8,10,10, 9,10,10,11,12, 9,10,10,
  144932. 11,12, 5, 7, 7, 9, 9, 7, 8, 7,10,10, 7, 8, 8,10,
  144933. 10, 9,10, 9,12,11, 9,10,10,12,11, 9,10, 9,12,12,
  144934. 9,10,10,13,12, 9,10,10,12,13,12,12,12,14,14,11,
  144935. 12,12,13,14, 9, 9,10,12,12, 9,10,10,12,12, 9,10,
  144936. 10,12,13,11,12,11,14,13,12,12,12,14,13, 5, 7, 7,
  144937. 9, 9, 7, 8, 8,10,10, 7, 8, 8,10,10,10,10,10,12,
  144938. 12, 9,10,10,12,12, 7, 8, 8,11,10, 8, 8, 9,11,11,
  144939. 8, 9, 9,11,11,11,11,11,12,13,10,11,11,13,13, 6,
  144940. 8, 8,10,10, 7, 9, 8,11,10, 8, 9, 9,11,11,10,11,
  144941. 10,13,11,10,11,11,13,13, 9,11,10,13,12,10,11,11,
  144942. 13,13,10,11,11,13,13,12,12,13,12,15,12,13,13,15,
  144943. 15, 9,10,10,12,13,10,11,10,13,12,10,11,11,13,14,
  144944. 12,13,11,15,13,12,13,13,15,15, 5, 7, 7, 9, 9, 7,
  144945. 8, 8,10,10, 7, 8, 8,10,10, 9,10,10,12,12,10,10,
  144946. 11,12,12, 6, 8, 8,10,10, 8, 9, 9,11,11, 7, 8, 9,
  144947. 10,11,10,11,11,13,13,10,10,11,11,13, 7, 8, 8,10,
  144948. 10, 8, 9, 9,11,11, 8, 9, 9,11,11,10,11,11,13,13,
  144949. 11,11,11,13,12, 9,10,10,13,12,10,11,11,14,13,10,
  144950. 10,11,12,13,12,13,13,15,15,12,11,13,13,14, 9,10,
  144951. 11,12,13,10,11,11,13,13,10,11,11,13,13,12,13,13,
  144952. 15,15,12,13,12,15,12, 8, 9, 9,12,12, 9,11,10,13,
  144953. 13, 9,10,10,13,13,12,13,13,15,14,12,12,12,14,13,
  144954. 9,10,10,13,12,10,11,11,13,13,10,11,11,14,12,13,
  144955. 13,14,14,16,12,13,13,15,15, 9,10,10,13,13,10,11,
  144956. 10,14,13,10,11,11,13,14,12,14,13,15,14,13,13,13,
  144957. 15,15,11,13,12,15,14,11,12,13,14,15,12,13,13,16,
  144958. 14,14,12,15,12,16,14,15,15,17,15,11,12,12,14,14,
  144959. 11,13,11,15,14,12,13,13,15,15,13,15,12,17,13,14,
  144960. 15,15,16,16, 8, 9, 9,12,12, 9,10,10,12,13, 9,10,
  144961. 10,13,13,12,12,12,14,14,12,13,13,15,15, 9,10,10,
  144962. 13,12,10,11,11,14,13,10,10,11,13,14,12,13,13,15,
  144963. 15,12,12,13,14,16, 9,10,10,13,13,10,11,11,13,14,
  144964. 10,11,11,14,13,12,13,13,14,15,13,14,13,16,14,11,
  144965. 12,12,14,14,12,13,13,15,14,11,12,13,14,15,14,15,
  144966. 15,16,16,13,13,15,13,16,11,12,12,14,15,12,13,13,
  144967. 14,15,11,13,12,15,14,14,15,15,16,16,14,15,12,16,
  144968. 13,
  144969. };
  144970. static float _vq_quantthresh__44u3__p4_0[] = {
  144971. -1.5, -0.5, 0.5, 1.5,
  144972. };
  144973. static long _vq_quantmap__44u3__p4_0[] = {
  144974. 3, 1, 0, 2, 4,
  144975. };
  144976. static encode_aux_threshmatch _vq_auxt__44u3__p4_0 = {
  144977. _vq_quantthresh__44u3__p4_0,
  144978. _vq_quantmap__44u3__p4_0,
  144979. 5,
  144980. 5
  144981. };
  144982. static static_codebook _44u3__p4_0 = {
  144983. 4, 625,
  144984. _vq_lengthlist__44u3__p4_0,
  144985. 1, -533725184, 1611661312, 3, 0,
  144986. _vq_quantlist__44u3__p4_0,
  144987. NULL,
  144988. &_vq_auxt__44u3__p4_0,
  144989. NULL,
  144990. 0
  144991. };
  144992. static long _vq_quantlist__44u3__p5_0[] = {
  144993. 4,
  144994. 3,
  144995. 5,
  144996. 2,
  144997. 6,
  144998. 1,
  144999. 7,
  145000. 0,
  145001. 8,
  145002. };
  145003. static long _vq_lengthlist__44u3__p5_0[] = {
  145004. 2, 3, 3, 6, 6, 7, 7, 9, 9, 4, 5, 5, 7, 7, 8, 8,
  145005. 10,10, 4, 5, 5, 7, 7, 8, 8,10,10, 6, 7, 7, 8, 8,
  145006. 9, 9,11,10, 6, 7, 7, 8, 8, 9, 9,10,10, 7, 8, 8,
  145007. 9, 9,10,10,11,11, 7, 8, 8, 9, 9,10,10,11,11, 9,
  145008. 10,10,11,10,11,11,12,12, 9,10,10,10,10,11,11,12,
  145009. 12,
  145010. };
  145011. static float _vq_quantthresh__44u3__p5_0[] = {
  145012. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  145013. };
  145014. static long _vq_quantmap__44u3__p5_0[] = {
  145015. 7, 5, 3, 1, 0, 2, 4, 6,
  145016. 8,
  145017. };
  145018. static encode_aux_threshmatch _vq_auxt__44u3__p5_0 = {
  145019. _vq_quantthresh__44u3__p5_0,
  145020. _vq_quantmap__44u3__p5_0,
  145021. 9,
  145022. 9
  145023. };
  145024. static static_codebook _44u3__p5_0 = {
  145025. 2, 81,
  145026. _vq_lengthlist__44u3__p5_0,
  145027. 1, -531628032, 1611661312, 4, 0,
  145028. _vq_quantlist__44u3__p5_0,
  145029. NULL,
  145030. &_vq_auxt__44u3__p5_0,
  145031. NULL,
  145032. 0
  145033. };
  145034. static long _vq_quantlist__44u3__p6_0[] = {
  145035. 6,
  145036. 5,
  145037. 7,
  145038. 4,
  145039. 8,
  145040. 3,
  145041. 9,
  145042. 2,
  145043. 10,
  145044. 1,
  145045. 11,
  145046. 0,
  145047. 12,
  145048. };
  145049. static long _vq_lengthlist__44u3__p6_0[] = {
  145050. 1, 4, 4, 6, 6, 8, 8, 9, 9,10,11,13,14, 4, 6, 5,
  145051. 8, 8, 9, 9,10,10,11,11,14,14, 4, 6, 6, 8, 8, 9,
  145052. 9,10,10,11,11,14,14, 6, 8, 8, 9, 9,10,10,11,11,
  145053. 12,12,15,15, 6, 8, 8, 9, 9,10,11,11,11,12,12,15,
  145054. 15, 8, 9, 9,11,10,11,11,12,12,13,13,15,16, 8, 9,
  145055. 9,10,11,11,11,12,12,13,13,16,16,10,10,11,11,11,
  145056. 12,12,13,13,13,14,17,16, 9,10,11,12,11,12,12,13,
  145057. 13,13,13,16,18,11,12,11,12,12,13,13,13,14,15,14,
  145058. 17,17,11,11,12,12,12,13,13,13,14,14,15,18,17,14,
  145059. 15,15,15,15,16,16,17,17,19,18, 0,20,14,15,14,15,
  145060. 15,16,16,16,17,18,16,20,18,
  145061. };
  145062. static float _vq_quantthresh__44u3__p6_0[] = {
  145063. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  145064. 12.5, 17.5, 22.5, 27.5,
  145065. };
  145066. static long _vq_quantmap__44u3__p6_0[] = {
  145067. 11, 9, 7, 5, 3, 1, 0, 2,
  145068. 4, 6, 8, 10, 12,
  145069. };
  145070. static encode_aux_threshmatch _vq_auxt__44u3__p6_0 = {
  145071. _vq_quantthresh__44u3__p6_0,
  145072. _vq_quantmap__44u3__p6_0,
  145073. 13,
  145074. 13
  145075. };
  145076. static static_codebook _44u3__p6_0 = {
  145077. 2, 169,
  145078. _vq_lengthlist__44u3__p6_0,
  145079. 1, -526516224, 1616117760, 4, 0,
  145080. _vq_quantlist__44u3__p6_0,
  145081. NULL,
  145082. &_vq_auxt__44u3__p6_0,
  145083. NULL,
  145084. 0
  145085. };
  145086. static long _vq_quantlist__44u3__p6_1[] = {
  145087. 2,
  145088. 1,
  145089. 3,
  145090. 0,
  145091. 4,
  145092. };
  145093. static long _vq_lengthlist__44u3__p6_1[] = {
  145094. 2, 4, 4, 5, 5, 4, 5, 5, 6, 5, 4, 5, 5, 5, 6, 5,
  145095. 6, 5, 6, 6, 5, 5, 6, 6, 6,
  145096. };
  145097. static float _vq_quantthresh__44u3__p6_1[] = {
  145098. -1.5, -0.5, 0.5, 1.5,
  145099. };
  145100. static long _vq_quantmap__44u3__p6_1[] = {
  145101. 3, 1, 0, 2, 4,
  145102. };
  145103. static encode_aux_threshmatch _vq_auxt__44u3__p6_1 = {
  145104. _vq_quantthresh__44u3__p6_1,
  145105. _vq_quantmap__44u3__p6_1,
  145106. 5,
  145107. 5
  145108. };
  145109. static static_codebook _44u3__p6_1 = {
  145110. 2, 25,
  145111. _vq_lengthlist__44u3__p6_1,
  145112. 1, -533725184, 1611661312, 3, 0,
  145113. _vq_quantlist__44u3__p6_1,
  145114. NULL,
  145115. &_vq_auxt__44u3__p6_1,
  145116. NULL,
  145117. 0
  145118. };
  145119. static long _vq_quantlist__44u3__p7_0[] = {
  145120. 4,
  145121. 3,
  145122. 5,
  145123. 2,
  145124. 6,
  145125. 1,
  145126. 7,
  145127. 0,
  145128. 8,
  145129. };
  145130. static long _vq_lengthlist__44u3__p7_0[] = {
  145131. 1, 3, 3,10,10,10,10,10,10, 4,10,10,10,10,10,10,
  145132. 10,10, 4,10,10,10,10,10,10,10,10,10,10, 9, 9, 9,
  145133. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  145134. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  145135. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  145136. 9,
  145137. };
  145138. static float _vq_quantthresh__44u3__p7_0[] = {
  145139. -892.5, -637.5, -382.5, -127.5, 127.5, 382.5, 637.5, 892.5,
  145140. };
  145141. static long _vq_quantmap__44u3__p7_0[] = {
  145142. 7, 5, 3, 1, 0, 2, 4, 6,
  145143. 8,
  145144. };
  145145. static encode_aux_threshmatch _vq_auxt__44u3__p7_0 = {
  145146. _vq_quantthresh__44u3__p7_0,
  145147. _vq_quantmap__44u3__p7_0,
  145148. 9,
  145149. 9
  145150. };
  145151. static static_codebook _44u3__p7_0 = {
  145152. 2, 81,
  145153. _vq_lengthlist__44u3__p7_0,
  145154. 1, -515907584, 1627381760, 4, 0,
  145155. _vq_quantlist__44u3__p7_0,
  145156. NULL,
  145157. &_vq_auxt__44u3__p7_0,
  145158. NULL,
  145159. 0
  145160. };
  145161. static long _vq_quantlist__44u3__p7_1[] = {
  145162. 7,
  145163. 6,
  145164. 8,
  145165. 5,
  145166. 9,
  145167. 4,
  145168. 10,
  145169. 3,
  145170. 11,
  145171. 2,
  145172. 12,
  145173. 1,
  145174. 13,
  145175. 0,
  145176. 14,
  145177. };
  145178. static long _vq_lengthlist__44u3__p7_1[] = {
  145179. 1, 4, 4, 6, 6, 7, 6, 8, 7, 9, 8,10, 9,11,11, 4,
  145180. 7, 7, 8, 7, 9, 9,10,10,11,11,11,11,12,12, 4, 7,
  145181. 7, 7, 7, 9, 9,10,10,11,11,12,12,12,11, 6, 8, 8,
  145182. 9, 9,10,10,11,11,12,12,13,12,13,13, 6, 8, 8, 9,
  145183. 9,10,11,11,11,12,12,13,14,13,13, 8, 9, 9,11,11,
  145184. 12,12,12,13,14,13,14,14,14,15, 8, 9, 9,11,11,11,
  145185. 12,13,14,13,14,15,17,14,15, 9,10,10,12,12,13,13,
  145186. 13,14,15,15,15,16,16,16, 9,11,11,12,12,13,13,14,
  145187. 14,14,15,16,16,16,16,10,12,12,13,13,14,14,15,15,
  145188. 15,16,17,17,17,17,10,12,11,13,13,15,14,15,14,16,
  145189. 17,16,16,16,16,11,13,12,14,14,14,14,15,16,17,16,
  145190. 17,17,17,17,11,13,12,14,14,14,15,17,16,17,17,17,
  145191. 17,17,17,12,13,13,15,16,15,16,17,17,16,16,17,17,
  145192. 17,17,12,13,13,15,15,15,16,17,17,17,16,17,16,17,
  145193. 17,
  145194. };
  145195. static float _vq_quantthresh__44u3__p7_1[] = {
  145196. -110.5, -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5,
  145197. 25.5, 42.5, 59.5, 76.5, 93.5, 110.5,
  145198. };
  145199. static long _vq_quantmap__44u3__p7_1[] = {
  145200. 13, 11, 9, 7, 5, 3, 1, 0,
  145201. 2, 4, 6, 8, 10, 12, 14,
  145202. };
  145203. static encode_aux_threshmatch _vq_auxt__44u3__p7_1 = {
  145204. _vq_quantthresh__44u3__p7_1,
  145205. _vq_quantmap__44u3__p7_1,
  145206. 15,
  145207. 15
  145208. };
  145209. static static_codebook _44u3__p7_1 = {
  145210. 2, 225,
  145211. _vq_lengthlist__44u3__p7_1,
  145212. 1, -522338304, 1620115456, 4, 0,
  145213. _vq_quantlist__44u3__p7_1,
  145214. NULL,
  145215. &_vq_auxt__44u3__p7_1,
  145216. NULL,
  145217. 0
  145218. };
  145219. static long _vq_quantlist__44u3__p7_2[] = {
  145220. 8,
  145221. 7,
  145222. 9,
  145223. 6,
  145224. 10,
  145225. 5,
  145226. 11,
  145227. 4,
  145228. 12,
  145229. 3,
  145230. 13,
  145231. 2,
  145232. 14,
  145233. 1,
  145234. 15,
  145235. 0,
  145236. 16,
  145237. };
  145238. static long _vq_lengthlist__44u3__p7_2[] = {
  145239. 2, 5, 5, 7, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  145240. 9, 5, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  145241. 10,10, 5, 6, 6, 7, 7, 8, 8, 8, 8, 9, 8, 9, 9, 9,
  145242. 9,10, 9, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  145243. 10,10,10,10, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9,10,
  145244. 9,10,10,10,10, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  145245. 10,10,10,10,10,10, 7, 8, 8, 9, 8, 9, 9, 9, 9,10,
  145246. 9,10,10,10,10,10,10, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  145247. 9,10,10,10,10,10,10,10, 8, 9, 8, 9, 9, 9, 9,10,
  145248. 9,10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9, 9,10,
  145249. 9,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9,10,
  145250. 9,10,10,10,10,10,10,10,10,10,10, 9, 9, 9,10, 9,
  145251. 10,10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9,10,
  145252. 10,10,10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9,
  145253. 10,10,10,10,10,10,10,10,10,10,10,10,10,11, 9,10,
  145254. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,11, 9,
  145255. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  145256. 9,10,10,10,10,10,10,10,10,10,10,10,11,11,11,10,
  145257. 11,
  145258. };
  145259. static float _vq_quantthresh__44u3__p7_2[] = {
  145260. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  145261. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  145262. };
  145263. static long _vq_quantmap__44u3__p7_2[] = {
  145264. 15, 13, 11, 9, 7, 5, 3, 1,
  145265. 0, 2, 4, 6, 8, 10, 12, 14,
  145266. 16,
  145267. };
  145268. static encode_aux_threshmatch _vq_auxt__44u3__p7_2 = {
  145269. _vq_quantthresh__44u3__p7_2,
  145270. _vq_quantmap__44u3__p7_2,
  145271. 17,
  145272. 17
  145273. };
  145274. static static_codebook _44u3__p7_2 = {
  145275. 2, 289,
  145276. _vq_lengthlist__44u3__p7_2,
  145277. 1, -529530880, 1611661312, 5, 0,
  145278. _vq_quantlist__44u3__p7_2,
  145279. NULL,
  145280. &_vq_auxt__44u3__p7_2,
  145281. NULL,
  145282. 0
  145283. };
  145284. static long _huff_lengthlist__44u3__short[] = {
  145285. 14,14,14,15,13,15,12,16,10, 8, 7, 9, 9, 8,12,16,
  145286. 10, 5, 4, 6, 5, 6, 9,16,14, 8, 6, 8, 7, 8,10,16,
  145287. 14, 7, 4, 6, 3, 5, 8,16,15, 9, 5, 7, 4, 4, 7,16,
  145288. 13,10, 6, 7, 4, 3, 4,13,13,12, 7, 9, 5, 5, 6,12,
  145289. };
  145290. static static_codebook _huff_book__44u3__short = {
  145291. 2, 64,
  145292. _huff_lengthlist__44u3__short,
  145293. 0, 0, 0, 0, 0,
  145294. NULL,
  145295. NULL,
  145296. NULL,
  145297. NULL,
  145298. 0
  145299. };
  145300. static long _huff_lengthlist__44u4__long[] = {
  145301. 3, 8,12,12,13,12,11,13, 5, 4, 6, 7, 8, 8, 9,13,
  145302. 9, 5, 4, 5, 5, 7, 9,13, 9, 6, 5, 6, 6, 7, 8,12,
  145303. 12, 7, 5, 6, 4, 5, 8,13,11, 7, 6, 6, 5, 5, 6,12,
  145304. 10, 8, 8, 7, 7, 5, 3, 8,10,12,13,12,12, 9, 6, 7,
  145305. };
  145306. static static_codebook _huff_book__44u4__long = {
  145307. 2, 64,
  145308. _huff_lengthlist__44u4__long,
  145309. 0, 0, 0, 0, 0,
  145310. NULL,
  145311. NULL,
  145312. NULL,
  145313. NULL,
  145314. 0
  145315. };
  145316. static long _vq_quantlist__44u4__p1_0[] = {
  145317. 1,
  145318. 0,
  145319. 2,
  145320. };
  145321. static long _vq_lengthlist__44u4__p1_0[] = {
  145322. 1, 4, 4, 5, 8, 7, 5, 7, 8, 5, 8, 8, 8,10,11, 8,
  145323. 10,11, 5, 8, 8, 8,11,10, 8,11,11, 4, 8, 8, 8,11,
  145324. 11, 8,11,11, 8,11,11,11,13,14,11,15,14, 8,11,11,
  145325. 10,13,12,11,14,14, 4, 8, 8, 8,11,11, 8,11,11, 7,
  145326. 11,11,11,15,14,10,12,14, 8,11,11,11,14,14,11,14,
  145327. 13,
  145328. };
  145329. static float _vq_quantthresh__44u4__p1_0[] = {
  145330. -0.5, 0.5,
  145331. };
  145332. static long _vq_quantmap__44u4__p1_0[] = {
  145333. 1, 0, 2,
  145334. };
  145335. static encode_aux_threshmatch _vq_auxt__44u4__p1_0 = {
  145336. _vq_quantthresh__44u4__p1_0,
  145337. _vq_quantmap__44u4__p1_0,
  145338. 3,
  145339. 3
  145340. };
  145341. static static_codebook _44u4__p1_0 = {
  145342. 4, 81,
  145343. _vq_lengthlist__44u4__p1_0,
  145344. 1, -535822336, 1611661312, 2, 0,
  145345. _vq_quantlist__44u4__p1_0,
  145346. NULL,
  145347. &_vq_auxt__44u4__p1_0,
  145348. NULL,
  145349. 0
  145350. };
  145351. static long _vq_quantlist__44u4__p2_0[] = {
  145352. 1,
  145353. 0,
  145354. 2,
  145355. };
  145356. static long _vq_lengthlist__44u4__p2_0[] = {
  145357. 2, 5, 5, 5, 6, 6, 5, 6, 6, 5, 6, 6, 7, 8, 8, 6,
  145358. 8, 8, 5, 6, 6, 6, 8, 8, 7, 8, 8, 5, 7, 6, 6, 8,
  145359. 8, 6, 8, 8, 6, 8, 8, 8, 9,10, 8,10,10, 6, 8, 8,
  145360. 8,10, 8, 8,10,10, 5, 6, 6, 6, 8, 8, 6, 8, 8, 6,
  145361. 8, 8, 8,10,10, 8, 8,10, 6, 8, 8, 8,10,10, 8,10,
  145362. 9,
  145363. };
  145364. static float _vq_quantthresh__44u4__p2_0[] = {
  145365. -0.5, 0.5,
  145366. };
  145367. static long _vq_quantmap__44u4__p2_0[] = {
  145368. 1, 0, 2,
  145369. };
  145370. static encode_aux_threshmatch _vq_auxt__44u4__p2_0 = {
  145371. _vq_quantthresh__44u4__p2_0,
  145372. _vq_quantmap__44u4__p2_0,
  145373. 3,
  145374. 3
  145375. };
  145376. static static_codebook _44u4__p2_0 = {
  145377. 4, 81,
  145378. _vq_lengthlist__44u4__p2_0,
  145379. 1, -535822336, 1611661312, 2, 0,
  145380. _vq_quantlist__44u4__p2_0,
  145381. NULL,
  145382. &_vq_auxt__44u4__p2_0,
  145383. NULL,
  145384. 0
  145385. };
  145386. static long _vq_quantlist__44u4__p3_0[] = {
  145387. 2,
  145388. 1,
  145389. 3,
  145390. 0,
  145391. 4,
  145392. };
  145393. static long _vq_lengthlist__44u4__p3_0[] = {
  145394. 2, 4, 4, 8, 8, 5, 7, 7, 9, 9, 5, 7, 7, 9, 9, 8,
  145395. 10, 9,12,12, 8, 9,10,12,12, 5, 7, 7,10,10, 7, 9,
  145396. 9,11,11, 7, 9, 9,11,11,10,12,11,14,14, 9,10,11,
  145397. 13,14, 5, 7, 7,10,10, 7, 9, 9,11,11, 7, 9, 9,11,
  145398. 11, 9,11,10,14,13,10,11,11,14,14, 8,10,10,14,13,
  145399. 10,12,12,15,14, 9,11,11,15,14,13,14,14,17,17,12,
  145400. 14,14,16,16, 8,10,10,14,14, 9,11,11,14,15,10,12,
  145401. 12,14,15,12,14,13,16,16,13,14,15,15,18, 4, 7, 7,
  145402. 10,10, 7, 9, 9,12,11, 7, 9, 9,11,12,10,12,11,15,
  145403. 14,10,11,12,14,15, 7, 9, 9,12,12, 9,11,12,13,13,
  145404. 9,11,12,13,13,12,13,13,15,16,11,13,13,15,16, 7,
  145405. 9, 9,12,12, 9,11,10,13,12, 9,11,12,13,14,11,13,
  145406. 12,16,14,12,13,13,15,16,10,12,12,16,15,11,13,13,
  145407. 17,16,11,13,13,17,16,14,15,15,17,17,14,16,16,18,
  145408. 20, 9,11,11,15,16,11,13,12,16,16,11,13,13,16,17,
  145409. 14,15,14,18,16,14,16,16,17,20, 5, 7, 7,10,10, 7,
  145410. 9, 9,12,11, 7, 9,10,11,12,10,12,11,15,15,10,12,
  145411. 12,14,14, 7, 9, 9,12,12, 9,12,11,14,13, 9,10,11,
  145412. 12,13,12,13,14,16,16,11,12,13,14,16, 7, 9, 9,12,
  145413. 12, 9,12,11,13,13, 9,12,11,13,13,11,13,13,16,16,
  145414. 12,13,13,16,15, 9,11,11,16,14,11,13,13,16,16,11,
  145415. 12,13,16,16,14,16,16,17,17,13,14,15,16,17,10,12,
  145416. 12,15,15,11,13,13,16,17,11,13,13,16,16,14,16,15,
  145417. 19,19,14,15,15,17,18, 8,10,10,14,14,10,12,12,15,
  145418. 15,10,12,12,16,16,14,16,15,20,19,13,15,15,17,16,
  145419. 9,12,12,16,16,11,13,13,16,18,11,14,13,16,17,16,
  145420. 17,16,20, 0,15,16,18,18,20, 9,11,11,15,15,11,14,
  145421. 12,17,16,11,13,13,17,17,15,17,15,20,20,14,16,16,
  145422. 17, 0,13,15,14,18,16,14,15,16, 0,18,14,16,16, 0,
  145423. 0,18,16, 0, 0,20,16,18,18, 0, 0,12,14,14,17,18,
  145424. 13,15,14,20,18,14,16,15,19,19,16,20,16, 0,18,16,
  145425. 19,17,19, 0, 8,10,10,14,14,10,12,12,16,15,10,12,
  145426. 12,16,16,13,15,15,18,17,14,16,16,19, 0, 9,11,11,
  145427. 16,15,11,14,13,18,17,11,12,13,17,18,14,17,16,18,
  145428. 18,15,16,17,18,18, 9,12,12,16,16,11,13,13,16,18,
  145429. 11,14,13,17,17,15,16,16,18,20,16,17,17,20,20,12,
  145430. 14,14,18,17,14,16,16, 0,19,13,14,15,18, 0,16, 0,
  145431. 0, 0, 0,16,16, 0,19,20,13,15,14, 0, 0,14,16,16,
  145432. 18,19,14,16,15, 0,20,16,20,18, 0,20,17,20,17, 0,
  145433. 0,
  145434. };
  145435. static float _vq_quantthresh__44u4__p3_0[] = {
  145436. -1.5, -0.5, 0.5, 1.5,
  145437. };
  145438. static long _vq_quantmap__44u4__p3_0[] = {
  145439. 3, 1, 0, 2, 4,
  145440. };
  145441. static encode_aux_threshmatch _vq_auxt__44u4__p3_0 = {
  145442. _vq_quantthresh__44u4__p3_0,
  145443. _vq_quantmap__44u4__p3_0,
  145444. 5,
  145445. 5
  145446. };
  145447. static static_codebook _44u4__p3_0 = {
  145448. 4, 625,
  145449. _vq_lengthlist__44u4__p3_0,
  145450. 1, -533725184, 1611661312, 3, 0,
  145451. _vq_quantlist__44u4__p3_0,
  145452. NULL,
  145453. &_vq_auxt__44u4__p3_0,
  145454. NULL,
  145455. 0
  145456. };
  145457. static long _vq_quantlist__44u4__p4_0[] = {
  145458. 2,
  145459. 1,
  145460. 3,
  145461. 0,
  145462. 4,
  145463. };
  145464. static long _vq_lengthlist__44u4__p4_0[] = {
  145465. 4, 5, 5, 8, 8, 5, 7, 6, 9, 9, 5, 6, 7, 9, 9, 9,
  145466. 9, 9,11,11, 8, 9, 9,11,11, 5, 7, 7, 9, 9, 7, 8,
  145467. 8,10,10, 7, 7, 8,10,10, 9,10,10,11,12, 9,10,10,
  145468. 11,12, 5, 7, 7, 9, 9, 7, 8, 7,10,10, 7, 8, 8,10,
  145469. 10, 9,10,10,12,11, 9,10,10,12,11, 9,10, 9,12,12,
  145470. 9,10,10,13,12, 9,10,10,12,12,12,12,12,14,14,11,
  145471. 12,12,13,14, 9, 9,10,12,12, 9,10,10,13,13, 9,10,
  145472. 10,12,13,11,12,12,14,13,11,12,12,14,14, 5, 7, 7,
  145473. 9, 9, 7, 8, 8,10,10, 7, 8, 8,10,10,10,10,10,12,
  145474. 12, 9,10,10,12,12, 7, 8, 8,11,10, 8, 8, 9,11,11,
  145475. 8, 9, 9,11,11,11,11,11,12,13,10,11,11,13,13, 6,
  145476. 8, 8,10,10, 7, 9, 8,11,10, 8, 9, 9,11,11,10,11,
  145477. 10,13,11,10,11,11,13,13, 9,11,10,13,12,10,11,11,
  145478. 13,14,10,11,11,14,13,12,12,13,12,15,12,13,13,15,
  145479. 15, 9,10,10,12,13,10,11,10,13,12,10,11,11,13,14,
  145480. 12,13,11,15,13,13,13,13,15,15, 5, 7, 7, 9, 9, 7,
  145481. 8, 8,10,10, 7, 8, 8,10,10, 9,10,10,12,12,10,10,
  145482. 11,12,13, 6, 8, 8,10,10, 8, 9, 9,11,11, 7, 8, 9,
  145483. 10,11,10,11,11,13,13,10,10,11,11,13, 7, 8, 8,10,
  145484. 11, 8, 9, 9,11,11, 8, 9, 8,11,11,10,11,11,13,13,
  145485. 11,12,11,13,12, 9,10,10,13,12,10,11,11,14,13,10,
  145486. 10,11,12,13,12,13,13,15,15,12,11,13,13,14, 9,10,
  145487. 11,12,13,10,11,11,13,14,10,11,11,13,13,12,13,13,
  145488. 15,15,12,13,12,15,12, 8, 9, 9,12,12, 9,11,10,13,
  145489. 13, 9,10,10,13,13,12,13,13,15,15,12,12,12,14,14,
  145490. 9,10,10,13,13,10,11,11,13,14,10,11,11,14,13,13,
  145491. 13,14,14,16,13,13,13,15,15, 9,10,10,13,13,10,11,
  145492. 10,14,13,10,11,11,13,14,12,14,13,16,14,12,13,13,
  145493. 14,15,11,12,12,15,14,11,12,13,14,15,12,13,13,16,
  145494. 15,14,12,15,12,16,14,15,15,16,16,11,12,12,14,14,
  145495. 11,13,12,15,14,12,13,13,15,16,13,15,13,17,13,14,
  145496. 15,15,16,17, 8, 9, 9,12,12, 9,10,10,12,13, 9,10,
  145497. 10,13,13,12,12,12,14,14,12,13,13,15,15, 9,10,10,
  145498. 13,12,10,11,11,14,13,10,10,11,13,14,13,13,13,15,
  145499. 15,12,13,14,14,16, 9,10,10,13,13,10,11,11,13,14,
  145500. 10,11,11,14,14,13,13,13,15,15,13,14,13,16,14,11,
  145501. 12,12,15,14,12,13,13,16,15,11,12,13,14,15,14,15,
  145502. 15,17,16,13,13,15,13,16,11,12,13,14,15,13,13,13,
  145503. 15,16,11,13,12,15,14,14,15,15,16,16,14,15,12,17,
  145504. 13,
  145505. };
  145506. static float _vq_quantthresh__44u4__p4_0[] = {
  145507. -1.5, -0.5, 0.5, 1.5,
  145508. };
  145509. static long _vq_quantmap__44u4__p4_0[] = {
  145510. 3, 1, 0, 2, 4,
  145511. };
  145512. static encode_aux_threshmatch _vq_auxt__44u4__p4_0 = {
  145513. _vq_quantthresh__44u4__p4_0,
  145514. _vq_quantmap__44u4__p4_0,
  145515. 5,
  145516. 5
  145517. };
  145518. static static_codebook _44u4__p4_0 = {
  145519. 4, 625,
  145520. _vq_lengthlist__44u4__p4_0,
  145521. 1, -533725184, 1611661312, 3, 0,
  145522. _vq_quantlist__44u4__p4_0,
  145523. NULL,
  145524. &_vq_auxt__44u4__p4_0,
  145525. NULL,
  145526. 0
  145527. };
  145528. static long _vq_quantlist__44u4__p5_0[] = {
  145529. 4,
  145530. 3,
  145531. 5,
  145532. 2,
  145533. 6,
  145534. 1,
  145535. 7,
  145536. 0,
  145537. 8,
  145538. };
  145539. static long _vq_lengthlist__44u4__p5_0[] = {
  145540. 2, 3, 3, 6, 6, 7, 7, 9, 9, 4, 5, 5, 7, 7, 8, 8,
  145541. 10, 9, 4, 5, 5, 7, 7, 8, 8,10,10, 6, 7, 7, 8, 8,
  145542. 9, 9,11,10, 6, 7, 7, 8, 8, 9, 9,10,11, 7, 8, 8,
  145543. 9, 9,10,10,11,11, 7, 8, 8, 9, 9,10,10,11,11, 9,
  145544. 10,10,11,10,11,11,12,12, 9,10,10,10,11,11,11,12,
  145545. 12,
  145546. };
  145547. static float _vq_quantthresh__44u4__p5_0[] = {
  145548. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  145549. };
  145550. static long _vq_quantmap__44u4__p5_0[] = {
  145551. 7, 5, 3, 1, 0, 2, 4, 6,
  145552. 8,
  145553. };
  145554. static encode_aux_threshmatch _vq_auxt__44u4__p5_0 = {
  145555. _vq_quantthresh__44u4__p5_0,
  145556. _vq_quantmap__44u4__p5_0,
  145557. 9,
  145558. 9
  145559. };
  145560. static static_codebook _44u4__p5_0 = {
  145561. 2, 81,
  145562. _vq_lengthlist__44u4__p5_0,
  145563. 1, -531628032, 1611661312, 4, 0,
  145564. _vq_quantlist__44u4__p5_0,
  145565. NULL,
  145566. &_vq_auxt__44u4__p5_0,
  145567. NULL,
  145568. 0
  145569. };
  145570. static long _vq_quantlist__44u4__p6_0[] = {
  145571. 6,
  145572. 5,
  145573. 7,
  145574. 4,
  145575. 8,
  145576. 3,
  145577. 9,
  145578. 2,
  145579. 10,
  145580. 1,
  145581. 11,
  145582. 0,
  145583. 12,
  145584. };
  145585. static long _vq_lengthlist__44u4__p6_0[] = {
  145586. 1, 4, 4, 6, 6, 8, 8, 9, 9,11,10,13,13, 4, 6, 5,
  145587. 8, 8, 9, 9,10,10,11,11,14,14, 4, 6, 6, 8, 8, 9,
  145588. 9,10,10,11,11,14,14, 6, 8, 8, 9, 9,10,10,11,11,
  145589. 12,12,15,15, 6, 8, 8, 9, 9,10,11,11,11,12,12,15,
  145590. 15, 8, 9, 9,11,10,11,11,12,12,13,13,16,16, 8, 9,
  145591. 9,10,10,11,11,12,12,13,13,16,16,10,10,10,12,11,
  145592. 12,12,13,13,14,14,16,16,10,10,10,11,12,12,12,13,
  145593. 13,13,14,16,17,11,12,11,12,12,13,13,14,14,15,14,
  145594. 18,17,11,11,12,12,12,13,13,14,14,14,15,19,18,14,
  145595. 15,14,15,15,17,16,17,17,17,17,21, 0,14,15,15,16,
  145596. 16,16,16,17,17,18,17,20,21,
  145597. };
  145598. static float _vq_quantthresh__44u4__p6_0[] = {
  145599. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  145600. 12.5, 17.5, 22.5, 27.5,
  145601. };
  145602. static long _vq_quantmap__44u4__p6_0[] = {
  145603. 11, 9, 7, 5, 3, 1, 0, 2,
  145604. 4, 6, 8, 10, 12,
  145605. };
  145606. static encode_aux_threshmatch _vq_auxt__44u4__p6_0 = {
  145607. _vq_quantthresh__44u4__p6_0,
  145608. _vq_quantmap__44u4__p6_0,
  145609. 13,
  145610. 13
  145611. };
  145612. static static_codebook _44u4__p6_0 = {
  145613. 2, 169,
  145614. _vq_lengthlist__44u4__p6_0,
  145615. 1, -526516224, 1616117760, 4, 0,
  145616. _vq_quantlist__44u4__p6_0,
  145617. NULL,
  145618. &_vq_auxt__44u4__p6_0,
  145619. NULL,
  145620. 0
  145621. };
  145622. static long _vq_quantlist__44u4__p6_1[] = {
  145623. 2,
  145624. 1,
  145625. 3,
  145626. 0,
  145627. 4,
  145628. };
  145629. static long _vq_lengthlist__44u4__p6_1[] = {
  145630. 2, 4, 4, 5, 5, 4, 5, 5, 6, 5, 4, 5, 5, 5, 6, 5,
  145631. 6, 5, 6, 6, 5, 5, 6, 6, 6,
  145632. };
  145633. static float _vq_quantthresh__44u4__p6_1[] = {
  145634. -1.5, -0.5, 0.5, 1.5,
  145635. };
  145636. static long _vq_quantmap__44u4__p6_1[] = {
  145637. 3, 1, 0, 2, 4,
  145638. };
  145639. static encode_aux_threshmatch _vq_auxt__44u4__p6_1 = {
  145640. _vq_quantthresh__44u4__p6_1,
  145641. _vq_quantmap__44u4__p6_1,
  145642. 5,
  145643. 5
  145644. };
  145645. static static_codebook _44u4__p6_1 = {
  145646. 2, 25,
  145647. _vq_lengthlist__44u4__p6_1,
  145648. 1, -533725184, 1611661312, 3, 0,
  145649. _vq_quantlist__44u4__p6_1,
  145650. NULL,
  145651. &_vq_auxt__44u4__p6_1,
  145652. NULL,
  145653. 0
  145654. };
  145655. static long _vq_quantlist__44u4__p7_0[] = {
  145656. 6,
  145657. 5,
  145658. 7,
  145659. 4,
  145660. 8,
  145661. 3,
  145662. 9,
  145663. 2,
  145664. 10,
  145665. 1,
  145666. 11,
  145667. 0,
  145668. 12,
  145669. };
  145670. static long _vq_lengthlist__44u4__p7_0[] = {
  145671. 1, 3, 3,12,12,12,12,12,12,12,12,12,12, 3,12,11,
  145672. 12,12,12,12,12,12,12,12,12,12, 4,11,10,12,12,12,
  145673. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  145674. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  145675. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  145676. 12,12,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  145677. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  145678. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  145679. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  145680. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  145681. 11,11,11,11,11,11,11,11,11,
  145682. };
  145683. static float _vq_quantthresh__44u4__p7_0[] = {
  145684. -1402.5, -1147.5, -892.5, -637.5, -382.5, -127.5, 127.5, 382.5,
  145685. 637.5, 892.5, 1147.5, 1402.5,
  145686. };
  145687. static long _vq_quantmap__44u4__p7_0[] = {
  145688. 11, 9, 7, 5, 3, 1, 0, 2,
  145689. 4, 6, 8, 10, 12,
  145690. };
  145691. static encode_aux_threshmatch _vq_auxt__44u4__p7_0 = {
  145692. _vq_quantthresh__44u4__p7_0,
  145693. _vq_quantmap__44u4__p7_0,
  145694. 13,
  145695. 13
  145696. };
  145697. static static_codebook _44u4__p7_0 = {
  145698. 2, 169,
  145699. _vq_lengthlist__44u4__p7_0,
  145700. 1, -514332672, 1627381760, 4, 0,
  145701. _vq_quantlist__44u4__p7_0,
  145702. NULL,
  145703. &_vq_auxt__44u4__p7_0,
  145704. NULL,
  145705. 0
  145706. };
  145707. static long _vq_quantlist__44u4__p7_1[] = {
  145708. 7,
  145709. 6,
  145710. 8,
  145711. 5,
  145712. 9,
  145713. 4,
  145714. 10,
  145715. 3,
  145716. 11,
  145717. 2,
  145718. 12,
  145719. 1,
  145720. 13,
  145721. 0,
  145722. 14,
  145723. };
  145724. static long _vq_lengthlist__44u4__p7_1[] = {
  145725. 1, 4, 4, 6, 6, 7, 7, 9, 8,10, 8,10, 9,11,11, 4,
  145726. 7, 6, 8, 7, 9, 9,10,10,11,10,11,10,12,10, 4, 6,
  145727. 7, 8, 8, 9, 9,10,10,11,11,11,11,12,12, 6, 8, 8,
  145728. 10, 9,11,10,12,11,12,12,12,12,13,13, 6, 8, 8,10,
  145729. 10,10,11,11,11,12,12,13,12,13,13, 8, 9, 9,11,11,
  145730. 12,11,12,12,13,13,13,13,13,13, 8, 9, 9,11,11,11,
  145731. 12,12,12,13,13,13,13,13,13, 9,10,10,12,11,13,13,
  145732. 13,13,14,13,13,14,14,14, 9,10,11,11,12,12,13,13,
  145733. 13,13,13,14,15,14,14,10,11,11,12,12,13,13,14,14,
  145734. 14,14,14,15,16,16,10,11,11,12,13,13,13,13,15,14,
  145735. 14,15,16,15,16,10,12,12,13,13,14,14,14,15,15,15,
  145736. 15,15,15,16,11,12,12,13,13,14,14,14,15,15,15,16,
  145737. 15,17,16,11,12,12,13,13,13,15,15,14,16,16,16,16,
  145738. 16,17,11,12,12,13,13,14,14,15,14,15,15,17,17,16,
  145739. 16,
  145740. };
  145741. static float _vq_quantthresh__44u4__p7_1[] = {
  145742. -110.5, -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5,
  145743. 25.5, 42.5, 59.5, 76.5, 93.5, 110.5,
  145744. };
  145745. static long _vq_quantmap__44u4__p7_1[] = {
  145746. 13, 11, 9, 7, 5, 3, 1, 0,
  145747. 2, 4, 6, 8, 10, 12, 14,
  145748. };
  145749. static encode_aux_threshmatch _vq_auxt__44u4__p7_1 = {
  145750. _vq_quantthresh__44u4__p7_1,
  145751. _vq_quantmap__44u4__p7_1,
  145752. 15,
  145753. 15
  145754. };
  145755. static static_codebook _44u4__p7_1 = {
  145756. 2, 225,
  145757. _vq_lengthlist__44u4__p7_1,
  145758. 1, -522338304, 1620115456, 4, 0,
  145759. _vq_quantlist__44u4__p7_1,
  145760. NULL,
  145761. &_vq_auxt__44u4__p7_1,
  145762. NULL,
  145763. 0
  145764. };
  145765. static long _vq_quantlist__44u4__p7_2[] = {
  145766. 8,
  145767. 7,
  145768. 9,
  145769. 6,
  145770. 10,
  145771. 5,
  145772. 11,
  145773. 4,
  145774. 12,
  145775. 3,
  145776. 13,
  145777. 2,
  145778. 14,
  145779. 1,
  145780. 15,
  145781. 0,
  145782. 16,
  145783. };
  145784. static long _vq_lengthlist__44u4__p7_2[] = {
  145785. 2, 5, 5, 7, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  145786. 9, 5, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  145787. 9, 9, 5, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  145788. 9, 9, 9, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  145789. 10,10,10,10, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9,10,
  145790. 9,10, 9,10,10, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  145791. 10,10,10,10,10,10, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  145792. 9,10,10,10,10,10,10, 8, 9, 8, 9, 9, 9, 9, 9, 9,
  145793. 10,10,10,10,10,10,10,10, 8, 8, 8, 9, 9, 9, 9, 9,
  145794. 10,10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9,10,10,
  145795. 10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9,10,
  145796. 10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9,10,
  145797. 10,10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9,
  145798. 10,10,10,10,10,10,10,10,10,11,10,10,10, 9, 9, 9,
  145799. 10,10,10,10,10,10,10,10,10,10,10,10,10,10, 9, 9,
  145800. 9,10,10,10,10,10,10,10,10,10,10,10,10,10,10, 9,
  145801. 10, 9,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  145802. 9,10, 9,10,10,10,10,10,10,10,10,10,10,11,10,10,
  145803. 10,
  145804. };
  145805. static float _vq_quantthresh__44u4__p7_2[] = {
  145806. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  145807. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  145808. };
  145809. static long _vq_quantmap__44u4__p7_2[] = {
  145810. 15, 13, 11, 9, 7, 5, 3, 1,
  145811. 0, 2, 4, 6, 8, 10, 12, 14,
  145812. 16,
  145813. };
  145814. static encode_aux_threshmatch _vq_auxt__44u4__p7_2 = {
  145815. _vq_quantthresh__44u4__p7_2,
  145816. _vq_quantmap__44u4__p7_2,
  145817. 17,
  145818. 17
  145819. };
  145820. static static_codebook _44u4__p7_2 = {
  145821. 2, 289,
  145822. _vq_lengthlist__44u4__p7_2,
  145823. 1, -529530880, 1611661312, 5, 0,
  145824. _vq_quantlist__44u4__p7_2,
  145825. NULL,
  145826. &_vq_auxt__44u4__p7_2,
  145827. NULL,
  145828. 0
  145829. };
  145830. static long _huff_lengthlist__44u4__short[] = {
  145831. 14,17,15,17,16,14,13,16,10, 7, 7,10,13,10,15,16,
  145832. 9, 4, 4, 6, 5, 7, 9,16,12, 8, 7, 8, 8, 8,11,16,
  145833. 14, 7, 4, 6, 3, 5, 8,15,13, 8, 5, 7, 4, 5, 7,16,
  145834. 12, 9, 6, 8, 3, 3, 5,16,14,13, 7,10, 5, 5, 7,15,
  145835. };
  145836. static static_codebook _huff_book__44u4__short = {
  145837. 2, 64,
  145838. _huff_lengthlist__44u4__short,
  145839. 0, 0, 0, 0, 0,
  145840. NULL,
  145841. NULL,
  145842. NULL,
  145843. NULL,
  145844. 0
  145845. };
  145846. static long _huff_lengthlist__44u5__long[] = {
  145847. 3, 8,13,12,14,12,16,11,13,14, 5, 4, 5, 6, 7, 8,
  145848. 10, 9,12,15,10, 5, 5, 5, 6, 8, 9, 9,13,15,10, 5,
  145849. 5, 6, 6, 7, 8, 8,11,13,12, 7, 5, 6, 4, 6, 7, 7,
  145850. 11,14,11, 7, 7, 6, 6, 6, 7, 6,10,14,14, 9, 8, 8,
  145851. 6, 7, 7, 7,11,16,11, 8, 8, 7, 6, 6, 7, 4, 7,12,
  145852. 10,10,12,10,10, 9,10, 5, 6, 9,10,12,15,13,14,14,
  145853. 14, 8, 7, 8,
  145854. };
  145855. static static_codebook _huff_book__44u5__long = {
  145856. 2, 100,
  145857. _huff_lengthlist__44u5__long,
  145858. 0, 0, 0, 0, 0,
  145859. NULL,
  145860. NULL,
  145861. NULL,
  145862. NULL,
  145863. 0
  145864. };
  145865. static long _vq_quantlist__44u5__p1_0[] = {
  145866. 1,
  145867. 0,
  145868. 2,
  145869. };
  145870. static long _vq_lengthlist__44u5__p1_0[] = {
  145871. 1, 4, 4, 5, 8, 7, 5, 7, 7, 5, 8, 8, 8,10,10, 7,
  145872. 9,10, 5, 8, 8, 7,10, 9, 8,10,10, 5, 8, 8, 8,10,
  145873. 10, 8,10,10, 8,10,10,10,12,13,10,13,13, 7,10,10,
  145874. 10,13,11,10,13,13, 4, 8, 8, 8,11,10, 8,10,10, 7,
  145875. 10,10,10,13,13,10,11,13, 8,10,11,10,13,13,10,13,
  145876. 12,
  145877. };
  145878. static float _vq_quantthresh__44u5__p1_0[] = {
  145879. -0.5, 0.5,
  145880. };
  145881. static long _vq_quantmap__44u5__p1_0[] = {
  145882. 1, 0, 2,
  145883. };
  145884. static encode_aux_threshmatch _vq_auxt__44u5__p1_0 = {
  145885. _vq_quantthresh__44u5__p1_0,
  145886. _vq_quantmap__44u5__p1_0,
  145887. 3,
  145888. 3
  145889. };
  145890. static static_codebook _44u5__p1_0 = {
  145891. 4, 81,
  145892. _vq_lengthlist__44u5__p1_0,
  145893. 1, -535822336, 1611661312, 2, 0,
  145894. _vq_quantlist__44u5__p1_0,
  145895. NULL,
  145896. &_vq_auxt__44u5__p1_0,
  145897. NULL,
  145898. 0
  145899. };
  145900. static long _vq_quantlist__44u5__p2_0[] = {
  145901. 1,
  145902. 0,
  145903. 2,
  145904. };
  145905. static long _vq_lengthlist__44u5__p2_0[] = {
  145906. 3, 4, 4, 5, 6, 6, 5, 6, 6, 5, 6, 6, 6, 8, 8, 6,
  145907. 7, 8, 5, 6, 6, 6, 8, 7, 6, 8, 8, 5, 6, 6, 6, 8,
  145908. 8, 6, 8, 8, 6, 8, 8, 8, 9, 9, 8, 9, 9, 6, 8, 7,
  145909. 7, 9, 8, 8, 9, 9, 5, 6, 6, 6, 8, 7, 6, 8, 8, 6,
  145910. 8, 7, 8, 9, 9, 7, 8, 9, 6, 8, 8, 8, 9, 9, 8, 9,
  145911. 9,
  145912. };
  145913. static float _vq_quantthresh__44u5__p2_0[] = {
  145914. -0.5, 0.5,
  145915. };
  145916. static long _vq_quantmap__44u5__p2_0[] = {
  145917. 1, 0, 2,
  145918. };
  145919. static encode_aux_threshmatch _vq_auxt__44u5__p2_0 = {
  145920. _vq_quantthresh__44u5__p2_0,
  145921. _vq_quantmap__44u5__p2_0,
  145922. 3,
  145923. 3
  145924. };
  145925. static static_codebook _44u5__p2_0 = {
  145926. 4, 81,
  145927. _vq_lengthlist__44u5__p2_0,
  145928. 1, -535822336, 1611661312, 2, 0,
  145929. _vq_quantlist__44u5__p2_0,
  145930. NULL,
  145931. &_vq_auxt__44u5__p2_0,
  145932. NULL,
  145933. 0
  145934. };
  145935. static long _vq_quantlist__44u5__p3_0[] = {
  145936. 2,
  145937. 1,
  145938. 3,
  145939. 0,
  145940. 4,
  145941. };
  145942. static long _vq_lengthlist__44u5__p3_0[] = {
  145943. 2, 4, 5, 8, 8, 5, 7, 6, 9, 9, 5, 6, 7, 9, 9, 8,
  145944. 10, 9,13,12, 8, 9,10,12,12, 5, 7, 7,10,10, 7, 9,
  145945. 9,11,11, 6, 8, 9,11,11,10,11,11,14,14, 9,10,11,
  145946. 13,14, 5, 7, 7, 9,10, 7, 9, 8,11,11, 7, 9, 9,11,
  145947. 11, 9,11,10,14,13,10,11,11,14,14, 8,10,10,13,13,
  145948. 10,11,11,15,14, 9,11,11,14,14,13,14,14,17,16,12,
  145949. 13,13,15,16, 8,10,10,13,13, 9,11,11,14,15,10,11,
  145950. 11,14,15,12,14,13,16,16,13,15,14,15,17, 5, 7, 7,
  145951. 10,10, 7, 9, 9,11,11, 7, 9, 9,11,11,10,11,11,14,
  145952. 14,10,11,12,14,14, 7, 9, 9,12,11, 9,11,11,13,13,
  145953. 9,11,11,13,13,12,13,13,15,16,11,12,13,15,16, 6,
  145954. 9, 9,11,11, 8,11,10,13,12, 9,11,11,13,14,11,13,
  145955. 12,16,14,11,13,13,16,17,10,12,11,15,15,11,13,13,
  145956. 16,16,11,13,13,17,16,14,15,15,17,17,14,16,16,17,
  145957. 18, 9,11,11,14,15,10,12,12,15,15,11,13,13,16,17,
  145958. 13,15,13,17,15,14,15,16,18, 0, 5, 7, 7,10,10, 7,
  145959. 9, 9,11,11, 7, 9, 9,11,11,10,11,11,14,14,10,11,
  145960. 12,14,15, 6, 9, 9,12,11, 9,11,11,13,13, 8,10,11,
  145961. 12,13,11,13,13,16,15,11,12,13,14,15, 7, 9, 9,11,
  145962. 12, 9,11,11,13,13, 9,11,11,13,13,11,13,13,15,16,
  145963. 11,13,13,15,14, 9,11,11,15,14,11,13,13,17,15,10,
  145964. 12,12,15,15,14,16,16,17,17,13,13,15,15,17,10,11,
  145965. 12,15,15,11,13,13,16,16,11,13,13,15,15,14,15,15,
  145966. 18,18,14,15,15,17,17, 8,10,10,13,13,10,12,11,15,
  145967. 15,10,11,12,15,15,14,15,15,18,18,13,14,14,18,18,
  145968. 9,11,11,15,16,11,13,13,17,17,11,13,13,16,16,15,
  145969. 15,16,17, 0,14,15,17, 0, 0, 9,11,11,15,15,10,13,
  145970. 12,18,16,11,13,13,15,16,14,16,15,20,20,14,15,16,
  145971. 17, 0,13,14,14,20,16,14,15,16,19,18,14,15,15,19,
  145972. 0,18,16, 0,20,20,16,18,18, 0, 0,12,14,14,18,18,
  145973. 13,15,14,18,16,14,15,16,18,20,16,19,16, 0,17,17,
  145974. 18,18,19, 0, 8,10,10,14,14,10,11,11,14,15,10,11,
  145975. 12,15,15,13,15,14,19,17,13,15,15,17, 0, 9,11,11,
  145976. 16,15,11,13,13,16,16,10,12,13,15,17,14,16,16,18,
  145977. 18,14,15,15,18, 0, 9,11,11,15,15,11,13,13,16,17,
  145978. 11,13,13,18,17,14,18,16,18,18,15,17,17,18, 0,12,
  145979. 14,14,18,18,14,15,15,20, 0,13,14,15,17, 0,16,18,
  145980. 17, 0, 0,16,16, 0,17,20,12,14,14,18,18,14,16,15,
  145981. 0,18,14,16,15,18, 0,16,19,17, 0, 0,17,18,16, 0,
  145982. 0,
  145983. };
  145984. static float _vq_quantthresh__44u5__p3_0[] = {
  145985. -1.5, -0.5, 0.5, 1.5,
  145986. };
  145987. static long _vq_quantmap__44u5__p3_0[] = {
  145988. 3, 1, 0, 2, 4,
  145989. };
  145990. static encode_aux_threshmatch _vq_auxt__44u5__p3_0 = {
  145991. _vq_quantthresh__44u5__p3_0,
  145992. _vq_quantmap__44u5__p3_0,
  145993. 5,
  145994. 5
  145995. };
  145996. static static_codebook _44u5__p3_0 = {
  145997. 4, 625,
  145998. _vq_lengthlist__44u5__p3_0,
  145999. 1, -533725184, 1611661312, 3, 0,
  146000. _vq_quantlist__44u5__p3_0,
  146001. NULL,
  146002. &_vq_auxt__44u5__p3_0,
  146003. NULL,
  146004. 0
  146005. };
  146006. static long _vq_quantlist__44u5__p4_0[] = {
  146007. 2,
  146008. 1,
  146009. 3,
  146010. 0,
  146011. 4,
  146012. };
  146013. static long _vq_lengthlist__44u5__p4_0[] = {
  146014. 4, 5, 5, 8, 8, 6, 7, 6, 9, 9, 6, 6, 7, 9, 9, 8,
  146015. 9, 9,11,11, 8, 9, 9,11,11, 6, 7, 7, 9, 9, 7, 8,
  146016. 8,10,10, 6, 7, 8, 9,10, 9,10,10,11,12, 9, 9,10,
  146017. 11,12, 6, 7, 7, 9, 9, 6, 8, 7,10, 9, 7, 8, 8,10,
  146018. 10, 9,10, 9,12,11, 9,10,10,12,11, 8, 9, 9,12,11,
  146019. 9,10,10,12,12, 9,10,10,12,12,11,12,12,13,14,11,
  146020. 11,12,13,14, 8, 9, 9,11,12, 9,10,10,12,12, 9,10,
  146021. 10,12,12,11,12,11,14,13,11,12,12,13,13, 5, 7, 7,
  146022. 9, 9, 7, 8, 8,10,10, 7, 8, 8,10,10, 9,10,10,12,
  146023. 12, 9,10,10,12,12, 7, 8, 8,10,10, 8, 8, 9,10,11,
  146024. 8, 9, 9,11,11,10,10,11,11,13,10,11,11,12,13, 6,
  146025. 7, 8,10,10, 7, 9, 8,11,10, 8, 9, 9,11,11,10,11,
  146026. 10,13,11,10,11,11,12,12, 9,10,10,12,12,10,10,11,
  146027. 12,13,10,11,11,13,13,12,11,13,12,15,12,13,13,14,
  146028. 15, 9,10,10,12,12, 9,11,10,13,12,10,11,11,13,13,
  146029. 11,13,11,14,12,12,13,13,14,15, 5, 7, 7, 9, 9, 7,
  146030. 8, 8,10,10, 7, 8, 8,10,10, 9,10,10,12,12, 9,10,
  146031. 10,12,12, 6, 8, 7,10,10, 8, 9, 9,11,11, 7, 8, 9,
  146032. 10,11,10,11,11,12,12,10,10,11,11,13, 7, 8, 8,10,
  146033. 10, 8, 9, 9,11,11, 8, 9, 8,11,10,10,11,11,13,12,
  146034. 10,11,10,13,11, 9,10,10,12,12,10,11,11,13,12, 9,
  146035. 10,10,12,13,12,13,13,14,15,11,11,13,12,14, 9,10,
  146036. 10,12,12,10,11,11,13,13,10,11,10,13,12,12,13,13,
  146037. 14,14,12,13,11,14,12, 8, 9, 9,12,12, 9,10,10,12,
  146038. 12, 9,10,10,12,12,12,12,12,14,14,11,12,12,14,13,
  146039. 9,10,10,12,12,10,11,11,13,13,10,11,11,13,12,12,
  146040. 12,13,14,15,12,13,13,15,14, 9,10,10,12,12,10,11,
  146041. 10,13,12,10,11,11,12,13,12,13,12,15,13,12,13,13,
  146042. 14,15,11,12,12,14,13,11,12,12,14,15,12,13,13,15,
  146043. 14,13,12,14,12,16,13,14,14,15,15,11,11,12,14,14,
  146044. 11,12,11,14,13,12,13,13,14,15,13,14,12,16,12,14,
  146045. 14,15,16,16, 8, 9, 9,11,12, 9,10,10,12,12, 9,10,
  146046. 10,12,13,11,12,12,13,13,12,12,13,14,14, 9,10,10,
  146047. 12,12,10,11,10,13,12,10,10,11,12,13,12,13,13,15,
  146048. 14,12,12,13,13,15, 9,10,10,12,13,10,11,11,12,13,
  146049. 10,11,11,13,13,12,13,13,14,15,12,13,12,15,14,11,
  146050. 12,11,14,13,12,13,13,15,14,11,11,12,13,14,14,15,
  146051. 14,16,15,13,12,14,13,16,11,12,12,13,14,12,13,13,
  146052. 14,15,11,12,11,14,14,14,14,14,15,16,13,15,12,16,
  146053. 12,
  146054. };
  146055. static float _vq_quantthresh__44u5__p4_0[] = {
  146056. -1.5, -0.5, 0.5, 1.5,
  146057. };
  146058. static long _vq_quantmap__44u5__p4_0[] = {
  146059. 3, 1, 0, 2, 4,
  146060. };
  146061. static encode_aux_threshmatch _vq_auxt__44u5__p4_0 = {
  146062. _vq_quantthresh__44u5__p4_0,
  146063. _vq_quantmap__44u5__p4_0,
  146064. 5,
  146065. 5
  146066. };
  146067. static static_codebook _44u5__p4_0 = {
  146068. 4, 625,
  146069. _vq_lengthlist__44u5__p4_0,
  146070. 1, -533725184, 1611661312, 3, 0,
  146071. _vq_quantlist__44u5__p4_0,
  146072. NULL,
  146073. &_vq_auxt__44u5__p4_0,
  146074. NULL,
  146075. 0
  146076. };
  146077. static long _vq_quantlist__44u5__p5_0[] = {
  146078. 4,
  146079. 3,
  146080. 5,
  146081. 2,
  146082. 6,
  146083. 1,
  146084. 7,
  146085. 0,
  146086. 8,
  146087. };
  146088. static long _vq_lengthlist__44u5__p5_0[] = {
  146089. 2, 3, 3, 6, 6, 8, 8,10,10, 4, 5, 5, 8, 7, 8, 8,
  146090. 11,10, 3, 5, 5, 7, 8, 8, 8,10,11, 6, 8, 7,10, 9,
  146091. 10,10,11,11, 6, 7, 8, 9, 9, 9,10,11,12, 8, 8, 8,
  146092. 10,10,11,11,13,12, 8, 8, 9, 9,10,11,11,12,13,10,
  146093. 11,10,12,11,13,12,14,14,10,10,11,11,12,12,13,14,
  146094. 14,
  146095. };
  146096. static float _vq_quantthresh__44u5__p5_0[] = {
  146097. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  146098. };
  146099. static long _vq_quantmap__44u5__p5_0[] = {
  146100. 7, 5, 3, 1, 0, 2, 4, 6,
  146101. 8,
  146102. };
  146103. static encode_aux_threshmatch _vq_auxt__44u5__p5_0 = {
  146104. _vq_quantthresh__44u5__p5_0,
  146105. _vq_quantmap__44u5__p5_0,
  146106. 9,
  146107. 9
  146108. };
  146109. static static_codebook _44u5__p5_0 = {
  146110. 2, 81,
  146111. _vq_lengthlist__44u5__p5_0,
  146112. 1, -531628032, 1611661312, 4, 0,
  146113. _vq_quantlist__44u5__p5_0,
  146114. NULL,
  146115. &_vq_auxt__44u5__p5_0,
  146116. NULL,
  146117. 0
  146118. };
  146119. static long _vq_quantlist__44u5__p6_0[] = {
  146120. 4,
  146121. 3,
  146122. 5,
  146123. 2,
  146124. 6,
  146125. 1,
  146126. 7,
  146127. 0,
  146128. 8,
  146129. };
  146130. static long _vq_lengthlist__44u5__p6_0[] = {
  146131. 3, 4, 4, 5, 5, 7, 7, 9, 9, 4, 5, 4, 6, 6, 7, 7,
  146132. 9, 9, 4, 4, 5, 6, 6, 7, 7, 9, 9, 5, 6, 6, 7, 7,
  146133. 8, 8,10,10, 6, 6, 6, 7, 7, 8, 8,10,10, 7, 7, 7,
  146134. 8, 8, 9, 9,11,10, 7, 7, 7, 8, 8, 9, 9,10,11, 9,
  146135. 9, 9,10,10,11,10,11,11, 9, 9, 9,10,10,11,10,11,
  146136. 11,
  146137. };
  146138. static float _vq_quantthresh__44u5__p6_0[] = {
  146139. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  146140. };
  146141. static long _vq_quantmap__44u5__p6_0[] = {
  146142. 7, 5, 3, 1, 0, 2, 4, 6,
  146143. 8,
  146144. };
  146145. static encode_aux_threshmatch _vq_auxt__44u5__p6_0 = {
  146146. _vq_quantthresh__44u5__p6_0,
  146147. _vq_quantmap__44u5__p6_0,
  146148. 9,
  146149. 9
  146150. };
  146151. static static_codebook _44u5__p6_0 = {
  146152. 2, 81,
  146153. _vq_lengthlist__44u5__p6_0,
  146154. 1, -531628032, 1611661312, 4, 0,
  146155. _vq_quantlist__44u5__p6_0,
  146156. NULL,
  146157. &_vq_auxt__44u5__p6_0,
  146158. NULL,
  146159. 0
  146160. };
  146161. static long _vq_quantlist__44u5__p7_0[] = {
  146162. 1,
  146163. 0,
  146164. 2,
  146165. };
  146166. static long _vq_lengthlist__44u5__p7_0[] = {
  146167. 1, 4, 4, 5, 7, 7, 5, 7, 7, 5, 9, 9, 8,11,10, 7,
  146168. 11,10, 5, 9, 9, 7,10,10, 8,10,11, 4, 9, 9, 9,12,
  146169. 12, 9,12,12, 8,12,12,11,12,12,10,12,13, 7,12,12,
  146170. 11,12,12,10,12,13, 4, 9, 9, 9,12,12, 9,12,12, 7,
  146171. 12,11,10,13,13,11,12,12, 7,12,12,10,13,13,11,12,
  146172. 12,
  146173. };
  146174. static float _vq_quantthresh__44u5__p7_0[] = {
  146175. -5.5, 5.5,
  146176. };
  146177. static long _vq_quantmap__44u5__p7_0[] = {
  146178. 1, 0, 2,
  146179. };
  146180. static encode_aux_threshmatch _vq_auxt__44u5__p7_0 = {
  146181. _vq_quantthresh__44u5__p7_0,
  146182. _vq_quantmap__44u5__p7_0,
  146183. 3,
  146184. 3
  146185. };
  146186. static static_codebook _44u5__p7_0 = {
  146187. 4, 81,
  146188. _vq_lengthlist__44u5__p7_0,
  146189. 1, -529137664, 1618345984, 2, 0,
  146190. _vq_quantlist__44u5__p7_0,
  146191. NULL,
  146192. &_vq_auxt__44u5__p7_0,
  146193. NULL,
  146194. 0
  146195. };
  146196. static long _vq_quantlist__44u5__p7_1[] = {
  146197. 5,
  146198. 4,
  146199. 6,
  146200. 3,
  146201. 7,
  146202. 2,
  146203. 8,
  146204. 1,
  146205. 9,
  146206. 0,
  146207. 10,
  146208. };
  146209. static long _vq_lengthlist__44u5__p7_1[] = {
  146210. 2, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8, 4, 5, 5, 7, 7,
  146211. 8, 8, 9, 8, 8, 9, 4, 5, 5, 7, 7, 8, 8, 9, 9, 8,
  146212. 9, 6, 7, 7, 8, 8, 9, 8, 9, 9, 9, 9, 6, 7, 7, 8,
  146213. 8, 9, 9, 9, 9, 9, 9, 7, 8, 8, 9, 9, 9, 9, 9, 9,
  146214. 9, 9, 7, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 8, 9, 9,
  146215. 9, 9, 9, 9,10,10,10,10, 8, 9, 9, 9, 9, 9, 9,10,
  146216. 10,10,10, 8, 9, 9, 9, 9, 9, 9,10,10,10,10, 8, 9,
  146217. 9, 9, 9, 9, 9,10,10,10,10,
  146218. };
  146219. static float _vq_quantthresh__44u5__p7_1[] = {
  146220. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  146221. 3.5, 4.5,
  146222. };
  146223. static long _vq_quantmap__44u5__p7_1[] = {
  146224. 9, 7, 5, 3, 1, 0, 2, 4,
  146225. 6, 8, 10,
  146226. };
  146227. static encode_aux_threshmatch _vq_auxt__44u5__p7_1 = {
  146228. _vq_quantthresh__44u5__p7_1,
  146229. _vq_quantmap__44u5__p7_1,
  146230. 11,
  146231. 11
  146232. };
  146233. static static_codebook _44u5__p7_1 = {
  146234. 2, 121,
  146235. _vq_lengthlist__44u5__p7_1,
  146236. 1, -531365888, 1611661312, 4, 0,
  146237. _vq_quantlist__44u5__p7_1,
  146238. NULL,
  146239. &_vq_auxt__44u5__p7_1,
  146240. NULL,
  146241. 0
  146242. };
  146243. static long _vq_quantlist__44u5__p8_0[] = {
  146244. 5,
  146245. 4,
  146246. 6,
  146247. 3,
  146248. 7,
  146249. 2,
  146250. 8,
  146251. 1,
  146252. 9,
  146253. 0,
  146254. 10,
  146255. };
  146256. static long _vq_lengthlist__44u5__p8_0[] = {
  146257. 1, 4, 4, 6, 6, 8, 8, 9, 9,10,10, 4, 6, 6, 7, 7,
  146258. 9, 9,10,10,11,11, 4, 6, 6, 7, 7, 9, 9,10,10,11,
  146259. 11, 6, 8, 7, 9, 9,10,10,11,11,13,12, 6, 8, 8, 9,
  146260. 9,10,10,11,11,12,13, 8, 9, 9,10,10,12,12,13,12,
  146261. 14,13, 8, 9, 9,10,10,12,12,13,13,14,14, 9,11,11,
  146262. 12,12,13,13,14,14,15,14, 9,11,11,12,12,13,13,14,
  146263. 14,15,14,11,12,12,13,13,14,14,15,14,15,14,11,11,
  146264. 12,13,13,14,14,14,14,15,15,
  146265. };
  146266. static float _vq_quantthresh__44u5__p8_0[] = {
  146267. -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5, 27.5,
  146268. 38.5, 49.5,
  146269. };
  146270. static long _vq_quantmap__44u5__p8_0[] = {
  146271. 9, 7, 5, 3, 1, 0, 2, 4,
  146272. 6, 8, 10,
  146273. };
  146274. static encode_aux_threshmatch _vq_auxt__44u5__p8_0 = {
  146275. _vq_quantthresh__44u5__p8_0,
  146276. _vq_quantmap__44u5__p8_0,
  146277. 11,
  146278. 11
  146279. };
  146280. static static_codebook _44u5__p8_0 = {
  146281. 2, 121,
  146282. _vq_lengthlist__44u5__p8_0,
  146283. 1, -524582912, 1618345984, 4, 0,
  146284. _vq_quantlist__44u5__p8_0,
  146285. NULL,
  146286. &_vq_auxt__44u5__p8_0,
  146287. NULL,
  146288. 0
  146289. };
  146290. static long _vq_quantlist__44u5__p8_1[] = {
  146291. 5,
  146292. 4,
  146293. 6,
  146294. 3,
  146295. 7,
  146296. 2,
  146297. 8,
  146298. 1,
  146299. 9,
  146300. 0,
  146301. 10,
  146302. };
  146303. static long _vq_lengthlist__44u5__p8_1[] = {
  146304. 3, 5, 5, 6, 6, 7, 7, 7, 7, 7, 7, 5, 6, 5, 7, 6,
  146305. 7, 7, 8, 8, 8, 8, 5, 5, 5, 6, 6, 7, 7, 8, 8, 8,
  146306. 8, 6, 7, 6, 7, 7, 8, 8, 8, 8, 8, 8, 6, 6, 7, 7,
  146307. 7, 8, 8, 8, 8, 8, 8, 7, 7, 7, 8, 8, 8, 8, 8, 8,
  146308. 8, 8, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 7, 8, 8,
  146309. 8, 8, 8, 8, 8, 8, 8, 8, 7, 8, 8, 8, 8, 8, 8, 8,
  146310. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  146311. 8, 8, 8, 8, 8, 8, 8, 8, 8,
  146312. };
  146313. static float _vq_quantthresh__44u5__p8_1[] = {
  146314. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  146315. 3.5, 4.5,
  146316. };
  146317. static long _vq_quantmap__44u5__p8_1[] = {
  146318. 9, 7, 5, 3, 1, 0, 2, 4,
  146319. 6, 8, 10,
  146320. };
  146321. static encode_aux_threshmatch _vq_auxt__44u5__p8_1 = {
  146322. _vq_quantthresh__44u5__p8_1,
  146323. _vq_quantmap__44u5__p8_1,
  146324. 11,
  146325. 11
  146326. };
  146327. static static_codebook _44u5__p8_1 = {
  146328. 2, 121,
  146329. _vq_lengthlist__44u5__p8_1,
  146330. 1, -531365888, 1611661312, 4, 0,
  146331. _vq_quantlist__44u5__p8_1,
  146332. NULL,
  146333. &_vq_auxt__44u5__p8_1,
  146334. NULL,
  146335. 0
  146336. };
  146337. static long _vq_quantlist__44u5__p9_0[] = {
  146338. 6,
  146339. 5,
  146340. 7,
  146341. 4,
  146342. 8,
  146343. 3,
  146344. 9,
  146345. 2,
  146346. 10,
  146347. 1,
  146348. 11,
  146349. 0,
  146350. 12,
  146351. };
  146352. static long _vq_lengthlist__44u5__p9_0[] = {
  146353. 1, 3, 2,12,10,13,13,13,13,13,13,13,13, 4, 9, 9,
  146354. 13,13,13,13,13,13,13,13,13,13, 5,10, 9,13,13,13,
  146355. 13,13,13,13,13,13,13,12,13,13,13,13,13,13,13,13,
  146356. 13,13,13,13,11,13,13,13,13,13,13,13,13,13,13,13,
  146357. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  146358. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  146359. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  146360. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  146361. 13,13,13,13,13,13,13,13,13,13,13,13,13,12,12,12,
  146362. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  146363. 12,12,12,12,12,12,12,12,12,
  146364. };
  146365. static float _vq_quantthresh__44u5__p9_0[] = {
  146366. -1402.5, -1147.5, -892.5, -637.5, -382.5, -127.5, 127.5, 382.5,
  146367. 637.5, 892.5, 1147.5, 1402.5,
  146368. };
  146369. static long _vq_quantmap__44u5__p9_0[] = {
  146370. 11, 9, 7, 5, 3, 1, 0, 2,
  146371. 4, 6, 8, 10, 12,
  146372. };
  146373. static encode_aux_threshmatch _vq_auxt__44u5__p9_0 = {
  146374. _vq_quantthresh__44u5__p9_0,
  146375. _vq_quantmap__44u5__p9_0,
  146376. 13,
  146377. 13
  146378. };
  146379. static static_codebook _44u5__p9_0 = {
  146380. 2, 169,
  146381. _vq_lengthlist__44u5__p9_0,
  146382. 1, -514332672, 1627381760, 4, 0,
  146383. _vq_quantlist__44u5__p9_0,
  146384. NULL,
  146385. &_vq_auxt__44u5__p9_0,
  146386. NULL,
  146387. 0
  146388. };
  146389. static long _vq_quantlist__44u5__p9_1[] = {
  146390. 7,
  146391. 6,
  146392. 8,
  146393. 5,
  146394. 9,
  146395. 4,
  146396. 10,
  146397. 3,
  146398. 11,
  146399. 2,
  146400. 12,
  146401. 1,
  146402. 13,
  146403. 0,
  146404. 14,
  146405. };
  146406. static long _vq_lengthlist__44u5__p9_1[] = {
  146407. 1, 4, 4, 7, 7, 8, 8, 8, 7, 8, 7, 9, 8, 9, 9, 4,
  146408. 7, 6, 9, 8,10,10, 9, 8, 9, 9, 9, 9, 9, 8, 5, 6,
  146409. 6, 8, 9,10,10, 9, 9, 9,10,10,10,10,11, 7, 8, 8,
  146410. 10,10,11,11,10,10,11,11,11,12,11,11, 7, 8, 8,10,
  146411. 10,11,11,10,10,11,11,12,11,11,11, 8, 9, 9,11,11,
  146412. 12,12,11,11,12,11,12,12,12,12, 8, 9,10,11,11,12,
  146413. 12,11,11,12,12,12,12,12,12, 8, 9, 9,10,10,12,11,
  146414. 12,12,12,12,12,12,12,13, 8, 9, 9,11,11,11,11,12,
  146415. 12,12,12,13,12,13,13, 9,10,10,11,11,12,12,12,13,
  146416. 12,13,13,13,14,13, 9,10,10,11,11,12,12,12,13,13,
  146417. 12,13,13,14,13, 9,11,10,12,11,13,12,12,13,13,13,
  146418. 13,13,13,14, 9,10,10,12,12,12,12,12,13,13,13,13,
  146419. 13,14,14,10,11,11,12,12,12,13,13,13,14,14,13,14,
  146420. 14,14,10,11,11,12,12,12,12,13,12,13,14,13,14,14,
  146421. 14,
  146422. };
  146423. static float _vq_quantthresh__44u5__p9_1[] = {
  146424. -110.5, -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5,
  146425. 25.5, 42.5, 59.5, 76.5, 93.5, 110.5,
  146426. };
  146427. static long _vq_quantmap__44u5__p9_1[] = {
  146428. 13, 11, 9, 7, 5, 3, 1, 0,
  146429. 2, 4, 6, 8, 10, 12, 14,
  146430. };
  146431. static encode_aux_threshmatch _vq_auxt__44u5__p9_1 = {
  146432. _vq_quantthresh__44u5__p9_1,
  146433. _vq_quantmap__44u5__p9_1,
  146434. 15,
  146435. 15
  146436. };
  146437. static static_codebook _44u5__p9_1 = {
  146438. 2, 225,
  146439. _vq_lengthlist__44u5__p9_1,
  146440. 1, -522338304, 1620115456, 4, 0,
  146441. _vq_quantlist__44u5__p9_1,
  146442. NULL,
  146443. &_vq_auxt__44u5__p9_1,
  146444. NULL,
  146445. 0
  146446. };
  146447. static long _vq_quantlist__44u5__p9_2[] = {
  146448. 8,
  146449. 7,
  146450. 9,
  146451. 6,
  146452. 10,
  146453. 5,
  146454. 11,
  146455. 4,
  146456. 12,
  146457. 3,
  146458. 13,
  146459. 2,
  146460. 14,
  146461. 1,
  146462. 15,
  146463. 0,
  146464. 16,
  146465. };
  146466. static long _vq_lengthlist__44u5__p9_2[] = {
  146467. 2, 5, 5, 7, 7, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  146468. 9, 5, 6, 6, 7, 7, 8, 8, 9, 8, 9, 9, 9, 9, 9, 9,
  146469. 9, 9, 5, 6, 6, 7, 7, 8, 8, 9, 8, 9, 9, 9, 9, 9,
  146470. 9, 9, 9, 7, 7, 7, 8, 8, 9, 8, 9, 9, 9, 9, 9, 9,
  146471. 9, 9, 9, 9, 7, 7, 7, 8, 8, 9, 8, 9, 9, 9, 9, 9,
  146472. 9, 9, 9, 9, 9, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9,
  146473. 9,10, 9,10,10,10, 8, 8, 8, 9, 8, 9, 9, 9, 9, 9,
  146474. 9, 9,10, 9,10, 9,10, 8, 9, 9, 9, 9, 9, 9, 9, 9,
  146475. 9,10, 9,10,10,10,10,10, 8, 9, 9, 9, 9, 9, 9,10,
  146476. 9,10, 9,10,10,10,10,10,10, 9, 9, 9, 9, 9,10, 9,
  146477. 10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9, 9,
  146478. 9,10, 9,10, 9,10,10,10,10,10,10, 9, 9, 9, 9, 9,
  146479. 10,10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9,
  146480. 9, 9,10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9,
  146481. 9,10,10, 9,10,10,10,10,10,10,10,10,10,10, 9, 9,
  146482. 9, 9, 9,10,10,10,10,10,10,10,10,10,10,10,10, 9,
  146483. 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,10,10,10,
  146484. 9, 9, 9,10, 9,10,10,10,10,10,10,10,10,10,10,10,
  146485. 10,
  146486. };
  146487. static float _vq_quantthresh__44u5__p9_2[] = {
  146488. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  146489. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  146490. };
  146491. static long _vq_quantmap__44u5__p9_2[] = {
  146492. 15, 13, 11, 9, 7, 5, 3, 1,
  146493. 0, 2, 4, 6, 8, 10, 12, 14,
  146494. 16,
  146495. };
  146496. static encode_aux_threshmatch _vq_auxt__44u5__p9_2 = {
  146497. _vq_quantthresh__44u5__p9_2,
  146498. _vq_quantmap__44u5__p9_2,
  146499. 17,
  146500. 17
  146501. };
  146502. static static_codebook _44u5__p9_2 = {
  146503. 2, 289,
  146504. _vq_lengthlist__44u5__p9_2,
  146505. 1, -529530880, 1611661312, 5, 0,
  146506. _vq_quantlist__44u5__p9_2,
  146507. NULL,
  146508. &_vq_auxt__44u5__p9_2,
  146509. NULL,
  146510. 0
  146511. };
  146512. static long _huff_lengthlist__44u5__short[] = {
  146513. 4,10,17,13,17,13,17,17,17,17, 3, 6, 8, 9,11, 9,
  146514. 15,12,16,17, 6, 5, 5, 7, 7, 8,10,11,17,17, 7, 8,
  146515. 7, 9, 9,10,13,13,17,17, 8, 6, 5, 7, 4, 7, 5, 8,
  146516. 14,17, 9, 9, 8, 9, 7, 9, 8,10,16,17,12,10, 7, 8,
  146517. 4, 7, 4, 7,16,17,12,11, 9,10, 6, 9, 5, 7,14,17,
  146518. 14,13,10,15, 4, 8, 3, 5,14,17,17,14,11,15, 6,10,
  146519. 6, 8,15,17,
  146520. };
  146521. static static_codebook _huff_book__44u5__short = {
  146522. 2, 100,
  146523. _huff_lengthlist__44u5__short,
  146524. 0, 0, 0, 0, 0,
  146525. NULL,
  146526. NULL,
  146527. NULL,
  146528. NULL,
  146529. 0
  146530. };
  146531. static long _huff_lengthlist__44u6__long[] = {
  146532. 3, 9,14,13,14,13,16,12,13,14, 5, 4, 6, 6, 8, 9,
  146533. 11,10,12,15,10, 5, 5, 6, 6, 8,10,10,13,16,10, 6,
  146534. 6, 6, 6, 8, 9, 9,12,14,13, 7, 6, 6, 4, 6, 6, 7,
  146535. 11,14,10, 7, 7, 7, 6, 6, 6, 7,10,13,15,10, 9, 8,
  146536. 5, 6, 5, 6,10,14,10, 9, 8, 8, 6, 6, 5, 4, 6,11,
  146537. 11,11,12,11,10, 9, 9, 5, 5, 9,10,12,15,13,13,13,
  146538. 13, 8, 7, 7,
  146539. };
  146540. static static_codebook _huff_book__44u6__long = {
  146541. 2, 100,
  146542. _huff_lengthlist__44u6__long,
  146543. 0, 0, 0, 0, 0,
  146544. NULL,
  146545. NULL,
  146546. NULL,
  146547. NULL,
  146548. 0
  146549. };
  146550. static long _vq_quantlist__44u6__p1_0[] = {
  146551. 1,
  146552. 0,
  146553. 2,
  146554. };
  146555. static long _vq_lengthlist__44u6__p1_0[] = {
  146556. 1, 4, 4, 4, 8, 7, 5, 7, 7, 5, 8, 8, 8,10,10, 7,
  146557. 9,10, 5, 8, 8, 7,10, 9, 8,10,10, 5, 8, 8, 8,10,
  146558. 10, 8,10,10, 8,10,10,10,12,13,10,13,13, 7,10,10,
  146559. 10,13,11,10,13,13, 5, 8, 8, 8,11,10, 8,10,10, 7,
  146560. 10,10,10,13,13,10,11,13, 8,10,11,10,13,13,10,13,
  146561. 12,
  146562. };
  146563. static float _vq_quantthresh__44u6__p1_0[] = {
  146564. -0.5, 0.5,
  146565. };
  146566. static long _vq_quantmap__44u6__p1_0[] = {
  146567. 1, 0, 2,
  146568. };
  146569. static encode_aux_threshmatch _vq_auxt__44u6__p1_0 = {
  146570. _vq_quantthresh__44u6__p1_0,
  146571. _vq_quantmap__44u6__p1_0,
  146572. 3,
  146573. 3
  146574. };
  146575. static static_codebook _44u6__p1_0 = {
  146576. 4, 81,
  146577. _vq_lengthlist__44u6__p1_0,
  146578. 1, -535822336, 1611661312, 2, 0,
  146579. _vq_quantlist__44u6__p1_0,
  146580. NULL,
  146581. &_vq_auxt__44u6__p1_0,
  146582. NULL,
  146583. 0
  146584. };
  146585. static long _vq_quantlist__44u6__p2_0[] = {
  146586. 1,
  146587. 0,
  146588. 2,
  146589. };
  146590. static long _vq_lengthlist__44u6__p2_0[] = {
  146591. 3, 4, 4, 5, 6, 6, 5, 6, 6, 5, 6, 6, 6, 8, 8, 6,
  146592. 7, 8, 5, 6, 6, 6, 8, 7, 6, 8, 8, 5, 6, 6, 6, 8,
  146593. 8, 6, 8, 8, 6, 8, 8, 8, 9, 9, 8, 9, 9, 6, 7, 7,
  146594. 7, 9, 8, 8, 9, 9, 5, 6, 6, 6, 8, 7, 6, 8, 8, 6,
  146595. 8, 8, 8, 9, 9, 7, 8, 9, 6, 8, 8, 8, 9, 9, 8, 9,
  146596. 9,
  146597. };
  146598. static float _vq_quantthresh__44u6__p2_0[] = {
  146599. -0.5, 0.5,
  146600. };
  146601. static long _vq_quantmap__44u6__p2_0[] = {
  146602. 1, 0, 2,
  146603. };
  146604. static encode_aux_threshmatch _vq_auxt__44u6__p2_0 = {
  146605. _vq_quantthresh__44u6__p2_0,
  146606. _vq_quantmap__44u6__p2_0,
  146607. 3,
  146608. 3
  146609. };
  146610. static static_codebook _44u6__p2_0 = {
  146611. 4, 81,
  146612. _vq_lengthlist__44u6__p2_0,
  146613. 1, -535822336, 1611661312, 2, 0,
  146614. _vq_quantlist__44u6__p2_0,
  146615. NULL,
  146616. &_vq_auxt__44u6__p2_0,
  146617. NULL,
  146618. 0
  146619. };
  146620. static long _vq_quantlist__44u6__p3_0[] = {
  146621. 2,
  146622. 1,
  146623. 3,
  146624. 0,
  146625. 4,
  146626. };
  146627. static long _vq_lengthlist__44u6__p3_0[] = {
  146628. 2, 5, 4, 8, 8, 5, 7, 6, 9, 9, 5, 6, 7, 9, 9, 8,
  146629. 9, 9,13,12, 8, 9,10,12,13, 5, 7, 7,10, 9, 7, 9,
  146630. 9,11,11, 7, 8, 9,11,11,10,11,11,14,14, 9,10,11,
  146631. 13,14, 5, 7, 7, 9,10, 6, 9, 8,11,11, 7, 9, 9,11,
  146632. 11, 9,11,10,14,13,10,11,11,14,13, 8,10,10,13,13,
  146633. 10,11,11,15,15, 9,11,11,14,14,13,14,14,17,16,12,
  146634. 13,14,16,16, 8,10,10,13,14, 9,11,11,14,15,10,11,
  146635. 12,14,15,12,14,13,16,15,13,14,14,15,17, 5, 7, 7,
  146636. 10,10, 7, 9, 9,11,11, 7, 9, 9,11,11,10,12,11,14,
  146637. 14,10,11,11,14,14, 7, 9, 9,12,11, 9,11,11,13,13,
  146638. 9,11,11,13,13,11,13,13,14,15,11,12,13,15,16, 6,
  146639. 9, 9,11,12, 8,11,10,13,12, 9,11,11,13,14,11,13,
  146640. 12,16,14,11,13,13,15,16,10,12,11,14,15,11,13,13,
  146641. 15,17,11,13,13,17,16,15,15,16,17,16,14,15,16,18,
  146642. 0, 9,11,11,14,15,10,12,12,16,15,11,13,13,16,16,
  146643. 13,15,14,18,15,14,16,16, 0, 0, 5, 7, 7,10,10, 7,
  146644. 9, 9,11,11, 7, 9, 9,11,11,10,11,11,14,14,10,11,
  146645. 12,14,14, 6, 9, 9,11,11, 9,11,11,13,13, 8,10,11,
  146646. 12,13,11,13,13,16,15,11,12,13,14,16, 7, 9, 9,11,
  146647. 12, 9,11,11,13,13, 9,11,11,13,13,11,13,13,16,15,
  146648. 11,13,12,15,15, 9,11,11,15,14,11,13,13,17,16,10,
  146649. 12,13,15,16,14,16,16, 0,18,14,14,15,15,17,10,11,
  146650. 12,15,15,11,13,13,16,16,11,13,13,16,16,14,16,16,
  146651. 19,17,14,15,15,17,17, 8,10,10,14,14,10,12,11,15,
  146652. 15,10,11,12,16,15,14,15,15,18,20,13,14,16,17,18,
  146653. 9,11,11,15,16,11,13,13,17,17,11,13,13,17,16,15,
  146654. 16,16, 0, 0,15,16,16, 0, 0, 9,11,11,15,15,10,13,
  146655. 12,17,15,11,13,13,17,16,15,17,15,20,19,15,16,16,
  146656. 19, 0,13,15,14, 0,17,14,15,16, 0,20,15,16,16, 0,
  146657. 19,17,18, 0, 0, 0,16,17,18, 0, 0,12,14,14,19,18,
  146658. 13,15,14, 0,17,14,15,16,19,19,16,18,16, 0,19,19,
  146659. 20,17,20, 0, 8,10,10,13,14,10,11,11,15,15,10,12,
  146660. 12,15,16,14,15,14,19,16,14,15,15, 0,18, 9,11,11,
  146661. 16,15,11,13,13, 0,16,11,12,13,16,17,14,16,17, 0,
  146662. 19,15,16,16,18, 0, 9,11,11,15,16,11,13,13,16,16,
  146663. 11,14,13,18,17,15,16,16,18,20,15,17,19, 0, 0,12,
  146664. 14,14,17,17,14,16,15, 0, 0,13,14,15,19, 0,16,18,
  146665. 20, 0, 0,16,16,18,18, 0,12,14,14,17,20,14,16,16,
  146666. 19, 0,14,16,14, 0,20,16,20,17, 0, 0,17, 0,15, 0,
  146667. 19,
  146668. };
  146669. static float _vq_quantthresh__44u6__p3_0[] = {
  146670. -1.5, -0.5, 0.5, 1.5,
  146671. };
  146672. static long _vq_quantmap__44u6__p3_0[] = {
  146673. 3, 1, 0, 2, 4,
  146674. };
  146675. static encode_aux_threshmatch _vq_auxt__44u6__p3_0 = {
  146676. _vq_quantthresh__44u6__p3_0,
  146677. _vq_quantmap__44u6__p3_0,
  146678. 5,
  146679. 5
  146680. };
  146681. static static_codebook _44u6__p3_0 = {
  146682. 4, 625,
  146683. _vq_lengthlist__44u6__p3_0,
  146684. 1, -533725184, 1611661312, 3, 0,
  146685. _vq_quantlist__44u6__p3_0,
  146686. NULL,
  146687. &_vq_auxt__44u6__p3_0,
  146688. NULL,
  146689. 0
  146690. };
  146691. static long _vq_quantlist__44u6__p4_0[] = {
  146692. 2,
  146693. 1,
  146694. 3,
  146695. 0,
  146696. 4,
  146697. };
  146698. static long _vq_lengthlist__44u6__p4_0[] = {
  146699. 4, 5, 5, 8, 8, 6, 7, 6, 9, 9, 6, 6, 7, 9, 9, 8,
  146700. 9, 9,11,11, 8, 9, 9,11,11, 6, 7, 7, 9, 9, 7, 8,
  146701. 8,10,10, 7, 7, 8, 9,10, 9,10,10,11,11, 9, 9,10,
  146702. 11,12, 6, 7, 7, 9, 9, 7, 8, 7,10, 9, 7, 8, 8,10,
  146703. 10, 9,10, 9,12,11, 9,10,10,12,11, 8, 9, 9,11,11,
  146704. 9,10,10,12,12, 9,10,10,12,12,11,12,12,14,13,11,
  146705. 11,12,13,13, 8, 9, 9,11,11, 9,10,10,12,12, 9,10,
  146706. 10,12,12,11,12,11,13,12,11,12,12,13,13, 5, 7, 7,
  146707. 9, 9, 7, 8, 7,10,10, 7, 7, 8,10,10, 9,10,10,12,
  146708. 11, 9,10,10,11,12, 7, 8, 8,10,10, 8, 8, 9,11,11,
  146709. 8, 9, 9,11,11,10,10,11,12,13,10,10,11,12,12, 6,
  146710. 7, 7,10,10, 7, 9, 8,11,10, 8, 8, 9,10,11,10,11,
  146711. 10,13,11,10,11,11,12,12, 9,10,10,12,12,10,10,11,
  146712. 13,13,10,11,11,12,13,12,12,12,13,14,12,12,13,14,
  146713. 14, 9,10,10,12,12, 9,10,10,13,12,10,11,11,13,13,
  146714. 11,12,11,14,12,12,13,13,14,14, 6, 7, 7, 9, 9, 7,
  146715. 8, 7,10,10, 7, 8, 8,10,10, 9,10,10,12,11, 9,10,
  146716. 10,11,12, 6, 7, 7,10,10, 8, 9, 8,11,10, 7, 8, 9,
  146717. 10,11,10,11,11,12,12,10,10,11,11,13, 7, 8, 8,10,
  146718. 10, 8, 9, 9,11,11, 8, 9, 8,11,11,10,11,10,13,12,
  146719. 10,11,11,13,12, 9,10,10,12,12,10,11,11,13,12, 9,
  146720. 10,10,12,13,12,13,12,14,14,11,11,12,12,14, 9,10,
  146721. 10,12,12,10,11,11,13,13,10,11,10,13,12,12,12,12,
  146722. 14,14,12,13,12,14,13, 8, 9, 9,11,11, 9,10,10,12,
  146723. 12, 9,10,10,12,12,11,12,12,14,13,11,12,12,13,14,
  146724. 9,10,10,12,12,10,11,11,13,13,10,11,11,13,13,12,
  146725. 12,13,14,15,12,12,13,14,14, 9,10,10,12,12, 9,11,
  146726. 10,13,12,10,10,11,12,13,12,13,12,14,13,12,12,13,
  146727. 14,15,11,12,12,14,13,11,12,12,14,14,12,13,13,14,
  146728. 14,13,13,14,14,16,13,14,14,15,15,11,12,11,13,13,
  146729. 11,12,11,14,13,12,12,13,14,15,12,14,12,15,12,13,
  146730. 14,15,15,16, 8, 9, 9,11,11, 9,10,10,12,12, 9,10,
  146731. 10,12,12,11,12,12,14,13,11,12,12,13,13, 9,10,10,
  146732. 12,12,10,11,10,13,12, 9,10,11,12,13,12,13,12,14,
  146733. 14,12,12,13,13,14, 9,10,10,12,12,10,11,11,13,13,
  146734. 10,11,11,13,13,12,13,12,14,14,12,13,13,14,14,11,
  146735. 11,11,13,13,12,13,12,14,14,11,11,12,13,14,14,14,
  146736. 14,16,15,12,12,14,12,15,11,12,12,13,14,12,13,13,
  146737. 14,15,11,12,12,14,14,13,14,14,16,16,13,14,13,16,
  146738. 13,
  146739. };
  146740. static float _vq_quantthresh__44u6__p4_0[] = {
  146741. -1.5, -0.5, 0.5, 1.5,
  146742. };
  146743. static long _vq_quantmap__44u6__p4_0[] = {
  146744. 3, 1, 0, 2, 4,
  146745. };
  146746. static encode_aux_threshmatch _vq_auxt__44u6__p4_0 = {
  146747. _vq_quantthresh__44u6__p4_0,
  146748. _vq_quantmap__44u6__p4_0,
  146749. 5,
  146750. 5
  146751. };
  146752. static static_codebook _44u6__p4_0 = {
  146753. 4, 625,
  146754. _vq_lengthlist__44u6__p4_0,
  146755. 1, -533725184, 1611661312, 3, 0,
  146756. _vq_quantlist__44u6__p4_0,
  146757. NULL,
  146758. &_vq_auxt__44u6__p4_0,
  146759. NULL,
  146760. 0
  146761. };
  146762. static long _vq_quantlist__44u6__p5_0[] = {
  146763. 4,
  146764. 3,
  146765. 5,
  146766. 2,
  146767. 6,
  146768. 1,
  146769. 7,
  146770. 0,
  146771. 8,
  146772. };
  146773. static long _vq_lengthlist__44u6__p5_0[] = {
  146774. 2, 3, 3, 6, 6, 8, 8,10,10, 4, 5, 5, 8, 7, 8, 8,
  146775. 11,11, 3, 5, 5, 7, 8, 8, 8,11,11, 6, 8, 7, 9, 9,
  146776. 10, 9,12,11, 6, 7, 8, 9, 9, 9,10,11,12, 8, 8, 8,
  146777. 10, 9,12,11,13,13, 8, 8, 9, 9,10,11,12,13,13,10,
  146778. 11,11,12,12,13,13,14,14,10,10,11,11,12,13,13,14,
  146779. 14,
  146780. };
  146781. static float _vq_quantthresh__44u6__p5_0[] = {
  146782. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  146783. };
  146784. static long _vq_quantmap__44u6__p5_0[] = {
  146785. 7, 5, 3, 1, 0, 2, 4, 6,
  146786. 8,
  146787. };
  146788. static encode_aux_threshmatch _vq_auxt__44u6__p5_0 = {
  146789. _vq_quantthresh__44u6__p5_0,
  146790. _vq_quantmap__44u6__p5_0,
  146791. 9,
  146792. 9
  146793. };
  146794. static static_codebook _44u6__p5_0 = {
  146795. 2, 81,
  146796. _vq_lengthlist__44u6__p5_0,
  146797. 1, -531628032, 1611661312, 4, 0,
  146798. _vq_quantlist__44u6__p5_0,
  146799. NULL,
  146800. &_vq_auxt__44u6__p5_0,
  146801. NULL,
  146802. 0
  146803. };
  146804. static long _vq_quantlist__44u6__p6_0[] = {
  146805. 4,
  146806. 3,
  146807. 5,
  146808. 2,
  146809. 6,
  146810. 1,
  146811. 7,
  146812. 0,
  146813. 8,
  146814. };
  146815. static long _vq_lengthlist__44u6__p6_0[] = {
  146816. 3, 4, 4, 5, 5, 7, 7, 9, 9, 4, 5, 4, 6, 6, 7, 7,
  146817. 9, 9, 4, 4, 5, 6, 6, 7, 8, 9, 9, 5, 6, 6, 7, 7,
  146818. 8, 8,10,10, 5, 6, 6, 7, 7, 8, 8,10,10, 7, 8, 7,
  146819. 8, 8,10, 9,11,11, 7, 7, 8, 8, 8, 9,10,10,11, 9,
  146820. 9, 9,10,10,11,11,12,11, 9, 9, 9,10,10,11,11,11,
  146821. 12,
  146822. };
  146823. static float _vq_quantthresh__44u6__p6_0[] = {
  146824. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  146825. };
  146826. static long _vq_quantmap__44u6__p6_0[] = {
  146827. 7, 5, 3, 1, 0, 2, 4, 6,
  146828. 8,
  146829. };
  146830. static encode_aux_threshmatch _vq_auxt__44u6__p6_0 = {
  146831. _vq_quantthresh__44u6__p6_0,
  146832. _vq_quantmap__44u6__p6_0,
  146833. 9,
  146834. 9
  146835. };
  146836. static static_codebook _44u6__p6_0 = {
  146837. 2, 81,
  146838. _vq_lengthlist__44u6__p6_0,
  146839. 1, -531628032, 1611661312, 4, 0,
  146840. _vq_quantlist__44u6__p6_0,
  146841. NULL,
  146842. &_vq_auxt__44u6__p6_0,
  146843. NULL,
  146844. 0
  146845. };
  146846. static long _vq_quantlist__44u6__p7_0[] = {
  146847. 1,
  146848. 0,
  146849. 2,
  146850. };
  146851. static long _vq_lengthlist__44u6__p7_0[] = {
  146852. 1, 4, 4, 5, 7, 7, 5, 7, 7, 5, 9, 8, 7,10,10, 8,
  146853. 10,10, 5, 8, 9, 7,10,10, 7,10, 9, 4, 8, 8, 9,11,
  146854. 11, 8,11,11, 7,11,11,10,10,13,10,13,13, 7,11,11,
  146855. 10,13,12,10,13,13, 5, 9, 8, 8,11,11, 9,11,11, 7,
  146856. 11,11,10,13,13,10,12,13, 7,11,11,10,13,13, 9,13,
  146857. 10,
  146858. };
  146859. static float _vq_quantthresh__44u6__p7_0[] = {
  146860. -5.5, 5.5,
  146861. };
  146862. static long _vq_quantmap__44u6__p7_0[] = {
  146863. 1, 0, 2,
  146864. };
  146865. static encode_aux_threshmatch _vq_auxt__44u6__p7_0 = {
  146866. _vq_quantthresh__44u6__p7_0,
  146867. _vq_quantmap__44u6__p7_0,
  146868. 3,
  146869. 3
  146870. };
  146871. static static_codebook _44u6__p7_0 = {
  146872. 4, 81,
  146873. _vq_lengthlist__44u6__p7_0,
  146874. 1, -529137664, 1618345984, 2, 0,
  146875. _vq_quantlist__44u6__p7_0,
  146876. NULL,
  146877. &_vq_auxt__44u6__p7_0,
  146878. NULL,
  146879. 0
  146880. };
  146881. static long _vq_quantlist__44u6__p7_1[] = {
  146882. 5,
  146883. 4,
  146884. 6,
  146885. 3,
  146886. 7,
  146887. 2,
  146888. 8,
  146889. 1,
  146890. 9,
  146891. 0,
  146892. 10,
  146893. };
  146894. static long _vq_lengthlist__44u6__p7_1[] = {
  146895. 3, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8, 4, 5, 5, 7, 6,
  146896. 8, 8, 8, 8, 8, 8, 4, 5, 5, 6, 7, 8, 8, 8, 8, 8,
  146897. 8, 6, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 6, 7, 7, 7,
  146898. 7, 8, 8, 8, 8, 8, 8, 7, 8, 8, 8, 8, 8, 8, 9, 9,
  146899. 9, 9, 7, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9, 8, 8, 8,
  146900. 8, 8, 9, 9, 9, 9, 9, 9, 8, 8, 8, 8, 8, 9, 9, 9,
  146901. 9, 9, 9, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 8, 8,
  146902. 8, 8, 8, 9, 9, 9, 9, 9, 9,
  146903. };
  146904. static float _vq_quantthresh__44u6__p7_1[] = {
  146905. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  146906. 3.5, 4.5,
  146907. };
  146908. static long _vq_quantmap__44u6__p7_1[] = {
  146909. 9, 7, 5, 3, 1, 0, 2, 4,
  146910. 6, 8, 10,
  146911. };
  146912. static encode_aux_threshmatch _vq_auxt__44u6__p7_1 = {
  146913. _vq_quantthresh__44u6__p7_1,
  146914. _vq_quantmap__44u6__p7_1,
  146915. 11,
  146916. 11
  146917. };
  146918. static static_codebook _44u6__p7_1 = {
  146919. 2, 121,
  146920. _vq_lengthlist__44u6__p7_1,
  146921. 1, -531365888, 1611661312, 4, 0,
  146922. _vq_quantlist__44u6__p7_1,
  146923. NULL,
  146924. &_vq_auxt__44u6__p7_1,
  146925. NULL,
  146926. 0
  146927. };
  146928. static long _vq_quantlist__44u6__p8_0[] = {
  146929. 5,
  146930. 4,
  146931. 6,
  146932. 3,
  146933. 7,
  146934. 2,
  146935. 8,
  146936. 1,
  146937. 9,
  146938. 0,
  146939. 10,
  146940. };
  146941. static long _vq_lengthlist__44u6__p8_0[] = {
  146942. 1, 4, 4, 6, 6, 8, 8, 9, 9,10,10, 4, 6, 6, 7, 7,
  146943. 9, 9,10,10,11,11, 4, 6, 6, 7, 7, 9, 9,10,10,11,
  146944. 11, 6, 8, 8, 9, 9,10,10,11,11,12,12, 6, 8, 8, 9,
  146945. 9,10,10,11,11,12,12, 8, 9, 9,10,10,11,11,12,12,
  146946. 13,13, 8, 9, 9,10,10,11,11,12,12,13,13,10,10,10,
  146947. 11,11,13,13,13,13,15,14, 9,10,10,12,11,12,13,13,
  146948. 13,14,15,11,12,12,13,13,13,13,15,14,15,15,11,11,
  146949. 12,13,13,14,14,14,15,15,15,
  146950. };
  146951. static float _vq_quantthresh__44u6__p8_0[] = {
  146952. -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5, 27.5,
  146953. 38.5, 49.5,
  146954. };
  146955. static long _vq_quantmap__44u6__p8_0[] = {
  146956. 9, 7, 5, 3, 1, 0, 2, 4,
  146957. 6, 8, 10,
  146958. };
  146959. static encode_aux_threshmatch _vq_auxt__44u6__p8_0 = {
  146960. _vq_quantthresh__44u6__p8_0,
  146961. _vq_quantmap__44u6__p8_0,
  146962. 11,
  146963. 11
  146964. };
  146965. static static_codebook _44u6__p8_0 = {
  146966. 2, 121,
  146967. _vq_lengthlist__44u6__p8_0,
  146968. 1, -524582912, 1618345984, 4, 0,
  146969. _vq_quantlist__44u6__p8_0,
  146970. NULL,
  146971. &_vq_auxt__44u6__p8_0,
  146972. NULL,
  146973. 0
  146974. };
  146975. static long _vq_quantlist__44u6__p8_1[] = {
  146976. 5,
  146977. 4,
  146978. 6,
  146979. 3,
  146980. 7,
  146981. 2,
  146982. 8,
  146983. 1,
  146984. 9,
  146985. 0,
  146986. 10,
  146987. };
  146988. static long _vq_lengthlist__44u6__p8_1[] = {
  146989. 3, 5, 5, 6, 6, 7, 7, 7, 7, 7, 7, 5, 6, 5, 7, 7,
  146990. 7, 7, 8, 7, 8, 8, 5, 5, 6, 6, 7, 7, 7, 7, 7, 8,
  146991. 8, 6, 7, 7, 7, 7, 8, 7, 8, 8, 8, 8, 6, 6, 7, 7,
  146992. 7, 7, 8, 8, 8, 8, 8, 7, 7, 7, 8, 8, 8, 8, 8, 8,
  146993. 8, 8, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 7, 7, 7,
  146994. 8, 8, 8, 8, 8, 8, 8, 8, 7, 8, 8, 8, 8, 8, 8, 8,
  146995. 8, 8, 8, 7, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 7, 8,
  146996. 8, 8, 8, 8, 8, 8, 8, 8, 8,
  146997. };
  146998. static float _vq_quantthresh__44u6__p8_1[] = {
  146999. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  147000. 3.5, 4.5,
  147001. };
  147002. static long _vq_quantmap__44u6__p8_1[] = {
  147003. 9, 7, 5, 3, 1, 0, 2, 4,
  147004. 6, 8, 10,
  147005. };
  147006. static encode_aux_threshmatch _vq_auxt__44u6__p8_1 = {
  147007. _vq_quantthresh__44u6__p8_1,
  147008. _vq_quantmap__44u6__p8_1,
  147009. 11,
  147010. 11
  147011. };
  147012. static static_codebook _44u6__p8_1 = {
  147013. 2, 121,
  147014. _vq_lengthlist__44u6__p8_1,
  147015. 1, -531365888, 1611661312, 4, 0,
  147016. _vq_quantlist__44u6__p8_1,
  147017. NULL,
  147018. &_vq_auxt__44u6__p8_1,
  147019. NULL,
  147020. 0
  147021. };
  147022. static long _vq_quantlist__44u6__p9_0[] = {
  147023. 7,
  147024. 6,
  147025. 8,
  147026. 5,
  147027. 9,
  147028. 4,
  147029. 10,
  147030. 3,
  147031. 11,
  147032. 2,
  147033. 12,
  147034. 1,
  147035. 13,
  147036. 0,
  147037. 14,
  147038. };
  147039. static long _vq_lengthlist__44u6__p9_0[] = {
  147040. 1, 3, 2, 9, 8,15,15,15,15,15,15,15,15,15,15, 4,
  147041. 8, 9,13,14,14,14,14,14,14,14,14,14,14,14, 5, 8,
  147042. 9,14,14,14,14,14,14,14,14,14,14,14,14,11,14,14,
  147043. 14,14,14,14,14,14,14,14,14,14,14,14,11,14,14,14,
  147044. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  147045. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  147046. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  147047. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  147048. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  147049. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  147050. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  147051. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  147052. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  147053. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  147054. 14,
  147055. };
  147056. static float _vq_quantthresh__44u6__p9_0[] = {
  147057. -1657.5, -1402.5, -1147.5, -892.5, -637.5, -382.5, -127.5, 127.5,
  147058. 382.5, 637.5, 892.5, 1147.5, 1402.5, 1657.5,
  147059. };
  147060. static long _vq_quantmap__44u6__p9_0[] = {
  147061. 13, 11, 9, 7, 5, 3, 1, 0,
  147062. 2, 4, 6, 8, 10, 12, 14,
  147063. };
  147064. static encode_aux_threshmatch _vq_auxt__44u6__p9_0 = {
  147065. _vq_quantthresh__44u6__p9_0,
  147066. _vq_quantmap__44u6__p9_0,
  147067. 15,
  147068. 15
  147069. };
  147070. static static_codebook _44u6__p9_0 = {
  147071. 2, 225,
  147072. _vq_lengthlist__44u6__p9_0,
  147073. 1, -514071552, 1627381760, 4, 0,
  147074. _vq_quantlist__44u6__p9_0,
  147075. NULL,
  147076. &_vq_auxt__44u6__p9_0,
  147077. NULL,
  147078. 0
  147079. };
  147080. static long _vq_quantlist__44u6__p9_1[] = {
  147081. 7,
  147082. 6,
  147083. 8,
  147084. 5,
  147085. 9,
  147086. 4,
  147087. 10,
  147088. 3,
  147089. 11,
  147090. 2,
  147091. 12,
  147092. 1,
  147093. 13,
  147094. 0,
  147095. 14,
  147096. };
  147097. static long _vq_lengthlist__44u6__p9_1[] = {
  147098. 1, 4, 4, 7, 7, 8, 9, 8, 8, 9, 8, 9, 8, 9, 9, 4,
  147099. 7, 6, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 4, 7,
  147100. 6, 9, 9,10,10, 9, 9,10,10,10,10,11,11, 7, 9, 8,
  147101. 10,10,11,11,10,10,11,11,11,11,11,11, 7, 8, 9,10,
  147102. 10,11,11,10,10,11,11,11,11,11,12, 8,10,10,11,11,
  147103. 12,12,11,11,12,12,12,12,13,12, 8,10,10,11,11,12,
  147104. 11,11,11,11,12,12,12,12,13, 8, 9, 9,11,10,11,11,
  147105. 12,12,12,12,13,12,13,12, 8, 9, 9,11,11,11,11,12,
  147106. 12,12,12,12,13,13,13, 9,10,10,11,12,12,12,12,12,
  147107. 13,13,13,13,13,13, 9,10,10,11,11,12,12,12,12,13,
  147108. 13,13,13,14,13,10,10,10,12,11,12,12,13,13,13,13,
  147109. 13,13,13,13,10,10,11,11,11,12,12,13,13,13,13,13,
  147110. 13,13,13,10,11,11,12,12,13,12,12,13,13,13,13,13,
  147111. 13,14,10,11,11,12,12,13,12,13,13,13,14,13,13,14,
  147112. 13,
  147113. };
  147114. static float _vq_quantthresh__44u6__p9_1[] = {
  147115. -110.5, -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5,
  147116. 25.5, 42.5, 59.5, 76.5, 93.5, 110.5,
  147117. };
  147118. static long _vq_quantmap__44u6__p9_1[] = {
  147119. 13, 11, 9, 7, 5, 3, 1, 0,
  147120. 2, 4, 6, 8, 10, 12, 14,
  147121. };
  147122. static encode_aux_threshmatch _vq_auxt__44u6__p9_1 = {
  147123. _vq_quantthresh__44u6__p9_1,
  147124. _vq_quantmap__44u6__p9_1,
  147125. 15,
  147126. 15
  147127. };
  147128. static static_codebook _44u6__p9_1 = {
  147129. 2, 225,
  147130. _vq_lengthlist__44u6__p9_1,
  147131. 1, -522338304, 1620115456, 4, 0,
  147132. _vq_quantlist__44u6__p9_1,
  147133. NULL,
  147134. &_vq_auxt__44u6__p9_1,
  147135. NULL,
  147136. 0
  147137. };
  147138. static long _vq_quantlist__44u6__p9_2[] = {
  147139. 8,
  147140. 7,
  147141. 9,
  147142. 6,
  147143. 10,
  147144. 5,
  147145. 11,
  147146. 4,
  147147. 12,
  147148. 3,
  147149. 13,
  147150. 2,
  147151. 14,
  147152. 1,
  147153. 15,
  147154. 0,
  147155. 16,
  147156. };
  147157. static long _vq_lengthlist__44u6__p9_2[] = {
  147158. 3, 5, 5, 7, 7, 8, 8, 8, 8, 8, 8, 9, 8, 8, 9, 9,
  147159. 9, 5, 6, 6, 7, 7, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9,
  147160. 9, 9, 5, 6, 6, 7, 7, 8, 8, 8, 8, 8, 8, 9, 9, 9,
  147161. 9, 9, 9, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  147162. 9, 9, 9, 9, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  147163. 9, 9, 9, 9, 9, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  147164. 9, 9, 9, 9, 9, 9, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  147165. 9, 9, 9, 9, 9, 9, 9, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  147166. 9, 9, 9, 9, 9, 9, 9, 9, 8, 8, 8, 9, 9, 9, 9, 9,
  147167. 9, 9, 9, 9, 9, 9, 9, 9, 9, 8, 9, 9, 9, 9, 9, 9,
  147168. 9, 9, 9, 9, 9, 9, 9, 9,10, 9, 8, 9, 9, 9, 9, 9,
  147169. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  147170. 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10, 9, 9, 9, 9, 9,
  147171. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 9, 9, 9,
  147172. 9, 9, 9, 9, 9, 9, 9, 9,10, 9, 9, 9,10, 9, 9, 9,
  147173. 9, 9, 9, 9, 9, 9, 9,10, 9, 9, 9,10, 9, 9,10, 9,
  147174. 9, 9, 9, 9, 9, 9, 9, 9,10,10,10, 9,10, 9,10,10,
  147175. 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10, 9,10,10, 9, 9,
  147176. 10,
  147177. };
  147178. static float _vq_quantthresh__44u6__p9_2[] = {
  147179. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  147180. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  147181. };
  147182. static long _vq_quantmap__44u6__p9_2[] = {
  147183. 15, 13, 11, 9, 7, 5, 3, 1,
  147184. 0, 2, 4, 6, 8, 10, 12, 14,
  147185. 16,
  147186. };
  147187. static encode_aux_threshmatch _vq_auxt__44u6__p9_2 = {
  147188. _vq_quantthresh__44u6__p9_2,
  147189. _vq_quantmap__44u6__p9_2,
  147190. 17,
  147191. 17
  147192. };
  147193. static static_codebook _44u6__p9_2 = {
  147194. 2, 289,
  147195. _vq_lengthlist__44u6__p9_2,
  147196. 1, -529530880, 1611661312, 5, 0,
  147197. _vq_quantlist__44u6__p9_2,
  147198. NULL,
  147199. &_vq_auxt__44u6__p9_2,
  147200. NULL,
  147201. 0
  147202. };
  147203. static long _huff_lengthlist__44u6__short[] = {
  147204. 4,11,16,13,17,13,17,16,17,17, 4, 7, 9, 9,13,10,
  147205. 16,12,16,17, 7, 6, 5, 7, 8, 9,12,12,16,17, 6, 9,
  147206. 7, 9,10,10,15,15,17,17, 6, 7, 5, 7, 5, 7, 7,10,
  147207. 16,17, 7, 9, 8, 9, 8,10,11,11,15,17, 7, 7, 7, 8,
  147208. 5, 8, 8, 9,15,17, 8, 7, 9, 9, 7, 8, 7, 2, 7,15,
  147209. 14,13,13,15, 5,10, 4, 3, 6,17,17,15,13,17, 7,11,
  147210. 7, 6, 9,16,
  147211. };
  147212. static static_codebook _huff_book__44u6__short = {
  147213. 2, 100,
  147214. _huff_lengthlist__44u6__short,
  147215. 0, 0, 0, 0, 0,
  147216. NULL,
  147217. NULL,
  147218. NULL,
  147219. NULL,
  147220. 0
  147221. };
  147222. static long _huff_lengthlist__44u7__long[] = {
  147223. 3, 9,14,13,15,14,16,13,13,14, 5, 5, 7, 7, 8, 9,
  147224. 11,10,12,15,10, 6, 5, 6, 6, 9,10,10,13,16,10, 6,
  147225. 6, 6, 6, 8, 9, 9,12,15,14, 7, 6, 6, 5, 6, 6, 8,
  147226. 12,15,10, 8, 7, 7, 6, 7, 7, 7,11,13,14,10, 9, 8,
  147227. 5, 6, 4, 5, 9,12,10, 9, 9, 8, 6, 6, 5, 3, 6,11,
  147228. 12,11,12,12,10, 9, 8, 5, 5, 8,10,11,15,13,13,13,
  147229. 12, 8, 6, 7,
  147230. };
  147231. static static_codebook _huff_book__44u7__long = {
  147232. 2, 100,
  147233. _huff_lengthlist__44u7__long,
  147234. 0, 0, 0, 0, 0,
  147235. NULL,
  147236. NULL,
  147237. NULL,
  147238. NULL,
  147239. 0
  147240. };
  147241. static long _vq_quantlist__44u7__p1_0[] = {
  147242. 1,
  147243. 0,
  147244. 2,
  147245. };
  147246. static long _vq_lengthlist__44u7__p1_0[] = {
  147247. 1, 4, 4, 4, 7, 7, 5, 7, 7, 5, 8, 8, 8,10,10, 7,
  147248. 10,10, 5, 8, 8, 7,10,10, 8,10,10, 5, 8, 8, 8,11,
  147249. 10, 8,10,10, 8,10,10,10,12,13,10,13,13, 7,10,10,
  147250. 10,13,12,10,13,13, 5, 8, 8, 8,11,10, 8,10,11, 7,
  147251. 10,10,10,13,13,10,12,13, 8,11,11,10,13,13,10,13,
  147252. 12,
  147253. };
  147254. static float _vq_quantthresh__44u7__p1_0[] = {
  147255. -0.5, 0.5,
  147256. };
  147257. static long _vq_quantmap__44u7__p1_0[] = {
  147258. 1, 0, 2,
  147259. };
  147260. static encode_aux_threshmatch _vq_auxt__44u7__p1_0 = {
  147261. _vq_quantthresh__44u7__p1_0,
  147262. _vq_quantmap__44u7__p1_0,
  147263. 3,
  147264. 3
  147265. };
  147266. static static_codebook _44u7__p1_0 = {
  147267. 4, 81,
  147268. _vq_lengthlist__44u7__p1_0,
  147269. 1, -535822336, 1611661312, 2, 0,
  147270. _vq_quantlist__44u7__p1_0,
  147271. NULL,
  147272. &_vq_auxt__44u7__p1_0,
  147273. NULL,
  147274. 0
  147275. };
  147276. static long _vq_quantlist__44u7__p2_0[] = {
  147277. 1,
  147278. 0,
  147279. 2,
  147280. };
  147281. static long _vq_lengthlist__44u7__p2_0[] = {
  147282. 3, 4, 4, 5, 6, 6, 5, 6, 6, 5, 6, 6, 6, 8, 8, 6,
  147283. 7, 8, 5, 6, 6, 6, 8, 7, 6, 8, 8, 5, 6, 6, 6, 8,
  147284. 7, 6, 8, 8, 6, 8, 8, 8, 9, 9, 8, 9, 9, 6, 8, 7,
  147285. 7, 9, 8, 8, 9, 9, 5, 6, 6, 6, 8, 7, 6, 8, 8, 6,
  147286. 8, 8, 8, 9, 9, 7, 8, 9, 6, 8, 8, 8, 9, 9, 8, 9,
  147287. 9,
  147288. };
  147289. static float _vq_quantthresh__44u7__p2_0[] = {
  147290. -0.5, 0.5,
  147291. };
  147292. static long _vq_quantmap__44u7__p2_0[] = {
  147293. 1, 0, 2,
  147294. };
  147295. static encode_aux_threshmatch _vq_auxt__44u7__p2_0 = {
  147296. _vq_quantthresh__44u7__p2_0,
  147297. _vq_quantmap__44u7__p2_0,
  147298. 3,
  147299. 3
  147300. };
  147301. static static_codebook _44u7__p2_0 = {
  147302. 4, 81,
  147303. _vq_lengthlist__44u7__p2_0,
  147304. 1, -535822336, 1611661312, 2, 0,
  147305. _vq_quantlist__44u7__p2_0,
  147306. NULL,
  147307. &_vq_auxt__44u7__p2_0,
  147308. NULL,
  147309. 0
  147310. };
  147311. static long _vq_quantlist__44u7__p3_0[] = {
  147312. 2,
  147313. 1,
  147314. 3,
  147315. 0,
  147316. 4,
  147317. };
  147318. static long _vq_lengthlist__44u7__p3_0[] = {
  147319. 2, 5, 4, 8, 8, 5, 7, 6, 9, 9, 5, 6, 7, 9, 9, 8,
  147320. 9, 9,13,12, 8, 9,10,12,13, 5, 7, 7,10, 9, 7, 9,
  147321. 9,11,11, 6, 8, 9,11,11,10,11,11,14,14, 9,10,11,
  147322. 13,14, 5, 7, 7, 9, 9, 7, 9, 8,11,11, 7, 9, 9,11,
  147323. 11, 9,11,10,14,13,10,11,11,14,14, 8,10,10,14,13,
  147324. 10,11,12,15,14, 9,11,11,15,14,13,14,14,16,16,12,
  147325. 13,14,17,16, 8,10,10,13,13, 9,11,11,14,15,10,11,
  147326. 12,14,15,12,14,13,16,16,13,14,15,15,17, 5, 7, 7,
  147327. 10,10, 7, 9, 9,11,11, 7, 9, 9,11,11,10,12,11,15,
  147328. 14,10,11,12,14,14, 7, 9, 9,12,12, 9,11,11,13,13,
  147329. 9,11,11,13,13,11,13,13,14,17,11,13,13,15,16, 6,
  147330. 9, 9,11,11, 8,11,10,13,12, 9,11,11,13,13,11,13,
  147331. 12,16,14,11,13,13,16,16,10,12,12,15,15,11,13,13,
  147332. 16,16,11,13,13,16,15,14,16,17,17,19,14,16,16,18,
  147333. 0, 9,11,11,14,15,10,13,12,16,15,11,13,13,16,16,
  147334. 14,15,14, 0,16,14,16,16,18, 0, 5, 7, 7,10,10, 7,
  147335. 9, 9,12,11, 7, 9, 9,11,12,10,11,11,15,14,10,11,
  147336. 12,14,14, 6, 9, 9,11,11, 9,11,11,13,13, 8,10,11,
  147337. 12,13,11,13,13,17,15,11,12,13,14,15, 7, 9, 9,11,
  147338. 12, 9,11,11,13,13, 9,11,11,13,13,11,13,12,16,16,
  147339. 11,13,13,15,14, 9,11,11,14,15,11,13,13,16,15,10,
  147340. 12,13,16,16,15,16,16, 0, 0,14,13,15,16,18,10,11,
  147341. 11,15,15,11,13,14,16,18,11,13,13,16,15,15,16,16,
  147342. 19, 0,14,15,15,16,16, 8,10,10,13,13,10,12,11,16,
  147343. 15,10,11,11,16,15,13,15,16,18, 0,13,14,15,17,17,
  147344. 9,11,11,15,15,11,13,13,16,18,11,13,13,16,17,15,
  147345. 16,16, 0, 0,15,18,16, 0,17, 9,11,11,15,15,11,13,
  147346. 12,17,15,11,13,14,16,17,15,18,15, 0,17,15,16,16,
  147347. 18,19,13,15,14, 0,18,14,16,16,19,18,14,16,15,19,
  147348. 19,16,18,19, 0, 0,16,17, 0, 0, 0,12,14,14,17,17,
  147349. 13,16,14, 0,18,14,16,15,18, 0,16,18,16,19,17,18,
  147350. 19,17, 0, 0, 8,10,10,14,14, 9,12,11,15,15,10,11,
  147351. 12,15,17,13,15,15,18,16,14,16,15,18,17, 9,11,11,
  147352. 16,15,11,13,13, 0,16,11,12,13,16,15,15,16,16, 0,
  147353. 17,15,15,16,18,17, 9,12,11,15,17,11,13,13,16,16,
  147354. 11,14,13,16,16,15,15,16,18,19,16,18,16, 0, 0,12,
  147355. 14,14, 0,16,14,16,16, 0,18,13,14,15,16, 0,17,16,
  147356. 18, 0, 0,16,16,17,19, 0,13,14,14,17, 0,14,17,16,
  147357. 0,19,14,15,15,18,19,17,16,18, 0, 0,15,19,16, 0,
  147358. 0,
  147359. };
  147360. static float _vq_quantthresh__44u7__p3_0[] = {
  147361. -1.5, -0.5, 0.5, 1.5,
  147362. };
  147363. static long _vq_quantmap__44u7__p3_0[] = {
  147364. 3, 1, 0, 2, 4,
  147365. };
  147366. static encode_aux_threshmatch _vq_auxt__44u7__p3_0 = {
  147367. _vq_quantthresh__44u7__p3_0,
  147368. _vq_quantmap__44u7__p3_0,
  147369. 5,
  147370. 5
  147371. };
  147372. static static_codebook _44u7__p3_0 = {
  147373. 4, 625,
  147374. _vq_lengthlist__44u7__p3_0,
  147375. 1, -533725184, 1611661312, 3, 0,
  147376. _vq_quantlist__44u7__p3_0,
  147377. NULL,
  147378. &_vq_auxt__44u7__p3_0,
  147379. NULL,
  147380. 0
  147381. };
  147382. static long _vq_quantlist__44u7__p4_0[] = {
  147383. 2,
  147384. 1,
  147385. 3,
  147386. 0,
  147387. 4,
  147388. };
  147389. static long _vq_lengthlist__44u7__p4_0[] = {
  147390. 4, 5, 5, 8, 8, 6, 7, 6, 9, 9, 6, 6, 7, 9, 9, 8,
  147391. 9, 9,11,11, 8, 9, 9,10,11, 6, 7, 7, 9, 9, 7, 8,
  147392. 8,10,10, 6, 7, 8, 9,10, 9,10,10,12,12, 9, 9,10,
  147393. 11,12, 6, 7, 7, 9, 9, 6, 8, 7,10, 9, 7, 8, 8,10,
  147394. 10, 9,10, 9,12,11, 9,10,10,12,11, 8, 9, 9,11,11,
  147395. 9,10,10,12,12, 9,10,10,12,12,11,12,12,13,14,11,
  147396. 11,12,13,13, 8, 9, 9,11,11, 9,10,10,12,11, 9,10,
  147397. 10,12,12,11,12,11,13,13,11,12,12,13,13, 6, 7, 7,
  147398. 9, 9, 7, 8, 7,10,10, 7, 7, 8,10,10, 9,10,10,12,
  147399. 11, 9,10,10,12,12, 7, 8, 8,10,10, 8, 8, 9,11,11,
  147400. 8, 9, 9,11,11,10,11,11,12,12,10,10,11,12,13, 6,
  147401. 7, 7,10,10, 7, 9, 8,11,10, 8, 8, 9,10,11,10,11,
  147402. 10,13,11,10,11,11,12,12, 9,10,10,12,12,10,10,11,
  147403. 13,13,10,11,11,13,12,12,12,13,13,14,12,12,13,14,
  147404. 14, 9,10,10,12,12, 9,10,10,12,12,10,11,11,13,13,
  147405. 11,12,11,14,12,12,13,13,14,14, 6, 7, 7, 9, 9, 7,
  147406. 8, 7,10,10, 7, 7, 8,10,10, 9,10,10,12,11, 9,10,
  147407. 10,11,12, 6, 7, 7,10,10, 8, 9, 8,11,10, 7, 8, 9,
  147408. 10,11,10,11,11,13,12,10,10,11,11,13, 7, 8, 8,10,
  147409. 10, 8, 9, 9,11,11, 8, 9, 9,11,11,10,11,10,13,12,
  147410. 10,11,11,12,12, 9,10,10,12,12,10,11,11,13,12, 9,
  147411. 10,10,12,13,12,13,12,14,14,11,11,12,12,14, 9,10,
  147412. 10,12,12,10,11,11,13,13,10,11,11,13,13,12,13,12,
  147413. 14,14,12,13,12,14,13, 8, 9, 9,11,11, 9,10,10,12,
  147414. 12, 9,10,10,12,12,11,12,12,14,13,11,12,12,13,13,
  147415. 9,10,10,12,12,10,11,11,13,13,10,11,11,13,12,12,
  147416. 13,13,14,14,12,12,13,14,14, 9,10,10,12,12, 9,11,
  147417. 10,13,12,10,10,11,12,13,11,13,12,14,13,12,12,13,
  147418. 14,14,11,12,12,13,13,11,12,13,14,14,12,13,13,14,
  147419. 14,13,13,14,14,16,13,14,14,16,16,11,11,11,13,13,
  147420. 11,12,11,14,13,12,12,13,14,15,13,14,12,16,13,14,
  147421. 14,14,15,16, 8, 9, 9,11,11, 9,10,10,12,12, 9,10,
  147422. 10,12,12,11,12,12,14,13,11,12,12,13,14, 9,10,10,
  147423. 12,12,10,11,10,13,12, 9,10,11,12,13,12,13,12,14,
  147424. 14,12,12,13,13,14, 9,10,10,12,12,10,11,11,12,13,
  147425. 10,11,11,13,13,12,13,12,14,14,12,13,13,14,14,11,
  147426. 12,12,13,13,12,13,12,14,14,11,11,12,13,14,13,15,
  147427. 14,16,15,13,12,14,13,16,11,12,12,13,13,12,13,13,
  147428. 14,14,12,12,12,14,14,13,14,14,15,15,13,14,13,16,
  147429. 14,
  147430. };
  147431. static float _vq_quantthresh__44u7__p4_0[] = {
  147432. -1.5, -0.5, 0.5, 1.5,
  147433. };
  147434. static long _vq_quantmap__44u7__p4_0[] = {
  147435. 3, 1, 0, 2, 4,
  147436. };
  147437. static encode_aux_threshmatch _vq_auxt__44u7__p4_0 = {
  147438. _vq_quantthresh__44u7__p4_0,
  147439. _vq_quantmap__44u7__p4_0,
  147440. 5,
  147441. 5
  147442. };
  147443. static static_codebook _44u7__p4_0 = {
  147444. 4, 625,
  147445. _vq_lengthlist__44u7__p4_0,
  147446. 1, -533725184, 1611661312, 3, 0,
  147447. _vq_quantlist__44u7__p4_0,
  147448. NULL,
  147449. &_vq_auxt__44u7__p4_0,
  147450. NULL,
  147451. 0
  147452. };
  147453. static long _vq_quantlist__44u7__p5_0[] = {
  147454. 4,
  147455. 3,
  147456. 5,
  147457. 2,
  147458. 6,
  147459. 1,
  147460. 7,
  147461. 0,
  147462. 8,
  147463. };
  147464. static long _vq_lengthlist__44u7__p5_0[] = {
  147465. 2, 3, 3, 6, 6, 7, 8,10,10, 4, 5, 5, 8, 7, 8, 8,
  147466. 11,11, 3, 5, 5, 7, 7, 8, 9,11,11, 6, 8, 7, 9, 9,
  147467. 10,10,12,12, 6, 7, 8, 9,10,10,10,12,12, 8, 8, 8,
  147468. 10,10,12,11,13,13, 8, 8, 9,10,10,11,11,13,13,10,
  147469. 11,11,12,12,13,13,14,14,10,11,11,12,12,13,13,14,
  147470. 14,
  147471. };
  147472. static float _vq_quantthresh__44u7__p5_0[] = {
  147473. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  147474. };
  147475. static long _vq_quantmap__44u7__p5_0[] = {
  147476. 7, 5, 3, 1, 0, 2, 4, 6,
  147477. 8,
  147478. };
  147479. static encode_aux_threshmatch _vq_auxt__44u7__p5_0 = {
  147480. _vq_quantthresh__44u7__p5_0,
  147481. _vq_quantmap__44u7__p5_0,
  147482. 9,
  147483. 9
  147484. };
  147485. static static_codebook _44u7__p5_0 = {
  147486. 2, 81,
  147487. _vq_lengthlist__44u7__p5_0,
  147488. 1, -531628032, 1611661312, 4, 0,
  147489. _vq_quantlist__44u7__p5_0,
  147490. NULL,
  147491. &_vq_auxt__44u7__p5_0,
  147492. NULL,
  147493. 0
  147494. };
  147495. static long _vq_quantlist__44u7__p6_0[] = {
  147496. 4,
  147497. 3,
  147498. 5,
  147499. 2,
  147500. 6,
  147501. 1,
  147502. 7,
  147503. 0,
  147504. 8,
  147505. };
  147506. static long _vq_lengthlist__44u7__p6_0[] = {
  147507. 3, 4, 4, 5, 5, 7, 7, 9, 9, 4, 5, 4, 6, 6, 8, 7,
  147508. 9, 9, 4, 4, 5, 6, 6, 7, 7, 9, 9, 5, 6, 6, 7, 7,
  147509. 8, 8,10,10, 5, 6, 6, 7, 7, 8, 8,10,10, 7, 8, 7,
  147510. 8, 8,10, 9,11,11, 7, 7, 8, 8, 8, 9,10,11,11, 9,
  147511. 9, 9,10,10,11,10,12,11, 9, 9, 9,10,10,11,11,11,
  147512. 12,
  147513. };
  147514. static float _vq_quantthresh__44u7__p6_0[] = {
  147515. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  147516. };
  147517. static long _vq_quantmap__44u7__p6_0[] = {
  147518. 7, 5, 3, 1, 0, 2, 4, 6,
  147519. 8,
  147520. };
  147521. static encode_aux_threshmatch _vq_auxt__44u7__p6_0 = {
  147522. _vq_quantthresh__44u7__p6_0,
  147523. _vq_quantmap__44u7__p6_0,
  147524. 9,
  147525. 9
  147526. };
  147527. static static_codebook _44u7__p6_0 = {
  147528. 2, 81,
  147529. _vq_lengthlist__44u7__p6_0,
  147530. 1, -531628032, 1611661312, 4, 0,
  147531. _vq_quantlist__44u7__p6_0,
  147532. NULL,
  147533. &_vq_auxt__44u7__p6_0,
  147534. NULL,
  147535. 0
  147536. };
  147537. static long _vq_quantlist__44u7__p7_0[] = {
  147538. 1,
  147539. 0,
  147540. 2,
  147541. };
  147542. static long _vq_lengthlist__44u7__p7_0[] = {
  147543. 1, 4, 4, 5, 7, 7, 5, 7, 7, 5, 9, 8, 8, 9, 9, 7,
  147544. 10,10, 5, 8, 9, 7, 9,10, 8, 9, 9, 4, 9, 9, 9,11,
  147545. 10, 8,10,10, 7,11,10,10,10,12,10,12,12, 7,10,10,
  147546. 10,12,11,10,12,12, 5, 9, 9, 8,10,10, 9,11,11, 7,
  147547. 11,10,10,12,12,10,11,12, 7,10,11,10,12,12,10,12,
  147548. 10,
  147549. };
  147550. static float _vq_quantthresh__44u7__p7_0[] = {
  147551. -5.5, 5.5,
  147552. };
  147553. static long _vq_quantmap__44u7__p7_0[] = {
  147554. 1, 0, 2,
  147555. };
  147556. static encode_aux_threshmatch _vq_auxt__44u7__p7_0 = {
  147557. _vq_quantthresh__44u7__p7_0,
  147558. _vq_quantmap__44u7__p7_0,
  147559. 3,
  147560. 3
  147561. };
  147562. static static_codebook _44u7__p7_0 = {
  147563. 4, 81,
  147564. _vq_lengthlist__44u7__p7_0,
  147565. 1, -529137664, 1618345984, 2, 0,
  147566. _vq_quantlist__44u7__p7_0,
  147567. NULL,
  147568. &_vq_auxt__44u7__p7_0,
  147569. NULL,
  147570. 0
  147571. };
  147572. static long _vq_quantlist__44u7__p7_1[] = {
  147573. 5,
  147574. 4,
  147575. 6,
  147576. 3,
  147577. 7,
  147578. 2,
  147579. 8,
  147580. 1,
  147581. 9,
  147582. 0,
  147583. 10,
  147584. };
  147585. static long _vq_lengthlist__44u7__p7_1[] = {
  147586. 3, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8, 4, 5, 5, 6, 6,
  147587. 8, 7, 8, 8, 8, 8, 4, 5, 5, 6, 6, 7, 8, 8, 8, 8,
  147588. 8, 6, 7, 6, 7, 7, 8, 8, 9, 9, 9, 9, 6, 6, 7, 7,
  147589. 7, 8, 8, 9, 9, 9, 9, 7, 8, 7, 8, 8, 9, 9, 9, 9,
  147590. 9, 9, 7, 7, 8, 8, 8, 9, 9, 9, 9, 9, 9, 8, 8, 8,
  147591. 9, 9, 9, 9,10, 9, 9, 9, 8, 8, 8, 9, 9, 9, 9, 9,
  147592. 9, 9,10, 8, 8, 8, 9, 9, 9, 9,10, 9,10,10, 8, 8,
  147593. 8, 9, 9, 9, 9, 9,10,10,10,
  147594. };
  147595. static float _vq_quantthresh__44u7__p7_1[] = {
  147596. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  147597. 3.5, 4.5,
  147598. };
  147599. static long _vq_quantmap__44u7__p7_1[] = {
  147600. 9, 7, 5, 3, 1, 0, 2, 4,
  147601. 6, 8, 10,
  147602. };
  147603. static encode_aux_threshmatch _vq_auxt__44u7__p7_1 = {
  147604. _vq_quantthresh__44u7__p7_1,
  147605. _vq_quantmap__44u7__p7_1,
  147606. 11,
  147607. 11
  147608. };
  147609. static static_codebook _44u7__p7_1 = {
  147610. 2, 121,
  147611. _vq_lengthlist__44u7__p7_1,
  147612. 1, -531365888, 1611661312, 4, 0,
  147613. _vq_quantlist__44u7__p7_1,
  147614. NULL,
  147615. &_vq_auxt__44u7__p7_1,
  147616. NULL,
  147617. 0
  147618. };
  147619. static long _vq_quantlist__44u7__p8_0[] = {
  147620. 5,
  147621. 4,
  147622. 6,
  147623. 3,
  147624. 7,
  147625. 2,
  147626. 8,
  147627. 1,
  147628. 9,
  147629. 0,
  147630. 10,
  147631. };
  147632. static long _vq_lengthlist__44u7__p8_0[] = {
  147633. 1, 4, 4, 6, 6, 8, 8,10,10,11,11, 4, 6, 6, 7, 7,
  147634. 9, 9,11,10,12,12, 5, 6, 5, 7, 7, 9, 9,10,11,12,
  147635. 12, 6, 7, 7, 8, 8,10,10,11,11,13,13, 6, 7, 7, 8,
  147636. 8,10,10,11,12,13,13, 8, 9, 9,10,10,11,11,12,12,
  147637. 14,14, 8, 9, 9,10,10,11,11,12,12,14,14,10,10,10,
  147638. 11,11,13,12,14,14,15,15,10,10,10,12,12,13,13,14,
  147639. 14,15,15,11,12,12,13,13,14,14,15,14,16,15,11,12,
  147640. 12,13,13,14,14,15,15,15,16,
  147641. };
  147642. static float _vq_quantthresh__44u7__p8_0[] = {
  147643. -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5, 27.5,
  147644. 38.5, 49.5,
  147645. };
  147646. static long _vq_quantmap__44u7__p8_0[] = {
  147647. 9, 7, 5, 3, 1, 0, 2, 4,
  147648. 6, 8, 10,
  147649. };
  147650. static encode_aux_threshmatch _vq_auxt__44u7__p8_0 = {
  147651. _vq_quantthresh__44u7__p8_0,
  147652. _vq_quantmap__44u7__p8_0,
  147653. 11,
  147654. 11
  147655. };
  147656. static static_codebook _44u7__p8_0 = {
  147657. 2, 121,
  147658. _vq_lengthlist__44u7__p8_0,
  147659. 1, -524582912, 1618345984, 4, 0,
  147660. _vq_quantlist__44u7__p8_0,
  147661. NULL,
  147662. &_vq_auxt__44u7__p8_0,
  147663. NULL,
  147664. 0
  147665. };
  147666. static long _vq_quantlist__44u7__p8_1[] = {
  147667. 5,
  147668. 4,
  147669. 6,
  147670. 3,
  147671. 7,
  147672. 2,
  147673. 8,
  147674. 1,
  147675. 9,
  147676. 0,
  147677. 10,
  147678. };
  147679. static long _vq_lengthlist__44u7__p8_1[] = {
  147680. 4, 5, 5, 6, 6, 7, 7, 7, 7, 7, 7, 5, 6, 6, 7, 7,
  147681. 7, 7, 7, 7, 7, 7, 5, 6, 6, 6, 7, 7, 7, 7, 7, 7,
  147682. 7, 6, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 6, 7, 7, 7,
  147683. 7, 7, 7, 7, 7, 8, 8, 7, 7, 7, 7, 7, 8, 7, 8, 8,
  147684. 8, 8, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8, 7, 7, 7,
  147685. 7, 7, 8, 8, 8, 8, 8, 8, 7, 7, 7, 7, 7, 8, 8, 8,
  147686. 8, 8, 8, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 7, 7,
  147687. 7, 8, 8, 8, 8, 8, 8, 8, 8,
  147688. };
  147689. static float _vq_quantthresh__44u7__p8_1[] = {
  147690. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  147691. 3.5, 4.5,
  147692. };
  147693. static long _vq_quantmap__44u7__p8_1[] = {
  147694. 9, 7, 5, 3, 1, 0, 2, 4,
  147695. 6, 8, 10,
  147696. };
  147697. static encode_aux_threshmatch _vq_auxt__44u7__p8_1 = {
  147698. _vq_quantthresh__44u7__p8_1,
  147699. _vq_quantmap__44u7__p8_1,
  147700. 11,
  147701. 11
  147702. };
  147703. static static_codebook _44u7__p8_1 = {
  147704. 2, 121,
  147705. _vq_lengthlist__44u7__p8_1,
  147706. 1, -531365888, 1611661312, 4, 0,
  147707. _vq_quantlist__44u7__p8_1,
  147708. NULL,
  147709. &_vq_auxt__44u7__p8_1,
  147710. NULL,
  147711. 0
  147712. };
  147713. static long _vq_quantlist__44u7__p9_0[] = {
  147714. 5,
  147715. 4,
  147716. 6,
  147717. 3,
  147718. 7,
  147719. 2,
  147720. 8,
  147721. 1,
  147722. 9,
  147723. 0,
  147724. 10,
  147725. };
  147726. static long _vq_lengthlist__44u7__p9_0[] = {
  147727. 1, 3, 3,10,10,10,10,10,10,10,10, 4,10,10,10,10,
  147728. 10,10,10,10,10,10, 4,10,10,10,10,10,10,10,10,10,
  147729. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  147730. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  147731. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  147732. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  147733. 10,10,10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9,
  147734. 9, 9, 9, 9, 9, 9, 9, 9, 9,
  147735. };
  147736. static float _vq_quantthresh__44u7__p9_0[] = {
  147737. -2866.5, -2229.5, -1592.5, -955.5, -318.5, 318.5, 955.5, 1592.5,
  147738. 2229.5, 2866.5,
  147739. };
  147740. static long _vq_quantmap__44u7__p9_0[] = {
  147741. 9, 7, 5, 3, 1, 0, 2, 4,
  147742. 6, 8, 10,
  147743. };
  147744. static encode_aux_threshmatch _vq_auxt__44u7__p9_0 = {
  147745. _vq_quantthresh__44u7__p9_0,
  147746. _vq_quantmap__44u7__p9_0,
  147747. 11,
  147748. 11
  147749. };
  147750. static static_codebook _44u7__p9_0 = {
  147751. 2, 121,
  147752. _vq_lengthlist__44u7__p9_0,
  147753. 1, -512171520, 1630791680, 4, 0,
  147754. _vq_quantlist__44u7__p9_0,
  147755. NULL,
  147756. &_vq_auxt__44u7__p9_0,
  147757. NULL,
  147758. 0
  147759. };
  147760. static long _vq_quantlist__44u7__p9_1[] = {
  147761. 6,
  147762. 5,
  147763. 7,
  147764. 4,
  147765. 8,
  147766. 3,
  147767. 9,
  147768. 2,
  147769. 10,
  147770. 1,
  147771. 11,
  147772. 0,
  147773. 12,
  147774. };
  147775. static long _vq_lengthlist__44u7__p9_1[] = {
  147776. 1, 4, 4, 6, 5, 8, 6, 9, 8,10, 9,11,10, 4, 6, 6,
  147777. 8, 8, 9, 9,11,10,11,11,11,11, 4, 6, 6, 8, 8,10,
  147778. 9,11,11,11,11,11,12, 6, 8, 8,10,10,11,11,12,12,
  147779. 13,12,13,13, 6, 8, 8,10,10,11,11,12,12,12,13,14,
  147780. 13, 8,10,10,11,11,12,13,14,14,14,14,15,15, 8,10,
  147781. 10,11,12,12,13,13,14,14,14,14,15, 9,11,11,13,13,
  147782. 14,14,15,14,16,15,17,15, 9,11,11,12,13,14,14,15,
  147783. 14,15,15,15,16,10,12,12,13,14,15,15,15,15,16,17,
  147784. 16,17,10,13,12,13,14,14,16,16,16,16,15,16,17,11,
  147785. 13,13,14,15,14,17,15,16,17,17,17,17,11,13,13,14,
  147786. 15,15,15,15,17,17,16,17,16,
  147787. };
  147788. static float _vq_quantthresh__44u7__p9_1[] = {
  147789. -269.5, -220.5, -171.5, -122.5, -73.5, -24.5, 24.5, 73.5,
  147790. 122.5, 171.5, 220.5, 269.5,
  147791. };
  147792. static long _vq_quantmap__44u7__p9_1[] = {
  147793. 11, 9, 7, 5, 3, 1, 0, 2,
  147794. 4, 6, 8, 10, 12,
  147795. };
  147796. static encode_aux_threshmatch _vq_auxt__44u7__p9_1 = {
  147797. _vq_quantthresh__44u7__p9_1,
  147798. _vq_quantmap__44u7__p9_1,
  147799. 13,
  147800. 13
  147801. };
  147802. static static_codebook _44u7__p9_1 = {
  147803. 2, 169,
  147804. _vq_lengthlist__44u7__p9_1,
  147805. 1, -518889472, 1622704128, 4, 0,
  147806. _vq_quantlist__44u7__p9_1,
  147807. NULL,
  147808. &_vq_auxt__44u7__p9_1,
  147809. NULL,
  147810. 0
  147811. };
  147812. static long _vq_quantlist__44u7__p9_2[] = {
  147813. 24,
  147814. 23,
  147815. 25,
  147816. 22,
  147817. 26,
  147818. 21,
  147819. 27,
  147820. 20,
  147821. 28,
  147822. 19,
  147823. 29,
  147824. 18,
  147825. 30,
  147826. 17,
  147827. 31,
  147828. 16,
  147829. 32,
  147830. 15,
  147831. 33,
  147832. 14,
  147833. 34,
  147834. 13,
  147835. 35,
  147836. 12,
  147837. 36,
  147838. 11,
  147839. 37,
  147840. 10,
  147841. 38,
  147842. 9,
  147843. 39,
  147844. 8,
  147845. 40,
  147846. 7,
  147847. 41,
  147848. 6,
  147849. 42,
  147850. 5,
  147851. 43,
  147852. 4,
  147853. 44,
  147854. 3,
  147855. 45,
  147856. 2,
  147857. 46,
  147858. 1,
  147859. 47,
  147860. 0,
  147861. 48,
  147862. };
  147863. static long _vq_lengthlist__44u7__p9_2[] = {
  147864. 2, 4, 4, 4, 4, 5, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6,
  147865. 6, 6, 6, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  147866. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8,
  147867. 8,
  147868. };
  147869. static float _vq_quantthresh__44u7__p9_2[] = {
  147870. -23.5, -22.5, -21.5, -20.5, -19.5, -18.5, -17.5, -16.5,
  147871. -15.5, -14.5, -13.5, -12.5, -11.5, -10.5, -9.5, -8.5,
  147872. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  147873. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  147874. 8.5, 9.5, 10.5, 11.5, 12.5, 13.5, 14.5, 15.5,
  147875. 16.5, 17.5, 18.5, 19.5, 20.5, 21.5, 22.5, 23.5,
  147876. };
  147877. static long _vq_quantmap__44u7__p9_2[] = {
  147878. 47, 45, 43, 41, 39, 37, 35, 33,
  147879. 31, 29, 27, 25, 23, 21, 19, 17,
  147880. 15, 13, 11, 9, 7, 5, 3, 1,
  147881. 0, 2, 4, 6, 8, 10, 12, 14,
  147882. 16, 18, 20, 22, 24, 26, 28, 30,
  147883. 32, 34, 36, 38, 40, 42, 44, 46,
  147884. 48,
  147885. };
  147886. static encode_aux_threshmatch _vq_auxt__44u7__p9_2 = {
  147887. _vq_quantthresh__44u7__p9_2,
  147888. _vq_quantmap__44u7__p9_2,
  147889. 49,
  147890. 49
  147891. };
  147892. static static_codebook _44u7__p9_2 = {
  147893. 1, 49,
  147894. _vq_lengthlist__44u7__p9_2,
  147895. 1, -526909440, 1611661312, 6, 0,
  147896. _vq_quantlist__44u7__p9_2,
  147897. NULL,
  147898. &_vq_auxt__44u7__p9_2,
  147899. NULL,
  147900. 0
  147901. };
  147902. static long _huff_lengthlist__44u7__short[] = {
  147903. 5,12,17,16,16,17,17,17,17,17, 4, 7,11,11,12, 9,
  147904. 17,10,17,17, 7, 7, 8, 9, 7, 9,11,10,15,17, 7, 9,
  147905. 10,11,10,12,14,12,16,17, 7, 8, 5, 7, 4, 7, 7, 8,
  147906. 16,16, 6,10, 9,10, 7,10,11,11,16,17, 6, 8, 8, 9,
  147907. 5, 7, 5, 8,16,17, 5, 5, 8, 7, 6, 7, 7, 6, 6,14,
  147908. 12,10,12,11, 7,11, 4, 4, 2, 7,17,15,15,15, 8,15,
  147909. 6, 8, 5, 9,
  147910. };
  147911. static static_codebook _huff_book__44u7__short = {
  147912. 2, 100,
  147913. _huff_lengthlist__44u7__short,
  147914. 0, 0, 0, 0, 0,
  147915. NULL,
  147916. NULL,
  147917. NULL,
  147918. NULL,
  147919. 0
  147920. };
  147921. static long _huff_lengthlist__44u8__long[] = {
  147922. 3, 9,13,14,14,15,14,14,15,15, 5, 4, 6, 8,10,12,
  147923. 12,14,15,15, 9, 5, 4, 5, 8,10,11,13,16,16,10, 7,
  147924. 4, 3, 5, 7, 9,11,13,13,10, 9, 7, 4, 4, 6, 8,10,
  147925. 12,14,13,11, 9, 6, 5, 5, 6, 8,12,14,13,11,10, 8,
  147926. 7, 6, 6, 7,10,14,13,11,12,10, 8, 7, 6, 6, 9,13,
  147927. 12,11,14,12,11, 9, 8, 7, 9,11,11,12,14,13,14,11,
  147928. 10, 8, 8, 9,
  147929. };
  147930. static static_codebook _huff_book__44u8__long = {
  147931. 2, 100,
  147932. _huff_lengthlist__44u8__long,
  147933. 0, 0, 0, 0, 0,
  147934. NULL,
  147935. NULL,
  147936. NULL,
  147937. NULL,
  147938. 0
  147939. };
  147940. static long _huff_lengthlist__44u8__short[] = {
  147941. 6,14,18,18,17,17,17,17,17,17, 4, 7, 9, 9,10,13,
  147942. 15,17,17,17, 6, 7, 5, 6, 8,11,16,17,16,17, 5, 7,
  147943. 5, 4, 6,10,14,17,17,17, 6, 6, 6, 5, 7,10,13,16,
  147944. 17,17, 7, 6, 7, 7, 7, 8, 7,10,15,16,12, 9, 9, 6,
  147945. 6, 5, 3, 5,11,15,14,14,13, 5, 5, 7, 3, 4, 8,15,
  147946. 17,17,13, 7, 7,10, 6, 6,10,15,17,17,16,10,11,14,
  147947. 10,10,15,17,
  147948. };
  147949. static static_codebook _huff_book__44u8__short = {
  147950. 2, 100,
  147951. _huff_lengthlist__44u8__short,
  147952. 0, 0, 0, 0, 0,
  147953. NULL,
  147954. NULL,
  147955. NULL,
  147956. NULL,
  147957. 0
  147958. };
  147959. static long _vq_quantlist__44u8_p1_0[] = {
  147960. 1,
  147961. 0,
  147962. 2,
  147963. };
  147964. static long _vq_lengthlist__44u8_p1_0[] = {
  147965. 1, 5, 5, 5, 7, 7, 5, 7, 7, 5, 7, 7, 8, 9, 9, 7,
  147966. 9, 9, 5, 7, 7, 7, 9, 9, 8, 9, 9, 5, 7, 7, 7, 9,
  147967. 9, 7, 9, 9, 7, 9, 9, 9,10,11, 9,11,10, 7, 9, 9,
  147968. 9,11,10, 9,10,11, 5, 7, 7, 7, 9, 9, 7, 9, 9, 7,
  147969. 9, 9, 9,11,10, 9,10,10, 8, 9, 9, 9,11,11, 9,11,
  147970. 10,
  147971. };
  147972. static float _vq_quantthresh__44u8_p1_0[] = {
  147973. -0.5, 0.5,
  147974. };
  147975. static long _vq_quantmap__44u8_p1_0[] = {
  147976. 1, 0, 2,
  147977. };
  147978. static encode_aux_threshmatch _vq_auxt__44u8_p1_0 = {
  147979. _vq_quantthresh__44u8_p1_0,
  147980. _vq_quantmap__44u8_p1_0,
  147981. 3,
  147982. 3
  147983. };
  147984. static static_codebook _44u8_p1_0 = {
  147985. 4, 81,
  147986. _vq_lengthlist__44u8_p1_0,
  147987. 1, -535822336, 1611661312, 2, 0,
  147988. _vq_quantlist__44u8_p1_0,
  147989. NULL,
  147990. &_vq_auxt__44u8_p1_0,
  147991. NULL,
  147992. 0
  147993. };
  147994. static long _vq_quantlist__44u8_p2_0[] = {
  147995. 2,
  147996. 1,
  147997. 3,
  147998. 0,
  147999. 4,
  148000. };
  148001. static long _vq_lengthlist__44u8_p2_0[] = {
  148002. 4, 5, 5, 8, 8, 5, 7, 6, 9, 9, 5, 6, 7, 9, 9, 8,
  148003. 9, 9,11,11, 8, 9, 9,11,11, 5, 7, 7, 9, 9, 7, 8,
  148004. 8,10,10, 7, 8, 8,10,10, 9,10,10,12,12, 9,10,10,
  148005. 11,12, 5, 7, 7, 9, 9, 7, 8, 7,10,10, 7, 8, 8,10,
  148006. 10, 9,10, 9,12,11, 9,10,10,12,12, 8, 9, 9,12,11,
  148007. 9,10,10,12,12, 9,10,10,12,12,11,12,12,14,14,11,
  148008. 11,12,13,14, 8, 9, 9,11,11, 9,10,10,12,12, 9,10,
  148009. 10,12,12,11,12,11,13,13,11,12,12,14,14, 5, 7, 7,
  148010. 9, 9, 7, 8, 8,10,10, 7, 8, 8,10,10, 9,10,10,12,
  148011. 12, 9,10,10,11,12, 7, 8, 8,10,10, 8, 9, 9,11,11,
  148012. 8, 9, 9,11,11,10,11,11,12,13,10,11,11,12,13, 6,
  148013. 8, 8,10,10, 8, 9, 8,11,10, 8, 9, 9,11,11,10,11,
  148014. 10,13,12,10,11,11,13,13, 9,10,10,12,12,10,11,11,
  148015. 13,13,10,11,11,13,13,12,12,13,13,14,12,13,13,14,
  148016. 14, 9,10,10,12,12,10,11,10,13,12,10,11,11,13,13,
  148017. 11,13,12,14,13,12,13,13,14,14, 5, 7, 7, 9, 9, 7,
  148018. 8, 8,10,10, 7, 8, 8,10,10, 9,10,10,12,12, 9,10,
  148019. 10,12,12, 7, 8, 8,10,10, 8, 9, 9,11,11, 8, 8, 9,
  148020. 10,11,10,11,11,13,13,10,10,11,12,13, 7, 8, 8,10,
  148021. 10, 8, 9, 9,11,11, 8, 9, 9,11,11,10,11,11,13,13,
  148022. 10,11,11,13,12, 9,10,10,12,12,10,11,11,13,13,10,
  148023. 10,11,12,13,12,13,13,14,14,12,12,13,13,14, 9,10,
  148024. 10,12,12,10,11,11,13,13,10,11,11,13,13,12,13,13,
  148025. 15,14,12,13,13,14,13, 8, 9, 9,11,11, 9,10,10,12,
  148026. 12, 9,10,10,12,12,12,12,12,14,13,11,12,12,14,14,
  148027. 9,10,10,12,12,10,11,11,13,13,10,11,11,13,13,12,
  148028. 13,13,14,15,12,13,13,14,15, 9,10,10,12,12,10,11,
  148029. 10,13,12,10,11,11,13,13,12,13,12,15,14,12,13,13,
  148030. 14,15,11,12,12,14,14,12,13,13,14,14,12,13,13,15,
  148031. 14,14,14,14,14,16,14,14,15,16,16,11,12,12,14,14,
  148032. 11,12,12,14,14,12,13,13,14,15,13,14,13,16,14,14,
  148033. 14,14,16,16, 8, 9, 9,11,11, 9,10,10,12,12, 9,10,
  148034. 10,12,12,11,12,12,14,13,11,12,12,14,14, 9,10,10,
  148035. 12,12,10,11,11,13,13,10,10,11,12,13,12,13,13,15,
  148036. 14,12,12,13,13,14, 9,10,10,12,12,10,11,11,13,13,
  148037. 10,11,11,13,13,12,13,13,14,14,12,13,13,15,14,11,
  148038. 12,12,14,13,12,13,13,15,14,11,12,12,13,14,14,15,
  148039. 14,16,15,13,13,14,13,16,11,12,12,14,14,12,13,13,
  148040. 14,15,12,13,12,15,14,14,14,14,16,15,14,15,13,16,
  148041. 14,
  148042. };
  148043. static float _vq_quantthresh__44u8_p2_0[] = {
  148044. -1.5, -0.5, 0.5, 1.5,
  148045. };
  148046. static long _vq_quantmap__44u8_p2_0[] = {
  148047. 3, 1, 0, 2, 4,
  148048. };
  148049. static encode_aux_threshmatch _vq_auxt__44u8_p2_0 = {
  148050. _vq_quantthresh__44u8_p2_0,
  148051. _vq_quantmap__44u8_p2_0,
  148052. 5,
  148053. 5
  148054. };
  148055. static static_codebook _44u8_p2_0 = {
  148056. 4, 625,
  148057. _vq_lengthlist__44u8_p2_0,
  148058. 1, -533725184, 1611661312, 3, 0,
  148059. _vq_quantlist__44u8_p2_0,
  148060. NULL,
  148061. &_vq_auxt__44u8_p2_0,
  148062. NULL,
  148063. 0
  148064. };
  148065. static long _vq_quantlist__44u8_p3_0[] = {
  148066. 4,
  148067. 3,
  148068. 5,
  148069. 2,
  148070. 6,
  148071. 1,
  148072. 7,
  148073. 0,
  148074. 8,
  148075. };
  148076. static long _vq_lengthlist__44u8_p3_0[] = {
  148077. 3, 4, 4, 5, 5, 7, 7, 9, 9, 4, 5, 4, 6, 6, 7, 7,
  148078. 9, 9, 4, 4, 5, 6, 6, 7, 7, 9, 9, 5, 6, 6, 7, 7,
  148079. 8, 8,10,10, 6, 6, 6, 7, 7, 8, 8,10,10, 7, 7, 7,
  148080. 8, 8, 9, 9,11,10, 7, 7, 7, 8, 8, 9, 9,10,11, 9,
  148081. 9, 9,10,10,11,10,12,11, 9, 9, 9, 9,10,11,11,11,
  148082. 12,
  148083. };
  148084. static float _vq_quantthresh__44u8_p3_0[] = {
  148085. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  148086. };
  148087. static long _vq_quantmap__44u8_p3_0[] = {
  148088. 7, 5, 3, 1, 0, 2, 4, 6,
  148089. 8,
  148090. };
  148091. static encode_aux_threshmatch _vq_auxt__44u8_p3_0 = {
  148092. _vq_quantthresh__44u8_p3_0,
  148093. _vq_quantmap__44u8_p3_0,
  148094. 9,
  148095. 9
  148096. };
  148097. static static_codebook _44u8_p3_0 = {
  148098. 2, 81,
  148099. _vq_lengthlist__44u8_p3_0,
  148100. 1, -531628032, 1611661312, 4, 0,
  148101. _vq_quantlist__44u8_p3_0,
  148102. NULL,
  148103. &_vq_auxt__44u8_p3_0,
  148104. NULL,
  148105. 0
  148106. };
  148107. static long _vq_quantlist__44u8_p4_0[] = {
  148108. 8,
  148109. 7,
  148110. 9,
  148111. 6,
  148112. 10,
  148113. 5,
  148114. 11,
  148115. 4,
  148116. 12,
  148117. 3,
  148118. 13,
  148119. 2,
  148120. 14,
  148121. 1,
  148122. 15,
  148123. 0,
  148124. 16,
  148125. };
  148126. static long _vq_lengthlist__44u8_p4_0[] = {
  148127. 4, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8,10,10,11,11,11,
  148128. 11, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9,10,10,11,11,
  148129. 12,12, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9,10,10,11,
  148130. 11,12,12, 6, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  148131. 11,11,12,12, 6, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9,10,
  148132. 10,11,11,12,12, 7, 7, 7, 8, 8, 9, 8,10, 9,10, 9,
  148133. 11,10,12,11,13,12, 7, 7, 7, 8, 8, 8, 9, 9,10, 9,
  148134. 10,10,11,11,12,12,13, 8, 8, 8, 9, 9, 9, 9,10,10,
  148135. 11,10,11,11,12,12,13,13, 8, 8, 8, 9, 9, 9,10,10,
  148136. 10,10,11,11,11,12,12,12,13, 8, 9, 9, 9, 9,10, 9,
  148137. 11,10,11,11,12,11,13,12,13,13, 8, 9, 9, 9, 9, 9,
  148138. 10,10,11,11,11,11,12,12,13,13,13,10,10,10,10,10,
  148139. 11,10,11,11,12,11,13,12,13,13,14,13,10,10,10,10,
  148140. 10,10,11,11,11,11,12,12,13,13,13,13,14,11,11,11,
  148141. 11,11,12,11,12,12,13,12,13,13,14,13,14,14,11,11,
  148142. 11,11,11,11,12,12,12,12,13,13,13,13,14,14,14,11,
  148143. 12,12,12,12,13,12,13,12,13,13,14,13,14,14,14,14,
  148144. 11,12,12,12,12,12,12,13,13,13,13,13,14,14,14,14,
  148145. 14,
  148146. };
  148147. static float _vq_quantthresh__44u8_p4_0[] = {
  148148. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  148149. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  148150. };
  148151. static long _vq_quantmap__44u8_p4_0[] = {
  148152. 15, 13, 11, 9, 7, 5, 3, 1,
  148153. 0, 2, 4, 6, 8, 10, 12, 14,
  148154. 16,
  148155. };
  148156. static encode_aux_threshmatch _vq_auxt__44u8_p4_0 = {
  148157. _vq_quantthresh__44u8_p4_0,
  148158. _vq_quantmap__44u8_p4_0,
  148159. 17,
  148160. 17
  148161. };
  148162. static static_codebook _44u8_p4_0 = {
  148163. 2, 289,
  148164. _vq_lengthlist__44u8_p4_0,
  148165. 1, -529530880, 1611661312, 5, 0,
  148166. _vq_quantlist__44u8_p4_0,
  148167. NULL,
  148168. &_vq_auxt__44u8_p4_0,
  148169. NULL,
  148170. 0
  148171. };
  148172. static long _vq_quantlist__44u8_p5_0[] = {
  148173. 1,
  148174. 0,
  148175. 2,
  148176. };
  148177. static long _vq_lengthlist__44u8_p5_0[] = {
  148178. 1, 4, 4, 5, 7, 7, 5, 7, 7, 5, 8, 8, 8, 9, 9, 7,
  148179. 9, 9, 5, 8, 8, 7, 9, 9, 8, 9, 9, 5, 8, 8, 8,10,
  148180. 10, 8,10,10, 7,10,10, 9,10,12, 9,12,11, 7,10,10,
  148181. 9,11,10, 9,11,12, 5, 8, 8, 8,10,10, 8,10,10, 7,
  148182. 10,10, 9,11,11, 9,10,11, 7,10,10, 9,11,11,10,12,
  148183. 10,
  148184. };
  148185. static float _vq_quantthresh__44u8_p5_0[] = {
  148186. -5.5, 5.5,
  148187. };
  148188. static long _vq_quantmap__44u8_p5_0[] = {
  148189. 1, 0, 2,
  148190. };
  148191. static encode_aux_threshmatch _vq_auxt__44u8_p5_0 = {
  148192. _vq_quantthresh__44u8_p5_0,
  148193. _vq_quantmap__44u8_p5_0,
  148194. 3,
  148195. 3
  148196. };
  148197. static static_codebook _44u8_p5_0 = {
  148198. 4, 81,
  148199. _vq_lengthlist__44u8_p5_0,
  148200. 1, -529137664, 1618345984, 2, 0,
  148201. _vq_quantlist__44u8_p5_0,
  148202. NULL,
  148203. &_vq_auxt__44u8_p5_0,
  148204. NULL,
  148205. 0
  148206. };
  148207. static long _vq_quantlist__44u8_p5_1[] = {
  148208. 5,
  148209. 4,
  148210. 6,
  148211. 3,
  148212. 7,
  148213. 2,
  148214. 8,
  148215. 1,
  148216. 9,
  148217. 0,
  148218. 10,
  148219. };
  148220. static long _vq_lengthlist__44u8_p5_1[] = {
  148221. 4, 5, 5, 6, 6, 7, 7, 7, 7, 8, 8, 5, 5, 5, 6, 6,
  148222. 7, 7, 8, 8, 8, 8, 5, 5, 5, 6, 6, 7, 7, 7, 8, 8,
  148223. 8, 6, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8, 6, 6, 6, 7,
  148224. 7, 7, 7, 8, 8, 8, 8, 7, 7, 7, 7, 7, 8, 8, 8, 8,
  148225. 8, 8, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 7, 8, 7,
  148226. 8, 8, 8, 8, 8, 8, 8, 8, 7, 8, 8, 8, 8, 8, 8, 8,
  148227. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 9, 9, 8, 8,
  148228. 8, 8, 8, 8, 8, 8, 8, 9, 9,
  148229. };
  148230. static float _vq_quantthresh__44u8_p5_1[] = {
  148231. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  148232. 3.5, 4.5,
  148233. };
  148234. static long _vq_quantmap__44u8_p5_1[] = {
  148235. 9, 7, 5, 3, 1, 0, 2, 4,
  148236. 6, 8, 10,
  148237. };
  148238. static encode_aux_threshmatch _vq_auxt__44u8_p5_1 = {
  148239. _vq_quantthresh__44u8_p5_1,
  148240. _vq_quantmap__44u8_p5_1,
  148241. 11,
  148242. 11
  148243. };
  148244. static static_codebook _44u8_p5_1 = {
  148245. 2, 121,
  148246. _vq_lengthlist__44u8_p5_1,
  148247. 1, -531365888, 1611661312, 4, 0,
  148248. _vq_quantlist__44u8_p5_1,
  148249. NULL,
  148250. &_vq_auxt__44u8_p5_1,
  148251. NULL,
  148252. 0
  148253. };
  148254. static long _vq_quantlist__44u8_p6_0[] = {
  148255. 6,
  148256. 5,
  148257. 7,
  148258. 4,
  148259. 8,
  148260. 3,
  148261. 9,
  148262. 2,
  148263. 10,
  148264. 1,
  148265. 11,
  148266. 0,
  148267. 12,
  148268. };
  148269. static long _vq_lengthlist__44u8_p6_0[] = {
  148270. 2, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10, 4, 6, 5,
  148271. 7, 7, 8, 8, 8, 8, 9, 9,10,10, 4, 6, 6, 7, 7, 8,
  148272. 8, 8, 8, 9, 9,10,10, 6, 7, 7, 7, 8, 8, 8, 8, 9,
  148273. 9,10,10,10, 6, 7, 7, 8, 8, 8, 8, 9, 8,10, 9,11,
  148274. 10, 7, 8, 8, 8, 8, 8, 9, 9, 9,10,10,11,11, 7, 8,
  148275. 8, 8, 8, 9, 8, 9, 9,10,10,11,11, 8, 8, 8, 9, 9,
  148276. 9, 9, 9,10,10,10,11,11, 8, 8, 8, 9, 9, 9, 9,10,
  148277. 9,10,10,11,11, 9, 9, 9, 9,10,10,10,10,10,10,11,
  148278. 11,12, 9, 9, 9,10, 9,10,10,10,10,11,10,12,11,10,
  148279. 10,10,10,10,11,11,11,11,11,12,12,12,10,10,10,10,
  148280. 11,11,11,11,11,12,11,12,12,
  148281. };
  148282. static float _vq_quantthresh__44u8_p6_0[] = {
  148283. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  148284. 12.5, 17.5, 22.5, 27.5,
  148285. };
  148286. static long _vq_quantmap__44u8_p6_0[] = {
  148287. 11, 9, 7, 5, 3, 1, 0, 2,
  148288. 4, 6, 8, 10, 12,
  148289. };
  148290. static encode_aux_threshmatch _vq_auxt__44u8_p6_0 = {
  148291. _vq_quantthresh__44u8_p6_0,
  148292. _vq_quantmap__44u8_p6_0,
  148293. 13,
  148294. 13
  148295. };
  148296. static static_codebook _44u8_p6_0 = {
  148297. 2, 169,
  148298. _vq_lengthlist__44u8_p6_0,
  148299. 1, -526516224, 1616117760, 4, 0,
  148300. _vq_quantlist__44u8_p6_0,
  148301. NULL,
  148302. &_vq_auxt__44u8_p6_0,
  148303. NULL,
  148304. 0
  148305. };
  148306. static long _vq_quantlist__44u8_p6_1[] = {
  148307. 2,
  148308. 1,
  148309. 3,
  148310. 0,
  148311. 4,
  148312. };
  148313. static long _vq_lengthlist__44u8_p6_1[] = {
  148314. 3, 4, 4, 5, 5, 4, 5, 5, 5, 5, 4, 5, 5, 5, 5, 5,
  148315. 5, 5, 5, 5, 5, 5, 5, 5, 5,
  148316. };
  148317. static float _vq_quantthresh__44u8_p6_1[] = {
  148318. -1.5, -0.5, 0.5, 1.5,
  148319. };
  148320. static long _vq_quantmap__44u8_p6_1[] = {
  148321. 3, 1, 0, 2, 4,
  148322. };
  148323. static encode_aux_threshmatch _vq_auxt__44u8_p6_1 = {
  148324. _vq_quantthresh__44u8_p6_1,
  148325. _vq_quantmap__44u8_p6_1,
  148326. 5,
  148327. 5
  148328. };
  148329. static static_codebook _44u8_p6_1 = {
  148330. 2, 25,
  148331. _vq_lengthlist__44u8_p6_1,
  148332. 1, -533725184, 1611661312, 3, 0,
  148333. _vq_quantlist__44u8_p6_1,
  148334. NULL,
  148335. &_vq_auxt__44u8_p6_1,
  148336. NULL,
  148337. 0
  148338. };
  148339. static long _vq_quantlist__44u8_p7_0[] = {
  148340. 6,
  148341. 5,
  148342. 7,
  148343. 4,
  148344. 8,
  148345. 3,
  148346. 9,
  148347. 2,
  148348. 10,
  148349. 1,
  148350. 11,
  148351. 0,
  148352. 12,
  148353. };
  148354. static long _vq_lengthlist__44u8_p7_0[] = {
  148355. 1, 4, 5, 6, 6, 7, 7, 8, 8,10,10,11,11, 5, 6, 6,
  148356. 7, 7, 8, 8, 9, 9,11,10,12,11, 5, 6, 6, 7, 7, 8,
  148357. 8, 9, 9,10,11,11,12, 6, 7, 7, 8, 8, 9, 9,10,10,
  148358. 11,11,12,12, 6, 7, 7, 8, 8, 9, 9,10,10,11,12,13,
  148359. 12, 7, 8, 8, 9, 9,10,10,11,11,12,12,13,13, 8, 8,
  148360. 8, 9, 9,10,10,11,11,12,12,13,13, 9, 9, 9,10,10,
  148361. 11,11,12,12,13,13,14,14, 9, 9, 9,10,10,11,11,12,
  148362. 12,13,13,14,14,10,11,11,12,11,13,12,13,13,14,14,
  148363. 15,15,10,11,11,11,12,12,13,13,14,14,14,15,15,11,
  148364. 12,12,13,13,14,13,15,14,15,15,16,15,11,11,12,13,
  148365. 13,13,14,14,14,15,15,15,16,
  148366. };
  148367. static float _vq_quantthresh__44u8_p7_0[] = {
  148368. -60.5, -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5,
  148369. 27.5, 38.5, 49.5, 60.5,
  148370. };
  148371. static long _vq_quantmap__44u8_p7_0[] = {
  148372. 11, 9, 7, 5, 3, 1, 0, 2,
  148373. 4, 6, 8, 10, 12,
  148374. };
  148375. static encode_aux_threshmatch _vq_auxt__44u8_p7_0 = {
  148376. _vq_quantthresh__44u8_p7_0,
  148377. _vq_quantmap__44u8_p7_0,
  148378. 13,
  148379. 13
  148380. };
  148381. static static_codebook _44u8_p7_0 = {
  148382. 2, 169,
  148383. _vq_lengthlist__44u8_p7_0,
  148384. 1, -523206656, 1618345984, 4, 0,
  148385. _vq_quantlist__44u8_p7_0,
  148386. NULL,
  148387. &_vq_auxt__44u8_p7_0,
  148388. NULL,
  148389. 0
  148390. };
  148391. static long _vq_quantlist__44u8_p7_1[] = {
  148392. 5,
  148393. 4,
  148394. 6,
  148395. 3,
  148396. 7,
  148397. 2,
  148398. 8,
  148399. 1,
  148400. 9,
  148401. 0,
  148402. 10,
  148403. };
  148404. static long _vq_lengthlist__44u8_p7_1[] = {
  148405. 4, 5, 5, 6, 6, 7, 7, 7, 7, 7, 7, 5, 6, 6, 7, 7,
  148406. 7, 7, 7, 7, 7, 7, 5, 6, 6, 7, 7, 7, 7, 7, 7, 7,
  148407. 7, 6, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 6, 7, 7, 7,
  148408. 7, 7, 7, 7, 7, 7, 8, 7, 7, 7, 7, 7, 7, 7, 8, 8,
  148409. 8, 8, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 7, 7, 7,
  148410. 8, 7, 8, 8, 8, 8, 8, 8, 7, 7, 7, 7, 7, 8, 8, 8,
  148411. 8, 8, 8, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 7, 7,
  148412. 7, 8, 8, 8, 8, 8, 8, 8, 8,
  148413. };
  148414. static float _vq_quantthresh__44u8_p7_1[] = {
  148415. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  148416. 3.5, 4.5,
  148417. };
  148418. static long _vq_quantmap__44u8_p7_1[] = {
  148419. 9, 7, 5, 3, 1, 0, 2, 4,
  148420. 6, 8, 10,
  148421. };
  148422. static encode_aux_threshmatch _vq_auxt__44u8_p7_1 = {
  148423. _vq_quantthresh__44u8_p7_1,
  148424. _vq_quantmap__44u8_p7_1,
  148425. 11,
  148426. 11
  148427. };
  148428. static static_codebook _44u8_p7_1 = {
  148429. 2, 121,
  148430. _vq_lengthlist__44u8_p7_1,
  148431. 1, -531365888, 1611661312, 4, 0,
  148432. _vq_quantlist__44u8_p7_1,
  148433. NULL,
  148434. &_vq_auxt__44u8_p7_1,
  148435. NULL,
  148436. 0
  148437. };
  148438. static long _vq_quantlist__44u8_p8_0[] = {
  148439. 7,
  148440. 6,
  148441. 8,
  148442. 5,
  148443. 9,
  148444. 4,
  148445. 10,
  148446. 3,
  148447. 11,
  148448. 2,
  148449. 12,
  148450. 1,
  148451. 13,
  148452. 0,
  148453. 14,
  148454. };
  148455. static long _vq_lengthlist__44u8_p8_0[] = {
  148456. 1, 4, 4, 7, 7, 8, 8, 8, 7, 9, 8,10, 9,11,10, 4,
  148457. 6, 6, 8, 8,10, 9, 9, 9,10,10,11,10,12,10, 4, 6,
  148458. 6, 8, 8,10,10, 9, 9,10,10,11,11,11,12, 7, 8, 8,
  148459. 10,10,11,11,11,10,12,11,12,12,13,11, 7, 8, 8,10,
  148460. 10,11,11,10,10,11,11,12,12,13,13, 8,10,10,11,11,
  148461. 12,11,12,11,13,12,13,12,14,13, 8,10, 9,11,11,12,
  148462. 12,12,12,12,12,13,13,14,13, 8, 9, 9,11,10,12,11,
  148463. 13,12,13,13,14,13,14,13, 8, 9, 9,10,11,12,12,12,
  148464. 12,13,13,14,15,14,14, 9,10,10,12,11,13,12,13,13,
  148465. 14,13,14,14,14,14, 9,10,10,12,12,12,12,13,13,14,
  148466. 14,14,15,14,14,10,11,11,13,12,13,12,14,14,14,14,
  148467. 14,14,15,15,10,11,11,12,12,13,13,14,14,14,15,15,
  148468. 14,16,15,11,12,12,13,12,14,14,14,13,15,14,15,15,
  148469. 15,17,11,12,12,13,13,14,14,14,15,15,14,15,15,14,
  148470. 17,
  148471. };
  148472. static float _vq_quantthresh__44u8_p8_0[] = {
  148473. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  148474. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  148475. };
  148476. static long _vq_quantmap__44u8_p8_0[] = {
  148477. 13, 11, 9, 7, 5, 3, 1, 0,
  148478. 2, 4, 6, 8, 10, 12, 14,
  148479. };
  148480. static encode_aux_threshmatch _vq_auxt__44u8_p8_0 = {
  148481. _vq_quantthresh__44u8_p8_0,
  148482. _vq_quantmap__44u8_p8_0,
  148483. 15,
  148484. 15
  148485. };
  148486. static static_codebook _44u8_p8_0 = {
  148487. 2, 225,
  148488. _vq_lengthlist__44u8_p8_0,
  148489. 1, -520986624, 1620377600, 4, 0,
  148490. _vq_quantlist__44u8_p8_0,
  148491. NULL,
  148492. &_vq_auxt__44u8_p8_0,
  148493. NULL,
  148494. 0
  148495. };
  148496. static long _vq_quantlist__44u8_p8_1[] = {
  148497. 10,
  148498. 9,
  148499. 11,
  148500. 8,
  148501. 12,
  148502. 7,
  148503. 13,
  148504. 6,
  148505. 14,
  148506. 5,
  148507. 15,
  148508. 4,
  148509. 16,
  148510. 3,
  148511. 17,
  148512. 2,
  148513. 18,
  148514. 1,
  148515. 19,
  148516. 0,
  148517. 20,
  148518. };
  148519. static long _vq_lengthlist__44u8_p8_1[] = {
  148520. 4, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9,
  148521. 9, 9, 9, 9, 9, 6, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,
  148522. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 5, 6, 6, 7, 7, 8,
  148523. 8, 9, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 7,
  148524. 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  148525. 9, 9, 9, 9, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  148526. 9, 9, 9, 9, 9, 9, 9, 9, 9, 8, 8, 8, 8, 8, 9, 9,
  148527. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10, 9,10, 8, 8,
  148528. 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 9,10,
  148529. 10, 9,10, 8, 9, 8, 9, 9, 9, 9, 9, 9, 9, 9,10, 9,
  148530. 10,10,10,10,10,10,10,10, 8, 9, 8, 9, 9, 9, 9, 9,
  148531. 9, 9, 9, 9, 9, 9,10,10,10,10, 9,10,10, 9, 9, 9,
  148532. 9, 9, 9, 9, 9, 9, 9, 9,10, 9,10,10,10,10,10,10,
  148533. 10,10, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 9,10,
  148534. 10,10,10,10,10,10,10, 9, 9, 9, 9, 9, 9, 9,10, 9,
  148535. 10,10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9,
  148536. 9, 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,10,
  148537. 10, 9, 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,
  148538. 10,10,10,10,10,10, 9, 9, 9, 9, 9, 9, 9,10,10,10,
  148539. 10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9,
  148540. 9, 9,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  148541. 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,10,10,
  148542. 10,10,10,10,10, 9, 9, 9,10, 9,10,10,10,10,10,10,
  148543. 10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9,10,
  148544. 9,10,10,10,10,10,10,10,10,10,10,10,10,10,10, 9,
  148545. 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,10,10,
  148546. 10,10,10,10, 9, 9, 9,10, 9,10, 9,10,10,10,10,10,
  148547. 10,10,10,10,10,10,10,10,10,
  148548. };
  148549. static float _vq_quantthresh__44u8_p8_1[] = {
  148550. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  148551. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  148552. 6.5, 7.5, 8.5, 9.5,
  148553. };
  148554. static long _vq_quantmap__44u8_p8_1[] = {
  148555. 19, 17, 15, 13, 11, 9, 7, 5,
  148556. 3, 1, 0, 2, 4, 6, 8, 10,
  148557. 12, 14, 16, 18, 20,
  148558. };
  148559. static encode_aux_threshmatch _vq_auxt__44u8_p8_1 = {
  148560. _vq_quantthresh__44u8_p8_1,
  148561. _vq_quantmap__44u8_p8_1,
  148562. 21,
  148563. 21
  148564. };
  148565. static static_codebook _44u8_p8_1 = {
  148566. 2, 441,
  148567. _vq_lengthlist__44u8_p8_1,
  148568. 1, -529268736, 1611661312, 5, 0,
  148569. _vq_quantlist__44u8_p8_1,
  148570. NULL,
  148571. &_vq_auxt__44u8_p8_1,
  148572. NULL,
  148573. 0
  148574. };
  148575. static long _vq_quantlist__44u8_p9_0[] = {
  148576. 4,
  148577. 3,
  148578. 5,
  148579. 2,
  148580. 6,
  148581. 1,
  148582. 7,
  148583. 0,
  148584. 8,
  148585. };
  148586. static long _vq_lengthlist__44u8_p9_0[] = {
  148587. 1, 3, 3, 9, 9, 9, 9, 9, 9, 4, 9, 9, 9, 9, 9, 9,
  148588. 9, 9, 5, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  148589. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  148590. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  148591. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 8, 8, 8,
  148592. 8,
  148593. };
  148594. static float _vq_quantthresh__44u8_p9_0[] = {
  148595. -3258.5, -2327.5, -1396.5, -465.5, 465.5, 1396.5, 2327.5, 3258.5,
  148596. };
  148597. static long _vq_quantmap__44u8_p9_0[] = {
  148598. 7, 5, 3, 1, 0, 2, 4, 6,
  148599. 8,
  148600. };
  148601. static encode_aux_threshmatch _vq_auxt__44u8_p9_0 = {
  148602. _vq_quantthresh__44u8_p9_0,
  148603. _vq_quantmap__44u8_p9_0,
  148604. 9,
  148605. 9
  148606. };
  148607. static static_codebook _44u8_p9_0 = {
  148608. 2, 81,
  148609. _vq_lengthlist__44u8_p9_0,
  148610. 1, -511895552, 1631393792, 4, 0,
  148611. _vq_quantlist__44u8_p9_0,
  148612. NULL,
  148613. &_vq_auxt__44u8_p9_0,
  148614. NULL,
  148615. 0
  148616. };
  148617. static long _vq_quantlist__44u8_p9_1[] = {
  148618. 9,
  148619. 8,
  148620. 10,
  148621. 7,
  148622. 11,
  148623. 6,
  148624. 12,
  148625. 5,
  148626. 13,
  148627. 4,
  148628. 14,
  148629. 3,
  148630. 15,
  148631. 2,
  148632. 16,
  148633. 1,
  148634. 17,
  148635. 0,
  148636. 18,
  148637. };
  148638. static long _vq_lengthlist__44u8_p9_1[] = {
  148639. 1, 4, 4, 7, 7, 8, 7, 8, 6, 9, 7,10, 8,11,10,11,
  148640. 11,11,11, 4, 7, 6, 9, 9,10, 9, 9, 9,10,10,11,10,
  148641. 11,10,11,11,13,11, 4, 7, 7, 9, 9, 9, 9, 9, 9,10,
  148642. 10,11,10,11,11,11,12,11,12, 7, 9, 8,11,11,11,11,
  148643. 10,10,11,11,12,12,12,12,12,12,14,13, 7, 8, 9,10,
  148644. 11,11,11,10,10,11,11,11,11,12,12,14,12,13,14, 8,
  148645. 9, 9,11,11,11,11,11,11,12,12,14,12,15,14,14,14,
  148646. 15,14, 8, 9, 9,11,11,11,11,12,11,12,12,13,13,13,
  148647. 13,13,13,14,14, 8, 9, 9,11,10,12,11,12,12,13,13,
  148648. 13,13,15,14,14,14,16,16, 8, 9, 9,10,11,11,12,12,
  148649. 12,13,13,13,14,14,14,15,16,15,15, 9,10,10,11,12,
  148650. 12,13,13,13,14,14,16,14,14,16,16,16,16,15, 9,10,
  148651. 10,11,11,12,13,13,14,15,14,16,14,15,16,16,16,16,
  148652. 15,10,11,11,12,13,13,14,15,15,15,15,15,16,15,16,
  148653. 15,16,15,15,10,11,11,13,13,14,13,13,15,14,15,15,
  148654. 16,15,15,15,16,15,16,10,12,12,14,14,14,14,14,16,
  148655. 16,15,15,15,16,16,16,16,16,16,11,12,12,14,14,14,
  148656. 14,15,15,16,15,16,15,16,15,16,16,16,16,12,12,13,
  148657. 14,14,15,16,16,16,16,16,16,15,16,16,16,16,16,16,
  148658. 12,13,13,14,14,14,14,15,16,15,16,16,16,16,16,16,
  148659. 16,16,16,12,13,14,14,14,16,15,16,15,16,16,16,16,
  148660. 16,16,16,16,16,16,12,14,13,14,15,15,15,16,15,16,
  148661. 16,15,16,16,16,16,16,16,16,
  148662. };
  148663. static float _vq_quantthresh__44u8_p9_1[] = {
  148664. -416.5, -367.5, -318.5, -269.5, -220.5, -171.5, -122.5, -73.5,
  148665. -24.5, 24.5, 73.5, 122.5, 171.5, 220.5, 269.5, 318.5,
  148666. 367.5, 416.5,
  148667. };
  148668. static long _vq_quantmap__44u8_p9_1[] = {
  148669. 17, 15, 13, 11, 9, 7, 5, 3,
  148670. 1, 0, 2, 4, 6, 8, 10, 12,
  148671. 14, 16, 18,
  148672. };
  148673. static encode_aux_threshmatch _vq_auxt__44u8_p9_1 = {
  148674. _vq_quantthresh__44u8_p9_1,
  148675. _vq_quantmap__44u8_p9_1,
  148676. 19,
  148677. 19
  148678. };
  148679. static static_codebook _44u8_p9_1 = {
  148680. 2, 361,
  148681. _vq_lengthlist__44u8_p9_1,
  148682. 1, -518287360, 1622704128, 5, 0,
  148683. _vq_quantlist__44u8_p9_1,
  148684. NULL,
  148685. &_vq_auxt__44u8_p9_1,
  148686. NULL,
  148687. 0
  148688. };
  148689. static long _vq_quantlist__44u8_p9_2[] = {
  148690. 24,
  148691. 23,
  148692. 25,
  148693. 22,
  148694. 26,
  148695. 21,
  148696. 27,
  148697. 20,
  148698. 28,
  148699. 19,
  148700. 29,
  148701. 18,
  148702. 30,
  148703. 17,
  148704. 31,
  148705. 16,
  148706. 32,
  148707. 15,
  148708. 33,
  148709. 14,
  148710. 34,
  148711. 13,
  148712. 35,
  148713. 12,
  148714. 36,
  148715. 11,
  148716. 37,
  148717. 10,
  148718. 38,
  148719. 9,
  148720. 39,
  148721. 8,
  148722. 40,
  148723. 7,
  148724. 41,
  148725. 6,
  148726. 42,
  148727. 5,
  148728. 43,
  148729. 4,
  148730. 44,
  148731. 3,
  148732. 45,
  148733. 2,
  148734. 46,
  148735. 1,
  148736. 47,
  148737. 0,
  148738. 48,
  148739. };
  148740. static long _vq_lengthlist__44u8_p9_2[] = {
  148741. 2, 3, 4, 5, 5, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6, 6,
  148742. 6, 6, 6, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  148743. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  148744. 7,
  148745. };
  148746. static float _vq_quantthresh__44u8_p9_2[] = {
  148747. -23.5, -22.5, -21.5, -20.5, -19.5, -18.5, -17.5, -16.5,
  148748. -15.5, -14.5, -13.5, -12.5, -11.5, -10.5, -9.5, -8.5,
  148749. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  148750. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  148751. 8.5, 9.5, 10.5, 11.5, 12.5, 13.5, 14.5, 15.5,
  148752. 16.5, 17.5, 18.5, 19.5, 20.5, 21.5, 22.5, 23.5,
  148753. };
  148754. static long _vq_quantmap__44u8_p9_2[] = {
  148755. 47, 45, 43, 41, 39, 37, 35, 33,
  148756. 31, 29, 27, 25, 23, 21, 19, 17,
  148757. 15, 13, 11, 9, 7, 5, 3, 1,
  148758. 0, 2, 4, 6, 8, 10, 12, 14,
  148759. 16, 18, 20, 22, 24, 26, 28, 30,
  148760. 32, 34, 36, 38, 40, 42, 44, 46,
  148761. 48,
  148762. };
  148763. static encode_aux_threshmatch _vq_auxt__44u8_p9_2 = {
  148764. _vq_quantthresh__44u8_p9_2,
  148765. _vq_quantmap__44u8_p9_2,
  148766. 49,
  148767. 49
  148768. };
  148769. static static_codebook _44u8_p9_2 = {
  148770. 1, 49,
  148771. _vq_lengthlist__44u8_p9_2,
  148772. 1, -526909440, 1611661312, 6, 0,
  148773. _vq_quantlist__44u8_p9_2,
  148774. NULL,
  148775. &_vq_auxt__44u8_p9_2,
  148776. NULL,
  148777. 0
  148778. };
  148779. static long _huff_lengthlist__44u9__long[] = {
  148780. 3, 9,13,13,14,15,14,14,15,15, 5, 5, 9,10,12,12,
  148781. 13,14,16,15,10, 6, 6, 6, 8,11,12,13,16,15,11, 7,
  148782. 5, 3, 5, 8,10,12,15,15,10,10, 7, 4, 3, 5, 8,10,
  148783. 12,12,12,12, 9, 7, 5, 4, 6, 8,10,13,13,12,11, 9,
  148784. 7, 5, 5, 6, 9,12,14,12,12,10, 8, 6, 6, 6, 7,11,
  148785. 13,12,14,13,10, 8, 7, 7, 7,10,11,11,12,13,12,11,
  148786. 10, 8, 8, 9,
  148787. };
  148788. static static_codebook _huff_book__44u9__long = {
  148789. 2, 100,
  148790. _huff_lengthlist__44u9__long,
  148791. 0, 0, 0, 0, 0,
  148792. NULL,
  148793. NULL,
  148794. NULL,
  148795. NULL,
  148796. 0
  148797. };
  148798. static long _huff_lengthlist__44u9__short[] = {
  148799. 9,16,18,18,17,17,17,17,17,17, 5, 8,11,12,11,12,
  148800. 17,17,16,16, 6, 6, 8, 8, 9,10,14,15,16,16, 6, 7,
  148801. 7, 4, 6, 9,13,16,16,16, 6, 6, 7, 4, 5, 8,11,15,
  148802. 17,16, 7, 6, 7, 6, 6, 8, 9,10,14,16,11, 8, 8, 7,
  148803. 6, 6, 3, 4,10,15,14,12,12,10, 5, 6, 3, 3, 8,13,
  148804. 15,17,15,11, 6, 8, 6, 6, 9,14,17,15,15,12, 8,10,
  148805. 9, 9,12,15,
  148806. };
  148807. static static_codebook _huff_book__44u9__short = {
  148808. 2, 100,
  148809. _huff_lengthlist__44u9__short,
  148810. 0, 0, 0, 0, 0,
  148811. NULL,
  148812. NULL,
  148813. NULL,
  148814. NULL,
  148815. 0
  148816. };
  148817. static long _vq_quantlist__44u9_p1_0[] = {
  148818. 1,
  148819. 0,
  148820. 2,
  148821. };
  148822. static long _vq_lengthlist__44u9_p1_0[] = {
  148823. 1, 5, 5, 5, 7, 7, 5, 7, 7, 5, 7, 7, 7, 9, 9, 7,
  148824. 9, 9, 5, 7, 7, 7, 9, 9, 7, 9, 9, 5, 7, 7, 7, 9,
  148825. 9, 7, 9, 9, 8, 9, 9, 9,10,11, 9,11,11, 7, 9, 9,
  148826. 9,11,10, 9,11,11, 5, 7, 7, 7, 9, 9, 8, 9,10, 7,
  148827. 9, 9, 9,11,11, 9,10,11, 7, 9,10, 9,11,11, 9,11,
  148828. 10,
  148829. };
  148830. static float _vq_quantthresh__44u9_p1_0[] = {
  148831. -0.5, 0.5,
  148832. };
  148833. static long _vq_quantmap__44u9_p1_0[] = {
  148834. 1, 0, 2,
  148835. };
  148836. static encode_aux_threshmatch _vq_auxt__44u9_p1_0 = {
  148837. _vq_quantthresh__44u9_p1_0,
  148838. _vq_quantmap__44u9_p1_0,
  148839. 3,
  148840. 3
  148841. };
  148842. static static_codebook _44u9_p1_0 = {
  148843. 4, 81,
  148844. _vq_lengthlist__44u9_p1_0,
  148845. 1, -535822336, 1611661312, 2, 0,
  148846. _vq_quantlist__44u9_p1_0,
  148847. NULL,
  148848. &_vq_auxt__44u9_p1_0,
  148849. NULL,
  148850. 0
  148851. };
  148852. static long _vq_quantlist__44u9_p2_0[] = {
  148853. 2,
  148854. 1,
  148855. 3,
  148856. 0,
  148857. 4,
  148858. };
  148859. static long _vq_lengthlist__44u9_p2_0[] = {
  148860. 3, 5, 5, 8, 8, 5, 7, 7, 9, 9, 6, 7, 7, 9, 9, 8,
  148861. 9, 9,11,10, 8, 9, 9,11,11, 6, 7, 7, 9, 9, 7, 8,
  148862. 8,10,10, 7, 8, 8, 9,10, 9,10,10,11,11, 9, 9,10,
  148863. 11,11, 6, 7, 7, 9, 9, 7, 8, 8,10, 9, 7, 8, 8,10,
  148864. 10, 9,10, 9,11,11, 9,10,10,11,11, 8, 9, 9,11,11,
  148865. 9,10,10,12,11, 9,10,10,11,12,11,11,11,13,13,11,
  148866. 11,11,12,13, 8, 9, 9,11,11, 9,10,10,11,11, 9,10,
  148867. 10,12,11,11,12,11,13,12,11,11,12,13,13, 6, 7, 7,
  148868. 9, 9, 7, 8, 8,10,10, 7, 8, 8,10,10, 9,10,10,12,
  148869. 11, 9,10,10,11,12, 7, 8, 8,10,10, 8, 9, 9,11,11,
  148870. 8, 9, 9,10,10,10,11,11,12,12,10,10,11,12,12, 7,
  148871. 8, 8,10,10, 8, 9, 8,10,10, 8, 9, 9,10,10,10,11,
  148872. 10,12,11,10,10,11,12,12, 9,10,10,11,12,10,11,11,
  148873. 12,12,10,11,10,12,12,12,12,12,13,13,11,12,12,13,
  148874. 13, 9,10,10,11,11, 9,10,10,12,12,10,11,11,12,13,
  148875. 11,12,11,13,12,12,12,12,13,14, 6, 7, 7, 9, 9, 7,
  148876. 8, 8,10,10, 7, 8, 8,10,10, 9,10,10,11,11, 9,10,
  148877. 10,11,12, 7, 8, 8,10,10, 8, 9, 9,11,10, 8, 8, 9,
  148878. 10,10,10,11,10,12,12,10,10,11,11,12, 7, 8, 8,10,
  148879. 10, 8, 9, 9,10,10, 8, 9, 9,10,10,10,11,10,12,12,
  148880. 10,11,10,12,12, 9,10,10,12,11,10,11,11,12,12, 9,
  148881. 10,10,12,12,12,12,12,13,13,11,11,12,12,14, 9,10,
  148882. 10,11,12,10,11,11,12,12,10,11,11,12,12,11,12,12,
  148883. 14,14,12,12,12,13,13, 8, 9, 9,11,11, 9,10,10,12,
  148884. 11, 9,10,10,12,12,11,12,11,13,13,11,11,12,13,13,
  148885. 9,10,10,12,12,10,11,11,12,12,10,11,11,12,12,12,
  148886. 12,12,14,14,12,12,12,13,13, 9,10,10,12,11,10,11,
  148887. 10,12,12,10,11,11,12,12,11,12,12,14,13,12,12,12,
  148888. 13,14,11,12,11,13,13,11,12,12,13,13,12,12,12,14,
  148889. 14,13,13,13,13,15,13,13,14,15,15,11,11,11,13,13,
  148890. 11,12,11,13,13,11,12,12,13,13,12,13,12,15,13,13,
  148891. 13,14,14,15, 8, 9, 9,11,11, 9,10,10,11,12, 9,10,
  148892. 10,11,12,11,12,11,13,13,11,12,12,13,13, 9,10,10,
  148893. 11,12,10,11,10,12,12,10,10,11,12,13,12,12,12,14,
  148894. 13,11,12,12,13,14, 9,10,10,12,12,10,11,11,12,12,
  148895. 10,11,11,12,12,12,12,12,14,13,12,12,12,14,13,11,
  148896. 11,11,13,13,11,12,12,14,13,11,11,12,13,13,13,13,
  148897. 13,15,14,12,12,13,13,15,11,12,12,13,13,12,12,12,
  148898. 13,14,11,12,12,13,13,13,13,14,14,15,13,13,13,14,
  148899. 14,
  148900. };
  148901. static float _vq_quantthresh__44u9_p2_0[] = {
  148902. -1.5, -0.5, 0.5, 1.5,
  148903. };
  148904. static long _vq_quantmap__44u9_p2_0[] = {
  148905. 3, 1, 0, 2, 4,
  148906. };
  148907. static encode_aux_threshmatch _vq_auxt__44u9_p2_0 = {
  148908. _vq_quantthresh__44u9_p2_0,
  148909. _vq_quantmap__44u9_p2_0,
  148910. 5,
  148911. 5
  148912. };
  148913. static static_codebook _44u9_p2_0 = {
  148914. 4, 625,
  148915. _vq_lengthlist__44u9_p2_0,
  148916. 1, -533725184, 1611661312, 3, 0,
  148917. _vq_quantlist__44u9_p2_0,
  148918. NULL,
  148919. &_vq_auxt__44u9_p2_0,
  148920. NULL,
  148921. 0
  148922. };
  148923. static long _vq_quantlist__44u9_p3_0[] = {
  148924. 4,
  148925. 3,
  148926. 5,
  148927. 2,
  148928. 6,
  148929. 1,
  148930. 7,
  148931. 0,
  148932. 8,
  148933. };
  148934. static long _vq_lengthlist__44u9_p3_0[] = {
  148935. 3, 4, 4, 5, 5, 7, 7, 8, 8, 4, 5, 5, 6, 6, 7, 7,
  148936. 9, 9, 4, 4, 5, 6, 6, 7, 7, 9, 9, 5, 6, 6, 7, 7,
  148937. 8, 8, 9, 9, 5, 6, 6, 7, 7, 8, 8, 9, 9, 7, 7, 7,
  148938. 8, 8, 9, 9,10,10, 7, 7, 7, 8, 8, 9, 9,10,10, 8,
  148939. 9, 9,10, 9,10,10,11,11, 8, 9, 9, 9,10,10,10,11,
  148940. 11,
  148941. };
  148942. static float _vq_quantthresh__44u9_p3_0[] = {
  148943. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  148944. };
  148945. static long _vq_quantmap__44u9_p3_0[] = {
  148946. 7, 5, 3, 1, 0, 2, 4, 6,
  148947. 8,
  148948. };
  148949. static encode_aux_threshmatch _vq_auxt__44u9_p3_0 = {
  148950. _vq_quantthresh__44u9_p3_0,
  148951. _vq_quantmap__44u9_p3_0,
  148952. 9,
  148953. 9
  148954. };
  148955. static static_codebook _44u9_p3_0 = {
  148956. 2, 81,
  148957. _vq_lengthlist__44u9_p3_0,
  148958. 1, -531628032, 1611661312, 4, 0,
  148959. _vq_quantlist__44u9_p3_0,
  148960. NULL,
  148961. &_vq_auxt__44u9_p3_0,
  148962. NULL,
  148963. 0
  148964. };
  148965. static long _vq_quantlist__44u9_p4_0[] = {
  148966. 8,
  148967. 7,
  148968. 9,
  148969. 6,
  148970. 10,
  148971. 5,
  148972. 11,
  148973. 4,
  148974. 12,
  148975. 3,
  148976. 13,
  148977. 2,
  148978. 14,
  148979. 1,
  148980. 15,
  148981. 0,
  148982. 16,
  148983. };
  148984. static long _vq_lengthlist__44u9_p4_0[] = {
  148985. 4, 5, 5, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,10,11,
  148986. 11, 5, 5, 5, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,10,
  148987. 11,11, 5, 5, 5, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,
  148988. 10,11,11, 6, 6, 6, 7, 6, 7, 7, 8, 8, 9, 9,10,10,
  148989. 11,11,12,11, 6, 6, 6, 6, 7, 7, 7, 8, 8, 9, 9,10,
  148990. 10,11,11,11,12, 7, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9,
  148991. 10,10,11,11,12,12, 7, 7, 7, 7, 7, 8, 8, 9, 9, 9,
  148992. 9,10,10,11,11,12,12, 8, 8, 8, 8, 8, 9, 8,10, 9,
  148993. 10,10,11,10,12,11,13,12, 8, 8, 8, 8, 8, 9, 9, 9,
  148994. 10,10,10,10,11,11,12,12,12, 8, 8, 8, 9, 9, 9, 9,
  148995. 10,10,11,10,12,11,12,12,13,12, 8, 8, 8, 9, 9, 9,
  148996. 9,10,10,10,11,11,11,12,12,12,13, 9, 9, 9,10,10,
  148997. 10,10,11,10,11,11,12,11,13,12,13,13, 9, 9,10,10,
  148998. 10,10,10,10,11,11,11,11,12,12,13,13,13,10,11,10,
  148999. 11,11,11,11,12,11,12,12,13,12,13,13,14,13,10,10,
  149000. 10,11,11,11,11,11,12,12,12,12,13,13,13,13,14,11,
  149001. 11,11,12,11,12,12,12,12,13,13,13,13,14,13,14,14,
  149002. 11,11,11,11,12,12,12,12,12,12,13,13,13,13,14,14,
  149003. 14,
  149004. };
  149005. static float _vq_quantthresh__44u9_p4_0[] = {
  149006. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  149007. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  149008. };
  149009. static long _vq_quantmap__44u9_p4_0[] = {
  149010. 15, 13, 11, 9, 7, 5, 3, 1,
  149011. 0, 2, 4, 6, 8, 10, 12, 14,
  149012. 16,
  149013. };
  149014. static encode_aux_threshmatch _vq_auxt__44u9_p4_0 = {
  149015. _vq_quantthresh__44u9_p4_0,
  149016. _vq_quantmap__44u9_p4_0,
  149017. 17,
  149018. 17
  149019. };
  149020. static static_codebook _44u9_p4_0 = {
  149021. 2, 289,
  149022. _vq_lengthlist__44u9_p4_0,
  149023. 1, -529530880, 1611661312, 5, 0,
  149024. _vq_quantlist__44u9_p4_0,
  149025. NULL,
  149026. &_vq_auxt__44u9_p4_0,
  149027. NULL,
  149028. 0
  149029. };
  149030. static long _vq_quantlist__44u9_p5_0[] = {
  149031. 1,
  149032. 0,
  149033. 2,
  149034. };
  149035. static long _vq_lengthlist__44u9_p5_0[] = {
  149036. 1, 4, 4, 5, 7, 7, 5, 7, 7, 5, 8, 8, 8, 9, 9, 7,
  149037. 9, 9, 5, 8, 8, 7, 9, 9, 8, 9, 9, 5, 8, 8, 8,10,
  149038. 10, 8,10,10, 7,10,10, 9,10,12, 9,11,11, 7,10,10,
  149039. 9,11,10, 9,11,12, 5, 8, 8, 8,10,10, 8,10,10, 7,
  149040. 10,10, 9,12,11, 9,10,11, 7,10,10, 9,11,11,10,12,
  149041. 10,
  149042. };
  149043. static float _vq_quantthresh__44u9_p5_0[] = {
  149044. -5.5, 5.5,
  149045. };
  149046. static long _vq_quantmap__44u9_p5_0[] = {
  149047. 1, 0, 2,
  149048. };
  149049. static encode_aux_threshmatch _vq_auxt__44u9_p5_0 = {
  149050. _vq_quantthresh__44u9_p5_0,
  149051. _vq_quantmap__44u9_p5_0,
  149052. 3,
  149053. 3
  149054. };
  149055. static static_codebook _44u9_p5_0 = {
  149056. 4, 81,
  149057. _vq_lengthlist__44u9_p5_0,
  149058. 1, -529137664, 1618345984, 2, 0,
  149059. _vq_quantlist__44u9_p5_0,
  149060. NULL,
  149061. &_vq_auxt__44u9_p5_0,
  149062. NULL,
  149063. 0
  149064. };
  149065. static long _vq_quantlist__44u9_p5_1[] = {
  149066. 5,
  149067. 4,
  149068. 6,
  149069. 3,
  149070. 7,
  149071. 2,
  149072. 8,
  149073. 1,
  149074. 9,
  149075. 0,
  149076. 10,
  149077. };
  149078. static long _vq_lengthlist__44u9_p5_1[] = {
  149079. 5, 5, 5, 6, 6, 7, 7, 7, 7, 7, 7, 5, 6, 6, 6, 6,
  149080. 7, 7, 7, 7, 8, 7, 5, 6, 6, 6, 6, 7, 7, 7, 7, 7,
  149081. 7, 6, 6, 6, 7, 7, 7, 7, 7, 7, 8, 8, 6, 6, 6, 7,
  149082. 7, 7, 7, 7, 7, 8, 8, 7, 7, 7, 7, 7, 8, 7, 8, 8,
  149083. 8, 8, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8, 7, 7, 7,
  149084. 8, 7, 8, 8, 8, 8, 8, 8, 7, 7, 7, 7, 8, 8, 8, 8,
  149085. 8, 8, 8, 7, 8, 7, 8, 8, 8, 8, 8, 8, 8, 8, 7, 8,
  149086. 8, 8, 8, 8, 8, 8, 8, 8, 8,
  149087. };
  149088. static float _vq_quantthresh__44u9_p5_1[] = {
  149089. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  149090. 3.5, 4.5,
  149091. };
  149092. static long _vq_quantmap__44u9_p5_1[] = {
  149093. 9, 7, 5, 3, 1, 0, 2, 4,
  149094. 6, 8, 10,
  149095. };
  149096. static encode_aux_threshmatch _vq_auxt__44u9_p5_1 = {
  149097. _vq_quantthresh__44u9_p5_1,
  149098. _vq_quantmap__44u9_p5_1,
  149099. 11,
  149100. 11
  149101. };
  149102. static static_codebook _44u9_p5_1 = {
  149103. 2, 121,
  149104. _vq_lengthlist__44u9_p5_1,
  149105. 1, -531365888, 1611661312, 4, 0,
  149106. _vq_quantlist__44u9_p5_1,
  149107. NULL,
  149108. &_vq_auxt__44u9_p5_1,
  149109. NULL,
  149110. 0
  149111. };
  149112. static long _vq_quantlist__44u9_p6_0[] = {
  149113. 6,
  149114. 5,
  149115. 7,
  149116. 4,
  149117. 8,
  149118. 3,
  149119. 9,
  149120. 2,
  149121. 10,
  149122. 1,
  149123. 11,
  149124. 0,
  149125. 12,
  149126. };
  149127. static long _vq_lengthlist__44u9_p6_0[] = {
  149128. 2, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10, 4, 6, 5,
  149129. 7, 7, 8, 8, 8, 8, 9, 9,10,10, 4, 5, 6, 7, 7, 8,
  149130. 8, 8, 8, 9, 9,10,10, 6, 7, 7, 8, 8, 8, 8, 9, 9,
  149131. 10,10,10,10, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,10,10,
  149132. 10, 7, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,11, 7, 8,
  149133. 8, 8, 8, 9, 9, 9, 9,10,10,11,11, 8, 8, 8, 9, 9,
  149134. 9, 9, 9,10,10,10,11,11, 8, 8, 8, 9, 9, 9, 9,10,
  149135. 9,10,10,11,11, 9, 9, 9,10,10,10,10,10,11,11,11,
  149136. 11,12, 9, 9, 9,10,10,10,10,10,10,11,10,12,11,10,
  149137. 10,10,10,10,11,11,11,11,11,12,12,12,10,10,10,10,
  149138. 10,11,11,11,11,12,11,12,12,
  149139. };
  149140. static float _vq_quantthresh__44u9_p6_0[] = {
  149141. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  149142. 12.5, 17.5, 22.5, 27.5,
  149143. };
  149144. static long _vq_quantmap__44u9_p6_0[] = {
  149145. 11, 9, 7, 5, 3, 1, 0, 2,
  149146. 4, 6, 8, 10, 12,
  149147. };
  149148. static encode_aux_threshmatch _vq_auxt__44u9_p6_0 = {
  149149. _vq_quantthresh__44u9_p6_0,
  149150. _vq_quantmap__44u9_p6_0,
  149151. 13,
  149152. 13
  149153. };
  149154. static static_codebook _44u9_p6_0 = {
  149155. 2, 169,
  149156. _vq_lengthlist__44u9_p6_0,
  149157. 1, -526516224, 1616117760, 4, 0,
  149158. _vq_quantlist__44u9_p6_0,
  149159. NULL,
  149160. &_vq_auxt__44u9_p6_0,
  149161. NULL,
  149162. 0
  149163. };
  149164. static long _vq_quantlist__44u9_p6_1[] = {
  149165. 2,
  149166. 1,
  149167. 3,
  149168. 0,
  149169. 4,
  149170. };
  149171. static long _vq_lengthlist__44u9_p6_1[] = {
  149172. 4, 4, 4, 5, 5, 4, 5, 4, 5, 5, 4, 4, 5, 5, 5, 5,
  149173. 5, 5, 5, 5, 5, 5, 5, 5, 5,
  149174. };
  149175. static float _vq_quantthresh__44u9_p6_1[] = {
  149176. -1.5, -0.5, 0.5, 1.5,
  149177. };
  149178. static long _vq_quantmap__44u9_p6_1[] = {
  149179. 3, 1, 0, 2, 4,
  149180. };
  149181. static encode_aux_threshmatch _vq_auxt__44u9_p6_1 = {
  149182. _vq_quantthresh__44u9_p6_1,
  149183. _vq_quantmap__44u9_p6_1,
  149184. 5,
  149185. 5
  149186. };
  149187. static static_codebook _44u9_p6_1 = {
  149188. 2, 25,
  149189. _vq_lengthlist__44u9_p6_1,
  149190. 1, -533725184, 1611661312, 3, 0,
  149191. _vq_quantlist__44u9_p6_1,
  149192. NULL,
  149193. &_vq_auxt__44u9_p6_1,
  149194. NULL,
  149195. 0
  149196. };
  149197. static long _vq_quantlist__44u9_p7_0[] = {
  149198. 6,
  149199. 5,
  149200. 7,
  149201. 4,
  149202. 8,
  149203. 3,
  149204. 9,
  149205. 2,
  149206. 10,
  149207. 1,
  149208. 11,
  149209. 0,
  149210. 12,
  149211. };
  149212. static long _vq_lengthlist__44u9_p7_0[] = {
  149213. 1, 4, 5, 6, 6, 7, 7, 8, 9,10,10,11,11, 5, 6, 6,
  149214. 7, 7, 8, 8, 9, 9,10,10,11,11, 5, 6, 6, 7, 7, 8,
  149215. 8, 9, 9,10,10,11,11, 6, 7, 7, 8, 8, 9, 9,10,10,
  149216. 11,11,12,12, 6, 7, 7, 8, 8, 9, 9,10,10,11,11,12,
  149217. 12, 8, 8, 8, 9, 9,10,10,11,11,12,12,13,13, 8, 8,
  149218. 8, 9, 9,10,10,11,11,12,12,13,13, 9, 9, 9,10,10,
  149219. 11,11,12,12,13,13,13,13, 9, 9, 9,10,10,11,11,12,
  149220. 12,13,13,14,14,10,10,10,11,11,12,12,13,13,14,13,
  149221. 15,14,10,10,10,11,11,12,12,13,13,14,14,14,14,11,
  149222. 11,12,12,12,13,13,14,14,14,14,15,15,11,11,12,12,
  149223. 12,13,13,14,14,14,15,15,15,
  149224. };
  149225. static float _vq_quantthresh__44u9_p7_0[] = {
  149226. -60.5, -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5,
  149227. 27.5, 38.5, 49.5, 60.5,
  149228. };
  149229. static long _vq_quantmap__44u9_p7_0[] = {
  149230. 11, 9, 7, 5, 3, 1, 0, 2,
  149231. 4, 6, 8, 10, 12,
  149232. };
  149233. static encode_aux_threshmatch _vq_auxt__44u9_p7_0 = {
  149234. _vq_quantthresh__44u9_p7_0,
  149235. _vq_quantmap__44u9_p7_0,
  149236. 13,
  149237. 13
  149238. };
  149239. static static_codebook _44u9_p7_0 = {
  149240. 2, 169,
  149241. _vq_lengthlist__44u9_p7_0,
  149242. 1, -523206656, 1618345984, 4, 0,
  149243. _vq_quantlist__44u9_p7_0,
  149244. NULL,
  149245. &_vq_auxt__44u9_p7_0,
  149246. NULL,
  149247. 0
  149248. };
  149249. static long _vq_quantlist__44u9_p7_1[] = {
  149250. 5,
  149251. 4,
  149252. 6,
  149253. 3,
  149254. 7,
  149255. 2,
  149256. 8,
  149257. 1,
  149258. 9,
  149259. 0,
  149260. 10,
  149261. };
  149262. static long _vq_lengthlist__44u9_p7_1[] = {
  149263. 5, 6, 6, 7, 7, 7, 7, 7, 7, 7, 7, 6, 6, 6, 7, 7,
  149264. 7, 7, 7, 7, 7, 7, 6, 6, 6, 7, 7, 7, 7, 7, 7, 7,
  149265. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 6, 7, 7, 7,
  149266. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  149267. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  149268. 7, 7, 7, 7, 8, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  149269. 7, 8, 8, 7, 7, 7, 7, 7, 7, 7, 8, 7, 8, 8, 7, 7,
  149270. 7, 7, 7, 7, 7, 8, 8, 8, 8,
  149271. };
  149272. static float _vq_quantthresh__44u9_p7_1[] = {
  149273. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  149274. 3.5, 4.5,
  149275. };
  149276. static long _vq_quantmap__44u9_p7_1[] = {
  149277. 9, 7, 5, 3, 1, 0, 2, 4,
  149278. 6, 8, 10,
  149279. };
  149280. static encode_aux_threshmatch _vq_auxt__44u9_p7_1 = {
  149281. _vq_quantthresh__44u9_p7_1,
  149282. _vq_quantmap__44u9_p7_1,
  149283. 11,
  149284. 11
  149285. };
  149286. static static_codebook _44u9_p7_1 = {
  149287. 2, 121,
  149288. _vq_lengthlist__44u9_p7_1,
  149289. 1, -531365888, 1611661312, 4, 0,
  149290. _vq_quantlist__44u9_p7_1,
  149291. NULL,
  149292. &_vq_auxt__44u9_p7_1,
  149293. NULL,
  149294. 0
  149295. };
  149296. static long _vq_quantlist__44u9_p8_0[] = {
  149297. 7,
  149298. 6,
  149299. 8,
  149300. 5,
  149301. 9,
  149302. 4,
  149303. 10,
  149304. 3,
  149305. 11,
  149306. 2,
  149307. 12,
  149308. 1,
  149309. 13,
  149310. 0,
  149311. 14,
  149312. };
  149313. static long _vq_lengthlist__44u9_p8_0[] = {
  149314. 1, 4, 4, 7, 7, 8, 8, 8, 8, 9, 9,10, 9,11,10, 4,
  149315. 6, 6, 8, 8, 9, 9, 9, 9,10,10,11,10,12,10, 4, 6,
  149316. 6, 8, 8, 9,10, 9, 9,10,10,11,11,12,12, 7, 8, 8,
  149317. 10,10,11,11,10,10,11,11,12,12,13,12, 7, 8, 8,10,
  149318. 10,11,11,10,10,11,11,12,12,12,13, 8,10, 9,11,11,
  149319. 12,12,11,11,12,12,13,13,14,13, 8, 9, 9,11,11,12,
  149320. 12,11,12,12,12,13,13,14,13, 8, 9, 9,10,10,12,11,
  149321. 13,12,13,13,14,13,15,14, 8, 9, 9,10,10,11,12,12,
  149322. 12,13,13,13,14,14,14, 9,10,10,12,11,13,12,13,13,
  149323. 14,13,14,14,14,15, 9,10,10,11,12,12,12,13,13,14,
  149324. 14,14,15,15,15,10,11,11,12,12,13,13,14,14,14,14,
  149325. 15,14,16,15,10,11,11,12,12,13,13,13,14,14,14,14,
  149326. 14,15,16,11,12,12,13,13,14,13,14,14,15,14,15,16,
  149327. 16,16,11,12,12,13,13,14,13,14,14,15,15,15,16,15,
  149328. 15,
  149329. };
  149330. static float _vq_quantthresh__44u9_p8_0[] = {
  149331. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  149332. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  149333. };
  149334. static long _vq_quantmap__44u9_p8_0[] = {
  149335. 13, 11, 9, 7, 5, 3, 1, 0,
  149336. 2, 4, 6, 8, 10, 12, 14,
  149337. };
  149338. static encode_aux_threshmatch _vq_auxt__44u9_p8_0 = {
  149339. _vq_quantthresh__44u9_p8_0,
  149340. _vq_quantmap__44u9_p8_0,
  149341. 15,
  149342. 15
  149343. };
  149344. static static_codebook _44u9_p8_0 = {
  149345. 2, 225,
  149346. _vq_lengthlist__44u9_p8_0,
  149347. 1, -520986624, 1620377600, 4, 0,
  149348. _vq_quantlist__44u9_p8_0,
  149349. NULL,
  149350. &_vq_auxt__44u9_p8_0,
  149351. NULL,
  149352. 0
  149353. };
  149354. static long _vq_quantlist__44u9_p8_1[] = {
  149355. 10,
  149356. 9,
  149357. 11,
  149358. 8,
  149359. 12,
  149360. 7,
  149361. 13,
  149362. 6,
  149363. 14,
  149364. 5,
  149365. 15,
  149366. 4,
  149367. 16,
  149368. 3,
  149369. 17,
  149370. 2,
  149371. 18,
  149372. 1,
  149373. 19,
  149374. 0,
  149375. 20,
  149376. };
  149377. static long _vq_lengthlist__44u9_p8_1[] = {
  149378. 4, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9,
  149379. 9, 9, 9, 9, 9, 6, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,
  149380. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 6, 6, 6, 7, 7, 8,
  149381. 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 7,
  149382. 7, 7, 8, 8, 8, 8, 9, 8, 9, 9, 9, 9, 9, 9, 9, 9,
  149383. 9, 9, 9, 9, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  149384. 9, 9, 9, 9, 9, 9, 9, 9, 9, 8, 8, 8, 8, 8, 9, 9,
  149385. 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 9,10,10,10, 8, 8,
  149386. 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  149387. 9,10,10, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  149388. 10, 9,10, 9,10,10,10,10, 8, 8, 8, 9, 9, 9, 9, 9,
  149389. 9, 9, 9, 9, 9,10,10, 9,10,10,10,10,10, 9, 9, 9,
  149390. 9, 9, 9, 9, 9, 9, 9, 9,10, 9,10,10,10,10,10,10,
  149391. 10,10, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,
  149392. 10,10,10,10,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  149393. 9, 9,10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9,
  149394. 9, 9, 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,
  149395. 10, 9, 9, 9, 9, 9, 9, 9,10, 9,10,10,10,10,10,10,
  149396. 10,10,10,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9,10,10,
  149397. 10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9,
  149398. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  149399. 9, 9, 9, 9,10, 9, 9,10,10,10,10,10,10,10,10,10,
  149400. 10,10,10,10,10, 9, 9, 9,10, 9,10, 9,10,10,10,10,
  149401. 10,10,10,10,10,10,10,10,10,10, 9, 9, 9,10, 9,10,
  149402. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10, 9,
  149403. 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,10,10,10,
  149404. 10,10,10,10, 9, 9, 9,10,10,10,10,10,10,10,10,10,
  149405. 10,10,10,10,10,10,10,10,10,
  149406. };
  149407. static float _vq_quantthresh__44u9_p8_1[] = {
  149408. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  149409. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  149410. 6.5, 7.5, 8.5, 9.5,
  149411. };
  149412. static long _vq_quantmap__44u9_p8_1[] = {
  149413. 19, 17, 15, 13, 11, 9, 7, 5,
  149414. 3, 1, 0, 2, 4, 6, 8, 10,
  149415. 12, 14, 16, 18, 20,
  149416. };
  149417. static encode_aux_threshmatch _vq_auxt__44u9_p8_1 = {
  149418. _vq_quantthresh__44u9_p8_1,
  149419. _vq_quantmap__44u9_p8_1,
  149420. 21,
  149421. 21
  149422. };
  149423. static static_codebook _44u9_p8_1 = {
  149424. 2, 441,
  149425. _vq_lengthlist__44u9_p8_1,
  149426. 1, -529268736, 1611661312, 5, 0,
  149427. _vq_quantlist__44u9_p8_1,
  149428. NULL,
  149429. &_vq_auxt__44u9_p8_1,
  149430. NULL,
  149431. 0
  149432. };
  149433. static long _vq_quantlist__44u9_p9_0[] = {
  149434. 7,
  149435. 6,
  149436. 8,
  149437. 5,
  149438. 9,
  149439. 4,
  149440. 10,
  149441. 3,
  149442. 11,
  149443. 2,
  149444. 12,
  149445. 1,
  149446. 13,
  149447. 0,
  149448. 14,
  149449. };
  149450. static long _vq_lengthlist__44u9_p9_0[] = {
  149451. 1, 3, 3,11,11,11,11,11,11,11,11,11,11,11,11, 4,
  149452. 10,11,11,11,11,11,11,11,11,11,11,11,11,11, 4,10,
  149453. 10,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  149454. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  149455. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  149456. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  149457. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  149458. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  149459. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  149460. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  149461. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  149462. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  149463. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  149464. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  149465. 10,
  149466. };
  149467. static float _vq_quantthresh__44u9_p9_0[] = {
  149468. -6051.5, -5120.5, -4189.5, -3258.5, -2327.5, -1396.5, -465.5, 465.5,
  149469. 1396.5, 2327.5, 3258.5, 4189.5, 5120.5, 6051.5,
  149470. };
  149471. static long _vq_quantmap__44u9_p9_0[] = {
  149472. 13, 11, 9, 7, 5, 3, 1, 0,
  149473. 2, 4, 6, 8, 10, 12, 14,
  149474. };
  149475. static encode_aux_threshmatch _vq_auxt__44u9_p9_0 = {
  149476. _vq_quantthresh__44u9_p9_0,
  149477. _vq_quantmap__44u9_p9_0,
  149478. 15,
  149479. 15
  149480. };
  149481. static static_codebook _44u9_p9_0 = {
  149482. 2, 225,
  149483. _vq_lengthlist__44u9_p9_0,
  149484. 1, -510036736, 1631393792, 4, 0,
  149485. _vq_quantlist__44u9_p9_0,
  149486. NULL,
  149487. &_vq_auxt__44u9_p9_0,
  149488. NULL,
  149489. 0
  149490. };
  149491. static long _vq_quantlist__44u9_p9_1[] = {
  149492. 9,
  149493. 8,
  149494. 10,
  149495. 7,
  149496. 11,
  149497. 6,
  149498. 12,
  149499. 5,
  149500. 13,
  149501. 4,
  149502. 14,
  149503. 3,
  149504. 15,
  149505. 2,
  149506. 16,
  149507. 1,
  149508. 17,
  149509. 0,
  149510. 18,
  149511. };
  149512. static long _vq_lengthlist__44u9_p9_1[] = {
  149513. 1, 4, 4, 7, 7, 8, 7, 8, 7, 9, 8,10, 9,10,10,11,
  149514. 11,12,12, 4, 7, 6, 9, 9,10, 9, 9, 8,10,10,11,10,
  149515. 12,10,13,12,13,12, 4, 6, 6, 9, 9, 9, 9, 9, 9,10,
  149516. 10,11,11,11,12,12,12,12,12, 7, 9, 8,11,10,10,10,
  149517. 11,10,11,11,12,12,13,12,13,13,13,13, 7, 8, 9,10,
  149518. 10,11,11,10,10,11,11,11,12,13,13,13,13,14,14, 8,
  149519. 9, 9,11,11,12,11,12,12,13,12,12,13,13,14,15,14,
  149520. 14,14, 8, 9, 9,10,11,11,11,12,12,13,12,13,13,14,
  149521. 14,14,15,14,16, 8, 9, 9,11,10,12,12,12,12,15,13,
  149522. 13,13,17,14,15,15,15,14, 8, 9, 9,10,11,11,12,13,
  149523. 12,13,13,13,14,15,14,14,14,16,15, 9,11,10,12,12,
  149524. 13,13,13,13,14,14,16,15,14,14,14,15,15,17, 9,10,
  149525. 10,11,11,13,13,13,14,14,13,15,14,15,14,15,16,15,
  149526. 16,10,11,11,12,12,13,14,15,14,15,14,14,15,17,16,
  149527. 15,15,17,17,10,12,11,13,12,14,14,13,14,15,15,15,
  149528. 15,16,17,17,15,17,16,11,12,12,14,13,15,14,15,16,
  149529. 17,15,17,15,17,15,15,16,17,15,11,11,12,14,14,14,
  149530. 14,14,15,15,16,15,17,17,17,16,17,16,15,12,12,13,
  149531. 14,14,14,15,14,15,15,16,16,17,16,17,15,17,17,16,
  149532. 12,14,12,14,14,15,15,15,14,14,16,16,16,15,16,16,
  149533. 15,17,15,12,13,13,14,15,14,15,17,15,17,16,17,17,
  149534. 17,16,17,16,17,17,12,13,13,14,16,15,15,15,16,15,
  149535. 17,17,15,17,15,17,16,16,17,
  149536. };
  149537. static float _vq_quantthresh__44u9_p9_1[] = {
  149538. -416.5, -367.5, -318.5, -269.5, -220.5, -171.5, -122.5, -73.5,
  149539. -24.5, 24.5, 73.5, 122.5, 171.5, 220.5, 269.5, 318.5,
  149540. 367.5, 416.5,
  149541. };
  149542. static long _vq_quantmap__44u9_p9_1[] = {
  149543. 17, 15, 13, 11, 9, 7, 5, 3,
  149544. 1, 0, 2, 4, 6, 8, 10, 12,
  149545. 14, 16, 18,
  149546. };
  149547. static encode_aux_threshmatch _vq_auxt__44u9_p9_1 = {
  149548. _vq_quantthresh__44u9_p9_1,
  149549. _vq_quantmap__44u9_p9_1,
  149550. 19,
  149551. 19
  149552. };
  149553. static static_codebook _44u9_p9_1 = {
  149554. 2, 361,
  149555. _vq_lengthlist__44u9_p9_1,
  149556. 1, -518287360, 1622704128, 5, 0,
  149557. _vq_quantlist__44u9_p9_1,
  149558. NULL,
  149559. &_vq_auxt__44u9_p9_1,
  149560. NULL,
  149561. 0
  149562. };
  149563. static long _vq_quantlist__44u9_p9_2[] = {
  149564. 24,
  149565. 23,
  149566. 25,
  149567. 22,
  149568. 26,
  149569. 21,
  149570. 27,
  149571. 20,
  149572. 28,
  149573. 19,
  149574. 29,
  149575. 18,
  149576. 30,
  149577. 17,
  149578. 31,
  149579. 16,
  149580. 32,
  149581. 15,
  149582. 33,
  149583. 14,
  149584. 34,
  149585. 13,
  149586. 35,
  149587. 12,
  149588. 36,
  149589. 11,
  149590. 37,
  149591. 10,
  149592. 38,
  149593. 9,
  149594. 39,
  149595. 8,
  149596. 40,
  149597. 7,
  149598. 41,
  149599. 6,
  149600. 42,
  149601. 5,
  149602. 43,
  149603. 4,
  149604. 44,
  149605. 3,
  149606. 45,
  149607. 2,
  149608. 46,
  149609. 1,
  149610. 47,
  149611. 0,
  149612. 48,
  149613. };
  149614. static long _vq_lengthlist__44u9_p9_2[] = {
  149615. 2, 4, 4, 5, 4, 5, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6,
  149616. 6, 6, 6, 7, 6, 7, 6, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  149617. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  149618. 7,
  149619. };
  149620. static float _vq_quantthresh__44u9_p9_2[] = {
  149621. -23.5, -22.5, -21.5, -20.5, -19.5, -18.5, -17.5, -16.5,
  149622. -15.5, -14.5, -13.5, -12.5, -11.5, -10.5, -9.5, -8.5,
  149623. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  149624. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  149625. 8.5, 9.5, 10.5, 11.5, 12.5, 13.5, 14.5, 15.5,
  149626. 16.5, 17.5, 18.5, 19.5, 20.5, 21.5, 22.5, 23.5,
  149627. };
  149628. static long _vq_quantmap__44u9_p9_2[] = {
  149629. 47, 45, 43, 41, 39, 37, 35, 33,
  149630. 31, 29, 27, 25, 23, 21, 19, 17,
  149631. 15, 13, 11, 9, 7, 5, 3, 1,
  149632. 0, 2, 4, 6, 8, 10, 12, 14,
  149633. 16, 18, 20, 22, 24, 26, 28, 30,
  149634. 32, 34, 36, 38, 40, 42, 44, 46,
  149635. 48,
  149636. };
  149637. static encode_aux_threshmatch _vq_auxt__44u9_p9_2 = {
  149638. _vq_quantthresh__44u9_p9_2,
  149639. _vq_quantmap__44u9_p9_2,
  149640. 49,
  149641. 49
  149642. };
  149643. static static_codebook _44u9_p9_2 = {
  149644. 1, 49,
  149645. _vq_lengthlist__44u9_p9_2,
  149646. 1, -526909440, 1611661312, 6, 0,
  149647. _vq_quantlist__44u9_p9_2,
  149648. NULL,
  149649. &_vq_auxt__44u9_p9_2,
  149650. NULL,
  149651. 0
  149652. };
  149653. static long _huff_lengthlist__44un1__long[] = {
  149654. 5, 6,12, 9,14, 9, 9,19, 6, 1, 5, 5, 8, 7, 9,19,
  149655. 12, 4, 4, 7, 7, 9,11,18, 9, 5, 6, 6, 8, 7, 8,17,
  149656. 14, 8, 7, 8, 8,10,12,18, 9, 6, 8, 6, 8, 6, 8,18,
  149657. 9, 8,11, 8,11, 7, 5,15,16,18,18,18,17,15,11,18,
  149658. };
  149659. static static_codebook _huff_book__44un1__long = {
  149660. 2, 64,
  149661. _huff_lengthlist__44un1__long,
  149662. 0, 0, 0, 0, 0,
  149663. NULL,
  149664. NULL,
  149665. NULL,
  149666. NULL,
  149667. 0
  149668. };
  149669. static long _vq_quantlist__44un1__p1_0[] = {
  149670. 1,
  149671. 0,
  149672. 2,
  149673. };
  149674. static long _vq_lengthlist__44un1__p1_0[] = {
  149675. 1, 4, 4, 5, 8, 7, 5, 7, 8, 5, 8, 8, 8,10,11, 8,
  149676. 10,11, 5, 8, 8, 8,11,10, 8,11,10, 4, 9, 9, 8,11,
  149677. 11, 8,11,11, 8,12,11,10,12,14,11,13,13, 7,11,11,
  149678. 10,13,11,11,13,14, 4, 8, 9, 8,11,11, 8,11,12, 7,
  149679. 11,11,11,14,13,10,11,13, 8,11,12,11,13,13,10,14,
  149680. 12,
  149681. };
  149682. static float _vq_quantthresh__44un1__p1_0[] = {
  149683. -0.5, 0.5,
  149684. };
  149685. static long _vq_quantmap__44un1__p1_0[] = {
  149686. 1, 0, 2,
  149687. };
  149688. static encode_aux_threshmatch _vq_auxt__44un1__p1_0 = {
  149689. _vq_quantthresh__44un1__p1_0,
  149690. _vq_quantmap__44un1__p1_0,
  149691. 3,
  149692. 3
  149693. };
  149694. static static_codebook _44un1__p1_0 = {
  149695. 4, 81,
  149696. _vq_lengthlist__44un1__p1_0,
  149697. 1, -535822336, 1611661312, 2, 0,
  149698. _vq_quantlist__44un1__p1_0,
  149699. NULL,
  149700. &_vq_auxt__44un1__p1_0,
  149701. NULL,
  149702. 0
  149703. };
  149704. static long _vq_quantlist__44un1__p2_0[] = {
  149705. 1,
  149706. 0,
  149707. 2,
  149708. };
  149709. static long _vq_lengthlist__44un1__p2_0[] = {
  149710. 2, 4, 4, 5, 6, 6, 5, 6, 6, 5, 7, 7, 7, 8, 8, 6,
  149711. 7, 9, 5, 7, 7, 6, 8, 7, 7, 9, 8, 4, 7, 7, 7, 9,
  149712. 8, 7, 8, 8, 7, 9, 8, 8, 8,10, 9,10,10, 6, 8, 8,
  149713. 7,10, 8, 9,10,10, 5, 7, 7, 7, 8, 8, 7, 8, 9, 6,
  149714. 8, 8, 9,10,10, 7, 8,10, 6, 8, 9, 9,10,10, 8,10,
  149715. 8,
  149716. };
  149717. static float _vq_quantthresh__44un1__p2_0[] = {
  149718. -0.5, 0.5,
  149719. };
  149720. static long _vq_quantmap__44un1__p2_0[] = {
  149721. 1, 0, 2,
  149722. };
  149723. static encode_aux_threshmatch _vq_auxt__44un1__p2_0 = {
  149724. _vq_quantthresh__44un1__p2_0,
  149725. _vq_quantmap__44un1__p2_0,
  149726. 3,
  149727. 3
  149728. };
  149729. static static_codebook _44un1__p2_0 = {
  149730. 4, 81,
  149731. _vq_lengthlist__44un1__p2_0,
  149732. 1, -535822336, 1611661312, 2, 0,
  149733. _vq_quantlist__44un1__p2_0,
  149734. NULL,
  149735. &_vq_auxt__44un1__p2_0,
  149736. NULL,
  149737. 0
  149738. };
  149739. static long _vq_quantlist__44un1__p3_0[] = {
  149740. 2,
  149741. 1,
  149742. 3,
  149743. 0,
  149744. 4,
  149745. };
  149746. static long _vq_lengthlist__44un1__p3_0[] = {
  149747. 1, 5, 5, 8, 8, 5, 8, 7, 9, 9, 5, 7, 8, 9, 9, 9,
  149748. 10, 9,12,12, 9, 9,10,11,12, 6, 8, 8,10,10, 8,10,
  149749. 10,11,11, 8, 9,10,11,11,10,11,11,13,13,10,11,11,
  149750. 12,13, 6, 8, 8,10,10, 8,10, 9,11,11, 8,10,10,11,
  149751. 11,10,11,11,13,12,10,11,11,13,12, 9,11,11,15,13,
  149752. 10,12,11,15,13,10,11,11,15,14,12,14,13,16,15,12,
  149753. 13,13,17,16, 9,11,11,13,15,10,11,12,14,15,10,11,
  149754. 12,14,15,12,13,13,15,16,12,13,13,16,16, 5, 8, 8,
  149755. 11,11, 8,10,10,12,12, 8,10,10,12,12,11,12,12,14,
  149756. 14,11,12,12,14,14, 8,11,10,13,12,10,11,12,12,13,
  149757. 10,12,12,13,13,12,12,13,13,15,11,12,13,15,14, 7,
  149758. 10,10,12,12, 9,12,11,13,12,10,12,12,13,14,12,13,
  149759. 12,15,13,11,13,12,14,15,10,12,12,16,14,11,12,12,
  149760. 16,15,11,13,12,17,16,13,13,15,15,17,13,15,15,20,
  149761. 17,10,12,12,14,16,11,12,12,15,15,11,13,13,15,18,
  149762. 13,14,13,15,15,13,15,14,16,16, 5, 8, 8,11,11, 8,
  149763. 10,10,12,12, 8,10,10,12,12,11,12,12,14,14,11,12,
  149764. 12,14,15, 7,10,10,13,12,10,12,12,14,13, 9,10,12,
  149765. 12,13,11,13,13,15,15,11,12,13,13,15, 8,10,10,12,
  149766. 13,10,12,12,13,13,10,12,11,13,13,11,13,12,15,15,
  149767. 12,13,12,15,13,10,12,12,16,14,11,12,12,16,15,10,
  149768. 12,12,16,14,14,15,14,18,16,13,13,14,15,16,10,12,
  149769. 12,14,16,11,13,13,16,16,11,13,12,14,16,13,15,15,
  149770. 18,18,13,15,13,16,14, 8,11,11,16,16,10,13,13,17,
  149771. 16,10,12,12,16,15,14,16,15,20,17,13,14,14,17,17,
  149772. 9,12,12,16,16,11,13,14,16,17,11,13,13,16,16,15,
  149773. 15,19,18, 0,14,15,15,18,18, 9,12,12,17,16,11,13,
  149774. 12,17,16,11,12,13,15,17,15,16,15, 0,19,14,15,14,
  149775. 19,18,12,14,14, 0,16,13,14,14,19,18,13,15,16,17,
  149776. 16,15,15,17,18, 0,14,16,16,19, 0,12,14,14,16,18,
  149777. 13,15,13,17,18,13,15,14,17,18,15,18,14,18,18,16,
  149778. 17,16, 0,17, 8,11,11,15,15,10,12,12,16,16,10,13,
  149779. 13,16,16,13,15,14,17,17,14,15,17,17,18, 9,12,12,
  149780. 16,15,11,13,13,16,16,11,12,13,17,17,14,14,15,17,
  149781. 17,14,15,16, 0,18, 9,12,12,16,17,11,13,13,16,17,
  149782. 11,14,13,18,17,14,16,14,17,17,15,17,17,18,18,12,
  149783. 14,14, 0,16,13,15,15,19, 0,12,13,15, 0, 0,14,17,
  149784. 16,19, 0,16,15,18,18, 0,12,14,14,17, 0,13,14,14,
  149785. 17, 0,13,15,14, 0,18,15,16,16, 0,18,15,18,15, 0,
  149786. 17,
  149787. };
  149788. static float _vq_quantthresh__44un1__p3_0[] = {
  149789. -1.5, -0.5, 0.5, 1.5,
  149790. };
  149791. static long _vq_quantmap__44un1__p3_0[] = {
  149792. 3, 1, 0, 2, 4,
  149793. };
  149794. static encode_aux_threshmatch _vq_auxt__44un1__p3_0 = {
  149795. _vq_quantthresh__44un1__p3_0,
  149796. _vq_quantmap__44un1__p3_0,
  149797. 5,
  149798. 5
  149799. };
  149800. static static_codebook _44un1__p3_0 = {
  149801. 4, 625,
  149802. _vq_lengthlist__44un1__p3_0,
  149803. 1, -533725184, 1611661312, 3, 0,
  149804. _vq_quantlist__44un1__p3_0,
  149805. NULL,
  149806. &_vq_auxt__44un1__p3_0,
  149807. NULL,
  149808. 0
  149809. };
  149810. static long _vq_quantlist__44un1__p4_0[] = {
  149811. 2,
  149812. 1,
  149813. 3,
  149814. 0,
  149815. 4,
  149816. };
  149817. static long _vq_lengthlist__44un1__p4_0[] = {
  149818. 3, 5, 5, 9, 9, 5, 6, 6,10, 9, 5, 6, 6, 9,10,10,
  149819. 10,10,12,11, 9,10,10,12,12, 5, 7, 7,10,10, 7, 7,
  149820. 8,10,11, 7, 7, 8,10,11,10,10,11,11,13,10,10,11,
  149821. 11,13, 6, 7, 7,10,10, 7, 8, 7,11,10, 7, 8, 7,10,
  149822. 10,10,11, 9,13,11,10,11,10,13,11,10,10,10,14,13,
  149823. 10,11,11,14,13,10,10,11,13,14,12,12,13,15,15,12,
  149824. 12,13,13,14,10,10,10,12,13,10,11,10,13,13,10,11,
  149825. 11,13,13,12,13,12,14,13,12,13,13,14,13, 5, 7, 7,
  149826. 10,10, 7, 8, 8,11,10, 7, 8, 8,10,10,11,11,11,13,
  149827. 13,10,11,11,12,12, 7, 8, 8,11,11, 7, 8, 9,10,12,
  149828. 8, 9, 9,11,11,11,10,12,11,14,11,11,12,13,13, 6,
  149829. 8, 8,10,11, 7, 9, 7,12,10, 8, 9,10,11,12,10,12,
  149830. 10,14,11,11,12,11,13,13,10,11,11,14,14,10,10,11,
  149831. 13,14,11,12,12,15,13,12,11,14,12,16,12,13,14,15,
  149832. 16,10,10,11,13,14,10,11,10,14,12,11,12,12,13,14,
  149833. 12,13,11,15,12,14,14,14,15,15, 5, 7, 7,10,10, 7,
  149834. 8, 8,10,10, 7, 8, 8,10,11,10,11,10,12,12,10,11,
  149835. 11,12,13, 6, 8, 8,11,11, 8, 9, 9,12,11, 7, 7, 9,
  149836. 10,12,11,11,11,12,13,11,10,12,11,15, 7, 8, 8,11,
  149837. 11, 8, 9, 9,11,11, 7, 9, 8,12,10,11,12,11,13,12,
  149838. 11,12,10,15,11,10,11,10,14,12,11,12,11,14,13,10,
  149839. 10,11,13,14,13,13,13,17,15,12,11,14,12,15,10,10,
  149840. 11,13,14,11,12,12,14,14,10,11,10,14,13,13,14,13,
  149841. 16,17,12,14,11,16,12, 9,10,10,14,13,10,11,10,14,
  149842. 14,10,11,11,13,13,13,14,14,16,15,12,13,13,14,14,
  149843. 9,11,10,14,13,10,10,12,13,14,11,12,11,14,13,13,
  149844. 14,14,14,15,13,14,14,15,15, 9,10,11,13,14,10,11,
  149845. 10,15,13,11,11,12,12,15,13,14,12,15,14,13,13,14,
  149846. 14,15,12,13,12,16,14,11,11,12,15,14,13,15,13,16,
  149847. 14,13,12,15,12,17,15,16,15,16,16,12,12,13,13,15,
  149848. 11,13,11,15,14,13,13,14,15,17,13,14,12, 0,13,14,
  149849. 15,14,15, 0, 9,10,10,13,13,10,11,11,13,13,10,11,
  149850. 11,13,13,12,13,12,14,14,13,14,14,15,17, 9,10,10,
  149851. 13,13,11,12,11,15,12,10,10,11,13,16,13,14,13,15,
  149852. 14,13,13,14,15,16,10,10,11,13,14,11,11,12,13,14,
  149853. 10,12,11,14,14,13,13,13,14,15,13,15,13,16,15,12,
  149854. 13,12,15,13,12,15,13,15,15,11,11,13,14,15,15,15,
  149855. 15,15,17,13,12,14,13,17,12,12,14,14,15,13,13,14,
  149856. 14,16,11,13,11,16,15,14,16,16,17, 0,14,13,11,16,
  149857. 12,
  149858. };
  149859. static float _vq_quantthresh__44un1__p4_0[] = {
  149860. -1.5, -0.5, 0.5, 1.5,
  149861. };
  149862. static long _vq_quantmap__44un1__p4_0[] = {
  149863. 3, 1, 0, 2, 4,
  149864. };
  149865. static encode_aux_threshmatch _vq_auxt__44un1__p4_0 = {
  149866. _vq_quantthresh__44un1__p4_0,
  149867. _vq_quantmap__44un1__p4_0,
  149868. 5,
  149869. 5
  149870. };
  149871. static static_codebook _44un1__p4_0 = {
  149872. 4, 625,
  149873. _vq_lengthlist__44un1__p4_0,
  149874. 1, -533725184, 1611661312, 3, 0,
  149875. _vq_quantlist__44un1__p4_0,
  149876. NULL,
  149877. &_vq_auxt__44un1__p4_0,
  149878. NULL,
  149879. 0
  149880. };
  149881. static long _vq_quantlist__44un1__p5_0[] = {
  149882. 4,
  149883. 3,
  149884. 5,
  149885. 2,
  149886. 6,
  149887. 1,
  149888. 7,
  149889. 0,
  149890. 8,
  149891. };
  149892. static long _vq_lengthlist__44un1__p5_0[] = {
  149893. 1, 4, 4, 7, 7, 8, 8, 9, 9, 4, 6, 5, 8, 7, 8, 8,
  149894. 10, 9, 4, 6, 6, 8, 8, 8, 8,10,10, 7, 8, 7, 9, 9,
  149895. 9, 9,11,10, 7, 8, 8, 9, 9, 9, 9,10,11, 8, 8, 8,
  149896. 9, 9,10,10,11,11, 8, 8, 8, 9, 9,10,10,11,11, 9,
  149897. 10,10,11,10,11,11,12,12, 9,10,10,10,11,11,11,12,
  149898. 12,
  149899. };
  149900. static float _vq_quantthresh__44un1__p5_0[] = {
  149901. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  149902. };
  149903. static long _vq_quantmap__44un1__p5_0[] = {
  149904. 7, 5, 3, 1, 0, 2, 4, 6,
  149905. 8,
  149906. };
  149907. static encode_aux_threshmatch _vq_auxt__44un1__p5_0 = {
  149908. _vq_quantthresh__44un1__p5_0,
  149909. _vq_quantmap__44un1__p5_0,
  149910. 9,
  149911. 9
  149912. };
  149913. static static_codebook _44un1__p5_0 = {
  149914. 2, 81,
  149915. _vq_lengthlist__44un1__p5_0,
  149916. 1, -531628032, 1611661312, 4, 0,
  149917. _vq_quantlist__44un1__p5_0,
  149918. NULL,
  149919. &_vq_auxt__44un1__p5_0,
  149920. NULL,
  149921. 0
  149922. };
  149923. static long _vq_quantlist__44un1__p6_0[] = {
  149924. 6,
  149925. 5,
  149926. 7,
  149927. 4,
  149928. 8,
  149929. 3,
  149930. 9,
  149931. 2,
  149932. 10,
  149933. 1,
  149934. 11,
  149935. 0,
  149936. 12,
  149937. };
  149938. static long _vq_lengthlist__44un1__p6_0[] = {
  149939. 1, 4, 4, 6, 6, 8, 8,10,10,11,11,15,15, 4, 5, 5,
  149940. 8, 8, 9, 9,11,11,12,12,16,16, 4, 5, 6, 8, 8, 9,
  149941. 9,11,11,12,12,14,14, 7, 8, 8, 9, 9,10,10,11,12,
  149942. 13,13,16,17, 7, 8, 8, 9, 9,10,10,12,12,12,13,15,
  149943. 15, 9,10,10,10,10,11,11,12,12,13,13,15,16, 9, 9,
  149944. 9,10,10,11,11,13,12,13,13,17,17,10,11,11,11,12,
  149945. 12,12,13,13,14,15, 0,18,10,11,11,12,12,12,13,14,
  149946. 13,14,14,17,16,11,12,12,13,13,14,14,14,14,15,16,
  149947. 17,16,11,12,12,13,13,14,14,14,14,15,15,17,17,14,
  149948. 15,15,16,16,16,17,17,16, 0,17, 0,18,14,15,15,16,
  149949. 16, 0,15,18,18, 0,16, 0, 0,
  149950. };
  149951. static float _vq_quantthresh__44un1__p6_0[] = {
  149952. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  149953. 12.5, 17.5, 22.5, 27.5,
  149954. };
  149955. static long _vq_quantmap__44un1__p6_0[] = {
  149956. 11, 9, 7, 5, 3, 1, 0, 2,
  149957. 4, 6, 8, 10, 12,
  149958. };
  149959. static encode_aux_threshmatch _vq_auxt__44un1__p6_0 = {
  149960. _vq_quantthresh__44un1__p6_0,
  149961. _vq_quantmap__44un1__p6_0,
  149962. 13,
  149963. 13
  149964. };
  149965. static static_codebook _44un1__p6_0 = {
  149966. 2, 169,
  149967. _vq_lengthlist__44un1__p6_0,
  149968. 1, -526516224, 1616117760, 4, 0,
  149969. _vq_quantlist__44un1__p6_0,
  149970. NULL,
  149971. &_vq_auxt__44un1__p6_0,
  149972. NULL,
  149973. 0
  149974. };
  149975. static long _vq_quantlist__44un1__p6_1[] = {
  149976. 2,
  149977. 1,
  149978. 3,
  149979. 0,
  149980. 4,
  149981. };
  149982. static long _vq_lengthlist__44un1__p6_1[] = {
  149983. 2, 4, 4, 5, 5, 4, 5, 5, 5, 5, 4, 5, 5, 6, 5, 5,
  149984. 6, 5, 6, 6, 5, 6, 6, 6, 6,
  149985. };
  149986. static float _vq_quantthresh__44un1__p6_1[] = {
  149987. -1.5, -0.5, 0.5, 1.5,
  149988. };
  149989. static long _vq_quantmap__44un1__p6_1[] = {
  149990. 3, 1, 0, 2, 4,
  149991. };
  149992. static encode_aux_threshmatch _vq_auxt__44un1__p6_1 = {
  149993. _vq_quantthresh__44un1__p6_1,
  149994. _vq_quantmap__44un1__p6_1,
  149995. 5,
  149996. 5
  149997. };
  149998. static static_codebook _44un1__p6_1 = {
  149999. 2, 25,
  150000. _vq_lengthlist__44un1__p6_1,
  150001. 1, -533725184, 1611661312, 3, 0,
  150002. _vq_quantlist__44un1__p6_1,
  150003. NULL,
  150004. &_vq_auxt__44un1__p6_1,
  150005. NULL,
  150006. 0
  150007. };
  150008. static long _vq_quantlist__44un1__p7_0[] = {
  150009. 2,
  150010. 1,
  150011. 3,
  150012. 0,
  150013. 4,
  150014. };
  150015. static long _vq_lengthlist__44un1__p7_0[] = {
  150016. 1, 5, 3,11,11,11,11,11,11,11, 8,11,11,11,11,11,
  150017. 11,11,11,11,11,11,11,11,11,10,11,11,11,11,11,11,
  150018. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  150019. 11,11,10,11,11,11,11,11,11,11,11,11,11,11,11,11,
  150020. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  150021. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  150022. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  150023. 11,11,11,11,11,11,11,11,11,11,11,11,11, 8,11,11,
  150024. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  150025. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  150026. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,10,
  150027. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  150028. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  150029. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  150030. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  150031. 11,11,11,11,11,11,11,11,11,11, 7,11,11,11,11,11,
  150032. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  150033. 11,11,11,10,11,11,11,11,11,11,11,11,11,11,11,11,
  150034. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  150035. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  150036. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  150037. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  150038. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  150039. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  150040. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  150041. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  150042. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  150043. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  150044. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  150045. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  150046. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  150047. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  150048. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  150049. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  150050. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  150051. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  150052. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  150053. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  150054. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  150055. 10,
  150056. };
  150057. static float _vq_quantthresh__44un1__p7_0[] = {
  150058. -253.5, -84.5, 84.5, 253.5,
  150059. };
  150060. static long _vq_quantmap__44un1__p7_0[] = {
  150061. 3, 1, 0, 2, 4,
  150062. };
  150063. static encode_aux_threshmatch _vq_auxt__44un1__p7_0 = {
  150064. _vq_quantthresh__44un1__p7_0,
  150065. _vq_quantmap__44un1__p7_0,
  150066. 5,
  150067. 5
  150068. };
  150069. static static_codebook _44un1__p7_0 = {
  150070. 4, 625,
  150071. _vq_lengthlist__44un1__p7_0,
  150072. 1, -518709248, 1626677248, 3, 0,
  150073. _vq_quantlist__44un1__p7_0,
  150074. NULL,
  150075. &_vq_auxt__44un1__p7_0,
  150076. NULL,
  150077. 0
  150078. };
  150079. static long _vq_quantlist__44un1__p7_1[] = {
  150080. 6,
  150081. 5,
  150082. 7,
  150083. 4,
  150084. 8,
  150085. 3,
  150086. 9,
  150087. 2,
  150088. 10,
  150089. 1,
  150090. 11,
  150091. 0,
  150092. 12,
  150093. };
  150094. static long _vq_lengthlist__44un1__p7_1[] = {
  150095. 1, 4, 4, 6, 6, 6, 6, 9, 8, 9, 8, 8, 8, 5, 7, 7,
  150096. 7, 7, 8, 8, 8,10, 8,10, 8, 9, 5, 7, 7, 8, 7, 7,
  150097. 8,10,10,11,10,12,11, 7, 8, 8, 9, 9, 9,10,11,11,
  150098. 11,11,11,11, 7, 8, 8, 8, 9, 9, 9,10,10,10,11,11,
  150099. 12, 7, 8, 8, 9, 9,10,11,11,12,11,12,11,11, 7, 8,
  150100. 8, 9, 9,10,10,11,11,11,12,12,11, 8,10,10,10,10,
  150101. 11,11,14,11,12,12,12,13, 9,10,10,10,10,12,11,14,
  150102. 11,14,11,12,13,10,11,11,11,11,13,11,14,14,13,13,
  150103. 13,14,11,11,11,12,11,12,12,12,13,14,14,13,14,12,
  150104. 11,12,12,12,12,13,13,13,14,13,14,14,11,12,12,14,
  150105. 12,13,13,12,13,13,14,14,14,
  150106. };
  150107. static float _vq_quantthresh__44un1__p7_1[] = {
  150108. -71.5, -58.5, -45.5, -32.5, -19.5, -6.5, 6.5, 19.5,
  150109. 32.5, 45.5, 58.5, 71.5,
  150110. };
  150111. static long _vq_quantmap__44un1__p7_1[] = {
  150112. 11, 9, 7, 5, 3, 1, 0, 2,
  150113. 4, 6, 8, 10, 12,
  150114. };
  150115. static encode_aux_threshmatch _vq_auxt__44un1__p7_1 = {
  150116. _vq_quantthresh__44un1__p7_1,
  150117. _vq_quantmap__44un1__p7_1,
  150118. 13,
  150119. 13
  150120. };
  150121. static static_codebook _44un1__p7_1 = {
  150122. 2, 169,
  150123. _vq_lengthlist__44un1__p7_1,
  150124. 1, -523010048, 1618608128, 4, 0,
  150125. _vq_quantlist__44un1__p7_1,
  150126. NULL,
  150127. &_vq_auxt__44un1__p7_1,
  150128. NULL,
  150129. 0
  150130. };
  150131. static long _vq_quantlist__44un1__p7_2[] = {
  150132. 6,
  150133. 5,
  150134. 7,
  150135. 4,
  150136. 8,
  150137. 3,
  150138. 9,
  150139. 2,
  150140. 10,
  150141. 1,
  150142. 11,
  150143. 0,
  150144. 12,
  150145. };
  150146. static long _vq_lengthlist__44un1__p7_2[] = {
  150147. 3, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9, 9, 8, 4, 5, 5,
  150148. 6, 6, 8, 8, 9, 8, 9, 9, 9, 9, 4, 5, 5, 7, 6, 8,
  150149. 8, 8, 8, 9, 8, 9, 8, 6, 7, 7, 7, 8, 8, 8, 9, 9,
  150150. 9, 9, 9, 9, 6, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9, 9,
  150151. 9, 7, 8, 8, 8, 8, 9, 8, 9, 9,10, 9, 9,10, 7, 8,
  150152. 8, 8, 8, 9, 9, 9, 9, 9, 9,10,10, 8, 9, 9, 9, 9,
  150153. 9, 9, 9, 9,10,10, 9,10, 8, 9, 9, 9, 9, 9, 9, 9,
  150154. 9, 9, 9,10,10, 9, 9, 9,10, 9, 9,10, 9, 9,10,10,
  150155. 10,10, 9, 9, 9, 9, 9, 9, 9,10, 9,10,10,10,10, 9,
  150156. 9, 9,10, 9, 9,10,10, 9,10,10,10,10, 9, 9, 9,10,
  150157. 9, 9, 9,10,10,10,10,10,10,
  150158. };
  150159. static float _vq_quantthresh__44un1__p7_2[] = {
  150160. -5.5, -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5,
  150161. 2.5, 3.5, 4.5, 5.5,
  150162. };
  150163. static long _vq_quantmap__44un1__p7_2[] = {
  150164. 11, 9, 7, 5, 3, 1, 0, 2,
  150165. 4, 6, 8, 10, 12,
  150166. };
  150167. static encode_aux_threshmatch _vq_auxt__44un1__p7_2 = {
  150168. _vq_quantthresh__44un1__p7_2,
  150169. _vq_quantmap__44un1__p7_2,
  150170. 13,
  150171. 13
  150172. };
  150173. static static_codebook _44un1__p7_2 = {
  150174. 2, 169,
  150175. _vq_lengthlist__44un1__p7_2,
  150176. 1, -531103744, 1611661312, 4, 0,
  150177. _vq_quantlist__44un1__p7_2,
  150178. NULL,
  150179. &_vq_auxt__44un1__p7_2,
  150180. NULL,
  150181. 0
  150182. };
  150183. static long _huff_lengthlist__44un1__short[] = {
  150184. 12,12,14,12,14,14,14,14,12, 6, 6, 8, 9, 9,11,14,
  150185. 12, 4, 2, 6, 6, 7,11,14,13, 6, 5, 7, 8, 9,11,14,
  150186. 13, 8, 5, 8, 6, 8,12,14,12, 7, 7, 8, 8, 8,10,14,
  150187. 12, 6, 3, 4, 4, 4, 7,14,11, 7, 4, 6, 6, 6, 8,14,
  150188. };
  150189. static static_codebook _huff_book__44un1__short = {
  150190. 2, 64,
  150191. _huff_lengthlist__44un1__short,
  150192. 0, 0, 0, 0, 0,
  150193. NULL,
  150194. NULL,
  150195. NULL,
  150196. NULL,
  150197. 0
  150198. };
  150199. /*** End of inlined file: res_books_uncoupled.h ***/
  150200. /***** residue backends *********************************************/
  150201. static vorbis_info_residue0 _residue_44_low_un={
  150202. 0,-1, -1, 8,-1,
  150203. {0},
  150204. {-1},
  150205. { .5, 1.5, 1.5, 2.5, 2.5, 4.5, 28.5},
  150206. { -1, 25, -1, 45, -1, -1, -1}
  150207. };
  150208. static vorbis_info_residue0 _residue_44_mid_un={
  150209. 0,-1, -1, 10,-1,
  150210. /* 0 1 2 3 4 5 6 7 8 9 */
  150211. {0},
  150212. {-1},
  150213. { .5, 1.5, 1.5, 2.5, 2.5, 4.5, 4.5, 16.5, 60.5},
  150214. { -1, 30, -1, 50, -1, 80, -1, -1, -1}
  150215. };
  150216. static vorbis_info_residue0 _residue_44_hi_un={
  150217. 0,-1, -1, 10,-1,
  150218. /* 0 1 2 3 4 5 6 7 8 9 */
  150219. {0},
  150220. {-1},
  150221. { .5, 1.5, 2.5, 4.5, 8.5, 16.5, 32.5, 71.5,157.5},
  150222. { -1, -1, -1, -1, -1, -1, -1, -1, -1}
  150223. };
  150224. /* mapping conventions:
  150225. only one submap (this would change for efficient 5.1 support for example)*/
  150226. /* Four psychoacoustic profiles are used, one for each blocktype */
  150227. static vorbis_info_mapping0 _map_nominal_u[2]={
  150228. {1, {0,0}, {0}, {0}, 0,{0},{0}},
  150229. {1, {0,0}, {1}, {1}, 0,{0},{0}}
  150230. };
  150231. static static_bookblock _resbook_44u_n1={
  150232. {
  150233. {0},
  150234. {0,0,&_44un1__p1_0},
  150235. {0,0,&_44un1__p2_0},
  150236. {0,0,&_44un1__p3_0},
  150237. {0,0,&_44un1__p4_0},
  150238. {0,0,&_44un1__p5_0},
  150239. {&_44un1__p6_0,&_44un1__p6_1},
  150240. {&_44un1__p7_0,&_44un1__p7_1,&_44un1__p7_2}
  150241. }
  150242. };
  150243. static static_bookblock _resbook_44u_0={
  150244. {
  150245. {0},
  150246. {0,0,&_44u0__p1_0},
  150247. {0,0,&_44u0__p2_0},
  150248. {0,0,&_44u0__p3_0},
  150249. {0,0,&_44u0__p4_0},
  150250. {0,0,&_44u0__p5_0},
  150251. {&_44u0__p6_0,&_44u0__p6_1},
  150252. {&_44u0__p7_0,&_44u0__p7_1,&_44u0__p7_2}
  150253. }
  150254. };
  150255. static static_bookblock _resbook_44u_1={
  150256. {
  150257. {0},
  150258. {0,0,&_44u1__p1_0},
  150259. {0,0,&_44u1__p2_0},
  150260. {0,0,&_44u1__p3_0},
  150261. {0,0,&_44u1__p4_0},
  150262. {0,0,&_44u1__p5_0},
  150263. {&_44u1__p6_0,&_44u1__p6_1},
  150264. {&_44u1__p7_0,&_44u1__p7_1,&_44u1__p7_2}
  150265. }
  150266. };
  150267. static static_bookblock _resbook_44u_2={
  150268. {
  150269. {0},
  150270. {0,0,&_44u2__p1_0},
  150271. {0,0,&_44u2__p2_0},
  150272. {0,0,&_44u2__p3_0},
  150273. {0,0,&_44u2__p4_0},
  150274. {0,0,&_44u2__p5_0},
  150275. {&_44u2__p6_0,&_44u2__p6_1},
  150276. {&_44u2__p7_0,&_44u2__p7_1,&_44u2__p7_2}
  150277. }
  150278. };
  150279. static static_bookblock _resbook_44u_3={
  150280. {
  150281. {0},
  150282. {0,0,&_44u3__p1_0},
  150283. {0,0,&_44u3__p2_0},
  150284. {0,0,&_44u3__p3_0},
  150285. {0,0,&_44u3__p4_0},
  150286. {0,0,&_44u3__p5_0},
  150287. {&_44u3__p6_0,&_44u3__p6_1},
  150288. {&_44u3__p7_0,&_44u3__p7_1,&_44u3__p7_2}
  150289. }
  150290. };
  150291. static static_bookblock _resbook_44u_4={
  150292. {
  150293. {0},
  150294. {0,0,&_44u4__p1_0},
  150295. {0,0,&_44u4__p2_0},
  150296. {0,0,&_44u4__p3_0},
  150297. {0,0,&_44u4__p4_0},
  150298. {0,0,&_44u4__p5_0},
  150299. {&_44u4__p6_0,&_44u4__p6_1},
  150300. {&_44u4__p7_0,&_44u4__p7_1,&_44u4__p7_2}
  150301. }
  150302. };
  150303. static static_bookblock _resbook_44u_5={
  150304. {
  150305. {0},
  150306. {0,0,&_44u5__p1_0},
  150307. {0,0,&_44u5__p2_0},
  150308. {0,0,&_44u5__p3_0},
  150309. {0,0,&_44u5__p4_0},
  150310. {0,0,&_44u5__p5_0},
  150311. {0,0,&_44u5__p6_0},
  150312. {&_44u5__p7_0,&_44u5__p7_1},
  150313. {&_44u5__p8_0,&_44u5__p8_1},
  150314. {&_44u5__p9_0,&_44u5__p9_1,&_44u5__p9_2}
  150315. }
  150316. };
  150317. static static_bookblock _resbook_44u_6={
  150318. {
  150319. {0},
  150320. {0,0,&_44u6__p1_0},
  150321. {0,0,&_44u6__p2_0},
  150322. {0,0,&_44u6__p3_0},
  150323. {0,0,&_44u6__p4_0},
  150324. {0,0,&_44u6__p5_0},
  150325. {0,0,&_44u6__p6_0},
  150326. {&_44u6__p7_0,&_44u6__p7_1},
  150327. {&_44u6__p8_0,&_44u6__p8_1},
  150328. {&_44u6__p9_0,&_44u6__p9_1,&_44u6__p9_2}
  150329. }
  150330. };
  150331. static static_bookblock _resbook_44u_7={
  150332. {
  150333. {0},
  150334. {0,0,&_44u7__p1_0},
  150335. {0,0,&_44u7__p2_0},
  150336. {0,0,&_44u7__p3_0},
  150337. {0,0,&_44u7__p4_0},
  150338. {0,0,&_44u7__p5_0},
  150339. {0,0,&_44u7__p6_0},
  150340. {&_44u7__p7_0,&_44u7__p7_1},
  150341. {&_44u7__p8_0,&_44u7__p8_1},
  150342. {&_44u7__p9_0,&_44u7__p9_1,&_44u7__p9_2}
  150343. }
  150344. };
  150345. static static_bookblock _resbook_44u_8={
  150346. {
  150347. {0},
  150348. {0,0,&_44u8_p1_0},
  150349. {0,0,&_44u8_p2_0},
  150350. {0,0,&_44u8_p3_0},
  150351. {0,0,&_44u8_p4_0},
  150352. {&_44u8_p5_0,&_44u8_p5_1},
  150353. {&_44u8_p6_0,&_44u8_p6_1},
  150354. {&_44u8_p7_0,&_44u8_p7_1},
  150355. {&_44u8_p8_0,&_44u8_p8_1},
  150356. {&_44u8_p9_0,&_44u8_p9_1,&_44u8_p9_2}
  150357. }
  150358. };
  150359. static static_bookblock _resbook_44u_9={
  150360. {
  150361. {0},
  150362. {0,0,&_44u9_p1_0},
  150363. {0,0,&_44u9_p2_0},
  150364. {0,0,&_44u9_p3_0},
  150365. {0,0,&_44u9_p4_0},
  150366. {&_44u9_p5_0,&_44u9_p5_1},
  150367. {&_44u9_p6_0,&_44u9_p6_1},
  150368. {&_44u9_p7_0,&_44u9_p7_1},
  150369. {&_44u9_p8_0,&_44u9_p8_1},
  150370. {&_44u9_p9_0,&_44u9_p9_1,&_44u9_p9_2}
  150371. }
  150372. };
  150373. static vorbis_residue_template _res_44u_n1[]={
  150374. {1,0, &_residue_44_low_un,
  150375. &_huff_book__44un1__short,&_huff_book__44un1__short,
  150376. &_resbook_44u_n1,&_resbook_44u_n1},
  150377. {1,0, &_residue_44_low_un,
  150378. &_huff_book__44un1__long,&_huff_book__44un1__long,
  150379. &_resbook_44u_n1,&_resbook_44u_n1}
  150380. };
  150381. static vorbis_residue_template _res_44u_0[]={
  150382. {1,0, &_residue_44_low_un,
  150383. &_huff_book__44u0__short,&_huff_book__44u0__short,
  150384. &_resbook_44u_0,&_resbook_44u_0},
  150385. {1,0, &_residue_44_low_un,
  150386. &_huff_book__44u0__long,&_huff_book__44u0__long,
  150387. &_resbook_44u_0,&_resbook_44u_0}
  150388. };
  150389. static vorbis_residue_template _res_44u_1[]={
  150390. {1,0, &_residue_44_low_un,
  150391. &_huff_book__44u1__short,&_huff_book__44u1__short,
  150392. &_resbook_44u_1,&_resbook_44u_1},
  150393. {1,0, &_residue_44_low_un,
  150394. &_huff_book__44u1__long,&_huff_book__44u1__long,
  150395. &_resbook_44u_1,&_resbook_44u_1}
  150396. };
  150397. static vorbis_residue_template _res_44u_2[]={
  150398. {1,0, &_residue_44_low_un,
  150399. &_huff_book__44u2__short,&_huff_book__44u2__short,
  150400. &_resbook_44u_2,&_resbook_44u_2},
  150401. {1,0, &_residue_44_low_un,
  150402. &_huff_book__44u2__long,&_huff_book__44u2__long,
  150403. &_resbook_44u_2,&_resbook_44u_2}
  150404. };
  150405. static vorbis_residue_template _res_44u_3[]={
  150406. {1,0, &_residue_44_low_un,
  150407. &_huff_book__44u3__short,&_huff_book__44u3__short,
  150408. &_resbook_44u_3,&_resbook_44u_3},
  150409. {1,0, &_residue_44_low_un,
  150410. &_huff_book__44u3__long,&_huff_book__44u3__long,
  150411. &_resbook_44u_3,&_resbook_44u_3}
  150412. };
  150413. static vorbis_residue_template _res_44u_4[]={
  150414. {1,0, &_residue_44_low_un,
  150415. &_huff_book__44u4__short,&_huff_book__44u4__short,
  150416. &_resbook_44u_4,&_resbook_44u_4},
  150417. {1,0, &_residue_44_low_un,
  150418. &_huff_book__44u4__long,&_huff_book__44u4__long,
  150419. &_resbook_44u_4,&_resbook_44u_4}
  150420. };
  150421. static vorbis_residue_template _res_44u_5[]={
  150422. {1,0, &_residue_44_mid_un,
  150423. &_huff_book__44u5__short,&_huff_book__44u5__short,
  150424. &_resbook_44u_5,&_resbook_44u_5},
  150425. {1,0, &_residue_44_mid_un,
  150426. &_huff_book__44u5__long,&_huff_book__44u5__long,
  150427. &_resbook_44u_5,&_resbook_44u_5}
  150428. };
  150429. static vorbis_residue_template _res_44u_6[]={
  150430. {1,0, &_residue_44_mid_un,
  150431. &_huff_book__44u6__short,&_huff_book__44u6__short,
  150432. &_resbook_44u_6,&_resbook_44u_6},
  150433. {1,0, &_residue_44_mid_un,
  150434. &_huff_book__44u6__long,&_huff_book__44u6__long,
  150435. &_resbook_44u_6,&_resbook_44u_6}
  150436. };
  150437. static vorbis_residue_template _res_44u_7[]={
  150438. {1,0, &_residue_44_mid_un,
  150439. &_huff_book__44u7__short,&_huff_book__44u7__short,
  150440. &_resbook_44u_7,&_resbook_44u_7},
  150441. {1,0, &_residue_44_mid_un,
  150442. &_huff_book__44u7__long,&_huff_book__44u7__long,
  150443. &_resbook_44u_7,&_resbook_44u_7}
  150444. };
  150445. static vorbis_residue_template _res_44u_8[]={
  150446. {1,0, &_residue_44_hi_un,
  150447. &_huff_book__44u8__short,&_huff_book__44u8__short,
  150448. &_resbook_44u_8,&_resbook_44u_8},
  150449. {1,0, &_residue_44_hi_un,
  150450. &_huff_book__44u8__long,&_huff_book__44u8__long,
  150451. &_resbook_44u_8,&_resbook_44u_8}
  150452. };
  150453. static vorbis_residue_template _res_44u_9[]={
  150454. {1,0, &_residue_44_hi_un,
  150455. &_huff_book__44u9__short,&_huff_book__44u9__short,
  150456. &_resbook_44u_9,&_resbook_44u_9},
  150457. {1,0, &_residue_44_hi_un,
  150458. &_huff_book__44u9__long,&_huff_book__44u9__long,
  150459. &_resbook_44u_9,&_resbook_44u_9}
  150460. };
  150461. static vorbis_mapping_template _mapres_template_44_uncoupled[]={
  150462. { _map_nominal_u, _res_44u_n1 }, /* -1 */
  150463. { _map_nominal_u, _res_44u_0 }, /* 0 */
  150464. { _map_nominal_u, _res_44u_1 }, /* 1 */
  150465. { _map_nominal_u, _res_44u_2 }, /* 2 */
  150466. { _map_nominal_u, _res_44u_3 }, /* 3 */
  150467. { _map_nominal_u, _res_44u_4 }, /* 4 */
  150468. { _map_nominal_u, _res_44u_5 }, /* 5 */
  150469. { _map_nominal_u, _res_44u_6 }, /* 6 */
  150470. { _map_nominal_u, _res_44u_7 }, /* 7 */
  150471. { _map_nominal_u, _res_44u_8 }, /* 8 */
  150472. { _map_nominal_u, _res_44u_9 }, /* 9 */
  150473. };
  150474. /*** End of inlined file: residue_44u.h ***/
  150475. static double rate_mapping_44_un[12]={
  150476. 32000.,48000.,60000.,70000.,80000.,86000.,
  150477. 96000.,110000.,120000.,140000.,160000.,240001.
  150478. };
  150479. ve_setup_data_template ve_setup_44_uncoupled={
  150480. 11,
  150481. rate_mapping_44_un,
  150482. quality_mapping_44,
  150483. -1,
  150484. 40000,
  150485. 50000,
  150486. blocksize_short_44,
  150487. blocksize_long_44,
  150488. _psy_tone_masteratt_44,
  150489. _psy_tone_0dB,
  150490. _psy_tone_suppress,
  150491. _vp_tonemask_adj_otherblock,
  150492. _vp_tonemask_adj_longblock,
  150493. _vp_tonemask_adj_otherblock,
  150494. _psy_noiseguards_44,
  150495. _psy_noisebias_impulse,
  150496. _psy_noisebias_padding,
  150497. _psy_noisebias_trans,
  150498. _psy_noisebias_long,
  150499. _psy_noise_suppress,
  150500. _psy_compand_44,
  150501. _psy_compand_short_mapping,
  150502. _psy_compand_long_mapping,
  150503. {_noise_start_short_44,_noise_start_long_44},
  150504. {_noise_part_short_44,_noise_part_long_44},
  150505. _noise_thresh_44,
  150506. _psy_ath_floater,
  150507. _psy_ath_abs,
  150508. _psy_lowpass_44,
  150509. _psy_global_44,
  150510. _global_mapping_44,
  150511. NULL,
  150512. _floor_books,
  150513. _floor,
  150514. _floor_short_mapping_44,
  150515. _floor_long_mapping_44,
  150516. _mapres_template_44_uncoupled
  150517. };
  150518. /*** End of inlined file: setup_44u.h ***/
  150519. /*** Start of inlined file: setup_32.h ***/
  150520. static double rate_mapping_32[12]={
  150521. 18000.,28000.,35000.,45000.,56000.,60000.,
  150522. 75000.,90000.,100000.,115000.,150000.,190000.,
  150523. };
  150524. static double rate_mapping_32_un[12]={
  150525. 30000.,42000.,52000.,64000.,72000.,78000.,
  150526. 86000.,92000.,110000.,120000.,140000.,190000.,
  150527. };
  150528. static double _psy_lowpass_32[12]={
  150529. 12.3,13.,13.,14.,15.,99.,99.,99.,99.,99.,99.,99.
  150530. };
  150531. ve_setup_data_template ve_setup_32_stereo={
  150532. 11,
  150533. rate_mapping_32,
  150534. quality_mapping_44,
  150535. 2,
  150536. 26000,
  150537. 40000,
  150538. blocksize_short_44,
  150539. blocksize_long_44,
  150540. _psy_tone_masteratt_44,
  150541. _psy_tone_0dB,
  150542. _psy_tone_suppress,
  150543. _vp_tonemask_adj_otherblock,
  150544. _vp_tonemask_adj_longblock,
  150545. _vp_tonemask_adj_otherblock,
  150546. _psy_noiseguards_44,
  150547. _psy_noisebias_impulse,
  150548. _psy_noisebias_padding,
  150549. _psy_noisebias_trans,
  150550. _psy_noisebias_long,
  150551. _psy_noise_suppress,
  150552. _psy_compand_44,
  150553. _psy_compand_short_mapping,
  150554. _psy_compand_long_mapping,
  150555. {_noise_start_short_44,_noise_start_long_44},
  150556. {_noise_part_short_44,_noise_part_long_44},
  150557. _noise_thresh_44,
  150558. _psy_ath_floater,
  150559. _psy_ath_abs,
  150560. _psy_lowpass_32,
  150561. _psy_global_44,
  150562. _global_mapping_44,
  150563. _psy_stereo_modes_44,
  150564. _floor_books,
  150565. _floor,
  150566. _floor_short_mapping_44,
  150567. _floor_long_mapping_44,
  150568. _mapres_template_44_stereo
  150569. };
  150570. ve_setup_data_template ve_setup_32_uncoupled={
  150571. 11,
  150572. rate_mapping_32_un,
  150573. quality_mapping_44,
  150574. -1,
  150575. 26000,
  150576. 40000,
  150577. blocksize_short_44,
  150578. blocksize_long_44,
  150579. _psy_tone_masteratt_44,
  150580. _psy_tone_0dB,
  150581. _psy_tone_suppress,
  150582. _vp_tonemask_adj_otherblock,
  150583. _vp_tonemask_adj_longblock,
  150584. _vp_tonemask_adj_otherblock,
  150585. _psy_noiseguards_44,
  150586. _psy_noisebias_impulse,
  150587. _psy_noisebias_padding,
  150588. _psy_noisebias_trans,
  150589. _psy_noisebias_long,
  150590. _psy_noise_suppress,
  150591. _psy_compand_44,
  150592. _psy_compand_short_mapping,
  150593. _psy_compand_long_mapping,
  150594. {_noise_start_short_44,_noise_start_long_44},
  150595. {_noise_part_short_44,_noise_part_long_44},
  150596. _noise_thresh_44,
  150597. _psy_ath_floater,
  150598. _psy_ath_abs,
  150599. _psy_lowpass_32,
  150600. _psy_global_44,
  150601. _global_mapping_44,
  150602. NULL,
  150603. _floor_books,
  150604. _floor,
  150605. _floor_short_mapping_44,
  150606. _floor_long_mapping_44,
  150607. _mapres_template_44_uncoupled
  150608. };
  150609. /*** End of inlined file: setup_32.h ***/
  150610. /*** Start of inlined file: setup_8.h ***/
  150611. /*** Start of inlined file: psych_8.h ***/
  150612. static att3 _psy_tone_masteratt_8[3]={
  150613. {{ 32, 25, 12}, 0, 0}, /* 0 */
  150614. {{ 30, 25, 12}, 0, 0}, /* 0 */
  150615. {{ 20, 0, -14}, 0, 0}, /* 0 */
  150616. };
  150617. static vp_adjblock _vp_tonemask_adj_8[3]={
  150618. /* adjust for mode zero */
  150619. /* 63 125 250 500 1 2 4 8 16 */
  150620. {{-15,-15,-15,-15,-10,-10, -6, 0, 0, 0, 0,10, 0, 0,99,99,99}}, /* 1 */
  150621. {{-15,-15,-15,-15,-10,-10, -6, 0, 0, 0, 0,10, 0, 0,99,99,99}}, /* 1 */
  150622. {{-15,-15,-15,-15,-10,-10, -6, 0, 0, 0, 0, 0, 0, 0,99,99,99}}, /* 1 */
  150623. };
  150624. static noise3 _psy_noisebias_8[3]={
  150625. /* 63 125 250 500 1k 2k 4k 8k 16k*/
  150626. {{{-10,-10,-10,-10, -5, -5, -5, 0, 4, 8, 8, 8, 10, 10, 99, 99, 99},
  150627. {-10,-10,-10,-10, -5, -5, -5, 0, 0, 4, 4, 4, 4, 4, 99, 99, 99},
  150628. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, 99, 99, 99}}},
  150629. {{{-10,-10,-10,-10, -5, -5, -5, 0, 4, 8, 8, 8, 10, 10, 99, 99, 99},
  150630. {-10,-10,-10,-10,-10,-10, -5, -5, -5, 0, 0, 0, 0, 0, 99, 99, 99},
  150631. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, 99, 99, 99}}},
  150632. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 4, 4, 5, 5, 99, 99, 99},
  150633. {-30,-30,-30,-30,-26,-22,-20,-14,-12,-12,-10,-10,-10,-10, 99, 99, 99},
  150634. {-30,-30,-30,-30,-26,-26,-26,-26,-26,-26,-26,-26,-26,-24, 99, 99, 99}}},
  150635. };
  150636. /* stereo mode by base quality level */
  150637. static adj_stereo _psy_stereo_modes_8[3]={
  150638. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 */
  150639. {{ 4, 4, 4, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3},
  150640. { 6, 5, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4},
  150641. { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1},
  150642. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  150643. {{ 4, 4, 4, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3},
  150644. { 6, 5, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4},
  150645. { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1},
  150646. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  150647. {{ 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3},
  150648. { 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4},
  150649. { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1},
  150650. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  150651. };
  150652. static noiseguard _psy_noiseguards_8[2]={
  150653. {10,10,-1},
  150654. {10,10,-1},
  150655. };
  150656. static compandblock _psy_compand_8[2]={
  150657. {{
  150658. 0, 1, 2, 3, 4, 5, 6, 7, /* 7dB */
  150659. 8, 8, 9, 9,10,10,11, 11, /* 15dB */
  150660. 12,12,13,13,14,14,15, 15, /* 23dB */
  150661. 16,16,17,17,17,18,18, 19, /* 31dB */
  150662. 19,19,20,21,22,23,24, 25, /* 39dB */
  150663. }},
  150664. {{
  150665. 0, 1, 2, 3, 4, 5, 6, 6, /* 7dB */
  150666. 7, 7, 6, 6, 5, 5, 4, 4, /* 15dB */
  150667. 3, 3, 3, 4, 5, 6, 7, 8, /* 23dB */
  150668. 9,10,11,12,13,14,15, 16, /* 31dB */
  150669. 17,18,19,20,21,22,23, 24, /* 39dB */
  150670. }},
  150671. };
  150672. static double _psy_lowpass_8[3]={3.,4.,4.};
  150673. static int _noise_start_8[2]={
  150674. 64,64,
  150675. };
  150676. static int _noise_part_8[2]={
  150677. 8,8,
  150678. };
  150679. static int _psy_ath_floater_8[3]={
  150680. -100,-100,-105,
  150681. };
  150682. static int _psy_ath_abs_8[3]={
  150683. -130,-130,-140,
  150684. };
  150685. /*** End of inlined file: psych_8.h ***/
  150686. /*** Start of inlined file: residue_8.h ***/
  150687. /***** residue backends *********************************************/
  150688. static static_bookblock _resbook_8s_0={
  150689. {
  150690. {0},{0,0,&_8c0_s_p1_0},{0,0,&_8c0_s_p2_0},{0,0,&_8c0_s_p3_0},
  150691. {0,0,&_8c0_s_p4_0},{0,0,&_8c0_s_p5_0},{0,0,&_8c0_s_p6_0},
  150692. {&_8c0_s_p7_0,&_8c0_s_p7_1},{&_8c0_s_p8_0,&_8c0_s_p8_1},
  150693. {&_8c0_s_p9_0,&_8c0_s_p9_1,&_8c0_s_p9_2}
  150694. }
  150695. };
  150696. static static_bookblock _resbook_8s_1={
  150697. {
  150698. {0},{0,0,&_8c1_s_p1_0},{0,0,&_8c1_s_p2_0},{0,0,&_8c1_s_p3_0},
  150699. {0,0,&_8c1_s_p4_0},{0,0,&_8c1_s_p5_0},{0,0,&_8c1_s_p6_0},
  150700. {&_8c1_s_p7_0,&_8c1_s_p7_1},{&_8c1_s_p8_0,&_8c1_s_p8_1},
  150701. {&_8c1_s_p9_0,&_8c1_s_p9_1,&_8c1_s_p9_2}
  150702. }
  150703. };
  150704. static vorbis_residue_template _res_8s_0[]={
  150705. {2,0, &_residue_44_mid,
  150706. &_huff_book__8c0_s_single,&_huff_book__8c0_s_single,
  150707. &_resbook_8s_0,&_resbook_8s_0},
  150708. };
  150709. static vorbis_residue_template _res_8s_1[]={
  150710. {2,0, &_residue_44_mid,
  150711. &_huff_book__8c1_s_single,&_huff_book__8c1_s_single,
  150712. &_resbook_8s_1,&_resbook_8s_1},
  150713. };
  150714. static vorbis_mapping_template _mapres_template_8_stereo[2]={
  150715. { _map_nominal, _res_8s_0 }, /* 0 */
  150716. { _map_nominal, _res_8s_1 }, /* 1 */
  150717. };
  150718. static static_bookblock _resbook_8u_0={
  150719. {
  150720. {0},
  150721. {0,0,&_8u0__p1_0},
  150722. {0,0,&_8u0__p2_0},
  150723. {0,0,&_8u0__p3_0},
  150724. {0,0,&_8u0__p4_0},
  150725. {0,0,&_8u0__p5_0},
  150726. {&_8u0__p6_0,&_8u0__p6_1},
  150727. {&_8u0__p7_0,&_8u0__p7_1,&_8u0__p7_2}
  150728. }
  150729. };
  150730. static static_bookblock _resbook_8u_1={
  150731. {
  150732. {0},
  150733. {0,0,&_8u1__p1_0},
  150734. {0,0,&_8u1__p2_0},
  150735. {0,0,&_8u1__p3_0},
  150736. {0,0,&_8u1__p4_0},
  150737. {0,0,&_8u1__p5_0},
  150738. {0,0,&_8u1__p6_0},
  150739. {&_8u1__p7_0,&_8u1__p7_1},
  150740. {&_8u1__p8_0,&_8u1__p8_1},
  150741. {&_8u1__p9_0,&_8u1__p9_1,&_8u1__p9_2}
  150742. }
  150743. };
  150744. static vorbis_residue_template _res_8u_0[]={
  150745. {1,0, &_residue_44_low_un,
  150746. &_huff_book__8u0__single,&_huff_book__8u0__single,
  150747. &_resbook_8u_0,&_resbook_8u_0},
  150748. };
  150749. static vorbis_residue_template _res_8u_1[]={
  150750. {1,0, &_residue_44_mid_un,
  150751. &_huff_book__8u1__single,&_huff_book__8u1__single,
  150752. &_resbook_8u_1,&_resbook_8u_1},
  150753. };
  150754. static vorbis_mapping_template _mapres_template_8_uncoupled[2]={
  150755. { _map_nominal_u, _res_8u_0 }, /* 0 */
  150756. { _map_nominal_u, _res_8u_1 }, /* 1 */
  150757. };
  150758. /*** End of inlined file: residue_8.h ***/
  150759. static int blocksize_8[2]={
  150760. 512,512
  150761. };
  150762. static int _floor_mapping_8[2]={
  150763. 6,6,
  150764. };
  150765. static double rate_mapping_8[3]={
  150766. 6000.,9000.,32000.,
  150767. };
  150768. static double rate_mapping_8_uncoupled[3]={
  150769. 8000.,14000.,42000.,
  150770. };
  150771. static double quality_mapping_8[3]={
  150772. -.1,.0,1.
  150773. };
  150774. static double _psy_compand_8_mapping[3]={ 0., 1., 1.};
  150775. static double _global_mapping_8[3]={ 1., 2., 3. };
  150776. ve_setup_data_template ve_setup_8_stereo={
  150777. 2,
  150778. rate_mapping_8,
  150779. quality_mapping_8,
  150780. 2,
  150781. 8000,
  150782. 9000,
  150783. blocksize_8,
  150784. blocksize_8,
  150785. _psy_tone_masteratt_8,
  150786. _psy_tone_0dB,
  150787. _psy_tone_suppress,
  150788. _vp_tonemask_adj_8,
  150789. NULL,
  150790. _vp_tonemask_adj_8,
  150791. _psy_noiseguards_8,
  150792. _psy_noisebias_8,
  150793. _psy_noisebias_8,
  150794. NULL,
  150795. NULL,
  150796. _psy_noise_suppress,
  150797. _psy_compand_8,
  150798. _psy_compand_8_mapping,
  150799. NULL,
  150800. {_noise_start_8,_noise_start_8},
  150801. {_noise_part_8,_noise_part_8},
  150802. _noise_thresh_5only,
  150803. _psy_ath_floater_8,
  150804. _psy_ath_abs_8,
  150805. _psy_lowpass_8,
  150806. _psy_global_44,
  150807. _global_mapping_8,
  150808. _psy_stereo_modes_8,
  150809. _floor_books,
  150810. _floor,
  150811. _floor_mapping_8,
  150812. NULL,
  150813. _mapres_template_8_stereo
  150814. };
  150815. ve_setup_data_template ve_setup_8_uncoupled={
  150816. 2,
  150817. rate_mapping_8_uncoupled,
  150818. quality_mapping_8,
  150819. -1,
  150820. 8000,
  150821. 9000,
  150822. blocksize_8,
  150823. blocksize_8,
  150824. _psy_tone_masteratt_8,
  150825. _psy_tone_0dB,
  150826. _psy_tone_suppress,
  150827. _vp_tonemask_adj_8,
  150828. NULL,
  150829. _vp_tonemask_adj_8,
  150830. _psy_noiseguards_8,
  150831. _psy_noisebias_8,
  150832. _psy_noisebias_8,
  150833. NULL,
  150834. NULL,
  150835. _psy_noise_suppress,
  150836. _psy_compand_8,
  150837. _psy_compand_8_mapping,
  150838. NULL,
  150839. {_noise_start_8,_noise_start_8},
  150840. {_noise_part_8,_noise_part_8},
  150841. _noise_thresh_5only,
  150842. _psy_ath_floater_8,
  150843. _psy_ath_abs_8,
  150844. _psy_lowpass_8,
  150845. _psy_global_44,
  150846. _global_mapping_8,
  150847. _psy_stereo_modes_8,
  150848. _floor_books,
  150849. _floor,
  150850. _floor_mapping_8,
  150851. NULL,
  150852. _mapres_template_8_uncoupled
  150853. };
  150854. /*** End of inlined file: setup_8.h ***/
  150855. /*** Start of inlined file: setup_11.h ***/
  150856. /*** Start of inlined file: psych_11.h ***/
  150857. static double _psy_lowpass_11[3]={4.5,5.5,30.,};
  150858. static att3 _psy_tone_masteratt_11[3]={
  150859. {{ 30, 25, 12}, 0, 0}, /* 0 */
  150860. {{ 30, 25, 12}, 0, 0}, /* 0 */
  150861. {{ 20, 0, -14}, 0, 0}, /* 0 */
  150862. };
  150863. static vp_adjblock _vp_tonemask_adj_11[3]={
  150864. /* adjust for mode zero */
  150865. /* 63 125 250 500 1 2 4 8 16 */
  150866. {{-20,-20,-20,-20,-20,-16,-10, 0, 0, 0, 0,10, 2, 0,99,99,99}}, /* 0 */
  150867. {{-20,-20,-20,-20,-20,-16,-10, 0, 0, 0, 0, 5, 0, 0,99,99,99}}, /* 1 */
  150868. {{-20,-20,-20,-20,-20,-16,-10, 0, 0, 0, 0, 0, 0, 0,99,99,99}}, /* 2 */
  150869. };
  150870. static noise3 _psy_noisebias_11[3]={
  150871. /* 63 125 250 500 1k 2k 4k 8k 16k*/
  150872. {{{-10,-10,-10,-10, -5, -5, -5, 0, 4, 10, 10, 12, 12, 12, 99, 99, 99},
  150873. {-15,-15,-15,-15,-10,-10, -5, 0, 0, 4, 4, 5, 5, 10, 99, 99, 99},
  150874. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, 99, 99, 99}}},
  150875. {{{-10,-10,-10,-10, -5, -5, -5, 0, 4, 10, 10, 12, 12, 12, 99, 99, 99},
  150876. {-15,-15,-15,-15,-10,-10, -5, -5, -5, 0, 0, 0, 0, 0, 99, 99, 99},
  150877. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, 99, 99, 99}}},
  150878. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 4, 4, 5, 5, 99, 99, 99},
  150879. {-30,-30,-30,-30,-26,-22,-20,-14,-12,-12,-10,-10,-10,-10, 99, 99, 99},
  150880. {-30,-30,-30,-30,-26,-26,-26,-26,-26,-26,-26,-26,-26,-24, 99, 99, 99}}},
  150881. };
  150882. static double _noise_thresh_11[3]={ .3,.5,.5 };
  150883. /*** End of inlined file: psych_11.h ***/
  150884. static int blocksize_11[2]={
  150885. 512,512
  150886. };
  150887. static int _floor_mapping_11[2]={
  150888. 6,6,
  150889. };
  150890. static double rate_mapping_11[3]={
  150891. 8000.,13000.,44000.,
  150892. };
  150893. static double rate_mapping_11_uncoupled[3]={
  150894. 12000.,20000.,50000.,
  150895. };
  150896. static double quality_mapping_11[3]={
  150897. -.1,.0,1.
  150898. };
  150899. ve_setup_data_template ve_setup_11_stereo={
  150900. 2,
  150901. rate_mapping_11,
  150902. quality_mapping_11,
  150903. 2,
  150904. 9000,
  150905. 15000,
  150906. blocksize_11,
  150907. blocksize_11,
  150908. _psy_tone_masteratt_11,
  150909. _psy_tone_0dB,
  150910. _psy_tone_suppress,
  150911. _vp_tonemask_adj_11,
  150912. NULL,
  150913. _vp_tonemask_adj_11,
  150914. _psy_noiseguards_8,
  150915. _psy_noisebias_11,
  150916. _psy_noisebias_11,
  150917. NULL,
  150918. NULL,
  150919. _psy_noise_suppress,
  150920. _psy_compand_8,
  150921. _psy_compand_8_mapping,
  150922. NULL,
  150923. {_noise_start_8,_noise_start_8},
  150924. {_noise_part_8,_noise_part_8},
  150925. _noise_thresh_11,
  150926. _psy_ath_floater_8,
  150927. _psy_ath_abs_8,
  150928. _psy_lowpass_11,
  150929. _psy_global_44,
  150930. _global_mapping_8,
  150931. _psy_stereo_modes_8,
  150932. _floor_books,
  150933. _floor,
  150934. _floor_mapping_11,
  150935. NULL,
  150936. _mapres_template_8_stereo
  150937. };
  150938. ve_setup_data_template ve_setup_11_uncoupled={
  150939. 2,
  150940. rate_mapping_11_uncoupled,
  150941. quality_mapping_11,
  150942. -1,
  150943. 9000,
  150944. 15000,
  150945. blocksize_11,
  150946. blocksize_11,
  150947. _psy_tone_masteratt_11,
  150948. _psy_tone_0dB,
  150949. _psy_tone_suppress,
  150950. _vp_tonemask_adj_11,
  150951. NULL,
  150952. _vp_tonemask_adj_11,
  150953. _psy_noiseguards_8,
  150954. _psy_noisebias_11,
  150955. _psy_noisebias_11,
  150956. NULL,
  150957. NULL,
  150958. _psy_noise_suppress,
  150959. _psy_compand_8,
  150960. _psy_compand_8_mapping,
  150961. NULL,
  150962. {_noise_start_8,_noise_start_8},
  150963. {_noise_part_8,_noise_part_8},
  150964. _noise_thresh_11,
  150965. _psy_ath_floater_8,
  150966. _psy_ath_abs_8,
  150967. _psy_lowpass_11,
  150968. _psy_global_44,
  150969. _global_mapping_8,
  150970. _psy_stereo_modes_8,
  150971. _floor_books,
  150972. _floor,
  150973. _floor_mapping_11,
  150974. NULL,
  150975. _mapres_template_8_uncoupled
  150976. };
  150977. /*** End of inlined file: setup_11.h ***/
  150978. /*** Start of inlined file: setup_16.h ***/
  150979. /*** Start of inlined file: psych_16.h ***/
  150980. /* stereo mode by base quality level */
  150981. static adj_stereo _psy_stereo_modes_16[4]={
  150982. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 */
  150983. {{ 4, 4, 4, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3},
  150984. { 6, 5, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4},
  150985. { 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 3, 3, 4, 4},
  150986. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  150987. {{ 4, 4, 4, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3},
  150988. { 6, 5, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4},
  150989. { 2, 2, 2, 2, 2, 2, 2, 2, 2, 3, 4, 4, 4, 4, 4},
  150990. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  150991. {{ 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3},
  150992. { 5, 4, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3},
  150993. { 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4},
  150994. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  150995. {{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  150996. { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  150997. { 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8},
  150998. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  150999. };
  151000. static double _psy_lowpass_16[4]={6.5,8,30.,99.};
  151001. static att3 _psy_tone_masteratt_16[4]={
  151002. {{ 30, 25, 12}, 0, 0}, /* 0 */
  151003. {{ 25, 22, 12}, 0, 0}, /* 0 */
  151004. {{ 20, 12, 0}, 0, 0}, /* 0 */
  151005. {{ 15, 0, -14}, 0, 0}, /* 0 */
  151006. };
  151007. static vp_adjblock _vp_tonemask_adj_16[4]={
  151008. /* adjust for mode zero */
  151009. /* 63 125 250 500 1 2 4 8 16 */
  151010. {{-20,-20,-20,-20,-20,-16,-10, 0, 0, 0, 0,10, 0, 0, 0, 0, 0}}, /* 0 */
  151011. {{-20,-20,-20,-20,-20,-16,-10, 0, 0, 0, 0,10, 0, 0, 0, 0, 0}}, /* 1 */
  151012. {{-20,-20,-20,-20,-20,-16,-10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, /* 2 */
  151013. {{-30,-30,-30,-30,-30,-26,-20,-10, -5, 0, 0, 0, 0, 0, 0, 0, 0}}, /* 2 */
  151014. };
  151015. static noise3 _psy_noisebias_16_short[4]={
  151016. /* 63 125 250 500 1k 2k 4k 8k 16k*/
  151017. {{{-15,-15,-15,-15,-15,-10,-10,-5, 4, 10, 10, 10, 10, 12, 12, 14, 20},
  151018. {-15,-15,-15,-15,-15,-10,-10, -5, 0, 0, 4, 5, 5, 6, 8, 8, 15},
  151019. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, -6, -6, -6}}},
  151020. {{{-15,-15,-15,-15,-15,-10,-10,-5, 4, 6, 6, 6, 6, 8, 10, 12, 20},
  151021. {-15,-15,-15,-15,-15,-15,-15,-10, -5, -5, -5, 4, 5, 6, 8, 8, 15},
  151022. {-30,-30,-30,-30,-30,-24,-20,-14,-10,-10,-10,-10,-10,-10,-10,-10,-10}}},
  151023. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 4, 4, 5, 5, 5, 8, 12},
  151024. {-20,-20,-20,-20,-16,-12,-20,-14,-10,-10, -8, 0, 0, 0, 0, 2, 5},
  151025. {-30,-30,-30,-30,-26,-26,-26,-26,-26,-26,-26,-26,-26,-24,-20,-20,-20}}},
  151026. {{{-15,-15,-15,-15,-15,-12,-10, -8, -5, -5, -5, -5, -5, 0, 0, 0, 6},
  151027. {-30,-30,-30,-30,-26,-22,-20,-14,-12,-12,-10,-10,-10,-10,-10,-10, -6},
  151028. {-30,-30,-30,-30,-26,-26,-26,-26,-26,-26,-26,-26,-26,-24,-20,-20,-20}}},
  151029. };
  151030. static noise3 _psy_noisebias_16_impulse[4]={
  151031. /* 63 125 250 500 1k 2k 4k 8k 16k*/
  151032. {{{-15,-15,-15,-15,-15,-10,-10,-5, 4, 10, 10, 10, 10, 12, 12, 14, 20},
  151033. {-15,-15,-15,-15,-15,-10,-10, -5, 0, 0, 4, 5, 5, 6, 8, 8, 15},
  151034. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, -6, -6, -6}}},
  151035. {{{-15,-15,-15,-15,-15,-10,-10,-5, 4, 4, 4, 4, 5, 5, 6, 8, 15},
  151036. {-15,-15,-15,-15,-15,-15,-15,-10, -5, -5, -5, 0, 0, 0, 0, 4, 10},
  151037. {-30,-30,-30,-30,-30,-24,-20,-14,-10,-10,-10,-10,-10,-10,-10,-10,-10}}},
  151038. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 0, 0, 0, 0, 4, 10},
  151039. {-20,-20,-20,-20,-16,-12,-20,-14,-10,-10,-10,-10,-10,-10,-10, -7, -5},
  151040. {-30,-30,-30,-30,-26,-26,-26,-26,-26,-26,-26,-26,-26,-24,-20,-20,-20}}},
  151041. {{{-15,-15,-15,-15,-15,-12,-10, -8, -5, -5, -5, -5, -5, 0, 0, 0, 6},
  151042. {-30,-30,-30,-30,-26,-22,-20,-18,-18,-18,-20,-20,-20,-20,-20,-20,-16},
  151043. {-30,-30,-30,-30,-26,-26,-26,-26,-26,-26,-26,-26,-26,-24,-20,-20,-20}}},
  151044. };
  151045. static noise3 _psy_noisebias_16[4]={
  151046. /* 63 125 250 500 1k 2k 4k 8k 16k*/
  151047. {{{-10,-10,-10,-10, -5, -5, -5, 0, 4, 6, 8, 8, 10, 10, 10, 14, 20},
  151048. {-10,-10,-10,-10,-10, -5, -2, -2, 0, 0, 0, 4, 5, 6, 8, 8, 15},
  151049. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, -6, -6, -6}}},
  151050. {{{-10,-10,-10,-10, -5, -5, -5, 0, 4, 6, 6, 6, 6, 8, 10, 12, 20},
  151051. {-15,-15,-15,-15,-15,-10, -5, -5, 0, 0, 0, 4, 5, 6, 8, 8, 15},
  151052. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, -6, -6, -6}}},
  151053. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 4, 4, 5, 5, 5, 8, 12},
  151054. {-20,-20,-20,-20,-16,-12,-20,-10, -5, -5, 0, 0, 0, 0, 0, 2, 5},
  151055. {-30,-30,-30,-30,-26,-26,-26,-26,-26,-26,-26,-26,-26,-24,-20,-20,-20}}},
  151056. {{{-15,-15,-15,-15,-15,-12,-10, -8, -5, -5, -5, -5, -5, 0, 0, 0, 6},
  151057. {-30,-30,-30,-30,-26,-22,-20,-14,-12,-12,-10,-10,-10,-10,-10,-10, -6},
  151058. {-30,-30,-30,-30,-26,-26,-26,-26,-26,-26,-26,-26,-26,-24,-20,-20,-20}}},
  151059. };
  151060. static double _noise_thresh_16[4]={ .3,.5,.5,.5 };
  151061. static int _noise_start_16[3]={ 256,256,9999 };
  151062. static int _noise_part_16[4]={ 8,8,8,8 };
  151063. static int _psy_ath_floater_16[4]={
  151064. -100,-100,-100,-105,
  151065. };
  151066. static int _psy_ath_abs_16[4]={
  151067. -130,-130,-130,-140,
  151068. };
  151069. /*** End of inlined file: psych_16.h ***/
  151070. /*** Start of inlined file: residue_16.h ***/
  151071. /***** residue backends *********************************************/
  151072. static static_bookblock _resbook_16s_0={
  151073. {
  151074. {0},
  151075. {0,0,&_16c0_s_p1_0},
  151076. {0,0,&_16c0_s_p2_0},
  151077. {0,0,&_16c0_s_p3_0},
  151078. {0,0,&_16c0_s_p4_0},
  151079. {0,0,&_16c0_s_p5_0},
  151080. {0,0,&_16c0_s_p6_0},
  151081. {&_16c0_s_p7_0,&_16c0_s_p7_1},
  151082. {&_16c0_s_p8_0,&_16c0_s_p8_1},
  151083. {&_16c0_s_p9_0,&_16c0_s_p9_1,&_16c0_s_p9_2}
  151084. }
  151085. };
  151086. static static_bookblock _resbook_16s_1={
  151087. {
  151088. {0},
  151089. {0,0,&_16c1_s_p1_0},
  151090. {0,0,&_16c1_s_p2_0},
  151091. {0,0,&_16c1_s_p3_0},
  151092. {0,0,&_16c1_s_p4_0},
  151093. {0,0,&_16c1_s_p5_0},
  151094. {0,0,&_16c1_s_p6_0},
  151095. {&_16c1_s_p7_0,&_16c1_s_p7_1},
  151096. {&_16c1_s_p8_0,&_16c1_s_p8_1},
  151097. {&_16c1_s_p9_0,&_16c1_s_p9_1,&_16c1_s_p9_2}
  151098. }
  151099. };
  151100. static static_bookblock _resbook_16s_2={
  151101. {
  151102. {0},
  151103. {0,0,&_16c2_s_p1_0},
  151104. {0,0,&_16c2_s_p2_0},
  151105. {0,0,&_16c2_s_p3_0},
  151106. {0,0,&_16c2_s_p4_0},
  151107. {&_16c2_s_p5_0,&_16c2_s_p5_1},
  151108. {&_16c2_s_p6_0,&_16c2_s_p6_1},
  151109. {&_16c2_s_p7_0,&_16c2_s_p7_1},
  151110. {&_16c2_s_p8_0,&_16c2_s_p8_1},
  151111. {&_16c2_s_p9_0,&_16c2_s_p9_1,&_16c2_s_p9_2}
  151112. }
  151113. };
  151114. static vorbis_residue_template _res_16s_0[]={
  151115. {2,0, &_residue_44_mid,
  151116. &_huff_book__16c0_s_single,&_huff_book__16c0_s_single,
  151117. &_resbook_16s_0,&_resbook_16s_0},
  151118. };
  151119. static vorbis_residue_template _res_16s_1[]={
  151120. {2,0, &_residue_44_mid,
  151121. &_huff_book__16c1_s_short,&_huff_book__16c1_s_short,
  151122. &_resbook_16s_1,&_resbook_16s_1},
  151123. {2,0, &_residue_44_mid,
  151124. &_huff_book__16c1_s_long,&_huff_book__16c1_s_long,
  151125. &_resbook_16s_1,&_resbook_16s_1}
  151126. };
  151127. static vorbis_residue_template _res_16s_2[]={
  151128. {2,0, &_residue_44_high,
  151129. &_huff_book__16c2_s_short,&_huff_book__16c2_s_short,
  151130. &_resbook_16s_2,&_resbook_16s_2},
  151131. {2,0, &_residue_44_high,
  151132. &_huff_book__16c2_s_long,&_huff_book__16c2_s_long,
  151133. &_resbook_16s_2,&_resbook_16s_2}
  151134. };
  151135. static vorbis_mapping_template _mapres_template_16_stereo[3]={
  151136. { _map_nominal, _res_16s_0 }, /* 0 */
  151137. { _map_nominal, _res_16s_1 }, /* 1 */
  151138. { _map_nominal, _res_16s_2 }, /* 2 */
  151139. };
  151140. static static_bookblock _resbook_16u_0={
  151141. {
  151142. {0},
  151143. {0,0,&_16u0__p1_0},
  151144. {0,0,&_16u0__p2_0},
  151145. {0,0,&_16u0__p3_0},
  151146. {0,0,&_16u0__p4_0},
  151147. {0,0,&_16u0__p5_0},
  151148. {&_16u0__p6_0,&_16u0__p6_1},
  151149. {&_16u0__p7_0,&_16u0__p7_1,&_16u0__p7_2}
  151150. }
  151151. };
  151152. static static_bookblock _resbook_16u_1={
  151153. {
  151154. {0},
  151155. {0,0,&_16u1__p1_0},
  151156. {0,0,&_16u1__p2_0},
  151157. {0,0,&_16u1__p3_0},
  151158. {0,0,&_16u1__p4_0},
  151159. {0,0,&_16u1__p5_0},
  151160. {0,0,&_16u1__p6_0},
  151161. {&_16u1__p7_0,&_16u1__p7_1},
  151162. {&_16u1__p8_0,&_16u1__p8_1},
  151163. {&_16u1__p9_0,&_16u1__p9_1,&_16u1__p9_2}
  151164. }
  151165. };
  151166. static static_bookblock _resbook_16u_2={
  151167. {
  151168. {0},
  151169. {0,0,&_16u2_p1_0},
  151170. {0,0,&_16u2_p2_0},
  151171. {0,0,&_16u2_p3_0},
  151172. {0,0,&_16u2_p4_0},
  151173. {&_16u2_p5_0,&_16u2_p5_1},
  151174. {&_16u2_p6_0,&_16u2_p6_1},
  151175. {&_16u2_p7_0,&_16u2_p7_1},
  151176. {&_16u2_p8_0,&_16u2_p8_1},
  151177. {&_16u2_p9_0,&_16u2_p9_1,&_16u2_p9_2}
  151178. }
  151179. };
  151180. static vorbis_residue_template _res_16u_0[]={
  151181. {1,0, &_residue_44_low_un,
  151182. &_huff_book__16u0__single,&_huff_book__16u0__single,
  151183. &_resbook_16u_0,&_resbook_16u_0},
  151184. };
  151185. static vorbis_residue_template _res_16u_1[]={
  151186. {1,0, &_residue_44_mid_un,
  151187. &_huff_book__16u1__short,&_huff_book__16u1__short,
  151188. &_resbook_16u_1,&_resbook_16u_1},
  151189. {1,0, &_residue_44_mid_un,
  151190. &_huff_book__16u1__long,&_huff_book__16u1__long,
  151191. &_resbook_16u_1,&_resbook_16u_1}
  151192. };
  151193. static vorbis_residue_template _res_16u_2[]={
  151194. {1,0, &_residue_44_hi_un,
  151195. &_huff_book__16u2__short,&_huff_book__16u2__short,
  151196. &_resbook_16u_2,&_resbook_16u_2},
  151197. {1,0, &_residue_44_hi_un,
  151198. &_huff_book__16u2__long,&_huff_book__16u2__long,
  151199. &_resbook_16u_2,&_resbook_16u_2}
  151200. };
  151201. static vorbis_mapping_template _mapres_template_16_uncoupled[3]={
  151202. { _map_nominal_u, _res_16u_0 }, /* 0 */
  151203. { _map_nominal_u, _res_16u_1 }, /* 1 */
  151204. { _map_nominal_u, _res_16u_2 }, /* 2 */
  151205. };
  151206. /*** End of inlined file: residue_16.h ***/
  151207. static int blocksize_16_short[3]={
  151208. 1024,512,512
  151209. };
  151210. static int blocksize_16_long[3]={
  151211. 1024,1024,1024
  151212. };
  151213. static int _floor_mapping_16_short[3]={
  151214. 9,3,3
  151215. };
  151216. static int _floor_mapping_16[3]={
  151217. 9,9,9
  151218. };
  151219. static double rate_mapping_16[4]={
  151220. 12000.,20000.,44000.,86000.
  151221. };
  151222. static double rate_mapping_16_uncoupled[4]={
  151223. 16000.,28000.,64000.,100000.
  151224. };
  151225. static double _global_mapping_16[4]={ 1., 2., 3., 4. };
  151226. static double quality_mapping_16[4]={ -.1,.05,.5,1. };
  151227. static double _psy_compand_16_mapping[4]={ 0., .8, 1., 1.};
  151228. ve_setup_data_template ve_setup_16_stereo={
  151229. 3,
  151230. rate_mapping_16,
  151231. quality_mapping_16,
  151232. 2,
  151233. 15000,
  151234. 19000,
  151235. blocksize_16_short,
  151236. blocksize_16_long,
  151237. _psy_tone_masteratt_16,
  151238. _psy_tone_0dB,
  151239. _psy_tone_suppress,
  151240. _vp_tonemask_adj_16,
  151241. _vp_tonemask_adj_16,
  151242. _vp_tonemask_adj_16,
  151243. _psy_noiseguards_8,
  151244. _psy_noisebias_16_impulse,
  151245. _psy_noisebias_16_short,
  151246. _psy_noisebias_16_short,
  151247. _psy_noisebias_16,
  151248. _psy_noise_suppress,
  151249. _psy_compand_8,
  151250. _psy_compand_16_mapping,
  151251. _psy_compand_16_mapping,
  151252. {_noise_start_16,_noise_start_16},
  151253. { _noise_part_16, _noise_part_16},
  151254. _noise_thresh_16,
  151255. _psy_ath_floater_16,
  151256. _psy_ath_abs_16,
  151257. _psy_lowpass_16,
  151258. _psy_global_44,
  151259. _global_mapping_16,
  151260. _psy_stereo_modes_16,
  151261. _floor_books,
  151262. _floor,
  151263. _floor_mapping_16_short,
  151264. _floor_mapping_16,
  151265. _mapres_template_16_stereo
  151266. };
  151267. ve_setup_data_template ve_setup_16_uncoupled={
  151268. 3,
  151269. rate_mapping_16_uncoupled,
  151270. quality_mapping_16,
  151271. -1,
  151272. 15000,
  151273. 19000,
  151274. blocksize_16_short,
  151275. blocksize_16_long,
  151276. _psy_tone_masteratt_16,
  151277. _psy_tone_0dB,
  151278. _psy_tone_suppress,
  151279. _vp_tonemask_adj_16,
  151280. _vp_tonemask_adj_16,
  151281. _vp_tonemask_adj_16,
  151282. _psy_noiseguards_8,
  151283. _psy_noisebias_16_impulse,
  151284. _psy_noisebias_16_short,
  151285. _psy_noisebias_16_short,
  151286. _psy_noisebias_16,
  151287. _psy_noise_suppress,
  151288. _psy_compand_8,
  151289. _psy_compand_16_mapping,
  151290. _psy_compand_16_mapping,
  151291. {_noise_start_16,_noise_start_16},
  151292. { _noise_part_16, _noise_part_16},
  151293. _noise_thresh_16,
  151294. _psy_ath_floater_16,
  151295. _psy_ath_abs_16,
  151296. _psy_lowpass_16,
  151297. _psy_global_44,
  151298. _global_mapping_16,
  151299. _psy_stereo_modes_16,
  151300. _floor_books,
  151301. _floor,
  151302. _floor_mapping_16_short,
  151303. _floor_mapping_16,
  151304. _mapres_template_16_uncoupled
  151305. };
  151306. /*** End of inlined file: setup_16.h ***/
  151307. /*** Start of inlined file: setup_22.h ***/
  151308. static double rate_mapping_22[4]={
  151309. 15000.,20000.,44000.,86000.
  151310. };
  151311. static double rate_mapping_22_uncoupled[4]={
  151312. 16000.,28000.,50000.,90000.
  151313. };
  151314. static double _psy_lowpass_22[4]={9.5,11.,30.,99.};
  151315. ve_setup_data_template ve_setup_22_stereo={
  151316. 3,
  151317. rate_mapping_22,
  151318. quality_mapping_16,
  151319. 2,
  151320. 19000,
  151321. 26000,
  151322. blocksize_16_short,
  151323. blocksize_16_long,
  151324. _psy_tone_masteratt_16,
  151325. _psy_tone_0dB,
  151326. _psy_tone_suppress,
  151327. _vp_tonemask_adj_16,
  151328. _vp_tonemask_adj_16,
  151329. _vp_tonemask_adj_16,
  151330. _psy_noiseguards_8,
  151331. _psy_noisebias_16_impulse,
  151332. _psy_noisebias_16_short,
  151333. _psy_noisebias_16_short,
  151334. _psy_noisebias_16,
  151335. _psy_noise_suppress,
  151336. _psy_compand_8,
  151337. _psy_compand_8_mapping,
  151338. _psy_compand_8_mapping,
  151339. {_noise_start_16,_noise_start_16},
  151340. { _noise_part_16, _noise_part_16},
  151341. _noise_thresh_16,
  151342. _psy_ath_floater_16,
  151343. _psy_ath_abs_16,
  151344. _psy_lowpass_22,
  151345. _psy_global_44,
  151346. _global_mapping_16,
  151347. _psy_stereo_modes_16,
  151348. _floor_books,
  151349. _floor,
  151350. _floor_mapping_16_short,
  151351. _floor_mapping_16,
  151352. _mapres_template_16_stereo
  151353. };
  151354. ve_setup_data_template ve_setup_22_uncoupled={
  151355. 3,
  151356. rate_mapping_22_uncoupled,
  151357. quality_mapping_16,
  151358. -1,
  151359. 19000,
  151360. 26000,
  151361. blocksize_16_short,
  151362. blocksize_16_long,
  151363. _psy_tone_masteratt_16,
  151364. _psy_tone_0dB,
  151365. _psy_tone_suppress,
  151366. _vp_tonemask_adj_16,
  151367. _vp_tonemask_adj_16,
  151368. _vp_tonemask_adj_16,
  151369. _psy_noiseguards_8,
  151370. _psy_noisebias_16_impulse,
  151371. _psy_noisebias_16_short,
  151372. _psy_noisebias_16_short,
  151373. _psy_noisebias_16,
  151374. _psy_noise_suppress,
  151375. _psy_compand_8,
  151376. _psy_compand_8_mapping,
  151377. _psy_compand_8_mapping,
  151378. {_noise_start_16,_noise_start_16},
  151379. { _noise_part_16, _noise_part_16},
  151380. _noise_thresh_16,
  151381. _psy_ath_floater_16,
  151382. _psy_ath_abs_16,
  151383. _psy_lowpass_22,
  151384. _psy_global_44,
  151385. _global_mapping_16,
  151386. _psy_stereo_modes_16,
  151387. _floor_books,
  151388. _floor,
  151389. _floor_mapping_16_short,
  151390. _floor_mapping_16,
  151391. _mapres_template_16_uncoupled
  151392. };
  151393. /*** End of inlined file: setup_22.h ***/
  151394. /*** Start of inlined file: setup_X.h ***/
  151395. static double rate_mapping_X[12]={
  151396. -1.,-1.,-1.,-1.,-1.,-1.,
  151397. -1.,-1.,-1.,-1.,-1.,-1.
  151398. };
  151399. ve_setup_data_template ve_setup_X_stereo={
  151400. 11,
  151401. rate_mapping_X,
  151402. quality_mapping_44,
  151403. 2,
  151404. 50000,
  151405. 200000,
  151406. blocksize_short_44,
  151407. blocksize_long_44,
  151408. _psy_tone_masteratt_44,
  151409. _psy_tone_0dB,
  151410. _psy_tone_suppress,
  151411. _vp_tonemask_adj_otherblock,
  151412. _vp_tonemask_adj_longblock,
  151413. _vp_tonemask_adj_otherblock,
  151414. _psy_noiseguards_44,
  151415. _psy_noisebias_impulse,
  151416. _psy_noisebias_padding,
  151417. _psy_noisebias_trans,
  151418. _psy_noisebias_long,
  151419. _psy_noise_suppress,
  151420. _psy_compand_44,
  151421. _psy_compand_short_mapping,
  151422. _psy_compand_long_mapping,
  151423. {_noise_start_short_44,_noise_start_long_44},
  151424. {_noise_part_short_44,_noise_part_long_44},
  151425. _noise_thresh_44,
  151426. _psy_ath_floater,
  151427. _psy_ath_abs,
  151428. _psy_lowpass_44,
  151429. _psy_global_44,
  151430. _global_mapping_44,
  151431. _psy_stereo_modes_44,
  151432. _floor_books,
  151433. _floor,
  151434. _floor_short_mapping_44,
  151435. _floor_long_mapping_44,
  151436. _mapres_template_44_stereo
  151437. };
  151438. ve_setup_data_template ve_setup_X_uncoupled={
  151439. 11,
  151440. rate_mapping_X,
  151441. quality_mapping_44,
  151442. -1,
  151443. 50000,
  151444. 200000,
  151445. blocksize_short_44,
  151446. blocksize_long_44,
  151447. _psy_tone_masteratt_44,
  151448. _psy_tone_0dB,
  151449. _psy_tone_suppress,
  151450. _vp_tonemask_adj_otherblock,
  151451. _vp_tonemask_adj_longblock,
  151452. _vp_tonemask_adj_otherblock,
  151453. _psy_noiseguards_44,
  151454. _psy_noisebias_impulse,
  151455. _psy_noisebias_padding,
  151456. _psy_noisebias_trans,
  151457. _psy_noisebias_long,
  151458. _psy_noise_suppress,
  151459. _psy_compand_44,
  151460. _psy_compand_short_mapping,
  151461. _psy_compand_long_mapping,
  151462. {_noise_start_short_44,_noise_start_long_44},
  151463. {_noise_part_short_44,_noise_part_long_44},
  151464. _noise_thresh_44,
  151465. _psy_ath_floater,
  151466. _psy_ath_abs,
  151467. _psy_lowpass_44,
  151468. _psy_global_44,
  151469. _global_mapping_44,
  151470. NULL,
  151471. _floor_books,
  151472. _floor,
  151473. _floor_short_mapping_44,
  151474. _floor_long_mapping_44,
  151475. _mapres_template_44_uncoupled
  151476. };
  151477. ve_setup_data_template ve_setup_XX_stereo={
  151478. 2,
  151479. rate_mapping_X,
  151480. quality_mapping_8,
  151481. 2,
  151482. 0,
  151483. 8000,
  151484. blocksize_8,
  151485. blocksize_8,
  151486. _psy_tone_masteratt_8,
  151487. _psy_tone_0dB,
  151488. _psy_tone_suppress,
  151489. _vp_tonemask_adj_8,
  151490. NULL,
  151491. _vp_tonemask_adj_8,
  151492. _psy_noiseguards_8,
  151493. _psy_noisebias_8,
  151494. _psy_noisebias_8,
  151495. NULL,
  151496. NULL,
  151497. _psy_noise_suppress,
  151498. _psy_compand_8,
  151499. _psy_compand_8_mapping,
  151500. NULL,
  151501. {_noise_start_8,_noise_start_8},
  151502. {_noise_part_8,_noise_part_8},
  151503. _noise_thresh_5only,
  151504. _psy_ath_floater_8,
  151505. _psy_ath_abs_8,
  151506. _psy_lowpass_8,
  151507. _psy_global_44,
  151508. _global_mapping_8,
  151509. _psy_stereo_modes_8,
  151510. _floor_books,
  151511. _floor,
  151512. _floor_mapping_8,
  151513. NULL,
  151514. _mapres_template_8_stereo
  151515. };
  151516. ve_setup_data_template ve_setup_XX_uncoupled={
  151517. 2,
  151518. rate_mapping_X,
  151519. quality_mapping_8,
  151520. -1,
  151521. 0,
  151522. 8000,
  151523. blocksize_8,
  151524. blocksize_8,
  151525. _psy_tone_masteratt_8,
  151526. _psy_tone_0dB,
  151527. _psy_tone_suppress,
  151528. _vp_tonemask_adj_8,
  151529. NULL,
  151530. _vp_tonemask_adj_8,
  151531. _psy_noiseguards_8,
  151532. _psy_noisebias_8,
  151533. _psy_noisebias_8,
  151534. NULL,
  151535. NULL,
  151536. _psy_noise_suppress,
  151537. _psy_compand_8,
  151538. _psy_compand_8_mapping,
  151539. NULL,
  151540. {_noise_start_8,_noise_start_8},
  151541. {_noise_part_8,_noise_part_8},
  151542. _noise_thresh_5only,
  151543. _psy_ath_floater_8,
  151544. _psy_ath_abs_8,
  151545. _psy_lowpass_8,
  151546. _psy_global_44,
  151547. _global_mapping_8,
  151548. _psy_stereo_modes_8,
  151549. _floor_books,
  151550. _floor,
  151551. _floor_mapping_8,
  151552. NULL,
  151553. _mapres_template_8_uncoupled
  151554. };
  151555. /*** End of inlined file: setup_X.h ***/
  151556. static ve_setup_data_template *setup_list[]={
  151557. &ve_setup_44_stereo,
  151558. &ve_setup_44_uncoupled,
  151559. &ve_setup_32_stereo,
  151560. &ve_setup_32_uncoupled,
  151561. &ve_setup_22_stereo,
  151562. &ve_setup_22_uncoupled,
  151563. &ve_setup_16_stereo,
  151564. &ve_setup_16_uncoupled,
  151565. &ve_setup_11_stereo,
  151566. &ve_setup_11_uncoupled,
  151567. &ve_setup_8_stereo,
  151568. &ve_setup_8_uncoupled,
  151569. &ve_setup_X_stereo,
  151570. &ve_setup_X_uncoupled,
  151571. &ve_setup_XX_stereo,
  151572. &ve_setup_XX_uncoupled,
  151573. 0
  151574. };
  151575. static int vorbis_encode_toplevel_setup(vorbis_info *vi,int ch,long rate){
  151576. if(vi && vi->codec_setup){
  151577. vi->version=0;
  151578. vi->channels=ch;
  151579. vi->rate=rate;
  151580. return(0);
  151581. }
  151582. return(OV_EINVAL);
  151583. }
  151584. static void vorbis_encode_floor_setup(vorbis_info *vi,double s,int block,
  151585. static_codebook ***books,
  151586. vorbis_info_floor1 *in,
  151587. int *x){
  151588. int i,k,is=s;
  151589. vorbis_info_floor1 *f=(vorbis_info_floor1*) _ogg_calloc(1,sizeof(*f));
  151590. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  151591. memcpy(f,in+x[is],sizeof(*f));
  151592. /* fill in the lowpass field, even if it's temporary */
  151593. f->n=ci->blocksizes[block]>>1;
  151594. /* books */
  151595. {
  151596. int partitions=f->partitions;
  151597. int maxclass=-1;
  151598. int maxbook=-1;
  151599. for(i=0;i<partitions;i++)
  151600. if(f->partitionclass[i]>maxclass)maxclass=f->partitionclass[i];
  151601. for(i=0;i<=maxclass;i++){
  151602. if(f->class_book[i]>maxbook)maxbook=f->class_book[i];
  151603. f->class_book[i]+=ci->books;
  151604. for(k=0;k<(1<<f->class_subs[i]);k++){
  151605. if(f->class_subbook[i][k]>maxbook)maxbook=f->class_subbook[i][k];
  151606. if(f->class_subbook[i][k]>=0)f->class_subbook[i][k]+=ci->books;
  151607. }
  151608. }
  151609. for(i=0;i<=maxbook;i++)
  151610. ci->book_param[ci->books++]=books[x[is]][i];
  151611. }
  151612. /* for now, we're only using floor 1 */
  151613. ci->floor_type[ci->floors]=1;
  151614. ci->floor_param[ci->floors]=f;
  151615. ci->floors++;
  151616. return;
  151617. }
  151618. static void vorbis_encode_global_psych_setup(vorbis_info *vi,double s,
  151619. vorbis_info_psy_global *in,
  151620. double *x){
  151621. int i,is=s;
  151622. double ds=s-is;
  151623. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  151624. vorbis_info_psy_global *g=&ci->psy_g_param;
  151625. memcpy(g,in+(int)x[is],sizeof(*g));
  151626. ds=x[is]*(1.-ds)+x[is+1]*ds;
  151627. is=(int)ds;
  151628. ds-=is;
  151629. if(ds==0 && is>0){
  151630. is--;
  151631. ds=1.;
  151632. }
  151633. /* interpolate the trigger threshholds */
  151634. for(i=0;i<4;i++){
  151635. g->preecho_thresh[i]=in[is].preecho_thresh[i]*(1.-ds)+in[is+1].preecho_thresh[i]*ds;
  151636. g->postecho_thresh[i]=in[is].postecho_thresh[i]*(1.-ds)+in[is+1].postecho_thresh[i]*ds;
  151637. }
  151638. g->ampmax_att_per_sec=ci->hi.amplitude_track_dBpersec;
  151639. return;
  151640. }
  151641. static void vorbis_encode_global_stereo(vorbis_info *vi,
  151642. highlevel_encode_setup *hi,
  151643. adj_stereo *p){
  151644. float s=hi->stereo_point_setting;
  151645. int i,is=s;
  151646. double ds=s-is;
  151647. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  151648. vorbis_info_psy_global *g=&ci->psy_g_param;
  151649. if(p){
  151650. memcpy(g->coupling_prepointamp,p[is].pre,sizeof(*p[is].pre)*PACKETBLOBS);
  151651. memcpy(g->coupling_postpointamp,p[is].post,sizeof(*p[is].post)*PACKETBLOBS);
  151652. if(hi->managed){
  151653. /* interpolate the kHz threshholds */
  151654. for(i=0;i<PACKETBLOBS;i++){
  151655. float kHz=p[is].kHz[i]*(1.-ds)+p[is+1].kHz[i]*ds;
  151656. g->coupling_pointlimit[0][i]=kHz*1000./vi->rate*ci->blocksizes[0];
  151657. g->coupling_pointlimit[1][i]=kHz*1000./vi->rate*ci->blocksizes[1];
  151658. g->coupling_pkHz[i]=kHz;
  151659. kHz=p[is].lowpasskHz[i]*(1.-ds)+p[is+1].lowpasskHz[i]*ds;
  151660. g->sliding_lowpass[0][i]=kHz*1000./vi->rate*ci->blocksizes[0];
  151661. g->sliding_lowpass[1][i]=kHz*1000./vi->rate*ci->blocksizes[1];
  151662. }
  151663. }else{
  151664. float kHz=p[is].kHz[PACKETBLOBS/2]*(1.-ds)+p[is+1].kHz[PACKETBLOBS/2]*ds;
  151665. for(i=0;i<PACKETBLOBS;i++){
  151666. g->coupling_pointlimit[0][i]=kHz*1000./vi->rate*ci->blocksizes[0];
  151667. g->coupling_pointlimit[1][i]=kHz*1000./vi->rate*ci->blocksizes[1];
  151668. g->coupling_pkHz[i]=kHz;
  151669. }
  151670. kHz=p[is].lowpasskHz[PACKETBLOBS/2]*(1.-ds)+p[is+1].lowpasskHz[PACKETBLOBS/2]*ds;
  151671. for(i=0;i<PACKETBLOBS;i++){
  151672. g->sliding_lowpass[0][i]=kHz*1000./vi->rate*ci->blocksizes[0];
  151673. g->sliding_lowpass[1][i]=kHz*1000./vi->rate*ci->blocksizes[1];
  151674. }
  151675. }
  151676. }else{
  151677. for(i=0;i<PACKETBLOBS;i++){
  151678. g->sliding_lowpass[0][i]=ci->blocksizes[0];
  151679. g->sliding_lowpass[1][i]=ci->blocksizes[1];
  151680. }
  151681. }
  151682. return;
  151683. }
  151684. static void vorbis_encode_psyset_setup(vorbis_info *vi,double s,
  151685. int *nn_start,
  151686. int *nn_partition,
  151687. double *nn_thresh,
  151688. int block){
  151689. codec_setup_info *ci=(codec_setup_info*) vi->codec_setup;
  151690. vorbis_info_psy *p=ci->psy_param[block];
  151691. highlevel_encode_setup *hi=&ci->hi;
  151692. int is=s;
  151693. if(block>=ci->psys)
  151694. ci->psys=block+1;
  151695. if(!p){
  151696. p=(vorbis_info_psy*)_ogg_calloc(1,sizeof(*p));
  151697. ci->psy_param[block]=p;
  151698. }
  151699. memcpy(p,&_psy_info_template,sizeof(*p));
  151700. p->blockflag=block>>1;
  151701. if(hi->noise_normalize_p){
  151702. p->normal_channel_p=1;
  151703. p->normal_point_p=1;
  151704. p->normal_start=nn_start[is];
  151705. p->normal_partition=nn_partition[is];
  151706. p->normal_thresh=nn_thresh[is];
  151707. }
  151708. return;
  151709. }
  151710. static void vorbis_encode_tonemask_setup(vorbis_info *vi,double s,int block,
  151711. att3 *att,
  151712. int *max,
  151713. vp_adjblock *in){
  151714. int i,is=s;
  151715. double ds=s-is;
  151716. codec_setup_info *ci=(codec_setup_info*) vi->codec_setup;
  151717. vorbis_info_psy *p=ci->psy_param[block];
  151718. /* 0 and 2 are only used by bitmanagement, but there's no harm to always
  151719. filling the values in here */
  151720. p->tone_masteratt[0]=att[is].att[0]*(1.-ds)+att[is+1].att[0]*ds;
  151721. p->tone_masteratt[1]=att[is].att[1]*(1.-ds)+att[is+1].att[1]*ds;
  151722. p->tone_masteratt[2]=att[is].att[2]*(1.-ds)+att[is+1].att[2]*ds;
  151723. p->tone_centerboost=att[is].boost*(1.-ds)+att[is+1].boost*ds;
  151724. p->tone_decay=att[is].decay*(1.-ds)+att[is+1].decay*ds;
  151725. p->max_curve_dB=max[is]*(1.-ds)+max[is+1]*ds;
  151726. for(i=0;i<P_BANDS;i++)
  151727. p->toneatt[i]=in[is].block[i]*(1.-ds)+in[is+1].block[i]*ds;
  151728. return;
  151729. }
  151730. static void vorbis_encode_compand_setup(vorbis_info *vi,double s,int block,
  151731. compandblock *in, double *x){
  151732. int i,is=s;
  151733. double ds=s-is;
  151734. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  151735. vorbis_info_psy *p=ci->psy_param[block];
  151736. ds=x[is]*(1.-ds)+x[is+1]*ds;
  151737. is=(int)ds;
  151738. ds-=is;
  151739. if(ds==0 && is>0){
  151740. is--;
  151741. ds=1.;
  151742. }
  151743. /* interpolate the compander settings */
  151744. for(i=0;i<NOISE_COMPAND_LEVELS;i++)
  151745. p->noisecompand[i]=in[is].data[i]*(1.-ds)+in[is+1].data[i]*ds;
  151746. return;
  151747. }
  151748. static void vorbis_encode_peak_setup(vorbis_info *vi,double s,int block,
  151749. int *suppress){
  151750. int is=s;
  151751. double ds=s-is;
  151752. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  151753. vorbis_info_psy *p=ci->psy_param[block];
  151754. p->tone_abs_limit=suppress[is]*(1.-ds)+suppress[is+1]*ds;
  151755. return;
  151756. }
  151757. static void vorbis_encode_noisebias_setup(vorbis_info *vi,double s,int block,
  151758. int *suppress,
  151759. noise3 *in,
  151760. noiseguard *guard,
  151761. double userbias){
  151762. int i,is=s,j;
  151763. double ds=s-is;
  151764. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  151765. vorbis_info_psy *p=ci->psy_param[block];
  151766. p->noisemaxsupp=suppress[is]*(1.-ds)+suppress[is+1]*ds;
  151767. p->noisewindowlomin=guard[block].lo;
  151768. p->noisewindowhimin=guard[block].hi;
  151769. p->noisewindowfixed=guard[block].fixed;
  151770. for(j=0;j<P_NOISECURVES;j++)
  151771. for(i=0;i<P_BANDS;i++)
  151772. p->noiseoff[j][i]=in[is].data[j][i]*(1.-ds)+in[is+1].data[j][i]*ds;
  151773. /* impulse blocks may take a user specified bias to boost the
  151774. nominal/high noise encoding depth */
  151775. for(j=0;j<P_NOISECURVES;j++){
  151776. float min=p->noiseoff[j][0]+6; /* the lowest it can go */
  151777. for(i=0;i<P_BANDS;i++){
  151778. p->noiseoff[j][i]+=userbias;
  151779. if(p->noiseoff[j][i]<min)p->noiseoff[j][i]=min;
  151780. }
  151781. }
  151782. return;
  151783. }
  151784. static void vorbis_encode_ath_setup(vorbis_info *vi,int block){
  151785. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  151786. vorbis_info_psy *p=ci->psy_param[block];
  151787. p->ath_adjatt=ci->hi.ath_floating_dB;
  151788. p->ath_maxatt=ci->hi.ath_absolute_dB;
  151789. return;
  151790. }
  151791. static int book_dup_or_new(codec_setup_info *ci,static_codebook *book){
  151792. int i;
  151793. for(i=0;i<ci->books;i++)
  151794. if(ci->book_param[i]==book)return(i);
  151795. return(ci->books++);
  151796. }
  151797. static void vorbis_encode_blocksize_setup(vorbis_info *vi,double s,
  151798. int *shortb,int *longb){
  151799. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  151800. int is=s;
  151801. int blockshort=shortb[is];
  151802. int blocklong=longb[is];
  151803. ci->blocksizes[0]=blockshort;
  151804. ci->blocksizes[1]=blocklong;
  151805. }
  151806. static void vorbis_encode_residue_setup(vorbis_info *vi,
  151807. int number, int block,
  151808. vorbis_residue_template *res){
  151809. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  151810. int i,n;
  151811. vorbis_info_residue0 *r=(vorbis_info_residue0*)(ci->residue_param[number]=
  151812. (vorbis_info_residue0*)_ogg_malloc(sizeof(*r)));
  151813. memcpy(r,res->res,sizeof(*r));
  151814. if(ci->residues<=number)ci->residues=number+1;
  151815. switch(ci->blocksizes[block]){
  151816. case 64:case 128:case 256:
  151817. r->grouping=16;
  151818. break;
  151819. default:
  151820. r->grouping=32;
  151821. break;
  151822. }
  151823. ci->residue_type[number]=res->res_type;
  151824. /* to be adjusted by lowpass/pointlimit later */
  151825. n=r->end=ci->blocksizes[block]>>1;
  151826. if(res->res_type==2)
  151827. n=r->end*=vi->channels;
  151828. /* fill in all the books */
  151829. {
  151830. int booklist=0,k;
  151831. if(ci->hi.managed){
  151832. for(i=0;i<r->partitions;i++)
  151833. for(k=0;k<3;k++)
  151834. if(res->books_base_managed->books[i][k])
  151835. r->secondstages[i]|=(1<<k);
  151836. r->groupbook=book_dup_or_new(ci,res->book_aux_managed);
  151837. ci->book_param[r->groupbook]=res->book_aux_managed;
  151838. for(i=0;i<r->partitions;i++){
  151839. for(k=0;k<3;k++){
  151840. if(res->books_base_managed->books[i][k]){
  151841. int bookid=book_dup_or_new(ci,res->books_base_managed->books[i][k]);
  151842. r->booklist[booklist++]=bookid;
  151843. ci->book_param[bookid]=res->books_base_managed->books[i][k];
  151844. }
  151845. }
  151846. }
  151847. }else{
  151848. for(i=0;i<r->partitions;i++)
  151849. for(k=0;k<3;k++)
  151850. if(res->books_base->books[i][k])
  151851. r->secondstages[i]|=(1<<k);
  151852. r->groupbook=book_dup_or_new(ci,res->book_aux);
  151853. ci->book_param[r->groupbook]=res->book_aux;
  151854. for(i=0;i<r->partitions;i++){
  151855. for(k=0;k<3;k++){
  151856. if(res->books_base->books[i][k]){
  151857. int bookid=book_dup_or_new(ci,res->books_base->books[i][k]);
  151858. r->booklist[booklist++]=bookid;
  151859. ci->book_param[bookid]=res->books_base->books[i][k];
  151860. }
  151861. }
  151862. }
  151863. }
  151864. }
  151865. /* lowpass setup/pointlimit */
  151866. {
  151867. double freq=ci->hi.lowpass_kHz*1000.;
  151868. vorbis_info_floor1 *f=(vorbis_info_floor1*)ci->floor_param[block]; /* by convention */
  151869. double nyq=vi->rate/2.;
  151870. long blocksize=ci->blocksizes[block]>>1;
  151871. /* lowpass needs to be set in the floor and the residue. */
  151872. if(freq>nyq)freq=nyq;
  151873. /* in the floor, the granularity can be very fine; it doesn't alter
  151874. the encoding structure, only the samples used to fit the floor
  151875. approximation */
  151876. f->n=freq/nyq*blocksize;
  151877. /* this res may by limited by the maximum pointlimit of the mode,
  151878. not the lowpass. the floor is always lowpass limited. */
  151879. if(res->limit_type){
  151880. if(ci->hi.managed)
  151881. freq=ci->psy_g_param.coupling_pkHz[PACKETBLOBS-1]*1000.;
  151882. else
  151883. freq=ci->psy_g_param.coupling_pkHz[PACKETBLOBS/2]*1000.;
  151884. if(freq>nyq)freq=nyq;
  151885. }
  151886. /* in the residue, we're constrained, physically, by partition
  151887. boundaries. We still lowpass 'wherever', but we have to round up
  151888. here to next boundary, or the vorbis spec will round it *down* to
  151889. previous boundary in encode/decode */
  151890. if(ci->residue_type[block]==2)
  151891. r->end=(int)((freq/nyq*blocksize*2)/r->grouping+.9)* /* round up only if we're well past */
  151892. r->grouping;
  151893. else
  151894. r->end=(int)((freq/nyq*blocksize)/r->grouping+.9)* /* round up only if we're well past */
  151895. r->grouping;
  151896. }
  151897. }
  151898. /* we assume two maps in this encoder */
  151899. static void vorbis_encode_map_n_res_setup(vorbis_info *vi,double s,
  151900. vorbis_mapping_template *maps){
  151901. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  151902. int i,j,is=s,modes=2;
  151903. vorbis_info_mapping0 *map=maps[is].map;
  151904. vorbis_info_mode *mode=_mode_template;
  151905. vorbis_residue_template *res=maps[is].res;
  151906. if(ci->blocksizes[0]==ci->blocksizes[1])modes=1;
  151907. for(i=0;i<modes;i++){
  151908. ci->map_param[i]=_ogg_calloc(1,sizeof(*map));
  151909. ci->mode_param[i]=(vorbis_info_mode*)_ogg_calloc(1,sizeof(*mode));
  151910. memcpy(ci->mode_param[i],mode+i,sizeof(*_mode_template));
  151911. if(i>=ci->modes)ci->modes=i+1;
  151912. ci->map_type[i]=0;
  151913. memcpy(ci->map_param[i],map+i,sizeof(*map));
  151914. if(i>=ci->maps)ci->maps=i+1;
  151915. for(j=0;j<map[i].submaps;j++)
  151916. vorbis_encode_residue_setup(vi,map[i].residuesubmap[j],i
  151917. ,res+map[i].residuesubmap[j]);
  151918. }
  151919. }
  151920. static double setting_to_approx_bitrate(vorbis_info *vi){
  151921. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  151922. highlevel_encode_setup *hi=&ci->hi;
  151923. ve_setup_data_template *setup=(ve_setup_data_template *)hi->setup;
  151924. int is=hi->base_setting;
  151925. double ds=hi->base_setting-is;
  151926. int ch=vi->channels;
  151927. double *r=setup->rate_mapping;
  151928. if(r==NULL)
  151929. return(-1);
  151930. return((r[is]*(1.-ds)+r[is+1]*ds)*ch);
  151931. }
  151932. static void get_setup_template(vorbis_info *vi,
  151933. long ch,long srate,
  151934. double req,int q_or_bitrate){
  151935. int i=0,j;
  151936. codec_setup_info *ci=(codec_setup_info*) vi->codec_setup;
  151937. highlevel_encode_setup *hi=&ci->hi;
  151938. if(q_or_bitrate)req/=ch;
  151939. while(setup_list[i]){
  151940. if(setup_list[i]->coupling_restriction==-1 ||
  151941. setup_list[i]->coupling_restriction==ch){
  151942. if(srate>=setup_list[i]->samplerate_min_restriction &&
  151943. srate<=setup_list[i]->samplerate_max_restriction){
  151944. int mappings=setup_list[i]->mappings;
  151945. double *map=(q_or_bitrate?
  151946. setup_list[i]->rate_mapping:
  151947. setup_list[i]->quality_mapping);
  151948. /* the template matches. Does the requested quality mode
  151949. fall within this template's modes? */
  151950. if(req<map[0]){++i;continue;}
  151951. if(req>map[setup_list[i]->mappings]){++i;continue;}
  151952. for(j=0;j<mappings;j++)
  151953. if(req>=map[j] && req<map[j+1])break;
  151954. /* an all-points match */
  151955. hi->setup=setup_list[i];
  151956. if(j==mappings)
  151957. hi->base_setting=j-.001;
  151958. else{
  151959. float low=map[j];
  151960. float high=map[j+1];
  151961. float del=(req-low)/(high-low);
  151962. hi->base_setting=j+del;
  151963. }
  151964. return;
  151965. }
  151966. }
  151967. i++;
  151968. }
  151969. hi->setup=NULL;
  151970. }
  151971. /* encoders will need to use vorbis_info_init beforehand and call
  151972. vorbis_info clear when all done */
  151973. /* two interfaces; this, more detailed one, and later a convenience
  151974. layer on top */
  151975. /* the final setup call */
  151976. int vorbis_encode_setup_init(vorbis_info *vi){
  151977. int i0=0,singleblock=0;
  151978. codec_setup_info *ci=(codec_setup_info*) vi->codec_setup;
  151979. ve_setup_data_template *setup=NULL;
  151980. highlevel_encode_setup *hi=&ci->hi;
  151981. if(ci==NULL)return(OV_EINVAL);
  151982. if(!hi->impulse_block_p)i0=1;
  151983. /* too low/high an ATH floater is nonsensical, but doesn't break anything */
  151984. if(hi->ath_floating_dB>-80)hi->ath_floating_dB=-80;
  151985. if(hi->ath_floating_dB<-200)hi->ath_floating_dB=-200;
  151986. /* again, bound this to avoid the app shooting itself int he foot
  151987. too badly */
  151988. if(hi->amplitude_track_dBpersec>0.)hi->amplitude_track_dBpersec=0.;
  151989. if(hi->amplitude_track_dBpersec<-99999.)hi->amplitude_track_dBpersec=-99999.;
  151990. /* get the appropriate setup template; matches the fetch in previous
  151991. stages */
  151992. setup=(ve_setup_data_template *)hi->setup;
  151993. if(setup==NULL)return(OV_EINVAL);
  151994. hi->set_in_stone=1;
  151995. /* choose block sizes from configured sizes as well as paying
  151996. attention to long_block_p and short_block_p. If the configured
  151997. short and long blocks are the same length, we set long_block_p
  151998. and unset short_block_p */
  151999. vorbis_encode_blocksize_setup(vi,hi->base_setting,
  152000. setup->blocksize_short,
  152001. setup->blocksize_long);
  152002. if(ci->blocksizes[0]==ci->blocksizes[1])singleblock=1;
  152003. /* floor setup; choose proper floor params. Allocated on the floor
  152004. stack in order; if we alloc only long floor, it's 0 */
  152005. vorbis_encode_floor_setup(vi,hi->short_setting,0,
  152006. setup->floor_books,
  152007. setup->floor_params,
  152008. setup->floor_short_mapping);
  152009. if(!singleblock)
  152010. vorbis_encode_floor_setup(vi,hi->long_setting,1,
  152011. setup->floor_books,
  152012. setup->floor_params,
  152013. setup->floor_long_mapping);
  152014. /* setup of [mostly] short block detection and stereo*/
  152015. vorbis_encode_global_psych_setup(vi,hi->trigger_setting,
  152016. setup->global_params,
  152017. setup->global_mapping);
  152018. vorbis_encode_global_stereo(vi,hi,setup->stereo_modes);
  152019. /* basic psych setup and noise normalization */
  152020. vorbis_encode_psyset_setup(vi,hi->short_setting,
  152021. setup->psy_noise_normal_start[0],
  152022. setup->psy_noise_normal_partition[0],
  152023. setup->psy_noise_normal_thresh,
  152024. 0);
  152025. vorbis_encode_psyset_setup(vi,hi->short_setting,
  152026. setup->psy_noise_normal_start[0],
  152027. setup->psy_noise_normal_partition[0],
  152028. setup->psy_noise_normal_thresh,
  152029. 1);
  152030. if(!singleblock){
  152031. vorbis_encode_psyset_setup(vi,hi->long_setting,
  152032. setup->psy_noise_normal_start[1],
  152033. setup->psy_noise_normal_partition[1],
  152034. setup->psy_noise_normal_thresh,
  152035. 2);
  152036. vorbis_encode_psyset_setup(vi,hi->long_setting,
  152037. setup->psy_noise_normal_start[1],
  152038. setup->psy_noise_normal_partition[1],
  152039. setup->psy_noise_normal_thresh,
  152040. 3);
  152041. }
  152042. /* tone masking setup */
  152043. vorbis_encode_tonemask_setup(vi,hi->block[i0].tone_mask_setting,0,
  152044. setup->psy_tone_masteratt,
  152045. setup->psy_tone_0dB,
  152046. setup->psy_tone_adj_impulse);
  152047. vorbis_encode_tonemask_setup(vi,hi->block[1].tone_mask_setting,1,
  152048. setup->psy_tone_masteratt,
  152049. setup->psy_tone_0dB,
  152050. setup->psy_tone_adj_other);
  152051. if(!singleblock){
  152052. vorbis_encode_tonemask_setup(vi,hi->block[2].tone_mask_setting,2,
  152053. setup->psy_tone_masteratt,
  152054. setup->psy_tone_0dB,
  152055. setup->psy_tone_adj_other);
  152056. vorbis_encode_tonemask_setup(vi,hi->block[3].tone_mask_setting,3,
  152057. setup->psy_tone_masteratt,
  152058. setup->psy_tone_0dB,
  152059. setup->psy_tone_adj_long);
  152060. }
  152061. /* noise companding setup */
  152062. vorbis_encode_compand_setup(vi,hi->block[i0].noise_compand_setting,0,
  152063. setup->psy_noise_compand,
  152064. setup->psy_noise_compand_short_mapping);
  152065. vorbis_encode_compand_setup(vi,hi->block[1].noise_compand_setting,1,
  152066. setup->psy_noise_compand,
  152067. setup->psy_noise_compand_short_mapping);
  152068. if(!singleblock){
  152069. vorbis_encode_compand_setup(vi,hi->block[2].noise_compand_setting,2,
  152070. setup->psy_noise_compand,
  152071. setup->psy_noise_compand_long_mapping);
  152072. vorbis_encode_compand_setup(vi,hi->block[3].noise_compand_setting,3,
  152073. setup->psy_noise_compand,
  152074. setup->psy_noise_compand_long_mapping);
  152075. }
  152076. /* peak guarding setup */
  152077. vorbis_encode_peak_setup(vi,hi->block[i0].tone_peaklimit_setting,0,
  152078. setup->psy_tone_dBsuppress);
  152079. vorbis_encode_peak_setup(vi,hi->block[1].tone_peaklimit_setting,1,
  152080. setup->psy_tone_dBsuppress);
  152081. if(!singleblock){
  152082. vorbis_encode_peak_setup(vi,hi->block[2].tone_peaklimit_setting,2,
  152083. setup->psy_tone_dBsuppress);
  152084. vorbis_encode_peak_setup(vi,hi->block[3].tone_peaklimit_setting,3,
  152085. setup->psy_tone_dBsuppress);
  152086. }
  152087. /* noise bias setup */
  152088. vorbis_encode_noisebias_setup(vi,hi->block[i0].noise_bias_setting,0,
  152089. setup->psy_noise_dBsuppress,
  152090. setup->psy_noise_bias_impulse,
  152091. setup->psy_noiseguards,
  152092. (i0==0?hi->impulse_noisetune:0.));
  152093. vorbis_encode_noisebias_setup(vi,hi->block[1].noise_bias_setting,1,
  152094. setup->psy_noise_dBsuppress,
  152095. setup->psy_noise_bias_padding,
  152096. setup->psy_noiseguards,0.);
  152097. if(!singleblock){
  152098. vorbis_encode_noisebias_setup(vi,hi->block[2].noise_bias_setting,2,
  152099. setup->psy_noise_dBsuppress,
  152100. setup->psy_noise_bias_trans,
  152101. setup->psy_noiseguards,0.);
  152102. vorbis_encode_noisebias_setup(vi,hi->block[3].noise_bias_setting,3,
  152103. setup->psy_noise_dBsuppress,
  152104. setup->psy_noise_bias_long,
  152105. setup->psy_noiseguards,0.);
  152106. }
  152107. vorbis_encode_ath_setup(vi,0);
  152108. vorbis_encode_ath_setup(vi,1);
  152109. if(!singleblock){
  152110. vorbis_encode_ath_setup(vi,2);
  152111. vorbis_encode_ath_setup(vi,3);
  152112. }
  152113. vorbis_encode_map_n_res_setup(vi,hi->base_setting,setup->maps);
  152114. /* set bitrate readonlies and management */
  152115. if(hi->bitrate_av>0)
  152116. vi->bitrate_nominal=hi->bitrate_av;
  152117. else{
  152118. vi->bitrate_nominal=setting_to_approx_bitrate(vi);
  152119. }
  152120. vi->bitrate_lower=hi->bitrate_min;
  152121. vi->bitrate_upper=hi->bitrate_max;
  152122. if(hi->bitrate_av)
  152123. vi->bitrate_window=(double)hi->bitrate_reservoir/hi->bitrate_av;
  152124. else
  152125. vi->bitrate_window=0.;
  152126. if(hi->managed){
  152127. ci->bi.avg_rate=hi->bitrate_av;
  152128. ci->bi.min_rate=hi->bitrate_min;
  152129. ci->bi.max_rate=hi->bitrate_max;
  152130. ci->bi.reservoir_bits=hi->bitrate_reservoir;
  152131. ci->bi.reservoir_bias=
  152132. hi->bitrate_reservoir_bias;
  152133. ci->bi.slew_damp=hi->bitrate_av_damp;
  152134. }
  152135. return(0);
  152136. }
  152137. static int vorbis_encode_setup_setting(vorbis_info *vi,
  152138. long channels,
  152139. long rate){
  152140. int ret=0,i,is;
  152141. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  152142. highlevel_encode_setup *hi=&ci->hi;
  152143. ve_setup_data_template *setup=(ve_setup_data_template*) hi->setup;
  152144. double ds;
  152145. ret=vorbis_encode_toplevel_setup(vi,channels,rate);
  152146. if(ret)return(ret);
  152147. is=hi->base_setting;
  152148. ds=hi->base_setting-is;
  152149. hi->short_setting=hi->base_setting;
  152150. hi->long_setting=hi->base_setting;
  152151. hi->managed=0;
  152152. hi->impulse_block_p=1;
  152153. hi->noise_normalize_p=1;
  152154. hi->stereo_point_setting=hi->base_setting;
  152155. hi->lowpass_kHz=
  152156. setup->psy_lowpass[is]*(1.-ds)+setup->psy_lowpass[is+1]*ds;
  152157. hi->ath_floating_dB=setup->psy_ath_float[is]*(1.-ds)+
  152158. setup->psy_ath_float[is+1]*ds;
  152159. hi->ath_absolute_dB=setup->psy_ath_abs[is]*(1.-ds)+
  152160. setup->psy_ath_abs[is+1]*ds;
  152161. hi->amplitude_track_dBpersec=-6.;
  152162. hi->trigger_setting=hi->base_setting;
  152163. for(i=0;i<4;i++){
  152164. hi->block[i].tone_mask_setting=hi->base_setting;
  152165. hi->block[i].tone_peaklimit_setting=hi->base_setting;
  152166. hi->block[i].noise_bias_setting=hi->base_setting;
  152167. hi->block[i].noise_compand_setting=hi->base_setting;
  152168. }
  152169. return(ret);
  152170. }
  152171. int vorbis_encode_setup_vbr(vorbis_info *vi,
  152172. long channels,
  152173. long rate,
  152174. float quality){
  152175. codec_setup_info *ci=(codec_setup_info*) vi->codec_setup;
  152176. highlevel_encode_setup *hi=&ci->hi;
  152177. quality+=.0000001;
  152178. if(quality>=1.)quality=.9999;
  152179. get_setup_template(vi,channels,rate,quality,0);
  152180. if(!hi->setup)return OV_EIMPL;
  152181. return vorbis_encode_setup_setting(vi,channels,rate);
  152182. }
  152183. int vorbis_encode_init_vbr(vorbis_info *vi,
  152184. long channels,
  152185. long rate,
  152186. float base_quality /* 0. to 1. */
  152187. ){
  152188. int ret=0;
  152189. ret=vorbis_encode_setup_vbr(vi,channels,rate,base_quality);
  152190. if(ret){
  152191. vorbis_info_clear(vi);
  152192. return ret;
  152193. }
  152194. ret=vorbis_encode_setup_init(vi);
  152195. if(ret)
  152196. vorbis_info_clear(vi);
  152197. return(ret);
  152198. }
  152199. int vorbis_encode_setup_managed(vorbis_info *vi,
  152200. long channels,
  152201. long rate,
  152202. long max_bitrate,
  152203. long nominal_bitrate,
  152204. long min_bitrate){
  152205. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  152206. highlevel_encode_setup *hi=&ci->hi;
  152207. double tnominal=nominal_bitrate;
  152208. int ret=0;
  152209. if(nominal_bitrate<=0.){
  152210. if(max_bitrate>0.){
  152211. if(min_bitrate>0.)
  152212. nominal_bitrate=(max_bitrate+min_bitrate)*.5;
  152213. else
  152214. nominal_bitrate=max_bitrate*.875;
  152215. }else{
  152216. if(min_bitrate>0.){
  152217. nominal_bitrate=min_bitrate;
  152218. }else{
  152219. return(OV_EINVAL);
  152220. }
  152221. }
  152222. }
  152223. get_setup_template(vi,channels,rate,nominal_bitrate,1);
  152224. if(!hi->setup)return OV_EIMPL;
  152225. ret=vorbis_encode_setup_setting(vi,channels,rate);
  152226. if(ret){
  152227. vorbis_info_clear(vi);
  152228. return ret;
  152229. }
  152230. /* initialize management with sane defaults */
  152231. hi->managed=1;
  152232. hi->bitrate_min=min_bitrate;
  152233. hi->bitrate_max=max_bitrate;
  152234. hi->bitrate_av=tnominal;
  152235. hi->bitrate_av_damp=1.5f; /* full range in no less than 1.5 second */
  152236. hi->bitrate_reservoir=nominal_bitrate*2;
  152237. hi->bitrate_reservoir_bias=.1; /* bias toward hoarding bits */
  152238. return(ret);
  152239. }
  152240. int vorbis_encode_init(vorbis_info *vi,
  152241. long channels,
  152242. long rate,
  152243. long max_bitrate,
  152244. long nominal_bitrate,
  152245. long min_bitrate){
  152246. int ret=vorbis_encode_setup_managed(vi,channels,rate,
  152247. max_bitrate,
  152248. nominal_bitrate,
  152249. min_bitrate);
  152250. if(ret){
  152251. vorbis_info_clear(vi);
  152252. return(ret);
  152253. }
  152254. ret=vorbis_encode_setup_init(vi);
  152255. if(ret)
  152256. vorbis_info_clear(vi);
  152257. return(ret);
  152258. }
  152259. int vorbis_encode_ctl(vorbis_info *vi,int number,void *arg){
  152260. if(vi){
  152261. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  152262. highlevel_encode_setup *hi=&ci->hi;
  152263. int setp=(number&0xf); /* a read request has a low nibble of 0 */
  152264. if(setp && hi->set_in_stone)return(OV_EINVAL);
  152265. switch(number){
  152266. /* now deprecated *****************/
  152267. case OV_ECTL_RATEMANAGE_GET:
  152268. {
  152269. struct ovectl_ratemanage_arg *ai=
  152270. (struct ovectl_ratemanage_arg *)arg;
  152271. ai->management_active=hi->managed;
  152272. ai->bitrate_hard_window=ai->bitrate_av_window=
  152273. (double)hi->bitrate_reservoir/vi->rate;
  152274. ai->bitrate_av_window_center=1.;
  152275. ai->bitrate_hard_min=hi->bitrate_min;
  152276. ai->bitrate_hard_max=hi->bitrate_max;
  152277. ai->bitrate_av_lo=hi->bitrate_av;
  152278. ai->bitrate_av_hi=hi->bitrate_av;
  152279. }
  152280. return(0);
  152281. /* now deprecated *****************/
  152282. case OV_ECTL_RATEMANAGE_SET:
  152283. {
  152284. struct ovectl_ratemanage_arg *ai=
  152285. (struct ovectl_ratemanage_arg *)arg;
  152286. if(ai==NULL){
  152287. hi->managed=0;
  152288. }else{
  152289. hi->managed=ai->management_active;
  152290. vorbis_encode_ctl(vi,OV_ECTL_RATEMANAGE_AVG,arg);
  152291. vorbis_encode_ctl(vi,OV_ECTL_RATEMANAGE_HARD,arg);
  152292. }
  152293. }
  152294. return 0;
  152295. /* now deprecated *****************/
  152296. case OV_ECTL_RATEMANAGE_AVG:
  152297. {
  152298. struct ovectl_ratemanage_arg *ai=
  152299. (struct ovectl_ratemanage_arg *)arg;
  152300. if(ai==NULL){
  152301. hi->bitrate_av=0;
  152302. }else{
  152303. hi->bitrate_av=(ai->bitrate_av_lo+ai->bitrate_av_hi)*.5;
  152304. }
  152305. }
  152306. return(0);
  152307. /* now deprecated *****************/
  152308. case OV_ECTL_RATEMANAGE_HARD:
  152309. {
  152310. struct ovectl_ratemanage_arg *ai=
  152311. (struct ovectl_ratemanage_arg *)arg;
  152312. if(ai==NULL){
  152313. hi->bitrate_min=0;
  152314. hi->bitrate_max=0;
  152315. }else{
  152316. hi->bitrate_min=ai->bitrate_hard_min;
  152317. hi->bitrate_max=ai->bitrate_hard_max;
  152318. hi->bitrate_reservoir=ai->bitrate_hard_window*
  152319. (hi->bitrate_max+hi->bitrate_min)*.5;
  152320. }
  152321. if(hi->bitrate_reservoir<128.)
  152322. hi->bitrate_reservoir=128.;
  152323. }
  152324. return(0);
  152325. /* replacement ratemanage interface */
  152326. case OV_ECTL_RATEMANAGE2_GET:
  152327. {
  152328. struct ovectl_ratemanage2_arg *ai=
  152329. (struct ovectl_ratemanage2_arg *)arg;
  152330. if(ai==NULL)return OV_EINVAL;
  152331. ai->management_active=hi->managed;
  152332. ai->bitrate_limit_min_kbps=hi->bitrate_min/1000;
  152333. ai->bitrate_limit_max_kbps=hi->bitrate_max/1000;
  152334. ai->bitrate_average_kbps=hi->bitrate_av/1000;
  152335. ai->bitrate_average_damping=hi->bitrate_av_damp;
  152336. ai->bitrate_limit_reservoir_bits=hi->bitrate_reservoir;
  152337. ai->bitrate_limit_reservoir_bias=hi->bitrate_reservoir_bias;
  152338. }
  152339. return (0);
  152340. case OV_ECTL_RATEMANAGE2_SET:
  152341. {
  152342. struct ovectl_ratemanage2_arg *ai=
  152343. (struct ovectl_ratemanage2_arg *)arg;
  152344. if(ai==NULL){
  152345. hi->managed=0;
  152346. }else{
  152347. /* sanity check; only catch invariant violations */
  152348. if(ai->bitrate_limit_min_kbps>0 &&
  152349. ai->bitrate_average_kbps>0 &&
  152350. ai->bitrate_limit_min_kbps>ai->bitrate_average_kbps)
  152351. return OV_EINVAL;
  152352. if(ai->bitrate_limit_max_kbps>0 &&
  152353. ai->bitrate_average_kbps>0 &&
  152354. ai->bitrate_limit_max_kbps<ai->bitrate_average_kbps)
  152355. return OV_EINVAL;
  152356. if(ai->bitrate_limit_min_kbps>0 &&
  152357. ai->bitrate_limit_max_kbps>0 &&
  152358. ai->bitrate_limit_min_kbps>ai->bitrate_limit_max_kbps)
  152359. return OV_EINVAL;
  152360. if(ai->bitrate_average_damping <= 0.)
  152361. return OV_EINVAL;
  152362. if(ai->bitrate_limit_reservoir_bits < 0)
  152363. return OV_EINVAL;
  152364. if(ai->bitrate_limit_reservoir_bias < 0.)
  152365. return OV_EINVAL;
  152366. if(ai->bitrate_limit_reservoir_bias > 1.)
  152367. return OV_EINVAL;
  152368. hi->managed=ai->management_active;
  152369. hi->bitrate_min=ai->bitrate_limit_min_kbps * 1000;
  152370. hi->bitrate_max=ai->bitrate_limit_max_kbps * 1000;
  152371. hi->bitrate_av=ai->bitrate_average_kbps * 1000;
  152372. hi->bitrate_av_damp=ai->bitrate_average_damping;
  152373. hi->bitrate_reservoir=ai->bitrate_limit_reservoir_bits;
  152374. hi->bitrate_reservoir_bias=ai->bitrate_limit_reservoir_bias;
  152375. }
  152376. }
  152377. return 0;
  152378. case OV_ECTL_LOWPASS_GET:
  152379. {
  152380. double *farg=(double *)arg;
  152381. *farg=hi->lowpass_kHz;
  152382. }
  152383. return(0);
  152384. case OV_ECTL_LOWPASS_SET:
  152385. {
  152386. double *farg=(double *)arg;
  152387. hi->lowpass_kHz=*farg;
  152388. if(hi->lowpass_kHz<2.)hi->lowpass_kHz=2.;
  152389. if(hi->lowpass_kHz>99.)hi->lowpass_kHz=99.;
  152390. }
  152391. return(0);
  152392. case OV_ECTL_IBLOCK_GET:
  152393. {
  152394. double *farg=(double *)arg;
  152395. *farg=hi->impulse_noisetune;
  152396. }
  152397. return(0);
  152398. case OV_ECTL_IBLOCK_SET:
  152399. {
  152400. double *farg=(double *)arg;
  152401. hi->impulse_noisetune=*farg;
  152402. if(hi->impulse_noisetune>0.)hi->impulse_noisetune=0.;
  152403. if(hi->impulse_noisetune<-15.)hi->impulse_noisetune=-15.;
  152404. }
  152405. return(0);
  152406. }
  152407. return(OV_EIMPL);
  152408. }
  152409. return(OV_EINVAL);
  152410. }
  152411. #endif
  152412. /*** End of inlined file: vorbisenc.c ***/
  152413. /*** Start of inlined file: vorbisfile.c ***/
  152414. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  152415. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  152416. // tasks..
  152417. #if JUCE_MSVC
  152418. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  152419. #endif
  152420. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  152421. #if JUCE_USE_OGGVORBIS
  152422. #include <stdlib.h>
  152423. #include <stdio.h>
  152424. #include <errno.h>
  152425. #include <string.h>
  152426. #include <math.h>
  152427. /* A 'chained bitstream' is a Vorbis bitstream that contains more than
  152428. one logical bitstream arranged end to end (the only form of Ogg
  152429. multiplexing allowed in a Vorbis bitstream; grouping [parallel
  152430. multiplexing] is not allowed in Vorbis) */
  152431. /* A Vorbis file can be played beginning to end (streamed) without
  152432. worrying ahead of time about chaining (see decoder_example.c). If
  152433. we have the whole file, however, and want random access
  152434. (seeking/scrubbing) or desire to know the total length/time of a
  152435. file, we need to account for the possibility of chaining. */
  152436. /* We can handle things a number of ways; we can determine the entire
  152437. bitstream structure right off the bat, or find pieces on demand.
  152438. This example determines and caches structure for the entire
  152439. bitstream, but builds a virtual decoder on the fly when moving
  152440. between links in the chain. */
  152441. /* There are also different ways to implement seeking. Enough
  152442. information exists in an Ogg bitstream to seek to
  152443. sample-granularity positions in the output. Or, one can seek by
  152444. picking some portion of the stream roughly in the desired area if
  152445. we only want coarse navigation through the stream. */
  152446. /*************************************************************************
  152447. * Many, many internal helpers. The intention is not to be confusing;
  152448. * rampant duplication and monolithic function implementation would be
  152449. * harder to understand anyway. The high level functions are last. Begin
  152450. * grokking near the end of the file */
  152451. /* read a little more data from the file/pipe into the ogg_sync framer
  152452. */
  152453. #define CHUNKSIZE 8500 /* a shade over 8k; anyone using pages well
  152454. over 8k gets what they deserve */
  152455. static long _get_data(OggVorbis_File *vf){
  152456. errno=0;
  152457. if(vf->datasource){
  152458. char *buffer=ogg_sync_buffer(&vf->oy,CHUNKSIZE);
  152459. long bytes=(vf->callbacks.read_func)(buffer,1,CHUNKSIZE,vf->datasource);
  152460. if(bytes>0)ogg_sync_wrote(&vf->oy,bytes);
  152461. if(bytes==0 && errno)return(-1);
  152462. return(bytes);
  152463. }else
  152464. return(0);
  152465. }
  152466. /* save a tiny smidge of verbosity to make the code more readable */
  152467. static void _seek_helper(OggVorbis_File *vf,ogg_int64_t offset){
  152468. if(vf->datasource){
  152469. (vf->callbacks.seek_func)(vf->datasource, offset, SEEK_SET);
  152470. vf->offset=offset;
  152471. ogg_sync_reset(&vf->oy);
  152472. }else{
  152473. /* shouldn't happen unless someone writes a broken callback */
  152474. return;
  152475. }
  152476. }
  152477. /* The read/seek functions track absolute position within the stream */
  152478. /* from the head of the stream, get the next page. boundary specifies
  152479. if the function is allowed to fetch more data from the stream (and
  152480. how much) or only use internally buffered data.
  152481. boundary: -1) unbounded search
  152482. 0) read no additional data; use cached only
  152483. n) search for a new page beginning for n bytes
  152484. return: <0) did not find a page (OV_FALSE, OV_EOF, OV_EREAD)
  152485. n) found a page at absolute offset n */
  152486. static ogg_int64_t _get_next_page(OggVorbis_File *vf,ogg_page *og,
  152487. ogg_int64_t boundary){
  152488. if(boundary>0)boundary+=vf->offset;
  152489. while(1){
  152490. long more;
  152491. if(boundary>0 && vf->offset>=boundary)return(OV_FALSE);
  152492. more=ogg_sync_pageseek(&vf->oy,og);
  152493. if(more<0){
  152494. /* skipped n bytes */
  152495. vf->offset-=more;
  152496. }else{
  152497. if(more==0){
  152498. /* send more paramedics */
  152499. if(!boundary)return(OV_FALSE);
  152500. {
  152501. long ret=_get_data(vf);
  152502. if(ret==0)return(OV_EOF);
  152503. if(ret<0)return(OV_EREAD);
  152504. }
  152505. }else{
  152506. /* got a page. Return the offset at the page beginning,
  152507. advance the internal offset past the page end */
  152508. ogg_int64_t ret=vf->offset;
  152509. vf->offset+=more;
  152510. return(ret);
  152511. }
  152512. }
  152513. }
  152514. }
  152515. /* find the latest page beginning before the current stream cursor
  152516. position. Much dirtier than the above as Ogg doesn't have any
  152517. backward search linkage. no 'readp' as it will certainly have to
  152518. read. */
  152519. /* returns offset or OV_EREAD, OV_FAULT */
  152520. static ogg_int64_t _get_prev_page(OggVorbis_File *vf,ogg_page *og){
  152521. ogg_int64_t begin=vf->offset;
  152522. ogg_int64_t end=begin;
  152523. ogg_int64_t ret;
  152524. ogg_int64_t offset=-1;
  152525. while(offset==-1){
  152526. begin-=CHUNKSIZE;
  152527. if(begin<0)
  152528. begin=0;
  152529. _seek_helper(vf,begin);
  152530. while(vf->offset<end){
  152531. ret=_get_next_page(vf,og,end-vf->offset);
  152532. if(ret==OV_EREAD)return(OV_EREAD);
  152533. if(ret<0){
  152534. break;
  152535. }else{
  152536. offset=ret;
  152537. }
  152538. }
  152539. }
  152540. /* we have the offset. Actually snork and hold the page now */
  152541. _seek_helper(vf,offset);
  152542. ret=_get_next_page(vf,og,CHUNKSIZE);
  152543. if(ret<0)
  152544. /* this shouldn't be possible */
  152545. return(OV_EFAULT);
  152546. return(offset);
  152547. }
  152548. /* finds each bitstream link one at a time using a bisection search
  152549. (has to begin by knowing the offset of the lb's initial page).
  152550. Recurses for each link so it can alloc the link storage after
  152551. finding them all, then unroll and fill the cache at the same time */
  152552. static int _bisect_forward_serialno(OggVorbis_File *vf,
  152553. ogg_int64_t begin,
  152554. ogg_int64_t searched,
  152555. ogg_int64_t end,
  152556. long currentno,
  152557. long m){
  152558. ogg_int64_t endsearched=end;
  152559. ogg_int64_t next=end;
  152560. ogg_page og;
  152561. ogg_int64_t ret;
  152562. /* the below guards against garbage seperating the last and
  152563. first pages of two links. */
  152564. while(searched<endsearched){
  152565. ogg_int64_t bisect;
  152566. if(endsearched-searched<CHUNKSIZE){
  152567. bisect=searched;
  152568. }else{
  152569. bisect=(searched+endsearched)/2;
  152570. }
  152571. _seek_helper(vf,bisect);
  152572. ret=_get_next_page(vf,&og,-1);
  152573. if(ret==OV_EREAD)return(OV_EREAD);
  152574. if(ret<0 || ogg_page_serialno(&og)!=currentno){
  152575. endsearched=bisect;
  152576. if(ret>=0)next=ret;
  152577. }else{
  152578. searched=ret+og.header_len+og.body_len;
  152579. }
  152580. }
  152581. _seek_helper(vf,next);
  152582. ret=_get_next_page(vf,&og,-1);
  152583. if(ret==OV_EREAD)return(OV_EREAD);
  152584. if(searched>=end || ret<0){
  152585. vf->links=m+1;
  152586. vf->offsets=(ogg_int64_t*)_ogg_malloc((vf->links+1)*sizeof(*vf->offsets));
  152587. vf->serialnos=(long*)_ogg_malloc(vf->links*sizeof(*vf->serialnos));
  152588. vf->offsets[m+1]=searched;
  152589. }else{
  152590. ret=_bisect_forward_serialno(vf,next,vf->offset,
  152591. end,ogg_page_serialno(&og),m+1);
  152592. if(ret==OV_EREAD)return(OV_EREAD);
  152593. }
  152594. vf->offsets[m]=begin;
  152595. vf->serialnos[m]=currentno;
  152596. return(0);
  152597. }
  152598. /* uses the local ogg_stream storage in vf; this is important for
  152599. non-streaming input sources */
  152600. static int _fetch_headers(OggVorbis_File *vf,vorbis_info *vi,vorbis_comment *vc,
  152601. long *serialno,ogg_page *og_ptr){
  152602. ogg_page og;
  152603. ogg_packet op;
  152604. int i,ret;
  152605. if(!og_ptr){
  152606. ogg_int64_t llret=_get_next_page(vf,&og,CHUNKSIZE);
  152607. if(llret==OV_EREAD)return(OV_EREAD);
  152608. if(llret<0)return OV_ENOTVORBIS;
  152609. og_ptr=&og;
  152610. }
  152611. ogg_stream_reset_serialno(&vf->os,ogg_page_serialno(og_ptr));
  152612. if(serialno)*serialno=vf->os.serialno;
  152613. vf->ready_state=STREAMSET;
  152614. /* extract the initial header from the first page and verify that the
  152615. Ogg bitstream is in fact Vorbis data */
  152616. vorbis_info_init(vi);
  152617. vorbis_comment_init(vc);
  152618. i=0;
  152619. while(i<3){
  152620. ogg_stream_pagein(&vf->os,og_ptr);
  152621. while(i<3){
  152622. int result=ogg_stream_packetout(&vf->os,&op);
  152623. if(result==0)break;
  152624. if(result==-1){
  152625. ret=OV_EBADHEADER;
  152626. goto bail_header;
  152627. }
  152628. if((ret=vorbis_synthesis_headerin(vi,vc,&op))){
  152629. goto bail_header;
  152630. }
  152631. i++;
  152632. }
  152633. if(i<3)
  152634. if(_get_next_page(vf,og_ptr,CHUNKSIZE)<0){
  152635. ret=OV_EBADHEADER;
  152636. goto bail_header;
  152637. }
  152638. }
  152639. return 0;
  152640. bail_header:
  152641. vorbis_info_clear(vi);
  152642. vorbis_comment_clear(vc);
  152643. vf->ready_state=OPENED;
  152644. return ret;
  152645. }
  152646. /* last step of the OggVorbis_File initialization; get all the
  152647. vorbis_info structs and PCM positions. Only called by the seekable
  152648. initialization (local stream storage is hacked slightly; pay
  152649. attention to how that's done) */
  152650. /* this is void and does not propogate errors up because we want to be
  152651. able to open and use damaged bitstreams as well as we can. Just
  152652. watch out for missing information for links in the OggVorbis_File
  152653. struct */
  152654. static void _prefetch_all_headers(OggVorbis_File *vf, ogg_int64_t dataoffset){
  152655. ogg_page og;
  152656. int i;
  152657. ogg_int64_t ret;
  152658. vf->vi=(vorbis_info*) _ogg_realloc(vf->vi,vf->links*sizeof(*vf->vi));
  152659. vf->vc=(vorbis_comment*) _ogg_realloc(vf->vc,vf->links*sizeof(*vf->vc));
  152660. vf->dataoffsets=(ogg_int64_t*) _ogg_malloc(vf->links*sizeof(*vf->dataoffsets));
  152661. vf->pcmlengths=(ogg_int64_t*) _ogg_malloc(vf->links*2*sizeof(*vf->pcmlengths));
  152662. for(i=0;i<vf->links;i++){
  152663. if(i==0){
  152664. /* we already grabbed the initial header earlier. Just set the offset */
  152665. vf->dataoffsets[i]=dataoffset;
  152666. _seek_helper(vf,dataoffset);
  152667. }else{
  152668. /* seek to the location of the initial header */
  152669. _seek_helper(vf,vf->offsets[i]);
  152670. if(_fetch_headers(vf,vf->vi+i,vf->vc+i,NULL,NULL)<0){
  152671. vf->dataoffsets[i]=-1;
  152672. }else{
  152673. vf->dataoffsets[i]=vf->offset;
  152674. }
  152675. }
  152676. /* fetch beginning PCM offset */
  152677. if(vf->dataoffsets[i]!=-1){
  152678. ogg_int64_t accumulated=0;
  152679. long lastblock=-1;
  152680. int result;
  152681. ogg_stream_reset_serialno(&vf->os,vf->serialnos[i]);
  152682. while(1){
  152683. ogg_packet op;
  152684. ret=_get_next_page(vf,&og,-1);
  152685. if(ret<0)
  152686. /* this should not be possible unless the file is
  152687. truncated/mangled */
  152688. break;
  152689. if(ogg_page_serialno(&og)!=vf->serialnos[i])
  152690. break;
  152691. /* count blocksizes of all frames in the page */
  152692. ogg_stream_pagein(&vf->os,&og);
  152693. while((result=ogg_stream_packetout(&vf->os,&op))){
  152694. if(result>0){ /* ignore holes */
  152695. long thisblock=vorbis_packet_blocksize(vf->vi+i,&op);
  152696. if(lastblock!=-1)
  152697. accumulated+=(lastblock+thisblock)>>2;
  152698. lastblock=thisblock;
  152699. }
  152700. }
  152701. if(ogg_page_granulepos(&og)!=-1){
  152702. /* pcm offset of last packet on the first audio page */
  152703. accumulated= ogg_page_granulepos(&og)-accumulated;
  152704. break;
  152705. }
  152706. }
  152707. /* less than zero? This is a stream with samples trimmed off
  152708. the beginning, a normal occurrence; set the offset to zero */
  152709. if(accumulated<0)accumulated=0;
  152710. vf->pcmlengths[i*2]=accumulated;
  152711. }
  152712. /* get the PCM length of this link. To do this,
  152713. get the last page of the stream */
  152714. {
  152715. ogg_int64_t end=vf->offsets[i+1];
  152716. _seek_helper(vf,end);
  152717. while(1){
  152718. ret=_get_prev_page(vf,&og);
  152719. if(ret<0){
  152720. /* this should not be possible */
  152721. vorbis_info_clear(vf->vi+i);
  152722. vorbis_comment_clear(vf->vc+i);
  152723. break;
  152724. }
  152725. if(ogg_page_granulepos(&og)!=-1){
  152726. vf->pcmlengths[i*2+1]=ogg_page_granulepos(&og)-vf->pcmlengths[i*2];
  152727. break;
  152728. }
  152729. vf->offset=ret;
  152730. }
  152731. }
  152732. }
  152733. }
  152734. static int _make_decode_ready(OggVorbis_File *vf){
  152735. if(vf->ready_state>STREAMSET)return 0;
  152736. if(vf->ready_state<STREAMSET)return OV_EFAULT;
  152737. if(vf->seekable){
  152738. if(vorbis_synthesis_init(&vf->vd,vf->vi+vf->current_link))
  152739. return OV_EBADLINK;
  152740. }else{
  152741. if(vorbis_synthesis_init(&vf->vd,vf->vi))
  152742. return OV_EBADLINK;
  152743. }
  152744. vorbis_block_init(&vf->vd,&vf->vb);
  152745. vf->ready_state=INITSET;
  152746. vf->bittrack=0.f;
  152747. vf->samptrack=0.f;
  152748. return 0;
  152749. }
  152750. static int _open_seekable2(OggVorbis_File *vf){
  152751. long serialno=vf->current_serialno;
  152752. ogg_int64_t dataoffset=vf->offset, end;
  152753. ogg_page og;
  152754. /* we're partially open and have a first link header state in
  152755. storage in vf */
  152756. /* we can seek, so set out learning all about this file */
  152757. (vf->callbacks.seek_func)(vf->datasource,0,SEEK_END);
  152758. vf->offset=vf->end=(vf->callbacks.tell_func)(vf->datasource);
  152759. /* We get the offset for the last page of the physical bitstream.
  152760. Most OggVorbis files will contain a single logical bitstream */
  152761. end=_get_prev_page(vf,&og);
  152762. if(end<0)return(end);
  152763. /* more than one logical bitstream? */
  152764. if(ogg_page_serialno(&og)!=serialno){
  152765. /* Chained bitstream. Bisect-search each logical bitstream
  152766. section. Do so based on serial number only */
  152767. if(_bisect_forward_serialno(vf,0,0,end+1,serialno,0)<0)return(OV_EREAD);
  152768. }else{
  152769. /* Only one logical bitstream */
  152770. if(_bisect_forward_serialno(vf,0,end,end+1,serialno,0))return(OV_EREAD);
  152771. }
  152772. /* the initial header memory is referenced by vf after; don't free it */
  152773. _prefetch_all_headers(vf,dataoffset);
  152774. return(ov_raw_seek(vf,0));
  152775. }
  152776. /* clear out the current logical bitstream decoder */
  152777. static void _decode_clear(OggVorbis_File *vf){
  152778. vorbis_dsp_clear(&vf->vd);
  152779. vorbis_block_clear(&vf->vb);
  152780. vf->ready_state=OPENED;
  152781. }
  152782. /* fetch and process a packet. Handles the case where we're at a
  152783. bitstream boundary and dumps the decoding machine. If the decoding
  152784. machine is unloaded, it loads it. It also keeps pcm_offset up to
  152785. date (seek and read both use this. seek uses a special hack with
  152786. readp).
  152787. return: <0) error, OV_HOLE (lost packet) or OV_EOF
  152788. 0) need more data (only if readp==0)
  152789. 1) got a packet
  152790. */
  152791. static int _fetch_and_process_packet(OggVorbis_File *vf,
  152792. ogg_packet *op_in,
  152793. int readp,
  152794. int spanp){
  152795. ogg_page og;
  152796. /* handle one packet. Try to fetch it from current stream state */
  152797. /* extract packets from page */
  152798. while(1){
  152799. /* process a packet if we can. If the machine isn't loaded,
  152800. neither is a page */
  152801. if(vf->ready_state==INITSET){
  152802. while(1) {
  152803. ogg_packet op;
  152804. ogg_packet *op_ptr=(op_in?op_in:&op);
  152805. int result=ogg_stream_packetout(&vf->os,op_ptr);
  152806. ogg_int64_t granulepos;
  152807. op_in=NULL;
  152808. if(result==-1)return(OV_HOLE); /* hole in the data. */
  152809. if(result>0){
  152810. /* got a packet. process it */
  152811. granulepos=op_ptr->granulepos;
  152812. if(!vorbis_synthesis(&vf->vb,op_ptr)){ /* lazy check for lazy
  152813. header handling. The
  152814. header packets aren't
  152815. audio, so if/when we
  152816. submit them,
  152817. vorbis_synthesis will
  152818. reject them */
  152819. /* suck in the synthesis data and track bitrate */
  152820. {
  152821. int oldsamples=vorbis_synthesis_pcmout(&vf->vd,NULL);
  152822. /* for proper use of libvorbis within libvorbisfile,
  152823. oldsamples will always be zero. */
  152824. if(oldsamples)return(OV_EFAULT);
  152825. vorbis_synthesis_blockin(&vf->vd,&vf->vb);
  152826. vf->samptrack+=vorbis_synthesis_pcmout(&vf->vd,NULL)-oldsamples;
  152827. vf->bittrack+=op_ptr->bytes*8;
  152828. }
  152829. /* update the pcm offset. */
  152830. if(granulepos!=-1 && !op_ptr->e_o_s){
  152831. int link=(vf->seekable?vf->current_link:0);
  152832. int i,samples;
  152833. /* this packet has a pcm_offset on it (the last packet
  152834. completed on a page carries the offset) After processing
  152835. (above), we know the pcm position of the *last* sample
  152836. ready to be returned. Find the offset of the *first*
  152837. As an aside, this trick is inaccurate if we begin
  152838. reading anew right at the last page; the end-of-stream
  152839. granulepos declares the last frame in the stream, and the
  152840. last packet of the last page may be a partial frame.
  152841. So, we need a previous granulepos from an in-sequence page
  152842. to have a reference point. Thus the !op_ptr->e_o_s clause
  152843. above */
  152844. if(vf->seekable && link>0)
  152845. granulepos-=vf->pcmlengths[link*2];
  152846. if(granulepos<0)granulepos=0; /* actually, this
  152847. shouldn't be possible
  152848. here unless the stream
  152849. is very broken */
  152850. samples=vorbis_synthesis_pcmout(&vf->vd,NULL);
  152851. granulepos-=samples;
  152852. for(i=0;i<link;i++)
  152853. granulepos+=vf->pcmlengths[i*2+1];
  152854. vf->pcm_offset=granulepos;
  152855. }
  152856. return(1);
  152857. }
  152858. }
  152859. else
  152860. break;
  152861. }
  152862. }
  152863. if(vf->ready_state>=OPENED){
  152864. ogg_int64_t ret;
  152865. if(!readp)return(0);
  152866. if((ret=_get_next_page(vf,&og,-1))<0){
  152867. return(OV_EOF); /* eof.
  152868. leave unitialized */
  152869. }
  152870. /* bitrate tracking; add the header's bytes here, the body bytes
  152871. are done by packet above */
  152872. vf->bittrack+=og.header_len*8;
  152873. /* has our decoding just traversed a bitstream boundary? */
  152874. if(vf->ready_state==INITSET){
  152875. if(vf->current_serialno!=ogg_page_serialno(&og)){
  152876. if(!spanp)
  152877. return(OV_EOF);
  152878. _decode_clear(vf);
  152879. if(!vf->seekable){
  152880. vorbis_info_clear(vf->vi);
  152881. vorbis_comment_clear(vf->vc);
  152882. }
  152883. }
  152884. }
  152885. }
  152886. /* Do we need to load a new machine before submitting the page? */
  152887. /* This is different in the seekable and non-seekable cases.
  152888. In the seekable case, we already have all the header
  152889. information loaded and cached; we just initialize the machine
  152890. with it and continue on our merry way.
  152891. In the non-seekable (streaming) case, we'll only be at a
  152892. boundary if we just left the previous logical bitstream and
  152893. we're now nominally at the header of the next bitstream
  152894. */
  152895. if(vf->ready_state!=INITSET){
  152896. int link;
  152897. if(vf->ready_state<STREAMSET){
  152898. if(vf->seekable){
  152899. vf->current_serialno=ogg_page_serialno(&og);
  152900. /* match the serialno to bitstream section. We use this rather than
  152901. offset positions to avoid problems near logical bitstream
  152902. boundaries */
  152903. for(link=0;link<vf->links;link++)
  152904. if(vf->serialnos[link]==vf->current_serialno)break;
  152905. if(link==vf->links)return(OV_EBADLINK); /* sign of a bogus
  152906. stream. error out,
  152907. leave machine
  152908. uninitialized */
  152909. vf->current_link=link;
  152910. ogg_stream_reset_serialno(&vf->os,vf->current_serialno);
  152911. vf->ready_state=STREAMSET;
  152912. }else{
  152913. /* we're streaming */
  152914. /* fetch the three header packets, build the info struct */
  152915. int ret=_fetch_headers(vf,vf->vi,vf->vc,&vf->current_serialno,&og);
  152916. if(ret)return(ret);
  152917. vf->current_link++;
  152918. link=0;
  152919. }
  152920. }
  152921. {
  152922. int ret=_make_decode_ready(vf);
  152923. if(ret<0)return ret;
  152924. }
  152925. }
  152926. ogg_stream_pagein(&vf->os,&og);
  152927. }
  152928. }
  152929. /* if, eg, 64 bit stdio is configured by default, this will build with
  152930. fseek64 */
  152931. static int _fseek64_wrap(FILE *f,ogg_int64_t off,int whence){
  152932. if(f==NULL)return(-1);
  152933. return fseek(f,off,whence);
  152934. }
  152935. static int _ov_open1(void *f,OggVorbis_File *vf,char *initial,
  152936. long ibytes, ov_callbacks callbacks){
  152937. int offsettest=(f?callbacks.seek_func(f,0,SEEK_CUR):-1);
  152938. int ret;
  152939. memset(vf,0,sizeof(*vf));
  152940. vf->datasource=f;
  152941. vf->callbacks = callbacks;
  152942. /* init the framing state */
  152943. ogg_sync_init(&vf->oy);
  152944. /* perhaps some data was previously read into a buffer for testing
  152945. against other stream types. Allow initialization from this
  152946. previously read data (as we may be reading from a non-seekable
  152947. stream) */
  152948. if(initial){
  152949. char *buffer=ogg_sync_buffer(&vf->oy,ibytes);
  152950. memcpy(buffer,initial,ibytes);
  152951. ogg_sync_wrote(&vf->oy,ibytes);
  152952. }
  152953. /* can we seek? Stevens suggests the seek test was portable */
  152954. if(offsettest!=-1)vf->seekable=1;
  152955. /* No seeking yet; Set up a 'single' (current) logical bitstream
  152956. entry for partial open */
  152957. vf->links=1;
  152958. vf->vi=(vorbis_info*) _ogg_calloc(vf->links,sizeof(*vf->vi));
  152959. vf->vc=(vorbis_comment*) _ogg_calloc(vf->links,sizeof(*vf->vc));
  152960. ogg_stream_init(&vf->os,-1); /* fill in the serialno later */
  152961. /* Try to fetch the headers, maintaining all the storage */
  152962. if((ret=_fetch_headers(vf,vf->vi,vf->vc,&vf->current_serialno,NULL))<0){
  152963. vf->datasource=NULL;
  152964. ov_clear(vf);
  152965. }else
  152966. vf->ready_state=PARTOPEN;
  152967. return(ret);
  152968. }
  152969. static int _ov_open2(OggVorbis_File *vf){
  152970. if(vf->ready_state != PARTOPEN) return OV_EINVAL;
  152971. vf->ready_state=OPENED;
  152972. if(vf->seekable){
  152973. int ret=_open_seekable2(vf);
  152974. if(ret){
  152975. vf->datasource=NULL;
  152976. ov_clear(vf);
  152977. }
  152978. return(ret);
  152979. }else
  152980. vf->ready_state=STREAMSET;
  152981. return 0;
  152982. }
  152983. /* clear out the OggVorbis_File struct */
  152984. int ov_clear(OggVorbis_File *vf){
  152985. if(vf){
  152986. vorbis_block_clear(&vf->vb);
  152987. vorbis_dsp_clear(&vf->vd);
  152988. ogg_stream_clear(&vf->os);
  152989. if(vf->vi && vf->links){
  152990. int i;
  152991. for(i=0;i<vf->links;i++){
  152992. vorbis_info_clear(vf->vi+i);
  152993. vorbis_comment_clear(vf->vc+i);
  152994. }
  152995. _ogg_free(vf->vi);
  152996. _ogg_free(vf->vc);
  152997. }
  152998. if(vf->dataoffsets)_ogg_free(vf->dataoffsets);
  152999. if(vf->pcmlengths)_ogg_free(vf->pcmlengths);
  153000. if(vf->serialnos)_ogg_free(vf->serialnos);
  153001. if(vf->offsets)_ogg_free(vf->offsets);
  153002. ogg_sync_clear(&vf->oy);
  153003. if(vf->datasource)(vf->callbacks.close_func)(vf->datasource);
  153004. memset(vf,0,sizeof(*vf));
  153005. }
  153006. #ifdef DEBUG_LEAKS
  153007. _VDBG_dump();
  153008. #endif
  153009. return(0);
  153010. }
  153011. /* inspects the OggVorbis file and finds/documents all the logical
  153012. bitstreams contained in it. Tries to be tolerant of logical
  153013. bitstream sections that are truncated/woogie.
  153014. return: -1) error
  153015. 0) OK
  153016. */
  153017. int ov_open_callbacks(void *f,OggVorbis_File *vf,char *initial,long ibytes,
  153018. ov_callbacks callbacks){
  153019. int ret=_ov_open1(f,vf,initial,ibytes,callbacks);
  153020. if(ret)return ret;
  153021. return _ov_open2(vf);
  153022. }
  153023. int ov_open(FILE *f,OggVorbis_File *vf,char *initial,long ibytes){
  153024. ov_callbacks callbacks = {
  153025. (size_t (*)(void *, size_t, size_t, void *)) fread,
  153026. (int (*)(void *, ogg_int64_t, int)) _fseek64_wrap,
  153027. (int (*)(void *)) fclose,
  153028. (long (*)(void *)) ftell
  153029. };
  153030. return ov_open_callbacks((void *)f, vf, initial, ibytes, callbacks);
  153031. }
  153032. /* cheap hack for game usage where downsampling is desirable; there's
  153033. no need for SRC as we can just do it cheaply in libvorbis. */
  153034. int ov_halfrate(OggVorbis_File *vf,int flag){
  153035. int i;
  153036. if(vf->vi==NULL)return OV_EINVAL;
  153037. if(!vf->seekable)return OV_EINVAL;
  153038. if(vf->ready_state>=STREAMSET)
  153039. _decode_clear(vf); /* clear out stream state; later on libvorbis
  153040. will be able to swap this on the fly, but
  153041. for now dumping the decode machine is needed
  153042. to reinit the MDCT lookups. 1.1 libvorbis
  153043. is planned to be able to switch on the fly */
  153044. for(i=0;i<vf->links;i++){
  153045. if(vorbis_synthesis_halfrate(vf->vi+i,flag)){
  153046. ov_halfrate(vf,0);
  153047. return OV_EINVAL;
  153048. }
  153049. }
  153050. return 0;
  153051. }
  153052. int ov_halfrate_p(OggVorbis_File *vf){
  153053. if(vf->vi==NULL)return OV_EINVAL;
  153054. return vorbis_synthesis_halfrate_p(vf->vi);
  153055. }
  153056. /* Only partially open the vorbis file; test for Vorbisness, and load
  153057. the headers for the first chain. Do not seek (although test for
  153058. seekability). Use ov_test_open to finish opening the file, else
  153059. ov_clear to close/free it. Same return codes as open. */
  153060. int ov_test_callbacks(void *f,OggVorbis_File *vf,char *initial,long ibytes,
  153061. ov_callbacks callbacks)
  153062. {
  153063. return _ov_open1(f,vf,initial,ibytes,callbacks);
  153064. }
  153065. int ov_test(FILE *f,OggVorbis_File *vf,char *initial,long ibytes){
  153066. ov_callbacks callbacks = {
  153067. (size_t (*)(void *, size_t, size_t, void *)) fread,
  153068. (int (*)(void *, ogg_int64_t, int)) _fseek64_wrap,
  153069. (int (*)(void *)) fclose,
  153070. (long (*)(void *)) ftell
  153071. };
  153072. return ov_test_callbacks((void *)f, vf, initial, ibytes, callbacks);
  153073. }
  153074. int ov_test_open(OggVorbis_File *vf){
  153075. if(vf->ready_state!=PARTOPEN)return(OV_EINVAL);
  153076. return _ov_open2(vf);
  153077. }
  153078. /* How many logical bitstreams in this physical bitstream? */
  153079. long ov_streams(OggVorbis_File *vf){
  153080. return vf->links;
  153081. }
  153082. /* Is the FILE * associated with vf seekable? */
  153083. long ov_seekable(OggVorbis_File *vf){
  153084. return vf->seekable;
  153085. }
  153086. /* returns the bitrate for a given logical bitstream or the entire
  153087. physical bitstream. If the file is open for random access, it will
  153088. find the *actual* average bitrate. If the file is streaming, it
  153089. returns the nominal bitrate (if set) else the average of the
  153090. upper/lower bounds (if set) else -1 (unset).
  153091. If you want the actual bitrate field settings, get them from the
  153092. vorbis_info structs */
  153093. long ov_bitrate(OggVorbis_File *vf,int i){
  153094. if(vf->ready_state<OPENED)return(OV_EINVAL);
  153095. if(i>=vf->links)return(OV_EINVAL);
  153096. if(!vf->seekable && i!=0)return(ov_bitrate(vf,0));
  153097. if(i<0){
  153098. ogg_int64_t bits=0;
  153099. int i;
  153100. float br;
  153101. for(i=0;i<vf->links;i++)
  153102. bits+=(vf->offsets[i+1]-vf->dataoffsets[i])*8;
  153103. /* This once read: return(rint(bits/ov_time_total(vf,-1)));
  153104. * gcc 3.x on x86 miscompiled this at optimisation level 2 and above,
  153105. * so this is slightly transformed to make it work.
  153106. */
  153107. br = bits/ov_time_total(vf,-1);
  153108. return(rint(br));
  153109. }else{
  153110. if(vf->seekable){
  153111. /* return the actual bitrate */
  153112. return(rint((vf->offsets[i+1]-vf->dataoffsets[i])*8/ov_time_total(vf,i)));
  153113. }else{
  153114. /* return nominal if set */
  153115. if(vf->vi[i].bitrate_nominal>0){
  153116. return vf->vi[i].bitrate_nominal;
  153117. }else{
  153118. if(vf->vi[i].bitrate_upper>0){
  153119. if(vf->vi[i].bitrate_lower>0){
  153120. return (vf->vi[i].bitrate_upper+vf->vi[i].bitrate_lower)/2;
  153121. }else{
  153122. return vf->vi[i].bitrate_upper;
  153123. }
  153124. }
  153125. return(OV_FALSE);
  153126. }
  153127. }
  153128. }
  153129. }
  153130. /* returns the actual bitrate since last call. returns -1 if no
  153131. additional data to offer since last call (or at beginning of stream),
  153132. EINVAL if stream is only partially open
  153133. */
  153134. long ov_bitrate_instant(OggVorbis_File *vf){
  153135. int link=(vf->seekable?vf->current_link:0);
  153136. long ret;
  153137. if(vf->ready_state<OPENED)return(OV_EINVAL);
  153138. if(vf->samptrack==0)return(OV_FALSE);
  153139. ret=vf->bittrack/vf->samptrack*vf->vi[link].rate+.5;
  153140. vf->bittrack=0.f;
  153141. vf->samptrack=0.f;
  153142. return(ret);
  153143. }
  153144. /* Guess */
  153145. long ov_serialnumber(OggVorbis_File *vf,int i){
  153146. if(i>=vf->links)return(ov_serialnumber(vf,vf->links-1));
  153147. if(!vf->seekable && i>=0)return(ov_serialnumber(vf,-1));
  153148. if(i<0){
  153149. return(vf->current_serialno);
  153150. }else{
  153151. return(vf->serialnos[i]);
  153152. }
  153153. }
  153154. /* returns: total raw (compressed) length of content if i==-1
  153155. raw (compressed) length of that logical bitstream for i==0 to n
  153156. OV_EINVAL if the stream is not seekable (we can't know the length)
  153157. or if stream is only partially open
  153158. */
  153159. ogg_int64_t ov_raw_total(OggVorbis_File *vf,int i){
  153160. if(vf->ready_state<OPENED)return(OV_EINVAL);
  153161. if(!vf->seekable || i>=vf->links)return(OV_EINVAL);
  153162. if(i<0){
  153163. ogg_int64_t acc=0;
  153164. int i;
  153165. for(i=0;i<vf->links;i++)
  153166. acc+=ov_raw_total(vf,i);
  153167. return(acc);
  153168. }else{
  153169. return(vf->offsets[i+1]-vf->offsets[i]);
  153170. }
  153171. }
  153172. /* returns: total PCM length (samples) of content if i==-1 PCM length
  153173. (samples) of that logical bitstream for i==0 to n
  153174. OV_EINVAL if the stream is not seekable (we can't know the
  153175. length) or only partially open
  153176. */
  153177. ogg_int64_t ov_pcm_total(OggVorbis_File *vf,int i){
  153178. if(vf->ready_state<OPENED)return(OV_EINVAL);
  153179. if(!vf->seekable || i>=vf->links)return(OV_EINVAL);
  153180. if(i<0){
  153181. ogg_int64_t acc=0;
  153182. int i;
  153183. for(i=0;i<vf->links;i++)
  153184. acc+=ov_pcm_total(vf,i);
  153185. return(acc);
  153186. }else{
  153187. return(vf->pcmlengths[i*2+1]);
  153188. }
  153189. }
  153190. /* returns: total seconds of content if i==-1
  153191. seconds in that logical bitstream for i==0 to n
  153192. OV_EINVAL if the stream is not seekable (we can't know the
  153193. length) or only partially open
  153194. */
  153195. double ov_time_total(OggVorbis_File *vf,int i){
  153196. if(vf->ready_state<OPENED)return(OV_EINVAL);
  153197. if(!vf->seekable || i>=vf->links)return(OV_EINVAL);
  153198. if(i<0){
  153199. double acc=0;
  153200. int i;
  153201. for(i=0;i<vf->links;i++)
  153202. acc+=ov_time_total(vf,i);
  153203. return(acc);
  153204. }else{
  153205. return((double)(vf->pcmlengths[i*2+1])/vf->vi[i].rate);
  153206. }
  153207. }
  153208. /* seek to an offset relative to the *compressed* data. This also
  153209. scans packets to update the PCM cursor. It will cross a logical
  153210. bitstream boundary, but only if it can't get any packets out of the
  153211. tail of the bitstream we seek to (so no surprises).
  153212. returns zero on success, nonzero on failure */
  153213. int ov_raw_seek(OggVorbis_File *vf,ogg_int64_t pos){
  153214. ogg_stream_state work_os;
  153215. if(vf->ready_state<OPENED)return(OV_EINVAL);
  153216. if(!vf->seekable)
  153217. return(OV_ENOSEEK); /* don't dump machine if we can't seek */
  153218. if(pos<0 || pos>vf->end)return(OV_EINVAL);
  153219. /* don't yet clear out decoding machine (if it's initialized), in
  153220. the case we're in the same link. Restart the decode lapping, and
  153221. let _fetch_and_process_packet deal with a potential bitstream
  153222. boundary */
  153223. vf->pcm_offset=-1;
  153224. ogg_stream_reset_serialno(&vf->os,
  153225. vf->current_serialno); /* must set serialno */
  153226. vorbis_synthesis_restart(&vf->vd);
  153227. _seek_helper(vf,pos);
  153228. /* we need to make sure the pcm_offset is set, but we don't want to
  153229. advance the raw cursor past good packets just to get to the first
  153230. with a granulepos. That's not equivalent behavior to beginning
  153231. decoding as immediately after the seek position as possible.
  153232. So, a hack. We use two stream states; a local scratch state and
  153233. the shared vf->os stream state. We use the local state to
  153234. scan, and the shared state as a buffer for later decode.
  153235. Unfortuantely, on the last page we still advance to last packet
  153236. because the granulepos on the last page is not necessarily on a
  153237. packet boundary, and we need to make sure the granpos is
  153238. correct.
  153239. */
  153240. {
  153241. ogg_page og;
  153242. ogg_packet op;
  153243. int lastblock=0;
  153244. int accblock=0;
  153245. int thisblock;
  153246. int eosflag;
  153247. ogg_stream_init(&work_os,vf->current_serialno); /* get the memory ready */
  153248. ogg_stream_reset(&work_os); /* eliminate the spurious OV_HOLE
  153249. return from not necessarily
  153250. starting from the beginning */
  153251. while(1){
  153252. if(vf->ready_state>=STREAMSET){
  153253. /* snarf/scan a packet if we can */
  153254. int result=ogg_stream_packetout(&work_os,&op);
  153255. if(result>0){
  153256. if(vf->vi[vf->current_link].codec_setup){
  153257. thisblock=vorbis_packet_blocksize(vf->vi+vf->current_link,&op);
  153258. if(thisblock<0){
  153259. ogg_stream_packetout(&vf->os,NULL);
  153260. thisblock=0;
  153261. }else{
  153262. if(eosflag)
  153263. ogg_stream_packetout(&vf->os,NULL);
  153264. else
  153265. if(lastblock)accblock+=(lastblock+thisblock)>>2;
  153266. }
  153267. if(op.granulepos!=-1){
  153268. int i,link=vf->current_link;
  153269. ogg_int64_t granulepos=op.granulepos-vf->pcmlengths[link*2];
  153270. if(granulepos<0)granulepos=0;
  153271. for(i=0;i<link;i++)
  153272. granulepos+=vf->pcmlengths[i*2+1];
  153273. vf->pcm_offset=granulepos-accblock;
  153274. break;
  153275. }
  153276. lastblock=thisblock;
  153277. continue;
  153278. }else
  153279. ogg_stream_packetout(&vf->os,NULL);
  153280. }
  153281. }
  153282. if(!lastblock){
  153283. if(_get_next_page(vf,&og,-1)<0){
  153284. vf->pcm_offset=ov_pcm_total(vf,-1);
  153285. break;
  153286. }
  153287. }else{
  153288. /* huh? Bogus stream with packets but no granulepos */
  153289. vf->pcm_offset=-1;
  153290. break;
  153291. }
  153292. /* has our decoding just traversed a bitstream boundary? */
  153293. if(vf->ready_state>=STREAMSET)
  153294. if(vf->current_serialno!=ogg_page_serialno(&og)){
  153295. _decode_clear(vf); /* clear out stream state */
  153296. ogg_stream_clear(&work_os);
  153297. }
  153298. if(vf->ready_state<STREAMSET){
  153299. int link;
  153300. vf->current_serialno=ogg_page_serialno(&og);
  153301. for(link=0;link<vf->links;link++)
  153302. if(vf->serialnos[link]==vf->current_serialno)break;
  153303. if(link==vf->links)goto seek_error; /* sign of a bogus stream.
  153304. error out, leave
  153305. machine uninitialized */
  153306. vf->current_link=link;
  153307. ogg_stream_reset_serialno(&vf->os,vf->current_serialno);
  153308. ogg_stream_reset_serialno(&work_os,vf->current_serialno);
  153309. vf->ready_state=STREAMSET;
  153310. }
  153311. ogg_stream_pagein(&vf->os,&og);
  153312. ogg_stream_pagein(&work_os,&og);
  153313. eosflag=ogg_page_eos(&og);
  153314. }
  153315. }
  153316. ogg_stream_clear(&work_os);
  153317. vf->bittrack=0.f;
  153318. vf->samptrack=0.f;
  153319. return(0);
  153320. seek_error:
  153321. /* dump the machine so we're in a known state */
  153322. vf->pcm_offset=-1;
  153323. ogg_stream_clear(&work_os);
  153324. _decode_clear(vf);
  153325. return OV_EBADLINK;
  153326. }
  153327. /* Page granularity seek (faster than sample granularity because we
  153328. don't do the last bit of decode to find a specific sample).
  153329. Seek to the last [granule marked] page preceeding the specified pos
  153330. location, such that decoding past the returned point will quickly
  153331. arrive at the requested position. */
  153332. int ov_pcm_seek_page(OggVorbis_File *vf,ogg_int64_t pos){
  153333. int link=-1;
  153334. ogg_int64_t result=0;
  153335. ogg_int64_t total=ov_pcm_total(vf,-1);
  153336. if(vf->ready_state<OPENED)return(OV_EINVAL);
  153337. if(!vf->seekable)return(OV_ENOSEEK);
  153338. if(pos<0 || pos>total)return(OV_EINVAL);
  153339. /* which bitstream section does this pcm offset occur in? */
  153340. for(link=vf->links-1;link>=0;link--){
  153341. total-=vf->pcmlengths[link*2+1];
  153342. if(pos>=total)break;
  153343. }
  153344. /* search within the logical bitstream for the page with the highest
  153345. pcm_pos preceeding (or equal to) pos. There is a danger here;
  153346. missing pages or incorrect frame number information in the
  153347. bitstream could make our task impossible. Account for that (it
  153348. would be an error condition) */
  153349. /* new search algorithm by HB (Nicholas Vinen) */
  153350. {
  153351. ogg_int64_t end=vf->offsets[link+1];
  153352. ogg_int64_t begin=vf->offsets[link];
  153353. ogg_int64_t begintime = vf->pcmlengths[link*2];
  153354. ogg_int64_t endtime = vf->pcmlengths[link*2+1]+begintime;
  153355. ogg_int64_t target=pos-total+begintime;
  153356. ogg_int64_t best=begin;
  153357. ogg_page og;
  153358. while(begin<end){
  153359. ogg_int64_t bisect;
  153360. if(end-begin<CHUNKSIZE){
  153361. bisect=begin;
  153362. }else{
  153363. /* take a (pretty decent) guess. */
  153364. bisect=begin +
  153365. (target-begintime)*(end-begin)/(endtime-begintime) - CHUNKSIZE;
  153366. if(bisect<=begin)
  153367. bisect=begin+1;
  153368. }
  153369. _seek_helper(vf,bisect);
  153370. while(begin<end){
  153371. result=_get_next_page(vf,&og,end-vf->offset);
  153372. if(result==OV_EREAD) goto seek_error;
  153373. if(result<0){
  153374. if(bisect<=begin+1)
  153375. end=begin; /* found it */
  153376. else{
  153377. if(bisect==0) goto seek_error;
  153378. bisect-=CHUNKSIZE;
  153379. if(bisect<=begin)bisect=begin+1;
  153380. _seek_helper(vf,bisect);
  153381. }
  153382. }else{
  153383. ogg_int64_t granulepos=ogg_page_granulepos(&og);
  153384. if(granulepos==-1)continue;
  153385. if(granulepos<target){
  153386. best=result; /* raw offset of packet with granulepos */
  153387. begin=vf->offset; /* raw offset of next page */
  153388. begintime=granulepos;
  153389. if(target-begintime>44100)break;
  153390. bisect=begin; /* *not* begin + 1 */
  153391. }else{
  153392. if(bisect<=begin+1)
  153393. end=begin; /* found it */
  153394. else{
  153395. if(end==vf->offset){ /* we're pretty close - we'd be stuck in */
  153396. end=result;
  153397. bisect-=CHUNKSIZE; /* an endless loop otherwise. */
  153398. if(bisect<=begin)bisect=begin+1;
  153399. _seek_helper(vf,bisect);
  153400. }else{
  153401. end=result;
  153402. endtime=granulepos;
  153403. break;
  153404. }
  153405. }
  153406. }
  153407. }
  153408. }
  153409. }
  153410. /* found our page. seek to it, update pcm offset. Easier case than
  153411. raw_seek, don't keep packets preceeding granulepos. */
  153412. {
  153413. ogg_page og;
  153414. ogg_packet op;
  153415. /* seek */
  153416. _seek_helper(vf,best);
  153417. vf->pcm_offset=-1;
  153418. if(_get_next_page(vf,&og,-1)<0)return(OV_EOF); /* shouldn't happen */
  153419. if(link!=vf->current_link){
  153420. /* Different link; dump entire decode machine */
  153421. _decode_clear(vf);
  153422. vf->current_link=link;
  153423. vf->current_serialno=ogg_page_serialno(&og);
  153424. vf->ready_state=STREAMSET;
  153425. }else{
  153426. vorbis_synthesis_restart(&vf->vd);
  153427. }
  153428. ogg_stream_reset_serialno(&vf->os,vf->current_serialno);
  153429. ogg_stream_pagein(&vf->os,&og);
  153430. /* pull out all but last packet; the one with granulepos */
  153431. while(1){
  153432. result=ogg_stream_packetpeek(&vf->os,&op);
  153433. if(result==0){
  153434. /* !!! the packet finishing this page originated on a
  153435. preceeding page. Keep fetching previous pages until we
  153436. get one with a granulepos or without the 'continued' flag
  153437. set. Then just use raw_seek for simplicity. */
  153438. _seek_helper(vf,best);
  153439. while(1){
  153440. result=_get_prev_page(vf,&og);
  153441. if(result<0) goto seek_error;
  153442. if(ogg_page_granulepos(&og)>-1 ||
  153443. !ogg_page_continued(&og)){
  153444. return ov_raw_seek(vf,result);
  153445. }
  153446. vf->offset=result;
  153447. }
  153448. }
  153449. if(result<0){
  153450. result = OV_EBADPACKET;
  153451. goto seek_error;
  153452. }
  153453. if(op.granulepos!=-1){
  153454. vf->pcm_offset=op.granulepos-vf->pcmlengths[vf->current_link*2];
  153455. if(vf->pcm_offset<0)vf->pcm_offset=0;
  153456. vf->pcm_offset+=total;
  153457. break;
  153458. }else
  153459. result=ogg_stream_packetout(&vf->os,NULL);
  153460. }
  153461. }
  153462. }
  153463. /* verify result */
  153464. if(vf->pcm_offset>pos || pos>ov_pcm_total(vf,-1)){
  153465. result=OV_EFAULT;
  153466. goto seek_error;
  153467. }
  153468. vf->bittrack=0.f;
  153469. vf->samptrack=0.f;
  153470. return(0);
  153471. seek_error:
  153472. /* dump machine so we're in a known state */
  153473. vf->pcm_offset=-1;
  153474. _decode_clear(vf);
  153475. return (int)result;
  153476. }
  153477. /* seek to a sample offset relative to the decompressed pcm stream
  153478. returns zero on success, nonzero on failure */
  153479. int ov_pcm_seek(OggVorbis_File *vf,ogg_int64_t pos){
  153480. int thisblock,lastblock=0;
  153481. int ret=ov_pcm_seek_page(vf,pos);
  153482. if(ret<0)return(ret);
  153483. if((ret=_make_decode_ready(vf)))return ret;
  153484. /* discard leading packets we don't need for the lapping of the
  153485. position we want; don't decode them */
  153486. while(1){
  153487. ogg_packet op;
  153488. ogg_page og;
  153489. int ret=ogg_stream_packetpeek(&vf->os,&op);
  153490. if(ret>0){
  153491. thisblock=vorbis_packet_blocksize(vf->vi+vf->current_link,&op);
  153492. if(thisblock<0){
  153493. ogg_stream_packetout(&vf->os,NULL);
  153494. continue; /* non audio packet */
  153495. }
  153496. if(lastblock)vf->pcm_offset+=(lastblock+thisblock)>>2;
  153497. if(vf->pcm_offset+((thisblock+
  153498. vorbis_info_blocksize(vf->vi,1))>>2)>=pos)break;
  153499. /* remove the packet from packet queue and track its granulepos */
  153500. ogg_stream_packetout(&vf->os,NULL);
  153501. vorbis_synthesis_trackonly(&vf->vb,&op); /* set up a vb with
  153502. only tracking, no
  153503. pcm_decode */
  153504. vorbis_synthesis_blockin(&vf->vd,&vf->vb);
  153505. /* end of logical stream case is hard, especially with exact
  153506. length positioning. */
  153507. if(op.granulepos>-1){
  153508. int i;
  153509. /* always believe the stream markers */
  153510. vf->pcm_offset=op.granulepos-vf->pcmlengths[vf->current_link*2];
  153511. if(vf->pcm_offset<0)vf->pcm_offset=0;
  153512. for(i=0;i<vf->current_link;i++)
  153513. vf->pcm_offset+=vf->pcmlengths[i*2+1];
  153514. }
  153515. lastblock=thisblock;
  153516. }else{
  153517. if(ret<0 && ret!=OV_HOLE)break;
  153518. /* suck in a new page */
  153519. if(_get_next_page(vf,&og,-1)<0)break;
  153520. if(vf->current_serialno!=ogg_page_serialno(&og))_decode_clear(vf);
  153521. if(vf->ready_state<STREAMSET){
  153522. int link;
  153523. vf->current_serialno=ogg_page_serialno(&og);
  153524. for(link=0;link<vf->links;link++)
  153525. if(vf->serialnos[link]==vf->current_serialno)break;
  153526. if(link==vf->links)return(OV_EBADLINK);
  153527. vf->current_link=link;
  153528. ogg_stream_reset_serialno(&vf->os,vf->current_serialno);
  153529. vf->ready_state=STREAMSET;
  153530. ret=_make_decode_ready(vf);
  153531. if(ret)return ret;
  153532. lastblock=0;
  153533. }
  153534. ogg_stream_pagein(&vf->os,&og);
  153535. }
  153536. }
  153537. vf->bittrack=0.f;
  153538. vf->samptrack=0.f;
  153539. /* discard samples until we reach the desired position. Crossing a
  153540. logical bitstream boundary with abandon is OK. */
  153541. while(vf->pcm_offset<pos){
  153542. ogg_int64_t target=pos-vf->pcm_offset;
  153543. long samples=vorbis_synthesis_pcmout(&vf->vd,NULL);
  153544. if(samples>target)samples=target;
  153545. vorbis_synthesis_read(&vf->vd,samples);
  153546. vf->pcm_offset+=samples;
  153547. if(samples<target)
  153548. if(_fetch_and_process_packet(vf,NULL,1,1)<=0)
  153549. vf->pcm_offset=ov_pcm_total(vf,-1); /* eof */
  153550. }
  153551. return 0;
  153552. }
  153553. /* seek to a playback time relative to the decompressed pcm stream
  153554. returns zero on success, nonzero on failure */
  153555. int ov_time_seek(OggVorbis_File *vf,double seconds){
  153556. /* translate time to PCM position and call ov_pcm_seek */
  153557. int link=-1;
  153558. ogg_int64_t pcm_total=ov_pcm_total(vf,-1);
  153559. double time_total=ov_time_total(vf,-1);
  153560. if(vf->ready_state<OPENED)return(OV_EINVAL);
  153561. if(!vf->seekable)return(OV_ENOSEEK);
  153562. if(seconds<0 || seconds>time_total)return(OV_EINVAL);
  153563. /* which bitstream section does this time offset occur in? */
  153564. for(link=vf->links-1;link>=0;link--){
  153565. pcm_total-=vf->pcmlengths[link*2+1];
  153566. time_total-=ov_time_total(vf,link);
  153567. if(seconds>=time_total)break;
  153568. }
  153569. /* enough information to convert time offset to pcm offset */
  153570. {
  153571. ogg_int64_t target=pcm_total+(seconds-time_total)*vf->vi[link].rate;
  153572. return(ov_pcm_seek(vf,target));
  153573. }
  153574. }
  153575. /* page-granularity version of ov_time_seek
  153576. returns zero on success, nonzero on failure */
  153577. int ov_time_seek_page(OggVorbis_File *vf,double seconds){
  153578. /* translate time to PCM position and call ov_pcm_seek */
  153579. int link=-1;
  153580. ogg_int64_t pcm_total=ov_pcm_total(vf,-1);
  153581. double time_total=ov_time_total(vf,-1);
  153582. if(vf->ready_state<OPENED)return(OV_EINVAL);
  153583. if(!vf->seekable)return(OV_ENOSEEK);
  153584. if(seconds<0 || seconds>time_total)return(OV_EINVAL);
  153585. /* which bitstream section does this time offset occur in? */
  153586. for(link=vf->links-1;link>=0;link--){
  153587. pcm_total-=vf->pcmlengths[link*2+1];
  153588. time_total-=ov_time_total(vf,link);
  153589. if(seconds>=time_total)break;
  153590. }
  153591. /* enough information to convert time offset to pcm offset */
  153592. {
  153593. ogg_int64_t target=pcm_total+(seconds-time_total)*vf->vi[link].rate;
  153594. return(ov_pcm_seek_page(vf,target));
  153595. }
  153596. }
  153597. /* tell the current stream offset cursor. Note that seek followed by
  153598. tell will likely not give the set offset due to caching */
  153599. ogg_int64_t ov_raw_tell(OggVorbis_File *vf){
  153600. if(vf->ready_state<OPENED)return(OV_EINVAL);
  153601. return(vf->offset);
  153602. }
  153603. /* return PCM offset (sample) of next PCM sample to be read */
  153604. ogg_int64_t ov_pcm_tell(OggVorbis_File *vf){
  153605. if(vf->ready_state<OPENED)return(OV_EINVAL);
  153606. return(vf->pcm_offset);
  153607. }
  153608. /* return time offset (seconds) of next PCM sample to be read */
  153609. double ov_time_tell(OggVorbis_File *vf){
  153610. int link=0;
  153611. ogg_int64_t pcm_total=0;
  153612. double time_total=0.f;
  153613. if(vf->ready_state<OPENED)return(OV_EINVAL);
  153614. if(vf->seekable){
  153615. pcm_total=ov_pcm_total(vf,-1);
  153616. time_total=ov_time_total(vf,-1);
  153617. /* which bitstream section does this time offset occur in? */
  153618. for(link=vf->links-1;link>=0;link--){
  153619. pcm_total-=vf->pcmlengths[link*2+1];
  153620. time_total-=ov_time_total(vf,link);
  153621. if(vf->pcm_offset>=pcm_total)break;
  153622. }
  153623. }
  153624. return((double)time_total+(double)(vf->pcm_offset-pcm_total)/vf->vi[link].rate);
  153625. }
  153626. /* link: -1) return the vorbis_info struct for the bitstream section
  153627. currently being decoded
  153628. 0-n) to request information for a specific bitstream section
  153629. In the case of a non-seekable bitstream, any call returns the
  153630. current bitstream. NULL in the case that the machine is not
  153631. initialized */
  153632. vorbis_info *ov_info(OggVorbis_File *vf,int link){
  153633. if(vf->seekable){
  153634. if(link<0)
  153635. if(vf->ready_state>=STREAMSET)
  153636. return vf->vi+vf->current_link;
  153637. else
  153638. return vf->vi;
  153639. else
  153640. if(link>=vf->links)
  153641. return NULL;
  153642. else
  153643. return vf->vi+link;
  153644. }else{
  153645. return vf->vi;
  153646. }
  153647. }
  153648. /* grr, strong typing, grr, no templates/inheritence, grr */
  153649. vorbis_comment *ov_comment(OggVorbis_File *vf,int link){
  153650. if(vf->seekable){
  153651. if(link<0)
  153652. if(vf->ready_state>=STREAMSET)
  153653. return vf->vc+vf->current_link;
  153654. else
  153655. return vf->vc;
  153656. else
  153657. if(link>=vf->links)
  153658. return NULL;
  153659. else
  153660. return vf->vc+link;
  153661. }else{
  153662. return vf->vc;
  153663. }
  153664. }
  153665. static int host_is_big_endian() {
  153666. ogg_int32_t pattern = 0xfeedface; /* deadbeef */
  153667. unsigned char *bytewise = (unsigned char *)&pattern;
  153668. if (bytewise[0] == 0xfe) return 1;
  153669. return 0;
  153670. }
  153671. /* up to this point, everything could more or less hide the multiple
  153672. logical bitstream nature of chaining from the toplevel application
  153673. if the toplevel application didn't particularly care. However, at
  153674. the point that we actually read audio back, the multiple-section
  153675. nature must surface: Multiple bitstream sections do not necessarily
  153676. have to have the same number of channels or sampling rate.
  153677. ov_read returns the sequential logical bitstream number currently
  153678. being decoded along with the PCM data in order that the toplevel
  153679. application can take action on channel/sample rate changes. This
  153680. number will be incremented even for streamed (non-seekable) streams
  153681. (for seekable streams, it represents the actual logical bitstream
  153682. index within the physical bitstream. Note that the accessor
  153683. functions above are aware of this dichotomy).
  153684. input values: buffer) a buffer to hold packed PCM data for return
  153685. length) the byte length requested to be placed into buffer
  153686. bigendianp) should the data be packed LSB first (0) or
  153687. MSB first (1)
  153688. word) word size for output. currently 1 (byte) or
  153689. 2 (16 bit short)
  153690. return values: <0) error/hole in data (OV_HOLE), partial open (OV_EINVAL)
  153691. 0) EOF
  153692. n) number of bytes of PCM actually returned. The
  153693. below works on a packet-by-packet basis, so the
  153694. return length is not related to the 'length' passed
  153695. in, just guaranteed to fit.
  153696. *section) set to the logical bitstream number */
  153697. long ov_read(OggVorbis_File *vf,char *buffer,int length,
  153698. int bigendianp,int word,int sgned,int *bitstream){
  153699. int i,j;
  153700. int host_endian = host_is_big_endian();
  153701. float **pcm;
  153702. long samples;
  153703. if(vf->ready_state<OPENED)return(OV_EINVAL);
  153704. while(1){
  153705. if(vf->ready_state==INITSET){
  153706. samples=vorbis_synthesis_pcmout(&vf->vd,&pcm);
  153707. if(samples)break;
  153708. }
  153709. /* suck in another packet */
  153710. {
  153711. int ret=_fetch_and_process_packet(vf,NULL,1,1);
  153712. if(ret==OV_EOF)
  153713. return(0);
  153714. if(ret<=0)
  153715. return(ret);
  153716. }
  153717. }
  153718. if(samples>0){
  153719. /* yay! proceed to pack data into the byte buffer */
  153720. long channels=ov_info(vf,-1)->channels;
  153721. long bytespersample=word * channels;
  153722. vorbis_fpu_control fpu;
  153723. (void) fpu; // (to avoid a warning about it being unused)
  153724. if(samples>length/bytespersample)samples=length/bytespersample;
  153725. if(samples <= 0)
  153726. return OV_EINVAL;
  153727. /* a tight loop to pack each size */
  153728. {
  153729. int val;
  153730. if(word==1){
  153731. int off=(sgned?0:128);
  153732. vorbis_fpu_setround(&fpu);
  153733. for(j=0;j<samples;j++)
  153734. for(i=0;i<channels;i++){
  153735. val=vorbis_ftoi(pcm[i][j]*128.f);
  153736. if(val>127)val=127;
  153737. else if(val<-128)val=-128;
  153738. *buffer++=val+off;
  153739. }
  153740. vorbis_fpu_restore(fpu);
  153741. }else{
  153742. int off=(sgned?0:32768);
  153743. if(host_endian==bigendianp){
  153744. if(sgned){
  153745. vorbis_fpu_setround(&fpu);
  153746. for(i=0;i<channels;i++) { /* It's faster in this order */
  153747. float *src=pcm[i];
  153748. short *dest=((short *)buffer)+i;
  153749. for(j=0;j<samples;j++) {
  153750. val=vorbis_ftoi(src[j]*32768.f);
  153751. if(val>32767)val=32767;
  153752. else if(val<-32768)val=-32768;
  153753. *dest=val;
  153754. dest+=channels;
  153755. }
  153756. }
  153757. vorbis_fpu_restore(fpu);
  153758. }else{
  153759. vorbis_fpu_setround(&fpu);
  153760. for(i=0;i<channels;i++) {
  153761. float *src=pcm[i];
  153762. short *dest=((short *)buffer)+i;
  153763. for(j=0;j<samples;j++) {
  153764. val=vorbis_ftoi(src[j]*32768.f);
  153765. if(val>32767)val=32767;
  153766. else if(val<-32768)val=-32768;
  153767. *dest=val+off;
  153768. dest+=channels;
  153769. }
  153770. }
  153771. vorbis_fpu_restore(fpu);
  153772. }
  153773. }else if(bigendianp){
  153774. vorbis_fpu_setround(&fpu);
  153775. for(j=0;j<samples;j++)
  153776. for(i=0;i<channels;i++){
  153777. val=vorbis_ftoi(pcm[i][j]*32768.f);
  153778. if(val>32767)val=32767;
  153779. else if(val<-32768)val=-32768;
  153780. val+=off;
  153781. *buffer++=(val>>8);
  153782. *buffer++=(val&0xff);
  153783. }
  153784. vorbis_fpu_restore(fpu);
  153785. }else{
  153786. int val;
  153787. vorbis_fpu_setround(&fpu);
  153788. for(j=0;j<samples;j++)
  153789. for(i=0;i<channels;i++){
  153790. val=vorbis_ftoi(pcm[i][j]*32768.f);
  153791. if(val>32767)val=32767;
  153792. else if(val<-32768)val=-32768;
  153793. val+=off;
  153794. *buffer++=(val&0xff);
  153795. *buffer++=(val>>8);
  153796. }
  153797. vorbis_fpu_restore(fpu);
  153798. }
  153799. }
  153800. }
  153801. vorbis_synthesis_read(&vf->vd,samples);
  153802. vf->pcm_offset+=samples;
  153803. if(bitstream)*bitstream=vf->current_link;
  153804. return(samples*bytespersample);
  153805. }else{
  153806. return(samples);
  153807. }
  153808. }
  153809. /* input values: pcm_channels) a float vector per channel of output
  153810. length) the sample length being read by the app
  153811. return values: <0) error/hole in data (OV_HOLE), partial open (OV_EINVAL)
  153812. 0) EOF
  153813. n) number of samples of PCM actually returned. The
  153814. below works on a packet-by-packet basis, so the
  153815. return length is not related to the 'length' passed
  153816. in, just guaranteed to fit.
  153817. *section) set to the logical bitstream number */
  153818. long ov_read_float(OggVorbis_File *vf,float ***pcm_channels,int length,
  153819. int *bitstream){
  153820. if(vf->ready_state<OPENED)return(OV_EINVAL);
  153821. while(1){
  153822. if(vf->ready_state==INITSET){
  153823. float **pcm;
  153824. long samples=vorbis_synthesis_pcmout(&vf->vd,&pcm);
  153825. if(samples){
  153826. if(pcm_channels)*pcm_channels=pcm;
  153827. if(samples>length)samples=length;
  153828. vorbis_synthesis_read(&vf->vd,samples);
  153829. vf->pcm_offset+=samples;
  153830. if(bitstream)*bitstream=vf->current_link;
  153831. return samples;
  153832. }
  153833. }
  153834. /* suck in another packet */
  153835. {
  153836. int ret=_fetch_and_process_packet(vf,NULL,1,1);
  153837. if(ret==OV_EOF)return(0);
  153838. if(ret<=0)return(ret);
  153839. }
  153840. }
  153841. }
  153842. extern float *vorbis_window(vorbis_dsp_state *v,int W);
  153843. extern void _analysis_output_always(const char *base,int i,float *v,int n,int bark,int dB,
  153844. ogg_int64_t off);
  153845. static void _ov_splice(float **pcm,float **lappcm,
  153846. int n1, int n2,
  153847. int ch1, int ch2,
  153848. float *w1, float *w2){
  153849. int i,j;
  153850. float *w=w1;
  153851. int n=n1;
  153852. if(n1>n2){
  153853. n=n2;
  153854. w=w2;
  153855. }
  153856. /* splice */
  153857. for(j=0;j<ch1 && j<ch2;j++){
  153858. float *s=lappcm[j];
  153859. float *d=pcm[j];
  153860. for(i=0;i<n;i++){
  153861. float wd=w[i]*w[i];
  153862. float ws=1.-wd;
  153863. d[i]=d[i]*wd + s[i]*ws;
  153864. }
  153865. }
  153866. /* window from zero */
  153867. for(;j<ch2;j++){
  153868. float *d=pcm[j];
  153869. for(i=0;i<n;i++){
  153870. float wd=w[i]*w[i];
  153871. d[i]=d[i]*wd;
  153872. }
  153873. }
  153874. }
  153875. /* make sure vf is INITSET */
  153876. static int _ov_initset(OggVorbis_File *vf){
  153877. while(1){
  153878. if(vf->ready_state==INITSET)break;
  153879. /* suck in another packet */
  153880. {
  153881. int ret=_fetch_and_process_packet(vf,NULL,1,0);
  153882. if(ret<0 && ret!=OV_HOLE)return(ret);
  153883. }
  153884. }
  153885. return 0;
  153886. }
  153887. /* make sure vf is INITSET and that we have a primed buffer; if
  153888. we're crosslapping at a stream section boundary, this also makes
  153889. sure we're sanity checking against the right stream information */
  153890. static int _ov_initprime(OggVorbis_File *vf){
  153891. vorbis_dsp_state *vd=&vf->vd;
  153892. while(1){
  153893. if(vf->ready_state==INITSET)
  153894. if(vorbis_synthesis_pcmout(vd,NULL))break;
  153895. /* suck in another packet */
  153896. {
  153897. int ret=_fetch_and_process_packet(vf,NULL,1,0);
  153898. if(ret<0 && ret!=OV_HOLE)return(ret);
  153899. }
  153900. }
  153901. return 0;
  153902. }
  153903. /* grab enough data for lapping from vf; this may be in the form of
  153904. unreturned, already-decoded pcm, remaining PCM we will need to
  153905. decode, or synthetic postextrapolation from last packets. */
  153906. static void _ov_getlap(OggVorbis_File *vf,vorbis_info *vi,vorbis_dsp_state *vd,
  153907. float **lappcm,int lapsize){
  153908. int lapcount=0,i;
  153909. float **pcm;
  153910. /* try first to decode the lapping data */
  153911. while(lapcount<lapsize){
  153912. int samples=vorbis_synthesis_pcmout(vd,&pcm);
  153913. if(samples){
  153914. if(samples>lapsize-lapcount)samples=lapsize-lapcount;
  153915. for(i=0;i<vi->channels;i++)
  153916. memcpy(lappcm[i]+lapcount,pcm[i],sizeof(**pcm)*samples);
  153917. lapcount+=samples;
  153918. vorbis_synthesis_read(vd,samples);
  153919. }else{
  153920. /* suck in another packet */
  153921. int ret=_fetch_and_process_packet(vf,NULL,1,0); /* do *not* span */
  153922. if(ret==OV_EOF)break;
  153923. }
  153924. }
  153925. if(lapcount<lapsize){
  153926. /* failed to get lapping data from normal decode; pry it from the
  153927. postextrapolation buffering, or the second half of the MDCT
  153928. from the last packet */
  153929. int samples=vorbis_synthesis_lapout(&vf->vd,&pcm);
  153930. if(samples==0){
  153931. for(i=0;i<vi->channels;i++)
  153932. memset(lappcm[i]+lapcount,0,sizeof(**pcm)*lapsize-lapcount);
  153933. lapcount=lapsize;
  153934. }else{
  153935. if(samples>lapsize-lapcount)samples=lapsize-lapcount;
  153936. for(i=0;i<vi->channels;i++)
  153937. memcpy(lappcm[i]+lapcount,pcm[i],sizeof(**pcm)*samples);
  153938. lapcount+=samples;
  153939. }
  153940. }
  153941. }
  153942. /* this sets up crosslapping of a sample by using trailing data from
  153943. sample 1 and lapping it into the windowing buffer of sample 2 */
  153944. int ov_crosslap(OggVorbis_File *vf1, OggVorbis_File *vf2){
  153945. vorbis_info *vi1,*vi2;
  153946. float **lappcm;
  153947. float **pcm;
  153948. float *w1,*w2;
  153949. int n1,n2,i,ret,hs1,hs2;
  153950. if(vf1==vf2)return(0); /* degenerate case */
  153951. if(vf1->ready_state<OPENED)return(OV_EINVAL);
  153952. if(vf2->ready_state<OPENED)return(OV_EINVAL);
  153953. /* the relevant overlap buffers must be pre-checked and pre-primed
  153954. before looking at settings in the event that priming would cross
  153955. a bitstream boundary. So, do it now */
  153956. ret=_ov_initset(vf1);
  153957. if(ret)return(ret);
  153958. ret=_ov_initprime(vf2);
  153959. if(ret)return(ret);
  153960. vi1=ov_info(vf1,-1);
  153961. vi2=ov_info(vf2,-1);
  153962. hs1=ov_halfrate_p(vf1);
  153963. hs2=ov_halfrate_p(vf2);
  153964. lappcm=(float**) alloca(sizeof(*lappcm)*vi1->channels);
  153965. n1=vorbis_info_blocksize(vi1,0)>>(1+hs1);
  153966. n2=vorbis_info_blocksize(vi2,0)>>(1+hs2);
  153967. w1=vorbis_window(&vf1->vd,0);
  153968. w2=vorbis_window(&vf2->vd,0);
  153969. for(i=0;i<vi1->channels;i++)
  153970. lappcm[i]=(float*) alloca(sizeof(**lappcm)*n1);
  153971. _ov_getlap(vf1,vi1,&vf1->vd,lappcm,n1);
  153972. /* have a lapping buffer from vf1; now to splice it into the lapping
  153973. buffer of vf2 */
  153974. /* consolidate and expose the buffer. */
  153975. vorbis_synthesis_lapout(&vf2->vd,&pcm);
  153976. _analysis_output_always("pcmL",0,pcm[0],n1*2,0,0,0);
  153977. _analysis_output_always("pcmR",0,pcm[1],n1*2,0,0,0);
  153978. /* splice */
  153979. _ov_splice(pcm,lappcm,n1,n2,vi1->channels,vi2->channels,w1,w2);
  153980. /* done */
  153981. return(0);
  153982. }
  153983. static int _ov_64_seek_lap(OggVorbis_File *vf,ogg_int64_t pos,
  153984. int (*localseek)(OggVorbis_File *,ogg_int64_t)){
  153985. vorbis_info *vi;
  153986. float **lappcm;
  153987. float **pcm;
  153988. float *w1,*w2;
  153989. int n1,n2,ch1,ch2,hs;
  153990. int i,ret;
  153991. if(vf->ready_state<OPENED)return(OV_EINVAL);
  153992. ret=_ov_initset(vf);
  153993. if(ret)return(ret);
  153994. vi=ov_info(vf,-1);
  153995. hs=ov_halfrate_p(vf);
  153996. ch1=vi->channels;
  153997. n1=vorbis_info_blocksize(vi,0)>>(1+hs);
  153998. w1=vorbis_window(&vf->vd,0); /* window arrays from libvorbis are
  153999. persistent; even if the decode state
  154000. from this link gets dumped, this
  154001. window array continues to exist */
  154002. lappcm=(float**) alloca(sizeof(*lappcm)*ch1);
  154003. for(i=0;i<ch1;i++)
  154004. lappcm[i]=(float*) alloca(sizeof(**lappcm)*n1);
  154005. _ov_getlap(vf,vi,&vf->vd,lappcm,n1);
  154006. /* have lapping data; seek and prime the buffer */
  154007. ret=localseek(vf,pos);
  154008. if(ret)return ret;
  154009. ret=_ov_initprime(vf);
  154010. if(ret)return(ret);
  154011. /* Guard against cross-link changes; they're perfectly legal */
  154012. vi=ov_info(vf,-1);
  154013. ch2=vi->channels;
  154014. n2=vorbis_info_blocksize(vi,0)>>(1+hs);
  154015. w2=vorbis_window(&vf->vd,0);
  154016. /* consolidate and expose the buffer. */
  154017. vorbis_synthesis_lapout(&vf->vd,&pcm);
  154018. /* splice */
  154019. _ov_splice(pcm,lappcm,n1,n2,ch1,ch2,w1,w2);
  154020. /* done */
  154021. return(0);
  154022. }
  154023. int ov_raw_seek_lap(OggVorbis_File *vf,ogg_int64_t pos){
  154024. return _ov_64_seek_lap(vf,pos,ov_raw_seek);
  154025. }
  154026. int ov_pcm_seek_lap(OggVorbis_File *vf,ogg_int64_t pos){
  154027. return _ov_64_seek_lap(vf,pos,ov_pcm_seek);
  154028. }
  154029. int ov_pcm_seek_page_lap(OggVorbis_File *vf,ogg_int64_t pos){
  154030. return _ov_64_seek_lap(vf,pos,ov_pcm_seek_page);
  154031. }
  154032. static int _ov_d_seek_lap(OggVorbis_File *vf,double pos,
  154033. int (*localseek)(OggVorbis_File *,double)){
  154034. vorbis_info *vi;
  154035. float **lappcm;
  154036. float **pcm;
  154037. float *w1,*w2;
  154038. int n1,n2,ch1,ch2,hs;
  154039. int i,ret;
  154040. if(vf->ready_state<OPENED)return(OV_EINVAL);
  154041. ret=_ov_initset(vf);
  154042. if(ret)return(ret);
  154043. vi=ov_info(vf,-1);
  154044. hs=ov_halfrate_p(vf);
  154045. ch1=vi->channels;
  154046. n1=vorbis_info_blocksize(vi,0)>>(1+hs);
  154047. w1=vorbis_window(&vf->vd,0); /* window arrays from libvorbis are
  154048. persistent; even if the decode state
  154049. from this link gets dumped, this
  154050. window array continues to exist */
  154051. lappcm=(float**) alloca(sizeof(*lappcm)*ch1);
  154052. for(i=0;i<ch1;i++)
  154053. lappcm[i]=(float*) alloca(sizeof(**lappcm)*n1);
  154054. _ov_getlap(vf,vi,&vf->vd,lappcm,n1);
  154055. /* have lapping data; seek and prime the buffer */
  154056. ret=localseek(vf,pos);
  154057. if(ret)return ret;
  154058. ret=_ov_initprime(vf);
  154059. if(ret)return(ret);
  154060. /* Guard against cross-link changes; they're perfectly legal */
  154061. vi=ov_info(vf,-1);
  154062. ch2=vi->channels;
  154063. n2=vorbis_info_blocksize(vi,0)>>(1+hs);
  154064. w2=vorbis_window(&vf->vd,0);
  154065. /* consolidate and expose the buffer. */
  154066. vorbis_synthesis_lapout(&vf->vd,&pcm);
  154067. /* splice */
  154068. _ov_splice(pcm,lappcm,n1,n2,ch1,ch2,w1,w2);
  154069. /* done */
  154070. return(0);
  154071. }
  154072. int ov_time_seek_lap(OggVorbis_File *vf,double pos){
  154073. return _ov_d_seek_lap(vf,pos,ov_time_seek);
  154074. }
  154075. int ov_time_seek_page_lap(OggVorbis_File *vf,double pos){
  154076. return _ov_d_seek_lap(vf,pos,ov_time_seek_page);
  154077. }
  154078. #endif
  154079. /*** End of inlined file: vorbisfile.c ***/
  154080. /*** Start of inlined file: window.c ***/
  154081. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  154082. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  154083. // tasks..
  154084. #if JUCE_MSVC
  154085. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  154086. #endif
  154087. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  154088. #if JUCE_USE_OGGVORBIS
  154089. #include <stdlib.h>
  154090. #include <math.h>
  154091. static float vwin64[32] = {
  154092. 0.0009460463F, 0.0085006468F, 0.0235352254F, 0.0458950567F,
  154093. 0.0753351908F, 0.1115073077F, 0.1539457973F, 0.2020557475F,
  154094. 0.2551056759F, 0.3122276645F, 0.3724270287F, 0.4346027792F,
  154095. 0.4975789974F, 0.5601459521F, 0.6211085051F, 0.6793382689F,
  154096. 0.7338252629F, 0.7837245849F, 0.8283939355F, 0.8674186656F,
  154097. 0.9006222429F, 0.9280614787F, 0.9500073081F, 0.9669131782F,
  154098. 0.9793740220F, 0.9880792941F, 0.9937636139F, 0.9971582668F,
  154099. 0.9989462667F, 0.9997230082F, 0.9999638688F, 0.9999995525F,
  154100. };
  154101. static float vwin128[64] = {
  154102. 0.0002365472F, 0.0021280687F, 0.0059065254F, 0.0115626550F,
  154103. 0.0190823442F, 0.0284463735F, 0.0396300935F, 0.0526030430F,
  154104. 0.0673285281F, 0.0837631763F, 0.1018564887F, 0.1215504095F,
  154105. 0.1427789367F, 0.1654677960F, 0.1895342001F, 0.2148867160F,
  154106. 0.2414252576F, 0.2690412240F, 0.2976177952F, 0.3270303960F,
  154107. 0.3571473350F, 0.3878306189F, 0.4189369387F, 0.4503188188F,
  154108. 0.4818259135F, 0.5133064334F, 0.5446086751F, 0.5755826278F,
  154109. 0.6060816248F, 0.6359640047F, 0.6650947483F, 0.6933470543F,
  154110. 0.7206038179F, 0.7467589810F, 0.7717187213F, 0.7954024542F,
  154111. 0.8177436264F, 0.8386902831F, 0.8582053981F, 0.8762669622F,
  154112. 0.8928678298F, 0.9080153310F, 0.9217306608F, 0.9340480615F,
  154113. 0.9450138200F, 0.9546851041F, 0.9631286621F, 0.9704194171F,
  154114. 0.9766389810F, 0.9818741197F, 0.9862151938F, 0.9897546035F,
  154115. 0.9925852598F, 0.9947991032F, 0.9964856900F, 0.9977308602F,
  154116. 0.9986155015F, 0.9992144193F, 0.9995953200F, 0.9998179155F,
  154117. 0.9999331503F, 0.9999825563F, 0.9999977357F, 0.9999999720F,
  154118. };
  154119. static float vwin256[128] = {
  154120. 0.0000591390F, 0.0005321979F, 0.0014780301F, 0.0028960636F,
  154121. 0.0047854363F, 0.0071449926F, 0.0099732775F, 0.0132685298F,
  154122. 0.0170286741F, 0.0212513119F, 0.0259337111F, 0.0310727950F,
  154123. 0.0366651302F, 0.0427069140F, 0.0491939614F, 0.0561216907F,
  154124. 0.0634851102F, 0.0712788035F, 0.0794969160F, 0.0881331402F,
  154125. 0.0971807028F, 0.1066323515F, 0.1164803426F, 0.1267164297F,
  154126. 0.1373318534F, 0.1483173323F, 0.1596630553F, 0.1713586755F,
  154127. 0.1833933062F, 0.1957555184F, 0.2084333404F, 0.2214142599F,
  154128. 0.2346852280F, 0.2482326664F, 0.2620424757F, 0.2761000481F,
  154129. 0.2903902813F, 0.3048975959F, 0.3196059553F, 0.3344988887F,
  154130. 0.3495595160F, 0.3647705766F, 0.3801144597F, 0.3955732382F,
  154131. 0.4111287047F, 0.4267624093F, 0.4424557009F, 0.4581897696F,
  154132. 0.4739456913F, 0.4897044744F, 0.5054471075F, 0.5211546088F,
  154133. 0.5368080763F, 0.5523887395F, 0.5678780103F, 0.5832575361F,
  154134. 0.5985092508F, 0.6136154277F, 0.6285587300F, 0.6433222619F,
  154135. 0.6578896175F, 0.6722449294F, 0.6863729144F, 0.7002589187F,
  154136. 0.7138889597F, 0.7272497662F, 0.7403288154F, 0.7531143679F,
  154137. 0.7655954985F, 0.7777621249F, 0.7896050322F, 0.8011158947F,
  154138. 0.8122872932F, 0.8231127294F, 0.8335866365F, 0.8437043850F,
  154139. 0.8534622861F, 0.8628575905F, 0.8718884835F, 0.8805540765F,
  154140. 0.8888543947F, 0.8967903616F, 0.9043637797F, 0.9115773078F,
  154141. 0.9184344360F, 0.9249394562F, 0.9310974312F, 0.9369141608F,
  154142. 0.9423961446F, 0.9475505439F, 0.9523851406F, 0.9569082947F,
  154143. 0.9611289005F, 0.9650563408F, 0.9687004405F, 0.9720714191F,
  154144. 0.9751798427F, 0.9780365753F, 0.9806527301F, 0.9830396204F,
  154145. 0.9852087111F, 0.9871715701F, 0.9889398207F, 0.9905250941F,
  154146. 0.9919389832F, 0.9931929973F, 0.9942985174F, 0.9952667537F,
  154147. 0.9961087037F, 0.9968351119F, 0.9974564312F, 0.9979827858F,
  154148. 0.9984239359F, 0.9987892441F, 0.9990876435F, 0.9993276081F,
  154149. 0.9995171241F, 0.9996636648F, 0.9997741654F, 0.9998550016F,
  154150. 0.9999119692F, 0.9999502656F, 0.9999744742F, 0.9999885497F,
  154151. 0.9999958064F, 0.9999989077F, 0.9999998584F, 0.9999999983F,
  154152. };
  154153. static float vwin512[256] = {
  154154. 0.0000147849F, 0.0001330607F, 0.0003695946F, 0.0007243509F,
  154155. 0.0011972759F, 0.0017882983F, 0.0024973285F, 0.0033242588F,
  154156. 0.0042689632F, 0.0053312973F, 0.0065110982F, 0.0078081841F,
  154157. 0.0092223540F, 0.0107533880F, 0.0124010466F, 0.0141650703F,
  154158. 0.0160451800F, 0.0180410758F, 0.0201524373F, 0.0223789233F,
  154159. 0.0247201710F, 0.0271757958F, 0.0297453914F, 0.0324285286F,
  154160. 0.0352247556F, 0.0381335972F, 0.0411545545F, 0.0442871045F,
  154161. 0.0475306997F, 0.0508847676F, 0.0543487103F, 0.0579219038F,
  154162. 0.0616036982F, 0.0653934164F, 0.0692903546F, 0.0732937809F,
  154163. 0.0774029356F, 0.0816170305F, 0.0859352485F, 0.0903567428F,
  154164. 0.0948806375F, 0.0995060259F, 0.1042319712F, 0.1090575056F,
  154165. 0.1139816300F, 0.1190033137F, 0.1241214941F, 0.1293350764F,
  154166. 0.1346429333F, 0.1400439046F, 0.1455367974F, 0.1511203852F,
  154167. 0.1567934083F, 0.1625545735F, 0.1684025537F, 0.1743359881F,
  154168. 0.1803534820F, 0.1864536069F, 0.1926349000F, 0.1988958650F,
  154169. 0.2052349715F, 0.2116506555F, 0.2181413191F, 0.2247053313F,
  154170. 0.2313410275F, 0.2380467105F, 0.2448206500F, 0.2516610835F,
  154171. 0.2585662164F, 0.2655342226F, 0.2725632448F, 0.2796513950F,
  154172. 0.2867967551F, 0.2939973773F, 0.3012512852F, 0.3085564739F,
  154173. 0.3159109111F, 0.3233125375F, 0.3307592680F, 0.3382489922F,
  154174. 0.3457795756F, 0.3533488602F, 0.3609546657F, 0.3685947904F,
  154175. 0.3762670121F, 0.3839690896F, 0.3916987634F, 0.3994537572F,
  154176. 0.4072317788F, 0.4150305215F, 0.4228476653F, 0.4306808783F,
  154177. 0.4385278181F, 0.4463861329F, 0.4542534630F, 0.4621274424F,
  154178. 0.4700057001F, 0.4778858615F, 0.4857655502F, 0.4936423891F,
  154179. 0.5015140023F, 0.5093780165F, 0.5172320626F, 0.5250737772F,
  154180. 0.5329008043F, 0.5407107971F, 0.5485014192F, 0.5562703465F,
  154181. 0.5640152688F, 0.5717338914F, 0.5794239366F, 0.5870831457F,
  154182. 0.5947092801F, 0.6023001235F, 0.6098534829F, 0.6173671907F,
  154183. 0.6248391059F, 0.6322671161F, 0.6396491384F, 0.6469831217F,
  154184. 0.6542670475F, 0.6614989319F, 0.6686768267F, 0.6757988210F,
  154185. 0.6828630426F, 0.6898676592F, 0.6968108799F, 0.7036909564F,
  154186. 0.7105061843F, 0.7172549043F, 0.7239355032F, 0.7305464154F,
  154187. 0.7370861235F, 0.7435531598F, 0.7499461068F, 0.7562635986F,
  154188. 0.7625043214F, 0.7686670148F, 0.7747504721F, 0.7807535410F,
  154189. 0.7866751247F, 0.7925141825F, 0.7982697296F, 0.8039408387F,
  154190. 0.8095266395F, 0.8150263196F, 0.8204391248F, 0.8257643590F,
  154191. 0.8310013848F, 0.8361496236F, 0.8412085555F, 0.8461777194F,
  154192. 0.8510567129F, 0.8558451924F, 0.8605428730F, 0.8651495278F,
  154193. 0.8696649882F, 0.8740891432F, 0.8784219392F, 0.8826633797F,
  154194. 0.8868135244F, 0.8908724888F, 0.8948404441F, 0.8987176157F,
  154195. 0.9025042831F, 0.9062007791F, 0.9098074886F, 0.9133248482F,
  154196. 0.9167533451F, 0.9200935163F, 0.9233459472F, 0.9265112712F,
  154197. 0.9295901680F, 0.9325833632F, 0.9354916263F, 0.9383157705F,
  154198. 0.9410566504F, 0.9437151618F, 0.9462922398F, 0.9487888576F,
  154199. 0.9512060252F, 0.9535447882F, 0.9558062262F, 0.9579914516F,
  154200. 0.9601016078F, 0.9621378683F, 0.9641014348F, 0.9659935361F,
  154201. 0.9678154261F, 0.9695683830F, 0.9712537071F, 0.9728727198F,
  154202. 0.9744267618F, 0.9759171916F, 0.9773453842F, 0.9787127293F,
  154203. 0.9800206298F, 0.9812705006F, 0.9824637665F, 0.9836018613F,
  154204. 0.9846862258F, 0.9857183066F, 0.9866995544F, 0.9876314227F,
  154205. 0.9885153662F, 0.9893528393F, 0.9901452948F, 0.9908941823F,
  154206. 0.9916009470F, 0.9922670279F, 0.9928938570F, 0.9934828574F,
  154207. 0.9940354423F, 0.9945530133F, 0.9950369595F, 0.9954886562F,
  154208. 0.9959094633F, 0.9963007242F, 0.9966637649F, 0.9969998925F,
  154209. 0.9973103939F, 0.9975965351F, 0.9978595598F, 0.9981006885F,
  154210. 0.9983211172F, 0.9985220166F, 0.9987045311F, 0.9988697776F,
  154211. 0.9990188449F, 0.9991527924F, 0.9992726499F, 0.9993794157F,
  154212. 0.9994740570F, 0.9995575079F, 0.9996306699F, 0.9996944099F,
  154213. 0.9997495605F, 0.9997969190F, 0.9998372465F, 0.9998712678F,
  154214. 0.9998996704F, 0.9999231041F, 0.9999421807F, 0.9999574732F,
  154215. 0.9999695157F, 0.9999788026F, 0.9999857885F, 0.9999908879F,
  154216. 0.9999944746F, 0.9999968817F, 0.9999984010F, 0.9999992833F,
  154217. 0.9999997377F, 0.9999999317F, 0.9999999911F, 0.9999999999F,
  154218. };
  154219. static float vwin1024[512] = {
  154220. 0.0000036962F, 0.0000332659F, 0.0000924041F, 0.0001811086F,
  154221. 0.0002993761F, 0.0004472021F, 0.0006245811F, 0.0008315063F,
  154222. 0.0010679699F, 0.0013339631F, 0.0016294757F, 0.0019544965F,
  154223. 0.0023090133F, 0.0026930125F, 0.0031064797F, 0.0035493989F,
  154224. 0.0040217533F, 0.0045235250F, 0.0050546946F, 0.0056152418F,
  154225. 0.0062051451F, 0.0068243817F, 0.0074729278F, 0.0081507582F,
  154226. 0.0088578466F, 0.0095941655F, 0.0103596863F, 0.0111543789F,
  154227. 0.0119782122F, 0.0128311538F, 0.0137131701F, 0.0146242260F,
  154228. 0.0155642855F, 0.0165333111F, 0.0175312640F, 0.0185581042F,
  154229. 0.0196137903F, 0.0206982797F, 0.0218115284F, 0.0229534910F,
  154230. 0.0241241208F, 0.0253233698F, 0.0265511886F, 0.0278075263F,
  154231. 0.0290923308F, 0.0304055484F, 0.0317471241F, 0.0331170013F,
  154232. 0.0345151222F, 0.0359414274F, 0.0373958560F, 0.0388783456F,
  154233. 0.0403888325F, 0.0419272511F, 0.0434935347F, 0.0450876148F,
  154234. 0.0467094213F, 0.0483588828F, 0.0500359261F, 0.0517404765F,
  154235. 0.0534724575F, 0.0552317913F, 0.0570183983F, 0.0588321971F,
  154236. 0.0606731048F, 0.0625410369F, 0.0644359070F, 0.0663576272F,
  154237. 0.0683061077F, 0.0702812571F, 0.0722829821F, 0.0743111878F,
  154238. 0.0763657775F, 0.0784466526F, 0.0805537129F, 0.0826868561F,
  154239. 0.0848459782F, 0.0870309736F, 0.0892417345F, 0.0914781514F,
  154240. 0.0937401128F, 0.0960275056F, 0.0983402145F, 0.1006781223F,
  154241. 0.1030411101F, 0.1054290568F, 0.1078418397F, 0.1102793336F,
  154242. 0.1127414119F, 0.1152279457F, 0.1177388042F, 0.1202738544F,
  154243. 0.1228329618F, 0.1254159892F, 0.1280227980F, 0.1306532471F,
  154244. 0.1333071937F, 0.1359844927F, 0.1386849970F, 0.1414085575F,
  154245. 0.1441550230F, 0.1469242403F, 0.1497160539F, 0.1525303063F,
  154246. 0.1553668381F, 0.1582254875F, 0.1611060909F, 0.1640084822F,
  154247. 0.1669324936F, 0.1698779549F, 0.1728446939F, 0.1758325362F,
  154248. 0.1788413055F, 0.1818708232F, 0.1849209084F, 0.1879913785F,
  154249. 0.1910820485F, 0.1941927312F, 0.1973232376F, 0.2004733764F,
  154250. 0.2036429541F, 0.2068317752F, 0.2100396421F, 0.2132663552F,
  154251. 0.2165117125F, 0.2197755102F, 0.2230575422F, 0.2263576007F,
  154252. 0.2296754753F, 0.2330109540F, 0.2363638225F, 0.2397338646F,
  154253. 0.2431208619F, 0.2465245941F, 0.2499448389F, 0.2533813719F,
  154254. 0.2568339669F, 0.2603023956F, 0.2637864277F, 0.2672858312F,
  154255. 0.2708003718F, 0.2743298135F, 0.2778739186F, 0.2814324472F,
  154256. 0.2850051576F, 0.2885918065F, 0.2921921485F, 0.2958059366F,
  154257. 0.2994329219F, 0.3030728538F, 0.3067254799F, 0.3103905462F,
  154258. 0.3140677969F, 0.3177569747F, 0.3214578205F, 0.3251700736F,
  154259. 0.3288934718F, 0.3326277513F, 0.3363726468F, 0.3401278914F,
  154260. 0.3438932168F, 0.3476683533F, 0.3514530297F, 0.3552469734F,
  154261. 0.3590499106F, 0.3628615659F, 0.3666816630F, 0.3705099239F,
  154262. 0.3743460698F, 0.3781898204F, 0.3820408945F, 0.3858990095F,
  154263. 0.3897638820F, 0.3936352274F, 0.3975127601F, 0.4013961936F,
  154264. 0.4052852405F, 0.4091796123F, 0.4130790198F, 0.4169831732F,
  154265. 0.4208917815F, 0.4248045534F, 0.4287211965F, 0.4326414181F,
  154266. 0.4365649248F, 0.4404914225F, 0.4444206167F, 0.4483522125F,
  154267. 0.4522859146F, 0.4562214270F, 0.4601584538F, 0.4640966984F,
  154268. 0.4680358644F, 0.4719756548F, 0.4759157726F, 0.4798559209F,
  154269. 0.4837958024F, 0.4877351199F, 0.4916735765F, 0.4956108751F,
  154270. 0.4995467188F, 0.5034808109F, 0.5074128550F, 0.5113425550F,
  154271. 0.5152696149F, 0.5191937395F, 0.5231146336F, 0.5270320028F,
  154272. 0.5309455530F, 0.5348549910F, 0.5387600239F, 0.5426603597F,
  154273. 0.5465557070F, 0.5504457754F, 0.5543302752F, 0.5582089175F,
  154274. 0.5620814145F, 0.5659474793F, 0.5698068262F, 0.5736591704F,
  154275. 0.5775042283F, 0.5813417176F, 0.5851713571F, 0.5889928670F,
  154276. 0.5928059689F, 0.5966103856F, 0.6004058415F, 0.6041920626F,
  154277. 0.6079687761F, 0.6117357113F, 0.6154925986F, 0.6192391705F,
  154278. 0.6229751612F, 0.6267003064F, 0.6304143441F, 0.6341170137F,
  154279. 0.6378080569F, 0.6414872173F, 0.6451542405F, 0.6488088741F,
  154280. 0.6524508681F, 0.6560799742F, 0.6596959469F, 0.6632985424F,
  154281. 0.6668875197F, 0.6704626398F, 0.6740236662F, 0.6775703649F,
  154282. 0.6811025043F, 0.6846198554F, 0.6881221916F, 0.6916092892F,
  154283. 0.6950809269F, 0.6985368861F, 0.7019769510F, 0.7054009085F,
  154284. 0.7088085484F, 0.7121996632F, 0.7155740484F, 0.7189315023F,
  154285. 0.7222718263F, 0.7255948245F, 0.7289003043F, 0.7321880760F,
  154286. 0.7354579530F, 0.7387097518F, 0.7419432921F, 0.7451583966F,
  154287. 0.7483548915F, 0.7515326059F, 0.7546913723F, 0.7578310265F,
  154288. 0.7609514077F, 0.7640523581F, 0.7671337237F, 0.7701953535F,
  154289. 0.7732371001F, 0.7762588195F, 0.7792603711F, 0.7822416178F,
  154290. 0.7852024259F, 0.7881426654F, 0.7910622097F, 0.7939609356F,
  154291. 0.7968387237F, 0.7996954579F, 0.8025310261F, 0.8053453193F,
  154292. 0.8081382324F, 0.8109096638F, 0.8136595156F, 0.8163876936F,
  154293. 0.8190941071F, 0.8217786690F, 0.8244412960F, 0.8270819086F,
  154294. 0.8297004305F, 0.8322967896F, 0.8348709171F, 0.8374227481F,
  154295. 0.8399522213F, 0.8424592789F, 0.8449438672F, 0.8474059356F,
  154296. 0.8498454378F, 0.8522623306F, 0.8546565748F, 0.8570281348F,
  154297. 0.8593769787F, 0.8617030779F, 0.8640064080F, 0.8662869477F,
  154298. 0.8685446796F, 0.8707795899F, 0.8729916682F, 0.8751809079F,
  154299. 0.8773473059F, 0.8794908626F, 0.8816115819F, 0.8837094713F,
  154300. 0.8857845418F, 0.8878368079F, 0.8898662874F, 0.8918730019F,
  154301. 0.8938569760F, 0.8958182380F, 0.8977568194F, 0.8996727552F,
  154302. 0.9015660837F, 0.9034368465F, 0.9052850885F, 0.9071108577F,
  154303. 0.9089142057F, 0.9106951869F, 0.9124538591F, 0.9141902832F,
  154304. 0.9159045233F, 0.9175966464F, 0.9192667228F, 0.9209148257F,
  154305. 0.9225410313F, 0.9241454187F, 0.9257280701F, 0.9272890704F,
  154306. 0.9288285075F, 0.9303464720F, 0.9318430576F, 0.9333183603F,
  154307. 0.9347724792F, 0.9362055158F, 0.9376175745F, 0.9390087622F,
  154308. 0.9403791881F, 0.9417289644F, 0.9430582055F, 0.9443670283F,
  154309. 0.9456555521F, 0.9469238986F, 0.9481721917F, 0.9494005577F,
  154310. 0.9506091252F, 0.9517980248F, 0.9529673894F, 0.9541173540F,
  154311. 0.9552480557F, 0.9563596334F, 0.9574522282F, 0.9585259830F,
  154312. 0.9595810428F, 0.9606175542F, 0.9616356656F, 0.9626355274F,
  154313. 0.9636172915F, 0.9645811114F, 0.9655271425F, 0.9664555414F,
  154314. 0.9673664664F, 0.9682600774F, 0.9691365355F, 0.9699960034F,
  154315. 0.9708386448F, 0.9716646250F, 0.9724741103F, 0.9732672685F,
  154316. 0.9740442683F, 0.9748052795F, 0.9755504729F, 0.9762800205F,
  154317. 0.9769940950F, 0.9776928703F, 0.9783765210F, 0.9790452223F,
  154318. 0.9796991504F, 0.9803384823F, 0.9809633954F, 0.9815740679F,
  154319. 0.9821706784F, 0.9827534063F, 0.9833224312F, 0.9838779332F,
  154320. 0.9844200928F, 0.9849490910F, 0.9854651087F, 0.9859683274F,
  154321. 0.9864589286F, 0.9869370940F, 0.9874030054F, 0.9878568447F,
  154322. 0.9882987937F, 0.9887290343F, 0.9891477481F, 0.9895551169F,
  154323. 0.9899513220F, 0.9903365446F, 0.9907109658F, 0.9910747662F,
  154324. 0.9914281260F, 0.9917712252F, 0.9921042433F, 0.9924273593F,
  154325. 0.9927407516F, 0.9930445982F, 0.9933390763F, 0.9936243626F,
  154326. 0.9939006331F, 0.9941680631F, 0.9944268269F, 0.9946770982F,
  154327. 0.9949190498F, 0.9951528537F, 0.9953786808F, 0.9955967011F,
  154328. 0.9958070836F, 0.9960099963F, 0.9962056061F, 0.9963940787F,
  154329. 0.9965755786F, 0.9967502693F, 0.9969183129F, 0.9970798704F,
  154330. 0.9972351013F, 0.9973841640F, 0.9975272151F, 0.9976644103F,
  154331. 0.9977959036F, 0.9979218476F, 0.9980423932F, 0.9981576901F,
  154332. 0.9982678862F, 0.9983731278F, 0.9984735596F, 0.9985693247F,
  154333. 0.9986605645F, 0.9987474186F, 0.9988300248F, 0.9989085193F,
  154334. 0.9989830364F, 0.9990537085F, 0.9991206662F, 0.9991840382F,
  154335. 0.9992439513F, 0.9993005303F, 0.9993538982F, 0.9994041757F,
  154336. 0.9994514817F, 0.9994959330F, 0.9995376444F, 0.9995767286F,
  154337. 0.9996132960F, 0.9996474550F, 0.9996793121F, 0.9997089710F,
  154338. 0.9997365339F, 0.9997621003F, 0.9997857677F, 0.9998076311F,
  154339. 0.9998277836F, 0.9998463156F, 0.9998633155F, 0.9998788692F,
  154340. 0.9998930603F, 0.9999059701F, 0.9999176774F, 0.9999282586F,
  154341. 0.9999377880F, 0.9999463370F, 0.9999539749F, 0.9999607685F,
  154342. 0.9999667820F, 0.9999720773F, 0.9999767136F, 0.9999807479F,
  154343. 0.9999842344F, 0.9999872249F, 0.9999897688F, 0.9999919127F,
  154344. 0.9999937009F, 0.9999951749F, 0.9999963738F, 0.9999973342F,
  154345. 0.9999980900F, 0.9999986724F, 0.9999991103F, 0.9999994297F,
  154346. 0.9999996543F, 0.9999998049F, 0.9999999000F, 0.9999999552F,
  154347. 0.9999999836F, 0.9999999957F, 0.9999999994F, 1.0000000000F,
  154348. };
  154349. static float vwin2048[1024] = {
  154350. 0.0000009241F, 0.0000083165F, 0.0000231014F, 0.0000452785F,
  154351. 0.0000748476F, 0.0001118085F, 0.0001561608F, 0.0002079041F,
  154352. 0.0002670379F, 0.0003335617F, 0.0004074748F, 0.0004887765F,
  154353. 0.0005774661F, 0.0006735427F, 0.0007770054F, 0.0008878533F,
  154354. 0.0010060853F, 0.0011317002F, 0.0012646969F, 0.0014050742F,
  154355. 0.0015528307F, 0.0017079650F, 0.0018704756F, 0.0020403610F,
  154356. 0.0022176196F, 0.0024022497F, 0.0025942495F, 0.0027936173F,
  154357. 0.0030003511F, 0.0032144490F, 0.0034359088F, 0.0036647286F,
  154358. 0.0039009061F, 0.0041444391F, 0.0043953253F, 0.0046535621F,
  154359. 0.0049191472F, 0.0051920781F, 0.0054723520F, 0.0057599664F,
  154360. 0.0060549184F, 0.0063572052F, 0.0066668239F, 0.0069837715F,
  154361. 0.0073080449F, 0.0076396410F, 0.0079785566F, 0.0083247884F,
  154362. 0.0086783330F, 0.0090391871F, 0.0094073470F, 0.0097828092F,
  154363. 0.0101655700F, 0.0105556258F, 0.0109529726F, 0.0113576065F,
  154364. 0.0117695237F, 0.0121887200F, 0.0126151913F, 0.0130489335F,
  154365. 0.0134899422F, 0.0139382130F, 0.0143937415F, 0.0148565233F,
  154366. 0.0153265536F, 0.0158038279F, 0.0162883413F, 0.0167800889F,
  154367. 0.0172790660F, 0.0177852675F, 0.0182986882F, 0.0188193231F,
  154368. 0.0193471668F, 0.0198822141F, 0.0204244594F, 0.0209738974F,
  154369. 0.0215305225F, 0.0220943289F, 0.0226653109F, 0.0232434627F,
  154370. 0.0238287784F, 0.0244212519F, 0.0250208772F, 0.0256276481F,
  154371. 0.0262415582F, 0.0268626014F, 0.0274907711F, 0.0281260608F,
  154372. 0.0287684638F, 0.0294179736F, 0.0300745833F, 0.0307382859F,
  154373. 0.0314090747F, 0.0320869424F, 0.0327718819F, 0.0334638860F,
  154374. 0.0341629474F, 0.0348690586F, 0.0355822122F, 0.0363024004F,
  154375. 0.0370296157F, 0.0377638502F, 0.0385050960F, 0.0392533451F,
  154376. 0.0400085896F, 0.0407708211F, 0.0415400315F, 0.0423162123F,
  154377. 0.0430993552F, 0.0438894515F, 0.0446864926F, 0.0454904698F,
  154378. 0.0463013742F, 0.0471191969F, 0.0479439288F, 0.0487755607F,
  154379. 0.0496140836F, 0.0504594879F, 0.0513117642F, 0.0521709031F,
  154380. 0.0530368949F, 0.0539097297F, 0.0547893979F, 0.0556758894F,
  154381. 0.0565691941F, 0.0574693019F, 0.0583762026F, 0.0592898858F,
  154382. 0.0602103410F, 0.0611375576F, 0.0620715250F, 0.0630122324F,
  154383. 0.0639596688F, 0.0649138234F, 0.0658746848F, 0.0668422421F,
  154384. 0.0678164838F, 0.0687973985F, 0.0697849746F, 0.0707792005F,
  154385. 0.0717800645F, 0.0727875547F, 0.0738016591F, 0.0748223656F,
  154386. 0.0758496620F, 0.0768835359F, 0.0779239751F, 0.0789709668F,
  154387. 0.0800244985F, 0.0810845574F, 0.0821511306F, 0.0832242052F,
  154388. 0.0843037679F, 0.0853898056F, 0.0864823050F, 0.0875812525F,
  154389. 0.0886866347F, 0.0897984378F, 0.0909166480F, 0.0920412513F,
  154390. 0.0931722338F, 0.0943095813F, 0.0954532795F, 0.0966033140F,
  154391. 0.0977596702F, 0.0989223336F, 0.1000912894F, 0.1012665227F,
  154392. 0.1024480185F, 0.1036357616F, 0.1048297369F, 0.1060299290F,
  154393. 0.1072363224F, 0.1084489014F, 0.1096676504F, 0.1108925534F,
  154394. 0.1121235946F, 0.1133607577F, 0.1146040267F, 0.1158533850F,
  154395. 0.1171088163F, 0.1183703040F, 0.1196378312F, 0.1209113812F,
  154396. 0.1221909370F, 0.1234764815F, 0.1247679974F, 0.1260654674F,
  154397. 0.1273688740F, 0.1286781995F, 0.1299934263F, 0.1313145365F,
  154398. 0.1326415121F, 0.1339743349F, 0.1353129866F, 0.1366574490F,
  154399. 0.1380077035F, 0.1393637315F, 0.1407255141F, 0.1420930325F,
  154400. 0.1434662677F, 0.1448452004F, 0.1462298115F, 0.1476200814F,
  154401. 0.1490159906F, 0.1504175195F, 0.1518246482F, 0.1532373569F,
  154402. 0.1546556253F, 0.1560794333F, 0.1575087606F, 0.1589435866F,
  154403. 0.1603838909F, 0.1618296526F, 0.1632808509F, 0.1647374648F,
  154404. 0.1661994731F, 0.1676668546F, 0.1691395880F, 0.1706176516F,
  154405. 0.1721010238F, 0.1735896829F, 0.1750836068F, 0.1765827736F,
  154406. 0.1780871610F, 0.1795967468F, 0.1811115084F, 0.1826314234F,
  154407. 0.1841564689F, 0.1856866221F, 0.1872218600F, 0.1887621595F,
  154408. 0.1903074974F, 0.1918578503F, 0.1934131947F, 0.1949735068F,
  154409. 0.1965387630F, 0.1981089393F, 0.1996840117F, 0.2012639560F,
  154410. 0.2028487479F, 0.2044383630F, 0.2060327766F, 0.2076319642F,
  154411. 0.2092359007F, 0.2108445614F, 0.2124579211F, 0.2140759545F,
  154412. 0.2156986364F, 0.2173259411F, 0.2189578432F, 0.2205943168F,
  154413. 0.2222353361F, 0.2238808751F, 0.2255309076F, 0.2271854073F,
  154414. 0.2288443480F, 0.2305077030F, 0.2321754457F, 0.2338475493F,
  154415. 0.2355239869F, 0.2372047315F, 0.2388897560F, 0.2405790329F,
  154416. 0.2422725350F, 0.2439702347F, 0.2456721043F, 0.2473781159F,
  154417. 0.2490882418F, 0.2508024539F, 0.2525207240F, 0.2542430237F,
  154418. 0.2559693248F, 0.2576995986F, 0.2594338166F, 0.2611719498F,
  154419. 0.2629139695F, 0.2646598466F, 0.2664095520F, 0.2681630564F,
  154420. 0.2699203304F, 0.2716813445F, 0.2734460691F, 0.2752144744F,
  154421. 0.2769865307F, 0.2787622079F, 0.2805414760F, 0.2823243047F,
  154422. 0.2841106637F, 0.2859005227F, 0.2876938509F, 0.2894906179F,
  154423. 0.2912907928F, 0.2930943447F, 0.2949012426F, 0.2967114554F,
  154424. 0.2985249520F, 0.3003417009F, 0.3021616708F, 0.3039848301F,
  154425. 0.3058111471F, 0.3076405901F, 0.3094731273F, 0.3113087266F,
  154426. 0.3131473560F, 0.3149889833F, 0.3168335762F, 0.3186811024F,
  154427. 0.3205315294F, 0.3223848245F, 0.3242409552F, 0.3260998886F,
  154428. 0.3279615918F, 0.3298260319F, 0.3316931758F, 0.3335629903F,
  154429. 0.3354354423F, 0.3373104982F, 0.3391881247F, 0.3410682882F,
  154430. 0.3429509551F, 0.3448360917F, 0.3467236642F, 0.3486136387F,
  154431. 0.3505059811F, 0.3524006575F, 0.3542976336F, 0.3561968753F,
  154432. 0.3580983482F, 0.3600020179F, 0.3619078499F, 0.3638158096F,
  154433. 0.3657258625F, 0.3676379737F, 0.3695521086F, 0.3714682321F,
  154434. 0.3733863094F, 0.3753063055F, 0.3772281852F, 0.3791519134F,
  154435. 0.3810774548F, 0.3830047742F, 0.3849338362F, 0.3868646053F,
  154436. 0.3887970459F, 0.3907311227F, 0.3926667998F, 0.3946040417F,
  154437. 0.3965428125F, 0.3984830765F, 0.4004247978F, 0.4023679403F,
  154438. 0.4043124683F, 0.4062583455F, 0.4082055359F, 0.4101540034F,
  154439. 0.4121037117F, 0.4140546246F, 0.4160067058F, 0.4179599190F,
  154440. 0.4199142277F, 0.4218695956F, 0.4238259861F, 0.4257833627F,
  154441. 0.4277416888F, 0.4297009279F, 0.4316610433F, 0.4336219983F,
  154442. 0.4355837562F, 0.4375462803F, 0.4395095337F, 0.4414734797F,
  154443. 0.4434380815F, 0.4454033021F, 0.4473691046F, 0.4493354521F,
  154444. 0.4513023078F, 0.4532696345F, 0.4552373954F, 0.4572055533F,
  154445. 0.4591740713F, 0.4611429123F, 0.4631120393F, 0.4650814151F,
  154446. 0.4670510028F, 0.4690207650F, 0.4709906649F, 0.4729606651F,
  154447. 0.4749307287F, 0.4769008185F, 0.4788708972F, 0.4808409279F,
  154448. 0.4828108732F, 0.4847806962F, 0.4867503597F, 0.4887198264F,
  154449. 0.4906890593F, 0.4926580213F, 0.4946266753F, 0.4965949840F,
  154450. 0.4985629105F, 0.5005304176F, 0.5024974683F, 0.5044640255F,
  154451. 0.5064300522F, 0.5083955114F, 0.5103603659F, 0.5123245790F,
  154452. 0.5142881136F, 0.5162509328F, 0.5182129997F, 0.5201742774F,
  154453. 0.5221347290F, 0.5240943178F, 0.5260530070F, 0.5280107598F,
  154454. 0.5299675395F, 0.5319233095F, 0.5338780330F, 0.5358316736F,
  154455. 0.5377841946F, 0.5397355596F, 0.5416857320F, 0.5436346755F,
  154456. 0.5455823538F, 0.5475287304F, 0.5494737691F, 0.5514174337F,
  154457. 0.5533596881F, 0.5553004962F, 0.5572398218F, 0.5591776291F,
  154458. 0.5611138821F, 0.5630485449F, 0.5649815818F, 0.5669129570F,
  154459. 0.5688426349F, 0.5707705799F, 0.5726967564F, 0.5746211290F,
  154460. 0.5765436624F, 0.5784643212F, 0.5803830702F, 0.5822998743F,
  154461. 0.5842146984F, 0.5861275076F, 0.5880382669F, 0.5899469416F,
  154462. 0.5918534968F, 0.5937578981F, 0.5956601107F, 0.5975601004F,
  154463. 0.5994578326F, 0.6013532732F, 0.6032463880F, 0.6051371429F,
  154464. 0.6070255039F, 0.6089114372F, 0.6107949090F, 0.6126758856F,
  154465. 0.6145543334F, 0.6164302191F, 0.6183035092F, 0.6201741706F,
  154466. 0.6220421700F, 0.6239074745F, 0.6257700513F, 0.6276298674F,
  154467. 0.6294868903F, 0.6313410873F, 0.6331924262F, 0.6350408745F,
  154468. 0.6368864001F, 0.6387289710F, 0.6405685552F, 0.6424051209F,
  154469. 0.6442386364F, 0.6460690702F, 0.6478963910F, 0.6497205673F,
  154470. 0.6515415682F, 0.6533593625F, 0.6551739194F, 0.6569852082F,
  154471. 0.6587931984F, 0.6605978593F, 0.6623991609F, 0.6641970728F,
  154472. 0.6659915652F, 0.6677826081F, 0.6695701718F, 0.6713542268F,
  154473. 0.6731347437F, 0.6749116932F, 0.6766850461F, 0.6784547736F,
  154474. 0.6802208469F, 0.6819832374F, 0.6837419164F, 0.6854968559F,
  154475. 0.6872480275F, 0.6889954034F, 0.6907389556F, 0.6924786566F,
  154476. 0.6942144788F, 0.6959463950F, 0.6976743780F, 0.6993984008F,
  154477. 0.7011184365F, 0.7028344587F, 0.7045464407F, 0.7062543564F,
  154478. 0.7079581796F, 0.7096578844F, 0.7113534450F, 0.7130448359F,
  154479. 0.7147320316F, 0.7164150070F, 0.7180937371F, 0.7197681970F,
  154480. 0.7214383620F, 0.7231042077F, 0.7247657098F, 0.7264228443F,
  154481. 0.7280755871F, 0.7297239147F, 0.7313678035F, 0.7330072301F,
  154482. 0.7346421715F, 0.7362726046F, 0.7378985069F, 0.7395198556F,
  154483. 0.7411366285F, 0.7427488034F, 0.7443563584F, 0.7459592717F,
  154484. 0.7475575218F, 0.7491510873F, 0.7507399471F, 0.7523240803F,
  154485. 0.7539034661F, 0.7554780839F, 0.7570479136F, 0.7586129349F,
  154486. 0.7601731279F, 0.7617284730F, 0.7632789506F, 0.7648245416F,
  154487. 0.7663652267F, 0.7679009872F, 0.7694318044F, 0.7709576599F,
  154488. 0.7724785354F, 0.7739944130F, 0.7755052749F, 0.7770111035F,
  154489. 0.7785118815F, 0.7800075916F, 0.7814982170F, 0.7829837410F,
  154490. 0.7844641472F, 0.7859394191F, 0.7874095408F, 0.7888744965F,
  154491. 0.7903342706F, 0.7917888476F, 0.7932382124F, 0.7946823501F,
  154492. 0.7961212460F, 0.7975548855F, 0.7989832544F, 0.8004063386F,
  154493. 0.8018241244F, 0.8032365981F, 0.8046437463F, 0.8060455560F,
  154494. 0.8074420141F, 0.8088331080F, 0.8102188253F, 0.8115991536F,
  154495. 0.8129740810F, 0.8143435957F, 0.8157076861F, 0.8170663409F,
  154496. 0.8184195489F, 0.8197672994F, 0.8211095817F, 0.8224463853F,
  154497. 0.8237777001F, 0.8251035161F, 0.8264238235F, 0.8277386129F,
  154498. 0.8290478750F, 0.8303516008F, 0.8316497814F, 0.8329424083F,
  154499. 0.8342294731F, 0.8355109677F, 0.8367868841F, 0.8380572148F,
  154500. 0.8393219523F, 0.8405810893F, 0.8418346190F, 0.8430825345F,
  154501. 0.8443248294F, 0.8455614974F, 0.8467925323F, 0.8480179285F,
  154502. 0.8492376802F, 0.8504517822F, 0.8516602292F, 0.8528630164F,
  154503. 0.8540601391F, 0.8552515928F, 0.8564373733F, 0.8576174766F,
  154504. 0.8587918990F, 0.8599606368F, 0.8611236868F, 0.8622810460F,
  154505. 0.8634327113F, 0.8645786802F, 0.8657189504F, 0.8668535195F,
  154506. 0.8679823857F, 0.8691055472F, 0.8702230025F, 0.8713347503F,
  154507. 0.8724407896F, 0.8735411194F, 0.8746357394F, 0.8757246489F,
  154508. 0.8768078479F, 0.8778853364F, 0.8789571146F, 0.8800231832F,
  154509. 0.8810835427F, 0.8821381942F, 0.8831871387F, 0.8842303777F,
  154510. 0.8852679127F, 0.8862997456F, 0.8873258784F, 0.8883463132F,
  154511. 0.8893610527F, 0.8903700994F, 0.8913734562F, 0.8923711263F,
  154512. 0.8933631129F, 0.8943494196F, 0.8953300500F, 0.8963050083F,
  154513. 0.8972742985F, 0.8982379249F, 0.8991958922F, 0.9001482052F,
  154514. 0.9010948688F, 0.9020358883F, 0.9029712690F, 0.9039010165F,
  154515. 0.9048251367F, 0.9057436357F, 0.9066565195F, 0.9075637946F,
  154516. 0.9084654678F, 0.9093615456F, 0.9102520353F, 0.9111369440F,
  154517. 0.9120162792F, 0.9128900484F, 0.9137582595F, 0.9146209204F,
  154518. 0.9154780394F, 0.9163296248F, 0.9171756853F, 0.9180162296F,
  154519. 0.9188512667F, 0.9196808057F, 0.9205048559F, 0.9213234270F,
  154520. 0.9221365285F, 0.9229441704F, 0.9237463629F, 0.9245431160F,
  154521. 0.9253344404F, 0.9261203465F, 0.9269008453F, 0.9276759477F,
  154522. 0.9284456648F, 0.9292100080F, 0.9299689889F, 0.9307226190F,
  154523. 0.9314709103F, 0.9322138747F, 0.9329515245F, 0.9336838721F,
  154524. 0.9344109300F, 0.9351327108F, 0.9358492275F, 0.9365604931F,
  154525. 0.9372665208F, 0.9379673239F, 0.9386629160F, 0.9393533107F,
  154526. 0.9400385220F, 0.9407185637F, 0.9413934501F, 0.9420631954F,
  154527. 0.9427278141F, 0.9433873208F, 0.9440417304F, 0.9446910576F,
  154528. 0.9453353176F, 0.9459745255F, 0.9466086968F, 0.9472378469F,
  154529. 0.9478619915F, 0.9484811463F, 0.9490953274F, 0.9497045506F,
  154530. 0.9503088323F, 0.9509081888F, 0.9515026365F, 0.9520921921F,
  154531. 0.9526768723F, 0.9532566940F, 0.9538316742F, 0.9544018300F,
  154532. 0.9549671786F, 0.9555277375F, 0.9560835241F, 0.9566345562F,
  154533. 0.9571808513F, 0.9577224275F, 0.9582593027F, 0.9587914949F,
  154534. 0.9593190225F, 0.9598419038F, 0.9603601571F, 0.9608738012F,
  154535. 0.9613828546F, 0.9618873361F, 0.9623872646F, 0.9628826591F,
  154536. 0.9633735388F, 0.9638599227F, 0.9643418303F, 0.9648192808F,
  154537. 0.9652922939F, 0.9657608890F, 0.9662250860F, 0.9666849046F,
  154538. 0.9671403646F, 0.9675914861F, 0.9680382891F, 0.9684807937F,
  154539. 0.9689190202F, 0.9693529890F, 0.9697827203F, 0.9702082347F,
  154540. 0.9706295529F, 0.9710466953F, 0.9714596828F, 0.9718685362F,
  154541. 0.9722732762F, 0.9726739240F, 0.9730705005F, 0.9734630267F,
  154542. 0.9738515239F, 0.9742360134F, 0.9746165163F, 0.9749930540F,
  154543. 0.9753656481F, 0.9757343198F, 0.9760990909F, 0.9764599829F,
  154544. 0.9768170175F, 0.9771702164F, 0.9775196013F, 0.9778651941F,
  154545. 0.9782070167F, 0.9785450909F, 0.9788794388F, 0.9792100824F,
  154546. 0.9795370437F, 0.9798603449F, 0.9801800080F, 0.9804960554F,
  154547. 0.9808085092F, 0.9811173916F, 0.9814227251F, 0.9817245318F,
  154548. 0.9820228343F, 0.9823176549F, 0.9826090160F, 0.9828969402F,
  154549. 0.9831814498F, 0.9834625674F, 0.9837403156F, 0.9840147169F,
  154550. 0.9842857939F, 0.9845535692F, 0.9848180654F, 0.9850793052F,
  154551. 0.9853373113F, 0.9855921062F, 0.9858437127F, 0.9860921535F,
  154552. 0.9863374512F, 0.9865796287F, 0.9868187085F, 0.9870547136F,
  154553. 0.9872876664F, 0.9875175899F, 0.9877445067F, 0.9879684396F,
  154554. 0.9881894112F, 0.9884074444F, 0.9886225619F, 0.9888347863F,
  154555. 0.9890441404F, 0.9892506468F, 0.9894543284F, 0.9896552077F,
  154556. 0.9898533074F, 0.9900486502F, 0.9902412587F, 0.9904311555F,
  154557. 0.9906183633F, 0.9908029045F, 0.9909848019F, 0.9911640779F,
  154558. 0.9913407550F, 0.9915148557F, 0.9916864025F, 0.9918554179F,
  154559. 0.9920219241F, 0.9921859437F, 0.9923474989F, 0.9925066120F,
  154560. 0.9926633054F, 0.9928176012F, 0.9929695218F, 0.9931190891F,
  154561. 0.9932663254F, 0.9934112527F, 0.9935538932F, 0.9936942686F,
  154562. 0.9938324012F, 0.9939683126F, 0.9941020248F, 0.9942335597F,
  154563. 0.9943629388F, 0.9944901841F, 0.9946153170F, 0.9947383593F,
  154564. 0.9948593325F, 0.9949782579F, 0.9950951572F, 0.9952100516F,
  154565. 0.9953229625F, 0.9954339111F, 0.9955429186F, 0.9956500062F,
  154566. 0.9957551948F, 0.9958585056F, 0.9959599593F, 0.9960595769F,
  154567. 0.9961573792F, 0.9962533869F, 0.9963476206F, 0.9964401009F,
  154568. 0.9965308483F, 0.9966198833F, 0.9967072261F, 0.9967928971F,
  154569. 0.9968769164F, 0.9969593041F, 0.9970400804F, 0.9971192651F,
  154570. 0.9971968781F, 0.9972729391F, 0.9973474680F, 0.9974204842F,
  154571. 0.9974920074F, 0.9975620569F, 0.9976306521F, 0.9976978122F,
  154572. 0.9977635565F, 0.9978279039F, 0.9978908736F, 0.9979524842F,
  154573. 0.9980127547F, 0.9980717037F, 0.9981293499F, 0.9981857116F,
  154574. 0.9982408073F, 0.9982946554F, 0.9983472739F, 0.9983986810F,
  154575. 0.9984488947F, 0.9984979328F, 0.9985458132F, 0.9985925534F,
  154576. 0.9986381711F, 0.9986826838F, 0.9987261086F, 0.9987684630F,
  154577. 0.9988097640F, 0.9988500286F, 0.9988892738F, 0.9989275163F,
  154578. 0.9989647727F, 0.9990010597F, 0.9990363938F, 0.9990707911F,
  154579. 0.9991042679F, 0.9991368404F, 0.9991685244F, 0.9991993358F,
  154580. 0.9992292905F, 0.9992584038F, 0.9992866914F, 0.9993141686F,
  154581. 0.9993408506F, 0.9993667526F, 0.9993918895F, 0.9994162761F,
  154582. 0.9994399273F, 0.9994628576F, 0.9994850815F, 0.9995066133F,
  154583. 0.9995274672F, 0.9995476574F, 0.9995671978F, 0.9995861021F,
  154584. 0.9996043841F, 0.9996220573F, 0.9996391352F, 0.9996556310F,
  154585. 0.9996715579F, 0.9996869288F, 0.9997017568F, 0.9997160543F,
  154586. 0.9997298342F, 0.9997431088F, 0.9997558905F, 0.9997681914F,
  154587. 0.9997800236F, 0.9997913990F, 0.9998023292F, 0.9998128261F,
  154588. 0.9998229009F, 0.9998325650F, 0.9998418296F, 0.9998507058F,
  154589. 0.9998592044F, 0.9998673362F, 0.9998751117F, 0.9998825415F,
  154590. 0.9998896358F, 0.9998964047F, 0.9999028584F, 0.9999090066F,
  154591. 0.9999148590F, 0.9999204253F, 0.9999257148F, 0.9999307368F,
  154592. 0.9999355003F, 0.9999400144F, 0.9999442878F, 0.9999483293F,
  154593. 0.9999521472F, 0.9999557499F, 0.9999591457F, 0.9999623426F,
  154594. 0.9999653483F, 0.9999681708F, 0.9999708175F, 0.9999732959F,
  154595. 0.9999756132F, 0.9999777765F, 0.9999797928F, 0.9999816688F,
  154596. 0.9999834113F, 0.9999850266F, 0.9999865211F, 0.9999879009F,
  154597. 0.9999891721F, 0.9999903405F, 0.9999914118F, 0.9999923914F,
  154598. 0.9999932849F, 0.9999940972F, 0.9999948336F, 0.9999954989F,
  154599. 0.9999960978F, 0.9999966349F, 0.9999971146F, 0.9999975411F,
  154600. 0.9999979185F, 0.9999982507F, 0.9999985414F, 0.9999987944F,
  154601. 0.9999990129F, 0.9999992003F, 0.9999993596F, 0.9999994939F,
  154602. 0.9999996059F, 0.9999996981F, 0.9999997732F, 0.9999998333F,
  154603. 0.9999998805F, 0.9999999170F, 0.9999999444F, 0.9999999643F,
  154604. 0.9999999784F, 0.9999999878F, 0.9999999937F, 0.9999999972F,
  154605. 0.9999999990F, 0.9999999997F, 1.0000000000F, 1.0000000000F,
  154606. };
  154607. static float vwin4096[2048] = {
  154608. 0.0000002310F, 0.0000020791F, 0.0000057754F, 0.0000113197F,
  154609. 0.0000187121F, 0.0000279526F, 0.0000390412F, 0.0000519777F,
  154610. 0.0000667623F, 0.0000833949F, 0.0001018753F, 0.0001222036F,
  154611. 0.0001443798F, 0.0001684037F, 0.0001942754F, 0.0002219947F,
  154612. 0.0002515616F, 0.0002829761F, 0.0003162380F, 0.0003513472F,
  154613. 0.0003883038F, 0.0004271076F, 0.0004677584F, 0.0005102563F,
  154614. 0.0005546011F, 0.0006007928F, 0.0006488311F, 0.0006987160F,
  154615. 0.0007504474F, 0.0008040251F, 0.0008594490F, 0.0009167191F,
  154616. 0.0009758351F, 0.0010367969F, 0.0010996044F, 0.0011642574F,
  154617. 0.0012307558F, 0.0012990994F, 0.0013692880F, 0.0014413216F,
  154618. 0.0015151998F, 0.0015909226F, 0.0016684898F, 0.0017479011F,
  154619. 0.0018291565F, 0.0019122556F, 0.0019971983F, 0.0020839845F,
  154620. 0.0021726138F, 0.0022630861F, 0.0023554012F, 0.0024495588F,
  154621. 0.0025455588F, 0.0026434008F, 0.0027430847F, 0.0028446103F,
  154622. 0.0029479772F, 0.0030531853F, 0.0031602342F, 0.0032691238F,
  154623. 0.0033798538F, 0.0034924239F, 0.0036068338F, 0.0037230833F,
  154624. 0.0038411721F, 0.0039610999F, 0.0040828664F, 0.0042064714F,
  154625. 0.0043319145F, 0.0044591954F, 0.0045883139F, 0.0047192696F,
  154626. 0.0048520622F, 0.0049866914F, 0.0051231569F, 0.0052614583F,
  154627. 0.0054015953F, 0.0055435676F, 0.0056873748F, 0.0058330166F,
  154628. 0.0059804926F, 0.0061298026F, 0.0062809460F, 0.0064339226F,
  154629. 0.0065887320F, 0.0067453738F, 0.0069038476F, 0.0070641531F,
  154630. 0.0072262899F, 0.0073902575F, 0.0075560556F, 0.0077236838F,
  154631. 0.0078931417F, 0.0080644288F, 0.0082375447F, 0.0084124891F,
  154632. 0.0085892615F, 0.0087678614F, 0.0089482885F, 0.0091305422F,
  154633. 0.0093146223F, 0.0095005281F, 0.0096882592F, 0.0098778153F,
  154634. 0.0100691958F, 0.0102624002F, 0.0104574281F, 0.0106542791F,
  154635. 0.0108529525F, 0.0110534480F, 0.0112557651F, 0.0114599032F,
  154636. 0.0116658618F, 0.0118736405F, 0.0120832387F, 0.0122946560F,
  154637. 0.0125078917F, 0.0127229454F, 0.0129398166F, 0.0131585046F,
  154638. 0.0133790090F, 0.0136013292F, 0.0138254647F, 0.0140514149F,
  154639. 0.0142791792F, 0.0145087572F, 0.0147401481F, 0.0149733515F,
  154640. 0.0152083667F, 0.0154451932F, 0.0156838304F, 0.0159242777F,
  154641. 0.0161665345F, 0.0164106001F, 0.0166564741F, 0.0169041557F,
  154642. 0.0171536443F, 0.0174049393F, 0.0176580401F, 0.0179129461F,
  154643. 0.0181696565F, 0.0184281708F, 0.0186884883F, 0.0189506084F,
  154644. 0.0192145303F, 0.0194802535F, 0.0197477772F, 0.0200171008F,
  154645. 0.0202882236F, 0.0205611449F, 0.0208358639F, 0.0211123801F,
  154646. 0.0213906927F, 0.0216708011F, 0.0219527043F, 0.0222364019F,
  154647. 0.0225218930F, 0.0228091769F, 0.0230982529F, 0.0233891203F,
  154648. 0.0236817782F, 0.0239762259F, 0.0242724628F, 0.0245704880F,
  154649. 0.0248703007F, 0.0251719002F, 0.0254752858F, 0.0257804565F,
  154650. 0.0260874117F, 0.0263961506F, 0.0267066722F, 0.0270189760F,
  154651. 0.0273330609F, 0.0276489263F, 0.0279665712F, 0.0282859949F,
  154652. 0.0286071966F, 0.0289301753F, 0.0292549303F, 0.0295814607F,
  154653. 0.0299097656F, 0.0302398442F, 0.0305716957F, 0.0309053191F,
  154654. 0.0312407135F, 0.0315778782F, 0.0319168122F, 0.0322575145F,
  154655. 0.0325999844F, 0.0329442209F, 0.0332902231F, 0.0336379900F,
  154656. 0.0339875208F, 0.0343388146F, 0.0346918703F, 0.0350466871F,
  154657. 0.0354032640F, 0.0357616000F, 0.0361216943F, 0.0364835458F,
  154658. 0.0368471535F, 0.0372125166F, 0.0375796339F, 0.0379485046F,
  154659. 0.0383191276F, 0.0386915020F, 0.0390656267F, 0.0394415008F,
  154660. 0.0398191231F, 0.0401984927F, 0.0405796086F, 0.0409624698F,
  154661. 0.0413470751F, 0.0417334235F, 0.0421215141F, 0.0425113457F,
  154662. 0.0429029172F, 0.0432962277F, 0.0436912760F, 0.0440880610F,
  154663. 0.0444865817F, 0.0448868370F, 0.0452888257F, 0.0456925468F,
  154664. 0.0460979992F, 0.0465051816F, 0.0469140931F, 0.0473247325F,
  154665. 0.0477370986F, 0.0481511902F, 0.0485670064F, 0.0489845458F,
  154666. 0.0494038074F, 0.0498247899F, 0.0502474922F, 0.0506719131F,
  154667. 0.0510980514F, 0.0515259060F, 0.0519554756F, 0.0523867590F,
  154668. 0.0528197550F, 0.0532544624F, 0.0536908800F, 0.0541290066F,
  154669. 0.0545688408F, 0.0550103815F, 0.0554536274F, 0.0558985772F,
  154670. 0.0563452297F, 0.0567935837F, 0.0572436377F, 0.0576953907F,
  154671. 0.0581488412F, 0.0586039880F, 0.0590608297F, 0.0595193651F,
  154672. 0.0599795929F, 0.0604415117F, 0.0609051202F, 0.0613704170F,
  154673. 0.0618374009F, 0.0623060704F, 0.0627764243F, 0.0632484611F,
  154674. 0.0637221795F, 0.0641975781F, 0.0646746555F, 0.0651534104F,
  154675. 0.0656338413F, 0.0661159469F, 0.0665997257F, 0.0670851763F,
  154676. 0.0675722973F, 0.0680610873F, 0.0685515448F, 0.0690436684F,
  154677. 0.0695374567F, 0.0700329081F, 0.0705300213F, 0.0710287947F,
  154678. 0.0715292269F, 0.0720313163F, 0.0725350616F, 0.0730404612F,
  154679. 0.0735475136F, 0.0740562172F, 0.0745665707F, 0.0750785723F,
  154680. 0.0755922207F, 0.0761075143F, 0.0766244515F, 0.0771430307F,
  154681. 0.0776632505F, 0.0781851092F, 0.0787086052F, 0.0792337371F,
  154682. 0.0797605032F, 0.0802889018F, 0.0808189315F, 0.0813505905F,
  154683. 0.0818838773F, 0.0824187903F, 0.0829553277F, 0.0834934881F,
  154684. 0.0840332697F, 0.0845746708F, 0.0851176899F, 0.0856623252F,
  154685. 0.0862085751F, 0.0867564379F, 0.0873059119F, 0.0878569954F,
  154686. 0.0884096867F, 0.0889639840F, 0.0895198858F, 0.0900773902F,
  154687. 0.0906364955F, 0.0911972000F, 0.0917595019F, 0.0923233995F,
  154688. 0.0928888909F, 0.0934559745F, 0.0940246485F, 0.0945949110F,
  154689. 0.0951667604F, 0.0957401946F, 0.0963152121F, 0.0968918109F,
  154690. 0.0974699893F, 0.0980497454F, 0.0986310773F, 0.0992139832F,
  154691. 0.0997984614F, 0.1003845098F, 0.1009721267F, 0.1015613101F,
  154692. 0.1021520582F, 0.1027443692F, 0.1033382410F, 0.1039336718F,
  154693. 0.1045306597F, 0.1051292027F, 0.1057292990F, 0.1063309466F,
  154694. 0.1069341435F, 0.1075388878F, 0.1081451776F, 0.1087530108F,
  154695. 0.1093623856F, 0.1099732998F, 0.1105857516F, 0.1111997389F,
  154696. 0.1118152597F, 0.1124323121F, 0.1130508939F, 0.1136710032F,
  154697. 0.1142926379F, 0.1149157960F, 0.1155404755F, 0.1161666742F,
  154698. 0.1167943901F, 0.1174236211F, 0.1180543652F, 0.1186866202F,
  154699. 0.1193203841F, 0.1199556548F, 0.1205924300F, 0.1212307078F,
  154700. 0.1218704860F, 0.1225117624F, 0.1231545349F, 0.1237988013F,
  154701. 0.1244445596F, 0.1250918074F, 0.1257405427F, 0.1263907632F,
  154702. 0.1270424667F, 0.1276956512F, 0.1283503142F, 0.1290064537F,
  154703. 0.1296640674F, 0.1303231530F, 0.1309837084F, 0.1316457312F,
  154704. 0.1323092193F, 0.1329741703F, 0.1336405820F, 0.1343084520F,
  154705. 0.1349777782F, 0.1356485582F, 0.1363207897F, 0.1369944704F,
  154706. 0.1376695979F, 0.1383461700F, 0.1390241842F, 0.1397036384F,
  154707. 0.1403845300F, 0.1410668567F, 0.1417506162F, 0.1424358061F,
  154708. 0.1431224240F, 0.1438104674F, 0.1444999341F, 0.1451908216F,
  154709. 0.1458831274F, 0.1465768492F, 0.1472719844F, 0.1479685308F,
  154710. 0.1486664857F, 0.1493658468F, 0.1500666115F, 0.1507687775F,
  154711. 0.1514723422F, 0.1521773031F, 0.1528836577F, 0.1535914035F,
  154712. 0.1543005380F, 0.1550110587F, 0.1557229631F, 0.1564362485F,
  154713. 0.1571509124F, 0.1578669524F, 0.1585843657F, 0.1593031499F,
  154714. 0.1600233024F, 0.1607448205F, 0.1614677017F, 0.1621919433F,
  154715. 0.1629175428F, 0.1636444975F, 0.1643728047F, 0.1651024619F,
  154716. 0.1658334665F, 0.1665658156F, 0.1672995067F, 0.1680345371F,
  154717. 0.1687709041F, 0.1695086050F, 0.1702476372F, 0.1709879978F,
  154718. 0.1717296843F, 0.1724726938F, 0.1732170237F, 0.1739626711F,
  154719. 0.1747096335F, 0.1754579079F, 0.1762074916F, 0.1769583819F,
  154720. 0.1777105760F, 0.1784640710F, 0.1792188642F, 0.1799749529F,
  154721. 0.1807323340F, 0.1814910049F, 0.1822509628F, 0.1830122046F,
  154722. 0.1837747277F, 0.1845385292F, 0.1853036062F, 0.1860699558F,
  154723. 0.1868375751F, 0.1876064613F, 0.1883766114F, 0.1891480226F,
  154724. 0.1899206919F, 0.1906946164F, 0.1914697932F, 0.1922462194F,
  154725. 0.1930238919F, 0.1938028079F, 0.1945829643F, 0.1953643583F,
  154726. 0.1961469868F, 0.1969308468F, 0.1977159353F, 0.1985022494F,
  154727. 0.1992897859F, 0.2000785420F, 0.2008685145F, 0.2016597005F,
  154728. 0.2024520968F, 0.2032457005F, 0.2040405084F, 0.2048365175F,
  154729. 0.2056337247F, 0.2064321269F, 0.2072317211F, 0.2080325041F,
  154730. 0.2088344727F, 0.2096376240F, 0.2104419547F, 0.2112474618F,
  154731. 0.2120541420F, 0.2128619923F, 0.2136710094F, 0.2144811902F,
  154732. 0.2152925315F, 0.2161050301F, 0.2169186829F, 0.2177334866F,
  154733. 0.2185494381F, 0.2193665340F, 0.2201847712F, 0.2210041465F,
  154734. 0.2218246565F, 0.2226462981F, 0.2234690680F, 0.2242929629F,
  154735. 0.2251179796F, 0.2259441147F, 0.2267713650F, 0.2275997272F,
  154736. 0.2284291979F, 0.2292597739F, 0.2300914518F, 0.2309242283F,
  154737. 0.2317581001F, 0.2325930638F, 0.2334291160F, 0.2342662534F,
  154738. 0.2351044727F, 0.2359437703F, 0.2367841431F, 0.2376255875F,
  154739. 0.2384681001F, 0.2393116776F, 0.2401563165F, 0.2410020134F,
  154740. 0.2418487649F, 0.2426965675F, 0.2435454178F, 0.2443953122F,
  154741. 0.2452462474F, 0.2460982199F, 0.2469512262F, 0.2478052628F,
  154742. 0.2486603262F, 0.2495164129F, 0.2503735194F, 0.2512316421F,
  154743. 0.2520907776F, 0.2529509222F, 0.2538120726F, 0.2546742250F,
  154744. 0.2555373760F, 0.2564015219F, 0.2572666593F, 0.2581327845F,
  154745. 0.2589998939F, 0.2598679840F, 0.2607370510F, 0.2616070916F,
  154746. 0.2624781019F, 0.2633500783F, 0.2642230173F, 0.2650969152F,
  154747. 0.2659717684F, 0.2668475731F, 0.2677243257F, 0.2686020226F,
  154748. 0.2694806601F, 0.2703602344F, 0.2712407419F, 0.2721221789F,
  154749. 0.2730045417F, 0.2738878265F, 0.2747720297F, 0.2756571474F,
  154750. 0.2765431760F, 0.2774301117F, 0.2783179508F, 0.2792066895F,
  154751. 0.2800963240F, 0.2809868505F, 0.2818782654F, 0.2827705647F,
  154752. 0.2836637447F, 0.2845578016F, 0.2854527315F, 0.2863485307F,
  154753. 0.2872451953F, 0.2881427215F, 0.2890411055F, 0.2899403433F,
  154754. 0.2908404312F, 0.2917413654F, 0.2926431418F, 0.2935457567F,
  154755. 0.2944492061F, 0.2953534863F, 0.2962585932F, 0.2971645230F,
  154756. 0.2980712717F, 0.2989788356F, 0.2998872105F, 0.3007963927F,
  154757. 0.3017063781F, 0.3026171629F, 0.3035287430F, 0.3044411145F,
  154758. 0.3053542736F, 0.3062682161F, 0.3071829381F, 0.3080984356F,
  154759. 0.3090147047F, 0.3099317413F, 0.3108495414F, 0.3117681011F,
  154760. 0.3126874163F, 0.3136074830F, 0.3145282972F, 0.3154498548F,
  154761. 0.3163721517F, 0.3172951841F, 0.3182189477F, 0.3191434385F,
  154762. 0.3200686525F, 0.3209945856F, 0.3219212336F, 0.3228485927F,
  154763. 0.3237766585F, 0.3247054271F, 0.3256348943F, 0.3265650560F,
  154764. 0.3274959081F, 0.3284274465F, 0.3293596671F, 0.3302925657F,
  154765. 0.3312261382F, 0.3321603804F, 0.3330952882F, 0.3340308574F,
  154766. 0.3349670838F, 0.3359039634F, 0.3368414919F, 0.3377796651F,
  154767. 0.3387184789F, 0.3396579290F, 0.3405980113F, 0.3415387216F,
  154768. 0.3424800556F, 0.3434220091F, 0.3443645779F, 0.3453077578F,
  154769. 0.3462515446F, 0.3471959340F, 0.3481409217F, 0.3490865036F,
  154770. 0.3500326754F, 0.3509794328F, 0.3519267715F, 0.3528746873F,
  154771. 0.3538231759F, 0.3547722330F, 0.3557218544F, 0.3566720357F,
  154772. 0.3576227727F, 0.3585740610F, 0.3595258964F, 0.3604782745F,
  154773. 0.3614311910F, 0.3623846417F, 0.3633386221F, 0.3642931280F,
  154774. 0.3652481549F, 0.3662036987F, 0.3671597548F, 0.3681163191F,
  154775. 0.3690733870F, 0.3700309544F, 0.3709890167F, 0.3719475696F,
  154776. 0.3729066089F, 0.3738661299F, 0.3748261285F, 0.3757866002F,
  154777. 0.3767475406F, 0.3777089453F, 0.3786708100F, 0.3796331302F,
  154778. 0.3805959014F, 0.3815591194F, 0.3825227796F, 0.3834868777F,
  154779. 0.3844514093F, 0.3854163698F, 0.3863817549F, 0.3873475601F,
  154780. 0.3883137810F, 0.3892804131F, 0.3902474521F, 0.3912148933F,
  154781. 0.3921827325F, 0.3931509650F, 0.3941195865F, 0.3950885925F,
  154782. 0.3960579785F, 0.3970277400F, 0.3979978725F, 0.3989683716F,
  154783. 0.3999392328F, 0.4009104516F, 0.4018820234F, 0.4028539438F,
  154784. 0.4038262084F, 0.4047988125F, 0.4057717516F, 0.4067450214F,
  154785. 0.4077186172F, 0.4086925345F, 0.4096667688F, 0.4106413155F,
  154786. 0.4116161703F, 0.4125913284F, 0.4135667854F, 0.4145425368F,
  154787. 0.4155185780F, 0.4164949044F, 0.4174715116F, 0.4184483949F,
  154788. 0.4194255498F, 0.4204029718F, 0.4213806563F, 0.4223585987F,
  154789. 0.4233367946F, 0.4243152392F, 0.4252939281F, 0.4262728566F,
  154790. 0.4272520202F, 0.4282314144F, 0.4292110345F, 0.4301908760F,
  154791. 0.4311709343F, 0.4321512047F, 0.4331316828F, 0.4341123639F,
  154792. 0.4350932435F, 0.4360743168F, 0.4370555794F, 0.4380370267F,
  154793. 0.4390186540F, 0.4400004567F, 0.4409824303F, 0.4419645701F,
  154794. 0.4429468716F, 0.4439293300F, 0.4449119409F, 0.4458946996F,
  154795. 0.4468776014F, 0.4478606418F, 0.4488438162F, 0.4498271199F,
  154796. 0.4508105483F, 0.4517940967F, 0.4527777607F, 0.4537615355F,
  154797. 0.4547454165F, 0.4557293991F, 0.4567134786F, 0.4576976505F,
  154798. 0.4586819101F, 0.4596662527F, 0.4606506738F, 0.4616351687F,
  154799. 0.4626197328F, 0.4636043614F, 0.4645890499F, 0.4655737936F,
  154800. 0.4665585880F, 0.4675434284F, 0.4685283101F, 0.4695132286F,
  154801. 0.4704981791F, 0.4714831570F, 0.4724681577F, 0.4734531766F,
  154802. 0.4744382089F, 0.4754232501F, 0.4764082956F, 0.4773933406F,
  154803. 0.4783783806F, 0.4793634108F, 0.4803484267F, 0.4813334237F,
  154804. 0.4823183969F, 0.4833033419F, 0.4842882540F, 0.4852731285F,
  154805. 0.4862579608F, 0.4872427462F, 0.4882274802F, 0.4892121580F,
  154806. 0.4901967751F, 0.4911813267F, 0.4921658083F, 0.4931502151F,
  154807. 0.4941345427F, 0.4951187863F, 0.4961029412F, 0.4970870029F,
  154808. 0.4980709667F, 0.4990548280F, 0.5000385822F, 0.5010222245F,
  154809. 0.5020057505F, 0.5029891553F, 0.5039724345F, 0.5049555834F,
  154810. 0.5059385973F, 0.5069214716F, 0.5079042018F, 0.5088867831F,
  154811. 0.5098692110F, 0.5108514808F, 0.5118335879F, 0.5128155277F,
  154812. 0.5137972956F, 0.5147788869F, 0.5157602971F, 0.5167415215F,
  154813. 0.5177225555F, 0.5187033945F, 0.5196840339F, 0.5206644692F,
  154814. 0.5216446956F, 0.5226247086F, 0.5236045035F, 0.5245840759F,
  154815. 0.5255634211F, 0.5265425344F, 0.5275214114F, 0.5285000474F,
  154816. 0.5294784378F, 0.5304565781F, 0.5314344637F, 0.5324120899F,
  154817. 0.5333894522F, 0.5343665461F, 0.5353433670F, 0.5363199102F,
  154818. 0.5372961713F, 0.5382721457F, 0.5392478287F, 0.5402232159F,
  154819. 0.5411983027F, 0.5421730845F, 0.5431475569F, 0.5441217151F,
  154820. 0.5450955548F, 0.5460690714F, 0.5470422602F, 0.5480151169F,
  154821. 0.5489876368F, 0.5499598155F, 0.5509316484F, 0.5519031310F,
  154822. 0.5528742587F, 0.5538450271F, 0.5548154317F, 0.5557854680F,
  154823. 0.5567551314F, 0.5577244174F, 0.5586933216F, 0.5596618395F,
  154824. 0.5606299665F, 0.5615976983F, 0.5625650302F, 0.5635319580F,
  154825. 0.5644984770F, 0.5654645828F, 0.5664302709F, 0.5673955370F,
  154826. 0.5683603765F, 0.5693247850F, 0.5702887580F, 0.5712522912F,
  154827. 0.5722153800F, 0.5731780200F, 0.5741402069F, 0.5751019362F,
  154828. 0.5760632034F, 0.5770240042F, 0.5779843341F, 0.5789441889F,
  154829. 0.5799035639F, 0.5808624549F, 0.5818208575F, 0.5827787673F,
  154830. 0.5837361800F, 0.5846930910F, 0.5856494961F, 0.5866053910F,
  154831. 0.5875607712F, 0.5885156324F, 0.5894699703F, 0.5904237804F,
  154832. 0.5913770586F, 0.5923298004F, 0.5932820016F, 0.5942336578F,
  154833. 0.5951847646F, 0.5961353179F, 0.5970853132F, 0.5980347464F,
  154834. 0.5989836131F, 0.5999319090F, 0.6008796298F, 0.6018267713F,
  154835. 0.6027733292F, 0.6037192993F, 0.6046646773F, 0.6056094589F,
  154836. 0.6065536400F, 0.6074972162F, 0.6084401833F, 0.6093825372F,
  154837. 0.6103242736F, 0.6112653884F, 0.6122058772F, 0.6131457359F,
  154838. 0.6140849604F, 0.6150235464F, 0.6159614897F, 0.6168987862F,
  154839. 0.6178354318F, 0.6187714223F, 0.6197067535F, 0.6206414213F,
  154840. 0.6215754215F, 0.6225087501F, 0.6234414028F, 0.6243733757F,
  154841. 0.6253046646F, 0.6262352654F, 0.6271651739F, 0.6280943862F,
  154842. 0.6290228982F, 0.6299507057F, 0.6308778048F, 0.6318041913F,
  154843. 0.6327298612F, 0.6336548105F, 0.6345790352F, 0.6355025312F,
  154844. 0.6364252945F, 0.6373473211F, 0.6382686070F, 0.6391891483F,
  154845. 0.6401089409F, 0.6410279808F, 0.6419462642F, 0.6428637869F,
  154846. 0.6437805452F, 0.6446965350F, 0.6456117524F, 0.6465261935F,
  154847. 0.6474398544F, 0.6483527311F, 0.6492648197F, 0.6501761165F,
  154848. 0.6510866174F, 0.6519963186F, 0.6529052162F, 0.6538133064F,
  154849. 0.6547205854F, 0.6556270492F, 0.6565326941F, 0.6574375162F,
  154850. 0.6583415117F, 0.6592446769F, 0.6601470079F, 0.6610485009F,
  154851. 0.6619491521F, 0.6628489578F, 0.6637479143F, 0.6646460177F,
  154852. 0.6655432643F, 0.6664396505F, 0.6673351724F, 0.6682298264F,
  154853. 0.6691236087F, 0.6700165157F, 0.6709085436F, 0.6717996889F,
  154854. 0.6726899478F, 0.6735793167F, 0.6744677918F, 0.6753553697F,
  154855. 0.6762420466F, 0.6771278190F, 0.6780126832F, 0.6788966357F,
  154856. 0.6797796728F, 0.6806617909F, 0.6815429866F, 0.6824232562F,
  154857. 0.6833025961F, 0.6841810030F, 0.6850584731F, 0.6859350031F,
  154858. 0.6868105894F, 0.6876852284F, 0.6885589168F, 0.6894316510F,
  154859. 0.6903034275F, 0.6911742430F, 0.6920440939F, 0.6929129769F,
  154860. 0.6937808884F, 0.6946478251F, 0.6955137837F, 0.6963787606F,
  154861. 0.6972427525F, 0.6981057560F, 0.6989677678F, 0.6998287845F,
  154862. 0.7006888028F, 0.7015478194F, 0.7024058309F, 0.7032628340F,
  154863. 0.7041188254F, 0.7049738019F, 0.7058277601F, 0.7066806969F,
  154864. 0.7075326089F, 0.7083834929F, 0.7092333457F, 0.7100821640F,
  154865. 0.7109299447F, 0.7117766846F, 0.7126223804F, 0.7134670291F,
  154866. 0.7143106273F, 0.7151531721F, 0.7159946602F, 0.7168350885F,
  154867. 0.7176744539F, 0.7185127534F, 0.7193499837F, 0.7201861418F,
  154868. 0.7210212247F, 0.7218552293F, 0.7226881526F, 0.7235199914F,
  154869. 0.7243507428F, 0.7251804039F, 0.7260089715F, 0.7268364426F,
  154870. 0.7276628144F, 0.7284880839F, 0.7293122481F, 0.7301353040F,
  154871. 0.7309572487F, 0.7317780794F, 0.7325977930F, 0.7334163868F,
  154872. 0.7342338579F, 0.7350502033F, 0.7358654202F, 0.7366795059F,
  154873. 0.7374924573F, 0.7383042718F, 0.7391149465F, 0.7399244787F,
  154874. 0.7407328655F, 0.7415401041F, 0.7423461920F, 0.7431511261F,
  154875. 0.7439549040F, 0.7447575227F, 0.7455589797F, 0.7463592723F,
  154876. 0.7471583976F, 0.7479563532F, 0.7487531363F, 0.7495487443F,
  154877. 0.7503431745F, 0.7511364244F, 0.7519284913F, 0.7527193726F,
  154878. 0.7535090658F, 0.7542975683F, 0.7550848776F, 0.7558709910F,
  154879. 0.7566559062F, 0.7574396205F, 0.7582221314F, 0.7590034366F,
  154880. 0.7597835334F, 0.7605624194F, 0.7613400923F, 0.7621165495F,
  154881. 0.7628917886F, 0.7636658072F, 0.7644386030F, 0.7652101735F,
  154882. 0.7659805164F, 0.7667496292F, 0.7675175098F, 0.7682841556F,
  154883. 0.7690495645F, 0.7698137341F, 0.7705766622F, 0.7713383463F,
  154884. 0.7720987844F, 0.7728579741F, 0.7736159132F, 0.7743725994F,
  154885. 0.7751280306F, 0.7758822046F, 0.7766351192F, 0.7773867722F,
  154886. 0.7781371614F, 0.7788862848F, 0.7796341401F, 0.7803807253F,
  154887. 0.7811260383F, 0.7818700769F, 0.7826128392F, 0.7833543230F,
  154888. 0.7840945263F, 0.7848334471F, 0.7855710833F, 0.7863074330F,
  154889. 0.7870424941F, 0.7877762647F, 0.7885087428F, 0.7892399264F,
  154890. 0.7899698137F, 0.7906984026F, 0.7914256914F, 0.7921516780F,
  154891. 0.7928763607F, 0.7935997375F, 0.7943218065F, 0.7950425661F,
  154892. 0.7957620142F, 0.7964801492F, 0.7971969692F, 0.7979124724F,
  154893. 0.7986266570F, 0.7993395214F, 0.8000510638F, 0.8007612823F,
  154894. 0.8014701754F, 0.8021777413F, 0.8028839784F, 0.8035888849F,
  154895. 0.8042924592F, 0.8049946997F, 0.8056956048F, 0.8063951727F,
  154896. 0.8070934020F, 0.8077902910F, 0.8084858381F, 0.8091800419F,
  154897. 0.8098729007F, 0.8105644130F, 0.8112545774F, 0.8119433922F,
  154898. 0.8126308561F, 0.8133169676F, 0.8140017251F, 0.8146851272F,
  154899. 0.8153671726F, 0.8160478598F, 0.8167271874F, 0.8174051539F,
  154900. 0.8180817582F, 0.8187569986F, 0.8194308741F, 0.8201033831F,
  154901. 0.8207745244F, 0.8214442966F, 0.8221126986F, 0.8227797290F,
  154902. 0.8234453865F, 0.8241096700F, 0.8247725781F, 0.8254341097F,
  154903. 0.8260942636F, 0.8267530385F, 0.8274104334F, 0.8280664470F,
  154904. 0.8287210782F, 0.8293743259F, 0.8300261889F, 0.8306766662F,
  154905. 0.8313257566F, 0.8319734591F, 0.8326197727F, 0.8332646963F,
  154906. 0.8339082288F, 0.8345503692F, 0.8351911167F, 0.8358304700F,
  154907. 0.8364684284F, 0.8371049907F, 0.8377401562F, 0.8383739238F,
  154908. 0.8390062927F, 0.8396372618F, 0.8402668305F, 0.8408949977F,
  154909. 0.8415217626F, 0.8421471245F, 0.8427710823F, 0.8433936354F,
  154910. 0.8440147830F, 0.8446345242F, 0.8452528582F, 0.8458697844F,
  154911. 0.8464853020F, 0.8470994102F, 0.8477121084F, 0.8483233958F,
  154912. 0.8489332718F, 0.8495417356F, 0.8501487866F, 0.8507544243F,
  154913. 0.8513586479F, 0.8519614568F, 0.8525628505F, 0.8531628283F,
  154914. 0.8537613897F, 0.8543585341F, 0.8549542611F, 0.8555485699F,
  154915. 0.8561414603F, 0.8567329315F, 0.8573229832F, 0.8579116149F,
  154916. 0.8584988262F, 0.8590846165F, 0.8596689855F, 0.8602519327F,
  154917. 0.8608334577F, 0.8614135603F, 0.8619922399F, 0.8625694962F,
  154918. 0.8631453289F, 0.8637197377F, 0.8642927222F, 0.8648642821F,
  154919. 0.8654344172F, 0.8660031272F, 0.8665704118F, 0.8671362708F,
  154920. 0.8677007039F, 0.8682637109F, 0.8688252917F, 0.8693854460F,
  154921. 0.8699441737F, 0.8705014745F, 0.8710573485F, 0.8716117953F,
  154922. 0.8721648150F, 0.8727164073F, 0.8732665723F, 0.8738153098F,
  154923. 0.8743626197F, 0.8749085021F, 0.8754529569F, 0.8759959840F,
  154924. 0.8765375835F, 0.8770777553F, 0.8776164996F, 0.8781538162F,
  154925. 0.8786897054F, 0.8792241670F, 0.8797572013F, 0.8802888082F,
  154926. 0.8808189880F, 0.8813477407F, 0.8818750664F, 0.8824009653F,
  154927. 0.8829254375F, 0.8834484833F, 0.8839701028F, 0.8844902961F,
  154928. 0.8850090636F, 0.8855264054F, 0.8860423218F, 0.8865568131F,
  154929. 0.8870698794F, 0.8875815212F, 0.8880917386F, 0.8886005319F,
  154930. 0.8891079016F, 0.8896138479F, 0.8901183712F, 0.8906214719F,
  154931. 0.8911231503F, 0.8916234067F, 0.8921222417F, 0.8926196556F,
  154932. 0.8931156489F, 0.8936102219F, 0.8941033752F, 0.8945951092F,
  154933. 0.8950854244F, 0.8955743212F, 0.8960618003F, 0.8965478621F,
  154934. 0.8970325071F, 0.8975157359F, 0.8979975490F, 0.8984779471F,
  154935. 0.8989569307F, 0.8994345004F, 0.8999106568F, 0.9003854005F,
  154936. 0.9008587323F, 0.9013306526F, 0.9018011623F, 0.9022702619F,
  154937. 0.9027379521F, 0.9032042337F, 0.9036691074F, 0.9041325739F,
  154938. 0.9045946339F, 0.9050552882F, 0.9055145376F, 0.9059723828F,
  154939. 0.9064288246F, 0.9068838638F, 0.9073375013F, 0.9077897379F,
  154940. 0.9082405743F, 0.9086900115F, 0.9091380503F, 0.9095846917F,
  154941. 0.9100299364F, 0.9104737854F, 0.9109162397F, 0.9113573001F,
  154942. 0.9117969675F, 0.9122352430F, 0.9126721275F, 0.9131076219F,
  154943. 0.9135417273F, 0.9139744447F, 0.9144057750F, 0.9148357194F,
  154944. 0.9152642787F, 0.9156914542F, 0.9161172468F, 0.9165416576F,
  154945. 0.9169646877F, 0.9173863382F, 0.9178066102F, 0.9182255048F,
  154946. 0.9186430232F, 0.9190591665F, 0.9194739359F, 0.9198873324F,
  154947. 0.9202993574F, 0.9207100120F, 0.9211192973F, 0.9215272147F,
  154948. 0.9219337653F, 0.9223389504F, 0.9227427713F, 0.9231452290F,
  154949. 0.9235463251F, 0.9239460607F, 0.9243444371F, 0.9247414557F,
  154950. 0.9251371177F, 0.9255314245F, 0.9259243774F, 0.9263159778F,
  154951. 0.9267062270F, 0.9270951264F, 0.9274826774F, 0.9278688814F,
  154952. 0.9282537398F, 0.9286372540F, 0.9290194254F, 0.9294002555F,
  154953. 0.9297797458F, 0.9301578976F, 0.9305347125F, 0.9309101919F,
  154954. 0.9312843373F, 0.9316571503F, 0.9320286323F, 0.9323987849F,
  154955. 0.9327676097F, 0.9331351080F, 0.9335012816F, 0.9338661320F,
  154956. 0.9342296607F, 0.9345918694F, 0.9349527596F, 0.9353123330F,
  154957. 0.9356705911F, 0.9360275357F, 0.9363831683F, 0.9367374905F,
  154958. 0.9370905042F, 0.9374422108F, 0.9377926122F, 0.9381417099F,
  154959. 0.9384895057F, 0.9388360014F, 0.9391811985F, 0.9395250989F,
  154960. 0.9398677043F, 0.9402090165F, 0.9405490371F, 0.9408877680F,
  154961. 0.9412252110F, 0.9415613678F, 0.9418962402F, 0.9422298301F,
  154962. 0.9425621392F, 0.9428931695F, 0.9432229226F, 0.9435514005F,
  154963. 0.9438786050F, 0.9442045381F, 0.9445292014F, 0.9448525971F,
  154964. 0.9451747268F, 0.9454955926F, 0.9458151963F, 0.9461335399F,
  154965. 0.9464506253F, 0.9467664545F, 0.9470810293F, 0.9473943517F,
  154966. 0.9477064238F, 0.9480172474F, 0.9483268246F, 0.9486351573F,
  154967. 0.9489422475F, 0.9492480973F, 0.9495527087F, 0.9498560837F,
  154968. 0.9501582243F, 0.9504591325F, 0.9507588105F, 0.9510572603F,
  154969. 0.9513544839F, 0.9516504834F, 0.9519452609F, 0.9522388186F,
  154970. 0.9525311584F, 0.9528222826F, 0.9531121932F, 0.9534008923F,
  154971. 0.9536883821F, 0.9539746647F, 0.9542597424F, 0.9545436171F,
  154972. 0.9548262912F, 0.9551077667F, 0.9553880459F, 0.9556671309F,
  154973. 0.9559450239F, 0.9562217272F, 0.9564972429F, 0.9567715733F,
  154974. 0.9570447206F, 0.9573166871F, 0.9575874749F, 0.9578570863F,
  154975. 0.9581255236F, 0.9583927890F, 0.9586588849F, 0.9589238134F,
  154976. 0.9591875769F, 0.9594501777F, 0.9597116180F, 0.9599719003F,
  154977. 0.9602310267F, 0.9604889995F, 0.9607458213F, 0.9610014942F,
  154978. 0.9612560206F, 0.9615094028F, 0.9617616433F, 0.9620127443F,
  154979. 0.9622627083F, 0.9625115376F, 0.9627592345F, 0.9630058016F,
  154980. 0.9632512411F, 0.9634955555F, 0.9637387471F, 0.9639808185F,
  154981. 0.9642217720F, 0.9644616100F, 0.9647003349F, 0.9649379493F,
  154982. 0.9651744556F, 0.9654098561F, 0.9656441534F, 0.9658773499F,
  154983. 0.9661094480F, 0.9663404504F, 0.9665703593F, 0.9667991774F,
  154984. 0.9670269071F, 0.9672535509F, 0.9674791114F, 0.9677035909F,
  154985. 0.9679269921F, 0.9681493174F, 0.9683705694F, 0.9685907506F,
  154986. 0.9688098636F, 0.9690279108F, 0.9692448948F, 0.9694608182F,
  154987. 0.9696756836F, 0.9698894934F, 0.9701022503F, 0.9703139569F,
  154988. 0.9705246156F, 0.9707342291F, 0.9709428000F, 0.9711503309F,
  154989. 0.9713568243F, 0.9715622829F, 0.9717667093F, 0.9719701060F,
  154990. 0.9721724757F, 0.9723738210F, 0.9725741446F, 0.9727734490F,
  154991. 0.9729717369F, 0.9731690109F, 0.9733652737F, 0.9735605279F,
  154992. 0.9737547762F, 0.9739480212F, 0.9741402656F, 0.9743315120F,
  154993. 0.9745217631F, 0.9747110216F, 0.9748992901F, 0.9750865714F,
  154994. 0.9752728681F, 0.9754581829F, 0.9756425184F, 0.9758258775F,
  154995. 0.9760082627F, 0.9761896768F, 0.9763701224F, 0.9765496024F,
  154996. 0.9767281193F, 0.9769056760F, 0.9770822751F, 0.9772579193F,
  154997. 0.9774326114F, 0.9776063542F, 0.9777791502F, 0.9779510023F,
  154998. 0.9781219133F, 0.9782918858F, 0.9784609226F, 0.9786290264F,
  154999. 0.9787962000F, 0.9789624461F, 0.9791277676F, 0.9792921671F,
  155000. 0.9794556474F, 0.9796182113F, 0.9797798615F, 0.9799406009F,
  155001. 0.9801004321F, 0.9802593580F, 0.9804173813F, 0.9805745049F,
  155002. 0.9807307314F, 0.9808860637F, 0.9810405046F, 0.9811940568F,
  155003. 0.9813467232F, 0.9814985065F, 0.9816494095F, 0.9817994351F,
  155004. 0.9819485860F, 0.9820968650F, 0.9822442750F, 0.9823908186F,
  155005. 0.9825364988F, 0.9826813184F, 0.9828252801F, 0.9829683868F,
  155006. 0.9831106413F, 0.9832520463F, 0.9833926048F, 0.9835323195F,
  155007. 0.9836711932F, 0.9838092288F, 0.9839464291F, 0.9840827969F,
  155008. 0.9842183351F, 0.9843530464F, 0.9844869337F, 0.9846199998F,
  155009. 0.9847522475F, 0.9848836798F, 0.9850142993F, 0.9851441090F,
  155010. 0.9852731117F, 0.9854013101F, 0.9855287073F, 0.9856553058F,
  155011. 0.9857811087F, 0.9859061188F, 0.9860303388F, 0.9861537717F,
  155012. 0.9862764202F, 0.9863982872F, 0.9865193756F, 0.9866396882F,
  155013. 0.9867592277F, 0.9868779972F, 0.9869959993F, 0.9871132370F,
  155014. 0.9872297131F, 0.9873454304F, 0.9874603918F, 0.9875746001F,
  155015. 0.9876880581F, 0.9878007688F, 0.9879127348F, 0.9880239592F,
  155016. 0.9881344447F, 0.9882441941F, 0.9883532104F, 0.9884614962F,
  155017. 0.9885690546F, 0.9886758883F, 0.9887820001F, 0.9888873930F,
  155018. 0.9889920697F, 0.9890960331F, 0.9891992859F, 0.9893018312F,
  155019. 0.9894036716F, 0.9895048100F, 0.9896052493F, 0.9897049923F,
  155020. 0.9898040418F, 0.9899024006F, 0.9900000717F, 0.9900970577F,
  155021. 0.9901933616F, 0.9902889862F, 0.9903839343F, 0.9904782087F,
  155022. 0.9905718122F, 0.9906647477F, 0.9907570180F, 0.9908486259F,
  155023. 0.9909395742F, 0.9910298658F, 0.9911195034F, 0.9912084899F,
  155024. 0.9912968281F, 0.9913845208F, 0.9914715708F, 0.9915579810F,
  155025. 0.9916437540F, 0.9917288928F, 0.9918134001F, 0.9918972788F,
  155026. 0.9919805316F, 0.9920631613F, 0.9921451707F, 0.9922265626F,
  155027. 0.9923073399F, 0.9923875052F, 0.9924670615F, 0.9925460114F,
  155028. 0.9926243577F, 0.9927021033F, 0.9927792508F, 0.9928558032F,
  155029. 0.9929317631F, 0.9930071333F, 0.9930819167F, 0.9931561158F,
  155030. 0.9932297337F, 0.9933027728F, 0.9933752362F, 0.9934471264F,
  155031. 0.9935184462F, 0.9935891985F, 0.9936593859F, 0.9937290112F,
  155032. 0.9937980771F, 0.9938665864F, 0.9939345418F, 0.9940019460F,
  155033. 0.9940688018F, 0.9941351118F, 0.9942008789F, 0.9942661057F,
  155034. 0.9943307950F, 0.9943949494F, 0.9944585717F, 0.9945216645F,
  155035. 0.9945842307F, 0.9946462728F, 0.9947077936F, 0.9947687957F,
  155036. 0.9948292820F, 0.9948892550F, 0.9949487174F, 0.9950076719F,
  155037. 0.9950661212F, 0.9951240679F, 0.9951815148F, 0.9952384645F,
  155038. 0.9952949196F, 0.9953508828F, 0.9954063568F, 0.9954613442F,
  155039. 0.9955158476F, 0.9955698697F, 0.9956234132F, 0.9956764806F,
  155040. 0.9957290746F, 0.9957811978F, 0.9958328528F, 0.9958840423F,
  155041. 0.9959347688F, 0.9959850351F, 0.9960348435F, 0.9960841969F,
  155042. 0.9961330977F, 0.9961815486F, 0.9962295521F, 0.9962771108F,
  155043. 0.9963242274F, 0.9963709043F, 0.9964171441F, 0.9964629494F,
  155044. 0.9965083228F, 0.9965532668F, 0.9965977840F, 0.9966418768F,
  155045. 0.9966855479F, 0.9967287998F, 0.9967716350F, 0.9968140559F,
  155046. 0.9968560653F, 0.9968976655F, 0.9969388591F, 0.9969796485F,
  155047. 0.9970200363F, 0.9970600250F, 0.9970996170F, 0.9971388149F,
  155048. 0.9971776211F, 0.9972160380F, 0.9972540683F, 0.9972917142F,
  155049. 0.9973289783F, 0.9973658631F, 0.9974023709F, 0.9974385042F,
  155050. 0.9974742655F, 0.9975096571F, 0.9975446816F, 0.9975793413F,
  155051. 0.9976136386F, 0.9976475759F, 0.9976811557F, 0.9977143803F,
  155052. 0.9977472521F, 0.9977797736F, 0.9978119470F, 0.9978437748F,
  155053. 0.9978752593F, 0.9979064029F, 0.9979372079F, 0.9979676768F,
  155054. 0.9979978117F, 0.9980276151F, 0.9980570893F, 0.9980862367F,
  155055. 0.9981150595F, 0.9981435600F, 0.9981717406F, 0.9981996035F,
  155056. 0.9982271511F, 0.9982543856F, 0.9982813093F, 0.9983079246F,
  155057. 0.9983342336F, 0.9983602386F, 0.9983859418F, 0.9984113456F,
  155058. 0.9984364522F, 0.9984612638F, 0.9984857825F, 0.9985100108F,
  155059. 0.9985339507F, 0.9985576044F, 0.9985809743F, 0.9986040624F,
  155060. 0.9986268710F, 0.9986494022F, 0.9986716583F, 0.9986936413F,
  155061. 0.9987153535F, 0.9987367969F, 0.9987579738F, 0.9987788864F,
  155062. 0.9987995366F, 0.9988199267F, 0.9988400587F, 0.9988599348F,
  155063. 0.9988795572F, 0.9988989278F, 0.9989180487F, 0.9989369222F,
  155064. 0.9989555501F, 0.9989739347F, 0.9989920780F, 0.9990099820F,
  155065. 0.9990276487F, 0.9990450803F, 0.9990622787F, 0.9990792460F,
  155066. 0.9990959841F, 0.9991124952F, 0.9991287812F, 0.9991448440F,
  155067. 0.9991606858F, 0.9991763084F, 0.9991917139F, 0.9992069042F,
  155068. 0.9992218813F, 0.9992366471F, 0.9992512035F, 0.9992655525F,
  155069. 0.9992796961F, 0.9992936361F, 0.9993073744F, 0.9993209131F,
  155070. 0.9993342538F, 0.9993473987F, 0.9993603494F, 0.9993731080F,
  155071. 0.9993856762F, 0.9993980559F, 0.9994102490F, 0.9994222573F,
  155072. 0.9994340827F, 0.9994457269F, 0.9994571918F, 0.9994684793F,
  155073. 0.9994795910F, 0.9994905288F, 0.9995012945F, 0.9995118898F,
  155074. 0.9995223165F, 0.9995325765F, 0.9995426713F, 0.9995526029F,
  155075. 0.9995623728F, 0.9995719829F, 0.9995814349F, 0.9995907304F,
  155076. 0.9995998712F, 0.9996088590F, 0.9996176954F, 0.9996263821F,
  155077. 0.9996349208F, 0.9996433132F, 0.9996515609F, 0.9996596656F,
  155078. 0.9996676288F, 0.9996754522F, 0.9996831375F, 0.9996906862F,
  155079. 0.9996981000F, 0.9997053804F, 0.9997125290F, 0.9997195474F,
  155080. 0.9997264371F, 0.9997331998F, 0.9997398369F, 0.9997463500F,
  155081. 0.9997527406F, 0.9997590103F, 0.9997651606F, 0.9997711930F,
  155082. 0.9997771089F, 0.9997829098F, 0.9997885973F, 0.9997941728F,
  155083. 0.9997996378F, 0.9998049936F, 0.9998102419F, 0.9998153839F,
  155084. 0.9998204211F, 0.9998253550F, 0.9998301868F, 0.9998349182F,
  155085. 0.9998395503F, 0.9998440847F, 0.9998485226F, 0.9998528654F,
  155086. 0.9998571146F, 0.9998612713F, 0.9998653370F, 0.9998693130F,
  155087. 0.9998732007F, 0.9998770012F, 0.9998807159F, 0.9998843461F,
  155088. 0.9998878931F, 0.9998913581F, 0.9998947424F, 0.9998980473F,
  155089. 0.9999012740F, 0.9999044237F, 0.9999074976F, 0.9999104971F,
  155090. 0.9999134231F, 0.9999162771F, 0.9999190601F, 0.9999217733F,
  155091. 0.9999244179F, 0.9999269950F, 0.9999295058F, 0.9999319515F,
  155092. 0.9999343332F, 0.9999366519F, 0.9999389088F, 0.9999411050F,
  155093. 0.9999432416F, 0.9999453196F, 0.9999473402F, 0.9999493044F,
  155094. 0.9999512132F, 0.9999530677F, 0.9999548690F, 0.9999566180F,
  155095. 0.9999583157F, 0.9999599633F, 0.9999615616F, 0.9999631116F,
  155096. 0.9999646144F, 0.9999660709F, 0.9999674820F, 0.9999688487F,
  155097. 0.9999701719F, 0.9999714526F, 0.9999726917F, 0.9999738900F,
  155098. 0.9999750486F, 0.9999761682F, 0.9999772497F, 0.9999782941F,
  155099. 0.9999793021F, 0.9999802747F, 0.9999812126F, 0.9999821167F,
  155100. 0.9999829878F, 0.9999838268F, 0.9999846343F, 0.9999854113F,
  155101. 0.9999861584F, 0.9999868765F, 0.9999875664F, 0.9999882287F,
  155102. 0.9999888642F, 0.9999894736F, 0.9999900577F, 0.9999906172F,
  155103. 0.9999911528F, 0.9999916651F, 0.9999921548F, 0.9999926227F,
  155104. 0.9999930693F, 0.9999934954F, 0.9999939015F, 0.9999942883F,
  155105. 0.9999946564F, 0.9999950064F, 0.9999953390F, 0.9999956547F,
  155106. 0.9999959541F, 0.9999962377F, 0.9999965062F, 0.9999967601F,
  155107. 0.9999969998F, 0.9999972260F, 0.9999974392F, 0.9999976399F,
  155108. 0.9999978285F, 0.9999980056F, 0.9999981716F, 0.9999983271F,
  155109. 0.9999984724F, 0.9999986081F, 0.9999987345F, 0.9999988521F,
  155110. 0.9999989613F, 0.9999990625F, 0.9999991562F, 0.9999992426F,
  155111. 0.9999993223F, 0.9999993954F, 0.9999994625F, 0.9999995239F,
  155112. 0.9999995798F, 0.9999996307F, 0.9999996768F, 0.9999997184F,
  155113. 0.9999997559F, 0.9999997895F, 0.9999998195F, 0.9999998462F,
  155114. 0.9999998698F, 0.9999998906F, 0.9999999088F, 0.9999999246F,
  155115. 0.9999999383F, 0.9999999500F, 0.9999999600F, 0.9999999684F,
  155116. 0.9999999754F, 0.9999999811F, 0.9999999858F, 0.9999999896F,
  155117. 0.9999999925F, 0.9999999948F, 0.9999999965F, 0.9999999978F,
  155118. 0.9999999986F, 0.9999999992F, 0.9999999996F, 0.9999999998F,
  155119. 0.9999999999F, 1.0000000000F, 1.0000000000F, 1.0000000000F,
  155120. };
  155121. static float vwin8192[4096] = {
  155122. 0.0000000578F, 0.0000005198F, 0.0000014438F, 0.0000028299F,
  155123. 0.0000046780F, 0.0000069882F, 0.0000097604F, 0.0000129945F,
  155124. 0.0000166908F, 0.0000208490F, 0.0000254692F, 0.0000305515F,
  155125. 0.0000360958F, 0.0000421021F, 0.0000485704F, 0.0000555006F,
  155126. 0.0000628929F, 0.0000707472F, 0.0000790635F, 0.0000878417F,
  155127. 0.0000970820F, 0.0001067842F, 0.0001169483F, 0.0001275744F,
  155128. 0.0001386625F, 0.0001502126F, 0.0001622245F, 0.0001746984F,
  155129. 0.0001876343F, 0.0002010320F, 0.0002148917F, 0.0002292132F,
  155130. 0.0002439967F, 0.0002592421F, 0.0002749493F, 0.0002911184F,
  155131. 0.0003077493F, 0.0003248421F, 0.0003423967F, 0.0003604132F,
  155132. 0.0003788915F, 0.0003978316F, 0.0004172335F, 0.0004370971F,
  155133. 0.0004574226F, 0.0004782098F, 0.0004994587F, 0.0005211694F,
  155134. 0.0005433418F, 0.0005659759F, 0.0005890717F, 0.0006126292F,
  155135. 0.0006366484F, 0.0006611292F, 0.0006860716F, 0.0007114757F,
  155136. 0.0007373414F, 0.0007636687F, 0.0007904576F, 0.0008177080F,
  155137. 0.0008454200F, 0.0008735935F, 0.0009022285F, 0.0009313250F,
  155138. 0.0009608830F, 0.0009909025F, 0.0010213834F, 0.0010523257F,
  155139. 0.0010837295F, 0.0011155946F, 0.0011479211F, 0.0011807090F,
  155140. 0.0012139582F, 0.0012476687F, 0.0012818405F, 0.0013164736F,
  155141. 0.0013515679F, 0.0013871235F, 0.0014231402F, 0.0014596182F,
  155142. 0.0014965573F, 0.0015339576F, 0.0015718190F, 0.0016101415F,
  155143. 0.0016489251F, 0.0016881698F, 0.0017278754F, 0.0017680421F,
  155144. 0.0018086698F, 0.0018497584F, 0.0018913080F, 0.0019333185F,
  155145. 0.0019757898F, 0.0020187221F, 0.0020621151F, 0.0021059690F,
  155146. 0.0021502837F, 0.0021950591F, 0.0022402953F, 0.0022859921F,
  155147. 0.0023321497F, 0.0023787679F, 0.0024258467F, 0.0024733861F,
  155148. 0.0025213861F, 0.0025698466F, 0.0026187676F, 0.0026681491F,
  155149. 0.0027179911F, 0.0027682935F, 0.0028190562F, 0.0028702794F,
  155150. 0.0029219628F, 0.0029741066F, 0.0030267107F, 0.0030797749F,
  155151. 0.0031332994F, 0.0031872841F, 0.0032417289F, 0.0032966338F,
  155152. 0.0033519988F, 0.0034078238F, 0.0034641089F, 0.0035208539F,
  155153. 0.0035780589F, 0.0036357237F, 0.0036938485F, 0.0037524331F,
  155154. 0.0038114775F, 0.0038709817F, 0.0039309456F, 0.0039913692F,
  155155. 0.0040522524F, 0.0041135953F, 0.0041753978F, 0.0042376599F,
  155156. 0.0043003814F, 0.0043635624F, 0.0044272029F, 0.0044913028F,
  155157. 0.0045558620F, 0.0046208806F, 0.0046863585F, 0.0047522955F,
  155158. 0.0048186919F, 0.0048855473F, 0.0049528619F, 0.0050206356F,
  155159. 0.0050888684F, 0.0051575601F, 0.0052267108F, 0.0052963204F,
  155160. 0.0053663890F, 0.0054369163F, 0.0055079025F, 0.0055793474F,
  155161. 0.0056512510F, 0.0057236133F, 0.0057964342F, 0.0058697137F,
  155162. 0.0059434517F, 0.0060176482F, 0.0060923032F, 0.0061674166F,
  155163. 0.0062429883F, 0.0063190183F, 0.0063955066F, 0.0064724532F,
  155164. 0.0065498579F, 0.0066277207F, 0.0067060416F, 0.0067848205F,
  155165. 0.0068640575F, 0.0069437523F, 0.0070239051F, 0.0071045157F,
  155166. 0.0071855840F, 0.0072671102F, 0.0073490940F, 0.0074315355F,
  155167. 0.0075144345F, 0.0075977911F, 0.0076816052F, 0.0077658768F,
  155168. 0.0078506057F, 0.0079357920F, 0.0080214355F, 0.0081075363F,
  155169. 0.0081940943F, 0.0082811094F, 0.0083685816F, 0.0084565108F,
  155170. 0.0085448970F, 0.0086337401F, 0.0087230401F, 0.0088127969F,
  155171. 0.0089030104F, 0.0089936807F, 0.0090848076F, 0.0091763911F,
  155172. 0.0092684311F, 0.0093609276F, 0.0094538805F, 0.0095472898F,
  155173. 0.0096411554F, 0.0097354772F, 0.0098302552F, 0.0099254894F,
  155174. 0.0100211796F, 0.0101173259F, 0.0102139281F, 0.0103109863F,
  155175. 0.0104085002F, 0.0105064700F, 0.0106048955F, 0.0107037766F,
  155176. 0.0108031133F, 0.0109029056F, 0.0110031534F, 0.0111038565F,
  155177. 0.0112050151F, 0.0113066289F, 0.0114086980F, 0.0115112222F,
  155178. 0.0116142015F, 0.0117176359F, 0.0118215252F, 0.0119258695F,
  155179. 0.0120306686F, 0.0121359225F, 0.0122416312F, 0.0123477944F,
  155180. 0.0124544123F, 0.0125614847F, 0.0126690116F, 0.0127769928F,
  155181. 0.0128854284F, 0.0129943182F, 0.0131036623F, 0.0132134604F,
  155182. 0.0133237126F, 0.0134344188F, 0.0135455790F, 0.0136571929F,
  155183. 0.0137692607F, 0.0138817821F, 0.0139947572F, 0.0141081859F,
  155184. 0.0142220681F, 0.0143364037F, 0.0144511927F, 0.0145664350F,
  155185. 0.0146821304F, 0.0147982791F, 0.0149148808F, 0.0150319355F,
  155186. 0.0151494431F, 0.0152674036F, 0.0153858168F, 0.0155046828F,
  155187. 0.0156240014F, 0.0157437726F, 0.0158639962F, 0.0159846723F,
  155188. 0.0161058007F, 0.0162273814F, 0.0163494142F, 0.0164718991F,
  155189. 0.0165948361F, 0.0167182250F, 0.0168420658F, 0.0169663584F,
  155190. 0.0170911027F, 0.0172162987F, 0.0173419462F, 0.0174680452F,
  155191. 0.0175945956F, 0.0177215974F, 0.0178490504F, 0.0179769545F,
  155192. 0.0181053098F, 0.0182341160F, 0.0183633732F, 0.0184930812F,
  155193. 0.0186232399F, 0.0187538494F, 0.0188849094F, 0.0190164200F,
  155194. 0.0191483809F, 0.0192807923F, 0.0194136539F, 0.0195469656F,
  155195. 0.0196807275F, 0.0198149394F, 0.0199496012F, 0.0200847128F,
  155196. 0.0202202742F, 0.0203562853F, 0.0204927460F, 0.0206296561F,
  155197. 0.0207670157F, 0.0209048245F, 0.0210430826F, 0.0211817899F,
  155198. 0.0213209462F, 0.0214605515F, 0.0216006057F, 0.0217411086F,
  155199. 0.0218820603F, 0.0220234605F, 0.0221653093F, 0.0223076066F,
  155200. 0.0224503521F, 0.0225935459F, 0.0227371879F, 0.0228812779F,
  155201. 0.0230258160F, 0.0231708018F, 0.0233162355F, 0.0234621169F,
  155202. 0.0236084459F, 0.0237552224F, 0.0239024462F, 0.0240501175F,
  155203. 0.0241982359F, 0.0243468015F, 0.0244958141F, 0.0246452736F,
  155204. 0.0247951800F, 0.0249455331F, 0.0250963329F, 0.0252475792F,
  155205. 0.0253992720F, 0.0255514111F, 0.0257039965F, 0.0258570281F,
  155206. 0.0260105057F, 0.0261644293F, 0.0263187987F, 0.0264736139F,
  155207. 0.0266288747F, 0.0267845811F, 0.0269407330F, 0.0270973302F,
  155208. 0.0272543727F, 0.0274118604F, 0.0275697930F, 0.0277281707F,
  155209. 0.0278869932F, 0.0280462604F, 0.0282059723F, 0.0283661287F,
  155210. 0.0285267295F, 0.0286877747F, 0.0288492641F, 0.0290111976F,
  155211. 0.0291735751F, 0.0293363965F, 0.0294996617F, 0.0296633706F,
  155212. 0.0298275231F, 0.0299921190F, 0.0301571583F, 0.0303226409F,
  155213. 0.0304885667F, 0.0306549354F, 0.0308217472F, 0.0309890017F,
  155214. 0.0311566989F, 0.0313248388F, 0.0314934211F, 0.0316624459F,
  155215. 0.0318319128F, 0.0320018220F, 0.0321721732F, 0.0323429663F,
  155216. 0.0325142013F, 0.0326858779F, 0.0328579962F, 0.0330305559F,
  155217. 0.0332035570F, 0.0333769994F, 0.0335508829F, 0.0337252074F,
  155218. 0.0338999728F, 0.0340751790F, 0.0342508259F, 0.0344269134F,
  155219. 0.0346034412F, 0.0347804094F, 0.0349578178F, 0.0351356663F,
  155220. 0.0353139548F, 0.0354926831F, 0.0356718511F, 0.0358514588F,
  155221. 0.0360315059F, 0.0362119924F, 0.0363929182F, 0.0365742831F,
  155222. 0.0367560870F, 0.0369383297F, 0.0371210113F, 0.0373041315F,
  155223. 0.0374876902F, 0.0376716873F, 0.0378561226F, 0.0380409961F,
  155224. 0.0382263077F, 0.0384120571F, 0.0385982443F, 0.0387848691F,
  155225. 0.0389719315F, 0.0391594313F, 0.0393473683F, 0.0395357425F,
  155226. 0.0397245537F, 0.0399138017F, 0.0401034866F, 0.0402936080F,
  155227. 0.0404841660F, 0.0406751603F, 0.0408665909F, 0.0410584576F,
  155228. 0.0412507603F, 0.0414434988F, 0.0416366731F, 0.0418302829F,
  155229. 0.0420243282F, 0.0422188088F, 0.0424137246F, 0.0426090755F,
  155230. 0.0428048613F, 0.0430010819F, 0.0431977371F, 0.0433948269F,
  155231. 0.0435923511F, 0.0437903095F, 0.0439887020F, 0.0441875285F,
  155232. 0.0443867889F, 0.0445864830F, 0.0447866106F, 0.0449871717F,
  155233. 0.0451881661F, 0.0453895936F, 0.0455914542F, 0.0457937477F,
  155234. 0.0459964738F, 0.0461996326F, 0.0464032239F, 0.0466072475F,
  155235. 0.0468117032F, 0.0470165910F, 0.0472219107F, 0.0474276622F,
  155236. 0.0476338452F, 0.0478404597F, 0.0480475056F, 0.0482549827F,
  155237. 0.0484628907F, 0.0486712297F, 0.0488799994F, 0.0490891998F,
  155238. 0.0492988306F, 0.0495088917F, 0.0497193830F, 0.0499303043F,
  155239. 0.0501416554F, 0.0503534363F, 0.0505656468F, 0.0507782867F,
  155240. 0.0509913559F, 0.0512048542F, 0.0514187815F, 0.0516331376F,
  155241. 0.0518479225F, 0.0520631358F, 0.0522787775F, 0.0524948475F,
  155242. 0.0527113455F, 0.0529282715F, 0.0531456252F, 0.0533634066F,
  155243. 0.0535816154F, 0.0538002515F, 0.0540193148F, 0.0542388051F,
  155244. 0.0544587222F, 0.0546790660F, 0.0548998364F, 0.0551210331F,
  155245. 0.0553426561F, 0.0555647051F, 0.0557871801F, 0.0560100807F,
  155246. 0.0562334070F, 0.0564571587F, 0.0566813357F, 0.0569059378F,
  155247. 0.0571309649F, 0.0573564168F, 0.0575822933F, 0.0578085942F,
  155248. 0.0580353195F, 0.0582624689F, 0.0584900423F, 0.0587180396F,
  155249. 0.0589464605F, 0.0591753049F, 0.0594045726F, 0.0596342635F,
  155250. 0.0598643774F, 0.0600949141F, 0.0603258735F, 0.0605572555F,
  155251. 0.0607890597F, 0.0610212862F, 0.0612539346F, 0.0614870049F,
  155252. 0.0617204968F, 0.0619544103F, 0.0621887451F, 0.0624235010F,
  155253. 0.0626586780F, 0.0628942758F, 0.0631302942F, 0.0633667331F,
  155254. 0.0636035923F, 0.0638408717F, 0.0640785710F, 0.0643166901F,
  155255. 0.0645552288F, 0.0647941870F, 0.0650335645F, 0.0652733610F,
  155256. 0.0655135765F, 0.0657542108F, 0.0659952636F, 0.0662367348F,
  155257. 0.0664786242F, 0.0667209316F, 0.0669636570F, 0.0672068000F,
  155258. 0.0674503605F, 0.0676943384F, 0.0679387334F, 0.0681835454F,
  155259. 0.0684287742F, 0.0686744196F, 0.0689204814F, 0.0691669595F,
  155260. 0.0694138536F, 0.0696611637F, 0.0699088894F, 0.0701570307F,
  155261. 0.0704055873F, 0.0706545590F, 0.0709039458F, 0.0711537473F,
  155262. 0.0714039634F, 0.0716545939F, 0.0719056387F, 0.0721570975F,
  155263. 0.0724089702F, 0.0726612565F, 0.0729139563F, 0.0731670694F,
  155264. 0.0734205956F, 0.0736745347F, 0.0739288866F, 0.0741836510F,
  155265. 0.0744388277F, 0.0746944166F, 0.0749504175F, 0.0752068301F,
  155266. 0.0754636543F, 0.0757208899F, 0.0759785367F, 0.0762365946F,
  155267. 0.0764950632F, 0.0767539424F, 0.0770132320F, 0.0772729319F,
  155268. 0.0775330418F, 0.0777935616F, 0.0780544909F, 0.0783158298F,
  155269. 0.0785775778F, 0.0788397349F, 0.0791023009F, 0.0793652755F,
  155270. 0.0796286585F, 0.0798924498F, 0.0801566492F, 0.0804212564F,
  155271. 0.0806862712F, 0.0809516935F, 0.0812175231F, 0.0814837597F,
  155272. 0.0817504031F, 0.0820174532F, 0.0822849097F, 0.0825527724F,
  155273. 0.0828210412F, 0.0830897158F, 0.0833587960F, 0.0836282816F,
  155274. 0.0838981724F, 0.0841684682F, 0.0844391688F, 0.0847102740F,
  155275. 0.0849817835F, 0.0852536973F, 0.0855260150F, 0.0857987364F,
  155276. 0.0860718614F, 0.0863453897F, 0.0866193211F, 0.0868936554F,
  155277. 0.0871683924F, 0.0874435319F, 0.0877190737F, 0.0879950175F,
  155278. 0.0882713632F, 0.0885481105F, 0.0888252592F, 0.0891028091F,
  155279. 0.0893807600F, 0.0896591117F, 0.0899378639F, 0.0902170165F,
  155280. 0.0904965692F, 0.0907765218F, 0.0910568740F, 0.0913376258F,
  155281. 0.0916187767F, 0.0919003268F, 0.0921822756F, 0.0924646230F,
  155282. 0.0927473687F, 0.0930305126F, 0.0933140545F, 0.0935979940F,
  155283. 0.0938823310F, 0.0941670653F, 0.0944521966F, 0.0947377247F,
  155284. 0.0950236494F, 0.0953099704F, 0.0955966876F, 0.0958838007F,
  155285. 0.0961713094F, 0.0964592136F, 0.0967475131F, 0.0970362075F,
  155286. 0.0973252967F, 0.0976147805F, 0.0979046585F, 0.0981949307F,
  155287. 0.0984855967F, 0.0987766563F, 0.0990681093F, 0.0993599555F,
  155288. 0.0996521945F, 0.0999448263F, 0.1002378506F, 0.1005312671F,
  155289. 0.1008250755F, 0.1011192757F, 0.1014138675F, 0.1017088505F,
  155290. 0.1020042246F, 0.1022999895F, 0.1025961450F, 0.1028926909F,
  155291. 0.1031896268F, 0.1034869526F, 0.1037846680F, 0.1040827729F,
  155292. 0.1043812668F, 0.1046801497F, 0.1049794213F, 0.1052790813F,
  155293. 0.1055791294F, 0.1058795656F, 0.1061803894F, 0.1064816006F,
  155294. 0.1067831991F, 0.1070851846F, 0.1073875568F, 0.1076903155F,
  155295. 0.1079934604F, 0.1082969913F, 0.1086009079F, 0.1089052101F,
  155296. 0.1092098975F, 0.1095149699F, 0.1098204270F, 0.1101262687F,
  155297. 0.1104324946F, 0.1107391045F, 0.1110460982F, 0.1113534754F,
  155298. 0.1116612359F, 0.1119693793F, 0.1122779055F, 0.1125868142F,
  155299. 0.1128961052F, 0.1132057781F, 0.1135158328F, 0.1138262690F,
  155300. 0.1141370863F, 0.1144482847F, 0.1147598638F, 0.1150718233F,
  155301. 0.1153841631F, 0.1156968828F, 0.1160099822F, 0.1163234610F,
  155302. 0.1166373190F, 0.1169515559F, 0.1172661714F, 0.1175811654F,
  155303. 0.1178965374F, 0.1182122874F, 0.1185284149F, 0.1188449198F,
  155304. 0.1191618018F, 0.1194790606F, 0.1197966960F, 0.1201147076F,
  155305. 0.1204330953F, 0.1207518587F, 0.1210709976F, 0.1213905118F,
  155306. 0.1217104009F, 0.1220306647F, 0.1223513029F, 0.1226723153F,
  155307. 0.1229937016F, 0.1233154615F, 0.1236375948F, 0.1239601011F,
  155308. 0.1242829803F, 0.1246062319F, 0.1249298559F, 0.1252538518F,
  155309. 0.1255782195F, 0.1259029586F, 0.1262280689F, 0.1265535501F,
  155310. 0.1268794019F, 0.1272056241F, 0.1275322163F, 0.1278591784F,
  155311. 0.1281865099F, 0.1285142108F, 0.1288422805F, 0.1291707190F,
  155312. 0.1294995259F, 0.1298287009F, 0.1301582437F, 0.1304881542F,
  155313. 0.1308184319F, 0.1311490766F, 0.1314800881F, 0.1318114660F,
  155314. 0.1321432100F, 0.1324753200F, 0.1328077955F, 0.1331406364F,
  155315. 0.1334738422F, 0.1338074129F, 0.1341413479F, 0.1344756472F,
  155316. 0.1348103103F, 0.1351453370F, 0.1354807270F, 0.1358164801F,
  155317. 0.1361525959F, 0.1364890741F, 0.1368259145F, 0.1371631167F,
  155318. 0.1375006805F, 0.1378386056F, 0.1381768917F, 0.1385155384F,
  155319. 0.1388545456F, 0.1391939129F, 0.1395336400F, 0.1398737266F,
  155320. 0.1402141724F, 0.1405549772F, 0.1408961406F, 0.1412376623F,
  155321. 0.1415795421F, 0.1419217797F, 0.1422643746F, 0.1426073268F,
  155322. 0.1429506358F, 0.1432943013F, 0.1436383231F, 0.1439827008F,
  155323. 0.1443274342F, 0.1446725229F, 0.1450179667F, 0.1453637652F,
  155324. 0.1457099181F, 0.1460564252F, 0.1464032861F, 0.1467505006F,
  155325. 0.1470980682F, 0.1474459888F, 0.1477942620F, 0.1481428875F,
  155326. 0.1484918651F, 0.1488411942F, 0.1491908748F, 0.1495409065F,
  155327. 0.1498912889F, 0.1502420218F, 0.1505931048F, 0.1509445376F,
  155328. 0.1512963200F, 0.1516484516F, 0.1520009321F, 0.1523537612F,
  155329. 0.1527069385F, 0.1530604638F, 0.1534143368F, 0.1537685571F,
  155330. 0.1541231244F, 0.1544780384F, 0.1548332987F, 0.1551889052F,
  155331. 0.1555448574F, 0.1559011550F, 0.1562577978F, 0.1566147853F,
  155332. 0.1569721173F, 0.1573297935F, 0.1576878135F, 0.1580461771F,
  155333. 0.1584048838F, 0.1587639334F, 0.1591233255F, 0.1594830599F,
  155334. 0.1598431361F, 0.1602035540F, 0.1605643131F, 0.1609254131F,
  155335. 0.1612868537F, 0.1616486346F, 0.1620107555F, 0.1623732160F,
  155336. 0.1627360158F, 0.1630991545F, 0.1634626319F, 0.1638264476F,
  155337. 0.1641906013F, 0.1645550926F, 0.1649199212F, 0.1652850869F,
  155338. 0.1656505892F, 0.1660164278F, 0.1663826024F, 0.1667491127F,
  155339. 0.1671159583F, 0.1674831388F, 0.1678506541F, 0.1682185036F,
  155340. 0.1685866872F, 0.1689552044F, 0.1693240549F, 0.1696932384F,
  155341. 0.1700627545F, 0.1704326029F, 0.1708027833F, 0.1711732952F,
  155342. 0.1715441385F, 0.1719153127F, 0.1722868175F, 0.1726586526F,
  155343. 0.1730308176F, 0.1734033121F, 0.1737761359F, 0.1741492886F,
  155344. 0.1745227698F, 0.1748965792F, 0.1752707164F, 0.1756451812F,
  155345. 0.1760199731F, 0.1763950918F, 0.1767705370F, 0.1771463083F,
  155346. 0.1775224054F, 0.1778988279F, 0.1782755754F, 0.1786526477F,
  155347. 0.1790300444F, 0.1794077651F, 0.1797858094F, 0.1801641771F,
  155348. 0.1805428677F, 0.1809218810F, 0.1813012165F, 0.1816808739F,
  155349. 0.1820608528F, 0.1824411530F, 0.1828217739F, 0.1832027154F,
  155350. 0.1835839770F, 0.1839655584F, 0.1843474592F, 0.1847296790F,
  155351. 0.1851122175F, 0.1854950744F, 0.1858782492F, 0.1862617417F,
  155352. 0.1866455514F, 0.1870296780F, 0.1874141211F, 0.1877988804F,
  155353. 0.1881839555F, 0.1885693461F, 0.1889550517F, 0.1893410721F,
  155354. 0.1897274068F, 0.1901140555F, 0.1905010178F, 0.1908882933F,
  155355. 0.1912758818F, 0.1916637828F, 0.1920519959F, 0.1924405208F,
  155356. 0.1928293571F, 0.1932185044F, 0.1936079625F, 0.1939977308F,
  155357. 0.1943878091F, 0.1947781969F, 0.1951688939F, 0.1955598998F,
  155358. 0.1959512141F, 0.1963428364F, 0.1967347665F, 0.1971270038F,
  155359. 0.1975195482F, 0.1979123990F, 0.1983055561F, 0.1986990190F,
  155360. 0.1990927873F, 0.1994868607F, 0.1998812388F, 0.2002759212F,
  155361. 0.2006709075F, 0.2010661974F, 0.2014617904F, 0.2018576862F,
  155362. 0.2022538844F, 0.2026503847F, 0.2030471865F, 0.2034442897F,
  155363. 0.2038416937F, 0.2042393982F, 0.2046374028F, 0.2050357071F,
  155364. 0.2054343107F, 0.2058332133F, 0.2062324145F, 0.2066319138F,
  155365. 0.2070317110F, 0.2074318055F, 0.2078321970F, 0.2082328852F,
  155366. 0.2086338696F, 0.2090351498F, 0.2094367255F, 0.2098385962F,
  155367. 0.2102407617F, 0.2106432213F, 0.2110459749F, 0.2114490220F,
  155368. 0.2118523621F, 0.2122559950F, 0.2126599202F, 0.2130641373F,
  155369. 0.2134686459F, 0.2138734456F, 0.2142785361F, 0.2146839168F,
  155370. 0.2150895875F, 0.2154955478F, 0.2159017972F, 0.2163083353F,
  155371. 0.2167151617F, 0.2171222761F, 0.2175296780F, 0.2179373670F,
  155372. 0.2183453428F, 0.2187536049F, 0.2191621529F, 0.2195709864F,
  155373. 0.2199801051F, 0.2203895085F, 0.2207991961F, 0.2212091677F,
  155374. 0.2216194228F, 0.2220299610F, 0.2224407818F, 0.2228518850F,
  155375. 0.2232632699F, 0.2236749364F, 0.2240868839F, 0.2244991121F,
  155376. 0.2249116204F, 0.2253244086F, 0.2257374763F, 0.2261508229F,
  155377. 0.2265644481F, 0.2269783514F, 0.2273925326F, 0.2278069911F,
  155378. 0.2282217265F, 0.2286367384F, 0.2290520265F, 0.2294675902F,
  155379. 0.2298834292F, 0.2302995431F, 0.2307159314F, 0.2311325937F,
  155380. 0.2315495297F, 0.2319667388F, 0.2323842207F, 0.2328019749F,
  155381. 0.2332200011F, 0.2336382988F, 0.2340568675F, 0.2344757070F,
  155382. 0.2348948166F, 0.2353141961F, 0.2357338450F, 0.2361537629F,
  155383. 0.2365739493F, 0.2369944038F, 0.2374151261F, 0.2378361156F,
  155384. 0.2382573720F, 0.2386788948F, 0.2391006836F, 0.2395227380F,
  155385. 0.2399450575F, 0.2403676417F, 0.2407904902F, 0.2412136026F,
  155386. 0.2416369783F, 0.2420606171F, 0.2424845185F, 0.2429086820F,
  155387. 0.2433331072F, 0.2437577936F, 0.2441827409F, 0.2446079486F,
  155388. 0.2450334163F, 0.2454591435F, 0.2458851298F, 0.2463113747F,
  155389. 0.2467378779F, 0.2471646389F, 0.2475916573F, 0.2480189325F,
  155390. 0.2484464643F, 0.2488742521F, 0.2493022955F, 0.2497305940F,
  155391. 0.2501591473F, 0.2505879549F, 0.2510170163F, 0.2514463311F,
  155392. 0.2518758989F, 0.2523057193F, 0.2527357916F, 0.2531661157F,
  155393. 0.2535966909F, 0.2540275169F, 0.2544585931F, 0.2548899193F,
  155394. 0.2553214948F, 0.2557533193F, 0.2561853924F, 0.2566177135F,
  155395. 0.2570502822F, 0.2574830981F, 0.2579161608F, 0.2583494697F,
  155396. 0.2587830245F, 0.2592168246F, 0.2596508697F, 0.2600851593F,
  155397. 0.2605196929F, 0.2609544701F, 0.2613894904F, 0.2618247534F,
  155398. 0.2622602586F, 0.2626960055F, 0.2631319938F, 0.2635682230F,
  155399. 0.2640046925F, 0.2644414021F, 0.2648783511F, 0.2653155391F,
  155400. 0.2657529657F, 0.2661906305F, 0.2666285329F, 0.2670666725F,
  155401. 0.2675050489F, 0.2679436616F, 0.2683825101F, 0.2688215940F,
  155402. 0.2692609127F, 0.2697004660F, 0.2701402532F, 0.2705802739F,
  155403. 0.2710205278F, 0.2714610142F, 0.2719017327F, 0.2723426830F,
  155404. 0.2727838644F, 0.2732252766F, 0.2736669191F, 0.2741087914F,
  155405. 0.2745508930F, 0.2749932235F, 0.2754357824F, 0.2758785693F,
  155406. 0.2763215837F, 0.2767648251F, 0.2772082930F, 0.2776519870F,
  155407. 0.2780959066F, 0.2785400513F, 0.2789844207F, 0.2794290143F,
  155408. 0.2798738316F, 0.2803188722F, 0.2807641355F, 0.2812096211F,
  155409. 0.2816553286F, 0.2821012574F, 0.2825474071F, 0.2829937773F,
  155410. 0.2834403673F, 0.2838871768F, 0.2843342053F, 0.2847814523F,
  155411. 0.2852289174F, 0.2856765999F, 0.2861244996F, 0.2865726159F,
  155412. 0.2870209482F, 0.2874694962F, 0.2879182594F, 0.2883672372F,
  155413. 0.2888164293F, 0.2892658350F, 0.2897154540F, 0.2901652858F,
  155414. 0.2906153298F, 0.2910655856F, 0.2915160527F, 0.2919667306F,
  155415. 0.2924176189F, 0.2928687171F, 0.2933200246F, 0.2937715409F,
  155416. 0.2942232657F, 0.2946751984F, 0.2951273386F, 0.2955796856F,
  155417. 0.2960322391F, 0.2964849986F, 0.2969379636F, 0.2973911335F,
  155418. 0.2978445080F, 0.2982980864F, 0.2987518684F, 0.2992058534F,
  155419. 0.2996600409F, 0.3001144305F, 0.3005690217F, 0.3010238139F,
  155420. 0.3014788067F, 0.3019339995F, 0.3023893920F, 0.3028449835F,
  155421. 0.3033007736F, 0.3037567618F, 0.3042129477F, 0.3046693306F,
  155422. 0.3051259102F, 0.3055826859F, 0.3060396572F, 0.3064968236F,
  155423. 0.3069541847F, 0.3074117399F, 0.3078694887F, 0.3083274307F,
  155424. 0.3087855653F, 0.3092438920F, 0.3097024104F, 0.3101611199F,
  155425. 0.3106200200F, 0.3110791103F, 0.3115383902F, 0.3119978592F,
  155426. 0.3124575169F, 0.3129173627F, 0.3133773961F, 0.3138376166F,
  155427. 0.3142980238F, 0.3147586170F, 0.3152193959F, 0.3156803598F,
  155428. 0.3161415084F, 0.3166028410F, 0.3170643573F, 0.3175260566F,
  155429. 0.3179879384F, 0.3184500023F, 0.3189122478F, 0.3193746743F,
  155430. 0.3198372814F, 0.3203000685F, 0.3207630351F, 0.3212261807F,
  155431. 0.3216895048F, 0.3221530069F, 0.3226166865F, 0.3230805430F,
  155432. 0.3235445760F, 0.3240087849F, 0.3244731693F, 0.3249377285F,
  155433. 0.3254024622F, 0.3258673698F, 0.3263324507F, 0.3267977045F,
  155434. 0.3272631306F, 0.3277287286F, 0.3281944978F, 0.3286604379F,
  155435. 0.3291265482F, 0.3295928284F, 0.3300592777F, 0.3305258958F,
  155436. 0.3309926821F, 0.3314596361F, 0.3319267573F, 0.3323940451F,
  155437. 0.3328614990F, 0.3333291186F, 0.3337969033F, 0.3342648525F,
  155438. 0.3347329658F, 0.3352012427F, 0.3356696825F, 0.3361382849F,
  155439. 0.3366070492F, 0.3370759749F, 0.3375450616F, 0.3380143087F,
  155440. 0.3384837156F, 0.3389532819F, 0.3394230071F, 0.3398928905F,
  155441. 0.3403629317F, 0.3408331302F, 0.3413034854F, 0.3417739967F,
  155442. 0.3422446638F, 0.3427154860F, 0.3431864628F, 0.3436575938F,
  155443. 0.3441288782F, 0.3446003158F, 0.3450719058F, 0.3455436478F,
  155444. 0.3460155412F, 0.3464875856F, 0.3469597804F, 0.3474321250F,
  155445. 0.3479046189F, 0.3483772617F, 0.3488500527F, 0.3493229914F,
  155446. 0.3497960774F, 0.3502693100F, 0.3507426887F, 0.3512162131F,
  155447. 0.3516898825F, 0.3521636965F, 0.3526376545F, 0.3531117559F,
  155448. 0.3535860003F, 0.3540603870F, 0.3545349157F, 0.3550095856F,
  155449. 0.3554843964F, 0.3559593474F, 0.3564344381F, 0.3569096680F,
  155450. 0.3573850366F, 0.3578605432F, 0.3583361875F, 0.3588119687F,
  155451. 0.3592878865F, 0.3597639402F, 0.3602401293F, 0.3607164533F,
  155452. 0.3611929117F, 0.3616695038F, 0.3621462292F, 0.3626230873F,
  155453. 0.3631000776F, 0.3635771995F, 0.3640544525F, 0.3645318360F,
  155454. 0.3650093496F, 0.3654869926F, 0.3659647645F, 0.3664426648F,
  155455. 0.3669206930F, 0.3673988484F, 0.3678771306F, 0.3683555390F,
  155456. 0.3688340731F, 0.3693127322F, 0.3697915160F, 0.3702704237F,
  155457. 0.3707494549F, 0.3712286091F, 0.3717078857F, 0.3721872840F,
  155458. 0.3726668037F, 0.3731464441F, 0.3736262047F, 0.3741060850F,
  155459. 0.3745860843F, 0.3750662023F, 0.3755464382F, 0.3760267915F,
  155460. 0.3765072618F, 0.3769878484F, 0.3774685509F, 0.3779493686F,
  155461. 0.3784303010F, 0.3789113475F, 0.3793925076F, 0.3798737809F,
  155462. 0.3803551666F, 0.3808366642F, 0.3813182733F, 0.3817999932F,
  155463. 0.3822818234F, 0.3827637633F, 0.3832458124F, 0.3837279702F,
  155464. 0.3842102360F, 0.3846926093F, 0.3851750897F, 0.3856576764F,
  155465. 0.3861403690F, 0.3866231670F, 0.3871060696F, 0.3875890765F,
  155466. 0.3880721870F, 0.3885554007F, 0.3890387168F, 0.3895221349F,
  155467. 0.3900056544F, 0.3904892748F, 0.3909729955F, 0.3914568160F,
  155468. 0.3919407356F, 0.3924247539F, 0.3929088702F, 0.3933930841F,
  155469. 0.3938773949F, 0.3943618021F, 0.3948463052F, 0.3953309035F,
  155470. 0.3958155966F, 0.3963003838F, 0.3967852646F, 0.3972702385F,
  155471. 0.3977553048F, 0.3982404631F, 0.3987257127F, 0.3992110531F,
  155472. 0.3996964838F, 0.4001820041F, 0.4006676136F, 0.4011533116F,
  155473. 0.4016390976F, 0.4021249710F, 0.4026109313F, 0.4030969779F,
  155474. 0.4035831102F, 0.4040693277F, 0.4045556299F, 0.4050420160F,
  155475. 0.4055284857F, 0.4060150383F, 0.4065016732F, 0.4069883899F,
  155476. 0.4074751879F, 0.4079620665F, 0.4084490252F, 0.4089360635F,
  155477. 0.4094231807F, 0.4099103763F, 0.4103976498F, 0.4108850005F,
  155478. 0.4113724280F, 0.4118599315F, 0.4123475107F, 0.4128351648F,
  155479. 0.4133228934F, 0.4138106959F, 0.4142985716F, 0.4147865201F,
  155480. 0.4152745408F, 0.4157626330F, 0.4162507963F, 0.4167390301F,
  155481. 0.4172273337F, 0.4177157067F, 0.4182041484F, 0.4186926583F,
  155482. 0.4191812359F, 0.4196698805F, 0.4201585915F, 0.4206473685F,
  155483. 0.4211362108F, 0.4216251179F, 0.4221140892F, 0.4226031241F,
  155484. 0.4230922221F, 0.4235813826F, 0.4240706050F, 0.4245598887F,
  155485. 0.4250492332F, 0.4255386379F, 0.4260281022F, 0.4265176256F,
  155486. 0.4270072075F, 0.4274968473F, 0.4279865445F, 0.4284762984F,
  155487. 0.4289661086F, 0.4294559743F, 0.4299458951F, 0.4304358704F,
  155488. 0.4309258996F, 0.4314159822F, 0.4319061175F, 0.4323963050F,
  155489. 0.4328865441F, 0.4333768342F, 0.4338671749F, 0.4343575654F,
  155490. 0.4348480052F, 0.4353384938F, 0.4358290306F, 0.4363196149F,
  155491. 0.4368102463F, 0.4373009241F, 0.4377916478F, 0.4382824168F,
  155492. 0.4387732305F, 0.4392640884F, 0.4397549899F, 0.4402459343F,
  155493. 0.4407369212F, 0.4412279499F, 0.4417190198F, 0.4422101305F,
  155494. 0.4427012813F, 0.4431924717F, 0.4436837010F, 0.4441749686F,
  155495. 0.4446662742F, 0.4451576169F, 0.4456489963F, 0.4461404118F,
  155496. 0.4466318628F, 0.4471233487F, 0.4476148690F, 0.4481064230F,
  155497. 0.4485980103F, 0.4490896302F, 0.4495812821F, 0.4500729654F,
  155498. 0.4505646797F, 0.4510564243F, 0.4515481986F, 0.4520400021F,
  155499. 0.4525318341F, 0.4530236942F, 0.4535155816F, 0.4540074959F,
  155500. 0.4544994365F, 0.4549914028F, 0.4554833941F, 0.4559754100F,
  155501. 0.4564674499F, 0.4569595131F, 0.4574515991F, 0.4579437074F,
  155502. 0.4584358372F, 0.4589279881F, 0.4594201595F, 0.4599123508F,
  155503. 0.4604045615F, 0.4608967908F, 0.4613890383F, 0.4618813034F,
  155504. 0.4623735855F, 0.4628658841F, 0.4633581984F, 0.4638505281F,
  155505. 0.4643428724F, 0.4648352308F, 0.4653276028F, 0.4658199877F,
  155506. 0.4663123849F, 0.4668047940F, 0.4672972143F, 0.4677896451F,
  155507. 0.4682820861F, 0.4687745365F, 0.4692669958F, 0.4697594634F,
  155508. 0.4702519387F, 0.4707444211F, 0.4712369102F, 0.4717294052F,
  155509. 0.4722219056F, 0.4727144109F, 0.4732069204F, 0.4736994336F,
  155510. 0.4741919498F, 0.4746844686F, 0.4751769893F, 0.4756695113F,
  155511. 0.4761620341F, 0.4766545571F, 0.4771470797F, 0.4776396013F,
  155512. 0.4781321213F, 0.4786246392F, 0.4791171544F, 0.4796096663F,
  155513. 0.4801021744F, 0.4805946779F, 0.4810871765F, 0.4815796694F,
  155514. 0.4820721561F, 0.4825646360F, 0.4830571086F, 0.4835495732F,
  155515. 0.4840420293F, 0.4845344763F, 0.4850269136F, 0.4855193407F,
  155516. 0.4860117569F, 0.4865041617F, 0.4869965545F, 0.4874889347F,
  155517. 0.4879813018F, 0.4884736551F, 0.4889659941F, 0.4894583182F,
  155518. 0.4899506268F, 0.4904429193F, 0.4909351952F, 0.4914274538F,
  155519. 0.4919196947F, 0.4924119172F, 0.4929041207F, 0.4933963046F,
  155520. 0.4938884685F, 0.4943806116F, 0.4948727335F, 0.4953648335F,
  155521. 0.4958569110F, 0.4963489656F, 0.4968409965F, 0.4973330032F,
  155522. 0.4978249852F, 0.4983169419F, 0.4988088726F, 0.4993007768F,
  155523. 0.4997926539F, 0.5002845034F, 0.5007763247F, 0.5012681171F,
  155524. 0.5017598801F, 0.5022516132F, 0.5027433157F, 0.5032349871F,
  155525. 0.5037266268F, 0.5042182341F, 0.5047098086F, 0.5052013497F,
  155526. 0.5056928567F, 0.5061843292F, 0.5066757664F, 0.5071671679F,
  155527. 0.5076585330F, 0.5081498613F, 0.5086411520F, 0.5091324047F,
  155528. 0.5096236187F, 0.5101147934F, 0.5106059284F, 0.5110970230F,
  155529. 0.5115880766F, 0.5120790887F, 0.5125700587F, 0.5130609860F,
  155530. 0.5135518700F, 0.5140427102F, 0.5145335059F, 0.5150242566F,
  155531. 0.5155149618F, 0.5160056208F, 0.5164962331F, 0.5169867980F,
  155532. 0.5174773151F, 0.5179677837F, 0.5184582033F, 0.5189485733F,
  155533. 0.5194388931F, 0.5199291621F, 0.5204193798F, 0.5209095455F,
  155534. 0.5213996588F, 0.5218897190F, 0.5223797256F, 0.5228696779F,
  155535. 0.5233595755F, 0.5238494177F, 0.5243392039F, 0.5248289337F,
  155536. 0.5253186063F, 0.5258082213F, 0.5262977781F, 0.5267872760F,
  155537. 0.5272767146F, 0.5277660932F, 0.5282554112F, 0.5287446682F,
  155538. 0.5292338635F, 0.5297229965F, 0.5302120667F, 0.5307010736F,
  155539. 0.5311900164F, 0.5316788947F, 0.5321677079F, 0.5326564554F,
  155540. 0.5331451366F, 0.5336337511F, 0.5341222981F, 0.5346107771F,
  155541. 0.5350991876F, 0.5355875290F, 0.5360758007F, 0.5365640021F,
  155542. 0.5370521327F, 0.5375401920F, 0.5380281792F, 0.5385160939F,
  155543. 0.5390039355F, 0.5394917034F, 0.5399793971F, 0.5404670159F,
  155544. 0.5409545594F, 0.5414420269F, 0.5419294179F, 0.5424167318F,
  155545. 0.5429039680F, 0.5433911261F, 0.5438782053F, 0.5443652051F,
  155546. 0.5448521250F, 0.5453389644F, 0.5458257228F, 0.5463123995F,
  155547. 0.5467989940F, 0.5472855057F, 0.5477719341F, 0.5482582786F,
  155548. 0.5487445387F, 0.5492307137F, 0.5497168031F, 0.5502028063F,
  155549. 0.5506887228F, 0.5511745520F, 0.5516602934F, 0.5521459463F,
  155550. 0.5526315103F, 0.5531169847F, 0.5536023690F, 0.5540876626F,
  155551. 0.5545728649F, 0.5550579755F, 0.5555429937F, 0.5560279189F,
  155552. 0.5565127507F, 0.5569974884F, 0.5574821315F, 0.5579666794F,
  155553. 0.5584511316F, 0.5589354875F, 0.5594197465F, 0.5599039080F,
  155554. 0.5603879716F, 0.5608719367F, 0.5613558026F, 0.5618395689F,
  155555. 0.5623232350F, 0.5628068002F, 0.5632902642F, 0.5637736262F,
  155556. 0.5642568858F, 0.5647400423F, 0.5652230953F, 0.5657060442F,
  155557. 0.5661888883F, 0.5666716272F, 0.5671542603F, 0.5676367870F,
  155558. 0.5681192069F, 0.5686015192F, 0.5690837235F, 0.5695658192F,
  155559. 0.5700478058F, 0.5705296827F, 0.5710114494F, 0.5714931052F,
  155560. 0.5719746497F, 0.5724560822F, 0.5729374023F, 0.5734186094F,
  155561. 0.5738997029F, 0.5743806823F, 0.5748615470F, 0.5753422965F,
  155562. 0.5758229301F, 0.5763034475F, 0.5767838480F, 0.5772641310F,
  155563. 0.5777442960F, 0.5782243426F, 0.5787042700F, 0.5791840778F,
  155564. 0.5796637654F, 0.5801433322F, 0.5806227778F, 0.5811021016F,
  155565. 0.5815813029F, 0.5820603814F, 0.5825393363F, 0.5830181673F,
  155566. 0.5834968737F, 0.5839754549F, 0.5844539105F, 0.5849322399F,
  155567. 0.5854104425F, 0.5858885179F, 0.5863664653F, 0.5868442844F,
  155568. 0.5873219746F, 0.5877995353F, 0.5882769660F, 0.5887542661F,
  155569. 0.5892314351F, 0.5897084724F, 0.5901853776F, 0.5906621500F,
  155570. 0.5911387892F, 0.5916152945F, 0.5920916655F, 0.5925679016F,
  155571. 0.5930440022F, 0.5935199669F, 0.5939957950F, 0.5944714861F,
  155572. 0.5949470396F, 0.5954224550F, 0.5958977317F, 0.5963728692F,
  155573. 0.5968478669F, 0.5973227244F, 0.5977974411F, 0.5982720163F,
  155574. 0.5987464497F, 0.5992207407F, 0.5996948887F, 0.6001688932F,
  155575. 0.6006427537F, 0.6011164696F, 0.6015900405F, 0.6020634657F,
  155576. 0.6025367447F, 0.6030098770F, 0.6034828621F, 0.6039556995F,
  155577. 0.6044283885F, 0.6049009288F, 0.6053733196F, 0.6058455606F,
  155578. 0.6063176512F, 0.6067895909F, 0.6072613790F, 0.6077330152F,
  155579. 0.6082044989F, 0.6086758295F, 0.6091470065F, 0.6096180294F,
  155580. 0.6100888977F, 0.6105596108F, 0.6110301682F, 0.6115005694F,
  155581. 0.6119708139F, 0.6124409011F, 0.6129108305F, 0.6133806017F,
  155582. 0.6138502139F, 0.6143196669F, 0.6147889599F, 0.6152580926F,
  155583. 0.6157270643F, 0.6161958746F, 0.6166645230F, 0.6171330088F,
  155584. 0.6176013317F, 0.6180694910F, 0.6185374863F, 0.6190053171F,
  155585. 0.6194729827F, 0.6199404828F, 0.6204078167F, 0.6208749841F,
  155586. 0.6213419842F, 0.6218088168F, 0.6222754811F, 0.6227419768F,
  155587. 0.6232083032F, 0.6236744600F, 0.6241404465F, 0.6246062622F,
  155588. 0.6250719067F, 0.6255373795F, 0.6260026799F, 0.6264678076F,
  155589. 0.6269327619F, 0.6273975425F, 0.6278621487F, 0.6283265800F,
  155590. 0.6287908361F, 0.6292549163F, 0.6297188201F, 0.6301825471F,
  155591. 0.6306460966F, 0.6311094683F, 0.6315726617F, 0.6320356761F,
  155592. 0.6324985111F, 0.6329611662F, 0.6334236410F, 0.6338859348F,
  155593. 0.6343480472F, 0.6348099777F, 0.6352717257F, 0.6357332909F,
  155594. 0.6361946726F, 0.6366558704F, 0.6371168837F, 0.6375777122F,
  155595. 0.6380383552F, 0.6384988123F, 0.6389590830F, 0.6394191668F,
  155596. 0.6398790631F, 0.6403387716F, 0.6407982916F, 0.6412576228F,
  155597. 0.6417167645F, 0.6421757163F, 0.6426344778F, 0.6430930483F,
  155598. 0.6435514275F, 0.6440096149F, 0.6444676098F, 0.6449254119F,
  155599. 0.6453830207F, 0.6458404356F, 0.6462976562F, 0.6467546820F,
  155600. 0.6472115125F, 0.6476681472F, 0.6481245856F, 0.6485808273F,
  155601. 0.6490368717F, 0.6494927183F, 0.6499483667F, 0.6504038164F,
  155602. 0.6508590670F, 0.6513141178F, 0.6517689684F, 0.6522236185F,
  155603. 0.6526780673F, 0.6531323146F, 0.6535863598F, 0.6540402024F,
  155604. 0.6544938419F, 0.6549472779F, 0.6554005099F, 0.6558535373F,
  155605. 0.6563063598F, 0.6567589769F, 0.6572113880F, 0.6576635927F,
  155606. 0.6581155906F, 0.6585673810F, 0.6590189637F, 0.6594703380F,
  155607. 0.6599215035F, 0.6603724598F, 0.6608232064F, 0.6612737427F,
  155608. 0.6617240684F, 0.6621741829F, 0.6626240859F, 0.6630737767F,
  155609. 0.6635232550F, 0.6639725202F, 0.6644215720F, 0.6648704098F,
  155610. 0.6653190332F, 0.6657674417F, 0.6662156348F, 0.6666636121F,
  155611. 0.6671113731F, 0.6675589174F, 0.6680062445F, 0.6684533538F,
  155612. 0.6689002450F, 0.6693469177F, 0.6697933712F, 0.6702396052F,
  155613. 0.6706856193F, 0.6711314129F, 0.6715769855F, 0.6720223369F,
  155614. 0.6724674664F, 0.6729123736F, 0.6733570581F, 0.6738015194F,
  155615. 0.6742457570F, 0.6746897706F, 0.6751335596F, 0.6755771236F,
  155616. 0.6760204621F, 0.6764635747F, 0.6769064609F, 0.6773491204F,
  155617. 0.6777915525F, 0.6782337570F, 0.6786757332F, 0.6791174809F,
  155618. 0.6795589995F, 0.6800002886F, 0.6804413477F, 0.6808821765F,
  155619. 0.6813227743F, 0.6817631409F, 0.6822032758F, 0.6826431785F,
  155620. 0.6830828485F, 0.6835222855F, 0.6839614890F, 0.6844004585F,
  155621. 0.6848391936F, 0.6852776939F, 0.6857159589F, 0.6861539883F,
  155622. 0.6865917815F, 0.6870293381F, 0.6874666576F, 0.6879037398F,
  155623. 0.6883405840F, 0.6887771899F, 0.6892135571F, 0.6896496850F,
  155624. 0.6900855733F, 0.6905212216F, 0.6909566294F, 0.6913917963F,
  155625. 0.6918267218F, 0.6922614055F, 0.6926958471F, 0.6931300459F,
  155626. 0.6935640018F, 0.6939977141F, 0.6944311825F, 0.6948644066F,
  155627. 0.6952973859F, 0.6957301200F, 0.6961626085F, 0.6965948510F,
  155628. 0.6970268470F, 0.6974585961F, 0.6978900980F, 0.6983213521F,
  155629. 0.6987523580F, 0.6991831154F, 0.6996136238F, 0.7000438828F,
  155630. 0.7004738921F, 0.7009036510F, 0.7013331594F, 0.7017624166F,
  155631. 0.7021914224F, 0.7026201763F, 0.7030486779F, 0.7034769268F,
  155632. 0.7039049226F, 0.7043326648F, 0.7047601531F, 0.7051873870F,
  155633. 0.7056143662F, 0.7060410902F, 0.7064675586F, 0.7068937711F,
  155634. 0.7073197271F, 0.7077454264F, 0.7081708684F, 0.7085960529F,
  155635. 0.7090209793F, 0.7094456474F, 0.7098700566F, 0.7102942066F,
  155636. 0.7107180970F, 0.7111417274F, 0.7115650974F, 0.7119882066F,
  155637. 0.7124110545F, 0.7128336409F, 0.7132559653F, 0.7136780272F,
  155638. 0.7140998264F, 0.7145213624F, 0.7149426348F, 0.7153636433F,
  155639. 0.7157843874F, 0.7162048668F, 0.7166250810F, 0.7170450296F,
  155640. 0.7174647124F, 0.7178841289F, 0.7183032786F, 0.7187221613F,
  155641. 0.7191407765F, 0.7195591239F, 0.7199772030F, 0.7203950135F,
  155642. 0.7208125550F, 0.7212298271F, 0.7216468294F, 0.7220635616F,
  155643. 0.7224800233F, 0.7228962140F, 0.7233121335F, 0.7237277813F,
  155644. 0.7241431571F, 0.7245582604F, 0.7249730910F, 0.7253876484F,
  155645. 0.7258019322F, 0.7262159422F, 0.7266296778F, 0.7270431388F,
  155646. 0.7274563247F, 0.7278692353F, 0.7282818700F, 0.7286942287F,
  155647. 0.7291063108F, 0.7295181160F, 0.7299296440F, 0.7303408944F,
  155648. 0.7307518669F, 0.7311625609F, 0.7315729763F, 0.7319831126F,
  155649. 0.7323929695F, 0.7328025466F, 0.7332118435F, 0.7336208600F,
  155650. 0.7340295955F, 0.7344380499F, 0.7348462226F, 0.7352541134F,
  155651. 0.7356617220F, 0.7360690478F, 0.7364760907F, 0.7368828502F,
  155652. 0.7372893259F, 0.7376955176F, 0.7381014249F, 0.7385070475F,
  155653. 0.7389123849F, 0.7393174368F, 0.7397222029F, 0.7401266829F,
  155654. 0.7405308763F, 0.7409347829F, 0.7413384023F, 0.7417417341F,
  155655. 0.7421447780F, 0.7425475338F, 0.7429500009F, 0.7433521791F,
  155656. 0.7437540681F, 0.7441556674F, 0.7445569769F, 0.7449579960F,
  155657. 0.7453587245F, 0.7457591621F, 0.7461593084F, 0.7465591631F,
  155658. 0.7469587259F, 0.7473579963F, 0.7477569741F, 0.7481556590F,
  155659. 0.7485540506F, 0.7489521486F, 0.7493499526F, 0.7497474623F,
  155660. 0.7501446775F, 0.7505415977F, 0.7509382227F, 0.7513345521F,
  155661. 0.7517305856F, 0.7521263229F, 0.7525217636F, 0.7529169074F,
  155662. 0.7533117541F, 0.7537063032F, 0.7541005545F, 0.7544945076F,
  155663. 0.7548881623F, 0.7552815182F, 0.7556745749F, 0.7560673323F,
  155664. 0.7564597899F, 0.7568519474F, 0.7572438046F, 0.7576353611F,
  155665. 0.7580266166F, 0.7584175708F, 0.7588082235F, 0.7591985741F,
  155666. 0.7595886226F, 0.7599783685F, 0.7603678116F, 0.7607569515F,
  155667. 0.7611457879F, 0.7615343206F, 0.7619225493F, 0.7623104735F,
  155668. 0.7626980931F, 0.7630854078F, 0.7634724171F, 0.7638591209F,
  155669. 0.7642455188F, 0.7646316106F, 0.7650173959F, 0.7654028744F,
  155670. 0.7657880459F, 0.7661729100F, 0.7665574664F, 0.7669417150F,
  155671. 0.7673256553F, 0.7677092871F, 0.7680926100F, 0.7684756239F,
  155672. 0.7688583284F, 0.7692407232F, 0.7696228080F, 0.7700045826F,
  155673. 0.7703860467F, 0.7707671999F, 0.7711480420F, 0.7715285728F,
  155674. 0.7719087918F, 0.7722886989F, 0.7726682938F, 0.7730475762F,
  155675. 0.7734265458F, 0.7738052023F, 0.7741835454F, 0.7745615750F,
  155676. 0.7749392906F, 0.7753166921F, 0.7756937791F, 0.7760705514F,
  155677. 0.7764470087F, 0.7768231508F, 0.7771989773F, 0.7775744880F,
  155678. 0.7779496827F, 0.7783245610F, 0.7786991227F, 0.7790733676F,
  155679. 0.7794472953F, 0.7798209056F, 0.7801941982F, 0.7805671729F,
  155680. 0.7809398294F, 0.7813121675F, 0.7816841869F, 0.7820558873F,
  155681. 0.7824272684F, 0.7827983301F, 0.7831690720F, 0.7835394940F,
  155682. 0.7839095957F, 0.7842793768F, 0.7846488373F, 0.7850179767F,
  155683. 0.7853867948F, 0.7857552914F, 0.7861234663F, 0.7864913191F,
  155684. 0.7868588497F, 0.7872260578F, 0.7875929431F, 0.7879595055F,
  155685. 0.7883257445F, 0.7886916601F, 0.7890572520F, 0.7894225198F,
  155686. 0.7897874635F, 0.7901520827F, 0.7905163772F, 0.7908803468F,
  155687. 0.7912439912F, 0.7916073102F, 0.7919703035F, 0.7923329710F,
  155688. 0.7926953124F, 0.7930573274F, 0.7934190158F, 0.7937803774F,
  155689. 0.7941414120F, 0.7945021193F, 0.7948624991F, 0.7952225511F,
  155690. 0.7955822752F, 0.7959416711F, 0.7963007387F, 0.7966594775F,
  155691. 0.7970178875F, 0.7973759685F, 0.7977337201F, 0.7980911422F,
  155692. 0.7984482346F, 0.7988049970F, 0.7991614292F, 0.7995175310F,
  155693. 0.7998733022F, 0.8002287426F, 0.8005838519F, 0.8009386299F,
  155694. 0.8012930765F, 0.8016471914F, 0.8020009744F, 0.8023544253F,
  155695. 0.8027075438F, 0.8030603298F, 0.8034127831F, 0.8037649035F,
  155696. 0.8041166906F, 0.8044681445F, 0.8048192647F, 0.8051700512F,
  155697. 0.8055205038F, 0.8058706222F, 0.8062204062F, 0.8065698556F,
  155698. 0.8069189702F, 0.8072677499F, 0.8076161944F, 0.8079643036F,
  155699. 0.8083120772F, 0.8086595151F, 0.8090066170F, 0.8093533827F,
  155700. 0.8096998122F, 0.8100459051F, 0.8103916613F, 0.8107370806F,
  155701. 0.8110821628F, 0.8114269077F, 0.8117713151F, 0.8121153849F,
  155702. 0.8124591169F, 0.8128025108F, 0.8131455666F, 0.8134882839F,
  155703. 0.8138306627F, 0.8141727027F, 0.8145144038F, 0.8148557658F,
  155704. 0.8151967886F, 0.8155374718F, 0.8158778154F, 0.8162178192F,
  155705. 0.8165574830F, 0.8168968067F, 0.8172357900F, 0.8175744328F,
  155706. 0.8179127349F, 0.8182506962F, 0.8185883164F, 0.8189255955F,
  155707. 0.8192625332F, 0.8195991295F, 0.8199353840F, 0.8202712967F,
  155708. 0.8206068673F, 0.8209420958F, 0.8212769820F, 0.8216115256F,
  155709. 0.8219457266F, 0.8222795848F, 0.8226131000F, 0.8229462721F,
  155710. 0.8232791009F, 0.8236115863F, 0.8239437280F, 0.8242755260F,
  155711. 0.8246069801F, 0.8249380901F, 0.8252688559F, 0.8255992774F,
  155712. 0.8259293544F, 0.8262590867F, 0.8265884741F, 0.8269175167F,
  155713. 0.8272462141F, 0.8275745663F, 0.8279025732F, 0.8282302344F,
  155714. 0.8285575501F, 0.8288845199F, 0.8292111437F, 0.8295374215F,
  155715. 0.8298633530F, 0.8301889382F, 0.8305141768F, 0.8308390688F,
  155716. 0.8311636141F, 0.8314878124F, 0.8318116637F, 0.8321351678F,
  155717. 0.8324583246F, 0.8327811340F, 0.8331035957F, 0.8334257098F,
  155718. 0.8337474761F, 0.8340688944F, 0.8343899647F, 0.8347106867F,
  155719. 0.8350310605F, 0.8353510857F, 0.8356707624F, 0.8359900904F,
  155720. 0.8363090696F, 0.8366276999F, 0.8369459811F, 0.8372639131F,
  155721. 0.8375814958F, 0.8378987292F, 0.8382156130F, 0.8385321472F,
  155722. 0.8388483316F, 0.8391641662F, 0.8394796508F, 0.8397947853F,
  155723. 0.8401095697F, 0.8404240037F, 0.8407380873F, 0.8410518204F,
  155724. 0.8413652029F, 0.8416782347F, 0.8419909156F, 0.8423032456F,
  155725. 0.8426152245F, 0.8429268523F, 0.8432381289F, 0.8435490541F,
  155726. 0.8438596279F, 0.8441698502F, 0.8444797208F, 0.8447892396F,
  155727. 0.8450984067F, 0.8454072218F, 0.8457156849F, 0.8460237959F,
  155728. 0.8463315547F, 0.8466389612F, 0.8469460154F, 0.8472527170F,
  155729. 0.8475590661F, 0.8478650625F, 0.8481707063F, 0.8484759971F,
  155730. 0.8487809351F, 0.8490855201F, 0.8493897521F, 0.8496936308F,
  155731. 0.8499971564F, 0.8503003286F, 0.8506031474F, 0.8509056128F,
  155732. 0.8512077246F, 0.8515094828F, 0.8518108872F, 0.8521119379F,
  155733. 0.8524126348F, 0.8527129777F, 0.8530129666F, 0.8533126015F,
  155734. 0.8536118822F, 0.8539108087F, 0.8542093809F, 0.8545075988F,
  155735. 0.8548054623F, 0.8551029712F, 0.8554001257F, 0.8556969255F,
  155736. 0.8559933707F, 0.8562894611F, 0.8565851968F, 0.8568805775F,
  155737. 0.8571756034F, 0.8574702743F, 0.8577645902F, 0.8580585509F,
  155738. 0.8583521566F, 0.8586454070F, 0.8589383021F, 0.8592308420F,
  155739. 0.8595230265F, 0.8598148556F, 0.8601063292F, 0.8603974473F,
  155740. 0.8606882098F, 0.8609786167F, 0.8612686680F, 0.8615583636F,
  155741. 0.8618477034F, 0.8621366874F, 0.8624253156F, 0.8627135878F,
  155742. 0.8630015042F, 0.8632890646F, 0.8635762690F, 0.8638631173F,
  155743. 0.8641496096F, 0.8644357457F, 0.8647215257F, 0.8650069495F,
  155744. 0.8652920171F, 0.8655767283F, 0.8658610833F, 0.8661450820F,
  155745. 0.8664287243F, 0.8667120102F, 0.8669949397F, 0.8672775127F,
  155746. 0.8675597293F, 0.8678415894F, 0.8681230929F, 0.8684042398F,
  155747. 0.8686850302F, 0.8689654640F, 0.8692455412F, 0.8695252617F,
  155748. 0.8698046255F, 0.8700836327F, 0.8703622831F, 0.8706405768F,
  155749. 0.8709185138F, 0.8711960940F, 0.8714733174F, 0.8717501840F,
  155750. 0.8720266939F, 0.8723028469F, 0.8725786430F, 0.8728540824F,
  155751. 0.8731291648F, 0.8734038905F, 0.8736782592F, 0.8739522711F,
  155752. 0.8742259261F, 0.8744992242F, 0.8747721653F, 0.8750447496F,
  155753. 0.8753169770F, 0.8755888475F, 0.8758603611F, 0.8761315177F,
  155754. 0.8764023175F, 0.8766727603F, 0.8769428462F, 0.8772125752F,
  155755. 0.8774819474F, 0.8777509626F, 0.8780196209F, 0.8782879224F,
  155756. 0.8785558669F, 0.8788234546F, 0.8790906854F, 0.8793575594F,
  155757. 0.8796240765F, 0.8798902368F, 0.8801560403F, 0.8804214870F,
  155758. 0.8806865768F, 0.8809513099F, 0.8812156863F, 0.8814797059F,
  155759. 0.8817433687F, 0.8820066749F, 0.8822696243F, 0.8825322171F,
  155760. 0.8827944532F, 0.8830563327F, 0.8833178556F, 0.8835790219F,
  155761. 0.8838398316F, 0.8841002848F, 0.8843603815F, 0.8846201217F,
  155762. 0.8848795054F, 0.8851385327F, 0.8853972036F, 0.8856555182F,
  155763. 0.8859134764F, 0.8861710783F, 0.8864283239F, 0.8866852133F,
  155764. 0.8869417464F, 0.8871979234F, 0.8874537443F, 0.8877092090F,
  155765. 0.8879643177F, 0.8882190704F, 0.8884734671F, 0.8887275078F,
  155766. 0.8889811927F, 0.8892345216F, 0.8894874948F, 0.8897401122F,
  155767. 0.8899923738F, 0.8902442798F, 0.8904958301F, 0.8907470248F,
  155768. 0.8909978640F, 0.8912483477F, 0.8914984759F, 0.8917482487F,
  155769. 0.8919976662F, 0.8922467284F, 0.8924954353F, 0.8927437871F,
  155770. 0.8929917837F, 0.8932394252F, 0.8934867118F, 0.8937336433F,
  155771. 0.8939802199F, 0.8942264417F, 0.8944723087F, 0.8947178210F,
  155772. 0.8949629785F, 0.8952077815F, 0.8954522299F, 0.8956963239F,
  155773. 0.8959400634F, 0.8961834486F, 0.8964264795F, 0.8966691561F,
  155774. 0.8969114786F, 0.8971534470F, 0.8973950614F, 0.8976363219F,
  155775. 0.8978772284F, 0.8981177812F, 0.8983579802F, 0.8985978256F,
  155776. 0.8988373174F, 0.8990764556F, 0.8993152405F, 0.8995536720F,
  155777. 0.8997917502F, 0.9000294751F, 0.9002668470F, 0.9005038658F,
  155778. 0.9007405317F, 0.9009768446F, 0.9012128048F, 0.9014484123F,
  155779. 0.9016836671F, 0.9019185693F, 0.9021531191F, 0.9023873165F,
  155780. 0.9026211616F, 0.9028546546F, 0.9030877954F, 0.9033205841F,
  155781. 0.9035530210F, 0.9037851059F, 0.9040168392F, 0.9042482207F,
  155782. 0.9044792507F, 0.9047099293F, 0.9049402564F, 0.9051702323F,
  155783. 0.9053998569F, 0.9056291305F, 0.9058580531F, 0.9060866248F,
  155784. 0.9063148457F, 0.9065427159F, 0.9067702355F, 0.9069974046F,
  155785. 0.9072242233F, 0.9074506917F, 0.9076768100F, 0.9079025782F,
  155786. 0.9081279964F, 0.9083530647F, 0.9085777833F, 0.9088021523F,
  155787. 0.9090261717F, 0.9092498417F, 0.9094731623F, 0.9096961338F,
  155788. 0.9099187561F, 0.9101410295F, 0.9103629540F, 0.9105845297F,
  155789. 0.9108057568F, 0.9110266354F, 0.9112471656F, 0.9114673475F,
  155790. 0.9116871812F, 0.9119066668F, 0.9121258046F, 0.9123445945F,
  155791. 0.9125630367F, 0.9127811314F, 0.9129988786F, 0.9132162785F,
  155792. 0.9134333312F, 0.9136500368F, 0.9138663954F, 0.9140824073F,
  155793. 0.9142980724F, 0.9145133910F, 0.9147283632F, 0.9149429890F,
  155794. 0.9151572687F, 0.9153712023F, 0.9155847900F, 0.9157980319F,
  155795. 0.9160109282F, 0.9162234790F, 0.9164356844F, 0.9166475445F,
  155796. 0.9168590595F, 0.9170702296F, 0.9172810548F, 0.9174915354F,
  155797. 0.9177016714F, 0.9179114629F, 0.9181209102F, 0.9183300134F,
  155798. 0.9185387726F, 0.9187471879F, 0.9189552595F, 0.9191629876F,
  155799. 0.9193703723F, 0.9195774136F, 0.9197841119F, 0.9199904672F,
  155800. 0.9201964797F, 0.9204021495F, 0.9206074767F, 0.9208124616F,
  155801. 0.9210171043F, 0.9212214049F, 0.9214253636F, 0.9216289805F,
  155802. 0.9218322558F, 0.9220351896F, 0.9222377821F, 0.9224400335F,
  155803. 0.9226419439F, 0.9228435134F, 0.9230447423F, 0.9232456307F,
  155804. 0.9234461787F, 0.9236463865F, 0.9238462543F, 0.9240457822F,
  155805. 0.9242449704F, 0.9244438190F, 0.9246423282F, 0.9248404983F,
  155806. 0.9250383293F, 0.9252358214F, 0.9254329747F, 0.9256297896F,
  155807. 0.9258262660F, 0.9260224042F, 0.9262182044F, 0.9264136667F,
  155808. 0.9266087913F, 0.9268035783F, 0.9269980280F, 0.9271921405F,
  155809. 0.9273859160F, 0.9275793546F, 0.9277724566F, 0.9279652221F,
  155810. 0.9281576513F, 0.9283497443F, 0.9285415014F, 0.9287329227F,
  155811. 0.9289240084F, 0.9291147586F, 0.9293051737F, 0.9294952536F,
  155812. 0.9296849987F, 0.9298744091F, 0.9300634850F, 0.9302522266F,
  155813. 0.9304406340F, 0.9306287074F, 0.9308164471F, 0.9310038532F,
  155814. 0.9311909259F, 0.9313776654F, 0.9315640719F, 0.9317501455F,
  155815. 0.9319358865F, 0.9321212951F, 0.9323063713F, 0.9324911155F,
  155816. 0.9326755279F, 0.9328596085F, 0.9330433577F, 0.9332267756F,
  155817. 0.9334098623F, 0.9335926182F, 0.9337750434F, 0.9339571380F,
  155818. 0.9341389023F, 0.9343203366F, 0.9345014409F, 0.9346822155F,
  155819. 0.9348626606F, 0.9350427763F, 0.9352225630F, 0.9354020207F,
  155820. 0.9355811498F, 0.9357599503F, 0.9359384226F, 0.9361165667F,
  155821. 0.9362943830F, 0.9364718716F, 0.9366490327F, 0.9368258666F,
  155822. 0.9370023733F, 0.9371785533F, 0.9373544066F, 0.9375299335F,
  155823. 0.9377051341F, 0.9378800087F, 0.9380545576F, 0.9382287809F,
  155824. 0.9384026787F, 0.9385762515F, 0.9387494993F, 0.9389224223F,
  155825. 0.9390950209F, 0.9392672951F, 0.9394392453F, 0.9396108716F,
  155826. 0.9397821743F, 0.9399531536F, 0.9401238096F, 0.9402941427F,
  155827. 0.9404641530F, 0.9406338407F, 0.9408032061F, 0.9409722495F,
  155828. 0.9411409709F, 0.9413093707F, 0.9414774491F, 0.9416452062F,
  155829. 0.9418126424F, 0.9419797579F, 0.9421465528F, 0.9423130274F,
  155830. 0.9424791819F, 0.9426450166F, 0.9428105317F, 0.9429757274F,
  155831. 0.9431406039F, 0.9433051616F, 0.9434694005F, 0.9436333209F,
  155832. 0.9437969232F, 0.9439602074F, 0.9441231739F, 0.9442858229F,
  155833. 0.9444481545F, 0.9446101691F, 0.9447718669F, 0.9449332481F,
  155834. 0.9450943129F, 0.9452550617F, 0.9454154945F, 0.9455756118F,
  155835. 0.9457354136F, 0.9458949003F, 0.9460540721F, 0.9462129292F,
  155836. 0.9463714719F, 0.9465297003F, 0.9466876149F, 0.9468452157F,
  155837. 0.9470025031F, 0.9471594772F, 0.9473161384F, 0.9474724869F,
  155838. 0.9476285229F, 0.9477842466F, 0.9479396584F, 0.9480947585F,
  155839. 0.9482495470F, 0.9484040243F, 0.9485581906F, 0.9487120462F,
  155840. 0.9488655913F, 0.9490188262F, 0.9491717511F, 0.9493243662F,
  155841. 0.9494766718F, 0.9496286683F, 0.9497803557F, 0.9499317345F,
  155842. 0.9500828047F, 0.9502335668F, 0.9503840209F, 0.9505341673F,
  155843. 0.9506840062F, 0.9508335380F, 0.9509827629F, 0.9511316810F,
  155844. 0.9512802928F, 0.9514285984F, 0.9515765982F, 0.9517242923F,
  155845. 0.9518716810F, 0.9520187646F, 0.9521655434F, 0.9523120176F,
  155846. 0.9524581875F, 0.9526040534F, 0.9527496154F, 0.9528948739F,
  155847. 0.9530398292F, 0.9531844814F, 0.9533288310F, 0.9534728780F,
  155848. 0.9536166229F, 0.9537600659F, 0.9539032071F, 0.9540460470F,
  155849. 0.9541885858F, 0.9543308237F, 0.9544727611F, 0.9546143981F,
  155850. 0.9547557351F, 0.9548967723F, 0.9550375100F, 0.9551779485F,
  155851. 0.9553180881F, 0.9554579290F, 0.9555974714F, 0.9557367158F,
  155852. 0.9558756623F, 0.9560143112F, 0.9561526628F, 0.9562907174F,
  155853. 0.9564284752F, 0.9565659366F, 0.9567031017F, 0.9568399710F,
  155854. 0.9569765446F, 0.9571128229F, 0.9572488061F, 0.9573844944F,
  155855. 0.9575198883F, 0.9576549879F, 0.9577897936F, 0.9579243056F,
  155856. 0.9580585242F, 0.9581924497F, 0.9583260824F, 0.9584594226F,
  155857. 0.9585924705F, 0.9587252264F, 0.9588576906F, 0.9589898634F,
  155858. 0.9591217452F, 0.9592533360F, 0.9593846364F, 0.9595156465F,
  155859. 0.9596463666F, 0.9597767971F, 0.9599069382F, 0.9600367901F,
  155860. 0.9601663533F, 0.9602956279F, 0.9604246143F, 0.9605533128F,
  155861. 0.9606817236F, 0.9608098471F, 0.9609376835F, 0.9610652332F,
  155862. 0.9611924963F, 0.9613194733F, 0.9614461644F, 0.9615725699F,
  155863. 0.9616986901F, 0.9618245253F, 0.9619500757F, 0.9620753418F,
  155864. 0.9622003238F, 0.9623250219F, 0.9624494365F, 0.9625735679F,
  155865. 0.9626974163F, 0.9628209821F, 0.9629442656F, 0.9630672671F,
  155866. 0.9631899868F, 0.9633124251F, 0.9634345822F, 0.9635564585F,
  155867. 0.9636780543F, 0.9637993699F, 0.9639204056F, 0.9640411616F,
  155868. 0.9641616383F, 0.9642818359F, 0.9644017549F, 0.9645213955F,
  155869. 0.9646407579F, 0.9647598426F, 0.9648786497F, 0.9649971797F,
  155870. 0.9651154328F, 0.9652334092F, 0.9653511095F, 0.9654685337F,
  155871. 0.9655856823F, 0.9657025556F, 0.9658191538F, 0.9659354773F,
  155872. 0.9660515263F, 0.9661673013F, 0.9662828024F, 0.9663980300F,
  155873. 0.9665129845F, 0.9666276660F, 0.9667420750F, 0.9668562118F,
  155874. 0.9669700766F, 0.9670836698F, 0.9671969917F, 0.9673100425F,
  155875. 0.9674228227F, 0.9675353325F, 0.9676475722F, 0.9677595422F,
  155876. 0.9678712428F, 0.9679826742F, 0.9680938368F, 0.9682047309F,
  155877. 0.9683153569F, 0.9684257150F, 0.9685358056F, 0.9686456289F,
  155878. 0.9687551853F, 0.9688644752F, 0.9689734987F, 0.9690822564F,
  155879. 0.9691907483F, 0.9692989750F, 0.9694069367F, 0.9695146337F,
  155880. 0.9696220663F, 0.9697292349F, 0.9698361398F, 0.9699427813F,
  155881. 0.9700491597F, 0.9701552754F, 0.9702611286F, 0.9703667197F,
  155882. 0.9704720490F, 0.9705771169F, 0.9706819236F, 0.9707864695F,
  155883. 0.9708907549F, 0.9709947802F, 0.9710985456F, 0.9712020514F,
  155884. 0.9713052981F, 0.9714082859F, 0.9715110151F, 0.9716134862F,
  155885. 0.9717156993F, 0.9718176549F, 0.9719193532F, 0.9720207946F,
  155886. 0.9721219794F, 0.9722229080F, 0.9723235806F, 0.9724239976F,
  155887. 0.9725241593F, 0.9726240661F, 0.9727237183F, 0.9728231161F,
  155888. 0.9729222601F, 0.9730211503F, 0.9731197873F, 0.9732181713F,
  155889. 0.9733163027F, 0.9734141817F, 0.9735118088F, 0.9736091842F,
  155890. 0.9737063083F, 0.9738031814F, 0.9738998039F, 0.9739961760F,
  155891. 0.9740922981F, 0.9741881706F, 0.9742837938F, 0.9743791680F,
  155892. 0.9744742935F, 0.9745691707F, 0.9746637999F, 0.9747581814F,
  155893. 0.9748523157F, 0.9749462029F, 0.9750398435F, 0.9751332378F,
  155894. 0.9752263861F, 0.9753192887F, 0.9754119461F, 0.9755043585F,
  155895. 0.9755965262F, 0.9756884496F, 0.9757801291F, 0.9758715650F,
  155896. 0.9759627575F, 0.9760537071F, 0.9761444141F, 0.9762348789F,
  155897. 0.9763251016F, 0.9764150828F, 0.9765048228F, 0.9765943218F,
  155898. 0.9766835802F, 0.9767725984F, 0.9768613767F, 0.9769499154F,
  155899. 0.9770382149F, 0.9771262755F, 0.9772140976F, 0.9773016815F,
  155900. 0.9773890275F, 0.9774761360F, 0.9775630073F, 0.9776496418F,
  155901. 0.9777360398F, 0.9778222016F, 0.9779081277F, 0.9779938182F,
  155902. 0.9780792736F, 0.9781644943F, 0.9782494805F, 0.9783342326F,
  155903. 0.9784187509F, 0.9785030359F, 0.9785870877F, 0.9786709069F,
  155904. 0.9787544936F, 0.9788378484F, 0.9789209714F, 0.9790038631F,
  155905. 0.9790865238F, 0.9791689538F, 0.9792511535F, 0.9793331232F,
  155906. 0.9794148633F, 0.9794963742F, 0.9795776561F, 0.9796587094F,
  155907. 0.9797395345F, 0.9798201316F, 0.9799005013F, 0.9799806437F,
  155908. 0.9800605593F, 0.9801402483F, 0.9802197112F, 0.9802989483F,
  155909. 0.9803779600F, 0.9804567465F, 0.9805353082F, 0.9806136455F,
  155910. 0.9806917587F, 0.9807696482F, 0.9808473143F, 0.9809247574F,
  155911. 0.9810019778F, 0.9810789759F, 0.9811557519F, 0.9812323064F,
  155912. 0.9813086395F, 0.9813847517F, 0.9814606433F, 0.9815363147F,
  155913. 0.9816117662F, 0.9816869981F, 0.9817620108F, 0.9818368047F,
  155914. 0.9819113801F, 0.9819857374F, 0.9820598769F, 0.9821337989F,
  155915. 0.9822075038F, 0.9822809920F, 0.9823542638F, 0.9824273195F,
  155916. 0.9825001596F, 0.9825727843F, 0.9826451940F, 0.9827173891F,
  155917. 0.9827893700F, 0.9828611368F, 0.9829326901F, 0.9830040302F,
  155918. 0.9830751574F, 0.9831460720F, 0.9832167745F, 0.9832872652F,
  155919. 0.9833575444F, 0.9834276124F, 0.9834974697F, 0.9835671166F,
  155920. 0.9836365535F, 0.9837057806F, 0.9837747983F, 0.9838436071F,
  155921. 0.9839122072F, 0.9839805990F, 0.9840487829F, 0.9841167591F,
  155922. 0.9841845282F, 0.9842520903F, 0.9843194459F, 0.9843865953F,
  155923. 0.9844535389F, 0.9845202771F, 0.9845868101F, 0.9846531383F,
  155924. 0.9847192622F, 0.9847851820F, 0.9848508980F, 0.9849164108F,
  155925. 0.9849817205F, 0.9850468276F, 0.9851117324F, 0.9851764352F,
  155926. 0.9852409365F, 0.9853052366F, 0.9853693358F, 0.9854332344F,
  155927. 0.9854969330F, 0.9855604317F, 0.9856237309F, 0.9856868310F,
  155928. 0.9857497325F, 0.9858124355F, 0.9858749404F, 0.9859372477F,
  155929. 0.9859993577F, 0.9860612707F, 0.9861229871F, 0.9861845072F,
  155930. 0.9862458315F, 0.9863069601F, 0.9863678936F, 0.9864286322F,
  155931. 0.9864891764F, 0.9865495264F, 0.9866096826F, 0.9866696454F,
  155932. 0.9867294152F, 0.9867889922F, 0.9868483769F, 0.9869075695F,
  155933. 0.9869665706F, 0.9870253803F, 0.9870839991F, 0.9871424273F,
  155934. 0.9872006653F, 0.9872587135F, 0.9873165721F, 0.9873742415F,
  155935. 0.9874317222F, 0.9874890144F, 0.9875461185F, 0.9876030348F,
  155936. 0.9876597638F, 0.9877163057F, 0.9877726610F, 0.9878288300F,
  155937. 0.9878848130F, 0.9879406104F, 0.9879962225F, 0.9880516497F,
  155938. 0.9881068924F, 0.9881619509F, 0.9882168256F, 0.9882715168F,
  155939. 0.9883260249F, 0.9883803502F, 0.9884344931F, 0.9884884539F,
  155940. 0.9885422331F, 0.9885958309F, 0.9886492477F, 0.9887024838F,
  155941. 0.9887555397F, 0.9888084157F, 0.9888611120F, 0.9889136292F,
  155942. 0.9889659675F, 0.9890181273F, 0.9890701089F, 0.9891219128F,
  155943. 0.9891735392F, 0.9892249885F, 0.9892762610F, 0.9893273572F,
  155944. 0.9893782774F, 0.9894290219F, 0.9894795911F, 0.9895299853F,
  155945. 0.9895802049F, 0.9896302502F, 0.9896801217F, 0.9897298196F,
  155946. 0.9897793443F, 0.9898286961F, 0.9898778755F, 0.9899268828F,
  155947. 0.9899757183F, 0.9900243823F, 0.9900728753F, 0.9901211976F,
  155948. 0.9901693495F, 0.9902173314F, 0.9902651436F, 0.9903127865F,
  155949. 0.9903602605F, 0.9904075659F, 0.9904547031F, 0.9905016723F,
  155950. 0.9905484740F, 0.9905951086F, 0.9906415763F, 0.9906878775F,
  155951. 0.9907340126F, 0.9907799819F, 0.9908257858F, 0.9908714247F,
  155952. 0.9909168988F, 0.9909622086F, 0.9910073543F, 0.9910523364F,
  155953. 0.9910971552F, 0.9911418110F, 0.9911863042F, 0.9912306351F,
  155954. 0.9912748042F, 0.9913188117F, 0.9913626580F, 0.9914063435F,
  155955. 0.9914498684F, 0.9914932333F, 0.9915364383F, 0.9915794839F,
  155956. 0.9916223703F, 0.9916650981F, 0.9917076674F, 0.9917500787F,
  155957. 0.9917923323F, 0.9918344286F, 0.9918763679F, 0.9919181505F,
  155958. 0.9919597769F, 0.9920012473F, 0.9920425621F, 0.9920837217F,
  155959. 0.9921247263F, 0.9921655765F, 0.9922062724F, 0.9922468145F,
  155960. 0.9922872030F, 0.9923274385F, 0.9923675211F, 0.9924074513F,
  155961. 0.9924472294F, 0.9924868557F, 0.9925263306F, 0.9925656544F,
  155962. 0.9926048275F, 0.9926438503F, 0.9926827230F, 0.9927214461F,
  155963. 0.9927600199F, 0.9927984446F, 0.9928367208F, 0.9928748486F,
  155964. 0.9929128285F, 0.9929506608F, 0.9929883459F, 0.9930258841F,
  155965. 0.9930632757F, 0.9931005211F, 0.9931376207F, 0.9931745747F,
  155966. 0.9932113836F, 0.9932480476F, 0.9932845671F, 0.9933209425F,
  155967. 0.9933571742F, 0.9933932623F, 0.9934292074F, 0.9934650097F,
  155968. 0.9935006696F, 0.9935361874F, 0.9935715635F, 0.9936067982F,
  155969. 0.9936418919F, 0.9936768448F, 0.9937116574F, 0.9937463300F,
  155970. 0.9937808629F, 0.9938152565F, 0.9938495111F, 0.9938836271F,
  155971. 0.9939176047F, 0.9939514444F, 0.9939851465F, 0.9940187112F,
  155972. 0.9940521391F, 0.9940854303F, 0.9941185853F, 0.9941516044F,
  155973. 0.9941844879F, 0.9942172361F, 0.9942498495F, 0.9942823283F,
  155974. 0.9943146729F, 0.9943468836F, 0.9943789608F, 0.9944109047F,
  155975. 0.9944427158F, 0.9944743944F, 0.9945059408F, 0.9945373553F,
  155976. 0.9945686384F, 0.9945997902F, 0.9946308112F, 0.9946617017F,
  155977. 0.9946924621F, 0.9947230926F, 0.9947535937F, 0.9947839656F,
  155978. 0.9948142086F, 0.9948443232F, 0.9948743097F, 0.9949041683F,
  155979. 0.9949338995F, 0.9949635035F, 0.9949929807F, 0.9950223315F,
  155980. 0.9950515561F, 0.9950806549F, 0.9951096282F, 0.9951384764F,
  155981. 0.9951671998F, 0.9951957987F, 0.9952242735F, 0.9952526245F,
  155982. 0.9952808520F, 0.9953089564F, 0.9953369380F, 0.9953647971F,
  155983. 0.9953925340F, 0.9954201491F, 0.9954476428F, 0.9954750153F,
  155984. 0.9955022670F, 0.9955293981F, 0.9955564092F, 0.9955833003F,
  155985. 0.9956100720F, 0.9956367245F, 0.9956632582F, 0.9956896733F,
  155986. 0.9957159703F, 0.9957421494F, 0.9957682110F, 0.9957941553F,
  155987. 0.9958199828F, 0.9958456937F, 0.9958712884F, 0.9958967672F,
  155988. 0.9959221305F, 0.9959473784F, 0.9959725115F, 0.9959975300F,
  155989. 0.9960224342F, 0.9960472244F, 0.9960719011F, 0.9960964644F,
  155990. 0.9961209148F, 0.9961452525F, 0.9961694779F, 0.9961935913F,
  155991. 0.9962175930F, 0.9962414834F, 0.9962652627F, 0.9962889313F,
  155992. 0.9963124895F, 0.9963359377F, 0.9963592761F, 0.9963825051F,
  155993. 0.9964056250F, 0.9964286361F, 0.9964515387F, 0.9964743332F,
  155994. 0.9964970198F, 0.9965195990F, 0.9965420709F, 0.9965644360F,
  155995. 0.9965866946F, 0.9966088469F, 0.9966308932F, 0.9966528340F,
  155996. 0.9966746695F, 0.9966964001F, 0.9967180260F, 0.9967395475F,
  155997. 0.9967609651F, 0.9967822789F, 0.9968034894F, 0.9968245968F,
  155998. 0.9968456014F, 0.9968665036F, 0.9968873037F, 0.9969080019F,
  155999. 0.9969285987F, 0.9969490942F, 0.9969694889F, 0.9969897830F,
  156000. 0.9970099769F, 0.9970300708F, 0.9970500651F, 0.9970699601F,
  156001. 0.9970897561F, 0.9971094533F, 0.9971290522F, 0.9971485531F,
  156002. 0.9971679561F, 0.9971872617F, 0.9972064702F, 0.9972255818F,
  156003. 0.9972445968F, 0.9972635157F, 0.9972823386F, 0.9973010659F,
  156004. 0.9973196980F, 0.9973382350F, 0.9973566773F, 0.9973750253F,
  156005. 0.9973932791F, 0.9974114392F, 0.9974295059F, 0.9974474793F,
  156006. 0.9974653599F, 0.9974831480F, 0.9975008438F, 0.9975184476F,
  156007. 0.9975359598F, 0.9975533806F, 0.9975707104F, 0.9975879495F,
  156008. 0.9976050981F, 0.9976221566F, 0.9976391252F, 0.9976560043F,
  156009. 0.9976727941F, 0.9976894950F, 0.9977061073F, 0.9977226312F,
  156010. 0.9977390671F, 0.9977554152F, 0.9977716759F, 0.9977878495F,
  156011. 0.9978039361F, 0.9978199363F, 0.9978358501F, 0.9978516780F,
  156012. 0.9978674202F, 0.9978830771F, 0.9978986488F, 0.9979141358F,
  156013. 0.9979295383F, 0.9979448566F, 0.9979600909F, 0.9979752417F,
  156014. 0.9979903091F, 0.9980052936F, 0.9980201952F, 0.9980350145F,
  156015. 0.9980497515F, 0.9980644067F, 0.9980789804F, 0.9980934727F,
  156016. 0.9981078841F, 0.9981222147F, 0.9981364649F, 0.9981506350F,
  156017. 0.9981647253F, 0.9981787360F, 0.9981926674F, 0.9982065199F,
  156018. 0.9982202936F, 0.9982339890F, 0.9982476062F, 0.9982611456F,
  156019. 0.9982746074F, 0.9982879920F, 0.9983012996F, 0.9983145304F,
  156020. 0.9983276849F, 0.9983407632F, 0.9983537657F, 0.9983666926F,
  156021. 0.9983795442F, 0.9983923208F, 0.9984050226F, 0.9984176501F,
  156022. 0.9984302033F, 0.9984426827F, 0.9984550884F, 0.9984674208F,
  156023. 0.9984796802F, 0.9984918667F, 0.9985039808F, 0.9985160227F,
  156024. 0.9985279926F, 0.9985398909F, 0.9985517177F, 0.9985634734F,
  156025. 0.9985751583F, 0.9985867727F, 0.9985983167F, 0.9986097907F,
  156026. 0.9986211949F, 0.9986325297F, 0.9986437953F, 0.9986549919F,
  156027. 0.9986661199F, 0.9986771795F, 0.9986881710F, 0.9986990946F,
  156028. 0.9987099507F, 0.9987207394F, 0.9987314611F, 0.9987421161F,
  156029. 0.9987527045F, 0.9987632267F, 0.9987736829F, 0.9987840734F,
  156030. 0.9987943985F, 0.9988046584F, 0.9988148534F, 0.9988249838F,
  156031. 0.9988350498F, 0.9988450516F, 0.9988549897F, 0.9988648641F,
  156032. 0.9988746753F, 0.9988844233F, 0.9988941086F, 0.9989037313F,
  156033. 0.9989132918F, 0.9989227902F, 0.9989322269F, 0.9989416021F,
  156034. 0.9989509160F, 0.9989601690F, 0.9989693613F, 0.9989784931F,
  156035. 0.9989875647F, 0.9989965763F, 0.9990055283F, 0.9990144208F,
  156036. 0.9990232541F, 0.9990320286F, 0.9990407443F, 0.9990494016F,
  156037. 0.9990580008F, 0.9990665421F, 0.9990750257F, 0.9990834519F,
  156038. 0.9990918209F, 0.9991001331F, 0.9991083886F, 0.9991165877F,
  156039. 0.9991247307F, 0.9991328177F, 0.9991408491F, 0.9991488251F,
  156040. 0.9991567460F, 0.9991646119F, 0.9991724232F, 0.9991801801F,
  156041. 0.9991878828F, 0.9991955316F, 0.9992031267F, 0.9992106684F,
  156042. 0.9992181569F, 0.9992255925F, 0.9992329753F, 0.9992403057F,
  156043. 0.9992475839F, 0.9992548101F, 0.9992619846F, 0.9992691076F,
  156044. 0.9992761793F, 0.9992832001F, 0.9992901701F, 0.9992970895F,
  156045. 0.9993039587F, 0.9993107777F, 0.9993175470F, 0.9993242667F,
  156046. 0.9993309371F, 0.9993375583F, 0.9993441307F, 0.9993506545F,
  156047. 0.9993571298F, 0.9993635570F, 0.9993699362F, 0.9993762678F,
  156048. 0.9993825519F, 0.9993887887F, 0.9993949785F, 0.9994011216F,
  156049. 0.9994072181F, 0.9994132683F, 0.9994192725F, 0.9994252307F,
  156050. 0.9994311434F, 0.9994370107F, 0.9994428327F, 0.9994486099F,
  156051. 0.9994543423F, 0.9994600303F, 0.9994656739F, 0.9994712736F,
  156052. 0.9994768294F, 0.9994823417F, 0.9994878105F, 0.9994932363F,
  156053. 0.9994986191F, 0.9995039592F, 0.9995092568F, 0.9995145122F,
  156054. 0.9995197256F, 0.9995248971F, 0.9995300270F, 0.9995351156F,
  156055. 0.9995401630F, 0.9995451695F, 0.9995501352F, 0.9995550604F,
  156056. 0.9995599454F, 0.9995647903F, 0.9995695953F, 0.9995743607F,
  156057. 0.9995790866F, 0.9995837734F, 0.9995884211F, 0.9995930300F,
  156058. 0.9995976004F, 0.9996021324F, 0.9996066263F, 0.9996110822F,
  156059. 0.9996155004F, 0.9996198810F, 0.9996242244F, 0.9996285306F,
  156060. 0.9996327999F, 0.9996370326F, 0.9996412287F, 0.9996453886F,
  156061. 0.9996495125F, 0.9996536004F, 0.9996576527F, 0.9996616696F,
  156062. 0.9996656512F, 0.9996695977F, 0.9996735094F, 0.9996773865F,
  156063. 0.9996812291F, 0.9996850374F, 0.9996888118F, 0.9996925523F,
  156064. 0.9996962591F, 0.9996999325F, 0.9997035727F, 0.9997071798F,
  156065. 0.9997107541F, 0.9997142957F, 0.9997178049F, 0.9997212818F,
  156066. 0.9997247266F, 0.9997281396F, 0.9997315209F, 0.9997348708F,
  156067. 0.9997381893F, 0.9997414767F, 0.9997447333F, 0.9997479591F,
  156068. 0.9997511544F, 0.9997543194F, 0.9997574542F, 0.9997605591F,
  156069. 0.9997636342F, 0.9997666797F, 0.9997696958F, 0.9997726828F,
  156070. 0.9997756407F, 0.9997785698F, 0.9997814703F, 0.9997843423F,
  156071. 0.9997871860F, 0.9997900016F, 0.9997927894F, 0.9997955494F,
  156072. 0.9997982818F, 0.9998009869F, 0.9998036648F, 0.9998063157F,
  156073. 0.9998089398F, 0.9998115373F, 0.9998141082F, 0.9998166529F,
  156074. 0.9998191715F, 0.9998216642F, 0.9998241311F, 0.9998265724F,
  156075. 0.9998289884F, 0.9998313790F, 0.9998337447F, 0.9998360854F,
  156076. 0.9998384015F, 0.9998406930F, 0.9998429602F, 0.9998452031F,
  156077. 0.9998474221F, 0.9998496171F, 0.9998517885F, 0.9998539364F,
  156078. 0.9998560610F, 0.9998581624F, 0.9998602407F, 0.9998622962F,
  156079. 0.9998643291F, 0.9998663394F, 0.9998683274F, 0.9998702932F,
  156080. 0.9998722370F, 0.9998741589F, 0.9998760591F, 0.9998779378F,
  156081. 0.9998797952F, 0.9998816313F, 0.9998834464F, 0.9998852406F,
  156082. 0.9998870141F, 0.9998887670F, 0.9998904995F, 0.9998922117F,
  156083. 0.9998939039F, 0.9998955761F, 0.9998972285F, 0.9998988613F,
  156084. 0.9999004746F, 0.9999020686F, 0.9999036434F, 0.9999051992F,
  156085. 0.9999067362F, 0.9999082544F, 0.9999097541F, 0.9999112354F,
  156086. 0.9999126984F, 0.9999141433F, 0.9999155703F, 0.9999169794F,
  156087. 0.9999183709F, 0.9999197449F, 0.9999211014F, 0.9999224408F,
  156088. 0.9999237631F, 0.9999250684F, 0.9999263570F, 0.9999276289F,
  156089. 0.9999288843F, 0.9999301233F, 0.9999313461F, 0.9999325529F,
  156090. 0.9999337437F, 0.9999349187F, 0.9999360780F, 0.9999372218F,
  156091. 0.9999383503F, 0.9999394635F, 0.9999405616F, 0.9999416447F,
  156092. 0.9999427129F, 0.9999437665F, 0.9999448055F, 0.9999458301F,
  156093. 0.9999468404F, 0.9999478365F, 0.9999488185F, 0.9999497867F,
  156094. 0.9999507411F, 0.9999516819F, 0.9999526091F, 0.9999535230F,
  156095. 0.9999544236F, 0.9999553111F, 0.9999561856F, 0.9999570472F,
  156096. 0.9999578960F, 0.9999587323F, 0.9999595560F, 0.9999603674F,
  156097. 0.9999611666F, 0.9999619536F, 0.9999627286F, 0.9999634917F,
  156098. 0.9999642431F, 0.9999649828F, 0.9999657110F, 0.9999664278F,
  156099. 0.9999671334F, 0.9999678278F, 0.9999685111F, 0.9999691835F,
  156100. 0.9999698451F, 0.9999704960F, 0.9999711364F, 0.9999717662F,
  156101. 0.9999723858F, 0.9999729950F, 0.9999735942F, 0.9999741834F,
  156102. 0.9999747626F, 0.9999753321F, 0.9999758919F, 0.9999764421F,
  156103. 0.9999769828F, 0.9999775143F, 0.9999780364F, 0.9999785495F,
  156104. 0.9999790535F, 0.9999795485F, 0.9999800348F, 0.9999805124F,
  156105. 0.9999809813F, 0.9999814417F, 0.9999818938F, 0.9999823375F,
  156106. 0.9999827731F, 0.9999832005F, 0.9999836200F, 0.9999840316F,
  156107. 0.9999844353F, 0.9999848314F, 0.9999852199F, 0.9999856008F,
  156108. 0.9999859744F, 0.9999863407F, 0.9999866997F, 0.9999870516F,
  156109. 0.9999873965F, 0.9999877345F, 0.9999880656F, 0.9999883900F,
  156110. 0.9999887078F, 0.9999890190F, 0.9999893237F, 0.9999896220F,
  156111. 0.9999899140F, 0.9999901999F, 0.9999904796F, 0.9999907533F,
  156112. 0.9999910211F, 0.9999912830F, 0.9999915391F, 0.9999917896F,
  156113. 0.9999920345F, 0.9999922738F, 0.9999925077F, 0.9999927363F,
  156114. 0.9999929596F, 0.9999931777F, 0.9999933907F, 0.9999935987F,
  156115. 0.9999938018F, 0.9999940000F, 0.9999941934F, 0.9999943820F,
  156116. 0.9999945661F, 0.9999947456F, 0.9999949206F, 0.9999950912F,
  156117. 0.9999952575F, 0.9999954195F, 0.9999955773F, 0.9999957311F,
  156118. 0.9999958807F, 0.9999960265F, 0.9999961683F, 0.9999963063F,
  156119. 0.9999964405F, 0.9999965710F, 0.9999966979F, 0.9999968213F,
  156120. 0.9999969412F, 0.9999970576F, 0.9999971707F, 0.9999972805F,
  156121. 0.9999973871F, 0.9999974905F, 0.9999975909F, 0.9999976881F,
  156122. 0.9999977824F, 0.9999978738F, 0.9999979624F, 0.9999980481F,
  156123. 0.9999981311F, 0.9999982115F, 0.9999982892F, 0.9999983644F,
  156124. 0.9999984370F, 0.9999985072F, 0.9999985750F, 0.9999986405F,
  156125. 0.9999987037F, 0.9999987647F, 0.9999988235F, 0.9999988802F,
  156126. 0.9999989348F, 0.9999989873F, 0.9999990379F, 0.9999990866F,
  156127. 0.9999991334F, 0.9999991784F, 0.9999992217F, 0.9999992632F,
  156128. 0.9999993030F, 0.9999993411F, 0.9999993777F, 0.9999994128F,
  156129. 0.9999994463F, 0.9999994784F, 0.9999995091F, 0.9999995384F,
  156130. 0.9999995663F, 0.9999995930F, 0.9999996184F, 0.9999996426F,
  156131. 0.9999996657F, 0.9999996876F, 0.9999997084F, 0.9999997282F,
  156132. 0.9999997469F, 0.9999997647F, 0.9999997815F, 0.9999997973F,
  156133. 0.9999998123F, 0.9999998265F, 0.9999998398F, 0.9999998524F,
  156134. 0.9999998642F, 0.9999998753F, 0.9999998857F, 0.9999998954F,
  156135. 0.9999999045F, 0.9999999130F, 0.9999999209F, 0.9999999282F,
  156136. 0.9999999351F, 0.9999999414F, 0.9999999472F, 0.9999999526F,
  156137. 0.9999999576F, 0.9999999622F, 0.9999999664F, 0.9999999702F,
  156138. 0.9999999737F, 0.9999999769F, 0.9999999798F, 0.9999999824F,
  156139. 0.9999999847F, 0.9999999868F, 0.9999999887F, 0.9999999904F,
  156140. 0.9999999919F, 0.9999999932F, 0.9999999943F, 0.9999999953F,
  156141. 0.9999999961F, 0.9999999969F, 0.9999999975F, 0.9999999980F,
  156142. 0.9999999985F, 0.9999999988F, 0.9999999991F, 0.9999999993F,
  156143. 0.9999999995F, 0.9999999997F, 0.9999999998F, 0.9999999999F,
  156144. 0.9999999999F, 1.0000000000F, 1.0000000000F, 1.0000000000F,
  156145. 1.0000000000F, 1.0000000000F, 1.0000000000F, 1.0000000000F,
  156146. };
  156147. static float *vwin[8] = {
  156148. vwin64,
  156149. vwin128,
  156150. vwin256,
  156151. vwin512,
  156152. vwin1024,
  156153. vwin2048,
  156154. vwin4096,
  156155. vwin8192,
  156156. };
  156157. float *_vorbis_window_get(int n){
  156158. return vwin[n];
  156159. }
  156160. void _vorbis_apply_window(float *d,int *winno,long *blocksizes,
  156161. int lW,int W,int nW){
  156162. lW=(W?lW:0);
  156163. nW=(W?nW:0);
  156164. {
  156165. float *windowLW=vwin[winno[lW]];
  156166. float *windowNW=vwin[winno[nW]];
  156167. long n=blocksizes[W];
  156168. long ln=blocksizes[lW];
  156169. long rn=blocksizes[nW];
  156170. long leftbegin=n/4-ln/4;
  156171. long leftend=leftbegin+ln/2;
  156172. long rightbegin=n/2+n/4-rn/4;
  156173. long rightend=rightbegin+rn/2;
  156174. int i,p;
  156175. for(i=0;i<leftbegin;i++)
  156176. d[i]=0.f;
  156177. for(p=0;i<leftend;i++,p++)
  156178. d[i]*=windowLW[p];
  156179. for(i=rightbegin,p=rn/2-1;i<rightend;i++,p--)
  156180. d[i]*=windowNW[p];
  156181. for(;i<n;i++)
  156182. d[i]=0.f;
  156183. }
  156184. }
  156185. #endif
  156186. /*** End of inlined file: window.c ***/
  156187. #else
  156188. #include <vorbis/vorbisenc.h>
  156189. #include <vorbis/codec.h>
  156190. #include <vorbis/vorbisfile.h>
  156191. #endif
  156192. }
  156193. #undef max
  156194. #undef min
  156195. BEGIN_JUCE_NAMESPACE
  156196. static const char* const oggFormatName = "Ogg-Vorbis file";
  156197. static const char* const oggExtensions[] = { ".ogg", 0 };
  156198. class OggReader : public AudioFormatReader
  156199. {
  156200. OggVorbisNamespace::OggVorbis_File ovFile;
  156201. OggVorbisNamespace::ov_callbacks callbacks;
  156202. AudioSampleBuffer reservoir;
  156203. int reservoirStart, samplesInReservoir;
  156204. public:
  156205. OggReader (InputStream* const inp)
  156206. : AudioFormatReader (inp, TRANS (oggFormatName)),
  156207. reservoir (2, 4096),
  156208. reservoirStart (0),
  156209. samplesInReservoir (0)
  156210. {
  156211. using namespace OggVorbisNamespace;
  156212. sampleRate = 0;
  156213. usesFloatingPointData = true;
  156214. callbacks.read_func = &oggReadCallback;
  156215. callbacks.seek_func = &oggSeekCallback;
  156216. callbacks.close_func = &oggCloseCallback;
  156217. callbacks.tell_func = &oggTellCallback;
  156218. const int err = ov_open_callbacks (input, &ovFile, 0, 0, callbacks);
  156219. if (err == 0)
  156220. {
  156221. vorbis_info* info = ov_info (&ovFile, -1);
  156222. lengthInSamples = (uint32) ov_pcm_total (&ovFile, -1);
  156223. numChannels = info->channels;
  156224. bitsPerSample = 16;
  156225. sampleRate = info->rate;
  156226. reservoir.setSize (numChannels,
  156227. (int) jmin (lengthInSamples, (int64) reservoir.getNumSamples()));
  156228. }
  156229. }
  156230. ~OggReader()
  156231. {
  156232. OggVorbisNamespace::ov_clear (&ovFile);
  156233. }
  156234. bool readSamples (int** destSamples, int numDestChannels, int startOffsetInDestBuffer,
  156235. int64 startSampleInFile, int numSamples)
  156236. {
  156237. while (numSamples > 0)
  156238. {
  156239. const int numAvailable = reservoirStart + samplesInReservoir - startSampleInFile;
  156240. if (startSampleInFile >= reservoirStart && numAvailable > 0)
  156241. {
  156242. // got a few samples overlapping, so use them before seeking..
  156243. const int numToUse = jmin (numSamples, numAvailable);
  156244. for (int i = jmin (numDestChannels, reservoir.getNumChannels()); --i >= 0;)
  156245. if (destSamples[i] != 0)
  156246. memcpy (destSamples[i] + startOffsetInDestBuffer,
  156247. reservoir.getSampleData (i, (int) (startSampleInFile - reservoirStart)),
  156248. sizeof (float) * numToUse);
  156249. startSampleInFile += numToUse;
  156250. numSamples -= numToUse;
  156251. startOffsetInDestBuffer += numToUse;
  156252. if (numSamples == 0)
  156253. break;
  156254. }
  156255. if (startSampleInFile < reservoirStart
  156256. || startSampleInFile + numSamples > reservoirStart + samplesInReservoir)
  156257. {
  156258. // buffer miss, so refill the reservoir
  156259. int bitStream = 0;
  156260. reservoirStart = jmax (0, (int) startSampleInFile);
  156261. samplesInReservoir = reservoir.getNumSamples();
  156262. if (reservoirStart != (int) OggVorbisNamespace::ov_pcm_tell (&ovFile))
  156263. OggVorbisNamespace::ov_pcm_seek (&ovFile, reservoirStart);
  156264. int offset = 0;
  156265. int numToRead = samplesInReservoir;
  156266. while (numToRead > 0)
  156267. {
  156268. float** dataIn = 0;
  156269. const int samps = OggVorbisNamespace::ov_read_float (&ovFile, &dataIn, numToRead, &bitStream);
  156270. if (samps <= 0)
  156271. break;
  156272. jassert (samps <= numToRead);
  156273. for (int i = jmin ((int) numChannels, reservoir.getNumChannels()); --i >= 0;)
  156274. {
  156275. memcpy (reservoir.getSampleData (i, offset),
  156276. dataIn[i],
  156277. sizeof (float) * samps);
  156278. }
  156279. numToRead -= samps;
  156280. offset += samps;
  156281. }
  156282. if (numToRead > 0)
  156283. reservoir.clear (offset, numToRead);
  156284. }
  156285. }
  156286. if (numSamples > 0)
  156287. {
  156288. for (int i = numDestChannels; --i >= 0;)
  156289. if (destSamples[i] != 0)
  156290. zeromem (destSamples[i] + startOffsetInDestBuffer,
  156291. sizeof (int) * numSamples);
  156292. }
  156293. return true;
  156294. }
  156295. static size_t oggReadCallback (void* ptr, size_t size, size_t nmemb, void* datasource)
  156296. {
  156297. return (size_t) (static_cast <InputStream*> (datasource)->read (ptr, (int) (size * nmemb)) / size);
  156298. }
  156299. static int oggSeekCallback (void* datasource, OggVorbisNamespace::ogg_int64_t offset, int whence)
  156300. {
  156301. InputStream* const in = static_cast <InputStream*> (datasource);
  156302. if (whence == SEEK_CUR)
  156303. offset += in->getPosition();
  156304. else if (whence == SEEK_END)
  156305. offset += in->getTotalLength();
  156306. in->setPosition (offset);
  156307. return 0;
  156308. }
  156309. static int oggCloseCallback (void*)
  156310. {
  156311. return 0;
  156312. }
  156313. static long oggTellCallback (void* datasource)
  156314. {
  156315. return (long) static_cast <InputStream*> (datasource)->getPosition();
  156316. }
  156317. juce_UseDebuggingNewOperator
  156318. };
  156319. class OggWriter : public AudioFormatWriter
  156320. {
  156321. OggVorbisNamespace::ogg_stream_state os;
  156322. OggVorbisNamespace::ogg_page og;
  156323. OggVorbisNamespace::ogg_packet op;
  156324. OggVorbisNamespace::vorbis_info vi;
  156325. OggVorbisNamespace::vorbis_comment vc;
  156326. OggVorbisNamespace::vorbis_dsp_state vd;
  156327. OggVorbisNamespace::vorbis_block vb;
  156328. public:
  156329. bool ok;
  156330. OggWriter (OutputStream* const out,
  156331. const double sampleRate,
  156332. const int numChannels,
  156333. const int bitsPerSample,
  156334. const int qualityIndex)
  156335. : AudioFormatWriter (out, TRANS (oggFormatName),
  156336. sampleRate,
  156337. numChannels,
  156338. bitsPerSample)
  156339. {
  156340. using namespace OggVorbisNamespace;
  156341. ok = false;
  156342. vorbis_info_init (&vi);
  156343. if (vorbis_encode_init_vbr (&vi,
  156344. numChannels,
  156345. (int) sampleRate,
  156346. jlimit (0.0f, 1.0f, qualityIndex * 0.5f)) == 0)
  156347. {
  156348. vorbis_comment_init (&vc);
  156349. if (JUCEApplication::getInstance() != 0)
  156350. vorbis_comment_add_tag (&vc, "ENCODER", const_cast <char*> (JUCEApplication::getInstance()->getApplicationName().toUTF8()));
  156351. vorbis_analysis_init (&vd, &vi);
  156352. vorbis_block_init (&vd, &vb);
  156353. ogg_stream_init (&os, Random::getSystemRandom().nextInt());
  156354. ogg_packet header;
  156355. ogg_packet header_comm;
  156356. ogg_packet header_code;
  156357. vorbis_analysis_headerout (&vd, &vc, &header, &header_comm, &header_code);
  156358. ogg_stream_packetin (&os, &header);
  156359. ogg_stream_packetin (&os, &header_comm);
  156360. ogg_stream_packetin (&os, &header_code);
  156361. for (;;)
  156362. {
  156363. if (ogg_stream_flush (&os, &og) == 0)
  156364. break;
  156365. output->write (og.header, og.header_len);
  156366. output->write (og.body, og.body_len);
  156367. }
  156368. ok = true;
  156369. }
  156370. }
  156371. ~OggWriter()
  156372. {
  156373. using namespace OggVorbisNamespace;
  156374. if (ok)
  156375. {
  156376. // write a zero-length packet to show ogg that we're finished..
  156377. write (0, 0);
  156378. ogg_stream_clear (&os);
  156379. vorbis_block_clear (&vb);
  156380. vorbis_dsp_clear (&vd);
  156381. vorbis_comment_clear (&vc);
  156382. vorbis_info_clear (&vi);
  156383. output->flush();
  156384. }
  156385. else
  156386. {
  156387. vorbis_info_clear (&vi);
  156388. output = 0; // to stop the base class deleting this, as it needs to be returned
  156389. // to the caller of createWriter()
  156390. }
  156391. }
  156392. bool write (const int** samplesToWrite, int numSamples)
  156393. {
  156394. using namespace OggVorbisNamespace;
  156395. if (! ok)
  156396. return false;
  156397. if (numSamples > 0)
  156398. {
  156399. const double gain = 1.0 / 0x80000000u;
  156400. float** const vorbisBuffer = vorbis_analysis_buffer (&vd, numSamples);
  156401. for (int i = numChannels; --i >= 0;)
  156402. {
  156403. float* const dst = vorbisBuffer[i];
  156404. const int* const src = samplesToWrite [i];
  156405. if (src != 0 && dst != 0)
  156406. {
  156407. for (int j = 0; j < numSamples; ++j)
  156408. dst[j] = (float) (src[j] * gain);
  156409. }
  156410. }
  156411. }
  156412. vorbis_analysis_wrote (&vd, numSamples);
  156413. while (vorbis_analysis_blockout (&vd, &vb) == 1)
  156414. {
  156415. vorbis_analysis (&vb, 0);
  156416. vorbis_bitrate_addblock (&vb);
  156417. while (vorbis_bitrate_flushpacket (&vd, &op))
  156418. {
  156419. ogg_stream_packetin (&os, &op);
  156420. for (;;)
  156421. {
  156422. if (ogg_stream_pageout (&os, &og) == 0)
  156423. break;
  156424. output->write (og.header, og.header_len);
  156425. output->write (og.body, og.body_len);
  156426. if (ogg_page_eos (&og))
  156427. break;
  156428. }
  156429. }
  156430. }
  156431. return true;
  156432. }
  156433. juce_UseDebuggingNewOperator
  156434. };
  156435. OggVorbisAudioFormat::OggVorbisAudioFormat()
  156436. : AudioFormat (TRANS (oggFormatName), StringArray (oggExtensions))
  156437. {
  156438. }
  156439. OggVorbisAudioFormat::~OggVorbisAudioFormat()
  156440. {
  156441. }
  156442. const Array <int> OggVorbisAudioFormat::getPossibleSampleRates()
  156443. {
  156444. const int rates[] = { 22050, 32000, 44100, 48000, 0 };
  156445. return Array <int> (rates);
  156446. }
  156447. const Array <int> OggVorbisAudioFormat::getPossibleBitDepths()
  156448. {
  156449. Array <int> depths;
  156450. depths.add (32);
  156451. return depths;
  156452. }
  156453. bool OggVorbisAudioFormat::canDoStereo()
  156454. {
  156455. return true;
  156456. }
  156457. bool OggVorbisAudioFormat::canDoMono()
  156458. {
  156459. return true;
  156460. }
  156461. AudioFormatReader* OggVorbisAudioFormat::createReaderFor (InputStream* in,
  156462. const bool deleteStreamIfOpeningFails)
  156463. {
  156464. ScopedPointer <OggReader> r (new OggReader (in));
  156465. if (r->sampleRate != 0)
  156466. return r.release();
  156467. if (! deleteStreamIfOpeningFails)
  156468. r->input = 0;
  156469. return 0;
  156470. }
  156471. AudioFormatWriter* OggVorbisAudioFormat::createWriterFor (OutputStream* out,
  156472. double sampleRate,
  156473. unsigned int numChannels,
  156474. int bitsPerSample,
  156475. const StringPairArray& /*metadataValues*/,
  156476. int qualityOptionIndex)
  156477. {
  156478. ScopedPointer <OggWriter> w (new OggWriter (out,
  156479. sampleRate,
  156480. numChannels,
  156481. bitsPerSample,
  156482. qualityOptionIndex));
  156483. return w->ok ? w.release() : 0;
  156484. }
  156485. bool OggVorbisAudioFormat::isCompressed()
  156486. {
  156487. return true;
  156488. }
  156489. const StringArray OggVorbisAudioFormat::getQualityOptions()
  156490. {
  156491. StringArray s;
  156492. s.add ("Low Quality");
  156493. s.add ("Medium Quality");
  156494. s.add ("High Quality");
  156495. return s;
  156496. }
  156497. int OggVorbisAudioFormat::estimateOggFileQuality (const File& source)
  156498. {
  156499. FileInputStream* const in = source.createInputStream();
  156500. if (in != 0)
  156501. {
  156502. ScopedPointer <AudioFormatReader> r (createReaderFor (in, true));
  156503. if (r != 0)
  156504. {
  156505. const int64 numSamps = r->lengthInSamples;
  156506. r = 0;
  156507. const int64 fileNumSamps = source.getSize() / 4;
  156508. const double ratio = numSamps / (double) fileNumSamps;
  156509. if (ratio > 12.0)
  156510. return 0;
  156511. else if (ratio > 6.0)
  156512. return 1;
  156513. else
  156514. return 2;
  156515. }
  156516. }
  156517. return 1;
  156518. }
  156519. END_JUCE_NAMESPACE
  156520. #endif
  156521. /*** End of inlined file: juce_OggVorbisAudioFormat.cpp ***/
  156522. #endif
  156523. #if JUCE_BUILD_CORE && ! JUCE_ONLY_BUILD_CORE_LIBRARY // do these in the core section to help balance the sizes
  156524. /*** Start of inlined file: juce_JPEGLoader.cpp ***/
  156525. #if JUCE_MSVC
  156526. #pragma warning (push)
  156527. #endif
  156528. namespace jpeglibNamespace
  156529. {
  156530. #if JUCE_INCLUDE_JPEGLIB_CODE
  156531. #if JUCE_MINGW
  156532. typedef unsigned char boolean;
  156533. #endif
  156534. extern "C"
  156535. {
  156536. #define JPEG_INTERNALS
  156537. #undef FAR
  156538. /*** Start of inlined file: jpeglib.h ***/
  156539. #ifndef JPEGLIB_H
  156540. #define JPEGLIB_H
  156541. /*
  156542. * First we include the configuration files that record how this
  156543. * installation of the JPEG library is set up. jconfig.h can be
  156544. * generated automatically for many systems. jmorecfg.h contains
  156545. * manual configuration options that most people need not worry about.
  156546. */
  156547. #ifndef JCONFIG_INCLUDED /* in case jinclude.h already did */
  156548. /*** Start of inlined file: jconfig.h ***/
  156549. /* see jconfig.doc for explanations */
  156550. // disable all the warnings under MSVC
  156551. #ifdef _MSC_VER
  156552. #pragma warning (disable: 4996 4267 4100 4127 4702 4244)
  156553. #endif
  156554. #ifdef __BORLANDC__
  156555. #pragma warn -8057
  156556. #pragma warn -8019
  156557. #pragma warn -8004
  156558. #pragma warn -8008
  156559. #endif
  156560. #define HAVE_PROTOTYPES
  156561. #define HAVE_UNSIGNED_CHAR
  156562. #define HAVE_UNSIGNED_SHORT
  156563. /* #define void char */
  156564. /* #define const */
  156565. #undef CHAR_IS_UNSIGNED
  156566. #define HAVE_STDDEF_H
  156567. #define HAVE_STDLIB_H
  156568. #undef NEED_BSD_STRINGS
  156569. #undef NEED_SYS_TYPES_H
  156570. #undef NEED_FAR_POINTERS /* we presume a 32-bit flat memory model */
  156571. #undef NEED_SHORT_EXTERNAL_NAMES
  156572. #undef INCOMPLETE_TYPES_BROKEN
  156573. /* Define "boolean" as unsigned char, not int, per Windows custom */
  156574. #ifndef __RPCNDR_H__ /* don't conflict if rpcndr.h already read */
  156575. typedef unsigned char boolean;
  156576. #endif
  156577. #define HAVE_BOOLEAN /* prevent jmorecfg.h from redefining it */
  156578. #ifdef JPEG_INTERNALS
  156579. #undef RIGHT_SHIFT_IS_UNSIGNED
  156580. #endif /* JPEG_INTERNALS */
  156581. #ifdef JPEG_CJPEG_DJPEG
  156582. #define BMP_SUPPORTED /* BMP image file format */
  156583. #define GIF_SUPPORTED /* GIF image file format */
  156584. #define PPM_SUPPORTED /* PBMPLUS PPM/PGM image file format */
  156585. #undef RLE_SUPPORTED /* Utah RLE image file format */
  156586. #define TARGA_SUPPORTED /* Targa image file format */
  156587. #define TWO_FILE_COMMANDLINE /* optional */
  156588. #define USE_SETMODE /* Microsoft has setmode() */
  156589. #undef NEED_SIGNAL_CATCHER
  156590. #undef DONT_USE_B_MODE
  156591. #undef PROGRESS_REPORT /* optional */
  156592. #endif /* JPEG_CJPEG_DJPEG */
  156593. /*** End of inlined file: jconfig.h ***/
  156594. /* widely used configuration options */
  156595. #endif
  156596. /*** Start of inlined file: jmorecfg.h ***/
  156597. /*
  156598. * Define BITS_IN_JSAMPLE as either
  156599. * 8 for 8-bit sample values (the usual setting)
  156600. * 12 for 12-bit sample values
  156601. * Only 8 and 12 are legal data precisions for lossy JPEG according to the
  156602. * JPEG standard, and the IJG code does not support anything else!
  156603. * We do not support run-time selection of data precision, sorry.
  156604. */
  156605. #define BITS_IN_JSAMPLE 8 /* use 8 or 12 */
  156606. /*
  156607. * Maximum number of components (color channels) allowed in JPEG image.
  156608. * To meet the letter of the JPEG spec, set this to 255. However, darn
  156609. * few applications need more than 4 channels (maybe 5 for CMYK + alpha
  156610. * mask). We recommend 10 as a reasonable compromise; use 4 if you are
  156611. * really short on memory. (Each allowed component costs a hundred or so
  156612. * bytes of storage, whether actually used in an image or not.)
  156613. */
  156614. #define MAX_COMPONENTS 10 /* maximum number of image components */
  156615. /*
  156616. * Basic data types.
  156617. * You may need to change these if you have a machine with unusual data
  156618. * type sizes; for example, "char" not 8 bits, "short" not 16 bits,
  156619. * or "long" not 32 bits. We don't care whether "int" is 16 or 32 bits,
  156620. * but it had better be at least 16.
  156621. */
  156622. /* Representation of a single sample (pixel element value).
  156623. * We frequently allocate large arrays of these, so it's important to keep
  156624. * them small. But if you have memory to burn and access to char or short
  156625. * arrays is very slow on your hardware, you might want to change these.
  156626. */
  156627. #if BITS_IN_JSAMPLE == 8
  156628. /* JSAMPLE should be the smallest type that will hold the values 0..255.
  156629. * You can use a signed char by having GETJSAMPLE mask it with 0xFF.
  156630. */
  156631. #ifdef HAVE_UNSIGNED_CHAR
  156632. typedef unsigned char JSAMPLE;
  156633. #define GETJSAMPLE(value) ((int) (value))
  156634. #else /* not HAVE_UNSIGNED_CHAR */
  156635. typedef char JSAMPLE;
  156636. #ifdef CHAR_IS_UNSIGNED
  156637. #define GETJSAMPLE(value) ((int) (value))
  156638. #else
  156639. #define GETJSAMPLE(value) ((int) (value) & 0xFF)
  156640. #endif /* CHAR_IS_UNSIGNED */
  156641. #endif /* HAVE_UNSIGNED_CHAR */
  156642. #define MAXJSAMPLE 255
  156643. #define CENTERJSAMPLE 128
  156644. #endif /* BITS_IN_JSAMPLE == 8 */
  156645. #if BITS_IN_JSAMPLE == 12
  156646. /* JSAMPLE should be the smallest type that will hold the values 0..4095.
  156647. * On nearly all machines "short" will do nicely.
  156648. */
  156649. typedef short JSAMPLE;
  156650. #define GETJSAMPLE(value) ((int) (value))
  156651. #define MAXJSAMPLE 4095
  156652. #define CENTERJSAMPLE 2048
  156653. #endif /* BITS_IN_JSAMPLE == 12 */
  156654. /* Representation of a DCT frequency coefficient.
  156655. * This should be a signed value of at least 16 bits; "short" is usually OK.
  156656. * Again, we allocate large arrays of these, but you can change to int
  156657. * if you have memory to burn and "short" is really slow.
  156658. */
  156659. typedef short JCOEF;
  156660. /* Compressed datastreams are represented as arrays of JOCTET.
  156661. * These must be EXACTLY 8 bits wide, at least once they are written to
  156662. * external storage. Note that when using the stdio data source/destination
  156663. * managers, this is also the data type passed to fread/fwrite.
  156664. */
  156665. #ifdef HAVE_UNSIGNED_CHAR
  156666. typedef unsigned char JOCTET;
  156667. #define GETJOCTET(value) (value)
  156668. #else /* not HAVE_UNSIGNED_CHAR */
  156669. typedef char JOCTET;
  156670. #ifdef CHAR_IS_UNSIGNED
  156671. #define GETJOCTET(value) (value)
  156672. #else
  156673. #define GETJOCTET(value) ((value) & 0xFF)
  156674. #endif /* CHAR_IS_UNSIGNED */
  156675. #endif /* HAVE_UNSIGNED_CHAR */
  156676. /* These typedefs are used for various table entries and so forth.
  156677. * They must be at least as wide as specified; but making them too big
  156678. * won't cost a huge amount of memory, so we don't provide special
  156679. * extraction code like we did for JSAMPLE. (In other words, these
  156680. * typedefs live at a different point on the speed/space tradeoff curve.)
  156681. */
  156682. /* UINT8 must hold at least the values 0..255. */
  156683. #ifdef HAVE_UNSIGNED_CHAR
  156684. typedef unsigned char UINT8;
  156685. #else /* not HAVE_UNSIGNED_CHAR */
  156686. #ifdef CHAR_IS_UNSIGNED
  156687. typedef char UINT8;
  156688. #else /* not CHAR_IS_UNSIGNED */
  156689. typedef short UINT8;
  156690. #endif /* CHAR_IS_UNSIGNED */
  156691. #endif /* HAVE_UNSIGNED_CHAR */
  156692. /* UINT16 must hold at least the values 0..65535. */
  156693. #ifdef HAVE_UNSIGNED_SHORT
  156694. typedef unsigned short UINT16;
  156695. #else /* not HAVE_UNSIGNED_SHORT */
  156696. typedef unsigned int UINT16;
  156697. #endif /* HAVE_UNSIGNED_SHORT */
  156698. /* INT16 must hold at least the values -32768..32767. */
  156699. #ifndef XMD_H /* X11/xmd.h correctly defines INT16 */
  156700. typedef short INT16;
  156701. #endif
  156702. /* INT32 must hold at least signed 32-bit values. */
  156703. #ifndef XMD_H /* X11/xmd.h correctly defines INT32 */
  156704. typedef long INT32;
  156705. #endif
  156706. /* Datatype used for image dimensions. The JPEG standard only supports
  156707. * images up to 64K*64K due to 16-bit fields in SOF markers. Therefore
  156708. * "unsigned int" is sufficient on all machines. However, if you need to
  156709. * handle larger images and you don't mind deviating from the spec, you
  156710. * can change this datatype.
  156711. */
  156712. typedef unsigned int JDIMENSION;
  156713. #define JPEG_MAX_DIMENSION 65500L /* a tad under 64K to prevent overflows */
  156714. /* These macros are used in all function definitions and extern declarations.
  156715. * You could modify them if you need to change function linkage conventions;
  156716. * in particular, you'll need to do that to make the library a Windows DLL.
  156717. * Another application is to make all functions global for use with debuggers
  156718. * or code profilers that require it.
  156719. */
  156720. /* a function called through method pointers: */
  156721. #define METHODDEF(type) static type
  156722. /* a function used only in its module: */
  156723. #define LOCAL(type) static type
  156724. /* a function referenced thru EXTERNs: */
  156725. #define GLOBAL(type) type
  156726. /* a reference to a GLOBAL function: */
  156727. #define EXTERN(type) extern type
  156728. /* This macro is used to declare a "method", that is, a function pointer.
  156729. * We want to supply prototype parameters if the compiler can cope.
  156730. * Note that the arglist parameter must be parenthesized!
  156731. * Again, you can customize this if you need special linkage keywords.
  156732. */
  156733. #ifdef HAVE_PROTOTYPES
  156734. #define JMETHOD(type,methodname,arglist) type (*methodname) arglist
  156735. #else
  156736. #define JMETHOD(type,methodname,arglist) type (*methodname) ()
  156737. #endif
  156738. /* Here is the pseudo-keyword for declaring pointers that must be "far"
  156739. * on 80x86 machines. Most of the specialized coding for 80x86 is handled
  156740. * by just saying "FAR *" where such a pointer is needed. In a few places
  156741. * explicit coding is needed; see uses of the NEED_FAR_POINTERS symbol.
  156742. */
  156743. #ifdef NEED_FAR_POINTERS
  156744. #define FAR far
  156745. #else
  156746. #define FAR
  156747. #endif
  156748. /*
  156749. * On a few systems, type boolean and/or its values FALSE, TRUE may appear
  156750. * in standard header files. Or you may have conflicts with application-
  156751. * specific header files that you want to include together with these files.
  156752. * Defining HAVE_BOOLEAN before including jpeglib.h should make it work.
  156753. */
  156754. #ifndef HAVE_BOOLEAN
  156755. typedef int boolean;
  156756. #endif
  156757. #ifndef FALSE /* in case these macros already exist */
  156758. #define FALSE 0 /* values of boolean */
  156759. #endif
  156760. #ifndef TRUE
  156761. #define TRUE 1
  156762. #endif
  156763. /*
  156764. * The remaining options affect code selection within the JPEG library,
  156765. * but they don't need to be visible to most applications using the library.
  156766. * To minimize application namespace pollution, the symbols won't be
  156767. * defined unless JPEG_INTERNALS or JPEG_INTERNAL_OPTIONS has been defined.
  156768. */
  156769. #ifdef JPEG_INTERNALS
  156770. #define JPEG_INTERNAL_OPTIONS
  156771. #endif
  156772. #ifdef JPEG_INTERNAL_OPTIONS
  156773. /*
  156774. * These defines indicate whether to include various optional functions.
  156775. * Undefining some of these symbols will produce a smaller but less capable
  156776. * library. Note that you can leave certain source files out of the
  156777. * compilation/linking process if you've #undef'd the corresponding symbols.
  156778. * (You may HAVE to do that if your compiler doesn't like null source files.)
  156779. */
  156780. /* Arithmetic coding is unsupported for legal reasons. Complaints to IBM. */
  156781. /* Capability options common to encoder and decoder: */
  156782. #define DCT_ISLOW_SUPPORTED /* slow but accurate integer algorithm */
  156783. #define DCT_IFAST_SUPPORTED /* faster, less accurate integer method */
  156784. #define DCT_FLOAT_SUPPORTED /* floating-point: accurate, fast on fast HW */
  156785. /* Encoder capability options: */
  156786. #undef C_ARITH_CODING_SUPPORTED /* Arithmetic coding back end? */
  156787. #define C_MULTISCAN_FILES_SUPPORTED /* Multiple-scan JPEG files? */
  156788. #define C_PROGRESSIVE_SUPPORTED /* Progressive JPEG? (Requires MULTISCAN)*/
  156789. #define ENTROPY_OPT_SUPPORTED /* Optimization of entropy coding parms? */
  156790. /* Note: if you selected 12-bit data precision, it is dangerous to turn off
  156791. * ENTROPY_OPT_SUPPORTED. The standard Huffman tables are only good for 8-bit
  156792. * precision, so jchuff.c normally uses entropy optimization to compute
  156793. * usable tables for higher precision. If you don't want to do optimization,
  156794. * you'll have to supply different default Huffman tables.
  156795. * The exact same statements apply for progressive JPEG: the default tables
  156796. * don't work for progressive mode. (This may get fixed, however.)
  156797. */
  156798. #define INPUT_SMOOTHING_SUPPORTED /* Input image smoothing option? */
  156799. /* Decoder capability options: */
  156800. #undef D_ARITH_CODING_SUPPORTED /* Arithmetic coding back end? */
  156801. #define D_MULTISCAN_FILES_SUPPORTED /* Multiple-scan JPEG files? */
  156802. #define D_PROGRESSIVE_SUPPORTED /* Progressive JPEG? (Requires MULTISCAN)*/
  156803. #define SAVE_MARKERS_SUPPORTED /* jpeg_save_markers() needed? */
  156804. #define BLOCK_SMOOTHING_SUPPORTED /* Block smoothing? (Progressive only) */
  156805. #define IDCT_SCALING_SUPPORTED /* Output rescaling via IDCT? */
  156806. #undef UPSAMPLE_SCALING_SUPPORTED /* Output rescaling at upsample stage? */
  156807. #define UPSAMPLE_MERGING_SUPPORTED /* Fast path for sloppy upsampling? */
  156808. #define QUANT_1PASS_SUPPORTED /* 1-pass color quantization? */
  156809. #define QUANT_2PASS_SUPPORTED /* 2-pass color quantization? */
  156810. /* more capability options later, no doubt */
  156811. /*
  156812. * Ordering of RGB data in scanlines passed to or from the application.
  156813. * If your application wants to deal with data in the order B,G,R, just
  156814. * change these macros. You can also deal with formats such as R,G,B,X
  156815. * (one extra byte per pixel) by changing RGB_PIXELSIZE. Note that changing
  156816. * the offsets will also change the order in which colormap data is organized.
  156817. * RESTRICTIONS:
  156818. * 1. The sample applications cjpeg,djpeg do NOT support modified RGB formats.
  156819. * 2. These macros only affect RGB<=>YCbCr color conversion, so they are not
  156820. * useful if you are using JPEG color spaces other than YCbCr or grayscale.
  156821. * 3. The color quantizer modules will not behave desirably if RGB_PIXELSIZE
  156822. * is not 3 (they don't understand about dummy color components!). So you
  156823. * can't use color quantization if you change that value.
  156824. */
  156825. #define RGB_RED 0 /* Offset of Red in an RGB scanline element */
  156826. #define RGB_GREEN 1 /* Offset of Green */
  156827. #define RGB_BLUE 2 /* Offset of Blue */
  156828. #define RGB_PIXELSIZE 3 /* JSAMPLEs per RGB scanline element */
  156829. /* Definitions for speed-related optimizations. */
  156830. /* If your compiler supports inline functions, define INLINE
  156831. * as the inline keyword; otherwise define it as empty.
  156832. */
  156833. #ifndef INLINE
  156834. #ifdef __GNUC__ /* for instance, GNU C knows about inline */
  156835. #define INLINE __inline__
  156836. #endif
  156837. #ifndef INLINE
  156838. #define INLINE /* default is to define it as empty */
  156839. #endif
  156840. #endif
  156841. /* On some machines (notably 68000 series) "int" is 32 bits, but multiplying
  156842. * two 16-bit shorts is faster than multiplying two ints. Define MULTIPLIER
  156843. * as short on such a machine. MULTIPLIER must be at least 16 bits wide.
  156844. */
  156845. #ifndef MULTIPLIER
  156846. #define MULTIPLIER int /* type for fastest integer multiply */
  156847. #endif
  156848. /* FAST_FLOAT should be either float or double, whichever is done faster
  156849. * by your compiler. (Note that this type is only used in the floating point
  156850. * DCT routines, so it only matters if you've defined DCT_FLOAT_SUPPORTED.)
  156851. * Typically, float is faster in ANSI C compilers, while double is faster in
  156852. * pre-ANSI compilers (because they insist on converting to double anyway).
  156853. * The code below therefore chooses float if we have ANSI-style prototypes.
  156854. */
  156855. #ifndef FAST_FLOAT
  156856. #ifdef HAVE_PROTOTYPES
  156857. #define FAST_FLOAT float
  156858. #else
  156859. #define FAST_FLOAT double
  156860. #endif
  156861. #endif
  156862. #endif /* JPEG_INTERNAL_OPTIONS */
  156863. /*** End of inlined file: jmorecfg.h ***/
  156864. /* seldom changed options */
  156865. /* Version ID for the JPEG library.
  156866. * Might be useful for tests like "#if JPEG_LIB_VERSION >= 60".
  156867. */
  156868. #define JPEG_LIB_VERSION 62 /* Version 6b */
  156869. /* Various constants determining the sizes of things.
  156870. * All of these are specified by the JPEG standard, so don't change them
  156871. * if you want to be compatible.
  156872. */
  156873. #define DCTSIZE 8 /* The basic DCT block is 8x8 samples */
  156874. #define DCTSIZE2 64 /* DCTSIZE squared; # of elements in a block */
  156875. #define NUM_QUANT_TBLS 4 /* Quantization tables are numbered 0..3 */
  156876. #define NUM_HUFF_TBLS 4 /* Huffman tables are numbered 0..3 */
  156877. #define NUM_ARITH_TBLS 16 /* Arith-coding tables are numbered 0..15 */
  156878. #define MAX_COMPS_IN_SCAN 4 /* JPEG limit on # of components in one scan */
  156879. #define MAX_SAMP_FACTOR 4 /* JPEG limit on sampling factors */
  156880. /* Unfortunately, some bozo at Adobe saw no reason to be bound by the standard;
  156881. * the PostScript DCT filter can emit files with many more than 10 blocks/MCU.
  156882. * If you happen to run across such a file, you can up D_MAX_BLOCKS_IN_MCU
  156883. * to handle it. We even let you do this from the jconfig.h file. However,
  156884. * we strongly discourage changing C_MAX_BLOCKS_IN_MCU; just because Adobe
  156885. * sometimes emits noncompliant files doesn't mean you should too.
  156886. */
  156887. #define C_MAX_BLOCKS_IN_MCU 10 /* compressor's limit on blocks per MCU */
  156888. #ifndef D_MAX_BLOCKS_IN_MCU
  156889. #define D_MAX_BLOCKS_IN_MCU 10 /* decompressor's limit on blocks per MCU */
  156890. #endif
  156891. /* Data structures for images (arrays of samples and of DCT coefficients).
  156892. * On 80x86 machines, the image arrays are too big for near pointers,
  156893. * but the pointer arrays can fit in near memory.
  156894. */
  156895. typedef JSAMPLE FAR *JSAMPROW; /* ptr to one image row of pixel samples. */
  156896. typedef JSAMPROW *JSAMPARRAY; /* ptr to some rows (a 2-D sample array) */
  156897. typedef JSAMPARRAY *JSAMPIMAGE; /* a 3-D sample array: top index is color */
  156898. typedef JCOEF JBLOCK[DCTSIZE2]; /* one block of coefficients */
  156899. typedef JBLOCK FAR *JBLOCKROW; /* pointer to one row of coefficient blocks */
  156900. typedef JBLOCKROW *JBLOCKARRAY; /* a 2-D array of coefficient blocks */
  156901. typedef JBLOCKARRAY *JBLOCKIMAGE; /* a 3-D array of coefficient blocks */
  156902. typedef JCOEF FAR *JCOEFPTR; /* useful in a couple of places */
  156903. /* Types for JPEG compression parameters and working tables. */
  156904. /* DCT coefficient quantization tables. */
  156905. typedef struct {
  156906. /* This array gives the coefficient quantizers in natural array order
  156907. * (not the zigzag order in which they are stored in a JPEG DQT marker).
  156908. * CAUTION: IJG versions prior to v6a kept this array in zigzag order.
  156909. */
  156910. UINT16 quantval[DCTSIZE2]; /* quantization step for each coefficient */
  156911. /* This field is used only during compression. It's initialized FALSE when
  156912. * the table is created, and set TRUE when it's been output to the file.
  156913. * You could suppress output of a table by setting this to TRUE.
  156914. * (See jpeg_suppress_tables for an example.)
  156915. */
  156916. boolean sent_table; /* TRUE when table has been output */
  156917. } JQUANT_TBL;
  156918. /* Huffman coding tables. */
  156919. typedef struct {
  156920. /* These two fields directly represent the contents of a JPEG DHT marker */
  156921. UINT8 bits[17]; /* bits[k] = # of symbols with codes of */
  156922. /* length k bits; bits[0] is unused */
  156923. UINT8 huffval[256]; /* The symbols, in order of incr code length */
  156924. /* This field is used only during compression. It's initialized FALSE when
  156925. * the table is created, and set TRUE when it's been output to the file.
  156926. * You could suppress output of a table by setting this to TRUE.
  156927. * (See jpeg_suppress_tables for an example.)
  156928. */
  156929. boolean sent_table; /* TRUE when table has been output */
  156930. } JHUFF_TBL;
  156931. /* Basic info about one component (color channel). */
  156932. typedef struct {
  156933. /* These values are fixed over the whole image. */
  156934. /* For compression, they must be supplied by parameter setup; */
  156935. /* for decompression, they are read from the SOF marker. */
  156936. int component_id; /* identifier for this component (0..255) */
  156937. int component_index; /* its index in SOF or cinfo->comp_info[] */
  156938. int h_samp_factor; /* horizontal sampling factor (1..4) */
  156939. int v_samp_factor; /* vertical sampling factor (1..4) */
  156940. int quant_tbl_no; /* quantization table selector (0..3) */
  156941. /* These values may vary between scans. */
  156942. /* For compression, they must be supplied by parameter setup; */
  156943. /* for decompression, they are read from the SOS marker. */
  156944. /* The decompressor output side may not use these variables. */
  156945. int dc_tbl_no; /* DC entropy table selector (0..3) */
  156946. int ac_tbl_no; /* AC entropy table selector (0..3) */
  156947. /* Remaining fields should be treated as private by applications. */
  156948. /* These values are computed during compression or decompression startup: */
  156949. /* Component's size in DCT blocks.
  156950. * Any dummy blocks added to complete an MCU are not counted; therefore
  156951. * these values do not depend on whether a scan is interleaved or not.
  156952. */
  156953. JDIMENSION width_in_blocks;
  156954. JDIMENSION height_in_blocks;
  156955. /* Size of a DCT block in samples. Always DCTSIZE for compression.
  156956. * For decompression this is the size of the output from one DCT block,
  156957. * reflecting any scaling we choose to apply during the IDCT step.
  156958. * Values of 1,2,4,8 are likely to be supported. Note that different
  156959. * components may receive different IDCT scalings.
  156960. */
  156961. int DCT_scaled_size;
  156962. /* The downsampled dimensions are the component's actual, unpadded number
  156963. * of samples at the main buffer (preprocessing/compression interface), thus
  156964. * downsampled_width = ceil(image_width * Hi/Hmax)
  156965. * and similarly for height. For decompression, IDCT scaling is included, so
  156966. * downsampled_width = ceil(image_width * Hi/Hmax * DCT_scaled_size/DCTSIZE)
  156967. */
  156968. JDIMENSION downsampled_width; /* actual width in samples */
  156969. JDIMENSION downsampled_height; /* actual height in samples */
  156970. /* This flag is used only for decompression. In cases where some of the
  156971. * components will be ignored (eg grayscale output from YCbCr image),
  156972. * we can skip most computations for the unused components.
  156973. */
  156974. boolean component_needed; /* do we need the value of this component? */
  156975. /* These values are computed before starting a scan of the component. */
  156976. /* The decompressor output side may not use these variables. */
  156977. int MCU_width; /* number of blocks per MCU, horizontally */
  156978. int MCU_height; /* number of blocks per MCU, vertically */
  156979. int MCU_blocks; /* MCU_width * MCU_height */
  156980. int MCU_sample_width; /* MCU width in samples, MCU_width*DCT_scaled_size */
  156981. int last_col_width; /* # of non-dummy blocks across in last MCU */
  156982. int last_row_height; /* # of non-dummy blocks down in last MCU */
  156983. /* Saved quantization table for component; NULL if none yet saved.
  156984. * See jdinput.c comments about the need for this information.
  156985. * This field is currently used only for decompression.
  156986. */
  156987. JQUANT_TBL * quant_table;
  156988. /* Private per-component storage for DCT or IDCT subsystem. */
  156989. void * dct_table;
  156990. } jpeg_component_info;
  156991. /* The script for encoding a multiple-scan file is an array of these: */
  156992. typedef struct {
  156993. int comps_in_scan; /* number of components encoded in this scan */
  156994. int component_index[MAX_COMPS_IN_SCAN]; /* their SOF/comp_info[] indexes */
  156995. int Ss, Se; /* progressive JPEG spectral selection parms */
  156996. int Ah, Al; /* progressive JPEG successive approx. parms */
  156997. } jpeg_scan_info;
  156998. /* The decompressor can save APPn and COM markers in a list of these: */
  156999. typedef struct jpeg_marker_struct FAR * jpeg_saved_marker_ptr;
  157000. struct jpeg_marker_struct {
  157001. jpeg_saved_marker_ptr next; /* next in list, or NULL */
  157002. UINT8 marker; /* marker code: JPEG_COM, or JPEG_APP0+n */
  157003. unsigned int original_length; /* # bytes of data in the file */
  157004. unsigned int data_length; /* # bytes of data saved at data[] */
  157005. JOCTET FAR * data; /* the data contained in the marker */
  157006. /* the marker length word is not counted in data_length or original_length */
  157007. };
  157008. /* Known color spaces. */
  157009. typedef enum {
  157010. JCS_UNKNOWN, /* error/unspecified */
  157011. JCS_GRAYSCALE, /* monochrome */
  157012. JCS_RGB, /* red/green/blue */
  157013. JCS_YCbCr, /* Y/Cb/Cr (also known as YUV) */
  157014. JCS_CMYK, /* C/M/Y/K */
  157015. JCS_YCCK /* Y/Cb/Cr/K */
  157016. } J_COLOR_SPACE;
  157017. /* DCT/IDCT algorithm options. */
  157018. typedef enum {
  157019. JDCT_ISLOW, /* slow but accurate integer algorithm */
  157020. JDCT_IFAST, /* faster, less accurate integer method */
  157021. JDCT_FLOAT /* floating-point: accurate, fast on fast HW */
  157022. } J_DCT_METHOD;
  157023. #ifndef JDCT_DEFAULT /* may be overridden in jconfig.h */
  157024. #define JDCT_DEFAULT JDCT_ISLOW
  157025. #endif
  157026. #ifndef JDCT_FASTEST /* may be overridden in jconfig.h */
  157027. #define JDCT_FASTEST JDCT_IFAST
  157028. #endif
  157029. /* Dithering options for decompression. */
  157030. typedef enum {
  157031. JDITHER_NONE, /* no dithering */
  157032. JDITHER_ORDERED, /* simple ordered dither */
  157033. JDITHER_FS /* Floyd-Steinberg error diffusion dither */
  157034. } J_DITHER_MODE;
  157035. /* Common fields between JPEG compression and decompression master structs. */
  157036. #define jpeg_common_fields \
  157037. struct jpeg_error_mgr * err; /* Error handler module */\
  157038. struct jpeg_memory_mgr * mem; /* Memory manager module */\
  157039. struct jpeg_progress_mgr * progress; /* Progress monitor, or NULL if none */\
  157040. void * client_data; /* Available for use by application */\
  157041. boolean is_decompressor; /* So common code can tell which is which */\
  157042. int global_state /* For checking call sequence validity */
  157043. /* Routines that are to be used by both halves of the library are declared
  157044. * to receive a pointer to this structure. There are no actual instances of
  157045. * jpeg_common_struct, only of jpeg_compress_struct and jpeg_decompress_struct.
  157046. */
  157047. struct jpeg_common_struct {
  157048. jpeg_common_fields; /* Fields common to both master struct types */
  157049. /* Additional fields follow in an actual jpeg_compress_struct or
  157050. * jpeg_decompress_struct. All three structs must agree on these
  157051. * initial fields! (This would be a lot cleaner in C++.)
  157052. */
  157053. };
  157054. typedef struct jpeg_common_struct * j_common_ptr;
  157055. typedef struct jpeg_compress_struct * j_compress_ptr;
  157056. typedef struct jpeg_decompress_struct * j_decompress_ptr;
  157057. /* Master record for a compression instance */
  157058. struct jpeg_compress_struct {
  157059. jpeg_common_fields; /* Fields shared with jpeg_decompress_struct */
  157060. /* Destination for compressed data */
  157061. struct jpeg_destination_mgr * dest;
  157062. /* Description of source image --- these fields must be filled in by
  157063. * outer application before starting compression. in_color_space must
  157064. * be correct before you can even call jpeg_set_defaults().
  157065. */
  157066. JDIMENSION image_width; /* input image width */
  157067. JDIMENSION image_height; /* input image height */
  157068. int input_components; /* # of color components in input image */
  157069. J_COLOR_SPACE in_color_space; /* colorspace of input image */
  157070. double input_gamma; /* image gamma of input image */
  157071. /* Compression parameters --- these fields must be set before calling
  157072. * jpeg_start_compress(). We recommend calling jpeg_set_defaults() to
  157073. * initialize everything to reasonable defaults, then changing anything
  157074. * the application specifically wants to change. That way you won't get
  157075. * burnt when new parameters are added. Also note that there are several
  157076. * helper routines to simplify changing parameters.
  157077. */
  157078. int data_precision; /* bits of precision in image data */
  157079. int num_components; /* # of color components in JPEG image */
  157080. J_COLOR_SPACE jpeg_color_space; /* colorspace of JPEG image */
  157081. jpeg_component_info * comp_info;
  157082. /* comp_info[i] describes component that appears i'th in SOF */
  157083. JQUANT_TBL * quant_tbl_ptrs[NUM_QUANT_TBLS];
  157084. /* ptrs to coefficient quantization tables, or NULL if not defined */
  157085. JHUFF_TBL * dc_huff_tbl_ptrs[NUM_HUFF_TBLS];
  157086. JHUFF_TBL * ac_huff_tbl_ptrs[NUM_HUFF_TBLS];
  157087. /* ptrs to Huffman coding tables, or NULL if not defined */
  157088. UINT8 arith_dc_L[NUM_ARITH_TBLS]; /* L values for DC arith-coding tables */
  157089. UINT8 arith_dc_U[NUM_ARITH_TBLS]; /* U values for DC arith-coding tables */
  157090. UINT8 arith_ac_K[NUM_ARITH_TBLS]; /* Kx values for AC arith-coding tables */
  157091. int num_scans; /* # of entries in scan_info array */
  157092. const jpeg_scan_info * scan_info; /* script for multi-scan file, or NULL */
  157093. /* The default value of scan_info is NULL, which causes a single-scan
  157094. * sequential JPEG file to be emitted. To create a multi-scan file,
  157095. * set num_scans and scan_info to point to an array of scan definitions.
  157096. */
  157097. boolean raw_data_in; /* TRUE=caller supplies downsampled data */
  157098. boolean arith_code; /* TRUE=arithmetic coding, FALSE=Huffman */
  157099. boolean optimize_coding; /* TRUE=optimize entropy encoding parms */
  157100. boolean CCIR601_sampling; /* TRUE=first samples are cosited */
  157101. int smoothing_factor; /* 1..100, or 0 for no input smoothing */
  157102. J_DCT_METHOD dct_method; /* DCT algorithm selector */
  157103. /* The restart interval can be specified in absolute MCUs by setting
  157104. * restart_interval, or in MCU rows by setting restart_in_rows
  157105. * (in which case the correct restart_interval will be figured
  157106. * for each scan).
  157107. */
  157108. unsigned int restart_interval; /* MCUs per restart, or 0 for no restart */
  157109. int restart_in_rows; /* if > 0, MCU rows per restart interval */
  157110. /* Parameters controlling emission of special markers. */
  157111. boolean write_JFIF_header; /* should a JFIF marker be written? */
  157112. UINT8 JFIF_major_version; /* What to write for the JFIF version number */
  157113. UINT8 JFIF_minor_version;
  157114. /* These three values are not used by the JPEG code, merely copied */
  157115. /* into the JFIF APP0 marker. density_unit can be 0 for unknown, */
  157116. /* 1 for dots/inch, or 2 for dots/cm. Note that the pixel aspect */
  157117. /* ratio is defined by X_density/Y_density even when density_unit=0. */
  157118. UINT8 density_unit; /* JFIF code for pixel size units */
  157119. UINT16 X_density; /* Horizontal pixel density */
  157120. UINT16 Y_density; /* Vertical pixel density */
  157121. boolean write_Adobe_marker; /* should an Adobe marker be written? */
  157122. /* State variable: index of next scanline to be written to
  157123. * jpeg_write_scanlines(). Application may use this to control its
  157124. * processing loop, e.g., "while (next_scanline < image_height)".
  157125. */
  157126. JDIMENSION next_scanline; /* 0 .. image_height-1 */
  157127. /* Remaining fields are known throughout compressor, but generally
  157128. * should not be touched by a surrounding application.
  157129. */
  157130. /*
  157131. * These fields are computed during compression startup
  157132. */
  157133. boolean progressive_mode; /* TRUE if scan script uses progressive mode */
  157134. int max_h_samp_factor; /* largest h_samp_factor */
  157135. int max_v_samp_factor; /* largest v_samp_factor */
  157136. JDIMENSION total_iMCU_rows; /* # of iMCU rows to be input to coef ctlr */
  157137. /* The coefficient controller receives data in units of MCU rows as defined
  157138. * for fully interleaved scans (whether the JPEG file is interleaved or not).
  157139. * There are v_samp_factor * DCTSIZE sample rows of each component in an
  157140. * "iMCU" (interleaved MCU) row.
  157141. */
  157142. /*
  157143. * These fields are valid during any one scan.
  157144. * They describe the components and MCUs actually appearing in the scan.
  157145. */
  157146. int comps_in_scan; /* # of JPEG components in this scan */
  157147. jpeg_component_info * cur_comp_info[MAX_COMPS_IN_SCAN];
  157148. /* *cur_comp_info[i] describes component that appears i'th in SOS */
  157149. JDIMENSION MCUs_per_row; /* # of MCUs across the image */
  157150. JDIMENSION MCU_rows_in_scan; /* # of MCU rows in the image */
  157151. int blocks_in_MCU; /* # of DCT blocks per MCU */
  157152. int MCU_membership[C_MAX_BLOCKS_IN_MCU];
  157153. /* MCU_membership[i] is index in cur_comp_info of component owning */
  157154. /* i'th block in an MCU */
  157155. int Ss, Se, Ah, Al; /* progressive JPEG parameters for scan */
  157156. /*
  157157. * Links to compression subobjects (methods and private variables of modules)
  157158. */
  157159. struct jpeg_comp_master * master;
  157160. struct jpeg_c_main_controller * main;
  157161. struct jpeg_c_prep_controller * prep;
  157162. struct jpeg_c_coef_controller * coef;
  157163. struct jpeg_marker_writer * marker;
  157164. struct jpeg_color_converter * cconvert;
  157165. struct jpeg_downsampler * downsample;
  157166. struct jpeg_forward_dct * fdct;
  157167. struct jpeg_entropy_encoder * entropy;
  157168. jpeg_scan_info * script_space; /* workspace for jpeg_simple_progression */
  157169. int script_space_size;
  157170. };
  157171. /* Master record for a decompression instance */
  157172. struct jpeg_decompress_struct {
  157173. jpeg_common_fields; /* Fields shared with jpeg_compress_struct */
  157174. /* Source of compressed data */
  157175. struct jpeg_source_mgr * src;
  157176. /* Basic description of image --- filled in by jpeg_read_header(). */
  157177. /* Application may inspect these values to decide how to process image. */
  157178. JDIMENSION image_width; /* nominal image width (from SOF marker) */
  157179. JDIMENSION image_height; /* nominal image height */
  157180. int num_components; /* # of color components in JPEG image */
  157181. J_COLOR_SPACE jpeg_color_space; /* colorspace of JPEG image */
  157182. /* Decompression processing parameters --- these fields must be set before
  157183. * calling jpeg_start_decompress(). Note that jpeg_read_header() initializes
  157184. * them to default values.
  157185. */
  157186. J_COLOR_SPACE out_color_space; /* colorspace for output */
  157187. unsigned int scale_num, scale_denom; /* fraction by which to scale image */
  157188. double output_gamma; /* image gamma wanted in output */
  157189. boolean buffered_image; /* TRUE=multiple output passes */
  157190. boolean raw_data_out; /* TRUE=downsampled data wanted */
  157191. J_DCT_METHOD dct_method; /* IDCT algorithm selector */
  157192. boolean do_fancy_upsampling; /* TRUE=apply fancy upsampling */
  157193. boolean do_block_smoothing; /* TRUE=apply interblock smoothing */
  157194. boolean quantize_colors; /* TRUE=colormapped output wanted */
  157195. /* the following are ignored if not quantize_colors: */
  157196. J_DITHER_MODE dither_mode; /* type of color dithering to use */
  157197. boolean two_pass_quantize; /* TRUE=use two-pass color quantization */
  157198. int desired_number_of_colors; /* max # colors to use in created colormap */
  157199. /* these are significant only in buffered-image mode: */
  157200. boolean enable_1pass_quant; /* enable future use of 1-pass quantizer */
  157201. boolean enable_external_quant;/* enable future use of external colormap */
  157202. boolean enable_2pass_quant; /* enable future use of 2-pass quantizer */
  157203. /* Description of actual output image that will be returned to application.
  157204. * These fields are computed by jpeg_start_decompress().
  157205. * You can also use jpeg_calc_output_dimensions() to determine these values
  157206. * in advance of calling jpeg_start_decompress().
  157207. */
  157208. JDIMENSION output_width; /* scaled image width */
  157209. JDIMENSION output_height; /* scaled image height */
  157210. int out_color_components; /* # of color components in out_color_space */
  157211. int output_components; /* # of color components returned */
  157212. /* output_components is 1 (a colormap index) when quantizing colors;
  157213. * otherwise it equals out_color_components.
  157214. */
  157215. int rec_outbuf_height; /* min recommended height of scanline buffer */
  157216. /* If the buffer passed to jpeg_read_scanlines() is less than this many rows
  157217. * high, space and time will be wasted due to unnecessary data copying.
  157218. * Usually rec_outbuf_height will be 1 or 2, at most 4.
  157219. */
  157220. /* When quantizing colors, the output colormap is described by these fields.
  157221. * The application can supply a colormap by setting colormap non-NULL before
  157222. * calling jpeg_start_decompress; otherwise a colormap is created during
  157223. * jpeg_start_decompress or jpeg_start_output.
  157224. * The map has out_color_components rows and actual_number_of_colors columns.
  157225. */
  157226. int actual_number_of_colors; /* number of entries in use */
  157227. JSAMPARRAY colormap; /* The color map as a 2-D pixel array */
  157228. /* State variables: these variables indicate the progress of decompression.
  157229. * The application may examine these but must not modify them.
  157230. */
  157231. /* Row index of next scanline to be read from jpeg_read_scanlines().
  157232. * Application may use this to control its processing loop, e.g.,
  157233. * "while (output_scanline < output_height)".
  157234. */
  157235. JDIMENSION output_scanline; /* 0 .. output_height-1 */
  157236. /* Current input scan number and number of iMCU rows completed in scan.
  157237. * These indicate the progress of the decompressor input side.
  157238. */
  157239. int input_scan_number; /* Number of SOS markers seen so far */
  157240. JDIMENSION input_iMCU_row; /* Number of iMCU rows completed */
  157241. /* The "output scan number" is the notional scan being displayed by the
  157242. * output side. The decompressor will not allow output scan/row number
  157243. * to get ahead of input scan/row, but it can fall arbitrarily far behind.
  157244. */
  157245. int output_scan_number; /* Nominal scan number being displayed */
  157246. JDIMENSION output_iMCU_row; /* Number of iMCU rows read */
  157247. /* Current progression status. coef_bits[c][i] indicates the precision
  157248. * with which component c's DCT coefficient i (in zigzag order) is known.
  157249. * It is -1 when no data has yet been received, otherwise it is the point
  157250. * transform (shift) value for the most recent scan of the coefficient
  157251. * (thus, 0 at completion of the progression).
  157252. * This pointer is NULL when reading a non-progressive file.
  157253. */
  157254. int (*coef_bits)[DCTSIZE2]; /* -1 or current Al value for each coef */
  157255. /* Internal JPEG parameters --- the application usually need not look at
  157256. * these fields. Note that the decompressor output side may not use
  157257. * any parameters that can change between scans.
  157258. */
  157259. /* Quantization and Huffman tables are carried forward across input
  157260. * datastreams when processing abbreviated JPEG datastreams.
  157261. */
  157262. JQUANT_TBL * quant_tbl_ptrs[NUM_QUANT_TBLS];
  157263. /* ptrs to coefficient quantization tables, or NULL if not defined */
  157264. JHUFF_TBL * dc_huff_tbl_ptrs[NUM_HUFF_TBLS];
  157265. JHUFF_TBL * ac_huff_tbl_ptrs[NUM_HUFF_TBLS];
  157266. /* ptrs to Huffman coding tables, or NULL if not defined */
  157267. /* These parameters are never carried across datastreams, since they
  157268. * are given in SOF/SOS markers or defined to be reset by SOI.
  157269. */
  157270. int data_precision; /* bits of precision in image data */
  157271. jpeg_component_info * comp_info;
  157272. /* comp_info[i] describes component that appears i'th in SOF */
  157273. boolean progressive_mode; /* TRUE if SOFn specifies progressive mode */
  157274. boolean arith_code; /* TRUE=arithmetic coding, FALSE=Huffman */
  157275. UINT8 arith_dc_L[NUM_ARITH_TBLS]; /* L values for DC arith-coding tables */
  157276. UINT8 arith_dc_U[NUM_ARITH_TBLS]; /* U values for DC arith-coding tables */
  157277. UINT8 arith_ac_K[NUM_ARITH_TBLS]; /* Kx values for AC arith-coding tables */
  157278. unsigned int restart_interval; /* MCUs per restart interval, or 0 for no restart */
  157279. /* These fields record data obtained from optional markers recognized by
  157280. * the JPEG library.
  157281. */
  157282. boolean saw_JFIF_marker; /* TRUE iff a JFIF APP0 marker was found */
  157283. /* Data copied from JFIF marker; only valid if saw_JFIF_marker is TRUE: */
  157284. UINT8 JFIF_major_version; /* JFIF version number */
  157285. UINT8 JFIF_minor_version;
  157286. UINT8 density_unit; /* JFIF code for pixel size units */
  157287. UINT16 X_density; /* Horizontal pixel density */
  157288. UINT16 Y_density; /* Vertical pixel density */
  157289. boolean saw_Adobe_marker; /* TRUE iff an Adobe APP14 marker was found */
  157290. UINT8 Adobe_transform; /* Color transform code from Adobe marker */
  157291. boolean CCIR601_sampling; /* TRUE=first samples are cosited */
  157292. /* Aside from the specific data retained from APPn markers known to the
  157293. * library, the uninterpreted contents of any or all APPn and COM markers
  157294. * can be saved in a list for examination by the application.
  157295. */
  157296. jpeg_saved_marker_ptr marker_list; /* Head of list of saved markers */
  157297. /* Remaining fields are known throughout decompressor, but generally
  157298. * should not be touched by a surrounding application.
  157299. */
  157300. /*
  157301. * These fields are computed during decompression startup
  157302. */
  157303. int max_h_samp_factor; /* largest h_samp_factor */
  157304. int max_v_samp_factor; /* largest v_samp_factor */
  157305. int min_DCT_scaled_size; /* smallest DCT_scaled_size of any component */
  157306. JDIMENSION total_iMCU_rows; /* # of iMCU rows in image */
  157307. /* The coefficient controller's input and output progress is measured in
  157308. * units of "iMCU" (interleaved MCU) rows. These are the same as MCU rows
  157309. * in fully interleaved JPEG scans, but are used whether the scan is
  157310. * interleaved or not. We define an iMCU row as v_samp_factor DCT block
  157311. * rows of each component. Therefore, the IDCT output contains
  157312. * v_samp_factor*DCT_scaled_size sample rows of a component per iMCU row.
  157313. */
  157314. JSAMPLE * sample_range_limit; /* table for fast range-limiting */
  157315. /*
  157316. * These fields are valid during any one scan.
  157317. * They describe the components and MCUs actually appearing in the scan.
  157318. * Note that the decompressor output side must not use these fields.
  157319. */
  157320. int comps_in_scan; /* # of JPEG components in this scan */
  157321. jpeg_component_info * cur_comp_info[MAX_COMPS_IN_SCAN];
  157322. /* *cur_comp_info[i] describes component that appears i'th in SOS */
  157323. JDIMENSION MCUs_per_row; /* # of MCUs across the image */
  157324. JDIMENSION MCU_rows_in_scan; /* # of MCU rows in the image */
  157325. int blocks_in_MCU; /* # of DCT blocks per MCU */
  157326. int MCU_membership[D_MAX_BLOCKS_IN_MCU];
  157327. /* MCU_membership[i] is index in cur_comp_info of component owning */
  157328. /* i'th block in an MCU */
  157329. int Ss, Se, Ah, Al; /* progressive JPEG parameters for scan */
  157330. /* This field is shared between entropy decoder and marker parser.
  157331. * It is either zero or the code of a JPEG marker that has been
  157332. * read from the data source, but has not yet been processed.
  157333. */
  157334. int unread_marker;
  157335. /*
  157336. * Links to decompression subobjects (methods, private variables of modules)
  157337. */
  157338. struct jpeg_decomp_master * master;
  157339. struct jpeg_d_main_controller * main;
  157340. struct jpeg_d_coef_controller * coef;
  157341. struct jpeg_d_post_controller * post;
  157342. struct jpeg_input_controller * inputctl;
  157343. struct jpeg_marker_reader * marker;
  157344. struct jpeg_entropy_decoder * entropy;
  157345. struct jpeg_inverse_dct * idct;
  157346. struct jpeg_upsampler * upsample;
  157347. struct jpeg_color_deconverter * cconvert;
  157348. struct jpeg_color_quantizer * cquantize;
  157349. };
  157350. /* "Object" declarations for JPEG modules that may be supplied or called
  157351. * directly by the surrounding application.
  157352. * As with all objects in the JPEG library, these structs only define the
  157353. * publicly visible methods and state variables of a module. Additional
  157354. * private fields may exist after the public ones.
  157355. */
  157356. /* Error handler object */
  157357. struct jpeg_error_mgr {
  157358. /* Error exit handler: does not return to caller */
  157359. JMETHOD(void, error_exit, (j_common_ptr cinfo));
  157360. /* Conditionally emit a trace or warning message */
  157361. JMETHOD(void, emit_message, (j_common_ptr cinfo, int msg_level));
  157362. /* Routine that actually outputs a trace or error message */
  157363. JMETHOD(void, output_message, (j_common_ptr cinfo));
  157364. /* Format a message string for the most recent JPEG error or message */
  157365. JMETHOD(void, format_message, (j_common_ptr cinfo, char * buffer));
  157366. #define JMSG_LENGTH_MAX 200 /* recommended size of format_message buffer */
  157367. /* Reset error state variables at start of a new image */
  157368. JMETHOD(void, reset_error_mgr, (j_common_ptr cinfo));
  157369. /* The message ID code and any parameters are saved here.
  157370. * A message can have one string parameter or up to 8 int parameters.
  157371. */
  157372. int msg_code;
  157373. #define JMSG_STR_PARM_MAX 80
  157374. union {
  157375. int i[8];
  157376. char s[JMSG_STR_PARM_MAX];
  157377. } msg_parm;
  157378. /* Standard state variables for error facility */
  157379. int trace_level; /* max msg_level that will be displayed */
  157380. /* For recoverable corrupt-data errors, we emit a warning message,
  157381. * but keep going unless emit_message chooses to abort. emit_message
  157382. * should count warnings in num_warnings. The surrounding application
  157383. * can check for bad data by seeing if num_warnings is nonzero at the
  157384. * end of processing.
  157385. */
  157386. long num_warnings; /* number of corrupt-data warnings */
  157387. /* These fields point to the table(s) of error message strings.
  157388. * An application can change the table pointer to switch to a different
  157389. * message list (typically, to change the language in which errors are
  157390. * reported). Some applications may wish to add additional error codes
  157391. * that will be handled by the JPEG library error mechanism; the second
  157392. * table pointer is used for this purpose.
  157393. *
  157394. * First table includes all errors generated by JPEG library itself.
  157395. * Error code 0 is reserved for a "no such error string" message.
  157396. */
  157397. const char * const * jpeg_message_table; /* Library errors */
  157398. int last_jpeg_message; /* Table contains strings 0..last_jpeg_message */
  157399. /* Second table can be added by application (see cjpeg/djpeg for example).
  157400. * It contains strings numbered first_addon_message..last_addon_message.
  157401. */
  157402. const char * const * addon_message_table; /* Non-library errors */
  157403. int first_addon_message; /* code for first string in addon table */
  157404. int last_addon_message; /* code for last string in addon table */
  157405. };
  157406. /* Progress monitor object */
  157407. struct jpeg_progress_mgr {
  157408. JMETHOD(void, progress_monitor, (j_common_ptr cinfo));
  157409. long pass_counter; /* work units completed in this pass */
  157410. long pass_limit; /* total number of work units in this pass */
  157411. int completed_passes; /* passes completed so far */
  157412. int total_passes; /* total number of passes expected */
  157413. };
  157414. /* Data destination object for compression */
  157415. struct jpeg_destination_mgr {
  157416. JOCTET * next_output_byte; /* => next byte to write in buffer */
  157417. size_t free_in_buffer; /* # of byte spaces remaining in buffer */
  157418. JMETHOD(void, init_destination, (j_compress_ptr cinfo));
  157419. JMETHOD(boolean, empty_output_buffer, (j_compress_ptr cinfo));
  157420. JMETHOD(void, term_destination, (j_compress_ptr cinfo));
  157421. };
  157422. /* Data source object for decompression */
  157423. struct jpeg_source_mgr {
  157424. const JOCTET * next_input_byte; /* => next byte to read from buffer */
  157425. size_t bytes_in_buffer; /* # of bytes remaining in buffer */
  157426. JMETHOD(void, init_source, (j_decompress_ptr cinfo));
  157427. JMETHOD(boolean, fill_input_buffer, (j_decompress_ptr cinfo));
  157428. JMETHOD(void, skip_input_data, (j_decompress_ptr cinfo, long num_bytes));
  157429. JMETHOD(boolean, resync_to_restart, (j_decompress_ptr cinfo, int desired));
  157430. JMETHOD(void, term_source, (j_decompress_ptr cinfo));
  157431. };
  157432. /* Memory manager object.
  157433. * Allocates "small" objects (a few K total), "large" objects (tens of K),
  157434. * and "really big" objects (virtual arrays with backing store if needed).
  157435. * The memory manager does not allow individual objects to be freed; rather,
  157436. * each created object is assigned to a pool, and whole pools can be freed
  157437. * at once. This is faster and more convenient than remembering exactly what
  157438. * to free, especially where malloc()/free() are not too speedy.
  157439. * NB: alloc routines never return NULL. They exit to error_exit if not
  157440. * successful.
  157441. */
  157442. #define JPOOL_PERMANENT 0 /* lasts until master record is destroyed */
  157443. #define JPOOL_IMAGE 1 /* lasts until done with image/datastream */
  157444. #define JPOOL_NUMPOOLS 2
  157445. typedef struct jvirt_sarray_control * jvirt_sarray_ptr;
  157446. typedef struct jvirt_barray_control * jvirt_barray_ptr;
  157447. struct jpeg_memory_mgr {
  157448. /* Method pointers */
  157449. JMETHOD(void *, alloc_small, (j_common_ptr cinfo, int pool_id,
  157450. size_t sizeofobject));
  157451. JMETHOD(void FAR *, alloc_large, (j_common_ptr cinfo, int pool_id,
  157452. size_t sizeofobject));
  157453. JMETHOD(JSAMPARRAY, alloc_sarray, (j_common_ptr cinfo, int pool_id,
  157454. JDIMENSION samplesperrow,
  157455. JDIMENSION numrows));
  157456. JMETHOD(JBLOCKARRAY, alloc_barray, (j_common_ptr cinfo, int pool_id,
  157457. JDIMENSION blocksperrow,
  157458. JDIMENSION numrows));
  157459. JMETHOD(jvirt_sarray_ptr, request_virt_sarray, (j_common_ptr cinfo,
  157460. int pool_id,
  157461. boolean pre_zero,
  157462. JDIMENSION samplesperrow,
  157463. JDIMENSION numrows,
  157464. JDIMENSION maxaccess));
  157465. JMETHOD(jvirt_barray_ptr, request_virt_barray, (j_common_ptr cinfo,
  157466. int pool_id,
  157467. boolean pre_zero,
  157468. JDIMENSION blocksperrow,
  157469. JDIMENSION numrows,
  157470. JDIMENSION maxaccess));
  157471. JMETHOD(void, realize_virt_arrays, (j_common_ptr cinfo));
  157472. JMETHOD(JSAMPARRAY, access_virt_sarray, (j_common_ptr cinfo,
  157473. jvirt_sarray_ptr ptr,
  157474. JDIMENSION start_row,
  157475. JDIMENSION num_rows,
  157476. boolean writable));
  157477. JMETHOD(JBLOCKARRAY, access_virt_barray, (j_common_ptr cinfo,
  157478. jvirt_barray_ptr ptr,
  157479. JDIMENSION start_row,
  157480. JDIMENSION num_rows,
  157481. boolean writable));
  157482. JMETHOD(void, free_pool, (j_common_ptr cinfo, int pool_id));
  157483. JMETHOD(void, self_destruct, (j_common_ptr cinfo));
  157484. /* Limit on memory allocation for this JPEG object. (Note that this is
  157485. * merely advisory, not a guaranteed maximum; it only affects the space
  157486. * used for virtual-array buffers.) May be changed by outer application
  157487. * after creating the JPEG object.
  157488. */
  157489. long max_memory_to_use;
  157490. /* Maximum allocation request accepted by alloc_large. */
  157491. long max_alloc_chunk;
  157492. };
  157493. /* Routine signature for application-supplied marker processing methods.
  157494. * Need not pass marker code since it is stored in cinfo->unread_marker.
  157495. */
  157496. typedef JMETHOD(boolean, jpeg_marker_parser_method, (j_decompress_ptr cinfo));
  157497. /* Declarations for routines called by application.
  157498. * The JPP macro hides prototype parameters from compilers that can't cope.
  157499. * Note JPP requires double parentheses.
  157500. */
  157501. #ifdef HAVE_PROTOTYPES
  157502. #define JPP(arglist) arglist
  157503. #else
  157504. #define JPP(arglist) ()
  157505. #endif
  157506. /* Short forms of external names for systems with brain-damaged linkers.
  157507. * We shorten external names to be unique in the first six letters, which
  157508. * is good enough for all known systems.
  157509. * (If your compiler itself needs names to be unique in less than 15
  157510. * characters, you are out of luck. Get a better compiler.)
  157511. */
  157512. #ifdef NEED_SHORT_EXTERNAL_NAMES
  157513. #define jpeg_std_error jStdError
  157514. #define jpeg_CreateCompress jCreaCompress
  157515. #define jpeg_CreateDecompress jCreaDecompress
  157516. #define jpeg_destroy_compress jDestCompress
  157517. #define jpeg_destroy_decompress jDestDecompress
  157518. #define jpeg_stdio_dest jStdDest
  157519. #define jpeg_stdio_src jStdSrc
  157520. #define jpeg_set_defaults jSetDefaults
  157521. #define jpeg_set_colorspace jSetColorspace
  157522. #define jpeg_default_colorspace jDefColorspace
  157523. #define jpeg_set_quality jSetQuality
  157524. #define jpeg_set_linear_quality jSetLQuality
  157525. #define jpeg_add_quant_table jAddQuantTable
  157526. #define jpeg_quality_scaling jQualityScaling
  157527. #define jpeg_simple_progression jSimProgress
  157528. #define jpeg_suppress_tables jSuppressTables
  157529. #define jpeg_alloc_quant_table jAlcQTable
  157530. #define jpeg_alloc_huff_table jAlcHTable
  157531. #define jpeg_start_compress jStrtCompress
  157532. #define jpeg_write_scanlines jWrtScanlines
  157533. #define jpeg_finish_compress jFinCompress
  157534. #define jpeg_write_raw_data jWrtRawData
  157535. #define jpeg_write_marker jWrtMarker
  157536. #define jpeg_write_m_header jWrtMHeader
  157537. #define jpeg_write_m_byte jWrtMByte
  157538. #define jpeg_write_tables jWrtTables
  157539. #define jpeg_read_header jReadHeader
  157540. #define jpeg_start_decompress jStrtDecompress
  157541. #define jpeg_read_scanlines jReadScanlines
  157542. #define jpeg_finish_decompress jFinDecompress
  157543. #define jpeg_read_raw_data jReadRawData
  157544. #define jpeg_has_multiple_scans jHasMultScn
  157545. #define jpeg_start_output jStrtOutput
  157546. #define jpeg_finish_output jFinOutput
  157547. #define jpeg_input_complete jInComplete
  157548. #define jpeg_new_colormap jNewCMap
  157549. #define jpeg_consume_input jConsumeInput
  157550. #define jpeg_calc_output_dimensions jCalcDimensions
  157551. #define jpeg_save_markers jSaveMarkers
  157552. #define jpeg_set_marker_processor jSetMarker
  157553. #define jpeg_read_coefficients jReadCoefs
  157554. #define jpeg_write_coefficients jWrtCoefs
  157555. #define jpeg_copy_critical_parameters jCopyCrit
  157556. #define jpeg_abort_compress jAbrtCompress
  157557. #define jpeg_abort_decompress jAbrtDecompress
  157558. #define jpeg_abort jAbort
  157559. #define jpeg_destroy jDestroy
  157560. #define jpeg_resync_to_restart jResyncRestart
  157561. #endif /* NEED_SHORT_EXTERNAL_NAMES */
  157562. /* Default error-management setup */
  157563. EXTERN(struct jpeg_error_mgr *) jpeg_std_error
  157564. JPP((struct jpeg_error_mgr * err));
  157565. /* Initialization of JPEG compression objects.
  157566. * jpeg_create_compress() and jpeg_create_decompress() are the exported
  157567. * names that applications should call. These expand to calls on
  157568. * jpeg_CreateCompress and jpeg_CreateDecompress with additional information
  157569. * passed for version mismatch checking.
  157570. * NB: you must set up the error-manager BEFORE calling jpeg_create_xxx.
  157571. */
  157572. #define jpeg_create_compress(cinfo) \
  157573. jpeg_CreateCompress((cinfo), JPEG_LIB_VERSION, \
  157574. (size_t) sizeof(struct jpeg_compress_struct))
  157575. #define jpeg_create_decompress(cinfo) \
  157576. jpeg_CreateDecompress((cinfo), JPEG_LIB_VERSION, \
  157577. (size_t) sizeof(struct jpeg_decompress_struct))
  157578. EXTERN(void) jpeg_CreateCompress JPP((j_compress_ptr cinfo,
  157579. int version, size_t structsize));
  157580. EXTERN(void) jpeg_CreateDecompress JPP((j_decompress_ptr cinfo,
  157581. int version, size_t structsize));
  157582. /* Destruction of JPEG compression objects */
  157583. EXTERN(void) jpeg_destroy_compress JPP((j_compress_ptr cinfo));
  157584. EXTERN(void) jpeg_destroy_decompress JPP((j_decompress_ptr cinfo));
  157585. /* Standard data source and destination managers: stdio streams. */
  157586. /* Caller is responsible for opening the file before and closing after. */
  157587. EXTERN(void) jpeg_stdio_dest JPP((j_compress_ptr cinfo, FILE * outfile));
  157588. EXTERN(void) jpeg_stdio_src JPP((j_decompress_ptr cinfo, FILE * infile));
  157589. /* Default parameter setup for compression */
  157590. EXTERN(void) jpeg_set_defaults JPP((j_compress_ptr cinfo));
  157591. /* Compression parameter setup aids */
  157592. EXTERN(void) jpeg_set_colorspace JPP((j_compress_ptr cinfo,
  157593. J_COLOR_SPACE colorspace));
  157594. EXTERN(void) jpeg_default_colorspace JPP((j_compress_ptr cinfo));
  157595. EXTERN(void) jpeg_set_quality JPP((j_compress_ptr cinfo, int quality,
  157596. boolean force_baseline));
  157597. EXTERN(void) jpeg_set_linear_quality JPP((j_compress_ptr cinfo,
  157598. int scale_factor,
  157599. boolean force_baseline));
  157600. EXTERN(void) jpeg_add_quant_table JPP((j_compress_ptr cinfo, int which_tbl,
  157601. const unsigned int *basic_table,
  157602. int scale_factor,
  157603. boolean force_baseline));
  157604. EXTERN(int) jpeg_quality_scaling JPP((int quality));
  157605. EXTERN(void) jpeg_simple_progression JPP((j_compress_ptr cinfo));
  157606. EXTERN(void) jpeg_suppress_tables JPP((j_compress_ptr cinfo,
  157607. boolean suppress));
  157608. EXTERN(JQUANT_TBL *) jpeg_alloc_quant_table JPP((j_common_ptr cinfo));
  157609. EXTERN(JHUFF_TBL *) jpeg_alloc_huff_table JPP((j_common_ptr cinfo));
  157610. /* Main entry points for compression */
  157611. EXTERN(void) jpeg_start_compress JPP((j_compress_ptr cinfo,
  157612. boolean write_all_tables));
  157613. EXTERN(JDIMENSION) jpeg_write_scanlines JPP((j_compress_ptr cinfo,
  157614. JSAMPARRAY scanlines,
  157615. JDIMENSION num_lines));
  157616. EXTERN(void) jpeg_finish_compress JPP((j_compress_ptr cinfo));
  157617. /* Replaces jpeg_write_scanlines when writing raw downsampled data. */
  157618. EXTERN(JDIMENSION) jpeg_write_raw_data JPP((j_compress_ptr cinfo,
  157619. JSAMPIMAGE data,
  157620. JDIMENSION num_lines));
  157621. /* Write a special marker. See libjpeg.doc concerning safe usage. */
  157622. EXTERN(void) jpeg_write_marker
  157623. JPP((j_compress_ptr cinfo, int marker,
  157624. const JOCTET * dataptr, unsigned int datalen));
  157625. /* Same, but piecemeal. */
  157626. EXTERN(void) jpeg_write_m_header
  157627. JPP((j_compress_ptr cinfo, int marker, unsigned int datalen));
  157628. EXTERN(void) jpeg_write_m_byte
  157629. JPP((j_compress_ptr cinfo, int val));
  157630. /* Alternate compression function: just write an abbreviated table file */
  157631. EXTERN(void) jpeg_write_tables JPP((j_compress_ptr cinfo));
  157632. /* Decompression startup: read start of JPEG datastream to see what's there */
  157633. EXTERN(int) jpeg_read_header JPP((j_decompress_ptr cinfo,
  157634. boolean require_image));
  157635. /* Return value is one of: */
  157636. #define JPEG_SUSPENDED 0 /* Suspended due to lack of input data */
  157637. #define JPEG_HEADER_OK 1 /* Found valid image datastream */
  157638. #define JPEG_HEADER_TABLES_ONLY 2 /* Found valid table-specs-only datastream */
  157639. /* If you pass require_image = TRUE (normal case), you need not check for
  157640. * a TABLES_ONLY return code; an abbreviated file will cause an error exit.
  157641. * JPEG_SUSPENDED is only possible if you use a data source module that can
  157642. * give a suspension return (the stdio source module doesn't).
  157643. */
  157644. /* Main entry points for decompression */
  157645. EXTERN(boolean) jpeg_start_decompress JPP((j_decompress_ptr cinfo));
  157646. EXTERN(JDIMENSION) jpeg_read_scanlines JPP((j_decompress_ptr cinfo,
  157647. JSAMPARRAY scanlines,
  157648. JDIMENSION max_lines));
  157649. EXTERN(boolean) jpeg_finish_decompress JPP((j_decompress_ptr cinfo));
  157650. /* Replaces jpeg_read_scanlines when reading raw downsampled data. */
  157651. EXTERN(JDIMENSION) jpeg_read_raw_data JPP((j_decompress_ptr cinfo,
  157652. JSAMPIMAGE data,
  157653. JDIMENSION max_lines));
  157654. /* Additional entry points for buffered-image mode. */
  157655. EXTERN(boolean) jpeg_has_multiple_scans JPP((j_decompress_ptr cinfo));
  157656. EXTERN(boolean) jpeg_start_output JPP((j_decompress_ptr cinfo,
  157657. int scan_number));
  157658. EXTERN(boolean) jpeg_finish_output JPP((j_decompress_ptr cinfo));
  157659. EXTERN(boolean) jpeg_input_complete JPP((j_decompress_ptr cinfo));
  157660. EXTERN(void) jpeg_new_colormap JPP((j_decompress_ptr cinfo));
  157661. EXTERN(int) jpeg_consume_input JPP((j_decompress_ptr cinfo));
  157662. /* Return value is one of: */
  157663. /* #define JPEG_SUSPENDED 0 Suspended due to lack of input data */
  157664. #define JPEG_REACHED_SOS 1 /* Reached start of new scan */
  157665. #define JPEG_REACHED_EOI 2 /* Reached end of image */
  157666. #define JPEG_ROW_COMPLETED 3 /* Completed one iMCU row */
  157667. #define JPEG_SCAN_COMPLETED 4 /* Completed last iMCU row of a scan */
  157668. /* Precalculate output dimensions for current decompression parameters. */
  157669. EXTERN(void) jpeg_calc_output_dimensions JPP((j_decompress_ptr cinfo));
  157670. /* Control saving of COM and APPn markers into marker_list. */
  157671. EXTERN(void) jpeg_save_markers
  157672. JPP((j_decompress_ptr cinfo, int marker_code,
  157673. unsigned int length_limit));
  157674. /* Install a special processing method for COM or APPn markers. */
  157675. EXTERN(void) jpeg_set_marker_processor
  157676. JPP((j_decompress_ptr cinfo, int marker_code,
  157677. jpeg_marker_parser_method routine));
  157678. /* Read or write raw DCT coefficients --- useful for lossless transcoding. */
  157679. EXTERN(jvirt_barray_ptr *) jpeg_read_coefficients JPP((j_decompress_ptr cinfo));
  157680. EXTERN(void) jpeg_write_coefficients JPP((j_compress_ptr cinfo,
  157681. jvirt_barray_ptr * coef_arrays));
  157682. EXTERN(void) jpeg_copy_critical_parameters JPP((j_decompress_ptr srcinfo,
  157683. j_compress_ptr dstinfo));
  157684. /* If you choose to abort compression or decompression before completing
  157685. * jpeg_finish_(de)compress, then you need to clean up to release memory,
  157686. * temporary files, etc. You can just call jpeg_destroy_(de)compress
  157687. * if you're done with the JPEG object, but if you want to clean it up and
  157688. * reuse it, call this:
  157689. */
  157690. EXTERN(void) jpeg_abort_compress JPP((j_compress_ptr cinfo));
  157691. EXTERN(void) jpeg_abort_decompress JPP((j_decompress_ptr cinfo));
  157692. /* Generic versions of jpeg_abort and jpeg_destroy that work on either
  157693. * flavor of JPEG object. These may be more convenient in some places.
  157694. */
  157695. EXTERN(void) jpeg_abort JPP((j_common_ptr cinfo));
  157696. EXTERN(void) jpeg_destroy JPP((j_common_ptr cinfo));
  157697. /* Default restart-marker-resync procedure for use by data source modules */
  157698. EXTERN(boolean) jpeg_resync_to_restart JPP((j_decompress_ptr cinfo,
  157699. int desired));
  157700. /* These marker codes are exported since applications and data source modules
  157701. * are likely to want to use them.
  157702. */
  157703. #define JPEG_RST0 0xD0 /* RST0 marker code */
  157704. #define JPEG_EOI 0xD9 /* EOI marker code */
  157705. #define JPEG_APP0 0xE0 /* APP0 marker code */
  157706. #define JPEG_COM 0xFE /* COM marker code */
  157707. /* If we have a brain-damaged compiler that emits warnings (or worse, errors)
  157708. * for structure definitions that are never filled in, keep it quiet by
  157709. * supplying dummy definitions for the various substructures.
  157710. */
  157711. #ifdef INCOMPLETE_TYPES_BROKEN
  157712. #ifndef JPEG_INTERNALS /* will be defined in jpegint.h */
  157713. struct jvirt_sarray_control { long dummy; };
  157714. struct jvirt_barray_control { long dummy; };
  157715. struct jpeg_comp_master { long dummy; };
  157716. struct jpeg_c_main_controller { long dummy; };
  157717. struct jpeg_c_prep_controller { long dummy; };
  157718. struct jpeg_c_coef_controller { long dummy; };
  157719. struct jpeg_marker_writer { long dummy; };
  157720. struct jpeg_color_converter { long dummy; };
  157721. struct jpeg_downsampler { long dummy; };
  157722. struct jpeg_forward_dct { long dummy; };
  157723. struct jpeg_entropy_encoder { long dummy; };
  157724. struct jpeg_decomp_master { long dummy; };
  157725. struct jpeg_d_main_controller { long dummy; };
  157726. struct jpeg_d_coef_controller { long dummy; };
  157727. struct jpeg_d_post_controller { long dummy; };
  157728. struct jpeg_input_controller { long dummy; };
  157729. struct jpeg_marker_reader { long dummy; };
  157730. struct jpeg_entropy_decoder { long dummy; };
  157731. struct jpeg_inverse_dct { long dummy; };
  157732. struct jpeg_upsampler { long dummy; };
  157733. struct jpeg_color_deconverter { long dummy; };
  157734. struct jpeg_color_quantizer { long dummy; };
  157735. #endif /* JPEG_INTERNALS */
  157736. #endif /* INCOMPLETE_TYPES_BROKEN */
  157737. /*
  157738. * The JPEG library modules define JPEG_INTERNALS before including this file.
  157739. * The internal structure declarations are read only when that is true.
  157740. * Applications using the library should not include jpegint.h, but may wish
  157741. * to include jerror.h.
  157742. */
  157743. #ifdef JPEG_INTERNALS
  157744. /*** Start of inlined file: jpegint.h ***/
  157745. /* Declarations for both compression & decompression */
  157746. typedef enum { /* Operating modes for buffer controllers */
  157747. JBUF_PASS_THRU, /* Plain stripwise operation */
  157748. /* Remaining modes require a full-image buffer to have been created */
  157749. JBUF_SAVE_SOURCE, /* Run source subobject only, save output */
  157750. JBUF_CRANK_DEST, /* Run dest subobject only, using saved data */
  157751. JBUF_SAVE_AND_PASS /* Run both subobjects, save output */
  157752. } J_BUF_MODE;
  157753. /* Values of global_state field (jdapi.c has some dependencies on ordering!) */
  157754. #define CSTATE_START 100 /* after create_compress */
  157755. #define CSTATE_SCANNING 101 /* start_compress done, write_scanlines OK */
  157756. #define CSTATE_RAW_OK 102 /* start_compress done, write_raw_data OK */
  157757. #define CSTATE_WRCOEFS 103 /* jpeg_write_coefficients done */
  157758. #define DSTATE_START 200 /* after create_decompress */
  157759. #define DSTATE_INHEADER 201 /* reading header markers, no SOS yet */
  157760. #define DSTATE_READY 202 /* found SOS, ready for start_decompress */
  157761. #define DSTATE_PRELOAD 203 /* reading multiscan file in start_decompress*/
  157762. #define DSTATE_PRESCAN 204 /* performing dummy pass for 2-pass quant */
  157763. #define DSTATE_SCANNING 205 /* start_decompress done, read_scanlines OK */
  157764. #define DSTATE_RAW_OK 206 /* start_decompress done, read_raw_data OK */
  157765. #define DSTATE_BUFIMAGE 207 /* expecting jpeg_start_output */
  157766. #define DSTATE_BUFPOST 208 /* looking for SOS/EOI in jpeg_finish_output */
  157767. #define DSTATE_RDCOEFS 209 /* reading file in jpeg_read_coefficients */
  157768. #define DSTATE_STOPPING 210 /* looking for EOI in jpeg_finish_decompress */
  157769. /* Declarations for compression modules */
  157770. /* Master control module */
  157771. struct jpeg_comp_master {
  157772. JMETHOD(void, prepare_for_pass, (j_compress_ptr cinfo));
  157773. JMETHOD(void, pass_startup, (j_compress_ptr cinfo));
  157774. JMETHOD(void, finish_pass, (j_compress_ptr cinfo));
  157775. /* State variables made visible to other modules */
  157776. boolean call_pass_startup; /* True if pass_startup must be called */
  157777. boolean is_last_pass; /* True during last pass */
  157778. };
  157779. /* Main buffer control (downsampled-data buffer) */
  157780. struct jpeg_c_main_controller {
  157781. JMETHOD(void, start_pass, (j_compress_ptr cinfo, J_BUF_MODE pass_mode));
  157782. JMETHOD(void, process_data, (j_compress_ptr cinfo,
  157783. JSAMPARRAY input_buf, JDIMENSION *in_row_ctr,
  157784. JDIMENSION in_rows_avail));
  157785. };
  157786. /* Compression preprocessing (downsampling input buffer control) */
  157787. struct jpeg_c_prep_controller {
  157788. JMETHOD(void, start_pass, (j_compress_ptr cinfo, J_BUF_MODE pass_mode));
  157789. JMETHOD(void, pre_process_data, (j_compress_ptr cinfo,
  157790. JSAMPARRAY input_buf,
  157791. JDIMENSION *in_row_ctr,
  157792. JDIMENSION in_rows_avail,
  157793. JSAMPIMAGE output_buf,
  157794. JDIMENSION *out_row_group_ctr,
  157795. JDIMENSION out_row_groups_avail));
  157796. };
  157797. /* Coefficient buffer control */
  157798. struct jpeg_c_coef_controller {
  157799. JMETHOD(void, start_pass, (j_compress_ptr cinfo, J_BUF_MODE pass_mode));
  157800. JMETHOD(boolean, compress_data, (j_compress_ptr cinfo,
  157801. JSAMPIMAGE input_buf));
  157802. };
  157803. /* Colorspace conversion */
  157804. struct jpeg_color_converter {
  157805. JMETHOD(void, start_pass, (j_compress_ptr cinfo));
  157806. JMETHOD(void, color_convert, (j_compress_ptr cinfo,
  157807. JSAMPARRAY input_buf, JSAMPIMAGE output_buf,
  157808. JDIMENSION output_row, int num_rows));
  157809. };
  157810. /* Downsampling */
  157811. struct jpeg_downsampler {
  157812. JMETHOD(void, start_pass, (j_compress_ptr cinfo));
  157813. JMETHOD(void, downsample, (j_compress_ptr cinfo,
  157814. JSAMPIMAGE input_buf, JDIMENSION in_row_index,
  157815. JSAMPIMAGE output_buf,
  157816. JDIMENSION out_row_group_index));
  157817. boolean need_context_rows; /* TRUE if need rows above & below */
  157818. };
  157819. /* Forward DCT (also controls coefficient quantization) */
  157820. struct jpeg_forward_dct {
  157821. JMETHOD(void, start_pass, (j_compress_ptr cinfo));
  157822. /* perhaps this should be an array??? */
  157823. JMETHOD(void, forward_DCT, (j_compress_ptr cinfo,
  157824. jpeg_component_info * compptr,
  157825. JSAMPARRAY sample_data, JBLOCKROW coef_blocks,
  157826. JDIMENSION start_row, JDIMENSION start_col,
  157827. JDIMENSION num_blocks));
  157828. };
  157829. /* Entropy encoding */
  157830. struct jpeg_entropy_encoder {
  157831. JMETHOD(void, start_pass, (j_compress_ptr cinfo, boolean gather_statistics));
  157832. JMETHOD(boolean, encode_mcu, (j_compress_ptr cinfo, JBLOCKROW *MCU_data));
  157833. JMETHOD(void, finish_pass, (j_compress_ptr cinfo));
  157834. };
  157835. /* Marker writing */
  157836. struct jpeg_marker_writer {
  157837. JMETHOD(void, write_file_header, (j_compress_ptr cinfo));
  157838. JMETHOD(void, write_frame_header, (j_compress_ptr cinfo));
  157839. JMETHOD(void, write_scan_header, (j_compress_ptr cinfo));
  157840. JMETHOD(void, write_file_trailer, (j_compress_ptr cinfo));
  157841. JMETHOD(void, write_tables_only, (j_compress_ptr cinfo));
  157842. /* These routines are exported to allow insertion of extra markers */
  157843. /* Probably only COM and APPn markers should be written this way */
  157844. JMETHOD(void, write_marker_header, (j_compress_ptr cinfo, int marker,
  157845. unsigned int datalen));
  157846. JMETHOD(void, write_marker_byte, (j_compress_ptr cinfo, int val));
  157847. };
  157848. /* Declarations for decompression modules */
  157849. /* Master control module */
  157850. struct jpeg_decomp_master {
  157851. JMETHOD(void, prepare_for_output_pass, (j_decompress_ptr cinfo));
  157852. JMETHOD(void, finish_output_pass, (j_decompress_ptr cinfo));
  157853. /* State variables made visible to other modules */
  157854. boolean is_dummy_pass; /* True during 1st pass for 2-pass quant */
  157855. };
  157856. /* Input control module */
  157857. struct jpeg_input_controller {
  157858. JMETHOD(int, consume_input, (j_decompress_ptr cinfo));
  157859. JMETHOD(void, reset_input_controller, (j_decompress_ptr cinfo));
  157860. JMETHOD(void, start_input_pass, (j_decompress_ptr cinfo));
  157861. JMETHOD(void, finish_input_pass, (j_decompress_ptr cinfo));
  157862. /* State variables made visible to other modules */
  157863. boolean has_multiple_scans; /* True if file has multiple scans */
  157864. boolean eoi_reached; /* True when EOI has been consumed */
  157865. };
  157866. /* Main buffer control (downsampled-data buffer) */
  157867. struct jpeg_d_main_controller {
  157868. JMETHOD(void, start_pass, (j_decompress_ptr cinfo, J_BUF_MODE pass_mode));
  157869. JMETHOD(void, process_data, (j_decompress_ptr cinfo,
  157870. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  157871. JDIMENSION out_rows_avail));
  157872. };
  157873. /* Coefficient buffer control */
  157874. struct jpeg_d_coef_controller {
  157875. JMETHOD(void, start_input_pass, (j_decompress_ptr cinfo));
  157876. JMETHOD(int, consume_data, (j_decompress_ptr cinfo));
  157877. JMETHOD(void, start_output_pass, (j_decompress_ptr cinfo));
  157878. JMETHOD(int, decompress_data, (j_decompress_ptr cinfo,
  157879. JSAMPIMAGE output_buf));
  157880. /* Pointer to array of coefficient virtual arrays, or NULL if none */
  157881. jvirt_barray_ptr *coef_arrays;
  157882. };
  157883. /* Decompression postprocessing (color quantization buffer control) */
  157884. struct jpeg_d_post_controller {
  157885. JMETHOD(void, start_pass, (j_decompress_ptr cinfo, J_BUF_MODE pass_mode));
  157886. JMETHOD(void, post_process_data, (j_decompress_ptr cinfo,
  157887. JSAMPIMAGE input_buf,
  157888. JDIMENSION *in_row_group_ctr,
  157889. JDIMENSION in_row_groups_avail,
  157890. JSAMPARRAY output_buf,
  157891. JDIMENSION *out_row_ctr,
  157892. JDIMENSION out_rows_avail));
  157893. };
  157894. /* Marker reading & parsing */
  157895. struct jpeg_marker_reader {
  157896. JMETHOD(void, reset_marker_reader, (j_decompress_ptr cinfo));
  157897. /* Read markers until SOS or EOI.
  157898. * Returns same codes as are defined for jpeg_consume_input:
  157899. * JPEG_SUSPENDED, JPEG_REACHED_SOS, or JPEG_REACHED_EOI.
  157900. */
  157901. JMETHOD(int, read_markers, (j_decompress_ptr cinfo));
  157902. /* Read a restart marker --- exported for use by entropy decoder only */
  157903. jpeg_marker_parser_method read_restart_marker;
  157904. /* State of marker reader --- nominally internal, but applications
  157905. * supplying COM or APPn handlers might like to know the state.
  157906. */
  157907. boolean saw_SOI; /* found SOI? */
  157908. boolean saw_SOF; /* found SOF? */
  157909. int next_restart_num; /* next restart number expected (0-7) */
  157910. unsigned int discarded_bytes; /* # of bytes skipped looking for a marker */
  157911. };
  157912. /* Entropy decoding */
  157913. struct jpeg_entropy_decoder {
  157914. JMETHOD(void, start_pass, (j_decompress_ptr cinfo));
  157915. JMETHOD(boolean, decode_mcu, (j_decompress_ptr cinfo,
  157916. JBLOCKROW *MCU_data));
  157917. /* This is here to share code between baseline and progressive decoders; */
  157918. /* other modules probably should not use it */
  157919. boolean insufficient_data; /* set TRUE after emitting warning */
  157920. };
  157921. /* Inverse DCT (also performs dequantization) */
  157922. typedef JMETHOD(void, inverse_DCT_method_ptr,
  157923. (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  157924. JCOEFPTR coef_block,
  157925. JSAMPARRAY output_buf, JDIMENSION output_col));
  157926. struct jpeg_inverse_dct {
  157927. JMETHOD(void, start_pass, (j_decompress_ptr cinfo));
  157928. /* It is useful to allow each component to have a separate IDCT method. */
  157929. inverse_DCT_method_ptr inverse_DCT[MAX_COMPONENTS];
  157930. };
  157931. /* Upsampling (note that upsampler must also call color converter) */
  157932. struct jpeg_upsampler {
  157933. JMETHOD(void, start_pass, (j_decompress_ptr cinfo));
  157934. JMETHOD(void, upsample, (j_decompress_ptr cinfo,
  157935. JSAMPIMAGE input_buf,
  157936. JDIMENSION *in_row_group_ctr,
  157937. JDIMENSION in_row_groups_avail,
  157938. JSAMPARRAY output_buf,
  157939. JDIMENSION *out_row_ctr,
  157940. JDIMENSION out_rows_avail));
  157941. boolean need_context_rows; /* TRUE if need rows above & below */
  157942. };
  157943. /* Colorspace conversion */
  157944. struct jpeg_color_deconverter {
  157945. JMETHOD(void, start_pass, (j_decompress_ptr cinfo));
  157946. JMETHOD(void, color_convert, (j_decompress_ptr cinfo,
  157947. JSAMPIMAGE input_buf, JDIMENSION input_row,
  157948. JSAMPARRAY output_buf, int num_rows));
  157949. };
  157950. /* Color quantization or color precision reduction */
  157951. struct jpeg_color_quantizer {
  157952. JMETHOD(void, start_pass, (j_decompress_ptr cinfo, boolean is_pre_scan));
  157953. JMETHOD(void, color_quantize, (j_decompress_ptr cinfo,
  157954. JSAMPARRAY input_buf, JSAMPARRAY output_buf,
  157955. int num_rows));
  157956. JMETHOD(void, finish_pass, (j_decompress_ptr cinfo));
  157957. JMETHOD(void, new_color_map, (j_decompress_ptr cinfo));
  157958. };
  157959. /* Miscellaneous useful macros */
  157960. #undef MAX
  157961. #define MAX(a,b) ((a) > (b) ? (a) : (b))
  157962. #undef MIN
  157963. #define MIN(a,b) ((a) < (b) ? (a) : (b))
  157964. /* We assume that right shift corresponds to signed division by 2 with
  157965. * rounding towards minus infinity. This is correct for typical "arithmetic
  157966. * shift" instructions that shift in copies of the sign bit. But some
  157967. * C compilers implement >> with an unsigned shift. For these machines you
  157968. * must define RIGHT_SHIFT_IS_UNSIGNED.
  157969. * RIGHT_SHIFT provides a proper signed right shift of an INT32 quantity.
  157970. * It is only applied with constant shift counts. SHIFT_TEMPS must be
  157971. * included in the variables of any routine using RIGHT_SHIFT.
  157972. */
  157973. #ifdef RIGHT_SHIFT_IS_UNSIGNED
  157974. #define SHIFT_TEMPS INT32 shift_temp;
  157975. #define RIGHT_SHIFT(x,shft) \
  157976. ((shift_temp = (x)) < 0 ? \
  157977. (shift_temp >> (shft)) | ((~((INT32) 0)) << (32-(shft))) : \
  157978. (shift_temp >> (shft)))
  157979. #else
  157980. #define SHIFT_TEMPS
  157981. #define RIGHT_SHIFT(x,shft) ((x) >> (shft))
  157982. #endif
  157983. /* Short forms of external names for systems with brain-damaged linkers. */
  157984. #ifdef NEED_SHORT_EXTERNAL_NAMES
  157985. #define jinit_compress_master jICompress
  157986. #define jinit_c_master_control jICMaster
  157987. #define jinit_c_main_controller jICMainC
  157988. #define jinit_c_prep_controller jICPrepC
  157989. #define jinit_c_coef_controller jICCoefC
  157990. #define jinit_color_converter jICColor
  157991. #define jinit_downsampler jIDownsampler
  157992. #define jinit_forward_dct jIFDCT
  157993. #define jinit_huff_encoder jIHEncoder
  157994. #define jinit_phuff_encoder jIPHEncoder
  157995. #define jinit_marker_writer jIMWriter
  157996. #define jinit_master_decompress jIDMaster
  157997. #define jinit_d_main_controller jIDMainC
  157998. #define jinit_d_coef_controller jIDCoefC
  157999. #define jinit_d_post_controller jIDPostC
  158000. #define jinit_input_controller jIInCtlr
  158001. #define jinit_marker_reader jIMReader
  158002. #define jinit_huff_decoder jIHDecoder
  158003. #define jinit_phuff_decoder jIPHDecoder
  158004. #define jinit_inverse_dct jIIDCT
  158005. #define jinit_upsampler jIUpsampler
  158006. #define jinit_color_deconverter jIDColor
  158007. #define jinit_1pass_quantizer jI1Quant
  158008. #define jinit_2pass_quantizer jI2Quant
  158009. #define jinit_merged_upsampler jIMUpsampler
  158010. #define jinit_memory_mgr jIMemMgr
  158011. #define jdiv_round_up jDivRound
  158012. #define jround_up jRound
  158013. #define jcopy_sample_rows jCopySamples
  158014. #define jcopy_block_row jCopyBlocks
  158015. #define jzero_far jZeroFar
  158016. #define jpeg_zigzag_order jZIGTable
  158017. #define jpeg_natural_order jZAGTable
  158018. #endif /* NEED_SHORT_EXTERNAL_NAMES */
  158019. /* Compression module initialization routines */
  158020. EXTERN(void) jinit_compress_master JPP((j_compress_ptr cinfo));
  158021. EXTERN(void) jinit_c_master_control JPP((j_compress_ptr cinfo,
  158022. boolean transcode_only));
  158023. EXTERN(void) jinit_c_main_controller JPP((j_compress_ptr cinfo,
  158024. boolean need_full_buffer));
  158025. EXTERN(void) jinit_c_prep_controller JPP((j_compress_ptr cinfo,
  158026. boolean need_full_buffer));
  158027. EXTERN(void) jinit_c_coef_controller JPP((j_compress_ptr cinfo,
  158028. boolean need_full_buffer));
  158029. EXTERN(void) jinit_color_converter JPP((j_compress_ptr cinfo));
  158030. EXTERN(void) jinit_downsampler JPP((j_compress_ptr cinfo));
  158031. EXTERN(void) jinit_forward_dct JPP((j_compress_ptr cinfo));
  158032. EXTERN(void) jinit_huff_encoder JPP((j_compress_ptr cinfo));
  158033. EXTERN(void) jinit_phuff_encoder JPP((j_compress_ptr cinfo));
  158034. EXTERN(void) jinit_marker_writer JPP((j_compress_ptr cinfo));
  158035. /* Decompression module initialization routines */
  158036. EXTERN(void) jinit_master_decompress JPP((j_decompress_ptr cinfo));
  158037. EXTERN(void) jinit_d_main_controller JPP((j_decompress_ptr cinfo,
  158038. boolean need_full_buffer));
  158039. EXTERN(void) jinit_d_coef_controller JPP((j_decompress_ptr cinfo,
  158040. boolean need_full_buffer));
  158041. EXTERN(void) jinit_d_post_controller JPP((j_decompress_ptr cinfo,
  158042. boolean need_full_buffer));
  158043. EXTERN(void) jinit_input_controller JPP((j_decompress_ptr cinfo));
  158044. EXTERN(void) jinit_marker_reader JPP((j_decompress_ptr cinfo));
  158045. EXTERN(void) jinit_huff_decoder JPP((j_decompress_ptr cinfo));
  158046. EXTERN(void) jinit_phuff_decoder JPP((j_decompress_ptr cinfo));
  158047. EXTERN(void) jinit_inverse_dct JPP((j_decompress_ptr cinfo));
  158048. EXTERN(void) jinit_upsampler JPP((j_decompress_ptr cinfo));
  158049. EXTERN(void) jinit_color_deconverter JPP((j_decompress_ptr cinfo));
  158050. EXTERN(void) jinit_1pass_quantizer JPP((j_decompress_ptr cinfo));
  158051. EXTERN(void) jinit_2pass_quantizer JPP((j_decompress_ptr cinfo));
  158052. EXTERN(void) jinit_merged_upsampler JPP((j_decompress_ptr cinfo));
  158053. /* Memory manager initialization */
  158054. EXTERN(void) jinit_memory_mgr JPP((j_common_ptr cinfo));
  158055. /* Utility routines in jutils.c */
  158056. EXTERN(long) jdiv_round_up JPP((long a, long b));
  158057. EXTERN(long) jround_up JPP((long a, long b));
  158058. EXTERN(void) jcopy_sample_rows JPP((JSAMPARRAY input_array, int source_row,
  158059. JSAMPARRAY output_array, int dest_row,
  158060. int num_rows, JDIMENSION num_cols));
  158061. EXTERN(void) jcopy_block_row JPP((JBLOCKROW input_row, JBLOCKROW output_row,
  158062. JDIMENSION num_blocks));
  158063. EXTERN(void) jzero_far JPP((void FAR * target, size_t bytestozero));
  158064. /* Constant tables in jutils.c */
  158065. #if 0 /* This table is not actually needed in v6a */
  158066. extern const int jpeg_zigzag_order[]; /* natural coef order to zigzag order */
  158067. #endif
  158068. extern const int jpeg_natural_order[]; /* zigzag coef order to natural order */
  158069. /* Suppress undefined-structure complaints if necessary. */
  158070. #ifdef INCOMPLETE_TYPES_BROKEN
  158071. #ifndef AM_MEMORY_MANAGER /* only jmemmgr.c defines these */
  158072. struct jvirt_sarray_control { long dummy; };
  158073. struct jvirt_barray_control { long dummy; };
  158074. #endif
  158075. #endif /* INCOMPLETE_TYPES_BROKEN */
  158076. /*** End of inlined file: jpegint.h ***/
  158077. /* fetch private declarations */
  158078. /*** Start of inlined file: jerror.h ***/
  158079. /*
  158080. * To define the enum list of message codes, include this file without
  158081. * defining macro JMESSAGE. To create a message string table, include it
  158082. * again with a suitable JMESSAGE definition (see jerror.c for an example).
  158083. */
  158084. #ifndef JMESSAGE
  158085. #ifndef JERROR_H
  158086. /* First time through, define the enum list */
  158087. #define JMAKE_ENUM_LIST
  158088. #else
  158089. /* Repeated inclusions of this file are no-ops unless JMESSAGE is defined */
  158090. #define JMESSAGE(code,string)
  158091. #endif /* JERROR_H */
  158092. #endif /* JMESSAGE */
  158093. #ifdef JMAKE_ENUM_LIST
  158094. typedef enum {
  158095. #define JMESSAGE(code,string) code ,
  158096. #endif /* JMAKE_ENUM_LIST */
  158097. JMESSAGE(JMSG_NOMESSAGE, "Bogus message code %d") /* Must be first entry! */
  158098. /* For maintenance convenience, list is alphabetical by message code name */
  158099. JMESSAGE(JERR_ARITH_NOTIMPL,
  158100. "Sorry, there are legal restrictions on arithmetic coding")
  158101. JMESSAGE(JERR_BAD_ALIGN_TYPE, "ALIGN_TYPE is wrong, please fix")
  158102. JMESSAGE(JERR_BAD_ALLOC_CHUNK, "MAX_ALLOC_CHUNK is wrong, please fix")
  158103. JMESSAGE(JERR_BAD_BUFFER_MODE, "Bogus buffer control mode")
  158104. JMESSAGE(JERR_BAD_COMPONENT_ID, "Invalid component ID %d in SOS")
  158105. JMESSAGE(JERR_BAD_DCT_COEF, "DCT coefficient out of range")
  158106. JMESSAGE(JERR_BAD_DCTSIZE, "IDCT output block size %d not supported")
  158107. JMESSAGE(JERR_BAD_HUFF_TABLE, "Bogus Huffman table definition")
  158108. JMESSAGE(JERR_BAD_IN_COLORSPACE, "Bogus input colorspace")
  158109. JMESSAGE(JERR_BAD_J_COLORSPACE, "Bogus JPEG colorspace")
  158110. JMESSAGE(JERR_BAD_LENGTH, "Bogus marker length")
  158111. JMESSAGE(JERR_BAD_LIB_VERSION,
  158112. "Wrong JPEG library version: library is %d, caller expects %d")
  158113. JMESSAGE(JERR_BAD_MCU_SIZE, "Sampling factors too large for interleaved scan")
  158114. JMESSAGE(JERR_BAD_POOL_ID, "Invalid memory pool code %d")
  158115. JMESSAGE(JERR_BAD_PRECISION, "Unsupported JPEG data precision %d")
  158116. JMESSAGE(JERR_BAD_PROGRESSION,
  158117. "Invalid progressive parameters Ss=%d Se=%d Ah=%d Al=%d")
  158118. JMESSAGE(JERR_BAD_PROG_SCRIPT,
  158119. "Invalid progressive parameters at scan script entry %d")
  158120. JMESSAGE(JERR_BAD_SAMPLING, "Bogus sampling factors")
  158121. JMESSAGE(JERR_BAD_SCAN_SCRIPT, "Invalid scan script at entry %d")
  158122. JMESSAGE(JERR_BAD_STATE, "Improper call to JPEG library in state %d")
  158123. JMESSAGE(JERR_BAD_STRUCT_SIZE,
  158124. "JPEG parameter struct mismatch: library thinks size is %u, caller expects %u")
  158125. JMESSAGE(JERR_BAD_VIRTUAL_ACCESS, "Bogus virtual array access")
  158126. JMESSAGE(JERR_BUFFER_SIZE, "Buffer passed to JPEG library is too small")
  158127. JMESSAGE(JERR_CANT_SUSPEND, "Suspension not allowed here")
  158128. JMESSAGE(JERR_CCIR601_NOTIMPL, "CCIR601 sampling not implemented yet")
  158129. JMESSAGE(JERR_COMPONENT_COUNT, "Too many color components: %d, max %d")
  158130. JMESSAGE(JERR_CONVERSION_NOTIMPL, "Unsupported color conversion request")
  158131. JMESSAGE(JERR_DAC_INDEX, "Bogus DAC index %d")
  158132. JMESSAGE(JERR_DAC_VALUE, "Bogus DAC value 0x%x")
  158133. JMESSAGE(JERR_DHT_INDEX, "Bogus DHT index %d")
  158134. JMESSAGE(JERR_DQT_INDEX, "Bogus DQT index %d")
  158135. JMESSAGE(JERR_EMPTY_IMAGE, "Empty JPEG image (DNL not supported)")
  158136. JMESSAGE(JERR_EMS_READ, "Read from EMS failed")
  158137. JMESSAGE(JERR_EMS_WRITE, "Write to EMS failed")
  158138. JMESSAGE(JERR_EOI_EXPECTED, "Didn't expect more than one scan")
  158139. JMESSAGE(JERR_FILE_READ, "Input file read error")
  158140. JMESSAGE(JERR_FILE_WRITE, "Output file write error --- out of disk space?")
  158141. JMESSAGE(JERR_FRACT_SAMPLE_NOTIMPL, "Fractional sampling not implemented yet")
  158142. JMESSAGE(JERR_HUFF_CLEN_OVERFLOW, "Huffman code size table overflow")
  158143. JMESSAGE(JERR_HUFF_MISSING_CODE, "Missing Huffman code table entry")
  158144. JMESSAGE(JERR_IMAGE_TOO_BIG, "Maximum supported image dimension is %u pixels")
  158145. JMESSAGE(JERR_INPUT_EMPTY, "Empty input file")
  158146. JMESSAGE(JERR_INPUT_EOF, "Premature end of input file")
  158147. JMESSAGE(JERR_MISMATCHED_QUANT_TABLE,
  158148. "Cannot transcode due to multiple use of quantization table %d")
  158149. JMESSAGE(JERR_MISSING_DATA, "Scan script does not transmit all data")
  158150. JMESSAGE(JERR_MODE_CHANGE, "Invalid color quantization mode change")
  158151. JMESSAGE(JERR_NOTIMPL, "Not implemented yet")
  158152. JMESSAGE(JERR_NOT_COMPILED, "Requested feature was omitted at compile time")
  158153. JMESSAGE(JERR_NO_BACKING_STORE, "Backing store not supported")
  158154. JMESSAGE(JERR_NO_HUFF_TABLE, "Huffman table 0x%02x was not defined")
  158155. JMESSAGE(JERR_NO_IMAGE, "JPEG datastream contains no image")
  158156. JMESSAGE(JERR_NO_QUANT_TABLE, "Quantization table 0x%02x was not defined")
  158157. JMESSAGE(JERR_NO_SOI, "Not a JPEG file: starts with 0x%02x 0x%02x")
  158158. JMESSAGE(JERR_OUT_OF_MEMORY, "Insufficient memory (case %d)")
  158159. JMESSAGE(JERR_QUANT_COMPONENTS,
  158160. "Cannot quantize more than %d color components")
  158161. JMESSAGE(JERR_QUANT_FEW_COLORS, "Cannot quantize to fewer than %d colors")
  158162. JMESSAGE(JERR_QUANT_MANY_COLORS, "Cannot quantize to more than %d colors")
  158163. JMESSAGE(JERR_SOF_DUPLICATE, "Invalid JPEG file structure: two SOF markers")
  158164. JMESSAGE(JERR_SOF_NO_SOS, "Invalid JPEG file structure: missing SOS marker")
  158165. JMESSAGE(JERR_SOF_UNSUPPORTED, "Unsupported JPEG process: SOF type 0x%02x")
  158166. JMESSAGE(JERR_SOI_DUPLICATE, "Invalid JPEG file structure: two SOI markers")
  158167. JMESSAGE(JERR_SOS_NO_SOF, "Invalid JPEG file structure: SOS before SOF")
  158168. JMESSAGE(JERR_TFILE_CREATE, "Failed to create temporary file %s")
  158169. JMESSAGE(JERR_TFILE_READ, "Read failed on temporary file")
  158170. JMESSAGE(JERR_TFILE_SEEK, "Seek failed on temporary file")
  158171. JMESSAGE(JERR_TFILE_WRITE,
  158172. "Write failed on temporary file --- out of disk space?")
  158173. JMESSAGE(JERR_TOO_LITTLE_DATA, "Application transferred too few scanlines")
  158174. JMESSAGE(JERR_UNKNOWN_MARKER, "Unsupported marker type 0x%02x")
  158175. JMESSAGE(JERR_VIRTUAL_BUG, "Virtual array controller messed up")
  158176. JMESSAGE(JERR_WIDTH_OVERFLOW, "Image too wide for this implementation")
  158177. JMESSAGE(JERR_XMS_READ, "Read from XMS failed")
  158178. JMESSAGE(JERR_XMS_WRITE, "Write to XMS failed")
  158179. JMESSAGE(JMSG_COPYRIGHT, JCOPYRIGHT)
  158180. JMESSAGE(JMSG_VERSION, JVERSION)
  158181. JMESSAGE(JTRC_16BIT_TABLES,
  158182. "Caution: quantization tables are too coarse for baseline JPEG")
  158183. JMESSAGE(JTRC_ADOBE,
  158184. "Adobe APP14 marker: version %d, flags 0x%04x 0x%04x, transform %d")
  158185. JMESSAGE(JTRC_APP0, "Unknown APP0 marker (not JFIF), length %u")
  158186. JMESSAGE(JTRC_APP14, "Unknown APP14 marker (not Adobe), length %u")
  158187. JMESSAGE(JTRC_DAC, "Define Arithmetic Table 0x%02x: 0x%02x")
  158188. JMESSAGE(JTRC_DHT, "Define Huffman Table 0x%02x")
  158189. JMESSAGE(JTRC_DQT, "Define Quantization Table %d precision %d")
  158190. JMESSAGE(JTRC_DRI, "Define Restart Interval %u")
  158191. JMESSAGE(JTRC_EMS_CLOSE, "Freed EMS handle %u")
  158192. JMESSAGE(JTRC_EMS_OPEN, "Obtained EMS handle %u")
  158193. JMESSAGE(JTRC_EOI, "End Of Image")
  158194. JMESSAGE(JTRC_HUFFBITS, " %3d %3d %3d %3d %3d %3d %3d %3d")
  158195. JMESSAGE(JTRC_JFIF, "JFIF APP0 marker: version %d.%02d, density %dx%d %d")
  158196. JMESSAGE(JTRC_JFIF_BADTHUMBNAILSIZE,
  158197. "Warning: thumbnail image size does not match data length %u")
  158198. JMESSAGE(JTRC_JFIF_EXTENSION,
  158199. "JFIF extension marker: type 0x%02x, length %u")
  158200. JMESSAGE(JTRC_JFIF_THUMBNAIL, " with %d x %d thumbnail image")
  158201. JMESSAGE(JTRC_MISC_MARKER, "Miscellaneous marker 0x%02x, length %u")
  158202. JMESSAGE(JTRC_PARMLESS_MARKER, "Unexpected marker 0x%02x")
  158203. JMESSAGE(JTRC_QUANTVALS, " %4u %4u %4u %4u %4u %4u %4u %4u")
  158204. JMESSAGE(JTRC_QUANT_3_NCOLORS, "Quantizing to %d = %d*%d*%d colors")
  158205. JMESSAGE(JTRC_QUANT_NCOLORS, "Quantizing to %d colors")
  158206. JMESSAGE(JTRC_QUANT_SELECTED, "Selected %d colors for quantization")
  158207. JMESSAGE(JTRC_RECOVERY_ACTION, "At marker 0x%02x, recovery action %d")
  158208. JMESSAGE(JTRC_RST, "RST%d")
  158209. JMESSAGE(JTRC_SMOOTH_NOTIMPL,
  158210. "Smoothing not supported with nonstandard sampling ratios")
  158211. JMESSAGE(JTRC_SOF, "Start Of Frame 0x%02x: width=%u, height=%u, components=%d")
  158212. JMESSAGE(JTRC_SOF_COMPONENT, " Component %d: %dhx%dv q=%d")
  158213. JMESSAGE(JTRC_SOI, "Start of Image")
  158214. JMESSAGE(JTRC_SOS, "Start Of Scan: %d components")
  158215. JMESSAGE(JTRC_SOS_COMPONENT, " Component %d: dc=%d ac=%d")
  158216. JMESSAGE(JTRC_SOS_PARAMS, " Ss=%d, Se=%d, Ah=%d, Al=%d")
  158217. JMESSAGE(JTRC_TFILE_CLOSE, "Closed temporary file %s")
  158218. JMESSAGE(JTRC_TFILE_OPEN, "Opened temporary file %s")
  158219. JMESSAGE(JTRC_THUMB_JPEG,
  158220. "JFIF extension marker: JPEG-compressed thumbnail image, length %u")
  158221. JMESSAGE(JTRC_THUMB_PALETTE,
  158222. "JFIF extension marker: palette thumbnail image, length %u")
  158223. JMESSAGE(JTRC_THUMB_RGB,
  158224. "JFIF extension marker: RGB thumbnail image, length %u")
  158225. JMESSAGE(JTRC_UNKNOWN_IDS,
  158226. "Unrecognized component IDs %d %d %d, assuming YCbCr")
  158227. JMESSAGE(JTRC_XMS_CLOSE, "Freed XMS handle %u")
  158228. JMESSAGE(JTRC_XMS_OPEN, "Obtained XMS handle %u")
  158229. JMESSAGE(JWRN_ADOBE_XFORM, "Unknown Adobe color transform code %d")
  158230. JMESSAGE(JWRN_BOGUS_PROGRESSION,
  158231. "Inconsistent progression sequence for component %d coefficient %d")
  158232. JMESSAGE(JWRN_EXTRANEOUS_DATA,
  158233. "Corrupt JPEG data: %u extraneous bytes before marker 0x%02x")
  158234. JMESSAGE(JWRN_HIT_MARKER, "Corrupt JPEG data: premature end of data segment")
  158235. JMESSAGE(JWRN_HUFF_BAD_CODE, "Corrupt JPEG data: bad Huffman code")
  158236. JMESSAGE(JWRN_JFIF_MAJOR, "Warning: unknown JFIF revision number %d.%02d")
  158237. JMESSAGE(JWRN_JPEG_EOF, "Premature end of JPEG file")
  158238. JMESSAGE(JWRN_MUST_RESYNC,
  158239. "Corrupt JPEG data: found marker 0x%02x instead of RST%d")
  158240. JMESSAGE(JWRN_NOT_SEQUENTIAL, "Invalid SOS parameters for sequential JPEG")
  158241. JMESSAGE(JWRN_TOO_MUCH_DATA, "Application transferred too many scanlines")
  158242. #ifdef JMAKE_ENUM_LIST
  158243. JMSG_LASTMSGCODE
  158244. } J_MESSAGE_CODE;
  158245. #undef JMAKE_ENUM_LIST
  158246. #endif /* JMAKE_ENUM_LIST */
  158247. /* Zap JMESSAGE macro so that future re-inclusions do nothing by default */
  158248. #undef JMESSAGE
  158249. #ifndef JERROR_H
  158250. #define JERROR_H
  158251. /* Macros to simplify using the error and trace message stuff */
  158252. /* The first parameter is either type of cinfo pointer */
  158253. /* Fatal errors (print message and exit) */
  158254. #define ERREXIT(cinfo,code) \
  158255. ((cinfo)->err->msg_code = (code), \
  158256. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  158257. #define ERREXIT1(cinfo,code,p1) \
  158258. ((cinfo)->err->msg_code = (code), \
  158259. (cinfo)->err->msg_parm.i[0] = (p1), \
  158260. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  158261. #define ERREXIT2(cinfo,code,p1,p2) \
  158262. ((cinfo)->err->msg_code = (code), \
  158263. (cinfo)->err->msg_parm.i[0] = (p1), \
  158264. (cinfo)->err->msg_parm.i[1] = (p2), \
  158265. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  158266. #define ERREXIT3(cinfo,code,p1,p2,p3) \
  158267. ((cinfo)->err->msg_code = (code), \
  158268. (cinfo)->err->msg_parm.i[0] = (p1), \
  158269. (cinfo)->err->msg_parm.i[1] = (p2), \
  158270. (cinfo)->err->msg_parm.i[2] = (p3), \
  158271. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  158272. #define ERREXIT4(cinfo,code,p1,p2,p3,p4) \
  158273. ((cinfo)->err->msg_code = (code), \
  158274. (cinfo)->err->msg_parm.i[0] = (p1), \
  158275. (cinfo)->err->msg_parm.i[1] = (p2), \
  158276. (cinfo)->err->msg_parm.i[2] = (p3), \
  158277. (cinfo)->err->msg_parm.i[3] = (p4), \
  158278. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  158279. #define ERREXITS(cinfo,code,str) \
  158280. ((cinfo)->err->msg_code = (code), \
  158281. strncpy((cinfo)->err->msg_parm.s, (str), JMSG_STR_PARM_MAX), \
  158282. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  158283. #define MAKESTMT(stuff) do { stuff } while (0)
  158284. /* Nonfatal errors (we can keep going, but the data is probably corrupt) */
  158285. #define WARNMS(cinfo,code) \
  158286. ((cinfo)->err->msg_code = (code), \
  158287. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), -1))
  158288. #define WARNMS1(cinfo,code,p1) \
  158289. ((cinfo)->err->msg_code = (code), \
  158290. (cinfo)->err->msg_parm.i[0] = (p1), \
  158291. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), -1))
  158292. #define WARNMS2(cinfo,code,p1,p2) \
  158293. ((cinfo)->err->msg_code = (code), \
  158294. (cinfo)->err->msg_parm.i[0] = (p1), \
  158295. (cinfo)->err->msg_parm.i[1] = (p2), \
  158296. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), -1))
  158297. /* Informational/debugging messages */
  158298. #define TRACEMS(cinfo,lvl,code) \
  158299. ((cinfo)->err->msg_code = (code), \
  158300. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)))
  158301. #define TRACEMS1(cinfo,lvl,code,p1) \
  158302. ((cinfo)->err->msg_code = (code), \
  158303. (cinfo)->err->msg_parm.i[0] = (p1), \
  158304. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)))
  158305. #define TRACEMS2(cinfo,lvl,code,p1,p2) \
  158306. ((cinfo)->err->msg_code = (code), \
  158307. (cinfo)->err->msg_parm.i[0] = (p1), \
  158308. (cinfo)->err->msg_parm.i[1] = (p2), \
  158309. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)))
  158310. #define TRACEMS3(cinfo,lvl,code,p1,p2,p3) \
  158311. MAKESTMT(int * _mp = (cinfo)->err->msg_parm.i; \
  158312. _mp[0] = (p1); _mp[1] = (p2); _mp[2] = (p3); \
  158313. (cinfo)->err->msg_code = (code); \
  158314. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)); )
  158315. #define TRACEMS4(cinfo,lvl,code,p1,p2,p3,p4) \
  158316. MAKESTMT(int * _mp = (cinfo)->err->msg_parm.i; \
  158317. _mp[0] = (p1); _mp[1] = (p2); _mp[2] = (p3); _mp[3] = (p4); \
  158318. (cinfo)->err->msg_code = (code); \
  158319. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)); )
  158320. #define TRACEMS5(cinfo,lvl,code,p1,p2,p3,p4,p5) \
  158321. MAKESTMT(int * _mp = (cinfo)->err->msg_parm.i; \
  158322. _mp[0] = (p1); _mp[1] = (p2); _mp[2] = (p3); _mp[3] = (p4); \
  158323. _mp[4] = (p5); \
  158324. (cinfo)->err->msg_code = (code); \
  158325. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)); )
  158326. #define TRACEMS8(cinfo,lvl,code,p1,p2,p3,p4,p5,p6,p7,p8) \
  158327. MAKESTMT(int * _mp = (cinfo)->err->msg_parm.i; \
  158328. _mp[0] = (p1); _mp[1] = (p2); _mp[2] = (p3); _mp[3] = (p4); \
  158329. _mp[4] = (p5); _mp[5] = (p6); _mp[6] = (p7); _mp[7] = (p8); \
  158330. (cinfo)->err->msg_code = (code); \
  158331. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)); )
  158332. #define TRACEMSS(cinfo,lvl,code,str) \
  158333. ((cinfo)->err->msg_code = (code), \
  158334. strncpy((cinfo)->err->msg_parm.s, (str), JMSG_STR_PARM_MAX), \
  158335. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)))
  158336. #endif /* JERROR_H */
  158337. /*** End of inlined file: jerror.h ***/
  158338. /* fetch error codes too */
  158339. #endif
  158340. #endif /* JPEGLIB_H */
  158341. /*** End of inlined file: jpeglib.h ***/
  158342. /*** Start of inlined file: jcapimin.c ***/
  158343. #define JPEG_INTERNALS
  158344. /*** Start of inlined file: jinclude.h ***/
  158345. /* Include auto-config file to find out which system include files we need. */
  158346. #ifndef __jinclude_h__
  158347. #define __jinclude_h__
  158348. /*** Start of inlined file: jconfig.h ***/
  158349. /* see jconfig.doc for explanations */
  158350. // disable all the warnings under MSVC
  158351. #ifdef _MSC_VER
  158352. #pragma warning (disable: 4996 4267 4100 4127 4702 4244)
  158353. #endif
  158354. #ifdef __BORLANDC__
  158355. #pragma warn -8057
  158356. #pragma warn -8019
  158357. #pragma warn -8004
  158358. #pragma warn -8008
  158359. #endif
  158360. #define HAVE_PROTOTYPES
  158361. #define HAVE_UNSIGNED_CHAR
  158362. #define HAVE_UNSIGNED_SHORT
  158363. /* #define void char */
  158364. /* #define const */
  158365. #undef CHAR_IS_UNSIGNED
  158366. #define HAVE_STDDEF_H
  158367. #define HAVE_STDLIB_H
  158368. #undef NEED_BSD_STRINGS
  158369. #undef NEED_SYS_TYPES_H
  158370. #undef NEED_FAR_POINTERS /* we presume a 32-bit flat memory model */
  158371. #undef NEED_SHORT_EXTERNAL_NAMES
  158372. #undef INCOMPLETE_TYPES_BROKEN
  158373. /* Define "boolean" as unsigned char, not int, per Windows custom */
  158374. #ifndef __RPCNDR_H__ /* don't conflict if rpcndr.h already read */
  158375. typedef unsigned char boolean;
  158376. #endif
  158377. #define HAVE_BOOLEAN /* prevent jmorecfg.h from redefining it */
  158378. #ifdef JPEG_INTERNALS
  158379. #undef RIGHT_SHIFT_IS_UNSIGNED
  158380. #endif /* JPEG_INTERNALS */
  158381. #ifdef JPEG_CJPEG_DJPEG
  158382. #define BMP_SUPPORTED /* BMP image file format */
  158383. #define GIF_SUPPORTED /* GIF image file format */
  158384. #define PPM_SUPPORTED /* PBMPLUS PPM/PGM image file format */
  158385. #undef RLE_SUPPORTED /* Utah RLE image file format */
  158386. #define TARGA_SUPPORTED /* Targa image file format */
  158387. #define TWO_FILE_COMMANDLINE /* optional */
  158388. #define USE_SETMODE /* Microsoft has setmode() */
  158389. #undef NEED_SIGNAL_CATCHER
  158390. #undef DONT_USE_B_MODE
  158391. #undef PROGRESS_REPORT /* optional */
  158392. #endif /* JPEG_CJPEG_DJPEG */
  158393. /*** End of inlined file: jconfig.h ***/
  158394. /* auto configuration options */
  158395. #define JCONFIG_INCLUDED /* so that jpeglib.h doesn't do it again */
  158396. /*
  158397. * We need the NULL macro and size_t typedef.
  158398. * On an ANSI-conforming system it is sufficient to include <stddef.h>.
  158399. * Otherwise, we get them from <stdlib.h> or <stdio.h>; we may have to
  158400. * pull in <sys/types.h> as well.
  158401. * Note that the core JPEG library does not require <stdio.h>;
  158402. * only the default error handler and data source/destination modules do.
  158403. * But we must pull it in because of the references to FILE in jpeglib.h.
  158404. * You can remove those references if you want to compile without <stdio.h>.
  158405. */
  158406. #ifdef HAVE_STDDEF_H
  158407. #include <stddef.h>
  158408. #endif
  158409. #ifdef HAVE_STDLIB_H
  158410. #include <stdlib.h>
  158411. #endif
  158412. #ifdef NEED_SYS_TYPES_H
  158413. #include <sys/types.h>
  158414. #endif
  158415. #include <stdio.h>
  158416. /*
  158417. * We need memory copying and zeroing functions, plus strncpy().
  158418. * ANSI and System V implementations declare these in <string.h>.
  158419. * BSD doesn't have the mem() functions, but it does have bcopy()/bzero().
  158420. * Some systems may declare memset and memcpy in <memory.h>.
  158421. *
  158422. * NOTE: we assume the size parameters to these functions are of type size_t.
  158423. * Change the casts in these macros if not!
  158424. */
  158425. #ifdef NEED_BSD_STRINGS
  158426. #include <strings.h>
  158427. #define MEMZERO(target,size) bzero((void *)(target), (size_t)(size))
  158428. #define MEMCOPY(dest,src,size) bcopy((const void *)(src), (void *)(dest), (size_t)(size))
  158429. #else /* not BSD, assume ANSI/SysV string lib */
  158430. #include <string.h>
  158431. #define MEMZERO(target,size) memset((void *)(target), 0, (size_t)(size))
  158432. #define MEMCOPY(dest,src,size) memcpy((void *)(dest), (const void *)(src), (size_t)(size))
  158433. #endif
  158434. /*
  158435. * In ANSI C, and indeed any rational implementation, size_t is also the
  158436. * type returned by sizeof(). However, it seems there are some irrational
  158437. * implementations out there, in which sizeof() returns an int even though
  158438. * size_t is defined as long or unsigned long. To ensure consistent results
  158439. * we always use this SIZEOF() macro in place of using sizeof() directly.
  158440. */
  158441. #define SIZEOF(object) ((size_t) sizeof(object))
  158442. /*
  158443. * The modules that use fread() and fwrite() always invoke them through
  158444. * these macros. On some systems you may need to twiddle the argument casts.
  158445. * CAUTION: argument order is different from underlying functions!
  158446. */
  158447. #define JFREAD(file,buf,sizeofbuf) \
  158448. ((size_t) fread((void *) (buf), (size_t) 1, (size_t) (sizeofbuf), (file)))
  158449. #define JFWRITE(file,buf,sizeofbuf) \
  158450. ((size_t) fwrite((const void *) (buf), (size_t) 1, (size_t) (sizeofbuf), (file)))
  158451. typedef enum { /* JPEG marker codes */
  158452. M_SOF0 = 0xc0,
  158453. M_SOF1 = 0xc1,
  158454. M_SOF2 = 0xc2,
  158455. M_SOF3 = 0xc3,
  158456. M_SOF5 = 0xc5,
  158457. M_SOF6 = 0xc6,
  158458. M_SOF7 = 0xc7,
  158459. M_JPG = 0xc8,
  158460. M_SOF9 = 0xc9,
  158461. M_SOF10 = 0xca,
  158462. M_SOF11 = 0xcb,
  158463. M_SOF13 = 0xcd,
  158464. M_SOF14 = 0xce,
  158465. M_SOF15 = 0xcf,
  158466. M_DHT = 0xc4,
  158467. M_DAC = 0xcc,
  158468. M_RST0 = 0xd0,
  158469. M_RST1 = 0xd1,
  158470. M_RST2 = 0xd2,
  158471. M_RST3 = 0xd3,
  158472. M_RST4 = 0xd4,
  158473. M_RST5 = 0xd5,
  158474. M_RST6 = 0xd6,
  158475. M_RST7 = 0xd7,
  158476. M_SOI = 0xd8,
  158477. M_EOI = 0xd9,
  158478. M_SOS = 0xda,
  158479. M_DQT = 0xdb,
  158480. M_DNL = 0xdc,
  158481. M_DRI = 0xdd,
  158482. M_DHP = 0xde,
  158483. M_EXP = 0xdf,
  158484. M_APP0 = 0xe0,
  158485. M_APP1 = 0xe1,
  158486. M_APP2 = 0xe2,
  158487. M_APP3 = 0xe3,
  158488. M_APP4 = 0xe4,
  158489. M_APP5 = 0xe5,
  158490. M_APP6 = 0xe6,
  158491. M_APP7 = 0xe7,
  158492. M_APP8 = 0xe8,
  158493. M_APP9 = 0xe9,
  158494. M_APP10 = 0xea,
  158495. M_APP11 = 0xeb,
  158496. M_APP12 = 0xec,
  158497. M_APP13 = 0xed,
  158498. M_APP14 = 0xee,
  158499. M_APP15 = 0xef,
  158500. M_JPG0 = 0xf0,
  158501. M_JPG13 = 0xfd,
  158502. M_COM = 0xfe,
  158503. M_TEM = 0x01,
  158504. M_ERROR = 0x100
  158505. } JPEG_MARKER;
  158506. /*
  158507. * Figure F.12: extend sign bit.
  158508. * On some machines, a shift and add will be faster than a table lookup.
  158509. */
  158510. #ifdef AVOID_TABLES
  158511. #define HUFF_EXTEND(x,s) ((x) < (1<<((s)-1)) ? (x) + (((-1)<<(s)) + 1) : (x))
  158512. #else
  158513. #define HUFF_EXTEND(x,s) ((x) < extend_test[s] ? (x) + extend_offset[s] : (x))
  158514. static const int extend_test[16] = /* entry n is 2**(n-1) */
  158515. { 0, 0x0001, 0x0002, 0x0004, 0x0008, 0x0010, 0x0020, 0x0040, 0x0080,
  158516. 0x0100, 0x0200, 0x0400, 0x0800, 0x1000, 0x2000, 0x4000 };
  158517. static const int extend_offset[16] = /* entry n is (-1 << n) + 1 */
  158518. { 0, ((-1)<<1) + 1, ((-1)<<2) + 1, ((-1)<<3) + 1, ((-1)<<4) + 1,
  158519. ((-1)<<5) + 1, ((-1)<<6) + 1, ((-1)<<7) + 1, ((-1)<<8) + 1,
  158520. ((-1)<<9) + 1, ((-1)<<10) + 1, ((-1)<<11) + 1, ((-1)<<12) + 1,
  158521. ((-1)<<13) + 1, ((-1)<<14) + 1, ((-1)<<15) + 1 };
  158522. #endif /* AVOID_TABLES */
  158523. #endif
  158524. /*** End of inlined file: jinclude.h ***/
  158525. /*
  158526. * Initialization of a JPEG compression object.
  158527. * The error manager must already be set up (in case memory manager fails).
  158528. */
  158529. GLOBAL(void)
  158530. jpeg_CreateCompress (j_compress_ptr cinfo, int version, size_t structsize)
  158531. {
  158532. int i;
  158533. /* Guard against version mismatches between library and caller. */
  158534. cinfo->mem = NULL; /* so jpeg_destroy knows mem mgr not called */
  158535. if (version != JPEG_LIB_VERSION)
  158536. ERREXIT2(cinfo, JERR_BAD_LIB_VERSION, JPEG_LIB_VERSION, version);
  158537. if (structsize != SIZEOF(struct jpeg_compress_struct))
  158538. ERREXIT2(cinfo, JERR_BAD_STRUCT_SIZE,
  158539. (int) SIZEOF(struct jpeg_compress_struct), (int) structsize);
  158540. /* For debugging purposes, we zero the whole master structure.
  158541. * But the application has already set the err pointer, and may have set
  158542. * client_data, so we have to save and restore those fields.
  158543. * Note: if application hasn't set client_data, tools like Purify may
  158544. * complain here.
  158545. */
  158546. {
  158547. struct jpeg_error_mgr * err = cinfo->err;
  158548. void * client_data = cinfo->client_data; /* ignore Purify complaint here */
  158549. MEMZERO(cinfo, SIZEOF(struct jpeg_compress_struct));
  158550. cinfo->err = err;
  158551. cinfo->client_data = client_data;
  158552. }
  158553. cinfo->is_decompressor = FALSE;
  158554. /* Initialize a memory manager instance for this object */
  158555. jinit_memory_mgr((j_common_ptr) cinfo);
  158556. /* Zero out pointers to permanent structures. */
  158557. cinfo->progress = NULL;
  158558. cinfo->dest = NULL;
  158559. cinfo->comp_info = NULL;
  158560. for (i = 0; i < NUM_QUANT_TBLS; i++)
  158561. cinfo->quant_tbl_ptrs[i] = NULL;
  158562. for (i = 0; i < NUM_HUFF_TBLS; i++) {
  158563. cinfo->dc_huff_tbl_ptrs[i] = NULL;
  158564. cinfo->ac_huff_tbl_ptrs[i] = NULL;
  158565. }
  158566. cinfo->script_space = NULL;
  158567. cinfo->input_gamma = 1.0; /* in case application forgets */
  158568. /* OK, I'm ready */
  158569. cinfo->global_state = CSTATE_START;
  158570. }
  158571. /*
  158572. * Destruction of a JPEG compression object
  158573. */
  158574. GLOBAL(void)
  158575. jpeg_destroy_compress (j_compress_ptr cinfo)
  158576. {
  158577. jpeg_destroy((j_common_ptr) cinfo); /* use common routine */
  158578. }
  158579. /*
  158580. * Abort processing of a JPEG compression operation,
  158581. * but don't destroy the object itself.
  158582. */
  158583. GLOBAL(void)
  158584. jpeg_abort_compress (j_compress_ptr cinfo)
  158585. {
  158586. jpeg_abort((j_common_ptr) cinfo); /* use common routine */
  158587. }
  158588. /*
  158589. * Forcibly suppress or un-suppress all quantization and Huffman tables.
  158590. * Marks all currently defined tables as already written (if suppress)
  158591. * or not written (if !suppress). This will control whether they get emitted
  158592. * by a subsequent jpeg_start_compress call.
  158593. *
  158594. * This routine is exported for use by applications that want to produce
  158595. * abbreviated JPEG datastreams. It logically belongs in jcparam.c, but
  158596. * since it is called by jpeg_start_compress, we put it here --- otherwise
  158597. * jcparam.o would be linked whether the application used it or not.
  158598. */
  158599. GLOBAL(void)
  158600. jpeg_suppress_tables (j_compress_ptr cinfo, boolean suppress)
  158601. {
  158602. int i;
  158603. JQUANT_TBL * qtbl;
  158604. JHUFF_TBL * htbl;
  158605. for (i = 0; i < NUM_QUANT_TBLS; i++) {
  158606. if ((qtbl = cinfo->quant_tbl_ptrs[i]) != NULL)
  158607. qtbl->sent_table = suppress;
  158608. }
  158609. for (i = 0; i < NUM_HUFF_TBLS; i++) {
  158610. if ((htbl = cinfo->dc_huff_tbl_ptrs[i]) != NULL)
  158611. htbl->sent_table = suppress;
  158612. if ((htbl = cinfo->ac_huff_tbl_ptrs[i]) != NULL)
  158613. htbl->sent_table = suppress;
  158614. }
  158615. }
  158616. /*
  158617. * Finish JPEG compression.
  158618. *
  158619. * If a multipass operating mode was selected, this may do a great deal of
  158620. * work including most of the actual output.
  158621. */
  158622. GLOBAL(void)
  158623. jpeg_finish_compress (j_compress_ptr cinfo)
  158624. {
  158625. JDIMENSION iMCU_row;
  158626. if (cinfo->global_state == CSTATE_SCANNING ||
  158627. cinfo->global_state == CSTATE_RAW_OK) {
  158628. /* Terminate first pass */
  158629. if (cinfo->next_scanline < cinfo->image_height)
  158630. ERREXIT(cinfo, JERR_TOO_LITTLE_DATA);
  158631. (*cinfo->master->finish_pass) (cinfo);
  158632. } else if (cinfo->global_state != CSTATE_WRCOEFS)
  158633. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  158634. /* Perform any remaining passes */
  158635. while (! cinfo->master->is_last_pass) {
  158636. (*cinfo->master->prepare_for_pass) (cinfo);
  158637. for (iMCU_row = 0; iMCU_row < cinfo->total_iMCU_rows; iMCU_row++) {
  158638. if (cinfo->progress != NULL) {
  158639. cinfo->progress->pass_counter = (long) iMCU_row;
  158640. cinfo->progress->pass_limit = (long) cinfo->total_iMCU_rows;
  158641. (*cinfo->progress->progress_monitor) ((j_common_ptr) cinfo);
  158642. }
  158643. /* We bypass the main controller and invoke coef controller directly;
  158644. * all work is being done from the coefficient buffer.
  158645. */
  158646. if (! (*cinfo->coef->compress_data) (cinfo, (JSAMPIMAGE) NULL))
  158647. ERREXIT(cinfo, JERR_CANT_SUSPEND);
  158648. }
  158649. (*cinfo->master->finish_pass) (cinfo);
  158650. }
  158651. /* Write EOI, do final cleanup */
  158652. (*cinfo->marker->write_file_trailer) (cinfo);
  158653. (*cinfo->dest->term_destination) (cinfo);
  158654. /* We can use jpeg_abort to release memory and reset global_state */
  158655. jpeg_abort((j_common_ptr) cinfo);
  158656. }
  158657. /*
  158658. * Write a special marker.
  158659. * This is only recommended for writing COM or APPn markers.
  158660. * Must be called after jpeg_start_compress() and before
  158661. * first call to jpeg_write_scanlines() or jpeg_write_raw_data().
  158662. */
  158663. GLOBAL(void)
  158664. jpeg_write_marker (j_compress_ptr cinfo, int marker,
  158665. const JOCTET *dataptr, unsigned int datalen)
  158666. {
  158667. JMETHOD(void, write_marker_byte, (j_compress_ptr info, int val));
  158668. if (cinfo->next_scanline != 0 ||
  158669. (cinfo->global_state != CSTATE_SCANNING &&
  158670. cinfo->global_state != CSTATE_RAW_OK &&
  158671. cinfo->global_state != CSTATE_WRCOEFS))
  158672. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  158673. (*cinfo->marker->write_marker_header) (cinfo, marker, datalen);
  158674. write_marker_byte = cinfo->marker->write_marker_byte; /* copy for speed */
  158675. while (datalen--) {
  158676. (*write_marker_byte) (cinfo, *dataptr);
  158677. dataptr++;
  158678. }
  158679. }
  158680. /* Same, but piecemeal. */
  158681. GLOBAL(void)
  158682. jpeg_write_m_header (j_compress_ptr cinfo, int marker, unsigned int datalen)
  158683. {
  158684. if (cinfo->next_scanline != 0 ||
  158685. (cinfo->global_state != CSTATE_SCANNING &&
  158686. cinfo->global_state != CSTATE_RAW_OK &&
  158687. cinfo->global_state != CSTATE_WRCOEFS))
  158688. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  158689. (*cinfo->marker->write_marker_header) (cinfo, marker, datalen);
  158690. }
  158691. GLOBAL(void)
  158692. jpeg_write_m_byte (j_compress_ptr cinfo, int val)
  158693. {
  158694. (*cinfo->marker->write_marker_byte) (cinfo, val);
  158695. }
  158696. /*
  158697. * Alternate compression function: just write an abbreviated table file.
  158698. * Before calling this, all parameters and a data destination must be set up.
  158699. *
  158700. * To produce a pair of files containing abbreviated tables and abbreviated
  158701. * image data, one would proceed as follows:
  158702. *
  158703. * initialize JPEG object
  158704. * set JPEG parameters
  158705. * set destination to table file
  158706. * jpeg_write_tables(cinfo);
  158707. * set destination to image file
  158708. * jpeg_start_compress(cinfo, FALSE);
  158709. * write data...
  158710. * jpeg_finish_compress(cinfo);
  158711. *
  158712. * jpeg_write_tables has the side effect of marking all tables written
  158713. * (same as jpeg_suppress_tables(..., TRUE)). Thus a subsequent start_compress
  158714. * will not re-emit the tables unless it is passed write_all_tables=TRUE.
  158715. */
  158716. GLOBAL(void)
  158717. jpeg_write_tables (j_compress_ptr cinfo)
  158718. {
  158719. if (cinfo->global_state != CSTATE_START)
  158720. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  158721. /* (Re)initialize error mgr and destination modules */
  158722. (*cinfo->err->reset_error_mgr) ((j_common_ptr) cinfo);
  158723. (*cinfo->dest->init_destination) (cinfo);
  158724. /* Initialize the marker writer ... bit of a crock to do it here. */
  158725. jinit_marker_writer(cinfo);
  158726. /* Write them tables! */
  158727. (*cinfo->marker->write_tables_only) (cinfo);
  158728. /* And clean up. */
  158729. (*cinfo->dest->term_destination) (cinfo);
  158730. /*
  158731. * In library releases up through v6a, we called jpeg_abort() here to free
  158732. * any working memory allocated by the destination manager and marker
  158733. * writer. Some applications had a problem with that: they allocated space
  158734. * of their own from the library memory manager, and didn't want it to go
  158735. * away during write_tables. So now we do nothing. This will cause a
  158736. * memory leak if an app calls write_tables repeatedly without doing a full
  158737. * compression cycle or otherwise resetting the JPEG object. However, that
  158738. * seems less bad than unexpectedly freeing memory in the normal case.
  158739. * An app that prefers the old behavior can call jpeg_abort for itself after
  158740. * each call to jpeg_write_tables().
  158741. */
  158742. }
  158743. /*** End of inlined file: jcapimin.c ***/
  158744. /*** Start of inlined file: jcapistd.c ***/
  158745. #define JPEG_INTERNALS
  158746. /*
  158747. * Compression initialization.
  158748. * Before calling this, all parameters and a data destination must be set up.
  158749. *
  158750. * We require a write_all_tables parameter as a failsafe check when writing
  158751. * multiple datastreams from the same compression object. Since prior runs
  158752. * will have left all the tables marked sent_table=TRUE, a subsequent run
  158753. * would emit an abbreviated stream (no tables) by default. This may be what
  158754. * is wanted, but for safety's sake it should not be the default behavior:
  158755. * programmers should have to make a deliberate choice to emit abbreviated
  158756. * images. Therefore the documentation and examples should encourage people
  158757. * to pass write_all_tables=TRUE; then it will take active thought to do the
  158758. * wrong thing.
  158759. */
  158760. GLOBAL(void)
  158761. jpeg_start_compress (j_compress_ptr cinfo, boolean write_all_tables)
  158762. {
  158763. if (cinfo->global_state != CSTATE_START)
  158764. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  158765. if (write_all_tables)
  158766. jpeg_suppress_tables(cinfo, FALSE); /* mark all tables to be written */
  158767. /* (Re)initialize error mgr and destination modules */
  158768. (*cinfo->err->reset_error_mgr) ((j_common_ptr) cinfo);
  158769. (*cinfo->dest->init_destination) (cinfo);
  158770. /* Perform master selection of active modules */
  158771. jinit_compress_master(cinfo);
  158772. /* Set up for the first pass */
  158773. (*cinfo->master->prepare_for_pass) (cinfo);
  158774. /* Ready for application to drive first pass through jpeg_write_scanlines
  158775. * or jpeg_write_raw_data.
  158776. */
  158777. cinfo->next_scanline = 0;
  158778. cinfo->global_state = (cinfo->raw_data_in ? CSTATE_RAW_OK : CSTATE_SCANNING);
  158779. }
  158780. /*
  158781. * Write some scanlines of data to the JPEG compressor.
  158782. *
  158783. * The return value will be the number of lines actually written.
  158784. * This should be less than the supplied num_lines only in case that
  158785. * the data destination module has requested suspension of the compressor,
  158786. * or if more than image_height scanlines are passed in.
  158787. *
  158788. * Note: we warn about excess calls to jpeg_write_scanlines() since
  158789. * this likely signals an application programmer error. However,
  158790. * excess scanlines passed in the last valid call are *silently* ignored,
  158791. * so that the application need not adjust num_lines for end-of-image
  158792. * when using a multiple-scanline buffer.
  158793. */
  158794. GLOBAL(JDIMENSION)
  158795. jpeg_write_scanlines (j_compress_ptr cinfo, JSAMPARRAY scanlines,
  158796. JDIMENSION num_lines)
  158797. {
  158798. JDIMENSION row_ctr, rows_left;
  158799. if (cinfo->global_state != CSTATE_SCANNING)
  158800. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  158801. if (cinfo->next_scanline >= cinfo->image_height)
  158802. WARNMS(cinfo, JWRN_TOO_MUCH_DATA);
  158803. /* Call progress monitor hook if present */
  158804. if (cinfo->progress != NULL) {
  158805. cinfo->progress->pass_counter = (long) cinfo->next_scanline;
  158806. cinfo->progress->pass_limit = (long) cinfo->image_height;
  158807. (*cinfo->progress->progress_monitor) ((j_common_ptr) cinfo);
  158808. }
  158809. /* Give master control module another chance if this is first call to
  158810. * jpeg_write_scanlines. This lets output of the frame/scan headers be
  158811. * delayed so that application can write COM, etc, markers between
  158812. * jpeg_start_compress and jpeg_write_scanlines.
  158813. */
  158814. if (cinfo->master->call_pass_startup)
  158815. (*cinfo->master->pass_startup) (cinfo);
  158816. /* Ignore any extra scanlines at bottom of image. */
  158817. rows_left = cinfo->image_height - cinfo->next_scanline;
  158818. if (num_lines > rows_left)
  158819. num_lines = rows_left;
  158820. row_ctr = 0;
  158821. (*cinfo->main->process_data) (cinfo, scanlines, &row_ctr, num_lines);
  158822. cinfo->next_scanline += row_ctr;
  158823. return row_ctr;
  158824. }
  158825. /*
  158826. * Alternate entry point to write raw data.
  158827. * Processes exactly one iMCU row per call, unless suspended.
  158828. */
  158829. GLOBAL(JDIMENSION)
  158830. jpeg_write_raw_data (j_compress_ptr cinfo, JSAMPIMAGE data,
  158831. JDIMENSION num_lines)
  158832. {
  158833. JDIMENSION lines_per_iMCU_row;
  158834. if (cinfo->global_state != CSTATE_RAW_OK)
  158835. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  158836. if (cinfo->next_scanline >= cinfo->image_height) {
  158837. WARNMS(cinfo, JWRN_TOO_MUCH_DATA);
  158838. return 0;
  158839. }
  158840. /* Call progress monitor hook if present */
  158841. if (cinfo->progress != NULL) {
  158842. cinfo->progress->pass_counter = (long) cinfo->next_scanline;
  158843. cinfo->progress->pass_limit = (long) cinfo->image_height;
  158844. (*cinfo->progress->progress_monitor) ((j_common_ptr) cinfo);
  158845. }
  158846. /* Give master control module another chance if this is first call to
  158847. * jpeg_write_raw_data. This lets output of the frame/scan headers be
  158848. * delayed so that application can write COM, etc, markers between
  158849. * jpeg_start_compress and jpeg_write_raw_data.
  158850. */
  158851. if (cinfo->master->call_pass_startup)
  158852. (*cinfo->master->pass_startup) (cinfo);
  158853. /* Verify that at least one iMCU row has been passed. */
  158854. lines_per_iMCU_row = cinfo->max_v_samp_factor * DCTSIZE;
  158855. if (num_lines < lines_per_iMCU_row)
  158856. ERREXIT(cinfo, JERR_BUFFER_SIZE);
  158857. /* Directly compress the row. */
  158858. if (! (*cinfo->coef->compress_data) (cinfo, data)) {
  158859. /* If compressor did not consume the whole row, suspend processing. */
  158860. return 0;
  158861. }
  158862. /* OK, we processed one iMCU row. */
  158863. cinfo->next_scanline += lines_per_iMCU_row;
  158864. return lines_per_iMCU_row;
  158865. }
  158866. /*** End of inlined file: jcapistd.c ***/
  158867. /*** Start of inlined file: jccoefct.c ***/
  158868. #define JPEG_INTERNALS
  158869. /* We use a full-image coefficient buffer when doing Huffman optimization,
  158870. * and also for writing multiple-scan JPEG files. In all cases, the DCT
  158871. * step is run during the first pass, and subsequent passes need only read
  158872. * the buffered coefficients.
  158873. */
  158874. #ifdef ENTROPY_OPT_SUPPORTED
  158875. #define FULL_COEF_BUFFER_SUPPORTED
  158876. #else
  158877. #ifdef C_MULTISCAN_FILES_SUPPORTED
  158878. #define FULL_COEF_BUFFER_SUPPORTED
  158879. #endif
  158880. #endif
  158881. /* Private buffer controller object */
  158882. typedef struct {
  158883. struct jpeg_c_coef_controller pub; /* public fields */
  158884. JDIMENSION iMCU_row_num; /* iMCU row # within image */
  158885. JDIMENSION mcu_ctr; /* counts MCUs processed in current row */
  158886. int MCU_vert_offset; /* counts MCU rows within iMCU row */
  158887. int MCU_rows_per_iMCU_row; /* number of such rows needed */
  158888. /* For single-pass compression, it's sufficient to buffer just one MCU
  158889. * (although this may prove a bit slow in practice). We allocate a
  158890. * workspace of C_MAX_BLOCKS_IN_MCU coefficient blocks, and reuse it for each
  158891. * MCU constructed and sent. (On 80x86, the workspace is FAR even though
  158892. * it's not really very big; this is to keep the module interfaces unchanged
  158893. * when a large coefficient buffer is necessary.)
  158894. * In multi-pass modes, this array points to the current MCU's blocks
  158895. * within the virtual arrays.
  158896. */
  158897. JBLOCKROW MCU_buffer[C_MAX_BLOCKS_IN_MCU];
  158898. /* In multi-pass modes, we need a virtual block array for each component. */
  158899. jvirt_barray_ptr whole_image[MAX_COMPONENTS];
  158900. } my_coef_controller;
  158901. typedef my_coef_controller * my_coef_ptr;
  158902. /* Forward declarations */
  158903. METHODDEF(boolean) compress_data
  158904. JPP((j_compress_ptr cinfo, JSAMPIMAGE input_buf));
  158905. #ifdef FULL_COEF_BUFFER_SUPPORTED
  158906. METHODDEF(boolean) compress_first_pass
  158907. JPP((j_compress_ptr cinfo, JSAMPIMAGE input_buf));
  158908. METHODDEF(boolean) compress_output
  158909. JPP((j_compress_ptr cinfo, JSAMPIMAGE input_buf));
  158910. #endif
  158911. LOCAL(void)
  158912. start_iMCU_row (j_compress_ptr cinfo)
  158913. /* Reset within-iMCU-row counters for a new row */
  158914. {
  158915. my_coef_ptr coef = (my_coef_ptr) cinfo->coef;
  158916. /* In an interleaved scan, an MCU row is the same as an iMCU row.
  158917. * In a noninterleaved scan, an iMCU row has v_samp_factor MCU rows.
  158918. * But at the bottom of the image, process only what's left.
  158919. */
  158920. if (cinfo->comps_in_scan > 1) {
  158921. coef->MCU_rows_per_iMCU_row = 1;
  158922. } else {
  158923. if (coef->iMCU_row_num < (cinfo->total_iMCU_rows-1))
  158924. coef->MCU_rows_per_iMCU_row = cinfo->cur_comp_info[0]->v_samp_factor;
  158925. else
  158926. coef->MCU_rows_per_iMCU_row = cinfo->cur_comp_info[0]->last_row_height;
  158927. }
  158928. coef->mcu_ctr = 0;
  158929. coef->MCU_vert_offset = 0;
  158930. }
  158931. /*
  158932. * Initialize for a processing pass.
  158933. */
  158934. METHODDEF(void)
  158935. start_pass_coef (j_compress_ptr cinfo, J_BUF_MODE pass_mode)
  158936. {
  158937. my_coef_ptr coef = (my_coef_ptr) cinfo->coef;
  158938. coef->iMCU_row_num = 0;
  158939. start_iMCU_row(cinfo);
  158940. switch (pass_mode) {
  158941. case JBUF_PASS_THRU:
  158942. if (coef->whole_image[0] != NULL)
  158943. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  158944. coef->pub.compress_data = compress_data;
  158945. break;
  158946. #ifdef FULL_COEF_BUFFER_SUPPORTED
  158947. case JBUF_SAVE_AND_PASS:
  158948. if (coef->whole_image[0] == NULL)
  158949. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  158950. coef->pub.compress_data = compress_first_pass;
  158951. break;
  158952. case JBUF_CRANK_DEST:
  158953. if (coef->whole_image[0] == NULL)
  158954. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  158955. coef->pub.compress_data = compress_output;
  158956. break;
  158957. #endif
  158958. default:
  158959. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  158960. break;
  158961. }
  158962. }
  158963. /*
  158964. * Process some data in the single-pass case.
  158965. * We process the equivalent of one fully interleaved MCU row ("iMCU" row)
  158966. * per call, ie, v_samp_factor block rows for each component in the image.
  158967. * Returns TRUE if the iMCU row is completed, FALSE if suspended.
  158968. *
  158969. * NB: input_buf contains a plane for each component in image,
  158970. * which we index according to the component's SOF position.
  158971. */
  158972. METHODDEF(boolean)
  158973. compress_data (j_compress_ptr cinfo, JSAMPIMAGE input_buf)
  158974. {
  158975. my_coef_ptr coef = (my_coef_ptr) cinfo->coef;
  158976. JDIMENSION MCU_col_num; /* index of current MCU within row */
  158977. JDIMENSION last_MCU_col = cinfo->MCUs_per_row - 1;
  158978. JDIMENSION last_iMCU_row = cinfo->total_iMCU_rows - 1;
  158979. int blkn, bi, ci, yindex, yoffset, blockcnt;
  158980. JDIMENSION ypos, xpos;
  158981. jpeg_component_info *compptr;
  158982. /* Loop to write as much as one whole iMCU row */
  158983. for (yoffset = coef->MCU_vert_offset; yoffset < coef->MCU_rows_per_iMCU_row;
  158984. yoffset++) {
  158985. for (MCU_col_num = coef->mcu_ctr; MCU_col_num <= last_MCU_col;
  158986. MCU_col_num++) {
  158987. /* Determine where data comes from in input_buf and do the DCT thing.
  158988. * Each call on forward_DCT processes a horizontal row of DCT blocks
  158989. * as wide as an MCU; we rely on having allocated the MCU_buffer[] blocks
  158990. * sequentially. Dummy blocks at the right or bottom edge are filled in
  158991. * specially. The data in them does not matter for image reconstruction,
  158992. * so we fill them with values that will encode to the smallest amount of
  158993. * data, viz: all zeroes in the AC entries, DC entries equal to previous
  158994. * block's DC value. (Thanks to Thomas Kinsman for this idea.)
  158995. */
  158996. blkn = 0;
  158997. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  158998. compptr = cinfo->cur_comp_info[ci];
  158999. blockcnt = (MCU_col_num < last_MCU_col) ? compptr->MCU_width
  159000. : compptr->last_col_width;
  159001. xpos = MCU_col_num * compptr->MCU_sample_width;
  159002. ypos = yoffset * DCTSIZE; /* ypos == (yoffset+yindex) * DCTSIZE */
  159003. for (yindex = 0; yindex < compptr->MCU_height; yindex++) {
  159004. if (coef->iMCU_row_num < last_iMCU_row ||
  159005. yoffset+yindex < compptr->last_row_height) {
  159006. (*cinfo->fdct->forward_DCT) (cinfo, compptr,
  159007. input_buf[compptr->component_index],
  159008. coef->MCU_buffer[blkn],
  159009. ypos, xpos, (JDIMENSION) blockcnt);
  159010. if (blockcnt < compptr->MCU_width) {
  159011. /* Create some dummy blocks at the right edge of the image. */
  159012. jzero_far((void FAR *) coef->MCU_buffer[blkn + blockcnt],
  159013. (compptr->MCU_width - blockcnt) * SIZEOF(JBLOCK));
  159014. for (bi = blockcnt; bi < compptr->MCU_width; bi++) {
  159015. coef->MCU_buffer[blkn+bi][0][0] = coef->MCU_buffer[blkn+bi-1][0][0];
  159016. }
  159017. }
  159018. } else {
  159019. /* Create a row of dummy blocks at the bottom of the image. */
  159020. jzero_far((void FAR *) coef->MCU_buffer[blkn],
  159021. compptr->MCU_width * SIZEOF(JBLOCK));
  159022. for (bi = 0; bi < compptr->MCU_width; bi++) {
  159023. coef->MCU_buffer[blkn+bi][0][0] = coef->MCU_buffer[blkn-1][0][0];
  159024. }
  159025. }
  159026. blkn += compptr->MCU_width;
  159027. ypos += DCTSIZE;
  159028. }
  159029. }
  159030. /* Try to write the MCU. In event of a suspension failure, we will
  159031. * re-DCT the MCU on restart (a bit inefficient, could be fixed...)
  159032. */
  159033. if (! (*cinfo->entropy->encode_mcu) (cinfo, coef->MCU_buffer)) {
  159034. /* Suspension forced; update state counters and exit */
  159035. coef->MCU_vert_offset = yoffset;
  159036. coef->mcu_ctr = MCU_col_num;
  159037. return FALSE;
  159038. }
  159039. }
  159040. /* Completed an MCU row, but perhaps not an iMCU row */
  159041. coef->mcu_ctr = 0;
  159042. }
  159043. /* Completed the iMCU row, advance counters for next one */
  159044. coef->iMCU_row_num++;
  159045. start_iMCU_row(cinfo);
  159046. return TRUE;
  159047. }
  159048. #ifdef FULL_COEF_BUFFER_SUPPORTED
  159049. /*
  159050. * Process some data in the first pass of a multi-pass case.
  159051. * We process the equivalent of one fully interleaved MCU row ("iMCU" row)
  159052. * per call, ie, v_samp_factor block rows for each component in the image.
  159053. * This amount of data is read from the source buffer, DCT'd and quantized,
  159054. * and saved into the virtual arrays. We also generate suitable dummy blocks
  159055. * as needed at the right and lower edges. (The dummy blocks are constructed
  159056. * in the virtual arrays, which have been padded appropriately.) This makes
  159057. * it possible for subsequent passes not to worry about real vs. dummy blocks.
  159058. *
  159059. * We must also emit the data to the entropy encoder. This is conveniently
  159060. * done by calling compress_output() after we've loaded the current strip
  159061. * of the virtual arrays.
  159062. *
  159063. * NB: input_buf contains a plane for each component in image. All
  159064. * components are DCT'd and loaded into the virtual arrays in this pass.
  159065. * However, it may be that only a subset of the components are emitted to
  159066. * the entropy encoder during this first pass; be careful about looking
  159067. * at the scan-dependent variables (MCU dimensions, etc).
  159068. */
  159069. METHODDEF(boolean)
  159070. compress_first_pass (j_compress_ptr cinfo, JSAMPIMAGE input_buf)
  159071. {
  159072. my_coef_ptr coef = (my_coef_ptr) cinfo->coef;
  159073. JDIMENSION last_iMCU_row = cinfo->total_iMCU_rows - 1;
  159074. JDIMENSION blocks_across, MCUs_across, MCUindex;
  159075. int bi, ci, h_samp_factor, block_row, block_rows, ndummy;
  159076. JCOEF lastDC;
  159077. jpeg_component_info *compptr;
  159078. JBLOCKARRAY buffer;
  159079. JBLOCKROW thisblockrow, lastblockrow;
  159080. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  159081. ci++, compptr++) {
  159082. /* Align the virtual buffer for this component. */
  159083. buffer = (*cinfo->mem->access_virt_barray)
  159084. ((j_common_ptr) cinfo, coef->whole_image[ci],
  159085. coef->iMCU_row_num * compptr->v_samp_factor,
  159086. (JDIMENSION) compptr->v_samp_factor, TRUE);
  159087. /* Count non-dummy DCT block rows in this iMCU row. */
  159088. if (coef->iMCU_row_num < last_iMCU_row)
  159089. block_rows = compptr->v_samp_factor;
  159090. else {
  159091. /* NB: can't use last_row_height here, since may not be set! */
  159092. block_rows = (int) (compptr->height_in_blocks % compptr->v_samp_factor);
  159093. if (block_rows == 0) block_rows = compptr->v_samp_factor;
  159094. }
  159095. blocks_across = compptr->width_in_blocks;
  159096. h_samp_factor = compptr->h_samp_factor;
  159097. /* Count number of dummy blocks to be added at the right margin. */
  159098. ndummy = (int) (blocks_across % h_samp_factor);
  159099. if (ndummy > 0)
  159100. ndummy = h_samp_factor - ndummy;
  159101. /* Perform DCT for all non-dummy blocks in this iMCU row. Each call
  159102. * on forward_DCT processes a complete horizontal row of DCT blocks.
  159103. */
  159104. for (block_row = 0; block_row < block_rows; block_row++) {
  159105. thisblockrow = buffer[block_row];
  159106. (*cinfo->fdct->forward_DCT) (cinfo, compptr,
  159107. input_buf[ci], thisblockrow,
  159108. (JDIMENSION) (block_row * DCTSIZE),
  159109. (JDIMENSION) 0, blocks_across);
  159110. if (ndummy > 0) {
  159111. /* Create dummy blocks at the right edge of the image. */
  159112. thisblockrow += blocks_across; /* => first dummy block */
  159113. jzero_far((void FAR *) thisblockrow, ndummy * SIZEOF(JBLOCK));
  159114. lastDC = thisblockrow[-1][0];
  159115. for (bi = 0; bi < ndummy; bi++) {
  159116. thisblockrow[bi][0] = lastDC;
  159117. }
  159118. }
  159119. }
  159120. /* If at end of image, create dummy block rows as needed.
  159121. * The tricky part here is that within each MCU, we want the DC values
  159122. * of the dummy blocks to match the last real block's DC value.
  159123. * This squeezes a few more bytes out of the resulting file...
  159124. */
  159125. if (coef->iMCU_row_num == last_iMCU_row) {
  159126. blocks_across += ndummy; /* include lower right corner */
  159127. MCUs_across = blocks_across / h_samp_factor;
  159128. for (block_row = block_rows; block_row < compptr->v_samp_factor;
  159129. block_row++) {
  159130. thisblockrow = buffer[block_row];
  159131. lastblockrow = buffer[block_row-1];
  159132. jzero_far((void FAR *) thisblockrow,
  159133. (size_t) (blocks_across * SIZEOF(JBLOCK)));
  159134. for (MCUindex = 0; MCUindex < MCUs_across; MCUindex++) {
  159135. lastDC = lastblockrow[h_samp_factor-1][0];
  159136. for (bi = 0; bi < h_samp_factor; bi++) {
  159137. thisblockrow[bi][0] = lastDC;
  159138. }
  159139. thisblockrow += h_samp_factor; /* advance to next MCU in row */
  159140. lastblockrow += h_samp_factor;
  159141. }
  159142. }
  159143. }
  159144. }
  159145. /* NB: compress_output will increment iMCU_row_num if successful.
  159146. * A suspension return will result in redoing all the work above next time.
  159147. */
  159148. /* Emit data to the entropy encoder, sharing code with subsequent passes */
  159149. return compress_output(cinfo, input_buf);
  159150. }
  159151. /*
  159152. * Process some data in subsequent passes of a multi-pass case.
  159153. * We process the equivalent of one fully interleaved MCU row ("iMCU" row)
  159154. * per call, ie, v_samp_factor block rows for each component in the scan.
  159155. * The data is obtained from the virtual arrays and fed to the entropy coder.
  159156. * Returns TRUE if the iMCU row is completed, FALSE if suspended.
  159157. *
  159158. * NB: input_buf is ignored; it is likely to be a NULL pointer.
  159159. */
  159160. METHODDEF(boolean)
  159161. compress_output (j_compress_ptr cinfo, JSAMPIMAGE)
  159162. {
  159163. my_coef_ptr coef = (my_coef_ptr) cinfo->coef;
  159164. JDIMENSION MCU_col_num; /* index of current MCU within row */
  159165. int blkn, ci, xindex, yindex, yoffset;
  159166. JDIMENSION start_col;
  159167. JBLOCKARRAY buffer[MAX_COMPS_IN_SCAN];
  159168. JBLOCKROW buffer_ptr;
  159169. jpeg_component_info *compptr;
  159170. /* Align the virtual buffers for the components used in this scan.
  159171. * NB: during first pass, this is safe only because the buffers will
  159172. * already be aligned properly, so jmemmgr.c won't need to do any I/O.
  159173. */
  159174. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  159175. compptr = cinfo->cur_comp_info[ci];
  159176. buffer[ci] = (*cinfo->mem->access_virt_barray)
  159177. ((j_common_ptr) cinfo, coef->whole_image[compptr->component_index],
  159178. coef->iMCU_row_num * compptr->v_samp_factor,
  159179. (JDIMENSION) compptr->v_samp_factor, FALSE);
  159180. }
  159181. /* Loop to process one whole iMCU row */
  159182. for (yoffset = coef->MCU_vert_offset; yoffset < coef->MCU_rows_per_iMCU_row;
  159183. yoffset++) {
  159184. for (MCU_col_num = coef->mcu_ctr; MCU_col_num < cinfo->MCUs_per_row;
  159185. MCU_col_num++) {
  159186. /* Construct list of pointers to DCT blocks belonging to this MCU */
  159187. blkn = 0; /* index of current DCT block within MCU */
  159188. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  159189. compptr = cinfo->cur_comp_info[ci];
  159190. start_col = MCU_col_num * compptr->MCU_width;
  159191. for (yindex = 0; yindex < compptr->MCU_height; yindex++) {
  159192. buffer_ptr = buffer[ci][yindex+yoffset] + start_col;
  159193. for (xindex = 0; xindex < compptr->MCU_width; xindex++) {
  159194. coef->MCU_buffer[blkn++] = buffer_ptr++;
  159195. }
  159196. }
  159197. }
  159198. /* Try to write the MCU. */
  159199. if (! (*cinfo->entropy->encode_mcu) (cinfo, coef->MCU_buffer)) {
  159200. /* Suspension forced; update state counters and exit */
  159201. coef->MCU_vert_offset = yoffset;
  159202. coef->mcu_ctr = MCU_col_num;
  159203. return FALSE;
  159204. }
  159205. }
  159206. /* Completed an MCU row, but perhaps not an iMCU row */
  159207. coef->mcu_ctr = 0;
  159208. }
  159209. /* Completed the iMCU row, advance counters for next one */
  159210. coef->iMCU_row_num++;
  159211. start_iMCU_row(cinfo);
  159212. return TRUE;
  159213. }
  159214. #endif /* FULL_COEF_BUFFER_SUPPORTED */
  159215. /*
  159216. * Initialize coefficient buffer controller.
  159217. */
  159218. GLOBAL(void)
  159219. jinit_c_coef_controller (j_compress_ptr cinfo, boolean need_full_buffer)
  159220. {
  159221. my_coef_ptr coef;
  159222. coef = (my_coef_ptr)
  159223. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  159224. SIZEOF(my_coef_controller));
  159225. cinfo->coef = (struct jpeg_c_coef_controller *) coef;
  159226. coef->pub.start_pass = start_pass_coef;
  159227. /* Create the coefficient buffer. */
  159228. if (need_full_buffer) {
  159229. #ifdef FULL_COEF_BUFFER_SUPPORTED
  159230. /* Allocate a full-image virtual array for each component, */
  159231. /* padded to a multiple of samp_factor DCT blocks in each direction. */
  159232. int ci;
  159233. jpeg_component_info *compptr;
  159234. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  159235. ci++, compptr++) {
  159236. coef->whole_image[ci] = (*cinfo->mem->request_virt_barray)
  159237. ((j_common_ptr) cinfo, JPOOL_IMAGE, FALSE,
  159238. (JDIMENSION) jround_up((long) compptr->width_in_blocks,
  159239. (long) compptr->h_samp_factor),
  159240. (JDIMENSION) jround_up((long) compptr->height_in_blocks,
  159241. (long) compptr->v_samp_factor),
  159242. (JDIMENSION) compptr->v_samp_factor);
  159243. }
  159244. #else
  159245. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  159246. #endif
  159247. } else {
  159248. /* We only need a single-MCU buffer. */
  159249. JBLOCKROW buffer;
  159250. int i;
  159251. buffer = (JBLOCKROW)
  159252. (*cinfo->mem->alloc_large) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  159253. C_MAX_BLOCKS_IN_MCU * SIZEOF(JBLOCK));
  159254. for (i = 0; i < C_MAX_BLOCKS_IN_MCU; i++) {
  159255. coef->MCU_buffer[i] = buffer + i;
  159256. }
  159257. coef->whole_image[0] = NULL; /* flag for no virtual arrays */
  159258. }
  159259. }
  159260. /*** End of inlined file: jccoefct.c ***/
  159261. /*** Start of inlined file: jccolor.c ***/
  159262. #define JPEG_INTERNALS
  159263. /* Private subobject */
  159264. typedef struct {
  159265. struct jpeg_color_converter pub; /* public fields */
  159266. /* Private state for RGB->YCC conversion */
  159267. INT32 * rgb_ycc_tab; /* => table for RGB to YCbCr conversion */
  159268. } my_color_converter;
  159269. typedef my_color_converter * my_cconvert_ptr;
  159270. /**************** RGB -> YCbCr conversion: most common case **************/
  159271. /*
  159272. * YCbCr is defined per CCIR 601-1, except that Cb and Cr are
  159273. * normalized to the range 0..MAXJSAMPLE rather than -0.5 .. 0.5.
  159274. * The conversion equations to be implemented are therefore
  159275. * Y = 0.29900 * R + 0.58700 * G + 0.11400 * B
  159276. * Cb = -0.16874 * R - 0.33126 * G + 0.50000 * B + CENTERJSAMPLE
  159277. * Cr = 0.50000 * R - 0.41869 * G - 0.08131 * B + CENTERJSAMPLE
  159278. * (These numbers are derived from TIFF 6.0 section 21, dated 3-June-92.)
  159279. * Note: older versions of the IJG code used a zero offset of MAXJSAMPLE/2,
  159280. * rather than CENTERJSAMPLE, for Cb and Cr. This gave equal positive and
  159281. * negative swings for Cb/Cr, but meant that grayscale values (Cb=Cr=0)
  159282. * were not represented exactly. Now we sacrifice exact representation of
  159283. * maximum red and maximum blue in order to get exact grayscales.
  159284. *
  159285. * To avoid floating-point arithmetic, we represent the fractional constants
  159286. * as integers scaled up by 2^16 (about 4 digits precision); we have to divide
  159287. * the products by 2^16, with appropriate rounding, to get the correct answer.
  159288. *
  159289. * For even more speed, we avoid doing any multiplications in the inner loop
  159290. * by precalculating the constants times R,G,B for all possible values.
  159291. * For 8-bit JSAMPLEs this is very reasonable (only 256 entries per table);
  159292. * for 12-bit samples it is still acceptable. It's not very reasonable for
  159293. * 16-bit samples, but if you want lossless storage you shouldn't be changing
  159294. * colorspace anyway.
  159295. * The CENTERJSAMPLE offsets and the rounding fudge-factor of 0.5 are included
  159296. * in the tables to save adding them separately in the inner loop.
  159297. */
  159298. #define SCALEBITS 16 /* speediest right-shift on some machines */
  159299. #define CBCR_OFFSET ((INT32) CENTERJSAMPLE << SCALEBITS)
  159300. #define ONE_HALF ((INT32) 1 << (SCALEBITS-1))
  159301. #define FIX(x) ((INT32) ((x) * (1L<<SCALEBITS) + 0.5))
  159302. /* We allocate one big table and divide it up into eight parts, instead of
  159303. * doing eight alloc_small requests. This lets us use a single table base
  159304. * address, which can be held in a register in the inner loops on many
  159305. * machines (more than can hold all eight addresses, anyway).
  159306. */
  159307. #define R_Y_OFF 0 /* offset to R => Y section */
  159308. #define G_Y_OFF (1*(MAXJSAMPLE+1)) /* offset to G => Y section */
  159309. #define B_Y_OFF (2*(MAXJSAMPLE+1)) /* etc. */
  159310. #define R_CB_OFF (3*(MAXJSAMPLE+1))
  159311. #define G_CB_OFF (4*(MAXJSAMPLE+1))
  159312. #define B_CB_OFF (5*(MAXJSAMPLE+1))
  159313. #define R_CR_OFF B_CB_OFF /* B=>Cb, R=>Cr are the same */
  159314. #define G_CR_OFF (6*(MAXJSAMPLE+1))
  159315. #define B_CR_OFF (7*(MAXJSAMPLE+1))
  159316. #define TABLE_SIZE (8*(MAXJSAMPLE+1))
  159317. /*
  159318. * Initialize for RGB->YCC colorspace conversion.
  159319. */
  159320. METHODDEF(void)
  159321. rgb_ycc_start (j_compress_ptr cinfo)
  159322. {
  159323. my_cconvert_ptr cconvert = (my_cconvert_ptr) cinfo->cconvert;
  159324. INT32 * rgb_ycc_tab;
  159325. INT32 i;
  159326. /* Allocate and fill in the conversion tables. */
  159327. cconvert->rgb_ycc_tab = rgb_ycc_tab = (INT32 *)
  159328. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  159329. (TABLE_SIZE * SIZEOF(INT32)));
  159330. for (i = 0; i <= MAXJSAMPLE; i++) {
  159331. rgb_ycc_tab[i+R_Y_OFF] = FIX(0.29900) * i;
  159332. rgb_ycc_tab[i+G_Y_OFF] = FIX(0.58700) * i;
  159333. rgb_ycc_tab[i+B_Y_OFF] = FIX(0.11400) * i + ONE_HALF;
  159334. rgb_ycc_tab[i+R_CB_OFF] = (-FIX(0.16874)) * i;
  159335. rgb_ycc_tab[i+G_CB_OFF] = (-FIX(0.33126)) * i;
  159336. /* We use a rounding fudge-factor of 0.5-epsilon for Cb and Cr.
  159337. * This ensures that the maximum output will round to MAXJSAMPLE
  159338. * not MAXJSAMPLE+1, and thus that we don't have to range-limit.
  159339. */
  159340. rgb_ycc_tab[i+B_CB_OFF] = FIX(0.50000) * i + CBCR_OFFSET + ONE_HALF-1;
  159341. /* B=>Cb and R=>Cr tables are the same
  159342. rgb_ycc_tab[i+R_CR_OFF] = FIX(0.50000) * i + CBCR_OFFSET + ONE_HALF-1;
  159343. */
  159344. rgb_ycc_tab[i+G_CR_OFF] = (-FIX(0.41869)) * i;
  159345. rgb_ycc_tab[i+B_CR_OFF] = (-FIX(0.08131)) * i;
  159346. }
  159347. }
  159348. /*
  159349. * Convert some rows of samples to the JPEG colorspace.
  159350. *
  159351. * Note that we change from the application's interleaved-pixel format
  159352. * to our internal noninterleaved, one-plane-per-component format.
  159353. * The input buffer is therefore three times as wide as the output buffer.
  159354. *
  159355. * A starting row offset is provided only for the output buffer. The caller
  159356. * can easily adjust the passed input_buf value to accommodate any row
  159357. * offset required on that side.
  159358. */
  159359. METHODDEF(void)
  159360. rgb_ycc_convert (j_compress_ptr cinfo,
  159361. JSAMPARRAY input_buf, JSAMPIMAGE output_buf,
  159362. JDIMENSION output_row, int num_rows)
  159363. {
  159364. my_cconvert_ptr cconvert = (my_cconvert_ptr) cinfo->cconvert;
  159365. register int r, g, b;
  159366. register INT32 * ctab = cconvert->rgb_ycc_tab;
  159367. register JSAMPROW inptr;
  159368. register JSAMPROW outptr0, outptr1, outptr2;
  159369. register JDIMENSION col;
  159370. JDIMENSION num_cols = cinfo->image_width;
  159371. while (--num_rows >= 0) {
  159372. inptr = *input_buf++;
  159373. outptr0 = output_buf[0][output_row];
  159374. outptr1 = output_buf[1][output_row];
  159375. outptr2 = output_buf[2][output_row];
  159376. output_row++;
  159377. for (col = 0; col < num_cols; col++) {
  159378. r = GETJSAMPLE(inptr[RGB_RED]);
  159379. g = GETJSAMPLE(inptr[RGB_GREEN]);
  159380. b = GETJSAMPLE(inptr[RGB_BLUE]);
  159381. inptr += RGB_PIXELSIZE;
  159382. /* If the inputs are 0..MAXJSAMPLE, the outputs of these equations
  159383. * must be too; we do not need an explicit range-limiting operation.
  159384. * Hence the value being shifted is never negative, and we don't
  159385. * need the general RIGHT_SHIFT macro.
  159386. */
  159387. /* Y */
  159388. outptr0[col] = (JSAMPLE)
  159389. ((ctab[r+R_Y_OFF] + ctab[g+G_Y_OFF] + ctab[b+B_Y_OFF])
  159390. >> SCALEBITS);
  159391. /* Cb */
  159392. outptr1[col] = (JSAMPLE)
  159393. ((ctab[r+R_CB_OFF] + ctab[g+G_CB_OFF] + ctab[b+B_CB_OFF])
  159394. >> SCALEBITS);
  159395. /* Cr */
  159396. outptr2[col] = (JSAMPLE)
  159397. ((ctab[r+R_CR_OFF] + ctab[g+G_CR_OFF] + ctab[b+B_CR_OFF])
  159398. >> SCALEBITS);
  159399. }
  159400. }
  159401. }
  159402. /**************** Cases other than RGB -> YCbCr **************/
  159403. /*
  159404. * Convert some rows of samples to the JPEG colorspace.
  159405. * This version handles RGB->grayscale conversion, which is the same
  159406. * as the RGB->Y portion of RGB->YCbCr.
  159407. * We assume rgb_ycc_start has been called (we only use the Y tables).
  159408. */
  159409. METHODDEF(void)
  159410. rgb_gray_convert (j_compress_ptr cinfo,
  159411. JSAMPARRAY input_buf, JSAMPIMAGE output_buf,
  159412. JDIMENSION output_row, int num_rows)
  159413. {
  159414. my_cconvert_ptr cconvert = (my_cconvert_ptr) cinfo->cconvert;
  159415. register int r, g, b;
  159416. register INT32 * ctab = cconvert->rgb_ycc_tab;
  159417. register JSAMPROW inptr;
  159418. register JSAMPROW outptr;
  159419. register JDIMENSION col;
  159420. JDIMENSION num_cols = cinfo->image_width;
  159421. while (--num_rows >= 0) {
  159422. inptr = *input_buf++;
  159423. outptr = output_buf[0][output_row];
  159424. output_row++;
  159425. for (col = 0; col < num_cols; col++) {
  159426. r = GETJSAMPLE(inptr[RGB_RED]);
  159427. g = GETJSAMPLE(inptr[RGB_GREEN]);
  159428. b = GETJSAMPLE(inptr[RGB_BLUE]);
  159429. inptr += RGB_PIXELSIZE;
  159430. /* Y */
  159431. outptr[col] = (JSAMPLE)
  159432. ((ctab[r+R_Y_OFF] + ctab[g+G_Y_OFF] + ctab[b+B_Y_OFF])
  159433. >> SCALEBITS);
  159434. }
  159435. }
  159436. }
  159437. /*
  159438. * Convert some rows of samples to the JPEG colorspace.
  159439. * This version handles Adobe-style CMYK->YCCK conversion,
  159440. * where we convert R=1-C, G=1-M, and B=1-Y to YCbCr using the same
  159441. * conversion as above, while passing K (black) unchanged.
  159442. * We assume rgb_ycc_start has been called.
  159443. */
  159444. METHODDEF(void)
  159445. cmyk_ycck_convert (j_compress_ptr cinfo,
  159446. JSAMPARRAY input_buf, JSAMPIMAGE output_buf,
  159447. JDIMENSION output_row, int num_rows)
  159448. {
  159449. my_cconvert_ptr cconvert = (my_cconvert_ptr) cinfo->cconvert;
  159450. register int r, g, b;
  159451. register INT32 * ctab = cconvert->rgb_ycc_tab;
  159452. register JSAMPROW inptr;
  159453. register JSAMPROW outptr0, outptr1, outptr2, outptr3;
  159454. register JDIMENSION col;
  159455. JDIMENSION num_cols = cinfo->image_width;
  159456. while (--num_rows >= 0) {
  159457. inptr = *input_buf++;
  159458. outptr0 = output_buf[0][output_row];
  159459. outptr1 = output_buf[1][output_row];
  159460. outptr2 = output_buf[2][output_row];
  159461. outptr3 = output_buf[3][output_row];
  159462. output_row++;
  159463. for (col = 0; col < num_cols; col++) {
  159464. r = MAXJSAMPLE - GETJSAMPLE(inptr[0]);
  159465. g = MAXJSAMPLE - GETJSAMPLE(inptr[1]);
  159466. b = MAXJSAMPLE - GETJSAMPLE(inptr[2]);
  159467. /* K passes through as-is */
  159468. outptr3[col] = inptr[3]; /* don't need GETJSAMPLE here */
  159469. inptr += 4;
  159470. /* If the inputs are 0..MAXJSAMPLE, the outputs of these equations
  159471. * must be too; we do not need an explicit range-limiting operation.
  159472. * Hence the value being shifted is never negative, and we don't
  159473. * need the general RIGHT_SHIFT macro.
  159474. */
  159475. /* Y */
  159476. outptr0[col] = (JSAMPLE)
  159477. ((ctab[r+R_Y_OFF] + ctab[g+G_Y_OFF] + ctab[b+B_Y_OFF])
  159478. >> SCALEBITS);
  159479. /* Cb */
  159480. outptr1[col] = (JSAMPLE)
  159481. ((ctab[r+R_CB_OFF] + ctab[g+G_CB_OFF] + ctab[b+B_CB_OFF])
  159482. >> SCALEBITS);
  159483. /* Cr */
  159484. outptr2[col] = (JSAMPLE)
  159485. ((ctab[r+R_CR_OFF] + ctab[g+G_CR_OFF] + ctab[b+B_CR_OFF])
  159486. >> SCALEBITS);
  159487. }
  159488. }
  159489. }
  159490. /*
  159491. * Convert some rows of samples to the JPEG colorspace.
  159492. * This version handles grayscale output with no conversion.
  159493. * The source can be either plain grayscale or YCbCr (since Y == gray).
  159494. */
  159495. METHODDEF(void)
  159496. grayscale_convert (j_compress_ptr cinfo,
  159497. JSAMPARRAY input_buf, JSAMPIMAGE output_buf,
  159498. JDIMENSION output_row, int num_rows)
  159499. {
  159500. register JSAMPROW inptr;
  159501. register JSAMPROW outptr;
  159502. register JDIMENSION col;
  159503. JDIMENSION num_cols = cinfo->image_width;
  159504. int instride = cinfo->input_components;
  159505. while (--num_rows >= 0) {
  159506. inptr = *input_buf++;
  159507. outptr = output_buf[0][output_row];
  159508. output_row++;
  159509. for (col = 0; col < num_cols; col++) {
  159510. outptr[col] = inptr[0]; /* don't need GETJSAMPLE() here */
  159511. inptr += instride;
  159512. }
  159513. }
  159514. }
  159515. /*
  159516. * Convert some rows of samples to the JPEG colorspace.
  159517. * This version handles multi-component colorspaces without conversion.
  159518. * We assume input_components == num_components.
  159519. */
  159520. METHODDEF(void)
  159521. null_convert (j_compress_ptr cinfo,
  159522. JSAMPARRAY input_buf, JSAMPIMAGE output_buf,
  159523. JDIMENSION output_row, int num_rows)
  159524. {
  159525. register JSAMPROW inptr;
  159526. register JSAMPROW outptr;
  159527. register JDIMENSION col;
  159528. register int ci;
  159529. int nc = cinfo->num_components;
  159530. JDIMENSION num_cols = cinfo->image_width;
  159531. while (--num_rows >= 0) {
  159532. /* It seems fastest to make a separate pass for each component. */
  159533. for (ci = 0; ci < nc; ci++) {
  159534. inptr = *input_buf;
  159535. outptr = output_buf[ci][output_row];
  159536. for (col = 0; col < num_cols; col++) {
  159537. outptr[col] = inptr[ci]; /* don't need GETJSAMPLE() here */
  159538. inptr += nc;
  159539. }
  159540. }
  159541. input_buf++;
  159542. output_row++;
  159543. }
  159544. }
  159545. /*
  159546. * Empty method for start_pass.
  159547. */
  159548. METHODDEF(void)
  159549. null_method (j_compress_ptr)
  159550. {
  159551. /* no work needed */
  159552. }
  159553. /*
  159554. * Module initialization routine for input colorspace conversion.
  159555. */
  159556. GLOBAL(void)
  159557. jinit_color_converter (j_compress_ptr cinfo)
  159558. {
  159559. my_cconvert_ptr cconvert;
  159560. cconvert = (my_cconvert_ptr)
  159561. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  159562. SIZEOF(my_color_converter));
  159563. cinfo->cconvert = (struct jpeg_color_converter *) cconvert;
  159564. /* set start_pass to null method until we find out differently */
  159565. cconvert->pub.start_pass = null_method;
  159566. /* Make sure input_components agrees with in_color_space */
  159567. switch (cinfo->in_color_space) {
  159568. case JCS_GRAYSCALE:
  159569. if (cinfo->input_components != 1)
  159570. ERREXIT(cinfo, JERR_BAD_IN_COLORSPACE);
  159571. break;
  159572. case JCS_RGB:
  159573. #if RGB_PIXELSIZE != 3
  159574. if (cinfo->input_components != RGB_PIXELSIZE)
  159575. ERREXIT(cinfo, JERR_BAD_IN_COLORSPACE);
  159576. break;
  159577. #endif /* else share code with YCbCr */
  159578. case JCS_YCbCr:
  159579. if (cinfo->input_components != 3)
  159580. ERREXIT(cinfo, JERR_BAD_IN_COLORSPACE);
  159581. break;
  159582. case JCS_CMYK:
  159583. case JCS_YCCK:
  159584. if (cinfo->input_components != 4)
  159585. ERREXIT(cinfo, JERR_BAD_IN_COLORSPACE);
  159586. break;
  159587. default: /* JCS_UNKNOWN can be anything */
  159588. if (cinfo->input_components < 1)
  159589. ERREXIT(cinfo, JERR_BAD_IN_COLORSPACE);
  159590. break;
  159591. }
  159592. /* Check num_components, set conversion method based on requested space */
  159593. switch (cinfo->jpeg_color_space) {
  159594. case JCS_GRAYSCALE:
  159595. if (cinfo->num_components != 1)
  159596. ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
  159597. if (cinfo->in_color_space == JCS_GRAYSCALE)
  159598. cconvert->pub.color_convert = grayscale_convert;
  159599. else if (cinfo->in_color_space == JCS_RGB) {
  159600. cconvert->pub.start_pass = rgb_ycc_start;
  159601. cconvert->pub.color_convert = rgb_gray_convert;
  159602. } else if (cinfo->in_color_space == JCS_YCbCr)
  159603. cconvert->pub.color_convert = grayscale_convert;
  159604. else
  159605. ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
  159606. break;
  159607. case JCS_RGB:
  159608. if (cinfo->num_components != 3)
  159609. ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
  159610. if (cinfo->in_color_space == JCS_RGB && RGB_PIXELSIZE == 3)
  159611. cconvert->pub.color_convert = null_convert;
  159612. else
  159613. ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
  159614. break;
  159615. case JCS_YCbCr:
  159616. if (cinfo->num_components != 3)
  159617. ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
  159618. if (cinfo->in_color_space == JCS_RGB) {
  159619. cconvert->pub.start_pass = rgb_ycc_start;
  159620. cconvert->pub.color_convert = rgb_ycc_convert;
  159621. } else if (cinfo->in_color_space == JCS_YCbCr)
  159622. cconvert->pub.color_convert = null_convert;
  159623. else
  159624. ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
  159625. break;
  159626. case JCS_CMYK:
  159627. if (cinfo->num_components != 4)
  159628. ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
  159629. if (cinfo->in_color_space == JCS_CMYK)
  159630. cconvert->pub.color_convert = null_convert;
  159631. else
  159632. ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
  159633. break;
  159634. case JCS_YCCK:
  159635. if (cinfo->num_components != 4)
  159636. ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
  159637. if (cinfo->in_color_space == JCS_CMYK) {
  159638. cconvert->pub.start_pass = rgb_ycc_start;
  159639. cconvert->pub.color_convert = cmyk_ycck_convert;
  159640. } else if (cinfo->in_color_space == JCS_YCCK)
  159641. cconvert->pub.color_convert = null_convert;
  159642. else
  159643. ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
  159644. break;
  159645. default: /* allow null conversion of JCS_UNKNOWN */
  159646. if (cinfo->jpeg_color_space != cinfo->in_color_space ||
  159647. cinfo->num_components != cinfo->input_components)
  159648. ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
  159649. cconvert->pub.color_convert = null_convert;
  159650. break;
  159651. }
  159652. }
  159653. /*** End of inlined file: jccolor.c ***/
  159654. #undef FIX
  159655. /*** Start of inlined file: jcdctmgr.c ***/
  159656. #define JPEG_INTERNALS
  159657. /*** Start of inlined file: jdct.h ***/
  159658. /*
  159659. * A forward DCT routine is given a pointer to a work area of type DCTELEM[];
  159660. * the DCT is to be performed in-place in that buffer. Type DCTELEM is int
  159661. * for 8-bit samples, INT32 for 12-bit samples. (NOTE: Floating-point DCT
  159662. * implementations use an array of type FAST_FLOAT, instead.)
  159663. * The DCT inputs are expected to be signed (range +-CENTERJSAMPLE).
  159664. * The DCT outputs are returned scaled up by a factor of 8; they therefore
  159665. * have a range of +-8K for 8-bit data, +-128K for 12-bit data. This
  159666. * convention improves accuracy in integer implementations and saves some
  159667. * work in floating-point ones.
  159668. * Quantization of the output coefficients is done by jcdctmgr.c.
  159669. */
  159670. #ifndef __jdct_h__
  159671. #define __jdct_h__
  159672. #if BITS_IN_JSAMPLE == 8
  159673. typedef int DCTELEM; /* 16 or 32 bits is fine */
  159674. #else
  159675. typedef INT32 DCTELEM; /* must have 32 bits */
  159676. #endif
  159677. typedef JMETHOD(void, forward_DCT_method_ptr, (DCTELEM * data));
  159678. typedef JMETHOD(void, float_DCT_method_ptr, (FAST_FLOAT * data));
  159679. /*
  159680. * An inverse DCT routine is given a pointer to the input JBLOCK and a pointer
  159681. * to an output sample array. The routine must dequantize the input data as
  159682. * well as perform the IDCT; for dequantization, it uses the multiplier table
  159683. * pointed to by compptr->dct_table. The output data is to be placed into the
  159684. * sample array starting at a specified column. (Any row offset needed will
  159685. * be applied to the array pointer before it is passed to the IDCT code.)
  159686. * Note that the number of samples emitted by the IDCT routine is
  159687. * DCT_scaled_size * DCT_scaled_size.
  159688. */
  159689. /* typedef inverse_DCT_method_ptr is declared in jpegint.h */
  159690. /*
  159691. * Each IDCT routine has its own ideas about the best dct_table element type.
  159692. */
  159693. typedef MULTIPLIER ISLOW_MULT_TYPE; /* short or int, whichever is faster */
  159694. #if BITS_IN_JSAMPLE == 8
  159695. typedef MULTIPLIER IFAST_MULT_TYPE; /* 16 bits is OK, use short if faster */
  159696. #define IFAST_SCALE_BITS 2 /* fractional bits in scale factors */
  159697. #else
  159698. typedef INT32 IFAST_MULT_TYPE; /* need 32 bits for scaled quantizers */
  159699. #define IFAST_SCALE_BITS 13 /* fractional bits in scale factors */
  159700. #endif
  159701. typedef FAST_FLOAT FLOAT_MULT_TYPE; /* preferred floating type */
  159702. /*
  159703. * Each IDCT routine is responsible for range-limiting its results and
  159704. * converting them to unsigned form (0..MAXJSAMPLE). The raw outputs could
  159705. * be quite far out of range if the input data is corrupt, so a bulletproof
  159706. * range-limiting step is required. We use a mask-and-table-lookup method
  159707. * to do the combined operations quickly. See the comments with
  159708. * prepare_range_limit_table (in jdmaster.c) for more info.
  159709. */
  159710. #define IDCT_range_limit(cinfo) ((cinfo)->sample_range_limit + CENTERJSAMPLE)
  159711. #define RANGE_MASK (MAXJSAMPLE * 4 + 3) /* 2 bits wider than legal samples */
  159712. /* Short forms of external names for systems with brain-damaged linkers. */
  159713. #ifdef NEED_SHORT_EXTERNAL_NAMES
  159714. #define jpeg_fdct_islow jFDislow
  159715. #define jpeg_fdct_ifast jFDifast
  159716. #define jpeg_fdct_float jFDfloat
  159717. #define jpeg_idct_islow jRDislow
  159718. #define jpeg_idct_ifast jRDifast
  159719. #define jpeg_idct_float jRDfloat
  159720. #define jpeg_idct_4x4 jRD4x4
  159721. #define jpeg_idct_2x2 jRD2x2
  159722. #define jpeg_idct_1x1 jRD1x1
  159723. #endif /* NEED_SHORT_EXTERNAL_NAMES */
  159724. /* Extern declarations for the forward and inverse DCT routines. */
  159725. EXTERN(void) jpeg_fdct_islow JPP((DCTELEM * data));
  159726. EXTERN(void) jpeg_fdct_ifast JPP((DCTELEM * data));
  159727. EXTERN(void) jpeg_fdct_float JPP((FAST_FLOAT * data));
  159728. EXTERN(void) jpeg_idct_islow
  159729. JPP((j_decompress_ptr cinfo, jpeg_component_info * compptr,
  159730. JCOEFPTR coef_block, JSAMPARRAY output_buf, JDIMENSION output_col));
  159731. EXTERN(void) jpeg_idct_ifast
  159732. JPP((j_decompress_ptr cinfo, jpeg_component_info * compptr,
  159733. JCOEFPTR coef_block, JSAMPARRAY output_buf, JDIMENSION output_col));
  159734. EXTERN(void) jpeg_idct_float
  159735. JPP((j_decompress_ptr cinfo, jpeg_component_info * compptr,
  159736. JCOEFPTR coef_block, JSAMPARRAY output_buf, JDIMENSION output_col));
  159737. EXTERN(void) jpeg_idct_4x4
  159738. JPP((j_decompress_ptr cinfo, jpeg_component_info * compptr,
  159739. JCOEFPTR coef_block, JSAMPARRAY output_buf, JDIMENSION output_col));
  159740. EXTERN(void) jpeg_idct_2x2
  159741. JPP((j_decompress_ptr cinfo, jpeg_component_info * compptr,
  159742. JCOEFPTR coef_block, JSAMPARRAY output_buf, JDIMENSION output_col));
  159743. EXTERN(void) jpeg_idct_1x1
  159744. JPP((j_decompress_ptr cinfo, jpeg_component_info * compptr,
  159745. JCOEFPTR coef_block, JSAMPARRAY output_buf, JDIMENSION output_col));
  159746. /*
  159747. * Macros for handling fixed-point arithmetic; these are used by many
  159748. * but not all of the DCT/IDCT modules.
  159749. *
  159750. * All values are expected to be of type INT32.
  159751. * Fractional constants are scaled left by CONST_BITS bits.
  159752. * CONST_BITS is defined within each module using these macros,
  159753. * and may differ from one module to the next.
  159754. */
  159755. #define ONE ((INT32) 1)
  159756. #define CONST_SCALE (ONE << CONST_BITS)
  159757. /* Convert a positive real constant to an integer scaled by CONST_SCALE.
  159758. * Caution: some C compilers fail to reduce "FIX(constant)" at compile time,
  159759. * thus causing a lot of useless floating-point operations at run time.
  159760. */
  159761. #define FIX(x) ((INT32) ((x) * CONST_SCALE + 0.5))
  159762. /* Descale and correctly round an INT32 value that's scaled by N bits.
  159763. * We assume RIGHT_SHIFT rounds towards minus infinity, so adding
  159764. * the fudge factor is correct for either sign of X.
  159765. */
  159766. #define DESCALE(x,n) RIGHT_SHIFT((x) + (ONE << ((n)-1)), n)
  159767. /* Multiply an INT32 variable by an INT32 constant to yield an INT32 result.
  159768. * This macro is used only when the two inputs will actually be no more than
  159769. * 16 bits wide, so that a 16x16->32 bit multiply can be used instead of a
  159770. * full 32x32 multiply. This provides a useful speedup on many machines.
  159771. * Unfortunately there is no way to specify a 16x16->32 multiply portably
  159772. * in C, but some C compilers will do the right thing if you provide the
  159773. * correct combination of casts.
  159774. */
  159775. #ifdef SHORTxSHORT_32 /* may work if 'int' is 32 bits */
  159776. #define MULTIPLY16C16(var,const) (((INT16) (var)) * ((INT16) (const)))
  159777. #endif
  159778. #ifdef SHORTxLCONST_32 /* known to work with Microsoft C 6.0 */
  159779. #define MULTIPLY16C16(var,const) (((INT16) (var)) * ((INT32) (const)))
  159780. #endif
  159781. #ifndef MULTIPLY16C16 /* default definition */
  159782. #define MULTIPLY16C16(var,const) ((var) * (const))
  159783. #endif
  159784. /* Same except both inputs are variables. */
  159785. #ifdef SHORTxSHORT_32 /* may work if 'int' is 32 bits */
  159786. #define MULTIPLY16V16(var1,var2) (((INT16) (var1)) * ((INT16) (var2)))
  159787. #endif
  159788. #ifndef MULTIPLY16V16 /* default definition */
  159789. #define MULTIPLY16V16(var1,var2) ((var1) * (var2))
  159790. #endif
  159791. #endif
  159792. /*** End of inlined file: jdct.h ***/
  159793. /* Private declarations for DCT subsystem */
  159794. /* Private subobject for this module */
  159795. typedef struct {
  159796. struct jpeg_forward_dct pub; /* public fields */
  159797. /* Pointer to the DCT routine actually in use */
  159798. forward_DCT_method_ptr do_dct;
  159799. /* The actual post-DCT divisors --- not identical to the quant table
  159800. * entries, because of scaling (especially for an unnormalized DCT).
  159801. * Each table is given in normal array order.
  159802. */
  159803. DCTELEM * divisors[NUM_QUANT_TBLS];
  159804. #ifdef DCT_FLOAT_SUPPORTED
  159805. /* Same as above for the floating-point case. */
  159806. float_DCT_method_ptr do_float_dct;
  159807. FAST_FLOAT * float_divisors[NUM_QUANT_TBLS];
  159808. #endif
  159809. } my_fdct_controller;
  159810. typedef my_fdct_controller * my_fdct_ptr;
  159811. /*
  159812. * Initialize for a processing pass.
  159813. * Verify that all referenced Q-tables are present, and set up
  159814. * the divisor table for each one.
  159815. * In the current implementation, DCT of all components is done during
  159816. * the first pass, even if only some components will be output in the
  159817. * first scan. Hence all components should be examined here.
  159818. */
  159819. METHODDEF(void)
  159820. start_pass_fdctmgr (j_compress_ptr cinfo)
  159821. {
  159822. my_fdct_ptr fdct = (my_fdct_ptr) cinfo->fdct;
  159823. int ci, qtblno, i;
  159824. jpeg_component_info *compptr;
  159825. JQUANT_TBL * qtbl;
  159826. DCTELEM * dtbl;
  159827. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  159828. ci++, compptr++) {
  159829. qtblno = compptr->quant_tbl_no;
  159830. /* Make sure specified quantization table is present */
  159831. if (qtblno < 0 || qtblno >= NUM_QUANT_TBLS ||
  159832. cinfo->quant_tbl_ptrs[qtblno] == NULL)
  159833. ERREXIT1(cinfo, JERR_NO_QUANT_TABLE, qtblno);
  159834. qtbl = cinfo->quant_tbl_ptrs[qtblno];
  159835. /* Compute divisors for this quant table */
  159836. /* We may do this more than once for same table, but it's not a big deal */
  159837. switch (cinfo->dct_method) {
  159838. #ifdef DCT_ISLOW_SUPPORTED
  159839. case JDCT_ISLOW:
  159840. /* For LL&M IDCT method, divisors are equal to raw quantization
  159841. * coefficients multiplied by 8 (to counteract scaling).
  159842. */
  159843. if (fdct->divisors[qtblno] == NULL) {
  159844. fdct->divisors[qtblno] = (DCTELEM *)
  159845. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  159846. DCTSIZE2 * SIZEOF(DCTELEM));
  159847. }
  159848. dtbl = fdct->divisors[qtblno];
  159849. for (i = 0; i < DCTSIZE2; i++) {
  159850. dtbl[i] = ((DCTELEM) qtbl->quantval[i]) << 3;
  159851. }
  159852. break;
  159853. #endif
  159854. #ifdef DCT_IFAST_SUPPORTED
  159855. case JDCT_IFAST:
  159856. {
  159857. /* For AA&N IDCT method, divisors are equal to quantization
  159858. * coefficients scaled by scalefactor[row]*scalefactor[col], where
  159859. * scalefactor[0] = 1
  159860. * scalefactor[k] = cos(k*PI/16) * sqrt(2) for k=1..7
  159861. * We apply a further scale factor of 8.
  159862. */
  159863. #define CONST_BITS 14
  159864. static const INT16 aanscales[DCTSIZE2] = {
  159865. /* precomputed values scaled up by 14 bits */
  159866. 16384, 22725, 21407, 19266, 16384, 12873, 8867, 4520,
  159867. 22725, 31521, 29692, 26722, 22725, 17855, 12299, 6270,
  159868. 21407, 29692, 27969, 25172, 21407, 16819, 11585, 5906,
  159869. 19266, 26722, 25172, 22654, 19266, 15137, 10426, 5315,
  159870. 16384, 22725, 21407, 19266, 16384, 12873, 8867, 4520,
  159871. 12873, 17855, 16819, 15137, 12873, 10114, 6967, 3552,
  159872. 8867, 12299, 11585, 10426, 8867, 6967, 4799, 2446,
  159873. 4520, 6270, 5906, 5315, 4520, 3552, 2446, 1247
  159874. };
  159875. SHIFT_TEMPS
  159876. if (fdct->divisors[qtblno] == NULL) {
  159877. fdct->divisors[qtblno] = (DCTELEM *)
  159878. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  159879. DCTSIZE2 * SIZEOF(DCTELEM));
  159880. }
  159881. dtbl = fdct->divisors[qtblno];
  159882. for (i = 0; i < DCTSIZE2; i++) {
  159883. dtbl[i] = (DCTELEM)
  159884. DESCALE(MULTIPLY16V16((INT32) qtbl->quantval[i],
  159885. (INT32) aanscales[i]),
  159886. CONST_BITS-3);
  159887. }
  159888. }
  159889. break;
  159890. #endif
  159891. #ifdef DCT_FLOAT_SUPPORTED
  159892. case JDCT_FLOAT:
  159893. {
  159894. /* For float AA&N IDCT method, divisors are equal to quantization
  159895. * coefficients scaled by scalefactor[row]*scalefactor[col], where
  159896. * scalefactor[0] = 1
  159897. * scalefactor[k] = cos(k*PI/16) * sqrt(2) for k=1..7
  159898. * We apply a further scale factor of 8.
  159899. * What's actually stored is 1/divisor so that the inner loop can
  159900. * use a multiplication rather than a division.
  159901. */
  159902. FAST_FLOAT * fdtbl;
  159903. int row, col;
  159904. static const double aanscalefactor[DCTSIZE] = {
  159905. 1.0, 1.387039845, 1.306562965, 1.175875602,
  159906. 1.0, 0.785694958, 0.541196100, 0.275899379
  159907. };
  159908. if (fdct->float_divisors[qtblno] == NULL) {
  159909. fdct->float_divisors[qtblno] = (FAST_FLOAT *)
  159910. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  159911. DCTSIZE2 * SIZEOF(FAST_FLOAT));
  159912. }
  159913. fdtbl = fdct->float_divisors[qtblno];
  159914. i = 0;
  159915. for (row = 0; row < DCTSIZE; row++) {
  159916. for (col = 0; col < DCTSIZE; col++) {
  159917. fdtbl[i] = (FAST_FLOAT)
  159918. (1.0 / (((double) qtbl->quantval[i] *
  159919. aanscalefactor[row] * aanscalefactor[col] * 8.0)));
  159920. i++;
  159921. }
  159922. }
  159923. }
  159924. break;
  159925. #endif
  159926. default:
  159927. ERREXIT(cinfo, JERR_NOT_COMPILED);
  159928. break;
  159929. }
  159930. }
  159931. }
  159932. /*
  159933. * Perform forward DCT on one or more blocks of a component.
  159934. *
  159935. * The input samples are taken from the sample_data[] array starting at
  159936. * position start_row/start_col, and moving to the right for any additional
  159937. * blocks. The quantized coefficients are returned in coef_blocks[].
  159938. */
  159939. METHODDEF(void)
  159940. forward_DCT (j_compress_ptr cinfo, jpeg_component_info * compptr,
  159941. JSAMPARRAY sample_data, JBLOCKROW coef_blocks,
  159942. JDIMENSION start_row, JDIMENSION start_col,
  159943. JDIMENSION num_blocks)
  159944. /* This version is used for integer DCT implementations. */
  159945. {
  159946. /* This routine is heavily used, so it's worth coding it tightly. */
  159947. my_fdct_ptr fdct = (my_fdct_ptr) cinfo->fdct;
  159948. forward_DCT_method_ptr do_dct = fdct->do_dct;
  159949. DCTELEM * divisors = fdct->divisors[compptr->quant_tbl_no];
  159950. DCTELEM workspace[DCTSIZE2]; /* work area for FDCT subroutine */
  159951. JDIMENSION bi;
  159952. sample_data += start_row; /* fold in the vertical offset once */
  159953. for (bi = 0; bi < num_blocks; bi++, start_col += DCTSIZE) {
  159954. /* Load data into workspace, applying unsigned->signed conversion */
  159955. { register DCTELEM *workspaceptr;
  159956. register JSAMPROW elemptr;
  159957. register int elemr;
  159958. workspaceptr = workspace;
  159959. for (elemr = 0; elemr < DCTSIZE; elemr++) {
  159960. elemptr = sample_data[elemr] + start_col;
  159961. #if DCTSIZE == 8 /* unroll the inner loop */
  159962. *workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE;
  159963. *workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE;
  159964. *workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE;
  159965. *workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE;
  159966. *workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE;
  159967. *workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE;
  159968. *workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE;
  159969. *workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE;
  159970. #else
  159971. { register int elemc;
  159972. for (elemc = DCTSIZE; elemc > 0; elemc--) {
  159973. *workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE;
  159974. }
  159975. }
  159976. #endif
  159977. }
  159978. }
  159979. /* Perform the DCT */
  159980. (*do_dct) (workspace);
  159981. /* Quantize/descale the coefficients, and store into coef_blocks[] */
  159982. { register DCTELEM temp, qval;
  159983. register int i;
  159984. register JCOEFPTR output_ptr = coef_blocks[bi];
  159985. for (i = 0; i < DCTSIZE2; i++) {
  159986. qval = divisors[i];
  159987. temp = workspace[i];
  159988. /* Divide the coefficient value by qval, ensuring proper rounding.
  159989. * Since C does not specify the direction of rounding for negative
  159990. * quotients, we have to force the dividend positive for portability.
  159991. *
  159992. * In most files, at least half of the output values will be zero
  159993. * (at default quantization settings, more like three-quarters...)
  159994. * so we should ensure that this case is fast. On many machines,
  159995. * a comparison is enough cheaper than a divide to make a special test
  159996. * a win. Since both inputs will be nonnegative, we need only test
  159997. * for a < b to discover whether a/b is 0.
  159998. * If your machine's division is fast enough, define FAST_DIVIDE.
  159999. */
  160000. #ifdef FAST_DIVIDE
  160001. #define DIVIDE_BY(a,b) a /= b
  160002. #else
  160003. #define DIVIDE_BY(a,b) if (a >= b) a /= b; else a = 0
  160004. #endif
  160005. if (temp < 0) {
  160006. temp = -temp;
  160007. temp += qval>>1; /* for rounding */
  160008. DIVIDE_BY(temp, qval);
  160009. temp = -temp;
  160010. } else {
  160011. temp += qval>>1; /* for rounding */
  160012. DIVIDE_BY(temp, qval);
  160013. }
  160014. output_ptr[i] = (JCOEF) temp;
  160015. }
  160016. }
  160017. }
  160018. }
  160019. #ifdef DCT_FLOAT_SUPPORTED
  160020. METHODDEF(void)
  160021. forward_DCT_float (j_compress_ptr cinfo, jpeg_component_info * compptr,
  160022. JSAMPARRAY sample_data, JBLOCKROW coef_blocks,
  160023. JDIMENSION start_row, JDIMENSION start_col,
  160024. JDIMENSION num_blocks)
  160025. /* This version is used for floating-point DCT implementations. */
  160026. {
  160027. /* This routine is heavily used, so it's worth coding it tightly. */
  160028. my_fdct_ptr fdct = (my_fdct_ptr) cinfo->fdct;
  160029. float_DCT_method_ptr do_dct = fdct->do_float_dct;
  160030. FAST_FLOAT * divisors = fdct->float_divisors[compptr->quant_tbl_no];
  160031. FAST_FLOAT workspace[DCTSIZE2]; /* work area for FDCT subroutine */
  160032. JDIMENSION bi;
  160033. sample_data += start_row; /* fold in the vertical offset once */
  160034. for (bi = 0; bi < num_blocks; bi++, start_col += DCTSIZE) {
  160035. /* Load data into workspace, applying unsigned->signed conversion */
  160036. { register FAST_FLOAT *workspaceptr;
  160037. register JSAMPROW elemptr;
  160038. register int elemr;
  160039. workspaceptr = workspace;
  160040. for (elemr = 0; elemr < DCTSIZE; elemr++) {
  160041. elemptr = sample_data[elemr] + start_col;
  160042. #if DCTSIZE == 8 /* unroll the inner loop */
  160043. *workspaceptr++ = (FAST_FLOAT)(GETJSAMPLE(*elemptr++) - CENTERJSAMPLE);
  160044. *workspaceptr++ = (FAST_FLOAT)(GETJSAMPLE(*elemptr++) - CENTERJSAMPLE);
  160045. *workspaceptr++ = (FAST_FLOAT)(GETJSAMPLE(*elemptr++) - CENTERJSAMPLE);
  160046. *workspaceptr++ = (FAST_FLOAT)(GETJSAMPLE(*elemptr++) - CENTERJSAMPLE);
  160047. *workspaceptr++ = (FAST_FLOAT)(GETJSAMPLE(*elemptr++) - CENTERJSAMPLE);
  160048. *workspaceptr++ = (FAST_FLOAT)(GETJSAMPLE(*elemptr++) - CENTERJSAMPLE);
  160049. *workspaceptr++ = (FAST_FLOAT)(GETJSAMPLE(*elemptr++) - CENTERJSAMPLE);
  160050. *workspaceptr++ = (FAST_FLOAT)(GETJSAMPLE(*elemptr++) - CENTERJSAMPLE);
  160051. #else
  160052. { register int elemc;
  160053. for (elemc = DCTSIZE; elemc > 0; elemc--) {
  160054. *workspaceptr++ = (FAST_FLOAT)
  160055. (GETJSAMPLE(*elemptr++) - CENTERJSAMPLE);
  160056. }
  160057. }
  160058. #endif
  160059. }
  160060. }
  160061. /* Perform the DCT */
  160062. (*do_dct) (workspace);
  160063. /* Quantize/descale the coefficients, and store into coef_blocks[] */
  160064. { register FAST_FLOAT temp;
  160065. register int i;
  160066. register JCOEFPTR output_ptr = coef_blocks[bi];
  160067. for (i = 0; i < DCTSIZE2; i++) {
  160068. /* Apply the quantization and scaling factor */
  160069. temp = workspace[i] * divisors[i];
  160070. /* Round to nearest integer.
  160071. * Since C does not specify the direction of rounding for negative
  160072. * quotients, we have to force the dividend positive for portability.
  160073. * The maximum coefficient size is +-16K (for 12-bit data), so this
  160074. * code should work for either 16-bit or 32-bit ints.
  160075. */
  160076. output_ptr[i] = (JCOEF) ((int) (temp + (FAST_FLOAT) 16384.5) - 16384);
  160077. }
  160078. }
  160079. }
  160080. }
  160081. #endif /* DCT_FLOAT_SUPPORTED */
  160082. /*
  160083. * Initialize FDCT manager.
  160084. */
  160085. GLOBAL(void)
  160086. jinit_forward_dct (j_compress_ptr cinfo)
  160087. {
  160088. my_fdct_ptr fdct;
  160089. int i;
  160090. fdct = (my_fdct_ptr)
  160091. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  160092. SIZEOF(my_fdct_controller));
  160093. cinfo->fdct = (struct jpeg_forward_dct *) fdct;
  160094. fdct->pub.start_pass = start_pass_fdctmgr;
  160095. switch (cinfo->dct_method) {
  160096. #ifdef DCT_ISLOW_SUPPORTED
  160097. case JDCT_ISLOW:
  160098. fdct->pub.forward_DCT = forward_DCT;
  160099. fdct->do_dct = jpeg_fdct_islow;
  160100. break;
  160101. #endif
  160102. #ifdef DCT_IFAST_SUPPORTED
  160103. case JDCT_IFAST:
  160104. fdct->pub.forward_DCT = forward_DCT;
  160105. fdct->do_dct = jpeg_fdct_ifast;
  160106. break;
  160107. #endif
  160108. #ifdef DCT_FLOAT_SUPPORTED
  160109. case JDCT_FLOAT:
  160110. fdct->pub.forward_DCT = forward_DCT_float;
  160111. fdct->do_float_dct = jpeg_fdct_float;
  160112. break;
  160113. #endif
  160114. default:
  160115. ERREXIT(cinfo, JERR_NOT_COMPILED);
  160116. break;
  160117. }
  160118. /* Mark divisor tables unallocated */
  160119. for (i = 0; i < NUM_QUANT_TBLS; i++) {
  160120. fdct->divisors[i] = NULL;
  160121. #ifdef DCT_FLOAT_SUPPORTED
  160122. fdct->float_divisors[i] = NULL;
  160123. #endif
  160124. }
  160125. }
  160126. /*** End of inlined file: jcdctmgr.c ***/
  160127. #undef CONST_BITS
  160128. /*** Start of inlined file: jchuff.c ***/
  160129. #define JPEG_INTERNALS
  160130. /*** Start of inlined file: jchuff.h ***/
  160131. /* The legal range of a DCT coefficient is
  160132. * -1024 .. +1023 for 8-bit data;
  160133. * -16384 .. +16383 for 12-bit data.
  160134. * Hence the magnitude should always fit in 10 or 14 bits respectively.
  160135. */
  160136. #ifndef _jchuff_h_
  160137. #define _jchuff_h_
  160138. #if BITS_IN_JSAMPLE == 8
  160139. #define MAX_COEF_BITS 10
  160140. #else
  160141. #define MAX_COEF_BITS 14
  160142. #endif
  160143. /* Derived data constructed for each Huffman table */
  160144. typedef struct {
  160145. unsigned int ehufco[256]; /* code for each symbol */
  160146. char ehufsi[256]; /* length of code for each symbol */
  160147. /* If no code has been allocated for a symbol S, ehufsi[S] contains 0 */
  160148. } c_derived_tbl;
  160149. /* Short forms of external names for systems with brain-damaged linkers. */
  160150. #ifdef NEED_SHORT_EXTERNAL_NAMES
  160151. #define jpeg_make_c_derived_tbl jMkCDerived
  160152. #define jpeg_gen_optimal_table jGenOptTbl
  160153. #endif /* NEED_SHORT_EXTERNAL_NAMES */
  160154. /* Expand a Huffman table definition into the derived format */
  160155. EXTERN(void) jpeg_make_c_derived_tbl
  160156. JPP((j_compress_ptr cinfo, boolean isDC, int tblno,
  160157. c_derived_tbl ** pdtbl));
  160158. /* Generate an optimal table definition given the specified counts */
  160159. EXTERN(void) jpeg_gen_optimal_table
  160160. JPP((j_compress_ptr cinfo, JHUFF_TBL * htbl, long freq[]));
  160161. #endif
  160162. /*** End of inlined file: jchuff.h ***/
  160163. /* Declarations shared with jcphuff.c */
  160164. /* Expanded entropy encoder object for Huffman encoding.
  160165. *
  160166. * The savable_state subrecord contains fields that change within an MCU,
  160167. * but must not be updated permanently until we complete the MCU.
  160168. */
  160169. typedef struct {
  160170. INT32 put_buffer; /* current bit-accumulation buffer */
  160171. int put_bits; /* # of bits now in it */
  160172. int last_dc_val[MAX_COMPS_IN_SCAN]; /* last DC coef for each component */
  160173. } savable_state;
  160174. /* This macro is to work around compilers with missing or broken
  160175. * structure assignment. You'll need to fix this code if you have
  160176. * such a compiler and you change MAX_COMPS_IN_SCAN.
  160177. */
  160178. #ifndef NO_STRUCT_ASSIGN
  160179. #define ASSIGN_STATE(dest,src) ((dest) = (src))
  160180. #else
  160181. #if MAX_COMPS_IN_SCAN == 4
  160182. #define ASSIGN_STATE(dest,src) \
  160183. ((dest).put_buffer = (src).put_buffer, \
  160184. (dest).put_bits = (src).put_bits, \
  160185. (dest).last_dc_val[0] = (src).last_dc_val[0], \
  160186. (dest).last_dc_val[1] = (src).last_dc_val[1], \
  160187. (dest).last_dc_val[2] = (src).last_dc_val[2], \
  160188. (dest).last_dc_val[3] = (src).last_dc_val[3])
  160189. #endif
  160190. #endif
  160191. typedef struct {
  160192. struct jpeg_entropy_encoder pub; /* public fields */
  160193. savable_state saved; /* Bit buffer & DC state at start of MCU */
  160194. /* These fields are NOT loaded into local working state. */
  160195. unsigned int restarts_to_go; /* MCUs left in this restart interval */
  160196. int next_restart_num; /* next restart number to write (0-7) */
  160197. /* Pointers to derived tables (these workspaces have image lifespan) */
  160198. c_derived_tbl * dc_derived_tbls[NUM_HUFF_TBLS];
  160199. c_derived_tbl * ac_derived_tbls[NUM_HUFF_TBLS];
  160200. #ifdef ENTROPY_OPT_SUPPORTED /* Statistics tables for optimization */
  160201. long * dc_count_ptrs[NUM_HUFF_TBLS];
  160202. long * ac_count_ptrs[NUM_HUFF_TBLS];
  160203. #endif
  160204. } huff_entropy_encoder;
  160205. typedef huff_entropy_encoder * huff_entropy_ptr;
  160206. /* Working state while writing an MCU.
  160207. * This struct contains all the fields that are needed by subroutines.
  160208. */
  160209. typedef struct {
  160210. JOCTET * next_output_byte; /* => next byte to write in buffer */
  160211. size_t free_in_buffer; /* # of byte spaces remaining in buffer */
  160212. savable_state cur; /* Current bit buffer & DC state */
  160213. j_compress_ptr cinfo; /* dump_buffer needs access to this */
  160214. } working_state;
  160215. /* Forward declarations */
  160216. METHODDEF(boolean) encode_mcu_huff JPP((j_compress_ptr cinfo,
  160217. JBLOCKROW *MCU_data));
  160218. METHODDEF(void) finish_pass_huff JPP((j_compress_ptr cinfo));
  160219. #ifdef ENTROPY_OPT_SUPPORTED
  160220. METHODDEF(boolean) encode_mcu_gather JPP((j_compress_ptr cinfo,
  160221. JBLOCKROW *MCU_data));
  160222. METHODDEF(void) finish_pass_gather JPP((j_compress_ptr cinfo));
  160223. #endif
  160224. /*
  160225. * Initialize for a Huffman-compressed scan.
  160226. * If gather_statistics is TRUE, we do not output anything during the scan,
  160227. * just count the Huffman symbols used and generate Huffman code tables.
  160228. */
  160229. METHODDEF(void)
  160230. start_pass_huff (j_compress_ptr cinfo, boolean gather_statistics)
  160231. {
  160232. huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;
  160233. int ci, dctbl, actbl;
  160234. jpeg_component_info * compptr;
  160235. if (gather_statistics) {
  160236. #ifdef ENTROPY_OPT_SUPPORTED
  160237. entropy->pub.encode_mcu = encode_mcu_gather;
  160238. entropy->pub.finish_pass = finish_pass_gather;
  160239. #else
  160240. ERREXIT(cinfo, JERR_NOT_COMPILED);
  160241. #endif
  160242. } else {
  160243. entropy->pub.encode_mcu = encode_mcu_huff;
  160244. entropy->pub.finish_pass = finish_pass_huff;
  160245. }
  160246. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  160247. compptr = cinfo->cur_comp_info[ci];
  160248. dctbl = compptr->dc_tbl_no;
  160249. actbl = compptr->ac_tbl_no;
  160250. if (gather_statistics) {
  160251. #ifdef ENTROPY_OPT_SUPPORTED
  160252. /* Check for invalid table indexes */
  160253. /* (make_c_derived_tbl does this in the other path) */
  160254. if (dctbl < 0 || dctbl >= NUM_HUFF_TBLS)
  160255. ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, dctbl);
  160256. if (actbl < 0 || actbl >= NUM_HUFF_TBLS)
  160257. ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, actbl);
  160258. /* Allocate and zero the statistics tables */
  160259. /* Note that jpeg_gen_optimal_table expects 257 entries in each table! */
  160260. if (entropy->dc_count_ptrs[dctbl] == NULL)
  160261. entropy->dc_count_ptrs[dctbl] = (long *)
  160262. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  160263. 257 * SIZEOF(long));
  160264. MEMZERO(entropy->dc_count_ptrs[dctbl], 257 * SIZEOF(long));
  160265. if (entropy->ac_count_ptrs[actbl] == NULL)
  160266. entropy->ac_count_ptrs[actbl] = (long *)
  160267. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  160268. 257 * SIZEOF(long));
  160269. MEMZERO(entropy->ac_count_ptrs[actbl], 257 * SIZEOF(long));
  160270. #endif
  160271. } else {
  160272. /* Compute derived values for Huffman tables */
  160273. /* We may do this more than once for a table, but it's not expensive */
  160274. jpeg_make_c_derived_tbl(cinfo, TRUE, dctbl,
  160275. & entropy->dc_derived_tbls[dctbl]);
  160276. jpeg_make_c_derived_tbl(cinfo, FALSE, actbl,
  160277. & entropy->ac_derived_tbls[actbl]);
  160278. }
  160279. /* Initialize DC predictions to 0 */
  160280. entropy->saved.last_dc_val[ci] = 0;
  160281. }
  160282. /* Initialize bit buffer to empty */
  160283. entropy->saved.put_buffer = 0;
  160284. entropy->saved.put_bits = 0;
  160285. /* Initialize restart stuff */
  160286. entropy->restarts_to_go = cinfo->restart_interval;
  160287. entropy->next_restart_num = 0;
  160288. }
  160289. /*
  160290. * Compute the derived values for a Huffman table.
  160291. * This routine also performs some validation checks on the table.
  160292. *
  160293. * Note this is also used by jcphuff.c.
  160294. */
  160295. GLOBAL(void)
  160296. jpeg_make_c_derived_tbl (j_compress_ptr cinfo, boolean isDC, int tblno,
  160297. c_derived_tbl ** pdtbl)
  160298. {
  160299. JHUFF_TBL *htbl;
  160300. c_derived_tbl *dtbl;
  160301. int p, i, l, lastp, si, maxsymbol;
  160302. char huffsize[257];
  160303. unsigned int huffcode[257];
  160304. unsigned int code;
  160305. /* Note that huffsize[] and huffcode[] are filled in code-length order,
  160306. * paralleling the order of the symbols themselves in htbl->huffval[].
  160307. */
  160308. /* Find the input Huffman table */
  160309. if (tblno < 0 || tblno >= NUM_HUFF_TBLS)
  160310. ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, tblno);
  160311. htbl =
  160312. isDC ? cinfo->dc_huff_tbl_ptrs[tblno] : cinfo->ac_huff_tbl_ptrs[tblno];
  160313. if (htbl == NULL)
  160314. ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, tblno);
  160315. /* Allocate a workspace if we haven't already done so. */
  160316. if (*pdtbl == NULL)
  160317. *pdtbl = (c_derived_tbl *)
  160318. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  160319. SIZEOF(c_derived_tbl));
  160320. dtbl = *pdtbl;
  160321. /* Figure C.1: make table of Huffman code length for each symbol */
  160322. p = 0;
  160323. for (l = 1; l <= 16; l++) {
  160324. i = (int) htbl->bits[l];
  160325. if (i < 0 || p + i > 256) /* protect against table overrun */
  160326. ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
  160327. while (i--)
  160328. huffsize[p++] = (char) l;
  160329. }
  160330. huffsize[p] = 0;
  160331. lastp = p;
  160332. /* Figure C.2: generate the codes themselves */
  160333. /* We also validate that the counts represent a legal Huffman code tree. */
  160334. code = 0;
  160335. si = huffsize[0];
  160336. p = 0;
  160337. while (huffsize[p]) {
  160338. while (((int) huffsize[p]) == si) {
  160339. huffcode[p++] = code;
  160340. code++;
  160341. }
  160342. /* code is now 1 more than the last code used for codelength si; but
  160343. * it must still fit in si bits, since no code is allowed to be all ones.
  160344. */
  160345. if (((INT32) code) >= (((INT32) 1) << si))
  160346. ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
  160347. code <<= 1;
  160348. si++;
  160349. }
  160350. /* Figure C.3: generate encoding tables */
  160351. /* These are code and size indexed by symbol value */
  160352. /* Set all codeless symbols to have code length 0;
  160353. * this lets us detect duplicate VAL entries here, and later
  160354. * allows emit_bits to detect any attempt to emit such symbols.
  160355. */
  160356. MEMZERO(dtbl->ehufsi, SIZEOF(dtbl->ehufsi));
  160357. /* This is also a convenient place to check for out-of-range
  160358. * and duplicated VAL entries. We allow 0..255 for AC symbols
  160359. * but only 0..15 for DC. (We could constrain them further
  160360. * based on data depth and mode, but this seems enough.)
  160361. */
  160362. maxsymbol = isDC ? 15 : 255;
  160363. for (p = 0; p < lastp; p++) {
  160364. i = htbl->huffval[p];
  160365. if (i < 0 || i > maxsymbol || dtbl->ehufsi[i])
  160366. ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
  160367. dtbl->ehufco[i] = huffcode[p];
  160368. dtbl->ehufsi[i] = huffsize[p];
  160369. }
  160370. }
  160371. /* Outputting bytes to the file */
  160372. /* Emit a byte, taking 'action' if must suspend. */
  160373. #define emit_byte(state,val,action) \
  160374. { *(state)->next_output_byte++ = (JOCTET) (val); \
  160375. if (--(state)->free_in_buffer == 0) \
  160376. if (! dump_buffer(state)) \
  160377. { action; } }
  160378. LOCAL(boolean)
  160379. dump_buffer (working_state * state)
  160380. /* Empty the output buffer; return TRUE if successful, FALSE if must suspend */
  160381. {
  160382. struct jpeg_destination_mgr * dest = state->cinfo->dest;
  160383. if (! (*dest->empty_output_buffer) (state->cinfo))
  160384. return FALSE;
  160385. /* After a successful buffer dump, must reset buffer pointers */
  160386. state->next_output_byte = dest->next_output_byte;
  160387. state->free_in_buffer = dest->free_in_buffer;
  160388. return TRUE;
  160389. }
  160390. /* Outputting bits to the file */
  160391. /* Only the right 24 bits of put_buffer are used; the valid bits are
  160392. * left-justified in this part. At most 16 bits can be passed to emit_bits
  160393. * in one call, and we never retain more than 7 bits in put_buffer
  160394. * between calls, so 24 bits are sufficient.
  160395. */
  160396. INLINE
  160397. LOCAL(boolean)
  160398. emit_bits (working_state * state, unsigned int code, int size)
  160399. /* Emit some bits; return TRUE if successful, FALSE if must suspend */
  160400. {
  160401. /* This routine is heavily used, so it's worth coding tightly. */
  160402. register INT32 put_buffer = (INT32) code;
  160403. register int put_bits = state->cur.put_bits;
  160404. /* if size is 0, caller used an invalid Huffman table entry */
  160405. if (size == 0)
  160406. ERREXIT(state->cinfo, JERR_HUFF_MISSING_CODE);
  160407. put_buffer &= (((INT32) 1)<<size) - 1; /* mask off any extra bits in code */
  160408. put_bits += size; /* new number of bits in buffer */
  160409. put_buffer <<= 24 - put_bits; /* align incoming bits */
  160410. put_buffer |= state->cur.put_buffer; /* and merge with old buffer contents */
  160411. while (put_bits >= 8) {
  160412. int c = (int) ((put_buffer >> 16) & 0xFF);
  160413. emit_byte(state, c, return FALSE);
  160414. if (c == 0xFF) { /* need to stuff a zero byte? */
  160415. emit_byte(state, 0, return FALSE);
  160416. }
  160417. put_buffer <<= 8;
  160418. put_bits -= 8;
  160419. }
  160420. state->cur.put_buffer = put_buffer; /* update state variables */
  160421. state->cur.put_bits = put_bits;
  160422. return TRUE;
  160423. }
  160424. LOCAL(boolean)
  160425. flush_bits (working_state * state)
  160426. {
  160427. if (! emit_bits(state, 0x7F, 7)) /* fill any partial byte with ones */
  160428. return FALSE;
  160429. state->cur.put_buffer = 0; /* and reset bit-buffer to empty */
  160430. state->cur.put_bits = 0;
  160431. return TRUE;
  160432. }
  160433. /* Encode a single block's worth of coefficients */
  160434. LOCAL(boolean)
  160435. encode_one_block (working_state * state, JCOEFPTR block, int last_dc_val,
  160436. c_derived_tbl *dctbl, c_derived_tbl *actbl)
  160437. {
  160438. register int temp, temp2;
  160439. register int nbits;
  160440. register int k, r, i;
  160441. /* Encode the DC coefficient difference per section F.1.2.1 */
  160442. temp = temp2 = block[0] - last_dc_val;
  160443. if (temp < 0) {
  160444. temp = -temp; /* temp is abs value of input */
  160445. /* For a negative input, want temp2 = bitwise complement of abs(input) */
  160446. /* This code assumes we are on a two's complement machine */
  160447. temp2--;
  160448. }
  160449. /* Find the number of bits needed for the magnitude of the coefficient */
  160450. nbits = 0;
  160451. while (temp) {
  160452. nbits++;
  160453. temp >>= 1;
  160454. }
  160455. /* Check for out-of-range coefficient values.
  160456. * Since we're encoding a difference, the range limit is twice as much.
  160457. */
  160458. if (nbits > MAX_COEF_BITS+1)
  160459. ERREXIT(state->cinfo, JERR_BAD_DCT_COEF);
  160460. /* Emit the Huffman-coded symbol for the number of bits */
  160461. if (! emit_bits(state, dctbl->ehufco[nbits], dctbl->ehufsi[nbits]))
  160462. return FALSE;
  160463. /* Emit that number of bits of the value, if positive, */
  160464. /* or the complement of its magnitude, if negative. */
  160465. if (nbits) /* emit_bits rejects calls with size 0 */
  160466. if (! emit_bits(state, (unsigned int) temp2, nbits))
  160467. return FALSE;
  160468. /* Encode the AC coefficients per section F.1.2.2 */
  160469. r = 0; /* r = run length of zeros */
  160470. for (k = 1; k < DCTSIZE2; k++) {
  160471. if ((temp = block[jpeg_natural_order[k]]) == 0) {
  160472. r++;
  160473. } else {
  160474. /* if run length > 15, must emit special run-length-16 codes (0xF0) */
  160475. while (r > 15) {
  160476. if (! emit_bits(state, actbl->ehufco[0xF0], actbl->ehufsi[0xF0]))
  160477. return FALSE;
  160478. r -= 16;
  160479. }
  160480. temp2 = temp;
  160481. if (temp < 0) {
  160482. temp = -temp; /* temp is abs value of input */
  160483. /* This code assumes we are on a two's complement machine */
  160484. temp2--;
  160485. }
  160486. /* Find the number of bits needed for the magnitude of the coefficient */
  160487. nbits = 1; /* there must be at least one 1 bit */
  160488. while ((temp >>= 1))
  160489. nbits++;
  160490. /* Check for out-of-range coefficient values */
  160491. if (nbits > MAX_COEF_BITS)
  160492. ERREXIT(state->cinfo, JERR_BAD_DCT_COEF);
  160493. /* Emit Huffman symbol for run length / number of bits */
  160494. i = (r << 4) + nbits;
  160495. if (! emit_bits(state, actbl->ehufco[i], actbl->ehufsi[i]))
  160496. return FALSE;
  160497. /* Emit that number of bits of the value, if positive, */
  160498. /* or the complement of its magnitude, if negative. */
  160499. if (! emit_bits(state, (unsigned int) temp2, nbits))
  160500. return FALSE;
  160501. r = 0;
  160502. }
  160503. }
  160504. /* If the last coef(s) were zero, emit an end-of-block code */
  160505. if (r > 0)
  160506. if (! emit_bits(state, actbl->ehufco[0], actbl->ehufsi[0]))
  160507. return FALSE;
  160508. return TRUE;
  160509. }
  160510. /*
  160511. * Emit a restart marker & resynchronize predictions.
  160512. */
  160513. LOCAL(boolean)
  160514. emit_restart (working_state * state, int restart_num)
  160515. {
  160516. int ci;
  160517. if (! flush_bits(state))
  160518. return FALSE;
  160519. emit_byte(state, 0xFF, return FALSE);
  160520. emit_byte(state, JPEG_RST0 + restart_num, return FALSE);
  160521. /* Re-initialize DC predictions to 0 */
  160522. for (ci = 0; ci < state->cinfo->comps_in_scan; ci++)
  160523. state->cur.last_dc_val[ci] = 0;
  160524. /* The restart counter is not updated until we successfully write the MCU. */
  160525. return TRUE;
  160526. }
  160527. /*
  160528. * Encode and output one MCU's worth of Huffman-compressed coefficients.
  160529. */
  160530. METHODDEF(boolean)
  160531. encode_mcu_huff (j_compress_ptr cinfo, JBLOCKROW *MCU_data)
  160532. {
  160533. huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;
  160534. working_state state;
  160535. int blkn, ci;
  160536. jpeg_component_info * compptr;
  160537. /* Load up working state */
  160538. state.next_output_byte = cinfo->dest->next_output_byte;
  160539. state.free_in_buffer = cinfo->dest->free_in_buffer;
  160540. ASSIGN_STATE(state.cur, entropy->saved);
  160541. state.cinfo = cinfo;
  160542. /* Emit restart marker if needed */
  160543. if (cinfo->restart_interval) {
  160544. if (entropy->restarts_to_go == 0)
  160545. if (! emit_restart(&state, entropy->next_restart_num))
  160546. return FALSE;
  160547. }
  160548. /* Encode the MCU data blocks */
  160549. for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
  160550. ci = cinfo->MCU_membership[blkn];
  160551. compptr = cinfo->cur_comp_info[ci];
  160552. if (! encode_one_block(&state,
  160553. MCU_data[blkn][0], state.cur.last_dc_val[ci],
  160554. entropy->dc_derived_tbls[compptr->dc_tbl_no],
  160555. entropy->ac_derived_tbls[compptr->ac_tbl_no]))
  160556. return FALSE;
  160557. /* Update last_dc_val */
  160558. state.cur.last_dc_val[ci] = MCU_data[blkn][0][0];
  160559. }
  160560. /* Completed MCU, so update state */
  160561. cinfo->dest->next_output_byte = state.next_output_byte;
  160562. cinfo->dest->free_in_buffer = state.free_in_buffer;
  160563. ASSIGN_STATE(entropy->saved, state.cur);
  160564. /* Update restart-interval state too */
  160565. if (cinfo->restart_interval) {
  160566. if (entropy->restarts_to_go == 0) {
  160567. entropy->restarts_to_go = cinfo->restart_interval;
  160568. entropy->next_restart_num++;
  160569. entropy->next_restart_num &= 7;
  160570. }
  160571. entropy->restarts_to_go--;
  160572. }
  160573. return TRUE;
  160574. }
  160575. /*
  160576. * Finish up at the end of a Huffman-compressed scan.
  160577. */
  160578. METHODDEF(void)
  160579. finish_pass_huff (j_compress_ptr cinfo)
  160580. {
  160581. huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;
  160582. working_state state;
  160583. /* Load up working state ... flush_bits needs it */
  160584. state.next_output_byte = cinfo->dest->next_output_byte;
  160585. state.free_in_buffer = cinfo->dest->free_in_buffer;
  160586. ASSIGN_STATE(state.cur, entropy->saved);
  160587. state.cinfo = cinfo;
  160588. /* Flush out the last data */
  160589. if (! flush_bits(&state))
  160590. ERREXIT(cinfo, JERR_CANT_SUSPEND);
  160591. /* Update state */
  160592. cinfo->dest->next_output_byte = state.next_output_byte;
  160593. cinfo->dest->free_in_buffer = state.free_in_buffer;
  160594. ASSIGN_STATE(entropy->saved, state.cur);
  160595. }
  160596. /*
  160597. * Huffman coding optimization.
  160598. *
  160599. * We first scan the supplied data and count the number of uses of each symbol
  160600. * that is to be Huffman-coded. (This process MUST agree with the code above.)
  160601. * Then we build a Huffman coding tree for the observed counts.
  160602. * Symbols which are not needed at all for the particular image are not
  160603. * assigned any code, which saves space in the DHT marker as well as in
  160604. * the compressed data.
  160605. */
  160606. #ifdef ENTROPY_OPT_SUPPORTED
  160607. /* Process a single block's worth of coefficients */
  160608. LOCAL(void)
  160609. htest_one_block (j_compress_ptr cinfo, JCOEFPTR block, int last_dc_val,
  160610. long dc_counts[], long ac_counts[])
  160611. {
  160612. register int temp;
  160613. register int nbits;
  160614. register int k, r;
  160615. /* Encode the DC coefficient difference per section F.1.2.1 */
  160616. temp = block[0] - last_dc_val;
  160617. if (temp < 0)
  160618. temp = -temp;
  160619. /* Find the number of bits needed for the magnitude of the coefficient */
  160620. nbits = 0;
  160621. while (temp) {
  160622. nbits++;
  160623. temp >>= 1;
  160624. }
  160625. /* Check for out-of-range coefficient values.
  160626. * Since we're encoding a difference, the range limit is twice as much.
  160627. */
  160628. if (nbits > MAX_COEF_BITS+1)
  160629. ERREXIT(cinfo, JERR_BAD_DCT_COEF);
  160630. /* Count the Huffman symbol for the number of bits */
  160631. dc_counts[nbits]++;
  160632. /* Encode the AC coefficients per section F.1.2.2 */
  160633. r = 0; /* r = run length of zeros */
  160634. for (k = 1; k < DCTSIZE2; k++) {
  160635. if ((temp = block[jpeg_natural_order[k]]) == 0) {
  160636. r++;
  160637. } else {
  160638. /* if run length > 15, must emit special run-length-16 codes (0xF0) */
  160639. while (r > 15) {
  160640. ac_counts[0xF0]++;
  160641. r -= 16;
  160642. }
  160643. /* Find the number of bits needed for the magnitude of the coefficient */
  160644. if (temp < 0)
  160645. temp = -temp;
  160646. /* Find the number of bits needed for the magnitude of the coefficient */
  160647. nbits = 1; /* there must be at least one 1 bit */
  160648. while ((temp >>= 1))
  160649. nbits++;
  160650. /* Check for out-of-range coefficient values */
  160651. if (nbits > MAX_COEF_BITS)
  160652. ERREXIT(cinfo, JERR_BAD_DCT_COEF);
  160653. /* Count Huffman symbol for run length / number of bits */
  160654. ac_counts[(r << 4) + nbits]++;
  160655. r = 0;
  160656. }
  160657. }
  160658. /* If the last coef(s) were zero, emit an end-of-block code */
  160659. if (r > 0)
  160660. ac_counts[0]++;
  160661. }
  160662. /*
  160663. * Trial-encode one MCU's worth of Huffman-compressed coefficients.
  160664. * No data is actually output, so no suspension return is possible.
  160665. */
  160666. METHODDEF(boolean)
  160667. encode_mcu_gather (j_compress_ptr cinfo, JBLOCKROW *MCU_data)
  160668. {
  160669. huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;
  160670. int blkn, ci;
  160671. jpeg_component_info * compptr;
  160672. /* Take care of restart intervals if needed */
  160673. if (cinfo->restart_interval) {
  160674. if (entropy->restarts_to_go == 0) {
  160675. /* Re-initialize DC predictions to 0 */
  160676. for (ci = 0; ci < cinfo->comps_in_scan; ci++)
  160677. entropy->saved.last_dc_val[ci] = 0;
  160678. /* Update restart state */
  160679. entropy->restarts_to_go = cinfo->restart_interval;
  160680. }
  160681. entropy->restarts_to_go--;
  160682. }
  160683. for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
  160684. ci = cinfo->MCU_membership[blkn];
  160685. compptr = cinfo->cur_comp_info[ci];
  160686. htest_one_block(cinfo, MCU_data[blkn][0], entropy->saved.last_dc_val[ci],
  160687. entropy->dc_count_ptrs[compptr->dc_tbl_no],
  160688. entropy->ac_count_ptrs[compptr->ac_tbl_no]);
  160689. entropy->saved.last_dc_val[ci] = MCU_data[blkn][0][0];
  160690. }
  160691. return TRUE;
  160692. }
  160693. /*
  160694. * Generate the best Huffman code table for the given counts, fill htbl.
  160695. * Note this is also used by jcphuff.c.
  160696. *
  160697. * The JPEG standard requires that no symbol be assigned a codeword of all
  160698. * one bits (so that padding bits added at the end of a compressed segment
  160699. * can't look like a valid code). Because of the canonical ordering of
  160700. * codewords, this just means that there must be an unused slot in the
  160701. * longest codeword length category. Section K.2 of the JPEG spec suggests
  160702. * reserving such a slot by pretending that symbol 256 is a valid symbol
  160703. * with count 1. In theory that's not optimal; giving it count zero but
  160704. * including it in the symbol set anyway should give a better Huffman code.
  160705. * But the theoretically better code actually seems to come out worse in
  160706. * practice, because it produces more all-ones bytes (which incur stuffed
  160707. * zero bytes in the final file). In any case the difference is tiny.
  160708. *
  160709. * The JPEG standard requires Huffman codes to be no more than 16 bits long.
  160710. * If some symbols have a very small but nonzero probability, the Huffman tree
  160711. * must be adjusted to meet the code length restriction. We currently use
  160712. * the adjustment method suggested in JPEG section K.2. This method is *not*
  160713. * optimal; it may not choose the best possible limited-length code. But
  160714. * typically only very-low-frequency symbols will be given less-than-optimal
  160715. * lengths, so the code is almost optimal. Experimental comparisons against
  160716. * an optimal limited-length-code algorithm indicate that the difference is
  160717. * microscopic --- usually less than a hundredth of a percent of total size.
  160718. * So the extra complexity of an optimal algorithm doesn't seem worthwhile.
  160719. */
  160720. GLOBAL(void)
  160721. jpeg_gen_optimal_table (j_compress_ptr cinfo, JHUFF_TBL * htbl, long freq[])
  160722. {
  160723. #define MAX_CLEN 32 /* assumed maximum initial code length */
  160724. UINT8 bits[MAX_CLEN+1]; /* bits[k] = # of symbols with code length k */
  160725. int codesize[257]; /* codesize[k] = code length of symbol k */
  160726. int others[257]; /* next symbol in current branch of tree */
  160727. int c1, c2;
  160728. int p, i, j;
  160729. long v;
  160730. /* This algorithm is explained in section K.2 of the JPEG standard */
  160731. MEMZERO(bits, SIZEOF(bits));
  160732. MEMZERO(codesize, SIZEOF(codesize));
  160733. for (i = 0; i < 257; i++)
  160734. others[i] = -1; /* init links to empty */
  160735. freq[256] = 1; /* make sure 256 has a nonzero count */
  160736. /* Including the pseudo-symbol 256 in the Huffman procedure guarantees
  160737. * that no real symbol is given code-value of all ones, because 256
  160738. * will be placed last in the largest codeword category.
  160739. */
  160740. /* Huffman's basic algorithm to assign optimal code lengths to symbols */
  160741. for (;;) {
  160742. /* Find the smallest nonzero frequency, set c1 = its symbol */
  160743. /* In case of ties, take the larger symbol number */
  160744. c1 = -1;
  160745. v = 1000000000L;
  160746. for (i = 0; i <= 256; i++) {
  160747. if (freq[i] && freq[i] <= v) {
  160748. v = freq[i];
  160749. c1 = i;
  160750. }
  160751. }
  160752. /* Find the next smallest nonzero frequency, set c2 = its symbol */
  160753. /* In case of ties, take the larger symbol number */
  160754. c2 = -1;
  160755. v = 1000000000L;
  160756. for (i = 0; i <= 256; i++) {
  160757. if (freq[i] && freq[i] <= v && i != c1) {
  160758. v = freq[i];
  160759. c2 = i;
  160760. }
  160761. }
  160762. /* Done if we've merged everything into one frequency */
  160763. if (c2 < 0)
  160764. break;
  160765. /* Else merge the two counts/trees */
  160766. freq[c1] += freq[c2];
  160767. freq[c2] = 0;
  160768. /* Increment the codesize of everything in c1's tree branch */
  160769. codesize[c1]++;
  160770. while (others[c1] >= 0) {
  160771. c1 = others[c1];
  160772. codesize[c1]++;
  160773. }
  160774. others[c1] = c2; /* chain c2 onto c1's tree branch */
  160775. /* Increment the codesize of everything in c2's tree branch */
  160776. codesize[c2]++;
  160777. while (others[c2] >= 0) {
  160778. c2 = others[c2];
  160779. codesize[c2]++;
  160780. }
  160781. }
  160782. /* Now count the number of symbols of each code length */
  160783. for (i = 0; i <= 256; i++) {
  160784. if (codesize[i]) {
  160785. /* The JPEG standard seems to think that this can't happen, */
  160786. /* but I'm paranoid... */
  160787. if (codesize[i] > MAX_CLEN)
  160788. ERREXIT(cinfo, JERR_HUFF_CLEN_OVERFLOW);
  160789. bits[codesize[i]]++;
  160790. }
  160791. }
  160792. /* JPEG doesn't allow symbols with code lengths over 16 bits, so if the pure
  160793. * Huffman procedure assigned any such lengths, we must adjust the coding.
  160794. * Here is what the JPEG spec says about how this next bit works:
  160795. * Since symbols are paired for the longest Huffman code, the symbols are
  160796. * removed from this length category two at a time. The prefix for the pair
  160797. * (which is one bit shorter) is allocated to one of the pair; then,
  160798. * skipping the BITS entry for that prefix length, a code word from the next
  160799. * shortest nonzero BITS entry is converted into a prefix for two code words
  160800. * one bit longer.
  160801. */
  160802. for (i = MAX_CLEN; i > 16; i--) {
  160803. while (bits[i] > 0) {
  160804. j = i - 2; /* find length of new prefix to be used */
  160805. while (bits[j] == 0)
  160806. j--;
  160807. bits[i] -= 2; /* remove two symbols */
  160808. bits[i-1]++; /* one goes in this length */
  160809. bits[j+1] += 2; /* two new symbols in this length */
  160810. bits[j]--; /* symbol of this length is now a prefix */
  160811. }
  160812. }
  160813. /* Remove the count for the pseudo-symbol 256 from the largest codelength */
  160814. while (bits[i] == 0) /* find largest codelength still in use */
  160815. i--;
  160816. bits[i]--;
  160817. /* Return final symbol counts (only for lengths 0..16) */
  160818. MEMCOPY(htbl->bits, bits, SIZEOF(htbl->bits));
  160819. /* Return a list of the symbols sorted by code length */
  160820. /* It's not real clear to me why we don't need to consider the codelength
  160821. * changes made above, but the JPEG spec seems to think this works.
  160822. */
  160823. p = 0;
  160824. for (i = 1; i <= MAX_CLEN; i++) {
  160825. for (j = 0; j <= 255; j++) {
  160826. if (codesize[j] == i) {
  160827. htbl->huffval[p] = (UINT8) j;
  160828. p++;
  160829. }
  160830. }
  160831. }
  160832. /* Set sent_table FALSE so updated table will be written to JPEG file. */
  160833. htbl->sent_table = FALSE;
  160834. }
  160835. /*
  160836. * Finish up a statistics-gathering pass and create the new Huffman tables.
  160837. */
  160838. METHODDEF(void)
  160839. finish_pass_gather (j_compress_ptr cinfo)
  160840. {
  160841. huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;
  160842. int ci, dctbl, actbl;
  160843. jpeg_component_info * compptr;
  160844. JHUFF_TBL **htblptr;
  160845. boolean did_dc[NUM_HUFF_TBLS];
  160846. boolean did_ac[NUM_HUFF_TBLS];
  160847. /* It's important not to apply jpeg_gen_optimal_table more than once
  160848. * per table, because it clobbers the input frequency counts!
  160849. */
  160850. MEMZERO(did_dc, SIZEOF(did_dc));
  160851. MEMZERO(did_ac, SIZEOF(did_ac));
  160852. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  160853. compptr = cinfo->cur_comp_info[ci];
  160854. dctbl = compptr->dc_tbl_no;
  160855. actbl = compptr->ac_tbl_no;
  160856. if (! did_dc[dctbl]) {
  160857. htblptr = & cinfo->dc_huff_tbl_ptrs[dctbl];
  160858. if (*htblptr == NULL)
  160859. *htblptr = jpeg_alloc_huff_table((j_common_ptr) cinfo);
  160860. jpeg_gen_optimal_table(cinfo, *htblptr, entropy->dc_count_ptrs[dctbl]);
  160861. did_dc[dctbl] = TRUE;
  160862. }
  160863. if (! did_ac[actbl]) {
  160864. htblptr = & cinfo->ac_huff_tbl_ptrs[actbl];
  160865. if (*htblptr == NULL)
  160866. *htblptr = jpeg_alloc_huff_table((j_common_ptr) cinfo);
  160867. jpeg_gen_optimal_table(cinfo, *htblptr, entropy->ac_count_ptrs[actbl]);
  160868. did_ac[actbl] = TRUE;
  160869. }
  160870. }
  160871. }
  160872. #endif /* ENTROPY_OPT_SUPPORTED */
  160873. /*
  160874. * Module initialization routine for Huffman entropy encoding.
  160875. */
  160876. GLOBAL(void)
  160877. jinit_huff_encoder (j_compress_ptr cinfo)
  160878. {
  160879. huff_entropy_ptr entropy;
  160880. int i;
  160881. entropy = (huff_entropy_ptr)
  160882. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  160883. SIZEOF(huff_entropy_encoder));
  160884. cinfo->entropy = (struct jpeg_entropy_encoder *) entropy;
  160885. entropy->pub.start_pass = start_pass_huff;
  160886. /* Mark tables unallocated */
  160887. for (i = 0; i < NUM_HUFF_TBLS; i++) {
  160888. entropy->dc_derived_tbls[i] = entropy->ac_derived_tbls[i] = NULL;
  160889. #ifdef ENTROPY_OPT_SUPPORTED
  160890. entropy->dc_count_ptrs[i] = entropy->ac_count_ptrs[i] = NULL;
  160891. #endif
  160892. }
  160893. }
  160894. /*** End of inlined file: jchuff.c ***/
  160895. #undef emit_byte
  160896. /*** Start of inlined file: jcinit.c ***/
  160897. #define JPEG_INTERNALS
  160898. /*
  160899. * Master selection of compression modules.
  160900. * This is done once at the start of processing an image. We determine
  160901. * which modules will be used and give them appropriate initialization calls.
  160902. */
  160903. GLOBAL(void)
  160904. jinit_compress_master (j_compress_ptr cinfo)
  160905. {
  160906. /* Initialize master control (includes parameter checking/processing) */
  160907. jinit_c_master_control(cinfo, FALSE /* full compression */);
  160908. /* Preprocessing */
  160909. if (! cinfo->raw_data_in) {
  160910. jinit_color_converter(cinfo);
  160911. jinit_downsampler(cinfo);
  160912. jinit_c_prep_controller(cinfo, FALSE /* never need full buffer here */);
  160913. }
  160914. /* Forward DCT */
  160915. jinit_forward_dct(cinfo);
  160916. /* Entropy encoding: either Huffman or arithmetic coding. */
  160917. if (cinfo->arith_code) {
  160918. ERREXIT(cinfo, JERR_ARITH_NOTIMPL);
  160919. } else {
  160920. if (cinfo->progressive_mode) {
  160921. #ifdef C_PROGRESSIVE_SUPPORTED
  160922. jinit_phuff_encoder(cinfo);
  160923. #else
  160924. ERREXIT(cinfo, JERR_NOT_COMPILED);
  160925. #endif
  160926. } else
  160927. jinit_huff_encoder(cinfo);
  160928. }
  160929. /* Need a full-image coefficient buffer in any multi-pass mode. */
  160930. jinit_c_coef_controller(cinfo,
  160931. (boolean) (cinfo->num_scans > 1 || cinfo->optimize_coding));
  160932. jinit_c_main_controller(cinfo, FALSE /* never need full buffer here */);
  160933. jinit_marker_writer(cinfo);
  160934. /* We can now tell the memory manager to allocate virtual arrays. */
  160935. (*cinfo->mem->realize_virt_arrays) ((j_common_ptr) cinfo);
  160936. /* Write the datastream header (SOI) immediately.
  160937. * Frame and scan headers are postponed till later.
  160938. * This lets application insert special markers after the SOI.
  160939. */
  160940. (*cinfo->marker->write_file_header) (cinfo);
  160941. }
  160942. /*** End of inlined file: jcinit.c ***/
  160943. /*** Start of inlined file: jcmainct.c ***/
  160944. #define JPEG_INTERNALS
  160945. /* Note: currently, there is no operating mode in which a full-image buffer
  160946. * is needed at this step. If there were, that mode could not be used with
  160947. * "raw data" input, since this module is bypassed in that case. However,
  160948. * we've left the code here for possible use in special applications.
  160949. */
  160950. #undef FULL_MAIN_BUFFER_SUPPORTED
  160951. /* Private buffer controller object */
  160952. typedef struct {
  160953. struct jpeg_c_main_controller pub; /* public fields */
  160954. JDIMENSION cur_iMCU_row; /* number of current iMCU row */
  160955. JDIMENSION rowgroup_ctr; /* counts row groups received in iMCU row */
  160956. boolean suspended; /* remember if we suspended output */
  160957. J_BUF_MODE pass_mode; /* current operating mode */
  160958. /* If using just a strip buffer, this points to the entire set of buffers
  160959. * (we allocate one for each component). In the full-image case, this
  160960. * points to the currently accessible strips of the virtual arrays.
  160961. */
  160962. JSAMPARRAY buffer[MAX_COMPONENTS];
  160963. #ifdef FULL_MAIN_BUFFER_SUPPORTED
  160964. /* If using full-image storage, this array holds pointers to virtual-array
  160965. * control blocks for each component. Unused if not full-image storage.
  160966. */
  160967. jvirt_sarray_ptr whole_image[MAX_COMPONENTS];
  160968. #endif
  160969. } my_main_controller;
  160970. typedef my_main_controller * my_main_ptr;
  160971. /* Forward declarations */
  160972. METHODDEF(void) process_data_simple_main
  160973. JPP((j_compress_ptr cinfo, JSAMPARRAY input_buf,
  160974. JDIMENSION *in_row_ctr, JDIMENSION in_rows_avail));
  160975. #ifdef FULL_MAIN_BUFFER_SUPPORTED
  160976. METHODDEF(void) process_data_buffer_main
  160977. JPP((j_compress_ptr cinfo, JSAMPARRAY input_buf,
  160978. JDIMENSION *in_row_ctr, JDIMENSION in_rows_avail));
  160979. #endif
  160980. /*
  160981. * Initialize for a processing pass.
  160982. */
  160983. METHODDEF(void)
  160984. start_pass_main (j_compress_ptr cinfo, J_BUF_MODE pass_mode)
  160985. {
  160986. my_main_ptr main_ = (my_main_ptr) cinfo->main;
  160987. /* Do nothing in raw-data mode. */
  160988. if (cinfo->raw_data_in)
  160989. return;
  160990. main_->cur_iMCU_row = 0; /* initialize counters */
  160991. main_->rowgroup_ctr = 0;
  160992. main_->suspended = FALSE;
  160993. main_->pass_mode = pass_mode; /* save mode for use by process_data */
  160994. switch (pass_mode) {
  160995. case JBUF_PASS_THRU:
  160996. #ifdef FULL_MAIN_BUFFER_SUPPORTED
  160997. if (main_->whole_image[0] != NULL)
  160998. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  160999. #endif
  161000. main_->pub.process_data = process_data_simple_main;
  161001. break;
  161002. #ifdef FULL_MAIN_BUFFER_SUPPORTED
  161003. case JBUF_SAVE_SOURCE:
  161004. case JBUF_CRANK_DEST:
  161005. case JBUF_SAVE_AND_PASS:
  161006. if (main_->whole_image[0] == NULL)
  161007. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  161008. main_->pub.process_data = process_data_buffer_main;
  161009. break;
  161010. #endif
  161011. default:
  161012. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  161013. break;
  161014. }
  161015. }
  161016. /*
  161017. * Process some data.
  161018. * This routine handles the simple pass-through mode,
  161019. * where we have only a strip buffer.
  161020. */
  161021. METHODDEF(void)
  161022. process_data_simple_main (j_compress_ptr cinfo,
  161023. JSAMPARRAY input_buf, JDIMENSION *in_row_ctr,
  161024. JDIMENSION in_rows_avail)
  161025. {
  161026. my_main_ptr main_ = (my_main_ptr) cinfo->main;
  161027. while (main_->cur_iMCU_row < cinfo->total_iMCU_rows) {
  161028. /* Read input data if we haven't filled the main buffer yet */
  161029. if (main_->rowgroup_ctr < DCTSIZE)
  161030. (*cinfo->prep->pre_process_data) (cinfo,
  161031. input_buf, in_row_ctr, in_rows_avail,
  161032. main_->buffer, &main_->rowgroup_ctr,
  161033. (JDIMENSION) DCTSIZE);
  161034. /* If we don't have a full iMCU row buffered, return to application for
  161035. * more data. Note that preprocessor will always pad to fill the iMCU row
  161036. * at the bottom of the image.
  161037. */
  161038. if (main_->rowgroup_ctr != DCTSIZE)
  161039. return;
  161040. /* Send the completed row to the compressor */
  161041. if (! (*cinfo->coef->compress_data) (cinfo, main_->buffer)) {
  161042. /* If compressor did not consume the whole row, then we must need to
  161043. * suspend processing and return to the application. In this situation
  161044. * we pretend we didn't yet consume the last input row; otherwise, if
  161045. * it happened to be the last row of the image, the application would
  161046. * think we were done.
  161047. */
  161048. if (! main_->suspended) {
  161049. (*in_row_ctr)--;
  161050. main_->suspended = TRUE;
  161051. }
  161052. return;
  161053. }
  161054. /* We did finish the row. Undo our little suspension hack if a previous
  161055. * call suspended; then mark the main buffer empty.
  161056. */
  161057. if (main_->suspended) {
  161058. (*in_row_ctr)++;
  161059. main_->suspended = FALSE;
  161060. }
  161061. main_->rowgroup_ctr = 0;
  161062. main_->cur_iMCU_row++;
  161063. }
  161064. }
  161065. #ifdef FULL_MAIN_BUFFER_SUPPORTED
  161066. /*
  161067. * Process some data.
  161068. * This routine handles all of the modes that use a full-size buffer.
  161069. */
  161070. METHODDEF(void)
  161071. process_data_buffer_main (j_compress_ptr cinfo,
  161072. JSAMPARRAY input_buf, JDIMENSION *in_row_ctr,
  161073. JDIMENSION in_rows_avail)
  161074. {
  161075. my_main_ptr main = (my_main_ptr) cinfo->main;
  161076. int ci;
  161077. jpeg_component_info *compptr;
  161078. boolean writing = (main->pass_mode != JBUF_CRANK_DEST);
  161079. while (main->cur_iMCU_row < cinfo->total_iMCU_rows) {
  161080. /* Realign the virtual buffers if at the start of an iMCU row. */
  161081. if (main->rowgroup_ctr == 0) {
  161082. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  161083. ci++, compptr++) {
  161084. main->buffer[ci] = (*cinfo->mem->access_virt_sarray)
  161085. ((j_common_ptr) cinfo, main->whole_image[ci],
  161086. main->cur_iMCU_row * (compptr->v_samp_factor * DCTSIZE),
  161087. (JDIMENSION) (compptr->v_samp_factor * DCTSIZE), writing);
  161088. }
  161089. /* In a read pass, pretend we just read some source data. */
  161090. if (! writing) {
  161091. *in_row_ctr += cinfo->max_v_samp_factor * DCTSIZE;
  161092. main->rowgroup_ctr = DCTSIZE;
  161093. }
  161094. }
  161095. /* If a write pass, read input data until the current iMCU row is full. */
  161096. /* Note: preprocessor will pad if necessary to fill the last iMCU row. */
  161097. if (writing) {
  161098. (*cinfo->prep->pre_process_data) (cinfo,
  161099. input_buf, in_row_ctr, in_rows_avail,
  161100. main->buffer, &main->rowgroup_ctr,
  161101. (JDIMENSION) DCTSIZE);
  161102. /* Return to application if we need more data to fill the iMCU row. */
  161103. if (main->rowgroup_ctr < DCTSIZE)
  161104. return;
  161105. }
  161106. /* Emit data, unless this is a sink-only pass. */
  161107. if (main->pass_mode != JBUF_SAVE_SOURCE) {
  161108. if (! (*cinfo->coef->compress_data) (cinfo, main->buffer)) {
  161109. /* If compressor did not consume the whole row, then we must need to
  161110. * suspend processing and return to the application. In this situation
  161111. * we pretend we didn't yet consume the last input row; otherwise, if
  161112. * it happened to be the last row of the image, the application would
  161113. * think we were done.
  161114. */
  161115. if (! main->suspended) {
  161116. (*in_row_ctr)--;
  161117. main->suspended = TRUE;
  161118. }
  161119. return;
  161120. }
  161121. /* We did finish the row. Undo our little suspension hack if a previous
  161122. * call suspended; then mark the main buffer empty.
  161123. */
  161124. if (main->suspended) {
  161125. (*in_row_ctr)++;
  161126. main->suspended = FALSE;
  161127. }
  161128. }
  161129. /* If get here, we are done with this iMCU row. Mark buffer empty. */
  161130. main->rowgroup_ctr = 0;
  161131. main->cur_iMCU_row++;
  161132. }
  161133. }
  161134. #endif /* FULL_MAIN_BUFFER_SUPPORTED */
  161135. /*
  161136. * Initialize main buffer controller.
  161137. */
  161138. GLOBAL(void)
  161139. jinit_c_main_controller (j_compress_ptr cinfo, boolean need_full_buffer)
  161140. {
  161141. my_main_ptr main_;
  161142. int ci;
  161143. jpeg_component_info *compptr;
  161144. main_ = (my_main_ptr)
  161145. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  161146. SIZEOF(my_main_controller));
  161147. cinfo->main = (struct jpeg_c_main_controller *) main_;
  161148. main_->pub.start_pass = start_pass_main;
  161149. /* We don't need to create a buffer in raw-data mode. */
  161150. if (cinfo->raw_data_in)
  161151. return;
  161152. /* Create the buffer. It holds downsampled data, so each component
  161153. * may be of a different size.
  161154. */
  161155. if (need_full_buffer) {
  161156. #ifdef FULL_MAIN_BUFFER_SUPPORTED
  161157. /* Allocate a full-image virtual array for each component */
  161158. /* Note we pad the bottom to a multiple of the iMCU height */
  161159. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  161160. ci++, compptr++) {
  161161. main->whole_image[ci] = (*cinfo->mem->request_virt_sarray)
  161162. ((j_common_ptr) cinfo, JPOOL_IMAGE, FALSE,
  161163. compptr->width_in_blocks * DCTSIZE,
  161164. (JDIMENSION) jround_up((long) compptr->height_in_blocks,
  161165. (long) compptr->v_samp_factor) * DCTSIZE,
  161166. (JDIMENSION) (compptr->v_samp_factor * DCTSIZE));
  161167. }
  161168. #else
  161169. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  161170. #endif
  161171. } else {
  161172. #ifdef FULL_MAIN_BUFFER_SUPPORTED
  161173. main_->whole_image[0] = NULL; /* flag for no virtual arrays */
  161174. #endif
  161175. /* Allocate a strip buffer for each component */
  161176. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  161177. ci++, compptr++) {
  161178. main_->buffer[ci] = (*cinfo->mem->alloc_sarray)
  161179. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  161180. compptr->width_in_blocks * DCTSIZE,
  161181. (JDIMENSION) (compptr->v_samp_factor * DCTSIZE));
  161182. }
  161183. }
  161184. }
  161185. /*** End of inlined file: jcmainct.c ***/
  161186. /*** Start of inlined file: jcmarker.c ***/
  161187. #define JPEG_INTERNALS
  161188. /* Private state */
  161189. typedef struct {
  161190. struct jpeg_marker_writer pub; /* public fields */
  161191. unsigned int last_restart_interval; /* last DRI value emitted; 0 after SOI */
  161192. } my_marker_writer;
  161193. typedef my_marker_writer * my_marker_ptr;
  161194. /*
  161195. * Basic output routines.
  161196. *
  161197. * Note that we do not support suspension while writing a marker.
  161198. * Therefore, an application using suspension must ensure that there is
  161199. * enough buffer space for the initial markers (typ. 600-700 bytes) before
  161200. * calling jpeg_start_compress, and enough space to write the trailing EOI
  161201. * (a few bytes) before calling jpeg_finish_compress. Multipass compression
  161202. * modes are not supported at all with suspension, so those two are the only
  161203. * points where markers will be written.
  161204. */
  161205. LOCAL(void)
  161206. emit_byte (j_compress_ptr cinfo, int val)
  161207. /* Emit a byte */
  161208. {
  161209. struct jpeg_destination_mgr * dest = cinfo->dest;
  161210. *(dest->next_output_byte)++ = (JOCTET) val;
  161211. if (--dest->free_in_buffer == 0) {
  161212. if (! (*dest->empty_output_buffer) (cinfo))
  161213. ERREXIT(cinfo, JERR_CANT_SUSPEND);
  161214. }
  161215. }
  161216. LOCAL(void)
  161217. emit_marker (j_compress_ptr cinfo, JPEG_MARKER mark)
  161218. /* Emit a marker code */
  161219. {
  161220. emit_byte(cinfo, 0xFF);
  161221. emit_byte(cinfo, (int) mark);
  161222. }
  161223. LOCAL(void)
  161224. emit_2bytes (j_compress_ptr cinfo, int value)
  161225. /* Emit a 2-byte integer; these are always MSB first in JPEG files */
  161226. {
  161227. emit_byte(cinfo, (value >> 8) & 0xFF);
  161228. emit_byte(cinfo, value & 0xFF);
  161229. }
  161230. /*
  161231. * Routines to write specific marker types.
  161232. */
  161233. LOCAL(int)
  161234. emit_dqt (j_compress_ptr cinfo, int index)
  161235. /* Emit a DQT marker */
  161236. /* Returns the precision used (0 = 8bits, 1 = 16bits) for baseline checking */
  161237. {
  161238. JQUANT_TBL * qtbl = cinfo->quant_tbl_ptrs[index];
  161239. int prec;
  161240. int i;
  161241. if (qtbl == NULL)
  161242. ERREXIT1(cinfo, JERR_NO_QUANT_TABLE, index);
  161243. prec = 0;
  161244. for (i = 0; i < DCTSIZE2; i++) {
  161245. if (qtbl->quantval[i] > 255)
  161246. prec = 1;
  161247. }
  161248. if (! qtbl->sent_table) {
  161249. emit_marker(cinfo, M_DQT);
  161250. emit_2bytes(cinfo, prec ? DCTSIZE2*2 + 1 + 2 : DCTSIZE2 + 1 + 2);
  161251. emit_byte(cinfo, index + (prec<<4));
  161252. for (i = 0; i < DCTSIZE2; i++) {
  161253. /* The table entries must be emitted in zigzag order. */
  161254. unsigned int qval = qtbl->quantval[jpeg_natural_order[i]];
  161255. if (prec)
  161256. emit_byte(cinfo, (int) (qval >> 8));
  161257. emit_byte(cinfo, (int) (qval & 0xFF));
  161258. }
  161259. qtbl->sent_table = TRUE;
  161260. }
  161261. return prec;
  161262. }
  161263. LOCAL(void)
  161264. emit_dht (j_compress_ptr cinfo, int index, boolean is_ac)
  161265. /* Emit a DHT marker */
  161266. {
  161267. JHUFF_TBL * htbl;
  161268. int length, i;
  161269. if (is_ac) {
  161270. htbl = cinfo->ac_huff_tbl_ptrs[index];
  161271. index += 0x10; /* output index has AC bit set */
  161272. } else {
  161273. htbl = cinfo->dc_huff_tbl_ptrs[index];
  161274. }
  161275. if (htbl == NULL)
  161276. ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, index);
  161277. if (! htbl->sent_table) {
  161278. emit_marker(cinfo, M_DHT);
  161279. length = 0;
  161280. for (i = 1; i <= 16; i++)
  161281. length += htbl->bits[i];
  161282. emit_2bytes(cinfo, length + 2 + 1 + 16);
  161283. emit_byte(cinfo, index);
  161284. for (i = 1; i <= 16; i++)
  161285. emit_byte(cinfo, htbl->bits[i]);
  161286. for (i = 0; i < length; i++)
  161287. emit_byte(cinfo, htbl->huffval[i]);
  161288. htbl->sent_table = TRUE;
  161289. }
  161290. }
  161291. LOCAL(void)
  161292. emit_dac (j_compress_ptr)
  161293. /* Emit a DAC marker */
  161294. /* Since the useful info is so small, we want to emit all the tables in */
  161295. /* one DAC marker. Therefore this routine does its own scan of the table. */
  161296. {
  161297. #ifdef C_ARITH_CODING_SUPPORTED
  161298. char dc_in_use[NUM_ARITH_TBLS];
  161299. char ac_in_use[NUM_ARITH_TBLS];
  161300. int length, i;
  161301. jpeg_component_info *compptr;
  161302. for (i = 0; i < NUM_ARITH_TBLS; i++)
  161303. dc_in_use[i] = ac_in_use[i] = 0;
  161304. for (i = 0; i < cinfo->comps_in_scan; i++) {
  161305. compptr = cinfo->cur_comp_info[i];
  161306. dc_in_use[compptr->dc_tbl_no] = 1;
  161307. ac_in_use[compptr->ac_tbl_no] = 1;
  161308. }
  161309. length = 0;
  161310. for (i = 0; i < NUM_ARITH_TBLS; i++)
  161311. length += dc_in_use[i] + ac_in_use[i];
  161312. emit_marker(cinfo, M_DAC);
  161313. emit_2bytes(cinfo, length*2 + 2);
  161314. for (i = 0; i < NUM_ARITH_TBLS; i++) {
  161315. if (dc_in_use[i]) {
  161316. emit_byte(cinfo, i);
  161317. emit_byte(cinfo, cinfo->arith_dc_L[i] + (cinfo->arith_dc_U[i]<<4));
  161318. }
  161319. if (ac_in_use[i]) {
  161320. emit_byte(cinfo, i + 0x10);
  161321. emit_byte(cinfo, cinfo->arith_ac_K[i]);
  161322. }
  161323. }
  161324. #endif /* C_ARITH_CODING_SUPPORTED */
  161325. }
  161326. LOCAL(void)
  161327. emit_dri (j_compress_ptr cinfo)
  161328. /* Emit a DRI marker */
  161329. {
  161330. emit_marker(cinfo, M_DRI);
  161331. emit_2bytes(cinfo, 4); /* fixed length */
  161332. emit_2bytes(cinfo, (int) cinfo->restart_interval);
  161333. }
  161334. LOCAL(void)
  161335. emit_sof (j_compress_ptr cinfo, JPEG_MARKER code)
  161336. /* Emit a SOF marker */
  161337. {
  161338. int ci;
  161339. jpeg_component_info *compptr;
  161340. emit_marker(cinfo, code);
  161341. emit_2bytes(cinfo, 3 * cinfo->num_components + 2 + 5 + 1); /* length */
  161342. /* Make sure image isn't bigger than SOF field can handle */
  161343. if ((long) cinfo->image_height > 65535L ||
  161344. (long) cinfo->image_width > 65535L)
  161345. ERREXIT1(cinfo, JERR_IMAGE_TOO_BIG, (unsigned int) 65535);
  161346. emit_byte(cinfo, cinfo->data_precision);
  161347. emit_2bytes(cinfo, (int) cinfo->image_height);
  161348. emit_2bytes(cinfo, (int) cinfo->image_width);
  161349. emit_byte(cinfo, cinfo->num_components);
  161350. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  161351. ci++, compptr++) {
  161352. emit_byte(cinfo, compptr->component_id);
  161353. emit_byte(cinfo, (compptr->h_samp_factor << 4) + compptr->v_samp_factor);
  161354. emit_byte(cinfo, compptr->quant_tbl_no);
  161355. }
  161356. }
  161357. LOCAL(void)
  161358. emit_sos (j_compress_ptr cinfo)
  161359. /* Emit a SOS marker */
  161360. {
  161361. int i, td, ta;
  161362. jpeg_component_info *compptr;
  161363. emit_marker(cinfo, M_SOS);
  161364. emit_2bytes(cinfo, 2 * cinfo->comps_in_scan + 2 + 1 + 3); /* length */
  161365. emit_byte(cinfo, cinfo->comps_in_scan);
  161366. for (i = 0; i < cinfo->comps_in_scan; i++) {
  161367. compptr = cinfo->cur_comp_info[i];
  161368. emit_byte(cinfo, compptr->component_id);
  161369. td = compptr->dc_tbl_no;
  161370. ta = compptr->ac_tbl_no;
  161371. if (cinfo->progressive_mode) {
  161372. /* Progressive mode: only DC or only AC tables are used in one scan;
  161373. * furthermore, Huffman coding of DC refinement uses no table at all.
  161374. * We emit 0 for unused field(s); this is recommended by the P&M text
  161375. * but does not seem to be specified in the standard.
  161376. */
  161377. if (cinfo->Ss == 0) {
  161378. ta = 0; /* DC scan */
  161379. if (cinfo->Ah != 0 && !cinfo->arith_code)
  161380. td = 0; /* no DC table either */
  161381. } else {
  161382. td = 0; /* AC scan */
  161383. }
  161384. }
  161385. emit_byte(cinfo, (td << 4) + ta);
  161386. }
  161387. emit_byte(cinfo, cinfo->Ss);
  161388. emit_byte(cinfo, cinfo->Se);
  161389. emit_byte(cinfo, (cinfo->Ah << 4) + cinfo->Al);
  161390. }
  161391. LOCAL(void)
  161392. emit_jfif_app0 (j_compress_ptr cinfo)
  161393. /* Emit a JFIF-compliant APP0 marker */
  161394. {
  161395. /*
  161396. * Length of APP0 block (2 bytes)
  161397. * Block ID (4 bytes - ASCII "JFIF")
  161398. * Zero byte (1 byte to terminate the ID string)
  161399. * Version Major, Minor (2 bytes - major first)
  161400. * Units (1 byte - 0x00 = none, 0x01 = inch, 0x02 = cm)
  161401. * Xdpu (2 bytes - dots per unit horizontal)
  161402. * Ydpu (2 bytes - dots per unit vertical)
  161403. * Thumbnail X size (1 byte)
  161404. * Thumbnail Y size (1 byte)
  161405. */
  161406. emit_marker(cinfo, M_APP0);
  161407. emit_2bytes(cinfo, 2 + 4 + 1 + 2 + 1 + 2 + 2 + 1 + 1); /* length */
  161408. emit_byte(cinfo, 0x4A); /* Identifier: ASCII "JFIF" */
  161409. emit_byte(cinfo, 0x46);
  161410. emit_byte(cinfo, 0x49);
  161411. emit_byte(cinfo, 0x46);
  161412. emit_byte(cinfo, 0);
  161413. emit_byte(cinfo, cinfo->JFIF_major_version); /* Version fields */
  161414. emit_byte(cinfo, cinfo->JFIF_minor_version);
  161415. emit_byte(cinfo, cinfo->density_unit); /* Pixel size information */
  161416. emit_2bytes(cinfo, (int) cinfo->X_density);
  161417. emit_2bytes(cinfo, (int) cinfo->Y_density);
  161418. emit_byte(cinfo, 0); /* No thumbnail image */
  161419. emit_byte(cinfo, 0);
  161420. }
  161421. LOCAL(void)
  161422. emit_adobe_app14 (j_compress_ptr cinfo)
  161423. /* Emit an Adobe APP14 marker */
  161424. {
  161425. /*
  161426. * Length of APP14 block (2 bytes)
  161427. * Block ID (5 bytes - ASCII "Adobe")
  161428. * Version Number (2 bytes - currently 100)
  161429. * Flags0 (2 bytes - currently 0)
  161430. * Flags1 (2 bytes - currently 0)
  161431. * Color transform (1 byte)
  161432. *
  161433. * Although Adobe TN 5116 mentions Version = 101, all the Adobe files
  161434. * now in circulation seem to use Version = 100, so that's what we write.
  161435. *
  161436. * We write the color transform byte as 1 if the JPEG color space is
  161437. * YCbCr, 2 if it's YCCK, 0 otherwise. Adobe's definition has to do with
  161438. * whether the encoder performed a transformation, which is pretty useless.
  161439. */
  161440. emit_marker(cinfo, M_APP14);
  161441. emit_2bytes(cinfo, 2 + 5 + 2 + 2 + 2 + 1); /* length */
  161442. emit_byte(cinfo, 0x41); /* Identifier: ASCII "Adobe" */
  161443. emit_byte(cinfo, 0x64);
  161444. emit_byte(cinfo, 0x6F);
  161445. emit_byte(cinfo, 0x62);
  161446. emit_byte(cinfo, 0x65);
  161447. emit_2bytes(cinfo, 100); /* Version */
  161448. emit_2bytes(cinfo, 0); /* Flags0 */
  161449. emit_2bytes(cinfo, 0); /* Flags1 */
  161450. switch (cinfo->jpeg_color_space) {
  161451. case JCS_YCbCr:
  161452. emit_byte(cinfo, 1); /* Color transform = 1 */
  161453. break;
  161454. case JCS_YCCK:
  161455. emit_byte(cinfo, 2); /* Color transform = 2 */
  161456. break;
  161457. default:
  161458. emit_byte(cinfo, 0); /* Color transform = 0 */
  161459. break;
  161460. }
  161461. }
  161462. /*
  161463. * These routines allow writing an arbitrary marker with parameters.
  161464. * The only intended use is to emit COM or APPn markers after calling
  161465. * write_file_header and before calling write_frame_header.
  161466. * Other uses are not guaranteed to produce desirable results.
  161467. * Counting the parameter bytes properly is the caller's responsibility.
  161468. */
  161469. METHODDEF(void)
  161470. write_marker_header (j_compress_ptr cinfo, int marker, unsigned int datalen)
  161471. /* Emit an arbitrary marker header */
  161472. {
  161473. if (datalen > (unsigned int) 65533) /* safety check */
  161474. ERREXIT(cinfo, JERR_BAD_LENGTH);
  161475. emit_marker(cinfo, (JPEG_MARKER) marker);
  161476. emit_2bytes(cinfo, (int) (datalen + 2)); /* total length */
  161477. }
  161478. METHODDEF(void)
  161479. write_marker_byte (j_compress_ptr cinfo, int val)
  161480. /* Emit one byte of marker parameters following write_marker_header */
  161481. {
  161482. emit_byte(cinfo, val);
  161483. }
  161484. /*
  161485. * Write datastream header.
  161486. * This consists of an SOI and optional APPn markers.
  161487. * We recommend use of the JFIF marker, but not the Adobe marker,
  161488. * when using YCbCr or grayscale data. The JFIF marker should NOT
  161489. * be used for any other JPEG colorspace. The Adobe marker is helpful
  161490. * to distinguish RGB, CMYK, and YCCK colorspaces.
  161491. * Note that an application can write additional header markers after
  161492. * jpeg_start_compress returns.
  161493. */
  161494. METHODDEF(void)
  161495. write_file_header (j_compress_ptr cinfo)
  161496. {
  161497. my_marker_ptr marker = (my_marker_ptr) cinfo->marker;
  161498. emit_marker(cinfo, M_SOI); /* first the SOI */
  161499. /* SOI is defined to reset restart interval to 0 */
  161500. marker->last_restart_interval = 0;
  161501. if (cinfo->write_JFIF_header) /* next an optional JFIF APP0 */
  161502. emit_jfif_app0(cinfo);
  161503. if (cinfo->write_Adobe_marker) /* next an optional Adobe APP14 */
  161504. emit_adobe_app14(cinfo);
  161505. }
  161506. /*
  161507. * Write frame header.
  161508. * This consists of DQT and SOFn markers.
  161509. * Note that we do not emit the SOF until we have emitted the DQT(s).
  161510. * This avoids compatibility problems with incorrect implementations that
  161511. * try to error-check the quant table numbers as soon as they see the SOF.
  161512. */
  161513. METHODDEF(void)
  161514. write_frame_header (j_compress_ptr cinfo)
  161515. {
  161516. int ci, prec;
  161517. boolean is_baseline;
  161518. jpeg_component_info *compptr;
  161519. /* Emit DQT for each quantization table.
  161520. * Note that emit_dqt() suppresses any duplicate tables.
  161521. */
  161522. prec = 0;
  161523. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  161524. ci++, compptr++) {
  161525. prec += emit_dqt(cinfo, compptr->quant_tbl_no);
  161526. }
  161527. /* now prec is nonzero iff there are any 16-bit quant tables. */
  161528. /* Check for a non-baseline specification.
  161529. * Note we assume that Huffman table numbers won't be changed later.
  161530. */
  161531. if (cinfo->arith_code || cinfo->progressive_mode ||
  161532. cinfo->data_precision != 8) {
  161533. is_baseline = FALSE;
  161534. } else {
  161535. is_baseline = TRUE;
  161536. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  161537. ci++, compptr++) {
  161538. if (compptr->dc_tbl_no > 1 || compptr->ac_tbl_no > 1)
  161539. is_baseline = FALSE;
  161540. }
  161541. if (prec && is_baseline) {
  161542. is_baseline = FALSE;
  161543. /* If it's baseline except for quantizer size, warn the user */
  161544. TRACEMS(cinfo, 0, JTRC_16BIT_TABLES);
  161545. }
  161546. }
  161547. /* Emit the proper SOF marker */
  161548. if (cinfo->arith_code) {
  161549. emit_sof(cinfo, M_SOF9); /* SOF code for arithmetic coding */
  161550. } else {
  161551. if (cinfo->progressive_mode)
  161552. emit_sof(cinfo, M_SOF2); /* SOF code for progressive Huffman */
  161553. else if (is_baseline)
  161554. emit_sof(cinfo, M_SOF0); /* SOF code for baseline implementation */
  161555. else
  161556. emit_sof(cinfo, M_SOF1); /* SOF code for non-baseline Huffman file */
  161557. }
  161558. }
  161559. /*
  161560. * Write scan header.
  161561. * This consists of DHT or DAC markers, optional DRI, and SOS.
  161562. * Compressed data will be written following the SOS.
  161563. */
  161564. METHODDEF(void)
  161565. write_scan_header (j_compress_ptr cinfo)
  161566. {
  161567. my_marker_ptr marker = (my_marker_ptr) cinfo->marker;
  161568. int i;
  161569. jpeg_component_info *compptr;
  161570. if (cinfo->arith_code) {
  161571. /* Emit arith conditioning info. We may have some duplication
  161572. * if the file has multiple scans, but it's so small it's hardly
  161573. * worth worrying about.
  161574. */
  161575. emit_dac(cinfo);
  161576. } else {
  161577. /* Emit Huffman tables.
  161578. * Note that emit_dht() suppresses any duplicate tables.
  161579. */
  161580. for (i = 0; i < cinfo->comps_in_scan; i++) {
  161581. compptr = cinfo->cur_comp_info[i];
  161582. if (cinfo->progressive_mode) {
  161583. /* Progressive mode: only DC or only AC tables are used in one scan */
  161584. if (cinfo->Ss == 0) {
  161585. if (cinfo->Ah == 0) /* DC needs no table for refinement scan */
  161586. emit_dht(cinfo, compptr->dc_tbl_no, FALSE);
  161587. } else {
  161588. emit_dht(cinfo, compptr->ac_tbl_no, TRUE);
  161589. }
  161590. } else {
  161591. /* Sequential mode: need both DC and AC tables */
  161592. emit_dht(cinfo, compptr->dc_tbl_no, FALSE);
  161593. emit_dht(cinfo, compptr->ac_tbl_no, TRUE);
  161594. }
  161595. }
  161596. }
  161597. /* Emit DRI if required --- note that DRI value could change for each scan.
  161598. * We avoid wasting space with unnecessary DRIs, however.
  161599. */
  161600. if (cinfo->restart_interval != marker->last_restart_interval) {
  161601. emit_dri(cinfo);
  161602. marker->last_restart_interval = cinfo->restart_interval;
  161603. }
  161604. emit_sos(cinfo);
  161605. }
  161606. /*
  161607. * Write datastream trailer.
  161608. */
  161609. METHODDEF(void)
  161610. write_file_trailer (j_compress_ptr cinfo)
  161611. {
  161612. emit_marker(cinfo, M_EOI);
  161613. }
  161614. /*
  161615. * Write an abbreviated table-specification datastream.
  161616. * This consists of SOI, DQT and DHT tables, and EOI.
  161617. * Any table that is defined and not marked sent_table = TRUE will be
  161618. * emitted. Note that all tables will be marked sent_table = TRUE at exit.
  161619. */
  161620. METHODDEF(void)
  161621. write_tables_only (j_compress_ptr cinfo)
  161622. {
  161623. int i;
  161624. emit_marker(cinfo, M_SOI);
  161625. for (i = 0; i < NUM_QUANT_TBLS; i++) {
  161626. if (cinfo->quant_tbl_ptrs[i] != NULL)
  161627. (void) emit_dqt(cinfo, i);
  161628. }
  161629. if (! cinfo->arith_code) {
  161630. for (i = 0; i < NUM_HUFF_TBLS; i++) {
  161631. if (cinfo->dc_huff_tbl_ptrs[i] != NULL)
  161632. emit_dht(cinfo, i, FALSE);
  161633. if (cinfo->ac_huff_tbl_ptrs[i] != NULL)
  161634. emit_dht(cinfo, i, TRUE);
  161635. }
  161636. }
  161637. emit_marker(cinfo, M_EOI);
  161638. }
  161639. /*
  161640. * Initialize the marker writer module.
  161641. */
  161642. GLOBAL(void)
  161643. jinit_marker_writer (j_compress_ptr cinfo)
  161644. {
  161645. my_marker_ptr marker;
  161646. /* Create the subobject */
  161647. marker = (my_marker_ptr)
  161648. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  161649. SIZEOF(my_marker_writer));
  161650. cinfo->marker = (struct jpeg_marker_writer *) marker;
  161651. /* Initialize method pointers */
  161652. marker->pub.write_file_header = write_file_header;
  161653. marker->pub.write_frame_header = write_frame_header;
  161654. marker->pub.write_scan_header = write_scan_header;
  161655. marker->pub.write_file_trailer = write_file_trailer;
  161656. marker->pub.write_tables_only = write_tables_only;
  161657. marker->pub.write_marker_header = write_marker_header;
  161658. marker->pub.write_marker_byte = write_marker_byte;
  161659. /* Initialize private state */
  161660. marker->last_restart_interval = 0;
  161661. }
  161662. /*** End of inlined file: jcmarker.c ***/
  161663. /*** Start of inlined file: jcmaster.c ***/
  161664. #define JPEG_INTERNALS
  161665. /* Private state */
  161666. typedef enum {
  161667. main_pass, /* input data, also do first output step */
  161668. huff_opt_pass, /* Huffman code optimization pass */
  161669. output_pass /* data output pass */
  161670. } c_pass_type;
  161671. typedef struct {
  161672. struct jpeg_comp_master pub; /* public fields */
  161673. c_pass_type pass_type; /* the type of the current pass */
  161674. int pass_number; /* # of passes completed */
  161675. int total_passes; /* total # of passes needed */
  161676. int scan_number; /* current index in scan_info[] */
  161677. } my_comp_master;
  161678. typedef my_comp_master * my_master_ptr;
  161679. /*
  161680. * Support routines that do various essential calculations.
  161681. */
  161682. LOCAL(void)
  161683. initial_setup (j_compress_ptr cinfo)
  161684. /* Do computations that are needed before master selection phase */
  161685. {
  161686. int ci;
  161687. jpeg_component_info *compptr;
  161688. long samplesperrow;
  161689. JDIMENSION jd_samplesperrow;
  161690. /* Sanity check on image dimensions */
  161691. if (cinfo->image_height <= 0 || cinfo->image_width <= 0
  161692. || cinfo->num_components <= 0 || cinfo->input_components <= 0)
  161693. ERREXIT(cinfo, JERR_EMPTY_IMAGE);
  161694. /* Make sure image isn't bigger than I can handle */
  161695. if ((long) cinfo->image_height > (long) JPEG_MAX_DIMENSION ||
  161696. (long) cinfo->image_width > (long) JPEG_MAX_DIMENSION)
  161697. ERREXIT1(cinfo, JERR_IMAGE_TOO_BIG, (unsigned int) JPEG_MAX_DIMENSION);
  161698. /* Width of an input scanline must be representable as JDIMENSION. */
  161699. samplesperrow = (long) cinfo->image_width * (long) cinfo->input_components;
  161700. jd_samplesperrow = (JDIMENSION) samplesperrow;
  161701. if ((long) jd_samplesperrow != samplesperrow)
  161702. ERREXIT(cinfo, JERR_WIDTH_OVERFLOW);
  161703. /* For now, precision must match compiled-in value... */
  161704. if (cinfo->data_precision != BITS_IN_JSAMPLE)
  161705. ERREXIT1(cinfo, JERR_BAD_PRECISION, cinfo->data_precision);
  161706. /* Check that number of components won't exceed internal array sizes */
  161707. if (cinfo->num_components > MAX_COMPONENTS)
  161708. ERREXIT2(cinfo, JERR_COMPONENT_COUNT, cinfo->num_components,
  161709. MAX_COMPONENTS);
  161710. /* Compute maximum sampling factors; check factor validity */
  161711. cinfo->max_h_samp_factor = 1;
  161712. cinfo->max_v_samp_factor = 1;
  161713. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  161714. ci++, compptr++) {
  161715. if (compptr->h_samp_factor<=0 || compptr->h_samp_factor>MAX_SAMP_FACTOR ||
  161716. compptr->v_samp_factor<=0 || compptr->v_samp_factor>MAX_SAMP_FACTOR)
  161717. ERREXIT(cinfo, JERR_BAD_SAMPLING);
  161718. cinfo->max_h_samp_factor = MAX(cinfo->max_h_samp_factor,
  161719. compptr->h_samp_factor);
  161720. cinfo->max_v_samp_factor = MAX(cinfo->max_v_samp_factor,
  161721. compptr->v_samp_factor);
  161722. }
  161723. /* Compute dimensions of components */
  161724. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  161725. ci++, compptr++) {
  161726. /* Fill in the correct component_index value; don't rely on application */
  161727. compptr->component_index = ci;
  161728. /* For compression, we never do DCT scaling. */
  161729. compptr->DCT_scaled_size = DCTSIZE;
  161730. /* Size in DCT blocks */
  161731. compptr->width_in_blocks = (JDIMENSION)
  161732. jdiv_round_up((long) cinfo->image_width * (long) compptr->h_samp_factor,
  161733. (long) (cinfo->max_h_samp_factor * DCTSIZE));
  161734. compptr->height_in_blocks = (JDIMENSION)
  161735. jdiv_round_up((long) cinfo->image_height * (long) compptr->v_samp_factor,
  161736. (long) (cinfo->max_v_samp_factor * DCTSIZE));
  161737. /* Size in samples */
  161738. compptr->downsampled_width = (JDIMENSION)
  161739. jdiv_round_up((long) cinfo->image_width * (long) compptr->h_samp_factor,
  161740. (long) cinfo->max_h_samp_factor);
  161741. compptr->downsampled_height = (JDIMENSION)
  161742. jdiv_round_up((long) cinfo->image_height * (long) compptr->v_samp_factor,
  161743. (long) cinfo->max_v_samp_factor);
  161744. /* Mark component needed (this flag isn't actually used for compression) */
  161745. compptr->component_needed = TRUE;
  161746. }
  161747. /* Compute number of fully interleaved MCU rows (number of times that
  161748. * main controller will call coefficient controller).
  161749. */
  161750. cinfo->total_iMCU_rows = (JDIMENSION)
  161751. jdiv_round_up((long) cinfo->image_height,
  161752. (long) (cinfo->max_v_samp_factor*DCTSIZE));
  161753. }
  161754. #ifdef C_MULTISCAN_FILES_SUPPORTED
  161755. LOCAL(void)
  161756. validate_script (j_compress_ptr cinfo)
  161757. /* Verify that the scan script in cinfo->scan_info[] is valid; also
  161758. * determine whether it uses progressive JPEG, and set cinfo->progressive_mode.
  161759. */
  161760. {
  161761. const jpeg_scan_info * scanptr;
  161762. int scanno, ncomps, ci, coefi, thisi;
  161763. int Ss, Se, Ah, Al;
  161764. boolean component_sent[MAX_COMPONENTS];
  161765. #ifdef C_PROGRESSIVE_SUPPORTED
  161766. int * last_bitpos_ptr;
  161767. int last_bitpos[MAX_COMPONENTS][DCTSIZE2];
  161768. /* -1 until that coefficient has been seen; then last Al for it */
  161769. #endif
  161770. if (cinfo->num_scans <= 0)
  161771. ERREXIT1(cinfo, JERR_BAD_SCAN_SCRIPT, 0);
  161772. /* For sequential JPEG, all scans must have Ss=0, Se=DCTSIZE2-1;
  161773. * for progressive JPEG, no scan can have this.
  161774. */
  161775. scanptr = cinfo->scan_info;
  161776. if (scanptr->Ss != 0 || scanptr->Se != DCTSIZE2-1) {
  161777. #ifdef C_PROGRESSIVE_SUPPORTED
  161778. cinfo->progressive_mode = TRUE;
  161779. last_bitpos_ptr = & last_bitpos[0][0];
  161780. for (ci = 0; ci < cinfo->num_components; ci++)
  161781. for (coefi = 0; coefi < DCTSIZE2; coefi++)
  161782. *last_bitpos_ptr++ = -1;
  161783. #else
  161784. ERREXIT(cinfo, JERR_NOT_COMPILED);
  161785. #endif
  161786. } else {
  161787. cinfo->progressive_mode = FALSE;
  161788. for (ci = 0; ci < cinfo->num_components; ci++)
  161789. component_sent[ci] = FALSE;
  161790. }
  161791. for (scanno = 1; scanno <= cinfo->num_scans; scanptr++, scanno++) {
  161792. /* Validate component indexes */
  161793. ncomps = scanptr->comps_in_scan;
  161794. if (ncomps <= 0 || ncomps > MAX_COMPS_IN_SCAN)
  161795. ERREXIT2(cinfo, JERR_COMPONENT_COUNT, ncomps, MAX_COMPS_IN_SCAN);
  161796. for (ci = 0; ci < ncomps; ci++) {
  161797. thisi = scanptr->component_index[ci];
  161798. if (thisi < 0 || thisi >= cinfo->num_components)
  161799. ERREXIT1(cinfo, JERR_BAD_SCAN_SCRIPT, scanno);
  161800. /* Components must appear in SOF order within each scan */
  161801. if (ci > 0 && thisi <= scanptr->component_index[ci-1])
  161802. ERREXIT1(cinfo, JERR_BAD_SCAN_SCRIPT, scanno);
  161803. }
  161804. /* Validate progression parameters */
  161805. Ss = scanptr->Ss;
  161806. Se = scanptr->Se;
  161807. Ah = scanptr->Ah;
  161808. Al = scanptr->Al;
  161809. if (cinfo->progressive_mode) {
  161810. #ifdef C_PROGRESSIVE_SUPPORTED
  161811. /* The JPEG spec simply gives the ranges 0..13 for Ah and Al, but that
  161812. * seems wrong: the upper bound ought to depend on data precision.
  161813. * Perhaps they really meant 0..N+1 for N-bit precision.
  161814. * Here we allow 0..10 for 8-bit data; Al larger than 10 results in
  161815. * out-of-range reconstructed DC values during the first DC scan,
  161816. * which might cause problems for some decoders.
  161817. */
  161818. #if BITS_IN_JSAMPLE == 8
  161819. #define MAX_AH_AL 10
  161820. #else
  161821. #define MAX_AH_AL 13
  161822. #endif
  161823. if (Ss < 0 || Ss >= DCTSIZE2 || Se < Ss || Se >= DCTSIZE2 ||
  161824. Ah < 0 || Ah > MAX_AH_AL || Al < 0 || Al > MAX_AH_AL)
  161825. ERREXIT1(cinfo, JERR_BAD_PROG_SCRIPT, scanno);
  161826. if (Ss == 0) {
  161827. if (Se != 0) /* DC and AC together not OK */
  161828. ERREXIT1(cinfo, JERR_BAD_PROG_SCRIPT, scanno);
  161829. } else {
  161830. if (ncomps != 1) /* AC scans must be for only one component */
  161831. ERREXIT1(cinfo, JERR_BAD_PROG_SCRIPT, scanno);
  161832. }
  161833. for (ci = 0; ci < ncomps; ci++) {
  161834. last_bitpos_ptr = & last_bitpos[scanptr->component_index[ci]][0];
  161835. if (Ss != 0 && last_bitpos_ptr[0] < 0) /* AC without prior DC scan */
  161836. ERREXIT1(cinfo, JERR_BAD_PROG_SCRIPT, scanno);
  161837. for (coefi = Ss; coefi <= Se; coefi++) {
  161838. if (last_bitpos_ptr[coefi] < 0) {
  161839. /* first scan of this coefficient */
  161840. if (Ah != 0)
  161841. ERREXIT1(cinfo, JERR_BAD_PROG_SCRIPT, scanno);
  161842. } else {
  161843. /* not first scan */
  161844. if (Ah != last_bitpos_ptr[coefi] || Al != Ah-1)
  161845. ERREXIT1(cinfo, JERR_BAD_PROG_SCRIPT, scanno);
  161846. }
  161847. last_bitpos_ptr[coefi] = Al;
  161848. }
  161849. }
  161850. #endif
  161851. } else {
  161852. /* For sequential JPEG, all progression parameters must be these: */
  161853. if (Ss != 0 || Se != DCTSIZE2-1 || Ah != 0 || Al != 0)
  161854. ERREXIT1(cinfo, JERR_BAD_PROG_SCRIPT, scanno);
  161855. /* Make sure components are not sent twice */
  161856. for (ci = 0; ci < ncomps; ci++) {
  161857. thisi = scanptr->component_index[ci];
  161858. if (component_sent[thisi])
  161859. ERREXIT1(cinfo, JERR_BAD_SCAN_SCRIPT, scanno);
  161860. component_sent[thisi] = TRUE;
  161861. }
  161862. }
  161863. }
  161864. /* Now verify that everything got sent. */
  161865. if (cinfo->progressive_mode) {
  161866. #ifdef C_PROGRESSIVE_SUPPORTED
  161867. /* For progressive mode, we only check that at least some DC data
  161868. * got sent for each component; the spec does not require that all bits
  161869. * of all coefficients be transmitted. Would it be wiser to enforce
  161870. * transmission of all coefficient bits??
  161871. */
  161872. for (ci = 0; ci < cinfo->num_components; ci++) {
  161873. if (last_bitpos[ci][0] < 0)
  161874. ERREXIT(cinfo, JERR_MISSING_DATA);
  161875. }
  161876. #endif
  161877. } else {
  161878. for (ci = 0; ci < cinfo->num_components; ci++) {
  161879. if (! component_sent[ci])
  161880. ERREXIT(cinfo, JERR_MISSING_DATA);
  161881. }
  161882. }
  161883. }
  161884. #endif /* C_MULTISCAN_FILES_SUPPORTED */
  161885. LOCAL(void)
  161886. select_scan_parameters (j_compress_ptr cinfo)
  161887. /* Set up the scan parameters for the current scan */
  161888. {
  161889. int ci;
  161890. #ifdef C_MULTISCAN_FILES_SUPPORTED
  161891. if (cinfo->scan_info != NULL) {
  161892. /* Prepare for current scan --- the script is already validated */
  161893. my_master_ptr master = (my_master_ptr) cinfo->master;
  161894. const jpeg_scan_info * scanptr = cinfo->scan_info + master->scan_number;
  161895. cinfo->comps_in_scan = scanptr->comps_in_scan;
  161896. for (ci = 0; ci < scanptr->comps_in_scan; ci++) {
  161897. cinfo->cur_comp_info[ci] =
  161898. &cinfo->comp_info[scanptr->component_index[ci]];
  161899. }
  161900. cinfo->Ss = scanptr->Ss;
  161901. cinfo->Se = scanptr->Se;
  161902. cinfo->Ah = scanptr->Ah;
  161903. cinfo->Al = scanptr->Al;
  161904. }
  161905. else
  161906. #endif
  161907. {
  161908. /* Prepare for single sequential-JPEG scan containing all components */
  161909. if (cinfo->num_components > MAX_COMPS_IN_SCAN)
  161910. ERREXIT2(cinfo, JERR_COMPONENT_COUNT, cinfo->num_components,
  161911. MAX_COMPS_IN_SCAN);
  161912. cinfo->comps_in_scan = cinfo->num_components;
  161913. for (ci = 0; ci < cinfo->num_components; ci++) {
  161914. cinfo->cur_comp_info[ci] = &cinfo->comp_info[ci];
  161915. }
  161916. cinfo->Ss = 0;
  161917. cinfo->Se = DCTSIZE2-1;
  161918. cinfo->Ah = 0;
  161919. cinfo->Al = 0;
  161920. }
  161921. }
  161922. LOCAL(void)
  161923. per_scan_setup (j_compress_ptr cinfo)
  161924. /* Do computations that are needed before processing a JPEG scan */
  161925. /* cinfo->comps_in_scan and cinfo->cur_comp_info[] are already set */
  161926. {
  161927. int ci, mcublks, tmp;
  161928. jpeg_component_info *compptr;
  161929. if (cinfo->comps_in_scan == 1) {
  161930. /* Noninterleaved (single-component) scan */
  161931. compptr = cinfo->cur_comp_info[0];
  161932. /* Overall image size in MCUs */
  161933. cinfo->MCUs_per_row = compptr->width_in_blocks;
  161934. cinfo->MCU_rows_in_scan = compptr->height_in_blocks;
  161935. /* For noninterleaved scan, always one block per MCU */
  161936. compptr->MCU_width = 1;
  161937. compptr->MCU_height = 1;
  161938. compptr->MCU_blocks = 1;
  161939. compptr->MCU_sample_width = DCTSIZE;
  161940. compptr->last_col_width = 1;
  161941. /* For noninterleaved scans, it is convenient to define last_row_height
  161942. * as the number of block rows present in the last iMCU row.
  161943. */
  161944. tmp = (int) (compptr->height_in_blocks % compptr->v_samp_factor);
  161945. if (tmp == 0) tmp = compptr->v_samp_factor;
  161946. compptr->last_row_height = tmp;
  161947. /* Prepare array describing MCU composition */
  161948. cinfo->blocks_in_MCU = 1;
  161949. cinfo->MCU_membership[0] = 0;
  161950. } else {
  161951. /* Interleaved (multi-component) scan */
  161952. if (cinfo->comps_in_scan <= 0 || cinfo->comps_in_scan > MAX_COMPS_IN_SCAN)
  161953. ERREXIT2(cinfo, JERR_COMPONENT_COUNT, cinfo->comps_in_scan,
  161954. MAX_COMPS_IN_SCAN);
  161955. /* Overall image size in MCUs */
  161956. cinfo->MCUs_per_row = (JDIMENSION)
  161957. jdiv_round_up((long) cinfo->image_width,
  161958. (long) (cinfo->max_h_samp_factor*DCTSIZE));
  161959. cinfo->MCU_rows_in_scan = (JDIMENSION)
  161960. jdiv_round_up((long) cinfo->image_height,
  161961. (long) (cinfo->max_v_samp_factor*DCTSIZE));
  161962. cinfo->blocks_in_MCU = 0;
  161963. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  161964. compptr = cinfo->cur_comp_info[ci];
  161965. /* Sampling factors give # of blocks of component in each MCU */
  161966. compptr->MCU_width = compptr->h_samp_factor;
  161967. compptr->MCU_height = compptr->v_samp_factor;
  161968. compptr->MCU_blocks = compptr->MCU_width * compptr->MCU_height;
  161969. compptr->MCU_sample_width = compptr->MCU_width * DCTSIZE;
  161970. /* Figure number of non-dummy blocks in last MCU column & row */
  161971. tmp = (int) (compptr->width_in_blocks % compptr->MCU_width);
  161972. if (tmp == 0) tmp = compptr->MCU_width;
  161973. compptr->last_col_width = tmp;
  161974. tmp = (int) (compptr->height_in_blocks % compptr->MCU_height);
  161975. if (tmp == 0) tmp = compptr->MCU_height;
  161976. compptr->last_row_height = tmp;
  161977. /* Prepare array describing MCU composition */
  161978. mcublks = compptr->MCU_blocks;
  161979. if (cinfo->blocks_in_MCU + mcublks > C_MAX_BLOCKS_IN_MCU)
  161980. ERREXIT(cinfo, JERR_BAD_MCU_SIZE);
  161981. while (mcublks-- > 0) {
  161982. cinfo->MCU_membership[cinfo->blocks_in_MCU++] = ci;
  161983. }
  161984. }
  161985. }
  161986. /* Convert restart specified in rows to actual MCU count. */
  161987. /* Note that count must fit in 16 bits, so we provide limiting. */
  161988. if (cinfo->restart_in_rows > 0) {
  161989. long nominal = (long) cinfo->restart_in_rows * (long) cinfo->MCUs_per_row;
  161990. cinfo->restart_interval = (unsigned int) MIN(nominal, 65535L);
  161991. }
  161992. }
  161993. /*
  161994. * Per-pass setup.
  161995. * This is called at the beginning of each pass. We determine which modules
  161996. * will be active during this pass and give them appropriate start_pass calls.
  161997. * We also set is_last_pass to indicate whether any more passes will be
  161998. * required.
  161999. */
  162000. METHODDEF(void)
  162001. prepare_for_pass (j_compress_ptr cinfo)
  162002. {
  162003. my_master_ptr master = (my_master_ptr) cinfo->master;
  162004. switch (master->pass_type) {
  162005. case main_pass:
  162006. /* Initial pass: will collect input data, and do either Huffman
  162007. * optimization or data output for the first scan.
  162008. */
  162009. select_scan_parameters(cinfo);
  162010. per_scan_setup(cinfo);
  162011. if (! cinfo->raw_data_in) {
  162012. (*cinfo->cconvert->start_pass) (cinfo);
  162013. (*cinfo->downsample->start_pass) (cinfo);
  162014. (*cinfo->prep->start_pass) (cinfo, JBUF_PASS_THRU);
  162015. }
  162016. (*cinfo->fdct->start_pass) (cinfo);
  162017. (*cinfo->entropy->start_pass) (cinfo, cinfo->optimize_coding);
  162018. (*cinfo->coef->start_pass) (cinfo,
  162019. (master->total_passes > 1 ?
  162020. JBUF_SAVE_AND_PASS : JBUF_PASS_THRU));
  162021. (*cinfo->main->start_pass) (cinfo, JBUF_PASS_THRU);
  162022. if (cinfo->optimize_coding) {
  162023. /* No immediate data output; postpone writing frame/scan headers */
  162024. master->pub.call_pass_startup = FALSE;
  162025. } else {
  162026. /* Will write frame/scan headers at first jpeg_write_scanlines call */
  162027. master->pub.call_pass_startup = TRUE;
  162028. }
  162029. break;
  162030. #ifdef ENTROPY_OPT_SUPPORTED
  162031. case huff_opt_pass:
  162032. /* Do Huffman optimization for a scan after the first one. */
  162033. select_scan_parameters(cinfo);
  162034. per_scan_setup(cinfo);
  162035. if (cinfo->Ss != 0 || cinfo->Ah == 0 || cinfo->arith_code) {
  162036. (*cinfo->entropy->start_pass) (cinfo, TRUE);
  162037. (*cinfo->coef->start_pass) (cinfo, JBUF_CRANK_DEST);
  162038. master->pub.call_pass_startup = FALSE;
  162039. break;
  162040. }
  162041. /* Special case: Huffman DC refinement scans need no Huffman table
  162042. * and therefore we can skip the optimization pass for them.
  162043. */
  162044. master->pass_type = output_pass;
  162045. master->pass_number++;
  162046. /*FALLTHROUGH*/
  162047. #endif
  162048. case output_pass:
  162049. /* Do a data-output pass. */
  162050. /* We need not repeat per-scan setup if prior optimization pass did it. */
  162051. if (! cinfo->optimize_coding) {
  162052. select_scan_parameters(cinfo);
  162053. per_scan_setup(cinfo);
  162054. }
  162055. (*cinfo->entropy->start_pass) (cinfo, FALSE);
  162056. (*cinfo->coef->start_pass) (cinfo, JBUF_CRANK_DEST);
  162057. /* We emit frame/scan headers now */
  162058. if (master->scan_number == 0)
  162059. (*cinfo->marker->write_frame_header) (cinfo);
  162060. (*cinfo->marker->write_scan_header) (cinfo);
  162061. master->pub.call_pass_startup = FALSE;
  162062. break;
  162063. default:
  162064. ERREXIT(cinfo, JERR_NOT_COMPILED);
  162065. }
  162066. master->pub.is_last_pass = (master->pass_number == master->total_passes-1);
  162067. /* Set up progress monitor's pass info if present */
  162068. if (cinfo->progress != NULL) {
  162069. cinfo->progress->completed_passes = master->pass_number;
  162070. cinfo->progress->total_passes = master->total_passes;
  162071. }
  162072. }
  162073. /*
  162074. * Special start-of-pass hook.
  162075. * This is called by jpeg_write_scanlines if call_pass_startup is TRUE.
  162076. * In single-pass processing, we need this hook because we don't want to
  162077. * write frame/scan headers during jpeg_start_compress; we want to let the
  162078. * application write COM markers etc. between jpeg_start_compress and the
  162079. * jpeg_write_scanlines loop.
  162080. * In multi-pass processing, this routine is not used.
  162081. */
  162082. METHODDEF(void)
  162083. pass_startup (j_compress_ptr cinfo)
  162084. {
  162085. cinfo->master->call_pass_startup = FALSE; /* reset flag so call only once */
  162086. (*cinfo->marker->write_frame_header) (cinfo);
  162087. (*cinfo->marker->write_scan_header) (cinfo);
  162088. }
  162089. /*
  162090. * Finish up at end of pass.
  162091. */
  162092. METHODDEF(void)
  162093. finish_pass_master (j_compress_ptr cinfo)
  162094. {
  162095. my_master_ptr master = (my_master_ptr) cinfo->master;
  162096. /* The entropy coder always needs an end-of-pass call,
  162097. * either to analyze statistics or to flush its output buffer.
  162098. */
  162099. (*cinfo->entropy->finish_pass) (cinfo);
  162100. /* Update state for next pass */
  162101. switch (master->pass_type) {
  162102. case main_pass:
  162103. /* next pass is either output of scan 0 (after optimization)
  162104. * or output of scan 1 (if no optimization).
  162105. */
  162106. master->pass_type = output_pass;
  162107. if (! cinfo->optimize_coding)
  162108. master->scan_number++;
  162109. break;
  162110. case huff_opt_pass:
  162111. /* next pass is always output of current scan */
  162112. master->pass_type = output_pass;
  162113. break;
  162114. case output_pass:
  162115. /* next pass is either optimization or output of next scan */
  162116. if (cinfo->optimize_coding)
  162117. master->pass_type = huff_opt_pass;
  162118. master->scan_number++;
  162119. break;
  162120. }
  162121. master->pass_number++;
  162122. }
  162123. /*
  162124. * Initialize master compression control.
  162125. */
  162126. GLOBAL(void)
  162127. jinit_c_master_control (j_compress_ptr cinfo, boolean transcode_only)
  162128. {
  162129. my_master_ptr master;
  162130. master = (my_master_ptr)
  162131. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  162132. SIZEOF(my_comp_master));
  162133. cinfo->master = (struct jpeg_comp_master *) master;
  162134. master->pub.prepare_for_pass = prepare_for_pass;
  162135. master->pub.pass_startup = pass_startup;
  162136. master->pub.finish_pass = finish_pass_master;
  162137. master->pub.is_last_pass = FALSE;
  162138. /* Validate parameters, determine derived values */
  162139. initial_setup(cinfo);
  162140. if (cinfo->scan_info != NULL) {
  162141. #ifdef C_MULTISCAN_FILES_SUPPORTED
  162142. validate_script(cinfo);
  162143. #else
  162144. ERREXIT(cinfo, JERR_NOT_COMPILED);
  162145. #endif
  162146. } else {
  162147. cinfo->progressive_mode = FALSE;
  162148. cinfo->num_scans = 1;
  162149. }
  162150. if (cinfo->progressive_mode) /* TEMPORARY HACK ??? */
  162151. cinfo->optimize_coding = TRUE; /* assume default tables no good for progressive mode */
  162152. /* Initialize my private state */
  162153. if (transcode_only) {
  162154. /* no main pass in transcoding */
  162155. if (cinfo->optimize_coding)
  162156. master->pass_type = huff_opt_pass;
  162157. else
  162158. master->pass_type = output_pass;
  162159. } else {
  162160. /* for normal compression, first pass is always this type: */
  162161. master->pass_type = main_pass;
  162162. }
  162163. master->scan_number = 0;
  162164. master->pass_number = 0;
  162165. if (cinfo->optimize_coding)
  162166. master->total_passes = cinfo->num_scans * 2;
  162167. else
  162168. master->total_passes = cinfo->num_scans;
  162169. }
  162170. /*** End of inlined file: jcmaster.c ***/
  162171. /*** Start of inlined file: jcomapi.c ***/
  162172. #define JPEG_INTERNALS
  162173. /*
  162174. * Abort processing of a JPEG compression or decompression operation,
  162175. * but don't destroy the object itself.
  162176. *
  162177. * For this, we merely clean up all the nonpermanent memory pools.
  162178. * Note that temp files (virtual arrays) are not allowed to belong to
  162179. * the permanent pool, so we will be able to close all temp files here.
  162180. * Closing a data source or destination, if necessary, is the application's
  162181. * responsibility.
  162182. */
  162183. GLOBAL(void)
  162184. jpeg_abort (j_common_ptr cinfo)
  162185. {
  162186. int pool;
  162187. /* Do nothing if called on a not-initialized or destroyed JPEG object. */
  162188. if (cinfo->mem == NULL)
  162189. return;
  162190. /* Releasing pools in reverse order might help avoid fragmentation
  162191. * with some (brain-damaged) malloc libraries.
  162192. */
  162193. for (pool = JPOOL_NUMPOOLS-1; pool > JPOOL_PERMANENT; pool--) {
  162194. (*cinfo->mem->free_pool) (cinfo, pool);
  162195. }
  162196. /* Reset overall state for possible reuse of object */
  162197. if (cinfo->is_decompressor) {
  162198. cinfo->global_state = DSTATE_START;
  162199. /* Try to keep application from accessing now-deleted marker list.
  162200. * A bit kludgy to do it here, but this is the most central place.
  162201. */
  162202. ((j_decompress_ptr) cinfo)->marker_list = NULL;
  162203. } else {
  162204. cinfo->global_state = CSTATE_START;
  162205. }
  162206. }
  162207. /*
  162208. * Destruction of a JPEG object.
  162209. *
  162210. * Everything gets deallocated except the master jpeg_compress_struct itself
  162211. * and the error manager struct. Both of these are supplied by the application
  162212. * and must be freed, if necessary, by the application. (Often they are on
  162213. * the stack and so don't need to be freed anyway.)
  162214. * Closing a data source or destination, if necessary, is the application's
  162215. * responsibility.
  162216. */
  162217. GLOBAL(void)
  162218. jpeg_destroy (j_common_ptr cinfo)
  162219. {
  162220. /* We need only tell the memory manager to release everything. */
  162221. /* NB: mem pointer is NULL if memory mgr failed to initialize. */
  162222. if (cinfo->mem != NULL)
  162223. (*cinfo->mem->self_destruct) (cinfo);
  162224. cinfo->mem = NULL; /* be safe if jpeg_destroy is called twice */
  162225. cinfo->global_state = 0; /* mark it destroyed */
  162226. }
  162227. /*
  162228. * Convenience routines for allocating quantization and Huffman tables.
  162229. * (Would jutils.c be a more reasonable place to put these?)
  162230. */
  162231. GLOBAL(JQUANT_TBL *)
  162232. jpeg_alloc_quant_table (j_common_ptr cinfo)
  162233. {
  162234. JQUANT_TBL *tbl;
  162235. tbl = (JQUANT_TBL *)
  162236. (*cinfo->mem->alloc_small) (cinfo, JPOOL_PERMANENT, SIZEOF(JQUANT_TBL));
  162237. tbl->sent_table = FALSE; /* make sure this is false in any new table */
  162238. return tbl;
  162239. }
  162240. GLOBAL(JHUFF_TBL *)
  162241. jpeg_alloc_huff_table (j_common_ptr cinfo)
  162242. {
  162243. JHUFF_TBL *tbl;
  162244. tbl = (JHUFF_TBL *)
  162245. (*cinfo->mem->alloc_small) (cinfo, JPOOL_PERMANENT, SIZEOF(JHUFF_TBL));
  162246. tbl->sent_table = FALSE; /* make sure this is false in any new table */
  162247. return tbl;
  162248. }
  162249. /*** End of inlined file: jcomapi.c ***/
  162250. /*** Start of inlined file: jcparam.c ***/
  162251. #define JPEG_INTERNALS
  162252. /*
  162253. * Quantization table setup routines
  162254. */
  162255. GLOBAL(void)
  162256. jpeg_add_quant_table (j_compress_ptr cinfo, int which_tbl,
  162257. const unsigned int *basic_table,
  162258. int scale_factor, boolean force_baseline)
  162259. /* Define a quantization table equal to the basic_table times
  162260. * a scale factor (given as a percentage).
  162261. * If force_baseline is TRUE, the computed quantization table entries
  162262. * are limited to 1..255 for JPEG baseline compatibility.
  162263. */
  162264. {
  162265. JQUANT_TBL ** qtblptr;
  162266. int i;
  162267. long temp;
  162268. /* Safety check to ensure start_compress not called yet. */
  162269. if (cinfo->global_state != CSTATE_START)
  162270. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  162271. if (which_tbl < 0 || which_tbl >= NUM_QUANT_TBLS)
  162272. ERREXIT1(cinfo, JERR_DQT_INDEX, which_tbl);
  162273. qtblptr = & cinfo->quant_tbl_ptrs[which_tbl];
  162274. if (*qtblptr == NULL)
  162275. *qtblptr = jpeg_alloc_quant_table((j_common_ptr) cinfo);
  162276. for (i = 0; i < DCTSIZE2; i++) {
  162277. temp = ((long) basic_table[i] * scale_factor + 50L) / 100L;
  162278. /* limit the values to the valid range */
  162279. if (temp <= 0L) temp = 1L;
  162280. if (temp > 32767L) temp = 32767L; /* max quantizer needed for 12 bits */
  162281. if (force_baseline && temp > 255L)
  162282. temp = 255L; /* limit to baseline range if requested */
  162283. (*qtblptr)->quantval[i] = (UINT16) temp;
  162284. }
  162285. /* Initialize sent_table FALSE so table will be written to JPEG file. */
  162286. (*qtblptr)->sent_table = FALSE;
  162287. }
  162288. GLOBAL(void)
  162289. jpeg_set_linear_quality (j_compress_ptr cinfo, int scale_factor,
  162290. boolean force_baseline)
  162291. /* Set or change the 'quality' (quantization) setting, using default tables
  162292. * and a straight percentage-scaling quality scale. In most cases it's better
  162293. * to use jpeg_set_quality (below); this entry point is provided for
  162294. * applications that insist on a linear percentage scaling.
  162295. */
  162296. {
  162297. /* These are the sample quantization tables given in JPEG spec section K.1.
  162298. * The spec says that the values given produce "good" quality, and
  162299. * when divided by 2, "very good" quality.
  162300. */
  162301. static const unsigned int std_luminance_quant_tbl[DCTSIZE2] = {
  162302. 16, 11, 10, 16, 24, 40, 51, 61,
  162303. 12, 12, 14, 19, 26, 58, 60, 55,
  162304. 14, 13, 16, 24, 40, 57, 69, 56,
  162305. 14, 17, 22, 29, 51, 87, 80, 62,
  162306. 18, 22, 37, 56, 68, 109, 103, 77,
  162307. 24, 35, 55, 64, 81, 104, 113, 92,
  162308. 49, 64, 78, 87, 103, 121, 120, 101,
  162309. 72, 92, 95, 98, 112, 100, 103, 99
  162310. };
  162311. static const unsigned int std_chrominance_quant_tbl[DCTSIZE2] = {
  162312. 17, 18, 24, 47, 99, 99, 99, 99,
  162313. 18, 21, 26, 66, 99, 99, 99, 99,
  162314. 24, 26, 56, 99, 99, 99, 99, 99,
  162315. 47, 66, 99, 99, 99, 99, 99, 99,
  162316. 99, 99, 99, 99, 99, 99, 99, 99,
  162317. 99, 99, 99, 99, 99, 99, 99, 99,
  162318. 99, 99, 99, 99, 99, 99, 99, 99,
  162319. 99, 99, 99, 99, 99, 99, 99, 99
  162320. };
  162321. /* Set up two quantization tables using the specified scaling */
  162322. jpeg_add_quant_table(cinfo, 0, std_luminance_quant_tbl,
  162323. scale_factor, force_baseline);
  162324. jpeg_add_quant_table(cinfo, 1, std_chrominance_quant_tbl,
  162325. scale_factor, force_baseline);
  162326. }
  162327. GLOBAL(int)
  162328. jpeg_quality_scaling (int quality)
  162329. /* Convert a user-specified quality rating to a percentage scaling factor
  162330. * for an underlying quantization table, using our recommended scaling curve.
  162331. * The input 'quality' factor should be 0 (terrible) to 100 (very good).
  162332. */
  162333. {
  162334. /* Safety limit on quality factor. Convert 0 to 1 to avoid zero divide. */
  162335. if (quality <= 0) quality = 1;
  162336. if (quality > 100) quality = 100;
  162337. /* The basic table is used as-is (scaling 100) for a quality of 50.
  162338. * Qualities 50..100 are converted to scaling percentage 200 - 2*Q;
  162339. * note that at Q=100 the scaling is 0, which will cause jpeg_add_quant_table
  162340. * to make all the table entries 1 (hence, minimum quantization loss).
  162341. * Qualities 1..50 are converted to scaling percentage 5000/Q.
  162342. */
  162343. if (quality < 50)
  162344. quality = 5000 / quality;
  162345. else
  162346. quality = 200 - quality*2;
  162347. return quality;
  162348. }
  162349. GLOBAL(void)
  162350. jpeg_set_quality (j_compress_ptr cinfo, int quality, boolean force_baseline)
  162351. /* Set or change the 'quality' (quantization) setting, using default tables.
  162352. * This is the standard quality-adjusting entry point for typical user
  162353. * interfaces; only those who want detailed control over quantization tables
  162354. * would use the preceding three routines directly.
  162355. */
  162356. {
  162357. /* Convert user 0-100 rating to percentage scaling */
  162358. quality = jpeg_quality_scaling(quality);
  162359. /* Set up standard quality tables */
  162360. jpeg_set_linear_quality(cinfo, quality, force_baseline);
  162361. }
  162362. /*
  162363. * Huffman table setup routines
  162364. */
  162365. LOCAL(void)
  162366. add_huff_table (j_compress_ptr cinfo,
  162367. JHUFF_TBL **htblptr, const UINT8 *bits, const UINT8 *val)
  162368. /* Define a Huffman table */
  162369. {
  162370. int nsymbols, len;
  162371. if (*htblptr == NULL)
  162372. *htblptr = jpeg_alloc_huff_table((j_common_ptr) cinfo);
  162373. /* Copy the number-of-symbols-of-each-code-length counts */
  162374. MEMCOPY((*htblptr)->bits, bits, SIZEOF((*htblptr)->bits));
  162375. /* Validate the counts. We do this here mainly so we can copy the right
  162376. * number of symbols from the val[] array, without risking marching off
  162377. * the end of memory. jchuff.c will do a more thorough test later.
  162378. */
  162379. nsymbols = 0;
  162380. for (len = 1; len <= 16; len++)
  162381. nsymbols += bits[len];
  162382. if (nsymbols < 1 || nsymbols > 256)
  162383. ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
  162384. MEMCOPY((*htblptr)->huffval, val, nsymbols * SIZEOF(UINT8));
  162385. /* Initialize sent_table FALSE so table will be written to JPEG file. */
  162386. (*htblptr)->sent_table = FALSE;
  162387. }
  162388. LOCAL(void)
  162389. std_huff_tables (j_compress_ptr cinfo)
  162390. /* Set up the standard Huffman tables (cf. JPEG standard section K.3) */
  162391. /* IMPORTANT: these are only valid for 8-bit data precision! */
  162392. {
  162393. static const UINT8 bits_dc_luminance[17] =
  162394. { /* 0-base */ 0, 0, 1, 5, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0 };
  162395. static const UINT8 val_dc_luminance[] =
  162396. { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11 };
  162397. static const UINT8 bits_dc_chrominance[17] =
  162398. { /* 0-base */ 0, 0, 3, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0 };
  162399. static const UINT8 val_dc_chrominance[] =
  162400. { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11 };
  162401. static const UINT8 bits_ac_luminance[17] =
  162402. { /* 0-base */ 0, 0, 2, 1, 3, 3, 2, 4, 3, 5, 5, 4, 4, 0, 0, 1, 0x7d };
  162403. static const UINT8 val_ac_luminance[] =
  162404. { 0x01, 0x02, 0x03, 0x00, 0x04, 0x11, 0x05, 0x12,
  162405. 0x21, 0x31, 0x41, 0x06, 0x13, 0x51, 0x61, 0x07,
  162406. 0x22, 0x71, 0x14, 0x32, 0x81, 0x91, 0xa1, 0x08,
  162407. 0x23, 0x42, 0xb1, 0xc1, 0x15, 0x52, 0xd1, 0xf0,
  162408. 0x24, 0x33, 0x62, 0x72, 0x82, 0x09, 0x0a, 0x16,
  162409. 0x17, 0x18, 0x19, 0x1a, 0x25, 0x26, 0x27, 0x28,
  162410. 0x29, 0x2a, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39,
  162411. 0x3a, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48, 0x49,
  162412. 0x4a, 0x53, 0x54, 0x55, 0x56, 0x57, 0x58, 0x59,
  162413. 0x5a, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69,
  162414. 0x6a, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78, 0x79,
  162415. 0x7a, 0x83, 0x84, 0x85, 0x86, 0x87, 0x88, 0x89,
  162416. 0x8a, 0x92, 0x93, 0x94, 0x95, 0x96, 0x97, 0x98,
  162417. 0x99, 0x9a, 0xa2, 0xa3, 0xa4, 0xa5, 0xa6, 0xa7,
  162418. 0xa8, 0xa9, 0xaa, 0xb2, 0xb3, 0xb4, 0xb5, 0xb6,
  162419. 0xb7, 0xb8, 0xb9, 0xba, 0xc2, 0xc3, 0xc4, 0xc5,
  162420. 0xc6, 0xc7, 0xc8, 0xc9, 0xca, 0xd2, 0xd3, 0xd4,
  162421. 0xd5, 0xd6, 0xd7, 0xd8, 0xd9, 0xda, 0xe1, 0xe2,
  162422. 0xe3, 0xe4, 0xe5, 0xe6, 0xe7, 0xe8, 0xe9, 0xea,
  162423. 0xf1, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7, 0xf8,
  162424. 0xf9, 0xfa };
  162425. static const UINT8 bits_ac_chrominance[17] =
  162426. { /* 0-base */ 0, 0, 2, 1, 2, 4, 4, 3, 4, 7, 5, 4, 4, 0, 1, 2, 0x77 };
  162427. static const UINT8 val_ac_chrominance[] =
  162428. { 0x00, 0x01, 0x02, 0x03, 0x11, 0x04, 0x05, 0x21,
  162429. 0x31, 0x06, 0x12, 0x41, 0x51, 0x07, 0x61, 0x71,
  162430. 0x13, 0x22, 0x32, 0x81, 0x08, 0x14, 0x42, 0x91,
  162431. 0xa1, 0xb1, 0xc1, 0x09, 0x23, 0x33, 0x52, 0xf0,
  162432. 0x15, 0x62, 0x72, 0xd1, 0x0a, 0x16, 0x24, 0x34,
  162433. 0xe1, 0x25, 0xf1, 0x17, 0x18, 0x19, 0x1a, 0x26,
  162434. 0x27, 0x28, 0x29, 0x2a, 0x35, 0x36, 0x37, 0x38,
  162435. 0x39, 0x3a, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48,
  162436. 0x49, 0x4a, 0x53, 0x54, 0x55, 0x56, 0x57, 0x58,
  162437. 0x59, 0x5a, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68,
  162438. 0x69, 0x6a, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78,
  162439. 0x79, 0x7a, 0x82, 0x83, 0x84, 0x85, 0x86, 0x87,
  162440. 0x88, 0x89, 0x8a, 0x92, 0x93, 0x94, 0x95, 0x96,
  162441. 0x97, 0x98, 0x99, 0x9a, 0xa2, 0xa3, 0xa4, 0xa5,
  162442. 0xa6, 0xa7, 0xa8, 0xa9, 0xaa, 0xb2, 0xb3, 0xb4,
  162443. 0xb5, 0xb6, 0xb7, 0xb8, 0xb9, 0xba, 0xc2, 0xc3,
  162444. 0xc4, 0xc5, 0xc6, 0xc7, 0xc8, 0xc9, 0xca, 0xd2,
  162445. 0xd3, 0xd4, 0xd5, 0xd6, 0xd7, 0xd8, 0xd9, 0xda,
  162446. 0xe2, 0xe3, 0xe4, 0xe5, 0xe6, 0xe7, 0xe8, 0xe9,
  162447. 0xea, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7, 0xf8,
  162448. 0xf9, 0xfa };
  162449. add_huff_table(cinfo, &cinfo->dc_huff_tbl_ptrs[0],
  162450. bits_dc_luminance, val_dc_luminance);
  162451. add_huff_table(cinfo, &cinfo->ac_huff_tbl_ptrs[0],
  162452. bits_ac_luminance, val_ac_luminance);
  162453. add_huff_table(cinfo, &cinfo->dc_huff_tbl_ptrs[1],
  162454. bits_dc_chrominance, val_dc_chrominance);
  162455. add_huff_table(cinfo, &cinfo->ac_huff_tbl_ptrs[1],
  162456. bits_ac_chrominance, val_ac_chrominance);
  162457. }
  162458. /*
  162459. * Default parameter setup for compression.
  162460. *
  162461. * Applications that don't choose to use this routine must do their
  162462. * own setup of all these parameters. Alternately, you can call this
  162463. * to establish defaults and then alter parameters selectively. This
  162464. * is the recommended approach since, if we add any new parameters,
  162465. * your code will still work (they'll be set to reasonable defaults).
  162466. */
  162467. GLOBAL(void)
  162468. jpeg_set_defaults (j_compress_ptr cinfo)
  162469. {
  162470. int i;
  162471. /* Safety check to ensure start_compress not called yet. */
  162472. if (cinfo->global_state != CSTATE_START)
  162473. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  162474. /* Allocate comp_info array large enough for maximum component count.
  162475. * Array is made permanent in case application wants to compress
  162476. * multiple images at same param settings.
  162477. */
  162478. if (cinfo->comp_info == NULL)
  162479. cinfo->comp_info = (jpeg_component_info *)
  162480. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT,
  162481. MAX_COMPONENTS * SIZEOF(jpeg_component_info));
  162482. /* Initialize everything not dependent on the color space */
  162483. cinfo->data_precision = BITS_IN_JSAMPLE;
  162484. /* Set up two quantization tables using default quality of 75 */
  162485. jpeg_set_quality(cinfo, 75, TRUE);
  162486. /* Set up two Huffman tables */
  162487. std_huff_tables(cinfo);
  162488. /* Initialize default arithmetic coding conditioning */
  162489. for (i = 0; i < NUM_ARITH_TBLS; i++) {
  162490. cinfo->arith_dc_L[i] = 0;
  162491. cinfo->arith_dc_U[i] = 1;
  162492. cinfo->arith_ac_K[i] = 5;
  162493. }
  162494. /* Default is no multiple-scan output */
  162495. cinfo->scan_info = NULL;
  162496. cinfo->num_scans = 0;
  162497. /* Expect normal source image, not raw downsampled data */
  162498. cinfo->raw_data_in = FALSE;
  162499. /* Use Huffman coding, not arithmetic coding, by default */
  162500. cinfo->arith_code = FALSE;
  162501. /* By default, don't do extra passes to optimize entropy coding */
  162502. cinfo->optimize_coding = FALSE;
  162503. /* The standard Huffman tables are only valid for 8-bit data precision.
  162504. * If the precision is higher, force optimization on so that usable
  162505. * tables will be computed. This test can be removed if default tables
  162506. * are supplied that are valid for the desired precision.
  162507. */
  162508. if (cinfo->data_precision > 8)
  162509. cinfo->optimize_coding = TRUE;
  162510. /* By default, use the simpler non-cosited sampling alignment */
  162511. cinfo->CCIR601_sampling = FALSE;
  162512. /* No input smoothing */
  162513. cinfo->smoothing_factor = 0;
  162514. /* DCT algorithm preference */
  162515. cinfo->dct_method = JDCT_DEFAULT;
  162516. /* No restart markers */
  162517. cinfo->restart_interval = 0;
  162518. cinfo->restart_in_rows = 0;
  162519. /* Fill in default JFIF marker parameters. Note that whether the marker
  162520. * will actually be written is determined by jpeg_set_colorspace.
  162521. *
  162522. * By default, the library emits JFIF version code 1.01.
  162523. * An application that wants to emit JFIF 1.02 extension markers should set
  162524. * JFIF_minor_version to 2. We could probably get away with just defaulting
  162525. * to 1.02, but there may still be some decoders in use that will complain
  162526. * about that; saying 1.01 should minimize compatibility problems.
  162527. */
  162528. cinfo->JFIF_major_version = 1; /* Default JFIF version = 1.01 */
  162529. cinfo->JFIF_minor_version = 1;
  162530. cinfo->density_unit = 0; /* Pixel size is unknown by default */
  162531. cinfo->X_density = 1; /* Pixel aspect ratio is square by default */
  162532. cinfo->Y_density = 1;
  162533. /* Choose JPEG colorspace based on input space, set defaults accordingly */
  162534. jpeg_default_colorspace(cinfo);
  162535. }
  162536. /*
  162537. * Select an appropriate JPEG colorspace for in_color_space.
  162538. */
  162539. GLOBAL(void)
  162540. jpeg_default_colorspace (j_compress_ptr cinfo)
  162541. {
  162542. switch (cinfo->in_color_space) {
  162543. case JCS_GRAYSCALE:
  162544. jpeg_set_colorspace(cinfo, JCS_GRAYSCALE);
  162545. break;
  162546. case JCS_RGB:
  162547. jpeg_set_colorspace(cinfo, JCS_YCbCr);
  162548. break;
  162549. case JCS_YCbCr:
  162550. jpeg_set_colorspace(cinfo, JCS_YCbCr);
  162551. break;
  162552. case JCS_CMYK:
  162553. jpeg_set_colorspace(cinfo, JCS_CMYK); /* By default, no translation */
  162554. break;
  162555. case JCS_YCCK:
  162556. jpeg_set_colorspace(cinfo, JCS_YCCK);
  162557. break;
  162558. case JCS_UNKNOWN:
  162559. jpeg_set_colorspace(cinfo, JCS_UNKNOWN);
  162560. break;
  162561. default:
  162562. ERREXIT(cinfo, JERR_BAD_IN_COLORSPACE);
  162563. }
  162564. }
  162565. /*
  162566. * Set the JPEG colorspace, and choose colorspace-dependent default values.
  162567. */
  162568. GLOBAL(void)
  162569. jpeg_set_colorspace (j_compress_ptr cinfo, J_COLOR_SPACE colorspace)
  162570. {
  162571. jpeg_component_info * compptr;
  162572. int ci;
  162573. #define SET_COMP(index,id,hsamp,vsamp,quant,dctbl,actbl) \
  162574. (compptr = &cinfo->comp_info[index], \
  162575. compptr->component_id = (id), \
  162576. compptr->h_samp_factor = (hsamp), \
  162577. compptr->v_samp_factor = (vsamp), \
  162578. compptr->quant_tbl_no = (quant), \
  162579. compptr->dc_tbl_no = (dctbl), \
  162580. compptr->ac_tbl_no = (actbl) )
  162581. /* Safety check to ensure start_compress not called yet. */
  162582. if (cinfo->global_state != CSTATE_START)
  162583. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  162584. /* For all colorspaces, we use Q and Huff tables 0 for luminance components,
  162585. * tables 1 for chrominance components.
  162586. */
  162587. cinfo->jpeg_color_space = colorspace;
  162588. cinfo->write_JFIF_header = FALSE; /* No marker for non-JFIF colorspaces */
  162589. cinfo->write_Adobe_marker = FALSE; /* write no Adobe marker by default */
  162590. switch (colorspace) {
  162591. case JCS_GRAYSCALE:
  162592. cinfo->write_JFIF_header = TRUE; /* Write a JFIF marker */
  162593. cinfo->num_components = 1;
  162594. /* JFIF specifies component ID 1 */
  162595. SET_COMP(0, 1, 1,1, 0, 0,0);
  162596. break;
  162597. case JCS_RGB:
  162598. cinfo->write_Adobe_marker = TRUE; /* write Adobe marker to flag RGB */
  162599. cinfo->num_components = 3;
  162600. SET_COMP(0, 0x52 /* 'R' */, 1,1, 0, 0,0);
  162601. SET_COMP(1, 0x47 /* 'G' */, 1,1, 0, 0,0);
  162602. SET_COMP(2, 0x42 /* 'B' */, 1,1, 0, 0,0);
  162603. break;
  162604. case JCS_YCbCr:
  162605. cinfo->write_JFIF_header = TRUE; /* Write a JFIF marker */
  162606. cinfo->num_components = 3;
  162607. /* JFIF specifies component IDs 1,2,3 */
  162608. /* We default to 2x2 subsamples of chrominance */
  162609. SET_COMP(0, 1, 2,2, 0, 0,0);
  162610. SET_COMP(1, 2, 1,1, 1, 1,1);
  162611. SET_COMP(2, 3, 1,1, 1, 1,1);
  162612. break;
  162613. case JCS_CMYK:
  162614. cinfo->write_Adobe_marker = TRUE; /* write Adobe marker to flag CMYK */
  162615. cinfo->num_components = 4;
  162616. SET_COMP(0, 0x43 /* 'C' */, 1,1, 0, 0,0);
  162617. SET_COMP(1, 0x4D /* 'M' */, 1,1, 0, 0,0);
  162618. SET_COMP(2, 0x59 /* 'Y' */, 1,1, 0, 0,0);
  162619. SET_COMP(3, 0x4B /* 'K' */, 1,1, 0, 0,0);
  162620. break;
  162621. case JCS_YCCK:
  162622. cinfo->write_Adobe_marker = TRUE; /* write Adobe marker to flag YCCK */
  162623. cinfo->num_components = 4;
  162624. SET_COMP(0, 1, 2,2, 0, 0,0);
  162625. SET_COMP(1, 2, 1,1, 1, 1,1);
  162626. SET_COMP(2, 3, 1,1, 1, 1,1);
  162627. SET_COMP(3, 4, 2,2, 0, 0,0);
  162628. break;
  162629. case JCS_UNKNOWN:
  162630. cinfo->num_components = cinfo->input_components;
  162631. if (cinfo->num_components < 1 || cinfo->num_components > MAX_COMPONENTS)
  162632. ERREXIT2(cinfo, JERR_COMPONENT_COUNT, cinfo->num_components,
  162633. MAX_COMPONENTS);
  162634. for (ci = 0; ci < cinfo->num_components; ci++) {
  162635. SET_COMP(ci, ci, 1,1, 0, 0,0);
  162636. }
  162637. break;
  162638. default:
  162639. ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
  162640. }
  162641. }
  162642. #ifdef C_PROGRESSIVE_SUPPORTED
  162643. LOCAL(jpeg_scan_info *)
  162644. fill_a_scan (jpeg_scan_info * scanptr, int ci,
  162645. int Ss, int Se, int Ah, int Al)
  162646. /* Support routine: generate one scan for specified component */
  162647. {
  162648. scanptr->comps_in_scan = 1;
  162649. scanptr->component_index[0] = ci;
  162650. scanptr->Ss = Ss;
  162651. scanptr->Se = Se;
  162652. scanptr->Ah = Ah;
  162653. scanptr->Al = Al;
  162654. scanptr++;
  162655. return scanptr;
  162656. }
  162657. LOCAL(jpeg_scan_info *)
  162658. fill_scans (jpeg_scan_info * scanptr, int ncomps,
  162659. int Ss, int Se, int Ah, int Al)
  162660. /* Support routine: generate one scan for each component */
  162661. {
  162662. int ci;
  162663. for (ci = 0; ci < ncomps; ci++) {
  162664. scanptr->comps_in_scan = 1;
  162665. scanptr->component_index[0] = ci;
  162666. scanptr->Ss = Ss;
  162667. scanptr->Se = Se;
  162668. scanptr->Ah = Ah;
  162669. scanptr->Al = Al;
  162670. scanptr++;
  162671. }
  162672. return scanptr;
  162673. }
  162674. LOCAL(jpeg_scan_info *)
  162675. fill_dc_scans (jpeg_scan_info * scanptr, int ncomps, int Ah, int Al)
  162676. /* Support routine: generate interleaved DC scan if possible, else N scans */
  162677. {
  162678. int ci;
  162679. if (ncomps <= MAX_COMPS_IN_SCAN) {
  162680. /* Single interleaved DC scan */
  162681. scanptr->comps_in_scan = ncomps;
  162682. for (ci = 0; ci < ncomps; ci++)
  162683. scanptr->component_index[ci] = ci;
  162684. scanptr->Ss = scanptr->Se = 0;
  162685. scanptr->Ah = Ah;
  162686. scanptr->Al = Al;
  162687. scanptr++;
  162688. } else {
  162689. /* Noninterleaved DC scan for each component */
  162690. scanptr = fill_scans(scanptr, ncomps, 0, 0, Ah, Al);
  162691. }
  162692. return scanptr;
  162693. }
  162694. /*
  162695. * Create a recommended progressive-JPEG script.
  162696. * cinfo->num_components and cinfo->jpeg_color_space must be correct.
  162697. */
  162698. GLOBAL(void)
  162699. jpeg_simple_progression (j_compress_ptr cinfo)
  162700. {
  162701. int ncomps = cinfo->num_components;
  162702. int nscans;
  162703. jpeg_scan_info * scanptr;
  162704. /* Safety check to ensure start_compress not called yet. */
  162705. if (cinfo->global_state != CSTATE_START)
  162706. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  162707. /* Figure space needed for script. Calculation must match code below! */
  162708. if (ncomps == 3 && cinfo->jpeg_color_space == JCS_YCbCr) {
  162709. /* Custom script for YCbCr color images. */
  162710. nscans = 10;
  162711. } else {
  162712. /* All-purpose script for other color spaces. */
  162713. if (ncomps > MAX_COMPS_IN_SCAN)
  162714. nscans = 6 * ncomps; /* 2 DC + 4 AC scans per component */
  162715. else
  162716. nscans = 2 + 4 * ncomps; /* 2 DC scans; 4 AC scans per component */
  162717. }
  162718. /* Allocate space for script.
  162719. * We need to put it in the permanent pool in case the application performs
  162720. * multiple compressions without changing the settings. To avoid a memory
  162721. * leak if jpeg_simple_progression is called repeatedly for the same JPEG
  162722. * object, we try to re-use previously allocated space, and we allocate
  162723. * enough space to handle YCbCr even if initially asked for grayscale.
  162724. */
  162725. if (cinfo->script_space == NULL || cinfo->script_space_size < nscans) {
  162726. cinfo->script_space_size = MAX(nscans, 10);
  162727. cinfo->script_space = (jpeg_scan_info *)
  162728. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT,
  162729. cinfo->script_space_size * SIZEOF(jpeg_scan_info));
  162730. }
  162731. scanptr = cinfo->script_space;
  162732. cinfo->scan_info = scanptr;
  162733. cinfo->num_scans = nscans;
  162734. if (ncomps == 3 && cinfo->jpeg_color_space == JCS_YCbCr) {
  162735. /* Custom script for YCbCr color images. */
  162736. /* Initial DC scan */
  162737. scanptr = fill_dc_scans(scanptr, ncomps, 0, 1);
  162738. /* Initial AC scan: get some luma data out in a hurry */
  162739. scanptr = fill_a_scan(scanptr, 0, 1, 5, 0, 2);
  162740. /* Chroma data is too small to be worth expending many scans on */
  162741. scanptr = fill_a_scan(scanptr, 2, 1, 63, 0, 1);
  162742. scanptr = fill_a_scan(scanptr, 1, 1, 63, 0, 1);
  162743. /* Complete spectral selection for luma AC */
  162744. scanptr = fill_a_scan(scanptr, 0, 6, 63, 0, 2);
  162745. /* Refine next bit of luma AC */
  162746. scanptr = fill_a_scan(scanptr, 0, 1, 63, 2, 1);
  162747. /* Finish DC successive approximation */
  162748. scanptr = fill_dc_scans(scanptr, ncomps, 1, 0);
  162749. /* Finish AC successive approximation */
  162750. scanptr = fill_a_scan(scanptr, 2, 1, 63, 1, 0);
  162751. scanptr = fill_a_scan(scanptr, 1, 1, 63, 1, 0);
  162752. /* Luma bottom bit comes last since it's usually largest scan */
  162753. scanptr = fill_a_scan(scanptr, 0, 1, 63, 1, 0);
  162754. } else {
  162755. /* All-purpose script for other color spaces. */
  162756. /* Successive approximation first pass */
  162757. scanptr = fill_dc_scans(scanptr, ncomps, 0, 1);
  162758. scanptr = fill_scans(scanptr, ncomps, 1, 5, 0, 2);
  162759. scanptr = fill_scans(scanptr, ncomps, 6, 63, 0, 2);
  162760. /* Successive approximation second pass */
  162761. scanptr = fill_scans(scanptr, ncomps, 1, 63, 2, 1);
  162762. /* Successive approximation final pass */
  162763. scanptr = fill_dc_scans(scanptr, ncomps, 1, 0);
  162764. scanptr = fill_scans(scanptr, ncomps, 1, 63, 1, 0);
  162765. }
  162766. }
  162767. #endif /* C_PROGRESSIVE_SUPPORTED */
  162768. /*** End of inlined file: jcparam.c ***/
  162769. /*** Start of inlined file: jcphuff.c ***/
  162770. #define JPEG_INTERNALS
  162771. #ifdef C_PROGRESSIVE_SUPPORTED
  162772. /* Expanded entropy encoder object for progressive Huffman encoding. */
  162773. typedef struct {
  162774. struct jpeg_entropy_encoder pub; /* public fields */
  162775. /* Mode flag: TRUE for optimization, FALSE for actual data output */
  162776. boolean gather_statistics;
  162777. /* Bit-level coding status.
  162778. * next_output_byte/free_in_buffer are local copies of cinfo->dest fields.
  162779. */
  162780. JOCTET * next_output_byte; /* => next byte to write in buffer */
  162781. size_t free_in_buffer; /* # of byte spaces remaining in buffer */
  162782. INT32 put_buffer; /* current bit-accumulation buffer */
  162783. int put_bits; /* # of bits now in it */
  162784. j_compress_ptr cinfo; /* link to cinfo (needed for dump_buffer) */
  162785. /* Coding status for DC components */
  162786. int last_dc_val[MAX_COMPS_IN_SCAN]; /* last DC coef for each component */
  162787. /* Coding status for AC components */
  162788. int ac_tbl_no; /* the table number of the single component */
  162789. unsigned int EOBRUN; /* run length of EOBs */
  162790. unsigned int BE; /* # of buffered correction bits before MCU */
  162791. char * bit_buffer; /* buffer for correction bits (1 per char) */
  162792. /* packing correction bits tightly would save some space but cost time... */
  162793. unsigned int restarts_to_go; /* MCUs left in this restart interval */
  162794. int next_restart_num; /* next restart number to write (0-7) */
  162795. /* Pointers to derived tables (these workspaces have image lifespan).
  162796. * Since any one scan codes only DC or only AC, we only need one set
  162797. * of tables, not one for DC and one for AC.
  162798. */
  162799. c_derived_tbl * derived_tbls[NUM_HUFF_TBLS];
  162800. /* Statistics tables for optimization; again, one set is enough */
  162801. long * count_ptrs[NUM_HUFF_TBLS];
  162802. } phuff_entropy_encoder;
  162803. typedef phuff_entropy_encoder * phuff_entropy_ptr;
  162804. /* MAX_CORR_BITS is the number of bits the AC refinement correction-bit
  162805. * buffer can hold. Larger sizes may slightly improve compression, but
  162806. * 1000 is already well into the realm of overkill.
  162807. * The minimum safe size is 64 bits.
  162808. */
  162809. #define MAX_CORR_BITS 1000 /* Max # of correction bits I can buffer */
  162810. /* IRIGHT_SHIFT is like RIGHT_SHIFT, but works on int rather than INT32.
  162811. * We assume that int right shift is unsigned if INT32 right shift is,
  162812. * which should be safe.
  162813. */
  162814. #ifdef RIGHT_SHIFT_IS_UNSIGNED
  162815. #define ISHIFT_TEMPS int ishift_temp;
  162816. #define IRIGHT_SHIFT(x,shft) \
  162817. ((ishift_temp = (x)) < 0 ? \
  162818. (ishift_temp >> (shft)) | ((~0) << (16-(shft))) : \
  162819. (ishift_temp >> (shft)))
  162820. #else
  162821. #define ISHIFT_TEMPS
  162822. #define IRIGHT_SHIFT(x,shft) ((x) >> (shft))
  162823. #endif
  162824. /* Forward declarations */
  162825. METHODDEF(boolean) encode_mcu_DC_first JPP((j_compress_ptr cinfo,
  162826. JBLOCKROW *MCU_data));
  162827. METHODDEF(boolean) encode_mcu_AC_first JPP((j_compress_ptr cinfo,
  162828. JBLOCKROW *MCU_data));
  162829. METHODDEF(boolean) encode_mcu_DC_refine JPP((j_compress_ptr cinfo,
  162830. JBLOCKROW *MCU_data));
  162831. METHODDEF(boolean) encode_mcu_AC_refine JPP((j_compress_ptr cinfo,
  162832. JBLOCKROW *MCU_data));
  162833. METHODDEF(void) finish_pass_phuff JPP((j_compress_ptr cinfo));
  162834. METHODDEF(void) finish_pass_gather_phuff JPP((j_compress_ptr cinfo));
  162835. /*
  162836. * Initialize for a Huffman-compressed scan using progressive JPEG.
  162837. */
  162838. METHODDEF(void)
  162839. start_pass_phuff (j_compress_ptr cinfo, boolean gather_statistics)
  162840. {
  162841. phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy;
  162842. boolean is_DC_band;
  162843. int ci, tbl;
  162844. jpeg_component_info * compptr;
  162845. entropy->cinfo = cinfo;
  162846. entropy->gather_statistics = gather_statistics;
  162847. is_DC_band = (cinfo->Ss == 0);
  162848. /* We assume jcmaster.c already validated the scan parameters. */
  162849. /* Select execution routines */
  162850. if (cinfo->Ah == 0) {
  162851. if (is_DC_band)
  162852. entropy->pub.encode_mcu = encode_mcu_DC_first;
  162853. else
  162854. entropy->pub.encode_mcu = encode_mcu_AC_first;
  162855. } else {
  162856. if (is_DC_band)
  162857. entropy->pub.encode_mcu = encode_mcu_DC_refine;
  162858. else {
  162859. entropy->pub.encode_mcu = encode_mcu_AC_refine;
  162860. /* AC refinement needs a correction bit buffer */
  162861. if (entropy->bit_buffer == NULL)
  162862. entropy->bit_buffer = (char *)
  162863. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  162864. MAX_CORR_BITS * SIZEOF(char));
  162865. }
  162866. }
  162867. if (gather_statistics)
  162868. entropy->pub.finish_pass = finish_pass_gather_phuff;
  162869. else
  162870. entropy->pub.finish_pass = finish_pass_phuff;
  162871. /* Only DC coefficients may be interleaved, so cinfo->comps_in_scan = 1
  162872. * for AC coefficients.
  162873. */
  162874. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  162875. compptr = cinfo->cur_comp_info[ci];
  162876. /* Initialize DC predictions to 0 */
  162877. entropy->last_dc_val[ci] = 0;
  162878. /* Get table index */
  162879. if (is_DC_band) {
  162880. if (cinfo->Ah != 0) /* DC refinement needs no table */
  162881. continue;
  162882. tbl = compptr->dc_tbl_no;
  162883. } else {
  162884. entropy->ac_tbl_no = tbl = compptr->ac_tbl_no;
  162885. }
  162886. if (gather_statistics) {
  162887. /* Check for invalid table index */
  162888. /* (make_c_derived_tbl does this in the other path) */
  162889. if (tbl < 0 || tbl >= NUM_HUFF_TBLS)
  162890. ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, tbl);
  162891. /* Allocate and zero the statistics tables */
  162892. /* Note that jpeg_gen_optimal_table expects 257 entries in each table! */
  162893. if (entropy->count_ptrs[tbl] == NULL)
  162894. entropy->count_ptrs[tbl] = (long *)
  162895. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  162896. 257 * SIZEOF(long));
  162897. MEMZERO(entropy->count_ptrs[tbl], 257 * SIZEOF(long));
  162898. } else {
  162899. /* Compute derived values for Huffman table */
  162900. /* We may do this more than once for a table, but it's not expensive */
  162901. jpeg_make_c_derived_tbl(cinfo, is_DC_band, tbl,
  162902. & entropy->derived_tbls[tbl]);
  162903. }
  162904. }
  162905. /* Initialize AC stuff */
  162906. entropy->EOBRUN = 0;
  162907. entropy->BE = 0;
  162908. /* Initialize bit buffer to empty */
  162909. entropy->put_buffer = 0;
  162910. entropy->put_bits = 0;
  162911. /* Initialize restart stuff */
  162912. entropy->restarts_to_go = cinfo->restart_interval;
  162913. entropy->next_restart_num = 0;
  162914. }
  162915. /* Outputting bytes to the file.
  162916. * NB: these must be called only when actually outputting,
  162917. * that is, entropy->gather_statistics == FALSE.
  162918. */
  162919. /* Emit a byte */
  162920. #define emit_byte(entropy,val) \
  162921. { *(entropy)->next_output_byte++ = (JOCTET) (val); \
  162922. if (--(entropy)->free_in_buffer == 0) \
  162923. dump_buffer_p(entropy); }
  162924. LOCAL(void)
  162925. dump_buffer_p (phuff_entropy_ptr entropy)
  162926. /* Empty the output buffer; we do not support suspension in this module. */
  162927. {
  162928. struct jpeg_destination_mgr * dest = entropy->cinfo->dest;
  162929. if (! (*dest->empty_output_buffer) (entropy->cinfo))
  162930. ERREXIT(entropy->cinfo, JERR_CANT_SUSPEND);
  162931. /* After a successful buffer dump, must reset buffer pointers */
  162932. entropy->next_output_byte = dest->next_output_byte;
  162933. entropy->free_in_buffer = dest->free_in_buffer;
  162934. }
  162935. /* Outputting bits to the file */
  162936. /* Only the right 24 bits of put_buffer are used; the valid bits are
  162937. * left-justified in this part. At most 16 bits can be passed to emit_bits
  162938. * in one call, and we never retain more than 7 bits in put_buffer
  162939. * between calls, so 24 bits are sufficient.
  162940. */
  162941. INLINE
  162942. LOCAL(void)
  162943. emit_bits_p (phuff_entropy_ptr entropy, unsigned int code, int size)
  162944. /* Emit some bits, unless we are in gather mode */
  162945. {
  162946. /* This routine is heavily used, so it's worth coding tightly. */
  162947. register INT32 put_buffer = (INT32) code;
  162948. register int put_bits = entropy->put_bits;
  162949. /* if size is 0, caller used an invalid Huffman table entry */
  162950. if (size == 0)
  162951. ERREXIT(entropy->cinfo, JERR_HUFF_MISSING_CODE);
  162952. if (entropy->gather_statistics)
  162953. return; /* do nothing if we're only getting stats */
  162954. put_buffer &= (((INT32) 1)<<size) - 1; /* mask off any extra bits in code */
  162955. put_bits += size; /* new number of bits in buffer */
  162956. put_buffer <<= 24 - put_bits; /* align incoming bits */
  162957. put_buffer |= entropy->put_buffer; /* and merge with old buffer contents */
  162958. while (put_bits >= 8) {
  162959. int c = (int) ((put_buffer >> 16) & 0xFF);
  162960. emit_byte(entropy, c);
  162961. if (c == 0xFF) { /* need to stuff a zero byte? */
  162962. emit_byte(entropy, 0);
  162963. }
  162964. put_buffer <<= 8;
  162965. put_bits -= 8;
  162966. }
  162967. entropy->put_buffer = put_buffer; /* update variables */
  162968. entropy->put_bits = put_bits;
  162969. }
  162970. LOCAL(void)
  162971. flush_bits_p (phuff_entropy_ptr entropy)
  162972. {
  162973. emit_bits_p(entropy, 0x7F, 7); /* fill any partial byte with ones */
  162974. entropy->put_buffer = 0; /* and reset bit-buffer to empty */
  162975. entropy->put_bits = 0;
  162976. }
  162977. /*
  162978. * Emit (or just count) a Huffman symbol.
  162979. */
  162980. INLINE
  162981. LOCAL(void)
  162982. emit_symbol (phuff_entropy_ptr entropy, int tbl_no, int symbol)
  162983. {
  162984. if (entropy->gather_statistics)
  162985. entropy->count_ptrs[tbl_no][symbol]++;
  162986. else {
  162987. c_derived_tbl * tbl = entropy->derived_tbls[tbl_no];
  162988. emit_bits_p(entropy, tbl->ehufco[symbol], tbl->ehufsi[symbol]);
  162989. }
  162990. }
  162991. /*
  162992. * Emit bits from a correction bit buffer.
  162993. */
  162994. LOCAL(void)
  162995. emit_buffered_bits (phuff_entropy_ptr entropy, char * bufstart,
  162996. unsigned int nbits)
  162997. {
  162998. if (entropy->gather_statistics)
  162999. return; /* no real work */
  163000. while (nbits > 0) {
  163001. emit_bits_p(entropy, (unsigned int) (*bufstart), 1);
  163002. bufstart++;
  163003. nbits--;
  163004. }
  163005. }
  163006. /*
  163007. * Emit any pending EOBRUN symbol.
  163008. */
  163009. LOCAL(void)
  163010. emit_eobrun (phuff_entropy_ptr entropy)
  163011. {
  163012. register int temp, nbits;
  163013. if (entropy->EOBRUN > 0) { /* if there is any pending EOBRUN */
  163014. temp = entropy->EOBRUN;
  163015. nbits = 0;
  163016. while ((temp >>= 1))
  163017. nbits++;
  163018. /* safety check: shouldn't happen given limited correction-bit buffer */
  163019. if (nbits > 14)
  163020. ERREXIT(entropy->cinfo, JERR_HUFF_MISSING_CODE);
  163021. emit_symbol(entropy, entropy->ac_tbl_no, nbits << 4);
  163022. if (nbits)
  163023. emit_bits_p(entropy, entropy->EOBRUN, nbits);
  163024. entropy->EOBRUN = 0;
  163025. /* Emit any buffered correction bits */
  163026. emit_buffered_bits(entropy, entropy->bit_buffer, entropy->BE);
  163027. entropy->BE = 0;
  163028. }
  163029. }
  163030. /*
  163031. * Emit a restart marker & resynchronize predictions.
  163032. */
  163033. LOCAL(void)
  163034. emit_restart_p (phuff_entropy_ptr entropy, int restart_num)
  163035. {
  163036. int ci;
  163037. emit_eobrun(entropy);
  163038. if (! entropy->gather_statistics) {
  163039. flush_bits_p(entropy);
  163040. emit_byte(entropy, 0xFF);
  163041. emit_byte(entropy, JPEG_RST0 + restart_num);
  163042. }
  163043. if (entropy->cinfo->Ss == 0) {
  163044. /* Re-initialize DC predictions to 0 */
  163045. for (ci = 0; ci < entropy->cinfo->comps_in_scan; ci++)
  163046. entropy->last_dc_val[ci] = 0;
  163047. } else {
  163048. /* Re-initialize all AC-related fields to 0 */
  163049. entropy->EOBRUN = 0;
  163050. entropy->BE = 0;
  163051. }
  163052. }
  163053. /*
  163054. * MCU encoding for DC initial scan (either spectral selection,
  163055. * or first pass of successive approximation).
  163056. */
  163057. METHODDEF(boolean)
  163058. encode_mcu_DC_first (j_compress_ptr cinfo, JBLOCKROW *MCU_data)
  163059. {
  163060. phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy;
  163061. register int temp, temp2;
  163062. register int nbits;
  163063. int blkn, ci;
  163064. int Al = cinfo->Al;
  163065. JBLOCKROW block;
  163066. jpeg_component_info * compptr;
  163067. ISHIFT_TEMPS
  163068. entropy->next_output_byte = cinfo->dest->next_output_byte;
  163069. entropy->free_in_buffer = cinfo->dest->free_in_buffer;
  163070. /* Emit restart marker if needed */
  163071. if (cinfo->restart_interval)
  163072. if (entropy->restarts_to_go == 0)
  163073. emit_restart_p(entropy, entropy->next_restart_num);
  163074. /* Encode the MCU data blocks */
  163075. for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
  163076. block = MCU_data[blkn];
  163077. ci = cinfo->MCU_membership[blkn];
  163078. compptr = cinfo->cur_comp_info[ci];
  163079. /* Compute the DC value after the required point transform by Al.
  163080. * This is simply an arithmetic right shift.
  163081. */
  163082. temp2 = IRIGHT_SHIFT((int) ((*block)[0]), Al);
  163083. /* DC differences are figured on the point-transformed values. */
  163084. temp = temp2 - entropy->last_dc_val[ci];
  163085. entropy->last_dc_val[ci] = temp2;
  163086. /* Encode the DC coefficient difference per section G.1.2.1 */
  163087. temp2 = temp;
  163088. if (temp < 0) {
  163089. temp = -temp; /* temp is abs value of input */
  163090. /* For a negative input, want temp2 = bitwise complement of abs(input) */
  163091. /* This code assumes we are on a two's complement machine */
  163092. temp2--;
  163093. }
  163094. /* Find the number of bits needed for the magnitude of the coefficient */
  163095. nbits = 0;
  163096. while (temp) {
  163097. nbits++;
  163098. temp >>= 1;
  163099. }
  163100. /* Check for out-of-range coefficient values.
  163101. * Since we're encoding a difference, the range limit is twice as much.
  163102. */
  163103. if (nbits > MAX_COEF_BITS+1)
  163104. ERREXIT(cinfo, JERR_BAD_DCT_COEF);
  163105. /* Count/emit the Huffman-coded symbol for the number of bits */
  163106. emit_symbol(entropy, compptr->dc_tbl_no, nbits);
  163107. /* Emit that number of bits of the value, if positive, */
  163108. /* or the complement of its magnitude, if negative. */
  163109. if (nbits) /* emit_bits rejects calls with size 0 */
  163110. emit_bits_p(entropy, (unsigned int) temp2, nbits);
  163111. }
  163112. cinfo->dest->next_output_byte = entropy->next_output_byte;
  163113. cinfo->dest->free_in_buffer = entropy->free_in_buffer;
  163114. /* Update restart-interval state too */
  163115. if (cinfo->restart_interval) {
  163116. if (entropy->restarts_to_go == 0) {
  163117. entropy->restarts_to_go = cinfo->restart_interval;
  163118. entropy->next_restart_num++;
  163119. entropy->next_restart_num &= 7;
  163120. }
  163121. entropy->restarts_to_go--;
  163122. }
  163123. return TRUE;
  163124. }
  163125. /*
  163126. * MCU encoding for AC initial scan (either spectral selection,
  163127. * or first pass of successive approximation).
  163128. */
  163129. METHODDEF(boolean)
  163130. encode_mcu_AC_first (j_compress_ptr cinfo, JBLOCKROW *MCU_data)
  163131. {
  163132. phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy;
  163133. register int temp, temp2;
  163134. register int nbits;
  163135. register int r, k;
  163136. int Se = cinfo->Se;
  163137. int Al = cinfo->Al;
  163138. JBLOCKROW block;
  163139. entropy->next_output_byte = cinfo->dest->next_output_byte;
  163140. entropy->free_in_buffer = cinfo->dest->free_in_buffer;
  163141. /* Emit restart marker if needed */
  163142. if (cinfo->restart_interval)
  163143. if (entropy->restarts_to_go == 0)
  163144. emit_restart_p(entropy, entropy->next_restart_num);
  163145. /* Encode the MCU data block */
  163146. block = MCU_data[0];
  163147. /* Encode the AC coefficients per section G.1.2.2, fig. G.3 */
  163148. r = 0; /* r = run length of zeros */
  163149. for (k = cinfo->Ss; k <= Se; k++) {
  163150. if ((temp = (*block)[jpeg_natural_order[k]]) == 0) {
  163151. r++;
  163152. continue;
  163153. }
  163154. /* We must apply the point transform by Al. For AC coefficients this
  163155. * is an integer division with rounding towards 0. To do this portably
  163156. * in C, we shift after obtaining the absolute value; so the code is
  163157. * interwoven with finding the abs value (temp) and output bits (temp2).
  163158. */
  163159. if (temp < 0) {
  163160. temp = -temp; /* temp is abs value of input */
  163161. temp >>= Al; /* apply the point transform */
  163162. /* For a negative coef, want temp2 = bitwise complement of abs(coef) */
  163163. temp2 = ~temp;
  163164. } else {
  163165. temp >>= Al; /* apply the point transform */
  163166. temp2 = temp;
  163167. }
  163168. /* Watch out for case that nonzero coef is zero after point transform */
  163169. if (temp == 0) {
  163170. r++;
  163171. continue;
  163172. }
  163173. /* Emit any pending EOBRUN */
  163174. if (entropy->EOBRUN > 0)
  163175. emit_eobrun(entropy);
  163176. /* if run length > 15, must emit special run-length-16 codes (0xF0) */
  163177. while (r > 15) {
  163178. emit_symbol(entropy, entropy->ac_tbl_no, 0xF0);
  163179. r -= 16;
  163180. }
  163181. /* Find the number of bits needed for the magnitude of the coefficient */
  163182. nbits = 1; /* there must be at least one 1 bit */
  163183. while ((temp >>= 1))
  163184. nbits++;
  163185. /* Check for out-of-range coefficient values */
  163186. if (nbits > MAX_COEF_BITS)
  163187. ERREXIT(cinfo, JERR_BAD_DCT_COEF);
  163188. /* Count/emit Huffman symbol for run length / number of bits */
  163189. emit_symbol(entropy, entropy->ac_tbl_no, (r << 4) + nbits);
  163190. /* Emit that number of bits of the value, if positive, */
  163191. /* or the complement of its magnitude, if negative. */
  163192. emit_bits_p(entropy, (unsigned int) temp2, nbits);
  163193. r = 0; /* reset zero run length */
  163194. }
  163195. if (r > 0) { /* If there are trailing zeroes, */
  163196. entropy->EOBRUN++; /* count an EOB */
  163197. if (entropy->EOBRUN == 0x7FFF)
  163198. emit_eobrun(entropy); /* force it out to avoid overflow */
  163199. }
  163200. cinfo->dest->next_output_byte = entropy->next_output_byte;
  163201. cinfo->dest->free_in_buffer = entropy->free_in_buffer;
  163202. /* Update restart-interval state too */
  163203. if (cinfo->restart_interval) {
  163204. if (entropy->restarts_to_go == 0) {
  163205. entropy->restarts_to_go = cinfo->restart_interval;
  163206. entropy->next_restart_num++;
  163207. entropy->next_restart_num &= 7;
  163208. }
  163209. entropy->restarts_to_go--;
  163210. }
  163211. return TRUE;
  163212. }
  163213. /*
  163214. * MCU encoding for DC successive approximation refinement scan.
  163215. * Note: we assume such scans can be multi-component, although the spec
  163216. * is not very clear on the point.
  163217. */
  163218. METHODDEF(boolean)
  163219. encode_mcu_DC_refine (j_compress_ptr cinfo, JBLOCKROW *MCU_data)
  163220. {
  163221. phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy;
  163222. register int temp;
  163223. int blkn;
  163224. int Al = cinfo->Al;
  163225. JBLOCKROW block;
  163226. entropy->next_output_byte = cinfo->dest->next_output_byte;
  163227. entropy->free_in_buffer = cinfo->dest->free_in_buffer;
  163228. /* Emit restart marker if needed */
  163229. if (cinfo->restart_interval)
  163230. if (entropy->restarts_to_go == 0)
  163231. emit_restart_p(entropy, entropy->next_restart_num);
  163232. /* Encode the MCU data blocks */
  163233. for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
  163234. block = MCU_data[blkn];
  163235. /* We simply emit the Al'th bit of the DC coefficient value. */
  163236. temp = (*block)[0];
  163237. emit_bits_p(entropy, (unsigned int) (temp >> Al), 1);
  163238. }
  163239. cinfo->dest->next_output_byte = entropy->next_output_byte;
  163240. cinfo->dest->free_in_buffer = entropy->free_in_buffer;
  163241. /* Update restart-interval state too */
  163242. if (cinfo->restart_interval) {
  163243. if (entropy->restarts_to_go == 0) {
  163244. entropy->restarts_to_go = cinfo->restart_interval;
  163245. entropy->next_restart_num++;
  163246. entropy->next_restart_num &= 7;
  163247. }
  163248. entropy->restarts_to_go--;
  163249. }
  163250. return TRUE;
  163251. }
  163252. /*
  163253. * MCU encoding for AC successive approximation refinement scan.
  163254. */
  163255. METHODDEF(boolean)
  163256. encode_mcu_AC_refine (j_compress_ptr cinfo, JBLOCKROW *MCU_data)
  163257. {
  163258. phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy;
  163259. register int temp;
  163260. register int r, k;
  163261. int EOB;
  163262. char *BR_buffer;
  163263. unsigned int BR;
  163264. int Se = cinfo->Se;
  163265. int Al = cinfo->Al;
  163266. JBLOCKROW block;
  163267. int absvalues[DCTSIZE2];
  163268. entropy->next_output_byte = cinfo->dest->next_output_byte;
  163269. entropy->free_in_buffer = cinfo->dest->free_in_buffer;
  163270. /* Emit restart marker if needed */
  163271. if (cinfo->restart_interval)
  163272. if (entropy->restarts_to_go == 0)
  163273. emit_restart_p(entropy, entropy->next_restart_num);
  163274. /* Encode the MCU data block */
  163275. block = MCU_data[0];
  163276. /* It is convenient to make a pre-pass to determine the transformed
  163277. * coefficients' absolute values and the EOB position.
  163278. */
  163279. EOB = 0;
  163280. for (k = cinfo->Ss; k <= Se; k++) {
  163281. temp = (*block)[jpeg_natural_order[k]];
  163282. /* We must apply the point transform by Al. For AC coefficients this
  163283. * is an integer division with rounding towards 0. To do this portably
  163284. * in C, we shift after obtaining the absolute value.
  163285. */
  163286. if (temp < 0)
  163287. temp = -temp; /* temp is abs value of input */
  163288. temp >>= Al; /* apply the point transform */
  163289. absvalues[k] = temp; /* save abs value for main pass */
  163290. if (temp == 1)
  163291. EOB = k; /* EOB = index of last newly-nonzero coef */
  163292. }
  163293. /* Encode the AC coefficients per section G.1.2.3, fig. G.7 */
  163294. r = 0; /* r = run length of zeros */
  163295. BR = 0; /* BR = count of buffered bits added now */
  163296. BR_buffer = entropy->bit_buffer + entropy->BE; /* Append bits to buffer */
  163297. for (k = cinfo->Ss; k <= Se; k++) {
  163298. if ((temp = absvalues[k]) == 0) {
  163299. r++;
  163300. continue;
  163301. }
  163302. /* Emit any required ZRLs, but not if they can be folded into EOB */
  163303. while (r > 15 && k <= EOB) {
  163304. /* emit any pending EOBRUN and the BE correction bits */
  163305. emit_eobrun(entropy);
  163306. /* Emit ZRL */
  163307. emit_symbol(entropy, entropy->ac_tbl_no, 0xF0);
  163308. r -= 16;
  163309. /* Emit buffered correction bits that must be associated with ZRL */
  163310. emit_buffered_bits(entropy, BR_buffer, BR);
  163311. BR_buffer = entropy->bit_buffer; /* BE bits are gone now */
  163312. BR = 0;
  163313. }
  163314. /* If the coef was previously nonzero, it only needs a correction bit.
  163315. * NOTE: a straight translation of the spec's figure G.7 would suggest
  163316. * that we also need to test r > 15. But if r > 15, we can only get here
  163317. * if k > EOB, which implies that this coefficient is not 1.
  163318. */
  163319. if (temp > 1) {
  163320. /* The correction bit is the next bit of the absolute value. */
  163321. BR_buffer[BR++] = (char) (temp & 1);
  163322. continue;
  163323. }
  163324. /* Emit any pending EOBRUN and the BE correction bits */
  163325. emit_eobrun(entropy);
  163326. /* Count/emit Huffman symbol for run length / number of bits */
  163327. emit_symbol(entropy, entropy->ac_tbl_no, (r << 4) + 1);
  163328. /* Emit output bit for newly-nonzero coef */
  163329. temp = ((*block)[jpeg_natural_order[k]] < 0) ? 0 : 1;
  163330. emit_bits_p(entropy, (unsigned int) temp, 1);
  163331. /* Emit buffered correction bits that must be associated with this code */
  163332. emit_buffered_bits(entropy, BR_buffer, BR);
  163333. BR_buffer = entropy->bit_buffer; /* BE bits are gone now */
  163334. BR = 0;
  163335. r = 0; /* reset zero run length */
  163336. }
  163337. if (r > 0 || BR > 0) { /* If there are trailing zeroes, */
  163338. entropy->EOBRUN++; /* count an EOB */
  163339. entropy->BE += BR; /* concat my correction bits to older ones */
  163340. /* We force out the EOB if we risk either:
  163341. * 1. overflow of the EOB counter;
  163342. * 2. overflow of the correction bit buffer during the next MCU.
  163343. */
  163344. if (entropy->EOBRUN == 0x7FFF || entropy->BE > (MAX_CORR_BITS-DCTSIZE2+1))
  163345. emit_eobrun(entropy);
  163346. }
  163347. cinfo->dest->next_output_byte = entropy->next_output_byte;
  163348. cinfo->dest->free_in_buffer = entropy->free_in_buffer;
  163349. /* Update restart-interval state too */
  163350. if (cinfo->restart_interval) {
  163351. if (entropy->restarts_to_go == 0) {
  163352. entropy->restarts_to_go = cinfo->restart_interval;
  163353. entropy->next_restart_num++;
  163354. entropy->next_restart_num &= 7;
  163355. }
  163356. entropy->restarts_to_go--;
  163357. }
  163358. return TRUE;
  163359. }
  163360. /*
  163361. * Finish up at the end of a Huffman-compressed progressive scan.
  163362. */
  163363. METHODDEF(void)
  163364. finish_pass_phuff (j_compress_ptr cinfo)
  163365. {
  163366. phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy;
  163367. entropy->next_output_byte = cinfo->dest->next_output_byte;
  163368. entropy->free_in_buffer = cinfo->dest->free_in_buffer;
  163369. /* Flush out any buffered data */
  163370. emit_eobrun(entropy);
  163371. flush_bits_p(entropy);
  163372. cinfo->dest->next_output_byte = entropy->next_output_byte;
  163373. cinfo->dest->free_in_buffer = entropy->free_in_buffer;
  163374. }
  163375. /*
  163376. * Finish up a statistics-gathering pass and create the new Huffman tables.
  163377. */
  163378. METHODDEF(void)
  163379. finish_pass_gather_phuff (j_compress_ptr cinfo)
  163380. {
  163381. phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy;
  163382. boolean is_DC_band;
  163383. int ci, tbl;
  163384. jpeg_component_info * compptr;
  163385. JHUFF_TBL **htblptr;
  163386. boolean did[NUM_HUFF_TBLS];
  163387. /* Flush out buffered data (all we care about is counting the EOB symbol) */
  163388. emit_eobrun(entropy);
  163389. is_DC_band = (cinfo->Ss == 0);
  163390. /* It's important not to apply jpeg_gen_optimal_table more than once
  163391. * per table, because it clobbers the input frequency counts!
  163392. */
  163393. MEMZERO(did, SIZEOF(did));
  163394. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  163395. compptr = cinfo->cur_comp_info[ci];
  163396. if (is_DC_band) {
  163397. if (cinfo->Ah != 0) /* DC refinement needs no table */
  163398. continue;
  163399. tbl = compptr->dc_tbl_no;
  163400. } else {
  163401. tbl = compptr->ac_tbl_no;
  163402. }
  163403. if (! did[tbl]) {
  163404. if (is_DC_band)
  163405. htblptr = & cinfo->dc_huff_tbl_ptrs[tbl];
  163406. else
  163407. htblptr = & cinfo->ac_huff_tbl_ptrs[tbl];
  163408. if (*htblptr == NULL)
  163409. *htblptr = jpeg_alloc_huff_table((j_common_ptr) cinfo);
  163410. jpeg_gen_optimal_table(cinfo, *htblptr, entropy->count_ptrs[tbl]);
  163411. did[tbl] = TRUE;
  163412. }
  163413. }
  163414. }
  163415. /*
  163416. * Module initialization routine for progressive Huffman entropy encoding.
  163417. */
  163418. GLOBAL(void)
  163419. jinit_phuff_encoder (j_compress_ptr cinfo)
  163420. {
  163421. phuff_entropy_ptr entropy;
  163422. int i;
  163423. entropy = (phuff_entropy_ptr)
  163424. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  163425. SIZEOF(phuff_entropy_encoder));
  163426. cinfo->entropy = (struct jpeg_entropy_encoder *) entropy;
  163427. entropy->pub.start_pass = start_pass_phuff;
  163428. /* Mark tables unallocated */
  163429. for (i = 0; i < NUM_HUFF_TBLS; i++) {
  163430. entropy->derived_tbls[i] = NULL;
  163431. entropy->count_ptrs[i] = NULL;
  163432. }
  163433. entropy->bit_buffer = NULL; /* needed only in AC refinement scan */
  163434. }
  163435. #endif /* C_PROGRESSIVE_SUPPORTED */
  163436. /*** End of inlined file: jcphuff.c ***/
  163437. /*** Start of inlined file: jcprepct.c ***/
  163438. #define JPEG_INTERNALS
  163439. /* At present, jcsample.c can request context rows only for smoothing.
  163440. * In the future, we might also need context rows for CCIR601 sampling
  163441. * or other more-complex downsampling procedures. The code to support
  163442. * context rows should be compiled only if needed.
  163443. */
  163444. #ifdef INPUT_SMOOTHING_SUPPORTED
  163445. #define CONTEXT_ROWS_SUPPORTED
  163446. #endif
  163447. /*
  163448. * For the simple (no-context-row) case, we just need to buffer one
  163449. * row group's worth of pixels for the downsampling step. At the bottom of
  163450. * the image, we pad to a full row group by replicating the last pixel row.
  163451. * The downsampler's last output row is then replicated if needed to pad
  163452. * out to a full iMCU row.
  163453. *
  163454. * When providing context rows, we must buffer three row groups' worth of
  163455. * pixels. Three row groups are physically allocated, but the row pointer
  163456. * arrays are made five row groups high, with the extra pointers above and
  163457. * below "wrapping around" to point to the last and first real row groups.
  163458. * This allows the downsampler to access the proper context rows.
  163459. * At the top and bottom of the image, we create dummy context rows by
  163460. * copying the first or last real pixel row. This copying could be avoided
  163461. * by pointer hacking as is done in jdmainct.c, but it doesn't seem worth the
  163462. * trouble on the compression side.
  163463. */
  163464. /* Private buffer controller object */
  163465. typedef struct {
  163466. struct jpeg_c_prep_controller pub; /* public fields */
  163467. /* Downsampling input buffer. This buffer holds color-converted data
  163468. * until we have enough to do a downsample step.
  163469. */
  163470. JSAMPARRAY color_buf[MAX_COMPONENTS];
  163471. JDIMENSION rows_to_go; /* counts rows remaining in source image */
  163472. int next_buf_row; /* index of next row to store in color_buf */
  163473. #ifdef CONTEXT_ROWS_SUPPORTED /* only needed for context case */
  163474. int this_row_group; /* starting row index of group to process */
  163475. int next_buf_stop; /* downsample when we reach this index */
  163476. #endif
  163477. } my_prep_controller;
  163478. typedef my_prep_controller * my_prep_ptr;
  163479. /*
  163480. * Initialize for a processing pass.
  163481. */
  163482. METHODDEF(void)
  163483. start_pass_prep (j_compress_ptr cinfo, J_BUF_MODE pass_mode)
  163484. {
  163485. my_prep_ptr prep = (my_prep_ptr) cinfo->prep;
  163486. if (pass_mode != JBUF_PASS_THRU)
  163487. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  163488. /* Initialize total-height counter for detecting bottom of image */
  163489. prep->rows_to_go = cinfo->image_height;
  163490. /* Mark the conversion buffer empty */
  163491. prep->next_buf_row = 0;
  163492. #ifdef CONTEXT_ROWS_SUPPORTED
  163493. /* Preset additional state variables for context mode.
  163494. * These aren't used in non-context mode, so we needn't test which mode.
  163495. */
  163496. prep->this_row_group = 0;
  163497. /* Set next_buf_stop to stop after two row groups have been read in. */
  163498. prep->next_buf_stop = 2 * cinfo->max_v_samp_factor;
  163499. #endif
  163500. }
  163501. /*
  163502. * Expand an image vertically from height input_rows to height output_rows,
  163503. * by duplicating the bottom row.
  163504. */
  163505. LOCAL(void)
  163506. expand_bottom_edge (JSAMPARRAY image_data, JDIMENSION num_cols,
  163507. int input_rows, int output_rows)
  163508. {
  163509. register int row;
  163510. for (row = input_rows; row < output_rows; row++) {
  163511. jcopy_sample_rows(image_data, input_rows-1, image_data, row,
  163512. 1, num_cols);
  163513. }
  163514. }
  163515. /*
  163516. * Process some data in the simple no-context case.
  163517. *
  163518. * Preprocessor output data is counted in "row groups". A row group
  163519. * is defined to be v_samp_factor sample rows of each component.
  163520. * Downsampling will produce this much data from each max_v_samp_factor
  163521. * input rows.
  163522. */
  163523. METHODDEF(void)
  163524. pre_process_data (j_compress_ptr cinfo,
  163525. JSAMPARRAY input_buf, JDIMENSION *in_row_ctr,
  163526. JDIMENSION in_rows_avail,
  163527. JSAMPIMAGE output_buf, JDIMENSION *out_row_group_ctr,
  163528. JDIMENSION out_row_groups_avail)
  163529. {
  163530. my_prep_ptr prep = (my_prep_ptr) cinfo->prep;
  163531. int numrows, ci;
  163532. JDIMENSION inrows;
  163533. jpeg_component_info * compptr;
  163534. while (*in_row_ctr < in_rows_avail &&
  163535. *out_row_group_ctr < out_row_groups_avail) {
  163536. /* Do color conversion to fill the conversion buffer. */
  163537. inrows = in_rows_avail - *in_row_ctr;
  163538. numrows = cinfo->max_v_samp_factor - prep->next_buf_row;
  163539. numrows = (int) MIN((JDIMENSION) numrows, inrows);
  163540. (*cinfo->cconvert->color_convert) (cinfo, input_buf + *in_row_ctr,
  163541. prep->color_buf,
  163542. (JDIMENSION) prep->next_buf_row,
  163543. numrows);
  163544. *in_row_ctr += numrows;
  163545. prep->next_buf_row += numrows;
  163546. prep->rows_to_go -= numrows;
  163547. /* If at bottom of image, pad to fill the conversion buffer. */
  163548. if (prep->rows_to_go == 0 &&
  163549. prep->next_buf_row < cinfo->max_v_samp_factor) {
  163550. for (ci = 0; ci < cinfo->num_components; ci++) {
  163551. expand_bottom_edge(prep->color_buf[ci], cinfo->image_width,
  163552. prep->next_buf_row, cinfo->max_v_samp_factor);
  163553. }
  163554. prep->next_buf_row = cinfo->max_v_samp_factor;
  163555. }
  163556. /* If we've filled the conversion buffer, empty it. */
  163557. if (prep->next_buf_row == cinfo->max_v_samp_factor) {
  163558. (*cinfo->downsample->downsample) (cinfo,
  163559. prep->color_buf, (JDIMENSION) 0,
  163560. output_buf, *out_row_group_ctr);
  163561. prep->next_buf_row = 0;
  163562. (*out_row_group_ctr)++;
  163563. }
  163564. /* If at bottom of image, pad the output to a full iMCU height.
  163565. * Note we assume the caller is providing a one-iMCU-height output buffer!
  163566. */
  163567. if (prep->rows_to_go == 0 &&
  163568. *out_row_group_ctr < out_row_groups_avail) {
  163569. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  163570. ci++, compptr++) {
  163571. expand_bottom_edge(output_buf[ci],
  163572. compptr->width_in_blocks * DCTSIZE,
  163573. (int) (*out_row_group_ctr * compptr->v_samp_factor),
  163574. (int) (out_row_groups_avail * compptr->v_samp_factor));
  163575. }
  163576. *out_row_group_ctr = out_row_groups_avail;
  163577. break; /* can exit outer loop without test */
  163578. }
  163579. }
  163580. }
  163581. #ifdef CONTEXT_ROWS_SUPPORTED
  163582. /*
  163583. * Process some data in the context case.
  163584. */
  163585. METHODDEF(void)
  163586. pre_process_context (j_compress_ptr cinfo,
  163587. JSAMPARRAY input_buf, JDIMENSION *in_row_ctr,
  163588. JDIMENSION in_rows_avail,
  163589. JSAMPIMAGE output_buf, JDIMENSION *out_row_group_ctr,
  163590. JDIMENSION out_row_groups_avail)
  163591. {
  163592. my_prep_ptr prep = (my_prep_ptr) cinfo->prep;
  163593. int numrows, ci;
  163594. int buf_height = cinfo->max_v_samp_factor * 3;
  163595. JDIMENSION inrows;
  163596. while (*out_row_group_ctr < out_row_groups_avail) {
  163597. if (*in_row_ctr < in_rows_avail) {
  163598. /* Do color conversion to fill the conversion buffer. */
  163599. inrows = in_rows_avail - *in_row_ctr;
  163600. numrows = prep->next_buf_stop - prep->next_buf_row;
  163601. numrows = (int) MIN((JDIMENSION) numrows, inrows);
  163602. (*cinfo->cconvert->color_convert) (cinfo, input_buf + *in_row_ctr,
  163603. prep->color_buf,
  163604. (JDIMENSION) prep->next_buf_row,
  163605. numrows);
  163606. /* Pad at top of image, if first time through */
  163607. if (prep->rows_to_go == cinfo->image_height) {
  163608. for (ci = 0; ci < cinfo->num_components; ci++) {
  163609. int row;
  163610. for (row = 1; row <= cinfo->max_v_samp_factor; row++) {
  163611. jcopy_sample_rows(prep->color_buf[ci], 0,
  163612. prep->color_buf[ci], -row,
  163613. 1, cinfo->image_width);
  163614. }
  163615. }
  163616. }
  163617. *in_row_ctr += numrows;
  163618. prep->next_buf_row += numrows;
  163619. prep->rows_to_go -= numrows;
  163620. } else {
  163621. /* Return for more data, unless we are at the bottom of the image. */
  163622. if (prep->rows_to_go != 0)
  163623. break;
  163624. /* When at bottom of image, pad to fill the conversion buffer. */
  163625. if (prep->next_buf_row < prep->next_buf_stop) {
  163626. for (ci = 0; ci < cinfo->num_components; ci++) {
  163627. expand_bottom_edge(prep->color_buf[ci], cinfo->image_width,
  163628. prep->next_buf_row, prep->next_buf_stop);
  163629. }
  163630. prep->next_buf_row = prep->next_buf_stop;
  163631. }
  163632. }
  163633. /* If we've gotten enough data, downsample a row group. */
  163634. if (prep->next_buf_row == prep->next_buf_stop) {
  163635. (*cinfo->downsample->downsample) (cinfo,
  163636. prep->color_buf,
  163637. (JDIMENSION) prep->this_row_group,
  163638. output_buf, *out_row_group_ctr);
  163639. (*out_row_group_ctr)++;
  163640. /* Advance pointers with wraparound as necessary. */
  163641. prep->this_row_group += cinfo->max_v_samp_factor;
  163642. if (prep->this_row_group >= buf_height)
  163643. prep->this_row_group = 0;
  163644. if (prep->next_buf_row >= buf_height)
  163645. prep->next_buf_row = 0;
  163646. prep->next_buf_stop = prep->next_buf_row + cinfo->max_v_samp_factor;
  163647. }
  163648. }
  163649. }
  163650. /*
  163651. * Create the wrapped-around downsampling input buffer needed for context mode.
  163652. */
  163653. LOCAL(void)
  163654. create_context_buffer (j_compress_ptr cinfo)
  163655. {
  163656. my_prep_ptr prep = (my_prep_ptr) cinfo->prep;
  163657. int rgroup_height = cinfo->max_v_samp_factor;
  163658. int ci, i;
  163659. jpeg_component_info * compptr;
  163660. JSAMPARRAY true_buffer, fake_buffer;
  163661. /* Grab enough space for fake row pointers for all the components;
  163662. * we need five row groups' worth of pointers for each component.
  163663. */
  163664. fake_buffer = (JSAMPARRAY)
  163665. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  163666. (cinfo->num_components * 5 * rgroup_height) *
  163667. SIZEOF(JSAMPROW));
  163668. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  163669. ci++, compptr++) {
  163670. /* Allocate the actual buffer space (3 row groups) for this component.
  163671. * We make the buffer wide enough to allow the downsampler to edge-expand
  163672. * horizontally within the buffer, if it so chooses.
  163673. */
  163674. true_buffer = (*cinfo->mem->alloc_sarray)
  163675. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  163676. (JDIMENSION) (((long) compptr->width_in_blocks * DCTSIZE *
  163677. cinfo->max_h_samp_factor) / compptr->h_samp_factor),
  163678. (JDIMENSION) (3 * rgroup_height));
  163679. /* Copy true buffer row pointers into the middle of the fake row array */
  163680. MEMCOPY(fake_buffer + rgroup_height, true_buffer,
  163681. 3 * rgroup_height * SIZEOF(JSAMPROW));
  163682. /* Fill in the above and below wraparound pointers */
  163683. for (i = 0; i < rgroup_height; i++) {
  163684. fake_buffer[i] = true_buffer[2 * rgroup_height + i];
  163685. fake_buffer[4 * rgroup_height + i] = true_buffer[i];
  163686. }
  163687. prep->color_buf[ci] = fake_buffer + rgroup_height;
  163688. fake_buffer += 5 * rgroup_height; /* point to space for next component */
  163689. }
  163690. }
  163691. #endif /* CONTEXT_ROWS_SUPPORTED */
  163692. /*
  163693. * Initialize preprocessing controller.
  163694. */
  163695. GLOBAL(void)
  163696. jinit_c_prep_controller (j_compress_ptr cinfo, boolean need_full_buffer)
  163697. {
  163698. my_prep_ptr prep;
  163699. int ci;
  163700. jpeg_component_info * compptr;
  163701. if (need_full_buffer) /* safety check */
  163702. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  163703. prep = (my_prep_ptr)
  163704. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  163705. SIZEOF(my_prep_controller));
  163706. cinfo->prep = (struct jpeg_c_prep_controller *) prep;
  163707. prep->pub.start_pass = start_pass_prep;
  163708. /* Allocate the color conversion buffer.
  163709. * We make the buffer wide enough to allow the downsampler to edge-expand
  163710. * horizontally within the buffer, if it so chooses.
  163711. */
  163712. if (cinfo->downsample->need_context_rows) {
  163713. /* Set up to provide context rows */
  163714. #ifdef CONTEXT_ROWS_SUPPORTED
  163715. prep->pub.pre_process_data = pre_process_context;
  163716. create_context_buffer(cinfo);
  163717. #else
  163718. ERREXIT(cinfo, JERR_NOT_COMPILED);
  163719. #endif
  163720. } else {
  163721. /* No context, just make it tall enough for one row group */
  163722. prep->pub.pre_process_data = pre_process_data;
  163723. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  163724. ci++, compptr++) {
  163725. prep->color_buf[ci] = (*cinfo->mem->alloc_sarray)
  163726. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  163727. (JDIMENSION) (((long) compptr->width_in_blocks * DCTSIZE *
  163728. cinfo->max_h_samp_factor) / compptr->h_samp_factor),
  163729. (JDIMENSION) cinfo->max_v_samp_factor);
  163730. }
  163731. }
  163732. }
  163733. /*** End of inlined file: jcprepct.c ***/
  163734. /*** Start of inlined file: jcsample.c ***/
  163735. #define JPEG_INTERNALS
  163736. /* Pointer to routine to downsample a single component */
  163737. typedef JMETHOD(void, downsample1_ptr,
  163738. (j_compress_ptr cinfo, jpeg_component_info * compptr,
  163739. JSAMPARRAY input_data, JSAMPARRAY output_data));
  163740. /* Private subobject */
  163741. typedef struct {
  163742. struct jpeg_downsampler pub; /* public fields */
  163743. /* Downsampling method pointers, one per component */
  163744. downsample1_ptr methods[MAX_COMPONENTS];
  163745. } my_downsampler;
  163746. typedef my_downsampler * my_downsample_ptr;
  163747. /*
  163748. * Initialize for a downsampling pass.
  163749. */
  163750. METHODDEF(void)
  163751. start_pass_downsample (j_compress_ptr)
  163752. {
  163753. /* no work for now */
  163754. }
  163755. /*
  163756. * Expand a component horizontally from width input_cols to width output_cols,
  163757. * by duplicating the rightmost samples.
  163758. */
  163759. LOCAL(void)
  163760. expand_right_edge (JSAMPARRAY image_data, int num_rows,
  163761. JDIMENSION input_cols, JDIMENSION output_cols)
  163762. {
  163763. register JSAMPROW ptr;
  163764. register JSAMPLE pixval;
  163765. register int count;
  163766. int row;
  163767. int numcols = (int) (output_cols - input_cols);
  163768. if (numcols > 0) {
  163769. for (row = 0; row < num_rows; row++) {
  163770. ptr = image_data[row] + input_cols;
  163771. pixval = ptr[-1]; /* don't need GETJSAMPLE() here */
  163772. for (count = numcols; count > 0; count--)
  163773. *ptr++ = pixval;
  163774. }
  163775. }
  163776. }
  163777. /*
  163778. * Do downsampling for a whole row group (all components).
  163779. *
  163780. * In this version we simply downsample each component independently.
  163781. */
  163782. METHODDEF(void)
  163783. sep_downsample (j_compress_ptr cinfo,
  163784. JSAMPIMAGE input_buf, JDIMENSION in_row_index,
  163785. JSAMPIMAGE output_buf, JDIMENSION out_row_group_index)
  163786. {
  163787. my_downsample_ptr downsample = (my_downsample_ptr) cinfo->downsample;
  163788. int ci;
  163789. jpeg_component_info * compptr;
  163790. JSAMPARRAY in_ptr, out_ptr;
  163791. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  163792. ci++, compptr++) {
  163793. in_ptr = input_buf[ci] + in_row_index;
  163794. out_ptr = output_buf[ci] + (out_row_group_index * compptr->v_samp_factor);
  163795. (*downsample->methods[ci]) (cinfo, compptr, in_ptr, out_ptr);
  163796. }
  163797. }
  163798. /*
  163799. * Downsample pixel values of a single component.
  163800. * One row group is processed per call.
  163801. * This version handles arbitrary integral sampling ratios, without smoothing.
  163802. * Note that this version is not actually used for customary sampling ratios.
  163803. */
  163804. METHODDEF(void)
  163805. int_downsample (j_compress_ptr cinfo, jpeg_component_info * compptr,
  163806. JSAMPARRAY input_data, JSAMPARRAY output_data)
  163807. {
  163808. int inrow, outrow, h_expand, v_expand, numpix, numpix2, h, v;
  163809. JDIMENSION outcol, outcol_h; /* outcol_h == outcol*h_expand */
  163810. JDIMENSION output_cols = compptr->width_in_blocks * DCTSIZE;
  163811. JSAMPROW inptr, outptr;
  163812. INT32 outvalue;
  163813. h_expand = cinfo->max_h_samp_factor / compptr->h_samp_factor;
  163814. v_expand = cinfo->max_v_samp_factor / compptr->v_samp_factor;
  163815. numpix = h_expand * v_expand;
  163816. numpix2 = numpix/2;
  163817. /* Expand input data enough to let all the output samples be generated
  163818. * by the standard loop. Special-casing padded output would be more
  163819. * efficient.
  163820. */
  163821. expand_right_edge(input_data, cinfo->max_v_samp_factor,
  163822. cinfo->image_width, output_cols * h_expand);
  163823. inrow = 0;
  163824. for (outrow = 0; outrow < compptr->v_samp_factor; outrow++) {
  163825. outptr = output_data[outrow];
  163826. for (outcol = 0, outcol_h = 0; outcol < output_cols;
  163827. outcol++, outcol_h += h_expand) {
  163828. outvalue = 0;
  163829. for (v = 0; v < v_expand; v++) {
  163830. inptr = input_data[inrow+v] + outcol_h;
  163831. for (h = 0; h < h_expand; h++) {
  163832. outvalue += (INT32) GETJSAMPLE(*inptr++);
  163833. }
  163834. }
  163835. *outptr++ = (JSAMPLE) ((outvalue + numpix2) / numpix);
  163836. }
  163837. inrow += v_expand;
  163838. }
  163839. }
  163840. /*
  163841. * Downsample pixel values of a single component.
  163842. * This version handles the special case of a full-size component,
  163843. * without smoothing.
  163844. */
  163845. METHODDEF(void)
  163846. fullsize_downsample (j_compress_ptr cinfo, jpeg_component_info * compptr,
  163847. JSAMPARRAY input_data, JSAMPARRAY output_data)
  163848. {
  163849. /* Copy the data */
  163850. jcopy_sample_rows(input_data, 0, output_data, 0,
  163851. cinfo->max_v_samp_factor, cinfo->image_width);
  163852. /* Edge-expand */
  163853. expand_right_edge(output_data, cinfo->max_v_samp_factor,
  163854. cinfo->image_width, compptr->width_in_blocks * DCTSIZE);
  163855. }
  163856. /*
  163857. * Downsample pixel values of a single component.
  163858. * This version handles the common case of 2:1 horizontal and 1:1 vertical,
  163859. * without smoothing.
  163860. *
  163861. * A note about the "bias" calculations: when rounding fractional values to
  163862. * integer, we do not want to always round 0.5 up to the next integer.
  163863. * If we did that, we'd introduce a noticeable bias towards larger values.
  163864. * Instead, this code is arranged so that 0.5 will be rounded up or down at
  163865. * alternate pixel locations (a simple ordered dither pattern).
  163866. */
  163867. METHODDEF(void)
  163868. h2v1_downsample (j_compress_ptr cinfo, jpeg_component_info * compptr,
  163869. JSAMPARRAY input_data, JSAMPARRAY output_data)
  163870. {
  163871. int outrow;
  163872. JDIMENSION outcol;
  163873. JDIMENSION output_cols = compptr->width_in_blocks * DCTSIZE;
  163874. register JSAMPROW inptr, outptr;
  163875. register int bias;
  163876. /* Expand input data enough to let all the output samples be generated
  163877. * by the standard loop. Special-casing padded output would be more
  163878. * efficient.
  163879. */
  163880. expand_right_edge(input_data, cinfo->max_v_samp_factor,
  163881. cinfo->image_width, output_cols * 2);
  163882. for (outrow = 0; outrow < compptr->v_samp_factor; outrow++) {
  163883. outptr = output_data[outrow];
  163884. inptr = input_data[outrow];
  163885. bias = 0; /* bias = 0,1,0,1,... for successive samples */
  163886. for (outcol = 0; outcol < output_cols; outcol++) {
  163887. *outptr++ = (JSAMPLE) ((GETJSAMPLE(*inptr) + GETJSAMPLE(inptr[1])
  163888. + bias) >> 1);
  163889. bias ^= 1; /* 0=>1, 1=>0 */
  163890. inptr += 2;
  163891. }
  163892. }
  163893. }
  163894. /*
  163895. * Downsample pixel values of a single component.
  163896. * This version handles the standard case of 2:1 horizontal and 2:1 vertical,
  163897. * without smoothing.
  163898. */
  163899. METHODDEF(void)
  163900. h2v2_downsample (j_compress_ptr cinfo, jpeg_component_info * compptr,
  163901. JSAMPARRAY input_data, JSAMPARRAY output_data)
  163902. {
  163903. int inrow, outrow;
  163904. JDIMENSION outcol;
  163905. JDIMENSION output_cols = compptr->width_in_blocks * DCTSIZE;
  163906. register JSAMPROW inptr0, inptr1, outptr;
  163907. register int bias;
  163908. /* Expand input data enough to let all the output samples be generated
  163909. * by the standard loop. Special-casing padded output would be more
  163910. * efficient.
  163911. */
  163912. expand_right_edge(input_data, cinfo->max_v_samp_factor,
  163913. cinfo->image_width, output_cols * 2);
  163914. inrow = 0;
  163915. for (outrow = 0; outrow < compptr->v_samp_factor; outrow++) {
  163916. outptr = output_data[outrow];
  163917. inptr0 = input_data[inrow];
  163918. inptr1 = input_data[inrow+1];
  163919. bias = 1; /* bias = 1,2,1,2,... for successive samples */
  163920. for (outcol = 0; outcol < output_cols; outcol++) {
  163921. *outptr++ = (JSAMPLE) ((GETJSAMPLE(*inptr0) + GETJSAMPLE(inptr0[1]) +
  163922. GETJSAMPLE(*inptr1) + GETJSAMPLE(inptr1[1])
  163923. + bias) >> 2);
  163924. bias ^= 3; /* 1=>2, 2=>1 */
  163925. inptr0 += 2; inptr1 += 2;
  163926. }
  163927. inrow += 2;
  163928. }
  163929. }
  163930. #ifdef INPUT_SMOOTHING_SUPPORTED
  163931. /*
  163932. * Downsample pixel values of a single component.
  163933. * This version handles the standard case of 2:1 horizontal and 2:1 vertical,
  163934. * with smoothing. One row of context is required.
  163935. */
  163936. METHODDEF(void)
  163937. h2v2_smooth_downsample (j_compress_ptr cinfo, jpeg_component_info * compptr,
  163938. JSAMPARRAY input_data, JSAMPARRAY output_data)
  163939. {
  163940. int inrow, outrow;
  163941. JDIMENSION colctr;
  163942. JDIMENSION output_cols = compptr->width_in_blocks * DCTSIZE;
  163943. register JSAMPROW inptr0, inptr1, above_ptr, below_ptr, outptr;
  163944. INT32 membersum, neighsum, memberscale, neighscale;
  163945. /* Expand input data enough to let all the output samples be generated
  163946. * by the standard loop. Special-casing padded output would be more
  163947. * efficient.
  163948. */
  163949. expand_right_edge(input_data - 1, cinfo->max_v_samp_factor + 2,
  163950. cinfo->image_width, output_cols * 2);
  163951. /* We don't bother to form the individual "smoothed" input pixel values;
  163952. * we can directly compute the output which is the average of the four
  163953. * smoothed values. Each of the four member pixels contributes a fraction
  163954. * (1-8*SF) to its own smoothed image and a fraction SF to each of the three
  163955. * other smoothed pixels, therefore a total fraction (1-5*SF)/4 to the final
  163956. * output. The four corner-adjacent neighbor pixels contribute a fraction
  163957. * SF to just one smoothed pixel, or SF/4 to the final output; while the
  163958. * eight edge-adjacent neighbors contribute SF to each of two smoothed
  163959. * pixels, or SF/2 overall. In order to use integer arithmetic, these
  163960. * factors are scaled by 2^16 = 65536.
  163961. * Also recall that SF = smoothing_factor / 1024.
  163962. */
  163963. memberscale = 16384 - cinfo->smoothing_factor * 80; /* scaled (1-5*SF)/4 */
  163964. neighscale = cinfo->smoothing_factor * 16; /* scaled SF/4 */
  163965. inrow = 0;
  163966. for (outrow = 0; outrow < compptr->v_samp_factor; outrow++) {
  163967. outptr = output_data[outrow];
  163968. inptr0 = input_data[inrow];
  163969. inptr1 = input_data[inrow+1];
  163970. above_ptr = input_data[inrow-1];
  163971. below_ptr = input_data[inrow+2];
  163972. /* Special case for first column: pretend column -1 is same as column 0 */
  163973. membersum = GETJSAMPLE(*inptr0) + GETJSAMPLE(inptr0[1]) +
  163974. GETJSAMPLE(*inptr1) + GETJSAMPLE(inptr1[1]);
  163975. neighsum = GETJSAMPLE(*above_ptr) + GETJSAMPLE(above_ptr[1]) +
  163976. GETJSAMPLE(*below_ptr) + GETJSAMPLE(below_ptr[1]) +
  163977. GETJSAMPLE(*inptr0) + GETJSAMPLE(inptr0[2]) +
  163978. GETJSAMPLE(*inptr1) + GETJSAMPLE(inptr1[2]);
  163979. neighsum += neighsum;
  163980. neighsum += GETJSAMPLE(*above_ptr) + GETJSAMPLE(above_ptr[2]) +
  163981. GETJSAMPLE(*below_ptr) + GETJSAMPLE(below_ptr[2]);
  163982. membersum = membersum * memberscale + neighsum * neighscale;
  163983. *outptr++ = (JSAMPLE) ((membersum + 32768) >> 16);
  163984. inptr0 += 2; inptr1 += 2; above_ptr += 2; below_ptr += 2;
  163985. for (colctr = output_cols - 2; colctr > 0; colctr--) {
  163986. /* sum of pixels directly mapped to this output element */
  163987. membersum = GETJSAMPLE(*inptr0) + GETJSAMPLE(inptr0[1]) +
  163988. GETJSAMPLE(*inptr1) + GETJSAMPLE(inptr1[1]);
  163989. /* sum of edge-neighbor pixels */
  163990. neighsum = GETJSAMPLE(*above_ptr) + GETJSAMPLE(above_ptr[1]) +
  163991. GETJSAMPLE(*below_ptr) + GETJSAMPLE(below_ptr[1]) +
  163992. GETJSAMPLE(inptr0[-1]) + GETJSAMPLE(inptr0[2]) +
  163993. GETJSAMPLE(inptr1[-1]) + GETJSAMPLE(inptr1[2]);
  163994. /* The edge-neighbors count twice as much as corner-neighbors */
  163995. neighsum += neighsum;
  163996. /* Add in the corner-neighbors */
  163997. neighsum += GETJSAMPLE(above_ptr[-1]) + GETJSAMPLE(above_ptr[2]) +
  163998. GETJSAMPLE(below_ptr[-1]) + GETJSAMPLE(below_ptr[2]);
  163999. /* form final output scaled up by 2^16 */
  164000. membersum = membersum * memberscale + neighsum * neighscale;
  164001. /* round, descale and output it */
  164002. *outptr++ = (JSAMPLE) ((membersum + 32768) >> 16);
  164003. inptr0 += 2; inptr1 += 2; above_ptr += 2; below_ptr += 2;
  164004. }
  164005. /* Special case for last column */
  164006. membersum = GETJSAMPLE(*inptr0) + GETJSAMPLE(inptr0[1]) +
  164007. GETJSAMPLE(*inptr1) + GETJSAMPLE(inptr1[1]);
  164008. neighsum = GETJSAMPLE(*above_ptr) + GETJSAMPLE(above_ptr[1]) +
  164009. GETJSAMPLE(*below_ptr) + GETJSAMPLE(below_ptr[1]) +
  164010. GETJSAMPLE(inptr0[-1]) + GETJSAMPLE(inptr0[1]) +
  164011. GETJSAMPLE(inptr1[-1]) + GETJSAMPLE(inptr1[1]);
  164012. neighsum += neighsum;
  164013. neighsum += GETJSAMPLE(above_ptr[-1]) + GETJSAMPLE(above_ptr[1]) +
  164014. GETJSAMPLE(below_ptr[-1]) + GETJSAMPLE(below_ptr[1]);
  164015. membersum = membersum * memberscale + neighsum * neighscale;
  164016. *outptr = (JSAMPLE) ((membersum + 32768) >> 16);
  164017. inrow += 2;
  164018. }
  164019. }
  164020. /*
  164021. * Downsample pixel values of a single component.
  164022. * This version handles the special case of a full-size component,
  164023. * with smoothing. One row of context is required.
  164024. */
  164025. METHODDEF(void)
  164026. fullsize_smooth_downsample (j_compress_ptr cinfo, jpeg_component_info *compptr,
  164027. JSAMPARRAY input_data, JSAMPARRAY output_data)
  164028. {
  164029. int outrow;
  164030. JDIMENSION colctr;
  164031. JDIMENSION output_cols = compptr->width_in_blocks * DCTSIZE;
  164032. register JSAMPROW inptr, above_ptr, below_ptr, outptr;
  164033. INT32 membersum, neighsum, memberscale, neighscale;
  164034. int colsum, lastcolsum, nextcolsum;
  164035. /* Expand input data enough to let all the output samples be generated
  164036. * by the standard loop. Special-casing padded output would be more
  164037. * efficient.
  164038. */
  164039. expand_right_edge(input_data - 1, cinfo->max_v_samp_factor + 2,
  164040. cinfo->image_width, output_cols);
  164041. /* Each of the eight neighbor pixels contributes a fraction SF to the
  164042. * smoothed pixel, while the main pixel contributes (1-8*SF). In order
  164043. * to use integer arithmetic, these factors are multiplied by 2^16 = 65536.
  164044. * Also recall that SF = smoothing_factor / 1024.
  164045. */
  164046. memberscale = 65536L - cinfo->smoothing_factor * 512L; /* scaled 1-8*SF */
  164047. neighscale = cinfo->smoothing_factor * 64; /* scaled SF */
  164048. for (outrow = 0; outrow < compptr->v_samp_factor; outrow++) {
  164049. outptr = output_data[outrow];
  164050. inptr = input_data[outrow];
  164051. above_ptr = input_data[outrow-1];
  164052. below_ptr = input_data[outrow+1];
  164053. /* Special case for first column */
  164054. colsum = GETJSAMPLE(*above_ptr++) + GETJSAMPLE(*below_ptr++) +
  164055. GETJSAMPLE(*inptr);
  164056. membersum = GETJSAMPLE(*inptr++);
  164057. nextcolsum = GETJSAMPLE(*above_ptr) + GETJSAMPLE(*below_ptr) +
  164058. GETJSAMPLE(*inptr);
  164059. neighsum = colsum + (colsum - membersum) + nextcolsum;
  164060. membersum = membersum * memberscale + neighsum * neighscale;
  164061. *outptr++ = (JSAMPLE) ((membersum + 32768) >> 16);
  164062. lastcolsum = colsum; colsum = nextcolsum;
  164063. for (colctr = output_cols - 2; colctr > 0; colctr--) {
  164064. membersum = GETJSAMPLE(*inptr++);
  164065. above_ptr++; below_ptr++;
  164066. nextcolsum = GETJSAMPLE(*above_ptr) + GETJSAMPLE(*below_ptr) +
  164067. GETJSAMPLE(*inptr);
  164068. neighsum = lastcolsum + (colsum - membersum) + nextcolsum;
  164069. membersum = membersum * memberscale + neighsum * neighscale;
  164070. *outptr++ = (JSAMPLE) ((membersum + 32768) >> 16);
  164071. lastcolsum = colsum; colsum = nextcolsum;
  164072. }
  164073. /* Special case for last column */
  164074. membersum = GETJSAMPLE(*inptr);
  164075. neighsum = lastcolsum + (colsum - membersum) + colsum;
  164076. membersum = membersum * memberscale + neighsum * neighscale;
  164077. *outptr = (JSAMPLE) ((membersum + 32768) >> 16);
  164078. }
  164079. }
  164080. #endif /* INPUT_SMOOTHING_SUPPORTED */
  164081. /*
  164082. * Module initialization routine for downsampling.
  164083. * Note that we must select a routine for each component.
  164084. */
  164085. GLOBAL(void)
  164086. jinit_downsampler (j_compress_ptr cinfo)
  164087. {
  164088. my_downsample_ptr downsample;
  164089. int ci;
  164090. jpeg_component_info * compptr;
  164091. boolean smoothok = TRUE;
  164092. downsample = (my_downsample_ptr)
  164093. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  164094. SIZEOF(my_downsampler));
  164095. cinfo->downsample = (struct jpeg_downsampler *) downsample;
  164096. downsample->pub.start_pass = start_pass_downsample;
  164097. downsample->pub.downsample = sep_downsample;
  164098. downsample->pub.need_context_rows = FALSE;
  164099. if (cinfo->CCIR601_sampling)
  164100. ERREXIT(cinfo, JERR_CCIR601_NOTIMPL);
  164101. /* Verify we can handle the sampling factors, and set up method pointers */
  164102. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  164103. ci++, compptr++) {
  164104. if (compptr->h_samp_factor == cinfo->max_h_samp_factor &&
  164105. compptr->v_samp_factor == cinfo->max_v_samp_factor) {
  164106. #ifdef INPUT_SMOOTHING_SUPPORTED
  164107. if (cinfo->smoothing_factor) {
  164108. downsample->methods[ci] = fullsize_smooth_downsample;
  164109. downsample->pub.need_context_rows = TRUE;
  164110. } else
  164111. #endif
  164112. downsample->methods[ci] = fullsize_downsample;
  164113. } else if (compptr->h_samp_factor * 2 == cinfo->max_h_samp_factor &&
  164114. compptr->v_samp_factor == cinfo->max_v_samp_factor) {
  164115. smoothok = FALSE;
  164116. downsample->methods[ci] = h2v1_downsample;
  164117. } else if (compptr->h_samp_factor * 2 == cinfo->max_h_samp_factor &&
  164118. compptr->v_samp_factor * 2 == cinfo->max_v_samp_factor) {
  164119. #ifdef INPUT_SMOOTHING_SUPPORTED
  164120. if (cinfo->smoothing_factor) {
  164121. downsample->methods[ci] = h2v2_smooth_downsample;
  164122. downsample->pub.need_context_rows = TRUE;
  164123. } else
  164124. #endif
  164125. downsample->methods[ci] = h2v2_downsample;
  164126. } else if ((cinfo->max_h_samp_factor % compptr->h_samp_factor) == 0 &&
  164127. (cinfo->max_v_samp_factor % compptr->v_samp_factor) == 0) {
  164128. smoothok = FALSE;
  164129. downsample->methods[ci] = int_downsample;
  164130. } else
  164131. ERREXIT(cinfo, JERR_FRACT_SAMPLE_NOTIMPL);
  164132. }
  164133. #ifdef INPUT_SMOOTHING_SUPPORTED
  164134. if (cinfo->smoothing_factor && !smoothok)
  164135. TRACEMS(cinfo, 0, JTRC_SMOOTH_NOTIMPL);
  164136. #endif
  164137. }
  164138. /*** End of inlined file: jcsample.c ***/
  164139. /*** Start of inlined file: jctrans.c ***/
  164140. #define JPEG_INTERNALS
  164141. /* Forward declarations */
  164142. LOCAL(void) transencode_master_selection
  164143. JPP((j_compress_ptr cinfo, jvirt_barray_ptr * coef_arrays));
  164144. LOCAL(void) transencode_coef_controller
  164145. JPP((j_compress_ptr cinfo, jvirt_barray_ptr * coef_arrays));
  164146. /*
  164147. * Compression initialization for writing raw-coefficient data.
  164148. * Before calling this, all parameters and a data destination must be set up.
  164149. * Call jpeg_finish_compress() to actually write the data.
  164150. *
  164151. * The number of passed virtual arrays must match cinfo->num_components.
  164152. * Note that the virtual arrays need not be filled or even realized at
  164153. * the time write_coefficients is called; indeed, if the virtual arrays
  164154. * were requested from this compression object's memory manager, they
  164155. * typically will be realized during this routine and filled afterwards.
  164156. */
  164157. GLOBAL(void)
  164158. jpeg_write_coefficients (j_compress_ptr cinfo, jvirt_barray_ptr * coef_arrays)
  164159. {
  164160. if (cinfo->global_state != CSTATE_START)
  164161. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  164162. /* Mark all tables to be written */
  164163. jpeg_suppress_tables(cinfo, FALSE);
  164164. /* (Re)initialize error mgr and destination modules */
  164165. (*cinfo->err->reset_error_mgr) ((j_common_ptr) cinfo);
  164166. (*cinfo->dest->init_destination) (cinfo);
  164167. /* Perform master selection of active modules */
  164168. transencode_master_selection(cinfo, coef_arrays);
  164169. /* Wait for jpeg_finish_compress() call */
  164170. cinfo->next_scanline = 0; /* so jpeg_write_marker works */
  164171. cinfo->global_state = CSTATE_WRCOEFS;
  164172. }
  164173. /*
  164174. * Initialize the compression object with default parameters,
  164175. * then copy from the source object all parameters needed for lossless
  164176. * transcoding. Parameters that can be varied without loss (such as
  164177. * scan script and Huffman optimization) are left in their default states.
  164178. */
  164179. GLOBAL(void)
  164180. jpeg_copy_critical_parameters (j_decompress_ptr srcinfo,
  164181. j_compress_ptr dstinfo)
  164182. {
  164183. JQUANT_TBL ** qtblptr;
  164184. jpeg_component_info *incomp, *outcomp;
  164185. JQUANT_TBL *c_quant, *slot_quant;
  164186. int tblno, ci, coefi;
  164187. /* Safety check to ensure start_compress not called yet. */
  164188. if (dstinfo->global_state != CSTATE_START)
  164189. ERREXIT1(dstinfo, JERR_BAD_STATE, dstinfo->global_state);
  164190. /* Copy fundamental image dimensions */
  164191. dstinfo->image_width = srcinfo->image_width;
  164192. dstinfo->image_height = srcinfo->image_height;
  164193. dstinfo->input_components = srcinfo->num_components;
  164194. dstinfo->in_color_space = srcinfo->jpeg_color_space;
  164195. /* Initialize all parameters to default values */
  164196. jpeg_set_defaults(dstinfo);
  164197. /* jpeg_set_defaults may choose wrong colorspace, eg YCbCr if input is RGB.
  164198. * Fix it to get the right header markers for the image colorspace.
  164199. */
  164200. jpeg_set_colorspace(dstinfo, srcinfo->jpeg_color_space);
  164201. dstinfo->data_precision = srcinfo->data_precision;
  164202. dstinfo->CCIR601_sampling = srcinfo->CCIR601_sampling;
  164203. /* Copy the source's quantization tables. */
  164204. for (tblno = 0; tblno < NUM_QUANT_TBLS; tblno++) {
  164205. if (srcinfo->quant_tbl_ptrs[tblno] != NULL) {
  164206. qtblptr = & dstinfo->quant_tbl_ptrs[tblno];
  164207. if (*qtblptr == NULL)
  164208. *qtblptr = jpeg_alloc_quant_table((j_common_ptr) dstinfo);
  164209. MEMCOPY((*qtblptr)->quantval,
  164210. srcinfo->quant_tbl_ptrs[tblno]->quantval,
  164211. SIZEOF((*qtblptr)->quantval));
  164212. (*qtblptr)->sent_table = FALSE;
  164213. }
  164214. }
  164215. /* Copy the source's per-component info.
  164216. * Note we assume jpeg_set_defaults has allocated the dest comp_info array.
  164217. */
  164218. dstinfo->num_components = srcinfo->num_components;
  164219. if (dstinfo->num_components < 1 || dstinfo->num_components > MAX_COMPONENTS)
  164220. ERREXIT2(dstinfo, JERR_COMPONENT_COUNT, dstinfo->num_components,
  164221. MAX_COMPONENTS);
  164222. for (ci = 0, incomp = srcinfo->comp_info, outcomp = dstinfo->comp_info;
  164223. ci < dstinfo->num_components; ci++, incomp++, outcomp++) {
  164224. outcomp->component_id = incomp->component_id;
  164225. outcomp->h_samp_factor = incomp->h_samp_factor;
  164226. outcomp->v_samp_factor = incomp->v_samp_factor;
  164227. outcomp->quant_tbl_no = incomp->quant_tbl_no;
  164228. /* Make sure saved quantization table for component matches the qtable
  164229. * slot. If not, the input file re-used this qtable slot.
  164230. * IJG encoder currently cannot duplicate this.
  164231. */
  164232. tblno = outcomp->quant_tbl_no;
  164233. if (tblno < 0 || tblno >= NUM_QUANT_TBLS ||
  164234. srcinfo->quant_tbl_ptrs[tblno] == NULL)
  164235. ERREXIT1(dstinfo, JERR_NO_QUANT_TABLE, tblno);
  164236. slot_quant = srcinfo->quant_tbl_ptrs[tblno];
  164237. c_quant = incomp->quant_table;
  164238. if (c_quant != NULL) {
  164239. for (coefi = 0; coefi < DCTSIZE2; coefi++) {
  164240. if (c_quant->quantval[coefi] != slot_quant->quantval[coefi])
  164241. ERREXIT1(dstinfo, JERR_MISMATCHED_QUANT_TABLE, tblno);
  164242. }
  164243. }
  164244. /* Note: we do not copy the source's Huffman table assignments;
  164245. * instead we rely on jpeg_set_colorspace to have made a suitable choice.
  164246. */
  164247. }
  164248. /* Also copy JFIF version and resolution information, if available.
  164249. * Strictly speaking this isn't "critical" info, but it's nearly
  164250. * always appropriate to copy it if available. In particular,
  164251. * if the application chooses to copy JFIF 1.02 extension markers from
  164252. * the source file, we need to copy the version to make sure we don't
  164253. * emit a file that has 1.02 extensions but a claimed version of 1.01.
  164254. * We will *not*, however, copy version info from mislabeled "2.01" files.
  164255. */
  164256. if (srcinfo->saw_JFIF_marker) {
  164257. if (srcinfo->JFIF_major_version == 1) {
  164258. dstinfo->JFIF_major_version = srcinfo->JFIF_major_version;
  164259. dstinfo->JFIF_minor_version = srcinfo->JFIF_minor_version;
  164260. }
  164261. dstinfo->density_unit = srcinfo->density_unit;
  164262. dstinfo->X_density = srcinfo->X_density;
  164263. dstinfo->Y_density = srcinfo->Y_density;
  164264. }
  164265. }
  164266. /*
  164267. * Master selection of compression modules for transcoding.
  164268. * This substitutes for jcinit.c's initialization of the full compressor.
  164269. */
  164270. LOCAL(void)
  164271. transencode_master_selection (j_compress_ptr cinfo,
  164272. jvirt_barray_ptr * coef_arrays)
  164273. {
  164274. /* Although we don't actually use input_components for transcoding,
  164275. * jcmaster.c's initial_setup will complain if input_components is 0.
  164276. */
  164277. cinfo->input_components = 1;
  164278. /* Initialize master control (includes parameter checking/processing) */
  164279. jinit_c_master_control(cinfo, TRUE /* transcode only */);
  164280. /* Entropy encoding: either Huffman or arithmetic coding. */
  164281. if (cinfo->arith_code) {
  164282. ERREXIT(cinfo, JERR_ARITH_NOTIMPL);
  164283. } else {
  164284. if (cinfo->progressive_mode) {
  164285. #ifdef C_PROGRESSIVE_SUPPORTED
  164286. jinit_phuff_encoder(cinfo);
  164287. #else
  164288. ERREXIT(cinfo, JERR_NOT_COMPILED);
  164289. #endif
  164290. } else
  164291. jinit_huff_encoder(cinfo);
  164292. }
  164293. /* We need a special coefficient buffer controller. */
  164294. transencode_coef_controller(cinfo, coef_arrays);
  164295. jinit_marker_writer(cinfo);
  164296. /* We can now tell the memory manager to allocate virtual arrays. */
  164297. (*cinfo->mem->realize_virt_arrays) ((j_common_ptr) cinfo);
  164298. /* Write the datastream header (SOI, JFIF) immediately.
  164299. * Frame and scan headers are postponed till later.
  164300. * This lets application insert special markers after the SOI.
  164301. */
  164302. (*cinfo->marker->write_file_header) (cinfo);
  164303. }
  164304. /*
  164305. * The rest of this file is a special implementation of the coefficient
  164306. * buffer controller. This is similar to jccoefct.c, but it handles only
  164307. * output from presupplied virtual arrays. Furthermore, we generate any
  164308. * dummy padding blocks on-the-fly rather than expecting them to be present
  164309. * in the arrays.
  164310. */
  164311. /* Private buffer controller object */
  164312. typedef struct {
  164313. struct jpeg_c_coef_controller pub; /* public fields */
  164314. JDIMENSION iMCU_row_num; /* iMCU row # within image */
  164315. JDIMENSION mcu_ctr; /* counts MCUs processed in current row */
  164316. int MCU_vert_offset; /* counts MCU rows within iMCU row */
  164317. int MCU_rows_per_iMCU_row; /* number of such rows needed */
  164318. /* Virtual block array for each component. */
  164319. jvirt_barray_ptr * whole_image;
  164320. /* Workspace for constructing dummy blocks at right/bottom edges. */
  164321. JBLOCKROW dummy_buffer[C_MAX_BLOCKS_IN_MCU];
  164322. } my_coef_controller2;
  164323. typedef my_coef_controller2 * my_coef_ptr2;
  164324. LOCAL(void)
  164325. start_iMCU_row2 (j_compress_ptr cinfo)
  164326. /* Reset within-iMCU-row counters for a new row */
  164327. {
  164328. my_coef_ptr2 coef = (my_coef_ptr2) cinfo->coef;
  164329. /* In an interleaved scan, an MCU row is the same as an iMCU row.
  164330. * In a noninterleaved scan, an iMCU row has v_samp_factor MCU rows.
  164331. * But at the bottom of the image, process only what's left.
  164332. */
  164333. if (cinfo->comps_in_scan > 1) {
  164334. coef->MCU_rows_per_iMCU_row = 1;
  164335. } else {
  164336. if (coef->iMCU_row_num < (cinfo->total_iMCU_rows-1))
  164337. coef->MCU_rows_per_iMCU_row = cinfo->cur_comp_info[0]->v_samp_factor;
  164338. else
  164339. coef->MCU_rows_per_iMCU_row = cinfo->cur_comp_info[0]->last_row_height;
  164340. }
  164341. coef->mcu_ctr = 0;
  164342. coef->MCU_vert_offset = 0;
  164343. }
  164344. /*
  164345. * Initialize for a processing pass.
  164346. */
  164347. METHODDEF(void)
  164348. start_pass_coef2 (j_compress_ptr cinfo, J_BUF_MODE pass_mode)
  164349. {
  164350. my_coef_ptr2 coef = (my_coef_ptr2) cinfo->coef;
  164351. if (pass_mode != JBUF_CRANK_DEST)
  164352. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  164353. coef->iMCU_row_num = 0;
  164354. start_iMCU_row2(cinfo);
  164355. }
  164356. /*
  164357. * Process some data.
  164358. * We process the equivalent of one fully interleaved MCU row ("iMCU" row)
  164359. * per call, ie, v_samp_factor block rows for each component in the scan.
  164360. * The data is obtained from the virtual arrays and fed to the entropy coder.
  164361. * Returns TRUE if the iMCU row is completed, FALSE if suspended.
  164362. *
  164363. * NB: input_buf is ignored; it is likely to be a NULL pointer.
  164364. */
  164365. METHODDEF(boolean)
  164366. compress_output2 (j_compress_ptr cinfo, JSAMPIMAGE)
  164367. {
  164368. my_coef_ptr2 coef = (my_coef_ptr2) cinfo->coef;
  164369. JDIMENSION MCU_col_num; /* index of current MCU within row */
  164370. JDIMENSION last_MCU_col = cinfo->MCUs_per_row - 1;
  164371. JDIMENSION last_iMCU_row = cinfo->total_iMCU_rows - 1;
  164372. int blkn, ci, xindex, yindex, yoffset, blockcnt;
  164373. JDIMENSION start_col;
  164374. JBLOCKARRAY buffer[MAX_COMPS_IN_SCAN];
  164375. JBLOCKROW MCU_buffer[C_MAX_BLOCKS_IN_MCU];
  164376. JBLOCKROW buffer_ptr;
  164377. jpeg_component_info *compptr;
  164378. /* Align the virtual buffers for the components used in this scan. */
  164379. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  164380. compptr = cinfo->cur_comp_info[ci];
  164381. buffer[ci] = (*cinfo->mem->access_virt_barray)
  164382. ((j_common_ptr) cinfo, coef->whole_image[compptr->component_index],
  164383. coef->iMCU_row_num * compptr->v_samp_factor,
  164384. (JDIMENSION) compptr->v_samp_factor, FALSE);
  164385. }
  164386. /* Loop to process one whole iMCU row */
  164387. for (yoffset = coef->MCU_vert_offset; yoffset < coef->MCU_rows_per_iMCU_row;
  164388. yoffset++) {
  164389. for (MCU_col_num = coef->mcu_ctr; MCU_col_num < cinfo->MCUs_per_row;
  164390. MCU_col_num++) {
  164391. /* Construct list of pointers to DCT blocks belonging to this MCU */
  164392. blkn = 0; /* index of current DCT block within MCU */
  164393. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  164394. compptr = cinfo->cur_comp_info[ci];
  164395. start_col = MCU_col_num * compptr->MCU_width;
  164396. blockcnt = (MCU_col_num < last_MCU_col) ? compptr->MCU_width
  164397. : compptr->last_col_width;
  164398. for (yindex = 0; yindex < compptr->MCU_height; yindex++) {
  164399. if (coef->iMCU_row_num < last_iMCU_row ||
  164400. yindex+yoffset < compptr->last_row_height) {
  164401. /* Fill in pointers to real blocks in this row */
  164402. buffer_ptr = buffer[ci][yindex+yoffset] + start_col;
  164403. for (xindex = 0; xindex < blockcnt; xindex++)
  164404. MCU_buffer[blkn++] = buffer_ptr++;
  164405. } else {
  164406. /* At bottom of image, need a whole row of dummy blocks */
  164407. xindex = 0;
  164408. }
  164409. /* Fill in any dummy blocks needed in this row.
  164410. * Dummy blocks are filled in the same way as in jccoefct.c:
  164411. * all zeroes in the AC entries, DC entries equal to previous
  164412. * block's DC value. The init routine has already zeroed the
  164413. * AC entries, so we need only set the DC entries correctly.
  164414. */
  164415. for (; xindex < compptr->MCU_width; xindex++) {
  164416. MCU_buffer[blkn] = coef->dummy_buffer[blkn];
  164417. MCU_buffer[blkn][0][0] = MCU_buffer[blkn-1][0][0];
  164418. blkn++;
  164419. }
  164420. }
  164421. }
  164422. /* Try to write the MCU. */
  164423. if (! (*cinfo->entropy->encode_mcu) (cinfo, MCU_buffer)) {
  164424. /* Suspension forced; update state counters and exit */
  164425. coef->MCU_vert_offset = yoffset;
  164426. coef->mcu_ctr = MCU_col_num;
  164427. return FALSE;
  164428. }
  164429. }
  164430. /* Completed an MCU row, but perhaps not an iMCU row */
  164431. coef->mcu_ctr = 0;
  164432. }
  164433. /* Completed the iMCU row, advance counters for next one */
  164434. coef->iMCU_row_num++;
  164435. start_iMCU_row2(cinfo);
  164436. return TRUE;
  164437. }
  164438. /*
  164439. * Initialize coefficient buffer controller.
  164440. *
  164441. * Each passed coefficient array must be the right size for that
  164442. * coefficient: width_in_blocks wide and height_in_blocks high,
  164443. * with unitheight at least v_samp_factor.
  164444. */
  164445. LOCAL(void)
  164446. transencode_coef_controller (j_compress_ptr cinfo,
  164447. jvirt_barray_ptr * coef_arrays)
  164448. {
  164449. my_coef_ptr2 coef;
  164450. JBLOCKROW buffer;
  164451. int i;
  164452. coef = (my_coef_ptr2)
  164453. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  164454. SIZEOF(my_coef_controller2));
  164455. cinfo->coef = (struct jpeg_c_coef_controller *) coef;
  164456. coef->pub.start_pass = start_pass_coef2;
  164457. coef->pub.compress_data = compress_output2;
  164458. /* Save pointer to virtual arrays */
  164459. coef->whole_image = coef_arrays;
  164460. /* Allocate and pre-zero space for dummy DCT blocks. */
  164461. buffer = (JBLOCKROW)
  164462. (*cinfo->mem->alloc_large) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  164463. C_MAX_BLOCKS_IN_MCU * SIZEOF(JBLOCK));
  164464. jzero_far((void FAR *) buffer, C_MAX_BLOCKS_IN_MCU * SIZEOF(JBLOCK));
  164465. for (i = 0; i < C_MAX_BLOCKS_IN_MCU; i++) {
  164466. coef->dummy_buffer[i] = buffer + i;
  164467. }
  164468. }
  164469. /*** End of inlined file: jctrans.c ***/
  164470. /*** Start of inlined file: jdapistd.c ***/
  164471. #define JPEG_INTERNALS
  164472. /* Forward declarations */
  164473. LOCAL(boolean) output_pass_setup JPP((j_decompress_ptr cinfo));
  164474. /*
  164475. * Decompression initialization.
  164476. * jpeg_read_header must be completed before calling this.
  164477. *
  164478. * If a multipass operating mode was selected, this will do all but the
  164479. * last pass, and thus may take a great deal of time.
  164480. *
  164481. * Returns FALSE if suspended. The return value need be inspected only if
  164482. * a suspending data source is used.
  164483. */
  164484. GLOBAL(boolean)
  164485. jpeg_start_decompress (j_decompress_ptr cinfo)
  164486. {
  164487. if (cinfo->global_state == DSTATE_READY) {
  164488. /* First call: initialize master control, select active modules */
  164489. jinit_master_decompress(cinfo);
  164490. if (cinfo->buffered_image) {
  164491. /* No more work here; expecting jpeg_start_output next */
  164492. cinfo->global_state = DSTATE_BUFIMAGE;
  164493. return TRUE;
  164494. }
  164495. cinfo->global_state = DSTATE_PRELOAD;
  164496. }
  164497. if (cinfo->global_state == DSTATE_PRELOAD) {
  164498. /* If file has multiple scans, absorb them all into the coef buffer */
  164499. if (cinfo->inputctl->has_multiple_scans) {
  164500. #ifdef D_MULTISCAN_FILES_SUPPORTED
  164501. for (;;) {
  164502. int retcode;
  164503. /* Call progress monitor hook if present */
  164504. if (cinfo->progress != NULL)
  164505. (*cinfo->progress->progress_monitor) ((j_common_ptr) cinfo);
  164506. /* Absorb some more input */
  164507. retcode = (*cinfo->inputctl->consume_input) (cinfo);
  164508. if (retcode == JPEG_SUSPENDED)
  164509. return FALSE;
  164510. if (retcode == JPEG_REACHED_EOI)
  164511. break;
  164512. /* Advance progress counter if appropriate */
  164513. if (cinfo->progress != NULL &&
  164514. (retcode == JPEG_ROW_COMPLETED || retcode == JPEG_REACHED_SOS)) {
  164515. if (++cinfo->progress->pass_counter >= cinfo->progress->pass_limit) {
  164516. /* jdmaster underestimated number of scans; ratchet up one scan */
  164517. cinfo->progress->pass_limit += (long) cinfo->total_iMCU_rows;
  164518. }
  164519. }
  164520. }
  164521. #else
  164522. ERREXIT(cinfo, JERR_NOT_COMPILED);
  164523. #endif /* D_MULTISCAN_FILES_SUPPORTED */
  164524. }
  164525. cinfo->output_scan_number = cinfo->input_scan_number;
  164526. } else if (cinfo->global_state != DSTATE_PRESCAN)
  164527. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  164528. /* Perform any dummy output passes, and set up for the final pass */
  164529. return output_pass_setup(cinfo);
  164530. }
  164531. /*
  164532. * Set up for an output pass, and perform any dummy pass(es) needed.
  164533. * Common subroutine for jpeg_start_decompress and jpeg_start_output.
  164534. * Entry: global_state = DSTATE_PRESCAN only if previously suspended.
  164535. * Exit: If done, returns TRUE and sets global_state for proper output mode.
  164536. * If suspended, returns FALSE and sets global_state = DSTATE_PRESCAN.
  164537. */
  164538. LOCAL(boolean)
  164539. output_pass_setup (j_decompress_ptr cinfo)
  164540. {
  164541. if (cinfo->global_state != DSTATE_PRESCAN) {
  164542. /* First call: do pass setup */
  164543. (*cinfo->master->prepare_for_output_pass) (cinfo);
  164544. cinfo->output_scanline = 0;
  164545. cinfo->global_state = DSTATE_PRESCAN;
  164546. }
  164547. /* Loop over any required dummy passes */
  164548. while (cinfo->master->is_dummy_pass) {
  164549. #ifdef QUANT_2PASS_SUPPORTED
  164550. /* Crank through the dummy pass */
  164551. while (cinfo->output_scanline < cinfo->output_height) {
  164552. JDIMENSION last_scanline;
  164553. /* Call progress monitor hook if present */
  164554. if (cinfo->progress != NULL) {
  164555. cinfo->progress->pass_counter = (long) cinfo->output_scanline;
  164556. cinfo->progress->pass_limit = (long) cinfo->output_height;
  164557. (*cinfo->progress->progress_monitor) ((j_common_ptr) cinfo);
  164558. }
  164559. /* Process some data */
  164560. last_scanline = cinfo->output_scanline;
  164561. (*cinfo->main->process_data) (cinfo, (JSAMPARRAY) NULL,
  164562. &cinfo->output_scanline, (JDIMENSION) 0);
  164563. if (cinfo->output_scanline == last_scanline)
  164564. return FALSE; /* No progress made, must suspend */
  164565. }
  164566. /* Finish up dummy pass, and set up for another one */
  164567. (*cinfo->master->finish_output_pass) (cinfo);
  164568. (*cinfo->master->prepare_for_output_pass) (cinfo);
  164569. cinfo->output_scanline = 0;
  164570. #else
  164571. ERREXIT(cinfo, JERR_NOT_COMPILED);
  164572. #endif /* QUANT_2PASS_SUPPORTED */
  164573. }
  164574. /* Ready for application to drive output pass through
  164575. * jpeg_read_scanlines or jpeg_read_raw_data.
  164576. */
  164577. cinfo->global_state = cinfo->raw_data_out ? DSTATE_RAW_OK : DSTATE_SCANNING;
  164578. return TRUE;
  164579. }
  164580. /*
  164581. * Read some scanlines of data from the JPEG decompressor.
  164582. *
  164583. * The return value will be the number of lines actually read.
  164584. * This may be less than the number requested in several cases,
  164585. * including bottom of image, data source suspension, and operating
  164586. * modes that emit multiple scanlines at a time.
  164587. *
  164588. * Note: we warn about excess calls to jpeg_read_scanlines() since
  164589. * this likely signals an application programmer error. However,
  164590. * an oversize buffer (max_lines > scanlines remaining) is not an error.
  164591. */
  164592. GLOBAL(JDIMENSION)
  164593. jpeg_read_scanlines (j_decompress_ptr cinfo, JSAMPARRAY scanlines,
  164594. JDIMENSION max_lines)
  164595. {
  164596. JDIMENSION row_ctr;
  164597. if (cinfo->global_state != DSTATE_SCANNING)
  164598. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  164599. if (cinfo->output_scanline >= cinfo->output_height) {
  164600. WARNMS(cinfo, JWRN_TOO_MUCH_DATA);
  164601. return 0;
  164602. }
  164603. /* Call progress monitor hook if present */
  164604. if (cinfo->progress != NULL) {
  164605. cinfo->progress->pass_counter = (long) cinfo->output_scanline;
  164606. cinfo->progress->pass_limit = (long) cinfo->output_height;
  164607. (*cinfo->progress->progress_monitor) ((j_common_ptr) cinfo);
  164608. }
  164609. /* Process some data */
  164610. row_ctr = 0;
  164611. (*cinfo->main->process_data) (cinfo, scanlines, &row_ctr, max_lines);
  164612. cinfo->output_scanline += row_ctr;
  164613. return row_ctr;
  164614. }
  164615. /*
  164616. * Alternate entry point to read raw data.
  164617. * Processes exactly one iMCU row per call, unless suspended.
  164618. */
  164619. GLOBAL(JDIMENSION)
  164620. jpeg_read_raw_data (j_decompress_ptr cinfo, JSAMPIMAGE data,
  164621. JDIMENSION max_lines)
  164622. {
  164623. JDIMENSION lines_per_iMCU_row;
  164624. if (cinfo->global_state != DSTATE_RAW_OK)
  164625. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  164626. if (cinfo->output_scanline >= cinfo->output_height) {
  164627. WARNMS(cinfo, JWRN_TOO_MUCH_DATA);
  164628. return 0;
  164629. }
  164630. /* Call progress monitor hook if present */
  164631. if (cinfo->progress != NULL) {
  164632. cinfo->progress->pass_counter = (long) cinfo->output_scanline;
  164633. cinfo->progress->pass_limit = (long) cinfo->output_height;
  164634. (*cinfo->progress->progress_monitor) ((j_common_ptr) cinfo);
  164635. }
  164636. /* Verify that at least one iMCU row can be returned. */
  164637. lines_per_iMCU_row = cinfo->max_v_samp_factor * cinfo->min_DCT_scaled_size;
  164638. if (max_lines < lines_per_iMCU_row)
  164639. ERREXIT(cinfo, JERR_BUFFER_SIZE);
  164640. /* Decompress directly into user's buffer. */
  164641. if (! (*cinfo->coef->decompress_data) (cinfo, data))
  164642. return 0; /* suspension forced, can do nothing more */
  164643. /* OK, we processed one iMCU row. */
  164644. cinfo->output_scanline += lines_per_iMCU_row;
  164645. return lines_per_iMCU_row;
  164646. }
  164647. /* Additional entry points for buffered-image mode. */
  164648. #ifdef D_MULTISCAN_FILES_SUPPORTED
  164649. /*
  164650. * Initialize for an output pass in buffered-image mode.
  164651. */
  164652. GLOBAL(boolean)
  164653. jpeg_start_output (j_decompress_ptr cinfo, int scan_number)
  164654. {
  164655. if (cinfo->global_state != DSTATE_BUFIMAGE &&
  164656. cinfo->global_state != DSTATE_PRESCAN)
  164657. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  164658. /* Limit scan number to valid range */
  164659. if (scan_number <= 0)
  164660. scan_number = 1;
  164661. if (cinfo->inputctl->eoi_reached &&
  164662. scan_number > cinfo->input_scan_number)
  164663. scan_number = cinfo->input_scan_number;
  164664. cinfo->output_scan_number = scan_number;
  164665. /* Perform any dummy output passes, and set up for the real pass */
  164666. return output_pass_setup(cinfo);
  164667. }
  164668. /*
  164669. * Finish up after an output pass in buffered-image mode.
  164670. *
  164671. * Returns FALSE if suspended. The return value need be inspected only if
  164672. * a suspending data source is used.
  164673. */
  164674. GLOBAL(boolean)
  164675. jpeg_finish_output (j_decompress_ptr cinfo)
  164676. {
  164677. if ((cinfo->global_state == DSTATE_SCANNING ||
  164678. cinfo->global_state == DSTATE_RAW_OK) && cinfo->buffered_image) {
  164679. /* Terminate this pass. */
  164680. /* We do not require the whole pass to have been completed. */
  164681. (*cinfo->master->finish_output_pass) (cinfo);
  164682. cinfo->global_state = DSTATE_BUFPOST;
  164683. } else if (cinfo->global_state != DSTATE_BUFPOST) {
  164684. /* BUFPOST = repeat call after a suspension, anything else is error */
  164685. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  164686. }
  164687. /* Read markers looking for SOS or EOI */
  164688. while (cinfo->input_scan_number <= cinfo->output_scan_number &&
  164689. ! cinfo->inputctl->eoi_reached) {
  164690. if ((*cinfo->inputctl->consume_input) (cinfo) == JPEG_SUSPENDED)
  164691. return FALSE; /* Suspend, come back later */
  164692. }
  164693. cinfo->global_state = DSTATE_BUFIMAGE;
  164694. return TRUE;
  164695. }
  164696. #endif /* D_MULTISCAN_FILES_SUPPORTED */
  164697. /*** End of inlined file: jdapistd.c ***/
  164698. /*** Start of inlined file: jdapimin.c ***/
  164699. #define JPEG_INTERNALS
  164700. /*
  164701. * Initialization of a JPEG decompression object.
  164702. * The error manager must already be set up (in case memory manager fails).
  164703. */
  164704. GLOBAL(void)
  164705. jpeg_CreateDecompress (j_decompress_ptr cinfo, int version, size_t structsize)
  164706. {
  164707. int i;
  164708. /* Guard against version mismatches between library and caller. */
  164709. cinfo->mem = NULL; /* so jpeg_destroy knows mem mgr not called */
  164710. if (version != JPEG_LIB_VERSION)
  164711. ERREXIT2(cinfo, JERR_BAD_LIB_VERSION, JPEG_LIB_VERSION, version);
  164712. if (structsize != SIZEOF(struct jpeg_decompress_struct))
  164713. ERREXIT2(cinfo, JERR_BAD_STRUCT_SIZE,
  164714. (int) SIZEOF(struct jpeg_decompress_struct), (int) structsize);
  164715. /* For debugging purposes, we zero the whole master structure.
  164716. * But the application has already set the err pointer, and may have set
  164717. * client_data, so we have to save and restore those fields.
  164718. * Note: if application hasn't set client_data, tools like Purify may
  164719. * complain here.
  164720. */
  164721. {
  164722. struct jpeg_error_mgr * err = cinfo->err;
  164723. void * client_data = cinfo->client_data; /* ignore Purify complaint here */
  164724. MEMZERO(cinfo, SIZEOF(struct jpeg_decompress_struct));
  164725. cinfo->err = err;
  164726. cinfo->client_data = client_data;
  164727. }
  164728. cinfo->is_decompressor = TRUE;
  164729. /* Initialize a memory manager instance for this object */
  164730. jinit_memory_mgr((j_common_ptr) cinfo);
  164731. /* Zero out pointers to permanent structures. */
  164732. cinfo->progress = NULL;
  164733. cinfo->src = NULL;
  164734. for (i = 0; i < NUM_QUANT_TBLS; i++)
  164735. cinfo->quant_tbl_ptrs[i] = NULL;
  164736. for (i = 0; i < NUM_HUFF_TBLS; i++) {
  164737. cinfo->dc_huff_tbl_ptrs[i] = NULL;
  164738. cinfo->ac_huff_tbl_ptrs[i] = NULL;
  164739. }
  164740. /* Initialize marker processor so application can override methods
  164741. * for COM, APPn markers before calling jpeg_read_header.
  164742. */
  164743. cinfo->marker_list = NULL;
  164744. jinit_marker_reader(cinfo);
  164745. /* And initialize the overall input controller. */
  164746. jinit_input_controller(cinfo);
  164747. /* OK, I'm ready */
  164748. cinfo->global_state = DSTATE_START;
  164749. }
  164750. /*
  164751. * Destruction of a JPEG decompression object
  164752. */
  164753. GLOBAL(void)
  164754. jpeg_destroy_decompress (j_decompress_ptr cinfo)
  164755. {
  164756. jpeg_destroy((j_common_ptr) cinfo); /* use common routine */
  164757. }
  164758. /*
  164759. * Abort processing of a JPEG decompression operation,
  164760. * but don't destroy the object itself.
  164761. */
  164762. GLOBAL(void)
  164763. jpeg_abort_decompress (j_decompress_ptr cinfo)
  164764. {
  164765. jpeg_abort((j_common_ptr) cinfo); /* use common routine */
  164766. }
  164767. /*
  164768. * Set default decompression parameters.
  164769. */
  164770. LOCAL(void)
  164771. default_decompress_parms (j_decompress_ptr cinfo)
  164772. {
  164773. /* Guess the input colorspace, and set output colorspace accordingly. */
  164774. /* (Wish JPEG committee had provided a real way to specify this...) */
  164775. /* Note application may override our guesses. */
  164776. switch (cinfo->num_components) {
  164777. case 1:
  164778. cinfo->jpeg_color_space = JCS_GRAYSCALE;
  164779. cinfo->out_color_space = JCS_GRAYSCALE;
  164780. break;
  164781. case 3:
  164782. if (cinfo->saw_JFIF_marker) {
  164783. cinfo->jpeg_color_space = JCS_YCbCr; /* JFIF implies YCbCr */
  164784. } else if (cinfo->saw_Adobe_marker) {
  164785. switch (cinfo->Adobe_transform) {
  164786. case 0:
  164787. cinfo->jpeg_color_space = JCS_RGB;
  164788. break;
  164789. case 1:
  164790. cinfo->jpeg_color_space = JCS_YCbCr;
  164791. break;
  164792. default:
  164793. WARNMS1(cinfo, JWRN_ADOBE_XFORM, cinfo->Adobe_transform);
  164794. cinfo->jpeg_color_space = JCS_YCbCr; /* assume it's YCbCr */
  164795. break;
  164796. }
  164797. } else {
  164798. /* Saw no special markers, try to guess from the component IDs */
  164799. int cid0 = cinfo->comp_info[0].component_id;
  164800. int cid1 = cinfo->comp_info[1].component_id;
  164801. int cid2 = cinfo->comp_info[2].component_id;
  164802. if (cid0 == 1 && cid1 == 2 && cid2 == 3)
  164803. cinfo->jpeg_color_space = JCS_YCbCr; /* assume JFIF w/out marker */
  164804. else if (cid0 == 82 && cid1 == 71 && cid2 == 66)
  164805. cinfo->jpeg_color_space = JCS_RGB; /* ASCII 'R', 'G', 'B' */
  164806. else {
  164807. TRACEMS3(cinfo, 1, JTRC_UNKNOWN_IDS, cid0, cid1, cid2);
  164808. cinfo->jpeg_color_space = JCS_YCbCr; /* assume it's YCbCr */
  164809. }
  164810. }
  164811. /* Always guess RGB is proper output colorspace. */
  164812. cinfo->out_color_space = JCS_RGB;
  164813. break;
  164814. case 4:
  164815. if (cinfo->saw_Adobe_marker) {
  164816. switch (cinfo->Adobe_transform) {
  164817. case 0:
  164818. cinfo->jpeg_color_space = JCS_CMYK;
  164819. break;
  164820. case 2:
  164821. cinfo->jpeg_color_space = JCS_YCCK;
  164822. break;
  164823. default:
  164824. WARNMS1(cinfo, JWRN_ADOBE_XFORM, cinfo->Adobe_transform);
  164825. cinfo->jpeg_color_space = JCS_YCCK; /* assume it's YCCK */
  164826. break;
  164827. }
  164828. } else {
  164829. /* No special markers, assume straight CMYK. */
  164830. cinfo->jpeg_color_space = JCS_CMYK;
  164831. }
  164832. cinfo->out_color_space = JCS_CMYK;
  164833. break;
  164834. default:
  164835. cinfo->jpeg_color_space = JCS_UNKNOWN;
  164836. cinfo->out_color_space = JCS_UNKNOWN;
  164837. break;
  164838. }
  164839. /* Set defaults for other decompression parameters. */
  164840. cinfo->scale_num = 1; /* 1:1 scaling */
  164841. cinfo->scale_denom = 1;
  164842. cinfo->output_gamma = 1.0;
  164843. cinfo->buffered_image = FALSE;
  164844. cinfo->raw_data_out = FALSE;
  164845. cinfo->dct_method = JDCT_DEFAULT;
  164846. cinfo->do_fancy_upsampling = TRUE;
  164847. cinfo->do_block_smoothing = TRUE;
  164848. cinfo->quantize_colors = FALSE;
  164849. /* We set these in case application only sets quantize_colors. */
  164850. cinfo->dither_mode = JDITHER_FS;
  164851. #ifdef QUANT_2PASS_SUPPORTED
  164852. cinfo->two_pass_quantize = TRUE;
  164853. #else
  164854. cinfo->two_pass_quantize = FALSE;
  164855. #endif
  164856. cinfo->desired_number_of_colors = 256;
  164857. cinfo->colormap = NULL;
  164858. /* Initialize for no mode change in buffered-image mode. */
  164859. cinfo->enable_1pass_quant = FALSE;
  164860. cinfo->enable_external_quant = FALSE;
  164861. cinfo->enable_2pass_quant = FALSE;
  164862. }
  164863. /*
  164864. * Decompression startup: read start of JPEG datastream to see what's there.
  164865. * Need only initialize JPEG object and supply a data source before calling.
  164866. *
  164867. * This routine will read as far as the first SOS marker (ie, actual start of
  164868. * compressed data), and will save all tables and parameters in the JPEG
  164869. * object. It will also initialize the decompression parameters to default
  164870. * values, and finally return JPEG_HEADER_OK. On return, the application may
  164871. * adjust the decompression parameters and then call jpeg_start_decompress.
  164872. * (Or, if the application only wanted to determine the image parameters,
  164873. * the data need not be decompressed. In that case, call jpeg_abort or
  164874. * jpeg_destroy to release any temporary space.)
  164875. * If an abbreviated (tables only) datastream is presented, the routine will
  164876. * return JPEG_HEADER_TABLES_ONLY upon reaching EOI. The application may then
  164877. * re-use the JPEG object to read the abbreviated image datastream(s).
  164878. * It is unnecessary (but OK) to call jpeg_abort in this case.
  164879. * The JPEG_SUSPENDED return code only occurs if the data source module
  164880. * requests suspension of the decompressor. In this case the application
  164881. * should load more source data and then re-call jpeg_read_header to resume
  164882. * processing.
  164883. * If a non-suspending data source is used and require_image is TRUE, then the
  164884. * return code need not be inspected since only JPEG_HEADER_OK is possible.
  164885. *
  164886. * This routine is now just a front end to jpeg_consume_input, with some
  164887. * extra error checking.
  164888. */
  164889. GLOBAL(int)
  164890. jpeg_read_header (j_decompress_ptr cinfo, boolean require_image)
  164891. {
  164892. int retcode;
  164893. if (cinfo->global_state != DSTATE_START &&
  164894. cinfo->global_state != DSTATE_INHEADER)
  164895. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  164896. retcode = jpeg_consume_input(cinfo);
  164897. switch (retcode) {
  164898. case JPEG_REACHED_SOS:
  164899. retcode = JPEG_HEADER_OK;
  164900. break;
  164901. case JPEG_REACHED_EOI:
  164902. if (require_image) /* Complain if application wanted an image */
  164903. ERREXIT(cinfo, JERR_NO_IMAGE);
  164904. /* Reset to start state; it would be safer to require the application to
  164905. * call jpeg_abort, but we can't change it now for compatibility reasons.
  164906. * A side effect is to free any temporary memory (there shouldn't be any).
  164907. */
  164908. jpeg_abort((j_common_ptr) cinfo); /* sets state = DSTATE_START */
  164909. retcode = JPEG_HEADER_TABLES_ONLY;
  164910. break;
  164911. case JPEG_SUSPENDED:
  164912. /* no work */
  164913. break;
  164914. }
  164915. return retcode;
  164916. }
  164917. /*
  164918. * Consume data in advance of what the decompressor requires.
  164919. * This can be called at any time once the decompressor object has
  164920. * been created and a data source has been set up.
  164921. *
  164922. * This routine is essentially a state machine that handles a couple
  164923. * of critical state-transition actions, namely initial setup and
  164924. * transition from header scanning to ready-for-start_decompress.
  164925. * All the actual input is done via the input controller's consume_input
  164926. * method.
  164927. */
  164928. GLOBAL(int)
  164929. jpeg_consume_input (j_decompress_ptr cinfo)
  164930. {
  164931. int retcode = JPEG_SUSPENDED;
  164932. /* NB: every possible DSTATE value should be listed in this switch */
  164933. switch (cinfo->global_state) {
  164934. case DSTATE_START:
  164935. /* Start-of-datastream actions: reset appropriate modules */
  164936. (*cinfo->inputctl->reset_input_controller) (cinfo);
  164937. /* Initialize application's data source module */
  164938. (*cinfo->src->init_source) (cinfo);
  164939. cinfo->global_state = DSTATE_INHEADER;
  164940. /*FALLTHROUGH*/
  164941. case DSTATE_INHEADER:
  164942. retcode = (*cinfo->inputctl->consume_input) (cinfo);
  164943. if (retcode == JPEG_REACHED_SOS) { /* Found SOS, prepare to decompress */
  164944. /* Set up default parameters based on header data */
  164945. default_decompress_parms(cinfo);
  164946. /* Set global state: ready for start_decompress */
  164947. cinfo->global_state = DSTATE_READY;
  164948. }
  164949. break;
  164950. case DSTATE_READY:
  164951. /* Can't advance past first SOS until start_decompress is called */
  164952. retcode = JPEG_REACHED_SOS;
  164953. break;
  164954. case DSTATE_PRELOAD:
  164955. case DSTATE_PRESCAN:
  164956. case DSTATE_SCANNING:
  164957. case DSTATE_RAW_OK:
  164958. case DSTATE_BUFIMAGE:
  164959. case DSTATE_BUFPOST:
  164960. case DSTATE_STOPPING:
  164961. retcode = (*cinfo->inputctl->consume_input) (cinfo);
  164962. break;
  164963. default:
  164964. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  164965. }
  164966. return retcode;
  164967. }
  164968. /*
  164969. * Have we finished reading the input file?
  164970. */
  164971. GLOBAL(boolean)
  164972. jpeg_input_complete (j_decompress_ptr cinfo)
  164973. {
  164974. /* Check for valid jpeg object */
  164975. if (cinfo->global_state < DSTATE_START ||
  164976. cinfo->global_state > DSTATE_STOPPING)
  164977. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  164978. return cinfo->inputctl->eoi_reached;
  164979. }
  164980. /*
  164981. * Is there more than one scan?
  164982. */
  164983. GLOBAL(boolean)
  164984. jpeg_has_multiple_scans (j_decompress_ptr cinfo)
  164985. {
  164986. /* Only valid after jpeg_read_header completes */
  164987. if (cinfo->global_state < DSTATE_READY ||
  164988. cinfo->global_state > DSTATE_STOPPING)
  164989. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  164990. return cinfo->inputctl->has_multiple_scans;
  164991. }
  164992. /*
  164993. * Finish JPEG decompression.
  164994. *
  164995. * This will normally just verify the file trailer and release temp storage.
  164996. *
  164997. * Returns FALSE if suspended. The return value need be inspected only if
  164998. * a suspending data source is used.
  164999. */
  165000. GLOBAL(boolean)
  165001. jpeg_finish_decompress (j_decompress_ptr cinfo)
  165002. {
  165003. if ((cinfo->global_state == DSTATE_SCANNING ||
  165004. cinfo->global_state == DSTATE_RAW_OK) && ! cinfo->buffered_image) {
  165005. /* Terminate final pass of non-buffered mode */
  165006. if (cinfo->output_scanline < cinfo->output_height)
  165007. ERREXIT(cinfo, JERR_TOO_LITTLE_DATA);
  165008. (*cinfo->master->finish_output_pass) (cinfo);
  165009. cinfo->global_state = DSTATE_STOPPING;
  165010. } else if (cinfo->global_state == DSTATE_BUFIMAGE) {
  165011. /* Finishing after a buffered-image operation */
  165012. cinfo->global_state = DSTATE_STOPPING;
  165013. } else if (cinfo->global_state != DSTATE_STOPPING) {
  165014. /* STOPPING = repeat call after a suspension, anything else is error */
  165015. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  165016. }
  165017. /* Read until EOI */
  165018. while (! cinfo->inputctl->eoi_reached) {
  165019. if ((*cinfo->inputctl->consume_input) (cinfo) == JPEG_SUSPENDED)
  165020. return FALSE; /* Suspend, come back later */
  165021. }
  165022. /* Do final cleanup */
  165023. (*cinfo->src->term_source) (cinfo);
  165024. /* We can use jpeg_abort to release memory and reset global_state */
  165025. jpeg_abort((j_common_ptr) cinfo);
  165026. return TRUE;
  165027. }
  165028. /*** End of inlined file: jdapimin.c ***/
  165029. /*** Start of inlined file: jdatasrc.c ***/
  165030. /* this is not a core library module, so it doesn't define JPEG_INTERNALS */
  165031. /*** Start of inlined file: jerror.h ***/
  165032. /*
  165033. * To define the enum list of message codes, include this file without
  165034. * defining macro JMESSAGE. To create a message string table, include it
  165035. * again with a suitable JMESSAGE definition (see jerror.c for an example).
  165036. */
  165037. #ifndef JMESSAGE
  165038. #ifndef JERROR_H
  165039. /* First time through, define the enum list */
  165040. #define JMAKE_ENUM_LIST
  165041. #else
  165042. /* Repeated inclusions of this file are no-ops unless JMESSAGE is defined */
  165043. #define JMESSAGE(code,string)
  165044. #endif /* JERROR_H */
  165045. #endif /* JMESSAGE */
  165046. #ifdef JMAKE_ENUM_LIST
  165047. typedef enum {
  165048. #define JMESSAGE(code,string) code ,
  165049. #endif /* JMAKE_ENUM_LIST */
  165050. JMESSAGE(JMSG_NOMESSAGE, "Bogus message code %d") /* Must be first entry! */
  165051. /* For maintenance convenience, list is alphabetical by message code name */
  165052. JMESSAGE(JERR_ARITH_NOTIMPL,
  165053. "Sorry, there are legal restrictions on arithmetic coding")
  165054. JMESSAGE(JERR_BAD_ALIGN_TYPE, "ALIGN_TYPE is wrong, please fix")
  165055. JMESSAGE(JERR_BAD_ALLOC_CHUNK, "MAX_ALLOC_CHUNK is wrong, please fix")
  165056. JMESSAGE(JERR_BAD_BUFFER_MODE, "Bogus buffer control mode")
  165057. JMESSAGE(JERR_BAD_COMPONENT_ID, "Invalid component ID %d in SOS")
  165058. JMESSAGE(JERR_BAD_DCT_COEF, "DCT coefficient out of range")
  165059. JMESSAGE(JERR_BAD_DCTSIZE, "IDCT output block size %d not supported")
  165060. JMESSAGE(JERR_BAD_HUFF_TABLE, "Bogus Huffman table definition")
  165061. JMESSAGE(JERR_BAD_IN_COLORSPACE, "Bogus input colorspace")
  165062. JMESSAGE(JERR_BAD_J_COLORSPACE, "Bogus JPEG colorspace")
  165063. JMESSAGE(JERR_BAD_LENGTH, "Bogus marker length")
  165064. JMESSAGE(JERR_BAD_LIB_VERSION,
  165065. "Wrong JPEG library version: library is %d, caller expects %d")
  165066. JMESSAGE(JERR_BAD_MCU_SIZE, "Sampling factors too large for interleaved scan")
  165067. JMESSAGE(JERR_BAD_POOL_ID, "Invalid memory pool code %d")
  165068. JMESSAGE(JERR_BAD_PRECISION, "Unsupported JPEG data precision %d")
  165069. JMESSAGE(JERR_BAD_PROGRESSION,
  165070. "Invalid progressive parameters Ss=%d Se=%d Ah=%d Al=%d")
  165071. JMESSAGE(JERR_BAD_PROG_SCRIPT,
  165072. "Invalid progressive parameters at scan script entry %d")
  165073. JMESSAGE(JERR_BAD_SAMPLING, "Bogus sampling factors")
  165074. JMESSAGE(JERR_BAD_SCAN_SCRIPT, "Invalid scan script at entry %d")
  165075. JMESSAGE(JERR_BAD_STATE, "Improper call to JPEG library in state %d")
  165076. JMESSAGE(JERR_BAD_STRUCT_SIZE,
  165077. "JPEG parameter struct mismatch: library thinks size is %u, caller expects %u")
  165078. JMESSAGE(JERR_BAD_VIRTUAL_ACCESS, "Bogus virtual array access")
  165079. JMESSAGE(JERR_BUFFER_SIZE, "Buffer passed to JPEG library is too small")
  165080. JMESSAGE(JERR_CANT_SUSPEND, "Suspension not allowed here")
  165081. JMESSAGE(JERR_CCIR601_NOTIMPL, "CCIR601 sampling not implemented yet")
  165082. JMESSAGE(JERR_COMPONENT_COUNT, "Too many color components: %d, max %d")
  165083. JMESSAGE(JERR_CONVERSION_NOTIMPL, "Unsupported color conversion request")
  165084. JMESSAGE(JERR_DAC_INDEX, "Bogus DAC index %d")
  165085. JMESSAGE(JERR_DAC_VALUE, "Bogus DAC value 0x%x")
  165086. JMESSAGE(JERR_DHT_INDEX, "Bogus DHT index %d")
  165087. JMESSAGE(JERR_DQT_INDEX, "Bogus DQT index %d")
  165088. JMESSAGE(JERR_EMPTY_IMAGE, "Empty JPEG image (DNL not supported)")
  165089. JMESSAGE(JERR_EMS_READ, "Read from EMS failed")
  165090. JMESSAGE(JERR_EMS_WRITE, "Write to EMS failed")
  165091. JMESSAGE(JERR_EOI_EXPECTED, "Didn't expect more than one scan")
  165092. JMESSAGE(JERR_FILE_READ, "Input file read error")
  165093. JMESSAGE(JERR_FILE_WRITE, "Output file write error --- out of disk space?")
  165094. JMESSAGE(JERR_FRACT_SAMPLE_NOTIMPL, "Fractional sampling not implemented yet")
  165095. JMESSAGE(JERR_HUFF_CLEN_OVERFLOW, "Huffman code size table overflow")
  165096. JMESSAGE(JERR_HUFF_MISSING_CODE, "Missing Huffman code table entry")
  165097. JMESSAGE(JERR_IMAGE_TOO_BIG, "Maximum supported image dimension is %u pixels")
  165098. JMESSAGE(JERR_INPUT_EMPTY, "Empty input file")
  165099. JMESSAGE(JERR_INPUT_EOF, "Premature end of input file")
  165100. JMESSAGE(JERR_MISMATCHED_QUANT_TABLE,
  165101. "Cannot transcode due to multiple use of quantization table %d")
  165102. JMESSAGE(JERR_MISSING_DATA, "Scan script does not transmit all data")
  165103. JMESSAGE(JERR_MODE_CHANGE, "Invalid color quantization mode change")
  165104. JMESSAGE(JERR_NOTIMPL, "Not implemented yet")
  165105. JMESSAGE(JERR_NOT_COMPILED, "Requested feature was omitted at compile time")
  165106. JMESSAGE(JERR_NO_BACKING_STORE, "Backing store not supported")
  165107. JMESSAGE(JERR_NO_HUFF_TABLE, "Huffman table 0x%02x was not defined")
  165108. JMESSAGE(JERR_NO_IMAGE, "JPEG datastream contains no image")
  165109. JMESSAGE(JERR_NO_QUANT_TABLE, "Quantization table 0x%02x was not defined")
  165110. JMESSAGE(JERR_NO_SOI, "Not a JPEG file: starts with 0x%02x 0x%02x")
  165111. JMESSAGE(JERR_OUT_OF_MEMORY, "Insufficient memory (case %d)")
  165112. JMESSAGE(JERR_QUANT_COMPONENTS,
  165113. "Cannot quantize more than %d color components")
  165114. JMESSAGE(JERR_QUANT_FEW_COLORS, "Cannot quantize to fewer than %d colors")
  165115. JMESSAGE(JERR_QUANT_MANY_COLORS, "Cannot quantize to more than %d colors")
  165116. JMESSAGE(JERR_SOF_DUPLICATE, "Invalid JPEG file structure: two SOF markers")
  165117. JMESSAGE(JERR_SOF_NO_SOS, "Invalid JPEG file structure: missing SOS marker")
  165118. JMESSAGE(JERR_SOF_UNSUPPORTED, "Unsupported JPEG process: SOF type 0x%02x")
  165119. JMESSAGE(JERR_SOI_DUPLICATE, "Invalid JPEG file structure: two SOI markers")
  165120. JMESSAGE(JERR_SOS_NO_SOF, "Invalid JPEG file structure: SOS before SOF")
  165121. JMESSAGE(JERR_TFILE_CREATE, "Failed to create temporary file %s")
  165122. JMESSAGE(JERR_TFILE_READ, "Read failed on temporary file")
  165123. JMESSAGE(JERR_TFILE_SEEK, "Seek failed on temporary file")
  165124. JMESSAGE(JERR_TFILE_WRITE,
  165125. "Write failed on temporary file --- out of disk space?")
  165126. JMESSAGE(JERR_TOO_LITTLE_DATA, "Application transferred too few scanlines")
  165127. JMESSAGE(JERR_UNKNOWN_MARKER, "Unsupported marker type 0x%02x")
  165128. JMESSAGE(JERR_VIRTUAL_BUG, "Virtual array controller messed up")
  165129. JMESSAGE(JERR_WIDTH_OVERFLOW, "Image too wide for this implementation")
  165130. JMESSAGE(JERR_XMS_READ, "Read from XMS failed")
  165131. JMESSAGE(JERR_XMS_WRITE, "Write to XMS failed")
  165132. JMESSAGE(JMSG_COPYRIGHT, JCOPYRIGHT)
  165133. JMESSAGE(JMSG_VERSION, JVERSION)
  165134. JMESSAGE(JTRC_16BIT_TABLES,
  165135. "Caution: quantization tables are too coarse for baseline JPEG")
  165136. JMESSAGE(JTRC_ADOBE,
  165137. "Adobe APP14 marker: version %d, flags 0x%04x 0x%04x, transform %d")
  165138. JMESSAGE(JTRC_APP0, "Unknown APP0 marker (not JFIF), length %u")
  165139. JMESSAGE(JTRC_APP14, "Unknown APP14 marker (not Adobe), length %u")
  165140. JMESSAGE(JTRC_DAC, "Define Arithmetic Table 0x%02x: 0x%02x")
  165141. JMESSAGE(JTRC_DHT, "Define Huffman Table 0x%02x")
  165142. JMESSAGE(JTRC_DQT, "Define Quantization Table %d precision %d")
  165143. JMESSAGE(JTRC_DRI, "Define Restart Interval %u")
  165144. JMESSAGE(JTRC_EMS_CLOSE, "Freed EMS handle %u")
  165145. JMESSAGE(JTRC_EMS_OPEN, "Obtained EMS handle %u")
  165146. JMESSAGE(JTRC_EOI, "End Of Image")
  165147. JMESSAGE(JTRC_HUFFBITS, " %3d %3d %3d %3d %3d %3d %3d %3d")
  165148. JMESSAGE(JTRC_JFIF, "JFIF APP0 marker: version %d.%02d, density %dx%d %d")
  165149. JMESSAGE(JTRC_JFIF_BADTHUMBNAILSIZE,
  165150. "Warning: thumbnail image size does not match data length %u")
  165151. JMESSAGE(JTRC_JFIF_EXTENSION,
  165152. "JFIF extension marker: type 0x%02x, length %u")
  165153. JMESSAGE(JTRC_JFIF_THUMBNAIL, " with %d x %d thumbnail image")
  165154. JMESSAGE(JTRC_MISC_MARKER, "Miscellaneous marker 0x%02x, length %u")
  165155. JMESSAGE(JTRC_PARMLESS_MARKER, "Unexpected marker 0x%02x")
  165156. JMESSAGE(JTRC_QUANTVALS, " %4u %4u %4u %4u %4u %4u %4u %4u")
  165157. JMESSAGE(JTRC_QUANT_3_NCOLORS, "Quantizing to %d = %d*%d*%d colors")
  165158. JMESSAGE(JTRC_QUANT_NCOLORS, "Quantizing to %d colors")
  165159. JMESSAGE(JTRC_QUANT_SELECTED, "Selected %d colors for quantization")
  165160. JMESSAGE(JTRC_RECOVERY_ACTION, "At marker 0x%02x, recovery action %d")
  165161. JMESSAGE(JTRC_RST, "RST%d")
  165162. JMESSAGE(JTRC_SMOOTH_NOTIMPL,
  165163. "Smoothing not supported with nonstandard sampling ratios")
  165164. JMESSAGE(JTRC_SOF, "Start Of Frame 0x%02x: width=%u, height=%u, components=%d")
  165165. JMESSAGE(JTRC_SOF_COMPONENT, " Component %d: %dhx%dv q=%d")
  165166. JMESSAGE(JTRC_SOI, "Start of Image")
  165167. JMESSAGE(JTRC_SOS, "Start Of Scan: %d components")
  165168. JMESSAGE(JTRC_SOS_COMPONENT, " Component %d: dc=%d ac=%d")
  165169. JMESSAGE(JTRC_SOS_PARAMS, " Ss=%d, Se=%d, Ah=%d, Al=%d")
  165170. JMESSAGE(JTRC_TFILE_CLOSE, "Closed temporary file %s")
  165171. JMESSAGE(JTRC_TFILE_OPEN, "Opened temporary file %s")
  165172. JMESSAGE(JTRC_THUMB_JPEG,
  165173. "JFIF extension marker: JPEG-compressed thumbnail image, length %u")
  165174. JMESSAGE(JTRC_THUMB_PALETTE,
  165175. "JFIF extension marker: palette thumbnail image, length %u")
  165176. JMESSAGE(JTRC_THUMB_RGB,
  165177. "JFIF extension marker: RGB thumbnail image, length %u")
  165178. JMESSAGE(JTRC_UNKNOWN_IDS,
  165179. "Unrecognized component IDs %d %d %d, assuming YCbCr")
  165180. JMESSAGE(JTRC_XMS_CLOSE, "Freed XMS handle %u")
  165181. JMESSAGE(JTRC_XMS_OPEN, "Obtained XMS handle %u")
  165182. JMESSAGE(JWRN_ADOBE_XFORM, "Unknown Adobe color transform code %d")
  165183. JMESSAGE(JWRN_BOGUS_PROGRESSION,
  165184. "Inconsistent progression sequence for component %d coefficient %d")
  165185. JMESSAGE(JWRN_EXTRANEOUS_DATA,
  165186. "Corrupt JPEG data: %u extraneous bytes before marker 0x%02x")
  165187. JMESSAGE(JWRN_HIT_MARKER, "Corrupt JPEG data: premature end of data segment")
  165188. JMESSAGE(JWRN_HUFF_BAD_CODE, "Corrupt JPEG data: bad Huffman code")
  165189. JMESSAGE(JWRN_JFIF_MAJOR, "Warning: unknown JFIF revision number %d.%02d")
  165190. JMESSAGE(JWRN_JPEG_EOF, "Premature end of JPEG file")
  165191. JMESSAGE(JWRN_MUST_RESYNC,
  165192. "Corrupt JPEG data: found marker 0x%02x instead of RST%d")
  165193. JMESSAGE(JWRN_NOT_SEQUENTIAL, "Invalid SOS parameters for sequential JPEG")
  165194. JMESSAGE(JWRN_TOO_MUCH_DATA, "Application transferred too many scanlines")
  165195. #ifdef JMAKE_ENUM_LIST
  165196. JMSG_LASTMSGCODE
  165197. } J_MESSAGE_CODE;
  165198. #undef JMAKE_ENUM_LIST
  165199. #endif /* JMAKE_ENUM_LIST */
  165200. /* Zap JMESSAGE macro so that future re-inclusions do nothing by default */
  165201. #undef JMESSAGE
  165202. #ifndef JERROR_H
  165203. #define JERROR_H
  165204. /* Macros to simplify using the error and trace message stuff */
  165205. /* The first parameter is either type of cinfo pointer */
  165206. /* Fatal errors (print message and exit) */
  165207. #define ERREXIT(cinfo,code) \
  165208. ((cinfo)->err->msg_code = (code), \
  165209. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  165210. #define ERREXIT1(cinfo,code,p1) \
  165211. ((cinfo)->err->msg_code = (code), \
  165212. (cinfo)->err->msg_parm.i[0] = (p1), \
  165213. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  165214. #define ERREXIT2(cinfo,code,p1,p2) \
  165215. ((cinfo)->err->msg_code = (code), \
  165216. (cinfo)->err->msg_parm.i[0] = (p1), \
  165217. (cinfo)->err->msg_parm.i[1] = (p2), \
  165218. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  165219. #define ERREXIT3(cinfo,code,p1,p2,p3) \
  165220. ((cinfo)->err->msg_code = (code), \
  165221. (cinfo)->err->msg_parm.i[0] = (p1), \
  165222. (cinfo)->err->msg_parm.i[1] = (p2), \
  165223. (cinfo)->err->msg_parm.i[2] = (p3), \
  165224. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  165225. #define ERREXIT4(cinfo,code,p1,p2,p3,p4) \
  165226. ((cinfo)->err->msg_code = (code), \
  165227. (cinfo)->err->msg_parm.i[0] = (p1), \
  165228. (cinfo)->err->msg_parm.i[1] = (p2), \
  165229. (cinfo)->err->msg_parm.i[2] = (p3), \
  165230. (cinfo)->err->msg_parm.i[3] = (p4), \
  165231. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  165232. #define ERREXITS(cinfo,code,str) \
  165233. ((cinfo)->err->msg_code = (code), \
  165234. strncpy((cinfo)->err->msg_parm.s, (str), JMSG_STR_PARM_MAX), \
  165235. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  165236. #define MAKESTMT(stuff) do { stuff } while (0)
  165237. /* Nonfatal errors (we can keep going, but the data is probably corrupt) */
  165238. #define WARNMS(cinfo,code) \
  165239. ((cinfo)->err->msg_code = (code), \
  165240. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), -1))
  165241. #define WARNMS1(cinfo,code,p1) \
  165242. ((cinfo)->err->msg_code = (code), \
  165243. (cinfo)->err->msg_parm.i[0] = (p1), \
  165244. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), -1))
  165245. #define WARNMS2(cinfo,code,p1,p2) \
  165246. ((cinfo)->err->msg_code = (code), \
  165247. (cinfo)->err->msg_parm.i[0] = (p1), \
  165248. (cinfo)->err->msg_parm.i[1] = (p2), \
  165249. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), -1))
  165250. /* Informational/debugging messages */
  165251. #define TRACEMS(cinfo,lvl,code) \
  165252. ((cinfo)->err->msg_code = (code), \
  165253. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)))
  165254. #define TRACEMS1(cinfo,lvl,code,p1) \
  165255. ((cinfo)->err->msg_code = (code), \
  165256. (cinfo)->err->msg_parm.i[0] = (p1), \
  165257. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)))
  165258. #define TRACEMS2(cinfo,lvl,code,p1,p2) \
  165259. ((cinfo)->err->msg_code = (code), \
  165260. (cinfo)->err->msg_parm.i[0] = (p1), \
  165261. (cinfo)->err->msg_parm.i[1] = (p2), \
  165262. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)))
  165263. #define TRACEMS3(cinfo,lvl,code,p1,p2,p3) \
  165264. MAKESTMT(int * _mp = (cinfo)->err->msg_parm.i; \
  165265. _mp[0] = (p1); _mp[1] = (p2); _mp[2] = (p3); \
  165266. (cinfo)->err->msg_code = (code); \
  165267. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)); )
  165268. #define TRACEMS4(cinfo,lvl,code,p1,p2,p3,p4) \
  165269. MAKESTMT(int * _mp = (cinfo)->err->msg_parm.i; \
  165270. _mp[0] = (p1); _mp[1] = (p2); _mp[2] = (p3); _mp[3] = (p4); \
  165271. (cinfo)->err->msg_code = (code); \
  165272. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)); )
  165273. #define TRACEMS5(cinfo,lvl,code,p1,p2,p3,p4,p5) \
  165274. MAKESTMT(int * _mp = (cinfo)->err->msg_parm.i; \
  165275. _mp[0] = (p1); _mp[1] = (p2); _mp[2] = (p3); _mp[3] = (p4); \
  165276. _mp[4] = (p5); \
  165277. (cinfo)->err->msg_code = (code); \
  165278. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)); )
  165279. #define TRACEMS8(cinfo,lvl,code,p1,p2,p3,p4,p5,p6,p7,p8) \
  165280. MAKESTMT(int * _mp = (cinfo)->err->msg_parm.i; \
  165281. _mp[0] = (p1); _mp[1] = (p2); _mp[2] = (p3); _mp[3] = (p4); \
  165282. _mp[4] = (p5); _mp[5] = (p6); _mp[6] = (p7); _mp[7] = (p8); \
  165283. (cinfo)->err->msg_code = (code); \
  165284. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)); )
  165285. #define TRACEMSS(cinfo,lvl,code,str) \
  165286. ((cinfo)->err->msg_code = (code), \
  165287. strncpy((cinfo)->err->msg_parm.s, (str), JMSG_STR_PARM_MAX), \
  165288. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)))
  165289. #endif /* JERROR_H */
  165290. /*** End of inlined file: jerror.h ***/
  165291. /* Expanded data source object for stdio input */
  165292. typedef struct {
  165293. struct jpeg_source_mgr pub; /* public fields */
  165294. FILE * infile; /* source stream */
  165295. JOCTET * buffer; /* start of buffer */
  165296. boolean start_of_file; /* have we gotten any data yet? */
  165297. } my_source_mgr;
  165298. typedef my_source_mgr * my_src_ptr;
  165299. #define INPUT_BUF_SIZE 4096 /* choose an efficiently fread'able size */
  165300. /*
  165301. * Initialize source --- called by jpeg_read_header
  165302. * before any data is actually read.
  165303. */
  165304. METHODDEF(void)
  165305. init_source (j_decompress_ptr cinfo)
  165306. {
  165307. my_src_ptr src = (my_src_ptr) cinfo->src;
  165308. /* We reset the empty-input-file flag for each image,
  165309. * but we don't clear the input buffer.
  165310. * This is correct behavior for reading a series of images from one source.
  165311. */
  165312. src->start_of_file = TRUE;
  165313. }
  165314. /*
  165315. * Fill the input buffer --- called whenever buffer is emptied.
  165316. *
  165317. * In typical applications, this should read fresh data into the buffer
  165318. * (ignoring the current state of next_input_byte & bytes_in_buffer),
  165319. * reset the pointer & count to the start of the buffer, and return TRUE
  165320. * indicating that the buffer has been reloaded. It is not necessary to
  165321. * fill the buffer entirely, only to obtain at least one more byte.
  165322. *
  165323. * There is no such thing as an EOF return. If the end of the file has been
  165324. * reached, the routine has a choice of ERREXIT() or inserting fake data into
  165325. * the buffer. In most cases, generating a warning message and inserting a
  165326. * fake EOI marker is the best course of action --- this will allow the
  165327. * decompressor to output however much of the image is there. However,
  165328. * the resulting error message is misleading if the real problem is an empty
  165329. * input file, so we handle that case specially.
  165330. *
  165331. * In applications that need to be able to suspend compression due to input
  165332. * not being available yet, a FALSE return indicates that no more data can be
  165333. * obtained right now, but more may be forthcoming later. In this situation,
  165334. * the decompressor will return to its caller (with an indication of the
  165335. * number of scanlines it has read, if any). The application should resume
  165336. * decompression after it has loaded more data into the input buffer. Note
  165337. * that there are substantial restrictions on the use of suspension --- see
  165338. * the documentation.
  165339. *
  165340. * When suspending, the decompressor will back up to a convenient restart point
  165341. * (typically the start of the current MCU). next_input_byte & bytes_in_buffer
  165342. * indicate where the restart point will be if the current call returns FALSE.
  165343. * Data beyond this point must be rescanned after resumption, so move it to
  165344. * the front of the buffer rather than discarding it.
  165345. */
  165346. METHODDEF(boolean)
  165347. fill_input_buffer (j_decompress_ptr cinfo)
  165348. {
  165349. my_src_ptr src = (my_src_ptr) cinfo->src;
  165350. size_t nbytes;
  165351. nbytes = JFREAD(src->infile, src->buffer, INPUT_BUF_SIZE);
  165352. if (nbytes <= 0) {
  165353. if (src->start_of_file) /* Treat empty input file as fatal error */
  165354. ERREXIT(cinfo, JERR_INPUT_EMPTY);
  165355. WARNMS(cinfo, JWRN_JPEG_EOF);
  165356. /* Insert a fake EOI marker */
  165357. src->buffer[0] = (JOCTET) 0xFF;
  165358. src->buffer[1] = (JOCTET) JPEG_EOI;
  165359. nbytes = 2;
  165360. }
  165361. src->pub.next_input_byte = src->buffer;
  165362. src->pub.bytes_in_buffer = nbytes;
  165363. src->start_of_file = FALSE;
  165364. return TRUE;
  165365. }
  165366. /*
  165367. * Skip data --- used to skip over a potentially large amount of
  165368. * uninteresting data (such as an APPn marker).
  165369. *
  165370. * Writers of suspendable-input applications must note that skip_input_data
  165371. * is not granted the right to give a suspension return. If the skip extends
  165372. * beyond the data currently in the buffer, the buffer can be marked empty so
  165373. * that the next read will cause a fill_input_buffer call that can suspend.
  165374. * Arranging for additional bytes to be discarded before reloading the input
  165375. * buffer is the application writer's problem.
  165376. */
  165377. METHODDEF(void)
  165378. skip_input_data (j_decompress_ptr cinfo, long num_bytes)
  165379. {
  165380. my_src_ptr src = (my_src_ptr) cinfo->src;
  165381. /* Just a dumb implementation for now. Could use fseek() except
  165382. * it doesn't work on pipes. Not clear that being smart is worth
  165383. * any trouble anyway --- large skips are infrequent.
  165384. */
  165385. if (num_bytes > 0) {
  165386. while (num_bytes > (long) src->pub.bytes_in_buffer) {
  165387. num_bytes -= (long) src->pub.bytes_in_buffer;
  165388. (void) fill_input_buffer(cinfo);
  165389. /* note we assume that fill_input_buffer will never return FALSE,
  165390. * so suspension need not be handled.
  165391. */
  165392. }
  165393. src->pub.next_input_byte += (size_t) num_bytes;
  165394. src->pub.bytes_in_buffer -= (size_t) num_bytes;
  165395. }
  165396. }
  165397. /*
  165398. * An additional method that can be provided by data source modules is the
  165399. * resync_to_restart method for error recovery in the presence of RST markers.
  165400. * For the moment, this source module just uses the default resync method
  165401. * provided by the JPEG library. That method assumes that no backtracking
  165402. * is possible.
  165403. */
  165404. /*
  165405. * Terminate source --- called by jpeg_finish_decompress
  165406. * after all data has been read. Often a no-op.
  165407. *
  165408. * NB: *not* called by jpeg_abort or jpeg_destroy; surrounding
  165409. * application must deal with any cleanup that should happen even
  165410. * for error exit.
  165411. */
  165412. METHODDEF(void)
  165413. term_source (j_decompress_ptr)
  165414. {
  165415. /* no work necessary here */
  165416. }
  165417. /*
  165418. * Prepare for input from a stdio stream.
  165419. * The caller must have already opened the stream, and is responsible
  165420. * for closing it after finishing decompression.
  165421. */
  165422. GLOBAL(void)
  165423. jpeg_stdio_src (j_decompress_ptr cinfo, FILE * infile)
  165424. {
  165425. my_src_ptr src;
  165426. /* The source object and input buffer are made permanent so that a series
  165427. * of JPEG images can be read from the same file by calling jpeg_stdio_src
  165428. * only before the first one. (If we discarded the buffer at the end of
  165429. * one image, we'd likely lose the start of the next one.)
  165430. * This makes it unsafe to use this manager and a different source
  165431. * manager serially with the same JPEG object. Caveat programmer.
  165432. */
  165433. if (cinfo->src == NULL) { /* first time for this JPEG object? */
  165434. cinfo->src = (struct jpeg_source_mgr *)
  165435. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT,
  165436. SIZEOF(my_source_mgr));
  165437. src = (my_src_ptr) cinfo->src;
  165438. src->buffer = (JOCTET *)
  165439. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT,
  165440. INPUT_BUF_SIZE * SIZEOF(JOCTET));
  165441. }
  165442. src = (my_src_ptr) cinfo->src;
  165443. src->pub.init_source = init_source;
  165444. src->pub.fill_input_buffer = fill_input_buffer;
  165445. src->pub.skip_input_data = skip_input_data;
  165446. src->pub.resync_to_restart = jpeg_resync_to_restart; /* use default method */
  165447. src->pub.term_source = term_source;
  165448. src->infile = infile;
  165449. src->pub.bytes_in_buffer = 0; /* forces fill_input_buffer on first read */
  165450. src->pub.next_input_byte = NULL; /* until buffer loaded */
  165451. }
  165452. /*** End of inlined file: jdatasrc.c ***/
  165453. /*** Start of inlined file: jdcoefct.c ***/
  165454. #define JPEG_INTERNALS
  165455. /* Block smoothing is only applicable for progressive JPEG, so: */
  165456. #ifndef D_PROGRESSIVE_SUPPORTED
  165457. #undef BLOCK_SMOOTHING_SUPPORTED
  165458. #endif
  165459. /* Private buffer controller object */
  165460. typedef struct {
  165461. struct jpeg_d_coef_controller pub; /* public fields */
  165462. /* These variables keep track of the current location of the input side. */
  165463. /* cinfo->input_iMCU_row is also used for this. */
  165464. JDIMENSION MCU_ctr; /* counts MCUs processed in current row */
  165465. int MCU_vert_offset; /* counts MCU rows within iMCU row */
  165466. int MCU_rows_per_iMCU_row; /* number of such rows needed */
  165467. /* The output side's location is represented by cinfo->output_iMCU_row. */
  165468. /* In single-pass modes, it's sufficient to buffer just one MCU.
  165469. * We allocate a workspace of D_MAX_BLOCKS_IN_MCU coefficient blocks,
  165470. * and let the entropy decoder write into that workspace each time.
  165471. * (On 80x86, the workspace is FAR even though it's not really very big;
  165472. * this is to keep the module interfaces unchanged when a large coefficient
  165473. * buffer is necessary.)
  165474. * In multi-pass modes, this array points to the current MCU's blocks
  165475. * within the virtual arrays; it is used only by the input side.
  165476. */
  165477. JBLOCKROW MCU_buffer[D_MAX_BLOCKS_IN_MCU];
  165478. #ifdef D_MULTISCAN_FILES_SUPPORTED
  165479. /* In multi-pass modes, we need a virtual block array for each component. */
  165480. jvirt_barray_ptr whole_image[MAX_COMPONENTS];
  165481. #endif
  165482. #ifdef BLOCK_SMOOTHING_SUPPORTED
  165483. /* When doing block smoothing, we latch coefficient Al values here */
  165484. int * coef_bits_latch;
  165485. #define SAVED_COEFS 6 /* we save coef_bits[0..5] */
  165486. #endif
  165487. } my_coef_controller3;
  165488. typedef my_coef_controller3 * my_coef_ptr3;
  165489. /* Forward declarations */
  165490. METHODDEF(int) decompress_onepass
  165491. JPP((j_decompress_ptr cinfo, JSAMPIMAGE output_buf));
  165492. #ifdef D_MULTISCAN_FILES_SUPPORTED
  165493. METHODDEF(int) decompress_data
  165494. JPP((j_decompress_ptr cinfo, JSAMPIMAGE output_buf));
  165495. #endif
  165496. #ifdef BLOCK_SMOOTHING_SUPPORTED
  165497. LOCAL(boolean) smoothing_ok JPP((j_decompress_ptr cinfo));
  165498. METHODDEF(int) decompress_smooth_data
  165499. JPP((j_decompress_ptr cinfo, JSAMPIMAGE output_buf));
  165500. #endif
  165501. LOCAL(void)
  165502. start_iMCU_row3 (j_decompress_ptr cinfo)
  165503. /* Reset within-iMCU-row counters for a new row (input side) */
  165504. {
  165505. my_coef_ptr3 coef = (my_coef_ptr3) cinfo->coef;
  165506. /* In an interleaved scan, an MCU row is the same as an iMCU row.
  165507. * In a noninterleaved scan, an iMCU row has v_samp_factor MCU rows.
  165508. * But at the bottom of the image, process only what's left.
  165509. */
  165510. if (cinfo->comps_in_scan > 1) {
  165511. coef->MCU_rows_per_iMCU_row = 1;
  165512. } else {
  165513. if (cinfo->input_iMCU_row < (cinfo->total_iMCU_rows-1))
  165514. coef->MCU_rows_per_iMCU_row = cinfo->cur_comp_info[0]->v_samp_factor;
  165515. else
  165516. coef->MCU_rows_per_iMCU_row = cinfo->cur_comp_info[0]->last_row_height;
  165517. }
  165518. coef->MCU_ctr = 0;
  165519. coef->MCU_vert_offset = 0;
  165520. }
  165521. /*
  165522. * Initialize for an input processing pass.
  165523. */
  165524. METHODDEF(void)
  165525. start_input_pass (j_decompress_ptr cinfo)
  165526. {
  165527. cinfo->input_iMCU_row = 0;
  165528. start_iMCU_row3(cinfo);
  165529. }
  165530. /*
  165531. * Initialize for an output processing pass.
  165532. */
  165533. METHODDEF(void)
  165534. start_output_pass (j_decompress_ptr cinfo)
  165535. {
  165536. #ifdef BLOCK_SMOOTHING_SUPPORTED
  165537. my_coef_ptr3 coef = (my_coef_ptr3) cinfo->coef;
  165538. /* If multipass, check to see whether to use block smoothing on this pass */
  165539. if (coef->pub.coef_arrays != NULL) {
  165540. if (cinfo->do_block_smoothing && smoothing_ok(cinfo))
  165541. coef->pub.decompress_data = decompress_smooth_data;
  165542. else
  165543. coef->pub.decompress_data = decompress_data;
  165544. }
  165545. #endif
  165546. cinfo->output_iMCU_row = 0;
  165547. }
  165548. /*
  165549. * Decompress and return some data in the single-pass case.
  165550. * Always attempts to emit one fully interleaved MCU row ("iMCU" row).
  165551. * Input and output must run in lockstep since we have only a one-MCU buffer.
  165552. * Return value is JPEG_ROW_COMPLETED, JPEG_SCAN_COMPLETED, or JPEG_SUSPENDED.
  165553. *
  165554. * NB: output_buf contains a plane for each component in image,
  165555. * which we index according to the component's SOF position.
  165556. */
  165557. METHODDEF(int)
  165558. decompress_onepass (j_decompress_ptr cinfo, JSAMPIMAGE output_buf)
  165559. {
  165560. my_coef_ptr3 coef = (my_coef_ptr3) cinfo->coef;
  165561. JDIMENSION MCU_col_num; /* index of current MCU within row */
  165562. JDIMENSION last_MCU_col = cinfo->MCUs_per_row - 1;
  165563. JDIMENSION last_iMCU_row = cinfo->total_iMCU_rows - 1;
  165564. int blkn, ci, xindex, yindex, yoffset, useful_width;
  165565. JSAMPARRAY output_ptr;
  165566. JDIMENSION start_col, output_col;
  165567. jpeg_component_info *compptr;
  165568. inverse_DCT_method_ptr inverse_DCT;
  165569. /* Loop to process as much as one whole iMCU row */
  165570. for (yoffset = coef->MCU_vert_offset; yoffset < coef->MCU_rows_per_iMCU_row;
  165571. yoffset++) {
  165572. for (MCU_col_num = coef->MCU_ctr; MCU_col_num <= last_MCU_col;
  165573. MCU_col_num++) {
  165574. /* Try to fetch an MCU. Entropy decoder expects buffer to be zeroed. */
  165575. jzero_far((void FAR *) coef->MCU_buffer[0],
  165576. (size_t) (cinfo->blocks_in_MCU * SIZEOF(JBLOCK)));
  165577. if (! (*cinfo->entropy->decode_mcu) (cinfo, coef->MCU_buffer)) {
  165578. /* Suspension forced; update state counters and exit */
  165579. coef->MCU_vert_offset = yoffset;
  165580. coef->MCU_ctr = MCU_col_num;
  165581. return JPEG_SUSPENDED;
  165582. }
  165583. /* Determine where data should go in output_buf and do the IDCT thing.
  165584. * We skip dummy blocks at the right and bottom edges (but blkn gets
  165585. * incremented past them!). Note the inner loop relies on having
  165586. * allocated the MCU_buffer[] blocks sequentially.
  165587. */
  165588. blkn = 0; /* index of current DCT block within MCU */
  165589. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  165590. compptr = cinfo->cur_comp_info[ci];
  165591. /* Don't bother to IDCT an uninteresting component. */
  165592. if (! compptr->component_needed) {
  165593. blkn += compptr->MCU_blocks;
  165594. continue;
  165595. }
  165596. inverse_DCT = cinfo->idct->inverse_DCT[compptr->component_index];
  165597. useful_width = (MCU_col_num < last_MCU_col) ? compptr->MCU_width
  165598. : compptr->last_col_width;
  165599. output_ptr = output_buf[compptr->component_index] +
  165600. yoffset * compptr->DCT_scaled_size;
  165601. start_col = MCU_col_num * compptr->MCU_sample_width;
  165602. for (yindex = 0; yindex < compptr->MCU_height; yindex++) {
  165603. if (cinfo->input_iMCU_row < last_iMCU_row ||
  165604. yoffset+yindex < compptr->last_row_height) {
  165605. output_col = start_col;
  165606. for (xindex = 0; xindex < useful_width; xindex++) {
  165607. (*inverse_DCT) (cinfo, compptr,
  165608. (JCOEFPTR) coef->MCU_buffer[blkn+xindex],
  165609. output_ptr, output_col);
  165610. output_col += compptr->DCT_scaled_size;
  165611. }
  165612. }
  165613. blkn += compptr->MCU_width;
  165614. output_ptr += compptr->DCT_scaled_size;
  165615. }
  165616. }
  165617. }
  165618. /* Completed an MCU row, but perhaps not an iMCU row */
  165619. coef->MCU_ctr = 0;
  165620. }
  165621. /* Completed the iMCU row, advance counters for next one */
  165622. cinfo->output_iMCU_row++;
  165623. if (++(cinfo->input_iMCU_row) < cinfo->total_iMCU_rows) {
  165624. start_iMCU_row3(cinfo);
  165625. return JPEG_ROW_COMPLETED;
  165626. }
  165627. /* Completed the scan */
  165628. (*cinfo->inputctl->finish_input_pass) (cinfo);
  165629. return JPEG_SCAN_COMPLETED;
  165630. }
  165631. /*
  165632. * Dummy consume-input routine for single-pass operation.
  165633. */
  165634. METHODDEF(int)
  165635. dummy_consume_data (j_decompress_ptr)
  165636. {
  165637. return JPEG_SUSPENDED; /* Always indicate nothing was done */
  165638. }
  165639. #ifdef D_MULTISCAN_FILES_SUPPORTED
  165640. /*
  165641. * Consume input data and store it in the full-image coefficient buffer.
  165642. * We read as much as one fully interleaved MCU row ("iMCU" row) per call,
  165643. * ie, v_samp_factor block rows for each component in the scan.
  165644. * Return value is JPEG_ROW_COMPLETED, JPEG_SCAN_COMPLETED, or JPEG_SUSPENDED.
  165645. */
  165646. METHODDEF(int)
  165647. consume_data (j_decompress_ptr cinfo)
  165648. {
  165649. my_coef_ptr3 coef = (my_coef_ptr3) cinfo->coef;
  165650. JDIMENSION MCU_col_num; /* index of current MCU within row */
  165651. int blkn, ci, xindex, yindex, yoffset;
  165652. JDIMENSION start_col;
  165653. JBLOCKARRAY buffer[MAX_COMPS_IN_SCAN];
  165654. JBLOCKROW buffer_ptr;
  165655. jpeg_component_info *compptr;
  165656. /* Align the virtual buffers for the components used in this scan. */
  165657. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  165658. compptr = cinfo->cur_comp_info[ci];
  165659. buffer[ci] = (*cinfo->mem->access_virt_barray)
  165660. ((j_common_ptr) cinfo, coef->whole_image[compptr->component_index],
  165661. cinfo->input_iMCU_row * compptr->v_samp_factor,
  165662. (JDIMENSION) compptr->v_samp_factor, TRUE);
  165663. /* Note: entropy decoder expects buffer to be zeroed,
  165664. * but this is handled automatically by the memory manager
  165665. * because we requested a pre-zeroed array.
  165666. */
  165667. }
  165668. /* Loop to process one whole iMCU row */
  165669. for (yoffset = coef->MCU_vert_offset; yoffset < coef->MCU_rows_per_iMCU_row;
  165670. yoffset++) {
  165671. for (MCU_col_num = coef->MCU_ctr; MCU_col_num < cinfo->MCUs_per_row;
  165672. MCU_col_num++) {
  165673. /* Construct list of pointers to DCT blocks belonging to this MCU */
  165674. blkn = 0; /* index of current DCT block within MCU */
  165675. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  165676. compptr = cinfo->cur_comp_info[ci];
  165677. start_col = MCU_col_num * compptr->MCU_width;
  165678. for (yindex = 0; yindex < compptr->MCU_height; yindex++) {
  165679. buffer_ptr = buffer[ci][yindex+yoffset] + start_col;
  165680. for (xindex = 0; xindex < compptr->MCU_width; xindex++) {
  165681. coef->MCU_buffer[blkn++] = buffer_ptr++;
  165682. }
  165683. }
  165684. }
  165685. /* Try to fetch the MCU. */
  165686. if (! (*cinfo->entropy->decode_mcu) (cinfo, coef->MCU_buffer)) {
  165687. /* Suspension forced; update state counters and exit */
  165688. coef->MCU_vert_offset = yoffset;
  165689. coef->MCU_ctr = MCU_col_num;
  165690. return JPEG_SUSPENDED;
  165691. }
  165692. }
  165693. /* Completed an MCU row, but perhaps not an iMCU row */
  165694. coef->MCU_ctr = 0;
  165695. }
  165696. /* Completed the iMCU row, advance counters for next one */
  165697. if (++(cinfo->input_iMCU_row) < cinfo->total_iMCU_rows) {
  165698. start_iMCU_row3(cinfo);
  165699. return JPEG_ROW_COMPLETED;
  165700. }
  165701. /* Completed the scan */
  165702. (*cinfo->inputctl->finish_input_pass) (cinfo);
  165703. return JPEG_SCAN_COMPLETED;
  165704. }
  165705. /*
  165706. * Decompress and return some data in the multi-pass case.
  165707. * Always attempts to emit one fully interleaved MCU row ("iMCU" row).
  165708. * Return value is JPEG_ROW_COMPLETED, JPEG_SCAN_COMPLETED, or JPEG_SUSPENDED.
  165709. *
  165710. * NB: output_buf contains a plane for each component in image.
  165711. */
  165712. METHODDEF(int)
  165713. decompress_data (j_decompress_ptr cinfo, JSAMPIMAGE output_buf)
  165714. {
  165715. my_coef_ptr3 coef = (my_coef_ptr3) cinfo->coef;
  165716. JDIMENSION last_iMCU_row = cinfo->total_iMCU_rows - 1;
  165717. JDIMENSION block_num;
  165718. int ci, block_row, block_rows;
  165719. JBLOCKARRAY buffer;
  165720. JBLOCKROW buffer_ptr;
  165721. JSAMPARRAY output_ptr;
  165722. JDIMENSION output_col;
  165723. jpeg_component_info *compptr;
  165724. inverse_DCT_method_ptr inverse_DCT;
  165725. /* Force some input to be done if we are getting ahead of the input. */
  165726. while (cinfo->input_scan_number < cinfo->output_scan_number ||
  165727. (cinfo->input_scan_number == cinfo->output_scan_number &&
  165728. cinfo->input_iMCU_row <= cinfo->output_iMCU_row)) {
  165729. if ((*cinfo->inputctl->consume_input)(cinfo) == JPEG_SUSPENDED)
  165730. return JPEG_SUSPENDED;
  165731. }
  165732. /* OK, output from the virtual arrays. */
  165733. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  165734. ci++, compptr++) {
  165735. /* Don't bother to IDCT an uninteresting component. */
  165736. if (! compptr->component_needed)
  165737. continue;
  165738. /* Align the virtual buffer for this component. */
  165739. buffer = (*cinfo->mem->access_virt_barray)
  165740. ((j_common_ptr) cinfo, coef->whole_image[ci],
  165741. cinfo->output_iMCU_row * compptr->v_samp_factor,
  165742. (JDIMENSION) compptr->v_samp_factor, FALSE);
  165743. /* Count non-dummy DCT block rows in this iMCU row. */
  165744. if (cinfo->output_iMCU_row < last_iMCU_row)
  165745. block_rows = compptr->v_samp_factor;
  165746. else {
  165747. /* NB: can't use last_row_height here; it is input-side-dependent! */
  165748. block_rows = (int) (compptr->height_in_blocks % compptr->v_samp_factor);
  165749. if (block_rows == 0) block_rows = compptr->v_samp_factor;
  165750. }
  165751. inverse_DCT = cinfo->idct->inverse_DCT[ci];
  165752. output_ptr = output_buf[ci];
  165753. /* Loop over all DCT blocks to be processed. */
  165754. for (block_row = 0; block_row < block_rows; block_row++) {
  165755. buffer_ptr = buffer[block_row];
  165756. output_col = 0;
  165757. for (block_num = 0; block_num < compptr->width_in_blocks; block_num++) {
  165758. (*inverse_DCT) (cinfo, compptr, (JCOEFPTR) buffer_ptr,
  165759. output_ptr, output_col);
  165760. buffer_ptr++;
  165761. output_col += compptr->DCT_scaled_size;
  165762. }
  165763. output_ptr += compptr->DCT_scaled_size;
  165764. }
  165765. }
  165766. if (++(cinfo->output_iMCU_row) < cinfo->total_iMCU_rows)
  165767. return JPEG_ROW_COMPLETED;
  165768. return JPEG_SCAN_COMPLETED;
  165769. }
  165770. #endif /* D_MULTISCAN_FILES_SUPPORTED */
  165771. #ifdef BLOCK_SMOOTHING_SUPPORTED
  165772. /*
  165773. * This code applies interblock smoothing as described by section K.8
  165774. * of the JPEG standard: the first 5 AC coefficients are estimated from
  165775. * the DC values of a DCT block and its 8 neighboring blocks.
  165776. * We apply smoothing only for progressive JPEG decoding, and only if
  165777. * the coefficients it can estimate are not yet known to full precision.
  165778. */
  165779. /* Natural-order array positions of the first 5 zigzag-order coefficients */
  165780. #define Q01_POS 1
  165781. #define Q10_POS 8
  165782. #define Q20_POS 16
  165783. #define Q11_POS 9
  165784. #define Q02_POS 2
  165785. /*
  165786. * Determine whether block smoothing is applicable and safe.
  165787. * We also latch the current states of the coef_bits[] entries for the
  165788. * AC coefficients; otherwise, if the input side of the decompressor
  165789. * advances into a new scan, we might think the coefficients are known
  165790. * more accurately than they really are.
  165791. */
  165792. LOCAL(boolean)
  165793. smoothing_ok (j_decompress_ptr cinfo)
  165794. {
  165795. my_coef_ptr3 coef = (my_coef_ptr3) cinfo->coef;
  165796. boolean smoothing_useful = FALSE;
  165797. int ci, coefi;
  165798. jpeg_component_info *compptr;
  165799. JQUANT_TBL * qtable;
  165800. int * coef_bits;
  165801. int * coef_bits_latch;
  165802. if (! cinfo->progressive_mode || cinfo->coef_bits == NULL)
  165803. return FALSE;
  165804. /* Allocate latch area if not already done */
  165805. if (coef->coef_bits_latch == NULL)
  165806. coef->coef_bits_latch = (int *)
  165807. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  165808. cinfo->num_components *
  165809. (SAVED_COEFS * SIZEOF(int)));
  165810. coef_bits_latch = coef->coef_bits_latch;
  165811. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  165812. ci++, compptr++) {
  165813. /* All components' quantization values must already be latched. */
  165814. if ((qtable = compptr->quant_table) == NULL)
  165815. return FALSE;
  165816. /* Verify DC & first 5 AC quantizers are nonzero to avoid zero-divide. */
  165817. if (qtable->quantval[0] == 0 ||
  165818. qtable->quantval[Q01_POS] == 0 ||
  165819. qtable->quantval[Q10_POS] == 0 ||
  165820. qtable->quantval[Q20_POS] == 0 ||
  165821. qtable->quantval[Q11_POS] == 0 ||
  165822. qtable->quantval[Q02_POS] == 0)
  165823. return FALSE;
  165824. /* DC values must be at least partly known for all components. */
  165825. coef_bits = cinfo->coef_bits[ci];
  165826. if (coef_bits[0] < 0)
  165827. return FALSE;
  165828. /* Block smoothing is helpful if some AC coefficients remain inaccurate. */
  165829. for (coefi = 1; coefi <= 5; coefi++) {
  165830. coef_bits_latch[coefi] = coef_bits[coefi];
  165831. if (coef_bits[coefi] != 0)
  165832. smoothing_useful = TRUE;
  165833. }
  165834. coef_bits_latch += SAVED_COEFS;
  165835. }
  165836. return smoothing_useful;
  165837. }
  165838. /*
  165839. * Variant of decompress_data for use when doing block smoothing.
  165840. */
  165841. METHODDEF(int)
  165842. decompress_smooth_data (j_decompress_ptr cinfo, JSAMPIMAGE output_buf)
  165843. {
  165844. my_coef_ptr3 coef = (my_coef_ptr3) cinfo->coef;
  165845. JDIMENSION last_iMCU_row = cinfo->total_iMCU_rows - 1;
  165846. JDIMENSION block_num, last_block_column;
  165847. int ci, block_row, block_rows, access_rows;
  165848. JBLOCKARRAY buffer;
  165849. JBLOCKROW buffer_ptr, prev_block_row, next_block_row;
  165850. JSAMPARRAY output_ptr;
  165851. JDIMENSION output_col;
  165852. jpeg_component_info *compptr;
  165853. inverse_DCT_method_ptr inverse_DCT;
  165854. boolean first_row, last_row;
  165855. JBLOCK workspace;
  165856. int *coef_bits;
  165857. JQUANT_TBL *quanttbl;
  165858. INT32 Q00,Q01,Q02,Q10,Q11,Q20, num;
  165859. int DC1,DC2,DC3,DC4,DC5,DC6,DC7,DC8,DC9;
  165860. int Al, pred;
  165861. /* Force some input to be done if we are getting ahead of the input. */
  165862. while (cinfo->input_scan_number <= cinfo->output_scan_number &&
  165863. ! cinfo->inputctl->eoi_reached) {
  165864. if (cinfo->input_scan_number == cinfo->output_scan_number) {
  165865. /* If input is working on current scan, we ordinarily want it to
  165866. * have completed the current row. But if input scan is DC,
  165867. * we want it to keep one row ahead so that next block row's DC
  165868. * values are up to date.
  165869. */
  165870. JDIMENSION delta = (cinfo->Ss == 0) ? 1 : 0;
  165871. if (cinfo->input_iMCU_row > cinfo->output_iMCU_row+delta)
  165872. break;
  165873. }
  165874. if ((*cinfo->inputctl->consume_input)(cinfo) == JPEG_SUSPENDED)
  165875. return JPEG_SUSPENDED;
  165876. }
  165877. /* OK, output from the virtual arrays. */
  165878. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  165879. ci++, compptr++) {
  165880. /* Don't bother to IDCT an uninteresting component. */
  165881. if (! compptr->component_needed)
  165882. continue;
  165883. /* Count non-dummy DCT block rows in this iMCU row. */
  165884. if (cinfo->output_iMCU_row < last_iMCU_row) {
  165885. block_rows = compptr->v_samp_factor;
  165886. access_rows = block_rows * 2; /* this and next iMCU row */
  165887. last_row = FALSE;
  165888. } else {
  165889. /* NB: can't use last_row_height here; it is input-side-dependent! */
  165890. block_rows = (int) (compptr->height_in_blocks % compptr->v_samp_factor);
  165891. if (block_rows == 0) block_rows = compptr->v_samp_factor;
  165892. access_rows = block_rows; /* this iMCU row only */
  165893. last_row = TRUE;
  165894. }
  165895. /* Align the virtual buffer for this component. */
  165896. if (cinfo->output_iMCU_row > 0) {
  165897. access_rows += compptr->v_samp_factor; /* prior iMCU row too */
  165898. buffer = (*cinfo->mem->access_virt_barray)
  165899. ((j_common_ptr) cinfo, coef->whole_image[ci],
  165900. (cinfo->output_iMCU_row - 1) * compptr->v_samp_factor,
  165901. (JDIMENSION) access_rows, FALSE);
  165902. buffer += compptr->v_samp_factor; /* point to current iMCU row */
  165903. first_row = FALSE;
  165904. } else {
  165905. buffer = (*cinfo->mem->access_virt_barray)
  165906. ((j_common_ptr) cinfo, coef->whole_image[ci],
  165907. (JDIMENSION) 0, (JDIMENSION) access_rows, FALSE);
  165908. first_row = TRUE;
  165909. }
  165910. /* Fetch component-dependent info */
  165911. coef_bits = coef->coef_bits_latch + (ci * SAVED_COEFS);
  165912. quanttbl = compptr->quant_table;
  165913. Q00 = quanttbl->quantval[0];
  165914. Q01 = quanttbl->quantval[Q01_POS];
  165915. Q10 = quanttbl->quantval[Q10_POS];
  165916. Q20 = quanttbl->quantval[Q20_POS];
  165917. Q11 = quanttbl->quantval[Q11_POS];
  165918. Q02 = quanttbl->quantval[Q02_POS];
  165919. inverse_DCT = cinfo->idct->inverse_DCT[ci];
  165920. output_ptr = output_buf[ci];
  165921. /* Loop over all DCT blocks to be processed. */
  165922. for (block_row = 0; block_row < block_rows; block_row++) {
  165923. buffer_ptr = buffer[block_row];
  165924. if (first_row && block_row == 0)
  165925. prev_block_row = buffer_ptr;
  165926. else
  165927. prev_block_row = buffer[block_row-1];
  165928. if (last_row && block_row == block_rows-1)
  165929. next_block_row = buffer_ptr;
  165930. else
  165931. next_block_row = buffer[block_row+1];
  165932. /* We fetch the surrounding DC values using a sliding-register approach.
  165933. * Initialize all nine here so as to do the right thing on narrow pics.
  165934. */
  165935. DC1 = DC2 = DC3 = (int) prev_block_row[0][0];
  165936. DC4 = DC5 = DC6 = (int) buffer_ptr[0][0];
  165937. DC7 = DC8 = DC9 = (int) next_block_row[0][0];
  165938. output_col = 0;
  165939. last_block_column = compptr->width_in_blocks - 1;
  165940. for (block_num = 0; block_num <= last_block_column; block_num++) {
  165941. /* Fetch current DCT block into workspace so we can modify it. */
  165942. jcopy_block_row(buffer_ptr, (JBLOCKROW) workspace, (JDIMENSION) 1);
  165943. /* Update DC values */
  165944. if (block_num < last_block_column) {
  165945. DC3 = (int) prev_block_row[1][0];
  165946. DC6 = (int) buffer_ptr[1][0];
  165947. DC9 = (int) next_block_row[1][0];
  165948. }
  165949. /* Compute coefficient estimates per K.8.
  165950. * An estimate is applied only if coefficient is still zero,
  165951. * and is not known to be fully accurate.
  165952. */
  165953. /* AC01 */
  165954. if ((Al=coef_bits[1]) != 0 && workspace[1] == 0) {
  165955. num = 36 * Q00 * (DC4 - DC6);
  165956. if (num >= 0) {
  165957. pred = (int) (((Q01<<7) + num) / (Q01<<8));
  165958. if (Al > 0 && pred >= (1<<Al))
  165959. pred = (1<<Al)-1;
  165960. } else {
  165961. pred = (int) (((Q01<<7) - num) / (Q01<<8));
  165962. if (Al > 0 && pred >= (1<<Al))
  165963. pred = (1<<Al)-1;
  165964. pred = -pred;
  165965. }
  165966. workspace[1] = (JCOEF) pred;
  165967. }
  165968. /* AC10 */
  165969. if ((Al=coef_bits[2]) != 0 && workspace[8] == 0) {
  165970. num = 36 * Q00 * (DC2 - DC8);
  165971. if (num >= 0) {
  165972. pred = (int) (((Q10<<7) + num) / (Q10<<8));
  165973. if (Al > 0 && pred >= (1<<Al))
  165974. pred = (1<<Al)-1;
  165975. } else {
  165976. pred = (int) (((Q10<<7) - num) / (Q10<<8));
  165977. if (Al > 0 && pred >= (1<<Al))
  165978. pred = (1<<Al)-1;
  165979. pred = -pred;
  165980. }
  165981. workspace[8] = (JCOEF) pred;
  165982. }
  165983. /* AC20 */
  165984. if ((Al=coef_bits[3]) != 0 && workspace[16] == 0) {
  165985. num = 9 * Q00 * (DC2 + DC8 - 2*DC5);
  165986. if (num >= 0) {
  165987. pred = (int) (((Q20<<7) + num) / (Q20<<8));
  165988. if (Al > 0 && pred >= (1<<Al))
  165989. pred = (1<<Al)-1;
  165990. } else {
  165991. pred = (int) (((Q20<<7) - num) / (Q20<<8));
  165992. if (Al > 0 && pred >= (1<<Al))
  165993. pred = (1<<Al)-1;
  165994. pred = -pred;
  165995. }
  165996. workspace[16] = (JCOEF) pred;
  165997. }
  165998. /* AC11 */
  165999. if ((Al=coef_bits[4]) != 0 && workspace[9] == 0) {
  166000. num = 5 * Q00 * (DC1 - DC3 - DC7 + DC9);
  166001. if (num >= 0) {
  166002. pred = (int) (((Q11<<7) + num) / (Q11<<8));
  166003. if (Al > 0 && pred >= (1<<Al))
  166004. pred = (1<<Al)-1;
  166005. } else {
  166006. pred = (int) (((Q11<<7) - num) / (Q11<<8));
  166007. if (Al > 0 && pred >= (1<<Al))
  166008. pred = (1<<Al)-1;
  166009. pred = -pred;
  166010. }
  166011. workspace[9] = (JCOEF) pred;
  166012. }
  166013. /* AC02 */
  166014. if ((Al=coef_bits[5]) != 0 && workspace[2] == 0) {
  166015. num = 9 * Q00 * (DC4 + DC6 - 2*DC5);
  166016. if (num >= 0) {
  166017. pred = (int) (((Q02<<7) + num) / (Q02<<8));
  166018. if (Al > 0 && pred >= (1<<Al))
  166019. pred = (1<<Al)-1;
  166020. } else {
  166021. pred = (int) (((Q02<<7) - num) / (Q02<<8));
  166022. if (Al > 0 && pred >= (1<<Al))
  166023. pred = (1<<Al)-1;
  166024. pred = -pred;
  166025. }
  166026. workspace[2] = (JCOEF) pred;
  166027. }
  166028. /* OK, do the IDCT */
  166029. (*inverse_DCT) (cinfo, compptr, (JCOEFPTR) workspace,
  166030. output_ptr, output_col);
  166031. /* Advance for next column */
  166032. DC1 = DC2; DC2 = DC3;
  166033. DC4 = DC5; DC5 = DC6;
  166034. DC7 = DC8; DC8 = DC9;
  166035. buffer_ptr++, prev_block_row++, next_block_row++;
  166036. output_col += compptr->DCT_scaled_size;
  166037. }
  166038. output_ptr += compptr->DCT_scaled_size;
  166039. }
  166040. }
  166041. if (++(cinfo->output_iMCU_row) < cinfo->total_iMCU_rows)
  166042. return JPEG_ROW_COMPLETED;
  166043. return JPEG_SCAN_COMPLETED;
  166044. }
  166045. #endif /* BLOCK_SMOOTHING_SUPPORTED */
  166046. /*
  166047. * Initialize coefficient buffer controller.
  166048. */
  166049. GLOBAL(void)
  166050. jinit_d_coef_controller (j_decompress_ptr cinfo, boolean need_full_buffer)
  166051. {
  166052. my_coef_ptr3 coef;
  166053. coef = (my_coef_ptr3)
  166054. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  166055. SIZEOF(my_coef_controller3));
  166056. cinfo->coef = (struct jpeg_d_coef_controller *) coef;
  166057. coef->pub.start_input_pass = start_input_pass;
  166058. coef->pub.start_output_pass = start_output_pass;
  166059. #ifdef BLOCK_SMOOTHING_SUPPORTED
  166060. coef->coef_bits_latch = NULL;
  166061. #endif
  166062. /* Create the coefficient buffer. */
  166063. if (need_full_buffer) {
  166064. #ifdef D_MULTISCAN_FILES_SUPPORTED
  166065. /* Allocate a full-image virtual array for each component, */
  166066. /* padded to a multiple of samp_factor DCT blocks in each direction. */
  166067. /* Note we ask for a pre-zeroed array. */
  166068. int ci, access_rows;
  166069. jpeg_component_info *compptr;
  166070. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  166071. ci++, compptr++) {
  166072. access_rows = compptr->v_samp_factor;
  166073. #ifdef BLOCK_SMOOTHING_SUPPORTED
  166074. /* If block smoothing could be used, need a bigger window */
  166075. if (cinfo->progressive_mode)
  166076. access_rows *= 3;
  166077. #endif
  166078. coef->whole_image[ci] = (*cinfo->mem->request_virt_barray)
  166079. ((j_common_ptr) cinfo, JPOOL_IMAGE, TRUE,
  166080. (JDIMENSION) jround_up((long) compptr->width_in_blocks,
  166081. (long) compptr->h_samp_factor),
  166082. (JDIMENSION) jround_up((long) compptr->height_in_blocks,
  166083. (long) compptr->v_samp_factor),
  166084. (JDIMENSION) access_rows);
  166085. }
  166086. coef->pub.consume_data = consume_data;
  166087. coef->pub.decompress_data = decompress_data;
  166088. coef->pub.coef_arrays = coef->whole_image; /* link to virtual arrays */
  166089. #else
  166090. ERREXIT(cinfo, JERR_NOT_COMPILED);
  166091. #endif
  166092. } else {
  166093. /* We only need a single-MCU buffer. */
  166094. JBLOCKROW buffer;
  166095. int i;
  166096. buffer = (JBLOCKROW)
  166097. (*cinfo->mem->alloc_large) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  166098. D_MAX_BLOCKS_IN_MCU * SIZEOF(JBLOCK));
  166099. for (i = 0; i < D_MAX_BLOCKS_IN_MCU; i++) {
  166100. coef->MCU_buffer[i] = buffer + i;
  166101. }
  166102. coef->pub.consume_data = dummy_consume_data;
  166103. coef->pub.decompress_data = decompress_onepass;
  166104. coef->pub.coef_arrays = NULL; /* flag for no virtual arrays */
  166105. }
  166106. }
  166107. /*** End of inlined file: jdcoefct.c ***/
  166108. #undef FIX
  166109. /*** Start of inlined file: jdcolor.c ***/
  166110. #define JPEG_INTERNALS
  166111. /* Private subobject */
  166112. typedef struct {
  166113. struct jpeg_color_deconverter pub; /* public fields */
  166114. /* Private state for YCC->RGB conversion */
  166115. int * Cr_r_tab; /* => table for Cr to R conversion */
  166116. int * Cb_b_tab; /* => table for Cb to B conversion */
  166117. INT32 * Cr_g_tab; /* => table for Cr to G conversion */
  166118. INT32 * Cb_g_tab; /* => table for Cb to G conversion */
  166119. } my_color_deconverter2;
  166120. typedef my_color_deconverter2 * my_cconvert_ptr2;
  166121. /**************** YCbCr -> RGB conversion: most common case **************/
  166122. /*
  166123. * YCbCr is defined per CCIR 601-1, except that Cb and Cr are
  166124. * normalized to the range 0..MAXJSAMPLE rather than -0.5 .. 0.5.
  166125. * The conversion equations to be implemented are therefore
  166126. * R = Y + 1.40200 * Cr
  166127. * G = Y - 0.34414 * Cb - 0.71414 * Cr
  166128. * B = Y + 1.77200 * Cb
  166129. * where Cb and Cr represent the incoming values less CENTERJSAMPLE.
  166130. * (These numbers are derived from TIFF 6.0 section 21, dated 3-June-92.)
  166131. *
  166132. * To avoid floating-point arithmetic, we represent the fractional constants
  166133. * as integers scaled up by 2^16 (about 4 digits precision); we have to divide
  166134. * the products by 2^16, with appropriate rounding, to get the correct answer.
  166135. * Notice that Y, being an integral input, does not contribute any fraction
  166136. * so it need not participate in the rounding.
  166137. *
  166138. * For even more speed, we avoid doing any multiplications in the inner loop
  166139. * by precalculating the constants times Cb and Cr for all possible values.
  166140. * For 8-bit JSAMPLEs this is very reasonable (only 256 entries per table);
  166141. * for 12-bit samples it is still acceptable. It's not very reasonable for
  166142. * 16-bit samples, but if you want lossless storage you shouldn't be changing
  166143. * colorspace anyway.
  166144. * The Cr=>R and Cb=>B values can be rounded to integers in advance; the
  166145. * values for the G calculation are left scaled up, since we must add them
  166146. * together before rounding.
  166147. */
  166148. #define SCALEBITS 16 /* speediest right-shift on some machines */
  166149. #define ONE_HALF ((INT32) 1 << (SCALEBITS-1))
  166150. #define FIX(x) ((INT32) ((x) * (1L<<SCALEBITS) + 0.5))
  166151. /*
  166152. * Initialize tables for YCC->RGB colorspace conversion.
  166153. */
  166154. LOCAL(void)
  166155. build_ycc_rgb_table (j_decompress_ptr cinfo)
  166156. {
  166157. my_cconvert_ptr2 cconvert = (my_cconvert_ptr2) cinfo->cconvert;
  166158. int i;
  166159. INT32 x;
  166160. SHIFT_TEMPS
  166161. cconvert->Cr_r_tab = (int *)
  166162. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  166163. (MAXJSAMPLE+1) * SIZEOF(int));
  166164. cconvert->Cb_b_tab = (int *)
  166165. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  166166. (MAXJSAMPLE+1) * SIZEOF(int));
  166167. cconvert->Cr_g_tab = (INT32 *)
  166168. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  166169. (MAXJSAMPLE+1) * SIZEOF(INT32));
  166170. cconvert->Cb_g_tab = (INT32 *)
  166171. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  166172. (MAXJSAMPLE+1) * SIZEOF(INT32));
  166173. for (i = 0, x = -CENTERJSAMPLE; i <= MAXJSAMPLE; i++, x++) {
  166174. /* i is the actual input pixel value, in the range 0..MAXJSAMPLE */
  166175. /* The Cb or Cr value we are thinking of is x = i - CENTERJSAMPLE */
  166176. /* Cr=>R value is nearest int to 1.40200 * x */
  166177. cconvert->Cr_r_tab[i] = (int)
  166178. RIGHT_SHIFT(FIX(1.40200) * x + ONE_HALF, SCALEBITS);
  166179. /* Cb=>B value is nearest int to 1.77200 * x */
  166180. cconvert->Cb_b_tab[i] = (int)
  166181. RIGHT_SHIFT(FIX(1.77200) * x + ONE_HALF, SCALEBITS);
  166182. /* Cr=>G value is scaled-up -0.71414 * x */
  166183. cconvert->Cr_g_tab[i] = (- FIX(0.71414)) * x;
  166184. /* Cb=>G value is scaled-up -0.34414 * x */
  166185. /* We also add in ONE_HALF so that need not do it in inner loop */
  166186. cconvert->Cb_g_tab[i] = (- FIX(0.34414)) * x + ONE_HALF;
  166187. }
  166188. }
  166189. /*
  166190. * Convert some rows of samples to the output colorspace.
  166191. *
  166192. * Note that we change from noninterleaved, one-plane-per-component format
  166193. * to interleaved-pixel format. The output buffer is therefore three times
  166194. * as wide as the input buffer.
  166195. * A starting row offset is provided only for the input buffer. The caller
  166196. * can easily adjust the passed output_buf value to accommodate any row
  166197. * offset required on that side.
  166198. */
  166199. METHODDEF(void)
  166200. ycc_rgb_convert (j_decompress_ptr cinfo,
  166201. JSAMPIMAGE input_buf, JDIMENSION input_row,
  166202. JSAMPARRAY output_buf, int num_rows)
  166203. {
  166204. my_cconvert_ptr2 cconvert = (my_cconvert_ptr2) cinfo->cconvert;
  166205. register int y, cb, cr;
  166206. register JSAMPROW outptr;
  166207. register JSAMPROW inptr0, inptr1, inptr2;
  166208. register JDIMENSION col;
  166209. JDIMENSION num_cols = cinfo->output_width;
  166210. /* copy these pointers into registers if possible */
  166211. register JSAMPLE * range_limit = cinfo->sample_range_limit;
  166212. register int * Crrtab = cconvert->Cr_r_tab;
  166213. register int * Cbbtab = cconvert->Cb_b_tab;
  166214. register INT32 * Crgtab = cconvert->Cr_g_tab;
  166215. register INT32 * Cbgtab = cconvert->Cb_g_tab;
  166216. SHIFT_TEMPS
  166217. while (--num_rows >= 0) {
  166218. inptr0 = input_buf[0][input_row];
  166219. inptr1 = input_buf[1][input_row];
  166220. inptr2 = input_buf[2][input_row];
  166221. input_row++;
  166222. outptr = *output_buf++;
  166223. for (col = 0; col < num_cols; col++) {
  166224. y = GETJSAMPLE(inptr0[col]);
  166225. cb = GETJSAMPLE(inptr1[col]);
  166226. cr = GETJSAMPLE(inptr2[col]);
  166227. /* Range-limiting is essential due to noise introduced by DCT losses. */
  166228. outptr[RGB_RED] = range_limit[y + Crrtab[cr]];
  166229. outptr[RGB_GREEN] = range_limit[y +
  166230. ((int) RIGHT_SHIFT(Cbgtab[cb] + Crgtab[cr],
  166231. SCALEBITS))];
  166232. outptr[RGB_BLUE] = range_limit[y + Cbbtab[cb]];
  166233. outptr += RGB_PIXELSIZE;
  166234. }
  166235. }
  166236. }
  166237. /**************** Cases other than YCbCr -> RGB **************/
  166238. /*
  166239. * Color conversion for no colorspace change: just copy the data,
  166240. * converting from separate-planes to interleaved representation.
  166241. */
  166242. METHODDEF(void)
  166243. null_convert2 (j_decompress_ptr cinfo,
  166244. JSAMPIMAGE input_buf, JDIMENSION input_row,
  166245. JSAMPARRAY output_buf, int num_rows)
  166246. {
  166247. register JSAMPROW inptr, outptr;
  166248. register JDIMENSION count;
  166249. register int num_components = cinfo->num_components;
  166250. JDIMENSION num_cols = cinfo->output_width;
  166251. int ci;
  166252. while (--num_rows >= 0) {
  166253. for (ci = 0; ci < num_components; ci++) {
  166254. inptr = input_buf[ci][input_row];
  166255. outptr = output_buf[0] + ci;
  166256. for (count = num_cols; count > 0; count--) {
  166257. *outptr = *inptr++; /* needn't bother with GETJSAMPLE() here */
  166258. outptr += num_components;
  166259. }
  166260. }
  166261. input_row++;
  166262. output_buf++;
  166263. }
  166264. }
  166265. /*
  166266. * Color conversion for grayscale: just copy the data.
  166267. * This also works for YCbCr -> grayscale conversion, in which
  166268. * we just copy the Y (luminance) component and ignore chrominance.
  166269. */
  166270. METHODDEF(void)
  166271. grayscale_convert2 (j_decompress_ptr cinfo,
  166272. JSAMPIMAGE input_buf, JDIMENSION input_row,
  166273. JSAMPARRAY output_buf, int num_rows)
  166274. {
  166275. jcopy_sample_rows(input_buf[0], (int) input_row, output_buf, 0,
  166276. num_rows, cinfo->output_width);
  166277. }
  166278. /*
  166279. * Convert grayscale to RGB: just duplicate the graylevel three times.
  166280. * This is provided to support applications that don't want to cope
  166281. * with grayscale as a separate case.
  166282. */
  166283. METHODDEF(void)
  166284. gray_rgb_convert (j_decompress_ptr cinfo,
  166285. JSAMPIMAGE input_buf, JDIMENSION input_row,
  166286. JSAMPARRAY output_buf, int num_rows)
  166287. {
  166288. register JSAMPROW inptr, outptr;
  166289. register JDIMENSION col;
  166290. JDIMENSION num_cols = cinfo->output_width;
  166291. while (--num_rows >= 0) {
  166292. inptr = input_buf[0][input_row++];
  166293. outptr = *output_buf++;
  166294. for (col = 0; col < num_cols; col++) {
  166295. /* We can dispense with GETJSAMPLE() here */
  166296. outptr[RGB_RED] = outptr[RGB_GREEN] = outptr[RGB_BLUE] = inptr[col];
  166297. outptr += RGB_PIXELSIZE;
  166298. }
  166299. }
  166300. }
  166301. /*
  166302. * Adobe-style YCCK->CMYK conversion.
  166303. * We convert YCbCr to R=1-C, G=1-M, and B=1-Y using the same
  166304. * conversion as above, while passing K (black) unchanged.
  166305. * We assume build_ycc_rgb_table has been called.
  166306. */
  166307. METHODDEF(void)
  166308. ycck_cmyk_convert (j_decompress_ptr cinfo,
  166309. JSAMPIMAGE input_buf, JDIMENSION input_row,
  166310. JSAMPARRAY output_buf, int num_rows)
  166311. {
  166312. my_cconvert_ptr2 cconvert = (my_cconvert_ptr2) cinfo->cconvert;
  166313. register int y, cb, cr;
  166314. register JSAMPROW outptr;
  166315. register JSAMPROW inptr0, inptr1, inptr2, inptr3;
  166316. register JDIMENSION col;
  166317. JDIMENSION num_cols = cinfo->output_width;
  166318. /* copy these pointers into registers if possible */
  166319. register JSAMPLE * range_limit = cinfo->sample_range_limit;
  166320. register int * Crrtab = cconvert->Cr_r_tab;
  166321. register int * Cbbtab = cconvert->Cb_b_tab;
  166322. register INT32 * Crgtab = cconvert->Cr_g_tab;
  166323. register INT32 * Cbgtab = cconvert->Cb_g_tab;
  166324. SHIFT_TEMPS
  166325. while (--num_rows >= 0) {
  166326. inptr0 = input_buf[0][input_row];
  166327. inptr1 = input_buf[1][input_row];
  166328. inptr2 = input_buf[2][input_row];
  166329. inptr3 = input_buf[3][input_row];
  166330. input_row++;
  166331. outptr = *output_buf++;
  166332. for (col = 0; col < num_cols; col++) {
  166333. y = GETJSAMPLE(inptr0[col]);
  166334. cb = GETJSAMPLE(inptr1[col]);
  166335. cr = GETJSAMPLE(inptr2[col]);
  166336. /* Range-limiting is essential due to noise introduced by DCT losses. */
  166337. outptr[0] = range_limit[MAXJSAMPLE - (y + Crrtab[cr])]; /* red */
  166338. outptr[1] = range_limit[MAXJSAMPLE - (y + /* green */
  166339. ((int) RIGHT_SHIFT(Cbgtab[cb] + Crgtab[cr],
  166340. SCALEBITS)))];
  166341. outptr[2] = range_limit[MAXJSAMPLE - (y + Cbbtab[cb])]; /* blue */
  166342. /* K passes through unchanged */
  166343. outptr[3] = inptr3[col]; /* don't need GETJSAMPLE here */
  166344. outptr += 4;
  166345. }
  166346. }
  166347. }
  166348. /*
  166349. * Empty method for start_pass.
  166350. */
  166351. METHODDEF(void)
  166352. start_pass_dcolor (j_decompress_ptr)
  166353. {
  166354. /* no work needed */
  166355. }
  166356. /*
  166357. * Module initialization routine for output colorspace conversion.
  166358. */
  166359. GLOBAL(void)
  166360. jinit_color_deconverter (j_decompress_ptr cinfo)
  166361. {
  166362. my_cconvert_ptr2 cconvert;
  166363. int ci;
  166364. cconvert = (my_cconvert_ptr2)
  166365. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  166366. SIZEOF(my_color_deconverter2));
  166367. cinfo->cconvert = (struct jpeg_color_deconverter *) cconvert;
  166368. cconvert->pub.start_pass = start_pass_dcolor;
  166369. /* Make sure num_components agrees with jpeg_color_space */
  166370. switch (cinfo->jpeg_color_space) {
  166371. case JCS_GRAYSCALE:
  166372. if (cinfo->num_components != 1)
  166373. ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
  166374. break;
  166375. case JCS_RGB:
  166376. case JCS_YCbCr:
  166377. if (cinfo->num_components != 3)
  166378. ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
  166379. break;
  166380. case JCS_CMYK:
  166381. case JCS_YCCK:
  166382. if (cinfo->num_components != 4)
  166383. ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
  166384. break;
  166385. default: /* JCS_UNKNOWN can be anything */
  166386. if (cinfo->num_components < 1)
  166387. ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
  166388. break;
  166389. }
  166390. /* Set out_color_components and conversion method based on requested space.
  166391. * Also clear the component_needed flags for any unused components,
  166392. * so that earlier pipeline stages can avoid useless computation.
  166393. */
  166394. switch (cinfo->out_color_space) {
  166395. case JCS_GRAYSCALE:
  166396. cinfo->out_color_components = 1;
  166397. if (cinfo->jpeg_color_space == JCS_GRAYSCALE ||
  166398. cinfo->jpeg_color_space == JCS_YCbCr) {
  166399. cconvert->pub.color_convert = grayscale_convert2;
  166400. /* For color->grayscale conversion, only the Y (0) component is needed */
  166401. for (ci = 1; ci < cinfo->num_components; ci++)
  166402. cinfo->comp_info[ci].component_needed = FALSE;
  166403. } else
  166404. ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
  166405. break;
  166406. case JCS_RGB:
  166407. cinfo->out_color_components = RGB_PIXELSIZE;
  166408. if (cinfo->jpeg_color_space == JCS_YCbCr) {
  166409. cconvert->pub.color_convert = ycc_rgb_convert;
  166410. build_ycc_rgb_table(cinfo);
  166411. } else if (cinfo->jpeg_color_space == JCS_GRAYSCALE) {
  166412. cconvert->pub.color_convert = gray_rgb_convert;
  166413. } else if (cinfo->jpeg_color_space == JCS_RGB && RGB_PIXELSIZE == 3) {
  166414. cconvert->pub.color_convert = null_convert2;
  166415. } else
  166416. ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
  166417. break;
  166418. case JCS_CMYK:
  166419. cinfo->out_color_components = 4;
  166420. if (cinfo->jpeg_color_space == JCS_YCCK) {
  166421. cconvert->pub.color_convert = ycck_cmyk_convert;
  166422. build_ycc_rgb_table(cinfo);
  166423. } else if (cinfo->jpeg_color_space == JCS_CMYK) {
  166424. cconvert->pub.color_convert = null_convert2;
  166425. } else
  166426. ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
  166427. break;
  166428. default:
  166429. /* Permit null conversion to same output space */
  166430. if (cinfo->out_color_space == cinfo->jpeg_color_space) {
  166431. cinfo->out_color_components = cinfo->num_components;
  166432. cconvert->pub.color_convert = null_convert2;
  166433. } else /* unsupported non-null conversion */
  166434. ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
  166435. break;
  166436. }
  166437. if (cinfo->quantize_colors)
  166438. cinfo->output_components = 1; /* single colormapped output component */
  166439. else
  166440. cinfo->output_components = cinfo->out_color_components;
  166441. }
  166442. /*** End of inlined file: jdcolor.c ***/
  166443. #undef FIX
  166444. /*** Start of inlined file: jddctmgr.c ***/
  166445. #define JPEG_INTERNALS
  166446. /*
  166447. * The decompressor input side (jdinput.c) saves away the appropriate
  166448. * quantization table for each component at the start of the first scan
  166449. * involving that component. (This is necessary in order to correctly
  166450. * decode files that reuse Q-table slots.)
  166451. * When we are ready to make an output pass, the saved Q-table is converted
  166452. * to a multiplier table that will actually be used by the IDCT routine.
  166453. * The multiplier table contents are IDCT-method-dependent. To support
  166454. * application changes in IDCT method between scans, we can remake the
  166455. * multiplier tables if necessary.
  166456. * In buffered-image mode, the first output pass may occur before any data
  166457. * has been seen for some components, and thus before their Q-tables have
  166458. * been saved away. To handle this case, multiplier tables are preset
  166459. * to zeroes; the result of the IDCT will be a neutral gray level.
  166460. */
  166461. /* Private subobject for this module */
  166462. typedef struct {
  166463. struct jpeg_inverse_dct pub; /* public fields */
  166464. /* This array contains the IDCT method code that each multiplier table
  166465. * is currently set up for, or -1 if it's not yet set up.
  166466. * The actual multiplier tables are pointed to by dct_table in the
  166467. * per-component comp_info structures.
  166468. */
  166469. int cur_method[MAX_COMPONENTS];
  166470. } my_idct_controller;
  166471. typedef my_idct_controller * my_idct_ptr;
  166472. /* Allocated multiplier tables: big enough for any supported variant */
  166473. typedef union {
  166474. ISLOW_MULT_TYPE islow_array[DCTSIZE2];
  166475. #ifdef DCT_IFAST_SUPPORTED
  166476. IFAST_MULT_TYPE ifast_array[DCTSIZE2];
  166477. #endif
  166478. #ifdef DCT_FLOAT_SUPPORTED
  166479. FLOAT_MULT_TYPE float_array[DCTSIZE2];
  166480. #endif
  166481. } multiplier_table;
  166482. /* The current scaled-IDCT routines require ISLOW-style multiplier tables,
  166483. * so be sure to compile that code if either ISLOW or SCALING is requested.
  166484. */
  166485. #ifdef DCT_ISLOW_SUPPORTED
  166486. #define PROVIDE_ISLOW_TABLES
  166487. #else
  166488. #ifdef IDCT_SCALING_SUPPORTED
  166489. #define PROVIDE_ISLOW_TABLES
  166490. #endif
  166491. #endif
  166492. /*
  166493. * Prepare for an output pass.
  166494. * Here we select the proper IDCT routine for each component and build
  166495. * a matching multiplier table.
  166496. */
  166497. METHODDEF(void)
  166498. start_pass (j_decompress_ptr cinfo)
  166499. {
  166500. my_idct_ptr idct = (my_idct_ptr) cinfo->idct;
  166501. int ci, i;
  166502. jpeg_component_info *compptr;
  166503. int method = 0;
  166504. inverse_DCT_method_ptr method_ptr = NULL;
  166505. JQUANT_TBL * qtbl;
  166506. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  166507. ci++, compptr++) {
  166508. /* Select the proper IDCT routine for this component's scaling */
  166509. switch (compptr->DCT_scaled_size) {
  166510. #ifdef IDCT_SCALING_SUPPORTED
  166511. case 1:
  166512. method_ptr = jpeg_idct_1x1;
  166513. method = JDCT_ISLOW; /* jidctred uses islow-style table */
  166514. break;
  166515. case 2:
  166516. method_ptr = jpeg_idct_2x2;
  166517. method = JDCT_ISLOW; /* jidctred uses islow-style table */
  166518. break;
  166519. case 4:
  166520. method_ptr = jpeg_idct_4x4;
  166521. method = JDCT_ISLOW; /* jidctred uses islow-style table */
  166522. break;
  166523. #endif
  166524. case DCTSIZE:
  166525. switch (cinfo->dct_method) {
  166526. #ifdef DCT_ISLOW_SUPPORTED
  166527. case JDCT_ISLOW:
  166528. method_ptr = jpeg_idct_islow;
  166529. method = JDCT_ISLOW;
  166530. break;
  166531. #endif
  166532. #ifdef DCT_IFAST_SUPPORTED
  166533. case JDCT_IFAST:
  166534. method_ptr = jpeg_idct_ifast;
  166535. method = JDCT_IFAST;
  166536. break;
  166537. #endif
  166538. #ifdef DCT_FLOAT_SUPPORTED
  166539. case JDCT_FLOAT:
  166540. method_ptr = jpeg_idct_float;
  166541. method = JDCT_FLOAT;
  166542. break;
  166543. #endif
  166544. default:
  166545. ERREXIT(cinfo, JERR_NOT_COMPILED);
  166546. break;
  166547. }
  166548. break;
  166549. default:
  166550. ERREXIT1(cinfo, JERR_BAD_DCTSIZE, compptr->DCT_scaled_size);
  166551. break;
  166552. }
  166553. idct->pub.inverse_DCT[ci] = method_ptr;
  166554. /* Create multiplier table from quant table.
  166555. * However, we can skip this if the component is uninteresting
  166556. * or if we already built the table. Also, if no quant table
  166557. * has yet been saved for the component, we leave the
  166558. * multiplier table all-zero; we'll be reading zeroes from the
  166559. * coefficient controller's buffer anyway.
  166560. */
  166561. if (! compptr->component_needed || idct->cur_method[ci] == method)
  166562. continue;
  166563. qtbl = compptr->quant_table;
  166564. if (qtbl == NULL) /* happens if no data yet for component */
  166565. continue;
  166566. idct->cur_method[ci] = method;
  166567. switch (method) {
  166568. #ifdef PROVIDE_ISLOW_TABLES
  166569. case JDCT_ISLOW:
  166570. {
  166571. /* For LL&M IDCT method, multipliers are equal to raw quantization
  166572. * coefficients, but are stored as ints to ensure access efficiency.
  166573. */
  166574. ISLOW_MULT_TYPE * ismtbl = (ISLOW_MULT_TYPE *) compptr->dct_table;
  166575. for (i = 0; i < DCTSIZE2; i++) {
  166576. ismtbl[i] = (ISLOW_MULT_TYPE) qtbl->quantval[i];
  166577. }
  166578. }
  166579. break;
  166580. #endif
  166581. #ifdef DCT_IFAST_SUPPORTED
  166582. case JDCT_IFAST:
  166583. {
  166584. /* For AA&N IDCT method, multipliers are equal to quantization
  166585. * coefficients scaled by scalefactor[row]*scalefactor[col], where
  166586. * scalefactor[0] = 1
  166587. * scalefactor[k] = cos(k*PI/16) * sqrt(2) for k=1..7
  166588. * For integer operation, the multiplier table is to be scaled by
  166589. * IFAST_SCALE_BITS.
  166590. */
  166591. IFAST_MULT_TYPE * ifmtbl = (IFAST_MULT_TYPE *) compptr->dct_table;
  166592. #define CONST_BITS 14
  166593. static const INT16 aanscales[DCTSIZE2] = {
  166594. /* precomputed values scaled up by 14 bits */
  166595. 16384, 22725, 21407, 19266, 16384, 12873, 8867, 4520,
  166596. 22725, 31521, 29692, 26722, 22725, 17855, 12299, 6270,
  166597. 21407, 29692, 27969, 25172, 21407, 16819, 11585, 5906,
  166598. 19266, 26722, 25172, 22654, 19266, 15137, 10426, 5315,
  166599. 16384, 22725, 21407, 19266, 16384, 12873, 8867, 4520,
  166600. 12873, 17855, 16819, 15137, 12873, 10114, 6967, 3552,
  166601. 8867, 12299, 11585, 10426, 8867, 6967, 4799, 2446,
  166602. 4520, 6270, 5906, 5315, 4520, 3552, 2446, 1247
  166603. };
  166604. SHIFT_TEMPS
  166605. for (i = 0; i < DCTSIZE2; i++) {
  166606. ifmtbl[i] = (IFAST_MULT_TYPE)
  166607. DESCALE(MULTIPLY16V16((INT32) qtbl->quantval[i],
  166608. (INT32) aanscales[i]),
  166609. CONST_BITS-IFAST_SCALE_BITS);
  166610. }
  166611. }
  166612. break;
  166613. #endif
  166614. #ifdef DCT_FLOAT_SUPPORTED
  166615. case JDCT_FLOAT:
  166616. {
  166617. /* For float AA&N IDCT method, multipliers are equal to quantization
  166618. * coefficients scaled by scalefactor[row]*scalefactor[col], where
  166619. * scalefactor[0] = 1
  166620. * scalefactor[k] = cos(k*PI/16) * sqrt(2) for k=1..7
  166621. */
  166622. FLOAT_MULT_TYPE * fmtbl = (FLOAT_MULT_TYPE *) compptr->dct_table;
  166623. int row, col;
  166624. static const double aanscalefactor[DCTSIZE] = {
  166625. 1.0, 1.387039845, 1.306562965, 1.175875602,
  166626. 1.0, 0.785694958, 0.541196100, 0.275899379
  166627. };
  166628. i = 0;
  166629. for (row = 0; row < DCTSIZE; row++) {
  166630. for (col = 0; col < DCTSIZE; col++) {
  166631. fmtbl[i] = (FLOAT_MULT_TYPE)
  166632. ((double) qtbl->quantval[i] *
  166633. aanscalefactor[row] * aanscalefactor[col]);
  166634. i++;
  166635. }
  166636. }
  166637. }
  166638. break;
  166639. #endif
  166640. default:
  166641. ERREXIT(cinfo, JERR_NOT_COMPILED);
  166642. break;
  166643. }
  166644. }
  166645. }
  166646. /*
  166647. * Initialize IDCT manager.
  166648. */
  166649. GLOBAL(void)
  166650. jinit_inverse_dct (j_decompress_ptr cinfo)
  166651. {
  166652. my_idct_ptr idct;
  166653. int ci;
  166654. jpeg_component_info *compptr;
  166655. idct = (my_idct_ptr)
  166656. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  166657. SIZEOF(my_idct_controller));
  166658. cinfo->idct = (struct jpeg_inverse_dct *) idct;
  166659. idct->pub.start_pass = start_pass;
  166660. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  166661. ci++, compptr++) {
  166662. /* Allocate and pre-zero a multiplier table for each component */
  166663. compptr->dct_table =
  166664. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  166665. SIZEOF(multiplier_table));
  166666. MEMZERO(compptr->dct_table, SIZEOF(multiplier_table));
  166667. /* Mark multiplier table not yet set up for any method */
  166668. idct->cur_method[ci] = -1;
  166669. }
  166670. }
  166671. /*** End of inlined file: jddctmgr.c ***/
  166672. #undef CONST_BITS
  166673. #undef ASSIGN_STATE
  166674. /*** Start of inlined file: jdhuff.c ***/
  166675. #define JPEG_INTERNALS
  166676. /*** Start of inlined file: jdhuff.h ***/
  166677. /* Short forms of external names for systems with brain-damaged linkers. */
  166678. #ifndef __jdhuff_h__
  166679. #define __jdhuff_h__
  166680. #ifdef NEED_SHORT_EXTERNAL_NAMES
  166681. #define jpeg_make_d_derived_tbl jMkDDerived
  166682. #define jpeg_fill_bit_buffer jFilBitBuf
  166683. #define jpeg_huff_decode jHufDecode
  166684. #endif /* NEED_SHORT_EXTERNAL_NAMES */
  166685. /* Derived data constructed for each Huffman table */
  166686. #define HUFF_LOOKAHEAD 8 /* # of bits of lookahead */
  166687. typedef struct {
  166688. /* Basic tables: (element [0] of each array is unused) */
  166689. INT32 maxcode[18]; /* largest code of length k (-1 if none) */
  166690. /* (maxcode[17] is a sentinel to ensure jpeg_huff_decode terminates) */
  166691. INT32 valoffset[17]; /* huffval[] offset for codes of length k */
  166692. /* valoffset[k] = huffval[] index of 1st symbol of code length k, less
  166693. * the smallest code of length k; so given a code of length k, the
  166694. * corresponding symbol is huffval[code + valoffset[k]]
  166695. */
  166696. /* Link to public Huffman table (needed only in jpeg_huff_decode) */
  166697. JHUFF_TBL *pub;
  166698. /* Lookahead tables: indexed by the next HUFF_LOOKAHEAD bits of
  166699. * the input data stream. If the next Huffman code is no more
  166700. * than HUFF_LOOKAHEAD bits long, we can obtain its length and
  166701. * the corresponding symbol directly from these tables.
  166702. */
  166703. int look_nbits[1<<HUFF_LOOKAHEAD]; /* # bits, or 0 if too long */
  166704. UINT8 look_sym[1<<HUFF_LOOKAHEAD]; /* symbol, or unused */
  166705. } d_derived_tbl;
  166706. /* Expand a Huffman table definition into the derived format */
  166707. EXTERN(void) jpeg_make_d_derived_tbl
  166708. JPP((j_decompress_ptr cinfo, boolean isDC, int tblno,
  166709. d_derived_tbl ** pdtbl));
  166710. /*
  166711. * Fetching the next N bits from the input stream is a time-critical operation
  166712. * for the Huffman decoders. We implement it with a combination of inline
  166713. * macros and out-of-line subroutines. Note that N (the number of bits
  166714. * demanded at one time) never exceeds 15 for JPEG use.
  166715. *
  166716. * We read source bytes into get_buffer and dole out bits as needed.
  166717. * If get_buffer already contains enough bits, they are fetched in-line
  166718. * by the macros CHECK_BIT_BUFFER and GET_BITS. When there aren't enough
  166719. * bits, jpeg_fill_bit_buffer is called; it will attempt to fill get_buffer
  166720. * as full as possible (not just to the number of bits needed; this
  166721. * prefetching reduces the overhead cost of calling jpeg_fill_bit_buffer).
  166722. * Note that jpeg_fill_bit_buffer may return FALSE to indicate suspension.
  166723. * On TRUE return, jpeg_fill_bit_buffer guarantees that get_buffer contains
  166724. * at least the requested number of bits --- dummy zeroes are inserted if
  166725. * necessary.
  166726. */
  166727. typedef INT32 bit_buf_type; /* type of bit-extraction buffer */
  166728. #define BIT_BUF_SIZE 32 /* size of buffer in bits */
  166729. /* If long is > 32 bits on your machine, and shifting/masking longs is
  166730. * reasonably fast, making bit_buf_type be long and setting BIT_BUF_SIZE
  166731. * appropriately should be a win. Unfortunately we can't define the size
  166732. * with something like #define BIT_BUF_SIZE (sizeof(bit_buf_type)*8)
  166733. * because not all machines measure sizeof in 8-bit bytes.
  166734. */
  166735. typedef struct { /* Bitreading state saved across MCUs */
  166736. bit_buf_type get_buffer; /* current bit-extraction buffer */
  166737. int bits_left; /* # of unused bits in it */
  166738. } bitread_perm_state;
  166739. typedef struct { /* Bitreading working state within an MCU */
  166740. /* Current data source location */
  166741. /* We need a copy, rather than munging the original, in case of suspension */
  166742. const JOCTET * next_input_byte; /* => next byte to read from source */
  166743. size_t bytes_in_buffer; /* # of bytes remaining in source buffer */
  166744. /* Bit input buffer --- note these values are kept in register variables,
  166745. * not in this struct, inside the inner loops.
  166746. */
  166747. bit_buf_type get_buffer; /* current bit-extraction buffer */
  166748. int bits_left; /* # of unused bits in it */
  166749. /* Pointer needed by jpeg_fill_bit_buffer. */
  166750. j_decompress_ptr cinfo; /* back link to decompress master record */
  166751. } bitread_working_state;
  166752. /* Macros to declare and load/save bitread local variables. */
  166753. #define BITREAD_STATE_VARS \
  166754. register bit_buf_type get_buffer; \
  166755. register int bits_left; \
  166756. bitread_working_state br_state
  166757. #define BITREAD_LOAD_STATE(cinfop,permstate) \
  166758. br_state.cinfo = cinfop; \
  166759. br_state.next_input_byte = cinfop->src->next_input_byte; \
  166760. br_state.bytes_in_buffer = cinfop->src->bytes_in_buffer; \
  166761. get_buffer = permstate.get_buffer; \
  166762. bits_left = permstate.bits_left;
  166763. #define BITREAD_SAVE_STATE(cinfop,permstate) \
  166764. cinfop->src->next_input_byte = br_state.next_input_byte; \
  166765. cinfop->src->bytes_in_buffer = br_state.bytes_in_buffer; \
  166766. permstate.get_buffer = get_buffer; \
  166767. permstate.bits_left = bits_left
  166768. /*
  166769. * These macros provide the in-line portion of bit fetching.
  166770. * Use CHECK_BIT_BUFFER to ensure there are N bits in get_buffer
  166771. * before using GET_BITS, PEEK_BITS, or DROP_BITS.
  166772. * The variables get_buffer and bits_left are assumed to be locals,
  166773. * but the state struct might not be (jpeg_huff_decode needs this).
  166774. * CHECK_BIT_BUFFER(state,n,action);
  166775. * Ensure there are N bits in get_buffer; if suspend, take action.
  166776. * val = GET_BITS(n);
  166777. * Fetch next N bits.
  166778. * val = PEEK_BITS(n);
  166779. * Fetch next N bits without removing them from the buffer.
  166780. * DROP_BITS(n);
  166781. * Discard next N bits.
  166782. * The value N should be a simple variable, not an expression, because it
  166783. * is evaluated multiple times.
  166784. */
  166785. #define CHECK_BIT_BUFFER(state,nbits,action) \
  166786. { if (bits_left < (nbits)) { \
  166787. if (! jpeg_fill_bit_buffer(&(state),get_buffer,bits_left,nbits)) \
  166788. { action; } \
  166789. get_buffer = (state).get_buffer; bits_left = (state).bits_left; } }
  166790. #define GET_BITS(nbits) \
  166791. (((int) (get_buffer >> (bits_left -= (nbits)))) & ((1<<(nbits))-1))
  166792. #define PEEK_BITS(nbits) \
  166793. (((int) (get_buffer >> (bits_left - (nbits)))) & ((1<<(nbits))-1))
  166794. #define DROP_BITS(nbits) \
  166795. (bits_left -= (nbits))
  166796. /* Load up the bit buffer to a depth of at least nbits */
  166797. EXTERN(boolean) jpeg_fill_bit_buffer
  166798. JPP((bitread_working_state * state, register bit_buf_type get_buffer,
  166799. register int bits_left, int nbits));
  166800. /*
  166801. * Code for extracting next Huffman-coded symbol from input bit stream.
  166802. * Again, this is time-critical and we make the main paths be macros.
  166803. *
  166804. * We use a lookahead table to process codes of up to HUFF_LOOKAHEAD bits
  166805. * without looping. Usually, more than 95% of the Huffman codes will be 8
  166806. * or fewer bits long. The few overlength codes are handled with a loop,
  166807. * which need not be inline code.
  166808. *
  166809. * Notes about the HUFF_DECODE macro:
  166810. * 1. Near the end of the data segment, we may fail to get enough bits
  166811. * for a lookahead. In that case, we do it the hard way.
  166812. * 2. If the lookahead table contains no entry, the next code must be
  166813. * more than HUFF_LOOKAHEAD bits long.
  166814. * 3. jpeg_huff_decode returns -1 if forced to suspend.
  166815. */
  166816. #define HUFF_DECODE(result,state,htbl,failaction,slowlabel) \
  166817. { register int nb, look; \
  166818. if (bits_left < HUFF_LOOKAHEAD) { \
  166819. if (! jpeg_fill_bit_buffer(&state,get_buffer,bits_left, 0)) {failaction;} \
  166820. get_buffer = state.get_buffer; bits_left = state.bits_left; \
  166821. if (bits_left < HUFF_LOOKAHEAD) { \
  166822. nb = 1; goto slowlabel; \
  166823. } \
  166824. } \
  166825. look = PEEK_BITS(HUFF_LOOKAHEAD); \
  166826. if ((nb = htbl->look_nbits[look]) != 0) { \
  166827. DROP_BITS(nb); \
  166828. result = htbl->look_sym[look]; \
  166829. } else { \
  166830. nb = HUFF_LOOKAHEAD+1; \
  166831. slowlabel: \
  166832. if ((result=jpeg_huff_decode(&state,get_buffer,bits_left,htbl,nb)) < 0) \
  166833. { failaction; } \
  166834. get_buffer = state.get_buffer; bits_left = state.bits_left; \
  166835. } \
  166836. }
  166837. /* Out-of-line case for Huffman code fetching */
  166838. EXTERN(int) jpeg_huff_decode
  166839. JPP((bitread_working_state * state, register bit_buf_type get_buffer,
  166840. register int bits_left, d_derived_tbl * htbl, int min_bits));
  166841. #endif
  166842. /*** End of inlined file: jdhuff.h ***/
  166843. /* Declarations shared with jdphuff.c */
  166844. /*
  166845. * Expanded entropy decoder object for Huffman decoding.
  166846. *
  166847. * The savable_state subrecord contains fields that change within an MCU,
  166848. * but must not be updated permanently until we complete the MCU.
  166849. */
  166850. typedef struct {
  166851. int last_dc_val[MAX_COMPS_IN_SCAN]; /* last DC coef for each component */
  166852. } savable_state2;
  166853. /* This macro is to work around compilers with missing or broken
  166854. * structure assignment. You'll need to fix this code if you have
  166855. * such a compiler and you change MAX_COMPS_IN_SCAN.
  166856. */
  166857. #ifndef NO_STRUCT_ASSIGN
  166858. #define ASSIGN_STATE(dest,src) ((dest) = (src))
  166859. #else
  166860. #if MAX_COMPS_IN_SCAN == 4
  166861. #define ASSIGN_STATE(dest,src) \
  166862. ((dest).last_dc_val[0] = (src).last_dc_val[0], \
  166863. (dest).last_dc_val[1] = (src).last_dc_val[1], \
  166864. (dest).last_dc_val[2] = (src).last_dc_val[2], \
  166865. (dest).last_dc_val[3] = (src).last_dc_val[3])
  166866. #endif
  166867. #endif
  166868. typedef struct {
  166869. struct jpeg_entropy_decoder pub; /* public fields */
  166870. /* These fields are loaded into local variables at start of each MCU.
  166871. * In case of suspension, we exit WITHOUT updating them.
  166872. */
  166873. bitread_perm_state bitstate; /* Bit buffer at start of MCU */
  166874. savable_state2 saved; /* Other state at start of MCU */
  166875. /* These fields are NOT loaded into local working state. */
  166876. unsigned int restarts_to_go; /* MCUs left in this restart interval */
  166877. /* Pointers to derived tables (these workspaces have image lifespan) */
  166878. d_derived_tbl * dc_derived_tbls[NUM_HUFF_TBLS];
  166879. d_derived_tbl * ac_derived_tbls[NUM_HUFF_TBLS];
  166880. /* Precalculated info set up by start_pass for use in decode_mcu: */
  166881. /* Pointers to derived tables to be used for each block within an MCU */
  166882. d_derived_tbl * dc_cur_tbls[D_MAX_BLOCKS_IN_MCU];
  166883. d_derived_tbl * ac_cur_tbls[D_MAX_BLOCKS_IN_MCU];
  166884. /* Whether we care about the DC and AC coefficient values for each block */
  166885. boolean dc_needed[D_MAX_BLOCKS_IN_MCU];
  166886. boolean ac_needed[D_MAX_BLOCKS_IN_MCU];
  166887. } huff_entropy_decoder2;
  166888. typedef huff_entropy_decoder2 * huff_entropy_ptr2;
  166889. /*
  166890. * Initialize for a Huffman-compressed scan.
  166891. */
  166892. METHODDEF(void)
  166893. start_pass_huff_decoder (j_decompress_ptr cinfo)
  166894. {
  166895. huff_entropy_ptr2 entropy = (huff_entropy_ptr2) cinfo->entropy;
  166896. int ci, blkn, dctbl, actbl;
  166897. jpeg_component_info * compptr;
  166898. /* Check that the scan parameters Ss, Se, Ah/Al are OK for sequential JPEG.
  166899. * This ought to be an error condition, but we make it a warning because
  166900. * there are some baseline files out there with all zeroes in these bytes.
  166901. */
  166902. if (cinfo->Ss != 0 || cinfo->Se != DCTSIZE2-1 ||
  166903. cinfo->Ah != 0 || cinfo->Al != 0)
  166904. WARNMS(cinfo, JWRN_NOT_SEQUENTIAL);
  166905. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  166906. compptr = cinfo->cur_comp_info[ci];
  166907. dctbl = compptr->dc_tbl_no;
  166908. actbl = compptr->ac_tbl_no;
  166909. /* Compute derived values for Huffman tables */
  166910. /* We may do this more than once for a table, but it's not expensive */
  166911. jpeg_make_d_derived_tbl(cinfo, TRUE, dctbl,
  166912. & entropy->dc_derived_tbls[dctbl]);
  166913. jpeg_make_d_derived_tbl(cinfo, FALSE, actbl,
  166914. & entropy->ac_derived_tbls[actbl]);
  166915. /* Initialize DC predictions to 0 */
  166916. entropy->saved.last_dc_val[ci] = 0;
  166917. }
  166918. /* Precalculate decoding info for each block in an MCU of this scan */
  166919. for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
  166920. ci = cinfo->MCU_membership[blkn];
  166921. compptr = cinfo->cur_comp_info[ci];
  166922. /* Precalculate which table to use for each block */
  166923. entropy->dc_cur_tbls[blkn] = entropy->dc_derived_tbls[compptr->dc_tbl_no];
  166924. entropy->ac_cur_tbls[blkn] = entropy->ac_derived_tbls[compptr->ac_tbl_no];
  166925. /* Decide whether we really care about the coefficient values */
  166926. if (compptr->component_needed) {
  166927. entropy->dc_needed[blkn] = TRUE;
  166928. /* we don't need the ACs if producing a 1/8th-size image */
  166929. entropy->ac_needed[blkn] = (compptr->DCT_scaled_size > 1);
  166930. } else {
  166931. entropy->dc_needed[blkn] = entropy->ac_needed[blkn] = FALSE;
  166932. }
  166933. }
  166934. /* Initialize bitread state variables */
  166935. entropy->bitstate.bits_left = 0;
  166936. entropy->bitstate.get_buffer = 0; /* unnecessary, but keeps Purify quiet */
  166937. entropy->pub.insufficient_data = FALSE;
  166938. /* Initialize restart counter */
  166939. entropy->restarts_to_go = cinfo->restart_interval;
  166940. }
  166941. /*
  166942. * Compute the derived values for a Huffman table.
  166943. * This routine also performs some validation checks on the table.
  166944. *
  166945. * Note this is also used by jdphuff.c.
  166946. */
  166947. GLOBAL(void)
  166948. jpeg_make_d_derived_tbl (j_decompress_ptr cinfo, boolean isDC, int tblno,
  166949. d_derived_tbl ** pdtbl)
  166950. {
  166951. JHUFF_TBL *htbl;
  166952. d_derived_tbl *dtbl;
  166953. int p, i, l, si, numsymbols;
  166954. int lookbits, ctr;
  166955. char huffsize[257];
  166956. unsigned int huffcode[257];
  166957. unsigned int code;
  166958. /* Note that huffsize[] and huffcode[] are filled in code-length order,
  166959. * paralleling the order of the symbols themselves in htbl->huffval[].
  166960. */
  166961. /* Find the input Huffman table */
  166962. if (tblno < 0 || tblno >= NUM_HUFF_TBLS)
  166963. ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, tblno);
  166964. htbl =
  166965. isDC ? cinfo->dc_huff_tbl_ptrs[tblno] : cinfo->ac_huff_tbl_ptrs[tblno];
  166966. if (htbl == NULL)
  166967. ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, tblno);
  166968. /* Allocate a workspace if we haven't already done so. */
  166969. if (*pdtbl == NULL)
  166970. *pdtbl = (d_derived_tbl *)
  166971. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  166972. SIZEOF(d_derived_tbl));
  166973. dtbl = *pdtbl;
  166974. dtbl->pub = htbl; /* fill in back link */
  166975. /* Figure C.1: make table of Huffman code length for each symbol */
  166976. p = 0;
  166977. for (l = 1; l <= 16; l++) {
  166978. i = (int) htbl->bits[l];
  166979. if (i < 0 || p + i > 256) /* protect against table overrun */
  166980. ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
  166981. while (i--)
  166982. huffsize[p++] = (char) l;
  166983. }
  166984. huffsize[p] = 0;
  166985. numsymbols = p;
  166986. /* Figure C.2: generate the codes themselves */
  166987. /* We also validate that the counts represent a legal Huffman code tree. */
  166988. code = 0;
  166989. si = huffsize[0];
  166990. p = 0;
  166991. while (huffsize[p]) {
  166992. while (((int) huffsize[p]) == si) {
  166993. huffcode[p++] = code;
  166994. code++;
  166995. }
  166996. /* code is now 1 more than the last code used for codelength si; but
  166997. * it must still fit in si bits, since no code is allowed to be all ones.
  166998. */
  166999. if (((INT32) code) >= (((INT32) 1) << si))
  167000. ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
  167001. code <<= 1;
  167002. si++;
  167003. }
  167004. /* Figure F.15: generate decoding tables for bit-sequential decoding */
  167005. p = 0;
  167006. for (l = 1; l <= 16; l++) {
  167007. if (htbl->bits[l]) {
  167008. /* valoffset[l] = huffval[] index of 1st symbol of code length l,
  167009. * minus the minimum code of length l
  167010. */
  167011. dtbl->valoffset[l] = (INT32) p - (INT32) huffcode[p];
  167012. p += htbl->bits[l];
  167013. dtbl->maxcode[l] = huffcode[p-1]; /* maximum code of length l */
  167014. } else {
  167015. dtbl->maxcode[l] = -1; /* -1 if no codes of this length */
  167016. }
  167017. }
  167018. dtbl->maxcode[17] = 0xFFFFFL; /* ensures jpeg_huff_decode terminates */
  167019. /* Compute lookahead tables to speed up decoding.
  167020. * First we set all the table entries to 0, indicating "too long";
  167021. * then we iterate through the Huffman codes that are short enough and
  167022. * fill in all the entries that correspond to bit sequences starting
  167023. * with that code.
  167024. */
  167025. MEMZERO(dtbl->look_nbits, SIZEOF(dtbl->look_nbits));
  167026. p = 0;
  167027. for (l = 1; l <= HUFF_LOOKAHEAD; l++) {
  167028. for (i = 1; i <= (int) htbl->bits[l]; i++, p++) {
  167029. /* l = current code's length, p = its index in huffcode[] & huffval[]. */
  167030. /* Generate left-justified code followed by all possible bit sequences */
  167031. lookbits = huffcode[p] << (HUFF_LOOKAHEAD-l);
  167032. for (ctr = 1 << (HUFF_LOOKAHEAD-l); ctr > 0; ctr--) {
  167033. dtbl->look_nbits[lookbits] = l;
  167034. dtbl->look_sym[lookbits] = htbl->huffval[p];
  167035. lookbits++;
  167036. }
  167037. }
  167038. }
  167039. /* Validate symbols as being reasonable.
  167040. * For AC tables, we make no check, but accept all byte values 0..255.
  167041. * For DC tables, we require the symbols to be in range 0..15.
  167042. * (Tighter bounds could be applied depending on the data depth and mode,
  167043. * but this is sufficient to ensure safe decoding.)
  167044. */
  167045. if (isDC) {
  167046. for (i = 0; i < numsymbols; i++) {
  167047. int sym = htbl->huffval[i];
  167048. if (sym < 0 || sym > 15)
  167049. ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
  167050. }
  167051. }
  167052. }
  167053. /*
  167054. * Out-of-line code for bit fetching (shared with jdphuff.c).
  167055. * See jdhuff.h for info about usage.
  167056. * Note: current values of get_buffer and bits_left are passed as parameters,
  167057. * but are returned in the corresponding fields of the state struct.
  167058. *
  167059. * On most machines MIN_GET_BITS should be 25 to allow the full 32-bit width
  167060. * of get_buffer to be used. (On machines with wider words, an even larger
  167061. * buffer could be used.) However, on some machines 32-bit shifts are
  167062. * quite slow and take time proportional to the number of places shifted.
  167063. * (This is true with most PC compilers, for instance.) In this case it may
  167064. * be a win to set MIN_GET_BITS to the minimum value of 15. This reduces the
  167065. * average shift distance at the cost of more calls to jpeg_fill_bit_buffer.
  167066. */
  167067. #ifdef SLOW_SHIFT_32
  167068. #define MIN_GET_BITS 15 /* minimum allowable value */
  167069. #else
  167070. #define MIN_GET_BITS (BIT_BUF_SIZE-7)
  167071. #endif
  167072. GLOBAL(boolean)
  167073. jpeg_fill_bit_buffer (bitread_working_state * state,
  167074. register bit_buf_type get_buffer, register int bits_left,
  167075. int nbits)
  167076. /* Load up the bit buffer to a depth of at least nbits */
  167077. {
  167078. /* Copy heavily used state fields into locals (hopefully registers) */
  167079. register const JOCTET * next_input_byte = state->next_input_byte;
  167080. register size_t bytes_in_buffer = state->bytes_in_buffer;
  167081. j_decompress_ptr cinfo = state->cinfo;
  167082. /* Attempt to load at least MIN_GET_BITS bits into get_buffer. */
  167083. /* (It is assumed that no request will be for more than that many bits.) */
  167084. /* We fail to do so only if we hit a marker or are forced to suspend. */
  167085. if (cinfo->unread_marker == 0) { /* cannot advance past a marker */
  167086. while (bits_left < MIN_GET_BITS) {
  167087. register int c;
  167088. /* Attempt to read a byte */
  167089. if (bytes_in_buffer == 0) {
  167090. if (! (*cinfo->src->fill_input_buffer) (cinfo))
  167091. return FALSE;
  167092. next_input_byte = cinfo->src->next_input_byte;
  167093. bytes_in_buffer = cinfo->src->bytes_in_buffer;
  167094. }
  167095. bytes_in_buffer--;
  167096. c = GETJOCTET(*next_input_byte++);
  167097. /* If it's 0xFF, check and discard stuffed zero byte */
  167098. if (c == 0xFF) {
  167099. /* Loop here to discard any padding FF's on terminating marker,
  167100. * so that we can save a valid unread_marker value. NOTE: we will
  167101. * accept multiple FF's followed by a 0 as meaning a single FF data
  167102. * byte. This data pattern is not valid according to the standard.
  167103. */
  167104. do {
  167105. if (bytes_in_buffer == 0) {
  167106. if (! (*cinfo->src->fill_input_buffer) (cinfo))
  167107. return FALSE;
  167108. next_input_byte = cinfo->src->next_input_byte;
  167109. bytes_in_buffer = cinfo->src->bytes_in_buffer;
  167110. }
  167111. bytes_in_buffer--;
  167112. c = GETJOCTET(*next_input_byte++);
  167113. } while (c == 0xFF);
  167114. if (c == 0) {
  167115. /* Found FF/00, which represents an FF data byte */
  167116. c = 0xFF;
  167117. } else {
  167118. /* Oops, it's actually a marker indicating end of compressed data.
  167119. * Save the marker code for later use.
  167120. * Fine point: it might appear that we should save the marker into
  167121. * bitread working state, not straight into permanent state. But
  167122. * once we have hit a marker, we cannot need to suspend within the
  167123. * current MCU, because we will read no more bytes from the data
  167124. * source. So it is OK to update permanent state right away.
  167125. */
  167126. cinfo->unread_marker = c;
  167127. /* See if we need to insert some fake zero bits. */
  167128. goto no_more_bytes;
  167129. }
  167130. }
  167131. /* OK, load c into get_buffer */
  167132. get_buffer = (get_buffer << 8) | c;
  167133. bits_left += 8;
  167134. } /* end while */
  167135. } else {
  167136. no_more_bytes:
  167137. /* We get here if we've read the marker that terminates the compressed
  167138. * data segment. There should be enough bits in the buffer register
  167139. * to satisfy the request; if so, no problem.
  167140. */
  167141. if (nbits > bits_left) {
  167142. /* Uh-oh. Report corrupted data to user and stuff zeroes into
  167143. * the data stream, so that we can produce some kind of image.
  167144. * We use a nonvolatile flag to ensure that only one warning message
  167145. * appears per data segment.
  167146. */
  167147. if (! cinfo->entropy->insufficient_data) {
  167148. WARNMS(cinfo, JWRN_HIT_MARKER);
  167149. cinfo->entropy->insufficient_data = TRUE;
  167150. }
  167151. /* Fill the buffer with zero bits */
  167152. get_buffer <<= MIN_GET_BITS - bits_left;
  167153. bits_left = MIN_GET_BITS;
  167154. }
  167155. }
  167156. /* Unload the local registers */
  167157. state->next_input_byte = next_input_byte;
  167158. state->bytes_in_buffer = bytes_in_buffer;
  167159. state->get_buffer = get_buffer;
  167160. state->bits_left = bits_left;
  167161. return TRUE;
  167162. }
  167163. /*
  167164. * Out-of-line code for Huffman code decoding.
  167165. * See jdhuff.h for info about usage.
  167166. */
  167167. GLOBAL(int)
  167168. jpeg_huff_decode (bitread_working_state * state,
  167169. register bit_buf_type get_buffer, register int bits_left,
  167170. d_derived_tbl * htbl, int min_bits)
  167171. {
  167172. register int l = min_bits;
  167173. register INT32 code;
  167174. /* HUFF_DECODE has determined that the code is at least min_bits */
  167175. /* bits long, so fetch that many bits in one swoop. */
  167176. CHECK_BIT_BUFFER(*state, l, return -1);
  167177. code = GET_BITS(l);
  167178. /* Collect the rest of the Huffman code one bit at a time. */
  167179. /* This is per Figure F.16 in the JPEG spec. */
  167180. while (code > htbl->maxcode[l]) {
  167181. code <<= 1;
  167182. CHECK_BIT_BUFFER(*state, 1, return -1);
  167183. code |= GET_BITS(1);
  167184. l++;
  167185. }
  167186. /* Unload the local registers */
  167187. state->get_buffer = get_buffer;
  167188. state->bits_left = bits_left;
  167189. /* With garbage input we may reach the sentinel value l = 17. */
  167190. if (l > 16) {
  167191. WARNMS(state->cinfo, JWRN_HUFF_BAD_CODE);
  167192. return 0; /* fake a zero as the safest result */
  167193. }
  167194. return htbl->pub->huffval[ (int) (code + htbl->valoffset[l]) ];
  167195. }
  167196. /*
  167197. * Check for a restart marker & resynchronize decoder.
  167198. * Returns FALSE if must suspend.
  167199. */
  167200. LOCAL(boolean)
  167201. process_restart (j_decompress_ptr cinfo)
  167202. {
  167203. huff_entropy_ptr2 entropy = (huff_entropy_ptr2) cinfo->entropy;
  167204. int ci;
  167205. /* Throw away any unused bits remaining in bit buffer; */
  167206. /* include any full bytes in next_marker's count of discarded bytes */
  167207. cinfo->marker->discarded_bytes += entropy->bitstate.bits_left / 8;
  167208. entropy->bitstate.bits_left = 0;
  167209. /* Advance past the RSTn marker */
  167210. if (! (*cinfo->marker->read_restart_marker) (cinfo))
  167211. return FALSE;
  167212. /* Re-initialize DC predictions to 0 */
  167213. for (ci = 0; ci < cinfo->comps_in_scan; ci++)
  167214. entropy->saved.last_dc_val[ci] = 0;
  167215. /* Reset restart counter */
  167216. entropy->restarts_to_go = cinfo->restart_interval;
  167217. /* Reset out-of-data flag, unless read_restart_marker left us smack up
  167218. * against a marker. In that case we will end up treating the next data
  167219. * segment as empty, and we can avoid producing bogus output pixels by
  167220. * leaving the flag set.
  167221. */
  167222. if (cinfo->unread_marker == 0)
  167223. entropy->pub.insufficient_data = FALSE;
  167224. return TRUE;
  167225. }
  167226. /*
  167227. * Decode and return one MCU's worth of Huffman-compressed coefficients.
  167228. * The coefficients are reordered from zigzag order into natural array order,
  167229. * but are not dequantized.
  167230. *
  167231. * The i'th block of the MCU is stored into the block pointed to by
  167232. * MCU_data[i]. WE ASSUME THIS AREA HAS BEEN ZEROED BY THE CALLER.
  167233. * (Wholesale zeroing is usually a little faster than retail...)
  167234. *
  167235. * Returns FALSE if data source requested suspension. In that case no
  167236. * changes have been made to permanent state. (Exception: some output
  167237. * coefficients may already have been assigned. This is harmless for
  167238. * this module, since we'll just re-assign them on the next call.)
  167239. */
  167240. METHODDEF(boolean)
  167241. decode_mcu (j_decompress_ptr cinfo, JBLOCKROW *MCU_data)
  167242. {
  167243. huff_entropy_ptr2 entropy = (huff_entropy_ptr2) cinfo->entropy;
  167244. int blkn;
  167245. BITREAD_STATE_VARS;
  167246. savable_state2 state;
  167247. /* Process restart marker if needed; may have to suspend */
  167248. if (cinfo->restart_interval) {
  167249. if (entropy->restarts_to_go == 0)
  167250. if (! process_restart(cinfo))
  167251. return FALSE;
  167252. }
  167253. /* If we've run out of data, just leave the MCU set to zeroes.
  167254. * This way, we return uniform gray for the remainder of the segment.
  167255. */
  167256. if (! entropy->pub.insufficient_data) {
  167257. /* Load up working state */
  167258. BITREAD_LOAD_STATE(cinfo,entropy->bitstate);
  167259. ASSIGN_STATE(state, entropy->saved);
  167260. /* Outer loop handles each block in the MCU */
  167261. for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
  167262. JBLOCKROW block = MCU_data[blkn];
  167263. d_derived_tbl * dctbl = entropy->dc_cur_tbls[blkn];
  167264. d_derived_tbl * actbl = entropy->ac_cur_tbls[blkn];
  167265. register int s, k, r;
  167266. /* Decode a single block's worth of coefficients */
  167267. /* Section F.2.2.1: decode the DC coefficient difference */
  167268. HUFF_DECODE(s, br_state, dctbl, return FALSE, label1);
  167269. if (s) {
  167270. CHECK_BIT_BUFFER(br_state, s, return FALSE);
  167271. r = GET_BITS(s);
  167272. s = HUFF_EXTEND(r, s);
  167273. }
  167274. if (entropy->dc_needed[blkn]) {
  167275. /* Convert DC difference to actual value, update last_dc_val */
  167276. int ci = cinfo->MCU_membership[blkn];
  167277. s += state.last_dc_val[ci];
  167278. state.last_dc_val[ci] = s;
  167279. /* Output the DC coefficient (assumes jpeg_natural_order[0] = 0) */
  167280. (*block)[0] = (JCOEF) s;
  167281. }
  167282. if (entropy->ac_needed[blkn]) {
  167283. /* Section F.2.2.2: decode the AC coefficients */
  167284. /* Since zeroes are skipped, output area must be cleared beforehand */
  167285. for (k = 1; k < DCTSIZE2; k++) {
  167286. HUFF_DECODE(s, br_state, actbl, return FALSE, label2);
  167287. r = s >> 4;
  167288. s &= 15;
  167289. if (s) {
  167290. k += r;
  167291. CHECK_BIT_BUFFER(br_state, s, return FALSE);
  167292. r = GET_BITS(s);
  167293. s = HUFF_EXTEND(r, s);
  167294. /* Output coefficient in natural (dezigzagged) order.
  167295. * Note: the extra entries in jpeg_natural_order[] will save us
  167296. * if k >= DCTSIZE2, which could happen if the data is corrupted.
  167297. */
  167298. (*block)[jpeg_natural_order[k]] = (JCOEF) s;
  167299. } else {
  167300. if (r != 15)
  167301. break;
  167302. k += 15;
  167303. }
  167304. }
  167305. } else {
  167306. /* Section F.2.2.2: decode the AC coefficients */
  167307. /* In this path we just discard the values */
  167308. for (k = 1; k < DCTSIZE2; k++) {
  167309. HUFF_DECODE(s, br_state, actbl, return FALSE, label3);
  167310. r = s >> 4;
  167311. s &= 15;
  167312. if (s) {
  167313. k += r;
  167314. CHECK_BIT_BUFFER(br_state, s, return FALSE);
  167315. DROP_BITS(s);
  167316. } else {
  167317. if (r != 15)
  167318. break;
  167319. k += 15;
  167320. }
  167321. }
  167322. }
  167323. }
  167324. /* Completed MCU, so update state */
  167325. BITREAD_SAVE_STATE(cinfo,entropy->bitstate);
  167326. ASSIGN_STATE(entropy->saved, state);
  167327. }
  167328. /* Account for restart interval (no-op if not using restarts) */
  167329. entropy->restarts_to_go--;
  167330. return TRUE;
  167331. }
  167332. /*
  167333. * Module initialization routine for Huffman entropy decoding.
  167334. */
  167335. GLOBAL(void)
  167336. jinit_huff_decoder (j_decompress_ptr cinfo)
  167337. {
  167338. huff_entropy_ptr2 entropy;
  167339. int i;
  167340. entropy = (huff_entropy_ptr2)
  167341. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  167342. SIZEOF(huff_entropy_decoder2));
  167343. cinfo->entropy = (struct jpeg_entropy_decoder *) entropy;
  167344. entropy->pub.start_pass = start_pass_huff_decoder;
  167345. entropy->pub.decode_mcu = decode_mcu;
  167346. /* Mark tables unallocated */
  167347. for (i = 0; i < NUM_HUFF_TBLS; i++) {
  167348. entropy->dc_derived_tbls[i] = entropy->ac_derived_tbls[i] = NULL;
  167349. }
  167350. }
  167351. /*** End of inlined file: jdhuff.c ***/
  167352. /*** Start of inlined file: jdinput.c ***/
  167353. #define JPEG_INTERNALS
  167354. /* Private state */
  167355. typedef struct {
  167356. struct jpeg_input_controller pub; /* public fields */
  167357. boolean inheaders; /* TRUE until first SOS is reached */
  167358. } my_input_controller;
  167359. typedef my_input_controller * my_inputctl_ptr;
  167360. /* Forward declarations */
  167361. METHODDEF(int) consume_markers JPP((j_decompress_ptr cinfo));
  167362. /*
  167363. * Routines to calculate various quantities related to the size of the image.
  167364. */
  167365. LOCAL(void)
  167366. initial_setup2 (j_decompress_ptr cinfo)
  167367. /* Called once, when first SOS marker is reached */
  167368. {
  167369. int ci;
  167370. jpeg_component_info *compptr;
  167371. /* Make sure image isn't bigger than I can handle */
  167372. if ((long) cinfo->image_height > (long) JPEG_MAX_DIMENSION ||
  167373. (long) cinfo->image_width > (long) JPEG_MAX_DIMENSION)
  167374. ERREXIT1(cinfo, JERR_IMAGE_TOO_BIG, (unsigned int) JPEG_MAX_DIMENSION);
  167375. /* For now, precision must match compiled-in value... */
  167376. if (cinfo->data_precision != BITS_IN_JSAMPLE)
  167377. ERREXIT1(cinfo, JERR_BAD_PRECISION, cinfo->data_precision);
  167378. /* Check that number of components won't exceed internal array sizes */
  167379. if (cinfo->num_components > MAX_COMPONENTS)
  167380. ERREXIT2(cinfo, JERR_COMPONENT_COUNT, cinfo->num_components,
  167381. MAX_COMPONENTS);
  167382. /* Compute maximum sampling factors; check factor validity */
  167383. cinfo->max_h_samp_factor = 1;
  167384. cinfo->max_v_samp_factor = 1;
  167385. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  167386. ci++, compptr++) {
  167387. if (compptr->h_samp_factor<=0 || compptr->h_samp_factor>MAX_SAMP_FACTOR ||
  167388. compptr->v_samp_factor<=0 || compptr->v_samp_factor>MAX_SAMP_FACTOR)
  167389. ERREXIT(cinfo, JERR_BAD_SAMPLING);
  167390. cinfo->max_h_samp_factor = MAX(cinfo->max_h_samp_factor,
  167391. compptr->h_samp_factor);
  167392. cinfo->max_v_samp_factor = MAX(cinfo->max_v_samp_factor,
  167393. compptr->v_samp_factor);
  167394. }
  167395. /* We initialize DCT_scaled_size and min_DCT_scaled_size to DCTSIZE.
  167396. * In the full decompressor, this will be overridden by jdmaster.c;
  167397. * but in the transcoder, jdmaster.c is not used, so we must do it here.
  167398. */
  167399. cinfo->min_DCT_scaled_size = DCTSIZE;
  167400. /* Compute dimensions of components */
  167401. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  167402. ci++, compptr++) {
  167403. compptr->DCT_scaled_size = DCTSIZE;
  167404. /* Size in DCT blocks */
  167405. compptr->width_in_blocks = (JDIMENSION)
  167406. jdiv_round_up((long) cinfo->image_width * (long) compptr->h_samp_factor,
  167407. (long) (cinfo->max_h_samp_factor * DCTSIZE));
  167408. compptr->height_in_blocks = (JDIMENSION)
  167409. jdiv_round_up((long) cinfo->image_height * (long) compptr->v_samp_factor,
  167410. (long) (cinfo->max_v_samp_factor * DCTSIZE));
  167411. /* downsampled_width and downsampled_height will also be overridden by
  167412. * jdmaster.c if we are doing full decompression. The transcoder library
  167413. * doesn't use these values, but the calling application might.
  167414. */
  167415. /* Size in samples */
  167416. compptr->downsampled_width = (JDIMENSION)
  167417. jdiv_round_up((long) cinfo->image_width * (long) compptr->h_samp_factor,
  167418. (long) cinfo->max_h_samp_factor);
  167419. compptr->downsampled_height = (JDIMENSION)
  167420. jdiv_round_up((long) cinfo->image_height * (long) compptr->v_samp_factor,
  167421. (long) cinfo->max_v_samp_factor);
  167422. /* Mark component needed, until color conversion says otherwise */
  167423. compptr->component_needed = TRUE;
  167424. /* Mark no quantization table yet saved for component */
  167425. compptr->quant_table = NULL;
  167426. }
  167427. /* Compute number of fully interleaved MCU rows. */
  167428. cinfo->total_iMCU_rows = (JDIMENSION)
  167429. jdiv_round_up((long) cinfo->image_height,
  167430. (long) (cinfo->max_v_samp_factor*DCTSIZE));
  167431. /* Decide whether file contains multiple scans */
  167432. if (cinfo->comps_in_scan < cinfo->num_components || cinfo->progressive_mode)
  167433. cinfo->inputctl->has_multiple_scans = TRUE;
  167434. else
  167435. cinfo->inputctl->has_multiple_scans = FALSE;
  167436. }
  167437. LOCAL(void)
  167438. per_scan_setup2 (j_decompress_ptr cinfo)
  167439. /* Do computations that are needed before processing a JPEG scan */
  167440. /* cinfo->comps_in_scan and cinfo->cur_comp_info[] were set from SOS marker */
  167441. {
  167442. int ci, mcublks, tmp;
  167443. jpeg_component_info *compptr;
  167444. if (cinfo->comps_in_scan == 1) {
  167445. /* Noninterleaved (single-component) scan */
  167446. compptr = cinfo->cur_comp_info[0];
  167447. /* Overall image size in MCUs */
  167448. cinfo->MCUs_per_row = compptr->width_in_blocks;
  167449. cinfo->MCU_rows_in_scan = compptr->height_in_blocks;
  167450. /* For noninterleaved scan, always one block per MCU */
  167451. compptr->MCU_width = 1;
  167452. compptr->MCU_height = 1;
  167453. compptr->MCU_blocks = 1;
  167454. compptr->MCU_sample_width = compptr->DCT_scaled_size;
  167455. compptr->last_col_width = 1;
  167456. /* For noninterleaved scans, it is convenient to define last_row_height
  167457. * as the number of block rows present in the last iMCU row.
  167458. */
  167459. tmp = (int) (compptr->height_in_blocks % compptr->v_samp_factor);
  167460. if (tmp == 0) tmp = compptr->v_samp_factor;
  167461. compptr->last_row_height = tmp;
  167462. /* Prepare array describing MCU composition */
  167463. cinfo->blocks_in_MCU = 1;
  167464. cinfo->MCU_membership[0] = 0;
  167465. } else {
  167466. /* Interleaved (multi-component) scan */
  167467. if (cinfo->comps_in_scan <= 0 || cinfo->comps_in_scan > MAX_COMPS_IN_SCAN)
  167468. ERREXIT2(cinfo, JERR_COMPONENT_COUNT, cinfo->comps_in_scan,
  167469. MAX_COMPS_IN_SCAN);
  167470. /* Overall image size in MCUs */
  167471. cinfo->MCUs_per_row = (JDIMENSION)
  167472. jdiv_round_up((long) cinfo->image_width,
  167473. (long) (cinfo->max_h_samp_factor*DCTSIZE));
  167474. cinfo->MCU_rows_in_scan = (JDIMENSION)
  167475. jdiv_round_up((long) cinfo->image_height,
  167476. (long) (cinfo->max_v_samp_factor*DCTSIZE));
  167477. cinfo->blocks_in_MCU = 0;
  167478. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  167479. compptr = cinfo->cur_comp_info[ci];
  167480. /* Sampling factors give # of blocks of component in each MCU */
  167481. compptr->MCU_width = compptr->h_samp_factor;
  167482. compptr->MCU_height = compptr->v_samp_factor;
  167483. compptr->MCU_blocks = compptr->MCU_width * compptr->MCU_height;
  167484. compptr->MCU_sample_width = compptr->MCU_width * compptr->DCT_scaled_size;
  167485. /* Figure number of non-dummy blocks in last MCU column & row */
  167486. tmp = (int) (compptr->width_in_blocks % compptr->MCU_width);
  167487. if (tmp == 0) tmp = compptr->MCU_width;
  167488. compptr->last_col_width = tmp;
  167489. tmp = (int) (compptr->height_in_blocks % compptr->MCU_height);
  167490. if (tmp == 0) tmp = compptr->MCU_height;
  167491. compptr->last_row_height = tmp;
  167492. /* Prepare array describing MCU composition */
  167493. mcublks = compptr->MCU_blocks;
  167494. if (cinfo->blocks_in_MCU + mcublks > D_MAX_BLOCKS_IN_MCU)
  167495. ERREXIT(cinfo, JERR_BAD_MCU_SIZE);
  167496. while (mcublks-- > 0) {
  167497. cinfo->MCU_membership[cinfo->blocks_in_MCU++] = ci;
  167498. }
  167499. }
  167500. }
  167501. }
  167502. /*
  167503. * Save away a copy of the Q-table referenced by each component present
  167504. * in the current scan, unless already saved during a prior scan.
  167505. *
  167506. * In a multiple-scan JPEG file, the encoder could assign different components
  167507. * the same Q-table slot number, but change table definitions between scans
  167508. * so that each component uses a different Q-table. (The IJG encoder is not
  167509. * currently capable of doing this, but other encoders might.) Since we want
  167510. * to be able to dequantize all the components at the end of the file, this
  167511. * means that we have to save away the table actually used for each component.
  167512. * We do this by copying the table at the start of the first scan containing
  167513. * the component.
  167514. * The JPEG spec prohibits the encoder from changing the contents of a Q-table
  167515. * slot between scans of a component using that slot. If the encoder does so
  167516. * anyway, this decoder will simply use the Q-table values that were current
  167517. * at the start of the first scan for the component.
  167518. *
  167519. * The decompressor output side looks only at the saved quant tables,
  167520. * not at the current Q-table slots.
  167521. */
  167522. LOCAL(void)
  167523. latch_quant_tables (j_decompress_ptr cinfo)
  167524. {
  167525. int ci, qtblno;
  167526. jpeg_component_info *compptr;
  167527. JQUANT_TBL * qtbl;
  167528. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  167529. compptr = cinfo->cur_comp_info[ci];
  167530. /* No work if we already saved Q-table for this component */
  167531. if (compptr->quant_table != NULL)
  167532. continue;
  167533. /* Make sure specified quantization table is present */
  167534. qtblno = compptr->quant_tbl_no;
  167535. if (qtblno < 0 || qtblno >= NUM_QUANT_TBLS ||
  167536. cinfo->quant_tbl_ptrs[qtblno] == NULL)
  167537. ERREXIT1(cinfo, JERR_NO_QUANT_TABLE, qtblno);
  167538. /* OK, save away the quantization table */
  167539. qtbl = (JQUANT_TBL *)
  167540. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  167541. SIZEOF(JQUANT_TBL));
  167542. MEMCOPY(qtbl, cinfo->quant_tbl_ptrs[qtblno], SIZEOF(JQUANT_TBL));
  167543. compptr->quant_table = qtbl;
  167544. }
  167545. }
  167546. /*
  167547. * Initialize the input modules to read a scan of compressed data.
  167548. * The first call to this is done by jdmaster.c after initializing
  167549. * the entire decompressor (during jpeg_start_decompress).
  167550. * Subsequent calls come from consume_markers, below.
  167551. */
  167552. METHODDEF(void)
  167553. start_input_pass2 (j_decompress_ptr cinfo)
  167554. {
  167555. per_scan_setup2(cinfo);
  167556. latch_quant_tables(cinfo);
  167557. (*cinfo->entropy->start_pass) (cinfo);
  167558. (*cinfo->coef->start_input_pass) (cinfo);
  167559. cinfo->inputctl->consume_input = cinfo->coef->consume_data;
  167560. }
  167561. /*
  167562. * Finish up after inputting a compressed-data scan.
  167563. * This is called by the coefficient controller after it's read all
  167564. * the expected data of the scan.
  167565. */
  167566. METHODDEF(void)
  167567. finish_input_pass (j_decompress_ptr cinfo)
  167568. {
  167569. cinfo->inputctl->consume_input = consume_markers;
  167570. }
  167571. /*
  167572. * Read JPEG markers before, between, or after compressed-data scans.
  167573. * Change state as necessary when a new scan is reached.
  167574. * Return value is JPEG_SUSPENDED, JPEG_REACHED_SOS, or JPEG_REACHED_EOI.
  167575. *
  167576. * The consume_input method pointer points either here or to the
  167577. * coefficient controller's consume_data routine, depending on whether
  167578. * we are reading a compressed data segment or inter-segment markers.
  167579. */
  167580. METHODDEF(int)
  167581. consume_markers (j_decompress_ptr cinfo)
  167582. {
  167583. my_inputctl_ptr inputctl = (my_inputctl_ptr) cinfo->inputctl;
  167584. int val;
  167585. if (inputctl->pub.eoi_reached) /* After hitting EOI, read no further */
  167586. return JPEG_REACHED_EOI;
  167587. val = (*cinfo->marker->read_markers) (cinfo);
  167588. switch (val) {
  167589. case JPEG_REACHED_SOS: /* Found SOS */
  167590. if (inputctl->inheaders) { /* 1st SOS */
  167591. initial_setup2(cinfo);
  167592. inputctl->inheaders = FALSE;
  167593. /* Note: start_input_pass must be called by jdmaster.c
  167594. * before any more input can be consumed. jdapimin.c is
  167595. * responsible for enforcing this sequencing.
  167596. */
  167597. } else { /* 2nd or later SOS marker */
  167598. if (! inputctl->pub.has_multiple_scans)
  167599. ERREXIT(cinfo, JERR_EOI_EXPECTED); /* Oops, I wasn't expecting this! */
  167600. start_input_pass2(cinfo);
  167601. }
  167602. break;
  167603. case JPEG_REACHED_EOI: /* Found EOI */
  167604. inputctl->pub.eoi_reached = TRUE;
  167605. if (inputctl->inheaders) { /* Tables-only datastream, apparently */
  167606. if (cinfo->marker->saw_SOF)
  167607. ERREXIT(cinfo, JERR_SOF_NO_SOS);
  167608. } else {
  167609. /* Prevent infinite loop in coef ctlr's decompress_data routine
  167610. * if user set output_scan_number larger than number of scans.
  167611. */
  167612. if (cinfo->output_scan_number > cinfo->input_scan_number)
  167613. cinfo->output_scan_number = cinfo->input_scan_number;
  167614. }
  167615. break;
  167616. case JPEG_SUSPENDED:
  167617. break;
  167618. }
  167619. return val;
  167620. }
  167621. /*
  167622. * Reset state to begin a fresh datastream.
  167623. */
  167624. METHODDEF(void)
  167625. reset_input_controller (j_decompress_ptr cinfo)
  167626. {
  167627. my_inputctl_ptr inputctl = (my_inputctl_ptr) cinfo->inputctl;
  167628. inputctl->pub.consume_input = consume_markers;
  167629. inputctl->pub.has_multiple_scans = FALSE; /* "unknown" would be better */
  167630. inputctl->pub.eoi_reached = FALSE;
  167631. inputctl->inheaders = TRUE;
  167632. /* Reset other modules */
  167633. (*cinfo->err->reset_error_mgr) ((j_common_ptr) cinfo);
  167634. (*cinfo->marker->reset_marker_reader) (cinfo);
  167635. /* Reset progression state -- would be cleaner if entropy decoder did this */
  167636. cinfo->coef_bits = NULL;
  167637. }
  167638. /*
  167639. * Initialize the input controller module.
  167640. * This is called only once, when the decompression object is created.
  167641. */
  167642. GLOBAL(void)
  167643. jinit_input_controller (j_decompress_ptr cinfo)
  167644. {
  167645. my_inputctl_ptr inputctl;
  167646. /* Create subobject in permanent pool */
  167647. inputctl = (my_inputctl_ptr)
  167648. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT,
  167649. SIZEOF(my_input_controller));
  167650. cinfo->inputctl = (struct jpeg_input_controller *) inputctl;
  167651. /* Initialize method pointers */
  167652. inputctl->pub.consume_input = consume_markers;
  167653. inputctl->pub.reset_input_controller = reset_input_controller;
  167654. inputctl->pub.start_input_pass = start_input_pass2;
  167655. inputctl->pub.finish_input_pass = finish_input_pass;
  167656. /* Initialize state: can't use reset_input_controller since we don't
  167657. * want to try to reset other modules yet.
  167658. */
  167659. inputctl->pub.has_multiple_scans = FALSE; /* "unknown" would be better */
  167660. inputctl->pub.eoi_reached = FALSE;
  167661. inputctl->inheaders = TRUE;
  167662. }
  167663. /*** End of inlined file: jdinput.c ***/
  167664. /*** Start of inlined file: jdmainct.c ***/
  167665. #define JPEG_INTERNALS
  167666. /*
  167667. * In the current system design, the main buffer need never be a full-image
  167668. * buffer; any full-height buffers will be found inside the coefficient or
  167669. * postprocessing controllers. Nonetheless, the main controller is not
  167670. * trivial. Its responsibility is to provide context rows for upsampling/
  167671. * rescaling, and doing this in an efficient fashion is a bit tricky.
  167672. *
  167673. * Postprocessor input data is counted in "row groups". A row group
  167674. * is defined to be (v_samp_factor * DCT_scaled_size / min_DCT_scaled_size)
  167675. * sample rows of each component. (We require DCT_scaled_size values to be
  167676. * chosen such that these numbers are integers. In practice DCT_scaled_size
  167677. * values will likely be powers of two, so we actually have the stronger
  167678. * condition that DCT_scaled_size / min_DCT_scaled_size is an integer.)
  167679. * Upsampling will typically produce max_v_samp_factor pixel rows from each
  167680. * row group (times any additional scale factor that the upsampler is
  167681. * applying).
  167682. *
  167683. * The coefficient controller will deliver data to us one iMCU row at a time;
  167684. * each iMCU row contains v_samp_factor * DCT_scaled_size sample rows, or
  167685. * exactly min_DCT_scaled_size row groups. (This amount of data corresponds
  167686. * to one row of MCUs when the image is fully interleaved.) Note that the
  167687. * number of sample rows varies across components, but the number of row
  167688. * groups does not. Some garbage sample rows may be included in the last iMCU
  167689. * row at the bottom of the image.
  167690. *
  167691. * Depending on the vertical scaling algorithm used, the upsampler may need
  167692. * access to the sample row(s) above and below its current input row group.
  167693. * The upsampler is required to set need_context_rows TRUE at global selection
  167694. * time if so. When need_context_rows is FALSE, this controller can simply
  167695. * obtain one iMCU row at a time from the coefficient controller and dole it
  167696. * out as row groups to the postprocessor.
  167697. *
  167698. * When need_context_rows is TRUE, this controller guarantees that the buffer
  167699. * passed to postprocessing contains at least one row group's worth of samples
  167700. * above and below the row group(s) being processed. Note that the context
  167701. * rows "above" the first passed row group appear at negative row offsets in
  167702. * the passed buffer. At the top and bottom of the image, the required
  167703. * context rows are manufactured by duplicating the first or last real sample
  167704. * row; this avoids having special cases in the upsampling inner loops.
  167705. *
  167706. * The amount of context is fixed at one row group just because that's a
  167707. * convenient number for this controller to work with. The existing
  167708. * upsamplers really only need one sample row of context. An upsampler
  167709. * supporting arbitrary output rescaling might wish for more than one row
  167710. * group of context when shrinking the image; tough, we don't handle that.
  167711. * (This is justified by the assumption that downsizing will be handled mostly
  167712. * by adjusting the DCT_scaled_size values, so that the actual scale factor at
  167713. * the upsample step needn't be much less than one.)
  167714. *
  167715. * To provide the desired context, we have to retain the last two row groups
  167716. * of one iMCU row while reading in the next iMCU row. (The last row group
  167717. * can't be processed until we have another row group for its below-context,
  167718. * and so we have to save the next-to-last group too for its above-context.)
  167719. * We could do this most simply by copying data around in our buffer, but
  167720. * that'd be very slow. We can avoid copying any data by creating a rather
  167721. * strange pointer structure. Here's how it works. We allocate a workspace
  167722. * consisting of M+2 row groups (where M = min_DCT_scaled_size is the number
  167723. * of row groups per iMCU row). We create two sets of redundant pointers to
  167724. * the workspace. Labeling the physical row groups 0 to M+1, the synthesized
  167725. * pointer lists look like this:
  167726. * M+1 M-1
  167727. * master pointer --> 0 master pointer --> 0
  167728. * 1 1
  167729. * ... ...
  167730. * M-3 M-3
  167731. * M-2 M
  167732. * M-1 M+1
  167733. * M M-2
  167734. * M+1 M-1
  167735. * 0 0
  167736. * We read alternate iMCU rows using each master pointer; thus the last two
  167737. * row groups of the previous iMCU row remain un-overwritten in the workspace.
  167738. * The pointer lists are set up so that the required context rows appear to
  167739. * be adjacent to the proper places when we pass the pointer lists to the
  167740. * upsampler.
  167741. *
  167742. * The above pictures describe the normal state of the pointer lists.
  167743. * At top and bottom of the image, we diddle the pointer lists to duplicate
  167744. * the first or last sample row as necessary (this is cheaper than copying
  167745. * sample rows around).
  167746. *
  167747. * This scheme breaks down if M < 2, ie, min_DCT_scaled_size is 1. In that
  167748. * situation each iMCU row provides only one row group so the buffering logic
  167749. * must be different (eg, we must read two iMCU rows before we can emit the
  167750. * first row group). For now, we simply do not support providing context
  167751. * rows when min_DCT_scaled_size is 1. That combination seems unlikely to
  167752. * be worth providing --- if someone wants a 1/8th-size preview, they probably
  167753. * want it quick and dirty, so a context-free upsampler is sufficient.
  167754. */
  167755. /* Private buffer controller object */
  167756. typedef struct {
  167757. struct jpeg_d_main_controller pub; /* public fields */
  167758. /* Pointer to allocated workspace (M or M+2 row groups). */
  167759. JSAMPARRAY buffer[MAX_COMPONENTS];
  167760. boolean buffer_full; /* Have we gotten an iMCU row from decoder? */
  167761. JDIMENSION rowgroup_ctr; /* counts row groups output to postprocessor */
  167762. /* Remaining fields are only used in the context case. */
  167763. /* These are the master pointers to the funny-order pointer lists. */
  167764. JSAMPIMAGE xbuffer[2]; /* pointers to weird pointer lists */
  167765. int whichptr; /* indicates which pointer set is now in use */
  167766. int context_state; /* process_data state machine status */
  167767. JDIMENSION rowgroups_avail; /* row groups available to postprocessor */
  167768. JDIMENSION iMCU_row_ctr; /* counts iMCU rows to detect image top/bot */
  167769. } my_main_controller4;
  167770. typedef my_main_controller4 * my_main_ptr4;
  167771. /* context_state values: */
  167772. #define CTX_PREPARE_FOR_IMCU 0 /* need to prepare for MCU row */
  167773. #define CTX_PROCESS_IMCU 1 /* feeding iMCU to postprocessor */
  167774. #define CTX_POSTPONED_ROW 2 /* feeding postponed row group */
  167775. /* Forward declarations */
  167776. METHODDEF(void) process_data_simple_main2
  167777. JPP((j_decompress_ptr cinfo, JSAMPARRAY output_buf,
  167778. JDIMENSION *out_row_ctr, JDIMENSION out_rows_avail));
  167779. METHODDEF(void) process_data_context_main
  167780. JPP((j_decompress_ptr cinfo, JSAMPARRAY output_buf,
  167781. JDIMENSION *out_row_ctr, JDIMENSION out_rows_avail));
  167782. #ifdef QUANT_2PASS_SUPPORTED
  167783. METHODDEF(void) process_data_crank_post
  167784. JPP((j_decompress_ptr cinfo, JSAMPARRAY output_buf,
  167785. JDIMENSION *out_row_ctr, JDIMENSION out_rows_avail));
  167786. #endif
  167787. LOCAL(void)
  167788. alloc_funny_pointers (j_decompress_ptr cinfo)
  167789. /* Allocate space for the funny pointer lists.
  167790. * This is done only once, not once per pass.
  167791. */
  167792. {
  167793. my_main_ptr4 main_ = (my_main_ptr4) cinfo->main;
  167794. int ci, rgroup;
  167795. int M = cinfo->min_DCT_scaled_size;
  167796. jpeg_component_info *compptr;
  167797. JSAMPARRAY xbuf;
  167798. /* Get top-level space for component array pointers.
  167799. * We alloc both arrays with one call to save a few cycles.
  167800. */
  167801. main_->xbuffer[0] = (JSAMPIMAGE)
  167802. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  167803. cinfo->num_components * 2 * SIZEOF(JSAMPARRAY));
  167804. main_->xbuffer[1] = main_->xbuffer[0] + cinfo->num_components;
  167805. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  167806. ci++, compptr++) {
  167807. rgroup = (compptr->v_samp_factor * compptr->DCT_scaled_size) /
  167808. cinfo->min_DCT_scaled_size; /* height of a row group of component */
  167809. /* Get space for pointer lists --- M+4 row groups in each list.
  167810. * We alloc both pointer lists with one call to save a few cycles.
  167811. */
  167812. xbuf = (JSAMPARRAY)
  167813. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  167814. 2 * (rgroup * (M + 4)) * SIZEOF(JSAMPROW));
  167815. xbuf += rgroup; /* want one row group at negative offsets */
  167816. main_->xbuffer[0][ci] = xbuf;
  167817. xbuf += rgroup * (M + 4);
  167818. main_->xbuffer[1][ci] = xbuf;
  167819. }
  167820. }
  167821. LOCAL(void)
  167822. make_funny_pointers (j_decompress_ptr cinfo)
  167823. /* Create the funny pointer lists discussed in the comments above.
  167824. * The actual workspace is already allocated (in main->buffer),
  167825. * and the space for the pointer lists is allocated too.
  167826. * This routine just fills in the curiously ordered lists.
  167827. * This will be repeated at the beginning of each pass.
  167828. */
  167829. {
  167830. my_main_ptr4 main_ = (my_main_ptr4) cinfo->main;
  167831. int ci, i, rgroup;
  167832. int M = cinfo->min_DCT_scaled_size;
  167833. jpeg_component_info *compptr;
  167834. JSAMPARRAY buf, xbuf0, xbuf1;
  167835. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  167836. ci++, compptr++) {
  167837. rgroup = (compptr->v_samp_factor * compptr->DCT_scaled_size) /
  167838. cinfo->min_DCT_scaled_size; /* height of a row group of component */
  167839. xbuf0 = main_->xbuffer[0][ci];
  167840. xbuf1 = main_->xbuffer[1][ci];
  167841. /* First copy the workspace pointers as-is */
  167842. buf = main_->buffer[ci];
  167843. for (i = 0; i < rgroup * (M + 2); i++) {
  167844. xbuf0[i] = xbuf1[i] = buf[i];
  167845. }
  167846. /* In the second list, put the last four row groups in swapped order */
  167847. for (i = 0; i < rgroup * 2; i++) {
  167848. xbuf1[rgroup*(M-2) + i] = buf[rgroup*M + i];
  167849. xbuf1[rgroup*M + i] = buf[rgroup*(M-2) + i];
  167850. }
  167851. /* The wraparound pointers at top and bottom will be filled later
  167852. * (see set_wraparound_pointers, below). Initially we want the "above"
  167853. * pointers to duplicate the first actual data line. This only needs
  167854. * to happen in xbuffer[0].
  167855. */
  167856. for (i = 0; i < rgroup; i++) {
  167857. xbuf0[i - rgroup] = xbuf0[0];
  167858. }
  167859. }
  167860. }
  167861. LOCAL(void)
  167862. set_wraparound_pointers (j_decompress_ptr cinfo)
  167863. /* Set up the "wraparound" pointers at top and bottom of the pointer lists.
  167864. * This changes the pointer list state from top-of-image to the normal state.
  167865. */
  167866. {
  167867. my_main_ptr4 main_ = (my_main_ptr4) cinfo->main;
  167868. int ci, i, rgroup;
  167869. int M = cinfo->min_DCT_scaled_size;
  167870. jpeg_component_info *compptr;
  167871. JSAMPARRAY xbuf0, xbuf1;
  167872. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  167873. ci++, compptr++) {
  167874. rgroup = (compptr->v_samp_factor * compptr->DCT_scaled_size) /
  167875. cinfo->min_DCT_scaled_size; /* height of a row group of component */
  167876. xbuf0 = main_->xbuffer[0][ci];
  167877. xbuf1 = main_->xbuffer[1][ci];
  167878. for (i = 0; i < rgroup; i++) {
  167879. xbuf0[i - rgroup] = xbuf0[rgroup*(M+1) + i];
  167880. xbuf1[i - rgroup] = xbuf1[rgroup*(M+1) + i];
  167881. xbuf0[rgroup*(M+2) + i] = xbuf0[i];
  167882. xbuf1[rgroup*(M+2) + i] = xbuf1[i];
  167883. }
  167884. }
  167885. }
  167886. LOCAL(void)
  167887. set_bottom_pointers (j_decompress_ptr cinfo)
  167888. /* Change the pointer lists to duplicate the last sample row at the bottom
  167889. * of the image. whichptr indicates which xbuffer holds the final iMCU row.
  167890. * Also sets rowgroups_avail to indicate number of nondummy row groups in row.
  167891. */
  167892. {
  167893. my_main_ptr4 main_ = (my_main_ptr4) cinfo->main;
  167894. int ci, i, rgroup, iMCUheight, rows_left;
  167895. jpeg_component_info *compptr;
  167896. JSAMPARRAY xbuf;
  167897. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  167898. ci++, compptr++) {
  167899. /* Count sample rows in one iMCU row and in one row group */
  167900. iMCUheight = compptr->v_samp_factor * compptr->DCT_scaled_size;
  167901. rgroup = iMCUheight / cinfo->min_DCT_scaled_size;
  167902. /* Count nondummy sample rows remaining for this component */
  167903. rows_left = (int) (compptr->downsampled_height % (JDIMENSION) iMCUheight);
  167904. if (rows_left == 0) rows_left = iMCUheight;
  167905. /* Count nondummy row groups. Should get same answer for each component,
  167906. * so we need only do it once.
  167907. */
  167908. if (ci == 0) {
  167909. main_->rowgroups_avail = (JDIMENSION) ((rows_left-1) / rgroup + 1);
  167910. }
  167911. /* Duplicate the last real sample row rgroup*2 times; this pads out the
  167912. * last partial rowgroup and ensures at least one full rowgroup of context.
  167913. */
  167914. xbuf = main_->xbuffer[main_->whichptr][ci];
  167915. for (i = 0; i < rgroup * 2; i++) {
  167916. xbuf[rows_left + i] = xbuf[rows_left-1];
  167917. }
  167918. }
  167919. }
  167920. /*
  167921. * Initialize for a processing pass.
  167922. */
  167923. METHODDEF(void)
  167924. start_pass_main2 (j_decompress_ptr cinfo, J_BUF_MODE pass_mode)
  167925. {
  167926. my_main_ptr4 main_ = (my_main_ptr4) cinfo->main;
  167927. switch (pass_mode) {
  167928. case JBUF_PASS_THRU:
  167929. if (cinfo->upsample->need_context_rows) {
  167930. main_->pub.process_data = process_data_context_main;
  167931. make_funny_pointers(cinfo); /* Create the xbuffer[] lists */
  167932. main_->whichptr = 0; /* Read first iMCU row into xbuffer[0] */
  167933. main_->context_state = CTX_PREPARE_FOR_IMCU;
  167934. main_->iMCU_row_ctr = 0;
  167935. } else {
  167936. /* Simple case with no context needed */
  167937. main_->pub.process_data = process_data_simple_main2;
  167938. }
  167939. main_->buffer_full = FALSE; /* Mark buffer empty */
  167940. main_->rowgroup_ctr = 0;
  167941. break;
  167942. #ifdef QUANT_2PASS_SUPPORTED
  167943. case JBUF_CRANK_DEST:
  167944. /* For last pass of 2-pass quantization, just crank the postprocessor */
  167945. main_->pub.process_data = process_data_crank_post;
  167946. break;
  167947. #endif
  167948. default:
  167949. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  167950. break;
  167951. }
  167952. }
  167953. /*
  167954. * Process some data.
  167955. * This handles the simple case where no context is required.
  167956. */
  167957. METHODDEF(void)
  167958. process_data_simple_main2 (j_decompress_ptr cinfo,
  167959. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  167960. JDIMENSION out_rows_avail)
  167961. {
  167962. my_main_ptr4 main_ = (my_main_ptr4) cinfo->main;
  167963. JDIMENSION rowgroups_avail;
  167964. /* Read input data if we haven't filled the main buffer yet */
  167965. if (! main_->buffer_full) {
  167966. if (! (*cinfo->coef->decompress_data) (cinfo, main_->buffer))
  167967. return; /* suspension forced, can do nothing more */
  167968. main_->buffer_full = TRUE; /* OK, we have an iMCU row to work with */
  167969. }
  167970. /* There are always min_DCT_scaled_size row groups in an iMCU row. */
  167971. rowgroups_avail = (JDIMENSION) cinfo->min_DCT_scaled_size;
  167972. /* Note: at the bottom of the image, we may pass extra garbage row groups
  167973. * to the postprocessor. The postprocessor has to check for bottom
  167974. * of image anyway (at row resolution), so no point in us doing it too.
  167975. */
  167976. /* Feed the postprocessor */
  167977. (*cinfo->post->post_process_data) (cinfo, main_->buffer,
  167978. &main_->rowgroup_ctr, rowgroups_avail,
  167979. output_buf, out_row_ctr, out_rows_avail);
  167980. /* Has postprocessor consumed all the data yet? If so, mark buffer empty */
  167981. if (main_->rowgroup_ctr >= rowgroups_avail) {
  167982. main_->buffer_full = FALSE;
  167983. main_->rowgroup_ctr = 0;
  167984. }
  167985. }
  167986. /*
  167987. * Process some data.
  167988. * This handles the case where context rows must be provided.
  167989. */
  167990. METHODDEF(void)
  167991. process_data_context_main (j_decompress_ptr cinfo,
  167992. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  167993. JDIMENSION out_rows_avail)
  167994. {
  167995. my_main_ptr4 main_ = (my_main_ptr4) cinfo->main;
  167996. /* Read input data if we haven't filled the main buffer yet */
  167997. if (! main_->buffer_full) {
  167998. if (! (*cinfo->coef->decompress_data) (cinfo,
  167999. main_->xbuffer[main_->whichptr]))
  168000. return; /* suspension forced, can do nothing more */
  168001. main_->buffer_full = TRUE; /* OK, we have an iMCU row to work with */
  168002. main_->iMCU_row_ctr++; /* count rows received */
  168003. }
  168004. /* Postprocessor typically will not swallow all the input data it is handed
  168005. * in one call (due to filling the output buffer first). Must be prepared
  168006. * to exit and restart. This switch lets us keep track of how far we got.
  168007. * Note that each case falls through to the next on successful completion.
  168008. */
  168009. switch (main_->context_state) {
  168010. case CTX_POSTPONED_ROW:
  168011. /* Call postprocessor using previously set pointers for postponed row */
  168012. (*cinfo->post->post_process_data) (cinfo, main_->xbuffer[main_->whichptr],
  168013. &main_->rowgroup_ctr, main_->rowgroups_avail,
  168014. output_buf, out_row_ctr, out_rows_avail);
  168015. if (main_->rowgroup_ctr < main_->rowgroups_avail)
  168016. return; /* Need to suspend */
  168017. main_->context_state = CTX_PREPARE_FOR_IMCU;
  168018. if (*out_row_ctr >= out_rows_avail)
  168019. return; /* Postprocessor exactly filled output buf */
  168020. /*FALLTHROUGH*/
  168021. case CTX_PREPARE_FOR_IMCU:
  168022. /* Prepare to process first M-1 row groups of this iMCU row */
  168023. main_->rowgroup_ctr = 0;
  168024. main_->rowgroups_avail = (JDIMENSION) (cinfo->min_DCT_scaled_size - 1);
  168025. /* Check for bottom of image: if so, tweak pointers to "duplicate"
  168026. * the last sample row, and adjust rowgroups_avail to ignore padding rows.
  168027. */
  168028. if (main_->iMCU_row_ctr == cinfo->total_iMCU_rows)
  168029. set_bottom_pointers(cinfo);
  168030. main_->context_state = CTX_PROCESS_IMCU;
  168031. /*FALLTHROUGH*/
  168032. case CTX_PROCESS_IMCU:
  168033. /* Call postprocessor using previously set pointers */
  168034. (*cinfo->post->post_process_data) (cinfo, main_->xbuffer[main_->whichptr],
  168035. &main_->rowgroup_ctr, main_->rowgroups_avail,
  168036. output_buf, out_row_ctr, out_rows_avail);
  168037. if (main_->rowgroup_ctr < main_->rowgroups_avail)
  168038. return; /* Need to suspend */
  168039. /* After the first iMCU, change wraparound pointers to normal state */
  168040. if (main_->iMCU_row_ctr == 1)
  168041. set_wraparound_pointers(cinfo);
  168042. /* Prepare to load new iMCU row using other xbuffer list */
  168043. main_->whichptr ^= 1; /* 0=>1 or 1=>0 */
  168044. main_->buffer_full = FALSE;
  168045. /* Still need to process last row group of this iMCU row, */
  168046. /* which is saved at index M+1 of the other xbuffer */
  168047. main_->rowgroup_ctr = (JDIMENSION) (cinfo->min_DCT_scaled_size + 1);
  168048. main_->rowgroups_avail = (JDIMENSION) (cinfo->min_DCT_scaled_size + 2);
  168049. main_->context_state = CTX_POSTPONED_ROW;
  168050. }
  168051. }
  168052. /*
  168053. * Process some data.
  168054. * Final pass of two-pass quantization: just call the postprocessor.
  168055. * Source data will be the postprocessor controller's internal buffer.
  168056. */
  168057. #ifdef QUANT_2PASS_SUPPORTED
  168058. METHODDEF(void)
  168059. process_data_crank_post (j_decompress_ptr cinfo,
  168060. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  168061. JDIMENSION out_rows_avail)
  168062. {
  168063. (*cinfo->post->post_process_data) (cinfo, (JSAMPIMAGE) NULL,
  168064. (JDIMENSION *) NULL, (JDIMENSION) 0,
  168065. output_buf, out_row_ctr, out_rows_avail);
  168066. }
  168067. #endif /* QUANT_2PASS_SUPPORTED */
  168068. /*
  168069. * Initialize main buffer controller.
  168070. */
  168071. GLOBAL(void)
  168072. jinit_d_main_controller (j_decompress_ptr cinfo, boolean need_full_buffer)
  168073. {
  168074. my_main_ptr4 main_;
  168075. int ci, rgroup, ngroups;
  168076. jpeg_component_info *compptr;
  168077. main_ = (my_main_ptr4)
  168078. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  168079. SIZEOF(my_main_controller4));
  168080. cinfo->main = (struct jpeg_d_main_controller *) main_;
  168081. main_->pub.start_pass = start_pass_main2;
  168082. if (need_full_buffer) /* shouldn't happen */
  168083. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  168084. /* Allocate the workspace.
  168085. * ngroups is the number of row groups we need.
  168086. */
  168087. if (cinfo->upsample->need_context_rows) {
  168088. if (cinfo->min_DCT_scaled_size < 2) /* unsupported, see comments above */
  168089. ERREXIT(cinfo, JERR_NOTIMPL);
  168090. alloc_funny_pointers(cinfo); /* Alloc space for xbuffer[] lists */
  168091. ngroups = cinfo->min_DCT_scaled_size + 2;
  168092. } else {
  168093. ngroups = cinfo->min_DCT_scaled_size;
  168094. }
  168095. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  168096. ci++, compptr++) {
  168097. rgroup = (compptr->v_samp_factor * compptr->DCT_scaled_size) /
  168098. cinfo->min_DCT_scaled_size; /* height of a row group of component */
  168099. main_->buffer[ci] = (*cinfo->mem->alloc_sarray)
  168100. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  168101. compptr->width_in_blocks * compptr->DCT_scaled_size,
  168102. (JDIMENSION) (rgroup * ngroups));
  168103. }
  168104. }
  168105. /*** End of inlined file: jdmainct.c ***/
  168106. /*** Start of inlined file: jdmarker.c ***/
  168107. #define JPEG_INTERNALS
  168108. /* Private state */
  168109. typedef struct {
  168110. struct jpeg_marker_reader pub; /* public fields */
  168111. /* Application-overridable marker processing methods */
  168112. jpeg_marker_parser_method process_COM;
  168113. jpeg_marker_parser_method process_APPn[16];
  168114. /* Limit on marker data length to save for each marker type */
  168115. unsigned int length_limit_COM;
  168116. unsigned int length_limit_APPn[16];
  168117. /* Status of COM/APPn marker saving */
  168118. jpeg_saved_marker_ptr cur_marker; /* NULL if not processing a marker */
  168119. unsigned int bytes_read; /* data bytes read so far in marker */
  168120. /* Note: cur_marker is not linked into marker_list until it's all read. */
  168121. } my_marker_reader;
  168122. typedef my_marker_reader * my_marker_ptr2;
  168123. /*
  168124. * Macros for fetching data from the data source module.
  168125. *
  168126. * At all times, cinfo->src->next_input_byte and ->bytes_in_buffer reflect
  168127. * the current restart point; we update them only when we have reached a
  168128. * suitable place to restart if a suspension occurs.
  168129. */
  168130. /* Declare and initialize local copies of input pointer/count */
  168131. #define INPUT_VARS(cinfo) \
  168132. struct jpeg_source_mgr * datasrc = (cinfo)->src; \
  168133. const JOCTET * next_input_byte = datasrc->next_input_byte; \
  168134. size_t bytes_in_buffer = datasrc->bytes_in_buffer
  168135. /* Unload the local copies --- do this only at a restart boundary */
  168136. #define INPUT_SYNC(cinfo) \
  168137. ( datasrc->next_input_byte = next_input_byte, \
  168138. datasrc->bytes_in_buffer = bytes_in_buffer )
  168139. /* Reload the local copies --- used only in MAKE_BYTE_AVAIL */
  168140. #define INPUT_RELOAD(cinfo) \
  168141. ( next_input_byte = datasrc->next_input_byte, \
  168142. bytes_in_buffer = datasrc->bytes_in_buffer )
  168143. /* Internal macro for INPUT_BYTE and INPUT_2BYTES: make a byte available.
  168144. * Note we do *not* do INPUT_SYNC before calling fill_input_buffer,
  168145. * but we must reload the local copies after a successful fill.
  168146. */
  168147. #define MAKE_BYTE_AVAIL(cinfo,action) \
  168148. if (bytes_in_buffer == 0) { \
  168149. if (! (*datasrc->fill_input_buffer) (cinfo)) \
  168150. { action; } \
  168151. INPUT_RELOAD(cinfo); \
  168152. }
  168153. /* Read a byte into variable V.
  168154. * If must suspend, take the specified action (typically "return FALSE").
  168155. */
  168156. #define INPUT_BYTE(cinfo,V,action) \
  168157. MAKESTMT( MAKE_BYTE_AVAIL(cinfo,action); \
  168158. bytes_in_buffer--; \
  168159. V = GETJOCTET(*next_input_byte++); )
  168160. /* As above, but read two bytes interpreted as an unsigned 16-bit integer.
  168161. * V should be declared unsigned int or perhaps INT32.
  168162. */
  168163. #define INPUT_2BYTES(cinfo,V,action) \
  168164. MAKESTMT( MAKE_BYTE_AVAIL(cinfo,action); \
  168165. bytes_in_buffer--; \
  168166. V = ((unsigned int) GETJOCTET(*next_input_byte++)) << 8; \
  168167. MAKE_BYTE_AVAIL(cinfo,action); \
  168168. bytes_in_buffer--; \
  168169. V += GETJOCTET(*next_input_byte++); )
  168170. /*
  168171. * Routines to process JPEG markers.
  168172. *
  168173. * Entry condition: JPEG marker itself has been read and its code saved
  168174. * in cinfo->unread_marker; input restart point is just after the marker.
  168175. *
  168176. * Exit: if return TRUE, have read and processed any parameters, and have
  168177. * updated the restart point to point after the parameters.
  168178. * If return FALSE, was forced to suspend before reaching end of
  168179. * marker parameters; restart point has not been moved. Same routine
  168180. * will be called again after application supplies more input data.
  168181. *
  168182. * This approach to suspension assumes that all of a marker's parameters
  168183. * can fit into a single input bufferload. This should hold for "normal"
  168184. * markers. Some COM/APPn markers might have large parameter segments
  168185. * that might not fit. If we are simply dropping such a marker, we use
  168186. * skip_input_data to get past it, and thereby put the problem on the
  168187. * source manager's shoulders. If we are saving the marker's contents
  168188. * into memory, we use a slightly different convention: when forced to
  168189. * suspend, the marker processor updates the restart point to the end of
  168190. * what it's consumed (ie, the end of the buffer) before returning FALSE.
  168191. * On resumption, cinfo->unread_marker still contains the marker code,
  168192. * but the data source will point to the next chunk of marker data.
  168193. * The marker processor must retain internal state to deal with this.
  168194. *
  168195. * Note that we don't bother to avoid duplicate trace messages if a
  168196. * suspension occurs within marker parameters. Other side effects
  168197. * require more care.
  168198. */
  168199. LOCAL(boolean)
  168200. get_soi (j_decompress_ptr cinfo)
  168201. /* Process an SOI marker */
  168202. {
  168203. int i;
  168204. TRACEMS(cinfo, 1, JTRC_SOI);
  168205. if (cinfo->marker->saw_SOI)
  168206. ERREXIT(cinfo, JERR_SOI_DUPLICATE);
  168207. /* Reset all parameters that are defined to be reset by SOI */
  168208. for (i = 0; i < NUM_ARITH_TBLS; i++) {
  168209. cinfo->arith_dc_L[i] = 0;
  168210. cinfo->arith_dc_U[i] = 1;
  168211. cinfo->arith_ac_K[i] = 5;
  168212. }
  168213. cinfo->restart_interval = 0;
  168214. /* Set initial assumptions for colorspace etc */
  168215. cinfo->jpeg_color_space = JCS_UNKNOWN;
  168216. cinfo->CCIR601_sampling = FALSE; /* Assume non-CCIR sampling??? */
  168217. cinfo->saw_JFIF_marker = FALSE;
  168218. cinfo->JFIF_major_version = 1; /* set default JFIF APP0 values */
  168219. cinfo->JFIF_minor_version = 1;
  168220. cinfo->density_unit = 0;
  168221. cinfo->X_density = 1;
  168222. cinfo->Y_density = 1;
  168223. cinfo->saw_Adobe_marker = FALSE;
  168224. cinfo->Adobe_transform = 0;
  168225. cinfo->marker->saw_SOI = TRUE;
  168226. return TRUE;
  168227. }
  168228. LOCAL(boolean)
  168229. get_sof (j_decompress_ptr cinfo, boolean is_prog, boolean is_arith)
  168230. /* Process a SOFn marker */
  168231. {
  168232. INT32 length;
  168233. int c, ci;
  168234. jpeg_component_info * compptr;
  168235. INPUT_VARS(cinfo);
  168236. cinfo->progressive_mode = is_prog;
  168237. cinfo->arith_code = is_arith;
  168238. INPUT_2BYTES(cinfo, length, return FALSE);
  168239. INPUT_BYTE(cinfo, cinfo->data_precision, return FALSE);
  168240. INPUT_2BYTES(cinfo, cinfo->image_height, return FALSE);
  168241. INPUT_2BYTES(cinfo, cinfo->image_width, return FALSE);
  168242. INPUT_BYTE(cinfo, cinfo->num_components, return FALSE);
  168243. length -= 8;
  168244. TRACEMS4(cinfo, 1, JTRC_SOF, cinfo->unread_marker,
  168245. (int) cinfo->image_width, (int) cinfo->image_height,
  168246. cinfo->num_components);
  168247. if (cinfo->marker->saw_SOF)
  168248. ERREXIT(cinfo, JERR_SOF_DUPLICATE);
  168249. /* We don't support files in which the image height is initially specified */
  168250. /* as 0 and is later redefined by DNL. As long as we have to check that, */
  168251. /* might as well have a general sanity check. */
  168252. if (cinfo->image_height <= 0 || cinfo->image_width <= 0
  168253. || cinfo->num_components <= 0)
  168254. ERREXIT(cinfo, JERR_EMPTY_IMAGE);
  168255. if (length != (cinfo->num_components * 3))
  168256. ERREXIT(cinfo, JERR_BAD_LENGTH);
  168257. if (cinfo->comp_info == NULL) /* do only once, even if suspend */
  168258. cinfo->comp_info = (jpeg_component_info *) (*cinfo->mem->alloc_small)
  168259. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  168260. cinfo->num_components * SIZEOF(jpeg_component_info));
  168261. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  168262. ci++, compptr++) {
  168263. compptr->component_index = ci;
  168264. INPUT_BYTE(cinfo, compptr->component_id, return FALSE);
  168265. INPUT_BYTE(cinfo, c, return FALSE);
  168266. compptr->h_samp_factor = (c >> 4) & 15;
  168267. compptr->v_samp_factor = (c ) & 15;
  168268. INPUT_BYTE(cinfo, compptr->quant_tbl_no, return FALSE);
  168269. TRACEMS4(cinfo, 1, JTRC_SOF_COMPONENT,
  168270. compptr->component_id, compptr->h_samp_factor,
  168271. compptr->v_samp_factor, compptr->quant_tbl_no);
  168272. }
  168273. cinfo->marker->saw_SOF = TRUE;
  168274. INPUT_SYNC(cinfo);
  168275. return TRUE;
  168276. }
  168277. LOCAL(boolean)
  168278. get_sos (j_decompress_ptr cinfo)
  168279. /* Process a SOS marker */
  168280. {
  168281. INT32 length;
  168282. int i, ci, n, c, cc;
  168283. jpeg_component_info * compptr;
  168284. INPUT_VARS(cinfo);
  168285. if (! cinfo->marker->saw_SOF)
  168286. ERREXIT(cinfo, JERR_SOS_NO_SOF);
  168287. INPUT_2BYTES(cinfo, length, return FALSE);
  168288. INPUT_BYTE(cinfo, n, return FALSE); /* Number of components */
  168289. TRACEMS1(cinfo, 1, JTRC_SOS, n);
  168290. if (length != (n * 2 + 6) || n < 1 || n > MAX_COMPS_IN_SCAN)
  168291. ERREXIT(cinfo, JERR_BAD_LENGTH);
  168292. cinfo->comps_in_scan = n;
  168293. /* Collect the component-spec parameters */
  168294. for (i = 0; i < n; i++) {
  168295. INPUT_BYTE(cinfo, cc, return FALSE);
  168296. INPUT_BYTE(cinfo, c, return FALSE);
  168297. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  168298. ci++, compptr++) {
  168299. if (cc == compptr->component_id)
  168300. goto id_found;
  168301. }
  168302. ERREXIT1(cinfo, JERR_BAD_COMPONENT_ID, cc);
  168303. id_found:
  168304. cinfo->cur_comp_info[i] = compptr;
  168305. compptr->dc_tbl_no = (c >> 4) & 15;
  168306. compptr->ac_tbl_no = (c ) & 15;
  168307. TRACEMS3(cinfo, 1, JTRC_SOS_COMPONENT, cc,
  168308. compptr->dc_tbl_no, compptr->ac_tbl_no);
  168309. }
  168310. /* Collect the additional scan parameters Ss, Se, Ah/Al. */
  168311. INPUT_BYTE(cinfo, c, return FALSE);
  168312. cinfo->Ss = c;
  168313. INPUT_BYTE(cinfo, c, return FALSE);
  168314. cinfo->Se = c;
  168315. INPUT_BYTE(cinfo, c, return FALSE);
  168316. cinfo->Ah = (c >> 4) & 15;
  168317. cinfo->Al = (c ) & 15;
  168318. TRACEMS4(cinfo, 1, JTRC_SOS_PARAMS, cinfo->Ss, cinfo->Se,
  168319. cinfo->Ah, cinfo->Al);
  168320. /* Prepare to scan data & restart markers */
  168321. cinfo->marker->next_restart_num = 0;
  168322. /* Count another SOS marker */
  168323. cinfo->input_scan_number++;
  168324. INPUT_SYNC(cinfo);
  168325. return TRUE;
  168326. }
  168327. #ifdef D_ARITH_CODING_SUPPORTED
  168328. LOCAL(boolean)
  168329. get_dac (j_decompress_ptr cinfo)
  168330. /* Process a DAC marker */
  168331. {
  168332. INT32 length;
  168333. int index, val;
  168334. INPUT_VARS(cinfo);
  168335. INPUT_2BYTES(cinfo, length, return FALSE);
  168336. length -= 2;
  168337. while (length > 0) {
  168338. INPUT_BYTE(cinfo, index, return FALSE);
  168339. INPUT_BYTE(cinfo, val, return FALSE);
  168340. length -= 2;
  168341. TRACEMS2(cinfo, 1, JTRC_DAC, index, val);
  168342. if (index < 0 || index >= (2*NUM_ARITH_TBLS))
  168343. ERREXIT1(cinfo, JERR_DAC_INDEX, index);
  168344. if (index >= NUM_ARITH_TBLS) { /* define AC table */
  168345. cinfo->arith_ac_K[index-NUM_ARITH_TBLS] = (UINT8) val;
  168346. } else { /* define DC table */
  168347. cinfo->arith_dc_L[index] = (UINT8) (val & 0x0F);
  168348. cinfo->arith_dc_U[index] = (UINT8) (val >> 4);
  168349. if (cinfo->arith_dc_L[index] > cinfo->arith_dc_U[index])
  168350. ERREXIT1(cinfo, JERR_DAC_VALUE, val);
  168351. }
  168352. }
  168353. if (length != 0)
  168354. ERREXIT(cinfo, JERR_BAD_LENGTH);
  168355. INPUT_SYNC(cinfo);
  168356. return TRUE;
  168357. }
  168358. #else /* ! D_ARITH_CODING_SUPPORTED */
  168359. #define get_dac(cinfo) skip_variable(cinfo)
  168360. #endif /* D_ARITH_CODING_SUPPORTED */
  168361. LOCAL(boolean)
  168362. get_dht (j_decompress_ptr cinfo)
  168363. /* Process a DHT marker */
  168364. {
  168365. INT32 length;
  168366. UINT8 bits[17];
  168367. UINT8 huffval[256];
  168368. int i, index, count;
  168369. JHUFF_TBL **htblptr;
  168370. INPUT_VARS(cinfo);
  168371. INPUT_2BYTES(cinfo, length, return FALSE);
  168372. length -= 2;
  168373. while (length > 16) {
  168374. INPUT_BYTE(cinfo, index, return FALSE);
  168375. TRACEMS1(cinfo, 1, JTRC_DHT, index);
  168376. bits[0] = 0;
  168377. count = 0;
  168378. for (i = 1; i <= 16; i++) {
  168379. INPUT_BYTE(cinfo, bits[i], return FALSE);
  168380. count += bits[i];
  168381. }
  168382. length -= 1 + 16;
  168383. TRACEMS8(cinfo, 2, JTRC_HUFFBITS,
  168384. bits[1], bits[2], bits[3], bits[4],
  168385. bits[5], bits[6], bits[7], bits[8]);
  168386. TRACEMS8(cinfo, 2, JTRC_HUFFBITS,
  168387. bits[9], bits[10], bits[11], bits[12],
  168388. bits[13], bits[14], bits[15], bits[16]);
  168389. /* Here we just do minimal validation of the counts to avoid walking
  168390. * off the end of our table space. jdhuff.c will check more carefully.
  168391. */
  168392. if (count > 256 || ((INT32) count) > length)
  168393. ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
  168394. for (i = 0; i < count; i++)
  168395. INPUT_BYTE(cinfo, huffval[i], return FALSE);
  168396. length -= count;
  168397. if (index & 0x10) { /* AC table definition */
  168398. index -= 0x10;
  168399. htblptr = &cinfo->ac_huff_tbl_ptrs[index];
  168400. } else { /* DC table definition */
  168401. htblptr = &cinfo->dc_huff_tbl_ptrs[index];
  168402. }
  168403. if (index < 0 || index >= NUM_HUFF_TBLS)
  168404. ERREXIT1(cinfo, JERR_DHT_INDEX, index);
  168405. if (*htblptr == NULL)
  168406. *htblptr = jpeg_alloc_huff_table((j_common_ptr) cinfo);
  168407. MEMCOPY((*htblptr)->bits, bits, SIZEOF((*htblptr)->bits));
  168408. MEMCOPY((*htblptr)->huffval, huffval, SIZEOF((*htblptr)->huffval));
  168409. }
  168410. if (length != 0)
  168411. ERREXIT(cinfo, JERR_BAD_LENGTH);
  168412. INPUT_SYNC(cinfo);
  168413. return TRUE;
  168414. }
  168415. LOCAL(boolean)
  168416. get_dqt (j_decompress_ptr cinfo)
  168417. /* Process a DQT marker */
  168418. {
  168419. INT32 length;
  168420. int n, i, prec;
  168421. unsigned int tmp;
  168422. JQUANT_TBL *quant_ptr;
  168423. INPUT_VARS(cinfo);
  168424. INPUT_2BYTES(cinfo, length, return FALSE);
  168425. length -= 2;
  168426. while (length > 0) {
  168427. INPUT_BYTE(cinfo, n, return FALSE);
  168428. prec = n >> 4;
  168429. n &= 0x0F;
  168430. TRACEMS2(cinfo, 1, JTRC_DQT, n, prec);
  168431. if (n >= NUM_QUANT_TBLS)
  168432. ERREXIT1(cinfo, JERR_DQT_INDEX, n);
  168433. if (cinfo->quant_tbl_ptrs[n] == NULL)
  168434. cinfo->quant_tbl_ptrs[n] = jpeg_alloc_quant_table((j_common_ptr) cinfo);
  168435. quant_ptr = cinfo->quant_tbl_ptrs[n];
  168436. for (i = 0; i < DCTSIZE2; i++) {
  168437. if (prec)
  168438. INPUT_2BYTES(cinfo, tmp, return FALSE);
  168439. else
  168440. INPUT_BYTE(cinfo, tmp, return FALSE);
  168441. /* We convert the zigzag-order table to natural array order. */
  168442. quant_ptr->quantval[jpeg_natural_order[i]] = (UINT16) tmp;
  168443. }
  168444. if (cinfo->err->trace_level >= 2) {
  168445. for (i = 0; i < DCTSIZE2; i += 8) {
  168446. TRACEMS8(cinfo, 2, JTRC_QUANTVALS,
  168447. quant_ptr->quantval[i], quant_ptr->quantval[i+1],
  168448. quant_ptr->quantval[i+2], quant_ptr->quantval[i+3],
  168449. quant_ptr->quantval[i+4], quant_ptr->quantval[i+5],
  168450. quant_ptr->quantval[i+6], quant_ptr->quantval[i+7]);
  168451. }
  168452. }
  168453. length -= DCTSIZE2+1;
  168454. if (prec) length -= DCTSIZE2;
  168455. }
  168456. if (length != 0)
  168457. ERREXIT(cinfo, JERR_BAD_LENGTH);
  168458. INPUT_SYNC(cinfo);
  168459. return TRUE;
  168460. }
  168461. LOCAL(boolean)
  168462. get_dri (j_decompress_ptr cinfo)
  168463. /* Process a DRI marker */
  168464. {
  168465. INT32 length;
  168466. unsigned int tmp;
  168467. INPUT_VARS(cinfo);
  168468. INPUT_2BYTES(cinfo, length, return FALSE);
  168469. if (length != 4)
  168470. ERREXIT(cinfo, JERR_BAD_LENGTH);
  168471. INPUT_2BYTES(cinfo, tmp, return FALSE);
  168472. TRACEMS1(cinfo, 1, JTRC_DRI, tmp);
  168473. cinfo->restart_interval = tmp;
  168474. INPUT_SYNC(cinfo);
  168475. return TRUE;
  168476. }
  168477. /*
  168478. * Routines for processing APPn and COM markers.
  168479. * These are either saved in memory or discarded, per application request.
  168480. * APP0 and APP14 are specially checked to see if they are
  168481. * JFIF and Adobe markers, respectively.
  168482. */
  168483. #define APP0_DATA_LEN 14 /* Length of interesting data in APP0 */
  168484. #define APP14_DATA_LEN 12 /* Length of interesting data in APP14 */
  168485. #define APPN_DATA_LEN 14 /* Must be the largest of the above!! */
  168486. LOCAL(void)
  168487. examine_app0 (j_decompress_ptr cinfo, JOCTET FAR * data,
  168488. unsigned int datalen, INT32 remaining)
  168489. /* Examine first few bytes from an APP0.
  168490. * Take appropriate action if it is a JFIF marker.
  168491. * datalen is # of bytes at data[], remaining is length of rest of marker data.
  168492. */
  168493. {
  168494. INT32 totallen = (INT32) datalen + remaining;
  168495. if (datalen >= APP0_DATA_LEN &&
  168496. GETJOCTET(data[0]) == 0x4A &&
  168497. GETJOCTET(data[1]) == 0x46 &&
  168498. GETJOCTET(data[2]) == 0x49 &&
  168499. GETJOCTET(data[3]) == 0x46 &&
  168500. GETJOCTET(data[4]) == 0) {
  168501. /* Found JFIF APP0 marker: save info */
  168502. cinfo->saw_JFIF_marker = TRUE;
  168503. cinfo->JFIF_major_version = GETJOCTET(data[5]);
  168504. cinfo->JFIF_minor_version = GETJOCTET(data[6]);
  168505. cinfo->density_unit = GETJOCTET(data[7]);
  168506. cinfo->X_density = (GETJOCTET(data[8]) << 8) + GETJOCTET(data[9]);
  168507. cinfo->Y_density = (GETJOCTET(data[10]) << 8) + GETJOCTET(data[11]);
  168508. /* Check version.
  168509. * Major version must be 1, anything else signals an incompatible change.
  168510. * (We used to treat this as an error, but now it's a nonfatal warning,
  168511. * because some bozo at Hijaak couldn't read the spec.)
  168512. * Minor version should be 0..2, but process anyway if newer.
  168513. */
  168514. if (cinfo->JFIF_major_version != 1)
  168515. WARNMS2(cinfo, JWRN_JFIF_MAJOR,
  168516. cinfo->JFIF_major_version, cinfo->JFIF_minor_version);
  168517. /* Generate trace messages */
  168518. TRACEMS5(cinfo, 1, JTRC_JFIF,
  168519. cinfo->JFIF_major_version, cinfo->JFIF_minor_version,
  168520. cinfo->X_density, cinfo->Y_density, cinfo->density_unit);
  168521. /* Validate thumbnail dimensions and issue appropriate messages */
  168522. if (GETJOCTET(data[12]) | GETJOCTET(data[13]))
  168523. TRACEMS2(cinfo, 1, JTRC_JFIF_THUMBNAIL,
  168524. GETJOCTET(data[12]), GETJOCTET(data[13]));
  168525. totallen -= APP0_DATA_LEN;
  168526. if (totallen !=
  168527. ((INT32)GETJOCTET(data[12]) * (INT32)GETJOCTET(data[13]) * (INT32) 3))
  168528. TRACEMS1(cinfo, 1, JTRC_JFIF_BADTHUMBNAILSIZE, (int) totallen);
  168529. } else if (datalen >= 6 &&
  168530. GETJOCTET(data[0]) == 0x4A &&
  168531. GETJOCTET(data[1]) == 0x46 &&
  168532. GETJOCTET(data[2]) == 0x58 &&
  168533. GETJOCTET(data[3]) == 0x58 &&
  168534. GETJOCTET(data[4]) == 0) {
  168535. /* Found JFIF "JFXX" extension APP0 marker */
  168536. /* The library doesn't actually do anything with these,
  168537. * but we try to produce a helpful trace message.
  168538. */
  168539. switch (GETJOCTET(data[5])) {
  168540. case 0x10:
  168541. TRACEMS1(cinfo, 1, JTRC_THUMB_JPEG, (int) totallen);
  168542. break;
  168543. case 0x11:
  168544. TRACEMS1(cinfo, 1, JTRC_THUMB_PALETTE, (int) totallen);
  168545. break;
  168546. case 0x13:
  168547. TRACEMS1(cinfo, 1, JTRC_THUMB_RGB, (int) totallen);
  168548. break;
  168549. default:
  168550. TRACEMS2(cinfo, 1, JTRC_JFIF_EXTENSION,
  168551. GETJOCTET(data[5]), (int) totallen);
  168552. break;
  168553. }
  168554. } else {
  168555. /* Start of APP0 does not match "JFIF" or "JFXX", or too short */
  168556. TRACEMS1(cinfo, 1, JTRC_APP0, (int) totallen);
  168557. }
  168558. }
  168559. LOCAL(void)
  168560. examine_app14 (j_decompress_ptr cinfo, JOCTET FAR * data,
  168561. unsigned int datalen, INT32 remaining)
  168562. /* Examine first few bytes from an APP14.
  168563. * Take appropriate action if it is an Adobe marker.
  168564. * datalen is # of bytes at data[], remaining is length of rest of marker data.
  168565. */
  168566. {
  168567. unsigned int version, flags0, flags1, transform;
  168568. if (datalen >= APP14_DATA_LEN &&
  168569. GETJOCTET(data[0]) == 0x41 &&
  168570. GETJOCTET(data[1]) == 0x64 &&
  168571. GETJOCTET(data[2]) == 0x6F &&
  168572. GETJOCTET(data[3]) == 0x62 &&
  168573. GETJOCTET(data[4]) == 0x65) {
  168574. /* Found Adobe APP14 marker */
  168575. version = (GETJOCTET(data[5]) << 8) + GETJOCTET(data[6]);
  168576. flags0 = (GETJOCTET(data[7]) << 8) + GETJOCTET(data[8]);
  168577. flags1 = (GETJOCTET(data[9]) << 8) + GETJOCTET(data[10]);
  168578. transform = GETJOCTET(data[11]);
  168579. TRACEMS4(cinfo, 1, JTRC_ADOBE, version, flags0, flags1, transform);
  168580. cinfo->saw_Adobe_marker = TRUE;
  168581. cinfo->Adobe_transform = (UINT8) transform;
  168582. } else {
  168583. /* Start of APP14 does not match "Adobe", or too short */
  168584. TRACEMS1(cinfo, 1, JTRC_APP14, (int) (datalen + remaining));
  168585. }
  168586. }
  168587. METHODDEF(boolean)
  168588. get_interesting_appn (j_decompress_ptr cinfo)
  168589. /* Process an APP0 or APP14 marker without saving it */
  168590. {
  168591. INT32 length;
  168592. JOCTET b[APPN_DATA_LEN];
  168593. unsigned int i, numtoread;
  168594. INPUT_VARS(cinfo);
  168595. INPUT_2BYTES(cinfo, length, return FALSE);
  168596. length -= 2;
  168597. /* get the interesting part of the marker data */
  168598. if (length >= APPN_DATA_LEN)
  168599. numtoread = APPN_DATA_LEN;
  168600. else if (length > 0)
  168601. numtoread = (unsigned int) length;
  168602. else
  168603. numtoread = 0;
  168604. for (i = 0; i < numtoread; i++)
  168605. INPUT_BYTE(cinfo, b[i], return FALSE);
  168606. length -= numtoread;
  168607. /* process it */
  168608. switch (cinfo->unread_marker) {
  168609. case M_APP0:
  168610. examine_app0(cinfo, (JOCTET FAR *) b, numtoread, length);
  168611. break;
  168612. case M_APP14:
  168613. examine_app14(cinfo, (JOCTET FAR *) b, numtoread, length);
  168614. break;
  168615. default:
  168616. /* can't get here unless jpeg_save_markers chooses wrong processor */
  168617. ERREXIT1(cinfo, JERR_UNKNOWN_MARKER, cinfo->unread_marker);
  168618. break;
  168619. }
  168620. /* skip any remaining data -- could be lots */
  168621. INPUT_SYNC(cinfo);
  168622. if (length > 0)
  168623. (*cinfo->src->skip_input_data) (cinfo, (long) length);
  168624. return TRUE;
  168625. }
  168626. #ifdef SAVE_MARKERS_SUPPORTED
  168627. METHODDEF(boolean)
  168628. save_marker (j_decompress_ptr cinfo)
  168629. /* Save an APPn or COM marker into the marker list */
  168630. {
  168631. my_marker_ptr2 marker = (my_marker_ptr2) cinfo->marker;
  168632. jpeg_saved_marker_ptr cur_marker = marker->cur_marker;
  168633. unsigned int bytes_read, data_length;
  168634. JOCTET FAR * data;
  168635. INT32 length = 0;
  168636. INPUT_VARS(cinfo);
  168637. if (cur_marker == NULL) {
  168638. /* begin reading a marker */
  168639. INPUT_2BYTES(cinfo, length, return FALSE);
  168640. length -= 2;
  168641. if (length >= 0) { /* watch out for bogus length word */
  168642. /* figure out how much we want to save */
  168643. unsigned int limit;
  168644. if (cinfo->unread_marker == (int) M_COM)
  168645. limit = marker->length_limit_COM;
  168646. else
  168647. limit = marker->length_limit_APPn[cinfo->unread_marker - (int) M_APP0];
  168648. if ((unsigned int) length < limit)
  168649. limit = (unsigned int) length;
  168650. /* allocate and initialize the marker item */
  168651. cur_marker = (jpeg_saved_marker_ptr)
  168652. (*cinfo->mem->alloc_large) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  168653. SIZEOF(struct jpeg_marker_struct) + limit);
  168654. cur_marker->next = NULL;
  168655. cur_marker->marker = (UINT8) cinfo->unread_marker;
  168656. cur_marker->original_length = (unsigned int) length;
  168657. cur_marker->data_length = limit;
  168658. /* data area is just beyond the jpeg_marker_struct */
  168659. data = cur_marker->data = (JOCTET FAR *) (cur_marker + 1);
  168660. marker->cur_marker = cur_marker;
  168661. marker->bytes_read = 0;
  168662. bytes_read = 0;
  168663. data_length = limit;
  168664. } else {
  168665. /* deal with bogus length word */
  168666. bytes_read = data_length = 0;
  168667. data = NULL;
  168668. }
  168669. } else {
  168670. /* resume reading a marker */
  168671. bytes_read = marker->bytes_read;
  168672. data_length = cur_marker->data_length;
  168673. data = cur_marker->data + bytes_read;
  168674. }
  168675. while (bytes_read < data_length) {
  168676. INPUT_SYNC(cinfo); /* move the restart point to here */
  168677. marker->bytes_read = bytes_read;
  168678. /* If there's not at least one byte in buffer, suspend */
  168679. MAKE_BYTE_AVAIL(cinfo, return FALSE);
  168680. /* Copy bytes with reasonable rapidity */
  168681. while (bytes_read < data_length && bytes_in_buffer > 0) {
  168682. *data++ = *next_input_byte++;
  168683. bytes_in_buffer--;
  168684. bytes_read++;
  168685. }
  168686. }
  168687. /* Done reading what we want to read */
  168688. if (cur_marker != NULL) { /* will be NULL if bogus length word */
  168689. /* Add new marker to end of list */
  168690. if (cinfo->marker_list == NULL) {
  168691. cinfo->marker_list = cur_marker;
  168692. } else {
  168693. jpeg_saved_marker_ptr prev = cinfo->marker_list;
  168694. while (prev->next != NULL)
  168695. prev = prev->next;
  168696. prev->next = cur_marker;
  168697. }
  168698. /* Reset pointer & calc remaining data length */
  168699. data = cur_marker->data;
  168700. length = cur_marker->original_length - data_length;
  168701. }
  168702. /* Reset to initial state for next marker */
  168703. marker->cur_marker = NULL;
  168704. /* Process the marker if interesting; else just make a generic trace msg */
  168705. switch (cinfo->unread_marker) {
  168706. case M_APP0:
  168707. examine_app0(cinfo, data, data_length, length);
  168708. break;
  168709. case M_APP14:
  168710. examine_app14(cinfo, data, data_length, length);
  168711. break;
  168712. default:
  168713. TRACEMS2(cinfo, 1, JTRC_MISC_MARKER, cinfo->unread_marker,
  168714. (int) (data_length + length));
  168715. break;
  168716. }
  168717. /* skip any remaining data -- could be lots */
  168718. INPUT_SYNC(cinfo); /* do before skip_input_data */
  168719. if (length > 0)
  168720. (*cinfo->src->skip_input_data) (cinfo, (long) length);
  168721. return TRUE;
  168722. }
  168723. #endif /* SAVE_MARKERS_SUPPORTED */
  168724. METHODDEF(boolean)
  168725. skip_variable (j_decompress_ptr cinfo)
  168726. /* Skip over an unknown or uninteresting variable-length marker */
  168727. {
  168728. INT32 length;
  168729. INPUT_VARS(cinfo);
  168730. INPUT_2BYTES(cinfo, length, return FALSE);
  168731. length -= 2;
  168732. TRACEMS2(cinfo, 1, JTRC_MISC_MARKER, cinfo->unread_marker, (int) length);
  168733. INPUT_SYNC(cinfo); /* do before skip_input_data */
  168734. if (length > 0)
  168735. (*cinfo->src->skip_input_data) (cinfo, (long) length);
  168736. return TRUE;
  168737. }
  168738. /*
  168739. * Find the next JPEG marker, save it in cinfo->unread_marker.
  168740. * Returns FALSE if had to suspend before reaching a marker;
  168741. * in that case cinfo->unread_marker is unchanged.
  168742. *
  168743. * Note that the result might not be a valid marker code,
  168744. * but it will never be 0 or FF.
  168745. */
  168746. LOCAL(boolean)
  168747. next_marker (j_decompress_ptr cinfo)
  168748. {
  168749. int c;
  168750. INPUT_VARS(cinfo);
  168751. for (;;) {
  168752. INPUT_BYTE(cinfo, c, return FALSE);
  168753. /* Skip any non-FF bytes.
  168754. * This may look a bit inefficient, but it will not occur in a valid file.
  168755. * We sync after each discarded byte so that a suspending data source
  168756. * can discard the byte from its buffer.
  168757. */
  168758. while (c != 0xFF) {
  168759. cinfo->marker->discarded_bytes++;
  168760. INPUT_SYNC(cinfo);
  168761. INPUT_BYTE(cinfo, c, return FALSE);
  168762. }
  168763. /* This loop swallows any duplicate FF bytes. Extra FFs are legal as
  168764. * pad bytes, so don't count them in discarded_bytes. We assume there
  168765. * will not be so many consecutive FF bytes as to overflow a suspending
  168766. * data source's input buffer.
  168767. */
  168768. do {
  168769. INPUT_BYTE(cinfo, c, return FALSE);
  168770. } while (c == 0xFF);
  168771. if (c != 0)
  168772. break; /* found a valid marker, exit loop */
  168773. /* Reach here if we found a stuffed-zero data sequence (FF/00).
  168774. * Discard it and loop back to try again.
  168775. */
  168776. cinfo->marker->discarded_bytes += 2;
  168777. INPUT_SYNC(cinfo);
  168778. }
  168779. if (cinfo->marker->discarded_bytes != 0) {
  168780. WARNMS2(cinfo, JWRN_EXTRANEOUS_DATA, cinfo->marker->discarded_bytes, c);
  168781. cinfo->marker->discarded_bytes = 0;
  168782. }
  168783. cinfo->unread_marker = c;
  168784. INPUT_SYNC(cinfo);
  168785. return TRUE;
  168786. }
  168787. LOCAL(boolean)
  168788. first_marker (j_decompress_ptr cinfo)
  168789. /* Like next_marker, but used to obtain the initial SOI marker. */
  168790. /* For this marker, we do not allow preceding garbage or fill; otherwise,
  168791. * we might well scan an entire input file before realizing it ain't JPEG.
  168792. * If an application wants to process non-JFIF files, it must seek to the
  168793. * SOI before calling the JPEG library.
  168794. */
  168795. {
  168796. int c, c2;
  168797. INPUT_VARS(cinfo);
  168798. INPUT_BYTE(cinfo, c, return FALSE);
  168799. INPUT_BYTE(cinfo, c2, return FALSE);
  168800. if (c != 0xFF || c2 != (int) M_SOI)
  168801. ERREXIT2(cinfo, JERR_NO_SOI, c, c2);
  168802. cinfo->unread_marker = c2;
  168803. INPUT_SYNC(cinfo);
  168804. return TRUE;
  168805. }
  168806. /*
  168807. * Read markers until SOS or EOI.
  168808. *
  168809. * Returns same codes as are defined for jpeg_consume_input:
  168810. * JPEG_SUSPENDED, JPEG_REACHED_SOS, or JPEG_REACHED_EOI.
  168811. */
  168812. METHODDEF(int)
  168813. read_markers (j_decompress_ptr cinfo)
  168814. {
  168815. /* Outer loop repeats once for each marker. */
  168816. for (;;) {
  168817. /* Collect the marker proper, unless we already did. */
  168818. /* NB: first_marker() enforces the requirement that SOI appear first. */
  168819. if (cinfo->unread_marker == 0) {
  168820. if (! cinfo->marker->saw_SOI) {
  168821. if (! first_marker(cinfo))
  168822. return JPEG_SUSPENDED;
  168823. } else {
  168824. if (! next_marker(cinfo))
  168825. return JPEG_SUSPENDED;
  168826. }
  168827. }
  168828. /* At this point cinfo->unread_marker contains the marker code and the
  168829. * input point is just past the marker proper, but before any parameters.
  168830. * A suspension will cause us to return with this state still true.
  168831. */
  168832. switch (cinfo->unread_marker) {
  168833. case M_SOI:
  168834. if (! get_soi(cinfo))
  168835. return JPEG_SUSPENDED;
  168836. break;
  168837. case M_SOF0: /* Baseline */
  168838. case M_SOF1: /* Extended sequential, Huffman */
  168839. if (! get_sof(cinfo, FALSE, FALSE))
  168840. return JPEG_SUSPENDED;
  168841. break;
  168842. case M_SOF2: /* Progressive, Huffman */
  168843. if (! get_sof(cinfo, TRUE, FALSE))
  168844. return JPEG_SUSPENDED;
  168845. break;
  168846. case M_SOF9: /* Extended sequential, arithmetic */
  168847. if (! get_sof(cinfo, FALSE, TRUE))
  168848. return JPEG_SUSPENDED;
  168849. break;
  168850. case M_SOF10: /* Progressive, arithmetic */
  168851. if (! get_sof(cinfo, TRUE, TRUE))
  168852. return JPEG_SUSPENDED;
  168853. break;
  168854. /* Currently unsupported SOFn types */
  168855. case M_SOF3: /* Lossless, Huffman */
  168856. case M_SOF5: /* Differential sequential, Huffman */
  168857. case M_SOF6: /* Differential progressive, Huffman */
  168858. case M_SOF7: /* Differential lossless, Huffman */
  168859. case M_JPG: /* Reserved for JPEG extensions */
  168860. case M_SOF11: /* Lossless, arithmetic */
  168861. case M_SOF13: /* Differential sequential, arithmetic */
  168862. case M_SOF14: /* Differential progressive, arithmetic */
  168863. case M_SOF15: /* Differential lossless, arithmetic */
  168864. ERREXIT1(cinfo, JERR_SOF_UNSUPPORTED, cinfo->unread_marker);
  168865. break;
  168866. case M_SOS:
  168867. if (! get_sos(cinfo))
  168868. return JPEG_SUSPENDED;
  168869. cinfo->unread_marker = 0; /* processed the marker */
  168870. return JPEG_REACHED_SOS;
  168871. case M_EOI:
  168872. TRACEMS(cinfo, 1, JTRC_EOI);
  168873. cinfo->unread_marker = 0; /* processed the marker */
  168874. return JPEG_REACHED_EOI;
  168875. case M_DAC:
  168876. if (! get_dac(cinfo))
  168877. return JPEG_SUSPENDED;
  168878. break;
  168879. case M_DHT:
  168880. if (! get_dht(cinfo))
  168881. return JPEG_SUSPENDED;
  168882. break;
  168883. case M_DQT:
  168884. if (! get_dqt(cinfo))
  168885. return JPEG_SUSPENDED;
  168886. break;
  168887. case M_DRI:
  168888. if (! get_dri(cinfo))
  168889. return JPEG_SUSPENDED;
  168890. break;
  168891. case M_APP0:
  168892. case M_APP1:
  168893. case M_APP2:
  168894. case M_APP3:
  168895. case M_APP4:
  168896. case M_APP5:
  168897. case M_APP6:
  168898. case M_APP7:
  168899. case M_APP8:
  168900. case M_APP9:
  168901. case M_APP10:
  168902. case M_APP11:
  168903. case M_APP12:
  168904. case M_APP13:
  168905. case M_APP14:
  168906. case M_APP15:
  168907. if (! (*((my_marker_ptr2) cinfo->marker)->process_APPn[
  168908. cinfo->unread_marker - (int) M_APP0]) (cinfo))
  168909. return JPEG_SUSPENDED;
  168910. break;
  168911. case M_COM:
  168912. if (! (*((my_marker_ptr2) cinfo->marker)->process_COM) (cinfo))
  168913. return JPEG_SUSPENDED;
  168914. break;
  168915. case M_RST0: /* these are all parameterless */
  168916. case M_RST1:
  168917. case M_RST2:
  168918. case M_RST3:
  168919. case M_RST4:
  168920. case M_RST5:
  168921. case M_RST6:
  168922. case M_RST7:
  168923. case M_TEM:
  168924. TRACEMS1(cinfo, 1, JTRC_PARMLESS_MARKER, cinfo->unread_marker);
  168925. break;
  168926. case M_DNL: /* Ignore DNL ... perhaps the wrong thing */
  168927. if (! skip_variable(cinfo))
  168928. return JPEG_SUSPENDED;
  168929. break;
  168930. default: /* must be DHP, EXP, JPGn, or RESn */
  168931. /* For now, we treat the reserved markers as fatal errors since they are
  168932. * likely to be used to signal incompatible JPEG Part 3 extensions.
  168933. * Once the JPEG 3 version-number marker is well defined, this code
  168934. * ought to change!
  168935. */
  168936. ERREXIT1(cinfo, JERR_UNKNOWN_MARKER, cinfo->unread_marker);
  168937. break;
  168938. }
  168939. /* Successfully processed marker, so reset state variable */
  168940. cinfo->unread_marker = 0;
  168941. } /* end loop */
  168942. }
  168943. /*
  168944. * Read a restart marker, which is expected to appear next in the datastream;
  168945. * if the marker is not there, take appropriate recovery action.
  168946. * Returns FALSE if suspension is required.
  168947. *
  168948. * This is called by the entropy decoder after it has read an appropriate
  168949. * number of MCUs. cinfo->unread_marker may be nonzero if the entropy decoder
  168950. * has already read a marker from the data source. Under normal conditions
  168951. * cinfo->unread_marker will be reset to 0 before returning; if not reset,
  168952. * it holds a marker which the decoder will be unable to read past.
  168953. */
  168954. METHODDEF(boolean)
  168955. read_restart_marker (j_decompress_ptr cinfo)
  168956. {
  168957. /* Obtain a marker unless we already did. */
  168958. /* Note that next_marker will complain if it skips any data. */
  168959. if (cinfo->unread_marker == 0) {
  168960. if (! next_marker(cinfo))
  168961. return FALSE;
  168962. }
  168963. if (cinfo->unread_marker ==
  168964. ((int) M_RST0 + cinfo->marker->next_restart_num)) {
  168965. /* Normal case --- swallow the marker and let entropy decoder continue */
  168966. TRACEMS1(cinfo, 3, JTRC_RST, cinfo->marker->next_restart_num);
  168967. cinfo->unread_marker = 0;
  168968. } else {
  168969. /* Uh-oh, the restart markers have been messed up. */
  168970. /* Let the data source manager determine how to resync. */
  168971. if (! (*cinfo->src->resync_to_restart) (cinfo,
  168972. cinfo->marker->next_restart_num))
  168973. return FALSE;
  168974. }
  168975. /* Update next-restart state */
  168976. cinfo->marker->next_restart_num = (cinfo->marker->next_restart_num + 1) & 7;
  168977. return TRUE;
  168978. }
  168979. /*
  168980. * This is the default resync_to_restart method for data source managers
  168981. * to use if they don't have any better approach. Some data source managers
  168982. * may be able to back up, or may have additional knowledge about the data
  168983. * which permits a more intelligent recovery strategy; such managers would
  168984. * presumably supply their own resync method.
  168985. *
  168986. * read_restart_marker calls resync_to_restart if it finds a marker other than
  168987. * the restart marker it was expecting. (This code is *not* used unless
  168988. * a nonzero restart interval has been declared.) cinfo->unread_marker is
  168989. * the marker code actually found (might be anything, except 0 or FF).
  168990. * The desired restart marker number (0..7) is passed as a parameter.
  168991. * This routine is supposed to apply whatever error recovery strategy seems
  168992. * appropriate in order to position the input stream to the next data segment.
  168993. * Note that cinfo->unread_marker is treated as a marker appearing before
  168994. * the current data-source input point; usually it should be reset to zero
  168995. * before returning.
  168996. * Returns FALSE if suspension is required.
  168997. *
  168998. * This implementation is substantially constrained by wanting to treat the
  168999. * input as a data stream; this means we can't back up. Therefore, we have
  169000. * only the following actions to work with:
  169001. * 1. Simply discard the marker and let the entropy decoder resume at next
  169002. * byte of file.
  169003. * 2. Read forward until we find another marker, discarding intervening
  169004. * data. (In theory we could look ahead within the current bufferload,
  169005. * without having to discard data if we don't find the desired marker.
  169006. * This idea is not implemented here, in part because it makes behavior
  169007. * dependent on buffer size and chance buffer-boundary positions.)
  169008. * 3. Leave the marker unread (by failing to zero cinfo->unread_marker).
  169009. * This will cause the entropy decoder to process an empty data segment,
  169010. * inserting dummy zeroes, and then we will reprocess the marker.
  169011. *
  169012. * #2 is appropriate if we think the desired marker lies ahead, while #3 is
  169013. * appropriate if the found marker is a future restart marker (indicating
  169014. * that we have missed the desired restart marker, probably because it got
  169015. * corrupted).
  169016. * We apply #2 or #3 if the found marker is a restart marker no more than
  169017. * two counts behind or ahead of the expected one. We also apply #2 if the
  169018. * found marker is not a legal JPEG marker code (it's certainly bogus data).
  169019. * If the found marker is a restart marker more than 2 counts away, we do #1
  169020. * (too much risk that the marker is erroneous; with luck we will be able to
  169021. * resync at some future point).
  169022. * For any valid non-restart JPEG marker, we apply #3. This keeps us from
  169023. * overrunning the end of a scan. An implementation limited to single-scan
  169024. * files might find it better to apply #2 for markers other than EOI, since
  169025. * any other marker would have to be bogus data in that case.
  169026. */
  169027. GLOBAL(boolean)
  169028. jpeg_resync_to_restart (j_decompress_ptr cinfo, int desired)
  169029. {
  169030. int marker = cinfo->unread_marker;
  169031. int action = 1;
  169032. /* Always put up a warning. */
  169033. WARNMS2(cinfo, JWRN_MUST_RESYNC, marker, desired);
  169034. /* Outer loop handles repeated decision after scanning forward. */
  169035. for (;;) {
  169036. if (marker < (int) M_SOF0)
  169037. action = 2; /* invalid marker */
  169038. else if (marker < (int) M_RST0 || marker > (int) M_RST7)
  169039. action = 3; /* valid non-restart marker */
  169040. else {
  169041. if (marker == ((int) M_RST0 + ((desired+1) & 7)) ||
  169042. marker == ((int) M_RST0 + ((desired+2) & 7)))
  169043. action = 3; /* one of the next two expected restarts */
  169044. else if (marker == ((int) M_RST0 + ((desired-1) & 7)) ||
  169045. marker == ((int) M_RST0 + ((desired-2) & 7)))
  169046. action = 2; /* a prior restart, so advance */
  169047. else
  169048. action = 1; /* desired restart or too far away */
  169049. }
  169050. TRACEMS2(cinfo, 4, JTRC_RECOVERY_ACTION, marker, action);
  169051. switch (action) {
  169052. case 1:
  169053. /* Discard marker and let entropy decoder resume processing. */
  169054. cinfo->unread_marker = 0;
  169055. return TRUE;
  169056. case 2:
  169057. /* Scan to the next marker, and repeat the decision loop. */
  169058. if (! next_marker(cinfo))
  169059. return FALSE;
  169060. marker = cinfo->unread_marker;
  169061. break;
  169062. case 3:
  169063. /* Return without advancing past this marker. */
  169064. /* Entropy decoder will be forced to process an empty segment. */
  169065. return TRUE;
  169066. }
  169067. } /* end loop */
  169068. }
  169069. /*
  169070. * Reset marker processing state to begin a fresh datastream.
  169071. */
  169072. METHODDEF(void)
  169073. reset_marker_reader (j_decompress_ptr cinfo)
  169074. {
  169075. my_marker_ptr2 marker = (my_marker_ptr2) cinfo->marker;
  169076. cinfo->comp_info = NULL; /* until allocated by get_sof */
  169077. cinfo->input_scan_number = 0; /* no SOS seen yet */
  169078. cinfo->unread_marker = 0; /* no pending marker */
  169079. marker->pub.saw_SOI = FALSE; /* set internal state too */
  169080. marker->pub.saw_SOF = FALSE;
  169081. marker->pub.discarded_bytes = 0;
  169082. marker->cur_marker = NULL;
  169083. }
  169084. /*
  169085. * Initialize the marker reader module.
  169086. * This is called only once, when the decompression object is created.
  169087. */
  169088. GLOBAL(void)
  169089. jinit_marker_reader (j_decompress_ptr cinfo)
  169090. {
  169091. my_marker_ptr2 marker;
  169092. int i;
  169093. /* Create subobject in permanent pool */
  169094. marker = (my_marker_ptr2)
  169095. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT,
  169096. SIZEOF(my_marker_reader));
  169097. cinfo->marker = (struct jpeg_marker_reader *) marker;
  169098. /* Initialize public method pointers */
  169099. marker->pub.reset_marker_reader = reset_marker_reader;
  169100. marker->pub.read_markers = read_markers;
  169101. marker->pub.read_restart_marker = read_restart_marker;
  169102. /* Initialize COM/APPn processing.
  169103. * By default, we examine and then discard APP0 and APP14,
  169104. * but simply discard COM and all other APPn.
  169105. */
  169106. marker->process_COM = skip_variable;
  169107. marker->length_limit_COM = 0;
  169108. for (i = 0; i < 16; i++) {
  169109. marker->process_APPn[i] = skip_variable;
  169110. marker->length_limit_APPn[i] = 0;
  169111. }
  169112. marker->process_APPn[0] = get_interesting_appn;
  169113. marker->process_APPn[14] = get_interesting_appn;
  169114. /* Reset marker processing state */
  169115. reset_marker_reader(cinfo);
  169116. }
  169117. /*
  169118. * Control saving of COM and APPn markers into marker_list.
  169119. */
  169120. #ifdef SAVE_MARKERS_SUPPORTED
  169121. GLOBAL(void)
  169122. jpeg_save_markers (j_decompress_ptr cinfo, int marker_code,
  169123. unsigned int length_limit)
  169124. {
  169125. my_marker_ptr2 marker = (my_marker_ptr2) cinfo->marker;
  169126. long maxlength;
  169127. jpeg_marker_parser_method processor;
  169128. /* Length limit mustn't be larger than what we can allocate
  169129. * (should only be a concern in a 16-bit environment).
  169130. */
  169131. maxlength = cinfo->mem->max_alloc_chunk - SIZEOF(struct jpeg_marker_struct);
  169132. if (((long) length_limit) > maxlength)
  169133. length_limit = (unsigned int) maxlength;
  169134. /* Choose processor routine to use.
  169135. * APP0/APP14 have special requirements.
  169136. */
  169137. if (length_limit) {
  169138. processor = save_marker;
  169139. /* If saving APP0/APP14, save at least enough for our internal use. */
  169140. if (marker_code == (int) M_APP0 && length_limit < APP0_DATA_LEN)
  169141. length_limit = APP0_DATA_LEN;
  169142. else if (marker_code == (int) M_APP14 && length_limit < APP14_DATA_LEN)
  169143. length_limit = APP14_DATA_LEN;
  169144. } else {
  169145. processor = skip_variable;
  169146. /* If discarding APP0/APP14, use our regular on-the-fly processor. */
  169147. if (marker_code == (int) M_APP0 || marker_code == (int) M_APP14)
  169148. processor = get_interesting_appn;
  169149. }
  169150. if (marker_code == (int) M_COM) {
  169151. marker->process_COM = processor;
  169152. marker->length_limit_COM = length_limit;
  169153. } else if (marker_code >= (int) M_APP0 && marker_code <= (int) M_APP15) {
  169154. marker->process_APPn[marker_code - (int) M_APP0] = processor;
  169155. marker->length_limit_APPn[marker_code - (int) M_APP0] = length_limit;
  169156. } else
  169157. ERREXIT1(cinfo, JERR_UNKNOWN_MARKER, marker_code);
  169158. }
  169159. #endif /* SAVE_MARKERS_SUPPORTED */
  169160. /*
  169161. * Install a special processing method for COM or APPn markers.
  169162. */
  169163. GLOBAL(void)
  169164. jpeg_set_marker_processor (j_decompress_ptr cinfo, int marker_code,
  169165. jpeg_marker_parser_method routine)
  169166. {
  169167. my_marker_ptr2 marker = (my_marker_ptr2) cinfo->marker;
  169168. if (marker_code == (int) M_COM)
  169169. marker->process_COM = routine;
  169170. else if (marker_code >= (int) M_APP0 && marker_code <= (int) M_APP15)
  169171. marker->process_APPn[marker_code - (int) M_APP0] = routine;
  169172. else
  169173. ERREXIT1(cinfo, JERR_UNKNOWN_MARKER, marker_code);
  169174. }
  169175. /*** End of inlined file: jdmarker.c ***/
  169176. /*** Start of inlined file: jdmaster.c ***/
  169177. #define JPEG_INTERNALS
  169178. /* Private state */
  169179. typedef struct {
  169180. struct jpeg_decomp_master pub; /* public fields */
  169181. int pass_number; /* # of passes completed */
  169182. boolean using_merged_upsample; /* TRUE if using merged upsample/cconvert */
  169183. /* Saved references to initialized quantizer modules,
  169184. * in case we need to switch modes.
  169185. */
  169186. struct jpeg_color_quantizer * quantizer_1pass;
  169187. struct jpeg_color_quantizer * quantizer_2pass;
  169188. } my_decomp_master;
  169189. typedef my_decomp_master * my_master_ptr6;
  169190. /*
  169191. * Determine whether merged upsample/color conversion should be used.
  169192. * CRUCIAL: this must match the actual capabilities of jdmerge.c!
  169193. */
  169194. LOCAL(boolean)
  169195. use_merged_upsample (j_decompress_ptr cinfo)
  169196. {
  169197. #ifdef UPSAMPLE_MERGING_SUPPORTED
  169198. /* Merging is the equivalent of plain box-filter upsampling */
  169199. if (cinfo->do_fancy_upsampling || cinfo->CCIR601_sampling)
  169200. return FALSE;
  169201. /* jdmerge.c only supports YCC=>RGB color conversion */
  169202. if (cinfo->jpeg_color_space != JCS_YCbCr || cinfo->num_components != 3 ||
  169203. cinfo->out_color_space != JCS_RGB ||
  169204. cinfo->out_color_components != RGB_PIXELSIZE)
  169205. return FALSE;
  169206. /* and it only handles 2h1v or 2h2v sampling ratios */
  169207. if (cinfo->comp_info[0].h_samp_factor != 2 ||
  169208. cinfo->comp_info[1].h_samp_factor != 1 ||
  169209. cinfo->comp_info[2].h_samp_factor != 1 ||
  169210. cinfo->comp_info[0].v_samp_factor > 2 ||
  169211. cinfo->comp_info[1].v_samp_factor != 1 ||
  169212. cinfo->comp_info[2].v_samp_factor != 1)
  169213. return FALSE;
  169214. /* furthermore, it doesn't work if we've scaled the IDCTs differently */
  169215. if (cinfo->comp_info[0].DCT_scaled_size != cinfo->min_DCT_scaled_size ||
  169216. cinfo->comp_info[1].DCT_scaled_size != cinfo->min_DCT_scaled_size ||
  169217. cinfo->comp_info[2].DCT_scaled_size != cinfo->min_DCT_scaled_size)
  169218. return FALSE;
  169219. /* ??? also need to test for upsample-time rescaling, when & if supported */
  169220. return TRUE; /* by golly, it'll work... */
  169221. #else
  169222. return FALSE;
  169223. #endif
  169224. }
  169225. /*
  169226. * Compute output image dimensions and related values.
  169227. * NOTE: this is exported for possible use by application.
  169228. * Hence it mustn't do anything that can't be done twice.
  169229. * Also note that it may be called before the master module is initialized!
  169230. */
  169231. GLOBAL(void)
  169232. jpeg_calc_output_dimensions (j_decompress_ptr cinfo)
  169233. /* Do computations that are needed before master selection phase */
  169234. {
  169235. #ifdef IDCT_SCALING_SUPPORTED
  169236. int ci;
  169237. jpeg_component_info *compptr;
  169238. #endif
  169239. /* Prevent application from calling me at wrong times */
  169240. if (cinfo->global_state != DSTATE_READY)
  169241. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  169242. #ifdef IDCT_SCALING_SUPPORTED
  169243. /* Compute actual output image dimensions and DCT scaling choices. */
  169244. if (cinfo->scale_num * 8 <= cinfo->scale_denom) {
  169245. /* Provide 1/8 scaling */
  169246. cinfo->output_width = (JDIMENSION)
  169247. jdiv_round_up((long) cinfo->image_width, 8L);
  169248. cinfo->output_height = (JDIMENSION)
  169249. jdiv_round_up((long) cinfo->image_height, 8L);
  169250. cinfo->min_DCT_scaled_size = 1;
  169251. } else if (cinfo->scale_num * 4 <= cinfo->scale_denom) {
  169252. /* Provide 1/4 scaling */
  169253. cinfo->output_width = (JDIMENSION)
  169254. jdiv_round_up((long) cinfo->image_width, 4L);
  169255. cinfo->output_height = (JDIMENSION)
  169256. jdiv_round_up((long) cinfo->image_height, 4L);
  169257. cinfo->min_DCT_scaled_size = 2;
  169258. } else if (cinfo->scale_num * 2 <= cinfo->scale_denom) {
  169259. /* Provide 1/2 scaling */
  169260. cinfo->output_width = (JDIMENSION)
  169261. jdiv_round_up((long) cinfo->image_width, 2L);
  169262. cinfo->output_height = (JDIMENSION)
  169263. jdiv_round_up((long) cinfo->image_height, 2L);
  169264. cinfo->min_DCT_scaled_size = 4;
  169265. } else {
  169266. /* Provide 1/1 scaling */
  169267. cinfo->output_width = cinfo->image_width;
  169268. cinfo->output_height = cinfo->image_height;
  169269. cinfo->min_DCT_scaled_size = DCTSIZE;
  169270. }
  169271. /* In selecting the actual DCT scaling for each component, we try to
  169272. * scale up the chroma components via IDCT scaling rather than upsampling.
  169273. * This saves time if the upsampler gets to use 1:1 scaling.
  169274. * Note this code assumes that the supported DCT scalings are powers of 2.
  169275. */
  169276. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  169277. ci++, compptr++) {
  169278. int ssize = cinfo->min_DCT_scaled_size;
  169279. while (ssize < DCTSIZE &&
  169280. (compptr->h_samp_factor * ssize * 2 <=
  169281. cinfo->max_h_samp_factor * cinfo->min_DCT_scaled_size) &&
  169282. (compptr->v_samp_factor * ssize * 2 <=
  169283. cinfo->max_v_samp_factor * cinfo->min_DCT_scaled_size)) {
  169284. ssize = ssize * 2;
  169285. }
  169286. compptr->DCT_scaled_size = ssize;
  169287. }
  169288. /* Recompute downsampled dimensions of components;
  169289. * application needs to know these if using raw downsampled data.
  169290. */
  169291. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  169292. ci++, compptr++) {
  169293. /* Size in samples, after IDCT scaling */
  169294. compptr->downsampled_width = (JDIMENSION)
  169295. jdiv_round_up((long) cinfo->image_width *
  169296. (long) (compptr->h_samp_factor * compptr->DCT_scaled_size),
  169297. (long) (cinfo->max_h_samp_factor * DCTSIZE));
  169298. compptr->downsampled_height = (JDIMENSION)
  169299. jdiv_round_up((long) cinfo->image_height *
  169300. (long) (compptr->v_samp_factor * compptr->DCT_scaled_size),
  169301. (long) (cinfo->max_v_samp_factor * DCTSIZE));
  169302. }
  169303. #else /* !IDCT_SCALING_SUPPORTED */
  169304. /* Hardwire it to "no scaling" */
  169305. cinfo->output_width = cinfo->image_width;
  169306. cinfo->output_height = cinfo->image_height;
  169307. /* jdinput.c has already initialized DCT_scaled_size to DCTSIZE,
  169308. * and has computed unscaled downsampled_width and downsampled_height.
  169309. */
  169310. #endif /* IDCT_SCALING_SUPPORTED */
  169311. /* Report number of components in selected colorspace. */
  169312. /* Probably this should be in the color conversion module... */
  169313. switch (cinfo->out_color_space) {
  169314. case JCS_GRAYSCALE:
  169315. cinfo->out_color_components = 1;
  169316. break;
  169317. case JCS_RGB:
  169318. #if RGB_PIXELSIZE != 3
  169319. cinfo->out_color_components = RGB_PIXELSIZE;
  169320. break;
  169321. #endif /* else share code with YCbCr */
  169322. case JCS_YCbCr:
  169323. cinfo->out_color_components = 3;
  169324. break;
  169325. case JCS_CMYK:
  169326. case JCS_YCCK:
  169327. cinfo->out_color_components = 4;
  169328. break;
  169329. default: /* else must be same colorspace as in file */
  169330. cinfo->out_color_components = cinfo->num_components;
  169331. break;
  169332. }
  169333. cinfo->output_components = (cinfo->quantize_colors ? 1 :
  169334. cinfo->out_color_components);
  169335. /* See if upsampler will want to emit more than one row at a time */
  169336. if (use_merged_upsample(cinfo))
  169337. cinfo->rec_outbuf_height = cinfo->max_v_samp_factor;
  169338. else
  169339. cinfo->rec_outbuf_height = 1;
  169340. }
  169341. /*
  169342. * Several decompression processes need to range-limit values to the range
  169343. * 0..MAXJSAMPLE; the input value may fall somewhat outside this range
  169344. * due to noise introduced by quantization, roundoff error, etc. These
  169345. * processes are inner loops and need to be as fast as possible. On most
  169346. * machines, particularly CPUs with pipelines or instruction prefetch,
  169347. * a (subscript-check-less) C table lookup
  169348. * x = sample_range_limit[x];
  169349. * is faster than explicit tests
  169350. * if (x < 0) x = 0;
  169351. * else if (x > MAXJSAMPLE) x = MAXJSAMPLE;
  169352. * These processes all use a common table prepared by the routine below.
  169353. *
  169354. * For most steps we can mathematically guarantee that the initial value
  169355. * of x is within MAXJSAMPLE+1 of the legal range, so a table running from
  169356. * -(MAXJSAMPLE+1) to 2*MAXJSAMPLE+1 is sufficient. But for the initial
  169357. * limiting step (just after the IDCT), a wildly out-of-range value is
  169358. * possible if the input data is corrupt. To avoid any chance of indexing
  169359. * off the end of memory and getting a bad-pointer trap, we perform the
  169360. * post-IDCT limiting thus:
  169361. * x = range_limit[x & MASK];
  169362. * where MASK is 2 bits wider than legal sample data, ie 10 bits for 8-bit
  169363. * samples. Under normal circumstances this is more than enough range and
  169364. * a correct output will be generated; with bogus input data the mask will
  169365. * cause wraparound, and we will safely generate a bogus-but-in-range output.
  169366. * For the post-IDCT step, we want to convert the data from signed to unsigned
  169367. * representation by adding CENTERJSAMPLE at the same time that we limit it.
  169368. * So the post-IDCT limiting table ends up looking like this:
  169369. * CENTERJSAMPLE,CENTERJSAMPLE+1,...,MAXJSAMPLE,
  169370. * MAXJSAMPLE (repeat 2*(MAXJSAMPLE+1)-CENTERJSAMPLE times),
  169371. * 0 (repeat 2*(MAXJSAMPLE+1)-CENTERJSAMPLE times),
  169372. * 0,1,...,CENTERJSAMPLE-1
  169373. * Negative inputs select values from the upper half of the table after
  169374. * masking.
  169375. *
  169376. * We can save some space by overlapping the start of the post-IDCT table
  169377. * with the simpler range limiting table. The post-IDCT table begins at
  169378. * sample_range_limit + CENTERJSAMPLE.
  169379. *
  169380. * Note that the table is allocated in near data space on PCs; it's small
  169381. * enough and used often enough to justify this.
  169382. */
  169383. LOCAL(void)
  169384. prepare_range_limit_table (j_decompress_ptr cinfo)
  169385. /* Allocate and fill in the sample_range_limit table */
  169386. {
  169387. JSAMPLE * table;
  169388. int i;
  169389. table = (JSAMPLE *)
  169390. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  169391. (5 * (MAXJSAMPLE+1) + CENTERJSAMPLE) * SIZEOF(JSAMPLE));
  169392. table += (MAXJSAMPLE+1); /* allow negative subscripts of simple table */
  169393. cinfo->sample_range_limit = table;
  169394. /* First segment of "simple" table: limit[x] = 0 for x < 0 */
  169395. MEMZERO(table - (MAXJSAMPLE+1), (MAXJSAMPLE+1) * SIZEOF(JSAMPLE));
  169396. /* Main part of "simple" table: limit[x] = x */
  169397. for (i = 0; i <= MAXJSAMPLE; i++)
  169398. table[i] = (JSAMPLE) i;
  169399. table += CENTERJSAMPLE; /* Point to where post-IDCT table starts */
  169400. /* End of simple table, rest of first half of post-IDCT table */
  169401. for (i = CENTERJSAMPLE; i < 2*(MAXJSAMPLE+1); i++)
  169402. table[i] = MAXJSAMPLE;
  169403. /* Second half of post-IDCT table */
  169404. MEMZERO(table + (2 * (MAXJSAMPLE+1)),
  169405. (2 * (MAXJSAMPLE+1) - CENTERJSAMPLE) * SIZEOF(JSAMPLE));
  169406. MEMCOPY(table + (4 * (MAXJSAMPLE+1) - CENTERJSAMPLE),
  169407. cinfo->sample_range_limit, CENTERJSAMPLE * SIZEOF(JSAMPLE));
  169408. }
  169409. /*
  169410. * Master selection of decompression modules.
  169411. * This is done once at jpeg_start_decompress time. We determine
  169412. * which modules will be used and give them appropriate initialization calls.
  169413. * We also initialize the decompressor input side to begin consuming data.
  169414. *
  169415. * Since jpeg_read_header has finished, we know what is in the SOF
  169416. * and (first) SOS markers. We also have all the application parameter
  169417. * settings.
  169418. */
  169419. LOCAL(void)
  169420. master_selection (j_decompress_ptr cinfo)
  169421. {
  169422. my_master_ptr6 master = (my_master_ptr6) cinfo->master;
  169423. boolean use_c_buffer;
  169424. long samplesperrow;
  169425. JDIMENSION jd_samplesperrow;
  169426. /* Initialize dimensions and other stuff */
  169427. jpeg_calc_output_dimensions(cinfo);
  169428. prepare_range_limit_table(cinfo);
  169429. /* Width of an output scanline must be representable as JDIMENSION. */
  169430. samplesperrow = (long) cinfo->output_width * (long) cinfo->out_color_components;
  169431. jd_samplesperrow = (JDIMENSION) samplesperrow;
  169432. if ((long) jd_samplesperrow != samplesperrow)
  169433. ERREXIT(cinfo, JERR_WIDTH_OVERFLOW);
  169434. /* Initialize my private state */
  169435. master->pass_number = 0;
  169436. master->using_merged_upsample = use_merged_upsample(cinfo);
  169437. /* Color quantizer selection */
  169438. master->quantizer_1pass = NULL;
  169439. master->quantizer_2pass = NULL;
  169440. /* No mode changes if not using buffered-image mode. */
  169441. if (! cinfo->quantize_colors || ! cinfo->buffered_image) {
  169442. cinfo->enable_1pass_quant = FALSE;
  169443. cinfo->enable_external_quant = FALSE;
  169444. cinfo->enable_2pass_quant = FALSE;
  169445. }
  169446. if (cinfo->quantize_colors) {
  169447. if (cinfo->raw_data_out)
  169448. ERREXIT(cinfo, JERR_NOTIMPL);
  169449. /* 2-pass quantizer only works in 3-component color space. */
  169450. if (cinfo->out_color_components != 3) {
  169451. cinfo->enable_1pass_quant = TRUE;
  169452. cinfo->enable_external_quant = FALSE;
  169453. cinfo->enable_2pass_quant = FALSE;
  169454. cinfo->colormap = NULL;
  169455. } else if (cinfo->colormap != NULL) {
  169456. cinfo->enable_external_quant = TRUE;
  169457. } else if (cinfo->two_pass_quantize) {
  169458. cinfo->enable_2pass_quant = TRUE;
  169459. } else {
  169460. cinfo->enable_1pass_quant = TRUE;
  169461. }
  169462. if (cinfo->enable_1pass_quant) {
  169463. #ifdef QUANT_1PASS_SUPPORTED
  169464. jinit_1pass_quantizer(cinfo);
  169465. master->quantizer_1pass = cinfo->cquantize;
  169466. #else
  169467. ERREXIT(cinfo, JERR_NOT_COMPILED);
  169468. #endif
  169469. }
  169470. /* We use the 2-pass code to map to external colormaps. */
  169471. if (cinfo->enable_2pass_quant || cinfo->enable_external_quant) {
  169472. #ifdef QUANT_2PASS_SUPPORTED
  169473. jinit_2pass_quantizer(cinfo);
  169474. master->quantizer_2pass = cinfo->cquantize;
  169475. #else
  169476. ERREXIT(cinfo, JERR_NOT_COMPILED);
  169477. #endif
  169478. }
  169479. /* If both quantizers are initialized, the 2-pass one is left active;
  169480. * this is necessary for starting with quantization to an external map.
  169481. */
  169482. }
  169483. /* Post-processing: in particular, color conversion first */
  169484. if (! cinfo->raw_data_out) {
  169485. if (master->using_merged_upsample) {
  169486. #ifdef UPSAMPLE_MERGING_SUPPORTED
  169487. jinit_merged_upsampler(cinfo); /* does color conversion too */
  169488. #else
  169489. ERREXIT(cinfo, JERR_NOT_COMPILED);
  169490. #endif
  169491. } else {
  169492. jinit_color_deconverter(cinfo);
  169493. jinit_upsampler(cinfo);
  169494. }
  169495. jinit_d_post_controller(cinfo, cinfo->enable_2pass_quant);
  169496. }
  169497. /* Inverse DCT */
  169498. jinit_inverse_dct(cinfo);
  169499. /* Entropy decoding: either Huffman or arithmetic coding. */
  169500. if (cinfo->arith_code) {
  169501. ERREXIT(cinfo, JERR_ARITH_NOTIMPL);
  169502. } else {
  169503. if (cinfo->progressive_mode) {
  169504. #ifdef D_PROGRESSIVE_SUPPORTED
  169505. jinit_phuff_decoder(cinfo);
  169506. #else
  169507. ERREXIT(cinfo, JERR_NOT_COMPILED);
  169508. #endif
  169509. } else
  169510. jinit_huff_decoder(cinfo);
  169511. }
  169512. /* Initialize principal buffer controllers. */
  169513. use_c_buffer = cinfo->inputctl->has_multiple_scans || cinfo->buffered_image;
  169514. jinit_d_coef_controller(cinfo, use_c_buffer);
  169515. if (! cinfo->raw_data_out)
  169516. jinit_d_main_controller(cinfo, FALSE /* never need full buffer here */);
  169517. /* We can now tell the memory manager to allocate virtual arrays. */
  169518. (*cinfo->mem->realize_virt_arrays) ((j_common_ptr) cinfo);
  169519. /* Initialize input side of decompressor to consume first scan. */
  169520. (*cinfo->inputctl->start_input_pass) (cinfo);
  169521. #ifdef D_MULTISCAN_FILES_SUPPORTED
  169522. /* If jpeg_start_decompress will read the whole file, initialize
  169523. * progress monitoring appropriately. The input step is counted
  169524. * as one pass.
  169525. */
  169526. if (cinfo->progress != NULL && ! cinfo->buffered_image &&
  169527. cinfo->inputctl->has_multiple_scans) {
  169528. int nscans;
  169529. /* Estimate number of scans to set pass_limit. */
  169530. if (cinfo->progressive_mode) {
  169531. /* Arbitrarily estimate 2 interleaved DC scans + 3 AC scans/component. */
  169532. nscans = 2 + 3 * cinfo->num_components;
  169533. } else {
  169534. /* For a nonprogressive multiscan file, estimate 1 scan per component. */
  169535. nscans = cinfo->num_components;
  169536. }
  169537. cinfo->progress->pass_counter = 0L;
  169538. cinfo->progress->pass_limit = (long) cinfo->total_iMCU_rows * nscans;
  169539. cinfo->progress->completed_passes = 0;
  169540. cinfo->progress->total_passes = (cinfo->enable_2pass_quant ? 3 : 2);
  169541. /* Count the input pass as done */
  169542. master->pass_number++;
  169543. }
  169544. #endif /* D_MULTISCAN_FILES_SUPPORTED */
  169545. }
  169546. /*
  169547. * Per-pass setup.
  169548. * This is called at the beginning of each output pass. We determine which
  169549. * modules will be active during this pass and give them appropriate
  169550. * start_pass calls. We also set is_dummy_pass to indicate whether this
  169551. * is a "real" output pass or a dummy pass for color quantization.
  169552. * (In the latter case, jdapistd.c will crank the pass to completion.)
  169553. */
  169554. METHODDEF(void)
  169555. prepare_for_output_pass (j_decompress_ptr cinfo)
  169556. {
  169557. my_master_ptr6 master = (my_master_ptr6) cinfo->master;
  169558. if (master->pub.is_dummy_pass) {
  169559. #ifdef QUANT_2PASS_SUPPORTED
  169560. /* Final pass of 2-pass quantization */
  169561. master->pub.is_dummy_pass = FALSE;
  169562. (*cinfo->cquantize->start_pass) (cinfo, FALSE);
  169563. (*cinfo->post->start_pass) (cinfo, JBUF_CRANK_DEST);
  169564. (*cinfo->main->start_pass) (cinfo, JBUF_CRANK_DEST);
  169565. #else
  169566. ERREXIT(cinfo, JERR_NOT_COMPILED);
  169567. #endif /* QUANT_2PASS_SUPPORTED */
  169568. } else {
  169569. if (cinfo->quantize_colors && cinfo->colormap == NULL) {
  169570. /* Select new quantization method */
  169571. if (cinfo->two_pass_quantize && cinfo->enable_2pass_quant) {
  169572. cinfo->cquantize = master->quantizer_2pass;
  169573. master->pub.is_dummy_pass = TRUE;
  169574. } else if (cinfo->enable_1pass_quant) {
  169575. cinfo->cquantize = master->quantizer_1pass;
  169576. } else {
  169577. ERREXIT(cinfo, JERR_MODE_CHANGE);
  169578. }
  169579. }
  169580. (*cinfo->idct->start_pass) (cinfo);
  169581. (*cinfo->coef->start_output_pass) (cinfo);
  169582. if (! cinfo->raw_data_out) {
  169583. if (! master->using_merged_upsample)
  169584. (*cinfo->cconvert->start_pass) (cinfo);
  169585. (*cinfo->upsample->start_pass) (cinfo);
  169586. if (cinfo->quantize_colors)
  169587. (*cinfo->cquantize->start_pass) (cinfo, master->pub.is_dummy_pass);
  169588. (*cinfo->post->start_pass) (cinfo,
  169589. (master->pub.is_dummy_pass ? JBUF_SAVE_AND_PASS : JBUF_PASS_THRU));
  169590. (*cinfo->main->start_pass) (cinfo, JBUF_PASS_THRU);
  169591. }
  169592. }
  169593. /* Set up progress monitor's pass info if present */
  169594. if (cinfo->progress != NULL) {
  169595. cinfo->progress->completed_passes = master->pass_number;
  169596. cinfo->progress->total_passes = master->pass_number +
  169597. (master->pub.is_dummy_pass ? 2 : 1);
  169598. /* In buffered-image mode, we assume one more output pass if EOI not
  169599. * yet reached, but no more passes if EOI has been reached.
  169600. */
  169601. if (cinfo->buffered_image && ! cinfo->inputctl->eoi_reached) {
  169602. cinfo->progress->total_passes += (cinfo->enable_2pass_quant ? 2 : 1);
  169603. }
  169604. }
  169605. }
  169606. /*
  169607. * Finish up at end of an output pass.
  169608. */
  169609. METHODDEF(void)
  169610. finish_output_pass (j_decompress_ptr cinfo)
  169611. {
  169612. my_master_ptr6 master = (my_master_ptr6) cinfo->master;
  169613. if (cinfo->quantize_colors)
  169614. (*cinfo->cquantize->finish_pass) (cinfo);
  169615. master->pass_number++;
  169616. }
  169617. #ifdef D_MULTISCAN_FILES_SUPPORTED
  169618. /*
  169619. * Switch to a new external colormap between output passes.
  169620. */
  169621. GLOBAL(void)
  169622. jpeg_new_colormap (j_decompress_ptr cinfo)
  169623. {
  169624. my_master_ptr6 master = (my_master_ptr6) cinfo->master;
  169625. /* Prevent application from calling me at wrong times */
  169626. if (cinfo->global_state != DSTATE_BUFIMAGE)
  169627. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  169628. if (cinfo->quantize_colors && cinfo->enable_external_quant &&
  169629. cinfo->colormap != NULL) {
  169630. /* Select 2-pass quantizer for external colormap use */
  169631. cinfo->cquantize = master->quantizer_2pass;
  169632. /* Notify quantizer of colormap change */
  169633. (*cinfo->cquantize->new_color_map) (cinfo);
  169634. master->pub.is_dummy_pass = FALSE; /* just in case */
  169635. } else
  169636. ERREXIT(cinfo, JERR_MODE_CHANGE);
  169637. }
  169638. #endif /* D_MULTISCAN_FILES_SUPPORTED */
  169639. /*
  169640. * Initialize master decompression control and select active modules.
  169641. * This is performed at the start of jpeg_start_decompress.
  169642. */
  169643. GLOBAL(void)
  169644. jinit_master_decompress (j_decompress_ptr cinfo)
  169645. {
  169646. my_master_ptr6 master;
  169647. master = (my_master_ptr6)
  169648. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  169649. SIZEOF(my_decomp_master));
  169650. cinfo->master = (struct jpeg_decomp_master *) master;
  169651. master->pub.prepare_for_output_pass = prepare_for_output_pass;
  169652. master->pub.finish_output_pass = finish_output_pass;
  169653. master->pub.is_dummy_pass = FALSE;
  169654. master_selection(cinfo);
  169655. }
  169656. /*** End of inlined file: jdmaster.c ***/
  169657. #undef FIX
  169658. /*** Start of inlined file: jdmerge.c ***/
  169659. #define JPEG_INTERNALS
  169660. #ifdef UPSAMPLE_MERGING_SUPPORTED
  169661. /* Private subobject */
  169662. typedef struct {
  169663. struct jpeg_upsampler pub; /* public fields */
  169664. /* Pointer to routine to do actual upsampling/conversion of one row group */
  169665. JMETHOD(void, upmethod, (j_decompress_ptr cinfo,
  169666. JSAMPIMAGE input_buf, JDIMENSION in_row_group_ctr,
  169667. JSAMPARRAY output_buf));
  169668. /* Private state for YCC->RGB conversion */
  169669. int * Cr_r_tab; /* => table for Cr to R conversion */
  169670. int * Cb_b_tab; /* => table for Cb to B conversion */
  169671. INT32 * Cr_g_tab; /* => table for Cr to G conversion */
  169672. INT32 * Cb_g_tab; /* => table for Cb to G conversion */
  169673. /* For 2:1 vertical sampling, we produce two output rows at a time.
  169674. * We need a "spare" row buffer to hold the second output row if the
  169675. * application provides just a one-row buffer; we also use the spare
  169676. * to discard the dummy last row if the image height is odd.
  169677. */
  169678. JSAMPROW spare_row;
  169679. boolean spare_full; /* T if spare buffer is occupied */
  169680. JDIMENSION out_row_width; /* samples per output row */
  169681. JDIMENSION rows_to_go; /* counts rows remaining in image */
  169682. } my_upsampler;
  169683. typedef my_upsampler * my_upsample_ptr;
  169684. #define SCALEBITS 16 /* speediest right-shift on some machines */
  169685. #define ONE_HALF ((INT32) 1 << (SCALEBITS-1))
  169686. #define FIX(x) ((INT32) ((x) * (1L<<SCALEBITS) + 0.5))
  169687. /*
  169688. * Initialize tables for YCC->RGB colorspace conversion.
  169689. * This is taken directly from jdcolor.c; see that file for more info.
  169690. */
  169691. LOCAL(void)
  169692. build_ycc_rgb_table2 (j_decompress_ptr cinfo)
  169693. {
  169694. my_upsample_ptr upsample = (my_upsample_ptr) cinfo->upsample;
  169695. int i;
  169696. INT32 x;
  169697. SHIFT_TEMPS
  169698. upsample->Cr_r_tab = (int *)
  169699. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  169700. (MAXJSAMPLE+1) * SIZEOF(int));
  169701. upsample->Cb_b_tab = (int *)
  169702. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  169703. (MAXJSAMPLE+1) * SIZEOF(int));
  169704. upsample->Cr_g_tab = (INT32 *)
  169705. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  169706. (MAXJSAMPLE+1) * SIZEOF(INT32));
  169707. upsample->Cb_g_tab = (INT32 *)
  169708. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  169709. (MAXJSAMPLE+1) * SIZEOF(INT32));
  169710. for (i = 0, x = -CENTERJSAMPLE; i <= MAXJSAMPLE; i++, x++) {
  169711. /* i is the actual input pixel value, in the range 0..MAXJSAMPLE */
  169712. /* The Cb or Cr value we are thinking of is x = i - CENTERJSAMPLE */
  169713. /* Cr=>R value is nearest int to 1.40200 * x */
  169714. upsample->Cr_r_tab[i] = (int)
  169715. RIGHT_SHIFT(FIX(1.40200) * x + ONE_HALF, SCALEBITS);
  169716. /* Cb=>B value is nearest int to 1.77200 * x */
  169717. upsample->Cb_b_tab[i] = (int)
  169718. RIGHT_SHIFT(FIX(1.77200) * x + ONE_HALF, SCALEBITS);
  169719. /* Cr=>G value is scaled-up -0.71414 * x */
  169720. upsample->Cr_g_tab[i] = (- FIX(0.71414)) * x;
  169721. /* Cb=>G value is scaled-up -0.34414 * x */
  169722. /* We also add in ONE_HALF so that need not do it in inner loop */
  169723. upsample->Cb_g_tab[i] = (- FIX(0.34414)) * x + ONE_HALF;
  169724. }
  169725. }
  169726. /*
  169727. * Initialize for an upsampling pass.
  169728. */
  169729. METHODDEF(void)
  169730. start_pass_merged_upsample (j_decompress_ptr cinfo)
  169731. {
  169732. my_upsample_ptr upsample = (my_upsample_ptr) cinfo->upsample;
  169733. /* Mark the spare buffer empty */
  169734. upsample->spare_full = FALSE;
  169735. /* Initialize total-height counter for detecting bottom of image */
  169736. upsample->rows_to_go = cinfo->output_height;
  169737. }
  169738. /*
  169739. * Control routine to do upsampling (and color conversion).
  169740. *
  169741. * The control routine just handles the row buffering considerations.
  169742. */
  169743. METHODDEF(void)
  169744. merged_2v_upsample (j_decompress_ptr cinfo,
  169745. JSAMPIMAGE input_buf, JDIMENSION *in_row_group_ctr,
  169746. JDIMENSION,
  169747. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  169748. JDIMENSION out_rows_avail)
  169749. /* 2:1 vertical sampling case: may need a spare row. */
  169750. {
  169751. my_upsample_ptr upsample = (my_upsample_ptr) cinfo->upsample;
  169752. JSAMPROW work_ptrs[2];
  169753. JDIMENSION num_rows; /* number of rows returned to caller */
  169754. if (upsample->spare_full) {
  169755. /* If we have a spare row saved from a previous cycle, just return it. */
  169756. jcopy_sample_rows(& upsample->spare_row, 0, output_buf + *out_row_ctr, 0,
  169757. 1, upsample->out_row_width);
  169758. num_rows = 1;
  169759. upsample->spare_full = FALSE;
  169760. } else {
  169761. /* Figure number of rows to return to caller. */
  169762. num_rows = 2;
  169763. /* Not more than the distance to the end of the image. */
  169764. if (num_rows > upsample->rows_to_go)
  169765. num_rows = upsample->rows_to_go;
  169766. /* And not more than what the client can accept: */
  169767. out_rows_avail -= *out_row_ctr;
  169768. if (num_rows > out_rows_avail)
  169769. num_rows = out_rows_avail;
  169770. /* Create output pointer array for upsampler. */
  169771. work_ptrs[0] = output_buf[*out_row_ctr];
  169772. if (num_rows > 1) {
  169773. work_ptrs[1] = output_buf[*out_row_ctr + 1];
  169774. } else {
  169775. work_ptrs[1] = upsample->spare_row;
  169776. upsample->spare_full = TRUE;
  169777. }
  169778. /* Now do the upsampling. */
  169779. (*upsample->upmethod) (cinfo, input_buf, *in_row_group_ctr, work_ptrs);
  169780. }
  169781. /* Adjust counts */
  169782. *out_row_ctr += num_rows;
  169783. upsample->rows_to_go -= num_rows;
  169784. /* When the buffer is emptied, declare this input row group consumed */
  169785. if (! upsample->spare_full)
  169786. (*in_row_group_ctr)++;
  169787. }
  169788. METHODDEF(void)
  169789. merged_1v_upsample (j_decompress_ptr cinfo,
  169790. JSAMPIMAGE input_buf, JDIMENSION *in_row_group_ctr,
  169791. JDIMENSION,
  169792. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  169793. JDIMENSION)
  169794. /* 1:1 vertical sampling case: much easier, never need a spare row. */
  169795. {
  169796. my_upsample_ptr upsample = (my_upsample_ptr) cinfo->upsample;
  169797. /* Just do the upsampling. */
  169798. (*upsample->upmethod) (cinfo, input_buf, *in_row_group_ctr,
  169799. output_buf + *out_row_ctr);
  169800. /* Adjust counts */
  169801. (*out_row_ctr)++;
  169802. (*in_row_group_ctr)++;
  169803. }
  169804. /*
  169805. * These are the routines invoked by the control routines to do
  169806. * the actual upsampling/conversion. One row group is processed per call.
  169807. *
  169808. * Note: since we may be writing directly into application-supplied buffers,
  169809. * we have to be honest about the output width; we can't assume the buffer
  169810. * has been rounded up to an even width.
  169811. */
  169812. /*
  169813. * Upsample and color convert for the case of 2:1 horizontal and 1:1 vertical.
  169814. */
  169815. METHODDEF(void)
  169816. h2v1_merged_upsample (j_decompress_ptr cinfo,
  169817. JSAMPIMAGE input_buf, JDIMENSION in_row_group_ctr,
  169818. JSAMPARRAY output_buf)
  169819. {
  169820. my_upsample_ptr upsample = (my_upsample_ptr) cinfo->upsample;
  169821. register int y, cred, cgreen, cblue;
  169822. int cb, cr;
  169823. register JSAMPROW outptr;
  169824. JSAMPROW inptr0, inptr1, inptr2;
  169825. JDIMENSION col;
  169826. /* copy these pointers into registers if possible */
  169827. register JSAMPLE * range_limit = cinfo->sample_range_limit;
  169828. int * Crrtab = upsample->Cr_r_tab;
  169829. int * Cbbtab = upsample->Cb_b_tab;
  169830. INT32 * Crgtab = upsample->Cr_g_tab;
  169831. INT32 * Cbgtab = upsample->Cb_g_tab;
  169832. SHIFT_TEMPS
  169833. inptr0 = input_buf[0][in_row_group_ctr];
  169834. inptr1 = input_buf[1][in_row_group_ctr];
  169835. inptr2 = input_buf[2][in_row_group_ctr];
  169836. outptr = output_buf[0];
  169837. /* Loop for each pair of output pixels */
  169838. for (col = cinfo->output_width >> 1; col > 0; col--) {
  169839. /* Do the chroma part of the calculation */
  169840. cb = GETJSAMPLE(*inptr1++);
  169841. cr = GETJSAMPLE(*inptr2++);
  169842. cred = Crrtab[cr];
  169843. cgreen = (int) RIGHT_SHIFT(Cbgtab[cb] + Crgtab[cr], SCALEBITS);
  169844. cblue = Cbbtab[cb];
  169845. /* Fetch 2 Y values and emit 2 pixels */
  169846. y = GETJSAMPLE(*inptr0++);
  169847. outptr[RGB_RED] = range_limit[y + cred];
  169848. outptr[RGB_GREEN] = range_limit[y + cgreen];
  169849. outptr[RGB_BLUE] = range_limit[y + cblue];
  169850. outptr += RGB_PIXELSIZE;
  169851. y = GETJSAMPLE(*inptr0++);
  169852. outptr[RGB_RED] = range_limit[y + cred];
  169853. outptr[RGB_GREEN] = range_limit[y + cgreen];
  169854. outptr[RGB_BLUE] = range_limit[y + cblue];
  169855. outptr += RGB_PIXELSIZE;
  169856. }
  169857. /* If image width is odd, do the last output column separately */
  169858. if (cinfo->output_width & 1) {
  169859. cb = GETJSAMPLE(*inptr1);
  169860. cr = GETJSAMPLE(*inptr2);
  169861. cred = Crrtab[cr];
  169862. cgreen = (int) RIGHT_SHIFT(Cbgtab[cb] + Crgtab[cr], SCALEBITS);
  169863. cblue = Cbbtab[cb];
  169864. y = GETJSAMPLE(*inptr0);
  169865. outptr[RGB_RED] = range_limit[y + cred];
  169866. outptr[RGB_GREEN] = range_limit[y + cgreen];
  169867. outptr[RGB_BLUE] = range_limit[y + cblue];
  169868. }
  169869. }
  169870. /*
  169871. * Upsample and color convert for the case of 2:1 horizontal and 2:1 vertical.
  169872. */
  169873. METHODDEF(void)
  169874. h2v2_merged_upsample (j_decompress_ptr cinfo,
  169875. JSAMPIMAGE input_buf, JDIMENSION in_row_group_ctr,
  169876. JSAMPARRAY output_buf)
  169877. {
  169878. my_upsample_ptr upsample = (my_upsample_ptr) cinfo->upsample;
  169879. register int y, cred, cgreen, cblue;
  169880. int cb, cr;
  169881. register JSAMPROW outptr0, outptr1;
  169882. JSAMPROW inptr00, inptr01, inptr1, inptr2;
  169883. JDIMENSION col;
  169884. /* copy these pointers into registers if possible */
  169885. register JSAMPLE * range_limit = cinfo->sample_range_limit;
  169886. int * Crrtab = upsample->Cr_r_tab;
  169887. int * Cbbtab = upsample->Cb_b_tab;
  169888. INT32 * Crgtab = upsample->Cr_g_tab;
  169889. INT32 * Cbgtab = upsample->Cb_g_tab;
  169890. SHIFT_TEMPS
  169891. inptr00 = input_buf[0][in_row_group_ctr*2];
  169892. inptr01 = input_buf[0][in_row_group_ctr*2 + 1];
  169893. inptr1 = input_buf[1][in_row_group_ctr];
  169894. inptr2 = input_buf[2][in_row_group_ctr];
  169895. outptr0 = output_buf[0];
  169896. outptr1 = output_buf[1];
  169897. /* Loop for each group of output pixels */
  169898. for (col = cinfo->output_width >> 1; col > 0; col--) {
  169899. /* Do the chroma part of the calculation */
  169900. cb = GETJSAMPLE(*inptr1++);
  169901. cr = GETJSAMPLE(*inptr2++);
  169902. cred = Crrtab[cr];
  169903. cgreen = (int) RIGHT_SHIFT(Cbgtab[cb] + Crgtab[cr], SCALEBITS);
  169904. cblue = Cbbtab[cb];
  169905. /* Fetch 4 Y values and emit 4 pixels */
  169906. y = GETJSAMPLE(*inptr00++);
  169907. outptr0[RGB_RED] = range_limit[y + cred];
  169908. outptr0[RGB_GREEN] = range_limit[y + cgreen];
  169909. outptr0[RGB_BLUE] = range_limit[y + cblue];
  169910. outptr0 += RGB_PIXELSIZE;
  169911. y = GETJSAMPLE(*inptr00++);
  169912. outptr0[RGB_RED] = range_limit[y + cred];
  169913. outptr0[RGB_GREEN] = range_limit[y + cgreen];
  169914. outptr0[RGB_BLUE] = range_limit[y + cblue];
  169915. outptr0 += RGB_PIXELSIZE;
  169916. y = GETJSAMPLE(*inptr01++);
  169917. outptr1[RGB_RED] = range_limit[y + cred];
  169918. outptr1[RGB_GREEN] = range_limit[y + cgreen];
  169919. outptr1[RGB_BLUE] = range_limit[y + cblue];
  169920. outptr1 += RGB_PIXELSIZE;
  169921. y = GETJSAMPLE(*inptr01++);
  169922. outptr1[RGB_RED] = range_limit[y + cred];
  169923. outptr1[RGB_GREEN] = range_limit[y + cgreen];
  169924. outptr1[RGB_BLUE] = range_limit[y + cblue];
  169925. outptr1 += RGB_PIXELSIZE;
  169926. }
  169927. /* If image width is odd, do the last output column separately */
  169928. if (cinfo->output_width & 1) {
  169929. cb = GETJSAMPLE(*inptr1);
  169930. cr = GETJSAMPLE(*inptr2);
  169931. cred = Crrtab[cr];
  169932. cgreen = (int) RIGHT_SHIFT(Cbgtab[cb] + Crgtab[cr], SCALEBITS);
  169933. cblue = Cbbtab[cb];
  169934. y = GETJSAMPLE(*inptr00);
  169935. outptr0[RGB_RED] = range_limit[y + cred];
  169936. outptr0[RGB_GREEN] = range_limit[y + cgreen];
  169937. outptr0[RGB_BLUE] = range_limit[y + cblue];
  169938. y = GETJSAMPLE(*inptr01);
  169939. outptr1[RGB_RED] = range_limit[y + cred];
  169940. outptr1[RGB_GREEN] = range_limit[y + cgreen];
  169941. outptr1[RGB_BLUE] = range_limit[y + cblue];
  169942. }
  169943. }
  169944. /*
  169945. * Module initialization routine for merged upsampling/color conversion.
  169946. *
  169947. * NB: this is called under the conditions determined by use_merged_upsample()
  169948. * in jdmaster.c. That routine MUST correspond to the actual capabilities
  169949. * of this module; no safety checks are made here.
  169950. */
  169951. GLOBAL(void)
  169952. jinit_merged_upsampler (j_decompress_ptr cinfo)
  169953. {
  169954. my_upsample_ptr upsample;
  169955. upsample = (my_upsample_ptr)
  169956. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  169957. SIZEOF(my_upsampler));
  169958. cinfo->upsample = (struct jpeg_upsampler *) upsample;
  169959. upsample->pub.start_pass = start_pass_merged_upsample;
  169960. upsample->pub.need_context_rows = FALSE;
  169961. upsample->out_row_width = cinfo->output_width * cinfo->out_color_components;
  169962. if (cinfo->max_v_samp_factor == 2) {
  169963. upsample->pub.upsample = merged_2v_upsample;
  169964. upsample->upmethod = h2v2_merged_upsample;
  169965. /* Allocate a spare row buffer */
  169966. upsample->spare_row = (JSAMPROW)
  169967. (*cinfo->mem->alloc_large) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  169968. (size_t) (upsample->out_row_width * SIZEOF(JSAMPLE)));
  169969. } else {
  169970. upsample->pub.upsample = merged_1v_upsample;
  169971. upsample->upmethod = h2v1_merged_upsample;
  169972. /* No spare row needed */
  169973. upsample->spare_row = NULL;
  169974. }
  169975. build_ycc_rgb_table2(cinfo);
  169976. }
  169977. #endif /* UPSAMPLE_MERGING_SUPPORTED */
  169978. /*** End of inlined file: jdmerge.c ***/
  169979. #undef ASSIGN_STATE
  169980. /*** Start of inlined file: jdphuff.c ***/
  169981. #define JPEG_INTERNALS
  169982. #ifdef D_PROGRESSIVE_SUPPORTED
  169983. /*
  169984. * Expanded entropy decoder object for progressive Huffman decoding.
  169985. *
  169986. * The savable_state subrecord contains fields that change within an MCU,
  169987. * but must not be updated permanently until we complete the MCU.
  169988. */
  169989. typedef struct {
  169990. unsigned int EOBRUN; /* remaining EOBs in EOBRUN */
  169991. int last_dc_val[MAX_COMPS_IN_SCAN]; /* last DC coef for each component */
  169992. } savable_state3;
  169993. /* This macro is to work around compilers with missing or broken
  169994. * structure assignment. You'll need to fix this code if you have
  169995. * such a compiler and you change MAX_COMPS_IN_SCAN.
  169996. */
  169997. #ifndef NO_STRUCT_ASSIGN
  169998. #define ASSIGN_STATE(dest,src) ((dest) = (src))
  169999. #else
  170000. #if MAX_COMPS_IN_SCAN == 4
  170001. #define ASSIGN_STATE(dest,src) \
  170002. ((dest).EOBRUN = (src).EOBRUN, \
  170003. (dest).last_dc_val[0] = (src).last_dc_val[0], \
  170004. (dest).last_dc_val[1] = (src).last_dc_val[1], \
  170005. (dest).last_dc_val[2] = (src).last_dc_val[2], \
  170006. (dest).last_dc_val[3] = (src).last_dc_val[3])
  170007. #endif
  170008. #endif
  170009. typedef struct {
  170010. struct jpeg_entropy_decoder pub; /* public fields */
  170011. /* These fields are loaded into local variables at start of each MCU.
  170012. * In case of suspension, we exit WITHOUT updating them.
  170013. */
  170014. bitread_perm_state bitstate; /* Bit buffer at start of MCU */
  170015. savable_state3 saved; /* Other state at start of MCU */
  170016. /* These fields are NOT loaded into local working state. */
  170017. unsigned int restarts_to_go; /* MCUs left in this restart interval */
  170018. /* Pointers to derived tables (these workspaces have image lifespan) */
  170019. d_derived_tbl * derived_tbls[NUM_HUFF_TBLS];
  170020. d_derived_tbl * ac_derived_tbl; /* active table during an AC scan */
  170021. } phuff_entropy_decoder;
  170022. typedef phuff_entropy_decoder * phuff_entropy_ptr2;
  170023. /* Forward declarations */
  170024. METHODDEF(boolean) decode_mcu_DC_first JPP((j_decompress_ptr cinfo,
  170025. JBLOCKROW *MCU_data));
  170026. METHODDEF(boolean) decode_mcu_AC_first JPP((j_decompress_ptr cinfo,
  170027. JBLOCKROW *MCU_data));
  170028. METHODDEF(boolean) decode_mcu_DC_refine JPP((j_decompress_ptr cinfo,
  170029. JBLOCKROW *MCU_data));
  170030. METHODDEF(boolean) decode_mcu_AC_refine JPP((j_decompress_ptr cinfo,
  170031. JBLOCKROW *MCU_data));
  170032. /*
  170033. * Initialize for a Huffman-compressed scan.
  170034. */
  170035. METHODDEF(void)
  170036. start_pass_phuff_decoder (j_decompress_ptr cinfo)
  170037. {
  170038. phuff_entropy_ptr2 entropy = (phuff_entropy_ptr2) cinfo->entropy;
  170039. boolean is_DC_band, bad;
  170040. int ci, coefi, tbl;
  170041. int *coef_bit_ptr;
  170042. jpeg_component_info * compptr;
  170043. is_DC_band = (cinfo->Ss == 0);
  170044. /* Validate scan parameters */
  170045. bad = FALSE;
  170046. if (is_DC_band) {
  170047. if (cinfo->Se != 0)
  170048. bad = TRUE;
  170049. } else {
  170050. /* need not check Ss/Se < 0 since they came from unsigned bytes */
  170051. if (cinfo->Ss > cinfo->Se || cinfo->Se >= DCTSIZE2)
  170052. bad = TRUE;
  170053. /* AC scans may have only one component */
  170054. if (cinfo->comps_in_scan != 1)
  170055. bad = TRUE;
  170056. }
  170057. if (cinfo->Ah != 0) {
  170058. /* Successive approximation refinement scan: must have Al = Ah-1. */
  170059. if (cinfo->Al != cinfo->Ah-1)
  170060. bad = TRUE;
  170061. }
  170062. if (cinfo->Al > 13) /* need not check for < 0 */
  170063. bad = TRUE;
  170064. /* Arguably the maximum Al value should be less than 13 for 8-bit precision,
  170065. * but the spec doesn't say so, and we try to be liberal about what we
  170066. * accept. Note: large Al values could result in out-of-range DC
  170067. * coefficients during early scans, leading to bizarre displays due to
  170068. * overflows in the IDCT math. But we won't crash.
  170069. */
  170070. if (bad)
  170071. ERREXIT4(cinfo, JERR_BAD_PROGRESSION,
  170072. cinfo->Ss, cinfo->Se, cinfo->Ah, cinfo->Al);
  170073. /* Update progression status, and verify that scan order is legal.
  170074. * Note that inter-scan inconsistencies are treated as warnings
  170075. * not fatal errors ... not clear if this is right way to behave.
  170076. */
  170077. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  170078. int cindex = cinfo->cur_comp_info[ci]->component_index;
  170079. coef_bit_ptr = & cinfo->coef_bits[cindex][0];
  170080. if (!is_DC_band && coef_bit_ptr[0] < 0) /* AC without prior DC scan */
  170081. WARNMS2(cinfo, JWRN_BOGUS_PROGRESSION, cindex, 0);
  170082. for (coefi = cinfo->Ss; coefi <= cinfo->Se; coefi++) {
  170083. int expected = (coef_bit_ptr[coefi] < 0) ? 0 : coef_bit_ptr[coefi];
  170084. if (cinfo->Ah != expected)
  170085. WARNMS2(cinfo, JWRN_BOGUS_PROGRESSION, cindex, coefi);
  170086. coef_bit_ptr[coefi] = cinfo->Al;
  170087. }
  170088. }
  170089. /* Select MCU decoding routine */
  170090. if (cinfo->Ah == 0) {
  170091. if (is_DC_band)
  170092. entropy->pub.decode_mcu = decode_mcu_DC_first;
  170093. else
  170094. entropy->pub.decode_mcu = decode_mcu_AC_first;
  170095. } else {
  170096. if (is_DC_band)
  170097. entropy->pub.decode_mcu = decode_mcu_DC_refine;
  170098. else
  170099. entropy->pub.decode_mcu = decode_mcu_AC_refine;
  170100. }
  170101. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  170102. compptr = cinfo->cur_comp_info[ci];
  170103. /* Make sure requested tables are present, and compute derived tables.
  170104. * We may build same derived table more than once, but it's not expensive.
  170105. */
  170106. if (is_DC_band) {
  170107. if (cinfo->Ah == 0) { /* DC refinement needs no table */
  170108. tbl = compptr->dc_tbl_no;
  170109. jpeg_make_d_derived_tbl(cinfo, TRUE, tbl,
  170110. & entropy->derived_tbls[tbl]);
  170111. }
  170112. } else {
  170113. tbl = compptr->ac_tbl_no;
  170114. jpeg_make_d_derived_tbl(cinfo, FALSE, tbl,
  170115. & entropy->derived_tbls[tbl]);
  170116. /* remember the single active table */
  170117. entropy->ac_derived_tbl = entropy->derived_tbls[tbl];
  170118. }
  170119. /* Initialize DC predictions to 0 */
  170120. entropy->saved.last_dc_val[ci] = 0;
  170121. }
  170122. /* Initialize bitread state variables */
  170123. entropy->bitstate.bits_left = 0;
  170124. entropy->bitstate.get_buffer = 0; /* unnecessary, but keeps Purify quiet */
  170125. entropy->pub.insufficient_data = FALSE;
  170126. /* Initialize private state variables */
  170127. entropy->saved.EOBRUN = 0;
  170128. /* Initialize restart counter */
  170129. entropy->restarts_to_go = cinfo->restart_interval;
  170130. }
  170131. /*
  170132. * Check for a restart marker & resynchronize decoder.
  170133. * Returns FALSE if must suspend.
  170134. */
  170135. LOCAL(boolean)
  170136. process_restartp (j_decompress_ptr cinfo)
  170137. {
  170138. phuff_entropy_ptr2 entropy = (phuff_entropy_ptr2) cinfo->entropy;
  170139. int ci;
  170140. /* Throw away any unused bits remaining in bit buffer; */
  170141. /* include any full bytes in next_marker's count of discarded bytes */
  170142. cinfo->marker->discarded_bytes += entropy->bitstate.bits_left / 8;
  170143. entropy->bitstate.bits_left = 0;
  170144. /* Advance past the RSTn marker */
  170145. if (! (*cinfo->marker->read_restart_marker) (cinfo))
  170146. return FALSE;
  170147. /* Re-initialize DC predictions to 0 */
  170148. for (ci = 0; ci < cinfo->comps_in_scan; ci++)
  170149. entropy->saved.last_dc_val[ci] = 0;
  170150. /* Re-init EOB run count, too */
  170151. entropy->saved.EOBRUN = 0;
  170152. /* Reset restart counter */
  170153. entropy->restarts_to_go = cinfo->restart_interval;
  170154. /* Reset out-of-data flag, unless read_restart_marker left us smack up
  170155. * against a marker. In that case we will end up treating the next data
  170156. * segment as empty, and we can avoid producing bogus output pixels by
  170157. * leaving the flag set.
  170158. */
  170159. if (cinfo->unread_marker == 0)
  170160. entropy->pub.insufficient_data = FALSE;
  170161. return TRUE;
  170162. }
  170163. /*
  170164. * Huffman MCU decoding.
  170165. * Each of these routines decodes and returns one MCU's worth of
  170166. * Huffman-compressed coefficients.
  170167. * The coefficients are reordered from zigzag order into natural array order,
  170168. * but are not dequantized.
  170169. *
  170170. * The i'th block of the MCU is stored into the block pointed to by
  170171. * MCU_data[i]. WE ASSUME THIS AREA IS INITIALLY ZEROED BY THE CALLER.
  170172. *
  170173. * We return FALSE if data source requested suspension. In that case no
  170174. * changes have been made to permanent state. (Exception: some output
  170175. * coefficients may already have been assigned. This is harmless for
  170176. * spectral selection, since we'll just re-assign them on the next call.
  170177. * Successive approximation AC refinement has to be more careful, however.)
  170178. */
  170179. /*
  170180. * MCU decoding for DC initial scan (either spectral selection,
  170181. * or first pass of successive approximation).
  170182. */
  170183. METHODDEF(boolean)
  170184. decode_mcu_DC_first (j_decompress_ptr cinfo, JBLOCKROW *MCU_data)
  170185. {
  170186. phuff_entropy_ptr2 entropy = (phuff_entropy_ptr2) cinfo->entropy;
  170187. int Al = cinfo->Al;
  170188. register int s, r;
  170189. int blkn, ci;
  170190. JBLOCKROW block;
  170191. BITREAD_STATE_VARS;
  170192. savable_state3 state;
  170193. d_derived_tbl * tbl;
  170194. jpeg_component_info * compptr;
  170195. /* Process restart marker if needed; may have to suspend */
  170196. if (cinfo->restart_interval) {
  170197. if (entropy->restarts_to_go == 0)
  170198. if (! process_restartp(cinfo))
  170199. return FALSE;
  170200. }
  170201. /* If we've run out of data, just leave the MCU set to zeroes.
  170202. * This way, we return uniform gray for the remainder of the segment.
  170203. */
  170204. if (! entropy->pub.insufficient_data) {
  170205. /* Load up working state */
  170206. BITREAD_LOAD_STATE(cinfo,entropy->bitstate);
  170207. ASSIGN_STATE(state, entropy->saved);
  170208. /* Outer loop handles each block in the MCU */
  170209. for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
  170210. block = MCU_data[blkn];
  170211. ci = cinfo->MCU_membership[blkn];
  170212. compptr = cinfo->cur_comp_info[ci];
  170213. tbl = entropy->derived_tbls[compptr->dc_tbl_no];
  170214. /* Decode a single block's worth of coefficients */
  170215. /* Section F.2.2.1: decode the DC coefficient difference */
  170216. HUFF_DECODE(s, br_state, tbl, return FALSE, label1);
  170217. if (s) {
  170218. CHECK_BIT_BUFFER(br_state, s, return FALSE);
  170219. r = GET_BITS(s);
  170220. s = HUFF_EXTEND(r, s);
  170221. }
  170222. /* Convert DC difference to actual value, update last_dc_val */
  170223. s += state.last_dc_val[ci];
  170224. state.last_dc_val[ci] = s;
  170225. /* Scale and output the coefficient (assumes jpeg_natural_order[0]=0) */
  170226. (*block)[0] = (JCOEF) (s << Al);
  170227. }
  170228. /* Completed MCU, so update state */
  170229. BITREAD_SAVE_STATE(cinfo,entropy->bitstate);
  170230. ASSIGN_STATE(entropy->saved, state);
  170231. }
  170232. /* Account for restart interval (no-op if not using restarts) */
  170233. entropy->restarts_to_go--;
  170234. return TRUE;
  170235. }
  170236. /*
  170237. * MCU decoding for AC initial scan (either spectral selection,
  170238. * or first pass of successive approximation).
  170239. */
  170240. METHODDEF(boolean)
  170241. decode_mcu_AC_first (j_decompress_ptr cinfo, JBLOCKROW *MCU_data)
  170242. {
  170243. phuff_entropy_ptr2 entropy = (phuff_entropy_ptr2) cinfo->entropy;
  170244. int Se = cinfo->Se;
  170245. int Al = cinfo->Al;
  170246. register int s, k, r;
  170247. unsigned int EOBRUN;
  170248. JBLOCKROW block;
  170249. BITREAD_STATE_VARS;
  170250. d_derived_tbl * tbl;
  170251. /* Process restart marker if needed; may have to suspend */
  170252. if (cinfo->restart_interval) {
  170253. if (entropy->restarts_to_go == 0)
  170254. if (! process_restartp(cinfo))
  170255. return FALSE;
  170256. }
  170257. /* If we've run out of data, just leave the MCU set to zeroes.
  170258. * This way, we return uniform gray for the remainder of the segment.
  170259. */
  170260. if (! entropy->pub.insufficient_data) {
  170261. /* Load up working state.
  170262. * We can avoid loading/saving bitread state if in an EOB run.
  170263. */
  170264. EOBRUN = entropy->saved.EOBRUN; /* only part of saved state we need */
  170265. /* There is always only one block per MCU */
  170266. if (EOBRUN > 0) /* if it's a band of zeroes... */
  170267. EOBRUN--; /* ...process it now (we do nothing) */
  170268. else {
  170269. BITREAD_LOAD_STATE(cinfo,entropy->bitstate);
  170270. block = MCU_data[0];
  170271. tbl = entropy->ac_derived_tbl;
  170272. for (k = cinfo->Ss; k <= Se; k++) {
  170273. HUFF_DECODE(s, br_state, tbl, return FALSE, label2);
  170274. r = s >> 4;
  170275. s &= 15;
  170276. if (s) {
  170277. k += r;
  170278. CHECK_BIT_BUFFER(br_state, s, return FALSE);
  170279. r = GET_BITS(s);
  170280. s = HUFF_EXTEND(r, s);
  170281. /* Scale and output coefficient in natural (dezigzagged) order */
  170282. (*block)[jpeg_natural_order[k]] = (JCOEF) (s << Al);
  170283. } else {
  170284. if (r == 15) { /* ZRL */
  170285. k += 15; /* skip 15 zeroes in band */
  170286. } else { /* EOBr, run length is 2^r + appended bits */
  170287. EOBRUN = 1 << r;
  170288. if (r) { /* EOBr, r > 0 */
  170289. CHECK_BIT_BUFFER(br_state, r, return FALSE);
  170290. r = GET_BITS(r);
  170291. EOBRUN += r;
  170292. }
  170293. EOBRUN--; /* this band is processed at this moment */
  170294. break; /* force end-of-band */
  170295. }
  170296. }
  170297. }
  170298. BITREAD_SAVE_STATE(cinfo,entropy->bitstate);
  170299. }
  170300. /* Completed MCU, so update state */
  170301. entropy->saved.EOBRUN = EOBRUN; /* only part of saved state we need */
  170302. }
  170303. /* Account for restart interval (no-op if not using restarts) */
  170304. entropy->restarts_to_go--;
  170305. return TRUE;
  170306. }
  170307. /*
  170308. * MCU decoding for DC successive approximation refinement scan.
  170309. * Note: we assume such scans can be multi-component, although the spec
  170310. * is not very clear on the point.
  170311. */
  170312. METHODDEF(boolean)
  170313. decode_mcu_DC_refine (j_decompress_ptr cinfo, JBLOCKROW *MCU_data)
  170314. {
  170315. phuff_entropy_ptr2 entropy = (phuff_entropy_ptr2) cinfo->entropy;
  170316. int p1 = 1 << cinfo->Al; /* 1 in the bit position being coded */
  170317. int blkn;
  170318. JBLOCKROW block;
  170319. BITREAD_STATE_VARS;
  170320. /* Process restart marker if needed; may have to suspend */
  170321. if (cinfo->restart_interval) {
  170322. if (entropy->restarts_to_go == 0)
  170323. if (! process_restartp(cinfo))
  170324. return FALSE;
  170325. }
  170326. /* Not worth the cycles to check insufficient_data here,
  170327. * since we will not change the data anyway if we read zeroes.
  170328. */
  170329. /* Load up working state */
  170330. BITREAD_LOAD_STATE(cinfo,entropy->bitstate);
  170331. /* Outer loop handles each block in the MCU */
  170332. for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
  170333. block = MCU_data[blkn];
  170334. /* Encoded data is simply the next bit of the two's-complement DC value */
  170335. CHECK_BIT_BUFFER(br_state, 1, return FALSE);
  170336. if (GET_BITS(1))
  170337. (*block)[0] |= p1;
  170338. /* Note: since we use |=, repeating the assignment later is safe */
  170339. }
  170340. /* Completed MCU, so update state */
  170341. BITREAD_SAVE_STATE(cinfo,entropy->bitstate);
  170342. /* Account for restart interval (no-op if not using restarts) */
  170343. entropy->restarts_to_go--;
  170344. return TRUE;
  170345. }
  170346. /*
  170347. * MCU decoding for AC successive approximation refinement scan.
  170348. */
  170349. METHODDEF(boolean)
  170350. decode_mcu_AC_refine (j_decompress_ptr cinfo, JBLOCKROW *MCU_data)
  170351. {
  170352. phuff_entropy_ptr2 entropy = (phuff_entropy_ptr2) cinfo->entropy;
  170353. int Se = cinfo->Se;
  170354. int p1 = 1 << cinfo->Al; /* 1 in the bit position being coded */
  170355. int m1 = (-1) << cinfo->Al; /* -1 in the bit position being coded */
  170356. register int s, k, r;
  170357. unsigned int EOBRUN;
  170358. JBLOCKROW block;
  170359. JCOEFPTR thiscoef;
  170360. BITREAD_STATE_VARS;
  170361. d_derived_tbl * tbl;
  170362. int num_newnz;
  170363. int newnz_pos[DCTSIZE2];
  170364. /* Process restart marker if needed; may have to suspend */
  170365. if (cinfo->restart_interval) {
  170366. if (entropy->restarts_to_go == 0)
  170367. if (! process_restartp(cinfo))
  170368. return FALSE;
  170369. }
  170370. /* If we've run out of data, don't modify the MCU.
  170371. */
  170372. if (! entropy->pub.insufficient_data) {
  170373. /* Load up working state */
  170374. BITREAD_LOAD_STATE(cinfo,entropy->bitstate);
  170375. EOBRUN = entropy->saved.EOBRUN; /* only part of saved state we need */
  170376. /* There is always only one block per MCU */
  170377. block = MCU_data[0];
  170378. tbl = entropy->ac_derived_tbl;
  170379. /* If we are forced to suspend, we must undo the assignments to any newly
  170380. * nonzero coefficients in the block, because otherwise we'd get confused
  170381. * next time about which coefficients were already nonzero.
  170382. * But we need not undo addition of bits to already-nonzero coefficients;
  170383. * instead, we can test the current bit to see if we already did it.
  170384. */
  170385. num_newnz = 0;
  170386. /* initialize coefficient loop counter to start of band */
  170387. k = cinfo->Ss;
  170388. if (EOBRUN == 0) {
  170389. for (; k <= Se; k++) {
  170390. HUFF_DECODE(s, br_state, tbl, goto undoit, label3);
  170391. r = s >> 4;
  170392. s &= 15;
  170393. if (s) {
  170394. if (s != 1) /* size of new coef should always be 1 */
  170395. WARNMS(cinfo, JWRN_HUFF_BAD_CODE);
  170396. CHECK_BIT_BUFFER(br_state, 1, goto undoit);
  170397. if (GET_BITS(1))
  170398. s = p1; /* newly nonzero coef is positive */
  170399. else
  170400. s = m1; /* newly nonzero coef is negative */
  170401. } else {
  170402. if (r != 15) {
  170403. EOBRUN = 1 << r; /* EOBr, run length is 2^r + appended bits */
  170404. if (r) {
  170405. CHECK_BIT_BUFFER(br_state, r, goto undoit);
  170406. r = GET_BITS(r);
  170407. EOBRUN += r;
  170408. }
  170409. break; /* rest of block is handled by EOB logic */
  170410. }
  170411. /* note s = 0 for processing ZRL */
  170412. }
  170413. /* Advance over already-nonzero coefs and r still-zero coefs,
  170414. * appending correction bits to the nonzeroes. A correction bit is 1
  170415. * if the absolute value of the coefficient must be increased.
  170416. */
  170417. do {
  170418. thiscoef = *block + jpeg_natural_order[k];
  170419. if (*thiscoef != 0) {
  170420. CHECK_BIT_BUFFER(br_state, 1, goto undoit);
  170421. if (GET_BITS(1)) {
  170422. if ((*thiscoef & p1) == 0) { /* do nothing if already set it */
  170423. if (*thiscoef >= 0)
  170424. *thiscoef += p1;
  170425. else
  170426. *thiscoef += m1;
  170427. }
  170428. }
  170429. } else {
  170430. if (--r < 0)
  170431. break; /* reached target zero coefficient */
  170432. }
  170433. k++;
  170434. } while (k <= Se);
  170435. if (s) {
  170436. int pos = jpeg_natural_order[k];
  170437. /* Output newly nonzero coefficient */
  170438. (*block)[pos] = (JCOEF) s;
  170439. /* Remember its position in case we have to suspend */
  170440. newnz_pos[num_newnz++] = pos;
  170441. }
  170442. }
  170443. }
  170444. if (EOBRUN > 0) {
  170445. /* Scan any remaining coefficient positions after the end-of-band
  170446. * (the last newly nonzero coefficient, if any). Append a correction
  170447. * bit to each already-nonzero coefficient. A correction bit is 1
  170448. * if the absolute value of the coefficient must be increased.
  170449. */
  170450. for (; k <= Se; k++) {
  170451. thiscoef = *block + jpeg_natural_order[k];
  170452. if (*thiscoef != 0) {
  170453. CHECK_BIT_BUFFER(br_state, 1, goto undoit);
  170454. if (GET_BITS(1)) {
  170455. if ((*thiscoef & p1) == 0) { /* do nothing if already changed it */
  170456. if (*thiscoef >= 0)
  170457. *thiscoef += p1;
  170458. else
  170459. *thiscoef += m1;
  170460. }
  170461. }
  170462. }
  170463. }
  170464. /* Count one block completed in EOB run */
  170465. EOBRUN--;
  170466. }
  170467. /* Completed MCU, so update state */
  170468. BITREAD_SAVE_STATE(cinfo,entropy->bitstate);
  170469. entropy->saved.EOBRUN = EOBRUN; /* only part of saved state we need */
  170470. }
  170471. /* Account for restart interval (no-op if not using restarts) */
  170472. entropy->restarts_to_go--;
  170473. return TRUE;
  170474. undoit:
  170475. /* Re-zero any output coefficients that we made newly nonzero */
  170476. while (num_newnz > 0)
  170477. (*block)[newnz_pos[--num_newnz]] = 0;
  170478. return FALSE;
  170479. }
  170480. /*
  170481. * Module initialization routine for progressive Huffman entropy decoding.
  170482. */
  170483. GLOBAL(void)
  170484. jinit_phuff_decoder (j_decompress_ptr cinfo)
  170485. {
  170486. phuff_entropy_ptr2 entropy;
  170487. int *coef_bit_ptr;
  170488. int ci, i;
  170489. entropy = (phuff_entropy_ptr2)
  170490. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  170491. SIZEOF(phuff_entropy_decoder));
  170492. cinfo->entropy = (struct jpeg_entropy_decoder *) entropy;
  170493. entropy->pub.start_pass = start_pass_phuff_decoder;
  170494. /* Mark derived tables unallocated */
  170495. for (i = 0; i < NUM_HUFF_TBLS; i++) {
  170496. entropy->derived_tbls[i] = NULL;
  170497. }
  170498. /* Create progression status table */
  170499. cinfo->coef_bits = (int (*)[DCTSIZE2])
  170500. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  170501. cinfo->num_components*DCTSIZE2*SIZEOF(int));
  170502. coef_bit_ptr = & cinfo->coef_bits[0][0];
  170503. for (ci = 0; ci < cinfo->num_components; ci++)
  170504. for (i = 0; i < DCTSIZE2; i++)
  170505. *coef_bit_ptr++ = -1;
  170506. }
  170507. #endif /* D_PROGRESSIVE_SUPPORTED */
  170508. /*** End of inlined file: jdphuff.c ***/
  170509. /*** Start of inlined file: jdpostct.c ***/
  170510. #define JPEG_INTERNALS
  170511. /* Private buffer controller object */
  170512. typedef struct {
  170513. struct jpeg_d_post_controller pub; /* public fields */
  170514. /* Color quantization source buffer: this holds output data from
  170515. * the upsample/color conversion step to be passed to the quantizer.
  170516. * For two-pass color quantization, we need a full-image buffer;
  170517. * for one-pass operation, a strip buffer is sufficient.
  170518. */
  170519. jvirt_sarray_ptr whole_image; /* virtual array, or NULL if one-pass */
  170520. JSAMPARRAY buffer; /* strip buffer, or current strip of virtual */
  170521. JDIMENSION strip_height; /* buffer size in rows */
  170522. /* for two-pass mode only: */
  170523. JDIMENSION starting_row; /* row # of first row in current strip */
  170524. JDIMENSION next_row; /* index of next row to fill/empty in strip */
  170525. } my_post_controller;
  170526. typedef my_post_controller * my_post_ptr;
  170527. /* Forward declarations */
  170528. METHODDEF(void) post_process_1pass
  170529. JPP((j_decompress_ptr cinfo,
  170530. JSAMPIMAGE input_buf, JDIMENSION *in_row_group_ctr,
  170531. JDIMENSION in_row_groups_avail,
  170532. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  170533. JDIMENSION out_rows_avail));
  170534. #ifdef QUANT_2PASS_SUPPORTED
  170535. METHODDEF(void) post_process_prepass
  170536. JPP((j_decompress_ptr cinfo,
  170537. JSAMPIMAGE input_buf, JDIMENSION *in_row_group_ctr,
  170538. JDIMENSION in_row_groups_avail,
  170539. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  170540. JDIMENSION out_rows_avail));
  170541. METHODDEF(void) post_process_2pass
  170542. JPP((j_decompress_ptr cinfo,
  170543. JSAMPIMAGE input_buf, JDIMENSION *in_row_group_ctr,
  170544. JDIMENSION in_row_groups_avail,
  170545. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  170546. JDIMENSION out_rows_avail));
  170547. #endif
  170548. /*
  170549. * Initialize for a processing pass.
  170550. */
  170551. METHODDEF(void)
  170552. start_pass_dpost (j_decompress_ptr cinfo, J_BUF_MODE pass_mode)
  170553. {
  170554. my_post_ptr post = (my_post_ptr) cinfo->post;
  170555. switch (pass_mode) {
  170556. case JBUF_PASS_THRU:
  170557. if (cinfo->quantize_colors) {
  170558. /* Single-pass processing with color quantization. */
  170559. post->pub.post_process_data = post_process_1pass;
  170560. /* We could be doing buffered-image output before starting a 2-pass
  170561. * color quantization; in that case, jinit_d_post_controller did not
  170562. * allocate a strip buffer. Use the virtual-array buffer as workspace.
  170563. */
  170564. if (post->buffer == NULL) {
  170565. post->buffer = (*cinfo->mem->access_virt_sarray)
  170566. ((j_common_ptr) cinfo, post->whole_image,
  170567. (JDIMENSION) 0, post->strip_height, TRUE);
  170568. }
  170569. } else {
  170570. /* For single-pass processing without color quantization,
  170571. * I have no work to do; just call the upsampler directly.
  170572. */
  170573. post->pub.post_process_data = cinfo->upsample->upsample;
  170574. }
  170575. break;
  170576. #ifdef QUANT_2PASS_SUPPORTED
  170577. case JBUF_SAVE_AND_PASS:
  170578. /* First pass of 2-pass quantization */
  170579. if (post->whole_image == NULL)
  170580. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  170581. post->pub.post_process_data = post_process_prepass;
  170582. break;
  170583. case JBUF_CRANK_DEST:
  170584. /* Second pass of 2-pass quantization */
  170585. if (post->whole_image == NULL)
  170586. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  170587. post->pub.post_process_data = post_process_2pass;
  170588. break;
  170589. #endif /* QUANT_2PASS_SUPPORTED */
  170590. default:
  170591. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  170592. break;
  170593. }
  170594. post->starting_row = post->next_row = 0;
  170595. }
  170596. /*
  170597. * Process some data in the one-pass (strip buffer) case.
  170598. * This is used for color precision reduction as well as one-pass quantization.
  170599. */
  170600. METHODDEF(void)
  170601. post_process_1pass (j_decompress_ptr cinfo,
  170602. JSAMPIMAGE input_buf, JDIMENSION *in_row_group_ctr,
  170603. JDIMENSION in_row_groups_avail,
  170604. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  170605. JDIMENSION out_rows_avail)
  170606. {
  170607. my_post_ptr post = (my_post_ptr) cinfo->post;
  170608. JDIMENSION num_rows, max_rows;
  170609. /* Fill the buffer, but not more than what we can dump out in one go. */
  170610. /* Note we rely on the upsampler to detect bottom of image. */
  170611. max_rows = out_rows_avail - *out_row_ctr;
  170612. if (max_rows > post->strip_height)
  170613. max_rows = post->strip_height;
  170614. num_rows = 0;
  170615. (*cinfo->upsample->upsample) (cinfo,
  170616. input_buf, in_row_group_ctr, in_row_groups_avail,
  170617. post->buffer, &num_rows, max_rows);
  170618. /* Quantize and emit data. */
  170619. (*cinfo->cquantize->color_quantize) (cinfo,
  170620. post->buffer, output_buf + *out_row_ctr, (int) num_rows);
  170621. *out_row_ctr += num_rows;
  170622. }
  170623. #ifdef QUANT_2PASS_SUPPORTED
  170624. /*
  170625. * Process some data in the first pass of 2-pass quantization.
  170626. */
  170627. METHODDEF(void)
  170628. post_process_prepass (j_decompress_ptr cinfo,
  170629. JSAMPIMAGE input_buf, JDIMENSION *in_row_group_ctr,
  170630. JDIMENSION in_row_groups_avail,
  170631. JSAMPARRAY, JDIMENSION *out_row_ctr,
  170632. JDIMENSION)
  170633. {
  170634. my_post_ptr post = (my_post_ptr) cinfo->post;
  170635. JDIMENSION old_next_row, num_rows;
  170636. /* Reposition virtual buffer if at start of strip. */
  170637. if (post->next_row == 0) {
  170638. post->buffer = (*cinfo->mem->access_virt_sarray)
  170639. ((j_common_ptr) cinfo, post->whole_image,
  170640. post->starting_row, post->strip_height, TRUE);
  170641. }
  170642. /* Upsample some data (up to a strip height's worth). */
  170643. old_next_row = post->next_row;
  170644. (*cinfo->upsample->upsample) (cinfo,
  170645. input_buf, in_row_group_ctr, in_row_groups_avail,
  170646. post->buffer, &post->next_row, post->strip_height);
  170647. /* Allow quantizer to scan new data. No data is emitted, */
  170648. /* but we advance out_row_ctr so outer loop can tell when we're done. */
  170649. if (post->next_row > old_next_row) {
  170650. num_rows = post->next_row - old_next_row;
  170651. (*cinfo->cquantize->color_quantize) (cinfo, post->buffer + old_next_row,
  170652. (JSAMPARRAY) NULL, (int) num_rows);
  170653. *out_row_ctr += num_rows;
  170654. }
  170655. /* Advance if we filled the strip. */
  170656. if (post->next_row >= post->strip_height) {
  170657. post->starting_row += post->strip_height;
  170658. post->next_row = 0;
  170659. }
  170660. }
  170661. /*
  170662. * Process some data in the second pass of 2-pass quantization.
  170663. */
  170664. METHODDEF(void)
  170665. post_process_2pass (j_decompress_ptr cinfo,
  170666. JSAMPIMAGE, JDIMENSION *,
  170667. JDIMENSION,
  170668. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  170669. JDIMENSION out_rows_avail)
  170670. {
  170671. my_post_ptr post = (my_post_ptr) cinfo->post;
  170672. JDIMENSION num_rows, max_rows;
  170673. /* Reposition virtual buffer if at start of strip. */
  170674. if (post->next_row == 0) {
  170675. post->buffer = (*cinfo->mem->access_virt_sarray)
  170676. ((j_common_ptr) cinfo, post->whole_image,
  170677. post->starting_row, post->strip_height, FALSE);
  170678. }
  170679. /* Determine number of rows to emit. */
  170680. num_rows = post->strip_height - post->next_row; /* available in strip */
  170681. max_rows = out_rows_avail - *out_row_ctr; /* available in output area */
  170682. if (num_rows > max_rows)
  170683. num_rows = max_rows;
  170684. /* We have to check bottom of image here, can't depend on upsampler. */
  170685. max_rows = cinfo->output_height - post->starting_row;
  170686. if (num_rows > max_rows)
  170687. num_rows = max_rows;
  170688. /* Quantize and emit data. */
  170689. (*cinfo->cquantize->color_quantize) (cinfo,
  170690. post->buffer + post->next_row, output_buf + *out_row_ctr,
  170691. (int) num_rows);
  170692. *out_row_ctr += num_rows;
  170693. /* Advance if we filled the strip. */
  170694. post->next_row += num_rows;
  170695. if (post->next_row >= post->strip_height) {
  170696. post->starting_row += post->strip_height;
  170697. post->next_row = 0;
  170698. }
  170699. }
  170700. #endif /* QUANT_2PASS_SUPPORTED */
  170701. /*
  170702. * Initialize postprocessing controller.
  170703. */
  170704. GLOBAL(void)
  170705. jinit_d_post_controller (j_decompress_ptr cinfo, boolean need_full_buffer)
  170706. {
  170707. my_post_ptr post;
  170708. post = (my_post_ptr)
  170709. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  170710. SIZEOF(my_post_controller));
  170711. cinfo->post = (struct jpeg_d_post_controller *) post;
  170712. post->pub.start_pass = start_pass_dpost;
  170713. post->whole_image = NULL; /* flag for no virtual arrays */
  170714. post->buffer = NULL; /* flag for no strip buffer */
  170715. /* Create the quantization buffer, if needed */
  170716. if (cinfo->quantize_colors) {
  170717. /* The buffer strip height is max_v_samp_factor, which is typically
  170718. * an efficient number of rows for upsampling to return.
  170719. * (In the presence of output rescaling, we might want to be smarter?)
  170720. */
  170721. post->strip_height = (JDIMENSION) cinfo->max_v_samp_factor;
  170722. if (need_full_buffer) {
  170723. /* Two-pass color quantization: need full-image storage. */
  170724. /* We round up the number of rows to a multiple of the strip height. */
  170725. #ifdef QUANT_2PASS_SUPPORTED
  170726. post->whole_image = (*cinfo->mem->request_virt_sarray)
  170727. ((j_common_ptr) cinfo, JPOOL_IMAGE, FALSE,
  170728. cinfo->output_width * cinfo->out_color_components,
  170729. (JDIMENSION) jround_up((long) cinfo->output_height,
  170730. (long) post->strip_height),
  170731. post->strip_height);
  170732. #else
  170733. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  170734. #endif /* QUANT_2PASS_SUPPORTED */
  170735. } else {
  170736. /* One-pass color quantization: just make a strip buffer. */
  170737. post->buffer = (*cinfo->mem->alloc_sarray)
  170738. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  170739. cinfo->output_width * cinfo->out_color_components,
  170740. post->strip_height);
  170741. }
  170742. }
  170743. }
  170744. /*** End of inlined file: jdpostct.c ***/
  170745. #undef FIX
  170746. /*** Start of inlined file: jdsample.c ***/
  170747. #define JPEG_INTERNALS
  170748. /* Pointer to routine to upsample a single component */
  170749. typedef JMETHOD(void, upsample1_ptr,
  170750. (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  170751. JSAMPARRAY input_data, JSAMPARRAY * output_data_ptr));
  170752. /* Private subobject */
  170753. typedef struct {
  170754. struct jpeg_upsampler pub; /* public fields */
  170755. /* Color conversion buffer. When using separate upsampling and color
  170756. * conversion steps, this buffer holds one upsampled row group until it
  170757. * has been color converted and output.
  170758. * Note: we do not allocate any storage for component(s) which are full-size,
  170759. * ie do not need rescaling. The corresponding entry of color_buf[] is
  170760. * simply set to point to the input data array, thereby avoiding copying.
  170761. */
  170762. JSAMPARRAY color_buf[MAX_COMPONENTS];
  170763. /* Per-component upsampling method pointers */
  170764. upsample1_ptr methods[MAX_COMPONENTS];
  170765. int next_row_out; /* counts rows emitted from color_buf */
  170766. JDIMENSION rows_to_go; /* counts rows remaining in image */
  170767. /* Height of an input row group for each component. */
  170768. int rowgroup_height[MAX_COMPONENTS];
  170769. /* These arrays save pixel expansion factors so that int_expand need not
  170770. * recompute them each time. They are unused for other upsampling methods.
  170771. */
  170772. UINT8 h_expand[MAX_COMPONENTS];
  170773. UINT8 v_expand[MAX_COMPONENTS];
  170774. } my_upsampler2;
  170775. typedef my_upsampler2 * my_upsample_ptr2;
  170776. /*
  170777. * Initialize for an upsampling pass.
  170778. */
  170779. METHODDEF(void)
  170780. start_pass_upsample (j_decompress_ptr cinfo)
  170781. {
  170782. my_upsample_ptr2 upsample = (my_upsample_ptr2) cinfo->upsample;
  170783. /* Mark the conversion buffer empty */
  170784. upsample->next_row_out = cinfo->max_v_samp_factor;
  170785. /* Initialize total-height counter for detecting bottom of image */
  170786. upsample->rows_to_go = cinfo->output_height;
  170787. }
  170788. /*
  170789. * Control routine to do upsampling (and color conversion).
  170790. *
  170791. * In this version we upsample each component independently.
  170792. * We upsample one row group into the conversion buffer, then apply
  170793. * color conversion a row at a time.
  170794. */
  170795. METHODDEF(void)
  170796. sep_upsample (j_decompress_ptr cinfo,
  170797. JSAMPIMAGE input_buf, JDIMENSION *in_row_group_ctr,
  170798. JDIMENSION,
  170799. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  170800. JDIMENSION out_rows_avail)
  170801. {
  170802. my_upsample_ptr2 upsample = (my_upsample_ptr2) cinfo->upsample;
  170803. int ci;
  170804. jpeg_component_info * compptr;
  170805. JDIMENSION num_rows;
  170806. /* Fill the conversion buffer, if it's empty */
  170807. if (upsample->next_row_out >= cinfo->max_v_samp_factor) {
  170808. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  170809. ci++, compptr++) {
  170810. /* Invoke per-component upsample method. Notice we pass a POINTER
  170811. * to color_buf[ci], so that fullsize_upsample can change it.
  170812. */
  170813. (*upsample->methods[ci]) (cinfo, compptr,
  170814. input_buf[ci] + (*in_row_group_ctr * upsample->rowgroup_height[ci]),
  170815. upsample->color_buf + ci);
  170816. }
  170817. upsample->next_row_out = 0;
  170818. }
  170819. /* Color-convert and emit rows */
  170820. /* How many we have in the buffer: */
  170821. num_rows = (JDIMENSION) (cinfo->max_v_samp_factor - upsample->next_row_out);
  170822. /* Not more than the distance to the end of the image. Need this test
  170823. * in case the image height is not a multiple of max_v_samp_factor:
  170824. */
  170825. if (num_rows > upsample->rows_to_go)
  170826. num_rows = upsample->rows_to_go;
  170827. /* And not more than what the client can accept: */
  170828. out_rows_avail -= *out_row_ctr;
  170829. if (num_rows > out_rows_avail)
  170830. num_rows = out_rows_avail;
  170831. (*cinfo->cconvert->color_convert) (cinfo, upsample->color_buf,
  170832. (JDIMENSION) upsample->next_row_out,
  170833. output_buf + *out_row_ctr,
  170834. (int) num_rows);
  170835. /* Adjust counts */
  170836. *out_row_ctr += num_rows;
  170837. upsample->rows_to_go -= num_rows;
  170838. upsample->next_row_out += num_rows;
  170839. /* When the buffer is emptied, declare this input row group consumed */
  170840. if (upsample->next_row_out >= cinfo->max_v_samp_factor)
  170841. (*in_row_group_ctr)++;
  170842. }
  170843. /*
  170844. * These are the routines invoked by sep_upsample to upsample pixel values
  170845. * of a single component. One row group is processed per call.
  170846. */
  170847. /*
  170848. * For full-size components, we just make color_buf[ci] point at the
  170849. * input buffer, and thus avoid copying any data. Note that this is
  170850. * safe only because sep_upsample doesn't declare the input row group
  170851. * "consumed" until we are done color converting and emitting it.
  170852. */
  170853. METHODDEF(void)
  170854. fullsize_upsample (j_decompress_ptr, jpeg_component_info *,
  170855. JSAMPARRAY input_data, JSAMPARRAY * output_data_ptr)
  170856. {
  170857. *output_data_ptr = input_data;
  170858. }
  170859. /*
  170860. * This is a no-op version used for "uninteresting" components.
  170861. * These components will not be referenced by color conversion.
  170862. */
  170863. METHODDEF(void)
  170864. noop_upsample (j_decompress_ptr, jpeg_component_info *,
  170865. JSAMPARRAY, JSAMPARRAY * output_data_ptr)
  170866. {
  170867. *output_data_ptr = NULL; /* safety check */
  170868. }
  170869. /*
  170870. * This version handles any integral sampling ratios.
  170871. * This is not used for typical JPEG files, so it need not be fast.
  170872. * Nor, for that matter, is it particularly accurate: the algorithm is
  170873. * simple replication of the input pixel onto the corresponding output
  170874. * pixels. The hi-falutin sampling literature refers to this as a
  170875. * "box filter". A box filter tends to introduce visible artifacts,
  170876. * so if you are actually going to use 3:1 or 4:1 sampling ratios
  170877. * you would be well advised to improve this code.
  170878. */
  170879. METHODDEF(void)
  170880. int_upsample (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  170881. JSAMPARRAY input_data, JSAMPARRAY * output_data_ptr)
  170882. {
  170883. my_upsample_ptr2 upsample = (my_upsample_ptr2) cinfo->upsample;
  170884. JSAMPARRAY output_data = *output_data_ptr;
  170885. register JSAMPROW inptr, outptr;
  170886. register JSAMPLE invalue;
  170887. register int h;
  170888. JSAMPROW outend;
  170889. int h_expand, v_expand;
  170890. int inrow, outrow;
  170891. h_expand = upsample->h_expand[compptr->component_index];
  170892. v_expand = upsample->v_expand[compptr->component_index];
  170893. inrow = outrow = 0;
  170894. while (outrow < cinfo->max_v_samp_factor) {
  170895. /* Generate one output row with proper horizontal expansion */
  170896. inptr = input_data[inrow];
  170897. outptr = output_data[outrow];
  170898. outend = outptr + cinfo->output_width;
  170899. while (outptr < outend) {
  170900. invalue = *inptr++; /* don't need GETJSAMPLE() here */
  170901. for (h = h_expand; h > 0; h--) {
  170902. *outptr++ = invalue;
  170903. }
  170904. }
  170905. /* Generate any additional output rows by duplicating the first one */
  170906. if (v_expand > 1) {
  170907. jcopy_sample_rows(output_data, outrow, output_data, outrow+1,
  170908. v_expand-1, cinfo->output_width);
  170909. }
  170910. inrow++;
  170911. outrow += v_expand;
  170912. }
  170913. }
  170914. /*
  170915. * Fast processing for the common case of 2:1 horizontal and 1:1 vertical.
  170916. * It's still a box filter.
  170917. */
  170918. METHODDEF(void)
  170919. h2v1_upsample (j_decompress_ptr cinfo, jpeg_component_info *,
  170920. JSAMPARRAY input_data, JSAMPARRAY * output_data_ptr)
  170921. {
  170922. JSAMPARRAY output_data = *output_data_ptr;
  170923. register JSAMPROW inptr, outptr;
  170924. register JSAMPLE invalue;
  170925. JSAMPROW outend;
  170926. int inrow;
  170927. for (inrow = 0; inrow < cinfo->max_v_samp_factor; inrow++) {
  170928. inptr = input_data[inrow];
  170929. outptr = output_data[inrow];
  170930. outend = outptr + cinfo->output_width;
  170931. while (outptr < outend) {
  170932. invalue = *inptr++; /* don't need GETJSAMPLE() here */
  170933. *outptr++ = invalue;
  170934. *outptr++ = invalue;
  170935. }
  170936. }
  170937. }
  170938. /*
  170939. * Fast processing for the common case of 2:1 horizontal and 2:1 vertical.
  170940. * It's still a box filter.
  170941. */
  170942. METHODDEF(void)
  170943. h2v2_upsample (j_decompress_ptr cinfo, jpeg_component_info *,
  170944. JSAMPARRAY input_data, JSAMPARRAY * output_data_ptr)
  170945. {
  170946. JSAMPARRAY output_data = *output_data_ptr;
  170947. register JSAMPROW inptr, outptr;
  170948. register JSAMPLE invalue;
  170949. JSAMPROW outend;
  170950. int inrow, outrow;
  170951. inrow = outrow = 0;
  170952. while (outrow < cinfo->max_v_samp_factor) {
  170953. inptr = input_data[inrow];
  170954. outptr = output_data[outrow];
  170955. outend = outptr + cinfo->output_width;
  170956. while (outptr < outend) {
  170957. invalue = *inptr++; /* don't need GETJSAMPLE() here */
  170958. *outptr++ = invalue;
  170959. *outptr++ = invalue;
  170960. }
  170961. jcopy_sample_rows(output_data, outrow, output_data, outrow+1,
  170962. 1, cinfo->output_width);
  170963. inrow++;
  170964. outrow += 2;
  170965. }
  170966. }
  170967. /*
  170968. * Fancy processing for the common case of 2:1 horizontal and 1:1 vertical.
  170969. *
  170970. * The upsampling algorithm is linear interpolation between pixel centers,
  170971. * also known as a "triangle filter". This is a good compromise between
  170972. * speed and visual quality. The centers of the output pixels are 1/4 and 3/4
  170973. * of the way between input pixel centers.
  170974. *
  170975. * A note about the "bias" calculations: when rounding fractional values to
  170976. * integer, we do not want to always round 0.5 up to the next integer.
  170977. * If we did that, we'd introduce a noticeable bias towards larger values.
  170978. * Instead, this code is arranged so that 0.5 will be rounded up or down at
  170979. * alternate pixel locations (a simple ordered dither pattern).
  170980. */
  170981. METHODDEF(void)
  170982. h2v1_fancy_upsample (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  170983. JSAMPARRAY input_data, JSAMPARRAY * output_data_ptr)
  170984. {
  170985. JSAMPARRAY output_data = *output_data_ptr;
  170986. register JSAMPROW inptr, outptr;
  170987. register int invalue;
  170988. register JDIMENSION colctr;
  170989. int inrow;
  170990. for (inrow = 0; inrow < cinfo->max_v_samp_factor; inrow++) {
  170991. inptr = input_data[inrow];
  170992. outptr = output_data[inrow];
  170993. /* Special case for first column */
  170994. invalue = GETJSAMPLE(*inptr++);
  170995. *outptr++ = (JSAMPLE) invalue;
  170996. *outptr++ = (JSAMPLE) ((invalue * 3 + GETJSAMPLE(*inptr) + 2) >> 2);
  170997. for (colctr = compptr->downsampled_width - 2; colctr > 0; colctr--) {
  170998. /* General case: 3/4 * nearer pixel + 1/4 * further pixel */
  170999. invalue = GETJSAMPLE(*inptr++) * 3;
  171000. *outptr++ = (JSAMPLE) ((invalue + GETJSAMPLE(inptr[-2]) + 1) >> 2);
  171001. *outptr++ = (JSAMPLE) ((invalue + GETJSAMPLE(*inptr) + 2) >> 2);
  171002. }
  171003. /* Special case for last column */
  171004. invalue = GETJSAMPLE(*inptr);
  171005. *outptr++ = (JSAMPLE) ((invalue * 3 + GETJSAMPLE(inptr[-1]) + 1) >> 2);
  171006. *outptr++ = (JSAMPLE) invalue;
  171007. }
  171008. }
  171009. /*
  171010. * Fancy processing for the common case of 2:1 horizontal and 2:1 vertical.
  171011. * Again a triangle filter; see comments for h2v1 case, above.
  171012. *
  171013. * It is OK for us to reference the adjacent input rows because we demanded
  171014. * context from the main buffer controller (see initialization code).
  171015. */
  171016. METHODDEF(void)
  171017. h2v2_fancy_upsample (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  171018. JSAMPARRAY input_data, JSAMPARRAY * output_data_ptr)
  171019. {
  171020. JSAMPARRAY output_data = *output_data_ptr;
  171021. register JSAMPROW inptr0, inptr1, outptr;
  171022. #if BITS_IN_JSAMPLE == 8
  171023. register int thiscolsum, lastcolsum, nextcolsum;
  171024. #else
  171025. register INT32 thiscolsum, lastcolsum, nextcolsum;
  171026. #endif
  171027. register JDIMENSION colctr;
  171028. int inrow, outrow, v;
  171029. inrow = outrow = 0;
  171030. while (outrow < cinfo->max_v_samp_factor) {
  171031. for (v = 0; v < 2; v++) {
  171032. /* inptr0 points to nearest input row, inptr1 points to next nearest */
  171033. inptr0 = input_data[inrow];
  171034. if (v == 0) /* next nearest is row above */
  171035. inptr1 = input_data[inrow-1];
  171036. else /* next nearest is row below */
  171037. inptr1 = input_data[inrow+1];
  171038. outptr = output_data[outrow++];
  171039. /* Special case for first column */
  171040. thiscolsum = GETJSAMPLE(*inptr0++) * 3 + GETJSAMPLE(*inptr1++);
  171041. nextcolsum = GETJSAMPLE(*inptr0++) * 3 + GETJSAMPLE(*inptr1++);
  171042. *outptr++ = (JSAMPLE) ((thiscolsum * 4 + 8) >> 4);
  171043. *outptr++ = (JSAMPLE) ((thiscolsum * 3 + nextcolsum + 7) >> 4);
  171044. lastcolsum = thiscolsum; thiscolsum = nextcolsum;
  171045. for (colctr = compptr->downsampled_width - 2; colctr > 0; colctr--) {
  171046. /* General case: 3/4 * nearer pixel + 1/4 * further pixel in each */
  171047. /* dimension, thus 9/16, 3/16, 3/16, 1/16 overall */
  171048. nextcolsum = GETJSAMPLE(*inptr0++) * 3 + GETJSAMPLE(*inptr1++);
  171049. *outptr++ = (JSAMPLE) ((thiscolsum * 3 + lastcolsum + 8) >> 4);
  171050. *outptr++ = (JSAMPLE) ((thiscolsum * 3 + nextcolsum + 7) >> 4);
  171051. lastcolsum = thiscolsum; thiscolsum = nextcolsum;
  171052. }
  171053. /* Special case for last column */
  171054. *outptr++ = (JSAMPLE) ((thiscolsum * 3 + lastcolsum + 8) >> 4);
  171055. *outptr++ = (JSAMPLE) ((thiscolsum * 4 + 7) >> 4);
  171056. }
  171057. inrow++;
  171058. }
  171059. }
  171060. /*
  171061. * Module initialization routine for upsampling.
  171062. */
  171063. GLOBAL(void)
  171064. jinit_upsampler (j_decompress_ptr cinfo)
  171065. {
  171066. my_upsample_ptr2 upsample;
  171067. int ci;
  171068. jpeg_component_info * compptr;
  171069. boolean need_buffer, do_fancy;
  171070. int h_in_group, v_in_group, h_out_group, v_out_group;
  171071. upsample = (my_upsample_ptr2)
  171072. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  171073. SIZEOF(my_upsampler2));
  171074. cinfo->upsample = (struct jpeg_upsampler *) upsample;
  171075. upsample->pub.start_pass = start_pass_upsample;
  171076. upsample->pub.upsample = sep_upsample;
  171077. upsample->pub.need_context_rows = FALSE; /* until we find out differently */
  171078. if (cinfo->CCIR601_sampling) /* this isn't supported */
  171079. ERREXIT(cinfo, JERR_CCIR601_NOTIMPL);
  171080. /* jdmainct.c doesn't support context rows when min_DCT_scaled_size = 1,
  171081. * so don't ask for it.
  171082. */
  171083. do_fancy = cinfo->do_fancy_upsampling && cinfo->min_DCT_scaled_size > 1;
  171084. /* Verify we can handle the sampling factors, select per-component methods,
  171085. * and create storage as needed.
  171086. */
  171087. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  171088. ci++, compptr++) {
  171089. /* Compute size of an "input group" after IDCT scaling. This many samples
  171090. * are to be converted to max_h_samp_factor * max_v_samp_factor pixels.
  171091. */
  171092. h_in_group = (compptr->h_samp_factor * compptr->DCT_scaled_size) /
  171093. cinfo->min_DCT_scaled_size;
  171094. v_in_group = (compptr->v_samp_factor * compptr->DCT_scaled_size) /
  171095. cinfo->min_DCT_scaled_size;
  171096. h_out_group = cinfo->max_h_samp_factor;
  171097. v_out_group = cinfo->max_v_samp_factor;
  171098. upsample->rowgroup_height[ci] = v_in_group; /* save for use later */
  171099. need_buffer = TRUE;
  171100. if (! compptr->component_needed) {
  171101. /* Don't bother to upsample an uninteresting component. */
  171102. upsample->methods[ci] = noop_upsample;
  171103. need_buffer = FALSE;
  171104. } else if (h_in_group == h_out_group && v_in_group == v_out_group) {
  171105. /* Fullsize components can be processed without any work. */
  171106. upsample->methods[ci] = fullsize_upsample;
  171107. need_buffer = FALSE;
  171108. } else if (h_in_group * 2 == h_out_group &&
  171109. v_in_group == v_out_group) {
  171110. /* Special cases for 2h1v upsampling */
  171111. if (do_fancy && compptr->downsampled_width > 2)
  171112. upsample->methods[ci] = h2v1_fancy_upsample;
  171113. else
  171114. upsample->methods[ci] = h2v1_upsample;
  171115. } else if (h_in_group * 2 == h_out_group &&
  171116. v_in_group * 2 == v_out_group) {
  171117. /* Special cases for 2h2v upsampling */
  171118. if (do_fancy && compptr->downsampled_width > 2) {
  171119. upsample->methods[ci] = h2v2_fancy_upsample;
  171120. upsample->pub.need_context_rows = TRUE;
  171121. } else
  171122. upsample->methods[ci] = h2v2_upsample;
  171123. } else if ((h_out_group % h_in_group) == 0 &&
  171124. (v_out_group % v_in_group) == 0) {
  171125. /* Generic integral-factors upsampling method */
  171126. upsample->methods[ci] = int_upsample;
  171127. upsample->h_expand[ci] = (UINT8) (h_out_group / h_in_group);
  171128. upsample->v_expand[ci] = (UINT8) (v_out_group / v_in_group);
  171129. } else
  171130. ERREXIT(cinfo, JERR_FRACT_SAMPLE_NOTIMPL);
  171131. if (need_buffer) {
  171132. upsample->color_buf[ci] = (*cinfo->mem->alloc_sarray)
  171133. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  171134. (JDIMENSION) jround_up((long) cinfo->output_width,
  171135. (long) cinfo->max_h_samp_factor),
  171136. (JDIMENSION) cinfo->max_v_samp_factor);
  171137. }
  171138. }
  171139. }
  171140. /*** End of inlined file: jdsample.c ***/
  171141. /*** Start of inlined file: jdtrans.c ***/
  171142. #define JPEG_INTERNALS
  171143. /* Forward declarations */
  171144. LOCAL(void) transdecode_master_selection JPP((j_decompress_ptr cinfo));
  171145. /*
  171146. * Read the coefficient arrays from a JPEG file.
  171147. * jpeg_read_header must be completed before calling this.
  171148. *
  171149. * The entire image is read into a set of virtual coefficient-block arrays,
  171150. * one per component. The return value is a pointer to the array of
  171151. * virtual-array descriptors. These can be manipulated directly via the
  171152. * JPEG memory manager, or handed off to jpeg_write_coefficients().
  171153. * To release the memory occupied by the virtual arrays, call
  171154. * jpeg_finish_decompress() when done with the data.
  171155. *
  171156. * An alternative usage is to simply obtain access to the coefficient arrays
  171157. * during a buffered-image-mode decompression operation. This is allowed
  171158. * after any jpeg_finish_output() call. The arrays can be accessed until
  171159. * jpeg_finish_decompress() is called. (Note that any call to the library
  171160. * may reposition the arrays, so don't rely on access_virt_barray() results
  171161. * to stay valid across library calls.)
  171162. *
  171163. * Returns NULL if suspended. This case need be checked only if
  171164. * a suspending data source is used.
  171165. */
  171166. GLOBAL(jvirt_barray_ptr *)
  171167. jpeg_read_coefficients (j_decompress_ptr cinfo)
  171168. {
  171169. if (cinfo->global_state == DSTATE_READY) {
  171170. /* First call: initialize active modules */
  171171. transdecode_master_selection(cinfo);
  171172. cinfo->global_state = DSTATE_RDCOEFS;
  171173. }
  171174. if (cinfo->global_state == DSTATE_RDCOEFS) {
  171175. /* Absorb whole file into the coef buffer */
  171176. for (;;) {
  171177. int retcode;
  171178. /* Call progress monitor hook if present */
  171179. if (cinfo->progress != NULL)
  171180. (*cinfo->progress->progress_monitor) ((j_common_ptr) cinfo);
  171181. /* Absorb some more input */
  171182. retcode = (*cinfo->inputctl->consume_input) (cinfo);
  171183. if (retcode == JPEG_SUSPENDED)
  171184. return NULL;
  171185. if (retcode == JPEG_REACHED_EOI)
  171186. break;
  171187. /* Advance progress counter if appropriate */
  171188. if (cinfo->progress != NULL &&
  171189. (retcode == JPEG_ROW_COMPLETED || retcode == JPEG_REACHED_SOS)) {
  171190. if (++cinfo->progress->pass_counter >= cinfo->progress->pass_limit) {
  171191. /* startup underestimated number of scans; ratchet up one scan */
  171192. cinfo->progress->pass_limit += (long) cinfo->total_iMCU_rows;
  171193. }
  171194. }
  171195. }
  171196. /* Set state so that jpeg_finish_decompress does the right thing */
  171197. cinfo->global_state = DSTATE_STOPPING;
  171198. }
  171199. /* At this point we should be in state DSTATE_STOPPING if being used
  171200. * standalone, or in state DSTATE_BUFIMAGE if being invoked to get access
  171201. * to the coefficients during a full buffered-image-mode decompression.
  171202. */
  171203. if ((cinfo->global_state == DSTATE_STOPPING ||
  171204. cinfo->global_state == DSTATE_BUFIMAGE) && cinfo->buffered_image) {
  171205. return cinfo->coef->coef_arrays;
  171206. }
  171207. /* Oops, improper usage */
  171208. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  171209. return NULL; /* keep compiler happy */
  171210. }
  171211. /*
  171212. * Master selection of decompression modules for transcoding.
  171213. * This substitutes for jdmaster.c's initialization of the full decompressor.
  171214. */
  171215. LOCAL(void)
  171216. transdecode_master_selection (j_decompress_ptr cinfo)
  171217. {
  171218. /* This is effectively a buffered-image operation. */
  171219. cinfo->buffered_image = TRUE;
  171220. /* Entropy decoding: either Huffman or arithmetic coding. */
  171221. if (cinfo->arith_code) {
  171222. ERREXIT(cinfo, JERR_ARITH_NOTIMPL);
  171223. } else {
  171224. if (cinfo->progressive_mode) {
  171225. #ifdef D_PROGRESSIVE_SUPPORTED
  171226. jinit_phuff_decoder(cinfo);
  171227. #else
  171228. ERREXIT(cinfo, JERR_NOT_COMPILED);
  171229. #endif
  171230. } else
  171231. jinit_huff_decoder(cinfo);
  171232. }
  171233. /* Always get a full-image coefficient buffer. */
  171234. jinit_d_coef_controller(cinfo, TRUE);
  171235. /* We can now tell the memory manager to allocate virtual arrays. */
  171236. (*cinfo->mem->realize_virt_arrays) ((j_common_ptr) cinfo);
  171237. /* Initialize input side of decompressor to consume first scan. */
  171238. (*cinfo->inputctl->start_input_pass) (cinfo);
  171239. /* Initialize progress monitoring. */
  171240. if (cinfo->progress != NULL) {
  171241. int nscans;
  171242. /* Estimate number of scans to set pass_limit. */
  171243. if (cinfo->progressive_mode) {
  171244. /* Arbitrarily estimate 2 interleaved DC scans + 3 AC scans/component. */
  171245. nscans = 2 + 3 * cinfo->num_components;
  171246. } else if (cinfo->inputctl->has_multiple_scans) {
  171247. /* For a nonprogressive multiscan file, estimate 1 scan per component. */
  171248. nscans = cinfo->num_components;
  171249. } else {
  171250. nscans = 1;
  171251. }
  171252. cinfo->progress->pass_counter = 0L;
  171253. cinfo->progress->pass_limit = (long) cinfo->total_iMCU_rows * nscans;
  171254. cinfo->progress->completed_passes = 0;
  171255. cinfo->progress->total_passes = 1;
  171256. }
  171257. }
  171258. /*** End of inlined file: jdtrans.c ***/
  171259. /*** Start of inlined file: jfdctflt.c ***/
  171260. #define JPEG_INTERNALS
  171261. #ifdef DCT_FLOAT_SUPPORTED
  171262. /*
  171263. * This module is specialized to the case DCTSIZE = 8.
  171264. */
  171265. #if DCTSIZE != 8
  171266. Sorry, this code only copes with 8x8 DCTs. /* deliberate syntax err */
  171267. #endif
  171268. /*
  171269. * Perform the forward DCT on one block of samples.
  171270. */
  171271. GLOBAL(void)
  171272. jpeg_fdct_float (FAST_FLOAT * data)
  171273. {
  171274. FAST_FLOAT tmp0, tmp1, tmp2, tmp3, tmp4, tmp5, tmp6, tmp7;
  171275. FAST_FLOAT tmp10, tmp11, tmp12, tmp13;
  171276. FAST_FLOAT z1, z2, z3, z4, z5, z11, z13;
  171277. FAST_FLOAT *dataptr;
  171278. int ctr;
  171279. /* Pass 1: process rows. */
  171280. dataptr = data;
  171281. for (ctr = DCTSIZE-1; ctr >= 0; ctr--) {
  171282. tmp0 = dataptr[0] + dataptr[7];
  171283. tmp7 = dataptr[0] - dataptr[7];
  171284. tmp1 = dataptr[1] + dataptr[6];
  171285. tmp6 = dataptr[1] - dataptr[6];
  171286. tmp2 = dataptr[2] + dataptr[5];
  171287. tmp5 = dataptr[2] - dataptr[5];
  171288. tmp3 = dataptr[3] + dataptr[4];
  171289. tmp4 = dataptr[3] - dataptr[4];
  171290. /* Even part */
  171291. tmp10 = tmp0 + tmp3; /* phase 2 */
  171292. tmp13 = tmp0 - tmp3;
  171293. tmp11 = tmp1 + tmp2;
  171294. tmp12 = tmp1 - tmp2;
  171295. dataptr[0] = tmp10 + tmp11; /* phase 3 */
  171296. dataptr[4] = tmp10 - tmp11;
  171297. z1 = (tmp12 + tmp13) * ((FAST_FLOAT) 0.707106781); /* c4 */
  171298. dataptr[2] = tmp13 + z1; /* phase 5 */
  171299. dataptr[6] = tmp13 - z1;
  171300. /* Odd part */
  171301. tmp10 = tmp4 + tmp5; /* phase 2 */
  171302. tmp11 = tmp5 + tmp6;
  171303. tmp12 = tmp6 + tmp7;
  171304. /* The rotator is modified from fig 4-8 to avoid extra negations. */
  171305. z5 = (tmp10 - tmp12) * ((FAST_FLOAT) 0.382683433); /* c6 */
  171306. z2 = ((FAST_FLOAT) 0.541196100) * tmp10 + z5; /* c2-c6 */
  171307. z4 = ((FAST_FLOAT) 1.306562965) * tmp12 + z5; /* c2+c6 */
  171308. z3 = tmp11 * ((FAST_FLOAT) 0.707106781); /* c4 */
  171309. z11 = tmp7 + z3; /* phase 5 */
  171310. z13 = tmp7 - z3;
  171311. dataptr[5] = z13 + z2; /* phase 6 */
  171312. dataptr[3] = z13 - z2;
  171313. dataptr[1] = z11 + z4;
  171314. dataptr[7] = z11 - z4;
  171315. dataptr += DCTSIZE; /* advance pointer to next row */
  171316. }
  171317. /* Pass 2: process columns. */
  171318. dataptr = data;
  171319. for (ctr = DCTSIZE-1; ctr >= 0; ctr--) {
  171320. tmp0 = dataptr[DCTSIZE*0] + dataptr[DCTSIZE*7];
  171321. tmp7 = dataptr[DCTSIZE*0] - dataptr[DCTSIZE*7];
  171322. tmp1 = dataptr[DCTSIZE*1] + dataptr[DCTSIZE*6];
  171323. tmp6 = dataptr[DCTSIZE*1] - dataptr[DCTSIZE*6];
  171324. tmp2 = dataptr[DCTSIZE*2] + dataptr[DCTSIZE*5];
  171325. tmp5 = dataptr[DCTSIZE*2] - dataptr[DCTSIZE*5];
  171326. tmp3 = dataptr[DCTSIZE*3] + dataptr[DCTSIZE*4];
  171327. tmp4 = dataptr[DCTSIZE*3] - dataptr[DCTSIZE*4];
  171328. /* Even part */
  171329. tmp10 = tmp0 + tmp3; /* phase 2 */
  171330. tmp13 = tmp0 - tmp3;
  171331. tmp11 = tmp1 + tmp2;
  171332. tmp12 = tmp1 - tmp2;
  171333. dataptr[DCTSIZE*0] = tmp10 + tmp11; /* phase 3 */
  171334. dataptr[DCTSIZE*4] = tmp10 - tmp11;
  171335. z1 = (tmp12 + tmp13) * ((FAST_FLOAT) 0.707106781); /* c4 */
  171336. dataptr[DCTSIZE*2] = tmp13 + z1; /* phase 5 */
  171337. dataptr[DCTSIZE*6] = tmp13 - z1;
  171338. /* Odd part */
  171339. tmp10 = tmp4 + tmp5; /* phase 2 */
  171340. tmp11 = tmp5 + tmp6;
  171341. tmp12 = tmp6 + tmp7;
  171342. /* The rotator is modified from fig 4-8 to avoid extra negations. */
  171343. z5 = (tmp10 - tmp12) * ((FAST_FLOAT) 0.382683433); /* c6 */
  171344. z2 = ((FAST_FLOAT) 0.541196100) * tmp10 + z5; /* c2-c6 */
  171345. z4 = ((FAST_FLOAT) 1.306562965) * tmp12 + z5; /* c2+c6 */
  171346. z3 = tmp11 * ((FAST_FLOAT) 0.707106781); /* c4 */
  171347. z11 = tmp7 + z3; /* phase 5 */
  171348. z13 = tmp7 - z3;
  171349. dataptr[DCTSIZE*5] = z13 + z2; /* phase 6 */
  171350. dataptr[DCTSIZE*3] = z13 - z2;
  171351. dataptr[DCTSIZE*1] = z11 + z4;
  171352. dataptr[DCTSIZE*7] = z11 - z4;
  171353. dataptr++; /* advance pointer to next column */
  171354. }
  171355. }
  171356. #endif /* DCT_FLOAT_SUPPORTED */
  171357. /*** End of inlined file: jfdctflt.c ***/
  171358. /*** Start of inlined file: jfdctint.c ***/
  171359. #define JPEG_INTERNALS
  171360. #ifdef DCT_ISLOW_SUPPORTED
  171361. /*
  171362. * This module is specialized to the case DCTSIZE = 8.
  171363. */
  171364. #if DCTSIZE != 8
  171365. Sorry, this code only copes with 8x8 DCTs. /* deliberate syntax err */
  171366. #endif
  171367. /*
  171368. * The poop on this scaling stuff is as follows:
  171369. *
  171370. * Each 1-D DCT step produces outputs which are a factor of sqrt(N)
  171371. * larger than the true DCT outputs. The final outputs are therefore
  171372. * a factor of N larger than desired; since N=8 this can be cured by
  171373. * a simple right shift at the end of the algorithm. The advantage of
  171374. * this arrangement is that we save two multiplications per 1-D DCT,
  171375. * because the y0 and y4 outputs need not be divided by sqrt(N).
  171376. * In the IJG code, this factor of 8 is removed by the quantization step
  171377. * (in jcdctmgr.c), NOT in this module.
  171378. *
  171379. * We have to do addition and subtraction of the integer inputs, which
  171380. * is no problem, and multiplication by fractional constants, which is
  171381. * a problem to do in integer arithmetic. We multiply all the constants
  171382. * by CONST_SCALE and convert them to integer constants (thus retaining
  171383. * CONST_BITS bits of precision in the constants). After doing a
  171384. * multiplication we have to divide the product by CONST_SCALE, with proper
  171385. * rounding, to produce the correct output. This division can be done
  171386. * cheaply as a right shift of CONST_BITS bits. We postpone shifting
  171387. * as long as possible so that partial sums can be added together with
  171388. * full fractional precision.
  171389. *
  171390. * The outputs of the first pass are scaled up by PASS1_BITS bits so that
  171391. * they are represented to better-than-integral precision. These outputs
  171392. * require BITS_IN_JSAMPLE + PASS1_BITS + 3 bits; this fits in a 16-bit word
  171393. * with the recommended scaling. (For 12-bit sample data, the intermediate
  171394. * array is INT32 anyway.)
  171395. *
  171396. * To avoid overflow of the 32-bit intermediate results in pass 2, we must
  171397. * have BITS_IN_JSAMPLE + CONST_BITS + PASS1_BITS <= 26. Error analysis
  171398. * shows that the values given below are the most effective.
  171399. */
  171400. #if BITS_IN_JSAMPLE == 8
  171401. #define CONST_BITS 13
  171402. #define PASS1_BITS 2
  171403. #else
  171404. #define CONST_BITS 13
  171405. #define PASS1_BITS 1 /* lose a little precision to avoid overflow */
  171406. #endif
  171407. /* Some C compilers fail to reduce "FIX(constant)" at compile time, thus
  171408. * causing a lot of useless floating-point operations at run time.
  171409. * To get around this we use the following pre-calculated constants.
  171410. * If you change CONST_BITS you may want to add appropriate values.
  171411. * (With a reasonable C compiler, you can just rely on the FIX() macro...)
  171412. */
  171413. #if CONST_BITS == 13
  171414. #define FIX_0_298631336 ((INT32) 2446) /* FIX(0.298631336) */
  171415. #define FIX_0_390180644 ((INT32) 3196) /* FIX(0.390180644) */
  171416. #define FIX_0_541196100 ((INT32) 4433) /* FIX(0.541196100) */
  171417. #define FIX_0_765366865 ((INT32) 6270) /* FIX(0.765366865) */
  171418. #define FIX_0_899976223 ((INT32) 7373) /* FIX(0.899976223) */
  171419. #define FIX_1_175875602 ((INT32) 9633) /* FIX(1.175875602) */
  171420. #define FIX_1_501321110 ((INT32) 12299) /* FIX(1.501321110) */
  171421. #define FIX_1_847759065 ((INT32) 15137) /* FIX(1.847759065) */
  171422. #define FIX_1_961570560 ((INT32) 16069) /* FIX(1.961570560) */
  171423. #define FIX_2_053119869 ((INT32) 16819) /* FIX(2.053119869) */
  171424. #define FIX_2_562915447 ((INT32) 20995) /* FIX(2.562915447) */
  171425. #define FIX_3_072711026 ((INT32) 25172) /* FIX(3.072711026) */
  171426. #else
  171427. #define FIX_0_298631336 FIX(0.298631336)
  171428. #define FIX_0_390180644 FIX(0.390180644)
  171429. #define FIX_0_541196100 FIX(0.541196100)
  171430. #define FIX_0_765366865 FIX(0.765366865)
  171431. #define FIX_0_899976223 FIX(0.899976223)
  171432. #define FIX_1_175875602 FIX(1.175875602)
  171433. #define FIX_1_501321110 FIX(1.501321110)
  171434. #define FIX_1_847759065 FIX(1.847759065)
  171435. #define FIX_1_961570560 FIX(1.961570560)
  171436. #define FIX_2_053119869 FIX(2.053119869)
  171437. #define FIX_2_562915447 FIX(2.562915447)
  171438. #define FIX_3_072711026 FIX(3.072711026)
  171439. #endif
  171440. /* Multiply an INT32 variable by an INT32 constant to yield an INT32 result.
  171441. * For 8-bit samples with the recommended scaling, all the variable
  171442. * and constant values involved are no more than 16 bits wide, so a
  171443. * 16x16->32 bit multiply can be used instead of a full 32x32 multiply.
  171444. * For 12-bit samples, a full 32-bit multiplication will be needed.
  171445. */
  171446. #if BITS_IN_JSAMPLE == 8
  171447. #define MULTIPLY(var,const) MULTIPLY16C16(var,const)
  171448. #else
  171449. #define MULTIPLY(var,const) ((var) * (const))
  171450. #endif
  171451. /*
  171452. * Perform the forward DCT on one block of samples.
  171453. */
  171454. GLOBAL(void)
  171455. jpeg_fdct_islow (DCTELEM * data)
  171456. {
  171457. INT32 tmp0, tmp1, tmp2, tmp3, tmp4, tmp5, tmp6, tmp7;
  171458. INT32 tmp10, tmp11, tmp12, tmp13;
  171459. INT32 z1, z2, z3, z4, z5;
  171460. DCTELEM *dataptr;
  171461. int ctr;
  171462. SHIFT_TEMPS
  171463. /* Pass 1: process rows. */
  171464. /* Note results are scaled up by sqrt(8) compared to a true DCT; */
  171465. /* furthermore, we scale the results by 2**PASS1_BITS. */
  171466. dataptr = data;
  171467. for (ctr = DCTSIZE-1; ctr >= 0; ctr--) {
  171468. tmp0 = dataptr[0] + dataptr[7];
  171469. tmp7 = dataptr[0] - dataptr[7];
  171470. tmp1 = dataptr[1] + dataptr[6];
  171471. tmp6 = dataptr[1] - dataptr[6];
  171472. tmp2 = dataptr[2] + dataptr[5];
  171473. tmp5 = dataptr[2] - dataptr[5];
  171474. tmp3 = dataptr[3] + dataptr[4];
  171475. tmp4 = dataptr[3] - dataptr[4];
  171476. /* Even part per LL&M figure 1 --- note that published figure is faulty;
  171477. * rotator "sqrt(2)*c1" should be "sqrt(2)*c6".
  171478. */
  171479. tmp10 = tmp0 + tmp3;
  171480. tmp13 = tmp0 - tmp3;
  171481. tmp11 = tmp1 + tmp2;
  171482. tmp12 = tmp1 - tmp2;
  171483. dataptr[0] = (DCTELEM) ((tmp10 + tmp11) << PASS1_BITS);
  171484. dataptr[4] = (DCTELEM) ((tmp10 - tmp11) << PASS1_BITS);
  171485. z1 = MULTIPLY(tmp12 + tmp13, FIX_0_541196100);
  171486. dataptr[2] = (DCTELEM) DESCALE(z1 + MULTIPLY(tmp13, FIX_0_765366865),
  171487. CONST_BITS-PASS1_BITS);
  171488. dataptr[6] = (DCTELEM) DESCALE(z1 + MULTIPLY(tmp12, - FIX_1_847759065),
  171489. CONST_BITS-PASS1_BITS);
  171490. /* Odd part per figure 8 --- note paper omits factor of sqrt(2).
  171491. * cK represents cos(K*pi/16).
  171492. * i0..i3 in the paper are tmp4..tmp7 here.
  171493. */
  171494. z1 = tmp4 + tmp7;
  171495. z2 = tmp5 + tmp6;
  171496. z3 = tmp4 + tmp6;
  171497. z4 = tmp5 + tmp7;
  171498. z5 = MULTIPLY(z3 + z4, FIX_1_175875602); /* sqrt(2) * c3 */
  171499. tmp4 = MULTIPLY(tmp4, FIX_0_298631336); /* sqrt(2) * (-c1+c3+c5-c7) */
  171500. tmp5 = MULTIPLY(tmp5, FIX_2_053119869); /* sqrt(2) * ( c1+c3-c5+c7) */
  171501. tmp6 = MULTIPLY(tmp6, FIX_3_072711026); /* sqrt(2) * ( c1+c3+c5-c7) */
  171502. tmp7 = MULTIPLY(tmp7, FIX_1_501321110); /* sqrt(2) * ( c1+c3-c5-c7) */
  171503. z1 = MULTIPLY(z1, - FIX_0_899976223); /* sqrt(2) * (c7-c3) */
  171504. z2 = MULTIPLY(z2, - FIX_2_562915447); /* sqrt(2) * (-c1-c3) */
  171505. z3 = MULTIPLY(z3, - FIX_1_961570560); /* sqrt(2) * (-c3-c5) */
  171506. z4 = MULTIPLY(z4, - FIX_0_390180644); /* sqrt(2) * (c5-c3) */
  171507. z3 += z5;
  171508. z4 += z5;
  171509. dataptr[7] = (DCTELEM) DESCALE(tmp4 + z1 + z3, CONST_BITS-PASS1_BITS);
  171510. dataptr[5] = (DCTELEM) DESCALE(tmp5 + z2 + z4, CONST_BITS-PASS1_BITS);
  171511. dataptr[3] = (DCTELEM) DESCALE(tmp6 + z2 + z3, CONST_BITS-PASS1_BITS);
  171512. dataptr[1] = (DCTELEM) DESCALE(tmp7 + z1 + z4, CONST_BITS-PASS1_BITS);
  171513. dataptr += DCTSIZE; /* advance pointer to next row */
  171514. }
  171515. /* Pass 2: process columns.
  171516. * We remove the PASS1_BITS scaling, but leave the results scaled up
  171517. * by an overall factor of 8.
  171518. */
  171519. dataptr = data;
  171520. for (ctr = DCTSIZE-1; ctr >= 0; ctr--) {
  171521. tmp0 = dataptr[DCTSIZE*0] + dataptr[DCTSIZE*7];
  171522. tmp7 = dataptr[DCTSIZE*0] - dataptr[DCTSIZE*7];
  171523. tmp1 = dataptr[DCTSIZE*1] + dataptr[DCTSIZE*6];
  171524. tmp6 = dataptr[DCTSIZE*1] - dataptr[DCTSIZE*6];
  171525. tmp2 = dataptr[DCTSIZE*2] + dataptr[DCTSIZE*5];
  171526. tmp5 = dataptr[DCTSIZE*2] - dataptr[DCTSIZE*5];
  171527. tmp3 = dataptr[DCTSIZE*3] + dataptr[DCTSIZE*4];
  171528. tmp4 = dataptr[DCTSIZE*3] - dataptr[DCTSIZE*4];
  171529. /* Even part per LL&M figure 1 --- note that published figure is faulty;
  171530. * rotator "sqrt(2)*c1" should be "sqrt(2)*c6".
  171531. */
  171532. tmp10 = tmp0 + tmp3;
  171533. tmp13 = tmp0 - tmp3;
  171534. tmp11 = tmp1 + tmp2;
  171535. tmp12 = tmp1 - tmp2;
  171536. dataptr[DCTSIZE*0] = (DCTELEM) DESCALE(tmp10 + tmp11, PASS1_BITS);
  171537. dataptr[DCTSIZE*4] = (DCTELEM) DESCALE(tmp10 - tmp11, PASS1_BITS);
  171538. z1 = MULTIPLY(tmp12 + tmp13, FIX_0_541196100);
  171539. dataptr[DCTSIZE*2] = (DCTELEM) DESCALE(z1 + MULTIPLY(tmp13, FIX_0_765366865),
  171540. CONST_BITS+PASS1_BITS);
  171541. dataptr[DCTSIZE*6] = (DCTELEM) DESCALE(z1 + MULTIPLY(tmp12, - FIX_1_847759065),
  171542. CONST_BITS+PASS1_BITS);
  171543. /* Odd part per figure 8 --- note paper omits factor of sqrt(2).
  171544. * cK represents cos(K*pi/16).
  171545. * i0..i3 in the paper are tmp4..tmp7 here.
  171546. */
  171547. z1 = tmp4 + tmp7;
  171548. z2 = tmp5 + tmp6;
  171549. z3 = tmp4 + tmp6;
  171550. z4 = tmp5 + tmp7;
  171551. z5 = MULTIPLY(z3 + z4, FIX_1_175875602); /* sqrt(2) * c3 */
  171552. tmp4 = MULTIPLY(tmp4, FIX_0_298631336); /* sqrt(2) * (-c1+c3+c5-c7) */
  171553. tmp5 = MULTIPLY(tmp5, FIX_2_053119869); /* sqrt(2) * ( c1+c3-c5+c7) */
  171554. tmp6 = MULTIPLY(tmp6, FIX_3_072711026); /* sqrt(2) * ( c1+c3+c5-c7) */
  171555. tmp7 = MULTIPLY(tmp7, FIX_1_501321110); /* sqrt(2) * ( c1+c3-c5-c7) */
  171556. z1 = MULTIPLY(z1, - FIX_0_899976223); /* sqrt(2) * (c7-c3) */
  171557. z2 = MULTIPLY(z2, - FIX_2_562915447); /* sqrt(2) * (-c1-c3) */
  171558. z3 = MULTIPLY(z3, - FIX_1_961570560); /* sqrt(2) * (-c3-c5) */
  171559. z4 = MULTIPLY(z4, - FIX_0_390180644); /* sqrt(2) * (c5-c3) */
  171560. z3 += z5;
  171561. z4 += z5;
  171562. dataptr[DCTSIZE*7] = (DCTELEM) DESCALE(tmp4 + z1 + z3,
  171563. CONST_BITS+PASS1_BITS);
  171564. dataptr[DCTSIZE*5] = (DCTELEM) DESCALE(tmp5 + z2 + z4,
  171565. CONST_BITS+PASS1_BITS);
  171566. dataptr[DCTSIZE*3] = (DCTELEM) DESCALE(tmp6 + z2 + z3,
  171567. CONST_BITS+PASS1_BITS);
  171568. dataptr[DCTSIZE*1] = (DCTELEM) DESCALE(tmp7 + z1 + z4,
  171569. CONST_BITS+PASS1_BITS);
  171570. dataptr++; /* advance pointer to next column */
  171571. }
  171572. }
  171573. #endif /* DCT_ISLOW_SUPPORTED */
  171574. /*** End of inlined file: jfdctint.c ***/
  171575. #undef CONST_BITS
  171576. #undef MULTIPLY
  171577. #undef FIX_0_541196100
  171578. /*** Start of inlined file: jfdctfst.c ***/
  171579. #define JPEG_INTERNALS
  171580. #ifdef DCT_IFAST_SUPPORTED
  171581. /*
  171582. * This module is specialized to the case DCTSIZE = 8.
  171583. */
  171584. #if DCTSIZE != 8
  171585. Sorry, this code only copes with 8x8 DCTs. /* deliberate syntax err */
  171586. #endif
  171587. /* Scaling decisions are generally the same as in the LL&M algorithm;
  171588. * see jfdctint.c for more details. However, we choose to descale
  171589. * (right shift) multiplication products as soon as they are formed,
  171590. * rather than carrying additional fractional bits into subsequent additions.
  171591. * This compromises accuracy slightly, but it lets us save a few shifts.
  171592. * More importantly, 16-bit arithmetic is then adequate (for 8-bit samples)
  171593. * everywhere except in the multiplications proper; this saves a good deal
  171594. * of work on 16-bit-int machines.
  171595. *
  171596. * Again to save a few shifts, the intermediate results between pass 1 and
  171597. * pass 2 are not upscaled, but are represented only to integral precision.
  171598. *
  171599. * A final compromise is to represent the multiplicative constants to only
  171600. * 8 fractional bits, rather than 13. This saves some shifting work on some
  171601. * machines, and may also reduce the cost of multiplication (since there
  171602. * are fewer one-bits in the constants).
  171603. */
  171604. #define CONST_BITS 8
  171605. /* Some C compilers fail to reduce "FIX(constant)" at compile time, thus
  171606. * causing a lot of useless floating-point operations at run time.
  171607. * To get around this we use the following pre-calculated constants.
  171608. * If you change CONST_BITS you may want to add appropriate values.
  171609. * (With a reasonable C compiler, you can just rely on the FIX() macro...)
  171610. */
  171611. #if CONST_BITS == 8
  171612. #define FIX_0_382683433 ((INT32) 98) /* FIX(0.382683433) */
  171613. #define FIX_0_541196100 ((INT32) 139) /* FIX(0.541196100) */
  171614. #define FIX_0_707106781 ((INT32) 181) /* FIX(0.707106781) */
  171615. #define FIX_1_306562965 ((INT32) 334) /* FIX(1.306562965) */
  171616. #else
  171617. #define FIX_0_382683433 FIX(0.382683433)
  171618. #define FIX_0_541196100 FIX(0.541196100)
  171619. #define FIX_0_707106781 FIX(0.707106781)
  171620. #define FIX_1_306562965 FIX(1.306562965)
  171621. #endif
  171622. /* We can gain a little more speed, with a further compromise in accuracy,
  171623. * by omitting the addition in a descaling shift. This yields an incorrectly
  171624. * rounded result half the time...
  171625. */
  171626. #ifndef USE_ACCURATE_ROUNDING
  171627. #undef DESCALE
  171628. #define DESCALE(x,n) RIGHT_SHIFT(x, n)
  171629. #endif
  171630. /* Multiply a DCTELEM variable by an INT32 constant, and immediately
  171631. * descale to yield a DCTELEM result.
  171632. */
  171633. #define MULTIPLY(var,const) ((DCTELEM) DESCALE((var) * (const), CONST_BITS))
  171634. /*
  171635. * Perform the forward DCT on one block of samples.
  171636. */
  171637. GLOBAL(void)
  171638. jpeg_fdct_ifast (DCTELEM * data)
  171639. {
  171640. DCTELEM tmp0, tmp1, tmp2, tmp3, tmp4, tmp5, tmp6, tmp7;
  171641. DCTELEM tmp10, tmp11, tmp12, tmp13;
  171642. DCTELEM z1, z2, z3, z4, z5, z11, z13;
  171643. DCTELEM *dataptr;
  171644. int ctr;
  171645. SHIFT_TEMPS
  171646. /* Pass 1: process rows. */
  171647. dataptr = data;
  171648. for (ctr = DCTSIZE-1; ctr >= 0; ctr--) {
  171649. tmp0 = dataptr[0] + dataptr[7];
  171650. tmp7 = dataptr[0] - dataptr[7];
  171651. tmp1 = dataptr[1] + dataptr[6];
  171652. tmp6 = dataptr[1] - dataptr[6];
  171653. tmp2 = dataptr[2] + dataptr[5];
  171654. tmp5 = dataptr[2] - dataptr[5];
  171655. tmp3 = dataptr[3] + dataptr[4];
  171656. tmp4 = dataptr[3] - dataptr[4];
  171657. /* Even part */
  171658. tmp10 = tmp0 + tmp3; /* phase 2 */
  171659. tmp13 = tmp0 - tmp3;
  171660. tmp11 = tmp1 + tmp2;
  171661. tmp12 = tmp1 - tmp2;
  171662. dataptr[0] = tmp10 + tmp11; /* phase 3 */
  171663. dataptr[4] = tmp10 - tmp11;
  171664. z1 = MULTIPLY(tmp12 + tmp13, FIX_0_707106781); /* c4 */
  171665. dataptr[2] = tmp13 + z1; /* phase 5 */
  171666. dataptr[6] = tmp13 - z1;
  171667. /* Odd part */
  171668. tmp10 = tmp4 + tmp5; /* phase 2 */
  171669. tmp11 = tmp5 + tmp6;
  171670. tmp12 = tmp6 + tmp7;
  171671. /* The rotator is modified from fig 4-8 to avoid extra negations. */
  171672. z5 = MULTIPLY(tmp10 - tmp12, FIX_0_382683433); /* c6 */
  171673. z2 = MULTIPLY(tmp10, FIX_0_541196100) + z5; /* c2-c6 */
  171674. z4 = MULTIPLY(tmp12, FIX_1_306562965) + z5; /* c2+c6 */
  171675. z3 = MULTIPLY(tmp11, FIX_0_707106781); /* c4 */
  171676. z11 = tmp7 + z3; /* phase 5 */
  171677. z13 = tmp7 - z3;
  171678. dataptr[5] = z13 + z2; /* phase 6 */
  171679. dataptr[3] = z13 - z2;
  171680. dataptr[1] = z11 + z4;
  171681. dataptr[7] = z11 - z4;
  171682. dataptr += DCTSIZE; /* advance pointer to next row */
  171683. }
  171684. /* Pass 2: process columns. */
  171685. dataptr = data;
  171686. for (ctr = DCTSIZE-1; ctr >= 0; ctr--) {
  171687. tmp0 = dataptr[DCTSIZE*0] + dataptr[DCTSIZE*7];
  171688. tmp7 = dataptr[DCTSIZE*0] - dataptr[DCTSIZE*7];
  171689. tmp1 = dataptr[DCTSIZE*1] + dataptr[DCTSIZE*6];
  171690. tmp6 = dataptr[DCTSIZE*1] - dataptr[DCTSIZE*6];
  171691. tmp2 = dataptr[DCTSIZE*2] + dataptr[DCTSIZE*5];
  171692. tmp5 = dataptr[DCTSIZE*2] - dataptr[DCTSIZE*5];
  171693. tmp3 = dataptr[DCTSIZE*3] + dataptr[DCTSIZE*4];
  171694. tmp4 = dataptr[DCTSIZE*3] - dataptr[DCTSIZE*4];
  171695. /* Even part */
  171696. tmp10 = tmp0 + tmp3; /* phase 2 */
  171697. tmp13 = tmp0 - tmp3;
  171698. tmp11 = tmp1 + tmp2;
  171699. tmp12 = tmp1 - tmp2;
  171700. dataptr[DCTSIZE*0] = tmp10 + tmp11; /* phase 3 */
  171701. dataptr[DCTSIZE*4] = tmp10 - tmp11;
  171702. z1 = MULTIPLY(tmp12 + tmp13, FIX_0_707106781); /* c4 */
  171703. dataptr[DCTSIZE*2] = tmp13 + z1; /* phase 5 */
  171704. dataptr[DCTSIZE*6] = tmp13 - z1;
  171705. /* Odd part */
  171706. tmp10 = tmp4 + tmp5; /* phase 2 */
  171707. tmp11 = tmp5 + tmp6;
  171708. tmp12 = tmp6 + tmp7;
  171709. /* The rotator is modified from fig 4-8 to avoid extra negations. */
  171710. z5 = MULTIPLY(tmp10 - tmp12, FIX_0_382683433); /* c6 */
  171711. z2 = MULTIPLY(tmp10, FIX_0_541196100) + z5; /* c2-c6 */
  171712. z4 = MULTIPLY(tmp12, FIX_1_306562965) + z5; /* c2+c6 */
  171713. z3 = MULTIPLY(tmp11, FIX_0_707106781); /* c4 */
  171714. z11 = tmp7 + z3; /* phase 5 */
  171715. z13 = tmp7 - z3;
  171716. dataptr[DCTSIZE*5] = z13 + z2; /* phase 6 */
  171717. dataptr[DCTSIZE*3] = z13 - z2;
  171718. dataptr[DCTSIZE*1] = z11 + z4;
  171719. dataptr[DCTSIZE*7] = z11 - z4;
  171720. dataptr++; /* advance pointer to next column */
  171721. }
  171722. }
  171723. #endif /* DCT_IFAST_SUPPORTED */
  171724. /*** End of inlined file: jfdctfst.c ***/
  171725. #undef FIX_0_541196100
  171726. /*** Start of inlined file: jidctflt.c ***/
  171727. #define JPEG_INTERNALS
  171728. #ifdef DCT_FLOAT_SUPPORTED
  171729. /*
  171730. * This module is specialized to the case DCTSIZE = 8.
  171731. */
  171732. #if DCTSIZE != 8
  171733. Sorry, this code only copes with 8x8 DCTs. /* deliberate syntax err */
  171734. #endif
  171735. /* Dequantize a coefficient by multiplying it by the multiplier-table
  171736. * entry; produce a float result.
  171737. */
  171738. #define DEQUANTIZE(coef,quantval) (((FAST_FLOAT) (coef)) * (quantval))
  171739. /*
  171740. * Perform dequantization and inverse DCT on one block of coefficients.
  171741. */
  171742. GLOBAL(void)
  171743. jpeg_idct_float (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  171744. JCOEFPTR coef_block,
  171745. JSAMPARRAY output_buf, JDIMENSION output_col)
  171746. {
  171747. FAST_FLOAT tmp0, tmp1, tmp2, tmp3, tmp4, tmp5, tmp6, tmp7;
  171748. FAST_FLOAT tmp10, tmp11, tmp12, tmp13;
  171749. FAST_FLOAT z5, z10, z11, z12, z13;
  171750. JCOEFPTR inptr;
  171751. FLOAT_MULT_TYPE * quantptr;
  171752. FAST_FLOAT * wsptr;
  171753. JSAMPROW outptr;
  171754. JSAMPLE *range_limit = IDCT_range_limit(cinfo);
  171755. int ctr;
  171756. FAST_FLOAT workspace[DCTSIZE2]; /* buffers data between passes */
  171757. SHIFT_TEMPS
  171758. /* Pass 1: process columns from input, store into work array. */
  171759. inptr = coef_block;
  171760. quantptr = (FLOAT_MULT_TYPE *) compptr->dct_table;
  171761. wsptr = workspace;
  171762. for (ctr = DCTSIZE; ctr > 0; ctr--) {
  171763. /* Due to quantization, we will usually find that many of the input
  171764. * coefficients are zero, especially the AC terms. We can exploit this
  171765. * by short-circuiting the IDCT calculation for any column in which all
  171766. * the AC terms are zero. In that case each output is equal to the
  171767. * DC coefficient (with scale factor as needed).
  171768. * With typical images and quantization tables, half or more of the
  171769. * column DCT calculations can be simplified this way.
  171770. */
  171771. if (inptr[DCTSIZE*1] == 0 && inptr[DCTSIZE*2] == 0 &&
  171772. inptr[DCTSIZE*3] == 0 && inptr[DCTSIZE*4] == 0 &&
  171773. inptr[DCTSIZE*5] == 0 && inptr[DCTSIZE*6] == 0 &&
  171774. inptr[DCTSIZE*7] == 0) {
  171775. /* AC terms all zero */
  171776. FAST_FLOAT dcval = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]);
  171777. wsptr[DCTSIZE*0] = dcval;
  171778. wsptr[DCTSIZE*1] = dcval;
  171779. wsptr[DCTSIZE*2] = dcval;
  171780. wsptr[DCTSIZE*3] = dcval;
  171781. wsptr[DCTSIZE*4] = dcval;
  171782. wsptr[DCTSIZE*5] = dcval;
  171783. wsptr[DCTSIZE*6] = dcval;
  171784. wsptr[DCTSIZE*7] = dcval;
  171785. inptr++; /* advance pointers to next column */
  171786. quantptr++;
  171787. wsptr++;
  171788. continue;
  171789. }
  171790. /* Even part */
  171791. tmp0 = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]);
  171792. tmp1 = DEQUANTIZE(inptr[DCTSIZE*2], quantptr[DCTSIZE*2]);
  171793. tmp2 = DEQUANTIZE(inptr[DCTSIZE*4], quantptr[DCTSIZE*4]);
  171794. tmp3 = DEQUANTIZE(inptr[DCTSIZE*6], quantptr[DCTSIZE*6]);
  171795. tmp10 = tmp0 + tmp2; /* phase 3 */
  171796. tmp11 = tmp0 - tmp2;
  171797. tmp13 = tmp1 + tmp3; /* phases 5-3 */
  171798. tmp12 = (tmp1 - tmp3) * ((FAST_FLOAT) 1.414213562) - tmp13; /* 2*c4 */
  171799. tmp0 = tmp10 + tmp13; /* phase 2 */
  171800. tmp3 = tmp10 - tmp13;
  171801. tmp1 = tmp11 + tmp12;
  171802. tmp2 = tmp11 - tmp12;
  171803. /* Odd part */
  171804. tmp4 = DEQUANTIZE(inptr[DCTSIZE*1], quantptr[DCTSIZE*1]);
  171805. tmp5 = DEQUANTIZE(inptr[DCTSIZE*3], quantptr[DCTSIZE*3]);
  171806. tmp6 = DEQUANTIZE(inptr[DCTSIZE*5], quantptr[DCTSIZE*5]);
  171807. tmp7 = DEQUANTIZE(inptr[DCTSIZE*7], quantptr[DCTSIZE*7]);
  171808. z13 = tmp6 + tmp5; /* phase 6 */
  171809. z10 = tmp6 - tmp5;
  171810. z11 = tmp4 + tmp7;
  171811. z12 = tmp4 - tmp7;
  171812. tmp7 = z11 + z13; /* phase 5 */
  171813. tmp11 = (z11 - z13) * ((FAST_FLOAT) 1.414213562); /* 2*c4 */
  171814. z5 = (z10 + z12) * ((FAST_FLOAT) 1.847759065); /* 2*c2 */
  171815. tmp10 = ((FAST_FLOAT) 1.082392200) * z12 - z5; /* 2*(c2-c6) */
  171816. tmp12 = ((FAST_FLOAT) -2.613125930) * z10 + z5; /* -2*(c2+c6) */
  171817. tmp6 = tmp12 - tmp7; /* phase 2 */
  171818. tmp5 = tmp11 - tmp6;
  171819. tmp4 = tmp10 + tmp5;
  171820. wsptr[DCTSIZE*0] = tmp0 + tmp7;
  171821. wsptr[DCTSIZE*7] = tmp0 - tmp7;
  171822. wsptr[DCTSIZE*1] = tmp1 + tmp6;
  171823. wsptr[DCTSIZE*6] = tmp1 - tmp6;
  171824. wsptr[DCTSIZE*2] = tmp2 + tmp5;
  171825. wsptr[DCTSIZE*5] = tmp2 - tmp5;
  171826. wsptr[DCTSIZE*4] = tmp3 + tmp4;
  171827. wsptr[DCTSIZE*3] = tmp3 - tmp4;
  171828. inptr++; /* advance pointers to next column */
  171829. quantptr++;
  171830. wsptr++;
  171831. }
  171832. /* Pass 2: process rows from work array, store into output array. */
  171833. /* Note that we must descale the results by a factor of 8 == 2**3. */
  171834. wsptr = workspace;
  171835. for (ctr = 0; ctr < DCTSIZE; ctr++) {
  171836. outptr = output_buf[ctr] + output_col;
  171837. /* Rows of zeroes can be exploited in the same way as we did with columns.
  171838. * However, the column calculation has created many nonzero AC terms, so
  171839. * the simplification applies less often (typically 5% to 10% of the time).
  171840. * And testing floats for zero is relatively expensive, so we don't bother.
  171841. */
  171842. /* Even part */
  171843. tmp10 = wsptr[0] + wsptr[4];
  171844. tmp11 = wsptr[0] - wsptr[4];
  171845. tmp13 = wsptr[2] + wsptr[6];
  171846. tmp12 = (wsptr[2] - wsptr[6]) * ((FAST_FLOAT) 1.414213562) - tmp13;
  171847. tmp0 = tmp10 + tmp13;
  171848. tmp3 = tmp10 - tmp13;
  171849. tmp1 = tmp11 + tmp12;
  171850. tmp2 = tmp11 - tmp12;
  171851. /* Odd part */
  171852. z13 = wsptr[5] + wsptr[3];
  171853. z10 = wsptr[5] - wsptr[3];
  171854. z11 = wsptr[1] + wsptr[7];
  171855. z12 = wsptr[1] - wsptr[7];
  171856. tmp7 = z11 + z13;
  171857. tmp11 = (z11 - z13) * ((FAST_FLOAT) 1.414213562);
  171858. z5 = (z10 + z12) * ((FAST_FLOAT) 1.847759065); /* 2*c2 */
  171859. tmp10 = ((FAST_FLOAT) 1.082392200) * z12 - z5; /* 2*(c2-c6) */
  171860. tmp12 = ((FAST_FLOAT) -2.613125930) * z10 + z5; /* -2*(c2+c6) */
  171861. tmp6 = tmp12 - tmp7;
  171862. tmp5 = tmp11 - tmp6;
  171863. tmp4 = tmp10 + tmp5;
  171864. /* Final output stage: scale down by a factor of 8 and range-limit */
  171865. outptr[0] = range_limit[(int) DESCALE((INT32) (tmp0 + tmp7), 3)
  171866. & RANGE_MASK];
  171867. outptr[7] = range_limit[(int) DESCALE((INT32) (tmp0 - tmp7), 3)
  171868. & RANGE_MASK];
  171869. outptr[1] = range_limit[(int) DESCALE((INT32) (tmp1 + tmp6), 3)
  171870. & RANGE_MASK];
  171871. outptr[6] = range_limit[(int) DESCALE((INT32) (tmp1 - tmp6), 3)
  171872. & RANGE_MASK];
  171873. outptr[2] = range_limit[(int) DESCALE((INT32) (tmp2 + tmp5), 3)
  171874. & RANGE_MASK];
  171875. outptr[5] = range_limit[(int) DESCALE((INT32) (tmp2 - tmp5), 3)
  171876. & RANGE_MASK];
  171877. outptr[4] = range_limit[(int) DESCALE((INT32) (tmp3 + tmp4), 3)
  171878. & RANGE_MASK];
  171879. outptr[3] = range_limit[(int) DESCALE((INT32) (tmp3 - tmp4), 3)
  171880. & RANGE_MASK];
  171881. wsptr += DCTSIZE; /* advance pointer to next row */
  171882. }
  171883. }
  171884. #endif /* DCT_FLOAT_SUPPORTED */
  171885. /*** End of inlined file: jidctflt.c ***/
  171886. #undef CONST_BITS
  171887. #undef FIX_1_847759065
  171888. #undef MULTIPLY
  171889. #undef DEQUANTIZE
  171890. #undef DESCALE
  171891. /*** Start of inlined file: jidctfst.c ***/
  171892. #define JPEG_INTERNALS
  171893. #ifdef DCT_IFAST_SUPPORTED
  171894. /*
  171895. * This module is specialized to the case DCTSIZE = 8.
  171896. */
  171897. #if DCTSIZE != 8
  171898. Sorry, this code only copes with 8x8 DCTs. /* deliberate syntax err */
  171899. #endif
  171900. /* Scaling decisions are generally the same as in the LL&M algorithm;
  171901. * see jidctint.c for more details. However, we choose to descale
  171902. * (right shift) multiplication products as soon as they are formed,
  171903. * rather than carrying additional fractional bits into subsequent additions.
  171904. * This compromises accuracy slightly, but it lets us save a few shifts.
  171905. * More importantly, 16-bit arithmetic is then adequate (for 8-bit samples)
  171906. * everywhere except in the multiplications proper; this saves a good deal
  171907. * of work on 16-bit-int machines.
  171908. *
  171909. * The dequantized coefficients are not integers because the AA&N scaling
  171910. * factors have been incorporated. We represent them scaled up by PASS1_BITS,
  171911. * so that the first and second IDCT rounds have the same input scaling.
  171912. * For 8-bit JSAMPLEs, we choose IFAST_SCALE_BITS = PASS1_BITS so as to
  171913. * avoid a descaling shift; this compromises accuracy rather drastically
  171914. * for small quantization table entries, but it saves a lot of shifts.
  171915. * For 12-bit JSAMPLEs, there's no hope of using 16x16 multiplies anyway,
  171916. * so we use a much larger scaling factor to preserve accuracy.
  171917. *
  171918. * A final compromise is to represent the multiplicative constants to only
  171919. * 8 fractional bits, rather than 13. This saves some shifting work on some
  171920. * machines, and may also reduce the cost of multiplication (since there
  171921. * are fewer one-bits in the constants).
  171922. */
  171923. #if BITS_IN_JSAMPLE == 8
  171924. #define CONST_BITS 8
  171925. #define PASS1_BITS 2
  171926. #else
  171927. #define CONST_BITS 8
  171928. #define PASS1_BITS 1 /* lose a little precision to avoid overflow */
  171929. #endif
  171930. /* Some C compilers fail to reduce "FIX(constant)" at compile time, thus
  171931. * causing a lot of useless floating-point operations at run time.
  171932. * To get around this we use the following pre-calculated constants.
  171933. * If you change CONST_BITS you may want to add appropriate values.
  171934. * (With a reasonable C compiler, you can just rely on the FIX() macro...)
  171935. */
  171936. #if CONST_BITS == 8
  171937. #define FIX_1_082392200 ((INT32) 277) /* FIX(1.082392200) */
  171938. #define FIX_1_414213562 ((INT32) 362) /* FIX(1.414213562) */
  171939. #define FIX_1_847759065 ((INT32) 473) /* FIX(1.847759065) */
  171940. #define FIX_2_613125930 ((INT32) 669) /* FIX(2.613125930) */
  171941. #else
  171942. #define FIX_1_082392200 FIX(1.082392200)
  171943. #define FIX_1_414213562 FIX(1.414213562)
  171944. #define FIX_1_847759065 FIX(1.847759065)
  171945. #define FIX_2_613125930 FIX(2.613125930)
  171946. #endif
  171947. /* We can gain a little more speed, with a further compromise in accuracy,
  171948. * by omitting the addition in a descaling shift. This yields an incorrectly
  171949. * rounded result half the time...
  171950. */
  171951. #ifndef USE_ACCURATE_ROUNDING
  171952. #undef DESCALE
  171953. #define DESCALE(x,n) RIGHT_SHIFT(x, n)
  171954. #endif
  171955. /* Multiply a DCTELEM variable by an INT32 constant, and immediately
  171956. * descale to yield a DCTELEM result.
  171957. */
  171958. #define MULTIPLY(var,const) ((DCTELEM) DESCALE((var) * (const), CONST_BITS))
  171959. /* Dequantize a coefficient by multiplying it by the multiplier-table
  171960. * entry; produce a DCTELEM result. For 8-bit data a 16x16->16
  171961. * multiplication will do. For 12-bit data, the multiplier table is
  171962. * declared INT32, so a 32-bit multiply will be used.
  171963. */
  171964. #if BITS_IN_JSAMPLE == 8
  171965. #define DEQUANTIZE(coef,quantval) (((IFAST_MULT_TYPE) (coef)) * (quantval))
  171966. #else
  171967. #define DEQUANTIZE(coef,quantval) \
  171968. DESCALE((coef)*(quantval), IFAST_SCALE_BITS-PASS1_BITS)
  171969. #endif
  171970. /* Like DESCALE, but applies to a DCTELEM and produces an int.
  171971. * We assume that int right shift is unsigned if INT32 right shift is.
  171972. */
  171973. #ifdef RIGHT_SHIFT_IS_UNSIGNED
  171974. #define ISHIFT_TEMPS DCTELEM ishift_temp;
  171975. #if BITS_IN_JSAMPLE == 8
  171976. #define DCTELEMBITS 16 /* DCTELEM may be 16 or 32 bits */
  171977. #else
  171978. #define DCTELEMBITS 32 /* DCTELEM must be 32 bits */
  171979. #endif
  171980. #define IRIGHT_SHIFT(x,shft) \
  171981. ((ishift_temp = (x)) < 0 ? \
  171982. (ishift_temp >> (shft)) | ((~((DCTELEM) 0)) << (DCTELEMBITS-(shft))) : \
  171983. (ishift_temp >> (shft)))
  171984. #else
  171985. #define ISHIFT_TEMPS
  171986. #define IRIGHT_SHIFT(x,shft) ((x) >> (shft))
  171987. #endif
  171988. #ifdef USE_ACCURATE_ROUNDING
  171989. #define IDESCALE(x,n) ((int) IRIGHT_SHIFT((x) + (1 << ((n)-1)), n))
  171990. #else
  171991. #define IDESCALE(x,n) ((int) IRIGHT_SHIFT(x, n))
  171992. #endif
  171993. /*
  171994. * Perform dequantization and inverse DCT on one block of coefficients.
  171995. */
  171996. GLOBAL(void)
  171997. jpeg_idct_ifast (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  171998. JCOEFPTR coef_block,
  171999. JSAMPARRAY output_buf, JDIMENSION output_col)
  172000. {
  172001. DCTELEM tmp0, tmp1, tmp2, tmp3, tmp4, tmp5, tmp6, tmp7;
  172002. DCTELEM tmp10, tmp11, tmp12, tmp13;
  172003. DCTELEM z5, z10, z11, z12, z13;
  172004. JCOEFPTR inptr;
  172005. IFAST_MULT_TYPE * quantptr;
  172006. int * wsptr;
  172007. JSAMPROW outptr;
  172008. JSAMPLE *range_limit = IDCT_range_limit(cinfo);
  172009. int ctr;
  172010. int workspace[DCTSIZE2]; /* buffers data between passes */
  172011. SHIFT_TEMPS /* for DESCALE */
  172012. ISHIFT_TEMPS /* for IDESCALE */
  172013. /* Pass 1: process columns from input, store into work array. */
  172014. inptr = coef_block;
  172015. quantptr = (IFAST_MULT_TYPE *) compptr->dct_table;
  172016. wsptr = workspace;
  172017. for (ctr = DCTSIZE; ctr > 0; ctr--) {
  172018. /* Due to quantization, we will usually find that many of the input
  172019. * coefficients are zero, especially the AC terms. We can exploit this
  172020. * by short-circuiting the IDCT calculation for any column in which all
  172021. * the AC terms are zero. In that case each output is equal to the
  172022. * DC coefficient (with scale factor as needed).
  172023. * With typical images and quantization tables, half or more of the
  172024. * column DCT calculations can be simplified this way.
  172025. */
  172026. if (inptr[DCTSIZE*1] == 0 && inptr[DCTSIZE*2] == 0 &&
  172027. inptr[DCTSIZE*3] == 0 && inptr[DCTSIZE*4] == 0 &&
  172028. inptr[DCTSIZE*5] == 0 && inptr[DCTSIZE*6] == 0 &&
  172029. inptr[DCTSIZE*7] == 0) {
  172030. /* AC terms all zero */
  172031. int dcval = (int) DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]);
  172032. wsptr[DCTSIZE*0] = dcval;
  172033. wsptr[DCTSIZE*1] = dcval;
  172034. wsptr[DCTSIZE*2] = dcval;
  172035. wsptr[DCTSIZE*3] = dcval;
  172036. wsptr[DCTSIZE*4] = dcval;
  172037. wsptr[DCTSIZE*5] = dcval;
  172038. wsptr[DCTSIZE*6] = dcval;
  172039. wsptr[DCTSIZE*7] = dcval;
  172040. inptr++; /* advance pointers to next column */
  172041. quantptr++;
  172042. wsptr++;
  172043. continue;
  172044. }
  172045. /* Even part */
  172046. tmp0 = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]);
  172047. tmp1 = DEQUANTIZE(inptr[DCTSIZE*2], quantptr[DCTSIZE*2]);
  172048. tmp2 = DEQUANTIZE(inptr[DCTSIZE*4], quantptr[DCTSIZE*4]);
  172049. tmp3 = DEQUANTIZE(inptr[DCTSIZE*6], quantptr[DCTSIZE*6]);
  172050. tmp10 = tmp0 + tmp2; /* phase 3 */
  172051. tmp11 = tmp0 - tmp2;
  172052. tmp13 = tmp1 + tmp3; /* phases 5-3 */
  172053. tmp12 = MULTIPLY(tmp1 - tmp3, FIX_1_414213562) - tmp13; /* 2*c4 */
  172054. tmp0 = tmp10 + tmp13; /* phase 2 */
  172055. tmp3 = tmp10 - tmp13;
  172056. tmp1 = tmp11 + tmp12;
  172057. tmp2 = tmp11 - tmp12;
  172058. /* Odd part */
  172059. tmp4 = DEQUANTIZE(inptr[DCTSIZE*1], quantptr[DCTSIZE*1]);
  172060. tmp5 = DEQUANTIZE(inptr[DCTSIZE*3], quantptr[DCTSIZE*3]);
  172061. tmp6 = DEQUANTIZE(inptr[DCTSIZE*5], quantptr[DCTSIZE*5]);
  172062. tmp7 = DEQUANTIZE(inptr[DCTSIZE*7], quantptr[DCTSIZE*7]);
  172063. z13 = tmp6 + tmp5; /* phase 6 */
  172064. z10 = tmp6 - tmp5;
  172065. z11 = tmp4 + tmp7;
  172066. z12 = tmp4 - tmp7;
  172067. tmp7 = z11 + z13; /* phase 5 */
  172068. tmp11 = MULTIPLY(z11 - z13, FIX_1_414213562); /* 2*c4 */
  172069. z5 = MULTIPLY(z10 + z12, FIX_1_847759065); /* 2*c2 */
  172070. tmp10 = MULTIPLY(z12, FIX_1_082392200) - z5; /* 2*(c2-c6) */
  172071. tmp12 = MULTIPLY(z10, - FIX_2_613125930) + z5; /* -2*(c2+c6) */
  172072. tmp6 = tmp12 - tmp7; /* phase 2 */
  172073. tmp5 = tmp11 - tmp6;
  172074. tmp4 = tmp10 + tmp5;
  172075. wsptr[DCTSIZE*0] = (int) (tmp0 + tmp7);
  172076. wsptr[DCTSIZE*7] = (int) (tmp0 - tmp7);
  172077. wsptr[DCTSIZE*1] = (int) (tmp1 + tmp6);
  172078. wsptr[DCTSIZE*6] = (int) (tmp1 - tmp6);
  172079. wsptr[DCTSIZE*2] = (int) (tmp2 + tmp5);
  172080. wsptr[DCTSIZE*5] = (int) (tmp2 - tmp5);
  172081. wsptr[DCTSIZE*4] = (int) (tmp3 + tmp4);
  172082. wsptr[DCTSIZE*3] = (int) (tmp3 - tmp4);
  172083. inptr++; /* advance pointers to next column */
  172084. quantptr++;
  172085. wsptr++;
  172086. }
  172087. /* Pass 2: process rows from work array, store into output array. */
  172088. /* Note that we must descale the results by a factor of 8 == 2**3, */
  172089. /* and also undo the PASS1_BITS scaling. */
  172090. wsptr = workspace;
  172091. for (ctr = 0; ctr < DCTSIZE; ctr++) {
  172092. outptr = output_buf[ctr] + output_col;
  172093. /* Rows of zeroes can be exploited in the same way as we did with columns.
  172094. * However, the column calculation has created many nonzero AC terms, so
  172095. * the simplification applies less often (typically 5% to 10% of the time).
  172096. * On machines with very fast multiplication, it's possible that the
  172097. * test takes more time than it's worth. In that case this section
  172098. * may be commented out.
  172099. */
  172100. #ifndef NO_ZERO_ROW_TEST
  172101. if (wsptr[1] == 0 && wsptr[2] == 0 && wsptr[3] == 0 && wsptr[4] == 0 &&
  172102. wsptr[5] == 0 && wsptr[6] == 0 && wsptr[7] == 0) {
  172103. /* AC terms all zero */
  172104. JSAMPLE dcval = range_limit[IDESCALE(wsptr[0], PASS1_BITS+3)
  172105. & RANGE_MASK];
  172106. outptr[0] = dcval;
  172107. outptr[1] = dcval;
  172108. outptr[2] = dcval;
  172109. outptr[3] = dcval;
  172110. outptr[4] = dcval;
  172111. outptr[5] = dcval;
  172112. outptr[6] = dcval;
  172113. outptr[7] = dcval;
  172114. wsptr += DCTSIZE; /* advance pointer to next row */
  172115. continue;
  172116. }
  172117. #endif
  172118. /* Even part */
  172119. tmp10 = ((DCTELEM) wsptr[0] + (DCTELEM) wsptr[4]);
  172120. tmp11 = ((DCTELEM) wsptr[0] - (DCTELEM) wsptr[4]);
  172121. tmp13 = ((DCTELEM) wsptr[2] + (DCTELEM) wsptr[6]);
  172122. tmp12 = MULTIPLY((DCTELEM) wsptr[2] - (DCTELEM) wsptr[6], FIX_1_414213562)
  172123. - tmp13;
  172124. tmp0 = tmp10 + tmp13;
  172125. tmp3 = tmp10 - tmp13;
  172126. tmp1 = tmp11 + tmp12;
  172127. tmp2 = tmp11 - tmp12;
  172128. /* Odd part */
  172129. z13 = (DCTELEM) wsptr[5] + (DCTELEM) wsptr[3];
  172130. z10 = (DCTELEM) wsptr[5] - (DCTELEM) wsptr[3];
  172131. z11 = (DCTELEM) wsptr[1] + (DCTELEM) wsptr[7];
  172132. z12 = (DCTELEM) wsptr[1] - (DCTELEM) wsptr[7];
  172133. tmp7 = z11 + z13; /* phase 5 */
  172134. tmp11 = MULTIPLY(z11 - z13, FIX_1_414213562); /* 2*c4 */
  172135. z5 = MULTIPLY(z10 + z12, FIX_1_847759065); /* 2*c2 */
  172136. tmp10 = MULTIPLY(z12, FIX_1_082392200) - z5; /* 2*(c2-c6) */
  172137. tmp12 = MULTIPLY(z10, - FIX_2_613125930) + z5; /* -2*(c2+c6) */
  172138. tmp6 = tmp12 - tmp7; /* phase 2 */
  172139. tmp5 = tmp11 - tmp6;
  172140. tmp4 = tmp10 + tmp5;
  172141. /* Final output stage: scale down by a factor of 8 and range-limit */
  172142. outptr[0] = range_limit[IDESCALE(tmp0 + tmp7, PASS1_BITS+3)
  172143. & RANGE_MASK];
  172144. outptr[7] = range_limit[IDESCALE(tmp0 - tmp7, PASS1_BITS+3)
  172145. & RANGE_MASK];
  172146. outptr[1] = range_limit[IDESCALE(tmp1 + tmp6, PASS1_BITS+3)
  172147. & RANGE_MASK];
  172148. outptr[6] = range_limit[IDESCALE(tmp1 - tmp6, PASS1_BITS+3)
  172149. & RANGE_MASK];
  172150. outptr[2] = range_limit[IDESCALE(tmp2 + tmp5, PASS1_BITS+3)
  172151. & RANGE_MASK];
  172152. outptr[5] = range_limit[IDESCALE(tmp2 - tmp5, PASS1_BITS+3)
  172153. & RANGE_MASK];
  172154. outptr[4] = range_limit[IDESCALE(tmp3 + tmp4, PASS1_BITS+3)
  172155. & RANGE_MASK];
  172156. outptr[3] = range_limit[IDESCALE(tmp3 - tmp4, PASS1_BITS+3)
  172157. & RANGE_MASK];
  172158. wsptr += DCTSIZE; /* advance pointer to next row */
  172159. }
  172160. }
  172161. #endif /* DCT_IFAST_SUPPORTED */
  172162. /*** End of inlined file: jidctfst.c ***/
  172163. #undef CONST_BITS
  172164. #undef FIX_1_847759065
  172165. #undef MULTIPLY
  172166. #undef DEQUANTIZE
  172167. /*** Start of inlined file: jidctint.c ***/
  172168. #define JPEG_INTERNALS
  172169. #ifdef DCT_ISLOW_SUPPORTED
  172170. /*
  172171. * This module is specialized to the case DCTSIZE = 8.
  172172. */
  172173. #if DCTSIZE != 8
  172174. Sorry, this code only copes with 8x8 DCTs. /* deliberate syntax err */
  172175. #endif
  172176. /*
  172177. * The poop on this scaling stuff is as follows:
  172178. *
  172179. * Each 1-D IDCT step produces outputs which are a factor of sqrt(N)
  172180. * larger than the true IDCT outputs. The final outputs are therefore
  172181. * a factor of N larger than desired; since N=8 this can be cured by
  172182. * a simple right shift at the end of the algorithm. The advantage of
  172183. * this arrangement is that we save two multiplications per 1-D IDCT,
  172184. * because the y0 and y4 inputs need not be divided by sqrt(N).
  172185. *
  172186. * We have to do addition and subtraction of the integer inputs, which
  172187. * is no problem, and multiplication by fractional constants, which is
  172188. * a problem to do in integer arithmetic. We multiply all the constants
  172189. * by CONST_SCALE and convert them to integer constants (thus retaining
  172190. * CONST_BITS bits of precision in the constants). After doing a
  172191. * multiplication we have to divide the product by CONST_SCALE, with proper
  172192. * rounding, to produce the correct output. This division can be done
  172193. * cheaply as a right shift of CONST_BITS bits. We postpone shifting
  172194. * as long as possible so that partial sums can be added together with
  172195. * full fractional precision.
  172196. *
  172197. * The outputs of the first pass are scaled up by PASS1_BITS bits so that
  172198. * they are represented to better-than-integral precision. These outputs
  172199. * require BITS_IN_JSAMPLE + PASS1_BITS + 3 bits; this fits in a 16-bit word
  172200. * with the recommended scaling. (To scale up 12-bit sample data further, an
  172201. * intermediate INT32 array would be needed.)
  172202. *
  172203. * To avoid overflow of the 32-bit intermediate results in pass 2, we must
  172204. * have BITS_IN_JSAMPLE + CONST_BITS + PASS1_BITS <= 26. Error analysis
  172205. * shows that the values given below are the most effective.
  172206. */
  172207. #if BITS_IN_JSAMPLE == 8
  172208. #define CONST_BITS 13
  172209. #define PASS1_BITS 2
  172210. #else
  172211. #define CONST_BITS 13
  172212. #define PASS1_BITS 1 /* lose a little precision to avoid overflow */
  172213. #endif
  172214. /* Some C compilers fail to reduce "FIX(constant)" at compile time, thus
  172215. * causing a lot of useless floating-point operations at run time.
  172216. * To get around this we use the following pre-calculated constants.
  172217. * If you change CONST_BITS you may want to add appropriate values.
  172218. * (With a reasonable C compiler, you can just rely on the FIX() macro...)
  172219. */
  172220. #if CONST_BITS == 13
  172221. #define FIX_0_298631336 ((INT32) 2446) /* FIX(0.298631336) */
  172222. #define FIX_0_390180644 ((INT32) 3196) /* FIX(0.390180644) */
  172223. #define FIX_0_541196100 ((INT32) 4433) /* FIX(0.541196100) */
  172224. #define FIX_0_765366865 ((INT32) 6270) /* FIX(0.765366865) */
  172225. #define FIX_0_899976223 ((INT32) 7373) /* FIX(0.899976223) */
  172226. #define FIX_1_175875602 ((INT32) 9633) /* FIX(1.175875602) */
  172227. #define FIX_1_501321110 ((INT32) 12299) /* FIX(1.501321110) */
  172228. #define FIX_1_847759065 ((INT32) 15137) /* FIX(1.847759065) */
  172229. #define FIX_1_961570560 ((INT32) 16069) /* FIX(1.961570560) */
  172230. #define FIX_2_053119869 ((INT32) 16819) /* FIX(2.053119869) */
  172231. #define FIX_2_562915447 ((INT32) 20995) /* FIX(2.562915447) */
  172232. #define FIX_3_072711026 ((INT32) 25172) /* FIX(3.072711026) */
  172233. #else
  172234. #define FIX_0_298631336 FIX(0.298631336)
  172235. #define FIX_0_390180644 FIX(0.390180644)
  172236. #define FIX_0_541196100 FIX(0.541196100)
  172237. #define FIX_0_765366865 FIX(0.765366865)
  172238. #define FIX_0_899976223 FIX(0.899976223)
  172239. #define FIX_1_175875602 FIX(1.175875602)
  172240. #define FIX_1_501321110 FIX(1.501321110)
  172241. #define FIX_1_847759065 FIX(1.847759065)
  172242. #define FIX_1_961570560 FIX(1.961570560)
  172243. #define FIX_2_053119869 FIX(2.053119869)
  172244. #define FIX_2_562915447 FIX(2.562915447)
  172245. #define FIX_3_072711026 FIX(3.072711026)
  172246. #endif
  172247. /* Multiply an INT32 variable by an INT32 constant to yield an INT32 result.
  172248. * For 8-bit samples with the recommended scaling, all the variable
  172249. * and constant values involved are no more than 16 bits wide, so a
  172250. * 16x16->32 bit multiply can be used instead of a full 32x32 multiply.
  172251. * For 12-bit samples, a full 32-bit multiplication will be needed.
  172252. */
  172253. #if BITS_IN_JSAMPLE == 8
  172254. #define MULTIPLY(var,const) MULTIPLY16C16(var,const)
  172255. #else
  172256. #define MULTIPLY(var,const) ((var) * (const))
  172257. #endif
  172258. /* Dequantize a coefficient by multiplying it by the multiplier-table
  172259. * entry; produce an int result. In this module, both inputs and result
  172260. * are 16 bits or less, so either int or short multiply will work.
  172261. */
  172262. #define DEQUANTIZE(coef,quantval) (((ISLOW_MULT_TYPE) (coef)) * (quantval))
  172263. /*
  172264. * Perform dequantization and inverse DCT on one block of coefficients.
  172265. */
  172266. GLOBAL(void)
  172267. jpeg_idct_islow (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  172268. JCOEFPTR coef_block,
  172269. JSAMPARRAY output_buf, JDIMENSION output_col)
  172270. {
  172271. INT32 tmp0, tmp1, tmp2, tmp3;
  172272. INT32 tmp10, tmp11, tmp12, tmp13;
  172273. INT32 z1, z2, z3, z4, z5;
  172274. JCOEFPTR inptr;
  172275. ISLOW_MULT_TYPE * quantptr;
  172276. int * wsptr;
  172277. JSAMPROW outptr;
  172278. JSAMPLE *range_limit = IDCT_range_limit(cinfo);
  172279. int ctr;
  172280. int workspace[DCTSIZE2]; /* buffers data between passes */
  172281. SHIFT_TEMPS
  172282. /* Pass 1: process columns from input, store into work array. */
  172283. /* Note results are scaled up by sqrt(8) compared to a true IDCT; */
  172284. /* furthermore, we scale the results by 2**PASS1_BITS. */
  172285. inptr = coef_block;
  172286. quantptr = (ISLOW_MULT_TYPE *) compptr->dct_table;
  172287. wsptr = workspace;
  172288. for (ctr = DCTSIZE; ctr > 0; ctr--) {
  172289. /* Due to quantization, we will usually find that many of the input
  172290. * coefficients are zero, especially the AC terms. We can exploit this
  172291. * by short-circuiting the IDCT calculation for any column in which all
  172292. * the AC terms are zero. In that case each output is equal to the
  172293. * DC coefficient (with scale factor as needed).
  172294. * With typical images and quantization tables, half or more of the
  172295. * column DCT calculations can be simplified this way.
  172296. */
  172297. if (inptr[DCTSIZE*1] == 0 && inptr[DCTSIZE*2] == 0 &&
  172298. inptr[DCTSIZE*3] == 0 && inptr[DCTSIZE*4] == 0 &&
  172299. inptr[DCTSIZE*5] == 0 && inptr[DCTSIZE*6] == 0 &&
  172300. inptr[DCTSIZE*7] == 0) {
  172301. /* AC terms all zero */
  172302. int dcval = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]) << PASS1_BITS;
  172303. wsptr[DCTSIZE*0] = dcval;
  172304. wsptr[DCTSIZE*1] = dcval;
  172305. wsptr[DCTSIZE*2] = dcval;
  172306. wsptr[DCTSIZE*3] = dcval;
  172307. wsptr[DCTSIZE*4] = dcval;
  172308. wsptr[DCTSIZE*5] = dcval;
  172309. wsptr[DCTSIZE*6] = dcval;
  172310. wsptr[DCTSIZE*7] = dcval;
  172311. inptr++; /* advance pointers to next column */
  172312. quantptr++;
  172313. wsptr++;
  172314. continue;
  172315. }
  172316. /* Even part: reverse the even part of the forward DCT. */
  172317. /* The rotator is sqrt(2)*c(-6). */
  172318. z2 = DEQUANTIZE(inptr[DCTSIZE*2], quantptr[DCTSIZE*2]);
  172319. z3 = DEQUANTIZE(inptr[DCTSIZE*6], quantptr[DCTSIZE*6]);
  172320. z1 = MULTIPLY(z2 + z3, FIX_0_541196100);
  172321. tmp2 = z1 + MULTIPLY(z3, - FIX_1_847759065);
  172322. tmp3 = z1 + MULTIPLY(z2, FIX_0_765366865);
  172323. z2 = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]);
  172324. z3 = DEQUANTIZE(inptr[DCTSIZE*4], quantptr[DCTSIZE*4]);
  172325. tmp0 = (z2 + z3) << CONST_BITS;
  172326. tmp1 = (z2 - z3) << CONST_BITS;
  172327. tmp10 = tmp0 + tmp3;
  172328. tmp13 = tmp0 - tmp3;
  172329. tmp11 = tmp1 + tmp2;
  172330. tmp12 = tmp1 - tmp2;
  172331. /* Odd part per figure 8; the matrix is unitary and hence its
  172332. * transpose is its inverse. i0..i3 are y7,y5,y3,y1 respectively.
  172333. */
  172334. tmp0 = DEQUANTIZE(inptr[DCTSIZE*7], quantptr[DCTSIZE*7]);
  172335. tmp1 = DEQUANTIZE(inptr[DCTSIZE*5], quantptr[DCTSIZE*5]);
  172336. tmp2 = DEQUANTIZE(inptr[DCTSIZE*3], quantptr[DCTSIZE*3]);
  172337. tmp3 = DEQUANTIZE(inptr[DCTSIZE*1], quantptr[DCTSIZE*1]);
  172338. z1 = tmp0 + tmp3;
  172339. z2 = tmp1 + tmp2;
  172340. z3 = tmp0 + tmp2;
  172341. z4 = tmp1 + tmp3;
  172342. z5 = MULTIPLY(z3 + z4, FIX_1_175875602); /* sqrt(2) * c3 */
  172343. tmp0 = MULTIPLY(tmp0, FIX_0_298631336); /* sqrt(2) * (-c1+c3+c5-c7) */
  172344. tmp1 = MULTIPLY(tmp1, FIX_2_053119869); /* sqrt(2) * ( c1+c3-c5+c7) */
  172345. tmp2 = MULTIPLY(tmp2, FIX_3_072711026); /* sqrt(2) * ( c1+c3+c5-c7) */
  172346. tmp3 = MULTIPLY(tmp3, FIX_1_501321110); /* sqrt(2) * ( c1+c3-c5-c7) */
  172347. z1 = MULTIPLY(z1, - FIX_0_899976223); /* sqrt(2) * (c7-c3) */
  172348. z2 = MULTIPLY(z2, - FIX_2_562915447); /* sqrt(2) * (-c1-c3) */
  172349. z3 = MULTIPLY(z3, - FIX_1_961570560); /* sqrt(2) * (-c3-c5) */
  172350. z4 = MULTIPLY(z4, - FIX_0_390180644); /* sqrt(2) * (c5-c3) */
  172351. z3 += z5;
  172352. z4 += z5;
  172353. tmp0 += z1 + z3;
  172354. tmp1 += z2 + z4;
  172355. tmp2 += z2 + z3;
  172356. tmp3 += z1 + z4;
  172357. /* Final output stage: inputs are tmp10..tmp13, tmp0..tmp3 */
  172358. wsptr[DCTSIZE*0] = (int) DESCALE(tmp10 + tmp3, CONST_BITS-PASS1_BITS);
  172359. wsptr[DCTSIZE*7] = (int) DESCALE(tmp10 - tmp3, CONST_BITS-PASS1_BITS);
  172360. wsptr[DCTSIZE*1] = (int) DESCALE(tmp11 + tmp2, CONST_BITS-PASS1_BITS);
  172361. wsptr[DCTSIZE*6] = (int) DESCALE(tmp11 - tmp2, CONST_BITS-PASS1_BITS);
  172362. wsptr[DCTSIZE*2] = (int) DESCALE(tmp12 + tmp1, CONST_BITS-PASS1_BITS);
  172363. wsptr[DCTSIZE*5] = (int) DESCALE(tmp12 - tmp1, CONST_BITS-PASS1_BITS);
  172364. wsptr[DCTSIZE*3] = (int) DESCALE(tmp13 + tmp0, CONST_BITS-PASS1_BITS);
  172365. wsptr[DCTSIZE*4] = (int) DESCALE(tmp13 - tmp0, CONST_BITS-PASS1_BITS);
  172366. inptr++; /* advance pointers to next column */
  172367. quantptr++;
  172368. wsptr++;
  172369. }
  172370. /* Pass 2: process rows from work array, store into output array. */
  172371. /* Note that we must descale the results by a factor of 8 == 2**3, */
  172372. /* and also undo the PASS1_BITS scaling. */
  172373. wsptr = workspace;
  172374. for (ctr = 0; ctr < DCTSIZE; ctr++) {
  172375. outptr = output_buf[ctr] + output_col;
  172376. /* Rows of zeroes can be exploited in the same way as we did with columns.
  172377. * However, the column calculation has created many nonzero AC terms, so
  172378. * the simplification applies less often (typically 5% to 10% of the time).
  172379. * On machines with very fast multiplication, it's possible that the
  172380. * test takes more time than it's worth. In that case this section
  172381. * may be commented out.
  172382. */
  172383. #ifndef NO_ZERO_ROW_TEST
  172384. if (wsptr[1] == 0 && wsptr[2] == 0 && wsptr[3] == 0 && wsptr[4] == 0 &&
  172385. wsptr[5] == 0 && wsptr[6] == 0 && wsptr[7] == 0) {
  172386. /* AC terms all zero */
  172387. JSAMPLE dcval = range_limit[(int) DESCALE((INT32) wsptr[0], PASS1_BITS+3)
  172388. & RANGE_MASK];
  172389. outptr[0] = dcval;
  172390. outptr[1] = dcval;
  172391. outptr[2] = dcval;
  172392. outptr[3] = dcval;
  172393. outptr[4] = dcval;
  172394. outptr[5] = dcval;
  172395. outptr[6] = dcval;
  172396. outptr[7] = dcval;
  172397. wsptr += DCTSIZE; /* advance pointer to next row */
  172398. continue;
  172399. }
  172400. #endif
  172401. /* Even part: reverse the even part of the forward DCT. */
  172402. /* The rotator is sqrt(2)*c(-6). */
  172403. z2 = (INT32) wsptr[2];
  172404. z3 = (INT32) wsptr[6];
  172405. z1 = MULTIPLY(z2 + z3, FIX_0_541196100);
  172406. tmp2 = z1 + MULTIPLY(z3, - FIX_1_847759065);
  172407. tmp3 = z1 + MULTIPLY(z2, FIX_0_765366865);
  172408. tmp0 = ((INT32) wsptr[0] + (INT32) wsptr[4]) << CONST_BITS;
  172409. tmp1 = ((INT32) wsptr[0] - (INT32) wsptr[4]) << CONST_BITS;
  172410. tmp10 = tmp0 + tmp3;
  172411. tmp13 = tmp0 - tmp3;
  172412. tmp11 = tmp1 + tmp2;
  172413. tmp12 = tmp1 - tmp2;
  172414. /* Odd part per figure 8; the matrix is unitary and hence its
  172415. * transpose is its inverse. i0..i3 are y7,y5,y3,y1 respectively.
  172416. */
  172417. tmp0 = (INT32) wsptr[7];
  172418. tmp1 = (INT32) wsptr[5];
  172419. tmp2 = (INT32) wsptr[3];
  172420. tmp3 = (INT32) wsptr[1];
  172421. z1 = tmp0 + tmp3;
  172422. z2 = tmp1 + tmp2;
  172423. z3 = tmp0 + tmp2;
  172424. z4 = tmp1 + tmp3;
  172425. z5 = MULTIPLY(z3 + z4, FIX_1_175875602); /* sqrt(2) * c3 */
  172426. tmp0 = MULTIPLY(tmp0, FIX_0_298631336); /* sqrt(2) * (-c1+c3+c5-c7) */
  172427. tmp1 = MULTIPLY(tmp1, FIX_2_053119869); /* sqrt(2) * ( c1+c3-c5+c7) */
  172428. tmp2 = MULTIPLY(tmp2, FIX_3_072711026); /* sqrt(2) * ( c1+c3+c5-c7) */
  172429. tmp3 = MULTIPLY(tmp3, FIX_1_501321110); /* sqrt(2) * ( c1+c3-c5-c7) */
  172430. z1 = MULTIPLY(z1, - FIX_0_899976223); /* sqrt(2) * (c7-c3) */
  172431. z2 = MULTIPLY(z2, - FIX_2_562915447); /* sqrt(2) * (-c1-c3) */
  172432. z3 = MULTIPLY(z3, - FIX_1_961570560); /* sqrt(2) * (-c3-c5) */
  172433. z4 = MULTIPLY(z4, - FIX_0_390180644); /* sqrt(2) * (c5-c3) */
  172434. z3 += z5;
  172435. z4 += z5;
  172436. tmp0 += z1 + z3;
  172437. tmp1 += z2 + z4;
  172438. tmp2 += z2 + z3;
  172439. tmp3 += z1 + z4;
  172440. /* Final output stage: inputs are tmp10..tmp13, tmp0..tmp3 */
  172441. outptr[0] = range_limit[(int) DESCALE(tmp10 + tmp3,
  172442. CONST_BITS+PASS1_BITS+3)
  172443. & RANGE_MASK];
  172444. outptr[7] = range_limit[(int) DESCALE(tmp10 - tmp3,
  172445. CONST_BITS+PASS1_BITS+3)
  172446. & RANGE_MASK];
  172447. outptr[1] = range_limit[(int) DESCALE(tmp11 + tmp2,
  172448. CONST_BITS+PASS1_BITS+3)
  172449. & RANGE_MASK];
  172450. outptr[6] = range_limit[(int) DESCALE(tmp11 - tmp2,
  172451. CONST_BITS+PASS1_BITS+3)
  172452. & RANGE_MASK];
  172453. outptr[2] = range_limit[(int) DESCALE(tmp12 + tmp1,
  172454. CONST_BITS+PASS1_BITS+3)
  172455. & RANGE_MASK];
  172456. outptr[5] = range_limit[(int) DESCALE(tmp12 - tmp1,
  172457. CONST_BITS+PASS1_BITS+3)
  172458. & RANGE_MASK];
  172459. outptr[3] = range_limit[(int) DESCALE(tmp13 + tmp0,
  172460. CONST_BITS+PASS1_BITS+3)
  172461. & RANGE_MASK];
  172462. outptr[4] = range_limit[(int) DESCALE(tmp13 - tmp0,
  172463. CONST_BITS+PASS1_BITS+3)
  172464. & RANGE_MASK];
  172465. wsptr += DCTSIZE; /* advance pointer to next row */
  172466. }
  172467. }
  172468. #endif /* DCT_ISLOW_SUPPORTED */
  172469. /*** End of inlined file: jidctint.c ***/
  172470. /*** Start of inlined file: jidctred.c ***/
  172471. #define JPEG_INTERNALS
  172472. #ifdef IDCT_SCALING_SUPPORTED
  172473. /*
  172474. * This module is specialized to the case DCTSIZE = 8.
  172475. */
  172476. #if DCTSIZE != 8
  172477. Sorry, this code only copes with 8x8 DCTs. /* deliberate syntax err */
  172478. #endif
  172479. /* Scaling is the same as in jidctint.c. */
  172480. #if BITS_IN_JSAMPLE == 8
  172481. #define CONST_BITS 13
  172482. #define PASS1_BITS 2
  172483. #else
  172484. #define CONST_BITS 13
  172485. #define PASS1_BITS 1 /* lose a little precision to avoid overflow */
  172486. #endif
  172487. /* Some C compilers fail to reduce "FIX(constant)" at compile time, thus
  172488. * causing a lot of useless floating-point operations at run time.
  172489. * To get around this we use the following pre-calculated constants.
  172490. * If you change CONST_BITS you may want to add appropriate values.
  172491. * (With a reasonable C compiler, you can just rely on the FIX() macro...)
  172492. */
  172493. #if CONST_BITS == 13
  172494. #define FIX_0_211164243 ((INT32) 1730) /* FIX(0.211164243) */
  172495. #define FIX_0_509795579 ((INT32) 4176) /* FIX(0.509795579) */
  172496. #define FIX_0_601344887 ((INT32) 4926) /* FIX(0.601344887) */
  172497. #define FIX_0_720959822 ((INT32) 5906) /* FIX(0.720959822) */
  172498. #define FIX_0_765366865 ((INT32) 6270) /* FIX(0.765366865) */
  172499. #define FIX_0_850430095 ((INT32) 6967) /* FIX(0.850430095) */
  172500. #define FIX_0_899976223 ((INT32) 7373) /* FIX(0.899976223) */
  172501. #define FIX_1_061594337 ((INT32) 8697) /* FIX(1.061594337) */
  172502. #define FIX_1_272758580 ((INT32) 10426) /* FIX(1.272758580) */
  172503. #define FIX_1_451774981 ((INT32) 11893) /* FIX(1.451774981) */
  172504. #define FIX_1_847759065 ((INT32) 15137) /* FIX(1.847759065) */
  172505. #define FIX_2_172734803 ((INT32) 17799) /* FIX(2.172734803) */
  172506. #define FIX_2_562915447 ((INT32) 20995) /* FIX(2.562915447) */
  172507. #define FIX_3_624509785 ((INT32) 29692) /* FIX(3.624509785) */
  172508. #else
  172509. #define FIX_0_211164243 FIX(0.211164243)
  172510. #define FIX_0_509795579 FIX(0.509795579)
  172511. #define FIX_0_601344887 FIX(0.601344887)
  172512. #define FIX_0_720959822 FIX(0.720959822)
  172513. #define FIX_0_765366865 FIX(0.765366865)
  172514. #define FIX_0_850430095 FIX(0.850430095)
  172515. #define FIX_0_899976223 FIX(0.899976223)
  172516. #define FIX_1_061594337 FIX(1.061594337)
  172517. #define FIX_1_272758580 FIX(1.272758580)
  172518. #define FIX_1_451774981 FIX(1.451774981)
  172519. #define FIX_1_847759065 FIX(1.847759065)
  172520. #define FIX_2_172734803 FIX(2.172734803)
  172521. #define FIX_2_562915447 FIX(2.562915447)
  172522. #define FIX_3_624509785 FIX(3.624509785)
  172523. #endif
  172524. /* Multiply an INT32 variable by an INT32 constant to yield an INT32 result.
  172525. * For 8-bit samples with the recommended scaling, all the variable
  172526. * and constant values involved are no more than 16 bits wide, so a
  172527. * 16x16->32 bit multiply can be used instead of a full 32x32 multiply.
  172528. * For 12-bit samples, a full 32-bit multiplication will be needed.
  172529. */
  172530. #if BITS_IN_JSAMPLE == 8
  172531. #define MULTIPLY(var,const) MULTIPLY16C16(var,const)
  172532. #else
  172533. #define MULTIPLY(var,const) ((var) * (const))
  172534. #endif
  172535. /* Dequantize a coefficient by multiplying it by the multiplier-table
  172536. * entry; produce an int result. In this module, both inputs and result
  172537. * are 16 bits or less, so either int or short multiply will work.
  172538. */
  172539. #define DEQUANTIZE(coef,quantval) (((ISLOW_MULT_TYPE) (coef)) * (quantval))
  172540. /*
  172541. * Perform dequantization and inverse DCT on one block of coefficients,
  172542. * producing a reduced-size 4x4 output block.
  172543. */
  172544. GLOBAL(void)
  172545. jpeg_idct_4x4 (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  172546. JCOEFPTR coef_block,
  172547. JSAMPARRAY output_buf, JDIMENSION output_col)
  172548. {
  172549. INT32 tmp0, tmp2, tmp10, tmp12;
  172550. INT32 z1, z2, z3, z4;
  172551. JCOEFPTR inptr;
  172552. ISLOW_MULT_TYPE * quantptr;
  172553. int * wsptr;
  172554. JSAMPROW outptr;
  172555. JSAMPLE *range_limit = IDCT_range_limit(cinfo);
  172556. int ctr;
  172557. int workspace[DCTSIZE*4]; /* buffers data between passes */
  172558. SHIFT_TEMPS
  172559. /* Pass 1: process columns from input, store into work array. */
  172560. inptr = coef_block;
  172561. quantptr = (ISLOW_MULT_TYPE *) compptr->dct_table;
  172562. wsptr = workspace;
  172563. for (ctr = DCTSIZE; ctr > 0; inptr++, quantptr++, wsptr++, ctr--) {
  172564. /* Don't bother to process column 4, because second pass won't use it */
  172565. if (ctr == DCTSIZE-4)
  172566. continue;
  172567. if (inptr[DCTSIZE*1] == 0 && inptr[DCTSIZE*2] == 0 &&
  172568. inptr[DCTSIZE*3] == 0 && inptr[DCTSIZE*5] == 0 &&
  172569. inptr[DCTSIZE*6] == 0 && inptr[DCTSIZE*7] == 0) {
  172570. /* AC terms all zero; we need not examine term 4 for 4x4 output */
  172571. int dcval = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]) << PASS1_BITS;
  172572. wsptr[DCTSIZE*0] = dcval;
  172573. wsptr[DCTSIZE*1] = dcval;
  172574. wsptr[DCTSIZE*2] = dcval;
  172575. wsptr[DCTSIZE*3] = dcval;
  172576. continue;
  172577. }
  172578. /* Even part */
  172579. tmp0 = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]);
  172580. tmp0 <<= (CONST_BITS+1);
  172581. z2 = DEQUANTIZE(inptr[DCTSIZE*2], quantptr[DCTSIZE*2]);
  172582. z3 = DEQUANTIZE(inptr[DCTSIZE*6], quantptr[DCTSIZE*6]);
  172583. tmp2 = MULTIPLY(z2, FIX_1_847759065) + MULTIPLY(z3, - FIX_0_765366865);
  172584. tmp10 = tmp0 + tmp2;
  172585. tmp12 = tmp0 - tmp2;
  172586. /* Odd part */
  172587. z1 = DEQUANTIZE(inptr[DCTSIZE*7], quantptr[DCTSIZE*7]);
  172588. z2 = DEQUANTIZE(inptr[DCTSIZE*5], quantptr[DCTSIZE*5]);
  172589. z3 = DEQUANTIZE(inptr[DCTSIZE*3], quantptr[DCTSIZE*3]);
  172590. z4 = DEQUANTIZE(inptr[DCTSIZE*1], quantptr[DCTSIZE*1]);
  172591. tmp0 = MULTIPLY(z1, - FIX_0_211164243) /* sqrt(2) * (c3-c1) */
  172592. + MULTIPLY(z2, FIX_1_451774981) /* sqrt(2) * (c3+c7) */
  172593. + MULTIPLY(z3, - FIX_2_172734803) /* sqrt(2) * (-c1-c5) */
  172594. + MULTIPLY(z4, FIX_1_061594337); /* sqrt(2) * (c5+c7) */
  172595. tmp2 = MULTIPLY(z1, - FIX_0_509795579) /* sqrt(2) * (c7-c5) */
  172596. + MULTIPLY(z2, - FIX_0_601344887) /* sqrt(2) * (c5-c1) */
  172597. + MULTIPLY(z3, FIX_0_899976223) /* sqrt(2) * (c3-c7) */
  172598. + MULTIPLY(z4, FIX_2_562915447); /* sqrt(2) * (c1+c3) */
  172599. /* Final output stage */
  172600. wsptr[DCTSIZE*0] = (int) DESCALE(tmp10 + tmp2, CONST_BITS-PASS1_BITS+1);
  172601. wsptr[DCTSIZE*3] = (int) DESCALE(tmp10 - tmp2, CONST_BITS-PASS1_BITS+1);
  172602. wsptr[DCTSIZE*1] = (int) DESCALE(tmp12 + tmp0, CONST_BITS-PASS1_BITS+1);
  172603. wsptr[DCTSIZE*2] = (int) DESCALE(tmp12 - tmp0, CONST_BITS-PASS1_BITS+1);
  172604. }
  172605. /* Pass 2: process 4 rows from work array, store into output array. */
  172606. wsptr = workspace;
  172607. for (ctr = 0; ctr < 4; ctr++) {
  172608. outptr = output_buf[ctr] + output_col;
  172609. /* It's not clear whether a zero row test is worthwhile here ... */
  172610. #ifndef NO_ZERO_ROW_TEST
  172611. if (wsptr[1] == 0 && wsptr[2] == 0 && wsptr[3] == 0 &&
  172612. wsptr[5] == 0 && wsptr[6] == 0 && wsptr[7] == 0) {
  172613. /* AC terms all zero */
  172614. JSAMPLE dcval = range_limit[(int) DESCALE((INT32) wsptr[0], PASS1_BITS+3)
  172615. & RANGE_MASK];
  172616. outptr[0] = dcval;
  172617. outptr[1] = dcval;
  172618. outptr[2] = dcval;
  172619. outptr[3] = dcval;
  172620. wsptr += DCTSIZE; /* advance pointer to next row */
  172621. continue;
  172622. }
  172623. #endif
  172624. /* Even part */
  172625. tmp0 = ((INT32) wsptr[0]) << (CONST_BITS+1);
  172626. tmp2 = MULTIPLY((INT32) wsptr[2], FIX_1_847759065)
  172627. + MULTIPLY((INT32) wsptr[6], - FIX_0_765366865);
  172628. tmp10 = tmp0 + tmp2;
  172629. tmp12 = tmp0 - tmp2;
  172630. /* Odd part */
  172631. z1 = (INT32) wsptr[7];
  172632. z2 = (INT32) wsptr[5];
  172633. z3 = (INT32) wsptr[3];
  172634. z4 = (INT32) wsptr[1];
  172635. tmp0 = MULTIPLY(z1, - FIX_0_211164243) /* sqrt(2) * (c3-c1) */
  172636. + MULTIPLY(z2, FIX_1_451774981) /* sqrt(2) * (c3+c7) */
  172637. + MULTIPLY(z3, - FIX_2_172734803) /* sqrt(2) * (-c1-c5) */
  172638. + MULTIPLY(z4, FIX_1_061594337); /* sqrt(2) * (c5+c7) */
  172639. tmp2 = MULTIPLY(z1, - FIX_0_509795579) /* sqrt(2) * (c7-c5) */
  172640. + MULTIPLY(z2, - FIX_0_601344887) /* sqrt(2) * (c5-c1) */
  172641. + MULTIPLY(z3, FIX_0_899976223) /* sqrt(2) * (c3-c7) */
  172642. + MULTIPLY(z4, FIX_2_562915447); /* sqrt(2) * (c1+c3) */
  172643. /* Final output stage */
  172644. outptr[0] = range_limit[(int) DESCALE(tmp10 + tmp2,
  172645. CONST_BITS+PASS1_BITS+3+1)
  172646. & RANGE_MASK];
  172647. outptr[3] = range_limit[(int) DESCALE(tmp10 - tmp2,
  172648. CONST_BITS+PASS1_BITS+3+1)
  172649. & RANGE_MASK];
  172650. outptr[1] = range_limit[(int) DESCALE(tmp12 + tmp0,
  172651. CONST_BITS+PASS1_BITS+3+1)
  172652. & RANGE_MASK];
  172653. outptr[2] = range_limit[(int) DESCALE(tmp12 - tmp0,
  172654. CONST_BITS+PASS1_BITS+3+1)
  172655. & RANGE_MASK];
  172656. wsptr += DCTSIZE; /* advance pointer to next row */
  172657. }
  172658. }
  172659. /*
  172660. * Perform dequantization and inverse DCT on one block of coefficients,
  172661. * producing a reduced-size 2x2 output block.
  172662. */
  172663. GLOBAL(void)
  172664. jpeg_idct_2x2 (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  172665. JCOEFPTR coef_block,
  172666. JSAMPARRAY output_buf, JDIMENSION output_col)
  172667. {
  172668. INT32 tmp0, tmp10, z1;
  172669. JCOEFPTR inptr;
  172670. ISLOW_MULT_TYPE * quantptr;
  172671. int * wsptr;
  172672. JSAMPROW outptr;
  172673. JSAMPLE *range_limit = IDCT_range_limit(cinfo);
  172674. int ctr;
  172675. int workspace[DCTSIZE*2]; /* buffers data between passes */
  172676. SHIFT_TEMPS
  172677. /* Pass 1: process columns from input, store into work array. */
  172678. inptr = coef_block;
  172679. quantptr = (ISLOW_MULT_TYPE *) compptr->dct_table;
  172680. wsptr = workspace;
  172681. for (ctr = DCTSIZE; ctr > 0; inptr++, quantptr++, wsptr++, ctr--) {
  172682. /* Don't bother to process columns 2,4,6 */
  172683. if (ctr == DCTSIZE-2 || ctr == DCTSIZE-4 || ctr == DCTSIZE-6)
  172684. continue;
  172685. if (inptr[DCTSIZE*1] == 0 && inptr[DCTSIZE*3] == 0 &&
  172686. inptr[DCTSIZE*5] == 0 && inptr[DCTSIZE*7] == 0) {
  172687. /* AC terms all zero; we need not examine terms 2,4,6 for 2x2 output */
  172688. int dcval = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]) << PASS1_BITS;
  172689. wsptr[DCTSIZE*0] = dcval;
  172690. wsptr[DCTSIZE*1] = dcval;
  172691. continue;
  172692. }
  172693. /* Even part */
  172694. z1 = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]);
  172695. tmp10 = z1 << (CONST_BITS+2);
  172696. /* Odd part */
  172697. z1 = DEQUANTIZE(inptr[DCTSIZE*7], quantptr[DCTSIZE*7]);
  172698. tmp0 = MULTIPLY(z1, - FIX_0_720959822); /* sqrt(2) * (c7-c5+c3-c1) */
  172699. z1 = DEQUANTIZE(inptr[DCTSIZE*5], quantptr[DCTSIZE*5]);
  172700. tmp0 += MULTIPLY(z1, FIX_0_850430095); /* sqrt(2) * (-c1+c3+c5+c7) */
  172701. z1 = DEQUANTIZE(inptr[DCTSIZE*3], quantptr[DCTSIZE*3]);
  172702. tmp0 += MULTIPLY(z1, - FIX_1_272758580); /* sqrt(2) * (-c1+c3-c5-c7) */
  172703. z1 = DEQUANTIZE(inptr[DCTSIZE*1], quantptr[DCTSIZE*1]);
  172704. tmp0 += MULTIPLY(z1, FIX_3_624509785); /* sqrt(2) * (c1+c3+c5+c7) */
  172705. /* Final output stage */
  172706. wsptr[DCTSIZE*0] = (int) DESCALE(tmp10 + tmp0, CONST_BITS-PASS1_BITS+2);
  172707. wsptr[DCTSIZE*1] = (int) DESCALE(tmp10 - tmp0, CONST_BITS-PASS1_BITS+2);
  172708. }
  172709. /* Pass 2: process 2 rows from work array, store into output array. */
  172710. wsptr = workspace;
  172711. for (ctr = 0; ctr < 2; ctr++) {
  172712. outptr = output_buf[ctr] + output_col;
  172713. /* It's not clear whether a zero row test is worthwhile here ... */
  172714. #ifndef NO_ZERO_ROW_TEST
  172715. if (wsptr[1] == 0 && wsptr[3] == 0 && wsptr[5] == 0 && wsptr[7] == 0) {
  172716. /* AC terms all zero */
  172717. JSAMPLE dcval = range_limit[(int) DESCALE((INT32) wsptr[0], PASS1_BITS+3)
  172718. & RANGE_MASK];
  172719. outptr[0] = dcval;
  172720. outptr[1] = dcval;
  172721. wsptr += DCTSIZE; /* advance pointer to next row */
  172722. continue;
  172723. }
  172724. #endif
  172725. /* Even part */
  172726. tmp10 = ((INT32) wsptr[0]) << (CONST_BITS+2);
  172727. /* Odd part */
  172728. tmp0 = MULTIPLY((INT32) wsptr[7], - FIX_0_720959822) /* sqrt(2) * (c7-c5+c3-c1) */
  172729. + MULTIPLY((INT32) wsptr[5], FIX_0_850430095) /* sqrt(2) * (-c1+c3+c5+c7) */
  172730. + MULTIPLY((INT32) wsptr[3], - FIX_1_272758580) /* sqrt(2) * (-c1+c3-c5-c7) */
  172731. + MULTIPLY((INT32) wsptr[1], FIX_3_624509785); /* sqrt(2) * (c1+c3+c5+c7) */
  172732. /* Final output stage */
  172733. outptr[0] = range_limit[(int) DESCALE(tmp10 + tmp0,
  172734. CONST_BITS+PASS1_BITS+3+2)
  172735. & RANGE_MASK];
  172736. outptr[1] = range_limit[(int) DESCALE(tmp10 - tmp0,
  172737. CONST_BITS+PASS1_BITS+3+2)
  172738. & RANGE_MASK];
  172739. wsptr += DCTSIZE; /* advance pointer to next row */
  172740. }
  172741. }
  172742. /*
  172743. * Perform dequantization and inverse DCT on one block of coefficients,
  172744. * producing a reduced-size 1x1 output block.
  172745. */
  172746. GLOBAL(void)
  172747. jpeg_idct_1x1 (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  172748. JCOEFPTR coef_block,
  172749. JSAMPARRAY output_buf, JDIMENSION output_col)
  172750. {
  172751. int dcval;
  172752. ISLOW_MULT_TYPE * quantptr;
  172753. JSAMPLE *range_limit = IDCT_range_limit(cinfo);
  172754. SHIFT_TEMPS
  172755. /* We hardly need an inverse DCT routine for this: just take the
  172756. * average pixel value, which is one-eighth of the DC coefficient.
  172757. */
  172758. quantptr = (ISLOW_MULT_TYPE *) compptr->dct_table;
  172759. dcval = DEQUANTIZE(coef_block[0], quantptr[0]);
  172760. dcval = (int) DESCALE((INT32) dcval, 3);
  172761. output_buf[0][output_col] = range_limit[dcval & RANGE_MASK];
  172762. }
  172763. #endif /* IDCT_SCALING_SUPPORTED */
  172764. /*** End of inlined file: jidctred.c ***/
  172765. /*** Start of inlined file: jmemmgr.c ***/
  172766. #define JPEG_INTERNALS
  172767. #define AM_MEMORY_MANAGER /* we define jvirt_Xarray_control structs */
  172768. /*** Start of inlined file: jmemsys.h ***/
  172769. #ifndef __jmemsys_h__
  172770. #define __jmemsys_h__
  172771. /* Short forms of external names for systems with brain-damaged linkers. */
  172772. #ifdef NEED_SHORT_EXTERNAL_NAMES
  172773. #define jpeg_get_small jGetSmall
  172774. #define jpeg_free_small jFreeSmall
  172775. #define jpeg_get_large jGetLarge
  172776. #define jpeg_free_large jFreeLarge
  172777. #define jpeg_mem_available jMemAvail
  172778. #define jpeg_open_backing_store jOpenBackStore
  172779. #define jpeg_mem_init jMemInit
  172780. #define jpeg_mem_term jMemTerm
  172781. #endif /* NEED_SHORT_EXTERNAL_NAMES */
  172782. /*
  172783. * These two functions are used to allocate and release small chunks of
  172784. * memory. (Typically the total amount requested through jpeg_get_small is
  172785. * no more than 20K or so; this will be requested in chunks of a few K each.)
  172786. * Behavior should be the same as for the standard library functions malloc
  172787. * and free; in particular, jpeg_get_small must return NULL on failure.
  172788. * On most systems, these ARE malloc and free. jpeg_free_small is passed the
  172789. * size of the object being freed, just in case it's needed.
  172790. * On an 80x86 machine using small-data memory model, these manage near heap.
  172791. */
  172792. EXTERN(void *) jpeg_get_small JPP((j_common_ptr cinfo, size_t sizeofobject));
  172793. EXTERN(void) jpeg_free_small JPP((j_common_ptr cinfo, void * object,
  172794. size_t sizeofobject));
  172795. /*
  172796. * These two functions are used to allocate and release large chunks of
  172797. * memory (up to the total free space designated by jpeg_mem_available).
  172798. * The interface is the same as above, except that on an 80x86 machine,
  172799. * far pointers are used. On most other machines these are identical to
  172800. * the jpeg_get/free_small routines; but we keep them separate anyway,
  172801. * in case a different allocation strategy is desirable for large chunks.
  172802. */
  172803. EXTERN(void FAR *) jpeg_get_large JPP((j_common_ptr cinfo,
  172804. size_t sizeofobject));
  172805. EXTERN(void) jpeg_free_large JPP((j_common_ptr cinfo, void FAR * object,
  172806. size_t sizeofobject));
  172807. /*
  172808. * The macro MAX_ALLOC_CHUNK designates the maximum number of bytes that may
  172809. * be requested in a single call to jpeg_get_large (and jpeg_get_small for that
  172810. * matter, but that case should never come into play). This macro is needed
  172811. * to model the 64Kb-segment-size limit of far addressing on 80x86 machines.
  172812. * On those machines, we expect that jconfig.h will provide a proper value.
  172813. * On machines with 32-bit flat address spaces, any large constant may be used.
  172814. *
  172815. * NB: jmemmgr.c expects that MAX_ALLOC_CHUNK will be representable as type
  172816. * size_t and will be a multiple of sizeof(align_type).
  172817. */
  172818. #ifndef MAX_ALLOC_CHUNK /* may be overridden in jconfig.h */
  172819. #define MAX_ALLOC_CHUNK 1000000000L
  172820. #endif
  172821. /*
  172822. * This routine computes the total space still available for allocation by
  172823. * jpeg_get_large. If more space than this is needed, backing store will be
  172824. * used. NOTE: any memory already allocated must not be counted.
  172825. *
  172826. * There is a minimum space requirement, corresponding to the minimum
  172827. * feasible buffer sizes; jmemmgr.c will request that much space even if
  172828. * jpeg_mem_available returns zero. The maximum space needed, enough to hold
  172829. * all working storage in memory, is also passed in case it is useful.
  172830. * Finally, the total space already allocated is passed. If no better
  172831. * method is available, cinfo->mem->max_memory_to_use - already_allocated
  172832. * is often a suitable calculation.
  172833. *
  172834. * It is OK for jpeg_mem_available to underestimate the space available
  172835. * (that'll just lead to more backing-store access than is really necessary).
  172836. * However, an overestimate will lead to failure. Hence it's wise to subtract
  172837. * a slop factor from the true available space. 5% should be enough.
  172838. *
  172839. * On machines with lots of virtual memory, any large constant may be returned.
  172840. * Conversely, zero may be returned to always use the minimum amount of memory.
  172841. */
  172842. EXTERN(long) jpeg_mem_available JPP((j_common_ptr cinfo,
  172843. long min_bytes_needed,
  172844. long max_bytes_needed,
  172845. long already_allocated));
  172846. /*
  172847. * This structure holds whatever state is needed to access a single
  172848. * backing-store object. The read/write/close method pointers are called
  172849. * by jmemmgr.c to manipulate the backing-store object; all other fields
  172850. * are private to the system-dependent backing store routines.
  172851. */
  172852. #define TEMP_NAME_LENGTH 64 /* max length of a temporary file's name */
  172853. #ifdef USE_MSDOS_MEMMGR /* DOS-specific junk */
  172854. typedef unsigned short XMSH; /* type of extended-memory handles */
  172855. typedef unsigned short EMSH; /* type of expanded-memory handles */
  172856. typedef union {
  172857. short file_handle; /* DOS file handle if it's a temp file */
  172858. XMSH xms_handle; /* handle if it's a chunk of XMS */
  172859. EMSH ems_handle; /* handle if it's a chunk of EMS */
  172860. } handle_union;
  172861. #endif /* USE_MSDOS_MEMMGR */
  172862. #ifdef USE_MAC_MEMMGR /* Mac-specific junk */
  172863. #include <Files.h>
  172864. #endif /* USE_MAC_MEMMGR */
  172865. //typedef struct backing_store_struct * backing_store_ptr;
  172866. typedef struct backing_store_struct {
  172867. /* Methods for reading/writing/closing this backing-store object */
  172868. JMETHOD(void, read_backing_store, (j_common_ptr cinfo,
  172869. struct backing_store_struct *info,
  172870. void FAR * buffer_address,
  172871. long file_offset, long byte_count));
  172872. JMETHOD(void, write_backing_store, (j_common_ptr cinfo,
  172873. struct backing_store_struct *info,
  172874. void FAR * buffer_address,
  172875. long file_offset, long byte_count));
  172876. JMETHOD(void, close_backing_store, (j_common_ptr cinfo,
  172877. struct backing_store_struct *info));
  172878. /* Private fields for system-dependent backing-store management */
  172879. #ifdef USE_MSDOS_MEMMGR
  172880. /* For the MS-DOS manager (jmemdos.c), we need: */
  172881. handle_union handle; /* reference to backing-store storage object */
  172882. char temp_name[TEMP_NAME_LENGTH]; /* name if it's a file */
  172883. #else
  172884. #ifdef USE_MAC_MEMMGR
  172885. /* For the Mac manager (jmemmac.c), we need: */
  172886. short temp_file; /* file reference number to temp file */
  172887. FSSpec tempSpec; /* the FSSpec for the temp file */
  172888. char temp_name[TEMP_NAME_LENGTH]; /* name if it's a file */
  172889. #else
  172890. /* For a typical implementation with temp files, we need: */
  172891. FILE * temp_file; /* stdio reference to temp file */
  172892. char temp_name[TEMP_NAME_LENGTH]; /* name of temp file */
  172893. #endif
  172894. #endif
  172895. } backing_store_info;
  172896. /*
  172897. * Initial opening of a backing-store object. This must fill in the
  172898. * read/write/close pointers in the object. The read/write routines
  172899. * may take an error exit if the specified maximum file size is exceeded.
  172900. * (If jpeg_mem_available always returns a large value, this routine can
  172901. * just take an error exit.)
  172902. */
  172903. EXTERN(void) jpeg_open_backing_store JPP((j_common_ptr cinfo,
  172904. struct backing_store_struct *info,
  172905. long total_bytes_needed));
  172906. /*
  172907. * These routines take care of any system-dependent initialization and
  172908. * cleanup required. jpeg_mem_init will be called before anything is
  172909. * allocated (and, therefore, nothing in cinfo is of use except the error
  172910. * manager pointer). It should return a suitable default value for
  172911. * max_memory_to_use; this may subsequently be overridden by the surrounding
  172912. * application. (Note that max_memory_to_use is only important if
  172913. * jpeg_mem_available chooses to consult it ... no one else will.)
  172914. * jpeg_mem_term may assume that all requested memory has been freed and that
  172915. * all opened backing-store objects have been closed.
  172916. */
  172917. EXTERN(long) jpeg_mem_init JPP((j_common_ptr cinfo));
  172918. EXTERN(void) jpeg_mem_term JPP((j_common_ptr cinfo));
  172919. #endif
  172920. /*** End of inlined file: jmemsys.h ***/
  172921. /* import the system-dependent declarations */
  172922. #ifndef NO_GETENV
  172923. #ifndef HAVE_STDLIB_H /* <stdlib.h> should declare getenv() */
  172924. extern char * getenv JPP((const char * name));
  172925. #endif
  172926. #endif
  172927. /*
  172928. * Some important notes:
  172929. * The allocation routines provided here must never return NULL.
  172930. * They should exit to error_exit if unsuccessful.
  172931. *
  172932. * It's not a good idea to try to merge the sarray and barray routines,
  172933. * even though they are textually almost the same, because samples are
  172934. * usually stored as bytes while coefficients are shorts or ints. Thus,
  172935. * in machines where byte pointers have a different representation from
  172936. * word pointers, the resulting machine code could not be the same.
  172937. */
  172938. /*
  172939. * Many machines require storage alignment: longs must start on 4-byte
  172940. * boundaries, doubles on 8-byte boundaries, etc. On such machines, malloc()
  172941. * always returns pointers that are multiples of the worst-case alignment
  172942. * requirement, and we had better do so too.
  172943. * There isn't any really portable way to determine the worst-case alignment
  172944. * requirement. This module assumes that the alignment requirement is
  172945. * multiples of sizeof(ALIGN_TYPE).
  172946. * By default, we define ALIGN_TYPE as double. This is necessary on some
  172947. * workstations (where doubles really do need 8-byte alignment) and will work
  172948. * fine on nearly everything. If your machine has lesser alignment needs,
  172949. * you can save a few bytes by making ALIGN_TYPE smaller.
  172950. * The only place I know of where this will NOT work is certain Macintosh
  172951. * 680x0 compilers that define double as a 10-byte IEEE extended float.
  172952. * Doing 10-byte alignment is counterproductive because longwords won't be
  172953. * aligned well. Put "#define ALIGN_TYPE long" in jconfig.h if you have
  172954. * such a compiler.
  172955. */
  172956. #ifndef ALIGN_TYPE /* so can override from jconfig.h */
  172957. #define ALIGN_TYPE double
  172958. #endif
  172959. /*
  172960. * We allocate objects from "pools", where each pool is gotten with a single
  172961. * request to jpeg_get_small() or jpeg_get_large(). There is no per-object
  172962. * overhead within a pool, except for alignment padding. Each pool has a
  172963. * header with a link to the next pool of the same class.
  172964. * Small and large pool headers are identical except that the latter's
  172965. * link pointer must be FAR on 80x86 machines.
  172966. * Notice that the "real" header fields are union'ed with a dummy ALIGN_TYPE
  172967. * field. This forces the compiler to make SIZEOF(small_pool_hdr) a multiple
  172968. * of the alignment requirement of ALIGN_TYPE.
  172969. */
  172970. typedef union small_pool_struct * small_pool_ptr;
  172971. typedef union small_pool_struct {
  172972. struct {
  172973. small_pool_ptr next; /* next in list of pools */
  172974. size_t bytes_used; /* how many bytes already used within pool */
  172975. size_t bytes_left; /* bytes still available in this pool */
  172976. } hdr;
  172977. ALIGN_TYPE dummy; /* included in union to ensure alignment */
  172978. } small_pool_hdr;
  172979. typedef union large_pool_struct FAR * large_pool_ptr;
  172980. typedef union large_pool_struct {
  172981. struct {
  172982. large_pool_ptr next; /* next in list of pools */
  172983. size_t bytes_used; /* how many bytes already used within pool */
  172984. size_t bytes_left; /* bytes still available in this pool */
  172985. } hdr;
  172986. ALIGN_TYPE dummy; /* included in union to ensure alignment */
  172987. } large_pool_hdr;
  172988. /*
  172989. * Here is the full definition of a memory manager object.
  172990. */
  172991. typedef struct {
  172992. struct jpeg_memory_mgr pub; /* public fields */
  172993. /* Each pool identifier (lifetime class) names a linked list of pools. */
  172994. small_pool_ptr small_list[JPOOL_NUMPOOLS];
  172995. large_pool_ptr large_list[JPOOL_NUMPOOLS];
  172996. /* Since we only have one lifetime class of virtual arrays, only one
  172997. * linked list is necessary (for each datatype). Note that the virtual
  172998. * array control blocks being linked together are actually stored somewhere
  172999. * in the small-pool list.
  173000. */
  173001. jvirt_sarray_ptr virt_sarray_list;
  173002. jvirt_barray_ptr virt_barray_list;
  173003. /* This counts total space obtained from jpeg_get_small/large */
  173004. long total_space_allocated;
  173005. /* alloc_sarray and alloc_barray set this value for use by virtual
  173006. * array routines.
  173007. */
  173008. JDIMENSION last_rowsperchunk; /* from most recent alloc_sarray/barray */
  173009. } my_memory_mgr;
  173010. typedef my_memory_mgr * my_mem_ptr;
  173011. /*
  173012. * The control blocks for virtual arrays.
  173013. * Note that these blocks are allocated in the "small" pool area.
  173014. * System-dependent info for the associated backing store (if any) is hidden
  173015. * inside the backing_store_info struct.
  173016. */
  173017. struct jvirt_sarray_control {
  173018. JSAMPARRAY mem_buffer; /* => the in-memory buffer */
  173019. JDIMENSION rows_in_array; /* total virtual array height */
  173020. JDIMENSION samplesperrow; /* width of array (and of memory buffer) */
  173021. JDIMENSION maxaccess; /* max rows accessed by access_virt_sarray */
  173022. JDIMENSION rows_in_mem; /* height of memory buffer */
  173023. JDIMENSION rowsperchunk; /* allocation chunk size in mem_buffer */
  173024. JDIMENSION cur_start_row; /* first logical row # in the buffer */
  173025. JDIMENSION first_undef_row; /* row # of first uninitialized row */
  173026. boolean pre_zero; /* pre-zero mode requested? */
  173027. boolean dirty; /* do current buffer contents need written? */
  173028. boolean b_s_open; /* is backing-store data valid? */
  173029. jvirt_sarray_ptr next; /* link to next virtual sarray control block */
  173030. backing_store_info b_s_info; /* System-dependent control info */
  173031. };
  173032. struct jvirt_barray_control {
  173033. JBLOCKARRAY mem_buffer; /* => the in-memory buffer */
  173034. JDIMENSION rows_in_array; /* total virtual array height */
  173035. JDIMENSION blocksperrow; /* width of array (and of memory buffer) */
  173036. JDIMENSION maxaccess; /* max rows accessed by access_virt_barray */
  173037. JDIMENSION rows_in_mem; /* height of memory buffer */
  173038. JDIMENSION rowsperchunk; /* allocation chunk size in mem_buffer */
  173039. JDIMENSION cur_start_row; /* first logical row # in the buffer */
  173040. JDIMENSION first_undef_row; /* row # of first uninitialized row */
  173041. boolean pre_zero; /* pre-zero mode requested? */
  173042. boolean dirty; /* do current buffer contents need written? */
  173043. boolean b_s_open; /* is backing-store data valid? */
  173044. jvirt_barray_ptr next; /* link to next virtual barray control block */
  173045. backing_store_info b_s_info; /* System-dependent control info */
  173046. };
  173047. #ifdef MEM_STATS /* optional extra stuff for statistics */
  173048. LOCAL(void)
  173049. print_mem_stats (j_common_ptr cinfo, int pool_id)
  173050. {
  173051. my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
  173052. small_pool_ptr shdr_ptr;
  173053. large_pool_ptr lhdr_ptr;
  173054. /* Since this is only a debugging stub, we can cheat a little by using
  173055. * fprintf directly rather than going through the trace message code.
  173056. * This is helpful because message parm array can't handle longs.
  173057. */
  173058. fprintf(stderr, "Freeing pool %d, total space = %ld\n",
  173059. pool_id, mem->total_space_allocated);
  173060. for (lhdr_ptr = mem->large_list[pool_id]; lhdr_ptr != NULL;
  173061. lhdr_ptr = lhdr_ptr->hdr.next) {
  173062. fprintf(stderr, " Large chunk used %ld\n",
  173063. (long) lhdr_ptr->hdr.bytes_used);
  173064. }
  173065. for (shdr_ptr = mem->small_list[pool_id]; shdr_ptr != NULL;
  173066. shdr_ptr = shdr_ptr->hdr.next) {
  173067. fprintf(stderr, " Small chunk used %ld free %ld\n",
  173068. (long) shdr_ptr->hdr.bytes_used,
  173069. (long) shdr_ptr->hdr.bytes_left);
  173070. }
  173071. }
  173072. #endif /* MEM_STATS */
  173073. LOCAL(void)
  173074. out_of_memory (j_common_ptr cinfo, int which)
  173075. /* Report an out-of-memory error and stop execution */
  173076. /* If we compiled MEM_STATS support, report alloc requests before dying */
  173077. {
  173078. #ifdef MEM_STATS
  173079. cinfo->err->trace_level = 2; /* force self_destruct to report stats */
  173080. #endif
  173081. ERREXIT1(cinfo, JERR_OUT_OF_MEMORY, which);
  173082. }
  173083. /*
  173084. * Allocation of "small" objects.
  173085. *
  173086. * For these, we use pooled storage. When a new pool must be created,
  173087. * we try to get enough space for the current request plus a "slop" factor,
  173088. * where the slop will be the amount of leftover space in the new pool.
  173089. * The speed vs. space tradeoff is largely determined by the slop values.
  173090. * A different slop value is provided for each pool class (lifetime),
  173091. * and we also distinguish the first pool of a class from later ones.
  173092. * NOTE: the values given work fairly well on both 16- and 32-bit-int
  173093. * machines, but may be too small if longs are 64 bits or more.
  173094. */
  173095. static const size_t first_pool_slop[JPOOL_NUMPOOLS] =
  173096. {
  173097. 1600, /* first PERMANENT pool */
  173098. 16000 /* first IMAGE pool */
  173099. };
  173100. static const size_t extra_pool_slop[JPOOL_NUMPOOLS] =
  173101. {
  173102. 0, /* additional PERMANENT pools */
  173103. 5000 /* additional IMAGE pools */
  173104. };
  173105. #define MIN_SLOP 50 /* greater than 0 to avoid futile looping */
  173106. METHODDEF(void *)
  173107. alloc_small (j_common_ptr cinfo, int pool_id, size_t sizeofobject)
  173108. /* Allocate a "small" object */
  173109. {
  173110. my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
  173111. small_pool_ptr hdr_ptr, prev_hdr_ptr;
  173112. char * data_ptr;
  173113. size_t odd_bytes, min_request, slop;
  173114. /* Check for unsatisfiable request (do now to ensure no overflow below) */
  173115. if (sizeofobject > (size_t) (MAX_ALLOC_CHUNK-SIZEOF(small_pool_hdr)))
  173116. out_of_memory(cinfo, 1); /* request exceeds malloc's ability */
  173117. /* Round up the requested size to a multiple of SIZEOF(ALIGN_TYPE) */
  173118. odd_bytes = sizeofobject % SIZEOF(ALIGN_TYPE);
  173119. if (odd_bytes > 0)
  173120. sizeofobject += SIZEOF(ALIGN_TYPE) - odd_bytes;
  173121. /* See if space is available in any existing pool */
  173122. if (pool_id < 0 || pool_id >= JPOOL_NUMPOOLS)
  173123. ERREXIT1(cinfo, JERR_BAD_POOL_ID, pool_id); /* safety check */
  173124. prev_hdr_ptr = NULL;
  173125. hdr_ptr = mem->small_list[pool_id];
  173126. while (hdr_ptr != NULL) {
  173127. if (hdr_ptr->hdr.bytes_left >= sizeofobject)
  173128. break; /* found pool with enough space */
  173129. prev_hdr_ptr = hdr_ptr;
  173130. hdr_ptr = hdr_ptr->hdr.next;
  173131. }
  173132. /* Time to make a new pool? */
  173133. if (hdr_ptr == NULL) {
  173134. /* min_request is what we need now, slop is what will be leftover */
  173135. min_request = sizeofobject + SIZEOF(small_pool_hdr);
  173136. if (prev_hdr_ptr == NULL) /* first pool in class? */
  173137. slop = first_pool_slop[pool_id];
  173138. else
  173139. slop = extra_pool_slop[pool_id];
  173140. /* Don't ask for more than MAX_ALLOC_CHUNK */
  173141. if (slop > (size_t) (MAX_ALLOC_CHUNK-min_request))
  173142. slop = (size_t) (MAX_ALLOC_CHUNK-min_request);
  173143. /* Try to get space, if fail reduce slop and try again */
  173144. for (;;) {
  173145. hdr_ptr = (small_pool_ptr) jpeg_get_small(cinfo, min_request + slop);
  173146. if (hdr_ptr != NULL)
  173147. break;
  173148. slop /= 2;
  173149. if (slop < MIN_SLOP) /* give up when it gets real small */
  173150. out_of_memory(cinfo, 2); /* jpeg_get_small failed */
  173151. }
  173152. mem->total_space_allocated += min_request + slop;
  173153. /* Success, initialize the new pool header and add to end of list */
  173154. hdr_ptr->hdr.next = NULL;
  173155. hdr_ptr->hdr.bytes_used = 0;
  173156. hdr_ptr->hdr.bytes_left = sizeofobject + slop;
  173157. if (prev_hdr_ptr == NULL) /* first pool in class? */
  173158. mem->small_list[pool_id] = hdr_ptr;
  173159. else
  173160. prev_hdr_ptr->hdr.next = hdr_ptr;
  173161. }
  173162. /* OK, allocate the object from the current pool */
  173163. data_ptr = (char *) (hdr_ptr + 1); /* point to first data byte in pool */
  173164. data_ptr += hdr_ptr->hdr.bytes_used; /* point to place for object */
  173165. hdr_ptr->hdr.bytes_used += sizeofobject;
  173166. hdr_ptr->hdr.bytes_left -= sizeofobject;
  173167. return (void *) data_ptr;
  173168. }
  173169. /*
  173170. * Allocation of "large" objects.
  173171. *
  173172. * The external semantics of these are the same as "small" objects,
  173173. * except that FAR pointers are used on 80x86. However the pool
  173174. * management heuristics are quite different. We assume that each
  173175. * request is large enough that it may as well be passed directly to
  173176. * jpeg_get_large; the pool management just links everything together
  173177. * so that we can free it all on demand.
  173178. * Note: the major use of "large" objects is in JSAMPARRAY and JBLOCKARRAY
  173179. * structures. The routines that create these structures (see below)
  173180. * deliberately bunch rows together to ensure a large request size.
  173181. */
  173182. METHODDEF(void FAR *)
  173183. alloc_large (j_common_ptr cinfo, int pool_id, size_t sizeofobject)
  173184. /* Allocate a "large" object */
  173185. {
  173186. my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
  173187. large_pool_ptr hdr_ptr;
  173188. size_t odd_bytes;
  173189. /* Check for unsatisfiable request (do now to ensure no overflow below) */
  173190. if (sizeofobject > (size_t) (MAX_ALLOC_CHUNK-SIZEOF(large_pool_hdr)))
  173191. out_of_memory(cinfo, 3); /* request exceeds malloc's ability */
  173192. /* Round up the requested size to a multiple of SIZEOF(ALIGN_TYPE) */
  173193. odd_bytes = sizeofobject % SIZEOF(ALIGN_TYPE);
  173194. if (odd_bytes > 0)
  173195. sizeofobject += SIZEOF(ALIGN_TYPE) - odd_bytes;
  173196. /* Always make a new pool */
  173197. if (pool_id < 0 || pool_id >= JPOOL_NUMPOOLS)
  173198. ERREXIT1(cinfo, JERR_BAD_POOL_ID, pool_id); /* safety check */
  173199. hdr_ptr = (large_pool_ptr) jpeg_get_large(cinfo, sizeofobject +
  173200. SIZEOF(large_pool_hdr));
  173201. if (hdr_ptr == NULL)
  173202. out_of_memory(cinfo, 4); /* jpeg_get_large failed */
  173203. mem->total_space_allocated += sizeofobject + SIZEOF(large_pool_hdr);
  173204. /* Success, initialize the new pool header and add to list */
  173205. hdr_ptr->hdr.next = mem->large_list[pool_id];
  173206. /* We maintain space counts in each pool header for statistical purposes,
  173207. * even though they are not needed for allocation.
  173208. */
  173209. hdr_ptr->hdr.bytes_used = sizeofobject;
  173210. hdr_ptr->hdr.bytes_left = 0;
  173211. mem->large_list[pool_id] = hdr_ptr;
  173212. return (void FAR *) (hdr_ptr + 1); /* point to first data byte in pool */
  173213. }
  173214. /*
  173215. * Creation of 2-D sample arrays.
  173216. * The pointers are in near heap, the samples themselves in FAR heap.
  173217. *
  173218. * To minimize allocation overhead and to allow I/O of large contiguous
  173219. * blocks, we allocate the sample rows in groups of as many rows as possible
  173220. * without exceeding MAX_ALLOC_CHUNK total bytes per allocation request.
  173221. * NB: the virtual array control routines, later in this file, know about
  173222. * this chunking of rows. The rowsperchunk value is left in the mem manager
  173223. * object so that it can be saved away if this sarray is the workspace for
  173224. * a virtual array.
  173225. */
  173226. METHODDEF(JSAMPARRAY)
  173227. alloc_sarray (j_common_ptr cinfo, int pool_id,
  173228. JDIMENSION samplesperrow, JDIMENSION numrows)
  173229. /* Allocate a 2-D sample array */
  173230. {
  173231. my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
  173232. JSAMPARRAY result;
  173233. JSAMPROW workspace;
  173234. JDIMENSION rowsperchunk, currow, i;
  173235. long ltemp;
  173236. /* Calculate max # of rows allowed in one allocation chunk */
  173237. ltemp = (MAX_ALLOC_CHUNK-SIZEOF(large_pool_hdr)) /
  173238. ((long) samplesperrow * SIZEOF(JSAMPLE));
  173239. if (ltemp <= 0)
  173240. ERREXIT(cinfo, JERR_WIDTH_OVERFLOW);
  173241. if (ltemp < (long) numrows)
  173242. rowsperchunk = (JDIMENSION) ltemp;
  173243. else
  173244. rowsperchunk = numrows;
  173245. mem->last_rowsperchunk = rowsperchunk;
  173246. /* Get space for row pointers (small object) */
  173247. result = (JSAMPARRAY) alloc_small(cinfo, pool_id,
  173248. (size_t) (numrows * SIZEOF(JSAMPROW)));
  173249. /* Get the rows themselves (large objects) */
  173250. currow = 0;
  173251. while (currow < numrows) {
  173252. rowsperchunk = MIN(rowsperchunk, numrows - currow);
  173253. workspace = (JSAMPROW) alloc_large(cinfo, pool_id,
  173254. (size_t) ((size_t) rowsperchunk * (size_t) samplesperrow
  173255. * SIZEOF(JSAMPLE)));
  173256. for (i = rowsperchunk; i > 0; i--) {
  173257. result[currow++] = workspace;
  173258. workspace += samplesperrow;
  173259. }
  173260. }
  173261. return result;
  173262. }
  173263. /*
  173264. * Creation of 2-D coefficient-block arrays.
  173265. * This is essentially the same as the code for sample arrays, above.
  173266. */
  173267. METHODDEF(JBLOCKARRAY)
  173268. alloc_barray (j_common_ptr cinfo, int pool_id,
  173269. JDIMENSION blocksperrow, JDIMENSION numrows)
  173270. /* Allocate a 2-D coefficient-block array */
  173271. {
  173272. my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
  173273. JBLOCKARRAY result;
  173274. JBLOCKROW workspace;
  173275. JDIMENSION rowsperchunk, currow, i;
  173276. long ltemp;
  173277. /* Calculate max # of rows allowed in one allocation chunk */
  173278. ltemp = (MAX_ALLOC_CHUNK-SIZEOF(large_pool_hdr)) /
  173279. ((long) blocksperrow * SIZEOF(JBLOCK));
  173280. if (ltemp <= 0)
  173281. ERREXIT(cinfo, JERR_WIDTH_OVERFLOW);
  173282. if (ltemp < (long) numrows)
  173283. rowsperchunk = (JDIMENSION) ltemp;
  173284. else
  173285. rowsperchunk = numrows;
  173286. mem->last_rowsperchunk = rowsperchunk;
  173287. /* Get space for row pointers (small object) */
  173288. result = (JBLOCKARRAY) alloc_small(cinfo, pool_id,
  173289. (size_t) (numrows * SIZEOF(JBLOCKROW)));
  173290. /* Get the rows themselves (large objects) */
  173291. currow = 0;
  173292. while (currow < numrows) {
  173293. rowsperchunk = MIN(rowsperchunk, numrows - currow);
  173294. workspace = (JBLOCKROW) alloc_large(cinfo, pool_id,
  173295. (size_t) ((size_t) rowsperchunk * (size_t) blocksperrow
  173296. * SIZEOF(JBLOCK)));
  173297. for (i = rowsperchunk; i > 0; i--) {
  173298. result[currow++] = workspace;
  173299. workspace += blocksperrow;
  173300. }
  173301. }
  173302. return result;
  173303. }
  173304. /*
  173305. * About virtual array management:
  173306. *
  173307. * The above "normal" array routines are only used to allocate strip buffers
  173308. * (as wide as the image, but just a few rows high). Full-image-sized buffers
  173309. * are handled as "virtual" arrays. The array is still accessed a strip at a
  173310. * time, but the memory manager must save the whole array for repeated
  173311. * accesses. The intended implementation is that there is a strip buffer in
  173312. * memory (as high as is possible given the desired memory limit), plus a
  173313. * backing file that holds the rest of the array.
  173314. *
  173315. * The request_virt_array routines are told the total size of the image and
  173316. * the maximum number of rows that will be accessed at once. The in-memory
  173317. * buffer must be at least as large as the maxaccess value.
  173318. *
  173319. * The request routines create control blocks but not the in-memory buffers.
  173320. * That is postponed until realize_virt_arrays is called. At that time the
  173321. * total amount of space needed is known (approximately, anyway), so free
  173322. * memory can be divided up fairly.
  173323. *
  173324. * The access_virt_array routines are responsible for making a specific strip
  173325. * area accessible (after reading or writing the backing file, if necessary).
  173326. * Note that the access routines are told whether the caller intends to modify
  173327. * the accessed strip; during a read-only pass this saves having to rewrite
  173328. * data to disk. The access routines are also responsible for pre-zeroing
  173329. * any newly accessed rows, if pre-zeroing was requested.
  173330. *
  173331. * In current usage, the access requests are usually for nonoverlapping
  173332. * strips; that is, successive access start_row numbers differ by exactly
  173333. * num_rows = maxaccess. This means we can get good performance with simple
  173334. * buffer dump/reload logic, by making the in-memory buffer be a multiple
  173335. * of the access height; then there will never be accesses across bufferload
  173336. * boundaries. The code will still work with overlapping access requests,
  173337. * but it doesn't handle bufferload overlaps very efficiently.
  173338. */
  173339. METHODDEF(jvirt_sarray_ptr)
  173340. request_virt_sarray (j_common_ptr cinfo, int pool_id, boolean pre_zero,
  173341. JDIMENSION samplesperrow, JDIMENSION numrows,
  173342. JDIMENSION maxaccess)
  173343. /* Request a virtual 2-D sample array */
  173344. {
  173345. my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
  173346. jvirt_sarray_ptr result;
  173347. /* Only IMAGE-lifetime virtual arrays are currently supported */
  173348. if (pool_id != JPOOL_IMAGE)
  173349. ERREXIT1(cinfo, JERR_BAD_POOL_ID, pool_id); /* safety check */
  173350. /* get control block */
  173351. result = (jvirt_sarray_ptr) alloc_small(cinfo, pool_id,
  173352. SIZEOF(struct jvirt_sarray_control));
  173353. result->mem_buffer = NULL; /* marks array not yet realized */
  173354. result->rows_in_array = numrows;
  173355. result->samplesperrow = samplesperrow;
  173356. result->maxaccess = maxaccess;
  173357. result->pre_zero = pre_zero;
  173358. result->b_s_open = FALSE; /* no associated backing-store object */
  173359. result->next = mem->virt_sarray_list; /* add to list of virtual arrays */
  173360. mem->virt_sarray_list = result;
  173361. return result;
  173362. }
  173363. METHODDEF(jvirt_barray_ptr)
  173364. request_virt_barray (j_common_ptr cinfo, int pool_id, boolean pre_zero,
  173365. JDIMENSION blocksperrow, JDIMENSION numrows,
  173366. JDIMENSION maxaccess)
  173367. /* Request a virtual 2-D coefficient-block array */
  173368. {
  173369. my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
  173370. jvirt_barray_ptr result;
  173371. /* Only IMAGE-lifetime virtual arrays are currently supported */
  173372. if (pool_id != JPOOL_IMAGE)
  173373. ERREXIT1(cinfo, JERR_BAD_POOL_ID, pool_id); /* safety check */
  173374. /* get control block */
  173375. result = (jvirt_barray_ptr) alloc_small(cinfo, pool_id,
  173376. SIZEOF(struct jvirt_barray_control));
  173377. result->mem_buffer = NULL; /* marks array not yet realized */
  173378. result->rows_in_array = numrows;
  173379. result->blocksperrow = blocksperrow;
  173380. result->maxaccess = maxaccess;
  173381. result->pre_zero = pre_zero;
  173382. result->b_s_open = FALSE; /* no associated backing-store object */
  173383. result->next = mem->virt_barray_list; /* add to list of virtual arrays */
  173384. mem->virt_barray_list = result;
  173385. return result;
  173386. }
  173387. METHODDEF(void)
  173388. realize_virt_arrays (j_common_ptr cinfo)
  173389. /* Allocate the in-memory buffers for any unrealized virtual arrays */
  173390. {
  173391. my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
  173392. long space_per_minheight, maximum_space, avail_mem;
  173393. long minheights, max_minheights;
  173394. jvirt_sarray_ptr sptr;
  173395. jvirt_barray_ptr bptr;
  173396. /* Compute the minimum space needed (maxaccess rows in each buffer)
  173397. * and the maximum space needed (full image height in each buffer).
  173398. * These may be of use to the system-dependent jpeg_mem_available routine.
  173399. */
  173400. space_per_minheight = 0;
  173401. maximum_space = 0;
  173402. for (sptr = mem->virt_sarray_list; sptr != NULL; sptr = sptr->next) {
  173403. if (sptr->mem_buffer == NULL) { /* if not realized yet */
  173404. space_per_minheight += (long) sptr->maxaccess *
  173405. (long) sptr->samplesperrow * SIZEOF(JSAMPLE);
  173406. maximum_space += (long) sptr->rows_in_array *
  173407. (long) sptr->samplesperrow * SIZEOF(JSAMPLE);
  173408. }
  173409. }
  173410. for (bptr = mem->virt_barray_list; bptr != NULL; bptr = bptr->next) {
  173411. if (bptr->mem_buffer == NULL) { /* if not realized yet */
  173412. space_per_minheight += (long) bptr->maxaccess *
  173413. (long) bptr->blocksperrow * SIZEOF(JBLOCK);
  173414. maximum_space += (long) bptr->rows_in_array *
  173415. (long) bptr->blocksperrow * SIZEOF(JBLOCK);
  173416. }
  173417. }
  173418. if (space_per_minheight <= 0)
  173419. return; /* no unrealized arrays, no work */
  173420. /* Determine amount of memory to actually use; this is system-dependent. */
  173421. avail_mem = jpeg_mem_available(cinfo, space_per_minheight, maximum_space,
  173422. mem->total_space_allocated);
  173423. /* If the maximum space needed is available, make all the buffers full
  173424. * height; otherwise parcel it out with the same number of minheights
  173425. * in each buffer.
  173426. */
  173427. if (avail_mem >= maximum_space)
  173428. max_minheights = 1000000000L;
  173429. else {
  173430. max_minheights = avail_mem / space_per_minheight;
  173431. /* If there doesn't seem to be enough space, try to get the minimum
  173432. * anyway. This allows a "stub" implementation of jpeg_mem_available().
  173433. */
  173434. if (max_minheights <= 0)
  173435. max_minheights = 1;
  173436. }
  173437. /* Allocate the in-memory buffers and initialize backing store as needed. */
  173438. for (sptr = mem->virt_sarray_list; sptr != NULL; sptr = sptr->next) {
  173439. if (sptr->mem_buffer == NULL) { /* if not realized yet */
  173440. minheights = ((long) sptr->rows_in_array - 1L) / sptr->maxaccess + 1L;
  173441. if (minheights <= max_minheights) {
  173442. /* This buffer fits in memory */
  173443. sptr->rows_in_mem = sptr->rows_in_array;
  173444. } else {
  173445. /* It doesn't fit in memory, create backing store. */
  173446. sptr->rows_in_mem = (JDIMENSION) (max_minheights * sptr->maxaccess);
  173447. jpeg_open_backing_store(cinfo, & sptr->b_s_info,
  173448. (long) sptr->rows_in_array *
  173449. (long) sptr->samplesperrow *
  173450. (long) SIZEOF(JSAMPLE));
  173451. sptr->b_s_open = TRUE;
  173452. }
  173453. sptr->mem_buffer = alloc_sarray(cinfo, JPOOL_IMAGE,
  173454. sptr->samplesperrow, sptr->rows_in_mem);
  173455. sptr->rowsperchunk = mem->last_rowsperchunk;
  173456. sptr->cur_start_row = 0;
  173457. sptr->first_undef_row = 0;
  173458. sptr->dirty = FALSE;
  173459. }
  173460. }
  173461. for (bptr = mem->virt_barray_list; bptr != NULL; bptr = bptr->next) {
  173462. if (bptr->mem_buffer == NULL) { /* if not realized yet */
  173463. minheights = ((long) bptr->rows_in_array - 1L) / bptr->maxaccess + 1L;
  173464. if (minheights <= max_minheights) {
  173465. /* This buffer fits in memory */
  173466. bptr->rows_in_mem = bptr->rows_in_array;
  173467. } else {
  173468. /* It doesn't fit in memory, create backing store. */
  173469. bptr->rows_in_mem = (JDIMENSION) (max_minheights * bptr->maxaccess);
  173470. jpeg_open_backing_store(cinfo, & bptr->b_s_info,
  173471. (long) bptr->rows_in_array *
  173472. (long) bptr->blocksperrow *
  173473. (long) SIZEOF(JBLOCK));
  173474. bptr->b_s_open = TRUE;
  173475. }
  173476. bptr->mem_buffer = alloc_barray(cinfo, JPOOL_IMAGE,
  173477. bptr->blocksperrow, bptr->rows_in_mem);
  173478. bptr->rowsperchunk = mem->last_rowsperchunk;
  173479. bptr->cur_start_row = 0;
  173480. bptr->first_undef_row = 0;
  173481. bptr->dirty = FALSE;
  173482. }
  173483. }
  173484. }
  173485. LOCAL(void)
  173486. do_sarray_io (j_common_ptr cinfo, jvirt_sarray_ptr ptr, boolean writing)
  173487. /* Do backing store read or write of a virtual sample array */
  173488. {
  173489. long bytesperrow, file_offset, byte_count, rows, thisrow, i;
  173490. bytesperrow = (long) ptr->samplesperrow * SIZEOF(JSAMPLE);
  173491. file_offset = ptr->cur_start_row * bytesperrow;
  173492. /* Loop to read or write each allocation chunk in mem_buffer */
  173493. for (i = 0; i < (long) ptr->rows_in_mem; i += ptr->rowsperchunk) {
  173494. /* One chunk, but check for short chunk at end of buffer */
  173495. rows = MIN((long) ptr->rowsperchunk, (long) ptr->rows_in_mem - i);
  173496. /* Transfer no more than is currently defined */
  173497. thisrow = (long) ptr->cur_start_row + i;
  173498. rows = MIN(rows, (long) ptr->first_undef_row - thisrow);
  173499. /* Transfer no more than fits in file */
  173500. rows = MIN(rows, (long) ptr->rows_in_array - thisrow);
  173501. if (rows <= 0) /* this chunk might be past end of file! */
  173502. break;
  173503. byte_count = rows * bytesperrow;
  173504. if (writing)
  173505. (*ptr->b_s_info.write_backing_store) (cinfo, & ptr->b_s_info,
  173506. (void FAR *) ptr->mem_buffer[i],
  173507. file_offset, byte_count);
  173508. else
  173509. (*ptr->b_s_info.read_backing_store) (cinfo, & ptr->b_s_info,
  173510. (void FAR *) ptr->mem_buffer[i],
  173511. file_offset, byte_count);
  173512. file_offset += byte_count;
  173513. }
  173514. }
  173515. LOCAL(void)
  173516. do_barray_io (j_common_ptr cinfo, jvirt_barray_ptr ptr, boolean writing)
  173517. /* Do backing store read or write of a virtual coefficient-block array */
  173518. {
  173519. long bytesperrow, file_offset, byte_count, rows, thisrow, i;
  173520. bytesperrow = (long) ptr->blocksperrow * SIZEOF(JBLOCK);
  173521. file_offset = ptr->cur_start_row * bytesperrow;
  173522. /* Loop to read or write each allocation chunk in mem_buffer */
  173523. for (i = 0; i < (long) ptr->rows_in_mem; i += ptr->rowsperchunk) {
  173524. /* One chunk, but check for short chunk at end of buffer */
  173525. rows = MIN((long) ptr->rowsperchunk, (long) ptr->rows_in_mem - i);
  173526. /* Transfer no more than is currently defined */
  173527. thisrow = (long) ptr->cur_start_row + i;
  173528. rows = MIN(rows, (long) ptr->first_undef_row - thisrow);
  173529. /* Transfer no more than fits in file */
  173530. rows = MIN(rows, (long) ptr->rows_in_array - thisrow);
  173531. if (rows <= 0) /* this chunk might be past end of file! */
  173532. break;
  173533. byte_count = rows * bytesperrow;
  173534. if (writing)
  173535. (*ptr->b_s_info.write_backing_store) (cinfo, & ptr->b_s_info,
  173536. (void FAR *) ptr->mem_buffer[i],
  173537. file_offset, byte_count);
  173538. else
  173539. (*ptr->b_s_info.read_backing_store) (cinfo, & ptr->b_s_info,
  173540. (void FAR *) ptr->mem_buffer[i],
  173541. file_offset, byte_count);
  173542. file_offset += byte_count;
  173543. }
  173544. }
  173545. METHODDEF(JSAMPARRAY)
  173546. access_virt_sarray (j_common_ptr cinfo, jvirt_sarray_ptr ptr,
  173547. JDIMENSION start_row, JDIMENSION num_rows,
  173548. boolean writable)
  173549. /* Access the part of a virtual sample array starting at start_row */
  173550. /* and extending for num_rows rows. writable is true if */
  173551. /* caller intends to modify the accessed area. */
  173552. {
  173553. JDIMENSION end_row = start_row + num_rows;
  173554. JDIMENSION undef_row;
  173555. /* debugging check */
  173556. if (end_row > ptr->rows_in_array || num_rows > ptr->maxaccess ||
  173557. ptr->mem_buffer == NULL)
  173558. ERREXIT(cinfo, JERR_BAD_VIRTUAL_ACCESS);
  173559. /* Make the desired part of the virtual array accessible */
  173560. if (start_row < ptr->cur_start_row ||
  173561. end_row > ptr->cur_start_row+ptr->rows_in_mem) {
  173562. if (! ptr->b_s_open)
  173563. ERREXIT(cinfo, JERR_VIRTUAL_BUG);
  173564. /* Flush old buffer contents if necessary */
  173565. if (ptr->dirty) {
  173566. do_sarray_io(cinfo, ptr, TRUE);
  173567. ptr->dirty = FALSE;
  173568. }
  173569. /* Decide what part of virtual array to access.
  173570. * Algorithm: if target address > current window, assume forward scan,
  173571. * load starting at target address. If target address < current window,
  173572. * assume backward scan, load so that target area is top of window.
  173573. * Note that when switching from forward write to forward read, will have
  173574. * start_row = 0, so the limiting case applies and we load from 0 anyway.
  173575. */
  173576. if (start_row > ptr->cur_start_row) {
  173577. ptr->cur_start_row = start_row;
  173578. } else {
  173579. /* use long arithmetic here to avoid overflow & unsigned problems */
  173580. long ltemp;
  173581. ltemp = (long) end_row - (long) ptr->rows_in_mem;
  173582. if (ltemp < 0)
  173583. ltemp = 0; /* don't fall off front end of file */
  173584. ptr->cur_start_row = (JDIMENSION) ltemp;
  173585. }
  173586. /* Read in the selected part of the array.
  173587. * During the initial write pass, we will do no actual read
  173588. * because the selected part is all undefined.
  173589. */
  173590. do_sarray_io(cinfo, ptr, FALSE);
  173591. }
  173592. /* Ensure the accessed part of the array is defined; prezero if needed.
  173593. * To improve locality of access, we only prezero the part of the array
  173594. * that the caller is about to access, not the entire in-memory array.
  173595. */
  173596. if (ptr->first_undef_row < end_row) {
  173597. if (ptr->first_undef_row < start_row) {
  173598. if (writable) /* writer skipped over a section of array */
  173599. ERREXIT(cinfo, JERR_BAD_VIRTUAL_ACCESS);
  173600. undef_row = start_row; /* but reader is allowed to read ahead */
  173601. } else {
  173602. undef_row = ptr->first_undef_row;
  173603. }
  173604. if (writable)
  173605. ptr->first_undef_row = end_row;
  173606. if (ptr->pre_zero) {
  173607. size_t bytesperrow = (size_t) ptr->samplesperrow * SIZEOF(JSAMPLE);
  173608. undef_row -= ptr->cur_start_row; /* make indexes relative to buffer */
  173609. end_row -= ptr->cur_start_row;
  173610. while (undef_row < end_row) {
  173611. jzero_far((void FAR *) ptr->mem_buffer[undef_row], bytesperrow);
  173612. undef_row++;
  173613. }
  173614. } else {
  173615. if (! writable) /* reader looking at undefined data */
  173616. ERREXIT(cinfo, JERR_BAD_VIRTUAL_ACCESS);
  173617. }
  173618. }
  173619. /* Flag the buffer dirty if caller will write in it */
  173620. if (writable)
  173621. ptr->dirty = TRUE;
  173622. /* Return address of proper part of the buffer */
  173623. return ptr->mem_buffer + (start_row - ptr->cur_start_row);
  173624. }
  173625. METHODDEF(JBLOCKARRAY)
  173626. access_virt_barray (j_common_ptr cinfo, jvirt_barray_ptr ptr,
  173627. JDIMENSION start_row, JDIMENSION num_rows,
  173628. boolean writable)
  173629. /* Access the part of a virtual block array starting at start_row */
  173630. /* and extending for num_rows rows. writable is true if */
  173631. /* caller intends to modify the accessed area. */
  173632. {
  173633. JDIMENSION end_row = start_row + num_rows;
  173634. JDIMENSION undef_row;
  173635. /* debugging check */
  173636. if (end_row > ptr->rows_in_array || num_rows > ptr->maxaccess ||
  173637. ptr->mem_buffer == NULL)
  173638. ERREXIT(cinfo, JERR_BAD_VIRTUAL_ACCESS);
  173639. /* Make the desired part of the virtual array accessible */
  173640. if (start_row < ptr->cur_start_row ||
  173641. end_row > ptr->cur_start_row+ptr->rows_in_mem) {
  173642. if (! ptr->b_s_open)
  173643. ERREXIT(cinfo, JERR_VIRTUAL_BUG);
  173644. /* Flush old buffer contents if necessary */
  173645. if (ptr->dirty) {
  173646. do_barray_io(cinfo, ptr, TRUE);
  173647. ptr->dirty = FALSE;
  173648. }
  173649. /* Decide what part of virtual array to access.
  173650. * Algorithm: if target address > current window, assume forward scan,
  173651. * load starting at target address. If target address < current window,
  173652. * assume backward scan, load so that target area is top of window.
  173653. * Note that when switching from forward write to forward read, will have
  173654. * start_row = 0, so the limiting case applies and we load from 0 anyway.
  173655. */
  173656. if (start_row > ptr->cur_start_row) {
  173657. ptr->cur_start_row = start_row;
  173658. } else {
  173659. /* use long arithmetic here to avoid overflow & unsigned problems */
  173660. long ltemp;
  173661. ltemp = (long) end_row - (long) ptr->rows_in_mem;
  173662. if (ltemp < 0)
  173663. ltemp = 0; /* don't fall off front end of file */
  173664. ptr->cur_start_row = (JDIMENSION) ltemp;
  173665. }
  173666. /* Read in the selected part of the array.
  173667. * During the initial write pass, we will do no actual read
  173668. * because the selected part is all undefined.
  173669. */
  173670. do_barray_io(cinfo, ptr, FALSE);
  173671. }
  173672. /* Ensure the accessed part of the array is defined; prezero if needed.
  173673. * To improve locality of access, we only prezero the part of the array
  173674. * that the caller is about to access, not the entire in-memory array.
  173675. */
  173676. if (ptr->first_undef_row < end_row) {
  173677. if (ptr->first_undef_row < start_row) {
  173678. if (writable) /* writer skipped over a section of array */
  173679. ERREXIT(cinfo, JERR_BAD_VIRTUAL_ACCESS);
  173680. undef_row = start_row; /* but reader is allowed to read ahead */
  173681. } else {
  173682. undef_row = ptr->first_undef_row;
  173683. }
  173684. if (writable)
  173685. ptr->first_undef_row = end_row;
  173686. if (ptr->pre_zero) {
  173687. size_t bytesperrow = (size_t) ptr->blocksperrow * SIZEOF(JBLOCK);
  173688. undef_row -= ptr->cur_start_row; /* make indexes relative to buffer */
  173689. end_row -= ptr->cur_start_row;
  173690. while (undef_row < end_row) {
  173691. jzero_far((void FAR *) ptr->mem_buffer[undef_row], bytesperrow);
  173692. undef_row++;
  173693. }
  173694. } else {
  173695. if (! writable) /* reader looking at undefined data */
  173696. ERREXIT(cinfo, JERR_BAD_VIRTUAL_ACCESS);
  173697. }
  173698. }
  173699. /* Flag the buffer dirty if caller will write in it */
  173700. if (writable)
  173701. ptr->dirty = TRUE;
  173702. /* Return address of proper part of the buffer */
  173703. return ptr->mem_buffer + (start_row - ptr->cur_start_row);
  173704. }
  173705. /*
  173706. * Release all objects belonging to a specified pool.
  173707. */
  173708. METHODDEF(void)
  173709. free_pool (j_common_ptr cinfo, int pool_id)
  173710. {
  173711. my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
  173712. small_pool_ptr shdr_ptr;
  173713. large_pool_ptr lhdr_ptr;
  173714. size_t space_freed;
  173715. if (pool_id < 0 || pool_id >= JPOOL_NUMPOOLS)
  173716. ERREXIT1(cinfo, JERR_BAD_POOL_ID, pool_id); /* safety check */
  173717. #ifdef MEM_STATS
  173718. if (cinfo->err->trace_level > 1)
  173719. print_mem_stats(cinfo, pool_id); /* print pool's memory usage statistics */
  173720. #endif
  173721. /* If freeing IMAGE pool, close any virtual arrays first */
  173722. if (pool_id == JPOOL_IMAGE) {
  173723. jvirt_sarray_ptr sptr;
  173724. jvirt_barray_ptr bptr;
  173725. for (sptr = mem->virt_sarray_list; sptr != NULL; sptr = sptr->next) {
  173726. if (sptr->b_s_open) { /* there may be no backing store */
  173727. sptr->b_s_open = FALSE; /* prevent recursive close if error */
  173728. (*sptr->b_s_info.close_backing_store) (cinfo, & sptr->b_s_info);
  173729. }
  173730. }
  173731. mem->virt_sarray_list = NULL;
  173732. for (bptr = mem->virt_barray_list; bptr != NULL; bptr = bptr->next) {
  173733. if (bptr->b_s_open) { /* there may be no backing store */
  173734. bptr->b_s_open = FALSE; /* prevent recursive close if error */
  173735. (*bptr->b_s_info.close_backing_store) (cinfo, & bptr->b_s_info);
  173736. }
  173737. }
  173738. mem->virt_barray_list = NULL;
  173739. }
  173740. /* Release large objects */
  173741. lhdr_ptr = mem->large_list[pool_id];
  173742. mem->large_list[pool_id] = NULL;
  173743. while (lhdr_ptr != NULL) {
  173744. large_pool_ptr next_lhdr_ptr = lhdr_ptr->hdr.next;
  173745. space_freed = lhdr_ptr->hdr.bytes_used +
  173746. lhdr_ptr->hdr.bytes_left +
  173747. SIZEOF(large_pool_hdr);
  173748. jpeg_free_large(cinfo, (void FAR *) lhdr_ptr, space_freed);
  173749. mem->total_space_allocated -= space_freed;
  173750. lhdr_ptr = next_lhdr_ptr;
  173751. }
  173752. /* Release small objects */
  173753. shdr_ptr = mem->small_list[pool_id];
  173754. mem->small_list[pool_id] = NULL;
  173755. while (shdr_ptr != NULL) {
  173756. small_pool_ptr next_shdr_ptr = shdr_ptr->hdr.next;
  173757. space_freed = shdr_ptr->hdr.bytes_used +
  173758. shdr_ptr->hdr.bytes_left +
  173759. SIZEOF(small_pool_hdr);
  173760. jpeg_free_small(cinfo, (void *) shdr_ptr, space_freed);
  173761. mem->total_space_allocated -= space_freed;
  173762. shdr_ptr = next_shdr_ptr;
  173763. }
  173764. }
  173765. /*
  173766. * Close up shop entirely.
  173767. * Note that this cannot be called unless cinfo->mem is non-NULL.
  173768. */
  173769. METHODDEF(void)
  173770. self_destruct (j_common_ptr cinfo)
  173771. {
  173772. int pool;
  173773. /* Close all backing store, release all memory.
  173774. * Releasing pools in reverse order might help avoid fragmentation
  173775. * with some (brain-damaged) malloc libraries.
  173776. */
  173777. for (pool = JPOOL_NUMPOOLS-1; pool >= JPOOL_PERMANENT; pool--) {
  173778. free_pool(cinfo, pool);
  173779. }
  173780. /* Release the memory manager control block too. */
  173781. jpeg_free_small(cinfo, (void *) cinfo->mem, SIZEOF(my_memory_mgr));
  173782. cinfo->mem = NULL; /* ensures I will be called only once */
  173783. jpeg_mem_term(cinfo); /* system-dependent cleanup */
  173784. }
  173785. /*
  173786. * Memory manager initialization.
  173787. * When this is called, only the error manager pointer is valid in cinfo!
  173788. */
  173789. GLOBAL(void)
  173790. jinit_memory_mgr (j_common_ptr cinfo)
  173791. {
  173792. my_mem_ptr mem;
  173793. long max_to_use;
  173794. int pool;
  173795. size_t test_mac;
  173796. cinfo->mem = NULL; /* for safety if init fails */
  173797. /* Check for configuration errors.
  173798. * SIZEOF(ALIGN_TYPE) should be a power of 2; otherwise, it probably
  173799. * doesn't reflect any real hardware alignment requirement.
  173800. * The test is a little tricky: for X>0, X and X-1 have no one-bits
  173801. * in common if and only if X is a power of 2, ie has only one one-bit.
  173802. * Some compilers may give an "unreachable code" warning here; ignore it.
  173803. */
  173804. if ((SIZEOF(ALIGN_TYPE) & (SIZEOF(ALIGN_TYPE)-1)) != 0)
  173805. ERREXIT(cinfo, JERR_BAD_ALIGN_TYPE);
  173806. /* MAX_ALLOC_CHUNK must be representable as type size_t, and must be
  173807. * a multiple of SIZEOF(ALIGN_TYPE).
  173808. * Again, an "unreachable code" warning may be ignored here.
  173809. * But a "constant too large" warning means you need to fix MAX_ALLOC_CHUNK.
  173810. */
  173811. test_mac = (size_t) MAX_ALLOC_CHUNK;
  173812. if ((long) test_mac != MAX_ALLOC_CHUNK ||
  173813. (MAX_ALLOC_CHUNK % SIZEOF(ALIGN_TYPE)) != 0)
  173814. ERREXIT(cinfo, JERR_BAD_ALLOC_CHUNK);
  173815. max_to_use = jpeg_mem_init(cinfo); /* system-dependent initialization */
  173816. /* Attempt to allocate memory manager's control block */
  173817. mem = (my_mem_ptr) jpeg_get_small(cinfo, SIZEOF(my_memory_mgr));
  173818. if (mem == NULL) {
  173819. jpeg_mem_term(cinfo); /* system-dependent cleanup */
  173820. ERREXIT1(cinfo, JERR_OUT_OF_MEMORY, 0);
  173821. }
  173822. /* OK, fill in the method pointers */
  173823. mem->pub.alloc_small = alloc_small;
  173824. mem->pub.alloc_large = alloc_large;
  173825. mem->pub.alloc_sarray = alloc_sarray;
  173826. mem->pub.alloc_barray = alloc_barray;
  173827. mem->pub.request_virt_sarray = request_virt_sarray;
  173828. mem->pub.request_virt_barray = request_virt_barray;
  173829. mem->pub.realize_virt_arrays = realize_virt_arrays;
  173830. mem->pub.access_virt_sarray = access_virt_sarray;
  173831. mem->pub.access_virt_barray = access_virt_barray;
  173832. mem->pub.free_pool = free_pool;
  173833. mem->pub.self_destruct = self_destruct;
  173834. /* Make MAX_ALLOC_CHUNK accessible to other modules */
  173835. mem->pub.max_alloc_chunk = MAX_ALLOC_CHUNK;
  173836. /* Initialize working state */
  173837. mem->pub.max_memory_to_use = max_to_use;
  173838. for (pool = JPOOL_NUMPOOLS-1; pool >= JPOOL_PERMANENT; pool--) {
  173839. mem->small_list[pool] = NULL;
  173840. mem->large_list[pool] = NULL;
  173841. }
  173842. mem->virt_sarray_list = NULL;
  173843. mem->virt_barray_list = NULL;
  173844. mem->total_space_allocated = SIZEOF(my_memory_mgr);
  173845. /* Declare ourselves open for business */
  173846. cinfo->mem = & mem->pub;
  173847. /* Check for an environment variable JPEGMEM; if found, override the
  173848. * default max_memory setting from jpeg_mem_init. Note that the
  173849. * surrounding application may again override this value.
  173850. * If your system doesn't support getenv(), define NO_GETENV to disable
  173851. * this feature.
  173852. */
  173853. #ifndef NO_GETENV
  173854. { char * memenv;
  173855. if ((memenv = getenv("JPEGMEM")) != NULL) {
  173856. char ch = 'x';
  173857. if (sscanf(memenv, "%ld%c", &max_to_use, &ch) > 0) {
  173858. if (ch == 'm' || ch == 'M')
  173859. max_to_use *= 1000L;
  173860. mem->pub.max_memory_to_use = max_to_use * 1000L;
  173861. }
  173862. }
  173863. }
  173864. #endif
  173865. }
  173866. /*** End of inlined file: jmemmgr.c ***/
  173867. /*** Start of inlined file: jmemnobs.c ***/
  173868. #define JPEG_INTERNALS
  173869. #ifndef HAVE_STDLIB_H /* <stdlib.h> should declare malloc(),free() */
  173870. extern void * malloc JPP((size_t size));
  173871. extern void free JPP((void *ptr));
  173872. #endif
  173873. /*
  173874. * Memory allocation and freeing are controlled by the regular library
  173875. * routines malloc() and free().
  173876. */
  173877. GLOBAL(void *)
  173878. jpeg_get_small (j_common_ptr , size_t sizeofobject)
  173879. {
  173880. return (void *) malloc(sizeofobject);
  173881. }
  173882. GLOBAL(void)
  173883. jpeg_free_small (j_common_ptr , void * object, size_t)
  173884. {
  173885. free(object);
  173886. }
  173887. /*
  173888. * "Large" objects are treated the same as "small" ones.
  173889. * NB: although we include FAR keywords in the routine declarations,
  173890. * this file won't actually work in 80x86 small/medium model; at least,
  173891. * you probably won't be able to process useful-size images in only 64KB.
  173892. */
  173893. GLOBAL(void FAR *)
  173894. jpeg_get_large (j_common_ptr, size_t sizeofobject)
  173895. {
  173896. return (void FAR *) malloc(sizeofobject);
  173897. }
  173898. GLOBAL(void)
  173899. jpeg_free_large (j_common_ptr, void FAR * object, size_t)
  173900. {
  173901. free(object);
  173902. }
  173903. /*
  173904. * This routine computes the total memory space available for allocation.
  173905. * Here we always say, "we got all you want bud!"
  173906. */
  173907. GLOBAL(long)
  173908. jpeg_mem_available (j_common_ptr, long,
  173909. long max_bytes_needed, long)
  173910. {
  173911. return max_bytes_needed;
  173912. }
  173913. /*
  173914. * Backing store (temporary file) management.
  173915. * Since jpeg_mem_available always promised the moon,
  173916. * this should never be called and we can just error out.
  173917. */
  173918. GLOBAL(void)
  173919. jpeg_open_backing_store (j_common_ptr cinfo, struct backing_store_struct *,
  173920. long )
  173921. {
  173922. ERREXIT(cinfo, JERR_NO_BACKING_STORE);
  173923. }
  173924. /*
  173925. * These routines take care of any system-dependent initialization and
  173926. * cleanup required. Here, there isn't any.
  173927. */
  173928. GLOBAL(long)
  173929. jpeg_mem_init (j_common_ptr)
  173930. {
  173931. return 0; /* just set max_memory_to_use to 0 */
  173932. }
  173933. GLOBAL(void)
  173934. jpeg_mem_term (j_common_ptr)
  173935. {
  173936. /* no work */
  173937. }
  173938. /*** End of inlined file: jmemnobs.c ***/
  173939. /*** Start of inlined file: jquant1.c ***/
  173940. #define JPEG_INTERNALS
  173941. #ifdef QUANT_1PASS_SUPPORTED
  173942. /*
  173943. * The main purpose of 1-pass quantization is to provide a fast, if not very
  173944. * high quality, colormapped output capability. A 2-pass quantizer usually
  173945. * gives better visual quality; however, for quantized grayscale output this
  173946. * quantizer is perfectly adequate. Dithering is highly recommended with this
  173947. * quantizer, though you can turn it off if you really want to.
  173948. *
  173949. * In 1-pass quantization the colormap must be chosen in advance of seeing the
  173950. * image. We use a map consisting of all combinations of Ncolors[i] color
  173951. * values for the i'th component. The Ncolors[] values are chosen so that
  173952. * their product, the total number of colors, is no more than that requested.
  173953. * (In most cases, the product will be somewhat less.)
  173954. *
  173955. * Since the colormap is orthogonal, the representative value for each color
  173956. * component can be determined without considering the other components;
  173957. * then these indexes can be combined into a colormap index by a standard
  173958. * N-dimensional-array-subscript calculation. Most of the arithmetic involved
  173959. * can be precalculated and stored in the lookup table colorindex[].
  173960. * colorindex[i][j] maps pixel value j in component i to the nearest
  173961. * representative value (grid plane) for that component; this index is
  173962. * multiplied by the array stride for component i, so that the
  173963. * index of the colormap entry closest to a given pixel value is just
  173964. * sum( colorindex[component-number][pixel-component-value] )
  173965. * Aside from being fast, this scheme allows for variable spacing between
  173966. * representative values with no additional lookup cost.
  173967. *
  173968. * If gamma correction has been applied in color conversion, it might be wise
  173969. * to adjust the color grid spacing so that the representative colors are
  173970. * equidistant in linear space. At this writing, gamma correction is not
  173971. * implemented by jdcolor, so nothing is done here.
  173972. */
  173973. /* Declarations for ordered dithering.
  173974. *
  173975. * We use a standard 16x16 ordered dither array. The basic concept of ordered
  173976. * dithering is described in many references, for instance Dale Schumacher's
  173977. * chapter II.2 of Graphics Gems II (James Arvo, ed. Academic Press, 1991).
  173978. * In place of Schumacher's comparisons against a "threshold" value, we add a
  173979. * "dither" value to the input pixel and then round the result to the nearest
  173980. * output value. The dither value is equivalent to (0.5 - threshold) times
  173981. * the distance between output values. For ordered dithering, we assume that
  173982. * the output colors are equally spaced; if not, results will probably be
  173983. * worse, since the dither may be too much or too little at a given point.
  173984. *
  173985. * The normal calculation would be to form pixel value + dither, range-limit
  173986. * this to 0..MAXJSAMPLE, and then index into the colorindex table as usual.
  173987. * We can skip the separate range-limiting step by extending the colorindex
  173988. * table in both directions.
  173989. */
  173990. #define ODITHER_SIZE 16 /* dimension of dither matrix */
  173991. /* NB: if ODITHER_SIZE is not a power of 2, ODITHER_MASK uses will break */
  173992. #define ODITHER_CELLS (ODITHER_SIZE*ODITHER_SIZE) /* # cells in matrix */
  173993. #define ODITHER_MASK (ODITHER_SIZE-1) /* mask for wrapping around counters */
  173994. typedef int ODITHER_MATRIX[ODITHER_SIZE][ODITHER_SIZE];
  173995. typedef int (*ODITHER_MATRIX_PTR)[ODITHER_SIZE];
  173996. static const UINT8 base_dither_matrix[ODITHER_SIZE][ODITHER_SIZE] = {
  173997. /* Bayer's order-4 dither array. Generated by the code given in
  173998. * Stephen Hawley's article "Ordered Dithering" in Graphics Gems I.
  173999. * The values in this array must range from 0 to ODITHER_CELLS-1.
  174000. */
  174001. { 0,192, 48,240, 12,204, 60,252, 3,195, 51,243, 15,207, 63,255 },
  174002. { 128, 64,176,112,140, 76,188,124,131, 67,179,115,143, 79,191,127 },
  174003. { 32,224, 16,208, 44,236, 28,220, 35,227, 19,211, 47,239, 31,223 },
  174004. { 160, 96,144, 80,172,108,156, 92,163, 99,147, 83,175,111,159, 95 },
  174005. { 8,200, 56,248, 4,196, 52,244, 11,203, 59,251, 7,199, 55,247 },
  174006. { 136, 72,184,120,132, 68,180,116,139, 75,187,123,135, 71,183,119 },
  174007. { 40,232, 24,216, 36,228, 20,212, 43,235, 27,219, 39,231, 23,215 },
  174008. { 168,104,152, 88,164,100,148, 84,171,107,155, 91,167,103,151, 87 },
  174009. { 2,194, 50,242, 14,206, 62,254, 1,193, 49,241, 13,205, 61,253 },
  174010. { 130, 66,178,114,142, 78,190,126,129, 65,177,113,141, 77,189,125 },
  174011. { 34,226, 18,210, 46,238, 30,222, 33,225, 17,209, 45,237, 29,221 },
  174012. { 162, 98,146, 82,174,110,158, 94,161, 97,145, 81,173,109,157, 93 },
  174013. { 10,202, 58,250, 6,198, 54,246, 9,201, 57,249, 5,197, 53,245 },
  174014. { 138, 74,186,122,134, 70,182,118,137, 73,185,121,133, 69,181,117 },
  174015. { 42,234, 26,218, 38,230, 22,214, 41,233, 25,217, 37,229, 21,213 },
  174016. { 170,106,154, 90,166,102,150, 86,169,105,153, 89,165,101,149, 85 }
  174017. };
  174018. /* Declarations for Floyd-Steinberg dithering.
  174019. *
  174020. * Errors are accumulated into the array fserrors[], at a resolution of
  174021. * 1/16th of a pixel count. The error at a given pixel is propagated
  174022. * to its not-yet-processed neighbors using the standard F-S fractions,
  174023. * ... (here) 7/16
  174024. * 3/16 5/16 1/16
  174025. * We work left-to-right on even rows, right-to-left on odd rows.
  174026. *
  174027. * We can get away with a single array (holding one row's worth of errors)
  174028. * by using it to store the current row's errors at pixel columns not yet
  174029. * processed, but the next row's errors at columns already processed. We
  174030. * need only a few extra variables to hold the errors immediately around the
  174031. * current column. (If we are lucky, those variables are in registers, but
  174032. * even if not, they're probably cheaper to access than array elements are.)
  174033. *
  174034. * The fserrors[] array is indexed [component#][position].
  174035. * We provide (#columns + 2) entries per component; the extra entry at each
  174036. * end saves us from special-casing the first and last pixels.
  174037. *
  174038. * Note: on a wide image, we might not have enough room in a PC's near data
  174039. * segment to hold the error array; so it is allocated with alloc_large.
  174040. */
  174041. #if BITS_IN_JSAMPLE == 8
  174042. typedef INT16 FSERROR; /* 16 bits should be enough */
  174043. typedef int LOCFSERROR; /* use 'int' for calculation temps */
  174044. #else
  174045. typedef INT32 FSERROR; /* may need more than 16 bits */
  174046. typedef INT32 LOCFSERROR; /* be sure calculation temps are big enough */
  174047. #endif
  174048. typedef FSERROR FAR *FSERRPTR; /* pointer to error array (in FAR storage!) */
  174049. /* Private subobject */
  174050. #define MAX_Q_COMPS 4 /* max components I can handle */
  174051. typedef struct {
  174052. struct jpeg_color_quantizer pub; /* public fields */
  174053. /* Initially allocated colormap is saved here */
  174054. JSAMPARRAY sv_colormap; /* The color map as a 2-D pixel array */
  174055. int sv_actual; /* number of entries in use */
  174056. JSAMPARRAY colorindex; /* Precomputed mapping for speed */
  174057. /* colorindex[i][j] = index of color closest to pixel value j in component i,
  174058. * premultiplied as described above. Since colormap indexes must fit into
  174059. * JSAMPLEs, the entries of this array will too.
  174060. */
  174061. boolean is_padded; /* is the colorindex padded for odither? */
  174062. int Ncolors[MAX_Q_COMPS]; /* # of values alloced to each component */
  174063. /* Variables for ordered dithering */
  174064. int row_index; /* cur row's vertical index in dither matrix */
  174065. ODITHER_MATRIX_PTR odither[MAX_Q_COMPS]; /* one dither array per component */
  174066. /* Variables for Floyd-Steinberg dithering */
  174067. FSERRPTR fserrors[MAX_Q_COMPS]; /* accumulated errors */
  174068. boolean on_odd_row; /* flag to remember which row we are on */
  174069. } my_cquantizer;
  174070. typedef my_cquantizer * my_cquantize_ptr;
  174071. /*
  174072. * Policy-making subroutines for create_colormap and create_colorindex.
  174073. * These routines determine the colormap to be used. The rest of the module
  174074. * only assumes that the colormap is orthogonal.
  174075. *
  174076. * * select_ncolors decides how to divvy up the available colors
  174077. * among the components.
  174078. * * output_value defines the set of representative values for a component.
  174079. * * largest_input_value defines the mapping from input values to
  174080. * representative values for a component.
  174081. * Note that the latter two routines may impose different policies for
  174082. * different components, though this is not currently done.
  174083. */
  174084. LOCAL(int)
  174085. select_ncolors (j_decompress_ptr cinfo, int Ncolors[])
  174086. /* Determine allocation of desired colors to components, */
  174087. /* and fill in Ncolors[] array to indicate choice. */
  174088. /* Return value is total number of colors (product of Ncolors[] values). */
  174089. {
  174090. int nc = cinfo->out_color_components; /* number of color components */
  174091. int max_colors = cinfo->desired_number_of_colors;
  174092. int total_colors, iroot, i, j;
  174093. boolean changed;
  174094. long temp;
  174095. static const int RGB_order[3] = { RGB_GREEN, RGB_RED, RGB_BLUE };
  174096. /* We can allocate at least the nc'th root of max_colors per component. */
  174097. /* Compute floor(nc'th root of max_colors). */
  174098. iroot = 1;
  174099. do {
  174100. iroot++;
  174101. temp = iroot; /* set temp = iroot ** nc */
  174102. for (i = 1; i < nc; i++)
  174103. temp *= iroot;
  174104. } while (temp <= (long) max_colors); /* repeat till iroot exceeds root */
  174105. iroot--; /* now iroot = floor(root) */
  174106. /* Must have at least 2 color values per component */
  174107. if (iroot < 2)
  174108. ERREXIT1(cinfo, JERR_QUANT_FEW_COLORS, (int) temp);
  174109. /* Initialize to iroot color values for each component */
  174110. total_colors = 1;
  174111. for (i = 0; i < nc; i++) {
  174112. Ncolors[i] = iroot;
  174113. total_colors *= iroot;
  174114. }
  174115. /* We may be able to increment the count for one or more components without
  174116. * exceeding max_colors, though we know not all can be incremented.
  174117. * Sometimes, the first component can be incremented more than once!
  174118. * (Example: for 16 colors, we start at 2*2*2, go to 3*2*2, then 4*2*2.)
  174119. * In RGB colorspace, try to increment G first, then R, then B.
  174120. */
  174121. do {
  174122. changed = FALSE;
  174123. for (i = 0; i < nc; i++) {
  174124. j = (cinfo->out_color_space == JCS_RGB ? RGB_order[i] : i);
  174125. /* calculate new total_colors if Ncolors[j] is incremented */
  174126. temp = total_colors / Ncolors[j];
  174127. temp *= Ncolors[j]+1; /* done in long arith to avoid oflo */
  174128. if (temp > (long) max_colors)
  174129. break; /* won't fit, done with this pass */
  174130. Ncolors[j]++; /* OK, apply the increment */
  174131. total_colors = (int) temp;
  174132. changed = TRUE;
  174133. }
  174134. } while (changed);
  174135. return total_colors;
  174136. }
  174137. LOCAL(int)
  174138. output_value (j_decompress_ptr, int, int j, int maxj)
  174139. /* Return j'th output value, where j will range from 0 to maxj */
  174140. /* The output values must fall in 0..MAXJSAMPLE in increasing order */
  174141. {
  174142. /* We always provide values 0 and MAXJSAMPLE for each component;
  174143. * any additional values are equally spaced between these limits.
  174144. * (Forcing the upper and lower values to the limits ensures that
  174145. * dithering can't produce a color outside the selected gamut.)
  174146. */
  174147. return (int) (((INT32) j * MAXJSAMPLE + maxj/2) / maxj);
  174148. }
  174149. LOCAL(int)
  174150. largest_input_value (j_decompress_ptr, int, int j, int maxj)
  174151. /* Return largest input value that should map to j'th output value */
  174152. /* Must have largest(j=0) >= 0, and largest(j=maxj) >= MAXJSAMPLE */
  174153. {
  174154. /* Breakpoints are halfway between values returned by output_value */
  174155. return (int) (((INT32) (2*j + 1) * MAXJSAMPLE + maxj) / (2*maxj));
  174156. }
  174157. /*
  174158. * Create the colormap.
  174159. */
  174160. LOCAL(void)
  174161. create_colormap (j_decompress_ptr cinfo)
  174162. {
  174163. my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  174164. JSAMPARRAY colormap; /* Created colormap */
  174165. int total_colors; /* Number of distinct output colors */
  174166. int i,j,k, nci, blksize, blkdist, ptr, val;
  174167. /* Select number of colors for each component */
  174168. total_colors = select_ncolors(cinfo, cquantize->Ncolors);
  174169. /* Report selected color counts */
  174170. if (cinfo->out_color_components == 3)
  174171. TRACEMS4(cinfo, 1, JTRC_QUANT_3_NCOLORS,
  174172. total_colors, cquantize->Ncolors[0],
  174173. cquantize->Ncolors[1], cquantize->Ncolors[2]);
  174174. else
  174175. TRACEMS1(cinfo, 1, JTRC_QUANT_NCOLORS, total_colors);
  174176. /* Allocate and fill in the colormap. */
  174177. /* The colors are ordered in the map in standard row-major order, */
  174178. /* i.e. rightmost (highest-indexed) color changes most rapidly. */
  174179. colormap = (*cinfo->mem->alloc_sarray)
  174180. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  174181. (JDIMENSION) total_colors, (JDIMENSION) cinfo->out_color_components);
  174182. /* blksize is number of adjacent repeated entries for a component */
  174183. /* blkdist is distance between groups of identical entries for a component */
  174184. blkdist = total_colors;
  174185. for (i = 0; i < cinfo->out_color_components; i++) {
  174186. /* fill in colormap entries for i'th color component */
  174187. nci = cquantize->Ncolors[i]; /* # of distinct values for this color */
  174188. blksize = blkdist / nci;
  174189. for (j = 0; j < nci; j++) {
  174190. /* Compute j'th output value (out of nci) for component */
  174191. val = output_value(cinfo, i, j, nci-1);
  174192. /* Fill in all colormap entries that have this value of this component */
  174193. for (ptr = j * blksize; ptr < total_colors; ptr += blkdist) {
  174194. /* fill in blksize entries beginning at ptr */
  174195. for (k = 0; k < blksize; k++)
  174196. colormap[i][ptr+k] = (JSAMPLE) val;
  174197. }
  174198. }
  174199. blkdist = blksize; /* blksize of this color is blkdist of next */
  174200. }
  174201. /* Save the colormap in private storage,
  174202. * where it will survive color quantization mode changes.
  174203. */
  174204. cquantize->sv_colormap = colormap;
  174205. cquantize->sv_actual = total_colors;
  174206. }
  174207. /*
  174208. * Create the color index table.
  174209. */
  174210. LOCAL(void)
  174211. create_colorindex (j_decompress_ptr cinfo)
  174212. {
  174213. my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  174214. JSAMPROW indexptr;
  174215. int i,j,k, nci, blksize, val, pad;
  174216. /* For ordered dither, we pad the color index tables by MAXJSAMPLE in
  174217. * each direction (input index values can be -MAXJSAMPLE .. 2*MAXJSAMPLE).
  174218. * This is not necessary in the other dithering modes. However, we
  174219. * flag whether it was done in case user changes dithering mode.
  174220. */
  174221. if (cinfo->dither_mode == JDITHER_ORDERED) {
  174222. pad = MAXJSAMPLE*2;
  174223. cquantize->is_padded = TRUE;
  174224. } else {
  174225. pad = 0;
  174226. cquantize->is_padded = FALSE;
  174227. }
  174228. cquantize->colorindex = (*cinfo->mem->alloc_sarray)
  174229. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  174230. (JDIMENSION) (MAXJSAMPLE+1 + pad),
  174231. (JDIMENSION) cinfo->out_color_components);
  174232. /* blksize is number of adjacent repeated entries for a component */
  174233. blksize = cquantize->sv_actual;
  174234. for (i = 0; i < cinfo->out_color_components; i++) {
  174235. /* fill in colorindex entries for i'th color component */
  174236. nci = cquantize->Ncolors[i]; /* # of distinct values for this color */
  174237. blksize = blksize / nci;
  174238. /* adjust colorindex pointers to provide padding at negative indexes. */
  174239. if (pad)
  174240. cquantize->colorindex[i] += MAXJSAMPLE;
  174241. /* in loop, val = index of current output value, */
  174242. /* and k = largest j that maps to current val */
  174243. indexptr = cquantize->colorindex[i];
  174244. val = 0;
  174245. k = largest_input_value(cinfo, i, 0, nci-1);
  174246. for (j = 0; j <= MAXJSAMPLE; j++) {
  174247. while (j > k) /* advance val if past boundary */
  174248. k = largest_input_value(cinfo, i, ++val, nci-1);
  174249. /* premultiply so that no multiplication needed in main processing */
  174250. indexptr[j] = (JSAMPLE) (val * blksize);
  174251. }
  174252. /* Pad at both ends if necessary */
  174253. if (pad)
  174254. for (j = 1; j <= MAXJSAMPLE; j++) {
  174255. indexptr[-j] = indexptr[0];
  174256. indexptr[MAXJSAMPLE+j] = indexptr[MAXJSAMPLE];
  174257. }
  174258. }
  174259. }
  174260. /*
  174261. * Create an ordered-dither array for a component having ncolors
  174262. * distinct output values.
  174263. */
  174264. LOCAL(ODITHER_MATRIX_PTR)
  174265. make_odither_array (j_decompress_ptr cinfo, int ncolors)
  174266. {
  174267. ODITHER_MATRIX_PTR odither;
  174268. int j,k;
  174269. INT32 num,den;
  174270. odither = (ODITHER_MATRIX_PTR)
  174271. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  174272. SIZEOF(ODITHER_MATRIX));
  174273. /* The inter-value distance for this color is MAXJSAMPLE/(ncolors-1).
  174274. * Hence the dither value for the matrix cell with fill order f
  174275. * (f=0..N-1) should be (N-1-2*f)/(2*N) * MAXJSAMPLE/(ncolors-1).
  174276. * On 16-bit-int machine, be careful to avoid overflow.
  174277. */
  174278. den = 2 * ODITHER_CELLS * ((INT32) (ncolors - 1));
  174279. for (j = 0; j < ODITHER_SIZE; j++) {
  174280. for (k = 0; k < ODITHER_SIZE; k++) {
  174281. num = ((INT32) (ODITHER_CELLS-1 - 2*((int)base_dither_matrix[j][k])))
  174282. * MAXJSAMPLE;
  174283. /* Ensure round towards zero despite C's lack of consistency
  174284. * about rounding negative values in integer division...
  174285. */
  174286. odither[j][k] = (int) (num<0 ? -((-num)/den) : num/den);
  174287. }
  174288. }
  174289. return odither;
  174290. }
  174291. /*
  174292. * Create the ordered-dither tables.
  174293. * Components having the same number of representative colors may
  174294. * share a dither table.
  174295. */
  174296. LOCAL(void)
  174297. create_odither_tables (j_decompress_ptr cinfo)
  174298. {
  174299. my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  174300. ODITHER_MATRIX_PTR odither;
  174301. int i, j, nci;
  174302. for (i = 0; i < cinfo->out_color_components; i++) {
  174303. nci = cquantize->Ncolors[i]; /* # of distinct values for this color */
  174304. odither = NULL; /* search for matching prior component */
  174305. for (j = 0; j < i; j++) {
  174306. if (nci == cquantize->Ncolors[j]) {
  174307. odither = cquantize->odither[j];
  174308. break;
  174309. }
  174310. }
  174311. if (odither == NULL) /* need a new table? */
  174312. odither = make_odither_array(cinfo, nci);
  174313. cquantize->odither[i] = odither;
  174314. }
  174315. }
  174316. /*
  174317. * Map some rows of pixels to the output colormapped representation.
  174318. */
  174319. METHODDEF(void)
  174320. color_quantize (j_decompress_ptr cinfo, JSAMPARRAY input_buf,
  174321. JSAMPARRAY output_buf, int num_rows)
  174322. /* General case, no dithering */
  174323. {
  174324. my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  174325. JSAMPARRAY colorindex = cquantize->colorindex;
  174326. register int pixcode, ci;
  174327. register JSAMPROW ptrin, ptrout;
  174328. int row;
  174329. JDIMENSION col;
  174330. JDIMENSION width = cinfo->output_width;
  174331. register int nc = cinfo->out_color_components;
  174332. for (row = 0; row < num_rows; row++) {
  174333. ptrin = input_buf[row];
  174334. ptrout = output_buf[row];
  174335. for (col = width; col > 0; col--) {
  174336. pixcode = 0;
  174337. for (ci = 0; ci < nc; ci++) {
  174338. pixcode += GETJSAMPLE(colorindex[ci][GETJSAMPLE(*ptrin++)]);
  174339. }
  174340. *ptrout++ = (JSAMPLE) pixcode;
  174341. }
  174342. }
  174343. }
  174344. METHODDEF(void)
  174345. color_quantize3 (j_decompress_ptr cinfo, JSAMPARRAY input_buf,
  174346. JSAMPARRAY output_buf, int num_rows)
  174347. /* Fast path for out_color_components==3, no dithering */
  174348. {
  174349. my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  174350. register int pixcode;
  174351. register JSAMPROW ptrin, ptrout;
  174352. JSAMPROW colorindex0 = cquantize->colorindex[0];
  174353. JSAMPROW colorindex1 = cquantize->colorindex[1];
  174354. JSAMPROW colorindex2 = cquantize->colorindex[2];
  174355. int row;
  174356. JDIMENSION col;
  174357. JDIMENSION width = cinfo->output_width;
  174358. for (row = 0; row < num_rows; row++) {
  174359. ptrin = input_buf[row];
  174360. ptrout = output_buf[row];
  174361. for (col = width; col > 0; col--) {
  174362. pixcode = GETJSAMPLE(colorindex0[GETJSAMPLE(*ptrin++)]);
  174363. pixcode += GETJSAMPLE(colorindex1[GETJSAMPLE(*ptrin++)]);
  174364. pixcode += GETJSAMPLE(colorindex2[GETJSAMPLE(*ptrin++)]);
  174365. *ptrout++ = (JSAMPLE) pixcode;
  174366. }
  174367. }
  174368. }
  174369. METHODDEF(void)
  174370. quantize_ord_dither (j_decompress_ptr cinfo, JSAMPARRAY input_buf,
  174371. JSAMPARRAY output_buf, int num_rows)
  174372. /* General case, with ordered dithering */
  174373. {
  174374. my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  174375. register JSAMPROW input_ptr;
  174376. register JSAMPROW output_ptr;
  174377. JSAMPROW colorindex_ci;
  174378. int * dither; /* points to active row of dither matrix */
  174379. int row_index, col_index; /* current indexes into dither matrix */
  174380. int nc = cinfo->out_color_components;
  174381. int ci;
  174382. int row;
  174383. JDIMENSION col;
  174384. JDIMENSION width = cinfo->output_width;
  174385. for (row = 0; row < num_rows; row++) {
  174386. /* Initialize output values to 0 so can process components separately */
  174387. jzero_far((void FAR *) output_buf[row],
  174388. (size_t) (width * SIZEOF(JSAMPLE)));
  174389. row_index = cquantize->row_index;
  174390. for (ci = 0; ci < nc; ci++) {
  174391. input_ptr = input_buf[row] + ci;
  174392. output_ptr = output_buf[row];
  174393. colorindex_ci = cquantize->colorindex[ci];
  174394. dither = cquantize->odither[ci][row_index];
  174395. col_index = 0;
  174396. for (col = width; col > 0; col--) {
  174397. /* Form pixel value + dither, range-limit to 0..MAXJSAMPLE,
  174398. * select output value, accumulate into output code for this pixel.
  174399. * Range-limiting need not be done explicitly, as we have extended
  174400. * the colorindex table to produce the right answers for out-of-range
  174401. * inputs. The maximum dither is +- MAXJSAMPLE; this sets the
  174402. * required amount of padding.
  174403. */
  174404. *output_ptr += colorindex_ci[GETJSAMPLE(*input_ptr)+dither[col_index]];
  174405. input_ptr += nc;
  174406. output_ptr++;
  174407. col_index = (col_index + 1) & ODITHER_MASK;
  174408. }
  174409. }
  174410. /* Advance row index for next row */
  174411. row_index = (row_index + 1) & ODITHER_MASK;
  174412. cquantize->row_index = row_index;
  174413. }
  174414. }
  174415. METHODDEF(void)
  174416. quantize3_ord_dither (j_decompress_ptr cinfo, JSAMPARRAY input_buf,
  174417. JSAMPARRAY output_buf, int num_rows)
  174418. /* Fast path for out_color_components==3, with ordered dithering */
  174419. {
  174420. my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  174421. register int pixcode;
  174422. register JSAMPROW input_ptr;
  174423. register JSAMPROW output_ptr;
  174424. JSAMPROW colorindex0 = cquantize->colorindex[0];
  174425. JSAMPROW colorindex1 = cquantize->colorindex[1];
  174426. JSAMPROW colorindex2 = cquantize->colorindex[2];
  174427. int * dither0; /* points to active row of dither matrix */
  174428. int * dither1;
  174429. int * dither2;
  174430. int row_index, col_index; /* current indexes into dither matrix */
  174431. int row;
  174432. JDIMENSION col;
  174433. JDIMENSION width = cinfo->output_width;
  174434. for (row = 0; row < num_rows; row++) {
  174435. row_index = cquantize->row_index;
  174436. input_ptr = input_buf[row];
  174437. output_ptr = output_buf[row];
  174438. dither0 = cquantize->odither[0][row_index];
  174439. dither1 = cquantize->odither[1][row_index];
  174440. dither2 = cquantize->odither[2][row_index];
  174441. col_index = 0;
  174442. for (col = width; col > 0; col--) {
  174443. pixcode = GETJSAMPLE(colorindex0[GETJSAMPLE(*input_ptr++) +
  174444. dither0[col_index]]);
  174445. pixcode += GETJSAMPLE(colorindex1[GETJSAMPLE(*input_ptr++) +
  174446. dither1[col_index]]);
  174447. pixcode += GETJSAMPLE(colorindex2[GETJSAMPLE(*input_ptr++) +
  174448. dither2[col_index]]);
  174449. *output_ptr++ = (JSAMPLE) pixcode;
  174450. col_index = (col_index + 1) & ODITHER_MASK;
  174451. }
  174452. row_index = (row_index + 1) & ODITHER_MASK;
  174453. cquantize->row_index = row_index;
  174454. }
  174455. }
  174456. METHODDEF(void)
  174457. quantize_fs_dither (j_decompress_ptr cinfo, JSAMPARRAY input_buf,
  174458. JSAMPARRAY output_buf, int num_rows)
  174459. /* General case, with Floyd-Steinberg dithering */
  174460. {
  174461. my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  174462. register LOCFSERROR cur; /* current error or pixel value */
  174463. LOCFSERROR belowerr; /* error for pixel below cur */
  174464. LOCFSERROR bpreverr; /* error for below/prev col */
  174465. LOCFSERROR bnexterr; /* error for below/next col */
  174466. LOCFSERROR delta;
  174467. register FSERRPTR errorptr; /* => fserrors[] at column before current */
  174468. register JSAMPROW input_ptr;
  174469. register JSAMPROW output_ptr;
  174470. JSAMPROW colorindex_ci;
  174471. JSAMPROW colormap_ci;
  174472. int pixcode;
  174473. int nc = cinfo->out_color_components;
  174474. int dir; /* 1 for left-to-right, -1 for right-to-left */
  174475. int dirnc; /* dir * nc */
  174476. int ci;
  174477. int row;
  174478. JDIMENSION col;
  174479. JDIMENSION width = cinfo->output_width;
  174480. JSAMPLE *range_limit = cinfo->sample_range_limit;
  174481. SHIFT_TEMPS
  174482. for (row = 0; row < num_rows; row++) {
  174483. /* Initialize output values to 0 so can process components separately */
  174484. jzero_far((void FAR *) output_buf[row],
  174485. (size_t) (width * SIZEOF(JSAMPLE)));
  174486. for (ci = 0; ci < nc; ci++) {
  174487. input_ptr = input_buf[row] + ci;
  174488. output_ptr = output_buf[row];
  174489. if (cquantize->on_odd_row) {
  174490. /* work right to left in this row */
  174491. input_ptr += (width-1) * nc; /* so point to rightmost pixel */
  174492. output_ptr += width-1;
  174493. dir = -1;
  174494. dirnc = -nc;
  174495. errorptr = cquantize->fserrors[ci] + (width+1); /* => entry after last column */
  174496. } else {
  174497. /* work left to right in this row */
  174498. dir = 1;
  174499. dirnc = nc;
  174500. errorptr = cquantize->fserrors[ci]; /* => entry before first column */
  174501. }
  174502. colorindex_ci = cquantize->colorindex[ci];
  174503. colormap_ci = cquantize->sv_colormap[ci];
  174504. /* Preset error values: no error propagated to first pixel from left */
  174505. cur = 0;
  174506. /* and no error propagated to row below yet */
  174507. belowerr = bpreverr = 0;
  174508. for (col = width; col > 0; col--) {
  174509. /* cur holds the error propagated from the previous pixel on the
  174510. * current line. Add the error propagated from the previous line
  174511. * to form the complete error correction term for this pixel, and
  174512. * round the error term (which is expressed * 16) to an integer.
  174513. * RIGHT_SHIFT rounds towards minus infinity, so adding 8 is correct
  174514. * for either sign of the error value.
  174515. * Note: errorptr points to *previous* column's array entry.
  174516. */
  174517. cur = RIGHT_SHIFT(cur + errorptr[dir] + 8, 4);
  174518. /* Form pixel value + error, and range-limit to 0..MAXJSAMPLE.
  174519. * The maximum error is +- MAXJSAMPLE; this sets the required size
  174520. * of the range_limit array.
  174521. */
  174522. cur += GETJSAMPLE(*input_ptr);
  174523. cur = GETJSAMPLE(range_limit[cur]);
  174524. /* Select output value, accumulate into output code for this pixel */
  174525. pixcode = GETJSAMPLE(colorindex_ci[cur]);
  174526. *output_ptr += (JSAMPLE) pixcode;
  174527. /* Compute actual representation error at this pixel */
  174528. /* Note: we can do this even though we don't have the final */
  174529. /* pixel code, because the colormap is orthogonal. */
  174530. cur -= GETJSAMPLE(colormap_ci[pixcode]);
  174531. /* Compute error fractions to be propagated to adjacent pixels.
  174532. * Add these into the running sums, and simultaneously shift the
  174533. * next-line error sums left by 1 column.
  174534. */
  174535. bnexterr = cur;
  174536. delta = cur * 2;
  174537. cur += delta; /* form error * 3 */
  174538. errorptr[0] = (FSERROR) (bpreverr + cur);
  174539. cur += delta; /* form error * 5 */
  174540. bpreverr = belowerr + cur;
  174541. belowerr = bnexterr;
  174542. cur += delta; /* form error * 7 */
  174543. /* At this point cur contains the 7/16 error value to be propagated
  174544. * to the next pixel on the current line, and all the errors for the
  174545. * next line have been shifted over. We are therefore ready to move on.
  174546. */
  174547. input_ptr += dirnc; /* advance input ptr to next column */
  174548. output_ptr += dir; /* advance output ptr to next column */
  174549. errorptr += dir; /* advance errorptr to current column */
  174550. }
  174551. /* Post-loop cleanup: we must unload the final error value into the
  174552. * final fserrors[] entry. Note we need not unload belowerr because
  174553. * it is for the dummy column before or after the actual array.
  174554. */
  174555. errorptr[0] = (FSERROR) bpreverr; /* unload prev err into array */
  174556. }
  174557. cquantize->on_odd_row = (cquantize->on_odd_row ? FALSE : TRUE);
  174558. }
  174559. }
  174560. /*
  174561. * Allocate workspace for Floyd-Steinberg errors.
  174562. */
  174563. LOCAL(void)
  174564. alloc_fs_workspace (j_decompress_ptr cinfo)
  174565. {
  174566. my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  174567. size_t arraysize;
  174568. int i;
  174569. arraysize = (size_t) ((cinfo->output_width + 2) * SIZEOF(FSERROR));
  174570. for (i = 0; i < cinfo->out_color_components; i++) {
  174571. cquantize->fserrors[i] = (FSERRPTR)
  174572. (*cinfo->mem->alloc_large)((j_common_ptr) cinfo, JPOOL_IMAGE, arraysize);
  174573. }
  174574. }
  174575. /*
  174576. * Initialize for one-pass color quantization.
  174577. */
  174578. METHODDEF(void)
  174579. start_pass_1_quant (j_decompress_ptr cinfo, boolean)
  174580. {
  174581. my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  174582. size_t arraysize;
  174583. int i;
  174584. /* Install my colormap. */
  174585. cinfo->colormap = cquantize->sv_colormap;
  174586. cinfo->actual_number_of_colors = cquantize->sv_actual;
  174587. /* Initialize for desired dithering mode. */
  174588. switch (cinfo->dither_mode) {
  174589. case JDITHER_NONE:
  174590. if (cinfo->out_color_components == 3)
  174591. cquantize->pub.color_quantize = color_quantize3;
  174592. else
  174593. cquantize->pub.color_quantize = color_quantize;
  174594. break;
  174595. case JDITHER_ORDERED:
  174596. if (cinfo->out_color_components == 3)
  174597. cquantize->pub.color_quantize = quantize3_ord_dither;
  174598. else
  174599. cquantize->pub.color_quantize = quantize_ord_dither;
  174600. cquantize->row_index = 0; /* initialize state for ordered dither */
  174601. /* If user changed to ordered dither from another mode,
  174602. * we must recreate the color index table with padding.
  174603. * This will cost extra space, but probably isn't very likely.
  174604. */
  174605. if (! cquantize->is_padded)
  174606. create_colorindex(cinfo);
  174607. /* Create ordered-dither tables if we didn't already. */
  174608. if (cquantize->odither[0] == NULL)
  174609. create_odither_tables(cinfo);
  174610. break;
  174611. case JDITHER_FS:
  174612. cquantize->pub.color_quantize = quantize_fs_dither;
  174613. cquantize->on_odd_row = FALSE; /* initialize state for F-S dither */
  174614. /* Allocate Floyd-Steinberg workspace if didn't already. */
  174615. if (cquantize->fserrors[0] == NULL)
  174616. alloc_fs_workspace(cinfo);
  174617. /* Initialize the propagated errors to zero. */
  174618. arraysize = (size_t) ((cinfo->output_width + 2) * SIZEOF(FSERROR));
  174619. for (i = 0; i < cinfo->out_color_components; i++)
  174620. jzero_far((void FAR *) cquantize->fserrors[i], arraysize);
  174621. break;
  174622. default:
  174623. ERREXIT(cinfo, JERR_NOT_COMPILED);
  174624. break;
  174625. }
  174626. }
  174627. /*
  174628. * Finish up at the end of the pass.
  174629. */
  174630. METHODDEF(void)
  174631. finish_pass_1_quant (j_decompress_ptr)
  174632. {
  174633. /* no work in 1-pass case */
  174634. }
  174635. /*
  174636. * Switch to a new external colormap between output passes.
  174637. * Shouldn't get to this module!
  174638. */
  174639. METHODDEF(void)
  174640. new_color_map_1_quant (j_decompress_ptr cinfo)
  174641. {
  174642. ERREXIT(cinfo, JERR_MODE_CHANGE);
  174643. }
  174644. /*
  174645. * Module initialization routine for 1-pass color quantization.
  174646. */
  174647. GLOBAL(void)
  174648. jinit_1pass_quantizer (j_decompress_ptr cinfo)
  174649. {
  174650. my_cquantize_ptr cquantize;
  174651. cquantize = (my_cquantize_ptr)
  174652. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  174653. SIZEOF(my_cquantizer));
  174654. cinfo->cquantize = (struct jpeg_color_quantizer *) cquantize;
  174655. cquantize->pub.start_pass = start_pass_1_quant;
  174656. cquantize->pub.finish_pass = finish_pass_1_quant;
  174657. cquantize->pub.new_color_map = new_color_map_1_quant;
  174658. cquantize->fserrors[0] = NULL; /* Flag FS workspace not allocated */
  174659. cquantize->odither[0] = NULL; /* Also flag odither arrays not allocated */
  174660. /* Make sure my internal arrays won't overflow */
  174661. if (cinfo->out_color_components > MAX_Q_COMPS)
  174662. ERREXIT1(cinfo, JERR_QUANT_COMPONENTS, MAX_Q_COMPS);
  174663. /* Make sure colormap indexes can be represented by JSAMPLEs */
  174664. if (cinfo->desired_number_of_colors > (MAXJSAMPLE+1))
  174665. ERREXIT1(cinfo, JERR_QUANT_MANY_COLORS, MAXJSAMPLE+1);
  174666. /* Create the colormap and color index table. */
  174667. create_colormap(cinfo);
  174668. create_colorindex(cinfo);
  174669. /* Allocate Floyd-Steinberg workspace now if requested.
  174670. * We do this now since it is FAR storage and may affect the memory
  174671. * manager's space calculations. If the user changes to FS dither
  174672. * mode in a later pass, we will allocate the space then, and will
  174673. * possibly overrun the max_memory_to_use setting.
  174674. */
  174675. if (cinfo->dither_mode == JDITHER_FS)
  174676. alloc_fs_workspace(cinfo);
  174677. }
  174678. #endif /* QUANT_1PASS_SUPPORTED */
  174679. /*** End of inlined file: jquant1.c ***/
  174680. /*** Start of inlined file: jquant2.c ***/
  174681. #define JPEG_INTERNALS
  174682. #ifdef QUANT_2PASS_SUPPORTED
  174683. /*
  174684. * This module implements the well-known Heckbert paradigm for color
  174685. * quantization. Most of the ideas used here can be traced back to
  174686. * Heckbert's seminal paper
  174687. * Heckbert, Paul. "Color Image Quantization for Frame Buffer Display",
  174688. * Proc. SIGGRAPH '82, Computer Graphics v.16 #3 (July 1982), pp 297-304.
  174689. *
  174690. * In the first pass over the image, we accumulate a histogram showing the
  174691. * usage count of each possible color. To keep the histogram to a reasonable
  174692. * size, we reduce the precision of the input; typical practice is to retain
  174693. * 5 or 6 bits per color, so that 8 or 4 different input values are counted
  174694. * in the same histogram cell.
  174695. *
  174696. * Next, the color-selection step begins with a box representing the whole
  174697. * color space, and repeatedly splits the "largest" remaining box until we
  174698. * have as many boxes as desired colors. Then the mean color in each
  174699. * remaining box becomes one of the possible output colors.
  174700. *
  174701. * The second pass over the image maps each input pixel to the closest output
  174702. * color (optionally after applying a Floyd-Steinberg dithering correction).
  174703. * This mapping is logically trivial, but making it go fast enough requires
  174704. * considerable care.
  174705. *
  174706. * Heckbert-style quantizers vary a good deal in their policies for choosing
  174707. * the "largest" box and deciding where to cut it. The particular policies
  174708. * used here have proved out well in experimental comparisons, but better ones
  174709. * may yet be found.
  174710. *
  174711. * In earlier versions of the IJG code, this module quantized in YCbCr color
  174712. * space, processing the raw upsampled data without a color conversion step.
  174713. * This allowed the color conversion math to be done only once per colormap
  174714. * entry, not once per pixel. However, that optimization precluded other
  174715. * useful optimizations (such as merging color conversion with upsampling)
  174716. * and it also interfered with desired capabilities such as quantizing to an
  174717. * externally-supplied colormap. We have therefore abandoned that approach.
  174718. * The present code works in the post-conversion color space, typically RGB.
  174719. *
  174720. * To improve the visual quality of the results, we actually work in scaled
  174721. * RGB space, giving G distances more weight than R, and R in turn more than
  174722. * B. To do everything in integer math, we must use integer scale factors.
  174723. * The 2/3/1 scale factors used here correspond loosely to the relative
  174724. * weights of the colors in the NTSC grayscale equation.
  174725. * If you want to use this code to quantize a non-RGB color space, you'll
  174726. * probably need to change these scale factors.
  174727. */
  174728. #define R_SCALE 2 /* scale R distances by this much */
  174729. #define G_SCALE 3 /* scale G distances by this much */
  174730. #define B_SCALE 1 /* and B by this much */
  174731. /* Relabel R/G/B as components 0/1/2, respecting the RGB ordering defined
  174732. * in jmorecfg.h. As the code stands, it will do the right thing for R,G,B
  174733. * and B,G,R orders. If you define some other weird order in jmorecfg.h,
  174734. * you'll get compile errors until you extend this logic. In that case
  174735. * you'll probably want to tweak the histogram sizes too.
  174736. */
  174737. #if RGB_RED == 0
  174738. #define C0_SCALE R_SCALE
  174739. #endif
  174740. #if RGB_BLUE == 0
  174741. #define C0_SCALE B_SCALE
  174742. #endif
  174743. #if RGB_GREEN == 1
  174744. #define C1_SCALE G_SCALE
  174745. #endif
  174746. #if RGB_RED == 2
  174747. #define C2_SCALE R_SCALE
  174748. #endif
  174749. #if RGB_BLUE == 2
  174750. #define C2_SCALE B_SCALE
  174751. #endif
  174752. /*
  174753. * First we have the histogram data structure and routines for creating it.
  174754. *
  174755. * The number of bits of precision can be adjusted by changing these symbols.
  174756. * We recommend keeping 6 bits for G and 5 each for R and B.
  174757. * If you have plenty of memory and cycles, 6 bits all around gives marginally
  174758. * better results; if you are short of memory, 5 bits all around will save
  174759. * some space but degrade the results.
  174760. * To maintain a fully accurate histogram, we'd need to allocate a "long"
  174761. * (preferably unsigned long) for each cell. In practice this is overkill;
  174762. * we can get by with 16 bits per cell. Few of the cell counts will overflow,
  174763. * and clamping those that do overflow to the maximum value will give close-
  174764. * enough results. This reduces the recommended histogram size from 256Kb
  174765. * to 128Kb, which is a useful savings on PC-class machines.
  174766. * (In the second pass the histogram space is re-used for pixel mapping data;
  174767. * in that capacity, each cell must be able to store zero to the number of
  174768. * desired colors. 16 bits/cell is plenty for that too.)
  174769. * Since the JPEG code is intended to run in small memory model on 80x86
  174770. * machines, we can't just allocate the histogram in one chunk. Instead
  174771. * of a true 3-D array, we use a row of pointers to 2-D arrays. Each
  174772. * pointer corresponds to a C0 value (typically 2^5 = 32 pointers) and
  174773. * each 2-D array has 2^6*2^5 = 2048 or 2^6*2^6 = 4096 entries. Note that
  174774. * on 80x86 machines, the pointer row is in near memory but the actual
  174775. * arrays are in far memory (same arrangement as we use for image arrays).
  174776. */
  174777. #define MAXNUMCOLORS (MAXJSAMPLE+1) /* maximum size of colormap */
  174778. /* These will do the right thing for either R,G,B or B,G,R color order,
  174779. * but you may not like the results for other color orders.
  174780. */
  174781. #define HIST_C0_BITS 5 /* bits of precision in R/B histogram */
  174782. #define HIST_C1_BITS 6 /* bits of precision in G histogram */
  174783. #define HIST_C2_BITS 5 /* bits of precision in B/R histogram */
  174784. /* Number of elements along histogram axes. */
  174785. #define HIST_C0_ELEMS (1<<HIST_C0_BITS)
  174786. #define HIST_C1_ELEMS (1<<HIST_C1_BITS)
  174787. #define HIST_C2_ELEMS (1<<HIST_C2_BITS)
  174788. /* These are the amounts to shift an input value to get a histogram index. */
  174789. #define C0_SHIFT (BITS_IN_JSAMPLE-HIST_C0_BITS)
  174790. #define C1_SHIFT (BITS_IN_JSAMPLE-HIST_C1_BITS)
  174791. #define C2_SHIFT (BITS_IN_JSAMPLE-HIST_C2_BITS)
  174792. typedef UINT16 histcell; /* histogram cell; prefer an unsigned type */
  174793. typedef histcell FAR * histptr; /* for pointers to histogram cells */
  174794. typedef histcell hist1d[HIST_C2_ELEMS]; /* typedefs for the array */
  174795. typedef hist1d FAR * hist2d; /* type for the 2nd-level pointers */
  174796. typedef hist2d * hist3d; /* type for top-level pointer */
  174797. /* Declarations for Floyd-Steinberg dithering.
  174798. *
  174799. * Errors are accumulated into the array fserrors[], at a resolution of
  174800. * 1/16th of a pixel count. The error at a given pixel is propagated
  174801. * to its not-yet-processed neighbors using the standard F-S fractions,
  174802. * ... (here) 7/16
  174803. * 3/16 5/16 1/16
  174804. * We work left-to-right on even rows, right-to-left on odd rows.
  174805. *
  174806. * We can get away with a single array (holding one row's worth of errors)
  174807. * by using it to store the current row's errors at pixel columns not yet
  174808. * processed, but the next row's errors at columns already processed. We
  174809. * need only a few extra variables to hold the errors immediately around the
  174810. * current column. (If we are lucky, those variables are in registers, but
  174811. * even if not, they're probably cheaper to access than array elements are.)
  174812. *
  174813. * The fserrors[] array has (#columns + 2) entries; the extra entry at
  174814. * each end saves us from special-casing the first and last pixels.
  174815. * Each entry is three values long, one value for each color component.
  174816. *
  174817. * Note: on a wide image, we might not have enough room in a PC's near data
  174818. * segment to hold the error array; so it is allocated with alloc_large.
  174819. */
  174820. #if BITS_IN_JSAMPLE == 8
  174821. typedef INT16 FSERROR; /* 16 bits should be enough */
  174822. typedef int LOCFSERROR; /* use 'int' for calculation temps */
  174823. #else
  174824. typedef INT32 FSERROR; /* may need more than 16 bits */
  174825. typedef INT32 LOCFSERROR; /* be sure calculation temps are big enough */
  174826. #endif
  174827. typedef FSERROR FAR *FSERRPTR; /* pointer to error array (in FAR storage!) */
  174828. /* Private subobject */
  174829. typedef struct {
  174830. struct jpeg_color_quantizer pub; /* public fields */
  174831. /* Space for the eventually created colormap is stashed here */
  174832. JSAMPARRAY sv_colormap; /* colormap allocated at init time */
  174833. int desired; /* desired # of colors = size of colormap */
  174834. /* Variables for accumulating image statistics */
  174835. hist3d histogram; /* pointer to the histogram */
  174836. boolean needs_zeroed; /* TRUE if next pass must zero histogram */
  174837. /* Variables for Floyd-Steinberg dithering */
  174838. FSERRPTR fserrors; /* accumulated errors */
  174839. boolean on_odd_row; /* flag to remember which row we are on */
  174840. int * error_limiter; /* table for clamping the applied error */
  174841. } my_cquantizer2;
  174842. typedef my_cquantizer2 * my_cquantize_ptr2;
  174843. /*
  174844. * Prescan some rows of pixels.
  174845. * In this module the prescan simply updates the histogram, which has been
  174846. * initialized to zeroes by start_pass.
  174847. * An output_buf parameter is required by the method signature, but no data
  174848. * is actually output (in fact the buffer controller is probably passing a
  174849. * NULL pointer).
  174850. */
  174851. METHODDEF(void)
  174852. prescan_quantize (j_decompress_ptr cinfo, JSAMPARRAY input_buf,
  174853. JSAMPARRAY, int num_rows)
  174854. {
  174855. my_cquantize_ptr2 cquantize = (my_cquantize_ptr2) cinfo->cquantize;
  174856. register JSAMPROW ptr;
  174857. register histptr histp;
  174858. register hist3d histogram = cquantize->histogram;
  174859. int row;
  174860. JDIMENSION col;
  174861. JDIMENSION width = cinfo->output_width;
  174862. for (row = 0; row < num_rows; row++) {
  174863. ptr = input_buf[row];
  174864. for (col = width; col > 0; col--) {
  174865. /* get pixel value and index into the histogram */
  174866. histp = & histogram[GETJSAMPLE(ptr[0]) >> C0_SHIFT]
  174867. [GETJSAMPLE(ptr[1]) >> C1_SHIFT]
  174868. [GETJSAMPLE(ptr[2]) >> C2_SHIFT];
  174869. /* increment, check for overflow and undo increment if so. */
  174870. if (++(*histp) <= 0)
  174871. (*histp)--;
  174872. ptr += 3;
  174873. }
  174874. }
  174875. }
  174876. /*
  174877. * Next we have the really interesting routines: selection of a colormap
  174878. * given the completed histogram.
  174879. * These routines work with a list of "boxes", each representing a rectangular
  174880. * subset of the input color space (to histogram precision).
  174881. */
  174882. typedef struct {
  174883. /* The bounds of the box (inclusive); expressed as histogram indexes */
  174884. int c0min, c0max;
  174885. int c1min, c1max;
  174886. int c2min, c2max;
  174887. /* The volume (actually 2-norm) of the box */
  174888. INT32 volume;
  174889. /* The number of nonzero histogram cells within this box */
  174890. long colorcount;
  174891. } box;
  174892. typedef box * boxptr;
  174893. LOCAL(boxptr)
  174894. find_biggest_color_pop (boxptr boxlist, int numboxes)
  174895. /* Find the splittable box with the largest color population */
  174896. /* Returns NULL if no splittable boxes remain */
  174897. {
  174898. register boxptr boxp;
  174899. register int i;
  174900. register long maxc = 0;
  174901. boxptr which = NULL;
  174902. for (i = 0, boxp = boxlist; i < numboxes; i++, boxp++) {
  174903. if (boxp->colorcount > maxc && boxp->volume > 0) {
  174904. which = boxp;
  174905. maxc = boxp->colorcount;
  174906. }
  174907. }
  174908. return which;
  174909. }
  174910. LOCAL(boxptr)
  174911. find_biggest_volume (boxptr boxlist, int numboxes)
  174912. /* Find the splittable box with the largest (scaled) volume */
  174913. /* Returns NULL if no splittable boxes remain */
  174914. {
  174915. register boxptr boxp;
  174916. register int i;
  174917. register INT32 maxv = 0;
  174918. boxptr which = NULL;
  174919. for (i = 0, boxp = boxlist; i < numboxes; i++, boxp++) {
  174920. if (boxp->volume > maxv) {
  174921. which = boxp;
  174922. maxv = boxp->volume;
  174923. }
  174924. }
  174925. return which;
  174926. }
  174927. LOCAL(void)
  174928. update_box (j_decompress_ptr cinfo, boxptr boxp)
  174929. /* Shrink the min/max bounds of a box to enclose only nonzero elements, */
  174930. /* and recompute its volume and population */
  174931. {
  174932. my_cquantize_ptr2 cquantize = (my_cquantize_ptr2) cinfo->cquantize;
  174933. hist3d histogram = cquantize->histogram;
  174934. histptr histp;
  174935. int c0,c1,c2;
  174936. int c0min,c0max,c1min,c1max,c2min,c2max;
  174937. INT32 dist0,dist1,dist2;
  174938. long ccount;
  174939. c0min = boxp->c0min; c0max = boxp->c0max;
  174940. c1min = boxp->c1min; c1max = boxp->c1max;
  174941. c2min = boxp->c2min; c2max = boxp->c2max;
  174942. if (c0max > c0min)
  174943. for (c0 = c0min; c0 <= c0max; c0++)
  174944. for (c1 = c1min; c1 <= c1max; c1++) {
  174945. histp = & histogram[c0][c1][c2min];
  174946. for (c2 = c2min; c2 <= c2max; c2++)
  174947. if (*histp++ != 0) {
  174948. boxp->c0min = c0min = c0;
  174949. goto have_c0min;
  174950. }
  174951. }
  174952. have_c0min:
  174953. if (c0max > c0min)
  174954. for (c0 = c0max; c0 >= c0min; c0--)
  174955. for (c1 = c1min; c1 <= c1max; c1++) {
  174956. histp = & histogram[c0][c1][c2min];
  174957. for (c2 = c2min; c2 <= c2max; c2++)
  174958. if (*histp++ != 0) {
  174959. boxp->c0max = c0max = c0;
  174960. goto have_c0max;
  174961. }
  174962. }
  174963. have_c0max:
  174964. if (c1max > c1min)
  174965. for (c1 = c1min; c1 <= c1max; c1++)
  174966. for (c0 = c0min; c0 <= c0max; c0++) {
  174967. histp = & histogram[c0][c1][c2min];
  174968. for (c2 = c2min; c2 <= c2max; c2++)
  174969. if (*histp++ != 0) {
  174970. boxp->c1min = c1min = c1;
  174971. goto have_c1min;
  174972. }
  174973. }
  174974. have_c1min:
  174975. if (c1max > c1min)
  174976. for (c1 = c1max; c1 >= c1min; c1--)
  174977. for (c0 = c0min; c0 <= c0max; c0++) {
  174978. histp = & histogram[c0][c1][c2min];
  174979. for (c2 = c2min; c2 <= c2max; c2++)
  174980. if (*histp++ != 0) {
  174981. boxp->c1max = c1max = c1;
  174982. goto have_c1max;
  174983. }
  174984. }
  174985. have_c1max:
  174986. if (c2max > c2min)
  174987. for (c2 = c2min; c2 <= c2max; c2++)
  174988. for (c0 = c0min; c0 <= c0max; c0++) {
  174989. histp = & histogram[c0][c1min][c2];
  174990. for (c1 = c1min; c1 <= c1max; c1++, histp += HIST_C2_ELEMS)
  174991. if (*histp != 0) {
  174992. boxp->c2min = c2min = c2;
  174993. goto have_c2min;
  174994. }
  174995. }
  174996. have_c2min:
  174997. if (c2max > c2min)
  174998. for (c2 = c2max; c2 >= c2min; c2--)
  174999. for (c0 = c0min; c0 <= c0max; c0++) {
  175000. histp = & histogram[c0][c1min][c2];
  175001. for (c1 = c1min; c1 <= c1max; c1++, histp += HIST_C2_ELEMS)
  175002. if (*histp != 0) {
  175003. boxp->c2max = c2max = c2;
  175004. goto have_c2max;
  175005. }
  175006. }
  175007. have_c2max:
  175008. /* Update box volume.
  175009. * We use 2-norm rather than real volume here; this biases the method
  175010. * against making long narrow boxes, and it has the side benefit that
  175011. * a box is splittable iff norm > 0.
  175012. * Since the differences are expressed in histogram-cell units,
  175013. * we have to shift back to JSAMPLE units to get consistent distances;
  175014. * after which, we scale according to the selected distance scale factors.
  175015. */
  175016. dist0 = ((c0max - c0min) << C0_SHIFT) * C0_SCALE;
  175017. dist1 = ((c1max - c1min) << C1_SHIFT) * C1_SCALE;
  175018. dist2 = ((c2max - c2min) << C2_SHIFT) * C2_SCALE;
  175019. boxp->volume = dist0*dist0 + dist1*dist1 + dist2*dist2;
  175020. /* Now scan remaining volume of box and compute population */
  175021. ccount = 0;
  175022. for (c0 = c0min; c0 <= c0max; c0++)
  175023. for (c1 = c1min; c1 <= c1max; c1++) {
  175024. histp = & histogram[c0][c1][c2min];
  175025. for (c2 = c2min; c2 <= c2max; c2++, histp++)
  175026. if (*histp != 0) {
  175027. ccount++;
  175028. }
  175029. }
  175030. boxp->colorcount = ccount;
  175031. }
  175032. LOCAL(int)
  175033. median_cut (j_decompress_ptr cinfo, boxptr boxlist, int numboxes,
  175034. int desired_colors)
  175035. /* Repeatedly select and split the largest box until we have enough boxes */
  175036. {
  175037. int n,lb;
  175038. int c0,c1,c2,cmax;
  175039. register boxptr b1,b2;
  175040. while (numboxes < desired_colors) {
  175041. /* Select box to split.
  175042. * Current algorithm: by population for first half, then by volume.
  175043. */
  175044. if (numboxes*2 <= desired_colors) {
  175045. b1 = find_biggest_color_pop(boxlist, numboxes);
  175046. } else {
  175047. b1 = find_biggest_volume(boxlist, numboxes);
  175048. }
  175049. if (b1 == NULL) /* no splittable boxes left! */
  175050. break;
  175051. b2 = &boxlist[numboxes]; /* where new box will go */
  175052. /* Copy the color bounds to the new box. */
  175053. b2->c0max = b1->c0max; b2->c1max = b1->c1max; b2->c2max = b1->c2max;
  175054. b2->c0min = b1->c0min; b2->c1min = b1->c1min; b2->c2min = b1->c2min;
  175055. /* Choose which axis to split the box on.
  175056. * Current algorithm: longest scaled axis.
  175057. * See notes in update_box about scaling distances.
  175058. */
  175059. c0 = ((b1->c0max - b1->c0min) << C0_SHIFT) * C0_SCALE;
  175060. c1 = ((b1->c1max - b1->c1min) << C1_SHIFT) * C1_SCALE;
  175061. c2 = ((b1->c2max - b1->c2min) << C2_SHIFT) * C2_SCALE;
  175062. /* We want to break any ties in favor of green, then red, blue last.
  175063. * This code does the right thing for R,G,B or B,G,R color orders only.
  175064. */
  175065. #if RGB_RED == 0
  175066. cmax = c1; n = 1;
  175067. if (c0 > cmax) { cmax = c0; n = 0; }
  175068. if (c2 > cmax) { n = 2; }
  175069. #else
  175070. cmax = c1; n = 1;
  175071. if (c2 > cmax) { cmax = c2; n = 2; }
  175072. if (c0 > cmax) { n = 0; }
  175073. #endif
  175074. /* Choose split point along selected axis, and update box bounds.
  175075. * Current algorithm: split at halfway point.
  175076. * (Since the box has been shrunk to minimum volume,
  175077. * any split will produce two nonempty subboxes.)
  175078. * Note that lb value is max for lower box, so must be < old max.
  175079. */
  175080. switch (n) {
  175081. case 0:
  175082. lb = (b1->c0max + b1->c0min) / 2;
  175083. b1->c0max = lb;
  175084. b2->c0min = lb+1;
  175085. break;
  175086. case 1:
  175087. lb = (b1->c1max + b1->c1min) / 2;
  175088. b1->c1max = lb;
  175089. b2->c1min = lb+1;
  175090. break;
  175091. case 2:
  175092. lb = (b1->c2max + b1->c2min) / 2;
  175093. b1->c2max = lb;
  175094. b2->c2min = lb+1;
  175095. break;
  175096. }
  175097. /* Update stats for boxes */
  175098. update_box(cinfo, b1);
  175099. update_box(cinfo, b2);
  175100. numboxes++;
  175101. }
  175102. return numboxes;
  175103. }
  175104. LOCAL(void)
  175105. compute_color (j_decompress_ptr cinfo, boxptr boxp, int icolor)
  175106. /* Compute representative color for a box, put it in colormap[icolor] */
  175107. {
  175108. /* Current algorithm: mean weighted by pixels (not colors) */
  175109. /* Note it is important to get the rounding correct! */
  175110. my_cquantize_ptr2 cquantize = (my_cquantize_ptr2) cinfo->cquantize;
  175111. hist3d histogram = cquantize->histogram;
  175112. histptr histp;
  175113. int c0,c1,c2;
  175114. int c0min,c0max,c1min,c1max,c2min,c2max;
  175115. long count;
  175116. long total = 0;
  175117. long c0total = 0;
  175118. long c1total = 0;
  175119. long c2total = 0;
  175120. c0min = boxp->c0min; c0max = boxp->c0max;
  175121. c1min = boxp->c1min; c1max = boxp->c1max;
  175122. c2min = boxp->c2min; c2max = boxp->c2max;
  175123. for (c0 = c0min; c0 <= c0max; c0++)
  175124. for (c1 = c1min; c1 <= c1max; c1++) {
  175125. histp = & histogram[c0][c1][c2min];
  175126. for (c2 = c2min; c2 <= c2max; c2++) {
  175127. if ((count = *histp++) != 0) {
  175128. total += count;
  175129. c0total += ((c0 << C0_SHIFT) + ((1<<C0_SHIFT)>>1)) * count;
  175130. c1total += ((c1 << C1_SHIFT) + ((1<<C1_SHIFT)>>1)) * count;
  175131. c2total += ((c2 << C2_SHIFT) + ((1<<C2_SHIFT)>>1)) * count;
  175132. }
  175133. }
  175134. }
  175135. cinfo->colormap[0][icolor] = (JSAMPLE) ((c0total + (total>>1)) / total);
  175136. cinfo->colormap[1][icolor] = (JSAMPLE) ((c1total + (total>>1)) / total);
  175137. cinfo->colormap[2][icolor] = (JSAMPLE) ((c2total + (total>>1)) / total);
  175138. }
  175139. LOCAL(void)
  175140. select_colors (j_decompress_ptr cinfo, int desired_colors)
  175141. /* Master routine for color selection */
  175142. {
  175143. boxptr boxlist;
  175144. int numboxes;
  175145. int i;
  175146. /* Allocate workspace for box list */
  175147. boxlist = (boxptr) (*cinfo->mem->alloc_small)
  175148. ((j_common_ptr) cinfo, JPOOL_IMAGE, desired_colors * SIZEOF(box));
  175149. /* Initialize one box containing whole space */
  175150. numboxes = 1;
  175151. boxlist[0].c0min = 0;
  175152. boxlist[0].c0max = MAXJSAMPLE >> C0_SHIFT;
  175153. boxlist[0].c1min = 0;
  175154. boxlist[0].c1max = MAXJSAMPLE >> C1_SHIFT;
  175155. boxlist[0].c2min = 0;
  175156. boxlist[0].c2max = MAXJSAMPLE >> C2_SHIFT;
  175157. /* Shrink it to actually-used volume and set its statistics */
  175158. update_box(cinfo, & boxlist[0]);
  175159. /* Perform median-cut to produce final box list */
  175160. numboxes = median_cut(cinfo, boxlist, numboxes, desired_colors);
  175161. /* Compute the representative color for each box, fill colormap */
  175162. for (i = 0; i < numboxes; i++)
  175163. compute_color(cinfo, & boxlist[i], i);
  175164. cinfo->actual_number_of_colors = numboxes;
  175165. TRACEMS1(cinfo, 1, JTRC_QUANT_SELECTED, numboxes);
  175166. }
  175167. /*
  175168. * These routines are concerned with the time-critical task of mapping input
  175169. * colors to the nearest color in the selected colormap.
  175170. *
  175171. * We re-use the histogram space as an "inverse color map", essentially a
  175172. * cache for the results of nearest-color searches. All colors within a
  175173. * histogram cell will be mapped to the same colormap entry, namely the one
  175174. * closest to the cell's center. This may not be quite the closest entry to
  175175. * the actual input color, but it's almost as good. A zero in the cache
  175176. * indicates we haven't found the nearest color for that cell yet; the array
  175177. * is cleared to zeroes before starting the mapping pass. When we find the
  175178. * nearest color for a cell, its colormap index plus one is recorded in the
  175179. * cache for future use. The pass2 scanning routines call fill_inverse_cmap
  175180. * when they need to use an unfilled entry in the cache.
  175181. *
  175182. * Our method of efficiently finding nearest colors is based on the "locally
  175183. * sorted search" idea described by Heckbert and on the incremental distance
  175184. * calculation described by Spencer W. Thomas in chapter III.1 of Graphics
  175185. * Gems II (James Arvo, ed. Academic Press, 1991). Thomas points out that
  175186. * the distances from a given colormap entry to each cell of the histogram can
  175187. * be computed quickly using an incremental method: the differences between
  175188. * distances to adjacent cells themselves differ by a constant. This allows a
  175189. * fairly fast implementation of the "brute force" approach of computing the
  175190. * distance from every colormap entry to every histogram cell. Unfortunately,
  175191. * it needs a work array to hold the best-distance-so-far for each histogram
  175192. * cell (because the inner loop has to be over cells, not colormap entries).
  175193. * The work array elements have to be INT32s, so the work array would need
  175194. * 256Kb at our recommended precision. This is not feasible in DOS machines.
  175195. *
  175196. * To get around these problems, we apply Thomas' method to compute the
  175197. * nearest colors for only the cells within a small subbox of the histogram.
  175198. * The work array need be only as big as the subbox, so the memory usage
  175199. * problem is solved. Furthermore, we need not fill subboxes that are never
  175200. * referenced in pass2; many images use only part of the color gamut, so a
  175201. * fair amount of work is saved. An additional advantage of this
  175202. * approach is that we can apply Heckbert's locality criterion to quickly
  175203. * eliminate colormap entries that are far away from the subbox; typically
  175204. * three-fourths of the colormap entries are rejected by Heckbert's criterion,
  175205. * and we need not compute their distances to individual cells in the subbox.
  175206. * The speed of this approach is heavily influenced by the subbox size: too
  175207. * small means too much overhead, too big loses because Heckbert's criterion
  175208. * can't eliminate as many colormap entries. Empirically the best subbox
  175209. * size seems to be about 1/512th of the histogram (1/8th in each direction).
  175210. *
  175211. * Thomas' article also describes a refined method which is asymptotically
  175212. * faster than the brute-force method, but it is also far more complex and
  175213. * cannot efficiently be applied to small subboxes. It is therefore not
  175214. * useful for programs intended to be portable to DOS machines. On machines
  175215. * with plenty of memory, filling the whole histogram in one shot with Thomas'
  175216. * refined method might be faster than the present code --- but then again,
  175217. * it might not be any faster, and it's certainly more complicated.
  175218. */
  175219. /* log2(histogram cells in update box) for each axis; this can be adjusted */
  175220. #define BOX_C0_LOG (HIST_C0_BITS-3)
  175221. #define BOX_C1_LOG (HIST_C1_BITS-3)
  175222. #define BOX_C2_LOG (HIST_C2_BITS-3)
  175223. #define BOX_C0_ELEMS (1<<BOX_C0_LOG) /* # of hist cells in update box */
  175224. #define BOX_C1_ELEMS (1<<BOX_C1_LOG)
  175225. #define BOX_C2_ELEMS (1<<BOX_C2_LOG)
  175226. #define BOX_C0_SHIFT (C0_SHIFT + BOX_C0_LOG)
  175227. #define BOX_C1_SHIFT (C1_SHIFT + BOX_C1_LOG)
  175228. #define BOX_C2_SHIFT (C2_SHIFT + BOX_C2_LOG)
  175229. /*
  175230. * The next three routines implement inverse colormap filling. They could
  175231. * all be folded into one big routine, but splitting them up this way saves
  175232. * some stack space (the mindist[] and bestdist[] arrays need not coexist)
  175233. * and may allow some compilers to produce better code by registerizing more
  175234. * inner-loop variables.
  175235. */
  175236. LOCAL(int)
  175237. find_nearby_colors (j_decompress_ptr cinfo, int minc0, int minc1, int minc2,
  175238. JSAMPLE colorlist[])
  175239. /* Locate the colormap entries close enough to an update box to be candidates
  175240. * for the nearest entry to some cell(s) in the update box. The update box
  175241. * is specified by the center coordinates of its first cell. The number of
  175242. * candidate colormap entries is returned, and their colormap indexes are
  175243. * placed in colorlist[].
  175244. * This routine uses Heckbert's "locally sorted search" criterion to select
  175245. * the colors that need further consideration.
  175246. */
  175247. {
  175248. int numcolors = cinfo->actual_number_of_colors;
  175249. int maxc0, maxc1, maxc2;
  175250. int centerc0, centerc1, centerc2;
  175251. int i, x, ncolors;
  175252. INT32 minmaxdist, min_dist, max_dist, tdist;
  175253. INT32 mindist[MAXNUMCOLORS]; /* min distance to colormap entry i */
  175254. /* Compute true coordinates of update box's upper corner and center.
  175255. * Actually we compute the coordinates of the center of the upper-corner
  175256. * histogram cell, which are the upper bounds of the volume we care about.
  175257. * Note that since ">>" rounds down, the "center" values may be closer to
  175258. * min than to max; hence comparisons to them must be "<=", not "<".
  175259. */
  175260. maxc0 = minc0 + ((1 << BOX_C0_SHIFT) - (1 << C0_SHIFT));
  175261. centerc0 = (minc0 + maxc0) >> 1;
  175262. maxc1 = minc1 + ((1 << BOX_C1_SHIFT) - (1 << C1_SHIFT));
  175263. centerc1 = (minc1 + maxc1) >> 1;
  175264. maxc2 = minc2 + ((1 << BOX_C2_SHIFT) - (1 << C2_SHIFT));
  175265. centerc2 = (minc2 + maxc2) >> 1;
  175266. /* For each color in colormap, find:
  175267. * 1. its minimum squared-distance to any point in the update box
  175268. * (zero if color is within update box);
  175269. * 2. its maximum squared-distance to any point in the update box.
  175270. * Both of these can be found by considering only the corners of the box.
  175271. * We save the minimum distance for each color in mindist[];
  175272. * only the smallest maximum distance is of interest.
  175273. */
  175274. minmaxdist = 0x7FFFFFFFL;
  175275. for (i = 0; i < numcolors; i++) {
  175276. /* We compute the squared-c0-distance term, then add in the other two. */
  175277. x = GETJSAMPLE(cinfo->colormap[0][i]);
  175278. if (x < minc0) {
  175279. tdist = (x - minc0) * C0_SCALE;
  175280. min_dist = tdist*tdist;
  175281. tdist = (x - maxc0) * C0_SCALE;
  175282. max_dist = tdist*tdist;
  175283. } else if (x > maxc0) {
  175284. tdist = (x - maxc0) * C0_SCALE;
  175285. min_dist = tdist*tdist;
  175286. tdist = (x - minc0) * C0_SCALE;
  175287. max_dist = tdist*tdist;
  175288. } else {
  175289. /* within cell range so no contribution to min_dist */
  175290. min_dist = 0;
  175291. if (x <= centerc0) {
  175292. tdist = (x - maxc0) * C0_SCALE;
  175293. max_dist = tdist*tdist;
  175294. } else {
  175295. tdist = (x - minc0) * C0_SCALE;
  175296. max_dist = tdist*tdist;
  175297. }
  175298. }
  175299. x = GETJSAMPLE(cinfo->colormap[1][i]);
  175300. if (x < minc1) {
  175301. tdist = (x - minc1) * C1_SCALE;
  175302. min_dist += tdist*tdist;
  175303. tdist = (x - maxc1) * C1_SCALE;
  175304. max_dist += tdist*tdist;
  175305. } else if (x > maxc1) {
  175306. tdist = (x - maxc1) * C1_SCALE;
  175307. min_dist += tdist*tdist;
  175308. tdist = (x - minc1) * C1_SCALE;
  175309. max_dist += tdist*tdist;
  175310. } else {
  175311. /* within cell range so no contribution to min_dist */
  175312. if (x <= centerc1) {
  175313. tdist = (x - maxc1) * C1_SCALE;
  175314. max_dist += tdist*tdist;
  175315. } else {
  175316. tdist = (x - minc1) * C1_SCALE;
  175317. max_dist += tdist*tdist;
  175318. }
  175319. }
  175320. x = GETJSAMPLE(cinfo->colormap[2][i]);
  175321. if (x < minc2) {
  175322. tdist = (x - minc2) * C2_SCALE;
  175323. min_dist += tdist*tdist;
  175324. tdist = (x - maxc2) * C2_SCALE;
  175325. max_dist += tdist*tdist;
  175326. } else if (x > maxc2) {
  175327. tdist = (x - maxc2) * C2_SCALE;
  175328. min_dist += tdist*tdist;
  175329. tdist = (x - minc2) * C2_SCALE;
  175330. max_dist += tdist*tdist;
  175331. } else {
  175332. /* within cell range so no contribution to min_dist */
  175333. if (x <= centerc2) {
  175334. tdist = (x - maxc2) * C2_SCALE;
  175335. max_dist += tdist*tdist;
  175336. } else {
  175337. tdist = (x - minc2) * C2_SCALE;
  175338. max_dist += tdist*tdist;
  175339. }
  175340. }
  175341. mindist[i] = min_dist; /* save away the results */
  175342. if (max_dist < minmaxdist)
  175343. minmaxdist = max_dist;
  175344. }
  175345. /* Now we know that no cell in the update box is more than minmaxdist
  175346. * away from some colormap entry. Therefore, only colors that are
  175347. * within minmaxdist of some part of the box need be considered.
  175348. */
  175349. ncolors = 0;
  175350. for (i = 0; i < numcolors; i++) {
  175351. if (mindist[i] <= minmaxdist)
  175352. colorlist[ncolors++] = (JSAMPLE) i;
  175353. }
  175354. return ncolors;
  175355. }
  175356. LOCAL(void)
  175357. find_best_colors (j_decompress_ptr cinfo, int minc0, int minc1, int minc2,
  175358. int numcolors, JSAMPLE colorlist[], JSAMPLE bestcolor[])
  175359. /* Find the closest colormap entry for each cell in the update box,
  175360. * given the list of candidate colors prepared by find_nearby_colors.
  175361. * Return the indexes of the closest entries in the bestcolor[] array.
  175362. * This routine uses Thomas' incremental distance calculation method to
  175363. * find the distance from a colormap entry to successive cells in the box.
  175364. */
  175365. {
  175366. int ic0, ic1, ic2;
  175367. int i, icolor;
  175368. register INT32 * bptr; /* pointer into bestdist[] array */
  175369. JSAMPLE * cptr; /* pointer into bestcolor[] array */
  175370. INT32 dist0, dist1; /* initial distance values */
  175371. register INT32 dist2; /* current distance in inner loop */
  175372. INT32 xx0, xx1; /* distance increments */
  175373. register INT32 xx2;
  175374. INT32 inc0, inc1, inc2; /* initial values for increments */
  175375. /* This array holds the distance to the nearest-so-far color for each cell */
  175376. INT32 bestdist[BOX_C0_ELEMS * BOX_C1_ELEMS * BOX_C2_ELEMS];
  175377. /* Initialize best-distance for each cell of the update box */
  175378. bptr = bestdist;
  175379. for (i = BOX_C0_ELEMS*BOX_C1_ELEMS*BOX_C2_ELEMS-1; i >= 0; i--)
  175380. *bptr++ = 0x7FFFFFFFL;
  175381. /* For each color selected by find_nearby_colors,
  175382. * compute its distance to the center of each cell in the box.
  175383. * If that's less than best-so-far, update best distance and color number.
  175384. */
  175385. /* Nominal steps between cell centers ("x" in Thomas article) */
  175386. #define STEP_C0 ((1 << C0_SHIFT) * C0_SCALE)
  175387. #define STEP_C1 ((1 << C1_SHIFT) * C1_SCALE)
  175388. #define STEP_C2 ((1 << C2_SHIFT) * C2_SCALE)
  175389. for (i = 0; i < numcolors; i++) {
  175390. icolor = GETJSAMPLE(colorlist[i]);
  175391. /* Compute (square of) distance from minc0/c1/c2 to this color */
  175392. inc0 = (minc0 - GETJSAMPLE(cinfo->colormap[0][icolor])) * C0_SCALE;
  175393. dist0 = inc0*inc0;
  175394. inc1 = (minc1 - GETJSAMPLE(cinfo->colormap[1][icolor])) * C1_SCALE;
  175395. dist0 += inc1*inc1;
  175396. inc2 = (minc2 - GETJSAMPLE(cinfo->colormap[2][icolor])) * C2_SCALE;
  175397. dist0 += inc2*inc2;
  175398. /* Form the initial difference increments */
  175399. inc0 = inc0 * (2 * STEP_C0) + STEP_C0 * STEP_C0;
  175400. inc1 = inc1 * (2 * STEP_C1) + STEP_C1 * STEP_C1;
  175401. inc2 = inc2 * (2 * STEP_C2) + STEP_C2 * STEP_C2;
  175402. /* Now loop over all cells in box, updating distance per Thomas method */
  175403. bptr = bestdist;
  175404. cptr = bestcolor;
  175405. xx0 = inc0;
  175406. for (ic0 = BOX_C0_ELEMS-1; ic0 >= 0; ic0--) {
  175407. dist1 = dist0;
  175408. xx1 = inc1;
  175409. for (ic1 = BOX_C1_ELEMS-1; ic1 >= 0; ic1--) {
  175410. dist2 = dist1;
  175411. xx2 = inc2;
  175412. for (ic2 = BOX_C2_ELEMS-1; ic2 >= 0; ic2--) {
  175413. if (dist2 < *bptr) {
  175414. *bptr = dist2;
  175415. *cptr = (JSAMPLE) icolor;
  175416. }
  175417. dist2 += xx2;
  175418. xx2 += 2 * STEP_C2 * STEP_C2;
  175419. bptr++;
  175420. cptr++;
  175421. }
  175422. dist1 += xx1;
  175423. xx1 += 2 * STEP_C1 * STEP_C1;
  175424. }
  175425. dist0 += xx0;
  175426. xx0 += 2 * STEP_C0 * STEP_C0;
  175427. }
  175428. }
  175429. }
  175430. LOCAL(void)
  175431. fill_inverse_cmap (j_decompress_ptr cinfo, int c0, int c1, int c2)
  175432. /* Fill the inverse-colormap entries in the update box that contains */
  175433. /* histogram cell c0/c1/c2. (Only that one cell MUST be filled, but */
  175434. /* we can fill as many others as we wish.) */
  175435. {
  175436. my_cquantize_ptr2 cquantize = (my_cquantize_ptr2) cinfo->cquantize;
  175437. hist3d histogram = cquantize->histogram;
  175438. int minc0, minc1, minc2; /* lower left corner of update box */
  175439. int ic0, ic1, ic2;
  175440. register JSAMPLE * cptr; /* pointer into bestcolor[] array */
  175441. register histptr cachep; /* pointer into main cache array */
  175442. /* This array lists the candidate colormap indexes. */
  175443. JSAMPLE colorlist[MAXNUMCOLORS];
  175444. int numcolors; /* number of candidate colors */
  175445. /* This array holds the actually closest colormap index for each cell. */
  175446. JSAMPLE bestcolor[BOX_C0_ELEMS * BOX_C1_ELEMS * BOX_C2_ELEMS];
  175447. /* Convert cell coordinates to update box ID */
  175448. c0 >>= BOX_C0_LOG;
  175449. c1 >>= BOX_C1_LOG;
  175450. c2 >>= BOX_C2_LOG;
  175451. /* Compute true coordinates of update box's origin corner.
  175452. * Actually we compute the coordinates of the center of the corner
  175453. * histogram cell, which are the lower bounds of the volume we care about.
  175454. */
  175455. minc0 = (c0 << BOX_C0_SHIFT) + ((1 << C0_SHIFT) >> 1);
  175456. minc1 = (c1 << BOX_C1_SHIFT) + ((1 << C1_SHIFT) >> 1);
  175457. minc2 = (c2 << BOX_C2_SHIFT) + ((1 << C2_SHIFT) >> 1);
  175458. /* Determine which colormap entries are close enough to be candidates
  175459. * for the nearest entry to some cell in the update box.
  175460. */
  175461. numcolors = find_nearby_colors(cinfo, minc0, minc1, minc2, colorlist);
  175462. /* Determine the actually nearest colors. */
  175463. find_best_colors(cinfo, minc0, minc1, minc2, numcolors, colorlist,
  175464. bestcolor);
  175465. /* Save the best color numbers (plus 1) in the main cache array */
  175466. c0 <<= BOX_C0_LOG; /* convert ID back to base cell indexes */
  175467. c1 <<= BOX_C1_LOG;
  175468. c2 <<= BOX_C2_LOG;
  175469. cptr = bestcolor;
  175470. for (ic0 = 0; ic0 < BOX_C0_ELEMS; ic0++) {
  175471. for (ic1 = 0; ic1 < BOX_C1_ELEMS; ic1++) {
  175472. cachep = & histogram[c0+ic0][c1+ic1][c2];
  175473. for (ic2 = 0; ic2 < BOX_C2_ELEMS; ic2++) {
  175474. *cachep++ = (histcell) (GETJSAMPLE(*cptr++) + 1);
  175475. }
  175476. }
  175477. }
  175478. }
  175479. /*
  175480. * Map some rows of pixels to the output colormapped representation.
  175481. */
  175482. METHODDEF(void)
  175483. pass2_no_dither (j_decompress_ptr cinfo,
  175484. JSAMPARRAY input_buf, JSAMPARRAY output_buf, int num_rows)
  175485. /* This version performs no dithering */
  175486. {
  175487. my_cquantize_ptr2 cquantize = (my_cquantize_ptr2) cinfo->cquantize;
  175488. hist3d histogram = cquantize->histogram;
  175489. register JSAMPROW inptr, outptr;
  175490. register histptr cachep;
  175491. register int c0, c1, c2;
  175492. int row;
  175493. JDIMENSION col;
  175494. JDIMENSION width = cinfo->output_width;
  175495. for (row = 0; row < num_rows; row++) {
  175496. inptr = input_buf[row];
  175497. outptr = output_buf[row];
  175498. for (col = width; col > 0; col--) {
  175499. /* get pixel value and index into the cache */
  175500. c0 = GETJSAMPLE(*inptr++) >> C0_SHIFT;
  175501. c1 = GETJSAMPLE(*inptr++) >> C1_SHIFT;
  175502. c2 = GETJSAMPLE(*inptr++) >> C2_SHIFT;
  175503. cachep = & histogram[c0][c1][c2];
  175504. /* If we have not seen this color before, find nearest colormap entry */
  175505. /* and update the cache */
  175506. if (*cachep == 0)
  175507. fill_inverse_cmap(cinfo, c0,c1,c2);
  175508. /* Now emit the colormap index for this cell */
  175509. *outptr++ = (JSAMPLE) (*cachep - 1);
  175510. }
  175511. }
  175512. }
  175513. METHODDEF(void)
  175514. pass2_fs_dither (j_decompress_ptr cinfo,
  175515. JSAMPARRAY input_buf, JSAMPARRAY output_buf, int num_rows)
  175516. /* This version performs Floyd-Steinberg dithering */
  175517. {
  175518. my_cquantize_ptr2 cquantize = (my_cquantize_ptr2) cinfo->cquantize;
  175519. hist3d histogram = cquantize->histogram;
  175520. register LOCFSERROR cur0, cur1, cur2; /* current error or pixel value */
  175521. LOCFSERROR belowerr0, belowerr1, belowerr2; /* error for pixel below cur */
  175522. LOCFSERROR bpreverr0, bpreverr1, bpreverr2; /* error for below/prev col */
  175523. register FSERRPTR errorptr; /* => fserrors[] at column before current */
  175524. JSAMPROW inptr; /* => current input pixel */
  175525. JSAMPROW outptr; /* => current output pixel */
  175526. histptr cachep;
  175527. int dir; /* +1 or -1 depending on direction */
  175528. int dir3; /* 3*dir, for advancing inptr & errorptr */
  175529. int row;
  175530. JDIMENSION col;
  175531. JDIMENSION width = cinfo->output_width;
  175532. JSAMPLE *range_limit = cinfo->sample_range_limit;
  175533. int *error_limit = cquantize->error_limiter;
  175534. JSAMPROW colormap0 = cinfo->colormap[0];
  175535. JSAMPROW colormap1 = cinfo->colormap[1];
  175536. JSAMPROW colormap2 = cinfo->colormap[2];
  175537. SHIFT_TEMPS
  175538. for (row = 0; row < num_rows; row++) {
  175539. inptr = input_buf[row];
  175540. outptr = output_buf[row];
  175541. if (cquantize->on_odd_row) {
  175542. /* work right to left in this row */
  175543. inptr += (width-1) * 3; /* so point to rightmost pixel */
  175544. outptr += width-1;
  175545. dir = -1;
  175546. dir3 = -3;
  175547. errorptr = cquantize->fserrors + (width+1)*3; /* => entry after last column */
  175548. cquantize->on_odd_row = FALSE; /* flip for next time */
  175549. } else {
  175550. /* work left to right in this row */
  175551. dir = 1;
  175552. dir3 = 3;
  175553. errorptr = cquantize->fserrors; /* => entry before first real column */
  175554. cquantize->on_odd_row = TRUE; /* flip for next time */
  175555. }
  175556. /* Preset error values: no error propagated to first pixel from left */
  175557. cur0 = cur1 = cur2 = 0;
  175558. /* and no error propagated to row below yet */
  175559. belowerr0 = belowerr1 = belowerr2 = 0;
  175560. bpreverr0 = bpreverr1 = bpreverr2 = 0;
  175561. for (col = width; col > 0; col--) {
  175562. /* curN holds the error propagated from the previous pixel on the
  175563. * current line. Add the error propagated from the previous line
  175564. * to form the complete error correction term for this pixel, and
  175565. * round the error term (which is expressed * 16) to an integer.
  175566. * RIGHT_SHIFT rounds towards minus infinity, so adding 8 is correct
  175567. * for either sign of the error value.
  175568. * Note: errorptr points to *previous* column's array entry.
  175569. */
  175570. cur0 = RIGHT_SHIFT(cur0 + errorptr[dir3+0] + 8, 4);
  175571. cur1 = RIGHT_SHIFT(cur1 + errorptr[dir3+1] + 8, 4);
  175572. cur2 = RIGHT_SHIFT(cur2 + errorptr[dir3+2] + 8, 4);
  175573. /* Limit the error using transfer function set by init_error_limit.
  175574. * See comments with init_error_limit for rationale.
  175575. */
  175576. cur0 = error_limit[cur0];
  175577. cur1 = error_limit[cur1];
  175578. cur2 = error_limit[cur2];
  175579. /* Form pixel value + error, and range-limit to 0..MAXJSAMPLE.
  175580. * The maximum error is +- MAXJSAMPLE (or less with error limiting);
  175581. * this sets the required size of the range_limit array.
  175582. */
  175583. cur0 += GETJSAMPLE(inptr[0]);
  175584. cur1 += GETJSAMPLE(inptr[1]);
  175585. cur2 += GETJSAMPLE(inptr[2]);
  175586. cur0 = GETJSAMPLE(range_limit[cur0]);
  175587. cur1 = GETJSAMPLE(range_limit[cur1]);
  175588. cur2 = GETJSAMPLE(range_limit[cur2]);
  175589. /* Index into the cache with adjusted pixel value */
  175590. cachep = & histogram[cur0>>C0_SHIFT][cur1>>C1_SHIFT][cur2>>C2_SHIFT];
  175591. /* If we have not seen this color before, find nearest colormap */
  175592. /* entry and update the cache */
  175593. if (*cachep == 0)
  175594. fill_inverse_cmap(cinfo, cur0>>C0_SHIFT,cur1>>C1_SHIFT,cur2>>C2_SHIFT);
  175595. /* Now emit the colormap index for this cell */
  175596. { register int pixcode = *cachep - 1;
  175597. *outptr = (JSAMPLE) pixcode;
  175598. /* Compute representation error for this pixel */
  175599. cur0 -= GETJSAMPLE(colormap0[pixcode]);
  175600. cur1 -= GETJSAMPLE(colormap1[pixcode]);
  175601. cur2 -= GETJSAMPLE(colormap2[pixcode]);
  175602. }
  175603. /* Compute error fractions to be propagated to adjacent pixels.
  175604. * Add these into the running sums, and simultaneously shift the
  175605. * next-line error sums left by 1 column.
  175606. */
  175607. { register LOCFSERROR bnexterr, delta;
  175608. bnexterr = cur0; /* Process component 0 */
  175609. delta = cur0 * 2;
  175610. cur0 += delta; /* form error * 3 */
  175611. errorptr[0] = (FSERROR) (bpreverr0 + cur0);
  175612. cur0 += delta; /* form error * 5 */
  175613. bpreverr0 = belowerr0 + cur0;
  175614. belowerr0 = bnexterr;
  175615. cur0 += delta; /* form error * 7 */
  175616. bnexterr = cur1; /* Process component 1 */
  175617. delta = cur1 * 2;
  175618. cur1 += delta; /* form error * 3 */
  175619. errorptr[1] = (FSERROR) (bpreverr1 + cur1);
  175620. cur1 += delta; /* form error * 5 */
  175621. bpreverr1 = belowerr1 + cur1;
  175622. belowerr1 = bnexterr;
  175623. cur1 += delta; /* form error * 7 */
  175624. bnexterr = cur2; /* Process component 2 */
  175625. delta = cur2 * 2;
  175626. cur2 += delta; /* form error * 3 */
  175627. errorptr[2] = (FSERROR) (bpreverr2 + cur2);
  175628. cur2 += delta; /* form error * 5 */
  175629. bpreverr2 = belowerr2 + cur2;
  175630. belowerr2 = bnexterr;
  175631. cur2 += delta; /* form error * 7 */
  175632. }
  175633. /* At this point curN contains the 7/16 error value to be propagated
  175634. * to the next pixel on the current line, and all the errors for the
  175635. * next line have been shifted over. We are therefore ready to move on.
  175636. */
  175637. inptr += dir3; /* Advance pixel pointers to next column */
  175638. outptr += dir;
  175639. errorptr += dir3; /* advance errorptr to current column */
  175640. }
  175641. /* Post-loop cleanup: we must unload the final error values into the
  175642. * final fserrors[] entry. Note we need not unload belowerrN because
  175643. * it is for the dummy column before or after the actual array.
  175644. */
  175645. errorptr[0] = (FSERROR) bpreverr0; /* unload prev errs into array */
  175646. errorptr[1] = (FSERROR) bpreverr1;
  175647. errorptr[2] = (FSERROR) bpreverr2;
  175648. }
  175649. }
  175650. /*
  175651. * Initialize the error-limiting transfer function (lookup table).
  175652. * The raw F-S error computation can potentially compute error values of up to
  175653. * +- MAXJSAMPLE. But we want the maximum correction applied to a pixel to be
  175654. * much less, otherwise obviously wrong pixels will be created. (Typical
  175655. * effects include weird fringes at color-area boundaries, isolated bright
  175656. * pixels in a dark area, etc.) The standard advice for avoiding this problem
  175657. * is to ensure that the "corners" of the color cube are allocated as output
  175658. * colors; then repeated errors in the same direction cannot cause cascading
  175659. * error buildup. However, that only prevents the error from getting
  175660. * completely out of hand; Aaron Giles reports that error limiting improves
  175661. * the results even with corner colors allocated.
  175662. * A simple clamping of the error values to about +- MAXJSAMPLE/8 works pretty
  175663. * well, but the smoother transfer function used below is even better. Thanks
  175664. * to Aaron Giles for this idea.
  175665. */
  175666. LOCAL(void)
  175667. init_error_limit (j_decompress_ptr cinfo)
  175668. /* Allocate and fill in the error_limiter table */
  175669. {
  175670. my_cquantize_ptr2 cquantize = (my_cquantize_ptr2) cinfo->cquantize;
  175671. int * table;
  175672. int in, out;
  175673. table = (int *) (*cinfo->mem->alloc_small)
  175674. ((j_common_ptr) cinfo, JPOOL_IMAGE, (MAXJSAMPLE*2+1) * SIZEOF(int));
  175675. table += MAXJSAMPLE; /* so can index -MAXJSAMPLE .. +MAXJSAMPLE */
  175676. cquantize->error_limiter = table;
  175677. #define STEPSIZE ((MAXJSAMPLE+1)/16)
  175678. /* Map errors 1:1 up to +- MAXJSAMPLE/16 */
  175679. out = 0;
  175680. for (in = 0; in < STEPSIZE; in++, out++) {
  175681. table[in] = out; table[-in] = -out;
  175682. }
  175683. /* Map errors 1:2 up to +- 3*MAXJSAMPLE/16 */
  175684. for (; in < STEPSIZE*3; in++, out += (in&1) ? 0 : 1) {
  175685. table[in] = out; table[-in] = -out;
  175686. }
  175687. /* Clamp the rest to final out value (which is (MAXJSAMPLE+1)/8) */
  175688. for (; in <= MAXJSAMPLE; in++) {
  175689. table[in] = out; table[-in] = -out;
  175690. }
  175691. #undef STEPSIZE
  175692. }
  175693. /*
  175694. * Finish up at the end of each pass.
  175695. */
  175696. METHODDEF(void)
  175697. finish_pass1 (j_decompress_ptr cinfo)
  175698. {
  175699. my_cquantize_ptr2 cquantize = (my_cquantize_ptr2) cinfo->cquantize;
  175700. /* Select the representative colors and fill in cinfo->colormap */
  175701. cinfo->colormap = cquantize->sv_colormap;
  175702. select_colors(cinfo, cquantize->desired);
  175703. /* Force next pass to zero the color index table */
  175704. cquantize->needs_zeroed = TRUE;
  175705. }
  175706. METHODDEF(void)
  175707. finish_pass2 (j_decompress_ptr)
  175708. {
  175709. /* no work */
  175710. }
  175711. /*
  175712. * Initialize for each processing pass.
  175713. */
  175714. METHODDEF(void)
  175715. start_pass_2_quant (j_decompress_ptr cinfo, boolean is_pre_scan)
  175716. {
  175717. my_cquantize_ptr2 cquantize = (my_cquantize_ptr2) cinfo->cquantize;
  175718. hist3d histogram = cquantize->histogram;
  175719. int i;
  175720. /* Only F-S dithering or no dithering is supported. */
  175721. /* If user asks for ordered dither, give him F-S. */
  175722. if (cinfo->dither_mode != JDITHER_NONE)
  175723. cinfo->dither_mode = JDITHER_FS;
  175724. if (is_pre_scan) {
  175725. /* Set up method pointers */
  175726. cquantize->pub.color_quantize = prescan_quantize;
  175727. cquantize->pub.finish_pass = finish_pass1;
  175728. cquantize->needs_zeroed = TRUE; /* Always zero histogram */
  175729. } else {
  175730. /* Set up method pointers */
  175731. if (cinfo->dither_mode == JDITHER_FS)
  175732. cquantize->pub.color_quantize = pass2_fs_dither;
  175733. else
  175734. cquantize->pub.color_quantize = pass2_no_dither;
  175735. cquantize->pub.finish_pass = finish_pass2;
  175736. /* Make sure color count is acceptable */
  175737. i = cinfo->actual_number_of_colors;
  175738. if (i < 1)
  175739. ERREXIT1(cinfo, JERR_QUANT_FEW_COLORS, 1);
  175740. if (i > MAXNUMCOLORS)
  175741. ERREXIT1(cinfo, JERR_QUANT_MANY_COLORS, MAXNUMCOLORS);
  175742. if (cinfo->dither_mode == JDITHER_FS) {
  175743. size_t arraysize = (size_t) ((cinfo->output_width + 2) *
  175744. (3 * SIZEOF(FSERROR)));
  175745. /* Allocate Floyd-Steinberg workspace if we didn't already. */
  175746. if (cquantize->fserrors == NULL)
  175747. cquantize->fserrors = (FSERRPTR) (*cinfo->mem->alloc_large)
  175748. ((j_common_ptr) cinfo, JPOOL_IMAGE, arraysize);
  175749. /* Initialize the propagated errors to zero. */
  175750. jzero_far((void FAR *) cquantize->fserrors, arraysize);
  175751. /* Make the error-limit table if we didn't already. */
  175752. if (cquantize->error_limiter == NULL)
  175753. init_error_limit(cinfo);
  175754. cquantize->on_odd_row = FALSE;
  175755. }
  175756. }
  175757. /* Zero the histogram or inverse color map, if necessary */
  175758. if (cquantize->needs_zeroed) {
  175759. for (i = 0; i < HIST_C0_ELEMS; i++) {
  175760. jzero_far((void FAR *) histogram[i],
  175761. HIST_C1_ELEMS*HIST_C2_ELEMS * SIZEOF(histcell));
  175762. }
  175763. cquantize->needs_zeroed = FALSE;
  175764. }
  175765. }
  175766. /*
  175767. * Switch to a new external colormap between output passes.
  175768. */
  175769. METHODDEF(void)
  175770. new_color_map_2_quant (j_decompress_ptr cinfo)
  175771. {
  175772. my_cquantize_ptr2 cquantize = (my_cquantize_ptr2) cinfo->cquantize;
  175773. /* Reset the inverse color map */
  175774. cquantize->needs_zeroed = TRUE;
  175775. }
  175776. /*
  175777. * Module initialization routine for 2-pass color quantization.
  175778. */
  175779. GLOBAL(void)
  175780. jinit_2pass_quantizer (j_decompress_ptr cinfo)
  175781. {
  175782. my_cquantize_ptr2 cquantize;
  175783. int i;
  175784. cquantize = (my_cquantize_ptr2)
  175785. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  175786. SIZEOF(my_cquantizer2));
  175787. cinfo->cquantize = (struct jpeg_color_quantizer *) cquantize;
  175788. cquantize->pub.start_pass = start_pass_2_quant;
  175789. cquantize->pub.new_color_map = new_color_map_2_quant;
  175790. cquantize->fserrors = NULL; /* flag optional arrays not allocated */
  175791. cquantize->error_limiter = NULL;
  175792. /* Make sure jdmaster didn't give me a case I can't handle */
  175793. if (cinfo->out_color_components != 3)
  175794. ERREXIT(cinfo, JERR_NOTIMPL);
  175795. /* Allocate the histogram/inverse colormap storage */
  175796. cquantize->histogram = (hist3d) (*cinfo->mem->alloc_small)
  175797. ((j_common_ptr) cinfo, JPOOL_IMAGE, HIST_C0_ELEMS * SIZEOF(hist2d));
  175798. for (i = 0; i < HIST_C0_ELEMS; i++) {
  175799. cquantize->histogram[i] = (hist2d) (*cinfo->mem->alloc_large)
  175800. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  175801. HIST_C1_ELEMS*HIST_C2_ELEMS * SIZEOF(histcell));
  175802. }
  175803. cquantize->needs_zeroed = TRUE; /* histogram is garbage now */
  175804. /* Allocate storage for the completed colormap, if required.
  175805. * We do this now since it is FAR storage and may affect
  175806. * the memory manager's space calculations.
  175807. */
  175808. if (cinfo->enable_2pass_quant) {
  175809. /* Make sure color count is acceptable */
  175810. int desired = cinfo->desired_number_of_colors;
  175811. /* Lower bound on # of colors ... somewhat arbitrary as long as > 0 */
  175812. if (desired < 8)
  175813. ERREXIT1(cinfo, JERR_QUANT_FEW_COLORS, 8);
  175814. /* Make sure colormap indexes can be represented by JSAMPLEs */
  175815. if (desired > MAXNUMCOLORS)
  175816. ERREXIT1(cinfo, JERR_QUANT_MANY_COLORS, MAXNUMCOLORS);
  175817. cquantize->sv_colormap = (*cinfo->mem->alloc_sarray)
  175818. ((j_common_ptr) cinfo,JPOOL_IMAGE, (JDIMENSION) desired, (JDIMENSION) 3);
  175819. cquantize->desired = desired;
  175820. } else
  175821. cquantize->sv_colormap = NULL;
  175822. /* Only F-S dithering or no dithering is supported. */
  175823. /* If user asks for ordered dither, give him F-S. */
  175824. if (cinfo->dither_mode != JDITHER_NONE)
  175825. cinfo->dither_mode = JDITHER_FS;
  175826. /* Allocate Floyd-Steinberg workspace if necessary.
  175827. * This isn't really needed until pass 2, but again it is FAR storage.
  175828. * Although we will cope with a later change in dither_mode,
  175829. * we do not promise to honor max_memory_to_use if dither_mode changes.
  175830. */
  175831. if (cinfo->dither_mode == JDITHER_FS) {
  175832. cquantize->fserrors = (FSERRPTR) (*cinfo->mem->alloc_large)
  175833. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  175834. (size_t) ((cinfo->output_width + 2) * (3 * SIZEOF(FSERROR))));
  175835. /* Might as well create the error-limiting table too. */
  175836. init_error_limit(cinfo);
  175837. }
  175838. }
  175839. #endif /* QUANT_2PASS_SUPPORTED */
  175840. /*** End of inlined file: jquant2.c ***/
  175841. /*** Start of inlined file: jutils.c ***/
  175842. #define JPEG_INTERNALS
  175843. /*
  175844. * jpeg_zigzag_order[i] is the zigzag-order position of the i'th element
  175845. * of a DCT block read in natural order (left to right, top to bottom).
  175846. */
  175847. #if 0 /* This table is not actually needed in v6a */
  175848. const int jpeg_zigzag_order[DCTSIZE2] = {
  175849. 0, 1, 5, 6, 14, 15, 27, 28,
  175850. 2, 4, 7, 13, 16, 26, 29, 42,
  175851. 3, 8, 12, 17, 25, 30, 41, 43,
  175852. 9, 11, 18, 24, 31, 40, 44, 53,
  175853. 10, 19, 23, 32, 39, 45, 52, 54,
  175854. 20, 22, 33, 38, 46, 51, 55, 60,
  175855. 21, 34, 37, 47, 50, 56, 59, 61,
  175856. 35, 36, 48, 49, 57, 58, 62, 63
  175857. };
  175858. #endif
  175859. /*
  175860. * jpeg_natural_order[i] is the natural-order position of the i'th element
  175861. * of zigzag order.
  175862. *
  175863. * When reading corrupted data, the Huffman decoders could attempt
  175864. * to reference an entry beyond the end of this array (if the decoded
  175865. * zero run length reaches past the end of the block). To prevent
  175866. * wild stores without adding an inner-loop test, we put some extra
  175867. * "63"s after the real entries. This will cause the extra coefficient
  175868. * to be stored in location 63 of the block, not somewhere random.
  175869. * The worst case would be a run-length of 15, which means we need 16
  175870. * fake entries.
  175871. */
  175872. const int jpeg_natural_order[DCTSIZE2+16] = {
  175873. 0, 1, 8, 16, 9, 2, 3, 10,
  175874. 17, 24, 32, 25, 18, 11, 4, 5,
  175875. 12, 19, 26, 33, 40, 48, 41, 34,
  175876. 27, 20, 13, 6, 7, 14, 21, 28,
  175877. 35, 42, 49, 56, 57, 50, 43, 36,
  175878. 29, 22, 15, 23, 30, 37, 44, 51,
  175879. 58, 59, 52, 45, 38, 31, 39, 46,
  175880. 53, 60, 61, 54, 47, 55, 62, 63,
  175881. 63, 63, 63, 63, 63, 63, 63, 63, /* extra entries for safety in decoder */
  175882. 63, 63, 63, 63, 63, 63, 63, 63
  175883. };
  175884. /*
  175885. * Arithmetic utilities
  175886. */
  175887. GLOBAL(long)
  175888. jdiv_round_up (long a, long b)
  175889. /* Compute a/b rounded up to next integer, ie, ceil(a/b) */
  175890. /* Assumes a >= 0, b > 0 */
  175891. {
  175892. return (a + b - 1L) / b;
  175893. }
  175894. GLOBAL(long)
  175895. jround_up (long a, long b)
  175896. /* Compute a rounded up to next multiple of b, ie, ceil(a/b)*b */
  175897. /* Assumes a >= 0, b > 0 */
  175898. {
  175899. a += b - 1L;
  175900. return a - (a % b);
  175901. }
  175902. /* On normal machines we can apply MEMCOPY() and MEMZERO() to sample arrays
  175903. * and coefficient-block arrays. This won't work on 80x86 because the arrays
  175904. * are FAR and we're assuming a small-pointer memory model. However, some
  175905. * DOS compilers provide far-pointer versions of memcpy() and memset() even
  175906. * in the small-model libraries. These will be used if USE_FMEM is defined.
  175907. * Otherwise, the routines below do it the hard way. (The performance cost
  175908. * is not all that great, because these routines aren't very heavily used.)
  175909. */
  175910. #ifndef NEED_FAR_POINTERS /* normal case, same as regular macros */
  175911. #define FMEMCOPY(dest,src,size) MEMCOPY(dest,src,size)
  175912. #define FMEMZERO(target,size) MEMZERO(target,size)
  175913. #else /* 80x86 case, define if we can */
  175914. #ifdef USE_FMEM
  175915. #define FMEMCOPY(dest,src,size) _fmemcpy((void FAR *)(dest), (const void FAR *)(src), (size_t)(size))
  175916. #define FMEMZERO(target,size) _fmemset((void FAR *)(target), 0, (size_t)(size))
  175917. #endif
  175918. #endif
  175919. GLOBAL(void)
  175920. jcopy_sample_rows (JSAMPARRAY input_array, int source_row,
  175921. JSAMPARRAY output_array, int dest_row,
  175922. int num_rows, JDIMENSION num_cols)
  175923. /* Copy some rows of samples from one place to another.
  175924. * num_rows rows are copied from input_array[source_row++]
  175925. * to output_array[dest_row++]; these areas may overlap for duplication.
  175926. * The source and destination arrays must be at least as wide as num_cols.
  175927. */
  175928. {
  175929. register JSAMPROW inptr, outptr;
  175930. #ifdef FMEMCOPY
  175931. register size_t count = (size_t) (num_cols * SIZEOF(JSAMPLE));
  175932. #else
  175933. register JDIMENSION count;
  175934. #endif
  175935. register int row;
  175936. input_array += source_row;
  175937. output_array += dest_row;
  175938. for (row = num_rows; row > 0; row--) {
  175939. inptr = *input_array++;
  175940. outptr = *output_array++;
  175941. #ifdef FMEMCOPY
  175942. FMEMCOPY(outptr, inptr, count);
  175943. #else
  175944. for (count = num_cols; count > 0; count--)
  175945. *outptr++ = *inptr++; /* needn't bother with GETJSAMPLE() here */
  175946. #endif
  175947. }
  175948. }
  175949. GLOBAL(void)
  175950. jcopy_block_row (JBLOCKROW input_row, JBLOCKROW output_row,
  175951. JDIMENSION num_blocks)
  175952. /* Copy a row of coefficient blocks from one place to another. */
  175953. {
  175954. #ifdef FMEMCOPY
  175955. FMEMCOPY(output_row, input_row, num_blocks * (DCTSIZE2 * SIZEOF(JCOEF)));
  175956. #else
  175957. register JCOEFPTR inptr, outptr;
  175958. register long count;
  175959. inptr = (JCOEFPTR) input_row;
  175960. outptr = (JCOEFPTR) output_row;
  175961. for (count = (long) num_blocks * DCTSIZE2; count > 0; count--) {
  175962. *outptr++ = *inptr++;
  175963. }
  175964. #endif
  175965. }
  175966. GLOBAL(void)
  175967. jzero_far (void FAR * target, size_t bytestozero)
  175968. /* Zero out a chunk of FAR memory. */
  175969. /* This might be sample-array data, block-array data, or alloc_large data. */
  175970. {
  175971. #ifdef FMEMZERO
  175972. FMEMZERO(target, bytestozero);
  175973. #else
  175974. register char FAR * ptr = (char FAR *) target;
  175975. register size_t count;
  175976. for (count = bytestozero; count > 0; count--) {
  175977. *ptr++ = 0;
  175978. }
  175979. #endif
  175980. }
  175981. /*** End of inlined file: jutils.c ***/
  175982. /*** Start of inlined file: transupp.c ***/
  175983. /* Although this file really shouldn't have access to the library internals,
  175984. * it's helpful to let it call jround_up() and jcopy_block_row().
  175985. */
  175986. #define JPEG_INTERNALS
  175987. /*** Start of inlined file: transupp.h ***/
  175988. /* If you happen not to want the image transform support, disable it here */
  175989. #ifndef TRANSFORMS_SUPPORTED
  175990. #define TRANSFORMS_SUPPORTED 1 /* 0 disables transform code */
  175991. #endif
  175992. /* Short forms of external names for systems with brain-damaged linkers. */
  175993. #ifdef NEED_SHORT_EXTERNAL_NAMES
  175994. #define jtransform_request_workspace jTrRequest
  175995. #define jtransform_adjust_parameters jTrAdjust
  175996. #define jtransform_execute_transformation jTrExec
  175997. #define jcopy_markers_setup jCMrkSetup
  175998. #define jcopy_markers_execute jCMrkExec
  175999. #endif /* NEED_SHORT_EXTERNAL_NAMES */
  176000. /*
  176001. * Codes for supported types of image transformations.
  176002. */
  176003. typedef enum {
  176004. JXFORM_NONE, /* no transformation */
  176005. JXFORM_FLIP_H, /* horizontal flip */
  176006. JXFORM_FLIP_V, /* vertical flip */
  176007. JXFORM_TRANSPOSE, /* transpose across UL-to-LR axis */
  176008. JXFORM_TRANSVERSE, /* transpose across UR-to-LL axis */
  176009. JXFORM_ROT_90, /* 90-degree clockwise rotation */
  176010. JXFORM_ROT_180, /* 180-degree rotation */
  176011. JXFORM_ROT_270 /* 270-degree clockwise (or 90 ccw) */
  176012. } JXFORM_CODE;
  176013. /*
  176014. * Although rotating and flipping data expressed as DCT coefficients is not
  176015. * hard, there is an asymmetry in the JPEG format specification for images
  176016. * whose dimensions aren't multiples of the iMCU size. The right and bottom
  176017. * image edges are padded out to the next iMCU boundary with junk data; but
  176018. * no padding is possible at the top and left edges. If we were to flip
  176019. * the whole image including the pad data, then pad garbage would become
  176020. * visible at the top and/or left, and real pixels would disappear into the
  176021. * pad margins --- perhaps permanently, since encoders & decoders may not
  176022. * bother to preserve DCT blocks that appear to be completely outside the
  176023. * nominal image area. So, we have to exclude any partial iMCUs from the
  176024. * basic transformation.
  176025. *
  176026. * Transpose is the only transformation that can handle partial iMCUs at the
  176027. * right and bottom edges completely cleanly. flip_h can flip partial iMCUs
  176028. * at the bottom, but leaves any partial iMCUs at the right edge untouched.
  176029. * Similarly flip_v leaves any partial iMCUs at the bottom edge untouched.
  176030. * The other transforms are defined as combinations of these basic transforms
  176031. * and process edge blocks in a way that preserves the equivalence.
  176032. *
  176033. * The "trim" option causes untransformable partial iMCUs to be dropped;
  176034. * this is not strictly lossless, but it usually gives the best-looking
  176035. * result for odd-size images. Note that when this option is active,
  176036. * the expected mathematical equivalences between the transforms may not hold.
  176037. * (For example, -rot 270 -trim trims only the bottom edge, but -rot 90 -trim
  176038. * followed by -rot 180 -trim trims both edges.)
  176039. *
  176040. * We also offer a "force to grayscale" option, which simply discards the
  176041. * chrominance channels of a YCbCr image. This is lossless in the sense that
  176042. * the luminance channel is preserved exactly. It's not the same kind of
  176043. * thing as the rotate/flip transformations, but it's convenient to handle it
  176044. * as part of this package, mainly because the transformation routines have to
  176045. * be aware of the option to know how many components to work on.
  176046. */
  176047. typedef struct {
  176048. /* Options: set by caller */
  176049. JXFORM_CODE transform; /* image transform operator */
  176050. boolean trim; /* if TRUE, trim partial MCUs as needed */
  176051. boolean force_grayscale; /* if TRUE, convert color image to grayscale */
  176052. /* Internal workspace: caller should not touch these */
  176053. int num_components; /* # of components in workspace */
  176054. jvirt_barray_ptr * workspace_coef_arrays; /* workspace for transformations */
  176055. } jpeg_transform_info;
  176056. #if TRANSFORMS_SUPPORTED
  176057. /* Request any required workspace */
  176058. EXTERN(void) jtransform_request_workspace
  176059. JPP((j_decompress_ptr srcinfo, jpeg_transform_info *info));
  176060. /* Adjust output image parameters */
  176061. EXTERN(jvirt_barray_ptr *) jtransform_adjust_parameters
  176062. JPP((j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  176063. jvirt_barray_ptr *src_coef_arrays,
  176064. jpeg_transform_info *info));
  176065. /* Execute the actual transformation, if any */
  176066. EXTERN(void) jtransform_execute_transformation
  176067. JPP((j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  176068. jvirt_barray_ptr *src_coef_arrays,
  176069. jpeg_transform_info *info));
  176070. #endif /* TRANSFORMS_SUPPORTED */
  176071. /*
  176072. * Support for copying optional markers from source to destination file.
  176073. */
  176074. typedef enum {
  176075. JCOPYOPT_NONE, /* copy no optional markers */
  176076. JCOPYOPT_COMMENTS, /* copy only comment (COM) markers */
  176077. JCOPYOPT_ALL /* copy all optional markers */
  176078. } JCOPY_OPTION;
  176079. #define JCOPYOPT_DEFAULT JCOPYOPT_COMMENTS /* recommended default */
  176080. /* Setup decompression object to save desired markers in memory */
  176081. EXTERN(void) jcopy_markers_setup
  176082. JPP((j_decompress_ptr srcinfo, JCOPY_OPTION option));
  176083. /* Copy markers saved in the given source object to the destination object */
  176084. EXTERN(void) jcopy_markers_execute
  176085. JPP((j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  176086. JCOPY_OPTION option));
  176087. /*** End of inlined file: transupp.h ***/
  176088. /* My own external interface */
  176089. #if TRANSFORMS_SUPPORTED
  176090. /*
  176091. * Lossless image transformation routines. These routines work on DCT
  176092. * coefficient arrays and thus do not require any lossy decompression
  176093. * or recompression of the image.
  176094. * Thanks to Guido Vollbeding for the initial design and code of this feature.
  176095. *
  176096. * Horizontal flipping is done in-place, using a single top-to-bottom
  176097. * pass through the virtual source array. It will thus be much the
  176098. * fastest option for images larger than main memory.
  176099. *
  176100. * The other routines require a set of destination virtual arrays, so they
  176101. * need twice as much memory as jpegtran normally does. The destination
  176102. * arrays are always written in normal scan order (top to bottom) because
  176103. * the virtual array manager expects this. The source arrays will be scanned
  176104. * in the corresponding order, which means multiple passes through the source
  176105. * arrays for most of the transforms. That could result in much thrashing
  176106. * if the image is larger than main memory.
  176107. *
  176108. * Some notes about the operating environment of the individual transform
  176109. * routines:
  176110. * 1. Both the source and destination virtual arrays are allocated from the
  176111. * source JPEG object, and therefore should be manipulated by calling the
  176112. * source's memory manager.
  176113. * 2. The destination's component count should be used. It may be smaller
  176114. * than the source's when forcing to grayscale.
  176115. * 3. Likewise the destination's sampling factors should be used. When
  176116. * forcing to grayscale the destination's sampling factors will be all 1,
  176117. * and we may as well take that as the effective iMCU size.
  176118. * 4. When "trim" is in effect, the destination's dimensions will be the
  176119. * trimmed values but the source's will be untrimmed.
  176120. * 5. All the routines assume that the source and destination buffers are
  176121. * padded out to a full iMCU boundary. This is true, although for the
  176122. * source buffer it is an undocumented property of jdcoefct.c.
  176123. * Notes 2,3,4 boil down to this: generally we should use the destination's
  176124. * dimensions and ignore the source's.
  176125. */
  176126. LOCAL(void)
  176127. do_flip_h (j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  176128. jvirt_barray_ptr *src_coef_arrays)
  176129. /* Horizontal flip; done in-place, so no separate dest array is required */
  176130. {
  176131. JDIMENSION MCU_cols, comp_width, blk_x, blk_y;
  176132. int ci, k, offset_y;
  176133. JBLOCKARRAY buffer;
  176134. JCOEFPTR ptr1, ptr2;
  176135. JCOEF temp1, temp2;
  176136. jpeg_component_info *compptr;
  176137. /* Horizontal mirroring of DCT blocks is accomplished by swapping
  176138. * pairs of blocks in-place. Within a DCT block, we perform horizontal
  176139. * mirroring by changing the signs of odd-numbered columns.
  176140. * Partial iMCUs at the right edge are left untouched.
  176141. */
  176142. MCU_cols = dstinfo->image_width / (dstinfo->max_h_samp_factor * DCTSIZE);
  176143. for (ci = 0; ci < dstinfo->num_components; ci++) {
  176144. compptr = dstinfo->comp_info + ci;
  176145. comp_width = MCU_cols * compptr->h_samp_factor;
  176146. for (blk_y = 0; blk_y < compptr->height_in_blocks;
  176147. blk_y += compptr->v_samp_factor) {
  176148. buffer = (*srcinfo->mem->access_virt_barray)
  176149. ((j_common_ptr) srcinfo, src_coef_arrays[ci], blk_y,
  176150. (JDIMENSION) compptr->v_samp_factor, TRUE);
  176151. for (offset_y = 0; offset_y < compptr->v_samp_factor; offset_y++) {
  176152. for (blk_x = 0; blk_x * 2 < comp_width; blk_x++) {
  176153. ptr1 = buffer[offset_y][blk_x];
  176154. ptr2 = buffer[offset_y][comp_width - blk_x - 1];
  176155. /* this unrolled loop doesn't need to know which row it's on... */
  176156. for (k = 0; k < DCTSIZE2; k += 2) {
  176157. temp1 = *ptr1; /* swap even column */
  176158. temp2 = *ptr2;
  176159. *ptr1++ = temp2;
  176160. *ptr2++ = temp1;
  176161. temp1 = *ptr1; /* swap odd column with sign change */
  176162. temp2 = *ptr2;
  176163. *ptr1++ = -temp2;
  176164. *ptr2++ = -temp1;
  176165. }
  176166. }
  176167. }
  176168. }
  176169. }
  176170. }
  176171. LOCAL(void)
  176172. do_flip_v (j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  176173. jvirt_barray_ptr *src_coef_arrays,
  176174. jvirt_barray_ptr *dst_coef_arrays)
  176175. /* Vertical flip */
  176176. {
  176177. JDIMENSION MCU_rows, comp_height, dst_blk_x, dst_blk_y;
  176178. int ci, i, j, offset_y;
  176179. JBLOCKARRAY src_buffer, dst_buffer;
  176180. JBLOCKROW src_row_ptr, dst_row_ptr;
  176181. JCOEFPTR src_ptr, dst_ptr;
  176182. jpeg_component_info *compptr;
  176183. /* We output into a separate array because we can't touch different
  176184. * rows of the source virtual array simultaneously. Otherwise, this
  176185. * is a pretty straightforward analog of horizontal flip.
  176186. * Within a DCT block, vertical mirroring is done by changing the signs
  176187. * of odd-numbered rows.
  176188. * Partial iMCUs at the bottom edge are copied verbatim.
  176189. */
  176190. MCU_rows = dstinfo->image_height / (dstinfo->max_v_samp_factor * DCTSIZE);
  176191. for (ci = 0; ci < dstinfo->num_components; ci++) {
  176192. compptr = dstinfo->comp_info + ci;
  176193. comp_height = MCU_rows * compptr->v_samp_factor;
  176194. for (dst_blk_y = 0; dst_blk_y < compptr->height_in_blocks;
  176195. dst_blk_y += compptr->v_samp_factor) {
  176196. dst_buffer = (*srcinfo->mem->access_virt_barray)
  176197. ((j_common_ptr) srcinfo, dst_coef_arrays[ci], dst_blk_y,
  176198. (JDIMENSION) compptr->v_samp_factor, TRUE);
  176199. if (dst_blk_y < comp_height) {
  176200. /* Row is within the mirrorable area. */
  176201. src_buffer = (*srcinfo->mem->access_virt_barray)
  176202. ((j_common_ptr) srcinfo, src_coef_arrays[ci],
  176203. comp_height - dst_blk_y - (JDIMENSION) compptr->v_samp_factor,
  176204. (JDIMENSION) compptr->v_samp_factor, FALSE);
  176205. } else {
  176206. /* Bottom-edge blocks will be copied verbatim. */
  176207. src_buffer = (*srcinfo->mem->access_virt_barray)
  176208. ((j_common_ptr) srcinfo, src_coef_arrays[ci], dst_blk_y,
  176209. (JDIMENSION) compptr->v_samp_factor, FALSE);
  176210. }
  176211. for (offset_y = 0; offset_y < compptr->v_samp_factor; offset_y++) {
  176212. if (dst_blk_y < comp_height) {
  176213. /* Row is within the mirrorable area. */
  176214. dst_row_ptr = dst_buffer[offset_y];
  176215. src_row_ptr = src_buffer[compptr->v_samp_factor - offset_y - 1];
  176216. for (dst_blk_x = 0; dst_blk_x < compptr->width_in_blocks;
  176217. dst_blk_x++) {
  176218. dst_ptr = dst_row_ptr[dst_blk_x];
  176219. src_ptr = src_row_ptr[dst_blk_x];
  176220. for (i = 0; i < DCTSIZE; i += 2) {
  176221. /* copy even row */
  176222. for (j = 0; j < DCTSIZE; j++)
  176223. *dst_ptr++ = *src_ptr++;
  176224. /* copy odd row with sign change */
  176225. for (j = 0; j < DCTSIZE; j++)
  176226. *dst_ptr++ = - *src_ptr++;
  176227. }
  176228. }
  176229. } else {
  176230. /* Just copy row verbatim. */
  176231. jcopy_block_row(src_buffer[offset_y], dst_buffer[offset_y],
  176232. compptr->width_in_blocks);
  176233. }
  176234. }
  176235. }
  176236. }
  176237. }
  176238. LOCAL(void)
  176239. do_transpose (j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  176240. jvirt_barray_ptr *src_coef_arrays,
  176241. jvirt_barray_ptr *dst_coef_arrays)
  176242. /* Transpose source into destination */
  176243. {
  176244. JDIMENSION dst_blk_x, dst_blk_y;
  176245. int ci, i, j, offset_x, offset_y;
  176246. JBLOCKARRAY src_buffer, dst_buffer;
  176247. JCOEFPTR src_ptr, dst_ptr;
  176248. jpeg_component_info *compptr;
  176249. /* Transposing pixels within a block just requires transposing the
  176250. * DCT coefficients.
  176251. * Partial iMCUs at the edges require no special treatment; we simply
  176252. * process all the available DCT blocks for every component.
  176253. */
  176254. for (ci = 0; ci < dstinfo->num_components; ci++) {
  176255. compptr = dstinfo->comp_info + ci;
  176256. for (dst_blk_y = 0; dst_blk_y < compptr->height_in_blocks;
  176257. dst_blk_y += compptr->v_samp_factor) {
  176258. dst_buffer = (*srcinfo->mem->access_virt_barray)
  176259. ((j_common_ptr) srcinfo, dst_coef_arrays[ci], dst_blk_y,
  176260. (JDIMENSION) compptr->v_samp_factor, TRUE);
  176261. for (offset_y = 0; offset_y < compptr->v_samp_factor; offset_y++) {
  176262. for (dst_blk_x = 0; dst_blk_x < compptr->width_in_blocks;
  176263. dst_blk_x += compptr->h_samp_factor) {
  176264. src_buffer = (*srcinfo->mem->access_virt_barray)
  176265. ((j_common_ptr) srcinfo, src_coef_arrays[ci], dst_blk_x,
  176266. (JDIMENSION) compptr->h_samp_factor, FALSE);
  176267. for (offset_x = 0; offset_x < compptr->h_samp_factor; offset_x++) {
  176268. src_ptr = src_buffer[offset_x][dst_blk_y + offset_y];
  176269. dst_ptr = dst_buffer[offset_y][dst_blk_x + offset_x];
  176270. for (i = 0; i < DCTSIZE; i++)
  176271. for (j = 0; j < DCTSIZE; j++)
  176272. dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j];
  176273. }
  176274. }
  176275. }
  176276. }
  176277. }
  176278. }
  176279. LOCAL(void)
  176280. do_rot_90 (j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  176281. jvirt_barray_ptr *src_coef_arrays,
  176282. jvirt_barray_ptr *dst_coef_arrays)
  176283. /* 90 degree rotation is equivalent to
  176284. * 1. Transposing the image;
  176285. * 2. Horizontal mirroring.
  176286. * These two steps are merged into a single processing routine.
  176287. */
  176288. {
  176289. JDIMENSION MCU_cols, comp_width, dst_blk_x, dst_blk_y;
  176290. int ci, i, j, offset_x, offset_y;
  176291. JBLOCKARRAY src_buffer, dst_buffer;
  176292. JCOEFPTR src_ptr, dst_ptr;
  176293. jpeg_component_info *compptr;
  176294. /* Because of the horizontal mirror step, we can't process partial iMCUs
  176295. * at the (output) right edge properly. They just get transposed and
  176296. * not mirrored.
  176297. */
  176298. MCU_cols = dstinfo->image_width / (dstinfo->max_h_samp_factor * DCTSIZE);
  176299. for (ci = 0; ci < dstinfo->num_components; ci++) {
  176300. compptr = dstinfo->comp_info + ci;
  176301. comp_width = MCU_cols * compptr->h_samp_factor;
  176302. for (dst_blk_y = 0; dst_blk_y < compptr->height_in_blocks;
  176303. dst_blk_y += compptr->v_samp_factor) {
  176304. dst_buffer = (*srcinfo->mem->access_virt_barray)
  176305. ((j_common_ptr) srcinfo, dst_coef_arrays[ci], dst_blk_y,
  176306. (JDIMENSION) compptr->v_samp_factor, TRUE);
  176307. for (offset_y = 0; offset_y < compptr->v_samp_factor; offset_y++) {
  176308. for (dst_blk_x = 0; dst_blk_x < compptr->width_in_blocks;
  176309. dst_blk_x += compptr->h_samp_factor) {
  176310. src_buffer = (*srcinfo->mem->access_virt_barray)
  176311. ((j_common_ptr) srcinfo, src_coef_arrays[ci], dst_blk_x,
  176312. (JDIMENSION) compptr->h_samp_factor, FALSE);
  176313. for (offset_x = 0; offset_x < compptr->h_samp_factor; offset_x++) {
  176314. src_ptr = src_buffer[offset_x][dst_blk_y + offset_y];
  176315. if (dst_blk_x < comp_width) {
  176316. /* Block is within the mirrorable area. */
  176317. dst_ptr = dst_buffer[offset_y]
  176318. [comp_width - dst_blk_x - offset_x - 1];
  176319. for (i = 0; i < DCTSIZE; i++) {
  176320. for (j = 0; j < DCTSIZE; j++)
  176321. dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j];
  176322. i++;
  176323. for (j = 0; j < DCTSIZE; j++)
  176324. dst_ptr[j*DCTSIZE+i] = -src_ptr[i*DCTSIZE+j];
  176325. }
  176326. } else {
  176327. /* Edge blocks are transposed but not mirrored. */
  176328. dst_ptr = dst_buffer[offset_y][dst_blk_x + offset_x];
  176329. for (i = 0; i < DCTSIZE; i++)
  176330. for (j = 0; j < DCTSIZE; j++)
  176331. dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j];
  176332. }
  176333. }
  176334. }
  176335. }
  176336. }
  176337. }
  176338. }
  176339. LOCAL(void)
  176340. do_rot_270 (j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  176341. jvirt_barray_ptr *src_coef_arrays,
  176342. jvirt_barray_ptr *dst_coef_arrays)
  176343. /* 270 degree rotation is equivalent to
  176344. * 1. Horizontal mirroring;
  176345. * 2. Transposing the image.
  176346. * These two steps are merged into a single processing routine.
  176347. */
  176348. {
  176349. JDIMENSION MCU_rows, comp_height, dst_blk_x, dst_blk_y;
  176350. int ci, i, j, offset_x, offset_y;
  176351. JBLOCKARRAY src_buffer, dst_buffer;
  176352. JCOEFPTR src_ptr, dst_ptr;
  176353. jpeg_component_info *compptr;
  176354. /* Because of the horizontal mirror step, we can't process partial iMCUs
  176355. * at the (output) bottom edge properly. They just get transposed and
  176356. * not mirrored.
  176357. */
  176358. MCU_rows = dstinfo->image_height / (dstinfo->max_v_samp_factor * DCTSIZE);
  176359. for (ci = 0; ci < dstinfo->num_components; ci++) {
  176360. compptr = dstinfo->comp_info + ci;
  176361. comp_height = MCU_rows * compptr->v_samp_factor;
  176362. for (dst_blk_y = 0; dst_blk_y < compptr->height_in_blocks;
  176363. dst_blk_y += compptr->v_samp_factor) {
  176364. dst_buffer = (*srcinfo->mem->access_virt_barray)
  176365. ((j_common_ptr) srcinfo, dst_coef_arrays[ci], dst_blk_y,
  176366. (JDIMENSION) compptr->v_samp_factor, TRUE);
  176367. for (offset_y = 0; offset_y < compptr->v_samp_factor; offset_y++) {
  176368. for (dst_blk_x = 0; dst_blk_x < compptr->width_in_blocks;
  176369. dst_blk_x += compptr->h_samp_factor) {
  176370. src_buffer = (*srcinfo->mem->access_virt_barray)
  176371. ((j_common_ptr) srcinfo, src_coef_arrays[ci], dst_blk_x,
  176372. (JDIMENSION) compptr->h_samp_factor, FALSE);
  176373. for (offset_x = 0; offset_x < compptr->h_samp_factor; offset_x++) {
  176374. dst_ptr = dst_buffer[offset_y][dst_blk_x + offset_x];
  176375. if (dst_blk_y < comp_height) {
  176376. /* Block is within the mirrorable area. */
  176377. src_ptr = src_buffer[offset_x]
  176378. [comp_height - dst_blk_y - offset_y - 1];
  176379. for (i = 0; i < DCTSIZE; i++) {
  176380. for (j = 0; j < DCTSIZE; j++) {
  176381. dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j];
  176382. j++;
  176383. dst_ptr[j*DCTSIZE+i] = -src_ptr[i*DCTSIZE+j];
  176384. }
  176385. }
  176386. } else {
  176387. /* Edge blocks are transposed but not mirrored. */
  176388. src_ptr = src_buffer[offset_x][dst_blk_y + offset_y];
  176389. for (i = 0; i < DCTSIZE; i++)
  176390. for (j = 0; j < DCTSIZE; j++)
  176391. dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j];
  176392. }
  176393. }
  176394. }
  176395. }
  176396. }
  176397. }
  176398. }
  176399. LOCAL(void)
  176400. do_rot_180 (j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  176401. jvirt_barray_ptr *src_coef_arrays,
  176402. jvirt_barray_ptr *dst_coef_arrays)
  176403. /* 180 degree rotation is equivalent to
  176404. * 1. Vertical mirroring;
  176405. * 2. Horizontal mirroring.
  176406. * These two steps are merged into a single processing routine.
  176407. */
  176408. {
  176409. JDIMENSION MCU_cols, MCU_rows, comp_width, comp_height, dst_blk_x, dst_blk_y;
  176410. int ci, i, j, offset_y;
  176411. JBLOCKARRAY src_buffer, dst_buffer;
  176412. JBLOCKROW src_row_ptr, dst_row_ptr;
  176413. JCOEFPTR src_ptr, dst_ptr;
  176414. jpeg_component_info *compptr;
  176415. MCU_cols = dstinfo->image_width / (dstinfo->max_h_samp_factor * DCTSIZE);
  176416. MCU_rows = dstinfo->image_height / (dstinfo->max_v_samp_factor * DCTSIZE);
  176417. for (ci = 0; ci < dstinfo->num_components; ci++) {
  176418. compptr = dstinfo->comp_info + ci;
  176419. comp_width = MCU_cols * compptr->h_samp_factor;
  176420. comp_height = MCU_rows * compptr->v_samp_factor;
  176421. for (dst_blk_y = 0; dst_blk_y < compptr->height_in_blocks;
  176422. dst_blk_y += compptr->v_samp_factor) {
  176423. dst_buffer = (*srcinfo->mem->access_virt_barray)
  176424. ((j_common_ptr) srcinfo, dst_coef_arrays[ci], dst_blk_y,
  176425. (JDIMENSION) compptr->v_samp_factor, TRUE);
  176426. if (dst_blk_y < comp_height) {
  176427. /* Row is within the vertically mirrorable area. */
  176428. src_buffer = (*srcinfo->mem->access_virt_barray)
  176429. ((j_common_ptr) srcinfo, src_coef_arrays[ci],
  176430. comp_height - dst_blk_y - (JDIMENSION) compptr->v_samp_factor,
  176431. (JDIMENSION) compptr->v_samp_factor, FALSE);
  176432. } else {
  176433. /* Bottom-edge rows are only mirrored horizontally. */
  176434. src_buffer = (*srcinfo->mem->access_virt_barray)
  176435. ((j_common_ptr) srcinfo, src_coef_arrays[ci], dst_blk_y,
  176436. (JDIMENSION) compptr->v_samp_factor, FALSE);
  176437. }
  176438. for (offset_y = 0; offset_y < compptr->v_samp_factor; offset_y++) {
  176439. if (dst_blk_y < comp_height) {
  176440. /* Row is within the mirrorable area. */
  176441. dst_row_ptr = dst_buffer[offset_y];
  176442. src_row_ptr = src_buffer[compptr->v_samp_factor - offset_y - 1];
  176443. /* Process the blocks that can be mirrored both ways. */
  176444. for (dst_blk_x = 0; dst_blk_x < comp_width; dst_blk_x++) {
  176445. dst_ptr = dst_row_ptr[dst_blk_x];
  176446. src_ptr = src_row_ptr[comp_width - dst_blk_x - 1];
  176447. for (i = 0; i < DCTSIZE; i += 2) {
  176448. /* For even row, negate every odd column. */
  176449. for (j = 0; j < DCTSIZE; j += 2) {
  176450. *dst_ptr++ = *src_ptr++;
  176451. *dst_ptr++ = - *src_ptr++;
  176452. }
  176453. /* For odd row, negate every even column. */
  176454. for (j = 0; j < DCTSIZE; j += 2) {
  176455. *dst_ptr++ = - *src_ptr++;
  176456. *dst_ptr++ = *src_ptr++;
  176457. }
  176458. }
  176459. }
  176460. /* Any remaining right-edge blocks are only mirrored vertically. */
  176461. for (; dst_blk_x < compptr->width_in_blocks; dst_blk_x++) {
  176462. dst_ptr = dst_row_ptr[dst_blk_x];
  176463. src_ptr = src_row_ptr[dst_blk_x];
  176464. for (i = 0; i < DCTSIZE; i += 2) {
  176465. for (j = 0; j < DCTSIZE; j++)
  176466. *dst_ptr++ = *src_ptr++;
  176467. for (j = 0; j < DCTSIZE; j++)
  176468. *dst_ptr++ = - *src_ptr++;
  176469. }
  176470. }
  176471. } else {
  176472. /* Remaining rows are just mirrored horizontally. */
  176473. dst_row_ptr = dst_buffer[offset_y];
  176474. src_row_ptr = src_buffer[offset_y];
  176475. /* Process the blocks that can be mirrored. */
  176476. for (dst_blk_x = 0; dst_blk_x < comp_width; dst_blk_x++) {
  176477. dst_ptr = dst_row_ptr[dst_blk_x];
  176478. src_ptr = src_row_ptr[comp_width - dst_blk_x - 1];
  176479. for (i = 0; i < DCTSIZE2; i += 2) {
  176480. *dst_ptr++ = *src_ptr++;
  176481. *dst_ptr++ = - *src_ptr++;
  176482. }
  176483. }
  176484. /* Any remaining right-edge blocks are only copied. */
  176485. for (; dst_blk_x < compptr->width_in_blocks; dst_blk_x++) {
  176486. dst_ptr = dst_row_ptr[dst_blk_x];
  176487. src_ptr = src_row_ptr[dst_blk_x];
  176488. for (i = 0; i < DCTSIZE2; i++)
  176489. *dst_ptr++ = *src_ptr++;
  176490. }
  176491. }
  176492. }
  176493. }
  176494. }
  176495. }
  176496. LOCAL(void)
  176497. do_transverse (j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  176498. jvirt_barray_ptr *src_coef_arrays,
  176499. jvirt_barray_ptr *dst_coef_arrays)
  176500. /* Transverse transpose is equivalent to
  176501. * 1. 180 degree rotation;
  176502. * 2. Transposition;
  176503. * or
  176504. * 1. Horizontal mirroring;
  176505. * 2. Transposition;
  176506. * 3. Horizontal mirroring.
  176507. * These steps are merged into a single processing routine.
  176508. */
  176509. {
  176510. JDIMENSION MCU_cols, MCU_rows, comp_width, comp_height, dst_blk_x, dst_blk_y;
  176511. int ci, i, j, offset_x, offset_y;
  176512. JBLOCKARRAY src_buffer, dst_buffer;
  176513. JCOEFPTR src_ptr, dst_ptr;
  176514. jpeg_component_info *compptr;
  176515. MCU_cols = dstinfo->image_width / (dstinfo->max_h_samp_factor * DCTSIZE);
  176516. MCU_rows = dstinfo->image_height / (dstinfo->max_v_samp_factor * DCTSIZE);
  176517. for (ci = 0; ci < dstinfo->num_components; ci++) {
  176518. compptr = dstinfo->comp_info + ci;
  176519. comp_width = MCU_cols * compptr->h_samp_factor;
  176520. comp_height = MCU_rows * compptr->v_samp_factor;
  176521. for (dst_blk_y = 0; dst_blk_y < compptr->height_in_blocks;
  176522. dst_blk_y += compptr->v_samp_factor) {
  176523. dst_buffer = (*srcinfo->mem->access_virt_barray)
  176524. ((j_common_ptr) srcinfo, dst_coef_arrays[ci], dst_blk_y,
  176525. (JDIMENSION) compptr->v_samp_factor, TRUE);
  176526. for (offset_y = 0; offset_y < compptr->v_samp_factor; offset_y++) {
  176527. for (dst_blk_x = 0; dst_blk_x < compptr->width_in_blocks;
  176528. dst_blk_x += compptr->h_samp_factor) {
  176529. src_buffer = (*srcinfo->mem->access_virt_barray)
  176530. ((j_common_ptr) srcinfo, src_coef_arrays[ci], dst_blk_x,
  176531. (JDIMENSION) compptr->h_samp_factor, FALSE);
  176532. for (offset_x = 0; offset_x < compptr->h_samp_factor; offset_x++) {
  176533. if (dst_blk_y < comp_height) {
  176534. src_ptr = src_buffer[offset_x]
  176535. [comp_height - dst_blk_y - offset_y - 1];
  176536. if (dst_blk_x < comp_width) {
  176537. /* Block is within the mirrorable area. */
  176538. dst_ptr = dst_buffer[offset_y]
  176539. [comp_width - dst_blk_x - offset_x - 1];
  176540. for (i = 0; i < DCTSIZE; i++) {
  176541. for (j = 0; j < DCTSIZE; j++) {
  176542. dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j];
  176543. j++;
  176544. dst_ptr[j*DCTSIZE+i] = -src_ptr[i*DCTSIZE+j];
  176545. }
  176546. i++;
  176547. for (j = 0; j < DCTSIZE; j++) {
  176548. dst_ptr[j*DCTSIZE+i] = -src_ptr[i*DCTSIZE+j];
  176549. j++;
  176550. dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j];
  176551. }
  176552. }
  176553. } else {
  176554. /* Right-edge blocks are mirrored in y only */
  176555. dst_ptr = dst_buffer[offset_y][dst_blk_x + offset_x];
  176556. for (i = 0; i < DCTSIZE; i++) {
  176557. for (j = 0; j < DCTSIZE; j++) {
  176558. dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j];
  176559. j++;
  176560. dst_ptr[j*DCTSIZE+i] = -src_ptr[i*DCTSIZE+j];
  176561. }
  176562. }
  176563. }
  176564. } else {
  176565. src_ptr = src_buffer[offset_x][dst_blk_y + offset_y];
  176566. if (dst_blk_x < comp_width) {
  176567. /* Bottom-edge blocks are mirrored in x only */
  176568. dst_ptr = dst_buffer[offset_y]
  176569. [comp_width - dst_blk_x - offset_x - 1];
  176570. for (i = 0; i < DCTSIZE; i++) {
  176571. for (j = 0; j < DCTSIZE; j++)
  176572. dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j];
  176573. i++;
  176574. for (j = 0; j < DCTSIZE; j++)
  176575. dst_ptr[j*DCTSIZE+i] = -src_ptr[i*DCTSIZE+j];
  176576. }
  176577. } else {
  176578. /* At lower right corner, just transpose, no mirroring */
  176579. dst_ptr = dst_buffer[offset_y][dst_blk_x + offset_x];
  176580. for (i = 0; i < DCTSIZE; i++)
  176581. for (j = 0; j < DCTSIZE; j++)
  176582. dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j];
  176583. }
  176584. }
  176585. }
  176586. }
  176587. }
  176588. }
  176589. }
  176590. }
  176591. /* Request any required workspace.
  176592. *
  176593. * We allocate the workspace virtual arrays from the source decompression
  176594. * object, so that all the arrays (both the original data and the workspace)
  176595. * will be taken into account while making memory management decisions.
  176596. * Hence, this routine must be called after jpeg_read_header (which reads
  176597. * the image dimensions) and before jpeg_read_coefficients (which realizes
  176598. * the source's virtual arrays).
  176599. */
  176600. GLOBAL(void)
  176601. jtransform_request_workspace (j_decompress_ptr srcinfo,
  176602. jpeg_transform_info *info)
  176603. {
  176604. jvirt_barray_ptr *coef_arrays = NULL;
  176605. jpeg_component_info *compptr;
  176606. int ci;
  176607. if (info->force_grayscale &&
  176608. srcinfo->jpeg_color_space == JCS_YCbCr &&
  176609. srcinfo->num_components == 3) {
  176610. /* We'll only process the first component */
  176611. info->num_components = 1;
  176612. } else {
  176613. /* Process all the components */
  176614. info->num_components = srcinfo->num_components;
  176615. }
  176616. switch (info->transform) {
  176617. case JXFORM_NONE:
  176618. case JXFORM_FLIP_H:
  176619. /* Don't need a workspace array */
  176620. break;
  176621. case JXFORM_FLIP_V:
  176622. case JXFORM_ROT_180:
  176623. /* Need workspace arrays having same dimensions as source image.
  176624. * Note that we allocate arrays padded out to the next iMCU boundary,
  176625. * so that transform routines need not worry about missing edge blocks.
  176626. */
  176627. coef_arrays = (jvirt_barray_ptr *)
  176628. (*srcinfo->mem->alloc_small) ((j_common_ptr) srcinfo, JPOOL_IMAGE,
  176629. SIZEOF(jvirt_barray_ptr) * info->num_components);
  176630. for (ci = 0; ci < info->num_components; ci++) {
  176631. compptr = srcinfo->comp_info + ci;
  176632. coef_arrays[ci] = (*srcinfo->mem->request_virt_barray)
  176633. ((j_common_ptr) srcinfo, JPOOL_IMAGE, FALSE,
  176634. (JDIMENSION) jround_up((long) compptr->width_in_blocks,
  176635. (long) compptr->h_samp_factor),
  176636. (JDIMENSION) jround_up((long) compptr->height_in_blocks,
  176637. (long) compptr->v_samp_factor),
  176638. (JDIMENSION) compptr->v_samp_factor);
  176639. }
  176640. break;
  176641. case JXFORM_TRANSPOSE:
  176642. case JXFORM_TRANSVERSE:
  176643. case JXFORM_ROT_90:
  176644. case JXFORM_ROT_270:
  176645. /* Need workspace arrays having transposed dimensions.
  176646. * Note that we allocate arrays padded out to the next iMCU boundary,
  176647. * so that transform routines need not worry about missing edge blocks.
  176648. */
  176649. coef_arrays = (jvirt_barray_ptr *)
  176650. (*srcinfo->mem->alloc_small) ((j_common_ptr) srcinfo, JPOOL_IMAGE,
  176651. SIZEOF(jvirt_barray_ptr) * info->num_components);
  176652. for (ci = 0; ci < info->num_components; ci++) {
  176653. compptr = srcinfo->comp_info + ci;
  176654. coef_arrays[ci] = (*srcinfo->mem->request_virt_barray)
  176655. ((j_common_ptr) srcinfo, JPOOL_IMAGE, FALSE,
  176656. (JDIMENSION) jround_up((long) compptr->height_in_blocks,
  176657. (long) compptr->v_samp_factor),
  176658. (JDIMENSION) jround_up((long) compptr->width_in_blocks,
  176659. (long) compptr->h_samp_factor),
  176660. (JDIMENSION) compptr->h_samp_factor);
  176661. }
  176662. break;
  176663. }
  176664. info->workspace_coef_arrays = coef_arrays;
  176665. }
  176666. /* Transpose destination image parameters */
  176667. LOCAL(void)
  176668. transpose_critical_parameters (j_compress_ptr dstinfo)
  176669. {
  176670. int tblno, i, j, ci, itemp;
  176671. jpeg_component_info *compptr;
  176672. JQUANT_TBL *qtblptr;
  176673. JDIMENSION dtemp;
  176674. UINT16 qtemp;
  176675. /* Transpose basic image dimensions */
  176676. dtemp = dstinfo->image_width;
  176677. dstinfo->image_width = dstinfo->image_height;
  176678. dstinfo->image_height = dtemp;
  176679. /* Transpose sampling factors */
  176680. for (ci = 0; ci < dstinfo->num_components; ci++) {
  176681. compptr = dstinfo->comp_info + ci;
  176682. itemp = compptr->h_samp_factor;
  176683. compptr->h_samp_factor = compptr->v_samp_factor;
  176684. compptr->v_samp_factor = itemp;
  176685. }
  176686. /* Transpose quantization tables */
  176687. for (tblno = 0; tblno < NUM_QUANT_TBLS; tblno++) {
  176688. qtblptr = dstinfo->quant_tbl_ptrs[tblno];
  176689. if (qtblptr != NULL) {
  176690. for (i = 0; i < DCTSIZE; i++) {
  176691. for (j = 0; j < i; j++) {
  176692. qtemp = qtblptr->quantval[i*DCTSIZE+j];
  176693. qtblptr->quantval[i*DCTSIZE+j] = qtblptr->quantval[j*DCTSIZE+i];
  176694. qtblptr->quantval[j*DCTSIZE+i] = qtemp;
  176695. }
  176696. }
  176697. }
  176698. }
  176699. }
  176700. /* Trim off any partial iMCUs on the indicated destination edge */
  176701. LOCAL(void)
  176702. trim_right_edge (j_compress_ptr dstinfo)
  176703. {
  176704. int ci, max_h_samp_factor;
  176705. JDIMENSION MCU_cols;
  176706. /* We have to compute max_h_samp_factor ourselves,
  176707. * because it hasn't been set yet in the destination
  176708. * (and we don't want to use the source's value).
  176709. */
  176710. max_h_samp_factor = 1;
  176711. for (ci = 0; ci < dstinfo->num_components; ci++) {
  176712. int h_samp_factor = dstinfo->comp_info[ci].h_samp_factor;
  176713. max_h_samp_factor = MAX(max_h_samp_factor, h_samp_factor);
  176714. }
  176715. MCU_cols = dstinfo->image_width / (max_h_samp_factor * DCTSIZE);
  176716. if (MCU_cols > 0) /* can't trim to 0 pixels */
  176717. dstinfo->image_width = MCU_cols * (max_h_samp_factor * DCTSIZE);
  176718. }
  176719. LOCAL(void)
  176720. trim_bottom_edge (j_compress_ptr dstinfo)
  176721. {
  176722. int ci, max_v_samp_factor;
  176723. JDIMENSION MCU_rows;
  176724. /* We have to compute max_v_samp_factor ourselves,
  176725. * because it hasn't been set yet in the destination
  176726. * (and we don't want to use the source's value).
  176727. */
  176728. max_v_samp_factor = 1;
  176729. for (ci = 0; ci < dstinfo->num_components; ci++) {
  176730. int v_samp_factor = dstinfo->comp_info[ci].v_samp_factor;
  176731. max_v_samp_factor = MAX(max_v_samp_factor, v_samp_factor);
  176732. }
  176733. MCU_rows = dstinfo->image_height / (max_v_samp_factor * DCTSIZE);
  176734. if (MCU_rows > 0) /* can't trim to 0 pixels */
  176735. dstinfo->image_height = MCU_rows * (max_v_samp_factor * DCTSIZE);
  176736. }
  176737. /* Adjust output image parameters as needed.
  176738. *
  176739. * This must be called after jpeg_copy_critical_parameters()
  176740. * and before jpeg_write_coefficients().
  176741. *
  176742. * The return value is the set of virtual coefficient arrays to be written
  176743. * (either the ones allocated by jtransform_request_workspace, or the
  176744. * original source data arrays). The caller will need to pass this value
  176745. * to jpeg_write_coefficients().
  176746. */
  176747. GLOBAL(jvirt_barray_ptr *)
  176748. jtransform_adjust_parameters (j_decompress_ptr,
  176749. j_compress_ptr dstinfo,
  176750. jvirt_barray_ptr *src_coef_arrays,
  176751. jpeg_transform_info *info)
  176752. {
  176753. /* If force-to-grayscale is requested, adjust destination parameters */
  176754. if (info->force_grayscale) {
  176755. /* We use jpeg_set_colorspace to make sure subsidiary settings get fixed
  176756. * properly. Among other things, the target h_samp_factor & v_samp_factor
  176757. * will get set to 1, which typically won't match the source.
  176758. * In fact we do this even if the source is already grayscale; that
  176759. * provides an easy way of coercing a grayscale JPEG with funny sampling
  176760. * factors to the customary 1,1. (Some decoders fail on other factors.)
  176761. */
  176762. if ((dstinfo->jpeg_color_space == JCS_YCbCr &&
  176763. dstinfo->num_components == 3) ||
  176764. (dstinfo->jpeg_color_space == JCS_GRAYSCALE &&
  176765. dstinfo->num_components == 1)) {
  176766. /* We have to preserve the source's quantization table number. */
  176767. int sv_quant_tbl_no = dstinfo->comp_info[0].quant_tbl_no;
  176768. jpeg_set_colorspace(dstinfo, JCS_GRAYSCALE);
  176769. dstinfo->comp_info[0].quant_tbl_no = sv_quant_tbl_no;
  176770. } else {
  176771. /* Sorry, can't do it */
  176772. ERREXIT(dstinfo, JERR_CONVERSION_NOTIMPL);
  176773. }
  176774. }
  176775. /* Correct the destination's image dimensions etc if necessary */
  176776. switch (info->transform) {
  176777. case JXFORM_NONE:
  176778. /* Nothing to do */
  176779. break;
  176780. case JXFORM_FLIP_H:
  176781. if (info->trim)
  176782. trim_right_edge(dstinfo);
  176783. break;
  176784. case JXFORM_FLIP_V:
  176785. if (info->trim)
  176786. trim_bottom_edge(dstinfo);
  176787. break;
  176788. case JXFORM_TRANSPOSE:
  176789. transpose_critical_parameters(dstinfo);
  176790. /* transpose does NOT have to trim anything */
  176791. break;
  176792. case JXFORM_TRANSVERSE:
  176793. transpose_critical_parameters(dstinfo);
  176794. if (info->trim) {
  176795. trim_right_edge(dstinfo);
  176796. trim_bottom_edge(dstinfo);
  176797. }
  176798. break;
  176799. case JXFORM_ROT_90:
  176800. transpose_critical_parameters(dstinfo);
  176801. if (info->trim)
  176802. trim_right_edge(dstinfo);
  176803. break;
  176804. case JXFORM_ROT_180:
  176805. if (info->trim) {
  176806. trim_right_edge(dstinfo);
  176807. trim_bottom_edge(dstinfo);
  176808. }
  176809. break;
  176810. case JXFORM_ROT_270:
  176811. transpose_critical_parameters(dstinfo);
  176812. if (info->trim)
  176813. trim_bottom_edge(dstinfo);
  176814. break;
  176815. }
  176816. /* Return the appropriate output data set */
  176817. if (info->workspace_coef_arrays != NULL)
  176818. return info->workspace_coef_arrays;
  176819. return src_coef_arrays;
  176820. }
  176821. /* Execute the actual transformation, if any.
  176822. *
  176823. * This must be called *after* jpeg_write_coefficients, because it depends
  176824. * on jpeg_write_coefficients to have computed subsidiary values such as
  176825. * the per-component width and height fields in the destination object.
  176826. *
  176827. * Note that some transformations will modify the source data arrays!
  176828. */
  176829. GLOBAL(void)
  176830. jtransform_execute_transformation (j_decompress_ptr srcinfo,
  176831. j_compress_ptr dstinfo,
  176832. jvirt_barray_ptr *src_coef_arrays,
  176833. jpeg_transform_info *info)
  176834. {
  176835. jvirt_barray_ptr *dst_coef_arrays = info->workspace_coef_arrays;
  176836. switch (info->transform) {
  176837. case JXFORM_NONE:
  176838. break;
  176839. case JXFORM_FLIP_H:
  176840. do_flip_h(srcinfo, dstinfo, src_coef_arrays);
  176841. break;
  176842. case JXFORM_FLIP_V:
  176843. do_flip_v(srcinfo, dstinfo, src_coef_arrays, dst_coef_arrays);
  176844. break;
  176845. case JXFORM_TRANSPOSE:
  176846. do_transpose(srcinfo, dstinfo, src_coef_arrays, dst_coef_arrays);
  176847. break;
  176848. case JXFORM_TRANSVERSE:
  176849. do_transverse(srcinfo, dstinfo, src_coef_arrays, dst_coef_arrays);
  176850. break;
  176851. case JXFORM_ROT_90:
  176852. do_rot_90(srcinfo, dstinfo, src_coef_arrays, dst_coef_arrays);
  176853. break;
  176854. case JXFORM_ROT_180:
  176855. do_rot_180(srcinfo, dstinfo, src_coef_arrays, dst_coef_arrays);
  176856. break;
  176857. case JXFORM_ROT_270:
  176858. do_rot_270(srcinfo, dstinfo, src_coef_arrays, dst_coef_arrays);
  176859. break;
  176860. }
  176861. }
  176862. #endif /* TRANSFORMS_SUPPORTED */
  176863. /* Setup decompression object to save desired markers in memory.
  176864. * This must be called before jpeg_read_header() to have the desired effect.
  176865. */
  176866. GLOBAL(void)
  176867. jcopy_markers_setup (j_decompress_ptr srcinfo, JCOPY_OPTION option)
  176868. {
  176869. #ifdef SAVE_MARKERS_SUPPORTED
  176870. int m;
  176871. /* Save comments except under NONE option */
  176872. if (option != JCOPYOPT_NONE) {
  176873. jpeg_save_markers(srcinfo, JPEG_COM, 0xFFFF);
  176874. }
  176875. /* Save all types of APPn markers iff ALL option */
  176876. if (option == JCOPYOPT_ALL) {
  176877. for (m = 0; m < 16; m++)
  176878. jpeg_save_markers(srcinfo, JPEG_APP0 + m, 0xFFFF);
  176879. }
  176880. #endif /* SAVE_MARKERS_SUPPORTED */
  176881. }
  176882. /* Copy markers saved in the given source object to the destination object.
  176883. * This should be called just after jpeg_start_compress() or
  176884. * jpeg_write_coefficients().
  176885. * Note that those routines will have written the SOI, and also the
  176886. * JFIF APP0 or Adobe APP14 markers if selected.
  176887. */
  176888. GLOBAL(void)
  176889. jcopy_markers_execute (j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  176890. JCOPY_OPTION)
  176891. {
  176892. jpeg_saved_marker_ptr marker;
  176893. /* In the current implementation, we don't actually need to examine the
  176894. * option flag here; we just copy everything that got saved.
  176895. * But to avoid confusion, we do not output JFIF and Adobe APP14 markers
  176896. * if the encoder library already wrote one.
  176897. */
  176898. for (marker = srcinfo->marker_list; marker != NULL; marker = marker->next) {
  176899. if (dstinfo->write_JFIF_header &&
  176900. marker->marker == JPEG_APP0 &&
  176901. marker->data_length >= 5 &&
  176902. GETJOCTET(marker->data[0]) == 0x4A &&
  176903. GETJOCTET(marker->data[1]) == 0x46 &&
  176904. GETJOCTET(marker->data[2]) == 0x49 &&
  176905. GETJOCTET(marker->data[3]) == 0x46 &&
  176906. GETJOCTET(marker->data[4]) == 0)
  176907. continue; /* reject duplicate JFIF */
  176908. if (dstinfo->write_Adobe_marker &&
  176909. marker->marker == JPEG_APP0+14 &&
  176910. marker->data_length >= 5 &&
  176911. GETJOCTET(marker->data[0]) == 0x41 &&
  176912. GETJOCTET(marker->data[1]) == 0x64 &&
  176913. GETJOCTET(marker->data[2]) == 0x6F &&
  176914. GETJOCTET(marker->data[3]) == 0x62 &&
  176915. GETJOCTET(marker->data[4]) == 0x65)
  176916. continue; /* reject duplicate Adobe */
  176917. #ifdef NEED_FAR_POINTERS
  176918. /* We could use jpeg_write_marker if the data weren't FAR... */
  176919. {
  176920. unsigned int i;
  176921. jpeg_write_m_header(dstinfo, marker->marker, marker->data_length);
  176922. for (i = 0; i < marker->data_length; i++)
  176923. jpeg_write_m_byte(dstinfo, marker->data[i]);
  176924. }
  176925. #else
  176926. jpeg_write_marker(dstinfo, marker->marker,
  176927. marker->data, marker->data_length);
  176928. #endif
  176929. }
  176930. }
  176931. /*** End of inlined file: transupp.c ***/
  176932. }
  176933. #else
  176934. #define JPEG_INTERNALS
  176935. #undef FAR
  176936. #include <jpeglib.h>
  176937. #endif
  176938. }
  176939. #undef max
  176940. #undef min
  176941. #if JUCE_MSVC
  176942. #pragma warning (pop)
  176943. #endif
  176944. BEGIN_JUCE_NAMESPACE
  176945. namespace JPEGHelpers
  176946. {
  176947. using namespace jpeglibNamespace;
  176948. #if ! JUCE_MSVC
  176949. using jpeglibNamespace::boolean;
  176950. #endif
  176951. struct JPEGDecodingFailure {};
  176952. static void fatalErrorHandler (j_common_ptr)
  176953. {
  176954. throw JPEGDecodingFailure();
  176955. }
  176956. static void silentErrorCallback1 (j_common_ptr) {}
  176957. static void silentErrorCallback2 (j_common_ptr, int) {}
  176958. static void silentErrorCallback3 (j_common_ptr, char*) {}
  176959. static void setupSilentErrorHandler (struct jpeg_error_mgr& err)
  176960. {
  176961. zerostruct (err);
  176962. err.error_exit = fatalErrorHandler;
  176963. err.emit_message = silentErrorCallback2;
  176964. err.output_message = silentErrorCallback1;
  176965. err.format_message = silentErrorCallback3;
  176966. err.reset_error_mgr = silentErrorCallback1;
  176967. }
  176968. static void dummyCallback1 (j_decompress_ptr)
  176969. {
  176970. }
  176971. static void jpegSkip (j_decompress_ptr decompStruct, long num)
  176972. {
  176973. decompStruct->src->next_input_byte += num;
  176974. num = jmin (num, (long) decompStruct->src->bytes_in_buffer);
  176975. decompStruct->src->bytes_in_buffer -= num;
  176976. }
  176977. static boolean jpegFill (j_decompress_ptr)
  176978. {
  176979. return 0;
  176980. }
  176981. static const int jpegBufferSize = 512;
  176982. struct JuceJpegDest : public jpeg_destination_mgr
  176983. {
  176984. OutputStream* output;
  176985. char* buffer;
  176986. };
  176987. static void jpegWriteInit (j_compress_ptr)
  176988. {
  176989. }
  176990. static void jpegWriteTerminate (j_compress_ptr cinfo)
  176991. {
  176992. JuceJpegDest* const dest = static_cast <JuceJpegDest*> (cinfo->dest);
  176993. const size_t numToWrite = jpegBufferSize - dest->free_in_buffer;
  176994. dest->output->write (dest->buffer, (int) numToWrite);
  176995. }
  176996. static boolean jpegWriteFlush (j_compress_ptr cinfo)
  176997. {
  176998. JuceJpegDest* const dest = static_cast <JuceJpegDest*> (cinfo->dest);
  176999. const int numToWrite = jpegBufferSize;
  177000. dest->next_output_byte = reinterpret_cast <JOCTET*> (dest->buffer);
  177001. dest->free_in_buffer = jpegBufferSize;
  177002. return dest->output->write (dest->buffer, numToWrite);
  177003. }
  177004. }
  177005. JPEGImageFormat::JPEGImageFormat()
  177006. : quality (-1.0f)
  177007. {
  177008. }
  177009. JPEGImageFormat::~JPEGImageFormat() {}
  177010. void JPEGImageFormat::setQuality (const float newQuality)
  177011. {
  177012. quality = newQuality;
  177013. }
  177014. const String JPEGImageFormat::getFormatName()
  177015. {
  177016. return "JPEG";
  177017. }
  177018. bool JPEGImageFormat::canUnderstand (InputStream& in)
  177019. {
  177020. const int bytesNeeded = 10;
  177021. uint8 header [bytesNeeded];
  177022. if (in.read (header, bytesNeeded) == bytesNeeded)
  177023. {
  177024. return header[0] == 0xff
  177025. && header[1] == 0xd8
  177026. && header[2] == 0xff
  177027. && (header[3] == 0xe0 || header[3] == 0xe1);
  177028. }
  177029. return false;
  177030. }
  177031. Image* JPEGImageFormat::decodeImage (InputStream& in)
  177032. {
  177033. using namespace jpeglibNamespace;
  177034. using namespace JPEGHelpers;
  177035. MemoryBlock mb;
  177036. in.readIntoMemoryBlock (mb);
  177037. Image* image = 0;
  177038. if (mb.getSize() > 16)
  177039. {
  177040. struct jpeg_decompress_struct jpegDecompStruct;
  177041. struct jpeg_error_mgr jerr;
  177042. setupSilentErrorHandler (jerr);
  177043. jpegDecompStruct.err = &jerr;
  177044. jpeg_create_decompress (&jpegDecompStruct);
  177045. jpegDecompStruct.src = (jpeg_source_mgr*)(jpegDecompStruct.mem->alloc_small)
  177046. ((j_common_ptr)(&jpegDecompStruct), JPOOL_PERMANENT, sizeof (jpeg_source_mgr));
  177047. jpegDecompStruct.src->init_source = dummyCallback1;
  177048. jpegDecompStruct.src->fill_input_buffer = jpegFill;
  177049. jpegDecompStruct.src->skip_input_data = jpegSkip;
  177050. jpegDecompStruct.src->resync_to_restart = jpeg_resync_to_restart;
  177051. jpegDecompStruct.src->term_source = dummyCallback1;
  177052. jpegDecompStruct.src->next_input_byte = static_cast <const unsigned char*> (mb.getData());
  177053. jpegDecompStruct.src->bytes_in_buffer = mb.getSize();
  177054. try
  177055. {
  177056. jpeg_read_header (&jpegDecompStruct, TRUE);
  177057. jpeg_calc_output_dimensions (&jpegDecompStruct);
  177058. const int width = jpegDecompStruct.output_width;
  177059. const int height = jpegDecompStruct.output_height;
  177060. jpegDecompStruct.out_color_space = JCS_RGB;
  177061. JSAMPARRAY buffer
  177062. = (*jpegDecompStruct.mem->alloc_sarray) ((j_common_ptr) &jpegDecompStruct,
  177063. JPOOL_IMAGE,
  177064. width * 3, 1);
  177065. if (jpeg_start_decompress (&jpegDecompStruct))
  177066. {
  177067. image = Image::createNativeImage (Image::RGB, width, height, false);
  177068. const bool hasAlphaChan = image->hasAlphaChannel();
  177069. const Image::BitmapData destData (*image, 0, 0, width, height, true);
  177070. for (int y = 0; y < height; ++y)
  177071. {
  177072. jpeg_read_scanlines (&jpegDecompStruct, buffer, 1);
  177073. const uint8* src = *buffer;
  177074. uint8* dest = destData.getLinePointer (y);
  177075. if (hasAlphaChan)
  177076. {
  177077. for (int i = width; --i >= 0;)
  177078. {
  177079. ((PixelARGB*) dest)->setARGB (0xff, src[0], src[1], src[2]);
  177080. ((PixelARGB*) dest)->premultiply();
  177081. dest += destData.pixelStride;
  177082. src += 3;
  177083. }
  177084. }
  177085. else
  177086. {
  177087. for (int i = width; --i >= 0;)
  177088. {
  177089. ((PixelRGB*) dest)->setARGB (0xff, src[0], src[1], src[2]);
  177090. dest += destData.pixelStride;
  177091. src += 3;
  177092. }
  177093. }
  177094. }
  177095. jpeg_finish_decompress (&jpegDecompStruct);
  177096. in.setPosition (((char*) jpegDecompStruct.src->next_input_byte) - (char*) mb.getData());
  177097. }
  177098. jpeg_destroy_decompress (&jpegDecompStruct);
  177099. }
  177100. catch (...)
  177101. {}
  177102. }
  177103. return image;
  177104. }
  177105. bool JPEGImageFormat::writeImageToStream (const Image& image, OutputStream& out)
  177106. {
  177107. using namespace jpeglibNamespace;
  177108. using namespace JPEGHelpers;
  177109. if (image.hasAlphaChannel())
  177110. {
  177111. // this method could fill the background in white and still save the image..
  177112. jassertfalse
  177113. return true;
  177114. }
  177115. struct jpeg_compress_struct jpegCompStruct;
  177116. struct jpeg_error_mgr jerr;
  177117. setupSilentErrorHandler (jerr);
  177118. jpegCompStruct.err = &jerr;
  177119. jpeg_create_compress (&jpegCompStruct);
  177120. JuceJpegDest dest;
  177121. jpegCompStruct.dest = &dest;
  177122. dest.output = &out;
  177123. HeapBlock <char> tempBuffer (jpegBufferSize);
  177124. dest.buffer = tempBuffer;
  177125. dest.next_output_byte = (JOCTET*) dest.buffer;
  177126. dest.free_in_buffer = jpegBufferSize;
  177127. dest.init_destination = jpegWriteInit;
  177128. dest.empty_output_buffer = jpegWriteFlush;
  177129. dest.term_destination = jpegWriteTerminate;
  177130. jpegCompStruct.image_width = image.getWidth();
  177131. jpegCompStruct.image_height = image.getHeight();
  177132. jpegCompStruct.input_components = 3;
  177133. jpegCompStruct.in_color_space = JCS_RGB;
  177134. jpegCompStruct.write_JFIF_header = 1;
  177135. jpegCompStruct.X_density = 72;
  177136. jpegCompStruct.Y_density = 72;
  177137. jpeg_set_defaults (&jpegCompStruct);
  177138. jpegCompStruct.dct_method = JDCT_FLOAT;
  177139. jpegCompStruct.optimize_coding = 1;
  177140. //jpegCompStruct.smoothing_factor = 10;
  177141. if (quality < 0.0f)
  177142. quality = 0.85f;
  177143. jpeg_set_quality (&jpegCompStruct, jlimit (0, 100, roundToInt (quality * 100.0f)), TRUE);
  177144. jpeg_start_compress (&jpegCompStruct, TRUE);
  177145. const int strideBytes = jpegCompStruct.image_width * jpegCompStruct.input_components;
  177146. JSAMPARRAY buffer = (*jpegCompStruct.mem->alloc_sarray) ((j_common_ptr) &jpegCompStruct,
  177147. JPOOL_IMAGE, strideBytes, 1);
  177148. const Image::BitmapData srcData (image, 0, 0, jpegCompStruct.image_width, jpegCompStruct.image_height);
  177149. while (jpegCompStruct.next_scanline < jpegCompStruct.image_height)
  177150. {
  177151. const uint8* src = srcData.getLinePointer (jpegCompStruct.next_scanline);
  177152. uint8* dst = *buffer;
  177153. for (int i = jpegCompStruct.image_width; --i >= 0;)
  177154. {
  177155. *dst++ = ((const PixelRGB*) src)->getRed();
  177156. *dst++ = ((const PixelRGB*) src)->getGreen();
  177157. *dst++ = ((const PixelRGB*) src)->getBlue();
  177158. src += srcData.pixelStride;
  177159. }
  177160. jpeg_write_scanlines (&jpegCompStruct, buffer, 1);
  177161. }
  177162. jpeg_finish_compress (&jpegCompStruct);
  177163. jpeg_destroy_compress (&jpegCompStruct);
  177164. out.flush();
  177165. return true;
  177166. }
  177167. END_JUCE_NAMESPACE
  177168. /*** End of inlined file: juce_JPEGLoader.cpp ***/
  177169. /*** Start of inlined file: juce_PNGLoader.cpp ***/
  177170. #ifdef _MSC_VER
  177171. #pragma warning (push)
  177172. #pragma warning (disable: 4390 4611)
  177173. #endif
  177174. namespace zlibNamespace
  177175. {
  177176. #if JUCE_INCLUDE_ZLIB_CODE
  177177. #undef OS_CODE
  177178. #undef fdopen
  177179. #undef OS_CODE
  177180. #else
  177181. #include <zlib.h>
  177182. #endif
  177183. }
  177184. namespace pnglibNamespace
  177185. {
  177186. using namespace zlibNamespace;
  177187. #if JUCE_INCLUDE_PNGLIB_CODE
  177188. #if _MSC_VER != 1310
  177189. using ::calloc; // (causes conflict in VS.NET 2003)
  177190. using ::malloc;
  177191. using ::free;
  177192. #endif
  177193. extern "C"
  177194. {
  177195. using ::abs;
  177196. #define PNG_INTERNAL
  177197. #define NO_DUMMY_DECL
  177198. #define PNG_SETJMP_NOT_SUPPORTED
  177199. /*** Start of inlined file: png.h ***/
  177200. /* png.h - header file for PNG reference library
  177201. *
  177202. * libpng version 1.2.21 - October 4, 2007
  177203. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  177204. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  177205. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  177206. *
  177207. * Authors and maintainers:
  177208. * libpng versions 0.71, May 1995, through 0.88, January 1996: Guy Schalnat
  177209. * libpng versions 0.89c, June 1996, through 0.96, May 1997: Andreas Dilger
  177210. * libpng versions 0.97, January 1998, through 1.2.21 - October 4, 2007: Glenn
  177211. * See also "Contributing Authors", below.
  177212. *
  177213. * Note about libpng version numbers:
  177214. *
  177215. * Due to various miscommunications, unforeseen code incompatibilities
  177216. * and occasional factors outside the authors' control, version numbering
  177217. * on the library has not always been consistent and straightforward.
  177218. * The following table summarizes matters since version 0.89c, which was
  177219. * the first widely used release:
  177220. *
  177221. * source png.h png.h shared-lib
  177222. * version string int version
  177223. * ------- ------ ----- ----------
  177224. * 0.89c "1.0 beta 3" 0.89 89 1.0.89
  177225. * 0.90 "1.0 beta 4" 0.90 90 0.90 [should have been 2.0.90]
  177226. * 0.95 "1.0 beta 5" 0.95 95 0.95 [should have been 2.0.95]
  177227. * 0.96 "1.0 beta 6" 0.96 96 0.96 [should have been 2.0.96]
  177228. * 0.97b "1.00.97 beta 7" 1.00.97 97 1.0.1 [should have been 2.0.97]
  177229. * 0.97c 0.97 97 2.0.97
  177230. * 0.98 0.98 98 2.0.98
  177231. * 0.99 0.99 98 2.0.99
  177232. * 0.99a-m 0.99 99 2.0.99
  177233. * 1.00 1.00 100 2.1.0 [100 should be 10000]
  177234. * 1.0.0 (from here on, the 100 2.1.0 [100 should be 10000]
  177235. * 1.0.1 png.h string is 10001 2.1.0
  177236. * 1.0.1a-e identical to the 10002 from here on, the shared library
  177237. * 1.0.2 source version) 10002 is 2.V where V is the source code
  177238. * 1.0.2a-b 10003 version, except as noted.
  177239. * 1.0.3 10003
  177240. * 1.0.3a-d 10004
  177241. * 1.0.4 10004
  177242. * 1.0.4a-f 10005
  177243. * 1.0.5 (+ 2 patches) 10005
  177244. * 1.0.5a-d 10006
  177245. * 1.0.5e-r 10100 (not source compatible)
  177246. * 1.0.5s-v 10006 (not binary compatible)
  177247. * 1.0.6 (+ 3 patches) 10006 (still binary incompatible)
  177248. * 1.0.6d-f 10007 (still binary incompatible)
  177249. * 1.0.6g 10007
  177250. * 1.0.6h 10007 10.6h (testing xy.z so-numbering)
  177251. * 1.0.6i 10007 10.6i
  177252. * 1.0.6j 10007 2.1.0.6j (incompatible with 1.0.0)
  177253. * 1.0.7beta11-14 DLLNUM 10007 2.1.0.7beta11-14 (binary compatible)
  177254. * 1.0.7beta15-18 1 10007 2.1.0.7beta15-18 (binary compatible)
  177255. * 1.0.7rc1-2 1 10007 2.1.0.7rc1-2 (binary compatible)
  177256. * 1.0.7 1 10007 (still compatible)
  177257. * 1.0.8beta1-4 1 10008 2.1.0.8beta1-4
  177258. * 1.0.8rc1 1 10008 2.1.0.8rc1
  177259. * 1.0.8 1 10008 2.1.0.8
  177260. * 1.0.9beta1-6 1 10009 2.1.0.9beta1-6
  177261. * 1.0.9rc1 1 10009 2.1.0.9rc1
  177262. * 1.0.9beta7-10 1 10009 2.1.0.9beta7-10
  177263. * 1.0.9rc2 1 10009 2.1.0.9rc2
  177264. * 1.0.9 1 10009 2.1.0.9
  177265. * 1.0.10beta1 1 10010 2.1.0.10beta1
  177266. * 1.0.10rc1 1 10010 2.1.0.10rc1
  177267. * 1.0.10 1 10010 2.1.0.10
  177268. * 1.0.11beta1-3 1 10011 2.1.0.11beta1-3
  177269. * 1.0.11rc1 1 10011 2.1.0.11rc1
  177270. * 1.0.11 1 10011 2.1.0.11
  177271. * 1.0.12beta1-2 2 10012 2.1.0.12beta1-2
  177272. * 1.0.12rc1 2 10012 2.1.0.12rc1
  177273. * 1.0.12 2 10012 2.1.0.12
  177274. * 1.1.0a-f - 10100 2.1.1.0a-f (branch abandoned)
  177275. * 1.2.0beta1-2 2 10200 2.1.2.0beta1-2
  177276. * 1.2.0beta3-5 3 10200 3.1.2.0beta3-5
  177277. * 1.2.0rc1 3 10200 3.1.2.0rc1
  177278. * 1.2.0 3 10200 3.1.2.0
  177279. * 1.2.1beta1-4 3 10201 3.1.2.1beta1-4
  177280. * 1.2.1rc1-2 3 10201 3.1.2.1rc1-2
  177281. * 1.2.1 3 10201 3.1.2.1
  177282. * 1.2.2beta1-6 12 10202 12.so.0.1.2.2beta1-6
  177283. * 1.0.13beta1 10 10013 10.so.0.1.0.13beta1
  177284. * 1.0.13rc1 10 10013 10.so.0.1.0.13rc1
  177285. * 1.2.2rc1 12 10202 12.so.0.1.2.2rc1
  177286. * 1.0.13 10 10013 10.so.0.1.0.13
  177287. * 1.2.2 12 10202 12.so.0.1.2.2
  177288. * 1.2.3rc1-6 12 10203 12.so.0.1.2.3rc1-6
  177289. * 1.2.3 12 10203 12.so.0.1.2.3
  177290. * 1.2.4beta1-3 13 10204 12.so.0.1.2.4beta1-3
  177291. * 1.0.14rc1 13 10014 10.so.0.1.0.14rc1
  177292. * 1.2.4rc1 13 10204 12.so.0.1.2.4rc1
  177293. * 1.0.14 10 10014 10.so.0.1.0.14
  177294. * 1.2.4 13 10204 12.so.0.1.2.4
  177295. * 1.2.5beta1-2 13 10205 12.so.0.1.2.5beta1-2
  177296. * 1.0.15rc1-3 10 10015 10.so.0.1.0.15rc1-3
  177297. * 1.2.5rc1-3 13 10205 12.so.0.1.2.5rc1-3
  177298. * 1.0.15 10 10015 10.so.0.1.0.15
  177299. * 1.2.5 13 10205 12.so.0.1.2.5
  177300. * 1.2.6beta1-4 13 10206 12.so.0.1.2.6beta1-4
  177301. * 1.0.16 10 10016 10.so.0.1.0.16
  177302. * 1.2.6 13 10206 12.so.0.1.2.6
  177303. * 1.2.7beta1-2 13 10207 12.so.0.1.2.7beta1-2
  177304. * 1.0.17rc1 10 10017 10.so.0.1.0.17rc1
  177305. * 1.2.7rc1 13 10207 12.so.0.1.2.7rc1
  177306. * 1.0.17 10 10017 10.so.0.1.0.17
  177307. * 1.2.7 13 10207 12.so.0.1.2.7
  177308. * 1.2.8beta1-5 13 10208 12.so.0.1.2.8beta1-5
  177309. * 1.0.18rc1-5 10 10018 10.so.0.1.0.18rc1-5
  177310. * 1.2.8rc1-5 13 10208 12.so.0.1.2.8rc1-5
  177311. * 1.0.18 10 10018 10.so.0.1.0.18
  177312. * 1.2.8 13 10208 12.so.0.1.2.8
  177313. * 1.2.9beta1-3 13 10209 12.so.0.1.2.9beta1-3
  177314. * 1.2.9beta4-11 13 10209 12.so.0.9[.0]
  177315. * 1.2.9rc1 13 10209 12.so.0.9[.0]
  177316. * 1.2.9 13 10209 12.so.0.9[.0]
  177317. * 1.2.10beta1-8 13 10210 12.so.0.10[.0]
  177318. * 1.2.10rc1-3 13 10210 12.so.0.10[.0]
  177319. * 1.2.10 13 10210 12.so.0.10[.0]
  177320. * 1.2.11beta1-4 13 10211 12.so.0.11[.0]
  177321. * 1.0.19rc1-5 10 10019 10.so.0.19[.0]
  177322. * 1.2.11rc1-5 13 10211 12.so.0.11[.0]
  177323. * 1.0.19 10 10019 10.so.0.19[.0]
  177324. * 1.2.11 13 10211 12.so.0.11[.0]
  177325. * 1.0.20 10 10020 10.so.0.20[.0]
  177326. * 1.2.12 13 10212 12.so.0.12[.0]
  177327. * 1.2.13beta1 13 10213 12.so.0.13[.0]
  177328. * 1.0.21 10 10021 10.so.0.21[.0]
  177329. * 1.2.13 13 10213 12.so.0.13[.0]
  177330. * 1.2.14beta1-2 13 10214 12.so.0.14[.0]
  177331. * 1.0.22rc1 10 10022 10.so.0.22[.0]
  177332. * 1.2.14rc1 13 10214 12.so.0.14[.0]
  177333. * 1.0.22 10 10022 10.so.0.22[.0]
  177334. * 1.2.14 13 10214 12.so.0.14[.0]
  177335. * 1.2.15beta1-6 13 10215 12.so.0.15[.0]
  177336. * 1.0.23rc1-5 10 10023 10.so.0.23[.0]
  177337. * 1.2.15rc1-5 13 10215 12.so.0.15[.0]
  177338. * 1.0.23 10 10023 10.so.0.23[.0]
  177339. * 1.2.15 13 10215 12.so.0.15[.0]
  177340. * 1.2.16beta1-2 13 10216 12.so.0.16[.0]
  177341. * 1.2.16rc1 13 10216 12.so.0.16[.0]
  177342. * 1.0.24 10 10024 10.so.0.24[.0]
  177343. * 1.2.16 13 10216 12.so.0.16[.0]
  177344. * 1.2.17beta1-2 13 10217 12.so.0.17[.0]
  177345. * 1.0.25rc1 10 10025 10.so.0.25[.0]
  177346. * 1.2.17rc1-3 13 10217 12.so.0.17[.0]
  177347. * 1.0.25 10 10025 10.so.0.25[.0]
  177348. * 1.2.17 13 10217 12.so.0.17[.0]
  177349. * 1.0.26 10 10026 10.so.0.26[.0]
  177350. * 1.2.18 13 10218 12.so.0.18[.0]
  177351. * 1.2.19beta1-31 13 10219 12.so.0.19[.0]
  177352. * 1.0.27rc1-6 10 10027 10.so.0.27[.0]
  177353. * 1.2.19rc1-6 13 10219 12.so.0.19[.0]
  177354. * 1.0.27 10 10027 10.so.0.27[.0]
  177355. * 1.2.19 13 10219 12.so.0.19[.0]
  177356. * 1.2.20beta01-04 13 10220 12.so.0.20[.0]
  177357. * 1.0.28rc1-6 10 10028 10.so.0.28[.0]
  177358. * 1.2.20rc1-6 13 10220 12.so.0.20[.0]
  177359. * 1.0.28 10 10028 10.so.0.28[.0]
  177360. * 1.2.20 13 10220 12.so.0.20[.0]
  177361. * 1.2.21beta1-2 13 10221 12.so.0.21[.0]
  177362. * 1.2.21rc1-3 13 10221 12.so.0.21[.0]
  177363. * 1.0.29 10 10029 10.so.0.29[.0]
  177364. * 1.2.21 13 10221 12.so.0.21[.0]
  177365. *
  177366. * Henceforth the source version will match the shared-library major
  177367. * and minor numbers; the shared-library major version number will be
  177368. * used for changes in backward compatibility, as it is intended. The
  177369. * PNG_LIBPNG_VER macro, which is not used within libpng but is available
  177370. * for applications, is an unsigned integer of the form xyyzz corresponding
  177371. * to the source version x.y.z (leading zeros in y and z). Beta versions
  177372. * were given the previous public release number plus a letter, until
  177373. * version 1.0.6j; from then on they were given the upcoming public
  177374. * release number plus "betaNN" or "rcN".
  177375. *
  177376. * Binary incompatibility exists only when applications make direct access
  177377. * to the info_ptr or png_ptr members through png.h, and the compiled
  177378. * application is loaded with a different version of the library.
  177379. *
  177380. * DLLNUM will change each time there are forward or backward changes
  177381. * in binary compatibility (e.g., when a new feature is added).
  177382. *
  177383. * See libpng.txt or libpng.3 for more information. The PNG specification
  177384. * is available as a W3C Recommendation and as an ISO Specification,
  177385. * <http://www.w3.org/TR/2003/REC-PNG-20031110/
  177386. */
  177387. /*
  177388. * COPYRIGHT NOTICE, DISCLAIMER, and LICENSE:
  177389. *
  177390. * If you modify libpng you may insert additional notices immediately following
  177391. * this sentence.
  177392. *
  177393. * libpng versions 1.2.6, August 15, 2004, through 1.2.21, October 4, 2007, are
  177394. * Copyright (c) 2004, 2006-2007 Glenn Randers-Pehrson, and are
  177395. * distributed according to the same disclaimer and license as libpng-1.2.5
  177396. * with the following individual added to the list of Contributing Authors:
  177397. *
  177398. * Cosmin Truta
  177399. *
  177400. * libpng versions 1.0.7, July 1, 2000, through 1.2.5, October 3, 2002, are
  177401. * Copyright (c) 2000-2002 Glenn Randers-Pehrson, and are
  177402. * distributed according to the same disclaimer and license as libpng-1.0.6
  177403. * with the following individuals added to the list of Contributing Authors:
  177404. *
  177405. * Simon-Pierre Cadieux
  177406. * Eric S. Raymond
  177407. * Gilles Vollant
  177408. *
  177409. * and with the following additions to the disclaimer:
  177410. *
  177411. * There is no warranty against interference with your enjoyment of the
  177412. * library or against infringement. There is no warranty that our
  177413. * efforts or the library will fulfill any of your particular purposes
  177414. * or needs. This library is provided with all faults, and the entire
  177415. * risk of satisfactory quality, performance, accuracy, and effort is with
  177416. * the user.
  177417. *
  177418. * libpng versions 0.97, January 1998, through 1.0.6, March 20, 2000, are
  177419. * Copyright (c) 1998, 1999, 2000 Glenn Randers-Pehrson, and are
  177420. * distributed according to the same disclaimer and license as libpng-0.96,
  177421. * with the following individuals added to the list of Contributing Authors:
  177422. *
  177423. * Tom Lane
  177424. * Glenn Randers-Pehrson
  177425. * Willem van Schaik
  177426. *
  177427. * libpng versions 0.89, June 1996, through 0.96, May 1997, are
  177428. * Copyright (c) 1996, 1997 Andreas Dilger
  177429. * Distributed according to the same disclaimer and license as libpng-0.88,
  177430. * with the following individuals added to the list of Contributing Authors:
  177431. *
  177432. * John Bowler
  177433. * Kevin Bracey
  177434. * Sam Bushell
  177435. * Magnus Holmgren
  177436. * Greg Roelofs
  177437. * Tom Tanner
  177438. *
  177439. * libpng versions 0.5, May 1995, through 0.88, January 1996, are
  177440. * Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.
  177441. *
  177442. * For the purposes of this copyright and license, "Contributing Authors"
  177443. * is defined as the following set of individuals:
  177444. *
  177445. * Andreas Dilger
  177446. * Dave Martindale
  177447. * Guy Eric Schalnat
  177448. * Paul Schmidt
  177449. * Tim Wegner
  177450. *
  177451. * The PNG Reference Library is supplied "AS IS". The Contributing Authors
  177452. * and Group 42, Inc. disclaim all warranties, expressed or implied,
  177453. * including, without limitation, the warranties of merchantability and of
  177454. * fitness for any purpose. The Contributing Authors and Group 42, Inc.
  177455. * assume no liability for direct, indirect, incidental, special, exemplary,
  177456. * or consequential damages, which may result from the use of the PNG
  177457. * Reference Library, even if advised of the possibility of such damage.
  177458. *
  177459. * Permission is hereby granted to use, copy, modify, and distribute this
  177460. * source code, or portions hereof, for any purpose, without fee, subject
  177461. * to the following restrictions:
  177462. *
  177463. * 1. The origin of this source code must not be misrepresented.
  177464. *
  177465. * 2. Altered versions must be plainly marked as such and
  177466. * must not be misrepresented as being the original source.
  177467. *
  177468. * 3. This Copyright notice may not be removed or altered from
  177469. * any source or altered source distribution.
  177470. *
  177471. * The Contributing Authors and Group 42, Inc. specifically permit, without
  177472. * fee, and encourage the use of this source code as a component to
  177473. * supporting the PNG file format in commercial products. If you use this
  177474. * source code in a product, acknowledgment is not required but would be
  177475. * appreciated.
  177476. */
  177477. /*
  177478. * A "png_get_copyright" function is available, for convenient use in "about"
  177479. * boxes and the like:
  177480. *
  177481. * printf("%s",png_get_copyright(NULL));
  177482. *
  177483. * Also, the PNG logo (in PNG format, of course) is supplied in the
  177484. * files "pngbar.png" and "pngbar.jpg (88x31) and "pngnow.png" (98x31).
  177485. */
  177486. /*
  177487. * Libpng is OSI Certified Open Source Software. OSI Certified is a
  177488. * certification mark of the Open Source Initiative.
  177489. */
  177490. /*
  177491. * The contributing authors would like to thank all those who helped
  177492. * with testing, bug fixes, and patience. This wouldn't have been
  177493. * possible without all of you.
  177494. *
  177495. * Thanks to Frank J. T. Wojcik for helping with the documentation.
  177496. */
  177497. /*
  177498. * Y2K compliance in libpng:
  177499. * =========================
  177500. *
  177501. * October 4, 2007
  177502. *
  177503. * Since the PNG Development group is an ad-hoc body, we can't make
  177504. * an official declaration.
  177505. *
  177506. * This is your unofficial assurance that libpng from version 0.71 and
  177507. * upward through 1.2.21 are Y2K compliant. It is my belief that earlier
  177508. * versions were also Y2K compliant.
  177509. *
  177510. * Libpng only has three year fields. One is a 2-byte unsigned integer
  177511. * that will hold years up to 65535. The other two hold the date in text
  177512. * format, and will hold years up to 9999.
  177513. *
  177514. * The integer is
  177515. * "png_uint_16 year" in png_time_struct.
  177516. *
  177517. * The strings are
  177518. * "png_charp time_buffer" in png_struct and
  177519. * "near_time_buffer", which is a local character string in png.c.
  177520. *
  177521. * There are seven time-related functions:
  177522. * png.c: png_convert_to_rfc_1123() in png.c
  177523. * (formerly png_convert_to_rfc_1152() in error)
  177524. * png_convert_from_struct_tm() in pngwrite.c, called in pngwrite.c
  177525. * png_convert_from_time_t() in pngwrite.c
  177526. * png_get_tIME() in pngget.c
  177527. * png_handle_tIME() in pngrutil.c, called in pngread.c
  177528. * png_set_tIME() in pngset.c
  177529. * png_write_tIME() in pngwutil.c, called in pngwrite.c
  177530. *
  177531. * All handle dates properly in a Y2K environment. The
  177532. * png_convert_from_time_t() function calls gmtime() to convert from system
  177533. * clock time, which returns (year - 1900), which we properly convert to
  177534. * the full 4-digit year. There is a possibility that applications using
  177535. * libpng are not passing 4-digit years into the png_convert_to_rfc_1123()
  177536. * function, or that they are incorrectly passing only a 2-digit year
  177537. * instead of "year - 1900" into the png_convert_from_struct_tm() function,
  177538. * but this is not under our control. The libpng documentation has always
  177539. * stated that it works with 4-digit years, and the APIs have been
  177540. * documented as such.
  177541. *
  177542. * The tIME chunk itself is also Y2K compliant. It uses a 2-byte unsigned
  177543. * integer to hold the year, and can hold years as large as 65535.
  177544. *
  177545. * zlib, upon which libpng depends, is also Y2K compliant. It contains
  177546. * no date-related code.
  177547. *
  177548. * Glenn Randers-Pehrson
  177549. * libpng maintainer
  177550. * PNG Development Group
  177551. */
  177552. #ifndef PNG_H
  177553. #define PNG_H
  177554. /* This is not the place to learn how to use libpng. The file libpng.txt
  177555. * describes how to use libpng, and the file example.c summarizes it
  177556. * with some code on which to build. This file is useful for looking
  177557. * at the actual function definitions and structure components.
  177558. */
  177559. /* Version information for png.h - this should match the version in png.c */
  177560. #define PNG_LIBPNG_VER_STRING "1.2.21"
  177561. #define PNG_HEADER_VERSION_STRING \
  177562. " libpng version 1.2.21 - October 4, 2007\n"
  177563. #define PNG_LIBPNG_VER_SONUM 0
  177564. #define PNG_LIBPNG_VER_DLLNUM 13
  177565. /* These should match the first 3 components of PNG_LIBPNG_VER_STRING: */
  177566. #define PNG_LIBPNG_VER_MAJOR 1
  177567. #define PNG_LIBPNG_VER_MINOR 2
  177568. #define PNG_LIBPNG_VER_RELEASE 21
  177569. /* This should match the numeric part of the final component of
  177570. * PNG_LIBPNG_VER_STRING, omitting any leading zero: */
  177571. #define PNG_LIBPNG_VER_BUILD 0
  177572. /* Release Status */
  177573. #define PNG_LIBPNG_BUILD_ALPHA 1
  177574. #define PNG_LIBPNG_BUILD_BETA 2
  177575. #define PNG_LIBPNG_BUILD_RC 3
  177576. #define PNG_LIBPNG_BUILD_STABLE 4
  177577. #define PNG_LIBPNG_BUILD_RELEASE_STATUS_MASK 7
  177578. /* Release-Specific Flags */
  177579. #define PNG_LIBPNG_BUILD_PATCH 8 /* Can be OR'ed with
  177580. PNG_LIBPNG_BUILD_STABLE only */
  177581. #define PNG_LIBPNG_BUILD_PRIVATE 16 /* Cannot be OR'ed with
  177582. PNG_LIBPNG_BUILD_SPECIAL */
  177583. #define PNG_LIBPNG_BUILD_SPECIAL 32 /* Cannot be OR'ed with
  177584. PNG_LIBPNG_BUILD_PRIVATE */
  177585. #define PNG_LIBPNG_BUILD_BASE_TYPE PNG_LIBPNG_BUILD_STABLE
  177586. /* Careful here. At one time, Guy wanted to use 082, but that would be octal.
  177587. * We must not include leading zeros.
  177588. * Versions 0.7 through 1.0.0 were in the range 0 to 100 here (only
  177589. * version 1.0.0 was mis-numbered 100 instead of 10000). From
  177590. * version 1.0.1 it's xxyyzz, where x=major, y=minor, z=release */
  177591. #define PNG_LIBPNG_VER 10221 /* 1.2.21 */
  177592. #ifndef PNG_VERSION_INFO_ONLY
  177593. /* include the compression library's header */
  177594. #endif
  177595. /* include all user configurable info, including optional assembler routines */
  177596. /*** Start of inlined file: pngconf.h ***/
  177597. /* pngconf.h - machine configurable file for libpng
  177598. *
  177599. * libpng version 1.2.21 - October 4, 2007
  177600. * For conditions of distribution and use, see copyright notice in png.h
  177601. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  177602. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  177603. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  177604. */
  177605. /* Any machine specific code is near the front of this file, so if you
  177606. * are configuring libpng for a machine, you may want to read the section
  177607. * starting here down to where it starts to typedef png_color, png_text,
  177608. * and png_info.
  177609. */
  177610. #ifndef PNGCONF_H
  177611. #define PNGCONF_H
  177612. #define PNG_1_2_X
  177613. // These are some Juce config settings that should remove any unnecessary code bloat..
  177614. #define PNG_NO_STDIO 1
  177615. #define PNG_DEBUG 0
  177616. #define PNG_NO_WARNINGS 1
  177617. #define PNG_NO_ERROR_TEXT 1
  177618. #define PNG_NO_ERROR_NUMBERS 1
  177619. #define PNG_NO_USER_MEM 1
  177620. #define PNG_NO_READ_iCCP 1
  177621. #define PNG_NO_READ_UNKNOWN_CHUNKS 1
  177622. #define PNG_NO_READ_USER_CHUNKS 1
  177623. #define PNG_NO_READ_iTXt 1
  177624. #define PNG_NO_READ_sCAL 1
  177625. #define PNG_NO_READ_sPLT 1
  177626. #define png_error(a, b) png_err(a)
  177627. #define png_warning(a, b)
  177628. #define png_chunk_error(a, b) png_err(a)
  177629. #define png_chunk_warning(a, b)
  177630. /*
  177631. * PNG_USER_CONFIG has to be defined on the compiler command line. This
  177632. * includes the resource compiler for Windows DLL configurations.
  177633. */
  177634. #ifdef PNG_USER_CONFIG
  177635. # ifndef PNG_USER_PRIVATEBUILD
  177636. # define PNG_USER_PRIVATEBUILD
  177637. # endif
  177638. #include "pngusr.h"
  177639. #endif
  177640. /* PNG_CONFIGURE_LIBPNG is set by the "configure" script. */
  177641. #ifdef PNG_CONFIGURE_LIBPNG
  177642. #ifdef HAVE_CONFIG_H
  177643. #include "config.h"
  177644. #endif
  177645. #endif
  177646. /*
  177647. * Added at libpng-1.2.8
  177648. *
  177649. * If you create a private DLL you need to define in "pngusr.h" the followings:
  177650. * #define PNG_USER_PRIVATEBUILD <Describes by whom and why this version of
  177651. * the DLL was built>
  177652. * e.g. #define PNG_USER_PRIVATEBUILD "Build by MyCompany for xyz reasons."
  177653. * #define PNG_USER_DLLFNAME_POSTFIX <two-letter postfix that serve to
  177654. * distinguish your DLL from those of the official release. These
  177655. * correspond to the trailing letters that come after the version
  177656. * number and must match your private DLL name>
  177657. * e.g. // private DLL "libpng13gx.dll"
  177658. * #define PNG_USER_DLLFNAME_POSTFIX "gx"
  177659. *
  177660. * The following macros are also at your disposal if you want to complete the
  177661. * DLL VERSIONINFO structure.
  177662. * - PNG_USER_VERSIONINFO_COMMENTS
  177663. * - PNG_USER_VERSIONINFO_COMPANYNAME
  177664. * - PNG_USER_VERSIONINFO_LEGALTRADEMARKS
  177665. */
  177666. #ifdef __STDC__
  177667. #ifdef SPECIALBUILD
  177668. # pragma message("PNG_LIBPNG_SPECIALBUILD (and deprecated SPECIALBUILD)\
  177669. are now LIBPNG reserved macros. Use PNG_USER_PRIVATEBUILD instead.")
  177670. #endif
  177671. #ifdef PRIVATEBUILD
  177672. # pragma message("PRIVATEBUILD is deprecated.\
  177673. Use PNG_USER_PRIVATEBUILD instead.")
  177674. # define PNG_USER_PRIVATEBUILD PRIVATEBUILD
  177675. #endif
  177676. #endif /* __STDC__ */
  177677. #ifndef PNG_VERSION_INFO_ONLY
  177678. /* End of material added to libpng-1.2.8 */
  177679. /* Added at libpng-1.2.19, removed at libpng-1.2.20 because it caused trouble
  177680. Restored at libpng-1.2.21 */
  177681. # define PNG_WARN_UNINITIALIZED_ROW 1
  177682. /* End of material added at libpng-1.2.19/1.2.21 */
  177683. /* This is the size of the compression buffer, and thus the size of
  177684. * an IDAT chunk. Make this whatever size you feel is best for your
  177685. * machine. One of these will be allocated per png_struct. When this
  177686. * is full, it writes the data to the disk, and does some other
  177687. * calculations. Making this an extremely small size will slow
  177688. * the library down, but you may want to experiment to determine
  177689. * where it becomes significant, if you are concerned with memory
  177690. * usage. Note that zlib allocates at least 32Kb also. For readers,
  177691. * this describes the size of the buffer available to read the data in.
  177692. * Unless this gets smaller than the size of a row (compressed),
  177693. * it should not make much difference how big this is.
  177694. */
  177695. #ifndef PNG_ZBUF_SIZE
  177696. # define PNG_ZBUF_SIZE 8192
  177697. #endif
  177698. /* Enable if you want a write-only libpng */
  177699. #ifndef PNG_NO_READ_SUPPORTED
  177700. # define PNG_READ_SUPPORTED
  177701. #endif
  177702. /* Enable if you want a read-only libpng */
  177703. #ifndef PNG_NO_WRITE_SUPPORTED
  177704. # define PNG_WRITE_SUPPORTED
  177705. #endif
  177706. /* Enabled by default in 1.2.0. You can disable this if you don't need to
  177707. support PNGs that are embedded in MNG datastreams */
  177708. #if !defined(PNG_1_0_X) && !defined(PNG_NO_MNG_FEATURES)
  177709. # ifndef PNG_MNG_FEATURES_SUPPORTED
  177710. # define PNG_MNG_FEATURES_SUPPORTED
  177711. # endif
  177712. #endif
  177713. #ifndef PNG_NO_FLOATING_POINT_SUPPORTED
  177714. # ifndef PNG_FLOATING_POINT_SUPPORTED
  177715. # define PNG_FLOATING_POINT_SUPPORTED
  177716. # endif
  177717. #endif
  177718. /* If you are running on a machine where you cannot allocate more
  177719. * than 64K of memory at once, uncomment this. While libpng will not
  177720. * normally need that much memory in a chunk (unless you load up a very
  177721. * large file), zlib needs to know how big of a chunk it can use, and
  177722. * libpng thus makes sure to check any memory allocation to verify it
  177723. * will fit into memory.
  177724. #define PNG_MAX_MALLOC_64K
  177725. */
  177726. #if defined(MAXSEG_64K) && !defined(PNG_MAX_MALLOC_64K)
  177727. # define PNG_MAX_MALLOC_64K
  177728. #endif
  177729. /* Special munging to support doing things the 'cygwin' way:
  177730. * 'Normal' png-on-win32 defines/defaults:
  177731. * PNG_BUILD_DLL -- building dll
  177732. * PNG_USE_DLL -- building an application, linking to dll
  177733. * (no define) -- building static library, or building an
  177734. * application and linking to the static lib
  177735. * 'Cygwin' defines/defaults:
  177736. * PNG_BUILD_DLL -- (ignored) building the dll
  177737. * (no define) -- (ignored) building an application, linking to the dll
  177738. * PNG_STATIC -- (ignored) building the static lib, or building an
  177739. * application that links to the static lib.
  177740. * ALL_STATIC -- (ignored) building various static libs, or building an
  177741. * application that links to the static libs.
  177742. * Thus,
  177743. * a cygwin user should define either PNG_BUILD_DLL or PNG_STATIC, and
  177744. * this bit of #ifdefs will define the 'correct' config variables based on
  177745. * that. If a cygwin user *wants* to define 'PNG_USE_DLL' that's okay, but
  177746. * unnecessary.
  177747. *
  177748. * Also, the precedence order is:
  177749. * ALL_STATIC (since we can't #undef something outside our namespace)
  177750. * PNG_BUILD_DLL
  177751. * PNG_STATIC
  177752. * (nothing) == PNG_USE_DLL
  177753. *
  177754. * CYGWIN (2002-01-20): The preceding is now obsolete. With the advent
  177755. * of auto-import in binutils, we no longer need to worry about
  177756. * __declspec(dllexport) / __declspec(dllimport) and friends. Therefore,
  177757. * we don't need to worry about PNG_STATIC or ALL_STATIC when it comes
  177758. * to __declspec() stuff. However, we DO need to worry about
  177759. * PNG_BUILD_DLL and PNG_STATIC because those change some defaults
  177760. * such as CONSOLE_IO and whether GLOBAL_ARRAYS are allowed.
  177761. */
  177762. #if defined(__CYGWIN__)
  177763. # if defined(ALL_STATIC)
  177764. # if defined(PNG_BUILD_DLL)
  177765. # undef PNG_BUILD_DLL
  177766. # endif
  177767. # if defined(PNG_USE_DLL)
  177768. # undef PNG_USE_DLL
  177769. # endif
  177770. # if defined(PNG_DLL)
  177771. # undef PNG_DLL
  177772. # endif
  177773. # if !defined(PNG_STATIC)
  177774. # define PNG_STATIC
  177775. # endif
  177776. # else
  177777. # if defined (PNG_BUILD_DLL)
  177778. # if defined(PNG_STATIC)
  177779. # undef PNG_STATIC
  177780. # endif
  177781. # if defined(PNG_USE_DLL)
  177782. # undef PNG_USE_DLL
  177783. # endif
  177784. # if !defined(PNG_DLL)
  177785. # define PNG_DLL
  177786. # endif
  177787. # else
  177788. # if defined(PNG_STATIC)
  177789. # if defined(PNG_USE_DLL)
  177790. # undef PNG_USE_DLL
  177791. # endif
  177792. # if defined(PNG_DLL)
  177793. # undef PNG_DLL
  177794. # endif
  177795. # else
  177796. # if !defined(PNG_USE_DLL)
  177797. # define PNG_USE_DLL
  177798. # endif
  177799. # if !defined(PNG_DLL)
  177800. # define PNG_DLL
  177801. # endif
  177802. # endif
  177803. # endif
  177804. # endif
  177805. #endif
  177806. /* This protects us against compilers that run on a windowing system
  177807. * and thus don't have or would rather us not use the stdio types:
  177808. * stdin, stdout, and stderr. The only one currently used is stderr
  177809. * in png_error() and png_warning(). #defining PNG_NO_CONSOLE_IO will
  177810. * prevent these from being compiled and used. #defining PNG_NO_STDIO
  177811. * will also prevent these, plus will prevent the entire set of stdio
  177812. * macros and functions (FILE *, printf, etc.) from being compiled and used,
  177813. * unless (PNG_DEBUG > 0) has been #defined.
  177814. *
  177815. * #define PNG_NO_CONSOLE_IO
  177816. * #define PNG_NO_STDIO
  177817. */
  177818. #if defined(_WIN32_WCE)
  177819. # include <windows.h>
  177820. /* Console I/O functions are not supported on WindowsCE */
  177821. # define PNG_NO_CONSOLE_IO
  177822. # ifdef PNG_DEBUG
  177823. # undef PNG_DEBUG
  177824. # endif
  177825. #endif
  177826. #ifdef PNG_BUILD_DLL
  177827. # ifndef PNG_CONSOLE_IO_SUPPORTED
  177828. # ifndef PNG_NO_CONSOLE_IO
  177829. # define PNG_NO_CONSOLE_IO
  177830. # endif
  177831. # endif
  177832. #endif
  177833. # ifdef PNG_NO_STDIO
  177834. # ifndef PNG_NO_CONSOLE_IO
  177835. # define PNG_NO_CONSOLE_IO
  177836. # endif
  177837. # ifdef PNG_DEBUG
  177838. # if (PNG_DEBUG > 0)
  177839. # include <stdio.h>
  177840. # endif
  177841. # endif
  177842. # else
  177843. # if !defined(_WIN32_WCE)
  177844. /* "stdio.h" functions are not supported on WindowsCE */
  177845. # include <stdio.h>
  177846. # endif
  177847. # endif
  177848. /* This macro protects us against machines that don't have function
  177849. * prototypes (ie K&R style headers). If your compiler does not handle
  177850. * function prototypes, define this macro and use the included ansi2knr.
  177851. * I've always been able to use _NO_PROTO as the indicator, but you may
  177852. * need to drag the empty declaration out in front of here, or change the
  177853. * ifdef to suit your own needs.
  177854. */
  177855. #ifndef PNGARG
  177856. #ifdef OF /* zlib prototype munger */
  177857. # define PNGARG(arglist) OF(arglist)
  177858. #else
  177859. #ifdef _NO_PROTO
  177860. # define PNGARG(arglist) ()
  177861. # ifndef PNG_TYPECAST_NULL
  177862. # define PNG_TYPECAST_NULL
  177863. # endif
  177864. #else
  177865. # define PNGARG(arglist) arglist
  177866. #endif /* _NO_PROTO */
  177867. #endif /* OF */
  177868. #endif /* PNGARG */
  177869. /* Try to determine if we are compiling on a Mac. Note that testing for
  177870. * just __MWERKS__ is not good enough, because the Codewarrior is now used
  177871. * on non-Mac platforms.
  177872. */
  177873. #ifndef MACOS
  177874. # if (defined(__MWERKS__) && defined(macintosh)) || defined(applec) || \
  177875. defined(THINK_C) || defined(__SC__) || defined(TARGET_OS_MAC)
  177876. # define MACOS
  177877. # endif
  177878. #endif
  177879. /* enough people need this for various reasons to include it here */
  177880. #if !defined(MACOS) && !defined(RISCOS) && !defined(_WIN32_WCE)
  177881. # include <sys/types.h>
  177882. #endif
  177883. #if !defined(PNG_SETJMP_NOT_SUPPORTED) && !defined(PNG_NO_SETJMP_SUPPORTED)
  177884. # define PNG_SETJMP_SUPPORTED
  177885. #endif
  177886. #ifdef PNG_SETJMP_SUPPORTED
  177887. /* This is an attempt to force a single setjmp behaviour on Linux. If
  177888. * the X config stuff didn't define _BSD_SOURCE we wouldn't need this.
  177889. */
  177890. # ifdef __linux__
  177891. # ifdef _BSD_SOURCE
  177892. # define PNG_SAVE_BSD_SOURCE
  177893. # undef _BSD_SOURCE
  177894. # endif
  177895. # ifdef _SETJMP_H
  177896. /* If you encounter a compiler error here, see the explanation
  177897. * near the end of INSTALL.
  177898. */
  177899. __png.h__ already includes setjmp.h;
  177900. __dont__ include it again.;
  177901. # endif
  177902. # endif /* __linux__ */
  177903. /* include setjmp.h for error handling */
  177904. # include <setjmp.h>
  177905. # ifdef __linux__
  177906. # ifdef PNG_SAVE_BSD_SOURCE
  177907. # define _BSD_SOURCE
  177908. # undef PNG_SAVE_BSD_SOURCE
  177909. # endif
  177910. # endif /* __linux__ */
  177911. #endif /* PNG_SETJMP_SUPPORTED */
  177912. #ifdef BSD
  177913. #if ! JUCE_MAC
  177914. # include <strings.h>
  177915. #endif
  177916. #else
  177917. # include <string.h>
  177918. #endif
  177919. /* Other defines for things like memory and the like can go here. */
  177920. #ifdef PNG_INTERNAL
  177921. #include <stdlib.h>
  177922. /* The functions exported by PNG_EXTERN are PNG_INTERNAL functions, which
  177923. * aren't usually used outside the library (as far as I know), so it is
  177924. * debatable if they should be exported at all. In the future, when it is
  177925. * possible to have run-time registry of chunk-handling functions, some of
  177926. * these will be made available again.
  177927. #define PNG_EXTERN extern
  177928. */
  177929. #define PNG_EXTERN
  177930. /* Other defines specific to compilers can go here. Try to keep
  177931. * them inside an appropriate ifdef/endif pair for portability.
  177932. */
  177933. #if defined(PNG_FLOATING_POINT_SUPPORTED)
  177934. # if defined(MACOS)
  177935. /* We need to check that <math.h> hasn't already been included earlier
  177936. * as it seems it doesn't agree with <fp.h>, yet we should really use
  177937. * <fp.h> if possible.
  177938. */
  177939. # if !defined(__MATH_H__) && !defined(__MATH_H) && !defined(__cmath__)
  177940. # include <fp.h>
  177941. # endif
  177942. # else
  177943. # include <math.h>
  177944. # endif
  177945. # if defined(_AMIGA) && defined(__SASC) && defined(_M68881)
  177946. /* Amiga SAS/C: We must include builtin FPU functions when compiling using
  177947. * MATH=68881
  177948. */
  177949. # include <m68881.h>
  177950. # endif
  177951. #endif
  177952. /* Codewarrior on NT has linking problems without this. */
  177953. #if (defined(__MWERKS__) && defined(WIN32)) || defined(__STDC__)
  177954. # define PNG_ALWAYS_EXTERN
  177955. #endif
  177956. /* This provides the non-ANSI (far) memory allocation routines. */
  177957. #if defined(__TURBOC__) && defined(__MSDOS__)
  177958. # include <mem.h>
  177959. # include <alloc.h>
  177960. #endif
  177961. /* I have no idea why is this necessary... */
  177962. #if defined(_MSC_VER) && (defined(WIN32) || defined(_Windows) || \
  177963. defined(_WINDOWS) || defined(_WIN32) || defined(__WIN32__))
  177964. # include <malloc.h>
  177965. #endif
  177966. /* This controls how fine the dithering gets. As this allocates
  177967. * a largish chunk of memory (32K), those who are not as concerned
  177968. * with dithering quality can decrease some or all of these.
  177969. */
  177970. #ifndef PNG_DITHER_RED_BITS
  177971. # define PNG_DITHER_RED_BITS 5
  177972. #endif
  177973. #ifndef PNG_DITHER_GREEN_BITS
  177974. # define PNG_DITHER_GREEN_BITS 5
  177975. #endif
  177976. #ifndef PNG_DITHER_BLUE_BITS
  177977. # define PNG_DITHER_BLUE_BITS 5
  177978. #endif
  177979. /* This controls how fine the gamma correction becomes when you
  177980. * are only interested in 8 bits anyway. Increasing this value
  177981. * results in more memory being used, and more pow() functions
  177982. * being called to fill in the gamma tables. Don't set this value
  177983. * less then 8, and even that may not work (I haven't tested it).
  177984. */
  177985. #ifndef PNG_MAX_GAMMA_8
  177986. # define PNG_MAX_GAMMA_8 11
  177987. #endif
  177988. /* This controls how much a difference in gamma we can tolerate before
  177989. * we actually start doing gamma conversion.
  177990. */
  177991. #ifndef PNG_GAMMA_THRESHOLD
  177992. # define PNG_GAMMA_THRESHOLD 0.05
  177993. #endif
  177994. #endif /* PNG_INTERNAL */
  177995. /* The following uses const char * instead of char * for error
  177996. * and warning message functions, so some compilers won't complain.
  177997. * If you do not want to use const, define PNG_NO_CONST here.
  177998. */
  177999. #ifndef PNG_NO_CONST
  178000. # define PNG_CONST const
  178001. #else
  178002. # define PNG_CONST
  178003. #endif
  178004. /* The following defines give you the ability to remove code from the
  178005. * library that you will not be using. I wish I could figure out how to
  178006. * automate this, but I can't do that without making it seriously hard
  178007. * on the users. So if you are not using an ability, change the #define
  178008. * to and #undef, and that part of the library will not be compiled. If
  178009. * your linker can't find a function, you may want to make sure the
  178010. * ability is defined here. Some of these depend upon some others being
  178011. * defined. I haven't figured out all the interactions here, so you may
  178012. * have to experiment awhile to get everything to compile. If you are
  178013. * creating or using a shared library, you probably shouldn't touch this,
  178014. * as it will affect the size of the structures, and this will cause bad
  178015. * things to happen if the library and/or application ever change.
  178016. */
  178017. /* Any features you will not be using can be undef'ed here */
  178018. /* GR-P, 0.96a: Set "*TRANSFORMS_SUPPORTED as default but allow user
  178019. * to turn it off with "*TRANSFORMS_NOT_SUPPORTED" or *PNG_NO_*_TRANSFORMS
  178020. * on the compile line, then pick and choose which ones to define without
  178021. * having to edit this file. It is safe to use the *TRANSFORMS_NOT_SUPPORTED
  178022. * if you only want to have a png-compliant reader/writer but don't need
  178023. * any of the extra transformations. This saves about 80 kbytes in a
  178024. * typical installation of the library. (PNG_NO_* form added in version
  178025. * 1.0.1c, for consistency)
  178026. */
  178027. /* The size of the png_text structure changed in libpng-1.0.6 when
  178028. * iTXt support was added. iTXt support was turned off by default through
  178029. * libpng-1.2.x, to support old apps that malloc the png_text structure
  178030. * instead of calling png_set_text() and letting libpng malloc it. It
  178031. * was turned on by default in libpng-1.3.0.
  178032. */
  178033. #if defined(PNG_1_0_X) || defined (PNG_1_2_X)
  178034. # ifndef PNG_NO_iTXt_SUPPORTED
  178035. # define PNG_NO_iTXt_SUPPORTED
  178036. # endif
  178037. # ifndef PNG_NO_READ_iTXt
  178038. # define PNG_NO_READ_iTXt
  178039. # endif
  178040. # ifndef PNG_NO_WRITE_iTXt
  178041. # define PNG_NO_WRITE_iTXt
  178042. # endif
  178043. #endif
  178044. #if !defined(PNG_NO_iTXt_SUPPORTED)
  178045. # if !defined(PNG_READ_iTXt_SUPPORTED) && !defined(PNG_NO_READ_iTXt)
  178046. # define PNG_READ_iTXt
  178047. # endif
  178048. # if !defined(PNG_WRITE_iTXt_SUPPORTED) && !defined(PNG_NO_WRITE_iTXt)
  178049. # define PNG_WRITE_iTXt
  178050. # endif
  178051. #endif
  178052. /* The following support, added after version 1.0.0, can be turned off here en
  178053. * masse by defining PNG_LEGACY_SUPPORTED in case you need binary compatibility
  178054. * with old applications that require the length of png_struct and png_info
  178055. * to remain unchanged.
  178056. */
  178057. #ifdef PNG_LEGACY_SUPPORTED
  178058. # define PNG_NO_FREE_ME
  178059. # define PNG_NO_READ_UNKNOWN_CHUNKS
  178060. # define PNG_NO_WRITE_UNKNOWN_CHUNKS
  178061. # define PNG_NO_READ_USER_CHUNKS
  178062. # define PNG_NO_READ_iCCP
  178063. # define PNG_NO_WRITE_iCCP
  178064. # define PNG_NO_READ_iTXt
  178065. # define PNG_NO_WRITE_iTXt
  178066. # define PNG_NO_READ_sCAL
  178067. # define PNG_NO_WRITE_sCAL
  178068. # define PNG_NO_READ_sPLT
  178069. # define PNG_NO_WRITE_sPLT
  178070. # define PNG_NO_INFO_IMAGE
  178071. # define PNG_NO_READ_RGB_TO_GRAY
  178072. # define PNG_NO_READ_USER_TRANSFORM
  178073. # define PNG_NO_WRITE_USER_TRANSFORM
  178074. # define PNG_NO_USER_MEM
  178075. # define PNG_NO_READ_EMPTY_PLTE
  178076. # define PNG_NO_MNG_FEATURES
  178077. # define PNG_NO_FIXED_POINT_SUPPORTED
  178078. #endif
  178079. /* Ignore attempt to turn off both floating and fixed point support */
  178080. #if !defined(PNG_FLOATING_POINT_SUPPORTED) || \
  178081. !defined(PNG_NO_FIXED_POINT_SUPPORTED)
  178082. # define PNG_FIXED_POINT_SUPPORTED
  178083. #endif
  178084. #ifndef PNG_NO_FREE_ME
  178085. # define PNG_FREE_ME_SUPPORTED
  178086. #endif
  178087. #if defined(PNG_READ_SUPPORTED)
  178088. #if !defined(PNG_READ_TRANSFORMS_NOT_SUPPORTED) && \
  178089. !defined(PNG_NO_READ_TRANSFORMS)
  178090. # define PNG_READ_TRANSFORMS_SUPPORTED
  178091. #endif
  178092. #ifdef PNG_READ_TRANSFORMS_SUPPORTED
  178093. # ifndef PNG_NO_READ_EXPAND
  178094. # define PNG_READ_EXPAND_SUPPORTED
  178095. # endif
  178096. # ifndef PNG_NO_READ_SHIFT
  178097. # define PNG_READ_SHIFT_SUPPORTED
  178098. # endif
  178099. # ifndef PNG_NO_READ_PACK
  178100. # define PNG_READ_PACK_SUPPORTED
  178101. # endif
  178102. # ifndef PNG_NO_READ_BGR
  178103. # define PNG_READ_BGR_SUPPORTED
  178104. # endif
  178105. # ifndef PNG_NO_READ_SWAP
  178106. # define PNG_READ_SWAP_SUPPORTED
  178107. # endif
  178108. # ifndef PNG_NO_READ_PACKSWAP
  178109. # define PNG_READ_PACKSWAP_SUPPORTED
  178110. # endif
  178111. # ifndef PNG_NO_READ_INVERT
  178112. # define PNG_READ_INVERT_SUPPORTED
  178113. # endif
  178114. # ifndef PNG_NO_READ_DITHER
  178115. # define PNG_READ_DITHER_SUPPORTED
  178116. # endif
  178117. # ifndef PNG_NO_READ_BACKGROUND
  178118. # define PNG_READ_BACKGROUND_SUPPORTED
  178119. # endif
  178120. # ifndef PNG_NO_READ_16_TO_8
  178121. # define PNG_READ_16_TO_8_SUPPORTED
  178122. # endif
  178123. # ifndef PNG_NO_READ_FILLER
  178124. # define PNG_READ_FILLER_SUPPORTED
  178125. # endif
  178126. # ifndef PNG_NO_READ_GAMMA
  178127. # define PNG_READ_GAMMA_SUPPORTED
  178128. # endif
  178129. # ifndef PNG_NO_READ_GRAY_TO_RGB
  178130. # define PNG_READ_GRAY_TO_RGB_SUPPORTED
  178131. # endif
  178132. # ifndef PNG_NO_READ_SWAP_ALPHA
  178133. # define PNG_READ_SWAP_ALPHA_SUPPORTED
  178134. # endif
  178135. # ifndef PNG_NO_READ_INVERT_ALPHA
  178136. # define PNG_READ_INVERT_ALPHA_SUPPORTED
  178137. # endif
  178138. # ifndef PNG_NO_READ_STRIP_ALPHA
  178139. # define PNG_READ_STRIP_ALPHA_SUPPORTED
  178140. # endif
  178141. # ifndef PNG_NO_READ_USER_TRANSFORM
  178142. # define PNG_READ_USER_TRANSFORM_SUPPORTED
  178143. # endif
  178144. # ifndef PNG_NO_READ_RGB_TO_GRAY
  178145. # define PNG_READ_RGB_TO_GRAY_SUPPORTED
  178146. # endif
  178147. #endif /* PNG_READ_TRANSFORMS_SUPPORTED */
  178148. #if !defined(PNG_NO_PROGRESSIVE_READ) && \
  178149. !defined(PNG_PROGRESSIVE_READ_SUPPORTED) /* if you don't do progressive */
  178150. # define PNG_PROGRESSIVE_READ_SUPPORTED /* reading. This is not talking */
  178151. #endif /* about interlacing capability! You'll */
  178152. /* still have interlacing unless you change the following line: */
  178153. #define PNG_READ_INTERLACING_SUPPORTED /* required in PNG-compliant decoders */
  178154. #ifndef PNG_NO_READ_COMPOSITE_NODIV
  178155. # ifndef PNG_NO_READ_COMPOSITED_NODIV /* libpng-1.0.x misspelling */
  178156. # define PNG_READ_COMPOSITE_NODIV_SUPPORTED /* well tested on Intel, SGI */
  178157. # endif
  178158. #endif
  178159. #if defined(PNG_1_0_X) || defined (PNG_1_2_X)
  178160. /* Deprecated, will be removed from version 2.0.0.
  178161. Use PNG_MNG_FEATURES_SUPPORTED instead. */
  178162. #ifndef PNG_NO_READ_EMPTY_PLTE
  178163. # define PNG_READ_EMPTY_PLTE_SUPPORTED
  178164. #endif
  178165. #endif
  178166. #endif /* PNG_READ_SUPPORTED */
  178167. #if defined(PNG_WRITE_SUPPORTED)
  178168. # if !defined(PNG_WRITE_TRANSFORMS_NOT_SUPPORTED) && \
  178169. !defined(PNG_NO_WRITE_TRANSFORMS)
  178170. # define PNG_WRITE_TRANSFORMS_SUPPORTED
  178171. #endif
  178172. #ifdef PNG_WRITE_TRANSFORMS_SUPPORTED
  178173. # ifndef PNG_NO_WRITE_SHIFT
  178174. # define PNG_WRITE_SHIFT_SUPPORTED
  178175. # endif
  178176. # ifndef PNG_NO_WRITE_PACK
  178177. # define PNG_WRITE_PACK_SUPPORTED
  178178. # endif
  178179. # ifndef PNG_NO_WRITE_BGR
  178180. # define PNG_WRITE_BGR_SUPPORTED
  178181. # endif
  178182. # ifndef PNG_NO_WRITE_SWAP
  178183. # define PNG_WRITE_SWAP_SUPPORTED
  178184. # endif
  178185. # ifndef PNG_NO_WRITE_PACKSWAP
  178186. # define PNG_WRITE_PACKSWAP_SUPPORTED
  178187. # endif
  178188. # ifndef PNG_NO_WRITE_INVERT
  178189. # define PNG_WRITE_INVERT_SUPPORTED
  178190. # endif
  178191. # ifndef PNG_NO_WRITE_FILLER
  178192. # define PNG_WRITE_FILLER_SUPPORTED /* same as WRITE_STRIP_ALPHA */
  178193. # endif
  178194. # ifndef PNG_NO_WRITE_SWAP_ALPHA
  178195. # define PNG_WRITE_SWAP_ALPHA_SUPPORTED
  178196. # endif
  178197. # ifndef PNG_NO_WRITE_INVERT_ALPHA
  178198. # define PNG_WRITE_INVERT_ALPHA_SUPPORTED
  178199. # endif
  178200. # ifndef PNG_NO_WRITE_USER_TRANSFORM
  178201. # define PNG_WRITE_USER_TRANSFORM_SUPPORTED
  178202. # endif
  178203. #endif /* PNG_WRITE_TRANSFORMS_SUPPORTED */
  178204. #if !defined(PNG_NO_WRITE_INTERLACING_SUPPORTED) && \
  178205. !defined(PNG_WRITE_INTERLACING_SUPPORTED)
  178206. #define PNG_WRITE_INTERLACING_SUPPORTED /* not required for PNG-compliant
  178207. encoders, but can cause trouble
  178208. if left undefined */
  178209. #endif
  178210. #if !defined(PNG_NO_WRITE_WEIGHTED_FILTER) && \
  178211. !defined(PNG_WRITE_WEIGHTED_FILTER) && \
  178212. defined(PNG_FLOATING_POINT_SUPPORTED)
  178213. # define PNG_WRITE_WEIGHTED_FILTER_SUPPORTED
  178214. #endif
  178215. #ifndef PNG_NO_WRITE_FLUSH
  178216. # define PNG_WRITE_FLUSH_SUPPORTED
  178217. #endif
  178218. #if defined(PNG_1_0_X) || defined (PNG_1_2_X)
  178219. /* Deprecated, see PNG_MNG_FEATURES_SUPPORTED, above */
  178220. #ifndef PNG_NO_WRITE_EMPTY_PLTE
  178221. # define PNG_WRITE_EMPTY_PLTE_SUPPORTED
  178222. #endif
  178223. #endif
  178224. #endif /* PNG_WRITE_SUPPORTED */
  178225. #ifndef PNG_1_0_X
  178226. # ifndef PNG_NO_ERROR_NUMBERS
  178227. # define PNG_ERROR_NUMBERS_SUPPORTED
  178228. # endif
  178229. #endif /* PNG_1_0_X */
  178230. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED) || \
  178231. defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED)
  178232. # ifndef PNG_NO_USER_TRANSFORM_PTR
  178233. # define PNG_USER_TRANSFORM_PTR_SUPPORTED
  178234. # endif
  178235. #endif
  178236. #ifndef PNG_NO_STDIO
  178237. # define PNG_TIME_RFC1123_SUPPORTED
  178238. #endif
  178239. /* This adds extra functions in pngget.c for accessing data from the
  178240. * info pointer (added in version 0.99)
  178241. * png_get_image_width()
  178242. * png_get_image_height()
  178243. * png_get_bit_depth()
  178244. * png_get_color_type()
  178245. * png_get_compression_type()
  178246. * png_get_filter_type()
  178247. * png_get_interlace_type()
  178248. * png_get_pixel_aspect_ratio()
  178249. * png_get_pixels_per_meter()
  178250. * png_get_x_offset_pixels()
  178251. * png_get_y_offset_pixels()
  178252. * png_get_x_offset_microns()
  178253. * png_get_y_offset_microns()
  178254. */
  178255. #if !defined(PNG_NO_EASY_ACCESS) && !defined(PNG_EASY_ACCESS_SUPPORTED)
  178256. # define PNG_EASY_ACCESS_SUPPORTED
  178257. #endif
  178258. /* PNG_ASSEMBLER_CODE was enabled by default in version 1.2.0
  178259. * and removed from version 1.2.20. The following will be removed
  178260. * from libpng-1.4.0
  178261. */
  178262. #if defined(PNG_READ_SUPPORTED) && !defined(PNG_NO_OPTIMIZED_CODE)
  178263. # ifndef PNG_OPTIMIZED_CODE_SUPPORTED
  178264. # define PNG_OPTIMIZED_CODE_SUPPORTED
  178265. # endif
  178266. #endif
  178267. #if defined(PNG_READ_SUPPORTED) && !defined(PNG_NO_ASSEMBLER_CODE)
  178268. # ifndef PNG_ASSEMBLER_CODE_SUPPORTED
  178269. # define PNG_ASSEMBLER_CODE_SUPPORTED
  178270. # endif
  178271. # if defined(__GNUC__) && defined(__x86_64__) && (__GNUC__ < 4)
  178272. /* work around 64-bit gcc compiler bugs in gcc-3.x */
  178273. # if !defined(PNG_MMX_CODE_SUPPORTED) && !defined(PNG_NO_MMX_CODE)
  178274. # define PNG_NO_MMX_CODE
  178275. # endif
  178276. # endif
  178277. # if defined(__APPLE__)
  178278. # if !defined(PNG_MMX_CODE_SUPPORTED) && !defined(PNG_NO_MMX_CODE)
  178279. # define PNG_NO_MMX_CODE
  178280. # endif
  178281. # endif
  178282. # if (defined(__MWERKS__) && ((__MWERKS__ < 0x0900) || macintosh))
  178283. # if !defined(PNG_MMX_CODE_SUPPORTED) && !defined(PNG_NO_MMX_CODE)
  178284. # define PNG_NO_MMX_CODE
  178285. # endif
  178286. # endif
  178287. # if !defined(PNG_MMX_CODE_SUPPORTED) && !defined(PNG_NO_MMX_CODE)
  178288. # define PNG_MMX_CODE_SUPPORTED
  178289. # endif
  178290. #endif
  178291. /* end of obsolete code to be removed from libpng-1.4.0 */
  178292. #if !defined(PNG_1_0_X)
  178293. #if !defined(PNG_NO_USER_MEM) && !defined(PNG_USER_MEM_SUPPORTED)
  178294. # define PNG_USER_MEM_SUPPORTED
  178295. #endif
  178296. #endif /* PNG_1_0_X */
  178297. /* Added at libpng-1.2.6 */
  178298. #if !defined(PNG_1_0_X)
  178299. #ifndef PNG_SET_USER_LIMITS_SUPPORTED
  178300. #if !defined(PNG_NO_SET_USER_LIMITS) && !defined(PNG_SET_USER_LIMITS_SUPPORTED)
  178301. # define PNG_SET_USER_LIMITS_SUPPORTED
  178302. #endif
  178303. #endif
  178304. #endif /* PNG_1_0_X */
  178305. /* Added at libpng-1.0.16 and 1.2.6. To accept all valid PNGS no matter
  178306. * how large, set these limits to 0x7fffffffL
  178307. */
  178308. #ifndef PNG_USER_WIDTH_MAX
  178309. # define PNG_USER_WIDTH_MAX 1000000L
  178310. #endif
  178311. #ifndef PNG_USER_HEIGHT_MAX
  178312. # define PNG_USER_HEIGHT_MAX 1000000L
  178313. #endif
  178314. /* These are currently experimental features, define them if you want */
  178315. /* very little testing */
  178316. /*
  178317. #ifdef PNG_READ_SUPPORTED
  178318. # ifndef PNG_READ_16_TO_8_ACCURATE_SCALE_SUPPORTED
  178319. # define PNG_READ_16_TO_8_ACCURATE_SCALE_SUPPORTED
  178320. # endif
  178321. #endif
  178322. */
  178323. /* This is only for PowerPC big-endian and 680x0 systems */
  178324. /* some testing */
  178325. /*
  178326. #ifndef PNG_READ_BIG_ENDIAN_SUPPORTED
  178327. # define PNG_READ_BIG_ENDIAN_SUPPORTED
  178328. #endif
  178329. */
  178330. /* Buggy compilers (e.g., gcc 2.7.2.2) need this */
  178331. /*
  178332. #define PNG_NO_POINTER_INDEXING
  178333. */
  178334. /* These functions are turned off by default, as they will be phased out. */
  178335. /*
  178336. #define PNG_USELESS_TESTS_SUPPORTED
  178337. #define PNG_CORRECT_PALETTE_SUPPORTED
  178338. */
  178339. /* Any chunks you are not interested in, you can undef here. The
  178340. * ones that allocate memory may be expecially important (hIST,
  178341. * tEXt, zTXt, tRNS, pCAL). Others will just save time and make png_info
  178342. * a bit smaller.
  178343. */
  178344. #if defined(PNG_READ_SUPPORTED) && \
  178345. !defined(PNG_READ_ANCILLARY_CHUNKS_NOT_SUPPORTED) && \
  178346. !defined(PNG_NO_READ_ANCILLARY_CHUNKS)
  178347. # define PNG_READ_ANCILLARY_CHUNKS_SUPPORTED
  178348. #endif
  178349. #if defined(PNG_WRITE_SUPPORTED) && \
  178350. !defined(PNG_WRITE_ANCILLARY_CHUNKS_NOT_SUPPORTED) && \
  178351. !defined(PNG_NO_WRITE_ANCILLARY_CHUNKS)
  178352. # define PNG_WRITE_ANCILLARY_CHUNKS_SUPPORTED
  178353. #endif
  178354. #ifdef PNG_READ_ANCILLARY_CHUNKS_SUPPORTED
  178355. #ifdef PNG_NO_READ_TEXT
  178356. # define PNG_NO_READ_iTXt
  178357. # define PNG_NO_READ_tEXt
  178358. # define PNG_NO_READ_zTXt
  178359. #endif
  178360. #ifndef PNG_NO_READ_bKGD
  178361. # define PNG_READ_bKGD_SUPPORTED
  178362. # define PNG_bKGD_SUPPORTED
  178363. #endif
  178364. #ifndef PNG_NO_READ_cHRM
  178365. # define PNG_READ_cHRM_SUPPORTED
  178366. # define PNG_cHRM_SUPPORTED
  178367. #endif
  178368. #ifndef PNG_NO_READ_gAMA
  178369. # define PNG_READ_gAMA_SUPPORTED
  178370. # define PNG_gAMA_SUPPORTED
  178371. #endif
  178372. #ifndef PNG_NO_READ_hIST
  178373. # define PNG_READ_hIST_SUPPORTED
  178374. # define PNG_hIST_SUPPORTED
  178375. #endif
  178376. #ifndef PNG_NO_READ_iCCP
  178377. # define PNG_READ_iCCP_SUPPORTED
  178378. # define PNG_iCCP_SUPPORTED
  178379. #endif
  178380. #ifndef PNG_NO_READ_iTXt
  178381. # ifndef PNG_READ_iTXt_SUPPORTED
  178382. # define PNG_READ_iTXt_SUPPORTED
  178383. # endif
  178384. # ifndef PNG_iTXt_SUPPORTED
  178385. # define PNG_iTXt_SUPPORTED
  178386. # endif
  178387. #endif
  178388. #ifndef PNG_NO_READ_oFFs
  178389. # define PNG_READ_oFFs_SUPPORTED
  178390. # define PNG_oFFs_SUPPORTED
  178391. #endif
  178392. #ifndef PNG_NO_READ_pCAL
  178393. # define PNG_READ_pCAL_SUPPORTED
  178394. # define PNG_pCAL_SUPPORTED
  178395. #endif
  178396. #ifndef PNG_NO_READ_sCAL
  178397. # define PNG_READ_sCAL_SUPPORTED
  178398. # define PNG_sCAL_SUPPORTED
  178399. #endif
  178400. #ifndef PNG_NO_READ_pHYs
  178401. # define PNG_READ_pHYs_SUPPORTED
  178402. # define PNG_pHYs_SUPPORTED
  178403. #endif
  178404. #ifndef PNG_NO_READ_sBIT
  178405. # define PNG_READ_sBIT_SUPPORTED
  178406. # define PNG_sBIT_SUPPORTED
  178407. #endif
  178408. #ifndef PNG_NO_READ_sPLT
  178409. # define PNG_READ_sPLT_SUPPORTED
  178410. # define PNG_sPLT_SUPPORTED
  178411. #endif
  178412. #ifndef PNG_NO_READ_sRGB
  178413. # define PNG_READ_sRGB_SUPPORTED
  178414. # define PNG_sRGB_SUPPORTED
  178415. #endif
  178416. #ifndef PNG_NO_READ_tEXt
  178417. # define PNG_READ_tEXt_SUPPORTED
  178418. # define PNG_tEXt_SUPPORTED
  178419. #endif
  178420. #ifndef PNG_NO_READ_tIME
  178421. # define PNG_READ_tIME_SUPPORTED
  178422. # define PNG_tIME_SUPPORTED
  178423. #endif
  178424. #ifndef PNG_NO_READ_tRNS
  178425. # define PNG_READ_tRNS_SUPPORTED
  178426. # define PNG_tRNS_SUPPORTED
  178427. #endif
  178428. #ifndef PNG_NO_READ_zTXt
  178429. # define PNG_READ_zTXt_SUPPORTED
  178430. # define PNG_zTXt_SUPPORTED
  178431. #endif
  178432. #ifndef PNG_NO_READ_UNKNOWN_CHUNKS
  178433. # define PNG_READ_UNKNOWN_CHUNKS_SUPPORTED
  178434. # ifndef PNG_UNKNOWN_CHUNKS_SUPPORTED
  178435. # define PNG_UNKNOWN_CHUNKS_SUPPORTED
  178436. # endif
  178437. # ifndef PNG_NO_HANDLE_AS_UNKNOWN
  178438. # define PNG_HANDLE_AS_UNKNOWN_SUPPORTED
  178439. # endif
  178440. #endif
  178441. #if !defined(PNG_NO_READ_USER_CHUNKS) && \
  178442. defined(PNG_READ_UNKNOWN_CHUNKS_SUPPORTED)
  178443. # define PNG_READ_USER_CHUNKS_SUPPORTED
  178444. # define PNG_USER_CHUNKS_SUPPORTED
  178445. # ifdef PNG_NO_READ_UNKNOWN_CHUNKS
  178446. # undef PNG_NO_READ_UNKNOWN_CHUNKS
  178447. # endif
  178448. # ifdef PNG_NO_HANDLE_AS_UNKNOWN
  178449. # undef PNG_NO_HANDLE_AS_UNKNOWN
  178450. # endif
  178451. #endif
  178452. #ifndef PNG_NO_READ_OPT_PLTE
  178453. # define PNG_READ_OPT_PLTE_SUPPORTED /* only affects support of the */
  178454. #endif /* optional PLTE chunk in RGB and RGBA images */
  178455. #if defined(PNG_READ_iTXt_SUPPORTED) || defined(PNG_READ_tEXt_SUPPORTED) || \
  178456. defined(PNG_READ_zTXt_SUPPORTED)
  178457. # define PNG_READ_TEXT_SUPPORTED
  178458. # define PNG_TEXT_SUPPORTED
  178459. #endif
  178460. #endif /* PNG_READ_ANCILLARY_CHUNKS_SUPPORTED */
  178461. #ifdef PNG_WRITE_ANCILLARY_CHUNKS_SUPPORTED
  178462. #ifdef PNG_NO_WRITE_TEXT
  178463. # define PNG_NO_WRITE_iTXt
  178464. # define PNG_NO_WRITE_tEXt
  178465. # define PNG_NO_WRITE_zTXt
  178466. #endif
  178467. #ifndef PNG_NO_WRITE_bKGD
  178468. # define PNG_WRITE_bKGD_SUPPORTED
  178469. # ifndef PNG_bKGD_SUPPORTED
  178470. # define PNG_bKGD_SUPPORTED
  178471. # endif
  178472. #endif
  178473. #ifndef PNG_NO_WRITE_cHRM
  178474. # define PNG_WRITE_cHRM_SUPPORTED
  178475. # ifndef PNG_cHRM_SUPPORTED
  178476. # define PNG_cHRM_SUPPORTED
  178477. # endif
  178478. #endif
  178479. #ifndef PNG_NO_WRITE_gAMA
  178480. # define PNG_WRITE_gAMA_SUPPORTED
  178481. # ifndef PNG_gAMA_SUPPORTED
  178482. # define PNG_gAMA_SUPPORTED
  178483. # endif
  178484. #endif
  178485. #ifndef PNG_NO_WRITE_hIST
  178486. # define PNG_WRITE_hIST_SUPPORTED
  178487. # ifndef PNG_hIST_SUPPORTED
  178488. # define PNG_hIST_SUPPORTED
  178489. # endif
  178490. #endif
  178491. #ifndef PNG_NO_WRITE_iCCP
  178492. # define PNG_WRITE_iCCP_SUPPORTED
  178493. # ifndef PNG_iCCP_SUPPORTED
  178494. # define PNG_iCCP_SUPPORTED
  178495. # endif
  178496. #endif
  178497. #ifndef PNG_NO_WRITE_iTXt
  178498. # ifndef PNG_WRITE_iTXt_SUPPORTED
  178499. # define PNG_WRITE_iTXt_SUPPORTED
  178500. # endif
  178501. # ifndef PNG_iTXt_SUPPORTED
  178502. # define PNG_iTXt_SUPPORTED
  178503. # endif
  178504. #endif
  178505. #ifndef PNG_NO_WRITE_oFFs
  178506. # define PNG_WRITE_oFFs_SUPPORTED
  178507. # ifndef PNG_oFFs_SUPPORTED
  178508. # define PNG_oFFs_SUPPORTED
  178509. # endif
  178510. #endif
  178511. #ifndef PNG_NO_WRITE_pCAL
  178512. # define PNG_WRITE_pCAL_SUPPORTED
  178513. # ifndef PNG_pCAL_SUPPORTED
  178514. # define PNG_pCAL_SUPPORTED
  178515. # endif
  178516. #endif
  178517. #ifndef PNG_NO_WRITE_sCAL
  178518. # define PNG_WRITE_sCAL_SUPPORTED
  178519. # ifndef PNG_sCAL_SUPPORTED
  178520. # define PNG_sCAL_SUPPORTED
  178521. # endif
  178522. #endif
  178523. #ifndef PNG_NO_WRITE_pHYs
  178524. # define PNG_WRITE_pHYs_SUPPORTED
  178525. # ifndef PNG_pHYs_SUPPORTED
  178526. # define PNG_pHYs_SUPPORTED
  178527. # endif
  178528. #endif
  178529. #ifndef PNG_NO_WRITE_sBIT
  178530. # define PNG_WRITE_sBIT_SUPPORTED
  178531. # ifndef PNG_sBIT_SUPPORTED
  178532. # define PNG_sBIT_SUPPORTED
  178533. # endif
  178534. #endif
  178535. #ifndef PNG_NO_WRITE_sPLT
  178536. # define PNG_WRITE_sPLT_SUPPORTED
  178537. # ifndef PNG_sPLT_SUPPORTED
  178538. # define PNG_sPLT_SUPPORTED
  178539. # endif
  178540. #endif
  178541. #ifndef PNG_NO_WRITE_sRGB
  178542. # define PNG_WRITE_sRGB_SUPPORTED
  178543. # ifndef PNG_sRGB_SUPPORTED
  178544. # define PNG_sRGB_SUPPORTED
  178545. # endif
  178546. #endif
  178547. #ifndef PNG_NO_WRITE_tEXt
  178548. # define PNG_WRITE_tEXt_SUPPORTED
  178549. # ifndef PNG_tEXt_SUPPORTED
  178550. # define PNG_tEXt_SUPPORTED
  178551. # endif
  178552. #endif
  178553. #ifndef PNG_NO_WRITE_tIME
  178554. # define PNG_WRITE_tIME_SUPPORTED
  178555. # ifndef PNG_tIME_SUPPORTED
  178556. # define PNG_tIME_SUPPORTED
  178557. # endif
  178558. #endif
  178559. #ifndef PNG_NO_WRITE_tRNS
  178560. # define PNG_WRITE_tRNS_SUPPORTED
  178561. # ifndef PNG_tRNS_SUPPORTED
  178562. # define PNG_tRNS_SUPPORTED
  178563. # endif
  178564. #endif
  178565. #ifndef PNG_NO_WRITE_zTXt
  178566. # define PNG_WRITE_zTXt_SUPPORTED
  178567. # ifndef PNG_zTXt_SUPPORTED
  178568. # define PNG_zTXt_SUPPORTED
  178569. # endif
  178570. #endif
  178571. #ifndef PNG_NO_WRITE_UNKNOWN_CHUNKS
  178572. # define PNG_WRITE_UNKNOWN_CHUNKS_SUPPORTED
  178573. # ifndef PNG_UNKNOWN_CHUNKS_SUPPORTED
  178574. # define PNG_UNKNOWN_CHUNKS_SUPPORTED
  178575. # endif
  178576. # ifndef PNG_NO_HANDLE_AS_UNKNOWN
  178577. # ifndef PNG_HANDLE_AS_UNKNOWN_SUPPORTED
  178578. # define PNG_HANDLE_AS_UNKNOWN_SUPPORTED
  178579. # endif
  178580. # endif
  178581. #endif
  178582. #if defined(PNG_WRITE_iTXt_SUPPORTED) || defined(PNG_WRITE_tEXt_SUPPORTED) || \
  178583. defined(PNG_WRITE_zTXt_SUPPORTED)
  178584. # define PNG_WRITE_TEXT_SUPPORTED
  178585. # ifndef PNG_TEXT_SUPPORTED
  178586. # define PNG_TEXT_SUPPORTED
  178587. # endif
  178588. #endif
  178589. #endif /* PNG_WRITE_ANCILLARY_CHUNKS_SUPPORTED */
  178590. /* Turn this off to disable png_read_png() and
  178591. * png_write_png() and leave the row_pointers member
  178592. * out of the info structure.
  178593. */
  178594. #ifndef PNG_NO_INFO_IMAGE
  178595. # define PNG_INFO_IMAGE_SUPPORTED
  178596. #endif
  178597. /* need the time information for reading tIME chunks */
  178598. #if defined(PNG_tIME_SUPPORTED)
  178599. # if !defined(_WIN32_WCE)
  178600. /* "time.h" functions are not supported on WindowsCE */
  178601. # include <time.h>
  178602. # endif
  178603. #endif
  178604. /* Some typedefs to get us started. These should be safe on most of the
  178605. * common platforms. The typedefs should be at least as large as the
  178606. * numbers suggest (a png_uint_32 must be at least 32 bits long), but they
  178607. * don't have to be exactly that size. Some compilers dislike passing
  178608. * unsigned shorts as function parameters, so you may be better off using
  178609. * unsigned int for png_uint_16. Likewise, for 64-bit systems, you may
  178610. * want to have unsigned int for png_uint_32 instead of unsigned long.
  178611. */
  178612. typedef unsigned long png_uint_32;
  178613. typedef long png_int_32;
  178614. typedef unsigned short png_uint_16;
  178615. typedef short png_int_16;
  178616. typedef unsigned char png_byte;
  178617. /* This is usually size_t. It is typedef'ed just in case you need it to
  178618. change (I'm not sure if you will or not, so I thought I'd be safe) */
  178619. #ifdef PNG_SIZE_T
  178620. typedef PNG_SIZE_T png_size_t;
  178621. # define png_sizeof(x) png_convert_size(sizeof (x))
  178622. #else
  178623. typedef size_t png_size_t;
  178624. # define png_sizeof(x) sizeof (x)
  178625. #endif
  178626. /* The following is needed for medium model support. It cannot be in the
  178627. * PNG_INTERNAL section. Needs modification for other compilers besides
  178628. * MSC. Model independent support declares all arrays and pointers to be
  178629. * large using the far keyword. The zlib version used must also support
  178630. * model independent data. As of version zlib 1.0.4, the necessary changes
  178631. * have been made in zlib. The USE_FAR_KEYWORD define triggers other
  178632. * changes that are needed. (Tim Wegner)
  178633. */
  178634. /* Separate compiler dependencies (problem here is that zlib.h always
  178635. defines FAR. (SJT) */
  178636. #ifdef __BORLANDC__
  178637. # if defined(__LARGE__) || defined(__HUGE__) || defined(__COMPACT__)
  178638. # define LDATA 1
  178639. # else
  178640. # define LDATA 0
  178641. # endif
  178642. /* GRR: why is Cygwin in here? Cygwin is not Borland C... */
  178643. # if !defined(__WIN32__) && !defined(__FLAT__) && !defined(__CYGWIN__)
  178644. # define PNG_MAX_MALLOC_64K
  178645. # if (LDATA != 1)
  178646. # ifndef FAR
  178647. # define FAR __far
  178648. # endif
  178649. # define USE_FAR_KEYWORD
  178650. # endif /* LDATA != 1 */
  178651. /* Possibly useful for moving data out of default segment.
  178652. * Uncomment it if you want. Could also define FARDATA as
  178653. * const if your compiler supports it. (SJT)
  178654. # define FARDATA FAR
  178655. */
  178656. # endif /* __WIN32__, __FLAT__, __CYGWIN__ */
  178657. #endif /* __BORLANDC__ */
  178658. /* Suggest testing for specific compiler first before testing for
  178659. * FAR. The Watcom compiler defines both __MEDIUM__ and M_I86MM,
  178660. * making reliance oncertain keywords suspect. (SJT)
  178661. */
  178662. /* MSC Medium model */
  178663. #if defined(FAR)
  178664. # if defined(M_I86MM)
  178665. # define USE_FAR_KEYWORD
  178666. # define FARDATA FAR
  178667. # include <dos.h>
  178668. # endif
  178669. #endif
  178670. /* SJT: default case */
  178671. #ifndef FAR
  178672. # define FAR
  178673. #endif
  178674. /* At this point FAR is always defined */
  178675. #ifndef FARDATA
  178676. # define FARDATA
  178677. #endif
  178678. /* Typedef for floating-point numbers that are converted
  178679. to fixed-point with a multiple of 100,000, e.g., int_gamma */
  178680. typedef png_int_32 png_fixed_point;
  178681. /* Add typedefs for pointers */
  178682. typedef void FAR * png_voidp;
  178683. typedef png_byte FAR * png_bytep;
  178684. typedef png_uint_32 FAR * png_uint_32p;
  178685. typedef png_int_32 FAR * png_int_32p;
  178686. typedef png_uint_16 FAR * png_uint_16p;
  178687. typedef png_int_16 FAR * png_int_16p;
  178688. typedef PNG_CONST char FAR * png_const_charp;
  178689. typedef char FAR * png_charp;
  178690. typedef png_fixed_point FAR * png_fixed_point_p;
  178691. #ifndef PNG_NO_STDIO
  178692. #if defined(_WIN32_WCE)
  178693. typedef HANDLE png_FILE_p;
  178694. #else
  178695. typedef FILE * png_FILE_p;
  178696. #endif
  178697. #endif
  178698. #ifdef PNG_FLOATING_POINT_SUPPORTED
  178699. typedef double FAR * png_doublep;
  178700. #endif
  178701. /* Pointers to pointers; i.e. arrays */
  178702. typedef png_byte FAR * FAR * png_bytepp;
  178703. typedef png_uint_32 FAR * FAR * png_uint_32pp;
  178704. typedef png_int_32 FAR * FAR * png_int_32pp;
  178705. typedef png_uint_16 FAR * FAR * png_uint_16pp;
  178706. typedef png_int_16 FAR * FAR * png_int_16pp;
  178707. typedef PNG_CONST char FAR * FAR * png_const_charpp;
  178708. typedef char FAR * FAR * png_charpp;
  178709. typedef png_fixed_point FAR * FAR * png_fixed_point_pp;
  178710. #ifdef PNG_FLOATING_POINT_SUPPORTED
  178711. typedef double FAR * FAR * png_doublepp;
  178712. #endif
  178713. /* Pointers to pointers to pointers; i.e., pointer to array */
  178714. typedef char FAR * FAR * FAR * png_charppp;
  178715. #if 0
  178716. /* SPC - Is this stuff deprecated? */
  178717. /* It'll be removed as of libpng-1.3.0 - GR-P */
  178718. /* libpng typedefs for types in zlib. If zlib changes
  178719. * or another compression library is used, then change these.
  178720. * Eliminates need to change all the source files.
  178721. */
  178722. typedef charf * png_zcharp;
  178723. typedef charf * FAR * png_zcharpp;
  178724. typedef z_stream FAR * png_zstreamp;
  178725. #endif /* (PNG_1_0_X) || defined(PNG_1_2_X) */
  178726. /*
  178727. * Define PNG_BUILD_DLL if the module being built is a Windows
  178728. * LIBPNG DLL.
  178729. *
  178730. * Define PNG_USE_DLL if you want to *link* to the Windows LIBPNG DLL.
  178731. * It is equivalent to Microsoft predefined macro _DLL that is
  178732. * automatically defined when you compile using the share
  178733. * version of the CRT (C Run-Time library)
  178734. *
  178735. * The cygwin mods make this behavior a little different:
  178736. * Define PNG_BUILD_DLL if you are building a dll for use with cygwin
  178737. * Define PNG_STATIC if you are building a static library for use with cygwin,
  178738. * -or- if you are building an application that you want to link to the
  178739. * static library.
  178740. * PNG_USE_DLL is defined by default (no user action needed) unless one of
  178741. * the other flags is defined.
  178742. */
  178743. #if !defined(PNG_DLL) && (defined(PNG_BUILD_DLL) || defined(PNG_USE_DLL))
  178744. # define PNG_DLL
  178745. #endif
  178746. /* If CYGWIN, then disallow GLOBAL ARRAYS unless building a static lib.
  178747. * When building a static lib, default to no GLOBAL ARRAYS, but allow
  178748. * command-line override
  178749. */
  178750. #if defined(__CYGWIN__)
  178751. # if !defined(PNG_STATIC)
  178752. # if defined(PNG_USE_GLOBAL_ARRAYS)
  178753. # undef PNG_USE_GLOBAL_ARRAYS
  178754. # endif
  178755. # if !defined(PNG_USE_LOCAL_ARRAYS)
  178756. # define PNG_USE_LOCAL_ARRAYS
  178757. # endif
  178758. # else
  178759. # if defined(PNG_USE_LOCAL_ARRAYS) || defined(PNG_NO_GLOBAL_ARRAYS)
  178760. # if defined(PNG_USE_GLOBAL_ARRAYS)
  178761. # undef PNG_USE_GLOBAL_ARRAYS
  178762. # endif
  178763. # endif
  178764. # endif
  178765. # if !defined(PNG_USE_LOCAL_ARRAYS) && !defined(PNG_USE_GLOBAL_ARRAYS)
  178766. # define PNG_USE_LOCAL_ARRAYS
  178767. # endif
  178768. #endif
  178769. /* Do not use global arrays (helps with building DLL's)
  178770. * They are no longer used in libpng itself, since version 1.0.5c,
  178771. * but might be required for some pre-1.0.5c applications.
  178772. */
  178773. #if !defined(PNG_USE_LOCAL_ARRAYS) && !defined(PNG_USE_GLOBAL_ARRAYS)
  178774. # if defined(PNG_NO_GLOBAL_ARRAYS) || \
  178775. (defined(__GNUC__) && defined(PNG_DLL)) || defined(_MSC_VER)
  178776. # define PNG_USE_LOCAL_ARRAYS
  178777. # else
  178778. # define PNG_USE_GLOBAL_ARRAYS
  178779. # endif
  178780. #endif
  178781. #if defined(__CYGWIN__)
  178782. # undef PNGAPI
  178783. # define PNGAPI __cdecl
  178784. # undef PNG_IMPEXP
  178785. # define PNG_IMPEXP
  178786. #endif
  178787. /* If you define PNGAPI, e.g., with compiler option "-DPNGAPI=__stdcall",
  178788. * you may get warnings regarding the linkage of png_zalloc and png_zfree.
  178789. * Don't ignore those warnings; you must also reset the default calling
  178790. * convention in your compiler to match your PNGAPI, and you must build
  178791. * zlib and your applications the same way you build libpng.
  178792. */
  178793. #if defined(__MINGW32__) && !defined(PNG_MODULEDEF)
  178794. # ifndef PNG_NO_MODULEDEF
  178795. # define PNG_NO_MODULEDEF
  178796. # endif
  178797. #endif
  178798. #if !defined(PNG_IMPEXP) && defined(PNG_BUILD_DLL) && !defined(PNG_NO_MODULEDEF)
  178799. # define PNG_IMPEXP
  178800. #endif
  178801. #if defined(PNG_DLL) || defined(_DLL) || defined(__DLL__ ) || \
  178802. (( defined(_Windows) || defined(_WINDOWS) || \
  178803. defined(WIN32) || defined(_WIN32) || defined(__WIN32__) ))
  178804. # ifndef PNGAPI
  178805. # if defined(__GNUC__) || (defined (_MSC_VER) && (_MSC_VER >= 800))
  178806. # define PNGAPI __cdecl
  178807. # else
  178808. # define PNGAPI _cdecl
  178809. # endif
  178810. # endif
  178811. # if !defined(PNG_IMPEXP) && (!defined(PNG_DLL) || \
  178812. 0 /* WINCOMPILER_WITH_NO_SUPPORT_FOR_DECLIMPEXP */)
  178813. # define PNG_IMPEXP
  178814. # endif
  178815. # if !defined(PNG_IMPEXP)
  178816. # define PNG_EXPORT_TYPE1(type,symbol) PNG_IMPEXP type PNGAPI symbol
  178817. # define PNG_EXPORT_TYPE2(type,symbol) type PNG_IMPEXP PNGAPI symbol
  178818. /* Borland/Microsoft */
  178819. # if defined(_MSC_VER) || defined(__BORLANDC__)
  178820. # if (_MSC_VER >= 800) || (__BORLANDC__ >= 0x500)
  178821. # define PNG_EXPORT PNG_EXPORT_TYPE1
  178822. # else
  178823. # define PNG_EXPORT PNG_EXPORT_TYPE2
  178824. # if defined(PNG_BUILD_DLL)
  178825. # define PNG_IMPEXP __export
  178826. # else
  178827. # define PNG_IMPEXP /*__import */ /* doesn't exist AFAIK in
  178828. VC++ */
  178829. # endif /* Exists in Borland C++ for
  178830. C++ classes (== huge) */
  178831. # endif
  178832. # endif
  178833. # if !defined(PNG_IMPEXP)
  178834. # if defined(PNG_BUILD_DLL)
  178835. # define PNG_IMPEXP __declspec(dllexport)
  178836. # else
  178837. # define PNG_IMPEXP __declspec(dllimport)
  178838. # endif
  178839. # endif
  178840. # endif /* PNG_IMPEXP */
  178841. #else /* !(DLL || non-cygwin WINDOWS) */
  178842. # if (defined(__IBMC__) || defined(__IBMCPP__)) && defined(__OS2__)
  178843. # ifndef PNGAPI
  178844. # define PNGAPI _System
  178845. # endif
  178846. # else
  178847. # if 0 /* ... other platforms, with other meanings */
  178848. # endif
  178849. # endif
  178850. #endif
  178851. #ifndef PNGAPI
  178852. # define PNGAPI
  178853. #endif
  178854. #ifndef PNG_IMPEXP
  178855. # define PNG_IMPEXP
  178856. #endif
  178857. #ifdef PNG_BUILDSYMS
  178858. # ifndef PNG_EXPORT
  178859. # define PNG_EXPORT(type,symbol) PNG_FUNCTION_EXPORT symbol END
  178860. # endif
  178861. # ifdef PNG_USE_GLOBAL_ARRAYS
  178862. # ifndef PNG_EXPORT_VAR
  178863. # define PNG_EXPORT_VAR(type) PNG_DATA_EXPORT
  178864. # endif
  178865. # endif
  178866. #endif
  178867. #ifndef PNG_EXPORT
  178868. # define PNG_EXPORT(type,symbol) PNG_IMPEXP type PNGAPI symbol
  178869. #endif
  178870. #ifdef PNG_USE_GLOBAL_ARRAYS
  178871. # ifndef PNG_EXPORT_VAR
  178872. # define PNG_EXPORT_VAR(type) extern PNG_IMPEXP type
  178873. # endif
  178874. #endif
  178875. /* User may want to use these so they are not in PNG_INTERNAL. Any library
  178876. * functions that are passed far data must be model independent.
  178877. */
  178878. #ifndef PNG_ABORT
  178879. # define PNG_ABORT() abort()
  178880. #endif
  178881. #ifdef PNG_SETJMP_SUPPORTED
  178882. # define png_jmpbuf(png_ptr) ((png_ptr)->jmpbuf)
  178883. #else
  178884. # define png_jmpbuf(png_ptr) \
  178885. (LIBPNG_WAS_COMPILED_WITH__PNG_SETJMP_NOT_SUPPORTED)
  178886. #endif
  178887. #if defined(USE_FAR_KEYWORD) /* memory model independent fns */
  178888. /* use this to make far-to-near assignments */
  178889. # define CHECK 1
  178890. # define NOCHECK 0
  178891. # define CVT_PTR(ptr) (png_far_to_near(png_ptr,ptr,CHECK))
  178892. # define CVT_PTR_NOCHECK(ptr) (png_far_to_near(png_ptr,ptr,NOCHECK))
  178893. # define png_snprintf _fsnprintf /* Added to v 1.2.19 */
  178894. # define png_strcpy _fstrcpy
  178895. # define png_strncpy _fstrncpy /* Added to v 1.2.6 */
  178896. # define png_strlen _fstrlen
  178897. # define png_memcmp _fmemcmp /* SJT: added */
  178898. # define png_memcpy _fmemcpy
  178899. # define png_memset _fmemset
  178900. #else /* use the usual functions */
  178901. # define CVT_PTR(ptr) (ptr)
  178902. # define CVT_PTR_NOCHECK(ptr) (ptr)
  178903. # ifndef PNG_NO_SNPRINTF
  178904. # ifdef _MSC_VER
  178905. # define png_snprintf _snprintf /* Added to v 1.2.19 */
  178906. # define png_snprintf2 _snprintf
  178907. # define png_snprintf6 _snprintf
  178908. # else
  178909. # define png_snprintf snprintf /* Added to v 1.2.19 */
  178910. # define png_snprintf2 snprintf
  178911. # define png_snprintf6 snprintf
  178912. # endif
  178913. # else
  178914. /* You don't have or don't want to use snprintf(). Caution: Using
  178915. * sprintf instead of snprintf exposes your application to accidental
  178916. * or malevolent buffer overflows. If you don't have snprintf()
  178917. * as a general rule you should provide one (you can get one from
  178918. * Portable OpenSSH). */
  178919. # define png_snprintf(s1,n,fmt,x1) sprintf(s1,fmt,x1)
  178920. # define png_snprintf2(s1,n,fmt,x1,x2) sprintf(s1,fmt,x1,x2)
  178921. # define png_snprintf6(s1,n,fmt,x1,x2,x3,x4,x5,x6) \
  178922. sprintf(s1,fmt,x1,x2,x3,x4,x5,x6)
  178923. # endif
  178924. # define png_strcpy strcpy
  178925. # define png_strncpy strncpy /* Added to v 1.2.6 */
  178926. # define png_strlen strlen
  178927. # define png_memcmp memcmp /* SJT: added */
  178928. # define png_memcpy memcpy
  178929. # define png_memset memset
  178930. #endif
  178931. /* End of memory model independent support */
  178932. /* Just a little check that someone hasn't tried to define something
  178933. * contradictory.
  178934. */
  178935. #if (PNG_ZBUF_SIZE > 65536L) && defined(PNG_MAX_MALLOC_64K)
  178936. # undef PNG_ZBUF_SIZE
  178937. # define PNG_ZBUF_SIZE 65536L
  178938. #endif
  178939. /* Added at libpng-1.2.8 */
  178940. #endif /* PNG_VERSION_INFO_ONLY */
  178941. #endif /* PNGCONF_H */
  178942. /*** End of inlined file: pngconf.h ***/
  178943. #ifdef _MSC_VER
  178944. #pragma warning (disable: 4996 4100)
  178945. #endif
  178946. /*
  178947. * Added at libpng-1.2.8 */
  178948. /* Ref MSDN: Private as priority over Special
  178949. * VS_FF_PRIVATEBUILD File *was not* built using standard release
  178950. * procedures. If this value is given, the StringFileInfo block must
  178951. * contain a PrivateBuild string.
  178952. *
  178953. * VS_FF_SPECIALBUILD File *was* built by the original company using
  178954. * standard release procedures but is a variation of the standard
  178955. * file of the same version number. If this value is given, the
  178956. * StringFileInfo block must contain a SpecialBuild string.
  178957. */
  178958. #if defined(PNG_USER_PRIVATEBUILD)
  178959. # define PNG_LIBPNG_BUILD_TYPE \
  178960. (PNG_LIBPNG_BUILD_BASE_TYPE | PNG_LIBPNG_BUILD_PRIVATE)
  178961. #else
  178962. # if defined(PNG_LIBPNG_SPECIALBUILD)
  178963. # define PNG_LIBPNG_BUILD_TYPE \
  178964. (PNG_LIBPNG_BUILD_BASE_TYPE | PNG_LIBPNG_BUILD_SPECIAL)
  178965. # else
  178966. # define PNG_LIBPNG_BUILD_TYPE (PNG_LIBPNG_BUILD_BASE_TYPE)
  178967. # endif
  178968. #endif
  178969. #ifndef PNG_VERSION_INFO_ONLY
  178970. /* Inhibit C++ name-mangling for libpng functions but not for system calls. */
  178971. #ifdef __cplusplus
  178972. extern "C" {
  178973. #endif /* __cplusplus */
  178974. /* This file is arranged in several sections. The first section contains
  178975. * structure and type definitions. The second section contains the external
  178976. * library functions, while the third has the internal library functions,
  178977. * which applications aren't expected to use directly.
  178978. */
  178979. #ifndef PNG_NO_TYPECAST_NULL
  178980. #define int_p_NULL (int *)NULL
  178981. #define png_bytep_NULL (png_bytep)NULL
  178982. #define png_bytepp_NULL (png_bytepp)NULL
  178983. #define png_doublep_NULL (png_doublep)NULL
  178984. #define png_error_ptr_NULL (png_error_ptr)NULL
  178985. #define png_flush_ptr_NULL (png_flush_ptr)NULL
  178986. #define png_free_ptr_NULL (png_free_ptr)NULL
  178987. #define png_infopp_NULL (png_infopp)NULL
  178988. #define png_malloc_ptr_NULL (png_malloc_ptr)NULL
  178989. #define png_read_status_ptr_NULL (png_read_status_ptr)NULL
  178990. #define png_rw_ptr_NULL (png_rw_ptr)NULL
  178991. #define png_structp_NULL (png_structp)NULL
  178992. #define png_uint_16p_NULL (png_uint_16p)NULL
  178993. #define png_voidp_NULL (png_voidp)NULL
  178994. #define png_write_status_ptr_NULL (png_write_status_ptr)NULL
  178995. #else
  178996. #define int_p_NULL NULL
  178997. #define png_bytep_NULL NULL
  178998. #define png_bytepp_NULL NULL
  178999. #define png_doublep_NULL NULL
  179000. #define png_error_ptr_NULL NULL
  179001. #define png_flush_ptr_NULL NULL
  179002. #define png_free_ptr_NULL NULL
  179003. #define png_infopp_NULL NULL
  179004. #define png_malloc_ptr_NULL NULL
  179005. #define png_read_status_ptr_NULL NULL
  179006. #define png_rw_ptr_NULL NULL
  179007. #define png_structp_NULL NULL
  179008. #define png_uint_16p_NULL NULL
  179009. #define png_voidp_NULL NULL
  179010. #define png_write_status_ptr_NULL NULL
  179011. #endif
  179012. /* variables declared in png.c - only it needs to define PNG_NO_EXTERN */
  179013. #if !defined(PNG_NO_EXTERN) || defined(PNG_ALWAYS_EXTERN)
  179014. /* Version information for C files, stored in png.c. This had better match
  179015. * the version above.
  179016. */
  179017. #ifdef PNG_USE_GLOBAL_ARRAYS
  179018. PNG_EXPORT_VAR (PNG_CONST char) png_libpng_ver[18];
  179019. /* need room for 99.99.99beta99z */
  179020. #else
  179021. #define png_libpng_ver png_get_header_ver(NULL)
  179022. #endif
  179023. #ifdef PNG_USE_GLOBAL_ARRAYS
  179024. /* This was removed in version 1.0.5c */
  179025. /* Structures to facilitate easy interlacing. See png.c for more details */
  179026. PNG_EXPORT_VAR (PNG_CONST int FARDATA) png_pass_start[7];
  179027. PNG_EXPORT_VAR (PNG_CONST int FARDATA) png_pass_inc[7];
  179028. PNG_EXPORT_VAR (PNG_CONST int FARDATA) png_pass_ystart[7];
  179029. PNG_EXPORT_VAR (PNG_CONST int FARDATA) png_pass_yinc[7];
  179030. PNG_EXPORT_VAR (PNG_CONST int FARDATA) png_pass_mask[7];
  179031. PNG_EXPORT_VAR (PNG_CONST int FARDATA) png_pass_dsp_mask[7];
  179032. /* This isn't currently used. If you need it, see png.c for more details.
  179033. PNG_EXPORT_VAR (PNG_CONST int FARDATA) png_pass_height[7];
  179034. */
  179035. #endif
  179036. #endif /* PNG_NO_EXTERN */
  179037. /* Three color definitions. The order of the red, green, and blue, (and the
  179038. * exact size) is not important, although the size of the fields need to
  179039. * be png_byte or png_uint_16 (as defined below).
  179040. */
  179041. typedef struct png_color_struct
  179042. {
  179043. png_byte red;
  179044. png_byte green;
  179045. png_byte blue;
  179046. } png_color;
  179047. typedef png_color FAR * png_colorp;
  179048. typedef png_color FAR * FAR * png_colorpp;
  179049. typedef struct png_color_16_struct
  179050. {
  179051. png_byte index; /* used for palette files */
  179052. png_uint_16 red; /* for use in red green blue files */
  179053. png_uint_16 green;
  179054. png_uint_16 blue;
  179055. png_uint_16 gray; /* for use in grayscale files */
  179056. } png_color_16;
  179057. typedef png_color_16 FAR * png_color_16p;
  179058. typedef png_color_16 FAR * FAR * png_color_16pp;
  179059. typedef struct png_color_8_struct
  179060. {
  179061. png_byte red; /* for use in red green blue files */
  179062. png_byte green;
  179063. png_byte blue;
  179064. png_byte gray; /* for use in grayscale files */
  179065. png_byte alpha; /* for alpha channel files */
  179066. } png_color_8;
  179067. typedef png_color_8 FAR * png_color_8p;
  179068. typedef png_color_8 FAR * FAR * png_color_8pp;
  179069. /*
  179070. * The following two structures are used for the in-core representation
  179071. * of sPLT chunks.
  179072. */
  179073. typedef struct png_sPLT_entry_struct
  179074. {
  179075. png_uint_16 red;
  179076. png_uint_16 green;
  179077. png_uint_16 blue;
  179078. png_uint_16 alpha;
  179079. png_uint_16 frequency;
  179080. } png_sPLT_entry;
  179081. typedef png_sPLT_entry FAR * png_sPLT_entryp;
  179082. typedef png_sPLT_entry FAR * FAR * png_sPLT_entrypp;
  179083. /* When the depth of the sPLT palette is 8 bits, the color and alpha samples
  179084. * occupy the LSB of their respective members, and the MSB of each member
  179085. * is zero-filled. The frequency member always occupies the full 16 bits.
  179086. */
  179087. typedef struct png_sPLT_struct
  179088. {
  179089. png_charp name; /* palette name */
  179090. png_byte depth; /* depth of palette samples */
  179091. png_sPLT_entryp entries; /* palette entries */
  179092. png_int_32 nentries; /* number of palette entries */
  179093. } png_sPLT_t;
  179094. typedef png_sPLT_t FAR * png_sPLT_tp;
  179095. typedef png_sPLT_t FAR * FAR * png_sPLT_tpp;
  179096. #ifdef PNG_TEXT_SUPPORTED
  179097. /* png_text holds the contents of a text/ztxt/itxt chunk in a PNG file,
  179098. * and whether that contents is compressed or not. The "key" field
  179099. * points to a regular zero-terminated C string. The "text", "lang", and
  179100. * "lang_key" fields can be regular C strings, empty strings, or NULL pointers.
  179101. * However, the * structure returned by png_get_text() will always contain
  179102. * regular zero-terminated C strings (possibly empty), never NULL pointers,
  179103. * so they can be safely used in printf() and other string-handling functions.
  179104. */
  179105. typedef struct png_text_struct
  179106. {
  179107. int compression; /* compression value:
  179108. -1: tEXt, none
  179109. 0: zTXt, deflate
  179110. 1: iTXt, none
  179111. 2: iTXt, deflate */
  179112. png_charp key; /* keyword, 1-79 character description of "text" */
  179113. png_charp text; /* comment, may be an empty string (ie "")
  179114. or a NULL pointer */
  179115. png_size_t text_length; /* length of the text string */
  179116. #ifdef PNG_iTXt_SUPPORTED
  179117. png_size_t itxt_length; /* length of the itxt string */
  179118. png_charp lang; /* language code, 0-79 characters
  179119. or a NULL pointer */
  179120. png_charp lang_key; /* keyword translated UTF-8 string, 0 or more
  179121. chars or a NULL pointer */
  179122. #endif
  179123. } png_text;
  179124. typedef png_text FAR * png_textp;
  179125. typedef png_text FAR * FAR * png_textpp;
  179126. #endif
  179127. /* Supported compression types for text in PNG files (tEXt, and zTXt).
  179128. * The values of the PNG_TEXT_COMPRESSION_ defines should NOT be changed. */
  179129. #define PNG_TEXT_COMPRESSION_NONE_WR -3
  179130. #define PNG_TEXT_COMPRESSION_zTXt_WR -2
  179131. #define PNG_TEXT_COMPRESSION_NONE -1
  179132. #define PNG_TEXT_COMPRESSION_zTXt 0
  179133. #define PNG_ITXT_COMPRESSION_NONE 1
  179134. #define PNG_ITXT_COMPRESSION_zTXt 2
  179135. #define PNG_TEXT_COMPRESSION_LAST 3 /* Not a valid value */
  179136. /* png_time is a way to hold the time in an machine independent way.
  179137. * Two conversions are provided, both from time_t and struct tm. There
  179138. * is no portable way to convert to either of these structures, as far
  179139. * as I know. If you know of a portable way, send it to me. As a side
  179140. * note - PNG has always been Year 2000 compliant!
  179141. */
  179142. typedef struct png_time_struct
  179143. {
  179144. png_uint_16 year; /* full year, as in, 1995 */
  179145. png_byte month; /* month of year, 1 - 12 */
  179146. png_byte day; /* day of month, 1 - 31 */
  179147. png_byte hour; /* hour of day, 0 - 23 */
  179148. png_byte minute; /* minute of hour, 0 - 59 */
  179149. png_byte second; /* second of minute, 0 - 60 (for leap seconds) */
  179150. } png_time;
  179151. typedef png_time FAR * png_timep;
  179152. typedef png_time FAR * FAR * png_timepp;
  179153. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  179154. /* png_unknown_chunk is a structure to hold queued chunks for which there is
  179155. * no specific support. The idea is that we can use this to queue
  179156. * up private chunks for output even though the library doesn't actually
  179157. * know about their semantics.
  179158. */
  179159. typedef struct png_unknown_chunk_t
  179160. {
  179161. png_byte name[5];
  179162. png_byte *data;
  179163. png_size_t size;
  179164. /* libpng-using applications should NOT directly modify this byte. */
  179165. png_byte location; /* mode of operation at read time */
  179166. }
  179167. png_unknown_chunk;
  179168. typedef png_unknown_chunk FAR * png_unknown_chunkp;
  179169. typedef png_unknown_chunk FAR * FAR * png_unknown_chunkpp;
  179170. #endif
  179171. /* png_info is a structure that holds the information in a PNG file so
  179172. * that the application can find out the characteristics of the image.
  179173. * If you are reading the file, this structure will tell you what is
  179174. * in the PNG file. If you are writing the file, fill in the information
  179175. * you want to put into the PNG file, then call png_write_info().
  179176. * The names chosen should be very close to the PNG specification, so
  179177. * consult that document for information about the meaning of each field.
  179178. *
  179179. * With libpng < 0.95, it was only possible to directly set and read the
  179180. * the values in the png_info_struct, which meant that the contents and
  179181. * order of the values had to remain fixed. With libpng 0.95 and later,
  179182. * however, there are now functions that abstract the contents of
  179183. * png_info_struct from the application, so this makes it easier to use
  179184. * libpng with dynamic libraries, and even makes it possible to use
  179185. * libraries that don't have all of the libpng ancillary chunk-handing
  179186. * functionality.
  179187. *
  179188. * In any case, the order of the parameters in png_info_struct should NOT
  179189. * be changed for as long as possible to keep compatibility with applications
  179190. * that use the old direct-access method with png_info_struct.
  179191. *
  179192. * The following members may have allocated storage attached that should be
  179193. * cleaned up before the structure is discarded: palette, trans, text,
  179194. * pcal_purpose, pcal_units, pcal_params, hist, iccp_name, iccp_profile,
  179195. * splt_palettes, scal_unit, row_pointers, and unknowns. By default, these
  179196. * are automatically freed when the info structure is deallocated, if they were
  179197. * allocated internally by libpng. This behavior can be changed by means
  179198. * of the png_data_freer() function.
  179199. *
  179200. * More allocation details: all the chunk-reading functions that
  179201. * change these members go through the corresponding png_set_*
  179202. * functions. A function to clear these members is available: see
  179203. * png_free_data(). The png_set_* functions do not depend on being
  179204. * able to point info structure members to any of the storage they are
  179205. * passed (they make their own copies), EXCEPT that the png_set_text
  179206. * functions use the same storage passed to them in the text_ptr or
  179207. * itxt_ptr structure argument, and the png_set_rows and png_set_unknowns
  179208. * functions do not make their own copies.
  179209. */
  179210. typedef struct png_info_struct
  179211. {
  179212. /* the following are necessary for every PNG file */
  179213. png_uint_32 width; /* width of image in pixels (from IHDR) */
  179214. png_uint_32 height; /* height of image in pixels (from IHDR) */
  179215. png_uint_32 valid; /* valid chunk data (see PNG_INFO_ below) */
  179216. png_uint_32 rowbytes; /* bytes needed to hold an untransformed row */
  179217. png_colorp palette; /* array of color values (valid & PNG_INFO_PLTE) */
  179218. png_uint_16 num_palette; /* number of color entries in "palette" (PLTE) */
  179219. png_uint_16 num_trans; /* number of transparent palette color (tRNS) */
  179220. png_byte bit_depth; /* 1, 2, 4, 8, or 16 bits/channel (from IHDR) */
  179221. png_byte color_type; /* see PNG_COLOR_TYPE_ below (from IHDR) */
  179222. /* The following three should have been named *_method not *_type */
  179223. png_byte compression_type; /* must be PNG_COMPRESSION_TYPE_BASE (IHDR) */
  179224. png_byte filter_type; /* must be PNG_FILTER_TYPE_BASE (from IHDR) */
  179225. png_byte interlace_type; /* One of PNG_INTERLACE_NONE, PNG_INTERLACE_ADAM7 */
  179226. /* The following is informational only on read, and not used on writes. */
  179227. png_byte channels; /* number of data channels per pixel (1, 2, 3, 4) */
  179228. png_byte pixel_depth; /* number of bits per pixel */
  179229. png_byte spare_byte; /* to align the data, and for future use */
  179230. png_byte signature[8]; /* magic bytes read by libpng from start of file */
  179231. /* The rest of the data is optional. If you are reading, check the
  179232. * valid field to see if the information in these are valid. If you
  179233. * are writing, set the valid field to those chunks you want written,
  179234. * and initialize the appropriate fields below.
  179235. */
  179236. #if defined(PNG_gAMA_SUPPORTED) && defined(PNG_FLOATING_POINT_SUPPORTED)
  179237. /* The gAMA chunk describes the gamma characteristics of the system
  179238. * on which the image was created, normally in the range [1.0, 2.5].
  179239. * Data is valid if (valid & PNG_INFO_gAMA) is non-zero.
  179240. */
  179241. float gamma; /* gamma value of image, if (valid & PNG_INFO_gAMA) */
  179242. #endif
  179243. #if defined(PNG_sRGB_SUPPORTED)
  179244. /* GR-P, 0.96a */
  179245. /* Data valid if (valid & PNG_INFO_sRGB) non-zero. */
  179246. png_byte srgb_intent; /* sRGB rendering intent [0, 1, 2, or 3] */
  179247. #endif
  179248. #if defined(PNG_TEXT_SUPPORTED)
  179249. /* The tEXt, and zTXt chunks contain human-readable textual data in
  179250. * uncompressed, compressed, and optionally compressed forms, respectively.
  179251. * The data in "text" is an array of pointers to uncompressed,
  179252. * null-terminated C strings. Each chunk has a keyword that describes the
  179253. * textual data contained in that chunk. Keywords are not required to be
  179254. * unique, and the text string may be empty. Any number of text chunks may
  179255. * be in an image.
  179256. */
  179257. int num_text; /* number of comments read/to write */
  179258. int max_text; /* current size of text array */
  179259. png_textp text; /* array of comments read/to write */
  179260. #endif /* PNG_TEXT_SUPPORTED */
  179261. #if defined(PNG_tIME_SUPPORTED)
  179262. /* The tIME chunk holds the last time the displayed image data was
  179263. * modified. See the png_time struct for the contents of this struct.
  179264. */
  179265. png_time mod_time;
  179266. #endif
  179267. #if defined(PNG_sBIT_SUPPORTED)
  179268. /* The sBIT chunk specifies the number of significant high-order bits
  179269. * in the pixel data. Values are in the range [1, bit_depth], and are
  179270. * only specified for the channels in the pixel data. The contents of
  179271. * the low-order bits is not specified. Data is valid if
  179272. * (valid & PNG_INFO_sBIT) is non-zero.
  179273. */
  179274. png_color_8 sig_bit; /* significant bits in color channels */
  179275. #endif
  179276. #if defined(PNG_tRNS_SUPPORTED) || defined(PNG_READ_EXPAND_SUPPORTED) || \
  179277. defined(PNG_READ_BACKGROUND_SUPPORTED)
  179278. /* The tRNS chunk supplies transparency data for paletted images and
  179279. * other image types that don't need a full alpha channel. There are
  179280. * "num_trans" transparency values for a paletted image, stored in the
  179281. * same order as the palette colors, starting from index 0. Values
  179282. * for the data are in the range [0, 255], ranging from fully transparent
  179283. * to fully opaque, respectively. For non-paletted images, there is a
  179284. * single color specified that should be treated as fully transparent.
  179285. * Data is valid if (valid & PNG_INFO_tRNS) is non-zero.
  179286. */
  179287. png_bytep trans; /* transparent values for paletted image */
  179288. png_color_16 trans_values; /* transparent color for non-palette image */
  179289. #endif
  179290. #if defined(PNG_bKGD_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
  179291. /* The bKGD chunk gives the suggested image background color if the
  179292. * display program does not have its own background color and the image
  179293. * is needs to composited onto a background before display. The colors
  179294. * in "background" are normally in the same color space/depth as the
  179295. * pixel data. Data is valid if (valid & PNG_INFO_bKGD) is non-zero.
  179296. */
  179297. png_color_16 background;
  179298. #endif
  179299. #if defined(PNG_oFFs_SUPPORTED)
  179300. /* The oFFs chunk gives the offset in "offset_unit_type" units rightwards
  179301. * and downwards from the top-left corner of the display, page, or other
  179302. * application-specific co-ordinate space. See the PNG_OFFSET_ defines
  179303. * below for the unit types. Valid if (valid & PNG_INFO_oFFs) non-zero.
  179304. */
  179305. png_int_32 x_offset; /* x offset on page */
  179306. png_int_32 y_offset; /* y offset on page */
  179307. png_byte offset_unit_type; /* offset units type */
  179308. #endif
  179309. #if defined(PNG_pHYs_SUPPORTED)
  179310. /* The pHYs chunk gives the physical pixel density of the image for
  179311. * display or printing in "phys_unit_type" units (see PNG_RESOLUTION_
  179312. * defines below). Data is valid if (valid & PNG_INFO_pHYs) is non-zero.
  179313. */
  179314. png_uint_32 x_pixels_per_unit; /* horizontal pixel density */
  179315. png_uint_32 y_pixels_per_unit; /* vertical pixel density */
  179316. png_byte phys_unit_type; /* resolution type (see PNG_RESOLUTION_ below) */
  179317. #endif
  179318. #if defined(PNG_hIST_SUPPORTED)
  179319. /* The hIST chunk contains the relative frequency or importance of the
  179320. * various palette entries, so that a viewer can intelligently select a
  179321. * reduced-color palette, if required. Data is an array of "num_palette"
  179322. * values in the range [0,65535]. Data valid if (valid & PNG_INFO_hIST)
  179323. * is non-zero.
  179324. */
  179325. png_uint_16p hist;
  179326. #endif
  179327. #ifdef PNG_cHRM_SUPPORTED
  179328. /* The cHRM chunk describes the CIE color characteristics of the monitor
  179329. * on which the PNG was created. This data allows the viewer to do gamut
  179330. * mapping of the input image to ensure that the viewer sees the same
  179331. * colors in the image as the creator. Values are in the range
  179332. * [0.0, 0.8]. Data valid if (valid & PNG_INFO_cHRM) non-zero.
  179333. */
  179334. #ifdef PNG_FLOATING_POINT_SUPPORTED
  179335. float x_white;
  179336. float y_white;
  179337. float x_red;
  179338. float y_red;
  179339. float x_green;
  179340. float y_green;
  179341. float x_blue;
  179342. float y_blue;
  179343. #endif
  179344. #endif
  179345. #if defined(PNG_pCAL_SUPPORTED)
  179346. /* The pCAL chunk describes a transformation between the stored pixel
  179347. * values and original physical data values used to create the image.
  179348. * The integer range [0, 2^bit_depth - 1] maps to the floating-point
  179349. * range given by [pcal_X0, pcal_X1], and are further transformed by a
  179350. * (possibly non-linear) transformation function given by "pcal_type"
  179351. * and "pcal_params" into "pcal_units". Please see the PNG_EQUATION_
  179352. * defines below, and the PNG-Group's PNG extensions document for a
  179353. * complete description of the transformations and how they should be
  179354. * implemented, and for a description of the ASCII parameter strings.
  179355. * Data values are valid if (valid & PNG_INFO_pCAL) non-zero.
  179356. */
  179357. png_charp pcal_purpose; /* pCAL chunk description string */
  179358. png_int_32 pcal_X0; /* minimum value */
  179359. png_int_32 pcal_X1; /* maximum value */
  179360. png_charp pcal_units; /* Latin-1 string giving physical units */
  179361. png_charpp pcal_params; /* ASCII strings containing parameter values */
  179362. png_byte pcal_type; /* equation type (see PNG_EQUATION_ below) */
  179363. png_byte pcal_nparams; /* number of parameters given in pcal_params */
  179364. #endif
  179365. /* New members added in libpng-1.0.6 */
  179366. #ifdef PNG_FREE_ME_SUPPORTED
  179367. png_uint_32 free_me; /* flags items libpng is responsible for freeing */
  179368. #endif
  179369. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  179370. /* storage for unknown chunks that the library doesn't recognize. */
  179371. png_unknown_chunkp unknown_chunks;
  179372. png_size_t unknown_chunks_num;
  179373. #endif
  179374. #if defined(PNG_iCCP_SUPPORTED)
  179375. /* iCCP chunk data. */
  179376. png_charp iccp_name; /* profile name */
  179377. png_charp iccp_profile; /* International Color Consortium profile data */
  179378. /* Note to maintainer: should be png_bytep */
  179379. png_uint_32 iccp_proflen; /* ICC profile data length */
  179380. png_byte iccp_compression; /* Always zero */
  179381. #endif
  179382. #if defined(PNG_sPLT_SUPPORTED)
  179383. /* data on sPLT chunks (there may be more than one). */
  179384. png_sPLT_tp splt_palettes;
  179385. png_uint_32 splt_palettes_num;
  179386. #endif
  179387. #if defined(PNG_sCAL_SUPPORTED)
  179388. /* The sCAL chunk describes the actual physical dimensions of the
  179389. * subject matter of the graphic. The chunk contains a unit specification
  179390. * a byte value, and two ASCII strings representing floating-point
  179391. * values. The values are width and height corresponsing to one pixel
  179392. * in the image. This external representation is converted to double
  179393. * here. Data values are valid if (valid & PNG_INFO_sCAL) is non-zero.
  179394. */
  179395. png_byte scal_unit; /* unit of physical scale */
  179396. #ifdef PNG_FLOATING_POINT_SUPPORTED
  179397. double scal_pixel_width; /* width of one pixel */
  179398. double scal_pixel_height; /* height of one pixel */
  179399. #endif
  179400. #ifdef PNG_FIXED_POINT_SUPPORTED
  179401. png_charp scal_s_width; /* string containing height */
  179402. png_charp scal_s_height; /* string containing width */
  179403. #endif
  179404. #endif
  179405. #if defined(PNG_INFO_IMAGE_SUPPORTED)
  179406. /* Memory has been allocated if (valid & PNG_ALLOCATED_INFO_ROWS) non-zero */
  179407. /* Data valid if (valid & PNG_INFO_IDAT) non-zero */
  179408. png_bytepp row_pointers; /* the image bits */
  179409. #endif
  179410. #if defined(PNG_FIXED_POINT_SUPPORTED) && defined(PNG_gAMA_SUPPORTED)
  179411. png_fixed_point int_gamma; /* gamma of image, if (valid & PNG_INFO_gAMA) */
  179412. #endif
  179413. #if defined(PNG_cHRM_SUPPORTED) && defined(PNG_FIXED_POINT_SUPPORTED)
  179414. png_fixed_point int_x_white;
  179415. png_fixed_point int_y_white;
  179416. png_fixed_point int_x_red;
  179417. png_fixed_point int_y_red;
  179418. png_fixed_point int_x_green;
  179419. png_fixed_point int_y_green;
  179420. png_fixed_point int_x_blue;
  179421. png_fixed_point int_y_blue;
  179422. #endif
  179423. } png_info;
  179424. typedef png_info FAR * png_infop;
  179425. typedef png_info FAR * FAR * png_infopp;
  179426. /* Maximum positive integer used in PNG is (2^31)-1 */
  179427. #define PNG_UINT_31_MAX ((png_uint_32)0x7fffffffL)
  179428. #define PNG_UINT_32_MAX ((png_uint_32)(-1))
  179429. #define PNG_SIZE_MAX ((png_size_t)(-1))
  179430. #if defined(PNG_1_0_X) || defined (PNG_1_2_X)
  179431. /* PNG_MAX_UINT is deprecated; use PNG_UINT_31_MAX instead. */
  179432. #define PNG_MAX_UINT PNG_UINT_31_MAX
  179433. #endif
  179434. /* These describe the color_type field in png_info. */
  179435. /* color type masks */
  179436. #define PNG_COLOR_MASK_PALETTE 1
  179437. #define PNG_COLOR_MASK_COLOR 2
  179438. #define PNG_COLOR_MASK_ALPHA 4
  179439. /* color types. Note that not all combinations are legal */
  179440. #define PNG_COLOR_TYPE_GRAY 0
  179441. #define PNG_COLOR_TYPE_PALETTE (PNG_COLOR_MASK_COLOR | PNG_COLOR_MASK_PALETTE)
  179442. #define PNG_COLOR_TYPE_RGB (PNG_COLOR_MASK_COLOR)
  179443. #define PNG_COLOR_TYPE_RGB_ALPHA (PNG_COLOR_MASK_COLOR | PNG_COLOR_MASK_ALPHA)
  179444. #define PNG_COLOR_TYPE_GRAY_ALPHA (PNG_COLOR_MASK_ALPHA)
  179445. /* aliases */
  179446. #define PNG_COLOR_TYPE_RGBA PNG_COLOR_TYPE_RGB_ALPHA
  179447. #define PNG_COLOR_TYPE_GA PNG_COLOR_TYPE_GRAY_ALPHA
  179448. /* This is for compression type. PNG 1.0-1.2 only define the single type. */
  179449. #define PNG_COMPRESSION_TYPE_BASE 0 /* Deflate method 8, 32K window */
  179450. #define PNG_COMPRESSION_TYPE_DEFAULT PNG_COMPRESSION_TYPE_BASE
  179451. /* This is for filter type. PNG 1.0-1.2 only define the single type. */
  179452. #define PNG_FILTER_TYPE_BASE 0 /* Single row per-byte filtering */
  179453. #define PNG_INTRAPIXEL_DIFFERENCING 64 /* Used only in MNG datastreams */
  179454. #define PNG_FILTER_TYPE_DEFAULT PNG_FILTER_TYPE_BASE
  179455. /* These are for the interlacing type. These values should NOT be changed. */
  179456. #define PNG_INTERLACE_NONE 0 /* Non-interlaced image */
  179457. #define PNG_INTERLACE_ADAM7 1 /* Adam7 interlacing */
  179458. #define PNG_INTERLACE_LAST 2 /* Not a valid value */
  179459. /* These are for the oFFs chunk. These values should NOT be changed. */
  179460. #define PNG_OFFSET_PIXEL 0 /* Offset in pixels */
  179461. #define PNG_OFFSET_MICROMETER 1 /* Offset in micrometers (1/10^6 meter) */
  179462. #define PNG_OFFSET_LAST 2 /* Not a valid value */
  179463. /* These are for the pCAL chunk. These values should NOT be changed. */
  179464. #define PNG_EQUATION_LINEAR 0 /* Linear transformation */
  179465. #define PNG_EQUATION_BASE_E 1 /* Exponential base e transform */
  179466. #define PNG_EQUATION_ARBITRARY 2 /* Arbitrary base exponential transform */
  179467. #define PNG_EQUATION_HYPERBOLIC 3 /* Hyperbolic sine transformation */
  179468. #define PNG_EQUATION_LAST 4 /* Not a valid value */
  179469. /* These are for the sCAL chunk. These values should NOT be changed. */
  179470. #define PNG_SCALE_UNKNOWN 0 /* unknown unit (image scale) */
  179471. #define PNG_SCALE_METER 1 /* meters per pixel */
  179472. #define PNG_SCALE_RADIAN 2 /* radians per pixel */
  179473. #define PNG_SCALE_LAST 3 /* Not a valid value */
  179474. /* These are for the pHYs chunk. These values should NOT be changed. */
  179475. #define PNG_RESOLUTION_UNKNOWN 0 /* pixels/unknown unit (aspect ratio) */
  179476. #define PNG_RESOLUTION_METER 1 /* pixels/meter */
  179477. #define PNG_RESOLUTION_LAST 2 /* Not a valid value */
  179478. /* These are for the sRGB chunk. These values should NOT be changed. */
  179479. #define PNG_sRGB_INTENT_PERCEPTUAL 0
  179480. #define PNG_sRGB_INTENT_RELATIVE 1
  179481. #define PNG_sRGB_INTENT_SATURATION 2
  179482. #define PNG_sRGB_INTENT_ABSOLUTE 3
  179483. #define PNG_sRGB_INTENT_LAST 4 /* Not a valid value */
  179484. /* This is for text chunks */
  179485. #define PNG_KEYWORD_MAX_LENGTH 79
  179486. /* Maximum number of entries in PLTE/sPLT/tRNS arrays */
  179487. #define PNG_MAX_PALETTE_LENGTH 256
  179488. /* These determine if an ancillary chunk's data has been successfully read
  179489. * from the PNG header, or if the application has filled in the corresponding
  179490. * data in the info_struct to be written into the output file. The values
  179491. * of the PNG_INFO_<chunk> defines should NOT be changed.
  179492. */
  179493. #define PNG_INFO_gAMA 0x0001
  179494. #define PNG_INFO_sBIT 0x0002
  179495. #define PNG_INFO_cHRM 0x0004
  179496. #define PNG_INFO_PLTE 0x0008
  179497. #define PNG_INFO_tRNS 0x0010
  179498. #define PNG_INFO_bKGD 0x0020
  179499. #define PNG_INFO_hIST 0x0040
  179500. #define PNG_INFO_pHYs 0x0080
  179501. #define PNG_INFO_oFFs 0x0100
  179502. #define PNG_INFO_tIME 0x0200
  179503. #define PNG_INFO_pCAL 0x0400
  179504. #define PNG_INFO_sRGB 0x0800 /* GR-P, 0.96a */
  179505. #define PNG_INFO_iCCP 0x1000 /* ESR, 1.0.6 */
  179506. #define PNG_INFO_sPLT 0x2000 /* ESR, 1.0.6 */
  179507. #define PNG_INFO_sCAL 0x4000 /* ESR, 1.0.6 */
  179508. #define PNG_INFO_IDAT 0x8000L /* ESR, 1.0.6 */
  179509. /* This is used for the transformation routines, as some of them
  179510. * change these values for the row. It also should enable using
  179511. * the routines for other purposes.
  179512. */
  179513. typedef struct png_row_info_struct
  179514. {
  179515. png_uint_32 width; /* width of row */
  179516. png_uint_32 rowbytes; /* number of bytes in row */
  179517. png_byte color_type; /* color type of row */
  179518. png_byte bit_depth; /* bit depth of row */
  179519. png_byte channels; /* number of channels (1, 2, 3, or 4) */
  179520. png_byte pixel_depth; /* bits per pixel (depth * channels) */
  179521. } png_row_info;
  179522. typedef png_row_info FAR * png_row_infop;
  179523. typedef png_row_info FAR * FAR * png_row_infopp;
  179524. /* These are the function types for the I/O functions and for the functions
  179525. * that allow the user to override the default I/O functions with his or her
  179526. * own. The png_error_ptr type should match that of user-supplied warning
  179527. * and error functions, while the png_rw_ptr type should match that of the
  179528. * user read/write data functions.
  179529. */
  179530. typedef struct png_struct_def png_struct;
  179531. typedef png_struct FAR * png_structp;
  179532. typedef void (PNGAPI *png_error_ptr) PNGARG((png_structp, png_const_charp));
  179533. typedef void (PNGAPI *png_rw_ptr) PNGARG((png_structp, png_bytep, png_size_t));
  179534. typedef void (PNGAPI *png_flush_ptr) PNGARG((png_structp));
  179535. typedef void (PNGAPI *png_read_status_ptr) PNGARG((png_structp, png_uint_32,
  179536. int));
  179537. typedef void (PNGAPI *png_write_status_ptr) PNGARG((png_structp, png_uint_32,
  179538. int));
  179539. #ifdef PNG_PROGRESSIVE_READ_SUPPORTED
  179540. typedef void (PNGAPI *png_progressive_info_ptr) PNGARG((png_structp, png_infop));
  179541. typedef void (PNGAPI *png_progressive_end_ptr) PNGARG((png_structp, png_infop));
  179542. typedef void (PNGAPI *png_progressive_row_ptr) PNGARG((png_structp, png_bytep,
  179543. png_uint_32, int));
  179544. #endif
  179545. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED) || \
  179546. defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED) || \
  179547. defined(PNG_LEGACY_SUPPORTED)
  179548. typedef void (PNGAPI *png_user_transform_ptr) PNGARG((png_structp,
  179549. png_row_infop, png_bytep));
  179550. #endif
  179551. #if defined(PNG_USER_CHUNKS_SUPPORTED)
  179552. typedef int (PNGAPI *png_user_chunk_ptr) PNGARG((png_structp, png_unknown_chunkp));
  179553. #endif
  179554. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  179555. typedef void (PNGAPI *png_unknown_chunk_ptr) PNGARG((png_structp));
  179556. #endif
  179557. /* Transform masks for the high-level interface */
  179558. #define PNG_TRANSFORM_IDENTITY 0x0000 /* read and write */
  179559. #define PNG_TRANSFORM_STRIP_16 0x0001 /* read only */
  179560. #define PNG_TRANSFORM_STRIP_ALPHA 0x0002 /* read only */
  179561. #define PNG_TRANSFORM_PACKING 0x0004 /* read and write */
  179562. #define PNG_TRANSFORM_PACKSWAP 0x0008 /* read and write */
  179563. #define PNG_TRANSFORM_EXPAND 0x0010 /* read only */
  179564. #define PNG_TRANSFORM_INVERT_MONO 0x0020 /* read and write */
  179565. #define PNG_TRANSFORM_SHIFT 0x0040 /* read and write */
  179566. #define PNG_TRANSFORM_BGR 0x0080 /* read and write */
  179567. #define PNG_TRANSFORM_SWAP_ALPHA 0x0100 /* read and write */
  179568. #define PNG_TRANSFORM_SWAP_ENDIAN 0x0200 /* read and write */
  179569. #define PNG_TRANSFORM_INVERT_ALPHA 0x0400 /* read and write */
  179570. #define PNG_TRANSFORM_STRIP_FILLER 0x0800 /* WRITE only */
  179571. /* Flags for MNG supported features */
  179572. #define PNG_FLAG_MNG_EMPTY_PLTE 0x01
  179573. #define PNG_FLAG_MNG_FILTER_64 0x04
  179574. #define PNG_ALL_MNG_FEATURES 0x05
  179575. typedef png_voidp (*png_malloc_ptr) PNGARG((png_structp, png_size_t));
  179576. typedef void (*png_free_ptr) PNGARG((png_structp, png_voidp));
  179577. /* The structure that holds the information to read and write PNG files.
  179578. * The only people who need to care about what is inside of this are the
  179579. * people who will be modifying the library for their own special needs.
  179580. * It should NOT be accessed directly by an application, except to store
  179581. * the jmp_buf.
  179582. */
  179583. struct png_struct_def
  179584. {
  179585. #ifdef PNG_SETJMP_SUPPORTED
  179586. jmp_buf jmpbuf; /* used in png_error */
  179587. #endif
  179588. png_error_ptr error_fn; /* function for printing errors and aborting */
  179589. png_error_ptr warning_fn; /* function for printing warnings */
  179590. png_voidp error_ptr; /* user supplied struct for error functions */
  179591. png_rw_ptr write_data_fn; /* function for writing output data */
  179592. png_rw_ptr read_data_fn; /* function for reading input data */
  179593. png_voidp io_ptr; /* ptr to application struct for I/O functions */
  179594. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED)
  179595. png_user_transform_ptr read_user_transform_fn; /* user read transform */
  179596. #endif
  179597. #if defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED)
  179598. png_user_transform_ptr write_user_transform_fn; /* user write transform */
  179599. #endif
  179600. /* These were added in libpng-1.0.2 */
  179601. #if defined(PNG_USER_TRANSFORM_PTR_SUPPORTED)
  179602. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED) || \
  179603. defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED)
  179604. png_voidp user_transform_ptr; /* user supplied struct for user transform */
  179605. png_byte user_transform_depth; /* bit depth of user transformed pixels */
  179606. png_byte user_transform_channels; /* channels in user transformed pixels */
  179607. #endif
  179608. #endif
  179609. png_uint_32 mode; /* tells us where we are in the PNG file */
  179610. png_uint_32 flags; /* flags indicating various things to libpng */
  179611. png_uint_32 transformations; /* which transformations to perform */
  179612. z_stream zstream; /* pointer to decompression structure (below) */
  179613. png_bytep zbuf; /* buffer for zlib */
  179614. png_size_t zbuf_size; /* size of zbuf */
  179615. int zlib_level; /* holds zlib compression level */
  179616. int zlib_method; /* holds zlib compression method */
  179617. int zlib_window_bits; /* holds zlib compression window bits */
  179618. int zlib_mem_level; /* holds zlib compression memory level */
  179619. int zlib_strategy; /* holds zlib compression strategy */
  179620. png_uint_32 width; /* width of image in pixels */
  179621. png_uint_32 height; /* height of image in pixels */
  179622. png_uint_32 num_rows; /* number of rows in current pass */
  179623. png_uint_32 usr_width; /* width of row at start of write */
  179624. png_uint_32 rowbytes; /* size of row in bytes */
  179625. png_uint_32 irowbytes; /* size of current interlaced row in bytes */
  179626. png_uint_32 iwidth; /* width of current interlaced row in pixels */
  179627. png_uint_32 row_number; /* current row in interlace pass */
  179628. png_bytep prev_row; /* buffer to save previous (unfiltered) row */
  179629. png_bytep row_buf; /* buffer to save current (unfiltered) row */
  179630. png_bytep sub_row; /* buffer to save "sub" row when filtering */
  179631. png_bytep up_row; /* buffer to save "up" row when filtering */
  179632. png_bytep avg_row; /* buffer to save "avg" row when filtering */
  179633. png_bytep paeth_row; /* buffer to save "Paeth" row when filtering */
  179634. png_row_info row_info; /* used for transformation routines */
  179635. png_uint_32 idat_size; /* current IDAT size for read */
  179636. png_uint_32 crc; /* current chunk CRC value */
  179637. png_colorp palette; /* palette from the input file */
  179638. png_uint_16 num_palette; /* number of color entries in palette */
  179639. png_uint_16 num_trans; /* number of transparency values */
  179640. png_byte chunk_name[5]; /* null-terminated name of current chunk */
  179641. png_byte compression; /* file compression type (always 0) */
  179642. png_byte filter; /* file filter type (always 0) */
  179643. png_byte interlaced; /* PNG_INTERLACE_NONE, PNG_INTERLACE_ADAM7 */
  179644. png_byte pass; /* current interlace pass (0 - 6) */
  179645. png_byte do_filter; /* row filter flags (see PNG_FILTER_ below ) */
  179646. png_byte color_type; /* color type of file */
  179647. png_byte bit_depth; /* bit depth of file */
  179648. png_byte usr_bit_depth; /* bit depth of users row */
  179649. png_byte pixel_depth; /* number of bits per pixel */
  179650. png_byte channels; /* number of channels in file */
  179651. png_byte usr_channels; /* channels at start of write */
  179652. png_byte sig_bytes; /* magic bytes read/written from start of file */
  179653. #if defined(PNG_READ_FILLER_SUPPORTED) || defined(PNG_WRITE_FILLER_SUPPORTED)
  179654. #ifdef PNG_LEGACY_SUPPORTED
  179655. png_byte filler; /* filler byte for pixel expansion */
  179656. #else
  179657. png_uint_16 filler; /* filler bytes for pixel expansion */
  179658. #endif
  179659. #endif
  179660. #if defined(PNG_bKGD_SUPPORTED)
  179661. png_byte background_gamma_type;
  179662. # ifdef PNG_FLOATING_POINT_SUPPORTED
  179663. float background_gamma;
  179664. # endif
  179665. png_color_16 background; /* background color in screen gamma space */
  179666. #if defined(PNG_READ_GAMMA_SUPPORTED)
  179667. png_color_16 background_1; /* background normalized to gamma 1.0 */
  179668. #endif
  179669. #endif /* PNG_bKGD_SUPPORTED */
  179670. #if defined(PNG_WRITE_FLUSH_SUPPORTED)
  179671. png_flush_ptr output_flush_fn;/* Function for flushing output */
  179672. png_uint_32 flush_dist; /* how many rows apart to flush, 0 - no flush */
  179673. png_uint_32 flush_rows; /* number of rows written since last flush */
  179674. #endif
  179675. #if defined(PNG_READ_GAMMA_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
  179676. int gamma_shift; /* number of "insignificant" bits 16-bit gamma */
  179677. #ifdef PNG_FLOATING_POINT_SUPPORTED
  179678. float gamma; /* file gamma value */
  179679. float screen_gamma; /* screen gamma value (display_exponent) */
  179680. #endif
  179681. #endif
  179682. #if defined(PNG_READ_GAMMA_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
  179683. png_bytep gamma_table; /* gamma table for 8-bit depth files */
  179684. png_bytep gamma_from_1; /* converts from 1.0 to screen */
  179685. png_bytep gamma_to_1; /* converts from file to 1.0 */
  179686. png_uint_16pp gamma_16_table; /* gamma table for 16-bit depth files */
  179687. png_uint_16pp gamma_16_from_1; /* converts from 1.0 to screen */
  179688. png_uint_16pp gamma_16_to_1; /* converts from file to 1.0 */
  179689. #endif
  179690. #if defined(PNG_READ_GAMMA_SUPPORTED) || defined(PNG_sBIT_SUPPORTED)
  179691. png_color_8 sig_bit; /* significant bits in each available channel */
  179692. #endif
  179693. #if defined(PNG_READ_SHIFT_SUPPORTED) || defined(PNG_WRITE_SHIFT_SUPPORTED)
  179694. png_color_8 shift; /* shift for significant bit tranformation */
  179695. #endif
  179696. #if defined(PNG_tRNS_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED) \
  179697. || defined(PNG_READ_EXPAND_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
  179698. png_bytep trans; /* transparency values for paletted files */
  179699. png_color_16 trans_values; /* transparency values for non-paletted files */
  179700. #endif
  179701. png_read_status_ptr read_row_fn; /* called after each row is decoded */
  179702. png_write_status_ptr write_row_fn; /* called after each row is encoded */
  179703. #ifdef PNG_PROGRESSIVE_READ_SUPPORTED
  179704. png_progressive_info_ptr info_fn; /* called after header data fully read */
  179705. png_progressive_row_ptr row_fn; /* called after each prog. row is decoded */
  179706. png_progressive_end_ptr end_fn; /* called after image is complete */
  179707. png_bytep save_buffer_ptr; /* current location in save_buffer */
  179708. png_bytep save_buffer; /* buffer for previously read data */
  179709. png_bytep current_buffer_ptr; /* current location in current_buffer */
  179710. png_bytep current_buffer; /* buffer for recently used data */
  179711. png_uint_32 push_length; /* size of current input chunk */
  179712. png_uint_32 skip_length; /* bytes to skip in input data */
  179713. png_size_t save_buffer_size; /* amount of data now in save_buffer */
  179714. png_size_t save_buffer_max; /* total size of save_buffer */
  179715. png_size_t buffer_size; /* total amount of available input data */
  179716. png_size_t current_buffer_size; /* amount of data now in current_buffer */
  179717. int process_mode; /* what push library is currently doing */
  179718. int cur_palette; /* current push library palette index */
  179719. # if defined(PNG_TEXT_SUPPORTED)
  179720. png_size_t current_text_size; /* current size of text input data */
  179721. png_size_t current_text_left; /* how much text left to read in input */
  179722. png_charp current_text; /* current text chunk buffer */
  179723. png_charp current_text_ptr; /* current location in current_text */
  179724. # endif /* PNG_TEXT_SUPPORTED */
  179725. #endif /* PNG_PROGRESSIVE_READ_SUPPORTED */
  179726. #if defined(__TURBOC__) && !defined(_Windows) && !defined(__FLAT__)
  179727. /* for the Borland special 64K segment handler */
  179728. png_bytepp offset_table_ptr;
  179729. png_bytep offset_table;
  179730. png_uint_16 offset_table_number;
  179731. png_uint_16 offset_table_count;
  179732. png_uint_16 offset_table_count_free;
  179733. #endif
  179734. #if defined(PNG_READ_DITHER_SUPPORTED)
  179735. png_bytep palette_lookup; /* lookup table for dithering */
  179736. png_bytep dither_index; /* index translation for palette files */
  179737. #endif
  179738. #if defined(PNG_READ_DITHER_SUPPORTED) || defined(PNG_hIST_SUPPORTED)
  179739. png_uint_16p hist; /* histogram */
  179740. #endif
  179741. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  179742. png_byte heuristic_method; /* heuristic for row filter selection */
  179743. png_byte num_prev_filters; /* number of weights for previous rows */
  179744. png_bytep prev_filters; /* filter type(s) of previous row(s) */
  179745. png_uint_16p filter_weights; /* weight(s) for previous line(s) */
  179746. png_uint_16p inv_filter_weights; /* 1/weight(s) for previous line(s) */
  179747. png_uint_16p filter_costs; /* relative filter calculation cost */
  179748. png_uint_16p inv_filter_costs; /* 1/relative filter calculation cost */
  179749. #endif
  179750. #if defined(PNG_TIME_RFC1123_SUPPORTED)
  179751. png_charp time_buffer; /* String to hold RFC 1123 time text */
  179752. #endif
  179753. /* New members added in libpng-1.0.6 */
  179754. #ifdef PNG_FREE_ME_SUPPORTED
  179755. png_uint_32 free_me; /* flags items libpng is responsible for freeing */
  179756. #endif
  179757. #if defined(PNG_USER_CHUNKS_SUPPORTED)
  179758. png_voidp user_chunk_ptr;
  179759. png_user_chunk_ptr read_user_chunk_fn; /* user read chunk handler */
  179760. #endif
  179761. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  179762. int num_chunk_list;
  179763. png_bytep chunk_list;
  179764. #endif
  179765. /* New members added in libpng-1.0.3 */
  179766. #if defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
  179767. png_byte rgb_to_gray_status;
  179768. /* These were changed from png_byte in libpng-1.0.6 */
  179769. png_uint_16 rgb_to_gray_red_coeff;
  179770. png_uint_16 rgb_to_gray_green_coeff;
  179771. png_uint_16 rgb_to_gray_blue_coeff;
  179772. #endif
  179773. /* New member added in libpng-1.0.4 (renamed in 1.0.9) */
  179774. #if defined(PNG_MNG_FEATURES_SUPPORTED) || \
  179775. defined(PNG_READ_EMPTY_PLTE_SUPPORTED) || \
  179776. defined(PNG_WRITE_EMPTY_PLTE_SUPPORTED)
  179777. /* changed from png_byte to png_uint_32 at version 1.2.0 */
  179778. #ifdef PNG_1_0_X
  179779. png_byte mng_features_permitted;
  179780. #else
  179781. png_uint_32 mng_features_permitted;
  179782. #endif /* PNG_1_0_X */
  179783. #endif
  179784. /* New member added in libpng-1.0.7 */
  179785. #if defined(PNG_READ_GAMMA_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
  179786. png_fixed_point int_gamma;
  179787. #endif
  179788. /* New member added in libpng-1.0.9, ifdef'ed out in 1.0.12, enabled in 1.2.0 */
  179789. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  179790. png_byte filter_type;
  179791. #endif
  179792. #if defined(PNG_1_0_X)
  179793. /* New member added in libpng-1.0.10, ifdef'ed out in 1.2.0 */
  179794. png_uint_32 row_buf_size;
  179795. #endif
  179796. /* New members added in libpng-1.2.0 */
  179797. #if defined(PNG_ASSEMBLER_CODE_SUPPORTED)
  179798. # if !defined(PNG_1_0_X)
  179799. # if defined(PNG_MMX_CODE_SUPPORTED)
  179800. png_byte mmx_bitdepth_threshold;
  179801. png_uint_32 mmx_rowbytes_threshold;
  179802. # endif
  179803. png_uint_32 asm_flags;
  179804. # endif
  179805. #endif
  179806. /* New members added in libpng-1.0.2 but first enabled by default in 1.2.0 */
  179807. #ifdef PNG_USER_MEM_SUPPORTED
  179808. png_voidp mem_ptr; /* user supplied struct for mem functions */
  179809. png_malloc_ptr malloc_fn; /* function for allocating memory */
  179810. png_free_ptr free_fn; /* function for freeing memory */
  179811. #endif
  179812. /* New member added in libpng-1.0.13 and 1.2.0 */
  179813. png_bytep big_row_buf; /* buffer to save current (unfiltered) row */
  179814. #if defined(PNG_READ_DITHER_SUPPORTED)
  179815. /* The following three members were added at version 1.0.14 and 1.2.4 */
  179816. png_bytep dither_sort; /* working sort array */
  179817. png_bytep index_to_palette; /* where the original index currently is */
  179818. /* in the palette */
  179819. png_bytep palette_to_index; /* which original index points to this */
  179820. /* palette color */
  179821. #endif
  179822. /* New members added in libpng-1.0.16 and 1.2.6 */
  179823. png_byte compression_type;
  179824. #ifdef PNG_SET_USER_LIMITS_SUPPORTED
  179825. png_uint_32 user_width_max;
  179826. png_uint_32 user_height_max;
  179827. #endif
  179828. /* New member added in libpng-1.0.25 and 1.2.17 */
  179829. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  179830. /* storage for unknown chunk that the library doesn't recognize. */
  179831. png_unknown_chunk unknown_chunk;
  179832. #endif
  179833. };
  179834. /* This triggers a compiler error in png.c, if png.c and png.h
  179835. * do not agree upon the version number.
  179836. */
  179837. typedef png_structp version_1_2_21;
  179838. typedef png_struct FAR * FAR * png_structpp;
  179839. /* Here are the function definitions most commonly used. This is not
  179840. * the place to find out how to use libpng. See libpng.txt for the
  179841. * full explanation, see example.c for the summary. This just provides
  179842. * a simple one line description of the use of each function.
  179843. */
  179844. /* Returns the version number of the library */
  179845. extern PNG_EXPORT(png_uint_32,png_access_version_number) PNGARG((void));
  179846. /* Tell lib we have already handled the first <num_bytes> magic bytes.
  179847. * Handling more than 8 bytes from the beginning of the file is an error.
  179848. */
  179849. extern PNG_EXPORT(void,png_set_sig_bytes) PNGARG((png_structp png_ptr,
  179850. int num_bytes));
  179851. /* Check sig[start] through sig[start + num_to_check - 1] to see if it's a
  179852. * PNG file. Returns zero if the supplied bytes match the 8-byte PNG
  179853. * signature, and non-zero otherwise. Having num_to_check == 0 or
  179854. * start > 7 will always fail (ie return non-zero).
  179855. */
  179856. extern PNG_EXPORT(int,png_sig_cmp) PNGARG((png_bytep sig, png_size_t start,
  179857. png_size_t num_to_check));
  179858. /* Simple signature checking function. This is the same as calling
  179859. * png_check_sig(sig, n) := !png_sig_cmp(sig, 0, n).
  179860. */
  179861. extern PNG_EXPORT(int,png_check_sig) PNGARG((png_bytep sig, int num));
  179862. /* Allocate and initialize png_ptr struct for reading, and any other memory. */
  179863. extern PNG_EXPORT(png_structp,png_create_read_struct)
  179864. PNGARG((png_const_charp user_png_ver, png_voidp error_ptr,
  179865. png_error_ptr error_fn, png_error_ptr warn_fn));
  179866. /* Allocate and initialize png_ptr struct for writing, and any other memory */
  179867. extern PNG_EXPORT(png_structp,png_create_write_struct)
  179868. PNGARG((png_const_charp user_png_ver, png_voidp error_ptr,
  179869. png_error_ptr error_fn, png_error_ptr warn_fn));
  179870. #ifdef PNG_WRITE_SUPPORTED
  179871. extern PNG_EXPORT(png_uint_32,png_get_compression_buffer_size)
  179872. PNGARG((png_structp png_ptr));
  179873. #endif
  179874. #ifdef PNG_WRITE_SUPPORTED
  179875. extern PNG_EXPORT(void,png_set_compression_buffer_size)
  179876. PNGARG((png_structp png_ptr, png_uint_32 size));
  179877. #endif
  179878. /* Reset the compression stream */
  179879. extern PNG_EXPORT(int,png_reset_zstream) PNGARG((png_structp png_ptr));
  179880. /* New functions added in libpng-1.0.2 (not enabled by default until 1.2.0) */
  179881. #ifdef PNG_USER_MEM_SUPPORTED
  179882. extern PNG_EXPORT(png_structp,png_create_read_struct_2)
  179883. PNGARG((png_const_charp user_png_ver, png_voidp error_ptr,
  179884. png_error_ptr error_fn, png_error_ptr warn_fn, png_voidp mem_ptr,
  179885. png_malloc_ptr malloc_fn, png_free_ptr free_fn));
  179886. extern PNG_EXPORT(png_structp,png_create_write_struct_2)
  179887. PNGARG((png_const_charp user_png_ver, png_voidp error_ptr,
  179888. png_error_ptr error_fn, png_error_ptr warn_fn, png_voidp mem_ptr,
  179889. png_malloc_ptr malloc_fn, png_free_ptr free_fn));
  179890. #endif
  179891. /* Write a PNG chunk - size, type, (optional) data, CRC. */
  179892. extern PNG_EXPORT(void,png_write_chunk) PNGARG((png_structp png_ptr,
  179893. png_bytep chunk_name, png_bytep data, png_size_t length));
  179894. /* Write the start of a PNG chunk - length and chunk name. */
  179895. extern PNG_EXPORT(void,png_write_chunk_start) PNGARG((png_structp png_ptr,
  179896. png_bytep chunk_name, png_uint_32 length));
  179897. /* Write the data of a PNG chunk started with png_write_chunk_start(). */
  179898. extern PNG_EXPORT(void,png_write_chunk_data) PNGARG((png_structp png_ptr,
  179899. png_bytep data, png_size_t length));
  179900. /* Finish a chunk started with png_write_chunk_start() (includes CRC). */
  179901. extern PNG_EXPORT(void,png_write_chunk_end) PNGARG((png_structp png_ptr));
  179902. /* Allocate and initialize the info structure */
  179903. extern PNG_EXPORT(png_infop,png_create_info_struct)
  179904. PNGARG((png_structp png_ptr));
  179905. #if defined(PNG_1_0_X) || defined (PNG_1_2_X)
  179906. /* Initialize the info structure (old interface - DEPRECATED) */
  179907. extern PNG_EXPORT(void,png_info_init) PNGARG((png_infop info_ptr));
  179908. #undef png_info_init
  179909. #define png_info_init(info_ptr) png_info_init_3(&info_ptr,\
  179910. png_sizeof(png_info));
  179911. #endif
  179912. extern PNG_EXPORT(void,png_info_init_3) PNGARG((png_infopp info_ptr,
  179913. png_size_t png_info_struct_size));
  179914. /* Writes all the PNG information before the image. */
  179915. extern PNG_EXPORT(void,png_write_info_before_PLTE) PNGARG((png_structp png_ptr,
  179916. png_infop info_ptr));
  179917. extern PNG_EXPORT(void,png_write_info) PNGARG((png_structp png_ptr,
  179918. png_infop info_ptr));
  179919. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  179920. /* read the information before the actual image data. */
  179921. extern PNG_EXPORT(void,png_read_info) PNGARG((png_structp png_ptr,
  179922. png_infop info_ptr));
  179923. #endif
  179924. #if defined(PNG_TIME_RFC1123_SUPPORTED)
  179925. extern PNG_EXPORT(png_charp,png_convert_to_rfc1123)
  179926. PNGARG((png_structp png_ptr, png_timep ptime));
  179927. #endif
  179928. #if !defined(_WIN32_WCE)
  179929. /* "time.h" functions are not supported on WindowsCE */
  179930. #if defined(PNG_WRITE_tIME_SUPPORTED)
  179931. /* convert from a struct tm to png_time */
  179932. extern PNG_EXPORT(void,png_convert_from_struct_tm) PNGARG((png_timep ptime,
  179933. struct tm FAR * ttime));
  179934. /* convert from time_t to png_time. Uses gmtime() */
  179935. extern PNG_EXPORT(void,png_convert_from_time_t) PNGARG((png_timep ptime,
  179936. time_t ttime));
  179937. #endif /* PNG_WRITE_tIME_SUPPORTED */
  179938. #endif /* _WIN32_WCE */
  179939. #if defined(PNG_READ_EXPAND_SUPPORTED)
  179940. /* Expand data to 24-bit RGB, or 8-bit grayscale, with alpha if available. */
  179941. extern PNG_EXPORT(void,png_set_expand) PNGARG((png_structp png_ptr));
  179942. #if !defined(PNG_1_0_X)
  179943. extern PNG_EXPORT(void,png_set_expand_gray_1_2_4_to_8) PNGARG((png_structp
  179944. png_ptr));
  179945. #endif
  179946. extern PNG_EXPORT(void,png_set_palette_to_rgb) PNGARG((png_structp png_ptr));
  179947. extern PNG_EXPORT(void,png_set_tRNS_to_alpha) PNGARG((png_structp png_ptr));
  179948. #if defined(PNG_1_0_X) || defined (PNG_1_2_X)
  179949. /* Deprecated */
  179950. extern PNG_EXPORT(void,png_set_gray_1_2_4_to_8) PNGARG((png_structp png_ptr));
  179951. #endif
  179952. #endif
  179953. #if defined(PNG_READ_BGR_SUPPORTED) || defined(PNG_WRITE_BGR_SUPPORTED)
  179954. /* Use blue, green, red order for pixels. */
  179955. extern PNG_EXPORT(void,png_set_bgr) PNGARG((png_structp png_ptr));
  179956. #endif
  179957. #if defined(PNG_READ_GRAY_TO_RGB_SUPPORTED)
  179958. /* Expand the grayscale to 24-bit RGB if necessary. */
  179959. extern PNG_EXPORT(void,png_set_gray_to_rgb) PNGARG((png_structp png_ptr));
  179960. #endif
  179961. #if defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
  179962. /* Reduce RGB to grayscale. */
  179963. #ifdef PNG_FLOATING_POINT_SUPPORTED
  179964. extern PNG_EXPORT(void,png_set_rgb_to_gray) PNGARG((png_structp png_ptr,
  179965. int error_action, double red, double green ));
  179966. #endif
  179967. extern PNG_EXPORT(void,png_set_rgb_to_gray_fixed) PNGARG((png_structp png_ptr,
  179968. int error_action, png_fixed_point red, png_fixed_point green ));
  179969. extern PNG_EXPORT(png_byte,png_get_rgb_to_gray_status) PNGARG((png_structp
  179970. png_ptr));
  179971. #endif
  179972. extern PNG_EXPORT(void,png_build_grayscale_palette) PNGARG((int bit_depth,
  179973. png_colorp palette));
  179974. #if defined(PNG_READ_STRIP_ALPHA_SUPPORTED)
  179975. extern PNG_EXPORT(void,png_set_strip_alpha) PNGARG((png_structp png_ptr));
  179976. #endif
  179977. #if defined(PNG_READ_SWAP_ALPHA_SUPPORTED) || \
  179978. defined(PNG_WRITE_SWAP_ALPHA_SUPPORTED)
  179979. extern PNG_EXPORT(void,png_set_swap_alpha) PNGARG((png_structp png_ptr));
  179980. #endif
  179981. #if defined(PNG_READ_INVERT_ALPHA_SUPPORTED) || \
  179982. defined(PNG_WRITE_INVERT_ALPHA_SUPPORTED)
  179983. extern PNG_EXPORT(void,png_set_invert_alpha) PNGARG((png_structp png_ptr));
  179984. #endif
  179985. #if defined(PNG_READ_FILLER_SUPPORTED) || defined(PNG_WRITE_FILLER_SUPPORTED)
  179986. /* Add a filler byte to 8-bit Gray or 24-bit RGB images. */
  179987. extern PNG_EXPORT(void,png_set_filler) PNGARG((png_structp png_ptr,
  179988. png_uint_32 filler, int flags));
  179989. /* The values of the PNG_FILLER_ defines should NOT be changed */
  179990. #define PNG_FILLER_BEFORE 0
  179991. #define PNG_FILLER_AFTER 1
  179992. /* Add an alpha byte to 8-bit Gray or 24-bit RGB images. */
  179993. #if !defined(PNG_1_0_X)
  179994. extern PNG_EXPORT(void,png_set_add_alpha) PNGARG((png_structp png_ptr,
  179995. png_uint_32 filler, int flags));
  179996. #endif
  179997. #endif /* PNG_READ_FILLER_SUPPORTED || PNG_WRITE_FILLER_SUPPORTED */
  179998. #if defined(PNG_READ_SWAP_SUPPORTED) || defined(PNG_WRITE_SWAP_SUPPORTED)
  179999. /* Swap bytes in 16-bit depth files. */
  180000. extern PNG_EXPORT(void,png_set_swap) PNGARG((png_structp png_ptr));
  180001. #endif
  180002. #if defined(PNG_READ_PACK_SUPPORTED) || defined(PNG_WRITE_PACK_SUPPORTED)
  180003. /* Use 1 byte per pixel in 1, 2, or 4-bit depth files. */
  180004. extern PNG_EXPORT(void,png_set_packing) PNGARG((png_structp png_ptr));
  180005. #endif
  180006. #if defined(PNG_READ_PACKSWAP_SUPPORTED) || defined(PNG_WRITE_PACKSWAP_SUPPORTED)
  180007. /* Swap packing order of pixels in bytes. */
  180008. extern PNG_EXPORT(void,png_set_packswap) PNGARG((png_structp png_ptr));
  180009. #endif
  180010. #if defined(PNG_READ_SHIFT_SUPPORTED) || defined(PNG_WRITE_SHIFT_SUPPORTED)
  180011. /* Converts files to legal bit depths. */
  180012. extern PNG_EXPORT(void,png_set_shift) PNGARG((png_structp png_ptr,
  180013. png_color_8p true_bits));
  180014. #endif
  180015. #if defined(PNG_READ_INTERLACING_SUPPORTED) || \
  180016. defined(PNG_WRITE_INTERLACING_SUPPORTED)
  180017. /* Have the code handle the interlacing. Returns the number of passes. */
  180018. extern PNG_EXPORT(int,png_set_interlace_handling) PNGARG((png_structp png_ptr));
  180019. #endif
  180020. #if defined(PNG_READ_INVERT_SUPPORTED) || defined(PNG_WRITE_INVERT_SUPPORTED)
  180021. /* Invert monochrome files */
  180022. extern PNG_EXPORT(void,png_set_invert_mono) PNGARG((png_structp png_ptr));
  180023. #endif
  180024. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  180025. /* Handle alpha and tRNS by replacing with a background color. */
  180026. #ifdef PNG_FLOATING_POINT_SUPPORTED
  180027. extern PNG_EXPORT(void,png_set_background) PNGARG((png_structp png_ptr,
  180028. png_color_16p background_color, int background_gamma_code,
  180029. int need_expand, double background_gamma));
  180030. #endif
  180031. #define PNG_BACKGROUND_GAMMA_UNKNOWN 0
  180032. #define PNG_BACKGROUND_GAMMA_SCREEN 1
  180033. #define PNG_BACKGROUND_GAMMA_FILE 2
  180034. #define PNG_BACKGROUND_GAMMA_UNIQUE 3
  180035. #endif
  180036. #if defined(PNG_READ_16_TO_8_SUPPORTED)
  180037. /* strip the second byte of information from a 16-bit depth file. */
  180038. extern PNG_EXPORT(void,png_set_strip_16) PNGARG((png_structp png_ptr));
  180039. #endif
  180040. #if defined(PNG_READ_DITHER_SUPPORTED)
  180041. /* Turn on dithering, and reduce the palette to the number of colors available. */
  180042. extern PNG_EXPORT(void,png_set_dither) PNGARG((png_structp png_ptr,
  180043. png_colorp palette, int num_palette, int maximum_colors,
  180044. png_uint_16p histogram, int full_dither));
  180045. #endif
  180046. #if defined(PNG_READ_GAMMA_SUPPORTED)
  180047. /* Handle gamma correction. Screen_gamma=(display_exponent) */
  180048. #ifdef PNG_FLOATING_POINT_SUPPORTED
  180049. extern PNG_EXPORT(void,png_set_gamma) PNGARG((png_structp png_ptr,
  180050. double screen_gamma, double default_file_gamma));
  180051. #endif
  180052. #endif
  180053. #if defined(PNG_1_0_X) || defined (PNG_1_2_X)
  180054. #if defined(PNG_READ_EMPTY_PLTE_SUPPORTED) || \
  180055. defined(PNG_WRITE_EMPTY_PLTE_SUPPORTED)
  180056. /* Permit or disallow empty PLTE (0: not permitted, 1: permitted) */
  180057. /* Deprecated and will be removed. Use png_permit_mng_features() instead. */
  180058. extern PNG_EXPORT(void,png_permit_empty_plte) PNGARG((png_structp png_ptr,
  180059. int empty_plte_permitted));
  180060. #endif
  180061. #endif
  180062. #if defined(PNG_WRITE_FLUSH_SUPPORTED)
  180063. /* Set how many lines between output flushes - 0 for no flushing */
  180064. extern PNG_EXPORT(void,png_set_flush) PNGARG((png_structp png_ptr, int nrows));
  180065. /* Flush the current PNG output buffer */
  180066. extern PNG_EXPORT(void,png_write_flush) PNGARG((png_structp png_ptr));
  180067. #endif
  180068. /* optional update palette with requested transformations */
  180069. extern PNG_EXPORT(void,png_start_read_image) PNGARG((png_structp png_ptr));
  180070. /* optional call to update the users info structure */
  180071. extern PNG_EXPORT(void,png_read_update_info) PNGARG((png_structp png_ptr,
  180072. png_infop info_ptr));
  180073. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  180074. /* read one or more rows of image data. */
  180075. extern PNG_EXPORT(void,png_read_rows) PNGARG((png_structp png_ptr,
  180076. png_bytepp row, png_bytepp display_row, png_uint_32 num_rows));
  180077. #endif
  180078. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  180079. /* read a row of data. */
  180080. extern PNG_EXPORT(void,png_read_row) PNGARG((png_structp png_ptr,
  180081. png_bytep row,
  180082. png_bytep display_row));
  180083. #endif
  180084. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  180085. /* read the whole image into memory at once. */
  180086. extern PNG_EXPORT(void,png_read_image) PNGARG((png_structp png_ptr,
  180087. png_bytepp image));
  180088. #endif
  180089. /* write a row of image data */
  180090. extern PNG_EXPORT(void,png_write_row) PNGARG((png_structp png_ptr,
  180091. png_bytep row));
  180092. /* write a few rows of image data */
  180093. extern PNG_EXPORT(void,png_write_rows) PNGARG((png_structp png_ptr,
  180094. png_bytepp row, png_uint_32 num_rows));
  180095. /* write the image data */
  180096. extern PNG_EXPORT(void,png_write_image) PNGARG((png_structp png_ptr,
  180097. png_bytepp image));
  180098. /* writes the end of the PNG file. */
  180099. extern PNG_EXPORT(void,png_write_end) PNGARG((png_structp png_ptr,
  180100. png_infop info_ptr));
  180101. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  180102. /* read the end of the PNG file. */
  180103. extern PNG_EXPORT(void,png_read_end) PNGARG((png_structp png_ptr,
  180104. png_infop info_ptr));
  180105. #endif
  180106. /* free any memory associated with the png_info_struct */
  180107. extern PNG_EXPORT(void,png_destroy_info_struct) PNGARG((png_structp png_ptr,
  180108. png_infopp info_ptr_ptr));
  180109. /* free any memory associated with the png_struct and the png_info_structs */
  180110. extern PNG_EXPORT(void,png_destroy_read_struct) PNGARG((png_structpp
  180111. png_ptr_ptr, png_infopp info_ptr_ptr, png_infopp end_info_ptr_ptr));
  180112. /* free all memory used by the read (old method - NOT DLL EXPORTED) */
  180113. extern void png_read_destroy PNGARG((png_structp png_ptr, png_infop info_ptr,
  180114. png_infop end_info_ptr));
  180115. /* free any memory associated with the png_struct and the png_info_structs */
  180116. extern PNG_EXPORT(void,png_destroy_write_struct)
  180117. PNGARG((png_structpp png_ptr_ptr, png_infopp info_ptr_ptr));
  180118. /* free any memory used in png_ptr struct (old method - NOT DLL EXPORTED) */
  180119. extern void png_write_destroy PNGARG((png_structp png_ptr));
  180120. /* set the libpng method of handling chunk CRC errors */
  180121. extern PNG_EXPORT(void,png_set_crc_action) PNGARG((png_structp png_ptr,
  180122. int crit_action, int ancil_action));
  180123. /* Values for png_set_crc_action() to say how to handle CRC errors in
  180124. * ancillary and critical chunks, and whether to use the data contained
  180125. * therein. Note that it is impossible to "discard" data in a critical
  180126. * chunk. For versions prior to 0.90, the action was always error/quit,
  180127. * whereas in version 0.90 and later, the action for CRC errors in ancillary
  180128. * chunks is warn/discard. These values should NOT be changed.
  180129. *
  180130. * value action:critical action:ancillary
  180131. */
  180132. #define PNG_CRC_DEFAULT 0 /* error/quit warn/discard data */
  180133. #define PNG_CRC_ERROR_QUIT 1 /* error/quit error/quit */
  180134. #define PNG_CRC_WARN_DISCARD 2 /* (INVALID) warn/discard data */
  180135. #define PNG_CRC_WARN_USE 3 /* warn/use data warn/use data */
  180136. #define PNG_CRC_QUIET_USE 4 /* quiet/use data quiet/use data */
  180137. #define PNG_CRC_NO_CHANGE 5 /* use current value use current value */
  180138. /* These functions give the user control over the scan-line filtering in
  180139. * libpng and the compression methods used by zlib. These functions are
  180140. * mainly useful for testing, as the defaults should work with most users.
  180141. * Those users who are tight on memory or want faster performance at the
  180142. * expense of compression can modify them. See the compression library
  180143. * header file (zlib.h) for an explination of the compression functions.
  180144. */
  180145. /* set the filtering method(s) used by libpng. Currently, the only valid
  180146. * value for "method" is 0.
  180147. */
  180148. extern PNG_EXPORT(void,png_set_filter) PNGARG((png_structp png_ptr, int method,
  180149. int filters));
  180150. /* Flags for png_set_filter() to say which filters to use. The flags
  180151. * are chosen so that they don't conflict with real filter types
  180152. * below, in case they are supplied instead of the #defined constants.
  180153. * These values should NOT be changed.
  180154. */
  180155. #define PNG_NO_FILTERS 0x00
  180156. #define PNG_FILTER_NONE 0x08
  180157. #define PNG_FILTER_SUB 0x10
  180158. #define PNG_FILTER_UP 0x20
  180159. #define PNG_FILTER_AVG 0x40
  180160. #define PNG_FILTER_PAETH 0x80
  180161. #define PNG_ALL_FILTERS (PNG_FILTER_NONE | PNG_FILTER_SUB | PNG_FILTER_UP | \
  180162. PNG_FILTER_AVG | PNG_FILTER_PAETH)
  180163. /* Filter values (not flags) - used in pngwrite.c, pngwutil.c for now.
  180164. * These defines should NOT be changed.
  180165. */
  180166. #define PNG_FILTER_VALUE_NONE 0
  180167. #define PNG_FILTER_VALUE_SUB 1
  180168. #define PNG_FILTER_VALUE_UP 2
  180169. #define PNG_FILTER_VALUE_AVG 3
  180170. #define PNG_FILTER_VALUE_PAETH 4
  180171. #define PNG_FILTER_VALUE_LAST 5
  180172. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED) /* EXPERIMENTAL */
  180173. /* The "heuristic_method" is given by one of the PNG_FILTER_HEURISTIC_
  180174. * defines, either the default (minimum-sum-of-absolute-differences), or
  180175. * the experimental method (weighted-minimum-sum-of-absolute-differences).
  180176. *
  180177. * Weights are factors >= 1.0, indicating how important it is to keep the
  180178. * filter type consistent between rows. Larger numbers mean the current
  180179. * filter is that many times as likely to be the same as the "num_weights"
  180180. * previous filters. This is cumulative for each previous row with a weight.
  180181. * There needs to be "num_weights" values in "filter_weights", or it can be
  180182. * NULL if the weights aren't being specified. Weights have no influence on
  180183. * the selection of the first row filter. Well chosen weights can (in theory)
  180184. * improve the compression for a given image.
  180185. *
  180186. * Costs are factors >= 1.0 indicating the relative decoding costs of a
  180187. * filter type. Higher costs indicate more decoding expense, and are
  180188. * therefore less likely to be selected over a filter with lower computational
  180189. * costs. There needs to be a value in "filter_costs" for each valid filter
  180190. * type (given by PNG_FILTER_VALUE_LAST), or it can be NULL if you aren't
  180191. * setting the costs. Costs try to improve the speed of decompression without
  180192. * unduly increasing the compressed image size.
  180193. *
  180194. * A negative weight or cost indicates the default value is to be used, and
  180195. * values in the range [0.0, 1.0) indicate the value is to remain unchanged.
  180196. * The default values for both weights and costs are currently 1.0, but may
  180197. * change if good general weighting/cost heuristics can be found. If both
  180198. * the weights and costs are set to 1.0, this degenerates the WEIGHTED method
  180199. * to the UNWEIGHTED method, but with added encoding time/computation.
  180200. */
  180201. #ifdef PNG_FLOATING_POINT_SUPPORTED
  180202. extern PNG_EXPORT(void,png_set_filter_heuristics) PNGARG((png_structp png_ptr,
  180203. int heuristic_method, int num_weights, png_doublep filter_weights,
  180204. png_doublep filter_costs));
  180205. #endif
  180206. #endif /* PNG_WRITE_WEIGHTED_FILTER_SUPPORTED */
  180207. /* Heuristic used for row filter selection. These defines should NOT be
  180208. * changed.
  180209. */
  180210. #define PNG_FILTER_HEURISTIC_DEFAULT 0 /* Currently "UNWEIGHTED" */
  180211. #define PNG_FILTER_HEURISTIC_UNWEIGHTED 1 /* Used by libpng < 0.95 */
  180212. #define PNG_FILTER_HEURISTIC_WEIGHTED 2 /* Experimental feature */
  180213. #define PNG_FILTER_HEURISTIC_LAST 3 /* Not a valid value */
  180214. /* Set the library compression level. Currently, valid values range from
  180215. * 0 - 9, corresponding directly to the zlib compression levels 0 - 9
  180216. * (0 - no compression, 9 - "maximal" compression). Note that tests have
  180217. * shown that zlib compression levels 3-6 usually perform as well as level 9
  180218. * for PNG images, and do considerably fewer caclulations. In the future,
  180219. * these values may not correspond directly to the zlib compression levels.
  180220. */
  180221. extern PNG_EXPORT(void,png_set_compression_level) PNGARG((png_structp png_ptr,
  180222. int level));
  180223. extern PNG_EXPORT(void,png_set_compression_mem_level)
  180224. PNGARG((png_structp png_ptr, int mem_level));
  180225. extern PNG_EXPORT(void,png_set_compression_strategy)
  180226. PNGARG((png_structp png_ptr, int strategy));
  180227. extern PNG_EXPORT(void,png_set_compression_window_bits)
  180228. PNGARG((png_structp png_ptr, int window_bits));
  180229. extern PNG_EXPORT(void,png_set_compression_method) PNGARG((png_structp png_ptr,
  180230. int method));
  180231. /* These next functions are called for input/output, memory, and error
  180232. * handling. They are in the file pngrio.c, pngwio.c, and pngerror.c,
  180233. * and call standard C I/O routines such as fread(), fwrite(), and
  180234. * fprintf(). These functions can be made to use other I/O routines
  180235. * at run time for those applications that need to handle I/O in a
  180236. * different manner by calling png_set_???_fn(). See libpng.txt for
  180237. * more information.
  180238. */
  180239. #if !defined(PNG_NO_STDIO)
  180240. /* Initialize the input/output for the PNG file to the default functions. */
  180241. extern PNG_EXPORT(void,png_init_io) PNGARG((png_structp png_ptr, png_FILE_p fp));
  180242. #endif
  180243. /* Replace the (error and abort), and warning functions with user
  180244. * supplied functions. If no messages are to be printed you must still
  180245. * write and use replacement functions. The replacement error_fn should
  180246. * still do a longjmp to the last setjmp location if you are using this
  180247. * method of error handling. If error_fn or warning_fn is NULL, the
  180248. * default function will be used.
  180249. */
  180250. extern PNG_EXPORT(void,png_set_error_fn) PNGARG((png_structp png_ptr,
  180251. png_voidp error_ptr, png_error_ptr error_fn, png_error_ptr warning_fn));
  180252. /* Return the user pointer associated with the error functions */
  180253. extern PNG_EXPORT(png_voidp,png_get_error_ptr) PNGARG((png_structp png_ptr));
  180254. /* Replace the default data output functions with a user supplied one(s).
  180255. * If buffered output is not used, then output_flush_fn can be set to NULL.
  180256. * If PNG_WRITE_FLUSH_SUPPORTED is not defined at libpng compile time
  180257. * output_flush_fn will be ignored (and thus can be NULL).
  180258. */
  180259. extern PNG_EXPORT(void,png_set_write_fn) PNGARG((png_structp png_ptr,
  180260. png_voidp io_ptr, png_rw_ptr write_data_fn, png_flush_ptr output_flush_fn));
  180261. /* Replace the default data input function with a user supplied one. */
  180262. extern PNG_EXPORT(void,png_set_read_fn) PNGARG((png_structp png_ptr,
  180263. png_voidp io_ptr, png_rw_ptr read_data_fn));
  180264. /* Return the user pointer associated with the I/O functions */
  180265. extern PNG_EXPORT(png_voidp,png_get_io_ptr) PNGARG((png_structp png_ptr));
  180266. extern PNG_EXPORT(void,png_set_read_status_fn) PNGARG((png_structp png_ptr,
  180267. png_read_status_ptr read_row_fn));
  180268. extern PNG_EXPORT(void,png_set_write_status_fn) PNGARG((png_structp png_ptr,
  180269. png_write_status_ptr write_row_fn));
  180270. #ifdef PNG_USER_MEM_SUPPORTED
  180271. /* Replace the default memory allocation functions with user supplied one(s). */
  180272. extern PNG_EXPORT(void,png_set_mem_fn) PNGARG((png_structp png_ptr,
  180273. png_voidp mem_ptr, png_malloc_ptr malloc_fn, png_free_ptr free_fn));
  180274. /* Return the user pointer associated with the memory functions */
  180275. extern PNG_EXPORT(png_voidp,png_get_mem_ptr) PNGARG((png_structp png_ptr));
  180276. #endif
  180277. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED) || \
  180278. defined(PNG_LEGACY_SUPPORTED)
  180279. extern PNG_EXPORT(void,png_set_read_user_transform_fn) PNGARG((png_structp
  180280. png_ptr, png_user_transform_ptr read_user_transform_fn));
  180281. #endif
  180282. #if defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED) || \
  180283. defined(PNG_LEGACY_SUPPORTED)
  180284. extern PNG_EXPORT(void,png_set_write_user_transform_fn) PNGARG((png_structp
  180285. png_ptr, png_user_transform_ptr write_user_transform_fn));
  180286. #endif
  180287. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED) || \
  180288. defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED) || \
  180289. defined(PNG_LEGACY_SUPPORTED)
  180290. extern PNG_EXPORT(void,png_set_user_transform_info) PNGARG((png_structp
  180291. png_ptr, png_voidp user_transform_ptr, int user_transform_depth,
  180292. int user_transform_channels));
  180293. /* Return the user pointer associated with the user transform functions */
  180294. extern PNG_EXPORT(png_voidp,png_get_user_transform_ptr)
  180295. PNGARG((png_structp png_ptr));
  180296. #endif
  180297. #ifdef PNG_USER_CHUNKS_SUPPORTED
  180298. extern PNG_EXPORT(void,png_set_read_user_chunk_fn) PNGARG((png_structp png_ptr,
  180299. png_voidp user_chunk_ptr, png_user_chunk_ptr read_user_chunk_fn));
  180300. extern PNG_EXPORT(png_voidp,png_get_user_chunk_ptr) PNGARG((png_structp
  180301. png_ptr));
  180302. #endif
  180303. #ifdef PNG_PROGRESSIVE_READ_SUPPORTED
  180304. /* Sets the function callbacks for the push reader, and a pointer to a
  180305. * user-defined structure available to the callback functions.
  180306. */
  180307. extern PNG_EXPORT(void,png_set_progressive_read_fn) PNGARG((png_structp png_ptr,
  180308. png_voidp progressive_ptr,
  180309. png_progressive_info_ptr info_fn, png_progressive_row_ptr row_fn,
  180310. png_progressive_end_ptr end_fn));
  180311. /* returns the user pointer associated with the push read functions */
  180312. extern PNG_EXPORT(png_voidp,png_get_progressive_ptr)
  180313. PNGARG((png_structp png_ptr));
  180314. /* function to be called when data becomes available */
  180315. extern PNG_EXPORT(void,png_process_data) PNGARG((png_structp png_ptr,
  180316. png_infop info_ptr, png_bytep buffer, png_size_t buffer_size));
  180317. /* function that combines rows. Not very much different than the
  180318. * png_combine_row() call. Is this even used?????
  180319. */
  180320. extern PNG_EXPORT(void,png_progressive_combine_row) PNGARG((png_structp png_ptr,
  180321. png_bytep old_row, png_bytep new_row));
  180322. #endif /* PNG_PROGRESSIVE_READ_SUPPORTED */
  180323. extern PNG_EXPORT(png_voidp,png_malloc) PNGARG((png_structp png_ptr,
  180324. png_uint_32 size));
  180325. #if defined(PNG_1_0_X)
  180326. # define png_malloc_warn png_malloc
  180327. #else
  180328. /* Added at libpng version 1.2.4 */
  180329. extern PNG_EXPORT(png_voidp,png_malloc_warn) PNGARG((png_structp png_ptr,
  180330. png_uint_32 size));
  180331. #endif
  180332. /* frees a pointer allocated by png_malloc() */
  180333. extern PNG_EXPORT(void,png_free) PNGARG((png_structp png_ptr, png_voidp ptr));
  180334. #if defined(PNG_1_0_X)
  180335. /* Function to allocate memory for zlib. */
  180336. extern PNG_EXPORT(voidpf,png_zalloc) PNGARG((voidpf png_ptr, uInt items,
  180337. uInt size));
  180338. /* Function to free memory for zlib */
  180339. extern PNG_EXPORT(void,png_zfree) PNGARG((voidpf png_ptr, voidpf ptr));
  180340. #endif
  180341. /* Free data that was allocated internally */
  180342. extern PNG_EXPORT(void,png_free_data) PNGARG((png_structp png_ptr,
  180343. png_infop info_ptr, png_uint_32 free_me, int num));
  180344. #ifdef PNG_FREE_ME_SUPPORTED
  180345. /* Reassign responsibility for freeing existing data, whether allocated
  180346. * by libpng or by the application */
  180347. extern PNG_EXPORT(void,png_data_freer) PNGARG((png_structp png_ptr,
  180348. png_infop info_ptr, int freer, png_uint_32 mask));
  180349. #endif
  180350. /* assignments for png_data_freer */
  180351. #define PNG_DESTROY_WILL_FREE_DATA 1
  180352. #define PNG_SET_WILL_FREE_DATA 1
  180353. #define PNG_USER_WILL_FREE_DATA 2
  180354. /* Flags for png_ptr->free_me and info_ptr->free_me */
  180355. #define PNG_FREE_HIST 0x0008
  180356. #define PNG_FREE_ICCP 0x0010
  180357. #define PNG_FREE_SPLT 0x0020
  180358. #define PNG_FREE_ROWS 0x0040
  180359. #define PNG_FREE_PCAL 0x0080
  180360. #define PNG_FREE_SCAL 0x0100
  180361. #define PNG_FREE_UNKN 0x0200
  180362. #define PNG_FREE_LIST 0x0400
  180363. #define PNG_FREE_PLTE 0x1000
  180364. #define PNG_FREE_TRNS 0x2000
  180365. #define PNG_FREE_TEXT 0x4000
  180366. #define PNG_FREE_ALL 0x7fff
  180367. #define PNG_FREE_MUL 0x4220 /* PNG_FREE_SPLT|PNG_FREE_TEXT|PNG_FREE_UNKN */
  180368. #ifdef PNG_USER_MEM_SUPPORTED
  180369. extern PNG_EXPORT(png_voidp,png_malloc_default) PNGARG((png_structp png_ptr,
  180370. png_uint_32 size));
  180371. extern PNG_EXPORT(void,png_free_default) PNGARG((png_structp png_ptr,
  180372. png_voidp ptr));
  180373. #endif
  180374. extern PNG_EXPORT(png_voidp,png_memcpy_check) PNGARG((png_structp png_ptr,
  180375. png_voidp s1, png_voidp s2, png_uint_32 size));
  180376. extern PNG_EXPORT(png_voidp,png_memset_check) PNGARG((png_structp png_ptr,
  180377. png_voidp s1, int value, png_uint_32 size));
  180378. #if defined(USE_FAR_KEYWORD) /* memory model conversion function */
  180379. extern void *png_far_to_near PNGARG((png_structp png_ptr,png_voidp ptr,
  180380. int check));
  180381. #endif /* USE_FAR_KEYWORD */
  180382. #ifndef PNG_NO_ERROR_TEXT
  180383. /* Fatal error in PNG image of libpng - can't continue */
  180384. extern PNG_EXPORT(void,png_error) PNGARG((png_structp png_ptr,
  180385. png_const_charp error_message));
  180386. /* The same, but the chunk name is prepended to the error string. */
  180387. extern PNG_EXPORT(void,png_chunk_error) PNGARG((png_structp png_ptr,
  180388. png_const_charp error_message));
  180389. #else
  180390. /* Fatal error in PNG image of libpng - can't continue */
  180391. extern PNG_EXPORT(void,png_err) PNGARG((png_structp png_ptr));
  180392. #endif
  180393. #ifndef PNG_NO_WARNINGS
  180394. /* Non-fatal error in libpng. Can continue, but may have a problem. */
  180395. extern PNG_EXPORT(void,png_warning) PNGARG((png_structp png_ptr,
  180396. png_const_charp warning_message));
  180397. #ifdef PNG_READ_SUPPORTED
  180398. /* Non-fatal error in libpng, chunk name is prepended to message. */
  180399. extern PNG_EXPORT(void,png_chunk_warning) PNGARG((png_structp png_ptr,
  180400. png_const_charp warning_message));
  180401. #endif /* PNG_READ_SUPPORTED */
  180402. #endif /* PNG_NO_WARNINGS */
  180403. /* The png_set_<chunk> functions are for storing values in the png_info_struct.
  180404. * Similarly, the png_get_<chunk> calls are used to read values from the
  180405. * png_info_struct, either storing the parameters in the passed variables, or
  180406. * setting pointers into the png_info_struct where the data is stored. The
  180407. * png_get_<chunk> functions return a non-zero value if the data was available
  180408. * in info_ptr, or return zero and do not change any of the parameters if the
  180409. * data was not available.
  180410. *
  180411. * These functions should be used instead of directly accessing png_info
  180412. * to avoid problems with future changes in the size and internal layout of
  180413. * png_info_struct.
  180414. */
  180415. /* Returns "flag" if chunk data is valid in info_ptr. */
  180416. extern PNG_EXPORT(png_uint_32,png_get_valid) PNGARG((png_structp png_ptr,
  180417. png_infop info_ptr, png_uint_32 flag));
  180418. /* Returns number of bytes needed to hold a transformed row. */
  180419. extern PNG_EXPORT(png_uint_32,png_get_rowbytes) PNGARG((png_structp png_ptr,
  180420. png_infop info_ptr));
  180421. #if defined(PNG_INFO_IMAGE_SUPPORTED)
  180422. /* Returns row_pointers, which is an array of pointers to scanlines that was
  180423. returned from png_read_png(). */
  180424. extern PNG_EXPORT(png_bytepp,png_get_rows) PNGARG((png_structp png_ptr,
  180425. png_infop info_ptr));
  180426. /* Set row_pointers, which is an array of pointers to scanlines for use
  180427. by png_write_png(). */
  180428. extern PNG_EXPORT(void,png_set_rows) PNGARG((png_structp png_ptr,
  180429. png_infop info_ptr, png_bytepp row_pointers));
  180430. #endif
  180431. /* Returns number of color channels in image. */
  180432. extern PNG_EXPORT(png_byte,png_get_channels) PNGARG((png_structp png_ptr,
  180433. png_infop info_ptr));
  180434. #ifdef PNG_EASY_ACCESS_SUPPORTED
  180435. /* Returns image width in pixels. */
  180436. extern PNG_EXPORT(png_uint_32, png_get_image_width) PNGARG((png_structp
  180437. png_ptr, png_infop info_ptr));
  180438. /* Returns image height in pixels. */
  180439. extern PNG_EXPORT(png_uint_32, png_get_image_height) PNGARG((png_structp
  180440. png_ptr, png_infop info_ptr));
  180441. /* Returns image bit_depth. */
  180442. extern PNG_EXPORT(png_byte, png_get_bit_depth) PNGARG((png_structp
  180443. png_ptr, png_infop info_ptr));
  180444. /* Returns image color_type. */
  180445. extern PNG_EXPORT(png_byte, png_get_color_type) PNGARG((png_structp
  180446. png_ptr, png_infop info_ptr));
  180447. /* Returns image filter_type. */
  180448. extern PNG_EXPORT(png_byte, png_get_filter_type) PNGARG((png_structp
  180449. png_ptr, png_infop info_ptr));
  180450. /* Returns image interlace_type. */
  180451. extern PNG_EXPORT(png_byte, png_get_interlace_type) PNGARG((png_structp
  180452. png_ptr, png_infop info_ptr));
  180453. /* Returns image compression_type. */
  180454. extern PNG_EXPORT(png_byte, png_get_compression_type) PNGARG((png_structp
  180455. png_ptr, png_infop info_ptr));
  180456. /* Returns image resolution in pixels per meter, from pHYs chunk data. */
  180457. extern PNG_EXPORT(png_uint_32, png_get_pixels_per_meter) PNGARG((png_structp
  180458. png_ptr, png_infop info_ptr));
  180459. extern PNG_EXPORT(png_uint_32, png_get_x_pixels_per_meter) PNGARG((png_structp
  180460. png_ptr, png_infop info_ptr));
  180461. extern PNG_EXPORT(png_uint_32, png_get_y_pixels_per_meter) PNGARG((png_structp
  180462. png_ptr, png_infop info_ptr));
  180463. /* Returns pixel aspect ratio, computed from pHYs chunk data. */
  180464. #ifdef PNG_FLOATING_POINT_SUPPORTED
  180465. extern PNG_EXPORT(float, png_get_pixel_aspect_ratio) PNGARG((png_structp
  180466. png_ptr, png_infop info_ptr));
  180467. #endif
  180468. /* Returns image x, y offset in pixels or microns, from oFFs chunk data. */
  180469. extern PNG_EXPORT(png_int_32, png_get_x_offset_pixels) PNGARG((png_structp
  180470. png_ptr, png_infop info_ptr));
  180471. extern PNG_EXPORT(png_int_32, png_get_y_offset_pixels) PNGARG((png_structp
  180472. png_ptr, png_infop info_ptr));
  180473. extern PNG_EXPORT(png_int_32, png_get_x_offset_microns) PNGARG((png_structp
  180474. png_ptr, png_infop info_ptr));
  180475. extern PNG_EXPORT(png_int_32, png_get_y_offset_microns) PNGARG((png_structp
  180476. png_ptr, png_infop info_ptr));
  180477. #endif /* PNG_EASY_ACCESS_SUPPORTED */
  180478. /* Returns pointer to signature string read from PNG header */
  180479. extern PNG_EXPORT(png_bytep,png_get_signature) PNGARG((png_structp png_ptr,
  180480. png_infop info_ptr));
  180481. #if defined(PNG_bKGD_SUPPORTED)
  180482. extern PNG_EXPORT(png_uint_32,png_get_bKGD) PNGARG((png_structp png_ptr,
  180483. png_infop info_ptr, png_color_16p *background));
  180484. #endif
  180485. #if defined(PNG_bKGD_SUPPORTED)
  180486. extern PNG_EXPORT(void,png_set_bKGD) PNGARG((png_structp png_ptr,
  180487. png_infop info_ptr, png_color_16p background));
  180488. #endif
  180489. #if defined(PNG_cHRM_SUPPORTED)
  180490. #ifdef PNG_FLOATING_POINT_SUPPORTED
  180491. extern PNG_EXPORT(png_uint_32,png_get_cHRM) PNGARG((png_structp png_ptr,
  180492. png_infop info_ptr, double *white_x, double *white_y, double *red_x,
  180493. double *red_y, double *green_x, double *green_y, double *blue_x,
  180494. double *blue_y));
  180495. #endif
  180496. #ifdef PNG_FIXED_POINT_SUPPORTED
  180497. extern PNG_EXPORT(png_uint_32,png_get_cHRM_fixed) PNGARG((png_structp png_ptr,
  180498. png_infop info_ptr, png_fixed_point *int_white_x, png_fixed_point
  180499. *int_white_y, png_fixed_point *int_red_x, png_fixed_point *int_red_y,
  180500. png_fixed_point *int_green_x, png_fixed_point *int_green_y, png_fixed_point
  180501. *int_blue_x, png_fixed_point *int_blue_y));
  180502. #endif
  180503. #endif
  180504. #if defined(PNG_cHRM_SUPPORTED)
  180505. #ifdef PNG_FLOATING_POINT_SUPPORTED
  180506. extern PNG_EXPORT(void,png_set_cHRM) PNGARG((png_structp png_ptr,
  180507. png_infop info_ptr, double white_x, double white_y, double red_x,
  180508. double red_y, double green_x, double green_y, double blue_x, double blue_y));
  180509. #endif
  180510. #ifdef PNG_FIXED_POINT_SUPPORTED
  180511. extern PNG_EXPORT(void,png_set_cHRM_fixed) PNGARG((png_structp png_ptr,
  180512. png_infop info_ptr, png_fixed_point int_white_x, png_fixed_point int_white_y,
  180513. png_fixed_point int_red_x, png_fixed_point int_red_y, png_fixed_point
  180514. int_green_x, png_fixed_point int_green_y, png_fixed_point int_blue_x,
  180515. png_fixed_point int_blue_y));
  180516. #endif
  180517. #endif
  180518. #if defined(PNG_gAMA_SUPPORTED)
  180519. #ifdef PNG_FLOATING_POINT_SUPPORTED
  180520. extern PNG_EXPORT(png_uint_32,png_get_gAMA) PNGARG((png_structp png_ptr,
  180521. png_infop info_ptr, double *file_gamma));
  180522. #endif
  180523. extern PNG_EXPORT(png_uint_32,png_get_gAMA_fixed) PNGARG((png_structp png_ptr,
  180524. png_infop info_ptr, png_fixed_point *int_file_gamma));
  180525. #endif
  180526. #if defined(PNG_gAMA_SUPPORTED)
  180527. #ifdef PNG_FLOATING_POINT_SUPPORTED
  180528. extern PNG_EXPORT(void,png_set_gAMA) PNGARG((png_structp png_ptr,
  180529. png_infop info_ptr, double file_gamma));
  180530. #endif
  180531. extern PNG_EXPORT(void,png_set_gAMA_fixed) PNGARG((png_structp png_ptr,
  180532. png_infop info_ptr, png_fixed_point int_file_gamma));
  180533. #endif
  180534. #if defined(PNG_hIST_SUPPORTED)
  180535. extern PNG_EXPORT(png_uint_32,png_get_hIST) PNGARG((png_structp png_ptr,
  180536. png_infop info_ptr, png_uint_16p *hist));
  180537. #endif
  180538. #if defined(PNG_hIST_SUPPORTED)
  180539. extern PNG_EXPORT(void,png_set_hIST) PNGARG((png_structp png_ptr,
  180540. png_infop info_ptr, png_uint_16p hist));
  180541. #endif
  180542. extern PNG_EXPORT(png_uint_32,png_get_IHDR) PNGARG((png_structp png_ptr,
  180543. png_infop info_ptr, png_uint_32 *width, png_uint_32 *height,
  180544. int *bit_depth, int *color_type, int *interlace_method,
  180545. int *compression_method, int *filter_method));
  180546. extern PNG_EXPORT(void,png_set_IHDR) PNGARG((png_structp png_ptr,
  180547. png_infop info_ptr, png_uint_32 width, png_uint_32 height, int bit_depth,
  180548. int color_type, int interlace_method, int compression_method,
  180549. int filter_method));
  180550. #if defined(PNG_oFFs_SUPPORTED)
  180551. extern PNG_EXPORT(png_uint_32,png_get_oFFs) PNGARG((png_structp png_ptr,
  180552. png_infop info_ptr, png_int_32 *offset_x, png_int_32 *offset_y,
  180553. int *unit_type));
  180554. #endif
  180555. #if defined(PNG_oFFs_SUPPORTED)
  180556. extern PNG_EXPORT(void,png_set_oFFs) PNGARG((png_structp png_ptr,
  180557. png_infop info_ptr, png_int_32 offset_x, png_int_32 offset_y,
  180558. int unit_type));
  180559. #endif
  180560. #if defined(PNG_pCAL_SUPPORTED)
  180561. extern PNG_EXPORT(png_uint_32,png_get_pCAL) PNGARG((png_structp png_ptr,
  180562. png_infop info_ptr, png_charp *purpose, png_int_32 *X0, png_int_32 *X1,
  180563. int *type, int *nparams, png_charp *units, png_charpp *params));
  180564. #endif
  180565. #if defined(PNG_pCAL_SUPPORTED)
  180566. extern PNG_EXPORT(void,png_set_pCAL) PNGARG((png_structp png_ptr,
  180567. png_infop info_ptr, png_charp purpose, png_int_32 X0, png_int_32 X1,
  180568. int type, int nparams, png_charp units, png_charpp params));
  180569. #endif
  180570. #if defined(PNG_pHYs_SUPPORTED)
  180571. extern PNG_EXPORT(png_uint_32,png_get_pHYs) PNGARG((png_structp png_ptr,
  180572. png_infop info_ptr, png_uint_32 *res_x, png_uint_32 *res_y, int *unit_type));
  180573. #endif
  180574. #if defined(PNG_pHYs_SUPPORTED)
  180575. extern PNG_EXPORT(void,png_set_pHYs) PNGARG((png_structp png_ptr,
  180576. png_infop info_ptr, png_uint_32 res_x, png_uint_32 res_y, int unit_type));
  180577. #endif
  180578. extern PNG_EXPORT(png_uint_32,png_get_PLTE) PNGARG((png_structp png_ptr,
  180579. png_infop info_ptr, png_colorp *palette, int *num_palette));
  180580. extern PNG_EXPORT(void,png_set_PLTE) PNGARG((png_structp png_ptr,
  180581. png_infop info_ptr, png_colorp palette, int num_palette));
  180582. #if defined(PNG_sBIT_SUPPORTED)
  180583. extern PNG_EXPORT(png_uint_32,png_get_sBIT) PNGARG((png_structp png_ptr,
  180584. png_infop info_ptr, png_color_8p *sig_bit));
  180585. #endif
  180586. #if defined(PNG_sBIT_SUPPORTED)
  180587. extern PNG_EXPORT(void,png_set_sBIT) PNGARG((png_structp png_ptr,
  180588. png_infop info_ptr, png_color_8p sig_bit));
  180589. #endif
  180590. #if defined(PNG_sRGB_SUPPORTED)
  180591. extern PNG_EXPORT(png_uint_32,png_get_sRGB) PNGARG((png_structp png_ptr,
  180592. png_infop info_ptr, int *intent));
  180593. #endif
  180594. #if defined(PNG_sRGB_SUPPORTED)
  180595. extern PNG_EXPORT(void,png_set_sRGB) PNGARG((png_structp png_ptr,
  180596. png_infop info_ptr, int intent));
  180597. extern PNG_EXPORT(void,png_set_sRGB_gAMA_and_cHRM) PNGARG((png_structp png_ptr,
  180598. png_infop info_ptr, int intent));
  180599. #endif
  180600. #if defined(PNG_iCCP_SUPPORTED)
  180601. extern PNG_EXPORT(png_uint_32,png_get_iCCP) PNGARG((png_structp png_ptr,
  180602. png_infop info_ptr, png_charpp name, int *compression_type,
  180603. png_charpp profile, png_uint_32 *proflen));
  180604. /* Note to maintainer: profile should be png_bytepp */
  180605. #endif
  180606. #if defined(PNG_iCCP_SUPPORTED)
  180607. extern PNG_EXPORT(void,png_set_iCCP) PNGARG((png_structp png_ptr,
  180608. png_infop info_ptr, png_charp name, int compression_type,
  180609. png_charp profile, png_uint_32 proflen));
  180610. /* Note to maintainer: profile should be png_bytep */
  180611. #endif
  180612. #if defined(PNG_sPLT_SUPPORTED)
  180613. extern PNG_EXPORT(png_uint_32,png_get_sPLT) PNGARG((png_structp png_ptr,
  180614. png_infop info_ptr, png_sPLT_tpp entries));
  180615. #endif
  180616. #if defined(PNG_sPLT_SUPPORTED)
  180617. extern PNG_EXPORT(void,png_set_sPLT) PNGARG((png_structp png_ptr,
  180618. png_infop info_ptr, png_sPLT_tp entries, int nentries));
  180619. #endif
  180620. #if defined(PNG_TEXT_SUPPORTED)
  180621. /* png_get_text also returns the number of text chunks in *num_text */
  180622. extern PNG_EXPORT(png_uint_32,png_get_text) PNGARG((png_structp png_ptr,
  180623. png_infop info_ptr, png_textp *text_ptr, int *num_text));
  180624. #endif
  180625. /*
  180626. * Note while png_set_text() will accept a structure whose text,
  180627. * language, and translated keywords are NULL pointers, the structure
  180628. * returned by png_get_text will always contain regular
  180629. * zero-terminated C strings. They might be empty strings but
  180630. * they will never be NULL pointers.
  180631. */
  180632. #if defined(PNG_TEXT_SUPPORTED)
  180633. extern PNG_EXPORT(void,png_set_text) PNGARG((png_structp png_ptr,
  180634. png_infop info_ptr, png_textp text_ptr, int num_text));
  180635. #endif
  180636. #if defined(PNG_tIME_SUPPORTED)
  180637. extern PNG_EXPORT(png_uint_32,png_get_tIME) PNGARG((png_structp png_ptr,
  180638. png_infop info_ptr, png_timep *mod_time));
  180639. #endif
  180640. #if defined(PNG_tIME_SUPPORTED)
  180641. extern PNG_EXPORT(void,png_set_tIME) PNGARG((png_structp png_ptr,
  180642. png_infop info_ptr, png_timep mod_time));
  180643. #endif
  180644. #if defined(PNG_tRNS_SUPPORTED)
  180645. extern PNG_EXPORT(png_uint_32,png_get_tRNS) PNGARG((png_structp png_ptr,
  180646. png_infop info_ptr, png_bytep *trans, int *num_trans,
  180647. png_color_16p *trans_values));
  180648. #endif
  180649. #if defined(PNG_tRNS_SUPPORTED)
  180650. extern PNG_EXPORT(void,png_set_tRNS) PNGARG((png_structp png_ptr,
  180651. png_infop info_ptr, png_bytep trans, int num_trans,
  180652. png_color_16p trans_values));
  180653. #endif
  180654. #if defined(PNG_tRNS_SUPPORTED)
  180655. #endif
  180656. #if defined(PNG_sCAL_SUPPORTED)
  180657. #ifdef PNG_FLOATING_POINT_SUPPORTED
  180658. extern PNG_EXPORT(png_uint_32,png_get_sCAL) PNGARG((png_structp png_ptr,
  180659. png_infop info_ptr, int *unit, double *width, double *height));
  180660. #else
  180661. #ifdef PNG_FIXED_POINT_SUPPORTED
  180662. extern PNG_EXPORT(png_uint_32,png_get_sCAL_s) PNGARG((png_structp png_ptr,
  180663. png_infop info_ptr, int *unit, png_charpp swidth, png_charpp sheight));
  180664. #endif
  180665. #endif
  180666. #endif /* PNG_sCAL_SUPPORTED */
  180667. #if defined(PNG_sCAL_SUPPORTED)
  180668. #ifdef PNG_FLOATING_POINT_SUPPORTED
  180669. extern PNG_EXPORT(void,png_set_sCAL) PNGARG((png_structp png_ptr,
  180670. png_infop info_ptr, int unit, double width, double height));
  180671. #else
  180672. #ifdef PNG_FIXED_POINT_SUPPORTED
  180673. extern PNG_EXPORT(void,png_set_sCAL_s) PNGARG((png_structp png_ptr,
  180674. png_infop info_ptr, int unit, png_charp swidth, png_charp sheight));
  180675. #endif
  180676. #endif
  180677. #endif /* PNG_sCAL_SUPPORTED || PNG_WRITE_sCAL_SUPPORTED */
  180678. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  180679. /* provide a list of chunks and how they are to be handled, if the built-in
  180680. handling or default unknown chunk handling is not desired. Any chunks not
  180681. listed will be handled in the default manner. The IHDR and IEND chunks
  180682. must not be listed.
  180683. keep = 0: follow default behaviour
  180684. = 1: do not keep
  180685. = 2: keep only if safe-to-copy
  180686. = 3: keep even if unsafe-to-copy
  180687. */
  180688. extern PNG_EXPORT(void, png_set_keep_unknown_chunks) PNGARG((png_structp
  180689. png_ptr, int keep, png_bytep chunk_list, int num_chunks));
  180690. extern PNG_EXPORT(void, png_set_unknown_chunks) PNGARG((png_structp png_ptr,
  180691. png_infop info_ptr, png_unknown_chunkp unknowns, int num_unknowns));
  180692. extern PNG_EXPORT(void, png_set_unknown_chunk_location)
  180693. PNGARG((png_structp png_ptr, png_infop info_ptr, int chunk, int location));
  180694. extern PNG_EXPORT(png_uint_32,png_get_unknown_chunks) PNGARG((png_structp
  180695. png_ptr, png_infop info_ptr, png_unknown_chunkpp entries));
  180696. #endif
  180697. #ifdef PNG_HANDLE_AS_UNKNOWN_SUPPORTED
  180698. PNG_EXPORT(int,png_handle_as_unknown) PNGARG((png_structp png_ptr, png_bytep
  180699. chunk_name));
  180700. #endif
  180701. /* Png_free_data() will turn off the "valid" flag for anything it frees.
  180702. If you need to turn it off for a chunk that your application has freed,
  180703. you can use png_set_invalid(png_ptr, info_ptr, PNG_INFO_CHNK); */
  180704. extern PNG_EXPORT(void, png_set_invalid) PNGARG((png_structp png_ptr,
  180705. png_infop info_ptr, int mask));
  180706. #if defined(PNG_INFO_IMAGE_SUPPORTED)
  180707. /* The "params" pointer is currently not used and is for future expansion. */
  180708. extern PNG_EXPORT(void, png_read_png) PNGARG((png_structp png_ptr,
  180709. png_infop info_ptr,
  180710. int transforms,
  180711. png_voidp params));
  180712. extern PNG_EXPORT(void, png_write_png) PNGARG((png_structp png_ptr,
  180713. png_infop info_ptr,
  180714. int transforms,
  180715. png_voidp params));
  180716. #endif
  180717. /* Define PNG_DEBUG at compile time for debugging information. Higher
  180718. * numbers for PNG_DEBUG mean more debugging information. This has
  180719. * only been added since version 0.95 so it is not implemented throughout
  180720. * libpng yet, but more support will be added as needed.
  180721. */
  180722. #ifdef PNG_DEBUG
  180723. #if (PNG_DEBUG > 0)
  180724. #if !defined(PNG_DEBUG_FILE) && defined(_MSC_VER)
  180725. #include <crtdbg.h>
  180726. #if (PNG_DEBUG > 1)
  180727. #define png_debug(l,m) _RPT0(_CRT_WARN,m)
  180728. #define png_debug1(l,m,p1) _RPT1(_CRT_WARN,m,p1)
  180729. #define png_debug2(l,m,p1,p2) _RPT2(_CRT_WARN,m,p1,p2)
  180730. #endif
  180731. #else /* PNG_DEBUG_FILE || !_MSC_VER */
  180732. #ifndef PNG_DEBUG_FILE
  180733. #define PNG_DEBUG_FILE stderr
  180734. #endif /* PNG_DEBUG_FILE */
  180735. #if (PNG_DEBUG > 1)
  180736. #define png_debug(l,m) \
  180737. { \
  180738. int num_tabs=l; \
  180739. fprintf(PNG_DEBUG_FILE,"%s"m,(num_tabs==1 ? "\t" : \
  180740. (num_tabs==2 ? "\t\t":(num_tabs>2 ? "\t\t\t":"")))); \
  180741. }
  180742. #define png_debug1(l,m,p1) \
  180743. { \
  180744. int num_tabs=l; \
  180745. fprintf(PNG_DEBUG_FILE,"%s"m,(num_tabs==1 ? "\t" : \
  180746. (num_tabs==2 ? "\t\t":(num_tabs>2 ? "\t\t\t":""))),p1); \
  180747. }
  180748. #define png_debug2(l,m,p1,p2) \
  180749. { \
  180750. int num_tabs=l; \
  180751. fprintf(PNG_DEBUG_FILE,"%s"m,(num_tabs==1 ? "\t" : \
  180752. (num_tabs==2 ? "\t\t":(num_tabs>2 ? "\t\t\t":""))),p1,p2); \
  180753. }
  180754. #endif /* (PNG_DEBUG > 1) */
  180755. #endif /* _MSC_VER */
  180756. #endif /* (PNG_DEBUG > 0) */
  180757. #endif /* PNG_DEBUG */
  180758. #ifndef png_debug
  180759. #define png_debug(l, m)
  180760. #endif
  180761. #ifndef png_debug1
  180762. #define png_debug1(l, m, p1)
  180763. #endif
  180764. #ifndef png_debug2
  180765. #define png_debug2(l, m, p1, p2)
  180766. #endif
  180767. extern PNG_EXPORT(png_charp,png_get_copyright) PNGARG((png_structp png_ptr));
  180768. extern PNG_EXPORT(png_charp,png_get_header_ver) PNGARG((png_structp png_ptr));
  180769. extern PNG_EXPORT(png_charp,png_get_header_version) PNGARG((png_structp png_ptr));
  180770. extern PNG_EXPORT(png_charp,png_get_libpng_ver) PNGARG((png_structp png_ptr));
  180771. #ifdef PNG_MNG_FEATURES_SUPPORTED
  180772. extern PNG_EXPORT(png_uint_32,png_permit_mng_features) PNGARG((png_structp
  180773. png_ptr, png_uint_32 mng_features_permitted));
  180774. #endif
  180775. /* For use in png_set_keep_unknown, added to version 1.2.6 */
  180776. #define PNG_HANDLE_CHUNK_AS_DEFAULT 0
  180777. #define PNG_HANDLE_CHUNK_NEVER 1
  180778. #define PNG_HANDLE_CHUNK_IF_SAFE 2
  180779. #define PNG_HANDLE_CHUNK_ALWAYS 3
  180780. /* Added to version 1.2.0 */
  180781. #if defined(PNG_ASSEMBLER_CODE_SUPPORTED)
  180782. #if defined(PNG_MMX_CODE_SUPPORTED)
  180783. #define PNG_ASM_FLAG_MMX_SUPPORT_COMPILED 0x01 /* not user-settable */
  180784. #define PNG_ASM_FLAG_MMX_SUPPORT_IN_CPU 0x02 /* not user-settable */
  180785. #define PNG_ASM_FLAG_MMX_READ_COMBINE_ROW 0x04
  180786. #define PNG_ASM_FLAG_MMX_READ_INTERLACE 0x08
  180787. #define PNG_ASM_FLAG_MMX_READ_FILTER_SUB 0x10
  180788. #define PNG_ASM_FLAG_MMX_READ_FILTER_UP 0x20
  180789. #define PNG_ASM_FLAG_MMX_READ_FILTER_AVG 0x40
  180790. #define PNG_ASM_FLAG_MMX_READ_FILTER_PAETH 0x80
  180791. #define PNG_ASM_FLAGS_INITIALIZED 0x80000000 /* not user-settable */
  180792. #define PNG_MMX_READ_FLAGS ( PNG_ASM_FLAG_MMX_READ_COMBINE_ROW \
  180793. | PNG_ASM_FLAG_MMX_READ_INTERLACE \
  180794. | PNG_ASM_FLAG_MMX_READ_FILTER_SUB \
  180795. | PNG_ASM_FLAG_MMX_READ_FILTER_UP \
  180796. | PNG_ASM_FLAG_MMX_READ_FILTER_AVG \
  180797. | PNG_ASM_FLAG_MMX_READ_FILTER_PAETH )
  180798. #define PNG_MMX_WRITE_FLAGS ( 0 )
  180799. #define PNG_MMX_FLAGS ( PNG_ASM_FLAG_MMX_SUPPORT_COMPILED \
  180800. | PNG_ASM_FLAG_MMX_SUPPORT_IN_CPU \
  180801. | PNG_MMX_READ_FLAGS \
  180802. | PNG_MMX_WRITE_FLAGS )
  180803. #define PNG_SELECT_READ 1
  180804. #define PNG_SELECT_WRITE 2
  180805. #endif /* PNG_MMX_CODE_SUPPORTED */
  180806. #if !defined(PNG_1_0_X)
  180807. /* pngget.c */
  180808. extern PNG_EXPORT(png_uint_32,png_get_mmx_flagmask)
  180809. PNGARG((int flag_select, int *compilerID));
  180810. /* pngget.c */
  180811. extern PNG_EXPORT(png_uint_32,png_get_asm_flagmask)
  180812. PNGARG((int flag_select));
  180813. /* pngget.c */
  180814. extern PNG_EXPORT(png_uint_32,png_get_asm_flags)
  180815. PNGARG((png_structp png_ptr));
  180816. /* pngget.c */
  180817. extern PNG_EXPORT(png_byte,png_get_mmx_bitdepth_threshold)
  180818. PNGARG((png_structp png_ptr));
  180819. /* pngget.c */
  180820. extern PNG_EXPORT(png_uint_32,png_get_mmx_rowbytes_threshold)
  180821. PNGARG((png_structp png_ptr));
  180822. /* pngset.c */
  180823. extern PNG_EXPORT(void,png_set_asm_flags)
  180824. PNGARG((png_structp png_ptr, png_uint_32 asm_flags));
  180825. /* pngset.c */
  180826. extern PNG_EXPORT(void,png_set_mmx_thresholds)
  180827. PNGARG((png_structp png_ptr, png_byte mmx_bitdepth_threshold,
  180828. png_uint_32 mmx_rowbytes_threshold));
  180829. #endif /* PNG_1_0_X */
  180830. #if !defined(PNG_1_0_X)
  180831. /* png.c, pnggccrd.c, or pngvcrd.c */
  180832. extern PNG_EXPORT(int,png_mmx_support) PNGARG((void));
  180833. #endif /* PNG_ASSEMBLER_CODE_SUPPORTED */
  180834. /* Strip the prepended error numbers ("#nnn ") from error and warning
  180835. * messages before passing them to the error or warning handler. */
  180836. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  180837. extern PNG_EXPORT(void,png_set_strip_error_numbers) PNGARG((png_structp
  180838. png_ptr, png_uint_32 strip_mode));
  180839. #endif
  180840. #endif /* PNG_1_0_X */
  180841. /* Added at libpng-1.2.6 */
  180842. #ifdef PNG_SET_USER_LIMITS_SUPPORTED
  180843. extern PNG_EXPORT(void,png_set_user_limits) PNGARG((png_structp
  180844. png_ptr, png_uint_32 user_width_max, png_uint_32 user_height_max));
  180845. extern PNG_EXPORT(png_uint_32,png_get_user_width_max) PNGARG((png_structp
  180846. png_ptr));
  180847. extern PNG_EXPORT(png_uint_32,png_get_user_height_max) PNGARG((png_structp
  180848. png_ptr));
  180849. #endif
  180850. /* Maintainer: Put new public prototypes here ^, in libpng.3, and project defs */
  180851. #ifdef PNG_READ_COMPOSITE_NODIV_SUPPORTED
  180852. /* With these routines we avoid an integer divide, which will be slower on
  180853. * most machines. However, it does take more operations than the corresponding
  180854. * divide method, so it may be slower on a few RISC systems. There are two
  180855. * shifts (by 8 or 16 bits) and an addition, versus a single integer divide.
  180856. *
  180857. * Note that the rounding factors are NOT supposed to be the same! 128 and
  180858. * 32768 are correct for the NODIV code; 127 and 32767 are correct for the
  180859. * standard method.
  180860. *
  180861. * [Optimized code by Greg Roelofs and Mark Adler...blame us for bugs. :-) ]
  180862. */
  180863. /* fg and bg should be in `gamma 1.0' space; alpha is the opacity */
  180864. # define png_composite(composite, fg, alpha, bg) \
  180865. { png_uint_16 temp = (png_uint_16)((png_uint_16)(fg) * (png_uint_16)(alpha) \
  180866. + (png_uint_16)(bg)*(png_uint_16)(255 - \
  180867. (png_uint_16)(alpha)) + (png_uint_16)128); \
  180868. (composite) = (png_byte)((temp + (temp >> 8)) >> 8); }
  180869. # define png_composite_16(composite, fg, alpha, bg) \
  180870. { png_uint_32 temp = (png_uint_32)((png_uint_32)(fg) * (png_uint_32)(alpha) \
  180871. + (png_uint_32)(bg)*(png_uint_32)(65535L - \
  180872. (png_uint_32)(alpha)) + (png_uint_32)32768L); \
  180873. (composite) = (png_uint_16)((temp + (temp >> 16)) >> 16); }
  180874. #else /* standard method using integer division */
  180875. # define png_composite(composite, fg, alpha, bg) \
  180876. (composite) = (png_byte)(((png_uint_16)(fg) * (png_uint_16)(alpha) + \
  180877. (png_uint_16)(bg) * (png_uint_16)(255 - (png_uint_16)(alpha)) + \
  180878. (png_uint_16)127) / 255)
  180879. # define png_composite_16(composite, fg, alpha, bg) \
  180880. (composite) = (png_uint_16)(((png_uint_32)(fg) * (png_uint_32)(alpha) + \
  180881. (png_uint_32)(bg)*(png_uint_32)(65535L - (png_uint_32)(alpha)) + \
  180882. (png_uint_32)32767) / (png_uint_32)65535L)
  180883. #endif /* PNG_READ_COMPOSITE_NODIV_SUPPORTED */
  180884. /* Inline macros to do direct reads of bytes from the input buffer. These
  180885. * require that you are using an architecture that uses PNG byte ordering
  180886. * (MSB first) and supports unaligned data storage. I think that PowerPC
  180887. * in big-endian mode and 680x0 are the only ones that will support this.
  180888. * The x86 line of processors definitely do not. The png_get_int_32()
  180889. * routine also assumes we are using two's complement format for negative
  180890. * values, which is almost certainly true.
  180891. */
  180892. #if defined(PNG_READ_BIG_ENDIAN_SUPPORTED)
  180893. # define png_get_uint_32(buf) ( *((png_uint_32p) (buf)))
  180894. # define png_get_uint_16(buf) ( *((png_uint_16p) (buf)))
  180895. # define png_get_int_32(buf) ( *((png_int_32p) (buf)))
  180896. #else
  180897. extern PNG_EXPORT(png_uint_32,png_get_uint_32) PNGARG((png_bytep buf));
  180898. extern PNG_EXPORT(png_uint_16,png_get_uint_16) PNGARG((png_bytep buf));
  180899. extern PNG_EXPORT(png_int_32,png_get_int_32) PNGARG((png_bytep buf));
  180900. #endif /* !PNG_READ_BIG_ENDIAN_SUPPORTED */
  180901. extern PNG_EXPORT(png_uint_32,png_get_uint_31)
  180902. PNGARG((png_structp png_ptr, png_bytep buf));
  180903. /* No png_get_int_16 -- may be added if there's a real need for it. */
  180904. /* Place a 32-bit number into a buffer in PNG byte order (big-endian).
  180905. */
  180906. extern PNG_EXPORT(void,png_save_uint_32)
  180907. PNGARG((png_bytep buf, png_uint_32 i));
  180908. extern PNG_EXPORT(void,png_save_int_32)
  180909. PNGARG((png_bytep buf, png_int_32 i));
  180910. /* Place a 16-bit number into a buffer in PNG byte order.
  180911. * The parameter is declared unsigned int, not png_uint_16,
  180912. * just to avoid potential problems on pre-ANSI C compilers.
  180913. */
  180914. extern PNG_EXPORT(void,png_save_uint_16)
  180915. PNGARG((png_bytep buf, unsigned int i));
  180916. /* No png_save_int_16 -- may be added if there's a real need for it. */
  180917. /* ************************************************************************* */
  180918. /* These next functions are used internally in the code. They generally
  180919. * shouldn't be used unless you are writing code to add or replace some
  180920. * functionality in libpng. More information about most functions can
  180921. * be found in the files where the functions are located.
  180922. */
  180923. /* Various modes of operation, that are visible to applications because
  180924. * they are used for unknown chunk location.
  180925. */
  180926. #define PNG_HAVE_IHDR 0x01
  180927. #define PNG_HAVE_PLTE 0x02
  180928. #define PNG_HAVE_IDAT 0x04
  180929. #define PNG_AFTER_IDAT 0x08 /* Have complete zlib datastream */
  180930. #define PNG_HAVE_IEND 0x10
  180931. #if defined(PNG_INTERNAL)
  180932. /* More modes of operation. Note that after an init, mode is set to
  180933. * zero automatically when the structure is created.
  180934. */
  180935. #define PNG_HAVE_gAMA 0x20
  180936. #define PNG_HAVE_cHRM 0x40
  180937. #define PNG_HAVE_sRGB 0x80
  180938. #define PNG_HAVE_CHUNK_HEADER 0x100
  180939. #define PNG_WROTE_tIME 0x200
  180940. #define PNG_WROTE_INFO_BEFORE_PLTE 0x400
  180941. #define PNG_BACKGROUND_IS_GRAY 0x800
  180942. #define PNG_HAVE_PNG_SIGNATURE 0x1000
  180943. #define PNG_HAVE_CHUNK_AFTER_IDAT 0x2000 /* Have another chunk after IDAT */
  180944. /* flags for the transformations the PNG library does on the image data */
  180945. #define PNG_BGR 0x0001
  180946. #define PNG_INTERLACE 0x0002
  180947. #define PNG_PACK 0x0004
  180948. #define PNG_SHIFT 0x0008
  180949. #define PNG_SWAP_BYTES 0x0010
  180950. #define PNG_INVERT_MONO 0x0020
  180951. #define PNG_DITHER 0x0040
  180952. #define PNG_BACKGROUND 0x0080
  180953. #define PNG_BACKGROUND_EXPAND 0x0100
  180954. /* 0x0200 unused */
  180955. #define PNG_16_TO_8 0x0400
  180956. #define PNG_RGBA 0x0800
  180957. #define PNG_EXPAND 0x1000
  180958. #define PNG_GAMMA 0x2000
  180959. #define PNG_GRAY_TO_RGB 0x4000
  180960. #define PNG_FILLER 0x8000L
  180961. #define PNG_PACKSWAP 0x10000L
  180962. #define PNG_SWAP_ALPHA 0x20000L
  180963. #define PNG_STRIP_ALPHA 0x40000L
  180964. #define PNG_INVERT_ALPHA 0x80000L
  180965. #define PNG_USER_TRANSFORM 0x100000L
  180966. #define PNG_RGB_TO_GRAY_ERR 0x200000L
  180967. #define PNG_RGB_TO_GRAY_WARN 0x400000L
  180968. #define PNG_RGB_TO_GRAY 0x600000L /* two bits, RGB_TO_GRAY_ERR|WARN */
  180969. /* 0x800000L Unused */
  180970. #define PNG_ADD_ALPHA 0x1000000L /* Added to libpng-1.2.7 */
  180971. #define PNG_EXPAND_tRNS 0x2000000L /* Added to libpng-1.2.9 */
  180972. /* 0x4000000L unused */
  180973. /* 0x8000000L unused */
  180974. /* 0x10000000L unused */
  180975. /* 0x20000000L unused */
  180976. /* 0x40000000L unused */
  180977. /* flags for png_create_struct */
  180978. #define PNG_STRUCT_PNG 0x0001
  180979. #define PNG_STRUCT_INFO 0x0002
  180980. /* Scaling factor for filter heuristic weighting calculations */
  180981. #define PNG_WEIGHT_SHIFT 8
  180982. #define PNG_WEIGHT_FACTOR (1<<(PNG_WEIGHT_SHIFT))
  180983. #define PNG_COST_SHIFT 3
  180984. #define PNG_COST_FACTOR (1<<(PNG_COST_SHIFT))
  180985. /* flags for the png_ptr->flags rather than declaring a byte for each one */
  180986. #define PNG_FLAG_ZLIB_CUSTOM_STRATEGY 0x0001
  180987. #define PNG_FLAG_ZLIB_CUSTOM_LEVEL 0x0002
  180988. #define PNG_FLAG_ZLIB_CUSTOM_MEM_LEVEL 0x0004
  180989. #define PNG_FLAG_ZLIB_CUSTOM_WINDOW_BITS 0x0008
  180990. #define PNG_FLAG_ZLIB_CUSTOM_METHOD 0x0010
  180991. #define PNG_FLAG_ZLIB_FINISHED 0x0020
  180992. #define PNG_FLAG_ROW_INIT 0x0040
  180993. #define PNG_FLAG_FILLER_AFTER 0x0080
  180994. #define PNG_FLAG_CRC_ANCILLARY_USE 0x0100
  180995. #define PNG_FLAG_CRC_ANCILLARY_NOWARN 0x0200
  180996. #define PNG_FLAG_CRC_CRITICAL_USE 0x0400
  180997. #define PNG_FLAG_CRC_CRITICAL_IGNORE 0x0800
  180998. #define PNG_FLAG_FREE_PLTE 0x1000
  180999. #define PNG_FLAG_FREE_TRNS 0x2000
  181000. #define PNG_FLAG_FREE_HIST 0x4000
  181001. #define PNG_FLAG_KEEP_UNKNOWN_CHUNKS 0x8000L
  181002. #define PNG_FLAG_KEEP_UNSAFE_CHUNKS 0x10000L
  181003. #define PNG_FLAG_LIBRARY_MISMATCH 0x20000L
  181004. #define PNG_FLAG_STRIP_ERROR_NUMBERS 0x40000L
  181005. #define PNG_FLAG_STRIP_ERROR_TEXT 0x80000L
  181006. #define PNG_FLAG_MALLOC_NULL_MEM_OK 0x100000L
  181007. #define PNG_FLAG_ADD_ALPHA 0x200000L /* Added to libpng-1.2.8 */
  181008. #define PNG_FLAG_STRIP_ALPHA 0x400000L /* Added to libpng-1.2.8 */
  181009. /* 0x800000L unused */
  181010. /* 0x1000000L unused */
  181011. /* 0x2000000L unused */
  181012. /* 0x4000000L unused */
  181013. /* 0x8000000L unused */
  181014. /* 0x10000000L unused */
  181015. /* 0x20000000L unused */
  181016. /* 0x40000000L unused */
  181017. #define PNG_FLAG_CRC_ANCILLARY_MASK (PNG_FLAG_CRC_ANCILLARY_USE | \
  181018. PNG_FLAG_CRC_ANCILLARY_NOWARN)
  181019. #define PNG_FLAG_CRC_CRITICAL_MASK (PNG_FLAG_CRC_CRITICAL_USE | \
  181020. PNG_FLAG_CRC_CRITICAL_IGNORE)
  181021. #define PNG_FLAG_CRC_MASK (PNG_FLAG_CRC_ANCILLARY_MASK | \
  181022. PNG_FLAG_CRC_CRITICAL_MASK)
  181023. /* save typing and make code easier to understand */
  181024. #define PNG_COLOR_DIST(c1, c2) (abs((int)((c1).red) - (int)((c2).red)) + \
  181025. abs((int)((c1).green) - (int)((c2).green)) + \
  181026. abs((int)((c1).blue) - (int)((c2).blue)))
  181027. /* Added to libpng-1.2.6 JB */
  181028. #define PNG_ROWBYTES(pixel_bits, width) \
  181029. ((pixel_bits) >= 8 ? \
  181030. ((width) * (((png_uint_32)(pixel_bits)) >> 3)) : \
  181031. (( ((width) * ((png_uint_32)(pixel_bits))) + 7) >> 3) )
  181032. /* PNG_OUT_OF_RANGE returns true if value is outside the range
  181033. ideal-delta..ideal+delta. Each argument is evaluated twice.
  181034. "ideal" and "delta" should be constants, normally simple
  181035. integers, "value" a variable. Added to libpng-1.2.6 JB */
  181036. #define PNG_OUT_OF_RANGE(value, ideal, delta) \
  181037. ( (value) < (ideal)-(delta) || (value) > (ideal)+(delta) )
  181038. /* variables declared in png.c - only it needs to define PNG_NO_EXTERN */
  181039. #if !defined(PNG_NO_EXTERN) || defined(PNG_ALWAYS_EXTERN)
  181040. /* place to hold the signature string for a PNG file. */
  181041. #ifdef PNG_USE_GLOBAL_ARRAYS
  181042. PNG_EXPORT_VAR (PNG_CONST png_byte FARDATA) png_sig[8];
  181043. #else
  181044. #endif
  181045. #endif /* PNG_NO_EXTERN */
  181046. /* Constant strings for known chunk types. If you need to add a chunk,
  181047. * define the name here, and add an invocation of the macro in png.c and
  181048. * wherever it's needed.
  181049. */
  181050. #define PNG_IHDR png_byte png_IHDR[5] = { 73, 72, 68, 82, '\0'}
  181051. #define PNG_IDAT png_byte png_IDAT[5] = { 73, 68, 65, 84, '\0'}
  181052. #define PNG_IEND png_byte png_IEND[5] = { 73, 69, 78, 68, '\0'}
  181053. #define PNG_PLTE png_byte png_PLTE[5] = { 80, 76, 84, 69, '\0'}
  181054. #define PNG_bKGD png_byte png_bKGD[5] = { 98, 75, 71, 68, '\0'}
  181055. #define PNG_cHRM png_byte png_cHRM[5] = { 99, 72, 82, 77, '\0'}
  181056. #define PNG_gAMA png_byte png_gAMA[5] = {103, 65, 77, 65, '\0'}
  181057. #define PNG_hIST png_byte png_hIST[5] = {104, 73, 83, 84, '\0'}
  181058. #define PNG_iCCP png_byte png_iCCP[5] = {105, 67, 67, 80, '\0'}
  181059. #define PNG_iTXt png_byte png_iTXt[5] = {105, 84, 88, 116, '\0'}
  181060. #define PNG_oFFs png_byte png_oFFs[5] = {111, 70, 70, 115, '\0'}
  181061. #define PNG_pCAL png_byte png_pCAL[5] = {112, 67, 65, 76, '\0'}
  181062. #define PNG_sCAL png_byte png_sCAL[5] = {115, 67, 65, 76, '\0'}
  181063. #define PNG_pHYs png_byte png_pHYs[5] = {112, 72, 89, 115, '\0'}
  181064. #define PNG_sBIT png_byte png_sBIT[5] = {115, 66, 73, 84, '\0'}
  181065. #define PNG_sPLT png_byte png_sPLT[5] = {115, 80, 76, 84, '\0'}
  181066. #define PNG_sRGB png_byte png_sRGB[5] = {115, 82, 71, 66, '\0'}
  181067. #define PNG_tEXt png_byte png_tEXt[5] = {116, 69, 88, 116, '\0'}
  181068. #define PNG_tIME png_byte png_tIME[5] = {116, 73, 77, 69, '\0'}
  181069. #define PNG_tRNS png_byte png_tRNS[5] = {116, 82, 78, 83, '\0'}
  181070. #define PNG_zTXt png_byte png_zTXt[5] = {122, 84, 88, 116, '\0'}
  181071. #ifdef PNG_USE_GLOBAL_ARRAYS
  181072. PNG_EXPORT_VAR (png_byte FARDATA) png_IHDR[5];
  181073. PNG_EXPORT_VAR (png_byte FARDATA) png_IDAT[5];
  181074. PNG_EXPORT_VAR (png_byte FARDATA) png_IEND[5];
  181075. PNG_EXPORT_VAR (png_byte FARDATA) png_PLTE[5];
  181076. PNG_EXPORT_VAR (png_byte FARDATA) png_bKGD[5];
  181077. PNG_EXPORT_VAR (png_byte FARDATA) png_cHRM[5];
  181078. PNG_EXPORT_VAR (png_byte FARDATA) png_gAMA[5];
  181079. PNG_EXPORT_VAR (png_byte FARDATA) png_hIST[5];
  181080. PNG_EXPORT_VAR (png_byte FARDATA) png_iCCP[5];
  181081. PNG_EXPORT_VAR (png_byte FARDATA) png_iTXt[5];
  181082. PNG_EXPORT_VAR (png_byte FARDATA) png_oFFs[5];
  181083. PNG_EXPORT_VAR (png_byte FARDATA) png_pCAL[5];
  181084. PNG_EXPORT_VAR (png_byte FARDATA) png_sCAL[5];
  181085. PNG_EXPORT_VAR (png_byte FARDATA) png_pHYs[5];
  181086. PNG_EXPORT_VAR (png_byte FARDATA) png_sBIT[5];
  181087. PNG_EXPORT_VAR (png_byte FARDATA) png_sPLT[5];
  181088. PNG_EXPORT_VAR (png_byte FARDATA) png_sRGB[5];
  181089. PNG_EXPORT_VAR (png_byte FARDATA) png_tEXt[5];
  181090. PNG_EXPORT_VAR (png_byte FARDATA) png_tIME[5];
  181091. PNG_EXPORT_VAR (png_byte FARDATA) png_tRNS[5];
  181092. PNG_EXPORT_VAR (png_byte FARDATA) png_zTXt[5];
  181093. #endif /* PNG_USE_GLOBAL_ARRAYS */
  181094. #if defined(PNG_1_0_X) || defined (PNG_1_2_X)
  181095. /* Initialize png_ptr struct for reading, and allocate any other memory.
  181096. * (old interface - DEPRECATED - use png_create_read_struct instead).
  181097. */
  181098. extern PNG_EXPORT(void,png_read_init) PNGARG((png_structp png_ptr));
  181099. #undef png_read_init
  181100. #define png_read_init(png_ptr) png_read_init_3(&png_ptr, \
  181101. PNG_LIBPNG_VER_STRING, png_sizeof(png_struct));
  181102. #endif
  181103. extern PNG_EXPORT(void,png_read_init_3) PNGARG((png_structpp ptr_ptr,
  181104. png_const_charp user_png_ver, png_size_t png_struct_size));
  181105. #if defined(PNG_1_0_X) || defined (PNG_1_2_X)
  181106. extern PNG_EXPORT(void,png_read_init_2) PNGARG((png_structp png_ptr,
  181107. png_const_charp user_png_ver, png_size_t png_struct_size, png_size_t
  181108. png_info_size));
  181109. #endif
  181110. #if defined(PNG_1_0_X) || defined (PNG_1_2_X)
  181111. /* Initialize png_ptr struct for writing, and allocate any other memory.
  181112. * (old interface - DEPRECATED - use png_create_write_struct instead).
  181113. */
  181114. extern PNG_EXPORT(void,png_write_init) PNGARG((png_structp png_ptr));
  181115. #undef png_write_init
  181116. #define png_write_init(png_ptr) png_write_init_3(&png_ptr, \
  181117. PNG_LIBPNG_VER_STRING, png_sizeof(png_struct));
  181118. #endif
  181119. extern PNG_EXPORT(void,png_write_init_3) PNGARG((png_structpp ptr_ptr,
  181120. png_const_charp user_png_ver, png_size_t png_struct_size));
  181121. extern PNG_EXPORT(void,png_write_init_2) PNGARG((png_structp png_ptr,
  181122. png_const_charp user_png_ver, png_size_t png_struct_size, png_size_t
  181123. png_info_size));
  181124. /* Allocate memory for an internal libpng struct */
  181125. PNG_EXTERN png_voidp png_create_struct PNGARG((int type));
  181126. /* Free memory from internal libpng struct */
  181127. PNG_EXTERN void png_destroy_struct PNGARG((png_voidp struct_ptr));
  181128. PNG_EXTERN png_voidp png_create_struct_2 PNGARG((int type, png_malloc_ptr
  181129. malloc_fn, png_voidp mem_ptr));
  181130. PNG_EXTERN void png_destroy_struct_2 PNGARG((png_voidp struct_ptr,
  181131. png_free_ptr free_fn, png_voidp mem_ptr));
  181132. /* Free any memory that info_ptr points to and reset struct. */
  181133. PNG_EXTERN void png_info_destroy PNGARG((png_structp png_ptr,
  181134. png_infop info_ptr));
  181135. #ifndef PNG_1_0_X
  181136. /* Function to allocate memory for zlib. */
  181137. PNG_EXTERN voidpf png_zalloc PNGARG((voidpf png_ptr, uInt items, uInt size));
  181138. /* Function to free memory for zlib */
  181139. PNG_EXTERN void png_zfree PNGARG((voidpf png_ptr, voidpf ptr));
  181140. #ifdef PNG_SIZE_T
  181141. /* Function to convert a sizeof an item to png_sizeof item */
  181142. PNG_EXTERN png_size_t PNGAPI png_convert_size PNGARG((size_t size));
  181143. #endif
  181144. /* Next four functions are used internally as callbacks. PNGAPI is required
  181145. * but not PNG_EXPORT. PNGAPI added at libpng version 1.2.3. */
  181146. PNG_EXTERN void PNGAPI png_default_read_data PNGARG((png_structp png_ptr,
  181147. png_bytep data, png_size_t length));
  181148. #ifdef PNG_PROGRESSIVE_READ_SUPPORTED
  181149. PNG_EXTERN void PNGAPI png_push_fill_buffer PNGARG((png_structp png_ptr,
  181150. png_bytep buffer, png_size_t length));
  181151. #endif
  181152. PNG_EXTERN void PNGAPI png_default_write_data PNGARG((png_structp png_ptr,
  181153. png_bytep data, png_size_t length));
  181154. #if defined(PNG_WRITE_FLUSH_SUPPORTED)
  181155. #if !defined(PNG_NO_STDIO)
  181156. PNG_EXTERN void PNGAPI png_default_flush PNGARG((png_structp png_ptr));
  181157. #endif
  181158. #endif
  181159. #else /* PNG_1_0_X */
  181160. #ifdef PNG_PROGRESSIVE_READ_SUPPORTED
  181161. PNG_EXTERN void png_push_fill_buffer PNGARG((png_structp png_ptr,
  181162. png_bytep buffer, png_size_t length));
  181163. #endif
  181164. #endif /* PNG_1_0_X */
  181165. /* Reset the CRC variable */
  181166. PNG_EXTERN void png_reset_crc PNGARG((png_structp png_ptr));
  181167. /* Write the "data" buffer to whatever output you are using. */
  181168. PNG_EXTERN void png_write_data PNGARG((png_structp png_ptr, png_bytep data,
  181169. png_size_t length));
  181170. /* Read data from whatever input you are using into the "data" buffer */
  181171. PNG_EXTERN void png_read_data PNGARG((png_structp png_ptr, png_bytep data,
  181172. png_size_t length));
  181173. /* Read bytes into buf, and update png_ptr->crc */
  181174. PNG_EXTERN void png_crc_read PNGARG((png_structp png_ptr, png_bytep buf,
  181175. png_size_t length));
  181176. /* Decompress data in a chunk that uses compression */
  181177. #if defined(PNG_zTXt_SUPPORTED) || defined(PNG_iTXt_SUPPORTED) || \
  181178. defined(PNG_iCCP_SUPPORTED) || defined(PNG_sPLT_SUPPORTED)
  181179. PNG_EXTERN png_charp png_decompress_chunk PNGARG((png_structp png_ptr,
  181180. int comp_type, png_charp chunkdata, png_size_t chunklength,
  181181. png_size_t prefix_length, png_size_t *data_length));
  181182. #endif
  181183. /* Read "skip" bytes, read the file crc, and (optionally) verify png_ptr->crc */
  181184. PNG_EXTERN int png_crc_finish PNGARG((png_structp png_ptr, png_uint_32 skip));
  181185. /* Read the CRC from the file and compare it to the libpng calculated CRC */
  181186. PNG_EXTERN int png_crc_error PNGARG((png_structp png_ptr));
  181187. /* Calculate the CRC over a section of data. Note that we are only
  181188. * passing a maximum of 64K on systems that have this as a memory limit,
  181189. * since this is the maximum buffer size we can specify.
  181190. */
  181191. PNG_EXTERN void png_calculate_crc PNGARG((png_structp png_ptr, png_bytep ptr,
  181192. png_size_t length));
  181193. #if defined(PNG_WRITE_FLUSH_SUPPORTED)
  181194. PNG_EXTERN void png_flush PNGARG((png_structp png_ptr));
  181195. #endif
  181196. /* simple function to write the signature */
  181197. PNG_EXTERN void png_write_sig PNGARG((png_structp png_ptr));
  181198. /* write various chunks */
  181199. /* Write the IHDR chunk, and update the png_struct with the necessary
  181200. * information.
  181201. */
  181202. PNG_EXTERN void png_write_IHDR PNGARG((png_structp png_ptr, png_uint_32 width,
  181203. png_uint_32 height,
  181204. int bit_depth, int color_type, int compression_method, int filter_method,
  181205. int interlace_method));
  181206. PNG_EXTERN void png_write_PLTE PNGARG((png_structp png_ptr, png_colorp palette,
  181207. png_uint_32 num_pal));
  181208. PNG_EXTERN void png_write_IDAT PNGARG((png_structp png_ptr, png_bytep data,
  181209. png_size_t length));
  181210. PNG_EXTERN void png_write_IEND PNGARG((png_structp png_ptr));
  181211. #if defined(PNG_WRITE_gAMA_SUPPORTED)
  181212. #ifdef PNG_FLOATING_POINT_SUPPORTED
  181213. PNG_EXTERN void png_write_gAMA PNGARG((png_structp png_ptr, double file_gamma));
  181214. #endif
  181215. #ifdef PNG_FIXED_POINT_SUPPORTED
  181216. PNG_EXTERN void png_write_gAMA_fixed PNGARG((png_structp png_ptr, png_fixed_point
  181217. file_gamma));
  181218. #endif
  181219. #endif
  181220. #if defined(PNG_WRITE_sBIT_SUPPORTED)
  181221. PNG_EXTERN void png_write_sBIT PNGARG((png_structp png_ptr, png_color_8p sbit,
  181222. int color_type));
  181223. #endif
  181224. #if defined(PNG_WRITE_cHRM_SUPPORTED)
  181225. #ifdef PNG_FLOATING_POINT_SUPPORTED
  181226. PNG_EXTERN void png_write_cHRM PNGARG((png_structp png_ptr,
  181227. double white_x, double white_y,
  181228. double red_x, double red_y, double green_x, double green_y,
  181229. double blue_x, double blue_y));
  181230. #endif
  181231. #ifdef PNG_FIXED_POINT_SUPPORTED
  181232. PNG_EXTERN void png_write_cHRM_fixed PNGARG((png_structp png_ptr,
  181233. png_fixed_point int_white_x, png_fixed_point int_white_y,
  181234. png_fixed_point int_red_x, png_fixed_point int_red_y, png_fixed_point
  181235. int_green_x, png_fixed_point int_green_y, png_fixed_point int_blue_x,
  181236. png_fixed_point int_blue_y));
  181237. #endif
  181238. #endif
  181239. #if defined(PNG_WRITE_sRGB_SUPPORTED)
  181240. PNG_EXTERN void png_write_sRGB PNGARG((png_structp png_ptr,
  181241. int intent));
  181242. #endif
  181243. #if defined(PNG_WRITE_iCCP_SUPPORTED)
  181244. PNG_EXTERN void png_write_iCCP PNGARG((png_structp png_ptr,
  181245. png_charp name, int compression_type,
  181246. png_charp profile, int proflen));
  181247. /* Note to maintainer: profile should be png_bytep */
  181248. #endif
  181249. #if defined(PNG_WRITE_sPLT_SUPPORTED)
  181250. PNG_EXTERN void png_write_sPLT PNGARG((png_structp png_ptr,
  181251. png_sPLT_tp palette));
  181252. #endif
  181253. #if defined(PNG_WRITE_tRNS_SUPPORTED)
  181254. PNG_EXTERN void png_write_tRNS PNGARG((png_structp png_ptr, png_bytep trans,
  181255. png_color_16p values, int number, int color_type));
  181256. #endif
  181257. #if defined(PNG_WRITE_bKGD_SUPPORTED)
  181258. PNG_EXTERN void png_write_bKGD PNGARG((png_structp png_ptr,
  181259. png_color_16p values, int color_type));
  181260. #endif
  181261. #if defined(PNG_WRITE_hIST_SUPPORTED)
  181262. PNG_EXTERN void png_write_hIST PNGARG((png_structp png_ptr, png_uint_16p hist,
  181263. int num_hist));
  181264. #endif
  181265. #if defined(PNG_WRITE_TEXT_SUPPORTED) || defined(PNG_WRITE_pCAL_SUPPORTED) || \
  181266. defined(PNG_WRITE_iCCP_SUPPORTED) || defined(PNG_WRITE_sPLT_SUPPORTED)
  181267. PNG_EXTERN png_size_t png_check_keyword PNGARG((png_structp png_ptr,
  181268. png_charp key, png_charpp new_key));
  181269. #endif
  181270. #if defined(PNG_WRITE_tEXt_SUPPORTED)
  181271. PNG_EXTERN void png_write_tEXt PNGARG((png_structp png_ptr, png_charp key,
  181272. png_charp text, png_size_t text_len));
  181273. #endif
  181274. #if defined(PNG_WRITE_zTXt_SUPPORTED)
  181275. PNG_EXTERN void png_write_zTXt PNGARG((png_structp png_ptr, png_charp key,
  181276. png_charp text, png_size_t text_len, int compression));
  181277. #endif
  181278. #if defined(PNG_WRITE_iTXt_SUPPORTED)
  181279. PNG_EXTERN void png_write_iTXt PNGARG((png_structp png_ptr,
  181280. int compression, png_charp key, png_charp lang, png_charp lang_key,
  181281. png_charp text));
  181282. #endif
  181283. #if defined(PNG_TEXT_SUPPORTED) /* Added at version 1.0.14 and 1.2.4 */
  181284. PNG_EXTERN int png_set_text_2 PNGARG((png_structp png_ptr,
  181285. png_infop info_ptr, png_textp text_ptr, int num_text));
  181286. #endif
  181287. #if defined(PNG_WRITE_oFFs_SUPPORTED)
  181288. PNG_EXTERN void png_write_oFFs PNGARG((png_structp png_ptr,
  181289. png_int_32 x_offset, png_int_32 y_offset, int unit_type));
  181290. #endif
  181291. #if defined(PNG_WRITE_pCAL_SUPPORTED)
  181292. PNG_EXTERN void png_write_pCAL PNGARG((png_structp png_ptr, png_charp purpose,
  181293. png_int_32 X0, png_int_32 X1, int type, int nparams,
  181294. png_charp units, png_charpp params));
  181295. #endif
  181296. #if defined(PNG_WRITE_pHYs_SUPPORTED)
  181297. PNG_EXTERN void png_write_pHYs PNGARG((png_structp png_ptr,
  181298. png_uint_32 x_pixels_per_unit, png_uint_32 y_pixels_per_unit,
  181299. int unit_type));
  181300. #endif
  181301. #if defined(PNG_WRITE_tIME_SUPPORTED)
  181302. PNG_EXTERN void png_write_tIME PNGARG((png_structp png_ptr,
  181303. png_timep mod_time));
  181304. #endif
  181305. #if defined(PNG_WRITE_sCAL_SUPPORTED)
  181306. #if defined(PNG_FLOATING_POINT_SUPPORTED) && !defined(PNG_NO_STDIO)
  181307. PNG_EXTERN void png_write_sCAL PNGARG((png_structp png_ptr,
  181308. int unit, double width, double height));
  181309. #else
  181310. #ifdef PNG_FIXED_POINT_SUPPORTED
  181311. PNG_EXTERN void png_write_sCAL_s PNGARG((png_structp png_ptr,
  181312. int unit, png_charp width, png_charp height));
  181313. #endif
  181314. #endif
  181315. #endif
  181316. /* Called when finished processing a row of data */
  181317. PNG_EXTERN void png_write_finish_row PNGARG((png_structp png_ptr));
  181318. /* Internal use only. Called before first row of data */
  181319. PNG_EXTERN void png_write_start_row PNGARG((png_structp png_ptr));
  181320. #if defined(PNG_READ_GAMMA_SUPPORTED)
  181321. PNG_EXTERN void png_build_gamma_table PNGARG((png_structp png_ptr));
  181322. #endif
  181323. /* combine a row of data, dealing with alpha, etc. if requested */
  181324. PNG_EXTERN void png_combine_row PNGARG((png_structp png_ptr, png_bytep row,
  181325. int mask));
  181326. #if defined(PNG_READ_INTERLACING_SUPPORTED)
  181327. /* expand an interlaced row */
  181328. /* OLD pre-1.0.9 interface:
  181329. PNG_EXTERN void png_do_read_interlace PNGARG((png_row_infop row_info,
  181330. png_bytep row, int pass, png_uint_32 transformations));
  181331. */
  181332. PNG_EXTERN void png_do_read_interlace PNGARG((png_structp png_ptr));
  181333. #endif
  181334. /* GRR TO DO (2.0 or whenever): simplify other internal calling interfaces */
  181335. #if defined(PNG_WRITE_INTERLACING_SUPPORTED)
  181336. /* grab pixels out of a row for an interlaced pass */
  181337. PNG_EXTERN void png_do_write_interlace PNGARG((png_row_infop row_info,
  181338. png_bytep row, int pass));
  181339. #endif
  181340. /* unfilter a row */
  181341. PNG_EXTERN void png_read_filter_row PNGARG((png_structp png_ptr,
  181342. png_row_infop row_info, png_bytep row, png_bytep prev_row, int filter));
  181343. /* Choose the best filter to use and filter the row data */
  181344. PNG_EXTERN void png_write_find_filter PNGARG((png_structp png_ptr,
  181345. png_row_infop row_info));
  181346. /* Write out the filtered row. */
  181347. PNG_EXTERN void png_write_filtered_row PNGARG((png_structp png_ptr,
  181348. png_bytep filtered_row));
  181349. /* finish a row while reading, dealing with interlacing passes, etc. */
  181350. PNG_EXTERN void png_read_finish_row PNGARG((png_structp png_ptr));
  181351. /* initialize the row buffers, etc. */
  181352. PNG_EXTERN void png_read_start_row PNGARG((png_structp png_ptr));
  181353. /* optional call to update the users info structure */
  181354. PNG_EXTERN void png_read_transform_info PNGARG((png_structp png_ptr,
  181355. png_infop info_ptr));
  181356. /* these are the functions that do the transformations */
  181357. #if defined(PNG_READ_FILLER_SUPPORTED)
  181358. PNG_EXTERN void png_do_read_filler PNGARG((png_row_infop row_info,
  181359. png_bytep row, png_uint_32 filler, png_uint_32 flags));
  181360. #endif
  181361. #if defined(PNG_READ_SWAP_ALPHA_SUPPORTED)
  181362. PNG_EXTERN void png_do_read_swap_alpha PNGARG((png_row_infop row_info,
  181363. png_bytep row));
  181364. #endif
  181365. #if defined(PNG_WRITE_SWAP_ALPHA_SUPPORTED)
  181366. PNG_EXTERN void png_do_write_swap_alpha PNGARG((png_row_infop row_info,
  181367. png_bytep row));
  181368. #endif
  181369. #if defined(PNG_READ_INVERT_ALPHA_SUPPORTED)
  181370. PNG_EXTERN void png_do_read_invert_alpha PNGARG((png_row_infop row_info,
  181371. png_bytep row));
  181372. #endif
  181373. #if defined(PNG_WRITE_INVERT_ALPHA_SUPPORTED)
  181374. PNG_EXTERN void png_do_write_invert_alpha PNGARG((png_row_infop row_info,
  181375. png_bytep row));
  181376. #endif
  181377. #if defined(PNG_WRITE_FILLER_SUPPORTED) || \
  181378. defined(PNG_READ_STRIP_ALPHA_SUPPORTED)
  181379. PNG_EXTERN void png_do_strip_filler PNGARG((png_row_infop row_info,
  181380. png_bytep row, png_uint_32 flags));
  181381. #endif
  181382. #if defined(PNG_READ_SWAP_SUPPORTED) || defined(PNG_WRITE_SWAP_SUPPORTED)
  181383. PNG_EXTERN void png_do_swap PNGARG((png_row_infop row_info, png_bytep row));
  181384. #endif
  181385. #if defined(PNG_READ_PACKSWAP_SUPPORTED) || defined(PNG_WRITE_PACKSWAP_SUPPORTED)
  181386. PNG_EXTERN void png_do_packswap PNGARG((png_row_infop row_info, png_bytep row));
  181387. #endif
  181388. #if defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
  181389. PNG_EXTERN int png_do_rgb_to_gray PNGARG((png_structp png_ptr, png_row_infop
  181390. row_info, png_bytep row));
  181391. #endif
  181392. #if defined(PNG_READ_GRAY_TO_RGB_SUPPORTED)
  181393. PNG_EXTERN void png_do_gray_to_rgb PNGARG((png_row_infop row_info,
  181394. png_bytep row));
  181395. #endif
  181396. #if defined(PNG_READ_PACK_SUPPORTED)
  181397. PNG_EXTERN void png_do_unpack PNGARG((png_row_infop row_info, png_bytep row));
  181398. #endif
  181399. #if defined(PNG_READ_SHIFT_SUPPORTED)
  181400. PNG_EXTERN void png_do_unshift PNGARG((png_row_infop row_info, png_bytep row,
  181401. png_color_8p sig_bits));
  181402. #endif
  181403. #if defined(PNG_READ_INVERT_SUPPORTED) || defined(PNG_WRITE_INVERT_SUPPORTED)
  181404. PNG_EXTERN void png_do_invert PNGARG((png_row_infop row_info, png_bytep row));
  181405. #endif
  181406. #if defined(PNG_READ_16_TO_8_SUPPORTED)
  181407. PNG_EXTERN void png_do_chop PNGARG((png_row_infop row_info, png_bytep row));
  181408. #endif
  181409. #if defined(PNG_READ_DITHER_SUPPORTED)
  181410. PNG_EXTERN void png_do_dither PNGARG((png_row_infop row_info,
  181411. png_bytep row, png_bytep palette_lookup, png_bytep dither_lookup));
  181412. # if defined(PNG_CORRECT_PALETTE_SUPPORTED)
  181413. PNG_EXTERN void png_correct_palette PNGARG((png_structp png_ptr,
  181414. png_colorp palette, int num_palette));
  181415. # endif
  181416. #endif
  181417. #if defined(PNG_READ_BGR_SUPPORTED) || defined(PNG_WRITE_BGR_SUPPORTED)
  181418. PNG_EXTERN void png_do_bgr PNGARG((png_row_infop row_info, png_bytep row));
  181419. #endif
  181420. #if defined(PNG_WRITE_PACK_SUPPORTED)
  181421. PNG_EXTERN void png_do_pack PNGARG((png_row_infop row_info,
  181422. png_bytep row, png_uint_32 bit_depth));
  181423. #endif
  181424. #if defined(PNG_WRITE_SHIFT_SUPPORTED)
  181425. PNG_EXTERN void png_do_shift PNGARG((png_row_infop row_info, png_bytep row,
  181426. png_color_8p bit_depth));
  181427. #endif
  181428. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  181429. #if defined(PNG_READ_GAMMA_SUPPORTED)
  181430. PNG_EXTERN void png_do_background PNGARG((png_row_infop row_info, png_bytep row,
  181431. png_color_16p trans_values, png_color_16p background,
  181432. png_color_16p background_1,
  181433. png_bytep gamma_table, png_bytep gamma_from_1, png_bytep gamma_to_1,
  181434. png_uint_16pp gamma_16, png_uint_16pp gamma_16_from_1,
  181435. png_uint_16pp gamma_16_to_1, int gamma_shift));
  181436. #else
  181437. PNG_EXTERN void png_do_background PNGARG((png_row_infop row_info, png_bytep row,
  181438. png_color_16p trans_values, png_color_16p background));
  181439. #endif
  181440. #endif
  181441. #if defined(PNG_READ_GAMMA_SUPPORTED)
  181442. PNG_EXTERN void png_do_gamma PNGARG((png_row_infop row_info, png_bytep row,
  181443. png_bytep gamma_table, png_uint_16pp gamma_16_table,
  181444. int gamma_shift));
  181445. #endif
  181446. #if defined(PNG_READ_EXPAND_SUPPORTED)
  181447. PNG_EXTERN void png_do_expand_palette PNGARG((png_row_infop row_info,
  181448. png_bytep row, png_colorp palette, png_bytep trans, int num_trans));
  181449. PNG_EXTERN void png_do_expand PNGARG((png_row_infop row_info,
  181450. png_bytep row, png_color_16p trans_value));
  181451. #endif
  181452. /* The following decodes the appropriate chunks, and does error correction,
  181453. * then calls the appropriate callback for the chunk if it is valid.
  181454. */
  181455. /* decode the IHDR chunk */
  181456. PNG_EXTERN void png_handle_IHDR PNGARG((png_structp png_ptr, png_infop info_ptr,
  181457. png_uint_32 length));
  181458. PNG_EXTERN void png_handle_PLTE PNGARG((png_structp png_ptr, png_infop info_ptr,
  181459. png_uint_32 length));
  181460. PNG_EXTERN void png_handle_IEND PNGARG((png_structp png_ptr, png_infop info_ptr,
  181461. png_uint_32 length));
  181462. #if defined(PNG_READ_bKGD_SUPPORTED)
  181463. PNG_EXTERN void png_handle_bKGD PNGARG((png_structp png_ptr, png_infop info_ptr,
  181464. png_uint_32 length));
  181465. #endif
  181466. #if defined(PNG_READ_cHRM_SUPPORTED)
  181467. PNG_EXTERN void png_handle_cHRM PNGARG((png_structp png_ptr, png_infop info_ptr,
  181468. png_uint_32 length));
  181469. #endif
  181470. #if defined(PNG_READ_gAMA_SUPPORTED)
  181471. PNG_EXTERN void png_handle_gAMA PNGARG((png_structp png_ptr, png_infop info_ptr,
  181472. png_uint_32 length));
  181473. #endif
  181474. #if defined(PNG_READ_hIST_SUPPORTED)
  181475. PNG_EXTERN void png_handle_hIST PNGARG((png_structp png_ptr, png_infop info_ptr,
  181476. png_uint_32 length));
  181477. #endif
  181478. #if defined(PNG_READ_iCCP_SUPPORTED)
  181479. extern void png_handle_iCCP PNGARG((png_structp png_ptr, png_infop info_ptr,
  181480. png_uint_32 length));
  181481. #endif /* PNG_READ_iCCP_SUPPORTED */
  181482. #if defined(PNG_READ_iTXt_SUPPORTED)
  181483. PNG_EXTERN void png_handle_iTXt PNGARG((png_structp png_ptr, png_infop info_ptr,
  181484. png_uint_32 length));
  181485. #endif
  181486. #if defined(PNG_READ_oFFs_SUPPORTED)
  181487. PNG_EXTERN void png_handle_oFFs PNGARG((png_structp png_ptr, png_infop info_ptr,
  181488. png_uint_32 length));
  181489. #endif
  181490. #if defined(PNG_READ_pCAL_SUPPORTED)
  181491. PNG_EXTERN void png_handle_pCAL PNGARG((png_structp png_ptr, png_infop info_ptr,
  181492. png_uint_32 length));
  181493. #endif
  181494. #if defined(PNG_READ_pHYs_SUPPORTED)
  181495. PNG_EXTERN void png_handle_pHYs PNGARG((png_structp png_ptr, png_infop info_ptr,
  181496. png_uint_32 length));
  181497. #endif
  181498. #if defined(PNG_READ_sBIT_SUPPORTED)
  181499. PNG_EXTERN void png_handle_sBIT PNGARG((png_structp png_ptr, png_infop info_ptr,
  181500. png_uint_32 length));
  181501. #endif
  181502. #if defined(PNG_READ_sCAL_SUPPORTED)
  181503. PNG_EXTERN void png_handle_sCAL PNGARG((png_structp png_ptr, png_infop info_ptr,
  181504. png_uint_32 length));
  181505. #endif
  181506. #if defined(PNG_READ_sPLT_SUPPORTED)
  181507. extern void png_handle_sPLT PNGARG((png_structp png_ptr, png_infop info_ptr,
  181508. png_uint_32 length));
  181509. #endif /* PNG_READ_sPLT_SUPPORTED */
  181510. #if defined(PNG_READ_sRGB_SUPPORTED)
  181511. PNG_EXTERN void png_handle_sRGB PNGARG((png_structp png_ptr, png_infop info_ptr,
  181512. png_uint_32 length));
  181513. #endif
  181514. #if defined(PNG_READ_tEXt_SUPPORTED)
  181515. PNG_EXTERN void png_handle_tEXt PNGARG((png_structp png_ptr, png_infop info_ptr,
  181516. png_uint_32 length));
  181517. #endif
  181518. #if defined(PNG_READ_tIME_SUPPORTED)
  181519. PNG_EXTERN void png_handle_tIME PNGARG((png_structp png_ptr, png_infop info_ptr,
  181520. png_uint_32 length));
  181521. #endif
  181522. #if defined(PNG_READ_tRNS_SUPPORTED)
  181523. PNG_EXTERN void png_handle_tRNS PNGARG((png_structp png_ptr, png_infop info_ptr,
  181524. png_uint_32 length));
  181525. #endif
  181526. #if defined(PNG_READ_zTXt_SUPPORTED)
  181527. PNG_EXTERN void png_handle_zTXt PNGARG((png_structp png_ptr, png_infop info_ptr,
  181528. png_uint_32 length));
  181529. #endif
  181530. PNG_EXTERN void png_handle_unknown PNGARG((png_structp png_ptr,
  181531. png_infop info_ptr, png_uint_32 length));
  181532. PNG_EXTERN void png_check_chunk_name PNGARG((png_structp png_ptr,
  181533. png_bytep chunk_name));
  181534. /* handle the transformations for reading and writing */
  181535. PNG_EXTERN void png_do_read_transformations PNGARG((png_structp png_ptr));
  181536. PNG_EXTERN void png_do_write_transformations PNGARG((png_structp png_ptr));
  181537. PNG_EXTERN void png_init_read_transformations PNGARG((png_structp png_ptr));
  181538. #ifdef PNG_PROGRESSIVE_READ_SUPPORTED
  181539. PNG_EXTERN void png_push_read_chunk PNGARG((png_structp png_ptr,
  181540. png_infop info_ptr));
  181541. PNG_EXTERN void png_push_read_sig PNGARG((png_structp png_ptr,
  181542. png_infop info_ptr));
  181543. PNG_EXTERN void png_push_check_crc PNGARG((png_structp png_ptr));
  181544. PNG_EXTERN void png_push_crc_skip PNGARG((png_structp png_ptr,
  181545. png_uint_32 length));
  181546. PNG_EXTERN void png_push_crc_finish PNGARG((png_structp png_ptr));
  181547. PNG_EXTERN void png_push_save_buffer PNGARG((png_structp png_ptr));
  181548. PNG_EXTERN void png_push_restore_buffer PNGARG((png_structp png_ptr,
  181549. png_bytep buffer, png_size_t buffer_length));
  181550. PNG_EXTERN void png_push_read_IDAT PNGARG((png_structp png_ptr));
  181551. PNG_EXTERN void png_process_IDAT_data PNGARG((png_structp png_ptr,
  181552. png_bytep buffer, png_size_t buffer_length));
  181553. PNG_EXTERN void png_push_process_row PNGARG((png_structp png_ptr));
  181554. PNG_EXTERN void png_push_handle_unknown PNGARG((png_structp png_ptr,
  181555. png_infop info_ptr, png_uint_32 length));
  181556. PNG_EXTERN void png_push_have_info PNGARG((png_structp png_ptr,
  181557. png_infop info_ptr));
  181558. PNG_EXTERN void png_push_have_end PNGARG((png_structp png_ptr,
  181559. png_infop info_ptr));
  181560. PNG_EXTERN void png_push_have_row PNGARG((png_structp png_ptr, png_bytep row));
  181561. PNG_EXTERN void png_push_read_end PNGARG((png_structp png_ptr,
  181562. png_infop info_ptr));
  181563. PNG_EXTERN void png_process_some_data PNGARG((png_structp png_ptr,
  181564. png_infop info_ptr));
  181565. PNG_EXTERN void png_read_push_finish_row PNGARG((png_structp png_ptr));
  181566. #if defined(PNG_READ_tEXt_SUPPORTED)
  181567. PNG_EXTERN void png_push_handle_tEXt PNGARG((png_structp png_ptr,
  181568. png_infop info_ptr, png_uint_32 length));
  181569. PNG_EXTERN void png_push_read_tEXt PNGARG((png_structp png_ptr,
  181570. png_infop info_ptr));
  181571. #endif
  181572. #if defined(PNG_READ_zTXt_SUPPORTED)
  181573. PNG_EXTERN void png_push_handle_zTXt PNGARG((png_structp png_ptr,
  181574. png_infop info_ptr, png_uint_32 length));
  181575. PNG_EXTERN void png_push_read_zTXt PNGARG((png_structp png_ptr,
  181576. png_infop info_ptr));
  181577. #endif
  181578. #if defined(PNG_READ_iTXt_SUPPORTED)
  181579. PNG_EXTERN void png_push_handle_iTXt PNGARG((png_structp png_ptr,
  181580. png_infop info_ptr, png_uint_32 length));
  181581. PNG_EXTERN void png_push_read_iTXt PNGARG((png_structp png_ptr,
  181582. png_infop info_ptr));
  181583. #endif
  181584. #endif /* PNG_PROGRESSIVE_READ_SUPPORTED */
  181585. #ifdef PNG_MNG_FEATURES_SUPPORTED
  181586. PNG_EXTERN void png_do_read_intrapixel PNGARG((png_row_infop row_info,
  181587. png_bytep row));
  181588. PNG_EXTERN void png_do_write_intrapixel PNGARG((png_row_infop row_info,
  181589. png_bytep row));
  181590. #endif
  181591. #if defined(PNG_ASSEMBLER_CODE_SUPPORTED)
  181592. #if defined(PNG_MMX_CODE_SUPPORTED)
  181593. /* png.c */ /* PRIVATE */
  181594. PNG_EXTERN void png_init_mmx_flags PNGARG((png_structp png_ptr));
  181595. #endif
  181596. #endif
  181597. #if defined(PNG_INCH_CONVERSIONS) && defined(PNG_FLOATING_POINT_SUPPORTED)
  181598. PNG_EXTERN png_uint_32 png_get_pixels_per_inch PNGARG((png_structp png_ptr,
  181599. png_infop info_ptr));
  181600. PNG_EXTERN png_uint_32 png_get_x_pixels_per_inch PNGARG((png_structp png_ptr,
  181601. png_infop info_ptr));
  181602. PNG_EXTERN png_uint_32 png_get_y_pixels_per_inch PNGARG((png_structp png_ptr,
  181603. png_infop info_ptr));
  181604. PNG_EXTERN float png_get_x_offset_inches PNGARG((png_structp png_ptr,
  181605. png_infop info_ptr));
  181606. PNG_EXTERN float png_get_y_offset_inches PNGARG((png_structp png_ptr,
  181607. png_infop info_ptr));
  181608. #if defined(PNG_pHYs_SUPPORTED)
  181609. PNG_EXTERN png_uint_32 png_get_pHYs_dpi PNGARG((png_structp png_ptr,
  181610. png_infop info_ptr, png_uint_32 *res_x, png_uint_32 *res_y, int *unit_type));
  181611. #endif /* PNG_pHYs_SUPPORTED */
  181612. #endif /* PNG_INCH_CONVERSIONS && PNG_FLOATING_POINT_SUPPORTED */
  181613. /* Maintainer: Put new private prototypes here ^ and in libpngpf.3 */
  181614. #endif /* PNG_INTERNAL */
  181615. #ifdef __cplusplus
  181616. }
  181617. #endif
  181618. #endif /* PNG_VERSION_INFO_ONLY */
  181619. /* do not put anything past this line */
  181620. #endif /* PNG_H */
  181621. /*** End of inlined file: png.h ***/
  181622. #define PNG_NO_EXTERN
  181623. /*** Start of inlined file: png.c ***/
  181624. /* png.c - location for general purpose libpng functions
  181625. *
  181626. * Last changed in libpng 1.2.21 [October 4, 2007]
  181627. * For conditions of distribution and use, see copyright notice in png.h
  181628. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  181629. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  181630. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  181631. */
  181632. #define PNG_INTERNAL
  181633. #define PNG_NO_EXTERN
  181634. /* Generate a compiler error if there is an old png.h in the search path. */
  181635. typedef version_1_2_21 Your_png_h_is_not_version_1_2_21;
  181636. /* Version information for C files. This had better match the version
  181637. * string defined in png.h. */
  181638. #ifdef PNG_USE_GLOBAL_ARRAYS
  181639. /* png_libpng_ver was changed to a function in version 1.0.5c */
  181640. PNG_CONST char png_libpng_ver[18] = PNG_LIBPNG_VER_STRING;
  181641. #ifdef PNG_READ_SUPPORTED
  181642. /* png_sig was changed to a function in version 1.0.5c */
  181643. /* Place to hold the signature string for a PNG file. */
  181644. PNG_CONST png_byte FARDATA png_sig[8] = {137, 80, 78, 71, 13, 10, 26, 10};
  181645. #endif /* PNG_READ_SUPPORTED */
  181646. /* Invoke global declarations for constant strings for known chunk types */
  181647. PNG_IHDR;
  181648. PNG_IDAT;
  181649. PNG_IEND;
  181650. PNG_PLTE;
  181651. PNG_bKGD;
  181652. PNG_cHRM;
  181653. PNG_gAMA;
  181654. PNG_hIST;
  181655. PNG_iCCP;
  181656. PNG_iTXt;
  181657. PNG_oFFs;
  181658. PNG_pCAL;
  181659. PNG_sCAL;
  181660. PNG_pHYs;
  181661. PNG_sBIT;
  181662. PNG_sPLT;
  181663. PNG_sRGB;
  181664. PNG_tEXt;
  181665. PNG_tIME;
  181666. PNG_tRNS;
  181667. PNG_zTXt;
  181668. #ifdef PNG_READ_SUPPORTED
  181669. /* arrays to facilitate easy interlacing - use pass (0 - 6) as index */
  181670. /* start of interlace block */
  181671. PNG_CONST int FARDATA png_pass_start[] = {0, 4, 0, 2, 0, 1, 0};
  181672. /* offset to next interlace block */
  181673. PNG_CONST int FARDATA png_pass_inc[] = {8, 8, 4, 4, 2, 2, 1};
  181674. /* start of interlace block in the y direction */
  181675. PNG_CONST int FARDATA png_pass_ystart[] = {0, 0, 4, 0, 2, 0, 1};
  181676. /* offset to next interlace block in the y direction */
  181677. PNG_CONST int FARDATA png_pass_yinc[] = {8, 8, 8, 4, 4, 2, 2};
  181678. /* Height of interlace block. This is not currently used - if you need
  181679. * it, uncomment it here and in png.h
  181680. PNG_CONST int FARDATA png_pass_height[] = {8, 8, 4, 4, 2, 2, 1};
  181681. */
  181682. /* Mask to determine which pixels are valid in a pass */
  181683. PNG_CONST int FARDATA png_pass_mask[] = {0x80, 0x08, 0x88, 0x22, 0xaa, 0x55, 0xff};
  181684. /* Mask to determine which pixels to overwrite while displaying */
  181685. PNG_CONST int FARDATA png_pass_dsp_mask[]
  181686. = {0xff, 0x0f, 0xff, 0x33, 0xff, 0x55, 0xff};
  181687. #endif /* PNG_READ_SUPPORTED */
  181688. #endif /* PNG_USE_GLOBAL_ARRAYS */
  181689. /* Tells libpng that we have already handled the first "num_bytes" bytes
  181690. * of the PNG file signature. If the PNG data is embedded into another
  181691. * stream we can set num_bytes = 8 so that libpng will not attempt to read
  181692. * or write any of the magic bytes before it starts on the IHDR.
  181693. */
  181694. #ifdef PNG_READ_SUPPORTED
  181695. void PNGAPI
  181696. png_set_sig_bytes(png_structp png_ptr, int num_bytes)
  181697. {
  181698. if(png_ptr == NULL) return;
  181699. png_debug(1, "in png_set_sig_bytes\n");
  181700. if (num_bytes > 8)
  181701. png_error(png_ptr, "Too many bytes for PNG signature.");
  181702. png_ptr->sig_bytes = (png_byte)(num_bytes < 0 ? 0 : num_bytes);
  181703. }
  181704. /* Checks whether the supplied bytes match the PNG signature. We allow
  181705. * checking less than the full 8-byte signature so that those apps that
  181706. * already read the first few bytes of a file to determine the file type
  181707. * can simply check the remaining bytes for extra assurance. Returns
  181708. * an integer less than, equal to, or greater than zero if sig is found,
  181709. * respectively, to be less than, to match, or be greater than the correct
  181710. * PNG signature (this is the same behaviour as strcmp, memcmp, etc).
  181711. */
  181712. int PNGAPI
  181713. png_sig_cmp(png_bytep sig, png_size_t start, png_size_t num_to_check)
  181714. {
  181715. png_byte png_signature[8] = {137, 80, 78, 71, 13, 10, 26, 10};
  181716. if (num_to_check > 8)
  181717. num_to_check = 8;
  181718. else if (num_to_check < 1)
  181719. return (-1);
  181720. if (start > 7)
  181721. return (-1);
  181722. if (start + num_to_check > 8)
  181723. num_to_check = 8 - start;
  181724. return ((int)(png_memcmp(&sig[start], &png_signature[start], num_to_check)));
  181725. }
  181726. #if defined(PNG_1_0_X) || defined(PNG_1_2_X)
  181727. /* (Obsolete) function to check signature bytes. It does not allow one
  181728. * to check a partial signature. This function might be removed in the
  181729. * future - use png_sig_cmp(). Returns true (nonzero) if the file is PNG.
  181730. */
  181731. int PNGAPI
  181732. png_check_sig(png_bytep sig, int num)
  181733. {
  181734. return ((int)!png_sig_cmp(sig, (png_size_t)0, (png_size_t)num));
  181735. }
  181736. #endif
  181737. #endif /* PNG_READ_SUPPORTED */
  181738. #if defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED)
  181739. /* Function to allocate memory for zlib and clear it to 0. */
  181740. #ifdef PNG_1_0_X
  181741. voidpf PNGAPI
  181742. #else
  181743. voidpf /* private */
  181744. #endif
  181745. png_zalloc(voidpf png_ptr, uInt items, uInt size)
  181746. {
  181747. png_voidp ptr;
  181748. png_structp p=(png_structp)png_ptr;
  181749. png_uint_32 save_flags=p->flags;
  181750. png_uint_32 num_bytes;
  181751. if(png_ptr == NULL) return (NULL);
  181752. if (items > PNG_UINT_32_MAX/size)
  181753. {
  181754. png_warning (p, "Potential overflow in png_zalloc()");
  181755. return (NULL);
  181756. }
  181757. num_bytes = (png_uint_32)items * size;
  181758. p->flags|=PNG_FLAG_MALLOC_NULL_MEM_OK;
  181759. ptr = (png_voidp)png_malloc((png_structp)png_ptr, num_bytes);
  181760. p->flags=save_flags;
  181761. #if defined(PNG_1_0_X) && !defined(PNG_NO_ZALLOC_ZERO)
  181762. if (ptr == NULL)
  181763. return ((voidpf)ptr);
  181764. if (num_bytes > (png_uint_32)0x8000L)
  181765. {
  181766. png_memset(ptr, 0, (png_size_t)0x8000L);
  181767. png_memset((png_bytep)ptr + (png_size_t)0x8000L, 0,
  181768. (png_size_t)(num_bytes - (png_uint_32)0x8000L));
  181769. }
  181770. else
  181771. {
  181772. png_memset(ptr, 0, (png_size_t)num_bytes);
  181773. }
  181774. #endif
  181775. return ((voidpf)ptr);
  181776. }
  181777. /* function to free memory for zlib */
  181778. #ifdef PNG_1_0_X
  181779. void PNGAPI
  181780. #else
  181781. void /* private */
  181782. #endif
  181783. png_zfree(voidpf png_ptr, voidpf ptr)
  181784. {
  181785. png_free((png_structp)png_ptr, (png_voidp)ptr);
  181786. }
  181787. /* Reset the CRC variable to 32 bits of 1's. Care must be taken
  181788. * in case CRC is > 32 bits to leave the top bits 0.
  181789. */
  181790. void /* PRIVATE */
  181791. png_reset_crc(png_structp png_ptr)
  181792. {
  181793. png_ptr->crc = crc32(0, Z_NULL, 0);
  181794. }
  181795. /* Calculate the CRC over a section of data. We can only pass as
  181796. * much data to this routine as the largest single buffer size. We
  181797. * also check that this data will actually be used before going to the
  181798. * trouble of calculating it.
  181799. */
  181800. void /* PRIVATE */
  181801. png_calculate_crc(png_structp png_ptr, png_bytep ptr, png_size_t length)
  181802. {
  181803. int need_crc = 1;
  181804. if (png_ptr->chunk_name[0] & 0x20) /* ancillary */
  181805. {
  181806. if ((png_ptr->flags & PNG_FLAG_CRC_ANCILLARY_MASK) ==
  181807. (PNG_FLAG_CRC_ANCILLARY_USE | PNG_FLAG_CRC_ANCILLARY_NOWARN))
  181808. need_crc = 0;
  181809. }
  181810. else /* critical */
  181811. {
  181812. if (png_ptr->flags & PNG_FLAG_CRC_CRITICAL_IGNORE)
  181813. need_crc = 0;
  181814. }
  181815. if (need_crc)
  181816. png_ptr->crc = crc32(png_ptr->crc, ptr, (uInt)length);
  181817. }
  181818. /* Allocate the memory for an info_struct for the application. We don't
  181819. * really need the png_ptr, but it could potentially be useful in the
  181820. * future. This should be used in favour of malloc(png_sizeof(png_info))
  181821. * and png_info_init() so that applications that want to use a shared
  181822. * libpng don't have to be recompiled if png_info changes size.
  181823. */
  181824. png_infop PNGAPI
  181825. png_create_info_struct(png_structp png_ptr)
  181826. {
  181827. png_infop info_ptr;
  181828. png_debug(1, "in png_create_info_struct\n");
  181829. if(png_ptr == NULL) return (NULL);
  181830. #ifdef PNG_USER_MEM_SUPPORTED
  181831. info_ptr = (png_infop)png_create_struct_2(PNG_STRUCT_INFO,
  181832. png_ptr->malloc_fn, png_ptr->mem_ptr);
  181833. #else
  181834. info_ptr = (png_infop)png_create_struct(PNG_STRUCT_INFO);
  181835. #endif
  181836. if (info_ptr != NULL)
  181837. png_info_init_3(&info_ptr, png_sizeof(png_info));
  181838. return (info_ptr);
  181839. }
  181840. /* This function frees the memory associated with a single info struct.
  181841. * Normally, one would use either png_destroy_read_struct() or
  181842. * png_destroy_write_struct() to free an info struct, but this may be
  181843. * useful for some applications.
  181844. */
  181845. void PNGAPI
  181846. png_destroy_info_struct(png_structp png_ptr, png_infopp info_ptr_ptr)
  181847. {
  181848. png_infop info_ptr = NULL;
  181849. if(png_ptr == NULL) return;
  181850. png_debug(1, "in png_destroy_info_struct\n");
  181851. if (info_ptr_ptr != NULL)
  181852. info_ptr = *info_ptr_ptr;
  181853. if (info_ptr != NULL)
  181854. {
  181855. png_info_destroy(png_ptr, info_ptr);
  181856. #ifdef PNG_USER_MEM_SUPPORTED
  181857. png_destroy_struct_2((png_voidp)info_ptr, png_ptr->free_fn,
  181858. png_ptr->mem_ptr);
  181859. #else
  181860. png_destroy_struct((png_voidp)info_ptr);
  181861. #endif
  181862. *info_ptr_ptr = NULL;
  181863. }
  181864. }
  181865. /* Initialize the info structure. This is now an internal function (0.89)
  181866. * and applications using it are urged to use png_create_info_struct()
  181867. * instead.
  181868. */
  181869. #if defined(PNG_1_0_X) || defined(PNG_1_2_X)
  181870. #undef png_info_init
  181871. void PNGAPI
  181872. png_info_init(png_infop info_ptr)
  181873. {
  181874. /* We only come here via pre-1.0.12-compiled applications */
  181875. png_info_init_3(&info_ptr, 0);
  181876. }
  181877. #endif
  181878. void PNGAPI
  181879. png_info_init_3(png_infopp ptr_ptr, png_size_t png_info_struct_size)
  181880. {
  181881. png_infop info_ptr = *ptr_ptr;
  181882. if(info_ptr == NULL) return;
  181883. png_debug(1, "in png_info_init_3\n");
  181884. if(png_sizeof(png_info) > png_info_struct_size)
  181885. {
  181886. png_destroy_struct(info_ptr);
  181887. info_ptr = (png_infop)png_create_struct(PNG_STRUCT_INFO);
  181888. *ptr_ptr = info_ptr;
  181889. }
  181890. /* set everything to 0 */
  181891. png_memset(info_ptr, 0, png_sizeof (png_info));
  181892. }
  181893. #ifdef PNG_FREE_ME_SUPPORTED
  181894. void PNGAPI
  181895. png_data_freer(png_structp png_ptr, png_infop info_ptr,
  181896. int freer, png_uint_32 mask)
  181897. {
  181898. png_debug(1, "in png_data_freer\n");
  181899. if (png_ptr == NULL || info_ptr == NULL)
  181900. return;
  181901. if(freer == PNG_DESTROY_WILL_FREE_DATA)
  181902. info_ptr->free_me |= mask;
  181903. else if(freer == PNG_USER_WILL_FREE_DATA)
  181904. info_ptr->free_me &= ~mask;
  181905. else
  181906. png_warning(png_ptr,
  181907. "Unknown freer parameter in png_data_freer.");
  181908. }
  181909. #endif
  181910. void PNGAPI
  181911. png_free_data(png_structp png_ptr, png_infop info_ptr, png_uint_32 mask,
  181912. int num)
  181913. {
  181914. png_debug(1, "in png_free_data\n");
  181915. if (png_ptr == NULL || info_ptr == NULL)
  181916. return;
  181917. #if defined(PNG_TEXT_SUPPORTED)
  181918. /* free text item num or (if num == -1) all text items */
  181919. #ifdef PNG_FREE_ME_SUPPORTED
  181920. if ((mask & PNG_FREE_TEXT) & info_ptr->free_me)
  181921. #else
  181922. if (mask & PNG_FREE_TEXT)
  181923. #endif
  181924. {
  181925. if (num != -1)
  181926. {
  181927. if (info_ptr->text && info_ptr->text[num].key)
  181928. {
  181929. png_free(png_ptr, info_ptr->text[num].key);
  181930. info_ptr->text[num].key = NULL;
  181931. }
  181932. }
  181933. else
  181934. {
  181935. int i;
  181936. for (i = 0; i < info_ptr->num_text; i++)
  181937. png_free_data(png_ptr, info_ptr, PNG_FREE_TEXT, i);
  181938. png_free(png_ptr, info_ptr->text);
  181939. info_ptr->text = NULL;
  181940. info_ptr->num_text=0;
  181941. }
  181942. }
  181943. #endif
  181944. #if defined(PNG_tRNS_SUPPORTED)
  181945. /* free any tRNS entry */
  181946. #ifdef PNG_FREE_ME_SUPPORTED
  181947. if ((mask & PNG_FREE_TRNS) & info_ptr->free_me)
  181948. #else
  181949. if ((mask & PNG_FREE_TRNS) && (png_ptr->flags & PNG_FLAG_FREE_TRNS))
  181950. #endif
  181951. {
  181952. png_free(png_ptr, info_ptr->trans);
  181953. info_ptr->valid &= ~PNG_INFO_tRNS;
  181954. #ifndef PNG_FREE_ME_SUPPORTED
  181955. png_ptr->flags &= ~PNG_FLAG_FREE_TRNS;
  181956. #endif
  181957. info_ptr->trans = NULL;
  181958. }
  181959. #endif
  181960. #if defined(PNG_sCAL_SUPPORTED)
  181961. /* free any sCAL entry */
  181962. #ifdef PNG_FREE_ME_SUPPORTED
  181963. if ((mask & PNG_FREE_SCAL) & info_ptr->free_me)
  181964. #else
  181965. if (mask & PNG_FREE_SCAL)
  181966. #endif
  181967. {
  181968. #if defined(PNG_FIXED_POINT_SUPPORTED) && !defined(PNG_FLOATING_POINT_SUPPORTED)
  181969. png_free(png_ptr, info_ptr->scal_s_width);
  181970. png_free(png_ptr, info_ptr->scal_s_height);
  181971. info_ptr->scal_s_width = NULL;
  181972. info_ptr->scal_s_height = NULL;
  181973. #endif
  181974. info_ptr->valid &= ~PNG_INFO_sCAL;
  181975. }
  181976. #endif
  181977. #if defined(PNG_pCAL_SUPPORTED)
  181978. /* free any pCAL entry */
  181979. #ifdef PNG_FREE_ME_SUPPORTED
  181980. if ((mask & PNG_FREE_PCAL) & info_ptr->free_me)
  181981. #else
  181982. if (mask & PNG_FREE_PCAL)
  181983. #endif
  181984. {
  181985. png_free(png_ptr, info_ptr->pcal_purpose);
  181986. png_free(png_ptr, info_ptr->pcal_units);
  181987. info_ptr->pcal_purpose = NULL;
  181988. info_ptr->pcal_units = NULL;
  181989. if (info_ptr->pcal_params != NULL)
  181990. {
  181991. int i;
  181992. for (i = 0; i < (int)info_ptr->pcal_nparams; i++)
  181993. {
  181994. png_free(png_ptr, info_ptr->pcal_params[i]);
  181995. info_ptr->pcal_params[i]=NULL;
  181996. }
  181997. png_free(png_ptr, info_ptr->pcal_params);
  181998. info_ptr->pcal_params = NULL;
  181999. }
  182000. info_ptr->valid &= ~PNG_INFO_pCAL;
  182001. }
  182002. #endif
  182003. #if defined(PNG_iCCP_SUPPORTED)
  182004. /* free any iCCP entry */
  182005. #ifdef PNG_FREE_ME_SUPPORTED
  182006. if ((mask & PNG_FREE_ICCP) & info_ptr->free_me)
  182007. #else
  182008. if (mask & PNG_FREE_ICCP)
  182009. #endif
  182010. {
  182011. png_free(png_ptr, info_ptr->iccp_name);
  182012. png_free(png_ptr, info_ptr->iccp_profile);
  182013. info_ptr->iccp_name = NULL;
  182014. info_ptr->iccp_profile = NULL;
  182015. info_ptr->valid &= ~PNG_INFO_iCCP;
  182016. }
  182017. #endif
  182018. #if defined(PNG_sPLT_SUPPORTED)
  182019. /* free a given sPLT entry, or (if num == -1) all sPLT entries */
  182020. #ifdef PNG_FREE_ME_SUPPORTED
  182021. if ((mask & PNG_FREE_SPLT) & info_ptr->free_me)
  182022. #else
  182023. if (mask & PNG_FREE_SPLT)
  182024. #endif
  182025. {
  182026. if (num != -1)
  182027. {
  182028. if(info_ptr->splt_palettes)
  182029. {
  182030. png_free(png_ptr, info_ptr->splt_palettes[num].name);
  182031. png_free(png_ptr, info_ptr->splt_palettes[num].entries);
  182032. info_ptr->splt_palettes[num].name = NULL;
  182033. info_ptr->splt_palettes[num].entries = NULL;
  182034. }
  182035. }
  182036. else
  182037. {
  182038. if(info_ptr->splt_palettes_num)
  182039. {
  182040. int i;
  182041. for (i = 0; i < (int)info_ptr->splt_palettes_num; i++)
  182042. png_free_data(png_ptr, info_ptr, PNG_FREE_SPLT, i);
  182043. png_free(png_ptr, info_ptr->splt_palettes);
  182044. info_ptr->splt_palettes = NULL;
  182045. info_ptr->splt_palettes_num = 0;
  182046. }
  182047. info_ptr->valid &= ~PNG_INFO_sPLT;
  182048. }
  182049. }
  182050. #endif
  182051. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  182052. if(png_ptr->unknown_chunk.data)
  182053. {
  182054. png_free(png_ptr, png_ptr->unknown_chunk.data);
  182055. png_ptr->unknown_chunk.data = NULL;
  182056. }
  182057. #ifdef PNG_FREE_ME_SUPPORTED
  182058. if ((mask & PNG_FREE_UNKN) & info_ptr->free_me)
  182059. #else
  182060. if (mask & PNG_FREE_UNKN)
  182061. #endif
  182062. {
  182063. if (num != -1)
  182064. {
  182065. if(info_ptr->unknown_chunks)
  182066. {
  182067. png_free(png_ptr, info_ptr->unknown_chunks[num].data);
  182068. info_ptr->unknown_chunks[num].data = NULL;
  182069. }
  182070. }
  182071. else
  182072. {
  182073. int i;
  182074. if(info_ptr->unknown_chunks_num)
  182075. {
  182076. for (i = 0; i < (int)info_ptr->unknown_chunks_num; i++)
  182077. png_free_data(png_ptr, info_ptr, PNG_FREE_UNKN, i);
  182078. png_free(png_ptr, info_ptr->unknown_chunks);
  182079. info_ptr->unknown_chunks = NULL;
  182080. info_ptr->unknown_chunks_num = 0;
  182081. }
  182082. }
  182083. }
  182084. #endif
  182085. #if defined(PNG_hIST_SUPPORTED)
  182086. /* free any hIST entry */
  182087. #ifdef PNG_FREE_ME_SUPPORTED
  182088. if ((mask & PNG_FREE_HIST) & info_ptr->free_me)
  182089. #else
  182090. if ((mask & PNG_FREE_HIST) && (png_ptr->flags & PNG_FLAG_FREE_HIST))
  182091. #endif
  182092. {
  182093. png_free(png_ptr, info_ptr->hist);
  182094. info_ptr->hist = NULL;
  182095. info_ptr->valid &= ~PNG_INFO_hIST;
  182096. #ifndef PNG_FREE_ME_SUPPORTED
  182097. png_ptr->flags &= ~PNG_FLAG_FREE_HIST;
  182098. #endif
  182099. }
  182100. #endif
  182101. /* free any PLTE entry that was internally allocated */
  182102. #ifdef PNG_FREE_ME_SUPPORTED
  182103. if ((mask & PNG_FREE_PLTE) & info_ptr->free_me)
  182104. #else
  182105. if ((mask & PNG_FREE_PLTE) && (png_ptr->flags & PNG_FLAG_FREE_PLTE))
  182106. #endif
  182107. {
  182108. png_zfree(png_ptr, info_ptr->palette);
  182109. info_ptr->palette = NULL;
  182110. info_ptr->valid &= ~PNG_INFO_PLTE;
  182111. #ifndef PNG_FREE_ME_SUPPORTED
  182112. png_ptr->flags &= ~PNG_FLAG_FREE_PLTE;
  182113. #endif
  182114. info_ptr->num_palette = 0;
  182115. }
  182116. #if defined(PNG_INFO_IMAGE_SUPPORTED)
  182117. /* free any image bits attached to the info structure */
  182118. #ifdef PNG_FREE_ME_SUPPORTED
  182119. if ((mask & PNG_FREE_ROWS) & info_ptr->free_me)
  182120. #else
  182121. if (mask & PNG_FREE_ROWS)
  182122. #endif
  182123. {
  182124. if(info_ptr->row_pointers)
  182125. {
  182126. int row;
  182127. for (row = 0; row < (int)info_ptr->height; row++)
  182128. {
  182129. png_free(png_ptr, info_ptr->row_pointers[row]);
  182130. info_ptr->row_pointers[row]=NULL;
  182131. }
  182132. png_free(png_ptr, info_ptr->row_pointers);
  182133. info_ptr->row_pointers=NULL;
  182134. }
  182135. info_ptr->valid &= ~PNG_INFO_IDAT;
  182136. }
  182137. #endif
  182138. #ifdef PNG_FREE_ME_SUPPORTED
  182139. if(num == -1)
  182140. info_ptr->free_me &= ~mask;
  182141. else
  182142. info_ptr->free_me &= ~(mask & ~PNG_FREE_MUL);
  182143. #endif
  182144. }
  182145. /* This is an internal routine to free any memory that the info struct is
  182146. * pointing to before re-using it or freeing the struct itself. Recall
  182147. * that png_free() checks for NULL pointers for us.
  182148. */
  182149. void /* PRIVATE */
  182150. png_info_destroy(png_structp png_ptr, png_infop info_ptr)
  182151. {
  182152. png_debug(1, "in png_info_destroy\n");
  182153. png_free_data(png_ptr, info_ptr, PNG_FREE_ALL, -1);
  182154. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  182155. if (png_ptr->num_chunk_list)
  182156. {
  182157. png_free(png_ptr, png_ptr->chunk_list);
  182158. png_ptr->chunk_list=NULL;
  182159. png_ptr->num_chunk_list=0;
  182160. }
  182161. #endif
  182162. png_info_init_3(&info_ptr, png_sizeof(png_info));
  182163. }
  182164. #endif /* defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED) */
  182165. /* This function returns a pointer to the io_ptr associated with the user
  182166. * functions. The application should free any memory associated with this
  182167. * pointer before png_write_destroy() or png_read_destroy() are called.
  182168. */
  182169. png_voidp PNGAPI
  182170. png_get_io_ptr(png_structp png_ptr)
  182171. {
  182172. if(png_ptr == NULL) return (NULL);
  182173. return (png_ptr->io_ptr);
  182174. }
  182175. #if defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED)
  182176. #if !defined(PNG_NO_STDIO)
  182177. /* Initialize the default input/output functions for the PNG file. If you
  182178. * use your own read or write routines, you can call either png_set_read_fn()
  182179. * or png_set_write_fn() instead of png_init_io(). If you have defined
  182180. * PNG_NO_STDIO, you must use a function of your own because "FILE *" isn't
  182181. * necessarily available.
  182182. */
  182183. void PNGAPI
  182184. png_init_io(png_structp png_ptr, png_FILE_p fp)
  182185. {
  182186. png_debug(1, "in png_init_io\n");
  182187. if(png_ptr == NULL) return;
  182188. png_ptr->io_ptr = (png_voidp)fp;
  182189. }
  182190. #endif
  182191. #if defined(PNG_TIME_RFC1123_SUPPORTED)
  182192. /* Convert the supplied time into an RFC 1123 string suitable for use in
  182193. * a "Creation Time" or other text-based time string.
  182194. */
  182195. png_charp PNGAPI
  182196. png_convert_to_rfc1123(png_structp png_ptr, png_timep ptime)
  182197. {
  182198. static PNG_CONST char short_months[12][4] =
  182199. {"Jan", "Feb", "Mar", "Apr", "May", "Jun",
  182200. "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"};
  182201. if(png_ptr == NULL) return (NULL);
  182202. if (png_ptr->time_buffer == NULL)
  182203. {
  182204. png_ptr->time_buffer = (png_charp)png_malloc(png_ptr, (png_uint_32)(29*
  182205. png_sizeof(char)));
  182206. }
  182207. #if defined(_WIN32_WCE)
  182208. {
  182209. wchar_t time_buf[29];
  182210. wsprintf(time_buf, TEXT("%d %S %d %02d:%02d:%02d +0000"),
  182211. ptime->day % 32, short_months[(ptime->month - 1) % 12],
  182212. ptime->year, ptime->hour % 24, ptime->minute % 60,
  182213. ptime->second % 61);
  182214. WideCharToMultiByte(CP_ACP, 0, time_buf, -1, png_ptr->time_buffer, 29,
  182215. NULL, NULL);
  182216. }
  182217. #else
  182218. #ifdef USE_FAR_KEYWORD
  182219. {
  182220. char near_time_buf[29];
  182221. png_snprintf6(near_time_buf,29,"%d %s %d %02d:%02d:%02d +0000",
  182222. ptime->day % 32, short_months[(ptime->month - 1) % 12],
  182223. ptime->year, ptime->hour % 24, ptime->minute % 60,
  182224. ptime->second % 61);
  182225. png_memcpy(png_ptr->time_buffer, near_time_buf,
  182226. 29*png_sizeof(char));
  182227. }
  182228. #else
  182229. png_snprintf6(png_ptr->time_buffer,29,"%d %s %d %02d:%02d:%02d +0000",
  182230. ptime->day % 32, short_months[(ptime->month - 1) % 12],
  182231. ptime->year, ptime->hour % 24, ptime->minute % 60,
  182232. ptime->second % 61);
  182233. #endif
  182234. #endif /* _WIN32_WCE */
  182235. return ((png_charp)png_ptr->time_buffer);
  182236. }
  182237. #endif /* PNG_TIME_RFC1123_SUPPORTED */
  182238. #endif /* defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED) */
  182239. png_charp PNGAPI
  182240. png_get_copyright(png_structp png_ptr)
  182241. {
  182242. png_ptr = png_ptr; /* silence compiler warning about unused png_ptr */
  182243. return ((png_charp) "\n libpng version 1.2.21 - October 4, 2007\n\
  182244. Copyright (c) 1998-2007 Glenn Randers-Pehrson\n\
  182245. Copyright (c) 1996-1997 Andreas Dilger\n\
  182246. Copyright (c) 1995-1996 Guy Eric Schalnat, Group 42, Inc.\n");
  182247. }
  182248. /* The following return the library version as a short string in the
  182249. * format 1.0.0 through 99.99.99zz. To get the version of *.h files
  182250. * used with your application, print out PNG_LIBPNG_VER_STRING, which
  182251. * is defined in png.h.
  182252. * Note: now there is no difference between png_get_libpng_ver() and
  182253. * png_get_header_ver(). Due to the version_nn_nn_nn typedef guard,
  182254. * it is guaranteed that png.c uses the correct version of png.h.
  182255. */
  182256. png_charp PNGAPI
  182257. png_get_libpng_ver(png_structp png_ptr)
  182258. {
  182259. /* Version of *.c files used when building libpng */
  182260. png_ptr = png_ptr; /* silence compiler warning about unused png_ptr */
  182261. return ((png_charp) PNG_LIBPNG_VER_STRING);
  182262. }
  182263. png_charp PNGAPI
  182264. png_get_header_ver(png_structp png_ptr)
  182265. {
  182266. /* Version of *.h files used when building libpng */
  182267. png_ptr = png_ptr; /* silence compiler warning about unused png_ptr */
  182268. return ((png_charp) PNG_LIBPNG_VER_STRING);
  182269. }
  182270. png_charp PNGAPI
  182271. png_get_header_version(png_structp png_ptr)
  182272. {
  182273. /* Returns longer string containing both version and date */
  182274. png_ptr = png_ptr; /* silence compiler warning about unused png_ptr */
  182275. return ((png_charp) PNG_HEADER_VERSION_STRING
  182276. #ifndef PNG_READ_SUPPORTED
  182277. " (NO READ SUPPORT)"
  182278. #endif
  182279. "\n");
  182280. }
  182281. #if defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED)
  182282. #ifdef PNG_HANDLE_AS_UNKNOWN_SUPPORTED
  182283. int PNGAPI
  182284. png_handle_as_unknown(png_structp png_ptr, png_bytep chunk_name)
  182285. {
  182286. /* check chunk_name and return "keep" value if it's on the list, else 0 */
  182287. int i;
  182288. png_bytep p;
  182289. if(png_ptr == NULL || chunk_name == NULL || png_ptr->num_chunk_list<=0)
  182290. return 0;
  182291. p=png_ptr->chunk_list+png_ptr->num_chunk_list*5-5;
  182292. for (i = png_ptr->num_chunk_list; i; i--, p-=5)
  182293. if (!png_memcmp(chunk_name, p, 4))
  182294. return ((int)*(p+4));
  182295. return 0;
  182296. }
  182297. #endif
  182298. /* This function, added to libpng-1.0.6g, is untested. */
  182299. int PNGAPI
  182300. png_reset_zstream(png_structp png_ptr)
  182301. {
  182302. if (png_ptr == NULL) return Z_STREAM_ERROR;
  182303. return (inflateReset(&png_ptr->zstream));
  182304. }
  182305. #endif /* defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED) */
  182306. /* This function was added to libpng-1.0.7 */
  182307. png_uint_32 PNGAPI
  182308. png_access_version_number(void)
  182309. {
  182310. /* Version of *.c files used when building libpng */
  182311. return((png_uint_32) PNG_LIBPNG_VER);
  182312. }
  182313. #if defined(PNG_READ_SUPPORTED) && defined(PNG_ASSEMBLER_CODE_SUPPORTED)
  182314. #if !defined(PNG_1_0_X)
  182315. /* this function was added to libpng 1.2.0 */
  182316. int PNGAPI
  182317. png_mmx_support(void)
  182318. {
  182319. /* obsolete, to be removed from libpng-1.4.0 */
  182320. return -1;
  182321. }
  182322. #endif /* PNG_1_0_X */
  182323. #endif /* PNG_READ_SUPPORTED && PNG_ASSEMBLER_CODE_SUPPORTED */
  182324. #if defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED)
  182325. #ifdef PNG_SIZE_T
  182326. /* Added at libpng version 1.2.6 */
  182327. PNG_EXTERN png_size_t PNGAPI png_convert_size PNGARG((size_t size));
  182328. png_size_t PNGAPI
  182329. png_convert_size(size_t size)
  182330. {
  182331. if (size > (png_size_t)-1)
  182332. PNG_ABORT(); /* We haven't got access to png_ptr, so no png_error() */
  182333. return ((png_size_t)size);
  182334. }
  182335. #endif /* PNG_SIZE_T */
  182336. #endif /* defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED) */
  182337. /*** End of inlined file: png.c ***/
  182338. /*** Start of inlined file: pngerror.c ***/
  182339. /* pngerror.c - stub functions for i/o and memory allocation
  182340. *
  182341. * Last changed in libpng 1.2.20 October 4, 2007
  182342. * For conditions of distribution and use, see copyright notice in png.h
  182343. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  182344. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  182345. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  182346. *
  182347. * This file provides a location for all error handling. Users who
  182348. * need special error handling are expected to write replacement functions
  182349. * and use png_set_error_fn() to use those functions. See the instructions
  182350. * at each function.
  182351. */
  182352. #define PNG_INTERNAL
  182353. #if defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED)
  182354. static void /* PRIVATE */
  182355. png_default_error PNGARG((png_structp png_ptr,
  182356. png_const_charp error_message));
  182357. #ifndef PNG_NO_WARNINGS
  182358. static void /* PRIVATE */
  182359. png_default_warning PNGARG((png_structp png_ptr,
  182360. png_const_charp warning_message));
  182361. #endif /* PNG_NO_WARNINGS */
  182362. /* This function is called whenever there is a fatal error. This function
  182363. * should not be changed. If there is a need to handle errors differently,
  182364. * you should supply a replacement error function and use png_set_error_fn()
  182365. * to replace the error function at run-time.
  182366. */
  182367. #ifndef PNG_NO_ERROR_TEXT
  182368. void PNGAPI
  182369. png_error(png_structp png_ptr, png_const_charp error_message)
  182370. {
  182371. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  182372. char msg[16];
  182373. if (png_ptr != NULL)
  182374. {
  182375. if (png_ptr->flags&
  182376. (PNG_FLAG_STRIP_ERROR_NUMBERS|PNG_FLAG_STRIP_ERROR_TEXT))
  182377. {
  182378. if (*error_message == '#')
  182379. {
  182380. int offset;
  182381. for (offset=1; offset<15; offset++)
  182382. if (*(error_message+offset) == ' ')
  182383. break;
  182384. if (png_ptr->flags&PNG_FLAG_STRIP_ERROR_TEXT)
  182385. {
  182386. int i;
  182387. for (i=0; i<offset-1; i++)
  182388. msg[i]=error_message[i+1];
  182389. msg[i]='\0';
  182390. error_message=msg;
  182391. }
  182392. else
  182393. error_message+=offset;
  182394. }
  182395. else
  182396. {
  182397. if (png_ptr->flags&PNG_FLAG_STRIP_ERROR_TEXT)
  182398. {
  182399. msg[0]='0';
  182400. msg[1]='\0';
  182401. error_message=msg;
  182402. }
  182403. }
  182404. }
  182405. }
  182406. #endif
  182407. if (png_ptr != NULL && png_ptr->error_fn != NULL)
  182408. (*(png_ptr->error_fn))(png_ptr, error_message);
  182409. /* If the custom handler doesn't exist, or if it returns,
  182410. use the default handler, which will not return. */
  182411. png_default_error(png_ptr, error_message);
  182412. }
  182413. #else
  182414. void PNGAPI
  182415. png_err(png_structp png_ptr)
  182416. {
  182417. if (png_ptr != NULL && png_ptr->error_fn != NULL)
  182418. (*(png_ptr->error_fn))(png_ptr, '\0');
  182419. /* If the custom handler doesn't exist, or if it returns,
  182420. use the default handler, which will not return. */
  182421. png_default_error(png_ptr, '\0');
  182422. }
  182423. #endif /* PNG_NO_ERROR_TEXT */
  182424. #ifndef PNG_NO_WARNINGS
  182425. /* This function is called whenever there is a non-fatal error. This function
  182426. * should not be changed. If there is a need to handle warnings differently,
  182427. * you should supply a replacement warning function and use
  182428. * png_set_error_fn() to replace the warning function at run-time.
  182429. */
  182430. void PNGAPI
  182431. png_warning(png_structp png_ptr, png_const_charp warning_message)
  182432. {
  182433. int offset = 0;
  182434. if (png_ptr != NULL)
  182435. {
  182436. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  182437. if (png_ptr->flags&
  182438. (PNG_FLAG_STRIP_ERROR_NUMBERS|PNG_FLAG_STRIP_ERROR_TEXT))
  182439. #endif
  182440. {
  182441. if (*warning_message == '#')
  182442. {
  182443. for (offset=1; offset<15; offset++)
  182444. if (*(warning_message+offset) == ' ')
  182445. break;
  182446. }
  182447. }
  182448. if (png_ptr != NULL && png_ptr->warning_fn != NULL)
  182449. (*(png_ptr->warning_fn))(png_ptr, warning_message+offset);
  182450. }
  182451. else
  182452. png_default_warning(png_ptr, warning_message+offset);
  182453. }
  182454. #endif /* PNG_NO_WARNINGS */
  182455. /* These utilities are used internally to build an error message that relates
  182456. * to the current chunk. The chunk name comes from png_ptr->chunk_name,
  182457. * this is used to prefix the message. The message is limited in length
  182458. * to 63 bytes, the name characters are output as hex digits wrapped in []
  182459. * if the character is invalid.
  182460. */
  182461. #define isnonalpha(c) ((c) < 65 || (c) > 122 || ((c) > 90 && (c) < 97))
  182462. /*static PNG_CONST char png_digit[16] = {
  182463. '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
  182464. 'A', 'B', 'C', 'D', 'E', 'F'
  182465. };*/
  182466. #if !defined(PNG_NO_WARNINGS) || !defined(PNG_NO_ERROR_TEXT)
  182467. static void /* PRIVATE */
  182468. png_format_buffer(png_structp png_ptr, png_charp buffer, png_const_charp
  182469. error_message)
  182470. {
  182471. int iout = 0, iin = 0;
  182472. while (iin < 4)
  182473. {
  182474. int c = png_ptr->chunk_name[iin++];
  182475. if (isnonalpha(c))
  182476. {
  182477. buffer[iout++] = '[';
  182478. buffer[iout++] = png_digit[(c & 0xf0) >> 4];
  182479. buffer[iout++] = png_digit[c & 0x0f];
  182480. buffer[iout++] = ']';
  182481. }
  182482. else
  182483. {
  182484. buffer[iout++] = (png_byte)c;
  182485. }
  182486. }
  182487. if (error_message == NULL)
  182488. buffer[iout] = 0;
  182489. else
  182490. {
  182491. buffer[iout++] = ':';
  182492. buffer[iout++] = ' ';
  182493. png_strncpy(buffer+iout, error_message, 63);
  182494. buffer[iout+63] = 0;
  182495. }
  182496. }
  182497. #ifdef PNG_READ_SUPPORTED
  182498. void PNGAPI
  182499. png_chunk_error(png_structp png_ptr, png_const_charp error_message)
  182500. {
  182501. char msg[18+64];
  182502. if (png_ptr == NULL)
  182503. png_error(png_ptr, error_message);
  182504. else
  182505. {
  182506. png_format_buffer(png_ptr, msg, error_message);
  182507. png_error(png_ptr, msg);
  182508. }
  182509. }
  182510. #endif /* PNG_READ_SUPPORTED */
  182511. #endif /* !defined(PNG_NO_WARNINGS) || !defined(PNG_NO_ERROR_TEXT) */
  182512. #ifndef PNG_NO_WARNINGS
  182513. void PNGAPI
  182514. png_chunk_warning(png_structp png_ptr, png_const_charp warning_message)
  182515. {
  182516. char msg[18+64];
  182517. if (png_ptr == NULL)
  182518. png_warning(png_ptr, warning_message);
  182519. else
  182520. {
  182521. png_format_buffer(png_ptr, msg, warning_message);
  182522. png_warning(png_ptr, msg);
  182523. }
  182524. }
  182525. #endif /* PNG_NO_WARNINGS */
  182526. /* This is the default error handling function. Note that replacements for
  182527. * this function MUST NOT RETURN, or the program will likely crash. This
  182528. * function is used by default, or if the program supplies NULL for the
  182529. * error function pointer in png_set_error_fn().
  182530. */
  182531. static void /* PRIVATE */
  182532. png_default_error(png_structp, png_const_charp error_message)
  182533. {
  182534. #ifndef PNG_NO_CONSOLE_IO
  182535. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  182536. if (*error_message == '#')
  182537. {
  182538. int offset;
  182539. char error_number[16];
  182540. for (offset=0; offset<15; offset++)
  182541. {
  182542. error_number[offset] = *(error_message+offset+1);
  182543. if (*(error_message+offset) == ' ')
  182544. break;
  182545. }
  182546. if((offset > 1) && (offset < 15))
  182547. {
  182548. error_number[offset-1]='\0';
  182549. fprintf(stderr, "libpng error no. %s: %s\n", error_number,
  182550. error_message+offset);
  182551. }
  182552. else
  182553. fprintf(stderr, "libpng error: %s, offset=%d\n", error_message,offset);
  182554. }
  182555. else
  182556. #endif
  182557. fprintf(stderr, "libpng error: %s\n", error_message);
  182558. #endif
  182559. #ifdef PNG_SETJMP_SUPPORTED
  182560. if (png_ptr)
  182561. {
  182562. # ifdef USE_FAR_KEYWORD
  182563. {
  182564. jmp_buf jmpbuf;
  182565. png_memcpy(jmpbuf, png_ptr->jmpbuf, png_sizeof(jmp_buf));
  182566. longjmp(jmpbuf, 1);
  182567. }
  182568. # else
  182569. longjmp(png_ptr->jmpbuf, 1);
  182570. # endif
  182571. }
  182572. #else
  182573. PNG_ABORT();
  182574. #endif
  182575. #ifdef PNG_NO_CONSOLE_IO
  182576. error_message = error_message; /* make compiler happy */
  182577. #endif
  182578. }
  182579. #ifndef PNG_NO_WARNINGS
  182580. /* This function is called when there is a warning, but the library thinks
  182581. * it can continue anyway. Replacement functions don't have to do anything
  182582. * here if you don't want them to. In the default configuration, png_ptr is
  182583. * not used, but it is passed in case it may be useful.
  182584. */
  182585. static void /* PRIVATE */
  182586. png_default_warning(png_structp png_ptr, png_const_charp warning_message)
  182587. {
  182588. #ifndef PNG_NO_CONSOLE_IO
  182589. # ifdef PNG_ERROR_NUMBERS_SUPPORTED
  182590. if (*warning_message == '#')
  182591. {
  182592. int offset;
  182593. char warning_number[16];
  182594. for (offset=0; offset<15; offset++)
  182595. {
  182596. warning_number[offset]=*(warning_message+offset+1);
  182597. if (*(warning_message+offset) == ' ')
  182598. break;
  182599. }
  182600. if((offset > 1) && (offset < 15))
  182601. {
  182602. warning_number[offset-1]='\0';
  182603. fprintf(stderr, "libpng warning no. %s: %s\n", warning_number,
  182604. warning_message+offset);
  182605. }
  182606. else
  182607. fprintf(stderr, "libpng warning: %s\n", warning_message);
  182608. }
  182609. else
  182610. # endif
  182611. fprintf(stderr, "libpng warning: %s\n", warning_message);
  182612. #else
  182613. warning_message = warning_message; /* make compiler happy */
  182614. #endif
  182615. png_ptr = png_ptr; /* make compiler happy */
  182616. }
  182617. #endif /* PNG_NO_WARNINGS */
  182618. /* This function is called when the application wants to use another method
  182619. * of handling errors and warnings. Note that the error function MUST NOT
  182620. * return to the calling routine or serious problems will occur. The return
  182621. * method used in the default routine calls longjmp(png_ptr->jmpbuf, 1)
  182622. */
  182623. void PNGAPI
  182624. png_set_error_fn(png_structp png_ptr, png_voidp error_ptr,
  182625. png_error_ptr error_fn, png_error_ptr warning_fn)
  182626. {
  182627. if (png_ptr == NULL)
  182628. return;
  182629. png_ptr->error_ptr = error_ptr;
  182630. png_ptr->error_fn = error_fn;
  182631. png_ptr->warning_fn = warning_fn;
  182632. }
  182633. /* This function returns a pointer to the error_ptr associated with the user
  182634. * functions. The application should free any memory associated with this
  182635. * pointer before png_write_destroy and png_read_destroy are called.
  182636. */
  182637. png_voidp PNGAPI
  182638. png_get_error_ptr(png_structp png_ptr)
  182639. {
  182640. if (png_ptr == NULL)
  182641. return NULL;
  182642. return ((png_voidp)png_ptr->error_ptr);
  182643. }
  182644. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  182645. void PNGAPI
  182646. png_set_strip_error_numbers(png_structp png_ptr, png_uint_32 strip_mode)
  182647. {
  182648. if(png_ptr != NULL)
  182649. {
  182650. png_ptr->flags &=
  182651. ((~(PNG_FLAG_STRIP_ERROR_NUMBERS|PNG_FLAG_STRIP_ERROR_TEXT))&strip_mode);
  182652. }
  182653. }
  182654. #endif
  182655. #endif /* PNG_READ_SUPPORTED || PNG_WRITE_SUPPORTED */
  182656. /*** End of inlined file: pngerror.c ***/
  182657. /*** Start of inlined file: pngget.c ***/
  182658. /* pngget.c - retrieval of values from info struct
  182659. *
  182660. * Last changed in libpng 1.2.15 January 5, 2007
  182661. * For conditions of distribution and use, see copyright notice in png.h
  182662. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  182663. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  182664. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  182665. */
  182666. #define PNG_INTERNAL
  182667. #if defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED)
  182668. png_uint_32 PNGAPI
  182669. png_get_valid(png_structp png_ptr, png_infop info_ptr, png_uint_32 flag)
  182670. {
  182671. if (png_ptr != NULL && info_ptr != NULL)
  182672. return(info_ptr->valid & flag);
  182673. else
  182674. return(0);
  182675. }
  182676. png_uint_32 PNGAPI
  182677. png_get_rowbytes(png_structp png_ptr, png_infop info_ptr)
  182678. {
  182679. if (png_ptr != NULL && info_ptr != NULL)
  182680. return(info_ptr->rowbytes);
  182681. else
  182682. return(0);
  182683. }
  182684. #if defined(PNG_INFO_IMAGE_SUPPORTED)
  182685. png_bytepp PNGAPI
  182686. png_get_rows(png_structp png_ptr, png_infop info_ptr)
  182687. {
  182688. if (png_ptr != NULL && info_ptr != NULL)
  182689. return(info_ptr->row_pointers);
  182690. else
  182691. return(0);
  182692. }
  182693. #endif
  182694. #ifdef PNG_EASY_ACCESS_SUPPORTED
  182695. /* easy access to info, added in libpng-0.99 */
  182696. png_uint_32 PNGAPI
  182697. png_get_image_width(png_structp png_ptr, png_infop info_ptr)
  182698. {
  182699. if (png_ptr != NULL && info_ptr != NULL)
  182700. {
  182701. return info_ptr->width;
  182702. }
  182703. return (0);
  182704. }
  182705. png_uint_32 PNGAPI
  182706. png_get_image_height(png_structp png_ptr, png_infop info_ptr)
  182707. {
  182708. if (png_ptr != NULL && info_ptr != NULL)
  182709. {
  182710. return info_ptr->height;
  182711. }
  182712. return (0);
  182713. }
  182714. png_byte PNGAPI
  182715. png_get_bit_depth(png_structp png_ptr, png_infop info_ptr)
  182716. {
  182717. if (png_ptr != NULL && info_ptr != NULL)
  182718. {
  182719. return info_ptr->bit_depth;
  182720. }
  182721. return (0);
  182722. }
  182723. png_byte PNGAPI
  182724. png_get_color_type(png_structp png_ptr, png_infop info_ptr)
  182725. {
  182726. if (png_ptr != NULL && info_ptr != NULL)
  182727. {
  182728. return info_ptr->color_type;
  182729. }
  182730. return (0);
  182731. }
  182732. png_byte PNGAPI
  182733. png_get_filter_type(png_structp png_ptr, png_infop info_ptr)
  182734. {
  182735. if (png_ptr != NULL && info_ptr != NULL)
  182736. {
  182737. return info_ptr->filter_type;
  182738. }
  182739. return (0);
  182740. }
  182741. png_byte PNGAPI
  182742. png_get_interlace_type(png_structp png_ptr, png_infop info_ptr)
  182743. {
  182744. if (png_ptr != NULL && info_ptr != NULL)
  182745. {
  182746. return info_ptr->interlace_type;
  182747. }
  182748. return (0);
  182749. }
  182750. png_byte PNGAPI
  182751. png_get_compression_type(png_structp png_ptr, png_infop info_ptr)
  182752. {
  182753. if (png_ptr != NULL && info_ptr != NULL)
  182754. {
  182755. return info_ptr->compression_type;
  182756. }
  182757. return (0);
  182758. }
  182759. png_uint_32 PNGAPI
  182760. png_get_x_pixels_per_meter(png_structp png_ptr, png_infop info_ptr)
  182761. {
  182762. if (png_ptr != NULL && info_ptr != NULL)
  182763. #if defined(PNG_pHYs_SUPPORTED)
  182764. if (info_ptr->valid & PNG_INFO_pHYs)
  182765. {
  182766. png_debug1(1, "in %s retrieval function\n", "png_get_x_pixels_per_meter");
  182767. if(info_ptr->phys_unit_type != PNG_RESOLUTION_METER)
  182768. return (0);
  182769. else return (info_ptr->x_pixels_per_unit);
  182770. }
  182771. #else
  182772. return (0);
  182773. #endif
  182774. return (0);
  182775. }
  182776. png_uint_32 PNGAPI
  182777. png_get_y_pixels_per_meter(png_structp png_ptr, png_infop info_ptr)
  182778. {
  182779. if (png_ptr != NULL && info_ptr != NULL)
  182780. #if defined(PNG_pHYs_SUPPORTED)
  182781. if (info_ptr->valid & PNG_INFO_pHYs)
  182782. {
  182783. png_debug1(1, "in %s retrieval function\n", "png_get_y_pixels_per_meter");
  182784. if(info_ptr->phys_unit_type != PNG_RESOLUTION_METER)
  182785. return (0);
  182786. else return (info_ptr->y_pixels_per_unit);
  182787. }
  182788. #else
  182789. return (0);
  182790. #endif
  182791. return (0);
  182792. }
  182793. png_uint_32 PNGAPI
  182794. png_get_pixels_per_meter(png_structp png_ptr, png_infop info_ptr)
  182795. {
  182796. if (png_ptr != NULL && info_ptr != NULL)
  182797. #if defined(PNG_pHYs_SUPPORTED)
  182798. if (info_ptr->valid & PNG_INFO_pHYs)
  182799. {
  182800. png_debug1(1, "in %s retrieval function\n", "png_get_pixels_per_meter");
  182801. if(info_ptr->phys_unit_type != PNG_RESOLUTION_METER ||
  182802. info_ptr->x_pixels_per_unit != info_ptr->y_pixels_per_unit)
  182803. return (0);
  182804. else return (info_ptr->x_pixels_per_unit);
  182805. }
  182806. #else
  182807. return (0);
  182808. #endif
  182809. return (0);
  182810. }
  182811. #ifdef PNG_FLOATING_POINT_SUPPORTED
  182812. float PNGAPI
  182813. png_get_pixel_aspect_ratio(png_structp png_ptr, png_infop info_ptr)
  182814. {
  182815. if (png_ptr != NULL && info_ptr != NULL)
  182816. #if defined(PNG_pHYs_SUPPORTED)
  182817. if (info_ptr->valid & PNG_INFO_pHYs)
  182818. {
  182819. png_debug1(1, "in %s retrieval function\n", "png_get_aspect_ratio");
  182820. if (info_ptr->x_pixels_per_unit == 0)
  182821. return ((float)0.0);
  182822. else
  182823. return ((float)((float)info_ptr->y_pixels_per_unit
  182824. /(float)info_ptr->x_pixels_per_unit));
  182825. }
  182826. #else
  182827. return (0.0);
  182828. #endif
  182829. return ((float)0.0);
  182830. }
  182831. #endif
  182832. png_int_32 PNGAPI
  182833. png_get_x_offset_microns(png_structp png_ptr, png_infop info_ptr)
  182834. {
  182835. if (png_ptr != NULL && info_ptr != NULL)
  182836. #if defined(PNG_oFFs_SUPPORTED)
  182837. if (info_ptr->valid & PNG_INFO_oFFs)
  182838. {
  182839. png_debug1(1, "in %s retrieval function\n", "png_get_x_offset_microns");
  182840. if(info_ptr->offset_unit_type != PNG_OFFSET_MICROMETER)
  182841. return (0);
  182842. else return (info_ptr->x_offset);
  182843. }
  182844. #else
  182845. return (0);
  182846. #endif
  182847. return (0);
  182848. }
  182849. png_int_32 PNGAPI
  182850. png_get_y_offset_microns(png_structp png_ptr, png_infop info_ptr)
  182851. {
  182852. if (png_ptr != NULL && info_ptr != NULL)
  182853. #if defined(PNG_oFFs_SUPPORTED)
  182854. if (info_ptr->valid & PNG_INFO_oFFs)
  182855. {
  182856. png_debug1(1, "in %s retrieval function\n", "png_get_y_offset_microns");
  182857. if(info_ptr->offset_unit_type != PNG_OFFSET_MICROMETER)
  182858. return (0);
  182859. else return (info_ptr->y_offset);
  182860. }
  182861. #else
  182862. return (0);
  182863. #endif
  182864. return (0);
  182865. }
  182866. png_int_32 PNGAPI
  182867. png_get_x_offset_pixels(png_structp png_ptr, png_infop info_ptr)
  182868. {
  182869. if (png_ptr != NULL && info_ptr != NULL)
  182870. #if defined(PNG_oFFs_SUPPORTED)
  182871. if (info_ptr->valid & PNG_INFO_oFFs)
  182872. {
  182873. png_debug1(1, "in %s retrieval function\n", "png_get_x_offset_microns");
  182874. if(info_ptr->offset_unit_type != PNG_OFFSET_PIXEL)
  182875. return (0);
  182876. else return (info_ptr->x_offset);
  182877. }
  182878. #else
  182879. return (0);
  182880. #endif
  182881. return (0);
  182882. }
  182883. png_int_32 PNGAPI
  182884. png_get_y_offset_pixels(png_structp png_ptr, png_infop info_ptr)
  182885. {
  182886. if (png_ptr != NULL && info_ptr != NULL)
  182887. #if defined(PNG_oFFs_SUPPORTED)
  182888. if (info_ptr->valid & PNG_INFO_oFFs)
  182889. {
  182890. png_debug1(1, "in %s retrieval function\n", "png_get_y_offset_microns");
  182891. if(info_ptr->offset_unit_type != PNG_OFFSET_PIXEL)
  182892. return (0);
  182893. else return (info_ptr->y_offset);
  182894. }
  182895. #else
  182896. return (0);
  182897. #endif
  182898. return (0);
  182899. }
  182900. #if defined(PNG_INCH_CONVERSIONS) && defined(PNG_FLOATING_POINT_SUPPORTED)
  182901. png_uint_32 PNGAPI
  182902. png_get_pixels_per_inch(png_structp png_ptr, png_infop info_ptr)
  182903. {
  182904. return ((png_uint_32)((float)png_get_pixels_per_meter(png_ptr, info_ptr)
  182905. *.0254 +.5));
  182906. }
  182907. png_uint_32 PNGAPI
  182908. png_get_x_pixels_per_inch(png_structp png_ptr, png_infop info_ptr)
  182909. {
  182910. return ((png_uint_32)((float)png_get_x_pixels_per_meter(png_ptr, info_ptr)
  182911. *.0254 +.5));
  182912. }
  182913. png_uint_32 PNGAPI
  182914. png_get_y_pixels_per_inch(png_structp png_ptr, png_infop info_ptr)
  182915. {
  182916. return ((png_uint_32)((float)png_get_y_pixels_per_meter(png_ptr, info_ptr)
  182917. *.0254 +.5));
  182918. }
  182919. float PNGAPI
  182920. png_get_x_offset_inches(png_structp png_ptr, png_infop info_ptr)
  182921. {
  182922. return ((float)png_get_x_offset_microns(png_ptr, info_ptr)
  182923. *.00003937);
  182924. }
  182925. float PNGAPI
  182926. png_get_y_offset_inches(png_structp png_ptr, png_infop info_ptr)
  182927. {
  182928. return ((float)png_get_y_offset_microns(png_ptr, info_ptr)
  182929. *.00003937);
  182930. }
  182931. #if defined(PNG_pHYs_SUPPORTED)
  182932. png_uint_32 PNGAPI
  182933. png_get_pHYs_dpi(png_structp png_ptr, png_infop info_ptr,
  182934. png_uint_32 *res_x, png_uint_32 *res_y, int *unit_type)
  182935. {
  182936. png_uint_32 retval = 0;
  182937. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_pHYs))
  182938. {
  182939. png_debug1(1, "in %s retrieval function\n", "pHYs");
  182940. if (res_x != NULL)
  182941. {
  182942. *res_x = info_ptr->x_pixels_per_unit;
  182943. retval |= PNG_INFO_pHYs;
  182944. }
  182945. if (res_y != NULL)
  182946. {
  182947. *res_y = info_ptr->y_pixels_per_unit;
  182948. retval |= PNG_INFO_pHYs;
  182949. }
  182950. if (unit_type != NULL)
  182951. {
  182952. *unit_type = (int)info_ptr->phys_unit_type;
  182953. retval |= PNG_INFO_pHYs;
  182954. if(*unit_type == 1)
  182955. {
  182956. if (res_x != NULL) *res_x = (png_uint_32)(*res_x * .0254 + .50);
  182957. if (res_y != NULL) *res_y = (png_uint_32)(*res_y * .0254 + .50);
  182958. }
  182959. }
  182960. }
  182961. return (retval);
  182962. }
  182963. #endif /* PNG_pHYs_SUPPORTED */
  182964. #endif /* PNG_INCH_CONVERSIONS && PNG_FLOATING_POINT_SUPPORTED */
  182965. /* png_get_channels really belongs in here, too, but it's been around longer */
  182966. #endif /* PNG_EASY_ACCESS_SUPPORTED */
  182967. png_byte PNGAPI
  182968. png_get_channels(png_structp png_ptr, png_infop info_ptr)
  182969. {
  182970. if (png_ptr != NULL && info_ptr != NULL)
  182971. return(info_ptr->channels);
  182972. else
  182973. return (0);
  182974. }
  182975. png_bytep PNGAPI
  182976. png_get_signature(png_structp png_ptr, png_infop info_ptr)
  182977. {
  182978. if (png_ptr != NULL && info_ptr != NULL)
  182979. return(info_ptr->signature);
  182980. else
  182981. return (NULL);
  182982. }
  182983. #if defined(PNG_bKGD_SUPPORTED)
  182984. png_uint_32 PNGAPI
  182985. png_get_bKGD(png_structp png_ptr, png_infop info_ptr,
  182986. png_color_16p *background)
  182987. {
  182988. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_bKGD)
  182989. && background != NULL)
  182990. {
  182991. png_debug1(1, "in %s retrieval function\n", "bKGD");
  182992. *background = &(info_ptr->background);
  182993. return (PNG_INFO_bKGD);
  182994. }
  182995. return (0);
  182996. }
  182997. #endif
  182998. #if defined(PNG_cHRM_SUPPORTED)
  182999. #ifdef PNG_FLOATING_POINT_SUPPORTED
  183000. png_uint_32 PNGAPI
  183001. png_get_cHRM(png_structp png_ptr, png_infop info_ptr,
  183002. double *white_x, double *white_y, double *red_x, double *red_y,
  183003. double *green_x, double *green_y, double *blue_x, double *blue_y)
  183004. {
  183005. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_cHRM))
  183006. {
  183007. png_debug1(1, "in %s retrieval function\n", "cHRM");
  183008. if (white_x != NULL)
  183009. *white_x = (double)info_ptr->x_white;
  183010. if (white_y != NULL)
  183011. *white_y = (double)info_ptr->y_white;
  183012. if (red_x != NULL)
  183013. *red_x = (double)info_ptr->x_red;
  183014. if (red_y != NULL)
  183015. *red_y = (double)info_ptr->y_red;
  183016. if (green_x != NULL)
  183017. *green_x = (double)info_ptr->x_green;
  183018. if (green_y != NULL)
  183019. *green_y = (double)info_ptr->y_green;
  183020. if (blue_x != NULL)
  183021. *blue_x = (double)info_ptr->x_blue;
  183022. if (blue_y != NULL)
  183023. *blue_y = (double)info_ptr->y_blue;
  183024. return (PNG_INFO_cHRM);
  183025. }
  183026. return (0);
  183027. }
  183028. #endif
  183029. #ifdef PNG_FIXED_POINT_SUPPORTED
  183030. png_uint_32 PNGAPI
  183031. png_get_cHRM_fixed(png_structp png_ptr, png_infop info_ptr,
  183032. png_fixed_point *white_x, png_fixed_point *white_y, png_fixed_point *red_x,
  183033. png_fixed_point *red_y, png_fixed_point *green_x, png_fixed_point *green_y,
  183034. png_fixed_point *blue_x, png_fixed_point *blue_y)
  183035. {
  183036. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_cHRM))
  183037. {
  183038. png_debug1(1, "in %s retrieval function\n", "cHRM");
  183039. if (white_x != NULL)
  183040. *white_x = info_ptr->int_x_white;
  183041. if (white_y != NULL)
  183042. *white_y = info_ptr->int_y_white;
  183043. if (red_x != NULL)
  183044. *red_x = info_ptr->int_x_red;
  183045. if (red_y != NULL)
  183046. *red_y = info_ptr->int_y_red;
  183047. if (green_x != NULL)
  183048. *green_x = info_ptr->int_x_green;
  183049. if (green_y != NULL)
  183050. *green_y = info_ptr->int_y_green;
  183051. if (blue_x != NULL)
  183052. *blue_x = info_ptr->int_x_blue;
  183053. if (blue_y != NULL)
  183054. *blue_y = info_ptr->int_y_blue;
  183055. return (PNG_INFO_cHRM);
  183056. }
  183057. return (0);
  183058. }
  183059. #endif
  183060. #endif
  183061. #if defined(PNG_gAMA_SUPPORTED)
  183062. #ifdef PNG_FLOATING_POINT_SUPPORTED
  183063. png_uint_32 PNGAPI
  183064. png_get_gAMA(png_structp png_ptr, png_infop info_ptr, double *file_gamma)
  183065. {
  183066. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_gAMA)
  183067. && file_gamma != NULL)
  183068. {
  183069. png_debug1(1, "in %s retrieval function\n", "gAMA");
  183070. *file_gamma = (double)info_ptr->gamma;
  183071. return (PNG_INFO_gAMA);
  183072. }
  183073. return (0);
  183074. }
  183075. #endif
  183076. #ifdef PNG_FIXED_POINT_SUPPORTED
  183077. png_uint_32 PNGAPI
  183078. png_get_gAMA_fixed(png_structp png_ptr, png_infop info_ptr,
  183079. png_fixed_point *int_file_gamma)
  183080. {
  183081. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_gAMA)
  183082. && int_file_gamma != NULL)
  183083. {
  183084. png_debug1(1, "in %s retrieval function\n", "gAMA");
  183085. *int_file_gamma = info_ptr->int_gamma;
  183086. return (PNG_INFO_gAMA);
  183087. }
  183088. return (0);
  183089. }
  183090. #endif
  183091. #endif
  183092. #if defined(PNG_sRGB_SUPPORTED)
  183093. png_uint_32 PNGAPI
  183094. png_get_sRGB(png_structp png_ptr, png_infop info_ptr, int *file_srgb_intent)
  183095. {
  183096. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_sRGB)
  183097. && file_srgb_intent != NULL)
  183098. {
  183099. png_debug1(1, "in %s retrieval function\n", "sRGB");
  183100. *file_srgb_intent = (int)info_ptr->srgb_intent;
  183101. return (PNG_INFO_sRGB);
  183102. }
  183103. return (0);
  183104. }
  183105. #endif
  183106. #if defined(PNG_iCCP_SUPPORTED)
  183107. png_uint_32 PNGAPI
  183108. png_get_iCCP(png_structp png_ptr, png_infop info_ptr,
  183109. png_charpp name, int *compression_type,
  183110. png_charpp profile, png_uint_32 *proflen)
  183111. {
  183112. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_iCCP)
  183113. && name != NULL && profile != NULL && proflen != NULL)
  183114. {
  183115. png_debug1(1, "in %s retrieval function\n", "iCCP");
  183116. *name = info_ptr->iccp_name;
  183117. *profile = info_ptr->iccp_profile;
  183118. /* compression_type is a dummy so the API won't have to change
  183119. if we introduce multiple compression types later. */
  183120. *proflen = (int)info_ptr->iccp_proflen;
  183121. *compression_type = (int)info_ptr->iccp_compression;
  183122. return (PNG_INFO_iCCP);
  183123. }
  183124. return (0);
  183125. }
  183126. #endif
  183127. #if defined(PNG_sPLT_SUPPORTED)
  183128. png_uint_32 PNGAPI
  183129. png_get_sPLT(png_structp png_ptr, png_infop info_ptr,
  183130. png_sPLT_tpp spalettes)
  183131. {
  183132. if (png_ptr != NULL && info_ptr != NULL && spalettes != NULL)
  183133. {
  183134. *spalettes = info_ptr->splt_palettes;
  183135. return ((png_uint_32)info_ptr->splt_palettes_num);
  183136. }
  183137. return (0);
  183138. }
  183139. #endif
  183140. #if defined(PNG_hIST_SUPPORTED)
  183141. png_uint_32 PNGAPI
  183142. png_get_hIST(png_structp png_ptr, png_infop info_ptr, png_uint_16p *hist)
  183143. {
  183144. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_hIST)
  183145. && hist != NULL)
  183146. {
  183147. png_debug1(1, "in %s retrieval function\n", "hIST");
  183148. *hist = info_ptr->hist;
  183149. return (PNG_INFO_hIST);
  183150. }
  183151. return (0);
  183152. }
  183153. #endif
  183154. png_uint_32 PNGAPI
  183155. png_get_IHDR(png_structp png_ptr, png_infop info_ptr,
  183156. png_uint_32 *width, png_uint_32 *height, int *bit_depth,
  183157. int *color_type, int *interlace_type, int *compression_type,
  183158. int *filter_type)
  183159. {
  183160. if (png_ptr != NULL && info_ptr != NULL && width != NULL && height != NULL &&
  183161. bit_depth != NULL && color_type != NULL)
  183162. {
  183163. png_debug1(1, "in %s retrieval function\n", "IHDR");
  183164. *width = info_ptr->width;
  183165. *height = info_ptr->height;
  183166. *bit_depth = info_ptr->bit_depth;
  183167. if (info_ptr->bit_depth < 1 || info_ptr->bit_depth > 16)
  183168. png_error(png_ptr, "Invalid bit depth");
  183169. *color_type = info_ptr->color_type;
  183170. if (info_ptr->color_type > 6)
  183171. png_error(png_ptr, "Invalid color type");
  183172. if (compression_type != NULL)
  183173. *compression_type = info_ptr->compression_type;
  183174. if (filter_type != NULL)
  183175. *filter_type = info_ptr->filter_type;
  183176. if (interlace_type != NULL)
  183177. *interlace_type = info_ptr->interlace_type;
  183178. /* check for potential overflow of rowbytes */
  183179. if (*width == 0 || *width > PNG_UINT_31_MAX)
  183180. png_error(png_ptr, "Invalid image width");
  183181. if (*height == 0 || *height > PNG_UINT_31_MAX)
  183182. png_error(png_ptr, "Invalid image height");
  183183. if (info_ptr->width > (PNG_UINT_32_MAX
  183184. >> 3) /* 8-byte RGBA pixels */
  183185. - 64 /* bigrowbuf hack */
  183186. - 1 /* filter byte */
  183187. - 7*8 /* rounding of width to multiple of 8 pixels */
  183188. - 8) /* extra max_pixel_depth pad */
  183189. {
  183190. png_warning(png_ptr,
  183191. "Width too large for libpng to process image data.");
  183192. }
  183193. return (1);
  183194. }
  183195. return (0);
  183196. }
  183197. #if defined(PNG_oFFs_SUPPORTED)
  183198. png_uint_32 PNGAPI
  183199. png_get_oFFs(png_structp png_ptr, png_infop info_ptr,
  183200. png_int_32 *offset_x, png_int_32 *offset_y, int *unit_type)
  183201. {
  183202. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_oFFs)
  183203. && offset_x != NULL && offset_y != NULL && unit_type != NULL)
  183204. {
  183205. png_debug1(1, "in %s retrieval function\n", "oFFs");
  183206. *offset_x = info_ptr->x_offset;
  183207. *offset_y = info_ptr->y_offset;
  183208. *unit_type = (int)info_ptr->offset_unit_type;
  183209. return (PNG_INFO_oFFs);
  183210. }
  183211. return (0);
  183212. }
  183213. #endif
  183214. #if defined(PNG_pCAL_SUPPORTED)
  183215. png_uint_32 PNGAPI
  183216. png_get_pCAL(png_structp png_ptr, png_infop info_ptr,
  183217. png_charp *purpose, png_int_32 *X0, png_int_32 *X1, int *type, int *nparams,
  183218. png_charp *units, png_charpp *params)
  183219. {
  183220. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_pCAL)
  183221. && purpose != NULL && X0 != NULL && X1 != NULL && type != NULL &&
  183222. nparams != NULL && units != NULL && params != NULL)
  183223. {
  183224. png_debug1(1, "in %s retrieval function\n", "pCAL");
  183225. *purpose = info_ptr->pcal_purpose;
  183226. *X0 = info_ptr->pcal_X0;
  183227. *X1 = info_ptr->pcal_X1;
  183228. *type = (int)info_ptr->pcal_type;
  183229. *nparams = (int)info_ptr->pcal_nparams;
  183230. *units = info_ptr->pcal_units;
  183231. *params = info_ptr->pcal_params;
  183232. return (PNG_INFO_pCAL);
  183233. }
  183234. return (0);
  183235. }
  183236. #endif
  183237. #if defined(PNG_sCAL_SUPPORTED)
  183238. #ifdef PNG_FLOATING_POINT_SUPPORTED
  183239. png_uint_32 PNGAPI
  183240. png_get_sCAL(png_structp png_ptr, png_infop info_ptr,
  183241. int *unit, double *width, double *height)
  183242. {
  183243. if (png_ptr != NULL && info_ptr != NULL &&
  183244. (info_ptr->valid & PNG_INFO_sCAL))
  183245. {
  183246. *unit = info_ptr->scal_unit;
  183247. *width = info_ptr->scal_pixel_width;
  183248. *height = info_ptr->scal_pixel_height;
  183249. return (PNG_INFO_sCAL);
  183250. }
  183251. return(0);
  183252. }
  183253. #else
  183254. #ifdef PNG_FIXED_POINT_SUPPORTED
  183255. png_uint_32 PNGAPI
  183256. png_get_sCAL_s(png_structp png_ptr, png_infop info_ptr,
  183257. int *unit, png_charpp width, png_charpp height)
  183258. {
  183259. if (png_ptr != NULL && info_ptr != NULL &&
  183260. (info_ptr->valid & PNG_INFO_sCAL))
  183261. {
  183262. *unit = info_ptr->scal_unit;
  183263. *width = info_ptr->scal_s_width;
  183264. *height = info_ptr->scal_s_height;
  183265. return (PNG_INFO_sCAL);
  183266. }
  183267. return(0);
  183268. }
  183269. #endif
  183270. #endif
  183271. #endif
  183272. #if defined(PNG_pHYs_SUPPORTED)
  183273. png_uint_32 PNGAPI
  183274. png_get_pHYs(png_structp png_ptr, png_infop info_ptr,
  183275. png_uint_32 *res_x, png_uint_32 *res_y, int *unit_type)
  183276. {
  183277. png_uint_32 retval = 0;
  183278. if (png_ptr != NULL && info_ptr != NULL &&
  183279. (info_ptr->valid & PNG_INFO_pHYs))
  183280. {
  183281. png_debug1(1, "in %s retrieval function\n", "pHYs");
  183282. if (res_x != NULL)
  183283. {
  183284. *res_x = info_ptr->x_pixels_per_unit;
  183285. retval |= PNG_INFO_pHYs;
  183286. }
  183287. if (res_y != NULL)
  183288. {
  183289. *res_y = info_ptr->y_pixels_per_unit;
  183290. retval |= PNG_INFO_pHYs;
  183291. }
  183292. if (unit_type != NULL)
  183293. {
  183294. *unit_type = (int)info_ptr->phys_unit_type;
  183295. retval |= PNG_INFO_pHYs;
  183296. }
  183297. }
  183298. return (retval);
  183299. }
  183300. #endif
  183301. png_uint_32 PNGAPI
  183302. png_get_PLTE(png_structp png_ptr, png_infop info_ptr, png_colorp *palette,
  183303. int *num_palette)
  183304. {
  183305. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_PLTE)
  183306. && palette != NULL)
  183307. {
  183308. png_debug1(1, "in %s retrieval function\n", "PLTE");
  183309. *palette = info_ptr->palette;
  183310. *num_palette = info_ptr->num_palette;
  183311. png_debug1(3, "num_palette = %d\n", *num_palette);
  183312. return (PNG_INFO_PLTE);
  183313. }
  183314. return (0);
  183315. }
  183316. #if defined(PNG_sBIT_SUPPORTED)
  183317. png_uint_32 PNGAPI
  183318. png_get_sBIT(png_structp png_ptr, png_infop info_ptr, png_color_8p *sig_bit)
  183319. {
  183320. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_sBIT)
  183321. && sig_bit != NULL)
  183322. {
  183323. png_debug1(1, "in %s retrieval function\n", "sBIT");
  183324. *sig_bit = &(info_ptr->sig_bit);
  183325. return (PNG_INFO_sBIT);
  183326. }
  183327. return (0);
  183328. }
  183329. #endif
  183330. #if defined(PNG_TEXT_SUPPORTED)
  183331. png_uint_32 PNGAPI
  183332. png_get_text(png_structp png_ptr, png_infop info_ptr, png_textp *text_ptr,
  183333. int *num_text)
  183334. {
  183335. if (png_ptr != NULL && info_ptr != NULL && info_ptr->num_text > 0)
  183336. {
  183337. png_debug1(1, "in %s retrieval function\n",
  183338. (png_ptr->chunk_name[0] == '\0' ? "text"
  183339. : (png_const_charp)png_ptr->chunk_name));
  183340. if (text_ptr != NULL)
  183341. *text_ptr = info_ptr->text;
  183342. if (num_text != NULL)
  183343. *num_text = info_ptr->num_text;
  183344. return ((png_uint_32)info_ptr->num_text);
  183345. }
  183346. if (num_text != NULL)
  183347. *num_text = 0;
  183348. return(0);
  183349. }
  183350. #endif
  183351. #if defined(PNG_tIME_SUPPORTED)
  183352. png_uint_32 PNGAPI
  183353. png_get_tIME(png_structp png_ptr, png_infop info_ptr, png_timep *mod_time)
  183354. {
  183355. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_tIME)
  183356. && mod_time != NULL)
  183357. {
  183358. png_debug1(1, "in %s retrieval function\n", "tIME");
  183359. *mod_time = &(info_ptr->mod_time);
  183360. return (PNG_INFO_tIME);
  183361. }
  183362. return (0);
  183363. }
  183364. #endif
  183365. #if defined(PNG_tRNS_SUPPORTED)
  183366. png_uint_32 PNGAPI
  183367. png_get_tRNS(png_structp png_ptr, png_infop info_ptr,
  183368. png_bytep *trans, int *num_trans, png_color_16p *trans_values)
  183369. {
  183370. png_uint_32 retval = 0;
  183371. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_tRNS))
  183372. {
  183373. png_debug1(1, "in %s retrieval function\n", "tRNS");
  183374. if (info_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  183375. {
  183376. if (trans != NULL)
  183377. {
  183378. *trans = info_ptr->trans;
  183379. retval |= PNG_INFO_tRNS;
  183380. }
  183381. if (trans_values != NULL)
  183382. *trans_values = &(info_ptr->trans_values);
  183383. }
  183384. else /* if (info_ptr->color_type != PNG_COLOR_TYPE_PALETTE) */
  183385. {
  183386. if (trans_values != NULL)
  183387. {
  183388. *trans_values = &(info_ptr->trans_values);
  183389. retval |= PNG_INFO_tRNS;
  183390. }
  183391. if(trans != NULL)
  183392. *trans = NULL;
  183393. }
  183394. if(num_trans != NULL)
  183395. {
  183396. *num_trans = info_ptr->num_trans;
  183397. retval |= PNG_INFO_tRNS;
  183398. }
  183399. }
  183400. return (retval);
  183401. }
  183402. #endif
  183403. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  183404. png_uint_32 PNGAPI
  183405. png_get_unknown_chunks(png_structp png_ptr, png_infop info_ptr,
  183406. png_unknown_chunkpp unknowns)
  183407. {
  183408. if (png_ptr != NULL && info_ptr != NULL && unknowns != NULL)
  183409. {
  183410. *unknowns = info_ptr->unknown_chunks;
  183411. return ((png_uint_32)info_ptr->unknown_chunks_num);
  183412. }
  183413. return (0);
  183414. }
  183415. #endif
  183416. #if defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
  183417. png_byte PNGAPI
  183418. png_get_rgb_to_gray_status (png_structp png_ptr)
  183419. {
  183420. return (png_byte)(png_ptr? png_ptr->rgb_to_gray_status : 0);
  183421. }
  183422. #endif
  183423. #if defined(PNG_USER_CHUNKS_SUPPORTED)
  183424. png_voidp PNGAPI
  183425. png_get_user_chunk_ptr(png_structp png_ptr)
  183426. {
  183427. return (png_ptr? png_ptr->user_chunk_ptr : NULL);
  183428. }
  183429. #endif
  183430. #ifdef PNG_WRITE_SUPPORTED
  183431. png_uint_32 PNGAPI
  183432. png_get_compression_buffer_size(png_structp png_ptr)
  183433. {
  183434. return (png_uint_32)(png_ptr? png_ptr->zbuf_size : 0L);
  183435. }
  183436. #endif
  183437. #ifdef PNG_ASSEMBLER_CODE_SUPPORTED
  183438. #ifndef PNG_1_0_X
  183439. /* this function was added to libpng 1.2.0 and should exist by default */
  183440. png_uint_32 PNGAPI
  183441. png_get_asm_flags (png_structp png_ptr)
  183442. {
  183443. /* obsolete, to be removed from libpng-1.4.0 */
  183444. return (png_ptr? 0L: 0L);
  183445. }
  183446. /* this function was added to libpng 1.2.0 and should exist by default */
  183447. png_uint_32 PNGAPI
  183448. png_get_asm_flagmask (int flag_select)
  183449. {
  183450. /* obsolete, to be removed from libpng-1.4.0 */
  183451. flag_select=flag_select;
  183452. return 0L;
  183453. }
  183454. /* GRR: could add this: && defined(PNG_MMX_CODE_SUPPORTED) */
  183455. /* this function was added to libpng 1.2.0 */
  183456. png_uint_32 PNGAPI
  183457. png_get_mmx_flagmask (int flag_select, int *compilerID)
  183458. {
  183459. /* obsolete, to be removed from libpng-1.4.0 */
  183460. flag_select=flag_select;
  183461. *compilerID = -1; /* unknown (i.e., no asm/MMX code compiled) */
  183462. return 0L;
  183463. }
  183464. /* this function was added to libpng 1.2.0 */
  183465. png_byte PNGAPI
  183466. png_get_mmx_bitdepth_threshold (png_structp png_ptr)
  183467. {
  183468. /* obsolete, to be removed from libpng-1.4.0 */
  183469. return (png_ptr? 0: 0);
  183470. }
  183471. /* this function was added to libpng 1.2.0 */
  183472. png_uint_32 PNGAPI
  183473. png_get_mmx_rowbytes_threshold (png_structp png_ptr)
  183474. {
  183475. /* obsolete, to be removed from libpng-1.4.0 */
  183476. return (png_ptr? 0L: 0L);
  183477. }
  183478. #endif /* ?PNG_1_0_X */
  183479. #endif /* ?PNG_ASSEMBLER_CODE_SUPPORTED */
  183480. #ifdef PNG_SET_USER_LIMITS_SUPPORTED
  183481. /* these functions were added to libpng 1.2.6 */
  183482. png_uint_32 PNGAPI
  183483. png_get_user_width_max (png_structp png_ptr)
  183484. {
  183485. return (png_ptr? png_ptr->user_width_max : 0);
  183486. }
  183487. png_uint_32 PNGAPI
  183488. png_get_user_height_max (png_structp png_ptr)
  183489. {
  183490. return (png_ptr? png_ptr->user_height_max : 0);
  183491. }
  183492. #endif /* ?PNG_SET_USER_LIMITS_SUPPORTED */
  183493. #endif /* PNG_READ_SUPPORTED || PNG_WRITE_SUPPORTED */
  183494. /*** End of inlined file: pngget.c ***/
  183495. /*** Start of inlined file: pngmem.c ***/
  183496. /* pngmem.c - stub functions for memory allocation
  183497. *
  183498. * Last changed in libpng 1.2.13 November 13, 2006
  183499. * For conditions of distribution and use, see copyright notice in png.h
  183500. * Copyright (c) 1998-2006 Glenn Randers-Pehrson
  183501. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  183502. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  183503. *
  183504. * This file provides a location for all memory allocation. Users who
  183505. * need special memory handling are expected to supply replacement
  183506. * functions for png_malloc() and png_free(), and to use
  183507. * png_create_read_struct_2() and png_create_write_struct_2() to
  183508. * identify the replacement functions.
  183509. */
  183510. #define PNG_INTERNAL
  183511. #if defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED)
  183512. /* Borland DOS special memory handler */
  183513. #if defined(__TURBOC__) && !defined(_Windows) && !defined(__FLAT__)
  183514. /* if you change this, be sure to change the one in png.h also */
  183515. /* Allocate memory for a png_struct. The malloc and memset can be replaced
  183516. by a single call to calloc() if this is thought to improve performance. */
  183517. png_voidp /* PRIVATE */
  183518. png_create_struct(int type)
  183519. {
  183520. #ifdef PNG_USER_MEM_SUPPORTED
  183521. return (png_create_struct_2(type, png_malloc_ptr_NULL, png_voidp_NULL));
  183522. }
  183523. /* Alternate version of png_create_struct, for use with user-defined malloc. */
  183524. png_voidp /* PRIVATE */
  183525. png_create_struct_2(int type, png_malloc_ptr malloc_fn, png_voidp mem_ptr)
  183526. {
  183527. #endif /* PNG_USER_MEM_SUPPORTED */
  183528. png_size_t size;
  183529. png_voidp struct_ptr;
  183530. if (type == PNG_STRUCT_INFO)
  183531. size = png_sizeof(png_info);
  183532. else if (type == PNG_STRUCT_PNG)
  183533. size = png_sizeof(png_struct);
  183534. else
  183535. return (png_get_copyright(NULL));
  183536. #ifdef PNG_USER_MEM_SUPPORTED
  183537. if(malloc_fn != NULL)
  183538. {
  183539. png_struct dummy_struct;
  183540. png_structp png_ptr = &dummy_struct;
  183541. png_ptr->mem_ptr=mem_ptr;
  183542. struct_ptr = (*(malloc_fn))(png_ptr, (png_uint_32)size);
  183543. }
  183544. else
  183545. #endif /* PNG_USER_MEM_SUPPORTED */
  183546. struct_ptr = (png_voidp)farmalloc(size);
  183547. if (struct_ptr != NULL)
  183548. png_memset(struct_ptr, 0, size);
  183549. return (struct_ptr);
  183550. }
  183551. /* Free memory allocated by a png_create_struct() call */
  183552. void /* PRIVATE */
  183553. png_destroy_struct(png_voidp struct_ptr)
  183554. {
  183555. #ifdef PNG_USER_MEM_SUPPORTED
  183556. png_destroy_struct_2(struct_ptr, png_free_ptr_NULL, png_voidp_NULL);
  183557. }
  183558. /* Free memory allocated by a png_create_struct() call */
  183559. void /* PRIVATE */
  183560. png_destroy_struct_2(png_voidp struct_ptr, png_free_ptr free_fn,
  183561. png_voidp mem_ptr)
  183562. {
  183563. #endif
  183564. if (struct_ptr != NULL)
  183565. {
  183566. #ifdef PNG_USER_MEM_SUPPORTED
  183567. if(free_fn != NULL)
  183568. {
  183569. png_struct dummy_struct;
  183570. png_structp png_ptr = &dummy_struct;
  183571. png_ptr->mem_ptr=mem_ptr;
  183572. (*(free_fn))(png_ptr, struct_ptr);
  183573. return;
  183574. }
  183575. #endif /* PNG_USER_MEM_SUPPORTED */
  183576. farfree (struct_ptr);
  183577. }
  183578. }
  183579. /* Allocate memory. For reasonable files, size should never exceed
  183580. * 64K. However, zlib may allocate more then 64K if you don't tell
  183581. * it not to. See zconf.h and png.h for more information. zlib does
  183582. * need to allocate exactly 64K, so whatever you call here must
  183583. * have the ability to do that.
  183584. *
  183585. * Borland seems to have a problem in DOS mode for exactly 64K.
  183586. * It gives you a segment with an offset of 8 (perhaps to store its
  183587. * memory stuff). zlib doesn't like this at all, so we have to
  183588. * detect and deal with it. This code should not be needed in
  183589. * Windows or OS/2 modes, and only in 16 bit mode. This code has
  183590. * been updated by Alexander Lehmann for version 0.89 to waste less
  183591. * memory.
  183592. *
  183593. * Note that we can't use png_size_t for the "size" declaration,
  183594. * since on some systems a png_size_t is a 16-bit quantity, and as a
  183595. * result, we would be truncating potentially larger memory requests
  183596. * (which should cause a fatal error) and introducing major problems.
  183597. */
  183598. png_voidp PNGAPI
  183599. png_malloc(png_structp png_ptr, png_uint_32 size)
  183600. {
  183601. png_voidp ret;
  183602. if (png_ptr == NULL || size == 0)
  183603. return (NULL);
  183604. #ifdef PNG_USER_MEM_SUPPORTED
  183605. if(png_ptr->malloc_fn != NULL)
  183606. ret = ((png_voidp)(*(png_ptr->malloc_fn))(png_ptr, (png_size_t)size));
  183607. else
  183608. ret = (png_malloc_default(png_ptr, size));
  183609. if (ret == NULL && (png_ptr->flags&PNG_FLAG_MALLOC_NULL_MEM_OK) == 0)
  183610. png_error(png_ptr, "Out of memory!");
  183611. return (ret);
  183612. }
  183613. png_voidp PNGAPI
  183614. png_malloc_default(png_structp png_ptr, png_uint_32 size)
  183615. {
  183616. png_voidp ret;
  183617. #endif /* PNG_USER_MEM_SUPPORTED */
  183618. if (png_ptr == NULL || size == 0)
  183619. return (NULL);
  183620. #ifdef PNG_MAX_MALLOC_64K
  183621. if (size > (png_uint_32)65536L)
  183622. {
  183623. png_warning(png_ptr, "Cannot Allocate > 64K");
  183624. ret = NULL;
  183625. }
  183626. else
  183627. #endif
  183628. if (size != (size_t)size)
  183629. ret = NULL;
  183630. else if (size == (png_uint_32)65536L)
  183631. {
  183632. if (png_ptr->offset_table == NULL)
  183633. {
  183634. /* try to see if we need to do any of this fancy stuff */
  183635. ret = farmalloc(size);
  183636. if (ret == NULL || ((png_size_t)ret & 0xffff))
  183637. {
  183638. int num_blocks;
  183639. png_uint_32 total_size;
  183640. png_bytep table;
  183641. int i;
  183642. png_byte huge * hptr;
  183643. if (ret != NULL)
  183644. {
  183645. farfree(ret);
  183646. ret = NULL;
  183647. }
  183648. if(png_ptr->zlib_window_bits > 14)
  183649. num_blocks = (int)(1 << (png_ptr->zlib_window_bits - 14));
  183650. else
  183651. num_blocks = 1;
  183652. if (png_ptr->zlib_mem_level >= 7)
  183653. num_blocks += (int)(1 << (png_ptr->zlib_mem_level - 7));
  183654. else
  183655. num_blocks++;
  183656. total_size = ((png_uint_32)65536L) * (png_uint_32)num_blocks+16;
  183657. table = farmalloc(total_size);
  183658. if (table == NULL)
  183659. {
  183660. #ifndef PNG_USER_MEM_SUPPORTED
  183661. if ((png_ptr->flags&PNG_FLAG_MALLOC_NULL_MEM_OK) == 0)
  183662. png_error(png_ptr, "Out Of Memory."); /* Note "O" and "M" */
  183663. else
  183664. png_warning(png_ptr, "Out Of Memory.");
  183665. #endif
  183666. return (NULL);
  183667. }
  183668. if ((png_size_t)table & 0xfff0)
  183669. {
  183670. #ifndef PNG_USER_MEM_SUPPORTED
  183671. if ((png_ptr->flags&PNG_FLAG_MALLOC_NULL_MEM_OK) == 0)
  183672. png_error(png_ptr,
  183673. "Farmalloc didn't return normalized pointer");
  183674. else
  183675. png_warning(png_ptr,
  183676. "Farmalloc didn't return normalized pointer");
  183677. #endif
  183678. return (NULL);
  183679. }
  183680. png_ptr->offset_table = table;
  183681. png_ptr->offset_table_ptr = farmalloc(num_blocks *
  183682. png_sizeof (png_bytep));
  183683. if (png_ptr->offset_table_ptr == NULL)
  183684. {
  183685. #ifndef PNG_USER_MEM_SUPPORTED
  183686. if ((png_ptr->flags&PNG_FLAG_MALLOC_NULL_MEM_OK) == 0)
  183687. png_error(png_ptr, "Out Of memory."); /* Note "O" and "M" */
  183688. else
  183689. png_warning(png_ptr, "Out Of memory.");
  183690. #endif
  183691. return (NULL);
  183692. }
  183693. hptr = (png_byte huge *)table;
  183694. if ((png_size_t)hptr & 0xf)
  183695. {
  183696. hptr = (png_byte huge *)((long)(hptr) & 0xfffffff0L);
  183697. hptr = hptr + 16L; /* "hptr += 16L" fails on Turbo C++ 3.0 */
  183698. }
  183699. for (i = 0; i < num_blocks; i++)
  183700. {
  183701. png_ptr->offset_table_ptr[i] = (png_bytep)hptr;
  183702. hptr = hptr + (png_uint_32)65536L; /* "+=" fails on TC++3.0 */
  183703. }
  183704. png_ptr->offset_table_number = num_blocks;
  183705. png_ptr->offset_table_count = 0;
  183706. png_ptr->offset_table_count_free = 0;
  183707. }
  183708. }
  183709. if (png_ptr->offset_table_count >= png_ptr->offset_table_number)
  183710. {
  183711. #ifndef PNG_USER_MEM_SUPPORTED
  183712. if ((png_ptr->flags&PNG_FLAG_MALLOC_NULL_MEM_OK) == 0)
  183713. png_error(png_ptr, "Out of Memory."); /* Note "o" and "M" */
  183714. else
  183715. png_warning(png_ptr, "Out of Memory.");
  183716. #endif
  183717. return (NULL);
  183718. }
  183719. ret = png_ptr->offset_table_ptr[png_ptr->offset_table_count++];
  183720. }
  183721. else
  183722. ret = farmalloc(size);
  183723. #ifndef PNG_USER_MEM_SUPPORTED
  183724. if (ret == NULL)
  183725. {
  183726. if ((png_ptr->flags&PNG_FLAG_MALLOC_NULL_MEM_OK) == 0)
  183727. png_error(png_ptr, "Out of memory."); /* Note "o" and "m" */
  183728. else
  183729. png_warning(png_ptr, "Out of memory."); /* Note "o" and "m" */
  183730. }
  183731. #endif
  183732. return (ret);
  183733. }
  183734. /* free a pointer allocated by png_malloc(). In the default
  183735. configuration, png_ptr is not used, but is passed in case it
  183736. is needed. If ptr is NULL, return without taking any action. */
  183737. void PNGAPI
  183738. png_free(png_structp png_ptr, png_voidp ptr)
  183739. {
  183740. if (png_ptr == NULL || ptr == NULL)
  183741. return;
  183742. #ifdef PNG_USER_MEM_SUPPORTED
  183743. if (png_ptr->free_fn != NULL)
  183744. {
  183745. (*(png_ptr->free_fn))(png_ptr, ptr);
  183746. return;
  183747. }
  183748. else png_free_default(png_ptr, ptr);
  183749. }
  183750. void PNGAPI
  183751. png_free_default(png_structp png_ptr, png_voidp ptr)
  183752. {
  183753. #endif /* PNG_USER_MEM_SUPPORTED */
  183754. if(png_ptr == NULL) return;
  183755. if (png_ptr->offset_table != NULL)
  183756. {
  183757. int i;
  183758. for (i = 0; i < png_ptr->offset_table_count; i++)
  183759. {
  183760. if (ptr == png_ptr->offset_table_ptr[i])
  183761. {
  183762. ptr = NULL;
  183763. png_ptr->offset_table_count_free++;
  183764. break;
  183765. }
  183766. }
  183767. if (png_ptr->offset_table_count_free == png_ptr->offset_table_count)
  183768. {
  183769. farfree(png_ptr->offset_table);
  183770. farfree(png_ptr->offset_table_ptr);
  183771. png_ptr->offset_table = NULL;
  183772. png_ptr->offset_table_ptr = NULL;
  183773. }
  183774. }
  183775. if (ptr != NULL)
  183776. {
  183777. farfree(ptr);
  183778. }
  183779. }
  183780. #else /* Not the Borland DOS special memory handler */
  183781. /* Allocate memory for a png_struct or a png_info. The malloc and
  183782. memset can be replaced by a single call to calloc() if this is thought
  183783. to improve performance noticably. */
  183784. png_voidp /* PRIVATE */
  183785. png_create_struct(int type)
  183786. {
  183787. #ifdef PNG_USER_MEM_SUPPORTED
  183788. return (png_create_struct_2(type, png_malloc_ptr_NULL, png_voidp_NULL));
  183789. }
  183790. /* Allocate memory for a png_struct or a png_info. The malloc and
  183791. memset can be replaced by a single call to calloc() if this is thought
  183792. to improve performance noticably. */
  183793. png_voidp /* PRIVATE */
  183794. png_create_struct_2(int type, png_malloc_ptr malloc_fn, png_voidp mem_ptr)
  183795. {
  183796. #endif /* PNG_USER_MEM_SUPPORTED */
  183797. png_size_t size;
  183798. png_voidp struct_ptr;
  183799. if (type == PNG_STRUCT_INFO)
  183800. size = png_sizeof(png_info);
  183801. else if (type == PNG_STRUCT_PNG)
  183802. size = png_sizeof(png_struct);
  183803. else
  183804. return (NULL);
  183805. #ifdef PNG_USER_MEM_SUPPORTED
  183806. if(malloc_fn != NULL)
  183807. {
  183808. png_struct dummy_struct;
  183809. png_structp png_ptr = &dummy_struct;
  183810. png_ptr->mem_ptr=mem_ptr;
  183811. struct_ptr = (*(malloc_fn))(png_ptr, size);
  183812. if (struct_ptr != NULL)
  183813. png_memset(struct_ptr, 0, size);
  183814. return (struct_ptr);
  183815. }
  183816. #endif /* PNG_USER_MEM_SUPPORTED */
  183817. #if defined(__TURBOC__) && !defined(__FLAT__)
  183818. struct_ptr = (png_voidp)farmalloc(size);
  183819. #else
  183820. # if defined(_MSC_VER) && defined(MAXSEG_64K)
  183821. struct_ptr = (png_voidp)halloc(size,1);
  183822. # else
  183823. struct_ptr = (png_voidp)malloc(size);
  183824. # endif
  183825. #endif
  183826. if (struct_ptr != NULL)
  183827. png_memset(struct_ptr, 0, size);
  183828. return (struct_ptr);
  183829. }
  183830. /* Free memory allocated by a png_create_struct() call */
  183831. void /* PRIVATE */
  183832. png_destroy_struct(png_voidp struct_ptr)
  183833. {
  183834. #ifdef PNG_USER_MEM_SUPPORTED
  183835. png_destroy_struct_2(struct_ptr, png_free_ptr_NULL, png_voidp_NULL);
  183836. }
  183837. /* Free memory allocated by a png_create_struct() call */
  183838. void /* PRIVATE */
  183839. png_destroy_struct_2(png_voidp struct_ptr, png_free_ptr free_fn,
  183840. png_voidp mem_ptr)
  183841. {
  183842. #endif /* PNG_USER_MEM_SUPPORTED */
  183843. if (struct_ptr != NULL)
  183844. {
  183845. #ifdef PNG_USER_MEM_SUPPORTED
  183846. if(free_fn != NULL)
  183847. {
  183848. png_struct dummy_struct;
  183849. png_structp png_ptr = &dummy_struct;
  183850. png_ptr->mem_ptr=mem_ptr;
  183851. (*(free_fn))(png_ptr, struct_ptr);
  183852. return;
  183853. }
  183854. #endif /* PNG_USER_MEM_SUPPORTED */
  183855. #if defined(__TURBOC__) && !defined(__FLAT__)
  183856. farfree(struct_ptr);
  183857. #else
  183858. # if defined(_MSC_VER) && defined(MAXSEG_64K)
  183859. hfree(struct_ptr);
  183860. # else
  183861. free(struct_ptr);
  183862. # endif
  183863. #endif
  183864. }
  183865. }
  183866. /* Allocate memory. For reasonable files, size should never exceed
  183867. 64K. However, zlib may allocate more then 64K if you don't tell
  183868. it not to. See zconf.h and png.h for more information. zlib does
  183869. need to allocate exactly 64K, so whatever you call here must
  183870. have the ability to do that. */
  183871. png_voidp PNGAPI
  183872. png_malloc(png_structp png_ptr, png_uint_32 size)
  183873. {
  183874. png_voidp ret;
  183875. #ifdef PNG_USER_MEM_SUPPORTED
  183876. if (png_ptr == NULL || size == 0)
  183877. return (NULL);
  183878. if(png_ptr->malloc_fn != NULL)
  183879. ret = ((png_voidp)(*(png_ptr->malloc_fn))(png_ptr, (png_size_t)size));
  183880. else
  183881. ret = (png_malloc_default(png_ptr, size));
  183882. if (ret == NULL && (png_ptr->flags&PNG_FLAG_MALLOC_NULL_MEM_OK) == 0)
  183883. png_error(png_ptr, "Out of Memory!");
  183884. return (ret);
  183885. }
  183886. png_voidp PNGAPI
  183887. png_malloc_default(png_structp png_ptr, png_uint_32 size)
  183888. {
  183889. png_voidp ret;
  183890. #endif /* PNG_USER_MEM_SUPPORTED */
  183891. if (png_ptr == NULL || size == 0)
  183892. return (NULL);
  183893. #ifdef PNG_MAX_MALLOC_64K
  183894. if (size > (png_uint_32)65536L)
  183895. {
  183896. #ifndef PNG_USER_MEM_SUPPORTED
  183897. if(png_ptr->flags&PNG_FLAG_MALLOC_NULL_MEM_OK) == 0)
  183898. png_error(png_ptr, "Cannot Allocate > 64K");
  183899. else
  183900. #endif
  183901. return NULL;
  183902. }
  183903. #endif
  183904. /* Check for overflow */
  183905. #if defined(__TURBOC__) && !defined(__FLAT__)
  183906. if (size != (unsigned long)size)
  183907. ret = NULL;
  183908. else
  183909. ret = farmalloc(size);
  183910. #else
  183911. # if defined(_MSC_VER) && defined(MAXSEG_64K)
  183912. if (size != (unsigned long)size)
  183913. ret = NULL;
  183914. else
  183915. ret = halloc(size, 1);
  183916. # else
  183917. if (size != (size_t)size)
  183918. ret = NULL;
  183919. else
  183920. ret = malloc((size_t)size);
  183921. # endif
  183922. #endif
  183923. #ifndef PNG_USER_MEM_SUPPORTED
  183924. if (ret == NULL && (png_ptr->flags&PNG_FLAG_MALLOC_NULL_MEM_OK) == 0)
  183925. png_error(png_ptr, "Out of Memory");
  183926. #endif
  183927. return (ret);
  183928. }
  183929. /* Free a pointer allocated by png_malloc(). If ptr is NULL, return
  183930. without taking any action. */
  183931. void PNGAPI
  183932. png_free(png_structp png_ptr, png_voidp ptr)
  183933. {
  183934. if (png_ptr == NULL || ptr == NULL)
  183935. return;
  183936. #ifdef PNG_USER_MEM_SUPPORTED
  183937. if (png_ptr->free_fn != NULL)
  183938. {
  183939. (*(png_ptr->free_fn))(png_ptr, ptr);
  183940. return;
  183941. }
  183942. else png_free_default(png_ptr, ptr);
  183943. }
  183944. void PNGAPI
  183945. png_free_default(png_structp png_ptr, png_voidp ptr)
  183946. {
  183947. if (png_ptr == NULL || ptr == NULL)
  183948. return;
  183949. #endif /* PNG_USER_MEM_SUPPORTED */
  183950. #if defined(__TURBOC__) && !defined(__FLAT__)
  183951. farfree(ptr);
  183952. #else
  183953. # if defined(_MSC_VER) && defined(MAXSEG_64K)
  183954. hfree(ptr);
  183955. # else
  183956. free(ptr);
  183957. # endif
  183958. #endif
  183959. }
  183960. #endif /* Not Borland DOS special memory handler */
  183961. #if defined(PNG_1_0_X)
  183962. # define png_malloc_warn png_malloc
  183963. #else
  183964. /* This function was added at libpng version 1.2.3. The png_malloc_warn()
  183965. * function will set up png_malloc() to issue a png_warning and return NULL
  183966. * instead of issuing a png_error, if it fails to allocate the requested
  183967. * memory.
  183968. */
  183969. png_voidp PNGAPI
  183970. png_malloc_warn(png_structp png_ptr, png_uint_32 size)
  183971. {
  183972. png_voidp ptr;
  183973. png_uint_32 save_flags;
  183974. if(png_ptr == NULL) return (NULL);
  183975. save_flags=png_ptr->flags;
  183976. png_ptr->flags|=PNG_FLAG_MALLOC_NULL_MEM_OK;
  183977. ptr = (png_voidp)png_malloc((png_structp)png_ptr, size);
  183978. png_ptr->flags=save_flags;
  183979. return(ptr);
  183980. }
  183981. #endif
  183982. png_voidp PNGAPI
  183983. png_memcpy_check (png_structp png_ptr, png_voidp s1, png_voidp s2,
  183984. png_uint_32 length)
  183985. {
  183986. png_size_t size;
  183987. size = (png_size_t)length;
  183988. if ((png_uint_32)size != length)
  183989. png_error(png_ptr,"Overflow in png_memcpy_check.");
  183990. return(png_memcpy (s1, s2, size));
  183991. }
  183992. png_voidp PNGAPI
  183993. png_memset_check (png_structp png_ptr, png_voidp s1, int value,
  183994. png_uint_32 length)
  183995. {
  183996. png_size_t size;
  183997. size = (png_size_t)length;
  183998. if ((png_uint_32)size != length)
  183999. png_error(png_ptr,"Overflow in png_memset_check.");
  184000. return (png_memset (s1, value, size));
  184001. }
  184002. #ifdef PNG_USER_MEM_SUPPORTED
  184003. /* This function is called when the application wants to use another method
  184004. * of allocating and freeing memory.
  184005. */
  184006. void PNGAPI
  184007. png_set_mem_fn(png_structp png_ptr, png_voidp mem_ptr, png_malloc_ptr
  184008. malloc_fn, png_free_ptr free_fn)
  184009. {
  184010. if(png_ptr != NULL) {
  184011. png_ptr->mem_ptr = mem_ptr;
  184012. png_ptr->malloc_fn = malloc_fn;
  184013. png_ptr->free_fn = free_fn;
  184014. }
  184015. }
  184016. /* This function returns a pointer to the mem_ptr associated with the user
  184017. * functions. The application should free any memory associated with this
  184018. * pointer before png_write_destroy and png_read_destroy are called.
  184019. */
  184020. png_voidp PNGAPI
  184021. png_get_mem_ptr(png_structp png_ptr)
  184022. {
  184023. if(png_ptr == NULL) return (NULL);
  184024. return ((png_voidp)png_ptr->mem_ptr);
  184025. }
  184026. #endif /* PNG_USER_MEM_SUPPORTED */
  184027. #endif /* PNG_READ_SUPPORTED || PNG_WRITE_SUPPORTED */
  184028. /*** End of inlined file: pngmem.c ***/
  184029. /*** Start of inlined file: pngread.c ***/
  184030. /* pngread.c - read a PNG file
  184031. *
  184032. * Last changed in libpng 1.2.20 September 7, 2007
  184033. * For conditions of distribution and use, see copyright notice in png.h
  184034. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  184035. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  184036. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  184037. *
  184038. * This file contains routines that an application calls directly to
  184039. * read a PNG file or stream.
  184040. */
  184041. #define PNG_INTERNAL
  184042. #if defined(PNG_READ_SUPPORTED)
  184043. /* Create a PNG structure for reading, and allocate any memory needed. */
  184044. png_structp PNGAPI
  184045. png_create_read_struct(png_const_charp user_png_ver, png_voidp error_ptr,
  184046. png_error_ptr error_fn, png_error_ptr warn_fn)
  184047. {
  184048. #ifdef PNG_USER_MEM_SUPPORTED
  184049. return (png_create_read_struct_2(user_png_ver, error_ptr, error_fn,
  184050. warn_fn, png_voidp_NULL, png_malloc_ptr_NULL, png_free_ptr_NULL));
  184051. }
  184052. /* Alternate create PNG structure for reading, and allocate any memory needed. */
  184053. png_structp PNGAPI
  184054. png_create_read_struct_2(png_const_charp user_png_ver, png_voidp error_ptr,
  184055. png_error_ptr error_fn, png_error_ptr warn_fn, png_voidp mem_ptr,
  184056. png_malloc_ptr malloc_fn, png_free_ptr free_fn)
  184057. {
  184058. #endif /* PNG_USER_MEM_SUPPORTED */
  184059. png_structp png_ptr;
  184060. #ifdef PNG_SETJMP_SUPPORTED
  184061. #ifdef USE_FAR_KEYWORD
  184062. jmp_buf jmpbuf;
  184063. #endif
  184064. #endif
  184065. int i;
  184066. png_debug(1, "in png_create_read_struct\n");
  184067. #ifdef PNG_USER_MEM_SUPPORTED
  184068. png_ptr = (png_structp)png_create_struct_2(PNG_STRUCT_PNG,
  184069. (png_malloc_ptr)malloc_fn, (png_voidp)mem_ptr);
  184070. #else
  184071. png_ptr = (png_structp)png_create_struct(PNG_STRUCT_PNG);
  184072. #endif
  184073. if (png_ptr == NULL)
  184074. return (NULL);
  184075. /* added at libpng-1.2.6 */
  184076. #ifdef PNG_SET_USER_LIMITS_SUPPORTED
  184077. png_ptr->user_width_max=PNG_USER_WIDTH_MAX;
  184078. png_ptr->user_height_max=PNG_USER_HEIGHT_MAX;
  184079. #endif
  184080. #ifdef PNG_SETJMP_SUPPORTED
  184081. #ifdef USE_FAR_KEYWORD
  184082. if (setjmp(jmpbuf))
  184083. #else
  184084. if (setjmp(png_ptr->jmpbuf))
  184085. #endif
  184086. {
  184087. png_free(png_ptr, png_ptr->zbuf);
  184088. png_ptr->zbuf=NULL;
  184089. #ifdef PNG_USER_MEM_SUPPORTED
  184090. png_destroy_struct_2((png_voidp)png_ptr,
  184091. (png_free_ptr)free_fn, (png_voidp)mem_ptr);
  184092. #else
  184093. png_destroy_struct((png_voidp)png_ptr);
  184094. #endif
  184095. return (NULL);
  184096. }
  184097. #ifdef USE_FAR_KEYWORD
  184098. png_memcpy(png_ptr->jmpbuf,jmpbuf,png_sizeof(jmp_buf));
  184099. #endif
  184100. #endif
  184101. #ifdef PNG_USER_MEM_SUPPORTED
  184102. png_set_mem_fn(png_ptr, mem_ptr, malloc_fn, free_fn);
  184103. #endif
  184104. png_set_error_fn(png_ptr, error_ptr, error_fn, warn_fn);
  184105. i=0;
  184106. do
  184107. {
  184108. if(user_png_ver[i] != png_libpng_ver[i])
  184109. png_ptr->flags |= PNG_FLAG_LIBRARY_MISMATCH;
  184110. } while (png_libpng_ver[i++]);
  184111. if (png_ptr->flags & PNG_FLAG_LIBRARY_MISMATCH)
  184112. {
  184113. /* Libpng 0.90 and later are binary incompatible with libpng 0.89, so
  184114. * we must recompile any applications that use any older library version.
  184115. * For versions after libpng 1.0, we will be compatible, so we need
  184116. * only check the first digit.
  184117. */
  184118. if (user_png_ver == NULL || user_png_ver[0] != png_libpng_ver[0] ||
  184119. (user_png_ver[0] == '1' && user_png_ver[2] != png_libpng_ver[2]) ||
  184120. (user_png_ver[0] == '0' && user_png_ver[2] < '9'))
  184121. {
  184122. #if !defined(PNG_NO_STDIO) && !defined(_WIN32_WCE)
  184123. char msg[80];
  184124. if (user_png_ver)
  184125. {
  184126. png_snprintf(msg, 80,
  184127. "Application was compiled with png.h from libpng-%.20s",
  184128. user_png_ver);
  184129. png_warning(png_ptr, msg);
  184130. }
  184131. png_snprintf(msg, 80,
  184132. "Application is running with png.c from libpng-%.20s",
  184133. png_libpng_ver);
  184134. png_warning(png_ptr, msg);
  184135. #endif
  184136. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  184137. png_ptr->flags=0;
  184138. #endif
  184139. png_error(png_ptr,
  184140. "Incompatible libpng version in application and library");
  184141. }
  184142. }
  184143. /* initialize zbuf - compression buffer */
  184144. png_ptr->zbuf_size = PNG_ZBUF_SIZE;
  184145. png_ptr->zbuf = (png_bytep)png_malloc(png_ptr,
  184146. (png_uint_32)png_ptr->zbuf_size);
  184147. png_ptr->zstream.zalloc = png_zalloc;
  184148. png_ptr->zstream.zfree = png_zfree;
  184149. png_ptr->zstream.opaque = (voidpf)png_ptr;
  184150. switch (inflateInit(&png_ptr->zstream))
  184151. {
  184152. case Z_OK: /* Do nothing */ break;
  184153. case Z_MEM_ERROR:
  184154. case Z_STREAM_ERROR: png_error(png_ptr, "zlib memory error"); break;
  184155. case Z_VERSION_ERROR: png_error(png_ptr, "zlib version error"); break;
  184156. default: png_error(png_ptr, "Unknown zlib error");
  184157. }
  184158. png_ptr->zstream.next_out = png_ptr->zbuf;
  184159. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  184160. png_set_read_fn(png_ptr, png_voidp_NULL, png_rw_ptr_NULL);
  184161. #ifdef PNG_SETJMP_SUPPORTED
  184162. /* Applications that neglect to set up their own setjmp() and then encounter
  184163. a png_error() will longjmp here. Since the jmpbuf is then meaningless we
  184164. abort instead of returning. */
  184165. #ifdef USE_FAR_KEYWORD
  184166. if (setjmp(jmpbuf))
  184167. PNG_ABORT();
  184168. png_memcpy(png_ptr->jmpbuf,jmpbuf,png_sizeof(jmp_buf));
  184169. #else
  184170. if (setjmp(png_ptr->jmpbuf))
  184171. PNG_ABORT();
  184172. #endif
  184173. #endif
  184174. return (png_ptr);
  184175. }
  184176. #if defined(PNG_1_0_X) || defined(PNG_1_2_X)
  184177. /* Initialize PNG structure for reading, and allocate any memory needed.
  184178. This interface is deprecated in favour of the png_create_read_struct(),
  184179. and it will disappear as of libpng-1.3.0. */
  184180. #undef png_read_init
  184181. void PNGAPI
  184182. png_read_init(png_structp png_ptr)
  184183. {
  184184. /* We only come here via pre-1.0.7-compiled applications */
  184185. png_read_init_2(png_ptr, "1.0.6 or earlier", 0, 0);
  184186. }
  184187. void PNGAPI
  184188. png_read_init_2(png_structp png_ptr, png_const_charp user_png_ver,
  184189. png_size_t png_struct_size, png_size_t png_info_size)
  184190. {
  184191. /* We only come here via pre-1.0.12-compiled applications */
  184192. if(png_ptr == NULL) return;
  184193. #if !defined(PNG_NO_STDIO) && !defined(_WIN32_WCE)
  184194. if(png_sizeof(png_struct) > png_struct_size ||
  184195. png_sizeof(png_info) > png_info_size)
  184196. {
  184197. char msg[80];
  184198. png_ptr->warning_fn=NULL;
  184199. if (user_png_ver)
  184200. {
  184201. png_snprintf(msg, 80,
  184202. "Application was compiled with png.h from libpng-%.20s",
  184203. user_png_ver);
  184204. png_warning(png_ptr, msg);
  184205. }
  184206. png_snprintf(msg, 80,
  184207. "Application is running with png.c from libpng-%.20s",
  184208. png_libpng_ver);
  184209. png_warning(png_ptr, msg);
  184210. }
  184211. #endif
  184212. if(png_sizeof(png_struct) > png_struct_size)
  184213. {
  184214. png_ptr->error_fn=NULL;
  184215. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  184216. png_ptr->flags=0;
  184217. #endif
  184218. png_error(png_ptr,
  184219. "The png struct allocated by the application for reading is too small.");
  184220. }
  184221. if(png_sizeof(png_info) > png_info_size)
  184222. {
  184223. png_ptr->error_fn=NULL;
  184224. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  184225. png_ptr->flags=0;
  184226. #endif
  184227. png_error(png_ptr,
  184228. "The info struct allocated by application for reading is too small.");
  184229. }
  184230. png_read_init_3(&png_ptr, user_png_ver, png_struct_size);
  184231. }
  184232. #endif /* PNG_1_0_X || PNG_1_2_X */
  184233. void PNGAPI
  184234. png_read_init_3(png_structpp ptr_ptr, png_const_charp user_png_ver,
  184235. png_size_t png_struct_size)
  184236. {
  184237. #ifdef PNG_SETJMP_SUPPORTED
  184238. jmp_buf tmp_jmp; /* to save current jump buffer */
  184239. #endif
  184240. int i=0;
  184241. png_structp png_ptr=*ptr_ptr;
  184242. if(png_ptr == NULL) return;
  184243. do
  184244. {
  184245. if(user_png_ver[i] != png_libpng_ver[i])
  184246. {
  184247. #ifdef PNG_LEGACY_SUPPORTED
  184248. png_ptr->flags |= PNG_FLAG_LIBRARY_MISMATCH;
  184249. #else
  184250. png_ptr->warning_fn=NULL;
  184251. png_warning(png_ptr,
  184252. "Application uses deprecated png_read_init() and should be recompiled.");
  184253. break;
  184254. #endif
  184255. }
  184256. } while (png_libpng_ver[i++]);
  184257. png_debug(1, "in png_read_init_3\n");
  184258. #ifdef PNG_SETJMP_SUPPORTED
  184259. /* save jump buffer and error functions */
  184260. png_memcpy(tmp_jmp, png_ptr->jmpbuf, png_sizeof (jmp_buf));
  184261. #endif
  184262. if(png_sizeof(png_struct) > png_struct_size)
  184263. {
  184264. png_destroy_struct(png_ptr);
  184265. *ptr_ptr = (png_structp)png_create_struct(PNG_STRUCT_PNG);
  184266. png_ptr = *ptr_ptr;
  184267. }
  184268. /* reset all variables to 0 */
  184269. png_memset(png_ptr, 0, png_sizeof (png_struct));
  184270. #ifdef PNG_SETJMP_SUPPORTED
  184271. /* restore jump buffer */
  184272. png_memcpy(png_ptr->jmpbuf, tmp_jmp, png_sizeof (jmp_buf));
  184273. #endif
  184274. /* added at libpng-1.2.6 */
  184275. #ifdef PNG_SET_USER_LIMITS_SUPPORTED
  184276. png_ptr->user_width_max=PNG_USER_WIDTH_MAX;
  184277. png_ptr->user_height_max=PNG_USER_HEIGHT_MAX;
  184278. #endif
  184279. /* initialize zbuf - compression buffer */
  184280. png_ptr->zbuf_size = PNG_ZBUF_SIZE;
  184281. png_ptr->zbuf = (png_bytep)png_malloc(png_ptr,
  184282. (png_uint_32)png_ptr->zbuf_size);
  184283. png_ptr->zstream.zalloc = png_zalloc;
  184284. png_ptr->zstream.zfree = png_zfree;
  184285. png_ptr->zstream.opaque = (voidpf)png_ptr;
  184286. switch (inflateInit(&png_ptr->zstream))
  184287. {
  184288. case Z_OK: /* Do nothing */ break;
  184289. case Z_MEM_ERROR:
  184290. case Z_STREAM_ERROR: png_error(png_ptr, "zlib memory"); break;
  184291. case Z_VERSION_ERROR: png_error(png_ptr, "zlib version"); break;
  184292. default: png_error(png_ptr, "Unknown zlib error");
  184293. }
  184294. png_ptr->zstream.next_out = png_ptr->zbuf;
  184295. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  184296. png_set_read_fn(png_ptr, png_voidp_NULL, png_rw_ptr_NULL);
  184297. }
  184298. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  184299. /* Read the information before the actual image data. This has been
  184300. * changed in v0.90 to allow reading a file that already has the magic
  184301. * bytes read from the stream. You can tell libpng how many bytes have
  184302. * been read from the beginning of the stream (up to the maximum of 8)
  184303. * via png_set_sig_bytes(), and we will only check the remaining bytes
  184304. * here. The application can then have access to the signature bytes we
  184305. * read if it is determined that this isn't a valid PNG file.
  184306. */
  184307. void PNGAPI
  184308. png_read_info(png_structp png_ptr, png_infop info_ptr)
  184309. {
  184310. if(png_ptr == NULL) return;
  184311. png_debug(1, "in png_read_info\n");
  184312. /* If we haven't checked all of the PNG signature bytes, do so now. */
  184313. if (png_ptr->sig_bytes < 8)
  184314. {
  184315. png_size_t num_checked = png_ptr->sig_bytes,
  184316. num_to_check = 8 - num_checked;
  184317. png_read_data(png_ptr, &(info_ptr->signature[num_checked]), num_to_check);
  184318. png_ptr->sig_bytes = 8;
  184319. if (png_sig_cmp(info_ptr->signature, num_checked, num_to_check))
  184320. {
  184321. if (num_checked < 4 &&
  184322. png_sig_cmp(info_ptr->signature, num_checked, num_to_check - 4))
  184323. png_error(png_ptr, "Not a PNG file");
  184324. else
  184325. png_error(png_ptr, "PNG file corrupted by ASCII conversion");
  184326. }
  184327. if (num_checked < 3)
  184328. png_ptr->mode |= PNG_HAVE_PNG_SIGNATURE;
  184329. }
  184330. for(;;)
  184331. {
  184332. #ifdef PNG_USE_LOCAL_ARRAYS
  184333. PNG_CONST PNG_IHDR;
  184334. PNG_CONST PNG_IDAT;
  184335. PNG_CONST PNG_IEND;
  184336. PNG_CONST PNG_PLTE;
  184337. #if defined(PNG_READ_bKGD_SUPPORTED)
  184338. PNG_CONST PNG_bKGD;
  184339. #endif
  184340. #if defined(PNG_READ_cHRM_SUPPORTED)
  184341. PNG_CONST PNG_cHRM;
  184342. #endif
  184343. #if defined(PNG_READ_gAMA_SUPPORTED)
  184344. PNG_CONST PNG_gAMA;
  184345. #endif
  184346. #if defined(PNG_READ_hIST_SUPPORTED)
  184347. PNG_CONST PNG_hIST;
  184348. #endif
  184349. #if defined(PNG_READ_iCCP_SUPPORTED)
  184350. PNG_CONST PNG_iCCP;
  184351. #endif
  184352. #if defined(PNG_READ_iTXt_SUPPORTED)
  184353. PNG_CONST PNG_iTXt;
  184354. #endif
  184355. #if defined(PNG_READ_oFFs_SUPPORTED)
  184356. PNG_CONST PNG_oFFs;
  184357. #endif
  184358. #if defined(PNG_READ_pCAL_SUPPORTED)
  184359. PNG_CONST PNG_pCAL;
  184360. #endif
  184361. #if defined(PNG_READ_pHYs_SUPPORTED)
  184362. PNG_CONST PNG_pHYs;
  184363. #endif
  184364. #if defined(PNG_READ_sBIT_SUPPORTED)
  184365. PNG_CONST PNG_sBIT;
  184366. #endif
  184367. #if defined(PNG_READ_sCAL_SUPPORTED)
  184368. PNG_CONST PNG_sCAL;
  184369. #endif
  184370. #if defined(PNG_READ_sPLT_SUPPORTED)
  184371. PNG_CONST PNG_sPLT;
  184372. #endif
  184373. #if defined(PNG_READ_sRGB_SUPPORTED)
  184374. PNG_CONST PNG_sRGB;
  184375. #endif
  184376. #if defined(PNG_READ_tEXt_SUPPORTED)
  184377. PNG_CONST PNG_tEXt;
  184378. #endif
  184379. #if defined(PNG_READ_tIME_SUPPORTED)
  184380. PNG_CONST PNG_tIME;
  184381. #endif
  184382. #if defined(PNG_READ_tRNS_SUPPORTED)
  184383. PNG_CONST PNG_tRNS;
  184384. #endif
  184385. #if defined(PNG_READ_zTXt_SUPPORTED)
  184386. PNG_CONST PNG_zTXt;
  184387. #endif
  184388. #endif /* PNG_USE_LOCAL_ARRAYS */
  184389. png_byte chunk_length[4];
  184390. png_uint_32 length;
  184391. png_read_data(png_ptr, chunk_length, 4);
  184392. length = png_get_uint_31(png_ptr,chunk_length);
  184393. png_reset_crc(png_ptr);
  184394. png_crc_read(png_ptr, png_ptr->chunk_name, 4);
  184395. png_debug2(0, "Reading %s chunk, length=%lu.\n", png_ptr->chunk_name,
  184396. length);
  184397. /* This should be a binary subdivision search or a hash for
  184398. * matching the chunk name rather than a linear search.
  184399. */
  184400. if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  184401. if(png_ptr->mode & PNG_AFTER_IDAT)
  184402. png_ptr->mode |= PNG_HAVE_CHUNK_AFTER_IDAT;
  184403. if (!png_memcmp(png_ptr->chunk_name, png_IHDR, 4))
  184404. png_handle_IHDR(png_ptr, info_ptr, length);
  184405. else if (!png_memcmp(png_ptr->chunk_name, png_IEND, 4))
  184406. png_handle_IEND(png_ptr, info_ptr, length);
  184407. #ifdef PNG_HANDLE_AS_UNKNOWN_SUPPORTED
  184408. else if (png_handle_as_unknown(png_ptr, png_ptr->chunk_name))
  184409. {
  184410. if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  184411. png_ptr->mode |= PNG_HAVE_IDAT;
  184412. png_handle_unknown(png_ptr, info_ptr, length);
  184413. if (!png_memcmp(png_ptr->chunk_name, png_PLTE, 4))
  184414. png_ptr->mode |= PNG_HAVE_PLTE;
  184415. else if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  184416. {
  184417. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  184418. png_error(png_ptr, "Missing IHDR before IDAT");
  184419. else if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE &&
  184420. !(png_ptr->mode & PNG_HAVE_PLTE))
  184421. png_error(png_ptr, "Missing PLTE before IDAT");
  184422. break;
  184423. }
  184424. }
  184425. #endif
  184426. else if (!png_memcmp(png_ptr->chunk_name, png_PLTE, 4))
  184427. png_handle_PLTE(png_ptr, info_ptr, length);
  184428. else if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  184429. {
  184430. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  184431. png_error(png_ptr, "Missing IHDR before IDAT");
  184432. else if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE &&
  184433. !(png_ptr->mode & PNG_HAVE_PLTE))
  184434. png_error(png_ptr, "Missing PLTE before IDAT");
  184435. png_ptr->idat_size = length;
  184436. png_ptr->mode |= PNG_HAVE_IDAT;
  184437. break;
  184438. }
  184439. #if defined(PNG_READ_bKGD_SUPPORTED)
  184440. else if (!png_memcmp(png_ptr->chunk_name, png_bKGD, 4))
  184441. png_handle_bKGD(png_ptr, info_ptr, length);
  184442. #endif
  184443. #if defined(PNG_READ_cHRM_SUPPORTED)
  184444. else if (!png_memcmp(png_ptr->chunk_name, png_cHRM, 4))
  184445. png_handle_cHRM(png_ptr, info_ptr, length);
  184446. #endif
  184447. #if defined(PNG_READ_gAMA_SUPPORTED)
  184448. else if (!png_memcmp(png_ptr->chunk_name, png_gAMA, 4))
  184449. png_handle_gAMA(png_ptr, info_ptr, length);
  184450. #endif
  184451. #if defined(PNG_READ_hIST_SUPPORTED)
  184452. else if (!png_memcmp(png_ptr->chunk_name, png_hIST, 4))
  184453. png_handle_hIST(png_ptr, info_ptr, length);
  184454. #endif
  184455. #if defined(PNG_READ_oFFs_SUPPORTED)
  184456. else if (!png_memcmp(png_ptr->chunk_name, png_oFFs, 4))
  184457. png_handle_oFFs(png_ptr, info_ptr, length);
  184458. #endif
  184459. #if defined(PNG_READ_pCAL_SUPPORTED)
  184460. else if (!png_memcmp(png_ptr->chunk_name, png_pCAL, 4))
  184461. png_handle_pCAL(png_ptr, info_ptr, length);
  184462. #endif
  184463. #if defined(PNG_READ_sCAL_SUPPORTED)
  184464. else if (!png_memcmp(png_ptr->chunk_name, png_sCAL, 4))
  184465. png_handle_sCAL(png_ptr, info_ptr, length);
  184466. #endif
  184467. #if defined(PNG_READ_pHYs_SUPPORTED)
  184468. else if (!png_memcmp(png_ptr->chunk_name, png_pHYs, 4))
  184469. png_handle_pHYs(png_ptr, info_ptr, length);
  184470. #endif
  184471. #if defined(PNG_READ_sBIT_SUPPORTED)
  184472. else if (!png_memcmp(png_ptr->chunk_name, png_sBIT, 4))
  184473. png_handle_sBIT(png_ptr, info_ptr, length);
  184474. #endif
  184475. #if defined(PNG_READ_sRGB_SUPPORTED)
  184476. else if (!png_memcmp(png_ptr->chunk_name, png_sRGB, 4))
  184477. png_handle_sRGB(png_ptr, info_ptr, length);
  184478. #endif
  184479. #if defined(PNG_READ_iCCP_SUPPORTED)
  184480. else if (!png_memcmp(png_ptr->chunk_name, png_iCCP, 4))
  184481. png_handle_iCCP(png_ptr, info_ptr, length);
  184482. #endif
  184483. #if defined(PNG_READ_sPLT_SUPPORTED)
  184484. else if (!png_memcmp(png_ptr->chunk_name, png_sPLT, 4))
  184485. png_handle_sPLT(png_ptr, info_ptr, length);
  184486. #endif
  184487. #if defined(PNG_READ_tEXt_SUPPORTED)
  184488. else if (!png_memcmp(png_ptr->chunk_name, png_tEXt, 4))
  184489. png_handle_tEXt(png_ptr, info_ptr, length);
  184490. #endif
  184491. #if defined(PNG_READ_tIME_SUPPORTED)
  184492. else if (!png_memcmp(png_ptr->chunk_name, png_tIME, 4))
  184493. png_handle_tIME(png_ptr, info_ptr, length);
  184494. #endif
  184495. #if defined(PNG_READ_tRNS_SUPPORTED)
  184496. else if (!png_memcmp(png_ptr->chunk_name, png_tRNS, 4))
  184497. png_handle_tRNS(png_ptr, info_ptr, length);
  184498. #endif
  184499. #if defined(PNG_READ_zTXt_SUPPORTED)
  184500. else if (!png_memcmp(png_ptr->chunk_name, png_zTXt, 4))
  184501. png_handle_zTXt(png_ptr, info_ptr, length);
  184502. #endif
  184503. #if defined(PNG_READ_iTXt_SUPPORTED)
  184504. else if (!png_memcmp(png_ptr->chunk_name, png_iTXt, 4))
  184505. png_handle_iTXt(png_ptr, info_ptr, length);
  184506. #endif
  184507. else
  184508. png_handle_unknown(png_ptr, info_ptr, length);
  184509. }
  184510. }
  184511. #endif /* PNG_NO_SEQUENTIAL_READ_SUPPORTED */
  184512. /* optional call to update the users info_ptr structure */
  184513. void PNGAPI
  184514. png_read_update_info(png_structp png_ptr, png_infop info_ptr)
  184515. {
  184516. png_debug(1, "in png_read_update_info\n");
  184517. if(png_ptr == NULL) return;
  184518. if (!(png_ptr->flags & PNG_FLAG_ROW_INIT))
  184519. png_read_start_row(png_ptr);
  184520. else
  184521. png_warning(png_ptr,
  184522. "Ignoring extra png_read_update_info() call; row buffer not reallocated");
  184523. png_read_transform_info(png_ptr, info_ptr);
  184524. }
  184525. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  184526. /* Initialize palette, background, etc, after transformations
  184527. * are set, but before any reading takes place. This allows
  184528. * the user to obtain a gamma-corrected palette, for example.
  184529. * If the user doesn't call this, we will do it ourselves.
  184530. */
  184531. void PNGAPI
  184532. png_start_read_image(png_structp png_ptr)
  184533. {
  184534. png_debug(1, "in png_start_read_image\n");
  184535. if(png_ptr == NULL) return;
  184536. if (!(png_ptr->flags & PNG_FLAG_ROW_INIT))
  184537. png_read_start_row(png_ptr);
  184538. }
  184539. #endif /* PNG_NO_SEQUENTIAL_READ_SUPPORTED */
  184540. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  184541. void PNGAPI
  184542. png_read_row(png_structp png_ptr, png_bytep row, png_bytep dsp_row)
  184543. {
  184544. #ifdef PNG_USE_LOCAL_ARRAYS
  184545. PNG_CONST PNG_IDAT;
  184546. PNG_CONST int png_pass_dsp_mask[7] = {0xff, 0x0f, 0xff, 0x33, 0xff, 0x55,
  184547. 0xff};
  184548. PNG_CONST int png_pass_mask[7] = {0x80, 0x08, 0x88, 0x22, 0xaa, 0x55, 0xff};
  184549. #endif
  184550. int ret;
  184551. if(png_ptr == NULL) return;
  184552. png_debug2(1, "in png_read_row (row %lu, pass %d)\n",
  184553. png_ptr->row_number, png_ptr->pass);
  184554. if (!(png_ptr->flags & PNG_FLAG_ROW_INIT))
  184555. png_read_start_row(png_ptr);
  184556. if (png_ptr->row_number == 0 && png_ptr->pass == 0)
  184557. {
  184558. /* check for transforms that have been set but were defined out */
  184559. #if defined(PNG_WRITE_INVERT_SUPPORTED) && !defined(PNG_READ_INVERT_SUPPORTED)
  184560. if (png_ptr->transformations & PNG_INVERT_MONO)
  184561. png_warning(png_ptr, "PNG_READ_INVERT_SUPPORTED is not defined.");
  184562. #endif
  184563. #if defined(PNG_WRITE_FILLER_SUPPORTED) && !defined(PNG_READ_FILLER_SUPPORTED)
  184564. if (png_ptr->transformations & PNG_FILLER)
  184565. png_warning(png_ptr, "PNG_READ_FILLER_SUPPORTED is not defined.");
  184566. #endif
  184567. #if defined(PNG_WRITE_PACKSWAP_SUPPORTED) && !defined(PNG_READ_PACKSWAP_SUPPORTED)
  184568. if (png_ptr->transformations & PNG_PACKSWAP)
  184569. png_warning(png_ptr, "PNG_READ_PACKSWAP_SUPPORTED is not defined.");
  184570. #endif
  184571. #if defined(PNG_WRITE_PACK_SUPPORTED) && !defined(PNG_READ_PACK_SUPPORTED)
  184572. if (png_ptr->transformations & PNG_PACK)
  184573. png_warning(png_ptr, "PNG_READ_PACK_SUPPORTED is not defined.");
  184574. #endif
  184575. #if defined(PNG_WRITE_SHIFT_SUPPORTED) && !defined(PNG_READ_SHIFT_SUPPORTED)
  184576. if (png_ptr->transformations & PNG_SHIFT)
  184577. png_warning(png_ptr, "PNG_READ_SHIFT_SUPPORTED is not defined.");
  184578. #endif
  184579. #if defined(PNG_WRITE_BGR_SUPPORTED) && !defined(PNG_READ_BGR_SUPPORTED)
  184580. if (png_ptr->transformations & PNG_BGR)
  184581. png_warning(png_ptr, "PNG_READ_BGR_SUPPORTED is not defined.");
  184582. #endif
  184583. #if defined(PNG_WRITE_SWAP_SUPPORTED) && !defined(PNG_READ_SWAP_SUPPORTED)
  184584. if (png_ptr->transformations & PNG_SWAP_BYTES)
  184585. png_warning(png_ptr, "PNG_READ_SWAP_SUPPORTED is not defined.");
  184586. #endif
  184587. }
  184588. #if defined(PNG_READ_INTERLACING_SUPPORTED)
  184589. /* if interlaced and we do not need a new row, combine row and return */
  184590. if (png_ptr->interlaced && (png_ptr->transformations & PNG_INTERLACE))
  184591. {
  184592. switch (png_ptr->pass)
  184593. {
  184594. case 0:
  184595. if (png_ptr->row_number & 0x07)
  184596. {
  184597. if (dsp_row != NULL)
  184598. png_combine_row(png_ptr, dsp_row,
  184599. png_pass_dsp_mask[png_ptr->pass]);
  184600. png_read_finish_row(png_ptr);
  184601. return;
  184602. }
  184603. break;
  184604. case 1:
  184605. if ((png_ptr->row_number & 0x07) || png_ptr->width < 5)
  184606. {
  184607. if (dsp_row != NULL)
  184608. png_combine_row(png_ptr, dsp_row,
  184609. png_pass_dsp_mask[png_ptr->pass]);
  184610. png_read_finish_row(png_ptr);
  184611. return;
  184612. }
  184613. break;
  184614. case 2:
  184615. if ((png_ptr->row_number & 0x07) != 4)
  184616. {
  184617. if (dsp_row != NULL && (png_ptr->row_number & 4))
  184618. png_combine_row(png_ptr, dsp_row,
  184619. png_pass_dsp_mask[png_ptr->pass]);
  184620. png_read_finish_row(png_ptr);
  184621. return;
  184622. }
  184623. break;
  184624. case 3:
  184625. if ((png_ptr->row_number & 3) || png_ptr->width < 3)
  184626. {
  184627. if (dsp_row != NULL)
  184628. png_combine_row(png_ptr, dsp_row,
  184629. png_pass_dsp_mask[png_ptr->pass]);
  184630. png_read_finish_row(png_ptr);
  184631. return;
  184632. }
  184633. break;
  184634. case 4:
  184635. if ((png_ptr->row_number & 3) != 2)
  184636. {
  184637. if (dsp_row != NULL && (png_ptr->row_number & 2))
  184638. png_combine_row(png_ptr, dsp_row,
  184639. png_pass_dsp_mask[png_ptr->pass]);
  184640. png_read_finish_row(png_ptr);
  184641. return;
  184642. }
  184643. break;
  184644. case 5:
  184645. if ((png_ptr->row_number & 1) || png_ptr->width < 2)
  184646. {
  184647. if (dsp_row != NULL)
  184648. png_combine_row(png_ptr, dsp_row,
  184649. png_pass_dsp_mask[png_ptr->pass]);
  184650. png_read_finish_row(png_ptr);
  184651. return;
  184652. }
  184653. break;
  184654. case 6:
  184655. if (!(png_ptr->row_number & 1))
  184656. {
  184657. png_read_finish_row(png_ptr);
  184658. return;
  184659. }
  184660. break;
  184661. }
  184662. }
  184663. #endif
  184664. if (!(png_ptr->mode & PNG_HAVE_IDAT))
  184665. png_error(png_ptr, "Invalid attempt to read row data");
  184666. png_ptr->zstream.next_out = png_ptr->row_buf;
  184667. png_ptr->zstream.avail_out = (uInt)png_ptr->irowbytes;
  184668. do
  184669. {
  184670. if (!(png_ptr->zstream.avail_in))
  184671. {
  184672. while (!png_ptr->idat_size)
  184673. {
  184674. png_byte chunk_length[4];
  184675. png_crc_finish(png_ptr, 0);
  184676. png_read_data(png_ptr, chunk_length, 4);
  184677. png_ptr->idat_size = png_get_uint_31(png_ptr,chunk_length);
  184678. png_reset_crc(png_ptr);
  184679. png_crc_read(png_ptr, png_ptr->chunk_name, 4);
  184680. if (png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  184681. png_error(png_ptr, "Not enough image data");
  184682. }
  184683. png_ptr->zstream.avail_in = (uInt)png_ptr->zbuf_size;
  184684. png_ptr->zstream.next_in = png_ptr->zbuf;
  184685. if (png_ptr->zbuf_size > png_ptr->idat_size)
  184686. png_ptr->zstream.avail_in = (uInt)png_ptr->idat_size;
  184687. png_crc_read(png_ptr, png_ptr->zbuf,
  184688. (png_size_t)png_ptr->zstream.avail_in);
  184689. png_ptr->idat_size -= png_ptr->zstream.avail_in;
  184690. }
  184691. ret = inflate(&png_ptr->zstream, Z_PARTIAL_FLUSH);
  184692. if (ret == Z_STREAM_END)
  184693. {
  184694. if (png_ptr->zstream.avail_out || png_ptr->zstream.avail_in ||
  184695. png_ptr->idat_size)
  184696. png_error(png_ptr, "Extra compressed data");
  184697. png_ptr->mode |= PNG_AFTER_IDAT;
  184698. png_ptr->flags |= PNG_FLAG_ZLIB_FINISHED;
  184699. break;
  184700. }
  184701. if (ret != Z_OK)
  184702. png_error(png_ptr, png_ptr->zstream.msg ? png_ptr->zstream.msg :
  184703. "Decompression error");
  184704. } while (png_ptr->zstream.avail_out);
  184705. png_ptr->row_info.color_type = png_ptr->color_type;
  184706. png_ptr->row_info.width = png_ptr->iwidth;
  184707. png_ptr->row_info.channels = png_ptr->channels;
  184708. png_ptr->row_info.bit_depth = png_ptr->bit_depth;
  184709. png_ptr->row_info.pixel_depth = png_ptr->pixel_depth;
  184710. png_ptr->row_info.rowbytes = PNG_ROWBYTES(png_ptr->row_info.pixel_depth,
  184711. png_ptr->row_info.width);
  184712. if(png_ptr->row_buf[0])
  184713. png_read_filter_row(png_ptr, &(png_ptr->row_info),
  184714. png_ptr->row_buf + 1, png_ptr->prev_row + 1,
  184715. (int)(png_ptr->row_buf[0]));
  184716. png_memcpy_check(png_ptr, png_ptr->prev_row, png_ptr->row_buf,
  184717. png_ptr->rowbytes + 1);
  184718. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  184719. if((png_ptr->mng_features_permitted & PNG_FLAG_MNG_FILTER_64) &&
  184720. (png_ptr->filter_type == PNG_INTRAPIXEL_DIFFERENCING))
  184721. {
  184722. /* Intrapixel differencing */
  184723. png_do_read_intrapixel(&(png_ptr->row_info), png_ptr->row_buf + 1);
  184724. }
  184725. #endif
  184726. if (png_ptr->transformations || (png_ptr->flags&PNG_FLAG_STRIP_ALPHA))
  184727. png_do_read_transformations(png_ptr);
  184728. #if defined(PNG_READ_INTERLACING_SUPPORTED)
  184729. /* blow up interlaced rows to full size */
  184730. if (png_ptr->interlaced &&
  184731. (png_ptr->transformations & PNG_INTERLACE))
  184732. {
  184733. if (png_ptr->pass < 6)
  184734. /* old interface (pre-1.0.9):
  184735. png_do_read_interlace(&(png_ptr->row_info),
  184736. png_ptr->row_buf + 1, png_ptr->pass, png_ptr->transformations);
  184737. */
  184738. png_do_read_interlace(png_ptr);
  184739. if (dsp_row != NULL)
  184740. png_combine_row(png_ptr, dsp_row,
  184741. png_pass_dsp_mask[png_ptr->pass]);
  184742. if (row != NULL)
  184743. png_combine_row(png_ptr, row,
  184744. png_pass_mask[png_ptr->pass]);
  184745. }
  184746. else
  184747. #endif
  184748. {
  184749. if (row != NULL)
  184750. png_combine_row(png_ptr, row, 0xff);
  184751. if (dsp_row != NULL)
  184752. png_combine_row(png_ptr, dsp_row, 0xff);
  184753. }
  184754. png_read_finish_row(png_ptr);
  184755. if (png_ptr->read_row_fn != NULL)
  184756. (*(png_ptr->read_row_fn))(png_ptr, png_ptr->row_number, png_ptr->pass);
  184757. }
  184758. #endif /* PNG_NO_SEQUENTIAL_READ_SUPPORTED */
  184759. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  184760. /* Read one or more rows of image data. If the image is interlaced,
  184761. * and png_set_interlace_handling() has been called, the rows need to
  184762. * contain the contents of the rows from the previous pass. If the
  184763. * image has alpha or transparency, and png_handle_alpha()[*] has been
  184764. * called, the rows contents must be initialized to the contents of the
  184765. * screen.
  184766. *
  184767. * "row" holds the actual image, and pixels are placed in it
  184768. * as they arrive. If the image is displayed after each pass, it will
  184769. * appear to "sparkle" in. "display_row" can be used to display a
  184770. * "chunky" progressive image, with finer detail added as it becomes
  184771. * available. If you do not want this "chunky" display, you may pass
  184772. * NULL for display_row. If you do not want the sparkle display, and
  184773. * you have not called png_handle_alpha(), you may pass NULL for rows.
  184774. * If you have called png_handle_alpha(), and the image has either an
  184775. * alpha channel or a transparency chunk, you must provide a buffer for
  184776. * rows. In this case, you do not have to provide a display_row buffer
  184777. * also, but you may. If the image is not interlaced, or if you have
  184778. * not called png_set_interlace_handling(), the display_row buffer will
  184779. * be ignored, so pass NULL to it.
  184780. *
  184781. * [*] png_handle_alpha() does not exist yet, as of this version of libpng
  184782. */
  184783. void PNGAPI
  184784. png_read_rows(png_structp png_ptr, png_bytepp row,
  184785. png_bytepp display_row, png_uint_32 num_rows)
  184786. {
  184787. png_uint_32 i;
  184788. png_bytepp rp;
  184789. png_bytepp dp;
  184790. png_debug(1, "in png_read_rows\n");
  184791. if(png_ptr == NULL) return;
  184792. rp = row;
  184793. dp = display_row;
  184794. if (rp != NULL && dp != NULL)
  184795. for (i = 0; i < num_rows; i++)
  184796. {
  184797. png_bytep rptr = *rp++;
  184798. png_bytep dptr = *dp++;
  184799. png_read_row(png_ptr, rptr, dptr);
  184800. }
  184801. else if(rp != NULL)
  184802. for (i = 0; i < num_rows; i++)
  184803. {
  184804. png_bytep rptr = *rp;
  184805. png_read_row(png_ptr, rptr, png_bytep_NULL);
  184806. rp++;
  184807. }
  184808. else if(dp != NULL)
  184809. for (i = 0; i < num_rows; i++)
  184810. {
  184811. png_bytep dptr = *dp;
  184812. png_read_row(png_ptr, png_bytep_NULL, dptr);
  184813. dp++;
  184814. }
  184815. }
  184816. #endif /* PNG_NO_SEQUENTIAL_READ_SUPPORTED */
  184817. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  184818. /* Read the entire image. If the image has an alpha channel or a tRNS
  184819. * chunk, and you have called png_handle_alpha()[*], you will need to
  184820. * initialize the image to the current image that PNG will be overlaying.
  184821. * We set the num_rows again here, in case it was incorrectly set in
  184822. * png_read_start_row() by a call to png_read_update_info() or
  184823. * png_start_read_image() if png_set_interlace_handling() wasn't called
  184824. * prior to either of these functions like it should have been. You can
  184825. * only call this function once. If you desire to have an image for
  184826. * each pass of a interlaced image, use png_read_rows() instead.
  184827. *
  184828. * [*] png_handle_alpha() does not exist yet, as of this version of libpng
  184829. */
  184830. void PNGAPI
  184831. png_read_image(png_structp png_ptr, png_bytepp image)
  184832. {
  184833. png_uint_32 i,image_height;
  184834. int pass, j;
  184835. png_bytepp rp;
  184836. png_debug(1, "in png_read_image\n");
  184837. if(png_ptr == NULL) return;
  184838. #ifdef PNG_READ_INTERLACING_SUPPORTED
  184839. pass = png_set_interlace_handling(png_ptr);
  184840. #else
  184841. if (png_ptr->interlaced)
  184842. png_error(png_ptr,
  184843. "Cannot read interlaced image -- interlace handler disabled.");
  184844. pass = 1;
  184845. #endif
  184846. image_height=png_ptr->height;
  184847. png_ptr->num_rows = image_height; /* Make sure this is set correctly */
  184848. for (j = 0; j < pass; j++)
  184849. {
  184850. rp = image;
  184851. for (i = 0; i < image_height; i++)
  184852. {
  184853. png_read_row(png_ptr, *rp, png_bytep_NULL);
  184854. rp++;
  184855. }
  184856. }
  184857. }
  184858. #endif /* PNG_NO_SEQUENTIAL_READ_SUPPORTED */
  184859. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  184860. /* Read the end of the PNG file. Will not read past the end of the
  184861. * file, will verify the end is accurate, and will read any comments
  184862. * or time information at the end of the file, if info is not NULL.
  184863. */
  184864. void PNGAPI
  184865. png_read_end(png_structp png_ptr, png_infop info_ptr)
  184866. {
  184867. png_byte chunk_length[4];
  184868. png_uint_32 length;
  184869. png_debug(1, "in png_read_end\n");
  184870. if(png_ptr == NULL) return;
  184871. png_crc_finish(png_ptr, 0); /* Finish off CRC from last IDAT chunk */
  184872. do
  184873. {
  184874. #ifdef PNG_USE_LOCAL_ARRAYS
  184875. PNG_CONST PNG_IHDR;
  184876. PNG_CONST PNG_IDAT;
  184877. PNG_CONST PNG_IEND;
  184878. PNG_CONST PNG_PLTE;
  184879. #if defined(PNG_READ_bKGD_SUPPORTED)
  184880. PNG_CONST PNG_bKGD;
  184881. #endif
  184882. #if defined(PNG_READ_cHRM_SUPPORTED)
  184883. PNG_CONST PNG_cHRM;
  184884. #endif
  184885. #if defined(PNG_READ_gAMA_SUPPORTED)
  184886. PNG_CONST PNG_gAMA;
  184887. #endif
  184888. #if defined(PNG_READ_hIST_SUPPORTED)
  184889. PNG_CONST PNG_hIST;
  184890. #endif
  184891. #if defined(PNG_READ_iCCP_SUPPORTED)
  184892. PNG_CONST PNG_iCCP;
  184893. #endif
  184894. #if defined(PNG_READ_iTXt_SUPPORTED)
  184895. PNG_CONST PNG_iTXt;
  184896. #endif
  184897. #if defined(PNG_READ_oFFs_SUPPORTED)
  184898. PNG_CONST PNG_oFFs;
  184899. #endif
  184900. #if defined(PNG_READ_pCAL_SUPPORTED)
  184901. PNG_CONST PNG_pCAL;
  184902. #endif
  184903. #if defined(PNG_READ_pHYs_SUPPORTED)
  184904. PNG_CONST PNG_pHYs;
  184905. #endif
  184906. #if defined(PNG_READ_sBIT_SUPPORTED)
  184907. PNG_CONST PNG_sBIT;
  184908. #endif
  184909. #if defined(PNG_READ_sCAL_SUPPORTED)
  184910. PNG_CONST PNG_sCAL;
  184911. #endif
  184912. #if defined(PNG_READ_sPLT_SUPPORTED)
  184913. PNG_CONST PNG_sPLT;
  184914. #endif
  184915. #if defined(PNG_READ_sRGB_SUPPORTED)
  184916. PNG_CONST PNG_sRGB;
  184917. #endif
  184918. #if defined(PNG_READ_tEXt_SUPPORTED)
  184919. PNG_CONST PNG_tEXt;
  184920. #endif
  184921. #if defined(PNG_READ_tIME_SUPPORTED)
  184922. PNG_CONST PNG_tIME;
  184923. #endif
  184924. #if defined(PNG_READ_tRNS_SUPPORTED)
  184925. PNG_CONST PNG_tRNS;
  184926. #endif
  184927. #if defined(PNG_READ_zTXt_SUPPORTED)
  184928. PNG_CONST PNG_zTXt;
  184929. #endif
  184930. #endif /* PNG_USE_LOCAL_ARRAYS */
  184931. png_read_data(png_ptr, chunk_length, 4);
  184932. length = png_get_uint_31(png_ptr,chunk_length);
  184933. png_reset_crc(png_ptr);
  184934. png_crc_read(png_ptr, png_ptr->chunk_name, 4);
  184935. png_debug1(0, "Reading %s chunk.\n", png_ptr->chunk_name);
  184936. if (!png_memcmp(png_ptr->chunk_name, png_IHDR, 4))
  184937. png_handle_IHDR(png_ptr, info_ptr, length);
  184938. else if (!png_memcmp(png_ptr->chunk_name, png_IEND, 4))
  184939. png_handle_IEND(png_ptr, info_ptr, length);
  184940. #ifdef PNG_HANDLE_AS_UNKNOWN_SUPPORTED
  184941. else if (png_handle_as_unknown(png_ptr, png_ptr->chunk_name))
  184942. {
  184943. if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  184944. {
  184945. if ((length > 0) || (png_ptr->mode & PNG_HAVE_CHUNK_AFTER_IDAT))
  184946. png_error(png_ptr, "Too many IDAT's found");
  184947. }
  184948. png_handle_unknown(png_ptr, info_ptr, length);
  184949. if (!png_memcmp(png_ptr->chunk_name, png_PLTE, 4))
  184950. png_ptr->mode |= PNG_HAVE_PLTE;
  184951. }
  184952. #endif
  184953. else if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  184954. {
  184955. /* Zero length IDATs are legal after the last IDAT has been
  184956. * read, but not after other chunks have been read.
  184957. */
  184958. if ((length > 0) || (png_ptr->mode & PNG_HAVE_CHUNK_AFTER_IDAT))
  184959. png_error(png_ptr, "Too many IDAT's found");
  184960. png_crc_finish(png_ptr, length);
  184961. }
  184962. else if (!png_memcmp(png_ptr->chunk_name, png_PLTE, 4))
  184963. png_handle_PLTE(png_ptr, info_ptr, length);
  184964. #if defined(PNG_READ_bKGD_SUPPORTED)
  184965. else if (!png_memcmp(png_ptr->chunk_name, png_bKGD, 4))
  184966. png_handle_bKGD(png_ptr, info_ptr, length);
  184967. #endif
  184968. #if defined(PNG_READ_cHRM_SUPPORTED)
  184969. else if (!png_memcmp(png_ptr->chunk_name, png_cHRM, 4))
  184970. png_handle_cHRM(png_ptr, info_ptr, length);
  184971. #endif
  184972. #if defined(PNG_READ_gAMA_SUPPORTED)
  184973. else if (!png_memcmp(png_ptr->chunk_name, png_gAMA, 4))
  184974. png_handle_gAMA(png_ptr, info_ptr, length);
  184975. #endif
  184976. #if defined(PNG_READ_hIST_SUPPORTED)
  184977. else if (!png_memcmp(png_ptr->chunk_name, png_hIST, 4))
  184978. png_handle_hIST(png_ptr, info_ptr, length);
  184979. #endif
  184980. #if defined(PNG_READ_oFFs_SUPPORTED)
  184981. else if (!png_memcmp(png_ptr->chunk_name, png_oFFs, 4))
  184982. png_handle_oFFs(png_ptr, info_ptr, length);
  184983. #endif
  184984. #if defined(PNG_READ_pCAL_SUPPORTED)
  184985. else if (!png_memcmp(png_ptr->chunk_name, png_pCAL, 4))
  184986. png_handle_pCAL(png_ptr, info_ptr, length);
  184987. #endif
  184988. #if defined(PNG_READ_sCAL_SUPPORTED)
  184989. else if (!png_memcmp(png_ptr->chunk_name, png_sCAL, 4))
  184990. png_handle_sCAL(png_ptr, info_ptr, length);
  184991. #endif
  184992. #if defined(PNG_READ_pHYs_SUPPORTED)
  184993. else if (!png_memcmp(png_ptr->chunk_name, png_pHYs, 4))
  184994. png_handle_pHYs(png_ptr, info_ptr, length);
  184995. #endif
  184996. #if defined(PNG_READ_sBIT_SUPPORTED)
  184997. else if (!png_memcmp(png_ptr->chunk_name, png_sBIT, 4))
  184998. png_handle_sBIT(png_ptr, info_ptr, length);
  184999. #endif
  185000. #if defined(PNG_READ_sRGB_SUPPORTED)
  185001. else if (!png_memcmp(png_ptr->chunk_name, png_sRGB, 4))
  185002. png_handle_sRGB(png_ptr, info_ptr, length);
  185003. #endif
  185004. #if defined(PNG_READ_iCCP_SUPPORTED)
  185005. else if (!png_memcmp(png_ptr->chunk_name, png_iCCP, 4))
  185006. png_handle_iCCP(png_ptr, info_ptr, length);
  185007. #endif
  185008. #if defined(PNG_READ_sPLT_SUPPORTED)
  185009. else if (!png_memcmp(png_ptr->chunk_name, png_sPLT, 4))
  185010. png_handle_sPLT(png_ptr, info_ptr, length);
  185011. #endif
  185012. #if defined(PNG_READ_tEXt_SUPPORTED)
  185013. else if (!png_memcmp(png_ptr->chunk_name, png_tEXt, 4))
  185014. png_handle_tEXt(png_ptr, info_ptr, length);
  185015. #endif
  185016. #if defined(PNG_READ_tIME_SUPPORTED)
  185017. else if (!png_memcmp(png_ptr->chunk_name, png_tIME, 4))
  185018. png_handle_tIME(png_ptr, info_ptr, length);
  185019. #endif
  185020. #if defined(PNG_READ_tRNS_SUPPORTED)
  185021. else if (!png_memcmp(png_ptr->chunk_name, png_tRNS, 4))
  185022. png_handle_tRNS(png_ptr, info_ptr, length);
  185023. #endif
  185024. #if defined(PNG_READ_zTXt_SUPPORTED)
  185025. else if (!png_memcmp(png_ptr->chunk_name, png_zTXt, 4))
  185026. png_handle_zTXt(png_ptr, info_ptr, length);
  185027. #endif
  185028. #if defined(PNG_READ_iTXt_SUPPORTED)
  185029. else if (!png_memcmp(png_ptr->chunk_name, png_iTXt, 4))
  185030. png_handle_iTXt(png_ptr, info_ptr, length);
  185031. #endif
  185032. else
  185033. png_handle_unknown(png_ptr, info_ptr, length);
  185034. } while (!(png_ptr->mode & PNG_HAVE_IEND));
  185035. }
  185036. #endif /* PNG_NO_SEQUENTIAL_READ_SUPPORTED */
  185037. /* free all memory used by the read */
  185038. void PNGAPI
  185039. png_destroy_read_struct(png_structpp png_ptr_ptr, png_infopp info_ptr_ptr,
  185040. png_infopp end_info_ptr_ptr)
  185041. {
  185042. png_structp png_ptr = NULL;
  185043. png_infop info_ptr = NULL, end_info_ptr = NULL;
  185044. #ifdef PNG_USER_MEM_SUPPORTED
  185045. png_free_ptr free_fn;
  185046. png_voidp mem_ptr;
  185047. #endif
  185048. png_debug(1, "in png_destroy_read_struct\n");
  185049. if (png_ptr_ptr != NULL)
  185050. png_ptr = *png_ptr_ptr;
  185051. if (info_ptr_ptr != NULL)
  185052. info_ptr = *info_ptr_ptr;
  185053. if (end_info_ptr_ptr != NULL)
  185054. end_info_ptr = *end_info_ptr_ptr;
  185055. #ifdef PNG_USER_MEM_SUPPORTED
  185056. free_fn = png_ptr->free_fn;
  185057. mem_ptr = png_ptr->mem_ptr;
  185058. #endif
  185059. png_read_destroy(png_ptr, info_ptr, end_info_ptr);
  185060. if (info_ptr != NULL)
  185061. {
  185062. #if defined(PNG_TEXT_SUPPORTED)
  185063. png_free_data(png_ptr, info_ptr, PNG_FREE_TEXT, -1);
  185064. #endif
  185065. #ifdef PNG_USER_MEM_SUPPORTED
  185066. png_destroy_struct_2((png_voidp)info_ptr, (png_free_ptr)free_fn,
  185067. (png_voidp)mem_ptr);
  185068. #else
  185069. png_destroy_struct((png_voidp)info_ptr);
  185070. #endif
  185071. *info_ptr_ptr = NULL;
  185072. }
  185073. if (end_info_ptr != NULL)
  185074. {
  185075. #if defined(PNG_READ_TEXT_SUPPORTED)
  185076. png_free_data(png_ptr, end_info_ptr, PNG_FREE_TEXT, -1);
  185077. #endif
  185078. #ifdef PNG_USER_MEM_SUPPORTED
  185079. png_destroy_struct_2((png_voidp)end_info_ptr, (png_free_ptr)free_fn,
  185080. (png_voidp)mem_ptr);
  185081. #else
  185082. png_destroy_struct((png_voidp)end_info_ptr);
  185083. #endif
  185084. *end_info_ptr_ptr = NULL;
  185085. }
  185086. if (png_ptr != NULL)
  185087. {
  185088. #ifdef PNG_USER_MEM_SUPPORTED
  185089. png_destroy_struct_2((png_voidp)png_ptr, (png_free_ptr)free_fn,
  185090. (png_voidp)mem_ptr);
  185091. #else
  185092. png_destroy_struct((png_voidp)png_ptr);
  185093. #endif
  185094. *png_ptr_ptr = NULL;
  185095. }
  185096. }
  185097. /* free all memory used by the read (old method) */
  185098. void /* PRIVATE */
  185099. png_read_destroy(png_structp png_ptr, png_infop info_ptr, png_infop end_info_ptr)
  185100. {
  185101. #ifdef PNG_SETJMP_SUPPORTED
  185102. jmp_buf tmp_jmp;
  185103. #endif
  185104. png_error_ptr error_fn;
  185105. png_error_ptr warning_fn;
  185106. png_voidp error_ptr;
  185107. #ifdef PNG_USER_MEM_SUPPORTED
  185108. png_free_ptr free_fn;
  185109. #endif
  185110. png_debug(1, "in png_read_destroy\n");
  185111. if (info_ptr != NULL)
  185112. png_info_destroy(png_ptr, info_ptr);
  185113. if (end_info_ptr != NULL)
  185114. png_info_destroy(png_ptr, end_info_ptr);
  185115. png_free(png_ptr, png_ptr->zbuf);
  185116. png_free(png_ptr, png_ptr->big_row_buf);
  185117. png_free(png_ptr, png_ptr->prev_row);
  185118. #if defined(PNG_READ_DITHER_SUPPORTED)
  185119. png_free(png_ptr, png_ptr->palette_lookup);
  185120. png_free(png_ptr, png_ptr->dither_index);
  185121. #endif
  185122. #if defined(PNG_READ_GAMMA_SUPPORTED)
  185123. png_free(png_ptr, png_ptr->gamma_table);
  185124. #endif
  185125. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  185126. png_free(png_ptr, png_ptr->gamma_from_1);
  185127. png_free(png_ptr, png_ptr->gamma_to_1);
  185128. #endif
  185129. #ifdef PNG_FREE_ME_SUPPORTED
  185130. if (png_ptr->free_me & PNG_FREE_PLTE)
  185131. png_zfree(png_ptr, png_ptr->palette);
  185132. png_ptr->free_me &= ~PNG_FREE_PLTE;
  185133. #else
  185134. if (png_ptr->flags & PNG_FLAG_FREE_PLTE)
  185135. png_zfree(png_ptr, png_ptr->palette);
  185136. png_ptr->flags &= ~PNG_FLAG_FREE_PLTE;
  185137. #endif
  185138. #if defined(PNG_tRNS_SUPPORTED) || \
  185139. defined(PNG_READ_EXPAND_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
  185140. #ifdef PNG_FREE_ME_SUPPORTED
  185141. if (png_ptr->free_me & PNG_FREE_TRNS)
  185142. png_free(png_ptr, png_ptr->trans);
  185143. png_ptr->free_me &= ~PNG_FREE_TRNS;
  185144. #else
  185145. if (png_ptr->flags & PNG_FLAG_FREE_TRNS)
  185146. png_free(png_ptr, png_ptr->trans);
  185147. png_ptr->flags &= ~PNG_FLAG_FREE_TRNS;
  185148. #endif
  185149. #endif
  185150. #if defined(PNG_READ_hIST_SUPPORTED)
  185151. #ifdef PNG_FREE_ME_SUPPORTED
  185152. if (png_ptr->free_me & PNG_FREE_HIST)
  185153. png_free(png_ptr, png_ptr->hist);
  185154. png_ptr->free_me &= ~PNG_FREE_HIST;
  185155. #else
  185156. if (png_ptr->flags & PNG_FLAG_FREE_HIST)
  185157. png_free(png_ptr, png_ptr->hist);
  185158. png_ptr->flags &= ~PNG_FLAG_FREE_HIST;
  185159. #endif
  185160. #endif
  185161. #if defined(PNG_READ_GAMMA_SUPPORTED)
  185162. if (png_ptr->gamma_16_table != NULL)
  185163. {
  185164. int i;
  185165. int istop = (1 << (8 - png_ptr->gamma_shift));
  185166. for (i = 0; i < istop; i++)
  185167. {
  185168. png_free(png_ptr, png_ptr->gamma_16_table[i]);
  185169. }
  185170. png_free(png_ptr, png_ptr->gamma_16_table);
  185171. }
  185172. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  185173. if (png_ptr->gamma_16_from_1 != NULL)
  185174. {
  185175. int i;
  185176. int istop = (1 << (8 - png_ptr->gamma_shift));
  185177. for (i = 0; i < istop; i++)
  185178. {
  185179. png_free(png_ptr, png_ptr->gamma_16_from_1[i]);
  185180. }
  185181. png_free(png_ptr, png_ptr->gamma_16_from_1);
  185182. }
  185183. if (png_ptr->gamma_16_to_1 != NULL)
  185184. {
  185185. int i;
  185186. int istop = (1 << (8 - png_ptr->gamma_shift));
  185187. for (i = 0; i < istop; i++)
  185188. {
  185189. png_free(png_ptr, png_ptr->gamma_16_to_1[i]);
  185190. }
  185191. png_free(png_ptr, png_ptr->gamma_16_to_1);
  185192. }
  185193. #endif
  185194. #endif
  185195. #if defined(PNG_TIME_RFC1123_SUPPORTED)
  185196. png_free(png_ptr, png_ptr->time_buffer);
  185197. #endif
  185198. inflateEnd(&png_ptr->zstream);
  185199. #ifdef PNG_PROGRESSIVE_READ_SUPPORTED
  185200. png_free(png_ptr, png_ptr->save_buffer);
  185201. #endif
  185202. #ifdef PNG_PROGRESSIVE_READ_SUPPORTED
  185203. #ifdef PNG_TEXT_SUPPORTED
  185204. png_free(png_ptr, png_ptr->current_text);
  185205. #endif /* PNG_TEXT_SUPPORTED */
  185206. #endif /* PNG_PROGRESSIVE_READ_SUPPORTED */
  185207. /* Save the important info out of the png_struct, in case it is
  185208. * being used again.
  185209. */
  185210. #ifdef PNG_SETJMP_SUPPORTED
  185211. png_memcpy(tmp_jmp, png_ptr->jmpbuf, png_sizeof (jmp_buf));
  185212. #endif
  185213. error_fn = png_ptr->error_fn;
  185214. warning_fn = png_ptr->warning_fn;
  185215. error_ptr = png_ptr->error_ptr;
  185216. #ifdef PNG_USER_MEM_SUPPORTED
  185217. free_fn = png_ptr->free_fn;
  185218. #endif
  185219. png_memset(png_ptr, 0, png_sizeof (png_struct));
  185220. png_ptr->error_fn = error_fn;
  185221. png_ptr->warning_fn = warning_fn;
  185222. png_ptr->error_ptr = error_ptr;
  185223. #ifdef PNG_USER_MEM_SUPPORTED
  185224. png_ptr->free_fn = free_fn;
  185225. #endif
  185226. #ifdef PNG_SETJMP_SUPPORTED
  185227. png_memcpy(png_ptr->jmpbuf, tmp_jmp, png_sizeof (jmp_buf));
  185228. #endif
  185229. }
  185230. void PNGAPI
  185231. png_set_read_status_fn(png_structp png_ptr, png_read_status_ptr read_row_fn)
  185232. {
  185233. if(png_ptr == NULL) return;
  185234. png_ptr->read_row_fn = read_row_fn;
  185235. }
  185236. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  185237. #if defined(PNG_INFO_IMAGE_SUPPORTED)
  185238. void PNGAPI
  185239. png_read_png(png_structp png_ptr, png_infop info_ptr,
  185240. int transforms,
  185241. voidp params)
  185242. {
  185243. int row;
  185244. if(png_ptr == NULL) return;
  185245. #if defined(PNG_READ_INVERT_ALPHA_SUPPORTED)
  185246. /* invert the alpha channel from opacity to transparency
  185247. */
  185248. if (transforms & PNG_TRANSFORM_INVERT_ALPHA)
  185249. png_set_invert_alpha(png_ptr);
  185250. #endif
  185251. /* png_read_info() gives us all of the information from the
  185252. * PNG file before the first IDAT (image data chunk).
  185253. */
  185254. png_read_info(png_ptr, info_ptr);
  185255. if (info_ptr->height > PNG_UINT_32_MAX/png_sizeof(png_bytep))
  185256. png_error(png_ptr,"Image is too high to process with png_read_png()");
  185257. /* -------------- image transformations start here ------------------- */
  185258. #if defined(PNG_READ_16_TO_8_SUPPORTED)
  185259. /* tell libpng to strip 16 bit/color files down to 8 bits per color
  185260. */
  185261. if (transforms & PNG_TRANSFORM_STRIP_16)
  185262. png_set_strip_16(png_ptr);
  185263. #endif
  185264. #if defined(PNG_READ_STRIP_ALPHA_SUPPORTED)
  185265. /* Strip alpha bytes from the input data without combining with
  185266. * the background (not recommended).
  185267. */
  185268. if (transforms & PNG_TRANSFORM_STRIP_ALPHA)
  185269. png_set_strip_alpha(png_ptr);
  185270. #endif
  185271. #if defined(PNG_READ_PACK_SUPPORTED) && !defined(PNG_READ_EXPAND_SUPPORTED)
  185272. /* Extract multiple pixels with bit depths of 1, 2, or 4 from a single
  185273. * byte into separate bytes (useful for paletted and grayscale images).
  185274. */
  185275. if (transforms & PNG_TRANSFORM_PACKING)
  185276. png_set_packing(png_ptr);
  185277. #endif
  185278. #if defined(PNG_READ_PACKSWAP_SUPPORTED)
  185279. /* Change the order of packed pixels to least significant bit first
  185280. * (not useful if you are using png_set_packing).
  185281. */
  185282. if (transforms & PNG_TRANSFORM_PACKSWAP)
  185283. png_set_packswap(png_ptr);
  185284. #endif
  185285. #if defined(PNG_READ_EXPAND_SUPPORTED)
  185286. /* Expand paletted colors into true RGB triplets
  185287. * Expand grayscale images to full 8 bits from 1, 2, or 4 bits/pixel
  185288. * Expand paletted or RGB images with transparency to full alpha
  185289. * channels so the data will be available as RGBA quartets.
  185290. */
  185291. if (transforms & PNG_TRANSFORM_EXPAND)
  185292. if ((png_ptr->bit_depth < 8) ||
  185293. (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE) ||
  185294. (png_get_valid(png_ptr, info_ptr, PNG_INFO_tRNS)))
  185295. png_set_expand(png_ptr);
  185296. #endif
  185297. /* We don't handle background color or gamma transformation or dithering.
  185298. */
  185299. #if defined(PNG_READ_INVERT_SUPPORTED)
  185300. /* invert monochrome files to have 0 as white and 1 as black
  185301. */
  185302. if (transforms & PNG_TRANSFORM_INVERT_MONO)
  185303. png_set_invert_mono(png_ptr);
  185304. #endif
  185305. #if defined(PNG_READ_SHIFT_SUPPORTED)
  185306. /* If you want to shift the pixel values from the range [0,255] or
  185307. * [0,65535] to the original [0,7] or [0,31], or whatever range the
  185308. * colors were originally in:
  185309. */
  185310. if ((transforms & PNG_TRANSFORM_SHIFT)
  185311. && png_get_valid(png_ptr, info_ptr, PNG_INFO_sBIT))
  185312. {
  185313. png_color_8p sig_bit;
  185314. png_get_sBIT(png_ptr, info_ptr, &sig_bit);
  185315. png_set_shift(png_ptr, sig_bit);
  185316. }
  185317. #endif
  185318. #if defined(PNG_READ_BGR_SUPPORTED)
  185319. /* flip the RGB pixels to BGR (or RGBA to BGRA)
  185320. */
  185321. if (transforms & PNG_TRANSFORM_BGR)
  185322. png_set_bgr(png_ptr);
  185323. #endif
  185324. #if defined(PNG_READ_SWAP_ALPHA_SUPPORTED)
  185325. /* swap the RGBA or GA data to ARGB or AG (or BGRA to ABGR)
  185326. */
  185327. if (transforms & PNG_TRANSFORM_SWAP_ALPHA)
  185328. png_set_swap_alpha(png_ptr);
  185329. #endif
  185330. #if defined(PNG_READ_SWAP_SUPPORTED)
  185331. /* swap bytes of 16 bit files to least significant byte first
  185332. */
  185333. if (transforms & PNG_TRANSFORM_SWAP_ENDIAN)
  185334. png_set_swap(png_ptr);
  185335. #endif
  185336. /* We don't handle adding filler bytes */
  185337. /* Optional call to gamma correct and add the background to the palette
  185338. * and update info structure. REQUIRED if you are expecting libpng to
  185339. * update the palette for you (i.e., you selected such a transform above).
  185340. */
  185341. png_read_update_info(png_ptr, info_ptr);
  185342. /* -------------- image transformations end here ------------------- */
  185343. #ifdef PNG_FREE_ME_SUPPORTED
  185344. png_free_data(png_ptr, info_ptr, PNG_FREE_ROWS, 0);
  185345. #endif
  185346. if(info_ptr->row_pointers == NULL)
  185347. {
  185348. info_ptr->row_pointers = (png_bytepp)png_malloc(png_ptr,
  185349. info_ptr->height * png_sizeof(png_bytep));
  185350. #ifdef PNG_FREE_ME_SUPPORTED
  185351. info_ptr->free_me |= PNG_FREE_ROWS;
  185352. #endif
  185353. for (row = 0; row < (int)info_ptr->height; row++)
  185354. {
  185355. info_ptr->row_pointers[row] = (png_bytep)png_malloc(png_ptr,
  185356. png_get_rowbytes(png_ptr, info_ptr));
  185357. }
  185358. }
  185359. png_read_image(png_ptr, info_ptr->row_pointers);
  185360. info_ptr->valid |= PNG_INFO_IDAT;
  185361. /* read rest of file, and get additional chunks in info_ptr - REQUIRED */
  185362. png_read_end(png_ptr, info_ptr);
  185363. transforms = transforms; /* quiet compiler warnings */
  185364. params = params;
  185365. }
  185366. #endif /* PNG_INFO_IMAGE_SUPPORTED */
  185367. #endif /* PNG_NO_SEQUENTIAL_READ_SUPPORTED */
  185368. #endif /* PNG_READ_SUPPORTED */
  185369. /*** End of inlined file: pngread.c ***/
  185370. /*** Start of inlined file: pngpread.c ***/
  185371. /* pngpread.c - read a png file in push mode
  185372. *
  185373. * Last changed in libpng 1.2.21 October 4, 2007
  185374. * For conditions of distribution and use, see copyright notice in png.h
  185375. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  185376. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  185377. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  185378. */
  185379. #define PNG_INTERNAL
  185380. #ifdef PNG_PROGRESSIVE_READ_SUPPORTED
  185381. /* push model modes */
  185382. #define PNG_READ_SIG_MODE 0
  185383. #define PNG_READ_CHUNK_MODE 1
  185384. #define PNG_READ_IDAT_MODE 2
  185385. #define PNG_SKIP_MODE 3
  185386. #define PNG_READ_tEXt_MODE 4
  185387. #define PNG_READ_zTXt_MODE 5
  185388. #define PNG_READ_DONE_MODE 6
  185389. #define PNG_READ_iTXt_MODE 7
  185390. #define PNG_ERROR_MODE 8
  185391. void PNGAPI
  185392. png_process_data(png_structp png_ptr, png_infop info_ptr,
  185393. png_bytep buffer, png_size_t buffer_size)
  185394. {
  185395. if(png_ptr == NULL) return;
  185396. png_push_restore_buffer(png_ptr, buffer, buffer_size);
  185397. while (png_ptr->buffer_size)
  185398. {
  185399. png_process_some_data(png_ptr, info_ptr);
  185400. }
  185401. }
  185402. /* What we do with the incoming data depends on what we were previously
  185403. * doing before we ran out of data...
  185404. */
  185405. void /* PRIVATE */
  185406. png_process_some_data(png_structp png_ptr, png_infop info_ptr)
  185407. {
  185408. if(png_ptr == NULL) return;
  185409. switch (png_ptr->process_mode)
  185410. {
  185411. case PNG_READ_SIG_MODE:
  185412. {
  185413. png_push_read_sig(png_ptr, info_ptr);
  185414. break;
  185415. }
  185416. case PNG_READ_CHUNK_MODE:
  185417. {
  185418. png_push_read_chunk(png_ptr, info_ptr);
  185419. break;
  185420. }
  185421. case PNG_READ_IDAT_MODE:
  185422. {
  185423. png_push_read_IDAT(png_ptr);
  185424. break;
  185425. }
  185426. #if defined(PNG_READ_tEXt_SUPPORTED)
  185427. case PNG_READ_tEXt_MODE:
  185428. {
  185429. png_push_read_tEXt(png_ptr, info_ptr);
  185430. break;
  185431. }
  185432. #endif
  185433. #if defined(PNG_READ_zTXt_SUPPORTED)
  185434. case PNG_READ_zTXt_MODE:
  185435. {
  185436. png_push_read_zTXt(png_ptr, info_ptr);
  185437. break;
  185438. }
  185439. #endif
  185440. #if defined(PNG_READ_iTXt_SUPPORTED)
  185441. case PNG_READ_iTXt_MODE:
  185442. {
  185443. png_push_read_iTXt(png_ptr, info_ptr);
  185444. break;
  185445. }
  185446. #endif
  185447. case PNG_SKIP_MODE:
  185448. {
  185449. png_push_crc_finish(png_ptr);
  185450. break;
  185451. }
  185452. default:
  185453. {
  185454. png_ptr->buffer_size = 0;
  185455. break;
  185456. }
  185457. }
  185458. }
  185459. /* Read any remaining signature bytes from the stream and compare them with
  185460. * the correct PNG signature. It is possible that this routine is called
  185461. * with bytes already read from the signature, either because they have been
  185462. * checked by the calling application, or because of multiple calls to this
  185463. * routine.
  185464. */
  185465. void /* PRIVATE */
  185466. png_push_read_sig(png_structp png_ptr, png_infop info_ptr)
  185467. {
  185468. png_size_t num_checked = png_ptr->sig_bytes,
  185469. num_to_check = 8 - num_checked;
  185470. if (png_ptr->buffer_size < num_to_check)
  185471. {
  185472. num_to_check = png_ptr->buffer_size;
  185473. }
  185474. png_push_fill_buffer(png_ptr, &(info_ptr->signature[num_checked]),
  185475. num_to_check);
  185476. png_ptr->sig_bytes = (png_byte)(png_ptr->sig_bytes+num_to_check);
  185477. if (png_sig_cmp(info_ptr->signature, num_checked, num_to_check))
  185478. {
  185479. if (num_checked < 4 &&
  185480. png_sig_cmp(info_ptr->signature, num_checked, num_to_check - 4))
  185481. png_error(png_ptr, "Not a PNG file");
  185482. else
  185483. png_error(png_ptr, "PNG file corrupted by ASCII conversion");
  185484. }
  185485. else
  185486. {
  185487. if (png_ptr->sig_bytes >= 8)
  185488. {
  185489. png_ptr->process_mode = PNG_READ_CHUNK_MODE;
  185490. }
  185491. }
  185492. }
  185493. void /* PRIVATE */
  185494. png_push_read_chunk(png_structp png_ptr, png_infop info_ptr)
  185495. {
  185496. #ifdef PNG_USE_LOCAL_ARRAYS
  185497. PNG_CONST PNG_IHDR;
  185498. PNG_CONST PNG_IDAT;
  185499. PNG_CONST PNG_IEND;
  185500. PNG_CONST PNG_PLTE;
  185501. #if defined(PNG_READ_bKGD_SUPPORTED)
  185502. PNG_CONST PNG_bKGD;
  185503. #endif
  185504. #if defined(PNG_READ_cHRM_SUPPORTED)
  185505. PNG_CONST PNG_cHRM;
  185506. #endif
  185507. #if defined(PNG_READ_gAMA_SUPPORTED)
  185508. PNG_CONST PNG_gAMA;
  185509. #endif
  185510. #if defined(PNG_READ_hIST_SUPPORTED)
  185511. PNG_CONST PNG_hIST;
  185512. #endif
  185513. #if defined(PNG_READ_iCCP_SUPPORTED)
  185514. PNG_CONST PNG_iCCP;
  185515. #endif
  185516. #if defined(PNG_READ_iTXt_SUPPORTED)
  185517. PNG_CONST PNG_iTXt;
  185518. #endif
  185519. #if defined(PNG_READ_oFFs_SUPPORTED)
  185520. PNG_CONST PNG_oFFs;
  185521. #endif
  185522. #if defined(PNG_READ_pCAL_SUPPORTED)
  185523. PNG_CONST PNG_pCAL;
  185524. #endif
  185525. #if defined(PNG_READ_pHYs_SUPPORTED)
  185526. PNG_CONST PNG_pHYs;
  185527. #endif
  185528. #if defined(PNG_READ_sBIT_SUPPORTED)
  185529. PNG_CONST PNG_sBIT;
  185530. #endif
  185531. #if defined(PNG_READ_sCAL_SUPPORTED)
  185532. PNG_CONST PNG_sCAL;
  185533. #endif
  185534. #if defined(PNG_READ_sRGB_SUPPORTED)
  185535. PNG_CONST PNG_sRGB;
  185536. #endif
  185537. #if defined(PNG_READ_sPLT_SUPPORTED)
  185538. PNG_CONST PNG_sPLT;
  185539. #endif
  185540. #if defined(PNG_READ_tEXt_SUPPORTED)
  185541. PNG_CONST PNG_tEXt;
  185542. #endif
  185543. #if defined(PNG_READ_tIME_SUPPORTED)
  185544. PNG_CONST PNG_tIME;
  185545. #endif
  185546. #if defined(PNG_READ_tRNS_SUPPORTED)
  185547. PNG_CONST PNG_tRNS;
  185548. #endif
  185549. #if defined(PNG_READ_zTXt_SUPPORTED)
  185550. PNG_CONST PNG_zTXt;
  185551. #endif
  185552. #endif /* PNG_USE_LOCAL_ARRAYS */
  185553. /* First we make sure we have enough data for the 4 byte chunk name
  185554. * and the 4 byte chunk length before proceeding with decoding the
  185555. * chunk data. To fully decode each of these chunks, we also make
  185556. * sure we have enough data in the buffer for the 4 byte CRC at the
  185557. * end of every chunk (except IDAT, which is handled separately).
  185558. */
  185559. if (!(png_ptr->mode & PNG_HAVE_CHUNK_HEADER))
  185560. {
  185561. png_byte chunk_length[4];
  185562. if (png_ptr->buffer_size < 8)
  185563. {
  185564. png_push_save_buffer(png_ptr);
  185565. return;
  185566. }
  185567. png_push_fill_buffer(png_ptr, chunk_length, 4);
  185568. png_ptr->push_length = png_get_uint_31(png_ptr,chunk_length);
  185569. png_reset_crc(png_ptr);
  185570. png_crc_read(png_ptr, png_ptr->chunk_name, 4);
  185571. png_ptr->mode |= PNG_HAVE_CHUNK_HEADER;
  185572. }
  185573. if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  185574. if(png_ptr->mode & PNG_AFTER_IDAT)
  185575. png_ptr->mode |= PNG_HAVE_CHUNK_AFTER_IDAT;
  185576. if (!png_memcmp(png_ptr->chunk_name, png_IHDR, 4))
  185577. {
  185578. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  185579. {
  185580. png_push_save_buffer(png_ptr);
  185581. return;
  185582. }
  185583. png_handle_IHDR(png_ptr, info_ptr, png_ptr->push_length);
  185584. }
  185585. else if (!png_memcmp(png_ptr->chunk_name, png_IEND, 4))
  185586. {
  185587. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  185588. {
  185589. png_push_save_buffer(png_ptr);
  185590. return;
  185591. }
  185592. png_handle_IEND(png_ptr, info_ptr, png_ptr->push_length);
  185593. png_ptr->process_mode = PNG_READ_DONE_MODE;
  185594. png_push_have_end(png_ptr, info_ptr);
  185595. }
  185596. #ifdef PNG_HANDLE_AS_UNKNOWN_SUPPORTED
  185597. else if (png_handle_as_unknown(png_ptr, png_ptr->chunk_name))
  185598. {
  185599. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  185600. {
  185601. png_push_save_buffer(png_ptr);
  185602. return;
  185603. }
  185604. if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  185605. png_ptr->mode |= PNG_HAVE_IDAT;
  185606. png_handle_unknown(png_ptr, info_ptr, png_ptr->push_length);
  185607. if (!png_memcmp(png_ptr->chunk_name, png_PLTE, 4))
  185608. png_ptr->mode |= PNG_HAVE_PLTE;
  185609. else if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  185610. {
  185611. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  185612. png_error(png_ptr, "Missing IHDR before IDAT");
  185613. else if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE &&
  185614. !(png_ptr->mode & PNG_HAVE_PLTE))
  185615. png_error(png_ptr, "Missing PLTE before IDAT");
  185616. }
  185617. }
  185618. #endif
  185619. else if (!png_memcmp(png_ptr->chunk_name, png_PLTE, 4))
  185620. {
  185621. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  185622. {
  185623. png_push_save_buffer(png_ptr);
  185624. return;
  185625. }
  185626. png_handle_PLTE(png_ptr, info_ptr, png_ptr->push_length);
  185627. }
  185628. else if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  185629. {
  185630. /* If we reach an IDAT chunk, this means we have read all of the
  185631. * header chunks, and we can start reading the image (or if this
  185632. * is called after the image has been read - we have an error).
  185633. */
  185634. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  185635. png_error(png_ptr, "Missing IHDR before IDAT");
  185636. else if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE &&
  185637. !(png_ptr->mode & PNG_HAVE_PLTE))
  185638. png_error(png_ptr, "Missing PLTE before IDAT");
  185639. if (png_ptr->mode & PNG_HAVE_IDAT)
  185640. {
  185641. if (!(png_ptr->mode & PNG_HAVE_CHUNK_AFTER_IDAT))
  185642. if (png_ptr->push_length == 0)
  185643. return;
  185644. if (png_ptr->mode & PNG_AFTER_IDAT)
  185645. png_error(png_ptr, "Too many IDAT's found");
  185646. }
  185647. png_ptr->idat_size = png_ptr->push_length;
  185648. png_ptr->mode |= PNG_HAVE_IDAT;
  185649. png_ptr->process_mode = PNG_READ_IDAT_MODE;
  185650. png_push_have_info(png_ptr, info_ptr);
  185651. png_ptr->zstream.avail_out = (uInt)png_ptr->irowbytes;
  185652. png_ptr->zstream.next_out = png_ptr->row_buf;
  185653. return;
  185654. }
  185655. #if defined(PNG_READ_gAMA_SUPPORTED)
  185656. else if (!png_memcmp(png_ptr->chunk_name, png_gAMA, 4))
  185657. {
  185658. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  185659. {
  185660. png_push_save_buffer(png_ptr);
  185661. return;
  185662. }
  185663. png_handle_gAMA(png_ptr, info_ptr, png_ptr->push_length);
  185664. }
  185665. #endif
  185666. #if defined(PNG_READ_sBIT_SUPPORTED)
  185667. else if (!png_memcmp(png_ptr->chunk_name, png_sBIT, 4))
  185668. {
  185669. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  185670. {
  185671. png_push_save_buffer(png_ptr);
  185672. return;
  185673. }
  185674. png_handle_sBIT(png_ptr, info_ptr, png_ptr->push_length);
  185675. }
  185676. #endif
  185677. #if defined(PNG_READ_cHRM_SUPPORTED)
  185678. else if (!png_memcmp(png_ptr->chunk_name, png_cHRM, 4))
  185679. {
  185680. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  185681. {
  185682. png_push_save_buffer(png_ptr);
  185683. return;
  185684. }
  185685. png_handle_cHRM(png_ptr, info_ptr, png_ptr->push_length);
  185686. }
  185687. #endif
  185688. #if defined(PNG_READ_sRGB_SUPPORTED)
  185689. else if (!png_memcmp(png_ptr->chunk_name, png_sRGB, 4))
  185690. {
  185691. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  185692. {
  185693. png_push_save_buffer(png_ptr);
  185694. return;
  185695. }
  185696. png_handle_sRGB(png_ptr, info_ptr, png_ptr->push_length);
  185697. }
  185698. #endif
  185699. #if defined(PNG_READ_iCCP_SUPPORTED)
  185700. else if (!png_memcmp(png_ptr->chunk_name, png_iCCP, 4))
  185701. {
  185702. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  185703. {
  185704. png_push_save_buffer(png_ptr);
  185705. return;
  185706. }
  185707. png_handle_iCCP(png_ptr, info_ptr, png_ptr->push_length);
  185708. }
  185709. #endif
  185710. #if defined(PNG_READ_sPLT_SUPPORTED)
  185711. else if (!png_memcmp(png_ptr->chunk_name, png_sPLT, 4))
  185712. {
  185713. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  185714. {
  185715. png_push_save_buffer(png_ptr);
  185716. return;
  185717. }
  185718. png_handle_sPLT(png_ptr, info_ptr, png_ptr->push_length);
  185719. }
  185720. #endif
  185721. #if defined(PNG_READ_tRNS_SUPPORTED)
  185722. else if (!png_memcmp(png_ptr->chunk_name, png_tRNS, 4))
  185723. {
  185724. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  185725. {
  185726. png_push_save_buffer(png_ptr);
  185727. return;
  185728. }
  185729. png_handle_tRNS(png_ptr, info_ptr, png_ptr->push_length);
  185730. }
  185731. #endif
  185732. #if defined(PNG_READ_bKGD_SUPPORTED)
  185733. else if (!png_memcmp(png_ptr->chunk_name, png_bKGD, 4))
  185734. {
  185735. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  185736. {
  185737. png_push_save_buffer(png_ptr);
  185738. return;
  185739. }
  185740. png_handle_bKGD(png_ptr, info_ptr, png_ptr->push_length);
  185741. }
  185742. #endif
  185743. #if defined(PNG_READ_hIST_SUPPORTED)
  185744. else if (!png_memcmp(png_ptr->chunk_name, png_hIST, 4))
  185745. {
  185746. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  185747. {
  185748. png_push_save_buffer(png_ptr);
  185749. return;
  185750. }
  185751. png_handle_hIST(png_ptr, info_ptr, png_ptr->push_length);
  185752. }
  185753. #endif
  185754. #if defined(PNG_READ_pHYs_SUPPORTED)
  185755. else if (!png_memcmp(png_ptr->chunk_name, png_pHYs, 4))
  185756. {
  185757. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  185758. {
  185759. png_push_save_buffer(png_ptr);
  185760. return;
  185761. }
  185762. png_handle_pHYs(png_ptr, info_ptr, png_ptr->push_length);
  185763. }
  185764. #endif
  185765. #if defined(PNG_READ_oFFs_SUPPORTED)
  185766. else if (!png_memcmp(png_ptr->chunk_name, png_oFFs, 4))
  185767. {
  185768. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  185769. {
  185770. png_push_save_buffer(png_ptr);
  185771. return;
  185772. }
  185773. png_handle_oFFs(png_ptr, info_ptr, png_ptr->push_length);
  185774. }
  185775. #endif
  185776. #if defined(PNG_READ_pCAL_SUPPORTED)
  185777. else if (!png_memcmp(png_ptr->chunk_name, png_pCAL, 4))
  185778. {
  185779. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  185780. {
  185781. png_push_save_buffer(png_ptr);
  185782. return;
  185783. }
  185784. png_handle_pCAL(png_ptr, info_ptr, png_ptr->push_length);
  185785. }
  185786. #endif
  185787. #if defined(PNG_READ_sCAL_SUPPORTED)
  185788. else if (!png_memcmp(png_ptr->chunk_name, png_sCAL, 4))
  185789. {
  185790. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  185791. {
  185792. png_push_save_buffer(png_ptr);
  185793. return;
  185794. }
  185795. png_handle_sCAL(png_ptr, info_ptr, png_ptr->push_length);
  185796. }
  185797. #endif
  185798. #if defined(PNG_READ_tIME_SUPPORTED)
  185799. else if (!png_memcmp(png_ptr->chunk_name, png_tIME, 4))
  185800. {
  185801. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  185802. {
  185803. png_push_save_buffer(png_ptr);
  185804. return;
  185805. }
  185806. png_handle_tIME(png_ptr, info_ptr, png_ptr->push_length);
  185807. }
  185808. #endif
  185809. #if defined(PNG_READ_tEXt_SUPPORTED)
  185810. else if (!png_memcmp(png_ptr->chunk_name, png_tEXt, 4))
  185811. {
  185812. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  185813. {
  185814. png_push_save_buffer(png_ptr);
  185815. return;
  185816. }
  185817. png_push_handle_tEXt(png_ptr, info_ptr, png_ptr->push_length);
  185818. }
  185819. #endif
  185820. #if defined(PNG_READ_zTXt_SUPPORTED)
  185821. else if (!png_memcmp(png_ptr->chunk_name, png_zTXt, 4))
  185822. {
  185823. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  185824. {
  185825. png_push_save_buffer(png_ptr);
  185826. return;
  185827. }
  185828. png_push_handle_zTXt(png_ptr, info_ptr, png_ptr->push_length);
  185829. }
  185830. #endif
  185831. #if defined(PNG_READ_iTXt_SUPPORTED)
  185832. else if (!png_memcmp(png_ptr->chunk_name, png_iTXt, 4))
  185833. {
  185834. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  185835. {
  185836. png_push_save_buffer(png_ptr);
  185837. return;
  185838. }
  185839. png_push_handle_iTXt(png_ptr, info_ptr, png_ptr->push_length);
  185840. }
  185841. #endif
  185842. else
  185843. {
  185844. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  185845. {
  185846. png_push_save_buffer(png_ptr);
  185847. return;
  185848. }
  185849. png_push_handle_unknown(png_ptr, info_ptr, png_ptr->push_length);
  185850. }
  185851. png_ptr->mode &= ~PNG_HAVE_CHUNK_HEADER;
  185852. }
  185853. void /* PRIVATE */
  185854. png_push_crc_skip(png_structp png_ptr, png_uint_32 skip)
  185855. {
  185856. png_ptr->process_mode = PNG_SKIP_MODE;
  185857. png_ptr->skip_length = skip;
  185858. }
  185859. void /* PRIVATE */
  185860. png_push_crc_finish(png_structp png_ptr)
  185861. {
  185862. if (png_ptr->skip_length && png_ptr->save_buffer_size)
  185863. {
  185864. png_size_t save_size;
  185865. if (png_ptr->skip_length < (png_uint_32)png_ptr->save_buffer_size)
  185866. save_size = (png_size_t)png_ptr->skip_length;
  185867. else
  185868. save_size = png_ptr->save_buffer_size;
  185869. png_calculate_crc(png_ptr, png_ptr->save_buffer_ptr, save_size);
  185870. png_ptr->skip_length -= save_size;
  185871. png_ptr->buffer_size -= save_size;
  185872. png_ptr->save_buffer_size -= save_size;
  185873. png_ptr->save_buffer_ptr += save_size;
  185874. }
  185875. if (png_ptr->skip_length && png_ptr->current_buffer_size)
  185876. {
  185877. png_size_t save_size;
  185878. if (png_ptr->skip_length < (png_uint_32)png_ptr->current_buffer_size)
  185879. save_size = (png_size_t)png_ptr->skip_length;
  185880. else
  185881. save_size = png_ptr->current_buffer_size;
  185882. png_calculate_crc(png_ptr, png_ptr->current_buffer_ptr, save_size);
  185883. png_ptr->skip_length -= save_size;
  185884. png_ptr->buffer_size -= save_size;
  185885. png_ptr->current_buffer_size -= save_size;
  185886. png_ptr->current_buffer_ptr += save_size;
  185887. }
  185888. if (!png_ptr->skip_length)
  185889. {
  185890. if (png_ptr->buffer_size < 4)
  185891. {
  185892. png_push_save_buffer(png_ptr);
  185893. return;
  185894. }
  185895. png_crc_finish(png_ptr, 0);
  185896. png_ptr->process_mode = PNG_READ_CHUNK_MODE;
  185897. }
  185898. }
  185899. void PNGAPI
  185900. png_push_fill_buffer(png_structp png_ptr, png_bytep buffer, png_size_t length)
  185901. {
  185902. png_bytep ptr;
  185903. if(png_ptr == NULL) return;
  185904. ptr = buffer;
  185905. if (png_ptr->save_buffer_size)
  185906. {
  185907. png_size_t save_size;
  185908. if (length < png_ptr->save_buffer_size)
  185909. save_size = length;
  185910. else
  185911. save_size = png_ptr->save_buffer_size;
  185912. png_memcpy(ptr, png_ptr->save_buffer_ptr, save_size);
  185913. length -= save_size;
  185914. ptr += save_size;
  185915. png_ptr->buffer_size -= save_size;
  185916. png_ptr->save_buffer_size -= save_size;
  185917. png_ptr->save_buffer_ptr += save_size;
  185918. }
  185919. if (length && png_ptr->current_buffer_size)
  185920. {
  185921. png_size_t save_size;
  185922. if (length < png_ptr->current_buffer_size)
  185923. save_size = length;
  185924. else
  185925. save_size = png_ptr->current_buffer_size;
  185926. png_memcpy(ptr, png_ptr->current_buffer_ptr, save_size);
  185927. png_ptr->buffer_size -= save_size;
  185928. png_ptr->current_buffer_size -= save_size;
  185929. png_ptr->current_buffer_ptr += save_size;
  185930. }
  185931. }
  185932. void /* PRIVATE */
  185933. png_push_save_buffer(png_structp png_ptr)
  185934. {
  185935. if (png_ptr->save_buffer_size)
  185936. {
  185937. if (png_ptr->save_buffer_ptr != png_ptr->save_buffer)
  185938. {
  185939. png_size_t i,istop;
  185940. png_bytep sp;
  185941. png_bytep dp;
  185942. istop = png_ptr->save_buffer_size;
  185943. for (i = 0, sp = png_ptr->save_buffer_ptr, dp = png_ptr->save_buffer;
  185944. i < istop; i++, sp++, dp++)
  185945. {
  185946. *dp = *sp;
  185947. }
  185948. }
  185949. }
  185950. if (png_ptr->save_buffer_size + png_ptr->current_buffer_size >
  185951. png_ptr->save_buffer_max)
  185952. {
  185953. png_size_t new_max;
  185954. png_bytep old_buffer;
  185955. if (png_ptr->save_buffer_size > PNG_SIZE_MAX -
  185956. (png_ptr->current_buffer_size + 256))
  185957. {
  185958. png_error(png_ptr, "Potential overflow of save_buffer");
  185959. }
  185960. new_max = png_ptr->save_buffer_size + png_ptr->current_buffer_size + 256;
  185961. old_buffer = png_ptr->save_buffer;
  185962. png_ptr->save_buffer = (png_bytep)png_malloc(png_ptr,
  185963. (png_uint_32)new_max);
  185964. png_memcpy(png_ptr->save_buffer, old_buffer, png_ptr->save_buffer_size);
  185965. png_free(png_ptr, old_buffer);
  185966. png_ptr->save_buffer_max = new_max;
  185967. }
  185968. if (png_ptr->current_buffer_size)
  185969. {
  185970. png_memcpy(png_ptr->save_buffer + png_ptr->save_buffer_size,
  185971. png_ptr->current_buffer_ptr, png_ptr->current_buffer_size);
  185972. png_ptr->save_buffer_size += png_ptr->current_buffer_size;
  185973. png_ptr->current_buffer_size = 0;
  185974. }
  185975. png_ptr->save_buffer_ptr = png_ptr->save_buffer;
  185976. png_ptr->buffer_size = 0;
  185977. }
  185978. void /* PRIVATE */
  185979. png_push_restore_buffer(png_structp png_ptr, png_bytep buffer,
  185980. png_size_t buffer_length)
  185981. {
  185982. png_ptr->current_buffer = buffer;
  185983. png_ptr->current_buffer_size = buffer_length;
  185984. png_ptr->buffer_size = buffer_length + png_ptr->save_buffer_size;
  185985. png_ptr->current_buffer_ptr = png_ptr->current_buffer;
  185986. }
  185987. void /* PRIVATE */
  185988. png_push_read_IDAT(png_structp png_ptr)
  185989. {
  185990. #ifdef PNG_USE_LOCAL_ARRAYS
  185991. PNG_CONST PNG_IDAT;
  185992. #endif
  185993. if (!(png_ptr->mode & PNG_HAVE_CHUNK_HEADER))
  185994. {
  185995. png_byte chunk_length[4];
  185996. if (png_ptr->buffer_size < 8)
  185997. {
  185998. png_push_save_buffer(png_ptr);
  185999. return;
  186000. }
  186001. png_push_fill_buffer(png_ptr, chunk_length, 4);
  186002. png_ptr->push_length = png_get_uint_31(png_ptr,chunk_length);
  186003. png_reset_crc(png_ptr);
  186004. png_crc_read(png_ptr, png_ptr->chunk_name, 4);
  186005. png_ptr->mode |= PNG_HAVE_CHUNK_HEADER;
  186006. if (png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  186007. {
  186008. png_ptr->process_mode = PNG_READ_CHUNK_MODE;
  186009. if (!(png_ptr->flags & PNG_FLAG_ZLIB_FINISHED))
  186010. png_error(png_ptr, "Not enough compressed data");
  186011. return;
  186012. }
  186013. png_ptr->idat_size = png_ptr->push_length;
  186014. }
  186015. if (png_ptr->idat_size && png_ptr->save_buffer_size)
  186016. {
  186017. png_size_t save_size;
  186018. if (png_ptr->idat_size < (png_uint_32)png_ptr->save_buffer_size)
  186019. {
  186020. save_size = (png_size_t)png_ptr->idat_size;
  186021. /* check for overflow */
  186022. if((png_uint_32)save_size != png_ptr->idat_size)
  186023. png_error(png_ptr, "save_size overflowed in pngpread");
  186024. }
  186025. else
  186026. save_size = png_ptr->save_buffer_size;
  186027. png_calculate_crc(png_ptr, png_ptr->save_buffer_ptr, save_size);
  186028. if (!(png_ptr->flags & PNG_FLAG_ZLIB_FINISHED))
  186029. png_process_IDAT_data(png_ptr, png_ptr->save_buffer_ptr, save_size);
  186030. png_ptr->idat_size -= save_size;
  186031. png_ptr->buffer_size -= save_size;
  186032. png_ptr->save_buffer_size -= save_size;
  186033. png_ptr->save_buffer_ptr += save_size;
  186034. }
  186035. if (png_ptr->idat_size && png_ptr->current_buffer_size)
  186036. {
  186037. png_size_t save_size;
  186038. if (png_ptr->idat_size < (png_uint_32)png_ptr->current_buffer_size)
  186039. {
  186040. save_size = (png_size_t)png_ptr->idat_size;
  186041. /* check for overflow */
  186042. if((png_uint_32)save_size != png_ptr->idat_size)
  186043. png_error(png_ptr, "save_size overflowed in pngpread");
  186044. }
  186045. else
  186046. save_size = png_ptr->current_buffer_size;
  186047. png_calculate_crc(png_ptr, png_ptr->current_buffer_ptr, save_size);
  186048. if (!(png_ptr->flags & PNG_FLAG_ZLIB_FINISHED))
  186049. png_process_IDAT_data(png_ptr, png_ptr->current_buffer_ptr, save_size);
  186050. png_ptr->idat_size -= save_size;
  186051. png_ptr->buffer_size -= save_size;
  186052. png_ptr->current_buffer_size -= save_size;
  186053. png_ptr->current_buffer_ptr += save_size;
  186054. }
  186055. if (!png_ptr->idat_size)
  186056. {
  186057. if (png_ptr->buffer_size < 4)
  186058. {
  186059. png_push_save_buffer(png_ptr);
  186060. return;
  186061. }
  186062. png_crc_finish(png_ptr, 0);
  186063. png_ptr->mode &= ~PNG_HAVE_CHUNK_HEADER;
  186064. png_ptr->mode |= PNG_AFTER_IDAT;
  186065. }
  186066. }
  186067. void /* PRIVATE */
  186068. png_process_IDAT_data(png_structp png_ptr, png_bytep buffer,
  186069. png_size_t buffer_length)
  186070. {
  186071. int ret;
  186072. if ((png_ptr->flags & PNG_FLAG_ZLIB_FINISHED) && buffer_length)
  186073. png_error(png_ptr, "Extra compression data");
  186074. png_ptr->zstream.next_in = buffer;
  186075. png_ptr->zstream.avail_in = (uInt)buffer_length;
  186076. for(;;)
  186077. {
  186078. ret = inflate(&png_ptr->zstream, Z_PARTIAL_FLUSH);
  186079. if (ret != Z_OK)
  186080. {
  186081. if (ret == Z_STREAM_END)
  186082. {
  186083. if (png_ptr->zstream.avail_in)
  186084. png_error(png_ptr, "Extra compressed data");
  186085. if (!(png_ptr->zstream.avail_out))
  186086. {
  186087. png_push_process_row(png_ptr);
  186088. }
  186089. png_ptr->mode |= PNG_AFTER_IDAT;
  186090. png_ptr->flags |= PNG_FLAG_ZLIB_FINISHED;
  186091. break;
  186092. }
  186093. else if (ret == Z_BUF_ERROR)
  186094. break;
  186095. else
  186096. png_error(png_ptr, "Decompression Error");
  186097. }
  186098. if (!(png_ptr->zstream.avail_out))
  186099. {
  186100. if ((
  186101. #if defined(PNG_READ_INTERLACING_SUPPORTED)
  186102. png_ptr->interlaced && png_ptr->pass > 6) ||
  186103. (!png_ptr->interlaced &&
  186104. #endif
  186105. png_ptr->row_number == png_ptr->num_rows))
  186106. {
  186107. if (png_ptr->zstream.avail_in)
  186108. {
  186109. png_warning(png_ptr, "Too much data in IDAT chunks");
  186110. }
  186111. png_ptr->flags |= PNG_FLAG_ZLIB_FINISHED;
  186112. break;
  186113. }
  186114. png_push_process_row(png_ptr);
  186115. png_ptr->zstream.avail_out = (uInt)png_ptr->irowbytes;
  186116. png_ptr->zstream.next_out = png_ptr->row_buf;
  186117. }
  186118. else
  186119. break;
  186120. }
  186121. }
  186122. void /* PRIVATE */
  186123. png_push_process_row(png_structp png_ptr)
  186124. {
  186125. png_ptr->row_info.color_type = png_ptr->color_type;
  186126. png_ptr->row_info.width = png_ptr->iwidth;
  186127. png_ptr->row_info.channels = png_ptr->channels;
  186128. png_ptr->row_info.bit_depth = png_ptr->bit_depth;
  186129. png_ptr->row_info.pixel_depth = png_ptr->pixel_depth;
  186130. png_ptr->row_info.rowbytes = PNG_ROWBYTES(png_ptr->row_info.pixel_depth,
  186131. png_ptr->row_info.width);
  186132. png_read_filter_row(png_ptr, &(png_ptr->row_info),
  186133. png_ptr->row_buf + 1, png_ptr->prev_row + 1,
  186134. (int)(png_ptr->row_buf[0]));
  186135. png_memcpy_check(png_ptr, png_ptr->prev_row, png_ptr->row_buf,
  186136. png_ptr->rowbytes + 1);
  186137. if (png_ptr->transformations || (png_ptr->flags&PNG_FLAG_STRIP_ALPHA))
  186138. png_do_read_transformations(png_ptr);
  186139. #if defined(PNG_READ_INTERLACING_SUPPORTED)
  186140. /* blow up interlaced rows to full size */
  186141. if (png_ptr->interlaced && (png_ptr->transformations & PNG_INTERLACE))
  186142. {
  186143. if (png_ptr->pass < 6)
  186144. /* old interface (pre-1.0.9):
  186145. png_do_read_interlace(&(png_ptr->row_info),
  186146. png_ptr->row_buf + 1, png_ptr->pass, png_ptr->transformations);
  186147. */
  186148. png_do_read_interlace(png_ptr);
  186149. switch (png_ptr->pass)
  186150. {
  186151. case 0:
  186152. {
  186153. int i;
  186154. for (i = 0; i < 8 && png_ptr->pass == 0; i++)
  186155. {
  186156. png_push_have_row(png_ptr, png_ptr->row_buf + 1);
  186157. png_read_push_finish_row(png_ptr); /* updates png_ptr->pass */
  186158. }
  186159. if (png_ptr->pass == 2) /* pass 1 might be empty */
  186160. {
  186161. for (i = 0; i < 4 && png_ptr->pass == 2; i++)
  186162. {
  186163. png_push_have_row(png_ptr, png_bytep_NULL);
  186164. png_read_push_finish_row(png_ptr);
  186165. }
  186166. }
  186167. if (png_ptr->pass == 4 && png_ptr->height <= 4)
  186168. {
  186169. for (i = 0; i < 2 && png_ptr->pass == 4; i++)
  186170. {
  186171. png_push_have_row(png_ptr, png_bytep_NULL);
  186172. png_read_push_finish_row(png_ptr);
  186173. }
  186174. }
  186175. if (png_ptr->pass == 6 && png_ptr->height <= 4)
  186176. {
  186177. png_push_have_row(png_ptr, png_bytep_NULL);
  186178. png_read_push_finish_row(png_ptr);
  186179. }
  186180. break;
  186181. }
  186182. case 1:
  186183. {
  186184. int i;
  186185. for (i = 0; i < 8 && png_ptr->pass == 1; i++)
  186186. {
  186187. png_push_have_row(png_ptr, png_ptr->row_buf + 1);
  186188. png_read_push_finish_row(png_ptr);
  186189. }
  186190. if (png_ptr->pass == 2) /* skip top 4 generated rows */
  186191. {
  186192. for (i = 0; i < 4 && png_ptr->pass == 2; i++)
  186193. {
  186194. png_push_have_row(png_ptr, png_bytep_NULL);
  186195. png_read_push_finish_row(png_ptr);
  186196. }
  186197. }
  186198. break;
  186199. }
  186200. case 2:
  186201. {
  186202. int i;
  186203. for (i = 0; i < 4 && png_ptr->pass == 2; i++)
  186204. {
  186205. png_push_have_row(png_ptr, png_ptr->row_buf + 1);
  186206. png_read_push_finish_row(png_ptr);
  186207. }
  186208. for (i = 0; i < 4 && png_ptr->pass == 2; i++)
  186209. {
  186210. png_push_have_row(png_ptr, png_bytep_NULL);
  186211. png_read_push_finish_row(png_ptr);
  186212. }
  186213. if (png_ptr->pass == 4) /* pass 3 might be empty */
  186214. {
  186215. for (i = 0; i < 2 && png_ptr->pass == 4; i++)
  186216. {
  186217. png_push_have_row(png_ptr, png_bytep_NULL);
  186218. png_read_push_finish_row(png_ptr);
  186219. }
  186220. }
  186221. break;
  186222. }
  186223. case 3:
  186224. {
  186225. int i;
  186226. for (i = 0; i < 4 && png_ptr->pass == 3; i++)
  186227. {
  186228. png_push_have_row(png_ptr, png_ptr->row_buf + 1);
  186229. png_read_push_finish_row(png_ptr);
  186230. }
  186231. if (png_ptr->pass == 4) /* skip top two generated rows */
  186232. {
  186233. for (i = 0; i < 2 && png_ptr->pass == 4; i++)
  186234. {
  186235. png_push_have_row(png_ptr, png_bytep_NULL);
  186236. png_read_push_finish_row(png_ptr);
  186237. }
  186238. }
  186239. break;
  186240. }
  186241. case 4:
  186242. {
  186243. int i;
  186244. for (i = 0; i < 2 && png_ptr->pass == 4; i++)
  186245. {
  186246. png_push_have_row(png_ptr, png_ptr->row_buf + 1);
  186247. png_read_push_finish_row(png_ptr);
  186248. }
  186249. for (i = 0; i < 2 && png_ptr->pass == 4; i++)
  186250. {
  186251. png_push_have_row(png_ptr, png_bytep_NULL);
  186252. png_read_push_finish_row(png_ptr);
  186253. }
  186254. if (png_ptr->pass == 6) /* pass 5 might be empty */
  186255. {
  186256. png_push_have_row(png_ptr, png_bytep_NULL);
  186257. png_read_push_finish_row(png_ptr);
  186258. }
  186259. break;
  186260. }
  186261. case 5:
  186262. {
  186263. int i;
  186264. for (i = 0; i < 2 && png_ptr->pass == 5; i++)
  186265. {
  186266. png_push_have_row(png_ptr, png_ptr->row_buf + 1);
  186267. png_read_push_finish_row(png_ptr);
  186268. }
  186269. if (png_ptr->pass == 6) /* skip top generated row */
  186270. {
  186271. png_push_have_row(png_ptr, png_bytep_NULL);
  186272. png_read_push_finish_row(png_ptr);
  186273. }
  186274. break;
  186275. }
  186276. case 6:
  186277. {
  186278. png_push_have_row(png_ptr, png_ptr->row_buf + 1);
  186279. png_read_push_finish_row(png_ptr);
  186280. if (png_ptr->pass != 6)
  186281. break;
  186282. png_push_have_row(png_ptr, png_bytep_NULL);
  186283. png_read_push_finish_row(png_ptr);
  186284. }
  186285. }
  186286. }
  186287. else
  186288. #endif
  186289. {
  186290. png_push_have_row(png_ptr, png_ptr->row_buf + 1);
  186291. png_read_push_finish_row(png_ptr);
  186292. }
  186293. }
  186294. void /* PRIVATE */
  186295. png_read_push_finish_row(png_structp png_ptr)
  186296. {
  186297. #ifdef PNG_USE_LOCAL_ARRAYS
  186298. /* arrays to facilitate easy interlacing - use pass (0 - 6) as index */
  186299. /* start of interlace block */
  186300. PNG_CONST int FARDATA png_pass_start[] = {0, 4, 0, 2, 0, 1, 0};
  186301. /* offset to next interlace block */
  186302. PNG_CONST int FARDATA png_pass_inc[] = {8, 8, 4, 4, 2, 2, 1};
  186303. /* start of interlace block in the y direction */
  186304. PNG_CONST int FARDATA png_pass_ystart[] = {0, 0, 4, 0, 2, 0, 1};
  186305. /* offset to next interlace block in the y direction */
  186306. PNG_CONST int FARDATA png_pass_yinc[] = {8, 8, 8, 4, 4, 2, 2};
  186307. /* Height of interlace block. This is not currently used - if you need
  186308. * it, uncomment it here and in png.h
  186309. PNG_CONST int FARDATA png_pass_height[] = {8, 8, 4, 4, 2, 2, 1};
  186310. */
  186311. #endif
  186312. png_ptr->row_number++;
  186313. if (png_ptr->row_number < png_ptr->num_rows)
  186314. return;
  186315. if (png_ptr->interlaced)
  186316. {
  186317. png_ptr->row_number = 0;
  186318. png_memset_check(png_ptr, png_ptr->prev_row, 0,
  186319. png_ptr->rowbytes + 1);
  186320. do
  186321. {
  186322. png_ptr->pass++;
  186323. if ((png_ptr->pass == 1 && png_ptr->width < 5) ||
  186324. (png_ptr->pass == 3 && png_ptr->width < 3) ||
  186325. (png_ptr->pass == 5 && png_ptr->width < 2))
  186326. png_ptr->pass++;
  186327. if (png_ptr->pass > 7)
  186328. png_ptr->pass--;
  186329. if (png_ptr->pass >= 7)
  186330. break;
  186331. png_ptr->iwidth = (png_ptr->width +
  186332. png_pass_inc[png_ptr->pass] - 1 -
  186333. png_pass_start[png_ptr->pass]) /
  186334. png_pass_inc[png_ptr->pass];
  186335. png_ptr->irowbytes = PNG_ROWBYTES(png_ptr->pixel_depth,
  186336. png_ptr->iwidth) + 1;
  186337. if (png_ptr->transformations & PNG_INTERLACE)
  186338. break;
  186339. png_ptr->num_rows = (png_ptr->height +
  186340. png_pass_yinc[png_ptr->pass] - 1 -
  186341. png_pass_ystart[png_ptr->pass]) /
  186342. png_pass_yinc[png_ptr->pass];
  186343. } while (png_ptr->iwidth == 0 || png_ptr->num_rows == 0);
  186344. }
  186345. }
  186346. #if defined(PNG_READ_tEXt_SUPPORTED)
  186347. void /* PRIVATE */
  186348. png_push_handle_tEXt(png_structp png_ptr, png_infop info_ptr, png_uint_32
  186349. length)
  186350. {
  186351. if (!(png_ptr->mode & PNG_HAVE_IHDR) || (png_ptr->mode & PNG_HAVE_IEND))
  186352. {
  186353. png_error(png_ptr, "Out of place tEXt");
  186354. info_ptr = info_ptr; /* to quiet some compiler warnings */
  186355. }
  186356. #ifdef PNG_MAX_MALLOC_64K
  186357. png_ptr->skip_length = 0; /* This may not be necessary */
  186358. if (length > (png_uint_32)65535L) /* Can't hold entire string in memory */
  186359. {
  186360. png_warning(png_ptr, "tEXt chunk too large to fit in memory");
  186361. png_ptr->skip_length = length - (png_uint_32)65535L;
  186362. length = (png_uint_32)65535L;
  186363. }
  186364. #endif
  186365. png_ptr->current_text = (png_charp)png_malloc(png_ptr,
  186366. (png_uint_32)(length+1));
  186367. png_ptr->current_text[length] = '\0';
  186368. png_ptr->current_text_ptr = png_ptr->current_text;
  186369. png_ptr->current_text_size = (png_size_t)length;
  186370. png_ptr->current_text_left = (png_size_t)length;
  186371. png_ptr->process_mode = PNG_READ_tEXt_MODE;
  186372. }
  186373. void /* PRIVATE */
  186374. png_push_read_tEXt(png_structp png_ptr, png_infop info_ptr)
  186375. {
  186376. if (png_ptr->buffer_size && png_ptr->current_text_left)
  186377. {
  186378. png_size_t text_size;
  186379. if (png_ptr->buffer_size < png_ptr->current_text_left)
  186380. text_size = png_ptr->buffer_size;
  186381. else
  186382. text_size = png_ptr->current_text_left;
  186383. png_crc_read(png_ptr, (png_bytep)png_ptr->current_text_ptr, text_size);
  186384. png_ptr->current_text_left -= text_size;
  186385. png_ptr->current_text_ptr += text_size;
  186386. }
  186387. if (!(png_ptr->current_text_left))
  186388. {
  186389. png_textp text_ptr;
  186390. png_charp text;
  186391. png_charp key;
  186392. int ret;
  186393. if (png_ptr->buffer_size < 4)
  186394. {
  186395. png_push_save_buffer(png_ptr);
  186396. return;
  186397. }
  186398. png_push_crc_finish(png_ptr);
  186399. #if defined(PNG_MAX_MALLOC_64K)
  186400. if (png_ptr->skip_length)
  186401. return;
  186402. #endif
  186403. key = png_ptr->current_text;
  186404. for (text = key; *text; text++)
  186405. /* empty loop */ ;
  186406. if (text < key + png_ptr->current_text_size)
  186407. text++;
  186408. text_ptr = (png_textp)png_malloc(png_ptr,
  186409. (png_uint_32)png_sizeof(png_text));
  186410. text_ptr->compression = PNG_TEXT_COMPRESSION_NONE;
  186411. text_ptr->key = key;
  186412. #ifdef PNG_iTXt_SUPPORTED
  186413. text_ptr->lang = NULL;
  186414. text_ptr->lang_key = NULL;
  186415. #endif
  186416. text_ptr->text = text;
  186417. ret = png_set_text_2(png_ptr, info_ptr, text_ptr, 1);
  186418. png_free(png_ptr, key);
  186419. png_free(png_ptr, text_ptr);
  186420. png_ptr->current_text = NULL;
  186421. if (ret)
  186422. png_warning(png_ptr, "Insufficient memory to store text chunk.");
  186423. }
  186424. }
  186425. #endif
  186426. #if defined(PNG_READ_zTXt_SUPPORTED)
  186427. void /* PRIVATE */
  186428. png_push_handle_zTXt(png_structp png_ptr, png_infop info_ptr, png_uint_32
  186429. length)
  186430. {
  186431. if (!(png_ptr->mode & PNG_HAVE_IHDR) || (png_ptr->mode & PNG_HAVE_IEND))
  186432. {
  186433. png_error(png_ptr, "Out of place zTXt");
  186434. info_ptr = info_ptr; /* to quiet some compiler warnings */
  186435. }
  186436. #ifdef PNG_MAX_MALLOC_64K
  186437. /* We can't handle zTXt chunks > 64K, since we don't have enough space
  186438. * to be able to store the uncompressed data. Actually, the threshold
  186439. * is probably around 32K, but it isn't as definite as 64K is.
  186440. */
  186441. if (length > (png_uint_32)65535L)
  186442. {
  186443. png_warning(png_ptr, "zTXt chunk too large to fit in memory");
  186444. png_push_crc_skip(png_ptr, length);
  186445. return;
  186446. }
  186447. #endif
  186448. png_ptr->current_text = (png_charp)png_malloc(png_ptr,
  186449. (png_uint_32)(length+1));
  186450. png_ptr->current_text[length] = '\0';
  186451. png_ptr->current_text_ptr = png_ptr->current_text;
  186452. png_ptr->current_text_size = (png_size_t)length;
  186453. png_ptr->current_text_left = (png_size_t)length;
  186454. png_ptr->process_mode = PNG_READ_zTXt_MODE;
  186455. }
  186456. void /* PRIVATE */
  186457. png_push_read_zTXt(png_structp png_ptr, png_infop info_ptr)
  186458. {
  186459. if (png_ptr->buffer_size && png_ptr->current_text_left)
  186460. {
  186461. png_size_t text_size;
  186462. if (png_ptr->buffer_size < (png_uint_32)png_ptr->current_text_left)
  186463. text_size = png_ptr->buffer_size;
  186464. else
  186465. text_size = png_ptr->current_text_left;
  186466. png_crc_read(png_ptr, (png_bytep)png_ptr->current_text_ptr, text_size);
  186467. png_ptr->current_text_left -= text_size;
  186468. png_ptr->current_text_ptr += text_size;
  186469. }
  186470. if (!(png_ptr->current_text_left))
  186471. {
  186472. png_textp text_ptr;
  186473. png_charp text;
  186474. png_charp key;
  186475. int ret;
  186476. png_size_t text_size, key_size;
  186477. if (png_ptr->buffer_size < 4)
  186478. {
  186479. png_push_save_buffer(png_ptr);
  186480. return;
  186481. }
  186482. png_push_crc_finish(png_ptr);
  186483. key = png_ptr->current_text;
  186484. for (text = key; *text; text++)
  186485. /* empty loop */ ;
  186486. /* zTXt can't have zero text */
  186487. if (text >= key + png_ptr->current_text_size)
  186488. {
  186489. png_ptr->current_text = NULL;
  186490. png_free(png_ptr, key);
  186491. return;
  186492. }
  186493. text++;
  186494. if (*text != PNG_TEXT_COMPRESSION_zTXt) /* check compression byte */
  186495. {
  186496. png_ptr->current_text = NULL;
  186497. png_free(png_ptr, key);
  186498. return;
  186499. }
  186500. text++;
  186501. png_ptr->zstream.next_in = (png_bytep )text;
  186502. png_ptr->zstream.avail_in = (uInt)(png_ptr->current_text_size -
  186503. (text - key));
  186504. png_ptr->zstream.next_out = png_ptr->zbuf;
  186505. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  186506. key_size = text - key;
  186507. text_size = 0;
  186508. text = NULL;
  186509. ret = Z_STREAM_END;
  186510. while (png_ptr->zstream.avail_in)
  186511. {
  186512. ret = inflate(&png_ptr->zstream, Z_PARTIAL_FLUSH);
  186513. if (ret != Z_OK && ret != Z_STREAM_END)
  186514. {
  186515. inflateReset(&png_ptr->zstream);
  186516. png_ptr->zstream.avail_in = 0;
  186517. png_ptr->current_text = NULL;
  186518. png_free(png_ptr, key);
  186519. png_free(png_ptr, text);
  186520. return;
  186521. }
  186522. if (!(png_ptr->zstream.avail_out) || ret == Z_STREAM_END)
  186523. {
  186524. if (text == NULL)
  186525. {
  186526. text = (png_charp)png_malloc(png_ptr,
  186527. (png_uint_32)(png_ptr->zbuf_size - png_ptr->zstream.avail_out
  186528. + key_size + 1));
  186529. png_memcpy(text + key_size, png_ptr->zbuf,
  186530. png_ptr->zbuf_size - png_ptr->zstream.avail_out);
  186531. png_memcpy(text, key, key_size);
  186532. text_size = key_size + png_ptr->zbuf_size -
  186533. png_ptr->zstream.avail_out;
  186534. *(text + text_size) = '\0';
  186535. }
  186536. else
  186537. {
  186538. png_charp tmp;
  186539. tmp = text;
  186540. text = (png_charp)png_malloc(png_ptr, text_size +
  186541. (png_uint_32)(png_ptr->zbuf_size - png_ptr->zstream.avail_out
  186542. + 1));
  186543. png_memcpy(text, tmp, text_size);
  186544. png_free(png_ptr, tmp);
  186545. png_memcpy(text + text_size, png_ptr->zbuf,
  186546. png_ptr->zbuf_size - png_ptr->zstream.avail_out);
  186547. text_size += png_ptr->zbuf_size - png_ptr->zstream.avail_out;
  186548. *(text + text_size) = '\0';
  186549. }
  186550. if (ret != Z_STREAM_END)
  186551. {
  186552. png_ptr->zstream.next_out = png_ptr->zbuf;
  186553. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  186554. }
  186555. }
  186556. else
  186557. {
  186558. break;
  186559. }
  186560. if (ret == Z_STREAM_END)
  186561. break;
  186562. }
  186563. inflateReset(&png_ptr->zstream);
  186564. png_ptr->zstream.avail_in = 0;
  186565. if (ret != Z_STREAM_END)
  186566. {
  186567. png_ptr->current_text = NULL;
  186568. png_free(png_ptr, key);
  186569. png_free(png_ptr, text);
  186570. return;
  186571. }
  186572. png_ptr->current_text = NULL;
  186573. png_free(png_ptr, key);
  186574. key = text;
  186575. text += key_size;
  186576. text_ptr = (png_textp)png_malloc(png_ptr,
  186577. (png_uint_32)png_sizeof(png_text));
  186578. text_ptr->compression = PNG_TEXT_COMPRESSION_zTXt;
  186579. text_ptr->key = key;
  186580. #ifdef PNG_iTXt_SUPPORTED
  186581. text_ptr->lang = NULL;
  186582. text_ptr->lang_key = NULL;
  186583. #endif
  186584. text_ptr->text = text;
  186585. ret = png_set_text_2(png_ptr, info_ptr, text_ptr, 1);
  186586. png_free(png_ptr, key);
  186587. png_free(png_ptr, text_ptr);
  186588. if (ret)
  186589. png_warning(png_ptr, "Insufficient memory to store text chunk.");
  186590. }
  186591. }
  186592. #endif
  186593. #if defined(PNG_READ_iTXt_SUPPORTED)
  186594. void /* PRIVATE */
  186595. png_push_handle_iTXt(png_structp png_ptr, png_infop info_ptr, png_uint_32
  186596. length)
  186597. {
  186598. if (!(png_ptr->mode & PNG_HAVE_IHDR) || (png_ptr->mode & PNG_HAVE_IEND))
  186599. {
  186600. png_error(png_ptr, "Out of place iTXt");
  186601. info_ptr = info_ptr; /* to quiet some compiler warnings */
  186602. }
  186603. #ifdef PNG_MAX_MALLOC_64K
  186604. png_ptr->skip_length = 0; /* This may not be necessary */
  186605. if (length > (png_uint_32)65535L) /* Can't hold entire string in memory */
  186606. {
  186607. png_warning(png_ptr, "iTXt chunk too large to fit in memory");
  186608. png_ptr->skip_length = length - (png_uint_32)65535L;
  186609. length = (png_uint_32)65535L;
  186610. }
  186611. #endif
  186612. png_ptr->current_text = (png_charp)png_malloc(png_ptr,
  186613. (png_uint_32)(length+1));
  186614. png_ptr->current_text[length] = '\0';
  186615. png_ptr->current_text_ptr = png_ptr->current_text;
  186616. png_ptr->current_text_size = (png_size_t)length;
  186617. png_ptr->current_text_left = (png_size_t)length;
  186618. png_ptr->process_mode = PNG_READ_iTXt_MODE;
  186619. }
  186620. void /* PRIVATE */
  186621. png_push_read_iTXt(png_structp png_ptr, png_infop info_ptr)
  186622. {
  186623. if (png_ptr->buffer_size && png_ptr->current_text_left)
  186624. {
  186625. png_size_t text_size;
  186626. if (png_ptr->buffer_size < png_ptr->current_text_left)
  186627. text_size = png_ptr->buffer_size;
  186628. else
  186629. text_size = png_ptr->current_text_left;
  186630. png_crc_read(png_ptr, (png_bytep)png_ptr->current_text_ptr, text_size);
  186631. png_ptr->current_text_left -= text_size;
  186632. png_ptr->current_text_ptr += text_size;
  186633. }
  186634. if (!(png_ptr->current_text_left))
  186635. {
  186636. png_textp text_ptr;
  186637. png_charp key;
  186638. int comp_flag;
  186639. png_charp lang;
  186640. png_charp lang_key;
  186641. png_charp text;
  186642. int ret;
  186643. if (png_ptr->buffer_size < 4)
  186644. {
  186645. png_push_save_buffer(png_ptr);
  186646. return;
  186647. }
  186648. png_push_crc_finish(png_ptr);
  186649. #if defined(PNG_MAX_MALLOC_64K)
  186650. if (png_ptr->skip_length)
  186651. return;
  186652. #endif
  186653. key = png_ptr->current_text;
  186654. for (lang = key; *lang; lang++)
  186655. /* empty loop */ ;
  186656. if (lang < key + png_ptr->current_text_size - 3)
  186657. lang++;
  186658. comp_flag = *lang++;
  186659. lang++; /* skip comp_type, always zero */
  186660. for (lang_key = lang; *lang_key; lang_key++)
  186661. /* empty loop */ ;
  186662. lang_key++; /* skip NUL separator */
  186663. text=lang_key;
  186664. if (lang_key < key + png_ptr->current_text_size - 1)
  186665. {
  186666. for (; *text; text++)
  186667. /* empty loop */ ;
  186668. }
  186669. if (text < key + png_ptr->current_text_size)
  186670. text++;
  186671. text_ptr = (png_textp)png_malloc(png_ptr,
  186672. (png_uint_32)png_sizeof(png_text));
  186673. text_ptr->compression = comp_flag + 2;
  186674. text_ptr->key = key;
  186675. text_ptr->lang = lang;
  186676. text_ptr->lang_key = lang_key;
  186677. text_ptr->text = text;
  186678. text_ptr->text_length = 0;
  186679. text_ptr->itxt_length = png_strlen(text);
  186680. ret = png_set_text_2(png_ptr, info_ptr, text_ptr, 1);
  186681. png_ptr->current_text = NULL;
  186682. png_free(png_ptr, text_ptr);
  186683. if (ret)
  186684. png_warning(png_ptr, "Insufficient memory to store iTXt chunk.");
  186685. }
  186686. }
  186687. #endif
  186688. /* This function is called when we haven't found a handler for this
  186689. * chunk. If there isn't a problem with the chunk itself (ie a bad chunk
  186690. * name or a critical chunk), the chunk is (currently) silently ignored.
  186691. */
  186692. void /* PRIVATE */
  186693. png_push_handle_unknown(png_structp png_ptr, png_infop info_ptr, png_uint_32
  186694. length)
  186695. {
  186696. png_uint_32 skip=0;
  186697. png_check_chunk_name(png_ptr, png_ptr->chunk_name);
  186698. if (!(png_ptr->chunk_name[0] & 0x20))
  186699. {
  186700. #if defined(PNG_READ_UNKNOWN_CHUNKS_SUPPORTED)
  186701. if(png_handle_as_unknown(png_ptr, png_ptr->chunk_name) !=
  186702. PNG_HANDLE_CHUNK_ALWAYS
  186703. #if defined(PNG_READ_USER_CHUNKS_SUPPORTED)
  186704. && png_ptr->read_user_chunk_fn == NULL
  186705. #endif
  186706. )
  186707. #endif
  186708. png_chunk_error(png_ptr, "unknown critical chunk");
  186709. info_ptr = info_ptr; /* to quiet some compiler warnings */
  186710. }
  186711. #if defined(PNG_READ_UNKNOWN_CHUNKS_SUPPORTED)
  186712. if (png_ptr->flags & PNG_FLAG_KEEP_UNKNOWN_CHUNKS)
  186713. {
  186714. #ifdef PNG_MAX_MALLOC_64K
  186715. if (length > (png_uint_32)65535L)
  186716. {
  186717. png_warning(png_ptr, "unknown chunk too large to fit in memory");
  186718. skip = length - (png_uint_32)65535L;
  186719. length = (png_uint_32)65535L;
  186720. }
  186721. #endif
  186722. png_strncpy((png_charp)png_ptr->unknown_chunk.name,
  186723. (png_charp)png_ptr->chunk_name, 5);
  186724. png_ptr->unknown_chunk.data = (png_bytep)png_malloc(png_ptr, length);
  186725. png_ptr->unknown_chunk.size = (png_size_t)length;
  186726. png_crc_read(png_ptr, (png_bytep)png_ptr->unknown_chunk.data, length);
  186727. #if defined(PNG_READ_USER_CHUNKS_SUPPORTED)
  186728. if(png_ptr->read_user_chunk_fn != NULL)
  186729. {
  186730. /* callback to user unknown chunk handler */
  186731. int ret;
  186732. ret = (*(png_ptr->read_user_chunk_fn))
  186733. (png_ptr, &png_ptr->unknown_chunk);
  186734. if (ret < 0)
  186735. png_chunk_error(png_ptr, "error in user chunk");
  186736. if (ret == 0)
  186737. {
  186738. if (!(png_ptr->chunk_name[0] & 0x20))
  186739. if(png_handle_as_unknown(png_ptr, png_ptr->chunk_name) !=
  186740. PNG_HANDLE_CHUNK_ALWAYS)
  186741. png_chunk_error(png_ptr, "unknown critical chunk");
  186742. png_set_unknown_chunks(png_ptr, info_ptr,
  186743. &png_ptr->unknown_chunk, 1);
  186744. }
  186745. }
  186746. #else
  186747. png_set_unknown_chunks(png_ptr, info_ptr, &png_ptr->unknown_chunk, 1);
  186748. #endif
  186749. png_free(png_ptr, png_ptr->unknown_chunk.data);
  186750. png_ptr->unknown_chunk.data = NULL;
  186751. }
  186752. else
  186753. #endif
  186754. skip=length;
  186755. png_push_crc_skip(png_ptr, skip);
  186756. }
  186757. void /* PRIVATE */
  186758. png_push_have_info(png_structp png_ptr, png_infop info_ptr)
  186759. {
  186760. if (png_ptr->info_fn != NULL)
  186761. (*(png_ptr->info_fn))(png_ptr, info_ptr);
  186762. }
  186763. void /* PRIVATE */
  186764. png_push_have_end(png_structp png_ptr, png_infop info_ptr)
  186765. {
  186766. if (png_ptr->end_fn != NULL)
  186767. (*(png_ptr->end_fn))(png_ptr, info_ptr);
  186768. }
  186769. void /* PRIVATE */
  186770. png_push_have_row(png_structp png_ptr, png_bytep row)
  186771. {
  186772. if (png_ptr->row_fn != NULL)
  186773. (*(png_ptr->row_fn))(png_ptr, row, png_ptr->row_number,
  186774. (int)png_ptr->pass);
  186775. }
  186776. void PNGAPI
  186777. png_progressive_combine_row (png_structp png_ptr,
  186778. png_bytep old_row, png_bytep new_row)
  186779. {
  186780. #ifdef PNG_USE_LOCAL_ARRAYS
  186781. PNG_CONST int FARDATA png_pass_dsp_mask[7] =
  186782. {0xff, 0x0f, 0xff, 0x33, 0xff, 0x55, 0xff};
  186783. #endif
  186784. if(png_ptr == NULL) return;
  186785. if (new_row != NULL) /* new_row must == png_ptr->row_buf here. */
  186786. png_combine_row(png_ptr, old_row, png_pass_dsp_mask[png_ptr->pass]);
  186787. }
  186788. void PNGAPI
  186789. png_set_progressive_read_fn(png_structp png_ptr, png_voidp progressive_ptr,
  186790. png_progressive_info_ptr info_fn, png_progressive_row_ptr row_fn,
  186791. png_progressive_end_ptr end_fn)
  186792. {
  186793. if(png_ptr == NULL) return;
  186794. png_ptr->info_fn = info_fn;
  186795. png_ptr->row_fn = row_fn;
  186796. png_ptr->end_fn = end_fn;
  186797. png_set_read_fn(png_ptr, progressive_ptr, png_push_fill_buffer);
  186798. }
  186799. png_voidp PNGAPI
  186800. png_get_progressive_ptr(png_structp png_ptr)
  186801. {
  186802. if(png_ptr == NULL) return (NULL);
  186803. return png_ptr->io_ptr;
  186804. }
  186805. #endif /* PNG_PROGRESSIVE_READ_SUPPORTED */
  186806. /*** End of inlined file: pngpread.c ***/
  186807. /*** Start of inlined file: pngrio.c ***/
  186808. /* pngrio.c - functions for data input
  186809. *
  186810. * Last changed in libpng 1.2.13 November 13, 2006
  186811. * For conditions of distribution and use, see copyright notice in png.h
  186812. * Copyright (c) 1998-2006 Glenn Randers-Pehrson
  186813. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  186814. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  186815. *
  186816. * This file provides a location for all input. Users who need
  186817. * special handling are expected to write a function that has the same
  186818. * arguments as this and performs a similar function, but that possibly
  186819. * has a different input method. Note that you shouldn't change this
  186820. * function, but rather write a replacement function and then make
  186821. * libpng use it at run time with png_set_read_fn(...).
  186822. */
  186823. #define PNG_INTERNAL
  186824. #if defined(PNG_READ_SUPPORTED)
  186825. /* Read the data from whatever input you are using. The default routine
  186826. reads from a file pointer. Note that this routine sometimes gets called
  186827. with very small lengths, so you should implement some kind of simple
  186828. buffering if you are using unbuffered reads. This should never be asked
  186829. to read more then 64K on a 16 bit machine. */
  186830. void /* PRIVATE */
  186831. png_read_data(png_structp png_ptr, png_bytep data, png_size_t length)
  186832. {
  186833. png_debug1(4,"reading %d bytes\n", (int)length);
  186834. if (png_ptr->read_data_fn != NULL)
  186835. (*(png_ptr->read_data_fn))(png_ptr, data, length);
  186836. else
  186837. png_error(png_ptr, "Call to NULL read function");
  186838. }
  186839. #if !defined(PNG_NO_STDIO)
  186840. /* This is the function that does the actual reading of data. If you are
  186841. not reading from a standard C stream, you should create a replacement
  186842. read_data function and use it at run time with png_set_read_fn(), rather
  186843. than changing the library. */
  186844. #ifndef USE_FAR_KEYWORD
  186845. void PNGAPI
  186846. png_default_read_data(png_structp png_ptr, png_bytep data, png_size_t length)
  186847. {
  186848. png_size_t check;
  186849. if(png_ptr == NULL) return;
  186850. /* fread() returns 0 on error, so it is OK to store this in a png_size_t
  186851. * instead of an int, which is what fread() actually returns.
  186852. */
  186853. #if defined(_WIN32_WCE)
  186854. if ( !ReadFile((HANDLE)(png_ptr->io_ptr), data, length, &check, NULL) )
  186855. check = 0;
  186856. #else
  186857. check = (png_size_t)fread(data, (png_size_t)1, length,
  186858. (png_FILE_p)png_ptr->io_ptr);
  186859. #endif
  186860. if (check != length)
  186861. png_error(png_ptr, "Read Error");
  186862. }
  186863. #else
  186864. /* this is the model-independent version. Since the standard I/O library
  186865. can't handle far buffers in the medium and small models, we have to copy
  186866. the data.
  186867. */
  186868. #define NEAR_BUF_SIZE 1024
  186869. #define MIN(a,b) (a <= b ? a : b)
  186870. static void PNGAPI
  186871. png_default_read_data(png_structp png_ptr, png_bytep data, png_size_t length)
  186872. {
  186873. int check;
  186874. png_byte *n_data;
  186875. png_FILE_p io_ptr;
  186876. if(png_ptr == NULL) return;
  186877. /* Check if data really is near. If so, use usual code. */
  186878. n_data = (png_byte *)CVT_PTR_NOCHECK(data);
  186879. io_ptr = (png_FILE_p)CVT_PTR(png_ptr->io_ptr);
  186880. if ((png_bytep)n_data == data)
  186881. {
  186882. #if defined(_WIN32_WCE)
  186883. if ( !ReadFile((HANDLE)(png_ptr->io_ptr), data, length, &check, NULL) )
  186884. check = 0;
  186885. #else
  186886. check = fread(n_data, 1, length, io_ptr);
  186887. #endif
  186888. }
  186889. else
  186890. {
  186891. png_byte buf[NEAR_BUF_SIZE];
  186892. png_size_t read, remaining, err;
  186893. check = 0;
  186894. remaining = length;
  186895. do
  186896. {
  186897. read = MIN(NEAR_BUF_SIZE, remaining);
  186898. #if defined(_WIN32_WCE)
  186899. if ( !ReadFile((HANDLE)(io_ptr), buf, read, &err, NULL) )
  186900. err = 0;
  186901. #else
  186902. err = fread(buf, (png_size_t)1, read, io_ptr);
  186903. #endif
  186904. png_memcpy(data, buf, read); /* copy far buffer to near buffer */
  186905. if(err != read)
  186906. break;
  186907. else
  186908. check += err;
  186909. data += read;
  186910. remaining -= read;
  186911. }
  186912. while (remaining != 0);
  186913. }
  186914. if ((png_uint_32)check != (png_uint_32)length)
  186915. png_error(png_ptr, "read Error");
  186916. }
  186917. #endif
  186918. #endif
  186919. /* This function allows the application to supply a new input function
  186920. for libpng if standard C streams aren't being used.
  186921. This function takes as its arguments:
  186922. png_ptr - pointer to a png input data structure
  186923. io_ptr - pointer to user supplied structure containing info about
  186924. the input functions. May be NULL.
  186925. read_data_fn - pointer to a new input function that takes as its
  186926. arguments a pointer to a png_struct, a pointer to
  186927. a location where input data can be stored, and a 32-bit
  186928. unsigned int that is the number of bytes to be read.
  186929. To exit and output any fatal error messages the new write
  186930. function should call png_error(png_ptr, "Error msg"). */
  186931. void PNGAPI
  186932. png_set_read_fn(png_structp png_ptr, png_voidp io_ptr,
  186933. png_rw_ptr read_data_fn)
  186934. {
  186935. if(png_ptr == NULL) return;
  186936. png_ptr->io_ptr = io_ptr;
  186937. #if !defined(PNG_NO_STDIO)
  186938. if (read_data_fn != NULL)
  186939. png_ptr->read_data_fn = read_data_fn;
  186940. else
  186941. png_ptr->read_data_fn = png_default_read_data;
  186942. #else
  186943. png_ptr->read_data_fn = read_data_fn;
  186944. #endif
  186945. /* It is an error to write to a read device */
  186946. if (png_ptr->write_data_fn != NULL)
  186947. {
  186948. png_ptr->write_data_fn = NULL;
  186949. png_warning(png_ptr,
  186950. "It's an error to set both read_data_fn and write_data_fn in the ");
  186951. png_warning(png_ptr,
  186952. "same structure. Resetting write_data_fn to NULL.");
  186953. }
  186954. #if defined(PNG_WRITE_FLUSH_SUPPORTED)
  186955. png_ptr->output_flush_fn = NULL;
  186956. #endif
  186957. }
  186958. #endif /* PNG_READ_SUPPORTED */
  186959. /*** End of inlined file: pngrio.c ***/
  186960. /*** Start of inlined file: pngrtran.c ***/
  186961. /* pngrtran.c - transforms the data in a row for PNG readers
  186962. *
  186963. * Last changed in libpng 1.2.21 [October 4, 2007]
  186964. * For conditions of distribution and use, see copyright notice in png.h
  186965. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  186966. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  186967. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  186968. *
  186969. * This file contains functions optionally called by an application
  186970. * in order to tell libpng how to handle data when reading a PNG.
  186971. * Transformations that are used in both reading and writing are
  186972. * in pngtrans.c.
  186973. */
  186974. #define PNG_INTERNAL
  186975. #if defined(PNG_READ_SUPPORTED)
  186976. /* Set the action on getting a CRC error for an ancillary or critical chunk. */
  186977. void PNGAPI
  186978. png_set_crc_action(png_structp png_ptr, int crit_action, int ancil_action)
  186979. {
  186980. png_debug(1, "in png_set_crc_action\n");
  186981. /* Tell libpng how we react to CRC errors in critical chunks */
  186982. if(png_ptr == NULL) return;
  186983. switch (crit_action)
  186984. {
  186985. case PNG_CRC_NO_CHANGE: /* leave setting as is */
  186986. break;
  186987. case PNG_CRC_WARN_USE: /* warn/use data */
  186988. png_ptr->flags &= ~PNG_FLAG_CRC_CRITICAL_MASK;
  186989. png_ptr->flags |= PNG_FLAG_CRC_CRITICAL_USE;
  186990. break;
  186991. case PNG_CRC_QUIET_USE: /* quiet/use data */
  186992. png_ptr->flags &= ~PNG_FLAG_CRC_CRITICAL_MASK;
  186993. png_ptr->flags |= PNG_FLAG_CRC_CRITICAL_USE |
  186994. PNG_FLAG_CRC_CRITICAL_IGNORE;
  186995. break;
  186996. case PNG_CRC_WARN_DISCARD: /* not a valid action for critical data */
  186997. png_warning(png_ptr, "Can't discard critical data on CRC error.");
  186998. case PNG_CRC_ERROR_QUIT: /* error/quit */
  186999. case PNG_CRC_DEFAULT:
  187000. default:
  187001. png_ptr->flags &= ~PNG_FLAG_CRC_CRITICAL_MASK;
  187002. break;
  187003. }
  187004. switch (ancil_action)
  187005. {
  187006. case PNG_CRC_NO_CHANGE: /* leave setting as is */
  187007. break;
  187008. case PNG_CRC_WARN_USE: /* warn/use data */
  187009. png_ptr->flags &= ~PNG_FLAG_CRC_ANCILLARY_MASK;
  187010. png_ptr->flags |= PNG_FLAG_CRC_ANCILLARY_USE;
  187011. break;
  187012. case PNG_CRC_QUIET_USE: /* quiet/use data */
  187013. png_ptr->flags &= ~PNG_FLAG_CRC_ANCILLARY_MASK;
  187014. png_ptr->flags |= PNG_FLAG_CRC_ANCILLARY_USE |
  187015. PNG_FLAG_CRC_ANCILLARY_NOWARN;
  187016. break;
  187017. case PNG_CRC_ERROR_QUIT: /* error/quit */
  187018. png_ptr->flags &= ~PNG_FLAG_CRC_ANCILLARY_MASK;
  187019. png_ptr->flags |= PNG_FLAG_CRC_ANCILLARY_NOWARN;
  187020. break;
  187021. case PNG_CRC_WARN_DISCARD: /* warn/discard data */
  187022. case PNG_CRC_DEFAULT:
  187023. default:
  187024. png_ptr->flags &= ~PNG_FLAG_CRC_ANCILLARY_MASK;
  187025. break;
  187026. }
  187027. }
  187028. #if defined(PNG_READ_BACKGROUND_SUPPORTED) && \
  187029. defined(PNG_FLOATING_POINT_SUPPORTED)
  187030. /* handle alpha and tRNS via a background color */
  187031. void PNGAPI
  187032. png_set_background(png_structp png_ptr,
  187033. png_color_16p background_color, int background_gamma_code,
  187034. int need_expand, double background_gamma)
  187035. {
  187036. png_debug(1, "in png_set_background\n");
  187037. if(png_ptr == NULL) return;
  187038. if (background_gamma_code == PNG_BACKGROUND_GAMMA_UNKNOWN)
  187039. {
  187040. png_warning(png_ptr, "Application must supply a known background gamma");
  187041. return;
  187042. }
  187043. png_ptr->transformations |= PNG_BACKGROUND;
  187044. png_memcpy(&(png_ptr->background), background_color,
  187045. png_sizeof(png_color_16));
  187046. png_ptr->background_gamma = (float)background_gamma;
  187047. png_ptr->background_gamma_type = (png_byte)(background_gamma_code);
  187048. png_ptr->transformations |= (need_expand ? PNG_BACKGROUND_EXPAND : 0);
  187049. }
  187050. #endif
  187051. #if defined(PNG_READ_16_TO_8_SUPPORTED)
  187052. /* strip 16 bit depth files to 8 bit depth */
  187053. void PNGAPI
  187054. png_set_strip_16(png_structp png_ptr)
  187055. {
  187056. png_debug(1, "in png_set_strip_16\n");
  187057. if(png_ptr == NULL) return;
  187058. png_ptr->transformations |= PNG_16_TO_8;
  187059. }
  187060. #endif
  187061. #if defined(PNG_READ_STRIP_ALPHA_SUPPORTED)
  187062. void PNGAPI
  187063. png_set_strip_alpha(png_structp png_ptr)
  187064. {
  187065. png_debug(1, "in png_set_strip_alpha\n");
  187066. if(png_ptr == NULL) return;
  187067. png_ptr->flags |= PNG_FLAG_STRIP_ALPHA;
  187068. }
  187069. #endif
  187070. #if defined(PNG_READ_DITHER_SUPPORTED)
  187071. /* Dither file to 8 bit. Supply a palette, the current number
  187072. * of elements in the palette, the maximum number of elements
  187073. * allowed, and a histogram if possible. If the current number
  187074. * of colors is greater then the maximum number, the palette will be
  187075. * modified to fit in the maximum number. "full_dither" indicates
  187076. * whether we need a dithering cube set up for RGB images, or if we
  187077. * simply are reducing the number of colors in a paletted image.
  187078. */
  187079. typedef struct png_dsort_struct
  187080. {
  187081. struct png_dsort_struct FAR * next;
  187082. png_byte left;
  187083. png_byte right;
  187084. } png_dsort;
  187085. typedef png_dsort FAR * png_dsortp;
  187086. typedef png_dsort FAR * FAR * png_dsortpp;
  187087. void PNGAPI
  187088. png_set_dither(png_structp png_ptr, png_colorp palette,
  187089. int num_palette, int maximum_colors, png_uint_16p histogram,
  187090. int full_dither)
  187091. {
  187092. png_debug(1, "in png_set_dither\n");
  187093. if(png_ptr == NULL) return;
  187094. png_ptr->transformations |= PNG_DITHER;
  187095. if (!full_dither)
  187096. {
  187097. int i;
  187098. png_ptr->dither_index = (png_bytep)png_malloc(png_ptr,
  187099. (png_uint_32)(num_palette * png_sizeof (png_byte)));
  187100. for (i = 0; i < num_palette; i++)
  187101. png_ptr->dither_index[i] = (png_byte)i;
  187102. }
  187103. if (num_palette > maximum_colors)
  187104. {
  187105. if (histogram != NULL)
  187106. {
  187107. /* This is easy enough, just throw out the least used colors.
  187108. Perhaps not the best solution, but good enough. */
  187109. int i;
  187110. /* initialize an array to sort colors */
  187111. png_ptr->dither_sort = (png_bytep)png_malloc(png_ptr,
  187112. (png_uint_32)(num_palette * png_sizeof (png_byte)));
  187113. /* initialize the dither_sort array */
  187114. for (i = 0; i < num_palette; i++)
  187115. png_ptr->dither_sort[i] = (png_byte)i;
  187116. /* Find the least used palette entries by starting a
  187117. bubble sort, and running it until we have sorted
  187118. out enough colors. Note that we don't care about
  187119. sorting all the colors, just finding which are
  187120. least used. */
  187121. for (i = num_palette - 1; i >= maximum_colors; i--)
  187122. {
  187123. int done; /* to stop early if the list is pre-sorted */
  187124. int j;
  187125. done = 1;
  187126. for (j = 0; j < i; j++)
  187127. {
  187128. if (histogram[png_ptr->dither_sort[j]]
  187129. < histogram[png_ptr->dither_sort[j + 1]])
  187130. {
  187131. png_byte t;
  187132. t = png_ptr->dither_sort[j];
  187133. png_ptr->dither_sort[j] = png_ptr->dither_sort[j + 1];
  187134. png_ptr->dither_sort[j + 1] = t;
  187135. done = 0;
  187136. }
  187137. }
  187138. if (done)
  187139. break;
  187140. }
  187141. /* swap the palette around, and set up a table, if necessary */
  187142. if (full_dither)
  187143. {
  187144. int j = num_palette;
  187145. /* put all the useful colors within the max, but don't
  187146. move the others */
  187147. for (i = 0; i < maximum_colors; i++)
  187148. {
  187149. if ((int)png_ptr->dither_sort[i] >= maximum_colors)
  187150. {
  187151. do
  187152. j--;
  187153. while ((int)png_ptr->dither_sort[j] >= maximum_colors);
  187154. palette[i] = palette[j];
  187155. }
  187156. }
  187157. }
  187158. else
  187159. {
  187160. int j = num_palette;
  187161. /* move all the used colors inside the max limit, and
  187162. develop a translation table */
  187163. for (i = 0; i < maximum_colors; i++)
  187164. {
  187165. /* only move the colors we need to */
  187166. if ((int)png_ptr->dither_sort[i] >= maximum_colors)
  187167. {
  187168. png_color tmp_color;
  187169. do
  187170. j--;
  187171. while ((int)png_ptr->dither_sort[j] >= maximum_colors);
  187172. tmp_color = palette[j];
  187173. palette[j] = palette[i];
  187174. palette[i] = tmp_color;
  187175. /* indicate where the color went */
  187176. png_ptr->dither_index[j] = (png_byte)i;
  187177. png_ptr->dither_index[i] = (png_byte)j;
  187178. }
  187179. }
  187180. /* find closest color for those colors we are not using */
  187181. for (i = 0; i < num_palette; i++)
  187182. {
  187183. if ((int)png_ptr->dither_index[i] >= maximum_colors)
  187184. {
  187185. int min_d, k, min_k, d_index;
  187186. /* find the closest color to one we threw out */
  187187. d_index = png_ptr->dither_index[i];
  187188. min_d = PNG_COLOR_DIST(palette[d_index], palette[0]);
  187189. for (k = 1, min_k = 0; k < maximum_colors; k++)
  187190. {
  187191. int d;
  187192. d = PNG_COLOR_DIST(palette[d_index], palette[k]);
  187193. if (d < min_d)
  187194. {
  187195. min_d = d;
  187196. min_k = k;
  187197. }
  187198. }
  187199. /* point to closest color */
  187200. png_ptr->dither_index[i] = (png_byte)min_k;
  187201. }
  187202. }
  187203. }
  187204. png_free(png_ptr, png_ptr->dither_sort);
  187205. png_ptr->dither_sort=NULL;
  187206. }
  187207. else
  187208. {
  187209. /* This is much harder to do simply (and quickly). Perhaps
  187210. we need to go through a median cut routine, but those
  187211. don't always behave themselves with only a few colors
  187212. as input. So we will just find the closest two colors,
  187213. and throw out one of them (chosen somewhat randomly).
  187214. [We don't understand this at all, so if someone wants to
  187215. work on improving it, be our guest - AED, GRP]
  187216. */
  187217. int i;
  187218. int max_d;
  187219. int num_new_palette;
  187220. png_dsortp t;
  187221. png_dsortpp hash;
  187222. t=NULL;
  187223. /* initialize palette index arrays */
  187224. png_ptr->index_to_palette = (png_bytep)png_malloc(png_ptr,
  187225. (png_uint_32)(num_palette * png_sizeof (png_byte)));
  187226. png_ptr->palette_to_index = (png_bytep)png_malloc(png_ptr,
  187227. (png_uint_32)(num_palette * png_sizeof (png_byte)));
  187228. /* initialize the sort array */
  187229. for (i = 0; i < num_palette; i++)
  187230. {
  187231. png_ptr->index_to_palette[i] = (png_byte)i;
  187232. png_ptr->palette_to_index[i] = (png_byte)i;
  187233. }
  187234. hash = (png_dsortpp)png_malloc(png_ptr, (png_uint_32)(769 *
  187235. png_sizeof (png_dsortp)));
  187236. for (i = 0; i < 769; i++)
  187237. hash[i] = NULL;
  187238. /* png_memset(hash, 0, 769 * png_sizeof (png_dsortp)); */
  187239. num_new_palette = num_palette;
  187240. /* initial wild guess at how far apart the farthest pixel
  187241. pair we will be eliminating will be. Larger
  187242. numbers mean more areas will be allocated, Smaller
  187243. numbers run the risk of not saving enough data, and
  187244. having to do this all over again.
  187245. I have not done extensive checking on this number.
  187246. */
  187247. max_d = 96;
  187248. while (num_new_palette > maximum_colors)
  187249. {
  187250. for (i = 0; i < num_new_palette - 1; i++)
  187251. {
  187252. int j;
  187253. for (j = i + 1; j < num_new_palette; j++)
  187254. {
  187255. int d;
  187256. d = PNG_COLOR_DIST(palette[i], palette[j]);
  187257. if (d <= max_d)
  187258. {
  187259. t = (png_dsortp)png_malloc_warn(png_ptr,
  187260. (png_uint_32)(png_sizeof(png_dsort)));
  187261. if (t == NULL)
  187262. break;
  187263. t->next = hash[d];
  187264. t->left = (png_byte)i;
  187265. t->right = (png_byte)j;
  187266. hash[d] = t;
  187267. }
  187268. }
  187269. if (t == NULL)
  187270. break;
  187271. }
  187272. if (t != NULL)
  187273. for (i = 0; i <= max_d; i++)
  187274. {
  187275. if (hash[i] != NULL)
  187276. {
  187277. png_dsortp p;
  187278. for (p = hash[i]; p; p = p->next)
  187279. {
  187280. if ((int)png_ptr->index_to_palette[p->left]
  187281. < num_new_palette &&
  187282. (int)png_ptr->index_to_palette[p->right]
  187283. < num_new_palette)
  187284. {
  187285. int j, next_j;
  187286. if (num_new_palette & 0x01)
  187287. {
  187288. j = p->left;
  187289. next_j = p->right;
  187290. }
  187291. else
  187292. {
  187293. j = p->right;
  187294. next_j = p->left;
  187295. }
  187296. num_new_palette--;
  187297. palette[png_ptr->index_to_palette[j]]
  187298. = palette[num_new_palette];
  187299. if (!full_dither)
  187300. {
  187301. int k;
  187302. for (k = 0; k < num_palette; k++)
  187303. {
  187304. if (png_ptr->dither_index[k] ==
  187305. png_ptr->index_to_palette[j])
  187306. png_ptr->dither_index[k] =
  187307. png_ptr->index_to_palette[next_j];
  187308. if ((int)png_ptr->dither_index[k] ==
  187309. num_new_palette)
  187310. png_ptr->dither_index[k] =
  187311. png_ptr->index_to_palette[j];
  187312. }
  187313. }
  187314. png_ptr->index_to_palette[png_ptr->palette_to_index
  187315. [num_new_palette]] = png_ptr->index_to_palette[j];
  187316. png_ptr->palette_to_index[png_ptr->index_to_palette[j]]
  187317. = png_ptr->palette_to_index[num_new_palette];
  187318. png_ptr->index_to_palette[j] = (png_byte)num_new_palette;
  187319. png_ptr->palette_to_index[num_new_palette] = (png_byte)j;
  187320. }
  187321. if (num_new_palette <= maximum_colors)
  187322. break;
  187323. }
  187324. if (num_new_palette <= maximum_colors)
  187325. break;
  187326. }
  187327. }
  187328. for (i = 0; i < 769; i++)
  187329. {
  187330. if (hash[i] != NULL)
  187331. {
  187332. png_dsortp p = hash[i];
  187333. while (p)
  187334. {
  187335. t = p->next;
  187336. png_free(png_ptr, p);
  187337. p = t;
  187338. }
  187339. }
  187340. hash[i] = 0;
  187341. }
  187342. max_d += 96;
  187343. }
  187344. png_free(png_ptr, hash);
  187345. png_free(png_ptr, png_ptr->palette_to_index);
  187346. png_free(png_ptr, png_ptr->index_to_palette);
  187347. png_ptr->palette_to_index=NULL;
  187348. png_ptr->index_to_palette=NULL;
  187349. }
  187350. num_palette = maximum_colors;
  187351. }
  187352. if (png_ptr->palette == NULL)
  187353. {
  187354. png_ptr->palette = palette;
  187355. }
  187356. png_ptr->num_palette = (png_uint_16)num_palette;
  187357. if (full_dither)
  187358. {
  187359. int i;
  187360. png_bytep distance;
  187361. int total_bits = PNG_DITHER_RED_BITS + PNG_DITHER_GREEN_BITS +
  187362. PNG_DITHER_BLUE_BITS;
  187363. int num_red = (1 << PNG_DITHER_RED_BITS);
  187364. int num_green = (1 << PNG_DITHER_GREEN_BITS);
  187365. int num_blue = (1 << PNG_DITHER_BLUE_BITS);
  187366. png_size_t num_entries = ((png_size_t)1 << total_bits);
  187367. png_ptr->palette_lookup = (png_bytep )png_malloc(png_ptr,
  187368. (png_uint_32)(num_entries * png_sizeof (png_byte)));
  187369. png_memset(png_ptr->palette_lookup, 0, num_entries *
  187370. png_sizeof (png_byte));
  187371. distance = (png_bytep)png_malloc(png_ptr, (png_uint_32)(num_entries *
  187372. png_sizeof(png_byte)));
  187373. png_memset(distance, 0xff, num_entries * png_sizeof(png_byte));
  187374. for (i = 0; i < num_palette; i++)
  187375. {
  187376. int ir, ig, ib;
  187377. int r = (palette[i].red >> (8 - PNG_DITHER_RED_BITS));
  187378. int g = (palette[i].green >> (8 - PNG_DITHER_GREEN_BITS));
  187379. int b = (palette[i].blue >> (8 - PNG_DITHER_BLUE_BITS));
  187380. for (ir = 0; ir < num_red; ir++)
  187381. {
  187382. /* int dr = abs(ir - r); */
  187383. int dr = ((ir > r) ? ir - r : r - ir);
  187384. int index_r = (ir << (PNG_DITHER_BLUE_BITS + PNG_DITHER_GREEN_BITS));
  187385. for (ig = 0; ig < num_green; ig++)
  187386. {
  187387. /* int dg = abs(ig - g); */
  187388. int dg = ((ig > g) ? ig - g : g - ig);
  187389. int dt = dr + dg;
  187390. int dm = ((dr > dg) ? dr : dg);
  187391. int index_g = index_r | (ig << PNG_DITHER_BLUE_BITS);
  187392. for (ib = 0; ib < num_blue; ib++)
  187393. {
  187394. int d_index = index_g | ib;
  187395. /* int db = abs(ib - b); */
  187396. int db = ((ib > b) ? ib - b : b - ib);
  187397. int dmax = ((dm > db) ? dm : db);
  187398. int d = dmax + dt + db;
  187399. if (d < (int)distance[d_index])
  187400. {
  187401. distance[d_index] = (png_byte)d;
  187402. png_ptr->palette_lookup[d_index] = (png_byte)i;
  187403. }
  187404. }
  187405. }
  187406. }
  187407. }
  187408. png_free(png_ptr, distance);
  187409. }
  187410. }
  187411. #endif
  187412. #if defined(PNG_READ_GAMMA_SUPPORTED) && defined(PNG_FLOATING_POINT_SUPPORTED)
  187413. /* Transform the image from the file_gamma to the screen_gamma. We
  187414. * only do transformations on images where the file_gamma and screen_gamma
  187415. * are not close reciprocals, otherwise it slows things down slightly, and
  187416. * also needlessly introduces small errors.
  187417. *
  187418. * We will turn off gamma transformation later if no semitransparent entries
  187419. * are present in the tRNS array for palette images. We can't do it here
  187420. * because we don't necessarily have the tRNS chunk yet.
  187421. */
  187422. void PNGAPI
  187423. png_set_gamma(png_structp png_ptr, double scrn_gamma, double file_gamma)
  187424. {
  187425. png_debug(1, "in png_set_gamma\n");
  187426. if(png_ptr == NULL) return;
  187427. if ((fabs(scrn_gamma * file_gamma - 1.0) > PNG_GAMMA_THRESHOLD) ||
  187428. (png_ptr->color_type & PNG_COLOR_MASK_ALPHA) ||
  187429. (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE))
  187430. png_ptr->transformations |= PNG_GAMMA;
  187431. png_ptr->gamma = (float)file_gamma;
  187432. png_ptr->screen_gamma = (float)scrn_gamma;
  187433. }
  187434. #endif
  187435. #if defined(PNG_READ_EXPAND_SUPPORTED)
  187436. /* Expand paletted images to RGB, expand grayscale images of
  187437. * less than 8-bit depth to 8-bit depth, and expand tRNS chunks
  187438. * to alpha channels.
  187439. */
  187440. void PNGAPI
  187441. png_set_expand(png_structp png_ptr)
  187442. {
  187443. png_debug(1, "in png_set_expand\n");
  187444. if(png_ptr == NULL) return;
  187445. png_ptr->transformations |= (PNG_EXPAND | PNG_EXPAND_tRNS);
  187446. #ifdef PNG_WARN_UNINITIALIZED_ROW
  187447. png_ptr->flags &= ~PNG_FLAG_ROW_INIT;
  187448. #endif
  187449. }
  187450. /* GRR 19990627: the following three functions currently are identical
  187451. * to png_set_expand(). However, it is entirely reasonable that someone
  187452. * might wish to expand an indexed image to RGB but *not* expand a single,
  187453. * fully transparent palette entry to a full alpha channel--perhaps instead
  187454. * convert tRNS to the grayscale/RGB format (16-bit RGB value), or replace
  187455. * the transparent color with a particular RGB value, or drop tRNS entirely.
  187456. * IOW, a future version of the library may make the transformations flag
  187457. * a bit more fine-grained, with separate bits for each of these three
  187458. * functions.
  187459. *
  187460. * More to the point, these functions make it obvious what libpng will be
  187461. * doing, whereas "expand" can (and does) mean any number of things.
  187462. *
  187463. * GRP 20060307: In libpng-1.4.0, png_set_gray_1_2_4_to_8() was modified
  187464. * to expand only the sample depth but not to expand the tRNS to alpha.
  187465. */
  187466. /* Expand paletted images to RGB. */
  187467. void PNGAPI
  187468. png_set_palette_to_rgb(png_structp png_ptr)
  187469. {
  187470. png_debug(1, "in png_set_palette_to_rgb\n");
  187471. if(png_ptr == NULL) return;
  187472. png_ptr->transformations |= (PNG_EXPAND | PNG_EXPAND_tRNS);
  187473. #ifdef PNG_WARN_UNINITIALIZED_ROW
  187474. png_ptr->flags &= !(PNG_FLAG_ROW_INIT);
  187475. png_ptr->flags &= ~PNG_FLAG_ROW_INIT;
  187476. #endif
  187477. }
  187478. #if !defined(PNG_1_0_X)
  187479. /* Expand grayscale images of less than 8-bit depth to 8 bits. */
  187480. void PNGAPI
  187481. png_set_expand_gray_1_2_4_to_8(png_structp png_ptr)
  187482. {
  187483. png_debug(1, "in png_set_expand_gray_1_2_4_to_8\n");
  187484. if(png_ptr == NULL) return;
  187485. png_ptr->transformations |= PNG_EXPAND;
  187486. #ifdef PNG_WARN_UNINITIALIZED_ROW
  187487. png_ptr->flags &= ~PNG_FLAG_ROW_INIT;
  187488. #endif
  187489. }
  187490. #endif
  187491. #if defined(PNG_1_0_X) || defined(PNG_1_2_X)
  187492. /* Expand grayscale images of less than 8-bit depth to 8 bits. */
  187493. /* Deprecated as of libpng-1.2.9 */
  187494. void PNGAPI
  187495. png_set_gray_1_2_4_to_8(png_structp png_ptr)
  187496. {
  187497. png_debug(1, "in png_set_gray_1_2_4_to_8\n");
  187498. if(png_ptr == NULL) return;
  187499. png_ptr->transformations |= (PNG_EXPAND | PNG_EXPAND_tRNS);
  187500. }
  187501. #endif
  187502. /* Expand tRNS chunks to alpha channels. */
  187503. void PNGAPI
  187504. png_set_tRNS_to_alpha(png_structp png_ptr)
  187505. {
  187506. png_debug(1, "in png_set_tRNS_to_alpha\n");
  187507. png_ptr->transformations |= (PNG_EXPAND | PNG_EXPAND_tRNS);
  187508. #ifdef PNG_WARN_UNINITIALIZED_ROW
  187509. png_ptr->flags &= ~PNG_FLAG_ROW_INIT;
  187510. #endif
  187511. }
  187512. #endif /* defined(PNG_READ_EXPAND_SUPPORTED) */
  187513. #if defined(PNG_READ_GRAY_TO_RGB_SUPPORTED)
  187514. void PNGAPI
  187515. png_set_gray_to_rgb(png_structp png_ptr)
  187516. {
  187517. png_debug(1, "in png_set_gray_to_rgb\n");
  187518. png_ptr->transformations |= PNG_GRAY_TO_RGB;
  187519. #ifdef PNG_WARN_UNINITIALIZED_ROW
  187520. png_ptr->flags &= ~PNG_FLAG_ROW_INIT;
  187521. #endif
  187522. }
  187523. #endif
  187524. #if defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
  187525. #if defined(PNG_FLOATING_POINT_SUPPORTED)
  187526. /* Convert a RGB image to a grayscale of the same width. This allows us,
  187527. * for example, to convert a 24 bpp RGB image into an 8 bpp grayscale image.
  187528. */
  187529. void PNGAPI
  187530. png_set_rgb_to_gray(png_structp png_ptr, int error_action, double red,
  187531. double green)
  187532. {
  187533. int red_fixed = (int)((float)red*100000.0 + 0.5);
  187534. int green_fixed = (int)((float)green*100000.0 + 0.5);
  187535. if(png_ptr == NULL) return;
  187536. png_set_rgb_to_gray_fixed(png_ptr, error_action, red_fixed, green_fixed);
  187537. }
  187538. #endif
  187539. void PNGAPI
  187540. png_set_rgb_to_gray_fixed(png_structp png_ptr, int error_action,
  187541. png_fixed_point red, png_fixed_point green)
  187542. {
  187543. png_debug(1, "in png_set_rgb_to_gray\n");
  187544. if(png_ptr == NULL) return;
  187545. switch(error_action)
  187546. {
  187547. case 1: png_ptr->transformations |= PNG_RGB_TO_GRAY;
  187548. break;
  187549. case 2: png_ptr->transformations |= PNG_RGB_TO_GRAY_WARN;
  187550. break;
  187551. case 3: png_ptr->transformations |= PNG_RGB_TO_GRAY_ERR;
  187552. }
  187553. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  187554. #if defined(PNG_READ_EXPAND_SUPPORTED)
  187555. png_ptr->transformations |= PNG_EXPAND;
  187556. #else
  187557. {
  187558. png_warning(png_ptr, "Cannot do RGB_TO_GRAY without EXPAND_SUPPORTED.");
  187559. png_ptr->transformations &= ~PNG_RGB_TO_GRAY;
  187560. }
  187561. #endif
  187562. {
  187563. png_uint_16 red_int, green_int;
  187564. if(red < 0 || green < 0)
  187565. {
  187566. red_int = 6968; /* .212671 * 32768 + .5 */
  187567. green_int = 23434; /* .715160 * 32768 + .5 */
  187568. }
  187569. else if(red + green < 100000L)
  187570. {
  187571. red_int = (png_uint_16)(((png_uint_32)red*32768L)/100000L);
  187572. green_int = (png_uint_16)(((png_uint_32)green*32768L)/100000L);
  187573. }
  187574. else
  187575. {
  187576. png_warning(png_ptr, "ignoring out of range rgb_to_gray coefficients");
  187577. red_int = 6968;
  187578. green_int = 23434;
  187579. }
  187580. png_ptr->rgb_to_gray_red_coeff = red_int;
  187581. png_ptr->rgb_to_gray_green_coeff = green_int;
  187582. png_ptr->rgb_to_gray_blue_coeff = (png_uint_16)(32768-red_int-green_int);
  187583. }
  187584. }
  187585. #endif
  187586. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED) || \
  187587. defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED) || \
  187588. defined(PNG_LEGACY_SUPPORTED)
  187589. void PNGAPI
  187590. png_set_read_user_transform_fn(png_structp png_ptr, png_user_transform_ptr
  187591. read_user_transform_fn)
  187592. {
  187593. png_debug(1, "in png_set_read_user_transform_fn\n");
  187594. if(png_ptr == NULL) return;
  187595. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED)
  187596. png_ptr->transformations |= PNG_USER_TRANSFORM;
  187597. png_ptr->read_user_transform_fn = read_user_transform_fn;
  187598. #endif
  187599. #ifdef PNG_LEGACY_SUPPORTED
  187600. if(read_user_transform_fn)
  187601. png_warning(png_ptr,
  187602. "This version of libpng does not support user transforms");
  187603. #endif
  187604. }
  187605. #endif
  187606. /* Initialize everything needed for the read. This includes modifying
  187607. * the palette.
  187608. */
  187609. void /* PRIVATE */
  187610. png_init_read_transformations(png_structp png_ptr)
  187611. {
  187612. png_debug(1, "in png_init_read_transformations\n");
  187613. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  187614. if(png_ptr != NULL)
  187615. #endif
  187616. {
  187617. #if defined(PNG_READ_BACKGROUND_SUPPORTED) || defined(PNG_READ_SHIFT_SUPPORTED) \
  187618. || defined(PNG_READ_GAMMA_SUPPORTED)
  187619. int color_type = png_ptr->color_type;
  187620. #endif
  187621. #if defined(PNG_READ_EXPAND_SUPPORTED) && defined(PNG_READ_BACKGROUND_SUPPORTED)
  187622. #if defined(PNG_READ_GRAY_TO_RGB_SUPPORTED)
  187623. /* Detect gray background and attempt to enable optimization
  187624. * for gray --> RGB case */
  187625. /* Note: if PNG_BACKGROUND_EXPAND is set and color_type is either RGB or
  187626. * RGB_ALPHA (in which case need_expand is superfluous anyway), the
  187627. * background color might actually be gray yet not be flagged as such.
  187628. * This is not a problem for the current code, which uses
  187629. * PNG_BACKGROUND_IS_GRAY only to decide when to do the
  187630. * png_do_gray_to_rgb() transformation.
  187631. */
  187632. if ((png_ptr->transformations & PNG_BACKGROUND_EXPAND) &&
  187633. !(color_type & PNG_COLOR_MASK_COLOR))
  187634. {
  187635. png_ptr->mode |= PNG_BACKGROUND_IS_GRAY;
  187636. } else if ((png_ptr->transformations & PNG_BACKGROUND) &&
  187637. !(png_ptr->transformations & PNG_BACKGROUND_EXPAND) &&
  187638. (png_ptr->transformations & PNG_GRAY_TO_RGB) &&
  187639. png_ptr->background.red == png_ptr->background.green &&
  187640. png_ptr->background.red == png_ptr->background.blue)
  187641. {
  187642. png_ptr->mode |= PNG_BACKGROUND_IS_GRAY;
  187643. png_ptr->background.gray = png_ptr->background.red;
  187644. }
  187645. #endif
  187646. if ((png_ptr->transformations & PNG_BACKGROUND_EXPAND) &&
  187647. (png_ptr->transformations & PNG_EXPAND))
  187648. {
  187649. if (!(color_type & PNG_COLOR_MASK_COLOR)) /* i.e., GRAY or GRAY_ALPHA */
  187650. {
  187651. /* expand background and tRNS chunks */
  187652. switch (png_ptr->bit_depth)
  187653. {
  187654. case 1:
  187655. png_ptr->background.gray *= (png_uint_16)0xff;
  187656. png_ptr->background.red = png_ptr->background.green
  187657. = png_ptr->background.blue = png_ptr->background.gray;
  187658. if (!(png_ptr->transformations & PNG_EXPAND_tRNS))
  187659. {
  187660. png_ptr->trans_values.gray *= (png_uint_16)0xff;
  187661. png_ptr->trans_values.red = png_ptr->trans_values.green
  187662. = png_ptr->trans_values.blue = png_ptr->trans_values.gray;
  187663. }
  187664. break;
  187665. case 2:
  187666. png_ptr->background.gray *= (png_uint_16)0x55;
  187667. png_ptr->background.red = png_ptr->background.green
  187668. = png_ptr->background.blue = png_ptr->background.gray;
  187669. if (!(png_ptr->transformations & PNG_EXPAND_tRNS))
  187670. {
  187671. png_ptr->trans_values.gray *= (png_uint_16)0x55;
  187672. png_ptr->trans_values.red = png_ptr->trans_values.green
  187673. = png_ptr->trans_values.blue = png_ptr->trans_values.gray;
  187674. }
  187675. break;
  187676. case 4:
  187677. png_ptr->background.gray *= (png_uint_16)0x11;
  187678. png_ptr->background.red = png_ptr->background.green
  187679. = png_ptr->background.blue = png_ptr->background.gray;
  187680. if (!(png_ptr->transformations & PNG_EXPAND_tRNS))
  187681. {
  187682. png_ptr->trans_values.gray *= (png_uint_16)0x11;
  187683. png_ptr->trans_values.red = png_ptr->trans_values.green
  187684. = png_ptr->trans_values.blue = png_ptr->trans_values.gray;
  187685. }
  187686. break;
  187687. case 8:
  187688. case 16:
  187689. png_ptr->background.red = png_ptr->background.green
  187690. = png_ptr->background.blue = png_ptr->background.gray;
  187691. break;
  187692. }
  187693. }
  187694. else if (color_type == PNG_COLOR_TYPE_PALETTE)
  187695. {
  187696. png_ptr->background.red =
  187697. png_ptr->palette[png_ptr->background.index].red;
  187698. png_ptr->background.green =
  187699. png_ptr->palette[png_ptr->background.index].green;
  187700. png_ptr->background.blue =
  187701. png_ptr->palette[png_ptr->background.index].blue;
  187702. #if defined(PNG_READ_INVERT_ALPHA_SUPPORTED)
  187703. if (png_ptr->transformations & PNG_INVERT_ALPHA)
  187704. {
  187705. #if defined(PNG_READ_EXPAND_SUPPORTED)
  187706. if (!(png_ptr->transformations & PNG_EXPAND_tRNS))
  187707. #endif
  187708. {
  187709. /* invert the alpha channel (in tRNS) unless the pixels are
  187710. going to be expanded, in which case leave it for later */
  187711. int i,istop;
  187712. istop=(int)png_ptr->num_trans;
  187713. for (i=0; i<istop; i++)
  187714. png_ptr->trans[i] = (png_byte)(255 - png_ptr->trans[i]);
  187715. }
  187716. }
  187717. #endif
  187718. }
  187719. }
  187720. #endif
  187721. #if defined(PNG_READ_BACKGROUND_SUPPORTED) && defined(PNG_READ_GAMMA_SUPPORTED)
  187722. png_ptr->background_1 = png_ptr->background;
  187723. #endif
  187724. #if defined(PNG_READ_GAMMA_SUPPORTED) && defined(PNG_FLOATING_POINT_SUPPORTED)
  187725. if ((color_type == PNG_COLOR_TYPE_PALETTE && png_ptr->num_trans != 0)
  187726. && (fabs(png_ptr->screen_gamma * png_ptr->gamma - 1.0)
  187727. < PNG_GAMMA_THRESHOLD))
  187728. {
  187729. int i,k;
  187730. k=0;
  187731. for (i=0; i<png_ptr->num_trans; i++)
  187732. {
  187733. if (png_ptr->trans[i] != 0 && png_ptr->trans[i] != 0xff)
  187734. k=1; /* partial transparency is present */
  187735. }
  187736. if (k == 0)
  187737. png_ptr->transformations &= (~PNG_GAMMA);
  187738. }
  187739. if ((png_ptr->transformations & (PNG_GAMMA | PNG_RGB_TO_GRAY)) &&
  187740. png_ptr->gamma != 0.0)
  187741. {
  187742. png_build_gamma_table(png_ptr);
  187743. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  187744. if (png_ptr->transformations & PNG_BACKGROUND)
  187745. {
  187746. if (color_type == PNG_COLOR_TYPE_PALETTE)
  187747. {
  187748. /* could skip if no transparency and
  187749. */
  187750. png_color back, back_1;
  187751. png_colorp palette = png_ptr->palette;
  187752. int num_palette = png_ptr->num_palette;
  187753. int i;
  187754. if (png_ptr->background_gamma_type == PNG_BACKGROUND_GAMMA_FILE)
  187755. {
  187756. back.red = png_ptr->gamma_table[png_ptr->background.red];
  187757. back.green = png_ptr->gamma_table[png_ptr->background.green];
  187758. back.blue = png_ptr->gamma_table[png_ptr->background.blue];
  187759. back_1.red = png_ptr->gamma_to_1[png_ptr->background.red];
  187760. back_1.green = png_ptr->gamma_to_1[png_ptr->background.green];
  187761. back_1.blue = png_ptr->gamma_to_1[png_ptr->background.blue];
  187762. }
  187763. else
  187764. {
  187765. double g, gs;
  187766. switch (png_ptr->background_gamma_type)
  187767. {
  187768. case PNG_BACKGROUND_GAMMA_SCREEN:
  187769. g = (png_ptr->screen_gamma);
  187770. gs = 1.0;
  187771. break;
  187772. case PNG_BACKGROUND_GAMMA_FILE:
  187773. g = 1.0 / (png_ptr->gamma);
  187774. gs = 1.0 / (png_ptr->gamma * png_ptr->screen_gamma);
  187775. break;
  187776. case PNG_BACKGROUND_GAMMA_UNIQUE:
  187777. g = 1.0 / (png_ptr->background_gamma);
  187778. gs = 1.0 / (png_ptr->background_gamma *
  187779. png_ptr->screen_gamma);
  187780. break;
  187781. default:
  187782. g = 1.0; /* back_1 */
  187783. gs = 1.0; /* back */
  187784. }
  187785. if ( fabs(gs - 1.0) < PNG_GAMMA_THRESHOLD)
  187786. {
  187787. back.red = (png_byte)png_ptr->background.red;
  187788. back.green = (png_byte)png_ptr->background.green;
  187789. back.blue = (png_byte)png_ptr->background.blue;
  187790. }
  187791. else
  187792. {
  187793. back.red = (png_byte)(pow(
  187794. (double)png_ptr->background.red/255, gs) * 255.0 + .5);
  187795. back.green = (png_byte)(pow(
  187796. (double)png_ptr->background.green/255, gs) * 255.0 + .5);
  187797. back.blue = (png_byte)(pow(
  187798. (double)png_ptr->background.blue/255, gs) * 255.0 + .5);
  187799. }
  187800. back_1.red = (png_byte)(pow(
  187801. (double)png_ptr->background.red/255, g) * 255.0 + .5);
  187802. back_1.green = (png_byte)(pow(
  187803. (double)png_ptr->background.green/255, g) * 255.0 + .5);
  187804. back_1.blue = (png_byte)(pow(
  187805. (double)png_ptr->background.blue/255, g) * 255.0 + .5);
  187806. }
  187807. for (i = 0; i < num_palette; i++)
  187808. {
  187809. if (i < (int)png_ptr->num_trans && png_ptr->trans[i] != 0xff)
  187810. {
  187811. if (png_ptr->trans[i] == 0)
  187812. {
  187813. palette[i] = back;
  187814. }
  187815. else /* if (png_ptr->trans[i] != 0xff) */
  187816. {
  187817. png_byte v, w;
  187818. v = png_ptr->gamma_to_1[palette[i].red];
  187819. png_composite(w, v, png_ptr->trans[i], back_1.red);
  187820. palette[i].red = png_ptr->gamma_from_1[w];
  187821. v = png_ptr->gamma_to_1[palette[i].green];
  187822. png_composite(w, v, png_ptr->trans[i], back_1.green);
  187823. palette[i].green = png_ptr->gamma_from_1[w];
  187824. v = png_ptr->gamma_to_1[palette[i].blue];
  187825. png_composite(w, v, png_ptr->trans[i], back_1.blue);
  187826. palette[i].blue = png_ptr->gamma_from_1[w];
  187827. }
  187828. }
  187829. else
  187830. {
  187831. palette[i].red = png_ptr->gamma_table[palette[i].red];
  187832. palette[i].green = png_ptr->gamma_table[palette[i].green];
  187833. palette[i].blue = png_ptr->gamma_table[palette[i].blue];
  187834. }
  187835. }
  187836. }
  187837. /* if (png_ptr->background_gamma_type!=PNG_BACKGROUND_GAMMA_UNKNOWN) */
  187838. else
  187839. /* color_type != PNG_COLOR_TYPE_PALETTE */
  187840. {
  187841. double m = (double)(((png_uint_32)1 << png_ptr->bit_depth) - 1);
  187842. double g = 1.0;
  187843. double gs = 1.0;
  187844. switch (png_ptr->background_gamma_type)
  187845. {
  187846. case PNG_BACKGROUND_GAMMA_SCREEN:
  187847. g = (png_ptr->screen_gamma);
  187848. gs = 1.0;
  187849. break;
  187850. case PNG_BACKGROUND_GAMMA_FILE:
  187851. g = 1.0 / (png_ptr->gamma);
  187852. gs = 1.0 / (png_ptr->gamma * png_ptr->screen_gamma);
  187853. break;
  187854. case PNG_BACKGROUND_GAMMA_UNIQUE:
  187855. g = 1.0 / (png_ptr->background_gamma);
  187856. gs = 1.0 / (png_ptr->background_gamma *
  187857. png_ptr->screen_gamma);
  187858. break;
  187859. }
  187860. png_ptr->background_1.gray = (png_uint_16)(pow(
  187861. (double)png_ptr->background.gray / m, g) * m + .5);
  187862. png_ptr->background.gray = (png_uint_16)(pow(
  187863. (double)png_ptr->background.gray / m, gs) * m + .5);
  187864. if ((png_ptr->background.red != png_ptr->background.green) ||
  187865. (png_ptr->background.red != png_ptr->background.blue) ||
  187866. (png_ptr->background.red != png_ptr->background.gray))
  187867. {
  187868. /* RGB or RGBA with color background */
  187869. png_ptr->background_1.red = (png_uint_16)(pow(
  187870. (double)png_ptr->background.red / m, g) * m + .5);
  187871. png_ptr->background_1.green = (png_uint_16)(pow(
  187872. (double)png_ptr->background.green / m, g) * m + .5);
  187873. png_ptr->background_1.blue = (png_uint_16)(pow(
  187874. (double)png_ptr->background.blue / m, g) * m + .5);
  187875. png_ptr->background.red = (png_uint_16)(pow(
  187876. (double)png_ptr->background.red / m, gs) * m + .5);
  187877. png_ptr->background.green = (png_uint_16)(pow(
  187878. (double)png_ptr->background.green / m, gs) * m + .5);
  187879. png_ptr->background.blue = (png_uint_16)(pow(
  187880. (double)png_ptr->background.blue / m, gs) * m + .5);
  187881. }
  187882. else
  187883. {
  187884. /* GRAY, GRAY ALPHA, RGB, or RGBA with gray background */
  187885. png_ptr->background_1.red = png_ptr->background_1.green
  187886. = png_ptr->background_1.blue = png_ptr->background_1.gray;
  187887. png_ptr->background.red = png_ptr->background.green
  187888. = png_ptr->background.blue = png_ptr->background.gray;
  187889. }
  187890. }
  187891. }
  187892. else
  187893. /* transformation does not include PNG_BACKGROUND */
  187894. #endif /* PNG_READ_BACKGROUND_SUPPORTED */
  187895. if (color_type == PNG_COLOR_TYPE_PALETTE)
  187896. {
  187897. png_colorp palette = png_ptr->palette;
  187898. int num_palette = png_ptr->num_palette;
  187899. int i;
  187900. for (i = 0; i < num_palette; i++)
  187901. {
  187902. palette[i].red = png_ptr->gamma_table[palette[i].red];
  187903. palette[i].green = png_ptr->gamma_table[palette[i].green];
  187904. palette[i].blue = png_ptr->gamma_table[palette[i].blue];
  187905. }
  187906. }
  187907. }
  187908. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  187909. else
  187910. #endif
  187911. #endif /* PNG_READ_GAMMA_SUPPORTED && PNG_FLOATING_POINT_SUPPORTED */
  187912. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  187913. /* No GAMMA transformation */
  187914. if ((png_ptr->transformations & PNG_BACKGROUND) &&
  187915. (color_type == PNG_COLOR_TYPE_PALETTE))
  187916. {
  187917. int i;
  187918. int istop = (int)png_ptr->num_trans;
  187919. png_color back;
  187920. png_colorp palette = png_ptr->palette;
  187921. back.red = (png_byte)png_ptr->background.red;
  187922. back.green = (png_byte)png_ptr->background.green;
  187923. back.blue = (png_byte)png_ptr->background.blue;
  187924. for (i = 0; i < istop; i++)
  187925. {
  187926. if (png_ptr->trans[i] == 0)
  187927. {
  187928. palette[i] = back;
  187929. }
  187930. else if (png_ptr->trans[i] != 0xff)
  187931. {
  187932. /* The png_composite() macro is defined in png.h */
  187933. png_composite(palette[i].red, palette[i].red,
  187934. png_ptr->trans[i], back.red);
  187935. png_composite(palette[i].green, palette[i].green,
  187936. png_ptr->trans[i], back.green);
  187937. png_composite(palette[i].blue, palette[i].blue,
  187938. png_ptr->trans[i], back.blue);
  187939. }
  187940. }
  187941. }
  187942. #endif /* PNG_READ_BACKGROUND_SUPPORTED */
  187943. #if defined(PNG_READ_SHIFT_SUPPORTED)
  187944. if ((png_ptr->transformations & PNG_SHIFT) &&
  187945. (color_type == PNG_COLOR_TYPE_PALETTE))
  187946. {
  187947. png_uint_16 i;
  187948. png_uint_16 istop = png_ptr->num_palette;
  187949. int sr = 8 - png_ptr->sig_bit.red;
  187950. int sg = 8 - png_ptr->sig_bit.green;
  187951. int sb = 8 - png_ptr->sig_bit.blue;
  187952. if (sr < 0 || sr > 8)
  187953. sr = 0;
  187954. if (sg < 0 || sg > 8)
  187955. sg = 0;
  187956. if (sb < 0 || sb > 8)
  187957. sb = 0;
  187958. for (i = 0; i < istop; i++)
  187959. {
  187960. png_ptr->palette[i].red >>= sr;
  187961. png_ptr->palette[i].green >>= sg;
  187962. png_ptr->palette[i].blue >>= sb;
  187963. }
  187964. }
  187965. #endif /* PNG_READ_SHIFT_SUPPORTED */
  187966. }
  187967. #if !defined(PNG_READ_GAMMA_SUPPORTED) && !defined(PNG_READ_SHIFT_SUPPORTED) \
  187968. && !defined(PNG_READ_BACKGROUND_SUPPORTED)
  187969. if(png_ptr)
  187970. return;
  187971. #endif
  187972. }
  187973. /* Modify the info structure to reflect the transformations. The
  187974. * info should be updated so a PNG file could be written with it,
  187975. * assuming the transformations result in valid PNG data.
  187976. */
  187977. void /* PRIVATE */
  187978. png_read_transform_info(png_structp png_ptr, png_infop info_ptr)
  187979. {
  187980. png_debug(1, "in png_read_transform_info\n");
  187981. #if defined(PNG_READ_EXPAND_SUPPORTED)
  187982. if (png_ptr->transformations & PNG_EXPAND)
  187983. {
  187984. if (info_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  187985. {
  187986. if (png_ptr->num_trans && (png_ptr->transformations & PNG_EXPAND_tRNS))
  187987. info_ptr->color_type = PNG_COLOR_TYPE_RGB_ALPHA;
  187988. else
  187989. info_ptr->color_type = PNG_COLOR_TYPE_RGB;
  187990. info_ptr->bit_depth = 8;
  187991. info_ptr->num_trans = 0;
  187992. }
  187993. else
  187994. {
  187995. if (png_ptr->num_trans)
  187996. {
  187997. if (png_ptr->transformations & PNG_EXPAND_tRNS)
  187998. info_ptr->color_type |= PNG_COLOR_MASK_ALPHA;
  187999. else
  188000. info_ptr->color_type |= PNG_COLOR_MASK_COLOR;
  188001. }
  188002. if (info_ptr->bit_depth < 8)
  188003. info_ptr->bit_depth = 8;
  188004. info_ptr->num_trans = 0;
  188005. }
  188006. }
  188007. #endif
  188008. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  188009. if (png_ptr->transformations & PNG_BACKGROUND)
  188010. {
  188011. info_ptr->color_type &= ~PNG_COLOR_MASK_ALPHA;
  188012. info_ptr->num_trans = 0;
  188013. info_ptr->background = png_ptr->background;
  188014. }
  188015. #endif
  188016. #if defined(PNG_READ_GAMMA_SUPPORTED)
  188017. if (png_ptr->transformations & PNG_GAMMA)
  188018. {
  188019. #ifdef PNG_FLOATING_POINT_SUPPORTED
  188020. info_ptr->gamma = png_ptr->gamma;
  188021. #endif
  188022. #ifdef PNG_FIXED_POINT_SUPPORTED
  188023. info_ptr->int_gamma = png_ptr->int_gamma;
  188024. #endif
  188025. }
  188026. #endif
  188027. #if defined(PNG_READ_16_TO_8_SUPPORTED)
  188028. if ((png_ptr->transformations & PNG_16_TO_8) && (info_ptr->bit_depth == 16))
  188029. info_ptr->bit_depth = 8;
  188030. #endif
  188031. #if defined(PNG_READ_GRAY_TO_RGB_SUPPORTED)
  188032. if (png_ptr->transformations & PNG_GRAY_TO_RGB)
  188033. info_ptr->color_type |= PNG_COLOR_MASK_COLOR;
  188034. #endif
  188035. #if defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
  188036. if (png_ptr->transformations & PNG_RGB_TO_GRAY)
  188037. info_ptr->color_type &= ~PNG_COLOR_MASK_COLOR;
  188038. #endif
  188039. #if defined(PNG_READ_DITHER_SUPPORTED)
  188040. if (png_ptr->transformations & PNG_DITHER)
  188041. {
  188042. if (((info_ptr->color_type == PNG_COLOR_TYPE_RGB) ||
  188043. (info_ptr->color_type == PNG_COLOR_TYPE_RGB_ALPHA)) &&
  188044. png_ptr->palette_lookup && info_ptr->bit_depth == 8)
  188045. {
  188046. info_ptr->color_type = PNG_COLOR_TYPE_PALETTE;
  188047. }
  188048. }
  188049. #endif
  188050. #if defined(PNG_READ_PACK_SUPPORTED)
  188051. if ((png_ptr->transformations & PNG_PACK) && (info_ptr->bit_depth < 8))
  188052. info_ptr->bit_depth = 8;
  188053. #endif
  188054. if (info_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  188055. info_ptr->channels = 1;
  188056. else if (info_ptr->color_type & PNG_COLOR_MASK_COLOR)
  188057. info_ptr->channels = 3;
  188058. else
  188059. info_ptr->channels = 1;
  188060. #if defined(PNG_READ_STRIP_ALPHA_SUPPORTED)
  188061. if (png_ptr->flags & PNG_FLAG_STRIP_ALPHA)
  188062. info_ptr->color_type &= ~PNG_COLOR_MASK_ALPHA;
  188063. #endif
  188064. if (info_ptr->color_type & PNG_COLOR_MASK_ALPHA)
  188065. info_ptr->channels++;
  188066. #if defined(PNG_READ_FILLER_SUPPORTED)
  188067. /* STRIP_ALPHA and FILLER allowed: MASK_ALPHA bit stripped above */
  188068. if ((png_ptr->transformations & PNG_FILLER) &&
  188069. ((info_ptr->color_type == PNG_COLOR_TYPE_RGB) ||
  188070. (info_ptr->color_type == PNG_COLOR_TYPE_GRAY)))
  188071. {
  188072. info_ptr->channels++;
  188073. /* if adding a true alpha channel not just filler */
  188074. #if !defined(PNG_1_0_X)
  188075. if (png_ptr->transformations & PNG_ADD_ALPHA)
  188076. info_ptr->color_type |= PNG_COLOR_MASK_ALPHA;
  188077. #endif
  188078. }
  188079. #endif
  188080. #if defined(PNG_USER_TRANSFORM_PTR_SUPPORTED) && \
  188081. defined(PNG_READ_USER_TRANSFORM_SUPPORTED)
  188082. if(png_ptr->transformations & PNG_USER_TRANSFORM)
  188083. {
  188084. if(info_ptr->bit_depth < png_ptr->user_transform_depth)
  188085. info_ptr->bit_depth = png_ptr->user_transform_depth;
  188086. if(info_ptr->channels < png_ptr->user_transform_channels)
  188087. info_ptr->channels = png_ptr->user_transform_channels;
  188088. }
  188089. #endif
  188090. info_ptr->pixel_depth = (png_byte)(info_ptr->channels *
  188091. info_ptr->bit_depth);
  188092. info_ptr->rowbytes = PNG_ROWBYTES(info_ptr->pixel_depth,info_ptr->width);
  188093. #if !defined(PNG_READ_EXPAND_SUPPORTED)
  188094. if(png_ptr)
  188095. return;
  188096. #endif
  188097. }
  188098. /* Transform the row. The order of transformations is significant,
  188099. * and is very touchy. If you add a transformation, take care to
  188100. * decide how it fits in with the other transformations here.
  188101. */
  188102. void /* PRIVATE */
  188103. png_do_read_transformations(png_structp png_ptr)
  188104. {
  188105. png_debug(1, "in png_do_read_transformations\n");
  188106. if (png_ptr->row_buf == NULL)
  188107. {
  188108. #if !defined(PNG_NO_STDIO) && !defined(_WIN32_WCE)
  188109. char msg[50];
  188110. png_snprintf2(msg, 50,
  188111. "NULL row buffer for row %ld, pass %d", png_ptr->row_number,
  188112. png_ptr->pass);
  188113. png_error(png_ptr, msg);
  188114. #else
  188115. png_error(png_ptr, "NULL row buffer");
  188116. #endif
  188117. }
  188118. #ifdef PNG_WARN_UNINITIALIZED_ROW
  188119. if (!(png_ptr->flags & PNG_FLAG_ROW_INIT))
  188120. /* Application has failed to call either png_read_start_image()
  188121. * or png_read_update_info() after setting transforms that expand
  188122. * pixels. This check added to libpng-1.2.19 */
  188123. #if (PNG_WARN_UNINITIALIZED_ROW==1)
  188124. png_error(png_ptr, "Uninitialized row");
  188125. #else
  188126. png_warning(png_ptr, "Uninitialized row");
  188127. #endif
  188128. #endif
  188129. #if defined(PNG_READ_EXPAND_SUPPORTED)
  188130. if (png_ptr->transformations & PNG_EXPAND)
  188131. {
  188132. if (png_ptr->row_info.color_type == PNG_COLOR_TYPE_PALETTE)
  188133. {
  188134. png_do_expand_palette(&(png_ptr->row_info), png_ptr->row_buf + 1,
  188135. png_ptr->palette, png_ptr->trans, png_ptr->num_trans);
  188136. }
  188137. else
  188138. {
  188139. if (png_ptr->num_trans &&
  188140. (png_ptr->transformations & PNG_EXPAND_tRNS))
  188141. png_do_expand(&(png_ptr->row_info), png_ptr->row_buf + 1,
  188142. &(png_ptr->trans_values));
  188143. else
  188144. png_do_expand(&(png_ptr->row_info), png_ptr->row_buf + 1,
  188145. NULL);
  188146. }
  188147. }
  188148. #endif
  188149. #if defined(PNG_READ_STRIP_ALPHA_SUPPORTED)
  188150. if (png_ptr->flags & PNG_FLAG_STRIP_ALPHA)
  188151. png_do_strip_filler(&(png_ptr->row_info), png_ptr->row_buf + 1,
  188152. PNG_FLAG_FILLER_AFTER | (png_ptr->flags & PNG_FLAG_STRIP_ALPHA));
  188153. #endif
  188154. #if defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
  188155. if (png_ptr->transformations & PNG_RGB_TO_GRAY)
  188156. {
  188157. int rgb_error =
  188158. png_do_rgb_to_gray(png_ptr, &(png_ptr->row_info), png_ptr->row_buf + 1);
  188159. if(rgb_error)
  188160. {
  188161. png_ptr->rgb_to_gray_status=1;
  188162. if((png_ptr->transformations & PNG_RGB_TO_GRAY) ==
  188163. PNG_RGB_TO_GRAY_WARN)
  188164. png_warning(png_ptr, "png_do_rgb_to_gray found nongray pixel");
  188165. if((png_ptr->transformations & PNG_RGB_TO_GRAY) ==
  188166. PNG_RGB_TO_GRAY_ERR)
  188167. png_error(png_ptr, "png_do_rgb_to_gray found nongray pixel");
  188168. }
  188169. }
  188170. #endif
  188171. /*
  188172. From Andreas Dilger e-mail to png-implement, 26 March 1998:
  188173. In most cases, the "simple transparency" should be done prior to doing
  188174. gray-to-RGB, or you will have to test 3x as many bytes to check if a
  188175. pixel is transparent. You would also need to make sure that the
  188176. transparency information is upgraded to RGB.
  188177. To summarize, the current flow is:
  188178. - Gray + simple transparency -> compare 1 or 2 gray bytes and composite
  188179. with background "in place" if transparent,
  188180. convert to RGB if necessary
  188181. - Gray + alpha -> composite with gray background and remove alpha bytes,
  188182. convert to RGB if necessary
  188183. To support RGB backgrounds for gray images we need:
  188184. - Gray + simple transparency -> convert to RGB + simple transparency, compare
  188185. 3 or 6 bytes and composite with background
  188186. "in place" if transparent (3x compare/pixel
  188187. compared to doing composite with gray bkgrnd)
  188188. - Gray + alpha -> convert to RGB + alpha, composite with background and
  188189. remove alpha bytes (3x float operations/pixel
  188190. compared with composite on gray background)
  188191. Greg's change will do this. The reason it wasn't done before is for
  188192. performance, as this increases the per-pixel operations. If we would check
  188193. in advance if the background was gray or RGB, and position the gray-to-RGB
  188194. transform appropriately, then it would save a lot of work/time.
  188195. */
  188196. #if defined(PNG_READ_GRAY_TO_RGB_SUPPORTED)
  188197. /* if gray -> RGB, do so now only if background is non-gray; else do later
  188198. * for performance reasons */
  188199. if ((png_ptr->transformations & PNG_GRAY_TO_RGB) &&
  188200. !(png_ptr->mode & PNG_BACKGROUND_IS_GRAY))
  188201. png_do_gray_to_rgb(&(png_ptr->row_info), png_ptr->row_buf + 1);
  188202. #endif
  188203. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  188204. if ((png_ptr->transformations & PNG_BACKGROUND) &&
  188205. ((png_ptr->num_trans != 0 ) ||
  188206. (png_ptr->color_type & PNG_COLOR_MASK_ALPHA)))
  188207. png_do_background(&(png_ptr->row_info), png_ptr->row_buf + 1,
  188208. &(png_ptr->trans_values), &(png_ptr->background)
  188209. #if defined(PNG_READ_GAMMA_SUPPORTED)
  188210. , &(png_ptr->background_1),
  188211. png_ptr->gamma_table, png_ptr->gamma_from_1,
  188212. png_ptr->gamma_to_1, png_ptr->gamma_16_table,
  188213. png_ptr->gamma_16_from_1, png_ptr->gamma_16_to_1,
  188214. png_ptr->gamma_shift
  188215. #endif
  188216. );
  188217. #endif
  188218. #if defined(PNG_READ_GAMMA_SUPPORTED)
  188219. if ((png_ptr->transformations & PNG_GAMMA) &&
  188220. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  188221. !((png_ptr->transformations & PNG_BACKGROUND) &&
  188222. ((png_ptr->num_trans != 0) ||
  188223. (png_ptr->color_type & PNG_COLOR_MASK_ALPHA))) &&
  188224. #endif
  188225. (png_ptr->color_type != PNG_COLOR_TYPE_PALETTE))
  188226. png_do_gamma(&(png_ptr->row_info), png_ptr->row_buf + 1,
  188227. png_ptr->gamma_table, png_ptr->gamma_16_table,
  188228. png_ptr->gamma_shift);
  188229. #endif
  188230. #if defined(PNG_READ_16_TO_8_SUPPORTED)
  188231. if (png_ptr->transformations & PNG_16_TO_8)
  188232. png_do_chop(&(png_ptr->row_info), png_ptr->row_buf + 1);
  188233. #endif
  188234. #if defined(PNG_READ_DITHER_SUPPORTED)
  188235. if (png_ptr->transformations & PNG_DITHER)
  188236. {
  188237. png_do_dither((png_row_infop)&(png_ptr->row_info), png_ptr->row_buf + 1,
  188238. png_ptr->palette_lookup, png_ptr->dither_index);
  188239. if(png_ptr->row_info.rowbytes == (png_uint_32)0)
  188240. png_error(png_ptr, "png_do_dither returned rowbytes=0");
  188241. }
  188242. #endif
  188243. #if defined(PNG_READ_INVERT_SUPPORTED)
  188244. if (png_ptr->transformations & PNG_INVERT_MONO)
  188245. png_do_invert(&(png_ptr->row_info), png_ptr->row_buf + 1);
  188246. #endif
  188247. #if defined(PNG_READ_SHIFT_SUPPORTED)
  188248. if (png_ptr->transformations & PNG_SHIFT)
  188249. png_do_unshift(&(png_ptr->row_info), png_ptr->row_buf + 1,
  188250. &(png_ptr->shift));
  188251. #endif
  188252. #if defined(PNG_READ_PACK_SUPPORTED)
  188253. if (png_ptr->transformations & PNG_PACK)
  188254. png_do_unpack(&(png_ptr->row_info), png_ptr->row_buf + 1);
  188255. #endif
  188256. #if defined(PNG_READ_BGR_SUPPORTED)
  188257. if (png_ptr->transformations & PNG_BGR)
  188258. png_do_bgr(&(png_ptr->row_info), png_ptr->row_buf + 1);
  188259. #endif
  188260. #if defined(PNG_READ_PACKSWAP_SUPPORTED)
  188261. if (png_ptr->transformations & PNG_PACKSWAP)
  188262. png_do_packswap(&(png_ptr->row_info), png_ptr->row_buf + 1);
  188263. #endif
  188264. #if defined(PNG_READ_GRAY_TO_RGB_SUPPORTED)
  188265. /* if gray -> RGB, do so now only if we did not do so above */
  188266. if ((png_ptr->transformations & PNG_GRAY_TO_RGB) &&
  188267. (png_ptr->mode & PNG_BACKGROUND_IS_GRAY))
  188268. png_do_gray_to_rgb(&(png_ptr->row_info), png_ptr->row_buf + 1);
  188269. #endif
  188270. #if defined(PNG_READ_FILLER_SUPPORTED)
  188271. if (png_ptr->transformations & PNG_FILLER)
  188272. png_do_read_filler(&(png_ptr->row_info), png_ptr->row_buf + 1,
  188273. (png_uint_32)png_ptr->filler, png_ptr->flags);
  188274. #endif
  188275. #if defined(PNG_READ_INVERT_ALPHA_SUPPORTED)
  188276. if (png_ptr->transformations & PNG_INVERT_ALPHA)
  188277. png_do_read_invert_alpha(&(png_ptr->row_info), png_ptr->row_buf + 1);
  188278. #endif
  188279. #if defined(PNG_READ_SWAP_ALPHA_SUPPORTED)
  188280. if (png_ptr->transformations & PNG_SWAP_ALPHA)
  188281. png_do_read_swap_alpha(&(png_ptr->row_info), png_ptr->row_buf + 1);
  188282. #endif
  188283. #if defined(PNG_READ_SWAP_SUPPORTED)
  188284. if (png_ptr->transformations & PNG_SWAP_BYTES)
  188285. png_do_swap(&(png_ptr->row_info), png_ptr->row_buf + 1);
  188286. #endif
  188287. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED)
  188288. if (png_ptr->transformations & PNG_USER_TRANSFORM)
  188289. {
  188290. if(png_ptr->read_user_transform_fn != NULL)
  188291. (*(png_ptr->read_user_transform_fn)) /* user read transform function */
  188292. (png_ptr, /* png_ptr */
  188293. &(png_ptr->row_info), /* row_info: */
  188294. /* png_uint_32 width; width of row */
  188295. /* png_uint_32 rowbytes; number of bytes in row */
  188296. /* png_byte color_type; color type of pixels */
  188297. /* png_byte bit_depth; bit depth of samples */
  188298. /* png_byte channels; number of channels (1-4) */
  188299. /* png_byte pixel_depth; bits per pixel (depth*channels) */
  188300. png_ptr->row_buf + 1); /* start of pixel data for row */
  188301. #if defined(PNG_USER_TRANSFORM_PTR_SUPPORTED)
  188302. if(png_ptr->user_transform_depth)
  188303. png_ptr->row_info.bit_depth = png_ptr->user_transform_depth;
  188304. if(png_ptr->user_transform_channels)
  188305. png_ptr->row_info.channels = png_ptr->user_transform_channels;
  188306. #endif
  188307. png_ptr->row_info.pixel_depth = (png_byte)(png_ptr->row_info.bit_depth *
  188308. png_ptr->row_info.channels);
  188309. png_ptr->row_info.rowbytes = PNG_ROWBYTES(png_ptr->row_info.pixel_depth,
  188310. png_ptr->row_info.width);
  188311. }
  188312. #endif
  188313. }
  188314. #if defined(PNG_READ_PACK_SUPPORTED)
  188315. /* Unpack pixels of 1, 2, or 4 bits per pixel into 1 byte per pixel,
  188316. * without changing the actual values. Thus, if you had a row with
  188317. * a bit depth of 1, you would end up with bytes that only contained
  188318. * the numbers 0 or 1. If you would rather they contain 0 and 255, use
  188319. * png_do_shift() after this.
  188320. */
  188321. void /* PRIVATE */
  188322. png_do_unpack(png_row_infop row_info, png_bytep row)
  188323. {
  188324. png_debug(1, "in png_do_unpack\n");
  188325. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  188326. if (row != NULL && row_info != NULL && row_info->bit_depth < 8)
  188327. #else
  188328. if (row_info->bit_depth < 8)
  188329. #endif
  188330. {
  188331. png_uint_32 i;
  188332. png_uint_32 row_width=row_info->width;
  188333. switch (row_info->bit_depth)
  188334. {
  188335. case 1:
  188336. {
  188337. png_bytep sp = row + (png_size_t)((row_width - 1) >> 3);
  188338. png_bytep dp = row + (png_size_t)row_width - 1;
  188339. png_uint_32 shift = 7 - (int)((row_width + 7) & 0x07);
  188340. for (i = 0; i < row_width; i++)
  188341. {
  188342. *dp = (png_byte)((*sp >> shift) & 0x01);
  188343. if (shift == 7)
  188344. {
  188345. shift = 0;
  188346. sp--;
  188347. }
  188348. else
  188349. shift++;
  188350. dp--;
  188351. }
  188352. break;
  188353. }
  188354. case 2:
  188355. {
  188356. png_bytep sp = row + (png_size_t)((row_width - 1) >> 2);
  188357. png_bytep dp = row + (png_size_t)row_width - 1;
  188358. png_uint_32 shift = (int)((3 - ((row_width + 3) & 0x03)) << 1);
  188359. for (i = 0; i < row_width; i++)
  188360. {
  188361. *dp = (png_byte)((*sp >> shift) & 0x03);
  188362. if (shift == 6)
  188363. {
  188364. shift = 0;
  188365. sp--;
  188366. }
  188367. else
  188368. shift += 2;
  188369. dp--;
  188370. }
  188371. break;
  188372. }
  188373. case 4:
  188374. {
  188375. png_bytep sp = row + (png_size_t)((row_width - 1) >> 1);
  188376. png_bytep dp = row + (png_size_t)row_width - 1;
  188377. png_uint_32 shift = (int)((1 - ((row_width + 1) & 0x01)) << 2);
  188378. for (i = 0; i < row_width; i++)
  188379. {
  188380. *dp = (png_byte)((*sp >> shift) & 0x0f);
  188381. if (shift == 4)
  188382. {
  188383. shift = 0;
  188384. sp--;
  188385. }
  188386. else
  188387. shift = 4;
  188388. dp--;
  188389. }
  188390. break;
  188391. }
  188392. }
  188393. row_info->bit_depth = 8;
  188394. row_info->pixel_depth = (png_byte)(8 * row_info->channels);
  188395. row_info->rowbytes = row_width * row_info->channels;
  188396. }
  188397. }
  188398. #endif
  188399. #if defined(PNG_READ_SHIFT_SUPPORTED)
  188400. /* Reverse the effects of png_do_shift. This routine merely shifts the
  188401. * pixels back to their significant bits values. Thus, if you have
  188402. * a row of bit depth 8, but only 5 are significant, this will shift
  188403. * the values back to 0 through 31.
  188404. */
  188405. void /* PRIVATE */
  188406. png_do_unshift(png_row_infop row_info, png_bytep row, png_color_8p sig_bits)
  188407. {
  188408. png_debug(1, "in png_do_unshift\n");
  188409. if (
  188410. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  188411. row != NULL && row_info != NULL && sig_bits != NULL &&
  188412. #endif
  188413. row_info->color_type != PNG_COLOR_TYPE_PALETTE)
  188414. {
  188415. int shift[4];
  188416. int channels = 0;
  188417. int c;
  188418. png_uint_16 value = 0;
  188419. png_uint_32 row_width = row_info->width;
  188420. if (row_info->color_type & PNG_COLOR_MASK_COLOR)
  188421. {
  188422. shift[channels++] = row_info->bit_depth - sig_bits->red;
  188423. shift[channels++] = row_info->bit_depth - sig_bits->green;
  188424. shift[channels++] = row_info->bit_depth - sig_bits->blue;
  188425. }
  188426. else
  188427. {
  188428. shift[channels++] = row_info->bit_depth - sig_bits->gray;
  188429. }
  188430. if (row_info->color_type & PNG_COLOR_MASK_ALPHA)
  188431. {
  188432. shift[channels++] = row_info->bit_depth - sig_bits->alpha;
  188433. }
  188434. for (c = 0; c < channels; c++)
  188435. {
  188436. if (shift[c] <= 0)
  188437. shift[c] = 0;
  188438. else
  188439. value = 1;
  188440. }
  188441. if (!value)
  188442. return;
  188443. switch (row_info->bit_depth)
  188444. {
  188445. case 2:
  188446. {
  188447. png_bytep bp;
  188448. png_uint_32 i;
  188449. png_uint_32 istop = row_info->rowbytes;
  188450. for (bp = row, i = 0; i < istop; i++)
  188451. {
  188452. *bp >>= 1;
  188453. *bp++ &= 0x55;
  188454. }
  188455. break;
  188456. }
  188457. case 4:
  188458. {
  188459. png_bytep bp = row;
  188460. png_uint_32 i;
  188461. png_uint_32 istop = row_info->rowbytes;
  188462. png_byte mask = (png_byte)((((int)0xf0 >> shift[0]) & (int)0xf0) |
  188463. (png_byte)((int)0xf >> shift[0]));
  188464. for (i = 0; i < istop; i++)
  188465. {
  188466. *bp >>= shift[0];
  188467. *bp++ &= mask;
  188468. }
  188469. break;
  188470. }
  188471. case 8:
  188472. {
  188473. png_bytep bp = row;
  188474. png_uint_32 i;
  188475. png_uint_32 istop = row_width * channels;
  188476. for (i = 0; i < istop; i++)
  188477. {
  188478. *bp++ >>= shift[i%channels];
  188479. }
  188480. break;
  188481. }
  188482. case 16:
  188483. {
  188484. png_bytep bp = row;
  188485. png_uint_32 i;
  188486. png_uint_32 istop = channels * row_width;
  188487. for (i = 0; i < istop; i++)
  188488. {
  188489. value = (png_uint_16)((*bp << 8) + *(bp + 1));
  188490. value >>= shift[i%channels];
  188491. *bp++ = (png_byte)(value >> 8);
  188492. *bp++ = (png_byte)(value & 0xff);
  188493. }
  188494. break;
  188495. }
  188496. }
  188497. }
  188498. }
  188499. #endif
  188500. #if defined(PNG_READ_16_TO_8_SUPPORTED)
  188501. /* chop rows of bit depth 16 down to 8 */
  188502. void /* PRIVATE */
  188503. png_do_chop(png_row_infop row_info, png_bytep row)
  188504. {
  188505. png_debug(1, "in png_do_chop\n");
  188506. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  188507. if (row != NULL && row_info != NULL && row_info->bit_depth == 16)
  188508. #else
  188509. if (row_info->bit_depth == 16)
  188510. #endif
  188511. {
  188512. png_bytep sp = row;
  188513. png_bytep dp = row;
  188514. png_uint_32 i;
  188515. png_uint_32 istop = row_info->width * row_info->channels;
  188516. for (i = 0; i<istop; i++, sp += 2, dp++)
  188517. {
  188518. #if defined(PNG_READ_16_TO_8_ACCURATE_SCALE_SUPPORTED)
  188519. /* This does a more accurate scaling of the 16-bit color
  188520. * value, rather than a simple low-byte truncation.
  188521. *
  188522. * What the ideal calculation should be:
  188523. * *dp = (((((png_uint_32)(*sp) << 8) |
  188524. * (png_uint_32)(*(sp + 1))) * 255 + 127) / (png_uint_32)65535L;
  188525. *
  188526. * GRR: no, I think this is what it really should be:
  188527. * *dp = (((((png_uint_32)(*sp) << 8) |
  188528. * (png_uint_32)(*(sp + 1))) + 128L) / (png_uint_32)257L;
  188529. *
  188530. * GRR: here's the exact calculation with shifts:
  188531. * temp = (((png_uint_32)(*sp) << 8) | (png_uint_32)(*(sp + 1))) + 128L;
  188532. * *dp = (temp - (temp >> 8)) >> 8;
  188533. *
  188534. * Approximate calculation with shift/add instead of multiply/divide:
  188535. * *dp = ((((png_uint_32)(*sp) << 8) |
  188536. * (png_uint_32)((int)(*(sp + 1)) - *sp)) + 128) >> 8;
  188537. *
  188538. * What we actually do to avoid extra shifting and conversion:
  188539. */
  188540. *dp = *sp + ((((int)(*(sp + 1)) - *sp) > 128) ? 1 : 0);
  188541. #else
  188542. /* Simply discard the low order byte */
  188543. *dp = *sp;
  188544. #endif
  188545. }
  188546. row_info->bit_depth = 8;
  188547. row_info->pixel_depth = (png_byte)(8 * row_info->channels);
  188548. row_info->rowbytes = row_info->width * row_info->channels;
  188549. }
  188550. }
  188551. #endif
  188552. #if defined(PNG_READ_SWAP_ALPHA_SUPPORTED)
  188553. void /* PRIVATE */
  188554. png_do_read_swap_alpha(png_row_infop row_info, png_bytep row)
  188555. {
  188556. png_debug(1, "in png_do_read_swap_alpha\n");
  188557. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  188558. if (row != NULL && row_info != NULL)
  188559. #endif
  188560. {
  188561. png_uint_32 row_width = row_info->width;
  188562. if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  188563. {
  188564. /* This converts from RGBA to ARGB */
  188565. if (row_info->bit_depth == 8)
  188566. {
  188567. png_bytep sp = row + row_info->rowbytes;
  188568. png_bytep dp = sp;
  188569. png_byte save;
  188570. png_uint_32 i;
  188571. for (i = 0; i < row_width; i++)
  188572. {
  188573. save = *(--sp);
  188574. *(--dp) = *(--sp);
  188575. *(--dp) = *(--sp);
  188576. *(--dp) = *(--sp);
  188577. *(--dp) = save;
  188578. }
  188579. }
  188580. /* This converts from RRGGBBAA to AARRGGBB */
  188581. else
  188582. {
  188583. png_bytep sp = row + row_info->rowbytes;
  188584. png_bytep dp = sp;
  188585. png_byte save[2];
  188586. png_uint_32 i;
  188587. for (i = 0; i < row_width; i++)
  188588. {
  188589. save[0] = *(--sp);
  188590. save[1] = *(--sp);
  188591. *(--dp) = *(--sp);
  188592. *(--dp) = *(--sp);
  188593. *(--dp) = *(--sp);
  188594. *(--dp) = *(--sp);
  188595. *(--dp) = *(--sp);
  188596. *(--dp) = *(--sp);
  188597. *(--dp) = save[0];
  188598. *(--dp) = save[1];
  188599. }
  188600. }
  188601. }
  188602. else if (row_info->color_type == PNG_COLOR_TYPE_GRAY_ALPHA)
  188603. {
  188604. /* This converts from GA to AG */
  188605. if (row_info->bit_depth == 8)
  188606. {
  188607. png_bytep sp = row + row_info->rowbytes;
  188608. png_bytep dp = sp;
  188609. png_byte save;
  188610. png_uint_32 i;
  188611. for (i = 0; i < row_width; i++)
  188612. {
  188613. save = *(--sp);
  188614. *(--dp) = *(--sp);
  188615. *(--dp) = save;
  188616. }
  188617. }
  188618. /* This converts from GGAA to AAGG */
  188619. else
  188620. {
  188621. png_bytep sp = row + row_info->rowbytes;
  188622. png_bytep dp = sp;
  188623. png_byte save[2];
  188624. png_uint_32 i;
  188625. for (i = 0; i < row_width; i++)
  188626. {
  188627. save[0] = *(--sp);
  188628. save[1] = *(--sp);
  188629. *(--dp) = *(--sp);
  188630. *(--dp) = *(--sp);
  188631. *(--dp) = save[0];
  188632. *(--dp) = save[1];
  188633. }
  188634. }
  188635. }
  188636. }
  188637. }
  188638. #endif
  188639. #if defined(PNG_READ_INVERT_ALPHA_SUPPORTED)
  188640. void /* PRIVATE */
  188641. png_do_read_invert_alpha(png_row_infop row_info, png_bytep row)
  188642. {
  188643. png_debug(1, "in png_do_read_invert_alpha\n");
  188644. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  188645. if (row != NULL && row_info != NULL)
  188646. #endif
  188647. {
  188648. png_uint_32 row_width = row_info->width;
  188649. if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  188650. {
  188651. /* This inverts the alpha channel in RGBA */
  188652. if (row_info->bit_depth == 8)
  188653. {
  188654. png_bytep sp = row + row_info->rowbytes;
  188655. png_bytep dp = sp;
  188656. png_uint_32 i;
  188657. for (i = 0; i < row_width; i++)
  188658. {
  188659. *(--dp) = (png_byte)(255 - *(--sp));
  188660. /* This does nothing:
  188661. *(--dp) = *(--sp);
  188662. *(--dp) = *(--sp);
  188663. *(--dp) = *(--sp);
  188664. We can replace it with:
  188665. */
  188666. sp-=3;
  188667. dp=sp;
  188668. }
  188669. }
  188670. /* This inverts the alpha channel in RRGGBBAA */
  188671. else
  188672. {
  188673. png_bytep sp = row + row_info->rowbytes;
  188674. png_bytep dp = sp;
  188675. png_uint_32 i;
  188676. for (i = 0; i < row_width; i++)
  188677. {
  188678. *(--dp) = (png_byte)(255 - *(--sp));
  188679. *(--dp) = (png_byte)(255 - *(--sp));
  188680. /* This does nothing:
  188681. *(--dp) = *(--sp);
  188682. *(--dp) = *(--sp);
  188683. *(--dp) = *(--sp);
  188684. *(--dp) = *(--sp);
  188685. *(--dp) = *(--sp);
  188686. *(--dp) = *(--sp);
  188687. We can replace it with:
  188688. */
  188689. sp-=6;
  188690. dp=sp;
  188691. }
  188692. }
  188693. }
  188694. else if (row_info->color_type == PNG_COLOR_TYPE_GRAY_ALPHA)
  188695. {
  188696. /* This inverts the alpha channel in GA */
  188697. if (row_info->bit_depth == 8)
  188698. {
  188699. png_bytep sp = row + row_info->rowbytes;
  188700. png_bytep dp = sp;
  188701. png_uint_32 i;
  188702. for (i = 0; i < row_width; i++)
  188703. {
  188704. *(--dp) = (png_byte)(255 - *(--sp));
  188705. *(--dp) = *(--sp);
  188706. }
  188707. }
  188708. /* This inverts the alpha channel in GGAA */
  188709. else
  188710. {
  188711. png_bytep sp = row + row_info->rowbytes;
  188712. png_bytep dp = sp;
  188713. png_uint_32 i;
  188714. for (i = 0; i < row_width; i++)
  188715. {
  188716. *(--dp) = (png_byte)(255 - *(--sp));
  188717. *(--dp) = (png_byte)(255 - *(--sp));
  188718. /*
  188719. *(--dp) = *(--sp);
  188720. *(--dp) = *(--sp);
  188721. */
  188722. sp-=2;
  188723. dp=sp;
  188724. }
  188725. }
  188726. }
  188727. }
  188728. }
  188729. #endif
  188730. #if defined(PNG_READ_FILLER_SUPPORTED)
  188731. /* Add filler channel if we have RGB color */
  188732. void /* PRIVATE */
  188733. png_do_read_filler(png_row_infop row_info, png_bytep row,
  188734. png_uint_32 filler, png_uint_32 flags)
  188735. {
  188736. png_uint_32 i;
  188737. png_uint_32 row_width = row_info->width;
  188738. png_byte hi_filler = (png_byte)((filler>>8) & 0xff);
  188739. png_byte lo_filler = (png_byte)(filler & 0xff);
  188740. png_debug(1, "in png_do_read_filler\n");
  188741. if (
  188742. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  188743. row != NULL && row_info != NULL &&
  188744. #endif
  188745. row_info->color_type == PNG_COLOR_TYPE_GRAY)
  188746. {
  188747. if(row_info->bit_depth == 8)
  188748. {
  188749. /* This changes the data from G to GX */
  188750. if (flags & PNG_FLAG_FILLER_AFTER)
  188751. {
  188752. png_bytep sp = row + (png_size_t)row_width;
  188753. png_bytep dp = sp + (png_size_t)row_width;
  188754. for (i = 1; i < row_width; i++)
  188755. {
  188756. *(--dp) = lo_filler;
  188757. *(--dp) = *(--sp);
  188758. }
  188759. *(--dp) = lo_filler;
  188760. row_info->channels = 2;
  188761. row_info->pixel_depth = 16;
  188762. row_info->rowbytes = row_width * 2;
  188763. }
  188764. /* This changes the data from G to XG */
  188765. else
  188766. {
  188767. png_bytep sp = row + (png_size_t)row_width;
  188768. png_bytep dp = sp + (png_size_t)row_width;
  188769. for (i = 0; i < row_width; i++)
  188770. {
  188771. *(--dp) = *(--sp);
  188772. *(--dp) = lo_filler;
  188773. }
  188774. row_info->channels = 2;
  188775. row_info->pixel_depth = 16;
  188776. row_info->rowbytes = row_width * 2;
  188777. }
  188778. }
  188779. else if(row_info->bit_depth == 16)
  188780. {
  188781. /* This changes the data from GG to GGXX */
  188782. if (flags & PNG_FLAG_FILLER_AFTER)
  188783. {
  188784. png_bytep sp = row + (png_size_t)row_width * 2;
  188785. png_bytep dp = sp + (png_size_t)row_width * 2;
  188786. for (i = 1; i < row_width; i++)
  188787. {
  188788. *(--dp) = hi_filler;
  188789. *(--dp) = lo_filler;
  188790. *(--dp) = *(--sp);
  188791. *(--dp) = *(--sp);
  188792. }
  188793. *(--dp) = hi_filler;
  188794. *(--dp) = lo_filler;
  188795. row_info->channels = 2;
  188796. row_info->pixel_depth = 32;
  188797. row_info->rowbytes = row_width * 4;
  188798. }
  188799. /* This changes the data from GG to XXGG */
  188800. else
  188801. {
  188802. png_bytep sp = row + (png_size_t)row_width * 2;
  188803. png_bytep dp = sp + (png_size_t)row_width * 2;
  188804. for (i = 0; i < row_width; i++)
  188805. {
  188806. *(--dp) = *(--sp);
  188807. *(--dp) = *(--sp);
  188808. *(--dp) = hi_filler;
  188809. *(--dp) = lo_filler;
  188810. }
  188811. row_info->channels = 2;
  188812. row_info->pixel_depth = 32;
  188813. row_info->rowbytes = row_width * 4;
  188814. }
  188815. }
  188816. } /* COLOR_TYPE == GRAY */
  188817. else if (row_info->color_type == PNG_COLOR_TYPE_RGB)
  188818. {
  188819. if(row_info->bit_depth == 8)
  188820. {
  188821. /* This changes the data from RGB to RGBX */
  188822. if (flags & PNG_FLAG_FILLER_AFTER)
  188823. {
  188824. png_bytep sp = row + (png_size_t)row_width * 3;
  188825. png_bytep dp = sp + (png_size_t)row_width;
  188826. for (i = 1; i < row_width; i++)
  188827. {
  188828. *(--dp) = lo_filler;
  188829. *(--dp) = *(--sp);
  188830. *(--dp) = *(--sp);
  188831. *(--dp) = *(--sp);
  188832. }
  188833. *(--dp) = lo_filler;
  188834. row_info->channels = 4;
  188835. row_info->pixel_depth = 32;
  188836. row_info->rowbytes = row_width * 4;
  188837. }
  188838. /* This changes the data from RGB to XRGB */
  188839. else
  188840. {
  188841. png_bytep sp = row + (png_size_t)row_width * 3;
  188842. png_bytep dp = sp + (png_size_t)row_width;
  188843. for (i = 0; i < row_width; i++)
  188844. {
  188845. *(--dp) = *(--sp);
  188846. *(--dp) = *(--sp);
  188847. *(--dp) = *(--sp);
  188848. *(--dp) = lo_filler;
  188849. }
  188850. row_info->channels = 4;
  188851. row_info->pixel_depth = 32;
  188852. row_info->rowbytes = row_width * 4;
  188853. }
  188854. }
  188855. else if(row_info->bit_depth == 16)
  188856. {
  188857. /* This changes the data from RRGGBB to RRGGBBXX */
  188858. if (flags & PNG_FLAG_FILLER_AFTER)
  188859. {
  188860. png_bytep sp = row + (png_size_t)row_width * 6;
  188861. png_bytep dp = sp + (png_size_t)row_width * 2;
  188862. for (i = 1; i < row_width; i++)
  188863. {
  188864. *(--dp) = hi_filler;
  188865. *(--dp) = lo_filler;
  188866. *(--dp) = *(--sp);
  188867. *(--dp) = *(--sp);
  188868. *(--dp) = *(--sp);
  188869. *(--dp) = *(--sp);
  188870. *(--dp) = *(--sp);
  188871. *(--dp) = *(--sp);
  188872. }
  188873. *(--dp) = hi_filler;
  188874. *(--dp) = lo_filler;
  188875. row_info->channels = 4;
  188876. row_info->pixel_depth = 64;
  188877. row_info->rowbytes = row_width * 8;
  188878. }
  188879. /* This changes the data from RRGGBB to XXRRGGBB */
  188880. else
  188881. {
  188882. png_bytep sp = row + (png_size_t)row_width * 6;
  188883. png_bytep dp = sp + (png_size_t)row_width * 2;
  188884. for (i = 0; i < row_width; i++)
  188885. {
  188886. *(--dp) = *(--sp);
  188887. *(--dp) = *(--sp);
  188888. *(--dp) = *(--sp);
  188889. *(--dp) = *(--sp);
  188890. *(--dp) = *(--sp);
  188891. *(--dp) = *(--sp);
  188892. *(--dp) = hi_filler;
  188893. *(--dp) = lo_filler;
  188894. }
  188895. row_info->channels = 4;
  188896. row_info->pixel_depth = 64;
  188897. row_info->rowbytes = row_width * 8;
  188898. }
  188899. }
  188900. } /* COLOR_TYPE == RGB */
  188901. }
  188902. #endif
  188903. #if defined(PNG_READ_GRAY_TO_RGB_SUPPORTED)
  188904. /* expand grayscale files to RGB, with or without alpha */
  188905. void /* PRIVATE */
  188906. png_do_gray_to_rgb(png_row_infop row_info, png_bytep row)
  188907. {
  188908. png_uint_32 i;
  188909. png_uint_32 row_width = row_info->width;
  188910. png_debug(1, "in png_do_gray_to_rgb\n");
  188911. if (row_info->bit_depth >= 8 &&
  188912. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  188913. row != NULL && row_info != NULL &&
  188914. #endif
  188915. !(row_info->color_type & PNG_COLOR_MASK_COLOR))
  188916. {
  188917. if (row_info->color_type == PNG_COLOR_TYPE_GRAY)
  188918. {
  188919. if (row_info->bit_depth == 8)
  188920. {
  188921. png_bytep sp = row + (png_size_t)row_width - 1;
  188922. png_bytep dp = sp + (png_size_t)row_width * 2;
  188923. for (i = 0; i < row_width; i++)
  188924. {
  188925. *(dp--) = *sp;
  188926. *(dp--) = *sp;
  188927. *(dp--) = *(sp--);
  188928. }
  188929. }
  188930. else
  188931. {
  188932. png_bytep sp = row + (png_size_t)row_width * 2 - 1;
  188933. png_bytep dp = sp + (png_size_t)row_width * 4;
  188934. for (i = 0; i < row_width; i++)
  188935. {
  188936. *(dp--) = *sp;
  188937. *(dp--) = *(sp - 1);
  188938. *(dp--) = *sp;
  188939. *(dp--) = *(sp - 1);
  188940. *(dp--) = *(sp--);
  188941. *(dp--) = *(sp--);
  188942. }
  188943. }
  188944. }
  188945. else if (row_info->color_type == PNG_COLOR_TYPE_GRAY_ALPHA)
  188946. {
  188947. if (row_info->bit_depth == 8)
  188948. {
  188949. png_bytep sp = row + (png_size_t)row_width * 2 - 1;
  188950. png_bytep dp = sp + (png_size_t)row_width * 2;
  188951. for (i = 0; i < row_width; i++)
  188952. {
  188953. *(dp--) = *(sp--);
  188954. *(dp--) = *sp;
  188955. *(dp--) = *sp;
  188956. *(dp--) = *(sp--);
  188957. }
  188958. }
  188959. else
  188960. {
  188961. png_bytep sp = row + (png_size_t)row_width * 4 - 1;
  188962. png_bytep dp = sp + (png_size_t)row_width * 4;
  188963. for (i = 0; i < row_width; i++)
  188964. {
  188965. *(dp--) = *(sp--);
  188966. *(dp--) = *(sp--);
  188967. *(dp--) = *sp;
  188968. *(dp--) = *(sp - 1);
  188969. *(dp--) = *sp;
  188970. *(dp--) = *(sp - 1);
  188971. *(dp--) = *(sp--);
  188972. *(dp--) = *(sp--);
  188973. }
  188974. }
  188975. }
  188976. row_info->channels += (png_byte)2;
  188977. row_info->color_type |= PNG_COLOR_MASK_COLOR;
  188978. row_info->pixel_depth = (png_byte)(row_info->channels *
  188979. row_info->bit_depth);
  188980. row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,row_width);
  188981. }
  188982. }
  188983. #endif
  188984. #if defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
  188985. /* reduce RGB files to grayscale, with or without alpha
  188986. * using the equation given in Poynton's ColorFAQ at
  188987. * <http://www.inforamp.net/~poynton/>
  188988. * Copyright (c) 1998-01-04 Charles Poynton poynton at inforamp.net
  188989. *
  188990. * Y = 0.212671 * R + 0.715160 * G + 0.072169 * B
  188991. *
  188992. * We approximate this with
  188993. *
  188994. * Y = 0.21268 * R + 0.7151 * G + 0.07217 * B
  188995. *
  188996. * which can be expressed with integers as
  188997. *
  188998. * Y = (6969 * R + 23434 * G + 2365 * B)/32768
  188999. *
  189000. * The calculation is to be done in a linear colorspace.
  189001. *
  189002. * Other integer coefficents can be used via png_set_rgb_to_gray().
  189003. */
  189004. int /* PRIVATE */
  189005. png_do_rgb_to_gray(png_structp png_ptr, png_row_infop row_info, png_bytep row)
  189006. {
  189007. png_uint_32 i;
  189008. png_uint_32 row_width = row_info->width;
  189009. int rgb_error = 0;
  189010. png_debug(1, "in png_do_rgb_to_gray\n");
  189011. if (
  189012. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  189013. row != NULL && row_info != NULL &&
  189014. #endif
  189015. (row_info->color_type & PNG_COLOR_MASK_COLOR))
  189016. {
  189017. png_uint_32 rc = png_ptr->rgb_to_gray_red_coeff;
  189018. png_uint_32 gc = png_ptr->rgb_to_gray_green_coeff;
  189019. png_uint_32 bc = png_ptr->rgb_to_gray_blue_coeff;
  189020. if (row_info->color_type == PNG_COLOR_TYPE_RGB)
  189021. {
  189022. if (row_info->bit_depth == 8)
  189023. {
  189024. #if defined(PNG_READ_GAMMA_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
  189025. if (png_ptr->gamma_from_1 != NULL && png_ptr->gamma_to_1 != NULL)
  189026. {
  189027. png_bytep sp = row;
  189028. png_bytep dp = row;
  189029. for (i = 0; i < row_width; i++)
  189030. {
  189031. png_byte red = png_ptr->gamma_to_1[*(sp++)];
  189032. png_byte green = png_ptr->gamma_to_1[*(sp++)];
  189033. png_byte blue = png_ptr->gamma_to_1[*(sp++)];
  189034. if(red != green || red != blue)
  189035. {
  189036. rgb_error |= 1;
  189037. *(dp++) = png_ptr->gamma_from_1[
  189038. (rc*red+gc*green+bc*blue)>>15];
  189039. }
  189040. else
  189041. *(dp++) = *(sp-1);
  189042. }
  189043. }
  189044. else
  189045. #endif
  189046. {
  189047. png_bytep sp = row;
  189048. png_bytep dp = row;
  189049. for (i = 0; i < row_width; i++)
  189050. {
  189051. png_byte red = *(sp++);
  189052. png_byte green = *(sp++);
  189053. png_byte blue = *(sp++);
  189054. if(red != green || red != blue)
  189055. {
  189056. rgb_error |= 1;
  189057. *(dp++) = (png_byte)((rc*red+gc*green+bc*blue)>>15);
  189058. }
  189059. else
  189060. *(dp++) = *(sp-1);
  189061. }
  189062. }
  189063. }
  189064. else /* RGB bit_depth == 16 */
  189065. {
  189066. #if defined(PNG_READ_GAMMA_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
  189067. if (png_ptr->gamma_16_to_1 != NULL &&
  189068. png_ptr->gamma_16_from_1 != NULL)
  189069. {
  189070. png_bytep sp = row;
  189071. png_bytep dp = row;
  189072. for (i = 0; i < row_width; i++)
  189073. {
  189074. png_uint_16 red, green, blue, w;
  189075. red = (png_uint_16)(((*(sp))<<8) | *(sp+1)); sp+=2;
  189076. green = (png_uint_16)(((*(sp))<<8) | *(sp+1)); sp+=2;
  189077. blue = (png_uint_16)(((*(sp))<<8) | *(sp+1)); sp+=2;
  189078. if(red == green && red == blue)
  189079. w = red;
  189080. else
  189081. {
  189082. png_uint_16 red_1 = png_ptr->gamma_16_to_1[(red&0xff) >>
  189083. png_ptr->gamma_shift][red>>8];
  189084. png_uint_16 green_1 = png_ptr->gamma_16_to_1[(green&0xff) >>
  189085. png_ptr->gamma_shift][green>>8];
  189086. png_uint_16 blue_1 = png_ptr->gamma_16_to_1[(blue&0xff) >>
  189087. png_ptr->gamma_shift][blue>>8];
  189088. png_uint_16 gray16 = (png_uint_16)((rc*red_1 + gc*green_1
  189089. + bc*blue_1)>>15);
  189090. w = png_ptr->gamma_16_from_1[(gray16&0xff) >>
  189091. png_ptr->gamma_shift][gray16 >> 8];
  189092. rgb_error |= 1;
  189093. }
  189094. *(dp++) = (png_byte)((w>>8) & 0xff);
  189095. *(dp++) = (png_byte)(w & 0xff);
  189096. }
  189097. }
  189098. else
  189099. #endif
  189100. {
  189101. png_bytep sp = row;
  189102. png_bytep dp = row;
  189103. for (i = 0; i < row_width; i++)
  189104. {
  189105. png_uint_16 red, green, blue, gray16;
  189106. red = (png_uint_16)(((*(sp))<<8) | *(sp+1)); sp+=2;
  189107. green = (png_uint_16)(((*(sp))<<8) | *(sp+1)); sp+=2;
  189108. blue = (png_uint_16)(((*(sp))<<8) | *(sp+1)); sp+=2;
  189109. if(red != green || red != blue)
  189110. rgb_error |= 1;
  189111. gray16 = (png_uint_16)((rc*red + gc*green + bc*blue)>>15);
  189112. *(dp++) = (png_byte)((gray16>>8) & 0xff);
  189113. *(dp++) = (png_byte)(gray16 & 0xff);
  189114. }
  189115. }
  189116. }
  189117. }
  189118. if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  189119. {
  189120. if (row_info->bit_depth == 8)
  189121. {
  189122. #if defined(PNG_READ_GAMMA_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
  189123. if (png_ptr->gamma_from_1 != NULL && png_ptr->gamma_to_1 != NULL)
  189124. {
  189125. png_bytep sp = row;
  189126. png_bytep dp = row;
  189127. for (i = 0; i < row_width; i++)
  189128. {
  189129. png_byte red = png_ptr->gamma_to_1[*(sp++)];
  189130. png_byte green = png_ptr->gamma_to_1[*(sp++)];
  189131. png_byte blue = png_ptr->gamma_to_1[*(sp++)];
  189132. if(red != green || red != blue)
  189133. rgb_error |= 1;
  189134. *(dp++) = png_ptr->gamma_from_1
  189135. [(rc*red + gc*green + bc*blue)>>15];
  189136. *(dp++) = *(sp++); /* alpha */
  189137. }
  189138. }
  189139. else
  189140. #endif
  189141. {
  189142. png_bytep sp = row;
  189143. png_bytep dp = row;
  189144. for (i = 0; i < row_width; i++)
  189145. {
  189146. png_byte red = *(sp++);
  189147. png_byte green = *(sp++);
  189148. png_byte blue = *(sp++);
  189149. if(red != green || red != blue)
  189150. rgb_error |= 1;
  189151. *(dp++) = (png_byte)((rc*red + gc*green + bc*blue)>>15);
  189152. *(dp++) = *(sp++); /* alpha */
  189153. }
  189154. }
  189155. }
  189156. else /* RGBA bit_depth == 16 */
  189157. {
  189158. #if defined(PNG_READ_GAMMA_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
  189159. if (png_ptr->gamma_16_to_1 != NULL &&
  189160. png_ptr->gamma_16_from_1 != NULL)
  189161. {
  189162. png_bytep sp = row;
  189163. png_bytep dp = row;
  189164. for (i = 0; i < row_width; i++)
  189165. {
  189166. png_uint_16 red, green, blue, w;
  189167. red = (png_uint_16)(((*(sp))<<8) | *(sp+1)); sp+=2;
  189168. green = (png_uint_16)(((*(sp))<<8) | *(sp+1)); sp+=2;
  189169. blue = (png_uint_16)(((*(sp))<<8) | *(sp+1)); sp+=2;
  189170. if(red == green && red == blue)
  189171. w = red;
  189172. else
  189173. {
  189174. png_uint_16 red_1 = png_ptr->gamma_16_to_1[(red&0xff) >>
  189175. png_ptr->gamma_shift][red>>8];
  189176. png_uint_16 green_1 = png_ptr->gamma_16_to_1[(green&0xff) >>
  189177. png_ptr->gamma_shift][green>>8];
  189178. png_uint_16 blue_1 = png_ptr->gamma_16_to_1[(blue&0xff) >>
  189179. png_ptr->gamma_shift][blue>>8];
  189180. png_uint_16 gray16 = (png_uint_16)((rc * red_1
  189181. + gc * green_1 + bc * blue_1)>>15);
  189182. w = png_ptr->gamma_16_from_1[(gray16&0xff) >>
  189183. png_ptr->gamma_shift][gray16 >> 8];
  189184. rgb_error |= 1;
  189185. }
  189186. *(dp++) = (png_byte)((w>>8) & 0xff);
  189187. *(dp++) = (png_byte)(w & 0xff);
  189188. *(dp++) = *(sp++); /* alpha */
  189189. *(dp++) = *(sp++);
  189190. }
  189191. }
  189192. else
  189193. #endif
  189194. {
  189195. png_bytep sp = row;
  189196. png_bytep dp = row;
  189197. for (i = 0; i < row_width; i++)
  189198. {
  189199. png_uint_16 red, green, blue, gray16;
  189200. red = (png_uint_16)((*(sp)<<8) | *(sp+1)); sp+=2;
  189201. green = (png_uint_16)((*(sp)<<8) | *(sp+1)); sp+=2;
  189202. blue = (png_uint_16)((*(sp)<<8) | *(sp+1)); sp+=2;
  189203. if(red != green || red != blue)
  189204. rgb_error |= 1;
  189205. gray16 = (png_uint_16)((rc*red + gc*green + bc*blue)>>15);
  189206. *(dp++) = (png_byte)((gray16>>8) & 0xff);
  189207. *(dp++) = (png_byte)(gray16 & 0xff);
  189208. *(dp++) = *(sp++); /* alpha */
  189209. *(dp++) = *(sp++);
  189210. }
  189211. }
  189212. }
  189213. }
  189214. row_info->channels -= (png_byte)2;
  189215. row_info->color_type &= ~PNG_COLOR_MASK_COLOR;
  189216. row_info->pixel_depth = (png_byte)(row_info->channels *
  189217. row_info->bit_depth);
  189218. row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,row_width);
  189219. }
  189220. return rgb_error;
  189221. }
  189222. #endif
  189223. /* Build a grayscale palette. Palette is assumed to be 1 << bit_depth
  189224. * large of png_color. This lets grayscale images be treated as
  189225. * paletted. Most useful for gamma correction and simplification
  189226. * of code.
  189227. */
  189228. void PNGAPI
  189229. png_build_grayscale_palette(int bit_depth, png_colorp palette)
  189230. {
  189231. int num_palette;
  189232. int color_inc;
  189233. int i;
  189234. int v;
  189235. png_debug(1, "in png_do_build_grayscale_palette\n");
  189236. if (palette == NULL)
  189237. return;
  189238. switch (bit_depth)
  189239. {
  189240. case 1:
  189241. num_palette = 2;
  189242. color_inc = 0xff;
  189243. break;
  189244. case 2:
  189245. num_palette = 4;
  189246. color_inc = 0x55;
  189247. break;
  189248. case 4:
  189249. num_palette = 16;
  189250. color_inc = 0x11;
  189251. break;
  189252. case 8:
  189253. num_palette = 256;
  189254. color_inc = 1;
  189255. break;
  189256. default:
  189257. num_palette = 0;
  189258. color_inc = 0;
  189259. break;
  189260. }
  189261. for (i = 0, v = 0; i < num_palette; i++, v += color_inc)
  189262. {
  189263. palette[i].red = (png_byte)v;
  189264. palette[i].green = (png_byte)v;
  189265. palette[i].blue = (png_byte)v;
  189266. }
  189267. }
  189268. /* This function is currently unused. Do we really need it? */
  189269. #if defined(PNG_READ_DITHER_SUPPORTED) && defined(PNG_CORRECT_PALETTE_SUPPORTED)
  189270. void /* PRIVATE */
  189271. png_correct_palette(png_structp png_ptr, png_colorp palette,
  189272. int num_palette)
  189273. {
  189274. png_debug(1, "in png_correct_palette\n");
  189275. #if defined(PNG_READ_BACKGROUND_SUPPORTED) && \
  189276. defined(PNG_READ_GAMMA_SUPPORTED) && defined(PNG_FLOATING_POINT_SUPPORTED)
  189277. if (png_ptr->transformations & (PNG_GAMMA | PNG_BACKGROUND))
  189278. {
  189279. png_color back, back_1;
  189280. if (png_ptr->background_gamma_type == PNG_BACKGROUND_GAMMA_FILE)
  189281. {
  189282. back.red = png_ptr->gamma_table[png_ptr->background.red];
  189283. back.green = png_ptr->gamma_table[png_ptr->background.green];
  189284. back.blue = png_ptr->gamma_table[png_ptr->background.blue];
  189285. back_1.red = png_ptr->gamma_to_1[png_ptr->background.red];
  189286. back_1.green = png_ptr->gamma_to_1[png_ptr->background.green];
  189287. back_1.blue = png_ptr->gamma_to_1[png_ptr->background.blue];
  189288. }
  189289. else
  189290. {
  189291. double g;
  189292. g = 1.0 / (png_ptr->background_gamma * png_ptr->screen_gamma);
  189293. if (png_ptr->background_gamma_type == PNG_BACKGROUND_GAMMA_SCREEN ||
  189294. fabs(g - 1.0) < PNG_GAMMA_THRESHOLD)
  189295. {
  189296. back.red = png_ptr->background.red;
  189297. back.green = png_ptr->background.green;
  189298. back.blue = png_ptr->background.blue;
  189299. }
  189300. else
  189301. {
  189302. back.red =
  189303. (png_byte)(pow((double)png_ptr->background.red/255, g) *
  189304. 255.0 + 0.5);
  189305. back.green =
  189306. (png_byte)(pow((double)png_ptr->background.green/255, g) *
  189307. 255.0 + 0.5);
  189308. back.blue =
  189309. (png_byte)(pow((double)png_ptr->background.blue/255, g) *
  189310. 255.0 + 0.5);
  189311. }
  189312. g = 1.0 / png_ptr->background_gamma;
  189313. back_1.red =
  189314. (png_byte)(pow((double)png_ptr->background.red/255, g) *
  189315. 255.0 + 0.5);
  189316. back_1.green =
  189317. (png_byte)(pow((double)png_ptr->background.green/255, g) *
  189318. 255.0 + 0.5);
  189319. back_1.blue =
  189320. (png_byte)(pow((double)png_ptr->background.blue/255, g) *
  189321. 255.0 + 0.5);
  189322. }
  189323. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  189324. {
  189325. png_uint_32 i;
  189326. for (i = 0; i < (png_uint_32)num_palette; i++)
  189327. {
  189328. if (i < png_ptr->num_trans && png_ptr->trans[i] == 0)
  189329. {
  189330. palette[i] = back;
  189331. }
  189332. else if (i < png_ptr->num_trans && png_ptr->trans[i] != 0xff)
  189333. {
  189334. png_byte v, w;
  189335. v = png_ptr->gamma_to_1[png_ptr->palette[i].red];
  189336. png_composite(w, v, png_ptr->trans[i], back_1.red);
  189337. palette[i].red = png_ptr->gamma_from_1[w];
  189338. v = png_ptr->gamma_to_1[png_ptr->palette[i].green];
  189339. png_composite(w, v, png_ptr->trans[i], back_1.green);
  189340. palette[i].green = png_ptr->gamma_from_1[w];
  189341. v = png_ptr->gamma_to_1[png_ptr->palette[i].blue];
  189342. png_composite(w, v, png_ptr->trans[i], back_1.blue);
  189343. palette[i].blue = png_ptr->gamma_from_1[w];
  189344. }
  189345. else
  189346. {
  189347. palette[i].red = png_ptr->gamma_table[palette[i].red];
  189348. palette[i].green = png_ptr->gamma_table[palette[i].green];
  189349. palette[i].blue = png_ptr->gamma_table[palette[i].blue];
  189350. }
  189351. }
  189352. }
  189353. else
  189354. {
  189355. int i;
  189356. for (i = 0; i < num_palette; i++)
  189357. {
  189358. if (palette[i].red == (png_byte)png_ptr->trans_values.gray)
  189359. {
  189360. palette[i] = back;
  189361. }
  189362. else
  189363. {
  189364. palette[i].red = png_ptr->gamma_table[palette[i].red];
  189365. palette[i].green = png_ptr->gamma_table[palette[i].green];
  189366. palette[i].blue = png_ptr->gamma_table[palette[i].blue];
  189367. }
  189368. }
  189369. }
  189370. }
  189371. else
  189372. #endif
  189373. #if defined(PNG_READ_GAMMA_SUPPORTED)
  189374. if (png_ptr->transformations & PNG_GAMMA)
  189375. {
  189376. int i;
  189377. for (i = 0; i < num_palette; i++)
  189378. {
  189379. palette[i].red = png_ptr->gamma_table[palette[i].red];
  189380. palette[i].green = png_ptr->gamma_table[palette[i].green];
  189381. palette[i].blue = png_ptr->gamma_table[palette[i].blue];
  189382. }
  189383. }
  189384. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  189385. else
  189386. #endif
  189387. #endif
  189388. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  189389. if (png_ptr->transformations & PNG_BACKGROUND)
  189390. {
  189391. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  189392. {
  189393. png_color back;
  189394. back.red = (png_byte)png_ptr->background.red;
  189395. back.green = (png_byte)png_ptr->background.green;
  189396. back.blue = (png_byte)png_ptr->background.blue;
  189397. for (i = 0; i < (int)png_ptr->num_trans; i++)
  189398. {
  189399. if (png_ptr->trans[i] == 0)
  189400. {
  189401. palette[i].red = back.red;
  189402. palette[i].green = back.green;
  189403. palette[i].blue = back.blue;
  189404. }
  189405. else if (png_ptr->trans[i] != 0xff)
  189406. {
  189407. png_composite(palette[i].red, png_ptr->palette[i].red,
  189408. png_ptr->trans[i], back.red);
  189409. png_composite(palette[i].green, png_ptr->palette[i].green,
  189410. png_ptr->trans[i], back.green);
  189411. png_composite(palette[i].blue, png_ptr->palette[i].blue,
  189412. png_ptr->trans[i], back.blue);
  189413. }
  189414. }
  189415. }
  189416. else /* assume grayscale palette (what else could it be?) */
  189417. {
  189418. int i;
  189419. for (i = 0; i < num_palette; i++)
  189420. {
  189421. if (i == (png_byte)png_ptr->trans_values.gray)
  189422. {
  189423. palette[i].red = (png_byte)png_ptr->background.red;
  189424. palette[i].green = (png_byte)png_ptr->background.green;
  189425. palette[i].blue = (png_byte)png_ptr->background.blue;
  189426. }
  189427. }
  189428. }
  189429. }
  189430. #endif
  189431. }
  189432. #endif
  189433. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  189434. /* Replace any alpha or transparency with the supplied background color.
  189435. * "background" is already in the screen gamma, while "background_1" is
  189436. * at a gamma of 1.0. Paletted files have already been taken care of.
  189437. */
  189438. void /* PRIVATE */
  189439. png_do_background(png_row_infop row_info, png_bytep row,
  189440. png_color_16p trans_values, png_color_16p background
  189441. #if defined(PNG_READ_GAMMA_SUPPORTED)
  189442. , png_color_16p background_1,
  189443. png_bytep gamma_table, png_bytep gamma_from_1, png_bytep gamma_to_1,
  189444. png_uint_16pp gamma_16, png_uint_16pp gamma_16_from_1,
  189445. png_uint_16pp gamma_16_to_1, int gamma_shift
  189446. #endif
  189447. )
  189448. {
  189449. png_bytep sp, dp;
  189450. png_uint_32 i;
  189451. png_uint_32 row_width=row_info->width;
  189452. int shift;
  189453. png_debug(1, "in png_do_background\n");
  189454. if (background != NULL &&
  189455. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  189456. row != NULL && row_info != NULL &&
  189457. #endif
  189458. (!(row_info->color_type & PNG_COLOR_MASK_ALPHA) ||
  189459. (row_info->color_type != PNG_COLOR_TYPE_PALETTE && trans_values)))
  189460. {
  189461. switch (row_info->color_type)
  189462. {
  189463. case PNG_COLOR_TYPE_GRAY:
  189464. {
  189465. switch (row_info->bit_depth)
  189466. {
  189467. case 1:
  189468. {
  189469. sp = row;
  189470. shift = 7;
  189471. for (i = 0; i < row_width; i++)
  189472. {
  189473. if ((png_uint_16)((*sp >> shift) & 0x01)
  189474. == trans_values->gray)
  189475. {
  189476. *sp &= (png_byte)((0x7f7f >> (7 - shift)) & 0xff);
  189477. *sp |= (png_byte)(background->gray << shift);
  189478. }
  189479. if (!shift)
  189480. {
  189481. shift = 7;
  189482. sp++;
  189483. }
  189484. else
  189485. shift--;
  189486. }
  189487. break;
  189488. }
  189489. case 2:
  189490. {
  189491. #if defined(PNG_READ_GAMMA_SUPPORTED)
  189492. if (gamma_table != NULL)
  189493. {
  189494. sp = row;
  189495. shift = 6;
  189496. for (i = 0; i < row_width; i++)
  189497. {
  189498. if ((png_uint_16)((*sp >> shift) & 0x03)
  189499. == trans_values->gray)
  189500. {
  189501. *sp &= (png_byte)((0x3f3f >> (6 - shift)) & 0xff);
  189502. *sp |= (png_byte)(background->gray << shift);
  189503. }
  189504. else
  189505. {
  189506. png_byte p = (png_byte)((*sp >> shift) & 0x03);
  189507. png_byte g = (png_byte)((gamma_table [p | (p << 2) |
  189508. (p << 4) | (p << 6)] >> 6) & 0x03);
  189509. *sp &= (png_byte)((0x3f3f >> (6 - shift)) & 0xff);
  189510. *sp |= (png_byte)(g << shift);
  189511. }
  189512. if (!shift)
  189513. {
  189514. shift = 6;
  189515. sp++;
  189516. }
  189517. else
  189518. shift -= 2;
  189519. }
  189520. }
  189521. else
  189522. #endif
  189523. {
  189524. sp = row;
  189525. shift = 6;
  189526. for (i = 0; i < row_width; i++)
  189527. {
  189528. if ((png_uint_16)((*sp >> shift) & 0x03)
  189529. == trans_values->gray)
  189530. {
  189531. *sp &= (png_byte)((0x3f3f >> (6 - shift)) & 0xff);
  189532. *sp |= (png_byte)(background->gray << shift);
  189533. }
  189534. if (!shift)
  189535. {
  189536. shift = 6;
  189537. sp++;
  189538. }
  189539. else
  189540. shift -= 2;
  189541. }
  189542. }
  189543. break;
  189544. }
  189545. case 4:
  189546. {
  189547. #if defined(PNG_READ_GAMMA_SUPPORTED)
  189548. if (gamma_table != NULL)
  189549. {
  189550. sp = row;
  189551. shift = 4;
  189552. for (i = 0; i < row_width; i++)
  189553. {
  189554. if ((png_uint_16)((*sp >> shift) & 0x0f)
  189555. == trans_values->gray)
  189556. {
  189557. *sp &= (png_byte)((0xf0f >> (4 - shift)) & 0xff);
  189558. *sp |= (png_byte)(background->gray << shift);
  189559. }
  189560. else
  189561. {
  189562. png_byte p = (png_byte)((*sp >> shift) & 0x0f);
  189563. png_byte g = (png_byte)((gamma_table[p |
  189564. (p << 4)] >> 4) & 0x0f);
  189565. *sp &= (png_byte)((0xf0f >> (4 - shift)) & 0xff);
  189566. *sp |= (png_byte)(g << shift);
  189567. }
  189568. if (!shift)
  189569. {
  189570. shift = 4;
  189571. sp++;
  189572. }
  189573. else
  189574. shift -= 4;
  189575. }
  189576. }
  189577. else
  189578. #endif
  189579. {
  189580. sp = row;
  189581. shift = 4;
  189582. for (i = 0; i < row_width; i++)
  189583. {
  189584. if ((png_uint_16)((*sp >> shift) & 0x0f)
  189585. == trans_values->gray)
  189586. {
  189587. *sp &= (png_byte)((0xf0f >> (4 - shift)) & 0xff);
  189588. *sp |= (png_byte)(background->gray << shift);
  189589. }
  189590. if (!shift)
  189591. {
  189592. shift = 4;
  189593. sp++;
  189594. }
  189595. else
  189596. shift -= 4;
  189597. }
  189598. }
  189599. break;
  189600. }
  189601. case 8:
  189602. {
  189603. #if defined(PNG_READ_GAMMA_SUPPORTED)
  189604. if (gamma_table != NULL)
  189605. {
  189606. sp = row;
  189607. for (i = 0; i < row_width; i++, sp++)
  189608. {
  189609. if (*sp == trans_values->gray)
  189610. {
  189611. *sp = (png_byte)background->gray;
  189612. }
  189613. else
  189614. {
  189615. *sp = gamma_table[*sp];
  189616. }
  189617. }
  189618. }
  189619. else
  189620. #endif
  189621. {
  189622. sp = row;
  189623. for (i = 0; i < row_width; i++, sp++)
  189624. {
  189625. if (*sp == trans_values->gray)
  189626. {
  189627. *sp = (png_byte)background->gray;
  189628. }
  189629. }
  189630. }
  189631. break;
  189632. }
  189633. case 16:
  189634. {
  189635. #if defined(PNG_READ_GAMMA_SUPPORTED)
  189636. if (gamma_16 != NULL)
  189637. {
  189638. sp = row;
  189639. for (i = 0; i < row_width; i++, sp += 2)
  189640. {
  189641. png_uint_16 v;
  189642. v = (png_uint_16)(((*sp) << 8) + *(sp + 1));
  189643. if (v == trans_values->gray)
  189644. {
  189645. /* background is already in screen gamma */
  189646. *sp = (png_byte)((background->gray >> 8) & 0xff);
  189647. *(sp + 1) = (png_byte)(background->gray & 0xff);
  189648. }
  189649. else
  189650. {
  189651. v = gamma_16[*(sp + 1) >> gamma_shift][*sp];
  189652. *sp = (png_byte)((v >> 8) & 0xff);
  189653. *(sp + 1) = (png_byte)(v & 0xff);
  189654. }
  189655. }
  189656. }
  189657. else
  189658. #endif
  189659. {
  189660. sp = row;
  189661. for (i = 0; i < row_width; i++, sp += 2)
  189662. {
  189663. png_uint_16 v;
  189664. v = (png_uint_16)(((*sp) << 8) + *(sp + 1));
  189665. if (v == trans_values->gray)
  189666. {
  189667. *sp = (png_byte)((background->gray >> 8) & 0xff);
  189668. *(sp + 1) = (png_byte)(background->gray & 0xff);
  189669. }
  189670. }
  189671. }
  189672. break;
  189673. }
  189674. }
  189675. break;
  189676. }
  189677. case PNG_COLOR_TYPE_RGB:
  189678. {
  189679. if (row_info->bit_depth == 8)
  189680. {
  189681. #if defined(PNG_READ_GAMMA_SUPPORTED)
  189682. if (gamma_table != NULL)
  189683. {
  189684. sp = row;
  189685. for (i = 0; i < row_width; i++, sp += 3)
  189686. {
  189687. if (*sp == trans_values->red &&
  189688. *(sp + 1) == trans_values->green &&
  189689. *(sp + 2) == trans_values->blue)
  189690. {
  189691. *sp = (png_byte)background->red;
  189692. *(sp + 1) = (png_byte)background->green;
  189693. *(sp + 2) = (png_byte)background->blue;
  189694. }
  189695. else
  189696. {
  189697. *sp = gamma_table[*sp];
  189698. *(sp + 1) = gamma_table[*(sp + 1)];
  189699. *(sp + 2) = gamma_table[*(sp + 2)];
  189700. }
  189701. }
  189702. }
  189703. else
  189704. #endif
  189705. {
  189706. sp = row;
  189707. for (i = 0; i < row_width; i++, sp += 3)
  189708. {
  189709. if (*sp == trans_values->red &&
  189710. *(sp + 1) == trans_values->green &&
  189711. *(sp + 2) == trans_values->blue)
  189712. {
  189713. *sp = (png_byte)background->red;
  189714. *(sp + 1) = (png_byte)background->green;
  189715. *(sp + 2) = (png_byte)background->blue;
  189716. }
  189717. }
  189718. }
  189719. }
  189720. else /* if (row_info->bit_depth == 16) */
  189721. {
  189722. #if defined(PNG_READ_GAMMA_SUPPORTED)
  189723. if (gamma_16 != NULL)
  189724. {
  189725. sp = row;
  189726. for (i = 0; i < row_width; i++, sp += 6)
  189727. {
  189728. png_uint_16 r = (png_uint_16)(((*sp) << 8) + *(sp + 1));
  189729. png_uint_16 g = (png_uint_16)(((*(sp+2)) << 8) + *(sp+3));
  189730. png_uint_16 b = (png_uint_16)(((*(sp+4)) << 8) + *(sp+5));
  189731. if (r == trans_values->red && g == trans_values->green &&
  189732. b == trans_values->blue)
  189733. {
  189734. /* background is already in screen gamma */
  189735. *sp = (png_byte)((background->red >> 8) & 0xff);
  189736. *(sp + 1) = (png_byte)(background->red & 0xff);
  189737. *(sp + 2) = (png_byte)((background->green >> 8) & 0xff);
  189738. *(sp + 3) = (png_byte)(background->green & 0xff);
  189739. *(sp + 4) = (png_byte)((background->blue >> 8) & 0xff);
  189740. *(sp + 5) = (png_byte)(background->blue & 0xff);
  189741. }
  189742. else
  189743. {
  189744. png_uint_16 v = gamma_16[*(sp + 1) >> gamma_shift][*sp];
  189745. *sp = (png_byte)((v >> 8) & 0xff);
  189746. *(sp + 1) = (png_byte)(v & 0xff);
  189747. v = gamma_16[*(sp + 3) >> gamma_shift][*(sp + 2)];
  189748. *(sp + 2) = (png_byte)((v >> 8) & 0xff);
  189749. *(sp + 3) = (png_byte)(v & 0xff);
  189750. v = gamma_16[*(sp + 5) >> gamma_shift][*(sp + 4)];
  189751. *(sp + 4) = (png_byte)((v >> 8) & 0xff);
  189752. *(sp + 5) = (png_byte)(v & 0xff);
  189753. }
  189754. }
  189755. }
  189756. else
  189757. #endif
  189758. {
  189759. sp = row;
  189760. for (i = 0; i < row_width; i++, sp += 6)
  189761. {
  189762. png_uint_16 r = (png_uint_16)(((*sp) << 8) + *(sp+1));
  189763. png_uint_16 g = (png_uint_16)(((*(sp+2)) << 8) + *(sp+3));
  189764. png_uint_16 b = (png_uint_16)(((*(sp+4)) << 8) + *(sp+5));
  189765. if (r == trans_values->red && g == trans_values->green &&
  189766. b == trans_values->blue)
  189767. {
  189768. *sp = (png_byte)((background->red >> 8) & 0xff);
  189769. *(sp + 1) = (png_byte)(background->red & 0xff);
  189770. *(sp + 2) = (png_byte)((background->green >> 8) & 0xff);
  189771. *(sp + 3) = (png_byte)(background->green & 0xff);
  189772. *(sp + 4) = (png_byte)((background->blue >> 8) & 0xff);
  189773. *(sp + 5) = (png_byte)(background->blue & 0xff);
  189774. }
  189775. }
  189776. }
  189777. }
  189778. break;
  189779. }
  189780. case PNG_COLOR_TYPE_GRAY_ALPHA:
  189781. {
  189782. if (row_info->bit_depth == 8)
  189783. {
  189784. #if defined(PNG_READ_GAMMA_SUPPORTED)
  189785. if (gamma_to_1 != NULL && gamma_from_1 != NULL &&
  189786. gamma_table != NULL)
  189787. {
  189788. sp = row;
  189789. dp = row;
  189790. for (i = 0; i < row_width; i++, sp += 2, dp++)
  189791. {
  189792. png_uint_16 a = *(sp + 1);
  189793. if (a == 0xff)
  189794. {
  189795. *dp = gamma_table[*sp];
  189796. }
  189797. else if (a == 0)
  189798. {
  189799. /* background is already in screen gamma */
  189800. *dp = (png_byte)background->gray;
  189801. }
  189802. else
  189803. {
  189804. png_byte v, w;
  189805. v = gamma_to_1[*sp];
  189806. png_composite(w, v, a, background_1->gray);
  189807. *dp = gamma_from_1[w];
  189808. }
  189809. }
  189810. }
  189811. else
  189812. #endif
  189813. {
  189814. sp = row;
  189815. dp = row;
  189816. for (i = 0; i < row_width; i++, sp += 2, dp++)
  189817. {
  189818. png_byte a = *(sp + 1);
  189819. if (a == 0xff)
  189820. {
  189821. *dp = *sp;
  189822. }
  189823. #if defined(PNG_READ_GAMMA_SUPPORTED)
  189824. else if (a == 0)
  189825. {
  189826. *dp = (png_byte)background->gray;
  189827. }
  189828. else
  189829. {
  189830. png_composite(*dp, *sp, a, background_1->gray);
  189831. }
  189832. #else
  189833. *dp = (png_byte)background->gray;
  189834. #endif
  189835. }
  189836. }
  189837. }
  189838. else /* if (png_ptr->bit_depth == 16) */
  189839. {
  189840. #if defined(PNG_READ_GAMMA_SUPPORTED)
  189841. if (gamma_16 != NULL && gamma_16_from_1 != NULL &&
  189842. gamma_16_to_1 != NULL)
  189843. {
  189844. sp = row;
  189845. dp = row;
  189846. for (i = 0; i < row_width; i++, sp += 4, dp += 2)
  189847. {
  189848. png_uint_16 a = (png_uint_16)(((*(sp+2)) << 8) + *(sp+3));
  189849. if (a == (png_uint_16)0xffff)
  189850. {
  189851. png_uint_16 v;
  189852. v = gamma_16[*(sp + 1) >> gamma_shift][*sp];
  189853. *dp = (png_byte)((v >> 8) & 0xff);
  189854. *(dp + 1) = (png_byte)(v & 0xff);
  189855. }
  189856. #if defined(PNG_READ_GAMMA_SUPPORTED)
  189857. else if (a == 0)
  189858. #else
  189859. else
  189860. #endif
  189861. {
  189862. /* background is already in screen gamma */
  189863. *dp = (png_byte)((background->gray >> 8) & 0xff);
  189864. *(dp + 1) = (png_byte)(background->gray & 0xff);
  189865. }
  189866. #if defined(PNG_READ_GAMMA_SUPPORTED)
  189867. else
  189868. {
  189869. png_uint_16 g, v, w;
  189870. g = gamma_16_to_1[*(sp + 1) >> gamma_shift][*sp];
  189871. png_composite_16(v, g, a, background_1->gray);
  189872. w = gamma_16_from_1[(v&0xff) >> gamma_shift][v >> 8];
  189873. *dp = (png_byte)((w >> 8) & 0xff);
  189874. *(dp + 1) = (png_byte)(w & 0xff);
  189875. }
  189876. #endif
  189877. }
  189878. }
  189879. else
  189880. #endif
  189881. {
  189882. sp = row;
  189883. dp = row;
  189884. for (i = 0; i < row_width; i++, sp += 4, dp += 2)
  189885. {
  189886. png_uint_16 a = (png_uint_16)(((*(sp+2)) << 8) + *(sp+3));
  189887. if (a == (png_uint_16)0xffff)
  189888. {
  189889. png_memcpy(dp, sp, 2);
  189890. }
  189891. #if defined(PNG_READ_GAMMA_SUPPORTED)
  189892. else if (a == 0)
  189893. #else
  189894. else
  189895. #endif
  189896. {
  189897. *dp = (png_byte)((background->gray >> 8) & 0xff);
  189898. *(dp + 1) = (png_byte)(background->gray & 0xff);
  189899. }
  189900. #if defined(PNG_READ_GAMMA_SUPPORTED)
  189901. else
  189902. {
  189903. png_uint_16 g, v;
  189904. g = (png_uint_16)(((*sp) << 8) + *(sp + 1));
  189905. png_composite_16(v, g, a, background_1->gray);
  189906. *dp = (png_byte)((v >> 8) & 0xff);
  189907. *(dp + 1) = (png_byte)(v & 0xff);
  189908. }
  189909. #endif
  189910. }
  189911. }
  189912. }
  189913. break;
  189914. }
  189915. case PNG_COLOR_TYPE_RGB_ALPHA:
  189916. {
  189917. if (row_info->bit_depth == 8)
  189918. {
  189919. #if defined(PNG_READ_GAMMA_SUPPORTED)
  189920. if (gamma_to_1 != NULL && gamma_from_1 != NULL &&
  189921. gamma_table != NULL)
  189922. {
  189923. sp = row;
  189924. dp = row;
  189925. for (i = 0; i < row_width; i++, sp += 4, dp += 3)
  189926. {
  189927. png_byte a = *(sp + 3);
  189928. if (a == 0xff)
  189929. {
  189930. *dp = gamma_table[*sp];
  189931. *(dp + 1) = gamma_table[*(sp + 1)];
  189932. *(dp + 2) = gamma_table[*(sp + 2)];
  189933. }
  189934. else if (a == 0)
  189935. {
  189936. /* background is already in screen gamma */
  189937. *dp = (png_byte)background->red;
  189938. *(dp + 1) = (png_byte)background->green;
  189939. *(dp + 2) = (png_byte)background->blue;
  189940. }
  189941. else
  189942. {
  189943. png_byte v, w;
  189944. v = gamma_to_1[*sp];
  189945. png_composite(w, v, a, background_1->red);
  189946. *dp = gamma_from_1[w];
  189947. v = gamma_to_1[*(sp + 1)];
  189948. png_composite(w, v, a, background_1->green);
  189949. *(dp + 1) = gamma_from_1[w];
  189950. v = gamma_to_1[*(sp + 2)];
  189951. png_composite(w, v, a, background_1->blue);
  189952. *(dp + 2) = gamma_from_1[w];
  189953. }
  189954. }
  189955. }
  189956. else
  189957. #endif
  189958. {
  189959. sp = row;
  189960. dp = row;
  189961. for (i = 0; i < row_width; i++, sp += 4, dp += 3)
  189962. {
  189963. png_byte a = *(sp + 3);
  189964. if (a == 0xff)
  189965. {
  189966. *dp = *sp;
  189967. *(dp + 1) = *(sp + 1);
  189968. *(dp + 2) = *(sp + 2);
  189969. }
  189970. else if (a == 0)
  189971. {
  189972. *dp = (png_byte)background->red;
  189973. *(dp + 1) = (png_byte)background->green;
  189974. *(dp + 2) = (png_byte)background->blue;
  189975. }
  189976. else
  189977. {
  189978. png_composite(*dp, *sp, a, background->red);
  189979. png_composite(*(dp + 1), *(sp + 1), a,
  189980. background->green);
  189981. png_composite(*(dp + 2), *(sp + 2), a,
  189982. background->blue);
  189983. }
  189984. }
  189985. }
  189986. }
  189987. else /* if (row_info->bit_depth == 16) */
  189988. {
  189989. #if defined(PNG_READ_GAMMA_SUPPORTED)
  189990. if (gamma_16 != NULL && gamma_16_from_1 != NULL &&
  189991. gamma_16_to_1 != NULL)
  189992. {
  189993. sp = row;
  189994. dp = row;
  189995. for (i = 0; i < row_width; i++, sp += 8, dp += 6)
  189996. {
  189997. png_uint_16 a = (png_uint_16)(((png_uint_16)(*(sp + 6))
  189998. << 8) + (png_uint_16)(*(sp + 7)));
  189999. if (a == (png_uint_16)0xffff)
  190000. {
  190001. png_uint_16 v;
  190002. v = gamma_16[*(sp + 1) >> gamma_shift][*sp];
  190003. *dp = (png_byte)((v >> 8) & 0xff);
  190004. *(dp + 1) = (png_byte)(v & 0xff);
  190005. v = gamma_16[*(sp + 3) >> gamma_shift][*(sp + 2)];
  190006. *(dp + 2) = (png_byte)((v >> 8) & 0xff);
  190007. *(dp + 3) = (png_byte)(v & 0xff);
  190008. v = gamma_16[*(sp + 5) >> gamma_shift][*(sp + 4)];
  190009. *(dp + 4) = (png_byte)((v >> 8) & 0xff);
  190010. *(dp + 5) = (png_byte)(v & 0xff);
  190011. }
  190012. else if (a == 0)
  190013. {
  190014. /* background is already in screen gamma */
  190015. *dp = (png_byte)((background->red >> 8) & 0xff);
  190016. *(dp + 1) = (png_byte)(background->red & 0xff);
  190017. *(dp + 2) = (png_byte)((background->green >> 8) & 0xff);
  190018. *(dp + 3) = (png_byte)(background->green & 0xff);
  190019. *(dp + 4) = (png_byte)((background->blue >> 8) & 0xff);
  190020. *(dp + 5) = (png_byte)(background->blue & 0xff);
  190021. }
  190022. else
  190023. {
  190024. png_uint_16 v, w, x;
  190025. v = gamma_16_to_1[*(sp + 1) >> gamma_shift][*sp];
  190026. png_composite_16(w, v, a, background_1->red);
  190027. x = gamma_16_from_1[((w&0xff) >> gamma_shift)][w >> 8];
  190028. *dp = (png_byte)((x >> 8) & 0xff);
  190029. *(dp + 1) = (png_byte)(x & 0xff);
  190030. v = gamma_16_to_1[*(sp + 3) >> gamma_shift][*(sp + 2)];
  190031. png_composite_16(w, v, a, background_1->green);
  190032. x = gamma_16_from_1[((w&0xff) >> gamma_shift)][w >> 8];
  190033. *(dp + 2) = (png_byte)((x >> 8) & 0xff);
  190034. *(dp + 3) = (png_byte)(x & 0xff);
  190035. v = gamma_16_to_1[*(sp + 5) >> gamma_shift][*(sp + 4)];
  190036. png_composite_16(w, v, a, background_1->blue);
  190037. x = gamma_16_from_1[(w & 0xff) >> gamma_shift][w >> 8];
  190038. *(dp + 4) = (png_byte)((x >> 8) & 0xff);
  190039. *(dp + 5) = (png_byte)(x & 0xff);
  190040. }
  190041. }
  190042. }
  190043. else
  190044. #endif
  190045. {
  190046. sp = row;
  190047. dp = row;
  190048. for (i = 0; i < row_width; i++, sp += 8, dp += 6)
  190049. {
  190050. png_uint_16 a = (png_uint_16)(((png_uint_16)(*(sp + 6))
  190051. << 8) + (png_uint_16)(*(sp + 7)));
  190052. if (a == (png_uint_16)0xffff)
  190053. {
  190054. png_memcpy(dp, sp, 6);
  190055. }
  190056. else if (a == 0)
  190057. {
  190058. *dp = (png_byte)((background->red >> 8) & 0xff);
  190059. *(dp + 1) = (png_byte)(background->red & 0xff);
  190060. *(dp + 2) = (png_byte)((background->green >> 8) & 0xff);
  190061. *(dp + 3) = (png_byte)(background->green & 0xff);
  190062. *(dp + 4) = (png_byte)((background->blue >> 8) & 0xff);
  190063. *(dp + 5) = (png_byte)(background->blue & 0xff);
  190064. }
  190065. else
  190066. {
  190067. png_uint_16 v;
  190068. png_uint_16 r = (png_uint_16)(((*sp) << 8) + *(sp + 1));
  190069. png_uint_16 g = (png_uint_16)(((*(sp + 2)) << 8)
  190070. + *(sp + 3));
  190071. png_uint_16 b = (png_uint_16)(((*(sp + 4)) << 8)
  190072. + *(sp + 5));
  190073. png_composite_16(v, r, a, background->red);
  190074. *dp = (png_byte)((v >> 8) & 0xff);
  190075. *(dp + 1) = (png_byte)(v & 0xff);
  190076. png_composite_16(v, g, a, background->green);
  190077. *(dp + 2) = (png_byte)((v >> 8) & 0xff);
  190078. *(dp + 3) = (png_byte)(v & 0xff);
  190079. png_composite_16(v, b, a, background->blue);
  190080. *(dp + 4) = (png_byte)((v >> 8) & 0xff);
  190081. *(dp + 5) = (png_byte)(v & 0xff);
  190082. }
  190083. }
  190084. }
  190085. }
  190086. break;
  190087. }
  190088. }
  190089. if (row_info->color_type & PNG_COLOR_MASK_ALPHA)
  190090. {
  190091. row_info->color_type &= ~PNG_COLOR_MASK_ALPHA;
  190092. row_info->channels--;
  190093. row_info->pixel_depth = (png_byte)(row_info->channels *
  190094. row_info->bit_depth);
  190095. row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,row_width);
  190096. }
  190097. }
  190098. }
  190099. #endif
  190100. #if defined(PNG_READ_GAMMA_SUPPORTED)
  190101. /* Gamma correct the image, avoiding the alpha channel. Make sure
  190102. * you do this after you deal with the transparency issue on grayscale
  190103. * or RGB images. If your bit depth is 8, use gamma_table, if it
  190104. * is 16, use gamma_16_table and gamma_shift. Build these with
  190105. * build_gamma_table().
  190106. */
  190107. void /* PRIVATE */
  190108. png_do_gamma(png_row_infop row_info, png_bytep row,
  190109. png_bytep gamma_table, png_uint_16pp gamma_16_table,
  190110. int gamma_shift)
  190111. {
  190112. png_bytep sp;
  190113. png_uint_32 i;
  190114. png_uint_32 row_width=row_info->width;
  190115. png_debug(1, "in png_do_gamma\n");
  190116. if (
  190117. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  190118. row != NULL && row_info != NULL &&
  190119. #endif
  190120. ((row_info->bit_depth <= 8 && gamma_table != NULL) ||
  190121. (row_info->bit_depth == 16 && gamma_16_table != NULL)))
  190122. {
  190123. switch (row_info->color_type)
  190124. {
  190125. case PNG_COLOR_TYPE_RGB:
  190126. {
  190127. if (row_info->bit_depth == 8)
  190128. {
  190129. sp = row;
  190130. for (i = 0; i < row_width; i++)
  190131. {
  190132. *sp = gamma_table[*sp];
  190133. sp++;
  190134. *sp = gamma_table[*sp];
  190135. sp++;
  190136. *sp = gamma_table[*sp];
  190137. sp++;
  190138. }
  190139. }
  190140. else /* if (row_info->bit_depth == 16) */
  190141. {
  190142. sp = row;
  190143. for (i = 0; i < row_width; i++)
  190144. {
  190145. png_uint_16 v;
  190146. v = gamma_16_table[*(sp + 1) >> gamma_shift][*sp];
  190147. *sp = (png_byte)((v >> 8) & 0xff);
  190148. *(sp + 1) = (png_byte)(v & 0xff);
  190149. sp += 2;
  190150. v = gamma_16_table[*(sp + 1) >> gamma_shift][*sp];
  190151. *sp = (png_byte)((v >> 8) & 0xff);
  190152. *(sp + 1) = (png_byte)(v & 0xff);
  190153. sp += 2;
  190154. v = gamma_16_table[*(sp + 1) >> gamma_shift][*sp];
  190155. *sp = (png_byte)((v >> 8) & 0xff);
  190156. *(sp + 1) = (png_byte)(v & 0xff);
  190157. sp += 2;
  190158. }
  190159. }
  190160. break;
  190161. }
  190162. case PNG_COLOR_TYPE_RGB_ALPHA:
  190163. {
  190164. if (row_info->bit_depth == 8)
  190165. {
  190166. sp = row;
  190167. for (i = 0; i < row_width; i++)
  190168. {
  190169. *sp = gamma_table[*sp];
  190170. sp++;
  190171. *sp = gamma_table[*sp];
  190172. sp++;
  190173. *sp = gamma_table[*sp];
  190174. sp++;
  190175. sp++;
  190176. }
  190177. }
  190178. else /* if (row_info->bit_depth == 16) */
  190179. {
  190180. sp = row;
  190181. for (i = 0; i < row_width; i++)
  190182. {
  190183. png_uint_16 v = gamma_16_table[*(sp + 1) >> gamma_shift][*sp];
  190184. *sp = (png_byte)((v >> 8) & 0xff);
  190185. *(sp + 1) = (png_byte)(v & 0xff);
  190186. sp += 2;
  190187. v = gamma_16_table[*(sp + 1) >> gamma_shift][*sp];
  190188. *sp = (png_byte)((v >> 8) & 0xff);
  190189. *(sp + 1) = (png_byte)(v & 0xff);
  190190. sp += 2;
  190191. v = gamma_16_table[*(sp + 1) >> gamma_shift][*sp];
  190192. *sp = (png_byte)((v >> 8) & 0xff);
  190193. *(sp + 1) = (png_byte)(v & 0xff);
  190194. sp += 4;
  190195. }
  190196. }
  190197. break;
  190198. }
  190199. case PNG_COLOR_TYPE_GRAY_ALPHA:
  190200. {
  190201. if (row_info->bit_depth == 8)
  190202. {
  190203. sp = row;
  190204. for (i = 0; i < row_width; i++)
  190205. {
  190206. *sp = gamma_table[*sp];
  190207. sp += 2;
  190208. }
  190209. }
  190210. else /* if (row_info->bit_depth == 16) */
  190211. {
  190212. sp = row;
  190213. for (i = 0; i < row_width; i++)
  190214. {
  190215. png_uint_16 v = gamma_16_table[*(sp + 1) >> gamma_shift][*sp];
  190216. *sp = (png_byte)((v >> 8) & 0xff);
  190217. *(sp + 1) = (png_byte)(v & 0xff);
  190218. sp += 4;
  190219. }
  190220. }
  190221. break;
  190222. }
  190223. case PNG_COLOR_TYPE_GRAY:
  190224. {
  190225. if (row_info->bit_depth == 2)
  190226. {
  190227. sp = row;
  190228. for (i = 0; i < row_width; i += 4)
  190229. {
  190230. int a = *sp & 0xc0;
  190231. int b = *sp & 0x30;
  190232. int c = *sp & 0x0c;
  190233. int d = *sp & 0x03;
  190234. *sp = (png_byte)(
  190235. ((((int)gamma_table[a|(a>>2)|(a>>4)|(a>>6)]) ) & 0xc0)|
  190236. ((((int)gamma_table[(b<<2)|b|(b>>2)|(b>>4)])>>2) & 0x30)|
  190237. ((((int)gamma_table[(c<<4)|(c<<2)|c|(c>>2)])>>4) & 0x0c)|
  190238. ((((int)gamma_table[(d<<6)|(d<<4)|(d<<2)|d])>>6) ));
  190239. sp++;
  190240. }
  190241. }
  190242. if (row_info->bit_depth == 4)
  190243. {
  190244. sp = row;
  190245. for (i = 0; i < row_width; i += 2)
  190246. {
  190247. int msb = *sp & 0xf0;
  190248. int lsb = *sp & 0x0f;
  190249. *sp = (png_byte)((((int)gamma_table[msb | (msb >> 4)]) & 0xf0)
  190250. | (((int)gamma_table[(lsb << 4) | lsb]) >> 4));
  190251. sp++;
  190252. }
  190253. }
  190254. else if (row_info->bit_depth == 8)
  190255. {
  190256. sp = row;
  190257. for (i = 0; i < row_width; i++)
  190258. {
  190259. *sp = gamma_table[*sp];
  190260. sp++;
  190261. }
  190262. }
  190263. else if (row_info->bit_depth == 16)
  190264. {
  190265. sp = row;
  190266. for (i = 0; i < row_width; i++)
  190267. {
  190268. png_uint_16 v = gamma_16_table[*(sp + 1) >> gamma_shift][*sp];
  190269. *sp = (png_byte)((v >> 8) & 0xff);
  190270. *(sp + 1) = (png_byte)(v & 0xff);
  190271. sp += 2;
  190272. }
  190273. }
  190274. break;
  190275. }
  190276. }
  190277. }
  190278. }
  190279. #endif
  190280. #if defined(PNG_READ_EXPAND_SUPPORTED)
  190281. /* Expands a palette row to an RGB or RGBA row depending
  190282. * upon whether you supply trans and num_trans.
  190283. */
  190284. void /* PRIVATE */
  190285. png_do_expand_palette(png_row_infop row_info, png_bytep row,
  190286. png_colorp palette, png_bytep trans, int num_trans)
  190287. {
  190288. int shift, value;
  190289. png_bytep sp, dp;
  190290. png_uint_32 i;
  190291. png_uint_32 row_width=row_info->width;
  190292. png_debug(1, "in png_do_expand_palette\n");
  190293. if (
  190294. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  190295. row != NULL && row_info != NULL &&
  190296. #endif
  190297. row_info->color_type == PNG_COLOR_TYPE_PALETTE)
  190298. {
  190299. if (row_info->bit_depth < 8)
  190300. {
  190301. switch (row_info->bit_depth)
  190302. {
  190303. case 1:
  190304. {
  190305. sp = row + (png_size_t)((row_width - 1) >> 3);
  190306. dp = row + (png_size_t)row_width - 1;
  190307. shift = 7 - (int)((row_width + 7) & 0x07);
  190308. for (i = 0; i < row_width; i++)
  190309. {
  190310. if ((*sp >> shift) & 0x01)
  190311. *dp = 1;
  190312. else
  190313. *dp = 0;
  190314. if (shift == 7)
  190315. {
  190316. shift = 0;
  190317. sp--;
  190318. }
  190319. else
  190320. shift++;
  190321. dp--;
  190322. }
  190323. break;
  190324. }
  190325. case 2:
  190326. {
  190327. sp = row + (png_size_t)((row_width - 1) >> 2);
  190328. dp = row + (png_size_t)row_width - 1;
  190329. shift = (int)((3 - ((row_width + 3) & 0x03)) << 1);
  190330. for (i = 0; i < row_width; i++)
  190331. {
  190332. value = (*sp >> shift) & 0x03;
  190333. *dp = (png_byte)value;
  190334. if (shift == 6)
  190335. {
  190336. shift = 0;
  190337. sp--;
  190338. }
  190339. else
  190340. shift += 2;
  190341. dp--;
  190342. }
  190343. break;
  190344. }
  190345. case 4:
  190346. {
  190347. sp = row + (png_size_t)((row_width - 1) >> 1);
  190348. dp = row + (png_size_t)row_width - 1;
  190349. shift = (int)((row_width & 0x01) << 2);
  190350. for (i = 0; i < row_width; i++)
  190351. {
  190352. value = (*sp >> shift) & 0x0f;
  190353. *dp = (png_byte)value;
  190354. if (shift == 4)
  190355. {
  190356. shift = 0;
  190357. sp--;
  190358. }
  190359. else
  190360. shift += 4;
  190361. dp--;
  190362. }
  190363. break;
  190364. }
  190365. }
  190366. row_info->bit_depth = 8;
  190367. row_info->pixel_depth = 8;
  190368. row_info->rowbytes = row_width;
  190369. }
  190370. switch (row_info->bit_depth)
  190371. {
  190372. case 8:
  190373. {
  190374. if (trans != NULL)
  190375. {
  190376. sp = row + (png_size_t)row_width - 1;
  190377. dp = row + (png_size_t)(row_width << 2) - 1;
  190378. for (i = 0; i < row_width; i++)
  190379. {
  190380. if ((int)(*sp) >= num_trans)
  190381. *dp-- = 0xff;
  190382. else
  190383. *dp-- = trans[*sp];
  190384. *dp-- = palette[*sp].blue;
  190385. *dp-- = palette[*sp].green;
  190386. *dp-- = palette[*sp].red;
  190387. sp--;
  190388. }
  190389. row_info->bit_depth = 8;
  190390. row_info->pixel_depth = 32;
  190391. row_info->rowbytes = row_width * 4;
  190392. row_info->color_type = 6;
  190393. row_info->channels = 4;
  190394. }
  190395. else
  190396. {
  190397. sp = row + (png_size_t)row_width - 1;
  190398. dp = row + (png_size_t)(row_width * 3) - 1;
  190399. for (i = 0; i < row_width; i++)
  190400. {
  190401. *dp-- = palette[*sp].blue;
  190402. *dp-- = palette[*sp].green;
  190403. *dp-- = palette[*sp].red;
  190404. sp--;
  190405. }
  190406. row_info->bit_depth = 8;
  190407. row_info->pixel_depth = 24;
  190408. row_info->rowbytes = row_width * 3;
  190409. row_info->color_type = 2;
  190410. row_info->channels = 3;
  190411. }
  190412. break;
  190413. }
  190414. }
  190415. }
  190416. }
  190417. /* If the bit depth < 8, it is expanded to 8. Also, if the already
  190418. * expanded transparency value is supplied, an alpha channel is built.
  190419. */
  190420. void /* PRIVATE */
  190421. png_do_expand(png_row_infop row_info, png_bytep row,
  190422. png_color_16p trans_value)
  190423. {
  190424. int shift, value;
  190425. png_bytep sp, dp;
  190426. png_uint_32 i;
  190427. png_uint_32 row_width=row_info->width;
  190428. png_debug(1, "in png_do_expand\n");
  190429. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  190430. if (row != NULL && row_info != NULL)
  190431. #endif
  190432. {
  190433. if (row_info->color_type == PNG_COLOR_TYPE_GRAY)
  190434. {
  190435. png_uint_16 gray = (png_uint_16)(trans_value ? trans_value->gray : 0);
  190436. if (row_info->bit_depth < 8)
  190437. {
  190438. switch (row_info->bit_depth)
  190439. {
  190440. case 1:
  190441. {
  190442. gray = (png_uint_16)((gray&0x01)*0xff);
  190443. sp = row + (png_size_t)((row_width - 1) >> 3);
  190444. dp = row + (png_size_t)row_width - 1;
  190445. shift = 7 - (int)((row_width + 7) & 0x07);
  190446. for (i = 0; i < row_width; i++)
  190447. {
  190448. if ((*sp >> shift) & 0x01)
  190449. *dp = 0xff;
  190450. else
  190451. *dp = 0;
  190452. if (shift == 7)
  190453. {
  190454. shift = 0;
  190455. sp--;
  190456. }
  190457. else
  190458. shift++;
  190459. dp--;
  190460. }
  190461. break;
  190462. }
  190463. case 2:
  190464. {
  190465. gray = (png_uint_16)((gray&0x03)*0x55);
  190466. sp = row + (png_size_t)((row_width - 1) >> 2);
  190467. dp = row + (png_size_t)row_width - 1;
  190468. shift = (int)((3 - ((row_width + 3) & 0x03)) << 1);
  190469. for (i = 0; i < row_width; i++)
  190470. {
  190471. value = (*sp >> shift) & 0x03;
  190472. *dp = (png_byte)(value | (value << 2) | (value << 4) |
  190473. (value << 6));
  190474. if (shift == 6)
  190475. {
  190476. shift = 0;
  190477. sp--;
  190478. }
  190479. else
  190480. shift += 2;
  190481. dp--;
  190482. }
  190483. break;
  190484. }
  190485. case 4:
  190486. {
  190487. gray = (png_uint_16)((gray&0x0f)*0x11);
  190488. sp = row + (png_size_t)((row_width - 1) >> 1);
  190489. dp = row + (png_size_t)row_width - 1;
  190490. shift = (int)((1 - ((row_width + 1) & 0x01)) << 2);
  190491. for (i = 0; i < row_width; i++)
  190492. {
  190493. value = (*sp >> shift) & 0x0f;
  190494. *dp = (png_byte)(value | (value << 4));
  190495. if (shift == 4)
  190496. {
  190497. shift = 0;
  190498. sp--;
  190499. }
  190500. else
  190501. shift = 4;
  190502. dp--;
  190503. }
  190504. break;
  190505. }
  190506. }
  190507. row_info->bit_depth = 8;
  190508. row_info->pixel_depth = 8;
  190509. row_info->rowbytes = row_width;
  190510. }
  190511. if (trans_value != NULL)
  190512. {
  190513. if (row_info->bit_depth == 8)
  190514. {
  190515. gray = gray & 0xff;
  190516. sp = row + (png_size_t)row_width - 1;
  190517. dp = row + (png_size_t)(row_width << 1) - 1;
  190518. for (i = 0; i < row_width; i++)
  190519. {
  190520. if (*sp == gray)
  190521. *dp-- = 0;
  190522. else
  190523. *dp-- = 0xff;
  190524. *dp-- = *sp--;
  190525. }
  190526. }
  190527. else if (row_info->bit_depth == 16)
  190528. {
  190529. png_byte gray_high = (gray >> 8) & 0xff;
  190530. png_byte gray_low = gray & 0xff;
  190531. sp = row + row_info->rowbytes - 1;
  190532. dp = row + (row_info->rowbytes << 1) - 1;
  190533. for (i = 0; i < row_width; i++)
  190534. {
  190535. if (*(sp-1) == gray_high && *(sp) == gray_low)
  190536. {
  190537. *dp-- = 0;
  190538. *dp-- = 0;
  190539. }
  190540. else
  190541. {
  190542. *dp-- = 0xff;
  190543. *dp-- = 0xff;
  190544. }
  190545. *dp-- = *sp--;
  190546. *dp-- = *sp--;
  190547. }
  190548. }
  190549. row_info->color_type = PNG_COLOR_TYPE_GRAY_ALPHA;
  190550. row_info->channels = 2;
  190551. row_info->pixel_depth = (png_byte)(row_info->bit_depth << 1);
  190552. row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,
  190553. row_width);
  190554. }
  190555. }
  190556. else if (row_info->color_type == PNG_COLOR_TYPE_RGB && trans_value)
  190557. {
  190558. if (row_info->bit_depth == 8)
  190559. {
  190560. png_byte red = trans_value->red & 0xff;
  190561. png_byte green = trans_value->green & 0xff;
  190562. png_byte blue = trans_value->blue & 0xff;
  190563. sp = row + (png_size_t)row_info->rowbytes - 1;
  190564. dp = row + (png_size_t)(row_width << 2) - 1;
  190565. for (i = 0; i < row_width; i++)
  190566. {
  190567. if (*(sp - 2) == red && *(sp - 1) == green && *(sp) == blue)
  190568. *dp-- = 0;
  190569. else
  190570. *dp-- = 0xff;
  190571. *dp-- = *sp--;
  190572. *dp-- = *sp--;
  190573. *dp-- = *sp--;
  190574. }
  190575. }
  190576. else if (row_info->bit_depth == 16)
  190577. {
  190578. png_byte red_high = (trans_value->red >> 8) & 0xff;
  190579. png_byte green_high = (trans_value->green >> 8) & 0xff;
  190580. png_byte blue_high = (trans_value->blue >> 8) & 0xff;
  190581. png_byte red_low = trans_value->red & 0xff;
  190582. png_byte green_low = trans_value->green & 0xff;
  190583. png_byte blue_low = trans_value->blue & 0xff;
  190584. sp = row + row_info->rowbytes - 1;
  190585. dp = row + (png_size_t)(row_width << 3) - 1;
  190586. for (i = 0; i < row_width; i++)
  190587. {
  190588. if (*(sp - 5) == red_high &&
  190589. *(sp - 4) == red_low &&
  190590. *(sp - 3) == green_high &&
  190591. *(sp - 2) == green_low &&
  190592. *(sp - 1) == blue_high &&
  190593. *(sp ) == blue_low)
  190594. {
  190595. *dp-- = 0;
  190596. *dp-- = 0;
  190597. }
  190598. else
  190599. {
  190600. *dp-- = 0xff;
  190601. *dp-- = 0xff;
  190602. }
  190603. *dp-- = *sp--;
  190604. *dp-- = *sp--;
  190605. *dp-- = *sp--;
  190606. *dp-- = *sp--;
  190607. *dp-- = *sp--;
  190608. *dp-- = *sp--;
  190609. }
  190610. }
  190611. row_info->color_type = PNG_COLOR_TYPE_RGB_ALPHA;
  190612. row_info->channels = 4;
  190613. row_info->pixel_depth = (png_byte)(row_info->bit_depth << 2);
  190614. row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,row_width);
  190615. }
  190616. }
  190617. }
  190618. #endif
  190619. #if defined(PNG_READ_DITHER_SUPPORTED)
  190620. void /* PRIVATE */
  190621. png_do_dither(png_row_infop row_info, png_bytep row,
  190622. png_bytep palette_lookup, png_bytep dither_lookup)
  190623. {
  190624. png_bytep sp, dp;
  190625. png_uint_32 i;
  190626. png_uint_32 row_width=row_info->width;
  190627. png_debug(1, "in png_do_dither\n");
  190628. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  190629. if (row != NULL && row_info != NULL)
  190630. #endif
  190631. {
  190632. if (row_info->color_type == PNG_COLOR_TYPE_RGB &&
  190633. palette_lookup && row_info->bit_depth == 8)
  190634. {
  190635. int r, g, b, p;
  190636. sp = row;
  190637. dp = row;
  190638. for (i = 0; i < row_width; i++)
  190639. {
  190640. r = *sp++;
  190641. g = *sp++;
  190642. b = *sp++;
  190643. /* this looks real messy, but the compiler will reduce
  190644. it down to a reasonable formula. For example, with
  190645. 5 bits per color, we get:
  190646. p = (((r >> 3) & 0x1f) << 10) |
  190647. (((g >> 3) & 0x1f) << 5) |
  190648. ((b >> 3) & 0x1f);
  190649. */
  190650. p = (((r >> (8 - PNG_DITHER_RED_BITS)) &
  190651. ((1 << PNG_DITHER_RED_BITS) - 1)) <<
  190652. (PNG_DITHER_GREEN_BITS + PNG_DITHER_BLUE_BITS)) |
  190653. (((g >> (8 - PNG_DITHER_GREEN_BITS)) &
  190654. ((1 << PNG_DITHER_GREEN_BITS) - 1)) <<
  190655. (PNG_DITHER_BLUE_BITS)) |
  190656. ((b >> (8 - PNG_DITHER_BLUE_BITS)) &
  190657. ((1 << PNG_DITHER_BLUE_BITS) - 1));
  190658. *dp++ = palette_lookup[p];
  190659. }
  190660. row_info->color_type = PNG_COLOR_TYPE_PALETTE;
  190661. row_info->channels = 1;
  190662. row_info->pixel_depth = row_info->bit_depth;
  190663. row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,row_width);
  190664. }
  190665. else if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA &&
  190666. palette_lookup != NULL && row_info->bit_depth == 8)
  190667. {
  190668. int r, g, b, p;
  190669. sp = row;
  190670. dp = row;
  190671. for (i = 0; i < row_width; i++)
  190672. {
  190673. r = *sp++;
  190674. g = *sp++;
  190675. b = *sp++;
  190676. sp++;
  190677. p = (((r >> (8 - PNG_DITHER_RED_BITS)) &
  190678. ((1 << PNG_DITHER_RED_BITS) - 1)) <<
  190679. (PNG_DITHER_GREEN_BITS + PNG_DITHER_BLUE_BITS)) |
  190680. (((g >> (8 - PNG_DITHER_GREEN_BITS)) &
  190681. ((1 << PNG_DITHER_GREEN_BITS) - 1)) <<
  190682. (PNG_DITHER_BLUE_BITS)) |
  190683. ((b >> (8 - PNG_DITHER_BLUE_BITS)) &
  190684. ((1 << PNG_DITHER_BLUE_BITS) - 1));
  190685. *dp++ = palette_lookup[p];
  190686. }
  190687. row_info->color_type = PNG_COLOR_TYPE_PALETTE;
  190688. row_info->channels = 1;
  190689. row_info->pixel_depth = row_info->bit_depth;
  190690. row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,row_width);
  190691. }
  190692. else if (row_info->color_type == PNG_COLOR_TYPE_PALETTE &&
  190693. dither_lookup && row_info->bit_depth == 8)
  190694. {
  190695. sp = row;
  190696. for (i = 0; i < row_width; i++, sp++)
  190697. {
  190698. *sp = dither_lookup[*sp];
  190699. }
  190700. }
  190701. }
  190702. }
  190703. #endif
  190704. #ifdef PNG_FLOATING_POINT_SUPPORTED
  190705. #if defined(PNG_READ_GAMMA_SUPPORTED)
  190706. static PNG_CONST int png_gamma_shift[] =
  190707. {0x10, 0x21, 0x42, 0x84, 0x110, 0x248, 0x550, 0xff0, 0x00};
  190708. /* We build the 8- or 16-bit gamma tables here. Note that for 16-bit
  190709. * tables, we don't make a full table if we are reducing to 8-bit in
  190710. * the future. Note also how the gamma_16 tables are segmented so that
  190711. * we don't need to allocate > 64K chunks for a full 16-bit table.
  190712. */
  190713. void /* PRIVATE */
  190714. png_build_gamma_table(png_structp png_ptr)
  190715. {
  190716. png_debug(1, "in png_build_gamma_table\n");
  190717. if (png_ptr->bit_depth <= 8)
  190718. {
  190719. int i;
  190720. double g;
  190721. if (png_ptr->screen_gamma > .000001)
  190722. g = 1.0 / (png_ptr->gamma * png_ptr->screen_gamma);
  190723. else
  190724. g = 1.0;
  190725. png_ptr->gamma_table = (png_bytep)png_malloc(png_ptr,
  190726. (png_uint_32)256);
  190727. for (i = 0; i < 256; i++)
  190728. {
  190729. png_ptr->gamma_table[i] = (png_byte)(pow((double)i / 255.0,
  190730. g) * 255.0 + .5);
  190731. }
  190732. #if defined(PNG_READ_BACKGROUND_SUPPORTED) || \
  190733. defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
  190734. if (png_ptr->transformations & ((PNG_BACKGROUND) | PNG_RGB_TO_GRAY))
  190735. {
  190736. g = 1.0 / (png_ptr->gamma);
  190737. png_ptr->gamma_to_1 = (png_bytep)png_malloc(png_ptr,
  190738. (png_uint_32)256);
  190739. for (i = 0; i < 256; i++)
  190740. {
  190741. png_ptr->gamma_to_1[i] = (png_byte)(pow((double)i / 255.0,
  190742. g) * 255.0 + .5);
  190743. }
  190744. png_ptr->gamma_from_1 = (png_bytep)png_malloc(png_ptr,
  190745. (png_uint_32)256);
  190746. if(png_ptr->screen_gamma > 0.000001)
  190747. g = 1.0 / png_ptr->screen_gamma;
  190748. else
  190749. g = png_ptr->gamma; /* probably doing rgb_to_gray */
  190750. for (i = 0; i < 256; i++)
  190751. {
  190752. png_ptr->gamma_from_1[i] = (png_byte)(pow((double)i / 255.0,
  190753. g) * 255.0 + .5);
  190754. }
  190755. }
  190756. #endif /* PNG_READ_BACKGROUND_SUPPORTED || PNG_RGB_TO_GRAY_SUPPORTED */
  190757. }
  190758. else
  190759. {
  190760. double g;
  190761. int i, j, shift, num;
  190762. int sig_bit;
  190763. png_uint_32 ig;
  190764. if (png_ptr->color_type & PNG_COLOR_MASK_COLOR)
  190765. {
  190766. sig_bit = (int)png_ptr->sig_bit.red;
  190767. if ((int)png_ptr->sig_bit.green > sig_bit)
  190768. sig_bit = png_ptr->sig_bit.green;
  190769. if ((int)png_ptr->sig_bit.blue > sig_bit)
  190770. sig_bit = png_ptr->sig_bit.blue;
  190771. }
  190772. else
  190773. {
  190774. sig_bit = (int)png_ptr->sig_bit.gray;
  190775. }
  190776. if (sig_bit > 0)
  190777. shift = 16 - sig_bit;
  190778. else
  190779. shift = 0;
  190780. if (png_ptr->transformations & PNG_16_TO_8)
  190781. {
  190782. if (shift < (16 - PNG_MAX_GAMMA_8))
  190783. shift = (16 - PNG_MAX_GAMMA_8);
  190784. }
  190785. if (shift > 8)
  190786. shift = 8;
  190787. if (shift < 0)
  190788. shift = 0;
  190789. png_ptr->gamma_shift = (png_byte)shift;
  190790. num = (1 << (8 - shift));
  190791. if (png_ptr->screen_gamma > .000001)
  190792. g = 1.0 / (png_ptr->gamma * png_ptr->screen_gamma);
  190793. else
  190794. g = 1.0;
  190795. png_ptr->gamma_16_table = (png_uint_16pp)png_malloc(png_ptr,
  190796. (png_uint_32)(num * png_sizeof (png_uint_16p)));
  190797. if (png_ptr->transformations & (PNG_16_TO_8 | PNG_BACKGROUND))
  190798. {
  190799. double fin, fout;
  190800. png_uint_32 last, max;
  190801. for (i = 0; i < num; i++)
  190802. {
  190803. png_ptr->gamma_16_table[i] = (png_uint_16p)png_malloc(png_ptr,
  190804. (png_uint_32)(256 * png_sizeof (png_uint_16)));
  190805. }
  190806. g = 1.0 / g;
  190807. last = 0;
  190808. for (i = 0; i < 256; i++)
  190809. {
  190810. fout = ((double)i + 0.5) / 256.0;
  190811. fin = pow(fout, g);
  190812. max = (png_uint_32)(fin * (double)((png_uint_32)num << 8));
  190813. while (last <= max)
  190814. {
  190815. png_ptr->gamma_16_table[(int)(last & (0xff >> shift))]
  190816. [(int)(last >> (8 - shift))] = (png_uint_16)(
  190817. (png_uint_16)i | ((png_uint_16)i << 8));
  190818. last++;
  190819. }
  190820. }
  190821. while (last < ((png_uint_32)num << 8))
  190822. {
  190823. png_ptr->gamma_16_table[(int)(last & (0xff >> shift))]
  190824. [(int)(last >> (8 - shift))] = (png_uint_16)65535L;
  190825. last++;
  190826. }
  190827. }
  190828. else
  190829. {
  190830. for (i = 0; i < num; i++)
  190831. {
  190832. png_ptr->gamma_16_table[i] = (png_uint_16p)png_malloc(png_ptr,
  190833. (png_uint_32)(256 * png_sizeof (png_uint_16)));
  190834. ig = (((png_uint_32)i * (png_uint_32)png_gamma_shift[shift]) >> 4);
  190835. for (j = 0; j < 256; j++)
  190836. {
  190837. png_ptr->gamma_16_table[i][j] =
  190838. (png_uint_16)(pow((double)(ig + ((png_uint_32)j << 8)) /
  190839. 65535.0, g) * 65535.0 + .5);
  190840. }
  190841. }
  190842. }
  190843. #if defined(PNG_READ_BACKGROUND_SUPPORTED) || \
  190844. defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
  190845. if (png_ptr->transformations & (PNG_BACKGROUND | PNG_RGB_TO_GRAY))
  190846. {
  190847. g = 1.0 / (png_ptr->gamma);
  190848. png_ptr->gamma_16_to_1 = (png_uint_16pp)png_malloc(png_ptr,
  190849. (png_uint_32)(num * png_sizeof (png_uint_16p )));
  190850. for (i = 0; i < num; i++)
  190851. {
  190852. png_ptr->gamma_16_to_1[i] = (png_uint_16p)png_malloc(png_ptr,
  190853. (png_uint_32)(256 * png_sizeof (png_uint_16)));
  190854. ig = (((png_uint_32)i *
  190855. (png_uint_32)png_gamma_shift[shift]) >> 4);
  190856. for (j = 0; j < 256; j++)
  190857. {
  190858. png_ptr->gamma_16_to_1[i][j] =
  190859. (png_uint_16)(pow((double)(ig + ((png_uint_32)j << 8)) /
  190860. 65535.0, g) * 65535.0 + .5);
  190861. }
  190862. }
  190863. if(png_ptr->screen_gamma > 0.000001)
  190864. g = 1.0 / png_ptr->screen_gamma;
  190865. else
  190866. g = png_ptr->gamma; /* probably doing rgb_to_gray */
  190867. png_ptr->gamma_16_from_1 = (png_uint_16pp)png_malloc(png_ptr,
  190868. (png_uint_32)(num * png_sizeof (png_uint_16p)));
  190869. for (i = 0; i < num; i++)
  190870. {
  190871. png_ptr->gamma_16_from_1[i] = (png_uint_16p)png_malloc(png_ptr,
  190872. (png_uint_32)(256 * png_sizeof (png_uint_16)));
  190873. ig = (((png_uint_32)i *
  190874. (png_uint_32)png_gamma_shift[shift]) >> 4);
  190875. for (j = 0; j < 256; j++)
  190876. {
  190877. png_ptr->gamma_16_from_1[i][j] =
  190878. (png_uint_16)(pow((double)(ig + ((png_uint_32)j << 8)) /
  190879. 65535.0, g) * 65535.0 + .5);
  190880. }
  190881. }
  190882. }
  190883. #endif /* PNG_READ_BACKGROUND_SUPPORTED || PNG_RGB_TO_GRAY_SUPPORTED */
  190884. }
  190885. }
  190886. #endif
  190887. /* To do: install integer version of png_build_gamma_table here */
  190888. #endif
  190889. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  190890. /* undoes intrapixel differencing */
  190891. void /* PRIVATE */
  190892. png_do_read_intrapixel(png_row_infop row_info, png_bytep row)
  190893. {
  190894. png_debug(1, "in png_do_read_intrapixel\n");
  190895. if (
  190896. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  190897. row != NULL && row_info != NULL &&
  190898. #endif
  190899. (row_info->color_type & PNG_COLOR_MASK_COLOR))
  190900. {
  190901. int bytes_per_pixel;
  190902. png_uint_32 row_width = row_info->width;
  190903. if (row_info->bit_depth == 8)
  190904. {
  190905. png_bytep rp;
  190906. png_uint_32 i;
  190907. if (row_info->color_type == PNG_COLOR_TYPE_RGB)
  190908. bytes_per_pixel = 3;
  190909. else if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  190910. bytes_per_pixel = 4;
  190911. else
  190912. return;
  190913. for (i = 0, rp = row; i < row_width; i++, rp += bytes_per_pixel)
  190914. {
  190915. *(rp) = (png_byte)((256 + *rp + *(rp+1))&0xff);
  190916. *(rp+2) = (png_byte)((256 + *(rp+2) + *(rp+1))&0xff);
  190917. }
  190918. }
  190919. else if (row_info->bit_depth == 16)
  190920. {
  190921. png_bytep rp;
  190922. png_uint_32 i;
  190923. if (row_info->color_type == PNG_COLOR_TYPE_RGB)
  190924. bytes_per_pixel = 6;
  190925. else if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  190926. bytes_per_pixel = 8;
  190927. else
  190928. return;
  190929. for (i = 0, rp = row; i < row_width; i++, rp += bytes_per_pixel)
  190930. {
  190931. png_uint_32 s0 = (*(rp ) << 8) | *(rp+1);
  190932. png_uint_32 s1 = (*(rp+2) << 8) | *(rp+3);
  190933. png_uint_32 s2 = (*(rp+4) << 8) | *(rp+5);
  190934. png_uint_32 red = (png_uint_32)((s0+s1+65536L) & 0xffffL);
  190935. png_uint_32 blue = (png_uint_32)((s2+s1+65536L) & 0xffffL);
  190936. *(rp ) = (png_byte)((red >> 8) & 0xff);
  190937. *(rp+1) = (png_byte)(red & 0xff);
  190938. *(rp+4) = (png_byte)((blue >> 8) & 0xff);
  190939. *(rp+5) = (png_byte)(blue & 0xff);
  190940. }
  190941. }
  190942. }
  190943. }
  190944. #endif /* PNG_MNG_FEATURES_SUPPORTED */
  190945. #endif /* PNG_READ_SUPPORTED */
  190946. /*** End of inlined file: pngrtran.c ***/
  190947. /*** Start of inlined file: pngrutil.c ***/
  190948. /* pngrutil.c - utilities to read a PNG file
  190949. *
  190950. * Last changed in libpng 1.2.21 [October 4, 2007]
  190951. * For conditions of distribution and use, see copyright notice in png.h
  190952. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  190953. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  190954. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  190955. *
  190956. * This file contains routines that are only called from within
  190957. * libpng itself during the course of reading an image.
  190958. */
  190959. #define PNG_INTERNAL
  190960. #if defined(PNG_READ_SUPPORTED)
  190961. #if defined(_WIN32_WCE) && (_WIN32_WCE<0x500)
  190962. # define WIN32_WCE_OLD
  190963. #endif
  190964. #ifdef PNG_FLOATING_POINT_SUPPORTED
  190965. # if defined(WIN32_WCE_OLD)
  190966. /* strtod() function is not supported on WindowsCE */
  190967. __inline double png_strtod(png_structp png_ptr, PNG_CONST char *nptr, char **endptr)
  190968. {
  190969. double result = 0;
  190970. int len;
  190971. wchar_t *str, *end;
  190972. len = MultiByteToWideChar(CP_ACP, 0, nptr, -1, NULL, 0);
  190973. str = (wchar_t *)png_malloc(png_ptr, len * sizeof(wchar_t));
  190974. if ( NULL != str )
  190975. {
  190976. MultiByteToWideChar(CP_ACP, 0, nptr, -1, str, len);
  190977. result = wcstod(str, &end);
  190978. len = WideCharToMultiByte(CP_ACP, 0, end, -1, NULL, 0, NULL, NULL);
  190979. *endptr = (char *)nptr + (png_strlen(nptr) - len + 1);
  190980. png_free(png_ptr, str);
  190981. }
  190982. return result;
  190983. }
  190984. # else
  190985. # define png_strtod(p,a,b) strtod(a,b)
  190986. # endif
  190987. #endif
  190988. png_uint_32 PNGAPI
  190989. png_get_uint_31(png_structp png_ptr, png_bytep buf)
  190990. {
  190991. png_uint_32 i = png_get_uint_32(buf);
  190992. if (i > PNG_UINT_31_MAX)
  190993. png_error(png_ptr, "PNG unsigned integer out of range.");
  190994. return (i);
  190995. }
  190996. #ifndef PNG_READ_BIG_ENDIAN_SUPPORTED
  190997. /* Grab an unsigned 32-bit integer from a buffer in big-endian format. */
  190998. png_uint_32 PNGAPI
  190999. png_get_uint_32(png_bytep buf)
  191000. {
  191001. png_uint_32 i = ((png_uint_32)(*buf) << 24) +
  191002. ((png_uint_32)(*(buf + 1)) << 16) +
  191003. ((png_uint_32)(*(buf + 2)) << 8) +
  191004. (png_uint_32)(*(buf + 3));
  191005. return (i);
  191006. }
  191007. /* Grab a signed 32-bit integer from a buffer in big-endian format. The
  191008. * data is stored in the PNG file in two's complement format, and it is
  191009. * assumed that the machine format for signed integers is the same. */
  191010. png_int_32 PNGAPI
  191011. png_get_int_32(png_bytep buf)
  191012. {
  191013. png_int_32 i = ((png_int_32)(*buf) << 24) +
  191014. ((png_int_32)(*(buf + 1)) << 16) +
  191015. ((png_int_32)(*(buf + 2)) << 8) +
  191016. (png_int_32)(*(buf + 3));
  191017. return (i);
  191018. }
  191019. /* Grab an unsigned 16-bit integer from a buffer in big-endian format. */
  191020. png_uint_16 PNGAPI
  191021. png_get_uint_16(png_bytep buf)
  191022. {
  191023. png_uint_16 i = (png_uint_16)(((png_uint_16)(*buf) << 8) +
  191024. (png_uint_16)(*(buf + 1)));
  191025. return (i);
  191026. }
  191027. #endif /* PNG_READ_BIG_ENDIAN_SUPPORTED */
  191028. /* Read data, and (optionally) run it through the CRC. */
  191029. void /* PRIVATE */
  191030. png_crc_read(png_structp png_ptr, png_bytep buf, png_size_t length)
  191031. {
  191032. if(png_ptr == NULL) return;
  191033. png_read_data(png_ptr, buf, length);
  191034. png_calculate_crc(png_ptr, buf, length);
  191035. }
  191036. /* Optionally skip data and then check the CRC. Depending on whether we
  191037. are reading a ancillary or critical chunk, and how the program has set
  191038. things up, we may calculate the CRC on the data and print a message.
  191039. Returns '1' if there was a CRC error, '0' otherwise. */
  191040. int /* PRIVATE */
  191041. png_crc_finish(png_structp png_ptr, png_uint_32 skip)
  191042. {
  191043. png_size_t i;
  191044. png_size_t istop = png_ptr->zbuf_size;
  191045. for (i = (png_size_t)skip; i > istop; i -= istop)
  191046. {
  191047. png_crc_read(png_ptr, png_ptr->zbuf, png_ptr->zbuf_size);
  191048. }
  191049. if (i)
  191050. {
  191051. png_crc_read(png_ptr, png_ptr->zbuf, i);
  191052. }
  191053. if (png_crc_error(png_ptr))
  191054. {
  191055. if (((png_ptr->chunk_name[0] & 0x20) && /* Ancillary */
  191056. !(png_ptr->flags & PNG_FLAG_CRC_ANCILLARY_NOWARN)) ||
  191057. (!(png_ptr->chunk_name[0] & 0x20) && /* Critical */
  191058. (png_ptr->flags & PNG_FLAG_CRC_CRITICAL_USE)))
  191059. {
  191060. png_chunk_warning(png_ptr, "CRC error");
  191061. }
  191062. else
  191063. {
  191064. png_chunk_error(png_ptr, "CRC error");
  191065. }
  191066. return (1);
  191067. }
  191068. return (0);
  191069. }
  191070. /* Compare the CRC stored in the PNG file with that calculated by libpng from
  191071. the data it has read thus far. */
  191072. int /* PRIVATE */
  191073. png_crc_error(png_structp png_ptr)
  191074. {
  191075. png_byte crc_bytes[4];
  191076. png_uint_32 crc;
  191077. int need_crc = 1;
  191078. if (png_ptr->chunk_name[0] & 0x20) /* ancillary */
  191079. {
  191080. if ((png_ptr->flags & PNG_FLAG_CRC_ANCILLARY_MASK) ==
  191081. (PNG_FLAG_CRC_ANCILLARY_USE | PNG_FLAG_CRC_ANCILLARY_NOWARN))
  191082. need_crc = 0;
  191083. }
  191084. else /* critical */
  191085. {
  191086. if (png_ptr->flags & PNG_FLAG_CRC_CRITICAL_IGNORE)
  191087. need_crc = 0;
  191088. }
  191089. png_read_data(png_ptr, crc_bytes, 4);
  191090. if (need_crc)
  191091. {
  191092. crc = png_get_uint_32(crc_bytes);
  191093. return ((int)(crc != png_ptr->crc));
  191094. }
  191095. else
  191096. return (0);
  191097. }
  191098. #if defined(PNG_READ_zTXt_SUPPORTED) || defined(PNG_READ_iTXt_SUPPORTED) || \
  191099. defined(PNG_READ_iCCP_SUPPORTED)
  191100. /*
  191101. * Decompress trailing data in a chunk. The assumption is that chunkdata
  191102. * points at an allocated area holding the contents of a chunk with a
  191103. * trailing compressed part. What we get back is an allocated area
  191104. * holding the original prefix part and an uncompressed version of the
  191105. * trailing part (the malloc area passed in is freed).
  191106. */
  191107. png_charp /* PRIVATE */
  191108. png_decompress_chunk(png_structp png_ptr, int comp_type,
  191109. png_charp chunkdata, png_size_t chunklength,
  191110. png_size_t prefix_size, png_size_t *newlength)
  191111. {
  191112. static PNG_CONST char msg[] = "Error decoding compressed text";
  191113. png_charp text;
  191114. png_size_t text_size;
  191115. if (comp_type == PNG_COMPRESSION_TYPE_BASE)
  191116. {
  191117. int ret = Z_OK;
  191118. png_ptr->zstream.next_in = (png_bytep)(chunkdata + prefix_size);
  191119. png_ptr->zstream.avail_in = (uInt)(chunklength - prefix_size);
  191120. png_ptr->zstream.next_out = png_ptr->zbuf;
  191121. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  191122. text_size = 0;
  191123. text = NULL;
  191124. while (png_ptr->zstream.avail_in)
  191125. {
  191126. ret = inflate(&png_ptr->zstream, Z_PARTIAL_FLUSH);
  191127. if (ret != Z_OK && ret != Z_STREAM_END)
  191128. {
  191129. if (png_ptr->zstream.msg != NULL)
  191130. png_warning(png_ptr, png_ptr->zstream.msg);
  191131. else
  191132. png_warning(png_ptr, msg);
  191133. inflateReset(&png_ptr->zstream);
  191134. png_ptr->zstream.avail_in = 0;
  191135. if (text == NULL)
  191136. {
  191137. text_size = prefix_size + png_sizeof(msg) + 1;
  191138. text = (png_charp)png_malloc_warn(png_ptr, text_size);
  191139. if (text == NULL)
  191140. {
  191141. png_free(png_ptr,chunkdata);
  191142. png_error(png_ptr,"Not enough memory to decompress chunk");
  191143. }
  191144. png_memcpy(text, chunkdata, prefix_size);
  191145. }
  191146. text[text_size - 1] = 0x00;
  191147. /* Copy what we can of the error message into the text chunk */
  191148. text_size = (png_size_t)(chunklength - (text - chunkdata) - 1);
  191149. text_size = png_sizeof(msg) > text_size ? text_size :
  191150. png_sizeof(msg);
  191151. png_memcpy(text + prefix_size, msg, text_size + 1);
  191152. break;
  191153. }
  191154. if (!png_ptr->zstream.avail_out || ret == Z_STREAM_END)
  191155. {
  191156. if (text == NULL)
  191157. {
  191158. text_size = prefix_size +
  191159. png_ptr->zbuf_size - png_ptr->zstream.avail_out;
  191160. text = (png_charp)png_malloc_warn(png_ptr, text_size + 1);
  191161. if (text == NULL)
  191162. {
  191163. png_free(png_ptr,chunkdata);
  191164. png_error(png_ptr,"Not enough memory to decompress chunk.");
  191165. }
  191166. png_memcpy(text + prefix_size, png_ptr->zbuf,
  191167. text_size - prefix_size);
  191168. png_memcpy(text, chunkdata, prefix_size);
  191169. *(text + text_size) = 0x00;
  191170. }
  191171. else
  191172. {
  191173. png_charp tmp;
  191174. tmp = text;
  191175. text = (png_charp)png_malloc_warn(png_ptr,
  191176. (png_uint_32)(text_size +
  191177. png_ptr->zbuf_size - png_ptr->zstream.avail_out + 1));
  191178. if (text == NULL)
  191179. {
  191180. png_free(png_ptr, tmp);
  191181. png_free(png_ptr, chunkdata);
  191182. png_error(png_ptr,"Not enough memory to decompress chunk..");
  191183. }
  191184. png_memcpy(text, tmp, text_size);
  191185. png_free(png_ptr, tmp);
  191186. png_memcpy(text + text_size, png_ptr->zbuf,
  191187. (png_ptr->zbuf_size - png_ptr->zstream.avail_out));
  191188. text_size += png_ptr->zbuf_size - png_ptr->zstream.avail_out;
  191189. *(text + text_size) = 0x00;
  191190. }
  191191. if (ret == Z_STREAM_END)
  191192. break;
  191193. else
  191194. {
  191195. png_ptr->zstream.next_out = png_ptr->zbuf;
  191196. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  191197. }
  191198. }
  191199. }
  191200. if (ret != Z_STREAM_END)
  191201. {
  191202. #if !defined(PNG_NO_STDIO) && !defined(_WIN32_WCE)
  191203. char umsg[52];
  191204. if (ret == Z_BUF_ERROR)
  191205. png_snprintf(umsg, 52,
  191206. "Buffer error in compressed datastream in %s chunk",
  191207. png_ptr->chunk_name);
  191208. else if (ret == Z_DATA_ERROR)
  191209. png_snprintf(umsg, 52,
  191210. "Data error in compressed datastream in %s chunk",
  191211. png_ptr->chunk_name);
  191212. else
  191213. png_snprintf(umsg, 52,
  191214. "Incomplete compressed datastream in %s chunk",
  191215. png_ptr->chunk_name);
  191216. png_warning(png_ptr, umsg);
  191217. #else
  191218. png_warning(png_ptr,
  191219. "Incomplete compressed datastream in chunk other than IDAT");
  191220. #endif
  191221. text_size=prefix_size;
  191222. if (text == NULL)
  191223. {
  191224. text = (png_charp)png_malloc_warn(png_ptr, text_size+1);
  191225. if (text == NULL)
  191226. {
  191227. png_free(png_ptr, chunkdata);
  191228. png_error(png_ptr,"Not enough memory for text.");
  191229. }
  191230. png_memcpy(text, chunkdata, prefix_size);
  191231. }
  191232. *(text + text_size) = 0x00;
  191233. }
  191234. inflateReset(&png_ptr->zstream);
  191235. png_ptr->zstream.avail_in = 0;
  191236. png_free(png_ptr, chunkdata);
  191237. chunkdata = text;
  191238. *newlength=text_size;
  191239. }
  191240. else /* if (comp_type != PNG_COMPRESSION_TYPE_BASE) */
  191241. {
  191242. #if !defined(PNG_NO_STDIO) && !defined(_WIN32_WCE)
  191243. char umsg[50];
  191244. png_snprintf(umsg, 50,
  191245. "Unknown zTXt compression type %d", comp_type);
  191246. png_warning(png_ptr, umsg);
  191247. #else
  191248. png_warning(png_ptr, "Unknown zTXt compression type");
  191249. #endif
  191250. *(chunkdata + prefix_size) = 0x00;
  191251. *newlength=prefix_size;
  191252. }
  191253. return chunkdata;
  191254. }
  191255. #endif
  191256. /* read and check the IDHR chunk */
  191257. void /* PRIVATE */
  191258. png_handle_IHDR(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  191259. {
  191260. png_byte buf[13];
  191261. png_uint_32 width, height;
  191262. int bit_depth, color_type, compression_type, filter_type;
  191263. int interlace_type;
  191264. png_debug(1, "in png_handle_IHDR\n");
  191265. if (png_ptr->mode & PNG_HAVE_IHDR)
  191266. png_error(png_ptr, "Out of place IHDR");
  191267. /* check the length */
  191268. if (length != 13)
  191269. png_error(png_ptr, "Invalid IHDR chunk");
  191270. png_ptr->mode |= PNG_HAVE_IHDR;
  191271. png_crc_read(png_ptr, buf, 13);
  191272. png_crc_finish(png_ptr, 0);
  191273. width = png_get_uint_31(png_ptr, buf);
  191274. height = png_get_uint_31(png_ptr, buf + 4);
  191275. bit_depth = buf[8];
  191276. color_type = buf[9];
  191277. compression_type = buf[10];
  191278. filter_type = buf[11];
  191279. interlace_type = buf[12];
  191280. /* set internal variables */
  191281. png_ptr->width = width;
  191282. png_ptr->height = height;
  191283. png_ptr->bit_depth = (png_byte)bit_depth;
  191284. png_ptr->interlaced = (png_byte)interlace_type;
  191285. png_ptr->color_type = (png_byte)color_type;
  191286. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  191287. png_ptr->filter_type = (png_byte)filter_type;
  191288. #endif
  191289. png_ptr->compression_type = (png_byte)compression_type;
  191290. /* find number of channels */
  191291. switch (png_ptr->color_type)
  191292. {
  191293. case PNG_COLOR_TYPE_GRAY:
  191294. case PNG_COLOR_TYPE_PALETTE:
  191295. png_ptr->channels = 1;
  191296. break;
  191297. case PNG_COLOR_TYPE_RGB:
  191298. png_ptr->channels = 3;
  191299. break;
  191300. case PNG_COLOR_TYPE_GRAY_ALPHA:
  191301. png_ptr->channels = 2;
  191302. break;
  191303. case PNG_COLOR_TYPE_RGB_ALPHA:
  191304. png_ptr->channels = 4;
  191305. break;
  191306. }
  191307. /* set up other useful info */
  191308. png_ptr->pixel_depth = (png_byte)(png_ptr->bit_depth *
  191309. png_ptr->channels);
  191310. png_ptr->rowbytes = PNG_ROWBYTES(png_ptr->pixel_depth,png_ptr->width);
  191311. png_debug1(3,"bit_depth = %d\n", png_ptr->bit_depth);
  191312. png_debug1(3,"channels = %d\n", png_ptr->channels);
  191313. png_debug1(3,"rowbytes = %lu\n", png_ptr->rowbytes);
  191314. png_set_IHDR(png_ptr, info_ptr, width, height, bit_depth,
  191315. color_type, interlace_type, compression_type, filter_type);
  191316. }
  191317. /* read and check the palette */
  191318. void /* PRIVATE */
  191319. png_handle_PLTE(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  191320. {
  191321. png_color palette[PNG_MAX_PALETTE_LENGTH];
  191322. int num, i;
  191323. #ifndef PNG_NO_POINTER_INDEXING
  191324. png_colorp pal_ptr;
  191325. #endif
  191326. png_debug(1, "in png_handle_PLTE\n");
  191327. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  191328. png_error(png_ptr, "Missing IHDR before PLTE");
  191329. else if (png_ptr->mode & PNG_HAVE_IDAT)
  191330. {
  191331. png_warning(png_ptr, "Invalid PLTE after IDAT");
  191332. png_crc_finish(png_ptr, length);
  191333. return;
  191334. }
  191335. else if (png_ptr->mode & PNG_HAVE_PLTE)
  191336. png_error(png_ptr, "Duplicate PLTE chunk");
  191337. png_ptr->mode |= PNG_HAVE_PLTE;
  191338. if (!(png_ptr->color_type&PNG_COLOR_MASK_COLOR))
  191339. {
  191340. png_warning(png_ptr,
  191341. "Ignoring PLTE chunk in grayscale PNG");
  191342. png_crc_finish(png_ptr, length);
  191343. return;
  191344. }
  191345. #if !defined(PNG_READ_OPT_PLTE_SUPPORTED)
  191346. if (png_ptr->color_type != PNG_COLOR_TYPE_PALETTE)
  191347. {
  191348. png_crc_finish(png_ptr, length);
  191349. return;
  191350. }
  191351. #endif
  191352. if (length > 3*PNG_MAX_PALETTE_LENGTH || length % 3)
  191353. {
  191354. if (png_ptr->color_type != PNG_COLOR_TYPE_PALETTE)
  191355. {
  191356. png_warning(png_ptr, "Invalid palette chunk");
  191357. png_crc_finish(png_ptr, length);
  191358. return;
  191359. }
  191360. else
  191361. {
  191362. png_error(png_ptr, "Invalid palette chunk");
  191363. }
  191364. }
  191365. num = (int)length / 3;
  191366. #ifndef PNG_NO_POINTER_INDEXING
  191367. for (i = 0, pal_ptr = palette; i < num; i++, pal_ptr++)
  191368. {
  191369. png_byte buf[3];
  191370. png_crc_read(png_ptr, buf, 3);
  191371. pal_ptr->red = buf[0];
  191372. pal_ptr->green = buf[1];
  191373. pal_ptr->blue = buf[2];
  191374. }
  191375. #else
  191376. for (i = 0; i < num; i++)
  191377. {
  191378. png_byte buf[3];
  191379. png_crc_read(png_ptr, buf, 3);
  191380. /* don't depend upon png_color being any order */
  191381. palette[i].red = buf[0];
  191382. palette[i].green = buf[1];
  191383. palette[i].blue = buf[2];
  191384. }
  191385. #endif
  191386. /* If we actually NEED the PLTE chunk (ie for a paletted image), we do
  191387. whatever the normal CRC configuration tells us. However, if we
  191388. have an RGB image, the PLTE can be considered ancillary, so
  191389. we will act as though it is. */
  191390. #if !defined(PNG_READ_OPT_PLTE_SUPPORTED)
  191391. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  191392. #endif
  191393. {
  191394. png_crc_finish(png_ptr, 0);
  191395. }
  191396. #if !defined(PNG_READ_OPT_PLTE_SUPPORTED)
  191397. else if (png_crc_error(png_ptr)) /* Only if we have a CRC error */
  191398. {
  191399. /* If we don't want to use the data from an ancillary chunk,
  191400. we have two options: an error abort, or a warning and we
  191401. ignore the data in this chunk (which should be OK, since
  191402. it's considered ancillary for a RGB or RGBA image). */
  191403. if (!(png_ptr->flags & PNG_FLAG_CRC_ANCILLARY_USE))
  191404. {
  191405. if (png_ptr->flags & PNG_FLAG_CRC_ANCILLARY_NOWARN)
  191406. {
  191407. png_chunk_error(png_ptr, "CRC error");
  191408. }
  191409. else
  191410. {
  191411. png_chunk_warning(png_ptr, "CRC error");
  191412. return;
  191413. }
  191414. }
  191415. /* Otherwise, we (optionally) emit a warning and use the chunk. */
  191416. else if (!(png_ptr->flags & PNG_FLAG_CRC_ANCILLARY_NOWARN))
  191417. {
  191418. png_chunk_warning(png_ptr, "CRC error");
  191419. }
  191420. }
  191421. #endif
  191422. png_set_PLTE(png_ptr, info_ptr, palette, num);
  191423. #if defined(PNG_READ_tRNS_SUPPORTED)
  191424. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  191425. {
  191426. if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_tRNS))
  191427. {
  191428. if (png_ptr->num_trans > (png_uint_16)num)
  191429. {
  191430. png_warning(png_ptr, "Truncating incorrect tRNS chunk length");
  191431. png_ptr->num_trans = (png_uint_16)num;
  191432. }
  191433. if (info_ptr->num_trans > (png_uint_16)num)
  191434. {
  191435. png_warning(png_ptr, "Truncating incorrect info tRNS chunk length");
  191436. info_ptr->num_trans = (png_uint_16)num;
  191437. }
  191438. }
  191439. }
  191440. #endif
  191441. }
  191442. void /* PRIVATE */
  191443. png_handle_IEND(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  191444. {
  191445. png_debug(1, "in png_handle_IEND\n");
  191446. if (!(png_ptr->mode & PNG_HAVE_IHDR) || !(png_ptr->mode & PNG_HAVE_IDAT))
  191447. {
  191448. png_error(png_ptr, "No image in file");
  191449. }
  191450. png_ptr->mode |= (PNG_AFTER_IDAT | PNG_HAVE_IEND);
  191451. if (length != 0)
  191452. {
  191453. png_warning(png_ptr, "Incorrect IEND chunk length");
  191454. }
  191455. png_crc_finish(png_ptr, length);
  191456. info_ptr =info_ptr; /* quiet compiler warnings about unused info_ptr */
  191457. }
  191458. #if defined(PNG_READ_gAMA_SUPPORTED)
  191459. void /* PRIVATE */
  191460. png_handle_gAMA(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  191461. {
  191462. png_fixed_point igamma;
  191463. #ifdef PNG_FLOATING_POINT_SUPPORTED
  191464. float file_gamma;
  191465. #endif
  191466. png_byte buf[4];
  191467. png_debug(1, "in png_handle_gAMA\n");
  191468. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  191469. png_error(png_ptr, "Missing IHDR before gAMA");
  191470. else if (png_ptr->mode & PNG_HAVE_IDAT)
  191471. {
  191472. png_warning(png_ptr, "Invalid gAMA after IDAT");
  191473. png_crc_finish(png_ptr, length);
  191474. return;
  191475. }
  191476. else if (png_ptr->mode & PNG_HAVE_PLTE)
  191477. /* Should be an error, but we can cope with it */
  191478. png_warning(png_ptr, "Out of place gAMA chunk");
  191479. if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_gAMA)
  191480. #if defined(PNG_READ_sRGB_SUPPORTED)
  191481. && !(info_ptr->valid & PNG_INFO_sRGB)
  191482. #endif
  191483. )
  191484. {
  191485. png_warning(png_ptr, "Duplicate gAMA chunk");
  191486. png_crc_finish(png_ptr, length);
  191487. return;
  191488. }
  191489. if (length != 4)
  191490. {
  191491. png_warning(png_ptr, "Incorrect gAMA chunk length");
  191492. png_crc_finish(png_ptr, length);
  191493. return;
  191494. }
  191495. png_crc_read(png_ptr, buf, 4);
  191496. if (png_crc_finish(png_ptr, 0))
  191497. return;
  191498. igamma = (png_fixed_point)png_get_uint_32(buf);
  191499. /* check for zero gamma */
  191500. if (igamma == 0)
  191501. {
  191502. png_warning(png_ptr,
  191503. "Ignoring gAMA chunk with gamma=0");
  191504. return;
  191505. }
  191506. #if defined(PNG_READ_sRGB_SUPPORTED)
  191507. if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_sRGB))
  191508. if (PNG_OUT_OF_RANGE(igamma, 45500L, 500))
  191509. {
  191510. png_warning(png_ptr,
  191511. "Ignoring incorrect gAMA value when sRGB is also present");
  191512. #ifndef PNG_NO_CONSOLE_IO
  191513. fprintf(stderr, "gamma = (%d/100000)\n", (int)igamma);
  191514. #endif
  191515. return;
  191516. }
  191517. #endif /* PNG_READ_sRGB_SUPPORTED */
  191518. #ifdef PNG_FLOATING_POINT_SUPPORTED
  191519. file_gamma = (float)igamma / (float)100000.0;
  191520. # ifdef PNG_READ_GAMMA_SUPPORTED
  191521. png_ptr->gamma = file_gamma;
  191522. # endif
  191523. png_set_gAMA(png_ptr, info_ptr, file_gamma);
  191524. #endif
  191525. #ifdef PNG_FIXED_POINT_SUPPORTED
  191526. png_set_gAMA_fixed(png_ptr, info_ptr, igamma);
  191527. #endif
  191528. }
  191529. #endif
  191530. #if defined(PNG_READ_sBIT_SUPPORTED)
  191531. void /* PRIVATE */
  191532. png_handle_sBIT(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  191533. {
  191534. png_size_t truelen;
  191535. png_byte buf[4];
  191536. png_debug(1, "in png_handle_sBIT\n");
  191537. buf[0] = buf[1] = buf[2] = buf[3] = 0;
  191538. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  191539. png_error(png_ptr, "Missing IHDR before sBIT");
  191540. else if (png_ptr->mode & PNG_HAVE_IDAT)
  191541. {
  191542. png_warning(png_ptr, "Invalid sBIT after IDAT");
  191543. png_crc_finish(png_ptr, length);
  191544. return;
  191545. }
  191546. else if (png_ptr->mode & PNG_HAVE_PLTE)
  191547. {
  191548. /* Should be an error, but we can cope with it */
  191549. png_warning(png_ptr, "Out of place sBIT chunk");
  191550. }
  191551. if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_sBIT))
  191552. {
  191553. png_warning(png_ptr, "Duplicate sBIT chunk");
  191554. png_crc_finish(png_ptr, length);
  191555. return;
  191556. }
  191557. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  191558. truelen = 3;
  191559. else
  191560. truelen = (png_size_t)png_ptr->channels;
  191561. if (length != truelen || length > 4)
  191562. {
  191563. png_warning(png_ptr, "Incorrect sBIT chunk length");
  191564. png_crc_finish(png_ptr, length);
  191565. return;
  191566. }
  191567. png_crc_read(png_ptr, buf, truelen);
  191568. if (png_crc_finish(png_ptr, 0))
  191569. return;
  191570. if (png_ptr->color_type & PNG_COLOR_MASK_COLOR)
  191571. {
  191572. png_ptr->sig_bit.red = buf[0];
  191573. png_ptr->sig_bit.green = buf[1];
  191574. png_ptr->sig_bit.blue = buf[2];
  191575. png_ptr->sig_bit.alpha = buf[3];
  191576. }
  191577. else
  191578. {
  191579. png_ptr->sig_bit.gray = buf[0];
  191580. png_ptr->sig_bit.red = buf[0];
  191581. png_ptr->sig_bit.green = buf[0];
  191582. png_ptr->sig_bit.blue = buf[0];
  191583. png_ptr->sig_bit.alpha = buf[1];
  191584. }
  191585. png_set_sBIT(png_ptr, info_ptr, &(png_ptr->sig_bit));
  191586. }
  191587. #endif
  191588. #if defined(PNG_READ_cHRM_SUPPORTED)
  191589. void /* PRIVATE */
  191590. png_handle_cHRM(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  191591. {
  191592. png_byte buf[4];
  191593. #ifdef PNG_FLOATING_POINT_SUPPORTED
  191594. float white_x, white_y, red_x, red_y, green_x, green_y, blue_x, blue_y;
  191595. #endif
  191596. png_fixed_point int_x_white, int_y_white, int_x_red, int_y_red, int_x_green,
  191597. int_y_green, int_x_blue, int_y_blue;
  191598. png_uint_32 uint_x, uint_y;
  191599. png_debug(1, "in png_handle_cHRM\n");
  191600. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  191601. png_error(png_ptr, "Missing IHDR before cHRM");
  191602. else if (png_ptr->mode & PNG_HAVE_IDAT)
  191603. {
  191604. png_warning(png_ptr, "Invalid cHRM after IDAT");
  191605. png_crc_finish(png_ptr, length);
  191606. return;
  191607. }
  191608. else if (png_ptr->mode & PNG_HAVE_PLTE)
  191609. /* Should be an error, but we can cope with it */
  191610. png_warning(png_ptr, "Missing PLTE before cHRM");
  191611. if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_cHRM)
  191612. #if defined(PNG_READ_sRGB_SUPPORTED)
  191613. && !(info_ptr->valid & PNG_INFO_sRGB)
  191614. #endif
  191615. )
  191616. {
  191617. png_warning(png_ptr, "Duplicate cHRM chunk");
  191618. png_crc_finish(png_ptr, length);
  191619. return;
  191620. }
  191621. if (length != 32)
  191622. {
  191623. png_warning(png_ptr, "Incorrect cHRM chunk length");
  191624. png_crc_finish(png_ptr, length);
  191625. return;
  191626. }
  191627. png_crc_read(png_ptr, buf, 4);
  191628. uint_x = png_get_uint_32(buf);
  191629. png_crc_read(png_ptr, buf, 4);
  191630. uint_y = png_get_uint_32(buf);
  191631. if (uint_x > 80000L || uint_y > 80000L ||
  191632. uint_x + uint_y > 100000L)
  191633. {
  191634. png_warning(png_ptr, "Invalid cHRM white point");
  191635. png_crc_finish(png_ptr, 24);
  191636. return;
  191637. }
  191638. int_x_white = (png_fixed_point)uint_x;
  191639. int_y_white = (png_fixed_point)uint_y;
  191640. png_crc_read(png_ptr, buf, 4);
  191641. uint_x = png_get_uint_32(buf);
  191642. png_crc_read(png_ptr, buf, 4);
  191643. uint_y = png_get_uint_32(buf);
  191644. if (uint_x + uint_y > 100000L)
  191645. {
  191646. png_warning(png_ptr, "Invalid cHRM red point");
  191647. png_crc_finish(png_ptr, 16);
  191648. return;
  191649. }
  191650. int_x_red = (png_fixed_point)uint_x;
  191651. int_y_red = (png_fixed_point)uint_y;
  191652. png_crc_read(png_ptr, buf, 4);
  191653. uint_x = png_get_uint_32(buf);
  191654. png_crc_read(png_ptr, buf, 4);
  191655. uint_y = png_get_uint_32(buf);
  191656. if (uint_x + uint_y > 100000L)
  191657. {
  191658. png_warning(png_ptr, "Invalid cHRM green point");
  191659. png_crc_finish(png_ptr, 8);
  191660. return;
  191661. }
  191662. int_x_green = (png_fixed_point)uint_x;
  191663. int_y_green = (png_fixed_point)uint_y;
  191664. png_crc_read(png_ptr, buf, 4);
  191665. uint_x = png_get_uint_32(buf);
  191666. png_crc_read(png_ptr, buf, 4);
  191667. uint_y = png_get_uint_32(buf);
  191668. if (uint_x + uint_y > 100000L)
  191669. {
  191670. png_warning(png_ptr, "Invalid cHRM blue point");
  191671. png_crc_finish(png_ptr, 0);
  191672. return;
  191673. }
  191674. int_x_blue = (png_fixed_point)uint_x;
  191675. int_y_blue = (png_fixed_point)uint_y;
  191676. #ifdef PNG_FLOATING_POINT_SUPPORTED
  191677. white_x = (float)int_x_white / (float)100000.0;
  191678. white_y = (float)int_y_white / (float)100000.0;
  191679. red_x = (float)int_x_red / (float)100000.0;
  191680. red_y = (float)int_y_red / (float)100000.0;
  191681. green_x = (float)int_x_green / (float)100000.0;
  191682. green_y = (float)int_y_green / (float)100000.0;
  191683. blue_x = (float)int_x_blue / (float)100000.0;
  191684. blue_y = (float)int_y_blue / (float)100000.0;
  191685. #endif
  191686. #if defined(PNG_READ_sRGB_SUPPORTED)
  191687. if ((info_ptr != NULL) && (info_ptr->valid & PNG_INFO_sRGB))
  191688. {
  191689. if (PNG_OUT_OF_RANGE(int_x_white, 31270, 1000) ||
  191690. PNG_OUT_OF_RANGE(int_y_white, 32900, 1000) ||
  191691. PNG_OUT_OF_RANGE(int_x_red, 64000L, 1000) ||
  191692. PNG_OUT_OF_RANGE(int_y_red, 33000, 1000) ||
  191693. PNG_OUT_OF_RANGE(int_x_green, 30000, 1000) ||
  191694. PNG_OUT_OF_RANGE(int_y_green, 60000L, 1000) ||
  191695. PNG_OUT_OF_RANGE(int_x_blue, 15000, 1000) ||
  191696. PNG_OUT_OF_RANGE(int_y_blue, 6000, 1000))
  191697. {
  191698. png_warning(png_ptr,
  191699. "Ignoring incorrect cHRM value when sRGB is also present");
  191700. #ifndef PNG_NO_CONSOLE_IO
  191701. #ifdef PNG_FLOATING_POINT_SUPPORTED
  191702. fprintf(stderr,"wx=%f, wy=%f, rx=%f, ry=%f\n",
  191703. white_x, white_y, red_x, red_y);
  191704. fprintf(stderr,"gx=%f, gy=%f, bx=%f, by=%f\n",
  191705. green_x, green_y, blue_x, blue_y);
  191706. #else
  191707. fprintf(stderr,"wx=%ld, wy=%ld, rx=%ld, ry=%ld\n",
  191708. int_x_white, int_y_white, int_x_red, int_y_red);
  191709. fprintf(stderr,"gx=%ld, gy=%ld, bx=%ld, by=%ld\n",
  191710. int_x_green, int_y_green, int_x_blue, int_y_blue);
  191711. #endif
  191712. #endif /* PNG_NO_CONSOLE_IO */
  191713. }
  191714. png_crc_finish(png_ptr, 0);
  191715. return;
  191716. }
  191717. #endif /* PNG_READ_sRGB_SUPPORTED */
  191718. #ifdef PNG_FLOATING_POINT_SUPPORTED
  191719. png_set_cHRM(png_ptr, info_ptr,
  191720. white_x, white_y, red_x, red_y, green_x, green_y, blue_x, blue_y);
  191721. #endif
  191722. #ifdef PNG_FIXED_POINT_SUPPORTED
  191723. png_set_cHRM_fixed(png_ptr, info_ptr,
  191724. int_x_white, int_y_white, int_x_red, int_y_red, int_x_green,
  191725. int_y_green, int_x_blue, int_y_blue);
  191726. #endif
  191727. if (png_crc_finish(png_ptr, 0))
  191728. return;
  191729. }
  191730. #endif
  191731. #if defined(PNG_READ_sRGB_SUPPORTED)
  191732. void /* PRIVATE */
  191733. png_handle_sRGB(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  191734. {
  191735. int intent;
  191736. png_byte buf[1];
  191737. png_debug(1, "in png_handle_sRGB\n");
  191738. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  191739. png_error(png_ptr, "Missing IHDR before sRGB");
  191740. else if (png_ptr->mode & PNG_HAVE_IDAT)
  191741. {
  191742. png_warning(png_ptr, "Invalid sRGB after IDAT");
  191743. png_crc_finish(png_ptr, length);
  191744. return;
  191745. }
  191746. else if (png_ptr->mode & PNG_HAVE_PLTE)
  191747. /* Should be an error, but we can cope with it */
  191748. png_warning(png_ptr, "Out of place sRGB chunk");
  191749. if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_sRGB))
  191750. {
  191751. png_warning(png_ptr, "Duplicate sRGB chunk");
  191752. png_crc_finish(png_ptr, length);
  191753. return;
  191754. }
  191755. if (length != 1)
  191756. {
  191757. png_warning(png_ptr, "Incorrect sRGB chunk length");
  191758. png_crc_finish(png_ptr, length);
  191759. return;
  191760. }
  191761. png_crc_read(png_ptr, buf, 1);
  191762. if (png_crc_finish(png_ptr, 0))
  191763. return;
  191764. intent = buf[0];
  191765. /* check for bad intent */
  191766. if (intent >= PNG_sRGB_INTENT_LAST)
  191767. {
  191768. png_warning(png_ptr, "Unknown sRGB intent");
  191769. return;
  191770. }
  191771. #if defined(PNG_READ_gAMA_SUPPORTED) && defined(PNG_READ_GAMMA_SUPPORTED)
  191772. if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_gAMA))
  191773. {
  191774. png_fixed_point igamma;
  191775. #ifdef PNG_FIXED_POINT_SUPPORTED
  191776. igamma=info_ptr->int_gamma;
  191777. #else
  191778. # ifdef PNG_FLOATING_POINT_SUPPORTED
  191779. igamma=(png_fixed_point)(info_ptr->gamma * 100000.);
  191780. # endif
  191781. #endif
  191782. if (PNG_OUT_OF_RANGE(igamma, 45500L, 500))
  191783. {
  191784. png_warning(png_ptr,
  191785. "Ignoring incorrect gAMA value when sRGB is also present");
  191786. #ifndef PNG_NO_CONSOLE_IO
  191787. # ifdef PNG_FIXED_POINT_SUPPORTED
  191788. fprintf(stderr,"incorrect gamma=(%d/100000)\n",(int)png_ptr->int_gamma);
  191789. # else
  191790. # ifdef PNG_FLOATING_POINT_SUPPORTED
  191791. fprintf(stderr,"incorrect gamma=%f\n",png_ptr->gamma);
  191792. # endif
  191793. # endif
  191794. #endif
  191795. }
  191796. }
  191797. #endif /* PNG_READ_gAMA_SUPPORTED */
  191798. #ifdef PNG_READ_cHRM_SUPPORTED
  191799. #ifdef PNG_FIXED_POINT_SUPPORTED
  191800. if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_cHRM))
  191801. if (PNG_OUT_OF_RANGE(info_ptr->int_x_white, 31270, 1000) ||
  191802. PNG_OUT_OF_RANGE(info_ptr->int_y_white, 32900, 1000) ||
  191803. PNG_OUT_OF_RANGE(info_ptr->int_x_red, 64000L, 1000) ||
  191804. PNG_OUT_OF_RANGE(info_ptr->int_y_red, 33000, 1000) ||
  191805. PNG_OUT_OF_RANGE(info_ptr->int_x_green, 30000, 1000) ||
  191806. PNG_OUT_OF_RANGE(info_ptr->int_y_green, 60000L, 1000) ||
  191807. PNG_OUT_OF_RANGE(info_ptr->int_x_blue, 15000, 1000) ||
  191808. PNG_OUT_OF_RANGE(info_ptr->int_y_blue, 6000, 1000))
  191809. {
  191810. png_warning(png_ptr,
  191811. "Ignoring incorrect cHRM value when sRGB is also present");
  191812. }
  191813. #endif /* PNG_FIXED_POINT_SUPPORTED */
  191814. #endif /* PNG_READ_cHRM_SUPPORTED */
  191815. png_set_sRGB_gAMA_and_cHRM(png_ptr, info_ptr, intent);
  191816. }
  191817. #endif /* PNG_READ_sRGB_SUPPORTED */
  191818. #if defined(PNG_READ_iCCP_SUPPORTED)
  191819. void /* PRIVATE */
  191820. png_handle_iCCP(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  191821. /* Note: this does not properly handle chunks that are > 64K under DOS */
  191822. {
  191823. png_charp chunkdata;
  191824. png_byte compression_type;
  191825. png_bytep pC;
  191826. png_charp profile;
  191827. png_uint_32 skip = 0;
  191828. png_uint_32 profile_size, profile_length;
  191829. png_size_t slength, prefix_length, data_length;
  191830. png_debug(1, "in png_handle_iCCP\n");
  191831. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  191832. png_error(png_ptr, "Missing IHDR before iCCP");
  191833. else if (png_ptr->mode & PNG_HAVE_IDAT)
  191834. {
  191835. png_warning(png_ptr, "Invalid iCCP after IDAT");
  191836. png_crc_finish(png_ptr, length);
  191837. return;
  191838. }
  191839. else if (png_ptr->mode & PNG_HAVE_PLTE)
  191840. /* Should be an error, but we can cope with it */
  191841. png_warning(png_ptr, "Out of place iCCP chunk");
  191842. if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_iCCP))
  191843. {
  191844. png_warning(png_ptr, "Duplicate iCCP chunk");
  191845. png_crc_finish(png_ptr, length);
  191846. return;
  191847. }
  191848. #ifdef PNG_MAX_MALLOC_64K
  191849. if (length > (png_uint_32)65535L)
  191850. {
  191851. png_warning(png_ptr, "iCCP chunk too large to fit in memory");
  191852. skip = length - (png_uint_32)65535L;
  191853. length = (png_uint_32)65535L;
  191854. }
  191855. #endif
  191856. chunkdata = (png_charp)png_malloc(png_ptr, length + 1);
  191857. slength = (png_size_t)length;
  191858. png_crc_read(png_ptr, (png_bytep)chunkdata, slength);
  191859. if (png_crc_finish(png_ptr, skip))
  191860. {
  191861. png_free(png_ptr, chunkdata);
  191862. return;
  191863. }
  191864. chunkdata[slength] = 0x00;
  191865. for (profile = chunkdata; *profile; profile++)
  191866. /* empty loop to find end of name */ ;
  191867. ++profile;
  191868. /* there should be at least one zero (the compression type byte)
  191869. following the separator, and we should be on it */
  191870. if ( profile >= chunkdata + slength - 1)
  191871. {
  191872. png_free(png_ptr, chunkdata);
  191873. png_warning(png_ptr, "Malformed iCCP chunk");
  191874. return;
  191875. }
  191876. /* compression_type should always be zero */
  191877. compression_type = *profile++;
  191878. if (compression_type)
  191879. {
  191880. png_warning(png_ptr, "Ignoring nonzero compression type in iCCP chunk");
  191881. compression_type=0x00; /* Reset it to zero (libpng-1.0.6 through 1.0.8
  191882. wrote nonzero) */
  191883. }
  191884. prefix_length = profile - chunkdata;
  191885. chunkdata = png_decompress_chunk(png_ptr, compression_type, chunkdata,
  191886. slength, prefix_length, &data_length);
  191887. profile_length = data_length - prefix_length;
  191888. if ( prefix_length > data_length || profile_length < 4)
  191889. {
  191890. png_free(png_ptr, chunkdata);
  191891. png_warning(png_ptr, "Profile size field missing from iCCP chunk");
  191892. return;
  191893. }
  191894. /* Check the profile_size recorded in the first 32 bits of the ICC profile */
  191895. pC = (png_bytep)(chunkdata+prefix_length);
  191896. profile_size = ((*(pC ))<<24) |
  191897. ((*(pC+1))<<16) |
  191898. ((*(pC+2))<< 8) |
  191899. ((*(pC+3)) );
  191900. if(profile_size < profile_length)
  191901. profile_length = profile_size;
  191902. if(profile_size > profile_length)
  191903. {
  191904. png_free(png_ptr, chunkdata);
  191905. png_warning(png_ptr, "Ignoring truncated iCCP profile.");
  191906. return;
  191907. }
  191908. png_set_iCCP(png_ptr, info_ptr, chunkdata, compression_type,
  191909. chunkdata + prefix_length, profile_length);
  191910. png_free(png_ptr, chunkdata);
  191911. }
  191912. #endif /* PNG_READ_iCCP_SUPPORTED */
  191913. #if defined(PNG_READ_sPLT_SUPPORTED)
  191914. void /* PRIVATE */
  191915. png_handle_sPLT(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  191916. /* Note: this does not properly handle chunks that are > 64K under DOS */
  191917. {
  191918. png_bytep chunkdata;
  191919. png_bytep entry_start;
  191920. png_sPLT_t new_palette;
  191921. #ifdef PNG_NO_POINTER_INDEXING
  191922. png_sPLT_entryp pp;
  191923. #endif
  191924. int data_length, entry_size, i;
  191925. png_uint_32 skip = 0;
  191926. png_size_t slength;
  191927. png_debug(1, "in png_handle_sPLT\n");
  191928. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  191929. png_error(png_ptr, "Missing IHDR before sPLT");
  191930. else if (png_ptr->mode & PNG_HAVE_IDAT)
  191931. {
  191932. png_warning(png_ptr, "Invalid sPLT after IDAT");
  191933. png_crc_finish(png_ptr, length);
  191934. return;
  191935. }
  191936. #ifdef PNG_MAX_MALLOC_64K
  191937. if (length > (png_uint_32)65535L)
  191938. {
  191939. png_warning(png_ptr, "sPLT chunk too large to fit in memory");
  191940. skip = length - (png_uint_32)65535L;
  191941. length = (png_uint_32)65535L;
  191942. }
  191943. #endif
  191944. chunkdata = (png_bytep)png_malloc(png_ptr, length + 1);
  191945. slength = (png_size_t)length;
  191946. png_crc_read(png_ptr, (png_bytep)chunkdata, slength);
  191947. if (png_crc_finish(png_ptr, skip))
  191948. {
  191949. png_free(png_ptr, chunkdata);
  191950. return;
  191951. }
  191952. chunkdata[slength] = 0x00;
  191953. for (entry_start = chunkdata; *entry_start; entry_start++)
  191954. /* empty loop to find end of name */ ;
  191955. ++entry_start;
  191956. /* a sample depth should follow the separator, and we should be on it */
  191957. if (entry_start > chunkdata + slength - 2)
  191958. {
  191959. png_free(png_ptr, chunkdata);
  191960. png_warning(png_ptr, "malformed sPLT chunk");
  191961. return;
  191962. }
  191963. new_palette.depth = *entry_start++;
  191964. entry_size = (new_palette.depth == 8 ? 6 : 10);
  191965. data_length = (slength - (entry_start - chunkdata));
  191966. /* integrity-check the data length */
  191967. if (data_length % entry_size)
  191968. {
  191969. png_free(png_ptr, chunkdata);
  191970. png_warning(png_ptr, "sPLT chunk has bad length");
  191971. return;
  191972. }
  191973. new_palette.nentries = (png_int_32) ( data_length / entry_size);
  191974. if ((png_uint_32) new_palette.nentries > (png_uint_32) (PNG_SIZE_MAX /
  191975. png_sizeof(png_sPLT_entry)))
  191976. {
  191977. png_warning(png_ptr, "sPLT chunk too long");
  191978. return;
  191979. }
  191980. new_palette.entries = (png_sPLT_entryp)png_malloc_warn(
  191981. png_ptr, new_palette.nentries * png_sizeof(png_sPLT_entry));
  191982. if (new_palette.entries == NULL)
  191983. {
  191984. png_warning(png_ptr, "sPLT chunk requires too much memory");
  191985. return;
  191986. }
  191987. #ifndef PNG_NO_POINTER_INDEXING
  191988. for (i = 0; i < new_palette.nentries; i++)
  191989. {
  191990. png_sPLT_entryp pp = new_palette.entries + i;
  191991. if (new_palette.depth == 8)
  191992. {
  191993. pp->red = *entry_start++;
  191994. pp->green = *entry_start++;
  191995. pp->blue = *entry_start++;
  191996. pp->alpha = *entry_start++;
  191997. }
  191998. else
  191999. {
  192000. pp->red = png_get_uint_16(entry_start); entry_start += 2;
  192001. pp->green = png_get_uint_16(entry_start); entry_start += 2;
  192002. pp->blue = png_get_uint_16(entry_start); entry_start += 2;
  192003. pp->alpha = png_get_uint_16(entry_start); entry_start += 2;
  192004. }
  192005. pp->frequency = png_get_uint_16(entry_start); entry_start += 2;
  192006. }
  192007. #else
  192008. pp = new_palette.entries;
  192009. for (i = 0; i < new_palette.nentries; i++)
  192010. {
  192011. if (new_palette.depth == 8)
  192012. {
  192013. pp[i].red = *entry_start++;
  192014. pp[i].green = *entry_start++;
  192015. pp[i].blue = *entry_start++;
  192016. pp[i].alpha = *entry_start++;
  192017. }
  192018. else
  192019. {
  192020. pp[i].red = png_get_uint_16(entry_start); entry_start += 2;
  192021. pp[i].green = png_get_uint_16(entry_start); entry_start += 2;
  192022. pp[i].blue = png_get_uint_16(entry_start); entry_start += 2;
  192023. pp[i].alpha = png_get_uint_16(entry_start); entry_start += 2;
  192024. }
  192025. pp->frequency = png_get_uint_16(entry_start); entry_start += 2;
  192026. }
  192027. #endif
  192028. /* discard all chunk data except the name and stash that */
  192029. new_palette.name = (png_charp)chunkdata;
  192030. png_set_sPLT(png_ptr, info_ptr, &new_palette, 1);
  192031. png_free(png_ptr, chunkdata);
  192032. png_free(png_ptr, new_palette.entries);
  192033. }
  192034. #endif /* PNG_READ_sPLT_SUPPORTED */
  192035. #if defined(PNG_READ_tRNS_SUPPORTED)
  192036. void /* PRIVATE */
  192037. png_handle_tRNS(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  192038. {
  192039. png_byte readbuf[PNG_MAX_PALETTE_LENGTH];
  192040. int bit_mask;
  192041. png_debug(1, "in png_handle_tRNS\n");
  192042. /* For non-indexed color, mask off any bits in the tRNS value that
  192043. * exceed the bit depth. Some creators were writing extra bits there.
  192044. * This is not needed for indexed color. */
  192045. bit_mask = (1 << png_ptr->bit_depth) - 1;
  192046. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  192047. png_error(png_ptr, "Missing IHDR before tRNS");
  192048. else if (png_ptr->mode & PNG_HAVE_IDAT)
  192049. {
  192050. png_warning(png_ptr, "Invalid tRNS after IDAT");
  192051. png_crc_finish(png_ptr, length);
  192052. return;
  192053. }
  192054. else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_tRNS))
  192055. {
  192056. png_warning(png_ptr, "Duplicate tRNS chunk");
  192057. png_crc_finish(png_ptr, length);
  192058. return;
  192059. }
  192060. if (png_ptr->color_type == PNG_COLOR_TYPE_GRAY)
  192061. {
  192062. png_byte buf[2];
  192063. if (length != 2)
  192064. {
  192065. png_warning(png_ptr, "Incorrect tRNS chunk length");
  192066. png_crc_finish(png_ptr, length);
  192067. return;
  192068. }
  192069. png_crc_read(png_ptr, buf, 2);
  192070. png_ptr->num_trans = 1;
  192071. png_ptr->trans_values.gray = png_get_uint_16(buf) & bit_mask;
  192072. }
  192073. else if (png_ptr->color_type == PNG_COLOR_TYPE_RGB)
  192074. {
  192075. png_byte buf[6];
  192076. if (length != 6)
  192077. {
  192078. png_warning(png_ptr, "Incorrect tRNS chunk length");
  192079. png_crc_finish(png_ptr, length);
  192080. return;
  192081. }
  192082. png_crc_read(png_ptr, buf, (png_size_t)length);
  192083. png_ptr->num_trans = 1;
  192084. png_ptr->trans_values.red = png_get_uint_16(buf) & bit_mask;
  192085. png_ptr->trans_values.green = png_get_uint_16(buf + 2) & bit_mask;
  192086. png_ptr->trans_values.blue = png_get_uint_16(buf + 4) & bit_mask;
  192087. }
  192088. else if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  192089. {
  192090. if (!(png_ptr->mode & PNG_HAVE_PLTE))
  192091. {
  192092. /* Should be an error, but we can cope with it. */
  192093. png_warning(png_ptr, "Missing PLTE before tRNS");
  192094. }
  192095. if (length > (png_uint_32)png_ptr->num_palette ||
  192096. length > PNG_MAX_PALETTE_LENGTH)
  192097. {
  192098. png_warning(png_ptr, "Incorrect tRNS chunk length");
  192099. png_crc_finish(png_ptr, length);
  192100. return;
  192101. }
  192102. if (length == 0)
  192103. {
  192104. png_warning(png_ptr, "Zero length tRNS chunk");
  192105. png_crc_finish(png_ptr, length);
  192106. return;
  192107. }
  192108. png_crc_read(png_ptr, readbuf, (png_size_t)length);
  192109. png_ptr->num_trans = (png_uint_16)length;
  192110. }
  192111. else
  192112. {
  192113. png_warning(png_ptr, "tRNS chunk not allowed with alpha channel");
  192114. png_crc_finish(png_ptr, length);
  192115. return;
  192116. }
  192117. if (png_crc_finish(png_ptr, 0))
  192118. {
  192119. png_ptr->num_trans = 0;
  192120. return;
  192121. }
  192122. png_set_tRNS(png_ptr, info_ptr, readbuf, png_ptr->num_trans,
  192123. &(png_ptr->trans_values));
  192124. }
  192125. #endif
  192126. #if defined(PNG_READ_bKGD_SUPPORTED)
  192127. void /* PRIVATE */
  192128. png_handle_bKGD(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  192129. {
  192130. png_size_t truelen;
  192131. png_byte buf[6];
  192132. png_debug(1, "in png_handle_bKGD\n");
  192133. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  192134. png_error(png_ptr, "Missing IHDR before bKGD");
  192135. else if (png_ptr->mode & PNG_HAVE_IDAT)
  192136. {
  192137. png_warning(png_ptr, "Invalid bKGD after IDAT");
  192138. png_crc_finish(png_ptr, length);
  192139. return;
  192140. }
  192141. else if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE &&
  192142. !(png_ptr->mode & PNG_HAVE_PLTE))
  192143. {
  192144. png_warning(png_ptr, "Missing PLTE before bKGD");
  192145. png_crc_finish(png_ptr, length);
  192146. return;
  192147. }
  192148. else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_bKGD))
  192149. {
  192150. png_warning(png_ptr, "Duplicate bKGD chunk");
  192151. png_crc_finish(png_ptr, length);
  192152. return;
  192153. }
  192154. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  192155. truelen = 1;
  192156. else if (png_ptr->color_type & PNG_COLOR_MASK_COLOR)
  192157. truelen = 6;
  192158. else
  192159. truelen = 2;
  192160. if (length != truelen)
  192161. {
  192162. png_warning(png_ptr, "Incorrect bKGD chunk length");
  192163. png_crc_finish(png_ptr, length);
  192164. return;
  192165. }
  192166. png_crc_read(png_ptr, buf, truelen);
  192167. if (png_crc_finish(png_ptr, 0))
  192168. return;
  192169. /* We convert the index value into RGB components so that we can allow
  192170. * arbitrary RGB values for background when we have transparency, and
  192171. * so it is easy to determine the RGB values of the background color
  192172. * from the info_ptr struct. */
  192173. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  192174. {
  192175. png_ptr->background.index = buf[0];
  192176. if(info_ptr->num_palette)
  192177. {
  192178. if(buf[0] > info_ptr->num_palette)
  192179. {
  192180. png_warning(png_ptr, "Incorrect bKGD chunk index value");
  192181. return;
  192182. }
  192183. png_ptr->background.red =
  192184. (png_uint_16)png_ptr->palette[buf[0]].red;
  192185. png_ptr->background.green =
  192186. (png_uint_16)png_ptr->palette[buf[0]].green;
  192187. png_ptr->background.blue =
  192188. (png_uint_16)png_ptr->palette[buf[0]].blue;
  192189. }
  192190. }
  192191. else if (!(png_ptr->color_type & PNG_COLOR_MASK_COLOR)) /* GRAY */
  192192. {
  192193. png_ptr->background.red =
  192194. png_ptr->background.green =
  192195. png_ptr->background.blue =
  192196. png_ptr->background.gray = png_get_uint_16(buf);
  192197. }
  192198. else
  192199. {
  192200. png_ptr->background.red = png_get_uint_16(buf);
  192201. png_ptr->background.green = png_get_uint_16(buf + 2);
  192202. png_ptr->background.blue = png_get_uint_16(buf + 4);
  192203. }
  192204. png_set_bKGD(png_ptr, info_ptr, &(png_ptr->background));
  192205. }
  192206. #endif
  192207. #if defined(PNG_READ_hIST_SUPPORTED)
  192208. void /* PRIVATE */
  192209. png_handle_hIST(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  192210. {
  192211. unsigned int num, i;
  192212. png_uint_16 readbuf[PNG_MAX_PALETTE_LENGTH];
  192213. png_debug(1, "in png_handle_hIST\n");
  192214. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  192215. png_error(png_ptr, "Missing IHDR before hIST");
  192216. else if (png_ptr->mode & PNG_HAVE_IDAT)
  192217. {
  192218. png_warning(png_ptr, "Invalid hIST after IDAT");
  192219. png_crc_finish(png_ptr, length);
  192220. return;
  192221. }
  192222. else if (!(png_ptr->mode & PNG_HAVE_PLTE))
  192223. {
  192224. png_warning(png_ptr, "Missing PLTE before hIST");
  192225. png_crc_finish(png_ptr, length);
  192226. return;
  192227. }
  192228. else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_hIST))
  192229. {
  192230. png_warning(png_ptr, "Duplicate hIST chunk");
  192231. png_crc_finish(png_ptr, length);
  192232. return;
  192233. }
  192234. num = length / 2 ;
  192235. if (num != (unsigned int) png_ptr->num_palette || num >
  192236. (unsigned int) PNG_MAX_PALETTE_LENGTH)
  192237. {
  192238. png_warning(png_ptr, "Incorrect hIST chunk length");
  192239. png_crc_finish(png_ptr, length);
  192240. return;
  192241. }
  192242. for (i = 0; i < num; i++)
  192243. {
  192244. png_byte buf[2];
  192245. png_crc_read(png_ptr, buf, 2);
  192246. readbuf[i] = png_get_uint_16(buf);
  192247. }
  192248. if (png_crc_finish(png_ptr, 0))
  192249. return;
  192250. png_set_hIST(png_ptr, info_ptr, readbuf);
  192251. }
  192252. #endif
  192253. #if defined(PNG_READ_pHYs_SUPPORTED)
  192254. void /* PRIVATE */
  192255. png_handle_pHYs(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  192256. {
  192257. png_byte buf[9];
  192258. png_uint_32 res_x, res_y;
  192259. int unit_type;
  192260. png_debug(1, "in png_handle_pHYs\n");
  192261. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  192262. png_error(png_ptr, "Missing IHDR before pHYs");
  192263. else if (png_ptr->mode & PNG_HAVE_IDAT)
  192264. {
  192265. png_warning(png_ptr, "Invalid pHYs after IDAT");
  192266. png_crc_finish(png_ptr, length);
  192267. return;
  192268. }
  192269. else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_pHYs))
  192270. {
  192271. png_warning(png_ptr, "Duplicate pHYs chunk");
  192272. png_crc_finish(png_ptr, length);
  192273. return;
  192274. }
  192275. if (length != 9)
  192276. {
  192277. png_warning(png_ptr, "Incorrect pHYs chunk length");
  192278. png_crc_finish(png_ptr, length);
  192279. return;
  192280. }
  192281. png_crc_read(png_ptr, buf, 9);
  192282. if (png_crc_finish(png_ptr, 0))
  192283. return;
  192284. res_x = png_get_uint_32(buf);
  192285. res_y = png_get_uint_32(buf + 4);
  192286. unit_type = buf[8];
  192287. png_set_pHYs(png_ptr, info_ptr, res_x, res_y, unit_type);
  192288. }
  192289. #endif
  192290. #if defined(PNG_READ_oFFs_SUPPORTED)
  192291. void /* PRIVATE */
  192292. png_handle_oFFs(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  192293. {
  192294. png_byte buf[9];
  192295. png_int_32 offset_x, offset_y;
  192296. int unit_type;
  192297. png_debug(1, "in png_handle_oFFs\n");
  192298. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  192299. png_error(png_ptr, "Missing IHDR before oFFs");
  192300. else if (png_ptr->mode & PNG_HAVE_IDAT)
  192301. {
  192302. png_warning(png_ptr, "Invalid oFFs after IDAT");
  192303. png_crc_finish(png_ptr, length);
  192304. return;
  192305. }
  192306. else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_oFFs))
  192307. {
  192308. png_warning(png_ptr, "Duplicate oFFs chunk");
  192309. png_crc_finish(png_ptr, length);
  192310. return;
  192311. }
  192312. if (length != 9)
  192313. {
  192314. png_warning(png_ptr, "Incorrect oFFs chunk length");
  192315. png_crc_finish(png_ptr, length);
  192316. return;
  192317. }
  192318. png_crc_read(png_ptr, buf, 9);
  192319. if (png_crc_finish(png_ptr, 0))
  192320. return;
  192321. offset_x = png_get_int_32(buf);
  192322. offset_y = png_get_int_32(buf + 4);
  192323. unit_type = buf[8];
  192324. png_set_oFFs(png_ptr, info_ptr, offset_x, offset_y, unit_type);
  192325. }
  192326. #endif
  192327. #if defined(PNG_READ_pCAL_SUPPORTED)
  192328. /* read the pCAL chunk (described in the PNG Extensions document) */
  192329. void /* PRIVATE */
  192330. png_handle_pCAL(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  192331. {
  192332. png_charp purpose;
  192333. png_int_32 X0, X1;
  192334. png_byte type, nparams;
  192335. png_charp buf, units, endptr;
  192336. png_charpp params;
  192337. png_size_t slength;
  192338. int i;
  192339. png_debug(1, "in png_handle_pCAL\n");
  192340. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  192341. png_error(png_ptr, "Missing IHDR before pCAL");
  192342. else if (png_ptr->mode & PNG_HAVE_IDAT)
  192343. {
  192344. png_warning(png_ptr, "Invalid pCAL after IDAT");
  192345. png_crc_finish(png_ptr, length);
  192346. return;
  192347. }
  192348. else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_pCAL))
  192349. {
  192350. png_warning(png_ptr, "Duplicate pCAL chunk");
  192351. png_crc_finish(png_ptr, length);
  192352. return;
  192353. }
  192354. png_debug1(2, "Allocating and reading pCAL chunk data (%lu bytes)\n",
  192355. length + 1);
  192356. purpose = (png_charp)png_malloc_warn(png_ptr, length + 1);
  192357. if (purpose == NULL)
  192358. {
  192359. png_warning(png_ptr, "No memory for pCAL purpose.");
  192360. return;
  192361. }
  192362. slength = (png_size_t)length;
  192363. png_crc_read(png_ptr, (png_bytep)purpose, slength);
  192364. if (png_crc_finish(png_ptr, 0))
  192365. {
  192366. png_free(png_ptr, purpose);
  192367. return;
  192368. }
  192369. purpose[slength] = 0x00; /* null terminate the last string */
  192370. png_debug(3, "Finding end of pCAL purpose string\n");
  192371. for (buf = purpose; *buf; buf++)
  192372. /* empty loop */ ;
  192373. endptr = purpose + slength;
  192374. /* We need to have at least 12 bytes after the purpose string
  192375. in order to get the parameter information. */
  192376. if (endptr <= buf + 12)
  192377. {
  192378. png_warning(png_ptr, "Invalid pCAL data");
  192379. png_free(png_ptr, purpose);
  192380. return;
  192381. }
  192382. png_debug(3, "Reading pCAL X0, X1, type, nparams, and units\n");
  192383. X0 = png_get_int_32((png_bytep)buf+1);
  192384. X1 = png_get_int_32((png_bytep)buf+5);
  192385. type = buf[9];
  192386. nparams = buf[10];
  192387. units = buf + 11;
  192388. png_debug(3, "Checking pCAL equation type and number of parameters\n");
  192389. /* Check that we have the right number of parameters for known
  192390. equation types. */
  192391. if ((type == PNG_EQUATION_LINEAR && nparams != 2) ||
  192392. (type == PNG_EQUATION_BASE_E && nparams != 3) ||
  192393. (type == PNG_EQUATION_ARBITRARY && nparams != 3) ||
  192394. (type == PNG_EQUATION_HYPERBOLIC && nparams != 4))
  192395. {
  192396. png_warning(png_ptr, "Invalid pCAL parameters for equation type");
  192397. png_free(png_ptr, purpose);
  192398. return;
  192399. }
  192400. else if (type >= PNG_EQUATION_LAST)
  192401. {
  192402. png_warning(png_ptr, "Unrecognized equation type for pCAL chunk");
  192403. }
  192404. for (buf = units; *buf; buf++)
  192405. /* Empty loop to move past the units string. */ ;
  192406. png_debug(3, "Allocating pCAL parameters array\n");
  192407. params = (png_charpp)png_malloc_warn(png_ptr, (png_uint_32)(nparams
  192408. *png_sizeof(png_charp))) ;
  192409. if (params == NULL)
  192410. {
  192411. png_free(png_ptr, purpose);
  192412. png_warning(png_ptr, "No memory for pCAL params.");
  192413. return;
  192414. }
  192415. /* Get pointers to the start of each parameter string. */
  192416. for (i = 0; i < (int)nparams; i++)
  192417. {
  192418. buf++; /* Skip the null string terminator from previous parameter. */
  192419. png_debug1(3, "Reading pCAL parameter %d\n", i);
  192420. for (params[i] = buf; buf <= endptr && *buf != 0x00; buf++)
  192421. /* Empty loop to move past each parameter string */ ;
  192422. /* Make sure we haven't run out of data yet */
  192423. if (buf > endptr)
  192424. {
  192425. png_warning(png_ptr, "Invalid pCAL data");
  192426. png_free(png_ptr, purpose);
  192427. png_free(png_ptr, params);
  192428. return;
  192429. }
  192430. }
  192431. png_set_pCAL(png_ptr, info_ptr, purpose, X0, X1, type, nparams,
  192432. units, params);
  192433. png_free(png_ptr, purpose);
  192434. png_free(png_ptr, params);
  192435. }
  192436. #endif
  192437. #if defined(PNG_READ_sCAL_SUPPORTED)
  192438. /* read the sCAL chunk */
  192439. void /* PRIVATE */
  192440. png_handle_sCAL(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  192441. {
  192442. png_charp buffer, ep;
  192443. #ifdef PNG_FLOATING_POINT_SUPPORTED
  192444. double width, height;
  192445. png_charp vp;
  192446. #else
  192447. #ifdef PNG_FIXED_POINT_SUPPORTED
  192448. png_charp swidth, sheight;
  192449. #endif
  192450. #endif
  192451. png_size_t slength;
  192452. png_debug(1, "in png_handle_sCAL\n");
  192453. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  192454. png_error(png_ptr, "Missing IHDR before sCAL");
  192455. else if (png_ptr->mode & PNG_HAVE_IDAT)
  192456. {
  192457. png_warning(png_ptr, "Invalid sCAL after IDAT");
  192458. png_crc_finish(png_ptr, length);
  192459. return;
  192460. }
  192461. else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_sCAL))
  192462. {
  192463. png_warning(png_ptr, "Duplicate sCAL chunk");
  192464. png_crc_finish(png_ptr, length);
  192465. return;
  192466. }
  192467. png_debug1(2, "Allocating and reading sCAL chunk data (%lu bytes)\n",
  192468. length + 1);
  192469. buffer = (png_charp)png_malloc_warn(png_ptr, length + 1);
  192470. if (buffer == NULL)
  192471. {
  192472. png_warning(png_ptr, "Out of memory while processing sCAL chunk");
  192473. return;
  192474. }
  192475. slength = (png_size_t)length;
  192476. png_crc_read(png_ptr, (png_bytep)buffer, slength);
  192477. if (png_crc_finish(png_ptr, 0))
  192478. {
  192479. png_free(png_ptr, buffer);
  192480. return;
  192481. }
  192482. buffer[slength] = 0x00; /* null terminate the last string */
  192483. ep = buffer + 1; /* skip unit byte */
  192484. #ifdef PNG_FLOATING_POINT_SUPPORTED
  192485. width = png_strtod(png_ptr, ep, &vp);
  192486. if (*vp)
  192487. {
  192488. png_warning(png_ptr, "malformed width string in sCAL chunk");
  192489. return;
  192490. }
  192491. #else
  192492. #ifdef PNG_FIXED_POINT_SUPPORTED
  192493. swidth = (png_charp)png_malloc_warn(png_ptr, png_strlen(ep) + 1);
  192494. if (swidth == NULL)
  192495. {
  192496. png_warning(png_ptr, "Out of memory while processing sCAL chunk width");
  192497. return;
  192498. }
  192499. png_memcpy(swidth, ep, (png_size_t)png_strlen(ep));
  192500. #endif
  192501. #endif
  192502. for (ep = buffer; *ep; ep++)
  192503. /* empty loop */ ;
  192504. ep++;
  192505. if (buffer + slength < ep)
  192506. {
  192507. png_warning(png_ptr, "Truncated sCAL chunk");
  192508. #if defined(PNG_FIXED_POINT_SUPPORTED) && \
  192509. !defined(PNG_FLOATING_POINT_SUPPORTED)
  192510. png_free(png_ptr, swidth);
  192511. #endif
  192512. png_free(png_ptr, buffer);
  192513. return;
  192514. }
  192515. #ifdef PNG_FLOATING_POINT_SUPPORTED
  192516. height = png_strtod(png_ptr, ep, &vp);
  192517. if (*vp)
  192518. {
  192519. png_warning(png_ptr, "malformed height string in sCAL chunk");
  192520. return;
  192521. }
  192522. #else
  192523. #ifdef PNG_FIXED_POINT_SUPPORTED
  192524. sheight = (png_charp)png_malloc_warn(png_ptr, png_strlen(ep) + 1);
  192525. if (swidth == NULL)
  192526. {
  192527. png_warning(png_ptr, "Out of memory while processing sCAL chunk height");
  192528. return;
  192529. }
  192530. png_memcpy(sheight, ep, (png_size_t)png_strlen(ep));
  192531. #endif
  192532. #endif
  192533. if (buffer + slength < ep
  192534. #ifdef PNG_FLOATING_POINT_SUPPORTED
  192535. || width <= 0. || height <= 0.
  192536. #endif
  192537. )
  192538. {
  192539. png_warning(png_ptr, "Invalid sCAL data");
  192540. png_free(png_ptr, buffer);
  192541. #if defined(PNG_FIXED_POINT_SUPPORTED) && !defined(PNG_FLOATING_POINT_SUPPORTED)
  192542. png_free(png_ptr, swidth);
  192543. png_free(png_ptr, sheight);
  192544. #endif
  192545. return;
  192546. }
  192547. #ifdef PNG_FLOATING_POINT_SUPPORTED
  192548. png_set_sCAL(png_ptr, info_ptr, buffer[0], width, height);
  192549. #else
  192550. #ifdef PNG_FIXED_POINT_SUPPORTED
  192551. png_set_sCAL_s(png_ptr, info_ptr, buffer[0], swidth, sheight);
  192552. #endif
  192553. #endif
  192554. png_free(png_ptr, buffer);
  192555. #if defined(PNG_FIXED_POINT_SUPPORTED) && !defined(PNG_FLOATING_POINT_SUPPORTED)
  192556. png_free(png_ptr, swidth);
  192557. png_free(png_ptr, sheight);
  192558. #endif
  192559. }
  192560. #endif
  192561. #if defined(PNG_READ_tIME_SUPPORTED)
  192562. void /* PRIVATE */
  192563. png_handle_tIME(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  192564. {
  192565. png_byte buf[7];
  192566. png_time mod_time;
  192567. png_debug(1, "in png_handle_tIME\n");
  192568. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  192569. png_error(png_ptr, "Out of place tIME chunk");
  192570. else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_tIME))
  192571. {
  192572. png_warning(png_ptr, "Duplicate tIME chunk");
  192573. png_crc_finish(png_ptr, length);
  192574. return;
  192575. }
  192576. if (png_ptr->mode & PNG_HAVE_IDAT)
  192577. png_ptr->mode |= PNG_AFTER_IDAT;
  192578. if (length != 7)
  192579. {
  192580. png_warning(png_ptr, "Incorrect tIME chunk length");
  192581. png_crc_finish(png_ptr, length);
  192582. return;
  192583. }
  192584. png_crc_read(png_ptr, buf, 7);
  192585. if (png_crc_finish(png_ptr, 0))
  192586. return;
  192587. mod_time.second = buf[6];
  192588. mod_time.minute = buf[5];
  192589. mod_time.hour = buf[4];
  192590. mod_time.day = buf[3];
  192591. mod_time.month = buf[2];
  192592. mod_time.year = png_get_uint_16(buf);
  192593. png_set_tIME(png_ptr, info_ptr, &mod_time);
  192594. }
  192595. #endif
  192596. #if defined(PNG_READ_tEXt_SUPPORTED)
  192597. /* Note: this does not properly handle chunks that are > 64K under DOS */
  192598. void /* PRIVATE */
  192599. png_handle_tEXt(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  192600. {
  192601. png_textp text_ptr;
  192602. png_charp key;
  192603. png_charp text;
  192604. png_uint_32 skip = 0;
  192605. png_size_t slength;
  192606. int ret;
  192607. png_debug(1, "in png_handle_tEXt\n");
  192608. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  192609. png_error(png_ptr, "Missing IHDR before tEXt");
  192610. if (png_ptr->mode & PNG_HAVE_IDAT)
  192611. png_ptr->mode |= PNG_AFTER_IDAT;
  192612. #ifdef PNG_MAX_MALLOC_64K
  192613. if (length > (png_uint_32)65535L)
  192614. {
  192615. png_warning(png_ptr, "tEXt chunk too large to fit in memory");
  192616. skip = length - (png_uint_32)65535L;
  192617. length = (png_uint_32)65535L;
  192618. }
  192619. #endif
  192620. key = (png_charp)png_malloc_warn(png_ptr, length + 1);
  192621. if (key == NULL)
  192622. {
  192623. png_warning(png_ptr, "No memory to process text chunk.");
  192624. return;
  192625. }
  192626. slength = (png_size_t)length;
  192627. png_crc_read(png_ptr, (png_bytep)key, slength);
  192628. if (png_crc_finish(png_ptr, skip))
  192629. {
  192630. png_free(png_ptr, key);
  192631. return;
  192632. }
  192633. key[slength] = 0x00;
  192634. for (text = key; *text; text++)
  192635. /* empty loop to find end of key */ ;
  192636. if (text != key + slength)
  192637. text++;
  192638. text_ptr = (png_textp)png_malloc_warn(png_ptr,
  192639. (png_uint_32)png_sizeof(png_text));
  192640. if (text_ptr == NULL)
  192641. {
  192642. png_warning(png_ptr, "Not enough memory to process text chunk.");
  192643. png_free(png_ptr, key);
  192644. return;
  192645. }
  192646. text_ptr->compression = PNG_TEXT_COMPRESSION_NONE;
  192647. text_ptr->key = key;
  192648. #ifdef PNG_iTXt_SUPPORTED
  192649. text_ptr->lang = NULL;
  192650. text_ptr->lang_key = NULL;
  192651. text_ptr->itxt_length = 0;
  192652. #endif
  192653. text_ptr->text = text;
  192654. text_ptr->text_length = png_strlen(text);
  192655. ret=png_set_text_2(png_ptr, info_ptr, text_ptr, 1);
  192656. png_free(png_ptr, key);
  192657. png_free(png_ptr, text_ptr);
  192658. if (ret)
  192659. png_warning(png_ptr, "Insufficient memory to process text chunk.");
  192660. }
  192661. #endif
  192662. #if defined(PNG_READ_zTXt_SUPPORTED)
  192663. /* note: this does not correctly handle chunks that are > 64K under DOS */
  192664. void /* PRIVATE */
  192665. png_handle_zTXt(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  192666. {
  192667. png_textp text_ptr;
  192668. png_charp chunkdata;
  192669. png_charp text;
  192670. int comp_type;
  192671. int ret;
  192672. png_size_t slength, prefix_len, data_len;
  192673. png_debug(1, "in png_handle_zTXt\n");
  192674. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  192675. png_error(png_ptr, "Missing IHDR before zTXt");
  192676. if (png_ptr->mode & PNG_HAVE_IDAT)
  192677. png_ptr->mode |= PNG_AFTER_IDAT;
  192678. #ifdef PNG_MAX_MALLOC_64K
  192679. /* We will no doubt have problems with chunks even half this size, but
  192680. there is no hard and fast rule to tell us where to stop. */
  192681. if (length > (png_uint_32)65535L)
  192682. {
  192683. png_warning(png_ptr,"zTXt chunk too large to fit in memory");
  192684. png_crc_finish(png_ptr, length);
  192685. return;
  192686. }
  192687. #endif
  192688. chunkdata = (png_charp)png_malloc_warn(png_ptr, length + 1);
  192689. if (chunkdata == NULL)
  192690. {
  192691. png_warning(png_ptr,"Out of memory processing zTXt chunk.");
  192692. return;
  192693. }
  192694. slength = (png_size_t)length;
  192695. png_crc_read(png_ptr, (png_bytep)chunkdata, slength);
  192696. if (png_crc_finish(png_ptr, 0))
  192697. {
  192698. png_free(png_ptr, chunkdata);
  192699. return;
  192700. }
  192701. chunkdata[slength] = 0x00;
  192702. for (text = chunkdata; *text; text++)
  192703. /* empty loop */ ;
  192704. /* zTXt must have some text after the chunkdataword */
  192705. if (text >= chunkdata + slength - 2)
  192706. {
  192707. png_warning(png_ptr, "Truncated zTXt chunk");
  192708. png_free(png_ptr, chunkdata);
  192709. return;
  192710. }
  192711. else
  192712. {
  192713. comp_type = *(++text);
  192714. if (comp_type != PNG_TEXT_COMPRESSION_zTXt)
  192715. {
  192716. png_warning(png_ptr, "Unknown compression type in zTXt chunk");
  192717. comp_type = PNG_TEXT_COMPRESSION_zTXt;
  192718. }
  192719. text++; /* skip the compression_method byte */
  192720. }
  192721. prefix_len = text - chunkdata;
  192722. chunkdata = (png_charp)png_decompress_chunk(png_ptr, comp_type, chunkdata,
  192723. (png_size_t)length, prefix_len, &data_len);
  192724. text_ptr = (png_textp)png_malloc_warn(png_ptr,
  192725. (png_uint_32)png_sizeof(png_text));
  192726. if (text_ptr == NULL)
  192727. {
  192728. png_warning(png_ptr,"Not enough memory to process zTXt chunk.");
  192729. png_free(png_ptr, chunkdata);
  192730. return;
  192731. }
  192732. text_ptr->compression = comp_type;
  192733. text_ptr->key = chunkdata;
  192734. #ifdef PNG_iTXt_SUPPORTED
  192735. text_ptr->lang = NULL;
  192736. text_ptr->lang_key = NULL;
  192737. text_ptr->itxt_length = 0;
  192738. #endif
  192739. text_ptr->text = chunkdata + prefix_len;
  192740. text_ptr->text_length = data_len;
  192741. ret=png_set_text_2(png_ptr, info_ptr, text_ptr, 1);
  192742. png_free(png_ptr, text_ptr);
  192743. png_free(png_ptr, chunkdata);
  192744. if (ret)
  192745. png_error(png_ptr, "Insufficient memory to store zTXt chunk.");
  192746. }
  192747. #endif
  192748. #if defined(PNG_READ_iTXt_SUPPORTED)
  192749. /* note: this does not correctly handle chunks that are > 64K under DOS */
  192750. void /* PRIVATE */
  192751. png_handle_iTXt(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  192752. {
  192753. png_textp text_ptr;
  192754. png_charp chunkdata;
  192755. png_charp key, lang, text, lang_key;
  192756. int comp_flag;
  192757. int comp_type = 0;
  192758. int ret;
  192759. png_size_t slength, prefix_len, data_len;
  192760. png_debug(1, "in png_handle_iTXt\n");
  192761. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  192762. png_error(png_ptr, "Missing IHDR before iTXt");
  192763. if (png_ptr->mode & PNG_HAVE_IDAT)
  192764. png_ptr->mode |= PNG_AFTER_IDAT;
  192765. #ifdef PNG_MAX_MALLOC_64K
  192766. /* We will no doubt have problems with chunks even half this size, but
  192767. there is no hard and fast rule to tell us where to stop. */
  192768. if (length > (png_uint_32)65535L)
  192769. {
  192770. png_warning(png_ptr,"iTXt chunk too large to fit in memory");
  192771. png_crc_finish(png_ptr, length);
  192772. return;
  192773. }
  192774. #endif
  192775. chunkdata = (png_charp)png_malloc_warn(png_ptr, length + 1);
  192776. if (chunkdata == NULL)
  192777. {
  192778. png_warning(png_ptr, "No memory to process iTXt chunk.");
  192779. return;
  192780. }
  192781. slength = (png_size_t)length;
  192782. png_crc_read(png_ptr, (png_bytep)chunkdata, slength);
  192783. if (png_crc_finish(png_ptr, 0))
  192784. {
  192785. png_free(png_ptr, chunkdata);
  192786. return;
  192787. }
  192788. chunkdata[slength] = 0x00;
  192789. for (lang = chunkdata; *lang; lang++)
  192790. /* empty loop */ ;
  192791. lang++; /* skip NUL separator */
  192792. /* iTXt must have a language tag (possibly empty), two compression bytes,
  192793. translated keyword (possibly empty), and possibly some text after the
  192794. keyword */
  192795. if (lang >= chunkdata + slength - 3)
  192796. {
  192797. png_warning(png_ptr, "Truncated iTXt chunk");
  192798. png_free(png_ptr, chunkdata);
  192799. return;
  192800. }
  192801. else
  192802. {
  192803. comp_flag = *lang++;
  192804. comp_type = *lang++;
  192805. }
  192806. for (lang_key = lang; *lang_key; lang_key++)
  192807. /* empty loop */ ;
  192808. lang_key++; /* skip NUL separator */
  192809. if (lang_key >= chunkdata + slength)
  192810. {
  192811. png_warning(png_ptr, "Truncated iTXt chunk");
  192812. png_free(png_ptr, chunkdata);
  192813. return;
  192814. }
  192815. for (text = lang_key; *text; text++)
  192816. /* empty loop */ ;
  192817. text++; /* skip NUL separator */
  192818. if (text >= chunkdata + slength)
  192819. {
  192820. png_warning(png_ptr, "Malformed iTXt chunk");
  192821. png_free(png_ptr, chunkdata);
  192822. return;
  192823. }
  192824. prefix_len = text - chunkdata;
  192825. key=chunkdata;
  192826. if (comp_flag)
  192827. chunkdata = png_decompress_chunk(png_ptr, comp_type, chunkdata,
  192828. (size_t)length, prefix_len, &data_len);
  192829. else
  192830. data_len=png_strlen(chunkdata + prefix_len);
  192831. text_ptr = (png_textp)png_malloc_warn(png_ptr,
  192832. (png_uint_32)png_sizeof(png_text));
  192833. if (text_ptr == NULL)
  192834. {
  192835. png_warning(png_ptr,"Not enough memory to process iTXt chunk.");
  192836. png_free(png_ptr, chunkdata);
  192837. return;
  192838. }
  192839. text_ptr->compression = (int)comp_flag + 1;
  192840. text_ptr->lang_key = chunkdata+(lang_key-key);
  192841. text_ptr->lang = chunkdata+(lang-key);
  192842. text_ptr->itxt_length = data_len;
  192843. text_ptr->text_length = 0;
  192844. text_ptr->key = chunkdata;
  192845. text_ptr->text = chunkdata + prefix_len;
  192846. ret=png_set_text_2(png_ptr, info_ptr, text_ptr, 1);
  192847. png_free(png_ptr, text_ptr);
  192848. png_free(png_ptr, chunkdata);
  192849. if (ret)
  192850. png_error(png_ptr, "Insufficient memory to store iTXt chunk.");
  192851. }
  192852. #endif
  192853. /* This function is called when we haven't found a handler for a
  192854. chunk. If there isn't a problem with the chunk itself (ie bad
  192855. chunk name, CRC, or a critical chunk), the chunk is silently ignored
  192856. -- unless the PNG_FLAG_UNKNOWN_CHUNKS_SUPPORTED flag is on in which
  192857. case it will be saved away to be written out later. */
  192858. void /* PRIVATE */
  192859. png_handle_unknown(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  192860. {
  192861. png_uint_32 skip = 0;
  192862. png_debug(1, "in png_handle_unknown\n");
  192863. if (png_ptr->mode & PNG_HAVE_IDAT)
  192864. {
  192865. #ifdef PNG_USE_LOCAL_ARRAYS
  192866. PNG_CONST PNG_IDAT;
  192867. #endif
  192868. if (png_memcmp(png_ptr->chunk_name, png_IDAT, 4)) /* not an IDAT */
  192869. png_ptr->mode |= PNG_AFTER_IDAT;
  192870. }
  192871. png_check_chunk_name(png_ptr, png_ptr->chunk_name);
  192872. if (!(png_ptr->chunk_name[0] & 0x20))
  192873. {
  192874. #if defined(PNG_READ_UNKNOWN_CHUNKS_SUPPORTED)
  192875. if(png_handle_as_unknown(png_ptr, png_ptr->chunk_name) !=
  192876. PNG_HANDLE_CHUNK_ALWAYS
  192877. #if defined(PNG_READ_USER_CHUNKS_SUPPORTED)
  192878. && png_ptr->read_user_chunk_fn == NULL
  192879. #endif
  192880. )
  192881. #endif
  192882. png_chunk_error(png_ptr, "unknown critical chunk");
  192883. }
  192884. #if defined(PNG_READ_UNKNOWN_CHUNKS_SUPPORTED)
  192885. if ((png_ptr->flags & PNG_FLAG_KEEP_UNKNOWN_CHUNKS) ||
  192886. (png_ptr->read_user_chunk_fn != NULL))
  192887. {
  192888. #ifdef PNG_MAX_MALLOC_64K
  192889. if (length > (png_uint_32)65535L)
  192890. {
  192891. png_warning(png_ptr, "unknown chunk too large to fit in memory");
  192892. skip = length - (png_uint_32)65535L;
  192893. length = (png_uint_32)65535L;
  192894. }
  192895. #endif
  192896. png_strncpy((png_charp)png_ptr->unknown_chunk.name,
  192897. (png_charp)png_ptr->chunk_name, 5);
  192898. png_ptr->unknown_chunk.data = (png_bytep)png_malloc(png_ptr, length);
  192899. png_ptr->unknown_chunk.size = (png_size_t)length;
  192900. png_crc_read(png_ptr, (png_bytep)png_ptr->unknown_chunk.data, length);
  192901. #if defined(PNG_READ_USER_CHUNKS_SUPPORTED)
  192902. if(png_ptr->read_user_chunk_fn != NULL)
  192903. {
  192904. /* callback to user unknown chunk handler */
  192905. int ret;
  192906. ret = (*(png_ptr->read_user_chunk_fn))
  192907. (png_ptr, &png_ptr->unknown_chunk);
  192908. if (ret < 0)
  192909. png_chunk_error(png_ptr, "error in user chunk");
  192910. if (ret == 0)
  192911. {
  192912. if (!(png_ptr->chunk_name[0] & 0x20))
  192913. if(png_handle_as_unknown(png_ptr, png_ptr->chunk_name) !=
  192914. PNG_HANDLE_CHUNK_ALWAYS)
  192915. png_chunk_error(png_ptr, "unknown critical chunk");
  192916. png_set_unknown_chunks(png_ptr, info_ptr,
  192917. &png_ptr->unknown_chunk, 1);
  192918. }
  192919. }
  192920. #else
  192921. png_set_unknown_chunks(png_ptr, info_ptr, &png_ptr->unknown_chunk, 1);
  192922. #endif
  192923. png_free(png_ptr, png_ptr->unknown_chunk.data);
  192924. png_ptr->unknown_chunk.data = NULL;
  192925. }
  192926. else
  192927. #endif
  192928. skip = length;
  192929. png_crc_finish(png_ptr, skip);
  192930. #if !defined(PNG_READ_USER_CHUNKS_SUPPORTED)
  192931. info_ptr = info_ptr; /* quiet compiler warnings about unused info_ptr */
  192932. #endif
  192933. }
  192934. /* This function is called to verify that a chunk name is valid.
  192935. This function can't have the "critical chunk check" incorporated
  192936. into it, since in the future we will need to be able to call user
  192937. functions to handle unknown critical chunks after we check that
  192938. the chunk name itself is valid. */
  192939. #define isnonalpha(c) ((c) < 65 || (c) > 122 || ((c) > 90 && (c) < 97))
  192940. void /* PRIVATE */
  192941. png_check_chunk_name(png_structp png_ptr, png_bytep chunk_name)
  192942. {
  192943. png_debug(1, "in png_check_chunk_name\n");
  192944. if (isnonalpha(chunk_name[0]) || isnonalpha(chunk_name[1]) ||
  192945. isnonalpha(chunk_name[2]) || isnonalpha(chunk_name[3]))
  192946. {
  192947. png_chunk_error(png_ptr, "invalid chunk type");
  192948. }
  192949. }
  192950. /* Combines the row recently read in with the existing pixels in the
  192951. row. This routine takes care of alpha and transparency if requested.
  192952. This routine also handles the two methods of progressive display
  192953. of interlaced images, depending on the mask value.
  192954. The mask value describes which pixels are to be combined with
  192955. the row. The pattern always repeats every 8 pixels, so just 8
  192956. bits are needed. A one indicates the pixel is to be combined,
  192957. a zero indicates the pixel is to be skipped. This is in addition
  192958. to any alpha or transparency value associated with the pixel. If
  192959. you want all pixels to be combined, pass 0xff (255) in mask. */
  192960. void /* PRIVATE */
  192961. png_combine_row(png_structp png_ptr, png_bytep row, int mask)
  192962. {
  192963. png_debug(1,"in png_combine_row\n");
  192964. if (mask == 0xff)
  192965. {
  192966. png_memcpy(row, png_ptr->row_buf + 1,
  192967. PNG_ROWBYTES(png_ptr->row_info.pixel_depth, png_ptr->width));
  192968. }
  192969. else
  192970. {
  192971. switch (png_ptr->row_info.pixel_depth)
  192972. {
  192973. case 1:
  192974. {
  192975. png_bytep sp = png_ptr->row_buf + 1;
  192976. png_bytep dp = row;
  192977. int s_inc, s_start, s_end;
  192978. int m = 0x80;
  192979. int shift;
  192980. png_uint_32 i;
  192981. png_uint_32 row_width = png_ptr->width;
  192982. #if defined(PNG_READ_PACKSWAP_SUPPORTED)
  192983. if (png_ptr->transformations & PNG_PACKSWAP)
  192984. {
  192985. s_start = 0;
  192986. s_end = 7;
  192987. s_inc = 1;
  192988. }
  192989. else
  192990. #endif
  192991. {
  192992. s_start = 7;
  192993. s_end = 0;
  192994. s_inc = -1;
  192995. }
  192996. shift = s_start;
  192997. for (i = 0; i < row_width; i++)
  192998. {
  192999. if (m & mask)
  193000. {
  193001. int value;
  193002. value = (*sp >> shift) & 0x01;
  193003. *dp &= (png_byte)((0x7f7f >> (7 - shift)) & 0xff);
  193004. *dp |= (png_byte)(value << shift);
  193005. }
  193006. if (shift == s_end)
  193007. {
  193008. shift = s_start;
  193009. sp++;
  193010. dp++;
  193011. }
  193012. else
  193013. shift += s_inc;
  193014. if (m == 1)
  193015. m = 0x80;
  193016. else
  193017. m >>= 1;
  193018. }
  193019. break;
  193020. }
  193021. case 2:
  193022. {
  193023. png_bytep sp = png_ptr->row_buf + 1;
  193024. png_bytep dp = row;
  193025. int s_start, s_end, s_inc;
  193026. int m = 0x80;
  193027. int shift;
  193028. png_uint_32 i;
  193029. png_uint_32 row_width = png_ptr->width;
  193030. int value;
  193031. #if defined(PNG_READ_PACKSWAP_SUPPORTED)
  193032. if (png_ptr->transformations & PNG_PACKSWAP)
  193033. {
  193034. s_start = 0;
  193035. s_end = 6;
  193036. s_inc = 2;
  193037. }
  193038. else
  193039. #endif
  193040. {
  193041. s_start = 6;
  193042. s_end = 0;
  193043. s_inc = -2;
  193044. }
  193045. shift = s_start;
  193046. for (i = 0; i < row_width; i++)
  193047. {
  193048. if (m & mask)
  193049. {
  193050. value = (*sp >> shift) & 0x03;
  193051. *dp &= (png_byte)((0x3f3f >> (6 - shift)) & 0xff);
  193052. *dp |= (png_byte)(value << shift);
  193053. }
  193054. if (shift == s_end)
  193055. {
  193056. shift = s_start;
  193057. sp++;
  193058. dp++;
  193059. }
  193060. else
  193061. shift += s_inc;
  193062. if (m == 1)
  193063. m = 0x80;
  193064. else
  193065. m >>= 1;
  193066. }
  193067. break;
  193068. }
  193069. case 4:
  193070. {
  193071. png_bytep sp = png_ptr->row_buf + 1;
  193072. png_bytep dp = row;
  193073. int s_start, s_end, s_inc;
  193074. int m = 0x80;
  193075. int shift;
  193076. png_uint_32 i;
  193077. png_uint_32 row_width = png_ptr->width;
  193078. int value;
  193079. #if defined(PNG_READ_PACKSWAP_SUPPORTED)
  193080. if (png_ptr->transformations & PNG_PACKSWAP)
  193081. {
  193082. s_start = 0;
  193083. s_end = 4;
  193084. s_inc = 4;
  193085. }
  193086. else
  193087. #endif
  193088. {
  193089. s_start = 4;
  193090. s_end = 0;
  193091. s_inc = -4;
  193092. }
  193093. shift = s_start;
  193094. for (i = 0; i < row_width; i++)
  193095. {
  193096. if (m & mask)
  193097. {
  193098. value = (*sp >> shift) & 0xf;
  193099. *dp &= (png_byte)((0xf0f >> (4 - shift)) & 0xff);
  193100. *dp |= (png_byte)(value << shift);
  193101. }
  193102. if (shift == s_end)
  193103. {
  193104. shift = s_start;
  193105. sp++;
  193106. dp++;
  193107. }
  193108. else
  193109. shift += s_inc;
  193110. if (m == 1)
  193111. m = 0x80;
  193112. else
  193113. m >>= 1;
  193114. }
  193115. break;
  193116. }
  193117. default:
  193118. {
  193119. png_bytep sp = png_ptr->row_buf + 1;
  193120. png_bytep dp = row;
  193121. png_size_t pixel_bytes = (png_ptr->row_info.pixel_depth >> 3);
  193122. png_uint_32 i;
  193123. png_uint_32 row_width = png_ptr->width;
  193124. png_byte m = 0x80;
  193125. for (i = 0; i < row_width; i++)
  193126. {
  193127. if (m & mask)
  193128. {
  193129. png_memcpy(dp, sp, pixel_bytes);
  193130. }
  193131. sp += pixel_bytes;
  193132. dp += pixel_bytes;
  193133. if (m == 1)
  193134. m = 0x80;
  193135. else
  193136. m >>= 1;
  193137. }
  193138. break;
  193139. }
  193140. }
  193141. }
  193142. }
  193143. #ifdef PNG_READ_INTERLACING_SUPPORTED
  193144. /* OLD pre-1.0.9 interface:
  193145. void png_do_read_interlace(png_row_infop row_info, png_bytep row, int pass,
  193146. png_uint_32 transformations)
  193147. */
  193148. void /* PRIVATE */
  193149. png_do_read_interlace(png_structp png_ptr)
  193150. {
  193151. png_row_infop row_info = &(png_ptr->row_info);
  193152. png_bytep row = png_ptr->row_buf + 1;
  193153. int pass = png_ptr->pass;
  193154. png_uint_32 transformations = png_ptr->transformations;
  193155. #ifdef PNG_USE_LOCAL_ARRAYS
  193156. /* arrays to facilitate easy interlacing - use pass (0 - 6) as index */
  193157. /* offset to next interlace block */
  193158. PNG_CONST int png_pass_inc[7] = {8, 8, 4, 4, 2, 2, 1};
  193159. #endif
  193160. png_debug(1,"in png_do_read_interlace\n");
  193161. if (row != NULL && row_info != NULL)
  193162. {
  193163. png_uint_32 final_width;
  193164. final_width = row_info->width * png_pass_inc[pass];
  193165. switch (row_info->pixel_depth)
  193166. {
  193167. case 1:
  193168. {
  193169. png_bytep sp = row + (png_size_t)((row_info->width - 1) >> 3);
  193170. png_bytep dp = row + (png_size_t)((final_width - 1) >> 3);
  193171. int sshift, dshift;
  193172. int s_start, s_end, s_inc;
  193173. int jstop = png_pass_inc[pass];
  193174. png_byte v;
  193175. png_uint_32 i;
  193176. int j;
  193177. #if defined(PNG_READ_PACKSWAP_SUPPORTED)
  193178. if (transformations & PNG_PACKSWAP)
  193179. {
  193180. sshift = (int)((row_info->width + 7) & 0x07);
  193181. dshift = (int)((final_width + 7) & 0x07);
  193182. s_start = 7;
  193183. s_end = 0;
  193184. s_inc = -1;
  193185. }
  193186. else
  193187. #endif
  193188. {
  193189. sshift = 7 - (int)((row_info->width + 7) & 0x07);
  193190. dshift = 7 - (int)((final_width + 7) & 0x07);
  193191. s_start = 0;
  193192. s_end = 7;
  193193. s_inc = 1;
  193194. }
  193195. for (i = 0; i < row_info->width; i++)
  193196. {
  193197. v = (png_byte)((*sp >> sshift) & 0x01);
  193198. for (j = 0; j < jstop; j++)
  193199. {
  193200. *dp &= (png_byte)((0x7f7f >> (7 - dshift)) & 0xff);
  193201. *dp |= (png_byte)(v << dshift);
  193202. if (dshift == s_end)
  193203. {
  193204. dshift = s_start;
  193205. dp--;
  193206. }
  193207. else
  193208. dshift += s_inc;
  193209. }
  193210. if (sshift == s_end)
  193211. {
  193212. sshift = s_start;
  193213. sp--;
  193214. }
  193215. else
  193216. sshift += s_inc;
  193217. }
  193218. break;
  193219. }
  193220. case 2:
  193221. {
  193222. png_bytep sp = row + (png_uint_32)((row_info->width - 1) >> 2);
  193223. png_bytep dp = row + (png_uint_32)((final_width - 1) >> 2);
  193224. int sshift, dshift;
  193225. int s_start, s_end, s_inc;
  193226. int jstop = png_pass_inc[pass];
  193227. png_uint_32 i;
  193228. #if defined(PNG_READ_PACKSWAP_SUPPORTED)
  193229. if (transformations & PNG_PACKSWAP)
  193230. {
  193231. sshift = (int)(((row_info->width + 3) & 0x03) << 1);
  193232. dshift = (int)(((final_width + 3) & 0x03) << 1);
  193233. s_start = 6;
  193234. s_end = 0;
  193235. s_inc = -2;
  193236. }
  193237. else
  193238. #endif
  193239. {
  193240. sshift = (int)((3 - ((row_info->width + 3) & 0x03)) << 1);
  193241. dshift = (int)((3 - ((final_width + 3) & 0x03)) << 1);
  193242. s_start = 0;
  193243. s_end = 6;
  193244. s_inc = 2;
  193245. }
  193246. for (i = 0; i < row_info->width; i++)
  193247. {
  193248. png_byte v;
  193249. int j;
  193250. v = (png_byte)((*sp >> sshift) & 0x03);
  193251. for (j = 0; j < jstop; j++)
  193252. {
  193253. *dp &= (png_byte)((0x3f3f >> (6 - dshift)) & 0xff);
  193254. *dp |= (png_byte)(v << dshift);
  193255. if (dshift == s_end)
  193256. {
  193257. dshift = s_start;
  193258. dp--;
  193259. }
  193260. else
  193261. dshift += s_inc;
  193262. }
  193263. if (sshift == s_end)
  193264. {
  193265. sshift = s_start;
  193266. sp--;
  193267. }
  193268. else
  193269. sshift += s_inc;
  193270. }
  193271. break;
  193272. }
  193273. case 4:
  193274. {
  193275. png_bytep sp = row + (png_size_t)((row_info->width - 1) >> 1);
  193276. png_bytep dp = row + (png_size_t)((final_width - 1) >> 1);
  193277. int sshift, dshift;
  193278. int s_start, s_end, s_inc;
  193279. png_uint_32 i;
  193280. int jstop = png_pass_inc[pass];
  193281. #if defined(PNG_READ_PACKSWAP_SUPPORTED)
  193282. if (transformations & PNG_PACKSWAP)
  193283. {
  193284. sshift = (int)(((row_info->width + 1) & 0x01) << 2);
  193285. dshift = (int)(((final_width + 1) & 0x01) << 2);
  193286. s_start = 4;
  193287. s_end = 0;
  193288. s_inc = -4;
  193289. }
  193290. else
  193291. #endif
  193292. {
  193293. sshift = (int)((1 - ((row_info->width + 1) & 0x01)) << 2);
  193294. dshift = (int)((1 - ((final_width + 1) & 0x01)) << 2);
  193295. s_start = 0;
  193296. s_end = 4;
  193297. s_inc = 4;
  193298. }
  193299. for (i = 0; i < row_info->width; i++)
  193300. {
  193301. png_byte v = (png_byte)((*sp >> sshift) & 0xf);
  193302. int j;
  193303. for (j = 0; j < jstop; j++)
  193304. {
  193305. *dp &= (png_byte)((0xf0f >> (4 - dshift)) & 0xff);
  193306. *dp |= (png_byte)(v << dshift);
  193307. if (dshift == s_end)
  193308. {
  193309. dshift = s_start;
  193310. dp--;
  193311. }
  193312. else
  193313. dshift += s_inc;
  193314. }
  193315. if (sshift == s_end)
  193316. {
  193317. sshift = s_start;
  193318. sp--;
  193319. }
  193320. else
  193321. sshift += s_inc;
  193322. }
  193323. break;
  193324. }
  193325. default:
  193326. {
  193327. png_size_t pixel_bytes = (row_info->pixel_depth >> 3);
  193328. png_bytep sp = row + (png_size_t)(row_info->width - 1) * pixel_bytes;
  193329. png_bytep dp = row + (png_size_t)(final_width - 1) * pixel_bytes;
  193330. int jstop = png_pass_inc[pass];
  193331. png_uint_32 i;
  193332. for (i = 0; i < row_info->width; i++)
  193333. {
  193334. png_byte v[8];
  193335. int j;
  193336. png_memcpy(v, sp, pixel_bytes);
  193337. for (j = 0; j < jstop; j++)
  193338. {
  193339. png_memcpy(dp, v, pixel_bytes);
  193340. dp -= pixel_bytes;
  193341. }
  193342. sp -= pixel_bytes;
  193343. }
  193344. break;
  193345. }
  193346. }
  193347. row_info->width = final_width;
  193348. row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,final_width);
  193349. }
  193350. #if !defined(PNG_READ_PACKSWAP_SUPPORTED)
  193351. transformations = transformations; /* silence compiler warning */
  193352. #endif
  193353. }
  193354. #endif /* PNG_READ_INTERLACING_SUPPORTED */
  193355. void /* PRIVATE */
  193356. png_read_filter_row(png_structp, png_row_infop row_info, png_bytep row,
  193357. png_bytep prev_row, int filter)
  193358. {
  193359. png_debug(1, "in png_read_filter_row\n");
  193360. png_debug2(2,"row = %lu, filter = %d\n", png_ptr->row_number, filter);
  193361. switch (filter)
  193362. {
  193363. case PNG_FILTER_VALUE_NONE:
  193364. break;
  193365. case PNG_FILTER_VALUE_SUB:
  193366. {
  193367. png_uint_32 i;
  193368. png_uint_32 istop = row_info->rowbytes;
  193369. png_uint_32 bpp = (row_info->pixel_depth + 7) >> 3;
  193370. png_bytep rp = row + bpp;
  193371. png_bytep lp = row;
  193372. for (i = bpp; i < istop; i++)
  193373. {
  193374. *rp = (png_byte)(((int)(*rp) + (int)(*lp++)) & 0xff);
  193375. rp++;
  193376. }
  193377. break;
  193378. }
  193379. case PNG_FILTER_VALUE_UP:
  193380. {
  193381. png_uint_32 i;
  193382. png_uint_32 istop = row_info->rowbytes;
  193383. png_bytep rp = row;
  193384. png_bytep pp = prev_row;
  193385. for (i = 0; i < istop; i++)
  193386. {
  193387. *rp = (png_byte)(((int)(*rp) + (int)(*pp++)) & 0xff);
  193388. rp++;
  193389. }
  193390. break;
  193391. }
  193392. case PNG_FILTER_VALUE_AVG:
  193393. {
  193394. png_uint_32 i;
  193395. png_bytep rp = row;
  193396. png_bytep pp = prev_row;
  193397. png_bytep lp = row;
  193398. png_uint_32 bpp = (row_info->pixel_depth + 7) >> 3;
  193399. png_uint_32 istop = row_info->rowbytes - bpp;
  193400. for (i = 0; i < bpp; i++)
  193401. {
  193402. *rp = (png_byte)(((int)(*rp) +
  193403. ((int)(*pp++) / 2 )) & 0xff);
  193404. rp++;
  193405. }
  193406. for (i = 0; i < istop; i++)
  193407. {
  193408. *rp = (png_byte)(((int)(*rp) +
  193409. (int)(*pp++ + *lp++) / 2 ) & 0xff);
  193410. rp++;
  193411. }
  193412. break;
  193413. }
  193414. case PNG_FILTER_VALUE_PAETH:
  193415. {
  193416. png_uint_32 i;
  193417. png_bytep rp = row;
  193418. png_bytep pp = prev_row;
  193419. png_bytep lp = row;
  193420. png_bytep cp = prev_row;
  193421. png_uint_32 bpp = (row_info->pixel_depth + 7) >> 3;
  193422. png_uint_32 istop=row_info->rowbytes - bpp;
  193423. for (i = 0; i < bpp; i++)
  193424. {
  193425. *rp = (png_byte)(((int)(*rp) + (int)(*pp++)) & 0xff);
  193426. rp++;
  193427. }
  193428. for (i = 0; i < istop; i++) /* use leftover rp,pp */
  193429. {
  193430. int a, b, c, pa, pb, pc, p;
  193431. a = *lp++;
  193432. b = *pp++;
  193433. c = *cp++;
  193434. p = b - c;
  193435. pc = a - c;
  193436. #ifdef PNG_USE_ABS
  193437. pa = abs(p);
  193438. pb = abs(pc);
  193439. pc = abs(p + pc);
  193440. #else
  193441. pa = p < 0 ? -p : p;
  193442. pb = pc < 0 ? -pc : pc;
  193443. pc = (p + pc) < 0 ? -(p + pc) : p + pc;
  193444. #endif
  193445. /*
  193446. if (pa <= pb && pa <= pc)
  193447. p = a;
  193448. else if (pb <= pc)
  193449. p = b;
  193450. else
  193451. p = c;
  193452. */
  193453. p = (pa <= pb && pa <=pc) ? a : (pb <= pc) ? b : c;
  193454. *rp = (png_byte)(((int)(*rp) + p) & 0xff);
  193455. rp++;
  193456. }
  193457. break;
  193458. }
  193459. default:
  193460. png_warning(png_ptr, "Ignoring bad adaptive filter type");
  193461. *row=0;
  193462. break;
  193463. }
  193464. }
  193465. void /* PRIVATE */
  193466. png_read_finish_row(png_structp png_ptr)
  193467. {
  193468. #ifdef PNG_USE_LOCAL_ARRAYS
  193469. /* arrays to facilitate easy interlacing - use pass (0 - 6) as index */
  193470. /* start of interlace block */
  193471. PNG_CONST int png_pass_start[7] = {0, 4, 0, 2, 0, 1, 0};
  193472. /* offset to next interlace block */
  193473. PNG_CONST int png_pass_inc[7] = {8, 8, 4, 4, 2, 2, 1};
  193474. /* start of interlace block in the y direction */
  193475. PNG_CONST int png_pass_ystart[7] = {0, 0, 4, 0, 2, 0, 1};
  193476. /* offset to next interlace block in the y direction */
  193477. PNG_CONST int png_pass_yinc[7] = {8, 8, 8, 4, 4, 2, 2};
  193478. #endif
  193479. png_debug(1, "in png_read_finish_row\n");
  193480. png_ptr->row_number++;
  193481. if (png_ptr->row_number < png_ptr->num_rows)
  193482. return;
  193483. if (png_ptr->interlaced)
  193484. {
  193485. png_ptr->row_number = 0;
  193486. png_memset_check(png_ptr, png_ptr->prev_row, 0,
  193487. png_ptr->rowbytes + 1);
  193488. do
  193489. {
  193490. png_ptr->pass++;
  193491. if (png_ptr->pass >= 7)
  193492. break;
  193493. png_ptr->iwidth = (png_ptr->width +
  193494. png_pass_inc[png_ptr->pass] - 1 -
  193495. png_pass_start[png_ptr->pass]) /
  193496. png_pass_inc[png_ptr->pass];
  193497. png_ptr->irowbytes = PNG_ROWBYTES(png_ptr->pixel_depth,
  193498. png_ptr->iwidth) + 1;
  193499. if (!(png_ptr->transformations & PNG_INTERLACE))
  193500. {
  193501. png_ptr->num_rows = (png_ptr->height +
  193502. png_pass_yinc[png_ptr->pass] - 1 -
  193503. png_pass_ystart[png_ptr->pass]) /
  193504. png_pass_yinc[png_ptr->pass];
  193505. if (!(png_ptr->num_rows))
  193506. continue;
  193507. }
  193508. else /* if (png_ptr->transformations & PNG_INTERLACE) */
  193509. break;
  193510. } while (png_ptr->iwidth == 0);
  193511. if (png_ptr->pass < 7)
  193512. return;
  193513. }
  193514. if (!(png_ptr->flags & PNG_FLAG_ZLIB_FINISHED))
  193515. {
  193516. #ifdef PNG_USE_LOCAL_ARRAYS
  193517. PNG_CONST PNG_IDAT;
  193518. #endif
  193519. char extra;
  193520. int ret;
  193521. png_ptr->zstream.next_out = (Bytef *)&extra;
  193522. png_ptr->zstream.avail_out = (uInt)1;
  193523. for(;;)
  193524. {
  193525. if (!(png_ptr->zstream.avail_in))
  193526. {
  193527. while (!png_ptr->idat_size)
  193528. {
  193529. png_byte chunk_length[4];
  193530. png_crc_finish(png_ptr, 0);
  193531. png_read_data(png_ptr, chunk_length, 4);
  193532. png_ptr->idat_size = png_get_uint_31(png_ptr, chunk_length);
  193533. png_reset_crc(png_ptr);
  193534. png_crc_read(png_ptr, png_ptr->chunk_name, 4);
  193535. if (png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  193536. png_error(png_ptr, "Not enough image data");
  193537. }
  193538. png_ptr->zstream.avail_in = (uInt)png_ptr->zbuf_size;
  193539. png_ptr->zstream.next_in = png_ptr->zbuf;
  193540. if (png_ptr->zbuf_size > png_ptr->idat_size)
  193541. png_ptr->zstream.avail_in = (uInt)png_ptr->idat_size;
  193542. png_crc_read(png_ptr, png_ptr->zbuf, png_ptr->zstream.avail_in);
  193543. png_ptr->idat_size -= png_ptr->zstream.avail_in;
  193544. }
  193545. ret = inflate(&png_ptr->zstream, Z_PARTIAL_FLUSH);
  193546. if (ret == Z_STREAM_END)
  193547. {
  193548. if (!(png_ptr->zstream.avail_out) || png_ptr->zstream.avail_in ||
  193549. png_ptr->idat_size)
  193550. png_warning(png_ptr, "Extra compressed data");
  193551. png_ptr->mode |= PNG_AFTER_IDAT;
  193552. png_ptr->flags |= PNG_FLAG_ZLIB_FINISHED;
  193553. break;
  193554. }
  193555. if (ret != Z_OK)
  193556. png_error(png_ptr, png_ptr->zstream.msg ? png_ptr->zstream.msg :
  193557. "Decompression Error");
  193558. if (!(png_ptr->zstream.avail_out))
  193559. {
  193560. png_warning(png_ptr, "Extra compressed data.");
  193561. png_ptr->mode |= PNG_AFTER_IDAT;
  193562. png_ptr->flags |= PNG_FLAG_ZLIB_FINISHED;
  193563. break;
  193564. }
  193565. }
  193566. png_ptr->zstream.avail_out = 0;
  193567. }
  193568. if (png_ptr->idat_size || png_ptr->zstream.avail_in)
  193569. png_warning(png_ptr, "Extra compression data");
  193570. inflateReset(&png_ptr->zstream);
  193571. png_ptr->mode |= PNG_AFTER_IDAT;
  193572. }
  193573. void /* PRIVATE */
  193574. png_read_start_row(png_structp png_ptr)
  193575. {
  193576. #ifdef PNG_USE_LOCAL_ARRAYS
  193577. /* arrays to facilitate easy interlacing - use pass (0 - 6) as index */
  193578. /* start of interlace block */
  193579. PNG_CONST int png_pass_start[7] = {0, 4, 0, 2, 0, 1, 0};
  193580. /* offset to next interlace block */
  193581. PNG_CONST int png_pass_inc[7] = {8, 8, 4, 4, 2, 2, 1};
  193582. /* start of interlace block in the y direction */
  193583. PNG_CONST int png_pass_ystart[7] = {0, 0, 4, 0, 2, 0, 1};
  193584. /* offset to next interlace block in the y direction */
  193585. PNG_CONST int png_pass_yinc[7] = {8, 8, 8, 4, 4, 2, 2};
  193586. #endif
  193587. int max_pixel_depth;
  193588. png_uint_32 row_bytes;
  193589. png_debug(1, "in png_read_start_row\n");
  193590. png_ptr->zstream.avail_in = 0;
  193591. png_init_read_transformations(png_ptr);
  193592. if (png_ptr->interlaced)
  193593. {
  193594. if (!(png_ptr->transformations & PNG_INTERLACE))
  193595. png_ptr->num_rows = (png_ptr->height + png_pass_yinc[0] - 1 -
  193596. png_pass_ystart[0]) / png_pass_yinc[0];
  193597. else
  193598. png_ptr->num_rows = png_ptr->height;
  193599. png_ptr->iwidth = (png_ptr->width +
  193600. png_pass_inc[png_ptr->pass] - 1 -
  193601. png_pass_start[png_ptr->pass]) /
  193602. png_pass_inc[png_ptr->pass];
  193603. row_bytes = PNG_ROWBYTES(png_ptr->pixel_depth,png_ptr->iwidth) + 1;
  193604. png_ptr->irowbytes = (png_size_t)row_bytes;
  193605. if((png_uint_32)png_ptr->irowbytes != row_bytes)
  193606. png_error(png_ptr, "Rowbytes overflow in png_read_start_row");
  193607. }
  193608. else
  193609. {
  193610. png_ptr->num_rows = png_ptr->height;
  193611. png_ptr->iwidth = png_ptr->width;
  193612. png_ptr->irowbytes = png_ptr->rowbytes + 1;
  193613. }
  193614. max_pixel_depth = png_ptr->pixel_depth;
  193615. #if defined(PNG_READ_PACK_SUPPORTED)
  193616. if ((png_ptr->transformations & PNG_PACK) && png_ptr->bit_depth < 8)
  193617. max_pixel_depth = 8;
  193618. #endif
  193619. #if defined(PNG_READ_EXPAND_SUPPORTED)
  193620. if (png_ptr->transformations & PNG_EXPAND)
  193621. {
  193622. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  193623. {
  193624. if (png_ptr->num_trans)
  193625. max_pixel_depth = 32;
  193626. else
  193627. max_pixel_depth = 24;
  193628. }
  193629. else if (png_ptr->color_type == PNG_COLOR_TYPE_GRAY)
  193630. {
  193631. if (max_pixel_depth < 8)
  193632. max_pixel_depth = 8;
  193633. if (png_ptr->num_trans)
  193634. max_pixel_depth *= 2;
  193635. }
  193636. else if (png_ptr->color_type == PNG_COLOR_TYPE_RGB)
  193637. {
  193638. if (png_ptr->num_trans)
  193639. {
  193640. max_pixel_depth *= 4;
  193641. max_pixel_depth /= 3;
  193642. }
  193643. }
  193644. }
  193645. #endif
  193646. #if defined(PNG_READ_FILLER_SUPPORTED)
  193647. if (png_ptr->transformations & (PNG_FILLER))
  193648. {
  193649. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  193650. max_pixel_depth = 32;
  193651. else if (png_ptr->color_type == PNG_COLOR_TYPE_GRAY)
  193652. {
  193653. if (max_pixel_depth <= 8)
  193654. max_pixel_depth = 16;
  193655. else
  193656. max_pixel_depth = 32;
  193657. }
  193658. else if (png_ptr->color_type == PNG_COLOR_TYPE_RGB)
  193659. {
  193660. if (max_pixel_depth <= 32)
  193661. max_pixel_depth = 32;
  193662. else
  193663. max_pixel_depth = 64;
  193664. }
  193665. }
  193666. #endif
  193667. #if defined(PNG_READ_GRAY_TO_RGB_SUPPORTED)
  193668. if (png_ptr->transformations & PNG_GRAY_TO_RGB)
  193669. {
  193670. if (
  193671. #if defined(PNG_READ_EXPAND_SUPPORTED)
  193672. (png_ptr->num_trans && (png_ptr->transformations & PNG_EXPAND)) ||
  193673. #endif
  193674. #if defined(PNG_READ_FILLER_SUPPORTED)
  193675. (png_ptr->transformations & (PNG_FILLER)) ||
  193676. #endif
  193677. png_ptr->color_type == PNG_COLOR_TYPE_GRAY_ALPHA)
  193678. {
  193679. if (max_pixel_depth <= 16)
  193680. max_pixel_depth = 32;
  193681. else
  193682. max_pixel_depth = 64;
  193683. }
  193684. else
  193685. {
  193686. if (max_pixel_depth <= 8)
  193687. {
  193688. if (png_ptr->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  193689. max_pixel_depth = 32;
  193690. else
  193691. max_pixel_depth = 24;
  193692. }
  193693. else if (png_ptr->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  193694. max_pixel_depth = 64;
  193695. else
  193696. max_pixel_depth = 48;
  193697. }
  193698. }
  193699. #endif
  193700. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED) && \
  193701. defined(PNG_USER_TRANSFORM_PTR_SUPPORTED)
  193702. if(png_ptr->transformations & PNG_USER_TRANSFORM)
  193703. {
  193704. int user_pixel_depth=png_ptr->user_transform_depth*
  193705. png_ptr->user_transform_channels;
  193706. if(user_pixel_depth > max_pixel_depth)
  193707. max_pixel_depth=user_pixel_depth;
  193708. }
  193709. #endif
  193710. /* align the width on the next larger 8 pixels. Mainly used
  193711. for interlacing */
  193712. row_bytes = ((png_ptr->width + 7) & ~((png_uint_32)7));
  193713. /* calculate the maximum bytes needed, adding a byte and a pixel
  193714. for safety's sake */
  193715. row_bytes = PNG_ROWBYTES(max_pixel_depth,row_bytes) +
  193716. 1 + ((max_pixel_depth + 7) >> 3);
  193717. #ifdef PNG_MAX_MALLOC_64K
  193718. if (row_bytes > (png_uint_32)65536L)
  193719. png_error(png_ptr, "This image requires a row greater than 64KB");
  193720. #endif
  193721. png_ptr->big_row_buf = (png_bytep)png_malloc(png_ptr, row_bytes+64);
  193722. png_ptr->row_buf = png_ptr->big_row_buf+32;
  193723. #ifdef PNG_MAX_MALLOC_64K
  193724. if ((png_uint_32)png_ptr->rowbytes + 1 > (png_uint_32)65536L)
  193725. png_error(png_ptr, "This image requires a row greater than 64KB");
  193726. #endif
  193727. if ((png_uint_32)png_ptr->rowbytes > (png_uint_32)(PNG_SIZE_MAX - 1))
  193728. png_error(png_ptr, "Row has too many bytes to allocate in memory.");
  193729. png_ptr->prev_row = (png_bytep)png_malloc(png_ptr, (png_uint_32)(
  193730. png_ptr->rowbytes + 1));
  193731. png_memset_check(png_ptr, png_ptr->prev_row, 0, png_ptr->rowbytes + 1);
  193732. png_debug1(3, "width = %lu,\n", png_ptr->width);
  193733. png_debug1(3, "height = %lu,\n", png_ptr->height);
  193734. png_debug1(3, "iwidth = %lu,\n", png_ptr->iwidth);
  193735. png_debug1(3, "num_rows = %lu\n", png_ptr->num_rows);
  193736. png_debug1(3, "rowbytes = %lu,\n", png_ptr->rowbytes);
  193737. png_debug1(3, "irowbytes = %lu,\n", png_ptr->irowbytes);
  193738. png_ptr->flags |= PNG_FLAG_ROW_INIT;
  193739. }
  193740. #endif /* PNG_READ_SUPPORTED */
  193741. /*** End of inlined file: pngrutil.c ***/
  193742. /*** Start of inlined file: pngset.c ***/
  193743. /* pngset.c - storage of image information into info struct
  193744. *
  193745. * Last changed in libpng 1.2.21 [October 4, 2007]
  193746. * For conditions of distribution and use, see copyright notice in png.h
  193747. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  193748. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  193749. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  193750. *
  193751. * The functions here are used during reads to store data from the file
  193752. * into the info struct, and during writes to store application data
  193753. * into the info struct for writing into the file. This abstracts the
  193754. * info struct and allows us to change the structure in the future.
  193755. */
  193756. #define PNG_INTERNAL
  193757. #if defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED)
  193758. #if defined(PNG_bKGD_SUPPORTED)
  193759. void PNGAPI
  193760. png_set_bKGD(png_structp png_ptr, png_infop info_ptr, png_color_16p background)
  193761. {
  193762. png_debug1(1, "in %s storage function\n", "bKGD");
  193763. if (png_ptr == NULL || info_ptr == NULL)
  193764. return;
  193765. png_memcpy(&(info_ptr->background), background, png_sizeof(png_color_16));
  193766. info_ptr->valid |= PNG_INFO_bKGD;
  193767. }
  193768. #endif
  193769. #if defined(PNG_cHRM_SUPPORTED)
  193770. #ifdef PNG_FLOATING_POINT_SUPPORTED
  193771. void PNGAPI
  193772. png_set_cHRM(png_structp png_ptr, png_infop info_ptr,
  193773. double white_x, double white_y, double red_x, double red_y,
  193774. double green_x, double green_y, double blue_x, double blue_y)
  193775. {
  193776. png_debug1(1, "in %s storage function\n", "cHRM");
  193777. if (png_ptr == NULL || info_ptr == NULL)
  193778. return;
  193779. if (white_x < 0.0 || white_y < 0.0 ||
  193780. red_x < 0.0 || red_y < 0.0 ||
  193781. green_x < 0.0 || green_y < 0.0 ||
  193782. blue_x < 0.0 || blue_y < 0.0)
  193783. {
  193784. png_warning(png_ptr,
  193785. "Ignoring attempt to set negative chromaticity value");
  193786. return;
  193787. }
  193788. if (white_x > 21474.83 || white_y > 21474.83 ||
  193789. red_x > 21474.83 || red_y > 21474.83 ||
  193790. green_x > 21474.83 || green_y > 21474.83 ||
  193791. blue_x > 21474.83 || blue_y > 21474.83)
  193792. {
  193793. png_warning(png_ptr,
  193794. "Ignoring attempt to set chromaticity value exceeding 21474.83");
  193795. return;
  193796. }
  193797. info_ptr->x_white = (float)white_x;
  193798. info_ptr->y_white = (float)white_y;
  193799. info_ptr->x_red = (float)red_x;
  193800. info_ptr->y_red = (float)red_y;
  193801. info_ptr->x_green = (float)green_x;
  193802. info_ptr->y_green = (float)green_y;
  193803. info_ptr->x_blue = (float)blue_x;
  193804. info_ptr->y_blue = (float)blue_y;
  193805. #ifdef PNG_FIXED_POINT_SUPPORTED
  193806. info_ptr->int_x_white = (png_fixed_point)(white_x*100000.+0.5);
  193807. info_ptr->int_y_white = (png_fixed_point)(white_y*100000.+0.5);
  193808. info_ptr->int_x_red = (png_fixed_point)( red_x*100000.+0.5);
  193809. info_ptr->int_y_red = (png_fixed_point)( red_y*100000.+0.5);
  193810. info_ptr->int_x_green = (png_fixed_point)(green_x*100000.+0.5);
  193811. info_ptr->int_y_green = (png_fixed_point)(green_y*100000.+0.5);
  193812. info_ptr->int_x_blue = (png_fixed_point)( blue_x*100000.+0.5);
  193813. info_ptr->int_y_blue = (png_fixed_point)( blue_y*100000.+0.5);
  193814. #endif
  193815. info_ptr->valid |= PNG_INFO_cHRM;
  193816. }
  193817. #endif
  193818. #ifdef PNG_FIXED_POINT_SUPPORTED
  193819. void PNGAPI
  193820. png_set_cHRM_fixed(png_structp png_ptr, png_infop info_ptr,
  193821. png_fixed_point white_x, png_fixed_point white_y, png_fixed_point red_x,
  193822. png_fixed_point red_y, png_fixed_point green_x, png_fixed_point green_y,
  193823. png_fixed_point blue_x, png_fixed_point blue_y)
  193824. {
  193825. png_debug1(1, "in %s storage function\n", "cHRM");
  193826. if (png_ptr == NULL || info_ptr == NULL)
  193827. return;
  193828. if (white_x < 0 || white_y < 0 ||
  193829. red_x < 0 || red_y < 0 ||
  193830. green_x < 0 || green_y < 0 ||
  193831. blue_x < 0 || blue_y < 0)
  193832. {
  193833. png_warning(png_ptr,
  193834. "Ignoring attempt to set negative chromaticity value");
  193835. return;
  193836. }
  193837. #ifdef PNG_FLOATING_POINT_SUPPORTED
  193838. if (white_x > (double) PNG_UINT_31_MAX ||
  193839. white_y > (double) PNG_UINT_31_MAX ||
  193840. red_x > (double) PNG_UINT_31_MAX ||
  193841. red_y > (double) PNG_UINT_31_MAX ||
  193842. green_x > (double) PNG_UINT_31_MAX ||
  193843. green_y > (double) PNG_UINT_31_MAX ||
  193844. blue_x > (double) PNG_UINT_31_MAX ||
  193845. blue_y > (double) PNG_UINT_31_MAX)
  193846. #else
  193847. if (white_x > (png_fixed_point) PNG_UINT_31_MAX/100000L ||
  193848. white_y > (png_fixed_point) PNG_UINT_31_MAX/100000L ||
  193849. red_x > (png_fixed_point) PNG_UINT_31_MAX/100000L ||
  193850. red_y > (png_fixed_point) PNG_UINT_31_MAX/100000L ||
  193851. green_x > (png_fixed_point) PNG_UINT_31_MAX/100000L ||
  193852. green_y > (png_fixed_point) PNG_UINT_31_MAX/100000L ||
  193853. blue_x > (png_fixed_point) PNG_UINT_31_MAX/100000L ||
  193854. blue_y > (png_fixed_point) PNG_UINT_31_MAX/100000L)
  193855. #endif
  193856. {
  193857. png_warning(png_ptr,
  193858. "Ignoring attempt to set chromaticity value exceeding 21474.83");
  193859. return;
  193860. }
  193861. info_ptr->int_x_white = white_x;
  193862. info_ptr->int_y_white = white_y;
  193863. info_ptr->int_x_red = red_x;
  193864. info_ptr->int_y_red = red_y;
  193865. info_ptr->int_x_green = green_x;
  193866. info_ptr->int_y_green = green_y;
  193867. info_ptr->int_x_blue = blue_x;
  193868. info_ptr->int_y_blue = blue_y;
  193869. #ifdef PNG_FLOATING_POINT_SUPPORTED
  193870. info_ptr->x_white = (float)(white_x/100000.);
  193871. info_ptr->y_white = (float)(white_y/100000.);
  193872. info_ptr->x_red = (float)( red_x/100000.);
  193873. info_ptr->y_red = (float)( red_y/100000.);
  193874. info_ptr->x_green = (float)(green_x/100000.);
  193875. info_ptr->y_green = (float)(green_y/100000.);
  193876. info_ptr->x_blue = (float)( blue_x/100000.);
  193877. info_ptr->y_blue = (float)( blue_y/100000.);
  193878. #endif
  193879. info_ptr->valid |= PNG_INFO_cHRM;
  193880. }
  193881. #endif
  193882. #endif
  193883. #if defined(PNG_gAMA_SUPPORTED)
  193884. #ifdef PNG_FLOATING_POINT_SUPPORTED
  193885. void PNGAPI
  193886. png_set_gAMA(png_structp png_ptr, png_infop info_ptr, double file_gamma)
  193887. {
  193888. double gamma;
  193889. png_debug1(1, "in %s storage function\n", "gAMA");
  193890. if (png_ptr == NULL || info_ptr == NULL)
  193891. return;
  193892. /* Check for overflow */
  193893. if (file_gamma > 21474.83)
  193894. {
  193895. png_warning(png_ptr, "Limiting gamma to 21474.83");
  193896. gamma=21474.83;
  193897. }
  193898. else
  193899. gamma=file_gamma;
  193900. info_ptr->gamma = (float)gamma;
  193901. #ifdef PNG_FIXED_POINT_SUPPORTED
  193902. info_ptr->int_gamma = (int)(gamma*100000.+.5);
  193903. #endif
  193904. info_ptr->valid |= PNG_INFO_gAMA;
  193905. if(gamma == 0.0)
  193906. png_warning(png_ptr, "Setting gamma=0");
  193907. }
  193908. #endif
  193909. void PNGAPI
  193910. png_set_gAMA_fixed(png_structp png_ptr, png_infop info_ptr, png_fixed_point
  193911. int_gamma)
  193912. {
  193913. png_fixed_point gamma;
  193914. png_debug1(1, "in %s storage function\n", "gAMA");
  193915. if (png_ptr == NULL || info_ptr == NULL)
  193916. return;
  193917. if (int_gamma > (png_fixed_point) PNG_UINT_31_MAX)
  193918. {
  193919. png_warning(png_ptr, "Limiting gamma to 21474.83");
  193920. gamma=PNG_UINT_31_MAX;
  193921. }
  193922. else
  193923. {
  193924. if (int_gamma < 0)
  193925. {
  193926. png_warning(png_ptr, "Setting negative gamma to zero");
  193927. gamma=0;
  193928. }
  193929. else
  193930. gamma=int_gamma;
  193931. }
  193932. #ifdef PNG_FLOATING_POINT_SUPPORTED
  193933. info_ptr->gamma = (float)(gamma/100000.);
  193934. #endif
  193935. #ifdef PNG_FIXED_POINT_SUPPORTED
  193936. info_ptr->int_gamma = gamma;
  193937. #endif
  193938. info_ptr->valid |= PNG_INFO_gAMA;
  193939. if(gamma == 0)
  193940. png_warning(png_ptr, "Setting gamma=0");
  193941. }
  193942. #endif
  193943. #if defined(PNG_hIST_SUPPORTED)
  193944. void PNGAPI
  193945. png_set_hIST(png_structp png_ptr, png_infop info_ptr, png_uint_16p hist)
  193946. {
  193947. int i;
  193948. png_debug1(1, "in %s storage function\n", "hIST");
  193949. if (png_ptr == NULL || info_ptr == NULL)
  193950. return;
  193951. if (info_ptr->num_palette == 0 || info_ptr->num_palette
  193952. > PNG_MAX_PALETTE_LENGTH)
  193953. {
  193954. png_warning(png_ptr,
  193955. "Invalid palette size, hIST allocation skipped.");
  193956. return;
  193957. }
  193958. #ifdef PNG_FREE_ME_SUPPORTED
  193959. png_free_data(png_ptr, info_ptr, PNG_FREE_HIST, 0);
  193960. #endif
  193961. /* Changed from info->num_palette to PNG_MAX_PALETTE_LENGTH in version
  193962. 1.2.1 */
  193963. png_ptr->hist = (png_uint_16p)png_malloc_warn(png_ptr,
  193964. (png_uint_32)(PNG_MAX_PALETTE_LENGTH * png_sizeof (png_uint_16)));
  193965. if (png_ptr->hist == NULL)
  193966. {
  193967. png_warning(png_ptr, "Insufficient memory for hIST chunk data.");
  193968. return;
  193969. }
  193970. for (i = 0; i < info_ptr->num_palette; i++)
  193971. png_ptr->hist[i] = hist[i];
  193972. info_ptr->hist = png_ptr->hist;
  193973. info_ptr->valid |= PNG_INFO_hIST;
  193974. #ifdef PNG_FREE_ME_SUPPORTED
  193975. info_ptr->free_me |= PNG_FREE_HIST;
  193976. #else
  193977. png_ptr->flags |= PNG_FLAG_FREE_HIST;
  193978. #endif
  193979. }
  193980. #endif
  193981. void PNGAPI
  193982. png_set_IHDR(png_structp png_ptr, png_infop info_ptr,
  193983. png_uint_32 width, png_uint_32 height, int bit_depth,
  193984. int color_type, int interlace_type, int compression_type,
  193985. int filter_type)
  193986. {
  193987. png_debug1(1, "in %s storage function\n", "IHDR");
  193988. if (png_ptr == NULL || info_ptr == NULL)
  193989. return;
  193990. /* check for width and height valid values */
  193991. if (width == 0 || height == 0)
  193992. png_error(png_ptr, "Image width or height is zero in IHDR");
  193993. #ifdef PNG_SET_USER_LIMITS_SUPPORTED
  193994. if (width > png_ptr->user_width_max || height > png_ptr->user_height_max)
  193995. png_error(png_ptr, "image size exceeds user limits in IHDR");
  193996. #else
  193997. if (width > PNG_USER_WIDTH_MAX || height > PNG_USER_HEIGHT_MAX)
  193998. png_error(png_ptr, "image size exceeds user limits in IHDR");
  193999. #endif
  194000. if (width > PNG_UINT_31_MAX || height > PNG_UINT_31_MAX)
  194001. png_error(png_ptr, "Invalid image size in IHDR");
  194002. if ( width > (PNG_UINT_32_MAX
  194003. >> 3) /* 8-byte RGBA pixels */
  194004. - 64 /* bigrowbuf hack */
  194005. - 1 /* filter byte */
  194006. - 7*8 /* rounding of width to multiple of 8 pixels */
  194007. - 8) /* extra max_pixel_depth pad */
  194008. png_warning(png_ptr, "Width is too large for libpng to process pixels");
  194009. /* check other values */
  194010. if (bit_depth != 1 && bit_depth != 2 && bit_depth != 4 &&
  194011. bit_depth != 8 && bit_depth != 16)
  194012. png_error(png_ptr, "Invalid bit depth in IHDR");
  194013. if (color_type < 0 || color_type == 1 ||
  194014. color_type == 5 || color_type > 6)
  194015. png_error(png_ptr, "Invalid color type in IHDR");
  194016. if (((color_type == PNG_COLOR_TYPE_PALETTE) && bit_depth > 8) ||
  194017. ((color_type == PNG_COLOR_TYPE_RGB ||
  194018. color_type == PNG_COLOR_TYPE_GRAY_ALPHA ||
  194019. color_type == PNG_COLOR_TYPE_RGB_ALPHA) && bit_depth < 8))
  194020. png_error(png_ptr, "Invalid color type/bit depth combination in IHDR");
  194021. if (interlace_type >= PNG_INTERLACE_LAST)
  194022. png_error(png_ptr, "Unknown interlace method in IHDR");
  194023. if (compression_type != PNG_COMPRESSION_TYPE_BASE)
  194024. png_error(png_ptr, "Unknown compression method in IHDR");
  194025. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  194026. /* Accept filter_method 64 (intrapixel differencing) only if
  194027. * 1. Libpng was compiled with PNG_MNG_FEATURES_SUPPORTED and
  194028. * 2. Libpng did not read a PNG signature (this filter_method is only
  194029. * used in PNG datastreams that are embedded in MNG datastreams) and
  194030. * 3. The application called png_permit_mng_features with a mask that
  194031. * included PNG_FLAG_MNG_FILTER_64 and
  194032. * 4. The filter_method is 64 and
  194033. * 5. The color_type is RGB or RGBA
  194034. */
  194035. if((png_ptr->mode&PNG_HAVE_PNG_SIGNATURE)&&png_ptr->mng_features_permitted)
  194036. png_warning(png_ptr,"MNG features are not allowed in a PNG datastream");
  194037. if(filter_type != PNG_FILTER_TYPE_BASE)
  194038. {
  194039. if(!((png_ptr->mng_features_permitted & PNG_FLAG_MNG_FILTER_64) &&
  194040. (filter_type == PNG_INTRAPIXEL_DIFFERENCING) &&
  194041. ((png_ptr->mode&PNG_HAVE_PNG_SIGNATURE) == 0) &&
  194042. (color_type == PNG_COLOR_TYPE_RGB ||
  194043. color_type == PNG_COLOR_TYPE_RGB_ALPHA)))
  194044. png_error(png_ptr, "Unknown filter method in IHDR");
  194045. if(png_ptr->mode&PNG_HAVE_PNG_SIGNATURE)
  194046. png_warning(png_ptr, "Invalid filter method in IHDR");
  194047. }
  194048. #else
  194049. if(filter_type != PNG_FILTER_TYPE_BASE)
  194050. png_error(png_ptr, "Unknown filter method in IHDR");
  194051. #endif
  194052. info_ptr->width = width;
  194053. info_ptr->height = height;
  194054. info_ptr->bit_depth = (png_byte)bit_depth;
  194055. info_ptr->color_type =(png_byte) color_type;
  194056. info_ptr->compression_type = (png_byte)compression_type;
  194057. info_ptr->filter_type = (png_byte)filter_type;
  194058. info_ptr->interlace_type = (png_byte)interlace_type;
  194059. if (info_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  194060. info_ptr->channels = 1;
  194061. else if (info_ptr->color_type & PNG_COLOR_MASK_COLOR)
  194062. info_ptr->channels = 3;
  194063. else
  194064. info_ptr->channels = 1;
  194065. if (info_ptr->color_type & PNG_COLOR_MASK_ALPHA)
  194066. info_ptr->channels++;
  194067. info_ptr->pixel_depth = (png_byte)(info_ptr->channels * info_ptr->bit_depth);
  194068. /* check for potential overflow */
  194069. if (width > (PNG_UINT_32_MAX
  194070. >> 3) /* 8-byte RGBA pixels */
  194071. - 64 /* bigrowbuf hack */
  194072. - 1 /* filter byte */
  194073. - 7*8 /* rounding of width to multiple of 8 pixels */
  194074. - 8) /* extra max_pixel_depth pad */
  194075. info_ptr->rowbytes = (png_size_t)0;
  194076. else
  194077. info_ptr->rowbytes = PNG_ROWBYTES(info_ptr->pixel_depth,width);
  194078. }
  194079. #if defined(PNG_oFFs_SUPPORTED)
  194080. void PNGAPI
  194081. png_set_oFFs(png_structp png_ptr, png_infop info_ptr,
  194082. png_int_32 offset_x, png_int_32 offset_y, int unit_type)
  194083. {
  194084. png_debug1(1, "in %s storage function\n", "oFFs");
  194085. if (png_ptr == NULL || info_ptr == NULL)
  194086. return;
  194087. info_ptr->x_offset = offset_x;
  194088. info_ptr->y_offset = offset_y;
  194089. info_ptr->offset_unit_type = (png_byte)unit_type;
  194090. info_ptr->valid |= PNG_INFO_oFFs;
  194091. }
  194092. #endif
  194093. #if defined(PNG_pCAL_SUPPORTED)
  194094. void PNGAPI
  194095. png_set_pCAL(png_structp png_ptr, png_infop info_ptr,
  194096. png_charp purpose, png_int_32 X0, png_int_32 X1, int type, int nparams,
  194097. png_charp units, png_charpp params)
  194098. {
  194099. png_uint_32 length;
  194100. int i;
  194101. png_debug1(1, "in %s storage function\n", "pCAL");
  194102. if (png_ptr == NULL || info_ptr == NULL)
  194103. return;
  194104. length = png_strlen(purpose) + 1;
  194105. png_debug1(3, "allocating purpose for info (%lu bytes)\n", length);
  194106. info_ptr->pcal_purpose = (png_charp)png_malloc_warn(png_ptr, length);
  194107. if (info_ptr->pcal_purpose == NULL)
  194108. {
  194109. png_warning(png_ptr, "Insufficient memory for pCAL purpose.");
  194110. return;
  194111. }
  194112. png_memcpy(info_ptr->pcal_purpose, purpose, (png_size_t)length);
  194113. png_debug(3, "storing X0, X1, type, and nparams in info\n");
  194114. info_ptr->pcal_X0 = X0;
  194115. info_ptr->pcal_X1 = X1;
  194116. info_ptr->pcal_type = (png_byte)type;
  194117. info_ptr->pcal_nparams = (png_byte)nparams;
  194118. length = png_strlen(units) + 1;
  194119. png_debug1(3, "allocating units for info (%lu bytes)\n", length);
  194120. info_ptr->pcal_units = (png_charp)png_malloc_warn(png_ptr, length);
  194121. if (info_ptr->pcal_units == NULL)
  194122. {
  194123. png_warning(png_ptr, "Insufficient memory for pCAL units.");
  194124. return;
  194125. }
  194126. png_memcpy(info_ptr->pcal_units, units, (png_size_t)length);
  194127. info_ptr->pcal_params = (png_charpp)png_malloc_warn(png_ptr,
  194128. (png_uint_32)((nparams + 1) * png_sizeof(png_charp)));
  194129. if (info_ptr->pcal_params == NULL)
  194130. {
  194131. png_warning(png_ptr, "Insufficient memory for pCAL params.");
  194132. return;
  194133. }
  194134. info_ptr->pcal_params[nparams] = NULL;
  194135. for (i = 0; i < nparams; i++)
  194136. {
  194137. length = png_strlen(params[i]) + 1;
  194138. png_debug2(3, "allocating parameter %d for info (%lu bytes)\n", i, length);
  194139. info_ptr->pcal_params[i] = (png_charp)png_malloc_warn(png_ptr, length);
  194140. if (info_ptr->pcal_params[i] == NULL)
  194141. {
  194142. png_warning(png_ptr, "Insufficient memory for pCAL parameter.");
  194143. return;
  194144. }
  194145. png_memcpy(info_ptr->pcal_params[i], params[i], (png_size_t)length);
  194146. }
  194147. info_ptr->valid |= PNG_INFO_pCAL;
  194148. #ifdef PNG_FREE_ME_SUPPORTED
  194149. info_ptr->free_me |= PNG_FREE_PCAL;
  194150. #endif
  194151. }
  194152. #endif
  194153. #if defined(PNG_READ_sCAL_SUPPORTED) || defined(PNG_WRITE_sCAL_SUPPORTED)
  194154. #ifdef PNG_FLOATING_POINT_SUPPORTED
  194155. void PNGAPI
  194156. png_set_sCAL(png_structp png_ptr, png_infop info_ptr,
  194157. int unit, double width, double height)
  194158. {
  194159. png_debug1(1, "in %s storage function\n", "sCAL");
  194160. if (png_ptr == NULL || info_ptr == NULL)
  194161. return;
  194162. info_ptr->scal_unit = (png_byte)unit;
  194163. info_ptr->scal_pixel_width = width;
  194164. info_ptr->scal_pixel_height = height;
  194165. info_ptr->valid |= PNG_INFO_sCAL;
  194166. }
  194167. #else
  194168. #ifdef PNG_FIXED_POINT_SUPPORTED
  194169. void PNGAPI
  194170. png_set_sCAL_s(png_structp png_ptr, png_infop info_ptr,
  194171. int unit, png_charp swidth, png_charp sheight)
  194172. {
  194173. png_uint_32 length;
  194174. png_debug1(1, "in %s storage function\n", "sCAL");
  194175. if (png_ptr == NULL || info_ptr == NULL)
  194176. return;
  194177. info_ptr->scal_unit = (png_byte)unit;
  194178. length = png_strlen(swidth) + 1;
  194179. png_debug1(3, "allocating unit for info (%d bytes)\n", length);
  194180. info_ptr->scal_s_width = (png_charp)png_malloc_warn(png_ptr, length);
  194181. if (info_ptr->scal_s_width == NULL)
  194182. {
  194183. png_warning(png_ptr,
  194184. "Memory allocation failed while processing sCAL.");
  194185. }
  194186. png_memcpy(info_ptr->scal_s_width, swidth, (png_size_t)length);
  194187. length = png_strlen(sheight) + 1;
  194188. png_debug1(3, "allocating unit for info (%d bytes)\n", length);
  194189. info_ptr->scal_s_height = (png_charp)png_malloc_warn(png_ptr, length);
  194190. if (info_ptr->scal_s_height == NULL)
  194191. {
  194192. png_free (png_ptr, info_ptr->scal_s_width);
  194193. png_warning(png_ptr,
  194194. "Memory allocation failed while processing sCAL.");
  194195. }
  194196. png_memcpy(info_ptr->scal_s_height, sheight, (png_size_t)length);
  194197. info_ptr->valid |= PNG_INFO_sCAL;
  194198. #ifdef PNG_FREE_ME_SUPPORTED
  194199. info_ptr->free_me |= PNG_FREE_SCAL;
  194200. #endif
  194201. }
  194202. #endif
  194203. #endif
  194204. #endif
  194205. #if defined(PNG_pHYs_SUPPORTED)
  194206. void PNGAPI
  194207. png_set_pHYs(png_structp png_ptr, png_infop info_ptr,
  194208. png_uint_32 res_x, png_uint_32 res_y, int unit_type)
  194209. {
  194210. png_debug1(1, "in %s storage function\n", "pHYs");
  194211. if (png_ptr == NULL || info_ptr == NULL)
  194212. return;
  194213. info_ptr->x_pixels_per_unit = res_x;
  194214. info_ptr->y_pixels_per_unit = res_y;
  194215. info_ptr->phys_unit_type = (png_byte)unit_type;
  194216. info_ptr->valid |= PNG_INFO_pHYs;
  194217. }
  194218. #endif
  194219. void PNGAPI
  194220. png_set_PLTE(png_structp png_ptr, png_infop info_ptr,
  194221. png_colorp palette, int num_palette)
  194222. {
  194223. png_debug1(1, "in %s storage function\n", "PLTE");
  194224. if (png_ptr == NULL || info_ptr == NULL)
  194225. return;
  194226. if (num_palette < 0 || num_palette > PNG_MAX_PALETTE_LENGTH)
  194227. {
  194228. if (info_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  194229. png_error(png_ptr, "Invalid palette length");
  194230. else
  194231. {
  194232. png_warning(png_ptr, "Invalid palette length");
  194233. return;
  194234. }
  194235. }
  194236. /*
  194237. * It may not actually be necessary to set png_ptr->palette here;
  194238. * we do it for backward compatibility with the way the png_handle_tRNS
  194239. * function used to do the allocation.
  194240. */
  194241. #ifdef PNG_FREE_ME_SUPPORTED
  194242. png_free_data(png_ptr, info_ptr, PNG_FREE_PLTE, 0);
  194243. #endif
  194244. /* Changed in libpng-1.2.1 to allocate PNG_MAX_PALETTE_LENGTH instead
  194245. of num_palette entries,
  194246. in case of an invalid PNG file that has too-large sample values. */
  194247. png_ptr->palette = (png_colorp)png_malloc(png_ptr,
  194248. PNG_MAX_PALETTE_LENGTH * png_sizeof(png_color));
  194249. png_memset(png_ptr->palette, 0, PNG_MAX_PALETTE_LENGTH *
  194250. png_sizeof(png_color));
  194251. png_memcpy(png_ptr->palette, palette, num_palette * png_sizeof (png_color));
  194252. info_ptr->palette = png_ptr->palette;
  194253. info_ptr->num_palette = png_ptr->num_palette = (png_uint_16)num_palette;
  194254. #ifdef PNG_FREE_ME_SUPPORTED
  194255. info_ptr->free_me |= PNG_FREE_PLTE;
  194256. #else
  194257. png_ptr->flags |= PNG_FLAG_FREE_PLTE;
  194258. #endif
  194259. info_ptr->valid |= PNG_INFO_PLTE;
  194260. }
  194261. #if defined(PNG_sBIT_SUPPORTED)
  194262. void PNGAPI
  194263. png_set_sBIT(png_structp png_ptr, png_infop info_ptr,
  194264. png_color_8p sig_bit)
  194265. {
  194266. png_debug1(1, "in %s storage function\n", "sBIT");
  194267. if (png_ptr == NULL || info_ptr == NULL)
  194268. return;
  194269. png_memcpy(&(info_ptr->sig_bit), sig_bit, png_sizeof (png_color_8));
  194270. info_ptr->valid |= PNG_INFO_sBIT;
  194271. }
  194272. #endif
  194273. #if defined(PNG_sRGB_SUPPORTED)
  194274. void PNGAPI
  194275. png_set_sRGB(png_structp png_ptr, png_infop info_ptr, int intent)
  194276. {
  194277. png_debug1(1, "in %s storage function\n", "sRGB");
  194278. if (png_ptr == NULL || info_ptr == NULL)
  194279. return;
  194280. info_ptr->srgb_intent = (png_byte)intent;
  194281. info_ptr->valid |= PNG_INFO_sRGB;
  194282. }
  194283. void PNGAPI
  194284. png_set_sRGB_gAMA_and_cHRM(png_structp png_ptr, png_infop info_ptr,
  194285. int intent)
  194286. {
  194287. #if defined(PNG_gAMA_SUPPORTED)
  194288. #ifdef PNG_FLOATING_POINT_SUPPORTED
  194289. float file_gamma;
  194290. #endif
  194291. #ifdef PNG_FIXED_POINT_SUPPORTED
  194292. png_fixed_point int_file_gamma;
  194293. #endif
  194294. #endif
  194295. #if defined(PNG_cHRM_SUPPORTED)
  194296. #ifdef PNG_FLOATING_POINT_SUPPORTED
  194297. float white_x, white_y, red_x, red_y, green_x, green_y, blue_x, blue_y;
  194298. #endif
  194299. #ifdef PNG_FIXED_POINT_SUPPORTED
  194300. png_fixed_point int_white_x, int_white_y, int_red_x, int_red_y, int_green_x,
  194301. int_green_y, int_blue_x, int_blue_y;
  194302. #endif
  194303. #endif
  194304. png_debug1(1, "in %s storage function\n", "sRGB_gAMA_and_cHRM");
  194305. if (png_ptr == NULL || info_ptr == NULL)
  194306. return;
  194307. png_set_sRGB(png_ptr, info_ptr, intent);
  194308. #if defined(PNG_gAMA_SUPPORTED)
  194309. #ifdef PNG_FLOATING_POINT_SUPPORTED
  194310. file_gamma = (float).45455;
  194311. png_set_gAMA(png_ptr, info_ptr, file_gamma);
  194312. #endif
  194313. #ifdef PNG_FIXED_POINT_SUPPORTED
  194314. int_file_gamma = 45455L;
  194315. png_set_gAMA_fixed(png_ptr, info_ptr, int_file_gamma);
  194316. #endif
  194317. #endif
  194318. #if defined(PNG_cHRM_SUPPORTED)
  194319. #ifdef PNG_FIXED_POINT_SUPPORTED
  194320. int_white_x = 31270L;
  194321. int_white_y = 32900L;
  194322. int_red_x = 64000L;
  194323. int_red_y = 33000L;
  194324. int_green_x = 30000L;
  194325. int_green_y = 60000L;
  194326. int_blue_x = 15000L;
  194327. int_blue_y = 6000L;
  194328. png_set_cHRM_fixed(png_ptr, info_ptr,
  194329. int_white_x, int_white_y, int_red_x, int_red_y, int_green_x, int_green_y,
  194330. int_blue_x, int_blue_y);
  194331. #endif
  194332. #ifdef PNG_FLOATING_POINT_SUPPORTED
  194333. white_x = (float).3127;
  194334. white_y = (float).3290;
  194335. red_x = (float).64;
  194336. red_y = (float).33;
  194337. green_x = (float).30;
  194338. green_y = (float).60;
  194339. blue_x = (float).15;
  194340. blue_y = (float).06;
  194341. png_set_cHRM(png_ptr, info_ptr,
  194342. white_x, white_y, red_x, red_y, green_x, green_y, blue_x, blue_y);
  194343. #endif
  194344. #endif
  194345. }
  194346. #endif
  194347. #if defined(PNG_iCCP_SUPPORTED)
  194348. void PNGAPI
  194349. png_set_iCCP(png_structp png_ptr, png_infop info_ptr,
  194350. png_charp name, int compression_type,
  194351. png_charp profile, png_uint_32 proflen)
  194352. {
  194353. png_charp new_iccp_name;
  194354. png_charp new_iccp_profile;
  194355. png_debug1(1, "in %s storage function\n", "iCCP");
  194356. if (png_ptr == NULL || info_ptr == NULL || name == NULL || profile == NULL)
  194357. return;
  194358. new_iccp_name = (png_charp)png_malloc_warn(png_ptr, png_strlen(name)+1);
  194359. if (new_iccp_name == NULL)
  194360. {
  194361. png_warning(png_ptr, "Insufficient memory to process iCCP chunk.");
  194362. return;
  194363. }
  194364. png_strncpy(new_iccp_name, name, png_strlen(name)+1);
  194365. new_iccp_profile = (png_charp)png_malloc_warn(png_ptr, proflen);
  194366. if (new_iccp_profile == NULL)
  194367. {
  194368. png_free (png_ptr, new_iccp_name);
  194369. png_warning(png_ptr, "Insufficient memory to process iCCP profile.");
  194370. return;
  194371. }
  194372. png_memcpy(new_iccp_profile, profile, (png_size_t)proflen);
  194373. png_free_data(png_ptr, info_ptr, PNG_FREE_ICCP, 0);
  194374. info_ptr->iccp_proflen = proflen;
  194375. info_ptr->iccp_name = new_iccp_name;
  194376. info_ptr->iccp_profile = new_iccp_profile;
  194377. /* Compression is always zero but is here so the API and info structure
  194378. * does not have to change if we introduce multiple compression types */
  194379. info_ptr->iccp_compression = (png_byte)compression_type;
  194380. #ifdef PNG_FREE_ME_SUPPORTED
  194381. info_ptr->free_me |= PNG_FREE_ICCP;
  194382. #endif
  194383. info_ptr->valid |= PNG_INFO_iCCP;
  194384. }
  194385. #endif
  194386. #if defined(PNG_TEXT_SUPPORTED)
  194387. void PNGAPI
  194388. png_set_text(png_structp png_ptr, png_infop info_ptr, png_textp text_ptr,
  194389. int num_text)
  194390. {
  194391. int ret;
  194392. ret=png_set_text_2(png_ptr, info_ptr, text_ptr, num_text);
  194393. if (ret)
  194394. png_error(png_ptr, "Insufficient memory to store text");
  194395. }
  194396. int /* PRIVATE */
  194397. png_set_text_2(png_structp png_ptr, png_infop info_ptr, png_textp text_ptr,
  194398. int num_text)
  194399. {
  194400. int i;
  194401. png_debug1(1, "in %s storage function\n", (png_ptr->chunk_name[0] == '\0' ?
  194402. "text" : (png_const_charp)png_ptr->chunk_name));
  194403. if (png_ptr == NULL || info_ptr == NULL || num_text == 0)
  194404. return(0);
  194405. /* Make sure we have enough space in the "text" array in info_struct
  194406. * to hold all of the incoming text_ptr objects.
  194407. */
  194408. if (info_ptr->num_text + num_text > info_ptr->max_text)
  194409. {
  194410. if (info_ptr->text != NULL)
  194411. {
  194412. png_textp old_text;
  194413. int old_max;
  194414. old_max = info_ptr->max_text;
  194415. info_ptr->max_text = info_ptr->num_text + num_text + 8;
  194416. old_text = info_ptr->text;
  194417. info_ptr->text = (png_textp)png_malloc_warn(png_ptr,
  194418. (png_uint_32)(info_ptr->max_text * png_sizeof (png_text)));
  194419. if (info_ptr->text == NULL)
  194420. {
  194421. png_free(png_ptr, old_text);
  194422. return(1);
  194423. }
  194424. png_memcpy(info_ptr->text, old_text, (png_size_t)(old_max *
  194425. png_sizeof(png_text)));
  194426. png_free(png_ptr, old_text);
  194427. }
  194428. else
  194429. {
  194430. info_ptr->max_text = num_text + 8;
  194431. info_ptr->num_text = 0;
  194432. info_ptr->text = (png_textp)png_malloc_warn(png_ptr,
  194433. (png_uint_32)(info_ptr->max_text * png_sizeof (png_text)));
  194434. if (info_ptr->text == NULL)
  194435. return(1);
  194436. #ifdef PNG_FREE_ME_SUPPORTED
  194437. info_ptr->free_me |= PNG_FREE_TEXT;
  194438. #endif
  194439. }
  194440. png_debug1(3, "allocated %d entries for info_ptr->text\n",
  194441. info_ptr->max_text);
  194442. }
  194443. for (i = 0; i < num_text; i++)
  194444. {
  194445. png_size_t text_length,key_len;
  194446. png_size_t lang_len,lang_key_len;
  194447. png_textp textp = &(info_ptr->text[info_ptr->num_text]);
  194448. if (text_ptr[i].key == NULL)
  194449. continue;
  194450. key_len = png_strlen(text_ptr[i].key);
  194451. if(text_ptr[i].compression <= 0)
  194452. {
  194453. lang_len = 0;
  194454. lang_key_len = 0;
  194455. }
  194456. else
  194457. #ifdef PNG_iTXt_SUPPORTED
  194458. {
  194459. /* set iTXt data */
  194460. if (text_ptr[i].lang != NULL)
  194461. lang_len = png_strlen(text_ptr[i].lang);
  194462. else
  194463. lang_len = 0;
  194464. if (text_ptr[i].lang_key != NULL)
  194465. lang_key_len = png_strlen(text_ptr[i].lang_key);
  194466. else
  194467. lang_key_len = 0;
  194468. }
  194469. #else
  194470. {
  194471. png_warning(png_ptr, "iTXt chunk not supported.");
  194472. continue;
  194473. }
  194474. #endif
  194475. if (text_ptr[i].text == NULL || text_ptr[i].text[0] == '\0')
  194476. {
  194477. text_length = 0;
  194478. #ifdef PNG_iTXt_SUPPORTED
  194479. if(text_ptr[i].compression > 0)
  194480. textp->compression = PNG_ITXT_COMPRESSION_NONE;
  194481. else
  194482. #endif
  194483. textp->compression = PNG_TEXT_COMPRESSION_NONE;
  194484. }
  194485. else
  194486. {
  194487. text_length = png_strlen(text_ptr[i].text);
  194488. textp->compression = text_ptr[i].compression;
  194489. }
  194490. textp->key = (png_charp)png_malloc_warn(png_ptr,
  194491. (png_uint_32)(key_len + text_length + lang_len + lang_key_len + 4));
  194492. if (textp->key == NULL)
  194493. return(1);
  194494. png_debug2(2, "Allocated %lu bytes at %x in png_set_text\n",
  194495. (png_uint_32)(key_len + lang_len + lang_key_len + text_length + 4),
  194496. (int)textp->key);
  194497. png_memcpy(textp->key, text_ptr[i].key,
  194498. (png_size_t)(key_len));
  194499. *(textp->key+key_len) = '\0';
  194500. #ifdef PNG_iTXt_SUPPORTED
  194501. if (text_ptr[i].compression > 0)
  194502. {
  194503. textp->lang=textp->key + key_len + 1;
  194504. png_memcpy(textp->lang, text_ptr[i].lang, lang_len);
  194505. *(textp->lang+lang_len) = '\0';
  194506. textp->lang_key=textp->lang + lang_len + 1;
  194507. png_memcpy(textp->lang_key, text_ptr[i].lang_key, lang_key_len);
  194508. *(textp->lang_key+lang_key_len) = '\0';
  194509. textp->text=textp->lang_key + lang_key_len + 1;
  194510. }
  194511. else
  194512. #endif
  194513. {
  194514. #ifdef PNG_iTXt_SUPPORTED
  194515. textp->lang=NULL;
  194516. textp->lang_key=NULL;
  194517. #endif
  194518. textp->text=textp->key + key_len + 1;
  194519. }
  194520. if(text_length)
  194521. png_memcpy(textp->text, text_ptr[i].text,
  194522. (png_size_t)(text_length));
  194523. *(textp->text+text_length) = '\0';
  194524. #ifdef PNG_iTXt_SUPPORTED
  194525. if(textp->compression > 0)
  194526. {
  194527. textp->text_length = 0;
  194528. textp->itxt_length = text_length;
  194529. }
  194530. else
  194531. #endif
  194532. {
  194533. textp->text_length = text_length;
  194534. #ifdef PNG_iTXt_SUPPORTED
  194535. textp->itxt_length = 0;
  194536. #endif
  194537. }
  194538. info_ptr->num_text++;
  194539. png_debug1(3, "transferred text chunk %d\n", info_ptr->num_text);
  194540. }
  194541. return(0);
  194542. }
  194543. #endif
  194544. #if defined(PNG_tIME_SUPPORTED)
  194545. void PNGAPI
  194546. png_set_tIME(png_structp png_ptr, png_infop info_ptr, png_timep mod_time)
  194547. {
  194548. png_debug1(1, "in %s storage function\n", "tIME");
  194549. if (png_ptr == NULL || info_ptr == NULL ||
  194550. (png_ptr->mode & PNG_WROTE_tIME))
  194551. return;
  194552. png_memcpy(&(info_ptr->mod_time), mod_time, png_sizeof (png_time));
  194553. info_ptr->valid |= PNG_INFO_tIME;
  194554. }
  194555. #endif
  194556. #if defined(PNG_tRNS_SUPPORTED)
  194557. void PNGAPI
  194558. png_set_tRNS(png_structp png_ptr, png_infop info_ptr,
  194559. png_bytep trans, int num_trans, png_color_16p trans_values)
  194560. {
  194561. png_debug1(1, "in %s storage function\n", "tRNS");
  194562. if (png_ptr == NULL || info_ptr == NULL)
  194563. return;
  194564. if (trans != NULL)
  194565. {
  194566. /*
  194567. * It may not actually be necessary to set png_ptr->trans here;
  194568. * we do it for backward compatibility with the way the png_handle_tRNS
  194569. * function used to do the allocation.
  194570. */
  194571. #ifdef PNG_FREE_ME_SUPPORTED
  194572. png_free_data(png_ptr, info_ptr, PNG_FREE_TRNS, 0);
  194573. #endif
  194574. /* Changed from num_trans to PNG_MAX_PALETTE_LENGTH in version 1.2.1 */
  194575. png_ptr->trans = info_ptr->trans = (png_bytep)png_malloc(png_ptr,
  194576. (png_uint_32)PNG_MAX_PALETTE_LENGTH);
  194577. if (num_trans <= PNG_MAX_PALETTE_LENGTH)
  194578. png_memcpy(info_ptr->trans, trans, (png_size_t)num_trans);
  194579. #ifdef PNG_FREE_ME_SUPPORTED
  194580. info_ptr->free_me |= PNG_FREE_TRNS;
  194581. #else
  194582. png_ptr->flags |= PNG_FLAG_FREE_TRNS;
  194583. #endif
  194584. }
  194585. if (trans_values != NULL)
  194586. {
  194587. png_memcpy(&(info_ptr->trans_values), trans_values,
  194588. png_sizeof(png_color_16));
  194589. if (num_trans == 0)
  194590. num_trans = 1;
  194591. }
  194592. info_ptr->num_trans = (png_uint_16)num_trans;
  194593. info_ptr->valid |= PNG_INFO_tRNS;
  194594. }
  194595. #endif
  194596. #if defined(PNG_sPLT_SUPPORTED)
  194597. void PNGAPI
  194598. png_set_sPLT(png_structp png_ptr,
  194599. png_infop info_ptr, png_sPLT_tp entries, int nentries)
  194600. {
  194601. png_sPLT_tp np;
  194602. int i;
  194603. if (png_ptr == NULL || info_ptr == NULL)
  194604. return;
  194605. np = (png_sPLT_tp)png_malloc_warn(png_ptr,
  194606. (info_ptr->splt_palettes_num + nentries) * png_sizeof(png_sPLT_t));
  194607. if (np == NULL)
  194608. {
  194609. png_warning(png_ptr, "No memory for sPLT palettes.");
  194610. return;
  194611. }
  194612. png_memcpy(np, info_ptr->splt_palettes,
  194613. info_ptr->splt_palettes_num * png_sizeof(png_sPLT_t));
  194614. png_free(png_ptr, info_ptr->splt_palettes);
  194615. info_ptr->splt_palettes=NULL;
  194616. for (i = 0; i < nentries; i++)
  194617. {
  194618. png_sPLT_tp to = np + info_ptr->splt_palettes_num + i;
  194619. png_sPLT_tp from = entries + i;
  194620. to->name = (png_charp)png_malloc_warn(png_ptr,
  194621. png_strlen(from->name) + 1);
  194622. if (to->name == NULL)
  194623. {
  194624. png_warning(png_ptr,
  194625. "Out of memory while processing sPLT chunk");
  194626. }
  194627. /* TODO: use png_malloc_warn */
  194628. png_strncpy(to->name, from->name, png_strlen(from->name)+1);
  194629. to->entries = (png_sPLT_entryp)png_malloc_warn(png_ptr,
  194630. from->nentries * png_sizeof(png_sPLT_entry));
  194631. /* TODO: use png_malloc_warn */
  194632. png_memcpy(to->entries, from->entries,
  194633. from->nentries * png_sizeof(png_sPLT_entry));
  194634. if (to->entries == NULL)
  194635. {
  194636. png_warning(png_ptr,
  194637. "Out of memory while processing sPLT chunk");
  194638. png_free(png_ptr,to->name);
  194639. to->name = NULL;
  194640. }
  194641. to->nentries = from->nentries;
  194642. to->depth = from->depth;
  194643. }
  194644. info_ptr->splt_palettes = np;
  194645. info_ptr->splt_palettes_num += nentries;
  194646. info_ptr->valid |= PNG_INFO_sPLT;
  194647. #ifdef PNG_FREE_ME_SUPPORTED
  194648. info_ptr->free_me |= PNG_FREE_SPLT;
  194649. #endif
  194650. }
  194651. #endif /* PNG_sPLT_SUPPORTED */
  194652. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  194653. void PNGAPI
  194654. png_set_unknown_chunks(png_structp png_ptr,
  194655. png_infop info_ptr, png_unknown_chunkp unknowns, int num_unknowns)
  194656. {
  194657. png_unknown_chunkp np;
  194658. int i;
  194659. if (png_ptr == NULL || info_ptr == NULL || num_unknowns == 0)
  194660. return;
  194661. np = (png_unknown_chunkp)png_malloc_warn(png_ptr,
  194662. (info_ptr->unknown_chunks_num + num_unknowns) *
  194663. png_sizeof(png_unknown_chunk));
  194664. if (np == NULL)
  194665. {
  194666. png_warning(png_ptr,
  194667. "Out of memory while processing unknown chunk.");
  194668. return;
  194669. }
  194670. png_memcpy(np, info_ptr->unknown_chunks,
  194671. info_ptr->unknown_chunks_num * png_sizeof(png_unknown_chunk));
  194672. png_free(png_ptr, info_ptr->unknown_chunks);
  194673. info_ptr->unknown_chunks=NULL;
  194674. for (i = 0; i < num_unknowns; i++)
  194675. {
  194676. png_unknown_chunkp to = np + info_ptr->unknown_chunks_num + i;
  194677. png_unknown_chunkp from = unknowns + i;
  194678. png_strncpy((png_charp)to->name, (png_charp)from->name, 5);
  194679. to->data = (png_bytep)png_malloc_warn(png_ptr, from->size);
  194680. if (to->data == NULL)
  194681. {
  194682. png_warning(png_ptr,
  194683. "Out of memory while processing unknown chunk.");
  194684. }
  194685. else
  194686. {
  194687. png_memcpy(to->data, from->data, from->size);
  194688. to->size = from->size;
  194689. /* note our location in the read or write sequence */
  194690. to->location = (png_byte)(png_ptr->mode & 0xff);
  194691. }
  194692. }
  194693. info_ptr->unknown_chunks = np;
  194694. info_ptr->unknown_chunks_num += num_unknowns;
  194695. #ifdef PNG_FREE_ME_SUPPORTED
  194696. info_ptr->free_me |= PNG_FREE_UNKN;
  194697. #endif
  194698. }
  194699. void PNGAPI
  194700. png_set_unknown_chunk_location(png_structp png_ptr, png_infop info_ptr,
  194701. int chunk, int location)
  194702. {
  194703. if(png_ptr != NULL && info_ptr != NULL && chunk >= 0 && chunk <
  194704. (int)info_ptr->unknown_chunks_num)
  194705. info_ptr->unknown_chunks[chunk].location = (png_byte)location;
  194706. }
  194707. #endif
  194708. #if defined(PNG_1_0_X) || defined(PNG_1_2_X)
  194709. #if defined(PNG_READ_EMPTY_PLTE_SUPPORTED) || \
  194710. defined(PNG_WRITE_EMPTY_PLTE_SUPPORTED)
  194711. void PNGAPI
  194712. png_permit_empty_plte (png_structp png_ptr, int empty_plte_permitted)
  194713. {
  194714. /* This function is deprecated in favor of png_permit_mng_features()
  194715. and will be removed from libpng-1.3.0 */
  194716. png_debug(1, "in png_permit_empty_plte, DEPRECATED.\n");
  194717. if (png_ptr == NULL)
  194718. return;
  194719. png_ptr->mng_features_permitted = (png_byte)
  194720. ((png_ptr->mng_features_permitted & (~(PNG_FLAG_MNG_EMPTY_PLTE))) |
  194721. ((empty_plte_permitted & PNG_FLAG_MNG_EMPTY_PLTE)));
  194722. }
  194723. #endif
  194724. #endif
  194725. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  194726. png_uint_32 PNGAPI
  194727. png_permit_mng_features (png_structp png_ptr, png_uint_32 mng_features)
  194728. {
  194729. png_debug(1, "in png_permit_mng_features\n");
  194730. if (png_ptr == NULL)
  194731. return (png_uint_32)0;
  194732. png_ptr->mng_features_permitted =
  194733. (png_byte)(mng_features & PNG_ALL_MNG_FEATURES);
  194734. return (png_uint_32)png_ptr->mng_features_permitted;
  194735. }
  194736. #endif
  194737. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  194738. void PNGAPI
  194739. png_set_keep_unknown_chunks(png_structp png_ptr, int keep, png_bytep
  194740. chunk_list, int num_chunks)
  194741. {
  194742. png_bytep new_list, p;
  194743. int i, old_num_chunks;
  194744. if (png_ptr == NULL)
  194745. return;
  194746. if (num_chunks == 0)
  194747. {
  194748. if(keep == PNG_HANDLE_CHUNK_ALWAYS || keep == PNG_HANDLE_CHUNK_IF_SAFE)
  194749. png_ptr->flags |= PNG_FLAG_KEEP_UNKNOWN_CHUNKS;
  194750. else
  194751. png_ptr->flags &= ~PNG_FLAG_KEEP_UNKNOWN_CHUNKS;
  194752. if(keep == PNG_HANDLE_CHUNK_ALWAYS)
  194753. png_ptr->flags |= PNG_FLAG_KEEP_UNSAFE_CHUNKS;
  194754. else
  194755. png_ptr->flags &= ~PNG_FLAG_KEEP_UNSAFE_CHUNKS;
  194756. return;
  194757. }
  194758. if (chunk_list == NULL)
  194759. return;
  194760. old_num_chunks=png_ptr->num_chunk_list;
  194761. new_list=(png_bytep)png_malloc(png_ptr,
  194762. (png_uint_32)(5*(num_chunks+old_num_chunks)));
  194763. if(png_ptr->chunk_list != NULL)
  194764. {
  194765. png_memcpy(new_list, png_ptr->chunk_list,
  194766. (png_size_t)(5*old_num_chunks));
  194767. png_free(png_ptr, png_ptr->chunk_list);
  194768. png_ptr->chunk_list=NULL;
  194769. }
  194770. png_memcpy(new_list+5*old_num_chunks, chunk_list,
  194771. (png_size_t)(5*num_chunks));
  194772. for (p=new_list+5*old_num_chunks+4, i=0; i<num_chunks; i++, p+=5)
  194773. *p=(png_byte)keep;
  194774. png_ptr->num_chunk_list=old_num_chunks+num_chunks;
  194775. png_ptr->chunk_list=new_list;
  194776. #ifdef PNG_FREE_ME_SUPPORTED
  194777. png_ptr->free_me |= PNG_FREE_LIST;
  194778. #endif
  194779. }
  194780. #endif
  194781. #if defined(PNG_READ_USER_CHUNKS_SUPPORTED)
  194782. void PNGAPI
  194783. png_set_read_user_chunk_fn(png_structp png_ptr, png_voidp user_chunk_ptr,
  194784. png_user_chunk_ptr read_user_chunk_fn)
  194785. {
  194786. png_debug(1, "in png_set_read_user_chunk_fn\n");
  194787. if (png_ptr == NULL)
  194788. return;
  194789. png_ptr->read_user_chunk_fn = read_user_chunk_fn;
  194790. png_ptr->user_chunk_ptr = user_chunk_ptr;
  194791. }
  194792. #endif
  194793. #if defined(PNG_INFO_IMAGE_SUPPORTED)
  194794. void PNGAPI
  194795. png_set_rows(png_structp png_ptr, png_infop info_ptr, png_bytepp row_pointers)
  194796. {
  194797. png_debug1(1, "in %s storage function\n", "rows");
  194798. if (png_ptr == NULL || info_ptr == NULL)
  194799. return;
  194800. if(info_ptr->row_pointers && (info_ptr->row_pointers != row_pointers))
  194801. png_free_data(png_ptr, info_ptr, PNG_FREE_ROWS, 0);
  194802. info_ptr->row_pointers = row_pointers;
  194803. if(row_pointers)
  194804. info_ptr->valid |= PNG_INFO_IDAT;
  194805. }
  194806. #endif
  194807. #ifdef PNG_WRITE_SUPPORTED
  194808. void PNGAPI
  194809. png_set_compression_buffer_size(png_structp png_ptr, png_uint_32 size)
  194810. {
  194811. if (png_ptr == NULL)
  194812. return;
  194813. if(png_ptr->zbuf)
  194814. png_free(png_ptr, png_ptr->zbuf);
  194815. png_ptr->zbuf_size = (png_size_t)size;
  194816. png_ptr->zbuf = (png_bytep)png_malloc(png_ptr, size);
  194817. png_ptr->zstream.next_out = png_ptr->zbuf;
  194818. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  194819. }
  194820. #endif
  194821. void PNGAPI
  194822. png_set_invalid(png_structp png_ptr, png_infop info_ptr, int mask)
  194823. {
  194824. if (png_ptr && info_ptr)
  194825. info_ptr->valid &= ~(mask);
  194826. }
  194827. #ifndef PNG_1_0_X
  194828. #ifdef PNG_ASSEMBLER_CODE_SUPPORTED
  194829. /* function was added to libpng 1.2.0 and should always exist by default */
  194830. void PNGAPI
  194831. png_set_asm_flags (png_structp png_ptr, png_uint_32)
  194832. {
  194833. /* Obsolete as of libpng-1.2.20 and will be removed from libpng-1.4.0 */
  194834. if (png_ptr != NULL)
  194835. png_ptr->asm_flags = 0;
  194836. }
  194837. /* this function was added to libpng 1.2.0 */
  194838. void PNGAPI
  194839. png_set_mmx_thresholds (png_structp png_ptr,
  194840. png_byte,
  194841. png_uint_32)
  194842. {
  194843. /* Obsolete as of libpng-1.2.20 and will be removed from libpng-1.4.0 */
  194844. if (png_ptr == NULL)
  194845. return;
  194846. }
  194847. #endif /* ?PNG_ASSEMBLER_CODE_SUPPORTED */
  194848. #ifdef PNG_SET_USER_LIMITS_SUPPORTED
  194849. /* this function was added to libpng 1.2.6 */
  194850. void PNGAPI
  194851. png_set_user_limits (png_structp png_ptr, png_uint_32 user_width_max,
  194852. png_uint_32 user_height_max)
  194853. {
  194854. /* Images with dimensions larger than these limits will be
  194855. * rejected by png_set_IHDR(). To accept any PNG datastream
  194856. * regardless of dimensions, set both limits to 0x7ffffffL.
  194857. */
  194858. if(png_ptr == NULL) return;
  194859. png_ptr->user_width_max = user_width_max;
  194860. png_ptr->user_height_max = user_height_max;
  194861. }
  194862. #endif /* ?PNG_SET_USER_LIMITS_SUPPORTED */
  194863. #endif /* ?PNG_1_0_X */
  194864. #endif /* PNG_READ_SUPPORTED || PNG_WRITE_SUPPORTED */
  194865. /*** End of inlined file: pngset.c ***/
  194866. /*** Start of inlined file: pngtrans.c ***/
  194867. /* pngtrans.c - transforms the data in a row (used by both readers and writers)
  194868. *
  194869. * Last changed in libpng 1.2.17 May 15, 2007
  194870. * For conditions of distribution and use, see copyright notice in png.h
  194871. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  194872. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  194873. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  194874. */
  194875. #define PNG_INTERNAL
  194876. #if defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED)
  194877. #if defined(PNG_READ_BGR_SUPPORTED) || defined(PNG_WRITE_BGR_SUPPORTED)
  194878. /* turn on BGR-to-RGB mapping */
  194879. void PNGAPI
  194880. png_set_bgr(png_structp png_ptr)
  194881. {
  194882. png_debug(1, "in png_set_bgr\n");
  194883. if(png_ptr == NULL) return;
  194884. png_ptr->transformations |= PNG_BGR;
  194885. }
  194886. #endif
  194887. #if defined(PNG_READ_SWAP_SUPPORTED) || defined(PNG_WRITE_SWAP_SUPPORTED)
  194888. /* turn on 16 bit byte swapping */
  194889. void PNGAPI
  194890. png_set_swap(png_structp png_ptr)
  194891. {
  194892. png_debug(1, "in png_set_swap\n");
  194893. if(png_ptr == NULL) return;
  194894. if (png_ptr->bit_depth == 16)
  194895. png_ptr->transformations |= PNG_SWAP_BYTES;
  194896. }
  194897. #endif
  194898. #if defined(PNG_READ_PACK_SUPPORTED) || defined(PNG_WRITE_PACK_SUPPORTED)
  194899. /* turn on pixel packing */
  194900. void PNGAPI
  194901. png_set_packing(png_structp png_ptr)
  194902. {
  194903. png_debug(1, "in png_set_packing\n");
  194904. if(png_ptr == NULL) return;
  194905. if (png_ptr->bit_depth < 8)
  194906. {
  194907. png_ptr->transformations |= PNG_PACK;
  194908. png_ptr->usr_bit_depth = 8;
  194909. }
  194910. }
  194911. #endif
  194912. #if defined(PNG_READ_PACKSWAP_SUPPORTED)||defined(PNG_WRITE_PACKSWAP_SUPPORTED)
  194913. /* turn on packed pixel swapping */
  194914. void PNGAPI
  194915. png_set_packswap(png_structp png_ptr)
  194916. {
  194917. png_debug(1, "in png_set_packswap\n");
  194918. if(png_ptr == NULL) return;
  194919. if (png_ptr->bit_depth < 8)
  194920. png_ptr->transformations |= PNG_PACKSWAP;
  194921. }
  194922. #endif
  194923. #if defined(PNG_READ_SHIFT_SUPPORTED) || defined(PNG_WRITE_SHIFT_SUPPORTED)
  194924. void PNGAPI
  194925. png_set_shift(png_structp png_ptr, png_color_8p true_bits)
  194926. {
  194927. png_debug(1, "in png_set_shift\n");
  194928. if(png_ptr == NULL) return;
  194929. png_ptr->transformations |= PNG_SHIFT;
  194930. png_ptr->shift = *true_bits;
  194931. }
  194932. #endif
  194933. #if defined(PNG_READ_INTERLACING_SUPPORTED) || \
  194934. defined(PNG_WRITE_INTERLACING_SUPPORTED)
  194935. int PNGAPI
  194936. png_set_interlace_handling(png_structp png_ptr)
  194937. {
  194938. png_debug(1, "in png_set_interlace handling\n");
  194939. if (png_ptr && png_ptr->interlaced)
  194940. {
  194941. png_ptr->transformations |= PNG_INTERLACE;
  194942. return (7);
  194943. }
  194944. return (1);
  194945. }
  194946. #endif
  194947. #if defined(PNG_READ_FILLER_SUPPORTED) || defined(PNG_WRITE_FILLER_SUPPORTED)
  194948. /* Add a filler byte on read, or remove a filler or alpha byte on write.
  194949. * The filler type has changed in v0.95 to allow future 2-byte fillers
  194950. * for 48-bit input data, as well as to avoid problems with some compilers
  194951. * that don't like bytes as parameters.
  194952. */
  194953. void PNGAPI
  194954. png_set_filler(png_structp png_ptr, png_uint_32 filler, int filler_loc)
  194955. {
  194956. png_debug(1, "in png_set_filler\n");
  194957. if(png_ptr == NULL) return;
  194958. png_ptr->transformations |= PNG_FILLER;
  194959. png_ptr->filler = (png_byte)filler;
  194960. if (filler_loc == PNG_FILLER_AFTER)
  194961. png_ptr->flags |= PNG_FLAG_FILLER_AFTER;
  194962. else
  194963. png_ptr->flags &= ~PNG_FLAG_FILLER_AFTER;
  194964. /* This should probably go in the "do_read_filler" routine.
  194965. * I attempted to do that in libpng-1.0.1a but that caused problems
  194966. * so I restored it in libpng-1.0.2a
  194967. */
  194968. if (png_ptr->color_type == PNG_COLOR_TYPE_RGB)
  194969. {
  194970. png_ptr->usr_channels = 4;
  194971. }
  194972. /* Also I added this in libpng-1.0.2a (what happens when we expand
  194973. * a less-than-8-bit grayscale to GA? */
  194974. if (png_ptr->color_type == PNG_COLOR_TYPE_GRAY && png_ptr->bit_depth >= 8)
  194975. {
  194976. png_ptr->usr_channels = 2;
  194977. }
  194978. }
  194979. #if !defined(PNG_1_0_X)
  194980. /* Added to libpng-1.2.7 */
  194981. void PNGAPI
  194982. png_set_add_alpha(png_structp png_ptr, png_uint_32 filler, int filler_loc)
  194983. {
  194984. png_debug(1, "in png_set_add_alpha\n");
  194985. if(png_ptr == NULL) return;
  194986. png_set_filler(png_ptr, filler, filler_loc);
  194987. png_ptr->transformations |= PNG_ADD_ALPHA;
  194988. }
  194989. #endif
  194990. #endif
  194991. #if defined(PNG_READ_SWAP_ALPHA_SUPPORTED) || \
  194992. defined(PNG_WRITE_SWAP_ALPHA_SUPPORTED)
  194993. void PNGAPI
  194994. png_set_swap_alpha(png_structp png_ptr)
  194995. {
  194996. png_debug(1, "in png_set_swap_alpha\n");
  194997. if(png_ptr == NULL) return;
  194998. png_ptr->transformations |= PNG_SWAP_ALPHA;
  194999. }
  195000. #endif
  195001. #if defined(PNG_READ_INVERT_ALPHA_SUPPORTED) || \
  195002. defined(PNG_WRITE_INVERT_ALPHA_SUPPORTED)
  195003. void PNGAPI
  195004. png_set_invert_alpha(png_structp png_ptr)
  195005. {
  195006. png_debug(1, "in png_set_invert_alpha\n");
  195007. if(png_ptr == NULL) return;
  195008. png_ptr->transformations |= PNG_INVERT_ALPHA;
  195009. }
  195010. #endif
  195011. #if defined(PNG_READ_INVERT_SUPPORTED) || defined(PNG_WRITE_INVERT_SUPPORTED)
  195012. void PNGAPI
  195013. png_set_invert_mono(png_structp png_ptr)
  195014. {
  195015. png_debug(1, "in png_set_invert_mono\n");
  195016. if(png_ptr == NULL) return;
  195017. png_ptr->transformations |= PNG_INVERT_MONO;
  195018. }
  195019. /* invert monochrome grayscale data */
  195020. void /* PRIVATE */
  195021. png_do_invert(png_row_infop row_info, png_bytep row)
  195022. {
  195023. png_debug(1, "in png_do_invert\n");
  195024. /* This test removed from libpng version 1.0.13 and 1.2.0:
  195025. * if (row_info->bit_depth == 1 &&
  195026. */
  195027. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  195028. if (row == NULL || row_info == NULL)
  195029. return;
  195030. #endif
  195031. if (row_info->color_type == PNG_COLOR_TYPE_GRAY)
  195032. {
  195033. png_bytep rp = row;
  195034. png_uint_32 i;
  195035. png_uint_32 istop = row_info->rowbytes;
  195036. for (i = 0; i < istop; i++)
  195037. {
  195038. *rp = (png_byte)(~(*rp));
  195039. rp++;
  195040. }
  195041. }
  195042. else if (row_info->color_type == PNG_COLOR_TYPE_GRAY_ALPHA &&
  195043. row_info->bit_depth == 8)
  195044. {
  195045. png_bytep rp = row;
  195046. png_uint_32 i;
  195047. png_uint_32 istop = row_info->rowbytes;
  195048. for (i = 0; i < istop; i+=2)
  195049. {
  195050. *rp = (png_byte)(~(*rp));
  195051. rp+=2;
  195052. }
  195053. }
  195054. else if (row_info->color_type == PNG_COLOR_TYPE_GRAY_ALPHA &&
  195055. row_info->bit_depth == 16)
  195056. {
  195057. png_bytep rp = row;
  195058. png_uint_32 i;
  195059. png_uint_32 istop = row_info->rowbytes;
  195060. for (i = 0; i < istop; i+=4)
  195061. {
  195062. *rp = (png_byte)(~(*rp));
  195063. *(rp+1) = (png_byte)(~(*(rp+1)));
  195064. rp+=4;
  195065. }
  195066. }
  195067. }
  195068. #endif
  195069. #if defined(PNG_READ_SWAP_SUPPORTED) || defined(PNG_WRITE_SWAP_SUPPORTED)
  195070. /* swaps byte order on 16 bit depth images */
  195071. void /* PRIVATE */
  195072. png_do_swap(png_row_infop row_info, png_bytep row)
  195073. {
  195074. png_debug(1, "in png_do_swap\n");
  195075. if (
  195076. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  195077. row != NULL && row_info != NULL &&
  195078. #endif
  195079. row_info->bit_depth == 16)
  195080. {
  195081. png_bytep rp = row;
  195082. png_uint_32 i;
  195083. png_uint_32 istop= row_info->width * row_info->channels;
  195084. for (i = 0; i < istop; i++, rp += 2)
  195085. {
  195086. png_byte t = *rp;
  195087. *rp = *(rp + 1);
  195088. *(rp + 1) = t;
  195089. }
  195090. }
  195091. }
  195092. #endif
  195093. #if defined(PNG_READ_PACKSWAP_SUPPORTED)||defined(PNG_WRITE_PACKSWAP_SUPPORTED)
  195094. static PNG_CONST png_byte onebppswaptable[256] = {
  195095. 0x00, 0x80, 0x40, 0xC0, 0x20, 0xA0, 0x60, 0xE0,
  195096. 0x10, 0x90, 0x50, 0xD0, 0x30, 0xB0, 0x70, 0xF0,
  195097. 0x08, 0x88, 0x48, 0xC8, 0x28, 0xA8, 0x68, 0xE8,
  195098. 0x18, 0x98, 0x58, 0xD8, 0x38, 0xB8, 0x78, 0xF8,
  195099. 0x04, 0x84, 0x44, 0xC4, 0x24, 0xA4, 0x64, 0xE4,
  195100. 0x14, 0x94, 0x54, 0xD4, 0x34, 0xB4, 0x74, 0xF4,
  195101. 0x0C, 0x8C, 0x4C, 0xCC, 0x2C, 0xAC, 0x6C, 0xEC,
  195102. 0x1C, 0x9C, 0x5C, 0xDC, 0x3C, 0xBC, 0x7C, 0xFC,
  195103. 0x02, 0x82, 0x42, 0xC2, 0x22, 0xA2, 0x62, 0xE2,
  195104. 0x12, 0x92, 0x52, 0xD2, 0x32, 0xB2, 0x72, 0xF2,
  195105. 0x0A, 0x8A, 0x4A, 0xCA, 0x2A, 0xAA, 0x6A, 0xEA,
  195106. 0x1A, 0x9A, 0x5A, 0xDA, 0x3A, 0xBA, 0x7A, 0xFA,
  195107. 0x06, 0x86, 0x46, 0xC6, 0x26, 0xA6, 0x66, 0xE6,
  195108. 0x16, 0x96, 0x56, 0xD6, 0x36, 0xB6, 0x76, 0xF6,
  195109. 0x0E, 0x8E, 0x4E, 0xCE, 0x2E, 0xAE, 0x6E, 0xEE,
  195110. 0x1E, 0x9E, 0x5E, 0xDE, 0x3E, 0xBE, 0x7E, 0xFE,
  195111. 0x01, 0x81, 0x41, 0xC1, 0x21, 0xA1, 0x61, 0xE1,
  195112. 0x11, 0x91, 0x51, 0xD1, 0x31, 0xB1, 0x71, 0xF1,
  195113. 0x09, 0x89, 0x49, 0xC9, 0x29, 0xA9, 0x69, 0xE9,
  195114. 0x19, 0x99, 0x59, 0xD9, 0x39, 0xB9, 0x79, 0xF9,
  195115. 0x05, 0x85, 0x45, 0xC5, 0x25, 0xA5, 0x65, 0xE5,
  195116. 0x15, 0x95, 0x55, 0xD5, 0x35, 0xB5, 0x75, 0xF5,
  195117. 0x0D, 0x8D, 0x4D, 0xCD, 0x2D, 0xAD, 0x6D, 0xED,
  195118. 0x1D, 0x9D, 0x5D, 0xDD, 0x3D, 0xBD, 0x7D, 0xFD,
  195119. 0x03, 0x83, 0x43, 0xC3, 0x23, 0xA3, 0x63, 0xE3,
  195120. 0x13, 0x93, 0x53, 0xD3, 0x33, 0xB3, 0x73, 0xF3,
  195121. 0x0B, 0x8B, 0x4B, 0xCB, 0x2B, 0xAB, 0x6B, 0xEB,
  195122. 0x1B, 0x9B, 0x5B, 0xDB, 0x3B, 0xBB, 0x7B, 0xFB,
  195123. 0x07, 0x87, 0x47, 0xC7, 0x27, 0xA7, 0x67, 0xE7,
  195124. 0x17, 0x97, 0x57, 0xD7, 0x37, 0xB7, 0x77, 0xF7,
  195125. 0x0F, 0x8F, 0x4F, 0xCF, 0x2F, 0xAF, 0x6F, 0xEF,
  195126. 0x1F, 0x9F, 0x5F, 0xDF, 0x3F, 0xBF, 0x7F, 0xFF
  195127. };
  195128. static PNG_CONST png_byte twobppswaptable[256] = {
  195129. 0x00, 0x40, 0x80, 0xC0, 0x10, 0x50, 0x90, 0xD0,
  195130. 0x20, 0x60, 0xA0, 0xE0, 0x30, 0x70, 0xB0, 0xF0,
  195131. 0x04, 0x44, 0x84, 0xC4, 0x14, 0x54, 0x94, 0xD4,
  195132. 0x24, 0x64, 0xA4, 0xE4, 0x34, 0x74, 0xB4, 0xF4,
  195133. 0x08, 0x48, 0x88, 0xC8, 0x18, 0x58, 0x98, 0xD8,
  195134. 0x28, 0x68, 0xA8, 0xE8, 0x38, 0x78, 0xB8, 0xF8,
  195135. 0x0C, 0x4C, 0x8C, 0xCC, 0x1C, 0x5C, 0x9C, 0xDC,
  195136. 0x2C, 0x6C, 0xAC, 0xEC, 0x3C, 0x7C, 0xBC, 0xFC,
  195137. 0x01, 0x41, 0x81, 0xC1, 0x11, 0x51, 0x91, 0xD1,
  195138. 0x21, 0x61, 0xA1, 0xE1, 0x31, 0x71, 0xB1, 0xF1,
  195139. 0x05, 0x45, 0x85, 0xC5, 0x15, 0x55, 0x95, 0xD5,
  195140. 0x25, 0x65, 0xA5, 0xE5, 0x35, 0x75, 0xB5, 0xF5,
  195141. 0x09, 0x49, 0x89, 0xC9, 0x19, 0x59, 0x99, 0xD9,
  195142. 0x29, 0x69, 0xA9, 0xE9, 0x39, 0x79, 0xB9, 0xF9,
  195143. 0x0D, 0x4D, 0x8D, 0xCD, 0x1D, 0x5D, 0x9D, 0xDD,
  195144. 0x2D, 0x6D, 0xAD, 0xED, 0x3D, 0x7D, 0xBD, 0xFD,
  195145. 0x02, 0x42, 0x82, 0xC2, 0x12, 0x52, 0x92, 0xD2,
  195146. 0x22, 0x62, 0xA2, 0xE2, 0x32, 0x72, 0xB2, 0xF2,
  195147. 0x06, 0x46, 0x86, 0xC6, 0x16, 0x56, 0x96, 0xD6,
  195148. 0x26, 0x66, 0xA6, 0xE6, 0x36, 0x76, 0xB6, 0xF6,
  195149. 0x0A, 0x4A, 0x8A, 0xCA, 0x1A, 0x5A, 0x9A, 0xDA,
  195150. 0x2A, 0x6A, 0xAA, 0xEA, 0x3A, 0x7A, 0xBA, 0xFA,
  195151. 0x0E, 0x4E, 0x8E, 0xCE, 0x1E, 0x5E, 0x9E, 0xDE,
  195152. 0x2E, 0x6E, 0xAE, 0xEE, 0x3E, 0x7E, 0xBE, 0xFE,
  195153. 0x03, 0x43, 0x83, 0xC3, 0x13, 0x53, 0x93, 0xD3,
  195154. 0x23, 0x63, 0xA3, 0xE3, 0x33, 0x73, 0xB3, 0xF3,
  195155. 0x07, 0x47, 0x87, 0xC7, 0x17, 0x57, 0x97, 0xD7,
  195156. 0x27, 0x67, 0xA7, 0xE7, 0x37, 0x77, 0xB7, 0xF7,
  195157. 0x0B, 0x4B, 0x8B, 0xCB, 0x1B, 0x5B, 0x9B, 0xDB,
  195158. 0x2B, 0x6B, 0xAB, 0xEB, 0x3B, 0x7B, 0xBB, 0xFB,
  195159. 0x0F, 0x4F, 0x8F, 0xCF, 0x1F, 0x5F, 0x9F, 0xDF,
  195160. 0x2F, 0x6F, 0xAF, 0xEF, 0x3F, 0x7F, 0xBF, 0xFF
  195161. };
  195162. static PNG_CONST png_byte fourbppswaptable[256] = {
  195163. 0x00, 0x10, 0x20, 0x30, 0x40, 0x50, 0x60, 0x70,
  195164. 0x80, 0x90, 0xA0, 0xB0, 0xC0, 0xD0, 0xE0, 0xF0,
  195165. 0x01, 0x11, 0x21, 0x31, 0x41, 0x51, 0x61, 0x71,
  195166. 0x81, 0x91, 0xA1, 0xB1, 0xC1, 0xD1, 0xE1, 0xF1,
  195167. 0x02, 0x12, 0x22, 0x32, 0x42, 0x52, 0x62, 0x72,
  195168. 0x82, 0x92, 0xA2, 0xB2, 0xC2, 0xD2, 0xE2, 0xF2,
  195169. 0x03, 0x13, 0x23, 0x33, 0x43, 0x53, 0x63, 0x73,
  195170. 0x83, 0x93, 0xA3, 0xB3, 0xC3, 0xD3, 0xE3, 0xF3,
  195171. 0x04, 0x14, 0x24, 0x34, 0x44, 0x54, 0x64, 0x74,
  195172. 0x84, 0x94, 0xA4, 0xB4, 0xC4, 0xD4, 0xE4, 0xF4,
  195173. 0x05, 0x15, 0x25, 0x35, 0x45, 0x55, 0x65, 0x75,
  195174. 0x85, 0x95, 0xA5, 0xB5, 0xC5, 0xD5, 0xE5, 0xF5,
  195175. 0x06, 0x16, 0x26, 0x36, 0x46, 0x56, 0x66, 0x76,
  195176. 0x86, 0x96, 0xA6, 0xB6, 0xC6, 0xD6, 0xE6, 0xF6,
  195177. 0x07, 0x17, 0x27, 0x37, 0x47, 0x57, 0x67, 0x77,
  195178. 0x87, 0x97, 0xA7, 0xB7, 0xC7, 0xD7, 0xE7, 0xF7,
  195179. 0x08, 0x18, 0x28, 0x38, 0x48, 0x58, 0x68, 0x78,
  195180. 0x88, 0x98, 0xA8, 0xB8, 0xC8, 0xD8, 0xE8, 0xF8,
  195181. 0x09, 0x19, 0x29, 0x39, 0x49, 0x59, 0x69, 0x79,
  195182. 0x89, 0x99, 0xA9, 0xB9, 0xC9, 0xD9, 0xE9, 0xF9,
  195183. 0x0A, 0x1A, 0x2A, 0x3A, 0x4A, 0x5A, 0x6A, 0x7A,
  195184. 0x8A, 0x9A, 0xAA, 0xBA, 0xCA, 0xDA, 0xEA, 0xFA,
  195185. 0x0B, 0x1B, 0x2B, 0x3B, 0x4B, 0x5B, 0x6B, 0x7B,
  195186. 0x8B, 0x9B, 0xAB, 0xBB, 0xCB, 0xDB, 0xEB, 0xFB,
  195187. 0x0C, 0x1C, 0x2C, 0x3C, 0x4C, 0x5C, 0x6C, 0x7C,
  195188. 0x8C, 0x9C, 0xAC, 0xBC, 0xCC, 0xDC, 0xEC, 0xFC,
  195189. 0x0D, 0x1D, 0x2D, 0x3D, 0x4D, 0x5D, 0x6D, 0x7D,
  195190. 0x8D, 0x9D, 0xAD, 0xBD, 0xCD, 0xDD, 0xED, 0xFD,
  195191. 0x0E, 0x1E, 0x2E, 0x3E, 0x4E, 0x5E, 0x6E, 0x7E,
  195192. 0x8E, 0x9E, 0xAE, 0xBE, 0xCE, 0xDE, 0xEE, 0xFE,
  195193. 0x0F, 0x1F, 0x2F, 0x3F, 0x4F, 0x5F, 0x6F, 0x7F,
  195194. 0x8F, 0x9F, 0xAF, 0xBF, 0xCF, 0xDF, 0xEF, 0xFF
  195195. };
  195196. /* swaps pixel packing order within bytes */
  195197. void /* PRIVATE */
  195198. png_do_packswap(png_row_infop row_info, png_bytep row)
  195199. {
  195200. png_debug(1, "in png_do_packswap\n");
  195201. if (
  195202. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  195203. row != NULL && row_info != NULL &&
  195204. #endif
  195205. row_info->bit_depth < 8)
  195206. {
  195207. png_bytep rp, end, table;
  195208. end = row + row_info->rowbytes;
  195209. if (row_info->bit_depth == 1)
  195210. table = (png_bytep)onebppswaptable;
  195211. else if (row_info->bit_depth == 2)
  195212. table = (png_bytep)twobppswaptable;
  195213. else if (row_info->bit_depth == 4)
  195214. table = (png_bytep)fourbppswaptable;
  195215. else
  195216. return;
  195217. for (rp = row; rp < end; rp++)
  195218. *rp = table[*rp];
  195219. }
  195220. }
  195221. #endif /* PNG_READ_PACKSWAP_SUPPORTED or PNG_WRITE_PACKSWAP_SUPPORTED */
  195222. #if defined(PNG_WRITE_FILLER_SUPPORTED) || \
  195223. defined(PNG_READ_STRIP_ALPHA_SUPPORTED)
  195224. /* remove filler or alpha byte(s) */
  195225. void /* PRIVATE */
  195226. png_do_strip_filler(png_row_infop row_info, png_bytep row, png_uint_32 flags)
  195227. {
  195228. png_debug(1, "in png_do_strip_filler\n");
  195229. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  195230. if (row != NULL && row_info != NULL)
  195231. #endif
  195232. {
  195233. png_bytep sp=row;
  195234. png_bytep dp=row;
  195235. png_uint_32 row_width=row_info->width;
  195236. png_uint_32 i;
  195237. if ((row_info->color_type == PNG_COLOR_TYPE_RGB ||
  195238. (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA &&
  195239. (flags & PNG_FLAG_STRIP_ALPHA))) &&
  195240. row_info->channels == 4)
  195241. {
  195242. if (row_info->bit_depth == 8)
  195243. {
  195244. /* This converts from RGBX or RGBA to RGB */
  195245. if (flags & PNG_FLAG_FILLER_AFTER)
  195246. {
  195247. dp+=3; sp+=4;
  195248. for (i = 1; i < row_width; i++)
  195249. {
  195250. *dp++ = *sp++;
  195251. *dp++ = *sp++;
  195252. *dp++ = *sp++;
  195253. sp++;
  195254. }
  195255. }
  195256. /* This converts from XRGB or ARGB to RGB */
  195257. else
  195258. {
  195259. for (i = 0; i < row_width; i++)
  195260. {
  195261. sp++;
  195262. *dp++ = *sp++;
  195263. *dp++ = *sp++;
  195264. *dp++ = *sp++;
  195265. }
  195266. }
  195267. row_info->pixel_depth = 24;
  195268. row_info->rowbytes = row_width * 3;
  195269. }
  195270. else /* if (row_info->bit_depth == 16) */
  195271. {
  195272. if (flags & PNG_FLAG_FILLER_AFTER)
  195273. {
  195274. /* This converts from RRGGBBXX or RRGGBBAA to RRGGBB */
  195275. sp += 8; dp += 6;
  195276. for (i = 1; i < row_width; i++)
  195277. {
  195278. /* This could be (although png_memcpy is probably slower):
  195279. png_memcpy(dp, sp, 6);
  195280. sp += 8;
  195281. dp += 6;
  195282. */
  195283. *dp++ = *sp++;
  195284. *dp++ = *sp++;
  195285. *dp++ = *sp++;
  195286. *dp++ = *sp++;
  195287. *dp++ = *sp++;
  195288. *dp++ = *sp++;
  195289. sp += 2;
  195290. }
  195291. }
  195292. else
  195293. {
  195294. /* This converts from XXRRGGBB or AARRGGBB to RRGGBB */
  195295. for (i = 0; i < row_width; i++)
  195296. {
  195297. /* This could be (although png_memcpy is probably slower):
  195298. png_memcpy(dp, sp, 6);
  195299. sp += 8;
  195300. dp += 6;
  195301. */
  195302. sp+=2;
  195303. *dp++ = *sp++;
  195304. *dp++ = *sp++;
  195305. *dp++ = *sp++;
  195306. *dp++ = *sp++;
  195307. *dp++ = *sp++;
  195308. *dp++ = *sp++;
  195309. }
  195310. }
  195311. row_info->pixel_depth = 48;
  195312. row_info->rowbytes = row_width * 6;
  195313. }
  195314. row_info->channels = 3;
  195315. }
  195316. else if ((row_info->color_type == PNG_COLOR_TYPE_GRAY ||
  195317. (row_info->color_type == PNG_COLOR_TYPE_GRAY_ALPHA &&
  195318. (flags & PNG_FLAG_STRIP_ALPHA))) &&
  195319. row_info->channels == 2)
  195320. {
  195321. if (row_info->bit_depth == 8)
  195322. {
  195323. /* This converts from GX or GA to G */
  195324. if (flags & PNG_FLAG_FILLER_AFTER)
  195325. {
  195326. for (i = 0; i < row_width; i++)
  195327. {
  195328. *dp++ = *sp++;
  195329. sp++;
  195330. }
  195331. }
  195332. /* This converts from XG or AG to G */
  195333. else
  195334. {
  195335. for (i = 0; i < row_width; i++)
  195336. {
  195337. sp++;
  195338. *dp++ = *sp++;
  195339. }
  195340. }
  195341. row_info->pixel_depth = 8;
  195342. row_info->rowbytes = row_width;
  195343. }
  195344. else /* if (row_info->bit_depth == 16) */
  195345. {
  195346. if (flags & PNG_FLAG_FILLER_AFTER)
  195347. {
  195348. /* This converts from GGXX or GGAA to GG */
  195349. sp += 4; dp += 2;
  195350. for (i = 1; i < row_width; i++)
  195351. {
  195352. *dp++ = *sp++;
  195353. *dp++ = *sp++;
  195354. sp += 2;
  195355. }
  195356. }
  195357. else
  195358. {
  195359. /* This converts from XXGG or AAGG to GG */
  195360. for (i = 0; i < row_width; i++)
  195361. {
  195362. sp += 2;
  195363. *dp++ = *sp++;
  195364. *dp++ = *sp++;
  195365. }
  195366. }
  195367. row_info->pixel_depth = 16;
  195368. row_info->rowbytes = row_width * 2;
  195369. }
  195370. row_info->channels = 1;
  195371. }
  195372. if (flags & PNG_FLAG_STRIP_ALPHA)
  195373. row_info->color_type &= ~PNG_COLOR_MASK_ALPHA;
  195374. }
  195375. }
  195376. #endif
  195377. #if defined(PNG_READ_BGR_SUPPORTED) || defined(PNG_WRITE_BGR_SUPPORTED)
  195378. /* swaps red and blue bytes within a pixel */
  195379. void /* PRIVATE */
  195380. png_do_bgr(png_row_infop row_info, png_bytep row)
  195381. {
  195382. png_debug(1, "in png_do_bgr\n");
  195383. if (
  195384. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  195385. row != NULL && row_info != NULL &&
  195386. #endif
  195387. (row_info->color_type & PNG_COLOR_MASK_COLOR))
  195388. {
  195389. png_uint_32 row_width = row_info->width;
  195390. if (row_info->bit_depth == 8)
  195391. {
  195392. if (row_info->color_type == PNG_COLOR_TYPE_RGB)
  195393. {
  195394. png_bytep rp;
  195395. png_uint_32 i;
  195396. for (i = 0, rp = row; i < row_width; i++, rp += 3)
  195397. {
  195398. png_byte save = *rp;
  195399. *rp = *(rp + 2);
  195400. *(rp + 2) = save;
  195401. }
  195402. }
  195403. else if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  195404. {
  195405. png_bytep rp;
  195406. png_uint_32 i;
  195407. for (i = 0, rp = row; i < row_width; i++, rp += 4)
  195408. {
  195409. png_byte save = *rp;
  195410. *rp = *(rp + 2);
  195411. *(rp + 2) = save;
  195412. }
  195413. }
  195414. }
  195415. else if (row_info->bit_depth == 16)
  195416. {
  195417. if (row_info->color_type == PNG_COLOR_TYPE_RGB)
  195418. {
  195419. png_bytep rp;
  195420. png_uint_32 i;
  195421. for (i = 0, rp = row; i < row_width; i++, rp += 6)
  195422. {
  195423. png_byte save = *rp;
  195424. *rp = *(rp + 4);
  195425. *(rp + 4) = save;
  195426. save = *(rp + 1);
  195427. *(rp + 1) = *(rp + 5);
  195428. *(rp + 5) = save;
  195429. }
  195430. }
  195431. else if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  195432. {
  195433. png_bytep rp;
  195434. png_uint_32 i;
  195435. for (i = 0, rp = row; i < row_width; i++, rp += 8)
  195436. {
  195437. png_byte save = *rp;
  195438. *rp = *(rp + 4);
  195439. *(rp + 4) = save;
  195440. save = *(rp + 1);
  195441. *(rp + 1) = *(rp + 5);
  195442. *(rp + 5) = save;
  195443. }
  195444. }
  195445. }
  195446. }
  195447. }
  195448. #endif /* PNG_READ_BGR_SUPPORTED or PNG_WRITE_BGR_SUPPORTED */
  195449. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED) || \
  195450. defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED) || \
  195451. defined(PNG_LEGACY_SUPPORTED)
  195452. void PNGAPI
  195453. png_set_user_transform_info(png_structp png_ptr, png_voidp
  195454. user_transform_ptr, int user_transform_depth, int user_transform_channels)
  195455. {
  195456. png_debug(1, "in png_set_user_transform_info\n");
  195457. if(png_ptr == NULL) return;
  195458. #if defined(PNG_USER_TRANSFORM_PTR_SUPPORTED)
  195459. png_ptr->user_transform_ptr = user_transform_ptr;
  195460. png_ptr->user_transform_depth = (png_byte)user_transform_depth;
  195461. png_ptr->user_transform_channels = (png_byte)user_transform_channels;
  195462. #else
  195463. if(user_transform_ptr || user_transform_depth || user_transform_channels)
  195464. png_warning(png_ptr,
  195465. "This version of libpng does not support user transform info");
  195466. #endif
  195467. }
  195468. #endif
  195469. /* This function returns a pointer to the user_transform_ptr associated with
  195470. * the user transform functions. The application should free any memory
  195471. * associated with this pointer before png_write_destroy and png_read_destroy
  195472. * are called.
  195473. */
  195474. png_voidp PNGAPI
  195475. png_get_user_transform_ptr(png_structp png_ptr)
  195476. {
  195477. #if defined(PNG_USER_TRANSFORM_PTR_SUPPORTED)
  195478. if (png_ptr == NULL) return (NULL);
  195479. return ((png_voidp)png_ptr->user_transform_ptr);
  195480. #else
  195481. return (NULL);
  195482. #endif
  195483. }
  195484. #endif /* PNG_READ_SUPPORTED || PNG_WRITE_SUPPORTED */
  195485. /*** End of inlined file: pngtrans.c ***/
  195486. /*** Start of inlined file: pngwio.c ***/
  195487. /* pngwio.c - functions for data output
  195488. *
  195489. * Last changed in libpng 1.2.13 November 13, 2006
  195490. * For conditions of distribution and use, see copyright notice in png.h
  195491. * Copyright (c) 1998-2006 Glenn Randers-Pehrson
  195492. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  195493. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  195494. *
  195495. * This file provides a location for all output. Users who need
  195496. * special handling are expected to write functions that have the same
  195497. * arguments as these and perform similar functions, but that possibly
  195498. * use different output methods. Note that you shouldn't change these
  195499. * functions, but rather write replacement functions and then change
  195500. * them at run time with png_set_write_fn(...).
  195501. */
  195502. #define PNG_INTERNAL
  195503. #ifdef PNG_WRITE_SUPPORTED
  195504. /* Write the data to whatever output you are using. The default routine
  195505. writes to a file pointer. Note that this routine sometimes gets called
  195506. with very small lengths, so you should implement some kind of simple
  195507. buffering if you are using unbuffered writes. This should never be asked
  195508. to write more than 64K on a 16 bit machine. */
  195509. void /* PRIVATE */
  195510. png_write_data(png_structp png_ptr, png_bytep data, png_size_t length)
  195511. {
  195512. if (png_ptr->write_data_fn != NULL )
  195513. (*(png_ptr->write_data_fn))(png_ptr, data, length);
  195514. else
  195515. png_error(png_ptr, "Call to NULL write function");
  195516. }
  195517. #if !defined(PNG_NO_STDIO)
  195518. /* This is the function that does the actual writing of data. If you are
  195519. not writing to a standard C stream, you should create a replacement
  195520. write_data function and use it at run time with png_set_write_fn(), rather
  195521. than changing the library. */
  195522. #ifndef USE_FAR_KEYWORD
  195523. void PNGAPI
  195524. png_default_write_data(png_structp png_ptr, png_bytep data, png_size_t length)
  195525. {
  195526. png_uint_32 check;
  195527. if(png_ptr == NULL) return;
  195528. #if defined(_WIN32_WCE)
  195529. if ( !WriteFile((HANDLE)(png_ptr->io_ptr), data, length, &check, NULL) )
  195530. check = 0;
  195531. #else
  195532. check = fwrite(data, 1, length, (png_FILE_p)(png_ptr->io_ptr));
  195533. #endif
  195534. if (check != length)
  195535. png_error(png_ptr, "Write Error");
  195536. }
  195537. #else
  195538. /* this is the model-independent version. Since the standard I/O library
  195539. can't handle far buffers in the medium and small models, we have to copy
  195540. the data.
  195541. */
  195542. #define NEAR_BUF_SIZE 1024
  195543. #define MIN(a,b) (a <= b ? a : b)
  195544. void PNGAPI
  195545. png_default_write_data(png_structp png_ptr, png_bytep data, png_size_t length)
  195546. {
  195547. png_uint_32 check;
  195548. png_byte *near_data; /* Needs to be "png_byte *" instead of "png_bytep" */
  195549. png_FILE_p io_ptr;
  195550. if(png_ptr == NULL) return;
  195551. /* Check if data really is near. If so, use usual code. */
  195552. near_data = (png_byte *)CVT_PTR_NOCHECK(data);
  195553. io_ptr = (png_FILE_p)CVT_PTR(png_ptr->io_ptr);
  195554. if ((png_bytep)near_data == data)
  195555. {
  195556. #if defined(_WIN32_WCE)
  195557. if ( !WriteFile(io_ptr, near_data, length, &check, NULL) )
  195558. check = 0;
  195559. #else
  195560. check = fwrite(near_data, 1, length, io_ptr);
  195561. #endif
  195562. }
  195563. else
  195564. {
  195565. png_byte buf[NEAR_BUF_SIZE];
  195566. png_size_t written, remaining, err;
  195567. check = 0;
  195568. remaining = length;
  195569. do
  195570. {
  195571. written = MIN(NEAR_BUF_SIZE, remaining);
  195572. png_memcpy(buf, data, written); /* copy far buffer to near buffer */
  195573. #if defined(_WIN32_WCE)
  195574. if ( !WriteFile(io_ptr, buf, written, &err, NULL) )
  195575. err = 0;
  195576. #else
  195577. err = fwrite(buf, 1, written, io_ptr);
  195578. #endif
  195579. if (err != written)
  195580. break;
  195581. else
  195582. check += err;
  195583. data += written;
  195584. remaining -= written;
  195585. }
  195586. while (remaining != 0);
  195587. }
  195588. if (check != length)
  195589. png_error(png_ptr, "Write Error");
  195590. }
  195591. #endif
  195592. #endif
  195593. /* This function is called to output any data pending writing (normally
  195594. to disk). After png_flush is called, there should be no data pending
  195595. writing in any buffers. */
  195596. #if defined(PNG_WRITE_FLUSH_SUPPORTED)
  195597. void /* PRIVATE */
  195598. png_flush(png_structp png_ptr)
  195599. {
  195600. if (png_ptr->output_flush_fn != NULL)
  195601. (*(png_ptr->output_flush_fn))(png_ptr);
  195602. }
  195603. #if !defined(PNG_NO_STDIO)
  195604. void PNGAPI
  195605. png_default_flush(png_structp png_ptr)
  195606. {
  195607. #if !defined(_WIN32_WCE)
  195608. png_FILE_p io_ptr;
  195609. #endif
  195610. if(png_ptr == NULL) return;
  195611. #if !defined(_WIN32_WCE)
  195612. io_ptr = (png_FILE_p)CVT_PTR((png_ptr->io_ptr));
  195613. if (io_ptr != NULL)
  195614. fflush(io_ptr);
  195615. #endif
  195616. }
  195617. #endif
  195618. #endif
  195619. /* This function allows the application to supply new output functions for
  195620. libpng if standard C streams aren't being used.
  195621. This function takes as its arguments:
  195622. png_ptr - pointer to a png output data structure
  195623. io_ptr - pointer to user supplied structure containing info about
  195624. the output functions. May be NULL.
  195625. write_data_fn - pointer to a new output function that takes as its
  195626. arguments a pointer to a png_struct, a pointer to
  195627. data to be written, and a 32-bit unsigned int that is
  195628. the number of bytes to be written. The new write
  195629. function should call png_error(png_ptr, "Error msg")
  195630. to exit and output any fatal error messages.
  195631. flush_data_fn - pointer to a new flush function that takes as its
  195632. arguments a pointer to a png_struct. After a call to
  195633. the flush function, there should be no data in any buffers
  195634. or pending transmission. If the output method doesn't do
  195635. any buffering of ouput, a function prototype must still be
  195636. supplied although it doesn't have to do anything. If
  195637. PNG_WRITE_FLUSH_SUPPORTED is not defined at libpng compile
  195638. time, output_flush_fn will be ignored, although it must be
  195639. supplied for compatibility. */
  195640. void PNGAPI
  195641. png_set_write_fn(png_structp png_ptr, png_voidp io_ptr,
  195642. png_rw_ptr write_data_fn, png_flush_ptr output_flush_fn)
  195643. {
  195644. if(png_ptr == NULL) return;
  195645. png_ptr->io_ptr = io_ptr;
  195646. #if !defined(PNG_NO_STDIO)
  195647. if (write_data_fn != NULL)
  195648. png_ptr->write_data_fn = write_data_fn;
  195649. else
  195650. png_ptr->write_data_fn = png_default_write_data;
  195651. #else
  195652. png_ptr->write_data_fn = write_data_fn;
  195653. #endif
  195654. #if defined(PNG_WRITE_FLUSH_SUPPORTED)
  195655. #if !defined(PNG_NO_STDIO)
  195656. if (output_flush_fn != NULL)
  195657. png_ptr->output_flush_fn = output_flush_fn;
  195658. else
  195659. png_ptr->output_flush_fn = png_default_flush;
  195660. #else
  195661. png_ptr->output_flush_fn = output_flush_fn;
  195662. #endif
  195663. #endif /* PNG_WRITE_FLUSH_SUPPORTED */
  195664. /* It is an error to read while writing a png file */
  195665. if (png_ptr->read_data_fn != NULL)
  195666. {
  195667. png_ptr->read_data_fn = NULL;
  195668. png_warning(png_ptr,
  195669. "Attempted to set both read_data_fn and write_data_fn in");
  195670. png_warning(png_ptr,
  195671. "the same structure. Resetting read_data_fn to NULL.");
  195672. }
  195673. }
  195674. #if defined(USE_FAR_KEYWORD)
  195675. #if defined(_MSC_VER)
  195676. void *png_far_to_near(png_structp png_ptr,png_voidp ptr, int check)
  195677. {
  195678. void *near_ptr;
  195679. void FAR *far_ptr;
  195680. FP_OFF(near_ptr) = FP_OFF(ptr);
  195681. far_ptr = (void FAR *)near_ptr;
  195682. if(check != 0)
  195683. if(FP_SEG(ptr) != FP_SEG(far_ptr))
  195684. png_error(png_ptr,"segment lost in conversion");
  195685. return(near_ptr);
  195686. }
  195687. # else
  195688. void *png_far_to_near(png_structp png_ptr,png_voidp ptr, int check)
  195689. {
  195690. void *near_ptr;
  195691. void FAR *far_ptr;
  195692. near_ptr = (void FAR *)ptr;
  195693. far_ptr = (void FAR *)near_ptr;
  195694. if(check != 0)
  195695. if(far_ptr != ptr)
  195696. png_error(png_ptr,"segment lost in conversion");
  195697. return(near_ptr);
  195698. }
  195699. # endif
  195700. # endif
  195701. #endif /* PNG_WRITE_SUPPORTED */
  195702. /*** End of inlined file: pngwio.c ***/
  195703. /*** Start of inlined file: pngwrite.c ***/
  195704. /* pngwrite.c - general routines to write a PNG file
  195705. *
  195706. * Last changed in libpng 1.2.15 January 5, 2007
  195707. * For conditions of distribution and use, see copyright notice in png.h
  195708. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  195709. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  195710. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  195711. */
  195712. /* get internal access to png.h */
  195713. #define PNG_INTERNAL
  195714. #ifdef PNG_WRITE_SUPPORTED
  195715. /* Writes all the PNG information. This is the suggested way to use the
  195716. * library. If you have a new chunk to add, make a function to write it,
  195717. * and put it in the correct location here. If you want the chunk written
  195718. * after the image data, put it in png_write_end(). I strongly encourage
  195719. * you to supply a PNG_INFO_ flag, and check info_ptr->valid before writing
  195720. * the chunk, as that will keep the code from breaking if you want to just
  195721. * write a plain PNG file. If you have long comments, I suggest writing
  195722. * them in png_write_end(), and compressing them.
  195723. */
  195724. void PNGAPI
  195725. png_write_info_before_PLTE(png_structp png_ptr, png_infop info_ptr)
  195726. {
  195727. png_debug(1, "in png_write_info_before_PLTE\n");
  195728. if (png_ptr == NULL || info_ptr == NULL)
  195729. return;
  195730. if (!(png_ptr->mode & PNG_WROTE_INFO_BEFORE_PLTE))
  195731. {
  195732. png_write_sig(png_ptr); /* write PNG signature */
  195733. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  195734. if((png_ptr->mode&PNG_HAVE_PNG_SIGNATURE)&&(png_ptr->mng_features_permitted))
  195735. {
  195736. png_warning(png_ptr,"MNG features are not allowed in a PNG datastream");
  195737. png_ptr->mng_features_permitted=0;
  195738. }
  195739. #endif
  195740. /* write IHDR information. */
  195741. png_write_IHDR(png_ptr, info_ptr->width, info_ptr->height,
  195742. info_ptr->bit_depth, info_ptr->color_type, info_ptr->compression_type,
  195743. info_ptr->filter_type,
  195744. #if defined(PNG_WRITE_INTERLACING_SUPPORTED)
  195745. info_ptr->interlace_type);
  195746. #else
  195747. 0);
  195748. #endif
  195749. /* the rest of these check to see if the valid field has the appropriate
  195750. flag set, and if it does, writes the chunk. */
  195751. #if defined(PNG_WRITE_gAMA_SUPPORTED)
  195752. if (info_ptr->valid & PNG_INFO_gAMA)
  195753. {
  195754. # ifdef PNG_FLOATING_POINT_SUPPORTED
  195755. png_write_gAMA(png_ptr, info_ptr->gamma);
  195756. #else
  195757. #ifdef PNG_FIXED_POINT_SUPPORTED
  195758. png_write_gAMA_fixed(png_ptr, info_ptr->int_gamma);
  195759. # endif
  195760. #endif
  195761. }
  195762. #endif
  195763. #if defined(PNG_WRITE_sRGB_SUPPORTED)
  195764. if (info_ptr->valid & PNG_INFO_sRGB)
  195765. png_write_sRGB(png_ptr, (int)info_ptr->srgb_intent);
  195766. #endif
  195767. #if defined(PNG_WRITE_iCCP_SUPPORTED)
  195768. if (info_ptr->valid & PNG_INFO_iCCP)
  195769. png_write_iCCP(png_ptr, info_ptr->iccp_name, PNG_COMPRESSION_TYPE_BASE,
  195770. info_ptr->iccp_profile, (int)info_ptr->iccp_proflen);
  195771. #endif
  195772. #if defined(PNG_WRITE_sBIT_SUPPORTED)
  195773. if (info_ptr->valid & PNG_INFO_sBIT)
  195774. png_write_sBIT(png_ptr, &(info_ptr->sig_bit), info_ptr->color_type);
  195775. #endif
  195776. #if defined(PNG_WRITE_cHRM_SUPPORTED)
  195777. if (info_ptr->valid & PNG_INFO_cHRM)
  195778. {
  195779. #ifdef PNG_FLOATING_POINT_SUPPORTED
  195780. png_write_cHRM(png_ptr,
  195781. info_ptr->x_white, info_ptr->y_white,
  195782. info_ptr->x_red, info_ptr->y_red,
  195783. info_ptr->x_green, info_ptr->y_green,
  195784. info_ptr->x_blue, info_ptr->y_blue);
  195785. #else
  195786. # ifdef PNG_FIXED_POINT_SUPPORTED
  195787. png_write_cHRM_fixed(png_ptr,
  195788. info_ptr->int_x_white, info_ptr->int_y_white,
  195789. info_ptr->int_x_red, info_ptr->int_y_red,
  195790. info_ptr->int_x_green, info_ptr->int_y_green,
  195791. info_ptr->int_x_blue, info_ptr->int_y_blue);
  195792. # endif
  195793. #endif
  195794. }
  195795. #endif
  195796. #if defined(PNG_WRITE_UNKNOWN_CHUNKS_SUPPORTED)
  195797. if (info_ptr->unknown_chunks_num)
  195798. {
  195799. png_unknown_chunk *up;
  195800. png_debug(5, "writing extra chunks\n");
  195801. for (up = info_ptr->unknown_chunks;
  195802. up < info_ptr->unknown_chunks + info_ptr->unknown_chunks_num;
  195803. up++)
  195804. {
  195805. int keep=png_handle_as_unknown(png_ptr, up->name);
  195806. if (keep != PNG_HANDLE_CHUNK_NEVER &&
  195807. up->location && !(up->location & PNG_HAVE_PLTE) &&
  195808. !(up->location & PNG_HAVE_IDAT) &&
  195809. ((up->name[3] & 0x20) || keep == PNG_HANDLE_CHUNK_ALWAYS ||
  195810. (png_ptr->flags & PNG_FLAG_KEEP_UNSAFE_CHUNKS)))
  195811. {
  195812. png_write_chunk(png_ptr, up->name, up->data, up->size);
  195813. }
  195814. }
  195815. }
  195816. #endif
  195817. png_ptr->mode |= PNG_WROTE_INFO_BEFORE_PLTE;
  195818. }
  195819. }
  195820. void PNGAPI
  195821. png_write_info(png_structp png_ptr, png_infop info_ptr)
  195822. {
  195823. #if defined(PNG_WRITE_TEXT_SUPPORTED) || defined(PNG_WRITE_sPLT_SUPPORTED)
  195824. int i;
  195825. #endif
  195826. png_debug(1, "in png_write_info\n");
  195827. if (png_ptr == NULL || info_ptr == NULL)
  195828. return;
  195829. png_write_info_before_PLTE(png_ptr, info_ptr);
  195830. if (info_ptr->valid & PNG_INFO_PLTE)
  195831. png_write_PLTE(png_ptr, info_ptr->palette,
  195832. (png_uint_32)info_ptr->num_palette);
  195833. else if (info_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  195834. png_error(png_ptr, "Valid palette required for paletted images");
  195835. #if defined(PNG_WRITE_tRNS_SUPPORTED)
  195836. if (info_ptr->valid & PNG_INFO_tRNS)
  195837. {
  195838. #if defined(PNG_WRITE_INVERT_ALPHA_SUPPORTED)
  195839. /* invert the alpha channel (in tRNS) */
  195840. if ((png_ptr->transformations & PNG_INVERT_ALPHA) &&
  195841. info_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  195842. {
  195843. int j;
  195844. for (j=0; j<(int)info_ptr->num_trans; j++)
  195845. info_ptr->trans[j] = (png_byte)(255 - info_ptr->trans[j]);
  195846. }
  195847. #endif
  195848. png_write_tRNS(png_ptr, info_ptr->trans, &(info_ptr->trans_values),
  195849. info_ptr->num_trans, info_ptr->color_type);
  195850. }
  195851. #endif
  195852. #if defined(PNG_WRITE_bKGD_SUPPORTED)
  195853. if (info_ptr->valid & PNG_INFO_bKGD)
  195854. png_write_bKGD(png_ptr, &(info_ptr->background), info_ptr->color_type);
  195855. #endif
  195856. #if defined(PNG_WRITE_hIST_SUPPORTED)
  195857. if (info_ptr->valid & PNG_INFO_hIST)
  195858. png_write_hIST(png_ptr, info_ptr->hist, info_ptr->num_palette);
  195859. #endif
  195860. #if defined(PNG_WRITE_oFFs_SUPPORTED)
  195861. if (info_ptr->valid & PNG_INFO_oFFs)
  195862. png_write_oFFs(png_ptr, info_ptr->x_offset, info_ptr->y_offset,
  195863. info_ptr->offset_unit_type);
  195864. #endif
  195865. #if defined(PNG_WRITE_pCAL_SUPPORTED)
  195866. if (info_ptr->valid & PNG_INFO_pCAL)
  195867. png_write_pCAL(png_ptr, info_ptr->pcal_purpose, info_ptr->pcal_X0,
  195868. info_ptr->pcal_X1, info_ptr->pcal_type, info_ptr->pcal_nparams,
  195869. info_ptr->pcal_units, info_ptr->pcal_params);
  195870. #endif
  195871. #if defined(PNG_WRITE_sCAL_SUPPORTED)
  195872. if (info_ptr->valid & PNG_INFO_sCAL)
  195873. #if defined(PNG_FLOATING_POINT_SUPPORTED) && !defined(PNG_NO_STDIO)
  195874. png_write_sCAL(png_ptr, (int)info_ptr->scal_unit,
  195875. info_ptr->scal_pixel_width, info_ptr->scal_pixel_height);
  195876. #else
  195877. #ifdef PNG_FIXED_POINT_SUPPORTED
  195878. png_write_sCAL_s(png_ptr, (int)info_ptr->scal_unit,
  195879. info_ptr->scal_s_width, info_ptr->scal_s_height);
  195880. #else
  195881. png_warning(png_ptr,
  195882. "png_write_sCAL not supported; sCAL chunk not written.");
  195883. #endif
  195884. #endif
  195885. #endif
  195886. #if defined(PNG_WRITE_pHYs_SUPPORTED)
  195887. if (info_ptr->valid & PNG_INFO_pHYs)
  195888. png_write_pHYs(png_ptr, info_ptr->x_pixels_per_unit,
  195889. info_ptr->y_pixels_per_unit, info_ptr->phys_unit_type);
  195890. #endif
  195891. #if defined(PNG_WRITE_tIME_SUPPORTED)
  195892. if (info_ptr->valid & PNG_INFO_tIME)
  195893. {
  195894. png_write_tIME(png_ptr, &(info_ptr->mod_time));
  195895. png_ptr->mode |= PNG_WROTE_tIME;
  195896. }
  195897. #endif
  195898. #if defined(PNG_WRITE_sPLT_SUPPORTED)
  195899. if (info_ptr->valid & PNG_INFO_sPLT)
  195900. for (i = 0; i < (int)info_ptr->splt_palettes_num; i++)
  195901. png_write_sPLT(png_ptr, info_ptr->splt_palettes + i);
  195902. #endif
  195903. #if defined(PNG_WRITE_TEXT_SUPPORTED)
  195904. /* Check to see if we need to write text chunks */
  195905. for (i = 0; i < info_ptr->num_text; i++)
  195906. {
  195907. png_debug2(2, "Writing header text chunk %d, type %d\n", i,
  195908. info_ptr->text[i].compression);
  195909. /* an internationalized chunk? */
  195910. if (info_ptr->text[i].compression > 0)
  195911. {
  195912. #if defined(PNG_WRITE_iTXt_SUPPORTED)
  195913. /* write international chunk */
  195914. png_write_iTXt(png_ptr,
  195915. info_ptr->text[i].compression,
  195916. info_ptr->text[i].key,
  195917. info_ptr->text[i].lang,
  195918. info_ptr->text[i].lang_key,
  195919. info_ptr->text[i].text);
  195920. #else
  195921. png_warning(png_ptr, "Unable to write international text");
  195922. #endif
  195923. /* Mark this chunk as written */
  195924. info_ptr->text[i].compression = PNG_TEXT_COMPRESSION_NONE_WR;
  195925. }
  195926. /* If we want a compressed text chunk */
  195927. else if (info_ptr->text[i].compression == PNG_TEXT_COMPRESSION_zTXt)
  195928. {
  195929. #if defined(PNG_WRITE_zTXt_SUPPORTED)
  195930. /* write compressed chunk */
  195931. png_write_zTXt(png_ptr, info_ptr->text[i].key,
  195932. info_ptr->text[i].text, 0,
  195933. info_ptr->text[i].compression);
  195934. #else
  195935. png_warning(png_ptr, "Unable to write compressed text");
  195936. #endif
  195937. /* Mark this chunk as written */
  195938. info_ptr->text[i].compression = PNG_TEXT_COMPRESSION_zTXt_WR;
  195939. }
  195940. else if (info_ptr->text[i].compression == PNG_TEXT_COMPRESSION_NONE)
  195941. {
  195942. #if defined(PNG_WRITE_tEXt_SUPPORTED)
  195943. /* write uncompressed chunk */
  195944. png_write_tEXt(png_ptr, info_ptr->text[i].key,
  195945. info_ptr->text[i].text,
  195946. 0);
  195947. #else
  195948. png_warning(png_ptr, "Unable to write uncompressed text");
  195949. #endif
  195950. /* Mark this chunk as written */
  195951. info_ptr->text[i].compression = PNG_TEXT_COMPRESSION_NONE_WR;
  195952. }
  195953. }
  195954. #endif
  195955. #if defined(PNG_WRITE_UNKNOWN_CHUNKS_SUPPORTED)
  195956. if (info_ptr->unknown_chunks_num)
  195957. {
  195958. png_unknown_chunk *up;
  195959. png_debug(5, "writing extra chunks\n");
  195960. for (up = info_ptr->unknown_chunks;
  195961. up < info_ptr->unknown_chunks + info_ptr->unknown_chunks_num;
  195962. up++)
  195963. {
  195964. int keep=png_handle_as_unknown(png_ptr, up->name);
  195965. if (keep != PNG_HANDLE_CHUNK_NEVER &&
  195966. up->location && (up->location & PNG_HAVE_PLTE) &&
  195967. !(up->location & PNG_HAVE_IDAT) &&
  195968. ((up->name[3] & 0x20) || keep == PNG_HANDLE_CHUNK_ALWAYS ||
  195969. (png_ptr->flags & PNG_FLAG_KEEP_UNSAFE_CHUNKS)))
  195970. {
  195971. png_write_chunk(png_ptr, up->name, up->data, up->size);
  195972. }
  195973. }
  195974. }
  195975. #endif
  195976. }
  195977. /* Writes the end of the PNG file. If you don't want to write comments or
  195978. * time information, you can pass NULL for info. If you already wrote these
  195979. * in png_write_info(), do not write them again here. If you have long
  195980. * comments, I suggest writing them here, and compressing them.
  195981. */
  195982. void PNGAPI
  195983. png_write_end(png_structp png_ptr, png_infop info_ptr)
  195984. {
  195985. png_debug(1, "in png_write_end\n");
  195986. if (png_ptr == NULL)
  195987. return;
  195988. if (!(png_ptr->mode & PNG_HAVE_IDAT))
  195989. png_error(png_ptr, "No IDATs written into file");
  195990. /* see if user wants us to write information chunks */
  195991. if (info_ptr != NULL)
  195992. {
  195993. #if defined(PNG_WRITE_TEXT_SUPPORTED)
  195994. int i; /* local index variable */
  195995. #endif
  195996. #if defined(PNG_WRITE_tIME_SUPPORTED)
  195997. /* check to see if user has supplied a time chunk */
  195998. if ((info_ptr->valid & PNG_INFO_tIME) &&
  195999. !(png_ptr->mode & PNG_WROTE_tIME))
  196000. png_write_tIME(png_ptr, &(info_ptr->mod_time));
  196001. #endif
  196002. #if defined(PNG_WRITE_TEXT_SUPPORTED)
  196003. /* loop through comment chunks */
  196004. for (i = 0; i < info_ptr->num_text; i++)
  196005. {
  196006. png_debug2(2, "Writing trailer text chunk %d, type %d\n", i,
  196007. info_ptr->text[i].compression);
  196008. /* an internationalized chunk? */
  196009. if (info_ptr->text[i].compression > 0)
  196010. {
  196011. #if defined(PNG_WRITE_iTXt_SUPPORTED)
  196012. /* write international chunk */
  196013. png_write_iTXt(png_ptr,
  196014. info_ptr->text[i].compression,
  196015. info_ptr->text[i].key,
  196016. info_ptr->text[i].lang,
  196017. info_ptr->text[i].lang_key,
  196018. info_ptr->text[i].text);
  196019. #else
  196020. png_warning(png_ptr, "Unable to write international text");
  196021. #endif
  196022. /* Mark this chunk as written */
  196023. info_ptr->text[i].compression = PNG_TEXT_COMPRESSION_NONE_WR;
  196024. }
  196025. else if (info_ptr->text[i].compression >= PNG_TEXT_COMPRESSION_zTXt)
  196026. {
  196027. #if defined(PNG_WRITE_zTXt_SUPPORTED)
  196028. /* write compressed chunk */
  196029. png_write_zTXt(png_ptr, info_ptr->text[i].key,
  196030. info_ptr->text[i].text, 0,
  196031. info_ptr->text[i].compression);
  196032. #else
  196033. png_warning(png_ptr, "Unable to write compressed text");
  196034. #endif
  196035. /* Mark this chunk as written */
  196036. info_ptr->text[i].compression = PNG_TEXT_COMPRESSION_zTXt_WR;
  196037. }
  196038. else if (info_ptr->text[i].compression == PNG_TEXT_COMPRESSION_NONE)
  196039. {
  196040. #if defined(PNG_WRITE_tEXt_SUPPORTED)
  196041. /* write uncompressed chunk */
  196042. png_write_tEXt(png_ptr, info_ptr->text[i].key,
  196043. info_ptr->text[i].text, 0);
  196044. #else
  196045. png_warning(png_ptr, "Unable to write uncompressed text");
  196046. #endif
  196047. /* Mark this chunk as written */
  196048. info_ptr->text[i].compression = PNG_TEXT_COMPRESSION_NONE_WR;
  196049. }
  196050. }
  196051. #endif
  196052. #if defined(PNG_WRITE_UNKNOWN_CHUNKS_SUPPORTED)
  196053. if (info_ptr->unknown_chunks_num)
  196054. {
  196055. png_unknown_chunk *up;
  196056. png_debug(5, "writing extra chunks\n");
  196057. for (up = info_ptr->unknown_chunks;
  196058. up < info_ptr->unknown_chunks + info_ptr->unknown_chunks_num;
  196059. up++)
  196060. {
  196061. int keep=png_handle_as_unknown(png_ptr, up->name);
  196062. if (keep != PNG_HANDLE_CHUNK_NEVER &&
  196063. up->location && (up->location & PNG_AFTER_IDAT) &&
  196064. ((up->name[3] & 0x20) || keep == PNG_HANDLE_CHUNK_ALWAYS ||
  196065. (png_ptr->flags & PNG_FLAG_KEEP_UNSAFE_CHUNKS)))
  196066. {
  196067. png_write_chunk(png_ptr, up->name, up->data, up->size);
  196068. }
  196069. }
  196070. }
  196071. #endif
  196072. }
  196073. png_ptr->mode |= PNG_AFTER_IDAT;
  196074. /* write end of PNG file */
  196075. png_write_IEND(png_ptr);
  196076. }
  196077. #if defined(PNG_WRITE_tIME_SUPPORTED)
  196078. #if !defined(_WIN32_WCE)
  196079. /* "time.h" functions are not supported on WindowsCE */
  196080. void PNGAPI
  196081. png_convert_from_struct_tm(png_timep ptime, struct tm FAR * ttime)
  196082. {
  196083. png_debug(1, "in png_convert_from_struct_tm\n");
  196084. ptime->year = (png_uint_16)(1900 + ttime->tm_year);
  196085. ptime->month = (png_byte)(ttime->tm_mon + 1);
  196086. ptime->day = (png_byte)ttime->tm_mday;
  196087. ptime->hour = (png_byte)ttime->tm_hour;
  196088. ptime->minute = (png_byte)ttime->tm_min;
  196089. ptime->second = (png_byte)ttime->tm_sec;
  196090. }
  196091. void PNGAPI
  196092. png_convert_from_time_t(png_timep ptime, time_t ttime)
  196093. {
  196094. struct tm *tbuf;
  196095. png_debug(1, "in png_convert_from_time_t\n");
  196096. tbuf = gmtime(&ttime);
  196097. png_convert_from_struct_tm(ptime, tbuf);
  196098. }
  196099. #endif
  196100. #endif
  196101. /* Initialize png_ptr structure, and allocate any memory needed */
  196102. png_structp PNGAPI
  196103. png_create_write_struct(png_const_charp user_png_ver, png_voidp error_ptr,
  196104. png_error_ptr error_fn, png_error_ptr warn_fn)
  196105. {
  196106. #ifdef PNG_USER_MEM_SUPPORTED
  196107. return (png_create_write_struct_2(user_png_ver, error_ptr, error_fn,
  196108. warn_fn, png_voidp_NULL, png_malloc_ptr_NULL, png_free_ptr_NULL));
  196109. }
  196110. /* Alternate initialize png_ptr structure, and allocate any memory needed */
  196111. png_structp PNGAPI
  196112. png_create_write_struct_2(png_const_charp user_png_ver, png_voidp error_ptr,
  196113. png_error_ptr error_fn, png_error_ptr warn_fn, png_voidp mem_ptr,
  196114. png_malloc_ptr malloc_fn, png_free_ptr free_fn)
  196115. {
  196116. #endif /* PNG_USER_MEM_SUPPORTED */
  196117. png_structp png_ptr;
  196118. #ifdef PNG_SETJMP_SUPPORTED
  196119. #ifdef USE_FAR_KEYWORD
  196120. jmp_buf jmpbuf;
  196121. #endif
  196122. #endif
  196123. int i;
  196124. png_debug(1, "in png_create_write_struct\n");
  196125. #ifdef PNG_USER_MEM_SUPPORTED
  196126. png_ptr = (png_structp)png_create_struct_2(PNG_STRUCT_PNG,
  196127. (png_malloc_ptr)malloc_fn, (png_voidp)mem_ptr);
  196128. #else
  196129. png_ptr = (png_structp)png_create_struct(PNG_STRUCT_PNG);
  196130. #endif /* PNG_USER_MEM_SUPPORTED */
  196131. if (png_ptr == NULL)
  196132. return (NULL);
  196133. /* added at libpng-1.2.6 */
  196134. #ifdef PNG_SET_USER_LIMITS_SUPPORTED
  196135. png_ptr->user_width_max=PNG_USER_WIDTH_MAX;
  196136. png_ptr->user_height_max=PNG_USER_HEIGHT_MAX;
  196137. #endif
  196138. #ifdef PNG_SETJMP_SUPPORTED
  196139. #ifdef USE_FAR_KEYWORD
  196140. if (setjmp(jmpbuf))
  196141. #else
  196142. if (setjmp(png_ptr->jmpbuf))
  196143. #endif
  196144. {
  196145. png_free(png_ptr, png_ptr->zbuf);
  196146. png_ptr->zbuf=NULL;
  196147. png_destroy_struct(png_ptr);
  196148. return (NULL);
  196149. }
  196150. #ifdef USE_FAR_KEYWORD
  196151. png_memcpy(png_ptr->jmpbuf,jmpbuf,png_sizeof(jmp_buf));
  196152. #endif
  196153. #endif
  196154. #ifdef PNG_USER_MEM_SUPPORTED
  196155. png_set_mem_fn(png_ptr, mem_ptr, malloc_fn, free_fn);
  196156. #endif /* PNG_USER_MEM_SUPPORTED */
  196157. png_set_error_fn(png_ptr, error_ptr, error_fn, warn_fn);
  196158. i=0;
  196159. do
  196160. {
  196161. if(user_png_ver[i] != png_libpng_ver[i])
  196162. png_ptr->flags |= PNG_FLAG_LIBRARY_MISMATCH;
  196163. } while (png_libpng_ver[i++]);
  196164. if (png_ptr->flags & PNG_FLAG_LIBRARY_MISMATCH)
  196165. {
  196166. /* Libpng 0.90 and later are binary incompatible with libpng 0.89, so
  196167. * we must recompile any applications that use any older library version.
  196168. * For versions after libpng 1.0, we will be compatible, so we need
  196169. * only check the first digit.
  196170. */
  196171. if (user_png_ver == NULL || user_png_ver[0] != png_libpng_ver[0] ||
  196172. (user_png_ver[0] == '1' && user_png_ver[2] != png_libpng_ver[2]) ||
  196173. (user_png_ver[0] == '0' && user_png_ver[2] < '9'))
  196174. {
  196175. #if !defined(PNG_NO_STDIO) && !defined(_WIN32_WCE)
  196176. char msg[80];
  196177. if (user_png_ver)
  196178. {
  196179. png_snprintf(msg, 80,
  196180. "Application was compiled with png.h from libpng-%.20s",
  196181. user_png_ver);
  196182. png_warning(png_ptr, msg);
  196183. }
  196184. png_snprintf(msg, 80,
  196185. "Application is running with png.c from libpng-%.20s",
  196186. png_libpng_ver);
  196187. png_warning(png_ptr, msg);
  196188. #endif
  196189. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  196190. png_ptr->flags=0;
  196191. #endif
  196192. png_error(png_ptr,
  196193. "Incompatible libpng version in application and library");
  196194. }
  196195. }
  196196. /* initialize zbuf - compression buffer */
  196197. png_ptr->zbuf_size = PNG_ZBUF_SIZE;
  196198. png_ptr->zbuf = (png_bytep)png_malloc(png_ptr,
  196199. (png_uint_32)png_ptr->zbuf_size);
  196200. png_set_write_fn(png_ptr, png_voidp_NULL, png_rw_ptr_NULL,
  196201. png_flush_ptr_NULL);
  196202. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  196203. png_set_filter_heuristics(png_ptr, PNG_FILTER_HEURISTIC_DEFAULT,
  196204. 1, png_doublep_NULL, png_doublep_NULL);
  196205. #endif
  196206. #ifdef PNG_SETJMP_SUPPORTED
  196207. /* Applications that neglect to set up their own setjmp() and then encounter
  196208. a png_error() will longjmp here. Since the jmpbuf is then meaningless we
  196209. abort instead of returning. */
  196210. #ifdef USE_FAR_KEYWORD
  196211. if (setjmp(jmpbuf))
  196212. PNG_ABORT();
  196213. png_memcpy(png_ptr->jmpbuf,jmpbuf,png_sizeof(jmp_buf));
  196214. #else
  196215. if (setjmp(png_ptr->jmpbuf))
  196216. PNG_ABORT();
  196217. #endif
  196218. #endif
  196219. return (png_ptr);
  196220. }
  196221. /* Initialize png_ptr structure, and allocate any memory needed */
  196222. #if defined(PNG_1_0_X) || defined(PNG_1_2_X)
  196223. /* Deprecated. */
  196224. #undef png_write_init
  196225. void PNGAPI
  196226. png_write_init(png_structp png_ptr)
  196227. {
  196228. /* We only come here via pre-1.0.7-compiled applications */
  196229. png_write_init_2(png_ptr, "1.0.6 or earlier", 0, 0);
  196230. }
  196231. void PNGAPI
  196232. png_write_init_2(png_structp png_ptr, png_const_charp user_png_ver,
  196233. png_size_t png_struct_size, png_size_t png_info_size)
  196234. {
  196235. /* We only come here via pre-1.0.12-compiled applications */
  196236. if(png_ptr == NULL) return;
  196237. #if !defined(PNG_NO_STDIO) && !defined(_WIN32_WCE)
  196238. if(png_sizeof(png_struct) > png_struct_size ||
  196239. png_sizeof(png_info) > png_info_size)
  196240. {
  196241. char msg[80];
  196242. png_ptr->warning_fn=NULL;
  196243. if (user_png_ver)
  196244. {
  196245. png_snprintf(msg, 80,
  196246. "Application was compiled with png.h from libpng-%.20s",
  196247. user_png_ver);
  196248. png_warning(png_ptr, msg);
  196249. }
  196250. png_snprintf(msg, 80,
  196251. "Application is running with png.c from libpng-%.20s",
  196252. png_libpng_ver);
  196253. png_warning(png_ptr, msg);
  196254. }
  196255. #endif
  196256. if(png_sizeof(png_struct) > png_struct_size)
  196257. {
  196258. png_ptr->error_fn=NULL;
  196259. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  196260. png_ptr->flags=0;
  196261. #endif
  196262. png_error(png_ptr,
  196263. "The png struct allocated by the application for writing is too small.");
  196264. }
  196265. if(png_sizeof(png_info) > png_info_size)
  196266. {
  196267. png_ptr->error_fn=NULL;
  196268. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  196269. png_ptr->flags=0;
  196270. #endif
  196271. png_error(png_ptr,
  196272. "The info struct allocated by the application for writing is too small.");
  196273. }
  196274. png_write_init_3(&png_ptr, user_png_ver, png_struct_size);
  196275. }
  196276. #endif /* PNG_1_0_X || PNG_1_2_X */
  196277. void PNGAPI
  196278. png_write_init_3(png_structpp ptr_ptr, png_const_charp user_png_ver,
  196279. png_size_t png_struct_size)
  196280. {
  196281. png_structp png_ptr=*ptr_ptr;
  196282. #ifdef PNG_SETJMP_SUPPORTED
  196283. jmp_buf tmp_jmp; /* to save current jump buffer */
  196284. #endif
  196285. int i = 0;
  196286. if (png_ptr == NULL)
  196287. return;
  196288. do
  196289. {
  196290. if (user_png_ver[i] != png_libpng_ver[i])
  196291. {
  196292. #ifdef PNG_LEGACY_SUPPORTED
  196293. png_ptr->flags |= PNG_FLAG_LIBRARY_MISMATCH;
  196294. #else
  196295. png_ptr->warning_fn=NULL;
  196296. png_warning(png_ptr,
  196297. "Application uses deprecated png_write_init() and should be recompiled.");
  196298. break;
  196299. #endif
  196300. }
  196301. } while (png_libpng_ver[i++]);
  196302. png_debug(1, "in png_write_init_3\n");
  196303. #ifdef PNG_SETJMP_SUPPORTED
  196304. /* save jump buffer and error functions */
  196305. png_memcpy(tmp_jmp, png_ptr->jmpbuf, png_sizeof (jmp_buf));
  196306. #endif
  196307. if (png_sizeof(png_struct) > png_struct_size)
  196308. {
  196309. png_destroy_struct(png_ptr);
  196310. png_ptr = (png_structp)png_create_struct(PNG_STRUCT_PNG);
  196311. *ptr_ptr = png_ptr;
  196312. }
  196313. /* reset all variables to 0 */
  196314. png_memset(png_ptr, 0, png_sizeof (png_struct));
  196315. /* added at libpng-1.2.6 */
  196316. #ifdef PNG_SET_USER_LIMITS_SUPPORTED
  196317. png_ptr->user_width_max=PNG_USER_WIDTH_MAX;
  196318. png_ptr->user_height_max=PNG_USER_HEIGHT_MAX;
  196319. #endif
  196320. #ifdef PNG_SETJMP_SUPPORTED
  196321. /* restore jump buffer */
  196322. png_memcpy(png_ptr->jmpbuf, tmp_jmp, png_sizeof (jmp_buf));
  196323. #endif
  196324. png_set_write_fn(png_ptr, png_voidp_NULL, png_rw_ptr_NULL,
  196325. png_flush_ptr_NULL);
  196326. /* initialize zbuf - compression buffer */
  196327. png_ptr->zbuf_size = PNG_ZBUF_SIZE;
  196328. png_ptr->zbuf = (png_bytep)png_malloc(png_ptr,
  196329. (png_uint_32)png_ptr->zbuf_size);
  196330. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  196331. png_set_filter_heuristics(png_ptr, PNG_FILTER_HEURISTIC_DEFAULT,
  196332. 1, png_doublep_NULL, png_doublep_NULL);
  196333. #endif
  196334. }
  196335. /* Write a few rows of image data. If the image is interlaced,
  196336. * either you will have to write the 7 sub images, or, if you
  196337. * have called png_set_interlace_handling(), you will have to
  196338. * "write" the image seven times.
  196339. */
  196340. void PNGAPI
  196341. png_write_rows(png_structp png_ptr, png_bytepp row,
  196342. png_uint_32 num_rows)
  196343. {
  196344. png_uint_32 i; /* row counter */
  196345. png_bytepp rp; /* row pointer */
  196346. png_debug(1, "in png_write_rows\n");
  196347. if (png_ptr == NULL)
  196348. return;
  196349. /* loop through the rows */
  196350. for (i = 0, rp = row; i < num_rows; i++, rp++)
  196351. {
  196352. png_write_row(png_ptr, *rp);
  196353. }
  196354. }
  196355. /* Write the image. You only need to call this function once, even
  196356. * if you are writing an interlaced image.
  196357. */
  196358. void PNGAPI
  196359. png_write_image(png_structp png_ptr, png_bytepp image)
  196360. {
  196361. png_uint_32 i; /* row index */
  196362. int pass, num_pass; /* pass variables */
  196363. png_bytepp rp; /* points to current row */
  196364. if (png_ptr == NULL)
  196365. return;
  196366. png_debug(1, "in png_write_image\n");
  196367. #if defined(PNG_WRITE_INTERLACING_SUPPORTED)
  196368. /* intialize interlace handling. If image is not interlaced,
  196369. this will set pass to 1 */
  196370. num_pass = png_set_interlace_handling(png_ptr);
  196371. #else
  196372. num_pass = 1;
  196373. #endif
  196374. /* loop through passes */
  196375. for (pass = 0; pass < num_pass; pass++)
  196376. {
  196377. /* loop through image */
  196378. for (i = 0, rp = image; i < png_ptr->height; i++, rp++)
  196379. {
  196380. png_write_row(png_ptr, *rp);
  196381. }
  196382. }
  196383. }
  196384. /* called by user to write a row of image data */
  196385. void PNGAPI
  196386. png_write_row(png_structp png_ptr, png_bytep row)
  196387. {
  196388. if (png_ptr == NULL)
  196389. return;
  196390. png_debug2(1, "in png_write_row (row %ld, pass %d)\n",
  196391. png_ptr->row_number, png_ptr->pass);
  196392. /* initialize transformations and other stuff if first time */
  196393. if (png_ptr->row_number == 0 && png_ptr->pass == 0)
  196394. {
  196395. /* make sure we wrote the header info */
  196396. if (!(png_ptr->mode & PNG_WROTE_INFO_BEFORE_PLTE))
  196397. png_error(png_ptr,
  196398. "png_write_info was never called before png_write_row.");
  196399. /* check for transforms that have been set but were defined out */
  196400. #if !defined(PNG_WRITE_INVERT_SUPPORTED) && defined(PNG_READ_INVERT_SUPPORTED)
  196401. if (png_ptr->transformations & PNG_INVERT_MONO)
  196402. png_warning(png_ptr, "PNG_WRITE_INVERT_SUPPORTED is not defined.");
  196403. #endif
  196404. #if !defined(PNG_WRITE_FILLER_SUPPORTED) && defined(PNG_READ_FILLER_SUPPORTED)
  196405. if (png_ptr->transformations & PNG_FILLER)
  196406. png_warning(png_ptr, "PNG_WRITE_FILLER_SUPPORTED is not defined.");
  196407. #endif
  196408. #if !defined(PNG_WRITE_PACKSWAP_SUPPORTED) && defined(PNG_READ_PACKSWAP_SUPPORTED)
  196409. if (png_ptr->transformations & PNG_PACKSWAP)
  196410. png_warning(png_ptr, "PNG_WRITE_PACKSWAP_SUPPORTED is not defined.");
  196411. #endif
  196412. #if !defined(PNG_WRITE_PACK_SUPPORTED) && defined(PNG_READ_PACK_SUPPORTED)
  196413. if (png_ptr->transformations & PNG_PACK)
  196414. png_warning(png_ptr, "PNG_WRITE_PACK_SUPPORTED is not defined.");
  196415. #endif
  196416. #if !defined(PNG_WRITE_SHIFT_SUPPORTED) && defined(PNG_READ_SHIFT_SUPPORTED)
  196417. if (png_ptr->transformations & PNG_SHIFT)
  196418. png_warning(png_ptr, "PNG_WRITE_SHIFT_SUPPORTED is not defined.");
  196419. #endif
  196420. #if !defined(PNG_WRITE_BGR_SUPPORTED) && defined(PNG_READ_BGR_SUPPORTED)
  196421. if (png_ptr->transformations & PNG_BGR)
  196422. png_warning(png_ptr, "PNG_WRITE_BGR_SUPPORTED is not defined.");
  196423. #endif
  196424. #if !defined(PNG_WRITE_SWAP_SUPPORTED) && defined(PNG_READ_SWAP_SUPPORTED)
  196425. if (png_ptr->transformations & PNG_SWAP_BYTES)
  196426. png_warning(png_ptr, "PNG_WRITE_SWAP_SUPPORTED is not defined.");
  196427. #endif
  196428. png_write_start_row(png_ptr);
  196429. }
  196430. #if defined(PNG_WRITE_INTERLACING_SUPPORTED)
  196431. /* if interlaced and not interested in row, return */
  196432. if (png_ptr->interlaced && (png_ptr->transformations & PNG_INTERLACE))
  196433. {
  196434. switch (png_ptr->pass)
  196435. {
  196436. case 0:
  196437. if (png_ptr->row_number & 0x07)
  196438. {
  196439. png_write_finish_row(png_ptr);
  196440. return;
  196441. }
  196442. break;
  196443. case 1:
  196444. if ((png_ptr->row_number & 0x07) || png_ptr->width < 5)
  196445. {
  196446. png_write_finish_row(png_ptr);
  196447. return;
  196448. }
  196449. break;
  196450. case 2:
  196451. if ((png_ptr->row_number & 0x07) != 4)
  196452. {
  196453. png_write_finish_row(png_ptr);
  196454. return;
  196455. }
  196456. break;
  196457. case 3:
  196458. if ((png_ptr->row_number & 0x03) || png_ptr->width < 3)
  196459. {
  196460. png_write_finish_row(png_ptr);
  196461. return;
  196462. }
  196463. break;
  196464. case 4:
  196465. if ((png_ptr->row_number & 0x03) != 2)
  196466. {
  196467. png_write_finish_row(png_ptr);
  196468. return;
  196469. }
  196470. break;
  196471. case 5:
  196472. if ((png_ptr->row_number & 0x01) || png_ptr->width < 2)
  196473. {
  196474. png_write_finish_row(png_ptr);
  196475. return;
  196476. }
  196477. break;
  196478. case 6:
  196479. if (!(png_ptr->row_number & 0x01))
  196480. {
  196481. png_write_finish_row(png_ptr);
  196482. return;
  196483. }
  196484. break;
  196485. }
  196486. }
  196487. #endif
  196488. /* set up row info for transformations */
  196489. png_ptr->row_info.color_type = png_ptr->color_type;
  196490. png_ptr->row_info.width = png_ptr->usr_width;
  196491. png_ptr->row_info.channels = png_ptr->usr_channels;
  196492. png_ptr->row_info.bit_depth = png_ptr->usr_bit_depth;
  196493. png_ptr->row_info.pixel_depth = (png_byte)(png_ptr->row_info.bit_depth *
  196494. png_ptr->row_info.channels);
  196495. png_ptr->row_info.rowbytes = PNG_ROWBYTES(png_ptr->row_info.pixel_depth,
  196496. png_ptr->row_info.width);
  196497. png_debug1(3, "row_info->color_type = %d\n", png_ptr->row_info.color_type);
  196498. png_debug1(3, "row_info->width = %lu\n", png_ptr->row_info.width);
  196499. png_debug1(3, "row_info->channels = %d\n", png_ptr->row_info.channels);
  196500. png_debug1(3, "row_info->bit_depth = %d\n", png_ptr->row_info.bit_depth);
  196501. png_debug1(3, "row_info->pixel_depth = %d\n", png_ptr->row_info.pixel_depth);
  196502. png_debug1(3, "row_info->rowbytes = %lu\n", png_ptr->row_info.rowbytes);
  196503. /* Copy user's row into buffer, leaving room for filter byte. */
  196504. png_memcpy_check(png_ptr, png_ptr->row_buf + 1, row,
  196505. png_ptr->row_info.rowbytes);
  196506. #if defined(PNG_WRITE_INTERLACING_SUPPORTED)
  196507. /* handle interlacing */
  196508. if (png_ptr->interlaced && png_ptr->pass < 6 &&
  196509. (png_ptr->transformations & PNG_INTERLACE))
  196510. {
  196511. png_do_write_interlace(&(png_ptr->row_info),
  196512. png_ptr->row_buf + 1, png_ptr->pass);
  196513. /* this should always get caught above, but still ... */
  196514. if (!(png_ptr->row_info.width))
  196515. {
  196516. png_write_finish_row(png_ptr);
  196517. return;
  196518. }
  196519. }
  196520. #endif
  196521. /* handle other transformations */
  196522. if (png_ptr->transformations)
  196523. png_do_write_transformations(png_ptr);
  196524. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  196525. /* Write filter_method 64 (intrapixel differencing) only if
  196526. * 1. Libpng was compiled with PNG_MNG_FEATURES_SUPPORTED and
  196527. * 2. Libpng did not write a PNG signature (this filter_method is only
  196528. * used in PNG datastreams that are embedded in MNG datastreams) and
  196529. * 3. The application called png_permit_mng_features with a mask that
  196530. * included PNG_FLAG_MNG_FILTER_64 and
  196531. * 4. The filter_method is 64 and
  196532. * 5. The color_type is RGB or RGBA
  196533. */
  196534. if((png_ptr->mng_features_permitted & PNG_FLAG_MNG_FILTER_64) &&
  196535. (png_ptr->filter_type == PNG_INTRAPIXEL_DIFFERENCING))
  196536. {
  196537. /* Intrapixel differencing */
  196538. png_do_write_intrapixel(&(png_ptr->row_info), png_ptr->row_buf + 1);
  196539. }
  196540. #endif
  196541. /* Find a filter if necessary, filter the row and write it out. */
  196542. png_write_find_filter(png_ptr, &(png_ptr->row_info));
  196543. if (png_ptr->write_row_fn != NULL)
  196544. (*(png_ptr->write_row_fn))(png_ptr, png_ptr->row_number, png_ptr->pass);
  196545. }
  196546. #if defined(PNG_WRITE_FLUSH_SUPPORTED)
  196547. /* Set the automatic flush interval or 0 to turn flushing off */
  196548. void PNGAPI
  196549. png_set_flush(png_structp png_ptr, int nrows)
  196550. {
  196551. png_debug(1, "in png_set_flush\n");
  196552. if (png_ptr == NULL)
  196553. return;
  196554. png_ptr->flush_dist = (nrows < 0 ? 0 : nrows);
  196555. }
  196556. /* flush the current output buffers now */
  196557. void PNGAPI
  196558. png_write_flush(png_structp png_ptr)
  196559. {
  196560. int wrote_IDAT;
  196561. png_debug(1, "in png_write_flush\n");
  196562. if (png_ptr == NULL)
  196563. return;
  196564. /* We have already written out all of the data */
  196565. if (png_ptr->row_number >= png_ptr->num_rows)
  196566. return;
  196567. do
  196568. {
  196569. int ret;
  196570. /* compress the data */
  196571. ret = deflate(&png_ptr->zstream, Z_SYNC_FLUSH);
  196572. wrote_IDAT = 0;
  196573. /* check for compression errors */
  196574. if (ret != Z_OK)
  196575. {
  196576. if (png_ptr->zstream.msg != NULL)
  196577. png_error(png_ptr, png_ptr->zstream.msg);
  196578. else
  196579. png_error(png_ptr, "zlib error");
  196580. }
  196581. if (!(png_ptr->zstream.avail_out))
  196582. {
  196583. /* write the IDAT and reset the zlib output buffer */
  196584. png_write_IDAT(png_ptr, png_ptr->zbuf,
  196585. png_ptr->zbuf_size);
  196586. png_ptr->zstream.next_out = png_ptr->zbuf;
  196587. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  196588. wrote_IDAT = 1;
  196589. }
  196590. } while(wrote_IDAT == 1);
  196591. /* If there is any data left to be output, write it into a new IDAT */
  196592. if (png_ptr->zbuf_size != png_ptr->zstream.avail_out)
  196593. {
  196594. /* write the IDAT and reset the zlib output buffer */
  196595. png_write_IDAT(png_ptr, png_ptr->zbuf,
  196596. png_ptr->zbuf_size - png_ptr->zstream.avail_out);
  196597. png_ptr->zstream.next_out = png_ptr->zbuf;
  196598. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  196599. }
  196600. png_ptr->flush_rows = 0;
  196601. png_flush(png_ptr);
  196602. }
  196603. #endif /* PNG_WRITE_FLUSH_SUPPORTED */
  196604. /* free all memory used by the write */
  196605. void PNGAPI
  196606. png_destroy_write_struct(png_structpp png_ptr_ptr, png_infopp info_ptr_ptr)
  196607. {
  196608. png_structp png_ptr = NULL;
  196609. png_infop info_ptr = NULL;
  196610. #ifdef PNG_USER_MEM_SUPPORTED
  196611. png_free_ptr free_fn = NULL;
  196612. png_voidp mem_ptr = NULL;
  196613. #endif
  196614. png_debug(1, "in png_destroy_write_struct\n");
  196615. if (png_ptr_ptr != NULL)
  196616. {
  196617. png_ptr = *png_ptr_ptr;
  196618. #ifdef PNG_USER_MEM_SUPPORTED
  196619. free_fn = png_ptr->free_fn;
  196620. mem_ptr = png_ptr->mem_ptr;
  196621. #endif
  196622. }
  196623. if (info_ptr_ptr != NULL)
  196624. info_ptr = *info_ptr_ptr;
  196625. if (info_ptr != NULL)
  196626. {
  196627. png_free_data(png_ptr, info_ptr, PNG_FREE_ALL, -1);
  196628. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  196629. if (png_ptr->num_chunk_list)
  196630. {
  196631. png_free(png_ptr, png_ptr->chunk_list);
  196632. png_ptr->chunk_list=NULL;
  196633. png_ptr->num_chunk_list=0;
  196634. }
  196635. #endif
  196636. #ifdef PNG_USER_MEM_SUPPORTED
  196637. png_destroy_struct_2((png_voidp)info_ptr, (png_free_ptr)free_fn,
  196638. (png_voidp)mem_ptr);
  196639. #else
  196640. png_destroy_struct((png_voidp)info_ptr);
  196641. #endif
  196642. *info_ptr_ptr = NULL;
  196643. }
  196644. if (png_ptr != NULL)
  196645. {
  196646. png_write_destroy(png_ptr);
  196647. #ifdef PNG_USER_MEM_SUPPORTED
  196648. png_destroy_struct_2((png_voidp)png_ptr, (png_free_ptr)free_fn,
  196649. (png_voidp)mem_ptr);
  196650. #else
  196651. png_destroy_struct((png_voidp)png_ptr);
  196652. #endif
  196653. *png_ptr_ptr = NULL;
  196654. }
  196655. }
  196656. /* Free any memory used in png_ptr struct (old method) */
  196657. void /* PRIVATE */
  196658. png_write_destroy(png_structp png_ptr)
  196659. {
  196660. #ifdef PNG_SETJMP_SUPPORTED
  196661. jmp_buf tmp_jmp; /* save jump buffer */
  196662. #endif
  196663. png_error_ptr error_fn;
  196664. png_error_ptr warning_fn;
  196665. png_voidp error_ptr;
  196666. #ifdef PNG_USER_MEM_SUPPORTED
  196667. png_free_ptr free_fn;
  196668. #endif
  196669. png_debug(1, "in png_write_destroy\n");
  196670. /* free any memory zlib uses */
  196671. deflateEnd(&png_ptr->zstream);
  196672. /* free our memory. png_free checks NULL for us. */
  196673. png_free(png_ptr, png_ptr->zbuf);
  196674. png_free(png_ptr, png_ptr->row_buf);
  196675. png_free(png_ptr, png_ptr->prev_row);
  196676. png_free(png_ptr, png_ptr->sub_row);
  196677. png_free(png_ptr, png_ptr->up_row);
  196678. png_free(png_ptr, png_ptr->avg_row);
  196679. png_free(png_ptr, png_ptr->paeth_row);
  196680. #if defined(PNG_TIME_RFC1123_SUPPORTED)
  196681. png_free(png_ptr, png_ptr->time_buffer);
  196682. #endif
  196683. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  196684. png_free(png_ptr, png_ptr->prev_filters);
  196685. png_free(png_ptr, png_ptr->filter_weights);
  196686. png_free(png_ptr, png_ptr->inv_filter_weights);
  196687. png_free(png_ptr, png_ptr->filter_costs);
  196688. png_free(png_ptr, png_ptr->inv_filter_costs);
  196689. #endif
  196690. #ifdef PNG_SETJMP_SUPPORTED
  196691. /* reset structure */
  196692. png_memcpy(tmp_jmp, png_ptr->jmpbuf, png_sizeof (jmp_buf));
  196693. #endif
  196694. error_fn = png_ptr->error_fn;
  196695. warning_fn = png_ptr->warning_fn;
  196696. error_ptr = png_ptr->error_ptr;
  196697. #ifdef PNG_USER_MEM_SUPPORTED
  196698. free_fn = png_ptr->free_fn;
  196699. #endif
  196700. png_memset(png_ptr, 0, png_sizeof (png_struct));
  196701. png_ptr->error_fn = error_fn;
  196702. png_ptr->warning_fn = warning_fn;
  196703. png_ptr->error_ptr = error_ptr;
  196704. #ifdef PNG_USER_MEM_SUPPORTED
  196705. png_ptr->free_fn = free_fn;
  196706. #endif
  196707. #ifdef PNG_SETJMP_SUPPORTED
  196708. png_memcpy(png_ptr->jmpbuf, tmp_jmp, png_sizeof (jmp_buf));
  196709. #endif
  196710. }
  196711. /* Allow the application to select one or more row filters to use. */
  196712. void PNGAPI
  196713. png_set_filter(png_structp png_ptr, int method, int filters)
  196714. {
  196715. png_debug(1, "in png_set_filter\n");
  196716. if (png_ptr == NULL)
  196717. return;
  196718. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  196719. if((png_ptr->mng_features_permitted & PNG_FLAG_MNG_FILTER_64) &&
  196720. (method == PNG_INTRAPIXEL_DIFFERENCING))
  196721. method = PNG_FILTER_TYPE_BASE;
  196722. #endif
  196723. if (method == PNG_FILTER_TYPE_BASE)
  196724. {
  196725. switch (filters & (PNG_ALL_FILTERS | 0x07))
  196726. {
  196727. #ifndef PNG_NO_WRITE_FILTER
  196728. case 5:
  196729. case 6:
  196730. case 7: png_warning(png_ptr, "Unknown row filter for method 0");
  196731. #endif /* PNG_NO_WRITE_FILTER */
  196732. case PNG_FILTER_VALUE_NONE:
  196733. png_ptr->do_filter=PNG_FILTER_NONE; break;
  196734. #ifndef PNG_NO_WRITE_FILTER
  196735. case PNG_FILTER_VALUE_SUB:
  196736. png_ptr->do_filter=PNG_FILTER_SUB; break;
  196737. case PNG_FILTER_VALUE_UP:
  196738. png_ptr->do_filter=PNG_FILTER_UP; break;
  196739. case PNG_FILTER_VALUE_AVG:
  196740. png_ptr->do_filter=PNG_FILTER_AVG; break;
  196741. case PNG_FILTER_VALUE_PAETH:
  196742. png_ptr->do_filter=PNG_FILTER_PAETH; break;
  196743. default: png_ptr->do_filter = (png_byte)filters; break;
  196744. #else
  196745. default: png_warning(png_ptr, "Unknown row filter for method 0");
  196746. #endif /* PNG_NO_WRITE_FILTER */
  196747. }
  196748. /* If we have allocated the row_buf, this means we have already started
  196749. * with the image and we should have allocated all of the filter buffers
  196750. * that have been selected. If prev_row isn't already allocated, then
  196751. * it is too late to start using the filters that need it, since we
  196752. * will be missing the data in the previous row. If an application
  196753. * wants to start and stop using particular filters during compression,
  196754. * it should start out with all of the filters, and then add and
  196755. * remove them after the start of compression.
  196756. */
  196757. if (png_ptr->row_buf != NULL)
  196758. {
  196759. #ifndef PNG_NO_WRITE_FILTER
  196760. if ((png_ptr->do_filter & PNG_FILTER_SUB) && png_ptr->sub_row == NULL)
  196761. {
  196762. png_ptr->sub_row = (png_bytep)png_malloc(png_ptr,
  196763. (png_ptr->rowbytes + 1));
  196764. png_ptr->sub_row[0] = PNG_FILTER_VALUE_SUB;
  196765. }
  196766. if ((png_ptr->do_filter & PNG_FILTER_UP) && png_ptr->up_row == NULL)
  196767. {
  196768. if (png_ptr->prev_row == NULL)
  196769. {
  196770. png_warning(png_ptr, "Can't add Up filter after starting");
  196771. png_ptr->do_filter &= ~PNG_FILTER_UP;
  196772. }
  196773. else
  196774. {
  196775. png_ptr->up_row = (png_bytep)png_malloc(png_ptr,
  196776. (png_ptr->rowbytes + 1));
  196777. png_ptr->up_row[0] = PNG_FILTER_VALUE_UP;
  196778. }
  196779. }
  196780. if ((png_ptr->do_filter & PNG_FILTER_AVG) && png_ptr->avg_row == NULL)
  196781. {
  196782. if (png_ptr->prev_row == NULL)
  196783. {
  196784. png_warning(png_ptr, "Can't add Average filter after starting");
  196785. png_ptr->do_filter &= ~PNG_FILTER_AVG;
  196786. }
  196787. else
  196788. {
  196789. png_ptr->avg_row = (png_bytep)png_malloc(png_ptr,
  196790. (png_ptr->rowbytes + 1));
  196791. png_ptr->avg_row[0] = PNG_FILTER_VALUE_AVG;
  196792. }
  196793. }
  196794. if ((png_ptr->do_filter & PNG_FILTER_PAETH) &&
  196795. png_ptr->paeth_row == NULL)
  196796. {
  196797. if (png_ptr->prev_row == NULL)
  196798. {
  196799. png_warning(png_ptr, "Can't add Paeth filter after starting");
  196800. png_ptr->do_filter &= (png_byte)(~PNG_FILTER_PAETH);
  196801. }
  196802. else
  196803. {
  196804. png_ptr->paeth_row = (png_bytep)png_malloc(png_ptr,
  196805. (png_ptr->rowbytes + 1));
  196806. png_ptr->paeth_row[0] = PNG_FILTER_VALUE_PAETH;
  196807. }
  196808. }
  196809. if (png_ptr->do_filter == PNG_NO_FILTERS)
  196810. #endif /* PNG_NO_WRITE_FILTER */
  196811. png_ptr->do_filter = PNG_FILTER_NONE;
  196812. }
  196813. }
  196814. else
  196815. png_error(png_ptr, "Unknown custom filter method");
  196816. }
  196817. /* This allows us to influence the way in which libpng chooses the "best"
  196818. * filter for the current scanline. While the "minimum-sum-of-absolute-
  196819. * differences metric is relatively fast and effective, there is some
  196820. * question as to whether it can be improved upon by trying to keep the
  196821. * filtered data going to zlib more consistent, hopefully resulting in
  196822. * better compression.
  196823. */
  196824. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED) /* GRR 970116 */
  196825. void PNGAPI
  196826. png_set_filter_heuristics(png_structp png_ptr, int heuristic_method,
  196827. int num_weights, png_doublep filter_weights,
  196828. png_doublep filter_costs)
  196829. {
  196830. int i;
  196831. png_debug(1, "in png_set_filter_heuristics\n");
  196832. if (png_ptr == NULL)
  196833. return;
  196834. if (heuristic_method >= PNG_FILTER_HEURISTIC_LAST)
  196835. {
  196836. png_warning(png_ptr, "Unknown filter heuristic method");
  196837. return;
  196838. }
  196839. if (heuristic_method == PNG_FILTER_HEURISTIC_DEFAULT)
  196840. {
  196841. heuristic_method = PNG_FILTER_HEURISTIC_UNWEIGHTED;
  196842. }
  196843. if (num_weights < 0 || filter_weights == NULL ||
  196844. heuristic_method == PNG_FILTER_HEURISTIC_UNWEIGHTED)
  196845. {
  196846. num_weights = 0;
  196847. }
  196848. png_ptr->num_prev_filters = (png_byte)num_weights;
  196849. png_ptr->heuristic_method = (png_byte)heuristic_method;
  196850. if (num_weights > 0)
  196851. {
  196852. if (png_ptr->prev_filters == NULL)
  196853. {
  196854. png_ptr->prev_filters = (png_bytep)png_malloc(png_ptr,
  196855. (png_uint_32)(png_sizeof(png_byte) * num_weights));
  196856. /* To make sure that the weighting starts out fairly */
  196857. for (i = 0; i < num_weights; i++)
  196858. {
  196859. png_ptr->prev_filters[i] = 255;
  196860. }
  196861. }
  196862. if (png_ptr->filter_weights == NULL)
  196863. {
  196864. png_ptr->filter_weights = (png_uint_16p)png_malloc(png_ptr,
  196865. (png_uint_32)(png_sizeof(png_uint_16) * num_weights));
  196866. png_ptr->inv_filter_weights = (png_uint_16p)png_malloc(png_ptr,
  196867. (png_uint_32)(png_sizeof(png_uint_16) * num_weights));
  196868. for (i = 0; i < num_weights; i++)
  196869. {
  196870. png_ptr->inv_filter_weights[i] =
  196871. png_ptr->filter_weights[i] = PNG_WEIGHT_FACTOR;
  196872. }
  196873. }
  196874. for (i = 0; i < num_weights; i++)
  196875. {
  196876. if (filter_weights[i] < 0.0)
  196877. {
  196878. png_ptr->inv_filter_weights[i] =
  196879. png_ptr->filter_weights[i] = PNG_WEIGHT_FACTOR;
  196880. }
  196881. else
  196882. {
  196883. png_ptr->inv_filter_weights[i] =
  196884. (png_uint_16)((double)PNG_WEIGHT_FACTOR*filter_weights[i]+0.5);
  196885. png_ptr->filter_weights[i] =
  196886. (png_uint_16)((double)PNG_WEIGHT_FACTOR/filter_weights[i]+0.5);
  196887. }
  196888. }
  196889. }
  196890. /* If, in the future, there are other filter methods, this would
  196891. * need to be based on png_ptr->filter.
  196892. */
  196893. if (png_ptr->filter_costs == NULL)
  196894. {
  196895. png_ptr->filter_costs = (png_uint_16p)png_malloc(png_ptr,
  196896. (png_uint_32)(png_sizeof(png_uint_16) * PNG_FILTER_VALUE_LAST));
  196897. png_ptr->inv_filter_costs = (png_uint_16p)png_malloc(png_ptr,
  196898. (png_uint_32)(png_sizeof(png_uint_16) * PNG_FILTER_VALUE_LAST));
  196899. for (i = 0; i < PNG_FILTER_VALUE_LAST; i++)
  196900. {
  196901. png_ptr->inv_filter_costs[i] =
  196902. png_ptr->filter_costs[i] = PNG_COST_FACTOR;
  196903. }
  196904. }
  196905. /* Here is where we set the relative costs of the different filters. We
  196906. * should take the desired compression level into account when setting
  196907. * the costs, so that Paeth, for instance, has a high relative cost at low
  196908. * compression levels, while it has a lower relative cost at higher
  196909. * compression settings. The filter types are in order of increasing
  196910. * relative cost, so it would be possible to do this with an algorithm.
  196911. */
  196912. for (i = 0; i < PNG_FILTER_VALUE_LAST; i++)
  196913. {
  196914. if (filter_costs == NULL || filter_costs[i] < 0.0)
  196915. {
  196916. png_ptr->inv_filter_costs[i] =
  196917. png_ptr->filter_costs[i] = PNG_COST_FACTOR;
  196918. }
  196919. else if (filter_costs[i] >= 1.0)
  196920. {
  196921. png_ptr->inv_filter_costs[i] =
  196922. (png_uint_16)((double)PNG_COST_FACTOR / filter_costs[i] + 0.5);
  196923. png_ptr->filter_costs[i] =
  196924. (png_uint_16)((double)PNG_COST_FACTOR * filter_costs[i] + 0.5);
  196925. }
  196926. }
  196927. }
  196928. #endif /* PNG_WRITE_WEIGHTED_FILTER_SUPPORTED */
  196929. void PNGAPI
  196930. png_set_compression_level(png_structp png_ptr, int level)
  196931. {
  196932. png_debug(1, "in png_set_compression_level\n");
  196933. if (png_ptr == NULL)
  196934. return;
  196935. png_ptr->flags |= PNG_FLAG_ZLIB_CUSTOM_LEVEL;
  196936. png_ptr->zlib_level = level;
  196937. }
  196938. void PNGAPI
  196939. png_set_compression_mem_level(png_structp png_ptr, int mem_level)
  196940. {
  196941. png_debug(1, "in png_set_compression_mem_level\n");
  196942. if (png_ptr == NULL)
  196943. return;
  196944. png_ptr->flags |= PNG_FLAG_ZLIB_CUSTOM_MEM_LEVEL;
  196945. png_ptr->zlib_mem_level = mem_level;
  196946. }
  196947. void PNGAPI
  196948. png_set_compression_strategy(png_structp png_ptr, int strategy)
  196949. {
  196950. png_debug(1, "in png_set_compression_strategy\n");
  196951. if (png_ptr == NULL)
  196952. return;
  196953. png_ptr->flags |= PNG_FLAG_ZLIB_CUSTOM_STRATEGY;
  196954. png_ptr->zlib_strategy = strategy;
  196955. }
  196956. void PNGAPI
  196957. png_set_compression_window_bits(png_structp png_ptr, int window_bits)
  196958. {
  196959. if (png_ptr == NULL)
  196960. return;
  196961. if (window_bits > 15)
  196962. png_warning(png_ptr, "Only compression windows <= 32k supported by PNG");
  196963. else if (window_bits < 8)
  196964. png_warning(png_ptr, "Only compression windows >= 256 supported by PNG");
  196965. #ifndef WBITS_8_OK
  196966. /* avoid libpng bug with 256-byte windows */
  196967. if (window_bits == 8)
  196968. {
  196969. png_warning(png_ptr, "Compression window is being reset to 512");
  196970. window_bits=9;
  196971. }
  196972. #endif
  196973. png_ptr->flags |= PNG_FLAG_ZLIB_CUSTOM_WINDOW_BITS;
  196974. png_ptr->zlib_window_bits = window_bits;
  196975. }
  196976. void PNGAPI
  196977. png_set_compression_method(png_structp png_ptr, int method)
  196978. {
  196979. png_debug(1, "in png_set_compression_method\n");
  196980. if (png_ptr == NULL)
  196981. return;
  196982. if (method != 8)
  196983. png_warning(png_ptr, "Only compression method 8 is supported by PNG");
  196984. png_ptr->flags |= PNG_FLAG_ZLIB_CUSTOM_METHOD;
  196985. png_ptr->zlib_method = method;
  196986. }
  196987. void PNGAPI
  196988. png_set_write_status_fn(png_structp png_ptr, png_write_status_ptr write_row_fn)
  196989. {
  196990. if (png_ptr == NULL)
  196991. return;
  196992. png_ptr->write_row_fn = write_row_fn;
  196993. }
  196994. #if defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED)
  196995. void PNGAPI
  196996. png_set_write_user_transform_fn(png_structp png_ptr, png_user_transform_ptr
  196997. write_user_transform_fn)
  196998. {
  196999. png_debug(1, "in png_set_write_user_transform_fn\n");
  197000. if (png_ptr == NULL)
  197001. return;
  197002. png_ptr->transformations |= PNG_USER_TRANSFORM;
  197003. png_ptr->write_user_transform_fn = write_user_transform_fn;
  197004. }
  197005. #endif
  197006. #if defined(PNG_INFO_IMAGE_SUPPORTED)
  197007. void PNGAPI
  197008. png_write_png(png_structp png_ptr, png_infop info_ptr,
  197009. int transforms, voidp params)
  197010. {
  197011. if (png_ptr == NULL || info_ptr == NULL)
  197012. return;
  197013. #if defined(PNG_WRITE_INVERT_ALPHA_SUPPORTED)
  197014. /* invert the alpha channel from opacity to transparency */
  197015. if (transforms & PNG_TRANSFORM_INVERT_ALPHA)
  197016. png_set_invert_alpha(png_ptr);
  197017. #endif
  197018. /* Write the file header information. */
  197019. png_write_info(png_ptr, info_ptr);
  197020. /* ------ these transformations don't touch the info structure ------- */
  197021. #if defined(PNG_WRITE_INVERT_SUPPORTED)
  197022. /* invert monochrome pixels */
  197023. if (transforms & PNG_TRANSFORM_INVERT_MONO)
  197024. png_set_invert_mono(png_ptr);
  197025. #endif
  197026. #if defined(PNG_WRITE_SHIFT_SUPPORTED)
  197027. /* Shift the pixels up to a legal bit depth and fill in
  197028. * as appropriate to correctly scale the image.
  197029. */
  197030. if ((transforms & PNG_TRANSFORM_SHIFT)
  197031. && (info_ptr->valid & PNG_INFO_sBIT))
  197032. png_set_shift(png_ptr, &info_ptr->sig_bit);
  197033. #endif
  197034. #if defined(PNG_WRITE_PACK_SUPPORTED)
  197035. /* pack pixels into bytes */
  197036. if (transforms & PNG_TRANSFORM_PACKING)
  197037. png_set_packing(png_ptr);
  197038. #endif
  197039. #if defined(PNG_WRITE_SWAP_ALPHA_SUPPORTED)
  197040. /* swap location of alpha bytes from ARGB to RGBA */
  197041. if (transforms & PNG_TRANSFORM_SWAP_ALPHA)
  197042. png_set_swap_alpha(png_ptr);
  197043. #endif
  197044. #if defined(PNG_WRITE_FILLER_SUPPORTED)
  197045. /* Get rid of filler (OR ALPHA) bytes, pack XRGB/RGBX/ARGB/RGBA into
  197046. * RGB (4 channels -> 3 channels). The second parameter is not used.
  197047. */
  197048. if (transforms & PNG_TRANSFORM_STRIP_FILLER)
  197049. png_set_filler(png_ptr, 0, PNG_FILLER_BEFORE);
  197050. #endif
  197051. #if defined(PNG_WRITE_BGR_SUPPORTED)
  197052. /* flip BGR pixels to RGB */
  197053. if (transforms & PNG_TRANSFORM_BGR)
  197054. png_set_bgr(png_ptr);
  197055. #endif
  197056. #if defined(PNG_WRITE_SWAP_SUPPORTED)
  197057. /* swap bytes of 16-bit files to most significant byte first */
  197058. if (transforms & PNG_TRANSFORM_SWAP_ENDIAN)
  197059. png_set_swap(png_ptr);
  197060. #endif
  197061. #if defined(PNG_WRITE_PACKSWAP_SUPPORTED)
  197062. /* swap bits of 1, 2, 4 bit packed pixel formats */
  197063. if (transforms & PNG_TRANSFORM_PACKSWAP)
  197064. png_set_packswap(png_ptr);
  197065. #endif
  197066. /* ----------------------- end of transformations ------------------- */
  197067. /* write the bits */
  197068. if (info_ptr->valid & PNG_INFO_IDAT)
  197069. png_write_image(png_ptr, info_ptr->row_pointers);
  197070. /* It is REQUIRED to call this to finish writing the rest of the file */
  197071. png_write_end(png_ptr, info_ptr);
  197072. transforms = transforms; /* quiet compiler warnings */
  197073. params = params;
  197074. }
  197075. #endif
  197076. #endif /* PNG_WRITE_SUPPORTED */
  197077. /*** End of inlined file: pngwrite.c ***/
  197078. /*** Start of inlined file: pngwtran.c ***/
  197079. /* pngwtran.c - transforms the data in a row for PNG writers
  197080. *
  197081. * Last changed in libpng 1.2.9 April 14, 2006
  197082. * For conditions of distribution and use, see copyright notice in png.h
  197083. * Copyright (c) 1998-2006 Glenn Randers-Pehrson
  197084. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  197085. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  197086. */
  197087. #define PNG_INTERNAL
  197088. #ifdef PNG_WRITE_SUPPORTED
  197089. /* Transform the data according to the user's wishes. The order of
  197090. * transformations is significant.
  197091. */
  197092. void /* PRIVATE */
  197093. png_do_write_transformations(png_structp png_ptr)
  197094. {
  197095. png_debug(1, "in png_do_write_transformations\n");
  197096. if (png_ptr == NULL)
  197097. return;
  197098. #if defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED)
  197099. if (png_ptr->transformations & PNG_USER_TRANSFORM)
  197100. if(png_ptr->write_user_transform_fn != NULL)
  197101. (*(png_ptr->write_user_transform_fn)) /* user write transform function */
  197102. (png_ptr, /* png_ptr */
  197103. &(png_ptr->row_info), /* row_info: */
  197104. /* png_uint_32 width; width of row */
  197105. /* png_uint_32 rowbytes; number of bytes in row */
  197106. /* png_byte color_type; color type of pixels */
  197107. /* png_byte bit_depth; bit depth of samples */
  197108. /* png_byte channels; number of channels (1-4) */
  197109. /* png_byte pixel_depth; bits per pixel (depth*channels) */
  197110. png_ptr->row_buf + 1); /* start of pixel data for row */
  197111. #endif
  197112. #if defined(PNG_WRITE_FILLER_SUPPORTED)
  197113. if (png_ptr->transformations & PNG_FILLER)
  197114. png_do_strip_filler(&(png_ptr->row_info), png_ptr->row_buf + 1,
  197115. png_ptr->flags);
  197116. #endif
  197117. #if defined(PNG_WRITE_PACKSWAP_SUPPORTED)
  197118. if (png_ptr->transformations & PNG_PACKSWAP)
  197119. png_do_packswap(&(png_ptr->row_info), png_ptr->row_buf + 1);
  197120. #endif
  197121. #if defined(PNG_WRITE_PACK_SUPPORTED)
  197122. if (png_ptr->transformations & PNG_PACK)
  197123. png_do_pack(&(png_ptr->row_info), png_ptr->row_buf + 1,
  197124. (png_uint_32)png_ptr->bit_depth);
  197125. #endif
  197126. #if defined(PNG_WRITE_SWAP_SUPPORTED)
  197127. if (png_ptr->transformations & PNG_SWAP_BYTES)
  197128. png_do_swap(&(png_ptr->row_info), png_ptr->row_buf + 1);
  197129. #endif
  197130. #if defined(PNG_WRITE_SHIFT_SUPPORTED)
  197131. if (png_ptr->transformations & PNG_SHIFT)
  197132. png_do_shift(&(png_ptr->row_info), png_ptr->row_buf + 1,
  197133. &(png_ptr->shift));
  197134. #endif
  197135. #if defined(PNG_WRITE_SWAP_ALPHA_SUPPORTED)
  197136. if (png_ptr->transformations & PNG_SWAP_ALPHA)
  197137. png_do_write_swap_alpha(&(png_ptr->row_info), png_ptr->row_buf + 1);
  197138. #endif
  197139. #if defined(PNG_WRITE_INVERT_ALPHA_SUPPORTED)
  197140. if (png_ptr->transformations & PNG_INVERT_ALPHA)
  197141. png_do_write_invert_alpha(&(png_ptr->row_info), png_ptr->row_buf + 1);
  197142. #endif
  197143. #if defined(PNG_WRITE_BGR_SUPPORTED)
  197144. if (png_ptr->transformations & PNG_BGR)
  197145. png_do_bgr(&(png_ptr->row_info), png_ptr->row_buf + 1);
  197146. #endif
  197147. #if defined(PNG_WRITE_INVERT_SUPPORTED)
  197148. if (png_ptr->transformations & PNG_INVERT_MONO)
  197149. png_do_invert(&(png_ptr->row_info), png_ptr->row_buf + 1);
  197150. #endif
  197151. }
  197152. #if defined(PNG_WRITE_PACK_SUPPORTED)
  197153. /* Pack pixels into bytes. Pass the true bit depth in bit_depth. The
  197154. * row_info bit depth should be 8 (one pixel per byte). The channels
  197155. * should be 1 (this only happens on grayscale and paletted images).
  197156. */
  197157. void /* PRIVATE */
  197158. png_do_pack(png_row_infop row_info, png_bytep row, png_uint_32 bit_depth)
  197159. {
  197160. png_debug(1, "in png_do_pack\n");
  197161. if (row_info->bit_depth == 8 &&
  197162. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  197163. row != NULL && row_info != NULL &&
  197164. #endif
  197165. row_info->channels == 1)
  197166. {
  197167. switch ((int)bit_depth)
  197168. {
  197169. case 1:
  197170. {
  197171. png_bytep sp, dp;
  197172. int mask, v;
  197173. png_uint_32 i;
  197174. png_uint_32 row_width = row_info->width;
  197175. sp = row;
  197176. dp = row;
  197177. mask = 0x80;
  197178. v = 0;
  197179. for (i = 0; i < row_width; i++)
  197180. {
  197181. if (*sp != 0)
  197182. v |= mask;
  197183. sp++;
  197184. if (mask > 1)
  197185. mask >>= 1;
  197186. else
  197187. {
  197188. mask = 0x80;
  197189. *dp = (png_byte)v;
  197190. dp++;
  197191. v = 0;
  197192. }
  197193. }
  197194. if (mask != 0x80)
  197195. *dp = (png_byte)v;
  197196. break;
  197197. }
  197198. case 2:
  197199. {
  197200. png_bytep sp, dp;
  197201. int shift, v;
  197202. png_uint_32 i;
  197203. png_uint_32 row_width = row_info->width;
  197204. sp = row;
  197205. dp = row;
  197206. shift = 6;
  197207. v = 0;
  197208. for (i = 0; i < row_width; i++)
  197209. {
  197210. png_byte value;
  197211. value = (png_byte)(*sp & 0x03);
  197212. v |= (value << shift);
  197213. if (shift == 0)
  197214. {
  197215. shift = 6;
  197216. *dp = (png_byte)v;
  197217. dp++;
  197218. v = 0;
  197219. }
  197220. else
  197221. shift -= 2;
  197222. sp++;
  197223. }
  197224. if (shift != 6)
  197225. *dp = (png_byte)v;
  197226. break;
  197227. }
  197228. case 4:
  197229. {
  197230. png_bytep sp, dp;
  197231. int shift, v;
  197232. png_uint_32 i;
  197233. png_uint_32 row_width = row_info->width;
  197234. sp = row;
  197235. dp = row;
  197236. shift = 4;
  197237. v = 0;
  197238. for (i = 0; i < row_width; i++)
  197239. {
  197240. png_byte value;
  197241. value = (png_byte)(*sp & 0x0f);
  197242. v |= (value << shift);
  197243. if (shift == 0)
  197244. {
  197245. shift = 4;
  197246. *dp = (png_byte)v;
  197247. dp++;
  197248. v = 0;
  197249. }
  197250. else
  197251. shift -= 4;
  197252. sp++;
  197253. }
  197254. if (shift != 4)
  197255. *dp = (png_byte)v;
  197256. break;
  197257. }
  197258. }
  197259. row_info->bit_depth = (png_byte)bit_depth;
  197260. row_info->pixel_depth = (png_byte)(bit_depth * row_info->channels);
  197261. row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,
  197262. row_info->width);
  197263. }
  197264. }
  197265. #endif
  197266. #if defined(PNG_WRITE_SHIFT_SUPPORTED)
  197267. /* Shift pixel values to take advantage of whole range. Pass the
  197268. * true number of bits in bit_depth. The row should be packed
  197269. * according to row_info->bit_depth. Thus, if you had a row of
  197270. * bit depth 4, but the pixels only had values from 0 to 7, you
  197271. * would pass 3 as bit_depth, and this routine would translate the
  197272. * data to 0 to 15.
  197273. */
  197274. void /* PRIVATE */
  197275. png_do_shift(png_row_infop row_info, png_bytep row, png_color_8p bit_depth)
  197276. {
  197277. png_debug(1, "in png_do_shift\n");
  197278. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  197279. if (row != NULL && row_info != NULL &&
  197280. #else
  197281. if (
  197282. #endif
  197283. row_info->color_type != PNG_COLOR_TYPE_PALETTE)
  197284. {
  197285. int shift_start[4], shift_dec[4];
  197286. int channels = 0;
  197287. if (row_info->color_type & PNG_COLOR_MASK_COLOR)
  197288. {
  197289. shift_start[channels] = row_info->bit_depth - bit_depth->red;
  197290. shift_dec[channels] = bit_depth->red;
  197291. channels++;
  197292. shift_start[channels] = row_info->bit_depth - bit_depth->green;
  197293. shift_dec[channels] = bit_depth->green;
  197294. channels++;
  197295. shift_start[channels] = row_info->bit_depth - bit_depth->blue;
  197296. shift_dec[channels] = bit_depth->blue;
  197297. channels++;
  197298. }
  197299. else
  197300. {
  197301. shift_start[channels] = row_info->bit_depth - bit_depth->gray;
  197302. shift_dec[channels] = bit_depth->gray;
  197303. channels++;
  197304. }
  197305. if (row_info->color_type & PNG_COLOR_MASK_ALPHA)
  197306. {
  197307. shift_start[channels] = row_info->bit_depth - bit_depth->alpha;
  197308. shift_dec[channels] = bit_depth->alpha;
  197309. channels++;
  197310. }
  197311. /* with low row depths, could only be grayscale, so one channel */
  197312. if (row_info->bit_depth < 8)
  197313. {
  197314. png_bytep bp = row;
  197315. png_uint_32 i;
  197316. png_byte mask;
  197317. png_uint_32 row_bytes = row_info->rowbytes;
  197318. if (bit_depth->gray == 1 && row_info->bit_depth == 2)
  197319. mask = 0x55;
  197320. else if (row_info->bit_depth == 4 && bit_depth->gray == 3)
  197321. mask = 0x11;
  197322. else
  197323. mask = 0xff;
  197324. for (i = 0; i < row_bytes; i++, bp++)
  197325. {
  197326. png_uint_16 v;
  197327. int j;
  197328. v = *bp;
  197329. *bp = 0;
  197330. for (j = shift_start[0]; j > -shift_dec[0]; j -= shift_dec[0])
  197331. {
  197332. if (j > 0)
  197333. *bp |= (png_byte)((v << j) & 0xff);
  197334. else
  197335. *bp |= (png_byte)((v >> (-j)) & mask);
  197336. }
  197337. }
  197338. }
  197339. else if (row_info->bit_depth == 8)
  197340. {
  197341. png_bytep bp = row;
  197342. png_uint_32 i;
  197343. png_uint_32 istop = channels * row_info->width;
  197344. for (i = 0; i < istop; i++, bp++)
  197345. {
  197346. png_uint_16 v;
  197347. int j;
  197348. int c = (int)(i%channels);
  197349. v = *bp;
  197350. *bp = 0;
  197351. for (j = shift_start[c]; j > -shift_dec[c]; j -= shift_dec[c])
  197352. {
  197353. if (j > 0)
  197354. *bp |= (png_byte)((v << j) & 0xff);
  197355. else
  197356. *bp |= (png_byte)((v >> (-j)) & 0xff);
  197357. }
  197358. }
  197359. }
  197360. else
  197361. {
  197362. png_bytep bp;
  197363. png_uint_32 i;
  197364. png_uint_32 istop = channels * row_info->width;
  197365. for (bp = row, i = 0; i < istop; i++)
  197366. {
  197367. int c = (int)(i%channels);
  197368. png_uint_16 value, v;
  197369. int j;
  197370. v = (png_uint_16)(((png_uint_16)(*bp) << 8) + *(bp + 1));
  197371. value = 0;
  197372. for (j = shift_start[c]; j > -shift_dec[c]; j -= shift_dec[c])
  197373. {
  197374. if (j > 0)
  197375. value |= (png_uint_16)((v << j) & (png_uint_16)0xffff);
  197376. else
  197377. value |= (png_uint_16)((v >> (-j)) & (png_uint_16)0xffff);
  197378. }
  197379. *bp++ = (png_byte)(value >> 8);
  197380. *bp++ = (png_byte)(value & 0xff);
  197381. }
  197382. }
  197383. }
  197384. }
  197385. #endif
  197386. #if defined(PNG_WRITE_SWAP_ALPHA_SUPPORTED)
  197387. void /* PRIVATE */
  197388. png_do_write_swap_alpha(png_row_infop row_info, png_bytep row)
  197389. {
  197390. png_debug(1, "in png_do_write_swap_alpha\n");
  197391. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  197392. if (row != NULL && row_info != NULL)
  197393. #endif
  197394. {
  197395. if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  197396. {
  197397. /* This converts from ARGB to RGBA */
  197398. if (row_info->bit_depth == 8)
  197399. {
  197400. png_bytep sp, dp;
  197401. png_uint_32 i;
  197402. png_uint_32 row_width = row_info->width;
  197403. for (i = 0, sp = dp = row; i < row_width; i++)
  197404. {
  197405. png_byte save = *(sp++);
  197406. *(dp++) = *(sp++);
  197407. *(dp++) = *(sp++);
  197408. *(dp++) = *(sp++);
  197409. *(dp++) = save;
  197410. }
  197411. }
  197412. /* This converts from AARRGGBB to RRGGBBAA */
  197413. else
  197414. {
  197415. png_bytep sp, dp;
  197416. png_uint_32 i;
  197417. png_uint_32 row_width = row_info->width;
  197418. for (i = 0, sp = dp = row; i < row_width; i++)
  197419. {
  197420. png_byte save[2];
  197421. save[0] = *(sp++);
  197422. save[1] = *(sp++);
  197423. *(dp++) = *(sp++);
  197424. *(dp++) = *(sp++);
  197425. *(dp++) = *(sp++);
  197426. *(dp++) = *(sp++);
  197427. *(dp++) = *(sp++);
  197428. *(dp++) = *(sp++);
  197429. *(dp++) = save[0];
  197430. *(dp++) = save[1];
  197431. }
  197432. }
  197433. }
  197434. else if (row_info->color_type == PNG_COLOR_TYPE_GRAY_ALPHA)
  197435. {
  197436. /* This converts from AG to GA */
  197437. if (row_info->bit_depth == 8)
  197438. {
  197439. png_bytep sp, dp;
  197440. png_uint_32 i;
  197441. png_uint_32 row_width = row_info->width;
  197442. for (i = 0, sp = dp = row; i < row_width; i++)
  197443. {
  197444. png_byte save = *(sp++);
  197445. *(dp++) = *(sp++);
  197446. *(dp++) = save;
  197447. }
  197448. }
  197449. /* This converts from AAGG to GGAA */
  197450. else
  197451. {
  197452. png_bytep sp, dp;
  197453. png_uint_32 i;
  197454. png_uint_32 row_width = row_info->width;
  197455. for (i = 0, sp = dp = row; i < row_width; i++)
  197456. {
  197457. png_byte save[2];
  197458. save[0] = *(sp++);
  197459. save[1] = *(sp++);
  197460. *(dp++) = *(sp++);
  197461. *(dp++) = *(sp++);
  197462. *(dp++) = save[0];
  197463. *(dp++) = save[1];
  197464. }
  197465. }
  197466. }
  197467. }
  197468. }
  197469. #endif
  197470. #if defined(PNG_WRITE_INVERT_ALPHA_SUPPORTED)
  197471. void /* PRIVATE */
  197472. png_do_write_invert_alpha(png_row_infop row_info, png_bytep row)
  197473. {
  197474. png_debug(1, "in png_do_write_invert_alpha\n");
  197475. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  197476. if (row != NULL && row_info != NULL)
  197477. #endif
  197478. {
  197479. if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  197480. {
  197481. /* This inverts the alpha channel in RGBA */
  197482. if (row_info->bit_depth == 8)
  197483. {
  197484. png_bytep sp, dp;
  197485. png_uint_32 i;
  197486. png_uint_32 row_width = row_info->width;
  197487. for (i = 0, sp = dp = row; i < row_width; i++)
  197488. {
  197489. /* does nothing
  197490. *(dp++) = *(sp++);
  197491. *(dp++) = *(sp++);
  197492. *(dp++) = *(sp++);
  197493. */
  197494. sp+=3; dp = sp;
  197495. *(dp++) = (png_byte)(255 - *(sp++));
  197496. }
  197497. }
  197498. /* This inverts the alpha channel in RRGGBBAA */
  197499. else
  197500. {
  197501. png_bytep sp, dp;
  197502. png_uint_32 i;
  197503. png_uint_32 row_width = row_info->width;
  197504. for (i = 0, sp = dp = row; i < row_width; i++)
  197505. {
  197506. /* does nothing
  197507. *(dp++) = *(sp++);
  197508. *(dp++) = *(sp++);
  197509. *(dp++) = *(sp++);
  197510. *(dp++) = *(sp++);
  197511. *(dp++) = *(sp++);
  197512. *(dp++) = *(sp++);
  197513. */
  197514. sp+=6; dp = sp;
  197515. *(dp++) = (png_byte)(255 - *(sp++));
  197516. *(dp++) = (png_byte)(255 - *(sp++));
  197517. }
  197518. }
  197519. }
  197520. else if (row_info->color_type == PNG_COLOR_TYPE_GRAY_ALPHA)
  197521. {
  197522. /* This inverts the alpha channel in GA */
  197523. if (row_info->bit_depth == 8)
  197524. {
  197525. png_bytep sp, dp;
  197526. png_uint_32 i;
  197527. png_uint_32 row_width = row_info->width;
  197528. for (i = 0, sp = dp = row; i < row_width; i++)
  197529. {
  197530. *(dp++) = *(sp++);
  197531. *(dp++) = (png_byte)(255 - *(sp++));
  197532. }
  197533. }
  197534. /* This inverts the alpha channel in GGAA */
  197535. else
  197536. {
  197537. png_bytep sp, dp;
  197538. png_uint_32 i;
  197539. png_uint_32 row_width = row_info->width;
  197540. for (i = 0, sp = dp = row; i < row_width; i++)
  197541. {
  197542. /* does nothing
  197543. *(dp++) = *(sp++);
  197544. *(dp++) = *(sp++);
  197545. */
  197546. sp+=2; dp = sp;
  197547. *(dp++) = (png_byte)(255 - *(sp++));
  197548. *(dp++) = (png_byte)(255 - *(sp++));
  197549. }
  197550. }
  197551. }
  197552. }
  197553. }
  197554. #endif
  197555. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  197556. /* undoes intrapixel differencing */
  197557. void /* PRIVATE */
  197558. png_do_write_intrapixel(png_row_infop row_info, png_bytep row)
  197559. {
  197560. png_debug(1, "in png_do_write_intrapixel\n");
  197561. if (
  197562. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  197563. row != NULL && row_info != NULL &&
  197564. #endif
  197565. (row_info->color_type & PNG_COLOR_MASK_COLOR))
  197566. {
  197567. int bytes_per_pixel;
  197568. png_uint_32 row_width = row_info->width;
  197569. if (row_info->bit_depth == 8)
  197570. {
  197571. png_bytep rp;
  197572. png_uint_32 i;
  197573. if (row_info->color_type == PNG_COLOR_TYPE_RGB)
  197574. bytes_per_pixel = 3;
  197575. else if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  197576. bytes_per_pixel = 4;
  197577. else
  197578. return;
  197579. for (i = 0, rp = row; i < row_width; i++, rp += bytes_per_pixel)
  197580. {
  197581. *(rp) = (png_byte)((*rp - *(rp+1))&0xff);
  197582. *(rp+2) = (png_byte)((*(rp+2) - *(rp+1))&0xff);
  197583. }
  197584. }
  197585. else if (row_info->bit_depth == 16)
  197586. {
  197587. png_bytep rp;
  197588. png_uint_32 i;
  197589. if (row_info->color_type == PNG_COLOR_TYPE_RGB)
  197590. bytes_per_pixel = 6;
  197591. else if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  197592. bytes_per_pixel = 8;
  197593. else
  197594. return;
  197595. for (i = 0, rp = row; i < row_width; i++, rp += bytes_per_pixel)
  197596. {
  197597. png_uint_32 s0 = (*(rp ) << 8) | *(rp+1);
  197598. png_uint_32 s1 = (*(rp+2) << 8) | *(rp+3);
  197599. png_uint_32 s2 = (*(rp+4) << 8) | *(rp+5);
  197600. png_uint_32 red = (png_uint_32)((s0-s1) & 0xffffL);
  197601. png_uint_32 blue = (png_uint_32)((s2-s1) & 0xffffL);
  197602. *(rp ) = (png_byte)((red >> 8) & 0xff);
  197603. *(rp+1) = (png_byte)(red & 0xff);
  197604. *(rp+4) = (png_byte)((blue >> 8) & 0xff);
  197605. *(rp+5) = (png_byte)(blue & 0xff);
  197606. }
  197607. }
  197608. }
  197609. }
  197610. #endif /* PNG_MNG_FEATURES_SUPPORTED */
  197611. #endif /* PNG_WRITE_SUPPORTED */
  197612. /*** End of inlined file: pngwtran.c ***/
  197613. /*** Start of inlined file: pngwutil.c ***/
  197614. /* pngwutil.c - utilities to write a PNG file
  197615. *
  197616. * Last changed in libpng 1.2.20 Septhember 3, 2007
  197617. * For conditions of distribution and use, see copyright notice in png.h
  197618. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  197619. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  197620. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  197621. */
  197622. #define PNG_INTERNAL
  197623. #ifdef PNG_WRITE_SUPPORTED
  197624. /* Place a 32-bit number into a buffer in PNG byte order. We work
  197625. * with unsigned numbers for convenience, although one supported
  197626. * ancillary chunk uses signed (two's complement) numbers.
  197627. */
  197628. void PNGAPI
  197629. png_save_uint_32(png_bytep buf, png_uint_32 i)
  197630. {
  197631. buf[0] = (png_byte)((i >> 24) & 0xff);
  197632. buf[1] = (png_byte)((i >> 16) & 0xff);
  197633. buf[2] = (png_byte)((i >> 8) & 0xff);
  197634. buf[3] = (png_byte)(i & 0xff);
  197635. }
  197636. /* The png_save_int_32 function assumes integers are stored in two's
  197637. * complement format. If this isn't the case, then this routine needs to
  197638. * be modified to write data in two's complement format.
  197639. */
  197640. void PNGAPI
  197641. png_save_int_32(png_bytep buf, png_int_32 i)
  197642. {
  197643. buf[0] = (png_byte)((i >> 24) & 0xff);
  197644. buf[1] = (png_byte)((i >> 16) & 0xff);
  197645. buf[2] = (png_byte)((i >> 8) & 0xff);
  197646. buf[3] = (png_byte)(i & 0xff);
  197647. }
  197648. /* Place a 16-bit number into a buffer in PNG byte order.
  197649. * The parameter is declared unsigned int, not png_uint_16,
  197650. * just to avoid potential problems on pre-ANSI C compilers.
  197651. */
  197652. void PNGAPI
  197653. png_save_uint_16(png_bytep buf, unsigned int i)
  197654. {
  197655. buf[0] = (png_byte)((i >> 8) & 0xff);
  197656. buf[1] = (png_byte)(i & 0xff);
  197657. }
  197658. /* Write a PNG chunk all at once. The type is an array of ASCII characters
  197659. * representing the chunk name. The array must be at least 4 bytes in
  197660. * length, and does not need to be null terminated. To be safe, pass the
  197661. * pre-defined chunk names here, and if you need a new one, define it
  197662. * where the others are defined. The length is the length of the data.
  197663. * All the data must be present. If that is not possible, use the
  197664. * png_write_chunk_start(), png_write_chunk_data(), and png_write_chunk_end()
  197665. * functions instead.
  197666. */
  197667. void PNGAPI
  197668. png_write_chunk(png_structp png_ptr, png_bytep chunk_name,
  197669. png_bytep data, png_size_t length)
  197670. {
  197671. if(png_ptr == NULL) return;
  197672. png_write_chunk_start(png_ptr, chunk_name, (png_uint_32)length);
  197673. png_write_chunk_data(png_ptr, data, length);
  197674. png_write_chunk_end(png_ptr);
  197675. }
  197676. /* Write the start of a PNG chunk. The type is the chunk type.
  197677. * The total_length is the sum of the lengths of all the data you will be
  197678. * passing in png_write_chunk_data().
  197679. */
  197680. void PNGAPI
  197681. png_write_chunk_start(png_structp png_ptr, png_bytep chunk_name,
  197682. png_uint_32 length)
  197683. {
  197684. png_byte buf[4];
  197685. png_debug2(0, "Writing %s chunk (%lu bytes)\n", chunk_name, length);
  197686. if(png_ptr == NULL) return;
  197687. /* write the length */
  197688. png_save_uint_32(buf, length);
  197689. png_write_data(png_ptr, buf, (png_size_t)4);
  197690. /* write the chunk name */
  197691. png_write_data(png_ptr, chunk_name, (png_size_t)4);
  197692. /* reset the crc and run it over the chunk name */
  197693. png_reset_crc(png_ptr);
  197694. png_calculate_crc(png_ptr, chunk_name, (png_size_t)4);
  197695. }
  197696. /* Write the data of a PNG chunk started with png_write_chunk_start().
  197697. * Note that multiple calls to this function are allowed, and that the
  197698. * sum of the lengths from these calls *must* add up to the total_length
  197699. * given to png_write_chunk_start().
  197700. */
  197701. void PNGAPI
  197702. png_write_chunk_data(png_structp png_ptr, png_bytep data, png_size_t length)
  197703. {
  197704. /* write the data, and run the CRC over it */
  197705. if(png_ptr == NULL) return;
  197706. if (data != NULL && length > 0)
  197707. {
  197708. png_calculate_crc(png_ptr, data, length);
  197709. png_write_data(png_ptr, data, length);
  197710. }
  197711. }
  197712. /* Finish a chunk started with png_write_chunk_start(). */
  197713. void PNGAPI
  197714. png_write_chunk_end(png_structp png_ptr)
  197715. {
  197716. png_byte buf[4];
  197717. if(png_ptr == NULL) return;
  197718. /* write the crc */
  197719. png_save_uint_32(buf, png_ptr->crc);
  197720. png_write_data(png_ptr, buf, (png_size_t)4);
  197721. }
  197722. /* Simple function to write the signature. If we have already written
  197723. * the magic bytes of the signature, or more likely, the PNG stream is
  197724. * being embedded into another stream and doesn't need its own signature,
  197725. * we should call png_set_sig_bytes() to tell libpng how many of the
  197726. * bytes have already been written.
  197727. */
  197728. void /* PRIVATE */
  197729. png_write_sig(png_structp png_ptr)
  197730. {
  197731. png_byte png_signature[8] = {137, 80, 78, 71, 13, 10, 26, 10};
  197732. /* write the rest of the 8 byte signature */
  197733. png_write_data(png_ptr, &png_signature[png_ptr->sig_bytes],
  197734. (png_size_t)8 - png_ptr->sig_bytes);
  197735. if(png_ptr->sig_bytes < 3)
  197736. png_ptr->mode |= PNG_HAVE_PNG_SIGNATURE;
  197737. }
  197738. #if defined(PNG_WRITE_TEXT_SUPPORTED) || defined(PNG_WRITE_iCCP_SUPPORTED)
  197739. /*
  197740. * This pair of functions encapsulates the operation of (a) compressing a
  197741. * text string, and (b) issuing it later as a series of chunk data writes.
  197742. * The compression_state structure is shared context for these functions
  197743. * set up by the caller in order to make the whole mess thread-safe.
  197744. */
  197745. typedef struct
  197746. {
  197747. char *input; /* the uncompressed input data */
  197748. int input_len; /* its length */
  197749. int num_output_ptr; /* number of output pointers used */
  197750. int max_output_ptr; /* size of output_ptr */
  197751. png_charpp output_ptr; /* array of pointers to output */
  197752. } compression_state;
  197753. /* compress given text into storage in the png_ptr structure */
  197754. static int /* PRIVATE */
  197755. png_text_compress(png_structp png_ptr,
  197756. png_charp text, png_size_t text_len, int compression,
  197757. compression_state *comp)
  197758. {
  197759. int ret;
  197760. comp->num_output_ptr = 0;
  197761. comp->max_output_ptr = 0;
  197762. comp->output_ptr = NULL;
  197763. comp->input = NULL;
  197764. comp->input_len = 0;
  197765. /* we may just want to pass the text right through */
  197766. if (compression == PNG_TEXT_COMPRESSION_NONE)
  197767. {
  197768. comp->input = text;
  197769. comp->input_len = text_len;
  197770. return((int)text_len);
  197771. }
  197772. if (compression >= PNG_TEXT_COMPRESSION_LAST)
  197773. {
  197774. #if !defined(PNG_NO_STDIO) && !defined(_WIN32_WCE)
  197775. char msg[50];
  197776. png_snprintf(msg, 50, "Unknown compression type %d", compression);
  197777. png_warning(png_ptr, msg);
  197778. #else
  197779. png_warning(png_ptr, "Unknown compression type");
  197780. #endif
  197781. }
  197782. /* We can't write the chunk until we find out how much data we have,
  197783. * which means we need to run the compressor first and save the
  197784. * output. This shouldn't be a problem, as the vast majority of
  197785. * comments should be reasonable, but we will set up an array of
  197786. * malloc'd pointers to be sure.
  197787. *
  197788. * If we knew the application was well behaved, we could simplify this
  197789. * greatly by assuming we can always malloc an output buffer large
  197790. * enough to hold the compressed text ((1001 * text_len / 1000) + 12)
  197791. * and malloc this directly. The only time this would be a bad idea is
  197792. * if we can't malloc more than 64K and we have 64K of random input
  197793. * data, or if the input string is incredibly large (although this
  197794. * wouldn't cause a failure, just a slowdown due to swapping).
  197795. */
  197796. /* set up the compression buffers */
  197797. png_ptr->zstream.avail_in = (uInt)text_len;
  197798. png_ptr->zstream.next_in = (Bytef *)text;
  197799. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  197800. png_ptr->zstream.next_out = (Bytef *)png_ptr->zbuf;
  197801. /* this is the same compression loop as in png_write_row() */
  197802. do
  197803. {
  197804. /* compress the data */
  197805. ret = deflate(&png_ptr->zstream, Z_NO_FLUSH);
  197806. if (ret != Z_OK)
  197807. {
  197808. /* error */
  197809. if (png_ptr->zstream.msg != NULL)
  197810. png_error(png_ptr, png_ptr->zstream.msg);
  197811. else
  197812. png_error(png_ptr, "zlib error");
  197813. }
  197814. /* check to see if we need more room */
  197815. if (!(png_ptr->zstream.avail_out))
  197816. {
  197817. /* make sure the output array has room */
  197818. if (comp->num_output_ptr >= comp->max_output_ptr)
  197819. {
  197820. int old_max;
  197821. old_max = comp->max_output_ptr;
  197822. comp->max_output_ptr = comp->num_output_ptr + 4;
  197823. if (comp->output_ptr != NULL)
  197824. {
  197825. png_charpp old_ptr;
  197826. old_ptr = comp->output_ptr;
  197827. comp->output_ptr = (png_charpp)png_malloc(png_ptr,
  197828. (png_uint_32)(comp->max_output_ptr *
  197829. png_sizeof (png_charpp)));
  197830. png_memcpy(comp->output_ptr, old_ptr, old_max
  197831. * png_sizeof (png_charp));
  197832. png_free(png_ptr, old_ptr);
  197833. }
  197834. else
  197835. comp->output_ptr = (png_charpp)png_malloc(png_ptr,
  197836. (png_uint_32)(comp->max_output_ptr *
  197837. png_sizeof (png_charp)));
  197838. }
  197839. /* save the data */
  197840. comp->output_ptr[comp->num_output_ptr] = (png_charp)png_malloc(png_ptr,
  197841. (png_uint_32)png_ptr->zbuf_size);
  197842. png_memcpy(comp->output_ptr[comp->num_output_ptr], png_ptr->zbuf,
  197843. png_ptr->zbuf_size);
  197844. comp->num_output_ptr++;
  197845. /* and reset the buffer */
  197846. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  197847. png_ptr->zstream.next_out = png_ptr->zbuf;
  197848. }
  197849. /* continue until we don't have any more to compress */
  197850. } while (png_ptr->zstream.avail_in);
  197851. /* finish the compression */
  197852. do
  197853. {
  197854. /* tell zlib we are finished */
  197855. ret = deflate(&png_ptr->zstream, Z_FINISH);
  197856. if (ret == Z_OK)
  197857. {
  197858. /* check to see if we need more room */
  197859. if (!(png_ptr->zstream.avail_out))
  197860. {
  197861. /* check to make sure our output array has room */
  197862. if (comp->num_output_ptr >= comp->max_output_ptr)
  197863. {
  197864. int old_max;
  197865. old_max = comp->max_output_ptr;
  197866. comp->max_output_ptr = comp->num_output_ptr + 4;
  197867. if (comp->output_ptr != NULL)
  197868. {
  197869. png_charpp old_ptr;
  197870. old_ptr = comp->output_ptr;
  197871. /* This could be optimized to realloc() */
  197872. comp->output_ptr = (png_charpp)png_malloc(png_ptr,
  197873. (png_uint_32)(comp->max_output_ptr *
  197874. png_sizeof (png_charpp)));
  197875. png_memcpy(comp->output_ptr, old_ptr,
  197876. old_max * png_sizeof (png_charp));
  197877. png_free(png_ptr, old_ptr);
  197878. }
  197879. else
  197880. comp->output_ptr = (png_charpp)png_malloc(png_ptr,
  197881. (png_uint_32)(comp->max_output_ptr *
  197882. png_sizeof (png_charp)));
  197883. }
  197884. /* save off the data */
  197885. comp->output_ptr[comp->num_output_ptr] =
  197886. (png_charp)png_malloc(png_ptr, (png_uint_32)png_ptr->zbuf_size);
  197887. png_memcpy(comp->output_ptr[comp->num_output_ptr], png_ptr->zbuf,
  197888. png_ptr->zbuf_size);
  197889. comp->num_output_ptr++;
  197890. /* and reset the buffer pointers */
  197891. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  197892. png_ptr->zstream.next_out = png_ptr->zbuf;
  197893. }
  197894. }
  197895. else if (ret != Z_STREAM_END)
  197896. {
  197897. /* we got an error */
  197898. if (png_ptr->zstream.msg != NULL)
  197899. png_error(png_ptr, png_ptr->zstream.msg);
  197900. else
  197901. png_error(png_ptr, "zlib error");
  197902. }
  197903. } while (ret != Z_STREAM_END);
  197904. /* text length is number of buffers plus last buffer */
  197905. text_len = png_ptr->zbuf_size * comp->num_output_ptr;
  197906. if (png_ptr->zstream.avail_out < png_ptr->zbuf_size)
  197907. text_len += png_ptr->zbuf_size - (png_size_t)png_ptr->zstream.avail_out;
  197908. return((int)text_len);
  197909. }
  197910. /* ship the compressed text out via chunk writes */
  197911. static void /* PRIVATE */
  197912. png_write_compressed_data_out(png_structp png_ptr, compression_state *comp)
  197913. {
  197914. int i;
  197915. /* handle the no-compression case */
  197916. if (comp->input)
  197917. {
  197918. png_write_chunk_data(png_ptr, (png_bytep)comp->input,
  197919. (png_size_t)comp->input_len);
  197920. return;
  197921. }
  197922. /* write saved output buffers, if any */
  197923. for (i = 0; i < comp->num_output_ptr; i++)
  197924. {
  197925. png_write_chunk_data(png_ptr,(png_bytep)comp->output_ptr[i],
  197926. png_ptr->zbuf_size);
  197927. png_free(png_ptr, comp->output_ptr[i]);
  197928. comp->output_ptr[i]=NULL;
  197929. }
  197930. if (comp->max_output_ptr != 0)
  197931. png_free(png_ptr, comp->output_ptr);
  197932. comp->output_ptr=NULL;
  197933. /* write anything left in zbuf */
  197934. if (png_ptr->zstream.avail_out < (png_uint_32)png_ptr->zbuf_size)
  197935. png_write_chunk_data(png_ptr, png_ptr->zbuf,
  197936. png_ptr->zbuf_size - png_ptr->zstream.avail_out);
  197937. /* reset zlib for another zTXt/iTXt or image data */
  197938. deflateReset(&png_ptr->zstream);
  197939. png_ptr->zstream.data_type = Z_BINARY;
  197940. }
  197941. #endif
  197942. /* Write the IHDR chunk, and update the png_struct with the necessary
  197943. * information. Note that the rest of this code depends upon this
  197944. * information being correct.
  197945. */
  197946. void /* PRIVATE */
  197947. png_write_IHDR(png_structp png_ptr, png_uint_32 width, png_uint_32 height,
  197948. int bit_depth, int color_type, int compression_type, int filter_type,
  197949. int interlace_type)
  197950. {
  197951. #ifdef PNG_USE_LOCAL_ARRAYS
  197952. PNG_IHDR;
  197953. #endif
  197954. png_byte buf[13]; /* buffer to store the IHDR info */
  197955. png_debug(1, "in png_write_IHDR\n");
  197956. /* Check that we have valid input data from the application info */
  197957. switch (color_type)
  197958. {
  197959. case PNG_COLOR_TYPE_GRAY:
  197960. switch (bit_depth)
  197961. {
  197962. case 1:
  197963. case 2:
  197964. case 4:
  197965. case 8:
  197966. case 16: png_ptr->channels = 1; break;
  197967. default: png_error(png_ptr,"Invalid bit depth for grayscale image");
  197968. }
  197969. break;
  197970. case PNG_COLOR_TYPE_RGB:
  197971. if (bit_depth != 8 && bit_depth != 16)
  197972. png_error(png_ptr, "Invalid bit depth for RGB image");
  197973. png_ptr->channels = 3;
  197974. break;
  197975. case PNG_COLOR_TYPE_PALETTE:
  197976. switch (bit_depth)
  197977. {
  197978. case 1:
  197979. case 2:
  197980. case 4:
  197981. case 8: png_ptr->channels = 1; break;
  197982. default: png_error(png_ptr, "Invalid bit depth for paletted image");
  197983. }
  197984. break;
  197985. case PNG_COLOR_TYPE_GRAY_ALPHA:
  197986. if (bit_depth != 8 && bit_depth != 16)
  197987. png_error(png_ptr, "Invalid bit depth for grayscale+alpha image");
  197988. png_ptr->channels = 2;
  197989. break;
  197990. case PNG_COLOR_TYPE_RGB_ALPHA:
  197991. if (bit_depth != 8 && bit_depth != 16)
  197992. png_error(png_ptr, "Invalid bit depth for RGBA image");
  197993. png_ptr->channels = 4;
  197994. break;
  197995. default:
  197996. png_error(png_ptr, "Invalid image color type specified");
  197997. }
  197998. if (compression_type != PNG_COMPRESSION_TYPE_BASE)
  197999. {
  198000. png_warning(png_ptr, "Invalid compression type specified");
  198001. compression_type = PNG_COMPRESSION_TYPE_BASE;
  198002. }
  198003. /* Write filter_method 64 (intrapixel differencing) only if
  198004. * 1. Libpng was compiled with PNG_MNG_FEATURES_SUPPORTED and
  198005. * 2. Libpng did not write a PNG signature (this filter_method is only
  198006. * used in PNG datastreams that are embedded in MNG datastreams) and
  198007. * 3. The application called png_permit_mng_features with a mask that
  198008. * included PNG_FLAG_MNG_FILTER_64 and
  198009. * 4. The filter_method is 64 and
  198010. * 5. The color_type is RGB or RGBA
  198011. */
  198012. if (
  198013. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  198014. !((png_ptr->mng_features_permitted & PNG_FLAG_MNG_FILTER_64) &&
  198015. ((png_ptr->mode&PNG_HAVE_PNG_SIGNATURE) == 0) &&
  198016. (color_type == PNG_COLOR_TYPE_RGB ||
  198017. color_type == PNG_COLOR_TYPE_RGB_ALPHA) &&
  198018. (filter_type == PNG_INTRAPIXEL_DIFFERENCING)) &&
  198019. #endif
  198020. filter_type != PNG_FILTER_TYPE_BASE)
  198021. {
  198022. png_warning(png_ptr, "Invalid filter type specified");
  198023. filter_type = PNG_FILTER_TYPE_BASE;
  198024. }
  198025. #ifdef PNG_WRITE_INTERLACING_SUPPORTED
  198026. if (interlace_type != PNG_INTERLACE_NONE &&
  198027. interlace_type != PNG_INTERLACE_ADAM7)
  198028. {
  198029. png_warning(png_ptr, "Invalid interlace type specified");
  198030. interlace_type = PNG_INTERLACE_ADAM7;
  198031. }
  198032. #else
  198033. interlace_type=PNG_INTERLACE_NONE;
  198034. #endif
  198035. /* save off the relevent information */
  198036. png_ptr->bit_depth = (png_byte)bit_depth;
  198037. png_ptr->color_type = (png_byte)color_type;
  198038. png_ptr->interlaced = (png_byte)interlace_type;
  198039. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  198040. png_ptr->filter_type = (png_byte)filter_type;
  198041. #endif
  198042. png_ptr->compression_type = (png_byte)compression_type;
  198043. png_ptr->width = width;
  198044. png_ptr->height = height;
  198045. png_ptr->pixel_depth = (png_byte)(bit_depth * png_ptr->channels);
  198046. png_ptr->rowbytes = PNG_ROWBYTES(png_ptr->pixel_depth, width);
  198047. /* set the usr info, so any transformations can modify it */
  198048. png_ptr->usr_width = png_ptr->width;
  198049. png_ptr->usr_bit_depth = png_ptr->bit_depth;
  198050. png_ptr->usr_channels = png_ptr->channels;
  198051. /* pack the header information into the buffer */
  198052. png_save_uint_32(buf, width);
  198053. png_save_uint_32(buf + 4, height);
  198054. buf[8] = (png_byte)bit_depth;
  198055. buf[9] = (png_byte)color_type;
  198056. buf[10] = (png_byte)compression_type;
  198057. buf[11] = (png_byte)filter_type;
  198058. buf[12] = (png_byte)interlace_type;
  198059. /* write the chunk */
  198060. png_write_chunk(png_ptr, png_IHDR, buf, (png_size_t)13);
  198061. /* initialize zlib with PNG info */
  198062. png_ptr->zstream.zalloc = png_zalloc;
  198063. png_ptr->zstream.zfree = png_zfree;
  198064. png_ptr->zstream.opaque = (voidpf)png_ptr;
  198065. if (!(png_ptr->do_filter))
  198066. {
  198067. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE ||
  198068. png_ptr->bit_depth < 8)
  198069. png_ptr->do_filter = PNG_FILTER_NONE;
  198070. else
  198071. png_ptr->do_filter = PNG_ALL_FILTERS;
  198072. }
  198073. if (!(png_ptr->flags & PNG_FLAG_ZLIB_CUSTOM_STRATEGY))
  198074. {
  198075. if (png_ptr->do_filter != PNG_FILTER_NONE)
  198076. png_ptr->zlib_strategy = Z_FILTERED;
  198077. else
  198078. png_ptr->zlib_strategy = Z_DEFAULT_STRATEGY;
  198079. }
  198080. if (!(png_ptr->flags & PNG_FLAG_ZLIB_CUSTOM_LEVEL))
  198081. png_ptr->zlib_level = Z_DEFAULT_COMPRESSION;
  198082. if (!(png_ptr->flags & PNG_FLAG_ZLIB_CUSTOM_MEM_LEVEL))
  198083. png_ptr->zlib_mem_level = 8;
  198084. if (!(png_ptr->flags & PNG_FLAG_ZLIB_CUSTOM_WINDOW_BITS))
  198085. png_ptr->zlib_window_bits = 15;
  198086. if (!(png_ptr->flags & PNG_FLAG_ZLIB_CUSTOM_METHOD))
  198087. png_ptr->zlib_method = 8;
  198088. if (deflateInit2(&png_ptr->zstream, png_ptr->zlib_level,
  198089. png_ptr->zlib_method, png_ptr->zlib_window_bits,
  198090. png_ptr->zlib_mem_level, png_ptr->zlib_strategy) != Z_OK)
  198091. png_error(png_ptr, "zlib failed to initialize compressor");
  198092. png_ptr->zstream.next_out = png_ptr->zbuf;
  198093. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  198094. /* libpng is not interested in zstream.data_type */
  198095. /* set it to a predefined value, to avoid its evaluation inside zlib */
  198096. png_ptr->zstream.data_type = Z_BINARY;
  198097. png_ptr->mode = PNG_HAVE_IHDR;
  198098. }
  198099. /* write the palette. We are careful not to trust png_color to be in the
  198100. * correct order for PNG, so people can redefine it to any convenient
  198101. * structure.
  198102. */
  198103. void /* PRIVATE */
  198104. png_write_PLTE(png_structp png_ptr, png_colorp palette, png_uint_32 num_pal)
  198105. {
  198106. #ifdef PNG_USE_LOCAL_ARRAYS
  198107. PNG_PLTE;
  198108. #endif
  198109. png_uint_32 i;
  198110. png_colorp pal_ptr;
  198111. png_byte buf[3];
  198112. png_debug(1, "in png_write_PLTE\n");
  198113. if ((
  198114. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  198115. !(png_ptr->mng_features_permitted & PNG_FLAG_MNG_EMPTY_PLTE) &&
  198116. #endif
  198117. num_pal == 0) || num_pal > 256)
  198118. {
  198119. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  198120. {
  198121. png_error(png_ptr, "Invalid number of colors in palette");
  198122. }
  198123. else
  198124. {
  198125. png_warning(png_ptr, "Invalid number of colors in palette");
  198126. return;
  198127. }
  198128. }
  198129. if (!(png_ptr->color_type&PNG_COLOR_MASK_COLOR))
  198130. {
  198131. png_warning(png_ptr,
  198132. "Ignoring request to write a PLTE chunk in grayscale PNG");
  198133. return;
  198134. }
  198135. png_ptr->num_palette = (png_uint_16)num_pal;
  198136. png_debug1(3, "num_palette = %d\n", png_ptr->num_palette);
  198137. png_write_chunk_start(png_ptr, png_PLTE, num_pal * 3);
  198138. #ifndef PNG_NO_POINTER_INDEXING
  198139. for (i = 0, pal_ptr = palette; i < num_pal; i++, pal_ptr++)
  198140. {
  198141. buf[0] = pal_ptr->red;
  198142. buf[1] = pal_ptr->green;
  198143. buf[2] = pal_ptr->blue;
  198144. png_write_chunk_data(png_ptr, buf, (png_size_t)3);
  198145. }
  198146. #else
  198147. /* This is a little slower but some buggy compilers need to do this instead */
  198148. pal_ptr=palette;
  198149. for (i = 0; i < num_pal; i++)
  198150. {
  198151. buf[0] = pal_ptr[i].red;
  198152. buf[1] = pal_ptr[i].green;
  198153. buf[2] = pal_ptr[i].blue;
  198154. png_write_chunk_data(png_ptr, buf, (png_size_t)3);
  198155. }
  198156. #endif
  198157. png_write_chunk_end(png_ptr);
  198158. png_ptr->mode |= PNG_HAVE_PLTE;
  198159. }
  198160. /* write an IDAT chunk */
  198161. void /* PRIVATE */
  198162. png_write_IDAT(png_structp png_ptr, png_bytep data, png_size_t length)
  198163. {
  198164. #ifdef PNG_USE_LOCAL_ARRAYS
  198165. PNG_IDAT;
  198166. #endif
  198167. png_debug(1, "in png_write_IDAT\n");
  198168. /* Optimize the CMF field in the zlib stream. */
  198169. /* This hack of the zlib stream is compliant to the stream specification. */
  198170. if (!(png_ptr->mode & PNG_HAVE_IDAT) &&
  198171. png_ptr->compression_type == PNG_COMPRESSION_TYPE_BASE)
  198172. {
  198173. unsigned int z_cmf = data[0]; /* zlib compression method and flags */
  198174. if ((z_cmf & 0x0f) == 8 && (z_cmf & 0xf0) <= 0x70)
  198175. {
  198176. /* Avoid memory underflows and multiplication overflows. */
  198177. /* The conditions below are practically always satisfied;
  198178. however, they still must be checked. */
  198179. if (length >= 2 &&
  198180. png_ptr->height < 16384 && png_ptr->width < 16384)
  198181. {
  198182. png_uint_32 uncompressed_idat_size = png_ptr->height *
  198183. ((png_ptr->width *
  198184. png_ptr->channels * png_ptr->bit_depth + 15) >> 3);
  198185. unsigned int z_cinfo = z_cmf >> 4;
  198186. unsigned int half_z_window_size = 1 << (z_cinfo + 7);
  198187. while (uncompressed_idat_size <= half_z_window_size &&
  198188. half_z_window_size >= 256)
  198189. {
  198190. z_cinfo--;
  198191. half_z_window_size >>= 1;
  198192. }
  198193. z_cmf = (z_cmf & 0x0f) | (z_cinfo << 4);
  198194. if (data[0] != (png_byte)z_cmf)
  198195. {
  198196. data[0] = (png_byte)z_cmf;
  198197. data[1] &= 0xe0;
  198198. data[1] += (png_byte)(0x1f - ((z_cmf << 8) + data[1]) % 0x1f);
  198199. }
  198200. }
  198201. }
  198202. else
  198203. png_error(png_ptr,
  198204. "Invalid zlib compression method or flags in IDAT");
  198205. }
  198206. png_write_chunk(png_ptr, png_IDAT, data, length);
  198207. png_ptr->mode |= PNG_HAVE_IDAT;
  198208. }
  198209. /* write an IEND chunk */
  198210. void /* PRIVATE */
  198211. png_write_IEND(png_structp png_ptr)
  198212. {
  198213. #ifdef PNG_USE_LOCAL_ARRAYS
  198214. PNG_IEND;
  198215. #endif
  198216. png_debug(1, "in png_write_IEND\n");
  198217. png_write_chunk(png_ptr, png_IEND, png_bytep_NULL,
  198218. (png_size_t)0);
  198219. png_ptr->mode |= PNG_HAVE_IEND;
  198220. }
  198221. #if defined(PNG_WRITE_gAMA_SUPPORTED)
  198222. /* write a gAMA chunk */
  198223. #ifdef PNG_FLOATING_POINT_SUPPORTED
  198224. void /* PRIVATE */
  198225. png_write_gAMA(png_structp png_ptr, double file_gamma)
  198226. {
  198227. #ifdef PNG_USE_LOCAL_ARRAYS
  198228. PNG_gAMA;
  198229. #endif
  198230. png_uint_32 igamma;
  198231. png_byte buf[4];
  198232. png_debug(1, "in png_write_gAMA\n");
  198233. /* file_gamma is saved in 1/100,000ths */
  198234. igamma = (png_uint_32)(file_gamma * 100000.0 + 0.5);
  198235. png_save_uint_32(buf, igamma);
  198236. png_write_chunk(png_ptr, png_gAMA, buf, (png_size_t)4);
  198237. }
  198238. #endif
  198239. #ifdef PNG_FIXED_POINT_SUPPORTED
  198240. void /* PRIVATE */
  198241. png_write_gAMA_fixed(png_structp png_ptr, png_fixed_point file_gamma)
  198242. {
  198243. #ifdef PNG_USE_LOCAL_ARRAYS
  198244. PNG_gAMA;
  198245. #endif
  198246. png_byte buf[4];
  198247. png_debug(1, "in png_write_gAMA\n");
  198248. /* file_gamma is saved in 1/100,000ths */
  198249. png_save_uint_32(buf, (png_uint_32)file_gamma);
  198250. png_write_chunk(png_ptr, png_gAMA, buf, (png_size_t)4);
  198251. }
  198252. #endif
  198253. #endif
  198254. #if defined(PNG_WRITE_sRGB_SUPPORTED)
  198255. /* write a sRGB chunk */
  198256. void /* PRIVATE */
  198257. png_write_sRGB(png_structp png_ptr, int srgb_intent)
  198258. {
  198259. #ifdef PNG_USE_LOCAL_ARRAYS
  198260. PNG_sRGB;
  198261. #endif
  198262. png_byte buf[1];
  198263. png_debug(1, "in png_write_sRGB\n");
  198264. if(srgb_intent >= PNG_sRGB_INTENT_LAST)
  198265. png_warning(png_ptr,
  198266. "Invalid sRGB rendering intent specified");
  198267. buf[0]=(png_byte)srgb_intent;
  198268. png_write_chunk(png_ptr, png_sRGB, buf, (png_size_t)1);
  198269. }
  198270. #endif
  198271. #if defined(PNG_WRITE_iCCP_SUPPORTED)
  198272. /* write an iCCP chunk */
  198273. void /* PRIVATE */
  198274. png_write_iCCP(png_structp png_ptr, png_charp name, int compression_type,
  198275. png_charp profile, int profile_len)
  198276. {
  198277. #ifdef PNG_USE_LOCAL_ARRAYS
  198278. PNG_iCCP;
  198279. #endif
  198280. png_size_t name_len;
  198281. png_charp new_name;
  198282. compression_state comp;
  198283. int embedded_profile_len = 0;
  198284. png_debug(1, "in png_write_iCCP\n");
  198285. comp.num_output_ptr = 0;
  198286. comp.max_output_ptr = 0;
  198287. comp.output_ptr = NULL;
  198288. comp.input = NULL;
  198289. comp.input_len = 0;
  198290. if (name == NULL || (name_len = png_check_keyword(png_ptr, name,
  198291. &new_name)) == 0)
  198292. {
  198293. png_warning(png_ptr, "Empty keyword in iCCP chunk");
  198294. return;
  198295. }
  198296. if (compression_type != PNG_COMPRESSION_TYPE_BASE)
  198297. png_warning(png_ptr, "Unknown compression type in iCCP chunk");
  198298. if (profile == NULL)
  198299. profile_len = 0;
  198300. if (profile_len > 3)
  198301. embedded_profile_len =
  198302. ((*( (png_bytep)profile ))<<24) |
  198303. ((*( (png_bytep)profile+1))<<16) |
  198304. ((*( (png_bytep)profile+2))<< 8) |
  198305. ((*( (png_bytep)profile+3)) );
  198306. if (profile_len < embedded_profile_len)
  198307. {
  198308. png_warning(png_ptr,
  198309. "Embedded profile length too large in iCCP chunk");
  198310. return;
  198311. }
  198312. if (profile_len > embedded_profile_len)
  198313. {
  198314. png_warning(png_ptr,
  198315. "Truncating profile to actual length in iCCP chunk");
  198316. profile_len = embedded_profile_len;
  198317. }
  198318. if (profile_len)
  198319. profile_len = png_text_compress(png_ptr, profile, (png_size_t)profile_len,
  198320. PNG_COMPRESSION_TYPE_BASE, &comp);
  198321. /* make sure we include the NULL after the name and the compression type */
  198322. png_write_chunk_start(png_ptr, png_iCCP,
  198323. (png_uint_32)name_len+profile_len+2);
  198324. new_name[name_len+1]=0x00;
  198325. png_write_chunk_data(png_ptr, (png_bytep)new_name, name_len + 2);
  198326. if (profile_len)
  198327. png_write_compressed_data_out(png_ptr, &comp);
  198328. png_write_chunk_end(png_ptr);
  198329. png_free(png_ptr, new_name);
  198330. }
  198331. #endif
  198332. #if defined(PNG_WRITE_sPLT_SUPPORTED)
  198333. /* write a sPLT chunk */
  198334. void /* PRIVATE */
  198335. png_write_sPLT(png_structp png_ptr, png_sPLT_tp spalette)
  198336. {
  198337. #ifdef PNG_USE_LOCAL_ARRAYS
  198338. PNG_sPLT;
  198339. #endif
  198340. png_size_t name_len;
  198341. png_charp new_name;
  198342. png_byte entrybuf[10];
  198343. int entry_size = (spalette->depth == 8 ? 6 : 10);
  198344. int palette_size = entry_size * spalette->nentries;
  198345. png_sPLT_entryp ep;
  198346. #ifdef PNG_NO_POINTER_INDEXING
  198347. int i;
  198348. #endif
  198349. png_debug(1, "in png_write_sPLT\n");
  198350. if (spalette->name == NULL || (name_len = png_check_keyword(png_ptr,
  198351. spalette->name, &new_name))==0)
  198352. {
  198353. png_warning(png_ptr, "Empty keyword in sPLT chunk");
  198354. return;
  198355. }
  198356. /* make sure we include the NULL after the name */
  198357. png_write_chunk_start(png_ptr, png_sPLT,
  198358. (png_uint_32)(name_len + 2 + palette_size));
  198359. png_write_chunk_data(png_ptr, (png_bytep)new_name, name_len + 1);
  198360. png_write_chunk_data(png_ptr, (png_bytep)&spalette->depth, 1);
  198361. /* loop through each palette entry, writing appropriately */
  198362. #ifndef PNG_NO_POINTER_INDEXING
  198363. for (ep = spalette->entries; ep<spalette->entries+spalette->nentries; ep++)
  198364. {
  198365. if (spalette->depth == 8)
  198366. {
  198367. entrybuf[0] = (png_byte)ep->red;
  198368. entrybuf[1] = (png_byte)ep->green;
  198369. entrybuf[2] = (png_byte)ep->blue;
  198370. entrybuf[3] = (png_byte)ep->alpha;
  198371. png_save_uint_16(entrybuf + 4, ep->frequency);
  198372. }
  198373. else
  198374. {
  198375. png_save_uint_16(entrybuf + 0, ep->red);
  198376. png_save_uint_16(entrybuf + 2, ep->green);
  198377. png_save_uint_16(entrybuf + 4, ep->blue);
  198378. png_save_uint_16(entrybuf + 6, ep->alpha);
  198379. png_save_uint_16(entrybuf + 8, ep->frequency);
  198380. }
  198381. png_write_chunk_data(png_ptr, entrybuf, (png_size_t)entry_size);
  198382. }
  198383. #else
  198384. ep=spalette->entries;
  198385. for (i=0; i>spalette->nentries; i++)
  198386. {
  198387. if (spalette->depth == 8)
  198388. {
  198389. entrybuf[0] = (png_byte)ep[i].red;
  198390. entrybuf[1] = (png_byte)ep[i].green;
  198391. entrybuf[2] = (png_byte)ep[i].blue;
  198392. entrybuf[3] = (png_byte)ep[i].alpha;
  198393. png_save_uint_16(entrybuf + 4, ep[i].frequency);
  198394. }
  198395. else
  198396. {
  198397. png_save_uint_16(entrybuf + 0, ep[i].red);
  198398. png_save_uint_16(entrybuf + 2, ep[i].green);
  198399. png_save_uint_16(entrybuf + 4, ep[i].blue);
  198400. png_save_uint_16(entrybuf + 6, ep[i].alpha);
  198401. png_save_uint_16(entrybuf + 8, ep[i].frequency);
  198402. }
  198403. png_write_chunk_data(png_ptr, entrybuf, entry_size);
  198404. }
  198405. #endif
  198406. png_write_chunk_end(png_ptr);
  198407. png_free(png_ptr, new_name);
  198408. }
  198409. #endif
  198410. #if defined(PNG_WRITE_sBIT_SUPPORTED)
  198411. /* write the sBIT chunk */
  198412. void /* PRIVATE */
  198413. png_write_sBIT(png_structp png_ptr, png_color_8p sbit, int color_type)
  198414. {
  198415. #ifdef PNG_USE_LOCAL_ARRAYS
  198416. PNG_sBIT;
  198417. #endif
  198418. png_byte buf[4];
  198419. png_size_t size;
  198420. png_debug(1, "in png_write_sBIT\n");
  198421. /* make sure we don't depend upon the order of PNG_COLOR_8 */
  198422. if (color_type & PNG_COLOR_MASK_COLOR)
  198423. {
  198424. png_byte maxbits;
  198425. maxbits = (png_byte)(color_type==PNG_COLOR_TYPE_PALETTE ? 8 :
  198426. png_ptr->usr_bit_depth);
  198427. if (sbit->red == 0 || sbit->red > maxbits ||
  198428. sbit->green == 0 || sbit->green > maxbits ||
  198429. sbit->blue == 0 || sbit->blue > maxbits)
  198430. {
  198431. png_warning(png_ptr, "Invalid sBIT depth specified");
  198432. return;
  198433. }
  198434. buf[0] = sbit->red;
  198435. buf[1] = sbit->green;
  198436. buf[2] = sbit->blue;
  198437. size = 3;
  198438. }
  198439. else
  198440. {
  198441. if (sbit->gray == 0 || sbit->gray > png_ptr->usr_bit_depth)
  198442. {
  198443. png_warning(png_ptr, "Invalid sBIT depth specified");
  198444. return;
  198445. }
  198446. buf[0] = sbit->gray;
  198447. size = 1;
  198448. }
  198449. if (color_type & PNG_COLOR_MASK_ALPHA)
  198450. {
  198451. if (sbit->alpha == 0 || sbit->alpha > png_ptr->usr_bit_depth)
  198452. {
  198453. png_warning(png_ptr, "Invalid sBIT depth specified");
  198454. return;
  198455. }
  198456. buf[size++] = sbit->alpha;
  198457. }
  198458. png_write_chunk(png_ptr, png_sBIT, buf, size);
  198459. }
  198460. #endif
  198461. #if defined(PNG_WRITE_cHRM_SUPPORTED)
  198462. /* write the cHRM chunk */
  198463. #ifdef PNG_FLOATING_POINT_SUPPORTED
  198464. void /* PRIVATE */
  198465. png_write_cHRM(png_structp png_ptr, double white_x, double white_y,
  198466. double red_x, double red_y, double green_x, double green_y,
  198467. double blue_x, double blue_y)
  198468. {
  198469. #ifdef PNG_USE_LOCAL_ARRAYS
  198470. PNG_cHRM;
  198471. #endif
  198472. png_byte buf[32];
  198473. png_uint_32 itemp;
  198474. png_debug(1, "in png_write_cHRM\n");
  198475. /* each value is saved in 1/100,000ths */
  198476. if (white_x < 0 || white_x > 0.8 || white_y < 0 || white_y > 0.8 ||
  198477. white_x + white_y > 1.0)
  198478. {
  198479. png_warning(png_ptr, "Invalid cHRM white point specified");
  198480. #if !defined(PNG_NO_CONSOLE_IO)
  198481. fprintf(stderr,"white_x=%f, white_y=%f\n",white_x, white_y);
  198482. #endif
  198483. return;
  198484. }
  198485. itemp = (png_uint_32)(white_x * 100000.0 + 0.5);
  198486. png_save_uint_32(buf, itemp);
  198487. itemp = (png_uint_32)(white_y * 100000.0 + 0.5);
  198488. png_save_uint_32(buf + 4, itemp);
  198489. if (red_x < 0 || red_y < 0 || red_x + red_y > 1.0)
  198490. {
  198491. png_warning(png_ptr, "Invalid cHRM red point specified");
  198492. return;
  198493. }
  198494. itemp = (png_uint_32)(red_x * 100000.0 + 0.5);
  198495. png_save_uint_32(buf + 8, itemp);
  198496. itemp = (png_uint_32)(red_y * 100000.0 + 0.5);
  198497. png_save_uint_32(buf + 12, itemp);
  198498. if (green_x < 0 || green_y < 0 || green_x + green_y > 1.0)
  198499. {
  198500. png_warning(png_ptr, "Invalid cHRM green point specified");
  198501. return;
  198502. }
  198503. itemp = (png_uint_32)(green_x * 100000.0 + 0.5);
  198504. png_save_uint_32(buf + 16, itemp);
  198505. itemp = (png_uint_32)(green_y * 100000.0 + 0.5);
  198506. png_save_uint_32(buf + 20, itemp);
  198507. if (blue_x < 0 || blue_y < 0 || blue_x + blue_y > 1.0)
  198508. {
  198509. png_warning(png_ptr, "Invalid cHRM blue point specified");
  198510. return;
  198511. }
  198512. itemp = (png_uint_32)(blue_x * 100000.0 + 0.5);
  198513. png_save_uint_32(buf + 24, itemp);
  198514. itemp = (png_uint_32)(blue_y * 100000.0 + 0.5);
  198515. png_save_uint_32(buf + 28, itemp);
  198516. png_write_chunk(png_ptr, png_cHRM, buf, (png_size_t)32);
  198517. }
  198518. #endif
  198519. #ifdef PNG_FIXED_POINT_SUPPORTED
  198520. void /* PRIVATE */
  198521. png_write_cHRM_fixed(png_structp png_ptr, png_fixed_point white_x,
  198522. png_fixed_point white_y, png_fixed_point red_x, png_fixed_point red_y,
  198523. png_fixed_point green_x, png_fixed_point green_y, png_fixed_point blue_x,
  198524. png_fixed_point blue_y)
  198525. {
  198526. #ifdef PNG_USE_LOCAL_ARRAYS
  198527. PNG_cHRM;
  198528. #endif
  198529. png_byte buf[32];
  198530. png_debug(1, "in png_write_cHRM\n");
  198531. /* each value is saved in 1/100,000ths */
  198532. if (white_x > 80000L || white_y > 80000L || white_x + white_y > 100000L)
  198533. {
  198534. png_warning(png_ptr, "Invalid fixed cHRM white point specified");
  198535. #if !defined(PNG_NO_CONSOLE_IO)
  198536. fprintf(stderr,"white_x=%ld, white_y=%ld\n",white_x, white_y);
  198537. #endif
  198538. return;
  198539. }
  198540. png_save_uint_32(buf, (png_uint_32)white_x);
  198541. png_save_uint_32(buf + 4, (png_uint_32)white_y);
  198542. if (red_x + red_y > 100000L)
  198543. {
  198544. png_warning(png_ptr, "Invalid cHRM fixed red point specified");
  198545. return;
  198546. }
  198547. png_save_uint_32(buf + 8, (png_uint_32)red_x);
  198548. png_save_uint_32(buf + 12, (png_uint_32)red_y);
  198549. if (green_x + green_y > 100000L)
  198550. {
  198551. png_warning(png_ptr, "Invalid fixed cHRM green point specified");
  198552. return;
  198553. }
  198554. png_save_uint_32(buf + 16, (png_uint_32)green_x);
  198555. png_save_uint_32(buf + 20, (png_uint_32)green_y);
  198556. if (blue_x + blue_y > 100000L)
  198557. {
  198558. png_warning(png_ptr, "Invalid fixed cHRM blue point specified");
  198559. return;
  198560. }
  198561. png_save_uint_32(buf + 24, (png_uint_32)blue_x);
  198562. png_save_uint_32(buf + 28, (png_uint_32)blue_y);
  198563. png_write_chunk(png_ptr, png_cHRM, buf, (png_size_t)32);
  198564. }
  198565. #endif
  198566. #endif
  198567. #if defined(PNG_WRITE_tRNS_SUPPORTED)
  198568. /* write the tRNS chunk */
  198569. void /* PRIVATE */
  198570. png_write_tRNS(png_structp png_ptr, png_bytep trans, png_color_16p tran,
  198571. int num_trans, int color_type)
  198572. {
  198573. #ifdef PNG_USE_LOCAL_ARRAYS
  198574. PNG_tRNS;
  198575. #endif
  198576. png_byte buf[6];
  198577. png_debug(1, "in png_write_tRNS\n");
  198578. if (color_type == PNG_COLOR_TYPE_PALETTE)
  198579. {
  198580. if (num_trans <= 0 || num_trans > (int)png_ptr->num_palette)
  198581. {
  198582. png_warning(png_ptr,"Invalid number of transparent colors specified");
  198583. return;
  198584. }
  198585. /* write the chunk out as it is */
  198586. png_write_chunk(png_ptr, png_tRNS, trans, (png_size_t)num_trans);
  198587. }
  198588. else if (color_type == PNG_COLOR_TYPE_GRAY)
  198589. {
  198590. /* one 16 bit value */
  198591. if(tran->gray >= (1 << png_ptr->bit_depth))
  198592. {
  198593. png_warning(png_ptr,
  198594. "Ignoring attempt to write tRNS chunk out-of-range for bit_depth");
  198595. return;
  198596. }
  198597. png_save_uint_16(buf, tran->gray);
  198598. png_write_chunk(png_ptr, png_tRNS, buf, (png_size_t)2);
  198599. }
  198600. else if (color_type == PNG_COLOR_TYPE_RGB)
  198601. {
  198602. /* three 16 bit values */
  198603. png_save_uint_16(buf, tran->red);
  198604. png_save_uint_16(buf + 2, tran->green);
  198605. png_save_uint_16(buf + 4, tran->blue);
  198606. if(png_ptr->bit_depth == 8 && (buf[0] | buf[2] | buf[4]))
  198607. {
  198608. png_warning(png_ptr,
  198609. "Ignoring attempt to write 16-bit tRNS chunk when bit_depth is 8");
  198610. return;
  198611. }
  198612. png_write_chunk(png_ptr, png_tRNS, buf, (png_size_t)6);
  198613. }
  198614. else
  198615. {
  198616. png_warning(png_ptr, "Can't write tRNS with an alpha channel");
  198617. }
  198618. }
  198619. #endif
  198620. #if defined(PNG_WRITE_bKGD_SUPPORTED)
  198621. /* write the background chunk */
  198622. void /* PRIVATE */
  198623. png_write_bKGD(png_structp png_ptr, png_color_16p back, int color_type)
  198624. {
  198625. #ifdef PNG_USE_LOCAL_ARRAYS
  198626. PNG_bKGD;
  198627. #endif
  198628. png_byte buf[6];
  198629. png_debug(1, "in png_write_bKGD\n");
  198630. if (color_type == PNG_COLOR_TYPE_PALETTE)
  198631. {
  198632. if (
  198633. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  198634. (png_ptr->num_palette ||
  198635. (!(png_ptr->mng_features_permitted & PNG_FLAG_MNG_EMPTY_PLTE))) &&
  198636. #endif
  198637. back->index > png_ptr->num_palette)
  198638. {
  198639. png_warning(png_ptr, "Invalid background palette index");
  198640. return;
  198641. }
  198642. buf[0] = back->index;
  198643. png_write_chunk(png_ptr, png_bKGD, buf, (png_size_t)1);
  198644. }
  198645. else if (color_type & PNG_COLOR_MASK_COLOR)
  198646. {
  198647. png_save_uint_16(buf, back->red);
  198648. png_save_uint_16(buf + 2, back->green);
  198649. png_save_uint_16(buf + 4, back->blue);
  198650. if(png_ptr->bit_depth == 8 && (buf[0] | buf[2] | buf[4]))
  198651. {
  198652. png_warning(png_ptr,
  198653. "Ignoring attempt to write 16-bit bKGD chunk when bit_depth is 8");
  198654. return;
  198655. }
  198656. png_write_chunk(png_ptr, png_bKGD, buf, (png_size_t)6);
  198657. }
  198658. else
  198659. {
  198660. if(back->gray >= (1 << png_ptr->bit_depth))
  198661. {
  198662. png_warning(png_ptr,
  198663. "Ignoring attempt to write bKGD chunk out-of-range for bit_depth");
  198664. return;
  198665. }
  198666. png_save_uint_16(buf, back->gray);
  198667. png_write_chunk(png_ptr, png_bKGD, buf, (png_size_t)2);
  198668. }
  198669. }
  198670. #endif
  198671. #if defined(PNG_WRITE_hIST_SUPPORTED)
  198672. /* write the histogram */
  198673. void /* PRIVATE */
  198674. png_write_hIST(png_structp png_ptr, png_uint_16p hist, int num_hist)
  198675. {
  198676. #ifdef PNG_USE_LOCAL_ARRAYS
  198677. PNG_hIST;
  198678. #endif
  198679. int i;
  198680. png_byte buf[3];
  198681. png_debug(1, "in png_write_hIST\n");
  198682. if (num_hist > (int)png_ptr->num_palette)
  198683. {
  198684. png_debug2(3, "num_hist = %d, num_palette = %d\n", num_hist,
  198685. png_ptr->num_palette);
  198686. png_warning(png_ptr, "Invalid number of histogram entries specified");
  198687. return;
  198688. }
  198689. png_write_chunk_start(png_ptr, png_hIST, (png_uint_32)(num_hist * 2));
  198690. for (i = 0; i < num_hist; i++)
  198691. {
  198692. png_save_uint_16(buf, hist[i]);
  198693. png_write_chunk_data(png_ptr, buf, (png_size_t)2);
  198694. }
  198695. png_write_chunk_end(png_ptr);
  198696. }
  198697. #endif
  198698. #if defined(PNG_WRITE_TEXT_SUPPORTED) || defined(PNG_WRITE_pCAL_SUPPORTED) || \
  198699. defined(PNG_WRITE_iCCP_SUPPORTED) || defined(PNG_WRITE_sPLT_SUPPORTED)
  198700. /* Check that the tEXt or zTXt keyword is valid per PNG 1.0 specification,
  198701. * and if invalid, correct the keyword rather than discarding the entire
  198702. * chunk. The PNG 1.0 specification requires keywords 1-79 characters in
  198703. * length, forbids leading or trailing whitespace, multiple internal spaces,
  198704. * and the non-break space (0x80) from ISO 8859-1. Returns keyword length.
  198705. *
  198706. * The new_key is allocated to hold the corrected keyword and must be freed
  198707. * by the calling routine. This avoids problems with trying to write to
  198708. * static keywords without having to have duplicate copies of the strings.
  198709. */
  198710. png_size_t /* PRIVATE */
  198711. png_check_keyword(png_structp png_ptr, png_charp key, png_charpp new_key)
  198712. {
  198713. png_size_t key_len;
  198714. png_charp kp, dp;
  198715. int kflag;
  198716. int kwarn=0;
  198717. png_debug(1, "in png_check_keyword\n");
  198718. *new_key = NULL;
  198719. if (key == NULL || (key_len = png_strlen(key)) == 0)
  198720. {
  198721. png_warning(png_ptr, "zero length keyword");
  198722. return ((png_size_t)0);
  198723. }
  198724. png_debug1(2, "Keyword to be checked is '%s'\n", key);
  198725. *new_key = (png_charp)png_malloc_warn(png_ptr, (png_uint_32)(key_len + 2));
  198726. if (*new_key == NULL)
  198727. {
  198728. png_warning(png_ptr, "Out of memory while procesing keyword");
  198729. return ((png_size_t)0);
  198730. }
  198731. /* Replace non-printing characters with a blank and print a warning */
  198732. for (kp = key, dp = *new_key; *kp != '\0'; kp++, dp++)
  198733. {
  198734. if ((png_byte)*kp < 0x20 ||
  198735. ((png_byte)*kp > 0x7E && (png_byte)*kp < 0xA1))
  198736. {
  198737. #if !defined(PNG_NO_STDIO) && !defined(_WIN32_WCE)
  198738. char msg[40];
  198739. png_snprintf(msg, 40,
  198740. "invalid keyword character 0x%02X", (png_byte)*kp);
  198741. png_warning(png_ptr, msg);
  198742. #else
  198743. png_warning(png_ptr, "invalid character in keyword");
  198744. #endif
  198745. *dp = ' ';
  198746. }
  198747. else
  198748. {
  198749. *dp = *kp;
  198750. }
  198751. }
  198752. *dp = '\0';
  198753. /* Remove any trailing white space. */
  198754. kp = *new_key + key_len - 1;
  198755. if (*kp == ' ')
  198756. {
  198757. png_warning(png_ptr, "trailing spaces removed from keyword");
  198758. while (*kp == ' ')
  198759. {
  198760. *(kp--) = '\0';
  198761. key_len--;
  198762. }
  198763. }
  198764. /* Remove any leading white space. */
  198765. kp = *new_key;
  198766. if (*kp == ' ')
  198767. {
  198768. png_warning(png_ptr, "leading spaces removed from keyword");
  198769. while (*kp == ' ')
  198770. {
  198771. kp++;
  198772. key_len--;
  198773. }
  198774. }
  198775. png_debug1(2, "Checking for multiple internal spaces in '%s'\n", kp);
  198776. /* Remove multiple internal spaces. */
  198777. for (kflag = 0, dp = *new_key; *kp != '\0'; kp++)
  198778. {
  198779. if (*kp == ' ' && kflag == 0)
  198780. {
  198781. *(dp++) = *kp;
  198782. kflag = 1;
  198783. }
  198784. else if (*kp == ' ')
  198785. {
  198786. key_len--;
  198787. kwarn=1;
  198788. }
  198789. else
  198790. {
  198791. *(dp++) = *kp;
  198792. kflag = 0;
  198793. }
  198794. }
  198795. *dp = '\0';
  198796. if(kwarn)
  198797. png_warning(png_ptr, "extra interior spaces removed from keyword");
  198798. if (key_len == 0)
  198799. {
  198800. png_free(png_ptr, *new_key);
  198801. *new_key=NULL;
  198802. png_warning(png_ptr, "Zero length keyword");
  198803. }
  198804. if (key_len > 79)
  198805. {
  198806. png_warning(png_ptr, "keyword length must be 1 - 79 characters");
  198807. new_key[79] = '\0';
  198808. key_len = 79;
  198809. }
  198810. return (key_len);
  198811. }
  198812. #endif
  198813. #if defined(PNG_WRITE_tEXt_SUPPORTED)
  198814. /* write a tEXt chunk */
  198815. void /* PRIVATE */
  198816. png_write_tEXt(png_structp png_ptr, png_charp key, png_charp text,
  198817. png_size_t text_len)
  198818. {
  198819. #ifdef PNG_USE_LOCAL_ARRAYS
  198820. PNG_tEXt;
  198821. #endif
  198822. png_size_t key_len;
  198823. png_charp new_key;
  198824. png_debug(1, "in png_write_tEXt\n");
  198825. if (key == NULL || (key_len = png_check_keyword(png_ptr, key, &new_key))==0)
  198826. {
  198827. png_warning(png_ptr, "Empty keyword in tEXt chunk");
  198828. return;
  198829. }
  198830. if (text == NULL || *text == '\0')
  198831. text_len = 0;
  198832. else
  198833. text_len = png_strlen(text);
  198834. /* make sure we include the 0 after the key */
  198835. png_write_chunk_start(png_ptr, png_tEXt, (png_uint_32)key_len+text_len+1);
  198836. /*
  198837. * We leave it to the application to meet PNG-1.0 requirements on the
  198838. * contents of the text. PNG-1.0 through PNG-1.2 discourage the use of
  198839. * any non-Latin-1 characters except for NEWLINE. ISO PNG will forbid them.
  198840. * The NUL character is forbidden by PNG-1.0 through PNG-1.2 and ISO PNG.
  198841. */
  198842. png_write_chunk_data(png_ptr, (png_bytep)new_key, key_len + 1);
  198843. if (text_len)
  198844. png_write_chunk_data(png_ptr, (png_bytep)text, text_len);
  198845. png_write_chunk_end(png_ptr);
  198846. png_free(png_ptr, new_key);
  198847. }
  198848. #endif
  198849. #if defined(PNG_WRITE_zTXt_SUPPORTED)
  198850. /* write a compressed text chunk */
  198851. void /* PRIVATE */
  198852. png_write_zTXt(png_structp png_ptr, png_charp key, png_charp text,
  198853. png_size_t text_len, int compression)
  198854. {
  198855. #ifdef PNG_USE_LOCAL_ARRAYS
  198856. PNG_zTXt;
  198857. #endif
  198858. png_size_t key_len;
  198859. char buf[1];
  198860. png_charp new_key;
  198861. compression_state comp;
  198862. png_debug(1, "in png_write_zTXt\n");
  198863. comp.num_output_ptr = 0;
  198864. comp.max_output_ptr = 0;
  198865. comp.output_ptr = NULL;
  198866. comp.input = NULL;
  198867. comp.input_len = 0;
  198868. if (key == NULL || (key_len = png_check_keyword(png_ptr, key, &new_key))==0)
  198869. {
  198870. png_warning(png_ptr, "Empty keyword in zTXt chunk");
  198871. return;
  198872. }
  198873. if (text == NULL || *text == '\0' || compression==PNG_TEXT_COMPRESSION_NONE)
  198874. {
  198875. png_write_tEXt(png_ptr, new_key, text, (png_size_t)0);
  198876. png_free(png_ptr, new_key);
  198877. return;
  198878. }
  198879. text_len = png_strlen(text);
  198880. /* compute the compressed data; do it now for the length */
  198881. text_len = png_text_compress(png_ptr, text, text_len, compression,
  198882. &comp);
  198883. /* write start of chunk */
  198884. png_write_chunk_start(png_ptr, png_zTXt, (png_uint_32)
  198885. (key_len+text_len+2));
  198886. /* write key */
  198887. png_write_chunk_data(png_ptr, (png_bytep)new_key, key_len + 1);
  198888. png_free(png_ptr, new_key);
  198889. buf[0] = (png_byte)compression;
  198890. /* write compression */
  198891. png_write_chunk_data(png_ptr, (png_bytep)buf, (png_size_t)1);
  198892. /* write the compressed data */
  198893. png_write_compressed_data_out(png_ptr, &comp);
  198894. /* close the chunk */
  198895. png_write_chunk_end(png_ptr);
  198896. }
  198897. #endif
  198898. #if defined(PNG_WRITE_iTXt_SUPPORTED)
  198899. /* write an iTXt chunk */
  198900. void /* PRIVATE */
  198901. png_write_iTXt(png_structp png_ptr, int compression, png_charp key,
  198902. png_charp lang, png_charp lang_key, png_charp text)
  198903. {
  198904. #ifdef PNG_USE_LOCAL_ARRAYS
  198905. PNG_iTXt;
  198906. #endif
  198907. png_size_t lang_len, key_len, lang_key_len, text_len;
  198908. png_charp new_lang, new_key;
  198909. png_byte cbuf[2];
  198910. compression_state comp;
  198911. png_debug(1, "in png_write_iTXt\n");
  198912. comp.num_output_ptr = 0;
  198913. comp.max_output_ptr = 0;
  198914. comp.output_ptr = NULL;
  198915. comp.input = NULL;
  198916. if (key == NULL || (key_len = png_check_keyword(png_ptr, key, &new_key))==0)
  198917. {
  198918. png_warning(png_ptr, "Empty keyword in iTXt chunk");
  198919. return;
  198920. }
  198921. if (lang == NULL || (lang_len = png_check_keyword(png_ptr, lang, &new_lang))==0)
  198922. {
  198923. png_warning(png_ptr, "Empty language field in iTXt chunk");
  198924. new_lang = NULL;
  198925. lang_len = 0;
  198926. }
  198927. if (lang_key == NULL)
  198928. lang_key_len = 0;
  198929. else
  198930. lang_key_len = png_strlen(lang_key);
  198931. if (text == NULL)
  198932. text_len = 0;
  198933. else
  198934. text_len = png_strlen(text);
  198935. /* compute the compressed data; do it now for the length */
  198936. text_len = png_text_compress(png_ptr, text, text_len, compression-2,
  198937. &comp);
  198938. /* make sure we include the compression flag, the compression byte,
  198939. * and the NULs after the key, lang, and lang_key parts */
  198940. png_write_chunk_start(png_ptr, png_iTXt,
  198941. (png_uint_32)(
  198942. 5 /* comp byte, comp flag, terminators for key, lang and lang_key */
  198943. + key_len
  198944. + lang_len
  198945. + lang_key_len
  198946. + text_len));
  198947. /*
  198948. * We leave it to the application to meet PNG-1.0 requirements on the
  198949. * contents of the text. PNG-1.0 through PNG-1.2 discourage the use of
  198950. * any non-Latin-1 characters except for NEWLINE. ISO PNG will forbid them.
  198951. * The NUL character is forbidden by PNG-1.0 through PNG-1.2 and ISO PNG.
  198952. */
  198953. png_write_chunk_data(png_ptr, (png_bytep)new_key, key_len + 1);
  198954. /* set the compression flag */
  198955. if (compression == PNG_ITXT_COMPRESSION_NONE || \
  198956. compression == PNG_TEXT_COMPRESSION_NONE)
  198957. cbuf[0] = 0;
  198958. else /* compression == PNG_ITXT_COMPRESSION_zTXt */
  198959. cbuf[0] = 1;
  198960. /* set the compression method */
  198961. cbuf[1] = 0;
  198962. png_write_chunk_data(png_ptr, cbuf, 2);
  198963. cbuf[0] = 0;
  198964. png_write_chunk_data(png_ptr, (new_lang ? (png_bytep)new_lang : cbuf), lang_len + 1);
  198965. png_write_chunk_data(png_ptr, (lang_key ? (png_bytep)lang_key : cbuf), lang_key_len + 1);
  198966. png_write_compressed_data_out(png_ptr, &comp);
  198967. png_write_chunk_end(png_ptr);
  198968. png_free(png_ptr, new_key);
  198969. if (new_lang)
  198970. png_free(png_ptr, new_lang);
  198971. }
  198972. #endif
  198973. #if defined(PNG_WRITE_oFFs_SUPPORTED)
  198974. /* write the oFFs chunk */
  198975. void /* PRIVATE */
  198976. png_write_oFFs(png_structp png_ptr, png_int_32 x_offset, png_int_32 y_offset,
  198977. int unit_type)
  198978. {
  198979. #ifdef PNG_USE_LOCAL_ARRAYS
  198980. PNG_oFFs;
  198981. #endif
  198982. png_byte buf[9];
  198983. png_debug(1, "in png_write_oFFs\n");
  198984. if (unit_type >= PNG_OFFSET_LAST)
  198985. png_warning(png_ptr, "Unrecognized unit type for oFFs chunk");
  198986. png_save_int_32(buf, x_offset);
  198987. png_save_int_32(buf + 4, y_offset);
  198988. buf[8] = (png_byte)unit_type;
  198989. png_write_chunk(png_ptr, png_oFFs, buf, (png_size_t)9);
  198990. }
  198991. #endif
  198992. #if defined(PNG_WRITE_pCAL_SUPPORTED)
  198993. /* write the pCAL chunk (described in the PNG extensions document) */
  198994. void /* PRIVATE */
  198995. png_write_pCAL(png_structp png_ptr, png_charp purpose, png_int_32 X0,
  198996. png_int_32 X1, int type, int nparams, png_charp units, png_charpp params)
  198997. {
  198998. #ifdef PNG_USE_LOCAL_ARRAYS
  198999. PNG_pCAL;
  199000. #endif
  199001. png_size_t purpose_len, units_len, total_len;
  199002. png_uint_32p params_len;
  199003. png_byte buf[10];
  199004. png_charp new_purpose;
  199005. int i;
  199006. png_debug1(1, "in png_write_pCAL (%d parameters)\n", nparams);
  199007. if (type >= PNG_EQUATION_LAST)
  199008. png_warning(png_ptr, "Unrecognized equation type for pCAL chunk");
  199009. purpose_len = png_check_keyword(png_ptr, purpose, &new_purpose) + 1;
  199010. png_debug1(3, "pCAL purpose length = %d\n", (int)purpose_len);
  199011. units_len = png_strlen(units) + (nparams == 0 ? 0 : 1);
  199012. png_debug1(3, "pCAL units length = %d\n", (int)units_len);
  199013. total_len = purpose_len + units_len + 10;
  199014. params_len = (png_uint_32p)png_malloc(png_ptr, (png_uint_32)(nparams
  199015. *png_sizeof(png_uint_32)));
  199016. /* Find the length of each parameter, making sure we don't count the
  199017. null terminator for the last parameter. */
  199018. for (i = 0; i < nparams; i++)
  199019. {
  199020. params_len[i] = png_strlen(params[i]) + (i == nparams - 1 ? 0 : 1);
  199021. png_debug2(3, "pCAL parameter %d length = %lu\n", i, params_len[i]);
  199022. total_len += (png_size_t)params_len[i];
  199023. }
  199024. png_debug1(3, "pCAL total length = %d\n", (int)total_len);
  199025. png_write_chunk_start(png_ptr, png_pCAL, (png_uint_32)total_len);
  199026. png_write_chunk_data(png_ptr, (png_bytep)new_purpose, purpose_len);
  199027. png_save_int_32(buf, X0);
  199028. png_save_int_32(buf + 4, X1);
  199029. buf[8] = (png_byte)type;
  199030. buf[9] = (png_byte)nparams;
  199031. png_write_chunk_data(png_ptr, buf, (png_size_t)10);
  199032. png_write_chunk_data(png_ptr, (png_bytep)units, (png_size_t)units_len);
  199033. png_free(png_ptr, new_purpose);
  199034. for (i = 0; i < nparams; i++)
  199035. {
  199036. png_write_chunk_data(png_ptr, (png_bytep)params[i],
  199037. (png_size_t)params_len[i]);
  199038. }
  199039. png_free(png_ptr, params_len);
  199040. png_write_chunk_end(png_ptr);
  199041. }
  199042. #endif
  199043. #if defined(PNG_WRITE_sCAL_SUPPORTED)
  199044. /* write the sCAL chunk */
  199045. #if defined(PNG_FLOATING_POINT_SUPPORTED) && !defined(PNG_NO_STDIO)
  199046. void /* PRIVATE */
  199047. png_write_sCAL(png_structp png_ptr, int unit, double width, double height)
  199048. {
  199049. #ifdef PNG_USE_LOCAL_ARRAYS
  199050. PNG_sCAL;
  199051. #endif
  199052. char buf[64];
  199053. png_size_t total_len;
  199054. png_debug(1, "in png_write_sCAL\n");
  199055. buf[0] = (char)unit;
  199056. #if defined(_WIN32_WCE)
  199057. /* sprintf() function is not supported on WindowsCE */
  199058. {
  199059. wchar_t wc_buf[32];
  199060. size_t wc_len;
  199061. swprintf(wc_buf, TEXT("%12.12e"), width);
  199062. wc_len = wcslen(wc_buf);
  199063. WideCharToMultiByte(CP_ACP, 0, wc_buf, -1, buf + 1, wc_len, NULL, NULL);
  199064. total_len = wc_len + 2;
  199065. swprintf(wc_buf, TEXT("%12.12e"), height);
  199066. wc_len = wcslen(wc_buf);
  199067. WideCharToMultiByte(CP_ACP, 0, wc_buf, -1, buf + total_len, wc_len,
  199068. NULL, NULL);
  199069. total_len += wc_len;
  199070. }
  199071. #else
  199072. png_snprintf(buf + 1, 63, "%12.12e", width);
  199073. total_len = 1 + png_strlen(buf + 1) + 1;
  199074. png_snprintf(buf + total_len, 64-total_len, "%12.12e", height);
  199075. total_len += png_strlen(buf + total_len);
  199076. #endif
  199077. png_debug1(3, "sCAL total length = %u\n", (unsigned int)total_len);
  199078. png_write_chunk(png_ptr, png_sCAL, (png_bytep)buf, total_len);
  199079. }
  199080. #else
  199081. #ifdef PNG_FIXED_POINT_SUPPORTED
  199082. void /* PRIVATE */
  199083. png_write_sCAL_s(png_structp png_ptr, int unit, png_charp width,
  199084. png_charp height)
  199085. {
  199086. #ifdef PNG_USE_LOCAL_ARRAYS
  199087. PNG_sCAL;
  199088. #endif
  199089. png_byte buf[64];
  199090. png_size_t wlen, hlen, total_len;
  199091. png_debug(1, "in png_write_sCAL_s\n");
  199092. wlen = png_strlen(width);
  199093. hlen = png_strlen(height);
  199094. total_len = wlen + hlen + 2;
  199095. if (total_len > 64)
  199096. {
  199097. png_warning(png_ptr, "Can't write sCAL (buffer too small)");
  199098. return;
  199099. }
  199100. buf[0] = (png_byte)unit;
  199101. png_memcpy(buf + 1, width, wlen + 1); /* append the '\0' here */
  199102. png_memcpy(buf + wlen + 2, height, hlen); /* do NOT append the '\0' here */
  199103. png_debug1(3, "sCAL total length = %u\n", (unsigned int)total_len);
  199104. png_write_chunk(png_ptr, png_sCAL, buf, total_len);
  199105. }
  199106. #endif
  199107. #endif
  199108. #endif
  199109. #if defined(PNG_WRITE_pHYs_SUPPORTED)
  199110. /* write the pHYs chunk */
  199111. void /* PRIVATE */
  199112. png_write_pHYs(png_structp png_ptr, png_uint_32 x_pixels_per_unit,
  199113. png_uint_32 y_pixels_per_unit,
  199114. int unit_type)
  199115. {
  199116. #ifdef PNG_USE_LOCAL_ARRAYS
  199117. PNG_pHYs;
  199118. #endif
  199119. png_byte buf[9];
  199120. png_debug(1, "in png_write_pHYs\n");
  199121. if (unit_type >= PNG_RESOLUTION_LAST)
  199122. png_warning(png_ptr, "Unrecognized unit type for pHYs chunk");
  199123. png_save_uint_32(buf, x_pixels_per_unit);
  199124. png_save_uint_32(buf + 4, y_pixels_per_unit);
  199125. buf[8] = (png_byte)unit_type;
  199126. png_write_chunk(png_ptr, png_pHYs, buf, (png_size_t)9);
  199127. }
  199128. #endif
  199129. #if defined(PNG_WRITE_tIME_SUPPORTED)
  199130. /* Write the tIME chunk. Use either png_convert_from_struct_tm()
  199131. * or png_convert_from_time_t(), or fill in the structure yourself.
  199132. */
  199133. void /* PRIVATE */
  199134. png_write_tIME(png_structp png_ptr, png_timep mod_time)
  199135. {
  199136. #ifdef PNG_USE_LOCAL_ARRAYS
  199137. PNG_tIME;
  199138. #endif
  199139. png_byte buf[7];
  199140. png_debug(1, "in png_write_tIME\n");
  199141. if (mod_time->month > 12 || mod_time->month < 1 ||
  199142. mod_time->day > 31 || mod_time->day < 1 ||
  199143. mod_time->hour > 23 || mod_time->second > 60)
  199144. {
  199145. png_warning(png_ptr, "Invalid time specified for tIME chunk");
  199146. return;
  199147. }
  199148. png_save_uint_16(buf, mod_time->year);
  199149. buf[2] = mod_time->month;
  199150. buf[3] = mod_time->day;
  199151. buf[4] = mod_time->hour;
  199152. buf[5] = mod_time->minute;
  199153. buf[6] = mod_time->second;
  199154. png_write_chunk(png_ptr, png_tIME, buf, (png_size_t)7);
  199155. }
  199156. #endif
  199157. /* initializes the row writing capability of libpng */
  199158. void /* PRIVATE */
  199159. png_write_start_row(png_structp png_ptr)
  199160. {
  199161. #ifdef PNG_WRITE_INTERLACING_SUPPORTED
  199162. #ifdef PNG_USE_LOCAL_ARRAYS
  199163. /* arrays to facilitate easy interlacing - use pass (0 - 6) as index */
  199164. /* start of interlace block */
  199165. int png_pass_start[7] = {0, 4, 0, 2, 0, 1, 0};
  199166. /* offset to next interlace block */
  199167. int png_pass_inc[7] = {8, 8, 4, 4, 2, 2, 1};
  199168. /* start of interlace block in the y direction */
  199169. int png_pass_ystart[7] = {0, 0, 4, 0, 2, 0, 1};
  199170. /* offset to next interlace block in the y direction */
  199171. int png_pass_yinc[7] = {8, 8, 8, 4, 4, 2, 2};
  199172. #endif
  199173. #endif
  199174. png_size_t buf_size;
  199175. png_debug(1, "in png_write_start_row\n");
  199176. buf_size = (png_size_t)(PNG_ROWBYTES(
  199177. png_ptr->usr_channels*png_ptr->usr_bit_depth,png_ptr->width)+1);
  199178. /* set up row buffer */
  199179. png_ptr->row_buf = (png_bytep)png_malloc(png_ptr, (png_uint_32)buf_size);
  199180. png_ptr->row_buf[0] = PNG_FILTER_VALUE_NONE;
  199181. #ifndef PNG_NO_WRITE_FILTERING
  199182. /* set up filtering buffer, if using this filter */
  199183. if (png_ptr->do_filter & PNG_FILTER_SUB)
  199184. {
  199185. png_ptr->sub_row = (png_bytep)png_malloc(png_ptr,
  199186. (png_ptr->rowbytes + 1));
  199187. png_ptr->sub_row[0] = PNG_FILTER_VALUE_SUB;
  199188. }
  199189. /* We only need to keep the previous row if we are using one of these. */
  199190. if (png_ptr->do_filter & (PNG_FILTER_AVG | PNG_FILTER_UP | PNG_FILTER_PAETH))
  199191. {
  199192. /* set up previous row buffer */
  199193. png_ptr->prev_row = (png_bytep)png_malloc(png_ptr, (png_uint_32)buf_size);
  199194. png_memset(png_ptr->prev_row, 0, buf_size);
  199195. if (png_ptr->do_filter & PNG_FILTER_UP)
  199196. {
  199197. png_ptr->up_row = (png_bytep)png_malloc(png_ptr,
  199198. (png_ptr->rowbytes + 1));
  199199. png_ptr->up_row[0] = PNG_FILTER_VALUE_UP;
  199200. }
  199201. if (png_ptr->do_filter & PNG_FILTER_AVG)
  199202. {
  199203. png_ptr->avg_row = (png_bytep)png_malloc(png_ptr,
  199204. (png_ptr->rowbytes + 1));
  199205. png_ptr->avg_row[0] = PNG_FILTER_VALUE_AVG;
  199206. }
  199207. if (png_ptr->do_filter & PNG_FILTER_PAETH)
  199208. {
  199209. png_ptr->paeth_row = (png_bytep)png_malloc(png_ptr,
  199210. (png_ptr->rowbytes + 1));
  199211. png_ptr->paeth_row[0] = PNG_FILTER_VALUE_PAETH;
  199212. }
  199213. #endif /* PNG_NO_WRITE_FILTERING */
  199214. }
  199215. #ifdef PNG_WRITE_INTERLACING_SUPPORTED
  199216. /* if interlaced, we need to set up width and height of pass */
  199217. if (png_ptr->interlaced)
  199218. {
  199219. if (!(png_ptr->transformations & PNG_INTERLACE))
  199220. {
  199221. png_ptr->num_rows = (png_ptr->height + png_pass_yinc[0] - 1 -
  199222. png_pass_ystart[0]) / png_pass_yinc[0];
  199223. png_ptr->usr_width = (png_ptr->width + png_pass_inc[0] - 1 -
  199224. png_pass_start[0]) / png_pass_inc[0];
  199225. }
  199226. else
  199227. {
  199228. png_ptr->num_rows = png_ptr->height;
  199229. png_ptr->usr_width = png_ptr->width;
  199230. }
  199231. }
  199232. else
  199233. #endif
  199234. {
  199235. png_ptr->num_rows = png_ptr->height;
  199236. png_ptr->usr_width = png_ptr->width;
  199237. }
  199238. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  199239. png_ptr->zstream.next_out = png_ptr->zbuf;
  199240. }
  199241. /* Internal use only. Called when finished processing a row of data. */
  199242. void /* PRIVATE */
  199243. png_write_finish_row(png_structp png_ptr)
  199244. {
  199245. #ifdef PNG_WRITE_INTERLACING_SUPPORTED
  199246. #ifdef PNG_USE_LOCAL_ARRAYS
  199247. /* arrays to facilitate easy interlacing - use pass (0 - 6) as index */
  199248. /* start of interlace block */
  199249. int png_pass_start[7] = {0, 4, 0, 2, 0, 1, 0};
  199250. /* offset to next interlace block */
  199251. int png_pass_inc[7] = {8, 8, 4, 4, 2, 2, 1};
  199252. /* start of interlace block in the y direction */
  199253. int png_pass_ystart[7] = {0, 0, 4, 0, 2, 0, 1};
  199254. /* offset to next interlace block in the y direction */
  199255. int png_pass_yinc[7] = {8, 8, 8, 4, 4, 2, 2};
  199256. #endif
  199257. #endif
  199258. int ret;
  199259. png_debug(1, "in png_write_finish_row\n");
  199260. /* next row */
  199261. png_ptr->row_number++;
  199262. /* see if we are done */
  199263. if (png_ptr->row_number < png_ptr->num_rows)
  199264. return;
  199265. #ifdef PNG_WRITE_INTERLACING_SUPPORTED
  199266. /* if interlaced, go to next pass */
  199267. if (png_ptr->interlaced)
  199268. {
  199269. png_ptr->row_number = 0;
  199270. if (png_ptr->transformations & PNG_INTERLACE)
  199271. {
  199272. png_ptr->pass++;
  199273. }
  199274. else
  199275. {
  199276. /* loop until we find a non-zero width or height pass */
  199277. do
  199278. {
  199279. png_ptr->pass++;
  199280. if (png_ptr->pass >= 7)
  199281. break;
  199282. png_ptr->usr_width = (png_ptr->width +
  199283. png_pass_inc[png_ptr->pass] - 1 -
  199284. png_pass_start[png_ptr->pass]) /
  199285. png_pass_inc[png_ptr->pass];
  199286. png_ptr->num_rows = (png_ptr->height +
  199287. png_pass_yinc[png_ptr->pass] - 1 -
  199288. png_pass_ystart[png_ptr->pass]) /
  199289. png_pass_yinc[png_ptr->pass];
  199290. if (png_ptr->transformations & PNG_INTERLACE)
  199291. break;
  199292. } while (png_ptr->usr_width == 0 || png_ptr->num_rows == 0);
  199293. }
  199294. /* reset the row above the image for the next pass */
  199295. if (png_ptr->pass < 7)
  199296. {
  199297. if (png_ptr->prev_row != NULL)
  199298. png_memset(png_ptr->prev_row, 0,
  199299. (png_size_t)(PNG_ROWBYTES(png_ptr->usr_channels*
  199300. png_ptr->usr_bit_depth,png_ptr->width))+1);
  199301. return;
  199302. }
  199303. }
  199304. #endif
  199305. /* if we get here, we've just written the last row, so we need
  199306. to flush the compressor */
  199307. do
  199308. {
  199309. /* tell the compressor we are done */
  199310. ret = deflate(&png_ptr->zstream, Z_FINISH);
  199311. /* check for an error */
  199312. if (ret == Z_OK)
  199313. {
  199314. /* check to see if we need more room */
  199315. if (!(png_ptr->zstream.avail_out))
  199316. {
  199317. png_write_IDAT(png_ptr, png_ptr->zbuf, png_ptr->zbuf_size);
  199318. png_ptr->zstream.next_out = png_ptr->zbuf;
  199319. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  199320. }
  199321. }
  199322. else if (ret != Z_STREAM_END)
  199323. {
  199324. if (png_ptr->zstream.msg != NULL)
  199325. png_error(png_ptr, png_ptr->zstream.msg);
  199326. else
  199327. png_error(png_ptr, "zlib error");
  199328. }
  199329. } while (ret != Z_STREAM_END);
  199330. /* write any extra space */
  199331. if (png_ptr->zstream.avail_out < png_ptr->zbuf_size)
  199332. {
  199333. png_write_IDAT(png_ptr, png_ptr->zbuf, png_ptr->zbuf_size -
  199334. png_ptr->zstream.avail_out);
  199335. }
  199336. deflateReset(&png_ptr->zstream);
  199337. png_ptr->zstream.data_type = Z_BINARY;
  199338. }
  199339. #if defined(PNG_WRITE_INTERLACING_SUPPORTED)
  199340. /* Pick out the correct pixels for the interlace pass.
  199341. * The basic idea here is to go through the row with a source
  199342. * pointer and a destination pointer (sp and dp), and copy the
  199343. * correct pixels for the pass. As the row gets compacted,
  199344. * sp will always be >= dp, so we should never overwrite anything.
  199345. * See the default: case for the easiest code to understand.
  199346. */
  199347. void /* PRIVATE */
  199348. png_do_write_interlace(png_row_infop row_info, png_bytep row, int pass)
  199349. {
  199350. #ifdef PNG_USE_LOCAL_ARRAYS
  199351. /* arrays to facilitate easy interlacing - use pass (0 - 6) as index */
  199352. /* start of interlace block */
  199353. int png_pass_start[7] = {0, 4, 0, 2, 0, 1, 0};
  199354. /* offset to next interlace block */
  199355. int png_pass_inc[7] = {8, 8, 4, 4, 2, 2, 1};
  199356. #endif
  199357. png_debug(1, "in png_do_write_interlace\n");
  199358. /* we don't have to do anything on the last pass (6) */
  199359. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  199360. if (row != NULL && row_info != NULL && pass < 6)
  199361. #else
  199362. if (pass < 6)
  199363. #endif
  199364. {
  199365. /* each pixel depth is handled separately */
  199366. switch (row_info->pixel_depth)
  199367. {
  199368. case 1:
  199369. {
  199370. png_bytep sp;
  199371. png_bytep dp;
  199372. int shift;
  199373. int d;
  199374. int value;
  199375. png_uint_32 i;
  199376. png_uint_32 row_width = row_info->width;
  199377. dp = row;
  199378. d = 0;
  199379. shift = 7;
  199380. for (i = png_pass_start[pass]; i < row_width;
  199381. i += png_pass_inc[pass])
  199382. {
  199383. sp = row + (png_size_t)(i >> 3);
  199384. value = (int)(*sp >> (7 - (int)(i & 0x07))) & 0x01;
  199385. d |= (value << shift);
  199386. if (shift == 0)
  199387. {
  199388. shift = 7;
  199389. *dp++ = (png_byte)d;
  199390. d = 0;
  199391. }
  199392. else
  199393. shift--;
  199394. }
  199395. if (shift != 7)
  199396. *dp = (png_byte)d;
  199397. break;
  199398. }
  199399. case 2:
  199400. {
  199401. png_bytep sp;
  199402. png_bytep dp;
  199403. int shift;
  199404. int d;
  199405. int value;
  199406. png_uint_32 i;
  199407. png_uint_32 row_width = row_info->width;
  199408. dp = row;
  199409. shift = 6;
  199410. d = 0;
  199411. for (i = png_pass_start[pass]; i < row_width;
  199412. i += png_pass_inc[pass])
  199413. {
  199414. sp = row + (png_size_t)(i >> 2);
  199415. value = (*sp >> ((3 - (int)(i & 0x03)) << 1)) & 0x03;
  199416. d |= (value << shift);
  199417. if (shift == 0)
  199418. {
  199419. shift = 6;
  199420. *dp++ = (png_byte)d;
  199421. d = 0;
  199422. }
  199423. else
  199424. shift -= 2;
  199425. }
  199426. if (shift != 6)
  199427. *dp = (png_byte)d;
  199428. break;
  199429. }
  199430. case 4:
  199431. {
  199432. png_bytep sp;
  199433. png_bytep dp;
  199434. int shift;
  199435. int d;
  199436. int value;
  199437. png_uint_32 i;
  199438. png_uint_32 row_width = row_info->width;
  199439. dp = row;
  199440. shift = 4;
  199441. d = 0;
  199442. for (i = png_pass_start[pass]; i < row_width;
  199443. i += png_pass_inc[pass])
  199444. {
  199445. sp = row + (png_size_t)(i >> 1);
  199446. value = (*sp >> ((1 - (int)(i & 0x01)) << 2)) & 0x0f;
  199447. d |= (value << shift);
  199448. if (shift == 0)
  199449. {
  199450. shift = 4;
  199451. *dp++ = (png_byte)d;
  199452. d = 0;
  199453. }
  199454. else
  199455. shift -= 4;
  199456. }
  199457. if (shift != 4)
  199458. *dp = (png_byte)d;
  199459. break;
  199460. }
  199461. default:
  199462. {
  199463. png_bytep sp;
  199464. png_bytep dp;
  199465. png_uint_32 i;
  199466. png_uint_32 row_width = row_info->width;
  199467. png_size_t pixel_bytes;
  199468. /* start at the beginning */
  199469. dp = row;
  199470. /* find out how many bytes each pixel takes up */
  199471. pixel_bytes = (row_info->pixel_depth >> 3);
  199472. /* loop through the row, only looking at the pixels that
  199473. matter */
  199474. for (i = png_pass_start[pass]; i < row_width;
  199475. i += png_pass_inc[pass])
  199476. {
  199477. /* find out where the original pixel is */
  199478. sp = row + (png_size_t)i * pixel_bytes;
  199479. /* move the pixel */
  199480. if (dp != sp)
  199481. png_memcpy(dp, sp, pixel_bytes);
  199482. /* next pixel */
  199483. dp += pixel_bytes;
  199484. }
  199485. break;
  199486. }
  199487. }
  199488. /* set new row width */
  199489. row_info->width = (row_info->width +
  199490. png_pass_inc[pass] - 1 -
  199491. png_pass_start[pass]) /
  199492. png_pass_inc[pass];
  199493. row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,
  199494. row_info->width);
  199495. }
  199496. }
  199497. #endif
  199498. /* This filters the row, chooses which filter to use, if it has not already
  199499. * been specified by the application, and then writes the row out with the
  199500. * chosen filter.
  199501. */
  199502. #define PNG_MAXSUM (((png_uint_32)(-1)) >> 1)
  199503. #define PNG_HISHIFT 10
  199504. #define PNG_LOMASK ((png_uint_32)0xffffL)
  199505. #define PNG_HIMASK ((png_uint_32)(~PNG_LOMASK >> PNG_HISHIFT))
  199506. void /* PRIVATE */
  199507. png_write_find_filter(png_structp png_ptr, png_row_infop row_info)
  199508. {
  199509. png_bytep best_row;
  199510. #ifndef PNG_NO_WRITE_FILTER
  199511. png_bytep prev_row, row_buf;
  199512. png_uint_32 mins, bpp;
  199513. png_byte filter_to_do = png_ptr->do_filter;
  199514. png_uint_32 row_bytes = row_info->rowbytes;
  199515. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  199516. int num_p_filters = (int)png_ptr->num_prev_filters;
  199517. #endif
  199518. png_debug(1, "in png_write_find_filter\n");
  199519. /* find out how many bytes offset each pixel is */
  199520. bpp = (row_info->pixel_depth + 7) >> 3;
  199521. prev_row = png_ptr->prev_row;
  199522. #endif
  199523. best_row = png_ptr->row_buf;
  199524. #ifndef PNG_NO_WRITE_FILTER
  199525. row_buf = best_row;
  199526. mins = PNG_MAXSUM;
  199527. /* The prediction method we use is to find which method provides the
  199528. * smallest value when summing the absolute values of the distances
  199529. * from zero, using anything >= 128 as negative numbers. This is known
  199530. * as the "minimum sum of absolute differences" heuristic. Other
  199531. * heuristics are the "weighted minimum sum of absolute differences"
  199532. * (experimental and can in theory improve compression), and the "zlib
  199533. * predictive" method (not implemented yet), which does test compressions
  199534. * of lines using different filter methods, and then chooses the
  199535. * (series of) filter(s) that give minimum compressed data size (VERY
  199536. * computationally expensive).
  199537. *
  199538. * GRR 980525: consider also
  199539. * (1) minimum sum of absolute differences from running average (i.e.,
  199540. * keep running sum of non-absolute differences & count of bytes)
  199541. * [track dispersion, too? restart average if dispersion too large?]
  199542. * (1b) minimum sum of absolute differences from sliding average, probably
  199543. * with window size <= deflate window (usually 32K)
  199544. * (2) minimum sum of squared differences from zero or running average
  199545. * (i.e., ~ root-mean-square approach)
  199546. */
  199547. /* We don't need to test the 'no filter' case if this is the only filter
  199548. * that has been chosen, as it doesn't actually do anything to the data.
  199549. */
  199550. if ((filter_to_do & PNG_FILTER_NONE) &&
  199551. filter_to_do != PNG_FILTER_NONE)
  199552. {
  199553. png_bytep rp;
  199554. png_uint_32 sum = 0;
  199555. png_uint_32 i;
  199556. int v;
  199557. for (i = 0, rp = row_buf + 1; i < row_bytes; i++, rp++)
  199558. {
  199559. v = *rp;
  199560. sum += (v < 128) ? v : 256 - v;
  199561. }
  199562. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  199563. if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
  199564. {
  199565. png_uint_32 sumhi, sumlo;
  199566. int j;
  199567. sumlo = sum & PNG_LOMASK;
  199568. sumhi = (sum >> PNG_HISHIFT) & PNG_HIMASK; /* Gives us some footroom */
  199569. /* Reduce the sum if we match any of the previous rows */
  199570. for (j = 0; j < num_p_filters; j++)
  199571. {
  199572. if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_NONE)
  199573. {
  199574. sumlo = (sumlo * png_ptr->filter_weights[j]) >>
  199575. PNG_WEIGHT_SHIFT;
  199576. sumhi = (sumhi * png_ptr->filter_weights[j]) >>
  199577. PNG_WEIGHT_SHIFT;
  199578. }
  199579. }
  199580. /* Factor in the cost of this filter (this is here for completeness,
  199581. * but it makes no sense to have a "cost" for the NONE filter, as
  199582. * it has the minimum possible computational cost - none).
  199583. */
  199584. sumlo = (sumlo * png_ptr->filter_costs[PNG_FILTER_VALUE_NONE]) >>
  199585. PNG_COST_SHIFT;
  199586. sumhi = (sumhi * png_ptr->filter_costs[PNG_FILTER_VALUE_NONE]) >>
  199587. PNG_COST_SHIFT;
  199588. if (sumhi > PNG_HIMASK)
  199589. sum = PNG_MAXSUM;
  199590. else
  199591. sum = (sumhi << PNG_HISHIFT) + sumlo;
  199592. }
  199593. #endif
  199594. mins = sum;
  199595. }
  199596. /* sub filter */
  199597. if (filter_to_do == PNG_FILTER_SUB)
  199598. /* it's the only filter so no testing is needed */
  199599. {
  199600. png_bytep rp, lp, dp;
  199601. png_uint_32 i;
  199602. for (i = 0, rp = row_buf + 1, dp = png_ptr->sub_row + 1; i < bpp;
  199603. i++, rp++, dp++)
  199604. {
  199605. *dp = *rp;
  199606. }
  199607. for (lp = row_buf + 1; i < row_bytes;
  199608. i++, rp++, lp++, dp++)
  199609. {
  199610. *dp = (png_byte)(((int)*rp - (int)*lp) & 0xff);
  199611. }
  199612. best_row = png_ptr->sub_row;
  199613. }
  199614. else if (filter_to_do & PNG_FILTER_SUB)
  199615. {
  199616. png_bytep rp, dp, lp;
  199617. png_uint_32 sum = 0, lmins = mins;
  199618. png_uint_32 i;
  199619. int v;
  199620. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  199621. /* We temporarily increase the "minimum sum" by the factor we
  199622. * would reduce the sum of this filter, so that we can do the
  199623. * early exit comparison without scaling the sum each time.
  199624. */
  199625. if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
  199626. {
  199627. int j;
  199628. png_uint_32 lmhi, lmlo;
  199629. lmlo = lmins & PNG_LOMASK;
  199630. lmhi = (lmins >> PNG_HISHIFT) & PNG_HIMASK;
  199631. for (j = 0; j < num_p_filters; j++)
  199632. {
  199633. if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_SUB)
  199634. {
  199635. lmlo = (lmlo * png_ptr->inv_filter_weights[j]) >>
  199636. PNG_WEIGHT_SHIFT;
  199637. lmhi = (lmhi * png_ptr->inv_filter_weights[j]) >>
  199638. PNG_WEIGHT_SHIFT;
  199639. }
  199640. }
  199641. lmlo = (lmlo * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_SUB]) >>
  199642. PNG_COST_SHIFT;
  199643. lmhi = (lmhi * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_SUB]) >>
  199644. PNG_COST_SHIFT;
  199645. if (lmhi > PNG_HIMASK)
  199646. lmins = PNG_MAXSUM;
  199647. else
  199648. lmins = (lmhi << PNG_HISHIFT) + lmlo;
  199649. }
  199650. #endif
  199651. for (i = 0, rp = row_buf + 1, dp = png_ptr->sub_row + 1; i < bpp;
  199652. i++, rp++, dp++)
  199653. {
  199654. v = *dp = *rp;
  199655. sum += (v < 128) ? v : 256 - v;
  199656. }
  199657. for (lp = row_buf + 1; i < row_bytes;
  199658. i++, rp++, lp++, dp++)
  199659. {
  199660. v = *dp = (png_byte)(((int)*rp - (int)*lp) & 0xff);
  199661. sum += (v < 128) ? v : 256 - v;
  199662. if (sum > lmins) /* We are already worse, don't continue. */
  199663. break;
  199664. }
  199665. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  199666. if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
  199667. {
  199668. int j;
  199669. png_uint_32 sumhi, sumlo;
  199670. sumlo = sum & PNG_LOMASK;
  199671. sumhi = (sum >> PNG_HISHIFT) & PNG_HIMASK;
  199672. for (j = 0; j < num_p_filters; j++)
  199673. {
  199674. if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_SUB)
  199675. {
  199676. sumlo = (sumlo * png_ptr->inv_filter_weights[j]) >>
  199677. PNG_WEIGHT_SHIFT;
  199678. sumhi = (sumhi * png_ptr->inv_filter_weights[j]) >>
  199679. PNG_WEIGHT_SHIFT;
  199680. }
  199681. }
  199682. sumlo = (sumlo * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_SUB]) >>
  199683. PNG_COST_SHIFT;
  199684. sumhi = (sumhi * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_SUB]) >>
  199685. PNG_COST_SHIFT;
  199686. if (sumhi > PNG_HIMASK)
  199687. sum = PNG_MAXSUM;
  199688. else
  199689. sum = (sumhi << PNG_HISHIFT) + sumlo;
  199690. }
  199691. #endif
  199692. if (sum < mins)
  199693. {
  199694. mins = sum;
  199695. best_row = png_ptr->sub_row;
  199696. }
  199697. }
  199698. /* up filter */
  199699. if (filter_to_do == PNG_FILTER_UP)
  199700. {
  199701. png_bytep rp, dp, pp;
  199702. png_uint_32 i;
  199703. for (i = 0, rp = row_buf + 1, dp = png_ptr->up_row + 1,
  199704. pp = prev_row + 1; i < row_bytes;
  199705. i++, rp++, pp++, dp++)
  199706. {
  199707. *dp = (png_byte)(((int)*rp - (int)*pp) & 0xff);
  199708. }
  199709. best_row = png_ptr->up_row;
  199710. }
  199711. else if (filter_to_do & PNG_FILTER_UP)
  199712. {
  199713. png_bytep rp, dp, pp;
  199714. png_uint_32 sum = 0, lmins = mins;
  199715. png_uint_32 i;
  199716. int v;
  199717. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  199718. if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
  199719. {
  199720. int j;
  199721. png_uint_32 lmhi, lmlo;
  199722. lmlo = lmins & PNG_LOMASK;
  199723. lmhi = (lmins >> PNG_HISHIFT) & PNG_HIMASK;
  199724. for (j = 0; j < num_p_filters; j++)
  199725. {
  199726. if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_UP)
  199727. {
  199728. lmlo = (lmlo * png_ptr->inv_filter_weights[j]) >>
  199729. PNG_WEIGHT_SHIFT;
  199730. lmhi = (lmhi * png_ptr->inv_filter_weights[j]) >>
  199731. PNG_WEIGHT_SHIFT;
  199732. }
  199733. }
  199734. lmlo = (lmlo * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_UP]) >>
  199735. PNG_COST_SHIFT;
  199736. lmhi = (lmhi * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_UP]) >>
  199737. PNG_COST_SHIFT;
  199738. if (lmhi > PNG_HIMASK)
  199739. lmins = PNG_MAXSUM;
  199740. else
  199741. lmins = (lmhi << PNG_HISHIFT) + lmlo;
  199742. }
  199743. #endif
  199744. for (i = 0, rp = row_buf + 1, dp = png_ptr->up_row + 1,
  199745. pp = prev_row + 1; i < row_bytes; i++)
  199746. {
  199747. v = *dp++ = (png_byte)(((int)*rp++ - (int)*pp++) & 0xff);
  199748. sum += (v < 128) ? v : 256 - v;
  199749. if (sum > lmins) /* We are already worse, don't continue. */
  199750. break;
  199751. }
  199752. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  199753. if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
  199754. {
  199755. int j;
  199756. png_uint_32 sumhi, sumlo;
  199757. sumlo = sum & PNG_LOMASK;
  199758. sumhi = (sum >> PNG_HISHIFT) & PNG_HIMASK;
  199759. for (j = 0; j < num_p_filters; j++)
  199760. {
  199761. if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_UP)
  199762. {
  199763. sumlo = (sumlo * png_ptr->filter_weights[j]) >>
  199764. PNG_WEIGHT_SHIFT;
  199765. sumhi = (sumhi * png_ptr->filter_weights[j]) >>
  199766. PNG_WEIGHT_SHIFT;
  199767. }
  199768. }
  199769. sumlo = (sumlo * png_ptr->filter_costs[PNG_FILTER_VALUE_UP]) >>
  199770. PNG_COST_SHIFT;
  199771. sumhi = (sumhi * png_ptr->filter_costs[PNG_FILTER_VALUE_UP]) >>
  199772. PNG_COST_SHIFT;
  199773. if (sumhi > PNG_HIMASK)
  199774. sum = PNG_MAXSUM;
  199775. else
  199776. sum = (sumhi << PNG_HISHIFT) + sumlo;
  199777. }
  199778. #endif
  199779. if (sum < mins)
  199780. {
  199781. mins = sum;
  199782. best_row = png_ptr->up_row;
  199783. }
  199784. }
  199785. /* avg filter */
  199786. if (filter_to_do == PNG_FILTER_AVG)
  199787. {
  199788. png_bytep rp, dp, pp, lp;
  199789. png_uint_32 i;
  199790. for (i = 0, rp = row_buf + 1, dp = png_ptr->avg_row + 1,
  199791. pp = prev_row + 1; i < bpp; i++)
  199792. {
  199793. *dp++ = (png_byte)(((int)*rp++ - ((int)*pp++ / 2)) & 0xff);
  199794. }
  199795. for (lp = row_buf + 1; i < row_bytes; i++)
  199796. {
  199797. *dp++ = (png_byte)(((int)*rp++ - (((int)*pp++ + (int)*lp++) / 2))
  199798. & 0xff);
  199799. }
  199800. best_row = png_ptr->avg_row;
  199801. }
  199802. else if (filter_to_do & PNG_FILTER_AVG)
  199803. {
  199804. png_bytep rp, dp, pp, lp;
  199805. png_uint_32 sum = 0, lmins = mins;
  199806. png_uint_32 i;
  199807. int v;
  199808. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  199809. if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
  199810. {
  199811. int j;
  199812. png_uint_32 lmhi, lmlo;
  199813. lmlo = lmins & PNG_LOMASK;
  199814. lmhi = (lmins >> PNG_HISHIFT) & PNG_HIMASK;
  199815. for (j = 0; j < num_p_filters; j++)
  199816. {
  199817. if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_AVG)
  199818. {
  199819. lmlo = (lmlo * png_ptr->inv_filter_weights[j]) >>
  199820. PNG_WEIGHT_SHIFT;
  199821. lmhi = (lmhi * png_ptr->inv_filter_weights[j]) >>
  199822. PNG_WEIGHT_SHIFT;
  199823. }
  199824. }
  199825. lmlo = (lmlo * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_AVG]) >>
  199826. PNG_COST_SHIFT;
  199827. lmhi = (lmhi * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_AVG]) >>
  199828. PNG_COST_SHIFT;
  199829. if (lmhi > PNG_HIMASK)
  199830. lmins = PNG_MAXSUM;
  199831. else
  199832. lmins = (lmhi << PNG_HISHIFT) + lmlo;
  199833. }
  199834. #endif
  199835. for (i = 0, rp = row_buf + 1, dp = png_ptr->avg_row + 1,
  199836. pp = prev_row + 1; i < bpp; i++)
  199837. {
  199838. v = *dp++ = (png_byte)(((int)*rp++ - ((int)*pp++ / 2)) & 0xff);
  199839. sum += (v < 128) ? v : 256 - v;
  199840. }
  199841. for (lp = row_buf + 1; i < row_bytes; i++)
  199842. {
  199843. v = *dp++ =
  199844. (png_byte)(((int)*rp++ - (((int)*pp++ + (int)*lp++) / 2)) & 0xff);
  199845. sum += (v < 128) ? v : 256 - v;
  199846. if (sum > lmins) /* We are already worse, don't continue. */
  199847. break;
  199848. }
  199849. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  199850. if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
  199851. {
  199852. int j;
  199853. png_uint_32 sumhi, sumlo;
  199854. sumlo = sum & PNG_LOMASK;
  199855. sumhi = (sum >> PNG_HISHIFT) & PNG_HIMASK;
  199856. for (j = 0; j < num_p_filters; j++)
  199857. {
  199858. if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_NONE)
  199859. {
  199860. sumlo = (sumlo * png_ptr->filter_weights[j]) >>
  199861. PNG_WEIGHT_SHIFT;
  199862. sumhi = (sumhi * png_ptr->filter_weights[j]) >>
  199863. PNG_WEIGHT_SHIFT;
  199864. }
  199865. }
  199866. sumlo = (sumlo * png_ptr->filter_costs[PNG_FILTER_VALUE_AVG]) >>
  199867. PNG_COST_SHIFT;
  199868. sumhi = (sumhi * png_ptr->filter_costs[PNG_FILTER_VALUE_AVG]) >>
  199869. PNG_COST_SHIFT;
  199870. if (sumhi > PNG_HIMASK)
  199871. sum = PNG_MAXSUM;
  199872. else
  199873. sum = (sumhi << PNG_HISHIFT) + sumlo;
  199874. }
  199875. #endif
  199876. if (sum < mins)
  199877. {
  199878. mins = sum;
  199879. best_row = png_ptr->avg_row;
  199880. }
  199881. }
  199882. /* Paeth filter */
  199883. if (filter_to_do == PNG_FILTER_PAETH)
  199884. {
  199885. png_bytep rp, dp, pp, cp, lp;
  199886. png_uint_32 i;
  199887. for (i = 0, rp = row_buf + 1, dp = png_ptr->paeth_row + 1,
  199888. pp = prev_row + 1; i < bpp; i++)
  199889. {
  199890. *dp++ = (png_byte)(((int)*rp++ - (int)*pp++) & 0xff);
  199891. }
  199892. for (lp = row_buf + 1, cp = prev_row + 1; i < row_bytes; i++)
  199893. {
  199894. int a, b, c, pa, pb, pc, p;
  199895. b = *pp++;
  199896. c = *cp++;
  199897. a = *lp++;
  199898. p = b - c;
  199899. pc = a - c;
  199900. #ifdef PNG_USE_ABS
  199901. pa = abs(p);
  199902. pb = abs(pc);
  199903. pc = abs(p + pc);
  199904. #else
  199905. pa = p < 0 ? -p : p;
  199906. pb = pc < 0 ? -pc : pc;
  199907. pc = (p + pc) < 0 ? -(p + pc) : p + pc;
  199908. #endif
  199909. p = (pa <= pb && pa <=pc) ? a : (pb <= pc) ? b : c;
  199910. *dp++ = (png_byte)(((int)*rp++ - p) & 0xff);
  199911. }
  199912. best_row = png_ptr->paeth_row;
  199913. }
  199914. else if (filter_to_do & PNG_FILTER_PAETH)
  199915. {
  199916. png_bytep rp, dp, pp, cp, lp;
  199917. png_uint_32 sum = 0, lmins = mins;
  199918. png_uint_32 i;
  199919. int v;
  199920. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  199921. if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
  199922. {
  199923. int j;
  199924. png_uint_32 lmhi, lmlo;
  199925. lmlo = lmins & PNG_LOMASK;
  199926. lmhi = (lmins >> PNG_HISHIFT) & PNG_HIMASK;
  199927. for (j = 0; j < num_p_filters; j++)
  199928. {
  199929. if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_PAETH)
  199930. {
  199931. lmlo = (lmlo * png_ptr->inv_filter_weights[j]) >>
  199932. PNG_WEIGHT_SHIFT;
  199933. lmhi = (lmhi * png_ptr->inv_filter_weights[j]) >>
  199934. PNG_WEIGHT_SHIFT;
  199935. }
  199936. }
  199937. lmlo = (lmlo * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_PAETH]) >>
  199938. PNG_COST_SHIFT;
  199939. lmhi = (lmhi * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_PAETH]) >>
  199940. PNG_COST_SHIFT;
  199941. if (lmhi > PNG_HIMASK)
  199942. lmins = PNG_MAXSUM;
  199943. else
  199944. lmins = (lmhi << PNG_HISHIFT) + lmlo;
  199945. }
  199946. #endif
  199947. for (i = 0, rp = row_buf + 1, dp = png_ptr->paeth_row + 1,
  199948. pp = prev_row + 1; i < bpp; i++)
  199949. {
  199950. v = *dp++ = (png_byte)(((int)*rp++ - (int)*pp++) & 0xff);
  199951. sum += (v < 128) ? v : 256 - v;
  199952. }
  199953. for (lp = row_buf + 1, cp = prev_row + 1; i < row_bytes; i++)
  199954. {
  199955. int a, b, c, pa, pb, pc, p;
  199956. b = *pp++;
  199957. c = *cp++;
  199958. a = *lp++;
  199959. #ifndef PNG_SLOW_PAETH
  199960. p = b - c;
  199961. pc = a - c;
  199962. #ifdef PNG_USE_ABS
  199963. pa = abs(p);
  199964. pb = abs(pc);
  199965. pc = abs(p + pc);
  199966. #else
  199967. pa = p < 0 ? -p : p;
  199968. pb = pc < 0 ? -pc : pc;
  199969. pc = (p + pc) < 0 ? -(p + pc) : p + pc;
  199970. #endif
  199971. p = (pa <= pb && pa <=pc) ? a : (pb <= pc) ? b : c;
  199972. #else /* PNG_SLOW_PAETH */
  199973. p = a + b - c;
  199974. pa = abs(p - a);
  199975. pb = abs(p - b);
  199976. pc = abs(p - c);
  199977. if (pa <= pb && pa <= pc)
  199978. p = a;
  199979. else if (pb <= pc)
  199980. p = b;
  199981. else
  199982. p = c;
  199983. #endif /* PNG_SLOW_PAETH */
  199984. v = *dp++ = (png_byte)(((int)*rp++ - p) & 0xff);
  199985. sum += (v < 128) ? v : 256 - v;
  199986. if (sum > lmins) /* We are already worse, don't continue. */
  199987. break;
  199988. }
  199989. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  199990. if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
  199991. {
  199992. int j;
  199993. png_uint_32 sumhi, sumlo;
  199994. sumlo = sum & PNG_LOMASK;
  199995. sumhi = (sum >> PNG_HISHIFT) & PNG_HIMASK;
  199996. for (j = 0; j < num_p_filters; j++)
  199997. {
  199998. if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_PAETH)
  199999. {
  200000. sumlo = (sumlo * png_ptr->filter_weights[j]) >>
  200001. PNG_WEIGHT_SHIFT;
  200002. sumhi = (sumhi * png_ptr->filter_weights[j]) >>
  200003. PNG_WEIGHT_SHIFT;
  200004. }
  200005. }
  200006. sumlo = (sumlo * png_ptr->filter_costs[PNG_FILTER_VALUE_PAETH]) >>
  200007. PNG_COST_SHIFT;
  200008. sumhi = (sumhi * png_ptr->filter_costs[PNG_FILTER_VALUE_PAETH]) >>
  200009. PNG_COST_SHIFT;
  200010. if (sumhi > PNG_HIMASK)
  200011. sum = PNG_MAXSUM;
  200012. else
  200013. sum = (sumhi << PNG_HISHIFT) + sumlo;
  200014. }
  200015. #endif
  200016. if (sum < mins)
  200017. {
  200018. best_row = png_ptr->paeth_row;
  200019. }
  200020. }
  200021. #endif /* PNG_NO_WRITE_FILTER */
  200022. /* Do the actual writing of the filtered row data from the chosen filter. */
  200023. png_write_filtered_row(png_ptr, best_row);
  200024. #ifndef PNG_NO_WRITE_FILTER
  200025. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  200026. /* Save the type of filter we picked this time for future calculations */
  200027. if (png_ptr->num_prev_filters > 0)
  200028. {
  200029. int j;
  200030. for (j = 1; j < num_p_filters; j++)
  200031. {
  200032. png_ptr->prev_filters[j] = png_ptr->prev_filters[j - 1];
  200033. }
  200034. png_ptr->prev_filters[j] = best_row[0];
  200035. }
  200036. #endif
  200037. #endif /* PNG_NO_WRITE_FILTER */
  200038. }
  200039. /* Do the actual writing of a previously filtered row. */
  200040. void /* PRIVATE */
  200041. png_write_filtered_row(png_structp png_ptr, png_bytep filtered_row)
  200042. {
  200043. png_debug(1, "in png_write_filtered_row\n");
  200044. png_debug1(2, "filter = %d\n", filtered_row[0]);
  200045. /* set up the zlib input buffer */
  200046. png_ptr->zstream.next_in = filtered_row;
  200047. png_ptr->zstream.avail_in = (uInt)png_ptr->row_info.rowbytes + 1;
  200048. /* repeat until we have compressed all the data */
  200049. do
  200050. {
  200051. int ret; /* return of zlib */
  200052. /* compress the data */
  200053. ret = deflate(&png_ptr->zstream, Z_NO_FLUSH);
  200054. /* check for compression errors */
  200055. if (ret != Z_OK)
  200056. {
  200057. if (png_ptr->zstream.msg != NULL)
  200058. png_error(png_ptr, png_ptr->zstream.msg);
  200059. else
  200060. png_error(png_ptr, "zlib error");
  200061. }
  200062. /* see if it is time to write another IDAT */
  200063. if (!(png_ptr->zstream.avail_out))
  200064. {
  200065. /* write the IDAT and reset the zlib output buffer */
  200066. png_write_IDAT(png_ptr, png_ptr->zbuf, png_ptr->zbuf_size);
  200067. png_ptr->zstream.next_out = png_ptr->zbuf;
  200068. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  200069. }
  200070. /* repeat until all data has been compressed */
  200071. } while (png_ptr->zstream.avail_in);
  200072. /* swap the current and previous rows */
  200073. if (png_ptr->prev_row != NULL)
  200074. {
  200075. png_bytep tptr;
  200076. tptr = png_ptr->prev_row;
  200077. png_ptr->prev_row = png_ptr->row_buf;
  200078. png_ptr->row_buf = tptr;
  200079. }
  200080. /* finish row - updates counters and flushes zlib if last row */
  200081. png_write_finish_row(png_ptr);
  200082. #if defined(PNG_WRITE_FLUSH_SUPPORTED)
  200083. png_ptr->flush_rows++;
  200084. if (png_ptr->flush_dist > 0 &&
  200085. png_ptr->flush_rows >= png_ptr->flush_dist)
  200086. {
  200087. png_write_flush(png_ptr);
  200088. }
  200089. #endif
  200090. }
  200091. #endif /* PNG_WRITE_SUPPORTED */
  200092. /*** End of inlined file: pngwutil.c ***/
  200093. }
  200094. #else
  200095. extern "C"
  200096. {
  200097. #include <png.h>
  200098. #include <pngconf.h>
  200099. }
  200100. #endif
  200101. }
  200102. #undef max
  200103. #undef min
  200104. #ifdef _MSC_VER
  200105. #pragma warning (pop)
  200106. #endif
  200107. BEGIN_JUCE_NAMESPACE
  200108. using ::calloc;
  200109. using ::malloc;
  200110. using ::free;
  200111. namespace PNGHelpers
  200112. {
  200113. using namespace pnglibNamespace;
  200114. static void readCallback (png_structp png, png_bytep data, png_size_t length)
  200115. {
  200116. static_cast<InputStream*> (png_get_io_ptr (png))->read (data, (int) length);
  200117. }
  200118. static void writeDataCallback (png_structp png, png_bytep data, png_size_t length)
  200119. {
  200120. static_cast<OutputStream*> (png_get_io_ptr (png))->write (data, (int) length);
  200121. }
  200122. struct PNGErrorStruct {};
  200123. static void errorCallback (png_structp, png_const_charp)
  200124. {
  200125. throw PNGErrorStruct();
  200126. }
  200127. }
  200128. PNGImageFormat::PNGImageFormat() {}
  200129. PNGImageFormat::~PNGImageFormat() {}
  200130. const String PNGImageFormat::getFormatName()
  200131. {
  200132. return "PNG";
  200133. }
  200134. bool PNGImageFormat::canUnderstand (InputStream& in)
  200135. {
  200136. const int bytesNeeded = 4;
  200137. char header [bytesNeeded];
  200138. return in.read (header, bytesNeeded) == bytesNeeded
  200139. && header[1] == 'P'
  200140. && header[2] == 'N'
  200141. && header[3] == 'G';
  200142. }
  200143. Image* PNGImageFormat::decodeImage (InputStream& in)
  200144. {
  200145. using namespace pnglibNamespace;
  200146. Image* image = 0;
  200147. png_structp pngReadStruct;
  200148. png_infop pngInfoStruct;
  200149. pngReadStruct = png_create_read_struct (PNG_LIBPNG_VER_STRING, 0, 0, 0);
  200150. if (pngReadStruct != 0)
  200151. {
  200152. pngInfoStruct = png_create_info_struct (pngReadStruct);
  200153. if (pngInfoStruct == 0)
  200154. {
  200155. png_destroy_read_struct (&pngReadStruct, 0, 0);
  200156. return 0;
  200157. }
  200158. png_set_error_fn (pngReadStruct, 0, PNGHelpers::errorCallback, PNGHelpers::errorCallback );
  200159. // read the header..
  200160. png_set_read_fn (pngReadStruct, &in, PNGHelpers::readCallback);
  200161. png_uint_32 width, height;
  200162. int bitDepth, colorType, interlaceType;
  200163. png_read_info (pngReadStruct, pngInfoStruct);
  200164. png_get_IHDR (pngReadStruct, pngInfoStruct,
  200165. &width, &height,
  200166. &bitDepth, &colorType,
  200167. &interlaceType, 0, 0);
  200168. if (bitDepth == 16)
  200169. png_set_strip_16 (pngReadStruct);
  200170. if (colorType == PNG_COLOR_TYPE_PALETTE)
  200171. png_set_expand (pngReadStruct);
  200172. if (bitDepth < 8)
  200173. png_set_expand (pngReadStruct);
  200174. if (png_get_valid (pngReadStruct, pngInfoStruct, PNG_INFO_tRNS))
  200175. png_set_expand (pngReadStruct);
  200176. if (colorType == PNG_COLOR_TYPE_GRAY || colorType == PNG_COLOR_TYPE_GRAY_ALPHA)
  200177. png_set_gray_to_rgb (pngReadStruct);
  200178. png_set_add_alpha (pngReadStruct, 0xff, PNG_FILLER_AFTER);
  200179. bool hasAlphaChan = (colorType & PNG_COLOR_MASK_ALPHA) != 0
  200180. || pngInfoStruct->num_trans > 0;
  200181. // Load the image into a temp buffer in the pnglib format..
  200182. HeapBlock <uint8> tempBuffer (height * (width << 2));
  200183. {
  200184. HeapBlock <png_bytep> rows (height);
  200185. for (int y = (int) height; --y >= 0;)
  200186. rows[y] = (png_bytep) (tempBuffer + (width << 2) * y);
  200187. png_read_image (pngReadStruct, rows);
  200188. png_read_end (pngReadStruct, pngInfoStruct);
  200189. }
  200190. png_destroy_read_struct (&pngReadStruct, &pngInfoStruct, 0);
  200191. // now convert the data to a juce image format..
  200192. image = Image::createNativeImage (hasAlphaChan ? Image::ARGB : Image::RGB,
  200193. (int) width, (int) height, hasAlphaChan);
  200194. hasAlphaChan = image->hasAlphaChannel(); // (the native image creator may not give back what we expect)
  200195. const Image::BitmapData destData (*image, 0, 0, (int) width, (int) height, true);
  200196. uint8* srcRow = tempBuffer;
  200197. uint8* destRow = destData.data;
  200198. for (int y = 0; y < (int) height; ++y)
  200199. {
  200200. const uint8* src = srcRow;
  200201. srcRow += (width << 2);
  200202. uint8* dest = destRow;
  200203. destRow += destData.lineStride;
  200204. if (hasAlphaChan)
  200205. {
  200206. for (int i = (int) width; --i >= 0;)
  200207. {
  200208. ((PixelARGB*) dest)->setARGB (src[3], src[0], src[1], src[2]);
  200209. ((PixelARGB*) dest)->premultiply();
  200210. dest += destData.pixelStride;
  200211. src += 4;
  200212. }
  200213. }
  200214. else
  200215. {
  200216. for (int i = (int) width; --i >= 0;)
  200217. {
  200218. ((PixelRGB*) dest)->setARGB (0, src[0], src[1], src[2]);
  200219. dest += destData.pixelStride;
  200220. src += 4;
  200221. }
  200222. }
  200223. }
  200224. }
  200225. return image;
  200226. }
  200227. bool PNGImageFormat::writeImageToStream (const Image& image, OutputStream& out)
  200228. {
  200229. using namespace pnglibNamespace;
  200230. const int width = image.getWidth();
  200231. const int height = image.getHeight();
  200232. png_structp pngWriteStruct = png_create_write_struct (PNG_LIBPNG_VER_STRING, 0, 0, 0);
  200233. if (pngWriteStruct == 0)
  200234. return false;
  200235. png_infop pngInfoStruct = png_create_info_struct (pngWriteStruct);
  200236. if (pngInfoStruct == 0)
  200237. {
  200238. png_destroy_write_struct (&pngWriteStruct, (png_infopp) 0);
  200239. return false;
  200240. }
  200241. png_set_write_fn (pngWriteStruct, &out, PNGHelpers::writeDataCallback, 0);
  200242. png_set_IHDR (pngWriteStruct, pngInfoStruct, width, height, 8,
  200243. image.hasAlphaChannel() ? PNG_COLOR_TYPE_RGB_ALPHA
  200244. : PNG_COLOR_TYPE_RGB,
  200245. PNG_INTERLACE_NONE,
  200246. PNG_COMPRESSION_TYPE_BASE,
  200247. PNG_FILTER_TYPE_BASE);
  200248. HeapBlock <uint8> rowData (width * 4);
  200249. png_color_8 sig_bit;
  200250. sig_bit.red = 8;
  200251. sig_bit.green = 8;
  200252. sig_bit.blue = 8;
  200253. sig_bit.alpha = 8;
  200254. png_set_sBIT (pngWriteStruct, pngInfoStruct, &sig_bit);
  200255. png_write_info (pngWriteStruct, pngInfoStruct);
  200256. png_set_shift (pngWriteStruct, &sig_bit);
  200257. png_set_packing (pngWriteStruct);
  200258. const Image::BitmapData srcData (image, 0, 0, width, height);
  200259. for (int y = 0; y < height; ++y)
  200260. {
  200261. uint8* dst = rowData;
  200262. const uint8* src = srcData.getLinePointer (y);
  200263. if (image.hasAlphaChannel())
  200264. {
  200265. for (int i = width; --i >= 0;)
  200266. {
  200267. PixelARGB p (*(const PixelARGB*) src);
  200268. p.unpremultiply();
  200269. *dst++ = p.getRed();
  200270. *dst++ = p.getGreen();
  200271. *dst++ = p.getBlue();
  200272. *dst++ = p.getAlpha();
  200273. src += srcData.pixelStride;
  200274. }
  200275. }
  200276. else
  200277. {
  200278. for (int i = width; --i >= 0;)
  200279. {
  200280. *dst++ = ((const PixelRGB*) src)->getRed();
  200281. *dst++ = ((const PixelRGB*) src)->getGreen();
  200282. *dst++ = ((const PixelRGB*) src)->getBlue();
  200283. src += srcData.pixelStride;
  200284. }
  200285. }
  200286. png_write_rows (pngWriteStruct, &rowData, 1);
  200287. }
  200288. png_write_end (pngWriteStruct, pngInfoStruct);
  200289. png_destroy_write_struct (&pngWriteStruct, &pngInfoStruct);
  200290. out.flush();
  200291. return true;
  200292. }
  200293. END_JUCE_NAMESPACE
  200294. /*** End of inlined file: juce_PNGLoader.cpp ***/
  200295. #endif
  200296. //==============================================================================
  200297. #if JUCE_BUILD_NATIVE
  200298. #if JUCE_WINDOWS
  200299. /*** Start of inlined file: juce_win32_NativeCode.cpp ***/
  200300. /*
  200301. This file wraps together all the win32-specific code, so that
  200302. we can include all the native headers just once, and compile all our
  200303. platform-specific stuff in one big lump, keeping it out of the way of
  200304. the rest of the codebase.
  200305. */
  200306. #if JUCE_WINDOWS
  200307. BEGIN_JUCE_NAMESPACE
  200308. #define JUCE_INCLUDED_FILE 1
  200309. // Now include the actual code files..
  200310. /*** Start of inlined file: juce_win32_DynamicLibraryLoader.cpp ***/
  200311. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  200312. // compiled on its own).
  200313. #if JUCE_INCLUDED_FILE
  200314. /*** Start of inlined file: juce_win32_DynamicLibraryLoader.h ***/
  200315. #ifndef __JUCE_WIN32_DYNAMICLIBRARYLOADER_JUCEHEADER__
  200316. #define __JUCE_WIN32_DYNAMICLIBRARYLOADER_JUCEHEADER__
  200317. #ifndef DOXYGEN
  200318. // use with DynamicLibraryLoader to simplify importing functions
  200319. //
  200320. // functionName: function to import
  200321. // localFunctionName: name you want to use to actually call it (must be different)
  200322. // returnType: the return type
  200323. // object: the DynamicLibraryLoader to use
  200324. // params: list of params (bracketed)
  200325. //
  200326. #define DynamicLibraryImport(functionName, localFunctionName, returnType, object, params) \
  200327. typedef returnType (WINAPI *type##localFunctionName) params; \
  200328. type##localFunctionName localFunctionName \
  200329. = (type##localFunctionName)object.findProcAddress (#functionName);
  200330. // loads and unloads a DLL automatically
  200331. class JUCE_API DynamicLibraryLoader
  200332. {
  200333. public:
  200334. DynamicLibraryLoader (const String& name);
  200335. ~DynamicLibraryLoader();
  200336. void* findProcAddress (const String& functionName);
  200337. private:
  200338. void* libHandle;
  200339. };
  200340. #endif
  200341. #endif // __JUCE_WIN32_DYNAMICLIBRARYLOADER_JUCEHEADER__
  200342. /*** End of inlined file: juce_win32_DynamicLibraryLoader.h ***/
  200343. DynamicLibraryLoader::DynamicLibraryLoader (const String& name)
  200344. {
  200345. libHandle = LoadLibrary (name);
  200346. }
  200347. DynamicLibraryLoader::~DynamicLibraryLoader()
  200348. {
  200349. FreeLibrary ((HMODULE) libHandle);
  200350. }
  200351. void* DynamicLibraryLoader::findProcAddress (const String& functionName)
  200352. {
  200353. return GetProcAddress ((HMODULE) libHandle, functionName.toCString());
  200354. }
  200355. #endif
  200356. /*** End of inlined file: juce_win32_DynamicLibraryLoader.cpp ***/
  200357. /*** Start of inlined file: juce_win32_SystemStats.cpp ***/
  200358. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  200359. // compiled on its own).
  200360. #if JUCE_INCLUDED_FILE
  200361. extern void juce_initialiseThreadEvents();
  200362. void Logger::outputDebugString (const String& text)
  200363. {
  200364. OutputDebugString (text + "\n");
  200365. }
  200366. static int64 hiResTicksPerSecond;
  200367. static double hiResTicksScaleFactor;
  200368. #if JUCE_USE_INTRINSICS
  200369. // CPU info functions using intrinsics...
  200370. #pragma intrinsic (__cpuid)
  200371. #pragma intrinsic (__rdtsc)
  200372. const String SystemStats::getCpuVendor()
  200373. {
  200374. int info [4];
  200375. __cpuid (info, 0);
  200376. char v [12];
  200377. memcpy (v, info + 1, 4);
  200378. memcpy (v + 4, info + 3, 4);
  200379. memcpy (v + 8, info + 2, 4);
  200380. return String (v, 12);
  200381. }
  200382. #else
  200383. // CPU info functions using old fashioned inline asm...
  200384. static void juce_getCpuVendor (char* const v)
  200385. {
  200386. int vendor[4];
  200387. zeromem (vendor, 16);
  200388. #ifdef JUCE_64BIT
  200389. #else
  200390. #ifndef __MINGW32__
  200391. __try
  200392. #endif
  200393. {
  200394. #if JUCE_GCC
  200395. unsigned int dummy = 0;
  200396. __asm__ ("cpuid" : "=a" (dummy), "=b" (vendor[0]), "=c" (vendor[2]),"=d" (vendor[1]) : "a" (0));
  200397. #else
  200398. __asm
  200399. {
  200400. mov eax, 0
  200401. cpuid
  200402. mov [vendor], ebx
  200403. mov [vendor + 4], edx
  200404. mov [vendor + 8], ecx
  200405. }
  200406. #endif
  200407. }
  200408. #ifndef __MINGW32__
  200409. __except (EXCEPTION_EXECUTE_HANDLER)
  200410. {
  200411. *v = 0;
  200412. }
  200413. #endif
  200414. #endif
  200415. memcpy (v, vendor, 16);
  200416. }
  200417. const String SystemStats::getCpuVendor()
  200418. {
  200419. char v [16];
  200420. juce_getCpuVendor (v);
  200421. return String (v, 16);
  200422. }
  200423. #endif
  200424. struct CPUFlags
  200425. {
  200426. bool hasMMX : 1;
  200427. bool hasSSE : 1;
  200428. bool hasSSE2 : 1;
  200429. bool has3DNow : 1;
  200430. };
  200431. static CPUFlags cpuFlags;
  200432. bool SystemStats::hasMMX()
  200433. {
  200434. return cpuFlags.hasMMX;
  200435. }
  200436. bool SystemStats::hasSSE()
  200437. {
  200438. return cpuFlags.hasSSE;
  200439. }
  200440. bool SystemStats::hasSSE2()
  200441. {
  200442. return cpuFlags.hasSSE2;
  200443. }
  200444. bool SystemStats::has3DNow()
  200445. {
  200446. return cpuFlags.has3DNow;
  200447. }
  200448. void SystemStats::initialiseStats()
  200449. {
  200450. juce_initialiseThreadEvents();
  200451. cpuFlags.hasMMX = IsProcessorFeaturePresent (PF_MMX_INSTRUCTIONS_AVAILABLE) != 0;
  200452. cpuFlags.hasSSE = IsProcessorFeaturePresent (PF_XMMI_INSTRUCTIONS_AVAILABLE) != 0;
  200453. cpuFlags.hasSSE2 = IsProcessorFeaturePresent (PF_XMMI64_INSTRUCTIONS_AVAILABLE) != 0;
  200454. #ifdef PF_AMD3D_INSTRUCTIONS_AVAILABLE
  200455. cpuFlags.has3DNow = IsProcessorFeaturePresent (PF_AMD3D_INSTRUCTIONS_AVAILABLE) != 0;
  200456. #else
  200457. cpuFlags.has3DNow = IsProcessorFeaturePresent (PF_3DNOW_INSTRUCTIONS_AVAILABLE) != 0;
  200458. #endif
  200459. LARGE_INTEGER f;
  200460. QueryPerformanceFrequency (&f);
  200461. hiResTicksPerSecond = f.QuadPart;
  200462. hiResTicksScaleFactor = 1000.0 / hiResTicksPerSecond;
  200463. String s (SystemStats::getJUCEVersion());
  200464. #if JUCE_DEBUG
  200465. const MMRESULT res = timeBeginPeriod (1);
  200466. jassert (res == TIMERR_NOERROR);
  200467. #else
  200468. timeBeginPeriod (1);
  200469. #endif
  200470. #if JUCE_DEBUG && JUCE_MSVC && JUCE_CHECK_MEMORY_LEAKS
  200471. _CrtSetDbgFlag (_CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF);
  200472. #endif
  200473. }
  200474. SystemStats::OperatingSystemType SystemStats::getOperatingSystemType()
  200475. {
  200476. OSVERSIONINFO info;
  200477. info.dwOSVersionInfoSize = sizeof (info);
  200478. GetVersionEx (&info);
  200479. if (info.dwPlatformId == VER_PLATFORM_WIN32_NT)
  200480. {
  200481. switch (info.dwMajorVersion)
  200482. {
  200483. case 5: return (info.dwMinorVersion == 0) ? Win2000 : WinXP;
  200484. case 6: return (info.dwMinorVersion == 0) ? WinVista : Windows7;
  200485. default: jassertfalse; break; // !! not a supported OS!
  200486. }
  200487. }
  200488. else if (info.dwPlatformId == VER_PLATFORM_WIN32_WINDOWS)
  200489. {
  200490. jassert (info.dwMinorVersion != 0); // !! still running on Windows 95??
  200491. return Win98;
  200492. }
  200493. return UnknownOS;
  200494. }
  200495. const String SystemStats::getOperatingSystemName()
  200496. {
  200497. const char* name = "Unknown OS";
  200498. switch (getOperatingSystemType())
  200499. {
  200500. case Windows7: name = "Windows 7"; break;
  200501. case WinVista: name = "Windows Vista"; break;
  200502. case WinXP: name = "Windows XP"; break;
  200503. case Win2000: name = "Windows 2000"; break;
  200504. case Win98: name = "Windows 98"; break;
  200505. default: jassertfalse; break; // !! new type of OS?
  200506. }
  200507. return name;
  200508. }
  200509. bool SystemStats::isOperatingSystem64Bit()
  200510. {
  200511. #ifdef _WIN64
  200512. return true;
  200513. #else
  200514. typedef BOOL (WINAPI* LPFN_ISWOW64PROCESS) (HANDLE, PBOOL);
  200515. LPFN_ISWOW64PROCESS fnIsWow64Process = (LPFN_ISWOW64PROCESS) GetProcAddress (GetModuleHandle (L"kernel32"), "IsWow64Process");
  200516. BOOL isWow64 = FALSE;
  200517. return (fnIsWow64Process != 0)
  200518. && fnIsWow64Process (GetCurrentProcess(), &isWow64)
  200519. && (isWow64 != FALSE);
  200520. #endif
  200521. }
  200522. int SystemStats::getMemorySizeInMegabytes()
  200523. {
  200524. MEMORYSTATUSEX mem;
  200525. mem.dwLength = sizeof (mem);
  200526. GlobalMemoryStatusEx (&mem);
  200527. return (int) (mem.ullTotalPhys / (1024 * 1024)) + 1;
  200528. }
  200529. int SystemStats::getNumCpus()
  200530. {
  200531. SYSTEM_INFO systemInfo;
  200532. GetSystemInfo (&systemInfo);
  200533. return systemInfo.dwNumberOfProcessors;
  200534. }
  200535. uint32 juce_millisecondsSinceStartup() throw()
  200536. {
  200537. return (uint32) GetTickCount();
  200538. }
  200539. int64 Time::getHighResolutionTicks() throw()
  200540. {
  200541. LARGE_INTEGER ticks;
  200542. QueryPerformanceCounter (&ticks);
  200543. const int64 mainCounterAsHiResTicks = (GetTickCount() * hiResTicksPerSecond) / 1000;
  200544. const int64 newOffset = mainCounterAsHiResTicks - ticks.QuadPart;
  200545. // fix for a very obscure PCI hardware bug that can make the counter
  200546. // sometimes jump forwards by a few seconds..
  200547. static int64 hiResTicksOffset = 0;
  200548. const int64 offsetDrift = abs64 (newOffset - hiResTicksOffset);
  200549. if (offsetDrift > (hiResTicksPerSecond >> 1))
  200550. hiResTicksOffset = newOffset;
  200551. return ticks.QuadPart + hiResTicksOffset;
  200552. }
  200553. double Time::getMillisecondCounterHiRes() throw()
  200554. {
  200555. return getHighResolutionTicks() * hiResTicksScaleFactor;
  200556. }
  200557. int64 Time::getHighResolutionTicksPerSecond() throw()
  200558. {
  200559. return hiResTicksPerSecond;
  200560. }
  200561. static int64 juce_getClockCycleCounter() throw()
  200562. {
  200563. #if JUCE_USE_INTRINSICS
  200564. // MS intrinsics version...
  200565. return __rdtsc();
  200566. #elif JUCE_GCC
  200567. // GNU inline asm version...
  200568. unsigned int hi = 0, lo = 0;
  200569. __asm__ __volatile__ (
  200570. "xor %%eax, %%eax \n\
  200571. xor %%edx, %%edx \n\
  200572. rdtsc \n\
  200573. movl %%eax, %[lo] \n\
  200574. movl %%edx, %[hi]"
  200575. :
  200576. : [hi] "m" (hi),
  200577. [lo] "m" (lo)
  200578. : "cc", "eax", "ebx", "ecx", "edx", "memory");
  200579. return (int64) ((((uint64) hi) << 32) | lo);
  200580. #else
  200581. // MSVC inline asm version...
  200582. unsigned int hi = 0, lo = 0;
  200583. __asm
  200584. {
  200585. xor eax, eax
  200586. xor edx, edx
  200587. rdtsc
  200588. mov lo, eax
  200589. mov hi, edx
  200590. }
  200591. return (int64) ((((uint64) hi) << 32) | lo);
  200592. #endif
  200593. }
  200594. int SystemStats::getCpuSpeedInMegaherz()
  200595. {
  200596. const int64 cycles = juce_getClockCycleCounter();
  200597. const uint32 millis = Time::getMillisecondCounter();
  200598. int lastResult = 0;
  200599. for (;;)
  200600. {
  200601. int n = 1000000;
  200602. while (--n > 0) {}
  200603. const uint32 millisElapsed = Time::getMillisecondCounter() - millis;
  200604. const int64 cyclesNow = juce_getClockCycleCounter();
  200605. if (millisElapsed > 80)
  200606. {
  200607. const int newResult = (int) (((cyclesNow - cycles) / millisElapsed) / 1000);
  200608. if (millisElapsed > 500 || (lastResult == newResult && newResult > 100))
  200609. return newResult;
  200610. lastResult = newResult;
  200611. }
  200612. }
  200613. }
  200614. bool Time::setSystemTimeToThisTime() const
  200615. {
  200616. SYSTEMTIME st;
  200617. st.wDayOfWeek = 0;
  200618. st.wYear = (WORD) getYear();
  200619. st.wMonth = (WORD) (getMonth() + 1);
  200620. st.wDay = (WORD) getDayOfMonth();
  200621. st.wHour = (WORD) getHours();
  200622. st.wMinute = (WORD) getMinutes();
  200623. st.wSecond = (WORD) getSeconds();
  200624. st.wMilliseconds = (WORD) (millisSinceEpoch % 1000);
  200625. // do this twice because of daylight saving conversion problems - the
  200626. // first one sets it up, the second one kicks it in.
  200627. return SetLocalTime (&st) != 0
  200628. && SetLocalTime (&st) != 0;
  200629. }
  200630. int SystemStats::getPageSize()
  200631. {
  200632. SYSTEM_INFO systemInfo;
  200633. GetSystemInfo (&systemInfo);
  200634. return systemInfo.dwPageSize;
  200635. }
  200636. const String SystemStats::getLogonName()
  200637. {
  200638. TCHAR text [256];
  200639. DWORD len = numElementsInArray (text) - 2;
  200640. zerostruct (text);
  200641. GetUserName (text, &len);
  200642. return String (text, len);
  200643. }
  200644. const String SystemStats::getFullUserName()
  200645. {
  200646. return getLogonName();
  200647. }
  200648. #endif
  200649. /*** End of inlined file: juce_win32_SystemStats.cpp ***/
  200650. /*** Start of inlined file: juce_win32_Threads.cpp ***/
  200651. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  200652. // compiled on its own).
  200653. #if JUCE_INCLUDED_FILE
  200654. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  200655. extern HWND juce_messageWindowHandle;
  200656. #endif
  200657. #if ! JUCE_USE_INTRINSICS
  200658. // In newer compilers, the inline versions of these are used (in juce_Atomic.h), but in
  200659. // older ones we have to actually call the ops as win32 functions..
  200660. long juce_InterlockedExchange (volatile long* a, long b) throw() { return InterlockedExchange (a, b); }
  200661. long juce_InterlockedIncrement (volatile long* a) throw() { return InterlockedIncrement (a); }
  200662. long juce_InterlockedDecrement (volatile long* a) throw() { return InterlockedDecrement (a); }
  200663. long juce_InterlockedExchangeAdd (volatile long* a, long b) throw() { return InterlockedExchangeAdd (a, b); }
  200664. long juce_InterlockedCompareExchange (volatile long* a, long b, long c) throw() { return InterlockedCompareExchange (a, b, c); }
  200665. __int64 juce_InterlockedCompareExchange64 (volatile __int64* value, __int64 newValue, __int64 valueToCompare) throw()
  200666. {
  200667. jassertfalse; // This operation isn't available in old MS compiler versions!
  200668. __int64 oldValue = *value;
  200669. if (oldValue == valueToCompare)
  200670. *value = newValue;
  200671. return oldValue;
  200672. }
  200673. #endif
  200674. CriticalSection::CriticalSection() throw()
  200675. {
  200676. // (just to check the MS haven't changed this structure and broken things...)
  200677. #if _MSC_VER >= 1400
  200678. static_jassert (sizeof (CRITICAL_SECTION) <= sizeof (internal));
  200679. #else
  200680. static_jassert (sizeof (CRITICAL_SECTION) <= 24);
  200681. #endif
  200682. InitializeCriticalSection ((CRITICAL_SECTION*) internal);
  200683. }
  200684. CriticalSection::~CriticalSection() throw()
  200685. {
  200686. DeleteCriticalSection ((CRITICAL_SECTION*) internal);
  200687. }
  200688. void CriticalSection::enter() const throw()
  200689. {
  200690. EnterCriticalSection ((CRITICAL_SECTION*) internal);
  200691. }
  200692. bool CriticalSection::tryEnter() const throw()
  200693. {
  200694. return TryEnterCriticalSection ((CRITICAL_SECTION*) internal) != FALSE;
  200695. }
  200696. void CriticalSection::exit() const throw()
  200697. {
  200698. LeaveCriticalSection ((CRITICAL_SECTION*) internal);
  200699. }
  200700. WaitableEvent::WaitableEvent (const bool manualReset) throw()
  200701. : internal (CreateEvent (0, manualReset ? TRUE : FALSE, FALSE, 0))
  200702. {
  200703. }
  200704. WaitableEvent::~WaitableEvent() throw()
  200705. {
  200706. CloseHandle (internal);
  200707. }
  200708. bool WaitableEvent::wait (const int timeOutMillisecs) const throw()
  200709. {
  200710. return WaitForSingleObject (internal, timeOutMillisecs) == WAIT_OBJECT_0;
  200711. }
  200712. void WaitableEvent::signal() const throw()
  200713. {
  200714. SetEvent (internal);
  200715. }
  200716. void WaitableEvent::reset() const throw()
  200717. {
  200718. ResetEvent (internal);
  200719. }
  200720. void JUCE_API juce_threadEntryPoint (void*);
  200721. static unsigned int __stdcall threadEntryProc (void* userData)
  200722. {
  200723. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  200724. AttachThreadInput (GetWindowThreadProcessId (juce_messageWindowHandle, 0),
  200725. GetCurrentThreadId(), TRUE);
  200726. #endif
  200727. juce_threadEntryPoint (userData);
  200728. _endthreadex (0);
  200729. return 0;
  200730. }
  200731. void juce_CloseThreadHandle (void* handle)
  200732. {
  200733. CloseHandle ((HANDLE) handle);
  200734. }
  200735. void* juce_createThread (void* userData)
  200736. {
  200737. unsigned int threadId;
  200738. return (void*) _beginthreadex (0, 0, &threadEntryProc, userData, 0, &threadId);
  200739. }
  200740. void juce_killThread (void* handle)
  200741. {
  200742. if (handle != 0)
  200743. {
  200744. #if JUCE_DEBUG
  200745. OutputDebugString (_T("** Warning - Forced thread termination **\n"));
  200746. #endif
  200747. TerminateThread (handle, 0);
  200748. }
  200749. }
  200750. void juce_setCurrentThreadName (const String& name)
  200751. {
  200752. #if JUCE_DEBUG && JUCE_MSVC
  200753. struct
  200754. {
  200755. DWORD dwType;
  200756. LPCSTR szName;
  200757. DWORD dwThreadID;
  200758. DWORD dwFlags;
  200759. } info;
  200760. info.dwType = 0x1000;
  200761. info.szName = name.toCString();
  200762. info.dwThreadID = GetCurrentThreadId();
  200763. info.dwFlags = 0;
  200764. __try
  200765. {
  200766. RaiseException (0x406d1388 /*MS_VC_EXCEPTION*/, 0, sizeof (info) / sizeof (ULONG_PTR), (ULONG_PTR*) &info);
  200767. }
  200768. __except (EXCEPTION_CONTINUE_EXECUTION)
  200769. {}
  200770. #else
  200771. (void) name;
  200772. #endif
  200773. }
  200774. Thread::ThreadID Thread::getCurrentThreadId()
  200775. {
  200776. return (ThreadID) (pointer_sized_int) GetCurrentThreadId();
  200777. }
  200778. // priority 1 to 10 where 5=normal, 1=low
  200779. bool juce_setThreadPriority (void* threadHandle, int priority)
  200780. {
  200781. int pri = THREAD_PRIORITY_TIME_CRITICAL;
  200782. if (priority < 1)
  200783. pri = THREAD_PRIORITY_IDLE;
  200784. else if (priority < 2)
  200785. pri = THREAD_PRIORITY_LOWEST;
  200786. else if (priority < 5)
  200787. pri = THREAD_PRIORITY_BELOW_NORMAL;
  200788. else if (priority < 7)
  200789. pri = THREAD_PRIORITY_NORMAL;
  200790. else if (priority < 9)
  200791. pri = THREAD_PRIORITY_ABOVE_NORMAL;
  200792. else if (priority < 10)
  200793. pri = THREAD_PRIORITY_HIGHEST;
  200794. if (threadHandle == 0)
  200795. threadHandle = GetCurrentThread();
  200796. return SetThreadPriority (threadHandle, pri) != FALSE;
  200797. }
  200798. void Thread::setCurrentThreadAffinityMask (const uint32 affinityMask)
  200799. {
  200800. SetThreadAffinityMask (GetCurrentThread(), affinityMask);
  200801. }
  200802. static HANDLE sleepEvent = 0;
  200803. void juce_initialiseThreadEvents()
  200804. {
  200805. if (sleepEvent == 0)
  200806. #if JUCE_DEBUG
  200807. sleepEvent = CreateEvent (0, 0, 0, _T("Juce Sleep Event"));
  200808. #else
  200809. sleepEvent = CreateEvent (0, 0, 0, 0);
  200810. #endif
  200811. }
  200812. void Thread::yield()
  200813. {
  200814. Sleep (0);
  200815. }
  200816. void JUCE_CALLTYPE Thread::sleep (const int millisecs)
  200817. {
  200818. if (millisecs >= 10)
  200819. {
  200820. Sleep (millisecs);
  200821. }
  200822. else
  200823. {
  200824. jassert (sleepEvent != 0);
  200825. // unlike Sleep() this is guaranteed to return to the current thread after
  200826. // the time expires, so we'll use this for short waits, which are more likely
  200827. // to need to be accurate
  200828. WaitForSingleObject (sleepEvent, millisecs);
  200829. }
  200830. }
  200831. static int lastProcessPriority = -1;
  200832. // called by WindowDriver because Windows does wierd things to process priority
  200833. // when you swap apps, and this forces an update when the app is brought to the front.
  200834. void juce_repeatLastProcessPriority()
  200835. {
  200836. if (lastProcessPriority >= 0) // (avoid changing this if it's not been explicitly set by the app..)
  200837. {
  200838. DWORD p;
  200839. switch (lastProcessPriority)
  200840. {
  200841. case Process::LowPriority: p = IDLE_PRIORITY_CLASS; break;
  200842. case Process::NormalPriority: p = NORMAL_PRIORITY_CLASS; break;
  200843. case Process::HighPriority: p = HIGH_PRIORITY_CLASS; break;
  200844. case Process::RealtimePriority: p = REALTIME_PRIORITY_CLASS; break;
  200845. default: jassertfalse; return; // bad priority value
  200846. }
  200847. SetPriorityClass (GetCurrentProcess(), p);
  200848. }
  200849. }
  200850. void Process::setPriority (ProcessPriority prior)
  200851. {
  200852. if (lastProcessPriority != (int) prior)
  200853. {
  200854. lastProcessPriority = (int) prior;
  200855. juce_repeatLastProcessPriority();
  200856. }
  200857. }
  200858. bool JUCE_PUBLIC_FUNCTION juce_isRunningUnderDebugger()
  200859. {
  200860. return IsDebuggerPresent() != FALSE;
  200861. }
  200862. bool JUCE_CALLTYPE Process::isRunningUnderDebugger()
  200863. {
  200864. return juce_isRunningUnderDebugger();
  200865. }
  200866. void Process::raisePrivilege()
  200867. {
  200868. jassertfalse // xxx not implemented
  200869. }
  200870. void Process::lowerPrivilege()
  200871. {
  200872. jassertfalse // xxx not implemented
  200873. }
  200874. void Process::terminate()
  200875. {
  200876. #if JUCE_DEBUG && JUCE_MSVC && JUCE_CHECK_MEMORY_LEAKS
  200877. _CrtDumpMemoryLeaks();
  200878. #endif
  200879. // bullet in the head in case there's a problem shutting down..
  200880. ExitProcess (0);
  200881. }
  200882. void* PlatformUtilities::loadDynamicLibrary (const String& name)
  200883. {
  200884. void* result = 0;
  200885. JUCE_TRY
  200886. {
  200887. result = LoadLibrary (name);
  200888. }
  200889. JUCE_CATCH_ALL
  200890. return result;
  200891. }
  200892. void PlatformUtilities::freeDynamicLibrary (void* h)
  200893. {
  200894. JUCE_TRY
  200895. {
  200896. if (h != 0)
  200897. FreeLibrary ((HMODULE) h);
  200898. }
  200899. JUCE_CATCH_ALL
  200900. }
  200901. void* PlatformUtilities::getProcedureEntryPoint (void* h, const String& name)
  200902. {
  200903. return (h != 0) ? GetProcAddress ((HMODULE) h, name.toCString()) : 0;
  200904. }
  200905. class InterProcessLock::Pimpl
  200906. {
  200907. public:
  200908. Pimpl (const String& name, const int timeOutMillisecs)
  200909. : handle (0), refCount (1)
  200910. {
  200911. handle = CreateMutex (0, TRUE, "Global\\" + name.replaceCharacter ('\\','/'));
  200912. if (handle != 0 && GetLastError() == ERROR_ALREADY_EXISTS)
  200913. {
  200914. if (timeOutMillisecs == 0)
  200915. {
  200916. close();
  200917. return;
  200918. }
  200919. switch (WaitForSingleObject (handle, timeOutMillisecs < 0 ? INFINITE : timeOutMillisecs))
  200920. {
  200921. case WAIT_OBJECT_0:
  200922. case WAIT_ABANDONED:
  200923. break;
  200924. case WAIT_TIMEOUT:
  200925. default:
  200926. close();
  200927. break;
  200928. }
  200929. }
  200930. }
  200931. ~Pimpl()
  200932. {
  200933. close();
  200934. }
  200935. void close()
  200936. {
  200937. if (handle != 0)
  200938. {
  200939. ReleaseMutex (handle);
  200940. CloseHandle (handle);
  200941. handle = 0;
  200942. }
  200943. }
  200944. HANDLE handle;
  200945. int refCount;
  200946. };
  200947. InterProcessLock::InterProcessLock (const String& name_)
  200948. : name (name_)
  200949. {
  200950. }
  200951. InterProcessLock::~InterProcessLock()
  200952. {
  200953. }
  200954. bool InterProcessLock::enter (const int timeOutMillisecs)
  200955. {
  200956. const ScopedLock sl (lock);
  200957. if (pimpl == 0)
  200958. {
  200959. pimpl = new Pimpl (name, timeOutMillisecs);
  200960. if (pimpl->handle == 0)
  200961. pimpl = 0;
  200962. }
  200963. else
  200964. {
  200965. pimpl->refCount++;
  200966. }
  200967. return pimpl != 0;
  200968. }
  200969. void InterProcessLock::exit()
  200970. {
  200971. const ScopedLock sl (lock);
  200972. // Trying to release the lock too many times!
  200973. jassert (pimpl != 0);
  200974. if (pimpl != 0 && --(pimpl->refCount) == 0)
  200975. pimpl = 0;
  200976. }
  200977. #endif
  200978. /*** End of inlined file: juce_win32_Threads.cpp ***/
  200979. /*** Start of inlined file: juce_win32_Files.cpp ***/
  200980. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  200981. // compiled on its own).
  200982. #if JUCE_INCLUDED_FILE
  200983. #ifndef CSIDL_MYMUSIC
  200984. #define CSIDL_MYMUSIC 0x000d
  200985. #endif
  200986. #ifndef CSIDL_MYVIDEO
  200987. #define CSIDL_MYVIDEO 0x000e
  200988. #endif
  200989. #ifndef INVALID_FILE_ATTRIBUTES
  200990. #define INVALID_FILE_ATTRIBUTES ((DWORD) -1)
  200991. #endif
  200992. const juce_wchar File::separator = '\\';
  200993. const String File::separatorString ("\\");
  200994. bool File::exists() const
  200995. {
  200996. return fullPath.isNotEmpty()
  200997. && GetFileAttributes (fullPath) != INVALID_FILE_ATTRIBUTES;
  200998. }
  200999. bool File::existsAsFile() const
  201000. {
  201001. return fullPath.isNotEmpty()
  201002. && (GetFileAttributes (fullPath) & FILE_ATTRIBUTE_DIRECTORY) == 0;
  201003. }
  201004. bool File::isDirectory() const
  201005. {
  201006. const DWORD attr = GetFileAttributes (fullPath);
  201007. return ((attr & FILE_ATTRIBUTE_DIRECTORY) != 0) && (attr != INVALID_FILE_ATTRIBUTES);
  201008. }
  201009. bool File::hasWriteAccess() const
  201010. {
  201011. if (exists())
  201012. return (GetFileAttributes (fullPath) & FILE_ATTRIBUTE_READONLY) == 0;
  201013. // on windows, it seems that even read-only directories can still be written into,
  201014. // so checking the parent directory's permissions would return the wrong result..
  201015. return true;
  201016. }
  201017. bool File::setFileReadOnlyInternal (const bool shouldBeReadOnly) const
  201018. {
  201019. DWORD attr = GetFileAttributes (fullPath);
  201020. if (attr == INVALID_FILE_ATTRIBUTES)
  201021. return false;
  201022. if (shouldBeReadOnly == ((attr & FILE_ATTRIBUTE_READONLY) != 0))
  201023. return true;
  201024. if (shouldBeReadOnly)
  201025. attr |= FILE_ATTRIBUTE_READONLY;
  201026. else
  201027. attr &= ~FILE_ATTRIBUTE_READONLY;
  201028. return SetFileAttributes (fullPath, attr) != FALSE;
  201029. }
  201030. bool File::isHidden() const
  201031. {
  201032. return (GetFileAttributes (getFullPathName()) & FILE_ATTRIBUTE_HIDDEN) != 0;
  201033. }
  201034. bool File::deleteFile() const
  201035. {
  201036. if (! exists())
  201037. return true;
  201038. else if (isDirectory())
  201039. return RemoveDirectory (fullPath) != 0;
  201040. else
  201041. return DeleteFile (fullPath) != 0;
  201042. }
  201043. bool File::moveToTrash() const
  201044. {
  201045. if (! exists())
  201046. return true;
  201047. SHFILEOPSTRUCT fos;
  201048. zerostruct (fos);
  201049. // The string we pass in must be double null terminated..
  201050. String doubleNullTermPath (getFullPathName() + " ");
  201051. TCHAR* const p = const_cast <TCHAR*> (static_cast <const TCHAR*> (doubleNullTermPath));
  201052. p [getFullPathName().length()] = 0;
  201053. fos.wFunc = FO_DELETE;
  201054. fos.pFrom = p;
  201055. fos.fFlags = FOF_ALLOWUNDO | FOF_NOERRORUI | FOF_SILENT | FOF_NOCONFIRMATION
  201056. | FOF_NOCONFIRMMKDIR | FOF_RENAMEONCOLLISION;
  201057. return SHFileOperation (&fos) == 0;
  201058. }
  201059. bool File::copyInternal (const File& dest) const
  201060. {
  201061. return CopyFile (fullPath, dest.getFullPathName(), false) != 0;
  201062. }
  201063. bool File::moveInternal (const File& dest) const
  201064. {
  201065. return MoveFile (fullPath, dest.getFullPathName()) != 0;
  201066. }
  201067. void File::createDirectoryInternal (const String& fileName) const
  201068. {
  201069. CreateDirectory (fileName, 0);
  201070. }
  201071. // return 0 if not possible
  201072. void* juce_fileOpen (const File& file, bool forWriting)
  201073. {
  201074. HANDLE h;
  201075. if (forWriting)
  201076. {
  201077. h = CreateFile (file.getFullPathName(), GENERIC_WRITE, FILE_SHARE_READ, 0,
  201078. OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, 0);
  201079. if (h != INVALID_HANDLE_VALUE)
  201080. SetFilePointer (h, 0, 0, FILE_END);
  201081. else
  201082. h = 0;
  201083. }
  201084. else
  201085. {
  201086. h = CreateFile (file.getFullPathName(), GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE, 0,
  201087. OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL | FILE_FLAG_SEQUENTIAL_SCAN, 0);
  201088. if (h == INVALID_HANDLE_VALUE)
  201089. h = 0;
  201090. }
  201091. return h;
  201092. }
  201093. void juce_fileClose (void* handle)
  201094. {
  201095. CloseHandle (handle);
  201096. }
  201097. int juce_fileRead (void* handle, void* buffer, int size)
  201098. {
  201099. DWORD num = 0;
  201100. ReadFile ((HANDLE) handle, buffer, size, &num, 0);
  201101. return (int) num;
  201102. }
  201103. int juce_fileWrite (void* handle, const void* buffer, int size)
  201104. {
  201105. DWORD num;
  201106. WriteFile ((HANDLE) handle, buffer, size, &num, 0);
  201107. return (int) num;
  201108. }
  201109. int64 juce_fileSetPosition (void* handle, int64 pos)
  201110. {
  201111. LARGE_INTEGER li;
  201112. li.QuadPart = pos;
  201113. li.LowPart = SetFilePointer ((HANDLE) handle, li.LowPart, &li.HighPart, FILE_BEGIN); // (returns -1 if it fails)
  201114. return li.QuadPart;
  201115. }
  201116. int64 FileOutputStream::getPositionInternal() const
  201117. {
  201118. if (fileHandle == 0)
  201119. return -1;
  201120. LARGE_INTEGER li;
  201121. li.QuadPart = 0;
  201122. li.LowPart = SetFilePointer ((HANDLE) fileHandle, 0, &li.HighPart, FILE_CURRENT); // (returns -1 if it fails)
  201123. return jmax ((int64) 0, li.QuadPart);
  201124. }
  201125. void FileOutputStream::flushInternal()
  201126. {
  201127. if (fileHandle != 0)
  201128. FlushFileBuffers ((HANDLE) fileHandle);
  201129. }
  201130. int64 File::getSize() const
  201131. {
  201132. WIN32_FILE_ATTRIBUTE_DATA attributes;
  201133. if (GetFileAttributesEx (fullPath, GetFileExInfoStandard, &attributes))
  201134. return (((int64) attributes.nFileSizeHigh) << 32) | attributes.nFileSizeLow;
  201135. return 0;
  201136. }
  201137. static int64 fileTimeToTime (const FILETIME* const ft)
  201138. {
  201139. static_jassert (sizeof (ULARGE_INTEGER) == sizeof (FILETIME)); // tell me if this fails!
  201140. return (reinterpret_cast<const ULARGE_INTEGER*> (ft)->QuadPart - literal64bit (116444736000000000)) / 10000;
  201141. }
  201142. static void timeToFileTime (const int64 time, FILETIME* const ft)
  201143. {
  201144. reinterpret_cast<ULARGE_INTEGER*> (ft)->QuadPart = time * 10000 + literal64bit (116444736000000000);
  201145. }
  201146. void File::getFileTimesInternal (int64& modificationTime, int64& accessTime, int64& creationTime) const
  201147. {
  201148. WIN32_FILE_ATTRIBUTE_DATA attributes;
  201149. if (GetFileAttributesEx (fullPath, GetFileExInfoStandard, &attributes))
  201150. {
  201151. modificationTime = fileTimeToTime (&attributes.ftLastWriteTime);
  201152. creationTime = fileTimeToTime (&attributes.ftCreationTime);
  201153. accessTime = fileTimeToTime (&attributes.ftLastAccessTime);
  201154. }
  201155. else
  201156. {
  201157. creationTime = accessTime = modificationTime = 0;
  201158. }
  201159. }
  201160. bool File::setFileTimesInternal (int64 modificationTime, int64 accessTime, int64 creationTime) const
  201161. {
  201162. void* const h = juce_fileOpen (fullPath, true);
  201163. bool ok = false;
  201164. if (h != 0)
  201165. {
  201166. FILETIME m, a, c;
  201167. timeToFileTime (modificationTime, &m);
  201168. timeToFileTime (accessTime, &a);
  201169. timeToFileTime (creationTime, &c);
  201170. ok = SetFileTime ((HANDLE) h,
  201171. creationTime > 0 ? &c : 0,
  201172. accessTime > 0 ? &a : 0,
  201173. modificationTime > 0 ? &m : 0) != 0;
  201174. juce_fileClose (h);
  201175. }
  201176. return ok;
  201177. }
  201178. void File::findFileSystemRoots (Array<File>& destArray)
  201179. {
  201180. TCHAR buffer [2048];
  201181. buffer[0] = 0;
  201182. buffer[1] = 0;
  201183. GetLogicalDriveStrings (2048, buffer);
  201184. const TCHAR* n = buffer;
  201185. StringArray roots;
  201186. while (*n != 0)
  201187. {
  201188. roots.add (String (n));
  201189. while (*n++ != 0)
  201190. {}
  201191. }
  201192. roots.sort (true);
  201193. for (int i = 0; i < roots.size(); ++i)
  201194. destArray.add (roots [i]);
  201195. }
  201196. static const String getDriveFromPath (const String& path)
  201197. {
  201198. if (path.isNotEmpty() && path[1] == ':')
  201199. return path.substring (0, 2) + '\\';
  201200. return path;
  201201. }
  201202. const String File::getVolumeLabel() const
  201203. {
  201204. TCHAR dest[64];
  201205. if (! GetVolumeInformation (getDriveFromPath (getFullPathName()), dest,
  201206. numElementsInArray (dest), 0, 0, 0, 0, 0))
  201207. dest[0] = 0;
  201208. return dest;
  201209. }
  201210. int File::getVolumeSerialNumber() const
  201211. {
  201212. TCHAR dest[64];
  201213. DWORD serialNum;
  201214. if (! GetVolumeInformation (getDriveFromPath (getFullPathName()), dest,
  201215. numElementsInArray (dest), &serialNum, 0, 0, 0, 0))
  201216. return 0;
  201217. return (int) serialNum;
  201218. }
  201219. static int64 getDiskSpaceInfo (const String& path, const bool total)
  201220. {
  201221. ULARGE_INTEGER spc, tot, totFree;
  201222. if (GetDiskFreeSpaceEx (getDriveFromPath (path), &spc, &tot, &totFree))
  201223. return total ? (int64) tot.QuadPart
  201224. : (int64) spc.QuadPart;
  201225. return 0;
  201226. }
  201227. int64 File::getBytesFreeOnVolume() const
  201228. {
  201229. return getDiskSpaceInfo (getFullPathName(), false);
  201230. }
  201231. int64 File::getVolumeTotalSize() const
  201232. {
  201233. return getDiskSpaceInfo (getFullPathName(), true);
  201234. }
  201235. static unsigned int getWindowsDriveType (const String& path)
  201236. {
  201237. return GetDriveType (getDriveFromPath (path));
  201238. }
  201239. bool File::isOnCDRomDrive() const
  201240. {
  201241. return getWindowsDriveType (getFullPathName()) == DRIVE_CDROM;
  201242. }
  201243. bool File::isOnHardDisk() const
  201244. {
  201245. if (fullPath.isEmpty())
  201246. return false;
  201247. const unsigned int n = getWindowsDriveType (getFullPathName());
  201248. if (fullPath.toLowerCase()[0] <= 'b' && fullPath[1] == ':')
  201249. return n != DRIVE_REMOVABLE;
  201250. else
  201251. return n != DRIVE_CDROM && n != DRIVE_REMOTE;
  201252. }
  201253. bool File::isOnRemovableDrive() const
  201254. {
  201255. if (fullPath.isEmpty())
  201256. return false;
  201257. const unsigned int n = getWindowsDriveType (getFullPathName());
  201258. return n == DRIVE_CDROM
  201259. || n == DRIVE_REMOTE
  201260. || n == DRIVE_REMOVABLE
  201261. || n == DRIVE_RAMDISK;
  201262. }
  201263. static const File juce_getSpecialFolderPath (int type)
  201264. {
  201265. WCHAR path [MAX_PATH + 256];
  201266. if (SHGetSpecialFolderPath (0, path, type, FALSE))
  201267. return File (String (path));
  201268. return File::nonexistent;
  201269. }
  201270. const File JUCE_CALLTYPE File::getSpecialLocation (const SpecialLocationType type)
  201271. {
  201272. int csidlType = 0;
  201273. switch (type)
  201274. {
  201275. case userHomeDirectory: csidlType = CSIDL_PROFILE; break;
  201276. case userDocumentsDirectory: csidlType = CSIDL_PERSONAL; break;
  201277. case userDesktopDirectory: csidlType = CSIDL_DESKTOP; break;
  201278. case userApplicationDataDirectory: csidlType = CSIDL_APPDATA; break;
  201279. case commonApplicationDataDirectory: csidlType = CSIDL_COMMON_APPDATA; break;
  201280. case globalApplicationsDirectory: csidlType = CSIDL_PROGRAM_FILES; break;
  201281. case userMusicDirectory: csidlType = CSIDL_MYMUSIC; break;
  201282. case userMoviesDirectory: csidlType = CSIDL_MYVIDEO; break;
  201283. case tempDirectory:
  201284. {
  201285. WCHAR dest [2048];
  201286. dest[0] = 0;
  201287. GetTempPath (numElementsInArray (dest), dest);
  201288. return File (String (dest));
  201289. }
  201290. case invokedExecutableFile:
  201291. case currentExecutableFile:
  201292. case currentApplicationFile:
  201293. {
  201294. HINSTANCE moduleHandle = (HINSTANCE) PlatformUtilities::getCurrentModuleInstanceHandle();
  201295. WCHAR dest [MAX_PATH + 256];
  201296. dest[0] = 0;
  201297. GetModuleFileName (moduleHandle, dest, numElementsInArray (dest));
  201298. return File (String (dest));
  201299. }
  201300. break;
  201301. default:
  201302. jassertfalse // unknown type?
  201303. return File::nonexistent;
  201304. }
  201305. return juce_getSpecialFolderPath (csidlType);
  201306. }
  201307. const File File::getCurrentWorkingDirectory()
  201308. {
  201309. WCHAR dest [MAX_PATH + 256];
  201310. dest[0] = 0;
  201311. GetCurrentDirectory (numElementsInArray (dest), dest);
  201312. return File (String (dest));
  201313. }
  201314. bool File::setAsCurrentWorkingDirectory() const
  201315. {
  201316. return SetCurrentDirectory (getFullPathName()) != FALSE;
  201317. }
  201318. const String File::getVersion() const
  201319. {
  201320. String result;
  201321. DWORD handle = 0;
  201322. DWORD bufferSize = GetFileVersionInfoSize (getFullPathName(), &handle);
  201323. HeapBlock<char> buffer;
  201324. buffer.calloc (bufferSize);
  201325. if (GetFileVersionInfo (getFullPathName(), 0, bufferSize, buffer))
  201326. {
  201327. VS_FIXEDFILEINFO* vffi;
  201328. UINT len = 0;
  201329. if (VerQueryValue (buffer, (LPTSTR) _T("\\"), (LPVOID*) &vffi, &len))
  201330. {
  201331. result << (int) HIWORD (vffi->dwFileVersionMS) << '.'
  201332. << (int) LOWORD (vffi->dwFileVersionMS) << '.'
  201333. << (int) HIWORD (vffi->dwFileVersionLS) << '.'
  201334. << (int) LOWORD (vffi->dwFileVersionLS);
  201335. }
  201336. }
  201337. return result;
  201338. }
  201339. const File File::getLinkedTarget() const
  201340. {
  201341. File result (*this);
  201342. String p (getFullPathName());
  201343. if (! exists())
  201344. p += ".lnk";
  201345. else if (getFileExtension() != ".lnk")
  201346. return result;
  201347. ComSmartPtr <IShellLink> shellLink;
  201348. if (SUCCEEDED (shellLink.CoCreateInstance (CLSID_ShellLink)))
  201349. {
  201350. ComSmartPtr <IPersistFile> persistFile;
  201351. if (SUCCEEDED (shellLink->QueryInterface (IID_IPersistFile, (LPVOID*) &persistFile)))
  201352. {
  201353. if (SUCCEEDED (persistFile->Load ((const WCHAR*) p, STGM_READ))
  201354. && SUCCEEDED (shellLink->Resolve (0, SLR_ANY_MATCH | SLR_NO_UI)))
  201355. {
  201356. WIN32_FIND_DATA winFindData;
  201357. WCHAR resolvedPath [MAX_PATH];
  201358. if (SUCCEEDED (shellLink->GetPath (resolvedPath, MAX_PATH, &winFindData, SLGP_UNCPRIORITY)))
  201359. result = File (resolvedPath);
  201360. }
  201361. }
  201362. }
  201363. return result;
  201364. }
  201365. class DirectoryIterator::NativeIterator::Pimpl
  201366. {
  201367. public:
  201368. Pimpl (const File& directory, const String& wildCard)
  201369. : directoryWithWildCard (File::addTrailingSeparator (directory.getFullPathName()) + wildCard),
  201370. handle (INVALID_HANDLE_VALUE)
  201371. {
  201372. }
  201373. ~Pimpl()
  201374. {
  201375. if (handle != INVALID_HANDLE_VALUE)
  201376. FindClose (handle);
  201377. }
  201378. bool next (String& filenameFound,
  201379. bool* const isDir, bool* const isHidden, int64* const fileSize,
  201380. Time* const modTime, Time* const creationTime, bool* const isReadOnly)
  201381. {
  201382. WIN32_FIND_DATA findData;
  201383. if (handle == INVALID_HANDLE_VALUE)
  201384. {
  201385. handle = FindFirstFile (directoryWithWildCard, &findData);
  201386. if (handle == INVALID_HANDLE_VALUE)
  201387. return false;
  201388. }
  201389. else
  201390. {
  201391. if (FindNextFile (handle, &findData) == 0)
  201392. return false;
  201393. }
  201394. filenameFound = findData.cFileName;
  201395. if (isDir != 0) *isDir = ((findData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) != 0);
  201396. if (isHidden != 0) *isHidden = ((findData.dwFileAttributes & FILE_ATTRIBUTE_HIDDEN) != 0);
  201397. if (fileSize != 0) *fileSize = findData.nFileSizeLow + (((int64) findData.nFileSizeHigh) << 32);
  201398. if (modTime != 0) *modTime = fileTimeToTime (&findData.ftLastWriteTime);
  201399. if (creationTime != 0) *creationTime = fileTimeToTime (&findData.ftCreationTime);
  201400. if (isReadOnly != 0) *isReadOnly = ((findData.dwFileAttributes & FILE_ATTRIBUTE_READONLY) != 0);
  201401. return true;
  201402. }
  201403. juce_UseDebuggingNewOperator
  201404. private:
  201405. const String directoryWithWildCard;
  201406. HANDLE handle;
  201407. Pimpl (const Pimpl&);
  201408. Pimpl& operator= (const Pimpl&);
  201409. };
  201410. DirectoryIterator::NativeIterator::NativeIterator (const File& directory, const String& wildCard)
  201411. : pimpl (new DirectoryIterator::NativeIterator::Pimpl (directory, wildCard))
  201412. {
  201413. }
  201414. DirectoryIterator::NativeIterator::~NativeIterator()
  201415. {
  201416. }
  201417. bool DirectoryIterator::NativeIterator::next (String& filenameFound,
  201418. bool* const isDir, bool* const isHidden, int64* const fileSize,
  201419. Time* const modTime, Time* const creationTime, bool* const isReadOnly)
  201420. {
  201421. return pimpl->next (filenameFound, isDir, isHidden, fileSize, modTime, creationTime, isReadOnly);
  201422. }
  201423. bool PlatformUtilities::openDocument (const String& fileName, const String& parameters)
  201424. {
  201425. HINSTANCE hInstance = 0;
  201426. JUCE_TRY
  201427. {
  201428. hInstance = ShellExecute (0, 0, fileName, parameters, 0, SW_SHOWDEFAULT);
  201429. }
  201430. JUCE_CATCH_ALL
  201431. return hInstance > (HINSTANCE) 32;
  201432. }
  201433. void File::revealToUser() const
  201434. {
  201435. if (isDirectory())
  201436. startAsProcess();
  201437. else if (getParentDirectory().exists())
  201438. getParentDirectory().startAsProcess();
  201439. }
  201440. class NamedPipeInternal
  201441. {
  201442. public:
  201443. NamedPipeInternal (const String& file, const bool isPipe_)
  201444. : pipeH (0),
  201445. cancelEvent (0),
  201446. connected (false),
  201447. isPipe (isPipe_)
  201448. {
  201449. cancelEvent = CreateEvent (0, FALSE, FALSE, 0);
  201450. pipeH = isPipe ? CreateNamedPipe (file, PIPE_ACCESS_DUPLEX | FILE_FLAG_OVERLAPPED, 0,
  201451. PIPE_UNLIMITED_INSTANCES, 4096, 4096, 0, 0)
  201452. : CreateFile (file, GENERIC_READ | GENERIC_WRITE, 0, 0,
  201453. OPEN_EXISTING, FILE_FLAG_OVERLAPPED, 0);
  201454. }
  201455. ~NamedPipeInternal()
  201456. {
  201457. disconnectPipe();
  201458. if (pipeH != 0)
  201459. CloseHandle (pipeH);
  201460. CloseHandle (cancelEvent);
  201461. }
  201462. bool connect (const int timeOutMs)
  201463. {
  201464. if (! isPipe)
  201465. return true;
  201466. if (! connected)
  201467. {
  201468. OVERLAPPED over;
  201469. zerostruct (over);
  201470. over.hEvent = CreateEvent (0, TRUE, FALSE, 0);
  201471. if (ConnectNamedPipe (pipeH, &over))
  201472. {
  201473. connected = false; // yes, you read that right. In overlapped mode it should always return 0.
  201474. }
  201475. else
  201476. {
  201477. const int err = GetLastError();
  201478. if (err == ERROR_IO_PENDING || err == ERROR_PIPE_LISTENING)
  201479. {
  201480. HANDLE handles[] = { over.hEvent, cancelEvent };
  201481. if (WaitForMultipleObjects (2, handles, FALSE,
  201482. timeOutMs >= 0 ? timeOutMs : INFINITE) == WAIT_OBJECT_0)
  201483. connected = true;
  201484. }
  201485. else if (err == ERROR_PIPE_CONNECTED)
  201486. {
  201487. connected = true;
  201488. }
  201489. }
  201490. CloseHandle (over.hEvent);
  201491. }
  201492. return connected;
  201493. }
  201494. void disconnectPipe()
  201495. {
  201496. if (connected)
  201497. {
  201498. DisconnectNamedPipe (pipeH);
  201499. connected = false;
  201500. }
  201501. }
  201502. HANDLE pipeH;
  201503. HANDLE cancelEvent;
  201504. bool connected, isPipe;
  201505. };
  201506. void NamedPipe::close()
  201507. {
  201508. cancelPendingReads();
  201509. const ScopedLock sl (lock);
  201510. delete static_cast<NamedPipeInternal*> (internal);
  201511. internal = 0;
  201512. }
  201513. bool NamedPipe::openInternal (const String& pipeName, const bool createPipe)
  201514. {
  201515. close();
  201516. ScopedPointer<NamedPipeInternal> intern (new NamedPipeInternal ("\\\\.\\pipe\\" + pipeName, createPipe));
  201517. if (intern->pipeH != INVALID_HANDLE_VALUE)
  201518. {
  201519. internal = intern.release();
  201520. return true;
  201521. }
  201522. return false;
  201523. }
  201524. int NamedPipe::read (void* destBuffer, int maxBytesToRead, int timeOutMilliseconds)
  201525. {
  201526. const ScopedLock sl (lock);
  201527. int bytesRead = -1;
  201528. bool waitAgain = true;
  201529. while (waitAgain && internal != 0)
  201530. {
  201531. NamedPipeInternal* const intern = static_cast<NamedPipeInternal*> (internal);
  201532. waitAgain = false;
  201533. if (! intern->connect (timeOutMilliseconds))
  201534. break;
  201535. if (maxBytesToRead <= 0)
  201536. return 0;
  201537. OVERLAPPED over;
  201538. zerostruct (over);
  201539. over.hEvent = CreateEvent (0, TRUE, FALSE, 0);
  201540. unsigned long numRead;
  201541. if (ReadFile (intern->pipeH, destBuffer, maxBytesToRead, &numRead, &over))
  201542. {
  201543. bytesRead = (int) numRead;
  201544. }
  201545. else if (GetLastError() == ERROR_IO_PENDING)
  201546. {
  201547. HANDLE handles[] = { over.hEvent, intern->cancelEvent };
  201548. DWORD waitResult = WaitForMultipleObjects (2, handles, FALSE,
  201549. timeOutMilliseconds >= 0 ? timeOutMilliseconds
  201550. : INFINITE);
  201551. if (waitResult != WAIT_OBJECT_0)
  201552. {
  201553. // if the operation timed out, let's cancel it...
  201554. CancelIo (intern->pipeH);
  201555. WaitForSingleObject (over.hEvent, INFINITE); // makes sure cancel is complete
  201556. }
  201557. if (GetOverlappedResult (intern->pipeH, &over, &numRead, FALSE))
  201558. {
  201559. bytesRead = (int) numRead;
  201560. }
  201561. else if (GetLastError() == ERROR_BROKEN_PIPE && intern->isPipe)
  201562. {
  201563. intern->disconnectPipe();
  201564. waitAgain = true;
  201565. }
  201566. }
  201567. else
  201568. {
  201569. waitAgain = internal != 0;
  201570. Sleep (5);
  201571. }
  201572. CloseHandle (over.hEvent);
  201573. }
  201574. return bytesRead;
  201575. }
  201576. int NamedPipe::write (const void* sourceBuffer, int numBytesToWrite, int timeOutMilliseconds)
  201577. {
  201578. int bytesWritten = -1;
  201579. NamedPipeInternal* const intern = static_cast<NamedPipeInternal*> (internal);
  201580. if (intern != 0 && intern->connect (timeOutMilliseconds))
  201581. {
  201582. if (numBytesToWrite <= 0)
  201583. return 0;
  201584. OVERLAPPED over;
  201585. zerostruct (over);
  201586. over.hEvent = CreateEvent (0, TRUE, FALSE, 0);
  201587. unsigned long numWritten;
  201588. if (WriteFile (intern->pipeH, sourceBuffer, numBytesToWrite, &numWritten, &over))
  201589. {
  201590. bytesWritten = (int) numWritten;
  201591. }
  201592. else if (GetLastError() == ERROR_IO_PENDING)
  201593. {
  201594. HANDLE handles[] = { over.hEvent, intern->cancelEvent };
  201595. DWORD waitResult;
  201596. waitResult = WaitForMultipleObjects (2, handles, FALSE,
  201597. timeOutMilliseconds >= 0 ? timeOutMilliseconds
  201598. : INFINITE);
  201599. if (waitResult != WAIT_OBJECT_0)
  201600. {
  201601. CancelIo (intern->pipeH);
  201602. WaitForSingleObject (over.hEvent, INFINITE);
  201603. }
  201604. if (GetOverlappedResult (intern->pipeH, &over, &numWritten, FALSE))
  201605. {
  201606. bytesWritten = (int) numWritten;
  201607. }
  201608. else if (GetLastError() == ERROR_BROKEN_PIPE && intern->isPipe)
  201609. {
  201610. intern->disconnectPipe();
  201611. }
  201612. }
  201613. CloseHandle (over.hEvent);
  201614. }
  201615. return bytesWritten;
  201616. }
  201617. void NamedPipe::cancelPendingReads()
  201618. {
  201619. if (internal != 0)
  201620. SetEvent (static_cast<NamedPipeInternal*> (internal)->cancelEvent);
  201621. }
  201622. #endif
  201623. /*** End of inlined file: juce_win32_Files.cpp ***/
  201624. /*** Start of inlined file: juce_win32_Network.cpp ***/
  201625. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  201626. // compiled on its own).
  201627. #if JUCE_INCLUDED_FILE
  201628. #ifndef INTERNET_FLAG_NEED_FILE
  201629. #define INTERNET_FLAG_NEED_FILE 0x00000010
  201630. #endif
  201631. #ifndef INTERNET_OPTION_DISABLE_AUTODIAL
  201632. #define INTERNET_OPTION_DISABLE_AUTODIAL 70
  201633. #endif
  201634. struct ConnectionAndRequestStruct
  201635. {
  201636. HINTERNET connection, request;
  201637. };
  201638. static HINTERNET sessionHandle = 0;
  201639. #ifndef WORKAROUND_TIMEOUT_BUG
  201640. //#define WORKAROUND_TIMEOUT_BUG 1
  201641. #endif
  201642. #if WORKAROUND_TIMEOUT_BUG
  201643. // Required because of a Microsoft bug in setting a timeout
  201644. class InternetConnectThread : public Thread
  201645. {
  201646. public:
  201647. InternetConnectThread (URL_COMPONENTS& uc_, HINTERNET& connection_, const bool isFtp_)
  201648. : Thread ("Internet"), uc (uc_), connection (connection_), isFtp (isFtp_)
  201649. {
  201650. startThread();
  201651. }
  201652. ~InternetConnectThread()
  201653. {
  201654. stopThread (60000);
  201655. }
  201656. void run()
  201657. {
  201658. connection = InternetConnect (sessionHandle, uc.lpszHostName,
  201659. uc.nPort, _T(""), _T(""),
  201660. isFtp ? INTERNET_SERVICE_FTP
  201661. : INTERNET_SERVICE_HTTP,
  201662. 0, 0);
  201663. notify();
  201664. }
  201665. juce_UseDebuggingNewOperator
  201666. private:
  201667. URL_COMPONENTS& uc;
  201668. HINTERNET& connection;
  201669. const bool isFtp;
  201670. InternetConnectThread (const InternetConnectThread&);
  201671. InternetConnectThread& operator= (const InternetConnectThread&);
  201672. };
  201673. #endif
  201674. void* juce_openInternetFile (const String& url,
  201675. const String& headers,
  201676. const MemoryBlock& postData,
  201677. const bool isPost,
  201678. URL::OpenStreamProgressCallback* callback,
  201679. void* callbackContext,
  201680. int timeOutMs)
  201681. {
  201682. if (sessionHandle == 0)
  201683. sessionHandle = InternetOpen (_T("juce"),
  201684. INTERNET_OPEN_TYPE_PRECONFIG,
  201685. 0, 0, 0);
  201686. if (sessionHandle != 0)
  201687. {
  201688. // break up the url..
  201689. TCHAR file[1024], server[1024];
  201690. URL_COMPONENTS uc;
  201691. zerostruct (uc);
  201692. uc.dwStructSize = sizeof (uc);
  201693. uc.dwUrlPathLength = sizeof (file);
  201694. uc.dwHostNameLength = sizeof (server);
  201695. uc.lpszUrlPath = file;
  201696. uc.lpszHostName = server;
  201697. if (InternetCrackUrl (url, 0, 0, &uc))
  201698. {
  201699. int disable = 1;
  201700. InternetSetOption (sessionHandle, INTERNET_OPTION_DISABLE_AUTODIAL, &disable, sizeof (disable));
  201701. if (timeOutMs == 0)
  201702. timeOutMs = 30000;
  201703. else if (timeOutMs < 0)
  201704. timeOutMs = -1;
  201705. InternetSetOption (sessionHandle, INTERNET_OPTION_CONNECT_TIMEOUT, &timeOutMs, sizeof (timeOutMs));
  201706. const bool isFtp = url.startsWithIgnoreCase ("ftp:");
  201707. #if WORKAROUND_TIMEOUT_BUG
  201708. HINTERNET connection = 0;
  201709. {
  201710. InternetConnectThread connectThread (uc, connection, isFtp);
  201711. connectThread.wait (timeOutMs);
  201712. if (connection == 0)
  201713. {
  201714. InternetCloseHandle (sessionHandle);
  201715. sessionHandle = 0;
  201716. }
  201717. }
  201718. #else
  201719. HINTERNET connection = InternetConnect (sessionHandle,
  201720. uc.lpszHostName,
  201721. uc.nPort,
  201722. _T(""), _T(""),
  201723. isFtp ? INTERNET_SERVICE_FTP
  201724. : INTERNET_SERVICE_HTTP,
  201725. 0, 0);
  201726. #endif
  201727. if (connection != 0)
  201728. {
  201729. if (isFtp)
  201730. {
  201731. HINTERNET request = FtpOpenFile (connection,
  201732. uc.lpszUrlPath,
  201733. GENERIC_READ,
  201734. FTP_TRANSFER_TYPE_BINARY | INTERNET_FLAG_NEED_FILE,
  201735. 0);
  201736. ConnectionAndRequestStruct* const result = new ConnectionAndRequestStruct();
  201737. result->connection = connection;
  201738. result->request = request;
  201739. return result;
  201740. }
  201741. else
  201742. {
  201743. const TCHAR* mimeTypes[] = { _T("*/*"), 0 };
  201744. DWORD flags = INTERNET_FLAG_RELOAD | INTERNET_FLAG_NO_CACHE_WRITE;
  201745. if (url.startsWithIgnoreCase ("https:"))
  201746. flags |= INTERNET_FLAG_SECURE; // (this flag only seems necessary if the OS is running IE6 -
  201747. // IE7 seems to automatically work out when it's https)
  201748. HINTERNET request = HttpOpenRequest (connection,
  201749. isPost ? _T("POST")
  201750. : _T("GET"),
  201751. uc.lpszUrlPath,
  201752. 0, 0, mimeTypes, flags, 0);
  201753. if (request != 0)
  201754. {
  201755. INTERNET_BUFFERS buffers;
  201756. zerostruct (buffers);
  201757. buffers.dwStructSize = sizeof (INTERNET_BUFFERS);
  201758. buffers.lpcszHeader = (LPCTSTR) headers;
  201759. buffers.dwHeadersLength = headers.length();
  201760. buffers.dwBufferTotal = (DWORD) postData.getSize();
  201761. ConnectionAndRequestStruct* result = 0;
  201762. if (HttpSendRequestEx (request, &buffers, 0, HSR_INITIATE, 0))
  201763. {
  201764. int bytesSent = 0;
  201765. for (;;)
  201766. {
  201767. const int bytesToDo = jmin (1024, (int) postData.getSize() - bytesSent);
  201768. DWORD bytesDone = 0;
  201769. if (bytesToDo > 0
  201770. && ! InternetWriteFile (request,
  201771. static_cast <const char*> (postData.getData()) + bytesSent,
  201772. bytesToDo, &bytesDone))
  201773. {
  201774. break;
  201775. }
  201776. if (bytesToDo == 0 || (int) bytesDone < bytesToDo)
  201777. {
  201778. result = new ConnectionAndRequestStruct();
  201779. result->connection = connection;
  201780. result->request = request;
  201781. HttpEndRequest (request, 0, 0, 0);
  201782. return result;
  201783. }
  201784. bytesSent += bytesDone;
  201785. if (callback != 0 && ! callback (callbackContext, bytesSent, postData.getSize()))
  201786. break;
  201787. }
  201788. }
  201789. InternetCloseHandle (request);
  201790. }
  201791. InternetCloseHandle (connection);
  201792. }
  201793. }
  201794. }
  201795. }
  201796. return 0;
  201797. }
  201798. int juce_readFromInternetFile (void* handle, void* buffer, int bytesToRead)
  201799. {
  201800. DWORD bytesRead = 0;
  201801. const ConnectionAndRequestStruct* const crs = static_cast <ConnectionAndRequestStruct*> (handle);
  201802. if (crs != 0)
  201803. InternetReadFile (crs->request,
  201804. buffer, bytesToRead,
  201805. &bytesRead);
  201806. return bytesRead;
  201807. }
  201808. int juce_seekInInternetFile (void* handle, int newPosition)
  201809. {
  201810. if (handle != 0)
  201811. {
  201812. const ConnectionAndRequestStruct* const crs = static_cast <ConnectionAndRequestStruct*> (handle);
  201813. return InternetSetFilePointer (crs->request, newPosition, 0, FILE_BEGIN, 0);
  201814. }
  201815. return -1;
  201816. }
  201817. int64 juce_getInternetFileContentLength (void* handle)
  201818. {
  201819. const ConnectionAndRequestStruct* const crs = static_cast <ConnectionAndRequestStruct*> (handle);
  201820. if (crs != 0)
  201821. {
  201822. DWORD index = 0, result = 0, size = sizeof (result);
  201823. if (HttpQueryInfo (crs->request, HTTP_QUERY_CONTENT_LENGTH | HTTP_QUERY_FLAG_NUMBER,
  201824. &result, &size, &index))
  201825. {
  201826. return (int64) result;
  201827. }
  201828. }
  201829. return -1;
  201830. }
  201831. void juce_closeInternetFile (void* handle)
  201832. {
  201833. if (handle != 0)
  201834. {
  201835. ScopedPointer <ConnectionAndRequestStruct> crs (static_cast <ConnectionAndRequestStruct*> (handle));
  201836. InternetCloseHandle (crs->request);
  201837. InternetCloseHandle (crs->connection);
  201838. }
  201839. }
  201840. static int getMACAddressViaGetAdaptersInfo (int64* addresses, int maxNum, const bool littleEndian) throw()
  201841. {
  201842. int numFound = 0;
  201843. DynamicLibraryLoader dll ("iphlpapi.dll");
  201844. DynamicLibraryImport (GetAdaptersInfo, getAdaptersInfo, DWORD, dll, (PIP_ADAPTER_INFO, PULONG))
  201845. if (getAdaptersInfo != 0)
  201846. {
  201847. ULONG len = sizeof (IP_ADAPTER_INFO);
  201848. MemoryBlock mb;
  201849. PIP_ADAPTER_INFO adapterInfo = (PIP_ADAPTER_INFO) mb.getData();
  201850. if (getAdaptersInfo (adapterInfo, &len) == ERROR_BUFFER_OVERFLOW)
  201851. {
  201852. mb.setSize (len);
  201853. adapterInfo = (PIP_ADAPTER_INFO) mb.getData();
  201854. }
  201855. if (getAdaptersInfo (adapterInfo, &len) == NO_ERROR)
  201856. {
  201857. PIP_ADAPTER_INFO adapter = adapterInfo;
  201858. while (adapter != 0)
  201859. {
  201860. int64 mac = 0;
  201861. for (unsigned int i = 0; i < adapter->AddressLength; ++i)
  201862. mac = (mac << 8) | adapter->Address[i];
  201863. if (littleEndian)
  201864. mac = (int64) ByteOrder::swap ((uint64) mac);
  201865. if (numFound < maxNum && mac != 0)
  201866. addresses [numFound++] = mac;
  201867. adapter = adapter->Next;
  201868. }
  201869. }
  201870. }
  201871. return numFound;
  201872. }
  201873. static int getMACAddressesViaNetBios (int64* addresses, int maxNum, const bool littleEndian) throw()
  201874. {
  201875. int numFound = 0;
  201876. DynamicLibraryLoader dll ("netapi32.dll");
  201877. DynamicLibraryImport (Netbios, NetbiosCall, UCHAR, dll, (PNCB))
  201878. if (NetbiosCall != 0)
  201879. {
  201880. NCB ncb;
  201881. zerostruct (ncb);
  201882. struct ASTAT
  201883. {
  201884. ADAPTER_STATUS adapt;
  201885. NAME_BUFFER NameBuff [30];
  201886. };
  201887. ASTAT astat;
  201888. zeromem (&astat, sizeof (astat)); // (can't use zerostruct here in VC6)
  201889. LANA_ENUM enums;
  201890. zerostruct (enums);
  201891. ncb.ncb_command = NCBENUM;
  201892. ncb.ncb_buffer = (unsigned char*) &enums;
  201893. ncb.ncb_length = sizeof (LANA_ENUM);
  201894. NetbiosCall (&ncb);
  201895. for (int i = 0; i < enums.length; ++i)
  201896. {
  201897. zerostruct (ncb);
  201898. ncb.ncb_command = NCBRESET;
  201899. ncb.ncb_lana_num = enums.lana[i];
  201900. if (NetbiosCall (&ncb) == 0)
  201901. {
  201902. zerostruct (ncb);
  201903. memcpy (ncb.ncb_callname, "* ", NCBNAMSZ);
  201904. ncb.ncb_command = NCBASTAT;
  201905. ncb.ncb_lana_num = enums.lana[i];
  201906. ncb.ncb_buffer = (unsigned char*) &astat;
  201907. ncb.ncb_length = sizeof (ASTAT);
  201908. if (NetbiosCall (&ncb) == 0)
  201909. {
  201910. if (astat.adapt.adapter_type == 0xfe)
  201911. {
  201912. uint64 mac = 0;
  201913. for (int i = 6; --i >= 0;)
  201914. mac = (mac << 8) | astat.adapt.adapter_address [littleEndian ? i : (5 - i)];
  201915. if (numFound < maxNum && mac != 0)
  201916. addresses [numFound++] = mac;
  201917. }
  201918. }
  201919. }
  201920. }
  201921. }
  201922. return numFound;
  201923. }
  201924. int SystemStats::getMACAddresses (int64* addresses, int maxNum, const bool littleEndian)
  201925. {
  201926. int numFound = getMACAddressViaGetAdaptersInfo (addresses, maxNum, littleEndian);
  201927. if (numFound == 0)
  201928. numFound = getMACAddressesViaNetBios (addresses, maxNum, littleEndian);
  201929. return numFound;
  201930. }
  201931. bool PlatformUtilities::launchEmailWithAttachments (const String& targetEmailAddress,
  201932. const String& emailSubject,
  201933. const String& bodyText,
  201934. const StringArray& filesToAttach)
  201935. {
  201936. HMODULE h = LoadLibraryA ("MAPI32.dll");
  201937. typedef ULONG (WINAPI *MAPISendMailType) (LHANDLE, ULONG, lpMapiMessage, ::FLAGS, ULONG);
  201938. MAPISendMailType mapiSendMail = (MAPISendMailType) GetProcAddress (h, "MAPISendMail");
  201939. bool ok = false;
  201940. if (mapiSendMail != 0)
  201941. {
  201942. MapiMessage message;
  201943. zerostruct (message);
  201944. message.lpszSubject = (LPSTR) emailSubject.toCString();
  201945. message.lpszNoteText = (LPSTR) bodyText.toCString();
  201946. MapiRecipDesc recip;
  201947. zerostruct (recip);
  201948. recip.ulRecipClass = MAPI_TO;
  201949. String targetEmailAddress_ (targetEmailAddress);
  201950. if (targetEmailAddress_.isEmpty())
  201951. targetEmailAddress_ = " "; // (Windows Mail can't deal with a blank address)
  201952. recip.lpszName = (LPSTR) targetEmailAddress_.toCString();
  201953. message.nRecipCount = 1;
  201954. message.lpRecips = &recip;
  201955. HeapBlock <MapiFileDesc> files;
  201956. files.calloc (filesToAttach.size());
  201957. message.nFileCount = filesToAttach.size();
  201958. message.lpFiles = files;
  201959. for (int i = 0; i < filesToAttach.size(); ++i)
  201960. {
  201961. files[i].nPosition = (ULONG) -1;
  201962. files[i].lpszPathName = (LPSTR) filesToAttach[i].toCString();
  201963. }
  201964. ok = (mapiSendMail (0, 0, &message, MAPI_DIALOG | MAPI_LOGON_UI, 0) == SUCCESS_SUCCESS);
  201965. }
  201966. FreeLibrary (h);
  201967. return ok;
  201968. }
  201969. #endif
  201970. /*** End of inlined file: juce_win32_Network.cpp ***/
  201971. /*** Start of inlined file: juce_win32_PlatformUtils.cpp ***/
  201972. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  201973. // compiled on its own).
  201974. #if JUCE_INCLUDED_FILE
  201975. static HKEY findKeyForPath (String name,
  201976. const bool createForWriting,
  201977. String& valueName)
  201978. {
  201979. HKEY rootKey = 0;
  201980. if (name.startsWithIgnoreCase ("HKEY_CURRENT_USER\\"))
  201981. rootKey = HKEY_CURRENT_USER;
  201982. else if (name.startsWithIgnoreCase ("HKEY_LOCAL_MACHINE\\"))
  201983. rootKey = HKEY_LOCAL_MACHINE;
  201984. else if (name.startsWithIgnoreCase ("HKEY_CLASSES_ROOT\\"))
  201985. rootKey = HKEY_CLASSES_ROOT;
  201986. if (rootKey != 0)
  201987. {
  201988. name = name.substring (name.indexOfChar ('\\') + 1);
  201989. const int lastSlash = name.lastIndexOfChar ('\\');
  201990. valueName = name.substring (lastSlash + 1);
  201991. name = name.substring (0, lastSlash);
  201992. HKEY key;
  201993. DWORD result;
  201994. if (createForWriting)
  201995. {
  201996. if (RegCreateKeyEx (rootKey, name, 0, 0, REG_OPTION_NON_VOLATILE,
  201997. (KEY_WRITE | KEY_QUERY_VALUE), 0, &key, &result) == ERROR_SUCCESS)
  201998. return key;
  201999. }
  202000. else
  202001. {
  202002. if (RegOpenKeyEx (rootKey, name, 0, KEY_READ, &key) == ERROR_SUCCESS)
  202003. return key;
  202004. }
  202005. }
  202006. return 0;
  202007. }
  202008. const String PlatformUtilities::getRegistryValue (const String& regValuePath,
  202009. const String& defaultValue)
  202010. {
  202011. String valueName, result (defaultValue);
  202012. HKEY k = findKeyForPath (regValuePath, false, valueName);
  202013. if (k != 0)
  202014. {
  202015. WCHAR buffer [2048];
  202016. unsigned long bufferSize = sizeof (buffer);
  202017. DWORD type = REG_SZ;
  202018. if (RegQueryValueEx (k, valueName, 0, &type, (LPBYTE) buffer, &bufferSize) == ERROR_SUCCESS)
  202019. {
  202020. if (type == REG_SZ)
  202021. result = buffer;
  202022. else if (type == REG_DWORD)
  202023. result = String ((int) *(DWORD*) buffer);
  202024. }
  202025. RegCloseKey (k);
  202026. }
  202027. return result;
  202028. }
  202029. void PlatformUtilities::setRegistryValue (const String& regValuePath,
  202030. const String& value)
  202031. {
  202032. String valueName;
  202033. HKEY k = findKeyForPath (regValuePath, true, valueName);
  202034. if (k != 0)
  202035. {
  202036. RegSetValueEx (k, valueName, 0, REG_SZ,
  202037. (const BYTE*) (const WCHAR*) value,
  202038. sizeof (WCHAR) * (value.length() + 1));
  202039. RegCloseKey (k);
  202040. }
  202041. }
  202042. bool PlatformUtilities::registryValueExists (const String& regValuePath)
  202043. {
  202044. bool exists = false;
  202045. String valueName;
  202046. HKEY k = findKeyForPath (regValuePath, false, valueName);
  202047. if (k != 0)
  202048. {
  202049. unsigned char buffer [2048];
  202050. unsigned long bufferSize = sizeof (buffer);
  202051. DWORD type = 0;
  202052. if (RegQueryValueEx (k, valueName, 0, &type, buffer, &bufferSize) == ERROR_SUCCESS)
  202053. exists = true;
  202054. RegCloseKey (k);
  202055. }
  202056. return exists;
  202057. }
  202058. void PlatformUtilities::deleteRegistryValue (const String& regValuePath)
  202059. {
  202060. String valueName;
  202061. HKEY k = findKeyForPath (regValuePath, true, valueName);
  202062. if (k != 0)
  202063. {
  202064. RegDeleteValue (k, valueName);
  202065. RegCloseKey (k);
  202066. }
  202067. }
  202068. void PlatformUtilities::deleteRegistryKey (const String& regKeyPath)
  202069. {
  202070. String valueName;
  202071. HKEY k = findKeyForPath (regKeyPath, true, valueName);
  202072. if (k != 0)
  202073. {
  202074. RegDeleteKey (k, valueName);
  202075. RegCloseKey (k);
  202076. }
  202077. }
  202078. void PlatformUtilities::registerFileAssociation (const String& fileExtension,
  202079. const String& symbolicDescription,
  202080. const String& fullDescription,
  202081. const File& targetExecutable,
  202082. int iconResourceNumber)
  202083. {
  202084. setRegistryValue ("HKEY_CLASSES_ROOT\\" + fileExtension + "\\", symbolicDescription);
  202085. const String key ("HKEY_CLASSES_ROOT\\" + symbolicDescription);
  202086. if (iconResourceNumber != 0)
  202087. setRegistryValue (key + "\\DefaultIcon\\",
  202088. targetExecutable.getFullPathName() + "," + String (-iconResourceNumber));
  202089. setRegistryValue (key + "\\", fullDescription);
  202090. setRegistryValue (key + "\\shell\\open\\command\\",
  202091. targetExecutable.getFullPathName() + " %1");
  202092. }
  202093. bool juce_IsRunningInWine()
  202094. {
  202095. HKEY key;
  202096. if (RegOpenKeyEx (HKEY_CURRENT_USER, _T("Software\\Wine"), 0, KEY_READ, &key) == ERROR_SUCCESS)
  202097. {
  202098. RegCloseKey (key);
  202099. return true;
  202100. }
  202101. return false;
  202102. }
  202103. const String JUCE_CALLTYPE PlatformUtilities::getCurrentCommandLineParams() throw()
  202104. {
  202105. String s (::GetCommandLineW());
  202106. StringArray tokens;
  202107. tokens.addTokens (s, true); // tokenise so that we can remove the initial filename argument
  202108. return tokens.joinIntoString (" ", 1);
  202109. }
  202110. static void* currentModuleHandle = 0;
  202111. void* PlatformUtilities::getCurrentModuleInstanceHandle() throw()
  202112. {
  202113. if (currentModuleHandle == 0)
  202114. currentModuleHandle = GetModuleHandle (0);
  202115. return currentModuleHandle;
  202116. }
  202117. void PlatformUtilities::setCurrentModuleInstanceHandle (void* const newHandle) throw()
  202118. {
  202119. currentModuleHandle = newHandle;
  202120. }
  202121. void PlatformUtilities::fpuReset()
  202122. {
  202123. #if JUCE_MSVC
  202124. _clearfp();
  202125. #endif
  202126. }
  202127. void PlatformUtilities::beep()
  202128. {
  202129. MessageBeep (MB_OK);
  202130. }
  202131. #endif
  202132. /*** End of inlined file: juce_win32_PlatformUtils.cpp ***/
  202133. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  202134. /*** Start of inlined file: juce_win32_Messaging.cpp ***/
  202135. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  202136. // compiled on its own).
  202137. #if JUCE_INCLUDED_FILE
  202138. static const unsigned int specialId = WM_APP + 0x4400;
  202139. static const unsigned int broadcastId = WM_APP + 0x4403;
  202140. static const unsigned int specialCallbackId = WM_APP + 0x4402;
  202141. static const TCHAR* const messageWindowName = _T("JUCEWindow");
  202142. HWND juce_messageWindowHandle = 0;
  202143. extern long improbableWindowNumber; // defined in windowing.cpp
  202144. #ifndef WM_APPCOMMAND
  202145. #define WM_APPCOMMAND 0x0319
  202146. #endif
  202147. static LRESULT CALLBACK juce_MessageWndProc (HWND h,
  202148. const UINT message,
  202149. const WPARAM wParam,
  202150. const LPARAM lParam) throw()
  202151. {
  202152. JUCE_TRY
  202153. {
  202154. if (h == juce_messageWindowHandle)
  202155. {
  202156. if (message == specialCallbackId)
  202157. {
  202158. MessageCallbackFunction* const func = (MessageCallbackFunction*) wParam;
  202159. return (LRESULT) (*func) ((void*) lParam);
  202160. }
  202161. else if (message == specialId)
  202162. {
  202163. // these are trapped early in the dispatch call, but must also be checked
  202164. // here in case there are windows modal dialog boxes doing their own
  202165. // dispatch loop and not calling our version
  202166. MessageManager::getInstance()->deliverMessage ((void*) lParam);
  202167. return 0;
  202168. }
  202169. else if (message == broadcastId)
  202170. {
  202171. const ScopedPointer <String> messageString ((String*) lParam);
  202172. MessageManager::getInstance()->deliverBroadcastMessage (*messageString);
  202173. return 0;
  202174. }
  202175. else if (message == WM_COPYDATA && ((const COPYDATASTRUCT*) lParam)->dwData == broadcastId)
  202176. {
  202177. const String messageString ((const juce_wchar*) ((const COPYDATASTRUCT*) lParam)->lpData,
  202178. ((const COPYDATASTRUCT*) lParam)->cbData / sizeof (juce_wchar));
  202179. PostMessage (juce_messageWindowHandle, broadcastId, 0, (LPARAM) new String (messageString));
  202180. return 0;
  202181. }
  202182. }
  202183. }
  202184. JUCE_CATCH_EXCEPTION
  202185. return DefWindowProc (h, message, wParam, lParam);
  202186. }
  202187. static bool isEventBlockedByModalComps (MSG& m)
  202188. {
  202189. if (Component::getNumCurrentlyModalComponents() == 0
  202190. || GetWindowLong (m.hwnd, GWLP_USERDATA) == improbableWindowNumber)
  202191. return false;
  202192. switch (m.message)
  202193. {
  202194. case WM_MOUSEMOVE:
  202195. case WM_NCMOUSEMOVE:
  202196. case 0x020A: /* WM_MOUSEWHEEL */
  202197. case 0x020E: /* WM_MOUSEHWHEEL */
  202198. case WM_KEYUP:
  202199. case WM_SYSKEYUP:
  202200. case WM_CHAR:
  202201. case WM_APPCOMMAND:
  202202. case WM_LBUTTONUP:
  202203. case WM_MBUTTONUP:
  202204. case WM_RBUTTONUP:
  202205. case WM_MOUSEACTIVATE:
  202206. case WM_NCMOUSEHOVER:
  202207. case WM_MOUSEHOVER:
  202208. return true;
  202209. case WM_NCLBUTTONDOWN:
  202210. case WM_NCLBUTTONDBLCLK:
  202211. case WM_NCRBUTTONDOWN:
  202212. case WM_NCRBUTTONDBLCLK:
  202213. case WM_NCMBUTTONDOWN:
  202214. case WM_NCMBUTTONDBLCLK:
  202215. case WM_LBUTTONDOWN:
  202216. case WM_LBUTTONDBLCLK:
  202217. case WM_MBUTTONDOWN:
  202218. case WM_MBUTTONDBLCLK:
  202219. case WM_RBUTTONDOWN:
  202220. case WM_RBUTTONDBLCLK:
  202221. case WM_KEYDOWN:
  202222. case WM_SYSKEYDOWN:
  202223. {
  202224. Component* const modal = Component::getCurrentlyModalComponent (0);
  202225. if (modal != 0)
  202226. modal->inputAttemptWhenModal();
  202227. return true;
  202228. }
  202229. default:
  202230. break;
  202231. }
  202232. return false;
  202233. }
  202234. bool juce_dispatchNextMessageOnSystemQueue (const bool returnIfNoPendingMessages)
  202235. {
  202236. MSG m;
  202237. if (returnIfNoPendingMessages && ! PeekMessage (&m, (HWND) 0, 0, 0, 0))
  202238. return false;
  202239. if (GetMessage (&m, (HWND) 0, 0, 0) >= 0)
  202240. {
  202241. if (m.message == specialId && m.hwnd == juce_messageWindowHandle)
  202242. {
  202243. MessageManager::getInstance()->deliverMessage ((void*) m.lParam);
  202244. }
  202245. else if (m.message == WM_QUIT)
  202246. {
  202247. if (JUCEApplication::getInstance())
  202248. JUCEApplication::getInstance()->systemRequestedQuit();
  202249. }
  202250. else if (! isEventBlockedByModalComps (m))
  202251. {
  202252. if ((m.message == WM_LBUTTONDOWN || m.message == WM_RBUTTONDOWN)
  202253. && GetWindowLong (m.hwnd, GWLP_USERDATA) != improbableWindowNumber)
  202254. {
  202255. // if it's someone else's window being clicked on, and the focus is
  202256. // currently on a juce window, pass the kb focus over..
  202257. HWND currentFocus = GetFocus();
  202258. if (currentFocus == 0 || GetWindowLong (currentFocus, GWLP_USERDATA) == improbableWindowNumber)
  202259. SetFocus (m.hwnd);
  202260. }
  202261. TranslateMessage (&m);
  202262. DispatchMessage (&m);
  202263. }
  202264. }
  202265. return true;
  202266. }
  202267. bool juce_postMessageToSystemQueue (void* message)
  202268. {
  202269. return PostMessage (juce_messageWindowHandle, specialId, 0, (LPARAM) message) != 0;
  202270. }
  202271. void* MessageManager::callFunctionOnMessageThread (MessageCallbackFunction* callback,
  202272. void* userData)
  202273. {
  202274. if (MessageManager::getInstance()->isThisTheMessageThread())
  202275. {
  202276. return (*callback) (userData);
  202277. }
  202278. else
  202279. {
  202280. // If a thread has a MessageManagerLock and then tries to call this method, it'll
  202281. // deadlock because the message manager is blocked from running, and can't
  202282. // call your function..
  202283. jassert (! MessageManager::getInstance()->currentThreadHasLockedMessageManager());
  202284. return (void*) SendMessage (juce_messageWindowHandle,
  202285. specialCallbackId,
  202286. (WPARAM) callback,
  202287. (LPARAM) userData);
  202288. }
  202289. }
  202290. static BOOL CALLBACK BroadcastEnumWindowProc (HWND hwnd, LPARAM lParam)
  202291. {
  202292. if (hwnd != juce_messageWindowHandle)
  202293. reinterpret_cast <VoidArray*> (lParam)->add ((void*) hwnd);
  202294. return TRUE;
  202295. }
  202296. void MessageManager::broadcastMessage (const String& value) throw()
  202297. {
  202298. VoidArray windows;
  202299. EnumWindows (&BroadcastEnumWindowProc, (LPARAM) &windows);
  202300. const String localCopy (value);
  202301. COPYDATASTRUCT data;
  202302. data.dwData = broadcastId;
  202303. data.cbData = (localCopy.length() + 1) * sizeof (juce_wchar);
  202304. data.lpData = (void*) static_cast <const juce_wchar*> (localCopy);
  202305. for (int i = windows.size(); --i >= 0;)
  202306. {
  202307. HWND hwnd = (HWND) windows.getUnchecked(i);
  202308. TCHAR windowName [64]; // no need to read longer strings than this
  202309. GetWindowText (hwnd, windowName, 64);
  202310. windowName [63] = 0;
  202311. if (String (windowName) == messageWindowName)
  202312. {
  202313. DWORD_PTR result;
  202314. SendMessageTimeout (hwnd, WM_COPYDATA,
  202315. (WPARAM) juce_messageWindowHandle,
  202316. (LPARAM) &data,
  202317. SMTO_BLOCK | SMTO_ABORTIFHUNG,
  202318. 8000,
  202319. &result);
  202320. }
  202321. }
  202322. }
  202323. static const String getMessageWindowClassName()
  202324. {
  202325. // this name has to be different for each app/dll instance because otherwise
  202326. // poor old Win32 can get a bit confused (even despite it not being a process-global
  202327. // window class).
  202328. static int number = 0;
  202329. if (number == 0)
  202330. number = 0x7fffffff & (int) Time::getHighResolutionTicks();
  202331. return "JUCEcs_" + String (number);
  202332. }
  202333. void MessageManager::doPlatformSpecificInitialisation()
  202334. {
  202335. OleInitialize (0);
  202336. const String className (getMessageWindowClassName());
  202337. HMODULE hmod = (HMODULE) PlatformUtilities::getCurrentModuleInstanceHandle();
  202338. WNDCLASSEX wc;
  202339. zerostruct (wc);
  202340. wc.cbSize = sizeof (wc);
  202341. wc.lpfnWndProc = (WNDPROC) juce_MessageWndProc;
  202342. wc.cbWndExtra = 4;
  202343. wc.hInstance = hmod;
  202344. wc.lpszClassName = className;
  202345. RegisterClassEx (&wc);
  202346. juce_messageWindowHandle = CreateWindow (wc.lpszClassName,
  202347. messageWindowName,
  202348. 0, 0, 0, 0, 0, 0, 0,
  202349. hmod, 0);
  202350. }
  202351. void MessageManager::doPlatformSpecificShutdown()
  202352. {
  202353. DestroyWindow (juce_messageWindowHandle);
  202354. UnregisterClass (getMessageWindowClassName(), 0);
  202355. OleUninitialize();
  202356. }
  202357. #endif
  202358. /*** End of inlined file: juce_win32_Messaging.cpp ***/
  202359. /*** Start of inlined file: juce_win32_Windowing.cpp ***/
  202360. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  202361. // compiled on its own).
  202362. #if JUCE_INCLUDED_FILE
  202363. #undef GetSystemMetrics // multimon overrides this for some reason and causes a mess..
  202364. // these are in the windows SDK, but need to be repeated here for GCC..
  202365. #ifndef GET_APPCOMMAND_LPARAM
  202366. #define FAPPCOMMAND_MASK 0xF000
  202367. #define GET_APPCOMMAND_LPARAM(lParam) ((short) (HIWORD (lParam) & ~FAPPCOMMAND_MASK))
  202368. #define APPCOMMAND_MEDIA_NEXTTRACK 11
  202369. #define APPCOMMAND_MEDIA_PREVIOUSTRACK 12
  202370. #define APPCOMMAND_MEDIA_STOP 13
  202371. #define APPCOMMAND_MEDIA_PLAY_PAUSE 14
  202372. #define WM_APPCOMMAND 0x0319
  202373. #endif
  202374. extern void juce_repeatLastProcessPriority(); // in juce_win32_Threads.cpp
  202375. extern void juce_CheckCurrentlyFocusedTopLevelWindow(); // in juce_TopLevelWindow.cpp
  202376. extern bool juce_IsRunningInWine();
  202377. #ifndef ULW_ALPHA
  202378. #define ULW_ALPHA 0x00000002
  202379. #endif
  202380. #ifndef AC_SRC_ALPHA
  202381. #define AC_SRC_ALPHA 0x01
  202382. #endif
  202383. static HPALETTE palette = 0;
  202384. static bool createPaletteIfNeeded = true;
  202385. static bool shouldDeactivateTitleBar = true;
  202386. static HICON createHICONFromImage (const Image& image, const BOOL isIcon, int hotspotX, int hotspotY) throw();
  202387. #define WM_TRAYNOTIFY WM_USER + 100
  202388. using ::abs;
  202389. typedef BOOL (WINAPI* UpdateLayeredWinFunc) (HWND, HDC, POINT*, SIZE*, HDC, POINT*, COLORREF, BLENDFUNCTION*, DWORD);
  202390. static UpdateLayeredWinFunc updateLayeredWindow = 0;
  202391. bool Desktop::canUseSemiTransparentWindows() throw()
  202392. {
  202393. if (updateLayeredWindow == 0)
  202394. {
  202395. if (! juce_IsRunningInWine())
  202396. {
  202397. HMODULE user32Mod = GetModuleHandle (_T("user32.dll"));
  202398. updateLayeredWindow = (UpdateLayeredWinFunc) GetProcAddress (user32Mod, "UpdateLayeredWindow");
  202399. }
  202400. }
  202401. return updateLayeredWindow != 0;
  202402. }
  202403. const int extendedKeyModifier = 0x10000;
  202404. const int KeyPress::spaceKey = VK_SPACE;
  202405. const int KeyPress::returnKey = VK_RETURN;
  202406. const int KeyPress::escapeKey = VK_ESCAPE;
  202407. const int KeyPress::backspaceKey = VK_BACK;
  202408. const int KeyPress::deleteKey = VK_DELETE | extendedKeyModifier;
  202409. const int KeyPress::insertKey = VK_INSERT | extendedKeyModifier;
  202410. const int KeyPress::tabKey = VK_TAB;
  202411. const int KeyPress::leftKey = VK_LEFT | extendedKeyModifier;
  202412. const int KeyPress::rightKey = VK_RIGHT | extendedKeyModifier;
  202413. const int KeyPress::upKey = VK_UP | extendedKeyModifier;
  202414. const int KeyPress::downKey = VK_DOWN | extendedKeyModifier;
  202415. const int KeyPress::homeKey = VK_HOME | extendedKeyModifier;
  202416. const int KeyPress::endKey = VK_END | extendedKeyModifier;
  202417. const int KeyPress::pageUpKey = VK_PRIOR | extendedKeyModifier;
  202418. const int KeyPress::pageDownKey = VK_NEXT | extendedKeyModifier;
  202419. const int KeyPress::F1Key = VK_F1 | extendedKeyModifier;
  202420. const int KeyPress::F2Key = VK_F2 | extendedKeyModifier;
  202421. const int KeyPress::F3Key = VK_F3 | extendedKeyModifier;
  202422. const int KeyPress::F4Key = VK_F4 | extendedKeyModifier;
  202423. const int KeyPress::F5Key = VK_F5 | extendedKeyModifier;
  202424. const int KeyPress::F6Key = VK_F6 | extendedKeyModifier;
  202425. const int KeyPress::F7Key = VK_F7 | extendedKeyModifier;
  202426. const int KeyPress::F8Key = VK_F8 | extendedKeyModifier;
  202427. const int KeyPress::F9Key = VK_F9 | extendedKeyModifier;
  202428. const int KeyPress::F10Key = VK_F10 | extendedKeyModifier;
  202429. const int KeyPress::F11Key = VK_F11 | extendedKeyModifier;
  202430. const int KeyPress::F12Key = VK_F12 | extendedKeyModifier;
  202431. const int KeyPress::F13Key = VK_F13 | extendedKeyModifier;
  202432. const int KeyPress::F14Key = VK_F14 | extendedKeyModifier;
  202433. const int KeyPress::F15Key = VK_F15 | extendedKeyModifier;
  202434. const int KeyPress::F16Key = VK_F16 | extendedKeyModifier;
  202435. const int KeyPress::numberPad0 = VK_NUMPAD0 | extendedKeyModifier;
  202436. const int KeyPress::numberPad1 = VK_NUMPAD1 | extendedKeyModifier;
  202437. const int KeyPress::numberPad2 = VK_NUMPAD2 | extendedKeyModifier;
  202438. const int KeyPress::numberPad3 = VK_NUMPAD3 | extendedKeyModifier;
  202439. const int KeyPress::numberPad4 = VK_NUMPAD4 | extendedKeyModifier;
  202440. const int KeyPress::numberPad5 = VK_NUMPAD5 | extendedKeyModifier;
  202441. const int KeyPress::numberPad6 = VK_NUMPAD6 | extendedKeyModifier;
  202442. const int KeyPress::numberPad7 = VK_NUMPAD7 | extendedKeyModifier;
  202443. const int KeyPress::numberPad8 = VK_NUMPAD8 | extendedKeyModifier;
  202444. const int KeyPress::numberPad9 = VK_NUMPAD9 | extendedKeyModifier;
  202445. const int KeyPress::numberPadAdd = VK_ADD | extendedKeyModifier;
  202446. const int KeyPress::numberPadSubtract = VK_SUBTRACT | extendedKeyModifier;
  202447. const int KeyPress::numberPadMultiply = VK_MULTIPLY | extendedKeyModifier;
  202448. const int KeyPress::numberPadDivide = VK_DIVIDE | extendedKeyModifier;
  202449. const int KeyPress::numberPadSeparator = VK_SEPARATOR | extendedKeyModifier;
  202450. const int KeyPress::numberPadDecimalPoint = VK_DECIMAL | extendedKeyModifier;
  202451. const int KeyPress::numberPadEquals = 0x92 /*VK_OEM_NEC_EQUAL*/ | extendedKeyModifier;
  202452. const int KeyPress::numberPadDelete = VK_DELETE | extendedKeyModifier;
  202453. const int KeyPress::playKey = 0x30000;
  202454. const int KeyPress::stopKey = 0x30001;
  202455. const int KeyPress::fastForwardKey = 0x30002;
  202456. const int KeyPress::rewindKey = 0x30003;
  202457. class WindowsBitmapImage : public Image
  202458. {
  202459. public:
  202460. HBITMAP hBitmap;
  202461. BITMAPV4HEADER bitmapInfo;
  202462. HDC hdc;
  202463. unsigned char* bitmapData;
  202464. WindowsBitmapImage (const PixelFormat format_,
  202465. const int w, const int h, const bool clearImage)
  202466. : Image (format_, w, h)
  202467. {
  202468. jassert (format_ == RGB || format_ == ARGB);
  202469. pixelStride = (format_ == RGB) ? 3 : 4;
  202470. zerostruct (bitmapInfo);
  202471. bitmapInfo.bV4Size = sizeof (BITMAPV4HEADER);
  202472. bitmapInfo.bV4Width = w;
  202473. bitmapInfo.bV4Height = h;
  202474. bitmapInfo.bV4Planes = 1;
  202475. bitmapInfo.bV4CSType = 1;
  202476. bitmapInfo.bV4BitCount = (unsigned short) (pixelStride * 8);
  202477. if (format_ == ARGB)
  202478. {
  202479. bitmapInfo.bV4AlphaMask = 0xff000000;
  202480. bitmapInfo.bV4RedMask = 0xff0000;
  202481. bitmapInfo.bV4GreenMask = 0xff00;
  202482. bitmapInfo.bV4BlueMask = 0xff;
  202483. bitmapInfo.bV4V4Compression = BI_BITFIELDS;
  202484. }
  202485. else
  202486. {
  202487. bitmapInfo.bV4V4Compression = BI_RGB;
  202488. }
  202489. lineStride = -((w * pixelStride + 3) & ~3);
  202490. HDC dc = GetDC (0);
  202491. hdc = CreateCompatibleDC (dc);
  202492. ReleaseDC (0, dc);
  202493. SetMapMode (hdc, MM_TEXT);
  202494. hBitmap = CreateDIBSection (hdc,
  202495. (BITMAPINFO*) &(bitmapInfo),
  202496. DIB_RGB_COLORS,
  202497. (void**) &bitmapData,
  202498. 0, 0);
  202499. SelectObject (hdc, hBitmap);
  202500. if (format_ == ARGB && clearImage)
  202501. zeromem (bitmapData, abs (h * lineStride));
  202502. imageData = bitmapData - (lineStride * (h - 1));
  202503. }
  202504. ~WindowsBitmapImage()
  202505. {
  202506. DeleteDC (hdc);
  202507. DeleteObject (hBitmap);
  202508. }
  202509. void blitToWindow (HWND hwnd, HDC dc, const bool transparent,
  202510. const int x, const int y,
  202511. const RectangleList& maskedRegion) throw()
  202512. {
  202513. static HDRAWDIB hdd = 0;
  202514. static bool needToCreateDrawDib = true;
  202515. if (needToCreateDrawDib)
  202516. {
  202517. needToCreateDrawDib = false;
  202518. HDC dc = GetDC (0);
  202519. const int n = GetDeviceCaps (dc, BITSPIXEL);
  202520. ReleaseDC (0, dc);
  202521. // only open if we're not palettised
  202522. if (n > 8)
  202523. hdd = DrawDibOpen();
  202524. }
  202525. if (createPaletteIfNeeded)
  202526. {
  202527. HDC dc = GetDC (0);
  202528. const int n = GetDeviceCaps (dc, BITSPIXEL);
  202529. ReleaseDC (0, dc);
  202530. if (n <= 8)
  202531. palette = CreateHalftonePalette (dc);
  202532. createPaletteIfNeeded = false;
  202533. }
  202534. if (palette != 0)
  202535. {
  202536. SelectPalette (dc, palette, FALSE);
  202537. RealizePalette (dc);
  202538. SetStretchBltMode (dc, HALFTONE);
  202539. }
  202540. SetMapMode (dc, MM_TEXT);
  202541. if (transparent)
  202542. {
  202543. POINT p, pos;
  202544. SIZE size;
  202545. RECT windowBounds;
  202546. GetWindowRect (hwnd, &windowBounds);
  202547. p.x = -x;
  202548. p.y = -y;
  202549. pos.x = windowBounds.left;
  202550. pos.y = windowBounds.top;
  202551. size.cx = windowBounds.right - windowBounds.left;
  202552. size.cy = windowBounds.bottom - windowBounds.top;
  202553. BLENDFUNCTION bf;
  202554. bf.AlphaFormat = AC_SRC_ALPHA;
  202555. bf.BlendFlags = 0;
  202556. bf.BlendOp = AC_SRC_OVER;
  202557. bf.SourceConstantAlpha = 0xff;
  202558. if (! maskedRegion.isEmpty())
  202559. {
  202560. for (RectangleList::Iterator i (maskedRegion); i.next();)
  202561. {
  202562. const Rectangle<int>& r = *i.getRectangle();
  202563. ExcludeClipRect (hdc, r.getX(), r.getY(), r.getRight(), r.getBottom());
  202564. }
  202565. }
  202566. updateLayeredWindow (hwnd, 0, &pos, &size, hdc, &p, 0, &bf, ULW_ALPHA);
  202567. }
  202568. else
  202569. {
  202570. int savedDC = 0;
  202571. if (! maskedRegion.isEmpty())
  202572. {
  202573. savedDC = SaveDC (dc);
  202574. for (RectangleList::Iterator i (maskedRegion); i.next();)
  202575. {
  202576. const Rectangle<int>& r = *i.getRectangle();
  202577. ExcludeClipRect (dc, r.getX(), r.getY(), r.getRight(), r.getBottom());
  202578. }
  202579. }
  202580. const int w = getWidth();
  202581. const int h = getHeight();
  202582. if (hdd == 0)
  202583. {
  202584. StretchDIBits (dc,
  202585. x, y, w, h,
  202586. 0, 0, w, h,
  202587. bitmapData, (const BITMAPINFO*) &bitmapInfo,
  202588. DIB_RGB_COLORS, SRCCOPY);
  202589. }
  202590. else
  202591. {
  202592. DrawDibDraw (hdd, dc, x, y, -1, -1,
  202593. (BITMAPINFOHEADER*) &bitmapInfo, bitmapData,
  202594. 0, 0, w, h, 0);
  202595. }
  202596. if (! maskedRegion.isEmpty())
  202597. RestoreDC (dc, savedDC);
  202598. }
  202599. }
  202600. juce_UseDebuggingNewOperator
  202601. private:
  202602. WindowsBitmapImage (const WindowsBitmapImage&);
  202603. WindowsBitmapImage& operator= (const WindowsBitmapImage&);
  202604. };
  202605. long improbableWindowNumber = 0xf965aa01; // also referenced by messaging.cpp
  202606. bool KeyPress::isKeyCurrentlyDown (const int keyCode)
  202607. {
  202608. SHORT k = (SHORT) keyCode;
  202609. if ((keyCode & extendedKeyModifier) == 0
  202610. && (k >= (SHORT) 'a' && k <= (SHORT) 'z'))
  202611. k += (SHORT) 'A' - (SHORT) 'a';
  202612. const SHORT translatedValues[] = { (SHORT) ',', VK_OEM_COMMA,
  202613. (SHORT) '+', VK_OEM_PLUS,
  202614. (SHORT) '-', VK_OEM_MINUS,
  202615. (SHORT) '.', VK_OEM_PERIOD,
  202616. (SHORT) ';', VK_OEM_1,
  202617. (SHORT) ':', VK_OEM_1,
  202618. (SHORT) '/', VK_OEM_2,
  202619. (SHORT) '?', VK_OEM_2,
  202620. (SHORT) '[', VK_OEM_4,
  202621. (SHORT) ']', VK_OEM_6 };
  202622. for (int i = 0; i < numElementsInArray (translatedValues); i += 2)
  202623. if (k == translatedValues [i])
  202624. k = translatedValues [i + 1];
  202625. return (GetKeyState (k) & 0x8000) != 0;
  202626. }
  202627. static void* callFunctionIfNotLocked (MessageCallbackFunction* callback, void* userData)
  202628. {
  202629. if (MessageManager::getInstance()->currentThreadHasLockedMessageManager())
  202630. return callback (userData);
  202631. else
  202632. return MessageManager::getInstance()->callFunctionOnMessageThread (callback, userData);
  202633. }
  202634. class Win32ComponentPeer : public ComponentPeer
  202635. {
  202636. public:
  202637. Win32ComponentPeer (Component* const component,
  202638. const int windowStyleFlags)
  202639. : ComponentPeer (component, windowStyleFlags),
  202640. dontRepaint (false),
  202641. fullScreen (false),
  202642. isDragging (false),
  202643. isMouseOver (false),
  202644. hasCreatedCaret (false),
  202645. currentWindowIcon (0),
  202646. taskBarIcon (0),
  202647. dropTarget (0)
  202648. {
  202649. callFunctionIfNotLocked (&createWindowCallback, this);
  202650. setTitle (component->getName());
  202651. if ((windowStyleFlags & windowHasDropShadow) != 0
  202652. && Desktop::canUseSemiTransparentWindows())
  202653. {
  202654. shadower = component->getLookAndFeel().createDropShadowerForComponent (component);
  202655. if (shadower != 0)
  202656. shadower->setOwner (component);
  202657. }
  202658. else
  202659. {
  202660. shadower = 0;
  202661. }
  202662. }
  202663. ~Win32ComponentPeer()
  202664. {
  202665. setTaskBarIcon (0);
  202666. deleteAndZero (shadower);
  202667. // do this before the next bit to avoid messages arriving for this window
  202668. // before it's destroyed
  202669. SetWindowLongPtr (hwnd, GWLP_USERDATA, 0);
  202670. callFunctionIfNotLocked (&destroyWindowCallback, (void*) hwnd);
  202671. if (currentWindowIcon != 0)
  202672. DestroyIcon (currentWindowIcon);
  202673. if (dropTarget != 0)
  202674. {
  202675. dropTarget->Release();
  202676. dropTarget = 0;
  202677. }
  202678. }
  202679. void* getNativeHandle() const
  202680. {
  202681. return hwnd;
  202682. }
  202683. void setVisible (bool shouldBeVisible)
  202684. {
  202685. ShowWindow (hwnd, shouldBeVisible ? SW_SHOWNA : SW_HIDE);
  202686. if (shouldBeVisible)
  202687. InvalidateRect (hwnd, 0, 0);
  202688. else
  202689. lastPaintTime = 0;
  202690. }
  202691. void setTitle (const String& title)
  202692. {
  202693. SetWindowText (hwnd, title);
  202694. }
  202695. void setPosition (int x, int y)
  202696. {
  202697. offsetWithinParent (x, y);
  202698. SetWindowPos (hwnd, 0,
  202699. x - windowBorder.getLeft(),
  202700. y - windowBorder.getTop(),
  202701. 0, 0,
  202702. SWP_NOACTIVATE | SWP_NOSIZE | SWP_NOZORDER | SWP_NOOWNERZORDER);
  202703. }
  202704. void repaintNowIfTransparent()
  202705. {
  202706. if (isTransparent() && lastPaintTime > 0 && Time::getMillisecondCounter() > lastPaintTime + 30)
  202707. handlePaintMessage();
  202708. }
  202709. void updateBorderSize()
  202710. {
  202711. WINDOWINFO info;
  202712. info.cbSize = sizeof (info);
  202713. if (GetWindowInfo (hwnd, &info))
  202714. {
  202715. windowBorder = BorderSize (info.rcClient.top - info.rcWindow.top,
  202716. info.rcClient.left - info.rcWindow.left,
  202717. info.rcWindow.bottom - info.rcClient.bottom,
  202718. info.rcWindow.right - info.rcClient.right);
  202719. }
  202720. }
  202721. void setSize (int w, int h)
  202722. {
  202723. SetWindowPos (hwnd, 0, 0, 0,
  202724. w + windowBorder.getLeftAndRight(),
  202725. h + windowBorder.getTopAndBottom(),
  202726. SWP_NOACTIVATE | SWP_NOMOVE | SWP_NOZORDER | SWP_NOOWNERZORDER);
  202727. updateBorderSize();
  202728. repaintNowIfTransparent();
  202729. }
  202730. void setBounds (int x, int y, int w, int h, bool isNowFullScreen)
  202731. {
  202732. fullScreen = isNowFullScreen;
  202733. offsetWithinParent (x, y);
  202734. SetWindowPos (hwnd, 0,
  202735. x - windowBorder.getLeft(),
  202736. y - windowBorder.getTop(),
  202737. w + windowBorder.getLeftAndRight(),
  202738. h + windowBorder.getTopAndBottom(),
  202739. SWP_NOACTIVATE | SWP_NOZORDER | SWP_NOOWNERZORDER);
  202740. updateBorderSize();
  202741. repaintNowIfTransparent();
  202742. }
  202743. const Rectangle<int> getBounds() const
  202744. {
  202745. RECT r;
  202746. GetWindowRect (hwnd, &r);
  202747. Rectangle<int> bounds (r.left, r.top, r.right - r.left, r.bottom - r.top);
  202748. HWND parentH = GetParent (hwnd);
  202749. if (parentH != 0)
  202750. {
  202751. GetWindowRect (parentH, &r);
  202752. bounds.translate (-r.left, -r.top);
  202753. }
  202754. return windowBorder.subtractedFrom (bounds);
  202755. }
  202756. const Point<int> getScreenPosition() const
  202757. {
  202758. RECT r;
  202759. GetWindowRect (hwnd, &r);
  202760. return Point<int> (r.left + windowBorder.getLeft(),
  202761. r.top + windowBorder.getTop());
  202762. }
  202763. const Point<int> relativePositionToGlobal (const Point<int>& relativePosition)
  202764. {
  202765. return relativePosition + getScreenPosition();
  202766. }
  202767. const Point<int> globalPositionToRelative (const Point<int>& screenPosition)
  202768. {
  202769. return screenPosition - getScreenPosition();
  202770. }
  202771. void setMinimised (bool shouldBeMinimised)
  202772. {
  202773. if (shouldBeMinimised != isMinimised())
  202774. ShowWindow (hwnd, shouldBeMinimised ? SW_MINIMIZE : SW_SHOWNORMAL);
  202775. }
  202776. bool isMinimised() const
  202777. {
  202778. WINDOWPLACEMENT wp;
  202779. wp.length = sizeof (WINDOWPLACEMENT);
  202780. GetWindowPlacement (hwnd, &wp);
  202781. return wp.showCmd == SW_SHOWMINIMIZED;
  202782. }
  202783. void setFullScreen (bool shouldBeFullScreen)
  202784. {
  202785. setMinimised (false);
  202786. if (fullScreen != shouldBeFullScreen)
  202787. {
  202788. fullScreen = shouldBeFullScreen;
  202789. const Component::SafePointer<Component> deletionChecker (component);
  202790. if (! fullScreen)
  202791. {
  202792. const Rectangle<int> boundsCopy (lastNonFullscreenBounds);
  202793. if (hasTitleBar())
  202794. ShowWindow (hwnd, SW_SHOWNORMAL);
  202795. if (! boundsCopy.isEmpty())
  202796. {
  202797. setBounds (boundsCopy.getX(),
  202798. boundsCopy.getY(),
  202799. boundsCopy.getWidth(),
  202800. boundsCopy.getHeight(),
  202801. false);
  202802. }
  202803. }
  202804. else
  202805. {
  202806. if (hasTitleBar())
  202807. ShowWindow (hwnd, SW_SHOWMAXIMIZED);
  202808. else
  202809. SendMessageW (hwnd, WM_SETTINGCHANGE, 0, 0);
  202810. }
  202811. if (deletionChecker != 0)
  202812. handleMovedOrResized();
  202813. }
  202814. }
  202815. bool isFullScreen() const
  202816. {
  202817. if (! hasTitleBar())
  202818. return fullScreen;
  202819. WINDOWPLACEMENT wp;
  202820. wp.length = sizeof (wp);
  202821. GetWindowPlacement (hwnd, &wp);
  202822. return wp.showCmd == SW_SHOWMAXIMIZED;
  202823. }
  202824. bool contains (const Point<int>& position, bool trueIfInAChildWindow) const
  202825. {
  202826. if (((unsigned int) position.getX()) >= (unsigned int) component->getWidth()
  202827. || ((unsigned int) position.getY()) >= (unsigned int) component->getHeight())
  202828. return false;
  202829. RECT r;
  202830. GetWindowRect (hwnd, &r);
  202831. POINT p;
  202832. p.x = position.getX() + r.left + windowBorder.getLeft();
  202833. p.y = position.getY() + r.top + windowBorder.getTop();
  202834. HWND w = WindowFromPoint (p);
  202835. return w == hwnd || (trueIfInAChildWindow && (IsChild (hwnd, w) != 0));
  202836. }
  202837. const BorderSize getFrameSize() const
  202838. {
  202839. return windowBorder;
  202840. }
  202841. bool setAlwaysOnTop (bool alwaysOnTop)
  202842. {
  202843. const bool oldDeactivate = shouldDeactivateTitleBar;
  202844. shouldDeactivateTitleBar = ((styleFlags & windowIsTemporary) == 0);
  202845. SetWindowPos (hwnd, alwaysOnTop ? HWND_TOPMOST : HWND_NOTOPMOST,
  202846. 0, 0, 0, 0,
  202847. SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE | SWP_NOSENDCHANGING);
  202848. shouldDeactivateTitleBar = oldDeactivate;
  202849. if (shadower != 0)
  202850. shadower->componentBroughtToFront (*component);
  202851. return true;
  202852. }
  202853. void toFront (bool makeActive)
  202854. {
  202855. setMinimised (false);
  202856. const bool oldDeactivate = shouldDeactivateTitleBar;
  202857. shouldDeactivateTitleBar = ((styleFlags & windowIsTemporary) == 0);
  202858. callFunctionIfNotLocked (makeActive ? &toFrontCallback1 : &toFrontCallback2, hwnd);
  202859. shouldDeactivateTitleBar = oldDeactivate;
  202860. if (! makeActive)
  202861. {
  202862. // in this case a broughttofront call won't have occured, so do it now..
  202863. handleBroughtToFront();
  202864. }
  202865. }
  202866. void toBehind (ComponentPeer* other)
  202867. {
  202868. Win32ComponentPeer* const otherPeer = dynamic_cast <Win32ComponentPeer*> (other);
  202869. jassert (otherPeer != 0); // wrong type of window?
  202870. if (otherPeer != 0)
  202871. {
  202872. setMinimised (false);
  202873. // must be careful not to try to put a topmost window behind a normal one, or win32
  202874. // promotes the normal one to be topmost!
  202875. if (getComponent()->isAlwaysOnTop() == otherPeer->getComponent()->isAlwaysOnTop())
  202876. SetWindowPos (hwnd, otherPeer->hwnd, 0, 0, 0, 0,
  202877. SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE | SWP_NOSENDCHANGING);
  202878. else if (otherPeer->getComponent()->isAlwaysOnTop())
  202879. SetWindowPos (hwnd, HWND_TOP, 0, 0, 0, 0,
  202880. SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE | SWP_NOSENDCHANGING);
  202881. }
  202882. }
  202883. bool isFocused() const
  202884. {
  202885. return callFunctionIfNotLocked (&getFocusCallback, 0) == (void*) hwnd;
  202886. }
  202887. void grabFocus()
  202888. {
  202889. const bool oldDeactivate = shouldDeactivateTitleBar;
  202890. shouldDeactivateTitleBar = ((styleFlags & windowIsTemporary) == 0);
  202891. callFunctionIfNotLocked (&setFocusCallback, hwnd);
  202892. shouldDeactivateTitleBar = oldDeactivate;
  202893. }
  202894. void textInputRequired (const Point<int>&)
  202895. {
  202896. if (! hasCreatedCaret)
  202897. {
  202898. hasCreatedCaret = true;
  202899. CreateCaret (hwnd, (HBITMAP) 1, 0, 0);
  202900. }
  202901. ShowCaret (hwnd);
  202902. SetCaretPos (0, 0);
  202903. }
  202904. void repaint (int x, int y, int w, int h)
  202905. {
  202906. const RECT r = { x, y, x + w, y + h };
  202907. InvalidateRect (hwnd, &r, FALSE);
  202908. }
  202909. void performAnyPendingRepaintsNow()
  202910. {
  202911. MSG m;
  202912. if (component->isVisible() && PeekMessage (&m, hwnd, WM_PAINT, WM_PAINT, PM_REMOVE))
  202913. DispatchMessage (&m);
  202914. }
  202915. static Win32ComponentPeer* getOwnerOfWindow (HWND h) throw()
  202916. {
  202917. if (h != 0 && GetWindowLongPtr (h, GWLP_USERDATA) == improbableWindowNumber)
  202918. return (Win32ComponentPeer*) (pointer_sized_int) GetWindowLongPtr (h, 8);
  202919. return 0;
  202920. }
  202921. void setTaskBarIcon (const Image* const image)
  202922. {
  202923. if (image != 0)
  202924. {
  202925. HICON hicon = createHICONFromImage (*image, TRUE, 0, 0);
  202926. if (taskBarIcon == 0)
  202927. {
  202928. taskBarIcon = new NOTIFYICONDATA();
  202929. taskBarIcon->cbSize = sizeof (NOTIFYICONDATA);
  202930. taskBarIcon->hWnd = (HWND) hwnd;
  202931. taskBarIcon->uID = (int) (pointer_sized_int) hwnd;
  202932. taskBarIcon->uFlags = NIF_ICON | NIF_MESSAGE | NIF_TIP;
  202933. taskBarIcon->uCallbackMessage = WM_TRAYNOTIFY;
  202934. taskBarIcon->hIcon = hicon;
  202935. taskBarIcon->szTip[0] = 0;
  202936. Shell_NotifyIcon (NIM_ADD, taskBarIcon);
  202937. }
  202938. else
  202939. {
  202940. HICON oldIcon = taskBarIcon->hIcon;
  202941. taskBarIcon->hIcon = hicon;
  202942. taskBarIcon->uFlags = NIF_ICON;
  202943. Shell_NotifyIcon (NIM_MODIFY, taskBarIcon);
  202944. DestroyIcon (oldIcon);
  202945. }
  202946. DestroyIcon (hicon);
  202947. }
  202948. else if (taskBarIcon != 0)
  202949. {
  202950. taskBarIcon->uFlags = 0;
  202951. Shell_NotifyIcon (NIM_DELETE, taskBarIcon);
  202952. DestroyIcon (taskBarIcon->hIcon);
  202953. deleteAndZero (taskBarIcon);
  202954. }
  202955. }
  202956. void setTaskBarIconToolTip (const String& toolTip) const
  202957. {
  202958. if (taskBarIcon != 0)
  202959. {
  202960. taskBarIcon->uFlags = NIF_TIP;
  202961. toolTip.copyToUnicode (taskBarIcon->szTip, sizeof (taskBarIcon->szTip) - 1);
  202962. Shell_NotifyIcon (NIM_MODIFY, taskBarIcon);
  202963. }
  202964. }
  202965. bool isInside (HWND h) const
  202966. {
  202967. return GetAncestor (hwnd, GA_ROOT) == h;
  202968. }
  202969. static void updateKeyModifiers() throw()
  202970. {
  202971. int keyMods = 0;
  202972. if (GetKeyState (VK_SHIFT) & 0x8000) keyMods |= ModifierKeys::shiftModifier;
  202973. if (GetKeyState (VK_CONTROL) & 0x8000) keyMods |= ModifierKeys::ctrlModifier;
  202974. if (GetKeyState (VK_MENU) & 0x8000) keyMods |= ModifierKeys::altModifier;
  202975. if (GetKeyState (VK_RMENU) & 0x8000) keyMods &= ~(ModifierKeys::ctrlModifier | ModifierKeys::altModifier);
  202976. currentModifiers = currentModifiers.withOnlyMouseButtons().withFlags (keyMods);
  202977. }
  202978. static void updateModifiersFromWParam (const WPARAM wParam)
  202979. {
  202980. int mouseMods = 0;
  202981. if (wParam & MK_LBUTTON) mouseMods |= ModifierKeys::leftButtonModifier;
  202982. if (wParam & MK_RBUTTON) mouseMods |= ModifierKeys::rightButtonModifier;
  202983. if (wParam & MK_MBUTTON) mouseMods |= ModifierKeys::middleButtonModifier;
  202984. currentModifiers = currentModifiers.withoutMouseButtons().withFlags (mouseMods);
  202985. updateKeyModifiers();
  202986. }
  202987. static int64 getMouseEventTime()
  202988. {
  202989. static int64 eventTimeOffset = 0;
  202990. static DWORD lastMessageTime = 0;
  202991. const DWORD thisMessageTime = GetMessageTime();
  202992. if (thisMessageTime < lastMessageTime || lastMessageTime == 0)
  202993. {
  202994. lastMessageTime = thisMessageTime;
  202995. eventTimeOffset = Time::currentTimeMillis() - thisMessageTime;
  202996. }
  202997. return eventTimeOffset + thisMessageTime;
  202998. }
  202999. juce_UseDebuggingNewOperator
  203000. bool dontRepaint;
  203001. static ModifierKeys currentModifiers;
  203002. static ModifierKeys modifiersAtLastCallback;
  203003. private:
  203004. HWND hwnd;
  203005. DropShadower* shadower;
  203006. bool fullScreen, isDragging, isMouseOver, hasCreatedCaret;
  203007. BorderSize windowBorder;
  203008. HICON currentWindowIcon;
  203009. NOTIFYICONDATA* taskBarIcon;
  203010. IDropTarget* dropTarget;
  203011. class TemporaryImage : public Timer
  203012. {
  203013. public:
  203014. TemporaryImage() {}
  203015. ~TemporaryImage() {}
  203016. WindowsBitmapImage* getImage (const bool transparent, const int w, const int h) throw()
  203017. {
  203018. const Image::PixelFormat format = transparent ? Image::ARGB : Image::RGB;
  203019. if (image == 0 || image->getWidth() < w || image->getHeight() < h || image->getFormat() != format)
  203020. image = new WindowsBitmapImage (format, (w + 31) & ~31, (h + 31) & ~31, false);
  203021. startTimer (3000);
  203022. return image;
  203023. }
  203024. void timerCallback()
  203025. {
  203026. stopTimer();
  203027. image = 0;
  203028. }
  203029. private:
  203030. ScopedPointer <WindowsBitmapImage> image;
  203031. TemporaryImage (const TemporaryImage&);
  203032. TemporaryImage& operator= (const TemporaryImage&);
  203033. };
  203034. TemporaryImage offscreenImageGenerator;
  203035. class WindowClassHolder : public DeletedAtShutdown
  203036. {
  203037. public:
  203038. WindowClassHolder()
  203039. : windowClassName ("JUCE_")
  203040. {
  203041. // this name has to be different for each app/dll instance because otherwise
  203042. // poor old Win32 can get a bit confused (even despite it not being a process-global
  203043. // window class).
  203044. windowClassName << (int) (Time::currentTimeMillis() & 0x7fffffff);
  203045. HINSTANCE moduleHandle = (HINSTANCE) PlatformUtilities::getCurrentModuleInstanceHandle();
  203046. TCHAR moduleFile [1024];
  203047. moduleFile[0] = 0;
  203048. GetModuleFileName (moduleHandle, moduleFile, 1024);
  203049. WORD iconNum = 0;
  203050. WNDCLASSEX wcex;
  203051. wcex.cbSize = sizeof (wcex);
  203052. wcex.style = CS_OWNDC;
  203053. wcex.lpfnWndProc = (WNDPROC) windowProc;
  203054. wcex.lpszClassName = windowClassName;
  203055. wcex.cbClsExtra = 0;
  203056. wcex.cbWndExtra = 32;
  203057. wcex.hInstance = moduleHandle;
  203058. wcex.hIcon = ExtractAssociatedIcon (moduleHandle, moduleFile, &iconNum);
  203059. iconNum = 1;
  203060. wcex.hIconSm = ExtractAssociatedIcon (moduleHandle, moduleFile, &iconNum);
  203061. wcex.hCursor = 0;
  203062. wcex.hbrBackground = 0;
  203063. wcex.lpszMenuName = 0;
  203064. RegisterClassEx (&wcex);
  203065. }
  203066. ~WindowClassHolder()
  203067. {
  203068. if (ComponentPeer::getNumPeers() == 0)
  203069. UnregisterClass (windowClassName, (HINSTANCE) PlatformUtilities::getCurrentModuleInstanceHandle());
  203070. clearSingletonInstance();
  203071. }
  203072. String windowClassName;
  203073. juce_DeclareSingleton_SingleThreaded_Minimal (WindowClassHolder);
  203074. };
  203075. static void* createWindowCallback (void* userData)
  203076. {
  203077. static_cast <Win32ComponentPeer*> (userData)->createWindow();
  203078. return 0;
  203079. }
  203080. void createWindow()
  203081. {
  203082. DWORD exstyle = WS_EX_ACCEPTFILES;
  203083. DWORD type = WS_CLIPSIBLINGS | WS_CLIPCHILDREN;
  203084. if (hasTitleBar())
  203085. {
  203086. type |= WS_OVERLAPPED;
  203087. exstyle |= WS_EX_APPWINDOW;
  203088. if ((styleFlags & windowHasCloseButton) != 0)
  203089. {
  203090. type |= WS_SYSMENU;
  203091. }
  203092. else
  203093. {
  203094. // annoyingly, windows won't let you have a min/max button without a close button
  203095. jassert ((styleFlags & (windowHasMinimiseButton | windowHasMaximiseButton)) == 0);
  203096. }
  203097. if ((styleFlags & windowIsResizable) != 0)
  203098. type |= WS_THICKFRAME;
  203099. }
  203100. else
  203101. {
  203102. type |= WS_POPUP | WS_SYSMENU;
  203103. if ((styleFlags & windowAppearsOnTaskbar) == 0)
  203104. exstyle |= WS_EX_TOOLWINDOW;
  203105. else
  203106. exstyle |= WS_EX_APPWINDOW;
  203107. }
  203108. if ((styleFlags & windowHasMinimiseButton) != 0)
  203109. type |= WS_MINIMIZEBOX;
  203110. if ((styleFlags & windowHasMaximiseButton) != 0)
  203111. type |= WS_MAXIMIZEBOX;
  203112. if ((styleFlags & windowIgnoresMouseClicks) != 0)
  203113. exstyle |= WS_EX_TRANSPARENT;
  203114. if ((styleFlags & windowIsSemiTransparent) != 0
  203115. && Desktop::canUseSemiTransparentWindows())
  203116. exstyle |= WS_EX_LAYERED;
  203117. hwnd = CreateWindowEx (exstyle, WindowClassHolder::getInstance()->windowClassName, L"", type, 0, 0, 0, 0, 0, 0, 0, 0);
  203118. if (hwnd != 0)
  203119. {
  203120. SetWindowLongPtr (hwnd, 0, 0);
  203121. SetWindowLongPtr (hwnd, 8, (LONG_PTR) this);
  203122. SetWindowLongPtr (hwnd, GWLP_USERDATA, improbableWindowNumber);
  203123. if (dropTarget == 0)
  203124. dropTarget = new JuceDropTarget (this);
  203125. RegisterDragDrop (hwnd, dropTarget);
  203126. updateBorderSize();
  203127. // Calling this function here is (for some reason) necessary to make Windows
  203128. // correctly enable the menu items that we specify in the wm_initmenu message.
  203129. GetSystemMenu (hwnd, false);
  203130. }
  203131. else
  203132. {
  203133. jassertfalse
  203134. }
  203135. }
  203136. static void* destroyWindowCallback (void* handle)
  203137. {
  203138. RevokeDragDrop ((HWND) handle);
  203139. DestroyWindow ((HWND) handle);
  203140. return 0;
  203141. }
  203142. static void* toFrontCallback1 (void* h)
  203143. {
  203144. SetForegroundWindow ((HWND) h);
  203145. return 0;
  203146. }
  203147. static void* toFrontCallback2 (void* h)
  203148. {
  203149. SetWindowPos ((HWND) h, HWND_TOP, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE | SWP_NOSENDCHANGING);
  203150. return 0;
  203151. }
  203152. static void* setFocusCallback (void* h)
  203153. {
  203154. SetFocus ((HWND) h);
  203155. return 0;
  203156. }
  203157. static void* getFocusCallback (void*)
  203158. {
  203159. return GetFocus();
  203160. }
  203161. void offsetWithinParent (int& x, int& y) const
  203162. {
  203163. if (isTransparent())
  203164. {
  203165. HWND parentHwnd = GetParent (hwnd);
  203166. if (parentHwnd != 0)
  203167. {
  203168. RECT parentRect;
  203169. GetWindowRect (parentHwnd, &parentRect);
  203170. x += parentRect.left;
  203171. y += parentRect.top;
  203172. }
  203173. }
  203174. }
  203175. bool isTransparent() const
  203176. {
  203177. return (GetWindowLong (hwnd, GWL_EXSTYLE) & WS_EX_LAYERED) != 0;
  203178. }
  203179. inline bool hasTitleBar() const throw() { return (styleFlags & windowHasTitleBar) != 0; }
  203180. void setIcon (const Image& newIcon)
  203181. {
  203182. HICON hicon = createHICONFromImage (newIcon, TRUE, 0, 0);
  203183. if (hicon != 0)
  203184. {
  203185. SendMessage (hwnd, WM_SETICON, ICON_BIG, (LPARAM) hicon);
  203186. SendMessage (hwnd, WM_SETICON, ICON_SMALL, (LPARAM) hicon);
  203187. if (currentWindowIcon != 0)
  203188. DestroyIcon (currentWindowIcon);
  203189. currentWindowIcon = hicon;
  203190. }
  203191. }
  203192. void handlePaintMessage()
  203193. {
  203194. HRGN rgn = CreateRectRgn (0, 0, 0, 0);
  203195. const int regionType = GetUpdateRgn (hwnd, rgn, false);
  203196. PAINTSTRUCT paintStruct;
  203197. HDC dc = BeginPaint (hwnd, &paintStruct); // Note this can immediately generate a WM_NCPAINT
  203198. // message and become re-entrant, but that's OK
  203199. // if something in a paint handler calls, e.g. a message box, this can become reentrant and
  203200. // corrupt the image it's using to paint into, so do a check here.
  203201. static bool reentrant = false;
  203202. if (reentrant)
  203203. {
  203204. DeleteObject (rgn);
  203205. EndPaint (hwnd, &paintStruct);
  203206. return;
  203207. }
  203208. reentrant = true;
  203209. // this is the rectangle to update..
  203210. int x = paintStruct.rcPaint.left;
  203211. int y = paintStruct.rcPaint.top;
  203212. int w = paintStruct.rcPaint.right - x;
  203213. int h = paintStruct.rcPaint.bottom - y;
  203214. const bool transparent = isTransparent();
  203215. if (transparent)
  203216. {
  203217. // it's not possible to have a transparent window with a title bar at the moment!
  203218. jassert (! hasTitleBar());
  203219. RECT r;
  203220. GetWindowRect (hwnd, &r);
  203221. x = y = 0;
  203222. w = r.right - r.left;
  203223. h = r.bottom - r.top;
  203224. }
  203225. if (w > 0 && h > 0)
  203226. {
  203227. clearMaskedRegion();
  203228. WindowsBitmapImage* const offscreenImage = offscreenImageGenerator.getImage (transparent, w, h);
  203229. RectangleList contextClip;
  203230. const Rectangle<int> clipBounds (0, 0, w, h);
  203231. bool needToPaintAll = true;
  203232. if (regionType == COMPLEXREGION && ! transparent)
  203233. {
  203234. HRGN clipRgn = CreateRectRgnIndirect (&paintStruct.rcPaint);
  203235. CombineRgn (rgn, rgn, clipRgn, RGN_AND);
  203236. DeleteObject (clipRgn);
  203237. char rgnData [8192];
  203238. const DWORD res = GetRegionData (rgn, sizeof (rgnData), (RGNDATA*) rgnData);
  203239. if (res > 0 && res <= sizeof (rgnData))
  203240. {
  203241. const RGNDATAHEADER* const hdr = &(((const RGNDATA*) rgnData)->rdh);
  203242. if (hdr->iType == RDH_RECTANGLES
  203243. && hdr->rcBound.right - hdr->rcBound.left >= w
  203244. && hdr->rcBound.bottom - hdr->rcBound.top >= h)
  203245. {
  203246. needToPaintAll = false;
  203247. const RECT* rects = (const RECT*) (rgnData + sizeof (RGNDATAHEADER));
  203248. int num = ((RGNDATA*) rgnData)->rdh.nCount;
  203249. while (--num >= 0)
  203250. {
  203251. if (rects->right <= x + w && rects->bottom <= y + h)
  203252. {
  203253. // (need to move this one pixel to the left because of a win32 bug)
  203254. const int cx = jmax (x, (int) rects->left - 1);
  203255. contextClip.addWithoutMerging (Rectangle<int> (cx - x, rects->top - y, rects->right - cx, rects->bottom - rects->top)
  203256. .getIntersection (clipBounds));
  203257. }
  203258. else
  203259. {
  203260. needToPaintAll = true;
  203261. break;
  203262. }
  203263. ++rects;
  203264. }
  203265. }
  203266. }
  203267. }
  203268. if (needToPaintAll)
  203269. {
  203270. contextClip.clear();
  203271. contextClip.addWithoutMerging (Rectangle<int> (0, 0, w, h));
  203272. }
  203273. if (transparent)
  203274. {
  203275. RectangleList::Iterator i (contextClip);
  203276. while (i.next())
  203277. offscreenImage->clear (*i.getRectangle());
  203278. }
  203279. // if the component's not opaque, this won't draw properly unless the platform can support this
  203280. jassert (Desktop::canUseSemiTransparentWindows() || component->isOpaque());
  203281. updateCurrentModifiers();
  203282. LowLevelGraphicsSoftwareRenderer context (*offscreenImage, -x, -y, contextClip);
  203283. handlePaint (context);
  203284. if (! dontRepaint)
  203285. offscreenImage->blitToWindow (hwnd, dc, transparent, x, y, maskedRegion);
  203286. }
  203287. DeleteObject (rgn);
  203288. EndPaint (hwnd, &paintStruct);
  203289. reentrant = false;
  203290. #ifndef JUCE_GCC //xxx should add this fn for gcc..
  203291. _fpreset(); // because some graphics cards can unmask FP exceptions
  203292. #endif
  203293. lastPaintTime = Time::getMillisecondCounter();
  203294. }
  203295. void doMouseEvent (const Point<int>& position)
  203296. {
  203297. handleMouseEvent (0, position, currentModifiers, getMouseEventTime());
  203298. }
  203299. void doMouseMove (const Point<int>& position)
  203300. {
  203301. if (! isMouseOver)
  203302. {
  203303. isMouseOver = true;
  203304. updateKeyModifiers();
  203305. TRACKMOUSEEVENT tme;
  203306. tme.cbSize = sizeof (tme);
  203307. tme.dwFlags = TME_LEAVE;
  203308. tme.hwndTrack = hwnd;
  203309. tme.dwHoverTime = 0;
  203310. if (! TrackMouseEvent (&tme))
  203311. jassertfalse;
  203312. Desktop::getInstance().getMainMouseSource().forceMouseCursorUpdate();
  203313. }
  203314. else if (! isDragging)
  203315. {
  203316. if (! contains (position, false))
  203317. return;
  203318. }
  203319. // (Throttling the incoming queue of mouse-events seems to still be required in XP..)
  203320. static uint32 lastMouseTime = 0;
  203321. const uint32 now = Time::getMillisecondCounter();
  203322. const int maxMouseMovesPerSecond = 60;
  203323. if (now > lastMouseTime + 1000 / maxMouseMovesPerSecond)
  203324. {
  203325. lastMouseTime = now;
  203326. doMouseEvent (position);
  203327. }
  203328. }
  203329. void doMouseDown (const Point<int>& position, const WPARAM wParam)
  203330. {
  203331. if (GetCapture() != hwnd)
  203332. SetCapture (hwnd);
  203333. doMouseMove (position);
  203334. updateModifiersFromWParam (wParam);
  203335. isDragging = true;
  203336. doMouseEvent (position);
  203337. }
  203338. void doMouseUp (const Point<int>& position, const WPARAM wParam)
  203339. {
  203340. updateModifiersFromWParam (wParam);
  203341. isDragging = false;
  203342. // release the mouse capture if the user has released all buttons
  203343. if ((wParam & (MK_LBUTTON | MK_RBUTTON | MK_MBUTTON)) == 0 && hwnd == GetCapture())
  203344. ReleaseCapture();
  203345. doMouseEvent (position);
  203346. }
  203347. void doCaptureChanged()
  203348. {
  203349. if (isDragging)
  203350. doMouseUp (getCurrentMousePos(), (WPARAM) 0);
  203351. }
  203352. void doMouseExit()
  203353. {
  203354. isMouseOver = false;
  203355. doMouseEvent (getCurrentMousePos());
  203356. }
  203357. void doMouseWheel (const Point<int>& position, const WPARAM wParam, const bool isVertical)
  203358. {
  203359. updateKeyModifiers();
  203360. const float amount = jlimit (-1000.0f, 1000.0f, 0.75f * (short) HIWORD (wParam));
  203361. handleMouseWheel (0, position, getMouseEventTime(),
  203362. isVertical ? 0.0f : amount,
  203363. isVertical ? amount : 0.0f);
  203364. }
  203365. void sendModifierKeyChangeIfNeeded()
  203366. {
  203367. if (modifiersAtLastCallback != currentModifiers)
  203368. {
  203369. modifiersAtLastCallback = currentModifiers;
  203370. handleModifierKeysChange();
  203371. }
  203372. }
  203373. bool doKeyUp (const WPARAM key)
  203374. {
  203375. updateKeyModifiers();
  203376. switch (key)
  203377. {
  203378. case VK_SHIFT:
  203379. case VK_CONTROL:
  203380. case VK_MENU:
  203381. case VK_CAPITAL:
  203382. case VK_LWIN:
  203383. case VK_RWIN:
  203384. case VK_APPS:
  203385. case VK_NUMLOCK:
  203386. case VK_SCROLL:
  203387. case VK_LSHIFT:
  203388. case VK_RSHIFT:
  203389. case VK_LCONTROL:
  203390. case VK_LMENU:
  203391. case VK_RCONTROL:
  203392. case VK_RMENU:
  203393. sendModifierKeyChangeIfNeeded();
  203394. }
  203395. return handleKeyUpOrDown (false)
  203396. || Component::getCurrentlyModalComponent() != 0;
  203397. }
  203398. bool doKeyDown (const WPARAM key)
  203399. {
  203400. updateKeyModifiers();
  203401. bool used = false;
  203402. switch (key)
  203403. {
  203404. case VK_SHIFT:
  203405. case VK_LSHIFT:
  203406. case VK_RSHIFT:
  203407. case VK_CONTROL:
  203408. case VK_LCONTROL:
  203409. case VK_RCONTROL:
  203410. case VK_MENU:
  203411. case VK_LMENU:
  203412. case VK_RMENU:
  203413. case VK_LWIN:
  203414. case VK_RWIN:
  203415. case VK_CAPITAL:
  203416. case VK_NUMLOCK:
  203417. case VK_SCROLL:
  203418. case VK_APPS:
  203419. sendModifierKeyChangeIfNeeded();
  203420. break;
  203421. case VK_LEFT:
  203422. case VK_RIGHT:
  203423. case VK_UP:
  203424. case VK_DOWN:
  203425. case VK_PRIOR:
  203426. case VK_NEXT:
  203427. case VK_HOME:
  203428. case VK_END:
  203429. case VK_DELETE:
  203430. case VK_INSERT:
  203431. case VK_F1:
  203432. case VK_F2:
  203433. case VK_F3:
  203434. case VK_F4:
  203435. case VK_F5:
  203436. case VK_F6:
  203437. case VK_F7:
  203438. case VK_F8:
  203439. case VK_F9:
  203440. case VK_F10:
  203441. case VK_F11:
  203442. case VK_F12:
  203443. case VK_F13:
  203444. case VK_F14:
  203445. case VK_F15:
  203446. case VK_F16:
  203447. used = handleKeyUpOrDown (true);
  203448. used = handleKeyPress (extendedKeyModifier | (int) key, 0) || used;
  203449. break;
  203450. case VK_ADD:
  203451. case VK_SUBTRACT:
  203452. case VK_MULTIPLY:
  203453. case VK_DIVIDE:
  203454. case VK_SEPARATOR:
  203455. case VK_DECIMAL:
  203456. used = handleKeyUpOrDown (true);
  203457. break;
  203458. default:
  203459. used = handleKeyUpOrDown (true);
  203460. {
  203461. MSG msg;
  203462. if (! PeekMessage (&msg, hwnd, WM_CHAR, WM_DEADCHAR, PM_NOREMOVE))
  203463. {
  203464. // if there isn't a WM_CHAR or WM_DEADCHAR message pending, we need to
  203465. // manually generate the key-press event that matches this key-down.
  203466. const UINT keyChar = MapVirtualKey (key, 2);
  203467. used = handleKeyPress ((int) LOWORD (keyChar), 0) || used;
  203468. }
  203469. }
  203470. break;
  203471. }
  203472. if (Component::getCurrentlyModalComponent() != 0)
  203473. used = true;
  203474. return used;
  203475. }
  203476. bool doKeyChar (int key, const LPARAM flags)
  203477. {
  203478. updateKeyModifiers();
  203479. juce_wchar textChar = (juce_wchar) key;
  203480. const int virtualScanCode = (flags >> 16) & 0xff;
  203481. if (key >= '0' && key <= '9')
  203482. {
  203483. switch (virtualScanCode) // check for a numeric keypad scan-code
  203484. {
  203485. case 0x52:
  203486. case 0x4f:
  203487. case 0x50:
  203488. case 0x51:
  203489. case 0x4b:
  203490. case 0x4c:
  203491. case 0x4d:
  203492. case 0x47:
  203493. case 0x48:
  203494. case 0x49:
  203495. key = (key - '0') + KeyPress::numberPad0;
  203496. break;
  203497. default:
  203498. break;
  203499. }
  203500. }
  203501. else
  203502. {
  203503. // convert the scan code to an unmodified character code..
  203504. const UINT virtualKey = MapVirtualKey (virtualScanCode, 1);
  203505. UINT keyChar = MapVirtualKey (virtualKey, 2);
  203506. keyChar = LOWORD (keyChar);
  203507. if (keyChar != 0)
  203508. key = (int) keyChar;
  203509. // avoid sending junk text characters for some control-key combinations
  203510. if (textChar < ' ' && currentModifiers.testFlags (ModifierKeys::ctrlModifier | ModifierKeys::altModifier))
  203511. textChar = 0;
  203512. }
  203513. return handleKeyPress (key, textChar);
  203514. }
  203515. bool doAppCommand (const LPARAM lParam)
  203516. {
  203517. int key = 0;
  203518. switch (GET_APPCOMMAND_LPARAM (lParam))
  203519. {
  203520. case APPCOMMAND_MEDIA_PLAY_PAUSE:
  203521. key = KeyPress::playKey;
  203522. break;
  203523. case APPCOMMAND_MEDIA_STOP:
  203524. key = KeyPress::stopKey;
  203525. break;
  203526. case APPCOMMAND_MEDIA_NEXTTRACK:
  203527. key = KeyPress::fastForwardKey;
  203528. break;
  203529. case APPCOMMAND_MEDIA_PREVIOUSTRACK:
  203530. key = KeyPress::rewindKey;
  203531. break;
  203532. }
  203533. if (key != 0)
  203534. {
  203535. updateKeyModifiers();
  203536. if (hwnd == GetActiveWindow())
  203537. {
  203538. handleKeyPress (key, 0);
  203539. return true;
  203540. }
  203541. }
  203542. return false;
  203543. }
  203544. class JuceDropTarget : public ComBaseClassHelper <IDropTarget>
  203545. {
  203546. public:
  203547. JuceDropTarget (Win32ComponentPeer* const owner_)
  203548. : owner (owner_)
  203549. {
  203550. }
  203551. ~JuceDropTarget() {}
  203552. HRESULT __stdcall DragEnter (IDataObject* pDataObject, DWORD /*grfKeyState*/, POINTL mousePos, DWORD* pdwEffect)
  203553. {
  203554. updateFileList (pDataObject);
  203555. owner->handleFileDragMove (files, owner->globalPositionToRelative (Point<int> (mousePos.x, mousePos.y)));
  203556. *pdwEffect = DROPEFFECT_COPY;
  203557. return S_OK;
  203558. }
  203559. HRESULT __stdcall DragLeave()
  203560. {
  203561. owner->handleFileDragExit (files);
  203562. return S_OK;
  203563. }
  203564. HRESULT __stdcall DragOver (DWORD /*grfKeyState*/, POINTL mousePos, DWORD* pdwEffect)
  203565. {
  203566. owner->handleFileDragMove (files, owner->globalPositionToRelative (Point<int> (mousePos.x, mousePos.y)));
  203567. *pdwEffect = DROPEFFECT_COPY;
  203568. return S_OK;
  203569. }
  203570. HRESULT __stdcall Drop (IDataObject* pDataObject, DWORD /*grfKeyState*/, POINTL mousePos, DWORD* pdwEffect)
  203571. {
  203572. updateFileList (pDataObject);
  203573. owner->handleFileDragDrop (files, owner->globalPositionToRelative (Point<int> (mousePos.x, mousePos.y)));
  203574. *pdwEffect = DROPEFFECT_COPY;
  203575. return S_OK;
  203576. }
  203577. private:
  203578. Win32ComponentPeer* const owner;
  203579. StringArray files;
  203580. void updateFileList (IDataObject* const pDataObject)
  203581. {
  203582. files.clear();
  203583. FORMATETC format = { CF_HDROP, 0, DVASPECT_CONTENT, -1, TYMED_HGLOBAL };
  203584. STGMEDIUM medium = { TYMED_HGLOBAL, { 0 }, 0 };
  203585. if (pDataObject->GetData (&format, &medium) == S_OK)
  203586. {
  203587. const SIZE_T totalLen = GlobalSize (medium.hGlobal);
  203588. const LPDROPFILES pDropFiles = (const LPDROPFILES) GlobalLock (medium.hGlobal);
  203589. unsigned int i = 0;
  203590. if (pDropFiles->fWide)
  203591. {
  203592. const WCHAR* const fname = (WCHAR*) (((const char*) pDropFiles) + sizeof (DROPFILES));
  203593. for (;;)
  203594. {
  203595. unsigned int len = 0;
  203596. while (i + len < totalLen && fname [i + len] != 0)
  203597. ++len;
  203598. if (len == 0)
  203599. break;
  203600. files.add (String (fname + i, len));
  203601. i += len + 1;
  203602. }
  203603. }
  203604. else
  203605. {
  203606. const char* const fname = ((const char*) pDropFiles) + sizeof (DROPFILES);
  203607. for (;;)
  203608. {
  203609. unsigned int len = 0;
  203610. while (i + len < totalLen && fname [i + len] != 0)
  203611. ++len;
  203612. if (len == 0)
  203613. break;
  203614. files.add (String (fname + i, len));
  203615. i += len + 1;
  203616. }
  203617. }
  203618. GlobalUnlock (medium.hGlobal);
  203619. }
  203620. }
  203621. JuceDropTarget (const JuceDropTarget&);
  203622. JuceDropTarget& operator= (const JuceDropTarget&);
  203623. };
  203624. void doSettingChange()
  203625. {
  203626. Desktop::getInstance().refreshMonitorSizes();
  203627. if (fullScreen && ! isMinimised())
  203628. {
  203629. const Rectangle<int> r (component->getParentMonitorArea());
  203630. SetWindowPos (hwnd, 0,
  203631. r.getX(), r.getY(), r.getWidth(), r.getHeight(),
  203632. SWP_NOACTIVATE | SWP_NOOWNERZORDER | SWP_NOZORDER | SWP_NOSENDCHANGING);
  203633. }
  203634. }
  203635. public:
  203636. static LRESULT CALLBACK windowProc (HWND h, UINT message, WPARAM wParam, LPARAM lParam)
  203637. {
  203638. Win32ComponentPeer* const peer = getOwnerOfWindow (h);
  203639. if (peer != 0)
  203640. return peer->peerWindowProc (h, message, wParam, lParam);
  203641. return DefWindowProcW (h, message, wParam, lParam);
  203642. }
  203643. private:
  203644. static const Point<int> getPointFromLParam (LPARAM lParam) throw()
  203645. {
  203646. return Point<int> (GET_X_LPARAM (lParam), GET_Y_LPARAM (lParam));
  203647. }
  203648. const Point<int> getCurrentMousePos() throw()
  203649. {
  203650. RECT wr;
  203651. GetWindowRect (hwnd, &wr);
  203652. const DWORD mp = GetMessagePos();
  203653. return Point<int> (GET_X_LPARAM (mp) - wr.left - windowBorder.getLeft(),
  203654. GET_Y_LPARAM (mp) - wr.top - windowBorder.getTop());
  203655. }
  203656. LRESULT peerWindowProc (HWND h, UINT message, WPARAM wParam, LPARAM lParam)
  203657. {
  203658. if (isValidPeer (this))
  203659. {
  203660. switch (message)
  203661. {
  203662. case WM_NCHITTEST:
  203663. if ((styleFlags & windowIgnoresMouseClicks) != 0)
  203664. return HTTRANSPARENT;
  203665. if (hasTitleBar())
  203666. break;
  203667. return HTCLIENT;
  203668. case WM_PAINT:
  203669. handlePaintMessage();
  203670. return 0;
  203671. case WM_NCPAINT:
  203672. if (wParam != 1)
  203673. handlePaintMessage();
  203674. if (hasTitleBar())
  203675. break;
  203676. return 0;
  203677. case WM_ERASEBKGND:
  203678. case WM_NCCALCSIZE:
  203679. if (hasTitleBar())
  203680. break;
  203681. return 1;
  203682. case WM_MOUSEMOVE:
  203683. doMouseMove (getPointFromLParam (lParam));
  203684. return 0;
  203685. case WM_MOUSELEAVE:
  203686. doMouseExit();
  203687. return 0;
  203688. case WM_LBUTTONDOWN:
  203689. case WM_MBUTTONDOWN:
  203690. case WM_RBUTTONDOWN:
  203691. doMouseDown (getPointFromLParam (lParam), wParam);
  203692. return 0;
  203693. case WM_LBUTTONUP:
  203694. case WM_MBUTTONUP:
  203695. case WM_RBUTTONUP:
  203696. doMouseUp (getPointFromLParam (lParam), wParam);
  203697. return 0;
  203698. case WM_CAPTURECHANGED:
  203699. doCaptureChanged();
  203700. return 0;
  203701. case WM_NCMOUSEMOVE:
  203702. if (hasTitleBar())
  203703. break;
  203704. return 0;
  203705. case 0x020A: /* WM_MOUSEWHEEL */
  203706. doMouseWheel (getCurrentMousePos(), wParam, true);
  203707. return 0;
  203708. case 0x020E: /* WM_MOUSEHWHEEL */
  203709. doMouseWheel (getCurrentMousePos(), wParam, false);
  203710. return 0;
  203711. case WM_WINDOWPOSCHANGING:
  203712. if ((styleFlags & (windowHasTitleBar | windowIsResizable)) == (windowHasTitleBar | windowIsResizable))
  203713. {
  203714. WINDOWPOS* const wp = (WINDOWPOS*) lParam;
  203715. if ((wp->flags & (SWP_NOMOVE | SWP_NOSIZE)) != (SWP_NOMOVE | SWP_NOSIZE))
  203716. {
  203717. if (constrainer != 0)
  203718. {
  203719. const Rectangle<int> current (component->getX() - windowBorder.getLeft(),
  203720. component->getY() - windowBorder.getTop(),
  203721. component->getWidth() + windowBorder.getLeftAndRight(),
  203722. component->getHeight() + windowBorder.getTopAndBottom());
  203723. Rectangle<int> pos (wp->x, wp->y, wp->cx, wp->cy);
  203724. constrainer->checkBounds (pos, current,
  203725. Desktop::getInstance().getAllMonitorDisplayAreas().getBounds(),
  203726. pos.getY() != current.getY() && pos.getBottom() == current.getBottom(),
  203727. pos.getX() != current.getX() && pos.getRight() == current.getRight(),
  203728. pos.getY() == current.getY() && pos.getBottom() != current.getBottom(),
  203729. pos.getX() == current.getX() && pos.getRight() != current.getRight());
  203730. wp->x = pos.getX();
  203731. wp->y = pos.getY();
  203732. wp->cx = pos.getWidth();
  203733. wp->cy = pos.getHeight();
  203734. }
  203735. }
  203736. }
  203737. return 0;
  203738. case WM_WINDOWPOSCHANGED:
  203739. handleMovedOrResized();
  203740. if (dontRepaint)
  203741. break; // needed for non-accelerated openGL windows to draw themselves correctly..
  203742. return 0;
  203743. case WM_KEYDOWN:
  203744. case WM_SYSKEYDOWN:
  203745. if (doKeyDown (wParam))
  203746. return 0;
  203747. break;
  203748. case WM_KEYUP:
  203749. case WM_SYSKEYUP:
  203750. if (doKeyUp (wParam))
  203751. return 0;
  203752. break;
  203753. case WM_CHAR:
  203754. if (doKeyChar ((int) wParam, lParam))
  203755. return 0;
  203756. break;
  203757. case WM_APPCOMMAND:
  203758. if (doAppCommand (lParam))
  203759. return TRUE;
  203760. break;
  203761. case WM_SETFOCUS:
  203762. updateKeyModifiers();
  203763. handleFocusGain();
  203764. break;
  203765. case WM_KILLFOCUS:
  203766. if (hasCreatedCaret)
  203767. {
  203768. hasCreatedCaret = false;
  203769. DestroyCaret();
  203770. }
  203771. handleFocusLoss();
  203772. break;
  203773. case WM_ACTIVATEAPP:
  203774. // Windows does weird things to process priority when you swap apps,
  203775. // so this forces an update when the app is brought to the front
  203776. if (wParam != FALSE)
  203777. juce_repeatLastProcessPriority();
  203778. else
  203779. Desktop::getInstance().setKioskModeComponent (0); // turn kiosk mode off if we lose focus
  203780. juce_CheckCurrentlyFocusedTopLevelWindow();
  203781. modifiersAtLastCallback = -1;
  203782. return 0;
  203783. case WM_ACTIVATE:
  203784. if (LOWORD (wParam) == WA_ACTIVE || LOWORD (wParam) == WA_CLICKACTIVE)
  203785. {
  203786. modifiersAtLastCallback = -1;
  203787. updateKeyModifiers();
  203788. if (isMinimised())
  203789. {
  203790. component->repaint();
  203791. handleMovedOrResized();
  203792. if (! ComponentPeer::isValidPeer (this))
  203793. return 0;
  203794. }
  203795. if (LOWORD (wParam) == WA_CLICKACTIVE
  203796. && component->isCurrentlyBlockedByAnotherModalComponent())
  203797. {
  203798. const Point<int> mousePos (component->getMouseXYRelative());
  203799. Component* const underMouse = component->getComponentAt (mousePos.getX(), mousePos.getY());
  203800. if (underMouse != 0 && underMouse->isCurrentlyBlockedByAnotherModalComponent())
  203801. Component::getCurrentlyModalComponent()->inputAttemptWhenModal();
  203802. return 0;
  203803. }
  203804. handleBroughtToFront();
  203805. if (component->isCurrentlyBlockedByAnotherModalComponent())
  203806. Component::getCurrentlyModalComponent()->toFront (true);
  203807. return 0;
  203808. }
  203809. break;
  203810. case WM_NCACTIVATE:
  203811. // while a temporary window is being shown, prevent Windows from deactivating the
  203812. // title bars of our main windows.
  203813. if (wParam == 0 && ! shouldDeactivateTitleBar)
  203814. wParam = TRUE; // change this and let it get passed to the DefWindowProc.
  203815. break;
  203816. case WM_MOUSEACTIVATE:
  203817. if (! component->getMouseClickGrabsKeyboardFocus())
  203818. return MA_NOACTIVATE;
  203819. break;
  203820. case WM_SHOWWINDOW:
  203821. if (wParam != 0)
  203822. handleBroughtToFront();
  203823. break;
  203824. case WM_CLOSE:
  203825. if (! component->isCurrentlyBlockedByAnotherModalComponent())
  203826. handleUserClosingWindow();
  203827. return 0;
  203828. case WM_QUERYENDSESSION:
  203829. if (JUCEApplication::getInstance() != 0)
  203830. {
  203831. JUCEApplication::getInstance()->systemRequestedQuit();
  203832. return MessageManager::getInstance()->hasStopMessageBeenSent();
  203833. }
  203834. return TRUE;
  203835. case WM_TRAYNOTIFY:
  203836. if (component->isCurrentlyBlockedByAnotherModalComponent())
  203837. {
  203838. if (lParam == WM_LBUTTONDOWN || lParam == WM_RBUTTONDOWN
  203839. || lParam == WM_LBUTTONDBLCLK || lParam == WM_LBUTTONDBLCLK)
  203840. {
  203841. Component* const current = Component::getCurrentlyModalComponent();
  203842. if (current != 0)
  203843. current->inputAttemptWhenModal();
  203844. }
  203845. }
  203846. else
  203847. {
  203848. ModifierKeys eventMods (ModifierKeys::getCurrentModifiersRealtime());
  203849. if (lParam == WM_LBUTTONDOWN || lParam == WM_LBUTTONDBLCLK)
  203850. eventMods = eventMods.withFlags (ModifierKeys::leftButtonModifier);
  203851. else if (lParam == WM_RBUTTONDOWN || lParam == WM_RBUTTONDBLCLK)
  203852. eventMods = eventMods.withFlags (ModifierKeys::rightButtonModifier);
  203853. else if (lParam == WM_LBUTTONUP || lParam == WM_RBUTTONUP)
  203854. eventMods = eventMods.withoutMouseButtons();
  203855. const MouseEvent e (Desktop::getInstance().getMainMouseSource(),
  203856. Point<int>(), eventMods, component, getMouseEventTime(),
  203857. Point<int>(), getMouseEventTime(), 1, false);
  203858. if (lParam == WM_LBUTTONDOWN || lParam == WM_RBUTTONDOWN)
  203859. {
  203860. SetFocus (hwnd);
  203861. SetForegroundWindow (hwnd);
  203862. component->mouseDown (e);
  203863. }
  203864. else if (lParam == WM_LBUTTONUP || lParam == WM_RBUTTONUP)
  203865. {
  203866. component->mouseUp (e);
  203867. }
  203868. else if (lParam == WM_LBUTTONDBLCLK || lParam == WM_LBUTTONDBLCLK)
  203869. {
  203870. component->mouseDoubleClick (e);
  203871. }
  203872. else if (lParam == WM_MOUSEMOVE)
  203873. {
  203874. component->mouseMove (e);
  203875. }
  203876. }
  203877. break;
  203878. case WM_SYNCPAINT:
  203879. return 0;
  203880. case WM_PALETTECHANGED:
  203881. InvalidateRect (h, 0, 0);
  203882. break;
  203883. case WM_DISPLAYCHANGE:
  203884. InvalidateRect (h, 0, 0);
  203885. createPaletteIfNeeded = true;
  203886. // intentional fall-through...
  203887. case WM_SETTINGCHANGE: // note the fall-through in the previous case!
  203888. doSettingChange();
  203889. break;
  203890. case WM_INITMENU:
  203891. if (! hasTitleBar())
  203892. {
  203893. if (isFullScreen())
  203894. {
  203895. EnableMenuItem ((HMENU) wParam, SC_RESTORE, MF_BYCOMMAND | MF_ENABLED);
  203896. EnableMenuItem ((HMENU) wParam, SC_MOVE, MF_BYCOMMAND | MF_GRAYED);
  203897. }
  203898. else if (! isMinimised())
  203899. {
  203900. EnableMenuItem ((HMENU) wParam, SC_MAXIMIZE, MF_BYCOMMAND | MF_GRAYED);
  203901. }
  203902. }
  203903. break;
  203904. case WM_SYSCOMMAND:
  203905. switch (wParam & 0xfff0)
  203906. {
  203907. case SC_CLOSE:
  203908. if (sendInputAttemptWhenModalMessage())
  203909. return 0;
  203910. if (hasTitleBar())
  203911. {
  203912. PostMessage (h, WM_CLOSE, 0, 0);
  203913. return 0;
  203914. }
  203915. break;
  203916. case SC_KEYMENU:
  203917. // (NB mustn't call sendInputAttemptWhenModalMessage() here because of very
  203918. // obscure situations that can arise if a modal loop is started from an alt-key
  203919. // keypress).
  203920. if (hasTitleBar() && h == GetCapture())
  203921. ReleaseCapture();
  203922. break;
  203923. case SC_MAXIMIZE:
  203924. if (sendInputAttemptWhenModalMessage())
  203925. return 0;
  203926. setFullScreen (true);
  203927. return 0;
  203928. case SC_MINIMIZE:
  203929. if (sendInputAttemptWhenModalMessage())
  203930. return 0;
  203931. if (! hasTitleBar())
  203932. {
  203933. setMinimised (true);
  203934. return 0;
  203935. }
  203936. break;
  203937. case SC_RESTORE:
  203938. if (sendInputAttemptWhenModalMessage())
  203939. return 0;
  203940. if (hasTitleBar())
  203941. {
  203942. if (isFullScreen())
  203943. {
  203944. setFullScreen (false);
  203945. return 0;
  203946. }
  203947. }
  203948. else
  203949. {
  203950. if (isMinimised())
  203951. setMinimised (false);
  203952. else if (isFullScreen())
  203953. setFullScreen (false);
  203954. return 0;
  203955. }
  203956. break;
  203957. }
  203958. break;
  203959. case WM_NCLBUTTONDOWN:
  203960. case WM_NCRBUTTONDOWN:
  203961. case WM_NCMBUTTONDOWN:
  203962. sendInputAttemptWhenModalMessage();
  203963. break;
  203964. //case WM_IME_STARTCOMPOSITION;
  203965. // return 0;
  203966. case WM_GETDLGCODE:
  203967. return DLGC_WANTALLKEYS;
  203968. default:
  203969. break;
  203970. }
  203971. }
  203972. return DefWindowProcW (h, message, wParam, lParam);
  203973. }
  203974. bool sendInputAttemptWhenModalMessage()
  203975. {
  203976. if (component->isCurrentlyBlockedByAnotherModalComponent())
  203977. {
  203978. Component* const current = Component::getCurrentlyModalComponent();
  203979. if (current != 0)
  203980. current->inputAttemptWhenModal();
  203981. return true;
  203982. }
  203983. return false;
  203984. }
  203985. Win32ComponentPeer (const Win32ComponentPeer&);
  203986. Win32ComponentPeer& operator= (const Win32ComponentPeer&);
  203987. };
  203988. ModifierKeys Win32ComponentPeer::currentModifiers;
  203989. ModifierKeys Win32ComponentPeer::modifiersAtLastCallback;
  203990. ComponentPeer* Component::createNewPeer (int styleFlags, void* /*nativeWindowToAttachTo*/)
  203991. {
  203992. return new Win32ComponentPeer (this, styleFlags);
  203993. }
  203994. juce_ImplementSingleton_SingleThreaded (Win32ComponentPeer::WindowClassHolder);
  203995. void ModifierKeys::updateCurrentModifiers() throw()
  203996. {
  203997. currentModifiers = Win32ComponentPeer::currentModifiers;
  203998. }
  203999. const ModifierKeys ModifierKeys::getCurrentModifiersRealtime() throw()
  204000. {
  204001. Win32ComponentPeer::updateKeyModifiers();
  204002. int keyMods = 0;
  204003. if ((GetKeyState (VK_LBUTTON) & 0x8000) != 0) keyMods |= ModifierKeys::leftButtonModifier;
  204004. if ((GetKeyState (VK_RBUTTON) & 0x8000) != 0) keyMods |= ModifierKeys::rightButtonModifier;
  204005. if ((GetKeyState (VK_MBUTTON) & 0x8000) != 0) keyMods |= ModifierKeys::middleButtonModifier;
  204006. Win32ComponentPeer::currentModifiers
  204007. = Win32ComponentPeer::currentModifiers.withOnlyMouseButtons().withFlags (keyMods);
  204008. return Win32ComponentPeer::currentModifiers;
  204009. }
  204010. void SystemTrayIconComponent::setIconImage (const Image& newImage)
  204011. {
  204012. Win32ComponentPeer* const wp = dynamic_cast <Win32ComponentPeer*> (getPeer());
  204013. if (wp != 0)
  204014. wp->setTaskBarIcon (&newImage);
  204015. }
  204016. void SystemTrayIconComponent::setIconTooltip (const String& tooltip)
  204017. {
  204018. Win32ComponentPeer* const wp = dynamic_cast <Win32ComponentPeer*> (getPeer());
  204019. if (wp != 0)
  204020. wp->setTaskBarIconToolTip (tooltip);
  204021. }
  204022. void juce_setWindowStyleBit (HWND h, const int styleType, const int feature, const bool bitIsSet) throw()
  204023. {
  204024. DWORD val = GetWindowLong (h, styleType);
  204025. if (bitIsSet)
  204026. val |= feature;
  204027. else
  204028. val &= ~feature;
  204029. SetWindowLongPtr (h, styleType, val);
  204030. SetWindowPos (h, 0, 0, 0, 0, 0,
  204031. SWP_NOACTIVATE | SWP_NOMOVE | SWP_NOSIZE | SWP_NOZORDER
  204032. | SWP_NOOWNERZORDER | SWP_FRAMECHANGED | SWP_NOSENDCHANGING);
  204033. }
  204034. bool Process::isForegroundProcess()
  204035. {
  204036. HWND fg = GetForegroundWindow();
  204037. if (fg == 0)
  204038. return true;
  204039. // when running as a plugin in IE8, the browser UI runs in a different process to the plugin, so
  204040. // process ID isn't a reliable way to check if the foreground window belongs to us - instead, we
  204041. // have to see if any of our windows are children of the foreground window
  204042. fg = GetAncestor (fg, GA_ROOT);
  204043. for (int i = ComponentPeer::getNumPeers(); --i >= 0;)
  204044. {
  204045. Win32ComponentPeer* const wp = dynamic_cast <Win32ComponentPeer*> (ComponentPeer::getPeer (i));
  204046. if (wp != 0 && wp->isInside (fg))
  204047. return true;
  204048. }
  204049. return false;
  204050. }
  204051. bool AlertWindow::showNativeDialogBox (const String& title,
  204052. const String& bodyText,
  204053. bool isOkCancel)
  204054. {
  204055. return MessageBox (0, bodyText, title,
  204056. MB_SETFOREGROUND | (isOkCancel ? MB_OKCANCEL
  204057. : MB_OK)) == IDOK;
  204058. }
  204059. void Desktop::createMouseInputSources()
  204060. {
  204061. mouseSources.add (new MouseInputSource (0, true));
  204062. }
  204063. const Point<int> Desktop::getMousePosition()
  204064. {
  204065. POINT mousePos;
  204066. GetCursorPos (&mousePos);
  204067. return Point<int> (mousePos.x, mousePos.y);
  204068. }
  204069. void Desktop::setMousePosition (const Point<int>& newPosition)
  204070. {
  204071. SetCursorPos (newPosition.getX(), newPosition.getY());
  204072. }
  204073. Image* Image::createNativeImage (const PixelFormat format, const int imageWidth, const int imageHeight, const bool clearImage)
  204074. {
  204075. return new Image (format, imageWidth, imageHeight, clearImage);
  204076. }
  204077. class ScreenSaverDefeater : public Timer,
  204078. public DeletedAtShutdown
  204079. {
  204080. public:
  204081. ScreenSaverDefeater() throw()
  204082. {
  204083. startTimer (10000);
  204084. timerCallback();
  204085. }
  204086. ~ScreenSaverDefeater() {}
  204087. void timerCallback()
  204088. {
  204089. if (Process::isForegroundProcess())
  204090. {
  204091. // simulate a shift key getting pressed..
  204092. INPUT input[2];
  204093. input[0].type = INPUT_KEYBOARD;
  204094. input[0].ki.wVk = VK_SHIFT;
  204095. input[0].ki.dwFlags = 0;
  204096. input[0].ki.dwExtraInfo = 0;
  204097. input[1].type = INPUT_KEYBOARD;
  204098. input[1].ki.wVk = VK_SHIFT;
  204099. input[1].ki.dwFlags = KEYEVENTF_KEYUP;
  204100. input[1].ki.dwExtraInfo = 0;
  204101. SendInput (2, input, sizeof (INPUT));
  204102. }
  204103. }
  204104. };
  204105. static ScreenSaverDefeater* screenSaverDefeater = 0;
  204106. void Desktop::setScreenSaverEnabled (const bool isEnabled) throw()
  204107. {
  204108. if (isEnabled)
  204109. {
  204110. deleteAndZero (screenSaverDefeater);
  204111. }
  204112. else if (screenSaverDefeater == 0)
  204113. {
  204114. screenSaverDefeater = new ScreenSaverDefeater();
  204115. }
  204116. }
  204117. bool Desktop::isScreenSaverEnabled() throw()
  204118. {
  204119. return screenSaverDefeater == 0;
  204120. }
  204121. /* (The code below is the "correct" way to disable the screen saver, but it
  204122. completely fails on winXP when the saver is password-protected...)
  204123. static bool juce_screenSaverEnabled = true;
  204124. void Desktop::setScreenSaverEnabled (const bool isEnabled) throw()
  204125. {
  204126. juce_screenSaverEnabled = isEnabled;
  204127. SetThreadExecutionState (isEnabled ? ES_CONTINUOUS
  204128. : (ES_DISPLAY_REQUIRED | ES_CONTINUOUS));
  204129. }
  204130. bool Desktop::isScreenSaverEnabled() throw()
  204131. {
  204132. return juce_screenSaverEnabled;
  204133. }
  204134. */
  204135. void juce_setKioskComponent (Component* kioskModeComponent, bool enableOrDisable, bool /*allowMenusAndBars*/)
  204136. {
  204137. if (enableOrDisable)
  204138. kioskModeComponent->setBounds (Desktop::getInstance().getMainMonitorArea (false));
  204139. }
  204140. static BOOL CALLBACK enumMonitorsProc (HMONITOR, HDC, LPRECT r, LPARAM userInfo)
  204141. {
  204142. Array <Rectangle<int> >* const monitorCoords = (Array <Rectangle<int> >*) userInfo;
  204143. monitorCoords->add (Rectangle<int> (r->left, r->top, r->right - r->left, r->bottom - r->top));
  204144. return TRUE;
  204145. }
  204146. void juce_updateMultiMonitorInfo (Array <Rectangle<int> >& monitorCoords, const bool clipToWorkArea)
  204147. {
  204148. EnumDisplayMonitors (0, 0, &enumMonitorsProc, (LPARAM) &monitorCoords);
  204149. // make sure the first in the list is the main monitor
  204150. for (int i = 1; i < monitorCoords.size(); ++i)
  204151. if (monitorCoords[i].getX() == 0 && monitorCoords[i].getY() == 0)
  204152. monitorCoords.swap (i, 0);
  204153. if (monitorCoords.size() == 0)
  204154. {
  204155. RECT r;
  204156. GetWindowRect (GetDesktopWindow(), &r);
  204157. monitorCoords.add (Rectangle<int> (r.left, r.top, r.right - r.left, r.bottom - r.top));
  204158. }
  204159. if (clipToWorkArea)
  204160. {
  204161. // clip the main monitor to the active non-taskbar area
  204162. RECT r;
  204163. SystemParametersInfo (SPI_GETWORKAREA, 0, &r, 0);
  204164. Rectangle<int>& screen = monitorCoords.getReference (0);
  204165. screen.setPosition (jmax (screen.getX(), (int) r.left),
  204166. jmax (screen.getY(), (int) r.top));
  204167. screen.setSize (jmin (screen.getRight(), (int) r.right) - screen.getX(),
  204168. jmin (screen.getBottom(), (int) r.bottom) - screen.getY());
  204169. }
  204170. }
  204171. static Image* createImageFromHBITMAP (HBITMAP bitmap) throw()
  204172. {
  204173. Image* im = 0;
  204174. if (bitmap != 0)
  204175. {
  204176. BITMAP bm;
  204177. if (GetObject (bitmap, sizeof (BITMAP), &bm)
  204178. && bm.bmWidth > 0 && bm.bmHeight > 0)
  204179. {
  204180. HDC tempDC = GetDC (0);
  204181. HDC dc = CreateCompatibleDC (tempDC);
  204182. ReleaseDC (0, tempDC);
  204183. SelectObject (dc, bitmap);
  204184. im = new Image (Image::ARGB, bm.bmWidth, bm.bmHeight, true);
  204185. for (int y = bm.bmHeight; --y >= 0;)
  204186. {
  204187. for (int x = bm.bmWidth; --x >= 0;)
  204188. {
  204189. COLORREF col = GetPixel (dc, x, y);
  204190. im->setPixelAt (x, y, Colour ((uint8) GetRValue (col),
  204191. (uint8) GetGValue (col),
  204192. (uint8) GetBValue (col)));
  204193. }
  204194. }
  204195. DeleteDC (dc);
  204196. }
  204197. }
  204198. return im;
  204199. }
  204200. static Image* createImageFromHICON (HICON icon) throw()
  204201. {
  204202. ICONINFO info;
  204203. if (GetIconInfo (icon, &info))
  204204. {
  204205. ScopedPointer<Image> mask (createImageFromHBITMAP (info.hbmMask));
  204206. if (mask == 0)
  204207. return 0;
  204208. ScopedPointer<Image> image (createImageFromHBITMAP (info.hbmColor));
  204209. if (image == 0)
  204210. return mask.release();
  204211. for (int y = image->getHeight(); --y >= 0;)
  204212. {
  204213. for (int x = image->getWidth(); --x >= 0;)
  204214. {
  204215. const float brightness = mask->getPixelAt (x, y).getBrightness();
  204216. if (brightness > 0.0f)
  204217. image->multiplyAlphaAt (x, y, 1.0f - brightness);
  204218. }
  204219. }
  204220. return image.release();
  204221. }
  204222. return 0;
  204223. }
  204224. static HICON createHICONFromImage (const Image& image, const BOOL isIcon, int hotspotX, int hotspotY) throw()
  204225. {
  204226. WindowsBitmapImage bitmap (Image::ARGB, image.getWidth(), image.getHeight(), true);
  204227. {
  204228. Graphics g (bitmap);
  204229. g.drawImageAt (&image, 0, 0);
  204230. }
  204231. HBITMAP mask = CreateBitmap (image.getWidth(), image.getHeight(), 1, 1, 0);
  204232. ICONINFO info;
  204233. info.fIcon = isIcon;
  204234. info.xHotspot = hotspotX;
  204235. info.yHotspot = hotspotY;
  204236. info.hbmMask = mask;
  204237. info.hbmColor = bitmap.hBitmap;
  204238. HICON hi = CreateIconIndirect (&info);
  204239. DeleteObject (mask);
  204240. return hi;
  204241. }
  204242. Image* juce_createIconForFile (const File& file)
  204243. {
  204244. Image* image = 0;
  204245. WCHAR filename [1024];
  204246. file.getFullPathName().copyToUnicode (filename, 1023);
  204247. WORD iconNum = 0;
  204248. HICON icon = ExtractAssociatedIcon ((HINSTANCE) PlatformUtilities::getCurrentModuleInstanceHandle(),
  204249. filename, &iconNum);
  204250. if (icon != 0)
  204251. {
  204252. image = createImageFromHICON (icon);
  204253. DestroyIcon (icon);
  204254. }
  204255. return image;
  204256. }
  204257. void* MouseCursor::createMouseCursorFromImage (const Image& image, int hotspotX, int hotspotY)
  204258. {
  204259. const int maxW = GetSystemMetrics (SM_CXCURSOR);
  204260. const int maxH = GetSystemMetrics (SM_CYCURSOR);
  204261. const Image* im = &image;
  204262. ScopedPointer<Image> newIm;
  204263. if (image.getWidth() > maxW || image.getHeight() > maxH)
  204264. {
  204265. im = newIm = image.createCopy (maxW, maxH);
  204266. hotspotX = (hotspotX * maxW) / image.getWidth();
  204267. hotspotY = (hotspotY * maxH) / image.getHeight();
  204268. }
  204269. return createHICONFromImage (*im, FALSE, hotspotX, hotspotY);
  204270. }
  204271. void MouseCursor::deleteMouseCursor (void* const cursorHandle, const bool isStandard)
  204272. {
  204273. if (cursorHandle != 0 && ! isStandard)
  204274. DestroyCursor ((HCURSOR) cursorHandle);
  204275. }
  204276. void* MouseCursor::createStandardMouseCursor (const MouseCursor::StandardCursorType type)
  204277. {
  204278. LPCTSTR cursorName = IDC_ARROW;
  204279. switch (type)
  204280. {
  204281. case NormalCursor: break;
  204282. case NoCursor: return 0;
  204283. case WaitCursor: cursorName = IDC_WAIT; break;
  204284. case IBeamCursor: cursorName = IDC_IBEAM; break;
  204285. case PointingHandCursor: cursorName = MAKEINTRESOURCE(32649); break;
  204286. case CrosshairCursor: cursorName = IDC_CROSS; break;
  204287. case CopyingCursor: break; // can't seem to find one of these in the win32 list..
  204288. case LeftRightResizeCursor:
  204289. case LeftEdgeResizeCursor:
  204290. case RightEdgeResizeCursor: cursorName = IDC_SIZEWE; break;
  204291. case UpDownResizeCursor:
  204292. case TopEdgeResizeCursor:
  204293. case BottomEdgeResizeCursor: cursorName = IDC_SIZENS; break;
  204294. case TopLeftCornerResizeCursor:
  204295. case BottomRightCornerResizeCursor: cursorName = IDC_SIZENWSE; break;
  204296. case TopRightCornerResizeCursor:
  204297. case BottomLeftCornerResizeCursor: cursorName = IDC_SIZENESW; break;
  204298. case UpDownLeftRightResizeCursor: cursorName = IDC_SIZEALL; break;
  204299. case DraggingHandCursor:
  204300. {
  204301. static void* dragHandCursor = 0;
  204302. if (dragHandCursor == 0)
  204303. {
  204304. static const unsigned char dragHandData[] =
  204305. { 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,
  204306. 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,
  204307. 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 };
  204308. const ScopedPointer <Image> image (ImageFileFormat::loadFrom (dragHandData, sizeof (dragHandData)));
  204309. dragHandCursor = createMouseCursorFromImage (*image, 8, 7);
  204310. }
  204311. return dragHandCursor;
  204312. }
  204313. default:
  204314. jassertfalse; break;
  204315. }
  204316. HCURSOR cursorH = LoadCursor (0, cursorName);
  204317. if (cursorH == 0)
  204318. cursorH = LoadCursor (0, IDC_ARROW);
  204319. return cursorH;
  204320. }
  204321. void MouseCursor::showInWindow (ComponentPeer*) const
  204322. {
  204323. SetCursor ((HCURSOR) getHandle());
  204324. }
  204325. void MouseCursor::showInAllWindows() const
  204326. {
  204327. showInWindow (0);
  204328. }
  204329. class JuceDropSource : public ComBaseClassHelper <IDropSource>
  204330. {
  204331. public:
  204332. JuceDropSource() {}
  204333. ~JuceDropSource() {}
  204334. HRESULT __stdcall QueryContinueDrag (BOOL escapePressed, DWORD keys)
  204335. {
  204336. if (escapePressed)
  204337. return DRAGDROP_S_CANCEL;
  204338. if ((keys & (MK_LBUTTON | MK_RBUTTON)) == 0)
  204339. return DRAGDROP_S_DROP;
  204340. return S_OK;
  204341. }
  204342. HRESULT __stdcall GiveFeedback (DWORD)
  204343. {
  204344. return DRAGDROP_S_USEDEFAULTCURSORS;
  204345. }
  204346. };
  204347. class JuceEnumFormatEtc : public ComBaseClassHelper <IEnumFORMATETC>
  204348. {
  204349. public:
  204350. JuceEnumFormatEtc (const FORMATETC* const format_)
  204351. : format (format_),
  204352. index (0)
  204353. {
  204354. }
  204355. ~JuceEnumFormatEtc() {}
  204356. HRESULT __stdcall Clone (IEnumFORMATETC** result)
  204357. {
  204358. if (result == 0)
  204359. return E_POINTER;
  204360. JuceEnumFormatEtc* const newOne = new JuceEnumFormatEtc (format);
  204361. newOne->index = index;
  204362. *result = newOne;
  204363. return S_OK;
  204364. }
  204365. HRESULT __stdcall Next (ULONG celt, LPFORMATETC lpFormatEtc, ULONG* pceltFetched)
  204366. {
  204367. if (pceltFetched != 0)
  204368. *pceltFetched = 0;
  204369. else if (celt != 1)
  204370. return S_FALSE;
  204371. if (index == 0 && celt > 0 && lpFormatEtc != 0)
  204372. {
  204373. copyFormatEtc (lpFormatEtc [0], *format);
  204374. ++index;
  204375. if (pceltFetched != 0)
  204376. *pceltFetched = 1;
  204377. return S_OK;
  204378. }
  204379. return S_FALSE;
  204380. }
  204381. HRESULT __stdcall Skip (ULONG celt)
  204382. {
  204383. if (index + (int) celt >= 1)
  204384. return S_FALSE;
  204385. index += celt;
  204386. return S_OK;
  204387. }
  204388. HRESULT __stdcall Reset()
  204389. {
  204390. index = 0;
  204391. return S_OK;
  204392. }
  204393. private:
  204394. const FORMATETC* const format;
  204395. int index;
  204396. static void copyFormatEtc (FORMATETC& dest, const FORMATETC& source)
  204397. {
  204398. dest = source;
  204399. if (source.ptd != 0)
  204400. {
  204401. dest.ptd = (DVTARGETDEVICE*) CoTaskMemAlloc (sizeof (DVTARGETDEVICE));
  204402. *(dest.ptd) = *(source.ptd);
  204403. }
  204404. }
  204405. JuceEnumFormatEtc (const JuceEnumFormatEtc&);
  204406. JuceEnumFormatEtc& operator= (const JuceEnumFormatEtc&);
  204407. };
  204408. class JuceDataObject : public ComBaseClassHelper <IDataObject>
  204409. {
  204410. JuceDropSource* const dropSource;
  204411. const FORMATETC* const format;
  204412. const STGMEDIUM* const medium;
  204413. JuceDataObject (const JuceDataObject&);
  204414. JuceDataObject& operator= (const JuceDataObject&);
  204415. public:
  204416. JuceDataObject (JuceDropSource* const dropSource_,
  204417. const FORMATETC* const format_,
  204418. const STGMEDIUM* const medium_)
  204419. : dropSource (dropSource_),
  204420. format (format_),
  204421. medium (medium_)
  204422. {
  204423. }
  204424. virtual ~JuceDataObject()
  204425. {
  204426. jassert (refCount == 0);
  204427. }
  204428. HRESULT __stdcall GetData (FORMATETC __RPC_FAR* pFormatEtc, STGMEDIUM __RPC_FAR* pMedium)
  204429. {
  204430. if ((pFormatEtc->tymed & format->tymed) != 0
  204431. && pFormatEtc->cfFormat == format->cfFormat
  204432. && pFormatEtc->dwAspect == format->dwAspect)
  204433. {
  204434. pMedium->tymed = format->tymed;
  204435. pMedium->pUnkForRelease = 0;
  204436. if (format->tymed == TYMED_HGLOBAL)
  204437. {
  204438. const SIZE_T len = GlobalSize (medium->hGlobal);
  204439. void* const src = GlobalLock (medium->hGlobal);
  204440. void* const dst = GlobalAlloc (GMEM_FIXED, len);
  204441. memcpy (dst, src, len);
  204442. GlobalUnlock (medium->hGlobal);
  204443. pMedium->hGlobal = dst;
  204444. return S_OK;
  204445. }
  204446. }
  204447. return DV_E_FORMATETC;
  204448. }
  204449. HRESULT __stdcall QueryGetData (FORMATETC __RPC_FAR* f)
  204450. {
  204451. if (f == 0)
  204452. return E_INVALIDARG;
  204453. if (f->tymed == format->tymed
  204454. && f->cfFormat == format->cfFormat
  204455. && f->dwAspect == format->dwAspect)
  204456. return S_OK;
  204457. return DV_E_FORMATETC;
  204458. }
  204459. HRESULT __stdcall GetCanonicalFormatEtc (FORMATETC __RPC_FAR*, FORMATETC __RPC_FAR* pFormatEtcOut)
  204460. {
  204461. pFormatEtcOut->ptd = 0;
  204462. return E_NOTIMPL;
  204463. }
  204464. HRESULT __stdcall EnumFormatEtc (DWORD direction, IEnumFORMATETC __RPC_FAR *__RPC_FAR *result)
  204465. {
  204466. if (result == 0)
  204467. return E_POINTER;
  204468. if (direction == DATADIR_GET)
  204469. {
  204470. *result = new JuceEnumFormatEtc (format);
  204471. return S_OK;
  204472. }
  204473. *result = 0;
  204474. return E_NOTIMPL;
  204475. }
  204476. HRESULT __stdcall GetDataHere (FORMATETC __RPC_FAR*, STGMEDIUM __RPC_FAR*) { return DATA_E_FORMATETC; }
  204477. HRESULT __stdcall SetData (FORMATETC __RPC_FAR*, STGMEDIUM __RPC_FAR*, BOOL) { return E_NOTIMPL; }
  204478. HRESULT __stdcall DAdvise (FORMATETC __RPC_FAR*, DWORD, IAdviseSink __RPC_FAR*, DWORD __RPC_FAR*) { return OLE_E_ADVISENOTSUPPORTED; }
  204479. HRESULT __stdcall DUnadvise (DWORD) { return E_NOTIMPL; }
  204480. HRESULT __stdcall EnumDAdvise (IEnumSTATDATA __RPC_FAR *__RPC_FAR *) { return OLE_E_ADVISENOTSUPPORTED; }
  204481. };
  204482. static HDROP createHDrop (const StringArray& fileNames) throw()
  204483. {
  204484. int totalChars = 0;
  204485. for (int i = fileNames.size(); --i >= 0;)
  204486. totalChars += fileNames[i].length() + 1;
  204487. HDROP hDrop = (HDROP) GlobalAlloc (GMEM_MOVEABLE | GMEM_ZEROINIT,
  204488. sizeof (DROPFILES)
  204489. + sizeof (WCHAR) * (totalChars + 2));
  204490. if (hDrop != 0)
  204491. {
  204492. LPDROPFILES pDropFiles = (LPDROPFILES) GlobalLock (hDrop);
  204493. pDropFiles->pFiles = sizeof (DROPFILES);
  204494. pDropFiles->fWide = true;
  204495. WCHAR* fname = (WCHAR*) (((char*) pDropFiles) + sizeof (DROPFILES));
  204496. for (int i = 0; i < fileNames.size(); ++i)
  204497. {
  204498. fileNames[i].copyToUnicode (fname, 2048);
  204499. fname += fileNames[i].length() + 1;
  204500. }
  204501. *fname = 0;
  204502. GlobalUnlock (hDrop);
  204503. }
  204504. return hDrop;
  204505. }
  204506. static bool performDragDrop (FORMATETC* const format, STGMEDIUM* const medium, const DWORD whatToDo) throw()
  204507. {
  204508. JuceDropSource* const source = new JuceDropSource();
  204509. JuceDataObject* const data = new JuceDataObject (source, format, medium);
  204510. DWORD effect;
  204511. const HRESULT res = DoDragDrop (data, source, whatToDo, &effect);
  204512. data->Release();
  204513. source->Release();
  204514. return res == DRAGDROP_S_DROP;
  204515. }
  204516. bool DragAndDropContainer::performExternalDragDropOfFiles (const StringArray& files, const bool canMove)
  204517. {
  204518. FORMATETC format = { CF_HDROP, 0, DVASPECT_CONTENT, -1, TYMED_HGLOBAL };
  204519. STGMEDIUM medium = { TYMED_HGLOBAL, { 0 }, 0 };
  204520. medium.hGlobal = createHDrop (files);
  204521. return performDragDrop (&format, &medium, canMove ? (DROPEFFECT_COPY | DROPEFFECT_MOVE)
  204522. : DROPEFFECT_COPY);
  204523. }
  204524. bool DragAndDropContainer::performExternalDragDropOfText (const String& text)
  204525. {
  204526. FORMATETC format = { CF_TEXT, 0, DVASPECT_CONTENT, -1, TYMED_HGLOBAL };
  204527. STGMEDIUM medium = { TYMED_HGLOBAL, { 0 }, 0 };
  204528. const int numChars = text.length();
  204529. medium.hGlobal = GlobalAlloc (GMEM_MOVEABLE | GMEM_ZEROINIT, (numChars + 2) * sizeof (WCHAR));
  204530. WCHAR* const data = static_cast <WCHAR*> (GlobalLock (medium.hGlobal));
  204531. text.copyToUnicode (data, numChars + 1);
  204532. format.cfFormat = CF_UNICODETEXT;
  204533. GlobalUnlock (medium.hGlobal);
  204534. return performDragDrop (&format, &medium, DROPEFFECT_COPY | DROPEFFECT_MOVE);
  204535. }
  204536. #endif
  204537. /*** End of inlined file: juce_win32_Windowing.cpp ***/
  204538. /*** Start of inlined file: juce_win32_Fonts.cpp ***/
  204539. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  204540. // compiled on its own).
  204541. #if JUCE_INCLUDED_FILE
  204542. static int CALLBACK wfontEnum2 (ENUMLOGFONTEXW* lpelfe,
  204543. NEWTEXTMETRICEXW*,
  204544. int type,
  204545. LPARAM lParam)
  204546. {
  204547. if (lpelfe != 0 && (type & RASTER_FONTTYPE) == 0)
  204548. {
  204549. const String fontName (lpelfe->elfLogFont.lfFaceName);
  204550. ((StringArray*) lParam)->addIfNotAlreadyThere (fontName.removeCharacters ("@"));
  204551. }
  204552. return 1;
  204553. }
  204554. static int CALLBACK wfontEnum1 (ENUMLOGFONTEXW* lpelfe,
  204555. NEWTEXTMETRICEXW*,
  204556. int type,
  204557. LPARAM lParam)
  204558. {
  204559. if (lpelfe != 0 && (type & RASTER_FONTTYPE) == 0)
  204560. {
  204561. LOGFONTW lf;
  204562. zerostruct (lf);
  204563. lf.lfWeight = FW_DONTCARE;
  204564. lf.lfOutPrecision = OUT_OUTLINE_PRECIS;
  204565. lf.lfQuality = DEFAULT_QUALITY;
  204566. lf.lfCharSet = DEFAULT_CHARSET;
  204567. lf.lfClipPrecision = CLIP_DEFAULT_PRECIS;
  204568. lf.lfPitchAndFamily = FF_DONTCARE;
  204569. const String fontName (lpelfe->elfLogFont.lfFaceName);
  204570. fontName.copyToUnicode (lf.lfFaceName, LF_FACESIZE - 1);
  204571. HDC dc = CreateCompatibleDC (0);
  204572. EnumFontFamiliesEx (dc, &lf,
  204573. (FONTENUMPROCW) &wfontEnum2,
  204574. lParam, 0);
  204575. DeleteDC (dc);
  204576. }
  204577. return 1;
  204578. }
  204579. const StringArray Font::findAllTypefaceNames()
  204580. {
  204581. StringArray results;
  204582. HDC dc = CreateCompatibleDC (0);
  204583. {
  204584. LOGFONTW lf;
  204585. zerostruct (lf);
  204586. lf.lfWeight = FW_DONTCARE;
  204587. lf.lfOutPrecision = OUT_OUTLINE_PRECIS;
  204588. lf.lfQuality = DEFAULT_QUALITY;
  204589. lf.lfCharSet = DEFAULT_CHARSET;
  204590. lf.lfClipPrecision = CLIP_DEFAULT_PRECIS;
  204591. lf.lfPitchAndFamily = FF_DONTCARE;
  204592. lf.lfFaceName[0] = 0;
  204593. EnumFontFamiliesEx (dc, &lf,
  204594. (FONTENUMPROCW) &wfontEnum1,
  204595. (LPARAM) &results, 0);
  204596. }
  204597. DeleteDC (dc);
  204598. results.sort (true);
  204599. return results;
  204600. }
  204601. extern bool juce_IsRunningInWine();
  204602. void Font::getPlatformDefaultFontNames (String& defaultSans, String& defaultSerif, String& defaultFixed)
  204603. {
  204604. if (juce_IsRunningInWine())
  204605. {
  204606. // If we're running in Wine, then use fonts that might be available on Linux..
  204607. defaultSans = "Bitstream Vera Sans";
  204608. defaultSerif = "Bitstream Vera Serif";
  204609. defaultFixed = "Bitstream Vera Sans Mono";
  204610. }
  204611. else
  204612. {
  204613. defaultSans = "Verdana";
  204614. defaultSerif = "Times";
  204615. defaultFixed = "Lucida Console";
  204616. }
  204617. }
  204618. class FontDCHolder : private DeletedAtShutdown
  204619. {
  204620. public:
  204621. FontDCHolder()
  204622. : dc (0), numKPs (0), size (0),
  204623. bold (false), italic (false)
  204624. {
  204625. }
  204626. ~FontDCHolder()
  204627. {
  204628. if (dc != 0)
  204629. {
  204630. DeleteDC (dc);
  204631. DeleteObject (fontH);
  204632. }
  204633. clearSingletonInstance();
  204634. }
  204635. juce_DeclareSingleton_SingleThreaded_Minimal (FontDCHolder);
  204636. HDC loadFont (const String& fontName_, const bool bold_, const bool italic_, const int size_)
  204637. {
  204638. if (fontName != fontName_ || bold != bold_ || italic != italic_ || size != size_)
  204639. {
  204640. fontName = fontName_;
  204641. bold = bold_;
  204642. italic = italic_;
  204643. size = size_;
  204644. if (dc != 0)
  204645. {
  204646. DeleteDC (dc);
  204647. DeleteObject (fontH);
  204648. kps.free();
  204649. }
  204650. fontH = 0;
  204651. dc = CreateCompatibleDC (0);
  204652. SetMapperFlags (dc, 0);
  204653. SetMapMode (dc, MM_TEXT);
  204654. LOGFONTW lfw;
  204655. zerostruct (lfw);
  204656. lfw.lfCharSet = DEFAULT_CHARSET;
  204657. lfw.lfClipPrecision = CLIP_DEFAULT_PRECIS;
  204658. lfw.lfOutPrecision = OUT_OUTLINE_PRECIS;
  204659. lfw.lfPitchAndFamily = DEFAULT_PITCH | FF_DONTCARE;
  204660. lfw.lfQuality = PROOF_QUALITY;
  204661. lfw.lfItalic = (BYTE) (italic ? TRUE : FALSE);
  204662. lfw.lfWeight = bold ? FW_BOLD : FW_NORMAL;
  204663. fontName.copyToUnicode (lfw.lfFaceName, LF_FACESIZE - 1);
  204664. lfw.lfHeight = size > 0 ? size : -256;
  204665. HFONT standardSizedFont = CreateFontIndirect (&lfw);
  204666. if (standardSizedFont != 0)
  204667. {
  204668. if (SelectObject (dc, standardSizedFont) != 0)
  204669. {
  204670. fontH = standardSizedFont;
  204671. if (size == 0)
  204672. {
  204673. OUTLINETEXTMETRIC otm;
  204674. if (GetOutlineTextMetrics (dc, sizeof (otm), &otm) != 0)
  204675. {
  204676. lfw.lfHeight = -(int) otm.otmEMSquare;
  204677. fontH = CreateFontIndirect (&lfw);
  204678. SelectObject (dc, fontH);
  204679. DeleteObject (standardSizedFont);
  204680. }
  204681. }
  204682. }
  204683. else
  204684. {
  204685. jassertfalse
  204686. }
  204687. }
  204688. else
  204689. {
  204690. jassertfalse
  204691. }
  204692. }
  204693. return dc;
  204694. }
  204695. KERNINGPAIR* getKerningPairs (int& numKPs_)
  204696. {
  204697. if (kps == 0)
  204698. {
  204699. numKPs = GetKerningPairs (dc, 0, 0);
  204700. kps.calloc (numKPs);
  204701. GetKerningPairs (dc, numKPs, kps);
  204702. }
  204703. numKPs_ = numKPs;
  204704. return kps;
  204705. }
  204706. private:
  204707. HFONT fontH;
  204708. HDC dc;
  204709. String fontName;
  204710. HeapBlock <KERNINGPAIR> kps;
  204711. int numKPs, size;
  204712. bool bold, italic;
  204713. FontDCHolder (const FontDCHolder&);
  204714. FontDCHolder& operator= (const FontDCHolder&);
  204715. };
  204716. juce_ImplementSingleton_SingleThreaded (FontDCHolder);
  204717. class WindowsTypeface : public CustomTypeface
  204718. {
  204719. public:
  204720. WindowsTypeface (const Font& font)
  204721. {
  204722. HDC dc = FontDCHolder::getInstance()->loadFont (font.getTypefaceName(),
  204723. font.isBold(), font.isItalic(), 0);
  204724. TEXTMETRIC tm;
  204725. tm.tmAscent = tm.tmHeight = 1;
  204726. tm.tmDefaultChar = 0;
  204727. GetTextMetrics (dc, &tm);
  204728. setCharacteristics (font.getTypefaceName(),
  204729. tm.tmAscent / (float) tm.tmHeight,
  204730. font.isBold(), font.isItalic(),
  204731. tm.tmDefaultChar);
  204732. }
  204733. bool loadGlyphIfPossible (juce_wchar character)
  204734. {
  204735. HDC dc = FontDCHolder::getInstance()->loadFont (name, isBold, isItalic, 0);
  204736. GLYPHMETRICS gm;
  204737. {
  204738. const WCHAR charToTest[] = { (WCHAR) character, 0 };
  204739. WORD index = 0;
  204740. if (GetGlyphIndices (dc, charToTest, 1, &index, GGI_MARK_NONEXISTING_GLYPHS) != GDI_ERROR
  204741. && index == 0xffff)
  204742. {
  204743. return false;
  204744. }
  204745. }
  204746. Path glyphPath;
  204747. TEXTMETRIC tm;
  204748. if (! GetTextMetrics (dc, &tm))
  204749. {
  204750. addGlyph (character, glyphPath, 0);
  204751. return true;
  204752. }
  204753. const float height = (float) tm.tmHeight;
  204754. static const MAT2 identityMatrix = { { 0, 1 }, { 0, 0 }, { 0, 0 }, { 0, 1 } };
  204755. const int bufSize = GetGlyphOutline (dc, character, GGO_NATIVE,
  204756. &gm, 0, 0, &identityMatrix);
  204757. if (bufSize > 0)
  204758. {
  204759. HeapBlock<char> data (bufSize);
  204760. GetGlyphOutline (dc, character, GGO_NATIVE, &gm,
  204761. bufSize, data, &identityMatrix);
  204762. const TTPOLYGONHEADER* pheader = reinterpret_cast<TTPOLYGONHEADER*> (data.getData());
  204763. const float scaleX = 1.0f / height;
  204764. const float scaleY = -1.0f / height;
  204765. while ((char*) pheader < data + bufSize)
  204766. {
  204767. float x = scaleX * pheader->pfxStart.x.value;
  204768. float y = scaleY * pheader->pfxStart.y.value;
  204769. glyphPath.startNewSubPath (x, y);
  204770. const TTPOLYCURVE* curve = (const TTPOLYCURVE*) ((const char*) pheader + sizeof (TTPOLYGONHEADER));
  204771. const char* const curveEnd = ((const char*) pheader) + pheader->cb;
  204772. while ((const char*) curve < curveEnd)
  204773. {
  204774. if (curve->wType == TT_PRIM_LINE)
  204775. {
  204776. for (int i = 0; i < curve->cpfx; ++i)
  204777. {
  204778. x = scaleX * curve->apfx[i].x.value;
  204779. y = scaleY * curve->apfx[i].y.value;
  204780. glyphPath.lineTo (x, y);
  204781. }
  204782. }
  204783. else if (curve->wType == TT_PRIM_QSPLINE)
  204784. {
  204785. for (int i = 0; i < curve->cpfx - 1; ++i)
  204786. {
  204787. const float x2 = scaleX * curve->apfx[i].x.value;
  204788. const float y2 = scaleY * curve->apfx[i].y.value;
  204789. float x3, y3;
  204790. if (i < curve->cpfx - 2)
  204791. {
  204792. x3 = 0.5f * (x2 + scaleX * curve->apfx[i + 1].x.value);
  204793. y3 = 0.5f * (y2 + scaleY * curve->apfx[i + 1].y.value);
  204794. }
  204795. else
  204796. {
  204797. x3 = scaleX * curve->apfx[i + 1].x.value;
  204798. y3 = scaleY * curve->apfx[i + 1].y.value;
  204799. }
  204800. glyphPath.quadraticTo (x2, y2, x3, y3);
  204801. x = x3;
  204802. y = y3;
  204803. }
  204804. }
  204805. curve = (const TTPOLYCURVE*) &(curve->apfx [curve->cpfx]);
  204806. }
  204807. pheader = (const TTPOLYGONHEADER*) curve;
  204808. glyphPath.closeSubPath();
  204809. }
  204810. }
  204811. addGlyph (character, glyphPath, gm.gmCellIncX / height);
  204812. int numKPs;
  204813. const KERNINGPAIR* const kps = FontDCHolder::getInstance()->getKerningPairs (numKPs);
  204814. for (int i = 0; i < numKPs; ++i)
  204815. {
  204816. if (kps[i].wFirst == character)
  204817. addKerningPair (kps[i].wFirst, kps[i].wSecond,
  204818. kps[i].iKernAmount / height);
  204819. }
  204820. return true;
  204821. }
  204822. };
  204823. const Typeface::Ptr Typeface::createSystemTypefaceFor (const Font& font)
  204824. {
  204825. return new WindowsTypeface (font);
  204826. }
  204827. #endif
  204828. /*** End of inlined file: juce_win32_Fonts.cpp ***/
  204829. /*** Start of inlined file: juce_win32_FileChooser.cpp ***/
  204830. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  204831. // compiled on its own).
  204832. #if JUCE_INCLUDED_FILE
  204833. void juce_setWindowStyleBit (HWND h, const int styleType, const int feature, const bool bitIsSet) throw();
  204834. namespace FileChooserHelpers
  204835. {
  204836. static const void* defaultDirPath = 0;
  204837. static String returnedString; // need this to get non-existent pathnames from the directory chooser
  204838. static Component* currentExtraFileWin = 0;
  204839. static bool areThereAnyAlwaysOnTopWindows()
  204840. {
  204841. for (int i = Desktop::getInstance().getNumComponents(); --i >= 0;)
  204842. {
  204843. Component* c = Desktop::getInstance().getComponent (i);
  204844. if (c != 0 && c->isAlwaysOnTop() && c->isShowing())
  204845. return true;
  204846. }
  204847. return false;
  204848. }
  204849. static int CALLBACK browseCallbackProc (HWND hWnd, UINT msg, LPARAM lParam, LPARAM /*lpData*/)
  204850. {
  204851. if (msg == BFFM_INITIALIZED)
  204852. SendMessage (hWnd, BFFM_SETSELECTIONW, TRUE, (LPARAM) defaultDirPath);
  204853. else if (msg == BFFM_VALIDATEFAILEDW)
  204854. returnedString = (LPCWSTR) lParam;
  204855. else if (msg == BFFM_VALIDATEFAILEDA)
  204856. returnedString = (const char*) lParam;
  204857. return 0;
  204858. }
  204859. static UINT_PTR CALLBACK openCallback (HWND hdlg, UINT uiMsg, WPARAM /*wParam*/, LPARAM lParam)
  204860. {
  204861. if (currentExtraFileWin != 0)
  204862. {
  204863. if (uiMsg == WM_INITDIALOG)
  204864. {
  204865. HWND dialogH = GetParent (hdlg);
  204866. jassert (dialogH != 0);
  204867. if (dialogH == 0)
  204868. dialogH = hdlg;
  204869. RECT r, cr;
  204870. GetWindowRect (dialogH, &r);
  204871. GetClientRect (dialogH, &cr);
  204872. SetWindowPos (dialogH, 0,
  204873. r.left, r.top,
  204874. currentExtraFileWin->getWidth() + jmax (150, (int) (r.right - r.left)),
  204875. jmax (150, (int) (r.bottom - r.top)),
  204876. SWP_NOACTIVATE | SWP_NOOWNERZORDER | SWP_NOZORDER);
  204877. currentExtraFileWin->setBounds (cr.right, cr.top, currentExtraFileWin->getWidth(), cr.bottom - cr.top);
  204878. currentExtraFileWin->getChildComponent(0)->setBounds (0, 0, currentExtraFileWin->getWidth(), currentExtraFileWin->getHeight());
  204879. SetParent ((HWND) currentExtraFileWin->getWindowHandle(), (HWND) dialogH);
  204880. juce_setWindowStyleBit ((HWND)currentExtraFileWin->getWindowHandle(), GWL_STYLE, WS_CHILD, (dialogH != 0));
  204881. juce_setWindowStyleBit ((HWND)currentExtraFileWin->getWindowHandle(), GWL_STYLE, WS_POPUP, (dialogH == 0));
  204882. }
  204883. else if (uiMsg == WM_NOTIFY)
  204884. {
  204885. LPOFNOTIFY ofn = (LPOFNOTIFY) lParam;
  204886. if (ofn->hdr.code == CDN_SELCHANGE)
  204887. {
  204888. FilePreviewComponent* comp = (FilePreviewComponent*) currentExtraFileWin->getChildComponent(0);
  204889. if (comp != 0)
  204890. {
  204891. TCHAR path [MAX_PATH * 2];
  204892. path[0] = 0;
  204893. CommDlg_OpenSave_GetFilePath (GetParent (hdlg), (LPARAM) &path, MAX_PATH);
  204894. const String fn ((const WCHAR*) path);
  204895. comp->selectedFileChanged (File (fn));
  204896. }
  204897. }
  204898. }
  204899. }
  204900. return 0;
  204901. }
  204902. class FPComponentHolder : public Component
  204903. {
  204904. public:
  204905. FPComponentHolder()
  204906. {
  204907. setVisible (true);
  204908. setOpaque (true);
  204909. }
  204910. ~FPComponentHolder()
  204911. {
  204912. }
  204913. void paint (Graphics& g)
  204914. {
  204915. g.fillAll (Colours::lightgrey);
  204916. }
  204917. private:
  204918. FPComponentHolder (const FPComponentHolder&);
  204919. FPComponentHolder& operator= (const FPComponentHolder&);
  204920. };
  204921. }
  204922. void FileChooser::showPlatformDialog (Array<File>& results,
  204923. const String& title,
  204924. const File& currentFileOrDirectory,
  204925. const String& filter,
  204926. bool selectsDirectory,
  204927. bool /*selectsFiles*/,
  204928. bool isSaveDialogue,
  204929. bool warnAboutOverwritingExistingFiles,
  204930. bool selectMultipleFiles,
  204931. FilePreviewComponent* extraInfoComponent)
  204932. {
  204933. using namespace FileChooserHelpers;
  204934. const int numCharsAvailable = 32768;
  204935. MemoryBlock filenameSpace ((numCharsAvailable + 1) * sizeof (WCHAR), true);
  204936. WCHAR* const fname = (WCHAR*) filenameSpace.getData();
  204937. int fnameIdx = 0;
  204938. JUCE_TRY
  204939. {
  204940. // use a modal window as the parent for this dialog box
  204941. // to block input from other app windows
  204942. const Rectangle<int> mainMon (Desktop::getInstance().getMainMonitorArea());
  204943. Component w (String::empty);
  204944. w.setBounds (mainMon.getX() + mainMon.getWidth() / 4,
  204945. mainMon.getY() + mainMon.getHeight() / 4,
  204946. 0, 0);
  204947. w.setOpaque (true);
  204948. w.setAlwaysOnTop (areThereAnyAlwaysOnTopWindows());
  204949. w.addToDesktop (0);
  204950. if (extraInfoComponent == 0)
  204951. w.enterModalState();
  204952. String initialDir;
  204953. if (currentFileOrDirectory.isDirectory())
  204954. {
  204955. initialDir = currentFileOrDirectory.getFullPathName();
  204956. }
  204957. else
  204958. {
  204959. currentFileOrDirectory.getFileName().copyToUnicode (fname, numCharsAvailable);
  204960. initialDir = currentFileOrDirectory.getParentDirectory().getFullPathName();
  204961. }
  204962. if (currentExtraFileWin->isValidComponent())
  204963. {
  204964. jassertfalse
  204965. return;
  204966. }
  204967. if (selectsDirectory)
  204968. {
  204969. LPITEMIDLIST list = 0;
  204970. filenameSpace.fillWith (0);
  204971. {
  204972. BROWSEINFO bi;
  204973. zerostruct (bi);
  204974. bi.hwndOwner = (HWND) w.getWindowHandle();
  204975. bi.pszDisplayName = fname;
  204976. bi.lpszTitle = title;
  204977. bi.lpfn = browseCallbackProc;
  204978. #ifdef BIF_USENEWUI
  204979. bi.ulFlags = BIF_USENEWUI | BIF_VALIDATE;
  204980. #else
  204981. bi.ulFlags = 0x50;
  204982. #endif
  204983. defaultDirPath = (const WCHAR*) initialDir;
  204984. list = SHBrowseForFolder (&bi);
  204985. if (! SHGetPathFromIDListW (list, fname))
  204986. {
  204987. fname[0] = 0;
  204988. returnedString = String::empty;
  204989. }
  204990. }
  204991. LPMALLOC al;
  204992. if (list != 0 && SUCCEEDED (SHGetMalloc (&al)))
  204993. al->Free (list);
  204994. defaultDirPath = 0;
  204995. if (returnedString.isNotEmpty())
  204996. {
  204997. const String stringFName (fname);
  204998. results.add (File (stringFName).getSiblingFile (returnedString));
  204999. returnedString = String::empty;
  205000. return;
  205001. }
  205002. }
  205003. else
  205004. {
  205005. DWORD flags = OFN_EXPLORER | OFN_PATHMUSTEXIST | OFN_NOCHANGEDIR | OFN_HIDEREADONLY;
  205006. if (warnAboutOverwritingExistingFiles)
  205007. flags |= OFN_OVERWRITEPROMPT;
  205008. if (selectMultipleFiles)
  205009. flags |= OFN_ALLOWMULTISELECT;
  205010. if (extraInfoComponent != 0)
  205011. {
  205012. flags |= OFN_ENABLEHOOK;
  205013. currentExtraFileWin = new FPComponentHolder();
  205014. currentExtraFileWin->addAndMakeVisible (extraInfoComponent);
  205015. currentExtraFileWin->setSize (jlimit (20, 800, extraInfoComponent->getWidth()),
  205016. extraInfoComponent->getHeight());
  205017. currentExtraFileWin->addToDesktop (0);
  205018. currentExtraFileWin->enterModalState();
  205019. }
  205020. {
  205021. WCHAR filters [1024];
  205022. zeromem (filters, sizeof (filters));
  205023. filter.copyToUnicode (filters, 1024);
  205024. filter.copyToUnicode (filters + filter.length() + 1,
  205025. 1022 - filter.length());
  205026. OPENFILENAMEW of;
  205027. zerostruct (of);
  205028. #ifdef OPENFILENAME_SIZE_VERSION_400W
  205029. of.lStructSize = OPENFILENAME_SIZE_VERSION_400W;
  205030. #else
  205031. of.lStructSize = sizeof (of);
  205032. #endif
  205033. of.hwndOwner = (HWND) w.getWindowHandle();
  205034. of.lpstrFilter = filters;
  205035. of.nFilterIndex = 1;
  205036. of.lpstrFile = fname;
  205037. of.nMaxFile = numCharsAvailable;
  205038. of.lpstrInitialDir = initialDir;
  205039. of.lpstrTitle = title;
  205040. of.Flags = flags;
  205041. if (extraInfoComponent != 0)
  205042. of.lpfnHook = &openCallback;
  205043. if (isSaveDialogue)
  205044. {
  205045. if (! GetSaveFileName (&of))
  205046. fname[0] = 0;
  205047. else
  205048. fnameIdx = of.nFileOffset;
  205049. }
  205050. else
  205051. {
  205052. if (! GetOpenFileName (&of))
  205053. fname[0] = 0;
  205054. else
  205055. fnameIdx = of.nFileOffset;
  205056. }
  205057. }
  205058. }
  205059. }
  205060. #if JUCE_CATCH_UNHANDLED_EXCEPTIONS
  205061. catch (...)
  205062. {
  205063. fname[0] = 0;
  205064. }
  205065. #endif
  205066. deleteAndZero (currentExtraFileWin);
  205067. const WCHAR* const files = fname;
  205068. if (selectMultipleFiles && fnameIdx > 0 && files [fnameIdx - 1] == 0)
  205069. {
  205070. const WCHAR* filename = files + fnameIdx;
  205071. while (*filename != 0)
  205072. {
  205073. const String filepath (String (files) + "\\" + String (filename));
  205074. results.add (File (filepath));
  205075. filename += CharacterFunctions::length (filename) + 1;
  205076. }
  205077. }
  205078. else if (files[0] != 0)
  205079. {
  205080. results.add (File (files));
  205081. }
  205082. }
  205083. #endif
  205084. /*** End of inlined file: juce_win32_FileChooser.cpp ***/
  205085. /*** Start of inlined file: juce_win32_Misc.cpp ***/
  205086. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  205087. // compiled on its own).
  205088. #if JUCE_INCLUDED_FILE
  205089. void SystemClipboard::copyTextToClipboard (const String& text)
  205090. {
  205091. if (OpenClipboard (0) != 0)
  205092. {
  205093. if (EmptyClipboard() != 0)
  205094. {
  205095. const int len = text.length();
  205096. if (len > 0)
  205097. {
  205098. HGLOBAL bufH = GlobalAlloc (GMEM_MOVEABLE | GMEM_DDESHARE,
  205099. (len + 1) * sizeof (wchar_t));
  205100. if (bufH != 0)
  205101. {
  205102. WCHAR* const data = static_cast <WCHAR*> (GlobalLock (bufH));
  205103. text.copyToUnicode (data, len);
  205104. GlobalUnlock (bufH);
  205105. SetClipboardData (CF_UNICODETEXT, bufH);
  205106. }
  205107. }
  205108. }
  205109. CloseClipboard();
  205110. }
  205111. }
  205112. const String SystemClipboard::getTextFromClipboard()
  205113. {
  205114. String result;
  205115. if (OpenClipboard (0) != 0)
  205116. {
  205117. HANDLE bufH = GetClipboardData (CF_UNICODETEXT);
  205118. if (bufH != 0)
  205119. {
  205120. const wchar_t* const data = (const wchar_t*) GlobalLock (bufH);
  205121. if (data != 0)
  205122. {
  205123. result = String (data, (int) (GlobalSize (bufH) / sizeof (wchar_t)));
  205124. GlobalUnlock (bufH);
  205125. }
  205126. }
  205127. CloseClipboard();
  205128. }
  205129. return result;
  205130. }
  205131. #endif
  205132. /*** End of inlined file: juce_win32_Misc.cpp ***/
  205133. /*** Start of inlined file: juce_win32_ActiveXComponent.cpp ***/
  205134. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  205135. // compiled on its own).
  205136. #if JUCE_INCLUDED_FILE
  205137. namespace ActiveXHelpers
  205138. {
  205139. class JuceIStorage : public ComBaseClassHelper <IStorage>
  205140. {
  205141. public:
  205142. JuceIStorage() {}
  205143. ~JuceIStorage() {}
  205144. HRESULT __stdcall CreateStream (const WCHAR*, DWORD, DWORD, DWORD, IStream**) { return E_NOTIMPL; }
  205145. HRESULT __stdcall OpenStream (const WCHAR*, void*, DWORD, DWORD, IStream**) { return E_NOTIMPL; }
  205146. HRESULT __stdcall CreateStorage (const WCHAR*, DWORD, DWORD, DWORD, IStorage**) { return E_NOTIMPL; }
  205147. HRESULT __stdcall OpenStorage (const WCHAR*, IStorage*, DWORD, SNB, DWORD, IStorage**) { return E_NOTIMPL; }
  205148. HRESULT __stdcall CopyTo (DWORD, IID const*, SNB, IStorage*) { return E_NOTIMPL; }
  205149. HRESULT __stdcall MoveElementTo (const OLECHAR*,IStorage*, const OLECHAR*, DWORD) { return E_NOTIMPL; }
  205150. HRESULT __stdcall Commit (DWORD) { return E_NOTIMPL; }
  205151. HRESULT __stdcall Revert() { return E_NOTIMPL; }
  205152. HRESULT __stdcall EnumElements (DWORD, void*, DWORD, IEnumSTATSTG**) { return E_NOTIMPL; }
  205153. HRESULT __stdcall DestroyElement (const OLECHAR*) { return E_NOTIMPL; }
  205154. HRESULT __stdcall RenameElement (const WCHAR*, const WCHAR*) { return E_NOTIMPL; }
  205155. HRESULT __stdcall SetElementTimes (const WCHAR*, FILETIME const*, FILETIME const*, FILETIME const*) { return E_NOTIMPL; }
  205156. HRESULT __stdcall SetClass (REFCLSID) { return S_OK; }
  205157. HRESULT __stdcall SetStateBits (DWORD, DWORD) { return E_NOTIMPL; }
  205158. HRESULT __stdcall Stat (STATSTG*, DWORD) { return E_NOTIMPL; }
  205159. juce_UseDebuggingNewOperator
  205160. };
  205161. class JuceOleInPlaceFrame : public ComBaseClassHelper <IOleInPlaceFrame>
  205162. {
  205163. HWND window;
  205164. public:
  205165. JuceOleInPlaceFrame (HWND window_) : window (window_) {}
  205166. ~JuceOleInPlaceFrame() {}
  205167. HRESULT __stdcall GetWindow (HWND* lphwnd) { *lphwnd = window; return S_OK; }
  205168. HRESULT __stdcall ContextSensitiveHelp (BOOL) { return E_NOTIMPL; }
  205169. HRESULT __stdcall GetBorder (LPRECT) { return E_NOTIMPL; }
  205170. HRESULT __stdcall RequestBorderSpace (LPCBORDERWIDTHS) { return E_NOTIMPL; }
  205171. HRESULT __stdcall SetBorderSpace (LPCBORDERWIDTHS) { return E_NOTIMPL; }
  205172. HRESULT __stdcall SetActiveObject (IOleInPlaceActiveObject*, LPCOLESTR) { return S_OK; }
  205173. HRESULT __stdcall InsertMenus (HMENU, LPOLEMENUGROUPWIDTHS) { return E_NOTIMPL; }
  205174. HRESULT __stdcall SetMenu (HMENU, HOLEMENU, HWND) { return S_OK; }
  205175. HRESULT __stdcall RemoveMenus (HMENU) { return E_NOTIMPL; }
  205176. HRESULT __stdcall SetStatusText (LPCOLESTR) { return S_OK; }
  205177. HRESULT __stdcall EnableModeless (BOOL) { return S_OK; }
  205178. HRESULT __stdcall TranslateAccelerator(LPMSG, WORD) { return E_NOTIMPL; }
  205179. juce_UseDebuggingNewOperator
  205180. };
  205181. class JuceIOleInPlaceSite : public ComBaseClassHelper <IOleInPlaceSite>
  205182. {
  205183. HWND window;
  205184. JuceOleInPlaceFrame* frame;
  205185. public:
  205186. JuceIOleInPlaceSite (HWND window_)
  205187. : window (window_),
  205188. frame (new JuceOleInPlaceFrame (window))
  205189. {}
  205190. ~JuceIOleInPlaceSite()
  205191. {
  205192. frame->Release();
  205193. }
  205194. HRESULT __stdcall GetWindow (HWND* lphwnd) { *lphwnd = window; return S_OK; }
  205195. HRESULT __stdcall ContextSensitiveHelp (BOOL) { return E_NOTIMPL; }
  205196. HRESULT __stdcall CanInPlaceActivate() { return S_OK; }
  205197. HRESULT __stdcall OnInPlaceActivate() { return S_OK; }
  205198. HRESULT __stdcall OnUIActivate() { return S_OK; }
  205199. HRESULT __stdcall GetWindowContext (LPOLEINPLACEFRAME* lplpFrame, LPOLEINPLACEUIWINDOW* lplpDoc, LPRECT, LPRECT, LPOLEINPLACEFRAMEINFO lpFrameInfo)
  205200. {
  205201. *lplpFrame = frame;
  205202. *lplpDoc = 0;
  205203. lpFrameInfo->fMDIApp = FALSE;
  205204. lpFrameInfo->hwndFrame = window;
  205205. lpFrameInfo->haccel = 0;
  205206. lpFrameInfo->cAccelEntries = 0;
  205207. return S_OK;
  205208. }
  205209. HRESULT __stdcall Scroll (SIZE) { return E_NOTIMPL; }
  205210. HRESULT __stdcall OnUIDeactivate (BOOL) { return S_OK; }
  205211. HRESULT __stdcall OnInPlaceDeactivate() { return S_OK; }
  205212. HRESULT __stdcall DiscardUndoState() { return E_NOTIMPL; }
  205213. HRESULT __stdcall DeactivateAndUndo() { return E_NOTIMPL; }
  205214. HRESULT __stdcall OnPosRectChange (LPCRECT) { return S_OK; }
  205215. juce_UseDebuggingNewOperator
  205216. };
  205217. class JuceIOleClientSite : public ComBaseClassHelper <IOleClientSite>
  205218. {
  205219. JuceIOleInPlaceSite* inplaceSite;
  205220. public:
  205221. JuceIOleClientSite (HWND window)
  205222. : inplaceSite (new JuceIOleInPlaceSite (window))
  205223. {}
  205224. ~JuceIOleClientSite()
  205225. {
  205226. inplaceSite->Release();
  205227. }
  205228. HRESULT __stdcall QueryInterface (REFIID type, void __RPC_FAR* __RPC_FAR* result)
  205229. {
  205230. if (type == IID_IOleInPlaceSite)
  205231. {
  205232. inplaceSite->AddRef();
  205233. *result = static_cast <IOleInPlaceSite*> (inplaceSite);
  205234. return S_OK;
  205235. }
  205236. return ComBaseClassHelper <IOleClientSite>::QueryInterface (type, result);
  205237. }
  205238. HRESULT __stdcall SaveObject() { return E_NOTIMPL; }
  205239. HRESULT __stdcall GetMoniker (DWORD, DWORD, IMoniker**) { return E_NOTIMPL; }
  205240. HRESULT __stdcall GetContainer (LPOLECONTAINER* ppContainer) { *ppContainer = 0; return E_NOINTERFACE; }
  205241. HRESULT __stdcall ShowObject() { return S_OK; }
  205242. HRESULT __stdcall OnShowWindow (BOOL) { return E_NOTIMPL; }
  205243. HRESULT __stdcall RequestNewObjectLayout() { return E_NOTIMPL; }
  205244. juce_UseDebuggingNewOperator
  205245. };
  205246. static VoidArray activeXComps;
  205247. static HWND getHWND (const ActiveXControlComponent* const component)
  205248. {
  205249. HWND hwnd = 0;
  205250. const IID iid = IID_IOleWindow;
  205251. IOleWindow* const window = (IOleWindow*) component->queryInterface (&iid);
  205252. if (window != 0)
  205253. {
  205254. window->GetWindow (&hwnd);
  205255. window->Release();
  205256. }
  205257. return hwnd;
  205258. }
  205259. static void offerActiveXMouseEventToPeer (ComponentPeer* const peer, HWND hwnd, UINT message, LPARAM lParam)
  205260. {
  205261. RECT activeXRect, peerRect;
  205262. GetWindowRect (hwnd, &activeXRect);
  205263. GetWindowRect ((HWND) peer->getNativeHandle(), &peerRect);
  205264. const Point<int> mousePos (GET_X_LPARAM (lParam) + activeXRect.left - peerRect.left,
  205265. GET_Y_LPARAM (lParam) + activeXRect.top - peerRect.top);
  205266. const int64 mouseEventTime = Win32ComponentPeer::getMouseEventTime();
  205267. ModifierKeys::getCurrentModifiersRealtime(); // to update the mouse button flags
  205268. switch (message)
  205269. {
  205270. case WM_MOUSEMOVE:
  205271. case WM_LBUTTONDOWN:
  205272. case WM_MBUTTONDOWN:
  205273. case WM_RBUTTONDOWN:
  205274. case WM_LBUTTONUP:
  205275. case WM_MBUTTONUP:
  205276. case WM_RBUTTONUP:
  205277. peer->handleMouseEvent (0, mousePos, Win32ComponentPeer::currentModifiers, mouseEventTime);
  205278. break;
  205279. default:
  205280. break;
  205281. }
  205282. }
  205283. }
  205284. class ActiveXControlComponent::Pimpl : public ComponentMovementWatcher
  205285. {
  205286. ActiveXControlComponent* const owner;
  205287. bool wasShowing;
  205288. public:
  205289. HWND controlHWND;
  205290. IStorage* storage;
  205291. IOleClientSite* clientSite;
  205292. IOleObject* control;
  205293. Pimpl (HWND hwnd, ActiveXControlComponent* const owner_)
  205294. : ComponentMovementWatcher (owner_),
  205295. owner (owner_),
  205296. wasShowing (owner_ != 0 && owner_->isShowing()),
  205297. controlHWND (0),
  205298. storage (new ActiveXHelpers::JuceIStorage()),
  205299. clientSite (new ActiveXHelpers::JuceIOleClientSite (hwnd)),
  205300. control (0)
  205301. {
  205302. }
  205303. ~Pimpl()
  205304. {
  205305. if (control != 0)
  205306. {
  205307. control->Close (OLECLOSE_NOSAVE);
  205308. control->Release();
  205309. }
  205310. clientSite->Release();
  205311. storage->Release();
  205312. }
  205313. void componentMovedOrResized (bool /*wasMoved*/, bool /*wasResized*/)
  205314. {
  205315. Component* const topComp = owner->getTopLevelComponent();
  205316. if (topComp->getPeer() != 0)
  205317. {
  205318. const Point<int> pos (owner->relativePositionToOtherComponent (topComp, Point<int>()));
  205319. owner->setControlBounds (Rectangle<int> (pos.getX(), pos.getY(), owner->getWidth(), owner->getHeight()));
  205320. }
  205321. }
  205322. void componentPeerChanged()
  205323. {
  205324. const bool isShowingNow = owner->isShowing();
  205325. if (wasShowing != isShowingNow)
  205326. {
  205327. wasShowing = isShowingNow;
  205328. owner->setControlVisible (isShowingNow);
  205329. }
  205330. componentMovedOrResized (true, true);
  205331. }
  205332. void componentVisibilityChanged (Component&)
  205333. {
  205334. componentPeerChanged();
  205335. }
  205336. // intercepts events going to an activeX control, so we can sneakily use the mouse events
  205337. static LRESULT CALLBACK activeXHookWndProc (HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam)
  205338. {
  205339. for (int i = ActiveXHelpers::activeXComps.size(); --i >= 0;)
  205340. {
  205341. const ActiveXControlComponent* const ax
  205342. = static_cast <const ActiveXControlComponent*> (ActiveXHelpers::activeXComps.getUnchecked(i));
  205343. if (ax->control != 0 && ax->control->controlHWND == hwnd)
  205344. {
  205345. switch (message)
  205346. {
  205347. case WM_MOUSEMOVE:
  205348. case WM_LBUTTONDOWN:
  205349. case WM_MBUTTONDOWN:
  205350. case WM_RBUTTONDOWN:
  205351. case WM_LBUTTONUP:
  205352. case WM_MBUTTONUP:
  205353. case WM_RBUTTONUP:
  205354. case WM_LBUTTONDBLCLK:
  205355. case WM_MBUTTONDBLCLK:
  205356. case WM_RBUTTONDBLCLK:
  205357. if (ax->isShowing())
  205358. {
  205359. ComponentPeer* const peer = ax->getPeer();
  205360. if (peer != 0)
  205361. {
  205362. ActiveXHelpers::offerActiveXMouseEventToPeer (peer, hwnd, message, lParam);
  205363. if (! ax->areMouseEventsAllowed())
  205364. return 0;
  205365. }
  205366. }
  205367. break;
  205368. default:
  205369. break;
  205370. }
  205371. return CallWindowProc ((WNDPROC) ax->originalWndProc, hwnd, message, wParam, lParam);
  205372. }
  205373. }
  205374. return DefWindowProc (hwnd, message, wParam, lParam);
  205375. }
  205376. };
  205377. ActiveXControlComponent::ActiveXControlComponent()
  205378. : originalWndProc (0),
  205379. mouseEventsAllowed (true)
  205380. {
  205381. ActiveXHelpers::activeXComps.add (this);
  205382. }
  205383. ActiveXControlComponent::~ActiveXControlComponent()
  205384. {
  205385. deleteControl();
  205386. ActiveXHelpers::activeXComps.removeValue (this);
  205387. }
  205388. void ActiveXControlComponent::paint (Graphics& g)
  205389. {
  205390. if (control == 0)
  205391. g.fillAll (Colours::lightgrey);
  205392. }
  205393. bool ActiveXControlComponent::createControl (const void* controlIID)
  205394. {
  205395. deleteControl();
  205396. ComponentPeer* const peer = getPeer();
  205397. // the component must have already been added to a real window when you call this!
  205398. jassert (dynamic_cast <Win32ComponentPeer*> (peer) != 0);
  205399. if (dynamic_cast <Win32ComponentPeer*> (peer) != 0)
  205400. {
  205401. const Point<int> pos (relativePositionToOtherComponent (getTopLevelComponent(), Point<int>()));
  205402. HWND hwnd = (HWND) peer->getNativeHandle();
  205403. ScopedPointer<Pimpl> newControl (new Pimpl (hwnd, this));
  205404. HRESULT hr;
  205405. if ((hr = OleCreate (*(const IID*) controlIID, IID_IOleObject, 1 /*OLERENDER_DRAW*/, 0,
  205406. newControl->clientSite, newControl->storage,
  205407. (void**) &(newControl->control))) == S_OK)
  205408. {
  205409. newControl->control->SetHostNames (L"Juce", 0);
  205410. if (OleSetContainedObject (newControl->control, TRUE) == S_OK)
  205411. {
  205412. RECT rect;
  205413. rect.left = pos.getX();
  205414. rect.top = pos.getY();
  205415. rect.right = pos.getX() + getWidth();
  205416. rect.bottom = pos.getY() + getHeight();
  205417. if (newControl->control->DoVerb (OLEIVERB_SHOW, 0, newControl->clientSite, 0, hwnd, &rect) == S_OK)
  205418. {
  205419. control = newControl;
  205420. setControlBounds (Rectangle<int> (pos.getX(), pos.getY(), getWidth(), getHeight()));
  205421. control->controlHWND = ActiveXHelpers::getHWND (this);
  205422. if (control->controlHWND != 0)
  205423. {
  205424. originalWndProc = (void*) (pointer_sized_int) GetWindowLongPtr ((HWND) control->controlHWND, GWLP_WNDPROC);
  205425. SetWindowLongPtr ((HWND) control->controlHWND, GWLP_WNDPROC, (LONG_PTR) Pimpl::activeXHookWndProc);
  205426. }
  205427. return true;
  205428. }
  205429. }
  205430. }
  205431. }
  205432. return false;
  205433. }
  205434. void ActiveXControlComponent::deleteControl()
  205435. {
  205436. control = 0;
  205437. originalWndProc = 0;
  205438. }
  205439. void* ActiveXControlComponent::queryInterface (const void* iid) const
  205440. {
  205441. void* result = 0;
  205442. if (control != 0 && control->control != 0
  205443. && SUCCEEDED (control->control->QueryInterface (*(const IID*) iid, &result)))
  205444. return result;
  205445. return 0;
  205446. }
  205447. void ActiveXControlComponent::setControlBounds (const Rectangle<int>& newBounds) const
  205448. {
  205449. if (control->controlHWND != 0)
  205450. MoveWindow (control->controlHWND, newBounds.getX(), newBounds.getY(), newBounds.getWidth(), newBounds.getHeight(), TRUE);
  205451. }
  205452. void ActiveXControlComponent::setControlVisible (const bool shouldBeVisible) const
  205453. {
  205454. if (control->controlHWND != 0)
  205455. ShowWindow (control->controlHWND, shouldBeVisible ? SW_SHOWNA : SW_HIDE);
  205456. }
  205457. void ActiveXControlComponent::setMouseEventsAllowed (const bool eventsCanReachControl)
  205458. {
  205459. mouseEventsAllowed = eventsCanReachControl;
  205460. }
  205461. #endif
  205462. /*** End of inlined file: juce_win32_ActiveXComponent.cpp ***/
  205463. /*** Start of inlined file: juce_win32_QuickTimeMovieComponent.cpp ***/
  205464. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  205465. // compiled on its own).
  205466. #if JUCE_INCLUDED_FILE && JUCE_QUICKTIME
  205467. using namespace QTOLibrary;
  205468. using namespace QTOControlLib;
  205469. bool juce_OpenQuickTimeMovieFromStream (InputStream* input, Movie& movie, Handle& dataHandle);
  205470. static bool isQTAvailable = false;
  205471. class QuickTimeMovieComponent::Pimpl
  205472. {
  205473. public:
  205474. Pimpl() : dataHandle (0)
  205475. {
  205476. }
  205477. ~Pimpl()
  205478. {
  205479. clearHandle();
  205480. }
  205481. void clearHandle()
  205482. {
  205483. if (dataHandle != 0)
  205484. {
  205485. DisposeHandle (dataHandle);
  205486. dataHandle = 0;
  205487. }
  205488. }
  205489. IQTControlPtr qtControl;
  205490. IQTMoviePtr qtMovie;
  205491. Handle dataHandle;
  205492. };
  205493. QuickTimeMovieComponent::QuickTimeMovieComponent()
  205494. : movieLoaded (false),
  205495. controllerVisible (true)
  205496. {
  205497. pimpl = new Pimpl();
  205498. setMouseEventsAllowed (false);
  205499. }
  205500. QuickTimeMovieComponent::~QuickTimeMovieComponent()
  205501. {
  205502. closeMovie();
  205503. pimpl->qtControl = 0;
  205504. deleteControl();
  205505. pimpl = 0;
  205506. }
  205507. bool QuickTimeMovieComponent::isQuickTimeAvailable() throw()
  205508. {
  205509. if (! isQTAvailable)
  205510. isQTAvailable = (InitializeQTML (0) == noErr) && (EnterMovies() == noErr);
  205511. return isQTAvailable;
  205512. }
  205513. void QuickTimeMovieComponent::createControlIfNeeded()
  205514. {
  205515. if (isShowing() && ! isControlCreated())
  205516. {
  205517. const IID qtIID = __uuidof (QTControl);
  205518. if (createControl (&qtIID))
  205519. {
  205520. const IID qtInterfaceIID = __uuidof (IQTControl);
  205521. pimpl->qtControl = (IQTControl*) queryInterface (&qtInterfaceIID);
  205522. if (pimpl->qtControl != 0)
  205523. {
  205524. pimpl->qtControl->Release(); // it has one ref too many at this point
  205525. pimpl->qtControl->QuickTimeInitialize();
  205526. pimpl->qtControl->PutSizing (qtMovieFitsControl);
  205527. if (movieFile != File::nonexistent)
  205528. loadMovie (movieFile, controllerVisible);
  205529. }
  205530. }
  205531. }
  205532. }
  205533. bool QuickTimeMovieComponent::isControlCreated() const
  205534. {
  205535. return isControlOpen();
  205536. }
  205537. bool QuickTimeMovieComponent::loadMovie (InputStream* movieStream,
  205538. const bool isControllerVisible)
  205539. {
  205540. const ScopedPointer<InputStream> movieStreamDeleter (movieStream);
  205541. movieFile = File::nonexistent;
  205542. movieLoaded = false;
  205543. pimpl->qtMovie = 0;
  205544. controllerVisible = isControllerVisible;
  205545. createControlIfNeeded();
  205546. if (isControlCreated())
  205547. {
  205548. if (pimpl->qtControl != 0)
  205549. {
  205550. pimpl->qtControl->Put_MovieHandle (0);
  205551. pimpl->clearHandle();
  205552. Movie movie;
  205553. if (juce_OpenQuickTimeMovieFromStream (movieStream, movie, pimpl->dataHandle))
  205554. {
  205555. pimpl->qtControl->Put_MovieHandle ((long) (pointer_sized_int) movie);
  205556. pimpl->qtMovie = pimpl->qtControl->GetMovie();
  205557. if (pimpl->qtMovie != 0)
  205558. pimpl->qtMovie->PutMovieControllerType (isControllerVisible ? qtMovieControllerTypeStandard
  205559. : qtMovieControllerTypeNone);
  205560. }
  205561. if (movie == 0)
  205562. pimpl->clearHandle();
  205563. }
  205564. movieLoaded = (pimpl->qtMovie != 0);
  205565. }
  205566. else
  205567. {
  205568. // You're trying to open a movie when the control hasn't yet been created, probably because
  205569. // you've not yet added this component to a Window and made the whole component hierarchy visible.
  205570. jassertfalse
  205571. }
  205572. return movieLoaded;
  205573. }
  205574. void QuickTimeMovieComponent::closeMovie()
  205575. {
  205576. stop();
  205577. movieFile = File::nonexistent;
  205578. movieLoaded = false;
  205579. pimpl->qtMovie = 0;
  205580. if (pimpl->qtControl != 0)
  205581. pimpl->qtControl->Put_MovieHandle (0);
  205582. pimpl->clearHandle();
  205583. }
  205584. const File QuickTimeMovieComponent::getCurrentMovieFile() const
  205585. {
  205586. return movieFile;
  205587. }
  205588. bool QuickTimeMovieComponent::isMovieOpen() const
  205589. {
  205590. return movieLoaded;
  205591. }
  205592. double QuickTimeMovieComponent::getMovieDuration() const
  205593. {
  205594. if (pimpl->qtMovie != 0)
  205595. return pimpl->qtMovie->GetDuration() / (double) pimpl->qtMovie->GetTimeScale();
  205596. return 0.0;
  205597. }
  205598. void QuickTimeMovieComponent::getMovieNormalSize (int& width, int& height) const
  205599. {
  205600. if (pimpl->qtMovie != 0)
  205601. {
  205602. struct QTRECT r = pimpl->qtMovie->GetNaturalRect();
  205603. width = r.right - r.left;
  205604. height = r.bottom - r.top;
  205605. }
  205606. else
  205607. {
  205608. width = height = 0;
  205609. }
  205610. }
  205611. void QuickTimeMovieComponent::play()
  205612. {
  205613. if (pimpl->qtMovie != 0)
  205614. pimpl->qtMovie->Play();
  205615. }
  205616. void QuickTimeMovieComponent::stop()
  205617. {
  205618. if (pimpl->qtMovie != 0)
  205619. pimpl->qtMovie->Stop();
  205620. }
  205621. bool QuickTimeMovieComponent::isPlaying() const
  205622. {
  205623. return pimpl->qtMovie != 0 && pimpl->qtMovie->GetRate() != 0.0f;
  205624. }
  205625. void QuickTimeMovieComponent::setPosition (const double seconds)
  205626. {
  205627. if (pimpl->qtMovie != 0)
  205628. pimpl->qtMovie->PutTime ((long) (seconds * pimpl->qtMovie->GetTimeScale()));
  205629. }
  205630. double QuickTimeMovieComponent::getPosition() const
  205631. {
  205632. if (pimpl->qtMovie != 0)
  205633. return pimpl->qtMovie->GetTime() / (double) pimpl->qtMovie->GetTimeScale();
  205634. return 0.0;
  205635. }
  205636. void QuickTimeMovieComponent::setSpeed (const float newSpeed)
  205637. {
  205638. if (pimpl->qtMovie != 0)
  205639. pimpl->qtMovie->PutRate (newSpeed);
  205640. }
  205641. void QuickTimeMovieComponent::setMovieVolume (const float newVolume)
  205642. {
  205643. if (pimpl->qtMovie != 0)
  205644. {
  205645. pimpl->qtMovie->PutAudioVolume (newVolume);
  205646. pimpl->qtMovie->PutAudioMute (newVolume <= 0);
  205647. }
  205648. }
  205649. float QuickTimeMovieComponent::getMovieVolume() const
  205650. {
  205651. if (pimpl->qtMovie != 0)
  205652. return pimpl->qtMovie->GetAudioVolume();
  205653. return 0.0f;
  205654. }
  205655. void QuickTimeMovieComponent::setLooping (const bool shouldLoop)
  205656. {
  205657. if (pimpl->qtMovie != 0)
  205658. pimpl->qtMovie->PutLoop (shouldLoop);
  205659. }
  205660. bool QuickTimeMovieComponent::isLooping() const
  205661. {
  205662. return pimpl->qtMovie != 0 && pimpl->qtMovie->GetLoop();
  205663. }
  205664. bool QuickTimeMovieComponent::isControllerVisible() const
  205665. {
  205666. return controllerVisible;
  205667. }
  205668. void QuickTimeMovieComponent::parentHierarchyChanged()
  205669. {
  205670. createControlIfNeeded();
  205671. QTCompBaseClass::parentHierarchyChanged();
  205672. }
  205673. void QuickTimeMovieComponent::visibilityChanged()
  205674. {
  205675. createControlIfNeeded();
  205676. QTCompBaseClass::visibilityChanged();
  205677. }
  205678. void QuickTimeMovieComponent::paint (Graphics& g)
  205679. {
  205680. if (! isControlCreated())
  205681. g.fillAll (Colours::black);
  205682. }
  205683. static Handle createHandleDataRef (Handle dataHandle, const char* fileName)
  205684. {
  205685. Handle dataRef = 0;
  205686. OSStatus err = PtrToHand (&dataHandle, &dataRef, sizeof (Handle));
  205687. if (err == noErr)
  205688. {
  205689. Str255 suffix;
  205690. CharacterFunctions::copy ((char*) suffix, fileName, 128);
  205691. StringPtr name = suffix;
  205692. err = PtrAndHand (name, dataRef, name[0] + 1);
  205693. if (err == noErr)
  205694. {
  205695. long atoms[3];
  205696. atoms[0] = EndianU32_NtoB (3 * sizeof (long));
  205697. atoms[1] = EndianU32_NtoB (kDataRefExtensionMacOSFileType);
  205698. atoms[2] = EndianU32_NtoB (MovieFileType);
  205699. err = PtrAndHand (atoms, dataRef, 3 * sizeof (long));
  205700. if (err == noErr)
  205701. return dataRef;
  205702. }
  205703. DisposeHandle (dataRef);
  205704. }
  205705. return 0;
  205706. }
  205707. static CFStringRef juceStringToCFString (const String& s)
  205708. {
  205709. const int len = s.length();
  205710. const juce_wchar* const t = s;
  205711. HeapBlock <UniChar> temp (len + 2);
  205712. for (int i = 0; i <= len; ++i)
  205713. temp[i] = t[i];
  205714. return CFStringCreateWithCharacters (kCFAllocatorDefault, temp, len);
  205715. }
  205716. static bool openMovie (QTNewMoviePropertyElement* props, int prop, Movie& movie)
  205717. {
  205718. Boolean trueBool = true;
  205719. props[prop].propClass = kQTPropertyClass_MovieInstantiation;
  205720. props[prop].propID = kQTMovieInstantiationPropertyID_DontResolveDataRefs;
  205721. props[prop].propValueSize = sizeof (trueBool);
  205722. props[prop].propValueAddress = &trueBool;
  205723. ++prop;
  205724. props[prop].propClass = kQTPropertyClass_MovieInstantiation;
  205725. props[prop].propID = kQTMovieInstantiationPropertyID_AsyncOK;
  205726. props[prop].propValueSize = sizeof (trueBool);
  205727. props[prop].propValueAddress = &trueBool;
  205728. ++prop;
  205729. Boolean isActive = true;
  205730. props[prop].propClass = kQTPropertyClass_NewMovieProperty;
  205731. props[prop].propID = kQTNewMoviePropertyID_Active;
  205732. props[prop].propValueSize = sizeof (isActive);
  205733. props[prop].propValueAddress = &isActive;
  205734. ++prop;
  205735. MacSetPort (0);
  205736. jassert (prop <= 5);
  205737. OSStatus err = NewMovieFromProperties (prop, props, 0, 0, &movie);
  205738. return err == noErr;
  205739. }
  205740. bool juce_OpenQuickTimeMovieFromStream (InputStream* input, Movie& movie, Handle& dataHandle)
  205741. {
  205742. if (input == 0)
  205743. return false;
  205744. dataHandle = 0;
  205745. bool ok = false;
  205746. QTNewMoviePropertyElement props[5];
  205747. zeromem (props, sizeof (props));
  205748. int prop = 0;
  205749. DataReferenceRecord dr;
  205750. props[prop].propClass = kQTPropertyClass_DataLocation;
  205751. props[prop].propID = kQTDataLocationPropertyID_DataReference;
  205752. props[prop].propValueSize = sizeof (dr);
  205753. props[prop].propValueAddress = &dr;
  205754. ++prop;
  205755. FileInputStream* const fin = dynamic_cast <FileInputStream*> (input);
  205756. if (fin != 0)
  205757. {
  205758. CFStringRef filePath = juceStringToCFString (fin->getFile().getFullPathName());
  205759. QTNewDataReferenceFromFullPathCFString (filePath, (QTPathStyle) kQTNativeDefaultPathStyle, 0,
  205760. &dr.dataRef, &dr.dataRefType);
  205761. ok = openMovie (props, prop, movie);
  205762. DisposeHandle (dr.dataRef);
  205763. CFRelease (filePath);
  205764. }
  205765. else
  205766. {
  205767. // sanity-check because this currently needs to load the whole stream into memory..
  205768. jassert (input->getTotalLength() < 50 * 1024 * 1024);
  205769. dataHandle = NewHandle ((Size) input->getTotalLength());
  205770. HLock (dataHandle);
  205771. // read the entire stream into memory - this is a pain, but can't get it to work
  205772. // properly using a custom callback to supply the data.
  205773. input->read (*dataHandle, (int) input->getTotalLength());
  205774. HUnlock (dataHandle);
  205775. // different types to get QT to try. (We should really be a bit smarter here by
  205776. // working out in advance which one the stream contains, rather than just trying
  205777. // each one)
  205778. const char* const suffixesToTry[] = { "\04.mov", "\04.mp3",
  205779. "\04.avi", "\04.m4a" };
  205780. for (int i = 0; i < numElementsInArray (suffixesToTry) && ! ok; ++i)
  205781. {
  205782. /* // this fails for some bizarre reason - it can be bodged to work with
  205783. // movies, but can't seem to do it for other file types..
  205784. QTNewMovieUserProcRecord procInfo;
  205785. procInfo.getMovieUserProc = NewGetMovieUPP (readMovieStreamProc);
  205786. procInfo.getMovieUserProcRefcon = this;
  205787. procInfo.defaultDataRef.dataRef = dataRef;
  205788. procInfo.defaultDataRef.dataRefType = HandleDataHandlerSubType;
  205789. props[prop].propClass = kQTPropertyClass_DataLocation;
  205790. props[prop].propID = kQTDataLocationPropertyID_MovieUserProc;
  205791. props[prop].propValueSize = sizeof (procInfo);
  205792. props[prop].propValueAddress = (void*) &procInfo;
  205793. ++prop; */
  205794. dr.dataRef = createHandleDataRef (dataHandle, suffixesToTry [i]);
  205795. dr.dataRefType = HandleDataHandlerSubType;
  205796. ok = openMovie (props, prop, movie);
  205797. DisposeHandle (dr.dataRef);
  205798. }
  205799. }
  205800. return ok;
  205801. }
  205802. bool QuickTimeMovieComponent::loadMovie (const File& movieFile_,
  205803. const bool isControllerVisible)
  205804. {
  205805. const bool ok = loadMovie (static_cast <InputStream*> (movieFile_.createInputStream()), isControllerVisible);
  205806. movieFile = movieFile_;
  205807. return ok;
  205808. }
  205809. bool QuickTimeMovieComponent::loadMovie (const URL& movieURL,
  205810. const bool isControllerVisible)
  205811. {
  205812. return loadMovie (static_cast <InputStream*> (movieURL.createInputStream (false)), isControllerVisible);
  205813. }
  205814. void QuickTimeMovieComponent::goToStart()
  205815. {
  205816. setPosition (0.0);
  205817. }
  205818. void QuickTimeMovieComponent::setBoundsWithCorrectAspectRatio (const Rectangle<int>& spaceToFitWithin,
  205819. const RectanglePlacement& placement)
  205820. {
  205821. int normalWidth, normalHeight;
  205822. getMovieNormalSize (normalWidth, normalHeight);
  205823. if (normalWidth > 0 && normalHeight > 0 && ! spaceToFitWithin.isEmpty())
  205824. {
  205825. double x = 0.0, y = 0.0, w = normalWidth, h = normalHeight;
  205826. placement.applyTo (x, y, w, h,
  205827. spaceToFitWithin.getX(), spaceToFitWithin.getY(),
  205828. spaceToFitWithin.getWidth(), spaceToFitWithin.getHeight());
  205829. if (w > 0 && h > 0)
  205830. {
  205831. setBounds (roundToInt (x), roundToInt (y),
  205832. roundToInt (w), roundToInt (h));
  205833. }
  205834. }
  205835. else
  205836. {
  205837. setBounds (spaceToFitWithin);
  205838. }
  205839. }
  205840. #endif
  205841. /*** End of inlined file: juce_win32_QuickTimeMovieComponent.cpp ***/
  205842. /*** Start of inlined file: juce_win32_WebBrowserComponent.cpp ***/
  205843. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  205844. // compiled on its own).
  205845. #if JUCE_INCLUDED_FILE && JUCE_WEB_BROWSER
  205846. class WebBrowserComponentInternal : public ActiveXControlComponent
  205847. {
  205848. public:
  205849. WebBrowserComponentInternal()
  205850. : browser (0),
  205851. connectionPoint (0),
  205852. adviseCookie (0)
  205853. {
  205854. }
  205855. ~WebBrowserComponentInternal()
  205856. {
  205857. if (connectionPoint != 0)
  205858. connectionPoint->Unadvise (adviseCookie);
  205859. if (browser != 0)
  205860. browser->Release();
  205861. }
  205862. void createBrowser()
  205863. {
  205864. createControl (&CLSID_WebBrowser);
  205865. browser = (IWebBrowser2*) queryInterface (&IID_IWebBrowser2);
  205866. IConnectionPointContainer* connectionPointContainer = (IConnectionPointContainer*) queryInterface (&IID_IConnectionPointContainer);
  205867. if (connectionPointContainer != 0)
  205868. {
  205869. connectionPointContainer->FindConnectionPoint (DIID_DWebBrowserEvents2,
  205870. &connectionPoint);
  205871. if (connectionPoint != 0)
  205872. {
  205873. WebBrowserComponent* const owner = dynamic_cast <WebBrowserComponent*> (getParentComponent());
  205874. jassert (owner != 0);
  205875. EventHandler* handler = new EventHandler (owner);
  205876. connectionPoint->Advise (handler, &adviseCookie);
  205877. handler->Release();
  205878. }
  205879. }
  205880. }
  205881. void goToURL (const String& url,
  205882. const StringArray* headers,
  205883. const MemoryBlock* postData)
  205884. {
  205885. if (browser != 0)
  205886. {
  205887. LPSAFEARRAY sa = 0;
  205888. VARIANT flags, frame, postDataVar, headersVar; // (_variant_t isn't available in all compilers)
  205889. VariantInit (&flags);
  205890. VariantInit (&frame);
  205891. VariantInit (&postDataVar);
  205892. VariantInit (&headersVar);
  205893. if (headers != 0)
  205894. {
  205895. V_VT (&headersVar) = VT_BSTR;
  205896. V_BSTR (&headersVar) = SysAllocString ((const OLECHAR*) headers->joinIntoString ("\r\n"));
  205897. }
  205898. if (postData != 0 && postData->getSize() > 0)
  205899. {
  205900. LPSAFEARRAY sa = SafeArrayCreateVector (VT_UI1, 0, postData->getSize());
  205901. if (sa != 0)
  205902. {
  205903. void* data = 0;
  205904. SafeArrayAccessData (sa, &data);
  205905. jassert (data != 0);
  205906. if (data != 0)
  205907. {
  205908. postData->copyTo (data, 0, postData->getSize());
  205909. SafeArrayUnaccessData (sa);
  205910. VARIANT postDataVar2;
  205911. VariantInit (&postDataVar2);
  205912. V_VT (&postDataVar2) = VT_ARRAY | VT_UI1;
  205913. V_ARRAY (&postDataVar2) = sa;
  205914. postDataVar = postDataVar2;
  205915. }
  205916. }
  205917. }
  205918. browser->Navigate ((BSTR) (const OLECHAR*) url,
  205919. &flags, &frame,
  205920. &postDataVar, &headersVar);
  205921. if (sa != 0)
  205922. SafeArrayDestroy (sa);
  205923. VariantClear (&flags);
  205924. VariantClear (&frame);
  205925. VariantClear (&postDataVar);
  205926. VariantClear (&headersVar);
  205927. }
  205928. }
  205929. IWebBrowser2* browser;
  205930. juce_UseDebuggingNewOperator
  205931. private:
  205932. IConnectionPoint* connectionPoint;
  205933. DWORD adviseCookie;
  205934. class EventHandler : public ComBaseClassHelper <IDispatch>,
  205935. public ComponentMovementWatcher
  205936. {
  205937. public:
  205938. EventHandler (WebBrowserComponent* owner_)
  205939. : ComponentMovementWatcher (owner_),
  205940. owner (owner_)
  205941. {
  205942. }
  205943. ~EventHandler()
  205944. {
  205945. }
  205946. HRESULT __stdcall GetTypeInfoCount (UINT __RPC_FAR*) { return E_NOTIMPL; }
  205947. HRESULT __stdcall GetTypeInfo (UINT, LCID, ITypeInfo __RPC_FAR *__RPC_FAR*) { return E_NOTIMPL; }
  205948. HRESULT __stdcall GetIDsOfNames (REFIID, LPOLESTR __RPC_FAR*, UINT, LCID, DISPID __RPC_FAR*) { return E_NOTIMPL; }
  205949. HRESULT __stdcall Invoke (DISPID dispIdMember, REFIID /*riid*/, LCID /*lcid*/,
  205950. WORD /*wFlags*/, DISPPARAMS __RPC_FAR* pDispParams,
  205951. VARIANT __RPC_FAR* /*pVarResult*/, EXCEPINFO __RPC_FAR* /*pExcepInfo*/,
  205952. UINT __RPC_FAR* /*puArgErr*/)
  205953. {
  205954. switch (dispIdMember)
  205955. {
  205956. case DISPID_BEFORENAVIGATE2:
  205957. {
  205958. VARIANT* const vurl = pDispParams->rgvarg[5].pvarVal;
  205959. String url;
  205960. if ((vurl->vt & VT_BYREF) != 0)
  205961. url = *vurl->pbstrVal;
  205962. else
  205963. url = vurl->bstrVal;
  205964. *pDispParams->rgvarg->pboolVal
  205965. = owner->pageAboutToLoad (url) ? VARIANT_FALSE
  205966. : VARIANT_TRUE;
  205967. return S_OK;
  205968. }
  205969. default:
  205970. break;
  205971. }
  205972. return E_NOTIMPL;
  205973. }
  205974. void componentMovedOrResized (bool /*wasMoved*/, bool /*wasResized*/) {}
  205975. void componentPeerChanged() {}
  205976. void componentVisibilityChanged (Component&)
  205977. {
  205978. owner->visibilityChanged();
  205979. }
  205980. juce_UseDebuggingNewOperator
  205981. private:
  205982. WebBrowserComponent* const owner;
  205983. EventHandler (const EventHandler&);
  205984. EventHandler& operator= (const EventHandler&);
  205985. };
  205986. };
  205987. WebBrowserComponent::WebBrowserComponent (const bool unloadPageWhenBrowserIsHidden_)
  205988. : browser (0),
  205989. blankPageShown (false),
  205990. unloadPageWhenBrowserIsHidden (unloadPageWhenBrowserIsHidden_)
  205991. {
  205992. setOpaque (true);
  205993. addAndMakeVisible (browser = new WebBrowserComponentInternal());
  205994. }
  205995. WebBrowserComponent::~WebBrowserComponent()
  205996. {
  205997. delete browser;
  205998. }
  205999. void WebBrowserComponent::goToURL (const String& url,
  206000. const StringArray* headers,
  206001. const MemoryBlock* postData)
  206002. {
  206003. lastURL = url;
  206004. lastHeaders.clear();
  206005. if (headers != 0)
  206006. lastHeaders = *headers;
  206007. lastPostData.setSize (0);
  206008. if (postData != 0)
  206009. lastPostData = *postData;
  206010. blankPageShown = false;
  206011. browser->goToURL (url, headers, postData);
  206012. }
  206013. void WebBrowserComponent::stop()
  206014. {
  206015. if (browser->browser != 0)
  206016. browser->browser->Stop();
  206017. }
  206018. void WebBrowserComponent::goBack()
  206019. {
  206020. lastURL = String::empty;
  206021. blankPageShown = false;
  206022. if (browser->browser != 0)
  206023. browser->browser->GoBack();
  206024. }
  206025. void WebBrowserComponent::goForward()
  206026. {
  206027. lastURL = String::empty;
  206028. if (browser->browser != 0)
  206029. browser->browser->GoForward();
  206030. }
  206031. void WebBrowserComponent::refresh()
  206032. {
  206033. if (browser->browser != 0)
  206034. browser->browser->Refresh();
  206035. }
  206036. void WebBrowserComponent::paint (Graphics& g)
  206037. {
  206038. if (browser->browser == 0)
  206039. g.fillAll (Colours::white);
  206040. }
  206041. void WebBrowserComponent::checkWindowAssociation()
  206042. {
  206043. if (isShowing())
  206044. {
  206045. if (browser->browser == 0 && getPeer() != 0)
  206046. {
  206047. browser->createBrowser();
  206048. reloadLastURL();
  206049. }
  206050. else
  206051. {
  206052. if (blankPageShown)
  206053. goBack();
  206054. }
  206055. }
  206056. else
  206057. {
  206058. if (browser != 0 && unloadPageWhenBrowserIsHidden && ! blankPageShown)
  206059. {
  206060. // when the component becomes invisible, some stuff like flash
  206061. // carries on playing audio, so we need to force it onto a blank
  206062. // page to avoid this..
  206063. blankPageShown = true;
  206064. browser->goToURL ("about:blank", 0, 0);
  206065. }
  206066. }
  206067. }
  206068. void WebBrowserComponent::reloadLastURL()
  206069. {
  206070. if (lastURL.isNotEmpty())
  206071. {
  206072. goToURL (lastURL, &lastHeaders, &lastPostData);
  206073. lastURL = String::empty;
  206074. }
  206075. }
  206076. void WebBrowserComponent::parentHierarchyChanged()
  206077. {
  206078. checkWindowAssociation();
  206079. }
  206080. void WebBrowserComponent::resized()
  206081. {
  206082. browser->setSize (getWidth(), getHeight());
  206083. }
  206084. void WebBrowserComponent::visibilityChanged()
  206085. {
  206086. checkWindowAssociation();
  206087. }
  206088. bool WebBrowserComponent::pageAboutToLoad (const String&)
  206089. {
  206090. return true;
  206091. }
  206092. #endif
  206093. /*** End of inlined file: juce_win32_WebBrowserComponent.cpp ***/
  206094. /*** Start of inlined file: juce_win32_OpenGLComponent.cpp ***/
  206095. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  206096. // compiled on its own).
  206097. #if JUCE_INCLUDED_FILE && JUCE_OPENGL
  206098. #define WGL_EXT_FUNCTION_INIT(extType, extFunc) \
  206099. ((extFunc = (extType) wglGetProcAddress (#extFunc)) != 0)
  206100. typedef const char* (WINAPI* PFNWGLGETEXTENSIONSSTRINGARBPROC) (HDC hdc);
  206101. typedef BOOL (WINAPI * PFNWGLGETPIXELFORMATATTRIBIVARBPROC) (HDC hdc, int iPixelFormat, int iLayerPlane, UINT nAttributes, const int *piAttributes, int *piValues);
  206102. typedef BOOL (WINAPI * PFNWGLCHOOSEPIXELFORMATARBPROC) (HDC hdc, const int* piAttribIList, const FLOAT *pfAttribFList, UINT nMaxFormats, int *piFormats, UINT *nNumFormats);
  206103. typedef BOOL (WINAPI * PFNWGLSWAPINTERVALEXTPROC) (int interval);
  206104. typedef int (WINAPI * PFNWGLGETSWAPINTERVALEXTPROC) (void);
  206105. #define WGL_NUMBER_PIXEL_FORMATS_ARB 0x2000
  206106. #define WGL_DRAW_TO_WINDOW_ARB 0x2001
  206107. #define WGL_ACCELERATION_ARB 0x2003
  206108. #define WGL_SWAP_METHOD_ARB 0x2007
  206109. #define WGL_SUPPORT_OPENGL_ARB 0x2010
  206110. #define WGL_PIXEL_TYPE_ARB 0x2013
  206111. #define WGL_DOUBLE_BUFFER_ARB 0x2011
  206112. #define WGL_COLOR_BITS_ARB 0x2014
  206113. #define WGL_RED_BITS_ARB 0x2015
  206114. #define WGL_GREEN_BITS_ARB 0x2017
  206115. #define WGL_BLUE_BITS_ARB 0x2019
  206116. #define WGL_ALPHA_BITS_ARB 0x201B
  206117. #define WGL_DEPTH_BITS_ARB 0x2022
  206118. #define WGL_STENCIL_BITS_ARB 0x2023
  206119. #define WGL_FULL_ACCELERATION_ARB 0x2027
  206120. #define WGL_ACCUM_RED_BITS_ARB 0x201E
  206121. #define WGL_ACCUM_GREEN_BITS_ARB 0x201F
  206122. #define WGL_ACCUM_BLUE_BITS_ARB 0x2020
  206123. #define WGL_ACCUM_ALPHA_BITS_ARB 0x2021
  206124. #define WGL_STEREO_ARB 0x2012
  206125. #define WGL_SAMPLE_BUFFERS_ARB 0x2041
  206126. #define WGL_SAMPLES_ARB 0x2042
  206127. #define WGL_TYPE_RGBA_ARB 0x202B
  206128. static void getWglExtensions (HDC dc, StringArray& result) throw()
  206129. {
  206130. PFNWGLGETEXTENSIONSSTRINGARBPROC wglGetExtensionsStringARB = 0;
  206131. if (WGL_EXT_FUNCTION_INIT (PFNWGLGETEXTENSIONSSTRINGARBPROC, wglGetExtensionsStringARB))
  206132. result.addTokens (String (wglGetExtensionsStringARB (dc)), false);
  206133. else
  206134. jassertfalse // If this fails, it may be because you didn't activate the openGL context
  206135. }
  206136. class WindowedGLContext : public OpenGLContext
  206137. {
  206138. public:
  206139. WindowedGLContext (Component* const component_,
  206140. HGLRC contextToShareWith,
  206141. const OpenGLPixelFormat& pixelFormat)
  206142. : renderContext (0),
  206143. nativeWindow (0),
  206144. dc (0),
  206145. component (component_)
  206146. {
  206147. jassert (component != 0);
  206148. createNativeWindow();
  206149. // Use a default pixel format that should be supported everywhere
  206150. PIXELFORMATDESCRIPTOR pfd;
  206151. zerostruct (pfd);
  206152. pfd.nSize = sizeof (pfd);
  206153. pfd.nVersion = 1;
  206154. pfd.dwFlags = PFD_DRAW_TO_WINDOW | PFD_SUPPORT_OPENGL | PFD_DOUBLEBUFFER;
  206155. pfd.iPixelType = PFD_TYPE_RGBA;
  206156. pfd.cColorBits = 24;
  206157. pfd.cDepthBits = 16;
  206158. const int format = ChoosePixelFormat (dc, &pfd);
  206159. if (format != 0)
  206160. SetPixelFormat (dc, format, &pfd);
  206161. renderContext = wglCreateContext (dc);
  206162. makeActive();
  206163. setPixelFormat (pixelFormat);
  206164. if (contextToShareWith != 0 && renderContext != 0)
  206165. wglShareLists (contextToShareWith, renderContext);
  206166. }
  206167. ~WindowedGLContext()
  206168. {
  206169. makeInactive();
  206170. wglDeleteContext (renderContext);
  206171. ReleaseDC ((HWND) nativeWindow->getNativeHandle(), dc);
  206172. delete nativeWindow;
  206173. }
  206174. bool makeActive() const throw()
  206175. {
  206176. jassert (renderContext != 0);
  206177. return wglMakeCurrent (dc, renderContext) != 0;
  206178. }
  206179. bool makeInactive() const throw()
  206180. {
  206181. return (! isActive()) || (wglMakeCurrent (0, 0) != 0);
  206182. }
  206183. bool isActive() const throw()
  206184. {
  206185. return wglGetCurrentContext() == renderContext;
  206186. }
  206187. const OpenGLPixelFormat getPixelFormat() const
  206188. {
  206189. OpenGLPixelFormat pf;
  206190. makeActive();
  206191. StringArray availableExtensions;
  206192. getWglExtensions (dc, availableExtensions);
  206193. fillInPixelFormatDetails (GetPixelFormat (dc), pf, availableExtensions);
  206194. return pf;
  206195. }
  206196. void* getRawContext() const throw()
  206197. {
  206198. return renderContext;
  206199. }
  206200. bool setPixelFormat (const OpenGLPixelFormat& pixelFormat)
  206201. {
  206202. makeActive();
  206203. PIXELFORMATDESCRIPTOR pfd;
  206204. zerostruct (pfd);
  206205. pfd.nSize = sizeof (pfd);
  206206. pfd.nVersion = 1;
  206207. pfd.dwFlags = PFD_SUPPORT_OPENGL | PFD_DRAW_TO_WINDOW | PFD_DOUBLEBUFFER;
  206208. pfd.iPixelType = PFD_TYPE_RGBA;
  206209. pfd.iLayerType = PFD_MAIN_PLANE;
  206210. pfd.cColorBits = (BYTE) (pixelFormat.redBits + pixelFormat.greenBits + pixelFormat.blueBits);
  206211. pfd.cRedBits = (BYTE) pixelFormat.redBits;
  206212. pfd.cGreenBits = (BYTE) pixelFormat.greenBits;
  206213. pfd.cBlueBits = (BYTE) pixelFormat.blueBits;
  206214. pfd.cAlphaBits = (BYTE) pixelFormat.alphaBits;
  206215. pfd.cDepthBits = (BYTE) pixelFormat.depthBufferBits;
  206216. pfd.cStencilBits = (BYTE) pixelFormat.stencilBufferBits;
  206217. pfd.cAccumBits = (BYTE) (pixelFormat.accumulationBufferRedBits + pixelFormat.accumulationBufferGreenBits
  206218. + pixelFormat.accumulationBufferBlueBits + pixelFormat.accumulationBufferAlphaBits);
  206219. pfd.cAccumRedBits = (BYTE) pixelFormat.accumulationBufferRedBits;
  206220. pfd.cAccumGreenBits = (BYTE) pixelFormat.accumulationBufferGreenBits;
  206221. pfd.cAccumBlueBits = (BYTE) pixelFormat.accumulationBufferBlueBits;
  206222. pfd.cAccumAlphaBits = (BYTE) pixelFormat.accumulationBufferAlphaBits;
  206223. int format = 0;
  206224. PFNWGLCHOOSEPIXELFORMATARBPROC wglChoosePixelFormatARB = 0;
  206225. StringArray availableExtensions;
  206226. getWglExtensions (dc, availableExtensions);
  206227. if (availableExtensions.contains ("WGL_ARB_pixel_format")
  206228. && WGL_EXT_FUNCTION_INIT (PFNWGLCHOOSEPIXELFORMATARBPROC, wglChoosePixelFormatARB))
  206229. {
  206230. int attributes[64];
  206231. int n = 0;
  206232. attributes[n++] = WGL_DRAW_TO_WINDOW_ARB;
  206233. attributes[n++] = GL_TRUE;
  206234. attributes[n++] = WGL_SUPPORT_OPENGL_ARB;
  206235. attributes[n++] = GL_TRUE;
  206236. attributes[n++] = WGL_ACCELERATION_ARB;
  206237. attributes[n++] = WGL_FULL_ACCELERATION_ARB;
  206238. attributes[n++] = WGL_DOUBLE_BUFFER_ARB;
  206239. attributes[n++] = GL_TRUE;
  206240. attributes[n++] = WGL_PIXEL_TYPE_ARB;
  206241. attributes[n++] = WGL_TYPE_RGBA_ARB;
  206242. attributes[n++] = WGL_COLOR_BITS_ARB;
  206243. attributes[n++] = pfd.cColorBits;
  206244. attributes[n++] = WGL_RED_BITS_ARB;
  206245. attributes[n++] = pixelFormat.redBits;
  206246. attributes[n++] = WGL_GREEN_BITS_ARB;
  206247. attributes[n++] = pixelFormat.greenBits;
  206248. attributes[n++] = WGL_BLUE_BITS_ARB;
  206249. attributes[n++] = pixelFormat.blueBits;
  206250. attributes[n++] = WGL_ALPHA_BITS_ARB;
  206251. attributes[n++] = pixelFormat.alphaBits;
  206252. attributes[n++] = WGL_DEPTH_BITS_ARB;
  206253. attributes[n++] = pixelFormat.depthBufferBits;
  206254. if (pixelFormat.stencilBufferBits > 0)
  206255. {
  206256. attributes[n++] = WGL_STENCIL_BITS_ARB;
  206257. attributes[n++] = pixelFormat.stencilBufferBits;
  206258. }
  206259. attributes[n++] = WGL_ACCUM_RED_BITS_ARB;
  206260. attributes[n++] = pixelFormat.accumulationBufferRedBits;
  206261. attributes[n++] = WGL_ACCUM_GREEN_BITS_ARB;
  206262. attributes[n++] = pixelFormat.accumulationBufferGreenBits;
  206263. attributes[n++] = WGL_ACCUM_BLUE_BITS_ARB;
  206264. attributes[n++] = pixelFormat.accumulationBufferBlueBits;
  206265. attributes[n++] = WGL_ACCUM_ALPHA_BITS_ARB;
  206266. attributes[n++] = pixelFormat.accumulationBufferAlphaBits;
  206267. if (availableExtensions.contains ("WGL_ARB_multisample")
  206268. && pixelFormat.fullSceneAntiAliasingNumSamples > 0)
  206269. {
  206270. attributes[n++] = WGL_SAMPLE_BUFFERS_ARB;
  206271. attributes[n++] = 1;
  206272. attributes[n++] = WGL_SAMPLES_ARB;
  206273. attributes[n++] = pixelFormat.fullSceneAntiAliasingNumSamples;
  206274. }
  206275. attributes[n++] = 0;
  206276. UINT formatsCount;
  206277. const BOOL ok = wglChoosePixelFormatARB (dc, attributes, 0, 1, &format, &formatsCount);
  206278. (void) ok;
  206279. jassert (ok);
  206280. }
  206281. else
  206282. {
  206283. format = ChoosePixelFormat (dc, &pfd);
  206284. }
  206285. if (format != 0)
  206286. {
  206287. makeInactive();
  206288. // win32 can't change the pixel format of a window, so need to delete the
  206289. // old one and create a new one..
  206290. jassert (nativeWindow != 0);
  206291. ReleaseDC ((HWND) nativeWindow->getNativeHandle(), dc);
  206292. delete nativeWindow;
  206293. createNativeWindow();
  206294. if (SetPixelFormat (dc, format, &pfd))
  206295. {
  206296. wglDeleteContext (renderContext);
  206297. renderContext = wglCreateContext (dc);
  206298. jassert (renderContext != 0);
  206299. return renderContext != 0;
  206300. }
  206301. }
  206302. return false;
  206303. }
  206304. void updateWindowPosition (int x, int y, int w, int h, int)
  206305. {
  206306. SetWindowPos ((HWND) nativeWindow->getNativeHandle(), 0,
  206307. x, y, w, h,
  206308. SWP_NOACTIVATE | SWP_NOZORDER | SWP_NOOWNERZORDER);
  206309. }
  206310. void repaint()
  206311. {
  206312. const Rectangle<int> bounds (nativeWindow->getBounds());
  206313. nativeWindow->repaint (0, 0, bounds.getWidth(), bounds.getHeight());
  206314. }
  206315. void swapBuffers()
  206316. {
  206317. SwapBuffers (dc);
  206318. }
  206319. bool setSwapInterval (int numFramesPerSwap)
  206320. {
  206321. makeActive();
  206322. StringArray availableExtensions;
  206323. getWglExtensions (dc, availableExtensions);
  206324. PFNWGLSWAPINTERVALEXTPROC wglSwapIntervalEXT = 0;
  206325. return availableExtensions.contains ("WGL_EXT_swap_control")
  206326. && WGL_EXT_FUNCTION_INIT (PFNWGLSWAPINTERVALEXTPROC, wglSwapIntervalEXT)
  206327. && wglSwapIntervalEXT (numFramesPerSwap) != FALSE;
  206328. }
  206329. int getSwapInterval() const
  206330. {
  206331. makeActive();
  206332. StringArray availableExtensions;
  206333. getWglExtensions (dc, availableExtensions);
  206334. PFNWGLGETSWAPINTERVALEXTPROC wglGetSwapIntervalEXT = 0;
  206335. if (availableExtensions.contains ("WGL_EXT_swap_control")
  206336. && WGL_EXT_FUNCTION_INIT (PFNWGLGETSWAPINTERVALEXTPROC, wglGetSwapIntervalEXT))
  206337. return wglGetSwapIntervalEXT();
  206338. return 0;
  206339. }
  206340. void findAlternativeOpenGLPixelFormats (OwnedArray <OpenGLPixelFormat>& results)
  206341. {
  206342. jassert (isActive());
  206343. StringArray availableExtensions;
  206344. getWglExtensions (dc, availableExtensions);
  206345. PFNWGLGETPIXELFORMATATTRIBIVARBPROC wglGetPixelFormatAttribivARB = 0;
  206346. int numTypes = 0;
  206347. if (availableExtensions.contains("WGL_ARB_pixel_format")
  206348. && WGL_EXT_FUNCTION_INIT (PFNWGLGETPIXELFORMATATTRIBIVARBPROC, wglGetPixelFormatAttribivARB))
  206349. {
  206350. int attributes = WGL_NUMBER_PIXEL_FORMATS_ARB;
  206351. if (! wglGetPixelFormatAttribivARB (dc, 1, 0, 1, &attributes, &numTypes))
  206352. jassertfalse
  206353. }
  206354. else
  206355. {
  206356. numTypes = DescribePixelFormat (dc, 0, 0, 0);
  206357. }
  206358. OpenGLPixelFormat pf;
  206359. for (int i = 0; i < numTypes; ++i)
  206360. {
  206361. if (fillInPixelFormatDetails (i + 1, pf, availableExtensions))
  206362. {
  206363. bool alreadyListed = false;
  206364. for (int j = results.size(); --j >= 0;)
  206365. if (pf == *results.getUnchecked(j))
  206366. alreadyListed = true;
  206367. if (! alreadyListed)
  206368. results.add (new OpenGLPixelFormat (pf));
  206369. }
  206370. }
  206371. }
  206372. void* getNativeWindowHandle() const
  206373. {
  206374. return nativeWindow != 0 ? nativeWindow->getNativeHandle() : 0;
  206375. }
  206376. juce_UseDebuggingNewOperator
  206377. HGLRC renderContext;
  206378. private:
  206379. Win32ComponentPeer* nativeWindow;
  206380. Component* const component;
  206381. HDC dc;
  206382. void createNativeWindow()
  206383. {
  206384. nativeWindow = new Win32ComponentPeer (component, 0);
  206385. nativeWindow->dontRepaint = true;
  206386. nativeWindow->setVisible (true);
  206387. HWND hwnd = (HWND) nativeWindow->getNativeHandle();
  206388. Win32ComponentPeer* const peer = dynamic_cast <Win32ComponentPeer*> (component->getTopLevelComponent()->getPeer());
  206389. if (peer != 0)
  206390. {
  206391. SetParent (hwnd, (HWND) peer->getNativeHandle());
  206392. juce_setWindowStyleBit (hwnd, GWL_STYLE, WS_CHILD, true);
  206393. juce_setWindowStyleBit (hwnd, GWL_STYLE, WS_POPUP, false);
  206394. }
  206395. dc = GetDC (hwnd);
  206396. }
  206397. bool fillInPixelFormatDetails (const int pixelFormatIndex,
  206398. OpenGLPixelFormat& result,
  206399. const StringArray& availableExtensions) const throw()
  206400. {
  206401. PFNWGLGETPIXELFORMATATTRIBIVARBPROC wglGetPixelFormatAttribivARB = 0;
  206402. if (availableExtensions.contains ("WGL_ARB_pixel_format")
  206403. && WGL_EXT_FUNCTION_INIT (PFNWGLGETPIXELFORMATATTRIBIVARBPROC, wglGetPixelFormatAttribivARB))
  206404. {
  206405. int attributes[32];
  206406. int numAttributes = 0;
  206407. attributes[numAttributes++] = WGL_DRAW_TO_WINDOW_ARB;
  206408. attributes[numAttributes++] = WGL_SUPPORT_OPENGL_ARB;
  206409. attributes[numAttributes++] = WGL_ACCELERATION_ARB;
  206410. attributes[numAttributes++] = WGL_DOUBLE_BUFFER_ARB;
  206411. attributes[numAttributes++] = WGL_PIXEL_TYPE_ARB;
  206412. attributes[numAttributes++] = WGL_RED_BITS_ARB;
  206413. attributes[numAttributes++] = WGL_GREEN_BITS_ARB;
  206414. attributes[numAttributes++] = WGL_BLUE_BITS_ARB;
  206415. attributes[numAttributes++] = WGL_ALPHA_BITS_ARB;
  206416. attributes[numAttributes++] = WGL_DEPTH_BITS_ARB;
  206417. attributes[numAttributes++] = WGL_STENCIL_BITS_ARB;
  206418. attributes[numAttributes++] = WGL_ACCUM_RED_BITS_ARB;
  206419. attributes[numAttributes++] = WGL_ACCUM_GREEN_BITS_ARB;
  206420. attributes[numAttributes++] = WGL_ACCUM_BLUE_BITS_ARB;
  206421. attributes[numAttributes++] = WGL_ACCUM_ALPHA_BITS_ARB;
  206422. if (availableExtensions.contains ("WGL_ARB_multisample"))
  206423. attributes[numAttributes++] = WGL_SAMPLES_ARB;
  206424. int values[32];
  206425. zeromem (values, sizeof (values));
  206426. if (wglGetPixelFormatAttribivARB (dc, pixelFormatIndex, 0, numAttributes, attributes, values))
  206427. {
  206428. int n = 0;
  206429. bool isValidFormat = (values[n++] == GL_TRUE); // WGL_DRAW_TO_WINDOW_ARB
  206430. isValidFormat = (values[n++] == GL_TRUE) && isValidFormat; // WGL_SUPPORT_OPENGL_ARB
  206431. isValidFormat = (values[n++] == WGL_FULL_ACCELERATION_ARB) && isValidFormat; // WGL_ACCELERATION_ARB
  206432. isValidFormat = (values[n++] == GL_TRUE) && isValidFormat; // WGL_DOUBLE_BUFFER_ARB:
  206433. isValidFormat = (values[n++] == WGL_TYPE_RGBA_ARB) && isValidFormat; // WGL_PIXEL_TYPE_ARB
  206434. result.redBits = values[n++]; // WGL_RED_BITS_ARB
  206435. result.greenBits = values[n++]; // WGL_GREEN_BITS_ARB
  206436. result.blueBits = values[n++]; // WGL_BLUE_BITS_ARB
  206437. result.alphaBits = values[n++]; // WGL_ALPHA_BITS_ARB
  206438. result.depthBufferBits = values[n++]; // WGL_DEPTH_BITS_ARB
  206439. result.stencilBufferBits = values[n++]; // WGL_STENCIL_BITS_ARB
  206440. result.accumulationBufferRedBits = values[n++]; // WGL_ACCUM_RED_BITS_ARB
  206441. result.accumulationBufferGreenBits = values[n++]; // WGL_ACCUM_GREEN_BITS_ARB
  206442. result.accumulationBufferBlueBits = values[n++]; // WGL_ACCUM_BLUE_BITS_ARB
  206443. result.accumulationBufferAlphaBits = values[n++]; // WGL_ACCUM_ALPHA_BITS_ARB
  206444. result.fullSceneAntiAliasingNumSamples = (uint8) values[n++]; // WGL_SAMPLES_ARB
  206445. return isValidFormat;
  206446. }
  206447. else
  206448. {
  206449. jassertfalse
  206450. }
  206451. }
  206452. else
  206453. {
  206454. PIXELFORMATDESCRIPTOR pfd;
  206455. if (DescribePixelFormat (dc, pixelFormatIndex, sizeof (pfd), &pfd))
  206456. {
  206457. result.redBits = pfd.cRedBits;
  206458. result.greenBits = pfd.cGreenBits;
  206459. result.blueBits = pfd.cBlueBits;
  206460. result.alphaBits = pfd.cAlphaBits;
  206461. result.depthBufferBits = pfd.cDepthBits;
  206462. result.stencilBufferBits = pfd.cStencilBits;
  206463. result.accumulationBufferRedBits = pfd.cAccumRedBits;
  206464. result.accumulationBufferGreenBits = pfd.cAccumGreenBits;
  206465. result.accumulationBufferBlueBits = pfd.cAccumBlueBits;
  206466. result.accumulationBufferAlphaBits = pfd.cAccumAlphaBits;
  206467. result.fullSceneAntiAliasingNumSamples = 0;
  206468. return true;
  206469. }
  206470. else
  206471. {
  206472. jassertfalse
  206473. }
  206474. }
  206475. return false;
  206476. }
  206477. WindowedGLContext (const WindowedGLContext&);
  206478. WindowedGLContext& operator= (const WindowedGLContext&);
  206479. };
  206480. OpenGLContext* OpenGLComponent::createContext()
  206481. {
  206482. ScopedPointer<WindowedGLContext> c (new WindowedGLContext (this,
  206483. contextToShareListsWith != 0 ? (HGLRC) contextToShareListsWith->getRawContext() : 0,
  206484. preferredPixelFormat));
  206485. return (c->renderContext != 0) ? c.release() : 0;
  206486. }
  206487. void* OpenGLComponent::getNativeWindowHandle() const
  206488. {
  206489. return context != 0 ? static_cast<WindowedGLContext*> (static_cast<OpenGLContext*> (context))->getNativeWindowHandle() : 0;
  206490. }
  206491. void juce_glViewport (const int w, const int h)
  206492. {
  206493. glViewport (0, 0, w, h);
  206494. }
  206495. void OpenGLPixelFormat::getAvailablePixelFormats (Component* component,
  206496. OwnedArray <OpenGLPixelFormat>& results)
  206497. {
  206498. Component tempComp;
  206499. {
  206500. WindowedGLContext wc (component, 0, OpenGLPixelFormat (8, 8, 16, 0));
  206501. wc.makeActive();
  206502. wc.findAlternativeOpenGLPixelFormats (results);
  206503. }
  206504. }
  206505. #endif
  206506. /*** End of inlined file: juce_win32_OpenGLComponent.cpp ***/
  206507. /*** Start of inlined file: juce_win32_AudioCDReader.cpp ***/
  206508. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  206509. // compiled on its own).
  206510. #if JUCE_INCLUDED_FILE
  206511. #if JUCE_USE_CDREADER
  206512. namespace CDReaderHelpers
  206513. {
  206514. //***************************************************************************
  206515. // %%% TARGET STATUS VALUES %%%
  206516. //***************************************************************************
  206517. #define STATUS_GOOD 0x00 // Status Good
  206518. #define STATUS_CHKCOND 0x02 // Check Condition
  206519. #define STATUS_CONDMET 0x04 // Condition Met
  206520. #define STATUS_BUSY 0x08 // Busy
  206521. #define STATUS_INTERM 0x10 // Intermediate
  206522. #define STATUS_INTCDMET 0x14 // Intermediate-condition met
  206523. #define STATUS_RESCONF 0x18 // Reservation conflict
  206524. #define STATUS_COMTERM 0x22 // Command Terminated
  206525. #define STATUS_QFULL 0x28 // Queue full
  206526. //***************************************************************************
  206527. // %%% SCSI MISCELLANEOUS EQUATES %%%
  206528. //***************************************************************************
  206529. #define MAXLUN 7 // Maximum Logical Unit Id
  206530. #define MAXTARG 7 // Maximum Target Id
  206531. #define MAX_SCSI_LUNS 64 // Maximum Number of SCSI LUNs
  206532. #define MAX_NUM_HA 8 // Maximum Number of SCSI HA's
  206533. //***************************************************************************
  206534. // %%% Commands for all Device Types %%%
  206535. //***************************************************************************
  206536. #define SCSI_CHANGE_DEF 0x40 // Change Definition (Optional)
  206537. #define SCSI_COMPARE 0x39 // Compare (O)
  206538. #define SCSI_COPY 0x18 // Copy (O)
  206539. #define SCSI_COP_VERIFY 0x3A // Copy and Verify (O)
  206540. #define SCSI_INQUIRY 0x12 // Inquiry (MANDATORY)
  206541. #define SCSI_LOG_SELECT 0x4C // Log Select (O)
  206542. #define SCSI_LOG_SENSE 0x4D // Log Sense (O)
  206543. #define SCSI_MODE_SEL6 0x15 // Mode Select 6-byte (Device Specific)
  206544. #define SCSI_MODE_SEL10 0x55 // Mode Select 10-byte (Device Specific)
  206545. #define SCSI_MODE_SEN6 0x1A // Mode Sense 6-byte (Device Specific)
  206546. #define SCSI_MODE_SEN10 0x5A // Mode Sense 10-byte (Device Specific)
  206547. #define SCSI_READ_BUFF 0x3C // Read Buffer (O)
  206548. #define SCSI_REQ_SENSE 0x03 // Request Sense (MANDATORY)
  206549. #define SCSI_SEND_DIAG 0x1D // Send Diagnostic (O)
  206550. #define SCSI_TST_U_RDY 0x00 // Test Unit Ready (MANDATORY)
  206551. #define SCSI_WRITE_BUFF 0x3B // Write Buffer (O)
  206552. //***************************************************************************
  206553. // %%% Commands Unique to Direct Access Devices %%%
  206554. //***************************************************************************
  206555. #define SCSI_COMPARE 0x39 // Compare (O)
  206556. #define SCSI_FORMAT 0x04 // Format Unit (MANDATORY)
  206557. #define SCSI_LCK_UN_CAC 0x36 // Lock Unlock Cache (O)
  206558. #define SCSI_PREFETCH 0x34 // Prefetch (O)
  206559. #define SCSI_MED_REMOVL 0x1E // Prevent/Allow medium Removal (O)
  206560. #define SCSI_READ6 0x08 // Read 6-byte (MANDATORY)
  206561. #define SCSI_READ10 0x28 // Read 10-byte (MANDATORY)
  206562. #define SCSI_RD_CAPAC 0x25 // Read Capacity (MANDATORY)
  206563. #define SCSI_RD_DEFECT 0x37 // Read Defect Data (O)
  206564. #define SCSI_READ_LONG 0x3E // Read Long (O)
  206565. #define SCSI_REASS_BLK 0x07 // Reassign Blocks (O)
  206566. #define SCSI_RCV_DIAG 0x1C // Receive Diagnostic Results (O)
  206567. #define SCSI_RELEASE 0x17 // Release Unit (MANDATORY)
  206568. #define SCSI_REZERO 0x01 // Rezero Unit (O)
  206569. #define SCSI_SRCH_DAT_E 0x31 // Search Data Equal (O)
  206570. #define SCSI_SRCH_DAT_H 0x30 // Search Data High (O)
  206571. #define SCSI_SRCH_DAT_L 0x32 // Search Data Low (O)
  206572. #define SCSI_SEEK6 0x0B // Seek 6-Byte (O)
  206573. #define SCSI_SEEK10 0x2B // Seek 10-Byte (O)
  206574. #define SCSI_SEND_DIAG 0x1D // Send Diagnostics (MANDATORY)
  206575. #define SCSI_SET_LIMIT 0x33 // Set Limits (O)
  206576. #define SCSI_START_STP 0x1B // Start/Stop Unit (O)
  206577. #define SCSI_SYNC_CACHE 0x35 // Synchronize Cache (O)
  206578. #define SCSI_VERIFY 0x2F // Verify (O)
  206579. #define SCSI_WRITE6 0x0A // Write 6-Byte (MANDATORY)
  206580. #define SCSI_WRITE10 0x2A // Write 10-Byte (MANDATORY)
  206581. #define SCSI_WRT_VERIFY 0x2E // Write and Verify (O)
  206582. #define SCSI_WRITE_LONG 0x3F // Write Long (O)
  206583. #define SCSI_WRITE_SAME 0x41 // Write Same (O)
  206584. //***************************************************************************
  206585. // %%% Commands Unique to Sequential Access Devices %%%
  206586. //***************************************************************************
  206587. #define SCSI_ERASE 0x19 // Erase (MANDATORY)
  206588. #define SCSI_LOAD_UN 0x1b // Load/Unload (O)
  206589. #define SCSI_LOCATE 0x2B // Locate (O)
  206590. #define SCSI_RD_BLK_LIM 0x05 // Read Block Limits (MANDATORY)
  206591. #define SCSI_READ_POS 0x34 // Read Position (O)
  206592. #define SCSI_READ_REV 0x0F // Read Reverse (O)
  206593. #define SCSI_REC_BF_DAT 0x14 // Recover Buffer Data (O)
  206594. #define SCSI_RESERVE 0x16 // Reserve Unit (MANDATORY)
  206595. #define SCSI_REWIND 0x01 // Rewind (MANDATORY)
  206596. #define SCSI_SPACE 0x11 // Space (MANDATORY)
  206597. #define SCSI_VERIFY_T 0x13 // Verify (Tape) (O)
  206598. #define SCSI_WRT_FILE 0x10 // Write Filemarks (MANDATORY)
  206599. //***************************************************************************
  206600. // %%% Commands Unique to Printer Devices %%%
  206601. //***************************************************************************
  206602. #define SCSI_PRINT 0x0A // Print (MANDATORY)
  206603. #define SCSI_SLEW_PNT 0x0B // Slew and Print (O)
  206604. #define SCSI_STOP_PNT 0x1B // Stop Print (O)
  206605. #define SCSI_SYNC_BUFF 0x10 // Synchronize Buffer (O)
  206606. //***************************************************************************
  206607. // %%% Commands Unique to Processor Devices %%%
  206608. //***************************************************************************
  206609. #define SCSI_RECEIVE 0x08 // Receive (O)
  206610. #define SCSI_SEND 0x0A // Send (O)
  206611. //***************************************************************************
  206612. // %%% Commands Unique to Write-Once Devices %%%
  206613. //***************************************************************************
  206614. #define SCSI_MEDIUM_SCN 0x38 // Medium Scan (O)
  206615. #define SCSI_SRCHDATE10 0x31 // Search Data Equal 10-Byte (O)
  206616. #define SCSI_SRCHDATE12 0xB1 // Search Data Equal 12-Byte (O)
  206617. #define SCSI_SRCHDATH10 0x30 // Search Data High 10-Byte (O)
  206618. #define SCSI_SRCHDATH12 0xB0 // Search Data High 12-Byte (O)
  206619. #define SCSI_SRCHDATL10 0x32 // Search Data Low 10-Byte (O)
  206620. #define SCSI_SRCHDATL12 0xB2 // Search Data Low 12-Byte (O)
  206621. #define SCSI_SET_LIM_10 0x33 // Set Limits 10-Byte (O)
  206622. #define SCSI_SET_LIM_12 0xB3 // Set Limits 10-Byte (O)
  206623. #define SCSI_VERIFY10 0x2F // Verify 10-Byte (O)
  206624. #define SCSI_VERIFY12 0xAF // Verify 12-Byte (O)
  206625. #define SCSI_WRITE12 0xAA // Write 12-Byte (O)
  206626. #define SCSI_WRT_VER10 0x2E // Write and Verify 10-Byte (O)
  206627. #define SCSI_WRT_VER12 0xAE // Write and Verify 12-Byte (O)
  206628. //***************************************************************************
  206629. // %%% Commands Unique to CD-ROM Devices %%%
  206630. //***************************************************************************
  206631. #define SCSI_PLAYAUD_10 0x45 // Play Audio 10-Byte (O)
  206632. #define SCSI_PLAYAUD_12 0xA5 // Play Audio 12-Byte 12-Byte (O)
  206633. #define SCSI_PLAYAUDMSF 0x47 // Play Audio MSF (O)
  206634. #define SCSI_PLAYA_TKIN 0x48 // Play Audio Track/Index (O)
  206635. #define SCSI_PLYTKREL10 0x49 // Play Track Relative 10-Byte (O)
  206636. #define SCSI_PLYTKREL12 0xA9 // Play Track Relative 12-Byte (O)
  206637. #define SCSI_READCDCAP 0x25 // Read CD-ROM Capacity (MANDATORY)
  206638. #define SCSI_READHEADER 0x44 // Read Header (O)
  206639. #define SCSI_SUBCHANNEL 0x42 // Read Subchannel (O)
  206640. #define SCSI_READ_TOC 0x43 // Read TOC (O)
  206641. //***************************************************************************
  206642. // %%% Commands Unique to Scanner Devices %%%
  206643. //***************************************************************************
  206644. #define SCSI_GETDBSTAT 0x34 // Get Data Buffer Status (O)
  206645. #define SCSI_GETWINDOW 0x25 // Get Window (O)
  206646. #define SCSI_OBJECTPOS 0x31 // Object Postion (O)
  206647. #define SCSI_SCAN 0x1B // Scan (O)
  206648. #define SCSI_SETWINDOW 0x24 // Set Window (MANDATORY)
  206649. //***************************************************************************
  206650. // %%% Commands Unique to Optical Memory Devices %%%
  206651. //***************************************************************************
  206652. #define SCSI_UpdateBlk 0x3D // Update Block (O)
  206653. //***************************************************************************
  206654. // %%% Commands Unique to Medium Changer Devices %%%
  206655. //***************************************************************************
  206656. #define SCSI_EXCHMEDIUM 0xA6 // Exchange Medium (O)
  206657. #define SCSI_INITELSTAT 0x07 // Initialize Element Status (O)
  206658. #define SCSI_POSTOELEM 0x2B // Position to Element (O)
  206659. #define SCSI_REQ_VE_ADD 0xB5 // Request Volume Element Address (O)
  206660. #define SCSI_SENDVOLTAG 0xB6 // Send Volume Tag (O)
  206661. //***************************************************************************
  206662. // %%% Commands Unique to Communication Devices %%%
  206663. //***************************************************************************
  206664. #define SCSI_GET_MSG_6 0x08 // Get Message 6-Byte (MANDATORY)
  206665. #define SCSI_GET_MSG_10 0x28 // Get Message 10-Byte (O)
  206666. #define SCSI_GET_MSG_12 0xA8 // Get Message 12-Byte (O)
  206667. #define SCSI_SND_MSG_6 0x0A // Send Message 6-Byte (MANDATORY)
  206668. #define SCSI_SND_MSG_10 0x2A // Send Message 10-Byte (O)
  206669. #define SCSI_SND_MSG_12 0xAA // Send Message 12-Byte (O)
  206670. //***************************************************************************
  206671. // %%% Request Sense Data Format %%%
  206672. //***************************************************************************
  206673. typedef struct {
  206674. BYTE ErrorCode; // Error Code (70H or 71H)
  206675. BYTE SegmentNum; // Number of current segment descriptor
  206676. BYTE SenseKey; // Sense Key(See bit definitions too)
  206677. BYTE InfoByte0; // Information MSB
  206678. BYTE InfoByte1; // Information MID
  206679. BYTE InfoByte2; // Information MID
  206680. BYTE InfoByte3; // Information LSB
  206681. BYTE AddSenLen; // Additional Sense Length
  206682. BYTE ComSpecInf0; // Command Specific Information MSB
  206683. BYTE ComSpecInf1; // Command Specific Information MID
  206684. BYTE ComSpecInf2; // Command Specific Information MID
  206685. BYTE ComSpecInf3; // Command Specific Information LSB
  206686. BYTE AddSenseCode; // Additional Sense Code
  206687. BYTE AddSenQual; // Additional Sense Code Qualifier
  206688. BYTE FieldRepUCode; // Field Replaceable Unit Code
  206689. BYTE SenKeySpec15; // Sense Key Specific 15th byte
  206690. BYTE SenKeySpec16; // Sense Key Specific 16th byte
  206691. BYTE SenKeySpec17; // Sense Key Specific 17th byte
  206692. BYTE AddSenseBytes; // Additional Sense Bytes
  206693. } SENSE_DATA_FMT;
  206694. //***************************************************************************
  206695. // %%% REQUEST SENSE ERROR CODE %%%
  206696. //***************************************************************************
  206697. #define SERROR_CURRENT 0x70 // Current Errors
  206698. #define SERROR_DEFERED 0x71 // Deferred Errors
  206699. //***************************************************************************
  206700. // %%% REQUEST SENSE BIT DEFINITIONS %%%
  206701. //***************************************************************************
  206702. #define SENSE_VALID 0x80 // Byte 0 Bit 7
  206703. #define SENSE_FILEMRK 0x80 // Byte 2 Bit 7
  206704. #define SENSE_EOM 0x40 // Byte 2 Bit 6
  206705. #define SENSE_ILI 0x20 // Byte 2 Bit 5
  206706. //***************************************************************************
  206707. // %%% REQUEST SENSE SENSE KEY DEFINITIONS %%%
  206708. //***************************************************************************
  206709. #define KEY_NOSENSE 0x00 // No Sense
  206710. #define KEY_RECERROR 0x01 // Recovered Error
  206711. #define KEY_NOTREADY 0x02 // Not Ready
  206712. #define KEY_MEDIUMERR 0x03 // Medium Error
  206713. #define KEY_HARDERROR 0x04 // Hardware Error
  206714. #define KEY_ILLGLREQ 0x05 // Illegal Request
  206715. #define KEY_UNITATT 0x06 // Unit Attention
  206716. #define KEY_DATAPROT 0x07 // Data Protect
  206717. #define KEY_BLANKCHK 0x08 // Blank Check
  206718. #define KEY_VENDSPEC 0x09 // Vendor Specific
  206719. #define KEY_COPYABORT 0x0A // Copy Abort
  206720. #define KEY_EQUAL 0x0C // Equal (Search)
  206721. #define KEY_VOLOVRFLW 0x0D // Volume Overflow
  206722. #define KEY_MISCOMP 0x0E // Miscompare (Search)
  206723. #define KEY_RESERVED 0x0F // Reserved
  206724. //***************************************************************************
  206725. // %%% PERIPHERAL DEVICE TYPE DEFINITIONS %%%
  206726. //***************************************************************************
  206727. #define DTYPE_DASD 0x00 // Disk Device
  206728. #define DTYPE_SEQD 0x01 // Tape Device
  206729. #define DTYPE_PRNT 0x02 // Printer
  206730. #define DTYPE_PROC 0x03 // Processor
  206731. #define DTYPE_WORM 0x04 // Write-once read-multiple
  206732. #define DTYPE_CROM 0x05 // CD-ROM device
  206733. #define DTYPE_SCAN 0x06 // Scanner device
  206734. #define DTYPE_OPTI 0x07 // Optical memory device
  206735. #define DTYPE_JUKE 0x08 // Medium Changer device
  206736. #define DTYPE_COMM 0x09 // Communications device
  206737. #define DTYPE_RESL 0x0A // Reserved (low)
  206738. #define DTYPE_RESH 0x1E // Reserved (high)
  206739. #define DTYPE_UNKNOWN 0x1F // Unknown or no device type
  206740. //***************************************************************************
  206741. // %%% ANSI APPROVED VERSION DEFINITIONS %%%
  206742. //***************************************************************************
  206743. #define ANSI_MAYBE 0x0 // Device may or may not be ANSI approved stand
  206744. #define ANSI_SCSI1 0x1 // Device complies to ANSI X3.131-1986 (SCSI-1)
  206745. #define ANSI_SCSI2 0x2 // Device complies to SCSI-2
  206746. #define ANSI_RESLO 0x3 // Reserved (low)
  206747. #define ANSI_RESHI 0x7 // Reserved (high)
  206748. typedef struct
  206749. {
  206750. USHORT Length;
  206751. UCHAR ScsiStatus;
  206752. UCHAR PathId;
  206753. UCHAR TargetId;
  206754. UCHAR Lun;
  206755. UCHAR CdbLength;
  206756. UCHAR SenseInfoLength;
  206757. UCHAR DataIn;
  206758. ULONG DataTransferLength;
  206759. ULONG TimeOutValue;
  206760. ULONG DataBufferOffset;
  206761. ULONG SenseInfoOffset;
  206762. UCHAR Cdb[16];
  206763. } SCSI_PASS_THROUGH, *PSCSI_PASS_THROUGH;
  206764. typedef struct
  206765. {
  206766. USHORT Length;
  206767. UCHAR ScsiStatus;
  206768. UCHAR PathId;
  206769. UCHAR TargetId;
  206770. UCHAR Lun;
  206771. UCHAR CdbLength;
  206772. UCHAR SenseInfoLength;
  206773. UCHAR DataIn;
  206774. ULONG DataTransferLength;
  206775. ULONG TimeOutValue;
  206776. PVOID DataBuffer;
  206777. ULONG SenseInfoOffset;
  206778. UCHAR Cdb[16];
  206779. } SCSI_PASS_THROUGH_DIRECT, *PSCSI_PASS_THROUGH_DIRECT;
  206780. typedef struct
  206781. {
  206782. SCSI_PASS_THROUGH_DIRECT spt;
  206783. ULONG Filler;
  206784. UCHAR ucSenseBuf[32];
  206785. } SCSI_PASS_THROUGH_DIRECT_WITH_BUFFER, *PSCSI_PASS_THROUGH_DIRECT_WITH_BUFFER;
  206786. typedef struct
  206787. {
  206788. ULONG Length;
  206789. UCHAR PortNumber;
  206790. UCHAR PathId;
  206791. UCHAR TargetId;
  206792. UCHAR Lun;
  206793. } SCSI_ADDRESS, *PSCSI_ADDRESS;
  206794. #define METHOD_BUFFERED 0
  206795. #define METHOD_IN_DIRECT 1
  206796. #define METHOD_OUT_DIRECT 2
  206797. #define METHOD_NEITHER 3
  206798. #define FILE_ANY_ACCESS 0
  206799. #ifndef FILE_READ_ACCESS
  206800. #define FILE_READ_ACCESS (0x0001)
  206801. #endif
  206802. #ifndef FILE_WRITE_ACCESS
  206803. #define FILE_WRITE_ACCESS (0x0002)
  206804. #endif
  206805. #define IOCTL_SCSI_BASE 0x00000004
  206806. #define SCSI_IOCTL_DATA_OUT 0
  206807. #define SCSI_IOCTL_DATA_IN 1
  206808. #define SCSI_IOCTL_DATA_UNSPECIFIED 2
  206809. #define CTL_CODE2( DevType, Function, Method, Access ) ( \
  206810. ((DevType) << 16) | ((Access) << 14) | ((Function) << 2) | (Method) \
  206811. )
  206812. #define IOCTL_SCSI_PASS_THROUGH CTL_CODE2( IOCTL_SCSI_BASE, 0x0401, METHOD_BUFFERED, FILE_READ_ACCESS | FILE_WRITE_ACCESS )
  206813. #define IOCTL_SCSI_GET_CAPABILITIES CTL_CODE2( IOCTL_SCSI_BASE, 0x0404, METHOD_BUFFERED, FILE_ANY_ACCESS)
  206814. #define IOCTL_SCSI_PASS_THROUGH_DIRECT CTL_CODE2( IOCTL_SCSI_BASE, 0x0405, METHOD_BUFFERED, FILE_READ_ACCESS | FILE_WRITE_ACCESS )
  206815. #define IOCTL_SCSI_GET_ADDRESS CTL_CODE2( IOCTL_SCSI_BASE, 0x0406, METHOD_BUFFERED, FILE_ANY_ACCESS )
  206816. #define SENSE_LEN 14
  206817. #define SRB_DIR_SCSI 0x00
  206818. #define SRB_POSTING 0x01
  206819. #define SRB_ENABLE_RESIDUAL_COUNT 0x04
  206820. #define SRB_DIR_IN 0x08
  206821. #define SRB_DIR_OUT 0x10
  206822. #define SRB_EVENT_NOTIFY 0x40
  206823. #define RESIDUAL_COUNT_SUPPORTED 0x02
  206824. #define MAX_SRB_TIMEOUT 1080001u
  206825. #define DEFAULT_SRB_TIMEOUT 1080001u
  206826. #define SC_HA_INQUIRY 0x00
  206827. #define SC_GET_DEV_TYPE 0x01
  206828. #define SC_EXEC_SCSI_CMD 0x02
  206829. #define SC_ABORT_SRB 0x03
  206830. #define SC_RESET_DEV 0x04
  206831. #define SC_SET_HA_PARMS 0x05
  206832. #define SC_GET_DISK_INFO 0x06
  206833. #define SC_RESCAN_SCSI_BUS 0x07
  206834. #define SC_GETSET_TIMEOUTS 0x08
  206835. #define SS_PENDING 0x00
  206836. #define SS_COMP 0x01
  206837. #define SS_ABORTED 0x02
  206838. #define SS_ABORT_FAIL 0x03
  206839. #define SS_ERR 0x04
  206840. #define SS_INVALID_CMD 0x80
  206841. #define SS_INVALID_HA 0x81
  206842. #define SS_NO_DEVICE 0x82
  206843. #define SS_INVALID_SRB 0xE0
  206844. #define SS_OLD_MANAGER 0xE1
  206845. #define SS_BUFFER_ALIGN 0xE1
  206846. #define SS_ILLEGAL_MODE 0xE2
  206847. #define SS_NO_ASPI 0xE3
  206848. #define SS_FAILED_INIT 0xE4
  206849. #define SS_ASPI_IS_BUSY 0xE5
  206850. #define SS_BUFFER_TO_BIG 0xE6
  206851. #define SS_BUFFER_TOO_BIG 0xE6
  206852. #define SS_MISMATCHED_COMPONENTS 0xE7
  206853. #define SS_NO_ADAPTERS 0xE8
  206854. #define SS_INSUFFICIENT_RESOURCES 0xE9
  206855. #define SS_ASPI_IS_SHUTDOWN 0xEA
  206856. #define SS_BAD_INSTALL 0xEB
  206857. #define HASTAT_OK 0x00
  206858. #define HASTAT_SEL_TO 0x11
  206859. #define HASTAT_DO_DU 0x12
  206860. #define HASTAT_BUS_FREE 0x13
  206861. #define HASTAT_PHASE_ERR 0x14
  206862. #define HASTAT_TIMEOUT 0x09
  206863. #define HASTAT_COMMAND_TIMEOUT 0x0B
  206864. #define HASTAT_MESSAGE_REJECT 0x0D
  206865. #define HASTAT_BUS_RESET 0x0E
  206866. #define HASTAT_PARITY_ERROR 0x0F
  206867. #define HASTAT_REQUEST_SENSE_FAILED 0x10
  206868. #define PACKED
  206869. #pragma pack(1)
  206870. typedef struct
  206871. {
  206872. BYTE SRB_Cmd;
  206873. BYTE SRB_Status;
  206874. BYTE SRB_HaID;
  206875. BYTE SRB_Flags;
  206876. DWORD SRB_Hdr_Rsvd;
  206877. BYTE HA_Count;
  206878. BYTE HA_SCSI_ID;
  206879. BYTE HA_ManagerId[16];
  206880. BYTE HA_Identifier[16];
  206881. BYTE HA_Unique[16];
  206882. WORD HA_Rsvd1;
  206883. BYTE pad[20];
  206884. } PACKED SRB_HAInquiry, *PSRB_HAInquiry, FAR *LPSRB_HAInquiry;
  206885. typedef struct
  206886. {
  206887. BYTE SRB_Cmd;
  206888. BYTE SRB_Status;
  206889. BYTE SRB_HaID;
  206890. BYTE SRB_Flags;
  206891. DWORD SRB_Hdr_Rsvd;
  206892. BYTE SRB_Target;
  206893. BYTE SRB_Lun;
  206894. BYTE SRB_DeviceType;
  206895. BYTE SRB_Rsvd1;
  206896. BYTE pad[68];
  206897. } PACKED SRB_GDEVBlock, *PSRB_GDEVBlock, FAR *LPSRB_GDEVBlock;
  206898. typedef struct
  206899. {
  206900. BYTE SRB_Cmd;
  206901. BYTE SRB_Status;
  206902. BYTE SRB_HaID;
  206903. BYTE SRB_Flags;
  206904. DWORD SRB_Hdr_Rsvd;
  206905. BYTE SRB_Target;
  206906. BYTE SRB_Lun;
  206907. WORD SRB_Rsvd1;
  206908. DWORD SRB_BufLen;
  206909. BYTE FAR *SRB_BufPointer;
  206910. BYTE SRB_SenseLen;
  206911. BYTE SRB_CDBLen;
  206912. BYTE SRB_HaStat;
  206913. BYTE SRB_TargStat;
  206914. VOID FAR *SRB_PostProc;
  206915. BYTE SRB_Rsvd2[20];
  206916. BYTE CDBByte[16];
  206917. BYTE SenseArea[SENSE_LEN+2];
  206918. } PACKED SRB_ExecSCSICmd, *PSRB_ExecSCSICmd, FAR *LPSRB_ExecSCSICmd;
  206919. typedef struct
  206920. {
  206921. BYTE SRB_Cmd;
  206922. BYTE SRB_Status;
  206923. BYTE SRB_HaId;
  206924. BYTE SRB_Flags;
  206925. DWORD SRB_Hdr_Rsvd;
  206926. } PACKED SRB, *PSRB, FAR *LPSRB;
  206927. #pragma pack()
  206928. struct CDDeviceInfo
  206929. {
  206930. char vendor[9];
  206931. char productId[17];
  206932. char rev[5];
  206933. char vendorSpec[21];
  206934. BYTE ha;
  206935. BYTE tgt;
  206936. BYTE lun;
  206937. char scsiDriveLetter; // will be 0 if not using scsi
  206938. };
  206939. class CDReadBuffer
  206940. {
  206941. public:
  206942. int startFrame;
  206943. int numFrames;
  206944. int dataStartOffset;
  206945. int dataLength;
  206946. int bufferSize;
  206947. HeapBlock<BYTE> buffer;
  206948. int index;
  206949. bool wantsIndex;
  206950. CDReadBuffer (const int numberOfFrames)
  206951. : startFrame (0),
  206952. numFrames (0),
  206953. dataStartOffset (0),
  206954. dataLength (0),
  206955. bufferSize (2352 * numberOfFrames),
  206956. buffer (bufferSize),
  206957. index (0),
  206958. wantsIndex (false)
  206959. {
  206960. }
  206961. bool isZero() const throw()
  206962. {
  206963. BYTE* p = buffer + dataStartOffset;
  206964. for (int i = dataLength; --i >= 0;)
  206965. if (*p++ != 0)
  206966. return false;
  206967. return true;
  206968. }
  206969. };
  206970. class CDDeviceHandle;
  206971. class CDController
  206972. {
  206973. public:
  206974. CDController();
  206975. virtual ~CDController();
  206976. virtual bool read (CDReadBuffer* t) = 0;
  206977. virtual void shutDown();
  206978. bool readAudio (CDReadBuffer* t, CDReadBuffer* overlapBuffer = 0);
  206979. int getLastIndex();
  206980. public:
  206981. bool initialised;
  206982. CDDeviceHandle* deviceInfo;
  206983. int framesToCheck, framesOverlap;
  206984. void prepare (SRB_ExecSCSICmd& s);
  206985. void perform (SRB_ExecSCSICmd& s);
  206986. void setPaused (bool paused);
  206987. };
  206988. #pragma pack(1)
  206989. struct TOCTRACK
  206990. {
  206991. BYTE rsvd;
  206992. BYTE ADR;
  206993. BYTE trackNumber;
  206994. BYTE rsvd2;
  206995. BYTE addr[4];
  206996. };
  206997. struct TOC
  206998. {
  206999. WORD tocLen;
  207000. BYTE firstTrack;
  207001. BYTE lastTrack;
  207002. TOCTRACK tracks[100];
  207003. };
  207004. #pragma pack()
  207005. enum
  207006. {
  207007. READTYPE_ANY = 0,
  207008. READTYPE_ATAPI1 = 1,
  207009. READTYPE_ATAPI2 = 2,
  207010. READTYPE_READ6 = 3,
  207011. READTYPE_READ10 = 4,
  207012. READTYPE_READ_D8 = 5,
  207013. READTYPE_READ_D4 = 6,
  207014. READTYPE_READ_D4_1 = 7,
  207015. READTYPE_READ10_2 = 8
  207016. };
  207017. class CDDeviceHandle
  207018. {
  207019. public:
  207020. CDDeviceHandle (const CDDeviceInfo* const device)
  207021. : scsiHandle (0),
  207022. readType (READTYPE_ANY),
  207023. controller (0)
  207024. {
  207025. memcpy (&info, device, sizeof (info));
  207026. }
  207027. ~CDDeviceHandle()
  207028. {
  207029. if (controller != 0)
  207030. {
  207031. controller->shutDown();
  207032. controller = 0;
  207033. }
  207034. if (scsiHandle != 0)
  207035. CloseHandle (scsiHandle);
  207036. }
  207037. bool readTOC (TOC* lpToc, bool useMSF);
  207038. bool readAudio (CDReadBuffer* buffer, CDReadBuffer* overlapBuffer = 0);
  207039. void openDrawer (bool shouldBeOpen);
  207040. CDDeviceInfo info;
  207041. HANDLE scsiHandle;
  207042. BYTE readType;
  207043. private:
  207044. ScopedPointer<CDController> controller;
  207045. bool testController (const int readType,
  207046. CDController* const newController,
  207047. CDReadBuffer* const bufferToUse);
  207048. };
  207049. DWORD (*fGetASPI32SupportInfo)(void);
  207050. DWORD (*fSendASPI32Command)(LPSRB);
  207051. static HINSTANCE winAspiLib = 0;
  207052. static bool usingScsi = false;
  207053. static bool initialised = false;
  207054. static bool InitialiseCDRipper()
  207055. {
  207056. if (! initialised)
  207057. {
  207058. initialised = true;
  207059. OSVERSIONINFO info;
  207060. info.dwOSVersionInfoSize = sizeof (info);
  207061. GetVersionEx (&info);
  207062. usingScsi = (info.dwPlatformId == VER_PLATFORM_WIN32_NT) && (info.dwMajorVersion > 4);
  207063. if (! usingScsi)
  207064. {
  207065. fGetASPI32SupportInfo = 0;
  207066. fSendASPI32Command = 0;
  207067. winAspiLib = LoadLibrary (_T("WNASPI32.DLL"));
  207068. if (winAspiLib != 0)
  207069. {
  207070. fGetASPI32SupportInfo = (DWORD(*)(void)) GetProcAddress (winAspiLib, "GetASPI32SupportInfo");
  207071. fSendASPI32Command = (DWORD(*)(LPSRB)) GetProcAddress (winAspiLib, "SendASPI32Command");
  207072. if (fGetASPI32SupportInfo == 0 || fSendASPI32Command == 0)
  207073. return false;
  207074. }
  207075. else
  207076. {
  207077. usingScsi = true;
  207078. }
  207079. }
  207080. }
  207081. return true;
  207082. }
  207083. static void DeinitialiseCDRipper()
  207084. {
  207085. if (winAspiLib != 0)
  207086. {
  207087. fGetASPI32SupportInfo = 0;
  207088. fSendASPI32Command = 0;
  207089. FreeLibrary (winAspiLib);
  207090. winAspiLib = 0;
  207091. }
  207092. initialised = false;
  207093. }
  207094. static HANDLE CreateSCSIDeviceHandle (char driveLetter)
  207095. {
  207096. TCHAR devicePath[] = { '\\', '\\', '.', '\\', driveLetter, ':', 0, 0 };
  207097. OSVERSIONINFO info;
  207098. info.dwOSVersionInfoSize = sizeof (info);
  207099. GetVersionEx (&info);
  207100. DWORD flags = GENERIC_READ;
  207101. if ((info.dwPlatformId == VER_PLATFORM_WIN32_NT) && (info.dwMajorVersion > 4))
  207102. flags = GENERIC_READ | GENERIC_WRITE;
  207103. HANDLE h = CreateFile (devicePath, flags, FILE_SHARE_WRITE | FILE_SHARE_READ, 0, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0);
  207104. if (h == INVALID_HANDLE_VALUE)
  207105. {
  207106. flags ^= GENERIC_WRITE;
  207107. h = CreateFile (devicePath, flags, FILE_SHARE_WRITE | FILE_SHARE_READ, 0, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0);
  207108. }
  207109. return h;
  207110. }
  207111. static DWORD performScsiPassThroughCommand (const LPSRB_ExecSCSICmd srb,
  207112. const char driveLetter,
  207113. HANDLE& deviceHandle,
  207114. const bool retryOnFailure = true)
  207115. {
  207116. SCSI_PASS_THROUGH_DIRECT_WITH_BUFFER s;
  207117. zerostruct (s);
  207118. s.spt.Length = sizeof (SCSI_PASS_THROUGH);
  207119. s.spt.CdbLength = srb->SRB_CDBLen;
  207120. s.spt.DataIn = (BYTE) ((srb->SRB_Flags & SRB_DIR_IN)
  207121. ? SCSI_IOCTL_DATA_IN
  207122. : ((srb->SRB_Flags & SRB_DIR_OUT)
  207123. ? SCSI_IOCTL_DATA_OUT
  207124. : SCSI_IOCTL_DATA_UNSPECIFIED));
  207125. s.spt.DataTransferLength = srb->SRB_BufLen;
  207126. s.spt.TimeOutValue = 5;
  207127. s.spt.DataBuffer = srb->SRB_BufPointer;
  207128. s.spt.SenseInfoOffset = offsetof (SCSI_PASS_THROUGH_DIRECT_WITH_BUFFER, ucSenseBuf);
  207129. memcpy (s.spt.Cdb, srb->CDBByte, srb->SRB_CDBLen);
  207130. srb->SRB_Status = SS_ERR;
  207131. srb->SRB_TargStat = 0x0004;
  207132. DWORD bytesReturned = 0;
  207133. if (DeviceIoControl (deviceHandle, IOCTL_SCSI_PASS_THROUGH_DIRECT,
  207134. &s, sizeof (s),
  207135. &s, sizeof (s),
  207136. &bytesReturned, 0) != 0)
  207137. {
  207138. srb->SRB_Status = SS_COMP;
  207139. }
  207140. else if (retryOnFailure)
  207141. {
  207142. const DWORD error = GetLastError();
  207143. if ((error == ERROR_MEDIA_CHANGED) || (error == ERROR_INVALID_HANDLE))
  207144. {
  207145. if (error != ERROR_INVALID_HANDLE)
  207146. CloseHandle (deviceHandle);
  207147. deviceHandle = CreateSCSIDeviceHandle (driveLetter);
  207148. return performScsiPassThroughCommand (srb, driveLetter, deviceHandle, false);
  207149. }
  207150. }
  207151. return srb->SRB_Status;
  207152. }
  207153. // Controller types..
  207154. class ControllerType1 : public CDController
  207155. {
  207156. public:
  207157. ControllerType1() {}
  207158. ~ControllerType1() {}
  207159. bool read (CDReadBuffer* rb)
  207160. {
  207161. if (rb->numFrames * 2352 > rb->bufferSize)
  207162. return false;
  207163. SRB_ExecSCSICmd s;
  207164. prepare (s);
  207165. s.SRB_Flags = SRB_DIR_IN | SRB_EVENT_NOTIFY;
  207166. s.SRB_BufLen = rb->bufferSize;
  207167. s.SRB_BufPointer = rb->buffer;
  207168. s.SRB_CDBLen = 12;
  207169. s.CDBByte[0] = 0xBE;
  207170. s.CDBByte[3] = (BYTE)((rb->startFrame >> 16) & 0xFF);
  207171. s.CDBByte[4] = (BYTE)((rb->startFrame >> 8) & 0xFF);
  207172. s.CDBByte[5] = (BYTE)(rb->startFrame & 0xFF);
  207173. s.CDBByte[8] = (BYTE)(rb->numFrames & 0xFF);
  207174. s.CDBByte[9] = (BYTE)((deviceInfo->readType == READTYPE_ATAPI1) ? 0x10 : 0xF0);
  207175. perform (s);
  207176. if (s.SRB_Status != SS_COMP)
  207177. return false;
  207178. rb->dataLength = rb->numFrames * 2352;
  207179. rb->dataStartOffset = 0;
  207180. return true;
  207181. }
  207182. };
  207183. class ControllerType2 : public CDController
  207184. {
  207185. public:
  207186. ControllerType2() {}
  207187. ~ControllerType2() {}
  207188. void shutDown()
  207189. {
  207190. if (initialised)
  207191. {
  207192. BYTE bufPointer[] = { 0, 0, 0, 8, 83, 0, 0, 0, 0, 0, 8, 0 };
  207193. SRB_ExecSCSICmd s;
  207194. prepare (s);
  207195. s.SRB_Flags = SRB_EVENT_NOTIFY | SRB_ENABLE_RESIDUAL_COUNT;
  207196. s.SRB_BufLen = 0x0C;
  207197. s.SRB_BufPointer = bufPointer;
  207198. s.SRB_CDBLen = 6;
  207199. s.CDBByte[0] = 0x15;
  207200. s.CDBByte[4] = 0x0C;
  207201. perform (s);
  207202. }
  207203. }
  207204. bool init()
  207205. {
  207206. SRB_ExecSCSICmd s;
  207207. s.SRB_Status = SS_ERR;
  207208. if (deviceInfo->readType == READTYPE_READ10_2)
  207209. {
  207210. BYTE bufPointer1[] = { 0, 0, 0, 8, 0, 0, 0, 0, 0, 0, 9, 48, 35, 6, 0, 0, 0, 0, 0, 128 };
  207211. BYTE bufPointer2[] = { 0, 0, 0, 8, 0, 0, 0, 0, 0, 0, 9, 48, 1, 6, 32, 7, 0, 0, 0, 0 };
  207212. for (int i = 0; i < 2; ++i)
  207213. {
  207214. prepare (s);
  207215. s.SRB_Flags = SRB_EVENT_NOTIFY;
  207216. s.SRB_BufLen = 0x14;
  207217. s.SRB_BufPointer = (i == 0) ? bufPointer1 : bufPointer2;
  207218. s.SRB_CDBLen = 6;
  207219. s.CDBByte[0] = 0x15;
  207220. s.CDBByte[1] = 0x10;
  207221. s.CDBByte[4] = 0x14;
  207222. perform (s);
  207223. if (s.SRB_Status != SS_COMP)
  207224. return false;
  207225. }
  207226. }
  207227. else
  207228. {
  207229. BYTE bufPointer[] = { 0, 0, 0, 8, 0, 0, 0, 0, 0, 0, 9, 48 };
  207230. prepare (s);
  207231. s.SRB_Flags = SRB_EVENT_NOTIFY;
  207232. s.SRB_BufLen = 0x0C;
  207233. s.SRB_BufPointer = bufPointer;
  207234. s.SRB_CDBLen = 6;
  207235. s.CDBByte[0] = 0x15;
  207236. s.CDBByte[4] = 0x0C;
  207237. perform (s);
  207238. }
  207239. return s.SRB_Status == SS_COMP;
  207240. }
  207241. bool read (CDReadBuffer* rb)
  207242. {
  207243. if (rb->numFrames * 2352 > rb->bufferSize)
  207244. return false;
  207245. if (!initialised)
  207246. {
  207247. initialised = init();
  207248. if (!initialised)
  207249. return false;
  207250. }
  207251. SRB_ExecSCSICmd s;
  207252. prepare (s);
  207253. s.SRB_Flags = SRB_DIR_IN | SRB_EVENT_NOTIFY;
  207254. s.SRB_BufLen = rb->bufferSize;
  207255. s.SRB_BufPointer = rb->buffer;
  207256. s.SRB_CDBLen = 10;
  207257. s.CDBByte[0] = 0x28;
  207258. s.CDBByte[1] = (BYTE)(deviceInfo->info.lun << 5);
  207259. s.CDBByte[3] = (BYTE)((rb->startFrame >> 16) & 0xFF);
  207260. s.CDBByte[4] = (BYTE)((rb->startFrame >> 8) & 0xFF);
  207261. s.CDBByte[5] = (BYTE)(rb->startFrame & 0xFF);
  207262. s.CDBByte[8] = (BYTE)(rb->numFrames & 0xFF);
  207263. perform (s);
  207264. if (s.SRB_Status != SS_COMP)
  207265. return false;
  207266. rb->dataLength = rb->numFrames * 2352;
  207267. rb->dataStartOffset = 0;
  207268. return true;
  207269. }
  207270. };
  207271. class ControllerType3 : public CDController
  207272. {
  207273. public:
  207274. ControllerType3() {}
  207275. ~ControllerType3() {}
  207276. bool read (CDReadBuffer* rb)
  207277. {
  207278. if (rb->numFrames * 2352 > rb->bufferSize)
  207279. return false;
  207280. if (!initialised)
  207281. {
  207282. setPaused (false);
  207283. initialised = true;
  207284. }
  207285. SRB_ExecSCSICmd s;
  207286. prepare (s);
  207287. s.SRB_Flags = SRB_DIR_IN | SRB_EVENT_NOTIFY;
  207288. s.SRB_BufLen = rb->numFrames * 2352;
  207289. s.SRB_BufPointer = rb->buffer;
  207290. s.SRB_CDBLen = 12;
  207291. s.CDBByte[0] = 0xD8;
  207292. s.CDBByte[3] = (BYTE)((rb->startFrame >> 16) & 0xFF);
  207293. s.CDBByte[4] = (BYTE)((rb->startFrame >> 8) & 0xFF);
  207294. s.CDBByte[5] = (BYTE)(rb->startFrame & 0xFF);
  207295. s.CDBByte[9] = (BYTE)(rb->numFrames & 0xFF);
  207296. perform (s);
  207297. if (s.SRB_Status != SS_COMP)
  207298. return false;
  207299. rb->dataLength = rb->numFrames * 2352;
  207300. rb->dataStartOffset = 0;
  207301. return true;
  207302. }
  207303. };
  207304. class ControllerType4 : public CDController
  207305. {
  207306. public:
  207307. ControllerType4() {}
  207308. ~ControllerType4() {}
  207309. bool selectD4Mode()
  207310. {
  207311. BYTE bufPointer[12] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 9, 48 };
  207312. SRB_ExecSCSICmd s;
  207313. prepare (s);
  207314. s.SRB_Flags = SRB_EVENT_NOTIFY;
  207315. s.SRB_CDBLen = 6;
  207316. s.SRB_BufLen = 12;
  207317. s.SRB_BufPointer = bufPointer;
  207318. s.CDBByte[0] = 0x15;
  207319. s.CDBByte[1] = 0x10;
  207320. s.CDBByte[4] = 0x08;
  207321. perform (s);
  207322. return s.SRB_Status == SS_COMP;
  207323. }
  207324. bool read (CDReadBuffer* rb)
  207325. {
  207326. if (rb->numFrames * 2352 > rb->bufferSize)
  207327. return false;
  207328. if (!initialised)
  207329. {
  207330. setPaused (true);
  207331. if (deviceInfo->readType == READTYPE_READ_D4_1)
  207332. selectD4Mode();
  207333. initialised = true;
  207334. }
  207335. SRB_ExecSCSICmd s;
  207336. prepare (s);
  207337. s.SRB_Flags = SRB_DIR_IN | SRB_EVENT_NOTIFY;
  207338. s.SRB_BufLen = rb->bufferSize;
  207339. s.SRB_BufPointer = rb->buffer;
  207340. s.SRB_CDBLen = 10;
  207341. s.CDBByte[0] = 0xD4;
  207342. s.CDBByte[3] = (BYTE)((rb->startFrame >> 16) & 0xFF);
  207343. s.CDBByte[4] = (BYTE)((rb->startFrame >> 8) & 0xFF);
  207344. s.CDBByte[5] = (BYTE)(rb->startFrame & 0xFF);
  207345. s.CDBByte[8] = (BYTE)(rb->numFrames & 0xFF);
  207346. perform (s);
  207347. if (s.SRB_Status != SS_COMP)
  207348. return false;
  207349. rb->dataLength = rb->numFrames * 2352;
  207350. rb->dataStartOffset = 0;
  207351. return true;
  207352. }
  207353. };
  207354. CDController::CDController() : initialised (false)
  207355. {
  207356. }
  207357. CDController::~CDController()
  207358. {
  207359. }
  207360. void CDController::prepare (SRB_ExecSCSICmd& s)
  207361. {
  207362. zerostruct (s);
  207363. s.SRB_Cmd = SC_EXEC_SCSI_CMD;
  207364. s.SRB_HaID = deviceInfo->info.ha;
  207365. s.SRB_Target = deviceInfo->info.tgt;
  207366. s.SRB_Lun = deviceInfo->info.lun;
  207367. s.SRB_SenseLen = SENSE_LEN;
  207368. }
  207369. void CDController::perform (SRB_ExecSCSICmd& s)
  207370. {
  207371. HANDLE event = CreateEvent (0, TRUE, FALSE, 0);
  207372. s.SRB_PostProc = event;
  207373. ResetEvent (event);
  207374. DWORD status = (usingScsi) ? performScsiPassThroughCommand ((LPSRB_ExecSCSICmd)&s,
  207375. deviceInfo->info.scsiDriveLetter,
  207376. deviceInfo->scsiHandle)
  207377. : fSendASPI32Command ((LPSRB)&s);
  207378. if (status == SS_PENDING)
  207379. WaitForSingleObject (event, 4000);
  207380. CloseHandle (event);
  207381. }
  207382. void CDController::setPaused (bool paused)
  207383. {
  207384. SRB_ExecSCSICmd s;
  207385. prepare (s);
  207386. s.SRB_Flags = SRB_EVENT_NOTIFY;
  207387. s.SRB_CDBLen = 10;
  207388. s.CDBByte[0] = 0x4B;
  207389. s.CDBByte[8] = (BYTE) (paused ? 0 : 1);
  207390. perform (s);
  207391. }
  207392. void CDController::shutDown()
  207393. {
  207394. }
  207395. bool CDController::readAudio (CDReadBuffer* rb, CDReadBuffer* overlapBuffer)
  207396. {
  207397. if (overlapBuffer != 0)
  207398. {
  207399. const bool canDoJitter = (overlapBuffer->bufferSize >= 2352 * framesToCheck);
  207400. const bool doJitter = canDoJitter && ! overlapBuffer->isZero();
  207401. if (doJitter
  207402. && overlapBuffer->startFrame > 0
  207403. && overlapBuffer->numFrames > 0
  207404. && overlapBuffer->dataLength > 0)
  207405. {
  207406. const int numFrames = rb->numFrames;
  207407. if (overlapBuffer->startFrame == (rb->startFrame - framesToCheck))
  207408. {
  207409. rb->startFrame -= framesOverlap;
  207410. if (framesToCheck < framesOverlap
  207411. && numFrames + framesOverlap <= rb->bufferSize / 2352)
  207412. rb->numFrames += framesOverlap;
  207413. }
  207414. else
  207415. {
  207416. overlapBuffer->dataLength = 0;
  207417. overlapBuffer->startFrame = 0;
  207418. overlapBuffer->numFrames = 0;
  207419. }
  207420. }
  207421. if (! read (rb))
  207422. return false;
  207423. if (doJitter)
  207424. {
  207425. const int checkLen = framesToCheck * 2352;
  207426. const int maxToCheck = rb->dataLength - checkLen;
  207427. if (overlapBuffer->dataLength == 0 || overlapBuffer->isZero())
  207428. return true;
  207429. BYTE* const p = overlapBuffer->buffer + overlapBuffer->dataStartOffset;
  207430. bool found = false;
  207431. for (int i = 0; i < maxToCheck; ++i)
  207432. {
  207433. if (memcmp (p, rb->buffer + i, checkLen) == 0)
  207434. {
  207435. i += checkLen;
  207436. rb->dataStartOffset = i;
  207437. rb->dataLength -= i;
  207438. rb->startFrame = overlapBuffer->startFrame + framesToCheck;
  207439. found = true;
  207440. break;
  207441. }
  207442. }
  207443. rb->numFrames = rb->dataLength / 2352;
  207444. rb->dataLength = 2352 * rb->numFrames;
  207445. if (!found)
  207446. return false;
  207447. }
  207448. if (canDoJitter)
  207449. {
  207450. memcpy (overlapBuffer->buffer,
  207451. rb->buffer + rb->dataStartOffset + 2352 * (rb->numFrames - framesToCheck),
  207452. 2352 * framesToCheck);
  207453. overlapBuffer->startFrame = rb->startFrame + rb->numFrames - framesToCheck;
  207454. overlapBuffer->numFrames = framesToCheck;
  207455. overlapBuffer->dataLength = 2352 * framesToCheck;
  207456. overlapBuffer->dataStartOffset = 0;
  207457. }
  207458. else
  207459. {
  207460. overlapBuffer->startFrame = 0;
  207461. overlapBuffer->numFrames = 0;
  207462. overlapBuffer->dataLength = 0;
  207463. }
  207464. return true;
  207465. }
  207466. else
  207467. {
  207468. return read (rb);
  207469. }
  207470. }
  207471. int CDController::getLastIndex()
  207472. {
  207473. char qdata[100];
  207474. SRB_ExecSCSICmd s;
  207475. prepare (s);
  207476. s.SRB_Flags = SRB_DIR_IN | SRB_EVENT_NOTIFY;
  207477. s.SRB_BufLen = sizeof (qdata);
  207478. s.SRB_BufPointer = (BYTE*)qdata;
  207479. s.SRB_CDBLen = 12;
  207480. s.CDBByte[0] = 0x42;
  207481. s.CDBByte[1] = (BYTE)(deviceInfo->info.lun << 5);
  207482. s.CDBByte[2] = 64;
  207483. s.CDBByte[3] = 1; // get current position
  207484. s.CDBByte[7] = 0;
  207485. s.CDBByte[8] = (BYTE)sizeof (qdata);
  207486. perform (s);
  207487. if (s.SRB_Status == SS_COMP)
  207488. return qdata[7];
  207489. return 0;
  207490. }
  207491. bool CDDeviceHandle::readTOC (TOC* lpToc, bool useMSF)
  207492. {
  207493. HANDLE event = CreateEvent (0, TRUE, FALSE, 0);
  207494. SRB_ExecSCSICmd s;
  207495. zerostruct (s);
  207496. s.SRB_Cmd = SC_EXEC_SCSI_CMD;
  207497. s.SRB_HaID = info.ha;
  207498. s.SRB_Target = info.tgt;
  207499. s.SRB_Lun = info.lun;
  207500. s.SRB_Flags = SRB_DIR_IN | SRB_EVENT_NOTIFY;
  207501. s.SRB_BufLen = 0x324;
  207502. s.SRB_BufPointer = (BYTE*)lpToc;
  207503. s.SRB_SenseLen = 0x0E;
  207504. s.SRB_CDBLen = 0x0A;
  207505. s.SRB_PostProc = event;
  207506. s.CDBByte[0] = 0x43;
  207507. s.CDBByte[1] = (BYTE)(useMSF ? 0x02 : 0x00);
  207508. s.CDBByte[7] = 0x03;
  207509. s.CDBByte[8] = 0x24;
  207510. ResetEvent (event);
  207511. DWORD status = (usingScsi) ? performScsiPassThroughCommand ((LPSRB_ExecSCSICmd)&s, info.scsiDriveLetter, scsiHandle)
  207512. : fSendASPI32Command ((LPSRB)&s);
  207513. if (status == SS_PENDING)
  207514. WaitForSingleObject (event, 4000);
  207515. CloseHandle (event);
  207516. return (s.SRB_Status == SS_COMP);
  207517. }
  207518. bool CDDeviceHandle::readAudio (CDReadBuffer* const buffer,
  207519. CDReadBuffer* const overlapBuffer)
  207520. {
  207521. if (controller == 0)
  207522. {
  207523. testController (READTYPE_ATAPI2, new ControllerType1(), buffer)
  207524. || testController (READTYPE_ATAPI1, new ControllerType1(), buffer)
  207525. || testController (READTYPE_READ10_2, new ControllerType2(), buffer)
  207526. || testController (READTYPE_READ10, new ControllerType2(), buffer)
  207527. || testController (READTYPE_READ_D8, new ControllerType3(), buffer)
  207528. || testController (READTYPE_READ_D4, new ControllerType4(), buffer)
  207529. || testController (READTYPE_READ_D4_1, new ControllerType4(), buffer);
  207530. }
  207531. buffer->index = 0;
  207532. if ((controller != 0)
  207533. && controller->readAudio (buffer, overlapBuffer))
  207534. {
  207535. if (buffer->wantsIndex)
  207536. buffer->index = controller->getLastIndex();
  207537. return true;
  207538. }
  207539. return false;
  207540. }
  207541. void CDDeviceHandle::openDrawer (bool shouldBeOpen)
  207542. {
  207543. if (shouldBeOpen)
  207544. {
  207545. if (controller != 0)
  207546. {
  207547. controller->shutDown();
  207548. controller = 0;
  207549. }
  207550. if (scsiHandle != 0)
  207551. {
  207552. CloseHandle (scsiHandle);
  207553. scsiHandle = 0;
  207554. }
  207555. }
  207556. SRB_ExecSCSICmd s;
  207557. zerostruct (s);
  207558. s.SRB_Cmd = SC_EXEC_SCSI_CMD;
  207559. s.SRB_HaID = info.ha;
  207560. s.SRB_Target = info.tgt;
  207561. s.SRB_Lun = info.lun;
  207562. s.SRB_SenseLen = SENSE_LEN;
  207563. s.SRB_Flags = SRB_DIR_IN | SRB_EVENT_NOTIFY;
  207564. s.SRB_BufLen = 0;
  207565. s.SRB_BufPointer = 0;
  207566. s.SRB_CDBLen = 12;
  207567. s.CDBByte[0] = 0x1b;
  207568. s.CDBByte[1] = (BYTE)(info.lun << 5);
  207569. s.CDBByte[4] = (BYTE)((shouldBeOpen) ? 2 : 3);
  207570. HANDLE event = CreateEvent (0, TRUE, FALSE, 0);
  207571. s.SRB_PostProc = event;
  207572. ResetEvent (event);
  207573. DWORD status = (usingScsi) ? performScsiPassThroughCommand ((LPSRB_ExecSCSICmd)&s, info.scsiDriveLetter, scsiHandle)
  207574. : fSendASPI32Command ((LPSRB)&s);
  207575. if (status == SS_PENDING)
  207576. WaitForSingleObject (event, 4000);
  207577. CloseHandle (event);
  207578. }
  207579. bool CDDeviceHandle::testController (const int type,
  207580. CDController* const newController,
  207581. CDReadBuffer* const rb)
  207582. {
  207583. controller = newController;
  207584. readType = (BYTE)type;
  207585. controller->deviceInfo = this;
  207586. controller->framesToCheck = 1;
  207587. controller->framesOverlap = 3;
  207588. bool passed = false;
  207589. memset (rb->buffer, 0xcd, rb->bufferSize);
  207590. if (controller->read (rb))
  207591. {
  207592. passed = true;
  207593. int* p = (int*) (rb->buffer + rb->dataStartOffset);
  207594. int wrong = 0;
  207595. for (int i = rb->dataLength / 4; --i >= 0;)
  207596. {
  207597. if (*p++ == (int) 0xcdcdcdcd)
  207598. {
  207599. if (++wrong == 4)
  207600. {
  207601. passed = false;
  207602. break;
  207603. }
  207604. }
  207605. else
  207606. {
  207607. wrong = 0;
  207608. }
  207609. }
  207610. }
  207611. if (! passed)
  207612. {
  207613. controller->shutDown();
  207614. controller = 0;
  207615. }
  207616. return passed;
  207617. }
  207618. static void GetAspiDeviceInfo (CDDeviceInfo* dev, BYTE ha, BYTE tgt, BYTE lun)
  207619. {
  207620. HANDLE event = CreateEvent (0, TRUE, FALSE, 0);
  207621. const int bufSize = 128;
  207622. BYTE buffer[bufSize];
  207623. zeromem (buffer, bufSize);
  207624. SRB_ExecSCSICmd s;
  207625. zerostruct (s);
  207626. s.SRB_Cmd = SC_EXEC_SCSI_CMD;
  207627. s.SRB_HaID = ha;
  207628. s.SRB_Target = tgt;
  207629. s.SRB_Lun = lun;
  207630. s.SRB_Flags = SRB_DIR_IN | SRB_EVENT_NOTIFY;
  207631. s.SRB_BufLen = bufSize;
  207632. s.SRB_BufPointer = buffer;
  207633. s.SRB_SenseLen = SENSE_LEN;
  207634. s.SRB_CDBLen = 6;
  207635. s.SRB_PostProc = event;
  207636. s.CDBByte[0] = SCSI_INQUIRY;
  207637. s.CDBByte[4] = 100;
  207638. ResetEvent (event);
  207639. if (fSendASPI32Command ((LPSRB)&s) == SS_PENDING)
  207640. WaitForSingleObject (event, 4000);
  207641. CloseHandle (event);
  207642. if (s.SRB_Status == SS_COMP)
  207643. {
  207644. memcpy (dev->vendor, &buffer[8], 8);
  207645. memcpy (dev->productId, &buffer[16], 16);
  207646. memcpy (dev->rev, &buffer[32], 4);
  207647. memcpy (dev->vendorSpec, &buffer[36], 20);
  207648. }
  207649. }
  207650. static int FindCDDevices (CDDeviceInfo* const list,
  207651. int maxItems)
  207652. {
  207653. int count = 0;
  207654. if (usingScsi)
  207655. {
  207656. for (char driveLetter = 'b'; driveLetter <= 'z'; ++driveLetter)
  207657. {
  207658. TCHAR drivePath[8];
  207659. drivePath[0] = driveLetter;
  207660. drivePath[1] = ':';
  207661. drivePath[2] = '\\';
  207662. drivePath[3] = 0;
  207663. if (GetDriveType (drivePath) == DRIVE_CDROM)
  207664. {
  207665. HANDLE h = CreateSCSIDeviceHandle (driveLetter);
  207666. if (h != INVALID_HANDLE_VALUE)
  207667. {
  207668. BYTE buffer[100], passThroughStruct[1024];
  207669. zeromem (buffer, sizeof (buffer));
  207670. zeromem (passThroughStruct, sizeof (passThroughStruct));
  207671. PSCSI_PASS_THROUGH_DIRECT_WITH_BUFFER p = (PSCSI_PASS_THROUGH_DIRECT_WITH_BUFFER)passThroughStruct;
  207672. p->spt.Length = sizeof (SCSI_PASS_THROUGH);
  207673. p->spt.CdbLength = 6;
  207674. p->spt.SenseInfoLength = 24;
  207675. p->spt.DataIn = SCSI_IOCTL_DATA_IN;
  207676. p->spt.DataTransferLength = 100;
  207677. p->spt.TimeOutValue = 2;
  207678. p->spt.DataBuffer = buffer;
  207679. p->spt.SenseInfoOffset = offsetof (SCSI_PASS_THROUGH_DIRECT_WITH_BUFFER, ucSenseBuf);
  207680. p->spt.Cdb[0] = 0x12;
  207681. p->spt.Cdb[4] = 100;
  207682. DWORD bytesReturned = 0;
  207683. if (DeviceIoControl (h, IOCTL_SCSI_PASS_THROUGH_DIRECT,
  207684. p, sizeof (SCSI_PASS_THROUGH_DIRECT_WITH_BUFFER),
  207685. p, sizeof (SCSI_PASS_THROUGH_DIRECT_WITH_BUFFER),
  207686. &bytesReturned, 0) != 0)
  207687. {
  207688. zeromem (&list[count], sizeof (CDDeviceInfo));
  207689. list[count].scsiDriveLetter = driveLetter;
  207690. memcpy (list[count].vendor, &buffer[8], 8);
  207691. memcpy (list[count].productId, &buffer[16], 16);
  207692. memcpy (list[count].rev, &buffer[32], 4);
  207693. memcpy (list[count].vendorSpec, &buffer[36], 20);
  207694. zeromem (passThroughStruct, sizeof (passThroughStruct));
  207695. PSCSI_ADDRESS scsiAddr = (PSCSI_ADDRESS)passThroughStruct;
  207696. scsiAddr->Length = sizeof (SCSI_ADDRESS);
  207697. if (DeviceIoControl (h, IOCTL_SCSI_GET_ADDRESS,
  207698. 0, 0, scsiAddr, sizeof (SCSI_ADDRESS),
  207699. &bytesReturned, 0) != 0)
  207700. {
  207701. list[count].ha = scsiAddr->PortNumber;
  207702. list[count].tgt = scsiAddr->TargetId;
  207703. list[count].lun = scsiAddr->Lun;
  207704. ++count;
  207705. }
  207706. }
  207707. CloseHandle (h);
  207708. }
  207709. }
  207710. }
  207711. }
  207712. else
  207713. {
  207714. const DWORD d = fGetASPI32SupportInfo();
  207715. BYTE status = HIBYTE (LOWORD (d));
  207716. if (status != SS_COMP || status == SS_NO_ADAPTERS)
  207717. return 0;
  207718. const int numAdapters = LOBYTE (LOWORD (d));
  207719. for (BYTE ha = 0; ha < numAdapters; ++ha)
  207720. {
  207721. SRB_HAInquiry s;
  207722. zerostruct (s);
  207723. s.SRB_Cmd = SC_HA_INQUIRY;
  207724. s.SRB_HaID = ha;
  207725. fSendASPI32Command ((LPSRB)&s);
  207726. if (s.SRB_Status == SS_COMP)
  207727. {
  207728. maxItems = (int)s.HA_Unique[3];
  207729. if (maxItems == 0)
  207730. maxItems = 8;
  207731. for (BYTE tgt = 0; tgt < maxItems; ++tgt)
  207732. {
  207733. for (BYTE lun = 0; lun < 8; ++lun)
  207734. {
  207735. SRB_GDEVBlock sb;
  207736. zerostruct (sb);
  207737. sb.SRB_Cmd = SC_GET_DEV_TYPE;
  207738. sb.SRB_HaID = ha;
  207739. sb.SRB_Target = tgt;
  207740. sb.SRB_Lun = lun;
  207741. fSendASPI32Command ((LPSRB) &sb);
  207742. if (sb.SRB_Status == SS_COMP
  207743. && sb.SRB_DeviceType == DTYPE_CROM)
  207744. {
  207745. zeromem (&list[count], sizeof (CDDeviceInfo));
  207746. list[count].ha = ha;
  207747. list[count].tgt = tgt;
  207748. list[count].lun = lun;
  207749. GetAspiDeviceInfo (&(list[count]), ha, tgt, lun);
  207750. ++count;
  207751. }
  207752. }
  207753. }
  207754. }
  207755. }
  207756. }
  207757. return count;
  207758. }
  207759. static int ripperUsers = 0;
  207760. static bool initialisedOk = false;
  207761. class DeinitialiseTimer : private Timer,
  207762. private DeletedAtShutdown
  207763. {
  207764. DeinitialiseTimer (const DeinitialiseTimer&);
  207765. DeinitialiseTimer& operator= (const DeinitialiseTimer&);
  207766. public:
  207767. DeinitialiseTimer()
  207768. {
  207769. startTimer (4000);
  207770. }
  207771. ~DeinitialiseTimer()
  207772. {
  207773. if (--ripperUsers == 0)
  207774. DeinitialiseCDRipper();
  207775. }
  207776. void timerCallback()
  207777. {
  207778. delete this;
  207779. }
  207780. juce_UseDebuggingNewOperator
  207781. };
  207782. static void incUserCount()
  207783. {
  207784. if (ripperUsers++ == 0)
  207785. initialisedOk = InitialiseCDRipper();
  207786. }
  207787. static void decUserCount()
  207788. {
  207789. new DeinitialiseTimer();
  207790. }
  207791. struct CDDeviceWrapper
  207792. {
  207793. ScopedPointer<CDDeviceHandle> cdH;
  207794. ScopedPointer<CDReadBuffer> overlapBuffer;
  207795. bool jitter;
  207796. };
  207797. static int getAddressOf (const TOCTRACK* const t)
  207798. {
  207799. return (((DWORD)t->addr[0]) << 24) + (((DWORD)t->addr[1]) << 16) +
  207800. (((DWORD)t->addr[2]) << 8) + ((DWORD)t->addr[3]);
  207801. }
  207802. static int getMSFAddressOf (const TOCTRACK* const t)
  207803. {
  207804. return 60 * t->addr[1] + t->addr[2];
  207805. }
  207806. static const int samplesPerFrame = 44100 / 75;
  207807. static const int bytesPerFrame = samplesPerFrame * 4;
  207808. static CDDeviceHandle* openHandle (const CDDeviceInfo* const device)
  207809. {
  207810. SRB_GDEVBlock s;
  207811. zerostruct (s);
  207812. s.SRB_Cmd = SC_GET_DEV_TYPE;
  207813. s.SRB_HaID = device->ha;
  207814. s.SRB_Target = device->tgt;
  207815. s.SRB_Lun = device->lun;
  207816. if (usingScsi)
  207817. {
  207818. HANDLE h = CreateSCSIDeviceHandle (device->scsiDriveLetter);
  207819. if (h != INVALID_HANDLE_VALUE)
  207820. {
  207821. CDDeviceHandle* cdh = new CDDeviceHandle (device);
  207822. cdh->scsiHandle = h;
  207823. return cdh;
  207824. }
  207825. }
  207826. else
  207827. {
  207828. if (fSendASPI32Command ((LPSRB)&s) == SS_COMP
  207829. && s.SRB_DeviceType == DTYPE_CROM)
  207830. {
  207831. return new CDDeviceHandle (device);
  207832. }
  207833. }
  207834. return 0;
  207835. }
  207836. }
  207837. const StringArray AudioCDReader::getAvailableCDNames()
  207838. {
  207839. using namespace CDReaderHelpers;
  207840. StringArray results;
  207841. incUserCount();
  207842. if (initialisedOk)
  207843. {
  207844. CDDeviceInfo list[8];
  207845. const int num = FindCDDevices (list, 8);
  207846. decUserCount();
  207847. for (int i = 0; i < num; ++i)
  207848. {
  207849. String s;
  207850. if (list[i].scsiDriveLetter > 0)
  207851. s << String::charToString (list[i].scsiDriveLetter).toUpperCase() << ": ";
  207852. s << String (list[i].vendor).trim()
  207853. << ' ' << String (list[i].productId).trim()
  207854. << ' ' << String (list[i].rev).trim();
  207855. results.add (s);
  207856. }
  207857. }
  207858. return results;
  207859. }
  207860. AudioCDReader* AudioCDReader::createReaderForCD (const int deviceIndex)
  207861. {
  207862. using namespace CDReaderHelpers;
  207863. incUserCount();
  207864. if (initialisedOk)
  207865. {
  207866. CDDeviceInfo list[8];
  207867. const int num = FindCDDevices (list, 8);
  207868. if (((unsigned int) deviceIndex) < (unsigned int) num)
  207869. {
  207870. CDDeviceHandle* const handle = openHandle (&(list[deviceIndex]));
  207871. if (handle != 0)
  207872. {
  207873. CDDeviceWrapper* const d = new CDDeviceWrapper();
  207874. d->cdH = handle;
  207875. d->overlapBuffer = new CDReadBuffer(3);
  207876. return new AudioCDReader (d);
  207877. }
  207878. }
  207879. }
  207880. decUserCount();
  207881. return 0;
  207882. }
  207883. AudioCDReader::AudioCDReader (void* handle_)
  207884. : AudioFormatReader (0, "CD Audio"),
  207885. handle (handle_),
  207886. indexingEnabled (false),
  207887. lastIndex (0),
  207888. firstFrameInBuffer (0),
  207889. samplesInBuffer (0)
  207890. {
  207891. using namespace CDReaderHelpers;
  207892. jassert (handle_ != 0);
  207893. refreshTrackLengths();
  207894. sampleRate = 44100.0;
  207895. bitsPerSample = 16;
  207896. lengthInSamples = getPositionOfTrackStart (numTracks);
  207897. numChannels = 2;
  207898. usesFloatingPointData = false;
  207899. buffer.setSize (4 * bytesPerFrame, true);
  207900. }
  207901. AudioCDReader::~AudioCDReader()
  207902. {
  207903. using namespace CDReaderHelpers;
  207904. CDDeviceWrapper* const device = (CDDeviceWrapper*) handle;
  207905. delete device;
  207906. decUserCount();
  207907. }
  207908. bool AudioCDReader::readSamples (int** destSamples, int numDestChannels, int startOffsetInDestBuffer,
  207909. int64 startSampleInFile, int numSamples)
  207910. {
  207911. using namespace CDReaderHelpers;
  207912. CDDeviceWrapper* const device = (CDDeviceWrapper*) handle;
  207913. bool ok = true;
  207914. while (numSamples > 0)
  207915. {
  207916. const int bufferStartSample = firstFrameInBuffer * samplesPerFrame;
  207917. const int bufferEndSample = bufferStartSample + samplesInBuffer;
  207918. if (startSampleInFile >= bufferStartSample
  207919. && startSampleInFile < bufferEndSample)
  207920. {
  207921. const int toDo = (int) jmin ((int64) numSamples, bufferEndSample - startSampleInFile);
  207922. int* const l = destSamples[0] + startOffsetInDestBuffer;
  207923. int* const r = numDestChannels > 1 ? (destSamples[1] + startOffsetInDestBuffer) : 0;
  207924. const short* src = (const short*) buffer.getData();
  207925. src += 2 * (startSampleInFile - bufferStartSample);
  207926. for (int i = 0; i < toDo; ++i)
  207927. {
  207928. l[i] = src [i << 1] << 16;
  207929. if (r != 0)
  207930. r[i] = src [(i << 1) + 1] << 16;
  207931. }
  207932. startOffsetInDestBuffer += toDo;
  207933. startSampleInFile += toDo;
  207934. numSamples -= toDo;
  207935. }
  207936. else
  207937. {
  207938. const int framesInBuffer = buffer.getSize() / bytesPerFrame;
  207939. const int frameNeeded = (int) (startSampleInFile / samplesPerFrame);
  207940. if (firstFrameInBuffer + framesInBuffer != frameNeeded)
  207941. {
  207942. device->overlapBuffer->dataLength = 0;
  207943. device->overlapBuffer->startFrame = 0;
  207944. device->overlapBuffer->numFrames = 0;
  207945. device->jitter = false;
  207946. }
  207947. firstFrameInBuffer = frameNeeded;
  207948. lastIndex = 0;
  207949. CDReadBuffer readBuffer (framesInBuffer + 4);
  207950. readBuffer.wantsIndex = indexingEnabled;
  207951. int i;
  207952. for (i = 5; --i >= 0;)
  207953. {
  207954. readBuffer.startFrame = frameNeeded;
  207955. readBuffer.numFrames = framesInBuffer;
  207956. if (device->cdH->readAudio (&readBuffer, (device->jitter) ? device->overlapBuffer : 0))
  207957. break;
  207958. else
  207959. device->overlapBuffer->dataLength = 0;
  207960. }
  207961. if (i >= 0)
  207962. {
  207963. memcpy ((char*) buffer.getData(),
  207964. readBuffer.buffer + readBuffer.dataStartOffset,
  207965. readBuffer.dataLength);
  207966. samplesInBuffer = readBuffer.dataLength >> 2;
  207967. lastIndex = readBuffer.index;
  207968. }
  207969. else
  207970. {
  207971. int* l = destSamples[0] + startOffsetInDestBuffer;
  207972. int* r = numDestChannels > 1 ? (destSamples[1] + startOffsetInDestBuffer) : 0;
  207973. while (--numSamples >= 0)
  207974. {
  207975. *l++ = 0;
  207976. if (r != 0)
  207977. *r++ = 0;
  207978. }
  207979. // sometimes the read fails for just the very last couple of blocks, so
  207980. // we'll ignore and errors in the last half-second of the disk..
  207981. ok = startSampleInFile > (trackStarts [numTracks] - 20000);
  207982. break;
  207983. }
  207984. }
  207985. }
  207986. return ok;
  207987. }
  207988. bool AudioCDReader::isCDStillPresent() const
  207989. {
  207990. using namespace CDReaderHelpers;
  207991. TOC toc;
  207992. zerostruct (toc);
  207993. return ((CDDeviceWrapper*) handle)->cdH->readTOC (&toc, false);
  207994. }
  207995. int AudioCDReader::getNumTracks() const
  207996. {
  207997. return numTracks;
  207998. }
  207999. int AudioCDReader::getPositionOfTrackStart (int trackNum) const
  208000. {
  208001. using namespace CDReaderHelpers;
  208002. return (trackNum >= 0 && trackNum <= numTracks) ? trackStarts [trackNum] * samplesPerFrame
  208003. : 0;
  208004. }
  208005. void AudioCDReader::refreshTrackLengths()
  208006. {
  208007. using namespace CDReaderHelpers;
  208008. zeromem (trackStarts, sizeof (trackStarts));
  208009. zeromem (audioTracks, sizeof (audioTracks));
  208010. TOC toc;
  208011. zerostruct (toc);
  208012. if (((CDDeviceWrapper*)handle)->cdH->readTOC (&toc, false))
  208013. {
  208014. numTracks = 1 + toc.lastTrack - toc.firstTrack;
  208015. for (int i = 0; i <= numTracks; ++i)
  208016. {
  208017. trackStarts[i] = getAddressOf (&toc.tracks[i]);
  208018. audioTracks[i] = ((toc.tracks[i].ADR & 4) == 0);
  208019. }
  208020. }
  208021. else
  208022. {
  208023. numTracks = 0;
  208024. }
  208025. }
  208026. bool AudioCDReader::isTrackAudio (int trackNum) const
  208027. {
  208028. return (trackNum >= 0 && trackNum <= numTracks) ? audioTracks [trackNum]
  208029. : false;
  208030. }
  208031. void AudioCDReader::enableIndexScanning (bool b)
  208032. {
  208033. indexingEnabled = b;
  208034. }
  208035. int AudioCDReader::getLastIndex() const
  208036. {
  208037. return lastIndex;
  208038. }
  208039. const int framesPerIndexRead = 4;
  208040. int AudioCDReader::getIndexAt (int samplePos)
  208041. {
  208042. using namespace CDReaderHelpers;
  208043. CDDeviceWrapper* const device = (CDDeviceWrapper*) handle;
  208044. const int frameNeeded = samplePos / samplesPerFrame;
  208045. device->overlapBuffer->dataLength = 0;
  208046. device->overlapBuffer->startFrame = 0;
  208047. device->overlapBuffer->numFrames = 0;
  208048. device->jitter = false;
  208049. firstFrameInBuffer = 0;
  208050. lastIndex = 0;
  208051. CDReadBuffer readBuffer (4 + framesPerIndexRead);
  208052. readBuffer.wantsIndex = true;
  208053. int i;
  208054. for (i = 5; --i >= 0;)
  208055. {
  208056. readBuffer.startFrame = frameNeeded;
  208057. readBuffer.numFrames = framesPerIndexRead;
  208058. if (device->cdH->readAudio (&readBuffer, (false) ? device->overlapBuffer : 0))
  208059. break;
  208060. }
  208061. if (i >= 0)
  208062. return readBuffer.index;
  208063. return -1;
  208064. }
  208065. const Array <int> AudioCDReader::findIndexesInTrack (const int trackNumber)
  208066. {
  208067. using namespace CDReaderHelpers;
  208068. Array <int> indexes;
  208069. const int trackStart = getPositionOfTrackStart (trackNumber);
  208070. const int trackEnd = getPositionOfTrackStart (trackNumber + 1);
  208071. bool needToScan = true;
  208072. if (trackEnd - trackStart > 20 * 44100)
  208073. {
  208074. // check the end of the track for indexes before scanning the whole thing
  208075. needToScan = false;
  208076. int pos = jmax (trackStart, trackEnd - 44100 * 5);
  208077. bool seenAnIndex = false;
  208078. while (pos <= trackEnd - samplesPerFrame)
  208079. {
  208080. const int index = getIndexAt (pos);
  208081. if (index == 0)
  208082. {
  208083. // lead-out, so skip back a bit if we've not found any indexes yet..
  208084. if (seenAnIndex)
  208085. break;
  208086. pos -= 44100 * 5;
  208087. if (pos < trackStart)
  208088. break;
  208089. }
  208090. else
  208091. {
  208092. if (index > 0)
  208093. seenAnIndex = true;
  208094. if (index > 1)
  208095. {
  208096. needToScan = true;
  208097. break;
  208098. }
  208099. pos += samplesPerFrame * framesPerIndexRead;
  208100. }
  208101. }
  208102. }
  208103. if (needToScan)
  208104. {
  208105. CDDeviceWrapper* const device = (CDDeviceWrapper*) handle;
  208106. int pos = trackStart;
  208107. int last = -1;
  208108. while (pos < trackEnd - samplesPerFrame * 10)
  208109. {
  208110. const int frameNeeded = pos / samplesPerFrame;
  208111. device->overlapBuffer->dataLength = 0;
  208112. device->overlapBuffer->startFrame = 0;
  208113. device->overlapBuffer->numFrames = 0;
  208114. device->jitter = false;
  208115. firstFrameInBuffer = 0;
  208116. CDReadBuffer readBuffer (4);
  208117. readBuffer.wantsIndex = true;
  208118. int i;
  208119. for (i = 5; --i >= 0;)
  208120. {
  208121. readBuffer.startFrame = frameNeeded;
  208122. readBuffer.numFrames = framesPerIndexRead;
  208123. if (device->cdH->readAudio (&readBuffer, (false) ? device->overlapBuffer : 0))
  208124. break;
  208125. }
  208126. if (i < 0)
  208127. break;
  208128. if (readBuffer.index > last && readBuffer.index > 1)
  208129. {
  208130. last = readBuffer.index;
  208131. indexes.add (pos);
  208132. }
  208133. pos += samplesPerFrame * framesPerIndexRead;
  208134. }
  208135. indexes.removeValue (trackStart);
  208136. }
  208137. return indexes;
  208138. }
  208139. int AudioCDReader::getCDDBId()
  208140. {
  208141. using namespace CDReaderHelpers;
  208142. refreshTrackLengths();
  208143. if (numTracks > 0)
  208144. {
  208145. TOC toc;
  208146. zerostruct (toc);
  208147. if (((CDDeviceWrapper*) handle)->cdH->readTOC (&toc, true))
  208148. {
  208149. int n = 0;
  208150. for (int i = numTracks; --i >= 0;)
  208151. {
  208152. int j = getMSFAddressOf (&toc.tracks[i]);
  208153. while (j > 0)
  208154. {
  208155. n += (j % 10);
  208156. j /= 10;
  208157. }
  208158. }
  208159. if (n != 0)
  208160. {
  208161. const int t = getMSFAddressOf (&toc.tracks[numTracks])
  208162. - getMSFAddressOf (&toc.tracks[0]);
  208163. return ((n % 0xff) << 24) | (t << 8) | numTracks;
  208164. }
  208165. }
  208166. }
  208167. return 0;
  208168. }
  208169. void AudioCDReader::ejectDisk()
  208170. {
  208171. using namespace CDReaderHelpers;
  208172. ((CDDeviceWrapper*) handle)->cdH->openDrawer (true);
  208173. }
  208174. #endif
  208175. #if JUCE_USE_CDBURNER
  208176. static IDiscRecorder* enumCDBurners (StringArray* list, int indexToOpen, IDiscMaster** master)
  208177. {
  208178. CoInitialize (0);
  208179. IDiscMaster* dm;
  208180. IDiscRecorder* result = 0;
  208181. if (SUCCEEDED (CoCreateInstance (CLSID_MSDiscMasterObj, 0,
  208182. CLSCTX_INPROC_SERVER | CLSCTX_LOCAL_SERVER,
  208183. IID_IDiscMaster,
  208184. (void**) &dm)))
  208185. {
  208186. if (SUCCEEDED (dm->Open()))
  208187. {
  208188. IEnumDiscRecorders* drEnum = 0;
  208189. if (SUCCEEDED (dm->EnumDiscRecorders (&drEnum)))
  208190. {
  208191. IDiscRecorder* dr = 0;
  208192. DWORD dummy;
  208193. int index = 0;
  208194. while (drEnum->Next (1, &dr, &dummy) == S_OK)
  208195. {
  208196. if (indexToOpen == index)
  208197. {
  208198. result = dr;
  208199. break;
  208200. }
  208201. else if (list != 0)
  208202. {
  208203. BSTR path;
  208204. if (SUCCEEDED (dr->GetPath (&path)))
  208205. list->add ((const WCHAR*) path);
  208206. }
  208207. ++index;
  208208. dr->Release();
  208209. }
  208210. drEnum->Release();
  208211. }
  208212. if (master == 0)
  208213. dm->Close();
  208214. }
  208215. if (master != 0)
  208216. *master = dm;
  208217. else
  208218. dm->Release();
  208219. }
  208220. return result;
  208221. }
  208222. class AudioCDBurner::Pimpl : public ComBaseClassHelper <IDiscMasterProgressEvents>,
  208223. public Timer
  208224. {
  208225. public:
  208226. Pimpl (AudioCDBurner& owner_, IDiscMaster* discMaster_, IDiscRecorder* discRecorder_)
  208227. : owner (owner_), discMaster (discMaster_), discRecorder (discRecorder_), redbook (0),
  208228. listener (0), progress (0), shouldCancel (false)
  208229. {
  208230. HRESULT hr = discMaster->SetActiveDiscMasterFormat (IID_IRedbookDiscMaster, (void**) &redbook);
  208231. jassert (SUCCEEDED (hr));
  208232. hr = discMaster->SetActiveDiscRecorder (discRecorder);
  208233. //jassert (SUCCEEDED (hr));
  208234. lastState = getDiskState();
  208235. startTimer (2000);
  208236. }
  208237. ~Pimpl() {}
  208238. void releaseObjects()
  208239. {
  208240. discRecorder->Close();
  208241. if (redbook != 0)
  208242. redbook->Release();
  208243. discRecorder->Release();
  208244. discMaster->Release();
  208245. Release();
  208246. }
  208247. HRESULT __stdcall QueryCancel (boolean* pbCancel)
  208248. {
  208249. if (listener != 0 && ! shouldCancel)
  208250. shouldCancel = listener->audioCDBurnProgress (progress);
  208251. *pbCancel = shouldCancel;
  208252. return S_OK;
  208253. }
  208254. HRESULT __stdcall NotifyBlockProgress (long nCompleted, long nTotal)
  208255. {
  208256. progress = nCompleted / (float) nTotal;
  208257. shouldCancel = listener != 0 && listener->audioCDBurnProgress (progress);
  208258. return E_NOTIMPL;
  208259. }
  208260. HRESULT __stdcall NotifyPnPActivity (void) { return E_NOTIMPL; }
  208261. HRESULT __stdcall NotifyAddProgress (long /*nCompletedSteps*/, long /*nTotalSteps*/) { return E_NOTIMPL; }
  208262. HRESULT __stdcall NotifyTrackProgress (long /*nCurrentTrack*/, long /*nTotalTracks*/) { return E_NOTIMPL; }
  208263. HRESULT __stdcall NotifyPreparingBurn (long /*nEstimatedSeconds*/) { return E_NOTIMPL; }
  208264. HRESULT __stdcall NotifyClosingDisc (long /*nEstimatedSeconds*/) { return E_NOTIMPL; }
  208265. HRESULT __stdcall NotifyBurnComplete (HRESULT /*status*/) { return E_NOTIMPL; }
  208266. HRESULT __stdcall NotifyEraseComplete (HRESULT /*status*/) { return E_NOTIMPL; }
  208267. class ScopedDiscOpener
  208268. {
  208269. public:
  208270. ScopedDiscOpener (Pimpl& p) : pimpl (p) { pimpl.discRecorder->OpenExclusive(); }
  208271. ~ScopedDiscOpener() { pimpl.discRecorder->Close(); }
  208272. private:
  208273. Pimpl& pimpl;
  208274. ScopedDiscOpener (const ScopedDiscOpener&);
  208275. ScopedDiscOpener& operator= (const ScopedDiscOpener&);
  208276. };
  208277. DiskState getDiskState()
  208278. {
  208279. const ScopedDiscOpener opener (*this);
  208280. long type, flags;
  208281. HRESULT hr = discRecorder->QueryMediaType (&type, &flags);
  208282. if (FAILED (hr))
  208283. return unknown;
  208284. if (type != 0 && (flags & MEDIA_WRITABLE) != 0)
  208285. return writableDiskPresent;
  208286. if (type == 0)
  208287. return noDisc;
  208288. else
  208289. return readOnlyDiskPresent;
  208290. }
  208291. int getIntProperty (const LPOLESTR name, const int defaultReturn) const
  208292. {
  208293. ComSmartPtr<IPropertyStorage> prop;
  208294. if (FAILED (discRecorder->GetRecorderProperties (&prop)))
  208295. return defaultReturn;
  208296. PROPSPEC iPropSpec;
  208297. iPropSpec.ulKind = PRSPEC_LPWSTR;
  208298. iPropSpec.lpwstr = name;
  208299. PROPVARIANT iPropVariant;
  208300. return FAILED (prop->ReadMultiple (1, &iPropSpec, &iPropVariant))
  208301. ? defaultReturn : (int) iPropVariant.lVal;
  208302. }
  208303. bool setIntProperty (const LPOLESTR name, const int value) const
  208304. {
  208305. ComSmartPtr<IPropertyStorage> prop;
  208306. if (FAILED (discRecorder->GetRecorderProperties (&prop)))
  208307. return false;
  208308. PROPSPEC iPropSpec;
  208309. iPropSpec.ulKind = PRSPEC_LPWSTR;
  208310. iPropSpec.lpwstr = name;
  208311. PROPVARIANT iPropVariant;
  208312. if (FAILED (prop->ReadMultiple (1, &iPropSpec, &iPropVariant)))
  208313. return false;
  208314. iPropVariant.lVal = (long) value;
  208315. return SUCCEEDED (prop->WriteMultiple (1, &iPropSpec, &iPropVariant, iPropVariant.vt))
  208316. && SUCCEEDED (discRecorder->SetRecorderProperties (prop));
  208317. }
  208318. void timerCallback()
  208319. {
  208320. const DiskState state = getDiskState();
  208321. if (state != lastState)
  208322. {
  208323. lastState = state;
  208324. owner.sendChangeMessage (&owner);
  208325. }
  208326. }
  208327. AudioCDBurner& owner;
  208328. DiskState lastState;
  208329. IDiscMaster* discMaster;
  208330. IDiscRecorder* discRecorder;
  208331. IRedbookDiscMaster* redbook;
  208332. AudioCDBurner::BurnProgressListener* listener;
  208333. float progress;
  208334. bool shouldCancel;
  208335. };
  208336. AudioCDBurner::AudioCDBurner (const int deviceIndex)
  208337. {
  208338. IDiscMaster* discMaster = 0;
  208339. IDiscRecorder* discRecorder = enumCDBurners (0, deviceIndex, &discMaster);
  208340. if (discRecorder != 0)
  208341. pimpl = new Pimpl (*this, discMaster, discRecorder);
  208342. }
  208343. AudioCDBurner::~AudioCDBurner()
  208344. {
  208345. if (pimpl != 0)
  208346. pimpl.release()->releaseObjects();
  208347. }
  208348. const StringArray AudioCDBurner::findAvailableDevices()
  208349. {
  208350. StringArray devs;
  208351. enumCDBurners (&devs, -1, 0);
  208352. return devs;
  208353. }
  208354. AudioCDBurner* AudioCDBurner::openDevice (const int deviceIndex)
  208355. {
  208356. ScopedPointer<AudioCDBurner> b (new AudioCDBurner (deviceIndex));
  208357. if (b->pimpl == 0)
  208358. b = 0;
  208359. return b.release();
  208360. }
  208361. AudioCDBurner::DiskState AudioCDBurner::getDiskState() const
  208362. {
  208363. return pimpl->getDiskState();
  208364. }
  208365. bool AudioCDBurner::isDiskPresent() const
  208366. {
  208367. return getDiskState() == writableDiskPresent;
  208368. }
  208369. bool AudioCDBurner::openTray()
  208370. {
  208371. const Pimpl::ScopedDiscOpener opener (*pimpl);
  208372. return SUCCEEDED (pimpl->discRecorder->Eject());
  208373. }
  208374. AudioCDBurner::DiskState AudioCDBurner::waitUntilStateChange (int timeOutMilliseconds)
  208375. {
  208376. const int64 timeout = Time::currentTimeMillis() + timeOutMilliseconds;
  208377. DiskState oldState = getDiskState();
  208378. DiskState newState = oldState;
  208379. while (newState == oldState && Time::currentTimeMillis() < timeout)
  208380. {
  208381. newState = getDiskState();
  208382. Thread::sleep (jmin (250, (int) (timeout - Time::currentTimeMillis())));
  208383. }
  208384. return newState;
  208385. }
  208386. const Array<int> AudioCDBurner::getAvailableWriteSpeeds() const
  208387. {
  208388. Array<int> results;
  208389. const int maxSpeed = pimpl->getIntProperty (L"MaxWriteSpeed", 1);
  208390. const int speeds[] = { 1, 2, 4, 8, 12, 16, 20, 24, 32, 40, 64, 80 };
  208391. for (int i = 0; i < numElementsInArray (speeds); ++i)
  208392. if (speeds[i] <= maxSpeed)
  208393. results.add (speeds[i]);
  208394. results.addIfNotAlreadyThere (maxSpeed);
  208395. return results;
  208396. }
  208397. bool AudioCDBurner::setBufferUnderrunProtection (const bool shouldBeEnabled)
  208398. {
  208399. if (pimpl->getIntProperty (L"BufferUnderrunFreeCapable", 0) == 0)
  208400. return false;
  208401. pimpl->setIntProperty (L"EnableBufferUnderrunFree", shouldBeEnabled ? -1 : 0);
  208402. return pimpl->getIntProperty (L"EnableBufferUnderrunFree", 0) != 0;
  208403. }
  208404. int AudioCDBurner::getNumAvailableAudioBlocks() const
  208405. {
  208406. long blocksFree = 0;
  208407. pimpl->redbook->GetAvailableAudioTrackBlocks (&blocksFree);
  208408. return blocksFree;
  208409. }
  208410. const String AudioCDBurner::burn (AudioCDBurner::BurnProgressListener* listener, bool ejectDiscAfterwards,
  208411. bool performFakeBurnForTesting, int writeSpeed)
  208412. {
  208413. pimpl->setIntProperty (L"WriteSpeed", writeSpeed > 0 ? writeSpeed : -1);
  208414. pimpl->listener = listener;
  208415. pimpl->progress = 0;
  208416. pimpl->shouldCancel = false;
  208417. UINT_PTR cookie;
  208418. HRESULT hr = pimpl->discMaster->ProgressAdvise ((AudioCDBurner::Pimpl*) pimpl, &cookie);
  208419. hr = pimpl->discMaster->RecordDisc (performFakeBurnForTesting,
  208420. ejectDiscAfterwards);
  208421. String error;
  208422. if (hr != S_OK)
  208423. {
  208424. const char* e = "Couldn't open or write to the CD device";
  208425. if (hr == IMAPI_E_USERABORT)
  208426. e = "User cancelled the write operation";
  208427. else if (hr == IMAPI_E_MEDIUM_NOTPRESENT || hr == IMAPI_E_TRACKOPEN)
  208428. e = "No Disk present";
  208429. error = e;
  208430. }
  208431. pimpl->discMaster->ProgressUnadvise (cookie);
  208432. pimpl->listener = 0;
  208433. return error;
  208434. }
  208435. bool AudioCDBurner::addAudioTrack (AudioSource* audioSource, int numSamples)
  208436. {
  208437. if (audioSource == 0)
  208438. return false;
  208439. ScopedPointer<AudioSource> source (audioSource);
  208440. long bytesPerBlock;
  208441. HRESULT hr = pimpl->redbook->GetAudioBlockSize (&bytesPerBlock);
  208442. const int samplesPerBlock = bytesPerBlock / 4;
  208443. bool ok = true;
  208444. hr = pimpl->redbook->CreateAudioTrack ((long) numSamples / (bytesPerBlock * 4));
  208445. HeapBlock <byte> buffer (bytesPerBlock);
  208446. AudioSampleBuffer sourceBuffer (2, samplesPerBlock);
  208447. int samplesDone = 0;
  208448. source->prepareToPlay (samplesPerBlock, 44100.0);
  208449. while (ok)
  208450. {
  208451. {
  208452. AudioSourceChannelInfo info;
  208453. info.buffer = &sourceBuffer;
  208454. info.numSamples = samplesPerBlock;
  208455. info.startSample = 0;
  208456. sourceBuffer.clear();
  208457. source->getNextAudioBlock (info);
  208458. }
  208459. zeromem (buffer, bytesPerBlock);
  208460. AudioDataConverters::convertFloatToInt16LE (sourceBuffer.getSampleData (0, 0),
  208461. buffer, samplesPerBlock, 4);
  208462. AudioDataConverters::convertFloatToInt16LE (sourceBuffer.getSampleData (1, 0),
  208463. buffer + 2, samplesPerBlock, 4);
  208464. hr = pimpl->redbook->AddAudioTrackBlocks (buffer, bytesPerBlock);
  208465. if (FAILED (hr))
  208466. ok = false;
  208467. samplesDone += samplesPerBlock;
  208468. if (samplesDone >= numSamples)
  208469. break;
  208470. }
  208471. hr = pimpl->redbook->CloseAudioTrack();
  208472. return ok && hr == S_OK;
  208473. }
  208474. #endif
  208475. #endif
  208476. /*** End of inlined file: juce_win32_AudioCDReader.cpp ***/
  208477. /*** Start of inlined file: juce_win32_Midi.cpp ***/
  208478. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  208479. // compiled on its own).
  208480. #if JUCE_INCLUDED_FILE
  208481. using ::free;
  208482. namespace MidiConstants
  208483. {
  208484. static const int midiBufferSize = 1024 * 10;
  208485. static const int numInHeaders = 32;
  208486. static const int inBufferSize = 256;
  208487. }
  208488. class MidiInThread : public Thread
  208489. {
  208490. public:
  208491. MidiInThread (MidiInput* const input_,
  208492. MidiInputCallback* const callback_)
  208493. : Thread ("Juce Midi"),
  208494. hIn (0),
  208495. input (input_),
  208496. callback (callback_),
  208497. isStarted (false),
  208498. startTime (0),
  208499. pendingLength(0)
  208500. {
  208501. for (int i = MidiConstants::numInHeaders; --i >= 0;)
  208502. {
  208503. zeromem (&hdr[i], sizeof (MIDIHDR));
  208504. hdr[i].lpData = inData[i];
  208505. hdr[i].dwBufferLength = MidiConstants::inBufferSize;
  208506. }
  208507. };
  208508. ~MidiInThread()
  208509. {
  208510. stop();
  208511. if (hIn != 0)
  208512. {
  208513. int count = 5;
  208514. while (--count >= 0)
  208515. {
  208516. if (midiInClose (hIn) == MMSYSERR_NOERROR)
  208517. break;
  208518. Sleep (20);
  208519. }
  208520. }
  208521. }
  208522. void handle (const uint32 message, const uint32 timeStamp)
  208523. {
  208524. const int byte = message & 0xff;
  208525. if (byte < 0x80)
  208526. return;
  208527. const int numBytes = MidiMessage::getMessageLengthFromFirstByte ((uint8) byte);
  208528. const double time = timeStampToTime (timeStamp);
  208529. {
  208530. const ScopedLock sl (lock);
  208531. if (pendingLength < MidiConstants::midiBufferSize - 12)
  208532. {
  208533. char* const p = pending + pendingLength;
  208534. *(double*) p = time;
  208535. *(uint32*) (p + 8) = numBytes;
  208536. *(uint32*) (p + 12) = message;
  208537. pendingLength += 12 + numBytes;
  208538. }
  208539. else
  208540. {
  208541. jassertfalse // midi buffer overflow! You might need to increase the size..
  208542. }
  208543. }
  208544. notify();
  208545. }
  208546. void handleSysEx (MIDIHDR* const hdr, const uint32 timeStamp)
  208547. {
  208548. const int num = hdr->dwBytesRecorded;
  208549. if (num > 0)
  208550. {
  208551. const double time = timeStampToTime (timeStamp);
  208552. {
  208553. const ScopedLock sl (lock);
  208554. if (pendingLength < MidiConstants::midiBufferSize - (8 + num))
  208555. {
  208556. char* const p = pending + pendingLength;
  208557. *(double*) p = time;
  208558. *(uint32*) (p + 8) = num;
  208559. memcpy (p + 12, hdr->lpData, num);
  208560. pendingLength += 12 + num;
  208561. }
  208562. else
  208563. {
  208564. jassertfalse // midi buffer overflow! You might need to increase the size..
  208565. }
  208566. }
  208567. notify();
  208568. }
  208569. }
  208570. void writeBlock (const int i)
  208571. {
  208572. hdr[i].dwBytesRecorded = 0;
  208573. MMRESULT res = midiInPrepareHeader (hIn, &hdr[i], sizeof (MIDIHDR));
  208574. jassert (res == MMSYSERR_NOERROR);
  208575. res = midiInAddBuffer (hIn, &hdr[i], sizeof (MIDIHDR));
  208576. jassert (res == MMSYSERR_NOERROR);
  208577. }
  208578. void run()
  208579. {
  208580. MemoryBlock pendingCopy (64);
  208581. while (! threadShouldExit())
  208582. {
  208583. for (int i = 0; i < MidiConstants::numInHeaders; ++i)
  208584. {
  208585. if ((hdr[i].dwFlags & WHDR_DONE) != 0)
  208586. {
  208587. MMRESULT res = midiInUnprepareHeader (hIn, &hdr[i], sizeof (MIDIHDR));
  208588. (void) res;
  208589. jassert (res == MMSYSERR_NOERROR);
  208590. writeBlock (i);
  208591. }
  208592. }
  208593. int len;
  208594. {
  208595. const ScopedLock sl (lock);
  208596. len = pendingLength;
  208597. if (len > 0)
  208598. {
  208599. pendingCopy.ensureSize (len);
  208600. pendingCopy.copyFrom (pending, 0, len);
  208601. pendingLength = 0;
  208602. }
  208603. }
  208604. //xxx needs to figure out if blocks are broken up or not
  208605. if (len == 0)
  208606. {
  208607. wait (500);
  208608. }
  208609. else
  208610. {
  208611. const char* p = (const char*) pendingCopy.getData();
  208612. while (len > 0)
  208613. {
  208614. const double time = *(const double*) p;
  208615. const int messageLen = *(const int*) (p + 8);
  208616. const MidiMessage message ((const uint8*) (p + 12), messageLen, time);
  208617. callback->handleIncomingMidiMessage (input, message);
  208618. p += 12 + messageLen;
  208619. len -= 12 + messageLen;
  208620. }
  208621. }
  208622. }
  208623. }
  208624. void start()
  208625. {
  208626. jassert (hIn != 0);
  208627. if (hIn != 0 && ! isStarted)
  208628. {
  208629. stop();
  208630. activeMidiThreads.addIfNotAlreadyThere (this);
  208631. int i;
  208632. for (i = 0; i < MidiConstants::numInHeaders; ++i)
  208633. writeBlock (i);
  208634. startTime = Time::getMillisecondCounter();
  208635. MMRESULT res = midiInStart (hIn);
  208636. jassert (res == MMSYSERR_NOERROR);
  208637. if (res == MMSYSERR_NOERROR)
  208638. {
  208639. isStarted = true;
  208640. pendingLength = 0;
  208641. startThread (6);
  208642. }
  208643. }
  208644. }
  208645. void stop()
  208646. {
  208647. if (isStarted)
  208648. {
  208649. stopThread (5000);
  208650. midiInReset (hIn);
  208651. midiInStop (hIn);
  208652. activeMidiThreads.removeValue (this);
  208653. { const ScopedLock sl (lock); }
  208654. for (int i = MidiConstants::numInHeaders; --i >= 0;)
  208655. {
  208656. if ((hdr[i].dwFlags & WHDR_DONE) != 0)
  208657. {
  208658. int c = 10;
  208659. while (--c >= 0 && midiInUnprepareHeader (hIn, &hdr[i], sizeof (MIDIHDR)) == MIDIERR_STILLPLAYING)
  208660. Sleep (20);
  208661. jassert (c >= 0);
  208662. }
  208663. }
  208664. isStarted = false;
  208665. pendingLength = 0;
  208666. }
  208667. }
  208668. static void CALLBACK midiInCallback (HMIDIIN, UINT uMsg, DWORD_PTR dwInstance, DWORD_PTR midiMessage, DWORD_PTR timeStamp)
  208669. {
  208670. MidiInThread* const thread = reinterpret_cast <MidiInThread*> (dwInstance);
  208671. if (thread != 0 && activeMidiThreads.contains (thread))
  208672. {
  208673. if (uMsg == MIM_DATA)
  208674. thread->handle ((uint32) midiMessage, (uint32) timeStamp);
  208675. else if (uMsg == MIM_LONGDATA)
  208676. thread->handleSysEx ((MIDIHDR*) midiMessage, (uint32) timeStamp);
  208677. }
  208678. }
  208679. juce_UseDebuggingNewOperator
  208680. HMIDIIN hIn;
  208681. private:
  208682. static Array <void*, CriticalSection> activeMidiThreads;
  208683. MidiInput* input;
  208684. MidiInputCallback* callback;
  208685. bool isStarted;
  208686. uint32 startTime;
  208687. CriticalSection lock;
  208688. MIDIHDR hdr [MidiConstants::numInHeaders];
  208689. char inData [MidiConstants::numInHeaders] [MidiConstants::inBufferSize];
  208690. int pendingLength;
  208691. char pending [MidiConstants::midiBufferSize];
  208692. double timeStampToTime (uint32 timeStamp)
  208693. {
  208694. timeStamp += startTime;
  208695. const uint32 now = Time::getMillisecondCounter();
  208696. if (timeStamp > now)
  208697. {
  208698. if (timeStamp > now + 2)
  208699. --startTime;
  208700. timeStamp = now;
  208701. }
  208702. return 0.001 * timeStamp;
  208703. }
  208704. MidiInThread (const MidiInThread&);
  208705. MidiInThread& operator= (const MidiInThread&);
  208706. };
  208707. Array <void*, CriticalSection> MidiInThread::activeMidiThreads;
  208708. const StringArray MidiInput::getDevices()
  208709. {
  208710. StringArray s;
  208711. const int num = midiInGetNumDevs();
  208712. for (int i = 0; i < num; ++i)
  208713. {
  208714. MIDIINCAPS mc;
  208715. zerostruct (mc);
  208716. if (midiInGetDevCaps (i, &mc, sizeof (mc)) == MMSYSERR_NOERROR)
  208717. s.add (String (mc.szPname, sizeof (mc.szPname)));
  208718. }
  208719. return s;
  208720. }
  208721. int MidiInput::getDefaultDeviceIndex()
  208722. {
  208723. return 0;
  208724. }
  208725. MidiInput* MidiInput::openDevice (const int index, MidiInputCallback* const callback)
  208726. {
  208727. if (callback == 0)
  208728. return 0;
  208729. UINT deviceId = MIDI_MAPPER;
  208730. int n = 0;
  208731. String name;
  208732. const int num = midiInGetNumDevs();
  208733. for (int i = 0; i < num; ++i)
  208734. {
  208735. MIDIINCAPS mc;
  208736. zerostruct (mc);
  208737. if (midiInGetDevCaps (i, &mc, sizeof (mc)) == MMSYSERR_NOERROR)
  208738. {
  208739. if (index == n)
  208740. {
  208741. deviceId = i;
  208742. name = String (mc.szPname, sizeof (mc.szPname));
  208743. break;
  208744. }
  208745. ++n;
  208746. }
  208747. }
  208748. ScopedPointer <MidiInput> in (new MidiInput (name));
  208749. ScopedPointer <MidiInThread> thread (new MidiInThread (in, callback));
  208750. HMIDIIN h;
  208751. HRESULT err = midiInOpen (&h, deviceId,
  208752. (DWORD_PTR) &MidiInThread::midiInCallback,
  208753. (DWORD_PTR) (MidiInThread*) thread,
  208754. CALLBACK_FUNCTION);
  208755. if (err == MMSYSERR_NOERROR)
  208756. {
  208757. thread->hIn = h;
  208758. in->internal = thread.release();
  208759. return in.release();
  208760. }
  208761. return 0;
  208762. }
  208763. MidiInput::MidiInput (const String& name_)
  208764. : name (name_),
  208765. internal (0)
  208766. {
  208767. }
  208768. MidiInput::~MidiInput()
  208769. {
  208770. delete static_cast <MidiInThread*> (internal);
  208771. }
  208772. void MidiInput::start()
  208773. {
  208774. static_cast <MidiInThread*> (internal)->start();
  208775. }
  208776. void MidiInput::stop()
  208777. {
  208778. static_cast <MidiInThread*> (internal)->stop();
  208779. }
  208780. struct MidiOutHandle
  208781. {
  208782. int refCount;
  208783. UINT deviceId;
  208784. HMIDIOUT handle;
  208785. static Array<MidiOutHandle*> activeHandles;
  208786. juce_UseDebuggingNewOperator
  208787. };
  208788. Array<MidiOutHandle*> MidiOutHandle::activeHandles;
  208789. const StringArray MidiOutput::getDevices()
  208790. {
  208791. StringArray s;
  208792. const int num = midiOutGetNumDevs();
  208793. for (int i = 0; i < num; ++i)
  208794. {
  208795. MIDIOUTCAPS mc;
  208796. zerostruct (mc);
  208797. if (midiOutGetDevCaps (i, &mc, sizeof (mc)) == MMSYSERR_NOERROR)
  208798. s.add (String (mc.szPname, sizeof (mc.szPname)));
  208799. }
  208800. return s;
  208801. }
  208802. int MidiOutput::getDefaultDeviceIndex()
  208803. {
  208804. const int num = midiOutGetNumDevs();
  208805. int n = 0;
  208806. for (int i = 0; i < num; ++i)
  208807. {
  208808. MIDIOUTCAPS mc;
  208809. zerostruct (mc);
  208810. if (midiOutGetDevCaps (i, &mc, sizeof (mc)) == MMSYSERR_NOERROR)
  208811. {
  208812. if ((mc.wTechnology & MOD_MAPPER) != 0)
  208813. return n;
  208814. ++n;
  208815. }
  208816. }
  208817. return 0;
  208818. }
  208819. MidiOutput* MidiOutput::openDevice (int index)
  208820. {
  208821. UINT deviceId = MIDI_MAPPER;
  208822. const int num = midiOutGetNumDevs();
  208823. int i, n = 0;
  208824. for (i = 0; i < num; ++i)
  208825. {
  208826. MIDIOUTCAPS mc;
  208827. zerostruct (mc);
  208828. if (midiOutGetDevCaps (i, &mc, sizeof (mc)) == MMSYSERR_NOERROR)
  208829. {
  208830. // use the microsoft sw synth as a default - best not to allow deviceId
  208831. // to be MIDI_MAPPER, or else device sharing breaks
  208832. if (String (mc.szPname, sizeof (mc.szPname)).containsIgnoreCase ("microsoft"))
  208833. deviceId = i;
  208834. if (index == n)
  208835. {
  208836. deviceId = i;
  208837. break;
  208838. }
  208839. ++n;
  208840. }
  208841. }
  208842. for (i = MidiOutHandle::activeHandles.size(); --i >= 0;)
  208843. {
  208844. MidiOutHandle* const han = MidiOutHandle::activeHandles.getUnchecked(i);
  208845. if (han != 0 && han->deviceId == deviceId)
  208846. {
  208847. han->refCount++;
  208848. MidiOutput* const out = new MidiOutput();
  208849. out->internal = han;
  208850. return out;
  208851. }
  208852. }
  208853. for (i = 4; --i >= 0;)
  208854. {
  208855. HMIDIOUT h = 0;
  208856. MMRESULT res = midiOutOpen (&h, deviceId, 0, 0, CALLBACK_NULL);
  208857. if (res == MMSYSERR_NOERROR)
  208858. {
  208859. MidiOutHandle* const han = new MidiOutHandle();
  208860. han->deviceId = deviceId;
  208861. han->refCount = 1;
  208862. han->handle = h;
  208863. MidiOutHandle::activeHandles.add (han);
  208864. MidiOutput* const out = new MidiOutput();
  208865. out->internal = han;
  208866. return out;
  208867. }
  208868. else if (res == MMSYSERR_ALLOCATED)
  208869. {
  208870. Sleep (100);
  208871. }
  208872. else
  208873. {
  208874. break;
  208875. }
  208876. }
  208877. return 0;
  208878. }
  208879. MidiOutput::~MidiOutput()
  208880. {
  208881. MidiOutHandle* const h = static_cast <MidiOutHandle*> (internal);
  208882. if (MidiOutHandle::activeHandles.contains (h) && --(h->refCount) == 0)
  208883. {
  208884. midiOutClose (h->handle);
  208885. MidiOutHandle::activeHandles.removeValue (h);
  208886. delete h;
  208887. }
  208888. }
  208889. void MidiOutput::reset()
  208890. {
  208891. const MidiOutHandle* const h = static_cast <const MidiOutHandle*> (internal);
  208892. midiOutReset (h->handle);
  208893. }
  208894. bool MidiOutput::getVolume (float& leftVol,
  208895. float& rightVol)
  208896. {
  208897. const MidiOutHandle* const handle = static_cast <const MidiOutHandle*> (internal);
  208898. DWORD n;
  208899. if (midiOutGetVolume (handle->handle, &n) == MMSYSERR_NOERROR)
  208900. {
  208901. const unsigned short* const nn = (const unsigned short*) &n;
  208902. rightVol = nn[0] / (float) 0xffff;
  208903. leftVol = nn[1] / (float) 0xffff;
  208904. return true;
  208905. }
  208906. else
  208907. {
  208908. rightVol = leftVol = 1.0f;
  208909. return false;
  208910. }
  208911. }
  208912. void MidiOutput::setVolume (float leftVol,
  208913. float rightVol)
  208914. {
  208915. const MidiOutHandle* const handle = static_cast <MidiOutHandle*> (internal);
  208916. DWORD n;
  208917. unsigned short* const nn = (unsigned short*) &n;
  208918. nn[0] = (unsigned short) jlimit (0, 0xffff, (int) (rightVol * 0xffff));
  208919. nn[1] = (unsigned short) jlimit (0, 0xffff, (int) (leftVol * 0xffff));
  208920. midiOutSetVolume (handle->handle, n);
  208921. }
  208922. void MidiOutput::sendMessageNow (const MidiMessage& message)
  208923. {
  208924. const MidiOutHandle* const handle = static_cast <const MidiOutHandle*> (internal);
  208925. if (message.getRawDataSize() > 3
  208926. || message.isSysEx())
  208927. {
  208928. MIDIHDR h;
  208929. zerostruct (h);
  208930. h.lpData = (char*) message.getRawData();
  208931. h.dwBufferLength = message.getRawDataSize();
  208932. h.dwBytesRecorded = message.getRawDataSize();
  208933. if (midiOutPrepareHeader (handle->handle, &h, sizeof (MIDIHDR)) == MMSYSERR_NOERROR)
  208934. {
  208935. MMRESULT res = midiOutLongMsg (handle->handle, &h, sizeof (MIDIHDR));
  208936. if (res == MMSYSERR_NOERROR)
  208937. {
  208938. while ((h.dwFlags & MHDR_DONE) == 0)
  208939. Sleep (1);
  208940. int count = 500; // 1 sec timeout
  208941. while (--count >= 0)
  208942. {
  208943. res = midiOutUnprepareHeader (handle->handle, &h, sizeof (MIDIHDR));
  208944. if (res == MIDIERR_STILLPLAYING)
  208945. Sleep (2);
  208946. else
  208947. break;
  208948. }
  208949. }
  208950. }
  208951. }
  208952. else
  208953. {
  208954. midiOutShortMsg (handle->handle,
  208955. *(unsigned int*) message.getRawData());
  208956. }
  208957. }
  208958. #endif
  208959. /*** End of inlined file: juce_win32_Midi.cpp ***/
  208960. /*** Start of inlined file: juce_win32_ASIO.cpp ***/
  208961. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  208962. // compiled on its own).
  208963. #if JUCE_INCLUDED_FILE && JUCE_ASIO
  208964. #undef WINDOWS
  208965. // #define ASIO_DEBUGGING
  208966. #ifdef ASIO_DEBUGGING
  208967. #define log(a) { Logger::writeToLog (a); DBG (a) }
  208968. #else
  208969. #define log(a) {}
  208970. #endif
  208971. #ifdef ASIO_DEBUGGING
  208972. static void logError (const String& context, long error)
  208973. {
  208974. String err ("unknown error");
  208975. if (error == ASE_NotPresent)
  208976. err = "Not Present";
  208977. else if (error == ASE_HWMalfunction)
  208978. err = "Hardware Malfunction";
  208979. else if (error == ASE_InvalidParameter)
  208980. err = "Invalid Parameter";
  208981. else if (error == ASE_InvalidMode)
  208982. err = "Invalid Mode";
  208983. else if (error == ASE_SPNotAdvancing)
  208984. err = "Sample position not advancing";
  208985. else if (error == ASE_NoClock)
  208986. err = "No Clock";
  208987. else if (error == ASE_NoMemory)
  208988. err = "Out of memory";
  208989. log ("!!error: " + context + " - " + err);
  208990. }
  208991. #else
  208992. #define logError(a, b) {}
  208993. #endif
  208994. class ASIOAudioIODevice;
  208995. static ASIOAudioIODevice* volatile currentASIODev[3] = { 0, 0, 0 };
  208996. static const int maxASIOChannels = 160;
  208997. class JUCE_API ASIOAudioIODevice : public AudioIODevice,
  208998. private Timer
  208999. {
  209000. public:
  209001. Component ourWindow;
  209002. ASIOAudioIODevice (const String& name_, const CLSID classId_, const int slotNumber,
  209003. const String& optionalDllForDirectLoading_)
  209004. : AudioIODevice (name_, "ASIO"),
  209005. asioObject (0),
  209006. classId (classId_),
  209007. optionalDllForDirectLoading (optionalDllForDirectLoading_),
  209008. currentBitDepth (16),
  209009. currentSampleRate (0),
  209010. isOpen_ (false),
  209011. isStarted (false),
  209012. postOutput (true),
  209013. insideControlPanelModalLoop (false),
  209014. shouldUsePreferredSize (false)
  209015. {
  209016. name = name_;
  209017. ourWindow.addToDesktop (0);
  209018. windowHandle = ourWindow.getWindowHandle();
  209019. jassert (currentASIODev [slotNumber] == 0);
  209020. currentASIODev [slotNumber] = this;
  209021. openDevice();
  209022. }
  209023. ~ASIOAudioIODevice()
  209024. {
  209025. for (int i = 0; i < numElementsInArray (currentASIODev); ++i)
  209026. if (currentASIODev[i] == this)
  209027. currentASIODev[i] = 0;
  209028. close();
  209029. log ("ASIO - exiting");
  209030. removeCurrentDriver();
  209031. }
  209032. void updateSampleRates()
  209033. {
  209034. // find a list of sample rates..
  209035. const double possibleSampleRates[] = { 44100.0, 48000.0, 88200.0, 96000.0, 176400.0, 192000.0 };
  209036. sampleRates.clear();
  209037. if (asioObject != 0)
  209038. {
  209039. for (int index = 0; index < numElementsInArray (possibleSampleRates); ++index)
  209040. {
  209041. const long err = asioObject->canSampleRate (possibleSampleRates[index]);
  209042. if (err == 0)
  209043. {
  209044. sampleRates.add ((int) possibleSampleRates[index]);
  209045. log ("rate: " + String ((int) possibleSampleRates[index]));
  209046. }
  209047. else if (err != ASE_NoClock)
  209048. {
  209049. logError ("CanSampleRate", err);
  209050. }
  209051. }
  209052. if (sampleRates.size() == 0)
  209053. {
  209054. double cr = 0;
  209055. const long err = asioObject->getSampleRate (&cr);
  209056. log ("No sample rates supported - current rate: " + String ((int) cr));
  209057. if (err == 0)
  209058. sampleRates.add ((int) cr);
  209059. }
  209060. }
  209061. }
  209062. const StringArray getOutputChannelNames()
  209063. {
  209064. return outputChannelNames;
  209065. }
  209066. const StringArray getInputChannelNames()
  209067. {
  209068. return inputChannelNames;
  209069. }
  209070. int getNumSampleRates()
  209071. {
  209072. return sampleRates.size();
  209073. }
  209074. double getSampleRate (int index)
  209075. {
  209076. return sampleRates [index];
  209077. }
  209078. int getNumBufferSizesAvailable()
  209079. {
  209080. return bufferSizes.size();
  209081. }
  209082. int getBufferSizeSamples (int index)
  209083. {
  209084. return bufferSizes [index];
  209085. }
  209086. int getDefaultBufferSize()
  209087. {
  209088. return preferredSize;
  209089. }
  209090. const String open (const BigInteger& inputChannels,
  209091. const BigInteger& outputChannels,
  209092. double sr,
  209093. int bufferSizeSamples)
  209094. {
  209095. close();
  209096. currentCallback = 0;
  209097. if (bufferSizeSamples <= 0)
  209098. shouldUsePreferredSize = true;
  209099. if (asioObject == 0 || ! isASIOOpen)
  209100. {
  209101. log ("Warning: device not open");
  209102. const String err (openDevice());
  209103. if (asioObject == 0 || ! isASIOOpen)
  209104. return err;
  209105. }
  209106. isStarted = false;
  209107. bufferIndex = -1;
  209108. long err = 0;
  209109. long newPreferredSize = 0;
  209110. // if the preferred size has just changed, assume it's a control panel thing and use it as the new value.
  209111. minSize = 0;
  209112. maxSize = 0;
  209113. newPreferredSize = 0;
  209114. granularity = 0;
  209115. if (asioObject->getBufferSize (&minSize, &maxSize, &newPreferredSize, &granularity) == 0)
  209116. {
  209117. if (preferredSize != 0 && newPreferredSize != 0 && newPreferredSize != preferredSize)
  209118. shouldUsePreferredSize = true;
  209119. preferredSize = newPreferredSize;
  209120. }
  209121. // unfortunate workaround for certain manufacturers whose drivers crash horribly if you make
  209122. // dynamic changes to the buffer size...
  209123. shouldUsePreferredSize = shouldUsePreferredSize
  209124. || getName().containsIgnoreCase ("Digidesign");
  209125. if (shouldUsePreferredSize)
  209126. {
  209127. log ("Using preferred size for buffer..");
  209128. if ((err = asioObject->getBufferSize (&minSize, &maxSize, &preferredSize, &granularity)) == 0)
  209129. {
  209130. bufferSizeSamples = preferredSize;
  209131. }
  209132. else
  209133. {
  209134. bufferSizeSamples = 1024;
  209135. logError ("GetBufferSize1", err);
  209136. }
  209137. shouldUsePreferredSize = false;
  209138. }
  209139. int sampleRate = roundDoubleToInt (sr);
  209140. currentSampleRate = sampleRate;
  209141. currentBlockSizeSamples = bufferSizeSamples;
  209142. currentChansOut.clear();
  209143. currentChansIn.clear();
  209144. zeromem (inBuffers, sizeof (inBuffers));
  209145. zeromem (outBuffers, sizeof (outBuffers));
  209146. updateSampleRates();
  209147. if (sampleRate == 0 || (sampleRates.size() > 0 && ! sampleRates.contains (sampleRate)))
  209148. sampleRate = sampleRates[0];
  209149. jassert (sampleRate != 0);
  209150. if (sampleRate == 0)
  209151. sampleRate = 44100;
  209152. long numSources = 32;
  209153. ASIOClockSource clocks[32];
  209154. zeromem (clocks, sizeof (clocks));
  209155. asioObject->getClockSources (clocks, &numSources);
  209156. bool isSourceSet = false;
  209157. // careful not to remove this loop because it does more than just logging!
  209158. int i;
  209159. for (i = 0; i < numSources; ++i)
  209160. {
  209161. String s ("clock: ");
  209162. s += clocks[i].name;
  209163. if (clocks[i].isCurrentSource)
  209164. {
  209165. isSourceSet = true;
  209166. s << " (cur)";
  209167. }
  209168. log (s);
  209169. }
  209170. if (numSources > 1 && ! isSourceSet)
  209171. {
  209172. log ("setting clock source");
  209173. asioObject->setClockSource (clocks[0].index);
  209174. Thread::sleep (20);
  209175. }
  209176. else
  209177. {
  209178. if (numSources == 0)
  209179. {
  209180. log ("ASIO - no clock sources!");
  209181. }
  209182. }
  209183. double cr = 0;
  209184. err = asioObject->getSampleRate (&cr);
  209185. if (err == 0)
  209186. {
  209187. currentSampleRate = cr;
  209188. }
  209189. else
  209190. {
  209191. logError ("GetSampleRate", err);
  209192. currentSampleRate = 0;
  209193. }
  209194. error = String::empty;
  209195. needToReset = false;
  209196. isReSync = false;
  209197. err = 0;
  209198. bool buffersCreated = false;
  209199. if (currentSampleRate != sampleRate)
  209200. {
  209201. log ("ASIO samplerate: " + String (currentSampleRate) + " to " + String (sampleRate));
  209202. err = asioObject->setSampleRate (sampleRate);
  209203. if (err == ASE_NoClock && numSources > 0)
  209204. {
  209205. log ("trying to set a clock source..");
  209206. Thread::sleep (10);
  209207. err = asioObject->setClockSource (clocks[0].index);
  209208. if (err != 0)
  209209. {
  209210. logError ("SetClock", err);
  209211. }
  209212. Thread::sleep (10);
  209213. err = asioObject->setSampleRate (sampleRate);
  209214. }
  209215. }
  209216. if (err == 0)
  209217. {
  209218. currentSampleRate = sampleRate;
  209219. if (needToReset)
  209220. {
  209221. if (isReSync)
  209222. {
  209223. log ("Resync request");
  209224. }
  209225. log ("! Resetting ASIO after sample rate change");
  209226. removeCurrentDriver();
  209227. loadDriver();
  209228. const String error (initDriver());
  209229. if (error.isNotEmpty())
  209230. {
  209231. log ("ASIOInit: " + error);
  209232. }
  209233. needToReset = false;
  209234. isReSync = false;
  209235. }
  209236. numActiveInputChans = 0;
  209237. numActiveOutputChans = 0;
  209238. ASIOBufferInfo* info = bufferInfos;
  209239. int i;
  209240. for (i = 0; i < totalNumInputChans; ++i)
  209241. {
  209242. if (inputChannels[i])
  209243. {
  209244. currentChansIn.setBit (i);
  209245. info->isInput = 1;
  209246. info->channelNum = i;
  209247. info->buffers[0] = info->buffers[1] = 0;
  209248. ++info;
  209249. ++numActiveInputChans;
  209250. }
  209251. }
  209252. for (i = 0; i < totalNumOutputChans; ++i)
  209253. {
  209254. if (outputChannels[i])
  209255. {
  209256. currentChansOut.setBit (i);
  209257. info->isInput = 0;
  209258. info->channelNum = i;
  209259. info->buffers[0] = info->buffers[1] = 0;
  209260. ++info;
  209261. ++numActiveOutputChans;
  209262. }
  209263. }
  209264. const int totalBuffers = numActiveInputChans + numActiveOutputChans;
  209265. callbacks.sampleRateDidChange = &sampleRateChangedCallback;
  209266. if (currentASIODev[0] == this)
  209267. {
  209268. callbacks.bufferSwitch = &bufferSwitchCallback0;
  209269. callbacks.asioMessage = &asioMessagesCallback0;
  209270. callbacks.bufferSwitchTimeInfo = &bufferSwitchTimeInfoCallback0;
  209271. }
  209272. else if (currentASIODev[1] == this)
  209273. {
  209274. callbacks.bufferSwitch = &bufferSwitchCallback1;
  209275. callbacks.asioMessage = &asioMessagesCallback1;
  209276. callbacks.bufferSwitchTimeInfo = &bufferSwitchTimeInfoCallback1;
  209277. }
  209278. else if (currentASIODev[2] == this)
  209279. {
  209280. callbacks.bufferSwitch = &bufferSwitchCallback2;
  209281. callbacks.asioMessage = &asioMessagesCallback2;
  209282. callbacks.bufferSwitchTimeInfo = &bufferSwitchTimeInfoCallback2;
  209283. }
  209284. else
  209285. {
  209286. jassertfalse
  209287. }
  209288. log ("disposing buffers");
  209289. err = asioObject->disposeBuffers();
  209290. log ("creating buffers: " + String (totalBuffers) + ", " + String (currentBlockSizeSamples));
  209291. err = asioObject->createBuffers (bufferInfos,
  209292. totalBuffers,
  209293. currentBlockSizeSamples,
  209294. &callbacks);
  209295. if (err != 0)
  209296. {
  209297. currentBlockSizeSamples = preferredSize;
  209298. logError ("create buffers 2", err);
  209299. asioObject->disposeBuffers();
  209300. err = asioObject->createBuffers (bufferInfos,
  209301. totalBuffers,
  209302. currentBlockSizeSamples,
  209303. &callbacks);
  209304. }
  209305. if (err == 0)
  209306. {
  209307. buffersCreated = true;
  209308. tempBuffer.calloc (totalBuffers * currentBlockSizeSamples + 32);
  209309. int n = 0;
  209310. Array <int> types;
  209311. currentBitDepth = 16;
  209312. for (i = 0; i < jmin ((int) totalNumInputChans, maxASIOChannels); ++i)
  209313. {
  209314. if (inputChannels[i])
  209315. {
  209316. inBuffers[n] = tempBuffer + (currentBlockSizeSamples * n);
  209317. ASIOChannelInfo channelInfo;
  209318. zerostruct (channelInfo);
  209319. channelInfo.channel = i;
  209320. channelInfo.isInput = 1;
  209321. asioObject->getChannelInfo (&channelInfo);
  209322. types.addIfNotAlreadyThere (channelInfo.type);
  209323. typeToFormatParameters (channelInfo.type,
  209324. inputChannelBitDepths[n],
  209325. inputChannelBytesPerSample[n],
  209326. inputChannelIsFloat[n],
  209327. inputChannelLittleEndian[n]);
  209328. currentBitDepth = jmax (currentBitDepth, inputChannelBitDepths[n]);
  209329. ++n;
  209330. }
  209331. }
  209332. jassert (numActiveInputChans == n);
  209333. n = 0;
  209334. for (i = 0; i < jmin ((int) totalNumOutputChans, maxASIOChannels); ++i)
  209335. {
  209336. if (outputChannels[i])
  209337. {
  209338. outBuffers[n] = tempBuffer + (currentBlockSizeSamples * (numActiveInputChans + n));
  209339. ASIOChannelInfo channelInfo;
  209340. zerostruct (channelInfo);
  209341. channelInfo.channel = i;
  209342. channelInfo.isInput = 0;
  209343. asioObject->getChannelInfo (&channelInfo);
  209344. types.addIfNotAlreadyThere (channelInfo.type);
  209345. typeToFormatParameters (channelInfo.type,
  209346. outputChannelBitDepths[n],
  209347. outputChannelBytesPerSample[n],
  209348. outputChannelIsFloat[n],
  209349. outputChannelLittleEndian[n]);
  209350. currentBitDepth = jmax (currentBitDepth, outputChannelBitDepths[n]);
  209351. ++n;
  209352. }
  209353. }
  209354. jassert (numActiveOutputChans == n);
  209355. for (i = types.size(); --i >= 0;)
  209356. {
  209357. log ("channel format: " + String (types[i]));
  209358. }
  209359. jassert (n <= totalBuffers);
  209360. for (i = 0; i < numActiveOutputChans; ++i)
  209361. {
  209362. const int size = currentBlockSizeSamples * (outputChannelBitDepths[i] >> 3);
  209363. if (bufferInfos [numActiveInputChans + i].buffers[0] == 0
  209364. || bufferInfos [numActiveInputChans + i].buffers[1] == 0)
  209365. {
  209366. log ("!! Null buffers");
  209367. }
  209368. else
  209369. {
  209370. zeromem (bufferInfos[numActiveInputChans + i].buffers[0], size);
  209371. zeromem (bufferInfos[numActiveInputChans + i].buffers[1], size);
  209372. }
  209373. }
  209374. inputLatency = outputLatency = 0;
  209375. if (asioObject->getLatencies (&inputLatency, &outputLatency) != 0)
  209376. {
  209377. log ("ASIO - no latencies");
  209378. }
  209379. else
  209380. {
  209381. log ("ASIO latencies: " + String ((int) outputLatency) + ", " + String ((int) inputLatency));
  209382. }
  209383. isOpen_ = true;
  209384. log ("starting ASIO");
  209385. calledback = false;
  209386. err = asioObject->start();
  209387. if (err != 0)
  209388. {
  209389. isOpen_ = false;
  209390. log ("ASIO - stop on failure");
  209391. Thread::sleep (10);
  209392. asioObject->stop();
  209393. error = "Can't start device";
  209394. Thread::sleep (10);
  209395. }
  209396. else
  209397. {
  209398. int count = 300;
  209399. while (--count > 0 && ! calledback)
  209400. Thread::sleep (10);
  209401. isStarted = true;
  209402. if (! calledback)
  209403. {
  209404. error = "Device didn't start correctly";
  209405. log ("ASIO didn't callback - stopping..");
  209406. asioObject->stop();
  209407. }
  209408. }
  209409. }
  209410. else
  209411. {
  209412. error = "Can't create i/o buffers";
  209413. }
  209414. }
  209415. else
  209416. {
  209417. error = "Can't set sample rate: ";
  209418. error << sampleRate;
  209419. }
  209420. if (error.isNotEmpty())
  209421. {
  209422. logError (error, err);
  209423. if (asioObject != 0 && buffersCreated)
  209424. asioObject->disposeBuffers();
  209425. Thread::sleep (20);
  209426. isStarted = false;
  209427. isOpen_ = false;
  209428. close();
  209429. }
  209430. needToReset = false;
  209431. isReSync = false;
  209432. return error;
  209433. }
  209434. void close()
  209435. {
  209436. error = String::empty;
  209437. stopTimer();
  209438. stop();
  209439. if (isASIOOpen && isOpen_)
  209440. {
  209441. const ScopedLock sl (callbackLock);
  209442. isOpen_ = false;
  209443. isStarted = false;
  209444. needToReset = false;
  209445. isReSync = false;
  209446. log ("ASIO - stopping");
  209447. if (asioObject != 0)
  209448. {
  209449. Thread::sleep (20);
  209450. asioObject->stop();
  209451. Thread::sleep (10);
  209452. asioObject->disposeBuffers();
  209453. }
  209454. Thread::sleep (10);
  209455. }
  209456. }
  209457. bool isOpen()
  209458. {
  209459. return isOpen_ || insideControlPanelModalLoop;
  209460. }
  209461. int getCurrentBufferSizeSamples()
  209462. {
  209463. return currentBlockSizeSamples;
  209464. }
  209465. double getCurrentSampleRate()
  209466. {
  209467. return currentSampleRate;
  209468. }
  209469. const BigInteger getActiveOutputChannels() const
  209470. {
  209471. return currentChansOut;
  209472. }
  209473. const BigInteger getActiveInputChannels() const
  209474. {
  209475. return currentChansIn;
  209476. }
  209477. int getCurrentBitDepth()
  209478. {
  209479. return currentBitDepth;
  209480. }
  209481. int getOutputLatencyInSamples()
  209482. {
  209483. return outputLatency + currentBlockSizeSamples / 4;
  209484. }
  209485. int getInputLatencyInSamples()
  209486. {
  209487. return inputLatency + currentBlockSizeSamples / 4;
  209488. }
  209489. void start (AudioIODeviceCallback* callback)
  209490. {
  209491. if (callback != 0)
  209492. {
  209493. callback->audioDeviceAboutToStart (this);
  209494. const ScopedLock sl (callbackLock);
  209495. currentCallback = callback;
  209496. }
  209497. }
  209498. void stop()
  209499. {
  209500. AudioIODeviceCallback* const lastCallback = currentCallback;
  209501. {
  209502. const ScopedLock sl (callbackLock);
  209503. currentCallback = 0;
  209504. }
  209505. if (lastCallback != 0)
  209506. lastCallback->audioDeviceStopped();
  209507. }
  209508. bool isPlaying()
  209509. {
  209510. return isASIOOpen && (currentCallback != 0);
  209511. }
  209512. const String getLastError()
  209513. {
  209514. return error;
  209515. }
  209516. bool hasControlPanel() const
  209517. {
  209518. return true;
  209519. }
  209520. bool showControlPanel()
  209521. {
  209522. log ("ASIO - showing control panel");
  209523. Component modalWindow (String::empty);
  209524. modalWindow.setOpaque (true);
  209525. modalWindow.addToDesktop (0);
  209526. modalWindow.enterModalState();
  209527. bool done = false;
  209528. JUCE_TRY
  209529. {
  209530. // are there are devices that need to be closed before showing their control panel?
  209531. // close();
  209532. insideControlPanelModalLoop = true;
  209533. const uint32 started = Time::getMillisecondCounter();
  209534. if (asioObject != 0)
  209535. {
  209536. asioObject->controlPanel();
  209537. const int spent = (int) Time::getMillisecondCounter() - (int) started;
  209538. log ("spent: " + String (spent));
  209539. if (spent > 300)
  209540. {
  209541. shouldUsePreferredSize = true;
  209542. done = true;
  209543. }
  209544. }
  209545. }
  209546. JUCE_CATCH_ALL
  209547. insideControlPanelModalLoop = false;
  209548. return done;
  209549. }
  209550. void resetRequest() throw()
  209551. {
  209552. needToReset = true;
  209553. }
  209554. void resyncRequest() throw()
  209555. {
  209556. needToReset = true;
  209557. isReSync = true;
  209558. }
  209559. void timerCallback()
  209560. {
  209561. if (! insideControlPanelModalLoop)
  209562. {
  209563. stopTimer();
  209564. // used to cause a reset
  209565. log ("! ASIO restart request!");
  209566. if (isOpen_)
  209567. {
  209568. AudioIODeviceCallback* const oldCallback = currentCallback;
  209569. close();
  209570. open (BigInteger (currentChansIn), BigInteger (currentChansOut),
  209571. currentSampleRate, currentBlockSizeSamples);
  209572. if (oldCallback != 0)
  209573. start (oldCallback);
  209574. }
  209575. }
  209576. else
  209577. {
  209578. startTimer (100);
  209579. }
  209580. }
  209581. juce_UseDebuggingNewOperator
  209582. private:
  209583. IASIO* volatile asioObject;
  209584. ASIOCallbacks callbacks;
  209585. void* windowHandle;
  209586. CLSID classId;
  209587. const String optionalDllForDirectLoading;
  209588. String error;
  209589. long totalNumInputChans, totalNumOutputChans;
  209590. StringArray inputChannelNames, outputChannelNames;
  209591. Array<int> sampleRates, bufferSizes;
  209592. long inputLatency, outputLatency;
  209593. long minSize, maxSize, preferredSize, granularity;
  209594. int volatile currentBlockSizeSamples;
  209595. int volatile currentBitDepth;
  209596. double volatile currentSampleRate;
  209597. BigInteger currentChansOut, currentChansIn;
  209598. AudioIODeviceCallback* volatile currentCallback;
  209599. CriticalSection callbackLock;
  209600. ASIOBufferInfo bufferInfos [maxASIOChannels];
  209601. float* inBuffers [maxASIOChannels];
  209602. float* outBuffers [maxASIOChannels];
  209603. int inputChannelBitDepths [maxASIOChannels];
  209604. int outputChannelBitDepths [maxASIOChannels];
  209605. int inputChannelBytesPerSample [maxASIOChannels];
  209606. int outputChannelBytesPerSample [maxASIOChannels];
  209607. bool inputChannelIsFloat [maxASIOChannels];
  209608. bool outputChannelIsFloat [maxASIOChannels];
  209609. bool inputChannelLittleEndian [maxASIOChannels];
  209610. bool outputChannelLittleEndian [maxASIOChannels];
  209611. WaitableEvent event1;
  209612. HeapBlock <float> tempBuffer;
  209613. int volatile bufferIndex, numActiveInputChans, numActiveOutputChans;
  209614. bool isOpen_, isStarted;
  209615. bool volatile isASIOOpen;
  209616. bool volatile calledback;
  209617. bool volatile littleEndian, postOutput, needToReset, isReSync;
  209618. bool volatile insideControlPanelModalLoop;
  209619. bool volatile shouldUsePreferredSize;
  209620. void removeCurrentDriver()
  209621. {
  209622. if (asioObject != 0)
  209623. {
  209624. asioObject->Release();
  209625. asioObject = 0;
  209626. }
  209627. }
  209628. bool loadDriver()
  209629. {
  209630. removeCurrentDriver();
  209631. JUCE_TRY
  209632. {
  209633. if (CoCreateInstance (classId, 0, CLSCTX_INPROC_SERVER,
  209634. classId, (void**) &asioObject) == S_OK)
  209635. {
  209636. return true;
  209637. }
  209638. // If a class isn't registered but we have a path for it, we can fallback to
  209639. // doing a direct load of the COM object (only available via the juce_createASIOAudioIODeviceForGUID function).
  209640. if (optionalDllForDirectLoading.isNotEmpty())
  209641. {
  209642. HMODULE h = LoadLibrary (optionalDllForDirectLoading);
  209643. if (h != 0)
  209644. {
  209645. typedef HRESULT (CALLBACK* DllGetClassObjectFunc) (REFCLSID clsid, REFIID iid, LPVOID* ppv);
  209646. DllGetClassObjectFunc dllGetClassObject = (DllGetClassObjectFunc) GetProcAddress (h, "DllGetClassObject");
  209647. if (dllGetClassObject != 0)
  209648. {
  209649. IClassFactory* classFactory = 0;
  209650. HRESULT hr = dllGetClassObject (classId, IID_IClassFactory, (void**) &classFactory);
  209651. if (classFactory != 0)
  209652. {
  209653. hr = classFactory->CreateInstance (0, classId, (void**) &asioObject);
  209654. classFactory->Release();
  209655. }
  209656. return asioObject != 0;
  209657. }
  209658. }
  209659. }
  209660. }
  209661. JUCE_CATCH_ALL
  209662. asioObject = 0;
  209663. return false;
  209664. }
  209665. const String initDriver()
  209666. {
  209667. if (asioObject != 0)
  209668. {
  209669. char buffer [256];
  209670. zeromem (buffer, sizeof (buffer));
  209671. if (! asioObject->init (windowHandle))
  209672. {
  209673. asioObject->getErrorMessage (buffer);
  209674. return String (buffer, sizeof (buffer) - 1);
  209675. }
  209676. // just in case any daft drivers expect this to be called..
  209677. asioObject->getDriverName (buffer);
  209678. return String::empty;
  209679. }
  209680. return "No Driver";
  209681. }
  209682. const String openDevice()
  209683. {
  209684. // use this in case the driver starts opening dialog boxes..
  209685. Component modalWindow (String::empty);
  209686. modalWindow.setOpaque (true);
  209687. modalWindow.addToDesktop (0);
  209688. modalWindow.enterModalState();
  209689. // open the device and get its info..
  209690. log ("opening ASIO device: " + getName());
  209691. needToReset = false;
  209692. isReSync = false;
  209693. outputChannelNames.clear();
  209694. inputChannelNames.clear();
  209695. bufferSizes.clear();
  209696. sampleRates.clear();
  209697. isASIOOpen = false;
  209698. isOpen_ = false;
  209699. totalNumInputChans = 0;
  209700. totalNumOutputChans = 0;
  209701. numActiveInputChans = 0;
  209702. numActiveOutputChans = 0;
  209703. currentCallback = 0;
  209704. error = String::empty;
  209705. if (getName().isEmpty())
  209706. return error;
  209707. long err = 0;
  209708. if (loadDriver())
  209709. {
  209710. if ((error = initDriver()).isEmpty())
  209711. {
  209712. numActiveInputChans = 0;
  209713. numActiveOutputChans = 0;
  209714. totalNumInputChans = 0;
  209715. totalNumOutputChans = 0;
  209716. if (asioObject != 0
  209717. && (err = asioObject->getChannels (&totalNumInputChans, &totalNumOutputChans)) == 0)
  209718. {
  209719. log (String ((int) totalNumInputChans) + " in, " + String ((int) totalNumOutputChans) + " out");
  209720. if ((err = asioObject->getBufferSize (&minSize, &maxSize, &preferredSize, &granularity)) == 0)
  209721. {
  209722. // find a list of buffer sizes..
  209723. log (String ((int) minSize) + " " + String ((int) maxSize) + " " + String ((int) preferredSize) + " " + String ((int) granularity));
  209724. if (granularity >= 0)
  209725. {
  209726. granularity = jmax (1, (int) granularity);
  209727. for (int i = jmax ((int) minSize, (int) granularity); i < jmin (6400, (int) maxSize); i += granularity)
  209728. bufferSizes.addIfNotAlreadyThere (granularity * (i / granularity));
  209729. }
  209730. else if (granularity < 0)
  209731. {
  209732. for (int i = 0; i < 18; ++i)
  209733. {
  209734. const int s = (1 << i);
  209735. if (s >= minSize && s <= maxSize)
  209736. bufferSizes.add (s);
  209737. }
  209738. }
  209739. if (! bufferSizes.contains (preferredSize))
  209740. bufferSizes.insert (0, preferredSize);
  209741. double currentRate = 0;
  209742. asioObject->getSampleRate (&currentRate);
  209743. if (currentRate <= 0.0 || currentRate > 192001.0)
  209744. {
  209745. log ("setting sample rate");
  209746. err = asioObject->setSampleRate (44100.0);
  209747. if (err != 0)
  209748. {
  209749. logError ("setting sample rate", err);
  209750. }
  209751. asioObject->getSampleRate (&currentRate);
  209752. }
  209753. currentSampleRate = currentRate;
  209754. postOutput = (asioObject->outputReady() == 0);
  209755. if (postOutput)
  209756. {
  209757. log ("ASIO outputReady = ok");
  209758. }
  209759. updateSampleRates();
  209760. // ..because cubase does it at this point
  209761. inputLatency = outputLatency = 0;
  209762. if (asioObject->getLatencies (&inputLatency, &outputLatency) != 0)
  209763. {
  209764. log ("ASIO - no latencies");
  209765. }
  209766. log ("latencies: " + String ((int) inputLatency) + ", " + String ((int) outputLatency));
  209767. // create some dummy buffers now.. because cubase does..
  209768. numActiveInputChans = 0;
  209769. numActiveOutputChans = 0;
  209770. ASIOBufferInfo* info = bufferInfos;
  209771. int i, numChans = 0;
  209772. for (i = 0; i < jmin (2, (int) totalNumInputChans); ++i)
  209773. {
  209774. info->isInput = 1;
  209775. info->channelNum = i;
  209776. info->buffers[0] = info->buffers[1] = 0;
  209777. ++info;
  209778. ++numChans;
  209779. }
  209780. const int outputBufferIndex = numChans;
  209781. for (i = 0; i < jmin (2, (int) totalNumOutputChans); ++i)
  209782. {
  209783. info->isInput = 0;
  209784. info->channelNum = i;
  209785. info->buffers[0] = info->buffers[1] = 0;
  209786. ++info;
  209787. ++numChans;
  209788. }
  209789. callbacks.sampleRateDidChange = &sampleRateChangedCallback;
  209790. if (currentASIODev[0] == this)
  209791. {
  209792. callbacks.bufferSwitch = &bufferSwitchCallback0;
  209793. callbacks.asioMessage = &asioMessagesCallback0;
  209794. callbacks.bufferSwitchTimeInfo = &bufferSwitchTimeInfoCallback0;
  209795. }
  209796. else if (currentASIODev[1] == this)
  209797. {
  209798. callbacks.bufferSwitch = &bufferSwitchCallback1;
  209799. callbacks.asioMessage = &asioMessagesCallback1;
  209800. callbacks.bufferSwitchTimeInfo = &bufferSwitchTimeInfoCallback1;
  209801. }
  209802. else if (currentASIODev[2] == this)
  209803. {
  209804. callbacks.bufferSwitch = &bufferSwitchCallback2;
  209805. callbacks.asioMessage = &asioMessagesCallback2;
  209806. callbacks.bufferSwitchTimeInfo = &bufferSwitchTimeInfoCallback2;
  209807. }
  209808. else
  209809. {
  209810. jassertfalse
  209811. }
  209812. log ("creating buffers (dummy): " + String (numChans) + ", " + String ((int) preferredSize));
  209813. if (preferredSize > 0)
  209814. {
  209815. err = asioObject->createBuffers (bufferInfos, numChans, preferredSize, &callbacks);
  209816. if (err != 0)
  209817. {
  209818. logError ("dummy buffers", err);
  209819. }
  209820. }
  209821. long newInps = 0, newOuts = 0;
  209822. asioObject->getChannels (&newInps, &newOuts);
  209823. if (totalNumInputChans != newInps || totalNumOutputChans != newOuts)
  209824. {
  209825. totalNumInputChans = newInps;
  209826. totalNumOutputChans = newOuts;
  209827. log (String ((int) totalNumInputChans) + " in; " + String ((int) totalNumOutputChans) + " out");
  209828. }
  209829. updateSampleRates();
  209830. ASIOChannelInfo channelInfo;
  209831. channelInfo.type = 0;
  209832. for (i = 0; i < totalNumInputChans; ++i)
  209833. {
  209834. zerostruct (channelInfo);
  209835. channelInfo.channel = i;
  209836. channelInfo.isInput = 1;
  209837. asioObject->getChannelInfo (&channelInfo);
  209838. inputChannelNames.add (String (channelInfo.name));
  209839. }
  209840. for (i = 0; i < totalNumOutputChans; ++i)
  209841. {
  209842. zerostruct (channelInfo);
  209843. channelInfo.channel = i;
  209844. channelInfo.isInput = 0;
  209845. asioObject->getChannelInfo (&channelInfo);
  209846. outputChannelNames.add (String (channelInfo.name));
  209847. typeToFormatParameters (channelInfo.type,
  209848. outputChannelBitDepths[i],
  209849. outputChannelBytesPerSample[i],
  209850. outputChannelIsFloat[i],
  209851. outputChannelLittleEndian[i]);
  209852. if (i < 2)
  209853. {
  209854. // clear the channels that are used with the dummy stuff
  209855. const int bytesPerBuffer = preferredSize * (outputChannelBitDepths[i] >> 3);
  209856. zeromem (bufferInfos [outputBufferIndex + i].buffers[0], bytesPerBuffer);
  209857. zeromem (bufferInfos [outputBufferIndex + i].buffers[1], bytesPerBuffer);
  209858. }
  209859. }
  209860. outputChannelNames.trim();
  209861. inputChannelNames.trim();
  209862. outputChannelNames.appendNumbersToDuplicates (false, true);
  209863. inputChannelNames.appendNumbersToDuplicates (false, true);
  209864. // start and stop because cubase does it..
  209865. asioObject->getLatencies (&inputLatency, &outputLatency);
  209866. if ((err = asioObject->start()) != 0)
  209867. {
  209868. // ignore an error here, as it might start later after setting other stuff up
  209869. logError ("ASIO start", err);
  209870. }
  209871. Thread::sleep (100);
  209872. asioObject->stop();
  209873. }
  209874. else
  209875. {
  209876. error = "Can't detect buffer sizes";
  209877. }
  209878. }
  209879. else
  209880. {
  209881. error = "Can't detect asio channels";
  209882. }
  209883. }
  209884. }
  209885. else
  209886. {
  209887. error = "No such device";
  209888. }
  209889. if (error.isNotEmpty())
  209890. {
  209891. logError (error, err);
  209892. if (asioObject != 0)
  209893. asioObject->disposeBuffers();
  209894. removeCurrentDriver();
  209895. isASIOOpen = false;
  209896. }
  209897. else
  209898. {
  209899. isASIOOpen = true;
  209900. log ("ASIO device open");
  209901. }
  209902. isOpen_ = false;
  209903. needToReset = false;
  209904. isReSync = false;
  209905. return error;
  209906. }
  209907. void callback (const long index)
  209908. {
  209909. if (isStarted)
  209910. {
  209911. bufferIndex = index;
  209912. processBuffer();
  209913. }
  209914. else
  209915. {
  209916. if (postOutput && (asioObject != 0))
  209917. asioObject->outputReady();
  209918. }
  209919. calledback = true;
  209920. }
  209921. void processBuffer()
  209922. {
  209923. const ASIOBufferInfo* const infos = bufferInfos;
  209924. const int bi = bufferIndex;
  209925. const ScopedLock sl (callbackLock);
  209926. if (needToReset)
  209927. {
  209928. needToReset = false;
  209929. if (isReSync)
  209930. {
  209931. log ("! ASIO resync");
  209932. isReSync = false;
  209933. }
  209934. else
  209935. {
  209936. startTimer (20);
  209937. }
  209938. }
  209939. if (bi >= 0)
  209940. {
  209941. const int samps = currentBlockSizeSamples;
  209942. if (currentCallback != 0)
  209943. {
  209944. int i;
  209945. for (i = 0; i < numActiveInputChans; ++i)
  209946. {
  209947. float* const dst = inBuffers[i];
  209948. jassert (dst != 0);
  209949. const char* const src = (const char*) (infos[i].buffers[bi]);
  209950. if (inputChannelIsFloat[i])
  209951. {
  209952. memcpy (dst, src, samps * sizeof (float));
  209953. }
  209954. else
  209955. {
  209956. jassert (dst == tempBuffer + (samps * i));
  209957. switch (inputChannelBitDepths[i])
  209958. {
  209959. case 16:
  209960. convertInt16ToFloat (src, dst, inputChannelBytesPerSample[i],
  209961. samps, inputChannelLittleEndian[i]);
  209962. break;
  209963. case 24:
  209964. convertInt24ToFloat (src, dst, inputChannelBytesPerSample[i],
  209965. samps, inputChannelLittleEndian[i]);
  209966. break;
  209967. case 32:
  209968. convertInt32ToFloat (src, dst, inputChannelBytesPerSample[i],
  209969. samps, inputChannelLittleEndian[i]);
  209970. break;
  209971. case 64:
  209972. jassertfalse
  209973. break;
  209974. }
  209975. }
  209976. }
  209977. currentCallback->audioDeviceIOCallback ((const float**) inBuffers,
  209978. numActiveInputChans,
  209979. outBuffers,
  209980. numActiveOutputChans,
  209981. samps);
  209982. for (i = 0; i < numActiveOutputChans; ++i)
  209983. {
  209984. float* const src = outBuffers[i];
  209985. jassert (src != 0);
  209986. char* const dst = (char*) (infos [numActiveInputChans + i].buffers[bi]);
  209987. if (outputChannelIsFloat[i])
  209988. {
  209989. memcpy (dst, src, samps * sizeof (float));
  209990. }
  209991. else
  209992. {
  209993. jassert (src == tempBuffer + (samps * (numActiveInputChans + i)));
  209994. switch (outputChannelBitDepths[i])
  209995. {
  209996. case 16:
  209997. convertFloatToInt16 (src, dst, outputChannelBytesPerSample[i],
  209998. samps, outputChannelLittleEndian[i]);
  209999. break;
  210000. case 24:
  210001. convertFloatToInt24 (src, dst, outputChannelBytesPerSample[i],
  210002. samps, outputChannelLittleEndian[i]);
  210003. break;
  210004. case 32:
  210005. convertFloatToInt32 (src, dst, outputChannelBytesPerSample[i],
  210006. samps, outputChannelLittleEndian[i]);
  210007. break;
  210008. case 64:
  210009. jassertfalse
  210010. break;
  210011. }
  210012. }
  210013. }
  210014. }
  210015. else
  210016. {
  210017. for (int i = 0; i < numActiveOutputChans; ++i)
  210018. {
  210019. const int bytesPerBuffer = samps * (outputChannelBitDepths[i] >> 3);
  210020. zeromem (infos[numActiveInputChans + i].buffers[bi], bytesPerBuffer);
  210021. }
  210022. }
  210023. }
  210024. if (postOutput)
  210025. asioObject->outputReady();
  210026. }
  210027. static ASIOTime* bufferSwitchTimeInfoCallback0 (ASIOTime*, long index, long)
  210028. {
  210029. if (currentASIODev[0] != 0)
  210030. currentASIODev[0]->callback (index);
  210031. return 0;
  210032. }
  210033. static ASIOTime* bufferSwitchTimeInfoCallback1 (ASIOTime*, long index, long)
  210034. {
  210035. if (currentASIODev[1] != 0)
  210036. currentASIODev[1]->callback (index);
  210037. return 0;
  210038. }
  210039. static ASIOTime* bufferSwitchTimeInfoCallback2 (ASIOTime*, long index, long)
  210040. {
  210041. if (currentASIODev[2] != 0)
  210042. currentASIODev[2]->callback (index);
  210043. return 0;
  210044. }
  210045. static void bufferSwitchCallback0 (long index, long)
  210046. {
  210047. if (currentASIODev[0] != 0)
  210048. currentASIODev[0]->callback (index);
  210049. }
  210050. static void bufferSwitchCallback1 (long index, long)
  210051. {
  210052. if (currentASIODev[1] != 0)
  210053. currentASIODev[1]->callback (index);
  210054. }
  210055. static void bufferSwitchCallback2 (long index, long)
  210056. {
  210057. if (currentASIODev[2] != 0)
  210058. currentASIODev[2]->callback (index);
  210059. }
  210060. static long asioMessagesCallback0 (long selector, long value, void*, double*)
  210061. {
  210062. return asioMessagesCallback (selector, value, 0);
  210063. }
  210064. static long asioMessagesCallback1 (long selector, long value, void*, double*)
  210065. {
  210066. return asioMessagesCallback (selector, value, 1);
  210067. }
  210068. static long asioMessagesCallback2 (long selector, long value, void*, double*)
  210069. {
  210070. return asioMessagesCallback (selector, value, 2);
  210071. }
  210072. static long asioMessagesCallback (long selector, long value, const int deviceIndex)
  210073. {
  210074. switch (selector)
  210075. {
  210076. case kAsioSelectorSupported:
  210077. if (value == kAsioResetRequest
  210078. || value == kAsioEngineVersion
  210079. || value == kAsioResyncRequest
  210080. || value == kAsioLatenciesChanged
  210081. || value == kAsioSupportsInputMonitor)
  210082. return 1;
  210083. break;
  210084. case kAsioBufferSizeChange:
  210085. break;
  210086. case kAsioResetRequest:
  210087. if (currentASIODev[deviceIndex] != 0)
  210088. currentASIODev[deviceIndex]->resetRequest();
  210089. return 1;
  210090. case kAsioResyncRequest:
  210091. if (currentASIODev[deviceIndex] != 0)
  210092. currentASIODev[deviceIndex]->resyncRequest();
  210093. return 1;
  210094. case kAsioLatenciesChanged:
  210095. return 1;
  210096. case kAsioEngineVersion:
  210097. return 2;
  210098. case kAsioSupportsTimeInfo:
  210099. case kAsioSupportsTimeCode:
  210100. return 0;
  210101. }
  210102. return 0;
  210103. }
  210104. static void sampleRateChangedCallback (ASIOSampleRate) throw()
  210105. {
  210106. }
  210107. static void convertInt16ToFloat (const char* src,
  210108. float* dest,
  210109. const int srcStrideBytes,
  210110. int numSamples,
  210111. const bool littleEndian) throw()
  210112. {
  210113. const double g = 1.0 / 32768.0;
  210114. if (littleEndian)
  210115. {
  210116. while (--numSamples >= 0)
  210117. {
  210118. *dest++ = (float) (g * (short) ByteOrder::littleEndianShort (src));
  210119. src += srcStrideBytes;
  210120. }
  210121. }
  210122. else
  210123. {
  210124. while (--numSamples >= 0)
  210125. {
  210126. *dest++ = (float) (g * (short) ByteOrder::bigEndianShort (src));
  210127. src += srcStrideBytes;
  210128. }
  210129. }
  210130. }
  210131. static void convertFloatToInt16 (const float* src,
  210132. char* dest,
  210133. const int dstStrideBytes,
  210134. int numSamples,
  210135. const bool littleEndian) throw()
  210136. {
  210137. const double maxVal = (double) 0x7fff;
  210138. if (littleEndian)
  210139. {
  210140. while (--numSamples >= 0)
  210141. {
  210142. *(uint16*) dest = ByteOrder::swapIfBigEndian ((uint16) (short) roundDoubleToInt (jlimit (-maxVal, maxVal, maxVal * *src++)));
  210143. dest += dstStrideBytes;
  210144. }
  210145. }
  210146. else
  210147. {
  210148. while (--numSamples >= 0)
  210149. {
  210150. *(uint16*) dest = ByteOrder::swapIfLittleEndian ((uint16) (short) roundDoubleToInt (jlimit (-maxVal, maxVal, maxVal * *src++)));
  210151. dest += dstStrideBytes;
  210152. }
  210153. }
  210154. }
  210155. static void convertInt24ToFloat (const char* src,
  210156. float* dest,
  210157. const int srcStrideBytes,
  210158. int numSamples,
  210159. const bool littleEndian) throw()
  210160. {
  210161. const double g = 1.0 / 0x7fffff;
  210162. if (littleEndian)
  210163. {
  210164. while (--numSamples >= 0)
  210165. {
  210166. *dest++ = (float) (g * ByteOrder::littleEndian24Bit (src));
  210167. src += srcStrideBytes;
  210168. }
  210169. }
  210170. else
  210171. {
  210172. while (--numSamples >= 0)
  210173. {
  210174. *dest++ = (float) (g * ByteOrder::bigEndian24Bit (src));
  210175. src += srcStrideBytes;
  210176. }
  210177. }
  210178. }
  210179. static void convertFloatToInt24 (const float* src,
  210180. char* dest,
  210181. const int dstStrideBytes,
  210182. int numSamples,
  210183. const bool littleEndian) throw()
  210184. {
  210185. const double maxVal = (double) 0x7fffff;
  210186. if (littleEndian)
  210187. {
  210188. while (--numSamples >= 0)
  210189. {
  210190. ByteOrder::littleEndian24BitToChars ((uint32) roundDoubleToInt (jlimit (-maxVal, maxVal, maxVal * *src++)), dest);
  210191. dest += dstStrideBytes;
  210192. }
  210193. }
  210194. else
  210195. {
  210196. while (--numSamples >= 0)
  210197. {
  210198. ByteOrder::bigEndian24BitToChars ((uint32) roundDoubleToInt (jlimit (-maxVal, maxVal, maxVal * *src++)), dest);
  210199. dest += dstStrideBytes;
  210200. }
  210201. }
  210202. }
  210203. static void convertInt32ToFloat (const char* src,
  210204. float* dest,
  210205. const int srcStrideBytes,
  210206. int numSamples,
  210207. const bool littleEndian) throw()
  210208. {
  210209. const double g = 1.0 / 0x7fffffff;
  210210. if (littleEndian)
  210211. {
  210212. while (--numSamples >= 0)
  210213. {
  210214. *dest++ = (float) (g * (int) ByteOrder::littleEndianInt (src));
  210215. src += srcStrideBytes;
  210216. }
  210217. }
  210218. else
  210219. {
  210220. while (--numSamples >= 0)
  210221. {
  210222. *dest++ = (float) (g * (int) ByteOrder::bigEndianInt (src));
  210223. src += srcStrideBytes;
  210224. }
  210225. }
  210226. }
  210227. static void convertFloatToInt32 (const float* src,
  210228. char* dest,
  210229. const int dstStrideBytes,
  210230. int numSamples,
  210231. const bool littleEndian) throw()
  210232. {
  210233. const double maxVal = (double) 0x7fffffff;
  210234. if (littleEndian)
  210235. {
  210236. while (--numSamples >= 0)
  210237. {
  210238. *(uint32*) dest = ByteOrder::swapIfBigEndian ((uint32) roundDoubleToInt (jlimit (-maxVal, maxVal, maxVal * *src++)));
  210239. dest += dstStrideBytes;
  210240. }
  210241. }
  210242. else
  210243. {
  210244. while (--numSamples >= 0)
  210245. {
  210246. *(uint32*) dest = ByteOrder::swapIfLittleEndian ((uint32) roundDoubleToInt (jlimit (-maxVal, maxVal, maxVal * *src++)));
  210247. dest += dstStrideBytes;
  210248. }
  210249. }
  210250. }
  210251. static void typeToFormatParameters (const long type,
  210252. int& bitDepth,
  210253. int& byteStride,
  210254. bool& formatIsFloat,
  210255. bool& littleEndian) throw()
  210256. {
  210257. bitDepth = 0;
  210258. littleEndian = false;
  210259. formatIsFloat = false;
  210260. switch (type)
  210261. {
  210262. case ASIOSTInt16MSB:
  210263. case ASIOSTInt16LSB:
  210264. case ASIOSTInt32MSB16:
  210265. case ASIOSTInt32LSB16:
  210266. bitDepth = 16; break;
  210267. case ASIOSTFloat32MSB:
  210268. case ASIOSTFloat32LSB:
  210269. formatIsFloat = true;
  210270. bitDepth = 32; break;
  210271. case ASIOSTInt32MSB:
  210272. case ASIOSTInt32LSB:
  210273. bitDepth = 32; break;
  210274. case ASIOSTInt24MSB:
  210275. case ASIOSTInt24LSB:
  210276. case ASIOSTInt32MSB24:
  210277. case ASIOSTInt32LSB24:
  210278. case ASIOSTInt32MSB18:
  210279. case ASIOSTInt32MSB20:
  210280. case ASIOSTInt32LSB18:
  210281. case ASIOSTInt32LSB20:
  210282. bitDepth = 24; break;
  210283. case ASIOSTFloat64MSB:
  210284. case ASIOSTFloat64LSB:
  210285. default:
  210286. bitDepth = 64;
  210287. break;
  210288. }
  210289. switch (type)
  210290. {
  210291. case ASIOSTInt16MSB:
  210292. case ASIOSTInt32MSB16:
  210293. case ASIOSTFloat32MSB:
  210294. case ASIOSTFloat64MSB:
  210295. case ASIOSTInt32MSB:
  210296. case ASIOSTInt32MSB18:
  210297. case ASIOSTInt32MSB20:
  210298. case ASIOSTInt32MSB24:
  210299. case ASIOSTInt24MSB:
  210300. littleEndian = false; break;
  210301. case ASIOSTInt16LSB:
  210302. case ASIOSTInt32LSB16:
  210303. case ASIOSTFloat32LSB:
  210304. case ASIOSTFloat64LSB:
  210305. case ASIOSTInt32LSB:
  210306. case ASIOSTInt32LSB18:
  210307. case ASIOSTInt32LSB20:
  210308. case ASIOSTInt32LSB24:
  210309. case ASIOSTInt24LSB:
  210310. littleEndian = true; break;
  210311. default:
  210312. break;
  210313. }
  210314. switch (type)
  210315. {
  210316. case ASIOSTInt16LSB:
  210317. case ASIOSTInt16MSB:
  210318. byteStride = 2; break;
  210319. case ASIOSTInt24LSB:
  210320. case ASIOSTInt24MSB:
  210321. byteStride = 3; break;
  210322. case ASIOSTInt32MSB16:
  210323. case ASIOSTInt32LSB16:
  210324. case ASIOSTInt32MSB:
  210325. case ASIOSTInt32MSB18:
  210326. case ASIOSTInt32MSB20:
  210327. case ASIOSTInt32MSB24:
  210328. case ASIOSTInt32LSB:
  210329. case ASIOSTInt32LSB18:
  210330. case ASIOSTInt32LSB20:
  210331. case ASIOSTInt32LSB24:
  210332. case ASIOSTFloat32LSB:
  210333. case ASIOSTFloat32MSB:
  210334. byteStride = 4; break;
  210335. case ASIOSTFloat64MSB:
  210336. case ASIOSTFloat64LSB:
  210337. byteStride = 8; break;
  210338. default:
  210339. break;
  210340. }
  210341. }
  210342. };
  210343. class ASIOAudioIODeviceType : public AudioIODeviceType
  210344. {
  210345. public:
  210346. ASIOAudioIODeviceType()
  210347. : AudioIODeviceType ("ASIO"),
  210348. hasScanned (false)
  210349. {
  210350. CoInitialize (0);
  210351. }
  210352. ~ASIOAudioIODeviceType()
  210353. {
  210354. }
  210355. void scanForDevices()
  210356. {
  210357. hasScanned = true;
  210358. deviceNames.clear();
  210359. classIds.clear();
  210360. HKEY hk = 0;
  210361. int index = 0;
  210362. if (RegOpenKeyA (HKEY_LOCAL_MACHINE, "software\\asio", &hk) == ERROR_SUCCESS)
  210363. {
  210364. for (;;)
  210365. {
  210366. char name [256];
  210367. if (RegEnumKeyA (hk, index++, name, 256) == ERROR_SUCCESS)
  210368. {
  210369. addDriverInfo (name, hk);
  210370. }
  210371. else
  210372. {
  210373. break;
  210374. }
  210375. }
  210376. RegCloseKey (hk);
  210377. }
  210378. }
  210379. const StringArray getDeviceNames (bool /*wantInputNames*/) const
  210380. {
  210381. jassert (hasScanned); // need to call scanForDevices() before doing this
  210382. return deviceNames;
  210383. }
  210384. int getDefaultDeviceIndex (bool) const
  210385. {
  210386. jassert (hasScanned); // need to call scanForDevices() before doing this
  210387. for (int i = deviceNames.size(); --i >= 0;)
  210388. if (deviceNames[i].containsIgnoreCase ("asio4all"))
  210389. return i; // asio4all is a safe choice for a default..
  210390. #if JUCE_DEBUG
  210391. if (deviceNames.size() > 1 && deviceNames[0].containsIgnoreCase ("digidesign"))
  210392. return 1; // (the digi m-box driver crashes the app when you run
  210393. // it in the debugger, which can be a bit annoying)
  210394. #endif
  210395. return 0;
  210396. }
  210397. static int findFreeSlot()
  210398. {
  210399. for (int i = 0; i < numElementsInArray (currentASIODev); ++i)
  210400. if (currentASIODev[i] == 0)
  210401. return i;
  210402. jassertfalse; // unfortunately you can only have a finite number
  210403. // of ASIO devices open at the same time..
  210404. return -1;
  210405. }
  210406. int getIndexOfDevice (AudioIODevice* d, bool /*asInput*/) const
  210407. {
  210408. jassert (hasScanned); // need to call scanForDevices() before doing this
  210409. return d == 0 ? -1 : deviceNames.indexOf (d->getName());
  210410. }
  210411. bool hasSeparateInputsAndOutputs() const { return false; }
  210412. AudioIODevice* createDevice (const String& outputDeviceName,
  210413. const String& inputDeviceName)
  210414. {
  210415. // ASIO can't open two different devices for input and output - they must be the same one.
  210416. jassert (inputDeviceName == outputDeviceName || outputDeviceName.isEmpty() || inputDeviceName.isEmpty());
  210417. jassert (hasScanned); // need to call scanForDevices() before doing this
  210418. const int index = deviceNames.indexOf (outputDeviceName.isNotEmpty() ? outputDeviceName
  210419. : inputDeviceName);
  210420. if (index >= 0)
  210421. {
  210422. const int freeSlot = findFreeSlot();
  210423. if (freeSlot >= 0)
  210424. return new ASIOAudioIODevice (outputDeviceName, *(classIds [index]), freeSlot, String::empty);
  210425. }
  210426. return 0;
  210427. }
  210428. juce_UseDebuggingNewOperator
  210429. private:
  210430. StringArray deviceNames;
  210431. OwnedArray <CLSID> classIds;
  210432. bool hasScanned;
  210433. static bool checkClassIsOk (const String& classId)
  210434. {
  210435. HKEY hk = 0;
  210436. bool ok = false;
  210437. if (RegOpenKey (HKEY_CLASSES_ROOT, _T("clsid"), &hk) == ERROR_SUCCESS)
  210438. {
  210439. int index = 0;
  210440. for (;;)
  210441. {
  210442. WCHAR buf [512];
  210443. if (RegEnumKey (hk, index++, buf, 512) == ERROR_SUCCESS)
  210444. {
  210445. if (classId.equalsIgnoreCase (buf))
  210446. {
  210447. HKEY subKey, pathKey;
  210448. if (RegOpenKeyEx (hk, buf, 0, KEY_READ, &subKey) == ERROR_SUCCESS)
  210449. {
  210450. if (RegOpenKeyEx (subKey, _T("InprocServer32"), 0, KEY_READ, &pathKey) == ERROR_SUCCESS)
  210451. {
  210452. WCHAR pathName [1024];
  210453. DWORD dtype = REG_SZ;
  210454. DWORD dsize = sizeof (pathName);
  210455. if (RegQueryValueEx (pathKey, 0, 0, &dtype, (LPBYTE) pathName, &dsize) == ERROR_SUCCESS)
  210456. ok = File (pathName).exists();
  210457. RegCloseKey (pathKey);
  210458. }
  210459. RegCloseKey (subKey);
  210460. }
  210461. break;
  210462. }
  210463. }
  210464. else
  210465. {
  210466. break;
  210467. }
  210468. }
  210469. RegCloseKey (hk);
  210470. }
  210471. return ok;
  210472. }
  210473. void addDriverInfo (const String& keyName, HKEY hk)
  210474. {
  210475. HKEY subKey;
  210476. if (RegOpenKeyEx (hk, keyName, 0, KEY_READ, &subKey) == ERROR_SUCCESS)
  210477. {
  210478. WCHAR buf [256];
  210479. zerostruct (buf);
  210480. DWORD dtype = REG_SZ;
  210481. DWORD dsize = sizeof (buf);
  210482. if (RegQueryValueEx (subKey, _T("clsid"), 0, &dtype, (LPBYTE) buf, &dsize) == ERROR_SUCCESS)
  210483. {
  210484. if (dsize > 0 && checkClassIsOk (buf))
  210485. {
  210486. CLSID classId;
  210487. if (CLSIDFromString ((LPOLESTR) buf, &classId) == S_OK)
  210488. {
  210489. dtype = REG_SZ;
  210490. dsize = sizeof (buf);
  210491. String deviceName;
  210492. if (RegQueryValueEx (subKey, _T("description"), 0, &dtype, (LPBYTE) buf, &dsize) == ERROR_SUCCESS)
  210493. deviceName = buf;
  210494. else
  210495. deviceName = keyName;
  210496. log ("found " + deviceName);
  210497. deviceNames.add (deviceName);
  210498. classIds.add (new CLSID (classId));
  210499. }
  210500. }
  210501. RegCloseKey (subKey);
  210502. }
  210503. }
  210504. }
  210505. ASIOAudioIODeviceType (const ASIOAudioIODeviceType&);
  210506. ASIOAudioIODeviceType& operator= (const ASIOAudioIODeviceType&);
  210507. };
  210508. AudioIODeviceType* juce_createAudioIODeviceType_ASIO()
  210509. {
  210510. return new ASIOAudioIODeviceType();
  210511. }
  210512. AudioIODevice* juce_createASIOAudioIODeviceForGUID (const String& name,
  210513. void* guid,
  210514. const String& optionalDllForDirectLoading)
  210515. {
  210516. const int freeSlot = ASIOAudioIODeviceType::findFreeSlot();
  210517. if (freeSlot < 0)
  210518. return 0;
  210519. return new ASIOAudioIODevice (name, *(CLSID*) guid, freeSlot, optionalDllForDirectLoading);
  210520. }
  210521. #undef log
  210522. #endif
  210523. /*** End of inlined file: juce_win32_ASIO.cpp ***/
  210524. /*** Start of inlined file: juce_win32_DirectSound.cpp ***/
  210525. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  210526. // compiled on its own).
  210527. #if JUCE_INCLUDED_FILE && JUCE_DIRECTSOUND
  210528. END_JUCE_NAMESPACE
  210529. extern "C"
  210530. {
  210531. // Declare just the minimum number of interfaces for the DSound objects that we need..
  210532. typedef struct typeDSBUFFERDESC
  210533. {
  210534. DWORD dwSize;
  210535. DWORD dwFlags;
  210536. DWORD dwBufferBytes;
  210537. DWORD dwReserved;
  210538. LPWAVEFORMATEX lpwfxFormat;
  210539. GUID guid3DAlgorithm;
  210540. } DSBUFFERDESC;
  210541. struct IDirectSoundBuffer;
  210542. #undef INTERFACE
  210543. #define INTERFACE IDirectSound
  210544. DECLARE_INTERFACE_(IDirectSound, IUnknown)
  210545. {
  210546. STDMETHOD(QueryInterface) (THIS_ REFIID, LPVOID*) PURE;
  210547. STDMETHOD_(ULONG,AddRef) (THIS) PURE;
  210548. STDMETHOD_(ULONG,Release) (THIS) PURE;
  210549. STDMETHOD(CreateSoundBuffer) (THIS_ DSBUFFERDESC*, IDirectSoundBuffer**, LPUNKNOWN) PURE;
  210550. STDMETHOD(GetCaps) (THIS_ void*) PURE;
  210551. STDMETHOD(DuplicateSoundBuffer) (THIS_ IDirectSoundBuffer*, IDirectSoundBuffer**) PURE;
  210552. STDMETHOD(SetCooperativeLevel) (THIS_ HWND, DWORD) PURE;
  210553. STDMETHOD(Compact) (THIS) PURE;
  210554. STDMETHOD(GetSpeakerConfig) (THIS_ LPDWORD) PURE;
  210555. STDMETHOD(SetSpeakerConfig) (THIS_ DWORD) PURE;
  210556. STDMETHOD(Initialize) (THIS_ const GUID*) PURE;
  210557. };
  210558. #undef INTERFACE
  210559. #define INTERFACE IDirectSoundBuffer
  210560. DECLARE_INTERFACE_(IDirectSoundBuffer, IUnknown)
  210561. {
  210562. STDMETHOD(QueryInterface) (THIS_ REFIID, LPVOID*) PURE;
  210563. STDMETHOD_(ULONG,AddRef) (THIS) PURE;
  210564. STDMETHOD_(ULONG,Release) (THIS) PURE;
  210565. STDMETHOD(GetCaps) (THIS_ void*) PURE;
  210566. STDMETHOD(GetCurrentPosition) (THIS_ LPDWORD, LPDWORD) PURE;
  210567. STDMETHOD(GetFormat) (THIS_ LPWAVEFORMATEX, DWORD, LPDWORD) PURE;
  210568. STDMETHOD(GetVolume) (THIS_ LPLONG) PURE;
  210569. STDMETHOD(GetPan) (THIS_ LPLONG) PURE;
  210570. STDMETHOD(GetFrequency) (THIS_ LPDWORD) PURE;
  210571. STDMETHOD(GetStatus) (THIS_ LPDWORD) PURE;
  210572. STDMETHOD(Initialize) (THIS_ IDirectSound*, DSBUFFERDESC*) PURE;
  210573. STDMETHOD(Lock) (THIS_ DWORD, DWORD, LPVOID*, LPDWORD, LPVOID*, LPDWORD, DWORD) PURE;
  210574. STDMETHOD(Play) (THIS_ DWORD, DWORD, DWORD) PURE;
  210575. STDMETHOD(SetCurrentPosition) (THIS_ DWORD) PURE;
  210576. STDMETHOD(SetFormat) (THIS_ const WAVEFORMATEX*) PURE;
  210577. STDMETHOD(SetVolume) (THIS_ LONG) PURE;
  210578. STDMETHOD(SetPan) (THIS_ LONG) PURE;
  210579. STDMETHOD(SetFrequency) (THIS_ DWORD) PURE;
  210580. STDMETHOD(Stop) (THIS) PURE;
  210581. STDMETHOD(Unlock) (THIS_ LPVOID, DWORD, LPVOID, DWORD) PURE;
  210582. STDMETHOD(Restore) (THIS) PURE;
  210583. };
  210584. typedef struct typeDSCBUFFERDESC
  210585. {
  210586. DWORD dwSize;
  210587. DWORD dwFlags;
  210588. DWORD dwBufferBytes;
  210589. DWORD dwReserved;
  210590. LPWAVEFORMATEX lpwfxFormat;
  210591. } DSCBUFFERDESC;
  210592. struct IDirectSoundCaptureBuffer;
  210593. #undef INTERFACE
  210594. #define INTERFACE IDirectSoundCapture
  210595. DECLARE_INTERFACE_(IDirectSoundCapture, IUnknown)
  210596. {
  210597. STDMETHOD(QueryInterface) (THIS_ REFIID, LPVOID*) PURE;
  210598. STDMETHOD_(ULONG,AddRef) (THIS) PURE;
  210599. STDMETHOD_(ULONG,Release) (THIS) PURE;
  210600. STDMETHOD(CreateCaptureBuffer) (THIS_ DSCBUFFERDESC*, IDirectSoundCaptureBuffer**, LPUNKNOWN) PURE;
  210601. STDMETHOD(GetCaps) (THIS_ void*) PURE;
  210602. STDMETHOD(Initialize) (THIS_ const GUID*) PURE;
  210603. };
  210604. #undef INTERFACE
  210605. #define INTERFACE IDirectSoundCaptureBuffer
  210606. DECLARE_INTERFACE_(IDirectSoundCaptureBuffer, IUnknown)
  210607. {
  210608. STDMETHOD(QueryInterface) (THIS_ REFIID, LPVOID*) PURE;
  210609. STDMETHOD_(ULONG,AddRef) (THIS) PURE;
  210610. STDMETHOD_(ULONG,Release) (THIS) PURE;
  210611. STDMETHOD(GetCaps) (THIS_ void*) PURE;
  210612. STDMETHOD(GetCurrentPosition) (THIS_ LPDWORD, LPDWORD) PURE;
  210613. STDMETHOD(GetFormat) (THIS_ LPWAVEFORMATEX, DWORD, LPDWORD) PURE;
  210614. STDMETHOD(GetStatus) (THIS_ LPDWORD) PURE;
  210615. STDMETHOD(Initialize) (THIS_ IDirectSoundCapture*, DSCBUFFERDESC*) PURE;
  210616. STDMETHOD(Lock) (THIS_ DWORD, DWORD, LPVOID*, LPDWORD, LPVOID*, LPDWORD, DWORD) PURE;
  210617. STDMETHOD(Start) (THIS_ DWORD) PURE;
  210618. STDMETHOD(Stop) (THIS) PURE;
  210619. STDMETHOD(Unlock) (THIS_ LPVOID, DWORD, LPVOID, DWORD) PURE;
  210620. };
  210621. };
  210622. BEGIN_JUCE_NAMESPACE
  210623. static const String getDSErrorMessage (HRESULT hr)
  210624. {
  210625. const char* result = 0;
  210626. switch (hr)
  210627. {
  210628. case MAKE_HRESULT(1, 0x878, 10):
  210629. result = "Device already allocated";
  210630. break;
  210631. case MAKE_HRESULT(1, 0x878, 30):
  210632. result = "Control unavailable";
  210633. break;
  210634. case E_INVALIDARG:
  210635. result = "Invalid parameter";
  210636. break;
  210637. case MAKE_HRESULT(1, 0x878, 50):
  210638. result = "Invalid call";
  210639. break;
  210640. case E_FAIL:
  210641. result = "Generic error";
  210642. break;
  210643. case MAKE_HRESULT(1, 0x878, 70):
  210644. result = "Priority level error";
  210645. break;
  210646. case E_OUTOFMEMORY:
  210647. result = "Out of memory";
  210648. break;
  210649. case MAKE_HRESULT(1, 0x878, 100):
  210650. result = "Bad format";
  210651. break;
  210652. case E_NOTIMPL:
  210653. result = "Unsupported function";
  210654. break;
  210655. case MAKE_HRESULT(1, 0x878, 120):
  210656. result = "No driver";
  210657. break;
  210658. case MAKE_HRESULT(1, 0x878, 130):
  210659. result = "Already initialised";
  210660. break;
  210661. case CLASS_E_NOAGGREGATION:
  210662. result = "No aggregation";
  210663. break;
  210664. case MAKE_HRESULT(1, 0x878, 150):
  210665. result = "Buffer lost";
  210666. break;
  210667. case MAKE_HRESULT(1, 0x878, 160):
  210668. result = "Another app has priority";
  210669. break;
  210670. case MAKE_HRESULT(1, 0x878, 170):
  210671. result = "Uninitialised";
  210672. break;
  210673. case E_NOINTERFACE:
  210674. result = "No interface";
  210675. break;
  210676. case S_OK:
  210677. result = "No error";
  210678. break;
  210679. default:
  210680. return "Unknown error: " + String ((int) hr);
  210681. }
  210682. return result;
  210683. }
  210684. #define DS_DEBUGGING 1
  210685. #ifdef DS_DEBUGGING
  210686. #define CATCH JUCE_CATCH_EXCEPTION
  210687. #undef log
  210688. #define log(a) Logger::writeToLog(a);
  210689. #undef logError
  210690. #define logError(a) logDSError(a, __LINE__);
  210691. static void logDSError (HRESULT hr, int lineNum)
  210692. {
  210693. if (hr != S_OK)
  210694. {
  210695. String error ("DS error at line ");
  210696. error << lineNum << " - " << getDSErrorMessage (hr);
  210697. log (error);
  210698. }
  210699. }
  210700. #else
  210701. #define CATCH JUCE_CATCH_ALL
  210702. #define log(a)
  210703. #define logError(a)
  210704. #endif
  210705. #define DSOUND_FUNCTION(functionName, params) \
  210706. typedef HRESULT (WINAPI *type##functionName) params; \
  210707. static type##functionName ds##functionName = 0;
  210708. #define DSOUND_FUNCTION_LOAD(functionName) \
  210709. ds##functionName = (type##functionName) GetProcAddress (h, #functionName); \
  210710. jassert (ds##functionName != 0);
  210711. typedef BOOL (CALLBACK *LPDSENUMCALLBACKW) (LPGUID, LPCWSTR, LPCWSTR, LPVOID);
  210712. typedef BOOL (CALLBACK *LPDSENUMCALLBACKA) (LPGUID, LPCSTR, LPCSTR, LPVOID);
  210713. DSOUND_FUNCTION (DirectSoundCreate, (const GUID*, IDirectSound**, LPUNKNOWN))
  210714. DSOUND_FUNCTION (DirectSoundCaptureCreate, (const GUID*, IDirectSoundCapture**, LPUNKNOWN))
  210715. DSOUND_FUNCTION (DirectSoundEnumerateW, (LPDSENUMCALLBACKW, LPVOID))
  210716. DSOUND_FUNCTION (DirectSoundCaptureEnumerateW, (LPDSENUMCALLBACKW, LPVOID))
  210717. static void initialiseDSoundFunctions()
  210718. {
  210719. if (dsDirectSoundCreate == 0)
  210720. {
  210721. HMODULE h = LoadLibraryA ("dsound.dll");
  210722. DSOUND_FUNCTION_LOAD (DirectSoundCreate)
  210723. DSOUND_FUNCTION_LOAD (DirectSoundCaptureCreate)
  210724. DSOUND_FUNCTION_LOAD (DirectSoundEnumerateW)
  210725. DSOUND_FUNCTION_LOAD (DirectSoundCaptureEnumerateW)
  210726. }
  210727. }
  210728. class DSoundInternalOutChannel
  210729. {
  210730. String name;
  210731. LPGUID guid;
  210732. int sampleRate, bufferSizeSamples;
  210733. float* leftBuffer;
  210734. float* rightBuffer;
  210735. IDirectSound* pDirectSound;
  210736. IDirectSoundBuffer* pOutputBuffer;
  210737. DWORD writeOffset;
  210738. int totalBytesPerBuffer;
  210739. int bytesPerBuffer;
  210740. unsigned int lastPlayCursor;
  210741. public:
  210742. int bitDepth;
  210743. bool doneFlag;
  210744. DSoundInternalOutChannel (const String& name_,
  210745. LPGUID guid_,
  210746. int rate,
  210747. int bufferSize,
  210748. float* left,
  210749. float* right)
  210750. : name (name_),
  210751. guid (guid_),
  210752. sampleRate (rate),
  210753. bufferSizeSamples (bufferSize),
  210754. leftBuffer (left),
  210755. rightBuffer (right),
  210756. pDirectSound (0),
  210757. pOutputBuffer (0),
  210758. bitDepth (16)
  210759. {
  210760. }
  210761. ~DSoundInternalOutChannel()
  210762. {
  210763. close();
  210764. }
  210765. void close()
  210766. {
  210767. HRESULT hr;
  210768. if (pOutputBuffer != 0)
  210769. {
  210770. JUCE_TRY
  210771. {
  210772. log ("closing dsound out: " + name);
  210773. hr = pOutputBuffer->Stop();
  210774. logError (hr);
  210775. }
  210776. CATCH
  210777. JUCE_TRY
  210778. {
  210779. hr = pOutputBuffer->Release();
  210780. logError (hr);
  210781. }
  210782. CATCH
  210783. pOutputBuffer = 0;
  210784. }
  210785. if (pDirectSound != 0)
  210786. {
  210787. JUCE_TRY
  210788. {
  210789. hr = pDirectSound->Release();
  210790. logError (hr);
  210791. }
  210792. CATCH
  210793. pDirectSound = 0;
  210794. }
  210795. }
  210796. const String open()
  210797. {
  210798. log ("opening dsound out device: " + name + " rate=" + String (sampleRate)
  210799. + " bits=" + String (bitDepth) + " buf=" + String (bufferSizeSamples));
  210800. pDirectSound = 0;
  210801. pOutputBuffer = 0;
  210802. writeOffset = 0;
  210803. String error;
  210804. HRESULT hr = E_NOINTERFACE;
  210805. if (dsDirectSoundCreate != 0)
  210806. hr = dsDirectSoundCreate (guid, &pDirectSound, 0);
  210807. if (hr == S_OK)
  210808. {
  210809. bytesPerBuffer = (bufferSizeSamples * (bitDepth >> 2)) & ~15;
  210810. totalBytesPerBuffer = (3 * bytesPerBuffer) & ~15;
  210811. const int numChannels = 2;
  210812. hr = pDirectSound->SetCooperativeLevel (GetDesktopWindow(), 2 /* DSSCL_PRIORITY */);
  210813. logError (hr);
  210814. if (hr == S_OK)
  210815. {
  210816. IDirectSoundBuffer* pPrimaryBuffer;
  210817. DSBUFFERDESC primaryDesc;
  210818. zerostruct (primaryDesc);
  210819. primaryDesc.dwSize = sizeof (DSBUFFERDESC);
  210820. primaryDesc.dwFlags = 1 /* DSBCAPS_PRIMARYBUFFER */;
  210821. primaryDesc.dwBufferBytes = 0;
  210822. primaryDesc.lpwfxFormat = 0;
  210823. log ("opening dsound out step 2");
  210824. hr = pDirectSound->CreateSoundBuffer (&primaryDesc, &pPrimaryBuffer, 0);
  210825. logError (hr);
  210826. if (hr == S_OK)
  210827. {
  210828. WAVEFORMATEX wfFormat;
  210829. wfFormat.wFormatTag = WAVE_FORMAT_PCM;
  210830. wfFormat.nChannels = (unsigned short) numChannels;
  210831. wfFormat.nSamplesPerSec = sampleRate;
  210832. wfFormat.wBitsPerSample = (unsigned short) bitDepth;
  210833. wfFormat.nBlockAlign = (unsigned short) (wfFormat.nChannels * wfFormat.wBitsPerSample / 8);
  210834. wfFormat.nAvgBytesPerSec = wfFormat.nSamplesPerSec * wfFormat.nBlockAlign;
  210835. wfFormat.cbSize = 0;
  210836. hr = pPrimaryBuffer->SetFormat (&wfFormat);
  210837. logError (hr);
  210838. if (hr == S_OK)
  210839. {
  210840. DSBUFFERDESC secondaryDesc;
  210841. zerostruct (secondaryDesc);
  210842. secondaryDesc.dwSize = sizeof (DSBUFFERDESC);
  210843. secondaryDesc.dwFlags = 0x8000 /* DSBCAPS_GLOBALFOCUS */
  210844. | 0x10000 /* DSBCAPS_GETCURRENTPOSITION2 */;
  210845. secondaryDesc.dwBufferBytes = totalBytesPerBuffer;
  210846. secondaryDesc.lpwfxFormat = &wfFormat;
  210847. hr = pDirectSound->CreateSoundBuffer (&secondaryDesc, &pOutputBuffer, 0);
  210848. logError (hr);
  210849. if (hr == S_OK)
  210850. {
  210851. log ("opening dsound out step 3");
  210852. DWORD dwDataLen;
  210853. unsigned char* pDSBuffData;
  210854. hr = pOutputBuffer->Lock (0, totalBytesPerBuffer,
  210855. (LPVOID*) &pDSBuffData, &dwDataLen, 0, 0, 0);
  210856. logError (hr);
  210857. if (hr == S_OK)
  210858. {
  210859. zeromem (pDSBuffData, dwDataLen);
  210860. hr = pOutputBuffer->Unlock (pDSBuffData, dwDataLen, 0, 0);
  210861. if (hr == S_OK)
  210862. {
  210863. hr = pOutputBuffer->SetCurrentPosition (0);
  210864. if (hr == S_OK)
  210865. {
  210866. hr = pOutputBuffer->Play (0, 0, 1 /* DSBPLAY_LOOPING */);
  210867. if (hr == S_OK)
  210868. return String::empty;
  210869. }
  210870. }
  210871. }
  210872. }
  210873. }
  210874. }
  210875. }
  210876. }
  210877. error = getDSErrorMessage (hr);
  210878. close();
  210879. return error;
  210880. }
  210881. void synchronisePosition()
  210882. {
  210883. if (pOutputBuffer != 0)
  210884. {
  210885. DWORD playCursor;
  210886. pOutputBuffer->GetCurrentPosition (&playCursor, &writeOffset);
  210887. }
  210888. }
  210889. bool service()
  210890. {
  210891. if (pOutputBuffer == 0)
  210892. return true;
  210893. DWORD playCursor, writeCursor;
  210894. for (;;)
  210895. {
  210896. HRESULT hr = pOutputBuffer->GetCurrentPosition (&playCursor, &writeCursor);
  210897. if (hr == MAKE_HRESULT (1, 0x878, 150)) // DSERR_BUFFERLOST
  210898. {
  210899. pOutputBuffer->Restore();
  210900. continue;
  210901. }
  210902. if (hr == S_OK)
  210903. break;
  210904. logError (hr);
  210905. jassertfalse
  210906. return true;
  210907. }
  210908. int playWriteGap = writeCursor - playCursor;
  210909. if (playWriteGap < 0)
  210910. playWriteGap += totalBytesPerBuffer;
  210911. int bytesEmpty = playCursor - writeOffset;
  210912. if (bytesEmpty < 0)
  210913. bytesEmpty += totalBytesPerBuffer;
  210914. if (bytesEmpty > (totalBytesPerBuffer - playWriteGap))
  210915. {
  210916. writeOffset = writeCursor;
  210917. bytesEmpty = totalBytesPerBuffer - playWriteGap;
  210918. }
  210919. if (bytesEmpty >= bytesPerBuffer)
  210920. {
  210921. LPBYTE lpbuf1 = 0;
  210922. LPBYTE lpbuf2 = 0;
  210923. DWORD dwSize1 = 0;
  210924. DWORD dwSize2 = 0;
  210925. HRESULT hr = pOutputBuffer->Lock (writeOffset,
  210926. bytesPerBuffer,
  210927. (void**) &lpbuf1, &dwSize1,
  210928. (void**) &lpbuf2, &dwSize2, 0);
  210929. if (hr == MAKE_HRESULT (1, 0x878, 150)) // DSERR_BUFFERLOST
  210930. {
  210931. pOutputBuffer->Restore();
  210932. hr = pOutputBuffer->Lock (writeOffset,
  210933. bytesPerBuffer,
  210934. (void**) &lpbuf1, &dwSize1,
  210935. (void**) &lpbuf2, &dwSize2, 0);
  210936. }
  210937. if (hr == S_OK)
  210938. {
  210939. if (bitDepth == 16)
  210940. {
  210941. const float gainL = 32767.0f;
  210942. const float gainR = 32767.0f;
  210943. int* dest = (int*)lpbuf1;
  210944. const float* left = leftBuffer;
  210945. const float* right = rightBuffer;
  210946. int samples1 = dwSize1 >> 2;
  210947. int samples2 = dwSize2 >> 2;
  210948. if (left == 0)
  210949. {
  210950. while (--samples1 >= 0)
  210951. {
  210952. int r = roundToInt (gainR * *right++);
  210953. if (r < -32768)
  210954. r = -32768;
  210955. else if (r > 32767)
  210956. r = 32767;
  210957. *dest++ = (r << 16);
  210958. }
  210959. dest = (int*)lpbuf2;
  210960. while (--samples2 >= 0)
  210961. {
  210962. int r = roundToInt (gainR * *right++);
  210963. if (r < -32768)
  210964. r = -32768;
  210965. else if (r > 32767)
  210966. r = 32767;
  210967. *dest++ = (r << 16);
  210968. }
  210969. }
  210970. else if (right == 0)
  210971. {
  210972. while (--samples1 >= 0)
  210973. {
  210974. int l = roundToInt (gainL * *left++);
  210975. if (l < -32768)
  210976. l = -32768;
  210977. else if (l > 32767)
  210978. l = 32767;
  210979. l &= 0xffff;
  210980. *dest++ = l;
  210981. }
  210982. dest = (int*)lpbuf2;
  210983. while (--samples2 >= 0)
  210984. {
  210985. int l = roundToInt (gainL * *left++);
  210986. if (l < -32768)
  210987. l = -32768;
  210988. else if (l > 32767)
  210989. l = 32767;
  210990. l &= 0xffff;
  210991. *dest++ = l;
  210992. }
  210993. }
  210994. else
  210995. {
  210996. while (--samples1 >= 0)
  210997. {
  210998. int l = roundToInt (gainL * *left++);
  210999. if (l < -32768)
  211000. l = -32768;
  211001. else if (l > 32767)
  211002. l = 32767;
  211003. l &= 0xffff;
  211004. int r = roundToInt (gainR * *right++);
  211005. if (r < -32768)
  211006. r = -32768;
  211007. else if (r > 32767)
  211008. r = 32767;
  211009. *dest++ = (r << 16) | l;
  211010. }
  211011. dest = (int*)lpbuf2;
  211012. while (--samples2 >= 0)
  211013. {
  211014. int l = roundToInt (gainL * *left++);
  211015. if (l < -32768)
  211016. l = -32768;
  211017. else if (l > 32767)
  211018. l = 32767;
  211019. l &= 0xffff;
  211020. int r = roundToInt (gainR * *right++);
  211021. if (r < -32768)
  211022. r = -32768;
  211023. else if (r > 32767)
  211024. r = 32767;
  211025. *dest++ = (r << 16) | l;
  211026. }
  211027. }
  211028. }
  211029. else
  211030. {
  211031. jassertfalse
  211032. }
  211033. writeOffset = (writeOffset + dwSize1 + dwSize2) % totalBytesPerBuffer;
  211034. pOutputBuffer->Unlock (lpbuf1, dwSize1, lpbuf2, dwSize2);
  211035. }
  211036. else
  211037. {
  211038. jassertfalse
  211039. logError (hr);
  211040. }
  211041. bytesEmpty -= bytesPerBuffer;
  211042. return true;
  211043. }
  211044. else
  211045. {
  211046. return false;
  211047. }
  211048. }
  211049. };
  211050. struct DSoundInternalInChannel
  211051. {
  211052. String name;
  211053. LPGUID guid;
  211054. int sampleRate, bufferSizeSamples;
  211055. float* leftBuffer;
  211056. float* rightBuffer;
  211057. IDirectSound* pDirectSound;
  211058. IDirectSoundCapture* pDirectSoundCapture;
  211059. IDirectSoundCaptureBuffer* pInputBuffer;
  211060. public:
  211061. unsigned int readOffset;
  211062. int bytesPerBuffer, totalBytesPerBuffer;
  211063. int bitDepth;
  211064. bool doneFlag;
  211065. DSoundInternalInChannel (const String& name_,
  211066. LPGUID guid_,
  211067. int rate,
  211068. int bufferSize,
  211069. float* left,
  211070. float* right)
  211071. : name (name_),
  211072. guid (guid_),
  211073. sampleRate (rate),
  211074. bufferSizeSamples (bufferSize),
  211075. leftBuffer (left),
  211076. rightBuffer (right),
  211077. pDirectSound (0),
  211078. pDirectSoundCapture (0),
  211079. pInputBuffer (0),
  211080. bitDepth (16)
  211081. {
  211082. }
  211083. ~DSoundInternalInChannel()
  211084. {
  211085. close();
  211086. }
  211087. void close()
  211088. {
  211089. HRESULT hr;
  211090. if (pInputBuffer != 0)
  211091. {
  211092. JUCE_TRY
  211093. {
  211094. log ("closing dsound in: " + name);
  211095. hr = pInputBuffer->Stop();
  211096. logError (hr);
  211097. }
  211098. CATCH
  211099. JUCE_TRY
  211100. {
  211101. hr = pInputBuffer->Release();
  211102. logError (hr);
  211103. }
  211104. CATCH
  211105. pInputBuffer = 0;
  211106. }
  211107. if (pDirectSoundCapture != 0)
  211108. {
  211109. JUCE_TRY
  211110. {
  211111. hr = pDirectSoundCapture->Release();
  211112. logError (hr);
  211113. }
  211114. CATCH
  211115. pDirectSoundCapture = 0;
  211116. }
  211117. if (pDirectSound != 0)
  211118. {
  211119. JUCE_TRY
  211120. {
  211121. hr = pDirectSound->Release();
  211122. logError (hr);
  211123. }
  211124. CATCH
  211125. pDirectSound = 0;
  211126. }
  211127. }
  211128. const String open()
  211129. {
  211130. log ("opening dsound in device: " + name
  211131. + " rate=" + String (sampleRate) + " bits=" + String (bitDepth) + " buf=" + String (bufferSizeSamples));
  211132. pDirectSound = 0;
  211133. pDirectSoundCapture = 0;
  211134. pInputBuffer = 0;
  211135. readOffset = 0;
  211136. totalBytesPerBuffer = 0;
  211137. String error;
  211138. HRESULT hr = E_NOINTERFACE;
  211139. if (dsDirectSoundCaptureCreate != 0)
  211140. hr = dsDirectSoundCaptureCreate (guid, &pDirectSoundCapture, 0);
  211141. logError (hr);
  211142. if (hr == S_OK)
  211143. {
  211144. const int numChannels = 2;
  211145. bytesPerBuffer = (bufferSizeSamples * (bitDepth >> 2)) & ~15;
  211146. totalBytesPerBuffer = (3 * bytesPerBuffer) & ~15;
  211147. WAVEFORMATEX wfFormat;
  211148. wfFormat.wFormatTag = WAVE_FORMAT_PCM;
  211149. wfFormat.nChannels = (unsigned short)numChannels;
  211150. wfFormat.nSamplesPerSec = sampleRate;
  211151. wfFormat.wBitsPerSample = (unsigned short)bitDepth;
  211152. wfFormat.nBlockAlign = (unsigned short)(wfFormat.nChannels * (wfFormat.wBitsPerSample / 8));
  211153. wfFormat.nAvgBytesPerSec = wfFormat.nSamplesPerSec * wfFormat.nBlockAlign;
  211154. wfFormat.cbSize = 0;
  211155. DSCBUFFERDESC captureDesc;
  211156. zerostruct (captureDesc);
  211157. captureDesc.dwSize = sizeof (DSCBUFFERDESC);
  211158. captureDesc.dwFlags = 0;
  211159. captureDesc.dwBufferBytes = totalBytesPerBuffer;
  211160. captureDesc.lpwfxFormat = &wfFormat;
  211161. log ("opening dsound in step 2");
  211162. hr = pDirectSoundCapture->CreateCaptureBuffer (&captureDesc, &pInputBuffer, 0);
  211163. logError (hr);
  211164. if (hr == S_OK)
  211165. {
  211166. hr = pInputBuffer->Start (1 /* DSCBSTART_LOOPING */);
  211167. logError (hr);
  211168. if (hr == S_OK)
  211169. return String::empty;
  211170. }
  211171. }
  211172. error = getDSErrorMessage (hr);
  211173. close();
  211174. return error;
  211175. }
  211176. void synchronisePosition()
  211177. {
  211178. if (pInputBuffer != 0)
  211179. {
  211180. DWORD capturePos;
  211181. pInputBuffer->GetCurrentPosition (&capturePos, (DWORD*)&readOffset);
  211182. }
  211183. }
  211184. bool service()
  211185. {
  211186. if (pInputBuffer == 0)
  211187. return true;
  211188. DWORD capturePos, readPos;
  211189. HRESULT hr = pInputBuffer->GetCurrentPosition (&capturePos, &readPos);
  211190. logError (hr);
  211191. if (hr != S_OK)
  211192. return true;
  211193. int bytesFilled = readPos - readOffset;
  211194. if (bytesFilled < 0)
  211195. bytesFilled += totalBytesPerBuffer;
  211196. if (bytesFilled >= bytesPerBuffer)
  211197. {
  211198. LPBYTE lpbuf1 = 0;
  211199. LPBYTE lpbuf2 = 0;
  211200. DWORD dwsize1 = 0;
  211201. DWORD dwsize2 = 0;
  211202. HRESULT hr = pInputBuffer->Lock (readOffset,
  211203. bytesPerBuffer,
  211204. (void**) &lpbuf1, &dwsize1,
  211205. (void**) &lpbuf2, &dwsize2, 0);
  211206. if (hr == S_OK)
  211207. {
  211208. if (bitDepth == 16)
  211209. {
  211210. const float g = 1.0f / 32768.0f;
  211211. float* destL = leftBuffer;
  211212. float* destR = rightBuffer;
  211213. int samples1 = dwsize1 >> 2;
  211214. int samples2 = dwsize2 >> 2;
  211215. const short* src = (const short*)lpbuf1;
  211216. if (destL == 0)
  211217. {
  211218. while (--samples1 >= 0)
  211219. {
  211220. ++src;
  211221. *destR++ = *src++ * g;
  211222. }
  211223. src = (const short*)lpbuf2;
  211224. while (--samples2 >= 0)
  211225. {
  211226. ++src;
  211227. *destR++ = *src++ * g;
  211228. }
  211229. }
  211230. else if (destR == 0)
  211231. {
  211232. while (--samples1 >= 0)
  211233. {
  211234. *destL++ = *src++ * g;
  211235. ++src;
  211236. }
  211237. src = (const short*)lpbuf2;
  211238. while (--samples2 >= 0)
  211239. {
  211240. *destL++ = *src++ * g;
  211241. ++src;
  211242. }
  211243. }
  211244. else
  211245. {
  211246. while (--samples1 >= 0)
  211247. {
  211248. *destL++ = *src++ * g;
  211249. *destR++ = *src++ * g;
  211250. }
  211251. src = (const short*)lpbuf2;
  211252. while (--samples2 >= 0)
  211253. {
  211254. *destL++ = *src++ * g;
  211255. *destR++ = *src++ * g;
  211256. }
  211257. }
  211258. }
  211259. else
  211260. {
  211261. jassertfalse
  211262. }
  211263. readOffset = (readOffset + dwsize1 + dwsize2) % totalBytesPerBuffer;
  211264. pInputBuffer->Unlock (lpbuf1, dwsize1, lpbuf2, dwsize2);
  211265. }
  211266. else
  211267. {
  211268. logError (hr);
  211269. jassertfalse
  211270. }
  211271. bytesFilled -= bytesPerBuffer;
  211272. return true;
  211273. }
  211274. else
  211275. {
  211276. return false;
  211277. }
  211278. }
  211279. };
  211280. class DSoundAudioIODevice : public AudioIODevice,
  211281. public Thread
  211282. {
  211283. public:
  211284. DSoundAudioIODevice (const String& deviceName,
  211285. const int outputDeviceIndex_,
  211286. const int inputDeviceIndex_)
  211287. : AudioIODevice (deviceName, "DirectSound"),
  211288. Thread ("Juce DSound"),
  211289. isOpen_ (false),
  211290. isStarted (false),
  211291. outputDeviceIndex (outputDeviceIndex_),
  211292. inputDeviceIndex (inputDeviceIndex_),
  211293. totalSamplesOut (0),
  211294. sampleRate (0.0),
  211295. inputBuffers (1, 1),
  211296. outputBuffers (1, 1),
  211297. callback (0),
  211298. bufferSizeSamples (0)
  211299. {
  211300. if (outputDeviceIndex_ >= 0)
  211301. {
  211302. outChannels.add (TRANS("Left"));
  211303. outChannels.add (TRANS("Right"));
  211304. }
  211305. if (inputDeviceIndex_ >= 0)
  211306. {
  211307. inChannels.add (TRANS("Left"));
  211308. inChannels.add (TRANS("Right"));
  211309. }
  211310. }
  211311. ~DSoundAudioIODevice()
  211312. {
  211313. close();
  211314. }
  211315. const StringArray getOutputChannelNames()
  211316. {
  211317. return outChannels;
  211318. }
  211319. const StringArray getInputChannelNames()
  211320. {
  211321. return inChannels;
  211322. }
  211323. int getNumSampleRates()
  211324. {
  211325. return 4;
  211326. }
  211327. double getSampleRate (int index)
  211328. {
  211329. const double samps[] = { 44100.0, 48000.0, 88200.0, 96000.0 };
  211330. return samps [jlimit (0, 3, index)];
  211331. }
  211332. int getNumBufferSizesAvailable()
  211333. {
  211334. return 50;
  211335. }
  211336. int getBufferSizeSamples (int index)
  211337. {
  211338. int n = 64;
  211339. for (int i = 0; i < index; ++i)
  211340. n += (n < 512) ? 32
  211341. : ((n < 1024) ? 64
  211342. : ((n < 2048) ? 128 : 256));
  211343. return n;
  211344. }
  211345. int getDefaultBufferSize()
  211346. {
  211347. return 2560;
  211348. }
  211349. const String open (const BigInteger& inputChannels,
  211350. const BigInteger& outputChannels,
  211351. double sampleRate,
  211352. int bufferSizeSamples)
  211353. {
  211354. lastError = openDevice (inputChannels, outputChannels, sampleRate, bufferSizeSamples);
  211355. isOpen_ = lastError.isEmpty();
  211356. return lastError;
  211357. }
  211358. void close()
  211359. {
  211360. stop();
  211361. if (isOpen_)
  211362. {
  211363. closeDevice();
  211364. isOpen_ = false;
  211365. }
  211366. }
  211367. bool isOpen()
  211368. {
  211369. return isOpen_ && isThreadRunning();
  211370. }
  211371. int getCurrentBufferSizeSamples()
  211372. {
  211373. return bufferSizeSamples;
  211374. }
  211375. double getCurrentSampleRate()
  211376. {
  211377. return sampleRate;
  211378. }
  211379. int getCurrentBitDepth()
  211380. {
  211381. int i, bits = 256;
  211382. for (i = inChans.size(); --i >= 0;)
  211383. bits = jmin (bits, inChans[i]->bitDepth);
  211384. for (i = outChans.size(); --i >= 0;)
  211385. bits = jmin (bits, outChans[i]->bitDepth);
  211386. if (bits > 32)
  211387. bits = 16;
  211388. return bits;
  211389. }
  211390. const BigInteger getActiveOutputChannels() const
  211391. {
  211392. return enabledOutputs;
  211393. }
  211394. const BigInteger getActiveInputChannels() const
  211395. {
  211396. return enabledInputs;
  211397. }
  211398. int getOutputLatencyInSamples()
  211399. {
  211400. return (int) (getCurrentBufferSizeSamples() * 1.5);
  211401. }
  211402. int getInputLatencyInSamples()
  211403. {
  211404. return getOutputLatencyInSamples();
  211405. }
  211406. void start (AudioIODeviceCallback* call)
  211407. {
  211408. if (isOpen_ && call != 0 && ! isStarted)
  211409. {
  211410. if (! isThreadRunning())
  211411. {
  211412. // something gone wrong and the thread's stopped..
  211413. isOpen_ = false;
  211414. return;
  211415. }
  211416. call->audioDeviceAboutToStart (this);
  211417. const ScopedLock sl (startStopLock);
  211418. callback = call;
  211419. isStarted = true;
  211420. }
  211421. }
  211422. void stop()
  211423. {
  211424. if (isStarted)
  211425. {
  211426. AudioIODeviceCallback* const callbackLocal = callback;
  211427. {
  211428. const ScopedLock sl (startStopLock);
  211429. isStarted = false;
  211430. }
  211431. if (callbackLocal != 0)
  211432. callbackLocal->audioDeviceStopped();
  211433. }
  211434. }
  211435. bool isPlaying()
  211436. {
  211437. return isStarted && isOpen_ && isThreadRunning();
  211438. }
  211439. const String getLastError()
  211440. {
  211441. return lastError;
  211442. }
  211443. juce_UseDebuggingNewOperator
  211444. StringArray inChannels, outChannels;
  211445. int outputDeviceIndex, inputDeviceIndex;
  211446. private:
  211447. bool isOpen_;
  211448. bool isStarted;
  211449. String lastError;
  211450. OwnedArray <DSoundInternalInChannel> inChans;
  211451. OwnedArray <DSoundInternalOutChannel> outChans;
  211452. WaitableEvent startEvent;
  211453. int bufferSizeSamples;
  211454. int volatile totalSamplesOut;
  211455. int64 volatile lastBlockTime;
  211456. double sampleRate;
  211457. BigInteger enabledInputs, enabledOutputs;
  211458. AudioSampleBuffer inputBuffers, outputBuffers;
  211459. AudioIODeviceCallback* callback;
  211460. CriticalSection startStopLock;
  211461. DSoundAudioIODevice (const DSoundAudioIODevice&);
  211462. DSoundAudioIODevice& operator= (const DSoundAudioIODevice&);
  211463. const String openDevice (const BigInteger& inputChannels,
  211464. const BigInteger& outputChannels,
  211465. double sampleRate_,
  211466. int bufferSizeSamples_);
  211467. void closeDevice()
  211468. {
  211469. isStarted = false;
  211470. stopThread (5000);
  211471. inChans.clear();
  211472. outChans.clear();
  211473. inputBuffers.setSize (1, 1);
  211474. outputBuffers.setSize (1, 1);
  211475. }
  211476. void resync()
  211477. {
  211478. if (! threadShouldExit())
  211479. {
  211480. sleep (5);
  211481. int i;
  211482. for (i = 0; i < outChans.size(); ++i)
  211483. outChans.getUnchecked(i)->synchronisePosition();
  211484. for (i = 0; i < inChans.size(); ++i)
  211485. inChans.getUnchecked(i)->synchronisePosition();
  211486. }
  211487. }
  211488. public:
  211489. void run()
  211490. {
  211491. while (! threadShouldExit())
  211492. {
  211493. if (wait (100))
  211494. break;
  211495. }
  211496. const int latencyMs = (int) (bufferSizeSamples * 1000.0 / sampleRate);
  211497. const int maxTimeMS = jmax (5, 3 * latencyMs);
  211498. while (! threadShouldExit())
  211499. {
  211500. int numToDo = 0;
  211501. uint32 startTime = Time::getMillisecondCounter();
  211502. int i;
  211503. for (i = inChans.size(); --i >= 0;)
  211504. {
  211505. inChans.getUnchecked(i)->doneFlag = false;
  211506. ++numToDo;
  211507. }
  211508. for (i = outChans.size(); --i >= 0;)
  211509. {
  211510. outChans.getUnchecked(i)->doneFlag = false;
  211511. ++numToDo;
  211512. }
  211513. if (numToDo > 0)
  211514. {
  211515. const int maxCount = 3;
  211516. int count = maxCount;
  211517. for (;;)
  211518. {
  211519. for (i = inChans.size(); --i >= 0;)
  211520. {
  211521. DSoundInternalInChannel* const in = inChans.getUnchecked(i);
  211522. if ((! in->doneFlag) && in->service())
  211523. {
  211524. in->doneFlag = true;
  211525. --numToDo;
  211526. }
  211527. }
  211528. for (i = outChans.size(); --i >= 0;)
  211529. {
  211530. DSoundInternalOutChannel* const out = outChans.getUnchecked(i);
  211531. if ((! out->doneFlag) && out->service())
  211532. {
  211533. out->doneFlag = true;
  211534. --numToDo;
  211535. }
  211536. }
  211537. if (numToDo <= 0)
  211538. break;
  211539. if (Time::getMillisecondCounter() > startTime + maxTimeMS)
  211540. {
  211541. resync();
  211542. break;
  211543. }
  211544. if (--count <= 0)
  211545. {
  211546. Sleep (1);
  211547. count = maxCount;
  211548. }
  211549. if (threadShouldExit())
  211550. return;
  211551. }
  211552. }
  211553. else
  211554. {
  211555. sleep (1);
  211556. }
  211557. const ScopedLock sl (startStopLock);
  211558. if (isStarted)
  211559. {
  211560. JUCE_TRY
  211561. {
  211562. callback->audioDeviceIOCallback (const_cast <const float**> (inputBuffers.getArrayOfChannels()),
  211563. inputBuffers.getNumChannels(),
  211564. outputBuffers.getArrayOfChannels(),
  211565. outputBuffers.getNumChannels(),
  211566. bufferSizeSamples);
  211567. }
  211568. JUCE_CATCH_EXCEPTION
  211569. totalSamplesOut += bufferSizeSamples;
  211570. }
  211571. else
  211572. {
  211573. outputBuffers.clear();
  211574. totalSamplesOut = 0;
  211575. sleep (1);
  211576. }
  211577. }
  211578. }
  211579. };
  211580. class DSoundAudioIODeviceType : public AudioIODeviceType
  211581. {
  211582. public:
  211583. DSoundAudioIODeviceType()
  211584. : AudioIODeviceType ("DirectSound"),
  211585. hasScanned (false)
  211586. {
  211587. initialiseDSoundFunctions();
  211588. }
  211589. ~DSoundAudioIODeviceType()
  211590. {
  211591. }
  211592. void scanForDevices()
  211593. {
  211594. hasScanned = true;
  211595. outputDeviceNames.clear();
  211596. outputGuids.clear();
  211597. inputDeviceNames.clear();
  211598. inputGuids.clear();
  211599. if (dsDirectSoundEnumerateW != 0)
  211600. {
  211601. dsDirectSoundEnumerateW (outputEnumProcW, this);
  211602. dsDirectSoundCaptureEnumerateW (inputEnumProcW, this);
  211603. }
  211604. }
  211605. const StringArray getDeviceNames (bool wantInputNames) const
  211606. {
  211607. jassert (hasScanned); // need to call scanForDevices() before doing this
  211608. return wantInputNames ? inputDeviceNames
  211609. : outputDeviceNames;
  211610. }
  211611. int getDefaultDeviceIndex (bool /*forInput*/) const
  211612. {
  211613. jassert (hasScanned); // need to call scanForDevices() before doing this
  211614. return 0;
  211615. }
  211616. int getIndexOfDevice (AudioIODevice* device, bool asInput) const
  211617. {
  211618. jassert (hasScanned); // need to call scanForDevices() before doing this
  211619. DSoundAudioIODevice* const d = dynamic_cast <DSoundAudioIODevice*> (device);
  211620. if (d == 0)
  211621. return -1;
  211622. return asInput ? d->inputDeviceIndex
  211623. : d->outputDeviceIndex;
  211624. }
  211625. bool hasSeparateInputsAndOutputs() const { return true; }
  211626. AudioIODevice* createDevice (const String& outputDeviceName,
  211627. const String& inputDeviceName)
  211628. {
  211629. jassert (hasScanned); // need to call scanForDevices() before doing this
  211630. const int outputIndex = outputDeviceNames.indexOf (outputDeviceName);
  211631. const int inputIndex = inputDeviceNames.indexOf (inputDeviceName);
  211632. if (outputIndex >= 0 || inputIndex >= 0)
  211633. return new DSoundAudioIODevice (outputDeviceName.isNotEmpty() ? outputDeviceName
  211634. : inputDeviceName,
  211635. outputIndex, inputIndex);
  211636. return 0;
  211637. }
  211638. juce_UseDebuggingNewOperator
  211639. StringArray outputDeviceNames;
  211640. OwnedArray <GUID> outputGuids;
  211641. StringArray inputDeviceNames;
  211642. OwnedArray <GUID> inputGuids;
  211643. private:
  211644. bool hasScanned;
  211645. BOOL outputEnumProc (LPGUID lpGUID, String desc)
  211646. {
  211647. desc = desc.trim();
  211648. if (desc.isNotEmpty())
  211649. {
  211650. const String origDesc (desc);
  211651. int n = 2;
  211652. while (outputDeviceNames.contains (desc))
  211653. desc = origDesc + " (" + String (n++) + ")";
  211654. outputDeviceNames.add (desc);
  211655. if (lpGUID != 0)
  211656. outputGuids.add (new GUID (*lpGUID));
  211657. else
  211658. outputGuids.add (0);
  211659. }
  211660. return TRUE;
  211661. }
  211662. static BOOL CALLBACK outputEnumProcW (LPGUID lpGUID, LPCWSTR description, LPCWSTR, LPVOID object)
  211663. {
  211664. return ((DSoundAudioIODeviceType*) object)
  211665. ->outputEnumProc (lpGUID, String (description));
  211666. }
  211667. static BOOL CALLBACK outputEnumProcA (LPGUID lpGUID, LPCTSTR description, LPCTSTR, LPVOID object)
  211668. {
  211669. return ((DSoundAudioIODeviceType*) object)
  211670. ->outputEnumProc (lpGUID, String (description));
  211671. }
  211672. BOOL CALLBACK inputEnumProc (LPGUID lpGUID, String desc)
  211673. {
  211674. desc = desc.trim();
  211675. if (desc.isNotEmpty())
  211676. {
  211677. const String origDesc (desc);
  211678. int n = 2;
  211679. while (inputDeviceNames.contains (desc))
  211680. desc = origDesc + " (" + String (n++) + ")";
  211681. inputDeviceNames.add (desc);
  211682. if (lpGUID != 0)
  211683. inputGuids.add (new GUID (*lpGUID));
  211684. else
  211685. inputGuids.add (0);
  211686. }
  211687. return TRUE;
  211688. }
  211689. static BOOL CALLBACK inputEnumProcW (LPGUID lpGUID, LPCWSTR description, LPCWSTR, LPVOID object)
  211690. {
  211691. return ((DSoundAudioIODeviceType*) object)
  211692. ->inputEnumProc (lpGUID, String (description));
  211693. }
  211694. static BOOL CALLBACK inputEnumProcA (LPGUID lpGUID, LPCTSTR description, LPCTSTR, LPVOID object)
  211695. {
  211696. return ((DSoundAudioIODeviceType*) object)
  211697. ->inputEnumProc (lpGUID, String (description));
  211698. }
  211699. DSoundAudioIODeviceType (const DSoundAudioIODeviceType&);
  211700. DSoundAudioIODeviceType& operator= (const DSoundAudioIODeviceType&);
  211701. };
  211702. const String DSoundAudioIODevice::openDevice (const BigInteger& inputChannels,
  211703. const BigInteger& outputChannels,
  211704. double sampleRate_,
  211705. int bufferSizeSamples_)
  211706. {
  211707. closeDevice();
  211708. totalSamplesOut = 0;
  211709. sampleRate = sampleRate_;
  211710. if (bufferSizeSamples_ <= 0)
  211711. bufferSizeSamples_ = 960; // use as a default size if none is set.
  211712. bufferSizeSamples = bufferSizeSamples_ & ~7;
  211713. DSoundAudioIODeviceType dlh;
  211714. dlh.scanForDevices();
  211715. enabledInputs = inputChannels;
  211716. enabledInputs.setRange (inChannels.size(),
  211717. enabledInputs.getHighestBit() + 1 - inChannels.size(),
  211718. false);
  211719. inputBuffers.setSize (enabledInputs.countNumberOfSetBits(), bufferSizeSamples);
  211720. int i, numIns = 0;
  211721. for (i = 0; i <= enabledInputs.getHighestBit(); i += 2)
  211722. {
  211723. float* left = 0;
  211724. if (enabledInputs[i])
  211725. left = inputBuffers.getSampleData (numIns++);
  211726. float* right = 0;
  211727. if (enabledInputs[i + 1])
  211728. right = inputBuffers.getSampleData (numIns++);
  211729. if (left != 0 || right != 0)
  211730. inChans.add (new DSoundInternalInChannel (dlh.inputDeviceNames [inputDeviceIndex],
  211731. dlh.inputGuids [inputDeviceIndex],
  211732. (int) sampleRate, bufferSizeSamples,
  211733. left, right));
  211734. }
  211735. enabledOutputs = outputChannels;
  211736. enabledOutputs.setRange (outChannels.size(),
  211737. enabledOutputs.getHighestBit() + 1 - outChannels.size(),
  211738. false);
  211739. outputBuffers.setSize (enabledOutputs.countNumberOfSetBits(), bufferSizeSamples);
  211740. int numOuts = 0;
  211741. for (i = 0; i <= enabledOutputs.getHighestBit(); i += 2)
  211742. {
  211743. float* left = 0;
  211744. if (enabledOutputs[i])
  211745. left = outputBuffers.getSampleData (numOuts++);
  211746. float* right = 0;
  211747. if (enabledOutputs[i + 1])
  211748. right = outputBuffers.getSampleData (numOuts++);
  211749. if (left != 0 || right != 0)
  211750. outChans.add (new DSoundInternalOutChannel (dlh.outputDeviceNames[outputDeviceIndex],
  211751. dlh.outputGuids [outputDeviceIndex],
  211752. (int) sampleRate, bufferSizeSamples,
  211753. left, right));
  211754. }
  211755. String error;
  211756. // boost our priority while opening the devices to try to get better sync between them
  211757. const int oldThreadPri = GetThreadPriority (GetCurrentThread());
  211758. const int oldProcPri = GetPriorityClass (GetCurrentProcess());
  211759. SetThreadPriority (GetCurrentThread(), THREAD_PRIORITY_TIME_CRITICAL);
  211760. SetPriorityClass (GetCurrentProcess(), REALTIME_PRIORITY_CLASS);
  211761. for (i = 0; i < outChans.size(); ++i)
  211762. {
  211763. error = outChans[i]->open();
  211764. if (error.isNotEmpty())
  211765. {
  211766. error = "Error opening " + dlh.outputDeviceNames[i] + ": \"" + error + "\"";
  211767. break;
  211768. }
  211769. }
  211770. if (error.isEmpty())
  211771. {
  211772. for (i = 0; i < inChans.size(); ++i)
  211773. {
  211774. error = inChans[i]->open();
  211775. if (error.isNotEmpty())
  211776. {
  211777. error = "Error opening " + dlh.inputDeviceNames[i] + ": \"" + error + "\"";
  211778. break;
  211779. }
  211780. }
  211781. }
  211782. if (error.isEmpty())
  211783. {
  211784. totalSamplesOut = 0;
  211785. for (i = 0; i < outChans.size(); ++i)
  211786. outChans.getUnchecked(i)->synchronisePosition();
  211787. for (i = 0; i < inChans.size(); ++i)
  211788. inChans.getUnchecked(i)->synchronisePosition();
  211789. startThread (9);
  211790. sleep (10);
  211791. notify();
  211792. }
  211793. else
  211794. {
  211795. log (error);
  211796. }
  211797. SetThreadPriority (GetCurrentThread(), oldThreadPri);
  211798. SetPriorityClass (GetCurrentProcess(), oldProcPri);
  211799. return error;
  211800. }
  211801. AudioIODeviceType* juce_createAudioIODeviceType_DirectSound()
  211802. {
  211803. return new DSoundAudioIODeviceType();
  211804. }
  211805. #undef log
  211806. #endif
  211807. /*** End of inlined file: juce_win32_DirectSound.cpp ***/
  211808. /*** Start of inlined file: juce_win32_WASAPI.cpp ***/
  211809. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  211810. // compiled on its own).
  211811. #if JUCE_INCLUDED_FILE && JUCE_WASAPI
  211812. #if 1
  211813. const String getAudioErrorDesc (HRESULT hr)
  211814. {
  211815. const char* e = 0;
  211816. switch (hr)
  211817. {
  211818. case E_POINTER: e = "E_POINTER"; break;
  211819. case E_INVALIDARG: e = "E_INVALIDARG"; break;
  211820. case AUDCLNT_E_NOT_INITIALIZED: e = "AUDCLNT_E_NOT_INITIALIZED"; break;
  211821. case AUDCLNT_E_ALREADY_INITIALIZED: e = "AUDCLNT_E_ALREADY_INITIALIZED"; break;
  211822. case AUDCLNT_E_WRONG_ENDPOINT_TYPE: e = "AUDCLNT_E_WRONG_ENDPOINT_TYPE"; break;
  211823. case AUDCLNT_E_DEVICE_INVALIDATED: e = "AUDCLNT_E_DEVICE_INVALIDATED"; break;
  211824. case AUDCLNT_E_NOT_STOPPED: e = "AUDCLNT_E_NOT_STOPPED"; break;
  211825. case AUDCLNT_E_BUFFER_TOO_LARGE: e = "AUDCLNT_E_BUFFER_TOO_LARGE"; break;
  211826. case AUDCLNT_E_OUT_OF_ORDER: e = "AUDCLNT_E_OUT_OF_ORDER"; break;
  211827. case AUDCLNT_E_UNSUPPORTED_FORMAT: e = "AUDCLNT_E_UNSUPPORTED_FORMAT"; break;
  211828. case AUDCLNT_E_INVALID_SIZE: e = "AUDCLNT_E_INVALID_SIZE"; break;
  211829. case AUDCLNT_E_DEVICE_IN_USE: e = "AUDCLNT_E_DEVICE_IN_USE"; break;
  211830. case AUDCLNT_E_BUFFER_OPERATION_PENDING: e = "AUDCLNT_E_BUFFER_OPERATION_PENDING"; break;
  211831. case AUDCLNT_E_THREAD_NOT_REGISTERED: e = "AUDCLNT_E_THREAD_NOT_REGISTERED"; break;
  211832. case AUDCLNT_E_EXCLUSIVE_MODE_NOT_ALLOWED: e = "AUDCLNT_E_EXCLUSIVE_MODE_NOT_ALLOWED"; break;
  211833. case AUDCLNT_E_ENDPOINT_CREATE_FAILED: e = "AUDCLNT_E_ENDPOINT_CREATE_FAILED"; break;
  211834. case AUDCLNT_E_SERVICE_NOT_RUNNING: e = "AUDCLNT_E_SERVICE_NOT_RUNNING"; break;
  211835. case AUDCLNT_E_EVENTHANDLE_NOT_EXPECTED: e = "AUDCLNT_E_EVENTHANDLE_NOT_EXPECTED"; break;
  211836. case AUDCLNT_E_EXCLUSIVE_MODE_ONLY: e = "AUDCLNT_E_EXCLUSIVE_MODE_ONLY"; break;
  211837. case AUDCLNT_E_BUFDURATION_PERIOD_NOT_EQUAL: e = "AUDCLNT_E_BUFDURATION_PERIOD_NOT_EQUAL"; break;
  211838. case AUDCLNT_E_EVENTHANDLE_NOT_SET: e = "AUDCLNT_E_EVENTHANDLE_NOT_SET"; break;
  211839. case AUDCLNT_E_INCORRECT_BUFFER_SIZE: e = "AUDCLNT_E_INCORRECT_BUFFER_SIZE"; break;
  211840. case AUDCLNT_E_BUFFER_SIZE_ERROR: e = "AUDCLNT_E_BUFFER_SIZE_ERROR"; break;
  211841. case AUDCLNT_S_BUFFER_EMPTY: e = "AUDCLNT_S_BUFFER_EMPTY"; break;
  211842. case AUDCLNT_S_THREAD_ALREADY_REGISTERED: e = "AUDCLNT_S_THREAD_ALREADY_REGISTERED"; break;
  211843. default: return String::toHexString ((int) hr);
  211844. }
  211845. return e;
  211846. }
  211847. #define logFailure(hr) { if (FAILED (hr)) { DBG ("WASAPI FAIL! " + getAudioErrorDesc (hr)); jassertfalse } }
  211848. #define OK(a) wasapi_checkResult(a)
  211849. static bool wasapi_checkResult (HRESULT hr)
  211850. {
  211851. logFailure (hr);
  211852. return SUCCEEDED (hr);
  211853. }
  211854. #else
  211855. #define logFailure(hr) {}
  211856. #define OK(a) SUCCEEDED(a)
  211857. #endif
  211858. static const String wasapi_getDeviceID (IMMDevice* const device)
  211859. {
  211860. String s;
  211861. WCHAR* deviceId = 0;
  211862. if (OK (device->GetId (&deviceId)))
  211863. {
  211864. s = String (deviceId);
  211865. CoTaskMemFree (deviceId);
  211866. }
  211867. return s;
  211868. }
  211869. static EDataFlow wasapi_getDataFlow (IMMDevice* const device)
  211870. {
  211871. EDataFlow flow = eRender;
  211872. ComSmartPtr <IMMEndpoint> endPoint;
  211873. if (OK (device->QueryInterface (__uuidof (IMMEndpoint), (void**) &endPoint)))
  211874. (void) OK (endPoint->GetDataFlow (&flow));
  211875. return flow;
  211876. }
  211877. static int wasapi_refTimeToSamples (const REFERENCE_TIME& t, const double sampleRate) throw()
  211878. {
  211879. return roundDoubleToInt (sampleRate * ((double) t) * 0.0000001);
  211880. }
  211881. static void wasapi_copyWavFormat (WAVEFORMATEXTENSIBLE& dest, const WAVEFORMATEX* const src) throw()
  211882. {
  211883. memcpy (&dest, src, src->wFormatTag == WAVE_FORMAT_EXTENSIBLE ? sizeof (WAVEFORMATEXTENSIBLE)
  211884. : sizeof (WAVEFORMATEX));
  211885. }
  211886. class WASAPIDeviceBase
  211887. {
  211888. public:
  211889. WASAPIDeviceBase (const ComSmartPtr <IMMDevice>& device_, const bool useExclusiveMode_)
  211890. : device (device_),
  211891. sampleRate (0),
  211892. numChannels (0),
  211893. actualNumChannels (0),
  211894. defaultSampleRate (0),
  211895. minBufferSize (0),
  211896. defaultBufferSize (0),
  211897. latencySamples (0),
  211898. useExclusiveMode (useExclusiveMode_)
  211899. {
  211900. clientEvent = CreateEvent (0, false, false, _T("JuceWASAPI"));
  211901. ComSmartPtr <IAudioClient> tempClient (createClient());
  211902. if (tempClient == 0)
  211903. return;
  211904. REFERENCE_TIME defaultPeriod, minPeriod;
  211905. if (! OK (tempClient->GetDevicePeriod (&defaultPeriod, &minPeriod)))
  211906. return;
  211907. WAVEFORMATEX* mixFormat = 0;
  211908. if (! OK (tempClient->GetMixFormat (&mixFormat)))
  211909. return;
  211910. WAVEFORMATEXTENSIBLE format;
  211911. wasapi_copyWavFormat (format, mixFormat);
  211912. CoTaskMemFree (mixFormat);
  211913. actualNumChannels = numChannels = format.Format.nChannels;
  211914. defaultSampleRate = format.Format.nSamplesPerSec;
  211915. minBufferSize = wasapi_refTimeToSamples (minPeriod, defaultSampleRate);
  211916. defaultBufferSize = wasapi_refTimeToSamples (defaultPeriod, defaultSampleRate);
  211917. rates.addUsingDefaultSort (defaultSampleRate);
  211918. static const double ratesToTest[] = { 44100.0, 48000.0, 88200.0, 96000.0 };
  211919. for (int i = 0; i < numElementsInArray (ratesToTest); ++i)
  211920. {
  211921. if (ratesToTest[i] == defaultSampleRate)
  211922. continue;
  211923. format.Format.nSamplesPerSec = roundDoubleToInt (ratesToTest[i]);
  211924. if (SUCCEEDED (tempClient->IsFormatSupported (useExclusiveMode ? AUDCLNT_SHAREMODE_EXCLUSIVE : AUDCLNT_SHAREMODE_SHARED,
  211925. (WAVEFORMATEX*) &format, 0)))
  211926. if (! rates.contains (ratesToTest[i]))
  211927. rates.addUsingDefaultSort (ratesToTest[i]);
  211928. }
  211929. }
  211930. ~WASAPIDeviceBase()
  211931. {
  211932. device = 0;
  211933. CloseHandle (clientEvent);
  211934. }
  211935. bool isOk() const throw() { return defaultBufferSize > 0 && defaultSampleRate > 0; }
  211936. bool openClient (const double newSampleRate, const BigInteger& newChannels)
  211937. {
  211938. sampleRate = newSampleRate;
  211939. channels = newChannels;
  211940. channels.setRange (actualNumChannels, channels.getHighestBit() + 1 - actualNumChannels, false);
  211941. numChannels = channels.getHighestBit() + 1;
  211942. if (numChannels == 0)
  211943. return true;
  211944. client = createClient();
  211945. if (client != 0
  211946. && (tryInitialisingWithFormat (true, 4) || tryInitialisingWithFormat (false, 4)
  211947. || tryInitialisingWithFormat (false, 3) || tryInitialisingWithFormat (false, 2)))
  211948. {
  211949. channelMaps.clear();
  211950. for (int i = 0; i <= channels.getHighestBit(); ++i)
  211951. if (channels[i])
  211952. channelMaps.add (i);
  211953. REFERENCE_TIME latency;
  211954. if (OK (client->GetStreamLatency (&latency)))
  211955. latencySamples = wasapi_refTimeToSamples (latency, sampleRate);
  211956. (void) OK (client->GetBufferSize (&actualBufferSize));
  211957. return OK (client->SetEventHandle (clientEvent));
  211958. }
  211959. return false;
  211960. }
  211961. void closeClient()
  211962. {
  211963. if (client != 0)
  211964. client->Stop();
  211965. client = 0;
  211966. ResetEvent (clientEvent);
  211967. }
  211968. ComSmartPtr <IMMDevice> device;
  211969. ComSmartPtr <IAudioClient> client;
  211970. double sampleRate, defaultSampleRate;
  211971. int numChannels, actualNumChannels;
  211972. int minBufferSize, defaultBufferSize, latencySamples;
  211973. const bool useExclusiveMode;
  211974. Array <double> rates;
  211975. HANDLE clientEvent;
  211976. BigInteger channels;
  211977. AudioDataConverters::DataFormat dataFormat;
  211978. Array <int> channelMaps;
  211979. UINT32 actualBufferSize;
  211980. int bytesPerSample;
  211981. private:
  211982. const ComSmartPtr <IAudioClient> createClient()
  211983. {
  211984. ComSmartPtr <IAudioClient> client;
  211985. if (device != 0)
  211986. {
  211987. HRESULT hr = device->Activate (__uuidof (IAudioClient), CLSCTX_INPROC_SERVER, 0, (void**) &client);
  211988. logFailure (hr);
  211989. }
  211990. return client;
  211991. }
  211992. bool tryInitialisingWithFormat (const bool useFloat, const int bytesPerSampleToTry)
  211993. {
  211994. WAVEFORMATEXTENSIBLE format;
  211995. zerostruct (format);
  211996. if (numChannels <= 2 && bytesPerSampleToTry <= 2)
  211997. {
  211998. format.Format.wFormatTag = WAVE_FORMAT_PCM;
  211999. }
  212000. else
  212001. {
  212002. format.Format.wFormatTag = WAVE_FORMAT_EXTENSIBLE;
  212003. format.Format.cbSize = sizeof (WAVEFORMATEXTENSIBLE) - sizeof (WAVEFORMATEX);
  212004. }
  212005. format.Format.nSamplesPerSec = roundDoubleToInt (sampleRate);
  212006. format.Format.nChannels = (WORD) numChannels;
  212007. format.Format.wBitsPerSample = (WORD) (8 * bytesPerSampleToTry);
  212008. format.Format.nAvgBytesPerSec = (DWORD) (format.Format.nSamplesPerSec * numChannels * bytesPerSampleToTry);
  212009. format.Format.nBlockAlign = (WORD) (numChannels * bytesPerSampleToTry);
  212010. format.SubFormat = useFloat ? KSDATAFORMAT_SUBTYPE_IEEE_FLOAT : KSDATAFORMAT_SUBTYPE_PCM;
  212011. format.Samples.wValidBitsPerSample = format.Format.wBitsPerSample;
  212012. switch (numChannels)
  212013. {
  212014. case 1: format.dwChannelMask = SPEAKER_FRONT_CENTER; break;
  212015. case 2: format.dwChannelMask = SPEAKER_FRONT_LEFT | SPEAKER_FRONT_RIGHT; break;
  212016. case 4: format.dwChannelMask = SPEAKER_FRONT_LEFT | SPEAKER_FRONT_RIGHT | SPEAKER_BACK_LEFT | SPEAKER_BACK_RIGHT; break;
  212017. case 6: format.dwChannelMask = SPEAKER_FRONT_LEFT | SPEAKER_FRONT_RIGHT | SPEAKER_FRONT_CENTER | SPEAKER_LOW_FREQUENCY | SPEAKER_BACK_LEFT | SPEAKER_BACK_RIGHT; break;
  212018. case 8: format.dwChannelMask = SPEAKER_FRONT_LEFT | SPEAKER_FRONT_RIGHT | SPEAKER_FRONT_CENTER | SPEAKER_LOW_FREQUENCY | SPEAKER_BACK_LEFT | SPEAKER_BACK_RIGHT | SPEAKER_FRONT_LEFT_OF_CENTER | SPEAKER_FRONT_RIGHT_OF_CENTER; break;
  212019. default: break;
  212020. }
  212021. WAVEFORMATEXTENSIBLE* nearestFormat = 0;
  212022. HRESULT hr = client->IsFormatSupported (useExclusiveMode ? AUDCLNT_SHAREMODE_EXCLUSIVE : AUDCLNT_SHAREMODE_SHARED,
  212023. (WAVEFORMATEX*) &format, useExclusiveMode ? 0 : (WAVEFORMATEX**) &nearestFormat);
  212024. logFailure (hr);
  212025. if (hr == S_FALSE && format.Format.nSamplesPerSec == nearestFormat->Format.nSamplesPerSec)
  212026. {
  212027. wasapi_copyWavFormat (format, (WAVEFORMATEX*) nearestFormat);
  212028. hr = S_OK;
  212029. }
  212030. CoTaskMemFree (nearestFormat);
  212031. REFERENCE_TIME defaultPeriod = 0, minPeriod = 0;
  212032. if (useExclusiveMode)
  212033. OK (client->GetDevicePeriod (&defaultPeriod, &minPeriod));
  212034. GUID session;
  212035. if (hr == S_OK
  212036. && OK (client->Initialize (useExclusiveMode ? AUDCLNT_SHAREMODE_EXCLUSIVE : AUDCLNT_SHAREMODE_SHARED,
  212037. AUDCLNT_STREAMFLAGS_EVENTCALLBACK,
  212038. defaultPeriod, defaultPeriod, (WAVEFORMATEX*) &format, &session)))
  212039. {
  212040. actualNumChannels = format.Format.nChannels;
  212041. const bool isFloat = format.Format.wFormatTag == WAVE_FORMAT_EXTENSIBLE && format.SubFormat == KSDATAFORMAT_SUBTYPE_IEEE_FLOAT;
  212042. bytesPerSample = format.Format.wBitsPerSample / 8;
  212043. dataFormat = isFloat ? AudioDataConverters::float32LE
  212044. : (bytesPerSample == 4 ? AudioDataConverters::int32LE
  212045. : ((bytesPerSample == 3 ? AudioDataConverters::int24LE
  212046. : AudioDataConverters::int16LE)));
  212047. return true;
  212048. }
  212049. return false;
  212050. }
  212051. WASAPIDeviceBase (const WASAPIDeviceBase&);
  212052. WASAPIDeviceBase& operator= (const WASAPIDeviceBase&);
  212053. };
  212054. class WASAPIInputDevice : public WASAPIDeviceBase
  212055. {
  212056. public:
  212057. WASAPIInputDevice (const ComSmartPtr <IMMDevice>& device_, const bool useExclusiveMode_)
  212058. : WASAPIDeviceBase (device_, useExclusiveMode_),
  212059. reservoir (1, 1)
  212060. {
  212061. }
  212062. ~WASAPIInputDevice()
  212063. {
  212064. close();
  212065. }
  212066. bool open (const double newSampleRate, const BigInteger& newChannels)
  212067. {
  212068. reservoirSize = 0;
  212069. reservoirCapacity = 16384;
  212070. reservoir.setSize (actualNumChannels * reservoirCapacity * sizeof (float));
  212071. return openClient (newSampleRate, newChannels)
  212072. && (numChannels == 0 || OK (client->GetService (__uuidof (IAudioCaptureClient), (void**) &captureClient)));
  212073. }
  212074. void close()
  212075. {
  212076. closeClient();
  212077. captureClient = 0;
  212078. reservoir.setSize (0);
  212079. }
  212080. void copyBuffers (float** destBuffers, int numDestBuffers, int bufferSize, Thread& thread)
  212081. {
  212082. if (numChannels <= 0)
  212083. return;
  212084. int offset = 0;
  212085. while (bufferSize > 0)
  212086. {
  212087. if (reservoirSize > 0) // There's stuff in the reservoir, so use that...
  212088. {
  212089. const int samplesToDo = jmin (bufferSize, (int) reservoirSize);
  212090. for (int i = 0; i < numDestBuffers; ++i)
  212091. {
  212092. float* const dest = destBuffers[i] + offset;
  212093. const int srcChan = channelMaps.getUnchecked(i);
  212094. switch (dataFormat)
  212095. {
  212096. case AudioDataConverters::float32LE:
  212097. AudioDataConverters::convertFloat32LEToFloat (((uint8*) reservoir.getData()) + 4 * srcChan, dest, samplesToDo, 4 * actualNumChannels);
  212098. break;
  212099. case AudioDataConverters::int32LE:
  212100. AudioDataConverters::convertInt32LEToFloat (((uint8*) reservoir.getData()) + 4 * srcChan, dest, samplesToDo, 4 * actualNumChannels);
  212101. break;
  212102. case AudioDataConverters::int24LE:
  212103. AudioDataConverters::convertInt24LEToFloat (((uint8*) reservoir.getData()) + 3 * srcChan, dest, samplesToDo, 3 * actualNumChannels);
  212104. break;
  212105. case AudioDataConverters::int16LE:
  212106. AudioDataConverters::convertInt16LEToFloat (((uint8*) reservoir.getData()) + 2 * srcChan, dest, samplesToDo, 2 * actualNumChannels);
  212107. break;
  212108. default: jassertfalse; break;
  212109. }
  212110. }
  212111. bufferSize -= samplesToDo;
  212112. offset += samplesToDo;
  212113. reservoirSize -= samplesToDo;
  212114. }
  212115. else
  212116. {
  212117. UINT32 packetLength = 0;
  212118. if (! OK (captureClient->GetNextPacketSize (&packetLength)))
  212119. break;
  212120. if (packetLength == 0)
  212121. {
  212122. if (thread.threadShouldExit())
  212123. break;
  212124. Thread::sleep (1);
  212125. continue;
  212126. }
  212127. uint8* inputData = 0;
  212128. UINT32 numSamplesAvailable;
  212129. DWORD flags;
  212130. if (OK (captureClient->GetBuffer (&inputData, &numSamplesAvailable, &flags, 0, 0)))
  212131. {
  212132. const int samplesToDo = jmin (bufferSize, (int) numSamplesAvailable);
  212133. for (int i = 0; i < numDestBuffers; ++i)
  212134. {
  212135. float* const dest = destBuffers[i] + offset;
  212136. const int srcChan = channelMaps.getUnchecked(i);
  212137. switch (dataFormat)
  212138. {
  212139. case AudioDataConverters::float32LE:
  212140. AudioDataConverters::convertFloat32LEToFloat (inputData + 4 * srcChan, dest, samplesToDo, 4 * actualNumChannels);
  212141. break;
  212142. case AudioDataConverters::int32LE:
  212143. AudioDataConverters::convertInt32LEToFloat (inputData + 4 * srcChan, dest, samplesToDo, 4 * actualNumChannels);
  212144. break;
  212145. case AudioDataConverters::int24LE:
  212146. AudioDataConverters::convertInt24LEToFloat (inputData + 3 * srcChan, dest, samplesToDo, 3 * actualNumChannels);
  212147. break;
  212148. case AudioDataConverters::int16LE:
  212149. AudioDataConverters::convertInt16LEToFloat (inputData + 2 * srcChan, dest, samplesToDo, 2 * actualNumChannels);
  212150. break;
  212151. default: jassertfalse; break;
  212152. }
  212153. }
  212154. bufferSize -= samplesToDo;
  212155. offset += samplesToDo;
  212156. if (samplesToDo < (int) numSamplesAvailable)
  212157. {
  212158. reservoirSize = jmin ((int) (numSamplesAvailable - samplesToDo), reservoirCapacity);
  212159. memcpy ((uint8*) reservoir.getData(), inputData + bytesPerSample * actualNumChannels * samplesToDo,
  212160. bytesPerSample * actualNumChannels * reservoirSize);
  212161. }
  212162. captureClient->ReleaseBuffer (numSamplesAvailable);
  212163. }
  212164. }
  212165. }
  212166. }
  212167. ComSmartPtr <IAudioCaptureClient> captureClient;
  212168. MemoryBlock reservoir;
  212169. int reservoirSize, reservoirCapacity;
  212170. private:
  212171. WASAPIInputDevice (const WASAPIInputDevice&);
  212172. WASAPIInputDevice& operator= (const WASAPIInputDevice&);
  212173. };
  212174. class WASAPIOutputDevice : public WASAPIDeviceBase
  212175. {
  212176. public:
  212177. WASAPIOutputDevice (const ComSmartPtr <IMMDevice>& device_, const bool useExclusiveMode_)
  212178. : WASAPIDeviceBase (device_, useExclusiveMode_)
  212179. {
  212180. }
  212181. ~WASAPIOutputDevice()
  212182. {
  212183. close();
  212184. }
  212185. bool open (const double newSampleRate, const BigInteger& newChannels)
  212186. {
  212187. return openClient (newSampleRate, newChannels)
  212188. && (numChannels == 0 || OK (client->GetService (__uuidof (IAudioRenderClient), (void**) &renderClient)));
  212189. }
  212190. void close()
  212191. {
  212192. closeClient();
  212193. renderClient = 0;
  212194. }
  212195. void copyBuffers (const float** const srcBuffers, const int numSrcBuffers, int bufferSize, Thread& thread)
  212196. {
  212197. if (numChannels <= 0)
  212198. return;
  212199. int offset = 0;
  212200. while (bufferSize > 0)
  212201. {
  212202. UINT32 padding = 0;
  212203. if (! OK (client->GetCurrentPadding (&padding)))
  212204. return;
  212205. int samplesToDo = useExclusiveMode ? bufferSize
  212206. : jmin ((int) (actualBufferSize - padding), bufferSize);
  212207. if (samplesToDo <= 0)
  212208. {
  212209. if (thread.threadShouldExit())
  212210. break;
  212211. Thread::sleep (0);
  212212. continue;
  212213. }
  212214. uint8* outputData = 0;
  212215. if (OK (renderClient->GetBuffer (samplesToDo, &outputData)))
  212216. {
  212217. for (int i = 0; i < numSrcBuffers; ++i)
  212218. {
  212219. const float* const source = srcBuffers[i] + offset;
  212220. const int destChan = channelMaps.getUnchecked(i);
  212221. switch (dataFormat)
  212222. {
  212223. case AudioDataConverters::float32LE:
  212224. AudioDataConverters::convertFloatToFloat32LE (source, outputData + 4 * destChan, samplesToDo, 4 * actualNumChannels);
  212225. break;
  212226. case AudioDataConverters::int32LE:
  212227. AudioDataConverters::convertFloatToInt32LE (source, outputData + 4 * destChan, samplesToDo, 4 * actualNumChannels);
  212228. break;
  212229. case AudioDataConverters::int24LE:
  212230. AudioDataConverters::convertFloatToInt24LE (source, outputData + 3 * destChan, samplesToDo, 3 * actualNumChannels);
  212231. break;
  212232. case AudioDataConverters::int16LE:
  212233. AudioDataConverters::convertFloatToInt16LE (source, outputData + 2 * destChan, samplesToDo, 2 * actualNumChannels);
  212234. break;
  212235. default: jassertfalse; break;
  212236. }
  212237. }
  212238. renderClient->ReleaseBuffer (samplesToDo, 0);
  212239. offset += samplesToDo;
  212240. bufferSize -= samplesToDo;
  212241. }
  212242. }
  212243. }
  212244. ComSmartPtr <IAudioRenderClient> renderClient;
  212245. private:
  212246. WASAPIOutputDevice (const WASAPIOutputDevice&);
  212247. WASAPIOutputDevice& operator= (const WASAPIOutputDevice&);
  212248. };
  212249. class WASAPIAudioIODevice : public AudioIODevice,
  212250. public Thread
  212251. {
  212252. public:
  212253. WASAPIAudioIODevice (const String& deviceName,
  212254. const String& outputDeviceId_,
  212255. const String& inputDeviceId_,
  212256. const bool useExclusiveMode_)
  212257. : AudioIODevice (deviceName, "Windows Audio"),
  212258. Thread ("Juce WASAPI"),
  212259. isOpen_ (false),
  212260. isStarted (false),
  212261. outputDevice (0),
  212262. outputDeviceId (outputDeviceId_),
  212263. inputDevice (0),
  212264. inputDeviceId (inputDeviceId_),
  212265. useExclusiveMode (useExclusiveMode_),
  212266. currentBufferSizeSamples (0),
  212267. currentSampleRate (0),
  212268. callback (0)
  212269. {
  212270. }
  212271. ~WASAPIAudioIODevice()
  212272. {
  212273. close();
  212274. deleteAndZero (inputDevice);
  212275. deleteAndZero (outputDevice);
  212276. }
  212277. bool initialise()
  212278. {
  212279. double defaultSampleRateIn = 0, defaultSampleRateOut = 0;
  212280. int minBufferSizeIn = 0, defaultBufferSizeIn = 0, minBufferSizeOut = 0, defaultBufferSizeOut = 0;
  212281. latencyIn = latencyOut = 0;
  212282. Array <double> ratesIn, ratesOut;
  212283. if (createDevices())
  212284. {
  212285. jassert (inputDevice != 0 || outputDevice != 0);
  212286. if (inputDevice != 0 && outputDevice != 0)
  212287. {
  212288. defaultSampleRate = jmin (inputDevice->defaultSampleRate, outputDevice->defaultSampleRate);
  212289. minBufferSize = jmin (inputDevice->minBufferSize, outputDevice->minBufferSize);
  212290. defaultBufferSize = jmax (inputDevice->defaultBufferSize, outputDevice->defaultBufferSize);
  212291. sampleRates = inputDevice->rates;
  212292. sampleRates.removeValuesNotIn (outputDevice->rates);
  212293. }
  212294. else
  212295. {
  212296. WASAPIDeviceBase* const d = inputDevice != 0 ? (WASAPIDeviceBase*) inputDevice : (WASAPIDeviceBase*) outputDevice;
  212297. defaultSampleRate = d->defaultSampleRate;
  212298. minBufferSize = d->minBufferSize;
  212299. defaultBufferSize = d->defaultBufferSize;
  212300. sampleRates = d->rates;
  212301. }
  212302. bufferSizes.addUsingDefaultSort (defaultBufferSize);
  212303. if (minBufferSize != defaultBufferSize)
  212304. bufferSizes.addUsingDefaultSort (minBufferSize);
  212305. int n = 64;
  212306. for (int i = 0; i < 40; ++i)
  212307. {
  212308. if (n >= minBufferSize && n <= 2048 && ! bufferSizes.contains (n))
  212309. bufferSizes.addUsingDefaultSort (n);
  212310. n += (n < 512) ? 32 : (n < 1024 ? 64 : 128);
  212311. }
  212312. return true;
  212313. }
  212314. return false;
  212315. }
  212316. const StringArray getOutputChannelNames()
  212317. {
  212318. StringArray outChannels;
  212319. if (outputDevice != 0)
  212320. for (int i = 1; i <= outputDevice->actualNumChannels; ++i)
  212321. outChannels.add ("Output channel " + String (i));
  212322. return outChannels;
  212323. }
  212324. const StringArray getInputChannelNames()
  212325. {
  212326. StringArray inChannels;
  212327. if (inputDevice != 0)
  212328. for (int i = 1; i <= inputDevice->actualNumChannels; ++i)
  212329. inChannels.add ("Input channel " + String (i));
  212330. return inChannels;
  212331. }
  212332. int getNumSampleRates() { return sampleRates.size(); }
  212333. double getSampleRate (int index) { return sampleRates [index]; }
  212334. int getNumBufferSizesAvailable() { return bufferSizes.size(); }
  212335. int getBufferSizeSamples (int index) { return bufferSizes [index]; }
  212336. int getDefaultBufferSize() { return defaultBufferSize; }
  212337. int getCurrentBufferSizeSamples() { return currentBufferSizeSamples; }
  212338. double getCurrentSampleRate() { return currentSampleRate; }
  212339. int getCurrentBitDepth() { return 32; }
  212340. int getOutputLatencyInSamples() { return latencyOut; }
  212341. int getInputLatencyInSamples() { return latencyIn; }
  212342. const BigInteger getActiveOutputChannels() const { return outputDevice != 0 ? outputDevice->channels : BigInteger(); }
  212343. const BigInteger getActiveInputChannels() const { return inputDevice != 0 ? inputDevice->channels : BigInteger(); }
  212344. const String getLastError() { return lastError; }
  212345. const String open (const BigInteger& inputChannels, const BigInteger& outputChannels,
  212346. double sampleRate, int bufferSizeSamples)
  212347. {
  212348. close();
  212349. lastError = String::empty;
  212350. if (sampleRates.size() == 0 && inputDevice != 0 && outputDevice != 0)
  212351. {
  212352. lastError = "The input and output devices don't share a common sample rate!";
  212353. return lastError;
  212354. }
  212355. currentBufferSizeSamples = bufferSizeSamples <= 0 ? defaultBufferSize : jmax (bufferSizeSamples, minBufferSize);
  212356. currentSampleRate = sampleRate > 0 ? sampleRate : defaultSampleRate;
  212357. if (inputDevice != 0 && ! inputDevice->open (currentSampleRate, inputChannels))
  212358. {
  212359. lastError = "Couldn't open the input device!";
  212360. return lastError;
  212361. }
  212362. if (outputDevice != 0 && ! outputDevice->open (currentSampleRate, outputChannels))
  212363. {
  212364. close();
  212365. lastError = "Couldn't open the output device!";
  212366. return lastError;
  212367. }
  212368. if (inputDevice != 0)
  212369. ResetEvent (inputDevice->clientEvent);
  212370. if (outputDevice != 0)
  212371. ResetEvent (outputDevice->clientEvent);
  212372. startThread (8);
  212373. Thread::sleep (5);
  212374. if (inputDevice != 0 && inputDevice->client != 0)
  212375. {
  212376. latencyIn = inputDevice->latencySamples + inputDevice->actualBufferSize + inputDevice->minBufferSize;
  212377. HRESULT hr = inputDevice->client->Start();
  212378. logFailure (hr); //xxx handle this
  212379. }
  212380. if (outputDevice != 0 && outputDevice->client != 0)
  212381. {
  212382. latencyOut = outputDevice->latencySamples + outputDevice->actualBufferSize + outputDevice->minBufferSize;
  212383. HRESULT hr = outputDevice->client->Start();
  212384. logFailure (hr); //xxx handle this
  212385. }
  212386. isOpen_ = true;
  212387. return lastError;
  212388. }
  212389. void close()
  212390. {
  212391. stop();
  212392. if (inputDevice != 0)
  212393. SetEvent (inputDevice->clientEvent);
  212394. if (outputDevice != 0)
  212395. SetEvent (outputDevice->clientEvent);
  212396. stopThread (5000);
  212397. if (inputDevice != 0)
  212398. inputDevice->close();
  212399. if (outputDevice != 0)
  212400. outputDevice->close();
  212401. isOpen_ = false;
  212402. }
  212403. bool isOpen() { return isOpen_ && isThreadRunning(); }
  212404. bool isPlaying() { return isStarted && isOpen_ && isThreadRunning(); }
  212405. void start (AudioIODeviceCallback* call)
  212406. {
  212407. if (isOpen_ && call != 0 && ! isStarted)
  212408. {
  212409. if (! isThreadRunning())
  212410. {
  212411. // something's gone wrong and the thread's stopped..
  212412. isOpen_ = false;
  212413. return;
  212414. }
  212415. call->audioDeviceAboutToStart (this);
  212416. const ScopedLock sl (startStopLock);
  212417. callback = call;
  212418. isStarted = true;
  212419. }
  212420. }
  212421. void stop()
  212422. {
  212423. if (isStarted)
  212424. {
  212425. AudioIODeviceCallback* const callbackLocal = callback;
  212426. {
  212427. const ScopedLock sl (startStopLock);
  212428. isStarted = false;
  212429. }
  212430. if (callbackLocal != 0)
  212431. callbackLocal->audioDeviceStopped();
  212432. }
  212433. }
  212434. void setMMThreadPriority()
  212435. {
  212436. DynamicLibraryLoader dll ("avrt.dll");
  212437. DynamicLibraryImport (AvSetMmThreadCharacteristics, avSetMmThreadCharacteristics, HANDLE, dll, (LPCTSTR, LPDWORD))
  212438. DynamicLibraryImport (AvSetMmThreadPriority, avSetMmThreadPriority, HANDLE, dll, (HANDLE, AVRT_PRIORITY))
  212439. if (avSetMmThreadCharacteristics != 0 && avSetMmThreadPriority != 0)
  212440. {
  212441. DWORD dummy = 0;
  212442. HANDLE h = avSetMmThreadCharacteristics (_T("Pro Audio"), &dummy);
  212443. if (h != 0)
  212444. avSetMmThreadPriority (h, AVRT_PRIORITY_NORMAL);
  212445. }
  212446. }
  212447. void run()
  212448. {
  212449. setMMThreadPriority();
  212450. const int bufferSize = currentBufferSizeSamples;
  212451. HANDLE events[2];
  212452. int numEvents = 0;
  212453. if (inputDevice != 0)
  212454. events [numEvents++] = inputDevice->clientEvent;
  212455. if (outputDevice != 0)
  212456. events [numEvents++] = outputDevice->clientEvent;
  212457. const int numInputBuffers = getActiveInputChannels().countNumberOfSetBits();
  212458. const int numOutputBuffers = getActiveOutputChannels().countNumberOfSetBits();
  212459. AudioSampleBuffer ins (jmax (1, numInputBuffers), bufferSize + 32);
  212460. AudioSampleBuffer outs (jmax (1, numOutputBuffers), bufferSize + 32);
  212461. float** const inputBuffers = ins.getArrayOfChannels();
  212462. float** const outputBuffers = outs.getArrayOfChannels();
  212463. ins.clear();
  212464. while (! threadShouldExit())
  212465. {
  212466. const DWORD result = useExclusiveMode ? WaitForSingleObject (inputDevice->clientEvent, 1000)
  212467. : WaitForMultipleObjects (numEvents, events, true, 1000);
  212468. if (result == WAIT_TIMEOUT)
  212469. continue;
  212470. if (threadShouldExit())
  212471. break;
  212472. if (inputDevice != 0)
  212473. inputDevice->copyBuffers (inputBuffers, numInputBuffers, bufferSize, *this);
  212474. // Make the callback..
  212475. {
  212476. const ScopedLock sl (startStopLock);
  212477. if (isStarted)
  212478. {
  212479. JUCE_TRY
  212480. {
  212481. callback->audioDeviceIOCallback ((const float**) inputBuffers,
  212482. numInputBuffers,
  212483. outputBuffers,
  212484. numOutputBuffers,
  212485. bufferSize);
  212486. }
  212487. JUCE_CATCH_EXCEPTION
  212488. }
  212489. else
  212490. {
  212491. outs.clear();
  212492. }
  212493. }
  212494. if (useExclusiveMode && WaitForSingleObject (outputDevice->clientEvent, 1000) == WAIT_TIMEOUT)
  212495. continue;
  212496. if (outputDevice != 0)
  212497. outputDevice->copyBuffers ((const float**) outputBuffers, numOutputBuffers, bufferSize, *this);
  212498. }
  212499. }
  212500. juce_UseDebuggingNewOperator
  212501. String outputDeviceId, inputDeviceId;
  212502. String lastError;
  212503. private:
  212504. // Device stats...
  212505. WASAPIInputDevice* inputDevice;
  212506. WASAPIOutputDevice* outputDevice;
  212507. const bool useExclusiveMode;
  212508. double defaultSampleRate;
  212509. int minBufferSize, defaultBufferSize;
  212510. int latencyIn, latencyOut;
  212511. Array <double> sampleRates;
  212512. Array <int> bufferSizes;
  212513. // Active state...
  212514. bool isOpen_, isStarted;
  212515. int currentBufferSizeSamples;
  212516. double currentSampleRate;
  212517. AudioIODeviceCallback* callback;
  212518. CriticalSection startStopLock;
  212519. bool createDevices()
  212520. {
  212521. ComSmartPtr <IMMDeviceEnumerator> enumerator;
  212522. if (! OK (enumerator.CoCreateInstance (__uuidof (MMDeviceEnumerator))))
  212523. return false;
  212524. ComSmartPtr <IMMDeviceCollection> deviceCollection;
  212525. if (! OK (enumerator->EnumAudioEndpoints (eAll, DEVICE_STATE_ACTIVE, &deviceCollection)))
  212526. return false;
  212527. UINT32 numDevices = 0;
  212528. if (! OK (deviceCollection->GetCount (&numDevices)))
  212529. return false;
  212530. for (UINT32 i = 0; i < numDevices; ++i)
  212531. {
  212532. ComSmartPtr <IMMDevice> device;
  212533. if (! OK (deviceCollection->Item (i, &device)))
  212534. continue;
  212535. const String deviceId (wasapi_getDeviceID (device));
  212536. if (deviceId.isEmpty())
  212537. continue;
  212538. const EDataFlow flow = wasapi_getDataFlow (device);
  212539. if (deviceId == inputDeviceId && flow == eCapture)
  212540. inputDevice = new WASAPIInputDevice (device, useExclusiveMode);
  212541. else if (deviceId == outputDeviceId && flow == eRender)
  212542. outputDevice = new WASAPIOutputDevice (device, useExclusiveMode);
  212543. }
  212544. return (outputDeviceId.isEmpty() || (outputDevice != 0 && outputDevice->isOk()))
  212545. && (inputDeviceId.isEmpty() || (inputDevice != 0 && inputDevice->isOk()));
  212546. }
  212547. WASAPIAudioIODevice (const WASAPIAudioIODevice&);
  212548. WASAPIAudioIODevice& operator= (const WASAPIAudioIODevice&);
  212549. };
  212550. class WASAPIAudioIODeviceType : public AudioIODeviceType
  212551. {
  212552. public:
  212553. WASAPIAudioIODeviceType()
  212554. : AudioIODeviceType ("Windows Audio"),
  212555. hasScanned (false)
  212556. {
  212557. }
  212558. ~WASAPIAudioIODeviceType()
  212559. {
  212560. }
  212561. void scanForDevices()
  212562. {
  212563. hasScanned = true;
  212564. outputDeviceNames.clear();
  212565. inputDeviceNames.clear();
  212566. outputDeviceIds.clear();
  212567. inputDeviceIds.clear();
  212568. ComSmartPtr <IMMDeviceEnumerator> enumerator;
  212569. if (! OK (enumerator.CoCreateInstance (__uuidof (MMDeviceEnumerator))))
  212570. return;
  212571. const String defaultRenderer = getDefaultEndpoint (enumerator, false);
  212572. const String defaultCapture = getDefaultEndpoint (enumerator, true);
  212573. ComSmartPtr <IMMDeviceCollection> deviceCollection;
  212574. UINT32 numDevices = 0;
  212575. if (! (OK (enumerator->EnumAudioEndpoints (eAll, DEVICE_STATE_ACTIVE, &deviceCollection))
  212576. && OK (deviceCollection->GetCount (&numDevices))))
  212577. return;
  212578. for (UINT32 i = 0; i < numDevices; ++i)
  212579. {
  212580. ComSmartPtr <IMMDevice> device;
  212581. if (! OK (deviceCollection->Item (i, &device)))
  212582. continue;
  212583. const String deviceId (wasapi_getDeviceID (device));
  212584. DWORD state = 0;
  212585. if (! OK (device->GetState (&state)))
  212586. continue;
  212587. if (state != DEVICE_STATE_ACTIVE)
  212588. continue;
  212589. String name;
  212590. {
  212591. ComSmartPtr <IPropertyStore> properties;
  212592. if (! OK (device->OpenPropertyStore (STGM_READ, &properties)))
  212593. continue;
  212594. PROPVARIANT value;
  212595. PropVariantInit (&value);
  212596. if (OK (properties->GetValue (PKEY_Device_FriendlyName, &value)))
  212597. name = value.pwszVal;
  212598. PropVariantClear (&value);
  212599. }
  212600. const EDataFlow flow = wasapi_getDataFlow (device);
  212601. if (flow == eRender)
  212602. {
  212603. const int index = (deviceId == defaultRenderer) ? 0 : -1;
  212604. outputDeviceIds.insert (index, deviceId);
  212605. outputDeviceNames.insert (index, name);
  212606. }
  212607. else if (flow == eCapture)
  212608. {
  212609. const int index = (deviceId == defaultCapture) ? 0 : -1;
  212610. inputDeviceIds.insert (index, deviceId);
  212611. inputDeviceNames.insert (index, name);
  212612. }
  212613. }
  212614. inputDeviceNames.appendNumbersToDuplicates (false, false);
  212615. outputDeviceNames.appendNumbersToDuplicates (false, false);
  212616. }
  212617. const StringArray getDeviceNames (bool wantInputNames) const
  212618. {
  212619. jassert (hasScanned); // need to call scanForDevices() before doing this
  212620. return wantInputNames ? inputDeviceNames
  212621. : outputDeviceNames;
  212622. }
  212623. int getDefaultDeviceIndex (bool /*forInput*/) const
  212624. {
  212625. jassert (hasScanned); // need to call scanForDevices() before doing this
  212626. return 0;
  212627. }
  212628. int getIndexOfDevice (AudioIODevice* device, bool asInput) const
  212629. {
  212630. jassert (hasScanned); // need to call scanForDevices() before doing this
  212631. WASAPIAudioIODevice* const d = dynamic_cast <WASAPIAudioIODevice*> (device);
  212632. return d == 0 ? -1 : (asInput ? inputDeviceIds.indexOf (d->inputDeviceId)
  212633. : outputDeviceIds.indexOf (d->outputDeviceId));
  212634. }
  212635. bool hasSeparateInputsAndOutputs() const { return true; }
  212636. AudioIODevice* createDevice (const String& outputDeviceName,
  212637. const String& inputDeviceName)
  212638. {
  212639. jassert (hasScanned); // need to call scanForDevices() before doing this
  212640. const bool useExclusiveMode = false;
  212641. ScopedPointer<WASAPIAudioIODevice> device;
  212642. const int outputIndex = outputDeviceNames.indexOf (outputDeviceName);
  212643. const int inputIndex = inputDeviceNames.indexOf (inputDeviceName);
  212644. if (outputIndex >= 0 || inputIndex >= 0)
  212645. {
  212646. device = new WASAPIAudioIODevice (outputDeviceName.isNotEmpty() ? outputDeviceName
  212647. : inputDeviceName,
  212648. outputDeviceIds [outputIndex],
  212649. inputDeviceIds [inputIndex],
  212650. useExclusiveMode);
  212651. if (! device->initialise())
  212652. device = 0;
  212653. }
  212654. return device.release();
  212655. }
  212656. juce_UseDebuggingNewOperator
  212657. StringArray outputDeviceNames, outputDeviceIds;
  212658. StringArray inputDeviceNames, inputDeviceIds;
  212659. private:
  212660. bool hasScanned;
  212661. static const String getDefaultEndpoint (IMMDeviceEnumerator* const enumerator, const bool forCapture)
  212662. {
  212663. String s;
  212664. IMMDevice* dev = 0;
  212665. if (OK (enumerator->GetDefaultAudioEndpoint (forCapture ? eCapture : eRender,
  212666. eMultimedia, &dev)))
  212667. {
  212668. WCHAR* deviceId = 0;
  212669. if (OK (dev->GetId (&deviceId)))
  212670. {
  212671. s = String (deviceId);
  212672. CoTaskMemFree (deviceId);
  212673. }
  212674. dev->Release();
  212675. }
  212676. return s;
  212677. }
  212678. WASAPIAudioIODeviceType (const WASAPIAudioIODeviceType&);
  212679. WASAPIAudioIODeviceType& operator= (const WASAPIAudioIODeviceType&);
  212680. };
  212681. AudioIODeviceType* juce_createAudioIODeviceType_WASAPI()
  212682. {
  212683. return new WASAPIAudioIODeviceType();
  212684. }
  212685. #undef logFailure
  212686. #undef OK
  212687. #endif
  212688. /*** End of inlined file: juce_win32_WASAPI.cpp ***/
  212689. /*** Start of inlined file: juce_win32_CameraDevice.cpp ***/
  212690. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  212691. // compiled on its own).
  212692. #if JUCE_INCLUDED_FILE && JUCE_USE_CAMERA
  212693. class DShowCameraDeviceInteral : public ChangeBroadcaster
  212694. {
  212695. public:
  212696. DShowCameraDeviceInteral (CameraDevice* const owner_,
  212697. const ComSmartPtr <ICaptureGraphBuilder2>& captureGraphBuilder_,
  212698. const ComSmartPtr <IBaseFilter>& filter_,
  212699. int minWidth, int minHeight,
  212700. int maxWidth, int maxHeight)
  212701. : owner (owner_),
  212702. captureGraphBuilder (captureGraphBuilder_),
  212703. filter (filter_),
  212704. ok (false),
  212705. imageNeedsFlipping (false),
  212706. width (0),
  212707. height (0),
  212708. activeUsers (0),
  212709. recordNextFrameTime (false),
  212710. activeImage (0),
  212711. loadingImage (0)
  212712. {
  212713. HRESULT hr = graphBuilder.CoCreateInstance (CLSID_FilterGraph);
  212714. if (FAILED (hr))
  212715. return;
  212716. hr = captureGraphBuilder->SetFiltergraph (graphBuilder);
  212717. if (FAILED (hr))
  212718. return;
  212719. hr = graphBuilder->QueryInterface (IID_IMediaControl, (void**) &mediaControl);
  212720. if (FAILED (hr))
  212721. return;
  212722. {
  212723. ComSmartPtr <IAMStreamConfig> streamConfig;
  212724. hr = captureGraphBuilder->FindInterface (&PIN_CATEGORY_CAPTURE, 0, filter,
  212725. IID_IAMStreamConfig, (void**) &streamConfig);
  212726. if (streamConfig != 0)
  212727. {
  212728. getVideoSizes (streamConfig);
  212729. if (! selectVideoSize (streamConfig, minWidth, minHeight, maxWidth, maxHeight))
  212730. return;
  212731. }
  212732. }
  212733. hr = graphBuilder->AddFilter (filter, _T("Video Capture"));
  212734. if (FAILED (hr))
  212735. return;
  212736. hr = smartTee.CoCreateInstance (CLSID_SmartTee);
  212737. if (FAILED (hr))
  212738. return;
  212739. hr = graphBuilder->AddFilter (smartTee, _T("Smart Tee"));
  212740. if (FAILED (hr))
  212741. return;
  212742. if (! connectFilters (filter, smartTee))
  212743. return;
  212744. ComSmartPtr <IBaseFilter> sampleGrabberBase;
  212745. hr = sampleGrabberBase.CoCreateInstance (CLSID_SampleGrabber);
  212746. if (FAILED (hr))
  212747. return;
  212748. hr = sampleGrabberBase->QueryInterface (IID_ISampleGrabber, (void**) &sampleGrabber);
  212749. if (FAILED (hr))
  212750. return;
  212751. AM_MEDIA_TYPE mt;
  212752. zerostruct (mt);
  212753. mt.majortype = MEDIATYPE_Video;
  212754. mt.subtype = MEDIASUBTYPE_RGB24;
  212755. mt.formattype = FORMAT_VideoInfo;
  212756. sampleGrabber->SetMediaType (&mt);
  212757. callback = new GrabberCallback (*this);
  212758. sampleGrabber->SetCallback (callback, 1);
  212759. hr = graphBuilder->AddFilter (sampleGrabberBase, _T("Sample Grabber"));
  212760. if (FAILED (hr))
  212761. return;
  212762. ComSmartPtr <IPin> grabberInputPin;
  212763. if (! (getPin (smartTee, PINDIR_OUTPUT, &smartTeeCaptureOutputPin, "capture")
  212764. && getPin (smartTee, PINDIR_OUTPUT, &smartTeePreviewOutputPin, "preview")
  212765. && getPin (sampleGrabberBase, PINDIR_INPUT, &grabberInputPin)))
  212766. return;
  212767. hr = graphBuilder->Connect (smartTeePreviewOutputPin, grabberInputPin);
  212768. if (FAILED (hr))
  212769. return;
  212770. zerostruct (mt);
  212771. hr = sampleGrabber->GetConnectedMediaType (&mt);
  212772. VIDEOINFOHEADER* pVih = (VIDEOINFOHEADER*) (mt.pbFormat);
  212773. width = pVih->bmiHeader.biWidth;
  212774. height = pVih->bmiHeader.biHeight;
  212775. ComSmartPtr <IBaseFilter> nullFilter;
  212776. hr = nullFilter.CoCreateInstance (CLSID_NullRenderer);
  212777. hr = graphBuilder->AddFilter (nullFilter, _T("Null Renderer"));
  212778. if (connectFilters (sampleGrabberBase, nullFilter)
  212779. && addGraphToRot())
  212780. {
  212781. activeImage = new Image (Image::RGB, width, height, true);
  212782. loadingImage = new Image (Image::RGB, width, height, true);
  212783. ok = true;
  212784. }
  212785. }
  212786. ~DShowCameraDeviceInteral()
  212787. {
  212788. if (mediaControl != 0)
  212789. mediaControl->Stop();
  212790. removeGraphFromRot();
  212791. for (int i = viewerComps.size(); --i >= 0;)
  212792. ((DShowCaptureViewerComp*) viewerComps.getUnchecked(i))->ownerDeleted();
  212793. callback = 0;
  212794. graphBuilder = 0;
  212795. sampleGrabber = 0;
  212796. mediaControl = 0;
  212797. filter = 0;
  212798. captureGraphBuilder = 0;
  212799. smartTee = 0;
  212800. smartTeePreviewOutputPin = 0;
  212801. smartTeeCaptureOutputPin = 0;
  212802. asfWriter = 0;
  212803. delete activeImage;
  212804. delete loadingImage;
  212805. }
  212806. void addUser()
  212807. {
  212808. if (ok && activeUsers++ == 0)
  212809. mediaControl->Run();
  212810. }
  212811. void removeUser()
  212812. {
  212813. if (ok && --activeUsers == 0)
  212814. mediaControl->Stop();
  212815. }
  212816. void handleFrame (double /*time*/, BYTE* buffer, long /*bufferSize*/)
  212817. {
  212818. if (recordNextFrameTime)
  212819. {
  212820. const double defaultCameraLatency = 0.1;
  212821. firstRecordedTime = Time::getCurrentTime() - RelativeTime (defaultCameraLatency);
  212822. recordNextFrameTime = false;
  212823. ComSmartPtr <IPin> pin;
  212824. if (getPin (filter, PINDIR_OUTPUT, &pin))
  212825. {
  212826. ComSmartPtr <IAMPushSource> pushSource;
  212827. HRESULT hr = pin->QueryInterface (IID_IAMPushSource, (void**) &pushSource);
  212828. if (pushSource != 0)
  212829. {
  212830. REFERENCE_TIME latency = 0;
  212831. hr = pushSource->GetLatency (&latency);
  212832. firstRecordedTime = firstRecordedTime - RelativeTime ((double) latency);
  212833. }
  212834. }
  212835. }
  212836. {
  212837. const int lineStride = width * 3;
  212838. const ScopedLock sl (imageSwapLock);
  212839. {
  212840. const Image::BitmapData destData (*loadingImage, 0, 0, width, height, true);
  212841. for (int i = 0; i < height; ++i)
  212842. memcpy (destData.getLinePointer ((height - 1) - i),
  212843. buffer + lineStride * i,
  212844. lineStride);
  212845. }
  212846. imageNeedsFlipping = true;
  212847. }
  212848. if (listeners.size() > 0)
  212849. callListeners (*loadingImage);
  212850. sendChangeMessage (this);
  212851. }
  212852. void drawCurrentImage (Graphics& g, int x, int y, int w, int h)
  212853. {
  212854. if (imageNeedsFlipping)
  212855. {
  212856. const ScopedLock sl (imageSwapLock);
  212857. swapVariables (loadingImage, activeImage);
  212858. imageNeedsFlipping = false;
  212859. }
  212860. RectanglePlacement rp (RectanglePlacement::centred);
  212861. double dx = 0, dy = 0, dw = width, dh = height;
  212862. rp.applyTo (dx, dy, dw, dh, x, y, w, h);
  212863. const int rx = roundToInt (dx), ry = roundToInt (dy);
  212864. const int rw = roundToInt (dw), rh = roundToInt (dh);
  212865. g.saveState();
  212866. g.excludeClipRegion (Rectangle<int> (rx, ry, rw, rh));
  212867. g.fillAll (Colours::black);
  212868. g.restoreState();
  212869. g.drawImage (activeImage, rx, ry, rw, rh, 0, 0, width, height);
  212870. }
  212871. bool createFileCaptureFilter (const File& file)
  212872. {
  212873. removeFileCaptureFilter();
  212874. file.deleteFile();
  212875. mediaControl->Stop();
  212876. firstRecordedTime = Time();
  212877. recordNextFrameTime = true;
  212878. HRESULT hr = asfWriter.CoCreateInstance (CLSID_WMAsfWriter);
  212879. if (SUCCEEDED (hr))
  212880. {
  212881. ComSmartPtr <IFileSinkFilter> fileSink;
  212882. hr = asfWriter->QueryInterface (IID_IFileSinkFilter, (void**) &fileSink);
  212883. if (SUCCEEDED (hr))
  212884. {
  212885. hr = fileSink->SetFileName (file.getFullPathName(), 0);
  212886. if (SUCCEEDED (hr))
  212887. {
  212888. hr = graphBuilder->AddFilter (asfWriter, _T("AsfWriter"));
  212889. if (SUCCEEDED (hr))
  212890. {
  212891. ComSmartPtr <IConfigAsfWriter> asfConfig;
  212892. hr = asfWriter->QueryInterface (IID_IConfigAsfWriter, (void**) &asfConfig);
  212893. asfConfig->SetIndexMode (true);
  212894. ComSmartPtr <IWMProfileManager> profileManager;
  212895. hr = WMCreateProfileManager (&profileManager);
  212896. // This gibberish is the DirectShow profile for a video-only wmv file.
  212897. String prof ("<profile version=\"589824\" storageformat=\"1\" name=\"Quality\" description=\"Quality type for output.\"><streamconfig "
  212898. "majortype=\"{73646976-0000-0010-8000-00AA00389B71}\" streamnumber=\"1\" streamname=\"Video Stream\" inputname=\"Video409\" bitrate=\"894960\" "
  212899. "bufferwindow=\"0\" reliabletransport=\"1\" decodercomplexity=\"AU\" rfc1766langid=\"en-us\"><videomediaprops maxkeyframespacing=\"50000000\" quality=\"90\"/>"
  212900. "<wmmediatype subtype=\"{33564D57-0000-0010-8000-00AA00389B71}\" bfixedsizesamples=\"0\" btemporalcompression=\"1\" lsamplesize=\"0\"> <videoinfoheader "
  212901. "dwbitrate=\"894960\" dwbiterrorrate=\"0\" avgtimeperframe=\"100000\"><rcsource left=\"0\" top=\"0\" right=\"$WIDTH\" bottom=\"$HEIGHT\"/> <rctarget "
  212902. "left=\"0\" top=\"0\" right=\"$WIDTH\" bottom=\"$HEIGHT\"/> <bitmapinfoheader biwidth=\"$WIDTH\" biheight=\"$HEIGHT\" biplanes=\"1\" bibitcount=\"24\" "
  212903. "bicompression=\"WMV3\" bisizeimage=\"0\" bixpelspermeter=\"0\" biypelspermeter=\"0\" biclrused=\"0\" biclrimportant=\"0\"/> "
  212904. "</videoinfoheader></wmmediatype></streamconfig></profile>");
  212905. prof = prof.replace ("$WIDTH", String (width))
  212906. .replace ("$HEIGHT", String (height));
  212907. ComSmartPtr <IWMProfile> currentProfile;
  212908. hr = profileManager->LoadProfileByData ((const WCHAR*) prof, &currentProfile);
  212909. hr = asfConfig->ConfigureFilterUsingProfile (currentProfile);
  212910. if (SUCCEEDED (hr))
  212911. {
  212912. ComSmartPtr <IPin> asfWriterInputPin;
  212913. if (getPin (asfWriter, PINDIR_INPUT, &asfWriterInputPin, "Video Input 01"))
  212914. {
  212915. hr = graphBuilder->Connect (smartTeeCaptureOutputPin, asfWriterInputPin);
  212916. if (SUCCEEDED (hr)
  212917. && ok && activeUsers > 0
  212918. && SUCCEEDED (mediaControl->Run()))
  212919. {
  212920. return true;
  212921. }
  212922. }
  212923. }
  212924. }
  212925. }
  212926. }
  212927. }
  212928. removeFileCaptureFilter();
  212929. if (ok && activeUsers > 0)
  212930. mediaControl->Run();
  212931. return false;
  212932. }
  212933. void removeFileCaptureFilter()
  212934. {
  212935. mediaControl->Stop();
  212936. if (asfWriter != 0)
  212937. {
  212938. graphBuilder->RemoveFilter (asfWriter);
  212939. asfWriter = 0;
  212940. }
  212941. if (ok && activeUsers > 0)
  212942. mediaControl->Run();
  212943. }
  212944. void addListener (CameraImageListener* listenerToAdd)
  212945. {
  212946. const ScopedLock sl (listenerLock);
  212947. if (listeners.size() == 0)
  212948. addUser();
  212949. listeners.addIfNotAlreadyThere (listenerToAdd);
  212950. }
  212951. void removeListener (CameraImageListener* listenerToRemove)
  212952. {
  212953. const ScopedLock sl (listenerLock);
  212954. listeners.removeValue (listenerToRemove);
  212955. if (listeners.size() == 0)
  212956. removeUser();
  212957. }
  212958. void callListeners (Image& image)
  212959. {
  212960. const ScopedLock sl (listenerLock);
  212961. for (int i = listeners.size(); --i >= 0;)
  212962. {
  212963. CameraImageListener* l = (CameraImageListener*) listeners[i];
  212964. if (l != 0)
  212965. l->imageReceived (image);
  212966. }
  212967. }
  212968. class DShowCaptureViewerComp : public Component,
  212969. public ChangeListener
  212970. {
  212971. public:
  212972. DShowCaptureViewerComp (DShowCameraDeviceInteral* const owner_)
  212973. : owner (owner_)
  212974. {
  212975. setOpaque (true);
  212976. owner->addChangeListener (this);
  212977. owner->addUser();
  212978. owner->viewerComps.add (this);
  212979. setSize (owner_->width, owner_->height);
  212980. }
  212981. ~DShowCaptureViewerComp()
  212982. {
  212983. if (owner != 0)
  212984. {
  212985. owner->viewerComps.removeValue (this);
  212986. owner->removeUser();
  212987. owner->removeChangeListener (this);
  212988. }
  212989. }
  212990. void ownerDeleted()
  212991. {
  212992. owner = 0;
  212993. }
  212994. void paint (Graphics& g)
  212995. {
  212996. g.setColour (Colours::black);
  212997. g.setImageResamplingQuality (Graphics::lowResamplingQuality);
  212998. if (owner != 0)
  212999. owner->drawCurrentImage (g, 0, 0, getWidth(), getHeight());
  213000. else
  213001. g.fillAll (Colours::black);
  213002. }
  213003. void changeListenerCallback (void*)
  213004. {
  213005. repaint();
  213006. }
  213007. private:
  213008. DShowCameraDeviceInteral* owner;
  213009. };
  213010. bool ok;
  213011. int width, height;
  213012. Time firstRecordedTime;
  213013. VoidArray viewerComps;
  213014. private:
  213015. CameraDevice* const owner;
  213016. ComSmartPtr <ICaptureGraphBuilder2> captureGraphBuilder;
  213017. ComSmartPtr <IBaseFilter> filter;
  213018. ComSmartPtr <IBaseFilter> smartTee;
  213019. ComSmartPtr <IGraphBuilder> graphBuilder;
  213020. ComSmartPtr <ISampleGrabber> sampleGrabber;
  213021. ComSmartPtr <IMediaControl> mediaControl;
  213022. ComSmartPtr <IPin> smartTeePreviewOutputPin;
  213023. ComSmartPtr <IPin> smartTeeCaptureOutputPin;
  213024. ComSmartPtr <IBaseFilter> asfWriter;
  213025. int activeUsers;
  213026. Array <int> widths, heights;
  213027. DWORD graphRegistrationID;
  213028. CriticalSection imageSwapLock;
  213029. bool imageNeedsFlipping;
  213030. Image* loadingImage;
  213031. Image* activeImage;
  213032. bool recordNextFrameTime;
  213033. void getVideoSizes (IAMStreamConfig* const streamConfig)
  213034. {
  213035. widths.clear();
  213036. heights.clear();
  213037. int count = 0, size = 0;
  213038. streamConfig->GetNumberOfCapabilities (&count, &size);
  213039. if (size == sizeof (VIDEO_STREAM_CONFIG_CAPS))
  213040. {
  213041. for (int i = 0; i < count; ++i)
  213042. {
  213043. VIDEO_STREAM_CONFIG_CAPS scc;
  213044. AM_MEDIA_TYPE* config;
  213045. HRESULT hr = streamConfig->GetStreamCaps (i, &config, (BYTE*) &scc);
  213046. if (SUCCEEDED (hr))
  213047. {
  213048. const int w = scc.InputSize.cx;
  213049. const int h = scc.InputSize.cy;
  213050. bool duplicate = false;
  213051. for (int j = widths.size(); --j >= 0;)
  213052. {
  213053. if (w == widths.getUnchecked (j) && h == heights.getUnchecked (j))
  213054. {
  213055. duplicate = true;
  213056. break;
  213057. }
  213058. }
  213059. if (! duplicate)
  213060. {
  213061. DBG ("Camera capture size: " + String (w) + ", " + String (h));
  213062. widths.add (w);
  213063. heights.add (h);
  213064. }
  213065. deleteMediaType (config);
  213066. }
  213067. }
  213068. }
  213069. }
  213070. bool selectVideoSize (IAMStreamConfig* const streamConfig,
  213071. const int minWidth, const int minHeight,
  213072. const int maxWidth, const int maxHeight)
  213073. {
  213074. int count = 0, size = 0, bestArea = 0, bestIndex = -1;
  213075. streamConfig->GetNumberOfCapabilities (&count, &size);
  213076. if (size == sizeof (VIDEO_STREAM_CONFIG_CAPS))
  213077. {
  213078. AM_MEDIA_TYPE* config;
  213079. VIDEO_STREAM_CONFIG_CAPS scc;
  213080. for (int i = 0; i < count; ++i)
  213081. {
  213082. HRESULT hr = streamConfig->GetStreamCaps (i, &config, (BYTE*) &scc);
  213083. if (SUCCEEDED (hr))
  213084. {
  213085. if (scc.InputSize.cx >= minWidth
  213086. && scc.InputSize.cy >= minHeight
  213087. && scc.InputSize.cx <= maxWidth
  213088. && scc.InputSize.cy <= maxHeight)
  213089. {
  213090. int area = scc.InputSize.cx * scc.InputSize.cy;
  213091. if (area > bestArea)
  213092. {
  213093. bestIndex = i;
  213094. bestArea = area;
  213095. }
  213096. }
  213097. deleteMediaType (config);
  213098. }
  213099. }
  213100. if (bestIndex >= 0)
  213101. {
  213102. HRESULT hr = streamConfig->GetStreamCaps (bestIndex, &config, (BYTE*) &scc);
  213103. hr = streamConfig->SetFormat (config);
  213104. deleteMediaType (config);
  213105. return SUCCEEDED (hr);
  213106. }
  213107. }
  213108. return false;
  213109. }
  213110. static bool getPin (IBaseFilter* filter, const PIN_DIRECTION wantedDirection, IPin** result, const char* pinName = 0)
  213111. {
  213112. ComSmartPtr <IEnumPins> enumerator;
  213113. ComSmartPtr <IPin> pin;
  213114. filter->EnumPins (&enumerator);
  213115. while (enumerator->Next (1, &pin, 0) == S_OK)
  213116. {
  213117. PIN_DIRECTION dir;
  213118. pin->QueryDirection (&dir);
  213119. if (wantedDirection == dir)
  213120. {
  213121. PIN_INFO info;
  213122. zerostruct (info);
  213123. pin->QueryPinInfo (&info);
  213124. if (pinName == 0 || String (pinName).equalsIgnoreCase (String (info.achName)))
  213125. {
  213126. pin->AddRef();
  213127. *result = pin;
  213128. return true;
  213129. }
  213130. }
  213131. }
  213132. return false;
  213133. }
  213134. bool connectFilters (IBaseFilter* const first, IBaseFilter* const second) const
  213135. {
  213136. ComSmartPtr <IPin> in, out;
  213137. return getPin (first, PINDIR_OUTPUT, &out)
  213138. && getPin (second, PINDIR_INPUT, &in)
  213139. && SUCCEEDED (graphBuilder->Connect (out, in));
  213140. }
  213141. bool addGraphToRot()
  213142. {
  213143. ComSmartPtr <IRunningObjectTable> rot;
  213144. if (FAILED (GetRunningObjectTable (0, &rot)))
  213145. return false;
  213146. ComSmartPtr <IMoniker> moniker;
  213147. WCHAR buffer[128];
  213148. HRESULT hr = CreateItemMoniker (_T("!"), buffer, &moniker);
  213149. if (FAILED (hr))
  213150. return false;
  213151. graphRegistrationID = 0;
  213152. return SUCCEEDED (rot->Register (0, graphBuilder, moniker, &graphRegistrationID));
  213153. }
  213154. void removeGraphFromRot()
  213155. {
  213156. ComSmartPtr <IRunningObjectTable> rot;
  213157. if (SUCCEEDED (GetRunningObjectTable (0, &rot)))
  213158. rot->Revoke (graphRegistrationID);
  213159. }
  213160. static void deleteMediaType (AM_MEDIA_TYPE* const pmt)
  213161. {
  213162. if (pmt->cbFormat != 0)
  213163. CoTaskMemFree ((PVOID) pmt->pbFormat);
  213164. if (pmt->pUnk != 0)
  213165. pmt->pUnk->Release();
  213166. CoTaskMemFree (pmt);
  213167. }
  213168. class GrabberCallback : public ComBaseClassHelper <ISampleGrabberCB>
  213169. {
  213170. public:
  213171. GrabberCallback (DShowCameraDeviceInteral& owner_)
  213172. : owner (owner_)
  213173. {
  213174. }
  213175. STDMETHODIMP SampleCB (double /*SampleTime*/, IMediaSample* /*pSample*/)
  213176. {
  213177. return E_FAIL;
  213178. }
  213179. STDMETHODIMP BufferCB (double time, BYTE* buffer, long bufferSize)
  213180. {
  213181. owner.handleFrame (time, buffer, bufferSize);
  213182. return S_OK;
  213183. }
  213184. private:
  213185. DShowCameraDeviceInteral& owner;
  213186. GrabberCallback (const GrabberCallback&);
  213187. GrabberCallback& operator= (const GrabberCallback&);
  213188. };
  213189. ComSmartPtr <GrabberCallback> callback;
  213190. VoidArray listeners;
  213191. CriticalSection listenerLock;
  213192. DShowCameraDeviceInteral (const DShowCameraDeviceInteral&);
  213193. DShowCameraDeviceInteral& operator= (const DShowCameraDeviceInteral&);
  213194. };
  213195. CameraDevice::CameraDevice (const String& name_, int /*index*/)
  213196. : name (name_)
  213197. {
  213198. isRecording = false;
  213199. }
  213200. CameraDevice::~CameraDevice()
  213201. {
  213202. stopRecording();
  213203. delete static_cast <DShowCameraDeviceInteral*> (internal);
  213204. internal = 0;
  213205. }
  213206. Component* CameraDevice::createViewerComponent()
  213207. {
  213208. return new DShowCameraDeviceInteral::DShowCaptureViewerComp (static_cast <DShowCameraDeviceInteral*> (internal));
  213209. }
  213210. const String CameraDevice::getFileExtension()
  213211. {
  213212. return ".wmv";
  213213. }
  213214. void CameraDevice::startRecordingToFile (const File& file, int quality)
  213215. {
  213216. stopRecording();
  213217. DShowCameraDeviceInteral* const d = (DShowCameraDeviceInteral*) internal;
  213218. d->addUser();
  213219. isRecording = d->createFileCaptureFilter (file);
  213220. }
  213221. const Time CameraDevice::getTimeOfFirstRecordedFrame() const
  213222. {
  213223. DShowCameraDeviceInteral* const d = (DShowCameraDeviceInteral*) internal;
  213224. return d->firstRecordedTime;
  213225. }
  213226. void CameraDevice::stopRecording()
  213227. {
  213228. if (isRecording)
  213229. {
  213230. DShowCameraDeviceInteral* const d = (DShowCameraDeviceInteral*) internal;
  213231. d->removeFileCaptureFilter();
  213232. d->removeUser();
  213233. isRecording = false;
  213234. }
  213235. }
  213236. void CameraDevice::addListener (CameraImageListener* listenerToAdd)
  213237. {
  213238. DShowCameraDeviceInteral* const d = (DShowCameraDeviceInteral*) internal;
  213239. if (listenerToAdd != 0)
  213240. d->addListener (listenerToAdd);
  213241. }
  213242. void CameraDevice::removeListener (CameraImageListener* listenerToRemove)
  213243. {
  213244. DShowCameraDeviceInteral* const d = (DShowCameraDeviceInteral*) internal;
  213245. if (listenerToRemove != 0)
  213246. d->removeListener (listenerToRemove);
  213247. }
  213248. static ComSmartPtr <IBaseFilter> enumerateCameras (StringArray* const names,
  213249. const int deviceIndexToOpen,
  213250. String& name)
  213251. {
  213252. int index = 0;
  213253. ComSmartPtr <IBaseFilter> result;
  213254. ComSmartPtr <ICreateDevEnum> pDevEnum;
  213255. HRESULT hr = pDevEnum.CoCreateInstance (CLSID_SystemDeviceEnum);
  213256. if (SUCCEEDED (hr))
  213257. {
  213258. ComSmartPtr <IEnumMoniker> enumerator;
  213259. hr = pDevEnum->CreateClassEnumerator (CLSID_VideoInputDeviceCategory, &enumerator, 0);
  213260. if (SUCCEEDED (hr) && enumerator != 0)
  213261. {
  213262. ComSmartPtr <IBaseFilter> captureFilter;
  213263. ComSmartPtr <IMoniker> moniker;
  213264. ULONG fetched;
  213265. while (enumerator->Next (1, &moniker, &fetched) == S_OK)
  213266. {
  213267. hr = moniker->BindToObject (0, 0, IID_IBaseFilter, (void**) &captureFilter);
  213268. if (SUCCEEDED (hr))
  213269. {
  213270. ComSmartPtr <IPropertyBag> propertyBag;
  213271. hr = moniker->BindToStorage (0, 0, IID_IPropertyBag, (void**) &propertyBag);
  213272. if (SUCCEEDED (hr))
  213273. {
  213274. VARIANT var;
  213275. var.vt = VT_BSTR;
  213276. hr = propertyBag->Read (_T("FriendlyName"), &var, 0);
  213277. propertyBag = 0;
  213278. if (SUCCEEDED (hr))
  213279. {
  213280. if (names != 0)
  213281. names->add (var.bstrVal);
  213282. if (index == deviceIndexToOpen)
  213283. {
  213284. name = var.bstrVal;
  213285. result = captureFilter;
  213286. captureFilter = 0;
  213287. break;
  213288. }
  213289. ++index;
  213290. }
  213291. moniker = 0;
  213292. }
  213293. captureFilter = 0;
  213294. }
  213295. }
  213296. }
  213297. }
  213298. return result;
  213299. }
  213300. const StringArray CameraDevice::getAvailableDevices()
  213301. {
  213302. StringArray devs;
  213303. String dummy;
  213304. enumerateCameras (&devs, -1, dummy);
  213305. return devs;
  213306. }
  213307. CameraDevice* CameraDevice::openDevice (int index,
  213308. int minWidth, int minHeight,
  213309. int maxWidth, int maxHeight)
  213310. {
  213311. ComSmartPtr <ICaptureGraphBuilder2> captureGraphBuilder;
  213312. HRESULT hr = captureGraphBuilder.CoCreateInstance (CLSID_CaptureGraphBuilder2);
  213313. if (SUCCEEDED (hr))
  213314. {
  213315. String name;
  213316. const ComSmartPtr <IBaseFilter> filter (enumerateCameras (0, index, name));
  213317. if (filter != 0)
  213318. {
  213319. ScopedPointer <CameraDevice> cam (new CameraDevice (name, index));
  213320. DShowCameraDeviceInteral* const intern
  213321. = new DShowCameraDeviceInteral (cam, captureGraphBuilder, filter,
  213322. minWidth, minHeight, maxWidth, maxHeight);
  213323. cam->internal = intern;
  213324. if (intern->ok)
  213325. return cam.release();
  213326. }
  213327. }
  213328. return 0;
  213329. }
  213330. #endif
  213331. /*** End of inlined file: juce_win32_CameraDevice.cpp ***/
  213332. #endif
  213333. // Auto-link the other win32 libs that are needed by library calls..
  213334. #if (JUCE_AMALGAMATED_TEMPLATE || defined (JUCE_DLL_BUILD)) && JUCE_MSVC && ! DONT_AUTOLINK_TO_WIN32_LIBRARIES
  213335. /*** Start of inlined file: juce_win32_AutoLinkLibraries.h ***/
  213336. // Auto-links to various win32 libs that are needed by library calls..
  213337. #pragma comment(lib, "kernel32.lib")
  213338. #pragma comment(lib, "user32.lib")
  213339. #pragma comment(lib, "shell32.lib")
  213340. #pragma comment(lib, "gdi32.lib")
  213341. #pragma comment(lib, "vfw32.lib")
  213342. #pragma comment(lib, "comdlg32.lib")
  213343. #pragma comment(lib, "winmm.lib")
  213344. #pragma comment(lib, "wininet.lib")
  213345. #pragma comment(lib, "ole32.lib")
  213346. #pragma comment(lib, "oleaut32.lib")
  213347. #pragma comment(lib, "advapi32.lib")
  213348. #pragma comment(lib, "ws2_32.lib")
  213349. #pragma comment(lib, "comsupp.lib")
  213350. #pragma comment(lib, "version.lib")
  213351. #if JUCE_OPENGL
  213352. #pragma comment(lib, "OpenGL32.Lib")
  213353. #pragma comment(lib, "GlU32.Lib")
  213354. #endif
  213355. #if JUCE_QUICKTIME
  213356. #pragma comment (lib, "QTMLClient.lib")
  213357. #endif
  213358. #if JUCE_USE_CAMERA
  213359. #pragma comment (lib, "Strmiids.lib")
  213360. #pragma comment (lib, "wmvcore.lib")
  213361. #endif
  213362. /*** End of inlined file: juce_win32_AutoLinkLibraries.h ***/
  213363. #endif
  213364. END_JUCE_NAMESPACE
  213365. #endif
  213366. /*** End of inlined file: juce_win32_NativeCode.cpp ***/
  213367. #endif
  213368. #if JUCE_LINUX
  213369. /*** Start of inlined file: juce_linux_NativeCode.cpp ***/
  213370. /*
  213371. This file wraps together all the mac-specific code, so that
  213372. we can include all the native headers just once, and compile all our
  213373. platform-specific stuff in one big lump, keeping it out of the way of
  213374. the rest of the codebase.
  213375. */
  213376. #if JUCE_LINUX
  213377. BEGIN_JUCE_NAMESPACE
  213378. #define JUCE_INCLUDED_FILE 1
  213379. // Now include the actual code files..
  213380. /*** Start of inlined file: juce_posix_SharedCode.h ***/
  213381. /*
  213382. This file contains posix routines that are common to both the Linux and Mac builds.
  213383. It gets included directly in the cpp files for these platforms.
  213384. */
  213385. CriticalSection::CriticalSection() throw()
  213386. {
  213387. pthread_mutexattr_t atts;
  213388. pthread_mutexattr_init (&atts);
  213389. pthread_mutexattr_settype (&atts, PTHREAD_MUTEX_RECURSIVE);
  213390. pthread_mutex_init (&internal, &atts);
  213391. }
  213392. CriticalSection::~CriticalSection() throw()
  213393. {
  213394. pthread_mutex_destroy (&internal);
  213395. }
  213396. void CriticalSection::enter() const throw()
  213397. {
  213398. pthread_mutex_lock (&internal);
  213399. }
  213400. bool CriticalSection::tryEnter() const throw()
  213401. {
  213402. return pthread_mutex_trylock (&internal) == 0;
  213403. }
  213404. void CriticalSection::exit() const throw()
  213405. {
  213406. pthread_mutex_unlock (&internal);
  213407. }
  213408. class WaitableEventImpl
  213409. {
  213410. public:
  213411. WaitableEventImpl (const bool manualReset_)
  213412. : triggered (false),
  213413. manualReset (manualReset_)
  213414. {
  213415. pthread_cond_init (&condition, 0);
  213416. pthread_mutex_init (&mutex, 0);
  213417. }
  213418. ~WaitableEventImpl()
  213419. {
  213420. pthread_cond_destroy (&condition);
  213421. pthread_mutex_destroy (&mutex);
  213422. }
  213423. bool wait (const int timeOutMillisecs) throw()
  213424. {
  213425. pthread_mutex_lock (&mutex);
  213426. if (! triggered)
  213427. {
  213428. if (timeOutMillisecs < 0)
  213429. {
  213430. do
  213431. {
  213432. pthread_cond_wait (&condition, &mutex);
  213433. }
  213434. while (! triggered);
  213435. }
  213436. else
  213437. {
  213438. struct timeval now;
  213439. gettimeofday (&now, 0);
  213440. struct timespec time;
  213441. time.tv_sec = now.tv_sec + (timeOutMillisecs / 1000);
  213442. time.tv_nsec = (now.tv_usec + ((timeOutMillisecs % 1000) * 1000)) * 1000;
  213443. if (time.tv_nsec >= 1000000000)
  213444. {
  213445. time.tv_nsec -= 1000000000;
  213446. time.tv_sec++;
  213447. }
  213448. do
  213449. {
  213450. if (pthread_cond_timedwait (&condition, &mutex, &time) == ETIMEDOUT)
  213451. {
  213452. pthread_mutex_unlock (&mutex);
  213453. return false;
  213454. }
  213455. }
  213456. while (! triggered);
  213457. }
  213458. }
  213459. if (! manualReset)
  213460. triggered = false;
  213461. pthread_mutex_unlock (&mutex);
  213462. return true;
  213463. }
  213464. void signal() throw()
  213465. {
  213466. pthread_mutex_lock (&mutex);
  213467. triggered = true;
  213468. pthread_cond_broadcast (&condition);
  213469. pthread_mutex_unlock (&mutex);
  213470. }
  213471. void reset() throw()
  213472. {
  213473. pthread_mutex_lock (&mutex);
  213474. triggered = false;
  213475. pthread_mutex_unlock (&mutex);
  213476. }
  213477. private:
  213478. pthread_cond_t condition;
  213479. pthread_mutex_t mutex;
  213480. bool triggered;
  213481. const bool manualReset;
  213482. WaitableEventImpl (const WaitableEventImpl&);
  213483. WaitableEventImpl& operator= (const WaitableEventImpl&);
  213484. };
  213485. WaitableEvent::WaitableEvent (const bool manualReset) throw()
  213486. : internal (new WaitableEventImpl (manualReset))
  213487. {
  213488. }
  213489. WaitableEvent::~WaitableEvent() throw()
  213490. {
  213491. delete static_cast <WaitableEventImpl*> (internal);
  213492. }
  213493. bool WaitableEvent::wait (const int timeOutMillisecs) const throw()
  213494. {
  213495. return static_cast <WaitableEventImpl*> (internal)->wait (timeOutMillisecs);
  213496. }
  213497. void WaitableEvent::signal() const throw()
  213498. {
  213499. static_cast <WaitableEventImpl*> (internal)->signal();
  213500. }
  213501. void WaitableEvent::reset() const throw()
  213502. {
  213503. static_cast <WaitableEventImpl*> (internal)->reset();
  213504. }
  213505. void JUCE_CALLTYPE Thread::sleep (int millisecs)
  213506. {
  213507. struct timespec time;
  213508. time.tv_sec = millisecs / 1000;
  213509. time.tv_nsec = (millisecs % 1000) * 1000000;
  213510. nanosleep (&time, 0);
  213511. }
  213512. const juce_wchar File::separator = '/';
  213513. const String File::separatorString ("/");
  213514. const File File::getCurrentWorkingDirectory()
  213515. {
  213516. HeapBlock<char> heapBuffer;
  213517. char localBuffer [1024];
  213518. char* cwd = getcwd (localBuffer, sizeof (localBuffer) - 1);
  213519. int bufferSize = 4096;
  213520. while (cwd == 0 && errno == ERANGE)
  213521. {
  213522. heapBuffer.malloc (bufferSize);
  213523. cwd = getcwd (heapBuffer, bufferSize - 1);
  213524. bufferSize += 1024;
  213525. }
  213526. return File (String::fromUTF8 (cwd));
  213527. }
  213528. bool File::setAsCurrentWorkingDirectory() const
  213529. {
  213530. return chdir (getFullPathName().toUTF8()) == 0;
  213531. }
  213532. static bool juce_stat (const String& fileName, struct stat& info)
  213533. {
  213534. return fileName.isNotEmpty()
  213535. && (stat (fileName.toUTF8(), &info) == 0);
  213536. }
  213537. bool File::isDirectory() const
  213538. {
  213539. struct stat info;
  213540. return fullPath.isEmpty()
  213541. || (juce_stat (fullPath, info) && ((info.st_mode & S_IFDIR) != 0));
  213542. }
  213543. bool File::exists() const
  213544. {
  213545. return fullPath.isNotEmpty()
  213546. && access (fullPath.toUTF8(), F_OK) == 0;
  213547. }
  213548. bool File::existsAsFile() const
  213549. {
  213550. return exists() && ! isDirectory();
  213551. }
  213552. int64 File::getSize() const
  213553. {
  213554. struct stat info;
  213555. return juce_stat (fullPath, info) ? info.st_size : 0;
  213556. }
  213557. bool File::hasWriteAccess() const
  213558. {
  213559. if (exists())
  213560. return access (fullPath.toUTF8(), W_OK) == 0;
  213561. if ((! isDirectory()) && fullPath.containsChar (separator))
  213562. return getParentDirectory().hasWriteAccess();
  213563. return false;
  213564. }
  213565. bool File::setFileReadOnlyInternal (const bool shouldBeReadOnly) const
  213566. {
  213567. struct stat info;
  213568. const int res = stat (fullPath.toUTF8(), &info);
  213569. if (res != 0)
  213570. return false;
  213571. info.st_mode &= 0777; // Just permissions
  213572. if (shouldBeReadOnly)
  213573. info.st_mode &= ~(S_IWUSR | S_IWGRP | S_IWOTH);
  213574. else
  213575. // Give everybody write permission?
  213576. info.st_mode |= S_IWUSR | S_IWGRP | S_IWOTH;
  213577. return chmod (fullPath.toUTF8(), info.st_mode) == 0;
  213578. }
  213579. void File::getFileTimesInternal (int64& modificationTime, int64& accessTime, int64& creationTime) const
  213580. {
  213581. modificationTime = 0;
  213582. accessTime = 0;
  213583. creationTime = 0;
  213584. struct stat info;
  213585. const int res = stat (fullPath.toUTF8(), &info);
  213586. if (res == 0)
  213587. {
  213588. modificationTime = (int64) info.st_mtime * 1000;
  213589. accessTime = (int64) info.st_atime * 1000;
  213590. creationTime = (int64) info.st_ctime * 1000;
  213591. }
  213592. }
  213593. bool File::setFileTimesInternal (int64 modificationTime, int64 accessTime, int64 /*creationTime*/) const
  213594. {
  213595. struct utimbuf times;
  213596. times.actime = (time_t) (accessTime / 1000);
  213597. times.modtime = (time_t) (modificationTime / 1000);
  213598. return utime (fullPath.toUTF8(), &times) == 0;
  213599. }
  213600. bool File::deleteFile() const
  213601. {
  213602. if (! exists())
  213603. return true;
  213604. else if (isDirectory())
  213605. return rmdir (fullPath.toUTF8()) == 0;
  213606. else
  213607. return remove (fullPath.toUTF8()) == 0;
  213608. }
  213609. bool File::moveInternal (const File& dest) const
  213610. {
  213611. if (rename (fullPath.toUTF8(), dest.getFullPathName().toUTF8()) == 0)
  213612. return true;
  213613. if (hasWriteAccess() && copyInternal (dest))
  213614. {
  213615. if (deleteFile())
  213616. return true;
  213617. dest.deleteFile();
  213618. }
  213619. return false;
  213620. }
  213621. void File::createDirectoryInternal (const String& fileName) const
  213622. {
  213623. mkdir (fileName.toUTF8(), 0777);
  213624. }
  213625. void* juce_fileOpen (const File& file, bool forWriting)
  213626. {
  213627. int flags = O_RDONLY;
  213628. if (forWriting)
  213629. {
  213630. if (file.exists())
  213631. {
  213632. const int f = open (file.getFullPathName().toUTF8(), O_RDWR, 00644);
  213633. if (f != -1)
  213634. lseek (f, 0, SEEK_END);
  213635. return (void*) f;
  213636. }
  213637. else
  213638. {
  213639. flags = O_RDWR + O_CREAT;
  213640. }
  213641. }
  213642. return (void*) open (file.getFullPathName().toUTF8(), flags, 00644);
  213643. }
  213644. void juce_fileClose (void* handle)
  213645. {
  213646. if (handle != 0)
  213647. close ((int) (pointer_sized_int) handle);
  213648. }
  213649. int juce_fileRead (void* handle, void* buffer, int size)
  213650. {
  213651. if (handle != 0)
  213652. return jmax (0, (int) read ((int) (pointer_sized_int) handle, buffer, size));
  213653. return 0;
  213654. }
  213655. int juce_fileWrite (void* handle, const void* buffer, int size)
  213656. {
  213657. if (handle != 0)
  213658. return (int) write ((int) (pointer_sized_int) handle, buffer, size);
  213659. return 0;
  213660. }
  213661. int64 juce_fileSetPosition (void* handle, int64 pos)
  213662. {
  213663. if (handle != 0 && lseek ((int) (pointer_sized_int) handle, pos, SEEK_SET) == pos)
  213664. return pos;
  213665. return -1;
  213666. }
  213667. int64 FileOutputStream::getPositionInternal() const
  213668. {
  213669. if (fileHandle != 0)
  213670. return lseek ((int) (pointer_sized_int) fileHandle, 0, SEEK_CUR);
  213671. return -1;
  213672. }
  213673. void FileOutputStream::flushInternal()
  213674. {
  213675. if (fileHandle != 0)
  213676. fsync ((int) (pointer_sized_int) fileHandle);
  213677. }
  213678. const File juce_getExecutableFile()
  213679. {
  213680. Dl_info exeInfo;
  213681. dladdr ((const void*) juce_getExecutableFile, &exeInfo);
  213682. return File::getCurrentWorkingDirectory().getChildFile (String::fromUTF8 (exeInfo.dli_fname));
  213683. }
  213684. // if this file doesn't exist, find a parent of it that does..
  213685. static bool juce_doStatFS (File f, struct statfs& result)
  213686. {
  213687. for (int i = 5; --i >= 0;)
  213688. {
  213689. if (f.exists())
  213690. break;
  213691. f = f.getParentDirectory();
  213692. }
  213693. return statfs (f.getFullPathName().toUTF8(), &result) == 0;
  213694. }
  213695. int64 File::getBytesFreeOnVolume() const
  213696. {
  213697. struct statfs buf;
  213698. if (juce_doStatFS (*this, buf))
  213699. return (int64) buf.f_bsize * (int64) buf.f_bavail; // Note: this returns space available to non-super user
  213700. return 0;
  213701. }
  213702. int64 File::getVolumeTotalSize() const
  213703. {
  213704. struct statfs buf;
  213705. if (juce_doStatFS (*this, buf))
  213706. return (int64) buf.f_bsize * (int64) buf.f_blocks;
  213707. return 0;
  213708. }
  213709. const String File::getVolumeLabel() const
  213710. {
  213711. #if JUCE_MAC
  213712. struct VolAttrBuf
  213713. {
  213714. u_int32_t length;
  213715. attrreference_t mountPointRef;
  213716. char mountPointSpace [MAXPATHLEN];
  213717. } attrBuf;
  213718. struct attrlist attrList;
  213719. zerostruct (attrList);
  213720. attrList.bitmapcount = ATTR_BIT_MAP_COUNT;
  213721. attrList.volattr = ATTR_VOL_INFO | ATTR_VOL_NAME;
  213722. File f (*this);
  213723. for (;;)
  213724. {
  213725. if (getattrlist (f.getFullPathName().toUTF8(), &attrList, &attrBuf, sizeof (attrBuf), 0) == 0)
  213726. return String::fromUTF8 (((const char*) &attrBuf.mountPointRef) + attrBuf.mountPointRef.attr_dataoffset,
  213727. (int) attrBuf.mountPointRef.attr_length);
  213728. const File parent (f.getParentDirectory());
  213729. if (f == parent)
  213730. break;
  213731. f = parent;
  213732. }
  213733. #endif
  213734. return String::empty;
  213735. }
  213736. int File::getVolumeSerialNumber() const
  213737. {
  213738. return 0; // xxx
  213739. }
  213740. void juce_runSystemCommand (const String& command)
  213741. {
  213742. int result = system (command.toUTF8());
  213743. (void) result;
  213744. }
  213745. const String juce_getOutputFromCommand (const String& command)
  213746. {
  213747. // slight bodge here, as we just pipe the output into a temp file and read it...
  213748. const File tempFile (File::getSpecialLocation (File::tempDirectory)
  213749. .getNonexistentChildFile (String::toHexString (Random::getSystemRandom().nextInt()), ".tmp", false));
  213750. juce_runSystemCommand (command + " > " + tempFile.getFullPathName());
  213751. String result (tempFile.loadFileAsString());
  213752. tempFile.deleteFile();
  213753. return result;
  213754. }
  213755. class InterProcessLock::Pimpl
  213756. {
  213757. public:
  213758. Pimpl (const String& name, const int timeOutMillisecs)
  213759. : handle (0), refCount (1)
  213760. {
  213761. #if JUCE_MAC
  213762. // (don't use getSpecialLocation() to avoid the temp folder being different for each app)
  213763. const File temp (File ("~/Library/Caches/Juce").getChildFile (name));
  213764. #else
  213765. const File temp (File::getSpecialLocation (File::tempDirectory).getChildFile (name));
  213766. #endif
  213767. temp.create();
  213768. handle = open (temp.getFullPathName().toUTF8(), O_RDWR);
  213769. if (handle != 0)
  213770. {
  213771. struct flock fl;
  213772. zerostruct (fl);
  213773. fl.l_whence = SEEK_SET;
  213774. fl.l_type = F_WRLCK;
  213775. const int64 endTime = Time::currentTimeMillis() + timeOutMillisecs;
  213776. for (;;)
  213777. {
  213778. const int result = fcntl (handle, F_SETLK, &fl);
  213779. if (result >= 0)
  213780. return;
  213781. if (errno != EINTR)
  213782. {
  213783. if (timeOutMillisecs == 0
  213784. || (timeOutMillisecs > 0 && Time::currentTimeMillis() >= endTime))
  213785. break;
  213786. Thread::sleep (10);
  213787. }
  213788. }
  213789. }
  213790. closeFile();
  213791. }
  213792. ~Pimpl()
  213793. {
  213794. closeFile();
  213795. }
  213796. void closeFile()
  213797. {
  213798. if (handle != 0)
  213799. {
  213800. struct flock fl;
  213801. zerostruct (fl);
  213802. fl.l_whence = SEEK_SET;
  213803. fl.l_type = F_UNLCK;
  213804. while (! (fcntl (handle, F_SETLKW, &fl) >= 0 || errno != EINTR))
  213805. {}
  213806. close (handle);
  213807. handle = 0;
  213808. }
  213809. }
  213810. int handle, refCount;
  213811. };
  213812. InterProcessLock::InterProcessLock (const String& name_)
  213813. : name (name_)
  213814. {
  213815. }
  213816. InterProcessLock::~InterProcessLock()
  213817. {
  213818. }
  213819. bool InterProcessLock::enter (const int timeOutMillisecs)
  213820. {
  213821. const ScopedLock sl (lock);
  213822. if (pimpl == 0)
  213823. {
  213824. pimpl = new Pimpl (name, timeOutMillisecs);
  213825. if (pimpl->handle == 0)
  213826. pimpl = 0;
  213827. }
  213828. else
  213829. {
  213830. pimpl->refCount++;
  213831. }
  213832. return pimpl != 0;
  213833. }
  213834. void InterProcessLock::exit()
  213835. {
  213836. const ScopedLock sl (lock);
  213837. // Trying to release the lock too many times!
  213838. jassert (pimpl != 0);
  213839. if (pimpl != 0 && --(pimpl->refCount) == 0)
  213840. pimpl = 0;
  213841. }
  213842. /*** End of inlined file: juce_posix_SharedCode.h ***/
  213843. /*** Start of inlined file: juce_linux_Files.cpp ***/
  213844. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  213845. // compiled on its own).
  213846. #if JUCE_INCLUDED_FILE
  213847. static const short U_ISOFS_SUPER_MAGIC = 0x9660; // linux/iso_fs.h
  213848. static const short U_MSDOS_SUPER_MAGIC = 0x4d44; // linux/msdos_fs.h
  213849. static const short U_NFS_SUPER_MAGIC = 0x6969; // linux/nfs_fs.h
  213850. static const short U_SMB_SUPER_MAGIC = 0x517B; // linux/smb_fs.h
  213851. bool File::copyInternal (const File& dest) const
  213852. {
  213853. FileInputStream in (*this);
  213854. if (dest.deleteFile())
  213855. {
  213856. {
  213857. FileOutputStream out (dest);
  213858. if (out.failedToOpen())
  213859. return false;
  213860. if (out.writeFromInputStream (in, -1) == getSize())
  213861. return true;
  213862. }
  213863. dest.deleteFile();
  213864. }
  213865. return false;
  213866. }
  213867. void File::findFileSystemRoots (Array<File>& destArray)
  213868. {
  213869. destArray.add (File ("/"));
  213870. }
  213871. bool File::isOnCDRomDrive() const
  213872. {
  213873. struct statfs buf;
  213874. return statfs (getFullPathName().toUTF8(), &buf) == 0
  213875. && buf.f_type == U_ISOFS_SUPER_MAGIC;
  213876. }
  213877. bool File::isOnHardDisk() const
  213878. {
  213879. struct statfs buf;
  213880. if (statfs (getFullPathName().toUTF8(), &buf) == 0)
  213881. {
  213882. switch (buf.f_type)
  213883. {
  213884. case U_ISOFS_SUPER_MAGIC: // CD-ROM
  213885. case U_MSDOS_SUPER_MAGIC: // Probably floppy (but could be mounted FAT filesystem)
  213886. case U_NFS_SUPER_MAGIC: // Network NFS
  213887. case U_SMB_SUPER_MAGIC: // Network Samba
  213888. return false;
  213889. default:
  213890. // Assume anything else is a hard-disk (but note it could
  213891. // be a RAM disk. There isn't a good way of determining
  213892. // this for sure)
  213893. return true;
  213894. }
  213895. }
  213896. // Assume so if this fails for some reason
  213897. return true;
  213898. }
  213899. bool File::isOnRemovableDrive() const
  213900. {
  213901. jassertfalse // xxx not implemented for linux!
  213902. return false;
  213903. }
  213904. bool File::isHidden() const
  213905. {
  213906. return getFileName().startsWithChar ('.');
  213907. }
  213908. const char* juce_Argv0 = 0; // referenced from juce_Application.cpp
  213909. const File File::getSpecialLocation (const SpecialLocationType type)
  213910. {
  213911. switch (type)
  213912. {
  213913. case userHomeDirectory:
  213914. {
  213915. const char* homeDir = getenv ("HOME");
  213916. if (homeDir == 0)
  213917. {
  213918. struct passwd* const pw = getpwuid (getuid());
  213919. if (pw != 0)
  213920. homeDir = pw->pw_dir;
  213921. }
  213922. return File (String::fromUTF8 (homeDir));
  213923. }
  213924. case userDocumentsDirectory:
  213925. case userMusicDirectory:
  213926. case userMoviesDirectory:
  213927. case userApplicationDataDirectory:
  213928. return File ("~");
  213929. case userDesktopDirectory:
  213930. return File ("~/Desktop");
  213931. case commonApplicationDataDirectory:
  213932. return File ("/var");
  213933. case globalApplicationsDirectory:
  213934. return File ("/usr");
  213935. case tempDirectory:
  213936. {
  213937. File tmp ("/var/tmp");
  213938. if (! tmp.isDirectory())
  213939. {
  213940. tmp = "/tmp";
  213941. if (! tmp.isDirectory())
  213942. tmp = File::getCurrentWorkingDirectory();
  213943. }
  213944. return tmp;
  213945. }
  213946. case invokedExecutableFile:
  213947. if (juce_Argv0 != 0)
  213948. return File (String::fromUTF8 (juce_Argv0));
  213949. // deliberate fall-through...
  213950. case currentExecutableFile:
  213951. case currentApplicationFile:
  213952. return juce_getExecutableFile();
  213953. default:
  213954. jassertfalse // unknown type?
  213955. break;
  213956. }
  213957. return File::nonexistent;
  213958. }
  213959. const String File::getVersion() const
  213960. {
  213961. return String::empty; // xxx not yet implemented
  213962. }
  213963. const File File::getLinkedTarget() const
  213964. {
  213965. char buffer [4096];
  213966. size_t numChars = readlink (getFullPathName().toUTF8(),
  213967. buffer, sizeof (buffer));
  213968. if (numChars > 0 && numChars <= sizeof (buffer))
  213969. return File (String::fromUTF8 (buffer, (int) numChars));
  213970. return *this;
  213971. }
  213972. bool File::moveToTrash() const
  213973. {
  213974. if (! exists())
  213975. return true;
  213976. File trashCan ("~/.Trash");
  213977. if (! trashCan.isDirectory())
  213978. trashCan = "~/.local/share/Trash/files";
  213979. if (! trashCan.isDirectory())
  213980. return false;
  213981. return moveFileTo (trashCan.getNonexistentChildFile (getFileNameWithoutExtension(),
  213982. getFileExtension()));
  213983. }
  213984. class DirectoryIterator::NativeIterator::Pimpl
  213985. {
  213986. public:
  213987. Pimpl (const File& directory, const String& wildCard_)
  213988. : parentDir (File::addTrailingSeparator (directory.getFullPathName())),
  213989. wildCard (wildCard_),
  213990. dir (opendir (directory.getFullPathName().toUTF8()))
  213991. {
  213992. if (wildCard == "*.*")
  213993. wildCard = "*";
  213994. wildcardUTF8 = wildCard.toUTF8();
  213995. }
  213996. ~Pimpl()
  213997. {
  213998. if (dir != 0)
  213999. closedir (dir);
  214000. }
  214001. bool next (String& filenameFound,
  214002. bool* const isDir, bool* const isHidden, int64* const fileSize,
  214003. Time* const modTime, Time* const creationTime, bool* const isReadOnly)
  214004. {
  214005. if (dir == 0)
  214006. return false;
  214007. for (;;)
  214008. {
  214009. struct dirent* const de = readdir (dir);
  214010. if (de == 0)
  214011. return false;
  214012. if (fnmatch (wildcardUTF8, de->d_name, FNM_CASEFOLD) == 0)
  214013. {
  214014. filenameFound = String::fromUTF8 (de->d_name);
  214015. const String path (parentDir + filenameFound);
  214016. if (isDir != 0 || fileSize != 0 || modTime != 0 || creationTime != 0)
  214017. {
  214018. struct stat info;
  214019. const bool statOk = juce_stat (path, info);
  214020. if (isDir != 0) *isDir = statOk && ((info.st_mode & S_IFDIR) != 0);
  214021. if (fileSize != 0) *fileSize = statOk ? info.st_size : 0;
  214022. if (modTime != 0) *modTime = statOk ? (int64) info.st_mtime * 1000 : 0;
  214023. if (creationTime != 0) *creationTime = statOk ? (int64) info.st_ctime * 1000 : 0;
  214024. }
  214025. if (isHidden != 0)
  214026. *isHidden = filenameFound.startsWithChar ('.');
  214027. if (isReadOnly != 0)
  214028. *isReadOnly = access (path.toUTF8(), W_OK) != 0;
  214029. return true;
  214030. }
  214031. }
  214032. }
  214033. private:
  214034. String parentDir, wildCard;
  214035. const char* wildcardUTF8;
  214036. DIR* dir;
  214037. Pimpl (const Pimpl&);
  214038. Pimpl& operator= (const Pimpl&);
  214039. };
  214040. DirectoryIterator::NativeIterator::NativeIterator (const File& directory, const String& wildCard)
  214041. : pimpl (new DirectoryIterator::NativeIterator::Pimpl (directory, wildCard))
  214042. {
  214043. }
  214044. DirectoryIterator::NativeIterator::~NativeIterator()
  214045. {
  214046. }
  214047. bool DirectoryIterator::NativeIterator::next (String& filenameFound,
  214048. bool* const isDir, bool* const isHidden, int64* const fileSize,
  214049. Time* const modTime, Time* const creationTime, bool* const isReadOnly)
  214050. {
  214051. return pimpl->next (filenameFound, isDir, isHidden, fileSize, modTime, creationTime, isReadOnly);
  214052. }
  214053. bool PlatformUtilities::openDocument (const String& fileName, const String& parameters)
  214054. {
  214055. String cmdString (fileName.replace (" ", "\\ ",false));
  214056. cmdString << " " << parameters;
  214057. if (URL::isProbablyAWebsiteURL (fileName)
  214058. || cmdString.startsWithIgnoreCase ("file:")
  214059. || URL::isProbablyAnEmailAddress (fileName))
  214060. {
  214061. // create a command that tries to launch a bunch of likely browsers
  214062. const char* const browserNames[] = { "xdg-open", "/etc/alternatives/x-www-browser", "firefox", "mozilla", "konqueror", "opera" };
  214063. StringArray cmdLines;
  214064. for (int i = 0; i < numElementsInArray (browserNames); ++i)
  214065. cmdLines.add (String (browserNames[i]) + " " + cmdString.trim().quoted());
  214066. cmdString = cmdLines.joinIntoString (" || ");
  214067. }
  214068. const char* const argv[4] = { "/bin/sh", "-c", cmdString.toUTF8(), 0 };
  214069. const int cpid = fork();
  214070. if (cpid == 0)
  214071. {
  214072. setsid();
  214073. // Child process
  214074. execve (argv[0], (char**) argv, environ);
  214075. exit (0);
  214076. }
  214077. return cpid >= 0;
  214078. }
  214079. void File::revealToUser() const
  214080. {
  214081. if (isDirectory())
  214082. startAsProcess();
  214083. else if (getParentDirectory().exists())
  214084. getParentDirectory().startAsProcess();
  214085. }
  214086. #endif
  214087. /*** End of inlined file: juce_linux_Files.cpp ***/
  214088. /*** Start of inlined file: juce_posix_NamedPipe.cpp ***/
  214089. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  214090. // compiled on its own).
  214091. #if JUCE_INCLUDED_FILE
  214092. struct NamedPipeInternal
  214093. {
  214094. String pipeInName, pipeOutName;
  214095. int pipeIn, pipeOut;
  214096. bool volatile createdPipe, blocked, stopReadOperation;
  214097. static void signalHandler (int) {}
  214098. };
  214099. void NamedPipe::cancelPendingReads()
  214100. {
  214101. while (internal != 0 && ((NamedPipeInternal*) internal)->blocked)
  214102. {
  214103. NamedPipeInternal* const intern = (NamedPipeInternal*) internal;
  214104. intern->stopReadOperation = true;
  214105. char buffer [1] = { 0 };
  214106. int bytesWritten = (int) ::write (intern->pipeIn, buffer, 1);
  214107. (void) bytesWritten;
  214108. int timeout = 2000;
  214109. while (intern->blocked && --timeout >= 0)
  214110. Thread::sleep (2);
  214111. intern->stopReadOperation = false;
  214112. }
  214113. }
  214114. void NamedPipe::close()
  214115. {
  214116. NamedPipeInternal* const intern = (NamedPipeInternal*) internal;
  214117. if (intern != 0)
  214118. {
  214119. internal = 0;
  214120. if (intern->pipeIn != -1)
  214121. ::close (intern->pipeIn);
  214122. if (intern->pipeOut != -1)
  214123. ::close (intern->pipeOut);
  214124. if (intern->createdPipe)
  214125. {
  214126. unlink (intern->pipeInName.toUTF8());
  214127. unlink (intern->pipeOutName.toUTF8());
  214128. }
  214129. delete intern;
  214130. }
  214131. }
  214132. bool NamedPipe::openInternal (const String& pipeName, const bool createPipe)
  214133. {
  214134. close();
  214135. NamedPipeInternal* const intern = new NamedPipeInternal();
  214136. internal = intern;
  214137. intern->createdPipe = createPipe;
  214138. intern->blocked = false;
  214139. intern->stopReadOperation = false;
  214140. signal (SIGPIPE, NamedPipeInternal::signalHandler);
  214141. siginterrupt (SIGPIPE, 1);
  214142. const String pipePath ("/tmp/" + File::createLegalFileName (pipeName));
  214143. intern->pipeInName = pipePath + "_in";
  214144. intern->pipeOutName = pipePath + "_out";
  214145. intern->pipeIn = -1;
  214146. intern->pipeOut = -1;
  214147. if (createPipe)
  214148. {
  214149. if ((mkfifo (intern->pipeInName.toUTF8(), 0666) && errno != EEXIST)
  214150. || (mkfifo (intern->pipeOutName.toUTF8(), 0666) && errno != EEXIST))
  214151. {
  214152. delete intern;
  214153. internal = 0;
  214154. return false;
  214155. }
  214156. }
  214157. return true;
  214158. }
  214159. int NamedPipe::read (void* destBuffer, int maxBytesToRead, int /*timeOutMilliseconds*/)
  214160. {
  214161. int bytesRead = -1;
  214162. NamedPipeInternal* const intern = (NamedPipeInternal*) internal;
  214163. if (intern != 0)
  214164. {
  214165. intern->blocked = true;
  214166. if (intern->pipeIn == -1)
  214167. {
  214168. if (intern->createdPipe)
  214169. intern->pipeIn = ::open (intern->pipeInName.toUTF8(), O_RDWR);
  214170. else
  214171. intern->pipeIn = ::open (intern->pipeOutName.toUTF8(), O_RDWR);
  214172. if (intern->pipeIn == -1)
  214173. {
  214174. intern->blocked = false;
  214175. return -1;
  214176. }
  214177. }
  214178. bytesRead = 0;
  214179. char* p = (char*) destBuffer;
  214180. while (bytesRead < maxBytesToRead)
  214181. {
  214182. const int bytesThisTime = maxBytesToRead - bytesRead;
  214183. const int numRead = (int) ::read (intern->pipeIn, p, bytesThisTime);
  214184. if (numRead <= 0 || intern->stopReadOperation)
  214185. {
  214186. bytesRead = -1;
  214187. break;
  214188. }
  214189. bytesRead += numRead;
  214190. p += bytesRead;
  214191. }
  214192. intern->blocked = false;
  214193. }
  214194. return bytesRead;
  214195. }
  214196. int NamedPipe::write (const void* sourceBuffer, int numBytesToWrite, int timeOutMilliseconds)
  214197. {
  214198. int bytesWritten = -1;
  214199. NamedPipeInternal* const intern = (NamedPipeInternal*) internal;
  214200. if (intern != 0)
  214201. {
  214202. if (intern->pipeOut == -1)
  214203. {
  214204. if (intern->createdPipe)
  214205. intern->pipeOut = ::open (intern->pipeOutName.toUTF8(), O_WRONLY);
  214206. else
  214207. intern->pipeOut = ::open (intern->pipeInName.toUTF8(), O_WRONLY);
  214208. if (intern->pipeOut == -1)
  214209. {
  214210. return -1;
  214211. }
  214212. }
  214213. const char* p = (const char*) sourceBuffer;
  214214. bytesWritten = 0;
  214215. const uint32 timeOutTime = Time::getMillisecondCounter() + timeOutMilliseconds;
  214216. while (bytesWritten < numBytesToWrite
  214217. && (timeOutMilliseconds < 0 || Time::getMillisecondCounter() < timeOutTime))
  214218. {
  214219. const int bytesThisTime = numBytesToWrite - bytesWritten;
  214220. const int numWritten = (int) ::write (intern->pipeOut, p, bytesThisTime);
  214221. if (numWritten <= 0)
  214222. {
  214223. bytesWritten = -1;
  214224. break;
  214225. }
  214226. bytesWritten += numWritten;
  214227. p += bytesWritten;
  214228. }
  214229. }
  214230. return bytesWritten;
  214231. }
  214232. #endif
  214233. /*** End of inlined file: juce_posix_NamedPipe.cpp ***/
  214234. /*** Start of inlined file: juce_linux_Network.cpp ***/
  214235. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  214236. // compiled on its own).
  214237. #if JUCE_INCLUDED_FILE
  214238. int SystemStats::getMACAddresses (int64* addresses, int maxNum, const bool littleEndian)
  214239. {
  214240. int numResults = 0;
  214241. const int s = socket (AF_INET, SOCK_DGRAM, 0);
  214242. if (s != -1)
  214243. {
  214244. char buf [1024];
  214245. struct ifconf ifc;
  214246. ifc.ifc_len = sizeof (buf);
  214247. ifc.ifc_buf = buf;
  214248. ioctl (s, SIOCGIFCONF, &ifc);
  214249. for (unsigned int i = 0; i < ifc.ifc_len / sizeof (struct ifreq); ++i)
  214250. {
  214251. struct ifreq ifr;
  214252. strcpy (ifr.ifr_name, ifc.ifc_req[i].ifr_name);
  214253. if (ioctl (s, SIOCGIFFLAGS, &ifr) == 0
  214254. && (ifr.ifr_flags & IFF_LOOPBACK) == 0
  214255. && ioctl (s, SIOCGIFHWADDR, &ifr) == 0
  214256. && numResults < maxNum)
  214257. {
  214258. int64 a = 0;
  214259. for (int j = 6; --j >= 0;)
  214260. a = (a << 8) | (uint8) ifr.ifr_hwaddr.sa_data [littleEndian ? j : (5 - j)];
  214261. *addresses++ = a;
  214262. ++numResults;
  214263. }
  214264. }
  214265. close (s);
  214266. }
  214267. return numResults;
  214268. }
  214269. bool PlatformUtilities::launchEmailWithAttachments (const String& targetEmailAddress,
  214270. const String& emailSubject,
  214271. const String& bodyText,
  214272. const StringArray& filesToAttach)
  214273. {
  214274. jassertfalse // xxx todo
  214275. return false;
  214276. }
  214277. /** A HTTP input stream that uses sockets.
  214278. */
  214279. class JUCE_HTTPSocketStream
  214280. {
  214281. public:
  214282. JUCE_HTTPSocketStream()
  214283. : readPosition (0),
  214284. socketHandle (-1),
  214285. levelsOfRedirection (0),
  214286. timeoutSeconds (15)
  214287. {
  214288. }
  214289. ~JUCE_HTTPSocketStream()
  214290. {
  214291. closeSocket();
  214292. }
  214293. bool open (const String& url,
  214294. const String& headers,
  214295. const MemoryBlock& postData,
  214296. const bool isPost,
  214297. URL::OpenStreamProgressCallback* callback,
  214298. void* callbackContext,
  214299. int timeOutMs)
  214300. {
  214301. closeSocket();
  214302. uint32 timeOutTime = Time::getMillisecondCounter();
  214303. if (timeOutMs == 0)
  214304. timeOutTime += 60000;
  214305. else if (timeOutMs < 0)
  214306. timeOutTime = 0xffffffff;
  214307. else
  214308. timeOutTime += timeOutMs;
  214309. String hostName, hostPath;
  214310. int hostPort;
  214311. if (! decomposeURL (url, hostName, hostPath, hostPort))
  214312. return false;
  214313. const struct hostent* host = 0;
  214314. int port = 0;
  214315. String proxyName, proxyPath;
  214316. int proxyPort = 0;
  214317. String proxyURL (getenv ("http_proxy"));
  214318. if (proxyURL.startsWithIgnoreCase ("http://"))
  214319. {
  214320. if (! decomposeURL (proxyURL, proxyName, proxyPath, proxyPort))
  214321. return false;
  214322. host = gethostbyname (proxyName.toUTF8());
  214323. port = proxyPort;
  214324. }
  214325. else
  214326. {
  214327. host = gethostbyname (hostName.toUTF8());
  214328. port = hostPort;
  214329. }
  214330. if (host == 0)
  214331. return false;
  214332. struct sockaddr_in address;
  214333. zerostruct (address);
  214334. memcpy (&address.sin_addr, host->h_addr, host->h_length);
  214335. address.sin_family = host->h_addrtype;
  214336. address.sin_port = htons (port);
  214337. socketHandle = socket (host->h_addrtype, SOCK_STREAM, 0);
  214338. if (socketHandle == -1)
  214339. return false;
  214340. int receiveBufferSize = 16384;
  214341. setsockopt (socketHandle, SOL_SOCKET, SO_RCVBUF, (char*) &receiveBufferSize, sizeof (receiveBufferSize));
  214342. setsockopt (socketHandle, SOL_SOCKET, SO_KEEPALIVE, 0, 0);
  214343. #if JUCE_MAC
  214344. setsockopt (socketHandle, SOL_SOCKET, SO_NOSIGPIPE, 0, 0);
  214345. #endif
  214346. if (connect (socketHandle, (struct sockaddr*) &address, sizeof (address)) == -1)
  214347. {
  214348. closeSocket();
  214349. return false;
  214350. }
  214351. const MemoryBlock requestHeader (createRequestHeader (hostName, hostPort,
  214352. proxyName, proxyPort,
  214353. hostPath, url,
  214354. headers, postData,
  214355. isPost));
  214356. size_t totalHeaderSent = 0;
  214357. while (totalHeaderSent < requestHeader.getSize())
  214358. {
  214359. if (Time::getMillisecondCounter() > timeOutTime)
  214360. {
  214361. closeSocket();
  214362. return false;
  214363. }
  214364. const int numToSend = jmin (1024, (int) (requestHeader.getSize() - totalHeaderSent));
  214365. if (send (socketHandle,
  214366. ((const char*) requestHeader.getData()) + totalHeaderSent,
  214367. numToSend, 0)
  214368. != numToSend)
  214369. {
  214370. closeSocket();
  214371. return false;
  214372. }
  214373. totalHeaderSent += numToSend;
  214374. if (callback != 0 && ! callback (callbackContext, totalHeaderSent, requestHeader.getSize()))
  214375. {
  214376. closeSocket();
  214377. return false;
  214378. }
  214379. }
  214380. const String responseHeader (readResponse (timeOutTime));
  214381. if (responseHeader.isNotEmpty())
  214382. {
  214383. //DBG (responseHeader);
  214384. StringArray lines;
  214385. lines.addLines (responseHeader);
  214386. const int statusCode = responseHeader.fromFirstOccurrenceOf (" ", false, false)
  214387. .substring (0, 3).getIntValue();
  214388. //int contentLength = findHeaderItem (lines, "Content-Length:").getIntValue();
  214389. //bool isChunked = findHeaderItem (lines, "Transfer-Encoding:").equalsIgnoreCase ("chunked");
  214390. String location (findHeaderItem (lines, "Location:"));
  214391. if (statusCode >= 300 && statusCode < 400
  214392. && location.isNotEmpty())
  214393. {
  214394. if (! location.startsWithIgnoreCase ("http://"))
  214395. location = "http://" + location;
  214396. if (levelsOfRedirection++ < 3)
  214397. return open (location, headers, postData, isPost, callback, callbackContext, timeOutMs);
  214398. }
  214399. else
  214400. {
  214401. levelsOfRedirection = 0;
  214402. return true;
  214403. }
  214404. }
  214405. closeSocket();
  214406. return false;
  214407. }
  214408. int read (void* buffer, int bytesToRead)
  214409. {
  214410. fd_set readbits;
  214411. FD_ZERO (&readbits);
  214412. FD_SET (socketHandle, &readbits);
  214413. struct timeval tv;
  214414. tv.tv_sec = timeoutSeconds;
  214415. tv.tv_usec = 0;
  214416. if (select (socketHandle + 1, &readbits, 0, 0, &tv) <= 0)
  214417. return 0; // (timeout)
  214418. const int bytesRead = jmax (0, (int) recv (socketHandle, buffer, bytesToRead, MSG_WAITALL));
  214419. readPosition += bytesRead;
  214420. return bytesRead;
  214421. }
  214422. int readPosition;
  214423. juce_UseDebuggingNewOperator
  214424. private:
  214425. int socketHandle, levelsOfRedirection;
  214426. const int timeoutSeconds;
  214427. void closeSocket()
  214428. {
  214429. if (socketHandle >= 0)
  214430. close (socketHandle);
  214431. socketHandle = -1;
  214432. }
  214433. const MemoryBlock createRequestHeader (const String& hostName,
  214434. const int hostPort,
  214435. const String& proxyName,
  214436. const int proxyPort,
  214437. const String& hostPath,
  214438. const String& originalURL,
  214439. const String& headers,
  214440. const MemoryBlock& postData,
  214441. const bool isPost)
  214442. {
  214443. String header (isPost ? "POST " : "GET ");
  214444. if (proxyName.isEmpty())
  214445. {
  214446. header << hostPath << " HTTP/1.0\r\nHost: "
  214447. << hostName << ':' << hostPort;
  214448. }
  214449. else
  214450. {
  214451. header << originalURL << " HTTP/1.0\r\nHost: "
  214452. << proxyName << ':' << proxyPort;
  214453. }
  214454. header << "\r\nUser-Agent: JUCE/"
  214455. << JUCE_MAJOR_VERSION << '.' << JUCE_MINOR_VERSION
  214456. << "\r\nConnection: Close\r\nContent-Length: "
  214457. << postData.getSize() << "\r\n"
  214458. << headers << "\r\n";
  214459. MemoryBlock mb;
  214460. mb.append (header.toUTF8(), (int) strlen (header.toUTF8()));
  214461. mb.append (postData.getData(), postData.getSize());
  214462. return mb;
  214463. }
  214464. const String readResponse (const uint32 timeOutTime)
  214465. {
  214466. int bytesRead = 0, numConsecutiveLFs = 0;
  214467. MemoryBlock buffer (1024, true);
  214468. while (numConsecutiveLFs < 2 && bytesRead < 32768
  214469. && Time::getMillisecondCounter() <= timeOutTime)
  214470. {
  214471. fd_set readbits;
  214472. FD_ZERO (&readbits);
  214473. FD_SET (socketHandle, &readbits);
  214474. struct timeval tv;
  214475. tv.tv_sec = timeoutSeconds;
  214476. tv.tv_usec = 0;
  214477. if (select (socketHandle + 1, &readbits, 0, 0, &tv) <= 0)
  214478. return String::empty; // (timeout)
  214479. buffer.ensureSize (bytesRead + 8, true);
  214480. char* const dest = (char*) buffer.getData() + bytesRead;
  214481. if (recv (socketHandle, dest, 1, 0) == -1)
  214482. return String::empty;
  214483. const char lastByte = *dest;
  214484. ++bytesRead;
  214485. if (lastByte == '\n')
  214486. ++numConsecutiveLFs;
  214487. else if (lastByte != '\r')
  214488. numConsecutiveLFs = 0;
  214489. }
  214490. const String header (String::fromUTF8 ((const char*) buffer.getData()));
  214491. if (header.startsWithIgnoreCase ("HTTP/"))
  214492. return header.trimEnd();
  214493. return String::empty;
  214494. }
  214495. static bool decomposeURL (const String& url,
  214496. String& host, String& path, int& port)
  214497. {
  214498. if (! url.startsWithIgnoreCase ("http://"))
  214499. return false;
  214500. const int nextSlash = url.indexOfChar (7, '/');
  214501. int nextColon = url.indexOfChar (7, ':');
  214502. if (nextColon > nextSlash && nextSlash > 0)
  214503. nextColon = -1;
  214504. if (nextColon >= 0)
  214505. {
  214506. host = url.substring (7, nextColon);
  214507. if (nextSlash >= 0)
  214508. port = url.substring (nextColon + 1, nextSlash).getIntValue();
  214509. else
  214510. port = url.substring (nextColon + 1).getIntValue();
  214511. }
  214512. else
  214513. {
  214514. port = 80;
  214515. if (nextSlash >= 0)
  214516. host = url.substring (7, nextSlash);
  214517. else
  214518. host = url.substring (7);
  214519. }
  214520. if (nextSlash >= 0)
  214521. path = url.substring (nextSlash);
  214522. else
  214523. path = "/";
  214524. return true;
  214525. }
  214526. static const String findHeaderItem (const StringArray& lines, const String& itemName)
  214527. {
  214528. for (int i = 0; i < lines.size(); ++i)
  214529. if (lines[i].startsWithIgnoreCase (itemName))
  214530. return lines[i].substring (itemName.length()).trim();
  214531. return String::empty;
  214532. }
  214533. };
  214534. void* juce_openInternetFile (const String& url,
  214535. const String& headers,
  214536. const MemoryBlock& postData,
  214537. const bool isPost,
  214538. URL::OpenStreamProgressCallback* callback,
  214539. void* callbackContext,
  214540. int timeOutMs)
  214541. {
  214542. JUCE_HTTPSocketStream* const s = new JUCE_HTTPSocketStream();
  214543. if (s->open (url, headers, postData, isPost,
  214544. callback, callbackContext, timeOutMs))
  214545. return s;
  214546. delete s;
  214547. return 0;
  214548. }
  214549. void juce_closeInternetFile (void* handle)
  214550. {
  214551. delete static_cast <JUCE_HTTPSocketStream*> (handle);
  214552. }
  214553. int juce_readFromInternetFile (void* handle, void* buffer, int bytesToRead)
  214554. {
  214555. JUCE_HTTPSocketStream* const s = (JUCE_HTTPSocketStream*) handle;
  214556. if (s != 0)
  214557. return s->read (buffer, bytesToRead);
  214558. return 0;
  214559. }
  214560. int64 juce_getInternetFileContentLength (void* handle)
  214561. {
  214562. JUCE_HTTPSocketStream* const s = (JUCE_HTTPSocketStream*) handle;
  214563. if (s != 0)
  214564. {
  214565. //xxx todo
  214566. jassertfalse
  214567. }
  214568. return -1;
  214569. }
  214570. int juce_seekInInternetFile (void* handle, int newPosition)
  214571. {
  214572. JUCE_HTTPSocketStream* const s = (JUCE_HTTPSocketStream*) handle;
  214573. if (s != 0)
  214574. return s->readPosition;
  214575. return 0;
  214576. }
  214577. #endif
  214578. /*** End of inlined file: juce_linux_Network.cpp ***/
  214579. /*** Start of inlined file: juce_linux_SystemStats.cpp ***/
  214580. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  214581. // compiled on its own).
  214582. #if JUCE_INCLUDED_FILE
  214583. void Logger::outputDebugString (const String& text)
  214584. {
  214585. std::cerr << text << std::endl;
  214586. }
  214587. SystemStats::OperatingSystemType SystemStats::getOperatingSystemType()
  214588. {
  214589. return Linux;
  214590. }
  214591. const String SystemStats::getOperatingSystemName()
  214592. {
  214593. return "Linux";
  214594. }
  214595. bool SystemStats::isOperatingSystem64Bit()
  214596. {
  214597. #if JUCE_64BIT
  214598. return true;
  214599. #else
  214600. //xxx not sure how to find this out?..
  214601. return false;
  214602. #endif
  214603. }
  214604. static const String juce_getCpuInfo (const char* const key)
  214605. {
  214606. StringArray lines;
  214607. lines.addLines (File ("/proc/cpuinfo").loadFileAsString());
  214608. for (int i = lines.size(); --i >= 0;) // (NB - it's important that this runs in reverse order)
  214609. if (lines[i].startsWithIgnoreCase (key))
  214610. return lines[i].fromFirstOccurrenceOf (":", false, false).trim();
  214611. return String::empty;
  214612. }
  214613. bool SystemStats::hasMMX() { return juce_getCpuInfo ("flags").contains ("mmx"); }
  214614. bool SystemStats::hasSSE() { return juce_getCpuInfo ("flags").contains ("sse"); }
  214615. bool SystemStats::hasSSE2() { return juce_getCpuInfo ("flags").contains ("sse2"); }
  214616. bool SystemStats::has3DNow() { return juce_getCpuInfo ("flags").contains ("3dnow"); }
  214617. const String SystemStats::getCpuVendor()
  214618. {
  214619. return juce_getCpuInfo ("vendor_id");
  214620. }
  214621. int SystemStats::getCpuSpeedInMegaherz()
  214622. {
  214623. return roundToInt (juce_getCpuInfo ("cpu MHz").getFloatValue());
  214624. }
  214625. int SystemStats::getMemorySizeInMegabytes()
  214626. {
  214627. struct sysinfo sysi;
  214628. if (sysinfo (&sysi) == 0)
  214629. return (sysi.totalram * sysi.mem_unit / (1024 * 1024));
  214630. return 0;
  214631. }
  214632. int SystemStats::getPageSize()
  214633. {
  214634. return sysconf (_SC_PAGESIZE);
  214635. }
  214636. int SystemStats::getNumCpus()
  214637. {
  214638. return juce_getCpuInfo ("processor").getIntValue() + 1;
  214639. }
  214640. const String SystemStats::getLogonName()
  214641. {
  214642. const char* user = getenv ("USER");
  214643. if (user == 0)
  214644. {
  214645. struct passwd* const pw = getpwuid (getuid());
  214646. if (pw != 0)
  214647. user = pw->pw_name;
  214648. }
  214649. return String::fromUTF8 (user);
  214650. }
  214651. const String SystemStats::getFullUserName()
  214652. {
  214653. return getLogonName();
  214654. }
  214655. void SystemStats::initialiseStats()
  214656. {
  214657. }
  214658. void PlatformUtilities::fpuReset()
  214659. {
  214660. }
  214661. uint32 juce_millisecondsSinceStartup() throw()
  214662. {
  214663. static unsigned int calibrate = 0;
  214664. static bool calibrated = false;
  214665. timeval t;
  214666. unsigned int ret = 0;
  214667. if (! gettimeofday (&t, 0))
  214668. {
  214669. if (! calibrated)
  214670. {
  214671. struct sysinfo sysi;
  214672. if (sysinfo (&sysi) == 0)
  214673. // Safe to assume system was not brought up earlier than 1970!
  214674. calibrate = t.tv_sec - sysi.uptime;
  214675. calibrated = true;
  214676. }
  214677. ret = 1000 * (t.tv_sec - calibrate) + (t.tv_usec / 1000);
  214678. }
  214679. return ret;
  214680. }
  214681. double Time::getMillisecondCounterHiRes() throw()
  214682. {
  214683. return getHighResolutionTicks() * 0.001;
  214684. }
  214685. int64 Time::getHighResolutionTicks() throw()
  214686. {
  214687. timeval t;
  214688. if (gettimeofday (&t, 0))
  214689. return 0;
  214690. return ((int64) t.tv_sec * (int64) 1000000) + (int64) t.tv_usec;
  214691. }
  214692. int64 Time::getHighResolutionTicksPerSecond() throw()
  214693. {
  214694. return 1000000; // (microseconds)
  214695. }
  214696. bool Time::setSystemTimeToThisTime() const
  214697. {
  214698. timeval t;
  214699. t.tv_sec = millisSinceEpoch % 1000000;
  214700. t.tv_usec = millisSinceEpoch - t.tv_sec;
  214701. return settimeofday (&t, 0) ? false : true;
  214702. }
  214703. #endif
  214704. /*** End of inlined file: juce_linux_SystemStats.cpp ***/
  214705. /*** Start of inlined file: juce_linux_Threads.cpp ***/
  214706. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  214707. // compiled on its own).
  214708. #if JUCE_INCLUDED_FILE
  214709. /*
  214710. Note that a lot of methods that you'd expect to find in this file actually
  214711. live in juce_posix_SharedCode.h!
  214712. */
  214713. void JUCE_API juce_threadEntryPoint (void*);
  214714. void* threadEntryProc (void* value)
  214715. {
  214716. juce_threadEntryPoint (value);
  214717. return 0;
  214718. }
  214719. void* juce_createThread (void* userData)
  214720. {
  214721. pthread_t handle = 0;
  214722. if (pthread_create (&handle, 0, threadEntryProc, userData) == 0)
  214723. {
  214724. pthread_detach (handle);
  214725. return (void*) handle;
  214726. }
  214727. return 0;
  214728. }
  214729. void juce_killThread (void* handle)
  214730. {
  214731. if (handle != 0)
  214732. pthread_cancel ((pthread_t) handle);
  214733. }
  214734. void juce_setCurrentThreadName (const String& /*name*/)
  214735. {
  214736. }
  214737. Thread::ThreadID Thread::getCurrentThreadId()
  214738. {
  214739. return (ThreadID) pthread_self();
  214740. }
  214741. /* This is all a bit non-ideal... the trouble is that on Linux you
  214742. need to call setpriority to affect the dynamic priority for
  214743. non-realtime processes, but this requires the pid, which is not
  214744. accessible from the pthread_t. We could get it by calling getpid
  214745. once each thread has started, but then we would need a list of
  214746. running threads etc etc.
  214747. Also there is no such thing as IDLE priority on Linux.
  214748. For the moment, map idle, low and normal process priorities to
  214749. SCHED_OTHER, with the thread priority ignored for these classes.
  214750. Map high priority processes to the lower half of the SCHED_RR
  214751. range, and realtime to the upper half.
  214752. priority 1 to 10 where 5=normal, 1=low. If the handle is 0, sets the
  214753. priority of the current thread
  214754. */
  214755. bool juce_setThreadPriority (void* handle, int priority)
  214756. {
  214757. struct sched_param param;
  214758. int policy;
  214759. if (handle == 0)
  214760. handle = (void*) pthread_self();
  214761. if (pthread_getschedparam ((pthread_t) handle, &policy, &param) == 0
  214762. && policy != SCHED_OTHER)
  214763. {
  214764. int minp = sched_get_priority_min (policy);
  214765. int maxp = sched_get_priority_max (policy);
  214766. int pri = ((maxp - minp) / 2) * (priority - 1) / 9;
  214767. if (param.__sched_priority >= (minp + (maxp - minp) / 2))
  214768. param.__sched_priority = minp + ((maxp - minp) / 2) + pri; // (realtime)
  214769. else
  214770. param.__sched_priority = minp + pri; // (high)
  214771. param.sched_priority = jlimit (1, 127, 1 + (priority * 126) / 11);
  214772. return pthread_setschedparam ((pthread_t) handle, policy, &param) == 0;
  214773. }
  214774. return false;
  214775. }
  214776. /* Remove this macro if you're having problems compiling the cpu affinity
  214777. calls (the API for these has changed about quite a bit in various Linux
  214778. versions, and a lot of distros seem to ship with obsolete versions)
  214779. */
  214780. #if defined (CPU_ISSET) && ! defined (SUPPORT_AFFINITIES)
  214781. #define SUPPORT_AFFINITIES 1
  214782. #endif
  214783. void Thread::setCurrentThreadAffinityMask (const uint32 affinityMask)
  214784. {
  214785. #if SUPPORT_AFFINITIES
  214786. cpu_set_t affinity;
  214787. CPU_ZERO (&affinity);
  214788. for (int i = 0; i < 32; ++i)
  214789. if ((affinityMask & (1 << i)) != 0)
  214790. CPU_SET (i, &affinity);
  214791. /*
  214792. N.B. If this line causes a compile error, then you've probably not got the latest
  214793. version of glibc installed.
  214794. If you don't want to update your copy of glibc and don't care about cpu affinities,
  214795. then you can just disable all this stuff by setting the SUPPORT_AFFINITIES macro to 0.
  214796. */
  214797. sched_setaffinity (getpid(), sizeof (cpu_set_t), &affinity);
  214798. sched_yield();
  214799. #else
  214800. /* affinities aren't supported because either the appropriate header files weren't found,
  214801. or the SUPPORT_AFFINITIES macro was turned off
  214802. */
  214803. jassertfalse
  214804. #endif
  214805. }
  214806. void Thread::yield()
  214807. {
  214808. sched_yield();
  214809. }
  214810. // sets the process to 0=low priority, 1=normal, 2=high, 3=realtime
  214811. void Process::setPriority (ProcessPriority prior)
  214812. {
  214813. struct sched_param param;
  214814. int policy, maxp, minp;
  214815. const int p = (int) prior;
  214816. if (p <= 1)
  214817. policy = SCHED_OTHER;
  214818. else
  214819. policy = SCHED_RR;
  214820. minp = sched_get_priority_min (policy);
  214821. maxp = sched_get_priority_max (policy);
  214822. if (p < 2)
  214823. param.__sched_priority = 0;
  214824. else if (p == 2 )
  214825. // Set to middle of lower realtime priority range
  214826. param.__sched_priority = minp + (maxp - minp) / 4;
  214827. else
  214828. // Set to middle of higher realtime priority range
  214829. param.__sched_priority = minp + (3 * (maxp - minp) / 4);
  214830. pthread_setschedparam (pthread_self(), policy, &param);
  214831. }
  214832. void Process::terminate()
  214833. {
  214834. exit (0);
  214835. }
  214836. bool JUCE_PUBLIC_FUNCTION juce_isRunningUnderDebugger()
  214837. {
  214838. static char testResult = 0;
  214839. if (testResult == 0)
  214840. {
  214841. testResult = (char) ptrace (PT_TRACE_ME, 0, 0, 0);
  214842. if (testResult >= 0)
  214843. {
  214844. ptrace (PT_DETACH, 0, (caddr_t) 1, 0);
  214845. testResult = 1;
  214846. }
  214847. }
  214848. return testResult < 0;
  214849. }
  214850. bool JUCE_CALLTYPE Process::isRunningUnderDebugger()
  214851. {
  214852. return juce_isRunningUnderDebugger();
  214853. }
  214854. void Process::raisePrivilege()
  214855. {
  214856. // If running suid root, change effective user
  214857. // to root
  214858. if (geteuid() != 0 && getuid() == 0)
  214859. {
  214860. setreuid (geteuid(), getuid());
  214861. setregid (getegid(), getgid());
  214862. }
  214863. }
  214864. void Process::lowerPrivilege()
  214865. {
  214866. // If runing suid root, change effective user
  214867. // back to real user
  214868. if (geteuid() == 0 && getuid() != 0)
  214869. {
  214870. setreuid (geteuid(), getuid());
  214871. setregid (getegid(), getgid());
  214872. }
  214873. }
  214874. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  214875. void* PlatformUtilities::loadDynamicLibrary (const String& name)
  214876. {
  214877. return dlopen (name.toUTF8(), RTLD_LOCAL | RTLD_NOW);
  214878. }
  214879. void PlatformUtilities::freeDynamicLibrary (void* handle)
  214880. {
  214881. dlclose(handle);
  214882. }
  214883. void* PlatformUtilities::getProcedureEntryPoint (void* libraryHandle, const String& procedureName)
  214884. {
  214885. return dlsym (libraryHandle, procedureName.toCString());
  214886. }
  214887. #endif
  214888. #endif
  214889. /*** End of inlined file: juce_linux_Threads.cpp ***/
  214890. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  214891. /*** Start of inlined file: juce_linux_Clipboard.cpp ***/
  214892. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  214893. // compiled on its own).
  214894. #if JUCE_INCLUDED_FILE
  214895. #if JUCE_DEBUG
  214896. #define JUCE_DEBUG_XERRORS 1
  214897. #endif
  214898. extern Display* display;
  214899. extern Window juce_messageWindowHandle;
  214900. namespace ClipboardHelpers
  214901. {
  214902. static String localClipboardContent;
  214903. static Atom atom_UTF8_STRING;
  214904. static Atom atom_CLIPBOARD;
  214905. static Atom atom_TARGETS;
  214906. static void initSelectionAtoms()
  214907. {
  214908. static bool isInitialised = false;
  214909. if (! isInitialised)
  214910. {
  214911. atom_UTF8_STRING = XInternAtom (display, "UTF8_STRING", False);
  214912. atom_CLIPBOARD = XInternAtom (display, "CLIPBOARD", False);
  214913. atom_TARGETS = XInternAtom (display, "TARGETS", False);
  214914. }
  214915. }
  214916. // Read the content of a window property as either a locale-dependent string or an utf8 string
  214917. // works only for strings shorter than 1000000 bytes
  214918. static String readWindowProperty (Window window, Atom prop, Atom fmt)
  214919. {
  214920. String returnData;
  214921. char* clipData;
  214922. Atom actualType;
  214923. int actualFormat;
  214924. unsigned long numItems, bytesLeft;
  214925. if (XGetWindowProperty (display, window, prop,
  214926. 0L /* offset */, 1000000 /* length (max) */, False,
  214927. AnyPropertyType /* format */,
  214928. &actualType, &actualFormat, &numItems, &bytesLeft,
  214929. (unsigned char**) &clipData) == Success)
  214930. {
  214931. if (actualType == atom_UTF8_STRING && actualFormat == 8)
  214932. returnData = String::fromUTF8 (clipData, numItems);
  214933. else if (actualType == XA_STRING && actualFormat == 8)
  214934. returnData = String (clipData, numItems);
  214935. if (clipData != 0)
  214936. XFree (clipData);
  214937. jassert (bytesLeft == 0 || numItems == 1000000);
  214938. }
  214939. XDeleteProperty (display, window, prop);
  214940. return returnData;
  214941. }
  214942. // Send a SelectionRequest to the window owning the selection and waits for its answer (with a timeout) */
  214943. static bool requestSelectionContent (String& selectionContent, Atom selection, Atom requestedFormat)
  214944. {
  214945. Atom property_name = XInternAtom (display, "JUCE_SEL", false);
  214946. // The selection owner will be asked to set the JUCE_SEL property on the
  214947. // juce_messageWindowHandle with the selection content
  214948. XConvertSelection (display, selection, requestedFormat, property_name,
  214949. juce_messageWindowHandle, CurrentTime);
  214950. int count = 50; // will wait at most for 200 ms
  214951. while (--count >= 0)
  214952. {
  214953. XEvent event;
  214954. if (XCheckTypedWindowEvent (display, juce_messageWindowHandle, SelectionNotify, &event))
  214955. {
  214956. if (event.xselection.property == property_name)
  214957. {
  214958. jassert (event.xselection.requestor == juce_messageWindowHandle);
  214959. selectionContent = readWindowProperty (event.xselection.requestor,
  214960. event.xselection.property,
  214961. requestedFormat);
  214962. return true;
  214963. }
  214964. else
  214965. {
  214966. return false; // the format we asked for was denied.. (event.xselection.property == None)
  214967. }
  214968. }
  214969. // not very elegant.. we could do a select() or something like that...
  214970. // however clipboard content requesting is inherently slow on x11, it
  214971. // often takes 50ms or more so...
  214972. Thread::sleep (4);
  214973. }
  214974. return false;
  214975. }
  214976. }
  214977. // Called from the event loop in juce_linux_Messaging in response to SelectionRequest events
  214978. void juce_handleSelectionRequest (XSelectionRequestEvent &evt)
  214979. {
  214980. ClipboardHelpers::initSelectionAtoms();
  214981. // the selection content is sent to the target window as a window property
  214982. XSelectionEvent reply;
  214983. reply.type = SelectionNotify;
  214984. reply.display = evt.display;
  214985. reply.requestor = evt.requestor;
  214986. reply.selection = evt.selection;
  214987. reply.target = evt.target;
  214988. reply.property = None; // == "fail"
  214989. reply.time = evt.time;
  214990. HeapBlock <char> data;
  214991. int propertyFormat = 0, numDataItems = 0;
  214992. if (evt.selection == XA_PRIMARY || evt.selection == ClipboardHelpers::atom_CLIPBOARD)
  214993. {
  214994. if (evt.target == XA_STRING)
  214995. {
  214996. // format data according to system locale
  214997. numDataItems = ClipboardHelpers::localClipboardContent.getNumBytesAsCString() + 1;
  214998. data.calloc (numDataItems + 1);
  214999. ClipboardHelpers::localClipboardContent.copyToCString (data, numDataItems);
  215000. propertyFormat = 8; // bits/item
  215001. }
  215002. else if (evt.target == ClipboardHelpers::atom_UTF8_STRING)
  215003. {
  215004. // translate to utf8
  215005. numDataItems = ClipboardHelpers::localClipboardContent.getNumBytesAsUTF8() + 1;
  215006. data.calloc (numDataItems + 1);
  215007. ClipboardHelpers::localClipboardContent.copyToUTF8 (data, numDataItems);
  215008. propertyFormat = 8; // bits/item
  215009. }
  215010. else if (evt.target == ClipboardHelpers::atom_TARGETS)
  215011. {
  215012. // another application wants to know what we are able to send
  215013. numDataItems = 2;
  215014. propertyFormat = 32; // atoms are 32-bit
  215015. data.calloc (numDataItems * 4);
  215016. Atom* atoms = reinterpret_cast<Atom*> (data.getData());
  215017. atoms[0] = ClipboardHelpers::atom_UTF8_STRING;
  215018. atoms[1] = XA_STRING;
  215019. }
  215020. }
  215021. else
  215022. {
  215023. DBG ("requested unsupported clipboard");
  215024. }
  215025. if (data != 0)
  215026. {
  215027. const int maxReasonableSelectionSize = 1000000;
  215028. // for very big chunks of data, we should use the "INCR" protocol , which is a pain in the *ss
  215029. if (evt.property != None && numDataItems < maxReasonableSelectionSize)
  215030. {
  215031. XChangeProperty (evt.display, evt.requestor,
  215032. evt.property, evt.target,
  215033. propertyFormat /* 8 or 32 */, PropModeReplace,
  215034. reinterpret_cast<const unsigned char*> (data.getData()), numDataItems);
  215035. reply.property = evt.property; // " == success"
  215036. }
  215037. }
  215038. XSendEvent (evt.display, evt.requestor, 0, NoEventMask, (XEvent*) &reply);
  215039. }
  215040. void SystemClipboard::copyTextToClipboard (const String& clipText)
  215041. {
  215042. ClipboardHelpers::initSelectionAtoms();
  215043. ClipboardHelpers::localClipboardContent = clipText;
  215044. XSetSelectionOwner (display, XA_PRIMARY, juce_messageWindowHandle, CurrentTime);
  215045. XSetSelectionOwner (display, ClipboardHelpers::atom_CLIPBOARD, juce_messageWindowHandle, CurrentTime);
  215046. }
  215047. const String SystemClipboard::getTextFromClipboard()
  215048. {
  215049. ClipboardHelpers::initSelectionAtoms();
  215050. /* 1) try to read from the "CLIPBOARD" selection first (the "high
  215051. level" clipboard that is supposed to be filled by ctrl-C
  215052. etc). When a clipboard manager is running, the content of this
  215053. selection is preserved even when the original selection owner
  215054. exits.
  215055. 2) and then try to read from "PRIMARY" selection (the "legacy" selection
  215056. filled by good old x11 apps such as xterm)
  215057. */
  215058. String content;
  215059. Atom selection = XA_PRIMARY;
  215060. Window selectionOwner = None;
  215061. if ((selectionOwner = XGetSelectionOwner (display, selection)) == None)
  215062. {
  215063. selection = ClipboardHelpers::atom_CLIPBOARD;
  215064. selectionOwner = XGetSelectionOwner (display, selection);
  215065. }
  215066. if (selectionOwner != None)
  215067. {
  215068. if (selectionOwner == juce_messageWindowHandle)
  215069. {
  215070. content = ClipboardHelpers::localClipboardContent;
  215071. }
  215072. else
  215073. {
  215074. // first try: we want an utf8 string
  215075. bool ok = ClipboardHelpers::requestSelectionContent (content, selection, ClipboardHelpers::atom_UTF8_STRING);
  215076. if (! ok)
  215077. {
  215078. // second chance, ask for a good old locale-dependent string ..
  215079. ok = ClipboardHelpers::requestSelectionContent (content, selection, XA_STRING);
  215080. }
  215081. }
  215082. }
  215083. return content;
  215084. }
  215085. #endif
  215086. /*** End of inlined file: juce_linux_Clipboard.cpp ***/
  215087. /*** Start of inlined file: juce_linux_Messaging.cpp ***/
  215088. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  215089. // compiled on its own).
  215090. #if JUCE_INCLUDED_FILE
  215091. #if JUCE_DEBUG && ! defined (JUCE_DEBUG_XERRORS)
  215092. #define JUCE_DEBUG_XERRORS 1
  215093. #endif
  215094. Display* display = 0;
  215095. Window juce_messageWindowHandle = None;
  215096. XContext windowHandleXContext; // This is referenced from Windowing.cpp
  215097. extern void juce_windowMessageReceive (XEvent* event); // Defined in Windowing.cpp
  215098. extern void juce_handleSelectionRequest (XSelectionRequestEvent &evt); // Defined in Clipboard.cpp
  215099. ScopedXLock::ScopedXLock() { XLockDisplay (display); }
  215100. ScopedXLock::~ScopedXLock() { XUnlockDisplay (display); }
  215101. class InternalMessageQueue
  215102. {
  215103. public:
  215104. InternalMessageQueue()
  215105. : bytesInSocket (0)
  215106. {
  215107. int ret = ::socketpair (AF_LOCAL, SOCK_STREAM, 0, fd);
  215108. (void) ret; jassert (ret == 0);
  215109. //setNonBlocking (fd[0]);
  215110. //setNonBlocking (fd[1]);
  215111. }
  215112. ~InternalMessageQueue()
  215113. {
  215114. close (fd[0]);
  215115. close (fd[1]);
  215116. }
  215117. void postMessage (Message* msg)
  215118. {
  215119. const int maxBytesInSocketQueue = 128;
  215120. ScopedLock sl (lock);
  215121. queue.add (msg);
  215122. if (bytesInSocket < maxBytesInSocketQueue)
  215123. {
  215124. ++bytesInSocket;
  215125. ScopedUnlock ul (lock);
  215126. const unsigned char x = 0xff;
  215127. size_t bytesWritten = write (fd[0], &x, 1);
  215128. (void) bytesWritten;
  215129. }
  215130. }
  215131. bool isEmpty() const
  215132. {
  215133. ScopedLock sl (lock);
  215134. return queue.size() == 0;
  215135. }
  215136. Message* popNextMessage()
  215137. {
  215138. ScopedLock sl (lock);
  215139. if (bytesInSocket > 0)
  215140. {
  215141. --bytesInSocket;
  215142. ScopedUnlock ul (lock);
  215143. unsigned char x;
  215144. size_t numBytes = read (fd[1], &x, 1);
  215145. (void) numBytes;
  215146. }
  215147. Message* m = queue[0];
  215148. queue.remove (0, false /* deleteObject */);
  215149. return m;
  215150. }
  215151. int getWaitHandle() const { return fd[1]; }
  215152. private:
  215153. CriticalSection lock;
  215154. OwnedArray <Message> queue;
  215155. int fd[2];
  215156. int bytesInSocket;
  215157. static bool setNonBlocking (int handle)
  215158. {
  215159. int socketFlags = fcntl (handle, F_GETFL, 0);
  215160. if (socketFlags == -1)
  215161. return false;
  215162. socketFlags |= O_NONBLOCK;
  215163. return fcntl (handle, F_SETFL, socketFlags) == 0;
  215164. }
  215165. };
  215166. struct MessageThreadFuncCall
  215167. {
  215168. enum { uniqueID = 0x73774623 };
  215169. MessageCallbackFunction* func;
  215170. void* parameter;
  215171. void* result;
  215172. CriticalSection lock;
  215173. WaitableEvent event;
  215174. };
  215175. static InternalMessageQueue* juce_internalMessageQueue = 0;
  215176. // error handling in X11
  215177. static bool errorOccurred = false;
  215178. static bool keyboardBreakOccurred = false;
  215179. static XErrorHandler oldErrorHandler = (XErrorHandler) 0;
  215180. static XIOErrorHandler oldIOErrorHandler = (XIOErrorHandler) 0;
  215181. // Usually happens when client-server connection is broken
  215182. static int ioErrorHandler (Display* display)
  215183. {
  215184. DBG ("ERROR: connection to X server broken.. terminating.");
  215185. errorOccurred = true;
  215186. if (JUCEApplication::getInstance() != 0)
  215187. Process::terminate();
  215188. return 0;
  215189. }
  215190. // A protocol error has occurred
  215191. static int errorHandler (Display* display, XErrorEvent* event)
  215192. {
  215193. #if JUCE_DEBUG_XERRORS
  215194. char errorStr[64] = { 0 };
  215195. char requestStr[64] = { 0 };
  215196. XGetErrorText (display, event->error_code, errorStr, 64);
  215197. XGetErrorDatabaseText (display, "XRequest", String (event->request_code).toCString(),
  215198. "Unknown", requestStr, 64);
  215199. DBG ("ERROR: X returned " + String (errorStr) + " for operation " + String (requestStr));
  215200. #endif
  215201. return 0;
  215202. }
  215203. // Breakin from keyboard
  215204. static void signalHandler (int sig)
  215205. {
  215206. if (sig == SIGINT)
  215207. {
  215208. keyboardBreakOccurred = true;
  215209. return;
  215210. }
  215211. static bool reentrant = false;
  215212. if (! reentrant)
  215213. {
  215214. reentrant = true;
  215215. // Illegal instruction
  215216. fflush (stdout);
  215217. Logger::outputDebugString ("ERROR: Program executed illegal instruction.. terminating");
  215218. errorOccurred = true;
  215219. if (JUCEApplication::getInstance() != 0)
  215220. Process::terminate();
  215221. }
  215222. else
  215223. {
  215224. if (JUCEApplication::getInstance() != 0)
  215225. exit(0);
  215226. }
  215227. }
  215228. void MessageManager::doPlatformSpecificInitialisation()
  215229. {
  215230. // Initialise xlib for multiple thread support
  215231. static bool initThreadCalled = false;
  215232. if (! initThreadCalled)
  215233. {
  215234. if (! XInitThreads())
  215235. {
  215236. // This is fatal! Print error and closedown
  215237. Logger::outputDebugString ("Failed to initialise xlib thread support.");
  215238. if (JUCEApplication::getInstance() != 0)
  215239. Process::terminate();
  215240. return;
  215241. }
  215242. initThreadCalled = true;
  215243. }
  215244. // This is called if the client/server connection is broken
  215245. oldIOErrorHandler = XSetIOErrorHandler (ioErrorHandler);
  215246. // This is called if a protocol error occurs
  215247. oldErrorHandler = XSetErrorHandler (errorHandler);
  215248. // Install signal handler for break-in
  215249. struct sigaction saction;
  215250. sigset_t maskSet;
  215251. sigemptyset (&maskSet);
  215252. saction.sa_handler = signalHandler;
  215253. saction.sa_mask = maskSet;
  215254. saction.sa_flags = 0;
  215255. sigaction (SIGINT, &saction, 0);
  215256. #ifndef _DEBUG
  215257. // Setup signal handlers for various fatal errors
  215258. sigaction (SIGILL, &saction, 0);
  215259. sigaction (SIGBUS, &saction, 0);
  215260. sigaction (SIGFPE, &saction, 0);
  215261. sigaction (SIGSEGV, &saction, 0);
  215262. sigaction (SIGSYS, &saction, 0);
  215263. #endif
  215264. // Create the internal message queue
  215265. juce_internalMessageQueue = new InternalMessageQueue();
  215266. // Try to connect to a display
  215267. String displayName (getenv ("DISPLAY"));
  215268. if (displayName.isEmpty())
  215269. displayName = ":0.0";
  215270. display = XOpenDisplay (displayName.toCString());
  215271. if (display == 0)
  215272. {
  215273. // This is not fatal! we can run headless.
  215274. return;
  215275. }
  215276. // Get defaults for various properties
  215277. int screen = DefaultScreen (display);
  215278. Window root = RootWindow (display, screen);
  215279. Visual* visual = DefaultVisual (display, screen);
  215280. // Create a context to store user data associated with Windows we
  215281. // create in WindowDriver
  215282. windowHandleXContext = XUniqueContext();
  215283. // We're only interested in client messages for this window
  215284. // which are always sent
  215285. XSetWindowAttributes swa;
  215286. swa.event_mask = NoEventMask;
  215287. // Create our message window (this will never be mapped)
  215288. juce_messageWindowHandle = XCreateWindow (display, root,
  215289. 0, 0, 1, 1, 0, 0, InputOnly,
  215290. visual, CWEventMask, &swa);
  215291. }
  215292. void MessageManager::doPlatformSpecificShutdown()
  215293. {
  215294. deleteAndZero (juce_internalMessageQueue);
  215295. if (display != 0 && ! errorOccurred)
  215296. {
  215297. XDestroyWindow (display, juce_messageWindowHandle);
  215298. XCloseDisplay (display);
  215299. // reset pointers
  215300. juce_messageWindowHandle = 0;
  215301. display = 0;
  215302. // Restore original error handlers
  215303. XSetIOErrorHandler (oldIOErrorHandler);
  215304. oldIOErrorHandler = 0;
  215305. XSetErrorHandler (oldErrorHandler);
  215306. oldErrorHandler = 0;
  215307. }
  215308. }
  215309. bool juce_postMessageToSystemQueue (void* message)
  215310. {
  215311. if (errorOccurred)
  215312. return false;
  215313. juce_internalMessageQueue->postMessage ((Message*) message);
  215314. return true;
  215315. }
  215316. void MessageManager::broadcastMessage (const String& value) throw()
  215317. {
  215318. /* TODO */
  215319. }
  215320. void* MessageManager::callFunctionOnMessageThread (MessageCallbackFunction* func,
  215321. void* parameter)
  215322. {
  215323. if (errorOccurred)
  215324. return 0;
  215325. if (! isThisTheMessageThread())
  215326. {
  215327. MessageThreadFuncCall messageCallContext;
  215328. messageCallContext.func = func;
  215329. messageCallContext.parameter = parameter;
  215330. juce_internalMessageQueue->postMessage (new Message (MessageThreadFuncCall::uniqueID,
  215331. 0, 0, &messageCallContext));
  215332. // Wait for it to complete before continuing
  215333. messageCallContext.event.wait();
  215334. return messageCallContext.result;
  215335. }
  215336. else
  215337. {
  215338. // Just call the function directly
  215339. return func (parameter);
  215340. }
  215341. }
  215342. // Wait for an event (either XEvent, or an internal Message)
  215343. static bool juce_sleepUntilEvent (const int timeoutMs)
  215344. {
  215345. if (! juce_internalMessageQueue->isEmpty())
  215346. return true;
  215347. if (display != 0)
  215348. {
  215349. ScopedXLock xlock;
  215350. if (XPending (display))
  215351. return true;
  215352. }
  215353. struct timeval tv;
  215354. tv.tv_sec = 0;
  215355. tv.tv_usec = timeoutMs * 1000;
  215356. int fd0 = juce_internalMessageQueue->getWaitHandle();
  215357. int fdmax = fd0;
  215358. fd_set readset;
  215359. FD_ZERO (&readset);
  215360. FD_SET (fd0, &readset);
  215361. if (display != 0)
  215362. {
  215363. ScopedXLock xlock;
  215364. int fd1 = XConnectionNumber (display);
  215365. FD_SET (fd1, &readset);
  215366. fdmax = jmax (fd0, fd1);
  215367. }
  215368. const int ret = select (fdmax + 1, &readset, 0, 0, &tv);
  215369. return (ret > 0); // ret <= 0 if error or timeout
  215370. }
  215371. // Handle next XEvent (if any)
  215372. static bool juce_dispatchNextXEvent()
  215373. {
  215374. if (display == 0)
  215375. return false;
  215376. XEvent evt;
  215377. {
  215378. ScopedXLock xlock;
  215379. if (! XPending (display))
  215380. return false;
  215381. XNextEvent (display, &evt);
  215382. }
  215383. if (evt.type == SelectionRequest && evt.xany.window == juce_messageWindowHandle)
  215384. {
  215385. juce_handleSelectionRequest (evt.xselectionrequest);
  215386. }
  215387. else if (evt.xany.window != juce_messageWindowHandle)
  215388. {
  215389. juce_windowMessageReceive (&evt);
  215390. }
  215391. return true;
  215392. }
  215393. // Handle next internal Message (if any)
  215394. static bool juce_dispatchNextInternalMessage()
  215395. {
  215396. ScopedPointer <Message> msg (juce_internalMessageQueue->popNextMessage());
  215397. if (msg == 0)
  215398. return false;
  215399. if (msg->intParameter1 == MessageThreadFuncCall::uniqueID)
  215400. {
  215401. // Handle callback message
  215402. MessageThreadFuncCall* const call = (MessageThreadFuncCall*) msg->pointerParameter;
  215403. call->result = (*(call->func)) (call->parameter);
  215404. call->event.signal();
  215405. }
  215406. else
  215407. {
  215408. // Handle "normal" messages
  215409. MessageManager::getInstance()->deliverMessage (msg.release());
  215410. }
  215411. return true;
  215412. }
  215413. // this function expects that it will NEVER be called simultaneously for two concurrent threads
  215414. bool juce_dispatchNextMessageOnSystemQueue (bool returnIfNoPendingMessages)
  215415. {
  215416. for (;;)
  215417. {
  215418. if (errorOccurred)
  215419. break;
  215420. if (keyboardBreakOccurred)
  215421. {
  215422. errorOccurred = true;
  215423. if (JUCEApplication::getInstance() != 0)
  215424. Process::terminate();
  215425. break;
  215426. }
  215427. static int totalEventCount = 0;
  215428. ++totalEventCount;
  215429. // The purpose here is to give either priority to XEvents or
  215430. // to internal messages This is necessary to keep a "good"
  215431. // behaviour when the cpu is overloaded
  215432. if (totalEventCount & 1)
  215433. {
  215434. if (juce_dispatchNextXEvent() || juce_dispatchNextInternalMessage())
  215435. return true;
  215436. }
  215437. else
  215438. {
  215439. if (juce_dispatchNextInternalMessage() || juce_dispatchNextXEvent())
  215440. return true;
  215441. }
  215442. if (returnIfNoPendingMessages) // early exit
  215443. break;
  215444. // the timeout is to be on the safe side, but it does not seem to be useful
  215445. juce_sleepUntilEvent (2000);
  215446. }
  215447. return false;
  215448. }
  215449. #endif
  215450. /*** End of inlined file: juce_linux_Messaging.cpp ***/
  215451. /*** Start of inlined file: juce_linux_Fonts.cpp ***/
  215452. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  215453. // compiled on its own).
  215454. #if JUCE_INCLUDED_FILE
  215455. class FreeTypeFontFace
  215456. {
  215457. public:
  215458. enum FontStyle
  215459. {
  215460. Plain = 0,
  215461. Bold = 1,
  215462. Italic = 2
  215463. };
  215464. struct FontNameIndex
  215465. {
  215466. String fileName;
  215467. int faceIndex;
  215468. };
  215469. FreeTypeFontFace (const String& familyName)
  215470. : hasSerif (false),
  215471. monospaced (false)
  215472. {
  215473. family = familyName;
  215474. }
  215475. void setFileName (const String& name, const int faceIndex, FontStyle style)
  215476. {
  215477. if (names [(int) style].fileName.isEmpty())
  215478. {
  215479. names [(int) style].fileName = name;
  215480. names [(int) style].faceIndex = faceIndex;
  215481. }
  215482. }
  215483. const String& getFamilyName() const throw() { return family; }
  215484. const String& getFileName (const int style, int& faceIndex) const throw()
  215485. {
  215486. faceIndex = names[style].faceIndex;
  215487. return names[style].fileName;
  215488. }
  215489. void setMonospaced (bool mono) throw() { monospaced = mono; }
  215490. bool getMonospaced() const throw() { return monospaced; }
  215491. void setSerif (const bool serif) throw() { hasSerif = serif; }
  215492. bool getSerif() const throw() { return hasSerif; }
  215493. private:
  215494. String family;
  215495. FontNameIndex names[4];
  215496. bool hasSerif, monospaced;
  215497. };
  215498. class FreeTypeInterface : public DeletedAtShutdown
  215499. {
  215500. public:
  215501. FreeTypeInterface()
  215502. : ftLib (0),
  215503. lastFace (0),
  215504. lastBold (false),
  215505. lastItalic (false)
  215506. {
  215507. if (FT_Init_FreeType (&ftLib) != 0)
  215508. {
  215509. ftLib = 0;
  215510. DBG ("Failed to initialize FreeType");
  215511. }
  215512. StringArray fontDirs;
  215513. fontDirs.addTokens (String::fromUTF8 (getenv ("JUCE_FONT_PATH")), ";,", String::empty);
  215514. fontDirs.removeEmptyStrings (true);
  215515. if (fontDirs.size() == 0)
  215516. {
  215517. XmlDocument fontsConfig (File ("/etc/fonts/fonts.conf"));
  215518. const ScopedPointer<XmlElement> fontsInfo (fontsConfig.getDocumentElement());
  215519. if (fontsInfo != 0)
  215520. {
  215521. forEachXmlChildElementWithTagName (*fontsInfo, e, "dir")
  215522. {
  215523. fontDirs.add (e->getAllSubText().trim());
  215524. }
  215525. }
  215526. }
  215527. if (fontDirs.size() == 0)
  215528. fontDirs.add ("/usr/X11R6/lib/X11/fonts");
  215529. for (int i = 0; i < fontDirs.size(); ++i)
  215530. enumerateFaces (fontDirs[i]);
  215531. }
  215532. ~FreeTypeInterface()
  215533. {
  215534. if (lastFace != 0)
  215535. FT_Done_Face (lastFace);
  215536. if (ftLib != 0)
  215537. FT_Done_FreeType (ftLib);
  215538. clearSingletonInstance();
  215539. }
  215540. FreeTypeFontFace* findOrCreate (const String& familyName, const bool create = false)
  215541. {
  215542. for (int i = 0; i < faces.size(); i++)
  215543. if (faces[i]->getFamilyName() == familyName)
  215544. return faces[i];
  215545. if (! create)
  215546. return 0;
  215547. FreeTypeFontFace* newFace = new FreeTypeFontFace (familyName);
  215548. faces.add (newFace);
  215549. return newFace;
  215550. }
  215551. // Enumerate all font faces available in a given directory
  215552. void enumerateFaces (const String& path)
  215553. {
  215554. File dirPath (path);
  215555. if (path.isEmpty() || ! dirPath.isDirectory())
  215556. return;
  215557. DirectoryIterator di (dirPath, true);
  215558. while (di.next())
  215559. {
  215560. File possible (di.getFile());
  215561. if (possible.hasFileExtension ("ttf")
  215562. || possible.hasFileExtension ("pfb")
  215563. || possible.hasFileExtension ("pcf"))
  215564. {
  215565. FT_Face face;
  215566. int faceIndex = 0;
  215567. int numFaces = 0;
  215568. do
  215569. {
  215570. if (FT_New_Face (ftLib, possible.getFullPathName().toUTF8(),
  215571. faceIndex, &face) == 0)
  215572. {
  215573. if (faceIndex == 0)
  215574. numFaces = face->num_faces;
  215575. if ((face->face_flags & FT_FACE_FLAG_SCALABLE) != 0)
  215576. {
  215577. FreeTypeFontFace* const newFace = findOrCreate (face->family_name, true);
  215578. int style = (int) FreeTypeFontFace::Plain;
  215579. if ((face->style_flags & FT_STYLE_FLAG_BOLD) != 0)
  215580. style |= (int) FreeTypeFontFace::Bold;
  215581. if ((face->style_flags & FT_STYLE_FLAG_ITALIC) != 0)
  215582. style |= (int) FreeTypeFontFace::Italic;
  215583. newFace->setFileName (possible.getFullPathName(), faceIndex, (FreeTypeFontFace::FontStyle) style);
  215584. newFace->setMonospaced ((face->face_flags & FT_FACE_FLAG_FIXED_WIDTH) != 0);
  215585. // Surely there must be a better way to do this?
  215586. const String name (face->family_name);
  215587. newFace->setSerif (! (name.containsIgnoreCase ("Sans")
  215588. || name.containsIgnoreCase ("Verdana")
  215589. || name.containsIgnoreCase ("Arial")));
  215590. }
  215591. FT_Done_Face (face);
  215592. }
  215593. ++faceIndex;
  215594. }
  215595. while (faceIndex < numFaces);
  215596. }
  215597. }
  215598. }
  215599. // Create a FreeType face object for a given font
  215600. FT_Face createFT_Face (const String& fontName, const bool bold, const bool italic)
  215601. {
  215602. FT_Face face = 0;
  215603. if (fontName == lastFontName && bold == lastBold && italic == lastItalic)
  215604. {
  215605. face = lastFace;
  215606. }
  215607. else
  215608. {
  215609. if (lastFace != 0)
  215610. {
  215611. FT_Done_Face (lastFace);
  215612. lastFace = 0;
  215613. }
  215614. lastFontName = fontName;
  215615. lastBold = bold;
  215616. lastItalic = italic;
  215617. FreeTypeFontFace* const ftFace = findOrCreate (fontName);
  215618. if (ftFace != 0)
  215619. {
  215620. int style = (int) FreeTypeFontFace::Plain;
  215621. if (bold)
  215622. style |= (int) FreeTypeFontFace::Bold;
  215623. if (italic)
  215624. style |= (int) FreeTypeFontFace::Italic;
  215625. int faceIndex;
  215626. String fileName (ftFace->getFileName (style, faceIndex));
  215627. if (fileName.isEmpty())
  215628. {
  215629. style ^= (int) FreeTypeFontFace::Bold;
  215630. fileName = ftFace->getFileName (style, faceIndex);
  215631. if (fileName.isEmpty())
  215632. {
  215633. style ^= (int) FreeTypeFontFace::Bold;
  215634. style ^= (int) FreeTypeFontFace::Italic;
  215635. fileName = ftFace->getFileName (style, faceIndex);
  215636. if (! fileName.length())
  215637. {
  215638. style ^= (int) FreeTypeFontFace::Bold;
  215639. fileName = ftFace->getFileName (style, faceIndex);
  215640. }
  215641. }
  215642. }
  215643. if (! FT_New_Face (ftLib, fileName.toUTF8(), faceIndex, &lastFace))
  215644. {
  215645. face = lastFace;
  215646. // If there isn't a unicode charmap then select the first one.
  215647. if (FT_Select_Charmap (face, ft_encoding_unicode))
  215648. FT_Set_Charmap (face, face->charmaps[0]);
  215649. }
  215650. }
  215651. }
  215652. return face;
  215653. }
  215654. bool addGlyph (FT_Face face, CustomTypeface& dest, uint32 character)
  215655. {
  215656. const unsigned int glyphIndex = FT_Get_Char_Index (face, character);
  215657. const float height = (float) (face->ascender - face->descender);
  215658. const float scaleX = 1.0f / height;
  215659. const float scaleY = -1.0f / height;
  215660. Path destShape;
  215661. if (FT_Load_Glyph (face, glyphIndex, FT_LOAD_NO_SCALE | FT_LOAD_NO_BITMAP | FT_LOAD_IGNORE_TRANSFORM) != 0
  215662. || face->glyph->format != ft_glyph_format_outline)
  215663. {
  215664. return false;
  215665. }
  215666. const FT_Outline* const outline = &face->glyph->outline;
  215667. const short* const contours = outline->contours;
  215668. const char* const tags = outline->tags;
  215669. FT_Vector* const points = outline->points;
  215670. for (int c = 0; c < outline->n_contours; c++)
  215671. {
  215672. const int startPoint = (c == 0) ? 0 : contours [c - 1] + 1;
  215673. const int endPoint = contours[c];
  215674. for (int p = startPoint; p <= endPoint; p++)
  215675. {
  215676. const float x = scaleX * points[p].x;
  215677. const float y = scaleY * points[p].y;
  215678. if (p == startPoint)
  215679. {
  215680. if (FT_CURVE_TAG (tags[p]) == FT_Curve_Tag_Conic)
  215681. {
  215682. float x2 = scaleX * points [endPoint].x;
  215683. float y2 = scaleY * points [endPoint].y;
  215684. if (FT_CURVE_TAG (tags[endPoint]) != FT_Curve_Tag_On)
  215685. {
  215686. x2 = (x + x2) * 0.5f;
  215687. y2 = (y + y2) * 0.5f;
  215688. }
  215689. destShape.startNewSubPath (x2, y2);
  215690. }
  215691. else
  215692. {
  215693. destShape.startNewSubPath (x, y);
  215694. }
  215695. }
  215696. if (FT_CURVE_TAG (tags[p]) == FT_Curve_Tag_On)
  215697. {
  215698. if (p != startPoint)
  215699. destShape.lineTo (x, y);
  215700. }
  215701. else if (FT_CURVE_TAG (tags[p]) == FT_Curve_Tag_Conic)
  215702. {
  215703. const int nextIndex = (p == endPoint) ? startPoint : p + 1;
  215704. float x2 = scaleX * points [nextIndex].x;
  215705. float y2 = scaleY * points [nextIndex].y;
  215706. if (FT_CURVE_TAG (tags [nextIndex]) == FT_Curve_Tag_Conic)
  215707. {
  215708. x2 = (x + x2) * 0.5f;
  215709. y2 = (y + y2) * 0.5f;
  215710. }
  215711. else
  215712. {
  215713. ++p;
  215714. }
  215715. destShape.quadraticTo (x, y, x2, y2);
  215716. }
  215717. else if (FT_CURVE_TAG (tags[p]) == FT_Curve_Tag_Cubic)
  215718. {
  215719. if (p >= endPoint)
  215720. return false;
  215721. const int next1 = p + 1;
  215722. const int next2 = (p == (endPoint - 1)) ? startPoint : p + 2;
  215723. const float x2 = scaleX * points [next1].x;
  215724. const float y2 = scaleY * points [next1].y;
  215725. const float x3 = scaleX * points [next2].x;
  215726. const float y3 = scaleY * points [next2].y;
  215727. if (FT_CURVE_TAG (tags[next1]) != FT_Curve_Tag_Cubic
  215728. || FT_CURVE_TAG (tags[next2]) != FT_Curve_Tag_On)
  215729. return false;
  215730. destShape.cubicTo (x, y, x2, y2, x3, y3);
  215731. p += 2;
  215732. }
  215733. }
  215734. destShape.closeSubPath();
  215735. }
  215736. dest.addGlyph (character, destShape, face->glyph->metrics.horiAdvance / height);
  215737. if ((face->face_flags & FT_FACE_FLAG_KERNING) != 0)
  215738. addKerning (face, dest, character, glyphIndex);
  215739. return true;
  215740. }
  215741. void addKerning (FT_Face face, CustomTypeface& dest, const uint32 character, const uint32 glyphIndex)
  215742. {
  215743. const float height = (float) (face->ascender - face->descender);
  215744. uint32 rightGlyphIndex;
  215745. uint32 rightCharCode = FT_Get_First_Char (face, &rightGlyphIndex);
  215746. while (rightGlyphIndex != 0)
  215747. {
  215748. FT_Vector kerning;
  215749. if (FT_Get_Kerning (face, glyphIndex, rightGlyphIndex, ft_kerning_unscaled, &kerning) == 0)
  215750. {
  215751. if (kerning.x != 0)
  215752. dest.addKerningPair (character, rightCharCode, kerning.x / height);
  215753. }
  215754. rightCharCode = FT_Get_Next_Char (face, rightCharCode, &rightGlyphIndex);
  215755. }
  215756. }
  215757. // Add a glyph to a font
  215758. bool addGlyphToFont (const uint32 character, const String& fontName,
  215759. bool bold, bool italic, CustomTypeface& dest)
  215760. {
  215761. FT_Face face = createFT_Face (fontName, bold, italic);
  215762. return face != 0 && addGlyph (face, dest, character);
  215763. }
  215764. void getFamilyNames (StringArray& familyNames) const
  215765. {
  215766. for (int i = 0; i < faces.size(); i++)
  215767. familyNames.add (faces[i]->getFamilyName());
  215768. }
  215769. void getMonospacedNames (StringArray& monoSpaced) const
  215770. {
  215771. for (int i = 0; i < faces.size(); i++)
  215772. if (faces[i]->getMonospaced())
  215773. monoSpaced.add (faces[i]->getFamilyName());
  215774. }
  215775. void getSerifNames (StringArray& serif) const
  215776. {
  215777. for (int i = 0; i < faces.size(); i++)
  215778. if (faces[i]->getSerif())
  215779. serif.add (faces[i]->getFamilyName());
  215780. }
  215781. void getSansSerifNames (StringArray& sansSerif) const
  215782. {
  215783. for (int i = 0; i < faces.size(); i++)
  215784. if (! faces[i]->getSerif())
  215785. sansSerif.add (faces[i]->getFamilyName());
  215786. }
  215787. juce_DeclareSingleton_SingleThreaded_Minimal (FreeTypeInterface)
  215788. private:
  215789. FT_Library ftLib;
  215790. FT_Face lastFace;
  215791. String lastFontName;
  215792. bool lastBold, lastItalic;
  215793. OwnedArray<FreeTypeFontFace> faces;
  215794. };
  215795. juce_ImplementSingleton_SingleThreaded (FreeTypeInterface)
  215796. class FreetypeTypeface : public CustomTypeface
  215797. {
  215798. public:
  215799. FreetypeTypeface (const Font& font)
  215800. {
  215801. FT_Face face = FreeTypeInterface::getInstance()
  215802. ->createFT_Face (font.getTypefaceName(), font.isBold(), font.isItalic());
  215803. if (face == 0)
  215804. {
  215805. #if JUCE_DEBUG
  215806. String msg ("Failed to create typeface: ");
  215807. msg << font.getTypefaceName() << " " << (font.isBold() ? 'B' : ' ') << (font.isItalic() ? 'I' : ' ');
  215808. DBG (msg);
  215809. #endif
  215810. }
  215811. else
  215812. {
  215813. setCharacteristics (font.getTypefaceName(),
  215814. face->ascender / (float) (face->ascender - face->descender),
  215815. font.isBold(), font.isItalic(),
  215816. L' ');
  215817. }
  215818. }
  215819. bool loadGlyphIfPossible (juce_wchar character)
  215820. {
  215821. return FreeTypeInterface::getInstance()
  215822. ->addGlyphToFont (character, name, isBold, isItalic, *this);
  215823. }
  215824. };
  215825. const Typeface::Ptr Typeface::createSystemTypefaceFor (const Font& font)
  215826. {
  215827. return new FreetypeTypeface (font);
  215828. }
  215829. const StringArray Font::findAllTypefaceNames()
  215830. {
  215831. StringArray s;
  215832. FreeTypeInterface::getInstance()->getFamilyNames (s);
  215833. s.sort (true);
  215834. return s;
  215835. }
  215836. static const String pickBestFont (const StringArray& names,
  215837. const char* const choicesString)
  215838. {
  215839. StringArray choices;
  215840. choices.addTokens (String (choicesString), ",", String::empty);
  215841. choices.trim();
  215842. choices.removeEmptyStrings();
  215843. int i, j;
  215844. for (j = 0; j < choices.size(); ++j)
  215845. if (names.contains (choices[j], true))
  215846. return choices[j];
  215847. for (j = 0; j < choices.size(); ++j)
  215848. for (i = 0; i < names.size(); i++)
  215849. if (names[i].startsWithIgnoreCase (choices[j]))
  215850. return names[i];
  215851. for (j = 0; j < choices.size(); ++j)
  215852. for (i = 0; i < names.size(); i++)
  215853. if (names[i].containsIgnoreCase (choices[j]))
  215854. return names[i];
  215855. return names[0];
  215856. }
  215857. static const String linux_getDefaultSansSerifFontName()
  215858. {
  215859. StringArray allFonts;
  215860. FreeTypeInterface::getInstance()->getSansSerifNames (allFonts);
  215861. return pickBestFont (allFonts, "Verdana, Bitstream Vera Sans, Luxi Sans, Sans");
  215862. }
  215863. static const String linux_getDefaultSerifFontName()
  215864. {
  215865. StringArray allFonts;
  215866. FreeTypeInterface::getInstance()->getSerifNames (allFonts);
  215867. return pickBestFont (allFonts, "Bitstream Vera Serif, Times, Nimbus Roman, Serif");
  215868. }
  215869. static const String linux_getDefaultMonospacedFontName()
  215870. {
  215871. StringArray allFonts;
  215872. FreeTypeInterface::getInstance()->getMonospacedNames (allFonts);
  215873. return pickBestFont (allFonts, "Bitstream Vera Sans Mono, Courier, Sans Mono, Mono");
  215874. }
  215875. void Font::getPlatformDefaultFontNames (String& defaultSans, String& defaultSerif, String& defaultFixed)
  215876. {
  215877. defaultSans = linux_getDefaultSansSerifFontName();
  215878. defaultSerif = linux_getDefaultSerifFontName();
  215879. defaultFixed = linux_getDefaultMonospacedFontName();
  215880. }
  215881. #endif
  215882. /*** End of inlined file: juce_linux_Fonts.cpp ***/
  215883. /*** Start of inlined file: juce_linux_Windowing.cpp ***/
  215884. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  215885. // compiled on its own).
  215886. #if JUCE_INCLUDED_FILE
  215887. // These are defined in juce_linux_Messaging.cpp
  215888. extern Display* display;
  215889. extern XContext windowHandleXContext;
  215890. namespace Atoms
  215891. {
  215892. enum ProtocolItems
  215893. {
  215894. TAKE_FOCUS = 0,
  215895. DELETE_WINDOW = 1,
  215896. PING = 2
  215897. };
  215898. static Atom Protocols, ProtocolList[3], ChangeState, State,
  215899. ActiveWin, Pid, WindowType, WindowState,
  215900. XdndAware, XdndEnter, XdndLeave, XdndPosition, XdndStatus,
  215901. XdndDrop, XdndFinished, XdndSelection, XdndTypeList, XdndActionList,
  215902. XdndActionDescription, XdndActionCopy,
  215903. allowedActions[5],
  215904. allowedMimeTypes[2];
  215905. const unsigned long DndVersion = 3;
  215906. static void initialiseAtoms()
  215907. {
  215908. static bool atomsInitialised = false;
  215909. if (! atomsInitialised)
  215910. {
  215911. atomsInitialised = true;
  215912. Protocols = XInternAtom (display, "WM_PROTOCOLS", True);
  215913. ProtocolList [TAKE_FOCUS] = XInternAtom (display, "WM_TAKE_FOCUS", True);
  215914. ProtocolList [DELETE_WINDOW] = XInternAtom (display, "WM_DELETE_WINDOW", True);
  215915. ProtocolList [PING] = XInternAtom (display, "_NET_WM_PING", True);
  215916. ChangeState = XInternAtom (display, "WM_CHANGE_STATE", True);
  215917. State = XInternAtom (display, "WM_STATE", True);
  215918. ActiveWin = XInternAtom (display, "_NET_ACTIVE_WINDOW", False);
  215919. Pid = XInternAtom (display, "_NET_WM_PID", False);
  215920. WindowType = XInternAtom (display, "_NET_WM_WINDOW_TYPE", True);
  215921. WindowState = XInternAtom (display, "_NET_WM_STATE", True);
  215922. XdndAware = XInternAtom (display, "XdndAware", False);
  215923. XdndEnter = XInternAtom (display, "XdndEnter", False);
  215924. XdndLeave = XInternAtom (display, "XdndLeave", False);
  215925. XdndPosition = XInternAtom (display, "XdndPosition", False);
  215926. XdndStatus = XInternAtom (display, "XdndStatus", False);
  215927. XdndDrop = XInternAtom (display, "XdndDrop", False);
  215928. XdndFinished = XInternAtom (display, "XdndFinished", False);
  215929. XdndSelection = XInternAtom (display, "XdndSelection", False);
  215930. XdndTypeList = XInternAtom (display, "XdndTypeList", False);
  215931. XdndActionList = XInternAtom (display, "XdndActionList", False);
  215932. XdndActionCopy = XInternAtom (display, "XdndActionCopy", False);
  215933. XdndActionDescription = XInternAtom (display, "XdndActionDescription", False);
  215934. allowedMimeTypes[0] = XInternAtom (display, "text/plain", False);
  215935. allowedMimeTypes[1] = XInternAtom (display, "text/uri-list", False);
  215936. allowedActions[0] = XInternAtom (display, "XdndActionMove", False);
  215937. allowedActions[1] = XdndActionCopy;
  215938. allowedActions[2] = XInternAtom (display, "XdndActionLink", False);
  215939. allowedActions[3] = XInternAtom (display, "XdndActionAsk", False);
  215940. allowedActions[4] = XInternAtom (display, "XdndActionPrivate", False);
  215941. }
  215942. }
  215943. }
  215944. namespace Keys
  215945. {
  215946. enum MouseButtons
  215947. {
  215948. NoButton = 0,
  215949. LeftButton = 1,
  215950. MiddleButton = 2,
  215951. RightButton = 3,
  215952. WheelUp = 4,
  215953. WheelDown = 5
  215954. };
  215955. static int AltMask = 0;
  215956. static int NumLockMask = 0;
  215957. static bool numLock = false;
  215958. static bool capsLock = false;
  215959. static char keyStates [32];
  215960. static const int extendedKeyModifier = 0x10000000;
  215961. }
  215962. bool KeyPress::isKeyCurrentlyDown (const int keyCode)
  215963. {
  215964. int keysym;
  215965. if (keyCode & Keys::extendedKeyModifier)
  215966. {
  215967. keysym = 0xff00 | (keyCode & 0xff);
  215968. }
  215969. else
  215970. {
  215971. keysym = keyCode;
  215972. if (keysym == (XK_Tab & 0xff)
  215973. || keysym == (XK_Return & 0xff)
  215974. || keysym == (XK_Escape & 0xff)
  215975. || keysym == (XK_BackSpace & 0xff))
  215976. {
  215977. keysym |= 0xff00;
  215978. }
  215979. }
  215980. ScopedXLock xlock;
  215981. const int keycode = XKeysymToKeycode (display, keysym);
  215982. const int keybyte = keycode >> 3;
  215983. const int keybit = (1 << (keycode & 7));
  215984. return (Keys::keyStates [keybyte] & keybit) != 0;
  215985. }
  215986. #if JUCE_USE_XSHM
  215987. namespace XSHMHelpers
  215988. {
  215989. static int trappedErrorCode = 0;
  215990. extern "C" int errorTrapHandler (Display*, XErrorEvent* err)
  215991. {
  215992. trappedErrorCode = err->error_code;
  215993. return 0;
  215994. }
  215995. static bool isShmAvailable() throw()
  215996. {
  215997. static bool isChecked = false;
  215998. static bool isAvailable = false;
  215999. if (! isChecked)
  216000. {
  216001. isChecked = true;
  216002. int major, minor;
  216003. Bool pixmaps;
  216004. ScopedXLock xlock;
  216005. if (XShmQueryVersion (display, &major, &minor, &pixmaps))
  216006. {
  216007. trappedErrorCode = 0;
  216008. XErrorHandler oldHandler = XSetErrorHandler (errorTrapHandler);
  216009. XShmSegmentInfo segmentInfo;
  216010. zerostruct (segmentInfo);
  216011. XImage* xImage = XShmCreateImage (display, DefaultVisual (display, DefaultScreen (display)),
  216012. 24, ZPixmap, 0, &segmentInfo, 50, 50);
  216013. if ((segmentInfo.shmid = shmget (IPC_PRIVATE,
  216014. xImage->bytes_per_line * xImage->height,
  216015. IPC_CREAT | 0777)) >= 0)
  216016. {
  216017. segmentInfo.shmaddr = (char*) shmat (segmentInfo.shmid, 0, 0);
  216018. if (segmentInfo.shmaddr != (void*) -1)
  216019. {
  216020. segmentInfo.readOnly = False;
  216021. xImage->data = segmentInfo.shmaddr;
  216022. XSync (display, False);
  216023. if (XShmAttach (display, &segmentInfo) != 0)
  216024. {
  216025. XSync (display, False);
  216026. XShmDetach (display, &segmentInfo);
  216027. isAvailable = true;
  216028. }
  216029. }
  216030. XFlush (display);
  216031. XDestroyImage (xImage);
  216032. shmdt (segmentInfo.shmaddr);
  216033. }
  216034. shmctl (segmentInfo.shmid, IPC_RMID, 0);
  216035. XSetErrorHandler (oldHandler);
  216036. if (trappedErrorCode != 0)
  216037. isAvailable = false;
  216038. }
  216039. }
  216040. return isAvailable;
  216041. }
  216042. }
  216043. #endif
  216044. #if JUCE_USE_XRENDER
  216045. namespace XRender
  216046. {
  216047. typedef Status (*tXRenderQueryVersion) (Display*, int*, int*);
  216048. typedef XRenderPictFormat* (*tXrenderFindStandardFormat) (Display*, int);
  216049. typedef XRenderPictFormat* (*tXRenderFindFormat) (Display*, unsigned long, XRenderPictFormat*, int);
  216050. typedef XRenderPictFormat* (*tXRenderFindVisualFormat) (Display*, Visual*);
  216051. static tXRenderQueryVersion xRenderQueryVersion = 0;
  216052. static tXrenderFindStandardFormat xRenderFindStandardFormat = 0;
  216053. static tXRenderFindFormat xRenderFindFormat = 0;
  216054. static tXRenderFindVisualFormat xRenderFindVisualFormat = 0;
  216055. static bool isAvailable()
  216056. {
  216057. static bool hasLoaded = false;
  216058. if (! hasLoaded)
  216059. {
  216060. ScopedXLock xlock;
  216061. hasLoaded = true;
  216062. void* h = dlopen ("libXrender.so", RTLD_GLOBAL | RTLD_NOW);
  216063. if (h != 0)
  216064. {
  216065. xRenderQueryVersion = (tXRenderQueryVersion) dlsym (h, "XRenderQueryVersion");
  216066. xRenderFindStandardFormat = (tXrenderFindStandardFormat) dlsym (h, "XrenderFindStandardFormat");
  216067. xRenderFindFormat = (tXRenderFindFormat) dlsym (h, "XRenderFindFormat");
  216068. xRenderFindVisualFormat = (tXRenderFindVisualFormat) dlsym (h, "XRenderFindVisualFormat");
  216069. }
  216070. if (xRenderQueryVersion != 0
  216071. && xRenderFindStandardFormat != 0
  216072. && xRenderFindFormat != 0
  216073. && xRenderFindVisualFormat != 0)
  216074. {
  216075. int major, minor;
  216076. if (xRenderQueryVersion (display, &major, &minor))
  216077. return true;
  216078. }
  216079. xRenderQueryVersion = 0;
  216080. }
  216081. return xRenderQueryVersion != 0;
  216082. }
  216083. static XRenderPictFormat* findPictureFormat()
  216084. {
  216085. ScopedXLock xlock;
  216086. XRenderPictFormat* pictFormat = 0;
  216087. if (isAvailable())
  216088. {
  216089. pictFormat = xRenderFindStandardFormat (display, PictStandardARGB32);
  216090. if (pictFormat == 0)
  216091. {
  216092. XRenderPictFormat desiredFormat;
  216093. desiredFormat.type = PictTypeDirect;
  216094. desiredFormat.depth = 32;
  216095. desiredFormat.direct.alphaMask = 0xff;
  216096. desiredFormat.direct.redMask = 0xff;
  216097. desiredFormat.direct.greenMask = 0xff;
  216098. desiredFormat.direct.blueMask = 0xff;
  216099. desiredFormat.direct.alpha = 24;
  216100. desiredFormat.direct.red = 16;
  216101. desiredFormat.direct.green = 8;
  216102. desiredFormat.direct.blue = 0;
  216103. pictFormat = xRenderFindFormat (display,
  216104. PictFormatType | PictFormatDepth
  216105. | PictFormatRedMask | PictFormatRed
  216106. | PictFormatGreenMask | PictFormatGreen
  216107. | PictFormatBlueMask | PictFormatBlue
  216108. | PictFormatAlphaMask | PictFormatAlpha,
  216109. &desiredFormat,
  216110. 0);
  216111. }
  216112. }
  216113. return pictFormat;
  216114. }
  216115. }
  216116. #endif
  216117. namespace Visuals
  216118. {
  216119. static Visual* findVisualWithDepth (const int desiredDepth) throw()
  216120. {
  216121. ScopedXLock xlock;
  216122. Visual* visual = 0;
  216123. int numVisuals = 0;
  216124. long desiredMask = VisualNoMask;
  216125. XVisualInfo desiredVisual;
  216126. desiredVisual.screen = DefaultScreen (display);
  216127. desiredVisual.depth = desiredDepth;
  216128. desiredMask = VisualScreenMask | VisualDepthMask;
  216129. if (desiredDepth == 32)
  216130. {
  216131. desiredVisual.c_class = TrueColor;
  216132. desiredVisual.red_mask = 0x00FF0000;
  216133. desiredVisual.green_mask = 0x0000FF00;
  216134. desiredVisual.blue_mask = 0x000000FF;
  216135. desiredVisual.bits_per_rgb = 8;
  216136. desiredMask |= VisualClassMask;
  216137. desiredMask |= VisualRedMaskMask;
  216138. desiredMask |= VisualGreenMaskMask;
  216139. desiredMask |= VisualBlueMaskMask;
  216140. desiredMask |= VisualBitsPerRGBMask;
  216141. }
  216142. XVisualInfo* xvinfos = XGetVisualInfo (display,
  216143. desiredMask,
  216144. &desiredVisual,
  216145. &numVisuals);
  216146. if (xvinfos != 0)
  216147. {
  216148. for (int i = 0; i < numVisuals; i++)
  216149. {
  216150. if (xvinfos[i].depth == desiredDepth)
  216151. {
  216152. visual = xvinfos[i].visual;
  216153. break;
  216154. }
  216155. }
  216156. XFree (xvinfos);
  216157. }
  216158. return visual;
  216159. }
  216160. static Visual* findVisualFormat (const int desiredDepth, int& matchedDepth) throw()
  216161. {
  216162. Visual* visual = 0;
  216163. if (desiredDepth == 32)
  216164. {
  216165. #if JUCE_USE_XSHM
  216166. if (XSHMHelpers::isShmAvailable())
  216167. {
  216168. #if JUCE_USE_XRENDER
  216169. if (XRender::isAvailable())
  216170. {
  216171. XRenderPictFormat* pictFormat = XRender::findPictureFormat();
  216172. if (pictFormat != 0)
  216173. {
  216174. int numVisuals = 0;
  216175. XVisualInfo desiredVisual;
  216176. desiredVisual.screen = DefaultScreen (display);
  216177. desiredVisual.depth = 32;
  216178. desiredVisual.bits_per_rgb = 8;
  216179. XVisualInfo* xvinfos = XGetVisualInfo (display,
  216180. VisualScreenMask | VisualDepthMask | VisualBitsPerRGBMask,
  216181. &desiredVisual, &numVisuals);
  216182. if (xvinfos != 0)
  216183. {
  216184. for (int i = 0; i < numVisuals; ++i)
  216185. {
  216186. XRenderPictFormat* pictVisualFormat = XRender::xRenderFindVisualFormat (display, xvinfos[i].visual);
  216187. if (pictVisualFormat != 0
  216188. && pictVisualFormat->type == PictTypeDirect
  216189. && pictVisualFormat->direct.alphaMask)
  216190. {
  216191. visual = xvinfos[i].visual;
  216192. matchedDepth = 32;
  216193. break;
  216194. }
  216195. }
  216196. XFree (xvinfos);
  216197. }
  216198. }
  216199. }
  216200. #endif
  216201. if (visual == 0)
  216202. {
  216203. visual = findVisualWithDepth (32);
  216204. if (visual != 0)
  216205. matchedDepth = 32;
  216206. }
  216207. }
  216208. #endif
  216209. }
  216210. if (visual == 0 && desiredDepth >= 24)
  216211. {
  216212. visual = findVisualWithDepth (24);
  216213. if (visual != 0)
  216214. matchedDepth = 24;
  216215. }
  216216. if (visual == 0 && desiredDepth >= 16)
  216217. {
  216218. visual = findVisualWithDepth (16);
  216219. if (visual != 0)
  216220. matchedDepth = 16;
  216221. }
  216222. return visual;
  216223. }
  216224. }
  216225. class XBitmapImage : public Image
  216226. {
  216227. public:
  216228. XBitmapImage (const PixelFormat format_, const int w, const int h,
  216229. const bool clearImage, const int imageDepth_, Visual* visual)
  216230. : Image (format_, w, h),
  216231. imageDepth (imageDepth_),
  216232. gc (None)
  216233. {
  216234. jassert (format_ == RGB || format_ == ARGB);
  216235. pixelStride = (format_ == RGB) ? 3 : 4;
  216236. lineStride = ((w * pixelStride + 3) & ~3);
  216237. ScopedXLock xlock;
  216238. #if JUCE_USE_XSHM
  216239. usingXShm = false;
  216240. if ((imageDepth > 16) && XSHMHelpers::isShmAvailable())
  216241. {
  216242. zerostruct (segmentInfo);
  216243. segmentInfo.shmid = -1;
  216244. segmentInfo.shmaddr = (char *) -1;
  216245. segmentInfo.readOnly = False;
  216246. xImage = XShmCreateImage (display, visual, imageDepth, ZPixmap, 0, &segmentInfo, w, h);
  216247. if (xImage != 0)
  216248. {
  216249. if ((segmentInfo.shmid = shmget (IPC_PRIVATE,
  216250. xImage->bytes_per_line * xImage->height,
  216251. IPC_CREAT | 0777)) >= 0)
  216252. {
  216253. if (segmentInfo.shmid != -1)
  216254. {
  216255. segmentInfo.shmaddr = (char*) shmat (segmentInfo.shmid, 0, 0);
  216256. if (segmentInfo.shmaddr != (void*) -1)
  216257. {
  216258. segmentInfo.readOnly = False;
  216259. xImage->data = segmentInfo.shmaddr;
  216260. imageData = (uint8*) segmentInfo.shmaddr;
  216261. if (XShmAttach (display, &segmentInfo) != 0)
  216262. {
  216263. usingXShm = true;
  216264. }
  216265. else
  216266. {
  216267. jassertfalse
  216268. }
  216269. }
  216270. else
  216271. {
  216272. shmctl (segmentInfo.shmid, IPC_RMID, 0);
  216273. }
  216274. }
  216275. }
  216276. }
  216277. }
  216278. if (! usingXShm)
  216279. #endif
  216280. {
  216281. imageDataAllocated.malloc (lineStride * h);
  216282. imageData = imageDataAllocated;
  216283. if (format_ == ARGB && clearImage)
  216284. zeromem (imageData, h * lineStride);
  216285. xImage = (XImage*) juce_calloc (sizeof (XImage));
  216286. xImage->width = w;
  216287. xImage->height = h;
  216288. xImage->xoffset = 0;
  216289. xImage->format = ZPixmap;
  216290. xImage->data = (char*) imageData;
  216291. xImage->byte_order = ImageByteOrder (display);
  216292. xImage->bitmap_unit = BitmapUnit (display);
  216293. xImage->bitmap_bit_order = BitmapBitOrder (display);
  216294. xImage->bitmap_pad = 32;
  216295. xImage->depth = pixelStride * 8;
  216296. xImage->bytes_per_line = lineStride;
  216297. xImage->bits_per_pixel = pixelStride * 8;
  216298. xImage->red_mask = 0x00FF0000;
  216299. xImage->green_mask = 0x0000FF00;
  216300. xImage->blue_mask = 0x000000FF;
  216301. if (imageDepth == 16)
  216302. {
  216303. const int pixelStride = 2;
  216304. const int lineStride = ((w * pixelStride + 3) & ~3);
  216305. imageData16Bit.malloc (lineStride * h);
  216306. xImage->data = imageData16Bit;
  216307. xImage->bitmap_pad = 16;
  216308. xImage->depth = pixelStride * 8;
  216309. xImage->bytes_per_line = lineStride;
  216310. xImage->bits_per_pixel = pixelStride * 8;
  216311. xImage->red_mask = visual->red_mask;
  216312. xImage->green_mask = visual->green_mask;
  216313. xImage->blue_mask = visual->blue_mask;
  216314. }
  216315. if (! XInitImage (xImage))
  216316. {
  216317. jassertfalse
  216318. }
  216319. }
  216320. }
  216321. ~XBitmapImage()
  216322. {
  216323. ScopedXLock xlock;
  216324. if (gc != None)
  216325. XFreeGC (display, gc);
  216326. #if JUCE_USE_XSHM
  216327. if (usingXShm)
  216328. {
  216329. XShmDetach (display, &segmentInfo);
  216330. XFlush (display);
  216331. XDestroyImage (xImage);
  216332. shmdt (segmentInfo.shmaddr);
  216333. shmctl (segmentInfo.shmid, IPC_RMID, 0);
  216334. }
  216335. else
  216336. #endif
  216337. {
  216338. xImage->data = 0;
  216339. XDestroyImage (xImage);
  216340. }
  216341. }
  216342. void blitToWindow (Window window, int dx, int dy, int dw, int dh, int sx, int sy)
  216343. {
  216344. ScopedXLock xlock;
  216345. if (gc == None)
  216346. {
  216347. XGCValues gcvalues;
  216348. gcvalues.foreground = None;
  216349. gcvalues.background = None;
  216350. gcvalues.function = GXcopy;
  216351. gcvalues.plane_mask = AllPlanes;
  216352. gcvalues.clip_mask = None;
  216353. gcvalues.graphics_exposures = False;
  216354. gc = XCreateGC (display, window,
  216355. GCBackground | GCForeground | GCFunction | GCPlaneMask | GCClipMask | GCGraphicsExposures,
  216356. &gcvalues);
  216357. }
  216358. if (imageDepth == 16)
  216359. {
  216360. const uint32 rMask = xImage->red_mask;
  216361. const uint32 rShiftL = jmax (0, getShiftNeeded (rMask));
  216362. const uint32 rShiftR = jmax (0, -getShiftNeeded (rMask));
  216363. const uint32 gMask = xImage->green_mask;
  216364. const uint32 gShiftL = jmax (0, getShiftNeeded (gMask));
  216365. const uint32 gShiftR = jmax (0, -getShiftNeeded (gMask));
  216366. const uint32 bMask = xImage->blue_mask;
  216367. const uint32 bShiftL = jmax (0, getShiftNeeded (bMask));
  216368. const uint32 bShiftR = jmax (0, -getShiftNeeded (bMask));
  216369. const Image::BitmapData srcData (*this, 0, 0, getWidth(), getHeight());
  216370. for (int y = sy; y < sy + dh; ++y)
  216371. {
  216372. const uint8* p = srcData.getPixelPointer (sx, y);
  216373. for (int x = sx; x < sx + dw; ++x)
  216374. {
  216375. const PixelRGB* const pixel = (const PixelRGB*) p;
  216376. p += srcData.pixelStride;
  216377. XPutPixel (xImage, x, y,
  216378. (((((uint32) pixel->getRed()) << rShiftL) >> rShiftR) & rMask)
  216379. | (((((uint32) pixel->getGreen()) << gShiftL) >> gShiftR) & gMask)
  216380. | (((((uint32) pixel->getBlue()) << bShiftL) >> bShiftR) & bMask));
  216381. }
  216382. }
  216383. }
  216384. // blit results to screen.
  216385. #if JUCE_USE_XSHM
  216386. if (usingXShm)
  216387. XShmPutImage (display, (::Drawable) window, gc, xImage, sx, sy, dx, dy, dw, dh, True);
  216388. else
  216389. #endif
  216390. XPutImage (display, (::Drawable) window, gc, xImage, sx, sy, dx, dy, dw, dh);
  216391. }
  216392. juce_UseDebuggingNewOperator
  216393. private:
  216394. XImage* xImage;
  216395. const int imageDepth;
  216396. HeapBlock <char> imageData16Bit;
  216397. GC gc;
  216398. #if JUCE_USE_XSHM
  216399. XShmSegmentInfo segmentInfo;
  216400. bool usingXShm;
  216401. #endif
  216402. static int getShiftNeeded (const uint32 mask) throw()
  216403. {
  216404. for (int i = 32; --i >= 0;)
  216405. if (((mask >> i) & 1) != 0)
  216406. return i - 7;
  216407. jassertfalse
  216408. return 0;
  216409. }
  216410. };
  216411. class LinuxComponentPeer : public ComponentPeer
  216412. {
  216413. public:
  216414. LinuxComponentPeer (Component* const component, const int windowStyleFlags)
  216415. : ComponentPeer (component, windowStyleFlags),
  216416. windowH (0),
  216417. parentWindow (0),
  216418. wx (0),
  216419. wy (0),
  216420. ww (0),
  216421. wh (0),
  216422. fullScreen (false),
  216423. mapped (false),
  216424. visual (0),
  216425. depth (0)
  216426. {
  216427. // it's dangerous to create a window on a thread other than the message thread..
  216428. jassert (MessageManager::getInstance()->currentThreadHasLockedMessageManager());
  216429. repainter = new LinuxRepaintManager (this);
  216430. createWindow();
  216431. setTitle (component->getName());
  216432. }
  216433. ~LinuxComponentPeer()
  216434. {
  216435. // it's dangerous to delete a window on a thread other than the message thread..
  216436. jassert (MessageManager::getInstance()->currentThreadHasLockedMessageManager());
  216437. deleteIconPixmaps();
  216438. destroyWindow();
  216439. windowH = 0;
  216440. }
  216441. void* getNativeHandle() const
  216442. {
  216443. return (void*) windowH;
  216444. }
  216445. static LinuxComponentPeer* getPeerFor (Window windowHandle) throw()
  216446. {
  216447. XPointer peer = 0;
  216448. ScopedXLock xlock;
  216449. if (! XFindContext (display, (XID) windowHandle, windowHandleXContext, &peer))
  216450. {
  216451. if (peer != 0 && ! ComponentPeer::isValidPeer ((LinuxComponentPeer*) peer))
  216452. peer = 0;
  216453. }
  216454. return (LinuxComponentPeer*) peer;
  216455. }
  216456. void setVisible (bool shouldBeVisible)
  216457. {
  216458. ScopedXLock xlock;
  216459. if (shouldBeVisible)
  216460. XMapWindow (display, windowH);
  216461. else
  216462. XUnmapWindow (display, windowH);
  216463. }
  216464. void setTitle (const String& title)
  216465. {
  216466. setWindowTitle (windowH, title);
  216467. }
  216468. void setPosition (int x, int y)
  216469. {
  216470. setBounds (x, y, ww, wh, false);
  216471. }
  216472. void setSize (int w, int h)
  216473. {
  216474. setBounds (wx, wy, w, h, false);
  216475. }
  216476. void setBounds (int x, int y, int w, int h, bool isNowFullScreen)
  216477. {
  216478. fullScreen = isNowFullScreen;
  216479. if (windowH != 0)
  216480. {
  216481. Component::SafePointer<Component> deletionChecker (component);
  216482. wx = x;
  216483. wy = y;
  216484. ww = jmax (1, w);
  216485. wh = jmax (1, h);
  216486. ScopedXLock xlock;
  216487. // Make sure the Window manager does what we want
  216488. XSizeHints* hints = XAllocSizeHints();
  216489. hints->flags = USSize | USPosition;
  216490. hints->width = ww;
  216491. hints->height = wh;
  216492. hints->x = wx;
  216493. hints->y = wy;
  216494. if ((getStyleFlags() & (windowHasTitleBar | windowIsResizable)) == windowHasTitleBar)
  216495. {
  216496. hints->min_width = hints->max_width = hints->width;
  216497. hints->min_height = hints->max_height = hints->height;
  216498. hints->flags |= PMinSize | PMaxSize;
  216499. }
  216500. XSetWMNormalHints (display, windowH, hints);
  216501. XFree (hints);
  216502. XMoveResizeWindow (display, windowH,
  216503. wx - windowBorder.getLeft(),
  216504. wy - windowBorder.getTop(), ww, wh);
  216505. if (deletionChecker != 0)
  216506. {
  216507. updateBorderSize();
  216508. handleMovedOrResized();
  216509. }
  216510. }
  216511. }
  216512. const Rectangle<int> getBounds() const { return Rectangle<int> (wx, wy, ww, wh); }
  216513. const Point<int> getScreenPosition() const { return Point<int> (wx, wy); }
  216514. const Point<int> relativePositionToGlobal (const Point<int>& relativePosition)
  216515. {
  216516. return relativePosition + getScreenPosition();
  216517. }
  216518. const Point<int> globalPositionToRelative (const Point<int>& screenPosition)
  216519. {
  216520. return screenPosition - getScreenPosition();
  216521. }
  216522. void setMinimised (bool shouldBeMinimised)
  216523. {
  216524. if (shouldBeMinimised)
  216525. {
  216526. Window root = RootWindow (display, DefaultScreen (display));
  216527. XClientMessageEvent clientMsg;
  216528. clientMsg.display = display;
  216529. clientMsg.window = windowH;
  216530. clientMsg.type = ClientMessage;
  216531. clientMsg.format = 32;
  216532. clientMsg.message_type = Atoms::ChangeState;
  216533. clientMsg.data.l[0] = IconicState;
  216534. ScopedXLock xlock;
  216535. XSendEvent (display, root, false,
  216536. SubstructureRedirectMask | SubstructureNotifyMask,
  216537. (XEvent*) &clientMsg);
  216538. }
  216539. else
  216540. {
  216541. setVisible (true);
  216542. }
  216543. }
  216544. bool isMinimised() const
  216545. {
  216546. bool minimised = false;
  216547. unsigned char* stateProp;
  216548. unsigned long nitems, bytesLeft;
  216549. Atom actualType;
  216550. int actualFormat;
  216551. ScopedXLock xlock;
  216552. if (XGetWindowProperty (display, windowH, Atoms::State, 0, 64, False,
  216553. Atoms::State, &actualType, &actualFormat, &nitems, &bytesLeft,
  216554. &stateProp) == Success
  216555. && actualType == Atoms::State
  216556. && actualFormat == 32
  216557. && nitems > 0)
  216558. {
  216559. if (((unsigned long*) stateProp)[0] == IconicState)
  216560. minimised = true;
  216561. XFree (stateProp);
  216562. }
  216563. return minimised;
  216564. }
  216565. void setFullScreen (const bool shouldBeFullScreen)
  216566. {
  216567. Rectangle<int> r (lastNonFullscreenBounds); // (get a copy of this before de-minimising)
  216568. setMinimised (false);
  216569. if (fullScreen != shouldBeFullScreen)
  216570. {
  216571. if (shouldBeFullScreen)
  216572. r = Desktop::getInstance().getMainMonitorArea();
  216573. if (! r.isEmpty())
  216574. setBounds (r.getX(), r.getY(), r.getWidth(), r.getHeight(), shouldBeFullScreen);
  216575. getComponent()->repaint();
  216576. }
  216577. }
  216578. bool isFullScreen() const
  216579. {
  216580. return fullScreen;
  216581. }
  216582. bool isChildWindowOf (Window possibleParent) const
  216583. {
  216584. Window* windowList = 0;
  216585. uint32 windowListSize = 0;
  216586. Window parent, root;
  216587. ScopedXLock xlock;
  216588. if (XQueryTree (display, windowH, &root, &parent, &windowList, &windowListSize) != 0)
  216589. {
  216590. if (windowList != 0)
  216591. XFree (windowList);
  216592. return parent == possibleParent;
  216593. }
  216594. return false;
  216595. }
  216596. bool isFrontWindow() const
  216597. {
  216598. Window* windowList = 0;
  216599. uint32 windowListSize = 0;
  216600. bool result = false;
  216601. ScopedXLock xlock;
  216602. Window parent, root = RootWindow (display, DefaultScreen (display));
  216603. if (XQueryTree (display, root, &root, &parent, &windowList, &windowListSize) != 0)
  216604. {
  216605. for (int i = windowListSize; --i >= 0;)
  216606. {
  216607. LinuxComponentPeer* const peer = LinuxComponentPeer::getPeerFor (windowList[i]);
  216608. if (peer != 0)
  216609. {
  216610. result = (peer == this);
  216611. break;
  216612. }
  216613. }
  216614. }
  216615. if (windowList != 0)
  216616. XFree (windowList);
  216617. return result;
  216618. }
  216619. bool contains (const Point<int>& position, bool trueIfInAChildWindow) const
  216620. {
  216621. int x = position.getX();
  216622. int y = position.getY();
  216623. if (((unsigned int) x) >= (unsigned int) ww
  216624. || ((unsigned int) y) >= (unsigned int) wh)
  216625. return false;
  216626. bool inFront = false;
  216627. for (int i = 0; i < Desktop::getInstance().getNumComponents(); ++i)
  216628. {
  216629. Component* const c = Desktop::getInstance().getComponent (i);
  216630. if (inFront)
  216631. {
  216632. if (c->contains (x + wx - c->getScreenX(),
  216633. y + wy - c->getScreenY()))
  216634. {
  216635. return false;
  216636. }
  216637. }
  216638. else if (c == getComponent())
  216639. {
  216640. inFront = true;
  216641. }
  216642. }
  216643. if (trueIfInAChildWindow)
  216644. return true;
  216645. ::Window root, child;
  216646. unsigned int bw, depth;
  216647. int wx, wy, w, h;
  216648. ScopedXLock xlock;
  216649. if (! XGetGeometry (display, (::Drawable) windowH, &root,
  216650. &wx, &wy, (unsigned int*) &w, (unsigned int*) &h,
  216651. &bw, &depth))
  216652. {
  216653. return false;
  216654. }
  216655. if (! XTranslateCoordinates (display, windowH, windowH, x, y, &wx, &wy, &child))
  216656. return false;
  216657. return child == None;
  216658. }
  216659. const BorderSize getFrameSize() const
  216660. {
  216661. return BorderSize();
  216662. }
  216663. bool setAlwaysOnTop (bool alwaysOnTop)
  216664. {
  216665. if (windowH != 0)
  216666. {
  216667. const bool wasVisible = component->isVisible();
  216668. if (wasVisible)
  216669. setVisible (false); // doesn't always seem to work if the window is visible when this is done..
  216670. {
  216671. ScopedXLock xlock;
  216672. XSetWindowAttributes swa;
  216673. swa.override_redirect = alwaysOnTop ? True : False;
  216674. XChangeWindowAttributes (display, windowH, CWOverrideRedirect, &swa);
  216675. }
  216676. if (wasVisible)
  216677. setVisible (true);
  216678. }
  216679. return true;
  216680. }
  216681. void toFront (bool makeActive)
  216682. {
  216683. if (makeActive)
  216684. {
  216685. setVisible (true);
  216686. grabFocus();
  216687. }
  216688. XEvent ev;
  216689. ev.xclient.type = ClientMessage;
  216690. ev.xclient.serial = 0;
  216691. ev.xclient.send_event = True;
  216692. ev.xclient.message_type = Atoms::ActiveWin;
  216693. ev.xclient.window = windowH;
  216694. ev.xclient.format = 32;
  216695. ev.xclient.data.l[0] = 2;
  216696. ev.xclient.data.l[1] = CurrentTime;
  216697. ev.xclient.data.l[2] = 0;
  216698. ev.xclient.data.l[3] = 0;
  216699. ev.xclient.data.l[4] = 0;
  216700. {
  216701. ScopedXLock xlock;
  216702. XSendEvent (display, RootWindow (display, DefaultScreen (display)),
  216703. False,
  216704. SubstructureRedirectMask | SubstructureNotifyMask,
  216705. &ev);
  216706. XWindowAttributes attr;
  216707. XGetWindowAttributes (display, windowH, &attr);
  216708. if (attr.override_redirect)
  216709. XRaiseWindow (display, windowH);
  216710. XSync (display, False);
  216711. }
  216712. handleBroughtToFront();
  216713. }
  216714. void toBehind (ComponentPeer* other)
  216715. {
  216716. LinuxComponentPeer* const otherPeer = dynamic_cast <LinuxComponentPeer*> (other);
  216717. jassert (otherPeer != 0); // wrong type of window?
  216718. if (otherPeer != 0)
  216719. {
  216720. setMinimised (false);
  216721. Window newStack[] = { otherPeer->windowH, windowH };
  216722. ScopedXLock xlock;
  216723. XRestackWindows (display, newStack, 2);
  216724. }
  216725. }
  216726. bool isFocused() const
  216727. {
  216728. int revert;
  216729. Window focusedWindow = 0;
  216730. ScopedXLock xlock;
  216731. XGetInputFocus (display, &focusedWindow, &revert);
  216732. return focusedWindow == windowH;
  216733. }
  216734. void grabFocus()
  216735. {
  216736. XWindowAttributes atts;
  216737. ScopedXLock xlock;
  216738. if (windowH != 0
  216739. && XGetWindowAttributes (display, windowH, &atts)
  216740. && atts.map_state == IsViewable
  216741. && ! isFocused())
  216742. {
  216743. XSetInputFocus (display, windowH, RevertToParent, CurrentTime);
  216744. isActiveApplication = true;
  216745. }
  216746. }
  216747. void textInputRequired (const Point<int>&)
  216748. {
  216749. }
  216750. void repaint (int x, int y, int w, int h)
  216751. {
  216752. if (Rectangle<int>::intersectRectangles (x, y, w, h,
  216753. 0, 0,
  216754. getComponent()->getWidth(),
  216755. getComponent()->getHeight()))
  216756. {
  216757. repainter->repaint (x, y, w, h);
  216758. }
  216759. }
  216760. void performAnyPendingRepaintsNow()
  216761. {
  216762. repainter->performAnyPendingRepaintsNow();
  216763. }
  216764. static Pixmap juce_createColourPixmapFromImage (Display* display, const Image& image)
  216765. {
  216766. ScopedXLock xlock;
  216767. const int width = image.getWidth();
  216768. const int height = image.getHeight();
  216769. HeapBlock <char> colour (width * height);
  216770. int index = 0;
  216771. for (int y = 0; y < height; ++y)
  216772. for (int x = 0; x < width; ++x)
  216773. colour[index++] = static_cast<char> (image.getPixelAt (x, y).getARGB());
  216774. XImage* ximage = XCreateImage (display, CopyFromParent, 24, ZPixmap,
  216775. 0, colour.getData(),
  216776. width, height, 32, 0);
  216777. Pixmap pixmap = XCreatePixmap (display, DefaultRootWindow (display),
  216778. width, height, 24);
  216779. GC gc = XCreateGC (display, pixmap, 0, 0);
  216780. XPutImage (display, pixmap, gc, ximage, 0, 0, 0, 0, width, height);
  216781. XFreeGC (display, gc);
  216782. return pixmap;
  216783. }
  216784. static Pixmap juce_createMaskPixmapFromImage (Display* display, const Image& image)
  216785. {
  216786. ScopedXLock xlock;
  216787. const int width = image.getWidth();
  216788. const int height = image.getHeight();
  216789. const int stride = (width + 7) >> 3;
  216790. HeapBlock <char> mask;
  216791. mask.calloc (stride * height);
  216792. const bool msbfirst = (BitmapBitOrder (display) == MSBFirst);
  216793. for (int y = 0; y < height; ++y)
  216794. {
  216795. for (int x = 0; x < width; ++x)
  216796. {
  216797. const char bit = (char) (1 << (msbfirst ? (7 - (x & 7)) : (x & 7)));
  216798. const int offset = y * stride + (x >> 3);
  216799. if (image.getPixelAt (x, y).getAlpha() >= 128)
  216800. mask[offset] |= bit;
  216801. }
  216802. }
  216803. return XCreatePixmapFromBitmapData (display, DefaultRootWindow (display),
  216804. mask.getData(), width, height, 1, 0, 1);
  216805. }
  216806. void setIcon (const Image& newIcon)
  216807. {
  216808. const int dataSize = newIcon.getWidth() * newIcon.getHeight() + 2;
  216809. HeapBlock <unsigned long> data (dataSize);
  216810. int index = 0;
  216811. data[index++] = newIcon.getWidth();
  216812. data[index++] = newIcon.getHeight();
  216813. for (int y = 0; y < newIcon.getHeight(); ++y)
  216814. for (int x = 0; x < newIcon.getWidth(); ++x)
  216815. data[index++] = newIcon.getPixelAt (x, y).getARGB();
  216816. ScopedXLock xlock;
  216817. XChangeProperty (display, windowH,
  216818. XInternAtom (display, "_NET_WM_ICON", False),
  216819. XA_CARDINAL, 32, PropModeReplace,
  216820. reinterpret_cast<unsigned char*> (data.getData()), dataSize);
  216821. deleteIconPixmaps();
  216822. XWMHints* wmHints = XGetWMHints (display, windowH);
  216823. if (wmHints == 0)
  216824. wmHints = XAllocWMHints();
  216825. wmHints->flags |= IconPixmapHint | IconMaskHint;
  216826. wmHints->icon_pixmap = juce_createColourPixmapFromImage (display, newIcon);
  216827. wmHints->icon_mask = juce_createMaskPixmapFromImage (display, newIcon);
  216828. XSetWMHints (display, windowH, wmHints);
  216829. XFree (wmHints);
  216830. XSync (display, False);
  216831. }
  216832. void deleteIconPixmaps()
  216833. {
  216834. ScopedXLock xlock;
  216835. XWMHints* wmHints = XGetWMHints (display, windowH);
  216836. if (wmHints != 0)
  216837. {
  216838. if ((wmHints->flags & IconPixmapHint) != 0)
  216839. {
  216840. wmHints->flags &= ~IconPixmapHint;
  216841. XFreePixmap (display, wmHints->icon_pixmap);
  216842. }
  216843. if ((wmHints->flags & IconMaskHint) != 0)
  216844. {
  216845. wmHints->flags &= ~IconMaskHint;
  216846. XFreePixmap (display, wmHints->icon_mask);
  216847. }
  216848. XSetWMHints (display, windowH, wmHints);
  216849. XFree (wmHints);
  216850. }
  216851. }
  216852. void handleWindowMessage (XEvent* event)
  216853. {
  216854. switch (event->xany.type)
  216855. {
  216856. case 2: // 'KeyPress'
  216857. {
  216858. ScopedXLock xlock;
  216859. XKeyEvent* const keyEvent = (XKeyEvent*) &event->xkey;
  216860. updateKeyStates (keyEvent->keycode, true);
  216861. char utf8 [64];
  216862. zeromem (utf8, sizeof (utf8));
  216863. KeySym sym;
  216864. {
  216865. const char* oldLocale = ::setlocale (LC_ALL, 0);
  216866. ::setlocale (LC_ALL, "");
  216867. XLookupString (keyEvent, utf8, sizeof (utf8), &sym, 0);
  216868. ::setlocale (LC_ALL, oldLocale);
  216869. }
  216870. const juce_wchar unicodeChar = String::fromUTF8 (utf8, sizeof (utf8) - 1) [0];
  216871. int keyCode = (int) unicodeChar;
  216872. if (keyCode < 0x20)
  216873. keyCode = XKeycodeToKeysym (display, keyEvent->keycode, currentModifiers.isShiftDown() ? 1 : 0);
  216874. const ModifierKeys oldMods (currentModifiers);
  216875. bool keyPressed = false;
  216876. const bool keyDownChange = (sym != NoSymbol) && ! updateKeyModifiersFromSym (sym, true);
  216877. if ((sym & 0xff00) == 0xff00)
  216878. {
  216879. // Translate keypad
  216880. if (sym == XK_KP_Divide)
  216881. keyCode = XK_slash;
  216882. else if (sym == XK_KP_Multiply)
  216883. keyCode = XK_asterisk;
  216884. else if (sym == XK_KP_Subtract)
  216885. keyCode = XK_hyphen;
  216886. else if (sym == XK_KP_Add)
  216887. keyCode = XK_plus;
  216888. else if (sym == XK_KP_Enter)
  216889. keyCode = XK_Return;
  216890. else if (sym == XK_KP_Decimal)
  216891. keyCode = Keys::numLock ? XK_period : XK_Delete;
  216892. else if (sym == XK_KP_0)
  216893. keyCode = Keys::numLock ? XK_0 : XK_Insert;
  216894. else if (sym == XK_KP_1)
  216895. keyCode = Keys::numLock ? XK_1 : XK_End;
  216896. else if (sym == XK_KP_2)
  216897. keyCode = Keys::numLock ? XK_2 : XK_Down;
  216898. else if (sym == XK_KP_3)
  216899. keyCode = Keys::numLock ? XK_3 : XK_Page_Down;
  216900. else if (sym == XK_KP_4)
  216901. keyCode = Keys::numLock ? XK_4 : XK_Left;
  216902. else if (sym == XK_KP_5)
  216903. keyCode = XK_5;
  216904. else if (sym == XK_KP_6)
  216905. keyCode = Keys::numLock ? XK_6 : XK_Right;
  216906. else if (sym == XK_KP_7)
  216907. keyCode = Keys::numLock ? XK_7 : XK_Home;
  216908. else if (sym == XK_KP_8)
  216909. keyCode = Keys::numLock ? XK_8 : XK_Up;
  216910. else if (sym == XK_KP_9)
  216911. keyCode = Keys::numLock ? XK_9 : XK_Page_Up;
  216912. switch (sym)
  216913. {
  216914. case XK_Left:
  216915. case XK_Right:
  216916. case XK_Up:
  216917. case XK_Down:
  216918. case XK_Page_Up:
  216919. case XK_Page_Down:
  216920. case XK_End:
  216921. case XK_Home:
  216922. case XK_Delete:
  216923. case XK_Insert:
  216924. keyPressed = true;
  216925. keyCode = (sym & 0xff) | Keys::extendedKeyModifier;
  216926. break;
  216927. case XK_Tab:
  216928. case XK_Return:
  216929. case XK_Escape:
  216930. case XK_BackSpace:
  216931. keyPressed = true;
  216932. keyCode &= 0xff;
  216933. break;
  216934. default:
  216935. {
  216936. if (sym >= XK_F1 && sym <= XK_F16)
  216937. {
  216938. keyPressed = true;
  216939. keyCode = (sym & 0xff) | Keys::extendedKeyModifier;
  216940. }
  216941. break;
  216942. }
  216943. }
  216944. }
  216945. if (utf8[0] != 0 || ((sym & 0xff00) == 0 && sym >= 8))
  216946. keyPressed = true;
  216947. if (oldMods != currentModifiers)
  216948. handleModifierKeysChange();
  216949. if (keyDownChange)
  216950. handleKeyUpOrDown (true);
  216951. if (keyPressed)
  216952. handleKeyPress (keyCode, unicodeChar);
  216953. break;
  216954. }
  216955. case KeyRelease:
  216956. {
  216957. const XKeyEvent* const keyEvent = (const XKeyEvent*) &event->xkey;
  216958. updateKeyStates (keyEvent->keycode, false);
  216959. ScopedXLock xlock;
  216960. KeySym sym = XKeycodeToKeysym (display, keyEvent->keycode, 0);
  216961. const ModifierKeys oldMods (currentModifiers);
  216962. const bool keyDownChange = (sym != NoSymbol) && ! updateKeyModifiersFromSym (sym, false);
  216963. if (oldMods != currentModifiers)
  216964. handleModifierKeysChange();
  216965. if (keyDownChange)
  216966. handleKeyUpOrDown (false);
  216967. break;
  216968. }
  216969. case ButtonPress:
  216970. {
  216971. const XButtonPressedEvent* const buttonPressEvent = (const XButtonPressedEvent*) &event->xbutton;
  216972. updateKeyModifiers (buttonPressEvent->state);
  216973. bool buttonMsg = false;
  216974. const int map = pointerMap [buttonPressEvent->button - Button1];
  216975. if (map == Keys::WheelUp || map == Keys::WheelDown)
  216976. {
  216977. handleMouseWheel (0, Point<int> (buttonPressEvent->x, buttonPressEvent->y),
  216978. getEventTime (buttonPressEvent->time), 0, map == Keys::WheelDown ? -84.0f : 84.0f);
  216979. }
  216980. if (map == Keys::LeftButton)
  216981. {
  216982. currentModifiers = currentModifiers.withFlags (ModifierKeys::leftButtonModifier);
  216983. buttonMsg = true;
  216984. }
  216985. else if (map == Keys::RightButton)
  216986. {
  216987. currentModifiers = currentModifiers.withFlags (ModifierKeys::rightButtonModifier);
  216988. buttonMsg = true;
  216989. }
  216990. else if (map == Keys::MiddleButton)
  216991. {
  216992. currentModifiers = currentModifiers.withFlags (ModifierKeys::middleButtonModifier);
  216993. buttonMsg = true;
  216994. }
  216995. if (buttonMsg)
  216996. {
  216997. toFront (true);
  216998. handleMouseEvent (0, Point<int> (buttonPressEvent->x, buttonPressEvent->y), currentModifiers,
  216999. getEventTime (buttonPressEvent->time));
  217000. }
  217001. clearLastMousePos();
  217002. break;
  217003. }
  217004. case ButtonRelease:
  217005. {
  217006. const XButtonReleasedEvent* const buttonRelEvent = (const XButtonReleasedEvent*) &event->xbutton;
  217007. updateKeyModifiers (buttonRelEvent->state);
  217008. const int map = pointerMap [buttonRelEvent->button - Button1];
  217009. if (map == Keys::LeftButton)
  217010. currentModifiers = currentModifiers.withoutFlags (ModifierKeys::leftButtonModifier);
  217011. else if (map == Keys::RightButton)
  217012. currentModifiers = currentModifiers.withoutFlags (ModifierKeys::rightButtonModifier);
  217013. else if (map == Keys::MiddleButton)
  217014. currentModifiers = currentModifiers.withoutFlags (ModifierKeys::middleButtonModifier);
  217015. handleMouseEvent (0, Point<int> (buttonRelEvent->x, buttonRelEvent->y), currentModifiers,
  217016. getEventTime (buttonRelEvent->time));
  217017. clearLastMousePos();
  217018. break;
  217019. }
  217020. case MotionNotify:
  217021. {
  217022. const XPointerMovedEvent* const movedEvent = (const XPointerMovedEvent*) &event->xmotion;
  217023. updateKeyModifiers (movedEvent->state);
  217024. const Point<int> mousePos (Desktop::getMousePosition());
  217025. if (lastMousePos != mousePos)
  217026. {
  217027. lastMousePos = mousePos;
  217028. if (parentWindow != 0 && (styleFlags & windowHasTitleBar) == 0)
  217029. {
  217030. Window wRoot = 0, wParent = 0;
  217031. {
  217032. ScopedXLock xlock;
  217033. unsigned int numChildren;
  217034. Window* wChild = 0;
  217035. XQueryTree (display, windowH, &wRoot, &wParent, &wChild, &numChildren);
  217036. }
  217037. if (wParent != 0
  217038. && wParent != windowH
  217039. && wParent != wRoot)
  217040. {
  217041. parentWindow = wParent;
  217042. updateBounds();
  217043. }
  217044. else
  217045. {
  217046. parentWindow = 0;
  217047. }
  217048. }
  217049. handleMouseEvent (0, mousePos - getScreenPosition(), currentModifiers, getEventTime (movedEvent->time));
  217050. }
  217051. break;
  217052. }
  217053. case EnterNotify:
  217054. {
  217055. clearLastMousePos();
  217056. const XEnterWindowEvent* const enterEvent = (const XEnterWindowEvent*) &event->xcrossing;
  217057. if (! currentModifiers.isAnyMouseButtonDown())
  217058. {
  217059. updateKeyModifiers (enterEvent->state);
  217060. handleMouseEvent (0, Point<int> (enterEvent->x, enterEvent->y), currentModifiers, getEventTime (enterEvent->time));
  217061. }
  217062. break;
  217063. }
  217064. case LeaveNotify:
  217065. {
  217066. const XLeaveWindowEvent* const leaveEvent = (const XLeaveWindowEvent*) &event->xcrossing;
  217067. // Suppress the normal leave if we've got a pointer grab, or if
  217068. // it's a bogus one caused by clicking a mouse button when running
  217069. // in a Window manager
  217070. if (((! currentModifiers.isAnyMouseButtonDown()) && leaveEvent->mode == NotifyNormal)
  217071. || leaveEvent->mode == NotifyUngrab)
  217072. {
  217073. updateKeyModifiers (leaveEvent->state);
  217074. handleMouseEvent (0, Point<int> (leaveEvent->x, leaveEvent->y), currentModifiers, getEventTime (leaveEvent->time));
  217075. }
  217076. break;
  217077. }
  217078. case FocusIn:
  217079. {
  217080. isActiveApplication = true;
  217081. if (isFocused())
  217082. handleFocusGain();
  217083. break;
  217084. }
  217085. case FocusOut:
  217086. {
  217087. isActiveApplication = false;
  217088. if (! isFocused())
  217089. handleFocusLoss();
  217090. break;
  217091. }
  217092. case Expose:
  217093. {
  217094. // Batch together all pending expose events
  217095. XExposeEvent* exposeEvent = (XExposeEvent*) &event->xexpose;
  217096. XEvent nextEvent;
  217097. ScopedXLock xlock;
  217098. if (exposeEvent->window != windowH)
  217099. {
  217100. Window child;
  217101. XTranslateCoordinates (display, exposeEvent->window, windowH,
  217102. exposeEvent->x, exposeEvent->y, &exposeEvent->x, &exposeEvent->y,
  217103. &child);
  217104. }
  217105. repaint (exposeEvent->x, exposeEvent->y,
  217106. exposeEvent->width, exposeEvent->height);
  217107. while (XEventsQueued (display, QueuedAfterFlush) > 0)
  217108. {
  217109. XPeekEvent (display, (XEvent*) &nextEvent);
  217110. if (nextEvent.type != Expose || nextEvent.xany.window != event->xany.window)
  217111. break;
  217112. XNextEvent (display, (XEvent*) &nextEvent);
  217113. XExposeEvent* nextExposeEvent = (XExposeEvent*) &nextEvent.xexpose;
  217114. repaint (nextExposeEvent->x, nextExposeEvent->y,
  217115. nextExposeEvent->width, nextExposeEvent->height);
  217116. }
  217117. break;
  217118. }
  217119. case CirculateNotify:
  217120. case CreateNotify:
  217121. case DestroyNotify:
  217122. // Think we can ignore these
  217123. break;
  217124. case ConfigureNotify:
  217125. {
  217126. updateBounds();
  217127. updateBorderSize();
  217128. handleMovedOrResized();
  217129. // if the native title bar is dragged, need to tell any active menus, etc.
  217130. if ((styleFlags & windowHasTitleBar) != 0
  217131. && component->isCurrentlyBlockedByAnotherModalComponent())
  217132. {
  217133. Component* const currentModalComp = Component::getCurrentlyModalComponent();
  217134. if (currentModalComp != 0)
  217135. currentModalComp->inputAttemptWhenModal();
  217136. }
  217137. XConfigureEvent* const confEvent = (XConfigureEvent*) &event->xconfigure;
  217138. if (confEvent->window == windowH
  217139. && confEvent->above != 0
  217140. && isFrontWindow())
  217141. {
  217142. handleBroughtToFront();
  217143. }
  217144. break;
  217145. }
  217146. case ReparentNotify:
  217147. {
  217148. parentWindow = 0;
  217149. Window wRoot = 0;
  217150. Window* wChild = 0;
  217151. unsigned int numChildren;
  217152. {
  217153. ScopedXLock xlock;
  217154. XQueryTree (display, windowH, &wRoot, &parentWindow, &wChild, &numChildren);
  217155. }
  217156. if (parentWindow == windowH || parentWindow == wRoot)
  217157. parentWindow = 0;
  217158. updateBounds();
  217159. updateBorderSize();
  217160. handleMovedOrResized();
  217161. break;
  217162. }
  217163. case GravityNotify:
  217164. {
  217165. updateBounds();
  217166. updateBorderSize();
  217167. handleMovedOrResized();
  217168. break;
  217169. }
  217170. case MapNotify:
  217171. mapped = true;
  217172. handleBroughtToFront();
  217173. break;
  217174. case UnmapNotify:
  217175. mapped = false;
  217176. break;
  217177. case MappingNotify:
  217178. {
  217179. XMappingEvent* mappingEvent = (XMappingEvent*) &event->xmapping;
  217180. if (mappingEvent->request != MappingPointer)
  217181. {
  217182. // Deal with modifier/keyboard mapping
  217183. ScopedXLock xlock;
  217184. XRefreshKeyboardMapping (mappingEvent);
  217185. updateModifierMappings();
  217186. }
  217187. break;
  217188. }
  217189. case ClientMessage:
  217190. {
  217191. const XClientMessageEvent* const clientMsg = (const XClientMessageEvent*) &event->xclient;
  217192. if (clientMsg->message_type == Atoms::Protocols && clientMsg->format == 32)
  217193. {
  217194. const Atom atom = (Atom) clientMsg->data.l[0];
  217195. if (atom == Atoms::ProtocolList [Atoms::PING])
  217196. {
  217197. Window root = RootWindow (display, DefaultScreen (display));
  217198. event->xclient.window = root;
  217199. XSendEvent (display, root, False, NoEventMask, event);
  217200. XFlush (display);
  217201. }
  217202. else if (atom == Atoms::ProtocolList [Atoms::TAKE_FOCUS])
  217203. {
  217204. XWindowAttributes atts;
  217205. ScopedXLock xlock;
  217206. if (clientMsg->window != 0
  217207. && XGetWindowAttributes (display, clientMsg->window, &atts))
  217208. {
  217209. if (atts.map_state == IsViewable)
  217210. XSetInputFocus (display, clientMsg->window, RevertToParent, clientMsg->data.l[1]);
  217211. }
  217212. }
  217213. else if (atom == Atoms::ProtocolList [Atoms::DELETE_WINDOW])
  217214. {
  217215. handleUserClosingWindow();
  217216. }
  217217. }
  217218. else if (clientMsg->message_type == Atoms::XdndEnter)
  217219. {
  217220. handleDragAndDropEnter (clientMsg);
  217221. }
  217222. else if (clientMsg->message_type == Atoms::XdndLeave)
  217223. {
  217224. resetDragAndDrop();
  217225. }
  217226. else if (clientMsg->message_type == Atoms::XdndPosition)
  217227. {
  217228. handleDragAndDropPosition (clientMsg);
  217229. }
  217230. else if (clientMsg->message_type == Atoms::XdndDrop)
  217231. {
  217232. handleDragAndDropDrop (clientMsg);
  217233. }
  217234. else if (clientMsg->message_type == Atoms::XdndStatus)
  217235. {
  217236. handleDragAndDropStatus (clientMsg);
  217237. }
  217238. else if (clientMsg->message_type == Atoms::XdndFinished)
  217239. {
  217240. resetDragAndDrop();
  217241. }
  217242. break;
  217243. }
  217244. case SelectionNotify:
  217245. handleDragAndDropSelection (event);
  217246. break;
  217247. case SelectionClear:
  217248. case SelectionRequest:
  217249. break;
  217250. default:
  217251. #if JUCE_USE_XSHM
  217252. {
  217253. ScopedXLock xlock;
  217254. if (event->xany.type == XShmGetEventBase (display))
  217255. repainter->notifyPaintCompleted();
  217256. }
  217257. #endif
  217258. break;
  217259. }
  217260. }
  217261. void showMouseCursor (Cursor cursor) throw()
  217262. {
  217263. ScopedXLock xlock;
  217264. XDefineCursor (display, windowH, cursor);
  217265. }
  217266. void setTaskBarIcon (const Image& image)
  217267. {
  217268. ScopedXLock xlock;
  217269. taskbarImage = image.createCopy();
  217270. Screen* const screen = XDefaultScreenOfDisplay (display);
  217271. const int screenNumber = XScreenNumberOfScreen (screen);
  217272. String screenAtom ("_NET_SYSTEM_TRAY_S");
  217273. screenAtom << screenNumber;
  217274. Atom selectionAtom = XInternAtom (display, screenAtom.toUTF8(), false);
  217275. XGrabServer (display);
  217276. Window managerWin = XGetSelectionOwner (display, selectionAtom);
  217277. if (managerWin != None)
  217278. XSelectInput (display, managerWin, StructureNotifyMask);
  217279. XUngrabServer (display);
  217280. XFlush (display);
  217281. if (managerWin != None)
  217282. {
  217283. XEvent ev;
  217284. zerostruct (ev);
  217285. ev.xclient.type = ClientMessage;
  217286. ev.xclient.window = managerWin;
  217287. ev.xclient.message_type = XInternAtom (display, "_NET_SYSTEM_TRAY_OPCODE", False);
  217288. ev.xclient.format = 32;
  217289. ev.xclient.data.l[0] = CurrentTime;
  217290. ev.xclient.data.l[1] = 0 /*SYSTEM_TRAY_REQUEST_DOCK*/;
  217291. ev.xclient.data.l[2] = windowH;
  217292. ev.xclient.data.l[3] = 0;
  217293. ev.xclient.data.l[4] = 0;
  217294. XSendEvent (display, managerWin, False, NoEventMask, &ev);
  217295. XSync (display, False);
  217296. }
  217297. // For older KDE's ...
  217298. long atomData = 1;
  217299. Atom trayAtom = XInternAtom (display, "KWM_DOCKWINDOW", false);
  217300. XChangeProperty (display, windowH, trayAtom, trayAtom, 32, PropModeReplace, (unsigned char*) &atomData, 1);
  217301. // For more recent KDE's...
  217302. trayAtom = XInternAtom (display, "_KDE_NET_WM_SYSTEM_TRAY_WINDOW_FOR", false);
  217303. XChangeProperty (display, windowH, trayAtom, XA_WINDOW, 32, PropModeReplace, (unsigned char*) &windowH, 1);
  217304. // a minimum size must be specified for GNOME and Xfce, otherwise the icon is displayed with a width of 1
  217305. XSizeHints* hints = XAllocSizeHints();
  217306. hints->flags = PMinSize;
  217307. hints->min_width = 22;
  217308. hints->min_height = 22;
  217309. XSetWMNormalHints (display, windowH, hints);
  217310. XFree (hints);
  217311. }
  217312. const Image* getTaskbarIcon() const throw() { return taskbarImage; }
  217313. juce_UseDebuggingNewOperator
  217314. bool dontRepaint;
  217315. static ModifierKeys currentModifiers;
  217316. static bool isActiveApplication;
  217317. private:
  217318. class LinuxRepaintManager : public Timer
  217319. {
  217320. public:
  217321. LinuxRepaintManager (LinuxComponentPeer* const peer_)
  217322. : peer (peer_),
  217323. lastTimeImageUsed (0)
  217324. {
  217325. #if JUCE_USE_XSHM
  217326. shmCompletedDrawing = true;
  217327. useARGBImagesForRendering = XSHMHelpers::isShmAvailable();
  217328. if (useARGBImagesForRendering)
  217329. {
  217330. ScopedXLock xlock;
  217331. XShmSegmentInfo segmentinfo;
  217332. XImage* const testImage
  217333. = XShmCreateImage (display, DefaultVisual (display, DefaultScreen (display)),
  217334. 24, ZPixmap, 0, &segmentinfo, 64, 64);
  217335. useARGBImagesForRendering = (testImage->bits_per_pixel == 32);
  217336. XDestroyImage (testImage);
  217337. }
  217338. #endif
  217339. }
  217340. ~LinuxRepaintManager()
  217341. {
  217342. }
  217343. void timerCallback()
  217344. {
  217345. #if JUCE_USE_XSHM
  217346. if (! shmCompletedDrawing)
  217347. return;
  217348. #endif
  217349. if (! regionsNeedingRepaint.isEmpty())
  217350. {
  217351. stopTimer();
  217352. performAnyPendingRepaintsNow();
  217353. }
  217354. else if (Time::getApproximateMillisecondCounter() > lastTimeImageUsed + 3000)
  217355. {
  217356. stopTimer();
  217357. image = 0;
  217358. }
  217359. }
  217360. void repaint (int x, int y, int w, int h)
  217361. {
  217362. if (! isTimerRunning())
  217363. startTimer (repaintTimerPeriod);
  217364. regionsNeedingRepaint.add (x, y, w, h);
  217365. }
  217366. void performAnyPendingRepaintsNow()
  217367. {
  217368. #if JUCE_USE_XSHM
  217369. if (! shmCompletedDrawing)
  217370. {
  217371. startTimer (repaintTimerPeriod);
  217372. return;
  217373. }
  217374. #endif
  217375. peer->clearMaskedRegion();
  217376. RectangleList originalRepaintRegion (regionsNeedingRepaint);
  217377. regionsNeedingRepaint.clear();
  217378. const Rectangle<int> totalArea (originalRepaintRegion.getBounds());
  217379. if (! totalArea.isEmpty())
  217380. {
  217381. if (image == 0 || image->getWidth() < totalArea.getWidth()
  217382. || image->getHeight() < totalArea.getHeight())
  217383. {
  217384. #if JUCE_USE_XSHM
  217385. image = new XBitmapImage (useARGBImagesForRendering ? Image::ARGB
  217386. : Image::RGB,
  217387. #else
  217388. image = new XBitmapImage (Image::RGB,
  217389. #endif
  217390. (totalArea.getWidth() + 31) & ~31,
  217391. (totalArea.getHeight() + 31) & ~31,
  217392. false,
  217393. peer->depth,
  217394. peer->visual);
  217395. }
  217396. startTimer (repaintTimerPeriod);
  217397. RectangleList adjustedList (originalRepaintRegion);
  217398. adjustedList.offsetAll (-totalArea.getX(), -totalArea.getY());
  217399. LowLevelGraphicsSoftwareRenderer context (*image, -totalArea.getX(), -totalArea.getY(), adjustedList);
  217400. if (peer->depth == 32)
  217401. {
  217402. RectangleList::Iterator i (originalRepaintRegion);
  217403. while (i.next())
  217404. image->clear (*i.getRectangle() - totalArea.getPosition());
  217405. }
  217406. peer->handlePaint (context);
  217407. if (! peer->maskedRegion.isEmpty())
  217408. originalRepaintRegion.subtract (peer->maskedRegion);
  217409. for (RectangleList::Iterator i (originalRepaintRegion); i.next();)
  217410. {
  217411. #if JUCE_USE_XSHM
  217412. shmCompletedDrawing = false;
  217413. #endif
  217414. const Rectangle<int>& r = *i.getRectangle();
  217415. image->blitToWindow (peer->windowH,
  217416. r.getX(), r.getY(), r.getWidth(), r.getHeight(),
  217417. r.getX() - totalArea.getX(), r.getY() - totalArea.getY());
  217418. }
  217419. }
  217420. lastTimeImageUsed = Time::getApproximateMillisecondCounter();
  217421. startTimer (repaintTimerPeriod);
  217422. }
  217423. #if JUCE_USE_XSHM
  217424. void notifyPaintCompleted() { shmCompletedDrawing = true; }
  217425. #endif
  217426. private:
  217427. enum { repaintTimerPeriod = 1000 / 100 };
  217428. LinuxComponentPeer* const peer;
  217429. ScopedPointer <XBitmapImage> image;
  217430. uint32 lastTimeImageUsed;
  217431. RectangleList regionsNeedingRepaint;
  217432. #if JUCE_USE_XSHM
  217433. bool useARGBImagesForRendering, shmCompletedDrawing;
  217434. #endif
  217435. LinuxRepaintManager (const LinuxRepaintManager&);
  217436. LinuxRepaintManager& operator= (const LinuxRepaintManager&);
  217437. };
  217438. ScopedPointer <LinuxRepaintManager> repainter;
  217439. friend class LinuxRepaintManager;
  217440. Window windowH, parentWindow;
  217441. int wx, wy, ww, wh;
  217442. ScopedPointer<Image> taskbarImage;
  217443. bool fullScreen, mapped;
  217444. Visual* visual;
  217445. int depth;
  217446. BorderSize windowBorder;
  217447. struct MotifWmHints
  217448. {
  217449. unsigned long flags;
  217450. unsigned long functions;
  217451. unsigned long decorations;
  217452. long input_mode;
  217453. unsigned long status;
  217454. };
  217455. static void updateKeyStates (const int keycode, const bool press) throw()
  217456. {
  217457. const int keybyte = keycode >> 3;
  217458. const int keybit = (1 << (keycode & 7));
  217459. if (press)
  217460. Keys::keyStates [keybyte] |= keybit;
  217461. else
  217462. Keys::keyStates [keybyte] &= ~keybit;
  217463. }
  217464. static void updateKeyModifiers (const int status) throw()
  217465. {
  217466. int keyMods = 0;
  217467. if (status & ShiftMask) keyMods |= ModifierKeys::shiftModifier;
  217468. if (status & ControlMask) keyMods |= ModifierKeys::ctrlModifier;
  217469. if (status & Keys::AltMask) keyMods |= ModifierKeys::altModifier;
  217470. currentModifiers = currentModifiers.withOnlyMouseButtons().withFlags (keyMods);
  217471. Keys::numLock = ((status & Keys::NumLockMask) != 0);
  217472. Keys::capsLock = ((status & LockMask) != 0);
  217473. }
  217474. static bool updateKeyModifiersFromSym (KeySym sym, const bool press) throw()
  217475. {
  217476. int modifier = 0;
  217477. bool isModifier = true;
  217478. switch (sym)
  217479. {
  217480. case XK_Shift_L:
  217481. case XK_Shift_R:
  217482. modifier = ModifierKeys::shiftModifier;
  217483. break;
  217484. case XK_Control_L:
  217485. case XK_Control_R:
  217486. modifier = ModifierKeys::ctrlModifier;
  217487. break;
  217488. case XK_Alt_L:
  217489. case XK_Alt_R:
  217490. modifier = ModifierKeys::altModifier;
  217491. break;
  217492. case XK_Num_Lock:
  217493. if (press)
  217494. Keys::numLock = ! Keys::numLock;
  217495. break;
  217496. case XK_Caps_Lock:
  217497. if (press)
  217498. Keys::capsLock = ! Keys::capsLock;
  217499. break;
  217500. case XK_Scroll_Lock:
  217501. break;
  217502. default:
  217503. isModifier = false;
  217504. break;
  217505. }
  217506. if (modifier != 0)
  217507. {
  217508. if (press)
  217509. currentModifiers = currentModifiers.withFlags (modifier);
  217510. else
  217511. currentModifiers = currentModifiers.withoutFlags (modifier);
  217512. }
  217513. return isModifier;
  217514. }
  217515. // Alt and Num lock are not defined by standard X
  217516. // modifier constants: check what they're mapped to
  217517. static void updateModifierMappings() throw()
  217518. {
  217519. ScopedXLock xlock;
  217520. const int altLeftCode = XKeysymToKeycode (display, XK_Alt_L);
  217521. const int numLockCode = XKeysymToKeycode (display, XK_Num_Lock);
  217522. Keys::AltMask = 0;
  217523. Keys::NumLockMask = 0;
  217524. XModifierKeymap* mapping = XGetModifierMapping (display);
  217525. if (mapping)
  217526. {
  217527. for (int i = 0; i < 8; i++)
  217528. {
  217529. if (mapping->modifiermap [i << 1] == altLeftCode)
  217530. Keys::AltMask = 1 << i;
  217531. else if (mapping->modifiermap [i << 1] == numLockCode)
  217532. Keys::NumLockMask = 1 << i;
  217533. }
  217534. XFreeModifiermap (mapping);
  217535. }
  217536. }
  217537. void removeWindowDecorations (Window wndH)
  217538. {
  217539. Atom hints = XInternAtom (display, "_MOTIF_WM_HINTS", True);
  217540. if (hints != None)
  217541. {
  217542. MotifWmHints motifHints;
  217543. zerostruct (motifHints);
  217544. motifHints.flags = 2; /* MWM_HINTS_DECORATIONS */
  217545. motifHints.decorations = 0;
  217546. ScopedXLock xlock;
  217547. XChangeProperty (display, wndH, hints, hints, 32, PropModeReplace,
  217548. (unsigned char*) &motifHints, 4);
  217549. }
  217550. hints = XInternAtom (display, "_WIN_HINTS", True);
  217551. if (hints != None)
  217552. {
  217553. long gnomeHints = 0;
  217554. ScopedXLock xlock;
  217555. XChangeProperty (display, wndH, hints, hints, 32, PropModeReplace,
  217556. (unsigned char*) &gnomeHints, 1);
  217557. }
  217558. hints = XInternAtom (display, "KWM_WIN_DECORATION", True);
  217559. if (hints != None)
  217560. {
  217561. long kwmHints = 2; /*KDE_tinyDecoration*/
  217562. ScopedXLock xlock;
  217563. XChangeProperty (display, wndH, hints, hints, 32, PropModeReplace,
  217564. (unsigned char*) &kwmHints, 1);
  217565. }
  217566. }
  217567. void addWindowButtons (Window wndH)
  217568. {
  217569. ScopedXLock xlock;
  217570. Atom hints = XInternAtom (display, "_MOTIF_WM_HINTS", True);
  217571. if (hints != None)
  217572. {
  217573. MotifWmHints motifHints;
  217574. zerostruct (motifHints);
  217575. motifHints.flags = 1 | 2; /* MWM_HINTS_FUNCTIONS | MWM_HINTS_DECORATIONS */
  217576. motifHints.decorations = 2 /* MWM_DECOR_BORDER */ | 8 /* MWM_DECOR_TITLE */ | 16; /* MWM_DECOR_MENU */
  217577. motifHints.functions = 4 /* MWM_FUNC_MOVE */;
  217578. if ((styleFlags & windowHasCloseButton) != 0)
  217579. motifHints.functions |= 32; /* MWM_FUNC_CLOSE */
  217580. if ((styleFlags & windowHasMinimiseButton) != 0)
  217581. {
  217582. motifHints.functions |= 8; /* MWM_FUNC_MINIMIZE */
  217583. motifHints.decorations |= 0x20; /* MWM_DECOR_MINIMIZE */
  217584. }
  217585. if ((styleFlags & windowHasMaximiseButton) != 0)
  217586. {
  217587. motifHints.functions |= 0x10; /* MWM_FUNC_MAXIMIZE */
  217588. motifHints.decorations |= 0x40; /* MWM_DECOR_MAXIMIZE */
  217589. }
  217590. if ((styleFlags & windowIsResizable) != 0)
  217591. {
  217592. motifHints.functions |= 2; /* MWM_FUNC_RESIZE */
  217593. motifHints.decorations |= 0x4; /* MWM_DECOR_RESIZEH */
  217594. }
  217595. XChangeProperty (display, wndH, hints, hints, 32, 0, (unsigned char*) &motifHints, 5);
  217596. }
  217597. hints = XInternAtom (display, "_NET_WM_ALLOWED_ACTIONS", True);
  217598. if (hints != None)
  217599. {
  217600. int netHints [6];
  217601. int num = 0;
  217602. netHints [num++] = XInternAtom (display, "_NET_WM_ACTION_RESIZE", (styleFlags & windowIsResizable) ? True : False);
  217603. netHints [num++] = XInternAtom (display, "_NET_WM_ACTION_FULLSCREEN", (styleFlags & windowHasMaximiseButton) ? True : False);
  217604. netHints [num++] = XInternAtom (display, "_NET_WM_ACTION_MINIMIZE", (styleFlags & windowHasMinimiseButton) ? True : False);
  217605. netHints [num++] = XInternAtom (display, "_NET_WM_ACTION_CLOSE", (styleFlags & windowHasCloseButton) ? True : False);
  217606. XChangeProperty (display, wndH, hints, XA_ATOM, 32, PropModeReplace,
  217607. (unsigned char*) &netHints, num);
  217608. }
  217609. }
  217610. void setWindowType (Window wndH)
  217611. {
  217612. int netHints [2];
  217613. int numHints = 0;
  217614. if ((styleFlags & windowIsTemporary) != 0
  217615. || ((styleFlags & windowHasDropShadow) == 0 && Desktop::canUseSemiTransparentWindows()))
  217616. {
  217617. netHints [numHints] = XInternAtom (display, "_NET_WM_WINDOW_TYPE_COMBO", True);
  217618. }
  217619. else
  217620. {
  217621. netHints [numHints] = XInternAtom (display, "_NET_WM_WINDOW_TYPE_NORMAL", True);
  217622. }
  217623. if (netHints [numHints] != 0)
  217624. ++numHints;
  217625. netHints[numHints] = XInternAtom (display, "_KDE_NET_WM_WINDOW_TYPE_OVERRIDE", True);
  217626. if (netHints [numHints] != 0)
  217627. ++numHints;
  217628. XChangeProperty (display, wndH, Atoms::WindowType, XA_ATOM, 32, PropModeReplace,
  217629. (unsigned char*) &netHints, numHints);
  217630. if ((styleFlags & windowAppearsOnTaskbar) == 0)
  217631. {
  217632. Atom skipTaskbar = XInternAtom (display, "_NET_WM_STATE_SKIP_TASKBAR", False);
  217633. XChangeProperty (display, wndH, Atoms::WindowState, XA_ATOM, 32, PropModeReplace,
  217634. (unsigned char*) &skipTaskbar, 1);
  217635. }
  217636. }
  217637. void createWindow()
  217638. {
  217639. ScopedXLock xlock;
  217640. Atoms::initialiseAtoms();
  217641. resetDragAndDrop();
  217642. // Get defaults for various properties
  217643. const int screen = DefaultScreen (display);
  217644. Window root = RootWindow (display, screen);
  217645. // Try to obtain a 32-bit visual or fallback to 24 or 16
  217646. visual = Visuals::findVisualFormat ((styleFlags & windowIsSemiTransparent) ? 32 : 24, depth);
  217647. if (visual == 0)
  217648. {
  217649. Logger::outputDebugString ("ERROR: System doesn't support 32, 24 or 16 bit RGB display.\n");
  217650. Process::terminate();
  217651. }
  217652. // Create and install a colormap suitable fr our visual
  217653. Colormap colormap = XCreateColormap (display, root, visual, AllocNone);
  217654. XInstallColormap (display, colormap);
  217655. // Set up the window attributes
  217656. XSetWindowAttributes swa;
  217657. swa.border_pixel = 0;
  217658. swa.background_pixmap = None;
  217659. swa.colormap = colormap;
  217660. swa.override_redirect = getComponent()->isAlwaysOnTop() ? True : False;
  217661. swa.event_mask = getAllEventsMask();
  217662. Window wndH = XCreateWindow (display, root,
  217663. 0, 0, 1, 1,
  217664. 0, depth, InputOutput, visual,
  217665. CWBorderPixel | CWColormap | CWBackPixmap | CWEventMask | CWOverrideRedirect,
  217666. &swa);
  217667. XGrabButton (display, AnyButton, AnyModifier, wndH, False,
  217668. ButtonPressMask | ButtonReleaseMask | EnterWindowMask | LeaveWindowMask | PointerMotionMask,
  217669. GrabModeAsync, GrabModeAsync, None, None);
  217670. // Set the window context to identify the window handle object
  217671. if (XSaveContext (display, (XID) wndH, windowHandleXContext, (XPointer) this))
  217672. {
  217673. // Failed
  217674. jassertfalse
  217675. Logger::outputDebugString ("Failed to create context information for window.\n");
  217676. XDestroyWindow (display, wndH);
  217677. wndH = 0;
  217678. }
  217679. // Set window manager hints
  217680. XWMHints* wmHints = XAllocWMHints();
  217681. wmHints->flags = InputHint | StateHint;
  217682. wmHints->input = True; // Locally active input model
  217683. wmHints->initial_state = NormalState;
  217684. XSetWMHints (display, wndH, wmHints);
  217685. XFree (wmHints);
  217686. // Set the window type
  217687. setWindowType (wndH);
  217688. // Define decoration
  217689. if ((styleFlags & windowHasTitleBar) == 0)
  217690. removeWindowDecorations (wndH);
  217691. else
  217692. addWindowButtons (wndH);
  217693. // Set window name
  217694. setWindowTitle (wndH, getComponent()->getName());
  217695. // Associate the PID, allowing to be shut down when something goes wrong
  217696. unsigned long pid = getpid();
  217697. XChangeProperty (display, wndH, Atoms::Pid, XA_CARDINAL, 32, PropModeReplace,
  217698. (unsigned char*) &pid, 1);
  217699. // Set window manager protocols
  217700. XChangeProperty (display, wndH, Atoms::Protocols, XA_ATOM, 32, PropModeReplace,
  217701. (unsigned char*) Atoms::ProtocolList, 2);
  217702. // Set drag and drop flags
  217703. XChangeProperty (display, wndH, Atoms::XdndTypeList, XA_ATOM, 32, PropModeReplace,
  217704. (const unsigned char*) Atoms::allowedMimeTypes, numElementsInArray (Atoms::allowedMimeTypes));
  217705. XChangeProperty (display, wndH, Atoms::XdndActionList, XA_ATOM, 32, PropModeReplace,
  217706. (const unsigned char*) Atoms::allowedActions, numElementsInArray (Atoms::allowedActions));
  217707. XChangeProperty (display, wndH, Atoms::XdndActionDescription, XA_STRING, 8, PropModeReplace,
  217708. (const unsigned char*) "", 0);
  217709. unsigned long dndVersion = Atoms::DndVersion;
  217710. XChangeProperty (display, wndH, Atoms::XdndAware, XA_ATOM, 32, PropModeReplace,
  217711. (const unsigned char*) &dndVersion, 1);
  217712. // Initialise the pointer and keyboard mapping
  217713. // This is not the same as the logical pointer mapping the X server uses:
  217714. // we don't mess with this.
  217715. static bool mappingInitialised = false;
  217716. if (! mappingInitialised)
  217717. {
  217718. mappingInitialised = true;
  217719. const int numButtons = XGetPointerMapping (display, 0, 0);
  217720. if (numButtons == 2)
  217721. {
  217722. pointerMap[0] = Keys::LeftButton;
  217723. pointerMap[1] = Keys::RightButton;
  217724. pointerMap[2] = pointerMap[3] = pointerMap[4] = Keys::NoButton;
  217725. }
  217726. else if (numButtons >= 3)
  217727. {
  217728. pointerMap[0] = Keys::LeftButton;
  217729. pointerMap[1] = Keys::MiddleButton;
  217730. pointerMap[2] = Keys::RightButton;
  217731. if (numButtons >= 5)
  217732. {
  217733. pointerMap[3] = Keys::WheelUp;
  217734. pointerMap[4] = Keys::WheelDown;
  217735. }
  217736. }
  217737. updateModifierMappings();
  217738. }
  217739. windowH = wndH;
  217740. }
  217741. void destroyWindow()
  217742. {
  217743. ScopedXLock xlock;
  217744. XPointer handlePointer;
  217745. if (! XFindContext (display, (XID) windowH, windowHandleXContext, &handlePointer))
  217746. XDeleteContext (display, (XID) windowH, windowHandleXContext);
  217747. XDestroyWindow (display, windowH);
  217748. // Wait for it to complete and then remove any events for this
  217749. // window from the event queue.
  217750. XSync (display, false);
  217751. XEvent event;
  217752. while (XCheckWindowEvent (display, windowH, getAllEventsMask(), &event) == True)
  217753. {}
  217754. }
  217755. static int getAllEventsMask() throw()
  217756. {
  217757. return NoEventMask | KeyPressMask | KeyReleaseMask | ButtonPressMask | ButtonReleaseMask
  217758. | EnterWindowMask | LeaveWindowMask | PointerMotionMask | KeymapStateMask
  217759. | ExposureMask | StructureNotifyMask | FocusChangeMask;
  217760. }
  217761. static int64 getEventTime (::Time t)
  217762. {
  217763. static int64 eventTimeOffset = 0x12345678;
  217764. const int64 thisMessageTime = t;
  217765. if (eventTimeOffset == 0x12345678)
  217766. eventTimeOffset = Time::currentTimeMillis() - thisMessageTime;
  217767. return eventTimeOffset + thisMessageTime;
  217768. }
  217769. static void setWindowTitle (Window xwin, const String& title)
  217770. {
  217771. XTextProperty nameProperty;
  217772. char* strings[] = { const_cast <char*> (title.toUTF8()) };
  217773. ScopedXLock xlock;
  217774. if (XStringListToTextProperty (strings, 1, &nameProperty))
  217775. {
  217776. XSetWMName (display, xwin, &nameProperty);
  217777. XSetWMIconName (display, xwin, &nameProperty);
  217778. XFree (nameProperty.value);
  217779. }
  217780. }
  217781. void updateBorderSize()
  217782. {
  217783. if ((styleFlags & windowHasTitleBar) == 0)
  217784. {
  217785. windowBorder = BorderSize (0);
  217786. }
  217787. else if (windowBorder.getTopAndBottom() == 0 && windowBorder.getLeftAndRight() == 0)
  217788. {
  217789. ScopedXLock xlock;
  217790. Atom hints = XInternAtom (display, "_NET_FRAME_EXTENTS", True);
  217791. if (hints != None)
  217792. {
  217793. unsigned char* data = 0;
  217794. unsigned long nitems, bytesLeft;
  217795. Atom actualType;
  217796. int actualFormat;
  217797. if (XGetWindowProperty (display, windowH, hints, 0, 4, False,
  217798. XA_CARDINAL, &actualType, &actualFormat, &nitems, &bytesLeft,
  217799. &data) == Success)
  217800. {
  217801. const unsigned long* const sizes = (const unsigned long*) data;
  217802. if (actualFormat == 32)
  217803. windowBorder = BorderSize ((int) sizes[2], (int) sizes[0],
  217804. (int) sizes[3], (int) sizes[1]);
  217805. XFree (data);
  217806. }
  217807. }
  217808. }
  217809. }
  217810. void updateBounds()
  217811. {
  217812. jassert (windowH != 0);
  217813. if (windowH != 0)
  217814. {
  217815. Window root, child;
  217816. unsigned int bw, depth;
  217817. ScopedXLock xlock;
  217818. if (! XGetGeometry (display, (::Drawable) windowH, &root,
  217819. &wx, &wy, (unsigned int*) &ww, (unsigned int*) &wh,
  217820. &bw, &depth))
  217821. {
  217822. wx = wy = ww = wh = 0;
  217823. }
  217824. else if (! XTranslateCoordinates (display, windowH, root, 0, 0, &wx, &wy, &child))
  217825. {
  217826. wx = wy = 0;
  217827. }
  217828. }
  217829. }
  217830. void resetDragAndDrop()
  217831. {
  217832. dragAndDropFiles.clear();
  217833. lastDropPos = Point<int> (-1, -1);
  217834. dragAndDropCurrentMimeType = 0;
  217835. dragAndDropSourceWindow = 0;
  217836. srcMimeTypeAtomList.clear();
  217837. }
  217838. void sendDragAndDropMessage (XClientMessageEvent& msg)
  217839. {
  217840. msg.type = ClientMessage;
  217841. msg.display = display;
  217842. msg.window = dragAndDropSourceWindow;
  217843. msg.format = 32;
  217844. msg.data.l[0] = windowH;
  217845. ScopedXLock xlock;
  217846. XSendEvent (display, dragAndDropSourceWindow, False, 0, (XEvent*) &msg);
  217847. }
  217848. void sendDragAndDropStatus (const bool acceptDrop, Atom dropAction)
  217849. {
  217850. XClientMessageEvent msg;
  217851. zerostruct (msg);
  217852. msg.message_type = Atoms::XdndStatus;
  217853. msg.data.l[1] = (acceptDrop ? 1 : 0) | 2; // 2 indicates that we want to receive position messages
  217854. msg.data.l[4] = dropAction;
  217855. sendDragAndDropMessage (msg);
  217856. }
  217857. void sendDragAndDropLeave()
  217858. {
  217859. XClientMessageEvent msg;
  217860. zerostruct (msg);
  217861. msg.message_type = Atoms::XdndLeave;
  217862. sendDragAndDropMessage (msg);
  217863. }
  217864. void sendDragAndDropFinish()
  217865. {
  217866. XClientMessageEvent msg;
  217867. zerostruct (msg);
  217868. msg.message_type = Atoms::XdndFinished;
  217869. sendDragAndDropMessage (msg);
  217870. }
  217871. void handleDragAndDropStatus (const XClientMessageEvent* const clientMsg)
  217872. {
  217873. if ((clientMsg->data.l[1] & 1) == 0)
  217874. {
  217875. sendDragAndDropLeave();
  217876. if (dragAndDropFiles.size() > 0)
  217877. handleFileDragExit (dragAndDropFiles);
  217878. dragAndDropFiles.clear();
  217879. }
  217880. }
  217881. void handleDragAndDropPosition (const XClientMessageEvent* const clientMsg)
  217882. {
  217883. if (dragAndDropSourceWindow == 0)
  217884. return;
  217885. dragAndDropSourceWindow = clientMsg->data.l[0];
  217886. Point<int> dropPos ((int) clientMsg->data.l[2] >> 16,
  217887. (int) clientMsg->data.l[2] & 0xffff);
  217888. dropPos -= getScreenPosition();
  217889. if (lastDropPos != dropPos)
  217890. {
  217891. lastDropPos = dropPos;
  217892. dragAndDropTimestamp = clientMsg->data.l[3];
  217893. Atom targetAction = Atoms::XdndActionCopy;
  217894. for (int i = numElementsInArray (Atoms::allowedActions); --i >= 0;)
  217895. {
  217896. if ((Atom) clientMsg->data.l[4] == Atoms::allowedActions[i])
  217897. {
  217898. targetAction = Atoms::allowedActions[i];
  217899. break;
  217900. }
  217901. }
  217902. sendDragAndDropStatus (true, targetAction);
  217903. if (dragAndDropFiles.size() == 0)
  217904. updateDraggedFileList (clientMsg);
  217905. if (dragAndDropFiles.size() > 0)
  217906. handleFileDragMove (dragAndDropFiles, dropPos);
  217907. }
  217908. }
  217909. void handleDragAndDropDrop (const XClientMessageEvent* const clientMsg)
  217910. {
  217911. if (dragAndDropFiles.size() == 0)
  217912. updateDraggedFileList (clientMsg);
  217913. const StringArray files (dragAndDropFiles);
  217914. const Point<int> lastPos (lastDropPos);
  217915. sendDragAndDropFinish();
  217916. resetDragAndDrop();
  217917. if (files.size() > 0)
  217918. handleFileDragDrop (files, lastPos);
  217919. }
  217920. void handleDragAndDropEnter (const XClientMessageEvent* const clientMsg)
  217921. {
  217922. dragAndDropFiles.clear();
  217923. srcMimeTypeAtomList.clear();
  217924. dragAndDropCurrentMimeType = 0;
  217925. const unsigned long dndCurrentVersion = static_cast <unsigned long> (clientMsg->data.l[1] & 0xff000000) >> 24;
  217926. if (dndCurrentVersion < 3 || dndCurrentVersion > Atoms::DndVersion)
  217927. {
  217928. dragAndDropSourceWindow = 0;
  217929. return;
  217930. }
  217931. dragAndDropSourceWindow = clientMsg->data.l[0];
  217932. if ((clientMsg->data.l[1] & 1) != 0)
  217933. {
  217934. Atom actual;
  217935. int format;
  217936. unsigned long count = 0, remaining = 0;
  217937. unsigned char* data = 0;
  217938. ScopedXLock xlock;
  217939. XGetWindowProperty (display, dragAndDropSourceWindow, Atoms::XdndTypeList,
  217940. 0, 0x8000000L, False, XA_ATOM, &actual, &format,
  217941. &count, &remaining, &data);
  217942. if (data != 0)
  217943. {
  217944. if (actual == XA_ATOM && format == 32 && count != 0)
  217945. {
  217946. const unsigned long* const types = (const unsigned long*) data;
  217947. for (unsigned int i = 0; i < count; ++i)
  217948. if (types[i] != None)
  217949. srcMimeTypeAtomList.add (types[i]);
  217950. }
  217951. XFree (data);
  217952. }
  217953. }
  217954. if (srcMimeTypeAtomList.size() == 0)
  217955. {
  217956. for (int i = 2; i < 5; ++i)
  217957. if (clientMsg->data.l[i] != None)
  217958. srcMimeTypeAtomList.add (clientMsg->data.l[i]);
  217959. if (srcMimeTypeAtomList.size() == 0)
  217960. {
  217961. dragAndDropSourceWindow = 0;
  217962. return;
  217963. }
  217964. }
  217965. for (int i = 0; i < srcMimeTypeAtomList.size() && dragAndDropCurrentMimeType == 0; ++i)
  217966. for (int j = 0; j < numElementsInArray (Atoms::allowedMimeTypes); ++j)
  217967. if (srcMimeTypeAtomList[i] == Atoms::allowedMimeTypes[j])
  217968. dragAndDropCurrentMimeType = Atoms::allowedMimeTypes[j];
  217969. handleDragAndDropPosition (clientMsg);
  217970. }
  217971. void handleDragAndDropSelection (const XEvent* const evt)
  217972. {
  217973. dragAndDropFiles.clear();
  217974. if (evt->xselection.property != 0)
  217975. {
  217976. StringArray lines;
  217977. {
  217978. MemoryBlock dropData;
  217979. for (;;)
  217980. {
  217981. Atom actual;
  217982. uint8* data = 0;
  217983. unsigned long count = 0, remaining = 0;
  217984. int format = 0;
  217985. ScopedXLock xlock;
  217986. if (XGetWindowProperty (display, evt->xany.window, evt->xselection.property,
  217987. dropData.getSize() / 4, 65536, 1, AnyPropertyType, &actual,
  217988. &format, &count, &remaining, &data) == Success)
  217989. {
  217990. dropData.append (data, count * format / 8);
  217991. XFree (data);
  217992. if (remaining == 0)
  217993. break;
  217994. }
  217995. else
  217996. {
  217997. XFree (data);
  217998. break;
  217999. }
  218000. }
  218001. lines.addLines (dropData.toString());
  218002. }
  218003. for (int i = 0; i < lines.size(); ++i)
  218004. dragAndDropFiles.add (URL::removeEscapeChars (lines[i].fromFirstOccurrenceOf ("file://", false, true)));
  218005. dragAndDropFiles.trim();
  218006. dragAndDropFiles.removeEmptyStrings();
  218007. }
  218008. }
  218009. void updateDraggedFileList (const XClientMessageEvent* const clientMsg)
  218010. {
  218011. dragAndDropFiles.clear();
  218012. if (dragAndDropSourceWindow != None
  218013. && dragAndDropCurrentMimeType != 0)
  218014. {
  218015. dragAndDropTimestamp = clientMsg->data.l[2];
  218016. ScopedXLock xlock;
  218017. XConvertSelection (display,
  218018. Atoms::XdndSelection,
  218019. dragAndDropCurrentMimeType,
  218020. XInternAtom (display, "JXSelectionWindowProperty", 0),
  218021. windowH,
  218022. dragAndDropTimestamp);
  218023. }
  218024. }
  218025. StringArray dragAndDropFiles;
  218026. int dragAndDropTimestamp;
  218027. Point<int> lastDropPos;
  218028. Atom dragAndDropCurrentMimeType;
  218029. Window dragAndDropSourceWindow;
  218030. Array <Atom> srcMimeTypeAtomList;
  218031. static int pointerMap[5];
  218032. static Point<int> lastMousePos;
  218033. static void clearLastMousePos() throw()
  218034. {
  218035. lastMousePos = Point<int> (0x100000, 0x100000);
  218036. }
  218037. };
  218038. ModifierKeys LinuxComponentPeer::currentModifiers;
  218039. bool LinuxComponentPeer::isActiveApplication = false;
  218040. int LinuxComponentPeer::pointerMap[5];
  218041. Point<int> LinuxComponentPeer::lastMousePos;
  218042. bool Process::isForegroundProcess()
  218043. {
  218044. return LinuxComponentPeer::isActiveApplication;
  218045. }
  218046. void ModifierKeys::updateCurrentModifiers() throw()
  218047. {
  218048. currentModifiers = LinuxComponentPeer::currentModifiers;
  218049. }
  218050. const ModifierKeys ModifierKeys::getCurrentModifiersRealtime() throw()
  218051. {
  218052. Window root, child;
  218053. int x, y, winx, winy;
  218054. unsigned int mask;
  218055. int mouseMods = 0;
  218056. ScopedXLock xlock;
  218057. if (XQueryPointer (display, RootWindow (display, DefaultScreen (display)),
  218058. &root, &child, &x, &y, &winx, &winy, &mask) != False)
  218059. {
  218060. if ((mask & Button1Mask) != 0) mouseMods |= ModifierKeys::leftButtonModifier;
  218061. if ((mask & Button2Mask) != 0) mouseMods |= ModifierKeys::middleButtonModifier;
  218062. if ((mask & Button3Mask) != 0) mouseMods |= ModifierKeys::rightButtonModifier;
  218063. }
  218064. LinuxComponentPeer::currentModifiers = LinuxComponentPeer::currentModifiers.withoutMouseButtons().withFlags (mouseMods);
  218065. return LinuxComponentPeer::currentModifiers;
  218066. }
  218067. void juce_setKioskComponent (Component* kioskModeComponent, bool enableOrDisable, bool allowMenusAndBars)
  218068. {
  218069. if (enableOrDisable)
  218070. kioskModeComponent->setBounds (Desktop::getInstance().getMainMonitorArea (false));
  218071. }
  218072. ComponentPeer* Component::createNewPeer (int styleFlags, void* /*nativeWindowToAttachTo*/)
  218073. {
  218074. return new LinuxComponentPeer (this, styleFlags);
  218075. }
  218076. // (this callback is hooked up in the messaging code)
  218077. void juce_windowMessageReceive (XEvent* event)
  218078. {
  218079. if (event->xany.window != None)
  218080. {
  218081. LinuxComponentPeer* const peer = LinuxComponentPeer::getPeerFor (event->xany.window);
  218082. if (ComponentPeer::isValidPeer (peer))
  218083. peer->handleWindowMessage (event);
  218084. }
  218085. else
  218086. {
  218087. switch (event->xany.type)
  218088. {
  218089. case KeymapNotify:
  218090. {
  218091. const XKeymapEvent* const keymapEvent = (const XKeymapEvent*) &event->xkeymap;
  218092. memcpy (Keys::keyStates, keymapEvent->key_vector, 32);
  218093. break;
  218094. }
  218095. default:
  218096. break;
  218097. }
  218098. }
  218099. }
  218100. void juce_updateMultiMonitorInfo (Array <Rectangle<int> >& monitorCoords, const bool /*clipToWorkArea*/)
  218101. {
  218102. if (display == 0)
  218103. return;
  218104. #if JUCE_USE_XINERAMA
  218105. int major_opcode, first_event, first_error;
  218106. ScopedXLock xlock;
  218107. if (XQueryExtension (display, "XINERAMA", &major_opcode, &first_event, &first_error))
  218108. {
  218109. typedef Bool (*tXineramaIsActive) (Display*);
  218110. typedef XineramaScreenInfo* (*tXineramaQueryScreens) (Display*, int*);
  218111. static tXineramaIsActive xXineramaIsActive = 0;
  218112. static tXineramaQueryScreens xXineramaQueryScreens = 0;
  218113. if (xXineramaIsActive == 0 || xXineramaQueryScreens == 0)
  218114. {
  218115. void* h = dlopen ("libXinerama.so", RTLD_GLOBAL | RTLD_NOW);
  218116. if (h != 0)
  218117. {
  218118. xXineramaIsActive = (tXineramaIsActive) dlsym (h, "XineramaIsActive");
  218119. xXineramaQueryScreens = (tXineramaQueryScreens) dlsym (h, "XineramaQueryScreens");
  218120. }
  218121. }
  218122. if (xXineramaIsActive != 0
  218123. && xXineramaQueryScreens != 0
  218124. && xXineramaIsActive (display))
  218125. {
  218126. int numMonitors = 0;
  218127. XineramaScreenInfo* const screens = xXineramaQueryScreens (display, &numMonitors);
  218128. if (screens != 0)
  218129. {
  218130. for (int i = numMonitors; --i >= 0;)
  218131. {
  218132. int index = screens[i].screen_number;
  218133. if (index >= 0)
  218134. {
  218135. while (monitorCoords.size() < index)
  218136. monitorCoords.add (Rectangle<int>());
  218137. monitorCoords.set (index, Rectangle<int> (screens[i].x_org,
  218138. screens[i].y_org,
  218139. screens[i].width,
  218140. screens[i].height));
  218141. }
  218142. }
  218143. XFree (screens);
  218144. }
  218145. }
  218146. }
  218147. if (monitorCoords.size() == 0)
  218148. #endif
  218149. {
  218150. Atom hints = XInternAtom (display, "_NET_WORKAREA", True);
  218151. if (hints != None)
  218152. {
  218153. const int numMonitors = ScreenCount (display);
  218154. for (int i = 0; i < numMonitors; ++i)
  218155. {
  218156. Window root = RootWindow (display, i);
  218157. unsigned long nitems, bytesLeft;
  218158. Atom actualType;
  218159. int actualFormat;
  218160. unsigned char* data = 0;
  218161. if (XGetWindowProperty (display, root, hints, 0, 4, False,
  218162. XA_CARDINAL, &actualType, &actualFormat, &nitems, &bytesLeft,
  218163. &data) == Success)
  218164. {
  218165. const long* const position = (const long*) data;
  218166. if (actualType == XA_CARDINAL && actualFormat == 32 && nitems == 4)
  218167. monitorCoords.add (Rectangle<int> (position[0], position[1],
  218168. position[2], position[3]));
  218169. XFree (data);
  218170. }
  218171. }
  218172. }
  218173. if (monitorCoords.size() == 0)
  218174. {
  218175. monitorCoords.add (Rectangle<int> (0, 0,
  218176. DisplayWidth (display, DefaultScreen (display)),
  218177. DisplayHeight (display, DefaultScreen (display))));
  218178. }
  218179. }
  218180. }
  218181. void Desktop::createMouseInputSources()
  218182. {
  218183. mouseSources.add (new MouseInputSource (0, true));
  218184. }
  218185. bool Desktop::canUseSemiTransparentWindows() throw()
  218186. {
  218187. int matchedDepth = 0;
  218188. const int desiredDepth = 32;
  218189. return Visuals::findVisualFormat (desiredDepth, matchedDepth) != 0
  218190. && (matchedDepth == desiredDepth);
  218191. }
  218192. const Point<int> Desktop::getMousePosition()
  218193. {
  218194. Window root, child;
  218195. int x, y, winx, winy;
  218196. unsigned int mask;
  218197. ScopedXLock xlock;
  218198. if (XQueryPointer (display,
  218199. RootWindow (display, DefaultScreen (display)),
  218200. &root, &child,
  218201. &x, &y, &winx, &winy, &mask) == False)
  218202. {
  218203. // Pointer not on the default screen
  218204. x = y = -1;
  218205. }
  218206. return Point<int> (x, y);
  218207. }
  218208. void Desktop::setMousePosition (const Point<int>& newPosition)
  218209. {
  218210. ScopedXLock xlock;
  218211. Window root = RootWindow (display, DefaultScreen (display));
  218212. XWarpPointer (display, None, root, 0, 0, 0, 0, newPosition.getX(), newPosition.getY());
  218213. }
  218214. static bool screenSaverAllowed = true;
  218215. void Desktop::setScreenSaverEnabled (const bool isEnabled) throw()
  218216. {
  218217. if (screenSaverAllowed != isEnabled)
  218218. {
  218219. screenSaverAllowed = isEnabled;
  218220. typedef void (*tXScreenSaverSuspend) (Display*, Bool);
  218221. static tXScreenSaverSuspend xScreenSaverSuspend = 0;
  218222. if (xScreenSaverSuspend == 0)
  218223. {
  218224. void* h = dlopen ("libXss.so", RTLD_GLOBAL | RTLD_NOW);
  218225. if (h != 0)
  218226. xScreenSaverSuspend = (tXScreenSaverSuspend) dlsym (h, "XScreenSaverSuspend");
  218227. }
  218228. ScopedXLock xlock;
  218229. if (xScreenSaverSuspend != 0)
  218230. xScreenSaverSuspend (display, ! isEnabled);
  218231. }
  218232. }
  218233. bool Desktop::isScreenSaverEnabled() throw()
  218234. {
  218235. return screenSaverAllowed;
  218236. }
  218237. void* MouseCursor::createMouseCursorFromImage (const Image& image, int hotspotX, int hotspotY)
  218238. {
  218239. ScopedXLock xlock;
  218240. const unsigned int imageW = image.getWidth();
  218241. const unsigned int imageH = image.getHeight();
  218242. #if JUCE_USE_XCURSOR
  218243. {
  218244. typedef XcursorBool (*tXcursorSupportsARGB) (Display*);
  218245. typedef XcursorImage* (*tXcursorImageCreate) (int, int);
  218246. typedef void (*tXcursorImageDestroy) (XcursorImage*);
  218247. typedef Cursor (*tXcursorImageLoadCursor) (Display*, const XcursorImage*);
  218248. static tXcursorSupportsARGB xXcursorSupportsARGB = 0;
  218249. static tXcursorImageCreate xXcursorImageCreate = 0;
  218250. static tXcursorImageDestroy xXcursorImageDestroy = 0;
  218251. static tXcursorImageLoadCursor xXcursorImageLoadCursor = 0;
  218252. static bool hasBeenLoaded = false;
  218253. if (! hasBeenLoaded)
  218254. {
  218255. hasBeenLoaded = true;
  218256. void* h = dlopen ("libXcursor.so", RTLD_GLOBAL | RTLD_NOW);
  218257. if (h != 0)
  218258. {
  218259. xXcursorSupportsARGB = (tXcursorSupportsARGB) dlsym (h, "XcursorSupportsARGB");
  218260. xXcursorImageCreate = (tXcursorImageCreate) dlsym (h, "XcursorImageCreate");
  218261. xXcursorImageLoadCursor = (tXcursorImageLoadCursor) dlsym (h, "XcursorImageLoadCursor");
  218262. xXcursorImageDestroy = (tXcursorImageDestroy) dlsym (h, "XcursorImageDestroy");
  218263. if (xXcursorSupportsARGB == 0 || xXcursorImageCreate == 0
  218264. || xXcursorImageLoadCursor == 0 || xXcursorImageDestroy == 0
  218265. || ! xXcursorSupportsARGB (display))
  218266. xXcursorSupportsARGB = 0;
  218267. }
  218268. }
  218269. if (xXcursorSupportsARGB != 0)
  218270. {
  218271. XcursorImage* xcImage = xXcursorImageCreate (imageW, imageH);
  218272. if (xcImage != 0)
  218273. {
  218274. xcImage->xhot = hotspotX;
  218275. xcImage->yhot = hotspotY;
  218276. XcursorPixel* dest = xcImage->pixels;
  218277. for (int y = 0; y < (int) imageH; ++y)
  218278. for (int x = 0; x < (int) imageW; ++x)
  218279. *dest++ = image.getPixelAt (x, y).getARGB();
  218280. void* result = (void*) xXcursorImageLoadCursor (display, xcImage);
  218281. xXcursorImageDestroy (xcImage);
  218282. if (result != 0)
  218283. return result;
  218284. }
  218285. }
  218286. }
  218287. #endif
  218288. Window root = RootWindow (display, DefaultScreen (display));
  218289. unsigned int cursorW, cursorH;
  218290. if (! XQueryBestCursor (display, root, imageW, imageH, &cursorW, &cursorH))
  218291. return 0;
  218292. Image im (Image::ARGB, cursorW, cursorH, true);
  218293. {
  218294. Graphics g (im);
  218295. if (imageW > cursorW || imageH > cursorH)
  218296. {
  218297. hotspotX = (hotspotX * cursorW) / imageW;
  218298. hotspotY = (hotspotY * cursorH) / imageH;
  218299. g.drawImageWithin (&image, 0, 0, imageW, imageH,
  218300. RectanglePlacement::xLeft | RectanglePlacement::yTop | RectanglePlacement::onlyReduceInSize,
  218301. false);
  218302. }
  218303. else
  218304. {
  218305. g.drawImageAt (&image, 0, 0);
  218306. }
  218307. }
  218308. const int stride = (cursorW + 7) >> 3;
  218309. HeapBlock <char> maskPlane, sourcePlane;
  218310. maskPlane.calloc (stride * cursorH);
  218311. sourcePlane.calloc (stride * cursorH);
  218312. const bool msbfirst = (BitmapBitOrder (display) == MSBFirst);
  218313. for (int y = cursorH; --y >= 0;)
  218314. {
  218315. for (int x = cursorW; --x >= 0;)
  218316. {
  218317. const char mask = (char) (1 << (msbfirst ? (7 - (x & 7)) : (x & 7)));
  218318. const int offset = y * stride + (x >> 3);
  218319. const Colour c (im.getPixelAt (x, y));
  218320. if (c.getAlpha() >= 128)
  218321. maskPlane[offset] |= mask;
  218322. if (c.getBrightness() >= 0.5f)
  218323. sourcePlane[offset] |= mask;
  218324. }
  218325. }
  218326. Pixmap sourcePixmap = XCreatePixmapFromBitmapData (display, root, sourcePlane.getData(), cursorW, cursorH, 0xffff, 0, 1);
  218327. Pixmap maskPixmap = XCreatePixmapFromBitmapData (display, root, maskPlane.getData(), cursorW, cursorH, 0xffff, 0, 1);
  218328. XColor white, black;
  218329. black.red = black.green = black.blue = 0;
  218330. white.red = white.green = white.blue = 0xffff;
  218331. void* result = (void*) XCreatePixmapCursor (display, sourcePixmap, maskPixmap, &white, &black, hotspotX, hotspotY);
  218332. XFreePixmap (display, sourcePixmap);
  218333. XFreePixmap (display, maskPixmap);
  218334. return result;
  218335. }
  218336. void MouseCursor::deleteMouseCursor (void* const cursorHandle, const bool)
  218337. {
  218338. ScopedXLock xlock;
  218339. if (cursorHandle != 0)
  218340. XFreeCursor (display, (Cursor) cursorHandle);
  218341. }
  218342. void* MouseCursor::createStandardMouseCursor (MouseCursor::StandardCursorType type)
  218343. {
  218344. unsigned int shape;
  218345. switch (type)
  218346. {
  218347. case NormalCursor: return None; // Use parent cursor
  218348. case NoCursor: return createMouseCursorFromImage (Image (Image::ARGB, 16, 16, true), 0, 0);
  218349. case WaitCursor: shape = XC_watch; break;
  218350. case IBeamCursor: shape = XC_xterm; break;
  218351. case PointingHandCursor: shape = XC_hand2; break;
  218352. case LeftRightResizeCursor: shape = XC_sb_h_double_arrow; break;
  218353. case UpDownResizeCursor: shape = XC_sb_v_double_arrow; break;
  218354. case UpDownLeftRightResizeCursor: shape = XC_fleur; break;
  218355. case TopEdgeResizeCursor: shape = XC_top_side; break;
  218356. case BottomEdgeResizeCursor: shape = XC_bottom_side; break;
  218357. case LeftEdgeResizeCursor: shape = XC_left_side; break;
  218358. case RightEdgeResizeCursor: shape = XC_right_side; break;
  218359. case TopLeftCornerResizeCursor: shape = XC_top_left_corner; break;
  218360. case TopRightCornerResizeCursor: shape = XC_top_right_corner; break;
  218361. case BottomLeftCornerResizeCursor: shape = XC_bottom_left_corner; break;
  218362. case BottomRightCornerResizeCursor: shape = XC_bottom_right_corner; break;
  218363. case CrosshairCursor: shape = XC_crosshair; break;
  218364. case DraggingHandCursor:
  218365. {
  218366. static unsigned char dragHandData[] = { 71,73,70,56,57,97,16,0,16,0,145,2,0,0,0,0,255,255,255,0,
  218367. 0,0,0,0,0,33,249,4,1,0,0,2,0,44,0,0,0,0,16,0, 16,0,0,2,52,148,47,0,200,185,16,130,90,12,74,139,107,84,123,39,
  218368. 132,117,151,116,132,146,248,60,209,138,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 };
  218369. const int dragHandDataSize = 99;
  218370. const ScopedPointer <Image> im (ImageFileFormat::loadFrom (dragHandData, dragHandDataSize));
  218371. return createMouseCursorFromImage (*im, 8, 7);
  218372. }
  218373. case CopyingCursor:
  218374. {
  218375. static unsigned char copyCursorData[] = { 71,73,70,56,57,97,21,0,21,0,145,0,0,0,0,0,255,255,255,0,
  218376. 128,128,255,255,255,33,249,4,1,0,0,3,0,44,0,0,0,0,21,0, 21,0,0,2,72,4,134,169,171,16,199,98,11,79,90,71,161,93,56,111,
  218377. 78,133,218,215,137,31,82,154,100,200,86,91,202,142,12,108,212,87,235,174, 15,54,214,126,237,226,37,96,59,141,16,37,18,201,142,157,230,204,51,112,
  218378. 252,114,147,74,83,5,50,68,147,208,217,16,71,149,252,124,5,0,59,0,0 };
  218379. const int copyCursorSize = 119;
  218380. const ScopedPointer <Image> im (ImageFileFormat::loadFrom (copyCursorData, copyCursorSize));
  218381. return createMouseCursorFromImage (*im, 1, 3);
  218382. }
  218383. default:
  218384. jassertfalse;
  218385. return None;
  218386. }
  218387. ScopedXLock xlock;
  218388. return (void*) XCreateFontCursor (display, shape);
  218389. }
  218390. void MouseCursor::showInWindow (ComponentPeer* peer) const
  218391. {
  218392. LinuxComponentPeer* const lp = dynamic_cast <LinuxComponentPeer*> (peer);
  218393. if (lp != 0)
  218394. lp->showMouseCursor ((Cursor) getHandle());
  218395. }
  218396. void MouseCursor::showInAllWindows() const
  218397. {
  218398. for (int i = ComponentPeer::getNumPeers(); --i >= 0;)
  218399. showInWindow (ComponentPeer::getPeer (i));
  218400. }
  218401. Image* juce_createIconForFile (const File& file)
  218402. {
  218403. return 0;
  218404. }
  218405. Image* Image::createNativeImage (const PixelFormat format, const int imageWidth, const int imageHeight, const bool clearImage)
  218406. {
  218407. return new Image (format, imageWidth, imageHeight, clearImage);
  218408. }
  218409. #if JUCE_OPENGL
  218410. class WindowedGLContext : public OpenGLContext
  218411. {
  218412. public:
  218413. WindowedGLContext (Component* const component,
  218414. const OpenGLPixelFormat& pixelFormat_,
  218415. GLXContext sharedContext)
  218416. : renderContext (0),
  218417. embeddedWindow (0),
  218418. pixelFormat (pixelFormat_)
  218419. {
  218420. jassert (component != 0);
  218421. LinuxComponentPeer* const peer = dynamic_cast <LinuxComponentPeer*> (component->getTopLevelComponent()->getPeer());
  218422. if (peer == 0)
  218423. return;
  218424. ScopedXLock xlock;
  218425. XSync (display, False);
  218426. GLint attribs [64];
  218427. int n = 0;
  218428. attribs[n++] = GLX_RGBA;
  218429. attribs[n++] = GLX_DOUBLEBUFFER;
  218430. attribs[n++] = GLX_RED_SIZE;
  218431. attribs[n++] = pixelFormat.redBits;
  218432. attribs[n++] = GLX_GREEN_SIZE;
  218433. attribs[n++] = pixelFormat.greenBits;
  218434. attribs[n++] = GLX_BLUE_SIZE;
  218435. attribs[n++] = pixelFormat.blueBits;
  218436. attribs[n++] = GLX_ALPHA_SIZE;
  218437. attribs[n++] = pixelFormat.alphaBits;
  218438. attribs[n++] = GLX_DEPTH_SIZE;
  218439. attribs[n++] = pixelFormat.depthBufferBits;
  218440. attribs[n++] = GLX_STENCIL_SIZE;
  218441. attribs[n++] = pixelFormat.stencilBufferBits;
  218442. attribs[n++] = GLX_ACCUM_RED_SIZE;
  218443. attribs[n++] = pixelFormat.accumulationBufferRedBits;
  218444. attribs[n++] = GLX_ACCUM_GREEN_SIZE;
  218445. attribs[n++] = pixelFormat.accumulationBufferGreenBits;
  218446. attribs[n++] = GLX_ACCUM_BLUE_SIZE;
  218447. attribs[n++] = pixelFormat.accumulationBufferBlueBits;
  218448. attribs[n++] = GLX_ACCUM_ALPHA_SIZE;
  218449. attribs[n++] = pixelFormat.accumulationBufferAlphaBits;
  218450. // xxx not sure how to do fullSceneAntiAliasingNumSamples on linux..
  218451. attribs[n++] = None;
  218452. XVisualInfo* const bestVisual = glXChooseVisual (display, DefaultScreen (display), attribs);
  218453. if (bestVisual == 0)
  218454. return;
  218455. renderContext = glXCreateContext (display, bestVisual, sharedContext, GL_TRUE);
  218456. Window windowH = (Window) peer->getNativeHandle();
  218457. Colormap colourMap = XCreateColormap (display, windowH, bestVisual->visual, AllocNone);
  218458. XSetWindowAttributes swa;
  218459. swa.colormap = colourMap;
  218460. swa.border_pixel = 0;
  218461. swa.event_mask = ExposureMask | StructureNotifyMask;
  218462. embeddedWindow = XCreateWindow (display, windowH,
  218463. 0, 0, 1, 1, 0,
  218464. bestVisual->depth,
  218465. InputOutput,
  218466. bestVisual->visual,
  218467. CWBorderPixel | CWColormap | CWEventMask,
  218468. &swa);
  218469. XSaveContext (display, (XID) embeddedWindow, windowHandleXContext, (XPointer) peer);
  218470. XMapWindow (display, embeddedWindow);
  218471. XFreeColormap (display, colourMap);
  218472. XFree (bestVisual);
  218473. XSync (display, False);
  218474. }
  218475. ~WindowedGLContext()
  218476. {
  218477. makeInactive();
  218478. ScopedXLock xlock;
  218479. glXDestroyContext (display, renderContext);
  218480. XUnmapWindow (display, embeddedWindow);
  218481. XDestroyWindow (display, embeddedWindow);
  218482. }
  218483. bool makeActive() const throw()
  218484. {
  218485. jassert (renderContext != 0);
  218486. ScopedXLock xlock;
  218487. return glXMakeCurrent (display, embeddedWindow, renderContext)
  218488. && XSync (display, False);
  218489. }
  218490. bool makeInactive() const throw()
  218491. {
  218492. ScopedXLock xlock;
  218493. return (! isActive()) || glXMakeCurrent (display, None, 0);
  218494. }
  218495. bool isActive() const throw()
  218496. {
  218497. ScopedXLock xlock;
  218498. return glXGetCurrentContext() == renderContext;
  218499. }
  218500. const OpenGLPixelFormat getPixelFormat() const
  218501. {
  218502. return pixelFormat;
  218503. }
  218504. void* getRawContext() const throw()
  218505. {
  218506. return renderContext;
  218507. }
  218508. void updateWindowPosition (int x, int y, int w, int h, int)
  218509. {
  218510. ScopedXLock xlock;
  218511. XMoveResizeWindow (display, embeddedWindow,
  218512. x, y, jmax (1, w), jmax (1, h));
  218513. }
  218514. void swapBuffers()
  218515. {
  218516. ScopedXLock xlock;
  218517. glXSwapBuffers (display, embeddedWindow);
  218518. }
  218519. bool setSwapInterval (const int numFramesPerSwap)
  218520. {
  218521. // xxx needs doing..
  218522. return false;
  218523. }
  218524. int getSwapInterval() const
  218525. {
  218526. // xxx needs doing..
  218527. return 0;
  218528. }
  218529. void repaint()
  218530. {
  218531. }
  218532. juce_UseDebuggingNewOperator
  218533. GLXContext renderContext;
  218534. private:
  218535. Window embeddedWindow;
  218536. OpenGLPixelFormat pixelFormat;
  218537. WindowedGLContext (const WindowedGLContext&);
  218538. WindowedGLContext& operator= (const WindowedGLContext&);
  218539. };
  218540. OpenGLContext* OpenGLComponent::createContext()
  218541. {
  218542. ScopedPointer<WindowedGLContext> c (new WindowedGLContext (this, preferredPixelFormat,
  218543. contextToShareListsWith != 0 ? (GLXContext) contextToShareListsWith->getRawContext() : 0));
  218544. return (c->renderContext != 0) ? c.release() : 0;
  218545. }
  218546. void juce_glViewport (const int w, const int h)
  218547. {
  218548. glViewport (0, 0, w, h);
  218549. }
  218550. void OpenGLPixelFormat::getAvailablePixelFormats (Component* component,
  218551. OwnedArray <OpenGLPixelFormat>& results)
  218552. {
  218553. results.add (new OpenGLPixelFormat()); // xxx
  218554. }
  218555. #endif
  218556. bool DragAndDropContainer::performExternalDragDropOfFiles (const StringArray& files, const bool canMoveFiles)
  218557. {
  218558. jassertfalse // not implemented!
  218559. return false;
  218560. }
  218561. bool DragAndDropContainer::performExternalDragDropOfText (const String& text)
  218562. {
  218563. jassertfalse // not implemented!
  218564. return false;
  218565. }
  218566. void SystemTrayIconComponent::setIconImage (const Image& newImage)
  218567. {
  218568. if (! isOnDesktop ())
  218569. addToDesktop (0);
  218570. LinuxComponentPeer* const wp = dynamic_cast <LinuxComponentPeer*> (getPeer());
  218571. if (wp != 0)
  218572. {
  218573. wp->setTaskBarIcon (newImage);
  218574. setVisible (true);
  218575. toFront (false);
  218576. repaint();
  218577. }
  218578. }
  218579. void SystemTrayIconComponent::paint (Graphics& g)
  218580. {
  218581. LinuxComponentPeer* const wp = dynamic_cast <LinuxComponentPeer*> (getPeer());
  218582. if (wp != 0)
  218583. {
  218584. const Image* const image = wp->getTaskbarIcon();
  218585. if (image != 0)
  218586. {
  218587. g.drawImageWithin (image, 0, 0, getWidth(), getHeight(),
  218588. RectanglePlacement::xLeft | RectanglePlacement::yTop | RectanglePlacement::onlyReduceInSize,
  218589. false);
  218590. }
  218591. }
  218592. }
  218593. void SystemTrayIconComponent::setIconTooltip (const String& tooltip)
  218594. {
  218595. // xxx not yet implemented!
  218596. }
  218597. void PlatformUtilities::beep()
  218598. {
  218599. std::cout << "\a" << std::flush;
  218600. }
  218601. bool AlertWindow::showNativeDialogBox (const String& title,
  218602. const String& bodyText,
  218603. bool isOkCancel)
  218604. {
  218605. // use a non-native one for the time being..
  218606. if (isOkCancel)
  218607. return AlertWindow::showOkCancelBox (AlertWindow::NoIcon, title, bodyText);
  218608. else
  218609. AlertWindow::showMessageBox (AlertWindow::NoIcon, title, bodyText);
  218610. return true;
  218611. }
  218612. const int KeyPress::spaceKey = XK_space & 0xff;
  218613. const int KeyPress::returnKey = XK_Return & 0xff;
  218614. const int KeyPress::escapeKey = XK_Escape & 0xff;
  218615. const int KeyPress::backspaceKey = XK_BackSpace & 0xff;
  218616. const int KeyPress::leftKey = (XK_Left & 0xff) | Keys::extendedKeyModifier;
  218617. const int KeyPress::rightKey = (XK_Right & 0xff) | Keys::extendedKeyModifier;
  218618. const int KeyPress::upKey = (XK_Up & 0xff) | Keys::extendedKeyModifier;
  218619. const int KeyPress::downKey = (XK_Down & 0xff) | Keys::extendedKeyModifier;
  218620. const int KeyPress::pageUpKey = (XK_Page_Up & 0xff) | Keys::extendedKeyModifier;
  218621. const int KeyPress::pageDownKey = (XK_Page_Down & 0xff) | Keys::extendedKeyModifier;
  218622. const int KeyPress::endKey = (XK_End & 0xff) | Keys::extendedKeyModifier;
  218623. const int KeyPress::homeKey = (XK_Home & 0xff) | Keys::extendedKeyModifier;
  218624. const int KeyPress::insertKey = (XK_Insert & 0xff) | Keys::extendedKeyModifier;
  218625. const int KeyPress::deleteKey = (XK_Delete & 0xff) | Keys::extendedKeyModifier;
  218626. const int KeyPress::tabKey = XK_Tab & 0xff;
  218627. const int KeyPress::F1Key = (XK_F1 & 0xff) | Keys::extendedKeyModifier;
  218628. const int KeyPress::F2Key = (XK_F2 & 0xff) | Keys::extendedKeyModifier;
  218629. const int KeyPress::F3Key = (XK_F3 & 0xff) | Keys::extendedKeyModifier;
  218630. const int KeyPress::F4Key = (XK_F4 & 0xff) | Keys::extendedKeyModifier;
  218631. const int KeyPress::F5Key = (XK_F5 & 0xff) | Keys::extendedKeyModifier;
  218632. const int KeyPress::F6Key = (XK_F6 & 0xff) | Keys::extendedKeyModifier;
  218633. const int KeyPress::F7Key = (XK_F7 & 0xff) | Keys::extendedKeyModifier;
  218634. const int KeyPress::F8Key = (XK_F8 & 0xff) | Keys::extendedKeyModifier;
  218635. const int KeyPress::F9Key = (XK_F9 & 0xff) | Keys::extendedKeyModifier;
  218636. const int KeyPress::F10Key = (XK_F10 & 0xff) | Keys::extendedKeyModifier;
  218637. const int KeyPress::F11Key = (XK_F11 & 0xff) | Keys::extendedKeyModifier;
  218638. const int KeyPress::F12Key = (XK_F12 & 0xff) | Keys::extendedKeyModifier;
  218639. const int KeyPress::F13Key = (XK_F13 & 0xff) | Keys::extendedKeyModifier;
  218640. const int KeyPress::F14Key = (XK_F14 & 0xff) | Keys::extendedKeyModifier;
  218641. const int KeyPress::F15Key = (XK_F15 & 0xff) | Keys::extendedKeyModifier;
  218642. const int KeyPress::F16Key = (XK_F16 & 0xff) | Keys::extendedKeyModifier;
  218643. const int KeyPress::numberPad0 = (XK_KP_0 & 0xff) | Keys::extendedKeyModifier;
  218644. const int KeyPress::numberPad1 = (XK_KP_1 & 0xff) | Keys::extendedKeyModifier;
  218645. const int KeyPress::numberPad2 = (XK_KP_2 & 0xff) | Keys::extendedKeyModifier;
  218646. const int KeyPress::numberPad3 = (XK_KP_3 & 0xff) | Keys::extendedKeyModifier;
  218647. const int KeyPress::numberPad4 = (XK_KP_4 & 0xff) | Keys::extendedKeyModifier;
  218648. const int KeyPress::numberPad5 = (XK_KP_5 & 0xff) | Keys::extendedKeyModifier;
  218649. const int KeyPress::numberPad6 = (XK_KP_6 & 0xff) | Keys::extendedKeyModifier;
  218650. const int KeyPress::numberPad7 = (XK_KP_7 & 0xff)| Keys::extendedKeyModifier;
  218651. const int KeyPress::numberPad8 = (XK_KP_8 & 0xff)| Keys::extendedKeyModifier;
  218652. const int KeyPress::numberPad9 = (XK_KP_9 & 0xff)| Keys::extendedKeyModifier;
  218653. const int KeyPress::numberPadAdd = (XK_KP_Add & 0xff)| Keys::extendedKeyModifier;
  218654. const int KeyPress::numberPadSubtract = (XK_KP_Subtract & 0xff)| Keys::extendedKeyModifier;
  218655. const int KeyPress::numberPadMultiply = (XK_KP_Multiply & 0xff)| Keys::extendedKeyModifier;
  218656. const int KeyPress::numberPadDivide = (XK_KP_Divide & 0xff)| Keys::extendedKeyModifier;
  218657. const int KeyPress::numberPadSeparator = (XK_KP_Separator & 0xff)| Keys::extendedKeyModifier;
  218658. const int KeyPress::numberPadDecimalPoint = (XK_KP_Decimal & 0xff)| Keys::extendedKeyModifier;
  218659. const int KeyPress::numberPadEquals = (XK_KP_Equal & 0xff)| Keys::extendedKeyModifier;
  218660. const int KeyPress::numberPadDelete = (XK_KP_Delete & 0xff)| Keys::extendedKeyModifier;
  218661. const int KeyPress::playKey = (0xffeeff00) | Keys::extendedKeyModifier;
  218662. const int KeyPress::stopKey = (0xffeeff01) | Keys::extendedKeyModifier;
  218663. const int KeyPress::fastForwardKey = (0xffeeff02) | Keys::extendedKeyModifier;
  218664. const int KeyPress::rewindKey = (0xffeeff03) | Keys::extendedKeyModifier;
  218665. #endif
  218666. /*** End of inlined file: juce_linux_Windowing.cpp ***/
  218667. /*** Start of inlined file: juce_linux_Audio.cpp ***/
  218668. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  218669. // compiled on its own).
  218670. #if JUCE_INCLUDED_FILE && JUCE_ALSA
  218671. static const int maxNumChans = 64;
  218672. static void getDeviceSampleRates (snd_pcm_t* handle, Array <int>& rates)
  218673. {
  218674. const int ratesToTry[] = { 22050, 32000, 44100, 48000, 88200, 96000, 176400, 192000, 0 };
  218675. snd_pcm_hw_params_t* hwParams;
  218676. snd_pcm_hw_params_alloca (&hwParams);
  218677. for (int i = 0; ratesToTry[i] != 0; ++i)
  218678. {
  218679. if (snd_pcm_hw_params_any (handle, hwParams) >= 0
  218680. && snd_pcm_hw_params_test_rate (handle, hwParams, ratesToTry[i], 0) == 0)
  218681. {
  218682. rates.addIfNotAlreadyThere (ratesToTry[i]);
  218683. }
  218684. }
  218685. }
  218686. static void getDeviceNumChannels (snd_pcm_t* handle, unsigned int* minChans, unsigned int* maxChans)
  218687. {
  218688. snd_pcm_hw_params_t *params;
  218689. snd_pcm_hw_params_alloca (&params);
  218690. if (snd_pcm_hw_params_any (handle, params) >= 0)
  218691. {
  218692. snd_pcm_hw_params_get_channels_min (params, minChans);
  218693. snd_pcm_hw_params_get_channels_max (params, maxChans);
  218694. }
  218695. }
  218696. static void getDeviceProperties (const String& deviceID,
  218697. unsigned int& minChansOut,
  218698. unsigned int& maxChansOut,
  218699. unsigned int& minChansIn,
  218700. unsigned int& maxChansIn,
  218701. Array <int>& rates)
  218702. {
  218703. if (deviceID.isEmpty())
  218704. return;
  218705. snd_ctl_t* handle;
  218706. if (snd_ctl_open (&handle, deviceID.upToLastOccurrenceOf (",", false, false).toUTF8(), SND_CTL_NONBLOCK) >= 0)
  218707. {
  218708. snd_pcm_info_t* info;
  218709. snd_pcm_info_alloca (&info);
  218710. snd_pcm_info_set_stream (info, SND_PCM_STREAM_PLAYBACK);
  218711. snd_pcm_info_set_device (info, deviceID.fromLastOccurrenceOf (",", false, false).getIntValue());
  218712. snd_pcm_info_set_subdevice (info, 0);
  218713. if (snd_ctl_pcm_info (handle, info) >= 0)
  218714. {
  218715. snd_pcm_t* pcmHandle;
  218716. if (snd_pcm_open (&pcmHandle, deviceID.toUTF8(), SND_PCM_STREAM_PLAYBACK, SND_PCM_ASYNC | SND_PCM_NONBLOCK ) >= 0)
  218717. {
  218718. getDeviceNumChannels (pcmHandle, &minChansOut, &maxChansOut);
  218719. getDeviceSampleRates (pcmHandle, rates);
  218720. snd_pcm_close (pcmHandle);
  218721. }
  218722. }
  218723. snd_pcm_info_set_stream (info, SND_PCM_STREAM_CAPTURE);
  218724. if (snd_ctl_pcm_info (handle, info) >= 0)
  218725. {
  218726. snd_pcm_t* pcmHandle;
  218727. if (snd_pcm_open (&pcmHandle, deviceID.toUTF8(), SND_PCM_STREAM_CAPTURE, SND_PCM_ASYNC | SND_PCM_NONBLOCK ) >= 0)
  218728. {
  218729. getDeviceNumChannels (pcmHandle, &minChansIn, &maxChansIn);
  218730. if (rates.size() == 0)
  218731. getDeviceSampleRates (pcmHandle, rates);
  218732. snd_pcm_close (pcmHandle);
  218733. }
  218734. }
  218735. snd_ctl_close (handle);
  218736. }
  218737. }
  218738. class ALSADevice
  218739. {
  218740. public:
  218741. ALSADevice (const String& deviceID,
  218742. const bool forInput)
  218743. : handle (0),
  218744. bitDepth (16),
  218745. numChannelsRunning (0),
  218746. isInput (forInput),
  218747. sampleFormat (AudioDataConverters::int16LE)
  218748. {
  218749. failed (snd_pcm_open (&handle, deviceID.toUTF8(),
  218750. forInput ? SND_PCM_STREAM_CAPTURE : SND_PCM_STREAM_PLAYBACK,
  218751. SND_PCM_ASYNC));
  218752. }
  218753. ~ALSADevice()
  218754. {
  218755. if (handle != 0)
  218756. snd_pcm_close (handle);
  218757. }
  218758. bool setParameters (unsigned int sampleRate, int numChannels, int bufferSize)
  218759. {
  218760. if (handle == 0)
  218761. return false;
  218762. snd_pcm_hw_params_t* hwParams;
  218763. snd_pcm_hw_params_alloca (&hwParams);
  218764. if (failed (snd_pcm_hw_params_any (handle, hwParams)))
  218765. return false;
  218766. if (snd_pcm_hw_params_set_access (handle, hwParams, SND_PCM_ACCESS_RW_NONINTERLEAVED) >= 0)
  218767. isInterleaved = false;
  218768. else if (snd_pcm_hw_params_set_access (handle, hwParams, SND_PCM_ACCESS_RW_INTERLEAVED) >= 0)
  218769. isInterleaved = true;
  218770. else
  218771. {
  218772. jassertfalse
  218773. return false;
  218774. }
  218775. const int formatsToTry[] = { SND_PCM_FORMAT_FLOAT_LE, 32, AudioDataConverters::float32LE,
  218776. SND_PCM_FORMAT_FLOAT_BE, 32, AudioDataConverters::float32BE,
  218777. SND_PCM_FORMAT_S32_LE, 32, AudioDataConverters::int32LE,
  218778. SND_PCM_FORMAT_S32_BE, 32, AudioDataConverters::int32BE,
  218779. SND_PCM_FORMAT_S24_3LE, 24, AudioDataConverters::int24LE,
  218780. SND_PCM_FORMAT_S24_3BE, 24, AudioDataConverters::int24BE,
  218781. SND_PCM_FORMAT_S16_LE, 16, AudioDataConverters::int16LE,
  218782. SND_PCM_FORMAT_S16_BE, 16, AudioDataConverters::int16BE };
  218783. bitDepth = 0;
  218784. for (int i = 0; i < numElementsInArray (formatsToTry); i += 3)
  218785. {
  218786. if (snd_pcm_hw_params_set_format (handle, hwParams, (_snd_pcm_format) formatsToTry [i]) >= 0)
  218787. {
  218788. bitDepth = formatsToTry [i + 1];
  218789. sampleFormat = (AudioDataConverters::DataFormat) formatsToTry [i + 2];
  218790. break;
  218791. }
  218792. }
  218793. if (bitDepth == 0)
  218794. {
  218795. error = "device doesn't support a compatible PCM format";
  218796. DBG ("ALSA error: " + error + "\n");
  218797. return false;
  218798. }
  218799. int dir = 0;
  218800. unsigned int periods = 4;
  218801. snd_pcm_uframes_t samplesPerPeriod = bufferSize;
  218802. if (failed (snd_pcm_hw_params_set_rate_near (handle, hwParams, &sampleRate, 0))
  218803. || failed (snd_pcm_hw_params_set_channels (handle, hwParams, numChannels))
  218804. || failed (snd_pcm_hw_params_set_periods_near (handle, hwParams, &periods, &dir))
  218805. || failed (snd_pcm_hw_params_set_period_size_near (handle, hwParams, &samplesPerPeriod, &dir))
  218806. || failed (snd_pcm_hw_params (handle, hwParams)))
  218807. {
  218808. return false;
  218809. }
  218810. snd_pcm_sw_params_t* swParams;
  218811. snd_pcm_sw_params_alloca (&swParams);
  218812. snd_pcm_uframes_t boundary;
  218813. if (failed (snd_pcm_sw_params_current (handle, swParams))
  218814. || failed (snd_pcm_sw_params_get_boundary (swParams, &boundary))
  218815. || failed (snd_pcm_sw_params_set_silence_threshold (handle, swParams, 0))
  218816. || failed (snd_pcm_sw_params_set_silence_size (handle, swParams, boundary))
  218817. || failed (snd_pcm_sw_params_set_start_threshold (handle, swParams, samplesPerPeriod))
  218818. || failed (snd_pcm_sw_params_set_stop_threshold (handle, swParams, boundary))
  218819. || failed (snd_pcm_sw_params (handle, swParams)))
  218820. {
  218821. return false;
  218822. }
  218823. /*
  218824. #if JUCE_DEBUG
  218825. // enable this to dump the config of the devices that get opened
  218826. snd_output_t* out;
  218827. snd_output_stdio_attach (&out, stderr, 0);
  218828. snd_pcm_hw_params_dump (hwParams, out);
  218829. snd_pcm_sw_params_dump (swParams, out);
  218830. #endif
  218831. */
  218832. numChannelsRunning = numChannels;
  218833. return true;
  218834. }
  218835. bool write (AudioSampleBuffer& outputChannelBuffer, const int numSamples)
  218836. {
  218837. jassert (numChannelsRunning <= outputChannelBuffer.getNumChannels());
  218838. float** const data = outputChannelBuffer.getArrayOfChannels();
  218839. if (isInterleaved)
  218840. {
  218841. scratch.ensureSize (sizeof (float) * numSamples * numChannelsRunning, false);
  218842. float* interleaved = static_cast <float*> (scratch.getData());
  218843. AudioDataConverters::interleaveSamples ((const float**) data, interleaved, numSamples, numChannelsRunning);
  218844. AudioDataConverters::convertFloatToFormat (sampleFormat, interleaved, interleaved, numSamples * numChannelsRunning);
  218845. snd_pcm_sframes_t num = snd_pcm_writei (handle, interleaved, numSamples);
  218846. if (failed (num) && num != -EPIPE && num != -ESTRPIPE)
  218847. return false;
  218848. }
  218849. else
  218850. {
  218851. for (int i = 0; i < numChannelsRunning; ++i)
  218852. if (data[i] != 0)
  218853. AudioDataConverters::convertFloatToFormat (sampleFormat, data[i], data[i], numSamples);
  218854. snd_pcm_sframes_t num = snd_pcm_writen (handle, (void**) data, numSamples);
  218855. if (failed (num))
  218856. {
  218857. if (num == -EPIPE)
  218858. {
  218859. if (failed (snd_pcm_prepare (handle)))
  218860. return false;
  218861. }
  218862. else if (num != -ESTRPIPE)
  218863. return false;
  218864. }
  218865. }
  218866. return true;
  218867. }
  218868. bool read (AudioSampleBuffer& inputChannelBuffer, const int numSamples)
  218869. {
  218870. jassert (numChannelsRunning <= inputChannelBuffer.getNumChannels());
  218871. float** const data = inputChannelBuffer.getArrayOfChannels();
  218872. if (isInterleaved)
  218873. {
  218874. scratch.ensureSize (sizeof (float) * numSamples * numChannelsRunning, false);
  218875. float* interleaved = static_cast <float*> (scratch.getData());
  218876. snd_pcm_sframes_t num = snd_pcm_readi (handle, interleaved, numSamples);
  218877. if (failed (num))
  218878. {
  218879. if (num == -EPIPE)
  218880. {
  218881. if (failed (snd_pcm_prepare (handle)))
  218882. return false;
  218883. }
  218884. else if (num != -ESTRPIPE)
  218885. return false;
  218886. }
  218887. AudioDataConverters::convertFormatToFloat (sampleFormat, interleaved, interleaved, numSamples * numChannelsRunning);
  218888. AudioDataConverters::deinterleaveSamples (interleaved, data, numSamples, numChannelsRunning);
  218889. }
  218890. else
  218891. {
  218892. snd_pcm_sframes_t num = snd_pcm_readn (handle, (void**) data, numSamples);
  218893. if (failed (num) && num != -EPIPE && num != -ESTRPIPE)
  218894. return false;
  218895. for (int i = 0; i < numChannelsRunning; ++i)
  218896. if (data[i] != 0)
  218897. AudioDataConverters::convertFormatToFloat (sampleFormat, data[i], data[i], numSamples);
  218898. }
  218899. return true;
  218900. }
  218901. juce_UseDebuggingNewOperator
  218902. snd_pcm_t* handle;
  218903. String error;
  218904. int bitDepth, numChannelsRunning;
  218905. private:
  218906. const bool isInput;
  218907. bool isInterleaved;
  218908. MemoryBlock scratch;
  218909. AudioDataConverters::DataFormat sampleFormat;
  218910. bool failed (const int errorNum)
  218911. {
  218912. if (errorNum >= 0)
  218913. return false;
  218914. error = snd_strerror (errorNum);
  218915. DBG ("ALSA error: " + error + "\n");
  218916. return true;
  218917. }
  218918. };
  218919. class ALSAThread : public Thread
  218920. {
  218921. public:
  218922. ALSAThread (const String& inputId_,
  218923. const String& outputId_)
  218924. : Thread ("Juce ALSA"),
  218925. sampleRate (0),
  218926. bufferSize (0),
  218927. callback (0),
  218928. inputId (inputId_),
  218929. outputId (outputId_),
  218930. outputDevice (0),
  218931. inputDevice (0),
  218932. numCallbacks (0),
  218933. inputChannelBuffer (1, 1),
  218934. outputChannelBuffer (1, 1)
  218935. {
  218936. initialiseRatesAndChannels();
  218937. }
  218938. ~ALSAThread()
  218939. {
  218940. close();
  218941. }
  218942. void open (BigInteger inputChannels,
  218943. BigInteger outputChannels,
  218944. const double sampleRate_,
  218945. const int bufferSize_)
  218946. {
  218947. close();
  218948. error = String::empty;
  218949. sampleRate = sampleRate_;
  218950. bufferSize = bufferSize_;
  218951. inputChannelBuffer.setSize (jmax ((int) minChansIn, inputChannels.getHighestBit()) + 1, bufferSize);
  218952. inputChannelBuffer.clear();
  218953. inputChannelDataForCallback.clear();
  218954. currentInputChans.clear();
  218955. if (inputChannels.getHighestBit() >= 0)
  218956. {
  218957. for (int i = 0; i <= jmax (inputChannels.getHighestBit(), (int) minChansIn); ++i)
  218958. {
  218959. if (inputChannels[i])
  218960. {
  218961. inputChannelDataForCallback.add (inputChannelBuffer.getSampleData (i));
  218962. currentInputChans.setBit (i);
  218963. }
  218964. }
  218965. }
  218966. outputChannelBuffer.setSize (jmax ((int) minChansOut, outputChannels.getHighestBit()) + 1, bufferSize);
  218967. outputChannelBuffer.clear();
  218968. outputChannelDataForCallback.clear();
  218969. currentOutputChans.clear();
  218970. if (outputChannels.getHighestBit() >= 0)
  218971. {
  218972. for (int i = 0; i <= jmax (outputChannels.getHighestBit(), (int) minChansOut); ++i)
  218973. {
  218974. if (outputChannels[i])
  218975. {
  218976. outputChannelDataForCallback.add (outputChannelBuffer.getSampleData (i));
  218977. currentOutputChans.setBit (i);
  218978. }
  218979. }
  218980. }
  218981. if (outputChannelDataForCallback.size() > 0 && outputId.isNotEmpty())
  218982. {
  218983. outputDevice = new ALSADevice (outputId, false);
  218984. if (outputDevice->error.isNotEmpty())
  218985. {
  218986. error = outputDevice->error;
  218987. deleteAndZero (outputDevice);
  218988. return;
  218989. }
  218990. currentOutputChans.setRange (0, minChansOut, true);
  218991. if (! outputDevice->setParameters ((unsigned int) sampleRate,
  218992. jlimit ((int) minChansOut, (int) maxChansOut, currentOutputChans.getHighestBit() + 1),
  218993. bufferSize))
  218994. {
  218995. error = outputDevice->error;
  218996. deleteAndZero (outputDevice);
  218997. return;
  218998. }
  218999. }
  219000. if (inputChannelDataForCallback.size() > 0 && inputId.isNotEmpty())
  219001. {
  219002. inputDevice = new ALSADevice (inputId, true);
  219003. if (inputDevice->error.isNotEmpty())
  219004. {
  219005. error = inputDevice->error;
  219006. deleteAndZero (inputDevice);
  219007. return;
  219008. }
  219009. currentInputChans.setRange (0, minChansIn, true);
  219010. if (! inputDevice->setParameters ((unsigned int) sampleRate,
  219011. jlimit ((int) minChansIn, (int) maxChansIn, currentInputChans.getHighestBit() + 1),
  219012. bufferSize))
  219013. {
  219014. error = inputDevice->error;
  219015. deleteAndZero (inputDevice);
  219016. return;
  219017. }
  219018. }
  219019. if (outputDevice == 0 && inputDevice == 0)
  219020. {
  219021. error = "no channels";
  219022. return;
  219023. }
  219024. if (outputDevice != 0 && inputDevice != 0)
  219025. {
  219026. snd_pcm_link (outputDevice->handle, inputDevice->handle);
  219027. }
  219028. if (inputDevice != 0 && failed (snd_pcm_prepare (inputDevice->handle)))
  219029. return;
  219030. if (outputDevice != 0 && failed (snd_pcm_prepare (outputDevice->handle)))
  219031. return;
  219032. startThread (9);
  219033. int count = 1000;
  219034. while (numCallbacks == 0)
  219035. {
  219036. sleep (5);
  219037. if (--count < 0 || ! isThreadRunning())
  219038. {
  219039. error = "device didn't start";
  219040. break;
  219041. }
  219042. }
  219043. }
  219044. void close()
  219045. {
  219046. stopThread (6000);
  219047. deleteAndZero (inputDevice);
  219048. deleteAndZero (outputDevice);
  219049. inputChannelBuffer.setSize (1, 1);
  219050. outputChannelBuffer.setSize (1, 1);
  219051. numCallbacks = 0;
  219052. }
  219053. void setCallback (AudioIODeviceCallback* const newCallback) throw()
  219054. {
  219055. const ScopedLock sl (callbackLock);
  219056. callback = newCallback;
  219057. }
  219058. void run()
  219059. {
  219060. while (! threadShouldExit())
  219061. {
  219062. if (inputDevice != 0)
  219063. {
  219064. if (! inputDevice->read (inputChannelBuffer, bufferSize))
  219065. {
  219066. DBG ("ALSA: read failure");
  219067. break;
  219068. }
  219069. }
  219070. if (threadShouldExit())
  219071. break;
  219072. {
  219073. const ScopedLock sl (callbackLock);
  219074. ++numCallbacks;
  219075. if (callback != 0)
  219076. {
  219077. callback->audioDeviceIOCallback ((const float**) inputChannelDataForCallback.getRawDataPointer(),
  219078. inputChannelDataForCallback.size(),
  219079. outputChannelDataForCallback.getRawDataPointer(),
  219080. outputChannelDataForCallback.size(),
  219081. bufferSize);
  219082. }
  219083. else
  219084. {
  219085. for (int i = 0; i < outputChannelDataForCallback.size(); ++i)
  219086. zeromem (outputChannelDataForCallback[i], sizeof (float) * bufferSize);
  219087. }
  219088. }
  219089. if (outputDevice != 0)
  219090. {
  219091. failed (snd_pcm_wait (outputDevice->handle, 2000));
  219092. if (threadShouldExit())
  219093. break;
  219094. failed (snd_pcm_avail_update (outputDevice->handle));
  219095. if (! outputDevice->write (outputChannelBuffer, bufferSize))
  219096. {
  219097. DBG ("ALSA: write failure");
  219098. break;
  219099. }
  219100. }
  219101. }
  219102. }
  219103. int getBitDepth() const throw()
  219104. {
  219105. if (outputDevice != 0)
  219106. return outputDevice->bitDepth;
  219107. if (inputDevice != 0)
  219108. return inputDevice->bitDepth;
  219109. return 16;
  219110. }
  219111. juce_UseDebuggingNewOperator
  219112. String error;
  219113. double sampleRate;
  219114. int bufferSize;
  219115. BigInteger currentInputChans, currentOutputChans;
  219116. Array <int> sampleRates;
  219117. StringArray channelNamesOut, channelNamesIn;
  219118. AudioIODeviceCallback* callback;
  219119. private:
  219120. const String inputId, outputId;
  219121. ALSADevice* outputDevice;
  219122. ALSADevice* inputDevice;
  219123. int numCallbacks;
  219124. CriticalSection callbackLock;
  219125. AudioSampleBuffer inputChannelBuffer, outputChannelBuffer;
  219126. Array<float*> inputChannelDataForCallback, outputChannelDataForCallback;
  219127. unsigned int minChansOut, maxChansOut;
  219128. unsigned int minChansIn, maxChansIn;
  219129. bool failed (const int errorNum) throw()
  219130. {
  219131. if (errorNum >= 0)
  219132. return false;
  219133. error = snd_strerror (errorNum);
  219134. DBG ("ALSA error: " + error + "\n");
  219135. return true;
  219136. }
  219137. void initialiseRatesAndChannels() throw()
  219138. {
  219139. sampleRates.clear();
  219140. channelNamesOut.clear();
  219141. channelNamesIn.clear();
  219142. minChansOut = 0;
  219143. maxChansOut = 0;
  219144. minChansIn = 0;
  219145. maxChansIn = 0;
  219146. unsigned int dummy = 0;
  219147. getDeviceProperties (inputId, dummy, dummy, minChansIn, maxChansIn, sampleRates);
  219148. getDeviceProperties (outputId, minChansOut, maxChansOut, dummy, dummy, sampleRates);
  219149. unsigned int i;
  219150. for (i = 0; i < maxChansOut; ++i)
  219151. channelNamesOut.add ("channel " + String ((int) i + 1));
  219152. for (i = 0; i < maxChansIn; ++i)
  219153. channelNamesIn.add ("channel " + String ((int) i + 1));
  219154. }
  219155. };
  219156. class ALSAAudioIODevice : public AudioIODevice
  219157. {
  219158. public:
  219159. ALSAAudioIODevice (const String& deviceName,
  219160. const String& inputId_,
  219161. const String& outputId_)
  219162. : AudioIODevice (deviceName, "ALSA"),
  219163. inputId (inputId_),
  219164. outputId (outputId_),
  219165. isOpen_ (false),
  219166. isStarted (false),
  219167. internal (new ALSAThread (inputId_, outputId_))
  219168. {
  219169. }
  219170. ~ALSAAudioIODevice()
  219171. {
  219172. }
  219173. const StringArray getOutputChannelNames()
  219174. {
  219175. return internal->channelNamesOut;
  219176. }
  219177. const StringArray getInputChannelNames()
  219178. {
  219179. return internal->channelNamesIn;
  219180. }
  219181. int getNumSampleRates()
  219182. {
  219183. return internal->sampleRates.size();
  219184. }
  219185. double getSampleRate (int index)
  219186. {
  219187. return internal->sampleRates [index];
  219188. }
  219189. int getNumBufferSizesAvailable()
  219190. {
  219191. return 50;
  219192. }
  219193. int getBufferSizeSamples (int index)
  219194. {
  219195. int n = 16;
  219196. for (int i = 0; i < index; ++i)
  219197. n += n < 64 ? 16
  219198. : (n < 512 ? 32
  219199. : (n < 1024 ? 64
  219200. : (n < 2048 ? 128 : 256)));
  219201. return n;
  219202. }
  219203. int getDefaultBufferSize()
  219204. {
  219205. return 512;
  219206. }
  219207. const String open (const BigInteger& inputChannels,
  219208. const BigInteger& outputChannels,
  219209. double sampleRate,
  219210. int bufferSizeSamples)
  219211. {
  219212. close();
  219213. if (bufferSizeSamples <= 0)
  219214. bufferSizeSamples = getDefaultBufferSize();
  219215. if (sampleRate <= 0)
  219216. {
  219217. for (int i = 0; i < getNumSampleRates(); ++i)
  219218. {
  219219. if (getSampleRate (i) >= 44100)
  219220. {
  219221. sampleRate = getSampleRate (i);
  219222. break;
  219223. }
  219224. }
  219225. }
  219226. internal->open (inputChannels, outputChannels,
  219227. sampleRate, bufferSizeSamples);
  219228. isOpen_ = internal->error.isEmpty();
  219229. return internal->error;
  219230. }
  219231. void close()
  219232. {
  219233. stop();
  219234. internal->close();
  219235. isOpen_ = false;
  219236. }
  219237. bool isOpen()
  219238. {
  219239. return isOpen_;
  219240. }
  219241. int getCurrentBufferSizeSamples()
  219242. {
  219243. return internal->bufferSize;
  219244. }
  219245. double getCurrentSampleRate()
  219246. {
  219247. return internal->sampleRate;
  219248. }
  219249. int getCurrentBitDepth()
  219250. {
  219251. return internal->getBitDepth();
  219252. }
  219253. const BigInteger getActiveOutputChannels() const
  219254. {
  219255. return internal->currentOutputChans;
  219256. }
  219257. const BigInteger getActiveInputChannels() const
  219258. {
  219259. return internal->currentInputChans;
  219260. }
  219261. int getOutputLatencyInSamples()
  219262. {
  219263. return 0;
  219264. }
  219265. int getInputLatencyInSamples()
  219266. {
  219267. return 0;
  219268. }
  219269. void start (AudioIODeviceCallback* callback)
  219270. {
  219271. if (! isOpen_)
  219272. callback = 0;
  219273. internal->setCallback (callback);
  219274. if (callback != 0)
  219275. callback->audioDeviceAboutToStart (this);
  219276. isStarted = (callback != 0);
  219277. }
  219278. void stop()
  219279. {
  219280. AudioIODeviceCallback* const oldCallback = internal->callback;
  219281. start (0);
  219282. if (oldCallback != 0)
  219283. oldCallback->audioDeviceStopped();
  219284. }
  219285. bool isPlaying()
  219286. {
  219287. return isStarted && internal->error.isEmpty();
  219288. }
  219289. const String getLastError()
  219290. {
  219291. return internal->error;
  219292. }
  219293. String inputId, outputId;
  219294. private:
  219295. bool isOpen_, isStarted;
  219296. ScopedPointer<ALSAThread> internal;
  219297. };
  219298. class ALSAAudioIODeviceType : public AudioIODeviceType
  219299. {
  219300. public:
  219301. ALSAAudioIODeviceType()
  219302. : AudioIODeviceType ("ALSA"),
  219303. hasScanned (false)
  219304. {
  219305. }
  219306. ~ALSAAudioIODeviceType()
  219307. {
  219308. }
  219309. void scanForDevices()
  219310. {
  219311. if (hasScanned)
  219312. return;
  219313. hasScanned = true;
  219314. inputNames.clear();
  219315. inputIds.clear();
  219316. outputNames.clear();
  219317. outputIds.clear();
  219318. snd_ctl_t* handle;
  219319. snd_ctl_card_info_t* info;
  219320. snd_ctl_card_info_alloca (&info);
  219321. int cardNum = -1;
  219322. while (outputIds.size() + inputIds.size() <= 32)
  219323. {
  219324. snd_card_next (&cardNum);
  219325. if (cardNum < 0)
  219326. break;
  219327. if (snd_ctl_open (&handle, ("hw:" + String (cardNum)).toUTF8(), SND_CTL_NONBLOCK) >= 0)
  219328. {
  219329. if (snd_ctl_card_info (handle, info) >= 0)
  219330. {
  219331. String cardId (snd_ctl_card_info_get_id (info));
  219332. if (cardId.removeCharacters ("0123456789").isEmpty())
  219333. cardId = String (cardNum);
  219334. int device = -1;
  219335. for (;;)
  219336. {
  219337. if (snd_ctl_pcm_next_device (handle, &device) < 0 || device < 0)
  219338. break;
  219339. String id, name;
  219340. id << "hw:" << cardId << ',' << device;
  219341. bool isInput, isOutput;
  219342. if (testDevice (id, isInput, isOutput))
  219343. {
  219344. name << snd_ctl_card_info_get_name (info);
  219345. if (name.isEmpty())
  219346. name = id;
  219347. if (isInput)
  219348. {
  219349. inputNames.add (name);
  219350. inputIds.add (id);
  219351. }
  219352. if (isOutput)
  219353. {
  219354. outputNames.add (name);
  219355. outputIds.add (id);
  219356. }
  219357. }
  219358. }
  219359. }
  219360. snd_ctl_close (handle);
  219361. }
  219362. }
  219363. inputNames.appendNumbersToDuplicates (false, true);
  219364. outputNames.appendNumbersToDuplicates (false, true);
  219365. }
  219366. const StringArray getDeviceNames (bool wantInputNames) const
  219367. {
  219368. jassert (hasScanned); // need to call scanForDevices() before doing this
  219369. return wantInputNames ? inputNames : outputNames;
  219370. }
  219371. int getDefaultDeviceIndex (bool forInput) const
  219372. {
  219373. jassert (hasScanned); // need to call scanForDevices() before doing this
  219374. return 0;
  219375. }
  219376. bool hasSeparateInputsAndOutputs() const { return true; }
  219377. int getIndexOfDevice (AudioIODevice* device, bool asInput) const
  219378. {
  219379. jassert (hasScanned); // need to call scanForDevices() before doing this
  219380. ALSAAudioIODevice* d = dynamic_cast <ALSAAudioIODevice*> (device);
  219381. if (d == 0)
  219382. return -1;
  219383. return asInput ? inputIds.indexOf (d->inputId)
  219384. : outputIds.indexOf (d->outputId);
  219385. }
  219386. AudioIODevice* createDevice (const String& outputDeviceName,
  219387. const String& inputDeviceName)
  219388. {
  219389. jassert (hasScanned); // need to call scanForDevices() before doing this
  219390. const int inputIndex = inputNames.indexOf (inputDeviceName);
  219391. const int outputIndex = outputNames.indexOf (outputDeviceName);
  219392. String deviceName (outputIndex >= 0 ? outputDeviceName
  219393. : inputDeviceName);
  219394. if (inputIndex >= 0 || outputIndex >= 0)
  219395. return new ALSAAudioIODevice (deviceName,
  219396. inputIds [inputIndex],
  219397. outputIds [outputIndex]);
  219398. return 0;
  219399. }
  219400. juce_UseDebuggingNewOperator
  219401. private:
  219402. StringArray inputNames, outputNames, inputIds, outputIds;
  219403. bool hasScanned;
  219404. static bool testDevice (const String& id, bool& isInput, bool& isOutput)
  219405. {
  219406. unsigned int minChansOut = 0, maxChansOut = 0;
  219407. unsigned int minChansIn = 0, maxChansIn = 0;
  219408. Array <int> rates;
  219409. getDeviceProperties (id, minChansOut, maxChansOut, minChansIn, maxChansIn, rates);
  219410. DBG ("ALSA device: " + id
  219411. + " outs=" + String ((int) minChansOut) + "-" + String ((int) maxChansOut)
  219412. + " ins=" + String ((int) minChansIn) + "-" + String ((int) maxChansIn)
  219413. + " rates=" + String (rates.size()));
  219414. isInput = maxChansIn > 0;
  219415. isOutput = maxChansOut > 0;
  219416. return (isInput || isOutput) && rates.size() > 0;
  219417. }
  219418. ALSAAudioIODeviceType (const ALSAAudioIODeviceType&);
  219419. ALSAAudioIODeviceType& operator= (const ALSAAudioIODeviceType&);
  219420. };
  219421. AudioIODeviceType* juce_createAudioIODeviceType_ALSA()
  219422. {
  219423. return new ALSAAudioIODeviceType();
  219424. }
  219425. #endif
  219426. /*** End of inlined file: juce_linux_Audio.cpp ***/
  219427. /*** Start of inlined file: juce_linux_JackAudio.cpp ***/
  219428. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  219429. // compiled on its own).
  219430. #ifdef JUCE_INCLUDED_FILE
  219431. #if JUCE_JACK
  219432. static void* juce_libjack_handle = 0;
  219433. void* juce_load_jack_function (const char* const name)
  219434. {
  219435. if (juce_libjack_handle == 0)
  219436. return 0;
  219437. return dlsym (juce_libjack_handle, name);
  219438. }
  219439. #define JUCE_DECL_JACK_FUNCTION(return_type, fn_name, argument_types, arguments) \
  219440. typedef return_type (*fn_name##_ptr_t)argument_types; \
  219441. return_type fn_name argument_types { \
  219442. static fn_name##_ptr_t fn = 0; \
  219443. if (fn == 0) { fn = (fn_name##_ptr_t)juce_load_jack_function(#fn_name); } \
  219444. if (fn) return (*fn)arguments; \
  219445. else return 0; \
  219446. }
  219447. #define JUCE_DECL_VOID_JACK_FUNCTION(fn_name, argument_types, arguments) \
  219448. typedef void (*fn_name##_ptr_t)argument_types; \
  219449. void fn_name argument_types { \
  219450. static fn_name##_ptr_t fn = 0; \
  219451. if (fn == 0) { fn = (fn_name##_ptr_t)juce_load_jack_function(#fn_name); } \
  219452. if (fn) (*fn)arguments; \
  219453. }
  219454. JUCE_DECL_JACK_FUNCTION (jack_client_t*, jack_client_open, (const char* client_name, jack_options_t options, jack_status_t* status), (client_name, options, status));
  219455. JUCE_DECL_JACK_FUNCTION (int, jack_client_close, (jack_client_t *client), (client));
  219456. JUCE_DECL_JACK_FUNCTION (int, jack_activate, (jack_client_t* client), (client));
  219457. JUCE_DECL_JACK_FUNCTION (int, jack_deactivate, (jack_client_t* client), (client));
  219458. JUCE_DECL_JACK_FUNCTION (jack_nframes_t, jack_get_buffer_size, (jack_client_t* client), (client));
  219459. JUCE_DECL_JACK_FUNCTION (jack_nframes_t, jack_get_sample_rate, (jack_client_t* client), (client));
  219460. JUCE_DECL_VOID_JACK_FUNCTION (jack_on_shutdown, (jack_client_t* client, void (*function)(void* arg), void* arg), (client, function, arg));
  219461. JUCE_DECL_JACK_FUNCTION (void* , jack_port_get_buffer, (jack_port_t* port, jack_nframes_t nframes), (port, nframes));
  219462. JUCE_DECL_JACK_FUNCTION (jack_nframes_t, jack_port_get_total_latency, (jack_client_t* client, jack_port_t* port), (client, port));
  219463. JUCE_DECL_JACK_FUNCTION (jack_port_t* , jack_port_register, (jack_client_t* client, const char* port_name, const char* port_type, unsigned long flags, unsigned long buffer_size), (client, port_name, port_type, flags, buffer_size));
  219464. JUCE_DECL_VOID_JACK_FUNCTION (jack_set_error_function, (void (*func)(const char*)), (func));
  219465. JUCE_DECL_JACK_FUNCTION (int, jack_set_process_callback, (jack_client_t* client, JackProcessCallback process_callback, void* arg), (client, process_callback, arg));
  219466. JUCE_DECL_JACK_FUNCTION (const char**, jack_get_ports, (jack_client_t* client, const char* port_name_pattern, const char* type_name_pattern, unsigned long flags), (client, port_name_pattern, type_name_pattern, flags));
  219467. JUCE_DECL_JACK_FUNCTION (int, jack_connect, (jack_client_t* client, const char* source_port, const char* destination_port), (client, source_port, destination_port));
  219468. JUCE_DECL_JACK_FUNCTION (const char*, jack_port_name, (const jack_port_t* port), (port));
  219469. JUCE_DECL_JACK_FUNCTION (int, jack_set_port_connect_callback, (jack_client_t* client, JackPortConnectCallback connect_callback, void* arg), (client, connect_callback, arg));
  219470. JUCE_DECL_JACK_FUNCTION (jack_port_t* , jack_port_by_id, (jack_client_t* client, jack_port_id_t port_id), (client, port_id));
  219471. JUCE_DECL_JACK_FUNCTION (int, jack_port_connected, (const jack_port_t* port), (port));
  219472. JUCE_DECL_JACK_FUNCTION (int, jack_port_connected_to, (const jack_port_t* port, const char* port_name), (port, port_name));
  219473. #if JUCE_DEBUG
  219474. #define JACK_LOGGING_ENABLED 1
  219475. #endif
  219476. #if JACK_LOGGING_ENABLED
  219477. static void jack_Log (const String& s)
  219478. {
  219479. std::cerr << s << std::endl;
  219480. }
  219481. static void dumpJackErrorMessage (const jack_status_t status) throw()
  219482. {
  219483. if (status & JackServerFailed || status & JackServerError)
  219484. jack_Log ("Unable to connect to JACK server");
  219485. if (status & JackVersionError)
  219486. jack_Log ("Client's protocol version does not match");
  219487. if (status & JackInvalidOption)
  219488. jack_Log ("The operation contained an invalid or unsupported option");
  219489. if (status & JackNameNotUnique)
  219490. jack_Log ("The desired client name was not unique");
  219491. if (status & JackNoSuchClient)
  219492. jack_Log ("Requested client does not exist");
  219493. if (status & JackInitFailure)
  219494. jack_Log ("Unable to initialize client");
  219495. }
  219496. #else
  219497. #define dumpJackErrorMessage(a) {}
  219498. #define jack_Log(...) {}
  219499. #endif
  219500. #ifndef JUCE_JACK_CLIENT_NAME
  219501. #define JUCE_JACK_CLIENT_NAME "JuceJack"
  219502. #endif
  219503. class JackAudioIODevice : public AudioIODevice
  219504. {
  219505. public:
  219506. JackAudioIODevice (const String& deviceName,
  219507. const String& inputId_,
  219508. const String& outputId_)
  219509. : AudioIODevice (deviceName, "JACK"),
  219510. inputId (inputId_),
  219511. outputId (outputId_),
  219512. isOpen_ (false),
  219513. callback (0),
  219514. totalNumberOfInputChannels (0),
  219515. totalNumberOfOutputChannels (0)
  219516. {
  219517. jassert (deviceName.isNotEmpty());
  219518. jack_status_t status;
  219519. client = JUCE_NAMESPACE::jack_client_open (JUCE_JACK_CLIENT_NAME, JackNoStartServer, &status);
  219520. if (client == 0)
  219521. {
  219522. dumpJackErrorMessage (status);
  219523. }
  219524. else
  219525. {
  219526. JUCE_NAMESPACE::jack_set_error_function (errorCallback);
  219527. // open input ports
  219528. const StringArray inputChannels (getInputChannelNames());
  219529. for (int i = 0; i < inputChannels.size(); i++)
  219530. {
  219531. String inputName;
  219532. inputName << "in_" << ++totalNumberOfInputChannels;
  219533. inputPorts.add (JUCE_NAMESPACE::jack_port_register (client, inputName.toUTF8(),
  219534. JACK_DEFAULT_AUDIO_TYPE, JackPortIsInput, 0));
  219535. }
  219536. // open output ports
  219537. const StringArray outputChannels (getOutputChannelNames());
  219538. for (int i = 0; i < outputChannels.size (); i++)
  219539. {
  219540. String outputName;
  219541. outputName << "out_" << ++totalNumberOfOutputChannels;
  219542. outputPorts.add (JUCE_NAMESPACE::jack_port_register (client, outputName.toUTF8(),
  219543. JACK_DEFAULT_AUDIO_TYPE, JackPortIsOutput, 0));
  219544. }
  219545. inChans.calloc (totalNumberOfInputChannels + 2);
  219546. outChans.calloc (totalNumberOfOutputChannels + 2);
  219547. }
  219548. }
  219549. ~JackAudioIODevice()
  219550. {
  219551. close();
  219552. if (client != 0)
  219553. {
  219554. JUCE_NAMESPACE::jack_client_close (client);
  219555. client = 0;
  219556. }
  219557. }
  219558. const StringArray getChannelNames (bool forInput) const
  219559. {
  219560. StringArray names;
  219561. const char** const ports = JUCE_NAMESPACE::jack_get_ports (client, 0, 0, /* JackPortIsPhysical | */
  219562. forInput ? JackPortIsInput : JackPortIsOutput);
  219563. if (ports != 0)
  219564. {
  219565. int j = 0;
  219566. while (ports[j] != 0)
  219567. {
  219568. const String portName (ports [j++]);
  219569. if (portName.upToFirstOccurrenceOf (":", false, false) == getName())
  219570. names.add (portName.fromFirstOccurrenceOf (":", false, false));
  219571. }
  219572. free (ports);
  219573. }
  219574. return names;
  219575. }
  219576. const StringArray getOutputChannelNames() { return getChannelNames (false); }
  219577. const StringArray getInputChannelNames() { return getChannelNames (true); }
  219578. int getNumSampleRates() { return client != 0 ? 1 : 0; }
  219579. double getSampleRate (int index) { return client != 0 ? JUCE_NAMESPACE::jack_get_sample_rate (client) : 0; }
  219580. int getNumBufferSizesAvailable() { return client != 0 ? 1 : 0; }
  219581. int getBufferSizeSamples (int index) { return getDefaultBufferSize(); }
  219582. int getDefaultBufferSize() { return client != 0 ? JUCE_NAMESPACE::jack_get_buffer_size (client) : 0; }
  219583. const String open (const BigInteger& inputChannels, const BigInteger& outputChannels,
  219584. double sampleRate, int bufferSizeSamples)
  219585. {
  219586. if (client == 0)
  219587. {
  219588. lastError = "No JACK client running";
  219589. return lastError;
  219590. }
  219591. lastError = String::empty;
  219592. close();
  219593. JUCE_NAMESPACE::jack_set_process_callback (client, processCallback, this);
  219594. JUCE_NAMESPACE::jack_on_shutdown (client, shutdownCallback, this);
  219595. JUCE_NAMESPACE::jack_activate (client);
  219596. isOpen_ = true;
  219597. if (! inputChannels.isZero())
  219598. {
  219599. const char** const ports = JUCE_NAMESPACE::jack_get_ports (client, 0, 0, /* JackPortIsPhysical | */ JackPortIsOutput);
  219600. if (ports != 0)
  219601. {
  219602. const int numInputChannels = inputChannels.getHighestBit() + 1;
  219603. for (int i = 0; i < numInputChannels; ++i)
  219604. {
  219605. const String portName (ports[i]);
  219606. if (inputChannels[i] && portName.upToFirstOccurrenceOf (":", false, false) == getName())
  219607. {
  219608. int error = JUCE_NAMESPACE::jack_connect (client, ports[i], JUCE_NAMESPACE::jack_port_name ((jack_port_t*) inputPorts[i]));
  219609. if (error != 0)
  219610. jack_Log ("Cannot connect input port " + String (i) + " (" + String (ports[i]) + "), error " + String (error));
  219611. }
  219612. }
  219613. free (ports);
  219614. }
  219615. }
  219616. if (! outputChannels.isZero())
  219617. {
  219618. const char** const ports = JUCE_NAMESPACE::jack_get_ports (client, 0, 0, /* JackPortIsPhysical | */ JackPortIsInput);
  219619. if (ports != 0)
  219620. {
  219621. const int numOutputChannels = outputChannels.getHighestBit() + 1;
  219622. for (int i = 0; i < numOutputChannels; ++i)
  219623. {
  219624. const String portName (ports[i]);
  219625. if (outputChannels[i] && portName.upToFirstOccurrenceOf (":", false, false) == getName())
  219626. {
  219627. int error = JUCE_NAMESPACE::jack_connect (client, JUCE_NAMESPACE::jack_port_name ((jack_port_t*) outputPorts[i]), ports[i]);
  219628. if (error != 0)
  219629. jack_Log ("Cannot connect output port " + String (i) + " (" + String (ports[i]) + "), error " + String (error));
  219630. }
  219631. }
  219632. free (ports);
  219633. }
  219634. }
  219635. return lastError;
  219636. }
  219637. void close()
  219638. {
  219639. stop();
  219640. if (client != 0)
  219641. {
  219642. JUCE_NAMESPACE::jack_deactivate (client);
  219643. JUCE_NAMESPACE::jack_set_process_callback (client, processCallback, 0);
  219644. JUCE_NAMESPACE::jack_on_shutdown (client, shutdownCallback, 0);
  219645. }
  219646. isOpen_ = false;
  219647. }
  219648. void start (AudioIODeviceCallback* newCallback)
  219649. {
  219650. if (isOpen_ && newCallback != callback)
  219651. {
  219652. if (newCallback != 0)
  219653. newCallback->audioDeviceAboutToStart (this);
  219654. AudioIODeviceCallback* const oldCallback = callback;
  219655. {
  219656. const ScopedLock sl (callbackLock);
  219657. callback = newCallback;
  219658. }
  219659. if (oldCallback != 0)
  219660. oldCallback->audioDeviceStopped();
  219661. }
  219662. }
  219663. void stop()
  219664. {
  219665. start (0);
  219666. }
  219667. bool isOpen() { return isOpen_; }
  219668. bool isPlaying() { return callback != 0; }
  219669. int getCurrentBufferSizeSamples() { return getBufferSizeSamples (0); }
  219670. double getCurrentSampleRate() { return getSampleRate (0); }
  219671. int getCurrentBitDepth() { return 32; }
  219672. const String getLastError() { return lastError; }
  219673. const BigInteger getActiveOutputChannels() const
  219674. {
  219675. BigInteger outputBits;
  219676. for (int i = 0; i < outputPorts.size(); i++)
  219677. if (JUCE_NAMESPACE::jack_port_connected ((jack_port_t*) outputPorts [i]))
  219678. outputBits.setBit (i);
  219679. return outputBits;
  219680. }
  219681. const BigInteger getActiveInputChannels() const
  219682. {
  219683. BigInteger inputBits;
  219684. for (int i = 0; i < inputPorts.size(); i++)
  219685. if (JUCE_NAMESPACE::jack_port_connected ((jack_port_t*) inputPorts [i]))
  219686. inputBits.setBit (i);
  219687. return inputBits;
  219688. }
  219689. int getOutputLatencyInSamples()
  219690. {
  219691. int latency = 0;
  219692. for (int i = 0; i < outputPorts.size(); i++)
  219693. latency = jmax (latency, (int) JUCE_NAMESPACE::jack_port_get_total_latency (client, (jack_port_t*) outputPorts [i]));
  219694. return latency;
  219695. }
  219696. int getInputLatencyInSamples()
  219697. {
  219698. int latency = 0;
  219699. for (int i = 0; i < inputPorts.size(); i++)
  219700. latency = jmax (latency, (int) JUCE_NAMESPACE::jack_port_get_total_latency (client, (jack_port_t*) inputPorts [i]));
  219701. return latency;
  219702. }
  219703. String inputId, outputId;
  219704. private:
  219705. void process (const int numSamples)
  219706. {
  219707. int i, numActiveInChans = 0, numActiveOutChans = 0;
  219708. for (i = 0; i < totalNumberOfInputChannels; ++i)
  219709. {
  219710. jack_default_audio_sample_t* in
  219711. = (jack_default_audio_sample_t*) JUCE_NAMESPACE::jack_port_get_buffer ((jack_port_t*) inputPorts.getUnchecked(i), numSamples);
  219712. if (in != 0)
  219713. inChans [numActiveInChans++] = (float*) in;
  219714. }
  219715. for (i = 0; i < totalNumberOfOutputChannels; ++i)
  219716. {
  219717. jack_default_audio_sample_t* out
  219718. = (jack_default_audio_sample_t*) JUCE_NAMESPACE::jack_port_get_buffer ((jack_port_t*) outputPorts.getUnchecked(i), numSamples);
  219719. if (out != 0)
  219720. outChans [numActiveOutChans++] = (float*) out;
  219721. }
  219722. const ScopedLock sl (callbackLock);
  219723. if (callback != 0)
  219724. {
  219725. callback->audioDeviceIOCallback (const_cast<const float**> (inChans.getData()), numActiveInChans,
  219726. outChans, numActiveOutChans, numSamples);
  219727. }
  219728. else
  219729. {
  219730. for (i = 0; i < numActiveOutChans; ++i)
  219731. zeromem (outChans[i], sizeof (float) * numSamples);
  219732. }
  219733. }
  219734. static int processCallback (jack_nframes_t nframes, void* callbackArgument)
  219735. {
  219736. if (callbackArgument != 0)
  219737. ((JackAudioIODevice*) callbackArgument)->process (nframes);
  219738. return 0;
  219739. }
  219740. static void threadInitCallback (void* callbackArgument)
  219741. {
  219742. jack_Log ("JackAudioIODevice::initialise");
  219743. }
  219744. static void shutdownCallback (void* callbackArgument)
  219745. {
  219746. jack_Log ("JackAudioIODevice::shutdown");
  219747. JackAudioIODevice* device = (JackAudioIODevice*) callbackArgument;
  219748. if (device != 0)
  219749. {
  219750. device->client = 0;
  219751. device->close();
  219752. }
  219753. }
  219754. static void errorCallback (const char* msg)
  219755. {
  219756. jack_Log ("JackAudioIODevice::errorCallback " + String (msg));
  219757. }
  219758. bool isOpen_;
  219759. jack_client_t* client;
  219760. String lastError;
  219761. AudioIODeviceCallback* callback;
  219762. CriticalSection callbackLock;
  219763. HeapBlock <float*> inChans, outChans;
  219764. int totalNumberOfInputChannels;
  219765. int totalNumberOfOutputChannels;
  219766. VoidArray inputPorts, outputPorts;
  219767. };
  219768. class JackAudioIODeviceType : public AudioIODeviceType
  219769. {
  219770. public:
  219771. JackAudioIODeviceType()
  219772. : AudioIODeviceType ("JACK"),
  219773. hasScanned (false)
  219774. {
  219775. }
  219776. ~JackAudioIODeviceType()
  219777. {
  219778. }
  219779. void scanForDevices()
  219780. {
  219781. hasScanned = true;
  219782. inputNames.clear();
  219783. inputIds.clear();
  219784. outputNames.clear();
  219785. outputIds.clear();
  219786. if (juce_libjack_handle == 0)
  219787. {
  219788. juce_libjack_handle = dlopen ("libjack.so", RTLD_LAZY);
  219789. if (juce_libjack_handle == 0)
  219790. return;
  219791. }
  219792. // open a dummy client
  219793. jack_status_t status;
  219794. jack_client_t* client = JUCE_NAMESPACE::jack_client_open ("JuceJackDummy", JackNoStartServer, &status);
  219795. if (client == 0)
  219796. {
  219797. dumpJackErrorMessage (status);
  219798. }
  219799. else
  219800. {
  219801. // scan for output devices
  219802. const char** ports = JUCE_NAMESPACE::jack_get_ports (client, 0, 0, /* JackPortIsPhysical | */ JackPortIsOutput);
  219803. if (ports != 0)
  219804. {
  219805. int j = 0;
  219806. while (ports[j] != 0)
  219807. {
  219808. String clientName (ports[j]);
  219809. clientName = clientName.upToFirstOccurrenceOf (":", false, false);
  219810. if (clientName != String (JUCE_JACK_CLIENT_NAME)
  219811. && ! inputNames.contains (clientName))
  219812. {
  219813. inputNames.add (clientName);
  219814. inputIds.add (ports [j]);
  219815. }
  219816. ++j;
  219817. }
  219818. free (ports);
  219819. }
  219820. // scan for input devices
  219821. ports = JUCE_NAMESPACE::jack_get_ports (client, 0, 0, /* JackPortIsPhysical | */ JackPortIsInput);
  219822. if (ports != 0)
  219823. {
  219824. int j = 0;
  219825. while (ports[j] != 0)
  219826. {
  219827. String clientName (ports[j]);
  219828. clientName = clientName.upToFirstOccurrenceOf (":", false, false);
  219829. if (clientName != String (JUCE_JACK_CLIENT_NAME)
  219830. && ! outputNames.contains (clientName))
  219831. {
  219832. outputNames.add (clientName);
  219833. outputIds.add (ports [j]);
  219834. }
  219835. ++j;
  219836. }
  219837. free (ports);
  219838. }
  219839. JUCE_NAMESPACE::jack_client_close (client);
  219840. }
  219841. }
  219842. const StringArray getDeviceNames (bool wantInputNames) const
  219843. {
  219844. jassert (hasScanned); // need to call scanForDevices() before doing this
  219845. return wantInputNames ? inputNames : outputNames;
  219846. }
  219847. int getDefaultDeviceIndex (bool forInput) const
  219848. {
  219849. jassert (hasScanned); // need to call scanForDevices() before doing this
  219850. return 0;
  219851. }
  219852. bool hasSeparateInputsAndOutputs() const { return true; }
  219853. int getIndexOfDevice (AudioIODevice* device, bool asInput) const
  219854. {
  219855. jassert (hasScanned); // need to call scanForDevices() before doing this
  219856. JackAudioIODevice* d = dynamic_cast <JackAudioIODevice*> (device);
  219857. if (d == 0)
  219858. return -1;
  219859. return asInput ? inputIds.indexOf (d->inputId)
  219860. : outputIds.indexOf (d->outputId);
  219861. }
  219862. AudioIODevice* createDevice (const String& outputDeviceName,
  219863. const String& inputDeviceName)
  219864. {
  219865. jassert (hasScanned); // need to call scanForDevices() before doing this
  219866. const int inputIndex = inputNames.indexOf (inputDeviceName);
  219867. const int outputIndex = outputNames.indexOf (outputDeviceName);
  219868. if (inputIndex >= 0 || outputIndex >= 0)
  219869. return new JackAudioIODevice (outputIndex >= 0 ? outputDeviceName
  219870. : inputDeviceName,
  219871. inputIds [inputIndex],
  219872. outputIds [outputIndex]);
  219873. return 0;
  219874. }
  219875. juce_UseDebuggingNewOperator
  219876. private:
  219877. StringArray inputNames, outputNames, inputIds, outputIds;
  219878. bool hasScanned;
  219879. JackAudioIODeviceType (const JackAudioIODeviceType&);
  219880. JackAudioIODeviceType& operator= (const JackAudioIODeviceType&);
  219881. };
  219882. AudioIODeviceType* juce_createAudioIODeviceType_JACK()
  219883. {
  219884. return new JackAudioIODeviceType();
  219885. }
  219886. #else // if JACK is turned off..
  219887. AudioIODeviceType* juce_createAudioIODeviceType_JACK() { return 0; }
  219888. #endif
  219889. #endif
  219890. /*** End of inlined file: juce_linux_JackAudio.cpp ***/
  219891. /*** Start of inlined file: juce_linux_Midi.cpp ***/
  219892. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  219893. // compiled on its own).
  219894. #if JUCE_INCLUDED_FILE
  219895. #if JUCE_ALSA
  219896. static snd_seq_t* iterateDevices (const bool forInput,
  219897. StringArray& deviceNamesFound,
  219898. const int deviceIndexToOpen)
  219899. {
  219900. snd_seq_t* returnedHandle = 0;
  219901. snd_seq_t* seqHandle;
  219902. if (snd_seq_open (&seqHandle, "default", forInput ? SND_SEQ_OPEN_INPUT
  219903. : SND_SEQ_OPEN_OUTPUT, 0) == 0)
  219904. {
  219905. snd_seq_system_info_t* systemInfo;
  219906. snd_seq_client_info_t* clientInfo;
  219907. if (snd_seq_system_info_malloc (&systemInfo) == 0)
  219908. {
  219909. if (snd_seq_system_info (seqHandle, systemInfo) == 0
  219910. && snd_seq_client_info_malloc (&clientInfo) == 0)
  219911. {
  219912. int numClients = snd_seq_system_info_get_cur_clients (systemInfo);
  219913. while (--numClients >= 0 && returnedHandle == 0)
  219914. {
  219915. if (snd_seq_query_next_client (seqHandle, clientInfo) == 0)
  219916. {
  219917. snd_seq_port_info_t* portInfo;
  219918. if (snd_seq_port_info_malloc (&portInfo) == 0)
  219919. {
  219920. int numPorts = snd_seq_client_info_get_num_ports (clientInfo);
  219921. const int client = snd_seq_client_info_get_client (clientInfo);
  219922. snd_seq_port_info_set_client (portInfo, client);
  219923. snd_seq_port_info_set_port (portInfo, -1);
  219924. while (--numPorts >= 0)
  219925. {
  219926. if (snd_seq_query_next_port (seqHandle, portInfo) == 0
  219927. && (snd_seq_port_info_get_capability (portInfo)
  219928. & (forInput ? SND_SEQ_PORT_CAP_READ
  219929. : SND_SEQ_PORT_CAP_WRITE)) != 0)
  219930. {
  219931. deviceNamesFound.add (snd_seq_client_info_get_name (clientInfo));
  219932. if (deviceNamesFound.size() == deviceIndexToOpen + 1)
  219933. {
  219934. const int sourcePort = snd_seq_port_info_get_port (portInfo);
  219935. const int sourceClient = snd_seq_client_info_get_client (clientInfo);
  219936. if (sourcePort != -1)
  219937. {
  219938. snd_seq_set_client_name (seqHandle,
  219939. forInput ? "Juce Midi Input"
  219940. : "Juce Midi Output");
  219941. const int portId
  219942. = snd_seq_create_simple_port (seqHandle,
  219943. forInput ? "Juce Midi In Port"
  219944. : "Juce Midi Out Port",
  219945. forInput ? (SND_SEQ_PORT_CAP_WRITE | SND_SEQ_PORT_CAP_SUBS_WRITE)
  219946. : (SND_SEQ_PORT_CAP_READ | SND_SEQ_PORT_CAP_SUBS_READ),
  219947. SND_SEQ_PORT_TYPE_MIDI_GENERIC);
  219948. snd_seq_connect_from (seqHandle, portId, sourceClient, sourcePort);
  219949. returnedHandle = seqHandle;
  219950. }
  219951. }
  219952. }
  219953. }
  219954. snd_seq_port_info_free (portInfo);
  219955. }
  219956. }
  219957. }
  219958. snd_seq_client_info_free (clientInfo);
  219959. }
  219960. snd_seq_system_info_free (systemInfo);
  219961. }
  219962. if (returnedHandle == 0)
  219963. snd_seq_close (seqHandle);
  219964. }
  219965. deviceNamesFound.appendNumbersToDuplicates (true, true);
  219966. return returnedHandle;
  219967. }
  219968. static snd_seq_t* createDevice (const bool forInput,
  219969. const String& deviceNameToOpen)
  219970. {
  219971. snd_seq_t* seqHandle = 0;
  219972. if (snd_seq_open (&seqHandle, "default", forInput ? SND_SEQ_OPEN_INPUT
  219973. : SND_SEQ_OPEN_OUTPUT, 0) == 0)
  219974. {
  219975. snd_seq_set_client_name (seqHandle,
  219976. (deviceNameToOpen + (forInput ? " Input" : " Output")).toCString());
  219977. const int portId
  219978. = snd_seq_create_simple_port (seqHandle,
  219979. forInput ? "in"
  219980. : "out",
  219981. forInput ? (SND_SEQ_PORT_CAP_WRITE | SND_SEQ_PORT_CAP_SUBS_WRITE)
  219982. : (SND_SEQ_PORT_CAP_READ | SND_SEQ_PORT_CAP_SUBS_READ),
  219983. forInput ? SND_SEQ_PORT_TYPE_APPLICATION
  219984. : SND_SEQ_PORT_TYPE_MIDI_GENERIC);
  219985. if (portId < 0)
  219986. {
  219987. snd_seq_close (seqHandle);
  219988. seqHandle = 0;
  219989. }
  219990. }
  219991. return seqHandle;
  219992. }
  219993. class MidiOutputDevice
  219994. {
  219995. public:
  219996. MidiOutputDevice (MidiOutput* const midiOutput_,
  219997. snd_seq_t* const seqHandle_)
  219998. :
  219999. midiOutput (midiOutput_),
  220000. seqHandle (seqHandle_),
  220001. maxEventSize (16 * 1024)
  220002. {
  220003. jassert (seqHandle != 0 && midiOutput != 0);
  220004. snd_midi_event_new (maxEventSize, &midiParser);
  220005. }
  220006. ~MidiOutputDevice()
  220007. {
  220008. snd_midi_event_free (midiParser);
  220009. snd_seq_close (seqHandle);
  220010. }
  220011. void sendMessageNow (const MidiMessage& message)
  220012. {
  220013. if (message.getRawDataSize() > maxEventSize)
  220014. {
  220015. maxEventSize = message.getRawDataSize();
  220016. snd_midi_event_free (midiParser);
  220017. snd_midi_event_new (maxEventSize, &midiParser);
  220018. }
  220019. snd_seq_event_t event;
  220020. snd_seq_ev_clear (&event);
  220021. snd_midi_event_encode (midiParser,
  220022. message.getRawData(),
  220023. message.getRawDataSize(),
  220024. &event);
  220025. snd_midi_event_reset_encode (midiParser);
  220026. snd_seq_ev_set_source (&event, 0);
  220027. snd_seq_ev_set_subs (&event);
  220028. snd_seq_ev_set_direct (&event);
  220029. snd_seq_event_output (seqHandle, &event);
  220030. snd_seq_drain_output (seqHandle);
  220031. }
  220032. juce_UseDebuggingNewOperator
  220033. private:
  220034. MidiOutput* const midiOutput;
  220035. snd_seq_t* const seqHandle;
  220036. snd_midi_event_t* midiParser;
  220037. int maxEventSize;
  220038. };
  220039. const StringArray MidiOutput::getDevices()
  220040. {
  220041. StringArray devices;
  220042. iterateDevices (false, devices, -1);
  220043. return devices;
  220044. }
  220045. int MidiOutput::getDefaultDeviceIndex()
  220046. {
  220047. return 0;
  220048. }
  220049. MidiOutput* MidiOutput::openDevice (int deviceIndex)
  220050. {
  220051. MidiOutput* newDevice = 0;
  220052. StringArray devices;
  220053. snd_seq_t* const handle = iterateDevices (false, devices, deviceIndex);
  220054. if (handle != 0)
  220055. {
  220056. newDevice = new MidiOutput();
  220057. newDevice->internal = new MidiOutputDevice (newDevice, handle);
  220058. }
  220059. return newDevice;
  220060. }
  220061. MidiOutput* MidiOutput::createNewDevice (const String& deviceName)
  220062. {
  220063. MidiOutput* newDevice = 0;
  220064. snd_seq_t* const handle = createDevice (false, deviceName);
  220065. if (handle != 0)
  220066. {
  220067. newDevice = new MidiOutput();
  220068. newDevice->internal = new MidiOutputDevice (newDevice, handle);
  220069. }
  220070. return newDevice;
  220071. }
  220072. MidiOutput::~MidiOutput()
  220073. {
  220074. MidiOutputDevice* const device = (MidiOutputDevice*) internal;
  220075. delete device;
  220076. }
  220077. void MidiOutput::reset()
  220078. {
  220079. }
  220080. bool MidiOutput::getVolume (float& leftVol, float& rightVol)
  220081. {
  220082. return false;
  220083. }
  220084. void MidiOutput::setVolume (float leftVol, float rightVol)
  220085. {
  220086. }
  220087. void MidiOutput::sendMessageNow (const MidiMessage& message)
  220088. {
  220089. ((MidiOutputDevice*) internal)->sendMessageNow (message);
  220090. }
  220091. class MidiInputThread : public Thread
  220092. {
  220093. public:
  220094. MidiInputThread (MidiInput* const midiInput_,
  220095. snd_seq_t* const seqHandle_,
  220096. MidiInputCallback* const callback_)
  220097. : Thread ("Juce MIDI Input"),
  220098. midiInput (midiInput_),
  220099. seqHandle (seqHandle_),
  220100. callback (callback_)
  220101. {
  220102. jassert (seqHandle != 0 && callback != 0 && midiInput != 0);
  220103. }
  220104. ~MidiInputThread()
  220105. {
  220106. snd_seq_close (seqHandle);
  220107. }
  220108. void run()
  220109. {
  220110. const int maxEventSize = 16 * 1024;
  220111. snd_midi_event_t* midiParser;
  220112. if (snd_midi_event_new (maxEventSize, &midiParser) >= 0)
  220113. {
  220114. HeapBlock <uint8> buffer (maxEventSize);
  220115. const int numPfds = snd_seq_poll_descriptors_count (seqHandle, POLLIN);
  220116. struct pollfd* const pfd = (struct pollfd*) alloca (numPfds * sizeof (struct pollfd));
  220117. snd_seq_poll_descriptors (seqHandle, pfd, numPfds, POLLIN);
  220118. while (! threadShouldExit())
  220119. {
  220120. if (poll (pfd, numPfds, 500) > 0)
  220121. {
  220122. snd_seq_event_t* inputEvent = 0;
  220123. snd_seq_nonblock (seqHandle, 1);
  220124. do
  220125. {
  220126. if (snd_seq_event_input (seqHandle, &inputEvent) >= 0)
  220127. {
  220128. // xxx what about SYSEXes that are too big for the buffer?
  220129. const int numBytes = snd_midi_event_decode (midiParser, buffer, maxEventSize, inputEvent);
  220130. snd_midi_event_reset_decode (midiParser);
  220131. if (numBytes > 0)
  220132. {
  220133. const MidiMessage message ((const uint8*) buffer,
  220134. numBytes,
  220135. Time::getMillisecondCounter() * 0.001);
  220136. callback->handleIncomingMidiMessage (midiInput, message);
  220137. }
  220138. snd_seq_free_event (inputEvent);
  220139. }
  220140. }
  220141. while (snd_seq_event_input_pending (seqHandle, 0) > 0);
  220142. snd_seq_free_event (inputEvent);
  220143. }
  220144. }
  220145. snd_midi_event_free (midiParser);
  220146. }
  220147. };
  220148. juce_UseDebuggingNewOperator
  220149. private:
  220150. MidiInput* const midiInput;
  220151. snd_seq_t* const seqHandle;
  220152. MidiInputCallback* const callback;
  220153. };
  220154. MidiInput::MidiInput (const String& name_)
  220155. : name (name_),
  220156. internal (0)
  220157. {
  220158. }
  220159. MidiInput::~MidiInput()
  220160. {
  220161. stop();
  220162. MidiInputThread* const thread = (MidiInputThread*) internal;
  220163. delete thread;
  220164. }
  220165. void MidiInput::start()
  220166. {
  220167. ((MidiInputThread*) internal)->startThread();
  220168. }
  220169. void MidiInput::stop()
  220170. {
  220171. ((MidiInputThread*) internal)->stopThread (3000);
  220172. }
  220173. int MidiInput::getDefaultDeviceIndex()
  220174. {
  220175. return 0;
  220176. }
  220177. const StringArray MidiInput::getDevices()
  220178. {
  220179. StringArray devices;
  220180. iterateDevices (true, devices, -1);
  220181. return devices;
  220182. }
  220183. MidiInput* MidiInput::openDevice (int deviceIndex, MidiInputCallback* callback)
  220184. {
  220185. MidiInput* newDevice = 0;
  220186. StringArray devices;
  220187. snd_seq_t* const handle = iterateDevices (true, devices, deviceIndex);
  220188. if (handle != 0)
  220189. {
  220190. newDevice = new MidiInput (devices [deviceIndex]);
  220191. newDevice->internal = new MidiInputThread (newDevice, handle, callback);
  220192. }
  220193. return newDevice;
  220194. }
  220195. MidiInput* MidiInput::createNewDevice (const String& deviceName, MidiInputCallback* callback)
  220196. {
  220197. MidiInput* newDevice = 0;
  220198. snd_seq_t* const handle = createDevice (true, deviceName);
  220199. if (handle != 0)
  220200. {
  220201. newDevice = new MidiInput (deviceName);
  220202. newDevice->internal = new MidiInputThread (newDevice, handle, callback);
  220203. }
  220204. return newDevice;
  220205. }
  220206. #else
  220207. // (These are just stub functions if ALSA is unavailable...)
  220208. const StringArray MidiOutput::getDevices() { return StringArray(); }
  220209. int MidiOutput::getDefaultDeviceIndex() { return 0; }
  220210. MidiOutput* MidiOutput::openDevice (int) { return 0; }
  220211. MidiOutput* MidiOutput::createNewDevice (const String&) { return 0; }
  220212. MidiOutput::~MidiOutput() {}
  220213. void MidiOutput::reset() {}
  220214. bool MidiOutput::getVolume (float&, float&) { return false; }
  220215. void MidiOutput::setVolume (float, float) {}
  220216. void MidiOutput::sendMessageNow (const MidiMessage&) {}
  220217. MidiInput::MidiInput (const String& name_) : name (name_), internal (0) {}
  220218. MidiInput::~MidiInput() {}
  220219. void MidiInput::start() {}
  220220. void MidiInput::stop() {}
  220221. int MidiInput::getDefaultDeviceIndex() { return 0; }
  220222. const StringArray MidiInput::getDevices() { return StringArray(); }
  220223. MidiInput* MidiInput::openDevice (int, MidiInputCallback*) { return 0; }
  220224. MidiInput* MidiInput::createNewDevice (const String&, MidiInputCallback*) { return 0; }
  220225. #endif
  220226. #endif
  220227. /*** End of inlined file: juce_linux_Midi.cpp ***/
  220228. /*** Start of inlined file: juce_linux_AudioCDReader.cpp ***/
  220229. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  220230. // compiled on its own).
  220231. #if JUCE_INCLUDED_FILE && JUCE_USE_CDREADER
  220232. AudioCDReader::AudioCDReader()
  220233. : AudioFormatReader (0, "CD Audio")
  220234. {
  220235. }
  220236. const StringArray AudioCDReader::getAvailableCDNames()
  220237. {
  220238. StringArray names;
  220239. return names;
  220240. }
  220241. AudioCDReader* AudioCDReader::createReaderForCD (const int index)
  220242. {
  220243. return 0;
  220244. }
  220245. AudioCDReader::~AudioCDReader()
  220246. {
  220247. }
  220248. void AudioCDReader::refreshTrackLengths()
  220249. {
  220250. }
  220251. bool AudioCDReader::readSamples (int** destSamples, int numDestChannels, int startOffsetInDestBuffer,
  220252. int64 startSampleInFile, int numSamples)
  220253. {
  220254. return false;
  220255. }
  220256. bool AudioCDReader::isCDStillPresent() const
  220257. {
  220258. return false;
  220259. }
  220260. int AudioCDReader::getNumTracks() const
  220261. {
  220262. return 0;
  220263. }
  220264. int AudioCDReader::getPositionOfTrackStart (int trackNum) const
  220265. {
  220266. return 0;
  220267. }
  220268. bool AudioCDReader::isTrackAudio (int trackNum) const
  220269. {
  220270. return false;
  220271. }
  220272. void AudioCDReader::enableIndexScanning (bool b)
  220273. {
  220274. }
  220275. int AudioCDReader::getLastIndex() const
  220276. {
  220277. return 0;
  220278. }
  220279. const Array<int> AudioCDReader::findIndexesInTrack (const int trackNumber)
  220280. {
  220281. return Array<int>();
  220282. }
  220283. int AudioCDReader::getCDDBId()
  220284. {
  220285. return 0;
  220286. }
  220287. #endif
  220288. /*** End of inlined file: juce_linux_AudioCDReader.cpp ***/
  220289. /*** Start of inlined file: juce_linux_FileChooser.cpp ***/
  220290. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  220291. // compiled on its own).
  220292. #if JUCE_INCLUDED_FILE
  220293. void FileChooser::showPlatformDialog (Array<File>& results,
  220294. const String& title,
  220295. const File& file,
  220296. const String& filters,
  220297. bool isDirectory,
  220298. bool selectsFiles,
  220299. bool isSave,
  220300. bool warnAboutOverwritingExistingFiles,
  220301. bool selectMultipleFiles,
  220302. FilePreviewComponent* previewComponent)
  220303. {
  220304. const String separator (":");
  220305. String command ("zenity --file-selection");
  220306. if (title.isNotEmpty())
  220307. command << " --title=\"" << title << "\"";
  220308. if (file != File::nonexistent)
  220309. command << " --filename=\"" << file.getFullPathName () << "\"";
  220310. if (isDirectory)
  220311. command << " --directory";
  220312. if (isSave)
  220313. command << " --save";
  220314. if (selectMultipleFiles)
  220315. command << " --multiple --separator=\"" << separator << "\"";
  220316. command << " 2>&1";
  220317. MemoryOutputStream result;
  220318. int status = -1;
  220319. FILE* stream = popen (command.toUTF8(), "r");
  220320. if (stream != 0)
  220321. {
  220322. for (;;)
  220323. {
  220324. char buffer [1024];
  220325. const int bytesRead = fread (buffer, 1, sizeof (buffer), stream);
  220326. if (bytesRead <= 0)
  220327. break;
  220328. result.write (buffer, bytesRead);
  220329. }
  220330. status = pclose (stream);
  220331. }
  220332. if (status == 0)
  220333. {
  220334. StringArray tokens;
  220335. if (selectMultipleFiles)
  220336. tokens.addTokens (result.toUTF8(), separator, String::empty);
  220337. else
  220338. tokens.add (result.toUTF8());
  220339. for (int i = 0; i < tokens.size(); i++)
  220340. results.add (File (tokens[i]));
  220341. return;
  220342. }
  220343. //xxx ain't got one!
  220344. jassertfalse
  220345. }
  220346. #endif
  220347. /*** End of inlined file: juce_linux_FileChooser.cpp ***/
  220348. /*** Start of inlined file: juce_linux_WebBrowserComponent.cpp ***/
  220349. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  220350. // compiled on its own).
  220351. #if JUCE_INCLUDED_FILE && JUCE_WEB_BROWSER
  220352. /*
  220353. Sorry.. This class isn't implemented on Linux!
  220354. */
  220355. WebBrowserComponent::WebBrowserComponent (const bool unloadPageWhenBrowserIsHidden_)
  220356. : browser (0),
  220357. blankPageShown (false),
  220358. unloadPageWhenBrowserIsHidden (unloadPageWhenBrowserIsHidden_)
  220359. {
  220360. setOpaque (true);
  220361. }
  220362. WebBrowserComponent::~WebBrowserComponent()
  220363. {
  220364. }
  220365. void WebBrowserComponent::goToURL (const String& url,
  220366. const StringArray* headers,
  220367. const MemoryBlock* postData)
  220368. {
  220369. lastURL = url;
  220370. lastHeaders.clear();
  220371. if (headers != 0)
  220372. lastHeaders = *headers;
  220373. lastPostData.setSize (0);
  220374. if (postData != 0)
  220375. lastPostData = *postData;
  220376. blankPageShown = false;
  220377. }
  220378. void WebBrowserComponent::stop()
  220379. {
  220380. }
  220381. void WebBrowserComponent::goBack()
  220382. {
  220383. lastURL = String::empty;
  220384. blankPageShown = false;
  220385. }
  220386. void WebBrowserComponent::goForward()
  220387. {
  220388. lastURL = String::empty;
  220389. }
  220390. void WebBrowserComponent::refresh()
  220391. {
  220392. }
  220393. void WebBrowserComponent::paint (Graphics& g)
  220394. {
  220395. g.fillAll (Colours::white);
  220396. }
  220397. void WebBrowserComponent::checkWindowAssociation()
  220398. {
  220399. }
  220400. void WebBrowserComponent::reloadLastURL()
  220401. {
  220402. if (lastURL.isNotEmpty())
  220403. {
  220404. goToURL (lastURL, &lastHeaders, &lastPostData);
  220405. lastURL = String::empty;
  220406. }
  220407. }
  220408. void WebBrowserComponent::parentHierarchyChanged()
  220409. {
  220410. checkWindowAssociation();
  220411. }
  220412. void WebBrowserComponent::resized()
  220413. {
  220414. }
  220415. void WebBrowserComponent::visibilityChanged()
  220416. {
  220417. checkWindowAssociation();
  220418. }
  220419. bool WebBrowserComponent::pageAboutToLoad (const String& url)
  220420. {
  220421. return true;
  220422. }
  220423. #endif
  220424. /*** End of inlined file: juce_linux_WebBrowserComponent.cpp ***/
  220425. #endif
  220426. END_JUCE_NAMESPACE
  220427. #endif
  220428. /*** End of inlined file: juce_linux_NativeCode.cpp ***/
  220429. #endif
  220430. #if JUCE_MAC || JUCE_IPHONE
  220431. /*** Start of inlined file: juce_mac_NativeCode.mm ***/
  220432. /*
  220433. This file wraps together all the mac-specific code, so that
  220434. we can include all the native headers just once, and compile all our
  220435. platform-specific stuff in one big lump, keeping it out of the way of
  220436. the rest of the codebase.
  220437. */
  220438. #if JUCE_MAC || JUCE_IPHONE
  220439. BEGIN_JUCE_NAMESPACE
  220440. #undef Point
  220441. #define JUCE_INCLUDED_FILE 1
  220442. // Now include the actual code files..
  220443. /*** Start of inlined file: juce_mac_ObjCSuffix.h ***/
  220444. /** This suffix is used for naming all Obj-C classes that are used inside juce.
  220445. Because of the flat naming structure used by Obj-C, you can get horrible situations where
  220446. two DLLs are loaded into a host, each of which uses classes with the same names, and these get
  220447. cross-linked so that when you make a call to a class that you thought was private, it ends up
  220448. actually calling into a similarly named class in the other module's address space.
  220449. By changing this macro to a unique value, you ensure that all the obj-C classes in your app
  220450. have unique names, and should avoid this problem.
  220451. If you're using the amalgamated version, you can just set this macro to something unique before
  220452. you include juce_amalgamated.cpp.
  220453. */
  220454. #ifndef JUCE_ObjCExtraSuffix
  220455. #define JUCE_ObjCExtraSuffix 3
  220456. #endif
  220457. #define appendMacro1(a, b, c, d, e) a ## _ ## b ## _ ## c ## _ ## d ## _ ## e
  220458. #define appendMacro2(a, b, c, d, e) appendMacro1(a, b, c, d, e)
  220459. #define MakeObjCClassName(rootName) appendMacro2 (rootName, JUCE_MAJOR_VERSION, JUCE_MINOR_VERSION, JUCE_BUILDNUMBER, JUCE_ObjCExtraSuffix)
  220460. /*** End of inlined file: juce_mac_ObjCSuffix.h ***/
  220461. /*** Start of inlined file: juce_mac_Strings.mm ***/
  220462. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  220463. // compiled on its own).
  220464. #if JUCE_INCLUDED_FILE
  220465. static const String nsStringToJuce (NSString* s)
  220466. {
  220467. return String::fromUTF8 ([s UTF8String]);
  220468. }
  220469. static NSString* juceStringToNS (const String& s)
  220470. {
  220471. return [NSString stringWithUTF8String: s.toUTF8()];
  220472. }
  220473. static const String convertUTF16ToString (const UniChar* utf16)
  220474. {
  220475. String s;
  220476. while (*utf16 != 0)
  220477. s += (juce_wchar) *utf16++;
  220478. return s;
  220479. }
  220480. const String PlatformUtilities::cfStringToJuceString (CFStringRef cfString)
  220481. {
  220482. String result;
  220483. if (cfString != 0)
  220484. {
  220485. CFRange range = { 0, CFStringGetLength (cfString) };
  220486. HeapBlock <UniChar> u (range.length + 1);
  220487. CFStringGetCharacters (cfString, range, u);
  220488. u[range.length] = 0;
  220489. result = convertUTF16ToString (u);
  220490. }
  220491. return result;
  220492. }
  220493. CFStringRef PlatformUtilities::juceStringToCFString (const String& s)
  220494. {
  220495. const int len = s.length();
  220496. HeapBlock <UniChar> temp (len + 2);
  220497. for (int i = 0; i <= len; ++i)
  220498. temp[i] = s[i];
  220499. return CFStringCreateWithCharacters (kCFAllocatorDefault, temp, len);
  220500. }
  220501. const String PlatformUtilities::convertToPrecomposedUnicode (const String& s)
  220502. {
  220503. #if JUCE_IPHONE
  220504. const ScopedAutoReleasePool pool;
  220505. return nsStringToJuce ([juceStringToNS (s) precomposedStringWithCanonicalMapping]);
  220506. #else
  220507. UnicodeMapping map;
  220508. map.unicodeEncoding = CreateTextEncoding (kTextEncodingUnicodeDefault,
  220509. kUnicodeNoSubset,
  220510. kTextEncodingDefaultFormat);
  220511. map.otherEncoding = CreateTextEncoding (kTextEncodingUnicodeDefault,
  220512. kUnicodeCanonicalCompVariant,
  220513. kTextEncodingDefaultFormat);
  220514. map.mappingVersion = kUnicodeUseLatestMapping;
  220515. UnicodeToTextInfo conversionInfo = 0;
  220516. String result;
  220517. if (CreateUnicodeToTextInfo (&map, &conversionInfo) == noErr)
  220518. {
  220519. const int len = s.length();
  220520. HeapBlock <UniChar> tempIn, tempOut;
  220521. tempIn.calloc (len + 2);
  220522. tempOut.calloc (len + 2);
  220523. for (int i = 0; i <= len; ++i)
  220524. tempIn[i] = s[i];
  220525. ByteCount bytesRead = 0;
  220526. ByteCount outputBufferSize = 0;
  220527. if (ConvertFromUnicodeToText (conversionInfo,
  220528. len * sizeof (UniChar), tempIn,
  220529. kUnicodeDefaultDirectionMask,
  220530. 0, 0, 0, 0,
  220531. len * sizeof (UniChar), &bytesRead,
  220532. &outputBufferSize, tempOut) == noErr)
  220533. {
  220534. result.preallocateStorage (bytesRead / sizeof (UniChar) + 2);
  220535. juce_wchar* t = result;
  220536. unsigned int i;
  220537. for (i = 0; i < bytesRead / sizeof (UniChar); ++i)
  220538. t[i] = (juce_wchar) tempOut[i];
  220539. t[i] = 0;
  220540. }
  220541. DisposeUnicodeToTextInfo (&conversionInfo);
  220542. }
  220543. return result;
  220544. #endif
  220545. }
  220546. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  220547. void SystemClipboard::copyTextToClipboard (const String& text)
  220548. {
  220549. #if JUCE_IPHONE
  220550. [[UIPasteboard generalPasteboard] setValue: juceStringToNS (text)
  220551. forPasteboardType: @"public.text"];
  220552. #else
  220553. [[NSPasteboard generalPasteboard] declareTypes: [NSArray arrayWithObject: NSStringPboardType]
  220554. owner: nil];
  220555. [[NSPasteboard generalPasteboard] setString: juceStringToNS (text)
  220556. forType: NSStringPboardType];
  220557. #endif
  220558. }
  220559. const String SystemClipboard::getTextFromClipboard()
  220560. {
  220561. #if JUCE_IPHONE
  220562. NSString* text = [[UIPasteboard generalPasteboard] valueForPasteboardType: @"public.text"];
  220563. #else
  220564. NSString* text = [[NSPasteboard generalPasteboard] stringForType: NSStringPboardType];
  220565. #endif
  220566. return text == 0 ? String::empty
  220567. : nsStringToJuce (text);
  220568. }
  220569. #endif
  220570. #endif
  220571. /*** End of inlined file: juce_mac_Strings.mm ***/
  220572. /*** Start of inlined file: juce_mac_SystemStats.mm ***/
  220573. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  220574. // compiled on its own).
  220575. #if JUCE_INCLUDED_FILE
  220576. namespace SystemStatsHelpers
  220577. {
  220578. static int64 highResTimerFrequency = 0;
  220579. static double highResTimerToMillisecRatio = 0;
  220580. #if JUCE_INTEL
  220581. static void juce_getCpuVendor (char* const v) throw()
  220582. {
  220583. int vendor[4];
  220584. zerostruct (vendor);
  220585. int dummy = 0;
  220586. asm ("mov %%ebx, %%esi \n\t"
  220587. "cpuid \n\t"
  220588. "xchg %%esi, %%ebx"
  220589. : "=a" (dummy), "=S" (vendor[0]), "=c" (vendor[2]), "=d" (vendor[1]) : "a" (0));
  220590. memcpy (v, vendor, 16);
  220591. }
  220592. static unsigned int getCPUIDWord (unsigned int& familyModel, unsigned int& extFeatures)
  220593. {
  220594. unsigned int cpu = 0;
  220595. unsigned int ext = 0;
  220596. unsigned int family = 0;
  220597. unsigned int dummy = 0;
  220598. asm ("mov %%ebx, %%esi \n\t"
  220599. "cpuid \n\t"
  220600. "xchg %%esi, %%ebx"
  220601. : "=a" (family), "=S" (ext), "=c" (dummy), "=d" (cpu) : "a" (1));
  220602. familyModel = family;
  220603. extFeatures = ext;
  220604. return cpu;
  220605. }
  220606. struct CPUFlags
  220607. {
  220608. bool hasMMX : 1;
  220609. bool hasSSE : 1;
  220610. bool hasSSE2 : 1;
  220611. bool has3DNow : 1;
  220612. };
  220613. static CPUFlags cpuFlags;
  220614. #endif
  220615. }
  220616. void SystemStats::initialiseStats()
  220617. {
  220618. using namespace SystemStatsHelpers;
  220619. static bool initialised = false;
  220620. if (! initialised)
  220621. {
  220622. initialised = true;
  220623. #if JUCE_MAC
  220624. // extremely annoying: adding this line stops the apple menu items from working. Of
  220625. // course, not adding it means that carbon windows (e.g. in plugins) won't get
  220626. // any events.
  220627. //NSApplicationLoad();
  220628. [NSApplication sharedApplication];
  220629. #endif
  220630. #if JUCE_INTEL
  220631. {
  220632. unsigned int familyModel, extFeatures;
  220633. const unsigned int features = getCPUIDWord (familyModel, extFeatures);
  220634. cpuFlags.hasMMX = ((features & (1 << 23)) != 0);
  220635. cpuFlags.hasSSE = ((features & (1 << 25)) != 0);
  220636. cpuFlags.hasSSE2 = ((features & (1 << 26)) != 0);
  220637. cpuFlags.has3DNow = ((extFeatures & (1 << 31)) != 0);
  220638. }
  220639. #endif
  220640. mach_timebase_info_data_t timebase;
  220641. (void) mach_timebase_info (&timebase);
  220642. highResTimerFrequency = (int64) (1.0e9 * timebase.denom / timebase.numer);
  220643. highResTimerToMillisecRatio = timebase.numer / (1.0e6 * timebase.denom);
  220644. String s (SystemStats::getJUCEVersion());
  220645. rlimit lim;
  220646. getrlimit (RLIMIT_NOFILE, &lim);
  220647. lim.rlim_cur = lim.rlim_max = RLIM_INFINITY;
  220648. setrlimit (RLIMIT_NOFILE, &lim);
  220649. }
  220650. }
  220651. SystemStats::OperatingSystemType SystemStats::getOperatingSystemType()
  220652. {
  220653. return MacOSX;
  220654. }
  220655. const String SystemStats::getOperatingSystemName()
  220656. {
  220657. return "Mac OS X";
  220658. }
  220659. bool SystemStats::isOperatingSystem64Bit()
  220660. {
  220661. #if JUCE_64BIT
  220662. return true;
  220663. #else
  220664. //xxx not sure how to find this out?..
  220665. return false;
  220666. #endif
  220667. }
  220668. int SystemStats::getMemorySizeInMegabytes()
  220669. {
  220670. uint64 mem = 0;
  220671. size_t memSize = sizeof (mem);
  220672. int mib[] = { CTL_HW, HW_MEMSIZE };
  220673. sysctl (mib, 2, &mem, &memSize, 0, 0);
  220674. return (int) (mem / (1024 * 1024));
  220675. }
  220676. bool SystemStats::hasMMX()
  220677. {
  220678. #if JUCE_INTEL
  220679. return SystemStatsHelpers::cpuFlags.hasMMX;
  220680. #else
  220681. return false;
  220682. #endif
  220683. }
  220684. bool SystemStats::hasSSE()
  220685. {
  220686. #if JUCE_INTEL
  220687. return SystemStatsHelpers::cpuFlags.hasSSE;
  220688. #else
  220689. return false;
  220690. #endif
  220691. }
  220692. bool SystemStats::hasSSE2()
  220693. {
  220694. #if JUCE_INTEL
  220695. return SystemStatsHelpers::cpuFlags.hasSSE2;
  220696. #else
  220697. return false;
  220698. #endif
  220699. }
  220700. bool SystemStats::has3DNow()
  220701. {
  220702. #if JUCE_INTEL
  220703. return SystemStatsHelpers::cpuFlags.has3DNow;
  220704. #else
  220705. return false;
  220706. #endif
  220707. }
  220708. const String SystemStats::getCpuVendor()
  220709. {
  220710. #if JUCE_INTEL
  220711. char v [16];
  220712. SystemStatsHelpers::juce_getCpuVendor (v);
  220713. return String (v, 16);
  220714. #else
  220715. return String::empty;
  220716. #endif
  220717. }
  220718. int SystemStats::getCpuSpeedInMegaherz()
  220719. {
  220720. uint64 speedHz = 0;
  220721. size_t speedSize = sizeof (speedHz);
  220722. int mib[] = { CTL_HW, HW_CPU_FREQ };
  220723. sysctl (mib, 2, &speedHz, &speedSize, 0, 0);
  220724. #if JUCE_BIG_ENDIAN
  220725. if (speedSize == 4)
  220726. speedHz >>= 32;
  220727. #endif
  220728. return (int) (speedHz / 1000000);
  220729. }
  220730. int SystemStats::getNumCpus()
  220731. {
  220732. #if JUCE_IPHONE || (MAC_OS_X_VERSION_MIN_REQUIRED >= MAC_OS_X_VERSION_10_5)
  220733. return (int) [[NSProcessInfo processInfo] activeProcessorCount];
  220734. #else
  220735. return MPProcessors();
  220736. #endif
  220737. }
  220738. const String SystemStats::getLogonName()
  220739. {
  220740. return nsStringToJuce (NSUserName());
  220741. }
  220742. const String SystemStats::getFullUserName()
  220743. {
  220744. return nsStringToJuce (NSFullUserName());
  220745. }
  220746. uint32 juce_millisecondsSinceStartup() throw()
  220747. {
  220748. return (uint32) (mach_absolute_time() * SystemStatsHelpers::highResTimerToMillisecRatio);
  220749. }
  220750. double Time::getMillisecondCounterHiRes() throw()
  220751. {
  220752. return mach_absolute_time() * SystemStatsHelpers::highResTimerToMillisecRatio;
  220753. }
  220754. int64 Time::getHighResolutionTicks() throw()
  220755. {
  220756. return (int64) mach_absolute_time();
  220757. }
  220758. int64 Time::getHighResolutionTicksPerSecond() throw()
  220759. {
  220760. return SystemStatsHelpers::highResTimerFrequency;
  220761. }
  220762. bool Time::setSystemTimeToThisTime() const
  220763. {
  220764. jassertfalse
  220765. return false;
  220766. }
  220767. int SystemStats::getPageSize()
  220768. {
  220769. return (int) NSPageSize();
  220770. }
  220771. void PlatformUtilities::fpuReset()
  220772. {
  220773. }
  220774. #endif
  220775. /*** End of inlined file: juce_mac_SystemStats.mm ***/
  220776. /*** Start of inlined file: juce_mac_Network.mm ***/
  220777. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  220778. // compiled on its own).
  220779. #if JUCE_INCLUDED_FILE
  220780. int SystemStats::getMACAddresses (int64* addresses, int maxNum, const bool littleEndian)
  220781. {
  220782. #ifndef IFT_ETHER
  220783. #define IFT_ETHER 6
  220784. #endif
  220785. ifaddrs* addrs = 0;
  220786. int numResults = 0;
  220787. if (getifaddrs (&addrs) == 0)
  220788. {
  220789. const ifaddrs* cursor = addrs;
  220790. while (cursor != 0 && numResults < maxNum)
  220791. {
  220792. sockaddr_storage* sto = (sockaddr_storage*) cursor->ifa_addr;
  220793. if (sto->ss_family == AF_LINK)
  220794. {
  220795. const sockaddr_dl* const sadd = (const sockaddr_dl*) cursor->ifa_addr;
  220796. if (sadd->sdl_type == IFT_ETHER)
  220797. {
  220798. const uint8* const addr = ((const uint8*) sadd->sdl_data) + sadd->sdl_nlen;
  220799. uint64 a = 0;
  220800. for (int i = 6; --i >= 0;)
  220801. a = (a << 8) | addr [littleEndian ? i : (5 - i)];
  220802. *addresses++ = (int64) a;
  220803. ++numResults;
  220804. }
  220805. }
  220806. cursor = cursor->ifa_next;
  220807. }
  220808. freeifaddrs (addrs);
  220809. }
  220810. return numResults;
  220811. }
  220812. bool PlatformUtilities::launchEmailWithAttachments (const String& targetEmailAddress,
  220813. const String& emailSubject,
  220814. const String& bodyText,
  220815. const StringArray& filesToAttach)
  220816. {
  220817. #if JUCE_IPHONE
  220818. //xxx probably need to use MFMailComposeViewController
  220819. jassertfalse
  220820. return false;
  220821. #else
  220822. const ScopedAutoReleasePool pool;
  220823. String script;
  220824. script << "tell application \"Mail\"\r\n"
  220825. "set newMessage to make new outgoing message with properties {subject:\""
  220826. << emailSubject.replace ("\"", "\\\"")
  220827. << "\", content:\""
  220828. << bodyText.replace ("\"", "\\\"")
  220829. << "\" & return & return}\r\n"
  220830. "tell newMessage\r\n"
  220831. "set visible to true\r\n"
  220832. "set sender to \"sdfsdfsdfewf\"\r\n"
  220833. "make new to recipient at end of to recipients with properties {address:\""
  220834. << targetEmailAddress
  220835. << "\"}\r\n";
  220836. for (int i = 0; i < filesToAttach.size(); ++i)
  220837. {
  220838. script << "tell content\r\n"
  220839. "make new attachment with properties {file name:\""
  220840. << filesToAttach[i].replace ("\"", "\\\"")
  220841. << "\"} at after the last paragraph\r\n"
  220842. "end tell\r\n";
  220843. }
  220844. script << "end tell\r\n"
  220845. "end tell\r\n";
  220846. NSAppleScript* s = [[NSAppleScript alloc]
  220847. initWithSource: juceStringToNS (script)];
  220848. NSDictionary* error = 0;
  220849. const bool ok = [s executeAndReturnError: &error] != nil;
  220850. [s release];
  220851. return ok;
  220852. #endif
  220853. }
  220854. END_JUCE_NAMESPACE
  220855. using namespace JUCE_NAMESPACE;
  220856. #define JuceURLConnection MakeObjCClassName(JuceURLConnection)
  220857. @interface JuceURLConnection : NSObject
  220858. {
  220859. @public
  220860. NSURLRequest* request;
  220861. NSURLConnection* connection;
  220862. NSMutableData* data;
  220863. Thread* runLoopThread;
  220864. bool initialised, hasFailed, hasFinished;
  220865. int position;
  220866. int64 contentLength;
  220867. NSLock* dataLock;
  220868. }
  220869. - (JuceURLConnection*) initWithRequest: (NSURLRequest*) req withCallback: (URL::OpenStreamProgressCallback*) callback withContext: (void*) context;
  220870. - (void) dealloc;
  220871. - (void) connection: (NSURLConnection*) connection didReceiveResponse: (NSURLResponse*) response;
  220872. - (void) connection: (NSURLConnection*) connection didFailWithError: (NSError*) error;
  220873. - (void) connection: (NSURLConnection*) connection didReceiveData: (NSData*) data;
  220874. - (void) connectionDidFinishLoading: (NSURLConnection*) connection;
  220875. - (BOOL) isOpen;
  220876. - (int) read: (char*) dest numBytes: (int) num;
  220877. - (int) readPosition;
  220878. - (void) stop;
  220879. - (void) createConnection;
  220880. @end
  220881. class JuceURLConnectionMessageThread : public Thread
  220882. {
  220883. JuceURLConnection* owner;
  220884. public:
  220885. JuceURLConnectionMessageThread (JuceURLConnection* owner_)
  220886. : Thread ("http connection"),
  220887. owner (owner_)
  220888. {
  220889. }
  220890. ~JuceURLConnectionMessageThread()
  220891. {
  220892. stopThread (10000);
  220893. }
  220894. void run()
  220895. {
  220896. [owner createConnection];
  220897. while (! threadShouldExit())
  220898. {
  220899. const ScopedAutoReleasePool pool;
  220900. [[NSRunLoop currentRunLoop] runUntilDate: [NSDate dateWithTimeIntervalSinceNow: 0.01]];
  220901. }
  220902. }
  220903. };
  220904. @implementation JuceURLConnection
  220905. - (JuceURLConnection*) initWithRequest: (NSURLRequest*) req
  220906. withCallback: (URL::OpenStreamProgressCallback*) callback
  220907. withContext: (void*) context;
  220908. {
  220909. [super init];
  220910. request = req;
  220911. [request retain];
  220912. data = [[NSMutableData data] retain];
  220913. dataLock = [[NSLock alloc] init];
  220914. connection = 0;
  220915. initialised = false;
  220916. hasFailed = false;
  220917. hasFinished = false;
  220918. contentLength = -1;
  220919. runLoopThread = new JuceURLConnectionMessageThread (self);
  220920. runLoopThread->startThread();
  220921. while (runLoopThread->isThreadRunning() && ! initialised)
  220922. {
  220923. if (callback != 0)
  220924. callback (context, -1, (int) [[request HTTPBody] length]);
  220925. Thread::sleep (1);
  220926. }
  220927. return self;
  220928. }
  220929. - (void) dealloc
  220930. {
  220931. [self stop];
  220932. deleteAndZero (runLoopThread);
  220933. [connection release];
  220934. [data release];
  220935. [dataLock release];
  220936. [request release];
  220937. [super dealloc];
  220938. }
  220939. - (void) createConnection
  220940. {
  220941. connection = [[NSURLConnection alloc] initWithRequest: request
  220942. delegate: [self retain]];
  220943. if (connection == nil)
  220944. runLoopThread->signalThreadShouldExit();
  220945. }
  220946. - (void) connection: (NSURLConnection*) conn didReceiveResponse: (NSURLResponse*) response
  220947. {
  220948. (void) conn;
  220949. [dataLock lock];
  220950. [data setLength: 0];
  220951. [dataLock unlock];
  220952. initialised = true;
  220953. contentLength = [response expectedContentLength];
  220954. }
  220955. - (void) connection: (NSURLConnection*) conn didFailWithError: (NSError*) error
  220956. {
  220957. (void) conn;
  220958. DBG (nsStringToJuce ([error description]));
  220959. hasFailed = true;
  220960. initialised = true;
  220961. if (runLoopThread != 0)
  220962. runLoopThread->signalThreadShouldExit();
  220963. }
  220964. - (void) connection: (NSURLConnection*) conn didReceiveData: (NSData*) newData
  220965. {
  220966. (void) conn;
  220967. [dataLock lock];
  220968. [data appendData: newData];
  220969. [dataLock unlock];
  220970. initialised = true;
  220971. }
  220972. - (void) connectionDidFinishLoading: (NSURLConnection*) conn
  220973. {
  220974. (void) conn;
  220975. hasFinished = true;
  220976. initialised = true;
  220977. if (runLoopThread != 0)
  220978. runLoopThread->signalThreadShouldExit();
  220979. }
  220980. - (BOOL) isOpen
  220981. {
  220982. return connection != 0 && ! hasFailed;
  220983. }
  220984. - (int) readPosition
  220985. {
  220986. return position;
  220987. }
  220988. - (int) read: (char*) dest numBytes: (int) numNeeded
  220989. {
  220990. int numDone = 0;
  220991. while (numNeeded > 0)
  220992. {
  220993. int available = jmin (numNeeded, (int) [data length]);
  220994. if (available > 0)
  220995. {
  220996. [dataLock lock];
  220997. [data getBytes: dest length: available];
  220998. [data replaceBytesInRange: NSMakeRange (0, available) withBytes: nil length: 0];
  220999. [dataLock unlock];
  221000. numDone += available;
  221001. numNeeded -= available;
  221002. dest += available;
  221003. }
  221004. else
  221005. {
  221006. if (hasFailed || hasFinished)
  221007. break;
  221008. Thread::sleep (1);
  221009. }
  221010. }
  221011. position += numDone;
  221012. return numDone;
  221013. }
  221014. - (void) stop
  221015. {
  221016. [connection cancel];
  221017. if (runLoopThread != 0)
  221018. runLoopThread->stopThread (10000);
  221019. }
  221020. @end
  221021. BEGIN_JUCE_NAMESPACE
  221022. void* juce_openInternetFile (const String& url,
  221023. const String& headers,
  221024. const MemoryBlock& postData,
  221025. const bool isPost,
  221026. URL::OpenStreamProgressCallback* callback,
  221027. void* callbackContext,
  221028. int timeOutMs)
  221029. {
  221030. const ScopedAutoReleasePool pool;
  221031. NSMutableURLRequest* req = [NSMutableURLRequest
  221032. requestWithURL: [NSURL URLWithString: juceStringToNS (url)]
  221033. cachePolicy: NSURLRequestUseProtocolCachePolicy
  221034. timeoutInterval: timeOutMs <= 0 ? 60.0 : (timeOutMs / 1000.0)];
  221035. if (req == nil)
  221036. return 0;
  221037. [req setHTTPMethod: isPost ? @"POST" : @"GET"];
  221038. //[req setCachePolicy: NSURLRequestReloadIgnoringLocalAndRemoteCacheData];
  221039. StringArray headerLines;
  221040. headerLines.addLines (headers);
  221041. headerLines.removeEmptyStrings (true);
  221042. for (int i = 0; i < headerLines.size(); ++i)
  221043. {
  221044. const String key (headerLines[i].upToFirstOccurrenceOf (":", false, false).trim());
  221045. const String value (headerLines[i].fromFirstOccurrenceOf (":", false, false).trim());
  221046. if (key.isNotEmpty() && value.isNotEmpty())
  221047. [req addValue: juceStringToNS (value) forHTTPHeaderField: juceStringToNS (key)];
  221048. }
  221049. if (isPost && postData.getSize() > 0)
  221050. {
  221051. [req setHTTPBody: [NSData dataWithBytes: postData.getData()
  221052. length: postData.getSize()]];
  221053. }
  221054. JuceURLConnection* const s = [[JuceURLConnection alloc] initWithRequest: req
  221055. withCallback: callback
  221056. withContext: callbackContext];
  221057. if ([s isOpen])
  221058. return s;
  221059. [s release];
  221060. return 0;
  221061. }
  221062. void juce_closeInternetFile (void* handle)
  221063. {
  221064. JuceURLConnection* const s = (JuceURLConnection*) handle;
  221065. if (s != 0)
  221066. {
  221067. const ScopedAutoReleasePool pool;
  221068. [s stop];
  221069. [s release];
  221070. }
  221071. }
  221072. int juce_readFromInternetFile (void* handle, void* buffer, int bytesToRead)
  221073. {
  221074. JuceURLConnection* const s = (JuceURLConnection*) handle;
  221075. if (s != 0)
  221076. {
  221077. const ScopedAutoReleasePool pool;
  221078. return [s read: (char*) buffer numBytes: bytesToRead];
  221079. }
  221080. return 0;
  221081. }
  221082. int64 juce_getInternetFileContentLength (void* handle)
  221083. {
  221084. JuceURLConnection* const s = (JuceURLConnection*) handle;
  221085. if (s != 0)
  221086. return s->contentLength;
  221087. return -1;
  221088. }
  221089. int juce_seekInInternetFile (void* handle, int /*newPosition*/)
  221090. {
  221091. JuceURLConnection* const s = (JuceURLConnection*) handle;
  221092. if (s != 0)
  221093. return [s readPosition];
  221094. return 0;
  221095. }
  221096. #endif
  221097. /*** End of inlined file: juce_mac_Network.mm ***/
  221098. /*** Start of inlined file: juce_posix_NamedPipe.cpp ***/
  221099. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  221100. // compiled on its own).
  221101. #if JUCE_INCLUDED_FILE
  221102. struct NamedPipeInternal
  221103. {
  221104. String pipeInName, pipeOutName;
  221105. int pipeIn, pipeOut;
  221106. bool volatile createdPipe, blocked, stopReadOperation;
  221107. static void signalHandler (int) {}
  221108. };
  221109. void NamedPipe::cancelPendingReads()
  221110. {
  221111. while (internal != 0 && ((NamedPipeInternal*) internal)->blocked)
  221112. {
  221113. NamedPipeInternal* const intern = (NamedPipeInternal*) internal;
  221114. intern->stopReadOperation = true;
  221115. char buffer [1] = { 0 };
  221116. int bytesWritten = (int) ::write (intern->pipeIn, buffer, 1);
  221117. (void) bytesWritten;
  221118. int timeout = 2000;
  221119. while (intern->blocked && --timeout >= 0)
  221120. Thread::sleep (2);
  221121. intern->stopReadOperation = false;
  221122. }
  221123. }
  221124. void NamedPipe::close()
  221125. {
  221126. NamedPipeInternal* const intern = (NamedPipeInternal*) internal;
  221127. if (intern != 0)
  221128. {
  221129. internal = 0;
  221130. if (intern->pipeIn != -1)
  221131. ::close (intern->pipeIn);
  221132. if (intern->pipeOut != -1)
  221133. ::close (intern->pipeOut);
  221134. if (intern->createdPipe)
  221135. {
  221136. unlink (intern->pipeInName.toUTF8());
  221137. unlink (intern->pipeOutName.toUTF8());
  221138. }
  221139. delete intern;
  221140. }
  221141. }
  221142. bool NamedPipe::openInternal (const String& pipeName, const bool createPipe)
  221143. {
  221144. close();
  221145. NamedPipeInternal* const intern = new NamedPipeInternal();
  221146. internal = intern;
  221147. intern->createdPipe = createPipe;
  221148. intern->blocked = false;
  221149. intern->stopReadOperation = false;
  221150. signal (SIGPIPE, NamedPipeInternal::signalHandler);
  221151. siginterrupt (SIGPIPE, 1);
  221152. const String pipePath ("/tmp/" + File::createLegalFileName (pipeName));
  221153. intern->pipeInName = pipePath + "_in";
  221154. intern->pipeOutName = pipePath + "_out";
  221155. intern->pipeIn = -1;
  221156. intern->pipeOut = -1;
  221157. if (createPipe)
  221158. {
  221159. if ((mkfifo (intern->pipeInName.toUTF8(), 0666) && errno != EEXIST)
  221160. || (mkfifo (intern->pipeOutName.toUTF8(), 0666) && errno != EEXIST))
  221161. {
  221162. delete intern;
  221163. internal = 0;
  221164. return false;
  221165. }
  221166. }
  221167. return true;
  221168. }
  221169. int NamedPipe::read (void* destBuffer, int maxBytesToRead, int /*timeOutMilliseconds*/)
  221170. {
  221171. int bytesRead = -1;
  221172. NamedPipeInternal* const intern = (NamedPipeInternal*) internal;
  221173. if (intern != 0)
  221174. {
  221175. intern->blocked = true;
  221176. if (intern->pipeIn == -1)
  221177. {
  221178. if (intern->createdPipe)
  221179. intern->pipeIn = ::open (intern->pipeInName.toUTF8(), O_RDWR);
  221180. else
  221181. intern->pipeIn = ::open (intern->pipeOutName.toUTF8(), O_RDWR);
  221182. if (intern->pipeIn == -1)
  221183. {
  221184. intern->blocked = false;
  221185. return -1;
  221186. }
  221187. }
  221188. bytesRead = 0;
  221189. char* p = (char*) destBuffer;
  221190. while (bytesRead < maxBytesToRead)
  221191. {
  221192. const int bytesThisTime = maxBytesToRead - bytesRead;
  221193. const int numRead = (int) ::read (intern->pipeIn, p, bytesThisTime);
  221194. if (numRead <= 0 || intern->stopReadOperation)
  221195. {
  221196. bytesRead = -1;
  221197. break;
  221198. }
  221199. bytesRead += numRead;
  221200. p += bytesRead;
  221201. }
  221202. intern->blocked = false;
  221203. }
  221204. return bytesRead;
  221205. }
  221206. int NamedPipe::write (const void* sourceBuffer, int numBytesToWrite, int timeOutMilliseconds)
  221207. {
  221208. int bytesWritten = -1;
  221209. NamedPipeInternal* const intern = (NamedPipeInternal*) internal;
  221210. if (intern != 0)
  221211. {
  221212. if (intern->pipeOut == -1)
  221213. {
  221214. if (intern->createdPipe)
  221215. intern->pipeOut = ::open (intern->pipeOutName.toUTF8(), O_WRONLY);
  221216. else
  221217. intern->pipeOut = ::open (intern->pipeInName.toUTF8(), O_WRONLY);
  221218. if (intern->pipeOut == -1)
  221219. {
  221220. return -1;
  221221. }
  221222. }
  221223. const char* p = (const char*) sourceBuffer;
  221224. bytesWritten = 0;
  221225. const uint32 timeOutTime = Time::getMillisecondCounter() + timeOutMilliseconds;
  221226. while (bytesWritten < numBytesToWrite
  221227. && (timeOutMilliseconds < 0 || Time::getMillisecondCounter() < timeOutTime))
  221228. {
  221229. const int bytesThisTime = numBytesToWrite - bytesWritten;
  221230. const int numWritten = (int) ::write (intern->pipeOut, p, bytesThisTime);
  221231. if (numWritten <= 0)
  221232. {
  221233. bytesWritten = -1;
  221234. break;
  221235. }
  221236. bytesWritten += numWritten;
  221237. p += bytesWritten;
  221238. }
  221239. }
  221240. return bytesWritten;
  221241. }
  221242. #endif
  221243. /*** End of inlined file: juce_posix_NamedPipe.cpp ***/
  221244. /*** Start of inlined file: juce_mac_Threads.mm ***/
  221245. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  221246. // compiled on its own).
  221247. #if JUCE_INCLUDED_FILE
  221248. /*
  221249. Note that a lot of methods that you'd expect to find in this file actually
  221250. live in juce_posix_SharedCode.h!
  221251. */
  221252. void JUCE_API juce_threadEntryPoint (void*);
  221253. void* threadEntryProc (void* userData)
  221254. {
  221255. const ScopedAutoReleasePool pool;
  221256. juce_threadEntryPoint (userData);
  221257. return 0;
  221258. }
  221259. void* juce_createThread (void* userData)
  221260. {
  221261. pthread_t handle = 0;
  221262. if (pthread_create (&handle, 0, threadEntryProc, userData) == 0)
  221263. {
  221264. pthread_detach (handle);
  221265. return (void*) handle;
  221266. }
  221267. return 0;
  221268. }
  221269. void juce_killThread (void* handle)
  221270. {
  221271. if (handle != 0)
  221272. pthread_cancel ((pthread_t) handle);
  221273. }
  221274. void juce_setCurrentThreadName (const String& /*name*/)
  221275. {
  221276. }
  221277. bool juce_setThreadPriority (void* handle, int priority)
  221278. {
  221279. if (handle == 0)
  221280. handle = (void*) pthread_self();
  221281. struct sched_param param;
  221282. int policy;
  221283. pthread_getschedparam ((pthread_t) handle, &policy, &param);
  221284. param.sched_priority = jlimit (1, 127, 1 + (priority * 126) / 11);
  221285. return pthread_setschedparam ((pthread_t) handle, policy, &param) == 0;
  221286. }
  221287. Thread::ThreadID Thread::getCurrentThreadId()
  221288. {
  221289. return static_cast <ThreadID> (pthread_self());
  221290. }
  221291. void Thread::yield()
  221292. {
  221293. sched_yield();
  221294. }
  221295. void Thread::setCurrentThreadAffinityMask (const uint32 /*affinityMask*/)
  221296. {
  221297. // xxx
  221298. jassertfalse
  221299. }
  221300. bool Process::isForegroundProcess()
  221301. {
  221302. #if JUCE_MAC
  221303. return [NSApp isActive];
  221304. #else
  221305. return true; // xxx change this if more than one app is ever possible on the iPhone!
  221306. #endif
  221307. }
  221308. void Process::raisePrivilege()
  221309. {
  221310. jassertfalse
  221311. }
  221312. void Process::lowerPrivilege()
  221313. {
  221314. jassertfalse
  221315. }
  221316. void Process::terminate()
  221317. {
  221318. exit (0);
  221319. }
  221320. void Process::setPriority (ProcessPriority)
  221321. {
  221322. // xxx
  221323. }
  221324. #endif
  221325. /*** End of inlined file: juce_mac_Threads.mm ***/
  221326. /*** Start of inlined file: juce_posix_SharedCode.h ***/
  221327. /*
  221328. This file contains posix routines that are common to both the Linux and Mac builds.
  221329. It gets included directly in the cpp files for these platforms.
  221330. */
  221331. CriticalSection::CriticalSection() throw()
  221332. {
  221333. pthread_mutexattr_t atts;
  221334. pthread_mutexattr_init (&atts);
  221335. pthread_mutexattr_settype (&atts, PTHREAD_MUTEX_RECURSIVE);
  221336. pthread_mutex_init (&internal, &atts);
  221337. }
  221338. CriticalSection::~CriticalSection() throw()
  221339. {
  221340. pthread_mutex_destroy (&internal);
  221341. }
  221342. void CriticalSection::enter() const throw()
  221343. {
  221344. pthread_mutex_lock (&internal);
  221345. }
  221346. bool CriticalSection::tryEnter() const throw()
  221347. {
  221348. return pthread_mutex_trylock (&internal) == 0;
  221349. }
  221350. void CriticalSection::exit() const throw()
  221351. {
  221352. pthread_mutex_unlock (&internal);
  221353. }
  221354. class WaitableEventImpl
  221355. {
  221356. public:
  221357. WaitableEventImpl (const bool manualReset_)
  221358. : triggered (false),
  221359. manualReset (manualReset_)
  221360. {
  221361. pthread_cond_init (&condition, 0);
  221362. pthread_mutex_init (&mutex, 0);
  221363. }
  221364. ~WaitableEventImpl()
  221365. {
  221366. pthread_cond_destroy (&condition);
  221367. pthread_mutex_destroy (&mutex);
  221368. }
  221369. bool wait (const int timeOutMillisecs) throw()
  221370. {
  221371. pthread_mutex_lock (&mutex);
  221372. if (! triggered)
  221373. {
  221374. if (timeOutMillisecs < 0)
  221375. {
  221376. do
  221377. {
  221378. pthread_cond_wait (&condition, &mutex);
  221379. }
  221380. while (! triggered);
  221381. }
  221382. else
  221383. {
  221384. struct timeval now;
  221385. gettimeofday (&now, 0);
  221386. struct timespec time;
  221387. time.tv_sec = now.tv_sec + (timeOutMillisecs / 1000);
  221388. time.tv_nsec = (now.tv_usec + ((timeOutMillisecs % 1000) * 1000)) * 1000;
  221389. if (time.tv_nsec >= 1000000000)
  221390. {
  221391. time.tv_nsec -= 1000000000;
  221392. time.tv_sec++;
  221393. }
  221394. do
  221395. {
  221396. if (pthread_cond_timedwait (&condition, &mutex, &time) == ETIMEDOUT)
  221397. {
  221398. pthread_mutex_unlock (&mutex);
  221399. return false;
  221400. }
  221401. }
  221402. while (! triggered);
  221403. }
  221404. }
  221405. if (! manualReset)
  221406. triggered = false;
  221407. pthread_mutex_unlock (&mutex);
  221408. return true;
  221409. }
  221410. void signal() throw()
  221411. {
  221412. pthread_mutex_lock (&mutex);
  221413. triggered = true;
  221414. pthread_cond_broadcast (&condition);
  221415. pthread_mutex_unlock (&mutex);
  221416. }
  221417. void reset() throw()
  221418. {
  221419. pthread_mutex_lock (&mutex);
  221420. triggered = false;
  221421. pthread_mutex_unlock (&mutex);
  221422. }
  221423. private:
  221424. pthread_cond_t condition;
  221425. pthread_mutex_t mutex;
  221426. bool triggered;
  221427. const bool manualReset;
  221428. WaitableEventImpl (const WaitableEventImpl&);
  221429. WaitableEventImpl& operator= (const WaitableEventImpl&);
  221430. };
  221431. WaitableEvent::WaitableEvent (const bool manualReset) throw()
  221432. : internal (new WaitableEventImpl (manualReset))
  221433. {
  221434. }
  221435. WaitableEvent::~WaitableEvent() throw()
  221436. {
  221437. delete static_cast <WaitableEventImpl*> (internal);
  221438. }
  221439. bool WaitableEvent::wait (const int timeOutMillisecs) const throw()
  221440. {
  221441. return static_cast <WaitableEventImpl*> (internal)->wait (timeOutMillisecs);
  221442. }
  221443. void WaitableEvent::signal() const throw()
  221444. {
  221445. static_cast <WaitableEventImpl*> (internal)->signal();
  221446. }
  221447. void WaitableEvent::reset() const throw()
  221448. {
  221449. static_cast <WaitableEventImpl*> (internal)->reset();
  221450. }
  221451. void JUCE_CALLTYPE Thread::sleep (int millisecs)
  221452. {
  221453. struct timespec time;
  221454. time.tv_sec = millisecs / 1000;
  221455. time.tv_nsec = (millisecs % 1000) * 1000000;
  221456. nanosleep (&time, 0);
  221457. }
  221458. const juce_wchar File::separator = '/';
  221459. const String File::separatorString ("/");
  221460. const File File::getCurrentWorkingDirectory()
  221461. {
  221462. HeapBlock<char> heapBuffer;
  221463. char localBuffer [1024];
  221464. char* cwd = getcwd (localBuffer, sizeof (localBuffer) - 1);
  221465. int bufferSize = 4096;
  221466. while (cwd == 0 && errno == ERANGE)
  221467. {
  221468. heapBuffer.malloc (bufferSize);
  221469. cwd = getcwd (heapBuffer, bufferSize - 1);
  221470. bufferSize += 1024;
  221471. }
  221472. return File (String::fromUTF8 (cwd));
  221473. }
  221474. bool File::setAsCurrentWorkingDirectory() const
  221475. {
  221476. return chdir (getFullPathName().toUTF8()) == 0;
  221477. }
  221478. static bool juce_stat (const String& fileName, struct stat& info)
  221479. {
  221480. return fileName.isNotEmpty()
  221481. && (stat (fileName.toUTF8(), &info) == 0);
  221482. }
  221483. bool File::isDirectory() const
  221484. {
  221485. struct stat info;
  221486. return fullPath.isEmpty()
  221487. || (juce_stat (fullPath, info) && ((info.st_mode & S_IFDIR) != 0));
  221488. }
  221489. bool File::exists() const
  221490. {
  221491. return fullPath.isNotEmpty()
  221492. && access (fullPath.toUTF8(), F_OK) == 0;
  221493. }
  221494. bool File::existsAsFile() const
  221495. {
  221496. return exists() && ! isDirectory();
  221497. }
  221498. int64 File::getSize() const
  221499. {
  221500. struct stat info;
  221501. return juce_stat (fullPath, info) ? info.st_size : 0;
  221502. }
  221503. bool File::hasWriteAccess() const
  221504. {
  221505. if (exists())
  221506. return access (fullPath.toUTF8(), W_OK) == 0;
  221507. if ((! isDirectory()) && fullPath.containsChar (separator))
  221508. return getParentDirectory().hasWriteAccess();
  221509. return false;
  221510. }
  221511. bool File::setFileReadOnlyInternal (const bool shouldBeReadOnly) const
  221512. {
  221513. struct stat info;
  221514. const int res = stat (fullPath.toUTF8(), &info);
  221515. if (res != 0)
  221516. return false;
  221517. info.st_mode &= 0777; // Just permissions
  221518. if (shouldBeReadOnly)
  221519. info.st_mode &= ~(S_IWUSR | S_IWGRP | S_IWOTH);
  221520. else
  221521. // Give everybody write permission?
  221522. info.st_mode |= S_IWUSR | S_IWGRP | S_IWOTH;
  221523. return chmod (fullPath.toUTF8(), info.st_mode) == 0;
  221524. }
  221525. void File::getFileTimesInternal (int64& modificationTime, int64& accessTime, int64& creationTime) const
  221526. {
  221527. modificationTime = 0;
  221528. accessTime = 0;
  221529. creationTime = 0;
  221530. struct stat info;
  221531. const int res = stat (fullPath.toUTF8(), &info);
  221532. if (res == 0)
  221533. {
  221534. modificationTime = (int64) info.st_mtime * 1000;
  221535. accessTime = (int64) info.st_atime * 1000;
  221536. creationTime = (int64) info.st_ctime * 1000;
  221537. }
  221538. }
  221539. bool File::setFileTimesInternal (int64 modificationTime, int64 accessTime, int64 /*creationTime*/) const
  221540. {
  221541. struct utimbuf times;
  221542. times.actime = (time_t) (accessTime / 1000);
  221543. times.modtime = (time_t) (modificationTime / 1000);
  221544. return utime (fullPath.toUTF8(), &times) == 0;
  221545. }
  221546. bool File::deleteFile() const
  221547. {
  221548. if (! exists())
  221549. return true;
  221550. else if (isDirectory())
  221551. return rmdir (fullPath.toUTF8()) == 0;
  221552. else
  221553. return remove (fullPath.toUTF8()) == 0;
  221554. }
  221555. bool File::moveInternal (const File& dest) const
  221556. {
  221557. if (rename (fullPath.toUTF8(), dest.getFullPathName().toUTF8()) == 0)
  221558. return true;
  221559. if (hasWriteAccess() && copyInternal (dest))
  221560. {
  221561. if (deleteFile())
  221562. return true;
  221563. dest.deleteFile();
  221564. }
  221565. return false;
  221566. }
  221567. void File::createDirectoryInternal (const String& fileName) const
  221568. {
  221569. mkdir (fileName.toUTF8(), 0777);
  221570. }
  221571. void* juce_fileOpen (const File& file, bool forWriting)
  221572. {
  221573. int flags = O_RDONLY;
  221574. if (forWriting)
  221575. {
  221576. if (file.exists())
  221577. {
  221578. const int f = open (file.getFullPathName().toUTF8(), O_RDWR, 00644);
  221579. if (f != -1)
  221580. lseek (f, 0, SEEK_END);
  221581. return (void*) f;
  221582. }
  221583. else
  221584. {
  221585. flags = O_RDWR + O_CREAT;
  221586. }
  221587. }
  221588. return (void*) open (file.getFullPathName().toUTF8(), flags, 00644);
  221589. }
  221590. void juce_fileClose (void* handle)
  221591. {
  221592. if (handle != 0)
  221593. close ((int) (pointer_sized_int) handle);
  221594. }
  221595. int juce_fileRead (void* handle, void* buffer, int size)
  221596. {
  221597. if (handle != 0)
  221598. return jmax (0, (int) read ((int) (pointer_sized_int) handle, buffer, size));
  221599. return 0;
  221600. }
  221601. int juce_fileWrite (void* handle, const void* buffer, int size)
  221602. {
  221603. if (handle != 0)
  221604. return (int) write ((int) (pointer_sized_int) handle, buffer, size);
  221605. return 0;
  221606. }
  221607. int64 juce_fileSetPosition (void* handle, int64 pos)
  221608. {
  221609. if (handle != 0 && lseek ((int) (pointer_sized_int) handle, pos, SEEK_SET) == pos)
  221610. return pos;
  221611. return -1;
  221612. }
  221613. int64 FileOutputStream::getPositionInternal() const
  221614. {
  221615. if (fileHandle != 0)
  221616. return lseek ((int) (pointer_sized_int) fileHandle, 0, SEEK_CUR);
  221617. return -1;
  221618. }
  221619. void FileOutputStream::flushInternal()
  221620. {
  221621. if (fileHandle != 0)
  221622. fsync ((int) (pointer_sized_int) fileHandle);
  221623. }
  221624. const File juce_getExecutableFile()
  221625. {
  221626. Dl_info exeInfo;
  221627. dladdr ((const void*) juce_getExecutableFile, &exeInfo);
  221628. return File::getCurrentWorkingDirectory().getChildFile (String::fromUTF8 (exeInfo.dli_fname));
  221629. }
  221630. // if this file doesn't exist, find a parent of it that does..
  221631. static bool juce_doStatFS (File f, struct statfs& result)
  221632. {
  221633. for (int i = 5; --i >= 0;)
  221634. {
  221635. if (f.exists())
  221636. break;
  221637. f = f.getParentDirectory();
  221638. }
  221639. return statfs (f.getFullPathName().toUTF8(), &result) == 0;
  221640. }
  221641. int64 File::getBytesFreeOnVolume() const
  221642. {
  221643. struct statfs buf;
  221644. if (juce_doStatFS (*this, buf))
  221645. return (int64) buf.f_bsize * (int64) buf.f_bavail; // Note: this returns space available to non-super user
  221646. return 0;
  221647. }
  221648. int64 File::getVolumeTotalSize() const
  221649. {
  221650. struct statfs buf;
  221651. if (juce_doStatFS (*this, buf))
  221652. return (int64) buf.f_bsize * (int64) buf.f_blocks;
  221653. return 0;
  221654. }
  221655. const String File::getVolumeLabel() const
  221656. {
  221657. #if JUCE_MAC
  221658. struct VolAttrBuf
  221659. {
  221660. u_int32_t length;
  221661. attrreference_t mountPointRef;
  221662. char mountPointSpace [MAXPATHLEN];
  221663. } attrBuf;
  221664. struct attrlist attrList;
  221665. zerostruct (attrList);
  221666. attrList.bitmapcount = ATTR_BIT_MAP_COUNT;
  221667. attrList.volattr = ATTR_VOL_INFO | ATTR_VOL_NAME;
  221668. File f (*this);
  221669. for (;;)
  221670. {
  221671. if (getattrlist (f.getFullPathName().toUTF8(), &attrList, &attrBuf, sizeof (attrBuf), 0) == 0)
  221672. return String::fromUTF8 (((const char*) &attrBuf.mountPointRef) + attrBuf.mountPointRef.attr_dataoffset,
  221673. (int) attrBuf.mountPointRef.attr_length);
  221674. const File parent (f.getParentDirectory());
  221675. if (f == parent)
  221676. break;
  221677. f = parent;
  221678. }
  221679. #endif
  221680. return String::empty;
  221681. }
  221682. int File::getVolumeSerialNumber() const
  221683. {
  221684. return 0; // xxx
  221685. }
  221686. void juce_runSystemCommand (const String& command)
  221687. {
  221688. int result = system (command.toUTF8());
  221689. (void) result;
  221690. }
  221691. const String juce_getOutputFromCommand (const String& command)
  221692. {
  221693. // slight bodge here, as we just pipe the output into a temp file and read it...
  221694. const File tempFile (File::getSpecialLocation (File::tempDirectory)
  221695. .getNonexistentChildFile (String::toHexString (Random::getSystemRandom().nextInt()), ".tmp", false));
  221696. juce_runSystemCommand (command + " > " + tempFile.getFullPathName());
  221697. String result (tempFile.loadFileAsString());
  221698. tempFile.deleteFile();
  221699. return result;
  221700. }
  221701. class InterProcessLock::Pimpl
  221702. {
  221703. public:
  221704. Pimpl (const String& name, const int timeOutMillisecs)
  221705. : handle (0), refCount (1)
  221706. {
  221707. #if JUCE_MAC
  221708. // (don't use getSpecialLocation() to avoid the temp folder being different for each app)
  221709. const File temp (File ("~/Library/Caches/Juce").getChildFile (name));
  221710. #else
  221711. const File temp (File::getSpecialLocation (File::tempDirectory).getChildFile (name));
  221712. #endif
  221713. temp.create();
  221714. handle = open (temp.getFullPathName().toUTF8(), O_RDWR);
  221715. if (handle != 0)
  221716. {
  221717. struct flock fl;
  221718. zerostruct (fl);
  221719. fl.l_whence = SEEK_SET;
  221720. fl.l_type = F_WRLCK;
  221721. const int64 endTime = Time::currentTimeMillis() + timeOutMillisecs;
  221722. for (;;)
  221723. {
  221724. const int result = fcntl (handle, F_SETLK, &fl);
  221725. if (result >= 0)
  221726. return;
  221727. if (errno != EINTR)
  221728. {
  221729. if (timeOutMillisecs == 0
  221730. || (timeOutMillisecs > 0 && Time::currentTimeMillis() >= endTime))
  221731. break;
  221732. Thread::sleep (10);
  221733. }
  221734. }
  221735. }
  221736. closeFile();
  221737. }
  221738. ~Pimpl()
  221739. {
  221740. closeFile();
  221741. }
  221742. void closeFile()
  221743. {
  221744. if (handle != 0)
  221745. {
  221746. struct flock fl;
  221747. zerostruct (fl);
  221748. fl.l_whence = SEEK_SET;
  221749. fl.l_type = F_UNLCK;
  221750. while (! (fcntl (handle, F_SETLKW, &fl) >= 0 || errno != EINTR))
  221751. {}
  221752. close (handle);
  221753. handle = 0;
  221754. }
  221755. }
  221756. int handle, refCount;
  221757. };
  221758. InterProcessLock::InterProcessLock (const String& name_)
  221759. : name (name_)
  221760. {
  221761. }
  221762. InterProcessLock::~InterProcessLock()
  221763. {
  221764. }
  221765. bool InterProcessLock::enter (const int timeOutMillisecs)
  221766. {
  221767. const ScopedLock sl (lock);
  221768. if (pimpl == 0)
  221769. {
  221770. pimpl = new Pimpl (name, timeOutMillisecs);
  221771. if (pimpl->handle == 0)
  221772. pimpl = 0;
  221773. }
  221774. else
  221775. {
  221776. pimpl->refCount++;
  221777. }
  221778. return pimpl != 0;
  221779. }
  221780. void InterProcessLock::exit()
  221781. {
  221782. const ScopedLock sl (lock);
  221783. // Trying to release the lock too many times!
  221784. jassert (pimpl != 0);
  221785. if (pimpl != 0 && --(pimpl->refCount) == 0)
  221786. pimpl = 0;
  221787. }
  221788. /*** End of inlined file: juce_posix_SharedCode.h ***/
  221789. /*** Start of inlined file: juce_mac_Files.mm ***/
  221790. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  221791. // compiled on its own).
  221792. #if JUCE_INCLUDED_FILE
  221793. /*
  221794. Note that a lot of methods that you'd expect to find in this file actually
  221795. live in juce_posix_SharedCode.h!
  221796. */
  221797. bool File::copyInternal (const File& dest) const
  221798. {
  221799. const ScopedAutoReleasePool pool;
  221800. NSFileManager* fm = [NSFileManager defaultManager];
  221801. return [fm fileExistsAtPath: juceStringToNS (fullPath)]
  221802. #if defined (MAC_OS_X_VERSION_10_6) && MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_6
  221803. && [fm copyItemAtPath: juceStringToNS (fullPath)
  221804. toPath: juceStringToNS (dest.getFullPathName())
  221805. error: nil];
  221806. #else
  221807. && [fm copyPath: juceStringToNS (fullPath)
  221808. toPath: juceStringToNS (dest.getFullPathName())
  221809. handler: nil];
  221810. #endif
  221811. }
  221812. void File::findFileSystemRoots (Array<File>& destArray)
  221813. {
  221814. destArray.add (File ("/"));
  221815. }
  221816. static bool isFileOnDriveType (const File& f, const char* const* types)
  221817. {
  221818. struct statfs buf;
  221819. if (juce_doStatFS (f, buf))
  221820. {
  221821. const String type (buf.f_fstypename);
  221822. while (*types != 0)
  221823. if (type.equalsIgnoreCase (*types++))
  221824. return true;
  221825. }
  221826. return false;
  221827. }
  221828. bool File::isOnCDRomDrive() const
  221829. {
  221830. const char* const cdTypes[] = { "cd9660", "cdfs", "cddafs", "udf", 0 };
  221831. return isFileOnDriveType (*this, cdTypes);
  221832. }
  221833. bool File::isOnHardDisk() const
  221834. {
  221835. const char* const nonHDTypes[] = { "nfs", "smbfs", "ramfs", 0 };
  221836. return ! (isOnCDRomDrive() || isFileOnDriveType (*this, nonHDTypes));
  221837. }
  221838. bool File::isOnRemovableDrive() const
  221839. {
  221840. #if JUCE_IPHONE
  221841. return false; // xxx is this possible?
  221842. #else
  221843. const ScopedAutoReleasePool pool;
  221844. BOOL removable = false;
  221845. [[NSWorkspace sharedWorkspace]
  221846. getFileSystemInfoForPath: juceStringToNS (getFullPathName())
  221847. isRemovable: &removable
  221848. isWritable: nil
  221849. isUnmountable: nil
  221850. description: nil
  221851. type: nil];
  221852. return removable;
  221853. #endif
  221854. }
  221855. static bool juce_isHiddenFile (const String& path)
  221856. {
  221857. #if JUCE_IPHONE
  221858. return File (path).getFileName().startsWithChar ('.');
  221859. #else
  221860. FSRef ref;
  221861. if (! PlatformUtilities::makeFSRefFromPath (&ref, path))
  221862. return false;
  221863. FSCatalogInfo info;
  221864. FSGetCatalogInfo (&ref, kFSCatInfoNodeFlags | kFSCatInfoFinderInfo, &info, 0, 0, 0);
  221865. if ((info.nodeFlags & kFSNodeIsDirectoryBit) != 0)
  221866. return (((FolderInfo*) &info.finderInfo)->finderFlags & kIsInvisible) != 0;
  221867. return (((FileInfo*) &info.finderInfo)->finderFlags & kIsInvisible) != 0;
  221868. #endif
  221869. }
  221870. bool File::isHidden() const
  221871. {
  221872. return juce_isHiddenFile (getFullPathName());
  221873. }
  221874. const char* juce_Argv0 = 0; // referenced from juce_Application.cpp
  221875. const File File::getSpecialLocation (const SpecialLocationType type)
  221876. {
  221877. const ScopedAutoReleasePool pool;
  221878. String resultPath;
  221879. switch (type)
  221880. {
  221881. case userHomeDirectory:
  221882. resultPath = nsStringToJuce (NSHomeDirectory());
  221883. break;
  221884. case userDocumentsDirectory:
  221885. resultPath = "~/Documents";
  221886. break;
  221887. case userDesktopDirectory:
  221888. resultPath = "~/Desktop";
  221889. break;
  221890. case userApplicationDataDirectory:
  221891. resultPath = "~/Library";
  221892. break;
  221893. case commonApplicationDataDirectory:
  221894. resultPath = "/Library";
  221895. break;
  221896. case globalApplicationsDirectory:
  221897. resultPath = "/Applications";
  221898. break;
  221899. case userMusicDirectory:
  221900. resultPath = "~/Music";
  221901. break;
  221902. case userMoviesDirectory:
  221903. resultPath = "~/Movies";
  221904. break;
  221905. case tempDirectory:
  221906. {
  221907. File tmp ("~/Library/Caches/" + juce_getExecutableFile().getFileNameWithoutExtension());
  221908. tmp.createDirectory();
  221909. return tmp.getFullPathName();
  221910. }
  221911. case invokedExecutableFile:
  221912. if (juce_Argv0 != 0)
  221913. return File (String::fromUTF8 (juce_Argv0));
  221914. // deliberate fall-through...
  221915. case currentExecutableFile:
  221916. return juce_getExecutableFile();
  221917. case currentApplicationFile:
  221918. {
  221919. const File exe (juce_getExecutableFile());
  221920. const File parent (exe.getParentDirectory());
  221921. return parent.getFullPathName().endsWithIgnoreCase ("Contents/MacOS")
  221922. ? parent.getParentDirectory().getParentDirectory()
  221923. : exe;
  221924. }
  221925. default:
  221926. jassertfalse // unknown type?
  221927. break;
  221928. }
  221929. if (resultPath.isNotEmpty())
  221930. return File (PlatformUtilities::convertToPrecomposedUnicode (resultPath));
  221931. return File::nonexistent;
  221932. }
  221933. const String File::getVersion() const
  221934. {
  221935. const ScopedAutoReleasePool pool;
  221936. String result;
  221937. NSBundle* bundle = [NSBundle bundleWithPath: juceStringToNS (getFullPathName())];
  221938. if (bundle != 0)
  221939. {
  221940. NSDictionary* info = [bundle infoDictionary];
  221941. if (info != 0)
  221942. {
  221943. NSString* name = [info valueForKey: @"CFBundleShortVersionString"];
  221944. if (name != nil)
  221945. result = nsStringToJuce (name);
  221946. }
  221947. }
  221948. return result;
  221949. }
  221950. const File File::getLinkedTarget() const
  221951. {
  221952. #if JUCE_IPHONE || (defined (MAC_OS_X_VERSION_10_5) && MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_5)
  221953. NSString* dest = [[NSFileManager defaultManager] destinationOfSymbolicLinkAtPath: juceStringToNS (getFullPathName()) error: nil];
  221954. #else
  221955. NSString* dest = [[NSFileManager defaultManager] pathContentOfSymbolicLinkAtPath: juceStringToNS (getFullPathName())];
  221956. #endif
  221957. if (dest != nil)
  221958. return File (nsStringToJuce (dest));
  221959. return *this;
  221960. }
  221961. bool File::moveToTrash() const
  221962. {
  221963. if (! exists())
  221964. return true;
  221965. #if JUCE_IPHONE
  221966. return deleteFile(); //xxx is there a trashcan on the iPhone?
  221967. #else
  221968. const ScopedAutoReleasePool pool;
  221969. NSString* p = juceStringToNS (getFullPathName());
  221970. return [[NSWorkspace sharedWorkspace]
  221971. performFileOperation: NSWorkspaceRecycleOperation
  221972. source: [p stringByDeletingLastPathComponent]
  221973. destination: @""
  221974. files: [NSArray arrayWithObject: [p lastPathComponent]]
  221975. tag: nil ];
  221976. #endif
  221977. }
  221978. class DirectoryIterator::NativeIterator::Pimpl
  221979. {
  221980. public:
  221981. Pimpl (const File& directory, const String& wildCard_)
  221982. : parentDir (File::addTrailingSeparator (directory.getFullPathName())),
  221983. wildCard (wildCard_),
  221984. enumerator (0)
  221985. {
  221986. ScopedAutoReleasePool pool;
  221987. enumerator = [[[NSFileManager defaultManager] enumeratorAtPath: juceStringToNS (directory.getFullPathName())] retain];
  221988. wildcardUTF8 = wildCard.toUTF8();
  221989. }
  221990. ~Pimpl()
  221991. {
  221992. [enumerator release];
  221993. }
  221994. bool next (String& filenameFound,
  221995. bool* const isDir, bool* const isHidden, int64* const fileSize,
  221996. Time* const modTime, Time* const creationTime, bool* const isReadOnly)
  221997. {
  221998. ScopedAutoReleasePool pool;
  221999. for (;;)
  222000. {
  222001. NSString* file;
  222002. if (enumerator == 0 || (file = [enumerator nextObject]) == 0)
  222003. return false;
  222004. [enumerator skipDescendents];
  222005. filenameFound = nsStringToJuce (file);
  222006. if (fnmatch (wildcardUTF8, filenameFound.toUTF8(), FNM_CASEFOLD) != 0)
  222007. continue;
  222008. const String path (parentDir + filenameFound);
  222009. if (isDir != 0 || fileSize != 0 || modTime != 0 || creationTime != 0)
  222010. {
  222011. struct stat info;
  222012. const bool statOk = juce_stat (path, info);
  222013. if (isDir != 0) *isDir = statOk && ((info.st_mode & S_IFDIR) != 0);
  222014. if (fileSize != 0) *fileSize = statOk ? info.st_size : 0;
  222015. if (modTime != 0) *modTime = statOk ? (int64) info.st_mtime * 1000 : 0;
  222016. if (creationTime != 0) *creationTime = statOk ? (int64) info.st_ctime * 1000 : 0;
  222017. }
  222018. if (isHidden != 0)
  222019. *isHidden = juce_isHiddenFile (path);
  222020. if (isReadOnly != 0)
  222021. *isReadOnly = access (path.toUTF8(), W_OK) != 0;
  222022. return true;
  222023. }
  222024. }
  222025. private:
  222026. String parentDir, wildCard;
  222027. const char* wildcardUTF8;
  222028. NSDirectoryEnumerator* enumerator;
  222029. Pimpl (const Pimpl&);
  222030. Pimpl& operator= (const Pimpl&);
  222031. };
  222032. DirectoryIterator::NativeIterator::NativeIterator (const File& directory, const String& wildCard)
  222033. : pimpl (new DirectoryIterator::NativeIterator::Pimpl (directory, wildCard))
  222034. {
  222035. }
  222036. DirectoryIterator::NativeIterator::~NativeIterator()
  222037. {
  222038. }
  222039. bool DirectoryIterator::NativeIterator::next (String& filenameFound,
  222040. bool* const isDir, bool* const isHidden, int64* const fileSize,
  222041. Time* const modTime, Time* const creationTime, bool* const isReadOnly)
  222042. {
  222043. return pimpl->next (filenameFound, isDir, isHidden, fileSize, modTime, creationTime, isReadOnly);
  222044. }
  222045. bool juce_launchExecutable (const String& pathAndArguments)
  222046. {
  222047. const char* const argv[4] = { "/bin/sh", "-c", pathAndArguments.toUTF8(), 0 };
  222048. const int cpid = fork();
  222049. if (cpid == 0)
  222050. {
  222051. // Child process
  222052. if (execve (argv[0], (char**) argv, 0) < 0)
  222053. exit (0);
  222054. }
  222055. else
  222056. {
  222057. if (cpid < 0)
  222058. return false;
  222059. }
  222060. return true;
  222061. }
  222062. bool PlatformUtilities::openDocument (const String& fileName, const String& parameters)
  222063. {
  222064. #if JUCE_IPHONE
  222065. return [[UIApplication sharedApplication] openURL: [NSURL fileURLWithPath: juceStringToNS (fileName)]];
  222066. #else
  222067. const ScopedAutoReleasePool pool;
  222068. if (parameters.isEmpty())
  222069. {
  222070. return [[NSWorkspace sharedWorkspace] openFile: juceStringToNS (fileName)]
  222071. || [[NSWorkspace sharedWorkspace] openURL: [NSURL URLWithString: juceStringToNS (fileName)]];
  222072. }
  222073. bool ok = false;
  222074. FSRef ref;
  222075. if (PlatformUtilities::makeFSRefFromPath (&ref, fileName))
  222076. {
  222077. if (PlatformUtilities::isBundle (fileName))
  222078. {
  222079. NSMutableArray* urls = [NSMutableArray array];
  222080. StringArray docs;
  222081. docs.addTokens (parameters, true);
  222082. for (int i = 0; i < docs.size(); ++i)
  222083. [urls addObject: juceStringToNS (docs[i])];
  222084. ok = [[NSWorkspace sharedWorkspace] openURLs: urls
  222085. withAppBundleIdentifier: [[NSBundle bundleWithPath: juceStringToNS (fileName)] bundleIdentifier]
  222086. options: 0
  222087. additionalEventParamDescriptor: nil
  222088. launchIdentifiers: nil];
  222089. }
  222090. else
  222091. {
  222092. ok = juce_launchExecutable ("\"" + fileName + "\" " + parameters);
  222093. }
  222094. }
  222095. return ok;
  222096. #endif
  222097. }
  222098. void File::revealToUser() const
  222099. {
  222100. #if ! JUCE_IPHONE
  222101. if (exists())
  222102. [[NSWorkspace sharedWorkspace] selectFile: juceStringToNS (getFullPathName()) inFileViewerRootedAtPath: @""];
  222103. else if (getParentDirectory().exists())
  222104. getParentDirectory().revealToUser();
  222105. #endif
  222106. }
  222107. #if ! JUCE_IPHONE
  222108. bool PlatformUtilities::makeFSRefFromPath (FSRef* destFSRef, const String& path)
  222109. {
  222110. return FSPathMakeRef ((const UInt8*) path.toUTF8(), destFSRef, 0) == noErr;
  222111. }
  222112. const String PlatformUtilities::makePathFromFSRef (FSRef* file)
  222113. {
  222114. char path [2048];
  222115. zerostruct (path);
  222116. if (FSRefMakePath (file, (UInt8*) path, sizeof (path) - 1) == noErr)
  222117. return PlatformUtilities::convertToPrecomposedUnicode (String::fromUTF8 (path));
  222118. return String::empty;
  222119. }
  222120. #endif
  222121. OSType PlatformUtilities::getTypeOfFile (const String& filename)
  222122. {
  222123. const ScopedAutoReleasePool pool;
  222124. #if JUCE_IPHONE || (defined (MAC_OS_X_VERSION_10_5) && MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_5)
  222125. NSDictionary* fileDict = [[NSFileManager defaultManager] attributesOfItemAtPath: juceStringToNS (filename) error: nil];
  222126. #else
  222127. NSDictionary* fileDict = [[NSFileManager defaultManager] fileAttributesAtPath: juceStringToNS (filename) traverseLink: NO];
  222128. #endif
  222129. //return (OSType) [fileDict objectForKey: NSFileHFSTypeCode];
  222130. return [fileDict fileHFSTypeCode];
  222131. }
  222132. bool PlatformUtilities::isBundle (const String& filename)
  222133. {
  222134. #if JUCE_IPHONE
  222135. return false; // xxx can't find a sensible way to do this without trying to open the bundle..
  222136. #else
  222137. const ScopedAutoReleasePool pool;
  222138. return [[NSWorkspace sharedWorkspace] isFilePackageAtPath: juceStringToNS (filename)];
  222139. #endif
  222140. }
  222141. #endif
  222142. /*** End of inlined file: juce_mac_Files.mm ***/
  222143. #if JUCE_IPHONE
  222144. /*** Start of inlined file: juce_iphone_MiscUtilities.mm ***/
  222145. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  222146. // compiled on its own).
  222147. #if JUCE_INCLUDED_FILE
  222148. static JUCEApplication* juce_intialisingApp;
  222149. END_JUCE_NAMESPACE
  222150. @interface JuceAppStartupDelegate : NSObject <UIApplicationDelegate>
  222151. {
  222152. }
  222153. - (void) applicationDidFinishLaunching: (UIApplication*) application;
  222154. - (void) applicationWillResignActive: (UIApplication*) application;
  222155. @end
  222156. @implementation JuceAppStartupDelegate
  222157. - (void) applicationDidFinishLaunching: (UIApplication*) application
  222158. {
  222159. String dummy;
  222160. if (! juce_intialisingApp->initialiseApp (dummy))
  222161. exit (0);
  222162. }
  222163. - (void) applicationWillResignActive: (UIApplication*) application
  222164. {
  222165. JUCEApplication::shutdownAppAndClearUp();
  222166. }
  222167. @end
  222168. BEGIN_JUCE_NAMESPACE
  222169. int juce_IPhoneMain (int argc, const char* argv[], JUCEApplication* app)
  222170. {
  222171. juce_intialisingApp = app;
  222172. return UIApplicationMain (argc, const_cast<char**> (argv), nil, @"JuceAppStartupDelegate");
  222173. }
  222174. ScopedAutoReleasePool::ScopedAutoReleasePool()
  222175. {
  222176. pool = [[NSAutoreleasePool alloc] init];
  222177. }
  222178. ScopedAutoReleasePool::~ScopedAutoReleasePool()
  222179. {
  222180. [((NSAutoreleasePool*) pool) release];
  222181. }
  222182. void PlatformUtilities::beep()
  222183. {
  222184. //xxx
  222185. //AudioServicesPlaySystemSound ();
  222186. }
  222187. void PlatformUtilities::addItemToDock (const File& file)
  222188. {
  222189. }
  222190. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  222191. END_JUCE_NAMESPACE
  222192. @interface JuceAlertBoxDelegate : NSObject
  222193. {
  222194. @public
  222195. bool clickedOk;
  222196. }
  222197. - (void) alertView: (UIAlertView*) alertView clickedButtonAtIndex: (NSInteger) buttonIndex;
  222198. @end
  222199. @implementation JuceAlertBoxDelegate
  222200. - (void) alertView: (UIAlertView*) alertView clickedButtonAtIndex: (NSInteger) buttonIndex
  222201. {
  222202. clickedOk = (buttonIndex == 0);
  222203. alertView.hidden = true;
  222204. }
  222205. @end
  222206. BEGIN_JUCE_NAMESPACE
  222207. // (This function is used directly by other bits of code)
  222208. bool juce_iPhoneShowModalAlert (const String& title,
  222209. const String& bodyText,
  222210. NSString* okButtonText,
  222211. NSString* cancelButtonText)
  222212. {
  222213. const ScopedAutoReleasePool pool;
  222214. JuceAlertBoxDelegate* callback = [[JuceAlertBoxDelegate alloc] init];
  222215. UIAlertView* alert = [[UIAlertView alloc] initWithTitle: juceStringToNS (title)
  222216. message: juceStringToNS (bodyText)
  222217. delegate: callback
  222218. cancelButtonTitle: okButtonText
  222219. otherButtonTitles: cancelButtonText, nil];
  222220. [alert retain];
  222221. [alert show];
  222222. while (! alert.hidden && alert.superview != nil)
  222223. [[NSRunLoop mainRunLoop] runUntilDate: [NSDate dateWithTimeIntervalSinceNow: 0.01]];
  222224. const bool result = callback->clickedOk;
  222225. [alert release];
  222226. [callback release];
  222227. return result;
  222228. }
  222229. bool AlertWindow::showNativeDialogBox (const String& title,
  222230. const String& bodyText,
  222231. bool isOkCancel)
  222232. {
  222233. return juce_iPhoneShowModalAlert (title, bodyText,
  222234. @"OK",
  222235. isOkCancel ? @"Cancel" : nil);
  222236. }
  222237. bool DragAndDropContainer::performExternalDragDropOfFiles (const StringArray& files, const bool canMoveFiles)
  222238. {
  222239. jassertfalse // no such thing on the iphone!
  222240. return false;
  222241. }
  222242. bool DragAndDropContainer::performExternalDragDropOfText (const String& text)
  222243. {
  222244. jassertfalse // no such thing on the iphone!
  222245. return false;
  222246. }
  222247. void Desktop::setScreenSaverEnabled (const bool isEnabled) throw()
  222248. {
  222249. [[UIApplication sharedApplication] setIdleTimerDisabled: ! isEnabled];
  222250. }
  222251. bool Desktop::isScreenSaverEnabled() throw()
  222252. {
  222253. return ! [[UIApplication sharedApplication] isIdleTimerDisabled];
  222254. }
  222255. void juce_updateMultiMonitorInfo (Array <Rectangle <int> >& monitorCoords, const bool clipToWorkArea)
  222256. {
  222257. const ScopedAutoReleasePool pool;
  222258. monitorCoords.clear();
  222259. CGRect r = clipToWorkArea ? [[UIScreen mainScreen] applicationFrame]
  222260. : [[UIScreen mainScreen] bounds];
  222261. monitorCoords.add (Rectangle<int> ((int) r.origin.x,
  222262. (int) r.origin.y,
  222263. (int) r.size.width,
  222264. (int) r.size.height));
  222265. }
  222266. #endif
  222267. #endif
  222268. /*** End of inlined file: juce_iphone_MiscUtilities.mm ***/
  222269. #else
  222270. /*** Start of inlined file: juce_mac_MiscUtilities.mm ***/
  222271. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  222272. // compiled on its own).
  222273. #if JUCE_INCLUDED_FILE
  222274. ScopedAutoReleasePool::ScopedAutoReleasePool()
  222275. {
  222276. pool = [[NSAutoreleasePool alloc] init];
  222277. }
  222278. ScopedAutoReleasePool::~ScopedAutoReleasePool()
  222279. {
  222280. [((NSAutoreleasePool*) pool) release];
  222281. }
  222282. void PlatformUtilities::beep()
  222283. {
  222284. NSBeep();
  222285. }
  222286. void PlatformUtilities::addItemToDock (const File& file)
  222287. {
  222288. // check that it's not already there...
  222289. if (! juce_getOutputFromCommand ("defaults read com.apple.dock persistent-apps")
  222290. .containsIgnoreCase (file.getFullPathName()))
  222291. {
  222292. juce_runSystemCommand ("defaults write com.apple.dock persistent-apps -array-add \"<dict><key>tile-data</key><dict><key>file-data</key><dict><key>_CFURLString</key><string>"
  222293. + file.getFullPathName() + "</string><key>_CFURLStringType</key><integer>0</integer></dict></dict></dict>\"");
  222294. juce_runSystemCommand ("osascript -e \"tell application \\\"Dock\\\" to quit\"");
  222295. }
  222296. }
  222297. int PlatformUtilities::getOSXMinorVersionNumber()
  222298. {
  222299. SInt32 versionMinor = 0;
  222300. OSErr err = Gestalt (gestaltSystemVersionMinor, &versionMinor);
  222301. (void) err;
  222302. jassert (err == noErr);
  222303. return (int) versionMinor;
  222304. }
  222305. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  222306. bool AlertWindow::showNativeDialogBox (const String& title,
  222307. const String& bodyText,
  222308. bool isOkCancel)
  222309. {
  222310. const ScopedAutoReleasePool pool;
  222311. return NSRunAlertPanel (juceStringToNS (title),
  222312. juceStringToNS (bodyText),
  222313. @"Ok",
  222314. isOkCancel ? @"Cancel" : nil,
  222315. nil) == NSAlertDefaultReturn;
  222316. }
  222317. bool DragAndDropContainer::performExternalDragDropOfFiles (const StringArray& files, const bool /*canMoveFiles*/)
  222318. {
  222319. if (files.size() == 0)
  222320. return false;
  222321. MouseInputSource* draggingSource = Desktop::getInstance().getDraggingMouseSource(0);
  222322. if (draggingSource == 0)
  222323. {
  222324. jassertfalse // This method must be called in response to a component's mouseDown or mouseDrag event!
  222325. return false;
  222326. }
  222327. Component* sourceComp = draggingSource->getComponentUnderMouse();
  222328. if (sourceComp == 0)
  222329. {
  222330. jassertfalse // This method must be called in response to a component's mouseDown or mouseDrag event!
  222331. return false;
  222332. }
  222333. const ScopedAutoReleasePool pool;
  222334. NSView* view = (NSView*) sourceComp->getWindowHandle();
  222335. if (view == 0)
  222336. return false;
  222337. NSPasteboard* pboard = [NSPasteboard pasteboardWithName: NSDragPboard];
  222338. [pboard declareTypes: [NSArray arrayWithObject: NSFilenamesPboardType]
  222339. owner: nil];
  222340. NSMutableArray* filesArray = [NSMutableArray arrayWithCapacity: 4];
  222341. for (int i = 0; i < files.size(); ++i)
  222342. [filesArray addObject: juceStringToNS (files[i])];
  222343. [pboard setPropertyList: filesArray
  222344. forType: NSFilenamesPboardType];
  222345. NSPoint dragPosition = [view convertPoint: [[[view window] currentEvent] locationInWindow]
  222346. fromView: nil];
  222347. dragPosition.x -= 16;
  222348. dragPosition.y -= 16;
  222349. [view dragImage: [[NSWorkspace sharedWorkspace] iconForFile: juceStringToNS (files[0])]
  222350. at: dragPosition
  222351. offset: NSMakeSize (0, 0)
  222352. event: [[view window] currentEvent]
  222353. pasteboard: pboard
  222354. source: view
  222355. slideBack: YES];
  222356. return true;
  222357. }
  222358. bool DragAndDropContainer::performExternalDragDropOfText (const String& /*text*/)
  222359. {
  222360. jassertfalse // not implemented!
  222361. return false;
  222362. }
  222363. bool Desktop::canUseSemiTransparentWindows() throw()
  222364. {
  222365. return true;
  222366. }
  222367. const Point<int> Desktop::getMousePosition()
  222368. {
  222369. const ScopedAutoReleasePool pool;
  222370. const NSPoint p ([NSEvent mouseLocation]);
  222371. return Point<int> (roundToInt (p.x), roundToInt ([[[NSScreen screens] objectAtIndex: 0] frame].size.height - p.y));
  222372. }
  222373. void Desktop::setMousePosition (const Point<int>& newPosition)
  222374. {
  222375. // this rubbish needs to be done around the warp call, to avoid causing a
  222376. // bizarre glitch..
  222377. CGAssociateMouseAndMouseCursorPosition (false);
  222378. CGWarpMouseCursorPosition (CGPointMake (newPosition.getX(), newPosition.getY()));
  222379. CGAssociateMouseAndMouseCursorPosition (true);
  222380. }
  222381. #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
  222382. class ScreenSaverDefeater : public Timer,
  222383. public DeletedAtShutdown
  222384. {
  222385. public:
  222386. ScreenSaverDefeater()
  222387. {
  222388. startTimer (10000);
  222389. timerCallback();
  222390. }
  222391. ~ScreenSaverDefeater() {}
  222392. void timerCallback()
  222393. {
  222394. if (Process::isForegroundProcess())
  222395. UpdateSystemActivity (UsrActivity);
  222396. }
  222397. };
  222398. static ScreenSaverDefeater* screenSaverDefeater = 0;
  222399. void Desktop::setScreenSaverEnabled (const bool isEnabled) throw()
  222400. {
  222401. if (isEnabled)
  222402. {
  222403. deleteAndZero (screenSaverDefeater);
  222404. }
  222405. else if (screenSaverDefeater == 0)
  222406. {
  222407. screenSaverDefeater = new ScreenSaverDefeater();
  222408. }
  222409. }
  222410. bool Desktop::isScreenSaverEnabled() throw()
  222411. {
  222412. return screenSaverDefeater == 0;
  222413. }
  222414. #else
  222415. static IOPMAssertionID screenSaverDisablerID = 0;
  222416. void Desktop::setScreenSaverEnabled (const bool isEnabled) throw()
  222417. {
  222418. if (isEnabled)
  222419. {
  222420. if (screenSaverDisablerID != 0)
  222421. {
  222422. IOPMAssertionRelease (screenSaverDisablerID);
  222423. screenSaverDisablerID = 0;
  222424. }
  222425. }
  222426. else
  222427. {
  222428. if (screenSaverDisablerID == 0)
  222429. {
  222430. #if defined (MAC_OS_X_VERSION_10_6) && MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_6
  222431. IOPMAssertionCreateWithName (kIOPMAssertionTypeNoIdleSleep, kIOPMAssertionLevelOn,
  222432. CFSTR ("Juce"), &screenSaverDisablerID);
  222433. #else
  222434. IOPMAssertionCreate (kIOPMAssertionTypeNoIdleSleep, kIOPMAssertionLevelOn,
  222435. &screenSaverDisablerID);
  222436. #endif
  222437. }
  222438. }
  222439. }
  222440. bool Desktop::isScreenSaverEnabled() throw()
  222441. {
  222442. return screenSaverDisablerID == 0;
  222443. }
  222444. #endif
  222445. void juce_updateMultiMonitorInfo (Array <Rectangle<int> >& monitorCoords, const bool clipToWorkArea)
  222446. {
  222447. const ScopedAutoReleasePool pool;
  222448. monitorCoords.clear();
  222449. NSArray* screens = [NSScreen screens];
  222450. const CGFloat mainScreenBottom = [[[NSScreen screens] objectAtIndex: 0] frame].size.height;
  222451. for (unsigned int i = 0; i < [screens count]; ++i)
  222452. {
  222453. NSScreen* s = (NSScreen*) [screens objectAtIndex: i];
  222454. NSRect r = clipToWorkArea ? [s visibleFrame]
  222455. : [s frame];
  222456. monitorCoords.add (Rectangle<int> ((int) r.origin.x,
  222457. (int) (mainScreenBottom - (r.origin.y + r.size.height)),
  222458. (int) r.size.width,
  222459. (int) r.size.height));
  222460. }
  222461. jassert (monitorCoords.size() > 0);
  222462. }
  222463. #endif
  222464. #endif
  222465. /*** End of inlined file: juce_mac_MiscUtilities.mm ***/
  222466. #endif
  222467. /*** Start of inlined file: juce_mac_Debugging.mm ***/
  222468. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  222469. // compiled on its own).
  222470. #if JUCE_INCLUDED_FILE
  222471. void Logger::outputDebugString (const String& text)
  222472. {
  222473. std::cerr << text << std::endl;
  222474. }
  222475. bool JUCE_PUBLIC_FUNCTION juce_isRunningUnderDebugger()
  222476. {
  222477. static char testResult = 0;
  222478. if (testResult == 0)
  222479. {
  222480. struct kinfo_proc info;
  222481. int m[] = { CTL_KERN, KERN_PROC, KERN_PROC_PID, getpid() };
  222482. size_t sz = sizeof (info);
  222483. sysctl (m, 4, &info, &sz, 0, 0);
  222484. testResult = ((info.kp_proc.p_flag & P_TRACED) != 0) ? 1 : -1;
  222485. }
  222486. return testResult > 0;
  222487. }
  222488. bool JUCE_CALLTYPE Process::isRunningUnderDebugger()
  222489. {
  222490. return juce_isRunningUnderDebugger();
  222491. }
  222492. #endif
  222493. /*** End of inlined file: juce_mac_Debugging.mm ***/
  222494. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  222495. #if JUCE_IPHONE
  222496. /*** Start of inlined file: juce_mac_Fonts.mm ***/
  222497. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  222498. // compiled on its own).
  222499. #if JUCE_INCLUDED_FILE
  222500. #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
  222501. #define SUPPORT_10_4_FONTS 1
  222502. #define NEW_CGFONT_FUNCTIONS_UNAVAILABLE (CGFontCreateWithFontName == 0)
  222503. #if MAC_OS_X_VERSION_MAX_ALLOWED < MAC_OS_X_VERSION_10_5
  222504. #define SUPPORT_ONLY_10_4_FONTS 1
  222505. #endif
  222506. END_JUCE_NAMESPACE
  222507. @interface NSFont (PrivateHack)
  222508. - (NSGlyph) _defaultGlyphForChar: (unichar) theChar;
  222509. @end
  222510. BEGIN_JUCE_NAMESPACE
  222511. #endif
  222512. class MacTypeface : public Typeface
  222513. {
  222514. public:
  222515. MacTypeface (const Font& font)
  222516. : Typeface (font.getTypefaceName())
  222517. {
  222518. const ScopedAutoReleasePool pool;
  222519. renderingTransform = CGAffineTransformIdentity;
  222520. bool needsItalicTransform = false;
  222521. #if JUCE_IPHONE
  222522. NSString* fontName = juceStringToNS (font.getTypefaceName());
  222523. if (font.isItalic() || font.isBold())
  222524. {
  222525. NSArray* familyFonts = [UIFont fontNamesForFamilyName: juceStringToNS (font.getTypefaceName())];
  222526. for (NSString* i in familyFonts)
  222527. {
  222528. const String fn (nsStringToJuce (i));
  222529. const String afterDash (fn.fromFirstOccurrenceOf ("-", false, false));
  222530. const bool probablyBold = afterDash.containsIgnoreCase ("bold") || fn.endsWithIgnoreCase ("bold");
  222531. const bool probablyItalic = afterDash.containsIgnoreCase ("oblique")
  222532. || afterDash.containsIgnoreCase ("italic")
  222533. || fn.endsWithIgnoreCase ("oblique")
  222534. || fn.endsWithIgnoreCase ("italic");
  222535. if (probablyBold == font.isBold()
  222536. && probablyItalic == font.isItalic())
  222537. {
  222538. fontName = i;
  222539. needsItalicTransform = false;
  222540. break;
  222541. }
  222542. else if (probablyBold && (! probablyItalic) && probablyBold == font.isBold())
  222543. {
  222544. fontName = i;
  222545. needsItalicTransform = true; // not ideal, so carry on in case we find a better one
  222546. }
  222547. }
  222548. if (needsItalicTransform)
  222549. renderingTransform.c = 0.15f;
  222550. }
  222551. fontRef = CGFontCreateWithFontName ((CFStringRef) fontName);
  222552. const int ascender = abs (CGFontGetAscent (fontRef));
  222553. const float totalHeight = ascender + abs (CGFontGetDescent (fontRef));
  222554. ascent = ascender / totalHeight;
  222555. unitsToHeightScaleFactor = 1.0f / totalHeight;
  222556. fontHeightToCGSizeFactor = CGFontGetUnitsPerEm (fontRef) / totalHeight;
  222557. #else
  222558. nsFont = [NSFont fontWithName: juceStringToNS (font.getTypefaceName()) size: 1024];
  222559. if (font.isItalic())
  222560. {
  222561. NSFont* newFont = [[NSFontManager sharedFontManager] convertFont: nsFont
  222562. toHaveTrait: NSItalicFontMask];
  222563. if (newFont == nsFont)
  222564. needsItalicTransform = true; // couldn't find a proper italic version, so fake it with a transform..
  222565. nsFont = newFont;
  222566. }
  222567. if (font.isBold())
  222568. nsFont = [[NSFontManager sharedFontManager] convertFont: nsFont toHaveTrait: NSBoldFontMask];
  222569. [nsFont retain];
  222570. ascent = std::abs ((float) [nsFont ascender]);
  222571. float totalSize = ascent + std::abs ((float) [nsFont descender]);
  222572. ascent /= totalSize;
  222573. pathTransform = AffineTransform::identity.scale (1.0f / totalSize, 1.0f / totalSize);
  222574. if (needsItalicTransform)
  222575. {
  222576. pathTransform = pathTransform.sheared (-0.15f, 0.0f);
  222577. renderingTransform.c = 0.15f;
  222578. }
  222579. #if SUPPORT_ONLY_10_4_FONTS
  222580. ATSFontRef atsFont = ATSFontFindFromName ((CFStringRef) [nsFont fontName], kATSOptionFlagsDefault);
  222581. if (atsFont == 0)
  222582. atsFont = ATSFontFindFromPostScriptName ((CFStringRef) [nsFont fontName], kATSOptionFlagsDefault);
  222583. fontRef = CGFontCreateWithPlatformFont (&atsFont);
  222584. const float totalHeight = std::abs ([nsFont ascender]) + std::abs ([nsFont descender]);
  222585. unitsToHeightScaleFactor = 1.0f / totalHeight;
  222586. fontHeightToCGSizeFactor = 1024.0f / totalHeight;
  222587. #else
  222588. #if SUPPORT_10_4_FONTS
  222589. if (NEW_CGFONT_FUNCTIONS_UNAVAILABLE)
  222590. {
  222591. ATSFontRef atsFont = ATSFontFindFromName ((CFStringRef) [nsFont fontName], kATSOptionFlagsDefault);
  222592. if (atsFont == 0)
  222593. atsFont = ATSFontFindFromPostScriptName ((CFStringRef) [nsFont fontName], kATSOptionFlagsDefault);
  222594. fontRef = CGFontCreateWithPlatformFont (&atsFont);
  222595. const float totalHeight = std::abs ([nsFont ascender]) + std::abs ([nsFont descender]);
  222596. unitsToHeightScaleFactor = 1.0f / totalHeight;
  222597. fontHeightToCGSizeFactor = 1024.0f / totalHeight;
  222598. }
  222599. else
  222600. #endif
  222601. {
  222602. fontRef = CGFontCreateWithFontName ((CFStringRef) [nsFont fontName]);
  222603. const int totalHeight = abs (CGFontGetAscent (fontRef)) + abs (CGFontGetDescent (fontRef));
  222604. unitsToHeightScaleFactor = 1.0f / totalHeight;
  222605. fontHeightToCGSizeFactor = CGFontGetUnitsPerEm (fontRef) / (float) totalHeight;
  222606. }
  222607. #endif
  222608. #endif
  222609. }
  222610. ~MacTypeface()
  222611. {
  222612. #if ! JUCE_IPHONE
  222613. [nsFont release];
  222614. #endif
  222615. if (fontRef != 0)
  222616. CGFontRelease (fontRef);
  222617. }
  222618. float getAscent() const
  222619. {
  222620. return ascent;
  222621. }
  222622. float getDescent() const
  222623. {
  222624. return 1.0f - ascent;
  222625. }
  222626. float getStringWidth (const String& text)
  222627. {
  222628. if (fontRef == 0 || text.isEmpty())
  222629. return 0;
  222630. const int length = text.length();
  222631. HeapBlock <CGGlyph> glyphs;
  222632. createGlyphsForString (text, length, glyphs);
  222633. float x = 0;
  222634. #if SUPPORT_ONLY_10_4_FONTS
  222635. HeapBlock <NSSize> advances (length);
  222636. [nsFont getAdvancements: advances forGlyphs: reinterpret_cast <NSGlyph*> (glyphs.getData()) count: length];
  222637. for (int i = 0; i < length; ++i)
  222638. x += advances[i].width;
  222639. #else
  222640. #if SUPPORT_10_4_FONTS
  222641. if (NEW_CGFONT_FUNCTIONS_UNAVAILABLE)
  222642. {
  222643. HeapBlock <NSSize> advances (length);
  222644. [nsFont getAdvancements: advances forGlyphs: reinterpret_cast<NSGlyph*> (glyphs.getData()) count: length];
  222645. for (int i = 0; i < length; ++i)
  222646. x += advances[i].width;
  222647. }
  222648. else
  222649. #endif
  222650. {
  222651. HeapBlock <int> advances (length);
  222652. if (CGFontGetGlyphAdvances (fontRef, glyphs, length, advances))
  222653. for (int i = 0; i < length; ++i)
  222654. x += advances[i];
  222655. }
  222656. #endif
  222657. return x * unitsToHeightScaleFactor;
  222658. }
  222659. void getGlyphPositions (const String& text, Array <int>& resultGlyphs, Array <float>& xOffsets)
  222660. {
  222661. xOffsets.add (0);
  222662. if (fontRef == 0 || text.isEmpty())
  222663. return;
  222664. const int length = text.length();
  222665. HeapBlock <CGGlyph> glyphs;
  222666. createGlyphsForString (text, length, glyphs);
  222667. #if SUPPORT_ONLY_10_4_FONTS
  222668. HeapBlock <NSSize> advances (length);
  222669. [nsFont getAdvancements: advances forGlyphs: reinterpret_cast <NSGlyph*> (glyphs.getData()) count: length];
  222670. int x = 0;
  222671. for (int i = 0; i < length; ++i)
  222672. {
  222673. x += advances[i].width;
  222674. xOffsets.add (x * unitsToHeightScaleFactor);
  222675. resultGlyphs.add (reinterpret_cast <NSGlyph*> (glyphs.getData())[i]);
  222676. }
  222677. #else
  222678. #if SUPPORT_10_4_FONTS
  222679. if (NEW_CGFONT_FUNCTIONS_UNAVAILABLE)
  222680. {
  222681. HeapBlock <NSSize> advances (length);
  222682. NSGlyph* const nsGlyphs = reinterpret_cast<NSGlyph*> (glyphs.getData());
  222683. [nsFont getAdvancements: advances forGlyphs: nsGlyphs count: length];
  222684. float x = 0;
  222685. for (int i = 0; i < length; ++i)
  222686. {
  222687. x += advances[i].width;
  222688. xOffsets.add (x * unitsToHeightScaleFactor);
  222689. resultGlyphs.add (nsGlyphs[i]);
  222690. }
  222691. }
  222692. else
  222693. #endif
  222694. {
  222695. HeapBlock <int> advances (length);
  222696. if (CGFontGetGlyphAdvances (fontRef, glyphs, length, advances))
  222697. {
  222698. int x = 0;
  222699. for (int i = 0; i < length; ++i)
  222700. {
  222701. x += advances [i];
  222702. xOffsets.add (x * unitsToHeightScaleFactor);
  222703. resultGlyphs.add (glyphs[i]);
  222704. }
  222705. }
  222706. }
  222707. #endif
  222708. }
  222709. bool getOutlineForGlyph (int glyphNumber, Path& path)
  222710. {
  222711. #if JUCE_IPHONE
  222712. return false;
  222713. #else
  222714. if (nsFont == 0)
  222715. return false;
  222716. // we might need to apply a transform to the path, so it mustn't have anything else in it
  222717. jassert (path.isEmpty());
  222718. const ScopedAutoReleasePool pool;
  222719. NSBezierPath* bez = [NSBezierPath bezierPath];
  222720. [bez moveToPoint: NSMakePoint (0, 0)];
  222721. [bez appendBezierPathWithGlyph: (NSGlyph) glyphNumber
  222722. inFont: nsFont];
  222723. for (int i = 0; i < [bez elementCount]; ++i)
  222724. {
  222725. NSPoint p[3];
  222726. switch ([bez elementAtIndex: i associatedPoints: p])
  222727. {
  222728. case NSMoveToBezierPathElement:
  222729. path.startNewSubPath ((float) p[0].x, (float) -p[0].y);
  222730. break;
  222731. case NSLineToBezierPathElement:
  222732. path.lineTo ((float) p[0].x, (float) -p[0].y);
  222733. break;
  222734. case NSCurveToBezierPathElement:
  222735. path.cubicTo ((float) p[0].x, (float) -p[0].y, (float) p[1].x, (float) -p[1].y, (float) p[2].x, (float) -p[2].y);
  222736. break;
  222737. case NSClosePathBezierPathElement:
  222738. path.closeSubPath();
  222739. break;
  222740. default:
  222741. jassertfalse
  222742. break;
  222743. }
  222744. }
  222745. path.applyTransform (pathTransform);
  222746. return true;
  222747. #endif
  222748. }
  222749. juce_UseDebuggingNewOperator
  222750. CGFontRef fontRef;
  222751. float fontHeightToCGSizeFactor;
  222752. CGAffineTransform renderingTransform;
  222753. private:
  222754. float ascent, unitsToHeightScaleFactor;
  222755. #if JUCE_IPHONE
  222756. #else
  222757. NSFont* nsFont;
  222758. AffineTransform pathTransform;
  222759. #endif
  222760. void createGlyphsForString (const juce_wchar* const text, const int length, HeapBlock <CGGlyph>& glyphs)
  222761. {
  222762. #if SUPPORT_10_4_FONTS
  222763. #if ! SUPPORT_ONLY_10_4_FONTS
  222764. if (NEW_CGFONT_FUNCTIONS_UNAVAILABLE)
  222765. #endif
  222766. {
  222767. glyphs.malloc (sizeof (NSGlyph) * length, 1);
  222768. NSGlyph* const nsGlyphs = reinterpret_cast<NSGlyph*> (glyphs.getData());
  222769. for (int i = 0; i < length; ++i)
  222770. nsGlyphs[i] = (NSGlyph) [nsFont _defaultGlyphForChar: text[i]];
  222771. return;
  222772. }
  222773. #endif
  222774. #if ! SUPPORT_ONLY_10_4_FONTS
  222775. if (charToGlyphMapper == 0)
  222776. charToGlyphMapper = new CharToGlyphMapper (fontRef);
  222777. glyphs.malloc (length);
  222778. for (int i = 0; i < length; ++i)
  222779. glyphs[i] = (CGGlyph) charToGlyphMapper->getGlyphForCharacter (text[i]);
  222780. #endif
  222781. }
  222782. #if ! SUPPORT_ONLY_10_4_FONTS
  222783. // Reads a CGFontRef's character map table to convert unicode into glyph numbers
  222784. class CharToGlyphMapper
  222785. {
  222786. public:
  222787. CharToGlyphMapper (CGFontRef fontRef)
  222788. : segCount (0), endCode (0), startCode (0), idDelta (0),
  222789. idRangeOffset (0), glyphIndexes (0)
  222790. {
  222791. CFDataRef cmapTable = CGFontCopyTableForTag (fontRef, 'cmap');
  222792. if (cmapTable != 0)
  222793. {
  222794. const int numSubtables = getValue16 (cmapTable, 2);
  222795. for (int i = 0; i < numSubtables; ++i)
  222796. {
  222797. if (getValue16 (cmapTable, i * 8 + 4) == 0) // check for platform ID of 0
  222798. {
  222799. const int offset = getValue32 (cmapTable, i * 8 + 8);
  222800. if (getValue16 (cmapTable, offset) == 4) // check that it's format 4..
  222801. {
  222802. const int length = getValue16 (cmapTable, offset + 2);
  222803. const int segCountX2 = getValue16 (cmapTable, offset + 6);
  222804. segCount = segCountX2 / 2;
  222805. const int endCodeOffset = offset + 14;
  222806. const int startCodeOffset = endCodeOffset + 2 + segCountX2;
  222807. const int idDeltaOffset = startCodeOffset + segCountX2;
  222808. const int idRangeOffsetOffset = idDeltaOffset + segCountX2;
  222809. const int glyphIndexesOffset = idRangeOffsetOffset + segCountX2;
  222810. endCode = CFDataCreate (kCFAllocatorDefault, CFDataGetBytePtr (cmapTable) + endCodeOffset, segCountX2);
  222811. startCode = CFDataCreate (kCFAllocatorDefault, CFDataGetBytePtr (cmapTable) + startCodeOffset, segCountX2);
  222812. idDelta = CFDataCreate (kCFAllocatorDefault, CFDataGetBytePtr (cmapTable) + idDeltaOffset, segCountX2);
  222813. idRangeOffset = CFDataCreate (kCFAllocatorDefault, CFDataGetBytePtr (cmapTable) + idRangeOffsetOffset, segCountX2);
  222814. glyphIndexes = CFDataCreate (kCFAllocatorDefault, CFDataGetBytePtr (cmapTable) + glyphIndexesOffset, offset + length - glyphIndexesOffset);
  222815. }
  222816. break;
  222817. }
  222818. }
  222819. CFRelease (cmapTable);
  222820. }
  222821. }
  222822. ~CharToGlyphMapper()
  222823. {
  222824. if (endCode != 0)
  222825. {
  222826. CFRelease (endCode);
  222827. CFRelease (startCode);
  222828. CFRelease (idDelta);
  222829. CFRelease (idRangeOffset);
  222830. CFRelease (glyphIndexes);
  222831. }
  222832. }
  222833. int getGlyphForCharacter (const juce_wchar c) const
  222834. {
  222835. for (int i = 0; i < segCount; ++i)
  222836. {
  222837. if (getValue16 (endCode, i * 2) >= c)
  222838. {
  222839. const int start = getValue16 (startCode, i * 2);
  222840. if (start > c)
  222841. break;
  222842. const int delta = getValue16 (idDelta, i * 2);
  222843. const int rangeOffset = getValue16 (idRangeOffset, i * 2);
  222844. if (rangeOffset == 0)
  222845. return delta + c;
  222846. else
  222847. return getValue16 (glyphIndexes, 2 * ((rangeOffset / 2) + (c - start) - (segCount - i)));
  222848. }
  222849. }
  222850. // If we failed to find it "properly", this dodgy fall-back seems to do the trick for most fonts!
  222851. return jmax (-1, c - 29);
  222852. }
  222853. private:
  222854. int segCount;
  222855. CFDataRef endCode, startCode, idDelta, idRangeOffset, glyphIndexes;
  222856. static uint16 getValue16 (CFDataRef data, const int index)
  222857. {
  222858. return CFSwapInt16BigToHost (*(UInt16*) (CFDataGetBytePtr (data) + index));
  222859. }
  222860. static uint32 getValue32 (CFDataRef data, const int index)
  222861. {
  222862. return CFSwapInt32BigToHost (*(UInt32*) (CFDataGetBytePtr (data) + index));
  222863. }
  222864. };
  222865. ScopedPointer <CharToGlyphMapper> charToGlyphMapper;
  222866. #endif
  222867. MacTypeface (const MacTypeface&);
  222868. MacTypeface& operator= (const MacTypeface&);
  222869. };
  222870. const Typeface::Ptr Typeface::createSystemTypefaceFor (const Font& font)
  222871. {
  222872. return new MacTypeface (font);
  222873. }
  222874. const StringArray Font::findAllTypefaceNames()
  222875. {
  222876. StringArray names;
  222877. const ScopedAutoReleasePool pool;
  222878. #if JUCE_IPHONE
  222879. NSArray* fonts = [UIFont familyNames];
  222880. #else
  222881. NSArray* fonts = [[NSFontManager sharedFontManager] availableFontFamilies];
  222882. #endif
  222883. for (unsigned int i = 0; i < [fonts count]; ++i)
  222884. names.add (nsStringToJuce ((NSString*) [fonts objectAtIndex: i]));
  222885. names.sort (true);
  222886. return names;
  222887. }
  222888. void Font::getPlatformDefaultFontNames (String& defaultSans, String& defaultSerif, String& defaultFixed)
  222889. {
  222890. #if JUCE_IPHONE
  222891. defaultSans = "Helvetica";
  222892. defaultSerif = "Times New Roman";
  222893. defaultFixed = "Courier New";
  222894. #else
  222895. defaultSans = "Lucida Grande";
  222896. defaultSerif = "Times New Roman";
  222897. defaultFixed = "Monaco";
  222898. #endif
  222899. }
  222900. #endif
  222901. /*** End of inlined file: juce_mac_Fonts.mm ***/
  222902. /*** Start of inlined file: juce_mac_CoreGraphicsContext.mm ***/
  222903. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  222904. // compiled on its own).
  222905. #if JUCE_INCLUDED_FILE
  222906. class CoreGraphicsImage : public Image
  222907. {
  222908. public:
  222909. CoreGraphicsImage (const PixelFormat format_,
  222910. const int imageWidth_,
  222911. const int imageHeight_,
  222912. const bool clearImage)
  222913. : Image (format_, imageWidth_, imageHeight_, clearImage)
  222914. {
  222915. CGColorSpaceRef colourSpace = (format == Image::SingleChannel) ? CGColorSpaceCreateDeviceGray()
  222916. : CGColorSpaceCreateDeviceRGB();
  222917. context = CGBitmapContextCreate (imageData, imageWidth, imageHeight, 8, lineStride,
  222918. colourSpace, getCGImageFlags (*this));
  222919. CGColorSpaceRelease (colourSpace);
  222920. }
  222921. ~CoreGraphicsImage()
  222922. {
  222923. CGContextRelease (context);
  222924. }
  222925. LowLevelGraphicsContext* createLowLevelContext();
  222926. static CGImageRef createImage (const Image& juceImage, const bool forAlpha, CGColorSpaceRef colourSpace)
  222927. {
  222928. const CoreGraphicsImage* nativeImage = dynamic_cast <const CoreGraphicsImage*> (&juceImage);
  222929. if (nativeImage != 0 && (juceImage.getFormat() == Image::SingleChannel || ! forAlpha))
  222930. {
  222931. return CGBitmapContextCreateImage (nativeImage->context);
  222932. }
  222933. else
  222934. {
  222935. const Image::BitmapData srcData (juceImage, 0, 0, juceImage.getWidth(), juceImage.getHeight());
  222936. CGDataProviderRef provider = CGDataProviderCreateWithData (0, srcData.data, srcData.lineStride * srcData.height, 0);
  222937. CGImageRef imageRef = CGImageCreate (srcData.width, srcData.height,
  222938. 8, srcData.pixelStride * 8, srcData.lineStride,
  222939. colourSpace, getCGImageFlags (juceImage), provider,
  222940. 0, true, kCGRenderingIntentDefault);
  222941. CGDataProviderRelease (provider);
  222942. return imageRef;
  222943. }
  222944. }
  222945. #if JUCE_MAC
  222946. static NSImage* createNSImage (const Image& image)
  222947. {
  222948. const ScopedAutoReleasePool pool;
  222949. NSImage* im = [[NSImage alloc] init];
  222950. [im setSize: NSMakeSize (image.getWidth(), image.getHeight())];
  222951. [im lockFocus];
  222952. CGColorSpaceRef colourSpace = CGColorSpaceCreateDeviceRGB();
  222953. CGImageRef imageRef = createImage (image, false, colourSpace);
  222954. CGColorSpaceRelease (colourSpace);
  222955. CGContextRef cg = (CGContextRef) [[NSGraphicsContext currentContext] graphicsPort];
  222956. CGContextDrawImage (cg, CGRectMake (0, 0, image.getWidth(), image.getHeight()), imageRef);
  222957. CGImageRelease (imageRef);
  222958. [im unlockFocus];
  222959. return im;
  222960. }
  222961. #endif
  222962. CGContextRef context;
  222963. private:
  222964. static CGBitmapInfo getCGImageFlags (const Image& image)
  222965. {
  222966. #if JUCE_BIG_ENDIAN
  222967. return image.getFormat() == Image::ARGB ? (kCGImageAlphaPremultipliedFirst | kCGBitmapByteOrder32Big) : kCGBitmapByteOrderDefault;
  222968. #else
  222969. return image.getFormat() == Image::ARGB ? (kCGImageAlphaPremultipliedFirst | kCGBitmapByteOrder32Little) : kCGBitmapByteOrderDefault;
  222970. #endif
  222971. }
  222972. };
  222973. Image* Image::createNativeImage (const PixelFormat format, const int imageWidth, const int imageHeight, const bool clearImage)
  222974. {
  222975. #if USE_COREGRAPHICS_RENDERING
  222976. return new CoreGraphicsImage (format == RGB ? ARGB : format, imageWidth, imageHeight, clearImage);
  222977. #else
  222978. return new Image (format, imageWidth, imageHeight, clearImage);
  222979. #endif
  222980. }
  222981. class CoreGraphicsContext : public LowLevelGraphicsContext
  222982. {
  222983. public:
  222984. CoreGraphicsContext (CGContextRef context_, const float flipHeight_)
  222985. : context (context_),
  222986. flipHeight (flipHeight_),
  222987. state (new SavedState()),
  222988. numGradientLookupEntries (0)
  222989. {
  222990. CGContextRetain (context);
  222991. CGContextSaveGState(context);
  222992. CGContextSetShouldSmoothFonts (context, true);
  222993. CGContextSetShouldAntialias (context, true);
  222994. CGContextSetBlendMode (context, kCGBlendModeNormal);
  222995. rgbColourSpace = CGColorSpaceCreateDeviceRGB();
  222996. greyColourSpace = CGColorSpaceCreateDeviceGray();
  222997. gradientCallbacks.version = 0;
  222998. gradientCallbacks.evaluate = gradientCallback;
  222999. gradientCallbacks.releaseInfo = 0;
  223000. setFont (Font());
  223001. }
  223002. ~CoreGraphicsContext()
  223003. {
  223004. CGContextRestoreGState (context);
  223005. CGContextRelease (context);
  223006. CGColorSpaceRelease (rgbColourSpace);
  223007. CGColorSpaceRelease (greyColourSpace);
  223008. }
  223009. bool isVectorDevice() const { return false; }
  223010. void setOrigin (int x, int y)
  223011. {
  223012. CGContextTranslateCTM (context, x, -y);
  223013. }
  223014. bool clipToRectangle (const Rectangle<int>& r)
  223015. {
  223016. CGContextClipToRect (context, CGRectMake (r.getX(), flipHeight - r.getBottom(), r.getWidth(), r.getHeight()));
  223017. return ! isClipEmpty();
  223018. }
  223019. bool clipToRectangleList (const RectangleList& clipRegion)
  223020. {
  223021. if (clipRegion.isEmpty())
  223022. {
  223023. CGContextClipToRect (context, CGRectMake (0, 0, 0, 0));
  223024. return false;
  223025. }
  223026. else
  223027. {
  223028. const int numRects = clipRegion.getNumRectangles();
  223029. HeapBlock <CGRect> rects (numRects);
  223030. for (int i = 0; i < numRects; ++i)
  223031. {
  223032. const Rectangle<int>& r = clipRegion.getRectangle(i);
  223033. rects[i] = CGRectMake (r.getX(), flipHeight - r.getBottom(), r.getWidth(), r.getHeight());
  223034. }
  223035. CGContextClipToRects (context, rects, numRects);
  223036. return ! isClipEmpty();
  223037. }
  223038. }
  223039. void excludeClipRectangle (const Rectangle<int>& r)
  223040. {
  223041. RectangleList remaining (getClipBounds());
  223042. remaining.subtract (r);
  223043. clipToRectangleList (remaining);
  223044. }
  223045. void clipToPath (const Path& path, const AffineTransform& transform)
  223046. {
  223047. createPath (path, transform);
  223048. CGContextClip (context);
  223049. }
  223050. void clipToImageAlpha (const Image& sourceImage, const Rectangle<int>& srcClip, const AffineTransform& transform)
  223051. {
  223052. if (! transform.isSingularity())
  223053. {
  223054. ScopedPointer<Image> imageToDelete;
  223055. const Image* singleChannelImage = &sourceImage;
  223056. if (sourceImage.getFormat() != Image::SingleChannel)
  223057. {
  223058. imageToDelete = sourceImage.createCopyOfAlphaChannel();
  223059. singleChannelImage = imageToDelete;
  223060. }
  223061. CGImageRef image = CoreGraphicsImage::createImage (*singleChannelImage, true, greyColourSpace);
  223062. flip();
  223063. AffineTransform t (AffineTransform::scale (1.0f, -1.0f).translated (0, sourceImage.getHeight()).followedBy (transform));
  223064. applyTransform (t);
  223065. CGRect r = CGRectMake (srcClip.getX(), srcClip.getY(), srcClip.getWidth(), srcClip.getHeight());
  223066. CGContextClipToMask (context, r, image);
  223067. applyTransform (t.inverted());
  223068. flip();
  223069. CGImageRelease (image);
  223070. }
  223071. }
  223072. bool clipRegionIntersects (const Rectangle<int>& r)
  223073. {
  223074. return getClipBounds().intersects (r);
  223075. }
  223076. const Rectangle<int> getClipBounds() const
  223077. {
  223078. CGRect bounds = CGRectIntegral (CGContextGetClipBoundingBox (context));
  223079. return Rectangle<int> (roundToInt (bounds.origin.x),
  223080. roundToInt (flipHeight - (bounds.origin.y + bounds.size.height)),
  223081. roundToInt (bounds.size.width),
  223082. roundToInt (bounds.size.height));
  223083. }
  223084. bool isClipEmpty() const
  223085. {
  223086. return CGRectIsEmpty (CGContextGetClipBoundingBox (context));
  223087. }
  223088. void saveState()
  223089. {
  223090. CGContextSaveGState (context);
  223091. stateStack.add (new SavedState (*state));
  223092. }
  223093. void restoreState()
  223094. {
  223095. CGContextRestoreGState (context);
  223096. SavedState* const top = stateStack.getLast();
  223097. if (top != 0)
  223098. {
  223099. state = top;
  223100. stateStack.removeLast (1, false);
  223101. }
  223102. else
  223103. {
  223104. jassertfalse // trying to pop with an empty stack!
  223105. }
  223106. }
  223107. void setFill (const FillType& fillType)
  223108. {
  223109. state->fillType = fillType;
  223110. if (fillType.isColour())
  223111. {
  223112. CGContextSetRGBFillColor (context, fillType.colour.getFloatRed(), fillType.colour.getFloatGreen(),
  223113. fillType.colour.getFloatBlue(), fillType.colour.getFloatAlpha());
  223114. CGContextSetAlpha (context, 1.0f);
  223115. }
  223116. }
  223117. void setOpacity (float newOpacity)
  223118. {
  223119. state->fillType.setOpacity (newOpacity);
  223120. setFill (state->fillType);
  223121. }
  223122. void setInterpolationQuality (Graphics::ResamplingQuality quality)
  223123. {
  223124. CGContextSetInterpolationQuality (context, quality == Graphics::lowResamplingQuality
  223125. ? kCGInterpolationLow
  223126. : kCGInterpolationHigh);
  223127. }
  223128. void fillRect (const Rectangle<int>& r, const bool replaceExistingContents)
  223129. {
  223130. CGRect cgRect = CGRectMake (r.getX(), flipHeight - r.getBottom(), r.getWidth(), r.getHeight());
  223131. if (replaceExistingContents)
  223132. {
  223133. #if MAC_OS_X_VERSION_MAX_ALLOWED < MAC_OS_X_VERSION_10_5
  223134. CGContextClearRect (context, cgRect);
  223135. #else
  223136. #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
  223137. if (CGContextDrawLinearGradient == 0) // (just a way of checking whether we're running in 10.5 or later)
  223138. CGContextClearRect (context, cgRect);
  223139. else
  223140. #endif
  223141. CGContextSetBlendMode (context, kCGBlendModeCopy);
  223142. #endif
  223143. fillRect (r, false);
  223144. CGContextSetBlendMode (context, kCGBlendModeNormal);
  223145. }
  223146. else
  223147. {
  223148. if (state->fillType.isColour())
  223149. {
  223150. CGContextFillRect (context, cgRect);
  223151. }
  223152. else if (state->fillType.isGradient())
  223153. {
  223154. CGContextSaveGState (context);
  223155. CGContextClipToRect (context, cgRect);
  223156. drawGradient();
  223157. CGContextRestoreGState (context);
  223158. }
  223159. else
  223160. {
  223161. CGContextSaveGState (context);
  223162. CGContextClipToRect (context, cgRect);
  223163. drawImage (*(state->fillType.image), state->fillType.image->getBounds(), state->fillType.transform, true);
  223164. CGContextRestoreGState (context);
  223165. }
  223166. }
  223167. }
  223168. void fillPath (const Path& path, const AffineTransform& transform)
  223169. {
  223170. CGContextSaveGState (context);
  223171. if (state->fillType.isColour())
  223172. {
  223173. flip();
  223174. applyTransform (transform);
  223175. createPath (path);
  223176. if (path.isUsingNonZeroWinding())
  223177. CGContextFillPath (context);
  223178. else
  223179. CGContextEOFillPath (context);
  223180. }
  223181. else
  223182. {
  223183. createPath (path, transform);
  223184. if (path.isUsingNonZeroWinding())
  223185. CGContextClip (context);
  223186. else
  223187. CGContextEOClip (context);
  223188. if (state->fillType.isGradient())
  223189. drawGradient();
  223190. else
  223191. drawImage (*(state->fillType.image), state->fillType.image->getBounds(), state->fillType.transform, true);
  223192. }
  223193. CGContextRestoreGState (context);
  223194. }
  223195. void drawImage (const Image& sourceImage, const Rectangle<int>& srcClip,
  223196. const AffineTransform& transform, const bool fillEntireClipAsTiles)
  223197. {
  223198. jassert (sourceImage.getBounds().contains (srcClip));
  223199. CGImageRef fullImage = CoreGraphicsImage::createImage (sourceImage, false, rgbColourSpace);
  223200. CGImageRef image = fullImage;
  223201. if (srcClip != sourceImage.getBounds())
  223202. {
  223203. image = CGImageCreateWithImageInRect (fullImage, CGRectMake (srcClip.getX(), srcClip.getY(),
  223204. srcClip.getWidth(), srcClip.getHeight()));
  223205. CGImageRelease (fullImage);
  223206. }
  223207. CGContextSaveGState (context);
  223208. CGContextSetAlpha (context, state->fillType.getOpacity());
  223209. flip();
  223210. applyTransform (AffineTransform::scale (1.0f, -1.0f).translated (0, srcClip.getHeight()).followedBy (transform));
  223211. CGRect imageRect = CGRectMake (0, 0, srcClip.getWidth(), srcClip.getHeight());
  223212. if (fillEntireClipAsTiles)
  223213. {
  223214. #if JUCE_IPHONE
  223215. CGContextDrawTiledImage (context, imageRect, image);
  223216. #else
  223217. #if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_5
  223218. // There's a bug in CGContextDrawTiledImage that makes it incredibly slow
  223219. // if it's doing a transformation - it's quicker to just draw lots of images manually
  223220. if (CGContextDrawTiledImage != 0 && transform.isOnlyTranslation())
  223221. CGContextDrawTiledImage (context, imageRect, image);
  223222. else
  223223. #endif
  223224. {
  223225. // Fallback to manually doing a tiled fill on 10.4
  223226. CGRect clip = CGRectIntegral (CGContextGetClipBoundingBox (context));
  223227. const int iw = srcClip.getWidth();
  223228. const int ih = srcClip.getHeight();
  223229. int x = 0, y = 0;
  223230. while (x > clip.origin.x) x -= iw;
  223231. while (y > clip.origin.y) y -= ih;
  223232. const int right = (int) (clip.origin.x + clip.size.width);
  223233. const int bottom = (int) (clip.origin.y + clip.size.height);
  223234. while (y < bottom)
  223235. {
  223236. for (int x2 = x; x2 < right; x2 += iw)
  223237. CGContextDrawImage (context, CGRectMake (x2, y, iw, ih), image);
  223238. y += ih;
  223239. }
  223240. }
  223241. #endif
  223242. }
  223243. else
  223244. {
  223245. CGContextDrawImage (context, imageRect, image);
  223246. }
  223247. CGImageRelease (image); // (This causes a memory bug in iPhone sim 3.0 - try upgrading to a later version if you hit this)
  223248. CGContextRestoreGState (context);
  223249. }
  223250. void drawLine (double x1, double y1, double x2, double y2)
  223251. {
  223252. CGContextSetLineCap (context, kCGLineCapSquare);
  223253. CGContextSetLineWidth (context, 1.0f);
  223254. CGContextSetRGBStrokeColor (context,
  223255. state->fillType.colour.getFloatRed(), state->fillType.colour.getFloatGreen(),
  223256. state->fillType.colour.getFloatBlue(), state->fillType.colour.getFloatAlpha());
  223257. CGPoint line[] = { { (CGFloat) x1, flipHeight - (CGFloat) y1 },
  223258. { (CGFloat) x2, flipHeight - (CGFloat) y2 } };
  223259. CGContextStrokeLineSegments (context, line, 1);
  223260. }
  223261. void drawVerticalLine (const int x, double top, double bottom)
  223262. {
  223263. #if MAC_OS_X_VERSION_MIN_REQUIRED > MAC_OS_X_VERSION_10_5
  223264. CGContextFillRect (context, CGRectMake (x, flipHeight - (float) bottom, 1.0f, (float) (bottom - top)));
  223265. #else
  223266. // On Leopard, unless both co-ordinates are non-integer, it disables anti-aliasing, so nudge
  223267. // the x co-ord slightly to trick it..
  223268. CGContextFillRect (context, CGRectMake (x + 1.0f / 256.0f, flipHeight - (float) bottom, 1.0f + 1.0f / 256.0f, (float) (bottom - top)));
  223269. #endif
  223270. }
  223271. void drawHorizontalLine (const int y, double left, double right)
  223272. {
  223273. #if MAC_OS_X_VERSION_MIN_REQUIRED > MAC_OS_X_VERSION_10_5
  223274. CGContextFillRect (context, CGRectMake ((float) left, flipHeight - (y + 1.0f), (float) (right - left), 1.0f));
  223275. #else
  223276. // On Leopard, unless both co-ordinates are non-integer, it disables anti-aliasing, so nudge
  223277. // the x co-ord slightly to trick it..
  223278. CGContextFillRect (context, CGRectMake ((float) left, flipHeight - (y + (1.0f + 1.0f / 256.0f)), (float) (right - left), 1.0f + 1.0f / 256.0f));
  223279. #endif
  223280. }
  223281. void setFont (const Font& newFont)
  223282. {
  223283. if (state->font != newFont)
  223284. {
  223285. state->fontRef = 0;
  223286. state->font = newFont;
  223287. MacTypeface* mf = dynamic_cast <MacTypeface*> (state->font.getTypeface());
  223288. if (mf != 0)
  223289. {
  223290. state->fontRef = mf->fontRef;
  223291. CGContextSetFont (context, state->fontRef);
  223292. CGContextSetFontSize (context, state->font.getHeight() * mf->fontHeightToCGSizeFactor);
  223293. state->fontTransform = mf->renderingTransform;
  223294. state->fontTransform.a *= state->font.getHorizontalScale();
  223295. CGContextSetTextMatrix (context, state->fontTransform);
  223296. }
  223297. }
  223298. }
  223299. const Font getFont()
  223300. {
  223301. return state->font;
  223302. }
  223303. void drawGlyph (int glyphNumber, const AffineTransform& transform)
  223304. {
  223305. if (state->fontRef != 0 && state->fillType.isColour())
  223306. {
  223307. if (transform.isOnlyTranslation())
  223308. {
  223309. CGGlyph g = glyphNumber;
  223310. CGContextShowGlyphsAtPoint (context, transform.getTranslationX(),
  223311. flipHeight - roundToInt (transform.getTranslationY()), &g, 1);
  223312. }
  223313. else
  223314. {
  223315. CGContextSaveGState (context);
  223316. flip();
  223317. applyTransform (transform);
  223318. CGAffineTransform t = state->fontTransform;
  223319. t.d = -t.d;
  223320. CGContextSetTextMatrix (context, t);
  223321. CGGlyph g = glyphNumber;
  223322. CGContextShowGlyphsAtPoint (context, 0, 0, &g, 1);
  223323. CGContextSetTextMatrix (context, state->fontTransform);
  223324. CGContextRestoreGState (context);
  223325. }
  223326. }
  223327. else
  223328. {
  223329. Path p;
  223330. Font& f = state->font;
  223331. f.getTypeface()->getOutlineForGlyph (glyphNumber, p);
  223332. fillPath (p, AffineTransform::scale (f.getHeight() * f.getHorizontalScale(), f.getHeight())
  223333. .followedBy (transform));
  223334. }
  223335. }
  223336. private:
  223337. CGContextRef context;
  223338. const CGFloat flipHeight;
  223339. CGColorSpaceRef rgbColourSpace, greyColourSpace;
  223340. CGFunctionCallbacks gradientCallbacks;
  223341. struct SavedState
  223342. {
  223343. SavedState()
  223344. : font (1.0f), fontRef (0), fontTransform (CGAffineTransformIdentity)
  223345. {
  223346. }
  223347. SavedState (const SavedState& other)
  223348. : fillType (other.fillType), font (other.font), fontRef (other.fontRef),
  223349. fontTransform (other.fontTransform)
  223350. {
  223351. }
  223352. ~SavedState()
  223353. {
  223354. }
  223355. FillType fillType;
  223356. Font font;
  223357. CGFontRef fontRef;
  223358. CGAffineTransform fontTransform;
  223359. };
  223360. ScopedPointer <SavedState> state;
  223361. OwnedArray <SavedState> stateStack;
  223362. HeapBlock <PixelARGB> gradientLookupTable;
  223363. int numGradientLookupEntries;
  223364. static void gradientCallback (void* info, const CGFloat* inData, CGFloat* outData)
  223365. {
  223366. const CoreGraphicsContext* const g = static_cast <const CoreGraphicsContext*> (info);
  223367. const int index = roundToInt (g->numGradientLookupEntries * inData[0]);
  223368. PixelARGB colour (g->gradientLookupTable [jlimit (0, g->numGradientLookupEntries, index)]);
  223369. colour.unpremultiply();
  223370. outData[0] = colour.getRed() / 255.0f;
  223371. outData[1] = colour.getGreen() / 255.0f;
  223372. outData[2] = colour.getBlue() / 255.0f;
  223373. outData[3] = colour.getAlpha() / 255.0f;
  223374. }
  223375. CGShadingRef createGradient (const AffineTransform& transform, ColourGradient gradient)
  223376. {
  223377. numGradientLookupEntries = gradient.createLookupTable (transform, gradientLookupTable);
  223378. --numGradientLookupEntries;
  223379. CGShadingRef result = 0;
  223380. CGFunctionRef function = CGFunctionCreate (this, 1, 0, 4, 0, &gradientCallbacks);
  223381. CGPoint p1 (CGPointMake (gradient.x1, gradient.y1));
  223382. if (gradient.isRadial)
  223383. {
  223384. result = CGShadingCreateRadial (rgbColourSpace, p1, 0,
  223385. p1, hypotf (gradient.x1 - gradient.x2, gradient.y1 - gradient.y2),
  223386. function, true, true);
  223387. }
  223388. else
  223389. {
  223390. result = CGShadingCreateAxial (rgbColourSpace, p1,
  223391. CGPointMake (gradient.x2, gradient.y2),
  223392. function, true, true);
  223393. }
  223394. CGFunctionRelease (function);
  223395. return result;
  223396. }
  223397. void drawGradient()
  223398. {
  223399. flip();
  223400. applyTransform (state->fillType.transform);
  223401. CGContextSetInterpolationQuality (context, kCGInterpolationDefault); // (This is required for 10.4, where there's a crash if
  223402. // you draw a gradient with high quality interp enabled).
  223403. CGShadingRef shading = createGradient (state->fillType.transform, *(state->fillType.gradient));
  223404. CGContextSetAlpha (context, state->fillType.getOpacity());
  223405. CGContextDrawShading (context, shading);
  223406. CGShadingRelease (shading);
  223407. }
  223408. void createPath (const Path& path) const
  223409. {
  223410. CGContextBeginPath (context);
  223411. Path::Iterator i (path);
  223412. while (i.next())
  223413. {
  223414. switch (i.elementType)
  223415. {
  223416. case Path::Iterator::startNewSubPath:
  223417. CGContextMoveToPoint (context, i.x1, i.y1);
  223418. break;
  223419. case Path::Iterator::lineTo:
  223420. CGContextAddLineToPoint (context, i.x1, i.y1);
  223421. break;
  223422. case Path::Iterator::quadraticTo:
  223423. CGContextAddQuadCurveToPoint (context, i.x1, i.y1, i.x2, i.y2);
  223424. break;
  223425. case Path::Iterator::cubicTo:
  223426. CGContextAddCurveToPoint (context, i.x1, i.y1, i.x2, i.y2, i.x3, i.y3);
  223427. break;
  223428. case Path::Iterator::closePath:
  223429. CGContextClosePath (context); break;
  223430. default:
  223431. jassertfalse
  223432. break;
  223433. }
  223434. }
  223435. }
  223436. void createPath (const Path& path, const AffineTransform& transform) const
  223437. {
  223438. CGContextBeginPath (context);
  223439. Path::Iterator i (path);
  223440. while (i.next())
  223441. {
  223442. switch (i.elementType)
  223443. {
  223444. case Path::Iterator::startNewSubPath:
  223445. transform.transformPoint (i.x1, i.y1);
  223446. CGContextMoveToPoint (context, i.x1, flipHeight - i.y1);
  223447. break;
  223448. case Path::Iterator::lineTo:
  223449. transform.transformPoint (i.x1, i.y1);
  223450. CGContextAddLineToPoint (context, i.x1, flipHeight - i.y1);
  223451. break;
  223452. case Path::Iterator::quadraticTo:
  223453. transform.transformPoint (i.x1, i.y1);
  223454. transform.transformPoint (i.x2, i.y2);
  223455. CGContextAddQuadCurveToPoint (context, i.x1, flipHeight - i.y1, i.x2, flipHeight - i.y2);
  223456. break;
  223457. case Path::Iterator::cubicTo:
  223458. transform.transformPoint (i.x1, i.y1);
  223459. transform.transformPoint (i.x2, i.y2);
  223460. transform.transformPoint (i.x3, i.y3);
  223461. CGContextAddCurveToPoint (context, i.x1, flipHeight - i.y1, i.x2, flipHeight - i.y2, i.x3, flipHeight - i.y3);
  223462. break;
  223463. case Path::Iterator::closePath:
  223464. CGContextClosePath (context); break;
  223465. default:
  223466. jassertfalse
  223467. break;
  223468. }
  223469. }
  223470. }
  223471. void flip() const
  223472. {
  223473. CGContextConcatCTM (context, CGAffineTransformMake (1, 0, 0, -1, 0, flipHeight));
  223474. }
  223475. void applyTransform (const AffineTransform& transform) const
  223476. {
  223477. CGAffineTransform t;
  223478. t.a = transform.mat00;
  223479. t.b = transform.mat10;
  223480. t.c = transform.mat01;
  223481. t.d = transform.mat11;
  223482. t.tx = transform.mat02;
  223483. t.ty = transform.mat12;
  223484. CGContextConcatCTM (context, t);
  223485. }
  223486. CoreGraphicsContext (const CoreGraphicsContext&);
  223487. CoreGraphicsContext& operator= (const CoreGraphicsContext&);
  223488. };
  223489. LowLevelGraphicsContext* CoreGraphicsImage::createLowLevelContext()
  223490. {
  223491. return new CoreGraphicsContext (context, imageHeight);
  223492. }
  223493. #endif
  223494. /*** End of inlined file: juce_mac_CoreGraphicsContext.mm ***/
  223495. /*** Start of inlined file: juce_iphone_UIViewComponentPeer.mm ***/
  223496. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  223497. // compiled on its own).
  223498. #if JUCE_INCLUDED_FILE
  223499. class UIViewComponentPeer;
  223500. END_JUCE_NAMESPACE
  223501. #define JuceUIView MakeObjCClassName(JuceUIView)
  223502. @interface JuceUIView : UIView <UITextFieldDelegate>
  223503. {
  223504. @public
  223505. UIViewComponentPeer* owner;
  223506. UITextField *hiddenTextField;
  223507. }
  223508. - (JuceUIView*) initWithOwner: (UIViewComponentPeer*) owner withFrame: (CGRect) frame;
  223509. - (void) dealloc;
  223510. - (void) drawRect: (CGRect) r;
  223511. - (void) touchesBegan: (NSSet*) touches withEvent: (UIEvent*) event;
  223512. - (void) touchesMoved: (NSSet*) touches withEvent: (UIEvent*) event;
  223513. - (void) touchesEnded: (NSSet*) touches withEvent: (UIEvent*) event;
  223514. - (void) touchesCancelled: (NSSet*) touches withEvent: (UIEvent*) event;
  223515. - (BOOL) becomeFirstResponder;
  223516. - (BOOL) resignFirstResponder;
  223517. - (BOOL) canBecomeFirstResponder;
  223518. - (void) asyncRepaint: (id) rect;
  223519. - (BOOL) textField: (UITextField*) textField shouldChangeCharactersInRange: (NSRange) range replacementString: (NSString*) string;
  223520. - (BOOL) textFieldShouldClear: (UITextField*) textField;
  223521. - (BOOL) textFieldShouldReturn: (UITextField*) textField;
  223522. @end
  223523. #define JuceUIWindow MakeObjCClassName(JuceUIWindow)
  223524. @interface JuceUIWindow : UIWindow
  223525. {
  223526. @private
  223527. UIViewComponentPeer* owner;
  223528. bool isZooming;
  223529. }
  223530. - (void) setOwner: (UIViewComponentPeer*) owner;
  223531. - (void) becomeKeyWindow;
  223532. @end
  223533. BEGIN_JUCE_NAMESPACE
  223534. class UIViewComponentPeer : public ComponentPeer,
  223535. public FocusChangeListener
  223536. {
  223537. public:
  223538. UIViewComponentPeer (Component* const component,
  223539. const int windowStyleFlags,
  223540. UIView* viewToAttachTo);
  223541. ~UIViewComponentPeer();
  223542. void* getNativeHandle() const;
  223543. void setVisible (bool shouldBeVisible);
  223544. void setTitle (const String& title);
  223545. void setPosition (int x, int y);
  223546. void setSize (int w, int h);
  223547. void setBounds (int x, int y, int w, int h, bool isNowFullScreen);
  223548. const Rectangle<int> getBounds() const;
  223549. const Rectangle<int> getBounds (const bool global) const;
  223550. const Point<int> getScreenPosition() const;
  223551. const Point<int> relativePositionToGlobal (const Point<int>& relativePosition);
  223552. const Point<int> globalPositionToRelative (const Point<int>& screenPosition);
  223553. void setMinimised (bool shouldBeMinimised);
  223554. bool isMinimised() const;
  223555. void setFullScreen (bool shouldBeFullScreen);
  223556. bool isFullScreen() const;
  223557. bool contains (const Point<int>& position, bool trueIfInAChildWindow) const;
  223558. const BorderSize getFrameSize() const;
  223559. bool setAlwaysOnTop (bool alwaysOnTop);
  223560. void toFront (bool makeActiveWindow);
  223561. void toBehind (ComponentPeer* other);
  223562. void setIcon (const Image& newIcon);
  223563. virtual void drawRect (CGRect r);
  223564. virtual bool canBecomeKeyWindow();
  223565. virtual bool windowShouldClose();
  223566. virtual void redirectMovedOrResized();
  223567. virtual CGRect constrainRect (CGRect r);
  223568. virtual void viewFocusGain();
  223569. virtual void viewFocusLoss();
  223570. bool isFocused() const;
  223571. void grabFocus();
  223572. void textInputRequired (const Point<int>& position);
  223573. virtual BOOL textFieldReplaceCharacters (const Range<int>& range, const String& text);
  223574. virtual BOOL textFieldShouldClear();
  223575. virtual BOOL textFieldShouldReturn();
  223576. void updateHiddenTextContent (TextInputTarget* target);
  223577. void globalFocusChanged (Component*);
  223578. void handleTouches (UIEvent* e, bool isDown, bool isUp, bool isCancel);
  223579. void repaint (int x, int y, int w, int h);
  223580. void performAnyPendingRepaintsNow();
  223581. juce_UseDebuggingNewOperator
  223582. UIWindow* window;
  223583. JuceUIView* view;
  223584. bool isSharedWindow, fullScreen, insideDrawRect;
  223585. static ModifierKeys currentModifiers;
  223586. static int64 getMouseTime (UIEvent* e)
  223587. {
  223588. return (Time::currentTimeMillis() - Time::getMillisecondCounter())
  223589. + (int64) ([e timestamp] * 1000.0);
  223590. }
  223591. Array <UITouch*> currentTouches;
  223592. };
  223593. END_JUCE_NAMESPACE
  223594. @implementation JuceUIView
  223595. - (JuceUIView*) initWithOwner: (UIViewComponentPeer*) owner_
  223596. withFrame: (CGRect) frame
  223597. {
  223598. [super initWithFrame: frame];
  223599. owner = owner_;
  223600. hiddenTextField = [[UITextField alloc] initWithFrame: CGRectMake (0, 0, 0, 0)];
  223601. [self addSubview: hiddenTextField];
  223602. hiddenTextField.delegate = self;
  223603. return self;
  223604. }
  223605. - (void) dealloc
  223606. {
  223607. [hiddenTextField removeFromSuperview];
  223608. [hiddenTextField release];
  223609. [super dealloc];
  223610. }
  223611. - (void) drawRect: (CGRect) r
  223612. {
  223613. if (owner != 0)
  223614. owner->drawRect (r);
  223615. }
  223616. bool KeyPress::isKeyCurrentlyDown (const int keyCode)
  223617. {
  223618. return false;
  223619. }
  223620. ModifierKeys UIViewComponentPeer::currentModifiers;
  223621. const ModifierKeys ModifierKeys::getCurrentModifiersRealtime() throw()
  223622. {
  223623. return UIViewComponentPeer::currentModifiers;
  223624. }
  223625. void ModifierKeys::updateCurrentModifiers() throw()
  223626. {
  223627. currentModifiers = UIViewComponentPeer::currentModifiers;
  223628. }
  223629. JUCE_NAMESPACE::Point<int> juce_lastMousePos;
  223630. - (void) touchesBegan: (NSSet*) touches withEvent: (UIEvent*) event
  223631. {
  223632. if (owner != 0)
  223633. owner->handleTouches (event, true, false, false);
  223634. }
  223635. - (void) touchesMoved: (NSSet*) touches withEvent: (UIEvent*) event
  223636. {
  223637. if (owner != 0)
  223638. owner->handleTouches (event, false, false, false);
  223639. }
  223640. - (void) touchesEnded: (NSSet*) touches withEvent: (UIEvent*) event
  223641. {
  223642. if (owner != 0)
  223643. owner->handleTouches (event, false, true, false);
  223644. }
  223645. - (void) touchesCancelled: (NSSet*) touches withEvent: (UIEvent*) event
  223646. {
  223647. if (owner != 0)
  223648. owner->handleTouches (event, false, true, true);
  223649. [self touchesEnded: touches withEvent: event];
  223650. }
  223651. - (BOOL) becomeFirstResponder
  223652. {
  223653. if (owner != 0)
  223654. owner->viewFocusGain();
  223655. return true;
  223656. }
  223657. - (BOOL) resignFirstResponder
  223658. {
  223659. if (owner != 0)
  223660. owner->viewFocusLoss();
  223661. return true;
  223662. }
  223663. - (BOOL) canBecomeFirstResponder
  223664. {
  223665. return owner != 0 && owner->canBecomeKeyWindow();
  223666. }
  223667. - (void) asyncRepaint: (id) rect
  223668. {
  223669. CGRect* r = (CGRect*) [((NSData*) rect) bytes];
  223670. [self setNeedsDisplayInRect: *r];
  223671. }
  223672. - (BOOL) textField: (UITextField*) textField shouldChangeCharactersInRange: (NSRange) range replacementString: (NSString*) text
  223673. {
  223674. return owner->textFieldReplaceCharacters (Range<int> (range.location, range.location + range.length),
  223675. nsStringToJuce (text));
  223676. }
  223677. - (BOOL) textFieldShouldClear: (UITextField*) textField
  223678. {
  223679. return owner->textFieldShouldClear();
  223680. }
  223681. - (BOOL) textFieldShouldReturn: (UITextField*) textField
  223682. {
  223683. return owner->textFieldShouldReturn();
  223684. }
  223685. @end
  223686. @implementation JuceUIWindow
  223687. - (void) setOwner: (UIViewComponentPeer*) owner_
  223688. {
  223689. owner = owner_;
  223690. isZooming = false;
  223691. }
  223692. - (void) becomeKeyWindow
  223693. {
  223694. [super becomeKeyWindow];
  223695. if (owner != 0)
  223696. owner->grabFocus();
  223697. }
  223698. @end
  223699. BEGIN_JUCE_NAMESPACE
  223700. UIViewComponentPeer::UIViewComponentPeer (Component* const component,
  223701. const int windowStyleFlags,
  223702. UIView* viewToAttachTo)
  223703. : ComponentPeer (component, windowStyleFlags),
  223704. window (0),
  223705. view (0),
  223706. isSharedWindow (viewToAttachTo != 0),
  223707. fullScreen (false),
  223708. insideDrawRect (false)
  223709. {
  223710. CGRect r = CGRectMake (0, 0, (float) component->getWidth(), (float) component->getHeight());
  223711. view = [[JuceUIView alloc] initWithOwner: this withFrame: r];
  223712. if (isSharedWindow)
  223713. {
  223714. window = [viewToAttachTo window];
  223715. [viewToAttachTo addSubview: view];
  223716. setVisible (component->isVisible());
  223717. }
  223718. else
  223719. {
  223720. r.origin.x = (float) component->getX();
  223721. r.origin.y = (float) component->getY();
  223722. r.origin.y = [[UIScreen mainScreen] bounds].size.height - (r.origin.y + r.size.height);
  223723. window = [[JuceUIWindow alloc] init];
  223724. window.frame = r;
  223725. window.opaque = component->isOpaque();
  223726. view.opaque = component->isOpaque();
  223727. window.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent: 0];
  223728. view.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent: 0];
  223729. [((JuceUIWindow*) window) setOwner: this];
  223730. if (component->isAlwaysOnTop())
  223731. window.windowLevel = UIWindowLevelAlert;
  223732. [window addSubview: view];
  223733. view.frame = CGRectMake (0, 0, r.size.width, r.size.height);
  223734. view.hidden = ! component->isVisible();
  223735. window.hidden = ! component->isVisible();
  223736. view.multipleTouchEnabled = YES;
  223737. }
  223738. setTitle (component->getName());
  223739. Desktop::getInstance().addFocusChangeListener (this);
  223740. }
  223741. UIViewComponentPeer::~UIViewComponentPeer()
  223742. {
  223743. Desktop::getInstance().removeFocusChangeListener (this);
  223744. view->owner = 0;
  223745. [view removeFromSuperview];
  223746. [view release];
  223747. if (! isSharedWindow)
  223748. {
  223749. [((JuceUIWindow*) window) setOwner: 0];
  223750. [window release];
  223751. }
  223752. }
  223753. void* UIViewComponentPeer::getNativeHandle() const
  223754. {
  223755. return view;
  223756. }
  223757. void UIViewComponentPeer::setVisible (bool shouldBeVisible)
  223758. {
  223759. view.hidden = ! shouldBeVisible;
  223760. if (! isSharedWindow)
  223761. window.hidden = ! shouldBeVisible;
  223762. }
  223763. void UIViewComponentPeer::setTitle (const String& title)
  223764. {
  223765. // xxx is this possible?
  223766. }
  223767. void UIViewComponentPeer::setPosition (int x, int y)
  223768. {
  223769. setBounds (x, y, component->getWidth(), component->getHeight(), false);
  223770. }
  223771. void UIViewComponentPeer::setSize (int w, int h)
  223772. {
  223773. setBounds (component->getX(), component->getY(), w, h, false);
  223774. }
  223775. void UIViewComponentPeer::setBounds (int x, int y, int w, int h, const bool isNowFullScreen)
  223776. {
  223777. fullScreen = isNowFullScreen;
  223778. w = jmax (0, w);
  223779. h = jmax (0, h);
  223780. CGRect r;
  223781. r.origin.x = (float) x;
  223782. r.origin.y = (float) y;
  223783. r.size.width = (float) w;
  223784. r.size.height = (float) h;
  223785. if (isSharedWindow)
  223786. {
  223787. //r.origin.y = [[view superview] frame].size.height - (r.origin.y + r.size.height);
  223788. if ([view frame].size.width != r.size.width
  223789. || [view frame].size.height != r.size.height)
  223790. [view setNeedsDisplay];
  223791. view.frame = r;
  223792. }
  223793. else
  223794. {
  223795. window.frame = r;
  223796. view.frame = CGRectMake (0, 0, r.size.width, r.size.height);
  223797. }
  223798. }
  223799. const Rectangle<int> UIViewComponentPeer::getBounds (const bool global) const
  223800. {
  223801. CGRect r = [view frame];
  223802. if (global && [view window] != 0)
  223803. {
  223804. r = [view convertRect: r toView: nil];
  223805. CGRect wr = [[view window] frame];
  223806. r.origin.x += wr.origin.x;
  223807. r.origin.y += wr.origin.y;
  223808. }
  223809. return Rectangle<int> ((int) r.origin.x, (int) r.origin.y,
  223810. (int) r.size.width, (int) r.size.height);
  223811. }
  223812. const Rectangle<int> UIViewComponentPeer::getBounds() const
  223813. {
  223814. return getBounds (! isSharedWindow);
  223815. }
  223816. const Point<int> UIViewComponentPeer::getScreenPosition() const
  223817. {
  223818. return getBounds (true).getPosition();
  223819. }
  223820. const Point<int> UIViewComponentPeer::relativePositionToGlobal (const Point<int>& relativePosition)
  223821. {
  223822. return relativePosition + getScreenPosition();
  223823. }
  223824. const Point<int> UIViewComponentPeer::globalPositionToRelative (const Point<int>& screenPosition)
  223825. {
  223826. return screenPosition - getScreenPosition();
  223827. }
  223828. CGRect UIViewComponentPeer::constrainRect (CGRect r)
  223829. {
  223830. if (constrainer != 0)
  223831. {
  223832. CGRect current = [window frame];
  223833. current.origin.y = [[UIScreen mainScreen] bounds].size.height - current.origin.y - current.size.height;
  223834. r.origin.y = [[UIScreen mainScreen] bounds].size.height - r.origin.y - r.size.height;
  223835. Rectangle<int> pos ((int) r.origin.x, (int) r.origin.y,
  223836. (int) r.size.width, (int) r.size.height);
  223837. Rectangle<int> original ((int) current.origin.x, (int) current.origin.y,
  223838. (int) current.size.width, (int) current.size.height);
  223839. constrainer->checkBounds (pos, original,
  223840. Desktop::getInstance().getAllMonitorDisplayAreas().getBounds(),
  223841. pos.getY() != original.getY() && pos.getBottom() == original.getBottom(),
  223842. pos.getX() != original.getX() && pos.getRight() == original.getRight(),
  223843. pos.getY() == original.getY() && pos.getBottom() != original.getBottom(),
  223844. pos.getX() == original.getX() && pos.getRight() != original.getRight());
  223845. r.origin.x = pos.getX();
  223846. r.origin.y = [[UIScreen mainScreen] bounds].size.height - r.size.height - pos.getY();
  223847. r.size.width = pos.getWidth();
  223848. r.size.height = pos.getHeight();
  223849. }
  223850. return r;
  223851. }
  223852. void UIViewComponentPeer::setMinimised (bool shouldBeMinimised)
  223853. {
  223854. // xxx
  223855. }
  223856. bool UIViewComponentPeer::isMinimised() const
  223857. {
  223858. return false;
  223859. }
  223860. void UIViewComponentPeer::setFullScreen (bool shouldBeFullScreen)
  223861. {
  223862. if (! isSharedWindow)
  223863. {
  223864. Rectangle<int> r (lastNonFullscreenBounds);
  223865. setMinimised (false);
  223866. if (fullScreen != shouldBeFullScreen)
  223867. {
  223868. if (shouldBeFullScreen)
  223869. r = Desktop::getInstance().getMainMonitorArea();
  223870. // (can't call the component's setBounds method because that'll reset our fullscreen flag)
  223871. if (r != getComponent()->getBounds() && ! r.isEmpty())
  223872. setBounds (r.getX(), r.getY(), r.getWidth(), r.getHeight(), shouldBeFullScreen);
  223873. }
  223874. }
  223875. }
  223876. bool UIViewComponentPeer::isFullScreen() const
  223877. {
  223878. return fullScreen;
  223879. }
  223880. bool UIViewComponentPeer::contains (const Point<int>& position, bool trueIfInAChildWindow) const
  223881. {
  223882. if (((unsigned int) position.getX()) >= (unsigned int) component->getWidth()
  223883. || ((unsigned int) position.getY()) >= (unsigned int) component->getHeight())
  223884. return false;
  223885. CGPoint p;
  223886. p.x = (float) position.getX();
  223887. p.y = (float) position.getY();
  223888. UIView* v = [view hitTest: p withEvent: nil];
  223889. if (trueIfInAChildWindow)
  223890. return v != nil;
  223891. return v == view;
  223892. }
  223893. const BorderSize UIViewComponentPeer::getFrameSize() const
  223894. {
  223895. BorderSize b;
  223896. if (! isSharedWindow)
  223897. {
  223898. CGRect v = [view convertRect: [view frame] toView: nil];
  223899. CGRect w = [window frame];
  223900. b.setTop ((int) (w.size.height - (v.origin.y + v.size.height)));
  223901. b.setBottom ((int) v.origin.y);
  223902. b.setLeft ((int) v.origin.x);
  223903. b.setRight ((int) (w.size.width - (v.origin.x + v.size.width)));
  223904. }
  223905. return b;
  223906. }
  223907. bool UIViewComponentPeer::setAlwaysOnTop (bool alwaysOnTop)
  223908. {
  223909. if (! isSharedWindow)
  223910. window.windowLevel = alwaysOnTop ? UIWindowLevelAlert : UIWindowLevelNormal;
  223911. return true;
  223912. }
  223913. void UIViewComponentPeer::toFront (bool makeActiveWindow)
  223914. {
  223915. if (isSharedWindow)
  223916. [[view superview] bringSubviewToFront: view];
  223917. if (window != 0 && component->isVisible())
  223918. [window makeKeyAndVisible];
  223919. }
  223920. void UIViewComponentPeer::toBehind (ComponentPeer* other)
  223921. {
  223922. UIViewComponentPeer* const otherPeer = dynamic_cast <UIViewComponentPeer*> (other);
  223923. jassert (otherPeer != 0); // wrong type of window?
  223924. if (otherPeer != 0)
  223925. {
  223926. if (isSharedWindow)
  223927. {
  223928. [[view superview] insertSubview: view belowSubview: otherPeer->view];
  223929. }
  223930. else
  223931. {
  223932. jassertfalse // don't know how to do this
  223933. }
  223934. }
  223935. }
  223936. void UIViewComponentPeer::setIcon (const Image& /*newIcon*/)
  223937. {
  223938. // to do..
  223939. }
  223940. void UIViewComponentPeer::handleTouches (UIEvent* event, const bool isDown, const bool isUp, bool isCancel)
  223941. {
  223942. NSArray* touches = [[event touchesForView: view] allObjects];
  223943. for (unsigned int i = 0; i < [touches count]; ++i)
  223944. {
  223945. UITouch* touch = [touches objectAtIndex: i];
  223946. CGPoint p = [touch locationInView: view];
  223947. const Point<int> pos ((int) p.x, (int) p.y);
  223948. juce_lastMousePos = pos + getScreenPosition();
  223949. const int64 time = getMouseTime (event);
  223950. int touchIndex = currentTouches.indexOf (touch);
  223951. if (touchIndex < 0)
  223952. {
  223953. touchIndex = currentTouches.size();
  223954. currentTouches.add (touch);
  223955. }
  223956. if (isDown)
  223957. {
  223958. currentModifiers = currentModifiers.withoutMouseButtons();
  223959. handleMouseEvent (touchIndex, pos, currentModifiers, time);
  223960. currentModifiers = currentModifiers.withoutMouseButtons().withFlags (ModifierKeys::leftButtonModifier);
  223961. }
  223962. else if (isUp)
  223963. {
  223964. currentModifiers = currentModifiers.withoutMouseButtons();
  223965. currentTouches.remove (touchIndex);
  223966. }
  223967. if (isCancel)
  223968. currentTouches.clear();
  223969. handleMouseEvent (touchIndex, pos, currentModifiers, time);
  223970. }
  223971. }
  223972. static UIViewComponentPeer* currentlyFocusedPeer = 0;
  223973. void UIViewComponentPeer::viewFocusGain()
  223974. {
  223975. if (currentlyFocusedPeer != this)
  223976. {
  223977. if (ComponentPeer::isValidPeer (currentlyFocusedPeer))
  223978. currentlyFocusedPeer->handleFocusLoss();
  223979. currentlyFocusedPeer = this;
  223980. handleFocusGain();
  223981. }
  223982. }
  223983. void UIViewComponentPeer::viewFocusLoss()
  223984. {
  223985. if (currentlyFocusedPeer == this)
  223986. {
  223987. currentlyFocusedPeer = 0;
  223988. handleFocusLoss();
  223989. }
  223990. }
  223991. void juce_HandleProcessFocusChange()
  223992. {
  223993. if (UIViewComponentPeer::isValidPeer (currentlyFocusedPeer))
  223994. {
  223995. if (Process::isForegroundProcess())
  223996. {
  223997. currentlyFocusedPeer->handleFocusGain();
  223998. ComponentPeer::bringModalComponentToFront();
  223999. }
  224000. else
  224001. {
  224002. currentlyFocusedPeer->handleFocusLoss();
  224003. // turn kiosk mode off if we lose focus..
  224004. Desktop::getInstance().setKioskModeComponent (0);
  224005. }
  224006. }
  224007. }
  224008. bool UIViewComponentPeer::isFocused() const
  224009. {
  224010. return isSharedWindow ? this == currentlyFocusedPeer
  224011. : (window != 0 && [window isKeyWindow]);
  224012. }
  224013. void UIViewComponentPeer::grabFocus()
  224014. {
  224015. if (window != 0)
  224016. {
  224017. [window makeKeyWindow];
  224018. viewFocusGain();
  224019. }
  224020. }
  224021. void UIViewComponentPeer::textInputRequired (const Point<int>&)
  224022. {
  224023. }
  224024. void UIViewComponentPeer::updateHiddenTextContent (TextInputTarget* target)
  224025. {
  224026. view->hiddenTextField.text = juceStringToNS (target->getTextInRange (Range<int> (0, target->getHighlightedRegion().getStart())));
  224027. }
  224028. BOOL UIViewComponentPeer::textFieldReplaceCharacters (const Range<int>& range, const String& text)
  224029. {
  224030. TextInputTarget* const target = findCurrentTextInputTarget();
  224031. if (target != 0)
  224032. {
  224033. const Range<int> currentSelection (target->getHighlightedRegion());
  224034. if (range.getLength() == 1 && text.isEmpty()) // (detect backspace)
  224035. if (currentSelection.isEmpty())
  224036. target->setHighlightedRegion (currentSelection.withStart (currentSelection.getStart() - 1));
  224037. target->insertTextAtCaret (text);
  224038. updateHiddenTextContent (target);
  224039. }
  224040. return NO;
  224041. }
  224042. BOOL UIViewComponentPeer::textFieldShouldClear()
  224043. {
  224044. TextInputTarget* const target = findCurrentTextInputTarget();
  224045. if (target != 0)
  224046. {
  224047. target->setHighlightedRegion (Range<int> (0, std::numeric_limits<int>::max()));
  224048. target->insertTextAtCaret (String::empty);
  224049. updateHiddenTextContent (target);
  224050. }
  224051. return YES;
  224052. }
  224053. BOOL UIViewComponentPeer::textFieldShouldReturn()
  224054. {
  224055. TextInputTarget* const target = findCurrentTextInputTarget();
  224056. if (target != 0)
  224057. {
  224058. target->insertTextAtCaret ("\n");
  224059. updateHiddenTextContent (target);
  224060. }
  224061. return YES;
  224062. }
  224063. void UIViewComponentPeer::globalFocusChanged (Component*)
  224064. {
  224065. TextInputTarget* const target = findCurrentTextInputTarget();
  224066. if (target != 0)
  224067. {
  224068. Component* comp = dynamic_cast<Component*> (target);
  224069. Point<int> pos (comp->relativePositionToOtherComponent (component, Point<int>()));
  224070. view->hiddenTextField.frame = CGRectMake (pos.getX(), pos.getY(), 0, 0);
  224071. updateHiddenTextContent (target);
  224072. [view->hiddenTextField becomeFirstResponder];
  224073. }
  224074. else
  224075. {
  224076. [view->hiddenTextField resignFirstResponder];
  224077. }
  224078. }
  224079. void UIViewComponentPeer::drawRect (CGRect r)
  224080. {
  224081. if (r.size.width < 1.0f || r.size.height < 1.0f)
  224082. return;
  224083. CGContextRef cg = UIGraphicsGetCurrentContext();
  224084. if (! component->isOpaque())
  224085. CGContextClearRect (cg, CGContextGetClipBoundingBox (cg));
  224086. CGContextConcatCTM (cg, CGAffineTransformMake (1, 0, 0, -1, 0, view.bounds.size.height));
  224087. CoreGraphicsContext g (cg, view.bounds.size.height);
  224088. insideDrawRect = true;
  224089. handlePaint (g);
  224090. insideDrawRect = false;
  224091. }
  224092. bool UIViewComponentPeer::canBecomeKeyWindow()
  224093. {
  224094. return (getStyleFlags() & JUCE_NAMESPACE::ComponentPeer::windowIgnoresKeyPresses) == 0;
  224095. }
  224096. bool UIViewComponentPeer::windowShouldClose()
  224097. {
  224098. if (! isValidPeer (this))
  224099. return YES;
  224100. handleUserClosingWindow();
  224101. return NO;
  224102. }
  224103. void UIViewComponentPeer::redirectMovedOrResized()
  224104. {
  224105. handleMovedOrResized();
  224106. }
  224107. void juce_setKioskComponent (Component* kioskModeComponent, bool enableOrDisable, bool allowMenusAndBars)
  224108. {
  224109. }
  224110. class AsyncRepaintMessage : public CallbackMessage
  224111. {
  224112. public:
  224113. UIViewComponentPeer* const peer;
  224114. const Rectangle<int> rect;
  224115. AsyncRepaintMessage (UIViewComponentPeer* const peer_, const Rectangle<int>& rect_)
  224116. : peer (peer_), rect (rect_)
  224117. {
  224118. }
  224119. void messageCallback()
  224120. {
  224121. if (ComponentPeer::isValidPeer (peer))
  224122. peer->repaint (rect.getX(), rect.getY(), rect.getWidth(), rect.getHeight());
  224123. }
  224124. };
  224125. void UIViewComponentPeer::repaint (int x, int y, int w, int h)
  224126. {
  224127. if (insideDrawRect || ! MessageManager::getInstance()->isThisTheMessageThread())
  224128. {
  224129. (new AsyncRepaintMessage (this, Rectangle<int> (x, y, w, h)))->post();
  224130. }
  224131. else
  224132. {
  224133. [view setNeedsDisplayInRect: CGRectMake ((float) x, (float) y, (float) w, (float) h)];
  224134. }
  224135. }
  224136. void UIViewComponentPeer::performAnyPendingRepaintsNow()
  224137. {
  224138. }
  224139. ComponentPeer* Component::createNewPeer (int styleFlags, void* windowToAttachTo)
  224140. {
  224141. return new UIViewComponentPeer (this, styleFlags, (UIView*) windowToAttachTo);
  224142. }
  224143. Image* juce_createIconForFile (const File& file)
  224144. {
  224145. return 0;
  224146. }
  224147. void Desktop::createMouseInputSources()
  224148. {
  224149. for (int i = 0; i < 10; ++i)
  224150. mouseSources.add (new MouseInputSource (i, false));
  224151. }
  224152. bool Desktop::canUseSemiTransparentWindows() throw()
  224153. {
  224154. return true;
  224155. }
  224156. const Point<int> Desktop::getMousePosition()
  224157. {
  224158. return juce_lastMousePos;
  224159. }
  224160. void Desktop::setMousePosition (const Point<int>&)
  224161. {
  224162. }
  224163. const int KeyPress::spaceKey = ' ';
  224164. const int KeyPress::returnKey = 0x0d;
  224165. const int KeyPress::escapeKey = 0x1b;
  224166. const int KeyPress::backspaceKey = 0x7f;
  224167. const int KeyPress::leftKey = 0x1000;
  224168. const int KeyPress::rightKey = 0x1001;
  224169. const int KeyPress::upKey = 0x1002;
  224170. const int KeyPress::downKey = 0x1003;
  224171. const int KeyPress::pageUpKey = 0x1004;
  224172. const int KeyPress::pageDownKey = 0x1005;
  224173. const int KeyPress::endKey = 0x1006;
  224174. const int KeyPress::homeKey = 0x1007;
  224175. const int KeyPress::deleteKey = 0x1008;
  224176. const int KeyPress::insertKey = -1;
  224177. const int KeyPress::tabKey = 9;
  224178. const int KeyPress::F1Key = 0x2001;
  224179. const int KeyPress::F2Key = 0x2002;
  224180. const int KeyPress::F3Key = 0x2003;
  224181. const int KeyPress::F4Key = 0x2004;
  224182. const int KeyPress::F5Key = 0x2005;
  224183. const int KeyPress::F6Key = 0x2006;
  224184. const int KeyPress::F7Key = 0x2007;
  224185. const int KeyPress::F8Key = 0x2008;
  224186. const int KeyPress::F9Key = 0x2009;
  224187. const int KeyPress::F10Key = 0x200a;
  224188. const int KeyPress::F11Key = 0x200b;
  224189. const int KeyPress::F12Key = 0x200c;
  224190. const int KeyPress::F13Key = 0x200d;
  224191. const int KeyPress::F14Key = 0x200e;
  224192. const int KeyPress::F15Key = 0x200f;
  224193. const int KeyPress::F16Key = 0x2010;
  224194. const int KeyPress::numberPad0 = 0x30020;
  224195. const int KeyPress::numberPad1 = 0x30021;
  224196. const int KeyPress::numberPad2 = 0x30022;
  224197. const int KeyPress::numberPad3 = 0x30023;
  224198. const int KeyPress::numberPad4 = 0x30024;
  224199. const int KeyPress::numberPad5 = 0x30025;
  224200. const int KeyPress::numberPad6 = 0x30026;
  224201. const int KeyPress::numberPad7 = 0x30027;
  224202. const int KeyPress::numberPad8 = 0x30028;
  224203. const int KeyPress::numberPad9 = 0x30029;
  224204. const int KeyPress::numberPadAdd = 0x3002a;
  224205. const int KeyPress::numberPadSubtract = 0x3002b;
  224206. const int KeyPress::numberPadMultiply = 0x3002c;
  224207. const int KeyPress::numberPadDivide = 0x3002d;
  224208. const int KeyPress::numberPadSeparator = 0x3002e;
  224209. const int KeyPress::numberPadDecimalPoint = 0x3002f;
  224210. const int KeyPress::numberPadEquals = 0x30030;
  224211. const int KeyPress::numberPadDelete = 0x30031;
  224212. const int KeyPress::playKey = 0x30000;
  224213. const int KeyPress::stopKey = 0x30001;
  224214. const int KeyPress::fastForwardKey = 0x30002;
  224215. const int KeyPress::rewindKey = 0x30003;
  224216. #endif
  224217. /*** End of inlined file: juce_iphone_UIViewComponentPeer.mm ***/
  224218. /*** Start of inlined file: juce_iphone_MessageManager.mm ***/
  224219. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  224220. // compiled on its own).
  224221. #if JUCE_INCLUDED_FILE
  224222. struct CallbackMessagePayload
  224223. {
  224224. MessageCallbackFunction* function;
  224225. void* parameter;
  224226. void* volatile result;
  224227. bool volatile hasBeenExecuted;
  224228. };
  224229. END_JUCE_NAMESPACE
  224230. using namespace JUCE_NAMESPACE;
  224231. @interface JuceAppDelegate : NSObject <UIApplicationDelegate>
  224232. {
  224233. }
  224234. - (JuceAppDelegate*) init;
  224235. - (void) dealloc;
  224236. - (BOOL) application: (UIApplication*) application handleOpenURL: (NSURL*) url;
  224237. - (void) applicationDidBecomeActive: (NSNotification*) aNotification;
  224238. - (void) applicationDidResignActive: (NSNotification*) aNotification;
  224239. - (void) applicationWillUnhide: (NSNotification*) aNotification;
  224240. - (void) customEvent: (id) data;
  224241. - (void) performCallback: (id) info;
  224242. @end
  224243. @implementation JuceAppDelegate
  224244. - (JuceAppDelegate*) init
  224245. {
  224246. [super init];
  224247. [[UIApplication sharedApplication] setDelegate: self];
  224248. return self;
  224249. }
  224250. - (void) dealloc
  224251. {
  224252. [[UIApplication sharedApplication] setDelegate: nil];
  224253. [super dealloc];
  224254. }
  224255. - (BOOL) application: (UIApplication*) application handleOpenURL: (NSURL*) url
  224256. {
  224257. if (JUCEApplication::getInstance() != 0)
  224258. {
  224259. JUCEApplication::getInstance()->anotherInstanceStarted (nsStringToJuce ([url absoluteString]));
  224260. return YES;
  224261. }
  224262. return NO;
  224263. }
  224264. - (void) applicationDidBecomeActive: (NSNotification*) aNotification
  224265. {
  224266. juce_HandleProcessFocusChange();
  224267. }
  224268. - (void) applicationDidResignActive: (NSNotification*) aNotification
  224269. {
  224270. juce_HandleProcessFocusChange();
  224271. }
  224272. - (void) applicationWillUnhide: (NSNotification*) aNotification
  224273. {
  224274. juce_HandleProcessFocusChange();
  224275. }
  224276. - (void) customEvent: (id) n
  224277. {
  224278. NSData* data = (NSData*) n;
  224279. void* message = 0;
  224280. [data getBytes: &message length: sizeof (message)];
  224281. [data release];
  224282. if (message != 0)
  224283. MessageManager::getInstance()->deliverMessage (message);
  224284. }
  224285. - (void) performCallback: (id) info
  224286. {
  224287. if ([info isKindOfClass: [NSData class]])
  224288. {
  224289. CallbackMessagePayload* pl = (CallbackMessagePayload*) [((NSData*) info) bytes];
  224290. if (pl != 0)
  224291. {
  224292. pl->result = (*pl->function) (pl->parameter);
  224293. pl->hasBeenExecuted = true;
  224294. }
  224295. }
  224296. else
  224297. {
  224298. jassertfalse // should never get here!
  224299. }
  224300. }
  224301. @end
  224302. BEGIN_JUCE_NAMESPACE
  224303. static JuceAppDelegate* juceAppDelegate = 0;
  224304. void MessageManager::runDispatchLoop()
  224305. {
  224306. jassert (isThisTheMessageThread()); // must only be called by the message thread
  224307. runDispatchLoopUntil (-1);
  224308. }
  224309. void MessageManager::stopDispatchLoop()
  224310. {
  224311. exit (0); // iPhone apps get no mercy..
  224312. }
  224313. bool MessageManager::runDispatchLoopUntil (int millisecondsToRunFor)
  224314. {
  224315. const ScopedAutoReleasePool pool;
  224316. jassert (isThisTheMessageThread()); // must only be called by the message thread
  224317. uint32 endTime = Time::getMillisecondCounter() + millisecondsToRunFor;
  224318. NSDate* endDate = [NSDate dateWithTimeIntervalSinceNow: millisecondsToRunFor * 0.001];
  224319. while (! quitMessagePosted)
  224320. {
  224321. const ScopedAutoReleasePool pool;
  224322. [[NSRunLoop currentRunLoop] runMode: NSDefaultRunLoopMode
  224323. beforeDate: endDate];
  224324. if (millisecondsToRunFor >= 0 && Time::getMillisecondCounter() >= endTime)
  224325. break;
  224326. }
  224327. return ! quitMessagePosted;
  224328. }
  224329. static CFRunLoopRef runLoop = 0;
  224330. static CFRunLoopSourceRef runLoopSource = 0;
  224331. static Array <void*, CriticalSection>* pendingMessages = 0;
  224332. static void runLoopSourceCallback (void*)
  224333. {
  224334. if (pendingMessages != 0)
  224335. {
  224336. int numDispatched = 0;
  224337. do
  224338. {
  224339. void* const nextMessage = pendingMessages->remove (0);
  224340. if (nextMessage == 0)
  224341. return;
  224342. const ScopedAutoReleasePool pool;
  224343. MessageManager::getInstance()->deliverMessage (nextMessage);
  224344. } while (++numDispatched <= 4);
  224345. CFRunLoopSourceSignal (runLoopSource);
  224346. CFRunLoopWakeUp (runLoop);
  224347. }
  224348. }
  224349. void MessageManager::doPlatformSpecificInitialisation()
  224350. {
  224351. pendingMessages = new Array <void*, CriticalSection>();
  224352. runLoop = CFRunLoopGetCurrent();
  224353. CFRunLoopSourceContext sourceContext;
  224354. zerostruct (sourceContext);
  224355. sourceContext.perform = runLoopSourceCallback;
  224356. runLoopSource = CFRunLoopSourceCreate (kCFAllocatorDefault, 1, &sourceContext);
  224357. CFRunLoopAddSource (runLoop, runLoopSource, kCFRunLoopCommonModes);
  224358. if (juceAppDelegate == 0)
  224359. juceAppDelegate = [[JuceAppDelegate alloc] init];
  224360. }
  224361. void MessageManager::doPlatformSpecificShutdown()
  224362. {
  224363. CFRunLoopSourceInvalidate (runLoopSource);
  224364. CFRelease (runLoopSource);
  224365. runLoopSource = 0;
  224366. if (pendingMessages != 0)
  224367. {
  224368. while (pendingMessages->size() > 0)
  224369. delete ((Message*) pendingMessages->remove(0));
  224370. deleteAndZero (pendingMessages);
  224371. }
  224372. if (juceAppDelegate != 0)
  224373. {
  224374. [[NSRunLoop currentRunLoop] cancelPerformSelectorsWithTarget: juceAppDelegate];
  224375. [juceAppDelegate release];
  224376. juceAppDelegate = 0;
  224377. }
  224378. }
  224379. bool juce_postMessageToSystemQueue (void* message)
  224380. {
  224381. if (pendingMessages != 0)
  224382. {
  224383. pendingMessages->add (message);
  224384. CFRunLoopSourceSignal (runLoopSource);
  224385. CFRunLoopWakeUp (runLoop);
  224386. }
  224387. return true;
  224388. }
  224389. void MessageManager::broadcastMessage (const String& value) throw()
  224390. {
  224391. }
  224392. void* MessageManager::callFunctionOnMessageThread (MessageCallbackFunction* callback,
  224393. void* data)
  224394. {
  224395. if (isThisTheMessageThread())
  224396. {
  224397. return (*callback) (data);
  224398. }
  224399. else
  224400. {
  224401. // If a thread has a MessageManagerLock and then tries to call this method, it'll
  224402. // deadlock because the message manager is blocked from running, so can never
  224403. // call your function..
  224404. jassert (! MessageManager::getInstance()->currentThreadHasLockedMessageManager());
  224405. const ScopedAutoReleasePool pool;
  224406. CallbackMessagePayload cmp;
  224407. cmp.function = callback;
  224408. cmp.parameter = data;
  224409. cmp.result = 0;
  224410. cmp.hasBeenExecuted = false;
  224411. [juceAppDelegate performSelectorOnMainThread: @selector (performCallback:)
  224412. withObject: [NSData dataWithBytesNoCopy: &cmp
  224413. length: sizeof (cmp)
  224414. freeWhenDone: NO]
  224415. waitUntilDone: YES];
  224416. return cmp.result;
  224417. }
  224418. }
  224419. #endif
  224420. /*** End of inlined file: juce_iphone_MessageManager.mm ***/
  224421. /*** Start of inlined file: juce_mac_FileChooser.mm ***/
  224422. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  224423. // compiled on its own).
  224424. #if JUCE_INCLUDED_FILE
  224425. #if JUCE_MAC
  224426. END_JUCE_NAMESPACE
  224427. using namespace JUCE_NAMESPACE;
  224428. #define JuceFileChooserDelegate MakeObjCClassName(JuceFileChooserDelegate)
  224429. #if defined (MAC_OS_X_VERSION_10_6) && MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_6
  224430. @interface JuceFileChooserDelegate : NSObject <NSOpenSavePanelDelegate>
  224431. #else
  224432. @interface JuceFileChooserDelegate : NSObject
  224433. #endif
  224434. {
  224435. StringArray* filters;
  224436. }
  224437. - (JuceFileChooserDelegate*) initWithFilters: (StringArray*) filters_;
  224438. - (void) dealloc;
  224439. - (BOOL) panel: (id) sender shouldShowFilename: (NSString*) filename;
  224440. @end
  224441. @implementation JuceFileChooserDelegate
  224442. - (JuceFileChooserDelegate*) initWithFilters: (StringArray*) filters_
  224443. {
  224444. [super init];
  224445. filters = filters_;
  224446. return self;
  224447. }
  224448. - (void) dealloc
  224449. {
  224450. delete filters;
  224451. [super dealloc];
  224452. }
  224453. - (BOOL) panel: (id) sender shouldShowFilename: (NSString*) filename
  224454. {
  224455. (void) sender;
  224456. const File f (nsStringToJuce (filename));
  224457. for (int i = filters->size(); --i >= 0;)
  224458. if (f.getFileName().matchesWildcard ((*filters)[i], true))
  224459. return true;
  224460. return f.isDirectory();
  224461. }
  224462. @end
  224463. BEGIN_JUCE_NAMESPACE
  224464. void FileChooser::showPlatformDialog (Array<File>& results,
  224465. const String& title,
  224466. const File& currentFileOrDirectory,
  224467. const String& filter,
  224468. bool selectsDirectory,
  224469. bool selectsFiles,
  224470. bool isSaveDialogue,
  224471. bool warnAboutOverwritingExistingFiles,
  224472. bool selectMultipleFiles,
  224473. FilePreviewComponent* extraInfoComponent)
  224474. {
  224475. const ScopedAutoReleasePool pool;
  224476. StringArray* filters = new StringArray();
  224477. filters->addTokens (filter.replaceCharacters (",:", ";;"), ";", String::empty);
  224478. filters->trim();
  224479. filters->removeEmptyStrings();
  224480. JuceFileChooserDelegate* delegate = [[JuceFileChooserDelegate alloc] initWithFilters: filters];
  224481. [delegate autorelease];
  224482. NSSavePanel* panel = isSaveDialogue ? [NSSavePanel savePanel]
  224483. : [NSOpenPanel openPanel];
  224484. [panel setTitle: juceStringToNS (title)];
  224485. if (! isSaveDialogue)
  224486. {
  224487. NSOpenPanel* openPanel = (NSOpenPanel*) panel;
  224488. [openPanel setCanChooseDirectories: selectsDirectory];
  224489. [openPanel setCanChooseFiles: selectsFiles];
  224490. [openPanel setAllowsMultipleSelection: selectMultipleFiles];
  224491. }
  224492. [panel setDelegate: delegate];
  224493. if (isSaveDialogue || selectsDirectory)
  224494. [panel setCanCreateDirectories: YES];
  224495. String directory, filename;
  224496. if (currentFileOrDirectory.isDirectory())
  224497. {
  224498. directory = currentFileOrDirectory.getFullPathName();
  224499. }
  224500. else
  224501. {
  224502. directory = currentFileOrDirectory.getParentDirectory().getFullPathName();
  224503. filename = currentFileOrDirectory.getFileName();
  224504. }
  224505. if ([panel runModalForDirectory: juceStringToNS (directory)
  224506. file: juceStringToNS (filename)]
  224507. == NSOKButton)
  224508. {
  224509. if (isSaveDialogue)
  224510. {
  224511. results.add (File (nsStringToJuce ([panel filename])));
  224512. }
  224513. else
  224514. {
  224515. NSOpenPanel* openPanel = (NSOpenPanel*) panel;
  224516. NSArray* urls = [openPanel filenames];
  224517. for (unsigned int i = 0; i < [urls count]; ++i)
  224518. {
  224519. NSString* f = [urls objectAtIndex: i];
  224520. results.add (File (nsStringToJuce (f)));
  224521. }
  224522. }
  224523. }
  224524. [panel setDelegate: nil];
  224525. }
  224526. #else
  224527. void FileChooser::showPlatformDialog (Array<File>& results,
  224528. const String& title,
  224529. const File& currentFileOrDirectory,
  224530. const String& filter,
  224531. bool selectsDirectory,
  224532. bool selectsFiles,
  224533. bool isSaveDialogue,
  224534. bool warnAboutOverwritingExistingFiles,
  224535. bool selectMultipleFiles,
  224536. FilePreviewComponent* extraInfoComponent)
  224537. {
  224538. const ScopedAutoReleasePool pool;
  224539. jassertfalse //xxx to do
  224540. }
  224541. #endif
  224542. #endif
  224543. /*** End of inlined file: juce_mac_FileChooser.mm ***/
  224544. /*** Start of inlined file: juce_mac_OpenGLComponent.mm ***/
  224545. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  224546. // compiled on its own).
  224547. #if JUCE_INCLUDED_FILE && JUCE_OPENGL
  224548. #if JUCE_MAC
  224549. END_JUCE_NAMESPACE
  224550. #define ThreadSafeNSOpenGLView MakeObjCClassName(ThreadSafeNSOpenGLView)
  224551. @interface ThreadSafeNSOpenGLView : NSOpenGLView
  224552. {
  224553. CriticalSection* contextLock;
  224554. bool needsUpdate;
  224555. }
  224556. - (id) initWithFrame: (NSRect) frameRect pixelFormat: (NSOpenGLPixelFormat*) format;
  224557. - (bool) makeActive;
  224558. - (void) makeInactive;
  224559. - (void) reshape;
  224560. @end
  224561. @implementation ThreadSafeNSOpenGLView
  224562. - (id) initWithFrame: (NSRect) frameRect
  224563. pixelFormat: (NSOpenGLPixelFormat*) format
  224564. {
  224565. contextLock = new CriticalSection();
  224566. self = [super initWithFrame: frameRect pixelFormat: format];
  224567. if (self != nil)
  224568. [[NSNotificationCenter defaultCenter] addObserver: self
  224569. selector: @selector (_surfaceNeedsUpdate:)
  224570. name: NSViewGlobalFrameDidChangeNotification
  224571. object: self];
  224572. return self;
  224573. }
  224574. - (void) dealloc
  224575. {
  224576. [[NSNotificationCenter defaultCenter] removeObserver: self];
  224577. delete contextLock;
  224578. [super dealloc];
  224579. }
  224580. - (bool) makeActive
  224581. {
  224582. const ScopedLock sl (*contextLock);
  224583. if ([self openGLContext] == 0)
  224584. return false;
  224585. [[self openGLContext] makeCurrentContext];
  224586. if (needsUpdate)
  224587. {
  224588. [super update];
  224589. needsUpdate = false;
  224590. }
  224591. return true;
  224592. }
  224593. - (void) makeInactive
  224594. {
  224595. const ScopedLock sl (*contextLock);
  224596. [NSOpenGLContext clearCurrentContext];
  224597. }
  224598. - (void) _surfaceNeedsUpdate: (NSNotification*) notification
  224599. {
  224600. const ScopedLock sl (*contextLock);
  224601. needsUpdate = true;
  224602. }
  224603. - (void) update
  224604. {
  224605. const ScopedLock sl (*contextLock);
  224606. needsUpdate = true;
  224607. }
  224608. - (void) reshape
  224609. {
  224610. const ScopedLock sl (*contextLock);
  224611. needsUpdate = true;
  224612. }
  224613. @end
  224614. BEGIN_JUCE_NAMESPACE
  224615. class WindowedGLContext : public OpenGLContext
  224616. {
  224617. public:
  224618. WindowedGLContext (Component* const component,
  224619. const OpenGLPixelFormat& pixelFormat_,
  224620. NSOpenGLContext* sharedContext)
  224621. : renderContext (0),
  224622. pixelFormat (pixelFormat_)
  224623. {
  224624. jassert (component != 0);
  224625. NSOpenGLPixelFormatAttribute attribs [64];
  224626. int n = 0;
  224627. attribs[n++] = NSOpenGLPFADoubleBuffer;
  224628. attribs[n++] = NSOpenGLPFAAccelerated;
  224629. attribs[n++] = NSOpenGLPFAMPSafe; // NSOpenGLPFAAccelerated, NSOpenGLPFAMultiScreen, NSOpenGLPFASingleRenderer
  224630. attribs[n++] = NSOpenGLPFAColorSize;
  224631. attribs[n++] = (NSOpenGLPixelFormatAttribute) jmax (pixelFormat.redBits,
  224632. pixelFormat.greenBits,
  224633. pixelFormat.blueBits);
  224634. attribs[n++] = NSOpenGLPFAAlphaSize;
  224635. attribs[n++] = (NSOpenGLPixelFormatAttribute) pixelFormat.alphaBits;
  224636. attribs[n++] = NSOpenGLPFADepthSize;
  224637. attribs[n++] = (NSOpenGLPixelFormatAttribute) pixelFormat.depthBufferBits;
  224638. attribs[n++] = NSOpenGLPFAStencilSize;
  224639. attribs[n++] = (NSOpenGLPixelFormatAttribute) pixelFormat.stencilBufferBits;
  224640. attribs[n++] = NSOpenGLPFAAccumSize;
  224641. attribs[n++] = (NSOpenGLPixelFormatAttribute) jmax (pixelFormat.accumulationBufferRedBits,
  224642. pixelFormat.accumulationBufferGreenBits,
  224643. pixelFormat.accumulationBufferBlueBits,
  224644. pixelFormat.accumulationBufferAlphaBits);
  224645. // xxx not sure how to do fullSceneAntiAliasingNumSamples..
  224646. attribs[n++] = NSOpenGLPFASampleBuffers;
  224647. attribs[n++] = (NSOpenGLPixelFormatAttribute) 1;
  224648. attribs[n++] = NSOpenGLPFAClosestPolicy;
  224649. attribs[n++] = NSOpenGLPFANoRecovery;
  224650. attribs[n++] = (NSOpenGLPixelFormatAttribute) 0;
  224651. NSOpenGLPixelFormat* format
  224652. = [[NSOpenGLPixelFormat alloc] initWithAttributes: attribs];
  224653. view = [[ThreadSafeNSOpenGLView alloc] initWithFrame: NSMakeRect (0, 0, 100.0f, 100.0f)
  224654. pixelFormat: format];
  224655. renderContext = [[[NSOpenGLContext alloc] initWithFormat: format
  224656. shareContext: sharedContext] autorelease];
  224657. const GLint swapInterval = 1;
  224658. [renderContext setValues: &swapInterval forParameter: NSOpenGLCPSwapInterval];
  224659. [view setOpenGLContext: renderContext];
  224660. [renderContext setView: view];
  224661. [format release];
  224662. viewHolder = new NSViewComponentInternal (view, component);
  224663. }
  224664. ~WindowedGLContext()
  224665. {
  224666. makeInactive();
  224667. [renderContext clearDrawable];
  224668. viewHolder = 0;
  224669. }
  224670. bool makeActive() const throw()
  224671. {
  224672. jassert (renderContext != 0);
  224673. [view makeActive];
  224674. return isActive();
  224675. }
  224676. bool makeInactive() const throw()
  224677. {
  224678. [view makeInactive];
  224679. return true;
  224680. }
  224681. bool isActive() const throw()
  224682. {
  224683. return [NSOpenGLContext currentContext] == renderContext;
  224684. }
  224685. const OpenGLPixelFormat getPixelFormat() const { return pixelFormat; }
  224686. void* getRawContext() const throw() { return renderContext; }
  224687. void updateWindowPosition (int x, int y, int w, int h, int outerWindowHeight)
  224688. {
  224689. }
  224690. void swapBuffers()
  224691. {
  224692. [renderContext flushBuffer];
  224693. }
  224694. bool setSwapInterval (const int numFramesPerSwap)
  224695. {
  224696. [renderContext setValues: (const GLint*) &numFramesPerSwap
  224697. forParameter: NSOpenGLCPSwapInterval];
  224698. return true;
  224699. }
  224700. int getSwapInterval() const
  224701. {
  224702. GLint numFrames = 0;
  224703. [renderContext getValues: &numFrames
  224704. forParameter: NSOpenGLCPSwapInterval];
  224705. return numFrames;
  224706. }
  224707. void repaint()
  224708. {
  224709. // we need to invalidate the juce view that holds this gl view, to make it
  224710. // cause a repaint callback
  224711. NSView* v = (NSView*) viewHolder->view;
  224712. NSRect r = [v frame];
  224713. // bit of a bodge here.. if we only invalidate the area of the gl component,
  224714. // it's completely covered by the NSOpenGLView, so the OS throws away the
  224715. // repaint message, thus never causing our paint() callback, and never repainting
  224716. // the comp. So invalidating just a little bit around the edge helps..
  224717. [[v superview] setNeedsDisplayInRect: NSInsetRect (r, -2.0f, -2.0f)];
  224718. }
  224719. void* getNativeWindowHandle() const { return viewHolder->view; }
  224720. juce_UseDebuggingNewOperator
  224721. NSOpenGLContext* renderContext;
  224722. ThreadSafeNSOpenGLView* view;
  224723. private:
  224724. OpenGLPixelFormat pixelFormat;
  224725. ScopedPointer <NSViewComponentInternal> viewHolder;
  224726. WindowedGLContext (const WindowedGLContext&);
  224727. WindowedGLContext& operator= (const WindowedGLContext&);
  224728. };
  224729. OpenGLContext* OpenGLComponent::createContext()
  224730. {
  224731. ScopedPointer<WindowedGLContext> c (new WindowedGLContext (this, preferredPixelFormat,
  224732. contextToShareListsWith != 0 ? (NSOpenGLContext*) contextToShareListsWith->getRawContext() : 0));
  224733. return (c->renderContext != 0) ? c.release() : 0;
  224734. }
  224735. void* OpenGLComponent::getNativeWindowHandle() const
  224736. {
  224737. return context != 0 ? static_cast<WindowedGLContext*> (static_cast<OpenGLContext*> (context))->getNativeWindowHandle()
  224738. : 0;
  224739. }
  224740. void juce_glViewport (const int w, const int h)
  224741. {
  224742. glViewport (0, 0, w, h);
  224743. }
  224744. void OpenGLPixelFormat::getAvailablePixelFormats (Component* /*component*/,
  224745. OwnedArray <OpenGLPixelFormat>& results)
  224746. {
  224747. /* GLint attribs [64];
  224748. int n = 0;
  224749. attribs[n++] = AGL_RGBA;
  224750. attribs[n++] = AGL_DOUBLEBUFFER;
  224751. attribs[n++] = AGL_ACCELERATED;
  224752. attribs[n++] = AGL_NO_RECOVERY;
  224753. attribs[n++] = AGL_NONE;
  224754. AGLPixelFormat p = aglChoosePixelFormat (0, 0, attribs);
  224755. while (p != 0)
  224756. {
  224757. OpenGLPixelFormat* const pf = new OpenGLPixelFormat();
  224758. pf->redBits = getAGLAttribute (p, AGL_RED_SIZE);
  224759. pf->greenBits = getAGLAttribute (p, AGL_GREEN_SIZE);
  224760. pf->blueBits = getAGLAttribute (p, AGL_BLUE_SIZE);
  224761. pf->alphaBits = getAGLAttribute (p, AGL_ALPHA_SIZE);
  224762. pf->depthBufferBits = getAGLAttribute (p, AGL_DEPTH_SIZE);
  224763. pf->stencilBufferBits = getAGLAttribute (p, AGL_STENCIL_SIZE);
  224764. pf->accumulationBufferRedBits = getAGLAttribute (p, AGL_ACCUM_RED_SIZE);
  224765. pf->accumulationBufferGreenBits = getAGLAttribute (p, AGL_ACCUM_GREEN_SIZE);
  224766. pf->accumulationBufferBlueBits = getAGLAttribute (p, AGL_ACCUM_BLUE_SIZE);
  224767. pf->accumulationBufferAlphaBits = getAGLAttribute (p, AGL_ACCUM_ALPHA_SIZE);
  224768. results.add (pf);
  224769. p = aglNextPixelFormat (p);
  224770. }*/
  224771. //jassertfalse //xxx can't see how you do this in cocoa!
  224772. }
  224773. #else
  224774. END_JUCE_NAMESPACE
  224775. @interface JuceGLView : UIView
  224776. {
  224777. }
  224778. + (Class) layerClass;
  224779. @end
  224780. @implementation JuceGLView
  224781. + (Class) layerClass
  224782. {
  224783. return [CAEAGLLayer class];
  224784. }
  224785. @end
  224786. BEGIN_JUCE_NAMESPACE
  224787. class GLESContext : public OpenGLContext
  224788. {
  224789. public:
  224790. GLESContext (UIViewComponentPeer* peer,
  224791. Component* const component_,
  224792. const OpenGLPixelFormat& pixelFormat_,
  224793. const GLESContext* const sharedContext,
  224794. NSUInteger apiType)
  224795. : component (component_), pixelFormat (pixelFormat_), glLayer (0), context (0),
  224796. useDepthBuffer (pixelFormat_.depthBufferBits > 0), frameBufferHandle (0), colorBufferHandle (0),
  224797. depthBufferHandle (0), lastWidth (0), lastHeight (0)
  224798. {
  224799. view = [[JuceGLView alloc] initWithFrame: CGRectMake (0, 0, 64, 64)];
  224800. view.opaque = YES;
  224801. view.hidden = NO;
  224802. view.backgroundColor = [UIColor blackColor];
  224803. view.userInteractionEnabled = NO;
  224804. glLayer = (CAEAGLLayer*) [view layer];
  224805. [peer->view addSubview: view];
  224806. if (sharedContext != 0)
  224807. context = [[EAGLContext alloc] initWithAPI: apiType
  224808. sharegroup: [sharedContext->context sharegroup]];
  224809. else
  224810. context = [[EAGLContext alloc] initWithAPI: apiType];
  224811. createGLBuffers();
  224812. }
  224813. ~GLESContext()
  224814. {
  224815. makeInactive();
  224816. [context release];
  224817. [view removeFromSuperview];
  224818. [view release];
  224819. freeGLBuffers();
  224820. }
  224821. bool makeActive() const throw()
  224822. {
  224823. jassert (context != 0);
  224824. [EAGLContext setCurrentContext: context];
  224825. glBindFramebufferOES (GL_FRAMEBUFFER_OES, frameBufferHandle);
  224826. return true;
  224827. }
  224828. void swapBuffers()
  224829. {
  224830. glBindRenderbufferOES (GL_RENDERBUFFER_OES, colorBufferHandle);
  224831. [context presentRenderbuffer: GL_RENDERBUFFER_OES];
  224832. }
  224833. bool makeInactive() const throw()
  224834. {
  224835. return [EAGLContext setCurrentContext: nil];
  224836. }
  224837. bool isActive() const throw()
  224838. {
  224839. return [EAGLContext currentContext] == context;
  224840. }
  224841. const OpenGLPixelFormat getPixelFormat() const { return pixelFormat; }
  224842. void* getRawContext() const throw() { return glLayer; }
  224843. void updateWindowPosition (int x, int y, int w, int h, int outerWindowHeight)
  224844. {
  224845. view.frame = CGRectMake ((CGFloat) x, (CGFloat) y, (CGFloat) w, (CGFloat) h);
  224846. if (lastWidth != w || lastHeight != h)
  224847. {
  224848. lastWidth = w;
  224849. lastHeight = h;
  224850. freeGLBuffers();
  224851. createGLBuffers();
  224852. }
  224853. }
  224854. bool setSwapInterval (const int numFramesPerSwap)
  224855. {
  224856. numFrames = numFramesPerSwap;
  224857. return true;
  224858. }
  224859. int getSwapInterval() const
  224860. {
  224861. return numFrames;
  224862. }
  224863. void repaint()
  224864. {
  224865. }
  224866. void createGLBuffers()
  224867. {
  224868. makeActive();
  224869. glGenFramebuffersOES (1, &frameBufferHandle);
  224870. glGenRenderbuffersOES (1, &colorBufferHandle);
  224871. glGenRenderbuffersOES (1, &depthBufferHandle);
  224872. glBindRenderbufferOES (GL_RENDERBUFFER_OES, colorBufferHandle);
  224873. [context renderbufferStorage: GL_RENDERBUFFER_OES fromDrawable: glLayer];
  224874. GLint width, height;
  224875. glGetRenderbufferParameterivOES (GL_RENDERBUFFER_OES, GL_RENDERBUFFER_WIDTH_OES, &width);
  224876. glGetRenderbufferParameterivOES (GL_RENDERBUFFER_OES, GL_RENDERBUFFER_HEIGHT_OES, &height);
  224877. if (useDepthBuffer)
  224878. {
  224879. glBindRenderbufferOES (GL_RENDERBUFFER_OES, depthBufferHandle);
  224880. glRenderbufferStorageOES (GL_RENDERBUFFER_OES, GL_DEPTH_COMPONENT16_OES, width, height);
  224881. }
  224882. glBindRenderbufferOES (GL_RENDERBUFFER_OES, colorBufferHandle);
  224883. glBindFramebufferOES (GL_FRAMEBUFFER_OES, frameBufferHandle);
  224884. glFramebufferRenderbufferOES (GL_FRAMEBUFFER_OES, GL_COLOR_ATTACHMENT0_OES, GL_RENDERBUFFER_OES, colorBufferHandle);
  224885. if (useDepthBuffer)
  224886. glFramebufferRenderbufferOES (GL_FRAMEBUFFER_OES, GL_DEPTH_ATTACHMENT_OES, GL_RENDERBUFFER_OES, depthBufferHandle);
  224887. jassert (glCheckFramebufferStatusOES (GL_FRAMEBUFFER_OES) == GL_FRAMEBUFFER_COMPLETE_OES);
  224888. }
  224889. void freeGLBuffers()
  224890. {
  224891. if (frameBufferHandle != 0)
  224892. {
  224893. glDeleteFramebuffersOES (1, &frameBufferHandle);
  224894. frameBufferHandle = 0;
  224895. }
  224896. if (colorBufferHandle != 0)
  224897. {
  224898. glDeleteRenderbuffersOES (1, &colorBufferHandle);
  224899. colorBufferHandle = 0;
  224900. }
  224901. if (depthBufferHandle != 0)
  224902. {
  224903. glDeleteRenderbuffersOES (1, &depthBufferHandle);
  224904. depthBufferHandle = 0;
  224905. }
  224906. }
  224907. juce_UseDebuggingNewOperator
  224908. private:
  224909. Component::SafePointer<Component> component;
  224910. OpenGLPixelFormat pixelFormat;
  224911. JuceGLView* view;
  224912. CAEAGLLayer* glLayer;
  224913. EAGLContext* context;
  224914. bool useDepthBuffer;
  224915. GLuint frameBufferHandle, colorBufferHandle, depthBufferHandle;
  224916. int numFrames;
  224917. int lastWidth, lastHeight;
  224918. GLESContext (const GLESContext&);
  224919. GLESContext& operator= (const GLESContext&);
  224920. };
  224921. OpenGLContext* OpenGLComponent::createContext()
  224922. {
  224923. ScopedAutoReleasePool pool;
  224924. UIViewComponentPeer* peer = dynamic_cast <UIViewComponentPeer*> (getPeer());
  224925. if (peer != 0)
  224926. return new GLESContext (peer, this, preferredPixelFormat,
  224927. dynamic_cast <const GLESContext*> (contextToShareListsWith),
  224928. type == openGLES2 ? kEAGLRenderingAPIOpenGLES2 : kEAGLRenderingAPIOpenGLES1);
  224929. return 0;
  224930. }
  224931. void OpenGLPixelFormat::getAvailablePixelFormats (Component* /*component*/,
  224932. OwnedArray <OpenGLPixelFormat>& /*results*/)
  224933. {
  224934. }
  224935. void juce_glViewport (const int w, const int h)
  224936. {
  224937. glViewport (0, 0, w, h);
  224938. }
  224939. #endif
  224940. #endif
  224941. /*** End of inlined file: juce_mac_OpenGLComponent.mm ***/
  224942. /*** Start of inlined file: juce_mac_MouseCursor.mm ***/
  224943. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  224944. // compiled on its own).
  224945. #if JUCE_INCLUDED_FILE
  224946. #if JUCE_MAC
  224947. namespace MouseCursorHelpers
  224948. {
  224949. static void* createFromImage (const Image& image, float hotspotX, float hotspotY)
  224950. {
  224951. NSImage* im = CoreGraphicsImage::createNSImage (image);
  224952. NSCursor* c = [[NSCursor alloc] initWithImage: im
  224953. hotSpot: NSMakePoint (hotspotX, hotspotY)];
  224954. [im release];
  224955. return c;
  224956. }
  224957. static void* fromWebKitFile (const char* filename, float hx, float hy)
  224958. {
  224959. FileInputStream fileStream (String ("/System/Library/Frameworks/WebKit.framework/Frameworks/WebCore.framework/Resources/") + filename);
  224960. BufferedInputStream buf (&fileStream, 4096, false);
  224961. PNGImageFormat pngFormat;
  224962. const ScopedPointer <Image> im (pngFormat.decodeImage (buf));
  224963. if (im != 0)
  224964. return createFromImage (*im, hx * im->getWidth(), hy * im->getHeight());
  224965. jassertfalse;
  224966. return 0;
  224967. }
  224968. }
  224969. void* MouseCursor::createMouseCursorFromImage (const Image& image, int hotspotX, int hotspotY)
  224970. {
  224971. return MouseCursorHelpers::createFromImage (image, (float) hotspotX, (float) hotspotY);
  224972. }
  224973. void* MouseCursor::createStandardMouseCursor (MouseCursor::StandardCursorType type)
  224974. {
  224975. const ScopedAutoReleasePool pool;
  224976. NSCursor* c = 0;
  224977. switch (type)
  224978. {
  224979. case NormalCursor: c = [NSCursor arrowCursor]; break;
  224980. case NoCursor: return createMouseCursorFromImage (Image (Image::ARGB, 8, 8, true), 0, 0);
  224981. case DraggingHandCursor: c = [NSCursor openHandCursor]; break;
  224982. case WaitCursor: c = [NSCursor arrowCursor]; break; // avoid this on the mac, let the OS provide the beachball
  224983. case IBeamCursor: c = [NSCursor IBeamCursor]; break;
  224984. case PointingHandCursor: c = [NSCursor pointingHandCursor]; break;
  224985. case LeftRightResizeCursor: c = [NSCursor resizeLeftRightCursor]; break;
  224986. case LeftEdgeResizeCursor: c = [NSCursor resizeLeftCursor]; break;
  224987. case RightEdgeResizeCursor: c = [NSCursor resizeRightCursor]; break;
  224988. case CrosshairCursor: c = [NSCursor crosshairCursor]; break;
  224989. case CopyingCursor: return MouseCursorHelpers::fromWebKitFile ("copyCursor.png", 0, 0);
  224990. case UpDownResizeCursor:
  224991. case TopEdgeResizeCursor:
  224992. case BottomEdgeResizeCursor:
  224993. return MouseCursorHelpers::fromWebKitFile ("northSouthResizeCursor.png", 0.5f, 0.5f);
  224994. case TopLeftCornerResizeCursor:
  224995. case BottomRightCornerResizeCursor:
  224996. return MouseCursorHelpers::fromWebKitFile ("northWestSouthEastResizeCursor.png", 0.5f, 0.5f);
  224997. case TopRightCornerResizeCursor:
  224998. case BottomLeftCornerResizeCursor:
  224999. return MouseCursorHelpers::fromWebKitFile ("northEastSouthWestResizeCursor.png", 0.5f, 0.5f);
  225000. case UpDownLeftRightResizeCursor:
  225001. return MouseCursorHelpers::fromWebKitFile ("moveCursor.png", 0.5f, 0.5f);
  225002. default:
  225003. jassertfalse;
  225004. break;
  225005. }
  225006. [c retain];
  225007. return c;
  225008. }
  225009. void MouseCursor::deleteMouseCursor (void* const cursorHandle, const bool /*isStandard*/)
  225010. {
  225011. [((NSCursor*) cursorHandle) release];
  225012. }
  225013. void MouseCursor::showInAllWindows() const
  225014. {
  225015. showInWindow (0);
  225016. }
  225017. void MouseCursor::showInWindow (ComponentPeer*) const
  225018. {
  225019. [((NSCursor*) getHandle()) set];
  225020. }
  225021. #else
  225022. void* MouseCursor::createMouseCursorFromImage (const Image& image, int hotspotX, int hotspotY) { return 0; }
  225023. void* MouseCursor::createStandardMouseCursor (MouseCursor::StandardCursorType type) { return 0; }
  225024. void MouseCursor::deleteMouseCursor (void* const cursorHandle, const bool isStandard) {}
  225025. void MouseCursor::showInAllWindows() const {}
  225026. void MouseCursor::showInWindow (ComponentPeer*) const {}
  225027. #endif
  225028. #endif
  225029. /*** End of inlined file: juce_mac_MouseCursor.mm ***/
  225030. /*** Start of inlined file: juce_mac_WebBrowserComponent.mm ***/
  225031. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  225032. // compiled on its own).
  225033. #if JUCE_INCLUDED_FILE && JUCE_WEB_BROWSER
  225034. #if JUCE_MAC
  225035. END_JUCE_NAMESPACE
  225036. #define DownloadClickDetector MakeObjCClassName(DownloadClickDetector)
  225037. @interface DownloadClickDetector : NSObject
  225038. {
  225039. JUCE_NAMESPACE::WebBrowserComponent* ownerComponent;
  225040. }
  225041. - (DownloadClickDetector*) initWithWebBrowserOwner: (JUCE_NAMESPACE::WebBrowserComponent*) ownerComponent;
  225042. - (void) webView: (WebView*) webView decidePolicyForNavigationAction: (NSDictionary*) actionInformation
  225043. request: (NSURLRequest*) request
  225044. frame: (WebFrame*) frame
  225045. decisionListener: (id<WebPolicyDecisionListener>) listener;
  225046. @end
  225047. @implementation DownloadClickDetector
  225048. - (DownloadClickDetector*) initWithWebBrowserOwner: (JUCE_NAMESPACE::WebBrowserComponent*) ownerComponent_
  225049. {
  225050. [super init];
  225051. ownerComponent = ownerComponent_;
  225052. return self;
  225053. }
  225054. - (void) webView: (WebView*) sender decidePolicyForNavigationAction: (NSDictionary*) actionInformation
  225055. request: (NSURLRequest*) request
  225056. frame: (WebFrame*) frame
  225057. decisionListener: (id <WebPolicyDecisionListener>) listener
  225058. {
  225059. (void) sender;
  225060. (void) request;
  225061. (void) frame;
  225062. NSURL* url = [actionInformation valueForKey: @"WebActionOriginalURLKey"];
  225063. if (ownerComponent->pageAboutToLoad (nsStringToJuce ([url absoluteString])))
  225064. [listener use];
  225065. else
  225066. [listener ignore];
  225067. }
  225068. @end
  225069. BEGIN_JUCE_NAMESPACE
  225070. class WebBrowserComponentInternal : public NSViewComponent
  225071. {
  225072. public:
  225073. WebBrowserComponentInternal (WebBrowserComponent* owner)
  225074. {
  225075. webView = [[WebView alloc] initWithFrame: NSMakeRect (0, 0, 100.0f, 100.0f)
  225076. frameName: @""
  225077. groupName: @""];
  225078. setView (webView);
  225079. clickListener = [[DownloadClickDetector alloc] initWithWebBrowserOwner: owner];
  225080. [webView setPolicyDelegate: clickListener];
  225081. }
  225082. ~WebBrowserComponentInternal()
  225083. {
  225084. [webView setPolicyDelegate: nil];
  225085. [clickListener release];
  225086. setView (0);
  225087. }
  225088. void goToURL (const String& url,
  225089. const StringArray* headers,
  225090. const MemoryBlock* postData)
  225091. {
  225092. NSMutableURLRequest* r
  225093. = [NSMutableURLRequest requestWithURL: [NSURL URLWithString: juceStringToNS (url)]
  225094. cachePolicy: NSURLRequestUseProtocolCachePolicy
  225095. timeoutInterval: 30.0];
  225096. if (postData != 0 && postData->getSize() > 0)
  225097. {
  225098. [r setHTTPMethod: @"POST"];
  225099. [r setHTTPBody: [NSData dataWithBytes: postData->getData()
  225100. length: postData->getSize()]];
  225101. }
  225102. if (headers != 0)
  225103. {
  225104. for (int i = 0; i < headers->size(); ++i)
  225105. {
  225106. const String headerName ((*headers)[i].upToFirstOccurrenceOf (":", false, false).trim());
  225107. const String headerValue ((*headers)[i].fromFirstOccurrenceOf (":", false, false).trim());
  225108. [r setValue: juceStringToNS (headerValue)
  225109. forHTTPHeaderField: juceStringToNS (headerName)];
  225110. }
  225111. }
  225112. stop();
  225113. [[webView mainFrame] loadRequest: r];
  225114. }
  225115. void goBack()
  225116. {
  225117. [webView goBack];
  225118. }
  225119. void goForward()
  225120. {
  225121. [webView goForward];
  225122. }
  225123. void stop()
  225124. {
  225125. [webView stopLoading: nil];
  225126. }
  225127. void refresh()
  225128. {
  225129. [webView reload: nil];
  225130. }
  225131. private:
  225132. WebView* webView;
  225133. DownloadClickDetector* clickListener;
  225134. };
  225135. WebBrowserComponent::WebBrowserComponent (const bool unloadPageWhenBrowserIsHidden_)
  225136. : browser (0),
  225137. blankPageShown (false),
  225138. unloadPageWhenBrowserIsHidden (unloadPageWhenBrowserIsHidden_)
  225139. {
  225140. setOpaque (true);
  225141. addAndMakeVisible (browser = new WebBrowserComponentInternal (this));
  225142. }
  225143. WebBrowserComponent::~WebBrowserComponent()
  225144. {
  225145. deleteAndZero (browser);
  225146. }
  225147. void WebBrowserComponent::goToURL (const String& url,
  225148. const StringArray* headers,
  225149. const MemoryBlock* postData)
  225150. {
  225151. lastURL = url;
  225152. lastHeaders.clear();
  225153. if (headers != 0)
  225154. lastHeaders = *headers;
  225155. lastPostData.setSize (0);
  225156. if (postData != 0)
  225157. lastPostData = *postData;
  225158. blankPageShown = false;
  225159. browser->goToURL (url, headers, postData);
  225160. }
  225161. void WebBrowserComponent::stop()
  225162. {
  225163. browser->stop();
  225164. }
  225165. void WebBrowserComponent::goBack()
  225166. {
  225167. lastURL = String::empty;
  225168. blankPageShown = false;
  225169. browser->goBack();
  225170. }
  225171. void WebBrowserComponent::goForward()
  225172. {
  225173. lastURL = String::empty;
  225174. browser->goForward();
  225175. }
  225176. void WebBrowserComponent::refresh()
  225177. {
  225178. browser->refresh();
  225179. }
  225180. void WebBrowserComponent::paint (Graphics&)
  225181. {
  225182. }
  225183. void WebBrowserComponent::checkWindowAssociation()
  225184. {
  225185. if (isShowing())
  225186. {
  225187. if (blankPageShown)
  225188. goBack();
  225189. }
  225190. else
  225191. {
  225192. if (unloadPageWhenBrowserIsHidden && ! blankPageShown)
  225193. {
  225194. // when the component becomes invisible, some stuff like flash
  225195. // carries on playing audio, so we need to force it onto a blank
  225196. // page to avoid this, (and send it back when it's made visible again).
  225197. blankPageShown = true;
  225198. browser->goToURL ("about:blank", 0, 0);
  225199. }
  225200. }
  225201. }
  225202. void WebBrowserComponent::reloadLastURL()
  225203. {
  225204. if (lastURL.isNotEmpty())
  225205. {
  225206. goToURL (lastURL, &lastHeaders, &lastPostData);
  225207. lastURL = String::empty;
  225208. }
  225209. }
  225210. void WebBrowserComponent::parentHierarchyChanged()
  225211. {
  225212. checkWindowAssociation();
  225213. }
  225214. void WebBrowserComponent::resized()
  225215. {
  225216. browser->setSize (getWidth(), getHeight());
  225217. }
  225218. void WebBrowserComponent::visibilityChanged()
  225219. {
  225220. checkWindowAssociation();
  225221. }
  225222. bool WebBrowserComponent::pageAboutToLoad (const String&)
  225223. {
  225224. return true;
  225225. }
  225226. #else
  225227. WebBrowserComponent::WebBrowserComponent (const bool unloadPageWhenBrowserIsHidden_)
  225228. {
  225229. }
  225230. WebBrowserComponent::~WebBrowserComponent()
  225231. {
  225232. }
  225233. void WebBrowserComponent::goToURL (const String& url,
  225234. const StringArray* headers,
  225235. const MemoryBlock* postData)
  225236. {
  225237. }
  225238. void WebBrowserComponent::stop()
  225239. {
  225240. }
  225241. void WebBrowserComponent::goBack()
  225242. {
  225243. }
  225244. void WebBrowserComponent::goForward()
  225245. {
  225246. }
  225247. void WebBrowserComponent::refresh()
  225248. {
  225249. }
  225250. void WebBrowserComponent::paint (Graphics& g)
  225251. {
  225252. }
  225253. void WebBrowserComponent::checkWindowAssociation()
  225254. {
  225255. }
  225256. void WebBrowserComponent::reloadLastURL()
  225257. {
  225258. }
  225259. void WebBrowserComponent::parentHierarchyChanged()
  225260. {
  225261. }
  225262. void WebBrowserComponent::resized()
  225263. {
  225264. }
  225265. void WebBrowserComponent::visibilityChanged()
  225266. {
  225267. }
  225268. bool WebBrowserComponent::pageAboutToLoad (const String& url)
  225269. {
  225270. return true;
  225271. }
  225272. #endif
  225273. #endif
  225274. /*** End of inlined file: juce_mac_WebBrowserComponent.mm ***/
  225275. /*** Start of inlined file: juce_iphone_Audio.cpp ***/
  225276. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  225277. // compiled on its own).
  225278. #if JUCE_INCLUDED_FILE
  225279. class IPhoneAudioIODevice : public AudioIODevice
  225280. {
  225281. public:
  225282. IPhoneAudioIODevice (const String& deviceName)
  225283. : AudioIODevice (deviceName, "Audio"),
  225284. audioUnit (0),
  225285. isRunning (false),
  225286. callback (0),
  225287. actualBufferSize (0),
  225288. floatData (1, 2)
  225289. {
  225290. numInputChannels = 2;
  225291. numOutputChannels = 2;
  225292. preferredBufferSize = 0;
  225293. AudioSessionInitialize (0, 0, interruptionListenerStatic, this);
  225294. updateDeviceInfo();
  225295. }
  225296. ~IPhoneAudioIODevice()
  225297. {
  225298. close();
  225299. }
  225300. const StringArray getOutputChannelNames()
  225301. {
  225302. StringArray s;
  225303. s.add ("Left");
  225304. s.add ("Right");
  225305. return s;
  225306. }
  225307. const StringArray getInputChannelNames()
  225308. {
  225309. StringArray s;
  225310. if (audioInputIsAvailable)
  225311. {
  225312. s.add ("Left");
  225313. s.add ("Right");
  225314. }
  225315. return s;
  225316. }
  225317. int getNumSampleRates()
  225318. {
  225319. return 1;
  225320. }
  225321. double getSampleRate (int index)
  225322. {
  225323. return sampleRate;
  225324. }
  225325. int getNumBufferSizesAvailable()
  225326. {
  225327. return 1;
  225328. }
  225329. int getBufferSizeSamples (int index)
  225330. {
  225331. return getDefaultBufferSize();
  225332. }
  225333. int getDefaultBufferSize()
  225334. {
  225335. return 1024;
  225336. }
  225337. const String open (const BigInteger& inputChannels,
  225338. const BigInteger& outputChannels,
  225339. double sampleRate,
  225340. int bufferSize)
  225341. {
  225342. close();
  225343. lastError = String::empty;
  225344. preferredBufferSize = (bufferSize <= 0) ? getDefaultBufferSize() : bufferSize;
  225345. // xxx set up channel mapping
  225346. activeOutputChans = outputChannels;
  225347. activeOutputChans.setRange (2, activeOutputChans.getHighestBit(), false);
  225348. numOutputChannels = activeOutputChans.countNumberOfSetBits();
  225349. monoOutputChannelNumber = activeOutputChans.findNextSetBit (0);
  225350. activeInputChans = inputChannels;
  225351. activeInputChans.setRange (2, activeInputChans.getHighestBit(), false);
  225352. numInputChannels = activeInputChans.countNumberOfSetBits();
  225353. monoInputChannelNumber = activeInputChans.findNextSetBit (0);
  225354. AudioSessionSetActive (true);
  225355. UInt32 audioCategory = kAudioSessionCategory_PlayAndRecord;
  225356. AudioSessionSetProperty (kAudioSessionProperty_AudioCategory, sizeof (audioCategory), &audioCategory);
  225357. AudioSessionAddPropertyListener (kAudioSessionProperty_AudioRouteChange, propertyChangedStatic, this);
  225358. fixAudioRouteIfSetToReceiver();
  225359. updateDeviceInfo();
  225360. Float32 bufferDuration = preferredBufferSize / sampleRate;
  225361. AudioSessionSetProperty (kAudioSessionProperty_PreferredHardwareIOBufferDuration, sizeof (bufferDuration), &bufferDuration);
  225362. actualBufferSize = preferredBufferSize;
  225363. prepareFloatBuffers();
  225364. isRunning = true;
  225365. propertyChanged (0, 0, 0); // creates and starts the AU
  225366. lastError = audioUnit != 0 ? "" : "Couldn't open the device";
  225367. return lastError;
  225368. }
  225369. void close()
  225370. {
  225371. if (isRunning)
  225372. {
  225373. isRunning = false;
  225374. AudioSessionSetActive (false);
  225375. if (audioUnit != 0)
  225376. {
  225377. AudioComponentInstanceDispose (audioUnit);
  225378. audioUnit = 0;
  225379. }
  225380. }
  225381. }
  225382. bool isOpen()
  225383. {
  225384. return isRunning;
  225385. }
  225386. int getCurrentBufferSizeSamples()
  225387. {
  225388. return actualBufferSize;
  225389. }
  225390. double getCurrentSampleRate()
  225391. {
  225392. return sampleRate;
  225393. }
  225394. int getCurrentBitDepth()
  225395. {
  225396. return 16;
  225397. }
  225398. const BigInteger getActiveOutputChannels() const
  225399. {
  225400. return activeOutputChans;
  225401. }
  225402. const BigInteger getActiveInputChannels() const
  225403. {
  225404. return activeInputChans;
  225405. }
  225406. int getOutputLatencyInSamples()
  225407. {
  225408. return 0; //xxx
  225409. }
  225410. int getInputLatencyInSamples()
  225411. {
  225412. return 0; //xxx
  225413. }
  225414. void start (AudioIODeviceCallback* callback_)
  225415. {
  225416. if (isRunning && callback != callback_)
  225417. {
  225418. if (callback_ != 0)
  225419. callback_->audioDeviceAboutToStart (this);
  225420. const ScopedLock sl (callbackLock);
  225421. callback = callback_;
  225422. }
  225423. }
  225424. void stop()
  225425. {
  225426. if (isRunning)
  225427. {
  225428. AudioIODeviceCallback* lastCallback;
  225429. {
  225430. const ScopedLock sl (callbackLock);
  225431. lastCallback = callback;
  225432. callback = 0;
  225433. }
  225434. if (lastCallback != 0)
  225435. lastCallback->audioDeviceStopped();
  225436. }
  225437. }
  225438. bool isPlaying()
  225439. {
  225440. return isRunning && callback != 0;
  225441. }
  225442. const String getLastError()
  225443. {
  225444. return lastError;
  225445. }
  225446. private:
  225447. CriticalSection callbackLock;
  225448. Float64 sampleRate;
  225449. int numInputChannels, numOutputChannels;
  225450. int preferredBufferSize;
  225451. int actualBufferSize;
  225452. bool isRunning;
  225453. String lastError;
  225454. AudioStreamBasicDescription format;
  225455. AudioUnit audioUnit;
  225456. UInt32 audioInputIsAvailable;
  225457. AudioIODeviceCallback* callback;
  225458. BigInteger activeOutputChans, activeInputChans;
  225459. AudioSampleBuffer floatData;
  225460. float* inputChannels[3];
  225461. float* outputChannels[3];
  225462. bool monoInputChannelNumber, monoOutputChannelNumber;
  225463. void prepareFloatBuffers()
  225464. {
  225465. floatData.setSize (numInputChannels + numOutputChannels, actualBufferSize);
  225466. zerostruct (inputChannels);
  225467. zerostruct (outputChannels);
  225468. for (int i = 0; i < numInputChannels; ++i)
  225469. inputChannels[i] = floatData.getSampleData (i);
  225470. for (int i = 0; i < numOutputChannels; ++i)
  225471. outputChannels[i] = floatData.getSampleData (i + numInputChannels);
  225472. }
  225473. OSStatus process (AudioUnitRenderActionFlags* ioActionFlags, const AudioTimeStamp* inTimeStamp,
  225474. UInt32 inBusNumber, UInt32 inNumberFrames, AudioBufferList* ioData)
  225475. {
  225476. OSStatus err = noErr;
  225477. if (audioInputIsAvailable)
  225478. err = AudioUnitRender (audioUnit, ioActionFlags, inTimeStamp, 1, inNumberFrames, ioData);
  225479. const ScopedLock sl (callbackLock);
  225480. if (callback != 0)
  225481. {
  225482. if (audioInputIsAvailable && numInputChannels > 0)
  225483. {
  225484. short* shortData = (short*) ioData->mBuffers[0].mData;
  225485. if (numInputChannels >= 2)
  225486. {
  225487. for (UInt32 i = 0; i < inNumberFrames; ++i)
  225488. {
  225489. inputChannels[0][i] = *shortData++ * (1.0f / 32768.0f);
  225490. inputChannels[1][i] = *shortData++ * (1.0f / 32768.0f);
  225491. }
  225492. }
  225493. else
  225494. {
  225495. if (monoInputChannelNumber > 0)
  225496. ++shortData;
  225497. for (UInt32 i = 0; i < inNumberFrames; ++i)
  225498. {
  225499. inputChannels[0][i] = *shortData++ * (1.0f / 32768.0f);
  225500. ++shortData;
  225501. }
  225502. }
  225503. }
  225504. else
  225505. {
  225506. for (int i = numInputChannels; --i >= 0;)
  225507. zeromem (inputChannels[i], sizeof (float) * inNumberFrames);
  225508. }
  225509. callback->audioDeviceIOCallback ((const float**) inputChannels, numInputChannels,
  225510. outputChannels, numOutputChannels,
  225511. (int) inNumberFrames);
  225512. short* shortData = (short*) ioData->mBuffers[0].mData;
  225513. int n = 0;
  225514. if (numOutputChannels >= 2)
  225515. {
  225516. for (UInt32 i = 0; i < inNumberFrames; ++i)
  225517. {
  225518. shortData [n++] = (short) (outputChannels[0][i] * 32767.0f);
  225519. shortData [n++] = (short) (outputChannels[1][i] * 32767.0f);
  225520. }
  225521. }
  225522. else if (numOutputChannels == 1)
  225523. {
  225524. for (UInt32 i = 0; i < inNumberFrames; ++i)
  225525. {
  225526. const short s = (short) (outputChannels[monoOutputChannelNumber][i] * 32767.0f);
  225527. shortData [n++] = s;
  225528. shortData [n++] = s;
  225529. }
  225530. }
  225531. else
  225532. {
  225533. zeromem (ioData->mBuffers[0].mData, 2 * sizeof (short) * inNumberFrames);
  225534. }
  225535. }
  225536. else
  225537. {
  225538. zeromem (ioData->mBuffers[0].mData, 2 * sizeof (short) * inNumberFrames);
  225539. }
  225540. return err;
  225541. }
  225542. void updateDeviceInfo()
  225543. {
  225544. UInt32 size = sizeof (sampleRate);
  225545. AudioSessionGetProperty (kAudioSessionProperty_CurrentHardwareSampleRate, &size, &sampleRate);
  225546. size = sizeof (audioInputIsAvailable);
  225547. AudioSessionGetProperty (kAudioSessionProperty_AudioInputAvailable, &size, &audioInputIsAvailable);
  225548. }
  225549. void propertyChanged (AudioSessionPropertyID inID, UInt32 inDataSize, const void* inPropertyValue)
  225550. {
  225551. if (! isRunning)
  225552. return;
  225553. if (inPropertyValue != 0)
  225554. {
  225555. CFDictionaryRef routeChangeDictionary = (CFDictionaryRef) inPropertyValue;
  225556. CFNumberRef routeChangeReasonRef = (CFNumberRef) CFDictionaryGetValue (routeChangeDictionary,
  225557. CFSTR (kAudioSession_AudioRouteChangeKey_Reason));
  225558. SInt32 routeChangeReason;
  225559. CFNumberGetValue (routeChangeReasonRef, kCFNumberSInt32Type, &routeChangeReason);
  225560. if (routeChangeReason == kAudioSessionRouteChangeReason_OldDeviceUnavailable)
  225561. fixAudioRouteIfSetToReceiver();
  225562. }
  225563. updateDeviceInfo();
  225564. createAudioUnit();
  225565. AudioSessionSetActive (true);
  225566. if (audioUnit != 0)
  225567. {
  225568. UInt32 formatSize = sizeof (format);
  225569. AudioUnitGetProperty (audioUnit, kAudioUnitProperty_StreamFormat, kAudioUnitScope_Output, 1, &format, &formatSize);
  225570. Float32 bufferDuration = preferredBufferSize / sampleRate;
  225571. UInt32 bufferDurationSize = sizeof (bufferDuration);
  225572. AudioSessionGetProperty (kAudioSessionProperty_CurrentHardwareIOBufferDuration, &bufferDurationSize, &bufferDurationSize);
  225573. actualBufferSize = (int) (sampleRate * bufferDuration + 0.5);
  225574. AudioOutputUnitStart (audioUnit);
  225575. }
  225576. }
  225577. void interruptionListener (UInt32 inInterruption)
  225578. {
  225579. /*if (inInterruption == kAudioSessionBeginInterruption)
  225580. {
  225581. isRunning = false;
  225582. AudioOutputUnitStop (audioUnit);
  225583. if (juce_iPhoneShowModalAlert ("Audio Interrupted",
  225584. "This could have been interrupted by another application or by unplugging a headset",
  225585. @"Resume",
  225586. @"Cancel"))
  225587. {
  225588. isRunning = true;
  225589. propertyChanged (0, 0, 0);
  225590. }
  225591. }*/
  225592. if (inInterruption == kAudioSessionEndInterruption)
  225593. {
  225594. isRunning = true;
  225595. AudioSessionSetActive (true);
  225596. AudioOutputUnitStart (audioUnit);
  225597. }
  225598. }
  225599. static OSStatus processStatic (void* inRefCon, AudioUnitRenderActionFlags* ioActionFlags, const AudioTimeStamp* inTimeStamp,
  225600. UInt32 inBusNumber, UInt32 inNumberFrames, AudioBufferList* ioData)
  225601. {
  225602. return ((IPhoneAudioIODevice*) inRefCon)->process (ioActionFlags, inTimeStamp, inBusNumber, inNumberFrames, ioData);
  225603. }
  225604. static void propertyChangedStatic (void* inClientData, AudioSessionPropertyID inID, UInt32 inDataSize, const void* inPropertyValue)
  225605. {
  225606. ((IPhoneAudioIODevice*) inClientData)->propertyChanged (inID, inDataSize, inPropertyValue);
  225607. }
  225608. static void interruptionListenerStatic (void* inClientData, UInt32 inInterruption)
  225609. {
  225610. ((IPhoneAudioIODevice*) inClientData)->interruptionListener (inInterruption);
  225611. }
  225612. void resetFormat (const int numChannels)
  225613. {
  225614. memset (&format, 0, sizeof (format));
  225615. format.mFormatID = kAudioFormatLinearPCM;
  225616. format.mFormatFlags = kLinearPCMFormatFlagIsSignedInteger | kLinearPCMFormatFlagIsPacked;
  225617. format.mBitsPerChannel = 8 * sizeof (short);
  225618. format.mChannelsPerFrame = 2;
  225619. format.mFramesPerPacket = 1;
  225620. format.mBytesPerFrame = format.mBytesPerPacket = 2 * sizeof (short);
  225621. }
  225622. bool createAudioUnit()
  225623. {
  225624. if (audioUnit != 0)
  225625. {
  225626. AudioComponentInstanceDispose (audioUnit);
  225627. audioUnit = 0;
  225628. }
  225629. resetFormat (2);
  225630. AudioComponentDescription desc;
  225631. desc.componentType = kAudioUnitType_Output;
  225632. desc.componentSubType = kAudioUnitSubType_RemoteIO;
  225633. desc.componentManufacturer = kAudioUnitManufacturer_Apple;
  225634. desc.componentFlags = 0;
  225635. desc.componentFlagsMask = 0;
  225636. AudioComponent comp = AudioComponentFindNext (0, &desc);
  225637. AudioComponentInstanceNew (comp, &audioUnit);
  225638. if (audioUnit == 0)
  225639. return false;
  225640. const UInt32 one = 1;
  225641. AudioUnitSetProperty (audioUnit, kAudioOutputUnitProperty_EnableIO, kAudioUnitScope_Input, 1, &one, sizeof (one));
  225642. AudioChannelLayout layout;
  225643. layout.mChannelBitmap = 0;
  225644. layout.mNumberChannelDescriptions = 0;
  225645. layout.mChannelLayoutTag = kAudioChannelLayoutTag_Stereo;
  225646. AudioUnitSetProperty (audioUnit, kAudioUnitProperty_AudioChannelLayout, kAudioUnitScope_Input, 0, &layout, sizeof (layout));
  225647. AudioUnitSetProperty (audioUnit, kAudioUnitProperty_AudioChannelLayout, kAudioUnitScope_Output, 0, &layout, sizeof (layout));
  225648. AURenderCallbackStruct inputProc;
  225649. inputProc.inputProc = processStatic;
  225650. inputProc.inputProcRefCon = this;
  225651. AudioUnitSetProperty (audioUnit, kAudioUnitProperty_SetRenderCallback, kAudioUnitScope_Input, 0, &inputProc, sizeof (inputProc));
  225652. AudioUnitSetProperty (audioUnit, kAudioUnitProperty_StreamFormat, kAudioUnitScope_Input, 0, &format, sizeof (format));
  225653. AudioUnitSetProperty (audioUnit, kAudioUnitProperty_StreamFormat, kAudioUnitScope_Output, 1, &format, sizeof (format));
  225654. AudioUnitInitialize (audioUnit);
  225655. return true;
  225656. }
  225657. // If the routing is set to go through the receiver (i.e. the speaker, but quiet), this re-routes it
  225658. // to make it loud. Needed because by default when using an input + output, the output is kept quiet.
  225659. static void fixAudioRouteIfSetToReceiver()
  225660. {
  225661. CFStringRef audioRoute = 0;
  225662. UInt32 propertySize = sizeof (audioRoute);
  225663. if (AudioSessionGetProperty (kAudioSessionProperty_AudioRoute, &propertySize, &audioRoute) == noErr)
  225664. {
  225665. NSString* route = (NSString*) audioRoute;
  225666. //DBG ("audio route: " + nsStringToJuce (route));
  225667. if ([route hasPrefix: @"Receiver"])
  225668. {
  225669. UInt32 audioRouteOverride = kAudioSessionOverrideAudioRoute_Speaker;
  225670. AudioSessionSetProperty (kAudioSessionProperty_OverrideAudioRoute, sizeof (audioRouteOverride), &audioRouteOverride);
  225671. }
  225672. CFRelease (audioRoute);
  225673. }
  225674. }
  225675. IPhoneAudioIODevice (const IPhoneAudioIODevice&);
  225676. IPhoneAudioIODevice& operator= (const IPhoneAudioIODevice&);
  225677. };
  225678. class IPhoneAudioIODeviceType : public AudioIODeviceType
  225679. {
  225680. public:
  225681. IPhoneAudioIODeviceType()
  225682. : AudioIODeviceType ("iPhone Audio")
  225683. {
  225684. }
  225685. ~IPhoneAudioIODeviceType()
  225686. {
  225687. }
  225688. void scanForDevices()
  225689. {
  225690. }
  225691. const StringArray getDeviceNames (bool wantInputNames) const
  225692. {
  225693. StringArray s;
  225694. s.add ("iPhone Audio");
  225695. return s;
  225696. }
  225697. int getDefaultDeviceIndex (bool forInput) const
  225698. {
  225699. return 0;
  225700. }
  225701. int getIndexOfDevice (AudioIODevice* device, bool asInput) const
  225702. {
  225703. return device != 0 ? 0 : -1;
  225704. }
  225705. bool hasSeparateInputsAndOutputs() const { return false; }
  225706. AudioIODevice* createDevice (const String& outputDeviceName,
  225707. const String& inputDeviceName)
  225708. {
  225709. if (outputDeviceName.isNotEmpty() || inputDeviceName.isNotEmpty())
  225710. {
  225711. return new IPhoneAudioIODevice (outputDeviceName.isNotEmpty() ? outputDeviceName
  225712. : inputDeviceName);
  225713. }
  225714. return 0;
  225715. }
  225716. juce_UseDebuggingNewOperator
  225717. private:
  225718. IPhoneAudioIODeviceType (const IPhoneAudioIODeviceType&);
  225719. IPhoneAudioIODeviceType& operator= (const IPhoneAudioIODeviceType&);
  225720. };
  225721. AudioIODeviceType* juce_createAudioIODeviceType_iPhoneAudio()
  225722. {
  225723. return new IPhoneAudioIODeviceType();
  225724. }
  225725. #endif
  225726. /*** End of inlined file: juce_iphone_Audio.cpp ***/
  225727. /*** Start of inlined file: juce_mac_CoreMidi.cpp ***/
  225728. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  225729. // compiled on its own).
  225730. #if JUCE_INCLUDED_FILE
  225731. #if JUCE_MAC
  225732. #undef log
  225733. #define log(a) Logger::writeToLog(a)
  225734. static bool logAnyErrorsMidi (const OSStatus err, const int lineNum)
  225735. {
  225736. if (err == noErr)
  225737. return true;
  225738. log ("CoreMidi error: " + String (lineNum) + " - " + String::toHexString ((int) err));
  225739. jassertfalse
  225740. return false;
  225741. }
  225742. #undef OK
  225743. #define OK(a) logAnyErrorsMidi(a, __LINE__)
  225744. static const String getEndpointName (MIDIEndpointRef endpoint, bool isExternal)
  225745. {
  225746. String result;
  225747. CFStringRef str = 0;
  225748. MIDIObjectGetStringProperty (endpoint, kMIDIPropertyName, &str);
  225749. if (str != 0)
  225750. {
  225751. result = PlatformUtilities::cfStringToJuceString (str);
  225752. CFRelease (str);
  225753. str = 0;
  225754. }
  225755. MIDIEntityRef entity = 0;
  225756. MIDIEndpointGetEntity (endpoint, &entity);
  225757. if (entity == 0)
  225758. return result; // probably virtual
  225759. if (result.isEmpty())
  225760. {
  225761. // endpoint name has zero length - try the entity
  225762. MIDIObjectGetStringProperty (entity, kMIDIPropertyName, &str);
  225763. if (str != 0)
  225764. {
  225765. result += PlatformUtilities::cfStringToJuceString (str);
  225766. CFRelease (str);
  225767. str = 0;
  225768. }
  225769. }
  225770. // now consider the device's name
  225771. MIDIDeviceRef device = 0;
  225772. MIDIEntityGetDevice (entity, &device);
  225773. if (device == 0)
  225774. return result;
  225775. MIDIObjectGetStringProperty (device, kMIDIPropertyName, &str);
  225776. if (str != 0)
  225777. {
  225778. const String s (PlatformUtilities::cfStringToJuceString (str));
  225779. CFRelease (str);
  225780. // if an external device has only one entity, throw away
  225781. // the endpoint name and just use the device name
  225782. if (isExternal && MIDIDeviceGetNumberOfEntities (device) < 2)
  225783. {
  225784. result = s;
  225785. }
  225786. else if (! result.startsWithIgnoreCase (s))
  225787. {
  225788. // prepend the device name to the entity name
  225789. result = (s + " " + result).trimEnd();
  225790. }
  225791. }
  225792. return result;
  225793. }
  225794. static const String getConnectedEndpointName (MIDIEndpointRef endpoint)
  225795. {
  225796. String result;
  225797. // Does the endpoint have connections?
  225798. CFDataRef connections = 0;
  225799. int numConnections = 0;
  225800. MIDIObjectGetDataProperty (endpoint, kMIDIPropertyConnectionUniqueID, &connections);
  225801. if (connections != 0)
  225802. {
  225803. numConnections = (int) (CFDataGetLength (connections) / sizeof (MIDIUniqueID));
  225804. if (numConnections > 0)
  225805. {
  225806. const SInt32* pid = reinterpret_cast <const SInt32*> (CFDataGetBytePtr (connections));
  225807. for (int i = 0; i < numConnections; ++i, ++pid)
  225808. {
  225809. MIDIUniqueID uid = EndianS32_BtoN (*pid);
  225810. MIDIObjectRef connObject;
  225811. MIDIObjectType connObjectType;
  225812. OSStatus err = MIDIObjectFindByUniqueID (uid, &connObject, &connObjectType);
  225813. if (err == noErr)
  225814. {
  225815. String s;
  225816. if (connObjectType == kMIDIObjectType_ExternalSource
  225817. || connObjectType == kMIDIObjectType_ExternalDestination)
  225818. {
  225819. // Connected to an external device's endpoint (10.3 and later).
  225820. s = getEndpointName (static_cast <MIDIEndpointRef> (connObject), true);
  225821. }
  225822. else
  225823. {
  225824. // Connected to an external device (10.2) (or something else, catch-all)
  225825. CFStringRef str = 0;
  225826. MIDIObjectGetStringProperty (connObject, kMIDIPropertyName, &str);
  225827. if (str != 0)
  225828. {
  225829. s = PlatformUtilities::cfStringToJuceString (str);
  225830. CFRelease (str);
  225831. }
  225832. }
  225833. if (s.isNotEmpty())
  225834. {
  225835. if (result.isNotEmpty())
  225836. result += ", ";
  225837. result += s;
  225838. }
  225839. }
  225840. }
  225841. }
  225842. CFRelease (connections);
  225843. }
  225844. if (result.isNotEmpty())
  225845. return result;
  225846. // Here, either the endpoint had no connections, or we failed to obtain names for any of them.
  225847. return getEndpointName (endpoint, false);
  225848. }
  225849. const StringArray MidiOutput::getDevices()
  225850. {
  225851. StringArray s;
  225852. const ItemCount num = MIDIGetNumberOfDestinations();
  225853. for (ItemCount i = 0; i < num; ++i)
  225854. {
  225855. MIDIEndpointRef dest = MIDIGetDestination (i);
  225856. if (dest != 0)
  225857. {
  225858. String name (getConnectedEndpointName (dest));
  225859. if (name.isEmpty())
  225860. name = "<error>";
  225861. s.add (name);
  225862. }
  225863. else
  225864. {
  225865. s.add ("<error>");
  225866. }
  225867. }
  225868. return s;
  225869. }
  225870. int MidiOutput::getDefaultDeviceIndex()
  225871. {
  225872. return 0;
  225873. }
  225874. static MIDIClientRef globalMidiClient;
  225875. static bool hasGlobalClientBeenCreated = false;
  225876. static bool makeSureClientExists()
  225877. {
  225878. if (! hasGlobalClientBeenCreated)
  225879. {
  225880. String name ("JUCE");
  225881. if (JUCEApplication::getInstance() != 0)
  225882. name = JUCEApplication::getInstance()->getApplicationName();
  225883. CFStringRef appName = PlatformUtilities::juceStringToCFString (name);
  225884. hasGlobalClientBeenCreated = OK (MIDIClientCreate (appName, 0, 0, &globalMidiClient));
  225885. CFRelease (appName);
  225886. }
  225887. return hasGlobalClientBeenCreated;
  225888. }
  225889. class MidiPortAndEndpoint
  225890. {
  225891. public:
  225892. MidiPortAndEndpoint (MIDIPortRef port_, MIDIEndpointRef endPoint_)
  225893. : port (port_), endPoint (endPoint_)
  225894. {
  225895. }
  225896. ~MidiPortAndEndpoint()
  225897. {
  225898. if (port != 0)
  225899. MIDIPortDispose (port);
  225900. if (port == 0 && endPoint != 0) // if port == 0, it means we created the endpoint, so it's safe to delete it
  225901. MIDIEndpointDispose (endPoint);
  225902. }
  225903. MIDIPortRef port;
  225904. MIDIEndpointRef endPoint;
  225905. };
  225906. MidiOutput* MidiOutput::openDevice (int index)
  225907. {
  225908. MidiOutput* mo = 0;
  225909. if (((unsigned int) index) < (unsigned int) MIDIGetNumberOfDestinations())
  225910. {
  225911. MIDIEndpointRef endPoint = MIDIGetDestination (index);
  225912. CFStringRef pname;
  225913. if (OK (MIDIObjectGetStringProperty (endPoint, kMIDIPropertyName, &pname)))
  225914. {
  225915. log ("CoreMidi - opening out: " + PlatformUtilities::cfStringToJuceString (pname));
  225916. if (makeSureClientExists())
  225917. {
  225918. MIDIPortRef port;
  225919. if (OK (MIDIOutputPortCreate (globalMidiClient, pname, &port)))
  225920. {
  225921. mo = new MidiOutput();
  225922. mo->internal = new MidiPortAndEndpoint (port, endPoint);
  225923. }
  225924. }
  225925. CFRelease (pname);
  225926. }
  225927. }
  225928. return mo;
  225929. }
  225930. MidiOutput* MidiOutput::createNewDevice (const String& deviceName)
  225931. {
  225932. MidiOutput* mo = 0;
  225933. if (makeSureClientExists())
  225934. {
  225935. MIDIEndpointRef endPoint;
  225936. CFStringRef name = PlatformUtilities::juceStringToCFString (deviceName);
  225937. if (OK (MIDISourceCreate (globalMidiClient, name, &endPoint)))
  225938. {
  225939. mo = new MidiOutput();
  225940. mo->internal = new MidiPortAndEndpoint (0, endPoint);
  225941. }
  225942. CFRelease (name);
  225943. }
  225944. return mo;
  225945. }
  225946. MidiOutput::~MidiOutput()
  225947. {
  225948. delete (MidiPortAndEndpoint*) internal;
  225949. }
  225950. void MidiOutput::reset()
  225951. {
  225952. }
  225953. bool MidiOutput::getVolume (float& /*leftVol*/, float& /*rightVol*/)
  225954. {
  225955. return false;
  225956. }
  225957. void MidiOutput::setVolume (float /*leftVol*/, float /*rightVol*/)
  225958. {
  225959. }
  225960. void MidiOutput::sendMessageNow (const MidiMessage& message)
  225961. {
  225962. MidiPortAndEndpoint* const mpe = (MidiPortAndEndpoint*) internal;
  225963. if (message.isSysEx())
  225964. {
  225965. const int maxPacketSize = 256;
  225966. int pos = 0, bytesLeft = message.getRawDataSize();
  225967. const int numPackets = (bytesLeft + maxPacketSize - 1) / maxPacketSize;
  225968. HeapBlock <MIDIPacketList> packets;
  225969. packets.malloc (32 * numPackets + message.getRawDataSize(), 1);
  225970. packets->numPackets = numPackets;
  225971. MIDIPacket* p = packets->packet;
  225972. for (int i = 0; i < numPackets; ++i)
  225973. {
  225974. p->timeStamp = 0;
  225975. p->length = jmin (maxPacketSize, bytesLeft);
  225976. memcpy (p->data, message.getRawData() + pos, p->length);
  225977. pos += p->length;
  225978. bytesLeft -= p->length;
  225979. p = MIDIPacketNext (p);
  225980. }
  225981. if (mpe->port != 0)
  225982. MIDISend (mpe->port, mpe->endPoint, packets);
  225983. else
  225984. MIDIReceived (mpe->endPoint, packets);
  225985. }
  225986. else
  225987. {
  225988. MIDIPacketList packets;
  225989. packets.numPackets = 1;
  225990. packets.packet[0].timeStamp = 0;
  225991. packets.packet[0].length = message.getRawDataSize();
  225992. *(int*) (packets.packet[0].data) = *(const int*) message.getRawData();
  225993. if (mpe->port != 0)
  225994. MIDISend (mpe->port, mpe->endPoint, &packets);
  225995. else
  225996. MIDIReceived (mpe->endPoint, &packets);
  225997. }
  225998. }
  225999. const StringArray MidiInput::getDevices()
  226000. {
  226001. StringArray s;
  226002. const ItemCount num = MIDIGetNumberOfSources();
  226003. for (ItemCount i = 0; i < num; ++i)
  226004. {
  226005. MIDIEndpointRef source = MIDIGetSource (i);
  226006. if (source != 0)
  226007. {
  226008. String name (getConnectedEndpointName (source));
  226009. if (name.isEmpty())
  226010. name = "<error>";
  226011. s.add (name);
  226012. }
  226013. else
  226014. {
  226015. s.add ("<error>");
  226016. }
  226017. }
  226018. return s;
  226019. }
  226020. int MidiInput::getDefaultDeviceIndex()
  226021. {
  226022. return 0;
  226023. }
  226024. struct MidiPortAndCallback
  226025. {
  226026. MidiInput* input;
  226027. MidiPortAndEndpoint* portAndEndpoint;
  226028. MidiInputCallback* callback;
  226029. MemoryBlock pendingData;
  226030. int pendingBytes;
  226031. double pendingDataTime;
  226032. bool active;
  226033. void processSysex (const uint8*& d, int& size, const double time)
  226034. {
  226035. if (*d == 0xf0)
  226036. {
  226037. pendingBytes = 0;
  226038. pendingDataTime = time;
  226039. }
  226040. pendingData.ensureSize (pendingBytes + size, false);
  226041. uint8* totalMessage = (uint8*) pendingData.getData();
  226042. uint8* dest = totalMessage + pendingBytes;
  226043. while (size > 0)
  226044. {
  226045. if (pendingBytes > 0 && *d >= 0x80)
  226046. {
  226047. if (*d >= 0xfa || *d == 0xf8)
  226048. {
  226049. callback->handleIncomingMidiMessage (input, MidiMessage (*d, time));
  226050. ++d;
  226051. --size;
  226052. }
  226053. else
  226054. {
  226055. if (*d == 0xf7)
  226056. {
  226057. *dest++ = *d++;
  226058. pendingBytes++;
  226059. --size;
  226060. }
  226061. break;
  226062. }
  226063. }
  226064. else
  226065. {
  226066. *dest++ = *d++;
  226067. pendingBytes++;
  226068. --size;
  226069. }
  226070. }
  226071. if (totalMessage [pendingBytes - 1] == 0xf7)
  226072. {
  226073. callback->handleIncomingMidiMessage (input, MidiMessage (totalMessage, pendingBytes, pendingDataTime));
  226074. pendingBytes = 0;
  226075. }
  226076. else
  226077. {
  226078. callback->handlePartialSysexMessage (input, totalMessage, pendingBytes, pendingDataTime);
  226079. }
  226080. }
  226081. };
  226082. namespace CoreMidiCallbacks
  226083. {
  226084. static CriticalSection callbackLock;
  226085. static VoidArray activeCallbacks;
  226086. }
  226087. static void midiInputProc (const MIDIPacketList* pktlist,
  226088. void* readProcRefCon,
  226089. void* /*srcConnRefCon*/)
  226090. {
  226091. double time = Time::getMillisecondCounterHiRes() * 0.001;
  226092. const double originalTime = time;
  226093. MidiPortAndCallback* const mpc = (MidiPortAndCallback*) readProcRefCon;
  226094. const ScopedLock sl (CoreMidiCallbacks::callbackLock);
  226095. if (CoreMidiCallbacks::activeCallbacks.contains (mpc) && mpc->active)
  226096. {
  226097. const MIDIPacket* packet = &pktlist->packet[0];
  226098. for (unsigned int i = 0; i < pktlist->numPackets; ++i)
  226099. {
  226100. const uint8* d = (const uint8*) (packet->data);
  226101. int size = packet->length;
  226102. while (size > 0)
  226103. {
  226104. time = originalTime;
  226105. if (mpc->pendingBytes > 0 || d[0] == 0xf0)
  226106. {
  226107. mpc->processSysex (d, size, time);
  226108. }
  226109. else
  226110. {
  226111. int used = 0;
  226112. const MidiMessage m (d, size, used, 0, time);
  226113. if (used <= 0)
  226114. {
  226115. jassertfalse // malformed midi message
  226116. break;
  226117. }
  226118. else
  226119. {
  226120. mpc->callback->handleIncomingMidiMessage (mpc->input, m);
  226121. }
  226122. size -= used;
  226123. d += used;
  226124. }
  226125. }
  226126. packet = MIDIPacketNext (packet);
  226127. }
  226128. }
  226129. }
  226130. MidiInput* MidiInput::openDevice (int index, MidiInputCallback* callback)
  226131. {
  226132. MidiInput* mi = 0;
  226133. if (((unsigned int) index) < (unsigned int) MIDIGetNumberOfSources())
  226134. {
  226135. MIDIEndpointRef endPoint = MIDIGetSource (index);
  226136. if (endPoint != 0)
  226137. {
  226138. CFStringRef pname;
  226139. if (OK (MIDIObjectGetStringProperty (endPoint, kMIDIPropertyName, &pname)))
  226140. {
  226141. log ("CoreMidi - opening inp: " + PlatformUtilities::cfStringToJuceString (pname));
  226142. if (makeSureClientExists())
  226143. {
  226144. MIDIPortRef port;
  226145. ScopedPointer <MidiPortAndCallback> mpc (new MidiPortAndCallback());
  226146. mpc->active = false;
  226147. if (OK (MIDIInputPortCreate (globalMidiClient, pname, midiInputProc, mpc, &port)))
  226148. {
  226149. if (OK (MIDIPortConnectSource (port, endPoint, 0)))
  226150. {
  226151. mpc->portAndEndpoint = new MidiPortAndEndpoint (port, endPoint);
  226152. mpc->callback = callback;
  226153. mpc->pendingBytes = 0;
  226154. mpc->pendingData.ensureSize (128);
  226155. mi = new MidiInput (getDevices() [index]);
  226156. mpc->input = mi;
  226157. mi->internal = mpc;
  226158. const ScopedLock sl (CoreMidiCallbacks::callbackLock);
  226159. CoreMidiCallbacks::activeCallbacks.add (mpc.release());
  226160. }
  226161. else
  226162. {
  226163. OK (MIDIPortDispose (port));
  226164. }
  226165. }
  226166. }
  226167. }
  226168. CFRelease (pname);
  226169. }
  226170. }
  226171. return mi;
  226172. }
  226173. MidiInput* MidiInput::createNewDevice (const String& deviceName, MidiInputCallback* callback)
  226174. {
  226175. MidiInput* mi = 0;
  226176. if (makeSureClientExists())
  226177. {
  226178. ScopedPointer <MidiPortAndCallback> mpc (new MidiPortAndCallback());
  226179. mpc->active = false;
  226180. MIDIEndpointRef endPoint;
  226181. CFStringRef name = PlatformUtilities::juceStringToCFString(deviceName);
  226182. if (OK (MIDIDestinationCreate (globalMidiClient, name, midiInputProc, mpc, &endPoint)))
  226183. {
  226184. mpc->portAndEndpoint = new MidiPortAndEndpoint (0, endPoint);
  226185. mpc->callback = callback;
  226186. mpc->pendingBytes = 0;
  226187. mpc->pendingData.ensureSize (128);
  226188. mi = new MidiInput (deviceName);
  226189. mpc->input = mi;
  226190. mi->internal = mpc;
  226191. const ScopedLock sl (CoreMidiCallbacks::callbackLock);
  226192. CoreMidiCallbacks::activeCallbacks.add (mpc.release());
  226193. }
  226194. CFRelease (name);
  226195. }
  226196. return mi;
  226197. }
  226198. MidiInput::MidiInput (const String& name_)
  226199. : name (name_)
  226200. {
  226201. }
  226202. MidiInput::~MidiInput()
  226203. {
  226204. MidiPortAndCallback* const mpc = (MidiPortAndCallback*) internal;
  226205. mpc->active = false;
  226206. {
  226207. const ScopedLock sl (CoreMidiCallbacks::callbackLock);
  226208. CoreMidiCallbacks::activeCallbacks.removeValue (mpc);
  226209. }
  226210. if (mpc->portAndEndpoint->port != 0)
  226211. OK (MIDIPortDisconnectSource (mpc->portAndEndpoint->port, mpc->portAndEndpoint->endPoint));
  226212. delete mpc->portAndEndpoint;
  226213. delete mpc;
  226214. }
  226215. void MidiInput::start()
  226216. {
  226217. const ScopedLock sl (CoreMidiCallbacks::callbackLock);
  226218. ((MidiPortAndCallback*) internal)->active = true;
  226219. }
  226220. void MidiInput::stop()
  226221. {
  226222. const ScopedLock sl (CoreMidiCallbacks::callbackLock);
  226223. ((MidiPortAndCallback*) internal)->active = false;
  226224. }
  226225. #undef log
  226226. #else
  226227. MidiOutput::~MidiOutput()
  226228. {
  226229. }
  226230. void MidiOutput::reset()
  226231. {
  226232. }
  226233. bool MidiOutput::getVolume (float& /*leftVol*/, float& /*rightVol*/)
  226234. {
  226235. return false;
  226236. }
  226237. void MidiOutput::setVolume (float /*leftVol*/, float /*rightVol*/)
  226238. {
  226239. }
  226240. void MidiOutput::sendMessageNow (const MidiMessage& message)
  226241. {
  226242. }
  226243. const StringArray MidiOutput::getDevices()
  226244. {
  226245. return StringArray();
  226246. }
  226247. MidiOutput* MidiOutput::openDevice (int index)
  226248. {
  226249. return 0;
  226250. }
  226251. const StringArray MidiInput::getDevices()
  226252. {
  226253. return StringArray();
  226254. }
  226255. MidiInput* MidiInput::openDevice (int index, MidiInputCallback* callback)
  226256. {
  226257. return 0;
  226258. }
  226259. #endif
  226260. #endif
  226261. /*** End of inlined file: juce_mac_CoreMidi.cpp ***/
  226262. #else
  226263. /*** Start of inlined file: juce_mac_Fonts.mm ***/
  226264. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  226265. // compiled on its own).
  226266. #if JUCE_INCLUDED_FILE
  226267. #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
  226268. #define SUPPORT_10_4_FONTS 1
  226269. #define NEW_CGFONT_FUNCTIONS_UNAVAILABLE (CGFontCreateWithFontName == 0)
  226270. #if MAC_OS_X_VERSION_MAX_ALLOWED < MAC_OS_X_VERSION_10_5
  226271. #define SUPPORT_ONLY_10_4_FONTS 1
  226272. #endif
  226273. END_JUCE_NAMESPACE
  226274. @interface NSFont (PrivateHack)
  226275. - (NSGlyph) _defaultGlyphForChar: (unichar) theChar;
  226276. @end
  226277. BEGIN_JUCE_NAMESPACE
  226278. #endif
  226279. class MacTypeface : public Typeface
  226280. {
  226281. public:
  226282. MacTypeface (const Font& font)
  226283. : Typeface (font.getTypefaceName())
  226284. {
  226285. const ScopedAutoReleasePool pool;
  226286. renderingTransform = CGAffineTransformIdentity;
  226287. bool needsItalicTransform = false;
  226288. #if JUCE_IPHONE
  226289. NSString* fontName = juceStringToNS (font.getTypefaceName());
  226290. if (font.isItalic() || font.isBold())
  226291. {
  226292. NSArray* familyFonts = [UIFont fontNamesForFamilyName: juceStringToNS (font.getTypefaceName())];
  226293. for (NSString* i in familyFonts)
  226294. {
  226295. const String fn (nsStringToJuce (i));
  226296. const String afterDash (fn.fromFirstOccurrenceOf ("-", false, false));
  226297. const bool probablyBold = afterDash.containsIgnoreCase ("bold") || fn.endsWithIgnoreCase ("bold");
  226298. const bool probablyItalic = afterDash.containsIgnoreCase ("oblique")
  226299. || afterDash.containsIgnoreCase ("italic")
  226300. || fn.endsWithIgnoreCase ("oblique")
  226301. || fn.endsWithIgnoreCase ("italic");
  226302. if (probablyBold == font.isBold()
  226303. && probablyItalic == font.isItalic())
  226304. {
  226305. fontName = i;
  226306. needsItalicTransform = false;
  226307. break;
  226308. }
  226309. else if (probablyBold && (! probablyItalic) && probablyBold == font.isBold())
  226310. {
  226311. fontName = i;
  226312. needsItalicTransform = true; // not ideal, so carry on in case we find a better one
  226313. }
  226314. }
  226315. if (needsItalicTransform)
  226316. renderingTransform.c = 0.15f;
  226317. }
  226318. fontRef = CGFontCreateWithFontName ((CFStringRef) fontName);
  226319. const int ascender = abs (CGFontGetAscent (fontRef));
  226320. const float totalHeight = ascender + abs (CGFontGetDescent (fontRef));
  226321. ascent = ascender / totalHeight;
  226322. unitsToHeightScaleFactor = 1.0f / totalHeight;
  226323. fontHeightToCGSizeFactor = CGFontGetUnitsPerEm (fontRef) / totalHeight;
  226324. #else
  226325. nsFont = [NSFont fontWithName: juceStringToNS (font.getTypefaceName()) size: 1024];
  226326. if (font.isItalic())
  226327. {
  226328. NSFont* newFont = [[NSFontManager sharedFontManager] convertFont: nsFont
  226329. toHaveTrait: NSItalicFontMask];
  226330. if (newFont == nsFont)
  226331. needsItalicTransform = true; // couldn't find a proper italic version, so fake it with a transform..
  226332. nsFont = newFont;
  226333. }
  226334. if (font.isBold())
  226335. nsFont = [[NSFontManager sharedFontManager] convertFont: nsFont toHaveTrait: NSBoldFontMask];
  226336. [nsFont retain];
  226337. ascent = std::abs ((float) [nsFont ascender]);
  226338. float totalSize = ascent + std::abs ((float) [nsFont descender]);
  226339. ascent /= totalSize;
  226340. pathTransform = AffineTransform::identity.scale (1.0f / totalSize, 1.0f / totalSize);
  226341. if (needsItalicTransform)
  226342. {
  226343. pathTransform = pathTransform.sheared (-0.15f, 0.0f);
  226344. renderingTransform.c = 0.15f;
  226345. }
  226346. #if SUPPORT_ONLY_10_4_FONTS
  226347. ATSFontRef atsFont = ATSFontFindFromName ((CFStringRef) [nsFont fontName], kATSOptionFlagsDefault);
  226348. if (atsFont == 0)
  226349. atsFont = ATSFontFindFromPostScriptName ((CFStringRef) [nsFont fontName], kATSOptionFlagsDefault);
  226350. fontRef = CGFontCreateWithPlatformFont (&atsFont);
  226351. const float totalHeight = std::abs ([nsFont ascender]) + std::abs ([nsFont descender]);
  226352. unitsToHeightScaleFactor = 1.0f / totalHeight;
  226353. fontHeightToCGSizeFactor = 1024.0f / totalHeight;
  226354. #else
  226355. #if SUPPORT_10_4_FONTS
  226356. if (NEW_CGFONT_FUNCTIONS_UNAVAILABLE)
  226357. {
  226358. ATSFontRef atsFont = ATSFontFindFromName ((CFStringRef) [nsFont fontName], kATSOptionFlagsDefault);
  226359. if (atsFont == 0)
  226360. atsFont = ATSFontFindFromPostScriptName ((CFStringRef) [nsFont fontName], kATSOptionFlagsDefault);
  226361. fontRef = CGFontCreateWithPlatformFont (&atsFont);
  226362. const float totalHeight = std::abs ([nsFont ascender]) + std::abs ([nsFont descender]);
  226363. unitsToHeightScaleFactor = 1.0f / totalHeight;
  226364. fontHeightToCGSizeFactor = 1024.0f / totalHeight;
  226365. }
  226366. else
  226367. #endif
  226368. {
  226369. fontRef = CGFontCreateWithFontName ((CFStringRef) [nsFont fontName]);
  226370. const int totalHeight = abs (CGFontGetAscent (fontRef)) + abs (CGFontGetDescent (fontRef));
  226371. unitsToHeightScaleFactor = 1.0f / totalHeight;
  226372. fontHeightToCGSizeFactor = CGFontGetUnitsPerEm (fontRef) / (float) totalHeight;
  226373. }
  226374. #endif
  226375. #endif
  226376. }
  226377. ~MacTypeface()
  226378. {
  226379. #if ! JUCE_IPHONE
  226380. [nsFont release];
  226381. #endif
  226382. if (fontRef != 0)
  226383. CGFontRelease (fontRef);
  226384. }
  226385. float getAscent() const
  226386. {
  226387. return ascent;
  226388. }
  226389. float getDescent() const
  226390. {
  226391. return 1.0f - ascent;
  226392. }
  226393. float getStringWidth (const String& text)
  226394. {
  226395. if (fontRef == 0 || text.isEmpty())
  226396. return 0;
  226397. const int length = text.length();
  226398. HeapBlock <CGGlyph> glyphs;
  226399. createGlyphsForString (text, length, glyphs);
  226400. float x = 0;
  226401. #if SUPPORT_ONLY_10_4_FONTS
  226402. HeapBlock <NSSize> advances (length);
  226403. [nsFont getAdvancements: advances forGlyphs: reinterpret_cast <NSGlyph*> (glyphs.getData()) count: length];
  226404. for (int i = 0; i < length; ++i)
  226405. x += advances[i].width;
  226406. #else
  226407. #if SUPPORT_10_4_FONTS
  226408. if (NEW_CGFONT_FUNCTIONS_UNAVAILABLE)
  226409. {
  226410. HeapBlock <NSSize> advances (length);
  226411. [nsFont getAdvancements: advances forGlyphs: reinterpret_cast<NSGlyph*> (glyphs.getData()) count: length];
  226412. for (int i = 0; i < length; ++i)
  226413. x += advances[i].width;
  226414. }
  226415. else
  226416. #endif
  226417. {
  226418. HeapBlock <int> advances (length);
  226419. if (CGFontGetGlyphAdvances (fontRef, glyphs, length, advances))
  226420. for (int i = 0; i < length; ++i)
  226421. x += advances[i];
  226422. }
  226423. #endif
  226424. return x * unitsToHeightScaleFactor;
  226425. }
  226426. void getGlyphPositions (const String& text, Array <int>& resultGlyphs, Array <float>& xOffsets)
  226427. {
  226428. xOffsets.add (0);
  226429. if (fontRef == 0 || text.isEmpty())
  226430. return;
  226431. const int length = text.length();
  226432. HeapBlock <CGGlyph> glyphs;
  226433. createGlyphsForString (text, length, glyphs);
  226434. #if SUPPORT_ONLY_10_4_FONTS
  226435. HeapBlock <NSSize> advances (length);
  226436. [nsFont getAdvancements: advances forGlyphs: reinterpret_cast <NSGlyph*> (glyphs.getData()) count: length];
  226437. int x = 0;
  226438. for (int i = 0; i < length; ++i)
  226439. {
  226440. x += advances[i].width;
  226441. xOffsets.add (x * unitsToHeightScaleFactor);
  226442. resultGlyphs.add (reinterpret_cast <NSGlyph*> (glyphs.getData())[i]);
  226443. }
  226444. #else
  226445. #if SUPPORT_10_4_FONTS
  226446. if (NEW_CGFONT_FUNCTIONS_UNAVAILABLE)
  226447. {
  226448. HeapBlock <NSSize> advances (length);
  226449. NSGlyph* const nsGlyphs = reinterpret_cast<NSGlyph*> (glyphs.getData());
  226450. [nsFont getAdvancements: advances forGlyphs: nsGlyphs count: length];
  226451. float x = 0;
  226452. for (int i = 0; i < length; ++i)
  226453. {
  226454. x += advances[i].width;
  226455. xOffsets.add (x * unitsToHeightScaleFactor);
  226456. resultGlyphs.add (nsGlyphs[i]);
  226457. }
  226458. }
  226459. else
  226460. #endif
  226461. {
  226462. HeapBlock <int> advances (length);
  226463. if (CGFontGetGlyphAdvances (fontRef, glyphs, length, advances))
  226464. {
  226465. int x = 0;
  226466. for (int i = 0; i < length; ++i)
  226467. {
  226468. x += advances [i];
  226469. xOffsets.add (x * unitsToHeightScaleFactor);
  226470. resultGlyphs.add (glyphs[i]);
  226471. }
  226472. }
  226473. }
  226474. #endif
  226475. }
  226476. bool getOutlineForGlyph (int glyphNumber, Path& path)
  226477. {
  226478. #if JUCE_IPHONE
  226479. return false;
  226480. #else
  226481. if (nsFont == 0)
  226482. return false;
  226483. // we might need to apply a transform to the path, so it mustn't have anything else in it
  226484. jassert (path.isEmpty());
  226485. const ScopedAutoReleasePool pool;
  226486. NSBezierPath* bez = [NSBezierPath bezierPath];
  226487. [bez moveToPoint: NSMakePoint (0, 0)];
  226488. [bez appendBezierPathWithGlyph: (NSGlyph) glyphNumber
  226489. inFont: nsFont];
  226490. for (int i = 0; i < [bez elementCount]; ++i)
  226491. {
  226492. NSPoint p[3];
  226493. switch ([bez elementAtIndex: i associatedPoints: p])
  226494. {
  226495. case NSMoveToBezierPathElement:
  226496. path.startNewSubPath ((float) p[0].x, (float) -p[0].y);
  226497. break;
  226498. case NSLineToBezierPathElement:
  226499. path.lineTo ((float) p[0].x, (float) -p[0].y);
  226500. break;
  226501. case NSCurveToBezierPathElement:
  226502. path.cubicTo ((float) p[0].x, (float) -p[0].y, (float) p[1].x, (float) -p[1].y, (float) p[2].x, (float) -p[2].y);
  226503. break;
  226504. case NSClosePathBezierPathElement:
  226505. path.closeSubPath();
  226506. break;
  226507. default:
  226508. jassertfalse
  226509. break;
  226510. }
  226511. }
  226512. path.applyTransform (pathTransform);
  226513. return true;
  226514. #endif
  226515. }
  226516. juce_UseDebuggingNewOperator
  226517. CGFontRef fontRef;
  226518. float fontHeightToCGSizeFactor;
  226519. CGAffineTransform renderingTransform;
  226520. private:
  226521. float ascent, unitsToHeightScaleFactor;
  226522. #if JUCE_IPHONE
  226523. #else
  226524. NSFont* nsFont;
  226525. AffineTransform pathTransform;
  226526. #endif
  226527. void createGlyphsForString (const juce_wchar* const text, const int length, HeapBlock <CGGlyph>& glyphs)
  226528. {
  226529. #if SUPPORT_10_4_FONTS
  226530. #if ! SUPPORT_ONLY_10_4_FONTS
  226531. if (NEW_CGFONT_FUNCTIONS_UNAVAILABLE)
  226532. #endif
  226533. {
  226534. glyphs.malloc (sizeof (NSGlyph) * length, 1);
  226535. NSGlyph* const nsGlyphs = reinterpret_cast<NSGlyph*> (glyphs.getData());
  226536. for (int i = 0; i < length; ++i)
  226537. nsGlyphs[i] = (NSGlyph) [nsFont _defaultGlyphForChar: text[i]];
  226538. return;
  226539. }
  226540. #endif
  226541. #if ! SUPPORT_ONLY_10_4_FONTS
  226542. if (charToGlyphMapper == 0)
  226543. charToGlyphMapper = new CharToGlyphMapper (fontRef);
  226544. glyphs.malloc (length);
  226545. for (int i = 0; i < length; ++i)
  226546. glyphs[i] = (CGGlyph) charToGlyphMapper->getGlyphForCharacter (text[i]);
  226547. #endif
  226548. }
  226549. #if ! SUPPORT_ONLY_10_4_FONTS
  226550. // Reads a CGFontRef's character map table to convert unicode into glyph numbers
  226551. class CharToGlyphMapper
  226552. {
  226553. public:
  226554. CharToGlyphMapper (CGFontRef fontRef)
  226555. : segCount (0), endCode (0), startCode (0), idDelta (0),
  226556. idRangeOffset (0), glyphIndexes (0)
  226557. {
  226558. CFDataRef cmapTable = CGFontCopyTableForTag (fontRef, 'cmap');
  226559. if (cmapTable != 0)
  226560. {
  226561. const int numSubtables = getValue16 (cmapTable, 2);
  226562. for (int i = 0; i < numSubtables; ++i)
  226563. {
  226564. if (getValue16 (cmapTable, i * 8 + 4) == 0) // check for platform ID of 0
  226565. {
  226566. const int offset = getValue32 (cmapTable, i * 8 + 8);
  226567. if (getValue16 (cmapTable, offset) == 4) // check that it's format 4..
  226568. {
  226569. const int length = getValue16 (cmapTable, offset + 2);
  226570. const int segCountX2 = getValue16 (cmapTable, offset + 6);
  226571. segCount = segCountX2 / 2;
  226572. const int endCodeOffset = offset + 14;
  226573. const int startCodeOffset = endCodeOffset + 2 + segCountX2;
  226574. const int idDeltaOffset = startCodeOffset + segCountX2;
  226575. const int idRangeOffsetOffset = idDeltaOffset + segCountX2;
  226576. const int glyphIndexesOffset = idRangeOffsetOffset + segCountX2;
  226577. endCode = CFDataCreate (kCFAllocatorDefault, CFDataGetBytePtr (cmapTable) + endCodeOffset, segCountX2);
  226578. startCode = CFDataCreate (kCFAllocatorDefault, CFDataGetBytePtr (cmapTable) + startCodeOffset, segCountX2);
  226579. idDelta = CFDataCreate (kCFAllocatorDefault, CFDataGetBytePtr (cmapTable) + idDeltaOffset, segCountX2);
  226580. idRangeOffset = CFDataCreate (kCFAllocatorDefault, CFDataGetBytePtr (cmapTable) + idRangeOffsetOffset, segCountX2);
  226581. glyphIndexes = CFDataCreate (kCFAllocatorDefault, CFDataGetBytePtr (cmapTable) + glyphIndexesOffset, offset + length - glyphIndexesOffset);
  226582. }
  226583. break;
  226584. }
  226585. }
  226586. CFRelease (cmapTable);
  226587. }
  226588. }
  226589. ~CharToGlyphMapper()
  226590. {
  226591. if (endCode != 0)
  226592. {
  226593. CFRelease (endCode);
  226594. CFRelease (startCode);
  226595. CFRelease (idDelta);
  226596. CFRelease (idRangeOffset);
  226597. CFRelease (glyphIndexes);
  226598. }
  226599. }
  226600. int getGlyphForCharacter (const juce_wchar c) const
  226601. {
  226602. for (int i = 0; i < segCount; ++i)
  226603. {
  226604. if (getValue16 (endCode, i * 2) >= c)
  226605. {
  226606. const int start = getValue16 (startCode, i * 2);
  226607. if (start > c)
  226608. break;
  226609. const int delta = getValue16 (idDelta, i * 2);
  226610. const int rangeOffset = getValue16 (idRangeOffset, i * 2);
  226611. if (rangeOffset == 0)
  226612. return delta + c;
  226613. else
  226614. return getValue16 (glyphIndexes, 2 * ((rangeOffset / 2) + (c - start) - (segCount - i)));
  226615. }
  226616. }
  226617. // If we failed to find it "properly", this dodgy fall-back seems to do the trick for most fonts!
  226618. return jmax (-1, c - 29);
  226619. }
  226620. private:
  226621. int segCount;
  226622. CFDataRef endCode, startCode, idDelta, idRangeOffset, glyphIndexes;
  226623. static uint16 getValue16 (CFDataRef data, const int index)
  226624. {
  226625. return CFSwapInt16BigToHost (*(UInt16*) (CFDataGetBytePtr (data) + index));
  226626. }
  226627. static uint32 getValue32 (CFDataRef data, const int index)
  226628. {
  226629. return CFSwapInt32BigToHost (*(UInt32*) (CFDataGetBytePtr (data) + index));
  226630. }
  226631. };
  226632. ScopedPointer <CharToGlyphMapper> charToGlyphMapper;
  226633. #endif
  226634. MacTypeface (const MacTypeface&);
  226635. MacTypeface& operator= (const MacTypeface&);
  226636. };
  226637. const Typeface::Ptr Typeface::createSystemTypefaceFor (const Font& font)
  226638. {
  226639. return new MacTypeface (font);
  226640. }
  226641. const StringArray Font::findAllTypefaceNames()
  226642. {
  226643. StringArray names;
  226644. const ScopedAutoReleasePool pool;
  226645. #if JUCE_IPHONE
  226646. NSArray* fonts = [UIFont familyNames];
  226647. #else
  226648. NSArray* fonts = [[NSFontManager sharedFontManager] availableFontFamilies];
  226649. #endif
  226650. for (unsigned int i = 0; i < [fonts count]; ++i)
  226651. names.add (nsStringToJuce ((NSString*) [fonts objectAtIndex: i]));
  226652. names.sort (true);
  226653. return names;
  226654. }
  226655. void Font::getPlatformDefaultFontNames (String& defaultSans, String& defaultSerif, String& defaultFixed)
  226656. {
  226657. #if JUCE_IPHONE
  226658. defaultSans = "Helvetica";
  226659. defaultSerif = "Times New Roman";
  226660. defaultFixed = "Courier New";
  226661. #else
  226662. defaultSans = "Lucida Grande";
  226663. defaultSerif = "Times New Roman";
  226664. defaultFixed = "Monaco";
  226665. #endif
  226666. }
  226667. #endif
  226668. /*** End of inlined file: juce_mac_Fonts.mm ***/
  226669. // (must go before juce_mac_CoreGraphicsContext.mm)
  226670. /*** Start of inlined file: juce_mac_CoreGraphicsContext.mm ***/
  226671. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  226672. // compiled on its own).
  226673. #if JUCE_INCLUDED_FILE
  226674. class CoreGraphicsImage : public Image
  226675. {
  226676. public:
  226677. CoreGraphicsImage (const PixelFormat format_,
  226678. const int imageWidth_,
  226679. const int imageHeight_,
  226680. const bool clearImage)
  226681. : Image (format_, imageWidth_, imageHeight_, clearImage)
  226682. {
  226683. CGColorSpaceRef colourSpace = (format == Image::SingleChannel) ? CGColorSpaceCreateDeviceGray()
  226684. : CGColorSpaceCreateDeviceRGB();
  226685. context = CGBitmapContextCreate (imageData, imageWidth, imageHeight, 8, lineStride,
  226686. colourSpace, getCGImageFlags (*this));
  226687. CGColorSpaceRelease (colourSpace);
  226688. }
  226689. ~CoreGraphicsImage()
  226690. {
  226691. CGContextRelease (context);
  226692. }
  226693. LowLevelGraphicsContext* createLowLevelContext();
  226694. static CGImageRef createImage (const Image& juceImage, const bool forAlpha, CGColorSpaceRef colourSpace)
  226695. {
  226696. const CoreGraphicsImage* nativeImage = dynamic_cast <const CoreGraphicsImage*> (&juceImage);
  226697. if (nativeImage != 0 && (juceImage.getFormat() == Image::SingleChannel || ! forAlpha))
  226698. {
  226699. return CGBitmapContextCreateImage (nativeImage->context);
  226700. }
  226701. else
  226702. {
  226703. const Image::BitmapData srcData (juceImage, 0, 0, juceImage.getWidth(), juceImage.getHeight());
  226704. CGDataProviderRef provider = CGDataProviderCreateWithData (0, srcData.data, srcData.lineStride * srcData.height, 0);
  226705. CGImageRef imageRef = CGImageCreate (srcData.width, srcData.height,
  226706. 8, srcData.pixelStride * 8, srcData.lineStride,
  226707. colourSpace, getCGImageFlags (juceImage), provider,
  226708. 0, true, kCGRenderingIntentDefault);
  226709. CGDataProviderRelease (provider);
  226710. return imageRef;
  226711. }
  226712. }
  226713. #if JUCE_MAC
  226714. static NSImage* createNSImage (const Image& image)
  226715. {
  226716. const ScopedAutoReleasePool pool;
  226717. NSImage* im = [[NSImage alloc] init];
  226718. [im setSize: NSMakeSize (image.getWidth(), image.getHeight())];
  226719. [im lockFocus];
  226720. CGColorSpaceRef colourSpace = CGColorSpaceCreateDeviceRGB();
  226721. CGImageRef imageRef = createImage (image, false, colourSpace);
  226722. CGColorSpaceRelease (colourSpace);
  226723. CGContextRef cg = (CGContextRef) [[NSGraphicsContext currentContext] graphicsPort];
  226724. CGContextDrawImage (cg, CGRectMake (0, 0, image.getWidth(), image.getHeight()), imageRef);
  226725. CGImageRelease (imageRef);
  226726. [im unlockFocus];
  226727. return im;
  226728. }
  226729. #endif
  226730. CGContextRef context;
  226731. private:
  226732. static CGBitmapInfo getCGImageFlags (const Image& image)
  226733. {
  226734. #if JUCE_BIG_ENDIAN
  226735. return image.getFormat() == Image::ARGB ? (kCGImageAlphaPremultipliedFirst | kCGBitmapByteOrder32Big) : kCGBitmapByteOrderDefault;
  226736. #else
  226737. return image.getFormat() == Image::ARGB ? (kCGImageAlphaPremultipliedFirst | kCGBitmapByteOrder32Little) : kCGBitmapByteOrderDefault;
  226738. #endif
  226739. }
  226740. };
  226741. Image* Image::createNativeImage (const PixelFormat format, const int imageWidth, const int imageHeight, const bool clearImage)
  226742. {
  226743. #if USE_COREGRAPHICS_RENDERING
  226744. return new CoreGraphicsImage (format == RGB ? ARGB : format, imageWidth, imageHeight, clearImage);
  226745. #else
  226746. return new Image (format, imageWidth, imageHeight, clearImage);
  226747. #endif
  226748. }
  226749. class CoreGraphicsContext : public LowLevelGraphicsContext
  226750. {
  226751. public:
  226752. CoreGraphicsContext (CGContextRef context_, const float flipHeight_)
  226753. : context (context_),
  226754. flipHeight (flipHeight_),
  226755. state (new SavedState()),
  226756. numGradientLookupEntries (0)
  226757. {
  226758. CGContextRetain (context);
  226759. CGContextSaveGState(context);
  226760. CGContextSetShouldSmoothFonts (context, true);
  226761. CGContextSetShouldAntialias (context, true);
  226762. CGContextSetBlendMode (context, kCGBlendModeNormal);
  226763. rgbColourSpace = CGColorSpaceCreateDeviceRGB();
  226764. greyColourSpace = CGColorSpaceCreateDeviceGray();
  226765. gradientCallbacks.version = 0;
  226766. gradientCallbacks.evaluate = gradientCallback;
  226767. gradientCallbacks.releaseInfo = 0;
  226768. setFont (Font());
  226769. }
  226770. ~CoreGraphicsContext()
  226771. {
  226772. CGContextRestoreGState (context);
  226773. CGContextRelease (context);
  226774. CGColorSpaceRelease (rgbColourSpace);
  226775. CGColorSpaceRelease (greyColourSpace);
  226776. }
  226777. bool isVectorDevice() const { return false; }
  226778. void setOrigin (int x, int y)
  226779. {
  226780. CGContextTranslateCTM (context, x, -y);
  226781. }
  226782. bool clipToRectangle (const Rectangle<int>& r)
  226783. {
  226784. CGContextClipToRect (context, CGRectMake (r.getX(), flipHeight - r.getBottom(), r.getWidth(), r.getHeight()));
  226785. return ! isClipEmpty();
  226786. }
  226787. bool clipToRectangleList (const RectangleList& clipRegion)
  226788. {
  226789. if (clipRegion.isEmpty())
  226790. {
  226791. CGContextClipToRect (context, CGRectMake (0, 0, 0, 0));
  226792. return false;
  226793. }
  226794. else
  226795. {
  226796. const int numRects = clipRegion.getNumRectangles();
  226797. HeapBlock <CGRect> rects (numRects);
  226798. for (int i = 0; i < numRects; ++i)
  226799. {
  226800. const Rectangle<int>& r = clipRegion.getRectangle(i);
  226801. rects[i] = CGRectMake (r.getX(), flipHeight - r.getBottom(), r.getWidth(), r.getHeight());
  226802. }
  226803. CGContextClipToRects (context, rects, numRects);
  226804. return ! isClipEmpty();
  226805. }
  226806. }
  226807. void excludeClipRectangle (const Rectangle<int>& r)
  226808. {
  226809. RectangleList remaining (getClipBounds());
  226810. remaining.subtract (r);
  226811. clipToRectangleList (remaining);
  226812. }
  226813. void clipToPath (const Path& path, const AffineTransform& transform)
  226814. {
  226815. createPath (path, transform);
  226816. CGContextClip (context);
  226817. }
  226818. void clipToImageAlpha (const Image& sourceImage, const Rectangle<int>& srcClip, const AffineTransform& transform)
  226819. {
  226820. if (! transform.isSingularity())
  226821. {
  226822. ScopedPointer<Image> imageToDelete;
  226823. const Image* singleChannelImage = &sourceImage;
  226824. if (sourceImage.getFormat() != Image::SingleChannel)
  226825. {
  226826. imageToDelete = sourceImage.createCopyOfAlphaChannel();
  226827. singleChannelImage = imageToDelete;
  226828. }
  226829. CGImageRef image = CoreGraphicsImage::createImage (*singleChannelImage, true, greyColourSpace);
  226830. flip();
  226831. AffineTransform t (AffineTransform::scale (1.0f, -1.0f).translated (0, sourceImage.getHeight()).followedBy (transform));
  226832. applyTransform (t);
  226833. CGRect r = CGRectMake (srcClip.getX(), srcClip.getY(), srcClip.getWidth(), srcClip.getHeight());
  226834. CGContextClipToMask (context, r, image);
  226835. applyTransform (t.inverted());
  226836. flip();
  226837. CGImageRelease (image);
  226838. }
  226839. }
  226840. bool clipRegionIntersects (const Rectangle<int>& r)
  226841. {
  226842. return getClipBounds().intersects (r);
  226843. }
  226844. const Rectangle<int> getClipBounds() const
  226845. {
  226846. CGRect bounds = CGRectIntegral (CGContextGetClipBoundingBox (context));
  226847. return Rectangle<int> (roundToInt (bounds.origin.x),
  226848. roundToInt (flipHeight - (bounds.origin.y + bounds.size.height)),
  226849. roundToInt (bounds.size.width),
  226850. roundToInt (bounds.size.height));
  226851. }
  226852. bool isClipEmpty() const
  226853. {
  226854. return CGRectIsEmpty (CGContextGetClipBoundingBox (context));
  226855. }
  226856. void saveState()
  226857. {
  226858. CGContextSaveGState (context);
  226859. stateStack.add (new SavedState (*state));
  226860. }
  226861. void restoreState()
  226862. {
  226863. CGContextRestoreGState (context);
  226864. SavedState* const top = stateStack.getLast();
  226865. if (top != 0)
  226866. {
  226867. state = top;
  226868. stateStack.removeLast (1, false);
  226869. }
  226870. else
  226871. {
  226872. jassertfalse // trying to pop with an empty stack!
  226873. }
  226874. }
  226875. void setFill (const FillType& fillType)
  226876. {
  226877. state->fillType = fillType;
  226878. if (fillType.isColour())
  226879. {
  226880. CGContextSetRGBFillColor (context, fillType.colour.getFloatRed(), fillType.colour.getFloatGreen(),
  226881. fillType.colour.getFloatBlue(), fillType.colour.getFloatAlpha());
  226882. CGContextSetAlpha (context, 1.0f);
  226883. }
  226884. }
  226885. void setOpacity (float newOpacity)
  226886. {
  226887. state->fillType.setOpacity (newOpacity);
  226888. setFill (state->fillType);
  226889. }
  226890. void setInterpolationQuality (Graphics::ResamplingQuality quality)
  226891. {
  226892. CGContextSetInterpolationQuality (context, quality == Graphics::lowResamplingQuality
  226893. ? kCGInterpolationLow
  226894. : kCGInterpolationHigh);
  226895. }
  226896. void fillRect (const Rectangle<int>& r, const bool replaceExistingContents)
  226897. {
  226898. CGRect cgRect = CGRectMake (r.getX(), flipHeight - r.getBottom(), r.getWidth(), r.getHeight());
  226899. if (replaceExistingContents)
  226900. {
  226901. #if MAC_OS_X_VERSION_MAX_ALLOWED < MAC_OS_X_VERSION_10_5
  226902. CGContextClearRect (context, cgRect);
  226903. #else
  226904. #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
  226905. if (CGContextDrawLinearGradient == 0) // (just a way of checking whether we're running in 10.5 or later)
  226906. CGContextClearRect (context, cgRect);
  226907. else
  226908. #endif
  226909. CGContextSetBlendMode (context, kCGBlendModeCopy);
  226910. #endif
  226911. fillRect (r, false);
  226912. CGContextSetBlendMode (context, kCGBlendModeNormal);
  226913. }
  226914. else
  226915. {
  226916. if (state->fillType.isColour())
  226917. {
  226918. CGContextFillRect (context, cgRect);
  226919. }
  226920. else if (state->fillType.isGradient())
  226921. {
  226922. CGContextSaveGState (context);
  226923. CGContextClipToRect (context, cgRect);
  226924. drawGradient();
  226925. CGContextRestoreGState (context);
  226926. }
  226927. else
  226928. {
  226929. CGContextSaveGState (context);
  226930. CGContextClipToRect (context, cgRect);
  226931. drawImage (*(state->fillType.image), state->fillType.image->getBounds(), state->fillType.transform, true);
  226932. CGContextRestoreGState (context);
  226933. }
  226934. }
  226935. }
  226936. void fillPath (const Path& path, const AffineTransform& transform)
  226937. {
  226938. CGContextSaveGState (context);
  226939. if (state->fillType.isColour())
  226940. {
  226941. flip();
  226942. applyTransform (transform);
  226943. createPath (path);
  226944. if (path.isUsingNonZeroWinding())
  226945. CGContextFillPath (context);
  226946. else
  226947. CGContextEOFillPath (context);
  226948. }
  226949. else
  226950. {
  226951. createPath (path, transform);
  226952. if (path.isUsingNonZeroWinding())
  226953. CGContextClip (context);
  226954. else
  226955. CGContextEOClip (context);
  226956. if (state->fillType.isGradient())
  226957. drawGradient();
  226958. else
  226959. drawImage (*(state->fillType.image), state->fillType.image->getBounds(), state->fillType.transform, true);
  226960. }
  226961. CGContextRestoreGState (context);
  226962. }
  226963. void drawImage (const Image& sourceImage, const Rectangle<int>& srcClip,
  226964. const AffineTransform& transform, const bool fillEntireClipAsTiles)
  226965. {
  226966. jassert (sourceImage.getBounds().contains (srcClip));
  226967. CGImageRef fullImage = CoreGraphicsImage::createImage (sourceImage, false, rgbColourSpace);
  226968. CGImageRef image = fullImage;
  226969. if (srcClip != sourceImage.getBounds())
  226970. {
  226971. image = CGImageCreateWithImageInRect (fullImage, CGRectMake (srcClip.getX(), srcClip.getY(),
  226972. srcClip.getWidth(), srcClip.getHeight()));
  226973. CGImageRelease (fullImage);
  226974. }
  226975. CGContextSaveGState (context);
  226976. CGContextSetAlpha (context, state->fillType.getOpacity());
  226977. flip();
  226978. applyTransform (AffineTransform::scale (1.0f, -1.0f).translated (0, srcClip.getHeight()).followedBy (transform));
  226979. CGRect imageRect = CGRectMake (0, 0, srcClip.getWidth(), srcClip.getHeight());
  226980. if (fillEntireClipAsTiles)
  226981. {
  226982. #if JUCE_IPHONE
  226983. CGContextDrawTiledImage (context, imageRect, image);
  226984. #else
  226985. #if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_5
  226986. // There's a bug in CGContextDrawTiledImage that makes it incredibly slow
  226987. // if it's doing a transformation - it's quicker to just draw lots of images manually
  226988. if (CGContextDrawTiledImage != 0 && transform.isOnlyTranslation())
  226989. CGContextDrawTiledImage (context, imageRect, image);
  226990. else
  226991. #endif
  226992. {
  226993. // Fallback to manually doing a tiled fill on 10.4
  226994. CGRect clip = CGRectIntegral (CGContextGetClipBoundingBox (context));
  226995. const int iw = srcClip.getWidth();
  226996. const int ih = srcClip.getHeight();
  226997. int x = 0, y = 0;
  226998. while (x > clip.origin.x) x -= iw;
  226999. while (y > clip.origin.y) y -= ih;
  227000. const int right = (int) (clip.origin.x + clip.size.width);
  227001. const int bottom = (int) (clip.origin.y + clip.size.height);
  227002. while (y < bottom)
  227003. {
  227004. for (int x2 = x; x2 < right; x2 += iw)
  227005. CGContextDrawImage (context, CGRectMake (x2, y, iw, ih), image);
  227006. y += ih;
  227007. }
  227008. }
  227009. #endif
  227010. }
  227011. else
  227012. {
  227013. CGContextDrawImage (context, imageRect, image);
  227014. }
  227015. CGImageRelease (image); // (This causes a memory bug in iPhone sim 3.0 - try upgrading to a later version if you hit this)
  227016. CGContextRestoreGState (context);
  227017. }
  227018. void drawLine (double x1, double y1, double x2, double y2)
  227019. {
  227020. CGContextSetLineCap (context, kCGLineCapSquare);
  227021. CGContextSetLineWidth (context, 1.0f);
  227022. CGContextSetRGBStrokeColor (context,
  227023. state->fillType.colour.getFloatRed(), state->fillType.colour.getFloatGreen(),
  227024. state->fillType.colour.getFloatBlue(), state->fillType.colour.getFloatAlpha());
  227025. CGPoint line[] = { { (CGFloat) x1, flipHeight - (CGFloat) y1 },
  227026. { (CGFloat) x2, flipHeight - (CGFloat) y2 } };
  227027. CGContextStrokeLineSegments (context, line, 1);
  227028. }
  227029. void drawVerticalLine (const int x, double top, double bottom)
  227030. {
  227031. #if MAC_OS_X_VERSION_MIN_REQUIRED > MAC_OS_X_VERSION_10_5
  227032. CGContextFillRect (context, CGRectMake (x, flipHeight - (float) bottom, 1.0f, (float) (bottom - top)));
  227033. #else
  227034. // On Leopard, unless both co-ordinates are non-integer, it disables anti-aliasing, so nudge
  227035. // the x co-ord slightly to trick it..
  227036. CGContextFillRect (context, CGRectMake (x + 1.0f / 256.0f, flipHeight - (float) bottom, 1.0f + 1.0f / 256.0f, (float) (bottom - top)));
  227037. #endif
  227038. }
  227039. void drawHorizontalLine (const int y, double left, double right)
  227040. {
  227041. #if MAC_OS_X_VERSION_MIN_REQUIRED > MAC_OS_X_VERSION_10_5
  227042. CGContextFillRect (context, CGRectMake ((float) left, flipHeight - (y + 1.0f), (float) (right - left), 1.0f));
  227043. #else
  227044. // On Leopard, unless both co-ordinates are non-integer, it disables anti-aliasing, so nudge
  227045. // the x co-ord slightly to trick it..
  227046. CGContextFillRect (context, CGRectMake ((float) left, flipHeight - (y + (1.0f + 1.0f / 256.0f)), (float) (right - left), 1.0f + 1.0f / 256.0f));
  227047. #endif
  227048. }
  227049. void setFont (const Font& newFont)
  227050. {
  227051. if (state->font != newFont)
  227052. {
  227053. state->fontRef = 0;
  227054. state->font = newFont;
  227055. MacTypeface* mf = dynamic_cast <MacTypeface*> (state->font.getTypeface());
  227056. if (mf != 0)
  227057. {
  227058. state->fontRef = mf->fontRef;
  227059. CGContextSetFont (context, state->fontRef);
  227060. CGContextSetFontSize (context, state->font.getHeight() * mf->fontHeightToCGSizeFactor);
  227061. state->fontTransform = mf->renderingTransform;
  227062. state->fontTransform.a *= state->font.getHorizontalScale();
  227063. CGContextSetTextMatrix (context, state->fontTransform);
  227064. }
  227065. }
  227066. }
  227067. const Font getFont()
  227068. {
  227069. return state->font;
  227070. }
  227071. void drawGlyph (int glyphNumber, const AffineTransform& transform)
  227072. {
  227073. if (state->fontRef != 0 && state->fillType.isColour())
  227074. {
  227075. if (transform.isOnlyTranslation())
  227076. {
  227077. CGGlyph g = glyphNumber;
  227078. CGContextShowGlyphsAtPoint (context, transform.getTranslationX(),
  227079. flipHeight - roundToInt (transform.getTranslationY()), &g, 1);
  227080. }
  227081. else
  227082. {
  227083. CGContextSaveGState (context);
  227084. flip();
  227085. applyTransform (transform);
  227086. CGAffineTransform t = state->fontTransform;
  227087. t.d = -t.d;
  227088. CGContextSetTextMatrix (context, t);
  227089. CGGlyph g = glyphNumber;
  227090. CGContextShowGlyphsAtPoint (context, 0, 0, &g, 1);
  227091. CGContextSetTextMatrix (context, state->fontTransform);
  227092. CGContextRestoreGState (context);
  227093. }
  227094. }
  227095. else
  227096. {
  227097. Path p;
  227098. Font& f = state->font;
  227099. f.getTypeface()->getOutlineForGlyph (glyphNumber, p);
  227100. fillPath (p, AffineTransform::scale (f.getHeight() * f.getHorizontalScale(), f.getHeight())
  227101. .followedBy (transform));
  227102. }
  227103. }
  227104. private:
  227105. CGContextRef context;
  227106. const CGFloat flipHeight;
  227107. CGColorSpaceRef rgbColourSpace, greyColourSpace;
  227108. CGFunctionCallbacks gradientCallbacks;
  227109. struct SavedState
  227110. {
  227111. SavedState()
  227112. : font (1.0f), fontRef (0), fontTransform (CGAffineTransformIdentity)
  227113. {
  227114. }
  227115. SavedState (const SavedState& other)
  227116. : fillType (other.fillType), font (other.font), fontRef (other.fontRef),
  227117. fontTransform (other.fontTransform)
  227118. {
  227119. }
  227120. ~SavedState()
  227121. {
  227122. }
  227123. FillType fillType;
  227124. Font font;
  227125. CGFontRef fontRef;
  227126. CGAffineTransform fontTransform;
  227127. };
  227128. ScopedPointer <SavedState> state;
  227129. OwnedArray <SavedState> stateStack;
  227130. HeapBlock <PixelARGB> gradientLookupTable;
  227131. int numGradientLookupEntries;
  227132. static void gradientCallback (void* info, const CGFloat* inData, CGFloat* outData)
  227133. {
  227134. const CoreGraphicsContext* const g = static_cast <const CoreGraphicsContext*> (info);
  227135. const int index = roundToInt (g->numGradientLookupEntries * inData[0]);
  227136. PixelARGB colour (g->gradientLookupTable [jlimit (0, g->numGradientLookupEntries, index)]);
  227137. colour.unpremultiply();
  227138. outData[0] = colour.getRed() / 255.0f;
  227139. outData[1] = colour.getGreen() / 255.0f;
  227140. outData[2] = colour.getBlue() / 255.0f;
  227141. outData[3] = colour.getAlpha() / 255.0f;
  227142. }
  227143. CGShadingRef createGradient (const AffineTransform& transform, ColourGradient gradient)
  227144. {
  227145. numGradientLookupEntries = gradient.createLookupTable (transform, gradientLookupTable);
  227146. --numGradientLookupEntries;
  227147. CGShadingRef result = 0;
  227148. CGFunctionRef function = CGFunctionCreate (this, 1, 0, 4, 0, &gradientCallbacks);
  227149. CGPoint p1 (CGPointMake (gradient.x1, gradient.y1));
  227150. if (gradient.isRadial)
  227151. {
  227152. result = CGShadingCreateRadial (rgbColourSpace, p1, 0,
  227153. p1, hypotf (gradient.x1 - gradient.x2, gradient.y1 - gradient.y2),
  227154. function, true, true);
  227155. }
  227156. else
  227157. {
  227158. result = CGShadingCreateAxial (rgbColourSpace, p1,
  227159. CGPointMake (gradient.x2, gradient.y2),
  227160. function, true, true);
  227161. }
  227162. CGFunctionRelease (function);
  227163. return result;
  227164. }
  227165. void drawGradient()
  227166. {
  227167. flip();
  227168. applyTransform (state->fillType.transform);
  227169. CGContextSetInterpolationQuality (context, kCGInterpolationDefault); // (This is required for 10.4, where there's a crash if
  227170. // you draw a gradient with high quality interp enabled).
  227171. CGShadingRef shading = createGradient (state->fillType.transform, *(state->fillType.gradient));
  227172. CGContextSetAlpha (context, state->fillType.getOpacity());
  227173. CGContextDrawShading (context, shading);
  227174. CGShadingRelease (shading);
  227175. }
  227176. void createPath (const Path& path) const
  227177. {
  227178. CGContextBeginPath (context);
  227179. Path::Iterator i (path);
  227180. while (i.next())
  227181. {
  227182. switch (i.elementType)
  227183. {
  227184. case Path::Iterator::startNewSubPath:
  227185. CGContextMoveToPoint (context, i.x1, i.y1);
  227186. break;
  227187. case Path::Iterator::lineTo:
  227188. CGContextAddLineToPoint (context, i.x1, i.y1);
  227189. break;
  227190. case Path::Iterator::quadraticTo:
  227191. CGContextAddQuadCurveToPoint (context, i.x1, i.y1, i.x2, i.y2);
  227192. break;
  227193. case Path::Iterator::cubicTo:
  227194. CGContextAddCurveToPoint (context, i.x1, i.y1, i.x2, i.y2, i.x3, i.y3);
  227195. break;
  227196. case Path::Iterator::closePath:
  227197. CGContextClosePath (context); break;
  227198. default:
  227199. jassertfalse
  227200. break;
  227201. }
  227202. }
  227203. }
  227204. void createPath (const Path& path, const AffineTransform& transform) const
  227205. {
  227206. CGContextBeginPath (context);
  227207. Path::Iterator i (path);
  227208. while (i.next())
  227209. {
  227210. switch (i.elementType)
  227211. {
  227212. case Path::Iterator::startNewSubPath:
  227213. transform.transformPoint (i.x1, i.y1);
  227214. CGContextMoveToPoint (context, i.x1, flipHeight - i.y1);
  227215. break;
  227216. case Path::Iterator::lineTo:
  227217. transform.transformPoint (i.x1, i.y1);
  227218. CGContextAddLineToPoint (context, i.x1, flipHeight - i.y1);
  227219. break;
  227220. case Path::Iterator::quadraticTo:
  227221. transform.transformPoint (i.x1, i.y1);
  227222. transform.transformPoint (i.x2, i.y2);
  227223. CGContextAddQuadCurveToPoint (context, i.x1, flipHeight - i.y1, i.x2, flipHeight - i.y2);
  227224. break;
  227225. case Path::Iterator::cubicTo:
  227226. transform.transformPoint (i.x1, i.y1);
  227227. transform.transformPoint (i.x2, i.y2);
  227228. transform.transformPoint (i.x3, i.y3);
  227229. CGContextAddCurveToPoint (context, i.x1, flipHeight - i.y1, i.x2, flipHeight - i.y2, i.x3, flipHeight - i.y3);
  227230. break;
  227231. case Path::Iterator::closePath:
  227232. CGContextClosePath (context); break;
  227233. default:
  227234. jassertfalse
  227235. break;
  227236. }
  227237. }
  227238. }
  227239. void flip() const
  227240. {
  227241. CGContextConcatCTM (context, CGAffineTransformMake (1, 0, 0, -1, 0, flipHeight));
  227242. }
  227243. void applyTransform (const AffineTransform& transform) const
  227244. {
  227245. CGAffineTransform t;
  227246. t.a = transform.mat00;
  227247. t.b = transform.mat10;
  227248. t.c = transform.mat01;
  227249. t.d = transform.mat11;
  227250. t.tx = transform.mat02;
  227251. t.ty = transform.mat12;
  227252. CGContextConcatCTM (context, t);
  227253. }
  227254. CoreGraphicsContext (const CoreGraphicsContext&);
  227255. CoreGraphicsContext& operator= (const CoreGraphicsContext&);
  227256. };
  227257. LowLevelGraphicsContext* CoreGraphicsImage::createLowLevelContext()
  227258. {
  227259. return new CoreGraphicsContext (context, imageHeight);
  227260. }
  227261. #endif
  227262. /*** End of inlined file: juce_mac_CoreGraphicsContext.mm ***/
  227263. /*** Start of inlined file: juce_mac_NSViewComponentPeer.mm ***/
  227264. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  227265. // compiled on its own).
  227266. #if JUCE_INCLUDED_FILE
  227267. class NSViewComponentPeer;
  227268. END_JUCE_NAMESPACE
  227269. #define JuceNSView MakeObjCClassName(JuceNSView)
  227270. @interface JuceNSView : NSView<NSTextInput>
  227271. {
  227272. @public
  227273. NSViewComponentPeer* owner;
  227274. NSNotificationCenter* notificationCenter;
  227275. String* stringBeingComposed;
  227276. bool textWasInserted;
  227277. }
  227278. - (JuceNSView*) initWithOwner: (NSViewComponentPeer*) owner withFrame: (NSRect) frame;
  227279. - (void) dealloc;
  227280. - (BOOL) isOpaque;
  227281. - (void) drawRect: (NSRect) r;
  227282. - (void) mouseDown: (NSEvent*) ev;
  227283. - (void) asyncMouseDown: (NSEvent*) ev;
  227284. - (void) mouseUp: (NSEvent*) ev;
  227285. - (void) asyncMouseUp: (NSEvent*) ev;
  227286. - (void) mouseDragged: (NSEvent*) ev;
  227287. - (void) mouseMoved: (NSEvent*) ev;
  227288. - (void) mouseEntered: (NSEvent*) ev;
  227289. - (void) mouseExited: (NSEvent*) ev;
  227290. - (void) rightMouseDown: (NSEvent*) ev;
  227291. - (void) rightMouseDragged: (NSEvent*) ev;
  227292. - (void) rightMouseUp: (NSEvent*) ev;
  227293. - (void) otherMouseDown: (NSEvent*) ev;
  227294. - (void) otherMouseDragged: (NSEvent*) ev;
  227295. - (void) otherMouseUp: (NSEvent*) ev;
  227296. - (void) scrollWheel: (NSEvent*) ev;
  227297. - (BOOL) acceptsFirstMouse: (NSEvent*) ev;
  227298. - (void) frameChanged: (NSNotification*) n;
  227299. - (void) viewDidMoveToWindow;
  227300. - (void) keyDown: (NSEvent*) ev;
  227301. - (void) keyUp: (NSEvent*) ev;
  227302. // NSTextInput Methods
  227303. - (void) insertText: (id) aString;
  227304. - (void) doCommandBySelector: (SEL) aSelector;
  227305. - (void) setMarkedText: (id) aString selectedRange: (NSRange) selRange;
  227306. - (void) unmarkText;
  227307. - (BOOL) hasMarkedText;
  227308. - (long) conversationIdentifier;
  227309. - (NSAttributedString*) attributedSubstringFromRange: (NSRange) theRange;
  227310. - (NSRange) markedRange;
  227311. - (NSRange) selectedRange;
  227312. - (NSRect) firstRectForCharacterRange: (NSRange) theRange;
  227313. - (unsigned int) characterIndexForPoint: (NSPoint) thePoint;
  227314. - (NSArray*) validAttributesForMarkedText;
  227315. - (void) flagsChanged: (NSEvent*) ev;
  227316. #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
  227317. - (BOOL) performKeyEquivalent: (NSEvent*) ev;
  227318. #endif
  227319. - (BOOL) becomeFirstResponder;
  227320. - (BOOL) resignFirstResponder;
  227321. - (BOOL) acceptsFirstResponder;
  227322. - (void) asyncRepaint: (id) rect;
  227323. - (NSArray*) getSupportedDragTypes;
  227324. - (BOOL) sendDragCallback: (int) type sender: (id <NSDraggingInfo>) sender;
  227325. - (NSDragOperation) draggingEntered: (id <NSDraggingInfo>) sender;
  227326. - (NSDragOperation) draggingUpdated: (id <NSDraggingInfo>) sender;
  227327. - (void) draggingEnded: (id <NSDraggingInfo>) sender;
  227328. - (void) draggingExited: (id <NSDraggingInfo>) sender;
  227329. - (BOOL) prepareForDragOperation: (id <NSDraggingInfo>) sender;
  227330. - (BOOL) performDragOperation: (id <NSDraggingInfo>) sender;
  227331. - (void) concludeDragOperation: (id <NSDraggingInfo>) sender;
  227332. @end
  227333. #define JuceNSWindow MakeObjCClassName(JuceNSWindow)
  227334. #if defined (MAC_OS_X_VERSION_10_6) && MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_6
  227335. @interface JuceNSWindow : NSWindow <NSWindowDelegate>
  227336. #else
  227337. @interface JuceNSWindow : NSWindow
  227338. #endif
  227339. {
  227340. @private
  227341. NSViewComponentPeer* owner;
  227342. bool isZooming;
  227343. }
  227344. - (void) setOwner: (NSViewComponentPeer*) owner;
  227345. - (BOOL) canBecomeKeyWindow;
  227346. - (void) becomeKeyWindow;
  227347. - (BOOL) windowShouldClose: (id) window;
  227348. - (NSRect) constrainFrameRect: (NSRect) frameRect toScreen: (NSScreen*) screen;
  227349. - (NSSize) windowWillResize: (NSWindow*) window toSize: (NSSize) proposedFrameSize;
  227350. - (void) zoom: (id) sender;
  227351. @end
  227352. BEGIN_JUCE_NAMESPACE
  227353. class NSViewComponentPeer : public ComponentPeer
  227354. {
  227355. public:
  227356. NSViewComponentPeer (Component* const component,
  227357. const int windowStyleFlags,
  227358. NSView* viewToAttachTo);
  227359. ~NSViewComponentPeer();
  227360. void* getNativeHandle() const;
  227361. void setVisible (bool shouldBeVisible);
  227362. void setTitle (const String& title);
  227363. void setPosition (int x, int y);
  227364. void setSize (int w, int h);
  227365. void setBounds (int x, int y, int w, int h, const bool isNowFullScreen);
  227366. const Rectangle<int> getBounds (const bool global) const;
  227367. const Rectangle<int> getBounds() const;
  227368. const Point<int> getScreenPosition() const;
  227369. const Point<int> relativePositionToGlobal (const Point<int>& relativePosition);
  227370. const Point<int> globalPositionToRelative (const Point<int>& screenPosition);
  227371. void setMinimised (bool shouldBeMinimised);
  227372. bool isMinimised() const;
  227373. void setFullScreen (bool shouldBeFullScreen);
  227374. bool isFullScreen() const;
  227375. bool contains (const Point<int>& position, bool trueIfInAChildWindow) const;
  227376. const BorderSize getFrameSize() const;
  227377. bool setAlwaysOnTop (bool alwaysOnTop);
  227378. void toFront (bool makeActiveWindow);
  227379. void toBehind (ComponentPeer* other);
  227380. void setIcon (const Image& newIcon);
  227381. const StringArray getAvailableRenderingEngines() throw();
  227382. int getCurrentRenderingEngine() throw();
  227383. void setCurrentRenderingEngine (int index) throw();
  227384. /* When you use multiple DLLs which share similarly-named obj-c classes - like
  227385. for example having more than one juce plugin loaded into a host, then when a
  227386. method is called, the actual code that runs might actually be in a different module
  227387. than the one you expect... So any calls to library functions or statics that are
  227388. made inside obj-c methods will probably end up getting executed in a different DLL's
  227389. memory space. Not a great thing to happen - this obviously leads to bizarre crashes.
  227390. To work around this insanity, I'm only allowing obj-c methods to make calls to
  227391. virtual methods of an object that's known to live inside the right module's space.
  227392. */
  227393. virtual void redirectMouseDown (NSEvent* ev);
  227394. virtual void redirectMouseUp (NSEvent* ev);
  227395. virtual void redirectMouseDrag (NSEvent* ev);
  227396. virtual void redirectMouseMove (NSEvent* ev);
  227397. virtual void redirectMouseEnter (NSEvent* ev);
  227398. virtual void redirectMouseExit (NSEvent* ev);
  227399. virtual void redirectMouseWheel (NSEvent* ev);
  227400. void sendMouseEvent (NSEvent* ev);
  227401. bool handleKeyEvent (NSEvent* ev, bool isKeyDown);
  227402. virtual bool redirectKeyDown (NSEvent* ev);
  227403. virtual bool redirectKeyUp (NSEvent* ev);
  227404. virtual void redirectModKeyChange (NSEvent* ev);
  227405. #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
  227406. virtual bool redirectPerformKeyEquivalent (NSEvent* ev);
  227407. #endif
  227408. virtual BOOL sendDragCallback (int type, id <NSDraggingInfo> sender);
  227409. virtual bool isOpaque();
  227410. virtual void drawRect (NSRect r);
  227411. virtual bool canBecomeKeyWindow();
  227412. virtual bool windowShouldClose();
  227413. virtual void redirectMovedOrResized();
  227414. virtual void viewMovedToWindow();
  227415. virtual NSRect constrainRect (NSRect r);
  227416. static void showArrowCursorIfNeeded();
  227417. static void updateModifiers (NSEvent* e);
  227418. static void updateKeysDown (NSEvent* ev, bool isKeyDown);
  227419. static int getKeyCodeFromEvent (NSEvent* ev)
  227420. {
  227421. const String unmodified (nsStringToJuce ([ev charactersIgnoringModifiers]));
  227422. int keyCode = unmodified[0];
  227423. if (keyCode == 0x19) // (backwards-tab)
  227424. keyCode = '\t';
  227425. else if (keyCode == 0x03) // (enter)
  227426. keyCode = '\r';
  227427. return keyCode;
  227428. }
  227429. static int64 getMouseTime (NSEvent* e)
  227430. {
  227431. return (Time::currentTimeMillis() - Time::getMillisecondCounter())
  227432. + (int64) ([e timestamp] * 1000.0);
  227433. }
  227434. static const Point<int> getMousePos (NSEvent* e, NSView* view)
  227435. {
  227436. NSPoint p = [view convertPoint: [e locationInWindow] fromView: nil];
  227437. return Point<int> (roundToInt (p.x), roundToInt ([view frame].size.height - p.y));
  227438. }
  227439. static int getModifierForButtonNumber (const NSInteger num)
  227440. {
  227441. return num == 0 ? ModifierKeys::leftButtonModifier
  227442. : (num == 1 ? ModifierKeys::rightButtonModifier
  227443. : (num == 2 ? ModifierKeys::middleButtonModifier : 0));
  227444. }
  227445. virtual void viewFocusGain();
  227446. virtual void viewFocusLoss();
  227447. bool isFocused() const;
  227448. void grabFocus();
  227449. void textInputRequired (const Point<int>& position);
  227450. void repaint (int x, int y, int w, int h);
  227451. void performAnyPendingRepaintsNow();
  227452. juce_UseDebuggingNewOperator
  227453. NSWindow* window;
  227454. JuceNSView* view;
  227455. bool isSharedWindow, fullScreen, insideDrawRect, usingCoreGraphics, recursiveToFrontCall;
  227456. static ModifierKeys currentModifiers;
  227457. static ComponentPeer* currentlyFocusedPeer;
  227458. static Array<int> keysCurrentlyDown;
  227459. };
  227460. END_JUCE_NAMESPACE
  227461. @implementation JuceNSView
  227462. - (JuceNSView*) initWithOwner: (NSViewComponentPeer*) owner_
  227463. withFrame: (NSRect) frame
  227464. {
  227465. [super initWithFrame: frame];
  227466. owner = owner_;
  227467. stringBeingComposed = 0;
  227468. textWasInserted = false;
  227469. notificationCenter = [NSNotificationCenter defaultCenter];
  227470. [notificationCenter addObserver: self
  227471. selector: @selector (frameChanged:)
  227472. name: NSViewFrameDidChangeNotification
  227473. object: self];
  227474. if (! owner_->isSharedWindow)
  227475. {
  227476. [notificationCenter addObserver: self
  227477. selector: @selector (frameChanged:)
  227478. name: NSWindowDidMoveNotification
  227479. object: owner_->window];
  227480. }
  227481. [self registerForDraggedTypes: [self getSupportedDragTypes]];
  227482. return self;
  227483. }
  227484. - (void) dealloc
  227485. {
  227486. [notificationCenter removeObserver: self];
  227487. delete stringBeingComposed;
  227488. [super dealloc];
  227489. }
  227490. - (void) drawRect: (NSRect) r
  227491. {
  227492. if (owner != 0)
  227493. owner->drawRect (r);
  227494. }
  227495. - (BOOL) isOpaque
  227496. {
  227497. return owner == 0 || owner->isOpaque();
  227498. }
  227499. - (void) mouseDown: (NSEvent*) ev
  227500. {
  227501. // In some host situations, the host will stop modal loops from working
  227502. // correctly if they're called from a mouse event, so we'll trigger
  227503. // the event asynchronously..
  227504. if (JUCEApplication::getInstance() == 0)
  227505. [self performSelectorOnMainThread: @selector (asyncMouseDown:)
  227506. withObject: ev
  227507. waitUntilDone: NO];
  227508. else
  227509. [self asyncMouseDown: ev];
  227510. }
  227511. - (void) asyncMouseDown: (NSEvent*) ev
  227512. {
  227513. if (owner != 0)
  227514. owner->redirectMouseDown (ev);
  227515. }
  227516. - (void) mouseUp: (NSEvent*) ev
  227517. {
  227518. // In some host situations, the host will stop modal loops from working
  227519. // correctly if they're called from a mouse event, so we'll trigger
  227520. // the event asynchronously..
  227521. if (JUCEApplication::getInstance() == 0)
  227522. [self performSelectorOnMainThread: @selector (asyncMouseUp:)
  227523. withObject: ev
  227524. waitUntilDone: NO];
  227525. else
  227526. [self asyncMouseUp: ev];
  227527. }
  227528. - (void) asyncMouseUp: (NSEvent*) ev
  227529. {
  227530. if (owner != 0)
  227531. owner->redirectMouseUp (ev);
  227532. }
  227533. - (void) mouseDragged: (NSEvent*) ev
  227534. {
  227535. if (owner != 0)
  227536. owner->redirectMouseDrag (ev);
  227537. }
  227538. - (void) mouseMoved: (NSEvent*) ev
  227539. {
  227540. if (owner != 0)
  227541. owner->redirectMouseMove (ev);
  227542. }
  227543. - (void) mouseEntered: (NSEvent*) ev
  227544. {
  227545. if (owner != 0)
  227546. owner->redirectMouseEnter (ev);
  227547. }
  227548. - (void) mouseExited: (NSEvent*) ev
  227549. {
  227550. if (owner != 0)
  227551. owner->redirectMouseExit (ev);
  227552. }
  227553. - (void) rightMouseDown: (NSEvent*) ev
  227554. {
  227555. [self mouseDown: ev];
  227556. }
  227557. - (void) rightMouseDragged: (NSEvent*) ev
  227558. {
  227559. [self mouseDragged: ev];
  227560. }
  227561. - (void) rightMouseUp: (NSEvent*) ev
  227562. {
  227563. [self mouseUp: ev];
  227564. }
  227565. - (void) otherMouseDown: (NSEvent*) ev
  227566. {
  227567. [self mouseDown: ev];
  227568. }
  227569. - (void) otherMouseDragged: (NSEvent*) ev
  227570. {
  227571. [self mouseDragged: ev];
  227572. }
  227573. - (void) otherMouseUp: (NSEvent*) ev
  227574. {
  227575. [self mouseUp: ev];
  227576. }
  227577. - (void) scrollWheel: (NSEvent*) ev
  227578. {
  227579. if (owner != 0)
  227580. owner->redirectMouseWheel (ev);
  227581. }
  227582. - (BOOL) acceptsFirstMouse: (NSEvent*) ev
  227583. {
  227584. (void) ev;
  227585. return YES;
  227586. }
  227587. - (void) frameChanged: (NSNotification*) n
  227588. {
  227589. (void) n;
  227590. if (owner != 0)
  227591. owner->redirectMovedOrResized();
  227592. }
  227593. - (void) viewDidMoveToWindow
  227594. {
  227595. if (owner != 0)
  227596. owner->viewMovedToWindow();
  227597. }
  227598. - (void) asyncRepaint: (id) rect
  227599. {
  227600. NSRect* r = (NSRect*) [((NSData*) rect) bytes];
  227601. [self setNeedsDisplayInRect: *r];
  227602. }
  227603. - (void) keyDown: (NSEvent*) ev
  227604. {
  227605. TextInputTarget* const target = owner->findCurrentTextInputTarget();
  227606. textWasInserted = false;
  227607. if (target != 0)
  227608. [self interpretKeyEvents: [NSArray arrayWithObject: ev]];
  227609. else
  227610. deleteAndZero (stringBeingComposed);
  227611. if ((! textWasInserted) && (owner == 0 || ! owner->redirectKeyDown (ev)))
  227612. [super keyDown: ev];
  227613. }
  227614. - (void) keyUp: (NSEvent*) ev
  227615. {
  227616. if (owner == 0 || ! owner->redirectKeyUp (ev))
  227617. [super keyUp: ev];
  227618. }
  227619. - (void) insertText: (id) aString
  227620. {
  227621. // This commits multi-byte text when return is pressed, or after every keypress for western keyboards
  227622. if ([aString length] > 0)
  227623. {
  227624. TextInputTarget* const target = owner->findCurrentTextInputTarget();
  227625. if (target != 0)
  227626. {
  227627. target->insertTextAtCaret (nsStringToJuce ([aString isKindOfClass: [NSAttributedString class]] ? [aString string] : aString));
  227628. textWasInserted = true;
  227629. }
  227630. }
  227631. deleteAndZero (stringBeingComposed);
  227632. }
  227633. - (void) doCommandBySelector: (SEL) aSelector
  227634. {
  227635. (void) aSelector;
  227636. }
  227637. - (void) setMarkedText: (id) aString selectedRange: (NSRange) selectionRange
  227638. {
  227639. (void) selectionRange;
  227640. if (stringBeingComposed == 0)
  227641. stringBeingComposed = new String();
  227642. *stringBeingComposed = nsStringToJuce ([aString isKindOfClass:[NSAttributedString class]] ? [aString string] : aString);
  227643. TextInputTarget* const target = owner->findCurrentTextInputTarget();
  227644. if (target != 0)
  227645. {
  227646. const Range<int> currentHighlight (target->getHighlightedRegion());
  227647. target->insertTextAtCaret (*stringBeingComposed);
  227648. target->setHighlightedRegion (currentHighlight.withLength (stringBeingComposed->length()));
  227649. textWasInserted = true;
  227650. }
  227651. }
  227652. - (void) unmarkText
  227653. {
  227654. if (stringBeingComposed != 0)
  227655. {
  227656. TextInputTarget* const target = owner->findCurrentTextInputTarget();
  227657. if (target != 0)
  227658. {
  227659. target->insertTextAtCaret (*stringBeingComposed);
  227660. textWasInserted = true;
  227661. }
  227662. }
  227663. deleteAndZero (stringBeingComposed);
  227664. }
  227665. - (BOOL) hasMarkedText
  227666. {
  227667. return stringBeingComposed != 0;
  227668. }
  227669. - (long) conversationIdentifier
  227670. {
  227671. return (long) (pointer_sized_int) self;
  227672. }
  227673. - (NSAttributedString*) attributedSubstringFromRange: (NSRange) theRange
  227674. {
  227675. TextInputTarget* const target = owner->findCurrentTextInputTarget();
  227676. if (target != 0)
  227677. {
  227678. const Range<int> r ((int) theRange.location,
  227679. (int) (theRange.location + theRange.length));
  227680. return [[[NSAttributedString alloc] initWithString: juceStringToNS (target->getTextInRange (r))] autorelease];
  227681. }
  227682. return nil;
  227683. }
  227684. - (NSRange) markedRange
  227685. {
  227686. return stringBeingComposed != 0 ? NSMakeRange (0, stringBeingComposed->length())
  227687. : NSMakeRange (NSNotFound, 0);
  227688. }
  227689. - (NSRange) selectedRange
  227690. {
  227691. TextInputTarget* const target = owner->findCurrentTextInputTarget();
  227692. if (target != 0)
  227693. {
  227694. const Range<int> highlight (target->getHighlightedRegion());
  227695. if (! highlight.isEmpty())
  227696. return NSMakeRange (highlight.getStart(), highlight.getLength());
  227697. }
  227698. return NSMakeRange (NSNotFound, 0);
  227699. }
  227700. - (NSRect) firstRectForCharacterRange: (NSRange) theRange
  227701. {
  227702. (void) theRange;
  227703. JUCE_NAMESPACE::Component* const comp = dynamic_cast <JUCE_NAMESPACE::Component*> (owner->findCurrentTextInputTarget());
  227704. if (comp == 0)
  227705. return NSMakeRect (0, 0, 0, 0);
  227706. const Rectangle<int> bounds (comp->getScreenBounds());
  227707. return NSMakeRect (bounds.getX(),
  227708. [[[NSScreen screens] objectAtIndex: 0] frame].size.height - bounds.getY(),
  227709. bounds.getWidth(),
  227710. bounds.getHeight());
  227711. }
  227712. - (unsigned int) characterIndexForPoint: (NSPoint) thePoint
  227713. {
  227714. (void) thePoint;
  227715. return NSNotFound;
  227716. }
  227717. - (NSArray*) validAttributesForMarkedText
  227718. {
  227719. return [NSArray array];
  227720. }
  227721. - (void) flagsChanged: (NSEvent*) ev
  227722. {
  227723. if (owner != 0)
  227724. owner->redirectModKeyChange (ev);
  227725. }
  227726. #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
  227727. - (BOOL) performKeyEquivalent: (NSEvent*) ev
  227728. {
  227729. if (owner != 0 && owner->redirectPerformKeyEquivalent (ev))
  227730. return true;
  227731. return [super performKeyEquivalent: ev];
  227732. }
  227733. #endif
  227734. - (BOOL) becomeFirstResponder
  227735. {
  227736. if (owner != 0)
  227737. owner->viewFocusGain();
  227738. return true;
  227739. }
  227740. - (BOOL) resignFirstResponder
  227741. {
  227742. if (owner != 0)
  227743. owner->viewFocusLoss();
  227744. return true;
  227745. }
  227746. - (BOOL) acceptsFirstResponder
  227747. {
  227748. return owner != 0 && owner->canBecomeKeyWindow();
  227749. }
  227750. - (NSArray*) getSupportedDragTypes
  227751. {
  227752. return [NSArray arrayWithObjects: NSFilenamesPboardType, /*NSFilesPromisePboardType, NSStringPboardType,*/ nil];
  227753. }
  227754. - (BOOL) sendDragCallback: (int) type sender: (id <NSDraggingInfo>) sender
  227755. {
  227756. return owner != 0 && owner->sendDragCallback (type, sender);
  227757. }
  227758. - (NSDragOperation) draggingEntered: (id <NSDraggingInfo>) sender
  227759. {
  227760. if ([self sendDragCallback: 0 sender: sender])
  227761. return NSDragOperationCopy | NSDragOperationMove | NSDragOperationGeneric;
  227762. else
  227763. return NSDragOperationNone;
  227764. }
  227765. - (NSDragOperation) draggingUpdated: (id <NSDraggingInfo>) sender
  227766. {
  227767. if ([self sendDragCallback: 0 sender: sender])
  227768. return NSDragOperationCopy | NSDragOperationMove | NSDragOperationGeneric;
  227769. else
  227770. return NSDragOperationNone;
  227771. }
  227772. - (void) draggingEnded: (id <NSDraggingInfo>) sender
  227773. {
  227774. [self sendDragCallback: 1 sender: sender];
  227775. }
  227776. - (void) draggingExited: (id <NSDraggingInfo>) sender
  227777. {
  227778. [self sendDragCallback: 1 sender: sender];
  227779. }
  227780. - (BOOL) prepareForDragOperation: (id <NSDraggingInfo>) sender
  227781. {
  227782. (void) sender;
  227783. return YES;
  227784. }
  227785. - (BOOL) performDragOperation: (id <NSDraggingInfo>) sender
  227786. {
  227787. return [self sendDragCallback: 2 sender: sender];
  227788. }
  227789. - (void) concludeDragOperation: (id <NSDraggingInfo>) sender
  227790. {
  227791. (void) sender;
  227792. }
  227793. @end
  227794. @implementation JuceNSWindow
  227795. - (void) setOwner: (NSViewComponentPeer*) owner_
  227796. {
  227797. owner = owner_;
  227798. isZooming = false;
  227799. }
  227800. - (BOOL) canBecomeKeyWindow
  227801. {
  227802. return owner != 0 && owner->canBecomeKeyWindow();
  227803. }
  227804. - (void) becomeKeyWindow
  227805. {
  227806. [super becomeKeyWindow];
  227807. if (owner != 0)
  227808. owner->grabFocus();
  227809. }
  227810. - (BOOL) windowShouldClose: (id) window
  227811. {
  227812. (void) window;
  227813. return owner == 0 || owner->windowShouldClose();
  227814. }
  227815. - (NSRect) constrainFrameRect: (NSRect) frameRect toScreen: (NSScreen*) screen
  227816. {
  227817. (void) screen;
  227818. if (owner != 0)
  227819. frameRect = owner->constrainRect (frameRect);
  227820. return frameRect;
  227821. }
  227822. - (NSSize) windowWillResize: (NSWindow*) window toSize: (NSSize) proposedFrameSize
  227823. {
  227824. (void) window;
  227825. if (isZooming)
  227826. return proposedFrameSize;
  227827. NSRect frameRect = [self frame];
  227828. frameRect.origin.y -= proposedFrameSize.height - frameRect.size.height;
  227829. frameRect.size = proposedFrameSize;
  227830. if (owner != 0)
  227831. frameRect = owner->constrainRect (frameRect);
  227832. return frameRect.size;
  227833. }
  227834. - (void) zoom: (id) sender
  227835. {
  227836. isZooming = true;
  227837. [super zoom: sender];
  227838. isZooming = false;
  227839. }
  227840. - (void) windowWillMove: (NSNotification*) notification
  227841. {
  227842. (void) notification;
  227843. if (JUCE_NAMESPACE::Component::getCurrentlyModalComponent() != 0
  227844. && owner->getComponent()->isCurrentlyBlockedByAnotherModalComponent()
  227845. && (owner->getStyleFlags() & JUCE_NAMESPACE::ComponentPeer::windowHasTitleBar) != 0)
  227846. JUCE_NAMESPACE::Component::getCurrentlyModalComponent()->inputAttemptWhenModal();
  227847. }
  227848. @end
  227849. BEGIN_JUCE_NAMESPACE
  227850. ModifierKeys NSViewComponentPeer::currentModifiers;
  227851. ComponentPeer* NSViewComponentPeer::currentlyFocusedPeer = 0;
  227852. Array<int> NSViewComponentPeer::keysCurrentlyDown;
  227853. bool KeyPress::isKeyCurrentlyDown (const int keyCode)
  227854. {
  227855. if (NSViewComponentPeer::keysCurrentlyDown.contains (keyCode))
  227856. return true;
  227857. if (keyCode >= 'A' && keyCode <= 'Z'
  227858. && NSViewComponentPeer::keysCurrentlyDown.contains ((int) CharacterFunctions::toLowerCase ((juce_wchar) keyCode)))
  227859. return true;
  227860. if (keyCode >= 'a' && keyCode <= 'z'
  227861. && NSViewComponentPeer::keysCurrentlyDown.contains ((int) CharacterFunctions::toUpperCase ((juce_wchar) keyCode)))
  227862. return true;
  227863. return false;
  227864. }
  227865. void NSViewComponentPeer::updateModifiers (NSEvent* e)
  227866. {
  227867. int m = 0;
  227868. if (([e modifierFlags] & NSShiftKeyMask) != 0) m |= ModifierKeys::shiftModifier;
  227869. if (([e modifierFlags] & NSControlKeyMask) != 0) m |= ModifierKeys::ctrlModifier;
  227870. if (([e modifierFlags] & NSAlternateKeyMask) != 0) m |= ModifierKeys::altModifier;
  227871. if (([e modifierFlags] & NSCommandKeyMask) != 0) m |= ModifierKeys::commandModifier;
  227872. currentModifiers = currentModifiers.withOnlyMouseButtons().withFlags (m);
  227873. }
  227874. void NSViewComponentPeer::updateKeysDown (NSEvent* ev, bool isKeyDown)
  227875. {
  227876. updateModifiers (ev);
  227877. int keyCode = getKeyCodeFromEvent (ev);
  227878. if (keyCode != 0)
  227879. {
  227880. if (isKeyDown)
  227881. keysCurrentlyDown.addIfNotAlreadyThere (keyCode);
  227882. else
  227883. keysCurrentlyDown.removeValue (keyCode);
  227884. }
  227885. }
  227886. const ModifierKeys ModifierKeys::getCurrentModifiersRealtime() throw()
  227887. {
  227888. return NSViewComponentPeer::currentModifiers;
  227889. }
  227890. void ModifierKeys::updateCurrentModifiers() throw()
  227891. {
  227892. currentModifiers = NSViewComponentPeer::currentModifiers;
  227893. }
  227894. NSViewComponentPeer::NSViewComponentPeer (Component* const component_,
  227895. const int windowStyleFlags,
  227896. NSView* viewToAttachTo)
  227897. : ComponentPeer (component_, windowStyleFlags),
  227898. window (0),
  227899. view (0),
  227900. isSharedWindow (viewToAttachTo != 0),
  227901. fullScreen (false),
  227902. insideDrawRect (false),
  227903. #if USE_COREGRAPHICS_RENDERING
  227904. usingCoreGraphics (true),
  227905. #else
  227906. usingCoreGraphics (false),
  227907. #endif
  227908. recursiveToFrontCall (false)
  227909. {
  227910. NSRect r;
  227911. r.origin.x = 0;
  227912. r.origin.y = 0;
  227913. r.size.width = (float) component->getWidth();
  227914. r.size.height = (float) component->getHeight();
  227915. view = [[JuceNSView alloc] initWithOwner: this withFrame: r];
  227916. [view setPostsFrameChangedNotifications: YES];
  227917. if (isSharedWindow)
  227918. {
  227919. window = [viewToAttachTo window];
  227920. [viewToAttachTo addSubview: view];
  227921. setVisible (component->isVisible());
  227922. }
  227923. else
  227924. {
  227925. r.origin.x = (float) component->getX();
  227926. r.origin.y = (float) component->getY();
  227927. r.origin.y = [[[NSScreen screens] objectAtIndex: 0] frame].size.height - (r.origin.y + r.size.height);
  227928. unsigned int style = 0;
  227929. if ((windowStyleFlags & windowHasTitleBar) == 0)
  227930. style = NSBorderlessWindowMask;
  227931. else
  227932. style = NSTitledWindowMask;
  227933. if ((windowStyleFlags & windowHasMinimiseButton) != 0)
  227934. style |= NSMiniaturizableWindowMask;
  227935. if ((windowStyleFlags & windowHasCloseButton) != 0)
  227936. style |= NSClosableWindowMask;
  227937. if ((windowStyleFlags & windowIsResizable) != 0)
  227938. style |= NSResizableWindowMask;
  227939. window = [[JuceNSWindow alloc] initWithContentRect: r
  227940. styleMask: style
  227941. backing: NSBackingStoreBuffered
  227942. defer: YES];
  227943. [((JuceNSWindow*) window) setOwner: this];
  227944. [window orderOut: nil];
  227945. [window setDelegate: (JuceNSWindow*) window];
  227946. [window setOpaque: component->isOpaque()];
  227947. [window setHasShadow: ((windowStyleFlags & windowHasDropShadow) != 0)];
  227948. if (component->isAlwaysOnTop())
  227949. [window setLevel: NSFloatingWindowLevel];
  227950. [window setContentView: view];
  227951. [window setAutodisplay: YES];
  227952. [window setAcceptsMouseMovedEvents: YES];
  227953. // We'll both retain and also release this on closing because plugin hosts can unexpectedly
  227954. // close the window for us, and also tend to get cause trouble if setReleasedWhenClosed is NO.
  227955. [window setReleasedWhenClosed: YES];
  227956. [window retain];
  227957. [window setExcludedFromWindowsMenu: (windowStyleFlags & windowIsTemporary) != 0];
  227958. [window setIgnoresMouseEvents: (windowStyleFlags & windowIgnoresMouseClicks) != 0];
  227959. }
  227960. setTitle (component->getName());
  227961. }
  227962. NSViewComponentPeer::~NSViewComponentPeer()
  227963. {
  227964. view->owner = 0;
  227965. [view removeFromSuperview];
  227966. [view release];
  227967. if (! isSharedWindow)
  227968. {
  227969. [((JuceNSWindow*) window) setOwner: 0];
  227970. [window close];
  227971. [window release];
  227972. }
  227973. }
  227974. void* NSViewComponentPeer::getNativeHandle() const
  227975. {
  227976. return view;
  227977. }
  227978. void NSViewComponentPeer::setVisible (bool shouldBeVisible)
  227979. {
  227980. if (isSharedWindow)
  227981. {
  227982. [view setHidden: ! shouldBeVisible];
  227983. }
  227984. else
  227985. {
  227986. if (shouldBeVisible)
  227987. {
  227988. [window orderFront: nil];
  227989. handleBroughtToFront();
  227990. }
  227991. else
  227992. {
  227993. [window orderOut: nil];
  227994. }
  227995. }
  227996. }
  227997. void NSViewComponentPeer::setTitle (const String& title)
  227998. {
  227999. const ScopedAutoReleasePool pool;
  228000. if (! isSharedWindow)
  228001. [window setTitle: juceStringToNS (title)];
  228002. }
  228003. void NSViewComponentPeer::setPosition (int x, int y)
  228004. {
  228005. setBounds (x, y, component->getWidth(), component->getHeight(), false);
  228006. }
  228007. void NSViewComponentPeer::setSize (int w, int h)
  228008. {
  228009. setBounds (component->getX(), component->getY(), w, h, false);
  228010. }
  228011. void NSViewComponentPeer::setBounds (int x, int y, int w, int h, bool isNowFullScreen)
  228012. {
  228013. fullScreen = isNowFullScreen;
  228014. w = jmax (0, w);
  228015. h = jmax (0, h);
  228016. NSRect r;
  228017. r.origin.x = (float) x;
  228018. r.origin.y = (float) y;
  228019. r.size.width = (float) w;
  228020. r.size.height = (float) h;
  228021. if (isSharedWindow)
  228022. {
  228023. r.origin.y = [[view superview] frame].size.height - (r.origin.y + r.size.height);
  228024. if ([view frame].size.width != r.size.width
  228025. || [view frame].size.height != r.size.height)
  228026. [view setNeedsDisplay: true];
  228027. [view setFrame: r];
  228028. }
  228029. else
  228030. {
  228031. r.origin.y = [[[NSScreen screens] objectAtIndex: 0] frame].size.height - (r.origin.y + r.size.height);
  228032. [window setFrame: [window frameRectForContentRect: r]
  228033. display: true];
  228034. }
  228035. }
  228036. const Rectangle<int> NSViewComponentPeer::getBounds (const bool global) const
  228037. {
  228038. NSRect r = [view frame];
  228039. if (global && [view window] != 0)
  228040. {
  228041. r = [view convertRect: r toView: nil];
  228042. NSRect wr = [[view window] frame];
  228043. r.origin.x += wr.origin.x;
  228044. r.origin.y += wr.origin.y;
  228045. r.origin.y = [[[NSScreen screens] objectAtIndex: 0] frame].size.height - r.origin.y - r.size.height;
  228046. }
  228047. else
  228048. {
  228049. r.origin.y = [[view superview] frame].size.height - r.origin.y - r.size.height;
  228050. }
  228051. return Rectangle<int> ((int) r.origin.x, (int) r.origin.y, (int) r.size.width, (int) r.size.height);
  228052. }
  228053. const Rectangle<int> NSViewComponentPeer::getBounds() const
  228054. {
  228055. return getBounds (! isSharedWindow);
  228056. }
  228057. const Point<int> NSViewComponentPeer::getScreenPosition() const
  228058. {
  228059. return getBounds (true).getPosition();
  228060. }
  228061. const Point<int> NSViewComponentPeer::relativePositionToGlobal (const Point<int>& relativePosition)
  228062. {
  228063. return relativePosition + getScreenPosition();
  228064. }
  228065. const Point<int> NSViewComponentPeer::globalPositionToRelative (const Point<int>& screenPosition)
  228066. {
  228067. return screenPosition - getScreenPosition();
  228068. }
  228069. NSRect NSViewComponentPeer::constrainRect (NSRect r)
  228070. {
  228071. if (constrainer != 0)
  228072. {
  228073. NSRect current = [window frame];
  228074. current.origin.y = [[[NSScreen screens] objectAtIndex: 0] frame].size.height - current.origin.y - current.size.height;
  228075. r.origin.y = [[[NSScreen screens] objectAtIndex: 0] frame].size.height - r.origin.y - r.size.height;
  228076. Rectangle<int> pos ((int) r.origin.x, (int) r.origin.y,
  228077. (int) r.size.width, (int) r.size.height);
  228078. Rectangle<int> original ((int) current.origin.x, (int) current.origin.y,
  228079. (int) current.size.width, (int) current.size.height);
  228080. constrainer->checkBounds (pos, original,
  228081. Desktop::getInstance().getAllMonitorDisplayAreas().getBounds(),
  228082. pos.getY() != original.getY() && pos.getBottom() == original.getBottom(),
  228083. pos.getX() != original.getX() && pos.getRight() == original.getRight(),
  228084. pos.getY() == original.getY() && pos.getBottom() != original.getBottom(),
  228085. pos.getX() == original.getX() && pos.getRight() != original.getRight());
  228086. r.origin.x = pos.getX();
  228087. r.origin.y = [[[NSScreen screens] objectAtIndex: 0] frame].size.height - r.size.height - pos.getY();
  228088. r.size.width = pos.getWidth();
  228089. r.size.height = pos.getHeight();
  228090. }
  228091. return r;
  228092. }
  228093. void NSViewComponentPeer::setMinimised (bool shouldBeMinimised)
  228094. {
  228095. if (! isSharedWindow)
  228096. {
  228097. if (shouldBeMinimised)
  228098. [window miniaturize: nil];
  228099. else
  228100. [window deminiaturize: nil];
  228101. }
  228102. }
  228103. bool NSViewComponentPeer::isMinimised() const
  228104. {
  228105. return window != 0 && [window isMiniaturized];
  228106. }
  228107. void NSViewComponentPeer::setFullScreen (bool shouldBeFullScreen)
  228108. {
  228109. if (! isSharedWindow)
  228110. {
  228111. Rectangle<int> r (lastNonFullscreenBounds);
  228112. setMinimised (false);
  228113. if (fullScreen != shouldBeFullScreen)
  228114. {
  228115. if (shouldBeFullScreen && (getStyleFlags() & windowHasTitleBar) != 0)
  228116. {
  228117. fullScreen = true;
  228118. [window performZoom: nil];
  228119. }
  228120. else
  228121. {
  228122. if (shouldBeFullScreen)
  228123. r = Desktop::getInstance().getMainMonitorArea();
  228124. // (can't call the component's setBounds method because that'll reset our fullscreen flag)
  228125. if (r != getComponent()->getBounds() && ! r.isEmpty())
  228126. setBounds (r.getX(), r.getY(), r.getWidth(), r.getHeight(), shouldBeFullScreen);
  228127. }
  228128. }
  228129. }
  228130. }
  228131. bool NSViewComponentPeer::isFullScreen() const
  228132. {
  228133. return fullScreen;
  228134. }
  228135. bool NSViewComponentPeer::contains (const Point<int>& position, bool trueIfInAChildWindow) const
  228136. {
  228137. if (((unsigned int) position.getX()) >= (unsigned int) component->getWidth()
  228138. || ((unsigned int) position.getY()) >= (unsigned int) component->getHeight())
  228139. return false;
  228140. NSPoint p;
  228141. p.x = (float) position.getX();
  228142. p.y = (float) position.getY();
  228143. NSView* v = [view hitTest: p];
  228144. if (trueIfInAChildWindow)
  228145. return v != nil;
  228146. return v == view;
  228147. }
  228148. const BorderSize NSViewComponentPeer::getFrameSize() const
  228149. {
  228150. BorderSize b;
  228151. if (! isSharedWindow)
  228152. {
  228153. NSRect v = [view convertRect: [view frame] toView: nil];
  228154. NSRect w = [window frame];
  228155. b.setTop ((int) (w.size.height - (v.origin.y + v.size.height)));
  228156. b.setBottom ((int) v.origin.y);
  228157. b.setLeft ((int) v.origin.x);
  228158. b.setRight ((int) (w.size.width - (v.origin.x + v.size.width)));
  228159. }
  228160. return b;
  228161. }
  228162. bool NSViewComponentPeer::setAlwaysOnTop (bool alwaysOnTop)
  228163. {
  228164. if (! isSharedWindow)
  228165. {
  228166. [window setLevel: alwaysOnTop ? NSFloatingWindowLevel
  228167. : NSNormalWindowLevel];
  228168. }
  228169. return true;
  228170. }
  228171. void NSViewComponentPeer::toFront (bool makeActiveWindow)
  228172. {
  228173. if (isSharedWindow)
  228174. {
  228175. [[view superview] addSubview: view
  228176. positioned: NSWindowAbove
  228177. relativeTo: nil];
  228178. }
  228179. if (window != 0 && component->isVisible())
  228180. {
  228181. if (makeActiveWindow)
  228182. [window makeKeyAndOrderFront: nil];
  228183. else
  228184. [window orderFront: nil];
  228185. if (! recursiveToFrontCall)
  228186. {
  228187. recursiveToFrontCall = true;
  228188. Desktop::getInstance().getMainMouseSource().forceMouseCursorUpdate();
  228189. handleBroughtToFront();
  228190. recursiveToFrontCall = false;
  228191. }
  228192. }
  228193. }
  228194. void NSViewComponentPeer::toBehind (ComponentPeer* other)
  228195. {
  228196. NSViewComponentPeer* const otherPeer = dynamic_cast <NSViewComponentPeer*> (other);
  228197. jassert (otherPeer != 0); // wrong type of window?
  228198. if (otherPeer != 0)
  228199. {
  228200. if (isSharedWindow)
  228201. {
  228202. [[view superview] addSubview: view
  228203. positioned: NSWindowBelow
  228204. relativeTo: otherPeer->view];
  228205. }
  228206. else
  228207. {
  228208. [window orderWindow: NSWindowBelow
  228209. relativeTo: otherPeer->window != 0 ? [otherPeer->window windowNumber]
  228210. : nil ];
  228211. }
  228212. }
  228213. }
  228214. void NSViewComponentPeer::setIcon (const Image& /*newIcon*/)
  228215. {
  228216. // to do..
  228217. }
  228218. void NSViewComponentPeer::viewFocusGain()
  228219. {
  228220. if (currentlyFocusedPeer != this)
  228221. {
  228222. if (ComponentPeer::isValidPeer (currentlyFocusedPeer))
  228223. currentlyFocusedPeer->handleFocusLoss();
  228224. currentlyFocusedPeer = this;
  228225. handleFocusGain();
  228226. }
  228227. }
  228228. void NSViewComponentPeer::viewFocusLoss()
  228229. {
  228230. if (currentlyFocusedPeer == this)
  228231. {
  228232. currentlyFocusedPeer = 0;
  228233. handleFocusLoss();
  228234. }
  228235. }
  228236. void juce_HandleProcessFocusChange()
  228237. {
  228238. NSViewComponentPeer::keysCurrentlyDown.clear();
  228239. if (NSViewComponentPeer::isValidPeer (NSViewComponentPeer::currentlyFocusedPeer))
  228240. {
  228241. if (Process::isForegroundProcess())
  228242. {
  228243. NSViewComponentPeer::currentlyFocusedPeer->handleFocusGain();
  228244. ComponentPeer::bringModalComponentToFront();
  228245. }
  228246. else
  228247. {
  228248. NSViewComponentPeer::currentlyFocusedPeer->handleFocusLoss();
  228249. // turn kiosk mode off if we lose focus..
  228250. Desktop::getInstance().setKioskModeComponent (0);
  228251. }
  228252. }
  228253. }
  228254. bool NSViewComponentPeer::isFocused() const
  228255. {
  228256. return isSharedWindow ? this == currentlyFocusedPeer
  228257. : (window != 0 && [window isKeyWindow]);
  228258. }
  228259. void NSViewComponentPeer::grabFocus()
  228260. {
  228261. if (window != 0)
  228262. {
  228263. [window makeKeyWindow];
  228264. [window makeFirstResponder: view];
  228265. viewFocusGain();
  228266. }
  228267. }
  228268. void NSViewComponentPeer::textInputRequired (const Point<int>&)
  228269. {
  228270. }
  228271. bool NSViewComponentPeer::handleKeyEvent (NSEvent* ev, bool isKeyDown)
  228272. {
  228273. String unicode (nsStringToJuce ([ev characters]));
  228274. String unmodified (nsStringToJuce ([ev charactersIgnoringModifiers]));
  228275. int keyCode = getKeyCodeFromEvent (ev);
  228276. //DBG ("unicode: " + unicode + " " + String::toHexString ((int) unicode[0]));
  228277. //DBG ("unmodified: " + unmodified + " " + String::toHexString ((int) unmodified[0]));
  228278. if (unicode.isNotEmpty() || keyCode != 0)
  228279. {
  228280. if (isKeyDown)
  228281. {
  228282. bool used = false;
  228283. while (unicode.length() > 0)
  228284. {
  228285. juce_wchar textCharacter = unicode[0];
  228286. unicode = unicode.substring (1);
  228287. if (([ev modifierFlags] & NSCommandKeyMask) != 0)
  228288. textCharacter = 0;
  228289. used = handleKeyUpOrDown (true) || used;
  228290. used = handleKeyPress (keyCode, textCharacter) || used;
  228291. }
  228292. return used;
  228293. }
  228294. else
  228295. {
  228296. if (handleKeyUpOrDown (false))
  228297. return true;
  228298. }
  228299. }
  228300. return false;
  228301. }
  228302. bool NSViewComponentPeer::redirectKeyDown (NSEvent* ev)
  228303. {
  228304. updateKeysDown (ev, true);
  228305. bool used = handleKeyEvent (ev, true);
  228306. if (([ev modifierFlags] & NSCommandKeyMask) != 0)
  228307. {
  228308. // for command keys, the key-up event is thrown away, so simulate one..
  228309. updateKeysDown (ev, false);
  228310. used = (isValidPeer (this) && handleKeyEvent (ev, false)) || used;
  228311. }
  228312. // (If we're running modally, don't allow unused keystrokes to be passed
  228313. // along to other blocked views..)
  228314. if (Component::getCurrentlyModalComponent() != 0)
  228315. used = true;
  228316. return used;
  228317. }
  228318. bool NSViewComponentPeer::redirectKeyUp (NSEvent* ev)
  228319. {
  228320. updateKeysDown (ev, false);
  228321. return handleKeyEvent (ev, false)
  228322. || Component::getCurrentlyModalComponent() != 0;
  228323. }
  228324. void NSViewComponentPeer::redirectModKeyChange (NSEvent* ev)
  228325. {
  228326. keysCurrentlyDown.clear();
  228327. handleKeyUpOrDown (true);
  228328. updateModifiers (ev);
  228329. handleModifierKeysChange();
  228330. }
  228331. #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
  228332. bool NSViewComponentPeer::redirectPerformKeyEquivalent (NSEvent* ev)
  228333. {
  228334. if ([ev type] == NSKeyDown)
  228335. return redirectKeyDown (ev);
  228336. else if ([ev type] == NSKeyUp)
  228337. return redirectKeyUp (ev);
  228338. return false;
  228339. }
  228340. #endif
  228341. void NSViewComponentPeer::sendMouseEvent (NSEvent* ev)
  228342. {
  228343. updateModifiers (ev);
  228344. handleMouseEvent (0, getMousePos (ev, view), currentModifiers, getMouseTime (ev));
  228345. }
  228346. void NSViewComponentPeer::redirectMouseDown (NSEvent* ev)
  228347. {
  228348. currentModifiers = currentModifiers.withFlags (getModifierForButtonNumber ([ev buttonNumber]));
  228349. sendMouseEvent (ev);
  228350. }
  228351. void NSViewComponentPeer::redirectMouseUp (NSEvent* ev)
  228352. {
  228353. currentModifiers = currentModifiers.withoutFlags (getModifierForButtonNumber ([ev buttonNumber]));
  228354. sendMouseEvent (ev);
  228355. showArrowCursorIfNeeded();
  228356. }
  228357. void NSViewComponentPeer::redirectMouseDrag (NSEvent* ev)
  228358. {
  228359. currentModifiers = currentModifiers.withFlags (getModifierForButtonNumber ([ev buttonNumber]));
  228360. sendMouseEvent (ev);
  228361. }
  228362. void NSViewComponentPeer::redirectMouseMove (NSEvent* ev)
  228363. {
  228364. currentModifiers = currentModifiers.withoutMouseButtons();
  228365. sendMouseEvent (ev);
  228366. showArrowCursorIfNeeded();
  228367. }
  228368. void NSViewComponentPeer::redirectMouseEnter (NSEvent* ev)
  228369. {
  228370. Desktop::getInstance().getMainMouseSource().forceMouseCursorUpdate();
  228371. currentModifiers = currentModifiers.withoutMouseButtons();
  228372. sendMouseEvent (ev);
  228373. }
  228374. void NSViewComponentPeer::redirectMouseExit (NSEvent* ev)
  228375. {
  228376. currentModifiers = currentModifiers.withoutMouseButtons();
  228377. sendMouseEvent (ev);
  228378. }
  228379. void NSViewComponentPeer::redirectMouseWheel (NSEvent* ev)
  228380. {
  228381. updateModifiers (ev);
  228382. handleMouseWheel (0, getMousePos (ev, view), getMouseTime (ev),
  228383. [ev deltaX] * 10.0f, [ev deltaY] * 10.0f);
  228384. }
  228385. void NSViewComponentPeer::showArrowCursorIfNeeded()
  228386. {
  228387. MouseInputSource& mouse = Desktop::getInstance().getMainMouseSource();
  228388. if (mouse.getComponentUnderMouse() == 0
  228389. && Desktop::getInstance().findComponentAt (mouse.getScreenPosition()) == 0)
  228390. {
  228391. [[NSCursor arrowCursor] set];
  228392. }
  228393. }
  228394. BOOL NSViewComponentPeer::sendDragCallback (int type, id <NSDraggingInfo> sender)
  228395. {
  228396. NSString* bestType
  228397. = [[sender draggingPasteboard] availableTypeFromArray: [view getSupportedDragTypes]];
  228398. if (bestType == nil)
  228399. return false;
  228400. NSPoint p = [view convertPoint: [sender draggingLocation] fromView: nil];
  228401. const Point<int> pos ((int) p.x, (int) ([view frame].size.height - p.y));
  228402. StringArray files;
  228403. id list = [[sender draggingPasteboard] propertyListForType: bestType];
  228404. if (list == nil)
  228405. return false;
  228406. if ([list isKindOfClass: [NSArray class]])
  228407. {
  228408. NSArray* items = (NSArray*) list;
  228409. for (unsigned int i = 0; i < [items count]; ++i)
  228410. files.add (nsStringToJuce ((NSString*) [items objectAtIndex: i]));
  228411. }
  228412. if (files.size() == 0)
  228413. return false;
  228414. if (type == 0)
  228415. handleFileDragMove (files, pos);
  228416. else if (type == 1)
  228417. handleFileDragExit (files);
  228418. else if (type == 2)
  228419. handleFileDragDrop (files, pos);
  228420. return true;
  228421. }
  228422. bool NSViewComponentPeer::isOpaque()
  228423. {
  228424. return component == 0 || component->isOpaque();
  228425. }
  228426. void NSViewComponentPeer::drawRect (NSRect r)
  228427. {
  228428. if (r.size.width < 1.0f || r.size.height < 1.0f)
  228429. return;
  228430. CGContextRef cg = (CGContextRef) [[NSGraphicsContext currentContext] graphicsPort];
  228431. if (! component->isOpaque())
  228432. CGContextClearRect (cg, CGContextGetClipBoundingBox (cg));
  228433. #if USE_COREGRAPHICS_RENDERING
  228434. if (usingCoreGraphics)
  228435. {
  228436. CoreGraphicsContext context (cg, (float) [view frame].size.height);
  228437. insideDrawRect = true;
  228438. handlePaint (context);
  228439. insideDrawRect = false;
  228440. }
  228441. else
  228442. #endif
  228443. {
  228444. Image temp (getComponent()->isOpaque() ? Image::RGB : Image::ARGB,
  228445. (int) (r.size.width + 0.5f),
  228446. (int) (r.size.height + 0.5f),
  228447. ! getComponent()->isOpaque());
  228448. const int xOffset = -roundToInt (r.origin.x);
  228449. const int yOffset = -roundToInt ([view frame].size.height - (r.origin.y + r.size.height));
  228450. const NSRect* rects = 0;
  228451. NSInteger numRects = 0;
  228452. [view getRectsBeingDrawn: &rects count: &numRects];
  228453. const Rectangle<int> clipBounds (temp.getBounds());
  228454. RectangleList clip;
  228455. for (int i = 0; i < numRects; ++i)
  228456. {
  228457. clip.addWithoutMerging (clipBounds.getIntersection (Rectangle<int> (roundToInt (rects[i].origin.x) + xOffset,
  228458. roundToInt ([view frame].size.height - (rects[i].origin.y + rects[i].size.height)) + yOffset,
  228459. roundToInt (rects[i].size.width),
  228460. roundToInt (rects[i].size.height))));
  228461. }
  228462. if (! clip.isEmpty())
  228463. {
  228464. LowLevelGraphicsSoftwareRenderer context (temp, xOffset, yOffset, clip);
  228465. insideDrawRect = true;
  228466. handlePaint (context);
  228467. insideDrawRect = false;
  228468. CGColorSpaceRef colourSpace = CGColorSpaceCreateDeviceRGB();
  228469. CGImageRef image = CoreGraphicsImage::createImage (temp, false, colourSpace);
  228470. CGColorSpaceRelease (colourSpace);
  228471. CGContextDrawImage (cg, CGRectMake (r.origin.x, r.origin.y, temp.getWidth(), temp.getHeight()), image);
  228472. CGImageRelease (image);
  228473. }
  228474. }
  228475. }
  228476. const StringArray NSViewComponentPeer::getAvailableRenderingEngines() throw()
  228477. {
  228478. StringArray s;
  228479. s.add ("Software Renderer");
  228480. #if USE_COREGRAPHICS_RENDERING
  228481. s.add ("CoreGraphics Renderer");
  228482. #endif
  228483. return s;
  228484. }
  228485. int NSViewComponentPeer::getCurrentRenderingEngine() throw()
  228486. {
  228487. return usingCoreGraphics ? 1 : 0;
  228488. }
  228489. void NSViewComponentPeer::setCurrentRenderingEngine (int index) throw()
  228490. {
  228491. #if USE_COREGRAPHICS_RENDERING
  228492. if (usingCoreGraphics != (index > 0))
  228493. {
  228494. usingCoreGraphics = index > 0;
  228495. [view setNeedsDisplay: true];
  228496. }
  228497. #endif
  228498. }
  228499. bool NSViewComponentPeer::canBecomeKeyWindow()
  228500. {
  228501. return (getStyleFlags() & JUCE_NAMESPACE::ComponentPeer::windowIgnoresKeyPresses) == 0;
  228502. }
  228503. bool NSViewComponentPeer::windowShouldClose()
  228504. {
  228505. if (! isValidPeer (this))
  228506. return YES;
  228507. handleUserClosingWindow();
  228508. return NO;
  228509. }
  228510. void NSViewComponentPeer::redirectMovedOrResized()
  228511. {
  228512. handleMovedOrResized();
  228513. }
  228514. void NSViewComponentPeer::viewMovedToWindow()
  228515. {
  228516. if (isSharedWindow)
  228517. window = [view window];
  228518. }
  228519. void Desktop::createMouseInputSources()
  228520. {
  228521. mouseSources.add (new MouseInputSource (0, true));
  228522. }
  228523. void juce_setKioskComponent (Component* kioskModeComponent, bool enableOrDisable, bool allowMenusAndBars)
  228524. {
  228525. // Very annoyingly, this function has to use the old SetSystemUIMode function,
  228526. // which is in Carbon.framework. But, because there's no Cocoa equivalent, it
  228527. // is apparently still available in 64-bit apps..
  228528. if (enableOrDisable)
  228529. {
  228530. SetSystemUIMode (kUIModeAllSuppressed, allowMenusAndBars ? kUIOptionAutoShowMenuBar : 0);
  228531. kioskModeComponent->setBounds (Desktop::getInstance().getMainMonitorArea (false));
  228532. }
  228533. else
  228534. {
  228535. SetSystemUIMode (kUIModeNormal, 0);
  228536. }
  228537. }
  228538. class AsyncRepaintMessage : public CallbackMessage
  228539. {
  228540. public:
  228541. NSViewComponentPeer* const peer;
  228542. const Rectangle<int> rect;
  228543. AsyncRepaintMessage (NSViewComponentPeer* const peer_, const Rectangle<int>& rect_)
  228544. : peer (peer_), rect (rect_)
  228545. {
  228546. }
  228547. void messageCallback()
  228548. {
  228549. if (ComponentPeer::isValidPeer (peer))
  228550. peer->repaint (rect.getX(), rect.getY(), rect.getWidth(), rect.getHeight());
  228551. }
  228552. };
  228553. void NSViewComponentPeer::repaint (int x, int y, int w, int h)
  228554. {
  228555. if (insideDrawRect)
  228556. {
  228557. (new AsyncRepaintMessage (this, Rectangle<int> (x, y, w, h)))->post();
  228558. }
  228559. else
  228560. {
  228561. [view setNeedsDisplayInRect: NSMakeRect ((float) x, (float) ([view frame].size.height - (y + h)),
  228562. (float) w, (float) h)];
  228563. }
  228564. }
  228565. void NSViewComponentPeer::performAnyPendingRepaintsNow()
  228566. {
  228567. [view displayIfNeeded];
  228568. }
  228569. ComponentPeer* Component::createNewPeer (int styleFlags, void* windowToAttachTo)
  228570. {
  228571. return new NSViewComponentPeer (this, styleFlags, (NSView*) windowToAttachTo);
  228572. }
  228573. Image* juce_createIconForFile (const File& file)
  228574. {
  228575. const ScopedAutoReleasePool pool;
  228576. NSImage* image = [[NSWorkspace sharedWorkspace] iconForFile: juceStringToNS (file.getFullPathName())];
  228577. CoreGraphicsImage* result = new CoreGraphicsImage (Image::ARGB, (int) [image size].width, (int) [image size].height, true);
  228578. [NSGraphicsContext saveGraphicsState];
  228579. [NSGraphicsContext setCurrentContext: [NSGraphicsContext graphicsContextWithGraphicsPort: result->context flipped: false]];
  228580. [image drawAtPoint: NSMakePoint (0, 0)
  228581. fromRect: NSMakeRect (0, 0, [image size].width, [image size].height)
  228582. operation: NSCompositeSourceOver fraction: 1.0f];
  228583. [[NSGraphicsContext currentContext] flushGraphics];
  228584. [NSGraphicsContext restoreGraphicsState];
  228585. return result;
  228586. }
  228587. const int KeyPress::spaceKey = ' ';
  228588. const int KeyPress::returnKey = 0x0d;
  228589. const int KeyPress::escapeKey = 0x1b;
  228590. const int KeyPress::backspaceKey = 0x7f;
  228591. const int KeyPress::leftKey = NSLeftArrowFunctionKey;
  228592. const int KeyPress::rightKey = NSRightArrowFunctionKey;
  228593. const int KeyPress::upKey = NSUpArrowFunctionKey;
  228594. const int KeyPress::downKey = NSDownArrowFunctionKey;
  228595. const int KeyPress::pageUpKey = NSPageUpFunctionKey;
  228596. const int KeyPress::pageDownKey = NSPageDownFunctionKey;
  228597. const int KeyPress::endKey = NSEndFunctionKey;
  228598. const int KeyPress::homeKey = NSHomeFunctionKey;
  228599. const int KeyPress::deleteKey = NSDeleteFunctionKey;
  228600. const int KeyPress::insertKey = -1;
  228601. const int KeyPress::tabKey = 9;
  228602. const int KeyPress::F1Key = NSF1FunctionKey;
  228603. const int KeyPress::F2Key = NSF2FunctionKey;
  228604. const int KeyPress::F3Key = NSF3FunctionKey;
  228605. const int KeyPress::F4Key = NSF4FunctionKey;
  228606. const int KeyPress::F5Key = NSF5FunctionKey;
  228607. const int KeyPress::F6Key = NSF6FunctionKey;
  228608. const int KeyPress::F7Key = NSF7FunctionKey;
  228609. const int KeyPress::F8Key = NSF8FunctionKey;
  228610. const int KeyPress::F9Key = NSF9FunctionKey;
  228611. const int KeyPress::F10Key = NSF10FunctionKey;
  228612. const int KeyPress::F11Key = NSF1FunctionKey;
  228613. const int KeyPress::F12Key = NSF12FunctionKey;
  228614. const int KeyPress::F13Key = NSF13FunctionKey;
  228615. const int KeyPress::F14Key = NSF14FunctionKey;
  228616. const int KeyPress::F15Key = NSF15FunctionKey;
  228617. const int KeyPress::F16Key = NSF16FunctionKey;
  228618. const int KeyPress::numberPad0 = 0x30020;
  228619. const int KeyPress::numberPad1 = 0x30021;
  228620. const int KeyPress::numberPad2 = 0x30022;
  228621. const int KeyPress::numberPad3 = 0x30023;
  228622. const int KeyPress::numberPad4 = 0x30024;
  228623. const int KeyPress::numberPad5 = 0x30025;
  228624. const int KeyPress::numberPad6 = 0x30026;
  228625. const int KeyPress::numberPad7 = 0x30027;
  228626. const int KeyPress::numberPad8 = 0x30028;
  228627. const int KeyPress::numberPad9 = 0x30029;
  228628. const int KeyPress::numberPadAdd = 0x3002a;
  228629. const int KeyPress::numberPadSubtract = 0x3002b;
  228630. const int KeyPress::numberPadMultiply = 0x3002c;
  228631. const int KeyPress::numberPadDivide = 0x3002d;
  228632. const int KeyPress::numberPadSeparator = 0x3002e;
  228633. const int KeyPress::numberPadDecimalPoint = 0x3002f;
  228634. const int KeyPress::numberPadEquals = 0x30030;
  228635. const int KeyPress::numberPadDelete = 0x30031;
  228636. const int KeyPress::playKey = 0x30000;
  228637. const int KeyPress::stopKey = 0x30001;
  228638. const int KeyPress::fastForwardKey = 0x30002;
  228639. const int KeyPress::rewindKey = 0x30003;
  228640. #endif
  228641. /*** End of inlined file: juce_mac_NSViewComponentPeer.mm ***/
  228642. /*** Start of inlined file: juce_mac_MouseCursor.mm ***/
  228643. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  228644. // compiled on its own).
  228645. #if JUCE_INCLUDED_FILE
  228646. #if JUCE_MAC
  228647. namespace MouseCursorHelpers
  228648. {
  228649. static void* createFromImage (const Image& image, float hotspotX, float hotspotY)
  228650. {
  228651. NSImage* im = CoreGraphicsImage::createNSImage (image);
  228652. NSCursor* c = [[NSCursor alloc] initWithImage: im
  228653. hotSpot: NSMakePoint (hotspotX, hotspotY)];
  228654. [im release];
  228655. return c;
  228656. }
  228657. static void* fromWebKitFile (const char* filename, float hx, float hy)
  228658. {
  228659. FileInputStream fileStream (String ("/System/Library/Frameworks/WebKit.framework/Frameworks/WebCore.framework/Resources/") + filename);
  228660. BufferedInputStream buf (&fileStream, 4096, false);
  228661. PNGImageFormat pngFormat;
  228662. const ScopedPointer <Image> im (pngFormat.decodeImage (buf));
  228663. if (im != 0)
  228664. return createFromImage (*im, hx * im->getWidth(), hy * im->getHeight());
  228665. jassertfalse;
  228666. return 0;
  228667. }
  228668. }
  228669. void* MouseCursor::createMouseCursorFromImage (const Image& image, int hotspotX, int hotspotY)
  228670. {
  228671. return MouseCursorHelpers::createFromImage (image, (float) hotspotX, (float) hotspotY);
  228672. }
  228673. void* MouseCursor::createStandardMouseCursor (MouseCursor::StandardCursorType type)
  228674. {
  228675. const ScopedAutoReleasePool pool;
  228676. NSCursor* c = 0;
  228677. switch (type)
  228678. {
  228679. case NormalCursor: c = [NSCursor arrowCursor]; break;
  228680. case NoCursor: return createMouseCursorFromImage (Image (Image::ARGB, 8, 8, true), 0, 0);
  228681. case DraggingHandCursor: c = [NSCursor openHandCursor]; break;
  228682. case WaitCursor: c = [NSCursor arrowCursor]; break; // avoid this on the mac, let the OS provide the beachball
  228683. case IBeamCursor: c = [NSCursor IBeamCursor]; break;
  228684. case PointingHandCursor: c = [NSCursor pointingHandCursor]; break;
  228685. case LeftRightResizeCursor: c = [NSCursor resizeLeftRightCursor]; break;
  228686. case LeftEdgeResizeCursor: c = [NSCursor resizeLeftCursor]; break;
  228687. case RightEdgeResizeCursor: c = [NSCursor resizeRightCursor]; break;
  228688. case CrosshairCursor: c = [NSCursor crosshairCursor]; break;
  228689. case CopyingCursor: return MouseCursorHelpers::fromWebKitFile ("copyCursor.png", 0, 0);
  228690. case UpDownResizeCursor:
  228691. case TopEdgeResizeCursor:
  228692. case BottomEdgeResizeCursor:
  228693. return MouseCursorHelpers::fromWebKitFile ("northSouthResizeCursor.png", 0.5f, 0.5f);
  228694. case TopLeftCornerResizeCursor:
  228695. case BottomRightCornerResizeCursor:
  228696. return MouseCursorHelpers::fromWebKitFile ("northWestSouthEastResizeCursor.png", 0.5f, 0.5f);
  228697. case TopRightCornerResizeCursor:
  228698. case BottomLeftCornerResizeCursor:
  228699. return MouseCursorHelpers::fromWebKitFile ("northEastSouthWestResizeCursor.png", 0.5f, 0.5f);
  228700. case UpDownLeftRightResizeCursor:
  228701. return MouseCursorHelpers::fromWebKitFile ("moveCursor.png", 0.5f, 0.5f);
  228702. default:
  228703. jassertfalse;
  228704. break;
  228705. }
  228706. [c retain];
  228707. return c;
  228708. }
  228709. void MouseCursor::deleteMouseCursor (void* const cursorHandle, const bool /*isStandard*/)
  228710. {
  228711. [((NSCursor*) cursorHandle) release];
  228712. }
  228713. void MouseCursor::showInAllWindows() const
  228714. {
  228715. showInWindow (0);
  228716. }
  228717. void MouseCursor::showInWindow (ComponentPeer*) const
  228718. {
  228719. [((NSCursor*) getHandle()) set];
  228720. }
  228721. #else
  228722. void* MouseCursor::createMouseCursorFromImage (const Image& image, int hotspotX, int hotspotY) { return 0; }
  228723. void* MouseCursor::createStandardMouseCursor (MouseCursor::StandardCursorType type) { return 0; }
  228724. void MouseCursor::deleteMouseCursor (void* const cursorHandle, const bool isStandard) {}
  228725. void MouseCursor::showInAllWindows() const {}
  228726. void MouseCursor::showInWindow (ComponentPeer*) const {}
  228727. #endif
  228728. #endif
  228729. /*** End of inlined file: juce_mac_MouseCursor.mm ***/
  228730. /*** Start of inlined file: juce_mac_NSViewComponent.mm ***/
  228731. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  228732. // compiled on its own).
  228733. #if JUCE_INCLUDED_FILE
  228734. class NSViewComponentInternal : public ComponentMovementWatcher
  228735. {
  228736. Component* const owner;
  228737. NSViewComponentPeer* currentPeer;
  228738. bool wasShowing;
  228739. public:
  228740. NSView* const view;
  228741. NSViewComponentInternal (NSView* const view_, Component* const owner_)
  228742. : ComponentMovementWatcher (owner_),
  228743. owner (owner_),
  228744. currentPeer (0),
  228745. wasShowing (false),
  228746. view (view_)
  228747. {
  228748. [view_ retain];
  228749. if (owner_->isShowing())
  228750. componentPeerChanged();
  228751. }
  228752. ~NSViewComponentInternal()
  228753. {
  228754. [view removeFromSuperview];
  228755. [view release];
  228756. }
  228757. void componentMovedOrResized (Component& comp, bool wasMoved, bool wasResized)
  228758. {
  228759. ComponentMovementWatcher::componentMovedOrResized (comp, wasMoved, wasResized);
  228760. // The ComponentMovementWatcher version of this method avoids calling
  228761. // us when the top-level comp is resized, but for an NSView we need to know this
  228762. // because with inverted co-ords, we need to update the position even if the
  228763. // top-left pos hasn't changed
  228764. if (comp.isOnDesktop() && wasResized)
  228765. componentMovedOrResized (wasMoved, wasResized);
  228766. }
  228767. void componentMovedOrResized (bool /*wasMoved*/, bool /*wasResized*/)
  228768. {
  228769. Component* const topComp = owner->getTopLevelComponent();
  228770. if (topComp->getPeer() != 0)
  228771. {
  228772. const Point<int> pos (owner->relativePositionToOtherComponent (topComp, Point<int>()));
  228773. NSRect r;
  228774. r.origin.x = (float) pos.getX();
  228775. r.origin.y = (float) pos.getY();
  228776. r.size.width = (float) owner->getWidth();
  228777. r.size.height = (float) owner->getHeight();
  228778. r.origin.y = [[view superview] frame].size.height - (r.origin.y + r.size.height);
  228779. [view setFrame: r];
  228780. }
  228781. }
  228782. void componentPeerChanged()
  228783. {
  228784. NSViewComponentPeer* const peer = dynamic_cast <NSViewComponentPeer*> (owner->getPeer());
  228785. if (currentPeer != peer)
  228786. {
  228787. [view removeFromSuperview];
  228788. currentPeer = peer;
  228789. if (peer != 0)
  228790. {
  228791. [peer->view addSubview: view];
  228792. componentMovedOrResized (false, false);
  228793. }
  228794. }
  228795. [view setHidden: ! owner->isShowing()];
  228796. }
  228797. void componentVisibilityChanged (Component&)
  228798. {
  228799. componentPeerChanged();
  228800. }
  228801. juce_UseDebuggingNewOperator
  228802. private:
  228803. NSViewComponentInternal (const NSViewComponentInternal&);
  228804. NSViewComponentInternal& operator= (const NSViewComponentInternal&);
  228805. };
  228806. NSViewComponent::NSViewComponent()
  228807. {
  228808. }
  228809. NSViewComponent::~NSViewComponent()
  228810. {
  228811. }
  228812. void NSViewComponent::setView (void* view)
  228813. {
  228814. if (view != getView())
  228815. {
  228816. if (view != 0)
  228817. info = new NSViewComponentInternal ((NSView*) view, this);
  228818. else
  228819. info = 0;
  228820. }
  228821. }
  228822. void* NSViewComponent::getView() const
  228823. {
  228824. return info == 0 ? 0 : info->view;
  228825. }
  228826. void NSViewComponent::paint (Graphics&)
  228827. {
  228828. }
  228829. #endif
  228830. /*** End of inlined file: juce_mac_NSViewComponent.mm ***/
  228831. /*** Start of inlined file: juce_mac_AppleRemote.mm ***/
  228832. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  228833. // compiled on its own).
  228834. #if JUCE_INCLUDED_FILE
  228835. AppleRemoteDevice::AppleRemoteDevice()
  228836. : device (0),
  228837. queue (0),
  228838. remoteId (0)
  228839. {
  228840. }
  228841. AppleRemoteDevice::~AppleRemoteDevice()
  228842. {
  228843. stop();
  228844. }
  228845. static io_object_t getAppleRemoteDevice()
  228846. {
  228847. CFMutableDictionaryRef dict = IOServiceMatching ("AppleIRController");
  228848. io_iterator_t iter = 0;
  228849. io_object_t iod = 0;
  228850. if (IOServiceGetMatchingServices (kIOMasterPortDefault, dict, &iter) == kIOReturnSuccess
  228851. && iter != 0)
  228852. {
  228853. iod = IOIteratorNext (iter);
  228854. }
  228855. IOObjectRelease (iter);
  228856. return iod;
  228857. }
  228858. static bool createAppleRemoteInterface (io_object_t iod, void** device)
  228859. {
  228860. jassert (*device == 0);
  228861. io_name_t classname;
  228862. if (IOObjectGetClass (iod, classname) == kIOReturnSuccess)
  228863. {
  228864. IOCFPlugInInterface** cfPlugInInterface = 0;
  228865. SInt32 score = 0;
  228866. if (IOCreatePlugInInterfaceForService (iod,
  228867. kIOHIDDeviceUserClientTypeID,
  228868. kIOCFPlugInInterfaceID,
  228869. &cfPlugInInterface,
  228870. &score) == kIOReturnSuccess)
  228871. {
  228872. HRESULT hr = (*cfPlugInInterface)->QueryInterface (cfPlugInInterface,
  228873. CFUUIDGetUUIDBytes (kIOHIDDeviceInterfaceID),
  228874. device);
  228875. (void) hr;
  228876. (*cfPlugInInterface)->Release (cfPlugInInterface);
  228877. }
  228878. }
  228879. return *device != 0;
  228880. }
  228881. bool AppleRemoteDevice::start (const bool inExclusiveMode)
  228882. {
  228883. if (queue != 0)
  228884. return true;
  228885. stop();
  228886. bool result = false;
  228887. io_object_t iod = getAppleRemoteDevice();
  228888. if (iod != 0)
  228889. {
  228890. if (createAppleRemoteInterface (iod, &device) && open (inExclusiveMode))
  228891. result = true;
  228892. else
  228893. stop();
  228894. IOObjectRelease (iod);
  228895. }
  228896. return result;
  228897. }
  228898. void AppleRemoteDevice::stop()
  228899. {
  228900. if (queue != 0)
  228901. {
  228902. (*(IOHIDQueueInterface**) queue)->stop ((IOHIDQueueInterface**) queue);
  228903. (*(IOHIDQueueInterface**) queue)->dispose ((IOHIDQueueInterface**) queue);
  228904. (*(IOHIDQueueInterface**) queue)->Release ((IOHIDQueueInterface**) queue);
  228905. queue = 0;
  228906. }
  228907. if (device != 0)
  228908. {
  228909. (*(IOHIDDeviceInterface**) device)->close ((IOHIDDeviceInterface**) device);
  228910. (*(IOHIDDeviceInterface**) device)->Release ((IOHIDDeviceInterface**) device);
  228911. device = 0;
  228912. }
  228913. }
  228914. bool AppleRemoteDevice::isActive() const
  228915. {
  228916. return queue != 0;
  228917. }
  228918. static void appleRemoteQueueCallback (void* const target, const IOReturn result, void*, void*)
  228919. {
  228920. if (result == kIOReturnSuccess)
  228921. ((AppleRemoteDevice*) target)->handleCallbackInternal();
  228922. }
  228923. bool AppleRemoteDevice::open (const bool openInExclusiveMode)
  228924. {
  228925. Array <int> cookies;
  228926. CFArrayRef elements;
  228927. IOHIDDeviceInterface122** const device122 = (IOHIDDeviceInterface122**) device;
  228928. if ((*device122)->copyMatchingElements (device122, 0, &elements) != kIOReturnSuccess)
  228929. return false;
  228930. for (int i = 0; i < CFArrayGetCount (elements); ++i)
  228931. {
  228932. CFDictionaryRef element = (CFDictionaryRef) CFArrayGetValueAtIndex (elements, i);
  228933. // get the cookie
  228934. CFTypeRef object = CFDictionaryGetValue (element, CFSTR (kIOHIDElementCookieKey));
  228935. if (object == 0 || CFGetTypeID (object) != CFNumberGetTypeID())
  228936. continue;
  228937. long number;
  228938. if (! CFNumberGetValue ((CFNumberRef) object, kCFNumberLongType, &number))
  228939. continue;
  228940. cookies.add ((int) number);
  228941. }
  228942. CFRelease (elements);
  228943. if ((*(IOHIDDeviceInterface**) device)
  228944. ->open ((IOHIDDeviceInterface**) device,
  228945. openInExclusiveMode ? kIOHIDOptionsTypeSeizeDevice
  228946. : kIOHIDOptionsTypeNone) == KERN_SUCCESS)
  228947. {
  228948. queue = (*(IOHIDDeviceInterface**) device)->allocQueue ((IOHIDDeviceInterface**) device);
  228949. if (queue != 0)
  228950. {
  228951. (*(IOHIDQueueInterface**) queue)->create ((IOHIDQueueInterface**) queue, 0, 12);
  228952. for (int i = 0; i < cookies.size(); ++i)
  228953. {
  228954. IOHIDElementCookie cookie = (IOHIDElementCookie) cookies.getUnchecked(i);
  228955. (*(IOHIDQueueInterface**) queue)->addElement ((IOHIDQueueInterface**) queue, cookie, 0);
  228956. }
  228957. CFRunLoopSourceRef eventSource;
  228958. if ((*(IOHIDQueueInterface**) queue)
  228959. ->createAsyncEventSource ((IOHIDQueueInterface**) queue, &eventSource) == KERN_SUCCESS)
  228960. {
  228961. if ((*(IOHIDQueueInterface**) queue)->setEventCallout ((IOHIDQueueInterface**) queue,
  228962. appleRemoteQueueCallback, this, 0) == KERN_SUCCESS)
  228963. {
  228964. CFRunLoopAddSource (CFRunLoopGetCurrent(), eventSource, kCFRunLoopDefaultMode);
  228965. (*(IOHIDQueueInterface**) queue)->start ((IOHIDQueueInterface**) queue);
  228966. return true;
  228967. }
  228968. }
  228969. }
  228970. }
  228971. return false;
  228972. }
  228973. void AppleRemoteDevice::handleCallbackInternal()
  228974. {
  228975. int totalValues = 0;
  228976. AbsoluteTime nullTime = { 0, 0 };
  228977. char cookies [12];
  228978. int numCookies = 0;
  228979. while (numCookies < numElementsInArray (cookies))
  228980. {
  228981. IOHIDEventStruct e;
  228982. if ((*(IOHIDQueueInterface**) queue)->getNextEvent ((IOHIDQueueInterface**) queue, &e, nullTime, 0) != kIOReturnSuccess)
  228983. break;
  228984. if ((int) e.elementCookie == 19)
  228985. {
  228986. remoteId = e.value;
  228987. buttonPressed (switched, false);
  228988. }
  228989. else
  228990. {
  228991. totalValues += e.value;
  228992. cookies [numCookies++] = (char) (pointer_sized_int) e.elementCookie;
  228993. }
  228994. }
  228995. cookies [numCookies++] = 0;
  228996. //DBG (String::toHexString ((uint8*) cookies, numCookies, 1) + " " + String (totalValues));
  228997. static const char buttonPatterns[] =
  228998. {
  228999. 0x1f, 0x14, 0x12, 0x1f, 0x14, 0x12, 0,
  229000. 0x1f, 0x15, 0x12, 0x1f, 0x15, 0x12, 0,
  229001. 0x1f, 0x1d, 0x1c, 0x12, 0,
  229002. 0x1f, 0x1e, 0x1c, 0x12, 0,
  229003. 0x1f, 0x16, 0x12, 0x1f, 0x16, 0x12, 0,
  229004. 0x1f, 0x17, 0x12, 0x1f, 0x17, 0x12, 0,
  229005. 0x1f, 0x12, 0x04, 0x02, 0,
  229006. 0x1f, 0x12, 0x03, 0x02, 0,
  229007. 0x1f, 0x12, 0x1f, 0x12, 0,
  229008. 0x23, 0x1f, 0x12, 0x23, 0x1f, 0x12, 0,
  229009. 19, 0
  229010. };
  229011. int buttonNum = (int) menuButton;
  229012. int i = 0;
  229013. while (i < numElementsInArray (buttonPatterns))
  229014. {
  229015. if (strcmp (cookies, buttonPatterns + i) == 0)
  229016. {
  229017. buttonPressed ((ButtonType) buttonNum, totalValues > 0);
  229018. break;
  229019. }
  229020. i += (int) strlen (buttonPatterns + i) + 1;
  229021. ++buttonNum;
  229022. }
  229023. }
  229024. #endif
  229025. /*** End of inlined file: juce_mac_AppleRemote.mm ***/
  229026. /*** Start of inlined file: juce_mac_OpenGLComponent.mm ***/
  229027. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  229028. // compiled on its own).
  229029. #if JUCE_INCLUDED_FILE && JUCE_OPENGL
  229030. #if JUCE_MAC
  229031. END_JUCE_NAMESPACE
  229032. #define ThreadSafeNSOpenGLView MakeObjCClassName(ThreadSafeNSOpenGLView)
  229033. @interface ThreadSafeNSOpenGLView : NSOpenGLView
  229034. {
  229035. CriticalSection* contextLock;
  229036. bool needsUpdate;
  229037. }
  229038. - (id) initWithFrame: (NSRect) frameRect pixelFormat: (NSOpenGLPixelFormat*) format;
  229039. - (bool) makeActive;
  229040. - (void) makeInactive;
  229041. - (void) reshape;
  229042. @end
  229043. @implementation ThreadSafeNSOpenGLView
  229044. - (id) initWithFrame: (NSRect) frameRect
  229045. pixelFormat: (NSOpenGLPixelFormat*) format
  229046. {
  229047. contextLock = new CriticalSection();
  229048. self = [super initWithFrame: frameRect pixelFormat: format];
  229049. if (self != nil)
  229050. [[NSNotificationCenter defaultCenter] addObserver: self
  229051. selector: @selector (_surfaceNeedsUpdate:)
  229052. name: NSViewGlobalFrameDidChangeNotification
  229053. object: self];
  229054. return self;
  229055. }
  229056. - (void) dealloc
  229057. {
  229058. [[NSNotificationCenter defaultCenter] removeObserver: self];
  229059. delete contextLock;
  229060. [super dealloc];
  229061. }
  229062. - (bool) makeActive
  229063. {
  229064. const ScopedLock sl (*contextLock);
  229065. if ([self openGLContext] == 0)
  229066. return false;
  229067. [[self openGLContext] makeCurrentContext];
  229068. if (needsUpdate)
  229069. {
  229070. [super update];
  229071. needsUpdate = false;
  229072. }
  229073. return true;
  229074. }
  229075. - (void) makeInactive
  229076. {
  229077. const ScopedLock sl (*contextLock);
  229078. [NSOpenGLContext clearCurrentContext];
  229079. }
  229080. - (void) _surfaceNeedsUpdate: (NSNotification*) notification
  229081. {
  229082. const ScopedLock sl (*contextLock);
  229083. needsUpdate = true;
  229084. }
  229085. - (void) update
  229086. {
  229087. const ScopedLock sl (*contextLock);
  229088. needsUpdate = true;
  229089. }
  229090. - (void) reshape
  229091. {
  229092. const ScopedLock sl (*contextLock);
  229093. needsUpdate = true;
  229094. }
  229095. @end
  229096. BEGIN_JUCE_NAMESPACE
  229097. class WindowedGLContext : public OpenGLContext
  229098. {
  229099. public:
  229100. WindowedGLContext (Component* const component,
  229101. const OpenGLPixelFormat& pixelFormat_,
  229102. NSOpenGLContext* sharedContext)
  229103. : renderContext (0),
  229104. pixelFormat (pixelFormat_)
  229105. {
  229106. jassert (component != 0);
  229107. NSOpenGLPixelFormatAttribute attribs [64];
  229108. int n = 0;
  229109. attribs[n++] = NSOpenGLPFADoubleBuffer;
  229110. attribs[n++] = NSOpenGLPFAAccelerated;
  229111. attribs[n++] = NSOpenGLPFAMPSafe; // NSOpenGLPFAAccelerated, NSOpenGLPFAMultiScreen, NSOpenGLPFASingleRenderer
  229112. attribs[n++] = NSOpenGLPFAColorSize;
  229113. attribs[n++] = (NSOpenGLPixelFormatAttribute) jmax (pixelFormat.redBits,
  229114. pixelFormat.greenBits,
  229115. pixelFormat.blueBits);
  229116. attribs[n++] = NSOpenGLPFAAlphaSize;
  229117. attribs[n++] = (NSOpenGLPixelFormatAttribute) pixelFormat.alphaBits;
  229118. attribs[n++] = NSOpenGLPFADepthSize;
  229119. attribs[n++] = (NSOpenGLPixelFormatAttribute) pixelFormat.depthBufferBits;
  229120. attribs[n++] = NSOpenGLPFAStencilSize;
  229121. attribs[n++] = (NSOpenGLPixelFormatAttribute) pixelFormat.stencilBufferBits;
  229122. attribs[n++] = NSOpenGLPFAAccumSize;
  229123. attribs[n++] = (NSOpenGLPixelFormatAttribute) jmax (pixelFormat.accumulationBufferRedBits,
  229124. pixelFormat.accumulationBufferGreenBits,
  229125. pixelFormat.accumulationBufferBlueBits,
  229126. pixelFormat.accumulationBufferAlphaBits);
  229127. // xxx not sure how to do fullSceneAntiAliasingNumSamples..
  229128. attribs[n++] = NSOpenGLPFASampleBuffers;
  229129. attribs[n++] = (NSOpenGLPixelFormatAttribute) 1;
  229130. attribs[n++] = NSOpenGLPFAClosestPolicy;
  229131. attribs[n++] = NSOpenGLPFANoRecovery;
  229132. attribs[n++] = (NSOpenGLPixelFormatAttribute) 0;
  229133. NSOpenGLPixelFormat* format
  229134. = [[NSOpenGLPixelFormat alloc] initWithAttributes: attribs];
  229135. view = [[ThreadSafeNSOpenGLView alloc] initWithFrame: NSMakeRect (0, 0, 100.0f, 100.0f)
  229136. pixelFormat: format];
  229137. renderContext = [[[NSOpenGLContext alloc] initWithFormat: format
  229138. shareContext: sharedContext] autorelease];
  229139. const GLint swapInterval = 1;
  229140. [renderContext setValues: &swapInterval forParameter: NSOpenGLCPSwapInterval];
  229141. [view setOpenGLContext: renderContext];
  229142. [renderContext setView: view];
  229143. [format release];
  229144. viewHolder = new NSViewComponentInternal (view, component);
  229145. }
  229146. ~WindowedGLContext()
  229147. {
  229148. makeInactive();
  229149. [renderContext clearDrawable];
  229150. viewHolder = 0;
  229151. }
  229152. bool makeActive() const throw()
  229153. {
  229154. jassert (renderContext != 0);
  229155. [view makeActive];
  229156. return isActive();
  229157. }
  229158. bool makeInactive() const throw()
  229159. {
  229160. [view makeInactive];
  229161. return true;
  229162. }
  229163. bool isActive() const throw()
  229164. {
  229165. return [NSOpenGLContext currentContext] == renderContext;
  229166. }
  229167. const OpenGLPixelFormat getPixelFormat() const { return pixelFormat; }
  229168. void* getRawContext() const throw() { return renderContext; }
  229169. void updateWindowPosition (int x, int y, int w, int h, int outerWindowHeight)
  229170. {
  229171. }
  229172. void swapBuffers()
  229173. {
  229174. [renderContext flushBuffer];
  229175. }
  229176. bool setSwapInterval (const int numFramesPerSwap)
  229177. {
  229178. [renderContext setValues: (const GLint*) &numFramesPerSwap
  229179. forParameter: NSOpenGLCPSwapInterval];
  229180. return true;
  229181. }
  229182. int getSwapInterval() const
  229183. {
  229184. GLint numFrames = 0;
  229185. [renderContext getValues: &numFrames
  229186. forParameter: NSOpenGLCPSwapInterval];
  229187. return numFrames;
  229188. }
  229189. void repaint()
  229190. {
  229191. // we need to invalidate the juce view that holds this gl view, to make it
  229192. // cause a repaint callback
  229193. NSView* v = (NSView*) viewHolder->view;
  229194. NSRect r = [v frame];
  229195. // bit of a bodge here.. if we only invalidate the area of the gl component,
  229196. // it's completely covered by the NSOpenGLView, so the OS throws away the
  229197. // repaint message, thus never causing our paint() callback, and never repainting
  229198. // the comp. So invalidating just a little bit around the edge helps..
  229199. [[v superview] setNeedsDisplayInRect: NSInsetRect (r, -2.0f, -2.0f)];
  229200. }
  229201. void* getNativeWindowHandle() const { return viewHolder->view; }
  229202. juce_UseDebuggingNewOperator
  229203. NSOpenGLContext* renderContext;
  229204. ThreadSafeNSOpenGLView* view;
  229205. private:
  229206. OpenGLPixelFormat pixelFormat;
  229207. ScopedPointer <NSViewComponentInternal> viewHolder;
  229208. WindowedGLContext (const WindowedGLContext&);
  229209. WindowedGLContext& operator= (const WindowedGLContext&);
  229210. };
  229211. OpenGLContext* OpenGLComponent::createContext()
  229212. {
  229213. ScopedPointer<WindowedGLContext> c (new WindowedGLContext (this, preferredPixelFormat,
  229214. contextToShareListsWith != 0 ? (NSOpenGLContext*) contextToShareListsWith->getRawContext() : 0));
  229215. return (c->renderContext != 0) ? c.release() : 0;
  229216. }
  229217. void* OpenGLComponent::getNativeWindowHandle() const
  229218. {
  229219. return context != 0 ? static_cast<WindowedGLContext*> (static_cast<OpenGLContext*> (context))->getNativeWindowHandle()
  229220. : 0;
  229221. }
  229222. void juce_glViewport (const int w, const int h)
  229223. {
  229224. glViewport (0, 0, w, h);
  229225. }
  229226. void OpenGLPixelFormat::getAvailablePixelFormats (Component* /*component*/,
  229227. OwnedArray <OpenGLPixelFormat>& results)
  229228. {
  229229. /* GLint attribs [64];
  229230. int n = 0;
  229231. attribs[n++] = AGL_RGBA;
  229232. attribs[n++] = AGL_DOUBLEBUFFER;
  229233. attribs[n++] = AGL_ACCELERATED;
  229234. attribs[n++] = AGL_NO_RECOVERY;
  229235. attribs[n++] = AGL_NONE;
  229236. AGLPixelFormat p = aglChoosePixelFormat (0, 0, attribs);
  229237. while (p != 0)
  229238. {
  229239. OpenGLPixelFormat* const pf = new OpenGLPixelFormat();
  229240. pf->redBits = getAGLAttribute (p, AGL_RED_SIZE);
  229241. pf->greenBits = getAGLAttribute (p, AGL_GREEN_SIZE);
  229242. pf->blueBits = getAGLAttribute (p, AGL_BLUE_SIZE);
  229243. pf->alphaBits = getAGLAttribute (p, AGL_ALPHA_SIZE);
  229244. pf->depthBufferBits = getAGLAttribute (p, AGL_DEPTH_SIZE);
  229245. pf->stencilBufferBits = getAGLAttribute (p, AGL_STENCIL_SIZE);
  229246. pf->accumulationBufferRedBits = getAGLAttribute (p, AGL_ACCUM_RED_SIZE);
  229247. pf->accumulationBufferGreenBits = getAGLAttribute (p, AGL_ACCUM_GREEN_SIZE);
  229248. pf->accumulationBufferBlueBits = getAGLAttribute (p, AGL_ACCUM_BLUE_SIZE);
  229249. pf->accumulationBufferAlphaBits = getAGLAttribute (p, AGL_ACCUM_ALPHA_SIZE);
  229250. results.add (pf);
  229251. p = aglNextPixelFormat (p);
  229252. }*/
  229253. //jassertfalse //xxx can't see how you do this in cocoa!
  229254. }
  229255. #else
  229256. END_JUCE_NAMESPACE
  229257. @interface JuceGLView : UIView
  229258. {
  229259. }
  229260. + (Class) layerClass;
  229261. @end
  229262. @implementation JuceGLView
  229263. + (Class) layerClass
  229264. {
  229265. return [CAEAGLLayer class];
  229266. }
  229267. @end
  229268. BEGIN_JUCE_NAMESPACE
  229269. class GLESContext : public OpenGLContext
  229270. {
  229271. public:
  229272. GLESContext (UIViewComponentPeer* peer,
  229273. Component* const component_,
  229274. const OpenGLPixelFormat& pixelFormat_,
  229275. const GLESContext* const sharedContext,
  229276. NSUInteger apiType)
  229277. : component (component_), pixelFormat (pixelFormat_), glLayer (0), context (0),
  229278. useDepthBuffer (pixelFormat_.depthBufferBits > 0), frameBufferHandle (0), colorBufferHandle (0),
  229279. depthBufferHandle (0), lastWidth (0), lastHeight (0)
  229280. {
  229281. view = [[JuceGLView alloc] initWithFrame: CGRectMake (0, 0, 64, 64)];
  229282. view.opaque = YES;
  229283. view.hidden = NO;
  229284. view.backgroundColor = [UIColor blackColor];
  229285. view.userInteractionEnabled = NO;
  229286. glLayer = (CAEAGLLayer*) [view layer];
  229287. [peer->view addSubview: view];
  229288. if (sharedContext != 0)
  229289. context = [[EAGLContext alloc] initWithAPI: apiType
  229290. sharegroup: [sharedContext->context sharegroup]];
  229291. else
  229292. context = [[EAGLContext alloc] initWithAPI: apiType];
  229293. createGLBuffers();
  229294. }
  229295. ~GLESContext()
  229296. {
  229297. makeInactive();
  229298. [context release];
  229299. [view removeFromSuperview];
  229300. [view release];
  229301. freeGLBuffers();
  229302. }
  229303. bool makeActive() const throw()
  229304. {
  229305. jassert (context != 0);
  229306. [EAGLContext setCurrentContext: context];
  229307. glBindFramebufferOES (GL_FRAMEBUFFER_OES, frameBufferHandle);
  229308. return true;
  229309. }
  229310. void swapBuffers()
  229311. {
  229312. glBindRenderbufferOES (GL_RENDERBUFFER_OES, colorBufferHandle);
  229313. [context presentRenderbuffer: GL_RENDERBUFFER_OES];
  229314. }
  229315. bool makeInactive() const throw()
  229316. {
  229317. return [EAGLContext setCurrentContext: nil];
  229318. }
  229319. bool isActive() const throw()
  229320. {
  229321. return [EAGLContext currentContext] == context;
  229322. }
  229323. const OpenGLPixelFormat getPixelFormat() const { return pixelFormat; }
  229324. void* getRawContext() const throw() { return glLayer; }
  229325. void updateWindowPosition (int x, int y, int w, int h, int outerWindowHeight)
  229326. {
  229327. view.frame = CGRectMake ((CGFloat) x, (CGFloat) y, (CGFloat) w, (CGFloat) h);
  229328. if (lastWidth != w || lastHeight != h)
  229329. {
  229330. lastWidth = w;
  229331. lastHeight = h;
  229332. freeGLBuffers();
  229333. createGLBuffers();
  229334. }
  229335. }
  229336. bool setSwapInterval (const int numFramesPerSwap)
  229337. {
  229338. numFrames = numFramesPerSwap;
  229339. return true;
  229340. }
  229341. int getSwapInterval() const
  229342. {
  229343. return numFrames;
  229344. }
  229345. void repaint()
  229346. {
  229347. }
  229348. void createGLBuffers()
  229349. {
  229350. makeActive();
  229351. glGenFramebuffersOES (1, &frameBufferHandle);
  229352. glGenRenderbuffersOES (1, &colorBufferHandle);
  229353. glGenRenderbuffersOES (1, &depthBufferHandle);
  229354. glBindRenderbufferOES (GL_RENDERBUFFER_OES, colorBufferHandle);
  229355. [context renderbufferStorage: GL_RENDERBUFFER_OES fromDrawable: glLayer];
  229356. GLint width, height;
  229357. glGetRenderbufferParameterivOES (GL_RENDERBUFFER_OES, GL_RENDERBUFFER_WIDTH_OES, &width);
  229358. glGetRenderbufferParameterivOES (GL_RENDERBUFFER_OES, GL_RENDERBUFFER_HEIGHT_OES, &height);
  229359. if (useDepthBuffer)
  229360. {
  229361. glBindRenderbufferOES (GL_RENDERBUFFER_OES, depthBufferHandle);
  229362. glRenderbufferStorageOES (GL_RENDERBUFFER_OES, GL_DEPTH_COMPONENT16_OES, width, height);
  229363. }
  229364. glBindRenderbufferOES (GL_RENDERBUFFER_OES, colorBufferHandle);
  229365. glBindFramebufferOES (GL_FRAMEBUFFER_OES, frameBufferHandle);
  229366. glFramebufferRenderbufferOES (GL_FRAMEBUFFER_OES, GL_COLOR_ATTACHMENT0_OES, GL_RENDERBUFFER_OES, colorBufferHandle);
  229367. if (useDepthBuffer)
  229368. glFramebufferRenderbufferOES (GL_FRAMEBUFFER_OES, GL_DEPTH_ATTACHMENT_OES, GL_RENDERBUFFER_OES, depthBufferHandle);
  229369. jassert (glCheckFramebufferStatusOES (GL_FRAMEBUFFER_OES) == GL_FRAMEBUFFER_COMPLETE_OES);
  229370. }
  229371. void freeGLBuffers()
  229372. {
  229373. if (frameBufferHandle != 0)
  229374. {
  229375. glDeleteFramebuffersOES (1, &frameBufferHandle);
  229376. frameBufferHandle = 0;
  229377. }
  229378. if (colorBufferHandle != 0)
  229379. {
  229380. glDeleteRenderbuffersOES (1, &colorBufferHandle);
  229381. colorBufferHandle = 0;
  229382. }
  229383. if (depthBufferHandle != 0)
  229384. {
  229385. glDeleteRenderbuffersOES (1, &depthBufferHandle);
  229386. depthBufferHandle = 0;
  229387. }
  229388. }
  229389. juce_UseDebuggingNewOperator
  229390. private:
  229391. Component::SafePointer<Component> component;
  229392. OpenGLPixelFormat pixelFormat;
  229393. JuceGLView* view;
  229394. CAEAGLLayer* glLayer;
  229395. EAGLContext* context;
  229396. bool useDepthBuffer;
  229397. GLuint frameBufferHandle, colorBufferHandle, depthBufferHandle;
  229398. int numFrames;
  229399. int lastWidth, lastHeight;
  229400. GLESContext (const GLESContext&);
  229401. GLESContext& operator= (const GLESContext&);
  229402. };
  229403. OpenGLContext* OpenGLComponent::createContext()
  229404. {
  229405. ScopedAutoReleasePool pool;
  229406. UIViewComponentPeer* peer = dynamic_cast <UIViewComponentPeer*> (getPeer());
  229407. if (peer != 0)
  229408. return new GLESContext (peer, this, preferredPixelFormat,
  229409. dynamic_cast <const GLESContext*> (contextToShareListsWith),
  229410. type == openGLES2 ? kEAGLRenderingAPIOpenGLES2 : kEAGLRenderingAPIOpenGLES1);
  229411. return 0;
  229412. }
  229413. void OpenGLPixelFormat::getAvailablePixelFormats (Component* /*component*/,
  229414. OwnedArray <OpenGLPixelFormat>& /*results*/)
  229415. {
  229416. }
  229417. void juce_glViewport (const int w, const int h)
  229418. {
  229419. glViewport (0, 0, w, h);
  229420. }
  229421. #endif
  229422. #endif
  229423. /*** End of inlined file: juce_mac_OpenGLComponent.mm ***/
  229424. /*** Start of inlined file: juce_mac_MainMenu.mm ***/
  229425. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  229426. // compiled on its own).
  229427. #if JUCE_INCLUDED_FILE
  229428. class JuceMainMenuHandler;
  229429. END_JUCE_NAMESPACE
  229430. using namespace JUCE_NAMESPACE;
  229431. #define JuceMenuCallback MakeObjCClassName(JuceMenuCallback)
  229432. #if defined (MAC_OS_X_VERSION_10_6) && MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_6
  229433. @interface JuceMenuCallback : NSObject <NSMenuDelegate>
  229434. #else
  229435. @interface JuceMenuCallback : NSObject
  229436. #endif
  229437. {
  229438. JuceMainMenuHandler* owner;
  229439. }
  229440. - (JuceMenuCallback*) initWithOwner: (JuceMainMenuHandler*) owner_;
  229441. - (void) dealloc;
  229442. - (void) menuItemInvoked: (id) menu;
  229443. - (void) menuNeedsUpdate: (NSMenu*) menu;
  229444. @end
  229445. BEGIN_JUCE_NAMESPACE
  229446. class JuceMainMenuHandler : private MenuBarModelListener,
  229447. private DeletedAtShutdown
  229448. {
  229449. public:
  229450. static JuceMainMenuHandler* instance;
  229451. JuceMainMenuHandler()
  229452. : currentModel (0),
  229453. lastUpdateTime (0)
  229454. {
  229455. callback = [[JuceMenuCallback alloc] initWithOwner: this];
  229456. }
  229457. ~JuceMainMenuHandler()
  229458. {
  229459. setMenu (0);
  229460. jassert (instance == this);
  229461. instance = 0;
  229462. [callback release];
  229463. }
  229464. void setMenu (MenuBarModel* const newMenuBarModel)
  229465. {
  229466. if (currentModel != newMenuBarModel)
  229467. {
  229468. if (currentModel != 0)
  229469. currentModel->removeListener (this);
  229470. currentModel = newMenuBarModel;
  229471. if (currentModel != 0)
  229472. currentModel->addListener (this);
  229473. menuBarItemsChanged (0);
  229474. }
  229475. }
  229476. void addSubMenu (NSMenu* parent, const PopupMenu& child,
  229477. const String& name, const int menuId, const int tag)
  229478. {
  229479. NSMenuItem* item = [parent addItemWithTitle: juceStringToNS (name)
  229480. action: nil
  229481. keyEquivalent: @""];
  229482. [item setTag: tag];
  229483. NSMenu* sub = createMenu (child, name, menuId, tag);
  229484. [parent setSubmenu: sub forItem: item];
  229485. [sub setAutoenablesItems: false];
  229486. [sub release];
  229487. }
  229488. void updateSubMenu (NSMenuItem* parentItem, const PopupMenu& menuToCopy,
  229489. const String& name, const int menuId, const int tag)
  229490. {
  229491. [parentItem setTag: tag];
  229492. NSMenu* menu = [parentItem submenu];
  229493. [menu setTitle: juceStringToNS (name)];
  229494. while ([menu numberOfItems] > 0)
  229495. [menu removeItemAtIndex: 0];
  229496. PopupMenu::MenuItemIterator iter (menuToCopy);
  229497. while (iter.next())
  229498. addMenuItem (iter, menu, menuId, tag);
  229499. [menu setAutoenablesItems: false];
  229500. [menu update];
  229501. }
  229502. void menuBarItemsChanged (MenuBarModel*)
  229503. {
  229504. lastUpdateTime = Time::getMillisecondCounter();
  229505. StringArray menuNames;
  229506. if (currentModel != 0)
  229507. menuNames = currentModel->getMenuBarNames();
  229508. NSMenu* menuBar = [NSApp mainMenu];
  229509. while ([menuBar numberOfItems] > 1 + menuNames.size())
  229510. [menuBar removeItemAtIndex: [menuBar numberOfItems] - 1];
  229511. int menuId = 1;
  229512. for (int i = 0; i < menuNames.size(); ++i)
  229513. {
  229514. const PopupMenu menu (currentModel->getMenuForIndex (i, menuNames [i]));
  229515. if (i >= [menuBar numberOfItems] - 1)
  229516. addSubMenu (menuBar, menu, menuNames[i], menuId, i);
  229517. else
  229518. updateSubMenu ([menuBar itemAtIndex: 1 + i], menu, menuNames[i], menuId, i);
  229519. }
  229520. }
  229521. static void flashMenuBar (NSMenu* menu)
  229522. {
  229523. if ([[menu title] isEqualToString: @"Apple"])
  229524. return;
  229525. [menu retain];
  229526. const unichar f35Key = NSF35FunctionKey;
  229527. NSString* f35String = [NSString stringWithCharacters: &f35Key length: 1];
  229528. NSMenuItem* item = [[NSMenuItem alloc] initWithTitle: @"x"
  229529. action: nil
  229530. keyEquivalent: f35String];
  229531. [item setTarget: nil];
  229532. [menu insertItem: item atIndex: [menu numberOfItems]];
  229533. [item release];
  229534. if ([menu indexOfItem: item] >= 0)
  229535. {
  229536. NSEvent* f35Event = [NSEvent keyEventWithType: NSKeyDown
  229537. location: NSZeroPoint
  229538. modifierFlags: NSCommandKeyMask
  229539. timestamp: 0
  229540. windowNumber: 0
  229541. context: [NSGraphicsContext currentContext]
  229542. characters: f35String
  229543. charactersIgnoringModifiers: f35String
  229544. isARepeat: NO
  229545. keyCode: 0];
  229546. [menu performKeyEquivalent: f35Event];
  229547. if ([menu indexOfItem: item] >= 0)
  229548. [menu removeItem: item]; // (this throws if the item isn't actually in the menu)
  229549. }
  229550. [menu release];
  229551. }
  229552. static NSMenuItem* findMenuItem (NSMenu* const menu, const ApplicationCommandTarget::InvocationInfo& info)
  229553. {
  229554. for (NSInteger i = [menu numberOfItems]; --i >= 0;)
  229555. {
  229556. NSMenuItem* m = [menu itemAtIndex: i];
  229557. if ([m tag] == info.commandID)
  229558. return m;
  229559. if ([m submenu] != 0)
  229560. {
  229561. NSMenuItem* found = findMenuItem ([m submenu], info);
  229562. if (found != 0)
  229563. return found;
  229564. }
  229565. }
  229566. return 0;
  229567. }
  229568. void menuCommandInvoked (MenuBarModel*, const ApplicationCommandTarget::InvocationInfo& info)
  229569. {
  229570. NSMenuItem* item = findMenuItem ([NSApp mainMenu], info);
  229571. if (item != 0)
  229572. flashMenuBar ([item menu]);
  229573. }
  229574. void updateMenus()
  229575. {
  229576. if (Time::getMillisecondCounter() > lastUpdateTime + 500)
  229577. menuBarItemsChanged (0);
  229578. }
  229579. void invoke (const int commandId, ApplicationCommandManager* const commandManager, const int topLevelIndex) const
  229580. {
  229581. if (currentModel != 0)
  229582. {
  229583. if (commandManager != 0)
  229584. {
  229585. ApplicationCommandTarget::InvocationInfo info (commandId);
  229586. info.invocationMethod = ApplicationCommandTarget::InvocationInfo::fromMenu;
  229587. commandManager->invoke (info, true);
  229588. }
  229589. currentModel->menuItemSelected (commandId, topLevelIndex);
  229590. }
  229591. }
  229592. MenuBarModel* currentModel;
  229593. uint32 lastUpdateTime;
  229594. void addMenuItem (PopupMenu::MenuItemIterator& iter, NSMenu* menuToAddTo,
  229595. const int topLevelMenuId, const int topLevelIndex)
  229596. {
  229597. NSString* text = juceStringToNS (iter.itemName.upToFirstOccurrenceOf ("<end>", false, true));
  229598. if (text == 0)
  229599. text = @"";
  229600. if (iter.isSeparator)
  229601. {
  229602. [menuToAddTo addItem: [NSMenuItem separatorItem]];
  229603. }
  229604. else if (iter.isSectionHeader)
  229605. {
  229606. NSMenuItem* item = [menuToAddTo addItemWithTitle: text
  229607. action: nil
  229608. keyEquivalent: @""];
  229609. [item setEnabled: false];
  229610. }
  229611. else if (iter.subMenu != 0)
  229612. {
  229613. NSMenuItem* item = [menuToAddTo addItemWithTitle: text
  229614. action: nil
  229615. keyEquivalent: @""];
  229616. [item setTag: iter.itemId];
  229617. [item setEnabled: iter.isEnabled];
  229618. NSMenu* sub = createMenu (*iter.subMenu, iter.itemName, topLevelMenuId, topLevelIndex);
  229619. [sub setDelegate: nil];
  229620. [menuToAddTo setSubmenu: sub forItem: item];
  229621. [sub release];
  229622. }
  229623. else
  229624. {
  229625. NSMenuItem* item = [menuToAddTo addItemWithTitle: text
  229626. action: @selector (menuItemInvoked:)
  229627. keyEquivalent: @""];
  229628. [item setTag: iter.itemId];
  229629. [item setEnabled: iter.isEnabled];
  229630. [item setState: iter.isTicked ? NSOnState : NSOffState];
  229631. [item setTarget: (id) callback];
  229632. NSMutableArray* info = [NSMutableArray arrayWithObject: [NSNumber numberWithUnsignedLongLong: (pointer_sized_int) (void*) iter.commandManager]];
  229633. [info addObject: [NSNumber numberWithInt: topLevelIndex]];
  229634. [item setRepresentedObject: info];
  229635. if (iter.commandManager != 0)
  229636. {
  229637. const Array <KeyPress> keyPresses (iter.commandManager->getKeyMappings()
  229638. ->getKeyPressesAssignedToCommand (iter.itemId));
  229639. if (keyPresses.size() > 0)
  229640. {
  229641. const KeyPress& kp = keyPresses.getReference(0);
  229642. if (kp.getKeyCode() != KeyPress::backspaceKey
  229643. && kp.getKeyCode() != KeyPress::deleteKey) // (adding these is annoying because it flashes the menu bar
  229644. // every time you press the key while editing text)
  229645. {
  229646. juce_wchar key = kp.getTextCharacter();
  229647. if (kp.getKeyCode() == KeyPress::backspaceKey)
  229648. key = NSBackspaceCharacter;
  229649. else if (kp.getKeyCode() == KeyPress::deleteKey)
  229650. key = NSDeleteCharacter;
  229651. else if (key == 0)
  229652. key = (juce_wchar) kp.getKeyCode();
  229653. unsigned int mods = 0;
  229654. if (kp.getModifiers().isShiftDown())
  229655. mods |= NSShiftKeyMask;
  229656. if (kp.getModifiers().isCtrlDown())
  229657. mods |= NSControlKeyMask;
  229658. if (kp.getModifiers().isAltDown())
  229659. mods |= NSAlternateKeyMask;
  229660. if (kp.getModifiers().isCommandDown())
  229661. mods |= NSCommandKeyMask;
  229662. [item setKeyEquivalent: juceStringToNS (String::charToString (key))];
  229663. [item setKeyEquivalentModifierMask: mods];
  229664. }
  229665. }
  229666. }
  229667. }
  229668. }
  229669. JuceMenuCallback* callback;
  229670. private:
  229671. NSMenu* createMenu (const PopupMenu menu,
  229672. const String& menuName,
  229673. const int topLevelMenuId,
  229674. const int topLevelIndex)
  229675. {
  229676. NSMenu* m = [[NSMenu alloc] initWithTitle: juceStringToNS (menuName)];
  229677. [m setAutoenablesItems: false];
  229678. [m setDelegate: callback];
  229679. PopupMenu::MenuItemIterator iter (menu);
  229680. while (iter.next())
  229681. addMenuItem (iter, m, topLevelMenuId, topLevelIndex);
  229682. [m update];
  229683. return m;
  229684. }
  229685. };
  229686. JuceMainMenuHandler* JuceMainMenuHandler::instance = 0;
  229687. END_JUCE_NAMESPACE
  229688. @implementation JuceMenuCallback
  229689. - (JuceMenuCallback*) initWithOwner: (JuceMainMenuHandler*) owner_
  229690. {
  229691. [super init];
  229692. owner = owner_;
  229693. return self;
  229694. }
  229695. - (void) dealloc
  229696. {
  229697. [super dealloc];
  229698. }
  229699. - (void) menuItemInvoked: (id) menu
  229700. {
  229701. NSMenuItem* item = (NSMenuItem*) menu;
  229702. if ([[item representedObject] isKindOfClass: [NSArray class]])
  229703. {
  229704. // If the menu is being triggered by a keypress, the OS will have picked it up before we had a chance to offer it to
  229705. // our own components, which may have wanted to intercept it. So, rather than dispatching directly, we'll feed it back
  229706. // into the focused component and let it trigger the menu item indirectly.
  229707. NSEvent* e = [NSApp currentEvent];
  229708. if ([e type] == NSKeyDown || [e type] == NSKeyUp)
  229709. {
  229710. if (JUCE_NAMESPACE::Component::getCurrentlyFocusedComponent() != 0)
  229711. {
  229712. JUCE_NAMESPACE::NSViewComponentPeer* peer = dynamic_cast <JUCE_NAMESPACE::NSViewComponentPeer*> (JUCE_NAMESPACE::Component::getCurrentlyFocusedComponent()->getPeer());
  229713. if (peer != 0)
  229714. {
  229715. if ([e type] == NSKeyDown)
  229716. peer->redirectKeyDown (e);
  229717. else
  229718. peer->redirectKeyUp (e);
  229719. return;
  229720. }
  229721. }
  229722. }
  229723. NSArray* info = (NSArray*) [item representedObject];
  229724. owner->invoke ((int) [item tag],
  229725. (ApplicationCommandManager*) (pointer_sized_int)
  229726. [((NSNumber*) [info objectAtIndex: 0]) unsignedLongLongValue],
  229727. (int) [((NSNumber*) [info objectAtIndex: 1]) intValue]);
  229728. }
  229729. }
  229730. - (void) menuNeedsUpdate: (NSMenu*) menu;
  229731. {
  229732. (void) menu;
  229733. if (JuceMainMenuHandler::instance != 0)
  229734. JuceMainMenuHandler::instance->updateMenus();
  229735. }
  229736. @end
  229737. BEGIN_JUCE_NAMESPACE
  229738. static NSMenu* createStandardAppMenu (NSMenu* menu, const String& appName,
  229739. const PopupMenu* extraItems)
  229740. {
  229741. if (extraItems != 0 && JuceMainMenuHandler::instance != 0 && extraItems->getNumItems() > 0)
  229742. {
  229743. PopupMenu::MenuItemIterator iter (*extraItems);
  229744. while (iter.next())
  229745. JuceMainMenuHandler::instance->addMenuItem (iter, menu, 0, -1);
  229746. [menu addItem: [NSMenuItem separatorItem]];
  229747. }
  229748. NSMenuItem* item;
  229749. // Services...
  229750. item = [[NSMenuItem alloc] initWithTitle: NSLocalizedString (@"Services", nil)
  229751. action: nil keyEquivalent: @""];
  229752. [menu addItem: item];
  229753. [item release];
  229754. NSMenu* servicesMenu = [[NSMenu alloc] initWithTitle: @"Services"];
  229755. [menu setSubmenu: servicesMenu forItem: item];
  229756. [NSApp setServicesMenu: servicesMenu];
  229757. [servicesMenu release];
  229758. [menu addItem: [NSMenuItem separatorItem]];
  229759. // Hide + Show stuff...
  229760. item = [[NSMenuItem alloc] initWithTitle: juceStringToNS ("Hide " + appName)
  229761. action: @selector (hide:) keyEquivalent: @"h"];
  229762. [item setTarget: NSApp];
  229763. [menu addItem: item];
  229764. [item release];
  229765. item = [[NSMenuItem alloc] initWithTitle: NSLocalizedString (@"Hide Others", nil)
  229766. action: @selector (hideOtherApplications:) keyEquivalent: @"h"];
  229767. [item setKeyEquivalentModifierMask: NSCommandKeyMask | NSAlternateKeyMask];
  229768. [item setTarget: NSApp];
  229769. [menu addItem: item];
  229770. [item release];
  229771. item = [[NSMenuItem alloc] initWithTitle: NSLocalizedString (@"Show All", nil)
  229772. action: @selector (unhideAllApplications:) keyEquivalent: @""];
  229773. [item setTarget: NSApp];
  229774. [menu addItem: item];
  229775. [item release];
  229776. [menu addItem: [NSMenuItem separatorItem]];
  229777. // Quit item....
  229778. item = [[NSMenuItem alloc] initWithTitle: juceStringToNS ("Quit " + appName)
  229779. action: @selector (terminate:) keyEquivalent: @"q"];
  229780. [item setTarget: NSApp];
  229781. [menu addItem: item];
  229782. [item release];
  229783. return menu;
  229784. }
  229785. // Since our app has no NIB, this initialises a standard app menu...
  229786. static void rebuildMainMenu (const PopupMenu* extraItems)
  229787. {
  229788. // this can't be used in a plugin!
  229789. jassert (JUCEApplication::getInstance() != 0);
  229790. if (JUCEApplication::getInstance() != 0)
  229791. {
  229792. const ScopedAutoReleasePool pool;
  229793. NSMenu* mainMenu = [[NSMenu alloc] initWithTitle: @"MainMenu"];
  229794. NSMenuItem* item = [mainMenu addItemWithTitle: @"Apple" action: nil keyEquivalent: @""];
  229795. NSMenu* appMenu = [[NSMenu alloc] initWithTitle: @"Apple"];
  229796. [NSApp performSelector: @selector (setAppleMenu:) withObject: appMenu];
  229797. [mainMenu setSubmenu: appMenu forItem: item];
  229798. [NSApp setMainMenu: mainMenu];
  229799. createStandardAppMenu (appMenu, JUCEApplication::getInstance()->getApplicationName(), extraItems);
  229800. [appMenu release];
  229801. [mainMenu release];
  229802. }
  229803. }
  229804. void MenuBarModel::setMacMainMenu (MenuBarModel* newMenuBarModel,
  229805. const PopupMenu* extraAppleMenuItems)
  229806. {
  229807. if (getMacMainMenu() != newMenuBarModel)
  229808. {
  229809. const ScopedAutoReleasePool pool;
  229810. if (newMenuBarModel == 0)
  229811. {
  229812. delete JuceMainMenuHandler::instance;
  229813. jassert (JuceMainMenuHandler::instance == 0); // should be zeroed in the destructor
  229814. jassert (extraAppleMenuItems == 0); // you can't specify some extra items without also supplying a model
  229815. extraAppleMenuItems = 0;
  229816. }
  229817. else
  229818. {
  229819. if (JuceMainMenuHandler::instance == 0)
  229820. JuceMainMenuHandler::instance = new JuceMainMenuHandler();
  229821. JuceMainMenuHandler::instance->setMenu (newMenuBarModel);
  229822. }
  229823. }
  229824. rebuildMainMenu (extraAppleMenuItems);
  229825. if (newMenuBarModel != 0)
  229826. newMenuBarModel->menuItemsChanged();
  229827. }
  229828. MenuBarModel* MenuBarModel::getMacMainMenu()
  229829. {
  229830. return JuceMainMenuHandler::instance != 0
  229831. ? JuceMainMenuHandler::instance->currentModel : 0;
  229832. }
  229833. void initialiseMainMenu()
  229834. {
  229835. if (JUCEApplication::getInstance() != 0) // only needed in an app
  229836. rebuildMainMenu (0);
  229837. }
  229838. #endif
  229839. /*** End of inlined file: juce_mac_MainMenu.mm ***/
  229840. /*** Start of inlined file: juce_mac_FileChooser.mm ***/
  229841. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  229842. // compiled on its own).
  229843. #if JUCE_INCLUDED_FILE
  229844. #if JUCE_MAC
  229845. END_JUCE_NAMESPACE
  229846. using namespace JUCE_NAMESPACE;
  229847. #define JuceFileChooserDelegate MakeObjCClassName(JuceFileChooserDelegate)
  229848. #if defined (MAC_OS_X_VERSION_10_6) && MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_6
  229849. @interface JuceFileChooserDelegate : NSObject <NSOpenSavePanelDelegate>
  229850. #else
  229851. @interface JuceFileChooserDelegate : NSObject
  229852. #endif
  229853. {
  229854. StringArray* filters;
  229855. }
  229856. - (JuceFileChooserDelegate*) initWithFilters: (StringArray*) filters_;
  229857. - (void) dealloc;
  229858. - (BOOL) panel: (id) sender shouldShowFilename: (NSString*) filename;
  229859. @end
  229860. @implementation JuceFileChooserDelegate
  229861. - (JuceFileChooserDelegate*) initWithFilters: (StringArray*) filters_
  229862. {
  229863. [super init];
  229864. filters = filters_;
  229865. return self;
  229866. }
  229867. - (void) dealloc
  229868. {
  229869. delete filters;
  229870. [super dealloc];
  229871. }
  229872. - (BOOL) panel: (id) sender shouldShowFilename: (NSString*) filename
  229873. {
  229874. (void) sender;
  229875. const File f (nsStringToJuce (filename));
  229876. for (int i = filters->size(); --i >= 0;)
  229877. if (f.getFileName().matchesWildcard ((*filters)[i], true))
  229878. return true;
  229879. return f.isDirectory();
  229880. }
  229881. @end
  229882. BEGIN_JUCE_NAMESPACE
  229883. void FileChooser::showPlatformDialog (Array<File>& results,
  229884. const String& title,
  229885. const File& currentFileOrDirectory,
  229886. const String& filter,
  229887. bool selectsDirectory,
  229888. bool selectsFiles,
  229889. bool isSaveDialogue,
  229890. bool warnAboutOverwritingExistingFiles,
  229891. bool selectMultipleFiles,
  229892. FilePreviewComponent* extraInfoComponent)
  229893. {
  229894. const ScopedAutoReleasePool pool;
  229895. StringArray* filters = new StringArray();
  229896. filters->addTokens (filter.replaceCharacters (",:", ";;"), ";", String::empty);
  229897. filters->trim();
  229898. filters->removeEmptyStrings();
  229899. JuceFileChooserDelegate* delegate = [[JuceFileChooserDelegate alloc] initWithFilters: filters];
  229900. [delegate autorelease];
  229901. NSSavePanel* panel = isSaveDialogue ? [NSSavePanel savePanel]
  229902. : [NSOpenPanel openPanel];
  229903. [panel setTitle: juceStringToNS (title)];
  229904. if (! isSaveDialogue)
  229905. {
  229906. NSOpenPanel* openPanel = (NSOpenPanel*) panel;
  229907. [openPanel setCanChooseDirectories: selectsDirectory];
  229908. [openPanel setCanChooseFiles: selectsFiles];
  229909. [openPanel setAllowsMultipleSelection: selectMultipleFiles];
  229910. }
  229911. [panel setDelegate: delegate];
  229912. if (isSaveDialogue || selectsDirectory)
  229913. [panel setCanCreateDirectories: YES];
  229914. String directory, filename;
  229915. if (currentFileOrDirectory.isDirectory())
  229916. {
  229917. directory = currentFileOrDirectory.getFullPathName();
  229918. }
  229919. else
  229920. {
  229921. directory = currentFileOrDirectory.getParentDirectory().getFullPathName();
  229922. filename = currentFileOrDirectory.getFileName();
  229923. }
  229924. if ([panel runModalForDirectory: juceStringToNS (directory)
  229925. file: juceStringToNS (filename)]
  229926. == NSOKButton)
  229927. {
  229928. if (isSaveDialogue)
  229929. {
  229930. results.add (File (nsStringToJuce ([panel filename])));
  229931. }
  229932. else
  229933. {
  229934. NSOpenPanel* openPanel = (NSOpenPanel*) panel;
  229935. NSArray* urls = [openPanel filenames];
  229936. for (unsigned int i = 0; i < [urls count]; ++i)
  229937. {
  229938. NSString* f = [urls objectAtIndex: i];
  229939. results.add (File (nsStringToJuce (f)));
  229940. }
  229941. }
  229942. }
  229943. [panel setDelegate: nil];
  229944. }
  229945. #else
  229946. void FileChooser::showPlatformDialog (Array<File>& results,
  229947. const String& title,
  229948. const File& currentFileOrDirectory,
  229949. const String& filter,
  229950. bool selectsDirectory,
  229951. bool selectsFiles,
  229952. bool isSaveDialogue,
  229953. bool warnAboutOverwritingExistingFiles,
  229954. bool selectMultipleFiles,
  229955. FilePreviewComponent* extraInfoComponent)
  229956. {
  229957. const ScopedAutoReleasePool pool;
  229958. jassertfalse //xxx to do
  229959. }
  229960. #endif
  229961. #endif
  229962. /*** End of inlined file: juce_mac_FileChooser.mm ***/
  229963. /*** Start of inlined file: juce_mac_QuickTimeMovieComponent.mm ***/
  229964. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  229965. // compiled on its own).
  229966. #if JUCE_INCLUDED_FILE && JUCE_QUICKTIME
  229967. END_JUCE_NAMESPACE
  229968. #define NonInterceptingQTMovieView MakeObjCClassName(NonInterceptingQTMovieView)
  229969. @interface NonInterceptingQTMovieView : QTMovieView
  229970. {
  229971. }
  229972. - (id) initWithFrame: (NSRect) frame;
  229973. - (BOOL) acceptsFirstMouse: (NSEvent*) theEvent;
  229974. - (NSView*) hitTest: (NSPoint) p;
  229975. @end
  229976. @implementation NonInterceptingQTMovieView
  229977. - (id) initWithFrame: (NSRect) frame
  229978. {
  229979. self = [super initWithFrame: frame];
  229980. [self setNextResponder: [self superview]];
  229981. return self;
  229982. }
  229983. - (void) dealloc
  229984. {
  229985. [super dealloc];
  229986. }
  229987. - (NSView*) hitTest: (NSPoint) point
  229988. {
  229989. return [self isControllerVisible] ? [super hitTest: point] : nil;
  229990. }
  229991. - (BOOL) acceptsFirstMouse: (NSEvent*) theEvent
  229992. {
  229993. return YES;
  229994. }
  229995. @end
  229996. BEGIN_JUCE_NAMESPACE
  229997. #define theMovie (static_cast <QTMovie*> (movie))
  229998. QuickTimeMovieComponent::QuickTimeMovieComponent()
  229999. : movie (0)
  230000. {
  230001. setOpaque (true);
  230002. setVisible (true);
  230003. QTMovieView* view = [[NonInterceptingQTMovieView alloc] initWithFrame: NSMakeRect (0, 0, 100.0f, 100.0f)];
  230004. setView (view);
  230005. [view release];
  230006. }
  230007. QuickTimeMovieComponent::~QuickTimeMovieComponent()
  230008. {
  230009. closeMovie();
  230010. setView (0);
  230011. }
  230012. bool QuickTimeMovieComponent::isQuickTimeAvailable() throw()
  230013. {
  230014. return true;
  230015. }
  230016. static QTMovie* openMovieFromStream (InputStream* movieStream, File& movieFile)
  230017. {
  230018. // unfortunately, QTMovie objects can only be created on the main thread..
  230019. jassert (MessageManager::getInstance()->isThisTheMessageThread());
  230020. QTMovie* movie = 0;
  230021. FileInputStream* const fin = dynamic_cast <FileInputStream*> (movieStream);
  230022. if (fin != 0)
  230023. {
  230024. movieFile = fin->getFile();
  230025. movie = [QTMovie movieWithFile: juceStringToNS (movieFile.getFullPathName())
  230026. error: nil];
  230027. }
  230028. else
  230029. {
  230030. MemoryBlock temp;
  230031. movieStream->readIntoMemoryBlock (temp);
  230032. const char* const suffixesToTry[] = { ".mov", ".mp3", ".avi", ".m4a" };
  230033. for (int i = 0; i < numElementsInArray (suffixesToTry); ++i)
  230034. {
  230035. movie = [QTMovie movieWithDataReference: [QTDataReference dataReferenceWithReferenceToData: [NSData dataWithBytes: temp.getData()
  230036. length: temp.getSize()]
  230037. name: [NSString stringWithUTF8String: suffixesToTry[i]]
  230038. MIMEType: @""]
  230039. error: nil];
  230040. if (movie != 0)
  230041. break;
  230042. }
  230043. }
  230044. return movie;
  230045. }
  230046. bool QuickTimeMovieComponent::loadMovie (const File& movieFile_,
  230047. const bool isControllerVisible_)
  230048. {
  230049. return loadMovie ((InputStream*) movieFile_.createInputStream(), isControllerVisible_);
  230050. }
  230051. bool QuickTimeMovieComponent::loadMovie (InputStream* movieStream,
  230052. const bool controllerVisible_)
  230053. {
  230054. closeMovie();
  230055. if (getPeer() == 0)
  230056. {
  230057. // To open a movie, this component must be visible inside a functioning window, so that
  230058. // the QT control can be assigned to the window.
  230059. jassertfalse
  230060. return false;
  230061. }
  230062. movie = openMovieFromStream (movieStream, movieFile);
  230063. [theMovie retain];
  230064. QTMovieView* view = (QTMovieView*) getView();
  230065. [view setMovie: theMovie];
  230066. [view setControllerVisible: controllerVisible_];
  230067. setLooping (looping);
  230068. return movie != nil;
  230069. }
  230070. bool QuickTimeMovieComponent::loadMovie (const URL& movieURL,
  230071. const bool isControllerVisible_)
  230072. {
  230073. // unfortunately, QTMovie objects can only be created on the main thread..
  230074. jassert (MessageManager::getInstance()->isThisTheMessageThread());
  230075. closeMovie();
  230076. if (getPeer() == 0)
  230077. {
  230078. // To open a movie, this component must be visible inside a functioning window, so that
  230079. // the QT control can be assigned to the window.
  230080. jassertfalse
  230081. return false;
  230082. }
  230083. NSURL* url = [NSURL URLWithString: juceStringToNS (movieURL.toString (true))];
  230084. NSError* err;
  230085. if ([QTMovie canInitWithURL: url])
  230086. movie = [QTMovie movieWithURL: url error: &err];
  230087. [theMovie retain];
  230088. QTMovieView* view = (QTMovieView*) getView();
  230089. [view setMovie: theMovie];
  230090. [view setControllerVisible: controllerVisible];
  230091. setLooping (looping);
  230092. return movie != nil;
  230093. }
  230094. void QuickTimeMovieComponent::closeMovie()
  230095. {
  230096. stop();
  230097. QTMovieView* view = (QTMovieView*) getView();
  230098. [view setMovie: nil];
  230099. [theMovie release];
  230100. movie = 0;
  230101. movieFile = File::nonexistent;
  230102. }
  230103. bool QuickTimeMovieComponent::isMovieOpen() const
  230104. {
  230105. return movie != nil;
  230106. }
  230107. const File QuickTimeMovieComponent::getCurrentMovieFile() const
  230108. {
  230109. return movieFile;
  230110. }
  230111. void QuickTimeMovieComponent::play()
  230112. {
  230113. [theMovie play];
  230114. }
  230115. void QuickTimeMovieComponent::stop()
  230116. {
  230117. [theMovie stop];
  230118. }
  230119. bool QuickTimeMovieComponent::isPlaying() const
  230120. {
  230121. return movie != 0 && [theMovie rate] != 0;
  230122. }
  230123. void QuickTimeMovieComponent::setPosition (const double seconds)
  230124. {
  230125. if (movie != 0)
  230126. {
  230127. QTTime t;
  230128. t.timeValue = (uint64) (100000.0 * seconds);
  230129. t.timeScale = 100000;
  230130. t.flags = 0;
  230131. [theMovie setCurrentTime: t];
  230132. }
  230133. }
  230134. double QuickTimeMovieComponent::getPosition() const
  230135. {
  230136. if (movie == 0)
  230137. return 0.0;
  230138. QTTime t = [theMovie currentTime];
  230139. return t.timeValue / (double) t.timeScale;
  230140. }
  230141. void QuickTimeMovieComponent::setSpeed (const float newSpeed)
  230142. {
  230143. [theMovie setRate: newSpeed];
  230144. }
  230145. double QuickTimeMovieComponent::getMovieDuration() const
  230146. {
  230147. if (movie == 0)
  230148. return 0.0;
  230149. QTTime t = [theMovie duration];
  230150. return t.timeValue / (double) t.timeScale;
  230151. }
  230152. void QuickTimeMovieComponent::setLooping (const bool shouldLoop)
  230153. {
  230154. looping = shouldLoop;
  230155. [theMovie setAttribute: [NSNumber numberWithBool: shouldLoop]
  230156. forKey: QTMovieLoopsAttribute];
  230157. }
  230158. bool QuickTimeMovieComponent::isLooping() const
  230159. {
  230160. return looping;
  230161. }
  230162. void QuickTimeMovieComponent::setMovieVolume (const float newVolume)
  230163. {
  230164. [theMovie setVolume: newVolume];
  230165. }
  230166. float QuickTimeMovieComponent::getMovieVolume() const
  230167. {
  230168. return movie != 0 ? [theMovie volume] : 0.0f;
  230169. }
  230170. void QuickTimeMovieComponent::getMovieNormalSize (int& width, int& height) const
  230171. {
  230172. width = 0;
  230173. height = 0;
  230174. if (movie != 0)
  230175. {
  230176. NSSize s = [[theMovie attributeForKey: QTMovieNaturalSizeAttribute] sizeValue];
  230177. width = (int) s.width;
  230178. height = (int) s.height;
  230179. }
  230180. }
  230181. void QuickTimeMovieComponent::paint (Graphics& g)
  230182. {
  230183. if (movie == 0)
  230184. g.fillAll (Colours::black);
  230185. }
  230186. bool QuickTimeMovieComponent::isControllerVisible() const
  230187. {
  230188. return controllerVisible;
  230189. }
  230190. void QuickTimeMovieComponent::goToStart()
  230191. {
  230192. setPosition (0.0);
  230193. }
  230194. void QuickTimeMovieComponent::setBoundsWithCorrectAspectRatio (const Rectangle<int>& spaceToFitWithin,
  230195. const RectanglePlacement& placement)
  230196. {
  230197. int normalWidth, normalHeight;
  230198. getMovieNormalSize (normalWidth, normalHeight);
  230199. if (normalWidth > 0 && normalHeight > 0 && ! spaceToFitWithin.isEmpty())
  230200. {
  230201. double x = 0.0, y = 0.0, w = normalWidth, h = normalHeight;
  230202. placement.applyTo (x, y, w, h,
  230203. spaceToFitWithin.getX(), spaceToFitWithin.getY(),
  230204. spaceToFitWithin.getWidth(), spaceToFitWithin.getHeight());
  230205. if (w > 0 && h > 0)
  230206. {
  230207. setBounds (roundToInt (x), roundToInt (y),
  230208. roundToInt (w), roundToInt (h));
  230209. }
  230210. }
  230211. else
  230212. {
  230213. setBounds (spaceToFitWithin);
  230214. }
  230215. }
  230216. #if ! (JUCE_MAC && JUCE_64BIT)
  230217. bool juce_OpenQuickTimeMovieFromStream (InputStream* movieStream, Movie& result, Handle& dataHandle)
  230218. {
  230219. if (movieStream == 0)
  230220. return false;
  230221. File file;
  230222. QTMovie* movie = openMovieFromStream (movieStream, file);
  230223. if (movie != nil)
  230224. result = [movie quickTimeMovie];
  230225. return movie != nil;
  230226. }
  230227. #endif
  230228. #endif
  230229. /*** End of inlined file: juce_mac_QuickTimeMovieComponent.mm ***/
  230230. /*** Start of inlined file: juce_mac_AudioCDBurner.mm ***/
  230231. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  230232. // compiled on its own).
  230233. #if JUCE_INCLUDED_FILE && JUCE_USE_CDBURNER
  230234. const int kilobytesPerSecond1x = 176;
  230235. END_JUCE_NAMESPACE
  230236. #define OpenDiskDevice MakeObjCClassName(OpenDiskDevice)
  230237. @interface OpenDiskDevice : NSObject
  230238. {
  230239. @public
  230240. DRDevice* device;
  230241. NSMutableArray* tracks;
  230242. bool underrunProtection;
  230243. }
  230244. - (OpenDiskDevice*) initWithDRDevice: (DRDevice*) device;
  230245. - (void) dealloc;
  230246. - (void) addSourceTrack: (JUCE_NAMESPACE::AudioSource*) source numSamples: (int) numSamples_;
  230247. - (void) burn: (JUCE_NAMESPACE::AudioCDBurner::BurnProgressListener*) listener errorString: (JUCE_NAMESPACE::String*) error
  230248. ejectAfterwards: (bool) shouldEject isFake: (bool) peformFakeBurnForTesting speed: (int) burnSpeed;
  230249. @end
  230250. #define AudioTrackProducer MakeObjCClassName(AudioTrackProducer)
  230251. @interface AudioTrackProducer : NSObject
  230252. {
  230253. JUCE_NAMESPACE::AudioSource* source;
  230254. int readPosition, lengthInFrames;
  230255. }
  230256. - (AudioTrackProducer*) init: (int) lengthInFrames;
  230257. - (AudioTrackProducer*) initWithAudioSource: (JUCE_NAMESPACE::AudioSource*) source numSamples: (int) lengthInSamples;
  230258. - (void) dealloc;
  230259. - (void) setupTrackProperties: (DRTrack*) track;
  230260. - (void) cleanupTrackAfterBurn: (DRTrack*) track;
  230261. - (BOOL) cleanupTrackAfterVerification:(DRTrack*)track;
  230262. - (uint64_t) estimateLengthOfTrack:(DRTrack*)track;
  230263. - (BOOL) prepareTrack:(DRTrack*)track forBurn:(DRBurn*)burn
  230264. toMedia:(NSDictionary*)mediaInfo;
  230265. - (BOOL) prepareTrackForVerification:(DRTrack*)track;
  230266. - (uint32_t) produceDataForTrack:(DRTrack*)track intoBuffer:(char*)buffer
  230267. length:(uint32_t)bufferLength atAddress:(uint64_t)address
  230268. blockSize:(uint32_t)blockSize ioFlags:(uint32_t*)flags;
  230269. - (uint32_t) producePreGapForTrack:(DRTrack*)track
  230270. intoBuffer:(char*)buffer length:(uint32_t)bufferLength
  230271. atAddress:(uint64_t)address blockSize:(uint32_t)blockSize
  230272. ioFlags:(uint32_t*)flags;
  230273. - (BOOL) verifyDataForTrack:(DRTrack*)track inBuffer:(const char*)buffer
  230274. length:(uint32_t)bufferLength atAddress:(uint64_t)address
  230275. blockSize:(uint32_t)blockSize ioFlags:(uint32_t*)flags;
  230276. - (uint32_t) producePreGapForTrack:(DRTrack*)track
  230277. intoBuffer:(char*)buffer length:(uint32_t)bufferLength
  230278. atAddress:(uint64_t)address blockSize:(uint32_t)blockSize
  230279. ioFlags:(uint32_t*)flags;
  230280. @end
  230281. @implementation OpenDiskDevice
  230282. - (OpenDiskDevice*) initWithDRDevice: (DRDevice*) device_
  230283. {
  230284. [super init];
  230285. device = device_;
  230286. tracks = [[NSMutableArray alloc] init];
  230287. underrunProtection = true;
  230288. return self;
  230289. }
  230290. - (void) dealloc
  230291. {
  230292. [tracks release];
  230293. [super dealloc];
  230294. }
  230295. - (void) addSourceTrack: (JUCE_NAMESPACE::AudioSource*) source_ numSamples: (int) numSamples_
  230296. {
  230297. AudioTrackProducer* p = [[AudioTrackProducer alloc] initWithAudioSource: source_ numSamples: numSamples_];
  230298. DRTrack* t = [[DRTrack alloc] initWithProducer: p];
  230299. [p setupTrackProperties: t];
  230300. [tracks addObject: t];
  230301. [t release];
  230302. [p release];
  230303. }
  230304. - (void) burn: (JUCE_NAMESPACE::AudioCDBurner::BurnProgressListener*) listener errorString: (JUCE_NAMESPACE::String*) error
  230305. ejectAfterwards: (bool) shouldEject isFake: (bool) peformFakeBurnForTesting speed: (int) burnSpeed
  230306. {
  230307. DRBurn* burn = [DRBurn burnForDevice: device];
  230308. if (! [device acquireExclusiveAccess])
  230309. {
  230310. *error = "Couldn't open or write to the CD device";
  230311. return;
  230312. }
  230313. [device acquireMediaReservation];
  230314. NSMutableDictionary* d = [[burn properties] mutableCopy];
  230315. [d autorelease];
  230316. [d setObject: [NSNumber numberWithBool: peformFakeBurnForTesting] forKey: DRBurnTestingKey];
  230317. [d setObject: [NSNumber numberWithBool: false] forKey: DRBurnVerifyDiscKey];
  230318. [d setObject: (shouldEject ? DRBurnCompletionActionEject : DRBurnCompletionActionMount) forKey: DRBurnCompletionActionKey];
  230319. if (burnSpeed > 0)
  230320. [d setObject: [NSNumber numberWithFloat: burnSpeed * JUCE_NAMESPACE::kilobytesPerSecond1x] forKey: DRBurnRequestedSpeedKey];
  230321. if (! underrunProtection)
  230322. [d setObject: [NSNumber numberWithBool: false] forKey: DRBurnUnderrunProtectionKey];
  230323. [burn setProperties: d];
  230324. [burn writeLayout: tracks];
  230325. for (;;)
  230326. {
  230327. JUCE_NAMESPACE::Thread::sleep (300);
  230328. float progress = [[[burn status] objectForKey: DRStatusPercentCompleteKey] floatValue];
  230329. if (listener != 0 && listener->audioCDBurnProgress (progress))
  230330. {
  230331. [burn abort];
  230332. *error = "User cancelled the write operation";
  230333. break;
  230334. }
  230335. if ([[[burn status] objectForKey: DRStatusStateKey] isEqualTo: DRStatusStateFailed])
  230336. {
  230337. *error = "Write operation failed";
  230338. break;
  230339. }
  230340. else if ([[[burn status] objectForKey: DRStatusStateKey] isEqualTo: DRStatusStateDone])
  230341. {
  230342. break;
  230343. }
  230344. NSString* err = (NSString*) [[[burn status] objectForKey: DRErrorStatusKey]
  230345. objectForKey: DRErrorStatusErrorStringKey];
  230346. if ([err length] > 0)
  230347. {
  230348. *error = JUCE_NAMESPACE::String::fromUTF8 ([err UTF8String]);
  230349. break;
  230350. }
  230351. }
  230352. [device releaseMediaReservation];
  230353. [device releaseExclusiveAccess];
  230354. }
  230355. @end
  230356. @implementation AudioTrackProducer
  230357. - (AudioTrackProducer*) init: (int) lengthInFrames_
  230358. {
  230359. lengthInFrames = lengthInFrames_;
  230360. readPosition = 0;
  230361. return self;
  230362. }
  230363. - (void) setupTrackProperties: (DRTrack*) track
  230364. {
  230365. NSMutableDictionary* p = [[track properties] mutableCopy];
  230366. [p setObject:[DRMSF msfWithFrames: lengthInFrames] forKey: DRTrackLengthKey];
  230367. [p setObject:[NSNumber numberWithUnsignedShort:2352] forKey: DRBlockSizeKey];
  230368. [p setObject:[NSNumber numberWithInt:0] forKey: DRDataFormKey];
  230369. [p setObject:[NSNumber numberWithInt:0] forKey: DRBlockTypeKey];
  230370. [p setObject:[NSNumber numberWithInt:0] forKey: DRTrackModeKey];
  230371. [p setObject:[NSNumber numberWithInt:0] forKey: DRSessionFormatKey];
  230372. [track setProperties: p];
  230373. [p release];
  230374. }
  230375. - (AudioTrackProducer*) initWithAudioSource: (JUCE_NAMESPACE::AudioSource*) source_ numSamples: (int) lengthInSamples
  230376. {
  230377. AudioTrackProducer* s = [self init: (lengthInSamples + 587) / 588];
  230378. if (s != nil)
  230379. s->source = source_;
  230380. return s;
  230381. }
  230382. - (void) dealloc
  230383. {
  230384. if (source != 0)
  230385. {
  230386. source->releaseResources();
  230387. delete source;
  230388. }
  230389. [super dealloc];
  230390. }
  230391. - (void) cleanupTrackAfterBurn: (DRTrack*) track
  230392. {
  230393. }
  230394. - (BOOL) cleanupTrackAfterVerification: (DRTrack*) track
  230395. {
  230396. return true;
  230397. }
  230398. - (uint64_t) estimateLengthOfTrack: (DRTrack*) track
  230399. {
  230400. return lengthInFrames;
  230401. }
  230402. - (BOOL) prepareTrack: (DRTrack*) track forBurn: (DRBurn*) burn
  230403. toMedia: (NSDictionary*) mediaInfo
  230404. {
  230405. if (source != 0)
  230406. source->prepareToPlay (44100 / 75, 44100);
  230407. readPosition = 0;
  230408. return true;
  230409. }
  230410. - (BOOL) prepareTrackForVerification: (DRTrack*) track
  230411. {
  230412. if (source != 0)
  230413. source->prepareToPlay (44100 / 75, 44100);
  230414. return true;
  230415. }
  230416. - (uint32_t) produceDataForTrack: (DRTrack*) track intoBuffer: (char*) buffer
  230417. length: (uint32_t) bufferLength atAddress: (uint64_t) address
  230418. blockSize: (uint32_t) blockSize ioFlags: (uint32_t*) flags
  230419. {
  230420. if (source != 0)
  230421. {
  230422. const int numSamples = JUCE_NAMESPACE::jmin ((int) bufferLength / 4, (lengthInFrames * (44100 / 75)) - readPosition);
  230423. if (numSamples > 0)
  230424. {
  230425. JUCE_NAMESPACE::AudioSampleBuffer tempBuffer (2, numSamples);
  230426. JUCE_NAMESPACE::AudioSourceChannelInfo info;
  230427. info.buffer = &tempBuffer;
  230428. info.startSample = 0;
  230429. info.numSamples = numSamples;
  230430. source->getNextAudioBlock (info);
  230431. JUCE_NAMESPACE::AudioDataConverters::convertFloatToInt16LE (tempBuffer.getSampleData (0),
  230432. buffer, numSamples, 4);
  230433. JUCE_NAMESPACE::AudioDataConverters::convertFloatToInt16LE (tempBuffer.getSampleData (1),
  230434. buffer + 2, numSamples, 4);
  230435. readPosition += numSamples;
  230436. }
  230437. return numSamples * 4;
  230438. }
  230439. return 0;
  230440. }
  230441. - (uint32_t) producePreGapForTrack: (DRTrack*) track
  230442. intoBuffer: (char*) buffer length: (uint32_t) bufferLength
  230443. atAddress: (uint64_t) address blockSize: (uint32_t) blockSize
  230444. ioFlags: (uint32_t*) flags
  230445. {
  230446. zeromem (buffer, bufferLength);
  230447. return bufferLength;
  230448. }
  230449. - (BOOL) verifyDataForTrack: (DRTrack*) track inBuffer: (const char*) buffer
  230450. length: (uint32_t) bufferLength atAddress: (uint64_t) address
  230451. blockSize: (uint32_t) blockSize ioFlags: (uint32_t*) flags
  230452. {
  230453. return true;
  230454. }
  230455. @end
  230456. BEGIN_JUCE_NAMESPACE
  230457. class AudioCDBurner::Pimpl : public Timer
  230458. {
  230459. public:
  230460. Pimpl (AudioCDBurner& owner_, const int deviceIndex)
  230461. : device (0), owner (owner_)
  230462. {
  230463. DRDevice* dev = [[DRDevice devices] objectAtIndex: deviceIndex];
  230464. if (dev != 0)
  230465. {
  230466. device = [[OpenDiskDevice alloc] initWithDRDevice: dev];
  230467. lastState = getDiskState();
  230468. startTimer (1000);
  230469. }
  230470. }
  230471. ~Pimpl()
  230472. {
  230473. stopTimer();
  230474. [device release];
  230475. }
  230476. void timerCallback()
  230477. {
  230478. const DiskState state = getDiskState();
  230479. if (state != lastState)
  230480. {
  230481. lastState = state;
  230482. owner.sendChangeMessage (&owner);
  230483. }
  230484. }
  230485. DiskState getDiskState() const
  230486. {
  230487. if ([device->device isValid])
  230488. {
  230489. NSDictionary* status = [device->device status];
  230490. NSString* state = [status objectForKey: DRDeviceMediaStateKey];
  230491. if ([state isEqualTo: DRDeviceMediaStateNone])
  230492. {
  230493. if ([[status objectForKey: DRDeviceIsTrayOpenKey] boolValue])
  230494. return trayOpen;
  230495. return noDisc;
  230496. }
  230497. if ([state isEqualTo: DRDeviceMediaStateMediaPresent])
  230498. {
  230499. if ([[[status objectForKey: DRDeviceMediaInfoKey] objectForKey: DRDeviceMediaBlocksFreeKey] intValue] > 0)
  230500. return writableDiskPresent;
  230501. else
  230502. return readOnlyDiskPresent;
  230503. }
  230504. }
  230505. return unknown;
  230506. }
  230507. bool openTray() { return [device->device isValid] && [device->device ejectMedia]; }
  230508. const Array<int> getAvailableWriteSpeeds() const
  230509. {
  230510. Array<int> results;
  230511. if ([device->device isValid])
  230512. {
  230513. NSArray* speeds = [[[device->device status] objectForKey: DRDeviceMediaInfoKey] objectForKey: DRDeviceBurnSpeedsKey];
  230514. for (unsigned int i = 0; i < [speeds count]; ++i)
  230515. {
  230516. const int kbPerSec = [[speeds objectAtIndex: i] intValue];
  230517. results.add (kbPerSec / kilobytesPerSecond1x);
  230518. }
  230519. }
  230520. return results;
  230521. }
  230522. bool setBufferUnderrunProtection (const bool shouldBeEnabled)
  230523. {
  230524. if ([device->device isValid])
  230525. {
  230526. device->underrunProtection = shouldBeEnabled;
  230527. return shouldBeEnabled && [[[device->device status] objectForKey: DRDeviceCanUnderrunProtectCDKey] boolValue];
  230528. }
  230529. return false;
  230530. }
  230531. int getNumAvailableAudioBlocks() const
  230532. {
  230533. return [[[[device->device status] objectForKey: DRDeviceMediaInfoKey]
  230534. objectForKey: DRDeviceMediaBlocksFreeKey] intValue];
  230535. }
  230536. OpenDiskDevice* device;
  230537. private:
  230538. DiskState lastState;
  230539. AudioCDBurner& owner;
  230540. };
  230541. AudioCDBurner::AudioCDBurner (const int deviceIndex)
  230542. {
  230543. pimpl = new Pimpl (*this, deviceIndex);
  230544. }
  230545. AudioCDBurner::~AudioCDBurner()
  230546. {
  230547. }
  230548. AudioCDBurner* AudioCDBurner::openDevice (const int deviceIndex)
  230549. {
  230550. ScopedPointer <AudioCDBurner> b (new AudioCDBurner (deviceIndex));
  230551. if (b->pimpl->device == 0)
  230552. b = 0;
  230553. return b.release();
  230554. }
  230555. static NSArray* findDiskBurnerDevices()
  230556. {
  230557. NSMutableArray* results = [NSMutableArray array];
  230558. NSArray* devs = [DRDevice devices];
  230559. if (devs != 0)
  230560. {
  230561. int num = [devs count];
  230562. int i;
  230563. for (i = 0; i < num; ++i)
  230564. {
  230565. NSDictionary* dic = [[devs objectAtIndex: i] info];
  230566. NSString* name = [dic valueForKey: DRDeviceProductNameKey];
  230567. if (name != nil)
  230568. [results addObject: name];
  230569. }
  230570. }
  230571. return results;
  230572. }
  230573. const StringArray AudioCDBurner::findAvailableDevices()
  230574. {
  230575. NSArray* names = findDiskBurnerDevices();
  230576. StringArray s;
  230577. for (unsigned int i = 0; i < [names count]; ++i)
  230578. s.add (String::fromUTF8 ([[names objectAtIndex: i] UTF8String]));
  230579. return s;
  230580. }
  230581. AudioCDBurner::DiskState AudioCDBurner::getDiskState() const
  230582. {
  230583. return pimpl->getDiskState();
  230584. }
  230585. bool AudioCDBurner::isDiskPresent() const
  230586. {
  230587. return getDiskState() == writableDiskPresent;
  230588. }
  230589. bool AudioCDBurner::openTray()
  230590. {
  230591. return pimpl->openTray();
  230592. }
  230593. AudioCDBurner::DiskState AudioCDBurner::waitUntilStateChange (int timeOutMilliseconds)
  230594. {
  230595. const int64 timeout = Time::currentTimeMillis() + timeOutMilliseconds;
  230596. DiskState oldState = getDiskState();
  230597. DiskState newState = oldState;
  230598. while (newState == oldState && Time::currentTimeMillis() < timeout)
  230599. {
  230600. newState = getDiskState();
  230601. Thread::sleep (100);
  230602. }
  230603. return newState;
  230604. }
  230605. const Array<int> AudioCDBurner::getAvailableWriteSpeeds() const
  230606. {
  230607. return pimpl->getAvailableWriteSpeeds();
  230608. }
  230609. bool AudioCDBurner::setBufferUnderrunProtection (const bool shouldBeEnabled)
  230610. {
  230611. return pimpl->setBufferUnderrunProtection (shouldBeEnabled);
  230612. }
  230613. int AudioCDBurner::getNumAvailableAudioBlocks() const
  230614. {
  230615. return pimpl->getNumAvailableAudioBlocks();
  230616. }
  230617. bool AudioCDBurner::addAudioTrack (AudioSource* source, int numSamps)
  230618. {
  230619. if ([pimpl->device->device isValid])
  230620. {
  230621. [pimpl->device addSourceTrack: source numSamples: numSamps];
  230622. return true;
  230623. }
  230624. return false;
  230625. }
  230626. const String AudioCDBurner::burn (JUCE_NAMESPACE::AudioCDBurner::BurnProgressListener* listener,
  230627. bool ejectDiscAfterwards,
  230628. bool performFakeBurnForTesting,
  230629. int writeSpeed)
  230630. {
  230631. String error ("Couldn't open or write to the CD device");
  230632. if ([pimpl->device->device isValid])
  230633. {
  230634. error = String::empty;
  230635. [pimpl->device burn: listener
  230636. errorString: &error
  230637. ejectAfterwards: ejectDiscAfterwards
  230638. isFake: performFakeBurnForTesting
  230639. speed: writeSpeed];
  230640. }
  230641. return error;
  230642. }
  230643. #endif
  230644. #if JUCE_INCLUDED_FILE && JUCE_USE_CDREADER
  230645. void AudioCDReader::ejectDisk()
  230646. {
  230647. const ScopedAutoReleasePool p;
  230648. [[NSWorkspace sharedWorkspace] unmountAndEjectDeviceAtPath: juceStringToNS (volumeDir.getFullPathName())];
  230649. }
  230650. #endif
  230651. /*** End of inlined file: juce_mac_AudioCDBurner.mm ***/
  230652. /*** Start of inlined file: juce_mac_MessageManager.mm ***/
  230653. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  230654. // compiled on its own).
  230655. #if JUCE_INCLUDED_FILE
  230656. /* When you use multiple DLLs which share similarly-named obj-c classes - like
  230657. for example having more than one juce plugin loaded into a host, then when a
  230658. method is called, the actual code that runs might actually be in a different module
  230659. than the one you expect... So any calls to library functions or statics that are
  230660. made inside obj-c methods will probably end up getting executed in a different DLL's
  230661. memory space. Not a great thing to happen - this obviously leads to bizarre crashes.
  230662. To work around this insanity, I'm only allowing obj-c methods to make calls to
  230663. virtual methods of an object that's known to live inside the right module's space.
  230664. */
  230665. class AppDelegateRedirector
  230666. {
  230667. public:
  230668. AppDelegateRedirector()
  230669. {
  230670. #if MAC_OS_X_VERSION_MIN_REQUIRED > MAC_OS_X_VERSION_10_4
  230671. runLoop = CFRunLoopGetMain();
  230672. #else
  230673. runLoop = CFRunLoopGetCurrent();
  230674. #endif
  230675. CFRunLoopSourceContext sourceContext;
  230676. zerostruct (sourceContext);
  230677. sourceContext.info = this;
  230678. sourceContext.perform = runLoopSourceCallback;
  230679. runLoopSource = CFRunLoopSourceCreate (kCFAllocatorDefault, 1, &sourceContext);
  230680. CFRunLoopAddSource (runLoop, runLoopSource, kCFRunLoopCommonModes);
  230681. }
  230682. virtual ~AppDelegateRedirector()
  230683. {
  230684. CFRunLoopRemoveSource (runLoop, runLoopSource, kCFRunLoopCommonModes);
  230685. CFRunLoopSourceInvalidate (runLoopSource);
  230686. CFRelease (runLoopSource);
  230687. while (messages.size() > 0)
  230688. delete static_cast <Message*> (messages.remove(0));
  230689. }
  230690. virtual NSApplicationTerminateReply shouldTerminate()
  230691. {
  230692. if (JUCEApplication::getInstance() != 0)
  230693. {
  230694. JUCEApplication::getInstance()->systemRequestedQuit();
  230695. return NSTerminateCancel;
  230696. }
  230697. return NSTerminateNow;
  230698. }
  230699. virtual BOOL openFile (const NSString* filename)
  230700. {
  230701. if (JUCEApplication::getInstance() != 0)
  230702. {
  230703. JUCEApplication::getInstance()->anotherInstanceStarted (nsStringToJuce (filename));
  230704. return YES;
  230705. }
  230706. return NO;
  230707. }
  230708. virtual void openFiles (NSArray* filenames)
  230709. {
  230710. StringArray files;
  230711. for (unsigned int i = 0; i < [filenames count]; ++i)
  230712. {
  230713. String filename (nsStringToJuce ((NSString*) [filenames objectAtIndex: i]));
  230714. if (filename.containsChar (' '))
  230715. filename = filename.quoted('"');
  230716. files.add (filename);
  230717. }
  230718. if (files.size() > 0 && JUCEApplication::getInstance() != 0)
  230719. {
  230720. JUCEApplication::getInstance()->anotherInstanceStarted (files.joinIntoString (" "));
  230721. }
  230722. }
  230723. virtual void focusChanged()
  230724. {
  230725. juce_HandleProcessFocusChange();
  230726. }
  230727. struct CallbackMessagePayload
  230728. {
  230729. MessageCallbackFunction* function;
  230730. void* parameter;
  230731. void* volatile result;
  230732. bool volatile hasBeenExecuted;
  230733. };
  230734. virtual void performCallback (CallbackMessagePayload* pl)
  230735. {
  230736. pl->result = (*pl->function) (pl->parameter);
  230737. pl->hasBeenExecuted = true;
  230738. }
  230739. virtual void deleteSelf()
  230740. {
  230741. delete this;
  230742. }
  230743. void postMessage (void* m)
  230744. {
  230745. messages.add (m);
  230746. CFRunLoopSourceSignal (runLoopSource);
  230747. CFRunLoopWakeUp (runLoop);
  230748. }
  230749. private:
  230750. CFRunLoopRef runLoop;
  230751. CFRunLoopSourceRef runLoopSource;
  230752. Array <void*, CriticalSection> messages;
  230753. void runLoopCallback()
  230754. {
  230755. int numDispatched = 0;
  230756. do
  230757. {
  230758. void* const nextMessage = messages.remove (0);
  230759. if (nextMessage == 0)
  230760. return;
  230761. const ScopedAutoReleasePool pool;
  230762. MessageManager::getInstance()->deliverMessage (nextMessage);
  230763. } while (++numDispatched <= 4);
  230764. CFRunLoopSourceSignal (runLoopSource);
  230765. CFRunLoopWakeUp (runLoop);
  230766. }
  230767. static void runLoopSourceCallback (void* info)
  230768. {
  230769. static_cast <AppDelegateRedirector*> (info)->runLoopCallback();
  230770. }
  230771. };
  230772. END_JUCE_NAMESPACE
  230773. using namespace JUCE_NAMESPACE;
  230774. #define JuceAppDelegate MakeObjCClassName(JuceAppDelegate)
  230775. @interface JuceAppDelegate : NSObject
  230776. {
  230777. @private
  230778. id oldDelegate;
  230779. @public
  230780. AppDelegateRedirector* redirector;
  230781. }
  230782. - (JuceAppDelegate*) init;
  230783. - (void) dealloc;
  230784. - (BOOL) application: (NSApplication*) theApplication openFile: (NSString*) filename;
  230785. - (void) application: (NSApplication*) sender openFiles: (NSArray*) filenames;
  230786. - (NSApplicationTerminateReply) applicationShouldTerminate: (NSApplication*) app;
  230787. - (void) applicationDidBecomeActive: (NSNotification*) aNotification;
  230788. - (void) applicationDidResignActive: (NSNotification*) aNotification;
  230789. - (void) applicationWillUnhide: (NSNotification*) aNotification;
  230790. - (void) performCallback: (id) info;
  230791. - (void) dummyMethod;
  230792. @end
  230793. @implementation JuceAppDelegate
  230794. - (JuceAppDelegate*) init
  230795. {
  230796. [super init];
  230797. redirector = new AppDelegateRedirector();
  230798. NSNotificationCenter* center = [NSNotificationCenter defaultCenter];
  230799. if (JUCEApplication::getInstance() != 0)
  230800. {
  230801. oldDelegate = [NSApp delegate];
  230802. [NSApp setDelegate: self];
  230803. }
  230804. else
  230805. {
  230806. oldDelegate = 0;
  230807. [center addObserver: self selector: @selector (applicationDidResignActive:)
  230808. name: NSApplicationDidResignActiveNotification object: NSApp];
  230809. [center addObserver: self selector: @selector (applicationDidBecomeActive:)
  230810. name: NSApplicationDidBecomeActiveNotification object: NSApp];
  230811. [center addObserver: self selector: @selector (applicationWillUnhide:)
  230812. name: NSApplicationWillUnhideNotification object: NSApp];
  230813. }
  230814. return self;
  230815. }
  230816. - (void) dealloc
  230817. {
  230818. if (oldDelegate != 0)
  230819. [NSApp setDelegate: oldDelegate];
  230820. redirector->deleteSelf();
  230821. [super dealloc];
  230822. }
  230823. - (NSApplicationTerminateReply) applicationShouldTerminate: (NSApplication*) app
  230824. {
  230825. (void) app;
  230826. return redirector->shouldTerminate();
  230827. }
  230828. - (BOOL) application: (NSApplication*) app openFile: (NSString*) filename
  230829. {
  230830. (void) app;
  230831. return redirector->openFile (filename);
  230832. }
  230833. - (void) application: (NSApplication*) sender openFiles: (NSArray*) filenames
  230834. {
  230835. (void) sender;
  230836. return redirector->openFiles (filenames);
  230837. }
  230838. - (void) applicationDidBecomeActive: (NSNotification*) notification
  230839. {
  230840. (void) notification;
  230841. redirector->focusChanged();
  230842. }
  230843. - (void) applicationDidResignActive: (NSNotification*) notification
  230844. {
  230845. (void) notification;
  230846. redirector->focusChanged();
  230847. }
  230848. - (void) applicationWillUnhide: (NSNotification*) notification
  230849. {
  230850. (void) notification;
  230851. redirector->focusChanged();
  230852. }
  230853. - (void) performCallback: (id) info
  230854. {
  230855. if ([info isKindOfClass: [NSData class]])
  230856. {
  230857. AppDelegateRedirector::CallbackMessagePayload* pl
  230858. = (AppDelegateRedirector::CallbackMessagePayload*) [((NSData*) info) bytes];
  230859. if (pl != 0)
  230860. redirector->performCallback (pl);
  230861. }
  230862. else
  230863. {
  230864. jassertfalse // should never get here!
  230865. }
  230866. }
  230867. - (void) dummyMethod {} // (used as a way of running a dummy thread)
  230868. @end
  230869. BEGIN_JUCE_NAMESPACE
  230870. static JuceAppDelegate* juceAppDelegate = 0;
  230871. void MessageManager::runDispatchLoop()
  230872. {
  230873. if (! quitMessagePosted) // check that the quit message wasn't already posted..
  230874. {
  230875. const ScopedAutoReleasePool pool;
  230876. // must only be called by the message thread!
  230877. jassert (isThisTheMessageThread());
  230878. #if JUCE_CATCH_UNHANDLED_EXCEPTIONS
  230879. @try
  230880. {
  230881. [NSApp run];
  230882. }
  230883. @catch (NSException* e)
  230884. {
  230885. // An AppKit exception will kill the app, but at least this provides a chance to log it.,
  230886. std::runtime_error ex (std::string ("NSException: ") + [[e name] UTF8String] + ", Reason:" + [[e reason] UTF8String]);
  230887. JUCEApplication::sendUnhandledException (&ex, __FILE__, __LINE__);
  230888. }
  230889. @finally
  230890. {
  230891. }
  230892. #else
  230893. [NSApp run];
  230894. #endif
  230895. }
  230896. }
  230897. void MessageManager::stopDispatchLoop()
  230898. {
  230899. quitMessagePosted = true;
  230900. [NSApp stop: nil];
  230901. [NSApp activateIgnoringOtherApps: YES]; // (if the app is inactive, it sits there and ignores the quit request until the next time it gets activated)
  230902. [NSEvent startPeriodicEventsAfterDelay: 0 withPeriod: 0.1];
  230903. }
  230904. static bool isEventBlockedByModalComps (NSEvent* e)
  230905. {
  230906. if (Component::getNumCurrentlyModalComponents() == 0)
  230907. return false;
  230908. NSWindow* const w = [e window];
  230909. if (w == 0 || [w worksWhenModal])
  230910. return false;
  230911. bool isKey = false, isInputAttempt = false;
  230912. switch ([e type])
  230913. {
  230914. case NSKeyDown:
  230915. case NSKeyUp:
  230916. isKey = isInputAttempt = true;
  230917. break;
  230918. case NSLeftMouseDown:
  230919. case NSRightMouseDown:
  230920. case NSOtherMouseDown:
  230921. isInputAttempt = true;
  230922. break;
  230923. case NSLeftMouseDragged:
  230924. case NSRightMouseDragged:
  230925. case NSLeftMouseUp:
  230926. case NSRightMouseUp:
  230927. case NSOtherMouseUp:
  230928. case NSOtherMouseDragged:
  230929. if (Desktop::getInstance().getDraggingMouseSource(0) != 0)
  230930. return false;
  230931. break;
  230932. case NSMouseMoved:
  230933. case NSMouseEntered:
  230934. case NSMouseExited:
  230935. case NSCursorUpdate:
  230936. case NSScrollWheel:
  230937. case NSTabletPoint:
  230938. case NSTabletProximity:
  230939. break;
  230940. default:
  230941. return false;
  230942. }
  230943. for (int i = ComponentPeer::getNumPeers(); --i >= 0;)
  230944. {
  230945. ComponentPeer* const peer = ComponentPeer::getPeer (i);
  230946. NSView* const compView = (NSView*) peer->getNativeHandle();
  230947. if ([compView window] == w)
  230948. {
  230949. if (isKey)
  230950. {
  230951. if (compView == [w firstResponder])
  230952. return false;
  230953. }
  230954. else
  230955. {
  230956. if (NSPointInRect ([compView convertPoint: [e locationInWindow] fromView: nil],
  230957. [compView bounds]))
  230958. return false;
  230959. }
  230960. }
  230961. }
  230962. if (isInputAttempt)
  230963. {
  230964. if (! [NSApp isActive])
  230965. [NSApp activateIgnoringOtherApps: YES];
  230966. Component* const modal = Component::getCurrentlyModalComponent (0);
  230967. if (modal != 0)
  230968. modal->inputAttemptWhenModal();
  230969. }
  230970. return true;
  230971. }
  230972. bool MessageManager::runDispatchLoopUntil (int millisecondsToRunFor)
  230973. {
  230974. const ScopedAutoReleasePool pool;
  230975. jassert (isThisTheMessageThread()); // must only be called by the message thread
  230976. uint32 endTime = Time::getMillisecondCounter() + millisecondsToRunFor;
  230977. while (! quitMessagePosted)
  230978. {
  230979. const ScopedAutoReleasePool pool2;
  230980. CFRunLoopRunInMode (kCFRunLoopDefaultMode, 0.001, true);
  230981. NSEvent* e = [NSApp nextEventMatchingMask: NSAnyEventMask
  230982. untilDate: [NSDate dateWithTimeIntervalSinceNow: 0.001]
  230983. inMode: NSDefaultRunLoopMode
  230984. dequeue: YES];
  230985. if (e != 0 && ! isEventBlockedByModalComps (e))
  230986. [NSApp sendEvent: e];
  230987. if (Time::getMillisecondCounter() >= endTime)
  230988. break;
  230989. }
  230990. return ! quitMessagePosted;
  230991. }
  230992. void MessageManager::doPlatformSpecificInitialisation()
  230993. {
  230994. if (juceAppDelegate == 0)
  230995. juceAppDelegate = [[JuceAppDelegate alloc] init];
  230996. // This launches a dummy thread, which forces Cocoa to initialise NSThreads
  230997. // correctly (needed prior to 10.5)
  230998. if (! [NSThread isMultiThreaded])
  230999. [NSThread detachNewThreadSelector: @selector (dummyMethod)
  231000. toTarget: juceAppDelegate
  231001. withObject: nil];
  231002. initialiseMainMenu();
  231003. }
  231004. void MessageManager::doPlatformSpecificShutdown()
  231005. {
  231006. if (juceAppDelegate != 0)
  231007. {
  231008. [[NSRunLoop currentRunLoop] cancelPerformSelectorsWithTarget: juceAppDelegate];
  231009. [[NSNotificationCenter defaultCenter] removeObserver: juceAppDelegate];
  231010. [juceAppDelegate release];
  231011. juceAppDelegate = 0;
  231012. }
  231013. }
  231014. bool juce_postMessageToSystemQueue (void* message)
  231015. {
  231016. juceAppDelegate->redirector->postMessage (message);
  231017. return true;
  231018. }
  231019. void MessageManager::broadcastMessage (const String& value) throw()
  231020. {
  231021. }
  231022. void* MessageManager::callFunctionOnMessageThread (MessageCallbackFunction* callback,
  231023. void* data)
  231024. {
  231025. if (isThisTheMessageThread())
  231026. {
  231027. return (*callback) (data);
  231028. }
  231029. else
  231030. {
  231031. // If a thread has a MessageManagerLock and then tries to call this method, it'll
  231032. // deadlock because the message manager is blocked from running, so can never
  231033. // call your function..
  231034. jassert (! MessageManager::getInstance()->currentThreadHasLockedMessageManager());
  231035. const ScopedAutoReleasePool pool;
  231036. AppDelegateRedirector::CallbackMessagePayload cmp;
  231037. cmp.function = callback;
  231038. cmp.parameter = data;
  231039. cmp.result = 0;
  231040. cmp.hasBeenExecuted = false;
  231041. [juceAppDelegate performSelectorOnMainThread: @selector (performCallback:)
  231042. withObject: [NSData dataWithBytesNoCopy: &cmp
  231043. length: sizeof (cmp)
  231044. freeWhenDone: NO]
  231045. waitUntilDone: YES];
  231046. return cmp.result;
  231047. }
  231048. }
  231049. #endif
  231050. /*** End of inlined file: juce_mac_MessageManager.mm ***/
  231051. /*** Start of inlined file: juce_mac_WebBrowserComponent.mm ***/
  231052. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  231053. // compiled on its own).
  231054. #if JUCE_INCLUDED_FILE && JUCE_WEB_BROWSER
  231055. #if JUCE_MAC
  231056. END_JUCE_NAMESPACE
  231057. #define DownloadClickDetector MakeObjCClassName(DownloadClickDetector)
  231058. @interface DownloadClickDetector : NSObject
  231059. {
  231060. JUCE_NAMESPACE::WebBrowserComponent* ownerComponent;
  231061. }
  231062. - (DownloadClickDetector*) initWithWebBrowserOwner: (JUCE_NAMESPACE::WebBrowserComponent*) ownerComponent;
  231063. - (void) webView: (WebView*) webView decidePolicyForNavigationAction: (NSDictionary*) actionInformation
  231064. request: (NSURLRequest*) request
  231065. frame: (WebFrame*) frame
  231066. decisionListener: (id<WebPolicyDecisionListener>) listener;
  231067. @end
  231068. @implementation DownloadClickDetector
  231069. - (DownloadClickDetector*) initWithWebBrowserOwner: (JUCE_NAMESPACE::WebBrowserComponent*) ownerComponent_
  231070. {
  231071. [super init];
  231072. ownerComponent = ownerComponent_;
  231073. return self;
  231074. }
  231075. - (void) webView: (WebView*) sender decidePolicyForNavigationAction: (NSDictionary*) actionInformation
  231076. request: (NSURLRequest*) request
  231077. frame: (WebFrame*) frame
  231078. decisionListener: (id <WebPolicyDecisionListener>) listener
  231079. {
  231080. (void) sender;
  231081. (void) request;
  231082. (void) frame;
  231083. NSURL* url = [actionInformation valueForKey: @"WebActionOriginalURLKey"];
  231084. if (ownerComponent->pageAboutToLoad (nsStringToJuce ([url absoluteString])))
  231085. [listener use];
  231086. else
  231087. [listener ignore];
  231088. }
  231089. @end
  231090. BEGIN_JUCE_NAMESPACE
  231091. class WebBrowserComponentInternal : public NSViewComponent
  231092. {
  231093. public:
  231094. WebBrowserComponentInternal (WebBrowserComponent* owner)
  231095. {
  231096. webView = [[WebView alloc] initWithFrame: NSMakeRect (0, 0, 100.0f, 100.0f)
  231097. frameName: @""
  231098. groupName: @""];
  231099. setView (webView);
  231100. clickListener = [[DownloadClickDetector alloc] initWithWebBrowserOwner: owner];
  231101. [webView setPolicyDelegate: clickListener];
  231102. }
  231103. ~WebBrowserComponentInternal()
  231104. {
  231105. [webView setPolicyDelegate: nil];
  231106. [clickListener release];
  231107. setView (0);
  231108. }
  231109. void goToURL (const String& url,
  231110. const StringArray* headers,
  231111. const MemoryBlock* postData)
  231112. {
  231113. NSMutableURLRequest* r
  231114. = [NSMutableURLRequest requestWithURL: [NSURL URLWithString: juceStringToNS (url)]
  231115. cachePolicy: NSURLRequestUseProtocolCachePolicy
  231116. timeoutInterval: 30.0];
  231117. if (postData != 0 && postData->getSize() > 0)
  231118. {
  231119. [r setHTTPMethod: @"POST"];
  231120. [r setHTTPBody: [NSData dataWithBytes: postData->getData()
  231121. length: postData->getSize()]];
  231122. }
  231123. if (headers != 0)
  231124. {
  231125. for (int i = 0; i < headers->size(); ++i)
  231126. {
  231127. const String headerName ((*headers)[i].upToFirstOccurrenceOf (":", false, false).trim());
  231128. const String headerValue ((*headers)[i].fromFirstOccurrenceOf (":", false, false).trim());
  231129. [r setValue: juceStringToNS (headerValue)
  231130. forHTTPHeaderField: juceStringToNS (headerName)];
  231131. }
  231132. }
  231133. stop();
  231134. [[webView mainFrame] loadRequest: r];
  231135. }
  231136. void goBack()
  231137. {
  231138. [webView goBack];
  231139. }
  231140. void goForward()
  231141. {
  231142. [webView goForward];
  231143. }
  231144. void stop()
  231145. {
  231146. [webView stopLoading: nil];
  231147. }
  231148. void refresh()
  231149. {
  231150. [webView reload: nil];
  231151. }
  231152. private:
  231153. WebView* webView;
  231154. DownloadClickDetector* clickListener;
  231155. };
  231156. WebBrowserComponent::WebBrowserComponent (const bool unloadPageWhenBrowserIsHidden_)
  231157. : browser (0),
  231158. blankPageShown (false),
  231159. unloadPageWhenBrowserIsHidden (unloadPageWhenBrowserIsHidden_)
  231160. {
  231161. setOpaque (true);
  231162. addAndMakeVisible (browser = new WebBrowserComponentInternal (this));
  231163. }
  231164. WebBrowserComponent::~WebBrowserComponent()
  231165. {
  231166. deleteAndZero (browser);
  231167. }
  231168. void WebBrowserComponent::goToURL (const String& url,
  231169. const StringArray* headers,
  231170. const MemoryBlock* postData)
  231171. {
  231172. lastURL = url;
  231173. lastHeaders.clear();
  231174. if (headers != 0)
  231175. lastHeaders = *headers;
  231176. lastPostData.setSize (0);
  231177. if (postData != 0)
  231178. lastPostData = *postData;
  231179. blankPageShown = false;
  231180. browser->goToURL (url, headers, postData);
  231181. }
  231182. void WebBrowserComponent::stop()
  231183. {
  231184. browser->stop();
  231185. }
  231186. void WebBrowserComponent::goBack()
  231187. {
  231188. lastURL = String::empty;
  231189. blankPageShown = false;
  231190. browser->goBack();
  231191. }
  231192. void WebBrowserComponent::goForward()
  231193. {
  231194. lastURL = String::empty;
  231195. browser->goForward();
  231196. }
  231197. void WebBrowserComponent::refresh()
  231198. {
  231199. browser->refresh();
  231200. }
  231201. void WebBrowserComponent::paint (Graphics&)
  231202. {
  231203. }
  231204. void WebBrowserComponent::checkWindowAssociation()
  231205. {
  231206. if (isShowing())
  231207. {
  231208. if (blankPageShown)
  231209. goBack();
  231210. }
  231211. else
  231212. {
  231213. if (unloadPageWhenBrowserIsHidden && ! blankPageShown)
  231214. {
  231215. // when the component becomes invisible, some stuff like flash
  231216. // carries on playing audio, so we need to force it onto a blank
  231217. // page to avoid this, (and send it back when it's made visible again).
  231218. blankPageShown = true;
  231219. browser->goToURL ("about:blank", 0, 0);
  231220. }
  231221. }
  231222. }
  231223. void WebBrowserComponent::reloadLastURL()
  231224. {
  231225. if (lastURL.isNotEmpty())
  231226. {
  231227. goToURL (lastURL, &lastHeaders, &lastPostData);
  231228. lastURL = String::empty;
  231229. }
  231230. }
  231231. void WebBrowserComponent::parentHierarchyChanged()
  231232. {
  231233. checkWindowAssociation();
  231234. }
  231235. void WebBrowserComponent::resized()
  231236. {
  231237. browser->setSize (getWidth(), getHeight());
  231238. }
  231239. void WebBrowserComponent::visibilityChanged()
  231240. {
  231241. checkWindowAssociation();
  231242. }
  231243. bool WebBrowserComponent::pageAboutToLoad (const String&)
  231244. {
  231245. return true;
  231246. }
  231247. #else
  231248. WebBrowserComponent::WebBrowserComponent (const bool unloadPageWhenBrowserIsHidden_)
  231249. {
  231250. }
  231251. WebBrowserComponent::~WebBrowserComponent()
  231252. {
  231253. }
  231254. void WebBrowserComponent::goToURL (const String& url,
  231255. const StringArray* headers,
  231256. const MemoryBlock* postData)
  231257. {
  231258. }
  231259. void WebBrowserComponent::stop()
  231260. {
  231261. }
  231262. void WebBrowserComponent::goBack()
  231263. {
  231264. }
  231265. void WebBrowserComponent::goForward()
  231266. {
  231267. }
  231268. void WebBrowserComponent::refresh()
  231269. {
  231270. }
  231271. void WebBrowserComponent::paint (Graphics& g)
  231272. {
  231273. }
  231274. void WebBrowserComponent::checkWindowAssociation()
  231275. {
  231276. }
  231277. void WebBrowserComponent::reloadLastURL()
  231278. {
  231279. }
  231280. void WebBrowserComponent::parentHierarchyChanged()
  231281. {
  231282. }
  231283. void WebBrowserComponent::resized()
  231284. {
  231285. }
  231286. void WebBrowserComponent::visibilityChanged()
  231287. {
  231288. }
  231289. bool WebBrowserComponent::pageAboutToLoad (const String& url)
  231290. {
  231291. return true;
  231292. }
  231293. #endif
  231294. #endif
  231295. /*** End of inlined file: juce_mac_WebBrowserComponent.mm ***/
  231296. /*** Start of inlined file: juce_mac_CoreAudio.cpp ***/
  231297. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  231298. // compiled on its own).
  231299. #if JUCE_INCLUDED_FILE
  231300. #ifndef JUCE_COREAUDIO_ERROR_LOGGING_ENABLED
  231301. #define JUCE_COREAUDIO_ERROR_LOGGING_ENABLED 1
  231302. #endif
  231303. #undef log
  231304. #if JUCE_COREAUDIO_LOGGING_ENABLED
  231305. #define log(a) Logger::writeToLog (a)
  231306. #else
  231307. #define log(a)
  231308. #endif
  231309. #undef OK
  231310. #if JUCE_COREAUDIO_ERROR_LOGGING_ENABLED
  231311. static bool logAnyErrors_CoreAudio (const OSStatus err, const int lineNum)
  231312. {
  231313. if (err == noErr)
  231314. return true;
  231315. Logger::writeToLog ("CoreAudio error: " + String (lineNum) + " - " + String::toHexString ((int) err));
  231316. jassertfalse
  231317. return false;
  231318. }
  231319. #define OK(a) logAnyErrors_CoreAudio (a, __LINE__)
  231320. #else
  231321. #define OK(a) (a == noErr)
  231322. #endif
  231323. class CoreAudioInternal : public Timer
  231324. {
  231325. public:
  231326. CoreAudioInternal (AudioDeviceID id)
  231327. : inputLatency (0),
  231328. outputLatency (0),
  231329. callback (0),
  231330. #if MAC_OS_X_VERSION_MIN_REQUIRED >= MAC_OS_X_VERSION_10_5
  231331. audioProcID (0),
  231332. #endif
  231333. inputDevice (0),
  231334. isSlaveDevice (false),
  231335. deviceID (id),
  231336. started (false),
  231337. sampleRate (0),
  231338. bufferSize (512),
  231339. numInputChans (0),
  231340. numOutputChans (0),
  231341. callbacksAllowed (true),
  231342. numInputChannelInfos (0),
  231343. numOutputChannelInfos (0)
  231344. {
  231345. jassert (deviceID != 0);
  231346. updateDetailsFromDevice();
  231347. AudioObjectPropertyAddress pa;
  231348. pa.mSelector = kAudioObjectPropertySelectorWildcard;
  231349. pa.mScope = kAudioObjectPropertyScopeWildcard;
  231350. pa.mElement = kAudioObjectPropertyElementWildcard;
  231351. AudioObjectAddPropertyListener (deviceID, &pa, deviceListenerProc, this);
  231352. }
  231353. ~CoreAudioInternal()
  231354. {
  231355. AudioObjectPropertyAddress pa;
  231356. pa.mSelector = kAudioObjectPropertySelectorWildcard;
  231357. pa.mScope = kAudioObjectPropertyScopeWildcard;
  231358. pa.mElement = kAudioObjectPropertyElementWildcard;
  231359. AudioObjectRemovePropertyListener (deviceID, &pa, deviceListenerProc, this);
  231360. stop (false);
  231361. delete inputDevice;
  231362. }
  231363. void allocateTempBuffers()
  231364. {
  231365. const int tempBufSize = bufferSize + 4;
  231366. audioBuffer.calloc ((numInputChans + numOutputChans) * tempBufSize);
  231367. tempInputBuffers.calloc (numInputChans + 2);
  231368. tempOutputBuffers.calloc (numOutputChans + 2);
  231369. int i, count = 0;
  231370. for (i = 0; i < numInputChans; ++i)
  231371. tempInputBuffers[i] = audioBuffer + count++ * tempBufSize;
  231372. for (i = 0; i < numOutputChans; ++i)
  231373. tempOutputBuffers[i] = audioBuffer + count++ * tempBufSize;
  231374. }
  231375. // returns the number of actual available channels
  231376. void fillInChannelInfo (const bool input)
  231377. {
  231378. int chanNum = 0;
  231379. UInt32 size;
  231380. AudioObjectPropertyAddress pa;
  231381. pa.mSelector = kAudioDevicePropertyStreamConfiguration;
  231382. pa.mScope = input ? kAudioDevicePropertyScopeInput : kAudioDevicePropertyScopeOutput;
  231383. pa.mElement = kAudioObjectPropertyElementMaster;
  231384. if (OK (AudioObjectGetPropertyDataSize (deviceID, &pa, 0, 0, &size)))
  231385. {
  231386. HeapBlock <AudioBufferList> bufList;
  231387. bufList.calloc (size, 1);
  231388. if (OK (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &size, bufList)))
  231389. {
  231390. const int numStreams = bufList->mNumberBuffers;
  231391. for (int i = 0; i < numStreams; ++i)
  231392. {
  231393. const AudioBuffer& b = bufList->mBuffers[i];
  231394. for (unsigned int j = 0; j < b.mNumberChannels; ++j)
  231395. {
  231396. String name;
  231397. {
  231398. char channelName [256];
  231399. zerostruct (channelName);
  231400. UInt32 nameSize = sizeof (channelName);
  231401. UInt32 channelNum = chanNum + 1;
  231402. pa.mSelector = kAudioDevicePropertyChannelName;
  231403. if (AudioObjectGetPropertyData (deviceID, &pa, sizeof (channelNum), &channelNum, &nameSize, channelName) == noErr)
  231404. name = String::fromUTF8 (channelName, nameSize);
  231405. }
  231406. if (input)
  231407. {
  231408. if (activeInputChans[chanNum])
  231409. {
  231410. inputChannelInfo [numInputChannelInfos].streamNum = i;
  231411. inputChannelInfo [numInputChannelInfos].dataOffsetSamples = j;
  231412. inputChannelInfo [numInputChannelInfos].dataStrideSamples = b.mNumberChannels;
  231413. ++numInputChannelInfos;
  231414. }
  231415. if (name.isEmpty())
  231416. name << "Input " << (chanNum + 1);
  231417. inChanNames.add (name);
  231418. }
  231419. else
  231420. {
  231421. if (activeOutputChans[chanNum])
  231422. {
  231423. outputChannelInfo [numOutputChannelInfos].streamNum = i;
  231424. outputChannelInfo [numOutputChannelInfos].dataOffsetSamples = j;
  231425. outputChannelInfo [numOutputChannelInfos].dataStrideSamples = b.mNumberChannels;
  231426. ++numOutputChannelInfos;
  231427. }
  231428. if (name.isEmpty())
  231429. name << "Output " << (chanNum + 1);
  231430. outChanNames.add (name);
  231431. }
  231432. ++chanNum;
  231433. }
  231434. }
  231435. }
  231436. }
  231437. }
  231438. void updateDetailsFromDevice()
  231439. {
  231440. stopTimer();
  231441. if (deviceID == 0)
  231442. return;
  231443. const ScopedLock sl (callbackLock);
  231444. Float64 sr;
  231445. UInt32 size = sizeof (Float64);
  231446. AudioObjectPropertyAddress pa;
  231447. pa.mSelector = kAudioDevicePropertyNominalSampleRate;
  231448. pa.mScope = kAudioObjectPropertyScopeWildcard;
  231449. pa.mElement = kAudioObjectPropertyElementMaster;
  231450. if (OK (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &size, &sr)))
  231451. sampleRate = sr;
  231452. UInt32 framesPerBuf;
  231453. size = sizeof (framesPerBuf);
  231454. pa.mSelector = kAudioDevicePropertyBufferFrameSize;
  231455. if (OK (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &size, &framesPerBuf)))
  231456. {
  231457. bufferSize = framesPerBuf;
  231458. allocateTempBuffers();
  231459. }
  231460. bufferSizes.clear();
  231461. pa.mSelector = kAudioDevicePropertyBufferFrameSizeRange;
  231462. if (OK (AudioObjectGetPropertyDataSize (deviceID, &pa, 0, 0, &size)))
  231463. {
  231464. HeapBlock <AudioValueRange> ranges;
  231465. ranges.calloc (size, 1);
  231466. if (OK (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &size, ranges)))
  231467. {
  231468. bufferSizes.add ((int) ranges[0].mMinimum);
  231469. for (int i = 32; i < 2048; i += 32)
  231470. {
  231471. for (int j = size / (int) sizeof (AudioValueRange); --j >= 0;)
  231472. {
  231473. if (i >= ranges[j].mMinimum && i <= ranges[j].mMaximum)
  231474. {
  231475. bufferSizes.addIfNotAlreadyThere (i);
  231476. break;
  231477. }
  231478. }
  231479. }
  231480. if (bufferSize > 0)
  231481. bufferSizes.addIfNotAlreadyThere (bufferSize);
  231482. }
  231483. }
  231484. if (bufferSizes.size() == 0 && bufferSize > 0)
  231485. bufferSizes.add (bufferSize);
  231486. sampleRates.clear();
  231487. const double possibleRates[] = { 44100.0, 48000.0, 88200.0, 96000.0, 176400.0, 192000.0 };
  231488. String rates;
  231489. pa.mSelector = kAudioDevicePropertyAvailableNominalSampleRates;
  231490. if (OK (AudioObjectGetPropertyDataSize (deviceID, &pa, 0, 0, &size)))
  231491. {
  231492. HeapBlock <AudioValueRange> ranges;
  231493. ranges.calloc (size, 1);
  231494. if (OK (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &size, ranges)))
  231495. {
  231496. for (int i = 0; i < numElementsInArray (possibleRates); ++i)
  231497. {
  231498. bool ok = false;
  231499. for (int j = size / (int) sizeof (AudioValueRange); --j >= 0;)
  231500. if (possibleRates[i] >= ranges[j].mMinimum - 2 && possibleRates[i] <= ranges[j].mMaximum + 2)
  231501. ok = true;
  231502. if (ok)
  231503. {
  231504. sampleRates.add (possibleRates[i]);
  231505. rates << possibleRates[i] << ' ';
  231506. }
  231507. }
  231508. }
  231509. }
  231510. if (sampleRates.size() == 0 && sampleRate > 0)
  231511. {
  231512. sampleRates.add (sampleRate);
  231513. rates << sampleRate;
  231514. }
  231515. log ("sr: " + rates);
  231516. inputLatency = 0;
  231517. outputLatency = 0;
  231518. UInt32 lat;
  231519. size = sizeof (lat);
  231520. pa.mSelector = kAudioDevicePropertyLatency;
  231521. pa.mScope = kAudioDevicePropertyScopeInput;
  231522. //if (AudioDeviceGetProperty (deviceID, 0, true, kAudioDevicePropertyLatency, &size, &lat) == noErr)
  231523. if (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &size, &lat) == noErr)
  231524. inputLatency = (int) lat;
  231525. pa.mScope = kAudioDevicePropertyScopeOutput;
  231526. size = sizeof (lat);
  231527. if (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &size, &lat) == noErr)
  231528. outputLatency = (int) lat;
  231529. log ("lat: " + String (inputLatency) + " " + String (outputLatency));
  231530. inChanNames.clear();
  231531. outChanNames.clear();
  231532. inputChannelInfo.calloc (numInputChans + 2);
  231533. numInputChannelInfos = 0;
  231534. outputChannelInfo.calloc (numOutputChans + 2);
  231535. numOutputChannelInfos = 0;
  231536. fillInChannelInfo (true);
  231537. fillInChannelInfo (false);
  231538. }
  231539. const StringArray getSources (bool input)
  231540. {
  231541. StringArray s;
  231542. HeapBlock <OSType> types;
  231543. const int num = getAllDataSourcesForDevice (deviceID, types);
  231544. for (int i = 0; i < num; ++i)
  231545. {
  231546. AudioValueTranslation avt;
  231547. char buffer[256];
  231548. avt.mInputData = &(types[i]);
  231549. avt.mInputDataSize = sizeof (UInt32);
  231550. avt.mOutputData = buffer;
  231551. avt.mOutputDataSize = 256;
  231552. UInt32 transSize = sizeof (avt);
  231553. AudioObjectPropertyAddress pa;
  231554. pa.mSelector = kAudioDevicePropertyDataSourceNameForID;
  231555. pa.mScope = input ? kAudioDevicePropertyScopeInput : kAudioDevicePropertyScopeOutput;
  231556. pa.mElement = kAudioObjectPropertyElementMaster;
  231557. if (OK (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &transSize, &avt)))
  231558. {
  231559. DBG (buffer);
  231560. s.add (buffer);
  231561. }
  231562. }
  231563. return s;
  231564. }
  231565. int getCurrentSourceIndex (bool input) const
  231566. {
  231567. OSType currentSourceID = 0;
  231568. UInt32 size = sizeof (currentSourceID);
  231569. int result = -1;
  231570. AudioObjectPropertyAddress pa;
  231571. pa.mSelector = kAudioDevicePropertyDataSource;
  231572. pa.mScope = input ? kAudioDevicePropertyScopeInput : kAudioDevicePropertyScopeOutput;
  231573. pa.mElement = kAudioObjectPropertyElementMaster;
  231574. if (deviceID != 0)
  231575. {
  231576. if (OK (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &size, &currentSourceID)))
  231577. {
  231578. HeapBlock <OSType> types;
  231579. const int num = getAllDataSourcesForDevice (deviceID, types);
  231580. for (int i = 0; i < num; ++i)
  231581. {
  231582. if (types[num] == currentSourceID)
  231583. {
  231584. result = i;
  231585. break;
  231586. }
  231587. }
  231588. }
  231589. }
  231590. return result;
  231591. }
  231592. void setCurrentSourceIndex (int index, bool input)
  231593. {
  231594. if (deviceID != 0)
  231595. {
  231596. HeapBlock <OSType> types;
  231597. const int num = getAllDataSourcesForDevice (deviceID, types);
  231598. if (((unsigned int) index) < (unsigned int) num)
  231599. {
  231600. AudioObjectPropertyAddress pa;
  231601. pa.mSelector = kAudioDevicePropertyDataSource;
  231602. pa.mScope = input ? kAudioDevicePropertyScopeInput : kAudioDevicePropertyScopeOutput;
  231603. pa.mElement = kAudioObjectPropertyElementMaster;
  231604. OSType typeId = types[index];
  231605. OK (AudioObjectSetPropertyData (deviceID, &pa, 0, 0, sizeof (typeId), &typeId));
  231606. }
  231607. }
  231608. }
  231609. const String reopen (const BigInteger& inputChannels,
  231610. const BigInteger& outputChannels,
  231611. double newSampleRate,
  231612. int bufferSizeSamples)
  231613. {
  231614. String error;
  231615. log ("CoreAudio reopen");
  231616. callbacksAllowed = false;
  231617. stopTimer();
  231618. stop (false);
  231619. activeInputChans = inputChannels;
  231620. activeInputChans.setRange (inChanNames.size(),
  231621. activeInputChans.getHighestBit() + 1 - inChanNames.size(),
  231622. false);
  231623. activeOutputChans = outputChannels;
  231624. activeOutputChans.setRange (outChanNames.size(),
  231625. activeOutputChans.getHighestBit() + 1 - outChanNames.size(),
  231626. false);
  231627. numInputChans = activeInputChans.countNumberOfSetBits();
  231628. numOutputChans = activeOutputChans.countNumberOfSetBits();
  231629. // set sample rate
  231630. AudioObjectPropertyAddress pa;
  231631. pa.mSelector = kAudioDevicePropertyNominalSampleRate;
  231632. pa.mScope = kAudioObjectPropertyScopeWildcard;
  231633. pa.mElement = kAudioObjectPropertyElementMaster;
  231634. Float64 sr = newSampleRate;
  231635. if (! OK (AudioObjectSetPropertyData (deviceID, &pa, 0, 0, sizeof (sr), &sr)))
  231636. {
  231637. error = "Couldn't change sample rate";
  231638. }
  231639. else
  231640. {
  231641. // change buffer size
  231642. UInt32 framesPerBuf = bufferSizeSamples;
  231643. pa.mSelector = kAudioDevicePropertyBufferFrameSize;
  231644. if (! OK (AudioObjectSetPropertyData (deviceID, &pa, 0, 0, sizeof (framesPerBuf), &framesPerBuf)))
  231645. {
  231646. error = "Couldn't change buffer size";
  231647. }
  231648. else
  231649. {
  231650. // Annoyingly, after changing the rate and buffer size, some devices fail to
  231651. // correctly report their new settings until some random time in the future, so
  231652. // after calling updateDetailsFromDevice, we need to manually bodge these values
  231653. // to make sure we're using the correct numbers..
  231654. updateDetailsFromDevice();
  231655. sampleRate = newSampleRate;
  231656. bufferSize = bufferSizeSamples;
  231657. if (sampleRates.size() == 0)
  231658. error = "Device has no available sample-rates";
  231659. else if (bufferSizes.size() == 0)
  231660. error = "Device has no available buffer-sizes";
  231661. else if (inputDevice != 0)
  231662. error = inputDevice->reopen (inputChannels,
  231663. outputChannels,
  231664. newSampleRate,
  231665. bufferSizeSamples);
  231666. }
  231667. }
  231668. callbacksAllowed = true;
  231669. return error;
  231670. }
  231671. bool start (AudioIODeviceCallback* cb)
  231672. {
  231673. if (! started)
  231674. {
  231675. callback = 0;
  231676. if (deviceID != 0)
  231677. {
  231678. #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
  231679. if (OK (AudioDeviceAddIOProc (deviceID, audioIOProc, this)))
  231680. #else
  231681. if (OK (AudioDeviceCreateIOProcID (deviceID, audioIOProc, this, &audioProcID)))
  231682. #endif
  231683. {
  231684. if (OK (AudioDeviceStart (deviceID, audioIOProc)))
  231685. {
  231686. started = true;
  231687. }
  231688. else
  231689. {
  231690. #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
  231691. OK (AudioDeviceRemoveIOProc (deviceID, audioIOProc));
  231692. #else
  231693. OK (AudioDeviceDestroyIOProcID (deviceID, audioProcID));
  231694. audioProcID = 0;
  231695. #endif
  231696. }
  231697. }
  231698. }
  231699. }
  231700. if (started)
  231701. {
  231702. const ScopedLock sl (callbackLock);
  231703. callback = cb;
  231704. }
  231705. if (inputDevice != 0)
  231706. return started && inputDevice->start (cb);
  231707. else
  231708. return started;
  231709. }
  231710. void stop (bool leaveInterruptRunning)
  231711. {
  231712. {
  231713. const ScopedLock sl (callbackLock);
  231714. callback = 0;
  231715. }
  231716. if (started
  231717. && (deviceID != 0)
  231718. && ! leaveInterruptRunning)
  231719. {
  231720. OK (AudioDeviceStop (deviceID, audioIOProc));
  231721. #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
  231722. OK (AudioDeviceRemoveIOProc (deviceID, audioIOProc));
  231723. #else
  231724. OK (AudioDeviceDestroyIOProcID (deviceID, audioProcID));
  231725. audioProcID = 0;
  231726. #endif
  231727. started = false;
  231728. { const ScopedLock sl (callbackLock); }
  231729. // wait until it's definately stopped calling back..
  231730. for (int i = 40; --i >= 0;)
  231731. {
  231732. Thread::sleep (50);
  231733. UInt32 running = 0;
  231734. UInt32 size = sizeof (running);
  231735. AudioObjectPropertyAddress pa;
  231736. pa.mSelector = kAudioDevicePropertyDeviceIsRunning;
  231737. pa.mScope = kAudioObjectPropertyScopeWildcard;
  231738. pa.mElement = kAudioObjectPropertyElementMaster;
  231739. OK (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &size, &running));
  231740. if (running == 0)
  231741. break;
  231742. }
  231743. const ScopedLock sl (callbackLock);
  231744. }
  231745. if (inputDevice != 0)
  231746. inputDevice->stop (leaveInterruptRunning);
  231747. }
  231748. double getSampleRate() const
  231749. {
  231750. return sampleRate;
  231751. }
  231752. int getBufferSize() const
  231753. {
  231754. return bufferSize;
  231755. }
  231756. void audioCallback (const AudioBufferList* inInputData,
  231757. AudioBufferList* outOutputData)
  231758. {
  231759. int i;
  231760. const ScopedLock sl (callbackLock);
  231761. if (callback != 0)
  231762. {
  231763. if (inputDevice == 0)
  231764. {
  231765. for (i = numInputChans; --i >= 0;)
  231766. {
  231767. const CallbackDetailsForChannel& info = inputChannelInfo[i];
  231768. float* dest = tempInputBuffers [i];
  231769. const float* src = ((const float*) inInputData->mBuffers[info.streamNum].mData)
  231770. + info.dataOffsetSamples;
  231771. const int stride = info.dataStrideSamples;
  231772. if (stride != 0) // if this is zero, info is invalid
  231773. {
  231774. for (int j = bufferSize; --j >= 0;)
  231775. {
  231776. *dest++ = *src;
  231777. src += stride;
  231778. }
  231779. }
  231780. }
  231781. }
  231782. if (! isSlaveDevice)
  231783. {
  231784. if (inputDevice == 0)
  231785. {
  231786. callback->audioDeviceIOCallback (const_cast<const float**> (tempInputBuffers.getData()),
  231787. numInputChans,
  231788. tempOutputBuffers,
  231789. numOutputChans,
  231790. bufferSize);
  231791. }
  231792. else
  231793. {
  231794. jassert (inputDevice->bufferSize == bufferSize);
  231795. // Sometimes the two linked devices seem to get their callbacks in
  231796. // parallel, so we need to lock both devices to stop the input data being
  231797. // changed while inside our callback..
  231798. const ScopedLock sl2 (inputDevice->callbackLock);
  231799. callback->audioDeviceIOCallback (const_cast<const float**> (inputDevice->tempInputBuffers.getData()),
  231800. inputDevice->numInputChans,
  231801. tempOutputBuffers,
  231802. numOutputChans,
  231803. bufferSize);
  231804. }
  231805. for (i = numOutputChans; --i >= 0;)
  231806. {
  231807. const CallbackDetailsForChannel& info = outputChannelInfo[i];
  231808. const float* src = tempOutputBuffers [i];
  231809. float* dest = ((float*) outOutputData->mBuffers[info.streamNum].mData)
  231810. + info.dataOffsetSamples;
  231811. const int stride = info.dataStrideSamples;
  231812. if (stride != 0) // if this is zero, info is invalid
  231813. {
  231814. for (int j = bufferSize; --j >= 0;)
  231815. {
  231816. *dest = *src++;
  231817. dest += stride;
  231818. }
  231819. }
  231820. }
  231821. }
  231822. }
  231823. else
  231824. {
  231825. for (i = jmin (numOutputChans, numOutputChannelInfos); --i >= 0;)
  231826. {
  231827. const CallbackDetailsForChannel& info = outputChannelInfo[i];
  231828. float* dest = ((float*) outOutputData->mBuffers[info.streamNum].mData)
  231829. + info.dataOffsetSamples;
  231830. const int stride = info.dataStrideSamples;
  231831. if (stride != 0) // if this is zero, info is invalid
  231832. {
  231833. for (int j = bufferSize; --j >= 0;)
  231834. {
  231835. *dest = 0.0f;
  231836. dest += stride;
  231837. }
  231838. }
  231839. }
  231840. }
  231841. }
  231842. // called by callbacks
  231843. void deviceDetailsChanged()
  231844. {
  231845. if (callbacksAllowed)
  231846. startTimer (100);
  231847. }
  231848. void timerCallback()
  231849. {
  231850. stopTimer();
  231851. log ("CoreAudio device changed callback");
  231852. const double oldSampleRate = sampleRate;
  231853. const int oldBufferSize = bufferSize;
  231854. updateDetailsFromDevice();
  231855. if (oldBufferSize != bufferSize || oldSampleRate != sampleRate)
  231856. {
  231857. callbacksAllowed = false;
  231858. stop (false);
  231859. updateDetailsFromDevice();
  231860. callbacksAllowed = true;
  231861. }
  231862. }
  231863. CoreAudioInternal* getRelatedDevice() const
  231864. {
  231865. UInt32 size = 0;
  231866. ScopedPointer <CoreAudioInternal> result;
  231867. AudioObjectPropertyAddress pa;
  231868. pa.mSelector = kAudioDevicePropertyRelatedDevices;
  231869. pa.mScope = kAudioObjectPropertyScopeWildcard;
  231870. pa.mElement = kAudioObjectPropertyElementMaster;
  231871. if (deviceID != 0
  231872. && AudioObjectGetPropertyDataSize (deviceID, &pa, 0, 0, &size) == noErr
  231873. && size > 0)
  231874. {
  231875. HeapBlock <AudioDeviceID> devs;
  231876. devs.calloc (size, 1);
  231877. if (OK (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &size, devs)))
  231878. {
  231879. for (unsigned int i = 0; i < size / sizeof (AudioDeviceID); ++i)
  231880. {
  231881. if (devs[i] != deviceID && devs[i] != 0)
  231882. {
  231883. result = new CoreAudioInternal (devs[i]);
  231884. const bool thisIsInput = inChanNames.size() > 0 && outChanNames.size() == 0;
  231885. const bool otherIsInput = result->inChanNames.size() > 0 && result->outChanNames.size() == 0;
  231886. if (thisIsInput != otherIsInput
  231887. || (inChanNames.size() + outChanNames.size() == 0)
  231888. || (result->inChanNames.size() + result->outChanNames.size()) == 0)
  231889. break;
  231890. result = 0;
  231891. }
  231892. }
  231893. }
  231894. }
  231895. return result.release();
  231896. }
  231897. juce_UseDebuggingNewOperator
  231898. int inputLatency, outputLatency;
  231899. BigInteger activeInputChans, activeOutputChans;
  231900. StringArray inChanNames, outChanNames;
  231901. Array <double> sampleRates;
  231902. Array <int> bufferSizes;
  231903. AudioIODeviceCallback* callback;
  231904. #if MAC_OS_X_VERSION_MIN_REQUIRED >= MAC_OS_X_VERSION_10_5
  231905. AudioDeviceIOProcID audioProcID;
  231906. #endif
  231907. CoreAudioInternal* inputDevice;
  231908. bool isSlaveDevice;
  231909. private:
  231910. CriticalSection callbackLock;
  231911. AudioDeviceID deviceID;
  231912. bool started;
  231913. double sampleRate;
  231914. int bufferSize;
  231915. HeapBlock <float> audioBuffer;
  231916. int numInputChans, numOutputChans;
  231917. bool callbacksAllowed;
  231918. struct CallbackDetailsForChannel
  231919. {
  231920. int streamNum;
  231921. int dataOffsetSamples;
  231922. int dataStrideSamples;
  231923. };
  231924. int numInputChannelInfos, numOutputChannelInfos;
  231925. HeapBlock <CallbackDetailsForChannel> inputChannelInfo, outputChannelInfo;
  231926. HeapBlock <float*> tempInputBuffers, tempOutputBuffers;
  231927. CoreAudioInternal (const CoreAudioInternal&);
  231928. CoreAudioInternal& operator= (const CoreAudioInternal&);
  231929. static OSStatus audioIOProc (AudioDeviceID /*inDevice*/,
  231930. const AudioTimeStamp* /*inNow*/,
  231931. const AudioBufferList* inInputData,
  231932. const AudioTimeStamp* /*inInputTime*/,
  231933. AudioBufferList* outOutputData,
  231934. const AudioTimeStamp* /*inOutputTime*/,
  231935. void* device)
  231936. {
  231937. static_cast <CoreAudioInternal*> (device)->audioCallback (inInputData, outOutputData);
  231938. return noErr;
  231939. }
  231940. static OSStatus deviceListenerProc (AudioDeviceID /*inDevice*/, UInt32 /*inLine*/, const AudioObjectPropertyAddress* pa, void* inClientData)
  231941. {
  231942. CoreAudioInternal* const intern = static_cast <CoreAudioInternal*> (inClientData);
  231943. switch (pa->mSelector)
  231944. {
  231945. case kAudioDevicePropertyBufferSize:
  231946. case kAudioDevicePropertyBufferFrameSize:
  231947. case kAudioDevicePropertyNominalSampleRate:
  231948. case kAudioDevicePropertyStreamFormat:
  231949. case kAudioDevicePropertyDeviceIsAlive:
  231950. intern->deviceDetailsChanged();
  231951. break;
  231952. case kAudioDevicePropertyBufferSizeRange:
  231953. case kAudioDevicePropertyVolumeScalar:
  231954. case kAudioDevicePropertyMute:
  231955. case kAudioDevicePropertyPlayThru:
  231956. case kAudioDevicePropertyDataSource:
  231957. case kAudioDevicePropertyDeviceIsRunning:
  231958. break;
  231959. }
  231960. return noErr;
  231961. }
  231962. static int getAllDataSourcesForDevice (AudioDeviceID deviceID, HeapBlock <OSType>& types)
  231963. {
  231964. AudioObjectPropertyAddress pa;
  231965. pa.mSelector = kAudioDevicePropertyDataSources;
  231966. pa.mScope = kAudioObjectPropertyScopeWildcard;
  231967. pa.mElement = kAudioObjectPropertyElementMaster;
  231968. UInt32 size = 0;
  231969. if (deviceID != 0
  231970. && OK (AudioObjectGetPropertyDataSize (deviceID, &pa, 0, 0, &size)))
  231971. {
  231972. types.calloc (size, 1);
  231973. if (OK (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &size, types)))
  231974. return size / (int) sizeof (OSType);
  231975. }
  231976. return 0;
  231977. }
  231978. };
  231979. class CoreAudioIODevice : public AudioIODevice
  231980. {
  231981. public:
  231982. CoreAudioIODevice (const String& deviceName,
  231983. AudioDeviceID inputDeviceId,
  231984. const int inputIndex_,
  231985. AudioDeviceID outputDeviceId,
  231986. const int outputIndex_)
  231987. : AudioIODevice (deviceName, "CoreAudio"),
  231988. inputIndex (inputIndex_),
  231989. outputIndex (outputIndex_),
  231990. isOpen_ (false),
  231991. isStarted (false)
  231992. {
  231993. internal = 0;
  231994. CoreAudioInternal* device = 0;
  231995. if (outputDeviceId == 0 || outputDeviceId == inputDeviceId)
  231996. {
  231997. jassert (inputDeviceId != 0);
  231998. device = new CoreAudioInternal (inputDeviceId);
  231999. }
  232000. else
  232001. {
  232002. device = new CoreAudioInternal (outputDeviceId);
  232003. if (inputDeviceId != 0)
  232004. {
  232005. CoreAudioInternal* secondDevice = new CoreAudioInternal (inputDeviceId);
  232006. device->inputDevice = secondDevice;
  232007. secondDevice->isSlaveDevice = true;
  232008. }
  232009. }
  232010. internal = device;
  232011. AudioObjectPropertyAddress pa;
  232012. pa.mSelector = kAudioObjectPropertySelectorWildcard;
  232013. pa.mScope = kAudioObjectPropertyScopeWildcard;
  232014. pa.mElement = kAudioObjectPropertyElementWildcard;
  232015. AudioObjectAddPropertyListener (kAudioObjectSystemObject, &pa, hardwareListenerProc, internal);
  232016. }
  232017. ~CoreAudioIODevice()
  232018. {
  232019. AudioObjectPropertyAddress pa;
  232020. pa.mSelector = kAudioObjectPropertySelectorWildcard;
  232021. pa.mScope = kAudioObjectPropertyScopeWildcard;
  232022. pa.mElement = kAudioObjectPropertyElementWildcard;
  232023. AudioObjectRemovePropertyListener (kAudioObjectSystemObject, &pa, hardwareListenerProc, internal);
  232024. delete internal;
  232025. }
  232026. const StringArray getOutputChannelNames()
  232027. {
  232028. return internal->outChanNames;
  232029. }
  232030. const StringArray getInputChannelNames()
  232031. {
  232032. if (internal->inputDevice != 0)
  232033. return internal->inputDevice->inChanNames;
  232034. else
  232035. return internal->inChanNames;
  232036. }
  232037. int getNumSampleRates()
  232038. {
  232039. return internal->sampleRates.size();
  232040. }
  232041. double getSampleRate (int index)
  232042. {
  232043. return internal->sampleRates [index];
  232044. }
  232045. int getNumBufferSizesAvailable()
  232046. {
  232047. return internal->bufferSizes.size();
  232048. }
  232049. int getBufferSizeSamples (int index)
  232050. {
  232051. return internal->bufferSizes [index];
  232052. }
  232053. int getDefaultBufferSize()
  232054. {
  232055. for (int i = 0; i < getNumBufferSizesAvailable(); ++i)
  232056. if (getBufferSizeSamples(i) >= 512)
  232057. return getBufferSizeSamples(i);
  232058. return 512;
  232059. }
  232060. const String open (const BigInteger& inputChannels,
  232061. const BigInteger& outputChannels,
  232062. double sampleRate,
  232063. int bufferSizeSamples)
  232064. {
  232065. isOpen_ = true;
  232066. if (bufferSizeSamples <= 0)
  232067. bufferSizeSamples = getDefaultBufferSize();
  232068. lastError = internal->reopen (inputChannels, outputChannels, sampleRate, bufferSizeSamples);
  232069. isOpen_ = lastError.isEmpty();
  232070. return lastError;
  232071. }
  232072. void close()
  232073. {
  232074. isOpen_ = false;
  232075. internal->stop (false);
  232076. }
  232077. bool isOpen()
  232078. {
  232079. return isOpen_;
  232080. }
  232081. int getCurrentBufferSizeSamples()
  232082. {
  232083. return internal != 0 ? internal->getBufferSize() : 512;
  232084. }
  232085. double getCurrentSampleRate()
  232086. {
  232087. return internal != 0 ? internal->getSampleRate() : 0;
  232088. }
  232089. int getCurrentBitDepth()
  232090. {
  232091. return 32; // no way to find out, so just assume it's high..
  232092. }
  232093. const BigInteger getActiveOutputChannels() const
  232094. {
  232095. return internal != 0 ? internal->activeOutputChans : BigInteger();
  232096. }
  232097. const BigInteger getActiveInputChannels() const
  232098. {
  232099. BigInteger chans;
  232100. if (internal != 0)
  232101. {
  232102. chans = internal->activeInputChans;
  232103. if (internal->inputDevice != 0)
  232104. chans |= internal->inputDevice->activeInputChans;
  232105. }
  232106. return chans;
  232107. }
  232108. int getOutputLatencyInSamples()
  232109. {
  232110. if (internal == 0)
  232111. return 0;
  232112. // this seems like a good guess at getting the latency right - comparing
  232113. // this with a round-trip measurement, it gets it to within a few millisecs
  232114. // for the built-in mac soundcard
  232115. return internal->outputLatency + internal->getBufferSize() * 2;
  232116. }
  232117. int getInputLatencyInSamples()
  232118. {
  232119. if (internal == 0)
  232120. return 0;
  232121. return internal->inputLatency + internal->getBufferSize() * 2;
  232122. }
  232123. void start (AudioIODeviceCallback* callback)
  232124. {
  232125. if (internal != 0 && ! isStarted)
  232126. {
  232127. if (callback != 0)
  232128. callback->audioDeviceAboutToStart (this);
  232129. isStarted = true;
  232130. internal->start (callback);
  232131. }
  232132. }
  232133. void stop()
  232134. {
  232135. if (isStarted && internal != 0)
  232136. {
  232137. AudioIODeviceCallback* const lastCallback = internal->callback;
  232138. isStarted = false;
  232139. internal->stop (true);
  232140. if (lastCallback != 0)
  232141. lastCallback->audioDeviceStopped();
  232142. }
  232143. }
  232144. bool isPlaying()
  232145. {
  232146. if (internal->callback == 0)
  232147. isStarted = false;
  232148. return isStarted;
  232149. }
  232150. const String getLastError()
  232151. {
  232152. return lastError;
  232153. }
  232154. int inputIndex, outputIndex;
  232155. juce_UseDebuggingNewOperator
  232156. private:
  232157. CoreAudioInternal* internal;
  232158. bool isOpen_, isStarted;
  232159. String lastError;
  232160. static OSStatus hardwareListenerProc (AudioDeviceID /*inDevice*/, UInt32 /*inLine*/, const AudioObjectPropertyAddress* pa, void* inClientData)
  232161. {
  232162. CoreAudioInternal* const intern = static_cast <CoreAudioInternal*> (inClientData);
  232163. switch (pa->mSelector)
  232164. {
  232165. case kAudioHardwarePropertyDevices:
  232166. intern->deviceDetailsChanged();
  232167. break;
  232168. case kAudioHardwarePropertyDefaultOutputDevice:
  232169. case kAudioHardwarePropertyDefaultInputDevice:
  232170. case kAudioHardwarePropertyDefaultSystemOutputDevice:
  232171. break;
  232172. }
  232173. return noErr;
  232174. }
  232175. CoreAudioIODevice (const CoreAudioIODevice&);
  232176. CoreAudioIODevice& operator= (const CoreAudioIODevice&);
  232177. };
  232178. class CoreAudioIODeviceType : public AudioIODeviceType
  232179. {
  232180. public:
  232181. CoreAudioIODeviceType()
  232182. : AudioIODeviceType ("CoreAudio"),
  232183. hasScanned (false)
  232184. {
  232185. }
  232186. ~CoreAudioIODeviceType()
  232187. {
  232188. }
  232189. void scanForDevices()
  232190. {
  232191. hasScanned = true;
  232192. inputDeviceNames.clear();
  232193. outputDeviceNames.clear();
  232194. inputIds.clear();
  232195. outputIds.clear();
  232196. UInt32 size;
  232197. AudioObjectPropertyAddress pa;
  232198. pa.mSelector = kAudioHardwarePropertyDevices;
  232199. pa.mScope = kAudioObjectPropertyScopeWildcard;
  232200. pa.mElement = kAudioObjectPropertyElementMaster;
  232201. if (OK (AudioObjectGetPropertyDataSize (kAudioObjectSystemObject, &pa, 0, 0, &size)))
  232202. {
  232203. HeapBlock <AudioDeviceID> devs;
  232204. devs.calloc (size, 1);
  232205. if (OK (AudioObjectGetPropertyData (kAudioObjectSystemObject, &pa, 0, 0, &size, devs)))
  232206. {
  232207. static bool alreadyLogged = false;
  232208. const int num = size / (int) sizeof (AudioDeviceID);
  232209. for (int i = 0; i < num; ++i)
  232210. {
  232211. char name [1024];
  232212. size = sizeof (name);
  232213. pa.mSelector = kAudioDevicePropertyDeviceName;
  232214. if (OK (AudioObjectGetPropertyData (devs[i], &pa, 0, 0, &size, name)))
  232215. {
  232216. const String nameString (String::fromUTF8 (name, (int) strlen (name)));
  232217. if (! alreadyLogged)
  232218. log ("CoreAudio device: " + nameString);
  232219. const int numIns = getNumChannels (devs[i], true);
  232220. const int numOuts = getNumChannels (devs[i], false);
  232221. if (numIns > 0)
  232222. {
  232223. inputDeviceNames.add (nameString);
  232224. inputIds.add (devs[i]);
  232225. }
  232226. if (numOuts > 0)
  232227. {
  232228. outputDeviceNames.add (nameString);
  232229. outputIds.add (devs[i]);
  232230. }
  232231. }
  232232. }
  232233. alreadyLogged = true;
  232234. }
  232235. }
  232236. inputDeviceNames.appendNumbersToDuplicates (false, true);
  232237. outputDeviceNames.appendNumbersToDuplicates (false, true);
  232238. }
  232239. const StringArray getDeviceNames (bool wantInputNames) const
  232240. {
  232241. jassert (hasScanned); // need to call scanForDevices() before doing this
  232242. if (wantInputNames)
  232243. return inputDeviceNames;
  232244. else
  232245. return outputDeviceNames;
  232246. }
  232247. int getDefaultDeviceIndex (bool forInput) const
  232248. {
  232249. jassert (hasScanned); // need to call scanForDevices() before doing this
  232250. AudioDeviceID deviceID;
  232251. UInt32 size = sizeof (deviceID);
  232252. // if they're asking for any input channels at all, use the default input, so we
  232253. // get the built-in mic rather than the built-in output with no inputs..
  232254. AudioObjectPropertyAddress pa;
  232255. pa.mSelector = forInput ? kAudioHardwarePropertyDefaultInputDevice : kAudioHardwarePropertyDefaultOutputDevice;
  232256. pa.mScope = kAudioObjectPropertyScopeWildcard;
  232257. pa.mElement = kAudioObjectPropertyElementMaster;
  232258. if (AudioObjectGetPropertyData (kAudioObjectSystemObject, &pa, 0, 0, &size, &deviceID) == noErr)
  232259. {
  232260. if (forInput)
  232261. {
  232262. for (int i = inputIds.size(); --i >= 0;)
  232263. if (inputIds[i] == deviceID)
  232264. return i;
  232265. }
  232266. else
  232267. {
  232268. for (int i = outputIds.size(); --i >= 0;)
  232269. if (outputIds[i] == deviceID)
  232270. return i;
  232271. }
  232272. }
  232273. return 0;
  232274. }
  232275. int getIndexOfDevice (AudioIODevice* device, bool asInput) const
  232276. {
  232277. jassert (hasScanned); // need to call scanForDevices() before doing this
  232278. CoreAudioIODevice* const d = dynamic_cast <CoreAudioIODevice*> (device);
  232279. if (d == 0)
  232280. return -1;
  232281. return asInput ? d->inputIndex
  232282. : d->outputIndex;
  232283. }
  232284. bool hasSeparateInputsAndOutputs() const { return true; }
  232285. AudioIODevice* createDevice (const String& outputDeviceName,
  232286. const String& inputDeviceName)
  232287. {
  232288. jassert (hasScanned); // need to call scanForDevices() before doing this
  232289. const int inputIndex = inputDeviceNames.indexOf (inputDeviceName);
  232290. const int outputIndex = outputDeviceNames.indexOf (outputDeviceName);
  232291. String deviceName (outputDeviceName);
  232292. if (deviceName.isEmpty())
  232293. deviceName = inputDeviceName;
  232294. if (index >= 0)
  232295. return new CoreAudioIODevice (deviceName,
  232296. inputIds [inputIndex],
  232297. inputIndex,
  232298. outputIds [outputIndex],
  232299. outputIndex);
  232300. return 0;
  232301. }
  232302. juce_UseDebuggingNewOperator
  232303. private:
  232304. StringArray inputDeviceNames, outputDeviceNames;
  232305. Array <AudioDeviceID> inputIds, outputIds;
  232306. bool hasScanned;
  232307. static int getNumChannels (AudioDeviceID deviceID, bool input)
  232308. {
  232309. int total = 0;
  232310. UInt32 size;
  232311. AudioObjectPropertyAddress pa;
  232312. pa.mSelector = kAudioDevicePropertyStreamConfiguration;
  232313. pa.mScope = input ? kAudioDevicePropertyScopeInput : kAudioDevicePropertyScopeOutput;
  232314. pa.mElement = kAudioObjectPropertyElementMaster;
  232315. if (OK (AudioObjectGetPropertyDataSize (deviceID, &pa, 0, 0, &size)))
  232316. {
  232317. HeapBlock <AudioBufferList> bufList;
  232318. bufList.calloc (size, 1);
  232319. if (OK (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &size, bufList)))
  232320. {
  232321. const int numStreams = bufList->mNumberBuffers;
  232322. for (int i = 0; i < numStreams; ++i)
  232323. {
  232324. const AudioBuffer& b = bufList->mBuffers[i];
  232325. total += b.mNumberChannels;
  232326. }
  232327. }
  232328. }
  232329. return total;
  232330. }
  232331. CoreAudioIODeviceType (const CoreAudioIODeviceType&);
  232332. CoreAudioIODeviceType& operator= (const CoreAudioIODeviceType&);
  232333. };
  232334. AudioIODeviceType* juce_createAudioIODeviceType_CoreAudio()
  232335. {
  232336. return new CoreAudioIODeviceType();
  232337. }
  232338. #undef log
  232339. #endif
  232340. /*** End of inlined file: juce_mac_CoreAudio.cpp ***/
  232341. /*** Start of inlined file: juce_mac_CoreMidi.cpp ***/
  232342. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  232343. // compiled on its own).
  232344. #if JUCE_INCLUDED_FILE
  232345. #if JUCE_MAC
  232346. #undef log
  232347. #define log(a) Logger::writeToLog(a)
  232348. static bool logAnyErrorsMidi (const OSStatus err, const int lineNum)
  232349. {
  232350. if (err == noErr)
  232351. return true;
  232352. log ("CoreMidi error: " + String (lineNum) + " - " + String::toHexString ((int) err));
  232353. jassertfalse
  232354. return false;
  232355. }
  232356. #undef OK
  232357. #define OK(a) logAnyErrorsMidi(a, __LINE__)
  232358. static const String getEndpointName (MIDIEndpointRef endpoint, bool isExternal)
  232359. {
  232360. String result;
  232361. CFStringRef str = 0;
  232362. MIDIObjectGetStringProperty (endpoint, kMIDIPropertyName, &str);
  232363. if (str != 0)
  232364. {
  232365. result = PlatformUtilities::cfStringToJuceString (str);
  232366. CFRelease (str);
  232367. str = 0;
  232368. }
  232369. MIDIEntityRef entity = 0;
  232370. MIDIEndpointGetEntity (endpoint, &entity);
  232371. if (entity == 0)
  232372. return result; // probably virtual
  232373. if (result.isEmpty())
  232374. {
  232375. // endpoint name has zero length - try the entity
  232376. MIDIObjectGetStringProperty (entity, kMIDIPropertyName, &str);
  232377. if (str != 0)
  232378. {
  232379. result += PlatformUtilities::cfStringToJuceString (str);
  232380. CFRelease (str);
  232381. str = 0;
  232382. }
  232383. }
  232384. // now consider the device's name
  232385. MIDIDeviceRef device = 0;
  232386. MIDIEntityGetDevice (entity, &device);
  232387. if (device == 0)
  232388. return result;
  232389. MIDIObjectGetStringProperty (device, kMIDIPropertyName, &str);
  232390. if (str != 0)
  232391. {
  232392. const String s (PlatformUtilities::cfStringToJuceString (str));
  232393. CFRelease (str);
  232394. // if an external device has only one entity, throw away
  232395. // the endpoint name and just use the device name
  232396. if (isExternal && MIDIDeviceGetNumberOfEntities (device) < 2)
  232397. {
  232398. result = s;
  232399. }
  232400. else if (! result.startsWithIgnoreCase (s))
  232401. {
  232402. // prepend the device name to the entity name
  232403. result = (s + " " + result).trimEnd();
  232404. }
  232405. }
  232406. return result;
  232407. }
  232408. static const String getConnectedEndpointName (MIDIEndpointRef endpoint)
  232409. {
  232410. String result;
  232411. // Does the endpoint have connections?
  232412. CFDataRef connections = 0;
  232413. int numConnections = 0;
  232414. MIDIObjectGetDataProperty (endpoint, kMIDIPropertyConnectionUniqueID, &connections);
  232415. if (connections != 0)
  232416. {
  232417. numConnections = (int) (CFDataGetLength (connections) / sizeof (MIDIUniqueID));
  232418. if (numConnections > 0)
  232419. {
  232420. const SInt32* pid = reinterpret_cast <const SInt32*> (CFDataGetBytePtr (connections));
  232421. for (int i = 0; i < numConnections; ++i, ++pid)
  232422. {
  232423. MIDIUniqueID uid = EndianS32_BtoN (*pid);
  232424. MIDIObjectRef connObject;
  232425. MIDIObjectType connObjectType;
  232426. OSStatus err = MIDIObjectFindByUniqueID (uid, &connObject, &connObjectType);
  232427. if (err == noErr)
  232428. {
  232429. String s;
  232430. if (connObjectType == kMIDIObjectType_ExternalSource
  232431. || connObjectType == kMIDIObjectType_ExternalDestination)
  232432. {
  232433. // Connected to an external device's endpoint (10.3 and later).
  232434. s = getEndpointName (static_cast <MIDIEndpointRef> (connObject), true);
  232435. }
  232436. else
  232437. {
  232438. // Connected to an external device (10.2) (or something else, catch-all)
  232439. CFStringRef str = 0;
  232440. MIDIObjectGetStringProperty (connObject, kMIDIPropertyName, &str);
  232441. if (str != 0)
  232442. {
  232443. s = PlatformUtilities::cfStringToJuceString (str);
  232444. CFRelease (str);
  232445. }
  232446. }
  232447. if (s.isNotEmpty())
  232448. {
  232449. if (result.isNotEmpty())
  232450. result += ", ";
  232451. result += s;
  232452. }
  232453. }
  232454. }
  232455. }
  232456. CFRelease (connections);
  232457. }
  232458. if (result.isNotEmpty())
  232459. return result;
  232460. // Here, either the endpoint had no connections, or we failed to obtain names for any of them.
  232461. return getEndpointName (endpoint, false);
  232462. }
  232463. const StringArray MidiOutput::getDevices()
  232464. {
  232465. StringArray s;
  232466. const ItemCount num = MIDIGetNumberOfDestinations();
  232467. for (ItemCount i = 0; i < num; ++i)
  232468. {
  232469. MIDIEndpointRef dest = MIDIGetDestination (i);
  232470. if (dest != 0)
  232471. {
  232472. String name (getConnectedEndpointName (dest));
  232473. if (name.isEmpty())
  232474. name = "<error>";
  232475. s.add (name);
  232476. }
  232477. else
  232478. {
  232479. s.add ("<error>");
  232480. }
  232481. }
  232482. return s;
  232483. }
  232484. int MidiOutput::getDefaultDeviceIndex()
  232485. {
  232486. return 0;
  232487. }
  232488. static MIDIClientRef globalMidiClient;
  232489. static bool hasGlobalClientBeenCreated = false;
  232490. static bool makeSureClientExists()
  232491. {
  232492. if (! hasGlobalClientBeenCreated)
  232493. {
  232494. String name ("JUCE");
  232495. if (JUCEApplication::getInstance() != 0)
  232496. name = JUCEApplication::getInstance()->getApplicationName();
  232497. CFStringRef appName = PlatformUtilities::juceStringToCFString (name);
  232498. hasGlobalClientBeenCreated = OK (MIDIClientCreate (appName, 0, 0, &globalMidiClient));
  232499. CFRelease (appName);
  232500. }
  232501. return hasGlobalClientBeenCreated;
  232502. }
  232503. class MidiPortAndEndpoint
  232504. {
  232505. public:
  232506. MidiPortAndEndpoint (MIDIPortRef port_, MIDIEndpointRef endPoint_)
  232507. : port (port_), endPoint (endPoint_)
  232508. {
  232509. }
  232510. ~MidiPortAndEndpoint()
  232511. {
  232512. if (port != 0)
  232513. MIDIPortDispose (port);
  232514. if (port == 0 && endPoint != 0) // if port == 0, it means we created the endpoint, so it's safe to delete it
  232515. MIDIEndpointDispose (endPoint);
  232516. }
  232517. MIDIPortRef port;
  232518. MIDIEndpointRef endPoint;
  232519. };
  232520. MidiOutput* MidiOutput::openDevice (int index)
  232521. {
  232522. MidiOutput* mo = 0;
  232523. if (((unsigned int) index) < (unsigned int) MIDIGetNumberOfDestinations())
  232524. {
  232525. MIDIEndpointRef endPoint = MIDIGetDestination (index);
  232526. CFStringRef pname;
  232527. if (OK (MIDIObjectGetStringProperty (endPoint, kMIDIPropertyName, &pname)))
  232528. {
  232529. log ("CoreMidi - opening out: " + PlatformUtilities::cfStringToJuceString (pname));
  232530. if (makeSureClientExists())
  232531. {
  232532. MIDIPortRef port;
  232533. if (OK (MIDIOutputPortCreate (globalMidiClient, pname, &port)))
  232534. {
  232535. mo = new MidiOutput();
  232536. mo->internal = new MidiPortAndEndpoint (port, endPoint);
  232537. }
  232538. }
  232539. CFRelease (pname);
  232540. }
  232541. }
  232542. return mo;
  232543. }
  232544. MidiOutput* MidiOutput::createNewDevice (const String& deviceName)
  232545. {
  232546. MidiOutput* mo = 0;
  232547. if (makeSureClientExists())
  232548. {
  232549. MIDIEndpointRef endPoint;
  232550. CFStringRef name = PlatformUtilities::juceStringToCFString (deviceName);
  232551. if (OK (MIDISourceCreate (globalMidiClient, name, &endPoint)))
  232552. {
  232553. mo = new MidiOutput();
  232554. mo->internal = new MidiPortAndEndpoint (0, endPoint);
  232555. }
  232556. CFRelease (name);
  232557. }
  232558. return mo;
  232559. }
  232560. MidiOutput::~MidiOutput()
  232561. {
  232562. delete (MidiPortAndEndpoint*) internal;
  232563. }
  232564. void MidiOutput::reset()
  232565. {
  232566. }
  232567. bool MidiOutput::getVolume (float& /*leftVol*/, float& /*rightVol*/)
  232568. {
  232569. return false;
  232570. }
  232571. void MidiOutput::setVolume (float /*leftVol*/, float /*rightVol*/)
  232572. {
  232573. }
  232574. void MidiOutput::sendMessageNow (const MidiMessage& message)
  232575. {
  232576. MidiPortAndEndpoint* const mpe = (MidiPortAndEndpoint*) internal;
  232577. if (message.isSysEx())
  232578. {
  232579. const int maxPacketSize = 256;
  232580. int pos = 0, bytesLeft = message.getRawDataSize();
  232581. const int numPackets = (bytesLeft + maxPacketSize - 1) / maxPacketSize;
  232582. HeapBlock <MIDIPacketList> packets;
  232583. packets.malloc (32 * numPackets + message.getRawDataSize(), 1);
  232584. packets->numPackets = numPackets;
  232585. MIDIPacket* p = packets->packet;
  232586. for (int i = 0; i < numPackets; ++i)
  232587. {
  232588. p->timeStamp = 0;
  232589. p->length = jmin (maxPacketSize, bytesLeft);
  232590. memcpy (p->data, message.getRawData() + pos, p->length);
  232591. pos += p->length;
  232592. bytesLeft -= p->length;
  232593. p = MIDIPacketNext (p);
  232594. }
  232595. if (mpe->port != 0)
  232596. MIDISend (mpe->port, mpe->endPoint, packets);
  232597. else
  232598. MIDIReceived (mpe->endPoint, packets);
  232599. }
  232600. else
  232601. {
  232602. MIDIPacketList packets;
  232603. packets.numPackets = 1;
  232604. packets.packet[0].timeStamp = 0;
  232605. packets.packet[0].length = message.getRawDataSize();
  232606. *(int*) (packets.packet[0].data) = *(const int*) message.getRawData();
  232607. if (mpe->port != 0)
  232608. MIDISend (mpe->port, mpe->endPoint, &packets);
  232609. else
  232610. MIDIReceived (mpe->endPoint, &packets);
  232611. }
  232612. }
  232613. const StringArray MidiInput::getDevices()
  232614. {
  232615. StringArray s;
  232616. const ItemCount num = MIDIGetNumberOfSources();
  232617. for (ItemCount i = 0; i < num; ++i)
  232618. {
  232619. MIDIEndpointRef source = MIDIGetSource (i);
  232620. if (source != 0)
  232621. {
  232622. String name (getConnectedEndpointName (source));
  232623. if (name.isEmpty())
  232624. name = "<error>";
  232625. s.add (name);
  232626. }
  232627. else
  232628. {
  232629. s.add ("<error>");
  232630. }
  232631. }
  232632. return s;
  232633. }
  232634. int MidiInput::getDefaultDeviceIndex()
  232635. {
  232636. return 0;
  232637. }
  232638. struct MidiPortAndCallback
  232639. {
  232640. MidiInput* input;
  232641. MidiPortAndEndpoint* portAndEndpoint;
  232642. MidiInputCallback* callback;
  232643. MemoryBlock pendingData;
  232644. int pendingBytes;
  232645. double pendingDataTime;
  232646. bool active;
  232647. void processSysex (const uint8*& d, int& size, const double time)
  232648. {
  232649. if (*d == 0xf0)
  232650. {
  232651. pendingBytes = 0;
  232652. pendingDataTime = time;
  232653. }
  232654. pendingData.ensureSize (pendingBytes + size, false);
  232655. uint8* totalMessage = (uint8*) pendingData.getData();
  232656. uint8* dest = totalMessage + pendingBytes;
  232657. while (size > 0)
  232658. {
  232659. if (pendingBytes > 0 && *d >= 0x80)
  232660. {
  232661. if (*d >= 0xfa || *d == 0xf8)
  232662. {
  232663. callback->handleIncomingMidiMessage (input, MidiMessage (*d, time));
  232664. ++d;
  232665. --size;
  232666. }
  232667. else
  232668. {
  232669. if (*d == 0xf7)
  232670. {
  232671. *dest++ = *d++;
  232672. pendingBytes++;
  232673. --size;
  232674. }
  232675. break;
  232676. }
  232677. }
  232678. else
  232679. {
  232680. *dest++ = *d++;
  232681. pendingBytes++;
  232682. --size;
  232683. }
  232684. }
  232685. if (totalMessage [pendingBytes - 1] == 0xf7)
  232686. {
  232687. callback->handleIncomingMidiMessage (input, MidiMessage (totalMessage, pendingBytes, pendingDataTime));
  232688. pendingBytes = 0;
  232689. }
  232690. else
  232691. {
  232692. callback->handlePartialSysexMessage (input, totalMessage, pendingBytes, pendingDataTime);
  232693. }
  232694. }
  232695. };
  232696. namespace CoreMidiCallbacks
  232697. {
  232698. static CriticalSection callbackLock;
  232699. static VoidArray activeCallbacks;
  232700. }
  232701. static void midiInputProc (const MIDIPacketList* pktlist,
  232702. void* readProcRefCon,
  232703. void* /*srcConnRefCon*/)
  232704. {
  232705. double time = Time::getMillisecondCounterHiRes() * 0.001;
  232706. const double originalTime = time;
  232707. MidiPortAndCallback* const mpc = (MidiPortAndCallback*) readProcRefCon;
  232708. const ScopedLock sl (CoreMidiCallbacks::callbackLock);
  232709. if (CoreMidiCallbacks::activeCallbacks.contains (mpc) && mpc->active)
  232710. {
  232711. const MIDIPacket* packet = &pktlist->packet[0];
  232712. for (unsigned int i = 0; i < pktlist->numPackets; ++i)
  232713. {
  232714. const uint8* d = (const uint8*) (packet->data);
  232715. int size = packet->length;
  232716. while (size > 0)
  232717. {
  232718. time = originalTime;
  232719. if (mpc->pendingBytes > 0 || d[0] == 0xf0)
  232720. {
  232721. mpc->processSysex (d, size, time);
  232722. }
  232723. else
  232724. {
  232725. int used = 0;
  232726. const MidiMessage m (d, size, used, 0, time);
  232727. if (used <= 0)
  232728. {
  232729. jassertfalse // malformed midi message
  232730. break;
  232731. }
  232732. else
  232733. {
  232734. mpc->callback->handleIncomingMidiMessage (mpc->input, m);
  232735. }
  232736. size -= used;
  232737. d += used;
  232738. }
  232739. }
  232740. packet = MIDIPacketNext (packet);
  232741. }
  232742. }
  232743. }
  232744. MidiInput* MidiInput::openDevice (int index, MidiInputCallback* callback)
  232745. {
  232746. MidiInput* mi = 0;
  232747. if (((unsigned int) index) < (unsigned int) MIDIGetNumberOfSources())
  232748. {
  232749. MIDIEndpointRef endPoint = MIDIGetSource (index);
  232750. if (endPoint != 0)
  232751. {
  232752. CFStringRef pname;
  232753. if (OK (MIDIObjectGetStringProperty (endPoint, kMIDIPropertyName, &pname)))
  232754. {
  232755. log ("CoreMidi - opening inp: " + PlatformUtilities::cfStringToJuceString (pname));
  232756. if (makeSureClientExists())
  232757. {
  232758. MIDIPortRef port;
  232759. ScopedPointer <MidiPortAndCallback> mpc (new MidiPortAndCallback());
  232760. mpc->active = false;
  232761. if (OK (MIDIInputPortCreate (globalMidiClient, pname, midiInputProc, mpc, &port)))
  232762. {
  232763. if (OK (MIDIPortConnectSource (port, endPoint, 0)))
  232764. {
  232765. mpc->portAndEndpoint = new MidiPortAndEndpoint (port, endPoint);
  232766. mpc->callback = callback;
  232767. mpc->pendingBytes = 0;
  232768. mpc->pendingData.ensureSize (128);
  232769. mi = new MidiInput (getDevices() [index]);
  232770. mpc->input = mi;
  232771. mi->internal = mpc;
  232772. const ScopedLock sl (CoreMidiCallbacks::callbackLock);
  232773. CoreMidiCallbacks::activeCallbacks.add (mpc.release());
  232774. }
  232775. else
  232776. {
  232777. OK (MIDIPortDispose (port));
  232778. }
  232779. }
  232780. }
  232781. }
  232782. CFRelease (pname);
  232783. }
  232784. }
  232785. return mi;
  232786. }
  232787. MidiInput* MidiInput::createNewDevice (const String& deviceName, MidiInputCallback* callback)
  232788. {
  232789. MidiInput* mi = 0;
  232790. if (makeSureClientExists())
  232791. {
  232792. ScopedPointer <MidiPortAndCallback> mpc (new MidiPortAndCallback());
  232793. mpc->active = false;
  232794. MIDIEndpointRef endPoint;
  232795. CFStringRef name = PlatformUtilities::juceStringToCFString(deviceName);
  232796. if (OK (MIDIDestinationCreate (globalMidiClient, name, midiInputProc, mpc, &endPoint)))
  232797. {
  232798. mpc->portAndEndpoint = new MidiPortAndEndpoint (0, endPoint);
  232799. mpc->callback = callback;
  232800. mpc->pendingBytes = 0;
  232801. mpc->pendingData.ensureSize (128);
  232802. mi = new MidiInput (deviceName);
  232803. mpc->input = mi;
  232804. mi->internal = mpc;
  232805. const ScopedLock sl (CoreMidiCallbacks::callbackLock);
  232806. CoreMidiCallbacks::activeCallbacks.add (mpc.release());
  232807. }
  232808. CFRelease (name);
  232809. }
  232810. return mi;
  232811. }
  232812. MidiInput::MidiInput (const String& name_)
  232813. : name (name_)
  232814. {
  232815. }
  232816. MidiInput::~MidiInput()
  232817. {
  232818. MidiPortAndCallback* const mpc = (MidiPortAndCallback*) internal;
  232819. mpc->active = false;
  232820. {
  232821. const ScopedLock sl (CoreMidiCallbacks::callbackLock);
  232822. CoreMidiCallbacks::activeCallbacks.removeValue (mpc);
  232823. }
  232824. if (mpc->portAndEndpoint->port != 0)
  232825. OK (MIDIPortDisconnectSource (mpc->portAndEndpoint->port, mpc->portAndEndpoint->endPoint));
  232826. delete mpc->portAndEndpoint;
  232827. delete mpc;
  232828. }
  232829. void MidiInput::start()
  232830. {
  232831. const ScopedLock sl (CoreMidiCallbacks::callbackLock);
  232832. ((MidiPortAndCallback*) internal)->active = true;
  232833. }
  232834. void MidiInput::stop()
  232835. {
  232836. const ScopedLock sl (CoreMidiCallbacks::callbackLock);
  232837. ((MidiPortAndCallback*) internal)->active = false;
  232838. }
  232839. #undef log
  232840. #else
  232841. MidiOutput::~MidiOutput()
  232842. {
  232843. }
  232844. void MidiOutput::reset()
  232845. {
  232846. }
  232847. bool MidiOutput::getVolume (float& /*leftVol*/, float& /*rightVol*/)
  232848. {
  232849. return false;
  232850. }
  232851. void MidiOutput::setVolume (float /*leftVol*/, float /*rightVol*/)
  232852. {
  232853. }
  232854. void MidiOutput::sendMessageNow (const MidiMessage& message)
  232855. {
  232856. }
  232857. const StringArray MidiOutput::getDevices()
  232858. {
  232859. return StringArray();
  232860. }
  232861. MidiOutput* MidiOutput::openDevice (int index)
  232862. {
  232863. return 0;
  232864. }
  232865. const StringArray MidiInput::getDevices()
  232866. {
  232867. return StringArray();
  232868. }
  232869. MidiInput* MidiInput::openDevice (int index, MidiInputCallback* callback)
  232870. {
  232871. return 0;
  232872. }
  232873. #endif
  232874. #endif
  232875. /*** End of inlined file: juce_mac_CoreMidi.cpp ***/
  232876. /*** Start of inlined file: juce_mac_CameraDevice.mm ***/
  232877. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  232878. // compiled on its own).
  232879. #if JUCE_INCLUDED_FILE && JUCE_USE_CAMERA
  232880. #if ! JUCE_QUICKTIME
  232881. #error "On the Mac, cameras use Quicktime, so if you turn on JUCE_USE_CAMERA, you also need to enable JUCE_QUICKTIME"
  232882. #endif
  232883. #define QTCaptureCallbackDelegate MakeObjCClassName(QTCaptureCallbackDelegate)
  232884. class QTCameraDeviceInteral;
  232885. END_JUCE_NAMESPACE
  232886. @interface QTCaptureCallbackDelegate : NSObject
  232887. {
  232888. @public
  232889. CameraDevice* owner;
  232890. QTCameraDeviceInteral* internal;
  232891. int64 firstPresentationTime;
  232892. int64 averageTimeOffset;
  232893. }
  232894. - (QTCaptureCallbackDelegate*) initWithOwner: (CameraDevice*) owner internalDev: (QTCameraDeviceInteral*) d;
  232895. - (void) dealloc;
  232896. - (void) captureOutput: (QTCaptureOutput*) captureOutput
  232897. didOutputVideoFrame: (CVImageBufferRef) videoFrame
  232898. withSampleBuffer: (QTSampleBuffer*) sampleBuffer
  232899. fromConnection: (QTCaptureConnection*) connection;
  232900. - (void) captureOutput: (QTCaptureFileOutput*) captureOutput
  232901. didOutputSampleBuffer: (QTSampleBuffer*) sampleBuffer
  232902. fromConnection: (QTCaptureConnection*) connection;
  232903. @end
  232904. BEGIN_JUCE_NAMESPACE
  232905. class QTCameraDeviceInteral
  232906. {
  232907. public:
  232908. QTCameraDeviceInteral (CameraDevice* owner, int index)
  232909. {
  232910. const ScopedAutoReleasePool pool;
  232911. session = [[QTCaptureSession alloc] init];
  232912. NSArray* devs = [QTCaptureDevice inputDevicesWithMediaType: QTMediaTypeVideo];
  232913. device = (QTCaptureDevice*) [devs objectAtIndex: index];
  232914. input = 0;
  232915. audioInput = 0;
  232916. audioDevice = 0;
  232917. fileOutput = 0;
  232918. imageOutput = 0;
  232919. callbackDelegate = [[QTCaptureCallbackDelegate alloc] initWithOwner: owner
  232920. internalDev: this];
  232921. NSError* err = 0;
  232922. [device retain];
  232923. [device open: &err];
  232924. if (err == 0)
  232925. {
  232926. input = [[QTCaptureDeviceInput alloc] initWithDevice: device];
  232927. audioInput = [[QTCaptureDeviceInput alloc] initWithDevice: device];
  232928. [session addInput: input error: &err];
  232929. if (err == 0)
  232930. {
  232931. resetFile();
  232932. imageOutput = [[QTCaptureDecompressedVideoOutput alloc] init];
  232933. [imageOutput setDelegate: callbackDelegate];
  232934. if (err == 0)
  232935. {
  232936. [session startRunning];
  232937. return;
  232938. }
  232939. }
  232940. }
  232941. openingError = nsStringToJuce ([err description]);
  232942. DBG (openingError);
  232943. }
  232944. ~QTCameraDeviceInteral()
  232945. {
  232946. [session stopRunning];
  232947. [session removeOutput: imageOutput];
  232948. [session release];
  232949. [input release];
  232950. [device release];
  232951. [audioDevice release];
  232952. [audioInput release];
  232953. [fileOutput release];
  232954. [imageOutput release];
  232955. [callbackDelegate release];
  232956. }
  232957. void resetFile()
  232958. {
  232959. [fileOutput recordToOutputFileURL: nil];
  232960. [session removeOutput: fileOutput];
  232961. [fileOutput release];
  232962. fileOutput = [[QTCaptureMovieFileOutput alloc] init];
  232963. [session removeInput: audioInput];
  232964. [audioInput release];
  232965. audioInput = 0;
  232966. [audioDevice release];
  232967. audioDevice = 0;
  232968. [fileOutput setDelegate: callbackDelegate];
  232969. }
  232970. void addDefaultAudioInput()
  232971. {
  232972. NSError* err = nil;
  232973. audioDevice = [QTCaptureDevice defaultInputDeviceWithMediaType: QTMediaTypeSound];
  232974. if ([audioDevice open: &err])
  232975. [audioDevice retain];
  232976. else
  232977. audioDevice = nil;
  232978. if (audioDevice != 0)
  232979. {
  232980. audioInput = [[QTCaptureDeviceInput alloc] initWithDevice: audioDevice];
  232981. [session addInput: audioInput error: &err];
  232982. }
  232983. }
  232984. void addListener (CameraImageListener* listenerToAdd)
  232985. {
  232986. const ScopedLock sl (listenerLock);
  232987. if (listeners.size() == 0)
  232988. [session addOutput: imageOutput error: nil];
  232989. listeners.addIfNotAlreadyThere (listenerToAdd);
  232990. }
  232991. void removeListener (CameraImageListener* listenerToRemove)
  232992. {
  232993. const ScopedLock sl (listenerLock);
  232994. listeners.removeValue (listenerToRemove);
  232995. if (listeners.size() == 0)
  232996. [session removeOutput: imageOutput];
  232997. }
  232998. void callListeners (CIImage* frame, int w, int h)
  232999. {
  233000. CoreGraphicsImage image (Image::ARGB, w, h, false);
  233001. CIContext* cic = [CIContext contextWithCGContext: image.context options: nil];
  233002. [cic drawImage: frame inRect: CGRectMake (0, 0, w, h) fromRect: CGRectMake (0, 0, w, h)];
  233003. CGContextFlush (image.context);
  233004. const ScopedLock sl (listenerLock);
  233005. for (int i = listeners.size(); --i >= 0;)
  233006. {
  233007. CameraImageListener* l = (CameraImageListener*) listeners[i];
  233008. if (l != 0)
  233009. l->imageReceived (image);
  233010. }
  233011. }
  233012. QTCaptureDevice* device;
  233013. QTCaptureDeviceInput* input;
  233014. QTCaptureDevice* audioDevice;
  233015. QTCaptureDeviceInput* audioInput;
  233016. QTCaptureSession* session;
  233017. QTCaptureMovieFileOutput* fileOutput;
  233018. QTCaptureDecompressedVideoOutput* imageOutput;
  233019. QTCaptureCallbackDelegate* callbackDelegate;
  233020. String openingError;
  233021. VoidArray listeners;
  233022. CriticalSection listenerLock;
  233023. };
  233024. END_JUCE_NAMESPACE
  233025. @implementation QTCaptureCallbackDelegate
  233026. - (QTCaptureCallbackDelegate*) initWithOwner: (CameraDevice*) owner_
  233027. internalDev: (QTCameraDeviceInteral*) d
  233028. {
  233029. [super init];
  233030. owner = owner_;
  233031. internal = d;
  233032. firstPresentationTime = 0;
  233033. averageTimeOffset = 0;
  233034. return self;
  233035. }
  233036. - (void) dealloc
  233037. {
  233038. [super dealloc];
  233039. }
  233040. - (void) captureOutput: (QTCaptureOutput*) captureOutput
  233041. didOutputVideoFrame: (CVImageBufferRef) videoFrame
  233042. withSampleBuffer: (QTSampleBuffer*) sampleBuffer
  233043. fromConnection: (QTCaptureConnection*) connection
  233044. {
  233045. if (internal->listeners.size() > 0)
  233046. {
  233047. const ScopedAutoReleasePool pool;
  233048. internal->callListeners ([CIImage imageWithCVImageBuffer: videoFrame],
  233049. CVPixelBufferGetWidth (videoFrame),
  233050. CVPixelBufferGetHeight (videoFrame));
  233051. }
  233052. }
  233053. - (void) captureOutput: (QTCaptureFileOutput*) captureOutput
  233054. didOutputSampleBuffer: (QTSampleBuffer*) sampleBuffer
  233055. fromConnection: (QTCaptureConnection*) connection
  233056. {
  233057. const Time now (Time::getCurrentTime());
  233058. #if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_5
  233059. NSNumber* hosttime = (NSNumber*) [sampleBuffer attributeForKey: QTSampleBufferHostTimeAttribute];
  233060. #else
  233061. NSNumber* hosttime = (NSNumber*) [sampleBuffer attributeForKey: @"hostTime"];
  233062. #endif
  233063. int64 presentationTime = (hosttime != nil)
  233064. ? ((int64) AudioConvertHostTimeToNanos ([hosttime unsignedLongLongValue]) / 1000000 + 40)
  233065. : (([sampleBuffer presentationTime].timeValue * 1000) / [sampleBuffer presentationTime].timeScale + 50);
  233066. const int64 timeDiff = now.toMilliseconds() - presentationTime;
  233067. if (firstPresentationTime == 0)
  233068. {
  233069. firstPresentationTime = presentationTime;
  233070. averageTimeOffset = timeDiff;
  233071. }
  233072. else
  233073. {
  233074. averageTimeOffset = (averageTimeOffset * 120 + timeDiff * 8) / 128;
  233075. }
  233076. }
  233077. @end
  233078. BEGIN_JUCE_NAMESPACE
  233079. class QTCaptureViewerComp : public NSViewComponent
  233080. {
  233081. public:
  233082. QTCaptureViewerComp (CameraDevice* const cameraDevice, QTCameraDeviceInteral* const internal)
  233083. {
  233084. const ScopedAutoReleasePool pool;
  233085. captureView = [[QTCaptureView alloc] init];
  233086. [captureView setCaptureSession: internal->session];
  233087. setSize (640, 480); // xxx need to somehow get the movie size - how?
  233088. setView (captureView);
  233089. }
  233090. ~QTCaptureViewerComp()
  233091. {
  233092. setView (0);
  233093. [captureView setCaptureSession: nil];
  233094. [captureView release];
  233095. }
  233096. QTCaptureView* captureView;
  233097. };
  233098. CameraDevice::CameraDevice (const String& name_, int index)
  233099. : name (name_)
  233100. {
  233101. isRecording = false;
  233102. internal = new QTCameraDeviceInteral (this, index);
  233103. }
  233104. CameraDevice::~CameraDevice()
  233105. {
  233106. stopRecording();
  233107. delete static_cast <QTCameraDeviceInteral*> (internal);
  233108. internal = 0;
  233109. }
  233110. Component* CameraDevice::createViewerComponent()
  233111. {
  233112. return new QTCaptureViewerComp (this, static_cast <QTCameraDeviceInteral*> (internal));
  233113. }
  233114. const String CameraDevice::getFileExtension()
  233115. {
  233116. return ".mov";
  233117. }
  233118. void CameraDevice::startRecordingToFile (const File& file, int quality)
  233119. {
  233120. stopRecording();
  233121. QTCameraDeviceInteral* const d = static_cast <QTCameraDeviceInteral*> (internal);
  233122. d->callbackDelegate->firstPresentationTime = 0;
  233123. file.deleteFile();
  233124. // In some versions of QT (e.g. on 10.5), if you record video without audio, the speed comes
  233125. // out wrong, so we'll put some audio in there too..,
  233126. d->addDefaultAudioInput();
  233127. [d->session addOutput: d->fileOutput error: nil];
  233128. NSEnumerator* connectionEnumerator = [[d->fileOutput connections] objectEnumerator];
  233129. for (;;)
  233130. {
  233131. QTCaptureConnection* connection = [connectionEnumerator nextObject];
  233132. if (connection == 0)
  233133. break;
  233134. QTCompressionOptions* options = 0;
  233135. NSString* mediaType = [connection mediaType];
  233136. if ([mediaType isEqualToString: QTMediaTypeVideo])
  233137. options = [QTCompressionOptions compressionOptionsWithIdentifier:
  233138. quality >= 1 ? @"QTCompressionOptionsSD480SizeH264Video"
  233139. : @"QTCompressionOptions240SizeH264Video"];
  233140. else if ([mediaType isEqualToString: QTMediaTypeSound])
  233141. options = [QTCompressionOptions compressionOptionsWithIdentifier: @"QTCompressionOptionsHighQualityAACAudio"];
  233142. [d->fileOutput setCompressionOptions: options forConnection: connection];
  233143. }
  233144. [d->fileOutput recordToOutputFileURL: [NSURL fileURLWithPath: juceStringToNS (file.getFullPathName())]];
  233145. isRecording = true;
  233146. }
  233147. const Time CameraDevice::getTimeOfFirstRecordedFrame() const
  233148. {
  233149. QTCameraDeviceInteral* const d = static_cast <QTCameraDeviceInteral*> (internal);
  233150. if (d->callbackDelegate->firstPresentationTime != 0)
  233151. return Time (d->callbackDelegate->firstPresentationTime + d->callbackDelegate->averageTimeOffset);
  233152. return Time();
  233153. }
  233154. void CameraDevice::stopRecording()
  233155. {
  233156. if (isRecording)
  233157. {
  233158. static_cast <QTCameraDeviceInteral*> (internal)->resetFile();
  233159. isRecording = false;
  233160. }
  233161. }
  233162. void CameraDevice::addListener (CameraImageListener* listenerToAdd)
  233163. {
  233164. if (listenerToAdd != 0)
  233165. static_cast <QTCameraDeviceInteral*> (internal)->addListener (listenerToAdd);
  233166. }
  233167. void CameraDevice::removeListener (CameraImageListener* listenerToRemove)
  233168. {
  233169. if (listenerToRemove != 0)
  233170. static_cast <QTCameraDeviceInteral*> (internal)->removeListener (listenerToRemove);
  233171. }
  233172. const StringArray CameraDevice::getAvailableDevices()
  233173. {
  233174. const ScopedAutoReleasePool pool;
  233175. StringArray results;
  233176. NSArray* devs = [QTCaptureDevice inputDevicesWithMediaType: QTMediaTypeVideo];
  233177. for (int i = 0; i < (int) [devs count]; ++i)
  233178. {
  233179. QTCaptureDevice* dev = (QTCaptureDevice*) [devs objectAtIndex: i];
  233180. results.add (nsStringToJuce ([dev localizedDisplayName]));
  233181. }
  233182. return results;
  233183. }
  233184. CameraDevice* CameraDevice::openDevice (int index,
  233185. int minWidth, int minHeight,
  233186. int maxWidth, int maxHeight)
  233187. {
  233188. ScopedPointer <CameraDevice> d (new CameraDevice (getAvailableDevices() [index], index));
  233189. if (static_cast <QTCameraDeviceInteral*> (d->internal)->openingError.isEmpty())
  233190. return d.release();
  233191. return 0;
  233192. }
  233193. #endif
  233194. /*** End of inlined file: juce_mac_CameraDevice.mm ***/
  233195. #endif
  233196. #endif
  233197. END_JUCE_NAMESPACE
  233198. #endif
  233199. /*** End of inlined file: juce_mac_NativeCode.mm ***/
  233200. #endif
  233201. #endif